contract_repo.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  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, contract_download_url: str | None = None):
  43. """
  44. 根据手机号 + sign_flow_id 将合同标记为已签署,只更新匹配的合同项
  45. 当 is_master 为 1 时,更新签署状态和时间字段
  46. 同时写入签署/生效/到期时间(签署时间=T,生效=T+1天0点,失效=生效+365天)
  47. 同时更新 contract_download_url 到对应的字典中
  48. """
  49. result = await self.db.execute(
  50. ContractStore.__table__.select().where(ContractStore.contact_phone == contact_phone)
  51. )
  52. rows = result.mappings().all()
  53. updated = False
  54. for row in rows:
  55. contract_url_raw = row.get("contract_url")
  56. items = None
  57. if contract_url_raw:
  58. try:
  59. items = json.loads(contract_url_raw)
  60. except Exception:
  61. items = None
  62. changed = False
  63. matched_item = None
  64. if isinstance(items, list):
  65. for item in items:
  66. if item.get("sign_flow_id") == sign_flow_id:
  67. item["status"] = 1
  68. # 更新 contract_download_url
  69. if contract_download_url:
  70. item["contract_download_url"] = contract_download_url
  71. matched_item = item
  72. changed = True
  73. break
  74. # 只有当 is_master 为 1 时才更新时间字段
  75. if changed and matched_item and matched_item.get("is_master") == 1:
  76. # 时间处理
  77. signing_dt = signing_time
  78. effective_dt = expiry_dt = None
  79. if signing_dt:
  80. # effective_time 是 signing_time 第二天的 0 点
  81. effective_dt = (signing_dt + timedelta(days=1)).replace(hour=0, minute=0, second=0, microsecond=0)
  82. expiry_dt = effective_dt + timedelta(days=365)
  83. # 更新 contract_url 中对应字典的时间字段
  84. matched_item["signing_time"] = signing_dt.strftime("%Y-%m-%d %H:%M:%S") if signing_dt else ""
  85. matched_item["effective_time"] = effective_dt.strftime("%Y-%m-%d %H:%M:%S") if effective_dt else ""
  86. matched_item["expiry_time"] = expiry_dt.strftime("%Y-%m-%d %H:%M:%S") if expiry_dt else ""
  87. await self.db.execute(
  88. ContractStore.__table__.update()
  89. .where(ContractStore.id == row["id"])
  90. .values(
  91. signing_status="已签署",
  92. contract_url=json.dumps(items, ensure_ascii=False) if items else contract_url_raw,
  93. signing_time=signing_dt,
  94. effective_time=effective_dt,
  95. expiry_time=expiry_dt,
  96. )
  97. )
  98. updated = True
  99. elif changed:
  100. # is_master 不为 1 时,只更新 status,不更新时间字段
  101. await self.db.execute(
  102. ContractStore.__table__.update()
  103. .where(ContractStore.id == row["id"])
  104. .values(
  105. contract_url=json.dumps(items, ensure_ascii=False) if items else contract_url_raw,
  106. )
  107. )
  108. updated = True
  109. if updated:
  110. await self.db.commit()
  111. return updated
  112. async def update_sign_url(self, contact_phone: str, sign_flow_id: str, sign_url: str):
  113. """
  114. 根据手机号 + sign_flow_id 更新 contract_url 列表中对应项的 sign_url
  115. """
  116. result = await self.db.execute(
  117. ContractStore.__table__.select().where(ContractStore.contact_phone == contact_phone)
  118. )
  119. rows = result.mappings().all()
  120. updated = False
  121. for row in rows:
  122. contract_url_raw = row.get("contract_url")
  123. if not contract_url_raw:
  124. continue
  125. try:
  126. items = json.loads(contract_url_raw)
  127. except Exception:
  128. items = None
  129. if not isinstance(items, list):
  130. continue
  131. changed = False
  132. for item in items:
  133. if item.get("sign_flow_id") == sign_flow_id:
  134. item["sign_url"] = sign_url
  135. changed = True
  136. if changed:
  137. await self.db.execute(
  138. ContractStore.__table__.update()
  139. .where(ContractStore.id == row["id"])
  140. .values(contract_url=json.dumps(items, ensure_ascii=False))
  141. )
  142. updated = True
  143. if updated:
  144. await self.db.commit()
  145. return updated
  146. async def append_contract_url(self, templates_data, contract_item: dict):
  147. """
  148. 根据手机号,向 contract_url(JSON 列表)追加新的合同信息;
  149. 若手机号不存在,则创建新记录。
  150. """
  151. contact_phone = getattr(templates_data, "contact_phone", None)
  152. result = await self.db.execute(
  153. ContractStore.__table__.select().where(ContractStore.contact_phone == contact_phone)
  154. )
  155. rows = result.mappings().all()
  156. updated = False
  157. if rows:
  158. for row in rows:
  159. contract_url_raw = row.get("contract_url")
  160. try:
  161. items = json.loads(contract_url_raw) if contract_url_raw else []
  162. except Exception:
  163. items = []
  164. if not isinstance(items, list):
  165. items = []
  166. items.append(contract_item)
  167. await self.db.execute(
  168. ContractStore.__table__.update()
  169. .where(ContractStore.id == row["id"])
  170. .values(contract_url=json.dumps(items, ensure_ascii=False))
  171. )
  172. updated = True
  173. if updated:
  174. await self.db.commit()
  175. return updated
  176. # 未找到则创建新记录
  177. new_record = ContractStore(
  178. store_id=getattr(templates_data, "store_id", None),
  179. business_segment=getattr(templates_data, "business_segment", None),
  180. merchant_name=getattr(templates_data, "merchant_name", None),
  181. contact_phone=contact_phone,
  182. contract_url=json.dumps([contract_item], ensure_ascii=False),
  183. seal_url='0.0',
  184. signing_status='未签署'
  185. )
  186. self.db.add(new_record)
  187. await self.db.commit()
  188. await self.db.refresh(new_record)
  189. return True