protocol_sample_collection.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. """采集协议样本采集信息 API"""
  2. from typing import List, Optional
  3. from fastapi import APIRouter, Depends, Query
  4. from pydantic import BaseModel, ConfigDict, Field
  5. from sqlalchemy.orm import Session
  6. from app.core.database import get_db
  7. from app.core.menu_guard import require_any_menu_code
  8. from app.core.response import error_response, success_response
  9. from app.core.utils import parse_date, parse_datetime
  10. from app.crud import protocol_sample_collection as svc
  11. from app.crud import sample_info_quick_register as quick_svc
  12. from app.crud.collection_protocol import total_pages
  13. from app.models.models import SysUser
  14. from app.services.sample_customer_service_register import has_any_customer_service_payload
  15. router = APIRouter(prefix="/web/admin", tags=["采集协议样本采集信息"])
  16. _SAMPLE_INFO_MENU = require_any_menu_code(
  17. "cell-storage:sample-info:list",
  18. )
  19. _QUICK_REGISTER_MENU = require_any_menu_code(
  20. "cell-storage:sample-info:list",
  21. "research-donation:sample-info:list",
  22. )
  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 _page_payload(items: list, total: int, page: int, page_size: int) -> dict:
  32. return {
  33. "list": items,
  34. "total": total,
  35. "page": page,
  36. "pageSize": page_size,
  37. "totalPages": total_pages(total, page_size),
  38. }
  39. @router.get("/protocol-sample-collections/list")
  40. async def list_protocol_sample_collections(
  41. page: int = Query(1, ge=1),
  42. pageSize: int = Query(10, ge=1, le=100),
  43. keyword: Optional[str] = None,
  44. sampleStatus: Optional[str] = Query(None, alias="sampleStatus"),
  45. collectionFlag: Optional[str] = Query(None, alias="collectionFlag"),
  46. receptionFlag: Optional[str] = Query(None, alias="receptionFlag"),
  47. qcFlag: Optional[str] = Query(None, alias="qcFlag"),
  48. storageFlag: Optional[str] = Query(None, alias="storageFlag"),
  49. storageCertHandled: Optional[str] = Query(None, alias="storageCertHandled"),
  50. insuranceHandled: Optional[str] = Query(None, alias="insuranceHandled"),
  51. db: Session = Depends(get_db),
  52. user: dict = Depends(_SAMPLE_INFO_MENU),
  53. ):
  54. try:
  55. tenant_no = _get_tenant_no(db, user)
  56. items, total = svc.list_protocol_sample_collections(
  57. db,
  58. page=page,
  59. page_size=pageSize,
  60. tenant_no=tenant_no,
  61. keyword=keyword,
  62. sample_status=sampleStatus,
  63. collection_flag=collectionFlag,
  64. reception_flag=receptionFlag,
  65. qc_flag=qcFlag,
  66. storage_flag=storageFlag,
  67. storage_cert_handled=storageCertHandled,
  68. insurance_handled=insuranceHandled,
  69. user_info=user,
  70. )
  71. return success_response(_page_payload(items, total, page, pageSize))
  72. except PermissionError as e:
  73. return error_response(403, str(e))
  74. except Exception as e:
  75. return error_response(400, str(e))
  76. def _get_current_user_id(user: dict) -> str:
  77. user_id = user.get("user_id")
  78. if not user_id:
  79. raise PermissionError("用户身份信息缺失")
  80. return str(user_id)
  81. class QuickRegisterItem(BaseModel):
  82. model_config = ConfigDict(populate_by_name=True)
  83. sample_code: str = Field(..., alias="sampleCode")
  84. protocol_id: str = Field(..., alias="protocolId")
  85. class QuickRegisterBody(BaseModel):
  86. model_config = ConfigDict(populate_by_name=True)
  87. kind: str
  88. reception_source: str = Field(..., alias="receptionSource")
  89. items: List[QuickRegisterItem]
  90. handle_time: Optional[str] = Field(None, alias="handleTime")
  91. handler_user_id: Optional[str] = Field(None, alias="handlerUserId")
  92. attachments: Optional[str] = None
  93. remark: Optional[str] = None
  94. mail_cert_time: Optional[str] = Field(None, alias="mailCertTime")
  95. policy_send_time: Optional[str] = Field(None, alias="policySendTime")
  96. storage_handle_time: Optional[str] = Field(None, alias="storageHandleTime")
  97. storage_handler_user_id: Optional[str] = Field(None, alias="storageHandlerUserId")
  98. storage_attachments: Optional[str] = Field(None, alias="storageAttachments")
  99. storage_remark: Optional[str] = Field(None, alias="storageRemark")
  100. cert_handle_time: Optional[str] = Field(None, alias="certHandleTime")
  101. cert_handler_user_id: Optional[str] = Field(None, alias="certHandlerUserId")
  102. cert_attachments: Optional[str] = Field(None, alias="certAttachments")
  103. cert_remark: Optional[str] = Field(None, alias="certRemark")
  104. insurance_handle_time: Optional[str] = Field(None, alias="insuranceHandleTime")
  105. insurance_handler_user_id: Optional[str] = Field(None, alias="insuranceHandlerUserId")
  106. insurance_attachments: Optional[str] = Field(None, alias="insuranceAttachments")
  107. insurance_remark: Optional[str] = Field(None, alias="insuranceRemark")
  108. sms_send_date: Optional[str] = Field(None, alias="smsSendDate")
  109. sms_send_status: Optional[str] = Field(None, alias="smsSendStatus")
  110. microbe_followup_date: Optional[str] = Field(None, alias="microbeFollowupDate")
  111. microbe_followup_status: Optional[str] = Field(None, alias="microbeFollowupStatus")
  112. fullmoon_followup_date: Optional[str] = Field(None, alias="fullmoonFollowupDate")
  113. fullmoon_followup_status: Optional[str] = Field(None, alias="fullmoonFollowupStatus")
  114. household_registered: Optional[str] = Field(None, alias="householdRegistered")
  115. einvoice_send_time: Optional[str] = Field(None, alias="einvoiceSendTime")
  116. effective_address: Optional[str] = Field(None, alias="effectiveAddress")
  117. def _optional_dt(raw: Optional[str]):
  118. if raw is None:
  119. return None, False
  120. text = str(raw).strip()
  121. if not text:
  122. return None, False
  123. return parse_datetime(text), True
  124. def _customer_service_incoming_from_body(body: QuickRegisterBody) -> dict:
  125. return {
  126. "sms_send_date": parse_date(body.sms_send_date) if body.sms_send_date else None,
  127. "sms_send_status": body.sms_send_status,
  128. "microbe_followup_date": parse_date(body.microbe_followup_date)
  129. if body.microbe_followup_date
  130. else None,
  131. "microbe_followup_status": body.microbe_followup_status,
  132. "fullmoon_followup_date": parse_date(body.fullmoon_followup_date)
  133. if body.fullmoon_followup_date
  134. else None,
  135. "fullmoon_followup_status": body.fullmoon_followup_status,
  136. "household_registered": body.household_registered,
  137. "einvoice_send_time": parse_datetime(body.einvoice_send_time)
  138. if body.einvoice_send_time
  139. else None,
  140. "effective_address": body.effective_address,
  141. }
  142. @router.post("/sample-info/quick-register")
  143. async def quick_register_sample_info(
  144. body: QuickRegisterBody,
  145. db: Session = Depends(get_db),
  146. user: dict = Depends(_QUICK_REGISTER_MENU),
  147. ):
  148. kind = (body.kind or "").strip()
  149. try:
  150. tenant_no = _get_tenant_no(db, user)
  151. user_id = _get_current_user_id(user)
  152. ht = parse_datetime(body.handle_time) if body.handle_time else None
  153. items = [
  154. {"sampleCode": it.sample_code, "protocolId": it.protocol_id} for it in (body.items or [])
  155. ]
  156. source = (body.reception_source or "").strip()
  157. attachments = body.attachments or ""
  158. remark = body.remark or ""
  159. mail_t, update_mail = _optional_dt(body.mail_cert_time)
  160. policy_t, update_policy = _optional_dt(body.policy_send_time)
  161. cs_incoming = _customer_service_incoming_from_body(body)
  162. if kind == "storage":
  163. if ht is None:
  164. return error_response(400, "请填写办理时间")
  165. result = quick_svc.batch_quick_register_storage(
  166. db,
  167. items=items,
  168. reception_source=source,
  169. tenant_no=tenant_no,
  170. user_id=user_id,
  171. handle_time=ht,
  172. handler_user_id=body.handler_user_id,
  173. attachments=attachments,
  174. remark=remark,
  175. )
  176. elif kind == "storage_cert":
  177. if source != "cell_storage":
  178. return error_response(400, "储存证仅支持细胞存储样本")
  179. if ht is None:
  180. return error_response(400, "请填写办理时间")
  181. result = quick_svc.batch_handle_storage_certs(
  182. db,
  183. items=items,
  184. tenant_no=tenant_no,
  185. user_id=user_id,
  186. handle_time=ht,
  187. handler_user_id=body.handler_user_id,
  188. attachments=attachments,
  189. remark=remark,
  190. mail_cert_time=mail_t,
  191. update_mail_cert_time=update_mail,
  192. )
  193. elif kind == "insurance":
  194. if source != "cell_storage":
  195. return error_response(400, "保险仅支持细胞存储样本")
  196. if ht is None:
  197. return error_response(400, "请填写办理时间")
  198. result = quick_svc.batch_handle_insurance(
  199. db,
  200. items=items,
  201. tenant_no=tenant_no,
  202. user_id=user_id,
  203. handle_time=ht,
  204. handler_user_id=body.handler_user_id,
  205. attachments=attachments,
  206. remark=remark,
  207. policy_send_time=policy_t,
  208. update_policy_send_time=update_policy,
  209. )
  210. elif kind in ("sms", "followup", "fulfillment"):
  211. if source != "cell_storage":
  212. return error_response(400, "客户服务登记仅支持细胞存储样本")
  213. result = quick_svc.batch_register_customer_service(
  214. db,
  215. items=items,
  216. tenant_no=tenant_no,
  217. user_id=user_id,
  218. incoming=cs_incoming,
  219. )
  220. elif kind == "all":
  221. if source != "cell_storage":
  222. return error_response(400, "登记全部仅支持细胞存储样本")
  223. split = any(
  224. value is not None
  225. for value in (
  226. body.storage_handle_time,
  227. body.storage_handler_user_id,
  228. body.storage_attachments,
  229. body.storage_remark,
  230. body.cert_handle_time,
  231. body.insurance_handle_time,
  232. body.cert_attachments,
  233. body.insurance_attachments,
  234. body.cert_remark,
  235. body.insurance_remark,
  236. body.cert_handler_user_id,
  237. body.insurance_handler_user_id,
  238. )
  239. )
  240. if split:
  241. storage_ht = (
  242. parse_datetime(body.storage_handle_time)
  243. if (body.storage_handle_time or "").strip()
  244. else None
  245. )
  246. storage_handler = body.storage_handler_user_id
  247. storage_atts = body.storage_attachments or ""
  248. storage_remark = body.storage_remark or ""
  249. cert_ht = (
  250. parse_datetime(body.cert_handle_time)
  251. if (body.cert_handle_time or "").strip()
  252. else None
  253. )
  254. ins_ht = (
  255. parse_datetime(body.insurance_handle_time)
  256. if (body.insurance_handle_time or "").strip()
  257. else None
  258. )
  259. cert_handler = body.cert_handler_user_id
  260. ins_handler = body.insurance_handler_user_id
  261. cert_atts = body.cert_attachments or ""
  262. ins_atts = body.insurance_attachments or ""
  263. cert_remark = body.cert_remark or ""
  264. ins_remark = body.insurance_remark or ""
  265. else:
  266. storage_ht = None
  267. storage_handler = None
  268. storage_atts = ""
  269. storage_remark = ""
  270. cert_ht = ins_ht = ht
  271. cert_handler = ins_handler = body.handler_user_id
  272. cert_atts = ins_atts = attachments
  273. cert_remark = ins_remark = remark
  274. storage_side = bool(
  275. storage_ht is not None
  276. or (storage_atts or "").strip()
  277. or (storage_remark or "").strip()
  278. )
  279. cert_side = bool(
  280. cert_ht is not None
  281. or update_mail
  282. or (cert_atts or "").strip()
  283. or (cert_remark or "").strip()
  284. )
  285. ins_side = bool(
  286. ins_ht is not None
  287. or update_policy
  288. or (ins_atts or "").strip()
  289. or (ins_remark or "").strip()
  290. )
  291. if storage_side and storage_ht is None:
  292. return error_response(400, "请填写入库办理时间")
  293. if cert_side and cert_ht is None:
  294. return error_response(400, "请填写储存证办理时间")
  295. if ins_side and ins_ht is None:
  296. return error_response(400, "请填写保险办理时间")
  297. wrote_any = False
  298. success = 0
  299. fail = 0
  300. if storage_ht is not None:
  301. storage_r = quick_svc.batch_quick_register_storage(
  302. db,
  303. items=items,
  304. reception_source=source,
  305. tenant_no=tenant_no,
  306. user_id=user_id,
  307. handle_time=storage_ht,
  308. handler_user_id=storage_handler,
  309. attachments=storage_atts,
  310. remark=storage_remark,
  311. do_commit=False,
  312. )
  313. success = max(success, storage_r.get("success", 0))
  314. fail = max(fail, storage_r.get("fail", 0))
  315. wrote_any = True
  316. if cert_ht is not None:
  317. cert_r = quick_svc.batch_handle_storage_certs(
  318. db,
  319. items=items,
  320. tenant_no=tenant_no,
  321. user_id=user_id,
  322. handle_time=cert_ht,
  323. handler_user_id=cert_handler,
  324. attachments=cert_atts,
  325. remark=cert_remark,
  326. mail_cert_time=mail_t,
  327. update_mail_cert_time=update_mail,
  328. do_commit=False,
  329. )
  330. success = max(success, cert_r.get("success", 0))
  331. fail = max(fail, cert_r.get("fail", 0))
  332. wrote_any = True
  333. if ins_ht is not None:
  334. ins_r = quick_svc.batch_handle_insurance(
  335. db,
  336. items=items,
  337. tenant_no=tenant_no,
  338. user_id=user_id,
  339. handle_time=ins_ht,
  340. handler_user_id=ins_handler,
  341. attachments=ins_atts,
  342. remark=ins_remark,
  343. policy_send_time=policy_t,
  344. update_policy_send_time=update_policy,
  345. do_commit=False,
  346. )
  347. success = max(success, ins_r.get("success", 0))
  348. fail = max(fail, ins_r.get("fail", 0))
  349. wrote_any = True
  350. if has_any_customer_service_payload(cs_incoming):
  351. cs_r = quick_svc.batch_register_customer_service(
  352. db,
  353. items=items,
  354. tenant_no=tenant_no,
  355. user_id=user_id,
  356. incoming=cs_incoming,
  357. do_commit=False,
  358. )
  359. success = max(success, cs_r.get("success", 0))
  360. fail = max(fail, cs_r.get("fail", 0))
  361. wrote_any = True
  362. if not wrote_any:
  363. return error_response(400, "请至少填写一项登记信息")
  364. db.commit()
  365. result = {"success": success, "fail": fail}
  366. else:
  367. return error_response(400, "登记类型无效")
  368. return success_response(result, message="登记完成")
  369. except PermissionError as e:
  370. db.rollback()
  371. return error_response(403, str(e))
  372. except ValueError as e:
  373. db.rollback()
  374. return error_response(400, str(e))
  375. except Exception as e:
  376. db.rollback()
  377. return error_response(400, str(e))