contract_server.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. import datetime
  2. import json
  3. import logging
  4. import os
  5. from sqlalchemy.ext.asyncio import AsyncSession
  6. from alien_contract.repositories.contract_repo import ContractRepository
  7. from alien_contract.schemas.request.contract import BundleCreateRequest
  8. from alien_contract.infrastructure.esign import main as esign_main
  9. from alien_contract.infrastructure.esign.contract_builder import build_contract_items, ContractBuildError
  10. from alien_contract.infrastructure.esign.main import sign_url, file_download_url
  11. LOG_DIR = os.path.join("common", "logs", "alien_contract")
  12. os.makedirs(LOG_DIR, exist_ok=True)
  13. def _init_logger():
  14. logger = logging.getLogger("alien_contract_service")
  15. if logger.handlers:
  16. return logger
  17. logger.setLevel(logging.INFO)
  18. fmt = logging.Formatter("%(asctime)s [%(levelname)s] %(name)s %(message)s")
  19. info_handler = logging.FileHandler(os.path.join(LOG_DIR, "info.log"), encoding="utf-8")
  20. info_handler.setLevel(logging.INFO)
  21. info_handler.setFormatter(fmt)
  22. error_handler = logging.FileHandler(os.path.join(LOG_DIR, "error.log"), encoding="utf-8")
  23. error_handler.setLevel(logging.ERROR)
  24. error_handler.setFormatter(fmt)
  25. logger.addHandler(info_handler)
  26. logger.addHandler(error_handler)
  27. return logger
  28. logger = _init_logger()
  29. BUNDLE_CONFIGS = {
  30. "STORE_STANDARD": [
  31. ("store_agreement", "店铺入驻协议", 1),
  32. ("alipay_auth", "支付宝授权函", 0),
  33. ("wechat_pay_commitment", "微信支付承诺函", 0),
  34. ],
  35. "LAWYER_STANDARD": [
  36. ("lawyer_agreement", "律所入驻协议", 1),
  37. ("alipay_auth", "支付宝授权函", 0),
  38. ("wechat_pay_commitment", "微信支付承诺函", 0),
  39. ],
  40. }
  41. DEFAULT_BUNDLE_BY_SUBJECT = {
  42. "store": "STORE_STANDARD",
  43. "lawyer": "LAWYER_STANDARD",
  44. }
  45. class ContractCenterService:
  46. def __init__(self, db: AsyncSession):
  47. self.repo = ContractRepository(db)
  48. async def create_bundle(self, req: BundleCreateRequest) -> dict:
  49. bundle_type = req.bundle_type or DEFAULT_BUNDLE_BY_SUBJECT[req.subject_type]
  50. configs = BUNDLE_CONFIGS.get(bundle_type)
  51. if not configs:
  52. return {"success": False, "message": "不支持的合同包类型", "raw": {"bundle_type": bundle_type}}
  53. try:
  54. items = build_contract_items(
  55. configs=configs,
  56. template_name=req.subject_name,
  57. signer_name=req.subject_name,
  58. signer_id_num=req.ord_id,
  59. psn_account=req.contact_phone,
  60. psn_name=req.contact_name,
  61. )
  62. except ContractBuildError as exc:
  63. return {"success": False, "message": exc.message, "raw": exc.raw}
  64. bundle = await self.repo.create_bundle(
  65. {
  66. "subject_type": req.subject_type,
  67. "subject_id": req.subject_id,
  68. "subject_name": req.subject_name,
  69. "business_segment": req.business_segment,
  70. "contact_name": req.contact_name,
  71. "contact_phone": req.contact_phone,
  72. "ord_id": req.ord_id,
  73. "bundle_type": bundle_type,
  74. "status": "pending",
  75. }
  76. )
  77. documents = await self.repo.create_documents(bundle.id, items)
  78. primary_doc = next((doc for doc in documents if doc.is_primary == 1), documents[0])
  79. await self.repo.set_primary_document(bundle.id, primary_doc.id)
  80. await self.repo.commit()
  81. return {
  82. "success": True,
  83. "message": "合同包创建成功",
  84. "bundle_id": bundle.id,
  85. "primary_sign_flow_id": primary_doc.sign_flow_id,
  86. "created_contracts": [
  87. {
  88. "contract_type": d.contract_type,
  89. "contract_name": d.contract_name,
  90. "sign_flow_id": d.sign_flow_id,
  91. "file_id": d.file_id,
  92. "contract_url": d.template_url,
  93. }
  94. for d in documents
  95. ],
  96. }
  97. async def list_bundles(self, subject_type: str, subject_id: int, page: int, page_size: int) -> dict:
  98. bundles, total = await self.repo.list_bundles(subject_type, subject_id, page, page_size)
  99. ids = [b.id for b in bundles]
  100. docs_map = await self.repo.list_documents_by_bundle_ids(ids)
  101. items = []
  102. for b in bundles:
  103. docs = docs_map.get(b.id, [])
  104. items.append(
  105. {
  106. "id": b.id,
  107. "subject_type": b.subject_type,
  108. "subject_id": b.subject_id,
  109. "subject_name": b.subject_name,
  110. "business_segment": b.business_segment,
  111. "contact_name": b.contact_name,
  112. "contact_phone": b.contact_phone,
  113. "ord_id": b.ord_id,
  114. "bundle_type": b.bundle_type,
  115. "status": b.status,
  116. "primary_document_id": b.primary_document_id,
  117. "documents": [
  118. {
  119. "id": d.id,
  120. "contract_type": d.contract_type,
  121. "contract_name": d.contract_name,
  122. "is_primary": d.is_primary,
  123. "status": d.status,
  124. "sign_flow_id": d.sign_flow_id,
  125. "file_id": d.file_id,
  126. "template_url": d.template_url,
  127. "sign_url": d.sign_url,
  128. "download_url": d.download_url,
  129. "signing_time": d.signing_time,
  130. "effective_time": d.effective_time,
  131. "expiry_time": d.expiry_time,
  132. }
  133. for d in docs
  134. ],
  135. }
  136. )
  137. total_pages = (total + page_size - 1) // page_size if total > 0 else 0
  138. return {"items": items, "total": total, "page": page, "page_size": page_size, "total_pages": total_pages}
  139. async def get_document_detail(self, sign_flow_id: str) -> dict:
  140. document, bundle = await self.repo.get_document_and_bundle(sign_flow_id)
  141. if not document:
  142. return {"success": False, "message": "未找到合同"}
  143. if document.status == 0:
  144. return await self._get_pending_detail(document, bundle)
  145. return await self._get_signed_detail(document, bundle)
  146. async def _get_pending_detail(self, document, bundle):
  147. try:
  148. detail_resp = esign_main.get_contract_detail(document.file_id)
  149. detail_json = json.loads(detail_resp)
  150. data = detail_json.get("data") if isinstance(detail_json, dict) else None
  151. contract_url_val = data.get("fileDownloadUrl") if isinstance(data, dict) else None
  152. if not contract_url_val and isinstance(detail_json, dict):
  153. contract_url_val = detail_json.get("fileDownloadUrl")
  154. except Exception as exc:
  155. return {"success": False, "message": "获取合同链接失败", "raw": str(exc)}
  156. if not contract_url_val:
  157. return {"success": False, "message": "e签宝返回缺少合同链接", "raw": detail_resp}
  158. await self.repo.update_document_urls(document.id, template_url=contract_url_val)
  159. try:
  160. sign_resp = sign_url(document.sign_flow_id, bundle.contact_phone)
  161. sign_json = json.loads(sign_resp)
  162. sign_data = sign_json.get("data") if isinstance(sign_json, dict) else None
  163. result_sign_url = sign_data.get("url") if isinstance(sign_data, dict) else None
  164. except Exception as exc:
  165. return {"success": False, "message": "获取签署链接失败", "raw": str(exc)}
  166. if not result_sign_url:
  167. return {"success": False, "message": "e签宝返回缺少签署链接", "raw": sign_json}
  168. await self.repo.update_document_urls(document.id, sign_url=result_sign_url)
  169. await self.repo.commit()
  170. return {
  171. "status": 0,
  172. "contract_url": contract_url_val,
  173. "sign_url": result_sign_url,
  174. "sign_flow_id": document.sign_flow_id,
  175. }
  176. async def _get_signed_detail(self, document, _bundle):
  177. try:
  178. download_resp = file_download_url(document.sign_flow_id)
  179. download_json = json.loads(download_resp)
  180. contract_download_url = download_json["data"]["files"][0]["downloadUrl"]
  181. except Exception as exc:
  182. return {"success": False, "message": "获取合同下载链接失败", "raw": str(exc)}
  183. await self.repo.update_document_urls(document.id, template_url=contract_download_url, download_url=contract_download_url)
  184. await self.repo.commit()
  185. return {
  186. "status": 1,
  187. "contract_url": contract_download_url,
  188. "contract_download_url": contract_download_url,
  189. "sign_flow_id": document.sign_flow_id,
  190. }
  191. async def process_esign_callback(self, payload: dict) -> dict:
  192. sign_result = payload.get("signResult")
  193. sign_flow_id = payload.get("signFlowId")
  194. if not sign_flow_id:
  195. return {"success": True, "code": "200", "msg": "ignored_missing_signFlowId"}
  196. document, bundle = await self.repo.get_document_and_bundle(sign_flow_id)
  197. if not document:
  198. return {"success": True, "code": "200", "msg": "ignored_unknown_signFlowId"}
  199. await self.repo.create_event(bundle.id, document.id, sign_flow_id, "esign_callback", payload)
  200. if sign_result == 2:
  201. ts_ms = payload.get("operateTime") or payload.get("timestamp")
  202. signing_dt = None
  203. if ts_ms:
  204. try:
  205. signing_dt = datetime.datetime.fromtimestamp(ts_ms / 1000)
  206. except Exception:
  207. signing_dt = None
  208. effective_dt = expiry_dt = None
  209. if signing_dt:
  210. effective_dt = (signing_dt + datetime.timedelta(days=1)).replace(hour=0, minute=0, second=0, microsecond=0)
  211. expiry_dt = effective_dt + datetime.timedelta(days=365)
  212. contract_download_url = None
  213. try:
  214. download_resp = file_download_url(sign_flow_id)
  215. download_json = json.loads(download_resp)
  216. contract_download_url = download_json["data"]["files"][0]["downloadUrl"]
  217. except Exception:
  218. contract_download_url = None
  219. await self.repo.mark_document_signed(document.id, signing_dt, effective_dt, expiry_dt, contract_download_url)
  220. await self.repo.recalc_bundle_status(bundle.id)
  221. await self.repo.commit()
  222. return {"success": True, "code": "200", "msg": "success"}
  223. await self.repo.commit()
  224. return {"success": True, "code": "200", "msg": f"ignored_signResult_{sign_result}"}