pilot_infusion_schedule_mgmt.py 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178
  1. """中试输注计划管理 CRUD(输注计划列表、详情、状态变更、编辑)"""
  2. from __future__ import annotations
  3. import json
  4. import uuid
  5. from datetime import datetime
  6. from typing import Any, Dict, List, Optional
  7. from sqlalchemy import and_, desc, func, or_
  8. from sqlalchemy.orm import Session
  9. from app.core.utils import generate_uuid
  10. from app.models.models import (
  11. BizChannelAgreementProductPrice,
  12. BizChannelServiceOrder,
  13. BizChannelServiceOrderProduct,
  14. BizChannelServiceOrderTxn,
  15. BizPilotApplication,
  16. BizPilotInfusionPlan,
  17. BizPilotInfusionSchedule,
  18. BizPilotInfusionScheduleProduct,
  19. BizPilotPatient,
  20. BizProductionWorkOrder,
  21. BizQcWorkOrder,
  22. )
  23. from app.crud.pilot_service import (
  24. _get_or_create_channel_account,
  25. _reduce_channel_product_quota,
  26. _resolve_agreement_price_cell_type,
  27. )
  28. from app.crud import outbound_handover as handover_svc
  29. from app.crud import outbound_release_review as orr_svc
  30. from app.crud import pilot_infusion_confirm as confirm_svc
  31. # ────────────────────────────────────────────
  32. # Status transition map
  33. # ────────────────────────────────────────────
  34. VALID_TRANSITIONS: Dict[str, set] = {
  35. "dtz": {"yrqr", "yqx"},
  36. "yrqr": {"ywc", "yqx"},
  37. }
  38. QC_VALID_TRANSITIONS: Dict[str, set] = {
  39. "dzc": {"yzj", "yqx"},
  40. }
  41. # ────────────────────────────────────────────
  42. # Helpers: _row_to_dict
  43. # ────────────────────────────────────────────
  44. def _row_to_dict_schedule(
  45. row,
  46. application=None,
  47. plan=None,
  48. patient=None,
  49. products=None,
  50. service_order=None,
  51. plan_meta: Optional[Dict[str, Any]] = None,
  52. ) -> Dict[str, Any]:
  53. course = _resolve_course_display(row, plan, plan_meta)
  54. d: Dict[str, Any] = {
  55. "id": row.id,
  56. "infusionPlanId": row.infusion_plan_id or "",
  57. "sortNo": course.get("sortNo"),
  58. "totalCourseCount": course.get("totalCourseCount"),
  59. "cellType": row.cell_type or "",
  60. "specText": row.spec_text or "",
  61. "infusionTime": row.infusion_time.strftime("%Y-%m-%d %H:%M:%S") if row.infusion_time else "",
  62. "infusionLocation": row.infusion_location or "",
  63. "infusionMethod": row.infusion_method or "",
  64. "scheduleStatus": row.schedule_status or "",
  65. "infusionStatus": row.infusion_status or "",
  66. "cancelReason": row.cancel_reason or "",
  67. "qcStatus": row.qc_status or "",
  68. "attachments": row.attachments or "",
  69. "remark": row.remark or "",
  70. "createTime": row.create_time.strftime("%Y-%m-%d %H:%M:%S") if row.create_time else "",
  71. "updateTime": row.update_time.strftime("%Y-%m-%d %H:%M:%S") if row.update_time else "",
  72. }
  73. if application:
  74. d["applicationNo"] = application.application_no or ""
  75. d["applicationName"] = application.application_name or ""
  76. d["applicationStatus"] = application.application_status or ""
  77. d["channelName"] = application.channel_name or ""
  78. d["channelId"] = application.channel_id or ""
  79. d["pilotApplicationId"] = application.id or ""
  80. d["channelServiceOrderId"] = application.channel_service_order_id or ""
  81. d["projectTitle"] = application.project_title or ""
  82. d["customerName"] = application.customer_name or ""
  83. d["bizType"] = application.biz_type or "pilot_service"
  84. else:
  85. d["applicationNo"] = ""
  86. d["applicationName"] = ""
  87. d["applicationStatus"] = ""
  88. d["channelName"] = ""
  89. d["channelId"] = ""
  90. d["pilotApplicationId"] = ""
  91. d["channelServiceOrderId"] = ""
  92. d["projectTitle"] = ""
  93. d["customerName"] = ""
  94. d["bizType"] = ""
  95. if plan:
  96. d["channelAgreementId"] = plan.channel_agreement_id or ""
  97. else:
  98. d["channelAgreementId"] = ""
  99. if patient:
  100. d["patientName"] = patient.patient_name or ""
  101. d["patientSex"] = patient.sex or ""
  102. d["patientAge"] = patient.age
  103. else:
  104. d["patientName"] = ""
  105. d["patientSex"] = ""
  106. d["patientAge"] = None
  107. if service_order:
  108. d["orderType"] = service_order.order_type or ""
  109. d["channelServiceOrderName"] = service_order.order_name or ""
  110. else:
  111. d["orderType"] = ""
  112. d["channelServiceOrderName"] = ""
  113. if products is not None:
  114. d["products"] = products
  115. else:
  116. d["products"] = []
  117. return d
  118. def _row_to_dict_product(row) -> Dict[str, Any]:
  119. return {
  120. "id": row.id,
  121. "priceId": row.price_id or "",
  122. "projectCode": row.project_code or "",
  123. "projectName": row.project_name or "",
  124. "cellTypeName": row.cell_type_name or "",
  125. "specText": row.spec_text or "",
  126. "agreementPrice": float(row.agreement_price) if row.agreement_price is not None else None,
  127. "actualPrice": float(row.actual_price) if row.actual_price is not None else None,
  128. "quantity": row.quantity if row.quantity is not None else 1,
  129. "remark": row.remark or "",
  130. "productStatus": row.product_status or "",
  131. "status": row.product_status or "",
  132. }
  133. def _get_plan_schedule_course_meta(
  134. db: Session, plan_ids: List[str], tenant_no: str
  135. ) -> Dict[str, Dict[str, Any]]:
  136. """按输注方案汇总:计划条数、各计划内每条 schedule 的疗程序号(1 起)。"""
  137. unique_ids = list({pid for pid in plan_ids if pid})
  138. if not unique_ids:
  139. return {}
  140. rows = (
  141. db.query(BizPilotInfusionSchedule)
  142. .filter(
  143. BizPilotInfusionSchedule.infusion_plan_id.in_(unique_ids),
  144. BizPilotInfusionSchedule.tenant_no == tenant_no,
  145. BizPilotInfusionSchedule.del_flag == 0,
  146. )
  147. .order_by(
  148. BizPilotInfusionSchedule.infusion_plan_id.asc(),
  149. BizPilotInfusionSchedule.order_num.asc(),
  150. BizPilotInfusionSchedule.create_time.asc(),
  151. )
  152. .all()
  153. )
  154. meta: Dict[str, Dict[str, Any]] = {}
  155. by_plan: Dict[str, List[BizPilotInfusionSchedule]] = {}
  156. for row in rows:
  157. by_plan.setdefault(row.infusion_plan_id, []).append(row)
  158. for plan_id, schedules in by_plan.items():
  159. sort_no_by_id: Dict[str, int] = {}
  160. for idx, sch in enumerate(schedules):
  161. order_num = sch.order_num if sch.order_num is not None else 0
  162. sort_no_by_id[sch.id] = order_num if order_num > 0 else idx + 1
  163. meta[plan_id] = {
  164. "scheduleCount": len(schedules),
  165. "sortNoByScheduleId": sort_no_by_id,
  166. }
  167. return meta
  168. def _resolve_course_display(
  169. row: BizPilotInfusionSchedule,
  170. plan: Optional[BizPilotInfusionPlan],
  171. plan_meta: Optional[Dict[str, Any]] = None,
  172. ) -> Dict[str, Optional[int]]:
  173. sort_no: Optional[int] = None
  174. total: Optional[int] = None
  175. if plan_meta:
  176. sort_no = plan_meta.get("sortNoByScheduleId", {}).get(row.id)
  177. plan_total = plan.total_course_count if plan else None
  178. if plan_total is not None and plan_total > 0:
  179. total = int(plan_total)
  180. else:
  181. total = int(plan_meta.get("scheduleCount") or 0) or None
  182. elif plan and row.infusion_plan_id:
  183. order_num = row.order_num if row.order_num is not None else 0
  184. if order_num > 0:
  185. sort_no = int(order_num)
  186. plan_total = plan.total_course_count
  187. if plan_total is not None and plan_total > 0:
  188. total = int(plan_total)
  189. if sort_no is None or sort_no <= 0:
  190. order_num = row.order_num if row.order_num is not None else 0
  191. sort_no = int(order_num) if order_num > 0 else None
  192. return {"sortNo": sort_no, "totalCourseCount": total if total and total > 0 else None}
  193. def _get_products_for_schedule(db: Session, schedule_id: str, tenant_no: str) -> List[Dict[str, Any]]:
  194. rows = (
  195. db.query(BizPilotInfusionScheduleProduct)
  196. .filter(
  197. BizPilotInfusionScheduleProduct.infusion_schedule_id == schedule_id,
  198. BizPilotInfusionScheduleProduct.tenant_no == tenant_no,
  199. BizPilotInfusionScheduleProduct.del_flag == 0,
  200. )
  201. .order_by(
  202. BizPilotInfusionScheduleProduct.order_num.asc(),
  203. BizPilotInfusionScheduleProduct.create_time.asc(),
  204. )
  205. .all()
  206. )
  207. return [_row_to_dict_product(r) for r in rows]
  208. # ────────────────────────────────────────────
  209. # List (Paginated, Multi-table JOIN)
  210. # ────────────────────────────────────────────
  211. def list_infusion_schedules_mgmt(
  212. db: Session,
  213. tenant_no: str,
  214. page: int = 1,
  215. page_size: int = 10,
  216. keyword: Optional[str] = None,
  217. infusion_status: Optional[str] = None,
  218. qc_status: Optional[str] = None,
  219. infusion_time_start: Optional[str] = None,
  220. infusion_time_end: Optional[str] = None,
  221. biz_type: Optional[str] = None,
  222. ) -> Dict[str, Any]:
  223. sch = BizPilotInfusionSchedule
  224. plan = BizPilotInfusionPlan
  225. app = BizPilotApplication
  226. pat = BizPilotPatient
  227. prod = BizPilotInfusionScheduleProduct
  228. q = (
  229. db.query(sch)
  230. .outerjoin(plan, and_(sch.infusion_plan_id == plan.id, plan.del_flag == 0))
  231. .outerjoin(app, and_(plan.pilot_application_id == app.id, app.del_flag == 0))
  232. .outerjoin(pat, and_(app.id == pat.pilot_application_id, pat.del_flag == 0))
  233. .filter(
  234. sch.tenant_no == tenant_no,
  235. sch.del_flag == 0,
  236. )
  237. )
  238. bt = (biz_type or "").strip()
  239. if bt:
  240. q = q.filter(app.biz_type == bt)
  241. # keyword: application_no, channel_name, patient_name; basic_experiment also project_title/customer_name
  242. if keyword:
  243. kw = f"%{keyword}%"
  244. q = q.filter(
  245. or_(
  246. app.application_no.like(kw),
  247. app.channel_name.like(kw),
  248. app.project_title.like(kw),
  249. app.customer_name.like(kw),
  250. pat.patient_name.like(kw),
  251. )
  252. )
  253. if infusion_status:
  254. statuses = [s.strip() for s in infusion_status.split(",") if s.strip()]
  255. if statuses:
  256. q = q.filter(sch.infusion_status.in_(statuses))
  257. if qc_status:
  258. qc_statuses = [s.strip() for s in qc_status.split(",") if s.strip()]
  259. if qc_statuses:
  260. q = q.filter(sch.qc_status.in_(qc_statuses))
  261. time_bounds = []
  262. if infusion_time_start:
  263. try:
  264. start_dt = datetime.strptime(infusion_time_start[:10], "%Y-%m-%d")
  265. time_bounds.append(sch.infusion_time >= start_dt)
  266. except ValueError:
  267. pass
  268. if infusion_time_end:
  269. try:
  270. end_dt = datetime.strptime(infusion_time_end[:10], "%Y-%m-%d")
  271. end_dt = end_dt.replace(hour=23, minute=59, second=59)
  272. time_bounds.append(sch.infusion_time <= end_dt)
  273. except ValueError:
  274. pass
  275. # 未填写输注时间的计划(申请单新建时常见)在限定时间范围时仍应可见
  276. if time_bounds:
  277. q = q.filter(or_(and_(*time_bounds), sch.infusion_time.is_(None)))
  278. total = q.order_by(None).with_entities(func.count(sch.id)).scalar() or 0
  279. page = max(1, page)
  280. page_size = min(max(1, page_size), 100)
  281. # Use distinct to avoid duplicates from JOINs
  282. # MySQL 5.7 不支持 NULLS LAST:先排「有输注时间」再按时间倒序,未填时间的排最后
  283. schedule_rows = (
  284. q.order_by(sch.infusion_time.is_(None), desc(sch.infusion_time), desc(sch.create_time))
  285. .distinct()
  286. .offset((page - 1) * page_size)
  287. .limit(page_size)
  288. .all()
  289. )
  290. plan_ids = [r.infusion_plan_id for r in schedule_rows if r.infusion_plan_id]
  291. plan_course_meta = _get_plan_schedule_course_meta(db, plan_ids, tenant_no)
  292. items = []
  293. for row in schedule_rows:
  294. # Fetch related data for each schedule
  295. plan_row = (
  296. db.query(BizPilotInfusionPlan)
  297. .filter(
  298. BizPilotInfusionPlan.id == row.infusion_plan_id,
  299. BizPilotInfusionPlan.del_flag == 0,
  300. )
  301. .first()
  302. )
  303. application = None
  304. patient = None
  305. if plan_row:
  306. application = (
  307. db.query(BizPilotApplication)
  308. .filter(
  309. BizPilotApplication.id == plan_row.pilot_application_id,
  310. BizPilotApplication.del_flag == 0,
  311. )
  312. .first()
  313. )
  314. if application:
  315. patient = (
  316. db.query(BizPilotPatient)
  317. .filter(
  318. BizPilotPatient.pilot_application_id == application.id,
  319. BizPilotPatient.del_flag == 0,
  320. )
  321. .first()
  322. )
  323. service_order = None
  324. if application and application.channel_service_order_id:
  325. service_order = (
  326. db.query(BizChannelServiceOrder)
  327. .filter(
  328. BizChannelServiceOrder.id == application.channel_service_order_id,
  329. BizChannelServiceOrder.del_flag == 0,
  330. )
  331. .first()
  332. )
  333. products = _get_products_for_schedule(db, row.id, tenant_no)
  334. plan_meta = plan_course_meta.get(row.infusion_plan_id) if row.infusion_plan_id else None
  335. items.append(
  336. _row_to_dict_schedule(
  337. row,
  338. application,
  339. plan_row,
  340. patient,
  341. products,
  342. service_order,
  343. plan_meta=plan_meta,
  344. )
  345. )
  346. schedule_ids = [item["id"] for item in items if item.get("id")]
  347. if schedule_ids:
  348. from app.crud import clinical_payment
  349. payment_map = clinical_payment.map_payments_by_schedule_ids(
  350. db, schedule_ids=schedule_ids, tenant_no=tenant_no
  351. )
  352. for item in items:
  353. payment = payment_map.get(item["id"])
  354. if not payment:
  355. continue
  356. item["payment"] = payment
  357. item["amount"] = payment.get("amount")
  358. item["payStatus"] = payment.get("payStatus")
  359. return {
  360. "list": items,
  361. "pagination": {"page": page, "pageSize": page_size, "total": total},
  362. }
  363. # ────────────────────────────────────────────
  364. # Detail
  365. # ────────────────────────────────────────────
  366. def get_infusion_schedule_detail(
  367. db: Session, schedule_id: str, tenant_no: str
  368. ) -> Optional[Dict[str, Any]]:
  369. row = (
  370. db.query(BizPilotInfusionSchedule)
  371. .filter(
  372. BizPilotInfusionSchedule.id == schedule_id,
  373. BizPilotInfusionSchedule.tenant_no == tenant_no,
  374. BizPilotInfusionSchedule.del_flag == 0,
  375. )
  376. .first()
  377. )
  378. if not row:
  379. return None
  380. plan_row = (
  381. db.query(BizPilotInfusionPlan)
  382. .filter(
  383. BizPilotInfusionPlan.id == row.infusion_plan_id,
  384. BizPilotInfusionPlan.del_flag == 0,
  385. )
  386. .first()
  387. )
  388. application = None
  389. patient = None
  390. if plan_row:
  391. application = (
  392. db.query(BizPilotApplication)
  393. .filter(
  394. BizPilotApplication.id == plan_row.pilot_application_id,
  395. BizPilotApplication.del_flag == 0,
  396. )
  397. .first()
  398. )
  399. if application:
  400. patient = (
  401. db.query(BizPilotPatient)
  402. .filter(
  403. BizPilotPatient.pilot_application_id == application.id,
  404. BizPilotPatient.del_flag == 0,
  405. )
  406. .first()
  407. )
  408. service_order = None
  409. if application and application.channel_service_order_id:
  410. service_order = (
  411. db.query(BizChannelServiceOrder)
  412. .filter(
  413. BizChannelServiceOrder.id == application.channel_service_order_id,
  414. BizChannelServiceOrder.del_flag == 0,
  415. )
  416. .first()
  417. )
  418. products = _get_products_for_schedule(db, row.id, tenant_no)
  419. plan_meta = None
  420. if row.infusion_plan_id:
  421. batch_meta = _get_plan_schedule_course_meta(db, [row.infusion_plan_id], tenant_no)
  422. plan_meta = batch_meta.get(row.infusion_plan_id)
  423. flat = _row_to_dict_schedule(
  424. row, application, plan_row, patient, products, service_order, plan_meta=plan_meta
  425. )
  426. aggregated = orr_svc.get_schedule_detail(db, schedule_id, tenant_no) or {}
  427. app = dict(aggregated.get("application") or {})
  428. app["applicationNo"] = app.get("applicationNo") or flat.get("applicationNo") or ""
  429. app["applicationName"] = app.get("applicationName") or flat.get("applicationName") or ""
  430. app["applicationStatus"] = app.get("applicationStatus") or flat.get("applicationStatus") or ""
  431. app["channelName"] = app.get("channelName") or flat.get("channelName") or ""
  432. app["orderType"] = flat.get("orderType") or ""
  433. app["channelServiceOrderName"] = flat.get("channelServiceOrderName") or ""
  434. app["channelServiceOrderId"] = flat.get("channelServiceOrderId") or ""
  435. app["projectTitle"] = app.get("projectTitle") or flat.get("projectTitle") or ""
  436. app["customerName"] = app.get("customerName") or flat.get("customerName") or ""
  437. if application:
  438. app["bizType"] = application.biz_type or "pilot_service"
  439. if not app.get("projectTitle"):
  440. app["projectTitle"] = application.project_title or ""
  441. if not app.get("customerName"):
  442. app["customerName"] = application.customer_name or ""
  443. plan = dict(aggregated.get("infusionPlan") or {})
  444. if plan_row:
  445. plan.setdefault("cellType", plan_row.cell_type or "")
  446. plan.setdefault("specText", plan_row.spec_text or "")
  447. plan.setdefault("totalCourseCount", plan_row.total_course_count)
  448. plan.setdefault("courseInterval", plan_row.course_interval or "")
  449. plan.setdefault("infusionStartDate", plan_row.infusion_start_date or "")
  450. sched = dict(aggregated.get("infusionSchedule") or {})
  451. sched["sortNo"] = flat.get("sortNo")
  452. sched["totalCourseCount"] = flat.get("totalCourseCount")
  453. sched["cellType"] = flat.get("cellType") or sched.get("cellType") or ""
  454. sched["specText"] = flat.get("specText") or sched.get("specText") or ""
  455. sched["infusionTime"] = flat.get("infusionTime") or sched.get("infusionTime") or ""
  456. sched["infusionLocation"] = flat.get("infusionLocation") or sched.get("infusionLocation") or ""
  457. sched["infusionMethod"] = flat.get("infusionMethod") or sched.get("infusionMethod") or ""
  458. sched["scheduleStatus"] = flat.get("scheduleStatus") or sched.get("scheduleStatus") or ""
  459. sched["infusionStatus"] = flat.get("infusionStatus") or sched.get("infusionStatus") or ""
  460. sched["qcStatus"] = flat.get("qcStatus") or sched.get("qcStatus") or ""
  461. sched["cancelReason"] = flat.get("cancelReason") or sched.get("cancelReason") or ""
  462. sched["remark"] = flat.get("remark") or ""
  463. patient_data = dict(aggregated.get("patient") or {})
  464. if patient:
  465. patient_data.setdefault("patientName", patient.patient_name or "")
  466. patient_data.setdefault("sex", patient.sex or "")
  467. patient_data.setdefault("age", str(patient.age) if patient.age is not None else "")
  468. patient_data.setdefault("phoneNo", patient.phone_no or "")
  469. patient_data.setdefault("idCardNo", patient.id_card_no or "")
  470. patient_data.setdefault("emergencyContact", patient.emergency_contact or "")
  471. patient_data.setdefault("emergencyPhone", patient.emergency_phone or "")
  472. patient_data.setdefault("clinicalDiagnosis", patient.clinical_diagnosis or "")
  473. patient_data.setdefault("diagnosisAttachments", patient.diagnosis_attachments or "")
  474. patient_data.setdefault("needCheckup", patient.need_checkup)
  475. result: Dict[str, Any] = {
  476. **aggregated,
  477. **flat,
  478. "application": app,
  479. "patient": patient_data,
  480. "infusionPlan": plan,
  481. "infusionSchedule": sched,
  482. "products": flat.get("products") or aggregated.get("products") or [],
  483. "productionInfo": aggregated.get("productionInfo") or {},
  484. "qcInfo": aggregated.get("qcInfo") or {},
  485. "processQcInfoList": aggregated.get("processQcInfoList") or [],
  486. "reviewInfo": aggregated.get("reviewInfo") or {},
  487. "outboundMaterial": aggregated.get("outboundMaterial") or {},
  488. "outboundHandover": handover_svc.get_outbound_handover_view(db, schedule_id, tenant_no),
  489. "infusionConfirm": confirm_svc.get_confirm_by_schedule(db, schedule_id, tenant_no) or {},
  490. }
  491. if application and (application.biz_type or "") in ("clinical_application", "basic_experiment"):
  492. from app.crud import clinical_payment
  493. payment = clinical_payment.get_payment_by_schedule(
  494. db, schedule_id=schedule_id, tenant_no=tenant_no
  495. )
  496. if payment:
  497. result["payment"] = payment
  498. return result
  499. # ────────────────────────────────────────────
  500. # Status update
  501. # ────────────────────────────────────────────
  502. def update_infusion_status(
  503. db: Session,
  504. schedule_id: str,
  505. infusion_status: str,
  506. cancel_reason: Optional[str],
  507. tenant_no: str,
  508. user_id: str,
  509. ) -> Dict[str, Any]:
  510. row = (
  511. db.query(BizPilotInfusionSchedule)
  512. .filter(
  513. BizPilotInfusionSchedule.id == schedule_id,
  514. BizPilotInfusionSchedule.tenant_no == tenant_no,
  515. BizPilotInfusionSchedule.del_flag == 0,
  516. )
  517. .first()
  518. )
  519. if not row:
  520. raise ValueError("输注计划不存在")
  521. current = row.infusion_status or ""
  522. if current not in VALID_TRANSITIONS:
  523. raise ValueError(f"当前状态 {current} 不允许变更")
  524. if infusion_status not in VALID_TRANSITIONS.get(current, set()):
  525. raise ValueError(f"不允许从 {current} 变更为 {infusion_status}")
  526. # Cancel requires reason
  527. if infusion_status == "yqx" and not cancel_reason:
  528. raise ValueError("取消时需填写取消原因")
  529. now = datetime.now()
  530. row.infusion_status = infusion_status
  531. row.update_by = user_id
  532. row.update_time = now
  533. if infusion_status == "yqx":
  534. row.cancel_reason = cancel_reason or ""
  535. row.schedule_status = "yqx"
  536. row.qc_status = "yqx"
  537. # 自动作废关联的未完成出库生产工单
  538. outbound_wo = (
  539. db.query(BizProductionWorkOrder)
  540. .filter(
  541. BizProductionWorkOrder.infusion_schedule_id == schedule_id,
  542. BizProductionWorkOrder.tenant_no == tenant_no,
  543. BizProductionWorkOrder.del_flag == 0,
  544. BizProductionWorkOrder.work_order_type == "outbound",
  545. BizProductionWorkOrder.work_order_status.notin_(["ywc", "yzf"]),
  546. )
  547. .first()
  548. )
  549. if outbound_wo:
  550. outbound_wo.work_order_status = "yzf"
  551. outbound_wo.update_by = user_id
  552. outbound_wo.update_time = now
  553. # 自动作废关联的未完成出库质检工单
  554. pending_qc_orders = (
  555. db.query(BizQcWorkOrder)
  556. .filter(
  557. BizQcWorkOrder.infusion_schedule_id == schedule_id,
  558. BizQcWorkOrder.work_order_status.notin_(["ywc", "yzf"]),
  559. BizQcWorkOrder.del_flag == 0,
  560. )
  561. .all()
  562. )
  563. for order in pending_qc_orders:
  564. order.work_order_status = "yzf"
  565. order.update_by = user_id
  566. order.update_time = now
  567. from app.crud.pilot_outbound_status_sync import sync_pilot_outbound_from_schedule
  568. sync_pilot_outbound_from_schedule(db, row, user_id=user_id)
  569. # Sync all related products' product_status
  570. product_rows = (
  571. db.query(BizPilotInfusionScheduleProduct)
  572. .filter(
  573. BizPilotInfusionScheduleProduct.infusion_schedule_id == schedule_id,
  574. BizPilotInfusionScheduleProduct.tenant_no == tenant_no,
  575. BizPilotInfusionScheduleProduct.del_flag == 0,
  576. )
  577. .all()
  578. )
  579. for p_row in product_rows:
  580. p_row.product_status = infusion_status
  581. p_row.update_by = user_id
  582. p_row.update_time = now
  583. db.flush()
  584. # If completing, trigger fee deduction
  585. if infusion_status == "ywc":
  586. _deduct_fee_on_complete(db, schedule_id, tenant_no, user_id)
  587. db.commit()
  588. db.refresh(row)
  589. return get_infusion_schedule_detail(db, row.id, tenant_no)
  590. def update_qc_status(
  591. db: Session,
  592. schedule_id: str,
  593. qc_status: str,
  594. tenant_no: str,
  595. user_id: str,
  596. ) -> Dict[str, Any]:
  597. row = (
  598. db.query(BizPilotInfusionSchedule)
  599. .filter(
  600. BizPilotInfusionSchedule.id == schedule_id,
  601. BizPilotInfusionSchedule.tenant_no == tenant_no,
  602. BizPilotInfusionSchedule.del_flag == 0,
  603. )
  604. .first()
  605. )
  606. if not row:
  607. raise ValueError("输注计划不存在")
  608. current = row.qc_status or ""
  609. if current not in QC_VALID_TRANSITIONS:
  610. raise ValueError(f"当前质检状态 {current} 不允许变更")
  611. if qc_status not in QC_VALID_TRANSITIONS.get(current, set()):
  612. raise ValueError(f"不允许从质检状态 {current} 变更为 {qc_status}")
  613. now = datetime.now()
  614. row.qc_status = qc_status
  615. row.update_by = user_id
  616. row.update_time = now
  617. from app.crud.pilot_outbound_status_sync import sync_pilot_outbound_from_schedule
  618. sync_pilot_outbound_from_schedule(db, row, user_id=user_id)
  619. db.commit()
  620. db.refresh(row)
  621. return get_infusion_schedule_detail(db, row.id, tenant_no)
  622. def _settlement_remark_marker(schedule_id: str) -> str:
  623. """幂等检索用标记(中文);兼容历史英文标记 infusionScheduleId="""
  624. return f"输注计划ID={schedule_id}"
  625. def _settlement_remark_markers_for_lookup(schedule_id: str) -> List[str]:
  626. return [_settlement_remark_marker(schedule_id), f"infusionScheduleId={schedule_id}"]
  627. def _find_existing_settlement_txn(
  628. db: Session, order_id: str, schedule_id: str
  629. ) -> Optional[BizChannelServiceOrderTxn]:
  630. marker_filters = [
  631. BizChannelServiceOrderTxn.remark.like(f"%{m}%")
  632. for m in _settlement_remark_markers_for_lookup(schedule_id)
  633. ]
  634. return (
  635. db.query(BizChannelServiceOrderTxn)
  636. .filter(
  637. BizChannelServiceOrderTxn.service_order_id == order_id,
  638. BizChannelServiceOrderTxn.txn_type == "settlement",
  639. or_(*marker_filters),
  640. BizChannelServiceOrderTxn.txn_status != "yzf",
  641. BizChannelServiceOrderTxn.del_flag == 0,
  642. )
  643. .first()
  644. )
  645. def _resolve_yfk_unit_price(
  646. db: Session, agreement_id: str, product: BizPilotInfusionScheduleProduct
  647. ) -> float:
  648. spec = (product.spec_text or "").strip()
  649. if agreement_id and (product.project_code or "").strip():
  650. row = (
  651. db.query(BizChannelAgreementProductPrice)
  652. .filter(
  653. BizChannelAgreementProductPrice.channel_agreement_id == agreement_id,
  654. BizChannelAgreementProductPrice.project_code == (product.project_code or ""),
  655. BizChannelAgreementProductPrice.spec_text == spec,
  656. BizChannelAgreementProductPrice.del_flag == 0,
  657. )
  658. .first()
  659. )
  660. if row and row.agreement_price is not None:
  661. return float(row.agreement_price)
  662. cell_name = (product.cell_type_name or "").strip()
  663. if agreement_id and cell_name:
  664. row = (
  665. db.query(BizChannelAgreementProductPrice)
  666. .filter(
  667. BizChannelAgreementProductPrice.channel_agreement_id == agreement_id,
  668. BizChannelAgreementProductPrice.spec_text == spec,
  669. BizChannelAgreementProductPrice.del_flag == 0,
  670. or_(
  671. BizChannelAgreementProductPrice.cell_type_code == cell_name,
  672. BizChannelAgreementProductPrice.cell_type_name == cell_name,
  673. ),
  674. )
  675. .first()
  676. )
  677. if row and row.agreement_price is not None:
  678. return float(row.agreement_price)
  679. if product.actual_price is not None:
  680. return float(product.actual_price)
  681. if product.agreement_price is not None:
  682. return float(product.agreement_price)
  683. return 0.0
  684. def _find_service_order_product(
  685. db: Session, order_id: str, product: BizPilotInfusionScheduleProduct
  686. ) -> Optional[BizChannelServiceOrderProduct]:
  687. project_code = (product.project_code or "").strip()
  688. spec = (product.spec_text or "").strip()
  689. cell_type = (product.cell_type_name or "").strip()
  690. if project_code:
  691. row = (
  692. db.query(BizChannelServiceOrderProduct)
  693. .filter(
  694. BizChannelServiceOrderProduct.service_order_id == order_id,
  695. BizChannelServiceOrderProduct.project_code == project_code,
  696. BizChannelServiceOrderProduct.spec_text == spec,
  697. BizChannelServiceOrderProduct.del_flag == 0,
  698. )
  699. .first()
  700. )
  701. if row:
  702. return row
  703. if cell_type:
  704. return (
  705. db.query(BizChannelServiceOrderProduct)
  706. .filter(
  707. BizChannelServiceOrderProduct.service_order_id == order_id,
  708. BizChannelServiceOrderProduct.cell_type == cell_type,
  709. BizChannelServiceOrderProduct.spec_text == spec,
  710. BizChannelServiceOrderProduct.del_flag == 0,
  711. )
  712. .first()
  713. )
  714. return None
  715. def _schedule_product_to_txn_item(
  716. product: BizPilotInfusionScheduleProduct, *, qty: int, amount: float
  717. ) -> Dict[str, Any]:
  718. return {
  719. "projectCode": product.project_code or "",
  720. "projectName": product.project_name or "",
  721. "cellType": product.cell_type_name or "",
  722. "specText": product.spec_text or "",
  723. "qty": qty,
  724. "amount": round(amount, 2),
  725. }
  726. def _create_settlement_txn(
  727. db: Session,
  728. *,
  729. order: BizChannelServiceOrder,
  730. schedule_id: str,
  731. application_no: str,
  732. amount: float,
  733. products_json: List[Dict[str, Any]],
  734. balance_before: Optional[float],
  735. balance_after: Optional[float],
  736. tenant_no: str,
  737. user_id: str,
  738. ) -> BizChannelServiceOrderTxn:
  739. now = datetime.now()
  740. remark_parts = [
  741. "输注计划完成结算",
  742. _settlement_remark_marker(schedule_id),
  743. ]
  744. if application_no:
  745. remark_parts.append(f"申请单号={application_no}")
  746. txn = BizChannelServiceOrderTxn(
  747. id=generate_uuid(),
  748. service_order_id=order.id,
  749. txn_type="settlement",
  750. amount=round(amount, 2),
  751. txn_status="yqr",
  752. products_json=json.dumps(products_json, ensure_ascii=False) if products_json else None,
  753. remark=" ".join(remark_parts),
  754. balance_before=balance_before,
  755. balance_after=balance_after,
  756. finance_confirm_time=now,
  757. finance_confirm_by=user_id,
  758. finance_remark="输注计划完成自动结算",
  759. tenant_no=tenant_no or order.tenant_no,
  760. order_num=0,
  761. create_by=user_id,
  762. create_dept_id="",
  763. create_time=now,
  764. update_by=user_id,
  765. update_time=now,
  766. del_flag=0,
  767. )
  768. db.add(txn)
  769. db.flush()
  770. return txn
  771. def _deduct_fee_on_complete(db: Session, schedule_id: str, tenant_no: str, user_id: str):
  772. schedule = (
  773. db.query(BizPilotInfusionSchedule)
  774. .filter(
  775. BizPilotInfusionSchedule.id == schedule_id,
  776. BizPilotInfusionSchedule.tenant_no == tenant_no,
  777. BizPilotInfusionSchedule.del_flag == 0,
  778. )
  779. .first()
  780. )
  781. if not schedule:
  782. raise ValueError("输注计划不存在")
  783. plan = (
  784. db.query(BizPilotInfusionPlan)
  785. .filter(
  786. BizPilotInfusionPlan.id == schedule.infusion_plan_id,
  787. BizPilotInfusionPlan.del_flag == 0,
  788. )
  789. .first()
  790. )
  791. if not plan:
  792. raise ValueError("输注方案不存在")
  793. application = (
  794. db.query(BizPilotApplication)
  795. .filter(
  796. BizPilotApplication.id == plan.pilot_application_id,
  797. BizPilotApplication.tenant_no == tenant_no,
  798. BizPilotApplication.del_flag == 0,
  799. )
  800. .first()
  801. )
  802. if not application:
  803. raise ValueError("中试申请单不存在")
  804. # 临床应用/基础实验走缴费模块,不走服务订单扣费
  805. if (application.biz_type or "") in ("clinical_application", "basic_experiment"):
  806. return
  807. if not application.channel_service_order_id:
  808. raise ValueError("申请单未关联渠道服务订单,无法扣费")
  809. order = (
  810. db.query(BizChannelServiceOrder)
  811. .filter(
  812. BizChannelServiceOrder.id == application.channel_service_order_id,
  813. BizChannelServiceOrder.del_flag == 0,
  814. )
  815. .first()
  816. )
  817. if not order:
  818. raise ValueError("渠道服务订单不存在")
  819. order_type = order.order_type or ""
  820. application_no = application.application_no or ""
  821. if _find_existing_settlement_txn(db, order.id, schedule_id):
  822. return
  823. products = (
  824. db.query(BizPilotInfusionScheduleProduct)
  825. .filter(
  826. BizPilotInfusionScheduleProduct.infusion_schedule_id == schedule_id,
  827. BizPilotInfusionScheduleProduct.tenant_no == tenant_no,
  828. BizPilotInfusionScheduleProduct.del_flag == 0,
  829. )
  830. .order_by(
  831. BizPilotInfusionScheduleProduct.order_num.asc(),
  832. BizPilotInfusionScheduleProduct.create_time.asc(),
  833. )
  834. .all()
  835. )
  836. if not products:
  837. raise ValueError("输注计划未配置细胞产品,无法完成结算,请先在编辑中维护产品明细")
  838. now = datetime.now()
  839. if order_type == "yfk":
  840. agreement_id = order.channel_agreement_id
  841. if not agreement_id:
  842. raise ValueError("服务订单未关联渠道协议,无法确定扣费金额")
  843. total_deduction = 0.0
  844. txn_products: List[Dict[str, Any]] = []
  845. for p in products:
  846. qty = max(1, int(p.quantity or 1))
  847. unit_price = _resolve_yfk_unit_price(db, agreement_id, p)
  848. if unit_price <= 0:
  849. label = p.project_name or p.cell_type_name or p.project_code or "未知产品"
  850. raise ValueError(f"无法确定产品「{label}」的协议单价,请检查渠道协议价格或输注计划实际单价")
  851. line_amount = unit_price * qty
  852. total_deduction += line_amount
  853. txn_products.append(
  854. _schedule_product_to_txn_item(p, qty=qty, amount=line_amount)
  855. )
  856. account = _get_or_create_channel_account(db, order.channel_id, tenant_no, user_id)
  857. balance_before = float(account.balance_amount) if account.balance_amount else 0
  858. if balance_before < total_deduction:
  859. raise ValueError(
  860. f"渠道账户余额不足,当前余额 {balance_before} 元,需扣减 {total_deduction} 元"
  861. )
  862. account.balance_amount = balance_before - total_deduction
  863. balance_after = float(account.balance_amount)
  864. account.update_by = user_id
  865. account.update_time = now
  866. db.add(account)
  867. db.flush()
  868. order.current_balance = float(order.current_balance or 0) - total_deduction
  869. order.balance_before = balance_before
  870. order.balance_after = balance_after
  871. order.update_by = user_id
  872. order.update_time = now
  873. db.add(order)
  874. db.flush()
  875. _create_settlement_txn(
  876. db,
  877. order=order,
  878. schedule_id=schedule_id,
  879. application_no=application_no,
  880. amount=total_deduction,
  881. products_json=txn_products,
  882. balance_before=balance_before,
  883. balance_after=balance_after,
  884. tenant_no=tenant_no,
  885. user_id=user_id,
  886. )
  887. elif order_type == "gmcp":
  888. txn_products = []
  889. total_amount = 0.0
  890. for p in products:
  891. order_product = _find_service_order_product(db, order.id, p)
  892. if not order_product:
  893. label = p.project_name or p.cell_type_name or p.project_code or "未知产品"
  894. raise ValueError(f"服务订单中未找到匹配的产品持仓:{label}")
  895. project_code = order_product.project_code or ""
  896. spec_text = order_product.spec_text or ""
  897. qty = max(1, int(p.quantity or 1))
  898. cell_type_code, cell_type_name = _resolve_agreement_price_cell_type(
  899. db,
  900. order.channel_agreement_id,
  901. project_code,
  902. spec_text,
  903. order_product.cell_type or p.cell_type_name or "",
  904. )
  905. if not cell_type_code:
  906. cell_type_code = cell_type_name or (p.cell_type_name or "")
  907. _reduce_channel_product_quota(
  908. db,
  909. channel_id=order.channel_id,
  910. project_code=project_code,
  911. cell_type_code=cell_type_code,
  912. spec_text=spec_text,
  913. reduce_qty=qty,
  914. user_id=user_id,
  915. )
  916. current_qty = float(order_product.current_qty or 0)
  917. if current_qty < qty:
  918. raise ValueError(
  919. f"订单产品「{order_product.project_name or project_code}」持仓不足,"
  920. f"当前 {current_qty} 份,需扣减 {qty} 份"
  921. )
  922. order_product.current_qty = current_qty - qty
  923. order_product.update_by = user_id
  924. order_product.update_time = now
  925. db.add(order_product)
  926. db.flush()
  927. unit_price = float(order_product.agreement_unit_price or 0)
  928. if unit_price <= 0 and p.actual_price is not None:
  929. unit_price = float(p.actual_price)
  930. line_amount = unit_price * qty
  931. total_amount += line_amount
  932. txn_products.append(
  933. _schedule_product_to_txn_item(p, qty=qty, amount=line_amount)
  934. )
  935. _create_settlement_txn(
  936. db,
  937. order=order,
  938. schedule_id=schedule_id,
  939. application_no=application_no,
  940. amount=total_amount,
  941. products_json=txn_products,
  942. balance_before=None,
  943. balance_after=None,
  944. tenant_no=tenant_no,
  945. user_id=user_id,
  946. )
  947. else:
  948. raise ValueError(f"不支持的渠道服务订单类型:{order_type or '未知'}")
  949. # ────────────────────────────────────────────
  950. # Update schedule + products
  951. # ────────────────────────────────────────────
  952. def update_infusion_schedule_mgmt(
  953. db: Session,
  954. schedule_id: str,
  955. data: dict,
  956. tenant_no: str,
  957. user_id: str,
  958. ) -> Dict[str, Any]:
  959. row = (
  960. db.query(BizPilotInfusionSchedule)
  961. .filter(
  962. BizPilotInfusionSchedule.id == schedule_id,
  963. BizPilotInfusionSchedule.tenant_no == tenant_no,
  964. BizPilotInfusionSchedule.del_flag == 0,
  965. )
  966. .first()
  967. )
  968. if not row:
  969. raise ValueError("输注计划不存在")
  970. status = row.infusion_status or ""
  971. if status not in ("dtz", "yrqr"):
  972. raise ValueError("当前状态不允许编辑")
  973. now = datetime.now()
  974. fields = {
  975. "cellType": "cell_type",
  976. "specText": "spec_text",
  977. "infusionLocation": "infusion_location",
  978. "infusionMethod": "infusion_method",
  979. }
  980. for camel, snake in fields.items():
  981. if camel in data and data[camel] is not None:
  982. setattr(row, snake, data[camel])
  983. if "infusionTime" in data and data["infusionTime"] is not None:
  984. val = data["infusionTime"]
  985. if isinstance(val, str) and val:
  986. for fmt in ("%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M", "%Y-%m-%d"):
  987. try:
  988. row.infusion_time = datetime.strptime(val, fmt)
  989. break
  990. except ValueError:
  991. continue
  992. row.update_by = user_id
  993. row.update_time = now
  994. # Update products if provided
  995. products_data = data.get("products")
  996. if products_data is not None:
  997. # Soft-delete existing products
  998. db.query(BizPilotInfusionScheduleProduct).filter(
  999. BizPilotInfusionScheduleProduct.infusion_schedule_id == schedule_id,
  1000. BizPilotInfusionScheduleProduct.tenant_no == tenant_no,
  1001. BizPilotInfusionScheduleProduct.del_flag == 0,
  1002. ).update({"del_flag": 1, "update_time": now}, synchronize_session=False)
  1003. for idx, item in enumerate(products_data):
  1004. p_row = BizPilotInfusionScheduleProduct(
  1005. id=str(uuid.uuid4()),
  1006. infusion_schedule_id=schedule_id,
  1007. price_id=item.get("priceId") or item.get("price_id") or "",
  1008. project_code=item.get("projectCode") or item.get("project_code") or "",
  1009. project_name=item.get("projectName") or item.get("project_name") or "",
  1010. cell_type_name=item.get("cellTypeName") or item.get("cell_type_name") or "",
  1011. spec_text=item.get("specText") or item.get("spec_text") or "",
  1012. agreement_price=item.get("agreementPrice") if item.get("agreementPrice") is not None else (
  1013. item.get("agreement_price") if item.get("agreement_price") is not None else None
  1014. ),
  1015. actual_price=item.get("actualPrice") if item.get("actualPrice") is not None else (
  1016. item.get("actual_price") if item.get("actual_price") is not None else None
  1017. ),
  1018. quantity=item.get("quantity") if item.get("quantity") is not None else 1,
  1019. product_status=status,
  1020. tenant_no=tenant_no,
  1021. order_num=idx + 1,
  1022. remark=item.get("remark") or "",
  1023. create_by=user_id,
  1024. create_dept_id="",
  1025. create_time=now,
  1026. update_by=user_id,
  1027. update_time=now,
  1028. del_flag=0,
  1029. )
  1030. db.add(p_row)
  1031. db.commit()
  1032. db.refresh(row)
  1033. return get_infusion_schedule_detail(db, row.id, tenant_no)