contract_repo.py 8.2 KB

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