contract_server.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. import datetime
  2. import json
  3. import logging
  4. import os
  5. from typing import Optional, Any
  6. from sqlalchemy.ext.asyncio import AsyncSession
  7. from alien_lawyer.repositories.contract_repo import LawyerContractRepository
  8. from alien_lawyer.schemas.request.contract_lawyer import LawyerTemplatesCreate
  9. from common.esigntool import main as esign_main
  10. from common.esigntool.contract_builder import build_contract_items, ContractBuildError
  11. from common.esigntool.main import sign_url, file_download_url
  12. LOG_DIR = os.path.join("common", "logs", "alien_lawyer")
  13. os.makedirs(LOG_DIR, exist_ok=True)
  14. def _init_logger():
  15. logger = logging.getLogger("alien_lawyer_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. LAWYER_CONTRACT_CREATE_CONFIGS = [
  31. ("lawyer_agreement", "律所入驻协议", 1),
  32. ]
  33. class LawyerContractServer:
  34. def __init__(self, db: AsyncSession):
  35. self.db = db
  36. self.repo = LawyerContractRepository(db)
  37. async def create_esign_templates(self, templates_data: LawyerTemplatesCreate) -> dict:
  38. logger.info("create lawyer esign templates request: %s", templates_data)
  39. try:
  40. generated_contracts = build_contract_items(
  41. configs=LAWYER_CONTRACT_CREATE_CONFIGS,
  42. template_name=templates_data.law_firm_name,
  43. signer_name=templates_data.law_firm_name,
  44. signer_id_num=templates_data.ord_id,
  45. psn_account=templates_data.contact_phone,
  46. psn_name=templates_data.contact_name,
  47. )
  48. except ContractBuildError as exc:
  49. return {"success": False, "message": exc.message, "raw": exc.raw}
  50. for contract_item in generated_contracts:
  51. await self.repo.append_contract_url(templates_data, contract_item)
  52. master_contract = next((item for item in generated_contracts if item.get("is_master") == 1), generated_contracts[0])
  53. return {
  54. "success": True,
  55. "message": "律所合同模板已追加/创建",
  56. "sign_flow_id": master_contract.get("sign_flow_id"),
  57. "file_id": master_contract.get("file_id"),
  58. "contract_url": master_contract.get("contract_url"),
  59. "created_contracts": [
  60. {
  61. "contract_type": item["contract_type"],
  62. "contract_name": item["contract_name"],
  63. "sign_flow_id": item["sign_flow_id"],
  64. "file_id": item["file_id"],
  65. "contract_url": item["contract_url"],
  66. }
  67. for item in generated_contracts
  68. ],
  69. }
  70. async def list_contracts(self, lawyer_id: int, status: Optional[int], page: int, page_size: int) -> dict:
  71. rows = await self.repo.get_by_lawyer_id(lawyer_id)
  72. all_filtered_items: list[dict[str, Any]] = []
  73. for row in rows:
  74. contract_url_raw = row.get("contract_url")
  75. if not contract_url_raw:
  76. continue
  77. try:
  78. items = json.loads(contract_url_raw)
  79. if not isinstance(items, list):
  80. continue
  81. for item in items:
  82. if status is not None and item.get("status") != status:
  83. continue
  84. item_with_info = dict(item)
  85. item_with_info.update(
  86. {
  87. "id": row.get("id"),
  88. "lawyer_id": row.get("lawyer_id"),
  89. "law_firm_name": row.get("law_firm_name"),
  90. "contact_name": row.get("contact_name"),
  91. "contact_phone": row.get("contact_phone"),
  92. }
  93. )
  94. all_filtered_items.append(item_with_info)
  95. except Exception:
  96. continue
  97. total = len(all_filtered_items)
  98. start = (page - 1) * page_size
  99. end = start + page_size
  100. paged_items = all_filtered_items[start:end]
  101. total_pages = (total + page_size - 1) // page_size if total > 0 else 0
  102. return {
  103. "items": paged_items,
  104. "total": total,
  105. "page": page,
  106. "page_size": page_size,
  107. "total_pages": total_pages,
  108. }
  109. async def get_contract_detail(self, sign_flow_id: str) -> dict:
  110. row, item, items = await self.repo.get_contract_item_by_sign_flow_id(sign_flow_id)
  111. if not item:
  112. return {"success": False, "message": "未找到合同"}
  113. status = item.get("status")
  114. if status == 0:
  115. return await self._get_pending_contract_detail(sign_flow_id, row, item, items)
  116. if status == 1:
  117. return await self._get_signed_contract_detail(sign_flow_id, row, item, items)
  118. return {"success": False, "message": "未知合同状态", "raw": {"status": status}}
  119. async def _get_pending_contract_detail(self, sign_flow_id: str, row, item, items) -> dict:
  120. file_id = item.get("file_id")
  121. if not file_id:
  122. return {"success": False, "message": "缺少 file_id,无法获取合同详情"}
  123. try:
  124. detail_resp = esign_main.get_contract_detail(file_id)
  125. detail_json = json.loads(detail_resp)
  126. data = detail_json.get("data") if isinstance(detail_json, dict) else None
  127. contract_url_val = None
  128. if isinstance(data, dict):
  129. contract_url_val = data.get("fileDownloadUrl")
  130. if not contract_url_val and isinstance(detail_json, dict):
  131. contract_url_val = detail_json.get("fileDownloadUrl")
  132. except Exception as exc:
  133. return {"success": False, "message": "获取合同链接失败", "raw": str(exc)}
  134. if row and isinstance(items, list):
  135. for it in items:
  136. if it.get("sign_flow_id") == sign_flow_id:
  137. it["contract_url"] = contract_url_val
  138. break
  139. await self.repo.update_contract_items(row["id"], items)
  140. contact_phone = item.get("contact_phone") or (row.get("contact_phone") if isinstance(row, dict) else None)
  141. if not contact_phone:
  142. return {"success": False, "message": "缺少 contact_phone,无法获取签署链接"}
  143. try:
  144. sign_resp = sign_url(sign_flow_id, contact_phone)
  145. sign_json = json.loads(sign_resp)
  146. sign_data = sign_json.get("data") if isinstance(sign_json, dict) else None
  147. result_sign_url = sign_data.get("url") if isinstance(sign_data, dict) else None
  148. except Exception as exc:
  149. return {"success": False, "message": "获取签署链接失败", "raw": str(exc)}
  150. if not result_sign_url:
  151. return {"success": False, "message": "e签宝返回缺少签署链接", "raw": sign_json}
  152. await self.repo.update_sign_url(contact_phone, sign_flow_id, result_sign_url)
  153. return {
  154. "status": 0,
  155. "contract_url": contract_url_val,
  156. "sign_url": result_sign_url,
  157. "sign_flow_id": sign_flow_id,
  158. }
  159. async def _get_signed_contract_detail(self, sign_flow_id: str, row, item, items) -> dict:
  160. try:
  161. download_resp = file_download_url(sign_flow_id)
  162. download_json = json.loads(download_resp)
  163. contract_download_url = download_json["data"]["files"][0]["downloadUrl"]
  164. except Exception as exc:
  165. return {"success": False, "message": "获取合同下载链接失败", "raw": str(exc)}
  166. if row and isinstance(items, list):
  167. for it in items:
  168. if it.get("sign_flow_id") == sign_flow_id:
  169. it["contract_download_url"] = contract_download_url
  170. it["contract_url"] = contract_download_url
  171. break
  172. await self.repo.update_contract_items(row["id"], items)
  173. return {
  174. "status": 1,
  175. "contract_url": contract_download_url,
  176. "contract_download_url": contract_download_url,
  177. "sign_flow_id": sign_flow_id,
  178. }
  179. async def process_esign_callback(self, payload: dict) -> dict:
  180. sign_result = payload.get("signResult")
  181. sign_flow_id = payload.get("signFlowId")
  182. operator = payload.get("operator") or {}
  183. psn_account = operator.get("psnAccount") or {}
  184. contact_phone = psn_account.get("accountMobile")
  185. ts_ms = payload.get("operateTime") or payload.get("timestamp")
  186. signing_dt = None
  187. if ts_ms:
  188. try:
  189. signing_dt = datetime.datetime.fromtimestamp(ts_ms / 1000)
  190. except Exception:
  191. signing_dt = None
  192. if sign_result == 2:
  193. contract_download_url = None
  194. try:
  195. download_resp = file_download_url(sign_flow_id)
  196. download_json = json.loads(download_resp)
  197. contract_download_url = download_json["data"]["files"][0]["downloadUrl"]
  198. except Exception:
  199. contract_download_url = None
  200. await self.repo.mark_signed_by_phone(contact_phone, sign_flow_id, signing_dt, contract_download_url)
  201. return {"success": True, "code": "200", "msg": "success"}
  202. return {"success": False, "message": "未处理: signResult!=2 或手机号/签署流程缺失"}