contract_repo.py 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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, signing_time: datetime | None = None):
  43. """
  44. 根据手机号将合同标记为已签署,并更新 contract_url 内的 status=1
  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. item["status"] = 1
  64. changed = True
  65. # 时间处理
  66. signing_dt = signing_time
  67. effective_dt = expiry_dt = None
  68. if signing_dt:
  69. effective_dt = signing_dt + timedelta(days=1)
  70. expiry_dt = effective_dt + timedelta(days=365)
  71. if changed or True:
  72. await self.db.execute(
  73. ContractStore.__table__.update()
  74. .where(ContractStore.id == row["id"])
  75. .values(
  76. signing_status="已签署",
  77. contract_url=json.dumps(items, ensure_ascii=False) if items else contract_url_raw,
  78. signing_time=signing_dt,
  79. effective_time=effective_dt,
  80. expiry_time=expiry_dt,
  81. )
  82. )
  83. updated = True
  84. if updated:
  85. await self.db.commit()
  86. return updated