contract_repo.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. from sqlalchemy.ext.asyncio import AsyncSession
  2. from alien_store.db.models.contract_store import ContractStore
  3. import json
  4. from datetime import datetime, timedelta
  5. class ContractRepository:
  6. """合同数据访问层"""
  7. def __init__(self, db: AsyncSession):
  8. self.db = db
  9. async def get_by_store_id(self, store_id: int):
  10. """根据店铺id查询所有合同"""
  11. result = await self.db.execute(
  12. ContractStore.__table__.select().where(ContractStore.store_id == store_id)
  13. )
  14. # 返回列表[dict],避免 Pydantic 序列化 Row 对象出错
  15. return [dict(row) for row in result.mappings().all()]
  16. async def get_all(self):
  17. """查询所有合同"""
  18. result = await self.db.execute(ContractStore.__table__.select())
  19. return [dict(row) for row in result.mappings().all()]
  20. async def get_all_paged(self, page: int, page_size: int = 10):
  21. """分页查询所有合同"""
  22. offset = (page - 1) * page_size
  23. result = await self.db.execute(
  24. ContractStore.__table__.select().offset(offset).limit(page_size)
  25. )
  26. return [dict(row) for row in result.mappings().all()]
  27. async def create(self, user_data):
  28. """创建未签署合同模板"""
  29. db_templates = ContractStore(
  30. store_id=user_data.store_id,
  31. merchant_name=user_data.merchant_name,
  32. business_segment=user_data.business_segment,
  33. contact_phone=user_data.contact_phone,
  34. contract_url=user_data.contract_url,
  35. seal_url='0.0',
  36. signing_status='未签署'
  37. )
  38. self.db.add(db_templates)
  39. await self.db.commit()
  40. await self.db.refresh(db_templates)
  41. return db_templates
  42. async def mark_signed_by_phone(self, contact_phone: str, sign_flow_id: str, signing_time: datetime | None = None):
  43. """
  44. 根据手机号 + sign_flow_id 将合同标记为已签署,只更新匹配的合同项
  45. 同时写入签署/生效/到期时间(签署时间=T,生效=T+1天,失效=生效+365天)
  46. """
  47. result = await self.db.execute(
  48. ContractStore.__table__.select().where(ContractStore.contact_phone == contact_phone)
  49. )
  50. rows = result.mappings().all()
  51. updated = False
  52. for row in rows:
  53. contract_url_raw = row.get("contract_url")
  54. items = None
  55. if contract_url_raw:
  56. try:
  57. items = json.loads(contract_url_raw)
  58. except Exception:
  59. items = None
  60. changed = False
  61. if isinstance(items, list):
  62. for item in items:
  63. if item.get("sign_flow_id") == sign_flow_id:
  64. item["status"] = 1
  65. changed = True
  66. # 时间处理
  67. signing_dt = signing_time
  68. effective_dt = expiry_dt = None
  69. if signing_dt:
  70. effective_dt = signing_dt + timedelta(days=1)
  71. expiry_dt = effective_dt + timedelta(days=365)
  72. if changed:
  73. await self.db.execute(
  74. ContractStore.__table__.update()
  75. .where(ContractStore.id == row["id"])
  76. .values(
  77. signing_status="已签署",
  78. contract_url=json.dumps(items, ensure_ascii=False) if items else contract_url_raw,
  79. signing_time=signing_dt,
  80. effective_time=effective_dt,
  81. expiry_time=expiry_dt,
  82. )
  83. )
  84. updated = True
  85. if updated:
  86. await self.db.commit()
  87. return updated
  88. async def update_sign_url(self, contact_phone: str, sign_flow_id: str, sign_url: str):
  89. """
  90. 根据手机号 + sign_flow_id 更新 contract_url 列表中对应项的 sign_url
  91. """
  92. result = await self.db.execute(
  93. ContractStore.__table__.select().where(ContractStore.contact_phone == contact_phone)
  94. )
  95. rows = result.mappings().all()
  96. updated = False
  97. for row in rows:
  98. contract_url_raw = row.get("contract_url")
  99. if not contract_url_raw:
  100. continue
  101. try:
  102. items = json.loads(contract_url_raw)
  103. except Exception:
  104. items = None
  105. if not isinstance(items, list):
  106. continue
  107. changed = False
  108. for item in items:
  109. if item.get("sign_flow_id") == sign_flow_id:
  110. item["sign_url"] = sign_url
  111. changed = True
  112. if changed:
  113. await self.db.execute(
  114. ContractStore.__table__.update()
  115. .where(ContractStore.id == row["id"])
  116. .values(contract_url=json.dumps(items, ensure_ascii=False))
  117. )
  118. updated = True
  119. if updated:
  120. await self.db.commit()
  121. return updated
  122. async def append_contract_url(self, templates_data, contract_item: dict):
  123. """
  124. 根据手机号,向 contract_url(JSON 列表)追加新的合同信息;
  125. 若手机号不存在,则创建新记录。
  126. """
  127. contact_phone = getattr(templates_data, "contact_phone", None)
  128. result = await self.db.execute(
  129. ContractStore.__table__.select().where(ContractStore.contact_phone == contact_phone)
  130. )
  131. rows = result.mappings().all()
  132. updated = False
  133. if rows:
  134. for row in rows:
  135. contract_url_raw = row.get("contract_url")
  136. try:
  137. items = json.loads(contract_url_raw) if contract_url_raw else []
  138. except Exception:
  139. items = []
  140. if not isinstance(items, list):
  141. items = []
  142. items.append(contract_item)
  143. await self.db.execute(
  144. ContractStore.__table__.update()
  145. .where(ContractStore.id == row["id"])
  146. .values(contract_url=json.dumps(items, ensure_ascii=False))
  147. )
  148. updated = True
  149. if updated:
  150. await self.db.commit()
  151. return updated
  152. # 未找到则创建新记录
  153. new_record = ContractStore(
  154. store_id=getattr(templates_data, "store_id", None),
  155. business_segment=getattr(templates_data, "business_segment", None),
  156. merchant_name=getattr(templates_data, "merchant_name", None),
  157. contact_phone=contact_phone,
  158. contract_url=json.dumps([contract_item], ensure_ascii=False),
  159. seal_url='0.0',
  160. signing_status='未签署'
  161. )
  162. self.db.add(new_record)
  163. await self.db.commit()
  164. await self.db.refresh(new_record)
  165. return True