contract_server.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  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. SIGN_FLOW_FINISH_ACTIONS = {
  31. "SIGN_FLOW_FINISH",
  32. "SIGN_FLOW_COMPLETE",
  33. }
  34. NON_FINAL_SIGN_ACTIONS = {
  35. "OPERATOR_COMPLETE_SIGN",
  36. "OPERATOR_READ",
  37. "OPERATOR_VIEW",
  38. }
  39. BUNDLE_CONFIGS = {
  40. "STORE_STANDARD": [
  41. ("store_agreement", "店铺入驻协议", 1),
  42. ("alipay_auth", "支付宝授权函", 0),
  43. ("wechat_pay_commitment", "微信支付承诺函", 0),
  44. ],
  45. "LAWYER_STANDARD": [
  46. ("lawyer_agreement", "律所入驻协议", 1),
  47. ("alipay_auth", "支付宝授权函", 0),
  48. ("wechat_pay_commitment", "微信支付承诺函", 0),
  49. ],
  50. }
  51. DEFAULT_BUNDLE_BY_SUBJECT = {
  52. "store": "STORE_STANDARD",
  53. "lawyer": "LAWYER_STANDARD",
  54. }
  55. def _extract_download_url(download_resp: str) -> tuple[str | None, Any]:
  56. try:
  57. download_json = json.loads(download_resp)
  58. except json.JSONDecodeError as exc:
  59. return None, {"error": f"e签宝返回非 JSON: {exc}", "resp": download_resp}
  60. data = download_json.get("data") if isinstance(download_json, dict) else None
  61. files = data.get("files") if isinstance(data, dict) else None
  62. if isinstance(files, list) and files:
  63. first_file = files[0]
  64. if isinstance(first_file, dict):
  65. download_url = first_file.get("downloadUrl")
  66. if download_url:
  67. return download_url, download_json
  68. return None, download_json
  69. class ContractCenterService:
  70. def __init__(self, db: AsyncSession):
  71. self.repo = ContractRepository(db)
  72. async def create_bundle(self, req: BundleCreateRequest) -> dict:
  73. bundle_type = DEFAULT_BUNDLE_BY_SUBJECT[req.subject_type]
  74. configs = BUNDLE_CONFIGS.get(bundle_type)
  75. if not configs:
  76. return {"success": False, "message": "不支持的合同包类型", "raw": {"bundle_type": bundle_type}}
  77. try:
  78. items = build_contract_items(
  79. configs=configs,
  80. template_name=req.subject_name,
  81. signer_name=req.subject_name,
  82. signer_id_num=req.ord_id,
  83. psn_account=req.contact_phone,
  84. psn_name=req.contact_name,
  85. )
  86. except ContractBuildError as exc:
  87. return {"success": False, "message": exc.message, "raw": exc.raw}
  88. bundle = await self.repo.create_bundle(
  89. {
  90. "subject_type": req.subject_type,
  91. "subject_id": req.subject_id,
  92. "subject_name": req.subject_name,
  93. "business_segment": req.business_segment,
  94. "contact_name": req.contact_name,
  95. "contact_phone": req.contact_phone,
  96. "ord_id": req.ord_id,
  97. "bundle_type": bundle_type,
  98. "status": "未签署",
  99. }
  100. )
  101. documents = await self.repo.create_documents(bundle.id, items)
  102. for document in documents:
  103. try:
  104. sign_resp = sign_url(document.sign_flow_id, req.contact_phone)
  105. sign_json = json.loads(sign_resp)
  106. sign_data = sign_json.get("data") if isinstance(sign_json, dict) else None
  107. result_sign_url = sign_data.get("url") if isinstance(sign_data, dict) else None
  108. except Exception:
  109. await self.repo.rollback()
  110. return {
  111. "success": False,
  112. "message": f"{document.contract_name}创建成功但签署链接获取失败",
  113. "raw": {"contract_type": document.contract_type, "sign_flow_id": document.sign_flow_id},
  114. }
  115. if not result_sign_url:
  116. await self.repo.rollback()
  117. return {
  118. "success": False,
  119. "message": f"{document.contract_name}创建成功但签署链接缺失",
  120. "raw": {"contract_type": document.contract_type, "sign_flow_id": document.sign_flow_id, "resp": sign_json},
  121. }
  122. await self.repo.update_document_urls(document.id, sign_url=result_sign_url)
  123. document.sign_url = result_sign_url
  124. primary_doc = next((doc for doc in documents if doc.is_primary == 1), documents[0])
  125. await self.repo.set_primary_document(bundle.id, primary_doc.id)
  126. await self.repo.commit()
  127. return {
  128. "success": True,
  129. "message": "合同包创建成功",
  130. "bundle_id": bundle.id,
  131. "primary_sign_flow_id": primary_doc.sign_flow_id,
  132. "created_contracts": [
  133. {
  134. "contract_type": d.contract_type,
  135. "contract_name": d.contract_name,
  136. "sign_flow_id": d.sign_flow_id,
  137. "file_id": d.file_id,
  138. "contract_url": d.template_url,
  139. "sign_url": d.sign_url,
  140. }
  141. for d in documents
  142. ],
  143. }
  144. async def list_bundles(self, subject_type: str, subject_id: int, page: int, page_size: int, *, doc_status: int | None = None) -> dict:
  145. bundles, total = await self.repo.list_bundles(subject_type, subject_id, page, page_size)
  146. ids = [b.id for b in bundles]
  147. docs_map = await self.repo.list_documents_by_bundle_ids(ids, doc_status=doc_status)
  148. items = []
  149. for b in bundles:
  150. docs = docs_map.get(b.id, [])
  151. items.append(
  152. {
  153. "id": b.id,
  154. "subject_type": b.subject_type,
  155. "subject_id": b.subject_id,
  156. "subject_name": b.subject_name,
  157. "business_segment": b.business_segment,
  158. "contact_name": b.contact_name,
  159. "contact_phone": b.contact_phone,
  160. "ord_id": b.ord_id,
  161. "bundle_type": b.bundle_type,
  162. "status": b.status,
  163. "primary_document_id": b.primary_document_id,
  164. "documents": [
  165. {
  166. "id": d.id,
  167. "contract_type": d.contract_type,
  168. "contract_name": d.contract_name,
  169. "is_primary": d.is_primary,
  170. "status": d.status,
  171. "sign_flow_id": d.sign_flow_id,
  172. "file_id": d.file_id,
  173. "template_url": d.template_url,
  174. "sign_url": d.sign_url,
  175. "download_url": d.download_url,
  176. "signing_time": d.signing_time,
  177. "effective_time": d.effective_time,
  178. "expiry_time": d.expiry_time,
  179. }
  180. for d in docs
  181. ],
  182. }
  183. )
  184. total_pages = (total + page_size - 1) // page_size if total > 0 else 0
  185. return {"items": items, "total": total, "page": page, "page_size": page_size, "total_pages": total_pages}
  186. async def get_document_detail(self, sign_flow_id: str) -> dict:
  187. document, bundle = await self.repo.get_document_and_bundle(sign_flow_id)
  188. if not document:
  189. return {"success": False, "message": "未找到合同"}
  190. if document.status == 0:
  191. return await self._get_pending_detail(document, bundle)
  192. return await self._get_signed_detail(document, bundle)
  193. async def _get_pending_detail(self, document, bundle):
  194. try:
  195. detail_resp = esign_main.get_contract_detail(document.file_id)
  196. detail_json = json.loads(detail_resp)
  197. data = detail_json.get("data") if isinstance(detail_json, dict) else None
  198. contract_url_val = data.get("fileDownloadUrl") if isinstance(data, dict) else None
  199. if not contract_url_val and isinstance(detail_json, dict):
  200. contract_url_val = detail_json.get("fileDownloadUrl")
  201. except Exception as exc:
  202. return {"success": False, "message": "获取合同链接失败", "raw": str(exc)}
  203. if not contract_url_val:
  204. return {"success": False, "message": "e签宝返回缺少合同链接", "raw": detail_resp}
  205. await self.repo.update_document_urls(document.id, template_url=contract_url_val)
  206. try:
  207. sign_resp = sign_url(document.sign_flow_id, bundle.contact_phone)
  208. sign_json = json.loads(sign_resp)
  209. sign_data = sign_json.get("data") if isinstance(sign_json, dict) else None
  210. result_sign_url = sign_data.get("url") if isinstance(sign_data, dict) else None
  211. except Exception as exc:
  212. return {"success": False, "message": "获取签署链接失败", "raw": str(exc)}
  213. if not result_sign_url:
  214. return {"success": False, "message": "e签宝返回缺少签署链接", "raw": sign_json}
  215. await self.repo.update_document_urls(document.id, sign_url=result_sign_url)
  216. await self.repo.commit()
  217. return {
  218. "status": 0,
  219. "contract_url": contract_url_val,
  220. "sign_url": result_sign_url,
  221. "sign_flow_id": document.sign_flow_id,
  222. }
  223. async def _get_signed_detail(self, document, _bundle):
  224. try:
  225. download_resp = file_download_url(document.sign_flow_id)
  226. except Exception as exc:
  227. cached_url = document.download_url or None
  228. if cached_url:
  229. return {
  230. "status": 1,
  231. "contract_url": cached_url,
  232. "contract_download_url": cached_url,
  233. "sign_flow_id": document.sign_flow_id,
  234. }
  235. return {"success": False, "message": "获取合同下载链接失败", "raw": str(exc)}
  236. contract_download_url, raw = _extract_download_url(download_resp)
  237. if not contract_download_url:
  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. logger.error(
  247. "file_download_url missing downloadUrl sign_flow_id=%s resp=%s",
  248. document.sign_flow_id,
  249. download_resp,
  250. )
  251. return {"success": False, "message": "合同已签署,下载文件生成中,请稍后重试", "raw": raw}
  252. await self.repo.update_document_urls(document.id, template_url=contract_download_url, download_url=contract_download_url)
  253. await self.repo.commit()
  254. return {
  255. "status": 1,
  256. "contract_url": contract_download_url,
  257. "contract_download_url": contract_download_url,
  258. "sign_flow_id": document.sign_flow_id,
  259. }
  260. async def process_esign_callback(self, payload: dict) -> dict:
  261. sign_result = payload.get("signResult")
  262. sign_flow_id = payload.get("signFlowId")
  263. action = payload.get("action")
  264. operator_mobile = (
  265. payload.get("operator", {})
  266. .get("psnAccount", {})
  267. .get("accountMobile")
  268. )
  269. if not sign_flow_id:
  270. logger.info(
  271. "esign_callback_event %s",
  272. json.dumps(
  273. {
  274. "result": "ignored",
  275. "reason": "missing_signFlowId",
  276. "action": action,
  277. "sign_result": sign_result,
  278. "operator_mobile": operator_mobile,
  279. },
  280. ensure_ascii=False,
  281. ),
  282. )
  283. return {"success": True, "code": "200", "msg": "ignored_missing_signFlowId"}
  284. document, bundle = await self.repo.get_document_and_bundle(sign_flow_id)
  285. if not document:
  286. logger.info(
  287. "esign_callback_event %s",
  288. json.dumps(
  289. {
  290. "result": "ignored",
  291. "reason": "unknown_signFlowId",
  292. "sign_flow_id": sign_flow_id,
  293. "action": action,
  294. "sign_result": sign_result,
  295. "operator_mobile": operator_mobile,
  296. },
  297. ensure_ascii=False,
  298. ),
  299. )
  300. return {"success": True, "code": "200", "msg": "ignored_unknown_signFlowId"}
  301. event_type = f"esign_callback:{action or 'UNKNOWN'}"
  302. await self.repo.create_event(bundle.id, document.id, sign_flow_id, event_type[:50], payload)
  303. mark_signed = bool(action in SIGN_FLOW_FINISH_ACTIONS or (sign_result == 2 and action not in NON_FINAL_SIGN_ACTIONS))
  304. logger.info(
  305. "esign_callback_event %s",
  306. json.dumps(
  307. {
  308. "result": "mark_signed" if mark_signed else "ignored",
  309. "sign_flow_id": sign_flow_id,
  310. "bundle_id": bundle.id,
  311. "document_id": document.id,
  312. "contract_type": document.contract_type,
  313. "action": action,
  314. "sign_result": sign_result,
  315. "operator_mobile": operator_mobile,
  316. },
  317. ensure_ascii=False,
  318. ),
  319. )
  320. if mark_signed:
  321. ts_ms = payload.get("operateTime") or payload.get("timestamp")
  322. signing_dt = None
  323. if ts_ms:
  324. try:
  325. signing_dt = datetime.datetime.fromtimestamp(ts_ms / 1000)
  326. except Exception:
  327. signing_dt = None
  328. effective_dt = expiry_dt = None
  329. if signing_dt:
  330. effective_dt = (signing_dt + datetime.timedelta(days=1)).replace(hour=0, minute=0, second=0, microsecond=0)
  331. expiry_dt = effective_dt + datetime.timedelta(days=365)
  332. contract_download_url = None
  333. try:
  334. download_resp = file_download_url(sign_flow_id)
  335. contract_download_url, raw_download_resp = _extract_download_url(download_resp)
  336. except Exception as exc:
  337. raw_download_resp = str(exc)
  338. if not contract_download_url:
  339. logger.error(
  340. "file_download_url missing downloadUrl on callback sign_flow_id=%s resp=%s",
  341. sign_flow_id,
  342. raw_download_resp,
  343. )
  344. await self.repo.mark_document_signed(document.id, signing_dt, effective_dt, expiry_dt, contract_download_url)
  345. await self.repo.recalc_bundle_status(bundle.id)
  346. await self.repo.commit()
  347. return {"success": True, "code": "200", "msg": "success"}
  348. await self.repo.commit()
  349. if action:
  350. return {"success": True, "code": "200", "msg": f"ignored_action_{action}"}
  351. return {"success": True, "code": "200", "msg": f"ignored_signResult_{sign_result}"}