| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229 |
- import datetime
- import json
- import logging
- import os
- from typing import Optional, Any
- from sqlalchemy.ext.asyncio import AsyncSession
- from alien_lawyer.repositories.contract_repo import LawyerContractRepository
- from alien_lawyer.schemas.request.contract_lawyer import LawyerTemplatesCreate
- from alien_contract.infrastructure.esign import main as esign_main
- from alien_contract.infrastructure.esign.contract_builder import build_contract_items, ContractBuildError
- from alien_contract.infrastructure.esign.main import sign_url, file_download_url
- LOG_DIR = os.path.join("common", "logs", "alien_lawyer")
- os.makedirs(LOG_DIR, exist_ok=True)
- def _init_logger():
- logger = logging.getLogger("alien_lawyer_service")
- if logger.handlers:
- return logger
- logger.setLevel(logging.INFO)
- fmt = logging.Formatter("%(asctime)s [%(levelname)s] %(name)s %(message)s")
- info_handler = logging.FileHandler(os.path.join(LOG_DIR, "info.log"), encoding="utf-8")
- info_handler.setLevel(logging.INFO)
- info_handler.setFormatter(fmt)
- error_handler = logging.FileHandler(os.path.join(LOG_DIR, "error.log"), encoding="utf-8")
- error_handler.setLevel(logging.ERROR)
- error_handler.setFormatter(fmt)
- logger.addHandler(info_handler)
- logger.addHandler(error_handler)
- return logger
- logger = _init_logger()
- LAWYER_CONTRACT_CREATE_CONFIGS = [
- ("lawyer_agreement", "律所入驻协议", 1),
- ("alipay_auth", "支付宝授权函", 0),
- ("wechat_pay_commitment", "微信支付承诺函", 0),
- ]
- class LawyerContractServer:
- def __init__(self, db: AsyncSession):
- self.db = db
- self.repo = LawyerContractRepository(db)
- async def create_esign_templates(self, templates_data: LawyerTemplatesCreate) -> dict:
- logger.info("create lawyer esign templates request: %s", templates_data)
- try:
- generated_contracts = build_contract_items(
- configs=LAWYER_CONTRACT_CREATE_CONFIGS,
- template_name=templates_data.law_firm_name,
- signer_name=templates_data.law_firm_name,
- signer_id_num=templates_data.ord_id,
- psn_account=templates_data.contact_phone,
- psn_name=templates_data.contact_name,
- )
- except ContractBuildError as exc:
- return {"success": False, "message": exc.message, "raw": exc.raw}
- for contract_item in generated_contracts:
- await self.repo.append_contract_url(templates_data, contract_item)
- master_contract = next((item for item in generated_contracts if item.get("is_master") == 1), generated_contracts[0])
- return {
- "success": True,
- "message": "律所合同模板已追加/创建",
- "sign_flow_id": master_contract.get("sign_flow_id"),
- "file_id": master_contract.get("file_id"),
- "contract_url": master_contract.get("contract_url"),
- "created_contracts": [
- {
- "contract_type": item["contract_type"],
- "contract_name": item["contract_name"],
- "sign_flow_id": item["sign_flow_id"],
- "file_id": item["file_id"],
- "contract_url": item["contract_url"],
- }
- for item in generated_contracts
- ],
- }
- async def list_contracts(self, lawyer_id: int, status: Optional[int], page: int, page_size: int) -> dict:
- rows = await self.repo.get_by_lawyer_id(lawyer_id)
- all_filtered_items: list[dict[str, Any]] = []
- for row in rows:
- contract_url_raw = row.get("contract_url")
- if not contract_url_raw:
- continue
- try:
- items = json.loads(contract_url_raw)
- if not isinstance(items, list):
- continue
- for item in items:
- if status is not None and item.get("status") != status:
- continue
- item_with_info = dict(item)
- item_with_info.update(
- {
- "id": row.get("id"),
- "lawyer_id": row.get("lawyer_id"),
- "law_firm_name": row.get("law_firm_name"),
- "contact_name": row.get("contact_name"),
- "contact_phone": row.get("contact_phone"),
- }
- )
- all_filtered_items.append(item_with_info)
- except Exception:
- continue
- total = len(all_filtered_items)
- start = (page - 1) * page_size
- end = start + page_size
- paged_items = all_filtered_items[start:end]
- total_pages = (total + page_size - 1) // page_size if total > 0 else 0
- return {
- "items": paged_items,
- "total": total,
- "page": page,
- "page_size": page_size,
- "total_pages": total_pages,
- }
- async def get_contract_detail(self, sign_flow_id: str) -> dict:
- row, item, items = await self.repo.get_contract_item_by_sign_flow_id(sign_flow_id)
- if not item:
- return {"success": False, "message": "未找到合同"}
- status = item.get("status")
- if status == 0:
- return await self._get_pending_contract_detail(sign_flow_id, row, item, items)
- if status == 1:
- return await self._get_signed_contract_detail(sign_flow_id, row, item, items)
- return {"success": False, "message": "未知合同状态", "raw": {"status": status}}
- async def _get_pending_contract_detail(self, sign_flow_id: str, row, item, items) -> dict:
- file_id = item.get("file_id")
- if not file_id:
- return {"success": False, "message": "缺少 file_id,无法获取合同详情"}
- try:
- detail_resp = esign_main.get_contract_detail(file_id)
- detail_json = json.loads(detail_resp)
- data = detail_json.get("data") if isinstance(detail_json, dict) else None
- contract_url_val = None
- if isinstance(data, dict):
- contract_url_val = data.get("fileDownloadUrl")
- if not contract_url_val and isinstance(detail_json, dict):
- contract_url_val = detail_json.get("fileDownloadUrl")
- except Exception as exc:
- return {"success": False, "message": "获取合同链接失败", "raw": str(exc)}
- if row and isinstance(items, list):
- for it in items:
- if it.get("sign_flow_id") == sign_flow_id:
- it["contract_url"] = contract_url_val
- break
- await self.repo.update_contract_items(row["id"], items)
- contact_phone = item.get("contact_phone") or (row.get("contact_phone") if isinstance(row, dict) else None)
- if not contact_phone:
- return {"success": False, "message": "缺少 contact_phone,无法获取签署链接"}
- try:
- sign_resp = sign_url(sign_flow_id, contact_phone)
- sign_json = json.loads(sign_resp)
- sign_data = sign_json.get("data") if isinstance(sign_json, dict) else None
- result_sign_url = sign_data.get("url") if isinstance(sign_data, dict) else None
- except Exception as exc:
- return {"success": False, "message": "获取签署链接失败", "raw": str(exc)}
- if not result_sign_url:
- return {"success": False, "message": "e签宝返回缺少签署链接", "raw": sign_json}
- await self.repo.update_sign_url(contact_phone, sign_flow_id, result_sign_url)
- return {
- "status": 0,
- "contract_url": contract_url_val,
- "sign_url": result_sign_url,
- "sign_flow_id": sign_flow_id,
- }
- async def _get_signed_contract_detail(self, sign_flow_id: str, row, item, items) -> dict:
- try:
- download_resp = file_download_url(sign_flow_id)
- download_json = json.loads(download_resp)
- contract_download_url = download_json["data"]["files"][0]["downloadUrl"]
- except Exception as exc:
- return {"success": False, "message": "获取合同下载链接失败", "raw": str(exc)}
- if row and isinstance(items, list):
- for it in items:
- if it.get("sign_flow_id") == sign_flow_id:
- it["contract_download_url"] = contract_download_url
- it["contract_url"] = contract_download_url
- break
- await self.repo.update_contract_items(row["id"], items)
- return {
- "status": 1,
- "contract_url": contract_download_url,
- "contract_download_url": contract_download_url,
- "sign_flow_id": sign_flow_id,
- }
- async def process_esign_callback(self, payload: dict) -> dict:
- sign_result = payload.get("signResult")
- sign_flow_id = payload.get("signFlowId")
- operator = payload.get("operator") or {}
- psn_account = operator.get("psnAccount") or {}
- contact_phone = psn_account.get("accountMobile")
- ts_ms = payload.get("operateTime") or payload.get("timestamp")
- signing_dt = None
- if ts_ms:
- try:
- signing_dt = datetime.datetime.fromtimestamp(ts_ms / 1000)
- except Exception:
- signing_dt = None
- if sign_result == 2:
- contract_download_url = None
- try:
- download_resp = file_download_url(sign_flow_id)
- download_json = json.loads(download_resp)
- contract_download_url = download_json["data"]["files"][0]["downloadUrl"]
- except Exception:
- contract_download_url = None
- await self.repo.mark_signed_by_phone(contact_phone, sign_flow_id, signing_dt, contract_download_url)
- return {"success": True, "code": "200", "msg": "success"}
- return {"success": False, "message": "未处理: signResult!=2 或手机号/签署流程缺失"}
|