contract_server.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. import datetime
  2. import json
  3. import logging
  4. import os
  5. from typing import Any
  6. from sqlalchemy.ext.asyncio import AsyncSession
  7. from alien_contract.repositories.contract_repo import ContractRepository
  8. from alien_contract.schemas.request.contract import BundleCreateRequest
  9. from alien_contract.infrastructure.esign import main as esign_main
  10. from alien_contract.infrastructure.esign.contract_builder import build_contract_items, ContractBuildError
  11. from alien_contract.infrastructure.esign.main import sign_url, file_download_url
  12. LOG_DIR = os.path.join("common", "logs", "alien_contract")
  13. os.makedirs(LOG_DIR, exist_ok=True)
  14. def _init_logger():
  15. logger = logging.getLogger("alien_contract_service")
  16. if logger.handlers:
  17. return logger
  18. logger.setLevel(logging.INFO)
  19. fmt = logging.Formatter("%(asctime)s [%(levelname)s] %(name)s %(message)s")
  20. info_handler = logging.FileHandler(os.path.join(LOG_DIR, "info.log"), encoding="utf-8")
  21. info_handler.setLevel(logging.INFO)
  22. info_handler.setFormatter(fmt)
  23. error_handler = logging.FileHandler(os.path.join(LOG_DIR, "error.log"), encoding="utf-8")
  24. error_handler.setLevel(logging.ERROR)
  25. error_handler.setFormatter(fmt)
  26. logger.addHandler(info_handler)
  27. logger.addHandler(error_handler)
  28. return logger
  29. logger = _init_logger()
  30. # e签宝 v3 回调 action 说明:
  31. # SIGN_MISSON_COMPLETE 单个签署任务完成(按签署人维度,平台方自动盖章也会触发,signResult=2)
  32. # SIGN_FLOW_COMPLETE / SIGN_FLOW_FINISH 整个签署流程结束
  33. # 注意:绝不能用"单个任务完成"判定整份合同已签署,必须以流程真实状态 signFlowStatus 为准。
  34. SIGN_FLOW_FINISH_ACTIONS = {
  35. "SIGN_FLOW_FINISH",
  36. "SIGN_FLOW_COMPLETE",
  37. }
  38. # e签宝 流程状态 signFlowStatus: 0草稿 1签署中 2完成 3撤销 4终止 5过期 6删除 7拒签
  39. ESIGN_FLOW_STATUS_COMPLETED = 2
  40. # 与数据库 NOW() 时区(东八区)保持一致,避免应用容器在 UTC 时写入早 8 小时的时间
  41. CN_TZ = datetime.timezone(datetime.timedelta(hours=8))
  42. def _ms_to_naive_cn(ms) -> "datetime.datetime | None":
  43. """e签宝时间戳(epoch毫秒)转换为东八区(无时区)datetime"""
  44. if not ms:
  45. return None
  46. try:
  47. return datetime.datetime.fromtimestamp(ms / 1000, tz=CN_TZ).replace(tzinfo=None)
  48. except Exception:
  49. return None
  50. BUNDLE_CONFIGS = {
  51. "STORE_STANDARD": [
  52. ("store_agreement", "店铺入驻协议", 1),
  53. ("alipay_auth", "支付宝授权函", 0),
  54. ("wechat_pay_commitment", "微信支付承诺函", 0),
  55. ],
  56. "LAWYER_STANDARD": [
  57. ("lawyer_agreement", "律所入驻协议", 1),
  58. ("alipay_auth", "支付宝授权函", 0),
  59. ("wechat_pay_commitment", "微信支付承诺函", 0),
  60. ],
  61. }
  62. DEFAULT_BUNDLE_BY_SUBJECT = {
  63. "store": "STORE_STANDARD",
  64. "lawyer": "LAWYER_STANDARD",
  65. }
  66. def _extract_download_url(download_resp: str) -> tuple[str | None, Any]:
  67. try:
  68. download_json = json.loads(download_resp)
  69. except json.JSONDecodeError as exc:
  70. return None, {"error": f"e签宝返回非 JSON: {exc}", "resp": download_resp}
  71. data = download_json.get("data") if isinstance(download_json, dict) else None
  72. files = data.get("files") if isinstance(data, dict) else None
  73. if isinstance(files, list) and files:
  74. first_file = files[0]
  75. if isinstance(first_file, dict):
  76. download_url = first_file.get("downloadUrl")
  77. if download_url:
  78. return download_url, download_json
  79. return None, download_json
  80. class ContractCenterService:
  81. def __init__(self, db: AsyncSession):
  82. self.repo = ContractRepository(db)
  83. async def create_bundle(self, req: BundleCreateRequest) -> dict:
  84. bundle_type = DEFAULT_BUNDLE_BY_SUBJECT[req.subject_type]
  85. configs = BUNDLE_CONFIGS.get(bundle_type)
  86. if not configs:
  87. return {"success": False, "message": "不支持的合同包类型", "raw": {"bundle_type": bundle_type}}
  88. try:
  89. items = build_contract_items(
  90. configs=configs,
  91. template_name=req.subject_name,
  92. signer_name=req.subject_name,
  93. signer_id_num=req.ord_id,
  94. psn_account=req.contact_phone,
  95. psn_name=req.contact_name,
  96. )
  97. except ContractBuildError as exc:
  98. return {"success": False, "message": exc.message, "raw": exc.raw}
  99. bundle = await self.repo.create_bundle(
  100. {
  101. "subject_type": req.subject_type,
  102. "subject_id": req.subject_id,
  103. "subject_name": req.subject_name,
  104. "business_segment": req.business_segment,
  105. "contact_name": req.contact_name,
  106. "contact_phone": req.contact_phone,
  107. "ord_id": req.ord_id,
  108. "bundle_type": bundle_type,
  109. "status": "未签署",
  110. }
  111. )
  112. documents = await self.repo.create_documents(bundle.id, items)
  113. for document in documents:
  114. try:
  115. sign_resp = sign_url(document.sign_flow_id, req.contact_phone)
  116. sign_json = json.loads(sign_resp)
  117. sign_data = sign_json.get("data") if isinstance(sign_json, dict) else None
  118. result_sign_url = sign_data.get("url") if isinstance(sign_data, dict) else None
  119. except Exception:
  120. await self.repo.rollback()
  121. return {
  122. "success": False,
  123. "message": f"{document.contract_name}创建成功但签署链接获取失败",
  124. "raw": {"contract_type": document.contract_type, "sign_flow_id": document.sign_flow_id},
  125. }
  126. if not result_sign_url:
  127. await self.repo.rollback()
  128. return {
  129. "success": False,
  130. "message": f"{document.contract_name}创建成功但签署链接缺失",
  131. "raw": {"contract_type": document.contract_type, "sign_flow_id": document.sign_flow_id, "resp": sign_json},
  132. }
  133. await self.repo.update_document_urls(document.id, sign_url=result_sign_url)
  134. document.sign_url = result_sign_url
  135. primary_doc = next((doc for doc in documents if doc.is_primary == 1), documents[0])
  136. await self.repo.set_primary_document(bundle.id, primary_doc.id)
  137. await self.repo.commit()
  138. return {
  139. "success": True,
  140. "message": "合同包创建成功",
  141. "bundle_id": bundle.id,
  142. "primary_sign_flow_id": primary_doc.sign_flow_id,
  143. "created_contracts": [
  144. {
  145. "contract_type": d.contract_type,
  146. "contract_name": d.contract_name,
  147. "sign_flow_id": d.sign_flow_id,
  148. "file_id": d.file_id,
  149. "contract_url": d.template_url,
  150. "sign_url": d.sign_url,
  151. }
  152. for d in documents
  153. ],
  154. }
  155. async def list_bundles(self, subject_type: str, subject_id: int, page: int, page_size: int, *, doc_status: int | None = None) -> dict:
  156. bundles, total = await self.repo.list_bundles(subject_type, subject_id, page, page_size)
  157. ids = [b.id for b in bundles]
  158. docs_map = await self.repo.list_documents_by_bundle_ids(ids, doc_status=doc_status)
  159. items = []
  160. for b in bundles:
  161. docs = docs_map.get(b.id, [])
  162. items.append(
  163. {
  164. "id": b.id,
  165. "subject_type": b.subject_type,
  166. "subject_id": b.subject_id,
  167. "subject_name": b.subject_name,
  168. "business_segment": b.business_segment,
  169. "contact_name": b.contact_name,
  170. "contact_phone": b.contact_phone,
  171. "ord_id": b.ord_id,
  172. "bundle_type": b.bundle_type,
  173. "status": b.status,
  174. "primary_document_id": b.primary_document_id,
  175. "documents": [
  176. {
  177. "id": d.id,
  178. "contract_type": d.contract_type,
  179. "contract_name": d.contract_name,
  180. "is_primary": d.is_primary,
  181. "status": d.status,
  182. "sign_flow_id": d.sign_flow_id,
  183. "file_id": d.file_id,
  184. "template_url": d.template_url,
  185. "sign_url": d.sign_url,
  186. "download_url": d.download_url,
  187. "signing_time": d.signing_time,
  188. "effective_time": d.effective_time,
  189. "expiry_time": d.expiry_time,
  190. }
  191. for d in docs
  192. ],
  193. }
  194. )
  195. total_pages = (total + page_size - 1) // page_size if total > 0 else 0
  196. return {"items": items, "total": total, "page": page, "page_size": page_size, "total_pages": total_pages}
  197. async def get_document_detail(self, sign_flow_id: str) -> dict:
  198. document, bundle = await self.repo.get_document_and_bundle(sign_flow_id)
  199. if not document:
  200. return {"success": False, "message": "未找到合同"}
  201. if document.status == 0:
  202. return await self._get_pending_detail(document, bundle)
  203. return await self._get_signed_detail(document, bundle)
  204. async def _get_pending_detail(self, document, bundle):
  205. try:
  206. detail_resp = esign_main.get_contract_detail(document.file_id)
  207. detail_json = json.loads(detail_resp)
  208. data = detail_json.get("data") if isinstance(detail_json, dict) else None
  209. contract_url_val = data.get("fileDownloadUrl") if isinstance(data, dict) else None
  210. if not contract_url_val and isinstance(detail_json, dict):
  211. contract_url_val = detail_json.get("fileDownloadUrl")
  212. except Exception as exc:
  213. return {"success": False, "message": "获取合同链接失败", "raw": str(exc)}
  214. if not contract_url_val:
  215. return {"success": False, "message": "e签宝返回缺少合同链接", "raw": detail_resp}
  216. await self.repo.update_document_urls(document.id, template_url=contract_url_val)
  217. try:
  218. sign_resp = sign_url(document.sign_flow_id, bundle.contact_phone)
  219. sign_json = json.loads(sign_resp)
  220. sign_data = sign_json.get("data") if isinstance(sign_json, dict) else None
  221. result_sign_url = sign_data.get("url") if isinstance(sign_data, dict) else None
  222. except Exception as exc:
  223. return {"success": False, "message": "获取签署链接失败", "raw": str(exc)}
  224. if not result_sign_url:
  225. return {"success": False, "message": "e签宝返回缺少签署链接", "raw": sign_json}
  226. await self.repo.update_document_urls(document.id, sign_url=result_sign_url)
  227. await self.repo.commit()
  228. return {
  229. "status": 0,
  230. "contract_url": contract_url_val,
  231. "sign_url": result_sign_url,
  232. "sign_flow_id": document.sign_flow_id,
  233. }
  234. async def _get_signed_detail(self, document, _bundle):
  235. try:
  236. download_resp = file_download_url(document.sign_flow_id)
  237. except Exception as exc:
  238. cached_url = document.download_url or None
  239. if cached_url:
  240. return {
  241. "status": 1,
  242. "contract_url": cached_url,
  243. "contract_download_url": cached_url,
  244. "sign_flow_id": document.sign_flow_id,
  245. }
  246. return {"success": False, "message": "获取合同下载链接失败", "raw": str(exc)}
  247. contract_download_url, raw = _extract_download_url(download_resp)
  248. if not contract_download_url:
  249. cached_url = document.download_url or None
  250. if cached_url:
  251. return {
  252. "status": 1,
  253. "contract_url": cached_url,
  254. "contract_download_url": cached_url,
  255. "sign_flow_id": document.sign_flow_id,
  256. }
  257. logger.error(
  258. "file_download_url missing downloadUrl sign_flow_id=%s resp=%s",
  259. document.sign_flow_id,
  260. download_resp,
  261. )
  262. return {"success": False, "message": "合同已签署,下载文件生成中,请稍后重试", "raw": raw}
  263. await self.repo.update_document_urls(document.id, template_url=contract_download_url, download_url=contract_download_url)
  264. await self.repo.commit()
  265. return {
  266. "status": 1,
  267. "contract_url": contract_download_url,
  268. "contract_download_url": contract_download_url,
  269. "sign_flow_id": document.sign_flow_id,
  270. }
  271. async def process_esign_callback(self, payload: dict) -> dict:
  272. sign_result = payload.get("signResult")
  273. sign_flow_id = payload.get("signFlowId")
  274. action = payload.get("action")
  275. operator_mobile = (
  276. payload.get("operator", {})
  277. .get("psnAccount", {})
  278. .get("accountMobile")
  279. )
  280. if not sign_flow_id:
  281. logger.info(
  282. "esign_callback_event %s",
  283. json.dumps(
  284. {
  285. "result": "ignored",
  286. "reason": "missing_signFlowId",
  287. "action": action,
  288. "sign_result": sign_result,
  289. "operator_mobile": operator_mobile,
  290. },
  291. ensure_ascii=False,
  292. ),
  293. )
  294. return {"success": True, "code": "200", "msg": "ignored_missing_signFlowId"}
  295. document, bundle = await self.repo.get_document_and_bundle(sign_flow_id)
  296. if not document:
  297. logger.info(
  298. "esign_callback_event %s",
  299. json.dumps(
  300. {
  301. "result": "ignored",
  302. "reason": "unknown_signFlowId",
  303. "sign_flow_id": sign_flow_id,
  304. "action": action,
  305. "sign_result": sign_result,
  306. "operator_mobile": operator_mobile,
  307. },
  308. ensure_ascii=False,
  309. ),
  310. )
  311. return {"success": True, "code": "200", "msg": "ignored_unknown_signFlowId"}
  312. event_type = f"esign_callback:{action or 'UNKNOWN'}"
  313. await self.repo.create_event(bundle.id, document.id, sign_flow_id, event_type[:50], payload)
  314. # 不能凭"单个签署任务完成(SIGN_MISSON_COMPLETE / signResult=2)"判定整份合同已签署,
  315. # 因为平台方自动盖章也会触发该回调。以 e签宝 流程真实状态 signFlowStatus 为准。
  316. flow_status, finish_ms = self._query_flow_status(sign_flow_id)
  317. # 兜底:查询失败时,仅当为"流程结束"类回调且报文明确为已完成(2)才认定完成
  318. if flow_status is None and action in SIGN_FLOW_FINISH_ACTIONS:
  319. payload_status = payload.get("signFlowStatus") or payload.get("flowStatus")
  320. if payload_status in (2, "2"):
  321. flow_status = ESIGN_FLOW_STATUS_COMPLETED
  322. mark_signed = flow_status == ESIGN_FLOW_STATUS_COMPLETED
  323. logger.info(
  324. "esign_callback_event %s",
  325. json.dumps(
  326. {
  327. "result": "mark_signed" if mark_signed else "ignored",
  328. "sign_flow_id": sign_flow_id,
  329. "bundle_id": bundle.id,
  330. "document_id": document.id,
  331. "contract_type": document.contract_type,
  332. "action": action,
  333. "sign_result": sign_result,
  334. "flow_status": flow_status,
  335. "operator_mobile": operator_mobile,
  336. },
  337. ensure_ascii=False,
  338. ),
  339. )
  340. if mark_signed:
  341. ts_ms = finish_ms or payload.get("operateTime") or payload.get("timestamp")
  342. signing_dt = _ms_to_naive_cn(ts_ms)
  343. effective_dt = expiry_dt = None
  344. if signing_dt:
  345. effective_dt = (signing_dt + datetime.timedelta(days=1)).replace(hour=0, minute=0, second=0, microsecond=0)
  346. expiry_dt = effective_dt + datetime.timedelta(days=365)
  347. contract_download_url = None
  348. try:
  349. download_resp = file_download_url(sign_flow_id)
  350. contract_download_url, raw_download_resp = _extract_download_url(download_resp)
  351. except Exception as exc:
  352. raw_download_resp = str(exc)
  353. if not contract_download_url:
  354. logger.error(
  355. "file_download_url missing downloadUrl on callback sign_flow_id=%s resp=%s",
  356. sign_flow_id,
  357. raw_download_resp,
  358. )
  359. await self.repo.mark_document_signed(document.id, signing_dt, effective_dt, expiry_dt, contract_download_url)
  360. await self.repo.recalc_bundle_status(bundle.id)
  361. await self.repo.commit()
  362. return {"success": True, "code": "200", "msg": "success"}
  363. await self.repo.commit()
  364. return {"success": True, "code": "200", "msg": f"ignored_flow_status_{flow_status}"}
  365. def _query_flow_status(self, sign_flow_id: str) -> tuple[int | None, int | None]:
  366. """查询 e签宝 流程真实状态,返回 (signFlowStatus, signFlowFinishTime毫秒);失败返回 (None, None)"""
  367. try:
  368. detail_resp = esign_main.query_sign_flow_detail(sign_flow_id)
  369. detail_json = json.loads(detail_resp)
  370. except Exception as exc:
  371. logger.error("query_sign_flow_detail error sign_flow_id=%s err=%s", sign_flow_id, exc)
  372. return None, None
  373. data = detail_json.get("data") if isinstance(detail_json, dict) else None
  374. if not isinstance(data, dict):
  375. logger.error("query_sign_flow_detail no data sign_flow_id=%s resp=%s", sign_flow_id, detail_json)
  376. return None, None
  377. return data.get("signFlowStatus"), data.get("signFlowFinishTime")