collection_protocol.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853
  1. """细胞存储 — 采集协议单 / 审核 / 财务确认 / 分期预警 API"""
  2. from datetime import datetime, timedelta
  3. from typing import Any, Dict, List, Optional
  4. from fastapi import APIRouter, Depends, Query
  5. from pydantic import BaseModel, ConfigDict, Field
  6. from sqlalchemy.orm import Session
  7. from sqlalchemy import and_ as sa_and, func as sa_func, or_ as sa_or
  8. from app.core.database import get_db
  9. from app.core.menu_guard import require_admin_or_super_admin
  10. from app.core.response import error_response, success_response
  11. from app.core.utils import parse_datetime
  12. from app.crud import collection_protocol as cp_svc
  13. from app.crud import customer as customer_crud
  14. from app.models.models import (
  15. BizCollectionProtocol,
  16. BizCustomer,
  17. BizProtocolPartyCustomer,
  18. BizProtocolSample,
  19. BizProtocolStorageCert,
  20. SysUser,
  21. )
  22. router = APIRouter(prefix="/web/admin", tags=["细胞存储"])
  23. def _get_tenant_no(db: Session, user: dict) -> str:
  24. user_id = user.get("user_id")
  25. if not user_id:
  26. raise PermissionError("用户身份信息缺失,无法确定租户")
  27. sys_user = db.query(SysUser).filter(SysUser.id == user_id).first()
  28. if not sys_user or not sys_user.tenant_no:
  29. raise PermissionError("用户租户信息缺失")
  30. return sys_user.tenant_no
  31. def _get_current_user_id(user: dict) -> str:
  32. user_id = user.get("user_id")
  33. if not user_id:
  34. raise PermissionError("用户身份信息缺失")
  35. return str(user_id)
  36. _CAMEL_TO_SNAKE_DATETIME = {
  37. "newbornDeliveryTime": "newborn_delivery_time",
  38. "sampleCollectTime": "sample_collect_time",
  39. "maternalBloodCollectTime": "maternal_blood_collect_time",
  40. }
  41. def _parse_datetime_fields(d: dict, camel_keys: list) -> None:
  42. for camel in camel_keys:
  43. val = d.get(camel)
  44. if val is not None and isinstance(val, str):
  45. snake = _CAMEL_TO_SNAKE_DATETIME.get(camel, camel)
  46. parsed = parse_datetime(val)
  47. if parsed:
  48. d.pop(camel, None)
  49. d[snake] = parsed
  50. else:
  51. d.pop(camel, None)
  52. d[snake] = None
  53. def _ensure_customer_for_mother(db: Session, party_customer: dict, tenant_no: str, user_id: str) -> dict:
  54. """If mother info exists but no customerId, create a customer record and link it."""
  55. if not party_customer:
  56. return party_customer
  57. customer_id = party_customer.get("customer_id") or party_customer.get("customerId")
  58. mother_name = (party_customer.get("mother_name") or party_customer.get("motherName") or "").strip()
  59. if customer_id or not mother_name:
  60. return party_customer
  61. # Build customer fields from mother info
  62. mother_phone = (party_customer.get("mother_phone") or party_customer.get("motherPhone") or "").strip() or None
  63. mother_id_card = (party_customer.get("mother_id_card") or party_customer.get("motherIdCard") or "").strip() or None
  64. # Check if customer with this id_card already exists
  65. if mother_id_card and customer_crud.id_card_taken(db, mother_id_card, tenant_no):
  66. existing = db.query(BizCustomer).filter(
  67. sa_and(
  68. BizCustomer.id_card_no == mother_id_card,
  69. BizCustomer.tenant_no == tenant_no,
  70. BizCustomer.del_flag == 0,
  71. )
  72. ).first()
  73. if existing:
  74. party_customer["customer_id"] = existing.id
  75. return party_customer
  76. # Create new customer
  77. try:
  78. obj = customer_crud.create_customer(
  79. db,
  80. customer_name=mother_name,
  81. sex="1", # female (mother)
  82. id_card_no=mother_id_card,
  83. phone_no=mother_phone,
  84. tenant_no=tenant_no,
  85. user_id=user_id,
  86. )
  87. party_customer["customer_id"] = obj.id
  88. except ValueError:
  89. # If creation fails (e.g. duplicate), try to find existing
  90. pass
  91. return party_customer
  92. # ---------------------------------------------------------------------------
  93. # 采集协议单
  94. # ---------------------------------------------------------------------------
  95. @router.get("/collection-protocols")
  96. async def list_collection_protocols(
  97. page: int = Query(1, ge=1),
  98. pageSize: int = Query(10, ge=1, le=100, alias="pageSize"),
  99. keyword: Optional[str] = None,
  100. protocolStatus: Optional[str] = Query(None, alias="protocolStatus"),
  101. user: dict = Depends(require_admin_or_super_admin),
  102. db: Session = Depends(get_db),
  103. ):
  104. tenant_no = _get_tenant_no(db, user)
  105. current_user_id = _get_current_user_id(user)
  106. items, total = cp_svc.list_collection_protocols(
  107. db,
  108. page=page,
  109. page_size=pageSize,
  110. keyword=keyword,
  111. protocol_status=protocolStatus,
  112. tenant_no=tenant_no,
  113. scope_collector_user_id=current_user_id,
  114. user_info=user,
  115. )
  116. tp = cp_svc.total_pages(total, pageSize)
  117. return success_response({"list": items, "total": total, "page": page, "pageSize": pageSize, "totalPages": tp})
  118. @router.get("/collection-protocols/{protocol_id}")
  119. async def get_collection_protocol_detail(
  120. protocol_id: str,
  121. user: dict = Depends(require_admin_or_super_admin),
  122. db: Session = Depends(get_db),
  123. ):
  124. tenant_no = _get_tenant_no(db, user)
  125. current_user_id = _get_current_user_id(user)
  126. bundle = cp_svc.get_protocol_detail_bundle(
  127. db, protocol_id, tenant_no, scope_collector_user_id=current_user_id
  128. )
  129. if not bundle:
  130. return error_response(404, "协议单不存在或无权查看")
  131. return success_response(bundle)
  132. class ProtocolCreateBody(BaseModel):
  133. model_config = ConfigDict(populate_by_name=True)
  134. protocol_no: str = Field(..., alias="protocolNo")
  135. protocol_no_id: Optional[str] = Field(None, alias="protocolNoId")
  136. protocol_status: str = Field("dsx", alias="protocolStatus")
  137. protocol_attachments: Optional[str] = Field(None, alias="protocolAttachments")
  138. register_date: Optional[str] = Field(None, alias="registerDate")
  139. collector_user_id: Optional[str] = Field(None, alias="collectorUserId")
  140. remark: Optional[str] = None
  141. party_customer: Optional[dict] = Field(None, alias="partyCustomer")
  142. collection_info: Optional[dict] = Field(None, alias="collectionInfo")
  143. samples: Optional[list] = Field(None, alias="samples")
  144. payment: Optional[dict] = Field(None, alias="payment")
  145. payment_details: Optional[list] = Field(None, alias="paymentDetails")
  146. attachments: Optional[list] = Field(None, alias="attachments")
  147. storage_cert: Optional[dict] = Field(None, alias="storageCert")
  148. class ProtocolUpdateBody(BaseModel):
  149. model_config = ConfigDict(populate_by_name=True)
  150. protocol_no: Optional[str] = Field(None, alias="protocolNo")
  151. protocol_status: Optional[str] = Field(None, alias="protocolStatus")
  152. protocol_attachments: Optional[str] = Field(None, alias="protocolAttachments")
  153. register_date: Optional[str] = Field(None, alias="registerDate")
  154. effective_time: Optional[str] = Field(None, alias="effectiveTime")
  155. effective_desc: Optional[str] = Field(None, alias="effectiveDesc")
  156. expire_time: Optional[str] = Field(None, alias="expireTime")
  157. expire_desc: Optional[str] = Field(None, alias="expireDesc")
  158. void_time: Optional[str] = Field(None, alias="voidTime")
  159. void_desc: Optional[str] = Field(None, alias="voidDesc")
  160. to_research_time: Optional[str] = Field(None, alias="toResearchTime")
  161. to_research_desc: Optional[str] = Field(None, alias="toResearchDesc")
  162. collector_user_id: Optional[str] = Field(None, alias="collectorUserId")
  163. remark: Optional[str] = None
  164. party_customer: Optional[dict] = Field(None, alias="partyCustomer")
  165. collection_info: Optional[dict] = Field(None, alias="collectionInfo")
  166. samples: Optional[list] = Field(None, alias="samples")
  167. payment: Optional[dict] = Field(None, alias="payment")
  168. payment_details: Optional[list] = Field(None, alias="paymentDetails")
  169. attachments: Optional[list] = Field(None, alias="attachments")
  170. storage_cert: Optional[dict] = Field(None, alias="storageCert")
  171. def _resolve_protocol_attachments(
  172. protocol_attachments: Optional[str],
  173. attachments: Optional[list],
  174. ) -> Optional[str]:
  175. from_urls = cp_svc.attachments_to_urls(attachments)
  176. if from_urls:
  177. return from_urls
  178. return protocol_attachments
  179. def _persist_protocol_sub_resources(
  180. db: Session,
  181. protocol_id: str,
  182. tenant_no: str,
  183. user_id: str,
  184. *,
  185. party_customer: Optional[dict],
  186. collection_info: Optional[dict],
  187. samples: Optional[list],
  188. payment: Optional[dict],
  189. payment_details: Optional[list],
  190. storage_cert: Optional[dict],
  191. ) -> None:
  192. if party_customer:
  193. _parse_datetime_fields(party_customer, ["newbornDeliveryTime"])
  194. party_customer = _ensure_customer_for_mother(db, party_customer, tenant_no, user_id)
  195. cp_svc.upsert_party_customer(db, protocol_id, tenant_no, user_id, **party_customer)
  196. if collection_info:
  197. _parse_datetime_fields(collection_info, ["sampleCollectTime", "maternalBloodCollectTime"])
  198. cp_svc.upsert_collection_info(db, protocol_id, tenant_no, user_id, **collection_info)
  199. if samples is not None:
  200. cp_svc.save_samples(db, protocol_id, tenant_no, user_id, samples)
  201. pay = None
  202. if payment:
  203. pay = cp_svc.upsert_payment(db, protocol_id, tenant_no, user_id, **payment)
  204. if payment_details is not None:
  205. if not pay and payment:
  206. pay = cp_svc.upsert_payment(db, protocol_id, tenant_no, user_id, **payment)
  207. if pay:
  208. aligned_details = cp_svc.align_fq_payment_details_payload(pay, payment_details)
  209. cp_svc.save_payment_details(db, pay.id, tenant_no, user_id, aligned_details)
  210. if storage_cert:
  211. cp_svc.upsert_storage_cert(db, protocol_id, tenant_no, user_id, **storage_cert)
  212. @router.post("/collection-protocols")
  213. async def create_collection_protocol(
  214. body: ProtocolCreateBody,
  215. user: dict = Depends(require_admin_or_super_admin),
  216. db: Session = Depends(get_db),
  217. ):
  218. tenant_no = _get_tenant_no(db, user)
  219. user_id = _get_current_user_id(user)
  220. try:
  221. protocol_attachments = _resolve_protocol_attachments(
  222. body.protocol_attachments,
  223. body.attachments,
  224. )
  225. obj = cp_svc.create_collection_protocol(
  226. db,
  227. protocol_no=body.protocol_no,
  228. protocol_no_id=body.protocol_no_id,
  229. protocol_status=body.protocol_status,
  230. protocol_attachments=protocol_attachments,
  231. register_date=body.register_date,
  232. collector_user_id=user_id,
  233. remark=body.remark,
  234. tenant_no=tenant_no,
  235. user_id=user_id,
  236. )
  237. protocol_id = obj.id
  238. _persist_protocol_sub_resources(
  239. db,
  240. protocol_id,
  241. tenant_no,
  242. user_id,
  243. party_customer=body.party_customer,
  244. collection_info=body.collection_info,
  245. samples=body.samples,
  246. payment=body.payment,
  247. payment_details=body.payment_details,
  248. storage_cert=body.storage_cert,
  249. )
  250. return success_response(cp_svc._protocol_to_dict(obj), message="创建成功")
  251. except ValueError as e:
  252. return error_response(400, str(e))
  253. @router.put("/collection-protocols/{protocol_id}")
  254. async def update_collection_protocol(
  255. protocol_id: str,
  256. body: ProtocolUpdateBody,
  257. user: dict = Depends(require_admin_or_super_admin),
  258. db: Session = Depends(get_db),
  259. ):
  260. tenant_no = _get_tenant_no(db, user)
  261. user_id = _get_current_user_id(user)
  262. try:
  263. payload = body.model_dump(exclude_unset=True, by_alias=False)
  264. sub_keys = {
  265. "party_customer", "collection_info", "samples",
  266. "payment", "payment_details", "attachments", "storage_cert",
  267. }
  268. main_payload = {k: v for k, v in payload.items() if k not in sub_keys}
  269. main_payload.pop("collector_user_id", None)
  270. if body.attachments is not None:
  271. resolved = _resolve_protocol_attachments(
  272. main_payload.get("protocol_attachments"),
  273. body.attachments,
  274. )
  275. if resolved is not None:
  276. main_payload["protocol_attachments"] = resolved
  277. obj = cp_svc.update_collection_protocol(
  278. db,
  279. protocol_id,
  280. tenant_no=tenant_no,
  281. user_id=user_id,
  282. scope_collector_user_id=user_id,
  283. **{k: v for k, v in main_payload.items() if v is not None},
  284. )
  285. _persist_protocol_sub_resources(
  286. db,
  287. protocol_id,
  288. tenant_no,
  289. user_id,
  290. party_customer=body.party_customer,
  291. collection_info=body.collection_info,
  292. samples=body.samples,
  293. payment=body.payment,
  294. payment_details=body.payment_details,
  295. storage_cert=body.storage_cert,
  296. )
  297. return success_response(cp_svc._protocol_to_dict(obj), message="更新成功")
  298. except ValueError as e:
  299. return error_response(400, str(e))
  300. @router.delete("/collection-protocols/{protocol_id}")
  301. async def delete_collection_protocol(
  302. protocol_id: str,
  303. user: dict = Depends(require_admin_or_super_admin),
  304. db: Session = Depends(get_db),
  305. ):
  306. tenant_no = _get_tenant_no(db, user)
  307. user_id = _get_current_user_id(user)
  308. try:
  309. cp_svc.soft_delete_collection_protocol(
  310. db,
  311. protocol_id,
  312. tenant_no=tenant_no,
  313. scope_collector_user_id=user_id,
  314. user_id=user_id,
  315. )
  316. return success_response(None, message="删除成功")
  317. except ValueError as e:
  318. return error_response(400, str(e))
  319. # ---------------------------------------------------------------------------
  320. # 审核
  321. # ---------------------------------------------------------------------------
  322. @router.get("/collection-protocol-audits")
  323. async def list_collection_protocol_audits(
  324. page: int = Query(1, ge=1),
  325. pageSize: int = Query(10, ge=1, le=100, alias="pageSize"),
  326. keyword: Optional[str] = None,
  327. auditStatus: Optional[str] = Query(None, alias="auditStatus"),
  328. user: dict = Depends(require_admin_or_super_admin),
  329. db: Session = Depends(get_db),
  330. ):
  331. tenant_no = _get_tenant_no(db, user)
  332. items, total = cp_svc.list_audits(
  333. db,
  334. page=page,
  335. page_size=pageSize,
  336. keyword=keyword,
  337. audit_status=auditStatus,
  338. tenant_no=tenant_no,
  339. user_info=user,
  340. )
  341. tp = cp_svc.total_pages(total, pageSize)
  342. return success_response({"list": items, "total": total, "page": page, "pageSize": pageSize, "totalPages": tp})
  343. class AuditCreateBody(BaseModel):
  344. model_config = ConfigDict(populate_by_name=True)
  345. audit_status: str = Field(..., alias="auditStatus")
  346. audit_remark: Optional[str] = Field(None, alias="auditRemark")
  347. @router.post("/collection-protocols/{protocol_id}/audit")
  348. async def submit_collection_protocol_audit(
  349. protocol_id: str,
  350. body: AuditCreateBody,
  351. user: dict = Depends(require_admin_or_super_admin),
  352. db: Session = Depends(get_db),
  353. ):
  354. tenant_no = _get_tenant_no(db, user)
  355. try:
  356. cp_svc.create_audit(
  357. db,
  358. collection_protocol_id=protocol_id,
  359. audit_status=body.audit_status,
  360. audit_remark=body.audit_remark,
  361. tenant_no=tenant_no,
  362. user_id=user.get("user_id"),
  363. )
  364. p = db.query(BizCollectionProtocol).filter(BizCollectionProtocol.id == protocol_id).first()
  365. pn = (p.protocol_no if p else "") or ""
  366. return success_response({"protocolNo": pn}, message="审核已提交")
  367. except ValueError as e:
  368. return error_response(400, str(e))
  369. # ---------------------------------------------------------------------------
  370. # 收款确认
  371. # ---------------------------------------------------------------------------
  372. @router.get("/protocol-payment-details")
  373. async def list_payment_details(
  374. page: int = Query(1, ge=1),
  375. pageSize: int = Query(10, ge=1, le=100, alias="pageSize"),
  376. payStatus: str = Query("dfj", alias="payStatus"),
  377. keyword: str = Query("", alias="keyword"),
  378. transferType: str = Query("", alias="transferType"),
  379. user: dict = Depends(require_admin_or_super_admin),
  380. db: Session = Depends(get_db),
  381. ):
  382. tenant_no = _get_tenant_no(db, user)
  383. items, total = cp_svc.list_payment_details_page(
  384. db,
  385. page=page,
  386. page_size=pageSize,
  387. pay_status=payStatus,
  388. keyword=keyword or None,
  389. transfer_type=transferType or None,
  390. tenant_no=tenant_no,
  391. user_info=user,
  392. )
  393. tp = cp_svc.total_pages(total, pageSize)
  394. return success_response({"list": items, "total": total, "page": page, "pageSize": pageSize, "totalPages": tp})
  395. class BatchDetailIdsBody(BaseModel):
  396. model_config = ConfigDict(populate_by_name=True)
  397. detail_ids: List[str] = Field(..., alias="detailIds", min_length=1)
  398. class RefundFinanceSubmitBody(BaseModel):
  399. model_config = ConfigDict(populate_by_name=True)
  400. refund_amount: float = Field(..., alias="refundAmount", gt=0)
  401. refund_remark: Optional[str] = Field(None, alias="refundRemark")
  402. refund_attachments: Optional[str] = Field(None, alias="refundAttachments")
  403. class BatchRefundFinanceSubmitBody(RefundFinanceSubmitBody):
  404. model_config = ConfigDict(populate_by_name=True)
  405. detail_ids: List[str] = Field(..., alias="detailIds", min_length=1)
  406. @router.post("/protocol-payment-details/{detail_id}/submit-receipt-finance")
  407. async def post_submit_receipt_finance(
  408. detail_id: str,
  409. user: dict = Depends(require_admin_or_super_admin),
  410. db: Session = Depends(get_db),
  411. ):
  412. tenant_no = _get_tenant_no(db, user)
  413. try:
  414. cp_svc.submit_receipt_finance(
  415. db,
  416. detail_id=detail_id,
  417. tenant_no=tenant_no,
  418. user_id=user.get("user_id"),
  419. )
  420. return success_response(None, message="提交成功")
  421. except ValueError as e:
  422. return error_response(400, str(e))
  423. @router.post("/protocol-payment-details/submit-receipt-finance-batch")
  424. async def post_submit_receipt_finance_batch(
  425. body: BatchDetailIdsBody,
  426. user: dict = Depends(require_admin_or_super_admin),
  427. db: Session = Depends(get_db),
  428. ):
  429. tenant_no = _get_tenant_no(db, user)
  430. try:
  431. count = cp_svc.batch_submit_receipt_finance(
  432. db,
  433. detail_ids=body.detail_ids,
  434. tenant_no=tenant_no,
  435. user_id=user.get("user_id"),
  436. )
  437. return success_response({"count": count}, message=f"已成功提交 {count} 条")
  438. except ValueError as e:
  439. return error_response(400, str(e))
  440. @router.post("/protocol-payment-details/{detail_id}/submit-refund-finance")
  441. async def post_submit_refund_finance(
  442. detail_id: str,
  443. body: RefundFinanceSubmitBody,
  444. user: dict = Depends(require_admin_or_super_admin),
  445. db: Session = Depends(get_db),
  446. ):
  447. tenant_no = _get_tenant_no(db, user)
  448. try:
  449. cp_svc.submit_refund_finance(
  450. db,
  451. detail_id=detail_id,
  452. tenant_no=tenant_no,
  453. user_id=user.get("user_id"),
  454. refund_amount=body.refund_amount,
  455. refund_remark=body.refund_remark,
  456. refund_attachments=body.refund_attachments,
  457. )
  458. return success_response(None, message="提交成功")
  459. except ValueError as e:
  460. return error_response(400, str(e))
  461. @router.post("/protocol-payment-details/submit-refund-finance-batch")
  462. async def post_submit_refund_finance_batch(
  463. body: BatchRefundFinanceSubmitBody,
  464. user: dict = Depends(require_admin_or_super_admin),
  465. db: Session = Depends(get_db),
  466. ):
  467. tenant_no = _get_tenant_no(db, user)
  468. try:
  469. count = cp_svc.batch_submit_refund_finance(
  470. db,
  471. detail_ids=body.detail_ids,
  472. tenant_no=tenant_no,
  473. user_id=user.get("user_id"),
  474. refund_amount=body.refund_amount,
  475. refund_remark=body.refund_remark,
  476. refund_attachments=body.refund_attachments,
  477. )
  478. return success_response({"count": count}, message=f"已成功提交 {count} 条")
  479. except ValueError as e:
  480. return error_response(400, str(e))
  481. @router.get("/protocol-payment-details/receipt-confirm")
  482. async def list_receipt_confirm(
  483. page: int = Query(1, ge=1),
  484. pageSize: int = Query(10, ge=1, le=100, alias="pageSize"),
  485. user: dict = Depends(require_admin_or_super_admin),
  486. db: Session = Depends(get_db),
  487. ):
  488. tenant_no = _get_tenant_no(db, user)
  489. items, total = cp_svc.list_receipt_confirm_details(db, page=page, page_size=pageSize, tenant_no=tenant_no, user_info=user)
  490. tp = cp_svc.total_pages(total, pageSize)
  491. return success_response({"list": items, "total": total, "page": page, "pageSize": pageSize, "totalPages": tp})
  492. @router.get("/protocol-payment-details/receipt-confirmed")
  493. async def list_receipt_confirmed(
  494. page: int = Query(1, ge=1),
  495. pageSize: int = Query(10, ge=1, le=100, alias="pageSize"),
  496. user: dict = Depends(require_admin_or_super_admin),
  497. db: Session = Depends(get_db),
  498. ):
  499. tenant_no = _get_tenant_no(db, user)
  500. items, total = cp_svc.list_receipt_confirmed_details(
  501. db, page=page, page_size=pageSize, tenant_no=tenant_no, user_info=user
  502. )
  503. tp = cp_svc.total_pages(total, pageSize)
  504. return success_response({"list": items, "total": total, "page": page, "pageSize": pageSize, "totalPages": tp})
  505. class FinanceConfirmBody(BaseModel):
  506. model_config = ConfigDict(populate_by_name=True)
  507. finance_confirm_attachments: Optional[str] = Field(None, alias="financeConfirmAttachments")
  508. finance_remark: Optional[str] = Field(None, alias="financeRemark")
  509. class RefundFinanceConfirmBody(BaseModel):
  510. model_config = ConfigDict(populate_by_name=True)
  511. refund_finance_confirm_attachments: Optional[str] = Field(
  512. None, alias="refundFinanceConfirmAttachments"
  513. )
  514. refund_finance_remark: Optional[str] = Field(None, alias="refundFinanceRemark")
  515. @router.post("/protocol-payment-details/{detail_id}/receipt-confirm")
  516. async def post_receipt_confirm(
  517. detail_id: str,
  518. body: FinanceConfirmBody,
  519. user: dict = Depends(require_admin_or_super_admin),
  520. db: Session = Depends(get_db),
  521. ):
  522. tenant_no = _get_tenant_no(db, user)
  523. try:
  524. cp_svc.confirm_receipt(
  525. db,
  526. detail_id=detail_id,
  527. tenant_no=tenant_no,
  528. user_id=user.get("user_id"),
  529. finance_confirm_attachments=body.finance_confirm_attachments,
  530. finance_remark=body.finance_remark,
  531. )
  532. return success_response(None, message="确认成功")
  533. except ValueError as e:
  534. return error_response(400, str(e))
  535. # ---------------------------------------------------------------------------
  536. # 退费确认
  537. # ---------------------------------------------------------------------------
  538. @router.get("/protocol-payment-details/refund-confirm")
  539. async def list_refund_confirm(
  540. page: int = Query(1, ge=1),
  541. pageSize: int = Query(10, ge=1, le=100, alias="pageSize"),
  542. user: dict = Depends(require_admin_or_super_admin),
  543. db: Session = Depends(get_db),
  544. ):
  545. tenant_no = _get_tenant_no(db, user)
  546. items, total = cp_svc.list_refund_confirm_details(db, page=page, page_size=pageSize, tenant_no=tenant_no, user_info=user)
  547. tp = cp_svc.total_pages(total, pageSize)
  548. return success_response({"list": items, "total": total, "page": page, "pageSize": pageSize, "totalPages": tp})
  549. @router.get("/protocol-payment-details/refund-confirmed")
  550. async def list_refund_confirmed(
  551. page: int = Query(1, ge=1),
  552. pageSize: int = Query(10, ge=1, le=100, alias="pageSize"),
  553. user: dict = Depends(require_admin_or_super_admin),
  554. db: Session = Depends(get_db),
  555. ):
  556. tenant_no = _get_tenant_no(db, user)
  557. items, total = cp_svc.list_refund_confirmed_details(
  558. db, page=page, page_size=pageSize, tenant_no=tenant_no, user_info=user
  559. )
  560. tp = cp_svc.total_pages(total, pageSize)
  561. return success_response({"list": items, "total": total, "page": page, "pageSize": pageSize, "totalPages": tp})
  562. @router.post("/protocol-payment-details/{detail_id}/refund-confirm")
  563. async def post_refund_confirm(
  564. detail_id: str,
  565. body: RefundFinanceConfirmBody,
  566. user: dict = Depends(require_admin_or_super_admin),
  567. db: Session = Depends(get_db),
  568. ):
  569. tenant_no = _get_tenant_no(db, user)
  570. try:
  571. cp_svc.confirm_refund(
  572. db,
  573. detail_id=detail_id,
  574. tenant_no=tenant_no,
  575. user_id=user.get("user_id"),
  576. refund_finance_confirm_attachments=body.refund_finance_confirm_attachments,
  577. refund_finance_remark=body.refund_finance_remark,
  578. )
  579. return success_response(None, message="确认成功")
  580. except ValueError as e:
  581. return error_response(400, str(e))
  582. # ---------------------------------------------------------------------------
  583. # 储存证明管理 / 满月待办
  584. # ---------------------------------------------------------------------------
  585. @router.get("/storage-certs")
  586. async def list_storage_certs(
  587. page: int = Query(1, ge=1),
  588. pageSize: int = Query(10, ge=1, le=100, alias="pageSize"),
  589. keyword: Optional[str] = None,
  590. makeStatus: Optional[str] = Query(None, alias="makeStatus"),
  591. user: dict = Depends(require_admin_or_super_admin),
  592. db: Session = Depends(get_db),
  593. ):
  594. tenant_no = _get_tenant_no(db, user)
  595. page_items, total = cp_svc.list_storage_certs(
  596. db,
  597. tenant_no=tenant_no,
  598. keyword=keyword,
  599. make_status=makeStatus,
  600. page=page,
  601. page_size=pageSize,
  602. user_info=user,
  603. )
  604. page_safe = max(1, page)
  605. page_size_safe = min(max(1, pageSize), 100)
  606. tp = cp_svc.total_pages(total, page_size_safe)
  607. return success_response(
  608. {"list": page_items, "total": total, "page": page_safe, "pageSize": page_size_safe, "totalPages": tp}
  609. )
  610. @router.get("/fullmoon-todos")
  611. async def list_fullmoon_todos(
  612. page: int = Query(1, ge=1),
  613. pageSize: int = Query(10, ge=1, le=100, alias="pageSize"),
  614. keyword: Optional[str] = None,
  615. todoStatus: Optional[str] = Query(None, alias="todoStatus"),
  616. user: dict = Depends(require_admin_or_super_admin),
  617. db: Session = Depends(get_db),
  618. ):
  619. tenant_no = _get_tenant_no(db, user)
  620. party_join = sa_and(
  621. BizProtocolPartyCustomer.collection_protocol_id == BizCollectionProtocol.id,
  622. BizProtocolPartyCustomer.del_flag == 0,
  623. BizProtocolPartyCustomer.tenant_no == tenant_no,
  624. )
  625. q = (
  626. db.query(BizCollectionProtocol, BizProtocolPartyCustomer)
  627. .outerjoin(BizProtocolPartyCustomer, party_join)
  628. .filter(
  629. BizCollectionProtocol.del_flag == 0,
  630. BizCollectionProtocol.tenant_no == tenant_no,
  631. BizCollectionProtocol.protocol_status == "sxz",
  632. )
  633. )
  634. kw = (keyword or "").strip()
  635. if kw:
  636. like = f"%{kw}%"
  637. q = q.filter(
  638. sa_or(
  639. BizCollectionProtocol.protocol_no.like(like),
  640. BizProtocolPartyCustomer.mother_name.like(like),
  641. )
  642. )
  643. from app.core.data_scope import apply_data_scope
  644. q = apply_data_scope(q, BizCollectionProtocol, user, db, tenant_no)
  645. rows = q.order_by(BizCollectionProtocol.create_time.desc()).all()
  646. protocol_ids = [r.id for r, _ in rows]
  647. ft_map: Dict[str, Any] = {}
  648. if protocol_ids:
  649. from app.models.models import BizProtocolFullmoonTodo
  650. ft_rows = (
  651. db.query(BizProtocolFullmoonTodo)
  652. .filter(
  653. BizProtocolFullmoonTodo.collection_protocol_id.in_(protocol_ids),
  654. BizProtocolFullmoonTodo.tenant_no == tenant_no,
  655. BizProtocolFullmoonTodo.del_flag == 0,
  656. )
  657. .all()
  658. )
  659. for ft in ft_rows:
  660. ft_map[ft.collection_protocol_id] = ft
  661. now = datetime.now()
  662. _empty_ft: Dict[str, Any] = {
  663. "todoStatus": "0",
  664. "handleDate": "",
  665. "handleRemark": "",
  666. "insuranceAttachments": "",
  667. "insuranceCompanyId": "",
  668. "insuranceCompanyName": "",
  669. "insuranceType": "",
  670. "insurancePolicyNo": "",
  671. "insuranceEffectiveDate": "",
  672. "insuranceExpiryDate": "",
  673. "insuranceSubscribed": "0",
  674. "insuranceFee": None,
  675. }
  676. items: List[Dict[str, Any]] = []
  677. for proto, pc in rows:
  678. dt = pc.newborn_delivery_time if pc else None
  679. fullmoon_date_str = ""
  680. is_fullmoon_passed = False
  681. if dt:
  682. fullmoon_date = dt + timedelta(days=30)
  683. fullmoon_date_str = fullmoon_date.strftime("%Y-%m-%d")
  684. is_fullmoon_passed = fullmoon_date <= now
  685. ft = ft_map.get(proto.id)
  686. ts = (ft.todo_status or "0") if ft else "0"
  687. if todoStatus and todoStatus.strip() and ts != todoStatus.strip():
  688. continue
  689. ft_dict = cp_svc._fullmoon_todo_to_dict(ft) if ft else dict(_empty_ft)
  690. items.append(
  691. {
  692. "protocolId": proto.id,
  693. "id": proto.id,
  694. "protocolNo": proto.protocol_no or "",
  695. "protocolStatus": proto.protocol_status or "",
  696. "motherName": (pc.mother_name if pc else "") or "",
  697. "motherPhone": (pc.mother_phone if pc else "") or "",
  698. "newbornName": (pc.newborn_name if pc else "") or "",
  699. "newbornDeliveryTime": cp_svc._fmt_dt(dt) if dt else "",
  700. "fullmoonDate": fullmoon_date_str,
  701. "isFullmoonPassed": is_fullmoon_passed,
  702. **ft_dict,
  703. }
  704. )
  705. total = len(items)
  706. page_safe = max(1, page)
  707. page_size_safe = min(max(1, pageSize), 100)
  708. start = (page_safe - 1) * page_size_safe
  709. page_items = items[start : start + page_size_safe]
  710. tp = cp_svc.total_pages(total, page_size_safe)
  711. return success_response(
  712. {"list": page_items, "total": total, "page": page_safe, "pageSize": page_size_safe, "totalPages": tp}
  713. )
  714. class FullmoonTodoInsuranceBody(BaseModel):
  715. model_config = ConfigDict(populate_by_name=True)
  716. insurance_company_id: Optional[str] = Field(None, alias="insuranceCompanyId")
  717. insurance_company_name: Optional[str] = Field(None, alias="insuranceCompanyName")
  718. insurance_type: Optional[str] = Field(None, alias="insuranceType")
  719. insurance_policy_no: Optional[str] = Field(None, alias="insurancePolicyNo")
  720. insurance_effective_date: Optional[str] = Field(None, alias="insuranceEffectiveDate")
  721. insurance_expiry_date: Optional[str] = Field(None, alias="insuranceExpiryDate")
  722. insurance_subscribed: Optional[str] = Field(None, alias="insuranceSubscribed")
  723. insurance_fee: Optional[float] = Field(None, alias="insuranceFee")
  724. insurance_attachments: Optional[str] = Field(None, alias="insuranceAttachments")
  725. todo_status: Optional[str] = Field(None, alias="todoStatus")
  726. handle_date: Optional[str] = Field(None, alias="handleDate")
  727. handle_remark: Optional[str] = Field(None, alias="handleRemark")
  728. @router.put("/fullmoon-todos/{protocol_id}/insurance")
  729. async def update_fullmoon_todo_insurance(
  730. protocol_id: str,
  731. body: FullmoonTodoInsuranceBody,
  732. user: dict = Depends(require_admin_or_super_admin),
  733. db: Session = Depends(get_db),
  734. ):
  735. tenant_no = _get_tenant_no(db, user)
  736. user_id = _get_current_user_id(user)
  737. try:
  738. payload = body.model_dump(exclude_unset=True, by_alias=False)
  739. ft = cp_svc.upsert_fullmoon_todo(
  740. db,
  741. protocol_id,
  742. tenant_no,
  743. user_id,
  744. **payload,
  745. )
  746. return success_response(cp_svc._fullmoon_todo_to_dict(ft), message="更新成功")
  747. except ValueError as e:
  748. return error_response(400, str(e))