research_donation.py 87 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661
  1. """科研捐赠管理 CRUD(捐赠单 / 审核 / 状态变更 / 转换)"""
  2. from __future__ import annotations
  3. import math
  4. from datetime import datetime
  5. from decimal import Decimal
  6. from typing import Any, Dict, List, Optional, Tuple
  7. from sqlalchemy import and_, func, or_
  8. from sqlalchemy.orm import Session
  9. from app.core.protocol_status_display import assert_protocol_status_transition
  10. from app.core.utils import generate_uuid, parse_datetime, format_date, optional_date
  11. from app.crud.base import camel_to_snake
  12. from app.crud.biz_no_generator import allocate_next_biz_no
  13. from app.crud.collection_protocol import (
  14. append_protocol_status_change,
  15. attachments_to_urls,
  16. urls_to_attachment_list,
  17. validate_sample_codes_not_used,
  18. _format_sample_collect_summary,
  19. _load_express_name_map,
  20. _load_sample_type_name_map,
  21. _load_site_name_map,
  22. )
  23. from app.crud.protocol_donation_convert import (
  24. assert_biz_no_available,
  25. create_convert_link,
  26. get_convert_partner,
  27. has_active_convert_link,
  28. upsert_convert_link_for_to_storage,
  29. )
  30. from app.utils.sample_special import (
  31. apply_sample_special_fields,
  32. sample_special_to_dict,
  33. validate_sample_special_raw,
  34. )
  35. from app.models.models import (
  36. BizCollectionProtocol,
  37. BizCollectionRegion,
  38. BizCollectionHospital,
  39. BizItemUnit,
  40. BizProtocolCollectionInfo,
  41. BizProtocolPartyCustomer,
  42. BizProtocolSample,
  43. BizProtocolSampleTransport,
  44. BizQcWorkOrder,
  45. BizSampleReception,
  46. SysUser,
  47. )
  48. from app.models.research_donation import (
  49. BizDonationStatusChange,
  50. BizResearchDonation,
  51. BizResearchDonationAudit,
  52. BizResearchDonationCollection,
  53. BizResearchDonationParty,
  54. BizResearchDonationSample,
  55. BizResearchDonationSampleTransport,
  56. )
  57. # ---------------------------------------------------------------------------
  58. # Helpers
  59. # ---------------------------------------------------------------------------
  60. def total_pages(total: int, page_size: int) -> int:
  61. if total <= 0:
  62. return 0
  63. return int(math.ceil(total / float(page_size)))
  64. _DONATION_STATUS_CHANGE_TYPE = {
  65. "sxz": "activate",
  66. "ygq": "expire",
  67. "yzf": "void",
  68. "zckc": "to_storage",
  69. }
  70. def _donation_status_change_to_dict(
  71. row: BizDonationStatusChange,
  72. *,
  73. operator_user_name: str = "",
  74. ) -> Dict[str, Any]:
  75. return {
  76. "id": row.id,
  77. "researchDonationId": row.research_donation_id,
  78. "changeType": row.change_type or "",
  79. "fromStatus": row.from_status or "",
  80. "toStatus": row.to_status or "",
  81. "changeTime": _fmt_dt(row.change_time),
  82. "changeDesc": row.change_desc or "",
  83. "voidType": row.void_type or "",
  84. "operatorUserId": row.operator_user_id or "",
  85. "operatorUserName": operator_user_name or "",
  86. "tenantNo": row.tenant_no,
  87. "createTime": _fmt_dt(row.create_time),
  88. "updateTime": _fmt_dt(row.update_time),
  89. }
  90. def append_donation_status_change(
  91. db: Session,
  92. *,
  93. research_donation_id: str,
  94. change_type: str,
  95. from_status: Optional[str],
  96. to_status: str,
  97. change_time: datetime,
  98. change_desc: Optional[str] = None,
  99. void_type: Optional[str] = None,
  100. tenant_no: str,
  101. user_id: Optional[str] = None,
  102. ) -> BizDonationStatusChange:
  103. """追加一条捐赠状态变更历史(不 commit)。"""
  104. now = datetime.now()
  105. obj = BizDonationStatusChange(
  106. id=generate_uuid(),
  107. research_donation_id=research_donation_id,
  108. change_type=(change_type or "").strip(),
  109. from_status=(from_status or "").strip() or None,
  110. to_status=(to_status or "").strip(),
  111. change_time=change_time,
  112. change_desc=(change_desc or "").strip() or None,
  113. void_type=(void_type or "").strip() or None,
  114. operator_user_id=user_id,
  115. tenant_no=tenant_no,
  116. order_num=0,
  117. remark=None,
  118. create_by=user_id,
  119. create_dept_id="",
  120. create_time=now,
  121. update_by=user_id,
  122. update_time=now,
  123. del_flag=0,
  124. )
  125. db.add(obj)
  126. return obj
  127. def list_donation_status_changes(
  128. db: Session,
  129. *,
  130. research_donation_id: str,
  131. tenant_no: str,
  132. ) -> List[Dict[str, Any]]:
  133. did = (research_donation_id or "").strip()
  134. if not did:
  135. return []
  136. rows = (
  137. db.query(BizDonationStatusChange)
  138. .filter(
  139. BizDonationStatusChange.research_donation_id == did,
  140. BizDonationStatusChange.tenant_no == tenant_no,
  141. BizDonationStatusChange.del_flag == 0,
  142. )
  143. .order_by(
  144. BizDonationStatusChange.change_time.asc(),
  145. BizDonationStatusChange.create_time.asc(),
  146. )
  147. .all()
  148. )
  149. op_ids = list({r.operator_user_id for r in rows if r.operator_user_id})
  150. name_map: Dict[str, str] = {}
  151. if op_ids:
  152. for u in db.query(SysUser.id, SysUser.nick_name).filter(SysUser.id.in_(op_ids)).all():
  153. name_map[u.id] = u.nick_name or ""
  154. return [
  155. _donation_status_change_to_dict(
  156. r, operator_user_name=name_map.get(r.operator_user_id or "", "")
  157. )
  158. for r in rows
  159. ]
  160. _DONATION_SAMPLE_CODE_PREFIX = "KYJZ"
  161. _DONATION_SAMPLE_CODE_SEQ_LEN = 4
  162. def _donation_sample_code_seq(code: str, *, date_str: str) -> Optional[int]:
  163. """解析 KYJZ+YYYYMM+序号 中的序号;不匹配则返回 None。"""
  164. prefix = f"{_DONATION_SAMPLE_CODE_PREFIX}{date_str}"
  165. c = (code or "").strip()
  166. if not c.startswith(prefix):
  167. return None
  168. suffix = c[len(prefix) :]
  169. if len(suffix) != _DONATION_SAMPLE_CODE_SEQ_LEN or not suffix.isdigit():
  170. return None
  171. return int(suffix)
  172. def next_donation_sample_code(
  173. db: Session,
  174. *,
  175. tenant_no: str,
  176. extra_codes: Optional[List[str]] = None,
  177. ) -> str:
  178. """生成捐赠样本编码:KYJZ + YYYYMM + 4 位递增序号(0001 起)。"""
  179. date_str = datetime.now().strftime("%Y%m")
  180. prefix = f"{_DONATION_SAMPLE_CODE_PREFIX}{date_str}"
  181. max_seq = 0
  182. def bump(code: Optional[str]) -> None:
  183. nonlocal max_seq
  184. seq = _donation_sample_code_seq(code or "", date_str=date_str)
  185. if seq is not None:
  186. max_seq = max(max_seq, seq)
  187. donation_rows = (
  188. db.query(BizResearchDonationSample.sample_code)
  189. .filter(
  190. BizResearchDonationSample.tenant_no == tenant_no,
  191. BizResearchDonationSample.del_flag == 0,
  192. BizResearchDonationSample.sample_code.like(f"{prefix}%"),
  193. )
  194. .all()
  195. )
  196. for row in donation_rows:
  197. bump(row[0])
  198. protocol_rows = (
  199. db.query(BizProtocolSample.sample_code)
  200. .filter(
  201. BizProtocolSample.tenant_no == tenant_no,
  202. BizProtocolSample.del_flag == 0,
  203. BizProtocolSample.sample_code.like(f"{prefix}%"),
  204. )
  205. .all()
  206. )
  207. for row in protocol_rows:
  208. bump(row[0])
  209. from app.models.models import BizSampleCode
  210. pool_rows = (
  211. db.query(BizSampleCode.sample_code)
  212. .filter(
  213. BizSampleCode.tenant_no == tenant_no,
  214. BizSampleCode.del_flag == 0,
  215. BizSampleCode.sample_code.like(f"{prefix}%"),
  216. )
  217. .all()
  218. )
  219. for row in pool_rows:
  220. bump(row[0])
  221. for code in extra_codes or []:
  222. bump(code)
  223. return f"{prefix}{str(max_seq + 1).zfill(_DONATION_SAMPLE_CODE_SEQ_LEN)}"
  224. def allocate_monthly_verify_no(
  225. db: Session,
  226. *,
  227. tenant_no: str,
  228. create_time: datetime,
  229. ) -> str:
  230. """按租户 + create_time 年月分配 YYYYMM###;含软删占用,不回收。"""
  231. ym = create_time.strftime("%Y%m")
  232. prefix_len = len(ym)
  233. row = (
  234. db.query(BizResearchDonation.monthly_verify_no)
  235. .filter(
  236. BizResearchDonation.tenant_no == tenant_no,
  237. BizResearchDonation.monthly_verify_no.isnot(None),
  238. BizResearchDonation.monthly_verify_no.like(f"{ym}%"),
  239. )
  240. .order_by(BizResearchDonation.monthly_verify_no.desc())
  241. .first()
  242. )
  243. max_no = (row[0] if row else None) or ""
  244. seq = 0
  245. if max_no.startswith(ym) and len(max_no) >= prefix_len + 3:
  246. try:
  247. seq = int(max_no[prefix_len : prefix_len + 3])
  248. except ValueError:
  249. seq = 0
  250. nxt = seq + 1
  251. if nxt > 999:
  252. raise ValueError(f"当月核量号已用尽({ym})")
  253. return f"{ym}{nxt:03d}"
  254. def _fmt_dt(t: Optional[datetime]) -> str:
  255. return t.strftime("%Y-%m-%d %H:%M:%S") if t else ""
  256. def _normalize_date_bound(value: str, *, end_of_day: bool = False) -> str:
  257. val = (value or "").strip()
  258. if len(val) == 10:
  259. return f"{val} 23:59:59" if end_of_day else f"{val} 00:00:00"
  260. return val
  261. def _dec(v: Any) -> Optional[float]:
  262. if v is None:
  263. return None
  264. if isinstance(v, Decimal):
  265. return float(v)
  266. return float(v)
  267. def _optional_decimal(v: Any) -> Optional[Decimal]:
  268. if v is None or v == "":
  269. return None
  270. return Decimal(str(v))
  271. _SNAKE_ALIASES = {
  272. "apgar1min": "apgar_1min",
  273. "apgar5min": "apgar_5min",
  274. }
  275. def _normalize_fields(fields: Optional[dict]) -> dict:
  276. """将前端 camelCase 字段名转为数据库 snake_case。"""
  277. if not fields:
  278. return {}
  279. out: Dict[str, Any] = {}
  280. for k, v in fields.items():
  281. sk = _SNAKE_ALIASES.get(k) or camel_to_snake(k)
  282. out[sk] = v
  283. return out
  284. def _merge_comma_separated_urls(*parts: Optional[str]) -> Optional[str]:
  285. """合并逗号分隔的附件 URL,去重并保持顺序。"""
  286. seen: set[str] = set()
  287. urls: List[str] = []
  288. for part in parts:
  289. if not part:
  290. continue
  291. for url in str(part).split(","):
  292. u = url.strip()
  293. if not u or u in seen:
  294. continue
  295. seen.add(u)
  296. urls.append(u)
  297. return ",".join(urls) if urls else None
  298. def _resolve_donation_payload(raw: dict) -> None:
  299. """解析保存载荷:附件列表 → URL 字段;party/collection 别名。"""
  300. if raw.get("consent_attachments") is not None:
  301. raw["consent_form_urls"] = attachments_to_urls(raw["consent_attachments"]) or None
  302. elif (raw.get("consent_form_urls") or "").strip():
  303. raw["consent_form_urls"] = (raw["consent_form_urls"] or "").strip()
  304. if raw.get("other_attachments") is not None:
  305. raw["attachment_urls"] = attachments_to_urls(raw["other_attachments"]) or None
  306. elif (raw.get("attachment_urls") or "").strip():
  307. raw["attachment_urls"] = (raw["attachment_urls"] or "").strip()
  308. if raw.get("infectious_disease_report_attachments") is not None:
  309. raw["infectious_disease_report_urls"] = (
  310. attachments_to_urls(raw["infectious_disease_report_attachments"]) or None
  311. )
  312. elif (raw.get("infectious_disease_report_urls") or "").strip():
  313. raw["infectious_disease_report_urls"] = (
  314. (raw["infectious_disease_report_urls"] or "").strip()
  315. )
  316. if not raw.get("party") and raw.get("party_customer"):
  317. raw["party"] = raw["party_customer"]
  318. if not raw.get("collection") and raw.get("collection_info"):
  319. raw["collection"] = raw["collection_info"]
  320. def _user_nick_name_map(db: Session, user_ids: List[str]) -> Dict[str, str]:
  321. ids = list({x for x in user_ids if x})
  322. if not ids:
  323. return {}
  324. rows = db.query(SysUser.id, SysUser.nick_name).filter(SysUser.id.in_(ids)).all()
  325. return {u.id: u.nick_name or "" for u in rows}
  326. def _load_unit_name_map(db: Session, samples: List[BizResearchDonationSample]) -> Dict[str, str]:
  327. unit_ids = list({s.unit_id for s in samples if s.unit_id})
  328. if not unit_ids:
  329. return {}
  330. unit_map: Dict[str, str] = {}
  331. for u in (
  332. db.query(BizItemUnit)
  333. .filter(BizItemUnit.id.in_(unit_ids), BizItemUnit.del_flag == 0)
  334. .all()
  335. ):
  336. unit_map[u.id] = u.unit_name or ""
  337. return unit_map
  338. # ---------------------------------------------------------------------------
  339. # ORM → dict serializers
  340. # ---------------------------------------------------------------------------
  341. def _donation_to_dict(
  342. d: BizResearchDonation,
  343. db: Optional[Session] = None,
  344. tenant_no: Optional[str] = None,
  345. ) -> Dict[str, Any]:
  346. tn = tenant_no or d.tenant_no
  347. return {
  348. "id": d.id,
  349. "donationNo": d.donation_no or "",
  350. "monthlyVerifyNo": d.monthly_verify_no or "",
  351. "donationStatus": d.donation_status or "",
  352. "donationDate": (d.donation_date or "").strip() if d.donation_date else "",
  353. "sourceType": d.source_type or "direct",
  354. "sourceProtocolId": d.source_protocol_id or "",
  355. "consentFormUrls": d.consent_form_urls or "",
  356. "attachmentUrls": d.attachment_urls or "",
  357. "infectiousDiseaseReportUrls": d.infectious_disease_report_urls or "",
  358. "consentAttachmentFiles": urls_to_attachment_list(d.consent_form_urls, db, tn) if db else [],
  359. "attachmentFiles": urls_to_attachment_list(d.attachment_urls, db, tn) if db else [],
  360. "infectiousDiseaseReportAttachmentFiles": (
  361. urls_to_attachment_list(d.infectious_disease_report_urls, db, tn) if db else []
  362. ),
  363. "collectorUserId": d.collector_user_id or "",
  364. "effectiveTime": _fmt_dt(d.effective_time),
  365. "effectiveDesc": d.effective_desc or "",
  366. "expireTime": _fmt_dt(d.expire_time),
  367. "expireDesc": d.expire_desc or "",
  368. "voidTime": _fmt_dt(d.void_time),
  369. "voidDesc": d.void_desc or "",
  370. "voidType": d.void_type or "",
  371. "toStorageTime": _fmt_dt(d.to_storage_time),
  372. "toStorageDesc": d.to_storage_desc or "",
  373. "tenantNo": d.tenant_no,
  374. "orderNum": d.order_num if d.order_num is not None else 0,
  375. "remark": d.remark or "",
  376. "createTime": _fmt_dt(d.create_time),
  377. "updateTime": _fmt_dt(d.update_time),
  378. }
  379. def _audit_to_dict(
  380. a: BizResearchDonationAudit,
  381. *,
  382. donation_no: str = "",
  383. auditor_user_name: str = "",
  384. ) -> Dict[str, Any]:
  385. return {
  386. "id": a.id,
  387. "researchDonationId": a.research_donation_id,
  388. "donationNo": donation_no,
  389. "auditorUserId": a.auditor_user_id or "",
  390. "auditorUserName": auditor_user_name or "",
  391. "auditRemark": a.audit_remark or "",
  392. "auditStatus": a.audit_status or "",
  393. "tenantNo": a.tenant_no,
  394. "orderNum": a.order_num if a.order_num is not None else 0,
  395. "remark": a.remark or "",
  396. "createTime": _fmt_dt(a.create_time),
  397. "updateTime": _fmt_dt(a.update_time),
  398. }
  399. def _party_to_dict(p: BizResearchDonationParty) -> Dict[str, Any]:
  400. return {
  401. "id": p.id,
  402. "researchDonationId": p.research_donation_id,
  403. "customerId": p.customer_id or "",
  404. "fatherCustomerId": p.father_customer_id or "",
  405. "newbornCustomerId": p.newborn_customer_id or "",
  406. "motherName": p.mother_name or "",
  407. "motherPhone": p.mother_phone or "",
  408. "motherIdCard": p.mother_id_card or "",
  409. "motherBirthYm": (p.mother_birth_ym or "").strip() if p.mother_birth_ym else "",
  410. "motherEthnic": p.mother_ethnic or "",
  411. "motherEmail": p.mother_email or "",
  412. "motherAddress": p.mother_address or "",
  413. "fatherName": p.father_name or "",
  414. "fatherPhone": p.father_phone or "",
  415. "fatherIdCard": p.father_id_card or "",
  416. "newbornName": p.newborn_name or "",
  417. "newbornIdCard": p.newborn_id_card or "",
  418. "expectedDeliveryDate": format_date(p.expected_delivery_date),
  419. "newbornDeliveryTime": _fmt_dt(p.newborn_delivery_time),
  420. "newbornSex": p.newborn_sex or "",
  421. "deliveryMode": p.delivery_mode or "",
  422. "birthOrder": p.birth_order,
  423. "newbornWeightGram": p.newborn_weight_gram,
  424. "apgar1min": _dec(p.apgar_1min),
  425. "apgar5min": _dec(p.apgar_5min),
  426. "collectorUserId": p.collector_user_id or "",
  427. "tenantNo": p.tenant_no,
  428. "orderNum": p.order_num if p.order_num is not None else 0,
  429. "remark": p.remark or "",
  430. "createTime": _fmt_dt(p.create_time),
  431. "updateTime": _fmt_dt(p.update_time),
  432. }
  433. def _collection_to_dict(c: BizResearchDonationCollection) -> Dict[str, Any]:
  434. return {
  435. "id": c.id,
  436. "researchDonationId": c.research_donation_id,
  437. "regionId": c.region_id or "",
  438. "hospitalId": c.hospital_id or "",
  439. "medicalStaff": c.medical_staff or "",
  440. "salesUserId": c.sales_user_id or "",
  441. "regionManagerUserId": c.region_manager_user_id or "",
  442. "sampleCollectTime": _fmt_dt(c.sample_collect_time),
  443. "maternalBloodCollectTime": _fmt_dt(c.maternal_blood_collect_time),
  444. "tenantNo": c.tenant_no,
  445. "orderNum": c.order_num if c.order_num is not None else 0,
  446. "remark": c.remark or "",
  447. "createTime": _fmt_dt(c.create_time),
  448. "updateTime": _fmt_dt(c.update_time),
  449. }
  450. def _sample_to_dict(s: BizResearchDonationSample) -> Dict[str, Any]:
  451. return {
  452. "id": s.id,
  453. "researchDonationId": s.research_donation_id,
  454. "sampleTypeId": s.sample_type_id or "",
  455. "sampleCodeId": s.sample_code_id or "",
  456. "sampleCode": s.sample_code or "",
  457. "collectAmount": _dec(s.collect_amount),
  458. "unitId": s.unit_id or "",
  459. "storageYears": s.storage_years,
  460. "sampleStatus": (s.sample_status or "").strip() if (s.sample_status or "").strip() else "",
  461. "storageInDate": (s.storage_in_date or "").strip() if s.storage_in_date else "",
  462. "detectStartDate": (s.detect_start_date or "").strip() if s.detect_start_date else "",
  463. "voidDate": (s.void_date or "").strip() if s.void_date else "",
  464. "storageExpireDate": (s.storage_expire_date or "").strip() if s.storage_expire_date else "",
  465. **sample_special_to_dict(s),
  466. "tenantNo": s.tenant_no,
  467. "orderNum": s.order_num if s.order_num is not None else 0,
  468. "remark": s.remark or "",
  469. "createTime": _fmt_dt(s.create_time),
  470. "updateTime": _fmt_dt(s.update_time),
  471. }
  472. def _transport_to_dict(t: BizResearchDonationSampleTransport) -> Dict[str, Any]:
  473. return {
  474. "id": t.id,
  475. "researchDonationId": t.research_donation_id,
  476. "sampleId": t.sample_id,
  477. "transportType": t.transport_type or "",
  478. "expressCompanyId": t.express_company_id or "",
  479. "waybillNo": t.waybill_no or "",
  480. "destSiteId": t.dest_site_id or "",
  481. "expressFee": _dec(t.express_fee),
  482. "etaTime": _fmt_dt(t.eta_time),
  483. "carrierName": t.carrier_name or "",
  484. "carrierPhone": t.carrier_phone or "",
  485. "remark": t.remark or "",
  486. "orderNum": t.order_num if t.order_num is not None else 0,
  487. "createTime": _fmt_dt(t.create_time),
  488. "updateTime": _fmt_dt(t.update_time),
  489. }
  490. # ---------------------------------------------------------------------------
  491. # Sub-resource queries
  492. # ---------------------------------------------------------------------------
  493. def get_party(
  494. db: Session, research_donation_id: str, tenant_no: str
  495. ) -> Optional[BizResearchDonationParty]:
  496. return (
  497. db.query(BizResearchDonationParty)
  498. .filter(
  499. and_(
  500. BizResearchDonationParty.research_donation_id == research_donation_id,
  501. BizResearchDonationParty.tenant_no == tenant_no,
  502. BizResearchDonationParty.del_flag == 0,
  503. )
  504. )
  505. .first()
  506. )
  507. def get_collection(
  508. db: Session, research_donation_id: str, tenant_no: str
  509. ) -> Optional[BizResearchDonationCollection]:
  510. return (
  511. db.query(BizResearchDonationCollection)
  512. .filter(
  513. and_(
  514. BizResearchDonationCollection.research_donation_id == research_donation_id,
  515. BizResearchDonationCollection.tenant_no == tenant_no,
  516. BizResearchDonationCollection.del_flag == 0,
  517. )
  518. )
  519. .first()
  520. )
  521. def list_samples(
  522. db: Session, research_donation_id: str, tenant_no: str
  523. ) -> List[BizResearchDonationSample]:
  524. return (
  525. db.query(BizResearchDonationSample)
  526. .filter(
  527. and_(
  528. BizResearchDonationSample.research_donation_id == research_donation_id,
  529. BizResearchDonationSample.tenant_no == tenant_no,
  530. BizResearchDonationSample.del_flag == 0,
  531. )
  532. )
  533. .order_by(
  534. BizResearchDonationSample.order_num.asc(),
  535. BizResearchDonationSample.create_time.asc(),
  536. )
  537. .all()
  538. )
  539. def list_sample_transports(
  540. db: Session, research_donation_id: str, tenant_no: str
  541. ) -> List[BizResearchDonationSampleTransport]:
  542. return (
  543. db.query(BizResearchDonationSampleTransport)
  544. .filter(
  545. and_(
  546. BizResearchDonationSampleTransport.research_donation_id == research_donation_id,
  547. BizResearchDonationSampleTransport.tenant_no == tenant_no,
  548. BizResearchDonationSampleTransport.del_flag == 0,
  549. )
  550. )
  551. .order_by(
  552. BizResearchDonationSampleTransport.order_num.asc(),
  553. BizResearchDonationSampleTransport.create_time.asc(),
  554. )
  555. .all()
  556. )
  557. # ---------------------------------------------------------------------------
  558. # 1. list_donations
  559. # ---------------------------------------------------------------------------
  560. def list_donations(
  561. db: Session,
  562. *,
  563. tenant_no: str,
  564. page: int = 1,
  565. page_size: int = 10,
  566. keyword: Optional[str] = None,
  567. donation_status: Optional[str] = None,
  568. create_time_start: Optional[str] = None,
  569. create_time_end: Optional[str] = None,
  570. sample_collect_time_start: Optional[str] = None,
  571. sample_collect_time_end: Optional[str] = None,
  572. user_info=None,
  573. ) -> Dict[str, Any]:
  574. def _base():
  575. q = (
  576. db.query(BizResearchDonation)
  577. .filter(BizResearchDonation.del_flag == 0)
  578. )
  579. if tenant_no:
  580. q = q.filter(BizResearchDonation.tenant_no == tenant_no)
  581. if donation_status:
  582. q = q.filter(BizResearchDonation.donation_status == donation_status.strip())
  583. if create_time_start:
  584. q = q.filter(
  585. BizResearchDonation.create_time >= _normalize_date_bound(create_time_start)
  586. )
  587. if create_time_end:
  588. q = q.filter(
  589. BizResearchDonation.create_time
  590. <= _normalize_date_bound(create_time_end, end_of_day=True)
  591. )
  592. if sample_collect_time_start or sample_collect_time_end:
  593. coll_q = db.query(BizResearchDonationCollection.research_donation_id).filter(
  594. BizResearchDonationCollection.del_flag == 0,
  595. )
  596. if sample_collect_time_start:
  597. coll_q = coll_q.filter(
  598. BizResearchDonationCollection.sample_collect_time
  599. >= _normalize_date_bound(sample_collect_time_start)
  600. )
  601. if sample_collect_time_end:
  602. coll_q = coll_q.filter(
  603. BizResearchDonationCollection.sample_collect_time
  604. <= _normalize_date_bound(sample_collect_time_end, end_of_day=True)
  605. )
  606. q = q.filter(BizResearchDonation.id.in_(coll_q))
  607. kw = (keyword or "").strip()
  608. if kw:
  609. like = f"%{kw}%"
  610. party_match = (
  611. db.query(BizResearchDonationParty.research_donation_id)
  612. .filter(
  613. BizResearchDonationParty.del_flag == 0,
  614. BizResearchDonationParty.mother_name.like(like),
  615. )
  616. .subquery()
  617. )
  618. kw_conds = [
  619. BizResearchDonation.id.in_(party_match),
  620. ]
  621. if tenant_no:
  622. from app.crud import sample_reception as reception_svc
  623. donation_ids = reception_svc.donation_ids_matching_lab_storage_keyword(
  624. db, tenant_no, kw
  625. )
  626. if donation_ids:
  627. kw_conds.append(BizResearchDonation.id.in_(donation_ids))
  628. q = q.filter(or_(*kw_conds))
  629. if user_info:
  630. from app.core.data_scope import apply_data_scope
  631. q = apply_data_scope(q, BizResearchDonation, user_info, db, tenant_no)
  632. return q
  633. total = (
  634. _base()
  635. .order_by(None)
  636. .with_entities(func.count(BizResearchDonation.id))
  637. .scalar()
  638. ) or 0
  639. page = max(1, page)
  640. page_size = min(max(1, page_size), 100)
  641. rows = (
  642. _base()
  643. .order_by(BizResearchDonation.create_time.desc())
  644. .offset((page - 1) * page_size)
  645. .limit(page_size)
  646. .all()
  647. )
  648. # 批量加载 party / collection 子表,避免 N+1
  649. donation_ids = [r.id for r in rows]
  650. party_map: Dict[str, Dict[str, Any]] = {}
  651. collection_map: Dict[str, Dict[str, Any]] = {}
  652. if donation_ids:
  653. party_rows = (
  654. db.query(BizResearchDonationParty)
  655. .filter(
  656. BizResearchDonationParty.research_donation_id.in_(donation_ids),
  657. BizResearchDonationParty.del_flag == 0,
  658. )
  659. .all()
  660. )
  661. for p in party_rows:
  662. party_map[p.research_donation_id] = _party_to_dict(p)
  663. collection_rows = (
  664. db.query(BizResearchDonationCollection)
  665. .filter(
  666. BizResearchDonationCollection.research_donation_id.in_(donation_ids),
  667. BizResearchDonationCollection.del_flag == 0,
  668. )
  669. .all()
  670. )
  671. for c in collection_rows:
  672. collection_map[c.research_donation_id] = _collection_to_dict(c)
  673. # 批量解析地区 / 医院名称
  674. region_ids = list(
  675. {collection_map.get(did, {}).get("regionId", "") for did in donation_ids} - {""}
  676. )
  677. hospital_ids = list(
  678. {collection_map.get(did, {}).get("hospitalId", "") for did in donation_ids} - {""}
  679. )
  680. region_name_map: Dict[str, str] = {}
  681. hospital_name_map: Dict[str, str] = {}
  682. if region_ids:
  683. for reg in (
  684. db.query(BizCollectionRegion.id, BizCollectionRegion.region_name)
  685. .filter(BizCollectionRegion.id.in_(region_ids))
  686. .all()
  687. ):
  688. region_name_map[reg.id] = reg.region_name or ""
  689. if hospital_ids:
  690. for hosp in (
  691. db.query(BizCollectionHospital.id, BizCollectionHospital.hospital_name)
  692. .filter(BizCollectionHospital.id.in_(hospital_ids))
  693. .all()
  694. ):
  695. hospital_name_map[hosp.id] = hosp.hospital_name or ""
  696. # 批量解析采集专员 / 市场专员 / 地区经理名称
  697. sales_user_ids = list(
  698. {collection_map.get(did, {}).get("salesUserId", "") for did in donation_ids} - {""}
  699. )
  700. region_manager_user_ids = list(
  701. {
  702. collection_map.get(did, {}).get("regionManagerUserId", "")
  703. for did in donation_ids
  704. }
  705. - {""}
  706. )
  707. collector_ids = list({r.collector_user_id for r in rows if r.collector_user_id})
  708. user_name_map = _user_nick_name_map(
  709. db, list(set(collector_ids + sales_user_ids + region_manager_user_ids))
  710. )
  711. # 批量加载捐赠样本(列表展示样本类型、样本编码、采集情况)
  712. sample_map: Dict[str, List[BizResearchDonationSample]] = {}
  713. sample_type_name_map: Dict[str, str] = {}
  714. if donation_ids:
  715. s_rows = (
  716. db.query(BizResearchDonationSample)
  717. .filter(
  718. BizResearchDonationSample.research_donation_id.in_(donation_ids),
  719. BizResearchDonationSample.del_flag == 0,
  720. )
  721. .order_by(
  722. BizResearchDonationSample.order_num.asc(),
  723. BizResearchDonationSample.create_time.asc(),
  724. )
  725. .all()
  726. )
  727. sample_type_name_map = _load_sample_type_name_map(db, s_rows)
  728. for s in s_rows:
  729. sample_map.setdefault(s.research_donation_id, []).append(s)
  730. all_sample_codes: List[str] = []
  731. for samples in sample_map.values():
  732. for s in samples:
  733. c = (s.sample_code or "").strip()
  734. if c:
  735. all_sample_codes.append(c)
  736. lab_code_map: Dict[str, str] = {}
  737. reception_summary_map: Dict[str, Dict[str, str]] = {}
  738. qc_status_map: Dict[str, Dict[str, str]] = {}
  739. from app.services.protocol_sample_list_summary import (
  740. build_sample_item_reception_qc_fields,
  741. get_list_qc_status_map_by_sample_codes,
  742. get_list_reception_summary_map_by_sample_codes,
  743. )
  744. if tenant_no and all_sample_codes:
  745. from app.crud import sample_reception as reception_svc
  746. lab_code_map = reception_svc.get_lab_storage_code_map_by_sample_codes(
  747. db, tenant_no, all_sample_codes, reception_source="research_donation"
  748. )
  749. reception_summary_map = get_list_reception_summary_map_by_sample_codes(
  750. db, tenant_no, all_sample_codes, reception_source="research_donation"
  751. )
  752. qc_status_map = get_list_qc_status_map_by_sample_codes(
  753. db, tenant_no, all_sample_codes, reception_source="research_donation"
  754. )
  755. transport_by_sample_id: Dict[str, BizResearchDonationSampleTransport] = {}
  756. if donation_ids:
  757. for t in (
  758. db.query(BizResearchDonationSampleTransport)
  759. .filter(
  760. BizResearchDonationSampleTransport.research_donation_id.in_(donation_ids),
  761. BizResearchDonationSampleTransport.tenant_no == tenant_no,
  762. BizResearchDonationSampleTransport.del_flag == 0,
  763. )
  764. .all()
  765. ):
  766. transport_by_sample_id[t.sample_id] = t
  767. site_name_map = _load_site_name_map(
  768. db, [t.dest_site_id for t in transport_by_sample_id.values() if t.dest_site_id]
  769. )
  770. express_name_map = _load_express_name_map(
  771. db,
  772. [
  773. t.express_company_id
  774. for t in transport_by_sample_id.values()
  775. if t.express_company_id
  776. ],
  777. )
  778. result = []
  779. for r in rows:
  780. d = _donation_to_dict(r, db, tenant_no)
  781. d["collectorUserName"] = user_name_map.get(r.collector_user_id or "", "")
  782. pc = party_map.get(r.id)
  783. if pc:
  784. d["motherName"] = pc.get("motherName", "")
  785. d["motherPhone"] = pc.get("motherPhone", "")
  786. d["motherIdCard"] = pc.get("motherIdCard", "")
  787. d["fatherName"] = pc.get("fatherName", "")
  788. d["newbornName"] = pc.get("newbornName", "")
  789. d["expectedDeliveryDate"] = pc.get("expectedDeliveryDate", "")
  790. d["newbornDeliveryTime"] = pc.get("newbornDeliveryTime", "")
  791. d["newbornSex"] = pc.get("newbornSex", "")
  792. d["deliveryMode"] = pc.get("deliveryMode", "")
  793. d["newbornWeightGram"] = pc.get("newbornWeightGram")
  794. d["birthOrder"] = pc.get("birthOrder")
  795. else:
  796. d["motherName"] = ""
  797. d["motherPhone"] = ""
  798. d["motherIdCard"] = ""
  799. d["fatherName"] = ""
  800. d["newbornName"] = ""
  801. d["expectedDeliveryDate"] = ""
  802. d["newbornDeliveryTime"] = ""
  803. d["newbornSex"] = ""
  804. d["deliveryMode"] = ""
  805. d["newbornWeightGram"] = None
  806. d["birthOrder"] = None
  807. ci = collection_map.get(r.id)
  808. if ci:
  809. d["regionName"] = region_name_map.get(ci.get("regionId", ""), "")
  810. d["hospitalName"] = hospital_name_map.get(ci.get("hospitalId", ""), "")
  811. d["salesUserName"] = user_name_map.get(ci.get("salesUserId", ""), "")
  812. d["regionManagerUserName"] = user_name_map.get(
  813. ci.get("regionManagerUserId", ""), ""
  814. )
  815. d["sampleCollectTime"] = ci.get("sampleCollectTime", "")
  816. d["maternalBloodCollectTime"] = ci.get("maternalBloodCollectTime", "")
  817. else:
  818. d["regionName"] = ""
  819. d["hospitalName"] = ""
  820. d["salesUserName"] = ""
  821. d["regionManagerUserName"] = ""
  822. d["sampleCollectTime"] = ""
  823. d["maternalBloodCollectTime"] = ""
  824. donation_samples = sample_map.get(r.id, [])
  825. type_names: List[str] = []
  826. codes: List[str] = []
  827. sample_items: List[Dict[str, Any]] = []
  828. for s in donation_samples:
  829. type_name = sample_type_name_map.get(s.sample_type_id or "", "")
  830. if type_name:
  831. type_names.append(type_name)
  832. code = (s.sample_code or "").strip()
  833. if code:
  834. codes.append(code)
  835. transport_obj = transport_by_sample_id.get(s.id)
  836. transport_dict: Optional[Dict[str, Any]] = None
  837. if transport_obj and (
  838. (transport_obj.transport_type or "").strip() or transport_obj.eta_time
  839. ):
  840. dest_site_id = transport_obj.dest_site_id or ""
  841. express_company_id = transport_obj.express_company_id or ""
  842. transport_dict = {
  843. "transportType": transport_obj.transport_type or "",
  844. "destSiteId": dest_site_id,
  845. "destSiteName": site_name_map.get(dest_site_id, ""),
  846. "expressCompanyId": express_company_id,
  847. "expressCompanyName": express_name_map.get(express_company_id, ""),
  848. "waybillNo": transport_obj.waybill_no or "",
  849. "carrierName": transport_obj.carrier_name or "",
  850. "carrierPhone": transport_obj.carrier_phone or "",
  851. "etaTime": _fmt_dt(transport_obj.eta_time),
  852. }
  853. sample_items.append(
  854. {
  855. "sampleTypeName": type_name,
  856. "sampleCode": code,
  857. "sampleStatus": (s.sample_status or "").strip(),
  858. "labStorageCode": lab_code_map.get(code, "") if code else "",
  859. "transport": transport_dict,
  860. **sample_special_to_dict(s),
  861. **build_sample_item_reception_qc_fields(
  862. reception_summary_map.get(code) if code else None,
  863. qc_status_map.get(code) if code else None,
  864. ),
  865. }
  866. )
  867. d["sampleItems"] = sample_items
  868. d["sampleTypeNames"] = ",".join(type_names)
  869. d["sampleCodes"] = ",".join(codes)
  870. d["labStorageCodes"] = ",".join((lab_code_map.get(c) or "") for c in codes)
  871. d["sampleCollectSummary"] = _format_sample_collect_summary(donation_samples)
  872. result.append(d)
  873. return {
  874. "list": result,
  875. "total": int(total),
  876. "page": page,
  877. "pageSize": page_size,
  878. "totalPages": total_pages(int(total), page_size),
  879. }
  880. # ---------------------------------------------------------------------------
  881. # 2. get_donation_detail
  882. # ---------------------------------------------------------------------------
  883. def get_donation_detail(
  884. db: Session,
  885. donation_id: str,
  886. tenant_no: str,
  887. ) -> Optional[Dict[str, Any]]:
  888. """查询单条捐赠详情,含全部子资源嵌套。"""
  889. main = (
  890. db.query(BizResearchDonation)
  891. .filter(
  892. and_(
  893. BizResearchDonation.id == donation_id,
  894. BizResearchDonation.tenant_no == tenant_no,
  895. BizResearchDonation.del_flag == 0,
  896. )
  897. )
  898. .first()
  899. )
  900. if not main:
  901. return None
  902. out: Dict[str, Any] = {"donation": _donation_to_dict(main, db, tenant_no)}
  903. # 采集专员名称
  904. user_ids: List[str] = []
  905. if main.collector_user_id:
  906. user_ids.append(main.collector_user_id)
  907. # party
  908. party = get_party(db, donation_id, tenant_no)
  909. out["party"] = _party_to_dict(party) if party else None
  910. if party and party.collector_user_id:
  911. user_ids.append(party.collector_user_id)
  912. # collection
  913. coll = get_collection(db, donation_id, tenant_no)
  914. coll_dict = _collection_to_dict(coll) if coll else None
  915. if coll_dict and coll_dict.get("salesUserId"):
  916. user_ids.append(coll_dict["salesUserId"])
  917. if coll_dict and coll_dict.get("regionManagerUserId"):
  918. user_ids.append(coll_dict["regionManagerUserId"])
  919. if coll_dict:
  920. region_id = str(coll_dict.get("regionId") or "")
  921. if region_id:
  922. r = db.query(BizCollectionRegion.region_name).filter(
  923. BizCollectionRegion.id == region_id
  924. ).first()
  925. coll_dict["regionName"] = r.region_name if r else ""
  926. hospital_id = str(coll_dict.get("hospitalId") or "")
  927. if hospital_id:
  928. h = db.query(BizCollectionHospital.hospital_name).filter(
  929. BizCollectionHospital.id == hospital_id
  930. ).first()
  931. coll_dict["hospitalName"] = h.hospital_name if h else ""
  932. out["collection"] = coll_dict
  933. # samples + transport
  934. s_rows = list_samples(db, donation_id, tenant_no)
  935. transport_rows = list_sample_transports(db, donation_id, tenant_no)
  936. site_name_map = _load_site_name_map(
  937. db, [t.dest_site_id for t in transport_rows if t.dest_site_id]
  938. )
  939. transport_by_sample: Dict[str, Dict[str, Any]] = {}
  940. for t in transport_rows:
  941. td = _transport_to_dict(t)
  942. td["destSiteName"] = site_name_map.get(t.dest_site_id or "", "")
  943. transport_by_sample[t.sample_id] = td
  944. from app.crud import sample_reception as sample_reception_svc
  945. from app.crud import qc_work_order as qc_work_order_svc
  946. from app.crud import production_work_order as production_work_order_svc
  947. from app.crud import storage_release_review as storage_release_review_svc
  948. sample_ids = [s.id for s in s_rows]
  949. sample_code_by_id = {s.id: s.sample_code or "" for s in s_rows}
  950. reception_by_sample = sample_reception_svc.get_receptions_map_for_donation_samples(
  951. db, sample_ids, tenant_no
  952. )
  953. qc_by_sample = qc_work_order_svc.get_qc_info_map_for_samples(
  954. db,
  955. sample_ids,
  956. tenant_no,
  957. )
  958. process_qc_by_sample = qc_work_order_svc.get_process_qc_info_map_for_samples(
  959. db,
  960. sample_ids,
  961. tenant_no,
  962. sample_code_by_id=sample_code_by_id,
  963. )
  964. production_by_sample = production_work_order_svc.get_production_info_map_for_samples(
  965. db, sample_ids, tenant_no
  966. )
  967. storage_release_by_sample = storage_release_review_svc.get_storage_release_map_for_samples(
  968. db,
  969. sample_ids,
  970. tenant_no,
  971. sample_code_by_id=sample_code_by_id,
  972. )
  973. samples_out: List[Dict[str, Any]] = []
  974. unit_name_map = _load_unit_name_map(db, s_rows)
  975. from app.crud import sample_freight as sample_freight_svc
  976. freight_by_sample = sample_freight_svc.freight_map_for_samples(
  977. db,
  978. tenant_no=tenant_no,
  979. sample_source=sample_freight_svc.SAMPLE_SOURCE_DONATION,
  980. sample_ids=sample_ids,
  981. )
  982. for s in s_rows:
  983. item = _sample_to_dict(s)
  984. item["unitName"] = unit_name_map.get(s.unit_id or "", "")
  985. item["transport"] = transport_by_sample.get(s.id)
  986. item["freight"] = freight_by_sample.get(s.id)
  987. item["sampleReception"] = reception_by_sample.get(s.id)
  988. item["productionReception"] = (reception_by_sample.get(s.id) or {}).get(
  989. "productionReception"
  990. )
  991. item["qcInfo"] = qc_by_sample.get(s.id)
  992. item["processQcInfoList"] = process_qc_by_sample.get(s.id, [])
  993. item["productionInfo"] = production_by_sample.get(s.id)
  994. item["storageReleaseInfo"] = storage_release_by_sample.get(s.id)
  995. samples_out.append(item)
  996. out["samples"] = samples_out
  997. # user name map
  998. user_name_map = _user_nick_name_map(db, user_ids)
  999. out["donation"]["collectorUserName"] = user_name_map.get(
  1000. main.collector_user_id or "", ""
  1001. )
  1002. if coll_dict and coll_dict.get("salesUserId"):
  1003. coll_dict["salesUserName"] = user_name_map.get(
  1004. coll_dict["salesUserId"], ""
  1005. )
  1006. if coll_dict:
  1007. coll_dict["regionManagerUserName"] = user_name_map.get(
  1008. coll_dict.get("regionManagerUserId") or "", ""
  1009. )
  1010. return out
  1011. # ---------------------------------------------------------------------------
  1012. # 3. create_donation
  1013. # ---------------------------------------------------------------------------
  1014. def create_donation(
  1015. db: Session,
  1016. *,
  1017. data: dict,
  1018. tenant_no: str,
  1019. user_id: Optional[str] = None,
  1020. create_dept_id: str = "",
  1021. commit: bool = True,
  1022. sync_customers: bool = True,
  1023. ) -> BizResearchDonation:
  1024. """创建科研捐赠单(含 party / collection / samples + transports)。"""
  1025. raw = _normalize_fields(data)
  1026. _resolve_donation_payload(raw)
  1027. consent = (raw.get("consent_form_urls") or "").strip()
  1028. donation_no = (raw.get("donation_no") or "").strip()
  1029. if not donation_no:
  1030. donation_no = allocate_next_biz_no(
  1031. db, tenant_no=tenant_no, kind="donation", user_id=user_id
  1032. )
  1033. assert_biz_no_available(
  1034. db, tenant_no=tenant_no, biz_no=donation_no, for_donation=True
  1035. )
  1036. now = datetime.now()
  1037. monthly_verify_no = allocate_monthly_verify_no(
  1038. db, tenant_no=tenant_no, create_time=now
  1039. )
  1040. obj = BizResearchDonation(
  1041. id=generate_uuid(),
  1042. donation_no=donation_no,
  1043. monthly_verify_no=monthly_verify_no,
  1044. donation_status=(raw.get("donation_status") or "dsx").strip(),
  1045. donation_date=(raw.get("donation_date") or "").strip() or None,
  1046. source_type=(raw.get("source_type") or "direct").strip(),
  1047. source_protocol_id=(raw.get("source_protocol_id") or "").strip() or None,
  1048. consent_form_urls=consent or None,
  1049. attachment_urls=(raw.get("attachment_urls") or "").strip() or None,
  1050. infectious_disease_report_urls=(
  1051. (raw.get("infectious_disease_report_urls") or "").strip() or None
  1052. ),
  1053. collector_user_id=(raw.get("collector_user_id") or "").strip() or None,
  1054. tenant_no=tenant_no,
  1055. order_num=0,
  1056. remark=(raw.get("remark") or "").strip() or None,
  1057. create_by=user_id,
  1058. create_dept_id=create_dept_id,
  1059. create_time=now,
  1060. update_by=user_id,
  1061. update_time=now,
  1062. del_flag=0,
  1063. )
  1064. db.add(obj)
  1065. db.flush()
  1066. donation_id = obj.id
  1067. # party
  1068. from app.services.party_customer_sync import sync_party_customers
  1069. party_raw = _normalize_fields(raw.get("party") or {})
  1070. if sync_customers:
  1071. party_raw = sync_party_customers(
  1072. db,
  1073. party_raw,
  1074. tenant_no=tenant_no,
  1075. user_id=user_id or "",
  1076. commit=commit,
  1077. create_dept_id=create_dept_id,
  1078. )
  1079. _create_party(
  1080. db, donation_id, tenant_no, user_id, party_raw, now,
  1081. create_dept_id=create_dept_id,
  1082. )
  1083. # collection
  1084. coll_raw = _normalize_fields(raw.get("collection") or {})
  1085. _create_collection(
  1086. db, donation_id, tenant_no, user_id, coll_raw, now,
  1087. create_dept_id=create_dept_id,
  1088. )
  1089. # samples(运费批次在 commit 后挂钩;停写旧运输依赖)
  1090. samples_raw = raw.get("samples") or []
  1091. new_samples = _create_samples(
  1092. db, donation_id, tenant_no, user_id, samples_raw, now,
  1093. create_dept_id=create_dept_id,
  1094. )
  1095. from app.crud import sample_freight as sample_freight_svc
  1096. sample_freight_svc.apply_freight_on_protocol_save(
  1097. db,
  1098. tenant_no=tenant_no,
  1099. user_id=user_id,
  1100. sample_source=sample_freight_svc.SAMPLE_SOURCE_DONATION,
  1101. protocol_id=donation_id,
  1102. saved_samples=new_samples,
  1103. input_samples=samples_raw,
  1104. )
  1105. if commit:
  1106. db.commit()
  1107. db.refresh(obj)
  1108. else:
  1109. db.flush()
  1110. return obj
  1111. # ---------------------------------------------------------------------------
  1112. # 4. update_donation
  1113. # ---------------------------------------------------------------------------
  1114. def update_donation(
  1115. db: Session,
  1116. donation_id: str,
  1117. *,
  1118. data: dict,
  1119. tenant_no: str,
  1120. user_id: Optional[str] = None,
  1121. create_dept_id: str = "",
  1122. commit: bool = True,
  1123. sync_customers: bool = True,
  1124. ) -> BizResearchDonation:
  1125. """更新科研捐赠单:主表字段 + 子资源 upsert(软删旧 + 创建新)。"""
  1126. obj = (
  1127. db.query(BizResearchDonation)
  1128. .filter(
  1129. and_(
  1130. BizResearchDonation.id == donation_id,
  1131. BizResearchDonation.tenant_no == tenant_no,
  1132. BizResearchDonation.del_flag == 0,
  1133. )
  1134. )
  1135. .first()
  1136. )
  1137. if not obj:
  1138. raise ValueError("捐赠单不存在或无权操作")
  1139. raw = _normalize_fields(data)
  1140. _resolve_donation_payload(raw)
  1141. now = datetime.now()
  1142. # 主表字段
  1143. _MAIN_STR_FIELDS = [
  1144. "donation_status", "donation_date", "source_type",
  1145. "source_protocol_id", "consent_form_urls", "attachment_urls",
  1146. "infectious_disease_report_urls",
  1147. "collector_user_id", "effective_desc", "expire_desc",
  1148. "void_desc", "to_storage_desc", "remark", "donation_no",
  1149. ]
  1150. _MAIN_DT_FIELDS = [
  1151. "effective_time", "expire_time", "void_time", "to_storage_time",
  1152. ]
  1153. for k in _MAIN_STR_FIELDS:
  1154. if k in raw:
  1155. if k == "donation_no":
  1156. pn = (raw[k] or "").strip()
  1157. if pn and pn != (obj.donation_no or ""):
  1158. raise ValueError("捐赠协议号不可修改")
  1159. else:
  1160. val = raw[k]
  1161. if val is None:
  1162. continue
  1163. setattr(obj, k, (val or "").strip() or None)
  1164. for k in _MAIN_DT_FIELDS:
  1165. if k in raw:
  1166. val = raw[k]
  1167. if isinstance(val, str):
  1168. val = parse_datetime(val)
  1169. setattr(obj, k, val)
  1170. obj.update_by = user_id
  1171. obj.update_time = now
  1172. db.add(obj)
  1173. db.flush()
  1174. # party upsert: 软删旧 → 创建新
  1175. if "party" in raw:
  1176. from app.services.party_customer_sync import sync_party_customers
  1177. _soft_delete_party(db, donation_id, tenant_no, user_id)
  1178. party_raw = _normalize_fields(raw["party"] or {})
  1179. if sync_customers:
  1180. party_raw = sync_party_customers(
  1181. db,
  1182. party_raw,
  1183. tenant_no=tenant_no,
  1184. user_id=user_id or "",
  1185. commit=commit,
  1186. create_dept_id=create_dept_id,
  1187. )
  1188. _create_party(
  1189. db, donation_id, tenant_no, user_id, party_raw, now,
  1190. create_dept_id=create_dept_id,
  1191. )
  1192. # collection upsert
  1193. if "collection" in raw:
  1194. _soft_delete_collection(db, donation_id, tenant_no, user_id)
  1195. coll_raw = _normalize_fields(raw["collection"] or {})
  1196. _create_collection(
  1197. db, donation_id, tenant_no, user_id, coll_raw, now,
  1198. create_dept_id=create_dept_id,
  1199. )
  1200. # samples upsert
  1201. if "samples" in raw:
  1202. existing_samples = list_samples(db, donation_id, tenant_no)
  1203. old_id_to_code = {
  1204. s.id: (s.sample_code or "").strip()
  1205. for s in existing_samples
  1206. if (s.sample_code or "").strip()
  1207. }
  1208. _soft_delete_samples(db, donation_id, tenant_no, user_id)
  1209. _soft_delete_transports(db, donation_id, tenant_no, user_id)
  1210. samples_raw = raw["samples"] or []
  1211. new_samples = _create_samples(
  1212. db, donation_id, tenant_no, user_id, samples_raw, now,
  1213. create_dept_id=create_dept_id,
  1214. )
  1215. new_code_to_id = {
  1216. (s.sample_code or "").strip(): s.id
  1217. for s in new_samples
  1218. if (s.sample_code or "").strip()
  1219. }
  1220. _migrate_donation_sample_child_refs_on_replace(
  1221. db,
  1222. tenant_no=tenant_no,
  1223. old_id_to_code=old_id_to_code,
  1224. new_code_to_id=new_code_to_id,
  1225. user_id=user_id,
  1226. )
  1227. else:
  1228. samples_raw = None
  1229. new_samples = None
  1230. if new_samples is not None and samples_raw is not None:
  1231. from app.crud import sample_freight as sample_freight_svc
  1232. sample_freight_svc.apply_freight_on_protocol_save(
  1233. db,
  1234. tenant_no=tenant_no,
  1235. user_id=user_id,
  1236. sample_source=sample_freight_svc.SAMPLE_SOURCE_DONATION,
  1237. protocol_id=donation_id,
  1238. saved_samples=new_samples,
  1239. input_samples=samples_raw,
  1240. )
  1241. if commit:
  1242. db.commit()
  1243. db.refresh(obj)
  1244. else:
  1245. db.flush()
  1246. return obj
  1247. # ---------------------------------------------------------------------------
  1248. # 5. delete_donation / batch_delete_donations
  1249. # ---------------------------------------------------------------------------
  1250. def delete_donation(
  1251. db: Session,
  1252. donation_id: str,
  1253. tenant_no: str,
  1254. user_id: Optional[str] = None,
  1255. ) -> None:
  1256. """软删除捐赠单 + 所有子资源。"""
  1257. obj = (
  1258. db.query(BizResearchDonation)
  1259. .filter(
  1260. and_(
  1261. BizResearchDonation.id == donation_id,
  1262. BizResearchDonation.tenant_no == tenant_no,
  1263. BizResearchDonation.del_flag == 0,
  1264. )
  1265. )
  1266. .first()
  1267. )
  1268. if not obj:
  1269. raise ValueError("捐赠单不存在或无权操作")
  1270. _soft_delete_all(db, donation_id, tenant_no, user_id)
  1271. db.commit()
  1272. def batch_delete_donations(
  1273. db: Session,
  1274. ids: List[str],
  1275. tenant_no: str,
  1276. user_id: Optional[str] = None,
  1277. ) -> int:
  1278. """批量软删除捐赠单。"""
  1279. count = 0
  1280. for did in (ids or []):
  1281. did = str(did).strip()
  1282. if not did:
  1283. continue
  1284. obj = (
  1285. db.query(BizResearchDonation)
  1286. .filter(
  1287. and_(
  1288. BizResearchDonation.id == did,
  1289. BizResearchDonation.tenant_no == tenant_no,
  1290. BizResearchDonation.del_flag == 0,
  1291. )
  1292. )
  1293. .first()
  1294. )
  1295. if not obj:
  1296. continue
  1297. _soft_delete_all(db, did, tenant_no, user_id)
  1298. count += 1
  1299. db.commit()
  1300. return count
  1301. # ---------------------------------------------------------------------------
  1302. # 6. list_audits
  1303. # ---------------------------------------------------------------------------
  1304. def list_audits(
  1305. db: Session,
  1306. *,
  1307. tenant_no: str,
  1308. page: int = 1,
  1309. page_size: int = 10,
  1310. keyword: Optional[str] = None,
  1311. audit_status: Optional[str] = None,
  1312. research_donation_id: Optional[str] = None,
  1313. user_info=None,
  1314. ) -> Dict[str, Any]:
  1315. q_base = (
  1316. db.query(BizResearchDonationAudit, BizResearchDonation.donation_no)
  1317. .join(
  1318. BizResearchDonation,
  1319. and_(
  1320. BizResearchDonationAudit.research_donation_id == BizResearchDonation.id,
  1321. BizResearchDonation.del_flag == 0,
  1322. ),
  1323. )
  1324. .filter(BizResearchDonationAudit.del_flag == 0)
  1325. )
  1326. if tenant_no:
  1327. q_base = q_base.filter(BizResearchDonationAudit.tenant_no == tenant_no)
  1328. if audit_status:
  1329. q_base = q_base.filter(BizResearchDonationAudit.audit_status == audit_status.strip())
  1330. did = (research_donation_id or "").strip()
  1331. if did:
  1332. q_base = q_base.filter(BizResearchDonationAudit.research_donation_id == did)
  1333. kw = (keyword or "").strip()
  1334. if kw:
  1335. like = f"%{kw}%"
  1336. q_base = q_base.filter(
  1337. or_(
  1338. BizResearchDonation.donation_no.like(like),
  1339. BizResearchDonationAudit.audit_remark.like(like),
  1340. )
  1341. )
  1342. if user_info:
  1343. from app.core.data_scope import apply_data_scope
  1344. q_base = apply_data_scope(q_base, BizResearchDonationAudit, user_info, db, tenant_no)
  1345. total = (
  1346. q_base.order_by(None)
  1347. .with_entities(func.count(BizResearchDonationAudit.id))
  1348. .scalar()
  1349. ) or 0
  1350. page = max(1, page)
  1351. page_size = min(max(1, page_size), 100)
  1352. rows = (
  1353. q_base.order_by(BizResearchDonationAudit.create_time.desc())
  1354. .offset((page - 1) * page_size)
  1355. .limit(page_size)
  1356. .all()
  1357. )
  1358. auditor_ids = list({a.auditor_user_id for a, _ in rows if a.auditor_user_id})
  1359. auditor_name_map = _user_nick_name_map(db, auditor_ids)
  1360. result = [
  1361. _audit_to_dict(
  1362. a,
  1363. donation_no=pn or "",
  1364. auditor_user_name=auditor_name_map.get(a.auditor_user_id or "", ""),
  1365. )
  1366. for a, pn in rows
  1367. ]
  1368. return {
  1369. "list": result,
  1370. "total": int(total),
  1371. "page": page,
  1372. "pageSize": page_size,
  1373. "totalPages": total_pages(int(total), page_size),
  1374. }
  1375. # ---------------------------------------------------------------------------
  1376. # 7. submit_audit
  1377. # ---------------------------------------------------------------------------
  1378. def submit_audit(
  1379. db: Session,
  1380. donation_id: str,
  1381. *,
  1382. audit_status: str,
  1383. audit_remark: Optional[str] = None,
  1384. user_id: Optional[str] = None,
  1385. tenant_no: str = "",
  1386. ) -> BizResearchDonationAudit:
  1387. """提交审核。shtg → 捐赠状态变为 sxz;shth → 状态不变。"""
  1388. # 校验捐赠单存在
  1389. main = (
  1390. db.query(BizResearchDonation)
  1391. .filter(
  1392. and_(
  1393. BizResearchDonation.id == donation_id,
  1394. BizResearchDonation.tenant_no == tenant_no,
  1395. BizResearchDonation.del_flag == 0,
  1396. )
  1397. )
  1398. .first()
  1399. )
  1400. if not main:
  1401. raise ValueError("捐赠单不存在")
  1402. st = (audit_status or "").strip()
  1403. if st not in ("shtg", "shth"):
  1404. raise ValueError("审核状态无效")
  1405. now = datetime.now()
  1406. obj = BizResearchDonationAudit(
  1407. id=generate_uuid(),
  1408. research_donation_id=donation_id,
  1409. auditor_user_id=user_id,
  1410. audit_remark=(audit_remark or "").strip() or None,
  1411. audit_status=st,
  1412. tenant_no=tenant_no,
  1413. order_num=0,
  1414. remark=None,
  1415. create_by=user_id,
  1416. create_dept_id="",
  1417. create_time=now,
  1418. update_by=user_id,
  1419. update_time=now,
  1420. del_flag=0,
  1421. )
  1422. db.add(obj)
  1423. # 审核通过 → 变更状态为 sxz
  1424. if st == "shtg":
  1425. main.donation_status = "sxz"
  1426. main.effective_time = now
  1427. main.update_by = user_id
  1428. main.update_time = now
  1429. db.add(main)
  1430. db.commit()
  1431. db.refresh(obj)
  1432. return obj
  1433. # ---------------------------------------------------------------------------
  1434. # 8. change_status
  1435. # ---------------------------------------------------------------------------
  1436. def change_status(
  1437. db: Session,
  1438. donation_id: str,
  1439. *,
  1440. new_status: str,
  1441. desc: Optional[str] = None,
  1442. time_val: Optional[Any] = None,
  1443. void_type: Optional[str] = None,
  1444. user_id: Optional[str] = None,
  1445. tenant_no: str = "",
  1446. ) -> BizResearchDonation:
  1447. """变更捐赠单状态(含合法性校验)。"""
  1448. obj = (
  1449. db.query(BizResearchDonation)
  1450. .filter(
  1451. and_(
  1452. BizResearchDonation.id == donation_id,
  1453. BizResearchDonation.tenant_no == tenant_no,
  1454. BizResearchDonation.del_flag == 0,
  1455. )
  1456. )
  1457. .first()
  1458. )
  1459. if not obj:
  1460. raise ValueError("捐赠单不存在")
  1461. current = obj.donation_status or ""
  1462. ns = (new_status or "").strip()
  1463. assert_protocol_status_transition(current, ns, kind="donation")
  1464. now = datetime.now()
  1465. if isinstance(time_val, str):
  1466. time_val = parse_datetime(time_val)
  1467. effective_time = time_val or now
  1468. change_desc = (desc or "").strip() or None
  1469. normalized_void_type: Optional[str] = None
  1470. if current != ns:
  1471. obj.donation_status = ns
  1472. obj.update_by = user_id
  1473. obj.update_time = now
  1474. # 更新对应的时间/描述字段
  1475. if ns == "sxz":
  1476. obj.effective_time = effective_time
  1477. obj.effective_desc = change_desc
  1478. elif ns == "yzf":
  1479. obj.void_time = effective_time
  1480. obj.void_desc = change_desc
  1481. from app.crud.dict_data import normalize_void_type
  1482. normalized_void_type = normalize_void_type(db, value=void_type or "", tenant_no=tenant_no)
  1483. obj.void_type = normalized_void_type
  1484. elif ns == "ygq":
  1485. obj.expire_time = effective_time
  1486. obj.expire_desc = change_desc
  1487. elif ns == "zckc":
  1488. obj.to_storage_time = effective_time
  1489. obj.to_storage_desc = change_desc
  1490. change_type = _DONATION_STATUS_CHANGE_TYPE.get(ns)
  1491. if change_type:
  1492. append_donation_status_change(
  1493. db,
  1494. research_donation_id=obj.id,
  1495. change_type=change_type,
  1496. from_status=current,
  1497. to_status=ns,
  1498. change_time=effective_time,
  1499. change_desc=change_desc,
  1500. void_type=normalized_void_type if ns == "yzf" else None,
  1501. tenant_no=tenant_no,
  1502. user_id=user_id,
  1503. )
  1504. db.add(obj)
  1505. db.commit()
  1506. db.refresh(obj)
  1507. return obj
  1508. # ---------------------------------------------------------------------------
  1509. # 9. convert_from_storage
  1510. # ---------------------------------------------------------------------------
  1511. def convert_from_storage(
  1512. db: Session,
  1513. protocol_id: str,
  1514. *,
  1515. tenant_no: str,
  1516. user_id: Optional[str] = None,
  1517. ) -> BizResearchDonation:
  1518. """从细胞存储协议单转换创建科研捐赠单。"""
  1519. # 读取源协议
  1520. proto = (
  1521. db.query(BizCollectionProtocol)
  1522. .filter(
  1523. and_(
  1524. BizCollectionProtocol.id == protocol_id,
  1525. BizCollectionProtocol.tenant_no == tenant_no,
  1526. BizCollectionProtocol.del_flag == 0,
  1527. )
  1528. )
  1529. .first()
  1530. )
  1531. if not proto:
  1532. raise ValueError("源协议单不存在")
  1533. if proto.protocol_status != "sxz":
  1534. raise ValueError("仅生效中的协议可转科研")
  1535. if has_active_convert_link(db, tenant_no, protocol_id=protocol_id):
  1536. raise ValueError("该协议已存在转移关联,无法重复转科研")
  1537. pn_src = (proto.protocol_no or "").strip()
  1538. if not pn_src:
  1539. raise ValueError("源协议单协议号为空,无法转科研")
  1540. # 读取源子资源
  1541. src_party = (
  1542. db.query(BizProtocolPartyCustomer)
  1543. .filter(
  1544. and_(
  1545. BizProtocolPartyCustomer.collection_protocol_id == protocol_id,
  1546. BizProtocolPartyCustomer.tenant_no == tenant_no,
  1547. BizProtocolPartyCustomer.del_flag == 0,
  1548. )
  1549. )
  1550. .first()
  1551. )
  1552. src_coll = (
  1553. db.query(BizProtocolCollectionInfo)
  1554. .filter(
  1555. and_(
  1556. BizProtocolCollectionInfo.collection_protocol_id == protocol_id,
  1557. BizProtocolCollectionInfo.tenant_no == tenant_no,
  1558. BizProtocolCollectionInfo.del_flag == 0,
  1559. )
  1560. )
  1561. .first()
  1562. )
  1563. src_samples = (
  1564. db.query(BizProtocolSample)
  1565. .filter(
  1566. and_(
  1567. BizProtocolSample.collection_protocol_id == protocol_id,
  1568. BizProtocolSample.tenant_no == tenant_no,
  1569. BizProtocolSample.del_flag == 0,
  1570. )
  1571. )
  1572. .all()
  1573. )
  1574. src_transports = (
  1575. db.query(BizProtocolSampleTransport)
  1576. .filter(
  1577. and_(
  1578. BizProtocolSampleTransport.collection_protocol_id == protocol_id,
  1579. BizProtocolSampleTransport.tenant_no == tenant_no,
  1580. BizProtocolSampleTransport.del_flag == 0,
  1581. )
  1582. )
  1583. .all()
  1584. )
  1585. transport_by_sample = {t.sample_id: t for t in src_transports}
  1586. now = datetime.now()
  1587. donation_no = pn_src
  1588. monthly_verify_no = allocate_monthly_verify_no(
  1589. db, tenant_no=tenant_no, create_time=now
  1590. )
  1591. # 创建主记录
  1592. donation = BizResearchDonation(
  1593. id=generate_uuid(),
  1594. donation_no=donation_no,
  1595. monthly_verify_no=monthly_verify_no,
  1596. donation_status="dsx",
  1597. donation_date=now.strftime("%Y%m%d"),
  1598. source_type="from_storage",
  1599. source_protocol_id=protocol_id,
  1600. attachment_urls=(proto.protocol_attachments or "").strip() or None,
  1601. collector_user_id=proto.collector_user_id,
  1602. tenant_no=tenant_no,
  1603. order_num=0,
  1604. remark=f"由细胞存储协议单 {proto.protocol_no} 转入",
  1605. create_by=user_id,
  1606. create_dept_id="",
  1607. create_time=now,
  1608. update_by=user_id,
  1609. update_time=now,
  1610. del_flag=0,
  1611. )
  1612. db.add(donation)
  1613. db.flush()
  1614. did = donation.id
  1615. # 创建 party
  1616. if src_party:
  1617. party = BizResearchDonationParty(
  1618. id=generate_uuid(),
  1619. research_donation_id=did,
  1620. customer_id=src_party.customer_id,
  1621. father_customer_id=getattr(src_party, "father_customer_id", None),
  1622. newborn_customer_id=getattr(src_party, "newborn_customer_id", None),
  1623. mother_name=src_party.mother_name,
  1624. mother_phone=src_party.mother_phone,
  1625. mother_id_card=src_party.mother_id_card,
  1626. mother_birth_ym=src_party.mother_birth_ym,
  1627. mother_ethnic=src_party.mother_ethnic,
  1628. mother_email=src_party.mother_email,
  1629. mother_address=src_party.mother_address,
  1630. father_name=src_party.father_name,
  1631. father_phone=src_party.father_phone,
  1632. father_id_card=src_party.father_id_card,
  1633. newborn_name=src_party.newborn_name,
  1634. newborn_id_card=src_party.newborn_id_card,
  1635. expected_delivery_date=src_party.expected_delivery_date,
  1636. newborn_delivery_time=src_party.newborn_delivery_time,
  1637. newborn_sex=src_party.newborn_sex,
  1638. delivery_mode=src_party.delivery_mode,
  1639. birth_order=src_party.birth_order,
  1640. newborn_weight_gram=src_party.newborn_weight_gram,
  1641. apgar_1min=src_party.apgar_1min,
  1642. apgar_5min=src_party.apgar_5min,
  1643. collector_user_id=src_party.collector_user_id,
  1644. tenant_no=tenant_no,
  1645. order_num=0,
  1646. create_by=user_id,
  1647. create_dept_id="",
  1648. create_time=now,
  1649. update_by=user_id,
  1650. update_time=now,
  1651. del_flag=0,
  1652. )
  1653. db.add(party)
  1654. # 创建 collection
  1655. if src_coll:
  1656. coll = BizResearchDonationCollection(
  1657. id=generate_uuid(),
  1658. research_donation_id=did,
  1659. region_id=src_coll.region_id,
  1660. hospital_id=src_coll.hospital_id,
  1661. medical_staff=src_coll.medical_staff,
  1662. sales_user_id=src_coll.sales_user_id,
  1663. sample_collect_time=src_coll.sample_collect_time,
  1664. maternal_blood_collect_time=src_coll.maternal_blood_collect_time,
  1665. tenant_no=tenant_no,
  1666. order_num=0,
  1667. create_by=user_id,
  1668. create_dept_id="",
  1669. create_time=now,
  1670. update_by=user_id,
  1671. update_time=now,
  1672. del_flag=0,
  1673. )
  1674. db.add(coll)
  1675. # 创建 samples + transports
  1676. for idx, ss in enumerate(src_samples):
  1677. new_sample = BizResearchDonationSample(
  1678. id=generate_uuid(),
  1679. research_donation_id=did,
  1680. sample_type_id=ss.sample_type_id,
  1681. sample_code_id=ss.sample_code_id,
  1682. sample_code=ss.sample_code,
  1683. collect_amount=ss.collect_amount,
  1684. unit_id=ss.unit_id,
  1685. storage_years=ss.storage_years,
  1686. sample_status=ss.sample_status,
  1687. storage_in_date=ss.storage_in_date,
  1688. detect_start_date=ss.detect_start_date,
  1689. void_date=ss.void_date,
  1690. storage_expire_date=ss.storage_expire_date,
  1691. is_special=getattr(ss, "is_special", 0),
  1692. special_remark=getattr(ss, "special_remark", None),
  1693. tenant_no=tenant_no,
  1694. order_num=idx,
  1695. create_by=user_id,
  1696. create_dept_id="",
  1697. create_time=now,
  1698. update_by=user_id,
  1699. update_time=now,
  1700. del_flag=0,
  1701. )
  1702. db.add(new_sample)
  1703. db.flush()
  1704. # 对应运输记录
  1705. src_t = transport_by_sample.get(ss.id)
  1706. if src_t:
  1707. new_t = BizResearchDonationSampleTransport(
  1708. id=generate_uuid(),
  1709. research_donation_id=did,
  1710. sample_id=new_sample.id,
  1711. sample_code=ss.sample_code or None,
  1712. transport_type=src_t.transport_type,
  1713. express_company_id=src_t.express_company_id,
  1714. waybill_no=src_t.waybill_no,
  1715. dest_site_id=src_t.dest_site_id,
  1716. express_fee=src_t.express_fee,
  1717. eta_time=src_t.eta_time,
  1718. carrier_name=src_t.carrier_name,
  1719. carrier_phone=src_t.carrier_phone,
  1720. tenant_no=tenant_no,
  1721. order_num=idx,
  1722. create_by=user_id,
  1723. create_dept_id="",
  1724. create_time=now,
  1725. update_by=user_id,
  1726. update_time=now,
  1727. del_flag=0,
  1728. )
  1729. db.add(new_t)
  1730. # 更新源协议状态为 zky(转科研)
  1731. from_status = (proto.protocol_status or "").strip()
  1732. to_research_desc = f"已转入科研捐赠 {donation_no}"
  1733. proto.protocol_status = "zky"
  1734. proto.to_research_time = now
  1735. proto.to_research_desc = to_research_desc
  1736. proto.update_by = user_id
  1737. proto.update_time = now
  1738. db.add(proto)
  1739. append_protocol_status_change(
  1740. db,
  1741. collection_protocol_id=protocol_id,
  1742. change_type="to_research",
  1743. from_status=from_status,
  1744. to_status="zky",
  1745. change_time=now,
  1746. change_desc=to_research_desc,
  1747. tenant_no=tenant_no,
  1748. user_id=user_id,
  1749. )
  1750. create_convert_link(
  1751. db,
  1752. convert_type="storage_to_research",
  1753. protocol_id=protocol_id,
  1754. research_donation_id=did,
  1755. biz_no=donation_no,
  1756. tenant_no=tenant_no,
  1757. user_id=user_id,
  1758. now=now,
  1759. )
  1760. db.commit()
  1761. db.refresh(donation)
  1762. return donation
  1763. # ---------------------------------------------------------------------------
  1764. # 10. convert_to_storage
  1765. # ---------------------------------------------------------------------------
  1766. def convert_to_storage(
  1767. db: Session,
  1768. donation_id: str,
  1769. *,
  1770. tenant_no: str,
  1771. user_id: Optional[str] = None,
  1772. ) -> BizResearchDonation:
  1773. """从科研捐赠单转换创建细胞存储协议单,返回更新后的捐赠单。"""
  1774. # 读取源捐赠
  1775. donation = (
  1776. db.query(BizResearchDonation)
  1777. .filter(
  1778. and_(
  1779. BizResearchDonation.id == donation_id,
  1780. BizResearchDonation.tenant_no == tenant_no,
  1781. BizResearchDonation.del_flag == 0,
  1782. )
  1783. )
  1784. .first()
  1785. )
  1786. if not donation:
  1787. raise ValueError("捐赠单不存在")
  1788. if donation.donation_status != "sxz":
  1789. raise ValueError("仅生效中的捐赠单可转细胞存储")
  1790. partner = get_convert_partner(db, tenant_no, donation_id=donation_id)
  1791. if partner:
  1792. linked_proto = (
  1793. db.query(BizCollectionProtocol)
  1794. .filter(
  1795. and_(
  1796. BizCollectionProtocol.id == partner["protocol_id"],
  1797. BizCollectionProtocol.tenant_no == tenant_no,
  1798. BizCollectionProtocol.del_flag == 0,
  1799. )
  1800. )
  1801. .first()
  1802. )
  1803. if linked_proto and linked_proto.protocol_status != "zky":
  1804. raise ValueError("该捐赠单已转细胞存储,无法重复操作")
  1805. dn_src = (donation.donation_no or "").strip()
  1806. if not dn_src:
  1807. raise ValueError("源捐赠单协议号为空,无法转细胞存储")
  1808. src_party = get_party(db, donation_id, tenant_no)
  1809. src_coll = get_collection(db, donation_id, tenant_no)
  1810. src_samples = list_samples(db, donation_id, tenant_no)
  1811. src_transports = list_sample_transports(db, donation_id, tenant_no)
  1812. transport_by_sample = {t.sample_id: t for t in src_transports}
  1813. now = datetime.now()
  1814. protocol_no = dn_src
  1815. protocol_no_id = None
  1816. if (donation.source_protocol_id or "").strip():
  1817. src_proto = (
  1818. db.query(BizCollectionProtocol)
  1819. .filter(
  1820. and_(
  1821. BizCollectionProtocol.id == donation.source_protocol_id.strip(),
  1822. BizCollectionProtocol.tenant_no == tenant_no,
  1823. BizCollectionProtocol.del_flag == 0,
  1824. )
  1825. )
  1826. .first()
  1827. )
  1828. if src_proto and src_proto.protocol_no_id:
  1829. protocol_no_id = src_proto.protocol_no_id
  1830. protocol_attachment_urls = _merge_comma_separated_urls(
  1831. donation.consent_form_urls,
  1832. donation.infectious_disease_report_urls,
  1833. donation.attachment_urls,
  1834. )
  1835. # 创建协议单
  1836. proto = BizCollectionProtocol(
  1837. id=generate_uuid(),
  1838. protocol_no_id=protocol_no_id,
  1839. protocol_no=protocol_no,
  1840. protocol_status="dsx",
  1841. register_date=now.strftime("%Y%m%d"),
  1842. protocol_attachments=protocol_attachment_urls,
  1843. collector_user_id=donation.collector_user_id,
  1844. tenant_no=tenant_no,
  1845. order_num=0,
  1846. remark=f"由科研捐赠单 {donation.donation_no} 转入",
  1847. create_by=user_id,
  1848. create_dept_id="",
  1849. create_time=now,
  1850. update_by=user_id,
  1851. update_time=now,
  1852. del_flag=0,
  1853. )
  1854. db.add(proto)
  1855. db.flush()
  1856. pid = proto.id
  1857. # 创建 party
  1858. if src_party:
  1859. party = BizProtocolPartyCustomer(
  1860. id=generate_uuid(),
  1861. collection_protocol_id=pid,
  1862. customer_id=src_party.customer_id,
  1863. father_customer_id=getattr(src_party, "father_customer_id", None),
  1864. newborn_customer_id=getattr(src_party, "newborn_customer_id", None),
  1865. mother_name=src_party.mother_name,
  1866. mother_phone=src_party.mother_phone,
  1867. mother_id_card=src_party.mother_id_card,
  1868. mother_birth_ym=src_party.mother_birth_ym,
  1869. mother_ethnic=src_party.mother_ethnic,
  1870. mother_email=src_party.mother_email,
  1871. mother_address=src_party.mother_address,
  1872. father_name=src_party.father_name,
  1873. father_phone=src_party.father_phone,
  1874. father_id_card=src_party.father_id_card,
  1875. newborn_name=src_party.newborn_name,
  1876. newborn_id_card=src_party.newborn_id_card,
  1877. expected_delivery_date=src_party.expected_delivery_date,
  1878. newborn_delivery_time=src_party.newborn_delivery_time,
  1879. newborn_sex=src_party.newborn_sex,
  1880. delivery_mode=src_party.delivery_mode,
  1881. birth_order=src_party.birth_order,
  1882. newborn_weight_gram=src_party.newborn_weight_gram,
  1883. apgar_1min=src_party.apgar_1min,
  1884. apgar_5min=src_party.apgar_5min,
  1885. collector_user_id=src_party.collector_user_id,
  1886. tenant_no=tenant_no,
  1887. order_num=0,
  1888. create_by=user_id,
  1889. create_dept_id="",
  1890. create_time=now,
  1891. update_by=user_id,
  1892. update_time=now,
  1893. del_flag=0,
  1894. )
  1895. db.add(party)
  1896. # 创建 collection
  1897. if src_coll:
  1898. coll = BizProtocolCollectionInfo(
  1899. id=generate_uuid(),
  1900. collection_protocol_id=pid,
  1901. region_id=src_coll.region_id,
  1902. hospital_id=src_coll.hospital_id,
  1903. medical_staff=src_coll.medical_staff,
  1904. sales_user_id=src_coll.sales_user_id,
  1905. sample_collect_time=src_coll.sample_collect_time,
  1906. maternal_blood_collect_time=src_coll.maternal_blood_collect_time,
  1907. tenant_no=tenant_no,
  1908. order_num=0,
  1909. create_by=user_id,
  1910. create_dept_id="",
  1911. create_time=now,
  1912. update_by=user_id,
  1913. update_time=now,
  1914. del_flag=0,
  1915. )
  1916. db.add(coll)
  1917. # 创建 samples + transports(无 price 字段 → null)
  1918. for idx, ss in enumerate(src_samples):
  1919. new_sample = BizProtocolSample(
  1920. id=generate_uuid(),
  1921. collection_protocol_id=pid,
  1922. sample_type_id=ss.sample_type_id,
  1923. sample_code_id=ss.sample_code_id,
  1924. sample_code=ss.sample_code,
  1925. collect_amount=ss.collect_amount,
  1926. unit_id=ss.unit_id,
  1927. price=None,
  1928. storage_years=ss.storage_years,
  1929. sample_status=ss.sample_status,
  1930. storage_in_date=ss.storage_in_date,
  1931. detect_start_date=ss.detect_start_date,
  1932. void_date=ss.void_date,
  1933. storage_expire_date=ss.storage_expire_date,
  1934. is_special=ss.is_special,
  1935. special_remark=ss.special_remark,
  1936. tenant_no=tenant_no,
  1937. order_num=idx,
  1938. create_by=user_id,
  1939. create_dept_id="",
  1940. create_time=now,
  1941. update_by=user_id,
  1942. update_time=now,
  1943. del_flag=0,
  1944. )
  1945. db.add(new_sample)
  1946. db.flush()
  1947. src_t = transport_by_sample.get(ss.id)
  1948. if src_t:
  1949. new_t = BizProtocolSampleTransport(
  1950. id=generate_uuid(),
  1951. collection_protocol_id=pid,
  1952. sample_id=new_sample.id,
  1953. sample_code=ss.sample_code or None,
  1954. transport_type=src_t.transport_type,
  1955. express_company_id=src_t.express_company_id,
  1956. waybill_no=src_t.waybill_no,
  1957. dest_site_id=src_t.dest_site_id,
  1958. express_fee=src_t.express_fee,
  1959. eta_time=src_t.eta_time,
  1960. carrier_name=src_t.carrier_name,
  1961. carrier_phone=src_t.carrier_phone,
  1962. tenant_no=tenant_no,
  1963. order_num=idx,
  1964. create_by=user_id,
  1965. create_dept_id="",
  1966. create_time=now,
  1967. update_by=user_id,
  1968. update_time=now,
  1969. del_flag=0,
  1970. )
  1971. db.add(new_t)
  1972. # 更新捐赠单状态为 zckc
  1973. from_status = (donation.donation_status or "").strip()
  1974. to_storage_desc = f"已转细胞存储 {protocol_no}"
  1975. donation.donation_status = "zckc"
  1976. donation.to_storage_time = now
  1977. donation.to_storage_desc = to_storage_desc
  1978. donation.update_by = user_id
  1979. donation.update_time = now
  1980. db.add(donation)
  1981. append_donation_status_change(
  1982. db,
  1983. research_donation_id=donation_id,
  1984. change_type="to_storage",
  1985. from_status=from_status,
  1986. to_status="zckc",
  1987. change_time=now,
  1988. change_desc=to_storage_desc,
  1989. tenant_no=tenant_no,
  1990. user_id=user_id,
  1991. )
  1992. upsert_convert_link_for_to_storage(
  1993. db,
  1994. protocol_id=pid,
  1995. research_donation_id=donation_id,
  1996. biz_no=protocol_no,
  1997. tenant_no=tenant_no,
  1998. user_id=user_id,
  1999. now=now,
  2000. )
  2001. db.commit()
  2002. db.refresh(donation)
  2003. return donation
  2004. # ---------------------------------------------------------------------------
  2005. # Internal: sub-resource create helpers
  2006. # ---------------------------------------------------------------------------
  2007. _PARTY_STR_FIELDS = [
  2008. "customer_id", "father_customer_id", "newborn_customer_id",
  2009. "mother_name", "mother_phone", "mother_id_card",
  2010. "mother_birth_ym", "mother_ethnic", "mother_email", "mother_address",
  2011. "father_name", "father_phone", "father_id_card",
  2012. "newborn_name", "newborn_id_card", "newborn_sex",
  2013. "delivery_mode", "collector_user_id",
  2014. ]
  2015. _PARTY_INT_FIELDS = ["birth_order", "newborn_weight_gram"]
  2016. _PARTY_DEC_FIELDS = ["apgar_1min", "apgar_5min"]
  2017. _PARTY_DATE_FIELDS = ["expected_delivery_date"]
  2018. _PARTY_DT_FIELDS = ["newborn_delivery_time"]
  2019. def _create_party(
  2020. db: Session,
  2021. donation_id: str,
  2022. tenant_no: str,
  2023. user_id: Optional[str],
  2024. raw: dict,
  2025. now: datetime,
  2026. create_dept_id: str = "",
  2027. ) -> BizResearchDonationParty:
  2028. obj = BizResearchDonationParty(
  2029. id=generate_uuid(),
  2030. research_donation_id=donation_id,
  2031. tenant_no=tenant_no,
  2032. order_num=0,
  2033. remark=(raw.get("remark") or "").strip() or None,
  2034. create_by=user_id,
  2035. create_dept_id=create_dept_id,
  2036. create_time=now,
  2037. update_by=user_id,
  2038. update_time=now,
  2039. del_flag=0,
  2040. )
  2041. for k in _PARTY_STR_FIELDS:
  2042. if k in raw:
  2043. setattr(obj, k, (raw[k] or "").strip() or None)
  2044. for k in _PARTY_INT_FIELDS:
  2045. if k in raw:
  2046. setattr(obj, k, raw[k])
  2047. for k in _PARTY_DEC_FIELDS:
  2048. if k in raw:
  2049. setattr(obj, k, _optional_decimal(raw[k]))
  2050. for k in _PARTY_DATE_FIELDS:
  2051. if k in raw:
  2052. setattr(obj, k, optional_date(raw[k]))
  2053. for k in _PARTY_DT_FIELDS:
  2054. if k in raw:
  2055. val = raw[k]
  2056. if isinstance(val, str):
  2057. val = parse_datetime(val)
  2058. setattr(obj, k, val)
  2059. db.add(obj)
  2060. db.flush()
  2061. return obj
  2062. _COLL_STR_FIELDS = [
  2063. "region_id",
  2064. "hospital_id",
  2065. "medical_staff",
  2066. "sales_user_id",
  2067. "region_manager_user_id",
  2068. ]
  2069. _COLL_DT_FIELDS = ["sample_collect_time", "maternal_blood_collect_time"]
  2070. def _create_collection(
  2071. db: Session,
  2072. donation_id: str,
  2073. tenant_no: str,
  2074. user_id: Optional[str],
  2075. raw: dict,
  2076. now: datetime,
  2077. create_dept_id: str = "",
  2078. ) -> BizResearchDonationCollection:
  2079. obj = BizResearchDonationCollection(
  2080. id=generate_uuid(),
  2081. research_donation_id=donation_id,
  2082. tenant_no=tenant_no,
  2083. order_num=0,
  2084. remark=(raw.get("remark") or "").strip() or None,
  2085. create_by=user_id,
  2086. create_dept_id=create_dept_id,
  2087. create_time=now,
  2088. update_by=user_id,
  2089. update_time=now,
  2090. del_flag=0,
  2091. )
  2092. for k in _COLL_STR_FIELDS:
  2093. if k in raw:
  2094. setattr(obj, k, (raw[k] or "").strip() or None)
  2095. for k in _COLL_DT_FIELDS:
  2096. if k in raw:
  2097. val = raw[k]
  2098. if isinstance(val, str):
  2099. val = parse_datetime(val)
  2100. setattr(obj, k, val)
  2101. db.add(obj)
  2102. db.flush()
  2103. return obj
  2104. _SAMPLE_STR_FIELDS = [
  2105. "sample_type_id", "sample_code_id", "sample_code", "unit_id",
  2106. "sample_status", "storage_in_date", "detect_start_date",
  2107. "void_date", "storage_expire_date",
  2108. ]
  2109. _SAMPLE_DEC_FIELDS = ["collect_amount"]
  2110. _SAMPLE_INT_FIELDS = ["storage_years"]
  2111. def _migrate_donation_sample_child_refs_on_replace(
  2112. db: Session,
  2113. *,
  2114. tenant_no: str,
  2115. old_id_to_code: Dict[str, str],
  2116. new_code_to_id: Dict[str, str],
  2117. user_id: Optional[str],
  2118. ) -> None:
  2119. """捐赠样本行重建后,将接收/质检工单的捐赠样本 ID 迁移到新样本 ID。"""
  2120. if not old_id_to_code or not new_code_to_id:
  2121. return
  2122. old_ids = list(old_id_to_code.keys())
  2123. now = datetime.now()
  2124. rec_rows = (
  2125. db.query(BizSampleReception)
  2126. .filter(
  2127. BizSampleReception.donation_sample_id.in_(old_ids),
  2128. BizSampleReception.tenant_no == tenant_no,
  2129. BizSampleReception.del_flag == 0,
  2130. BizSampleReception.reception_source == "research_donation",
  2131. )
  2132. .all()
  2133. )
  2134. for row in rec_rows:
  2135. old_sid = (row.donation_sample_id or "").strip()
  2136. code = old_id_to_code.get(old_sid) or (row.sample_code or "").strip()
  2137. new_sid = new_code_to_id.get(code) if code else None
  2138. if not new_sid:
  2139. continue
  2140. row.donation_sample_id = new_sid
  2141. row.update_by = user_id
  2142. row.update_time = now
  2143. db.add(row)
  2144. wo_rows = (
  2145. db.query(BizQcWorkOrder)
  2146. .filter(
  2147. BizQcWorkOrder.protocol_sample_id.in_(old_ids),
  2148. BizQcWorkOrder.tenant_no == tenant_no,
  2149. BizQcWorkOrder.del_flag == 0,
  2150. BizQcWorkOrder.reception_source == "research_donation",
  2151. )
  2152. .all()
  2153. )
  2154. for row in wo_rows:
  2155. old_sid = (row.protocol_sample_id or "").strip()
  2156. code = old_id_to_code.get(old_sid) or (row.sample_code or "").strip()
  2157. new_sid = new_code_to_id.get(code) if code else None
  2158. if not new_sid:
  2159. continue
  2160. row.protocol_sample_id = new_sid
  2161. row.update_by = user_id
  2162. row.update_time = now
  2163. db.add(row)
  2164. def _create_samples(
  2165. db: Session,
  2166. donation_id: str,
  2167. tenant_no: str,
  2168. user_id: Optional[str],
  2169. samples: list,
  2170. now: datetime,
  2171. create_dept_id: str = "",
  2172. ) -> List[BizResearchDonationSample]:
  2173. validate_sample_codes_not_used(
  2174. db,
  2175. tenant_no=tenant_no,
  2176. samples=samples,
  2177. exclude_donation_id=donation_id,
  2178. )
  2179. result = []
  2180. assigned_codes: List[str] = []
  2181. for idx, raw_item in enumerate(samples or []):
  2182. raw = _normalize_fields(raw_item)
  2183. validate_sample_special_raw(raw, index=idx)
  2184. code = (raw.get("sample_code") or "").strip()
  2185. if not code and (raw.get("sample_type_id") or "").strip():
  2186. code = next_donation_sample_code(
  2187. db,
  2188. tenant_no=tenant_no,
  2189. extra_codes=assigned_codes,
  2190. )
  2191. raw["sample_code"] = code
  2192. if code:
  2193. assigned_codes.append(code)
  2194. obj = BizResearchDonationSample(
  2195. id=generate_uuid(),
  2196. research_donation_id=donation_id,
  2197. tenant_no=tenant_no,
  2198. order_num=idx,
  2199. remark=(raw.get("remark") or "").strip() or None,
  2200. create_by=user_id,
  2201. create_dept_id=create_dept_id,
  2202. create_time=now,
  2203. update_by=user_id,
  2204. update_time=now,
  2205. del_flag=0,
  2206. )
  2207. for k in _SAMPLE_STR_FIELDS:
  2208. if k == "sample_status":
  2209. continue
  2210. if k in raw:
  2211. setattr(obj, k, (raw[k] or "").strip() or None)
  2212. if "sample_status" in raw:
  2213. status_val = raw.get("sample_status")
  2214. obj.sample_status = (
  2215. str(status_val).strip()
  2216. if status_val is not None and str(status_val).strip()
  2217. else None
  2218. )
  2219. for k in _SAMPLE_DEC_FIELDS:
  2220. if k in raw and raw[k] is not None:
  2221. setattr(obj, k, Decimal(str(raw[k])))
  2222. for k in _SAMPLE_INT_FIELDS:
  2223. if k in raw:
  2224. setattr(obj, k, raw[k])
  2225. apply_sample_special_fields(obj, raw)
  2226. db.add(obj)
  2227. db.flush()
  2228. result.append(obj)
  2229. # 预计到达等仍写运输表;运费由 apply_freight_on_protocol_save 挂钩
  2230. transport_raw = raw.get("transport") if isinstance(raw.get("transport"), dict) else {}
  2231. if not transport_raw and raw.get("eta_time"):
  2232. transport_raw = {"eta_time": raw.get("eta_time")}
  2233. elif isinstance(transport_raw, dict) and raw.get("eta_time") and not (
  2234. transport_raw.get("eta_time") or transport_raw.get("etaTime")
  2235. ):
  2236. transport_raw = {**transport_raw, "eta_time": raw.get("eta_time")}
  2237. if transport_raw:
  2238. _create_transport(
  2239. db,
  2240. donation_id,
  2241. obj.id,
  2242. tenant_no,
  2243. user_id,
  2244. transport_raw,
  2245. idx,
  2246. now,
  2247. sample_code=obj.sample_code,
  2248. )
  2249. return result
  2250. def _create_transport(
  2251. db: Session,
  2252. donation_id: str,
  2253. sample_id: str,
  2254. tenant_no: str,
  2255. user_id: Optional[str],
  2256. raw: dict,
  2257. order_num: int,
  2258. now: datetime,
  2259. sample_code: Optional[str] = None,
  2260. ) -> Optional[BizResearchDonationSampleTransport]:
  2261. """写回捐赠样本运输;可仅有预计到达时间(运费批次改造后)。"""
  2262. tnorm = _normalize_fields(raw)
  2263. transport_type = (tnorm.get("transport_type") or "").strip()
  2264. eta_time = tnorm.get("eta_time")
  2265. if isinstance(eta_time, str):
  2266. eta_time = parse_datetime(eta_time)
  2267. if not transport_type and not eta_time:
  2268. return None
  2269. express_fee = tnorm.get("express_fee")
  2270. if express_fee is not None and express_fee != "":
  2271. express_fee = Decimal(str(express_fee))
  2272. else:
  2273. express_fee = None
  2274. obj = BizResearchDonationSampleTransport(
  2275. id=generate_uuid(),
  2276. research_donation_id=donation_id,
  2277. sample_id=sample_id,
  2278. sample_code=sample_code or None,
  2279. transport_type=transport_type,
  2280. express_company_id=(tnorm.get("express_company_id") or "").strip() or None,
  2281. waybill_no=(tnorm.get("waybill_no") or "").strip() or None,
  2282. dest_site_id=(tnorm.get("dest_site_id") or "").strip() or None,
  2283. express_fee=express_fee,
  2284. eta_time=eta_time,
  2285. carrier_name=(tnorm.get("carrier_name") or "").strip() or None,
  2286. carrier_phone=(tnorm.get("carrier_phone") or "").strip() or None,
  2287. tenant_no=tenant_no,
  2288. order_num=order_num,
  2289. remark=(tnorm.get("remark") or "").strip() or None,
  2290. create_by=user_id,
  2291. create_dept_id="",
  2292. create_time=now,
  2293. update_by=user_id,
  2294. update_time=now,
  2295. del_flag=0,
  2296. )
  2297. db.add(obj)
  2298. db.flush()
  2299. return obj
  2300. # ---------------------------------------------------------------------------
  2301. # Internal: soft delete helpers
  2302. # ---------------------------------------------------------------------------
  2303. def _soft_delete_party(
  2304. db: Session,
  2305. donation_id: str,
  2306. tenant_no: str,
  2307. user_id: Optional[str],
  2308. ) -> None:
  2309. rows = (
  2310. db.query(BizResearchDonationParty)
  2311. .filter(
  2312. and_(
  2313. BizResearchDonationParty.research_donation_id == donation_id,
  2314. BizResearchDonationParty.tenant_no == tenant_no,
  2315. BizResearchDonationParty.del_flag == 0,
  2316. )
  2317. )
  2318. .all()
  2319. )
  2320. for r in rows:
  2321. r.del_flag = 1
  2322. r.update_by = user_id
  2323. r.update_time = datetime.now()
  2324. db.add(r)
  2325. if rows:
  2326. db.flush()
  2327. def _soft_delete_collection(
  2328. db: Session,
  2329. donation_id: str,
  2330. tenant_no: str,
  2331. user_id: Optional[str],
  2332. ) -> None:
  2333. rows = (
  2334. db.query(BizResearchDonationCollection)
  2335. .filter(
  2336. and_(
  2337. BizResearchDonationCollection.research_donation_id == donation_id,
  2338. BizResearchDonationCollection.tenant_no == tenant_no,
  2339. BizResearchDonationCollection.del_flag == 0,
  2340. )
  2341. )
  2342. .all()
  2343. )
  2344. for r in rows:
  2345. r.del_flag = 1
  2346. r.update_by = user_id
  2347. r.update_time = datetime.now()
  2348. db.add(r)
  2349. if rows:
  2350. db.flush()
  2351. def _soft_delete_samples(
  2352. db: Session,
  2353. donation_id: str,
  2354. tenant_no: str,
  2355. user_id: Optional[str],
  2356. ) -> None:
  2357. rows = (
  2358. db.query(BizResearchDonationSample)
  2359. .filter(
  2360. and_(
  2361. BizResearchDonationSample.research_donation_id == donation_id,
  2362. BizResearchDonationSample.tenant_no == tenant_no,
  2363. BizResearchDonationSample.del_flag == 0,
  2364. )
  2365. )
  2366. .all()
  2367. )
  2368. for r in rows:
  2369. r.del_flag = 1
  2370. r.update_by = user_id
  2371. r.update_time = datetime.now()
  2372. db.add(r)
  2373. if rows:
  2374. db.flush()
  2375. def _soft_delete_transports(
  2376. db: Session,
  2377. donation_id: str,
  2378. tenant_no: str,
  2379. user_id: Optional[str],
  2380. ) -> None:
  2381. rows = (
  2382. db.query(BizResearchDonationSampleTransport)
  2383. .filter(
  2384. and_(
  2385. BizResearchDonationSampleTransport.research_donation_id == donation_id,
  2386. BizResearchDonationSampleTransport.tenant_no == tenant_no,
  2387. BizResearchDonationSampleTransport.del_flag == 0,
  2388. )
  2389. )
  2390. .all()
  2391. )
  2392. for r in rows:
  2393. r.del_flag = 1
  2394. r.update_by = user_id
  2395. r.update_time = datetime.now()
  2396. db.add(r)
  2397. if rows:
  2398. db.flush()
  2399. def _soft_delete_all(
  2400. db: Session,
  2401. donation_id: str,
  2402. tenant_no: str,
  2403. user_id: Optional[str],
  2404. ) -> None:
  2405. """软删除主记录 + 所有子资源。"""
  2406. now = datetime.now()
  2407. # 主记录
  2408. main = (
  2409. db.query(BizResearchDonation)
  2410. .filter(
  2411. and_(
  2412. BizResearchDonation.id == donation_id,
  2413. BizResearchDonation.tenant_no == tenant_no,
  2414. BizResearchDonation.del_flag == 0,
  2415. )
  2416. )
  2417. .first()
  2418. )
  2419. if main:
  2420. main.del_flag = 1
  2421. main.update_by = user_id
  2422. main.update_time = now
  2423. db.add(main)
  2424. _soft_delete_party(db, donation_id, tenant_no, user_id)
  2425. _soft_delete_collection(db, donation_id, tenant_no, user_id)
  2426. _soft_delete_samples(db, donation_id, tenant_no, user_id)
  2427. _soft_delete_transports(db, donation_id, tenant_no, user_id)