outbound_release_review.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857
  1. """出库放行审核 CRUD"""
  2. from __future__ import annotations
  3. import math
  4. from collections import defaultdict
  5. from datetime import datetime
  6. from typing import Any, Dict, List, Optional
  7. from sqlalchemy import and_, exists, func, or_
  8. from sqlalchemy.orm import Session
  9. from app.core.db_collation import eq_unicode
  10. from app.core.utils import generate_uuid
  11. from app.models.models import (
  12. BizOutboundReleaseReview,
  13. BizPilotApplication,
  14. BizPilotInfusionPlan,
  15. BizPilotInfusionSchedule,
  16. BizPilotInfusionScheduleProduct,
  17. BizPilotPatient,
  18. BizProductionTask,
  19. BizProductionWorkOrder,
  20. BizQcTask,
  21. BizQcWorkOrder,
  22. SysUser,
  23. )
  24. from app.models.qc_param import BizQcTaskResult
  25. _REVIEW_CONCLUSION_LABELS = {"tg": "通过", "btg": "不通过"}
  26. _SCHEDULE_STATUS_LABELS = {
  27. "dsc": "待生产",
  28. "ysc": "已生产",
  29. "yjf": "已交付",
  30. "yqx": "已取消",
  31. }
  32. _QC_STATUS_LABELS = {
  33. "dzc": "待质检",
  34. "yzj": "已质检",
  35. "yqx": "已取消",
  36. }
  37. _BIZ_TYPE_LABELS = {
  38. "pilot_service": "中试服务",
  39. "clinical_application": "临床应用",
  40. "basic_experiment": "基础实验",
  41. }
  42. # ────────────────────────────────────────────
  43. # Helpers
  44. # ────────────────────────────────────────────
  45. def _fmt_dt(t: Optional[datetime]) -> str:
  46. return t.strftime("%Y-%m-%d %H:%M:%S") if t else ""
  47. def _dec(v: Any) -> Optional[float]:
  48. if v is None:
  49. return None
  50. try:
  51. return float(v)
  52. except (TypeError, ValueError):
  53. return None
  54. def _total_pages(total: int, page_size: int) -> int:
  55. if total <= 0:
  56. return 0
  57. return int(math.ceil(total / float(page_size)))
  58. def normalize_outbound_review_phase(review_phase: Optional[str]) -> Optional[str]:
  59. p = (review_phase or "").strip().lower()
  60. if p in ("pending", "reviewed"):
  61. return p
  62. return None
  63. def normalize_outbound_ready_for_review_only(raw) -> Optional[bool]:
  64. """Return True when ready-only filter should apply; None means no filter."""
  65. if raw is None:
  66. return None
  67. if isinstance(raw, bool):
  68. return True if raw else None
  69. s = str(raw).strip().lower()
  70. if s in ("true", "1", "yes"):
  71. return True
  72. return None
  73. def outbound_work_orders_all_void(statuses) -> bool:
  74. """True when ≥1 non-empty status and every one equals yzf."""
  75. cleaned = [(s or "").strip() for s in (statuses or [])]
  76. if not cleaned or not any(s for s in cleaned):
  77. return False
  78. return all(s.lower() == "yzf" for s in cleaned)
  79. def _outbound_qc_unfinished_exists_for_schedule(tenant_no: str):
  80. """Any unfinished outbound schedule QC (dpz/ypz) for this infusion schedule."""
  81. return (
  82. exists()
  83. .where(
  84. and_(
  85. BizQcWorkOrder.tenant_no == tenant_no,
  86. BizQcWorkOrder.del_flag == 0,
  87. BizQcWorkOrder.qc_biz_type == "outbound",
  88. BizQcWorkOrder.trigger_source == "schedule",
  89. # 跨表 id 排序规则可能不同(general_ci vs unicode_ci)
  90. eq_unicode(
  91. BizQcWorkOrder.infusion_schedule_id, BizPilotInfusionSchedule.id
  92. ),
  93. BizQcWorkOrder.work_order_status.in_(("dpz", "ypz")),
  94. )
  95. )
  96. .correlate(BizPilotInfusionSchedule)
  97. )
  98. def _outbound_production_unfinished_exists_for_schedule(tenant_no: str):
  99. return (
  100. exists()
  101. .where(
  102. and_(
  103. BizProductionWorkOrder.tenant_no == tenant_no,
  104. BizProductionWorkOrder.del_flag == 0,
  105. BizProductionWorkOrder.work_order_type == "outbound",
  106. eq_unicode(
  107. BizProductionWorkOrder.infusion_schedule_id,
  108. BizPilotInfusionSchedule.id,
  109. ),
  110. BizProductionWorkOrder.work_order_status.in_(("dpz", "jxz")),
  111. )
  112. )
  113. .correlate(BizPilotInfusionSchedule)
  114. )
  115. def _outbound_qc_all_void_for_schedule(tenant_no: str):
  116. base = [
  117. BizQcWorkOrder.tenant_no == tenant_no,
  118. BizQcWorkOrder.del_flag == 0,
  119. BizQcWorkOrder.qc_biz_type == "outbound",
  120. BizQcWorkOrder.trigger_source == "schedule",
  121. eq_unicode(BizQcWorkOrder.infusion_schedule_id, BizPilotInfusionSchedule.id),
  122. ]
  123. any_wo = exists().where(and_(*base)).correlate(BizPilotInfusionSchedule)
  124. any_non_void = (
  125. exists()
  126. .where(
  127. and_(
  128. *base,
  129. or_(
  130. BizQcWorkOrder.work_order_status.is_(None),
  131. BizQcWorkOrder.work_order_status != "yzf",
  132. ),
  133. )
  134. )
  135. .correlate(BizPilotInfusionSchedule)
  136. )
  137. return and_(any_wo, ~any_non_void)
  138. def _outbound_production_all_void_for_schedule(tenant_no: str):
  139. base = [
  140. BizProductionWorkOrder.tenant_no == tenant_no,
  141. BizProductionWorkOrder.del_flag == 0,
  142. BizProductionWorkOrder.work_order_type == "outbound",
  143. eq_unicode(
  144. BizProductionWorkOrder.infusion_schedule_id, BizPilotInfusionSchedule.id
  145. ),
  146. ]
  147. any_wo = exists().where(and_(*base)).correlate(BizPilotInfusionSchedule)
  148. any_non_void = (
  149. exists()
  150. .where(
  151. and_(
  152. *base,
  153. or_(
  154. BizProductionWorkOrder.work_order_status.is_(None),
  155. BizProductionWorkOrder.work_order_status != "yzf",
  156. ),
  157. )
  158. )
  159. .correlate(BizPilotInfusionSchedule)
  160. )
  161. return and_(any_wo, ~any_non_void)
  162. def _get_user_name(db: Session, user_id: str) -> str:
  163. u = db.query(SysUser).filter(SysUser.id == user_id).first()
  164. return (u.nick_name or "") if u else ""
  165. def _resolve_schedule_biz_type(
  166. app: Optional[BizPilotApplication],
  167. qwo: Optional[BizQcWorkOrder],
  168. pwo: Optional[BizProductionWorkOrder],
  169. ) -> str:
  170. """输注计划业务类型:优先出库工单 biz_type,否则取申请单 biz_type。"""
  171. if qwo and (qwo.biz_type or "").strip():
  172. return (qwo.biz_type or "").strip()
  173. if pwo and (pwo.biz_type or "").strip():
  174. return (pwo.biz_type or "").strip()
  175. if app and (app.biz_type or "").strip():
  176. return (app.biz_type or "").strip()
  177. if app:
  178. return "pilot_service"
  179. return ""
  180. def _row_to_dict(row) -> Dict[str, Any]:
  181. """将 BizOutboundReleaseReview ORM 对象转为前端字典。"""
  182. return {
  183. "id": row.id,
  184. "infusionScheduleId": row.infusion_schedule_id or "",
  185. "productionWorkOrderId": row.production_work_order_id or "",
  186. "qcWorkOrderId": row.qc_work_order_id or "",
  187. "reviewConclusion": row.review_conclusion or "",
  188. "reviewConclusionLabel": _REVIEW_CONCLUSION_LABELS.get(
  189. row.review_conclusion or "", row.review_conclusion or ""
  190. ),
  191. "reviewerUserId": row.reviewer_user_id or "",
  192. "reviewByName": row.review_by_name or "",
  193. "reviewAttachments": row.review_attachments or "",
  194. "reviewRemark": row.review_remark or "",
  195. "reviewTime": _fmt_dt(row.review_time),
  196. "tenantNo": row.tenant_no or "",
  197. "orderNum": row.order_num if row.order_num is not None else 0,
  198. "remark": row.remark or "",
  199. "createBy": row.create_by or "",
  200. "createTime": _fmt_dt(row.create_time),
  201. "updateBy": row.update_by or "",
  202. "updateTime": _fmt_dt(row.update_time),
  203. }
  204. # ────────────────────────────────────────────
  205. # Paginated list
  206. # ────────────────────────────────────────────
  207. def list_reviews_paginated(
  208. db: Session,
  209. *,
  210. tenant_no: str,
  211. keyword: Optional[str] = None,
  212. review_conclusion: Optional[str] = None,
  213. schedule_status: Optional[str] = None,
  214. qc_status: Optional[str] = None,
  215. biz_type: Optional[str] = None,
  216. infusion_time_start: Optional[str] = None,
  217. infusion_time_end: Optional[str] = None,
  218. review_phase: Optional[str] = None,
  219. ready_for_review_only=None,
  220. page: int = 1,
  221. page_size: int = 10,
  222. user_info=None,
  223. ) -> Dict[str, Any]:
  224. """分页列出出库放行审核数据,以输注计划为主表 LEFT JOIN 审核/生产/质检工单。"""
  225. # ── 基础查询:输注计划 ──
  226. q0 = db.query(BizPilotInfusionSchedule).filter(
  227. BizPilotInfusionSchedule.tenant_no == tenant_no,
  228. BizPilotInfusionSchedule.del_flag == 0,
  229. )
  230. bt_filter = (biz_type or "").strip()
  231. if bt_filter:
  232. app_ids_for_biz = (
  233. db.query(BizPilotApplication.id)
  234. .filter(
  235. BizPilotApplication.tenant_no == tenant_no,
  236. BizPilotApplication.del_flag == 0,
  237. BizPilotApplication.biz_type == bt_filter,
  238. )
  239. .subquery()
  240. )
  241. plan_ids_for_biz = (
  242. db.query(BizPilotInfusionPlan.id)
  243. .filter(
  244. BizPilotInfusionPlan.tenant_no == tenant_no,
  245. BizPilotInfusionPlan.del_flag == 0,
  246. BizPilotInfusionPlan.pilot_application_id.in_(app_ids_for_biz),
  247. )
  248. .subquery()
  249. )
  250. q0 = q0.filter(BizPilotInfusionSchedule.infusion_plan_id.in_(plan_ids_for_biz))
  251. # ── 关键字过滤(application_no, patient_name)需要子查询 ──
  252. kw = (keyword or "").strip()
  253. if kw:
  254. like = f"%{kw}%"
  255. # 通过 infusion_plan_id 关联 plan → application → patient
  256. plan_ids = (
  257. db.query(BizPilotInfusionPlan.id)
  258. .filter(
  259. BizPilotInfusionPlan.tenant_no == tenant_no,
  260. BizPilotInfusionPlan.del_flag == 0,
  261. )
  262. .subquery()
  263. )
  264. app_ids = (
  265. db.query(BizPilotApplication.id)
  266. .filter(
  267. BizPilotApplication.tenant_no == tenant_no,
  268. BizPilotApplication.del_flag == 0,
  269. or_(
  270. BizPilotApplication.application_no.like(like),
  271. BizPilotApplication.application_name.like(like),
  272. BizPilotApplication.project_title.like(like),
  273. BizPilotApplication.customer_name.like(like),
  274. ),
  275. )
  276. .subquery()
  277. )
  278. patient_app_ids = (
  279. db.query(BizPilotPatient.pilot_application_id)
  280. .filter(
  281. BizPilotPatient.tenant_no == tenant_no,
  282. BizPilotPatient.del_flag == 0,
  283. BizPilotPatient.patient_name.like(like),
  284. )
  285. .subquery()
  286. )
  287. # 找出满足条件的 infusion_plan_id
  288. matched_plan_ids = (
  289. db.query(BizPilotInfusionPlan.id)
  290. .filter(
  291. BizPilotInfusionPlan.tenant_no == tenant_no,
  292. BizPilotInfusionPlan.del_flag == 0,
  293. or_(
  294. BizPilotInfusionPlan.pilot_application_id.in_(app_ids),
  295. BizPilotInfusionPlan.pilot_application_id.in_(patient_app_ids),
  296. ),
  297. )
  298. .subquery()
  299. )
  300. q0 = q0.filter(
  301. BizPilotInfusionSchedule.infusion_plan_id.in_(matched_plan_ids)
  302. )
  303. # ── schedule_status 过滤 ──
  304. ss = (schedule_status or "").strip()
  305. if ss:
  306. q0 = q0.filter(BizPilotInfusionSchedule.schedule_status == ss)
  307. # ── qc_status 过滤 ──
  308. qs = (qc_status or "").strip()
  309. if qs:
  310. q0 = q0.filter(BizPilotInfusionSchedule.qc_status == qs)
  311. # ── 输注时间范围 ──
  312. time_bounds = []
  313. if (infusion_time_start or "").strip():
  314. try:
  315. start_dt = datetime.strptime(infusion_time_start.strip()[:10], "%Y-%m-%d")
  316. time_bounds.append(BizPilotInfusionSchedule.infusion_time >= start_dt)
  317. except ValueError:
  318. pass
  319. if (infusion_time_end or "").strip():
  320. try:
  321. end_dt = datetime.strptime(infusion_time_end.strip()[:10], "%Y-%m-%d")
  322. end_dt = end_dt.replace(hour=23, minute=59, second=59)
  323. time_bounds.append(BizPilotInfusionSchedule.infusion_time <= end_dt)
  324. except ValueError:
  325. pass
  326. if time_bounds:
  327. q0 = q0.filter(or_(and_(*time_bounds), BizPilotInfusionSchedule.infusion_time.is_(None)))
  328. # ── reviewPhase / review_conclusion 过滤 ──
  329. phase = normalize_outbound_review_phase(review_phase)
  330. rc = (review_conclusion or "").strip()
  331. if phase == "pending" or (phase is None and rc == "pending"):
  332. reviewed_schedule_ids = (
  333. db.query(BizOutboundReleaseReview.infusion_schedule_id)
  334. .filter(
  335. BizOutboundReleaseReview.tenant_no == tenant_no,
  336. BizOutboundReleaseReview.del_flag == 0,
  337. BizOutboundReleaseReview.review_conclusion.isnot(None),
  338. BizOutboundReleaseReview.review_conclusion != "",
  339. )
  340. .subquery()
  341. )
  342. q0 = q0.filter(~BizPilotInfusionSchedule.id.in_(reviewed_schedule_ids))
  343. elif phase == "reviewed":
  344. reviewed_schedule_ids = (
  345. db.query(BizOutboundReleaseReview.infusion_schedule_id)
  346. .filter(
  347. BizOutboundReleaseReview.tenant_no == tenant_no,
  348. BizOutboundReleaseReview.del_flag == 0,
  349. BizOutboundReleaseReview.review_conclusion.isnot(None),
  350. BizOutboundReleaseReview.review_conclusion != "",
  351. )
  352. .subquery()
  353. )
  354. q0 = q0.filter(BizPilotInfusionSchedule.id.in_(reviewed_schedule_ids))
  355. if rc in ("tg", "btg"):
  356. conclusion_ids = (
  357. db.query(BizOutboundReleaseReview.infusion_schedule_id)
  358. .filter(
  359. BizOutboundReleaseReview.tenant_no == tenant_no,
  360. BizOutboundReleaseReview.del_flag == 0,
  361. BizOutboundReleaseReview.review_conclusion == rc,
  362. )
  363. .subquery()
  364. )
  365. q0 = q0.filter(BizPilotInfusionSchedule.id.in_(conclusion_ids))
  366. elif rc in ("tg", "btg"):
  367. reviewed_schedule_ids = (
  368. db.query(BizOutboundReleaseReview.infusion_schedule_id)
  369. .filter(
  370. BizOutboundReleaseReview.tenant_no == tenant_no,
  371. BizOutboundReleaseReview.del_flag == 0,
  372. BizOutboundReleaseReview.review_conclusion == rc,
  373. )
  374. .subquery()
  375. )
  376. q0 = q0.filter(BizPilotInfusionSchedule.id.in_(reviewed_schedule_ids))
  377. if normalize_outbound_ready_for_review_only(ready_for_review_only) is True:
  378. q0 = q0.filter(
  379. ~_outbound_qc_unfinished_exists_for_schedule(tenant_no),
  380. ~_outbound_production_unfinished_exists_for_schedule(tenant_no),
  381. )
  382. # 出库质检/生产「有工单且全部 yzf」→ 列表隐藏(两 Tab 常驻)
  383. q0 = q0.filter(
  384. ~or_(
  385. _outbound_qc_all_void_for_schedule(tenant_no),
  386. _outbound_production_all_void_for_schedule(tenant_no),
  387. )
  388. )
  389. # ── 数据权限 ──
  390. if user_info:
  391. from app.core.data_scope import apply_data_scope
  392. q0 = apply_data_scope(q0, BizPilotInfusionSchedule, user_info, db, tenant_no)
  393. # ── 分页 ──
  394. total = (
  395. q0.order_by(None)
  396. .with_entities(func.count(BizPilotInfusionSchedule.id))
  397. .scalar()
  398. or 0
  399. )
  400. page = max(1, page)
  401. page_size = min(max(1, page_size), 100)
  402. schedules = (
  403. q0.order_by(BizPilotInfusionSchedule.create_time.desc())
  404. .offset((page - 1) * page_size)
  405. .limit(page_size)
  406. .all()
  407. )
  408. schedule_ids = [s.id for s in schedules]
  409. # ── 批量加载关联数据 ──
  410. # 审核记录
  411. review_map: Dict[str, BizOutboundReleaseReview] = {}
  412. if schedule_ids:
  413. for rev in (
  414. db.query(BizOutboundReleaseReview)
  415. .filter(
  416. BizOutboundReleaseReview.infusion_schedule_id.in_(schedule_ids),
  417. BizOutboundReleaseReview.tenant_no == tenant_no,
  418. BizOutboundReleaseReview.del_flag == 0,
  419. )
  420. .all()
  421. ):
  422. review_map[rev.infusion_schedule_id] = rev
  423. # 生产工单(出库类型)
  424. production_map: Dict[str, BizProductionWorkOrder] = {}
  425. if schedule_ids:
  426. for pwo in (
  427. db.query(BizProductionWorkOrder)
  428. .filter(
  429. BizProductionWorkOrder.infusion_schedule_id.in_(schedule_ids),
  430. BizProductionWorkOrder.work_order_type == "outbound",
  431. BizProductionWorkOrder.biz_type.in_(
  432. list(_BIZ_TYPE_LABELS.keys())
  433. ),
  434. BizProductionWorkOrder.tenant_no == tenant_no,
  435. BizProductionWorkOrder.del_flag == 0,
  436. )
  437. .all()
  438. ):
  439. production_map[pwo.infusion_schedule_id] = pwo
  440. # 质检工单(出库类型)
  441. qc_map: Dict[str, BizQcWorkOrder] = {}
  442. if schedule_ids:
  443. for qwo in (
  444. db.query(BizQcWorkOrder)
  445. .filter(
  446. BizQcWorkOrder.infusion_schedule_id.in_(schedule_ids),
  447. BizQcWorkOrder.qc_biz_type == "outbound",
  448. BizQcWorkOrder.biz_type.in_(list(_BIZ_TYPE_LABELS.keys())),
  449. BizQcWorkOrder.tenant_no == tenant_no,
  450. BizQcWorkOrder.del_flag == 0,
  451. BizQcWorkOrder.trigger_source == "schedule",
  452. )
  453. .all()
  454. ):
  455. qc_map[qwo.infusion_schedule_id] = qwo
  456. # 输注计划产品明细(用户需求细胞)
  457. products_map: Dict[str, List[Dict[str, Any]]] = defaultdict(list)
  458. if schedule_ids:
  459. for product in (
  460. db.query(BizPilotInfusionScheduleProduct)
  461. .filter(
  462. BizPilotInfusionScheduleProduct.infusion_schedule_id.in_(schedule_ids),
  463. BizPilotInfusionScheduleProduct.tenant_no == tenant_no,
  464. BizPilotInfusionScheduleProduct.del_flag == 0,
  465. )
  466. .order_by(BizPilotInfusionScheduleProduct.order_num.asc())
  467. .all()
  468. ):
  469. products_map[product.infusion_schedule_id].append(
  470. {
  471. "projectCode": product.project_code or "",
  472. "projectName": product.project_name or "",
  473. "cellTypeName": product.cell_type_name or "",
  474. "specText": product.spec_text or "",
  475. "agreementPrice": _dec(product.agreement_price),
  476. "actualPrice": _dec(product.actual_price),
  477. "quantity": product.quantity,
  478. "productStatus": product.product_status or "",
  479. }
  480. )
  481. # 输注计划 → 申请单 → 患者
  482. plan_ids_for_schedules = {
  483. s.id: s.infusion_plan_id for s in schedules if s.infusion_plan_id
  484. }
  485. unique_plan_ids = list(set(plan_ids_for_schedules.values()))
  486. plan_map: Dict[str, BizPilotInfusionPlan] = {}
  487. if unique_plan_ids:
  488. for plan in (
  489. db.query(BizPilotInfusionPlan)
  490. .filter(
  491. BizPilotInfusionPlan.id.in_(unique_plan_ids),
  492. BizPilotInfusionPlan.tenant_no == tenant_no,
  493. BizPilotInfusionPlan.del_flag == 0,
  494. )
  495. .all()
  496. ):
  497. plan_map[plan.id] = plan
  498. unique_app_ids = list(
  499. {p.pilot_application_id for p in plan_map.values() if p.pilot_application_id}
  500. )
  501. app_map: Dict[str, BizPilotApplication] = {}
  502. if unique_app_ids:
  503. for app in (
  504. db.query(BizPilotApplication)
  505. .filter(
  506. BizPilotApplication.id.in_(unique_app_ids),
  507. BizPilotApplication.tenant_no == tenant_no,
  508. BizPilotApplication.del_flag == 0,
  509. )
  510. .all()
  511. ):
  512. app_map[app.id] = app
  513. # 患者
  514. patient_map: Dict[str, BizPilotPatient] = {}
  515. if unique_app_ids:
  516. for patient in (
  517. db.query(BizPilotPatient)
  518. .filter(
  519. BizPilotPatient.pilot_application_id.in_(unique_app_ids),
  520. BizPilotPatient.tenant_no == tenant_no,
  521. BizPilotPatient.del_flag == 0,
  522. )
  523. .all()
  524. ):
  525. patient_map[patient.pilot_application_id] = patient
  526. # ── 组装列表项 ──
  527. items: List[Dict[str, Any]] = []
  528. for s in schedules:
  529. plan = plan_map.get(s.infusion_plan_id)
  530. app = app_map.get(plan.pilot_application_id) if plan else None
  531. patient = patient_map.get(app.id) if app else None
  532. rev = review_map.get(s.id)
  533. pwo = production_map.get(s.id)
  534. qwo = qc_map.get(s.id)
  535. biz_type = _resolve_schedule_biz_type(app, qwo, pwo)
  536. item: Dict[str, Any] = {
  537. "id": s.id,
  538. "scheduleId": s.id,
  539. "bizType": biz_type,
  540. "bizTypeLabel": _BIZ_TYPE_LABELS.get(biz_type, biz_type),
  541. "applicationNo": (app.application_no or "") if app else "",
  542. "applicationName": (app.application_name or "") if app else "",
  543. "channelName": (app.channel_name or "") if app else "",
  544. "projectTitle": (app.project_title or "") if app else "",
  545. "customerName": (app.customer_name or "") if app else "",
  546. "patientName": (patient.patient_name or "") if patient else "",
  547. "cellType": s.cell_type or (plan.cell_type or "") if plan else (s.cell_type or ""),
  548. "specText": s.spec_text or (plan.spec_text or "") if plan else (s.spec_text or ""),
  549. "infusionTime": _fmt_dt(s.infusion_time),
  550. "scheduleStatus": s.schedule_status or "",
  551. "scheduleStatusLabel": _SCHEDULE_STATUS_LABELS.get(
  552. s.schedule_status or "", s.schedule_status or ""
  553. ),
  554. "qcStatus": s.qc_status or "",
  555. "qcStatusLabel": _QC_STATUS_LABELS.get(
  556. s.qc_status or "", s.qc_status or ""
  557. ),
  558. "products": products_map.get(s.id, []),
  559. "reviewConclusion": "",
  560. "reviewConclusionLabel": "",
  561. "reviewByName": "",
  562. "reviewTime": "",
  563. "reviewRemark": "",
  564. "reviewAttachments": "",
  565. "reviewId": "",
  566. "productionWorkOrderNo": "",
  567. "productionWorkOrderStatus": "",
  568. "qcWorkOrderNo": "",
  569. "qcWorkOrderStatus": "",
  570. }
  571. if rev:
  572. rc_val = rev.review_conclusion or ""
  573. item["reviewConclusion"] = rc_val
  574. item["reviewConclusionLabel"] = _REVIEW_CONCLUSION_LABELS.get(rc_val, rc_val)
  575. item["reviewByName"] = rev.review_by_name or ""
  576. item["reviewTime"] = _fmt_dt(rev.review_time)
  577. item["reviewRemark"] = rev.review_remark or ""
  578. item["reviewAttachments"] = rev.review_attachments or ""
  579. item["reviewId"] = rev.id
  580. else:
  581. item["reviewConclusionLabel"] = "待审核"
  582. if pwo:
  583. item["productionWorkOrderNo"] = pwo.work_order_no or ""
  584. item["productionWorkOrderStatus"] = pwo.work_order_status or ""
  585. if qwo:
  586. item["qcWorkOrderNo"] = qwo.work_order_no or ""
  587. item["qcWorkOrderStatus"] = qwo.work_order_status or ""
  588. items.append(item)
  589. return {
  590. "list": items,
  591. "total": int(total),
  592. "page": page,
  593. "pageSize": page_size,
  594. "totalPages": _total_pages(int(total), page_size),
  595. }
  596. # ────────────────────────────────────────────
  597. # Detail aggregation
  598. # ────────────────────────────────────────────
  599. def get_schedule_detail(
  600. db: Session, schedule_id: str, tenant_no: str
  601. ) -> Optional[Dict[str, Any]]:
  602. """按输注计划 ID 聚合出库放行审核详情(中试上下文 + 生产 + 质检 + 审核)。"""
  603. from app.crud.qc_work_order import build_outbound_pilot_context_by_schedule
  604. pilot_context = build_outbound_pilot_context_by_schedule(db, schedule_id, tenant_no)
  605. # ── 生产工单 + 任务 ──
  606. production_info: Dict[str, Any] = {}
  607. pwo = (
  608. db.query(BizProductionWorkOrder)
  609. .filter(
  610. BizProductionWorkOrder.infusion_schedule_id == schedule_id,
  611. BizProductionWorkOrder.work_order_type == "outbound",
  612. BizProductionWorkOrder.biz_type.in_(list(_BIZ_TYPE_LABELS.keys())),
  613. BizProductionWorkOrder.tenant_no == tenant_no,
  614. BizProductionWorkOrder.del_flag == 0,
  615. )
  616. .first()
  617. )
  618. if pwo:
  619. from app.crud.production_work_order import (
  620. _production_info_item,
  621. )
  622. production_info = _production_info_item(db, pwo)
  623. # ── 质检工单 + 任务 + 结果 ──
  624. from app.crud import qc_work_order as qc_work_order_svc
  625. qc_info = qc_work_order_svc.get_schedule_gate_qc_info(
  626. db, schedule_id=schedule_id, tenant_no=tenant_no
  627. ) or {}
  628. process_qc_info_list = qc_work_order_svc.list_process_qc_info_for_schedule(
  629. db, schedule_id=schedule_id, tenant_no=tenant_no
  630. )
  631. # ── 审核记录 ──
  632. review_info: Dict[str, Any] = {}
  633. rev = (
  634. db.query(BizOutboundReleaseReview)
  635. .filter(
  636. BizOutboundReleaseReview.infusion_schedule_id == schedule_id,
  637. BizOutboundReleaseReview.tenant_no == tenant_no,
  638. BizOutboundReleaseReview.del_flag == 0,
  639. )
  640. .first()
  641. )
  642. if rev:
  643. review_info = _row_to_dict(rev)
  644. outbound_material: Dict[str, Any] = {}
  645. try:
  646. from app.crud import outbound_release_material as orm_svc
  647. outbound_material = orm_svc.get_outbound_material(db, schedule_id, tenant_no)
  648. except Exception:
  649. outbound_material = {}
  650. # 与 OutboundReleaseReviewDetail / 出库质检详情一致:中试字段展平到顶层,勿嵌套 pilotContext
  651. return {
  652. **(pilot_context or {}),
  653. "productionInfo": production_info,
  654. "qcInfo": qc_info,
  655. "processQcInfoList": process_qc_info_list,
  656. "reviewInfo": review_info,
  657. "outboundMaterial": outbound_material,
  658. }
  659. # ────────────────────────────────────────────
  660. # Review operations
  661. # ────────────────────────────────────────────
  662. def review_schedule(
  663. db: Session,
  664. schedule_id: str,
  665. *,
  666. conclusion: str,
  667. remark: Optional[str] = None,
  668. attachments: Optional[str] = None,
  669. tenant_no: str,
  670. user_id: str,
  671. ) -> Dict[str, Any]:
  672. """对指定输注计划执行出库放行审核(upsert)。"""
  673. now = datetime.now()
  674. user_name = _get_user_name(db, user_id)
  675. # 查找已有审核记录
  676. rev = (
  677. db.query(BizOutboundReleaseReview)
  678. .filter(
  679. BizOutboundReleaseReview.infusion_schedule_id == schedule_id,
  680. BizOutboundReleaseReview.tenant_no == tenant_no,
  681. BizOutboundReleaseReview.del_flag == 0,
  682. )
  683. .first()
  684. )
  685. # 自动填充生产工单 ID
  686. pwo = (
  687. db.query(BizProductionWorkOrder)
  688. .filter(
  689. BizProductionWorkOrder.infusion_schedule_id == schedule_id,
  690. BizProductionWorkOrder.work_order_type == "outbound",
  691. BizProductionWorkOrder.tenant_no == tenant_no,
  692. BizProductionWorkOrder.del_flag == 0,
  693. )
  694. .first()
  695. )
  696. # 自动填充质检工单 ID
  697. qwo = (
  698. db.query(BizQcWorkOrder)
  699. .filter(
  700. BizQcWorkOrder.infusion_schedule_id == schedule_id,
  701. BizQcWorkOrder.qc_biz_type == "outbound",
  702. BizQcWorkOrder.tenant_no == tenant_no,
  703. BizQcWorkOrder.del_flag == 0,
  704. BizQcWorkOrder.trigger_source == "schedule",
  705. )
  706. .first()
  707. )
  708. if rev:
  709. # update
  710. rev.review_conclusion = conclusion
  711. rev.review_remark = (remark or "").strip() or None
  712. rev.review_attachments = (attachments or "").strip() or None
  713. rev.reviewer_user_id = user_id
  714. rev.review_by_name = user_name
  715. rev.review_time = now
  716. rev.production_work_order_id = pwo.id if pwo else (rev.production_work_order_id or "")
  717. rev.qc_work_order_id = qwo.id if qwo else (rev.qc_work_order_id or "")
  718. rev.update_by = user_id
  719. rev.update_time = now
  720. else:
  721. # create
  722. rev = BizOutboundReleaseReview(
  723. id=generate_uuid(),
  724. infusion_schedule_id=schedule_id,
  725. production_work_order_id=pwo.id if pwo else "",
  726. qc_work_order_id=qwo.id if qwo else "",
  727. review_conclusion=conclusion,
  728. reviewer_user_id=user_id,
  729. review_by_name=user_name,
  730. review_time=now,
  731. review_remark=(remark or "").strip() or None,
  732. review_attachments=(attachments or "").strip() or None,
  733. tenant_no=tenant_no,
  734. order_num=0,
  735. remark="",
  736. create_by=user_id,
  737. create_dept_id="",
  738. create_time=now,
  739. update_by=user_id,
  740. update_time=now,
  741. del_flag=0,
  742. )
  743. db.add(rev)
  744. db.flush()
  745. return _row_to_dict(rev)
  746. def batch_review(
  747. db: Session,
  748. schedule_ids: List[str],
  749. *,
  750. conclusion: str,
  751. remark: Optional[str] = None,
  752. attachments: Optional[str] = None,
  753. tenant_no: str,
  754. user_id: str,
  755. ) -> Dict[str, Any]:
  756. """批量审核多个输注计划。"""
  757. success = 0
  758. fail = 0
  759. for sid in schedule_ids:
  760. try:
  761. review_schedule(
  762. db,
  763. sid,
  764. conclusion=conclusion,
  765. remark=remark,
  766. attachments=attachments,
  767. tenant_no=tenant_no,
  768. user_id=user_id,
  769. )
  770. success += 1
  771. except Exception:
  772. fail += 1
  773. return {"success": success, "fail": fail}