market_protocol.py 79 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256
  1. """移动市场协议服务:双来源统一展示,写入保持来源内原子性。"""
  2. from __future__ import annotations
  3. from datetime import datetime, timedelta
  4. from decimal import Decimal
  5. from typing import List, Optional, Tuple
  6. from fastapi import HTTPException
  7. from sqlalchemy import func, or_
  8. from sqlalchemy.orm import Session
  9. from app.core.utils import parse_datetime
  10. from app.core.protocol_status_display import (
  11. build_void_type_label_map,
  12. resolve_void_type_label,
  13. )
  14. from app.crud import collection_protocol as cell_crud
  15. from app.crud import protocol_sample_payment as psp_crud
  16. from app.crud import research_donation as donation_crud
  17. from app.crud import sample_freight as sample_freight_crud
  18. from app.models.models import (
  19. BizCellSampleType,
  20. BizCollectionHospital,
  21. BizCollectionProtocol,
  22. BizCollectionRegion,
  23. BizCollectionRegionStaff,
  24. BizCustomer,
  25. BizItemUnit,
  26. BizProtocolCollectionInfo,
  27. BizProtocolPartyCustomer,
  28. BizProtocolPayment,
  29. BizProtocolPaymentDetail,
  30. BizProtocolPaymentSchedule,
  31. BizProtocolPaymentTransfer,
  32. BizProtocolSample,
  33. BizProtocolSamplePayment,
  34. BizProtocolSampleTransport,
  35. BizSampleCode,
  36. SysUser,
  37. )
  38. from app.models.research_donation import (
  39. BizResearchDonation,
  40. BizResearchDonationCollection,
  41. BizResearchDonationParty,
  42. BizResearchDonationSample,
  43. BizResearchDonationSampleTransport,
  44. )
  45. from app.schemas.market_mobile import MarketProtocolBody
  46. from app.services.market_field_scope import (
  47. MarketFieldContext,
  48. apply_cell_protocol_scope,
  49. apply_donation_scope,
  50. assert_cell_protocol_access,
  51. assert_donation_access,
  52. )
  53. from app.services import market_freight
  54. from app.services.market_support import (
  55. _dict_options,
  56. allowed_actions,
  57. validate_attachment_refs,
  58. )
  59. SOURCE_CELL = 'cell_storage'
  60. SOURCE_DONATION = 'research_donation'
  61. def _fixed_money(value):
  62. if value is None:
  63. return None
  64. return format(Decimal(str(value)).quantize(Decimal('0.01')), 'f')
  65. SOURCES = (SOURCE_CELL, SOURCE_DONATION)
  66. _CUSTOMER_LINK_FIELDS = (
  67. 'customer_id',
  68. 'father_customer_id',
  69. 'newborn_customer_id',
  70. )
  71. def _current_dept_id(user_info: dict) -> str:
  72. if not isinstance(user_info, dict):
  73. return ''
  74. return str(
  75. user_info.get('dept_id')
  76. or user_info.get('deptId')
  77. or user_info.get('region_id')
  78. or ''
  79. ).strip()
  80. def _dump(value) -> dict:
  81. if value is None:
  82. return {}
  83. if hasattr(value, 'model_dump'):
  84. return value.model_dump(by_alias=False, exclude_unset=True)
  85. return dict(value)
  86. def _assert_customer_link_policy(
  87. db: Session,
  88. customer: dict,
  89. *,
  90. ctx: MarketFieldContext,
  91. user_info: dict,
  92. ) -> None:
  93. """允许绑定/改绑本租户数据权限内的客户主档;空值表示清空;禁止无效 id。"""
  94. from app.core.data_scope import apply_data_scope
  95. for key in _CUSTOMER_LINK_FIELDS:
  96. if key not in customer:
  97. continue
  98. supplied = str(customer.get(key) or '').strip()
  99. if not supplied:
  100. continue
  101. query = db.query(BizCustomer.id).filter(
  102. BizCustomer.id == supplied,
  103. BizCustomer.tenant_no == ctx.tenant_no,
  104. BizCustomer.del_flag == 0,
  105. )
  106. query = apply_data_scope(query, BizCustomer, user_info, db, ctx.tenant_no)
  107. if query.first() is None:
  108. raise ValueError('客户不存在或不在权限范围内')
  109. def _fmt_dt(value) -> str:
  110. if value is None:
  111. return ''
  112. if isinstance(value, str):
  113. return value
  114. return value.strftime('%Y-%m-%d %H:%M:%S')
  115. def _manager_assignment_allowed(
  116. db: Session,
  117. ctx: MarketFieldContext,
  118. *,
  119. region_id: Optional[str],
  120. region_manager_user_id: Optional[str],
  121. ) -> bool:
  122. region = str(region_id or '').strip()
  123. if not region:
  124. return False
  125. return (
  126. db.query(BizCollectionRegionStaff.id)
  127. .filter(
  128. BizCollectionRegionStaff.tenant_no == ctx.tenant_no,
  129. BizCollectionRegionStaff.del_flag == 0,
  130. BizCollectionRegionStaff.user_id == ctx.user_id,
  131. BizCollectionRegionStaff.is_leader == 1,
  132. BizCollectionRegionStaff.region_id == region,
  133. )
  134. .first()
  135. is not None
  136. )
  137. def _ensure_manager_assignment(
  138. db: Session,
  139. ctx: MarketFieldContext,
  140. *,
  141. region_id: Optional[str],
  142. region_manager_user_id: Optional[str],
  143. ) -> None:
  144. if not _manager_assignment_allowed(
  145. db,
  146. ctx,
  147. region_id=region_id,
  148. region_manager_user_id=region_manager_user_id,
  149. ):
  150. raise ValueError('协议归属不在当前地区经理范围内')
  151. def _active_user_ids(db: Session, ctx: MarketFieldContext, ids: set) -> set:
  152. if not ids:
  153. return set()
  154. return {
  155. str(row[0])
  156. for row in db.query(SysUser.id)
  157. .filter(
  158. SysUser.id.in_(ids),
  159. SysUser.tenant_no == ctx.tenant_no,
  160. SysUser.del_flag == 0,
  161. SysUser.status == '1',
  162. )
  163. .all()
  164. }
  165. def _validate_references(
  166. db: Session,
  167. ctx: MarketFieldContext,
  168. *,
  169. customer: dict,
  170. collection: dict,
  171. samples: List[dict],
  172. extra_user_ids: Optional[set] = None,
  173. current_collection=None,
  174. ) -> None:
  175. region_id = str(collection.get('region_id') or '').strip()
  176. hospital_id = str(collection.get('hospital_id') or '').strip()
  177. if region_id:
  178. exists = (
  179. db.query(BizCollectionRegion.id)
  180. .filter(
  181. BizCollectionRegion.id == region_id,
  182. BizCollectionRegion.tenant_no == ctx.tenant_no,
  183. BizCollectionRegion.del_flag == 0,
  184. )
  185. .first()
  186. )
  187. if not exists:
  188. raise ValueError('采集地区不存在或不属于当前租户')
  189. if hospital_id:
  190. exists = (
  191. db.query(BizCollectionHospital.id)
  192. .filter(
  193. BizCollectionHospital.id == hospital_id,
  194. BizCollectionHospital.region_id == region_id,
  195. BizCollectionHospital.tenant_no == ctx.tenant_no,
  196. BizCollectionHospital.del_flag == 0,
  197. )
  198. .first()
  199. )
  200. if not exists:
  201. raise ValueError('医院不存在、不属于当前租户或与采集地区不匹配')
  202. user_ids = {
  203. str(value).strip()
  204. for value in (
  205. customer.get('collector_user_id'),
  206. collection.get('sales_user_id'),
  207. collection.get('region_manager_user_id'),
  208. )
  209. if str(value or '').strip()
  210. }
  211. user_ids.update(
  212. str(value).strip()
  213. for value in (extra_user_ids or set())
  214. if str(value or '').strip()
  215. )
  216. if _active_user_ids(db, ctx, user_ids) != user_ids:
  217. raise ValueError('引用用户不存在、已停用或不属于当前租户')
  218. _validate_region_staff_assignments(
  219. db,
  220. ctx,
  221. collection=collection,
  222. current_collection=current_collection,
  223. )
  224. customer_ids = {
  225. str(customer.get(key) or '').strip()
  226. for key in ('customer_id', 'father_customer_id', 'newborn_customer_id')
  227. if str(customer.get(key) or '').strip()
  228. }
  229. if customer_ids:
  230. existing = {
  231. str(row[0])
  232. for row in db.query(BizCustomer.id)
  233. .filter(
  234. BizCustomer.id.in_(customer_ids),
  235. BizCustomer.tenant_no == ctx.tenant_no,
  236. BizCustomer.del_flag == 0,
  237. )
  238. .all()
  239. }
  240. if existing != customer_ids:
  241. raise ValueError('客户不存在或不属于当前租户')
  242. type_ids = {
  243. str(item.get('sample_type_id') or '').strip()
  244. for item in samples
  245. if str(item.get('sample_type_id') or '').strip()
  246. }
  247. if type_ids:
  248. existing = {
  249. str(row[0])
  250. for row in db.query(BizCellSampleType.id)
  251. .filter(
  252. BizCellSampleType.id.in_(type_ids),
  253. BizCellSampleType.tenant_no == ctx.tenant_no,
  254. BizCellSampleType.del_flag == 0,
  255. )
  256. .all()
  257. }
  258. if existing != type_ids:
  259. raise ValueError('样本类型不存在或不属于当前租户')
  260. unit_ids = {
  261. str(item.get('unit_id') or '').strip()
  262. for item in samples
  263. if str(item.get('unit_id') or '').strip()
  264. }
  265. if unit_ids:
  266. existing = {
  267. str(row[0])
  268. for row in db.query(BizItemUnit.id)
  269. .filter(
  270. BizItemUnit.id.in_(unit_ids),
  271. BizItemUnit.tenant_no == ctx.tenant_no,
  272. BizItemUnit.del_flag == 0,
  273. )
  274. .all()
  275. }
  276. if existing != unit_ids:
  277. raise ValueError('计量单位不存在或不属于当前租户')
  278. sample_code_ids = {
  279. str(item.get('sample_code_id') or '').strip()
  280. for item in samples
  281. if str(item.get('sample_code_id') or '').strip()
  282. }
  283. sample_code_map = {}
  284. if sample_code_ids:
  285. sample_code_map = {
  286. str(row.id): str(row.sample_code or '').strip()
  287. for row in db.query(BizSampleCode)
  288. .filter(
  289. BizSampleCode.id.in_(sample_code_ids),
  290. BizSampleCode.tenant_no == ctx.tenant_no,
  291. BizSampleCode.del_flag == 0,
  292. )
  293. .all()
  294. }
  295. if set(sample_code_map) != sample_code_ids:
  296. raise ValueError('样本编码不存在、已删除或不属于当前租户')
  297. for item in samples:
  298. sample_code_id = str(item.get('sample_code_id') or '').strip()
  299. if not sample_code_id:
  300. continue
  301. expected_code = sample_code_map[sample_code_id]
  302. supplied_code = str(item.get('sample_code') or '').strip()
  303. if supplied_code and supplied_code != expected_code:
  304. raise ValueError('样本编码ID与样本编码不一致')
  305. item['sample_code'] = expected_code
  306. def _ensure_donation_sample_codes(
  307. db: Session, samples: List[dict], *, tenant_no: str
  308. ) -> None:
  309. """科研捐赠:空样本编码时按 Web 规则自动生成。"""
  310. reserved: List[str] = []
  311. for item in samples:
  312. existing = str(item.get('sample_code') or '').strip()
  313. if existing:
  314. reserved.append(existing)
  315. continue
  316. code = donation_crud.next_donation_sample_code(
  317. db, tenant_no=tenant_no, extra_codes=reserved
  318. )
  319. item['sample_code'] = code
  320. reserved.append(code)
  321. def _validate_region_staff_assignments(
  322. db: Session,
  323. ctx: MarketFieldContext,
  324. *,
  325. collection: dict,
  326. current_collection=None,
  327. ) -> None:
  328. """新增/变更归属必须来自目标地区人员;未变更历史值保持兼容。"""
  329. region_id = str(collection.get('region_id') or '').strip()
  330. current_region_id = str(
  331. getattr(current_collection, 'region_id', None) or ''
  332. ).strip()
  333. for field_name, api_name in (
  334. ('sales_user_id', 'salesUserId'),
  335. ('region_manager_user_id', 'regionManagerUserId'),
  336. ):
  337. user_id = str(collection.get(field_name) or '').strip()
  338. current_user_id = str(
  339. getattr(current_collection, field_name, None) or ''
  340. ).strip()
  341. unchanged = (
  342. current_collection is not None
  343. and region_id == current_region_id
  344. and user_id == current_user_id
  345. )
  346. if unchanged or not user_id:
  347. continue
  348. binding = (
  349. db.query(BizCollectionRegionStaff.id)
  350. .filter(
  351. BizCollectionRegionStaff.tenant_no == ctx.tenant_no,
  352. BizCollectionRegionStaff.region_id == region_id,
  353. BizCollectionRegionStaff.user_id == user_id,
  354. BizCollectionRegionStaff.del_flag == 0,
  355. )
  356. .first()
  357. )
  358. if binding is None:
  359. raise ValueError(f'{api_name} 必须是目标采集地区人员')
  360. def _normalize_write(
  361. db: Session,
  362. *,
  363. body: MarketProtocolBody,
  364. ctx: MarketFieldContext,
  365. current_collection=None,
  366. current_samples: Optional[List] = None,
  367. ) -> Tuple[dict, dict, List[dict], dict]:
  368. customer = _dump(body.customer)
  369. collection = _dump(body.collection)
  370. samples = [_dump(item) for item in (body.samples or [])]
  371. _validate_unique_sample_identity(samples)
  372. if body.samples is not None and current_samples is not None:
  373. samples = _merge_existing_sample_fields(current_samples, samples)
  374. elif any(str(item.get('id') or '').strip() for item in samples):
  375. raise ValueError('样本不存在或不属于当前协议')
  376. if body.source == SOURCE_DONATION:
  377. _ensure_donation_sample_codes(db, samples, tenant_no=ctx.tenant_no)
  378. # freight_draft 可能仍是嵌套 model;统一成 dict 供运费挂钩
  379. for item in samples:
  380. draft = item.get('freight_draft')
  381. if draft is not None and hasattr(draft, 'model_dump'):
  382. item['freight_draft'] = draft.model_dump(
  383. by_alias=False, exclude_unset=True
  384. )
  385. attachments = _dump(body.attachments)
  386. effective_collection = {
  387. key: getattr(current_collection, key, None)
  388. for key in (
  389. 'region_id',
  390. 'hospital_id',
  391. 'sales_user_id',
  392. 'region_manager_user_id',
  393. )
  394. }
  395. effective_collection.update(collection)
  396. if ctx.scope_kind == 'specialist':
  397. customer['collector_user_id'] = ctx.user_id
  398. collection['sales_user_id'] = ctx.user_id
  399. effective_collection['sales_user_id'] = ctx.user_id
  400. else:
  401. unchanged_direct_assignment = bool(
  402. current_collection is not None
  403. and str(getattr(current_collection, 'region_id', None) or '').strip()
  404. == str(effective_collection.get('region_id') or '').strip()
  405. and str(
  406. getattr(current_collection, 'region_manager_user_id', None) or ''
  407. ).strip()
  408. == ctx.user_id
  409. and str(effective_collection.get('region_manager_user_id') or '').strip()
  410. == ctx.user_id
  411. )
  412. if not unchanged_direct_assignment:
  413. _ensure_manager_assignment(
  414. db,
  415. ctx,
  416. region_id=effective_collection.get('region_id'),
  417. region_manager_user_id=effective_collection.get(
  418. 'region_manager_user_id'
  419. ),
  420. )
  421. for key in ('sample_collect_time', 'maternal_blood_collect_time'):
  422. if key in collection and isinstance(collection[key], str):
  423. collection[key] = parse_datetime(collection[key])
  424. if 'newborn_delivery_time' in customer and isinstance(
  425. customer['newborn_delivery_time'], str
  426. ):
  427. customer['newborn_delivery_time'] = parse_datetime(
  428. customer['newborn_delivery_time']
  429. )
  430. _validate_references(
  431. db,
  432. ctx,
  433. customer=customer,
  434. collection=effective_collection,
  435. samples=samples,
  436. extra_user_ids={body.collector_user_id}
  437. if ctx.scope_kind == 'manager' and body.collector_user_id
  438. else set(),
  439. current_collection=current_collection,
  440. )
  441. return customer, collection, samples, attachments
  442. _SAMPLE_PRESERVED_FIELDS = (
  443. 'sample_type_id',
  444. 'sample_code_id',
  445. 'sample_code',
  446. 'collect_amount',
  447. 'unit_id',
  448. 'price',
  449. 'original_price',
  450. 'storage_years',
  451. 'sample_status',
  452. 'storage_in_date',
  453. 'detect_start_date',
  454. 'void_date',
  455. 'storage_expire_date',
  456. 'is_special',
  457. 'special_remark',
  458. 'remark',
  459. )
  460. def _validate_unique_sample_identity(samples: List[dict]) -> None:
  461. for field_name, api_name in (
  462. ('id', 'sampleId'),
  463. ('sample_code', 'sampleCode'),
  464. ('sample_code_id', 'sampleCodeId'),
  465. ):
  466. values = [
  467. str(item.get(field_name) or '').strip()
  468. for item in samples
  469. if str(item.get(field_name) or '').strip()
  470. ]
  471. if len(values) != len(set(values)):
  472. raise ValueError(f'{api_name} 不能重复')
  473. def _unique_sample_map(current_samples: List, field_name: str) -> dict:
  474. grouped = {}
  475. for item in current_samples:
  476. value = str(getattr(item, field_name, None) or '').strip()
  477. if value:
  478. grouped.setdefault(value, []).append(item)
  479. return {
  480. value: rows[0]
  481. for value, rows in grouped.items()
  482. if len(rows) == 1
  483. }
  484. def _merge_existing_sample_fields(current_samples: List, samples: List[dict]) -> List[dict]:
  485. """按稳定身份沿用未展示字段;未匹配项一律按新样本处理。"""
  486. current_by_id = {
  487. str(getattr(item, 'id', None) or '').strip(): item
  488. for item in current_samples
  489. if str(getattr(item, 'id', None) or '').strip()
  490. }
  491. current_by_code_id = _unique_sample_map(current_samples, 'sample_code_id')
  492. current_by_code = _unique_sample_map(current_samples, 'sample_code')
  493. merged = []
  494. for incoming in samples:
  495. sample_id = str(incoming.get('id') or '').strip()
  496. code = str(incoming.get('sample_code') or '').strip()
  497. code_id = str(incoming.get('sample_code_id') or '').strip()
  498. if sample_id:
  499. current = current_by_id.get(sample_id)
  500. if current is None:
  501. raise ValueError('样本不存在或不属于当前协议')
  502. else:
  503. current = current_by_code_id.get(code_id) or current_by_code.get(code)
  504. base = (
  505. {
  506. key: getattr(current, key, None)
  507. for key in _SAMPLE_PRESERVED_FIELDS
  508. }
  509. if current is not None
  510. else {}
  511. )
  512. base.update(incoming)
  513. base.pop('id', None)
  514. merged.append(base)
  515. return merged
  516. def _validate_mobile_attachments(
  517. db: Session,
  518. attachments: dict,
  519. *,
  520. ctx: MarketFieldContext,
  521. creating: bool,
  522. existing: Optional[dict] = None,
  523. business_id: Optional[str] = None,
  524. ) -> dict:
  525. current = existing or {}
  526. normalized = dict(attachments)
  527. for key, refs in attachments.items():
  528. if refs is None:
  529. continue
  530. normalized[key] = validate_attachment_refs(
  531. db,
  532. refs,
  533. module='protocol',
  534. ctx=ctx,
  535. creating=creating,
  536. existing_refs=current.get(key),
  537. business_id=business_id,
  538. )
  539. return normalized
  540. def _validate_v1_payment_detail_attachments(
  541. db: Session,
  542. details: Optional[List],
  543. *,
  544. row: BizCollectionProtocol,
  545. ctx: MarketFieldContext,
  546. ) -> Optional[List[dict]]:
  547. """Validate and bind legacy detail receipts through the protocol boundary."""
  548. if details is None:
  549. return None
  550. payment = (
  551. db.query(BizProtocolPayment)
  552. .filter(
  553. BizProtocolPayment.collection_protocol_id == row.id,
  554. BizProtocolPayment.tenant_no == ctx.tenant_no,
  555. BizProtocolPayment.del_flag == 0,
  556. )
  557. .populate_existing()
  558. .with_for_update()
  559. .first()
  560. )
  561. existing_rows = (
  562. db.query(BizProtocolPaymentDetail)
  563. .filter(
  564. BizProtocolPaymentDetail.payment_id == payment.id,
  565. BizProtocolPaymentDetail.tenant_no == ctx.tenant_no,
  566. BizProtocolPaymentDetail.del_flag == 0,
  567. )
  568. .populate_existing()
  569. .with_for_update()
  570. .all()
  571. if payment is not None
  572. else []
  573. )
  574. existing_by_id = {item.id: item for item in existing_rows}
  575. normalized: List[dict] = []
  576. for item in details:
  577. raw = item.model_dump(by_alias=False, exclude_unset=True, mode='json')
  578. if 'transfer_attachments' not in raw:
  579. normalized.append(raw)
  580. continue
  581. current = existing_by_id.get(str(raw.get('id') or '').strip())
  582. current_refs = current.transfer_attachments if current is not None else None
  583. if current is not None and current.pay_status != 'dfj':
  584. if str(raw.get('transfer_attachments') or '').strip() != str(
  585. current_refs or ''
  586. ).strip():
  587. raise ValueError('锁定缴费明细的附件不可修改')
  588. raw['transfer_attachments'] = current_refs or ''
  589. else:
  590. raw['transfer_attachments'] = validate_attachment_refs(
  591. db,
  592. raw.get('transfer_attachments'),
  593. module='protocol',
  594. ctx=ctx,
  595. creating=current is None,
  596. existing_refs=current_refs,
  597. business_id=row.id,
  598. )
  599. normalized.append(raw)
  600. return normalized
  601. def _party_name_cell(db: Session, ids: List[str], tenant_no: str) -> dict:
  602. if not ids:
  603. return {}
  604. rows = (
  605. db.query(BizProtocolPartyCustomer)
  606. .filter(
  607. BizProtocolPartyCustomer.collection_protocol_id.in_(ids),
  608. BizProtocolPartyCustomer.tenant_no == tenant_no,
  609. BizProtocolPartyCustomer.del_flag == 0,
  610. )
  611. .all()
  612. )
  613. return {row.collection_protocol_id: row.mother_name or '' for row in rows}
  614. def _party_name_donation(db: Session, ids: List[str], tenant_no: str) -> dict:
  615. if not ids:
  616. return {}
  617. rows = (
  618. db.query(BizResearchDonationParty)
  619. .filter(
  620. BizResearchDonationParty.research_donation_id.in_(ids),
  621. BizResearchDonationParty.tenant_no == tenant_no,
  622. BizResearchDonationParty.del_flag == 0,
  623. )
  624. .all()
  625. )
  626. return {row.research_donation_id: row.mother_name or '' for row in rows}
  627. def _enrich_protocol_cards(
  628. db: Session, items: List[dict], tenant_no: str
  629. ) -> None:
  630. """批量补齐与 Web 列表一致的移动卡片字段,避免逐行查询。"""
  631. cell_ids = [item['id'] for item in items if item['source'] == SOURCE_CELL]
  632. donation_ids = [
  633. item['id'] for item in items if item['source'] == SOURCE_DONATION
  634. ]
  635. collection_map = {}
  636. sample_map = {}
  637. party_map = {}
  638. if cell_ids:
  639. for row in db.query(BizProtocolCollectionInfo).filter(
  640. BizProtocolCollectionInfo.collection_protocol_id.in_(cell_ids),
  641. BizProtocolCollectionInfo.tenant_no == tenant_no,
  642. BizProtocolCollectionInfo.del_flag == 0,
  643. ).order_by(BizProtocolCollectionInfo.create_time.desc()).all():
  644. collection_map.setdefault((SOURCE_CELL, row.collection_protocol_id), row)
  645. for row in db.query(BizProtocolSample).filter(
  646. BizProtocolSample.collection_protocol_id.in_(cell_ids),
  647. BizProtocolSample.tenant_no == tenant_no,
  648. BizProtocolSample.del_flag == 0,
  649. ).order_by(BizProtocolSample.create_time.asc()).all():
  650. sample_map.setdefault((SOURCE_CELL, row.collection_protocol_id), row)
  651. for row in db.query(BizProtocolPartyCustomer).filter(
  652. BizProtocolPartyCustomer.collection_protocol_id.in_(cell_ids),
  653. BizProtocolPartyCustomer.tenant_no == tenant_no,
  654. BizProtocolPartyCustomer.del_flag == 0,
  655. ).order_by(BizProtocolPartyCustomer.create_time.desc()).all():
  656. party_map.setdefault((SOURCE_CELL, row.collection_protocol_id), row)
  657. if donation_ids:
  658. for row in db.query(BizResearchDonationCollection).filter(
  659. BizResearchDonationCollection.research_donation_id.in_(donation_ids),
  660. BizResearchDonationCollection.tenant_no == tenant_no,
  661. BizResearchDonationCollection.del_flag == 0,
  662. ).order_by(BizResearchDonationCollection.create_time.desc()).all():
  663. collection_map.setdefault((SOURCE_DONATION, row.research_donation_id), row)
  664. for row in db.query(BizResearchDonationSample).filter(
  665. BizResearchDonationSample.research_donation_id.in_(donation_ids),
  666. BizResearchDonationSample.tenant_no == tenant_no,
  667. BizResearchDonationSample.del_flag == 0,
  668. ).order_by(BizResearchDonationSample.create_time.asc()).all():
  669. sample_map.setdefault((SOURCE_DONATION, row.research_donation_id), row)
  670. for row in db.query(BizResearchDonationParty).filter(
  671. BizResearchDonationParty.research_donation_id.in_(donation_ids),
  672. BizResearchDonationParty.tenant_no == tenant_no,
  673. BizResearchDonationParty.del_flag == 0,
  674. ).order_by(BizResearchDonationParty.create_time.desc()).all():
  675. party_map.setdefault((SOURCE_DONATION, row.research_donation_id), row)
  676. region_ids = {
  677. row.region_id for row in collection_map.values() if row.region_id
  678. }
  679. hospital_ids = {
  680. row.hospital_id for row in collection_map.values() if row.hospital_id
  681. }
  682. user_ids = {
  683. value
  684. for row in collection_map.values()
  685. for value in (row.sales_user_id, row.region_manager_user_id)
  686. if value
  687. }
  688. user_ids.update(
  689. item.get('collectorUserId')
  690. for item in items
  691. if item.get('collectorUserId')
  692. )
  693. type_ids = {
  694. row.sample_type_id for row in sample_map.values() if row.sample_type_id
  695. }
  696. region_names = {
  697. row.id: row.region_name or ''
  698. for row in db.query(BizCollectionRegion).filter(
  699. BizCollectionRegion.id.in_(region_ids or ['']),
  700. BizCollectionRegion.tenant_no == tenant_no,
  701. BizCollectionRegion.del_flag == 0,
  702. )
  703. }
  704. hospital_names = {
  705. row.id: row.hospital_name or ''
  706. for row in db.query(BizCollectionHospital).filter(
  707. BizCollectionHospital.id.in_(hospital_ids or ['']),
  708. BizCollectionHospital.tenant_no == tenant_no,
  709. BizCollectionHospital.del_flag == 0,
  710. )
  711. }
  712. user_names = {
  713. row.id: row.nick_name or ''
  714. for row in db.query(SysUser).filter(
  715. SysUser.id.in_(user_ids or ['']),
  716. SysUser.tenant_no == tenant_no,
  717. )
  718. }
  719. type_names = {
  720. row.id: row.type_name or ''
  721. for row in db.query(BizCellSampleType).filter(
  722. BizCellSampleType.id.in_(type_ids or ['']),
  723. BizCellSampleType.del_flag == 0,
  724. or_(
  725. BizCellSampleType.tenant_no == tenant_no,
  726. BizCellSampleType.tenant_no == '',
  727. ),
  728. )
  729. }
  730. sample_ids = [row.id for row in sample_map.values()]
  731. transport_by_sample = {}
  732. if sample_ids:
  733. for row in db.query(BizProtocolSampleTransport).filter(
  734. BizProtocolSampleTransport.sample_id.in_(sample_ids),
  735. BizProtocolSampleTransport.tenant_no == tenant_no,
  736. BizProtocolSampleTransport.del_flag == 0,
  737. ).all():
  738. transport_by_sample.setdefault(row.sample_id, row)
  739. for row in db.query(BizResearchDonationSampleTransport).filter(
  740. BizResearchDonationSampleTransport.sample_id.in_(sample_ids),
  741. BizResearchDonationSampleTransport.tenant_no == tenant_no,
  742. BizResearchDonationSampleTransport.del_flag == 0,
  743. ).all():
  744. transport_by_sample.setdefault(row.sample_id, row)
  745. lab_by_key = {}
  746. from app.crud import sample_reception as reception_crud
  747. for source in SOURCES:
  748. codes = [
  749. row.sample_code
  750. for (item_source, _), row in sample_map.items()
  751. if item_source == source and row.sample_code
  752. ]
  753. for code, lab_code in reception_crud.get_lab_storage_code_map_by_sample_codes(
  754. db, tenant_no, codes, reception_source=source
  755. ).items():
  756. lab_by_key[(source, code)] = lab_code
  757. payment_summaries = {}
  758. if cell_ids:
  759. from app.services.qc_work_order_fee_summary import (
  760. build_protocol_payment_summaries,
  761. )
  762. payment_summaries = build_protocol_payment_summaries(
  763. db, cell_ids, tenant_no
  764. )
  765. transport_labels = {'kdys': '快递运输', 'ryxd': '人员携带'}
  766. void_type_labels = build_void_type_label_map(
  767. db,
  768. tenant_no,
  769. [str(item.get('voidType') or '') for item in items],
  770. )
  771. for item in items:
  772. key = (item['source'], item['id'])
  773. collection = collection_map.get(key)
  774. sample = sample_map.get(key)
  775. party = party_map.get(key)
  776. payment_summary = payment_summaries.get(item['id']) or {}
  777. transport = transport_by_sample.get(getattr(sample, 'id', ''))
  778. sample_code = getattr(sample, 'sample_code', '') or ''
  779. region_manager_name = user_names.get(
  780. getattr(collection, 'region_manager_user_id', ''), ''
  781. )
  782. item.update(
  783. motherName=item.get('customerName', ''),
  784. motherPhone=getattr(party, 'mother_phone', '') or '',
  785. motherIdCard=getattr(party, 'mother_id_card', '') or '',
  786. fatherName=getattr(party, 'father_name', '') or '',
  787. newbornSex=getattr(party, 'newborn_sex', '') or '',
  788. deliveryMode=getattr(party, 'delivery_mode', '') or '',
  789. newbornWeightGram=getattr(party, 'newborn_weight_gram', None),
  790. birthOrder=getattr(party, 'birth_order', None),
  791. newbornDeliveryTime=_fmt_dt(
  792. getattr(party, 'newborn_delivery_time', None)
  793. ),
  794. protocolStatus=item.get('status', ''),
  795. donationStatus=item.get('status', ''),
  796. regionName=region_names.get(getattr(collection, 'region_id', ''), ''),
  797. hospitalName=hospital_names.get(
  798. getattr(collection, 'hospital_id', ''), ''
  799. ),
  800. sampleCollectTime=_fmt_dt(
  801. getattr(collection, 'sample_collect_time', None)
  802. ),
  803. maternalBloodCollectTime=_fmt_dt(
  804. getattr(collection, 'maternal_blood_collect_time', None)
  805. ),
  806. salesUserName=user_names.get(
  807. getattr(collection, 'sales_user_id', ''), ''
  808. ),
  809. collectorUserName=user_names.get(item.get('collectorUserId', ''), ''),
  810. managerName=region_manager_name,
  811. regionManagerUserName=region_manager_name,
  812. sampleCode=sample_code,
  813. sampleTypeName=type_names.get(
  814. getattr(sample, 'sample_type_id', ''), ''
  815. ),
  816. coStored=bool(getattr(sample, 'is_special', 0)),
  817. labStorageCode=lab_by_key.get((item['source'], sample_code), ''),
  818. payMode=payment_summary.get('payMode', ''),
  819. firstPayTime=payment_summary.get('firstPayTransferTime', ''),
  820. transportMode=getattr(transport, 'transport_type', '') or '',
  821. transportModeLabel=transport_labels.get(
  822. getattr(transport, 'transport_type', '') or '', ''
  823. ),
  824. voidTypeLabel=void_type_labels.get(
  825. str(item.get('voidType') or ''), ''
  826. ),
  827. )
  828. def list_protocols(
  829. db: Session,
  830. *,
  831. ctx: MarketFieldContext,
  832. user_info: dict,
  833. page: int = 1,
  834. page_size: int = 10,
  835. keyword: Optional[str] = None,
  836. source: Optional[str] = None,
  837. protocol_status: Optional[str] = None,
  838. create_time_start: Optional[str] = None,
  839. create_time_end: Optional[str] = None,
  840. sample_collect_time_start: Optional[str] = None,
  841. sample_collect_time_end: Optional[str] = None,
  842. ) -> Tuple[List[dict], int]:
  843. if source and source not in SOURCES:
  844. raise ValueError('不支持的协议来源')
  845. search = str(keyword or '').strip()
  846. def date_value(raw: Optional[str], *, end: bool = False) -> Optional[datetime]:
  847. text = str(raw or '').strip()
  848. if not text:
  849. return None
  850. try:
  851. parsed = datetime.strptime(text, '%Y-%m-%d')
  852. except ValueError as exc:
  853. raise ValueError('日期格式无效,应为 YYYY-MM-DD') from exc
  854. return parsed + timedelta(days=1) if end else parsed
  855. created_from = date_value(create_time_start)
  856. created_until = date_value(create_time_end, end=True)
  857. collected_from = date_value(sample_collect_time_start)
  858. collected_until = date_value(sample_collect_time_end, end=True)
  859. status = str(protocol_status or '').strip()
  860. rows = []
  861. fetch_limit = max(1, page) * min(max(1, page_size), 100)
  862. total = 0
  863. if source in (None, SOURCE_CELL):
  864. query = apply_cell_protocol_scope(
  865. db.query(BizCollectionProtocol), db, ctx, user_info=user_info
  866. )
  867. if status:
  868. query = query.filter(BizCollectionProtocol.protocol_status == status)
  869. if created_from:
  870. query = query.filter(BizCollectionProtocol.create_time >= created_from)
  871. if created_until:
  872. query = query.filter(BizCollectionProtocol.create_time < created_until)
  873. if collected_from or collected_until:
  874. collection_conditions = [
  875. BizProtocolCollectionInfo.collection_protocol_id
  876. == BizCollectionProtocol.id,
  877. BizProtocolCollectionInfo.tenant_no == ctx.tenant_no,
  878. BizProtocolCollectionInfo.del_flag == 0,
  879. ]
  880. if collected_from:
  881. collection_conditions.append(
  882. BizProtocolCollectionInfo.sample_collect_time >= collected_from
  883. )
  884. if collected_until:
  885. collection_conditions.append(
  886. BizProtocolCollectionInfo.sample_collect_time < collected_until
  887. )
  888. query = query.filter(
  889. db.query(BizProtocolCollectionInfo.id)
  890. .filter(*collection_conditions)
  891. .exists()
  892. .correlate(BizCollectionProtocol)
  893. )
  894. if search:
  895. like = f'%{search}%'
  896. party_ids = db.query(
  897. BizProtocolPartyCustomer.collection_protocol_id
  898. ).filter(
  899. BizProtocolPartyCustomer.tenant_no == ctx.tenant_no,
  900. BizProtocolPartyCustomer.del_flag == 0,
  901. or_(
  902. BizProtocolPartyCustomer.mother_name.like(like),
  903. BizProtocolPartyCustomer.mother_id_card.like(like),
  904. BizProtocolPartyCustomer.mother_phone.like(like),
  905. ),
  906. )
  907. sample_ids = db.query(BizProtocolSample.collection_protocol_id).filter(
  908. BizProtocolSample.tenant_no == ctx.tenant_no,
  909. BizProtocolSample.del_flag == 0,
  910. BizProtocolSample.sample_code.like(like),
  911. )
  912. query = query.filter(
  913. or_(
  914. BizCollectionProtocol.protocol_no.like(like),
  915. BizCollectionProtocol.id.in_(party_ids),
  916. BizCollectionProtocol.id.in_(sample_ids),
  917. )
  918. )
  919. total += int(
  920. query.order_by(None)
  921. .with_entities(func.count(BizCollectionProtocol.id))
  922. .scalar()
  923. or 0
  924. )
  925. cell_rows = (
  926. query.order_by(
  927. BizCollectionProtocol.create_time.desc(),
  928. BizCollectionProtocol.id.desc(),
  929. )
  930. .limit(fetch_limit)
  931. .all()
  932. )
  933. names = _party_name_cell(
  934. db, [row.id for row in cell_rows], ctx.tenant_no
  935. )
  936. rows.extend(
  937. {
  938. 'id': row.id,
  939. 'source': SOURCE_CELL,
  940. 'code': row.protocol_no or '',
  941. 'protocolNo': row.protocol_no or '',
  942. 'status': row.protocol_status or '',
  943. 'collectDate': row.register_date or '',
  944. 'registerDate': row.register_date or '',
  945. 'protocolTotalAmount': str(row.protocol_total_amount or ''),
  946. 'paymentModelVersion': int(
  947. getattr(row, 'payment_model_version', None) or 1
  948. ),
  949. 'voidType': row.void_type or '',
  950. 'collectorUserId': row.collector_user_id or '',
  951. 'customerName': names.get(row.id, ''),
  952. 'createTime': _fmt_dt(row.create_time),
  953. '_created': row.create_time or datetime.min,
  954. }
  955. for row in cell_rows
  956. )
  957. if source in (None, SOURCE_DONATION):
  958. if status or collected_from or collected_until:
  959. donation_enabled = False
  960. else:
  961. donation_enabled = True
  962. if not donation_enabled:
  963. query = None
  964. else:
  965. query = apply_donation_scope(
  966. db.query(BizResearchDonation), db, ctx, user_info=user_info
  967. )
  968. if query is None:
  969. donation_rows = []
  970. else:
  971. if created_from:
  972. query = query.filter(BizResearchDonation.create_time >= created_from)
  973. if created_until:
  974. query = query.filter(BizResearchDonation.create_time < created_until)
  975. if query is not None and search:
  976. like = f'%{search}%'
  977. party_ids = db.query(
  978. BizResearchDonationParty.research_donation_id
  979. ).filter(
  980. BizResearchDonationParty.tenant_no == ctx.tenant_no,
  981. BizResearchDonationParty.del_flag == 0,
  982. or_(
  983. BizResearchDonationParty.mother_name.like(like),
  984. BizResearchDonationParty.mother_id_card.like(like),
  985. BizResearchDonationParty.mother_phone.like(like),
  986. ),
  987. )
  988. sample_ids = db.query(
  989. BizResearchDonationSample.research_donation_id
  990. ).filter(
  991. BizResearchDonationSample.tenant_no == ctx.tenant_no,
  992. BizResearchDonationSample.del_flag == 0,
  993. BizResearchDonationSample.sample_code.like(like),
  994. )
  995. query = query.filter(
  996. or_(
  997. BizResearchDonation.donation_no.like(like),
  998. BizResearchDonation.id.in_(party_ids),
  999. BizResearchDonation.id.in_(sample_ids),
  1000. )
  1001. )
  1002. if query is not None:
  1003. total += int(
  1004. query.order_by(None)
  1005. .with_entities(func.count(BizResearchDonation.id))
  1006. .scalar()
  1007. or 0
  1008. )
  1009. donation_rows = (
  1010. query.order_by(
  1011. BizResearchDonation.create_time.desc(),
  1012. BizResearchDonation.id.desc(),
  1013. )
  1014. .limit(fetch_limit)
  1015. .all()
  1016. )
  1017. names = _party_name_donation(
  1018. db, [row.id for row in donation_rows], ctx.tenant_no
  1019. )
  1020. rows.extend(
  1021. {
  1022. 'id': row.id,
  1023. 'source': SOURCE_DONATION,
  1024. 'code': row.donation_no or '',
  1025. 'protocolNo': row.donation_no or '',
  1026. 'donationNo': row.donation_no or '',
  1027. 'status': row.donation_status or '',
  1028. 'collectDate': row.donation_date or '',
  1029. 'donationDate': row.donation_date or '',
  1030. 'customerName': names.get(row.id, ''),
  1031. 'collectorUserId': row.collector_user_id or '',
  1032. 'createTime': _fmt_dt(row.create_time),
  1033. 'monthlyVerifyNo': row.monthly_verify_no or '',
  1034. 'voidType': row.void_type or '',
  1035. 'voidDesc': row.void_desc or '',
  1036. 'consentFormUrls': row.consent_form_urls or '',
  1037. 'infectiousDiseaseReportUrls': row.infectious_disease_report_urls or '',
  1038. 'attachmentUrls': row.attachment_urls or '',
  1039. 'remark': row.remark or '',
  1040. '_created': row.create_time or datetime.min,
  1041. }
  1042. for row in donation_rows
  1043. )
  1044. rows.sort(
  1045. key=lambda item: (item['_created'], item['id']), reverse=True
  1046. )
  1047. safe_page = max(1, page)
  1048. safe_size = min(max(1, page_size), 100)
  1049. page_rows = rows[(safe_page - 1) * safe_size : safe_page * safe_size]
  1050. for item in page_rows:
  1051. item.pop('_created', None)
  1052. _enrich_protocol_cards(db, page_rows, ctx.tenant_no)
  1053. return page_rows, total
  1054. def _attach_sample_eta(
  1055. sample_dicts: List[dict],
  1056. transport_by_sample_id: dict,
  1057. ) -> List[dict]:
  1058. for item in sample_dicts:
  1059. transport = transport_by_sample_id.get(str(item.get('id') or ''))
  1060. eta = ''
  1061. if transport is not None:
  1062. eta = cell_crud._fmt_dt(getattr(transport, 'eta_time', None))
  1063. item['etaTime'] = eta
  1064. item['transport'] = {'etaTime': eta} if eta else None
  1065. return sample_dicts
  1066. def _attach_sample_freight(
  1067. db: Session,
  1068. sample_dicts: List[dict],
  1069. *,
  1070. tenant_no: str,
  1071. sample_source: str,
  1072. ) -> List[dict]:
  1073. from app.crud import sample_freight as sample_freight_svc
  1074. ids = [str(item.get('id') or '').strip() for item in sample_dicts if item.get('id')]
  1075. freight_map = sample_freight_svc.freight_map_for_samples(
  1076. db,
  1077. tenant_no=tenant_no,
  1078. sample_source=sample_source,
  1079. sample_ids=ids,
  1080. money_as_string=True,
  1081. )
  1082. for item in sample_dicts:
  1083. sid = str(item.get('id') or '').strip()
  1084. freight = freight_map.get(sid)
  1085. if freight:
  1086. item['freight'] = freight
  1087. item['freightId'] = freight.get('id') or ''
  1088. else:
  1089. item['freight'] = None
  1090. item['freightId'] = ''
  1091. return sample_dicts
  1092. def _assert_sample_freight_targets(
  1093. db: Session,
  1094. *,
  1095. protocol_id: Optional[str],
  1096. samples: List[dict],
  1097. ctx: MarketFieldContext,
  1098. user_info: dict,
  1099. ) -> None:
  1100. """协议保存只允许保留原批次,或关联当前市场范围可访问的批次。"""
  1101. existing_samples = (
  1102. cell_crud.list_samples(db, protocol_id, ctx.tenant_no)
  1103. if protocol_id
  1104. else []
  1105. )
  1106. freight_by_sample = sample_freight_crud.freight_map_for_samples(
  1107. db,
  1108. tenant_no=ctx.tenant_no,
  1109. sample_source=SOURCE_CELL,
  1110. sample_ids=[row.id for row in existing_samples],
  1111. )
  1112. current_by_code = {
  1113. str(row.sample_code or '').strip(): str(
  1114. (freight_by_sample.get(row.id) or {}).get('id') or ''
  1115. )
  1116. for row in existing_samples
  1117. if str(row.sample_code or '').strip()
  1118. }
  1119. checked_targets = set()
  1120. for sample in samples:
  1121. code = str(sample.get('sample_code') or sample.get('sampleCode') or '').strip()
  1122. target_id = str(
  1123. sample.get('freight_id') or sample.get('freightId') or ''
  1124. ).strip()
  1125. draft = sample.get('freight_draft') or sample.get('freightDraft')
  1126. current_id = current_by_code.get(code, '')
  1127. if current_id and (draft or (target_id and target_id != current_id)):
  1128. raise ValueError('样本已关联运费批次,请先通过运费功能取消关联')
  1129. if not target_id or target_id == current_id or target_id in checked_targets:
  1130. continue
  1131. market_freight.assert_link_target_access(
  1132. db,
  1133. target_id,
  1134. ctx=ctx,
  1135. user_info=user_info,
  1136. )
  1137. checked_targets.add(target_id)
  1138. def _market_sample_payment_payload(
  1139. db: Session,
  1140. *,
  1141. row: BizCollectionProtocol,
  1142. body: MarketProtocolBody,
  1143. ctx: MarketFieldContext,
  1144. saved_samples: List[BizProtocolSample],
  1145. ) -> List[dict]:
  1146. """忽略客户端嵌套转账和样本 ID,只同步当前协议的缴费方案与期次。"""
  1147. raw_payments = [
  1148. item.model_dump(by_alias=True, exclude_none=False)
  1149. for item in (body.sample_payments or [])
  1150. ]
  1151. sample_by_code = {
  1152. str(sample.sample_code or '').strip(): sample
  1153. for sample in saved_samples
  1154. if str(sample.sample_code or '').strip()
  1155. }
  1156. current_payments = (
  1157. db.query(BizProtocolSamplePayment)
  1158. .filter(
  1159. BizProtocolSamplePayment.collection_protocol_id == row.id,
  1160. BizProtocolSamplePayment.tenant_no == ctx.tenant_no,
  1161. BizProtocolSamplePayment.del_flag == 0,
  1162. )
  1163. .all()
  1164. )
  1165. payment_by_id = {payment.id: payment for payment in current_payments}
  1166. payment_by_code = {
  1167. str(payment.sample_code or '').strip(): payment
  1168. for payment in current_payments
  1169. }
  1170. payment_ids = [payment.id for payment in current_payments]
  1171. schedules = (
  1172. db.query(BizProtocolPaymentSchedule)
  1173. .filter(
  1174. BizProtocolPaymentSchedule.sample_payment_id.in_(payment_ids or ['']),
  1175. BizProtocolPaymentSchedule.tenant_no == ctx.tenant_no,
  1176. BizProtocolPaymentSchedule.del_flag == 0,
  1177. )
  1178. .all()
  1179. )
  1180. schedule_by_payment_no = {
  1181. (schedule.sample_payment_id, int(schedule.schedule_no or 0)): schedule
  1182. for schedule in schedules
  1183. }
  1184. schedule_ids = [schedule.id for schedule in schedules]
  1185. transfers = (
  1186. db.query(BizProtocolPaymentTransfer)
  1187. .filter(
  1188. BizProtocolPaymentTransfer.schedule_id.in_(schedule_ids or ['']),
  1189. BizProtocolPaymentTransfer.tenant_no == ctx.tenant_no,
  1190. BizProtocolPaymentTransfer.del_flag == 0,
  1191. )
  1192. .all()
  1193. )
  1194. transfers_by_schedule = {}
  1195. for transfer in transfers:
  1196. transfers_by_schedule.setdefault(transfer.schedule_id, []).append(transfer)
  1197. seen_codes = set()
  1198. result = []
  1199. for raw in raw_payments:
  1200. code = str(raw.get('sampleCode') or '').strip()
  1201. if not code or code not in sample_by_code:
  1202. raise ValueError('样本缴费方案不属于当前协议样本')
  1203. if code in seen_codes:
  1204. raise ValueError('同一样本不能重复配置缴费方案')
  1205. seen_codes.add(code)
  1206. supplied_id = str(raw.get('id') or '').strip()
  1207. current = payment_by_id.get(supplied_id) if supplied_id else payment_by_code.get(code)
  1208. if supplied_id and (
  1209. current is None or str(current.sample_code or '').strip() != code
  1210. ):
  1211. raise ValueError('样本缴费方案不存在或不属于当前协议样本')
  1212. if current and payment_by_code.get(code) not in (None, current):
  1213. raise ValueError('样本缴费方案与当前协议样本不一致')
  1214. if current:
  1215. raw['id'] = current.id
  1216. else:
  1217. raw.pop('id', None)
  1218. raw['protocolSampleId'] = sample_by_code[code].id
  1219. incoming_schedules = raw.get('schedules') or []
  1220. incoming_nos = {
  1221. int(schedule.get('scheduleNo') or index + 1)
  1222. for index, schedule in enumerate(incoming_schedules)
  1223. }
  1224. current_nos = {
  1225. number
  1226. for payment_id, number in schedule_by_payment_no
  1227. if current and payment_id == current.id
  1228. }
  1229. current_transfers = [
  1230. transfer
  1231. for schedule in schedules
  1232. if current and schedule.sample_payment_id == current.id
  1233. for transfer in transfers_by_schedule.get(schedule.id, [])
  1234. ]
  1235. if current and incoming_nos != current_nos and current_transfers:
  1236. raise ValueError('存在转账记录时不可调整缴费期次结构')
  1237. sanitized_schedules = []
  1238. for index, schedule_raw in enumerate(incoming_schedules):
  1239. schedule = dict(schedule_raw)
  1240. number = int(schedule.get('scheduleNo') or index + 1)
  1241. existing_schedule = (
  1242. schedule_by_payment_no.get((current.id, number))
  1243. if current
  1244. else None
  1245. )
  1246. schedule.pop('id', None)
  1247. schedule['scheduleStatus'] = (
  1248. existing_schedule.schedule_status
  1249. if existing_schedule
  1250. else 'open'
  1251. )
  1252. schedule['transfers'] = (
  1253. [
  1254. {'id': transfer.id}
  1255. for transfer in transfers_by_schedule.get(existing_schedule.id, [])
  1256. ]
  1257. if existing_schedule
  1258. else []
  1259. )
  1260. sanitized_schedules.append(schedule)
  1261. raw['schedules'] = sanitized_schedules
  1262. result.append(raw)
  1263. return result
  1264. def _persist_sample_payments_if_any(
  1265. db: Session,
  1266. *,
  1267. row: BizCollectionProtocol,
  1268. body: MarketProtocolBody,
  1269. ctx: MarketFieldContext,
  1270. saved_samples: List[BizProtocolSample],
  1271. ) -> None:
  1272. """按数据库版本互斥保存 v1 整单缴费或 v2 按样本缴费方案。"""
  1273. if body.source != SOURCE_CELL:
  1274. if (
  1275. body.sample_payments is not None
  1276. or body.payment is not None
  1277. or body.payment_details is not None
  1278. ):
  1279. raise ValueError('科研捐赠不支持缴费方案')
  1280. return
  1281. version = int(getattr(row, 'payment_model_version', None) or 1)
  1282. if version < 2:
  1283. if body.sample_payments is not None:
  1284. raise ValueError('旧版 v1 协议不支持 samplePayments 样本缴费方案')
  1285. if body.payment is None and body.payment_details is None:
  1286. return
  1287. if body.payment is None and body.payment_details is not None:
  1288. existing_payment = cell_crud.get_payment_by_protocol_id(
  1289. db, row.id, ctx.tenant_no
  1290. )
  1291. if existing_payment is None:
  1292. raise ValueError('提交缴费明细前必须先提交缴费主表方案')
  1293. payment_details = _validate_v1_payment_detail_attachments(
  1294. db,
  1295. body.payment_details,
  1296. row=row,
  1297. ctx=ctx,
  1298. )
  1299. cell_crud.save_payment_with_details(
  1300. db,
  1301. row.id,
  1302. ctx.tenant_no,
  1303. ctx.user_id,
  1304. payment=body.payment.model_dump(
  1305. by_alias=False, exclude_unset=True, mode='json'
  1306. ) if body.payment is not None else None,
  1307. payment_details=payment_details,
  1308. commit=False,
  1309. )
  1310. return
  1311. if body.payment is not None or body.payment_details is not None:
  1312. raise ValueError('新版 v2 协议不支持 payment/paymentDetails 整单缴费方案')
  1313. if body.sample_payments is None:
  1314. return
  1315. raw = _market_sample_payment_payload(
  1316. db,
  1317. row=row,
  1318. body=body,
  1319. ctx=ctx,
  1320. saved_samples=saved_samples,
  1321. )
  1322. psp_crud.save_sample_payments_for_protocol(
  1323. db,
  1324. collection_protocol_id=row.id,
  1325. tenant_no=ctx.tenant_no,
  1326. user_id=ctx.user_id,
  1327. sample_payments=raw,
  1328. )
  1329. def _cell_detail(db: Session, row: BizCollectionProtocol, tenant_no: str) -> dict:
  1330. party = cell_crud.get_party_customer(db, row.id, tenant_no)
  1331. collection = cell_crud.get_collection_info(db, row.id, tenant_no)
  1332. samples = cell_crud.list_samples(db, row.id, tenant_no)
  1333. payment = cell_crud.get_payment_by_protocol_id(db, row.id, tenant_no)
  1334. transports = cell_crud.list_sample_transports(db, row.id, tenant_no)
  1335. transport_by_sample_id = {str(t.sample_id): t for t in transports}
  1336. # qc_task 先于 qc_work_order 初始化,避免两者历史互相导入时拿到半初始化模块。
  1337. from app.crud import qc_task as _qc_task_svc # noqa: F401
  1338. web_bundle = cell_crud.get_protocol_detail_bundle(db, row.id, tenant_no) or {}
  1339. web_samples = web_bundle.get('samples') or []
  1340. web_sample_by_id = {
  1341. str(item.get('id') or ''): item for item in web_samples if item.get('id')
  1342. }
  1343. web_sample_by_code = {
  1344. str(item.get('sampleCode') or ''): item
  1345. for item in web_samples
  1346. if item.get('sampleCode')
  1347. }
  1348. sample_dicts = _attach_sample_freight(
  1349. db,
  1350. _attach_sample_eta(
  1351. [cell_crud._sample_to_dict(item) for item in samples],
  1352. transport_by_sample_id,
  1353. ),
  1354. tenant_no=tenant_no,
  1355. sample_source=SOURCE_CELL,
  1356. )
  1357. lifecycle_keys = (
  1358. 'sampleReception',
  1359. 'productionReception',
  1360. 'qcInfo',
  1361. 'processQcInfoList',
  1362. 'productionInfo',
  1363. 'storageReleaseInfo',
  1364. )
  1365. for item in sample_dicts:
  1366. web_sample = web_sample_by_id.get(str(item.get('id') or '')) or web_sample_by_code.get(
  1367. str(item.get('sampleCode') or '')
  1368. )
  1369. if not web_sample:
  1370. continue
  1371. for key in lifecycle_keys:
  1372. item[key] = web_sample.get(key)
  1373. version = int(getattr(row, 'payment_model_version', None) or 1)
  1374. sample_payments = []
  1375. if version >= 2:
  1376. sample_payments = psp_crud.get_sample_payments_bundle(
  1377. db,
  1378. collection_protocol_id=row.id,
  1379. tenant_no=tenant_no,
  1380. money_as_string=True,
  1381. )
  1382. source_presign_id = getattr(row, 'source_presign_order_id', None)
  1383. storage_cert = cell_crud.get_storage_cert(db, row.id, tenant_no)
  1384. storage_cert_dict = (
  1385. cell_crud._storage_cert_to_dict(storage_cert) if storage_cert else None
  1386. )
  1387. if storage_cert_dict:
  1388. hid = str(storage_cert_dict.get('handlerUserId') or '').strip()
  1389. if hid:
  1390. hu = (
  1391. db.query(SysUser)
  1392. .filter(
  1393. SysUser.id == hid,
  1394. SysUser.tenant_no == tenant_no,
  1395. SysUser.del_flag == 0,
  1396. )
  1397. .first()
  1398. )
  1399. storage_cert_dict['handlerUserName'] = (
  1400. (hu.nick_name or '') if hu else ''
  1401. )
  1402. else:
  1403. storage_cert_dict['handlerUserName'] = ''
  1404. delivery_dt = getattr(party, 'newborn_delivery_time', None) if party else None
  1405. fullmoon = cell_crud.get_fullmoon_todo(db, row.id, tenant_no)
  1406. fullmoon_dict = cell_crud._fullmoon_todo_detail_dict(
  1407. fullmoon, newborn_delivery_time=delivery_dt
  1408. )
  1409. hid2 = str(fullmoon_dict.get('handlerUserId') or '').strip()
  1410. if hid2:
  1411. hu2 = (
  1412. db.query(SysUser)
  1413. .filter(
  1414. SysUser.id == hid2,
  1415. SysUser.tenant_no == tenant_no,
  1416. SysUser.del_flag == 0,
  1417. )
  1418. .first()
  1419. )
  1420. fullmoon_dict['handlerUserName'] = (hu2.nick_name or '') if hu2 else ''
  1421. else:
  1422. fullmoon_dict['handlerUserName'] = ''
  1423. audits, _ = cell_crud.list_audits(
  1424. db,
  1425. page=1,
  1426. page_size=100,
  1427. collection_protocol_id=row.id,
  1428. tenant_no=tenant_no,
  1429. )
  1430. basic_dict = cell_crud._protocol_to_dict(row)
  1431. basic_dict['protocolTotalAmount'] = _fixed_money(row.protocol_total_amount)
  1432. payment_dict = cell_crud._payment_to_dict(payment) if payment else None
  1433. if payment_dict is not None:
  1434. payment_dict['contractAmount'] = _fixed_money(payment.contract_amount)
  1435. payment_details = list(web_bundle.get('paymentDetails') or [])
  1436. if payment:
  1437. detail_models = cell_crud.list_payment_details(db, payment.id, tenant_no)
  1438. model_by_id = {str(item.id): item for item in detail_models}
  1439. for item in payment_details:
  1440. model = model_by_id.get(str(item.get('id') or ''))
  1441. if model:
  1442. for key, attr in (
  1443. ('dueAmount', 'due_amount'),
  1444. ('transferAmount', 'transfer_amount'),
  1445. ('refundAmount', 'refund_amount'),
  1446. ):
  1447. item[key] = _fixed_money(getattr(model, attr, None))
  1448. sample_model_by_id = {str(item.id): item for item in samples}
  1449. for item in sample_dicts:
  1450. model = sample_model_by_id.get(str(item.get('id') or ''))
  1451. if model:
  1452. item['price'] = _fixed_money(model.price)
  1453. item['originalPrice'] = _fixed_money(model.original_price)
  1454. detail = {
  1455. 'source': SOURCE_CELL,
  1456. 'basic': basic_dict,
  1457. 'collection': cell_crud._collection_info_to_dict(collection)
  1458. if collection
  1459. else None,
  1460. 'customer': cell_crud._party_customer_to_dict(party) if party else None,
  1461. 'samples': sample_dicts,
  1462. 'payment': payment_dict,
  1463. 'paymentModelVersion': version,
  1464. 'samplePayments': sample_payments,
  1465. 'paymentDetails': payment_details,
  1466. 'depositTransfers': psp_crud.list_deposit_transfers_for_protocol(
  1467. db,
  1468. source_presign_order_id=source_presign_id,
  1469. tenant_no=tenant_no,
  1470. money_as_string=True,
  1471. ),
  1472. 'presignDepositHint': psp_crud.get_presign_deposit_hint(
  1473. db,
  1474. source_presign_order_id=source_presign_id,
  1475. tenant_no=tenant_no,
  1476. money_as_string=True,
  1477. ),
  1478. 'storageCert': storage_cert_dict,
  1479. 'fullmoonTodo': fullmoon_dict,
  1480. 'audits': audits,
  1481. 'attachments': {
  1482. 'protocolAttachments': row.protocol_attachments or '',
  1483. 'consentFormUrls': row.consent_form_urls or '',
  1484. 'healthSurveyFormUrls': row.health_survey_form_urls or '',
  1485. },
  1486. }
  1487. _enrich_transfer_type_labels(db, detail, tenant_no)
  1488. _enrich_protocol_detail_labels(db, detail, tenant_no)
  1489. return detail
  1490. def _donation_detail(
  1491. db: Session, row: BizResearchDonation, tenant_no: str
  1492. ) -> dict:
  1493. # 与 Web 查看弹窗共用同一份详情 DTO,避免移动端再次拼装时遗漏生命周期字段。
  1494. from app.crud import qc_task as _qc_task_svc # noqa: F401
  1495. web_bundle = donation_crud.get_donation_detail(db, row.id, tenant_no) or {}
  1496. basic = dict(web_bundle.get('donation') or donation_crud._donation_to_dict(row))
  1497. basic['convertTime'] = basic.get('convertTime') or basic.get('toStorageTime') or ''
  1498. basic['convertDesc'] = basic.get('convertDesc') or basic.get('toStorageDesc') or ''
  1499. audits = donation_crud.list_audits(
  1500. db,
  1501. tenant_no=tenant_no,
  1502. page=1,
  1503. page_size=100,
  1504. research_donation_id=row.id,
  1505. )
  1506. detail = {
  1507. 'source': SOURCE_DONATION,
  1508. 'basic': basic,
  1509. 'collection': web_bundle.get('collection'),
  1510. 'customer': web_bundle.get('party'),
  1511. 'samples': list(web_bundle.get('samples') or []),
  1512. 'audits': list(audits.get('list') or []),
  1513. 'attachments': {
  1514. 'consentFormUrls': basic.get('consentFormUrls') or '',
  1515. 'attachmentUrls': basic.get('attachmentUrls') or '',
  1516. 'infectiousDiseaseReportUrls': basic.get('infectiousDiseaseReportUrls') or '',
  1517. },
  1518. }
  1519. _enrich_protocol_detail_labels(db, detail, tenant_no)
  1520. return detail
  1521. def _enrich_transfer_type_labels(
  1522. db: Session, detail: dict, tenant_no: str
  1523. ) -> None:
  1524. """批量解析协议内所有转账方式;未知字典值保留原编码。"""
  1525. label_map = {
  1526. str(item.get('value') or ''): str(item.get('label') or '')
  1527. for item in _dict_options(db, tenant_no, 'zzfs')
  1528. }
  1529. def apply(row: dict) -> None:
  1530. code = str(row.get('transferType') or '').strip()
  1531. if code:
  1532. row['transferTypeLabel'] = (
  1533. label_map.get(code)
  1534. or str(row.get('transferTypeLabel') or '').strip()
  1535. or code
  1536. )
  1537. for row in detail.get('depositTransfers') or []:
  1538. apply(row)
  1539. for row in detail.get('paymentDetails') or []:
  1540. apply(row)
  1541. for payment in detail.get('samplePayments') or []:
  1542. for schedule in payment.get('schedules') or []:
  1543. for row in schedule.get('transfers') or []:
  1544. apply(row)
  1545. def _enrich_protocol_detail_labels(
  1546. db: Session, detail: dict, tenant_no: str
  1547. ) -> None:
  1548. """补齐 Web 详情使用的主数据名称,移动端不直接展示内部 ID。"""
  1549. basic = detail.get('basic') or {}
  1550. collection = detail.get('collection') or {}
  1551. samples = detail.get('samples') or []
  1552. basic['voidTypeLabel'] = resolve_void_type_label(
  1553. db,
  1554. tenant_no,
  1555. str(basic.get('voidType') or ''),
  1556. )
  1557. region_id = str(collection.get('regionId') or '').strip()
  1558. hospital_id = str(collection.get('hospitalId') or '').strip()
  1559. if region_id:
  1560. region = (
  1561. db.query(BizCollectionRegion)
  1562. .filter(
  1563. BizCollectionRegion.id == region_id,
  1564. BizCollectionRegion.tenant_no == tenant_no,
  1565. )
  1566. .first()
  1567. )
  1568. collection['regionName'] = region.region_name if region else ''
  1569. if hospital_id:
  1570. hospital = (
  1571. db.query(BizCollectionHospital)
  1572. .filter(
  1573. BizCollectionHospital.id == hospital_id,
  1574. BizCollectionHospital.tenant_no == tenant_no,
  1575. )
  1576. .first()
  1577. )
  1578. collection['hospitalName'] = hospital.hospital_name if hospital else ''
  1579. user_ids = {
  1580. str(value or '').strip()
  1581. for value in (
  1582. basic.get('collectorUserId'),
  1583. collection.get('salesUserId'),
  1584. collection.get('regionManagerUserId'),
  1585. )
  1586. if str(value or '').strip()
  1587. }
  1588. user_names = {
  1589. row.id: row.nick_name or ''
  1590. for row in db.query(SysUser).filter(
  1591. SysUser.id.in_(user_ids or ['']),
  1592. SysUser.tenant_no == tenant_no,
  1593. )
  1594. }
  1595. basic['collectorUserName'] = user_names.get(
  1596. str(basic.get('collectorUserId') or ''), ''
  1597. )
  1598. collection['salesUserName'] = user_names.get(
  1599. str(collection.get('salesUserId') or ''), ''
  1600. )
  1601. collection['regionManagerUserName'] = user_names.get(
  1602. str(collection.get('regionManagerUserId') or ''), ''
  1603. )
  1604. type_ids = {
  1605. str(item.get('sampleTypeId') or '').strip()
  1606. for item in samples
  1607. if str(item.get('sampleTypeId') or '').strip()
  1608. }
  1609. type_names = {
  1610. row.id: row.type_name or ''
  1611. for row in db.query(BizCellSampleType).filter(
  1612. BizCellSampleType.id.in_(type_ids or ['']),
  1613. or_(
  1614. BizCellSampleType.tenant_no == tenant_no,
  1615. BizCellSampleType.tenant_no == '',
  1616. ),
  1617. )
  1618. }
  1619. unit_ids = {
  1620. str(item.get('unitId') or '').strip()
  1621. for item in samples
  1622. if str(item.get('unitId') or '').strip()
  1623. }
  1624. unit_names = {
  1625. row.id: row.unit_name or ''
  1626. for row in db.query(BizItemUnit).filter(
  1627. BizItemUnit.id.in_(unit_ids or ['']),
  1628. BizItemUnit.tenant_no == tenant_no,
  1629. )
  1630. }
  1631. for item in samples:
  1632. item['sampleTypeName'] = type_names.get(
  1633. str(item.get('sampleTypeId') or ''),
  1634. str(item.get('sampleTypeName') or ''),
  1635. )
  1636. item['unitName'] = unit_names.get(
  1637. str(item.get('unitId') or ''),
  1638. str(item.get('unitName') or ''),
  1639. )
  1640. def get_protocol(
  1641. db: Session,
  1642. *,
  1643. source: Optional[str],
  1644. protocol_id: str,
  1645. ctx: MarketFieldContext,
  1646. user_info: dict,
  1647. ) -> dict:
  1648. if source == SOURCE_CELL:
  1649. row = assert_cell_protocol_access(
  1650. db, protocol_id, ctx, user_info=user_info
  1651. )
  1652. return _cell_detail(db, row, ctx.tenant_no)
  1653. if source == SOURCE_DONATION:
  1654. row = assert_donation_access(db, protocol_id, ctx, user_info=user_info)
  1655. return _donation_detail(db, row, ctx.tenant_no)
  1656. if source is None:
  1657. cell = (
  1658. apply_cell_protocol_scope(
  1659. db.query(BizCollectionProtocol), db, ctx, user_info=user_info
  1660. )
  1661. .filter(BizCollectionProtocol.id == protocol_id)
  1662. .first()
  1663. )
  1664. if cell is not None:
  1665. return _cell_detail(db, cell, ctx.tenant_no)
  1666. donation = (
  1667. apply_donation_scope(
  1668. db.query(BizResearchDonation), db, ctx, user_info=user_info
  1669. )
  1670. .filter(BizResearchDonation.id == protocol_id)
  1671. .first()
  1672. )
  1673. if donation is not None:
  1674. return _donation_detail(db, donation, ctx.tenant_no)
  1675. raise HTTPException(status_code=404, detail='数据不存在或无权访问')
  1676. raise ValueError('不支持的协议来源')
  1677. def _lock_cell_protocol_access(
  1678. db: Session,
  1679. protocol_id: str,
  1680. ctx: MarketFieldContext,
  1681. *,
  1682. user_info: dict,
  1683. ) -> BizCollectionProtocol:
  1684. row = (
  1685. apply_cell_protocol_scope(
  1686. db.query(BizCollectionProtocol), db, ctx, user_info=user_info
  1687. )
  1688. .filter(BizCollectionProtocol.id == protocol_id)
  1689. .populate_existing()
  1690. .with_for_update()
  1691. .first()
  1692. )
  1693. if row is None:
  1694. raise HTTPException(status_code=404, detail='数据不存在或无权访问')
  1695. return row
  1696. def _lock_donation_access(
  1697. db: Session,
  1698. protocol_id: str,
  1699. ctx: MarketFieldContext,
  1700. *,
  1701. user_info: dict,
  1702. ) -> BizResearchDonation:
  1703. row = (
  1704. apply_donation_scope(
  1705. db.query(BizResearchDonation), db, ctx, user_info=user_info
  1706. )
  1707. .filter(BizResearchDonation.id == protocol_id)
  1708. .populate_existing()
  1709. .with_for_update()
  1710. .first()
  1711. )
  1712. if row is None:
  1713. raise HTTPException(status_code=404, detail='数据不存在或无权访问')
  1714. return row
  1715. def audit_protocol(
  1716. db: Session,
  1717. *,
  1718. source: str,
  1719. protocol_id: str,
  1720. audit_status: str,
  1721. audit_remark: Optional[str],
  1722. ctx: MarketFieldContext,
  1723. user_info: dict,
  1724. ) -> dict:
  1725. if source == SOURCE_CELL:
  1726. row = assert_cell_protocol_access(db, protocol_id, ctx, user_info=user_info)
  1727. if 'audit' not in allowed_actions('protocol', status=row.protocol_status or ''):
  1728. raise ValueError('当前状态不可审核')
  1729. cell_crud.create_audit(
  1730. db,
  1731. collection_protocol_id=protocol_id,
  1732. audit_status=audit_status,
  1733. audit_remark=audit_remark,
  1734. tenant_no=ctx.tenant_no,
  1735. user_id=ctx.user_id,
  1736. )
  1737. return {'id': protocol_id, 'source': source, 'protocolNo': row.protocol_no or ''}
  1738. if source == SOURCE_DONATION:
  1739. row = assert_donation_access(db, protocol_id, ctx, user_info=user_info)
  1740. if 'audit' not in allowed_actions('protocol', status=row.donation_status or ''):
  1741. raise ValueError('当前状态不可审核')
  1742. donation_crud.submit_audit(
  1743. db,
  1744. protocol_id,
  1745. audit_status=audit_status,
  1746. audit_remark=audit_remark,
  1747. tenant_no=ctx.tenant_no,
  1748. user_id=ctx.user_id,
  1749. )
  1750. return {'id': protocol_id, 'source': source, 'donationNo': row.donation_no or ''}
  1751. raise ValueError('不支持的协议来源')
  1752. def delete_protocol(
  1753. db: Session,
  1754. *,
  1755. source: str,
  1756. protocol_id: str,
  1757. ctx: MarketFieldContext,
  1758. user_info: dict,
  1759. ) -> None:
  1760. if source == SOURCE_CELL:
  1761. _lock_cell_protocol_access(
  1762. db, protocol_id, ctx, user_info=user_info
  1763. )
  1764. cell_crud.soft_delete_collection_protocol(
  1765. db, protocol_id, ctx.tenant_no, user_id=ctx.user_id
  1766. )
  1767. return
  1768. if source == SOURCE_DONATION:
  1769. _lock_donation_access(
  1770. db, protocol_id, ctx, user_info=user_info
  1771. )
  1772. donation_crud.delete_donation(
  1773. db, protocol_id, ctx.tenant_no, user_id=ctx.user_id
  1774. )
  1775. return
  1776. raise ValueError('不支持的协议来源')
  1777. def create_protocol(
  1778. db: Session,
  1779. *,
  1780. body: MarketProtocolBody,
  1781. ctx: MarketFieldContext,
  1782. user_info: dict,
  1783. ) -> dict:
  1784. if body.source == SOURCE_DONATION and (
  1785. body.sample_payments is not None
  1786. or body.payment is not None
  1787. or body.payment_details is not None
  1788. ):
  1789. raise ValueError('科研捐赠不支持缴费方案')
  1790. customer, collection, samples, attachments = _normalize_write(
  1791. db, body=body, ctx=ctx
  1792. )
  1793. _assert_customer_link_policy(db, customer, ctx=ctx, user_info=user_info)
  1794. dept_id = _current_dept_id(user_info)
  1795. try:
  1796. if body.source == SOURCE_CELL:
  1797. _assert_sample_freight_targets(
  1798. db,
  1799. protocol_id=None,
  1800. samples=samples,
  1801. ctx=ctx,
  1802. user_info=user_info,
  1803. )
  1804. row = cell_crud.create_collection_protocol(
  1805. db,
  1806. protocol_no=body.protocol_no or '',
  1807. protocol_attachments=attachments.get('protocol_attachments'),
  1808. consent_form_urls=attachments.get('consent_form_urls'),
  1809. health_survey_form_urls=attachments.get(
  1810. 'health_survey_form_urls'
  1811. ),
  1812. register_date=body.register_date,
  1813. collector_user_id=ctx.user_id
  1814. if ctx.scope_kind == 'specialist'
  1815. else body.collector_user_id,
  1816. protocol_total_amount=body.protocol_total_amount,
  1817. remark=body.remark,
  1818. tenant_no=ctx.tenant_no,
  1819. user_id=ctx.user_id,
  1820. create_dept_id=dept_id,
  1821. commit=False,
  1822. )
  1823. attachments = _validate_mobile_attachments(
  1824. db,
  1825. attachments,
  1826. ctx=ctx,
  1827. creating=True,
  1828. business_id=row.id,
  1829. )
  1830. row.protocol_attachments = attachments.get('protocol_attachments')
  1831. row.consent_form_urls = attachments.get('consent_form_urls')
  1832. row.health_survey_form_urls = attachments.get(
  1833. 'health_survey_form_urls'
  1834. )
  1835. db.add(row)
  1836. cell_crud.upsert_party_customer(
  1837. db,
  1838. row.id,
  1839. ctx.tenant_no,
  1840. ctx.user_id,
  1841. commit=False,
  1842. create_dept_id=dept_id,
  1843. **customer,
  1844. )
  1845. cell_crud.upsert_collection_info(
  1846. db,
  1847. row.id,
  1848. ctx.tenant_no,
  1849. ctx.user_id,
  1850. commit=False,
  1851. create_dept_id=dept_id,
  1852. **collection,
  1853. )
  1854. saved_samples = cell_crud.save_samples(
  1855. db,
  1856. row.id,
  1857. ctx.tenant_no,
  1858. ctx.user_id,
  1859. samples,
  1860. create_dept_id=dept_id,
  1861. commit=False,
  1862. )
  1863. _persist_sample_payments_if_any(
  1864. db,
  1865. row=row,
  1866. body=body,
  1867. ctx=ctx,
  1868. saved_samples=saved_samples,
  1869. )
  1870. assert_cell_protocol_access(db, row.id, ctx, user_info=user_info)
  1871. db.commit()
  1872. db.refresh(row)
  1873. return _cell_detail(db, row, ctx.tenant_no)
  1874. if body.sample_payments:
  1875. raise ValueError('科研捐赠不支持样本缴费方案')
  1876. data = {
  1877. 'donation_no': body.donation_no or '',
  1878. 'donation_date': body.donation_date,
  1879. 'collector_user_id': ctx.user_id
  1880. if ctx.scope_kind == 'specialist'
  1881. else body.collector_user_id,
  1882. 'remark': body.remark,
  1883. 'party': customer,
  1884. 'collection': collection,
  1885. 'samples': samples,
  1886. 'consent_form_urls': attachments.get('consent_form_urls'),
  1887. 'attachment_urls': attachments.get('attachment_urls'),
  1888. 'infectious_disease_report_urls': attachments.get(
  1889. 'infectious_disease_report_urls'
  1890. ),
  1891. }
  1892. row = donation_crud.create_donation(
  1893. db,
  1894. data=data,
  1895. tenant_no=ctx.tenant_no,
  1896. user_id=ctx.user_id,
  1897. create_dept_id=dept_id,
  1898. commit=False,
  1899. sync_customers=False,
  1900. )
  1901. attachments = _validate_mobile_attachments(
  1902. db,
  1903. attachments,
  1904. ctx=ctx,
  1905. creating=True,
  1906. business_id=row.id,
  1907. )
  1908. row.consent_form_urls = attachments.get('consent_form_urls')
  1909. row.attachment_urls = attachments.get('attachment_urls')
  1910. row.infectious_disease_report_urls = attachments.get(
  1911. 'infectious_disease_report_urls'
  1912. )
  1913. db.add(row)
  1914. assert_donation_access(db, row.id, ctx, user_info=user_info)
  1915. db.commit()
  1916. db.refresh(row)
  1917. return _donation_detail(db, row, ctx.tenant_no)
  1918. except Exception:
  1919. db.rollback()
  1920. raise
  1921. def update_protocol(
  1922. db: Session,
  1923. *,
  1924. source: str,
  1925. protocol_id: str,
  1926. body: MarketProtocolBody,
  1927. ctx: MarketFieldContext,
  1928. user_info: dict,
  1929. ) -> dict:
  1930. if body.source != source:
  1931. raise ValueError('请求来源与路径来源不一致')
  1932. if source == SOURCE_DONATION and (
  1933. body.sample_payments is not None
  1934. or body.payment is not None
  1935. or body.payment_details is not None
  1936. ):
  1937. raise ValueError('科研捐赠不支持缴费方案')
  1938. dept_id = _current_dept_id(user_info)
  1939. try:
  1940. if source == SOURCE_CELL:
  1941. row = _lock_cell_protocol_access(
  1942. db, protocol_id, ctx, user_info=user_info
  1943. )
  1944. current_collection = cell_crud.get_collection_info(
  1945. db, row.id, ctx.tenant_no
  1946. )
  1947. current_party = cell_crud.get_party_customer(
  1948. db, row.id, ctx.tenant_no
  1949. )
  1950. current_samples = cell_crud.list_samples(
  1951. db, row.id, ctx.tenant_no
  1952. )
  1953. customer, collection, samples, attachments = _normalize_write(
  1954. db,
  1955. body=body,
  1956. ctx=ctx,
  1957. current_collection=current_collection,
  1958. current_samples=current_samples,
  1959. )
  1960. if body.samples is not None:
  1961. _assert_sample_freight_targets(
  1962. db,
  1963. protocol_id=row.id,
  1964. samples=samples,
  1965. ctx=ctx,
  1966. user_info=user_info,
  1967. )
  1968. attachments = _validate_mobile_attachments(
  1969. db,
  1970. attachments,
  1971. ctx=ctx,
  1972. creating=False,
  1973. existing={
  1974. 'protocol_attachments': row.protocol_attachments,
  1975. 'consent_form_urls': row.consent_form_urls,
  1976. 'health_survey_form_urls': row.health_survey_form_urls,
  1977. },
  1978. business_id=row.id,
  1979. )
  1980. _assert_customer_link_policy(
  1981. db, customer, ctx=ctx, user_info=user_info
  1982. )
  1983. cell_crud.update_collection_protocol(
  1984. db,
  1985. row.id,
  1986. tenant_no=ctx.tenant_no,
  1987. user_id=ctx.user_id,
  1988. protocol_no=body.protocol_no,
  1989. protocol_attachments=attachments.get('protocol_attachments'),
  1990. consent_form_urls=attachments.get('consent_form_urls'),
  1991. health_survey_form_urls=attachments.get(
  1992. 'health_survey_form_urls'
  1993. ),
  1994. register_date=body.register_date,
  1995. collector_user_id=ctx.user_id
  1996. if ctx.scope_kind == 'specialist'
  1997. else body.collector_user_id,
  1998. protocol_total_amount=body.protocol_total_amount,
  1999. remark=body.remark,
  2000. commit=False,
  2001. )
  2002. if body.customer is not None:
  2003. if current_party is not None:
  2004. customer = {
  2005. **cell_crud._normalize_fields(
  2006. cell_crud._party_customer_to_dict(current_party)
  2007. ),
  2008. **customer,
  2009. }
  2010. for metadata_key in (
  2011. 'id',
  2012. 'collection_protocol_id',
  2013. 'tenant_no',
  2014. 'order_num',
  2015. 'create_time',
  2016. 'update_time',
  2017. ):
  2018. customer.pop(metadata_key, None)
  2019. newborn_delivery_time = customer.get(
  2020. 'newborn_delivery_time'
  2021. )
  2022. if isinstance(newborn_delivery_time, str):
  2023. if newborn_delivery_time.strip():
  2024. customer['newborn_delivery_time'] = parse_datetime(
  2025. newborn_delivery_time
  2026. )
  2027. else:
  2028. customer.pop('newborn_delivery_time', None)
  2029. cell_crud.upsert_party_customer(
  2030. db,
  2031. row.id,
  2032. ctx.tenant_no,
  2033. ctx.user_id,
  2034. commit=False,
  2035. create_dept_id=dept_id,
  2036. **customer,
  2037. )
  2038. if body.collection is not None:
  2039. cell_crud.upsert_collection_info(
  2040. db,
  2041. row.id,
  2042. ctx.tenant_no,
  2043. ctx.user_id,
  2044. commit=False,
  2045. create_dept_id=dept_id,
  2046. **collection,
  2047. )
  2048. saved_samples = current_samples
  2049. if body.samples is not None:
  2050. saved_samples = cell_crud.save_samples(
  2051. db,
  2052. row.id,
  2053. ctx.tenant_no,
  2054. ctx.user_id,
  2055. samples,
  2056. create_dept_id=dept_id,
  2057. commit=False,
  2058. )
  2059. _persist_sample_payments_if_any(
  2060. db,
  2061. row=row,
  2062. body=body,
  2063. ctx=ctx,
  2064. saved_samples=saved_samples,
  2065. )
  2066. row = assert_cell_protocol_access(
  2067. db, row.id, ctx, user_info=user_info
  2068. )
  2069. db.commit()
  2070. db.refresh(row)
  2071. return _cell_detail(db, row, ctx.tenant_no)
  2072. row = _lock_donation_access(
  2073. db, protocol_id, ctx, user_info=user_info
  2074. )
  2075. current_collection = donation_crud.get_collection(
  2076. db, row.id, ctx.tenant_no
  2077. )
  2078. current_party = donation_crud.get_party(db, row.id, ctx.tenant_no)
  2079. current_samples = donation_crud.list_samples(
  2080. db, row.id, ctx.tenant_no
  2081. )
  2082. customer, collection, samples, attachments = _normalize_write(
  2083. db,
  2084. body=body,
  2085. ctx=ctx,
  2086. current_collection=current_collection,
  2087. current_samples=current_samples,
  2088. )
  2089. attachments = _validate_mobile_attachments(
  2090. db,
  2091. attachments,
  2092. ctx=ctx,
  2093. creating=False,
  2094. existing={
  2095. 'consent_form_urls': row.consent_form_urls,
  2096. 'attachment_urls': row.attachment_urls,
  2097. 'infectious_disease_report_urls': row.infectious_disease_report_urls,
  2098. },
  2099. business_id=row.id,
  2100. )
  2101. _assert_customer_link_policy(
  2102. db, customer, ctx=ctx, user_info=user_info
  2103. )
  2104. if body.customer is not None and current_party is not None:
  2105. customer = {
  2106. **donation_crud._normalize_fields(
  2107. donation_crud._party_to_dict(current_party)
  2108. ),
  2109. **customer,
  2110. }
  2111. if body.collection is not None and current_collection is not None:
  2112. collection = {
  2113. **donation_crud._normalize_fields(
  2114. donation_crud._collection_to_dict(current_collection)
  2115. ),
  2116. **collection,
  2117. }
  2118. data = {
  2119. 'donation_no': body.donation_no,
  2120. 'donation_date': body.donation_date,
  2121. 'collector_user_id': ctx.user_id
  2122. if ctx.scope_kind == 'specialist'
  2123. else body.collector_user_id,
  2124. 'remark': body.remark,
  2125. 'consent_form_urls': attachments.get('consent_form_urls'),
  2126. 'attachment_urls': attachments.get('attachment_urls'),
  2127. 'infectious_disease_report_urls': attachments.get(
  2128. 'infectious_disease_report_urls'
  2129. ),
  2130. }
  2131. if body.customer is not None:
  2132. data['party'] = customer
  2133. if body.collection is not None:
  2134. data['collection'] = collection
  2135. if body.samples is not None:
  2136. data['samples'] = samples
  2137. data = {key: value for key, value in data.items() if value is not None}
  2138. row = donation_crud.update_donation(
  2139. db,
  2140. row.id,
  2141. data=data,
  2142. tenant_no=ctx.tenant_no,
  2143. user_id=ctx.user_id,
  2144. create_dept_id=dept_id,
  2145. commit=False,
  2146. sync_customers=False,
  2147. )
  2148. row = assert_donation_access(db, row.id, ctx, user_info=user_info)
  2149. db.commit()
  2150. db.refresh(row)
  2151. return _donation_detail(db, row, ctx.tenant_no)
  2152. except Exception:
  2153. db.rollback()
  2154. raise