market_protocol.py 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375
  1. """移动市场协议服务:双来源统一展示,写入保持来源内原子性。"""
  2. from __future__ import annotations
  3. from datetime import datetime
  4. from typing import List, Optional, Tuple
  5. from fastapi import HTTPException
  6. from sqlalchemy import func, or_
  7. from sqlalchemy.orm import Session
  8. from app.core.utils import parse_datetime
  9. from app.crud import collection_protocol as cell_crud
  10. from app.crud import research_donation as donation_crud
  11. from app.models.models import (
  12. BizCellSampleType,
  13. BizCollectionHospital,
  14. BizCollectionProtocol,
  15. BizCollectionRegion,
  16. BizCollectionRegionStaff,
  17. BizCustomer,
  18. BizItemUnit,
  19. BizProtocolCollectionInfo,
  20. BizProtocolPartyCustomer,
  21. BizProtocolSample,
  22. BizProtocolSampleTransport,
  23. BizSampleCode,
  24. SysUser,
  25. )
  26. from app.models.research_donation import (
  27. BizResearchDonation,
  28. BizResearchDonationCollection,
  29. BizResearchDonationParty,
  30. BizResearchDonationSample,
  31. BizResearchDonationSampleTransport,
  32. )
  33. from app.schemas.market_mobile import MarketProtocolBody
  34. from app.services.market_field_scope import (
  35. MarketFieldContext,
  36. apply_cell_protocol_scope,
  37. apply_donation_scope,
  38. assert_cell_protocol_access,
  39. assert_donation_access,
  40. )
  41. from app.services.market_support import allowed_actions, validate_attachment_refs
  42. SOURCE_CELL = 'cell_storage'
  43. SOURCE_DONATION = 'research_donation'
  44. SOURCES = (SOURCE_CELL, SOURCE_DONATION)
  45. _CUSTOMER_LINK_FIELDS = (
  46. 'customer_id',
  47. 'father_customer_id',
  48. 'newborn_customer_id',
  49. )
  50. def _current_dept_id(user_info: dict) -> str:
  51. if not isinstance(user_info, dict):
  52. return ''
  53. return str(
  54. user_info.get('dept_id')
  55. or user_info.get('deptId')
  56. or user_info.get('region_id')
  57. or ''
  58. ).strip()
  59. def _dump(value) -> dict:
  60. if value is None:
  61. return {}
  62. if hasattr(value, 'model_dump'):
  63. return value.model_dump(by_alias=False, exclude_unset=True)
  64. return dict(value)
  65. def _assert_customer_link_policy(
  66. customer: dict, *, current_party=None, creating: bool
  67. ) -> None:
  68. """移动端不创建/改挂客户主档,只保留单据原有客户关联。"""
  69. for key in _CUSTOMER_LINK_FIELDS:
  70. if key not in customer:
  71. continue
  72. supplied = str(customer.get(key) or '').strip()
  73. if creating:
  74. if supplied:
  75. raise ValueError('移动端创建协议不允许指定已有客户')
  76. continue
  77. current = str(getattr(current_party, key, None) or '').strip()
  78. if supplied != current:
  79. raise ValueError('客户关联不属于当前协议,禁止改挂')
  80. def _fmt_dt(value) -> str:
  81. if value is None:
  82. return ''
  83. if isinstance(value, str):
  84. return value
  85. return value.strftime('%Y-%m-%d %H:%M:%S')
  86. def _manager_assignment_allowed(
  87. db: Session,
  88. ctx: MarketFieldContext,
  89. *,
  90. region_id: Optional[str],
  91. region_manager_user_id: Optional[str],
  92. ) -> bool:
  93. if str(region_manager_user_id or '').strip() == ctx.user_id:
  94. return True
  95. region = str(region_id or '').strip()
  96. if not region:
  97. return False
  98. return (
  99. db.query(BizCollectionRegionStaff.id)
  100. .filter(
  101. BizCollectionRegionStaff.tenant_no == ctx.tenant_no,
  102. BizCollectionRegionStaff.del_flag == 0,
  103. BizCollectionRegionStaff.user_id == ctx.user_id,
  104. BizCollectionRegionStaff.is_leader == 1,
  105. BizCollectionRegionStaff.region_id == region,
  106. )
  107. .first()
  108. is not None
  109. )
  110. def _ensure_manager_assignment(
  111. db: Session,
  112. ctx: MarketFieldContext,
  113. *,
  114. region_id: Optional[str],
  115. region_manager_user_id: Optional[str],
  116. ) -> None:
  117. if not _manager_assignment_allowed(
  118. db,
  119. ctx,
  120. region_id=region_id,
  121. region_manager_user_id=region_manager_user_id,
  122. ):
  123. raise ValueError('协议归属不在当前地区经理范围内')
  124. def _active_user_ids(db: Session, ctx: MarketFieldContext, ids: set) -> set:
  125. if not ids:
  126. return set()
  127. return {
  128. str(row[0])
  129. for row in db.query(SysUser.id)
  130. .filter(
  131. SysUser.id.in_(ids),
  132. SysUser.tenant_no == ctx.tenant_no,
  133. SysUser.del_flag == 0,
  134. SysUser.status == '1',
  135. )
  136. .all()
  137. }
  138. def _validate_references(
  139. db: Session,
  140. ctx: MarketFieldContext,
  141. *,
  142. customer: dict,
  143. collection: dict,
  144. samples: List[dict],
  145. extra_user_ids: Optional[set] = None,
  146. ) -> None:
  147. region_id = str(collection.get('region_id') or '').strip()
  148. hospital_id = str(collection.get('hospital_id') or '').strip()
  149. if region_id:
  150. exists = (
  151. db.query(BizCollectionRegion.id)
  152. .filter(
  153. BizCollectionRegion.id == region_id,
  154. BizCollectionRegion.tenant_no == ctx.tenant_no,
  155. BizCollectionRegion.del_flag == 0,
  156. )
  157. .first()
  158. )
  159. if not exists:
  160. raise ValueError('采集地区不存在或不属于当前租户')
  161. if hospital_id:
  162. exists = (
  163. db.query(BizCollectionHospital.id)
  164. .filter(
  165. BizCollectionHospital.id == hospital_id,
  166. BizCollectionHospital.region_id == region_id,
  167. BizCollectionHospital.tenant_no == ctx.tenant_no,
  168. BizCollectionHospital.del_flag == 0,
  169. )
  170. .first()
  171. )
  172. if not exists:
  173. raise ValueError('医院不存在、不属于当前租户或与采集地区不匹配')
  174. user_ids = {
  175. str(value).strip()
  176. for value in (
  177. customer.get('collector_user_id'),
  178. collection.get('sales_user_id'),
  179. collection.get('region_manager_user_id'),
  180. )
  181. if str(value or '').strip()
  182. }
  183. user_ids.update(
  184. str(value).strip()
  185. for value in (extra_user_ids or set())
  186. if str(value or '').strip()
  187. )
  188. if _active_user_ids(db, ctx, user_ids) != user_ids:
  189. raise ValueError('引用用户不存在、已停用或不属于当前租户')
  190. customer_ids = {
  191. str(customer.get(key) or '').strip()
  192. for key in ('customer_id', 'father_customer_id', 'newborn_customer_id')
  193. if str(customer.get(key) or '').strip()
  194. }
  195. if customer_ids:
  196. existing = {
  197. str(row[0])
  198. for row in db.query(BizCustomer.id)
  199. .filter(
  200. BizCustomer.id.in_(customer_ids),
  201. BizCustomer.tenant_no == ctx.tenant_no,
  202. BizCustomer.del_flag == 0,
  203. )
  204. .all()
  205. }
  206. if existing != customer_ids:
  207. raise ValueError('客户不存在或不属于当前租户')
  208. type_ids = {
  209. str(item.get('sample_type_id') or '').strip()
  210. for item in samples
  211. if str(item.get('sample_type_id') or '').strip()
  212. }
  213. if type_ids:
  214. existing = {
  215. str(row[0])
  216. for row in db.query(BizCellSampleType.id)
  217. .filter(
  218. BizCellSampleType.id.in_(type_ids),
  219. BizCellSampleType.tenant_no == ctx.tenant_no,
  220. BizCellSampleType.del_flag == 0,
  221. )
  222. .all()
  223. }
  224. if existing != type_ids:
  225. raise ValueError('样本类型不存在或不属于当前租户')
  226. unit_ids = {
  227. str(item.get('unit_id') or '').strip()
  228. for item in samples
  229. if str(item.get('unit_id') or '').strip()
  230. }
  231. if unit_ids:
  232. existing = {
  233. str(row[0])
  234. for row in db.query(BizItemUnit.id)
  235. .filter(
  236. BizItemUnit.id.in_(unit_ids),
  237. BizItemUnit.tenant_no == ctx.tenant_no,
  238. BizItemUnit.del_flag == 0,
  239. )
  240. .all()
  241. }
  242. if existing != unit_ids:
  243. raise ValueError('计量单位不存在或不属于当前租户')
  244. sample_code_ids = {
  245. str(item.get('sample_code_id') or '').strip()
  246. for item in samples
  247. if str(item.get('sample_code_id') or '').strip()
  248. }
  249. sample_code_map = {}
  250. if sample_code_ids:
  251. sample_code_map = {
  252. str(row.id): str(row.sample_code or '').strip()
  253. for row in db.query(BizSampleCode)
  254. .filter(
  255. BizSampleCode.id.in_(sample_code_ids),
  256. BizSampleCode.tenant_no == ctx.tenant_no,
  257. BizSampleCode.del_flag == 0,
  258. )
  259. .all()
  260. }
  261. if set(sample_code_map) != sample_code_ids:
  262. raise ValueError('样本编码不存在、已删除或不属于当前租户')
  263. for item in samples:
  264. sample_code_id = str(item.get('sample_code_id') or '').strip()
  265. if not sample_code_id:
  266. continue
  267. expected_code = sample_code_map[sample_code_id]
  268. supplied_code = str(item.get('sample_code') or '').strip()
  269. if supplied_code and supplied_code != expected_code:
  270. raise ValueError('样本编码ID与样本编码不一致')
  271. item['sample_code'] = expected_code
  272. def _normalize_write(
  273. db: Session,
  274. *,
  275. body: MarketProtocolBody,
  276. ctx: MarketFieldContext,
  277. current_collection=None,
  278. ) -> Tuple[dict, dict, List[dict], dict]:
  279. customer = _dump(body.customer)
  280. collection = _dump(body.collection)
  281. samples = [_dump(item) for item in (body.samples or [])]
  282. attachments = _dump(body.attachments)
  283. effective_collection = {
  284. key: getattr(current_collection, key, None)
  285. for key in (
  286. 'region_id',
  287. 'hospital_id',
  288. 'sales_user_id',
  289. 'region_manager_user_id',
  290. )
  291. }
  292. effective_collection.update(collection)
  293. if ctx.scope_kind == 'specialist':
  294. customer['collector_user_id'] = ctx.user_id
  295. collection['sales_user_id'] = ctx.user_id
  296. effective_collection['sales_user_id'] = ctx.user_id
  297. else:
  298. _ensure_manager_assignment(
  299. db,
  300. ctx,
  301. region_id=effective_collection.get('region_id'),
  302. region_manager_user_id=effective_collection.get(
  303. 'region_manager_user_id'
  304. ),
  305. )
  306. for key in ('sample_collect_time', 'maternal_blood_collect_time'):
  307. if key in collection and isinstance(collection[key], str):
  308. collection[key] = parse_datetime(collection[key])
  309. if 'newborn_delivery_time' in customer and isinstance(
  310. customer['newborn_delivery_time'], str
  311. ):
  312. customer['newborn_delivery_time'] = parse_datetime(
  313. customer['newborn_delivery_time']
  314. )
  315. _validate_references(
  316. db,
  317. ctx,
  318. customer=customer,
  319. collection=effective_collection,
  320. samples=samples,
  321. extra_user_ids={body.collector_user_id}
  322. if ctx.scope_kind == 'manager' and body.collector_user_id
  323. else set(),
  324. )
  325. return customer, collection, samples, attachments
  326. def _validate_mobile_attachments(
  327. db: Session,
  328. attachments: dict,
  329. *,
  330. ctx: MarketFieldContext,
  331. creating: bool,
  332. existing: Optional[dict] = None,
  333. business_id: Optional[str] = None,
  334. ) -> dict:
  335. current = existing or {}
  336. normalized = dict(attachments)
  337. for key, refs in attachments.items():
  338. if refs is None:
  339. continue
  340. normalized[key] = validate_attachment_refs(
  341. db,
  342. refs,
  343. module='protocol',
  344. ctx=ctx,
  345. creating=creating,
  346. existing_refs=current.get(key),
  347. business_id=business_id,
  348. )
  349. return normalized
  350. def _party_name_cell(db: Session, ids: List[str], tenant_no: str) -> dict:
  351. if not ids:
  352. return {}
  353. rows = (
  354. db.query(BizProtocolPartyCustomer)
  355. .filter(
  356. BizProtocolPartyCustomer.collection_protocol_id.in_(ids),
  357. BizProtocolPartyCustomer.tenant_no == tenant_no,
  358. BizProtocolPartyCustomer.del_flag == 0,
  359. )
  360. .all()
  361. )
  362. return {row.collection_protocol_id: row.mother_name or '' for row in rows}
  363. def _party_name_donation(db: Session, ids: List[str], tenant_no: str) -> dict:
  364. if not ids:
  365. return {}
  366. rows = (
  367. db.query(BizResearchDonationParty)
  368. .filter(
  369. BizResearchDonationParty.research_donation_id.in_(ids),
  370. BizResearchDonationParty.tenant_no == tenant_no,
  371. BizResearchDonationParty.del_flag == 0,
  372. )
  373. .all()
  374. )
  375. return {row.research_donation_id: row.mother_name or '' for row in rows}
  376. def _enrich_protocol_cards(
  377. db: Session, items: List[dict], tenant_no: str
  378. ) -> None:
  379. """批量补齐与 Web 列表一致的移动卡片字段,避免逐行查询。"""
  380. cell_ids = [item['id'] for item in items if item['source'] == SOURCE_CELL]
  381. donation_ids = [
  382. item['id'] for item in items if item['source'] == SOURCE_DONATION
  383. ]
  384. collection_map = {}
  385. sample_map = {}
  386. party_map = {}
  387. if cell_ids:
  388. for row in db.query(BizProtocolCollectionInfo).filter(
  389. BizProtocolCollectionInfo.collection_protocol_id.in_(cell_ids),
  390. BizProtocolCollectionInfo.tenant_no == tenant_no,
  391. BizProtocolCollectionInfo.del_flag == 0,
  392. ).order_by(BizProtocolCollectionInfo.create_time.desc()).all():
  393. collection_map.setdefault((SOURCE_CELL, row.collection_protocol_id), row)
  394. for row in db.query(BizProtocolSample).filter(
  395. BizProtocolSample.collection_protocol_id.in_(cell_ids),
  396. BizProtocolSample.tenant_no == tenant_no,
  397. BizProtocolSample.del_flag == 0,
  398. ).order_by(BizProtocolSample.create_time.asc()).all():
  399. sample_map.setdefault((SOURCE_CELL, row.collection_protocol_id), row)
  400. for row in db.query(BizProtocolPartyCustomer).filter(
  401. BizProtocolPartyCustomer.collection_protocol_id.in_(cell_ids),
  402. BizProtocolPartyCustomer.tenant_no == tenant_no,
  403. BizProtocolPartyCustomer.del_flag == 0,
  404. ).order_by(BizProtocolPartyCustomer.create_time.desc()).all():
  405. party_map.setdefault((SOURCE_CELL, row.collection_protocol_id), row)
  406. if donation_ids:
  407. for row in db.query(BizResearchDonationCollection).filter(
  408. BizResearchDonationCollection.research_donation_id.in_(donation_ids),
  409. BizResearchDonationCollection.tenant_no == tenant_no,
  410. BizResearchDonationCollection.del_flag == 0,
  411. ).order_by(BizResearchDonationCollection.create_time.desc()).all():
  412. collection_map.setdefault((SOURCE_DONATION, row.research_donation_id), row)
  413. for row in db.query(BizResearchDonationSample).filter(
  414. BizResearchDonationSample.research_donation_id.in_(donation_ids),
  415. BizResearchDonationSample.tenant_no == tenant_no,
  416. BizResearchDonationSample.del_flag == 0,
  417. ).order_by(BizResearchDonationSample.create_time.asc()).all():
  418. sample_map.setdefault((SOURCE_DONATION, row.research_donation_id), row)
  419. for row in db.query(BizResearchDonationParty).filter(
  420. BizResearchDonationParty.research_donation_id.in_(donation_ids),
  421. BizResearchDonationParty.tenant_no == tenant_no,
  422. BizResearchDonationParty.del_flag == 0,
  423. ).order_by(BizResearchDonationParty.create_time.desc()).all():
  424. party_map.setdefault((SOURCE_DONATION, row.research_donation_id), row)
  425. region_ids = {
  426. row.region_id for row in collection_map.values() if row.region_id
  427. }
  428. hospital_ids = {
  429. row.hospital_id for row in collection_map.values() if row.hospital_id
  430. }
  431. user_ids = {
  432. value
  433. for row in collection_map.values()
  434. for value in (row.sales_user_id, row.region_manager_user_id)
  435. if value
  436. }
  437. user_ids.update(
  438. item.get('collectorUserId')
  439. for item in items
  440. if item.get('collectorUserId')
  441. )
  442. type_ids = {
  443. row.sample_type_id for row in sample_map.values() if row.sample_type_id
  444. }
  445. region_names = {
  446. row.id: row.region_name or ''
  447. for row in db.query(BizCollectionRegion).filter(
  448. BizCollectionRegion.id.in_(region_ids or ['']),
  449. BizCollectionRegion.tenant_no == tenant_no,
  450. BizCollectionRegion.del_flag == 0,
  451. )
  452. }
  453. hospital_names = {
  454. row.id: row.hospital_name or ''
  455. for row in db.query(BizCollectionHospital).filter(
  456. BizCollectionHospital.id.in_(hospital_ids or ['']),
  457. BizCollectionHospital.tenant_no == tenant_no,
  458. BizCollectionHospital.del_flag == 0,
  459. )
  460. }
  461. user_names = {
  462. row.id: row.nick_name or ''
  463. for row in db.query(SysUser).filter(
  464. SysUser.id.in_(user_ids or ['']),
  465. SysUser.tenant_no == tenant_no,
  466. )
  467. }
  468. type_names = {
  469. row.id: row.type_name or ''
  470. for row in db.query(BizCellSampleType).filter(
  471. BizCellSampleType.id.in_(type_ids or ['']),
  472. BizCellSampleType.del_flag == 0,
  473. or_(
  474. BizCellSampleType.tenant_no == tenant_no,
  475. BizCellSampleType.tenant_no == '',
  476. ),
  477. )
  478. }
  479. sample_ids = [row.id for row in sample_map.values()]
  480. transport_by_sample = {}
  481. if sample_ids:
  482. for row in db.query(BizProtocolSampleTransport).filter(
  483. BizProtocolSampleTransport.sample_id.in_(sample_ids),
  484. BizProtocolSampleTransport.tenant_no == tenant_no,
  485. BizProtocolSampleTransport.del_flag == 0,
  486. ).all():
  487. transport_by_sample.setdefault(row.sample_id, row)
  488. for row in db.query(BizResearchDonationSampleTransport).filter(
  489. BizResearchDonationSampleTransport.sample_id.in_(sample_ids),
  490. BizResearchDonationSampleTransport.tenant_no == tenant_no,
  491. BizResearchDonationSampleTransport.del_flag == 0,
  492. ).all():
  493. transport_by_sample.setdefault(row.sample_id, row)
  494. lab_by_key = {}
  495. from app.crud import sample_reception as reception_crud
  496. for source in SOURCES:
  497. codes = [
  498. row.sample_code
  499. for (item_source, _), row in sample_map.items()
  500. if item_source == source and row.sample_code
  501. ]
  502. for code, lab_code in reception_crud.get_lab_storage_code_map_by_sample_codes(
  503. db, tenant_no, codes, reception_source=source
  504. ).items():
  505. lab_by_key[(source, code)] = lab_code
  506. payment_summaries = {}
  507. if cell_ids:
  508. from app.services.qc_work_order_fee_summary import (
  509. build_protocol_payment_summaries,
  510. )
  511. payment_summaries = build_protocol_payment_summaries(
  512. db, cell_ids, tenant_no
  513. )
  514. transport_labels = {'kdys': '快递运输', 'ryxd': '人员携带'}
  515. for item in items:
  516. key = (item['source'], item['id'])
  517. collection = collection_map.get(key)
  518. sample = sample_map.get(key)
  519. party = party_map.get(key)
  520. payment_summary = payment_summaries.get(item['id']) or {}
  521. transport = transport_by_sample.get(getattr(sample, 'id', ''))
  522. sample_code = getattr(sample, 'sample_code', '') or ''
  523. region_manager_name = user_names.get(
  524. getattr(collection, 'region_manager_user_id', ''), ''
  525. )
  526. item.update(
  527. motherName=item.get('customerName', ''),
  528. motherPhone=getattr(party, 'mother_phone', '') or '',
  529. motherIdCard=getattr(party, 'mother_id_card', '') or '',
  530. fatherName=getattr(party, 'father_name', '') or '',
  531. newbornSex=getattr(party, 'newborn_sex', '') or '',
  532. deliveryMode=getattr(party, 'delivery_mode', '') or '',
  533. newbornWeightGram=getattr(party, 'newborn_weight_gram', None),
  534. birthOrder=getattr(party, 'birth_order', None),
  535. newbornDeliveryTime=_fmt_dt(
  536. getattr(party, 'newborn_delivery_time', None)
  537. ),
  538. protocolStatus=item.get('status', ''),
  539. donationStatus=item.get('status', ''),
  540. regionName=region_names.get(getattr(collection, 'region_id', ''), ''),
  541. hospitalName=hospital_names.get(
  542. getattr(collection, 'hospital_id', ''), ''
  543. ),
  544. sampleCollectTime=_fmt_dt(
  545. getattr(collection, 'sample_collect_time', None)
  546. ),
  547. maternalBloodCollectTime=_fmt_dt(
  548. getattr(collection, 'maternal_blood_collect_time', None)
  549. ),
  550. salesUserName=user_names.get(
  551. getattr(collection, 'sales_user_id', ''), ''
  552. ),
  553. collectorUserName=user_names.get(item.get('collectorUserId', ''), ''),
  554. managerName=region_manager_name,
  555. regionManagerUserName=region_manager_name,
  556. sampleCode=sample_code,
  557. sampleTypeName=type_names.get(
  558. getattr(sample, 'sample_type_id', ''), ''
  559. ),
  560. coStored=bool(getattr(sample, 'is_special', 0)),
  561. labStorageCode=lab_by_key.get((item['source'], sample_code), ''),
  562. payMode=payment_summary.get('payMode', ''),
  563. firstPayTime=payment_summary.get('firstPayTransferTime', ''),
  564. transportMode=getattr(transport, 'transport_type', '') or '',
  565. transportModeLabel=transport_labels.get(
  566. getattr(transport, 'transport_type', '') or '', ''
  567. ),
  568. )
  569. def list_protocols(
  570. db: Session,
  571. *,
  572. ctx: MarketFieldContext,
  573. user_info: dict,
  574. page: int = 1,
  575. page_size: int = 10,
  576. keyword: Optional[str] = None,
  577. source: Optional[str] = None,
  578. ) -> Tuple[List[dict], int]:
  579. if source and source not in SOURCES:
  580. raise ValueError('不支持的协议来源')
  581. search = str(keyword or '').strip()
  582. rows = []
  583. fetch_limit = max(1, page) * min(max(1, page_size), 100)
  584. total = 0
  585. if source in (None, SOURCE_CELL):
  586. query = apply_cell_protocol_scope(
  587. db.query(BizCollectionProtocol), db, ctx, user_info=user_info
  588. )
  589. if search:
  590. like = f'%{search}%'
  591. party_ids = db.query(
  592. BizProtocolPartyCustomer.collection_protocol_id
  593. ).filter(
  594. BizProtocolPartyCustomer.tenant_no == ctx.tenant_no,
  595. BizProtocolPartyCustomer.del_flag == 0,
  596. BizProtocolPartyCustomer.mother_name.like(like),
  597. )
  598. sample_ids = db.query(BizProtocolSample.collection_protocol_id).filter(
  599. BizProtocolSample.tenant_no == ctx.tenant_no,
  600. BizProtocolSample.del_flag == 0,
  601. BizProtocolSample.sample_code.like(like),
  602. )
  603. query = query.filter(
  604. or_(
  605. BizCollectionProtocol.protocol_no.like(like),
  606. BizCollectionProtocol.id.in_(party_ids),
  607. BizCollectionProtocol.id.in_(sample_ids),
  608. )
  609. )
  610. total += int(
  611. query.order_by(None)
  612. .with_entities(func.count(BizCollectionProtocol.id))
  613. .scalar()
  614. or 0
  615. )
  616. cell_rows = (
  617. query.order_by(
  618. BizCollectionProtocol.create_time.desc(),
  619. BizCollectionProtocol.id.desc(),
  620. )
  621. .limit(fetch_limit)
  622. .all()
  623. )
  624. names = _party_name_cell(
  625. db, [row.id for row in cell_rows], ctx.tenant_no
  626. )
  627. rows.extend(
  628. {
  629. 'id': row.id,
  630. 'source': SOURCE_CELL,
  631. 'code': row.protocol_no or '',
  632. 'protocolNo': row.protocol_no or '',
  633. 'status': row.protocol_status or '',
  634. 'collectDate': row.register_date or '',
  635. 'registerDate': row.register_date or '',
  636. 'protocolTotalAmount': str(row.protocol_total_amount or ''),
  637. 'collectorUserId': row.collector_user_id or '',
  638. 'customerName': names.get(row.id, ''),
  639. 'createTime': _fmt_dt(row.create_time),
  640. '_created': row.create_time or datetime.min,
  641. }
  642. for row in cell_rows
  643. )
  644. if source in (None, SOURCE_DONATION):
  645. query = apply_donation_scope(
  646. db.query(BizResearchDonation), db, ctx, user_info=user_info
  647. )
  648. if search:
  649. like = f'%{search}%'
  650. party_ids = db.query(
  651. BizResearchDonationParty.research_donation_id
  652. ).filter(
  653. BizResearchDonationParty.tenant_no == ctx.tenant_no,
  654. BizResearchDonationParty.del_flag == 0,
  655. BizResearchDonationParty.mother_name.like(like),
  656. )
  657. sample_ids = db.query(
  658. BizResearchDonationSample.research_donation_id
  659. ).filter(
  660. BizResearchDonationSample.tenant_no == ctx.tenant_no,
  661. BizResearchDonationSample.del_flag == 0,
  662. BizResearchDonationSample.sample_code.like(like),
  663. )
  664. query = query.filter(
  665. or_(
  666. BizResearchDonation.donation_no.like(like),
  667. BizResearchDonation.id.in_(party_ids),
  668. BizResearchDonation.id.in_(sample_ids),
  669. )
  670. )
  671. total += int(
  672. query.order_by(None)
  673. .with_entities(func.count(BizResearchDonation.id))
  674. .scalar()
  675. or 0
  676. )
  677. donation_rows = (
  678. query.order_by(
  679. BizResearchDonation.create_time.desc(),
  680. BizResearchDonation.id.desc(),
  681. )
  682. .limit(fetch_limit)
  683. .all()
  684. )
  685. names = _party_name_donation(
  686. db, [row.id for row in donation_rows], ctx.tenant_no
  687. )
  688. rows.extend(
  689. {
  690. 'id': row.id,
  691. 'source': SOURCE_DONATION,
  692. 'code': row.donation_no or '',
  693. 'protocolNo': row.donation_no or '',
  694. 'donationNo': row.donation_no or '',
  695. 'status': row.donation_status or '',
  696. 'collectDate': row.donation_date or '',
  697. 'donationDate': row.donation_date or '',
  698. 'customerName': names.get(row.id, ''),
  699. 'collectorUserId': row.collector_user_id or '',
  700. 'createTime': _fmt_dt(row.create_time),
  701. 'monthlyVerifyNo': row.monthly_verify_no or '',
  702. 'voidDesc': row.void_desc or '',
  703. 'consentFormUrls': row.consent_form_urls or '',
  704. 'infectiousDiseaseReportUrls': row.infectious_disease_report_urls or '',
  705. 'attachmentUrls': row.attachment_urls or '',
  706. 'remark': row.remark or '',
  707. '_created': row.create_time or datetime.min,
  708. }
  709. for row in donation_rows
  710. )
  711. rows.sort(
  712. key=lambda item: (item['_created'], item['id']), reverse=True
  713. )
  714. safe_page = max(1, page)
  715. safe_size = min(max(1, page_size), 100)
  716. page_rows = rows[(safe_page - 1) * safe_size : safe_page * safe_size]
  717. for item in page_rows:
  718. item.pop('_created', None)
  719. _enrich_protocol_cards(db, page_rows, ctx.tenant_no)
  720. return page_rows, total
  721. def _attach_sample_eta(
  722. sample_dicts: List[dict],
  723. transport_by_sample_id: dict,
  724. ) -> List[dict]:
  725. for item in sample_dicts:
  726. transport = transport_by_sample_id.get(str(item.get('id') or ''))
  727. eta = ''
  728. if transport is not None:
  729. eta = cell_crud._fmt_dt(getattr(transport, 'eta_time', None))
  730. item['etaTime'] = eta
  731. item['transport'] = {'etaTime': eta} if eta else None
  732. return sample_dicts
  733. def _cell_detail(db: Session, row: BizCollectionProtocol, tenant_no: str) -> dict:
  734. party = cell_crud.get_party_customer(db, row.id, tenant_no)
  735. collection = cell_crud.get_collection_info(db, row.id, tenant_no)
  736. samples = cell_crud.list_samples(db, row.id, tenant_no)
  737. payment = cell_crud.get_payment_by_protocol_id(db, row.id, tenant_no)
  738. transports = cell_crud.list_sample_transports(db, row.id, tenant_no)
  739. transport_by_sample_id = {str(t.sample_id): t for t in transports}
  740. detail = {
  741. 'source': SOURCE_CELL,
  742. 'basic': cell_crud._protocol_to_dict(row),
  743. 'collection': cell_crud._collection_info_to_dict(collection)
  744. if collection
  745. else None,
  746. 'customer': cell_crud._party_customer_to_dict(party) if party else None,
  747. 'samples': _attach_sample_eta(
  748. [cell_crud._sample_to_dict(item) for item in samples],
  749. transport_by_sample_id,
  750. ),
  751. 'payment': cell_crud._payment_to_dict(payment) if payment else None,
  752. 'attachments': {
  753. 'protocolAttachments': row.protocol_attachments or '',
  754. 'consentFormUrls': row.consent_form_urls or '',
  755. 'healthSurveyFormUrls': row.health_survey_form_urls or '',
  756. },
  757. }
  758. _enrich_protocol_detail_labels(db, detail, tenant_no)
  759. return detail
  760. def _donation_detail(
  761. db: Session, row: BizResearchDonation, tenant_no: str
  762. ) -> dict:
  763. party = donation_crud.get_party(db, row.id, tenant_no)
  764. collection = donation_crud.get_collection(db, row.id, tenant_no)
  765. samples = donation_crud.list_samples(db, row.id, tenant_no)
  766. transports = donation_crud.list_sample_transports(db, row.id, tenant_no)
  767. transport_by_sample_id = {str(t.sample_id): t for t in transports}
  768. detail = {
  769. 'source': SOURCE_DONATION,
  770. 'basic': donation_crud._donation_to_dict(row),
  771. 'collection': donation_crud._collection_to_dict(collection)
  772. if collection
  773. else None,
  774. 'customer': donation_crud._party_to_dict(party) if party else None,
  775. 'samples': _attach_sample_eta(
  776. [donation_crud._sample_to_dict(item) for item in samples],
  777. transport_by_sample_id,
  778. ),
  779. 'attachments': {
  780. 'consentFormUrls': row.consent_form_urls or '',
  781. 'attachmentUrls': row.attachment_urls or '',
  782. 'infectiousDiseaseReportUrls': row.infectious_disease_report_urls
  783. or '',
  784. },
  785. }
  786. _enrich_protocol_detail_labels(db, detail, tenant_no)
  787. return detail
  788. def _enrich_protocol_detail_labels(
  789. db: Session, detail: dict, tenant_no: str
  790. ) -> None:
  791. """补齐 Web 详情使用的主数据名称,移动端不直接展示内部 ID。"""
  792. basic = detail.get('basic') or {}
  793. collection = detail.get('collection') or {}
  794. samples = detail.get('samples') or []
  795. region_id = str(collection.get('regionId') or '').strip()
  796. hospital_id = str(collection.get('hospitalId') or '').strip()
  797. if region_id:
  798. region = (
  799. db.query(BizCollectionRegion)
  800. .filter(
  801. BizCollectionRegion.id == region_id,
  802. BizCollectionRegion.tenant_no == tenant_no,
  803. )
  804. .first()
  805. )
  806. collection['regionName'] = region.region_name if region else ''
  807. if hospital_id:
  808. hospital = (
  809. db.query(BizCollectionHospital)
  810. .filter(
  811. BizCollectionHospital.id == hospital_id,
  812. BizCollectionHospital.tenant_no == tenant_no,
  813. )
  814. .first()
  815. )
  816. collection['hospitalName'] = hospital.hospital_name if hospital else ''
  817. user_ids = {
  818. str(value or '').strip()
  819. for value in (
  820. basic.get('collectorUserId'),
  821. collection.get('salesUserId'),
  822. collection.get('regionManagerUserId'),
  823. )
  824. if str(value or '').strip()
  825. }
  826. user_names = {
  827. row.id: row.nick_name or ''
  828. for row in db.query(SysUser).filter(
  829. SysUser.id.in_(user_ids or ['']),
  830. SysUser.tenant_no == tenant_no,
  831. )
  832. }
  833. basic['collectorUserName'] = user_names.get(
  834. str(basic.get('collectorUserId') or ''), ''
  835. )
  836. collection['salesUserName'] = user_names.get(
  837. str(collection.get('salesUserId') or ''), ''
  838. )
  839. collection['regionManagerUserName'] = user_names.get(
  840. str(collection.get('regionManagerUserId') or ''), ''
  841. )
  842. type_ids = {
  843. str(item.get('sampleTypeId') or '').strip()
  844. for item in samples
  845. if str(item.get('sampleTypeId') or '').strip()
  846. }
  847. type_names = {
  848. row.id: row.type_name or ''
  849. for row in db.query(BizCellSampleType).filter(
  850. BizCellSampleType.id.in_(type_ids or ['']),
  851. or_(
  852. BizCellSampleType.tenant_no == tenant_no,
  853. BizCellSampleType.tenant_no == '',
  854. ),
  855. )
  856. }
  857. unit_ids = {
  858. str(item.get('unitId') or '').strip()
  859. for item in samples
  860. if str(item.get('unitId') or '').strip()
  861. }
  862. unit_names = {
  863. row.id: row.unit_name or ''
  864. for row in db.query(BizItemUnit).filter(
  865. BizItemUnit.id.in_(unit_ids or ['']),
  866. BizItemUnit.tenant_no == tenant_no,
  867. )
  868. }
  869. for item in samples:
  870. item['sampleTypeName'] = type_names.get(
  871. str(item.get('sampleTypeId') or ''), ''
  872. )
  873. item['unitName'] = unit_names.get(str(item.get('unitId') or ''), '')
  874. def get_protocol(
  875. db: Session,
  876. *,
  877. source: Optional[str],
  878. protocol_id: str,
  879. ctx: MarketFieldContext,
  880. user_info: dict,
  881. ) -> dict:
  882. if source == SOURCE_CELL:
  883. row = assert_cell_protocol_access(
  884. db, protocol_id, ctx, user_info=user_info
  885. )
  886. return _cell_detail(db, row, ctx.tenant_no)
  887. if source == SOURCE_DONATION:
  888. row = assert_donation_access(db, protocol_id, ctx, user_info=user_info)
  889. return _donation_detail(db, row, ctx.tenant_no)
  890. if source is None:
  891. cell = (
  892. apply_cell_protocol_scope(
  893. db.query(BizCollectionProtocol), db, ctx, user_info=user_info
  894. )
  895. .filter(BizCollectionProtocol.id == protocol_id)
  896. .first()
  897. )
  898. if cell is not None:
  899. return _cell_detail(db, cell, ctx.tenant_no)
  900. donation = (
  901. apply_donation_scope(
  902. db.query(BizResearchDonation), db, ctx, user_info=user_info
  903. )
  904. .filter(BizResearchDonation.id == protocol_id)
  905. .first()
  906. )
  907. if donation is not None:
  908. return _donation_detail(db, donation, ctx.tenant_no)
  909. raise HTTPException(status_code=404, detail='数据不存在或无权访问')
  910. raise ValueError('不支持的协议来源')
  911. def audit_protocol(
  912. db: Session,
  913. *,
  914. source: str,
  915. protocol_id: str,
  916. audit_status: str,
  917. audit_remark: Optional[str],
  918. ctx: MarketFieldContext,
  919. user_info: dict,
  920. ) -> dict:
  921. if source == SOURCE_CELL:
  922. row = assert_cell_protocol_access(db, protocol_id, ctx, user_info=user_info)
  923. if 'audit' not in allowed_actions('protocol', status=row.protocol_status or ''):
  924. raise ValueError('当前状态不可审核')
  925. cell_crud.create_audit(
  926. db,
  927. collection_protocol_id=protocol_id,
  928. audit_status=audit_status,
  929. audit_remark=audit_remark,
  930. tenant_no=ctx.tenant_no,
  931. user_id=ctx.user_id,
  932. )
  933. return {'id': protocol_id, 'source': source, 'protocolNo': row.protocol_no or ''}
  934. if source == SOURCE_DONATION:
  935. row = assert_donation_access(db, protocol_id, ctx, user_info=user_info)
  936. if 'audit' not in allowed_actions('protocol', status=row.donation_status or ''):
  937. raise ValueError('当前状态不可审核')
  938. donation_crud.submit_audit(
  939. db,
  940. protocol_id,
  941. audit_status=audit_status,
  942. audit_remark=audit_remark,
  943. tenant_no=ctx.tenant_no,
  944. user_id=ctx.user_id,
  945. )
  946. return {'id': protocol_id, 'source': source, 'donationNo': row.donation_no or ''}
  947. raise ValueError('不支持的协议来源')
  948. def delete_protocol(
  949. db: Session,
  950. *,
  951. source: str,
  952. protocol_id: str,
  953. ctx: MarketFieldContext,
  954. user_info: dict,
  955. ) -> None:
  956. if source == SOURCE_CELL:
  957. row = assert_cell_protocol_access(db, protocol_id, ctx, user_info=user_info)
  958. if 'delete' not in allowed_actions('protocol', status=row.protocol_status or ''):
  959. raise ValueError('当前状态不可删除')
  960. cell_crud.soft_delete_collection_protocol(
  961. db, protocol_id, ctx.tenant_no, user_id=ctx.user_id
  962. )
  963. return
  964. if source == SOURCE_DONATION:
  965. row = assert_donation_access(db, protocol_id, ctx, user_info=user_info)
  966. if 'delete' not in allowed_actions('protocol', status=row.donation_status or ''):
  967. raise ValueError('当前状态不可删除')
  968. donation_crud.delete_donation(
  969. db, protocol_id, ctx.tenant_no, user_id=ctx.user_id
  970. )
  971. return
  972. raise ValueError('不支持的协议来源')
  973. def create_protocol(
  974. db: Session,
  975. *,
  976. body: MarketProtocolBody,
  977. ctx: MarketFieldContext,
  978. user_info: dict,
  979. ) -> dict:
  980. customer, collection, samples, attachments = _normalize_write(
  981. db, body=body, ctx=ctx
  982. )
  983. _assert_customer_link_policy(customer, creating=True)
  984. dept_id = _current_dept_id(user_info)
  985. try:
  986. if body.source == SOURCE_CELL:
  987. row = cell_crud.create_collection_protocol(
  988. db,
  989. protocol_no=body.protocol_no or '',
  990. protocol_attachments=attachments.get('protocol_attachments'),
  991. consent_form_urls=attachments.get('consent_form_urls'),
  992. health_survey_form_urls=attachments.get(
  993. 'health_survey_form_urls'
  994. ),
  995. register_date=body.register_date,
  996. collector_user_id=ctx.user_id
  997. if ctx.scope_kind == 'specialist'
  998. else body.collector_user_id,
  999. protocol_total_amount=body.protocol_total_amount,
  1000. remark=body.remark,
  1001. tenant_no=ctx.tenant_no,
  1002. user_id=ctx.user_id,
  1003. create_dept_id=dept_id,
  1004. commit=False,
  1005. )
  1006. attachments = _validate_mobile_attachments(
  1007. db,
  1008. attachments,
  1009. ctx=ctx,
  1010. creating=True,
  1011. business_id=row.id,
  1012. )
  1013. row.protocol_attachments = attachments.get('protocol_attachments')
  1014. row.consent_form_urls = attachments.get('consent_form_urls')
  1015. row.health_survey_form_urls = attachments.get(
  1016. 'health_survey_form_urls'
  1017. )
  1018. db.add(row)
  1019. cell_crud.upsert_party_customer(
  1020. db,
  1021. row.id,
  1022. ctx.tenant_no,
  1023. ctx.user_id,
  1024. commit=False,
  1025. create_dept_id=dept_id,
  1026. **customer,
  1027. )
  1028. cell_crud.upsert_collection_info(
  1029. db,
  1030. row.id,
  1031. ctx.tenant_no,
  1032. ctx.user_id,
  1033. commit=False,
  1034. create_dept_id=dept_id,
  1035. **collection,
  1036. )
  1037. cell_crud.save_samples(
  1038. db,
  1039. row.id,
  1040. ctx.tenant_no,
  1041. ctx.user_id,
  1042. samples,
  1043. create_dept_id=dept_id,
  1044. commit=False,
  1045. )
  1046. assert_cell_protocol_access(db, row.id, ctx, user_info=user_info)
  1047. db.commit()
  1048. db.refresh(row)
  1049. return _cell_detail(db, row, ctx.tenant_no)
  1050. data = {
  1051. 'donation_no': body.donation_no or '',
  1052. 'donation_date': body.donation_date,
  1053. 'collector_user_id': ctx.user_id
  1054. if ctx.scope_kind == 'specialist'
  1055. else body.collector_user_id,
  1056. 'remark': body.remark,
  1057. 'party': customer,
  1058. 'collection': collection,
  1059. 'samples': samples,
  1060. 'consent_form_urls': attachments.get('consent_form_urls'),
  1061. 'attachment_urls': attachments.get('attachment_urls'),
  1062. 'infectious_disease_report_urls': attachments.get(
  1063. 'infectious_disease_report_urls'
  1064. ),
  1065. }
  1066. row = donation_crud.create_donation(
  1067. db,
  1068. data=data,
  1069. tenant_no=ctx.tenant_no,
  1070. user_id=ctx.user_id,
  1071. create_dept_id=dept_id,
  1072. commit=False,
  1073. sync_customers=False,
  1074. )
  1075. attachments = _validate_mobile_attachments(
  1076. db,
  1077. attachments,
  1078. ctx=ctx,
  1079. creating=True,
  1080. business_id=row.id,
  1081. )
  1082. row.consent_form_urls = attachments.get('consent_form_urls')
  1083. row.attachment_urls = attachments.get('attachment_urls')
  1084. row.infectious_disease_report_urls = attachments.get(
  1085. 'infectious_disease_report_urls'
  1086. )
  1087. db.add(row)
  1088. assert_donation_access(db, row.id, ctx, user_info=user_info)
  1089. db.commit()
  1090. db.refresh(row)
  1091. return _donation_detail(db, row, ctx.tenant_no)
  1092. except Exception:
  1093. db.rollback()
  1094. raise
  1095. def update_protocol(
  1096. db: Session,
  1097. *,
  1098. source: str,
  1099. protocol_id: str,
  1100. body: MarketProtocolBody,
  1101. ctx: MarketFieldContext,
  1102. user_info: dict,
  1103. ) -> dict:
  1104. if body.source != source:
  1105. raise ValueError('请求来源与路径来源不一致')
  1106. dept_id = _current_dept_id(user_info)
  1107. try:
  1108. if source == SOURCE_CELL:
  1109. row = assert_cell_protocol_access(
  1110. db, protocol_id, ctx, user_info=user_info
  1111. )
  1112. if (row.protocol_status or '').strip() not in (
  1113. '',
  1114. 'draft',
  1115. 'dsx',
  1116. 'dqr',
  1117. 'sxz',
  1118. 'ygq',
  1119. ):
  1120. raise ValueError('当前状态的协议不可修改')
  1121. current_collection = cell_crud.get_collection_info(
  1122. db, row.id, ctx.tenant_no
  1123. )
  1124. current_party = cell_crud.get_party_customer(
  1125. db, row.id, ctx.tenant_no
  1126. )
  1127. customer, collection, samples, attachments = _normalize_write(
  1128. db,
  1129. body=body,
  1130. ctx=ctx,
  1131. current_collection=current_collection,
  1132. )
  1133. attachments = _validate_mobile_attachments(
  1134. db,
  1135. attachments,
  1136. ctx=ctx,
  1137. creating=False,
  1138. existing={
  1139. 'protocol_attachments': row.protocol_attachments,
  1140. 'consent_form_urls': row.consent_form_urls,
  1141. 'health_survey_form_urls': row.health_survey_form_urls,
  1142. },
  1143. business_id=row.id,
  1144. )
  1145. _assert_customer_link_policy(
  1146. customer, current_party=current_party, creating=False
  1147. )
  1148. cell_crud.update_collection_protocol(
  1149. db,
  1150. row.id,
  1151. tenant_no=ctx.tenant_no,
  1152. user_id=ctx.user_id,
  1153. protocol_no=body.protocol_no,
  1154. protocol_attachments=attachments.get('protocol_attachments'),
  1155. consent_form_urls=attachments.get('consent_form_urls'),
  1156. health_survey_form_urls=attachments.get(
  1157. 'health_survey_form_urls'
  1158. ),
  1159. register_date=body.register_date,
  1160. collector_user_id=ctx.user_id
  1161. if ctx.scope_kind == 'specialist'
  1162. else body.collector_user_id,
  1163. protocol_total_amount=body.protocol_total_amount,
  1164. remark=body.remark,
  1165. commit=False,
  1166. )
  1167. if body.customer is not None:
  1168. if current_party is not None:
  1169. customer = {
  1170. **cell_crud._normalize_fields(
  1171. cell_crud._party_customer_to_dict(current_party)
  1172. ),
  1173. **customer,
  1174. }
  1175. for metadata_key in (
  1176. 'id',
  1177. 'collection_protocol_id',
  1178. 'tenant_no',
  1179. 'order_num',
  1180. 'create_time',
  1181. 'update_time',
  1182. ):
  1183. customer.pop(metadata_key, None)
  1184. newborn_delivery_time = customer.get(
  1185. 'newborn_delivery_time'
  1186. )
  1187. if isinstance(newborn_delivery_time, str):
  1188. if newborn_delivery_time.strip():
  1189. customer['newborn_delivery_time'] = parse_datetime(
  1190. newborn_delivery_time
  1191. )
  1192. else:
  1193. customer.pop('newborn_delivery_time', None)
  1194. cell_crud.upsert_party_customer(
  1195. db,
  1196. row.id,
  1197. ctx.tenant_no,
  1198. ctx.user_id,
  1199. commit=False,
  1200. create_dept_id=dept_id,
  1201. **customer,
  1202. )
  1203. if body.collection is not None:
  1204. cell_crud.upsert_collection_info(
  1205. db,
  1206. row.id,
  1207. ctx.tenant_no,
  1208. ctx.user_id,
  1209. commit=False,
  1210. create_dept_id=dept_id,
  1211. **collection,
  1212. )
  1213. if body.samples is not None:
  1214. cell_crud.save_samples(
  1215. db,
  1216. row.id,
  1217. ctx.tenant_no,
  1218. ctx.user_id,
  1219. samples,
  1220. create_dept_id=dept_id,
  1221. commit=False,
  1222. )
  1223. row = assert_cell_protocol_access(
  1224. db, row.id, ctx, user_info=user_info
  1225. )
  1226. db.commit()
  1227. db.refresh(row)
  1228. return _cell_detail(db, row, ctx.tenant_no)
  1229. row = assert_donation_access(db, protocol_id, ctx, user_info=user_info)
  1230. if (row.donation_status or '').strip() not in (
  1231. '',
  1232. 'draft',
  1233. 'dsx',
  1234. 'dqr',
  1235. 'sxz',
  1236. 'ygq',
  1237. ):
  1238. raise ValueError('当前状态的协议不可修改')
  1239. current_collection = donation_crud.get_collection(
  1240. db, row.id, ctx.tenant_no
  1241. )
  1242. current_party = donation_crud.get_party(db, row.id, ctx.tenant_no)
  1243. customer, collection, samples, attachments = _normalize_write(
  1244. db,
  1245. body=body,
  1246. ctx=ctx,
  1247. current_collection=current_collection,
  1248. )
  1249. attachments = _validate_mobile_attachments(
  1250. db,
  1251. attachments,
  1252. ctx=ctx,
  1253. creating=False,
  1254. existing={
  1255. 'consent_form_urls': row.consent_form_urls,
  1256. 'attachment_urls': row.attachment_urls,
  1257. 'infectious_disease_report_urls': row.infectious_disease_report_urls,
  1258. },
  1259. business_id=row.id,
  1260. )
  1261. _assert_customer_link_policy(
  1262. customer, current_party=current_party, creating=False
  1263. )
  1264. if body.customer is not None and current_party is not None:
  1265. customer = {
  1266. **donation_crud._normalize_fields(
  1267. donation_crud._party_to_dict(current_party)
  1268. ),
  1269. **customer,
  1270. }
  1271. if body.collection is not None and current_collection is not None:
  1272. collection = {
  1273. **donation_crud._normalize_fields(
  1274. donation_crud._collection_to_dict(current_collection)
  1275. ),
  1276. **collection,
  1277. }
  1278. data = {
  1279. 'donation_no': body.donation_no,
  1280. 'donation_date': body.donation_date,
  1281. 'collector_user_id': ctx.user_id
  1282. if ctx.scope_kind == 'specialist'
  1283. else body.collector_user_id,
  1284. 'remark': body.remark,
  1285. 'consent_form_urls': attachments.get('consent_form_urls'),
  1286. 'attachment_urls': attachments.get('attachment_urls'),
  1287. 'infectious_disease_report_urls': attachments.get(
  1288. 'infectious_disease_report_urls'
  1289. ),
  1290. }
  1291. if body.customer is not None:
  1292. data['party'] = customer
  1293. if body.collection is not None:
  1294. data['collection'] = collection
  1295. if body.samples is not None:
  1296. data['samples'] = samples
  1297. data = {key: value for key, value in data.items() if value is not None}
  1298. row = donation_crud.update_donation(
  1299. db,
  1300. row.id,
  1301. data=data,
  1302. tenant_no=ctx.tenant_no,
  1303. user_id=ctx.user_id,
  1304. create_dept_id=dept_id,
  1305. commit=False,
  1306. sync_customers=False,
  1307. )
  1308. row = assert_donation_access(db, row.id, ctx, user_info=user_info)
  1309. db.commit()
  1310. db.refresh(row)
  1311. return _donation_detail(db, row, ctx.tenant_no)
  1312. except Exception:
  1313. db.rollback()
  1314. raise