Compare commits

...
Author SHA1 Message Date
cykjandCursor d7611a1bd6 fix(web-admin): 历史归属维护列表支持每页条数选择
表格下方分页增加 10/20/30/50 可选,默认每页 10 条。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-12-01 16:51:40 +08:00
cykjandCursor 608a225c78 fix(web-admin): 质检工单与我的任务列表默认每页 10 条
两页共用 useQcWorkOrderTabPage,将默认 pageSize 从 100 改为 10。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-12-01 16:46:45 +08:00
cykjandCursor dfcef6f81f feat(qc): 工单级附件与取消第三方检测材料必填
质检工单卡片右上角可上传/查看附件;第三方任务材料改为选填,校验与前端必填一并取消。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-12-01 16:36:18 +08:00
cykj 7792c28893 feat(qc): 样本接收已接收支持按样本类型与是否废弃筛选
已接收列表增加 sampleTypeId、isVoided 查询参数与前端检索栏,便于质检进一步筛选样本。
2026-12-01 11:24:01 +08:00
cykjandCursor c22a0d1eb0 feat(market): 完善临床科研与委托加工上线能力
补齐项目组负责人审批、费用信息、合作客户、生产出库菜单、申请单号 LCKY 前缀及配套 SQL 迁移,并同步相关前后端与单测。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-30 18:51:37 +08:00
cykjandCursor 7a3c58ed99 fix(web-admin): refresh assignment filter project options after save
归属调整成功后递增 ProjectSelect refreshKey,立即重拉筛选区项目组/项目选项。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-25 15:55:13 +08:00
cykjandCursor 9b5e68f4ae feat(market): 新增委托加工业务并复用临床科研流程
独立 biz_type=contract_processing,申请/缴费/出库与临床科研共用逻辑;
业务子类型支持胎盘冻干粉/脂肪外泌体/NK/MSC/其他自定义,并补充菜单与生产质检 Tab。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-23 12:28:23 +08:00
cykj 964384108a fix(qc): 我的质检任务关键词与工单列表口径对齐 (#168)
fix(qc): 我的质检任务关键词与工单列表口径对齐

Merge pull request #168 from codex/issue-167-mine-kw-filter-88f5de9f0988
2026-11-20 22:53:45 +00:00
zlwuandCursor 5a011926d7 fix(qc): 我的质检任务关键词与工单列表口径对齐
抽取共用关键词条件,mine 接口在保留任务号/检测项外,按工单号、
协议号、入库编码、母亲姓名、出库申请字段等检索,避免占位符失效。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-21 06:52:36 +08:00
cykj 0ac8c924aa fix(qc): 科研捐赠协议状态空选不限制,mine 请求带上过滤 (#166)
fix(qc): 科研捐赠协议状态空选不限制,mine 请求带上过滤

Merge pull request #166 from codex/issue-165-qc-protocol-filter-4d4a72f74c72
2026-11-20 22:35:08 +00:00
zlwuandCursor 2bc20e695f fix(qc): 科研捐赠协议状态空选不限制,mine 请求带上过滤
空协议状态改为不限制而非无结果,避免搜索像失效;我的质检任务
mine 接口与前端请求补传 protocolStatus,与质检工单列表语义对齐。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-21 06:33:51 +08:00
zlwu 95b07639e8 Merge branch 'codex/issue-prod-cell-outbound-5ff2a9ccf69c' into V2.0 2026-11-20 17:05:47 +08:00
zlwuandCursor f3672d3cc2 feat(production): 临床科研出库细胞改由生产确认
市场出库交接对 basic_experiment 保留细胞只读并不改库存;生产工单新增确认出库细胞 API/弹窗,从细胞产品库勾选并联动已售状态。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-20 17:03:45 +08:00
zlwu 4de69c37ff Merge branch 'codex/issue-clinical-research-channel-5d20f51468ed' into V2.0 2026-11-20 16:06:37 +08:00
zlwuandCursor 9242ed0538 feat(pilot): 临床科研申请单增加必填渠道
开通 showChannel,保存校验并回写 channel_id/name;表单/列表/详情展示渠道,不绑定服务订单。用户确认免除 Figma。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-20 16:05:05 +08:00
zlwu 2e741b1284 Merge branch 'codex/issue-research-category-552c89fcb0a6' into V2.0 2026-11-20 15:52:47 +08:00
zlwuandCursor 6b1bf8a1d2 feat(pilot): 临床科研申请单新增业务类型字段
在申请单信息中增加 researchCategory(生物新技术临床科研/临床课题联合申报/生物制药研发),贯通 SQL、后端校验与 Web 表单/列表/详情;用户确认免除 Figma。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-20 15:51:19 +08:00
cykj ef3e015ff9 Merge pull request 'fix(web-admin): 项目业务类型下拉去掉中试服务可选 (#162)' (#163) from codex/issue-162-hide-project-pilot-7d830f6b021e into V2.0
fix(web-admin): 项目业务类型下拉去掉中试服务可选 (#162)

Merged from PR #163
2026-11-20 07:17:18 +00:00
zlwuandCursor a598b17ab9 fix(web-admin): 项目业务类型下拉去掉中试服务可选 (#162)
新建不可选中试;旧项目已含 pilot_service 时编辑仍展示该选项。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-20 15:15:54 +08:00
cykjandCursor f7890f5560 Merge pull request 'refactor: 将基础实验展示名统一改为临床科研' (#155) from codex/issue-rename-basic-experiment-96cc7a73d023 into V2.0
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-20 15:05:02 +08:00
cykj 6ea3aed8db Merge pull request 'fix(web-admin): 隐藏生产/质检中试服务 Tab 并从「所有」排除 (#160)' (#161) from codex/issue-160-hide-pilot-tabs-8fb0018cdfea into V2.0
fix(web-admin): 隐藏生产/质检中试服务 Tab 并从「所有」排除 (#160)

Merged from PR #161
2026-11-20 06:51:05 +00:00
zlwuandCursor 8349b0ce73 fix(web-admin): 隐藏生产/质检中试服务 Tab 并从「所有」排除 (#160)
客户已下线中试业务:侧栏不再展示中试 Tab,前端在「所有」列表过滤出库中试数据(含 bizType 缺省)。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-20 14:48:58 +08:00
cykj 85fe63fa9f fix(web-admin): 下线市场侧栏中试服务菜单 (#158)
fix(web-admin): 下线市场侧栏中试服务菜单 (#158)

Merge pull request #159
2026-11-20 06:35:05 +00:00
zlwuandCursor 77cdeede15 fix(web-admin): 下线市场侧栏中试服务菜单
超管在 frontend 模式下走静态路由全量展示,仅解绑 sys_role_menu 无效;同步移除 sqxp/STATIC_MENU_TREE 并软删对应 sys_menu。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-20 14:33:31 +08:00
cykj 4dc352e4f4 fix(sql): 解除市场中试服务菜单与角色绑定 (#156)
fix(sql): 解除市场中试服务菜单与角色绑定 (#156)

Merge pull request #157
2026-11-20 06:26:18 +00:00
zlwuandCursor c5f26912bd fix(sql): 解除市场中试服务菜单与角色绑定
软删市场→中试服务目录及其全部子菜单/按钮在 sys_role_menu 上的有效授权,菜单本身保留,避免误伤其他业务线下的同名菜单。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-20 14:24:39 +08:00
zlwuandCursor e85645a649 refactor: 将基础实验展示名统一改为临床科研
保留 basic_experiment 等内部编码与业务逻辑,全量替换用户可见及源码中文;新增 sys_menu REPLACE 迁移(不改 perms/path)。Gitea 工单因凭据 401 待补关联。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-20 13:51:27 +08:00
cykj 5ec997228d Merge pull request 'feat(qc): 修改记录同次提交合并节点并附件化展示 (#153)' (#154) from codex/issue-153-chg-group-fc14c4ae0ee7 into V2.0
continuous-integration/drone/tag Build is passing
feat(qc): 修改记录同次提交合并节点并附件化展示 (#153)\n\nMerge pull request #154
2026-11-20 05:25:22 +00:00
zlwu fb4bceb6b0 merge(V2.0): 同步集成分支后再合入 #153 2026-11-20 13:24:46 +08:00
zlwuandCursor cc17ac2425 feat(qc): 修改记录同次提交合并节点并附件化展示
批量保存写入 operateBatchId;弹窗按批次合并时间线,检测材料复用附件只读组件。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-20 13:23:26 +08:00
zlwuandCursor 70ebd4eff7 feat(web-admin): 市场侧栏新增器械销售菜单与施工中占位页
在市场模块末位注册器械销售目录及三类/二类医疗器械、化妆品子路由,同步后端静态菜单与 SQL 迁移写入 sys_menu 并向已有市场权限角色授权;子页面暂用统一施工中占位。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-20 13:17:02 +08:00
cykj 4d4856d4c2 Merge pull request 'fix(qc): 修改记录图标、空列表与弹窗尺寸 (#151)' (#152) from codex/issue-151-qc-hist-icon-7be0e4fa7247 into V2.0
fix(qc): 修改记录图标、空列表与弹窗尺寸 (#151)

Merge pull request #152
2026-11-20 03:57:14 +00:00
zlwuandCursor fb67f3dbd7 fix(web-admin): 放大质检修改记录弹窗宽高
验收反馈:弹窗过小;宽度 560→800,正文区 min-height 480 并限制可滚动高度。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-20 11:55:26 +08:00
zlwuandCursor 38bad4232a fix(qc): 修改记录批量查询避免路由误匹配并空列表返回
/qc-tasks/result-change-logs 须先于 /qc-tasks/{task_id} 注册;
无留痕时返回 [],不再因路径被当成任务 ID 报「任务不存在」。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-20 11:53:13 +08:00
zlwuandCursor e396b1a6eb fix(web-admin): 质检任务卡片修改记录改为右上角图标
验收反馈 #151:去掉底部文字按钮,改用 Clock 图标固定在卡片右上角。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-20 11:51:20 +08:00
cykj 7640052c96 Merge pull request 'feat(qc): 检测结果默认已完成/通过并记录修改历史 (#148/#149)' (#150) from codex/issue-148-qc-result-hist-dd33d3d3b407 into V2.0
feat(qc): 检测结果默认已完成/通过并记录修改历史 (#148/#149)

Closes related delivery for #148 #149 via PR.
2026-11-20 03:41:06 +00:00
zlwuandCursor 99583b38ce fix(qc): 任务软删级联清理检测结果留痕
删除质检任务/工单时同步软删修改记录,避免批量查询仍返回已删任务历史;
实验室填写结论回显优先沿用列表行结论。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-20 11:39:41 +08:00
zlwuandCursor 9b6228860f feat(qc): 检测结果默认已完成/通过并记录修改历史
填写弹窗未落结论时默认任务状态已完成、结论通过(实验室与第三方);
每次保存追加操作留痕,卡片可查看修改时间线。关联 #148 #149。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-20 11:34:18 +08:00
cykj 8d7b2ada59 Merge pull request 'feat(web-admin): 采集协议详情样本卡展示作废原因问号 (#146)' (#147) from codex/issue-146-protocol-view-sample-status-84884352219b into V2.0
详情样本卡头 SampleStatusTag;界面验收留给用户。
2026-11-19 07:39:06 +00:00
zlwuandCursor 332711ad36 feat(web-admin): 采集协议详情样本卡展示作废原因问号
详情样本卡头复用 SampleStatusTag,已作废时展示作废原因。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-19 15:38:18 +08:00
cykj 03acf5115a Merge pull request 'fix(protocol): 列表 sampleItems 返回样本作废原因 (#144)' (#145) from codex/issue-144-audit-sample-void-desc-7e739b6f7441 into V2.0
协议审核列表展示样本 voidDesc;单元测试 3 ok;构建验收留给用户。
2026-11-19 07:32:01 +00:00
zlwuandCursor 12cf373a49 fix(protocol): 列表 sampleItems 返回样本作废原因
协议审核/捐赠列表与样本信息列表此前未带回样本 voidDesc,导致已作废问号显示暂无作废原因。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-19 15:31:26 +08:00
cykj 0434999603 Merge pull request 'fix(qc): 样本接收废弃时将备注写入作废原因 (#142)' (#143) from codex/issue-142-reception-void-desc-315d12855585 into V2.0
接收废弃同步 void_desc;单元测试 8 ok;构建验收留给用户。
2026-11-19 07:19:01 +00:00
zlwuandCursor f40d33b07a fix(qc): 样本接收废弃时将备注写入作废原因
接收结论为废弃时同步样本 yzf,并把接收备注写入 void_desc,改回接收时一并清空。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-19 15:17:29 +08:00
cykj e5f84b4693 feat(sample): 样本废弃弹窗展示实验室入库编码 (#140) (#141)
feat(sample): 样本废弃弹窗展示实验室入库编码 (#140)
2026-11-19 07:05:41 +00:00
zlwuandCursor 71424ff576 feat(sample): 样本废弃弹窗展示实验室入库编码
在样本编码前展示实验室入库编码;生产/质检工单打开弹窗时传入该字段(#140)。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-19 15:04:51 +08:00
cykj fbe62c7a9b fix(market): 催缴/运费/实验室处理列表返回样本状态 (#138) (#139)
fix(market): 催缴/运费/实验室处理列表返回样本状态 (#138)
2026-11-19 07:00:48 +00:00
zlwuandCursor 034a4da1ad fix(market): 催缴/运费/实验室处理列表返回样本状态
Web 三处列表 CRUD 补齐 sampleStatus/voidDesc,与缴费信息修复同类缺口(#138)。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-19 14:59:56 +08:00
cykj dbc4a24543 fix(payment): 缴费信息列表返回样本状态与作废原因 (#136) (#137)
fix(payment): 缴费信息列表返回样本状态与作废原因 (#136)
2026-11-19 06:52:16 +00:00
zlwuandCursor b59c921b50 fix(payment): 缴费信息列表返回样本状态与作废原因
Web 列表走 list_sample_payments_page,补齐 sampleStatus/voidDesc(#136)。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-19 14:51:29 +08:00
cykj b57898fabb fix(sample): 样本状态问号仅已作废时展示 (#134) (#135)
fix(sample): 样本状态问号仅已作废时展示 (#134)
2026-11-19 06:30:49 +00:00
zlwuandCursor 9fd1cc4370 fix(sample): 样本状态问号仅已作废时展示
Web SampleStatusTag 仅在 sampleStatus=yzf 时显示问号;移动市场部回归断言非作废无 help(#134)。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-19 14:29:07 +08:00
cykj af02e2cdd2 Merge pull request 'feat(sample): 展示样本状态并支持样本废弃与作废原因 (#131)' (#133)
feat(sample): 展示样本状态并支持样本废弃与作废原因 (#131)
2026-11-19 06:26:05 +00:00
zlwuandCursor 0b4c8dfda8 feat(sample): 展示样本状态并支持样本废弃与作废原因
生产/质检入库卡片展示样本状态并支持【样本废弃】;市场 Web 列表与移动市场部卡片补充样本状态及问号查看作废原因;样本表新增 void_desc,人工作废不联动接收但全部作废时自动作废协议(#131)。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-19 14:25:24 +08:00
cykj 6ddd07dbb5 feat(oa): 评论@人员优先展示同部门用户 (#117)
feat(oa): 评论@人员优先展示同部门用户 (#117)
2026-11-19 06:25:21 +00:00
zlwuandCursor f9aa16ef31 feat(oa): 评论@人员优先展示同部门用户
OA 评论选人列表改为请求 users/options 时按当前登录用户部门优先排序,Web 与移动 OA 共用后端稳定排序,便于先选到同部门同事。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-19 14:24:21 +08:00
cykj 7751cc0f4a Merge pull request 'fix(qc): 样本接收废弃同步该样本状态为已作废 (#129)' (#130)
fix(qc): 样本接收废弃同步该样本状态为已作废 (#129)
2026-11-19 05:19:04 +00:00
zlwuandCursor 0346bc0b1d fix(qc): 样本接收废弃同步该样本状态为已作废
单条接收结论为废弃时仅将该样本置 yzf;改回接收且协议仍有效时清空作废状态;全部废弃仍自动作废协议。补充历史回刷 SQL(#129)。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-19 13:14:10 +08:00
cykj 76ddb81818 Merge pull request 'fix(protocol): 协议作废/属地废弃同步样本状态为已作废 (#127)' (#128)
fix(protocol): 协议作废/属地废弃同步样本状态为已作废 (#127)
2026-11-19 04:33:48 +00:00
zlwuandCursor 3f16a8ab3e fix(protocol): 协议作废/属地废弃同步样本状态为已作废
协议变为 yzf 或 sdfq 时,除样本接收废弃联动外,将下属有效样本 sample_status 置为 yzf 并写入 void_date;补充历史回刷 SQL 与单测(#127)。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-19 12:31:57 +08:00
cykj 14e733faf0 Merge pull request 'feat(oa): 收款账户组件支持图标编辑与删除 (#110)' (#126) from codex/issue-110-receive-account-edit-07c5b0874c18 into V2.0
feat(oa): 收款账户组件支持图标编辑与删除 (#110)

Merge pull request #126
2026-11-19 04:05:04 +00:00
zlwuandCursor aac72e1fd9 feat(oa): 收款账户组件支持图标编辑与删除 (#110)
在 Web 与移动 OA 表单收款账户选择器中,对可见账户增加行尾编辑/删除图标;
复用现有新增表单做编辑,删除二次确认后软删并从已选移除。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-19 12:04:08 +08:00
cykj f0a6abe538 fix(oa): 同意/拒绝/打回前自动发送评论草稿 (#125)
fix(oa): 同意/拒绝/打回前自动发送评论草稿 (#125)

关联 #118。
2026-11-19 03:56:42 +00:00
zlwuandCursor a69dcc5bca fix(oa): 同意/拒绝/打回前自动发送评论草稿
审批动作前冲刷评论区未发送内容,减少先点发送再审批的一步操作。
关联 #118。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-19 11:55:53 +08:00
cykj 0929164bf5 fix(qc): 去掉入库质检对象两列跨度导致的空白间距 (#124)
Refs #122
2026-11-19 03:27:55 +00:00
zlwuandCursor 5ecde0c80d fix(qc): 去掉入库质检对象两列跨度导致的空白间距
样本接收场景「质检对象」值很短,colSpan:2 会在样本编码前留出空列(#122)。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-19 11:27:25 +08:00
cykj 4024aad174 feat(qc): 质检工单卡片展示协议母血采集时间 (#123)
feat(qc): 质检工单卡片展示协议母血采集时间 (#123)

Refs #122
2026-11-19 03:20:40 +00:00
zlwuandCursor 02811197c6 feat(qc): 质检工单卡片展示协议母血采集时间
入库细胞存储/科研捐赠质检列表从协议采集信息补齐 maternalBloodCollectTime,
卡片 meta 与协议组摘要同步展示,未录入显示 —(#122)。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-19 11:19:15 +08:00
zlwuandCursor 7b6a0523dd fix(sql): 兼容 UC MSC 回补脚本的 collation 与确定性 ID
跨表比较统一 COLLATE,避免 unicode_ci/general_ci 混用失败;回补 ID 改 MD5 业务键并修正 task_no 序号,避免 UUID 撞主键与浮点序号。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-13 13:27:43 +08:00
cykj 99562ee584 Merge pull request 'chore(sql): 移除旧版实验室样本处理一级菜单相关迁移 (#108)' (#109) from codex/issue-108-remove-old-lab-sql-5302d8a2cc into V2.0
chore(sql): 移除旧版实验室样本处理一级菜单相关迁移 (#108)

Merged from PR #109
2026-11-13 05:21:18 +00:00
zlwuandCursor 96773ae7a3 chore(sql): 移除旧版实验室样本处理一级菜单相关迁移
生产库已无旧菜单与 biz_lab_sample_processing_extra,保留这些脚本易被误执行;一并去掉仅服务该清理流程的恢复说明。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-13 13:20:02 +08:00
zlwuandCursor ef4d687d03 chore: 清理主分支残留删除项
continuous-integration/drone/tag Build is passing
再次移除多余实验室样本处理一级静态路由,并删除弱密码刷新说明 SQL。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-13 12:14:37 +08:00
cykj f5ab0c3167 chore(sql): UC 入库编码生产任务一次性回补 SQL (#106)
一次性回补 SQL,与种子脚本分开。
2026-11-13 03:12:51 +00:00
zlwuandCursor e4b62d6406 chore(sql): 增加 UC 入库编码生产任务一次性回补脚本
与种子 SQL 分开,按空任务入库工单补派五步任务;并在种子/Python 回补说明中交叉引用。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-13 11:12:07 +08:00
cykj 808f7dcf03 fix(production): UC 入库编码自动派发脐带MSC五步任务 (#104)
fix(production): UC 入库编码自动派发脐带MSC五步任务
2026-11-13 03:03:17 +00:00
zlwuandCursor 50679fa75e fix(production): UC 入库编码自动派发脐带MSC五步任务
样本接收 UC… 此前无内置匹配规则导致工单空任务;新增 5 步原代培养模版与回补脚本,且不影响 BC 六步模版。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-13 11:01:48 +08:00
zlwuandCursor 2124ce9208 fix(lab-sample): 剔除导出自存伪数据并补齐间充质采集字段
过滤导出自存占位协议与无接收间充质行;科研捐献行从捐赠采集表取采集时间,运输温度回落到接收温度。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 17:38:33 +08:00
zlwuandCursor e7b3876db6 fix(lab-sample): 恢复 Excel 真菌等补充字段并同步质检
纠正入库编码被误软删问题,恢复可关联样本的补充字段;列表接入质检填空,并补充间充质科研捐献接收行。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 17:32:09 +08:00
zlwuandCursor c0aba421da fix(lab-sample): 新旧实验室样本台账补录双向联动
新模块读取旧台账补录并映射字段;旧台账保存时同步到新补充表与生产传染四项,新模块保存时回写旧补录。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 17:19:19 +08:00
zlwuandCursor 2aecb69cc4 fix(lab-sample): 细胞编码、母血等字段与传染四项显示
列表细胞编码改展示实验室入库编码;从母血采集时间、协议附件与收样检查推导是否有母血等列;传染四项 zc/bzc 显示为正常/不正常。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 17:01:05 +08:00
zlwuandCursor 2878c6889d fix(lab-sample): 归一化市场生产质检字段 ACL 授权
撤销历史过宽角色菜单后,仅按部门员工/主管/只读角色重授,确保员工仅可编辑本部门字段。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 15:54:59 +08:00
zlwuandCursor 4aee2b1fe5 fix(web-admin): 恢复实验室样本处理三表前端路由
合入 #100 后静态路由缺失导致刷新后顶级菜单与页面不可达,补回 hsc/ubmc/msc 路由注册。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 15:47:03 +08:00
zlwuandCursor 5698a9dfc4 fix(lab-sample): 台账改聚合真实市场生产质检数据
去掉 Excel 演示独有行,源表字段优先于补充表;按协议样本与科研捐献接收关联已发生业务数据,并修复导出分页超限。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 15:41:26 +08:00
zlwuandCursor 77d45d0bc5 feat(menu): 实验室样本处理数据挂到市场/生产/质检并分端授权
continuous-integration/drone/tag Build is passing
质检入口调到入库放行审核下方;存储服务挂缴费财务确认下方;生产管理挂废弃物管理下方。三处权限码分离,拥有对应顶级菜单的角色授予本端入口。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 14:18:27 +08:00
cykj dc0f8541c4 merge: 合入 #100 移除多余一级菜单实验室样本处理数据
merge: 合入 #100 移除多余一级菜单实验室样本处理数据
2026-11-12 06:02:59 +00:00
zlwuandCursor 4fd6ef4be5 fix(web-admin): 移除多余一级菜单实验室样本处理数据
软删除 menu:lab-sample-processing 及子菜单/按钮与角色授权,并去掉静态路由;保留质检下 lab-sample-process 台账。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 14:01:46 +08:00
zlwuandCursor b3c191ee99 fix(web-admin): 实验室样本处理数据 Tab 对齐样本接收胶囊样式
与质检样本接收页共用 panel-pill-tabs,保持质检管理列表页视觉一致。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 13:33:44 +08:00
zlwu bbef46b645 merge: 合入 #99 实验室样本处理三表台账与部门字段 ACL 2026-11-12 12:50:29 +08:00
248 changed files with 18351 additions and 2053 deletions

No files matched your search

+1 -1
View File
@@ -86,7 +86,7 @@ SECRET_KEY=
# WX_MP_TPL_PROGRESS_FIELD_APPROVER=thing6
# WX_MP_TPL_PROGRESS_FIELD_RESULT=const4
# WX_MP_TPL_PROGRESS_FIELD_TIME=time11
# 基础实验交付日前一天提醒(出库提醒模板)
# 临床科研交付日前一天提醒(出库提醒模板)
# WX_MP_TEMPLATE_BASIC_EXPERIMENT_DELIVERY=oQNU3t0Q5kwc4KPJ8Z6yPA-k6qlsH9pikSCIb4eAwgM
# WX_MP_TPL_BE_DELIVERY_FIELD_CUSTOMER=thing6
# WX_MP_TPL_BE_DELIVERY_FIELD_PRODUCT=thing10
+2
View File
@@ -47,10 +47,12 @@ from app.api.sample_cert_insurance import router as sample_cert_insurance_router
from app.api.sample_code_correction import router as sample_code_correction_router
from app.api.lab_sample_process import router as lab_sample_process_router
from app.api.lab_sample_processing import router as lab_sample_processing_router
from app.api.business_sample import router as business_sample_router
from app.api.project_management import router as project_management_router
__all__ = [
"business_sample_router",
"project_management_router",
"lab_sample_process_router",
"public_router",
+15 -2
View File
@@ -29,6 +29,7 @@ from app.crud import user as user_svc
from app.crud.collection_protocol import _lookup_attachment_by_url
from app.models.models import BizAttachment, SysDept, SysRole, SysUser, SysMenu, SysPost
from app.services.permission_administration import validate_tenant_references
from app.services.user_select_options import prioritize_caller_dept_options
from app.services.web_auth_roles import (
_map_role_name_to_web,
list_user_ids_with_effective_role_name,
@@ -77,12 +78,15 @@ async def list_roles_for_select(
@router.get("/users/options")
async def list_users_for_select(
roleName: Optional[str] = Query(None, alias="roleName"),
prioritizeCallerDept: bool = Query(False, alias="prioritizeCallerDept"),
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
"""返回用户下拉选项(label=昵称,value=用户ID),供流程设计器审批人选择使用。
"""返回用户下拉选项(label=昵称,value=用户ID,deptId=部门ID)。
供流程设计器审批人选择、OA 评论 @ 人员等使用。
可选 roleName:按有效角色(直接绑定 ∪ 职位继承)精确过滤。
可选 prioritizeCallerDept:当前登录用户同部门人员排在前面(组内仍按创建时间倒序)。
"""
tenant_no = _user.get("tenant_no", "")
q = db.query(SysUser).filter(SysUser.del_flag == 0, SysUser.status == "1")
@@ -97,7 +101,16 @@ async def list_users_for_select(
return success_response([])
q = q.filter(SysUser.id.in_(matched_ids))
rows = q.order_by(SysUser.create_time.desc()).distinct().all()
out = [{"label": (r.nick_name or r.user_no or ""), "value": r.id} for r in rows]
out = [
{
"label": (r.nick_name or r.user_no or ""),
"value": r.id,
"deptId": (r.dept_id or ""),
}
for r in rows
]
if prioritizeCallerDept:
out = prioritize_caller_dept_options(out, _user.get("region_id") or "")
return success_response(out)
+130
View File
@@ -15,12 +15,14 @@ from app.crud import collection_region as region_svc
from app.crud import collection_protocol as collection_protocol_svc
from app.crud import collection_protocol_no as protocol_no_svc
from app.crud import customer as customer_svc
from app.crud import partner_customer as partner_customer_svc
from app.crud import sample_code as sample_code_svc
from app.models.models import (
BizCellSampleType,
BizCollectionProtocolNo,
BizCollectionRegion,
BizCustomer,
BizPartnerCustomer,
BizSampleCode,
SysUser,
)
@@ -218,6 +220,134 @@ async def delete_customer(
return error_response(400, str(e))
# ---------------------------------------------------------------------------
# 合作客户(临床科研 / 委托加工)
# ---------------------------------------------------------------------------
class PartnerCustomerCreateBody(BaseModel):
model_config = ConfigDict(populate_by_name=True)
customer_name: str = Field(..., alias="customerName")
customer_contact: str = Field(..., alias="customerContact")
customer_phone: str = Field(..., alias="customerPhone")
order_num: Optional[int] = Field(0, alias="orderNum")
remark: Optional[str] = None
class PartnerCustomerUpdateBody(BaseModel):
model_config = ConfigDict(populate_by_name=True)
customer_name: Optional[str] = Field(None, alias="customerName")
customer_contact: Optional[str] = Field(None, alias="customerContact")
customer_phone: Optional[str] = Field(None, alias="customerPhone")
order_num: Optional[int] = Field(None, alias="orderNum")
remark: Optional[str] = None
@router.get("/partner-customers")
async def list_partner_customers(
page: int = Query(1, ge=1),
pageSize: int = Query(10, ge=1, le=200, alias="pageSize"),
keyword: Optional[str] = None,
user: dict = Depends(require_menu_code("biz:customer:list")),
db: Session = Depends(get_db),
):
tenant_no = _get_tenant_no(db, user)
query = db.query(BizPartnerCustomer).filter(
BizPartnerCustomer.del_flag == 0,
BizPartnerCustomer.tenant_no == tenant_no,
)
if keyword:
kw = keyword.strip()
if kw:
like = f"%{kw}%"
query = query.filter(
or_(
BizPartnerCustomer.customer_name.like(like),
BizPartnerCustomer.customer_contact.like(like),
BizPartnerCustomer.customer_phone.like(like),
)
)
query = apply_data_scope(query, BizPartnerCustomer, user, db, tenant_no)
total = query.count()
items = (
query.order_by(BizPartnerCustomer.create_time.desc())
.offset((page - 1) * pageSize)
.limit(pageSize)
.all()
)
result_list = [partner_customer_svc._row_to_dict(r) for r in items]
tp = partner_customer_svc.total_pages(total, pageSize)
return success_response(
{"list": result_list, "total": total, "page": page, "pageSize": pageSize, "totalPages": tp}
)
@router.post("/partner-customers")
async def create_partner_customer(
body: PartnerCustomerCreateBody,
user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = _get_tenant_no(db, user)
obj = partner_customer_svc.create_partner_customer(
db,
customer_name=body.customer_name,
customer_contact=body.customer_contact,
customer_phone=body.customer_phone,
tenant_no=tenant_no,
order_num=body.order_num,
remark=body.remark,
user_id=user.get("user_id"),
create_dept_id=user.get("dept_id") or "",
)
return success_response(partner_customer_svc._row_to_dict(obj), message="创建成功")
except ValueError as e:
return error_response(400, str(e))
@router.put("/partner-customers/{customer_id}")
async def update_partner_customer(
customer_id: str,
body: PartnerCustomerUpdateBody,
user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = _get_tenant_no(db, user)
payload: dict[str, Any] = body.model_dump(exclude_unset=True, by_alias=False)
obj = partner_customer_svc.update_partner_customer(
db,
customer_id,
customer_name=payload.get("customer_name"),
customer_contact=payload.get("customer_contact"),
customer_phone=payload.get("customer_phone"),
order_num=payload.get("order_num"),
remark=payload.get("remark"),
user_id=user.get("user_id"),
tenant_no=tenant_no,
)
return success_response(partner_customer_svc._row_to_dict(obj), message="更新成功")
except ValueError as e:
return error_response(400, str(e))
@router.delete("/partner-customers/{customer_id}")
async def delete_partner_customer(
customer_id: str,
user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = _get_tenant_no(db, user)
partner_customer_svc.soft_delete_partner_customer(db, customer_id, tenant_no=tenant_no)
return success_response(None, message="删除成功")
except ValueError as e:
return error_response(400, str(e))
# ---------------------------------------------------------------------------
# 细胞样本类型
# ---------------------------------------------------------------------------
+80
View File
@@ -0,0 +1,80 @@
"""业务样本:人工作废等跨模块入口。"""
from __future__ import annotations
from typing import Optional
from fastapi import APIRouter, Depends
from pydantic import BaseModel, ConfigDict, Field
from sqlalchemy.orm import Session
from app.core.database import get_db
from app.core.menu_guard import require_admin_or_super_admin
from app.core.response import error_response, success_response
from app.models.models import SysUser
from app.services.protocol_reception_discard_sync import SAMPLE_VOID_STATUS, void_sample_manually
router = APIRouter(prefix="/web/admin", tags=["业务样本"])
class VoidSampleBody(BaseModel):
model_config = ConfigDict(populate_by_name=True)
reception_source: str = Field(..., alias="receptionSource")
void_desc: str = Field(..., alias="voidDesc")
sample_id: Optional[str] = Field(None, alias="sampleId")
sample_code: Optional[str] = Field(None, alias="sampleCode")
protocol_id: Optional[str] = Field(None, alias="protocolId")
def _get_tenant_no(db: Session, user: dict) -> str:
user_id = user.get("user_id")
if not user_id:
raise PermissionError("用户身份信息缺失,无法确定租户")
sys_user = db.query(SysUser).filter(SysUser.id == user_id).first()
if not sys_user or not sys_user.tenant_no:
raise PermissionError("用户租户信息缺失")
return sys_user.tenant_no
def _get_current_user_id(user: dict) -> str:
user_id = user.get("user_id")
if not user_id:
raise PermissionError("用户身份信息缺失")
return str(user_id)
@router.put("/business-samples/void")
async def void_business_sample(
body: VoidSampleBody,
db: Session = Depends(get_db),
user: dict = Depends(require_admin_or_super_admin),
):
try:
tenant_no = _get_tenant_no(db, user)
user_id = _get_current_user_id(user)
sample = void_sample_manually(
db,
source=body.reception_source,
tenant_no=tenant_no,
void_desc=body.void_desc,
user_id=user_id,
sample_id=body.sample_id,
sample_code=body.sample_code,
protocol_id=body.protocol_id,
commit=True,
)
return success_response(
{
"id": sample.id,
"sampleCode": getattr(sample, "sample_code", None) or "",
"sampleStatus": SAMPLE_VOID_STATUS,
"voidDate": getattr(sample, "void_date", None) or "",
"voidDesc": getattr(sample, "void_desc", None) or "",
}
)
except PermissionError as e:
return error_response(403, str(e))
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(400, str(e))
+15 -6
View File
@@ -6,7 +6,7 @@ from pydantic import BaseModel, ConfigDict, Field
from sqlalchemy.orm import Session
from app.core.database import get_db
from app.core.menu_guard import require_menu_code
from app.core.menu_guard import require_any_menu_code
from app.core.response import error_response, success_response
from app.crud import lab_sample_process as svc
from app.models.models import SysUser
@@ -14,8 +14,17 @@ from app.services import lab_sample_process as ledger
router = APIRouter(prefix="/web/admin", tags=["质检管理"])
LIST_MENU = "biz:labSampleProcess:list"
SUPPLEMENT_MENU = "biz:labSampleProcess:supplement"
# 市场/生产/质检三处菜单权限码不同,接口按并集鉴权
LIST_MENU_CODES = (
"biz:labSampleProcess:list",
"production:labSampleProcess:list",
"cellStorage:labSampleProcess:list",
)
SUPPLEMENT_MENU_CODES = (
"biz:labSampleProcess:supplement",
"production:labSampleProcess:supplement",
"cellStorage:labSampleProcess:supplement",
)
def _tenant_no(db: Session, user: dict) -> str:
@@ -59,7 +68,7 @@ def list_lab_sample_process(
createTimeStart: Optional[str] = Query(None),
createTimeEnd: Optional[str] = Query(None),
db: Session = Depends(get_db),
user=Depends(require_menu_code(LIST_MENU)),
user=Depends(require_any_menu_code(*LIST_MENU_CODES)),
):
try:
tenant_no = _tenant_no(db, user)
@@ -98,7 +107,7 @@ def list_lab_sample_process(
def get_supplement(
labStorageCode: str = Query(...),
db: Session = Depends(get_db),
user=Depends(require_menu_code(LIST_MENU)),
user=Depends(require_any_menu_code(*LIST_MENU_CODES)),
):
try:
tenant_no = _tenant_no(db, user)
@@ -114,7 +123,7 @@ def get_supplement(
def save_supplement(
body: SupplementBody,
db: Session = Depends(get_db),
user=Depends(require_menu_code(SUPPLEMENT_MENU)),
user=Depends(require_any_menu_code(*SUPPLEMENT_MENU_CODES)),
):
try:
tenant_no = _tenant_no(db, user)
+178 -36
View File
@@ -7,7 +7,7 @@ from app.core.response import success_response
router = APIRouter(prefix="/web/menu", tags=["菜单管理"])
# 与 web-admin/src/router/modules/sqxp.ts 一致:6 个一级菜单分组
# 市场二级顺序:存储服务、科研捐赠、市场基础信息、中试服务、基础实验
# 市场二级顺序:存储服务、科研捐赠、市场基础信息、临床科研、器械销售
STATIC_MENU_TREE = [
{
"id": "TOP00000000000000000000000000006",
@@ -199,7 +199,7 @@ STATIC_MENU_TREE = [
],
},
# 市场基础信息(前段:存储/捐赠相关;后段:中试/基础实验相关)
# 市场基础信息(前段:存储/捐赠相关;后段:中试/临床科研相关)
{
"id": "MKT00000000000000000000000000001",
"name": "MarketInfo",
@@ -298,44 +298,14 @@ STATIC_MENU_TREE = [
],
},
# 中试服务
{
"id": "PIL00000000000000000000000000001",
"name": "PilotService",
"path": "pilot-service",
"component": "",
"meta": {
"title": "中试服务",
"icon": "ri:flask-line",
"keepAlive": False,
"roles": ["admin"],
},
"children": [
{
"id": "80000000000000000000000000000010",
"name": "PilotApplication",
"path": "pilot-application",
"component": "/pilot-service/pilot-application/index",
"meta": {"title": "中试服务申请单", "keepAlive": True, "menuCode": "pilot-service:pilot-application:list"},
},
{
"id": "PIL00000000000000000000000000004",
"name": "PilotOutboundRelease",
"path": "outbound-release-review",
"component": "/pilot-service/outbound-release-review/index",
"meta": {"title": "出库放行审核", "keepAlive": True, "menuCode": "pilot-service:outbound-release-review:list"},
},
],
},
# 基础实验
# 临床科研(与 sqxp.ts / 委托加工成对:申请、审批、费用、出库放行)
{
"id": "BEX00000000000000000000000000001",
"name": "BasicExperiment",
"path": "basic-experiment",
"component": "",
"meta": {
"title": "基础实验",
"title": "临床科研",
"icon": "ri:flask-line",
"keepAlive": False,
"roles": ["admin"],
@@ -347,11 +317,35 @@ STATIC_MENU_TREE = [
"path": "application",
"component": "/pilot-service/pilot-application/index",
"meta": {
"title": "基础实验申请单",
"title": "临床科研申请单",
"keepAlive": True,
"menuCode": "basic-experiment:application:list",
},
},
{
"id": "BEX00000000000000000000000000006",
"name": "BasicExperimentApproval",
"path": "approval",
"component": "/pilot-service/pilot-application/index",
"meta": {
"title": "临床科研审批",
"keepAlive": True,
"menuCode": "basic-experiment:approval:list",
"bizType": "basic_experiment",
"approvalOnly": True,
},
},
{
"id": "BEX00000000000000000000000000005",
"name": "BasicExperimentFeeInfo",
"path": "fee-info",
"component": "/pilot-service/fee-info/index",
"meta": {
"title": "费用信息",
"keepAlive": True,
"menuCode": "basic-experiment:fee-info:list",
},
},
{
"id": "BEX00000000000000000000000000003",
"name": "BasicExperimentPaymentConfirm",
@@ -360,6 +354,7 @@ STATIC_MENU_TREE = [
"meta": {
"title": "缴退费财务确认",
"keepAlive": True,
"isHide": True,
"menuCode": "basic-experiment:payment-confirm:list",
},
},
@@ -375,7 +370,128 @@ STATIC_MENU_TREE = [
},
},
],
}
},
# 委托加工(复用临床科研页面,bizType=contract_processing)
{
"id": "CPG00000000000000000000000000001",
"name": "ContractProcessing",
"path": "contract-processing",
"component": "",
"meta": {
"title": "委托加工",
"icon": "ri:tools-line",
"keepAlive": False,
"roles": ["admin"],
},
"children": [
{
"id": "CPG00000000000000000000000000002",
"name": "ContractProcessingApplication",
"path": "application",
"component": "/pilot-service/pilot-application/index",
"meta": {
"title": "委托加工申请单",
"keepAlive": True,
"menuCode": "contract-processing:application:list",
},
},
{
"id": "CPG00000000000000000000000000006",
"name": "ContractProcessingApproval",
"path": "approval",
"component": "/pilot-service/pilot-application/index",
"meta": {
"title": "委托加工审批",
"keepAlive": True,
"menuCode": "contract-processing:approval:list",
"bizType": "contract_processing",
"approvalOnly": True,
},
},
{
"id": "CPG00000000000000000000000000005",
"name": "ContractProcessingFeeInfo",
"path": "fee-info",
"component": "/pilot-service/fee-info/index",
"meta": {
"title": "费用信息",
"keepAlive": True,
"menuCode": "contract-processing:fee-info:list",
},
},
{
"id": "CPG00000000000000000000000000003",
"name": "ContractProcessingPaymentConfirm",
"path": "payment-confirm",
"component": "/pilot-service/clinical-payment-confirm/index",
"meta": {
"title": "缴退费财务确认",
"keepAlive": True,
"isHide": True,
"menuCode": "contract-processing:payment-confirm:list",
},
},
{
"id": "CPG00000000000000000000000000004",
"name": "ContractProcessingOutboundRelease",
"path": "outbound-release-review",
"component": "/pilot-service/outbound-release-review/index",
"meta": {
"title": "出库放行审核",
"keepAlive": True,
"menuCode": "contract-processing:outbound-release-review:list",
},
},
],
},
# 器械销售(市场侧栏末位)
{
"id": "DEV00000000000000000000000000001",
"name": "DeviceSales",
"path": "device-sales",
"component": "",
"meta": {
"title": "器械销售",
"icon": "ri:shopping-bag-3-line",
"keepAlive": False,
"roles": ["admin"],
},
"children": [
{
"id": "DEV00000000000000000000000000002",
"name": "DeviceSalesClassIii",
"path": "class-iii",
"component": "/device-sales/under-construction/index",
"meta": {
"title": "三类医疗器械",
"keepAlive": False,
"menuCode": "device-sales:class-iii:list",
},
},
{
"id": "DEV00000000000000000000000000003",
"name": "DeviceSalesClassIi",
"path": "class-ii",
"component": "/device-sales/under-construction/index",
"meta": {
"title": "二类医疗器械",
"keepAlive": False,
"menuCode": "device-sales:class-ii:list",
},
},
{
"id": "DEV00000000000000000000000000004",
"name": "DeviceSalesCosmetics",
"path": "cosmetics",
"component": "/device-sales/under-construction/index",
"meta": {
"title": "化妆品产品",
"keepAlive": False,
"menuCode": "device-sales:cosmetics:list",
},
},
],
},
],
},
@@ -583,6 +699,32 @@ STATIC_MENU_TREE = [
"menuCode": "production:waste-output:list",
},
},
{
"id": "PRD00000000000000000000000000001",
"name": "ProductionBasicExperimentOutbound",
"path": "basic-experiment-outbound",
"component": "/pilot-service/pilot-application/index",
"meta": {
"title": "临床科研出库",
"keepAlive": True,
"menuCode": "production:basic-experiment-outbound:list",
"bizType": "basic_experiment",
"productionOutbound": True,
},
},
{
"id": "PRD00000000000000000000000000002",
"name": "ProductionContractProcessingOutbound",
"path": "contract-processing-outbound",
"component": "/pilot-service/pilot-application/index",
"meta": {
"title": "委托加工出库",
"keepAlive": True,
"menuCode": "production:contract-processing-outbound:list",
"bizType": "contract_processing",
"productionOutbound": True,
},
},
],
},
# 生产基础信息
+243 -5
View File
@@ -25,6 +25,35 @@ def _get_tenant_no(db: Session, user: dict) -> str:
return sys_user.tenant_no
def _access_pilot_application(
db: Session,
tenant_no: str,
user: dict,
app_id: str,
*,
lock: bool = False,
for_approval: bool = False,
):
"""科研类走项目组可见性;其它业务走通用数据权限。"""
q = db.query(BizPilotApplication).filter(
BizPilotApplication.id == app_id,
BizPilotApplication.tenant_no == tenant_no,
BizPilotApplication.del_flag == 0,
)
if lock:
q = q.populate_existing().with_for_update()
row = q.first()
if row is None:
raise HTTPException(404, "单据不存在或无权访问")
if pilot_application.requires_leader_approval(row.biz_type):
if not pilot_application.user_can_access_research_application(
db, tenant_no, user, row, for_approval=for_approval
):
raise HTTPException(404, "单据不存在或无权访问")
return row
return accessible_order(db, BizPilotApplication, tenant_no, user, app_id, lock=lock)
# ---------------------------------------------------------------------------
# Pydantic Schemas
# ---------------------------------------------------------------------------
@@ -53,6 +82,7 @@ class ApplicationCreateBody(BaseModel):
customer_name: Optional[str] = Field(None, alias="customerName")
customer_contact: Optional[str] = Field(None, alias="customerContact")
customer_phone: Optional[str] = Field(None, alias="customerPhone")
research_category: Optional[str] = Field(None, alias="researchCategory")
class ApplicationUpdateBody(BaseModel):
@@ -65,6 +95,7 @@ class ApplicationUpdateBody(BaseModel):
customer_name: Optional[str] = Field(None, alias="customerName")
customer_contact: Optional[str] = Field(None, alias="customerContact")
customer_phone: Optional[str] = Field(None, alias="customerPhone")
research_category: Optional[str] = Field(None, alias="researchCategory")
class PatientSaveBody(BaseModel):
@@ -206,6 +237,7 @@ class ApplicationSaveBody(BaseModel):
customer_name: Optional[str] = Field(None, alias="customerName")
customer_contact: Optional[str] = Field(None, alias="customerContact")
customer_phone: Optional[str] = Field(None, alias="customerPhone")
research_category: Optional[str] = Field(None, alias="researchCategory")
remark: Optional[str] = None
consent_form_urls: Optional[str] = Field(None, alias="consentFormUrls")
consent_attachments: Optional[list] = Field(None, alias="consentAttachments")
@@ -233,8 +265,11 @@ async def api_list_applications(
keyword: Optional[str] = Query(None, alias="keyword"),
channelId: Optional[str] = Query(None, alias="channelId"),
applicationStatus: Optional[str] = Query(None, alias="applicationStatus"),
approvalStatus: Optional[str] = Query(None, alias="approvalStatus"),
pendingMine: Optional[bool] = Query(False, alias="pendingMine"),
channelServiceOrderId: Optional[str] = Query(None, alias="channelServiceOrderId"),
bizType: Optional[str] = Query(None, alias="bizType"),
forApproval: Optional[bool] = Query(False, alias="forApproval"),
user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
@@ -248,10 +283,13 @@ async def api_list_applications(
page_size=pageSize,
channel_id=channelId,
application_status=applicationStatus,
approval_status=approvalStatus,
pending_mine=bool(pendingMine),
channel_service_order_id=channelServiceOrderId,
keyword=keyword,
biz_type=bizType,
user_info=user,
for_approval=bool(forApproval),
)
return success_response(result)
@@ -263,7 +301,10 @@ async def api_get_application(
db: Session = Depends(get_db),
):
tenant_no = _get_tenant_no(db, user)
accessible_order(db, BizPilotApplication, tenant_no, user, id)
try:
_access_pilot_application(db, tenant_no, user, id)
except HTTPException as e:
return error_response(e.status_code, e.detail)
result = pilot_application.get_application(db, app_id=id, tenant_no=tenant_no)
if result is None:
return error_response(404, "申请单不存在")
@@ -287,6 +328,7 @@ async def api_create_application(
"customerName": body.customer_name,
"customerContact": body.customer_contact,
"customerPhone": body.customer_phone,
"researchCategory": body.research_category,
}
result = pilot_application.create_application(
db,
@@ -308,7 +350,7 @@ async def api_update_application(
):
try:
tenant_no = _get_tenant_no(db, user)
accessible_order(db, BizPilotApplication, tenant_no, user, body.id, lock=True)
_access_pilot_application(db, tenant_no, user, body.id, lock=True)
data = {}
if "project_id" in body.model_fields_set:
data["projectId"] = body.project_id
@@ -322,12 +364,16 @@ async def api_update_application(
data["customerContact"] = body.customer_contact
if body.customer_phone is not None:
data["customerPhone"] = body.customer_phone
if body.research_category is not None:
data["researchCategory"] = body.research_category
result = pilot_application.update_application(
db, app_id=body.id, data=data, tenant_no=tenant_no
)
return success_response(result, message="更新成功")
except ValueError as e:
return error_response(400, str(e))
except HTTPException as e:
return error_response(e.status_code, e.detail)
@router.post("/pilot-application/save")
@@ -364,6 +410,8 @@ async def api_save_application(
app_data["customerContact"] = body.customer_contact
if body.customer_phone is not None:
app_data["customerPhone"] = body.customer_phone
if body.research_category is not None:
app_data["researchCategory"] = body.research_category
if body.consent_attachments is not None:
app_data["consentAttachments"] = body.consent_attachments
elif body.consent_form_urls is not None:
@@ -375,16 +423,20 @@ async def api_save_application(
if (
not is_edit
and biz_type not in ("clinical_application", "basic_experiment")
and biz_type not in ("clinical_application", "basic_experiment", "contract_processing")
and not app_data["channelServiceOrderId"]
):
return error_response(400, "请选择渠道服务订单")
if not is_edit and biz_type == "clinical_application" and not app_data["channelId"]:
if (
not is_edit
and biz_type == "clinical_application"
and not app_data["channelId"]
):
return error_response(400, "请选择渠道")
if is_edit:
accessible_order(db, BizPilotApplication, tenant_no, user, body.id, lock=True)
_access_pilot_application(db, tenant_no, user, body.id, lock=True)
if is_edit:
app_result = pilot_application.update_application(
db,
@@ -505,6 +557,41 @@ async def api_start_application(
return error_response(400, str(e))
class ApplicationApproveBody(BaseModel):
model_config = ConfigDict(populate_by_name=True)
id: str
approval_status: str = Field(..., alias="approvalStatus")
approval_remark: Optional[str] = Field(None, alias="approvalRemark")
@router.post("/pilot-application/approve")
async def api_approve_application(
body: ApplicationApproveBody,
user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = _get_tenant_no(db, user)
_access_pilot_application(
db, tenant_no, user, body.id, lock=True, for_approval=True
)
result = pilot_application.approve_application(
db,
app_id=body.id,
tenant_no=tenant_no,
user_id=user.get("user_id"),
approval_status=body.approval_status,
approval_remark=body.approval_remark,
is_super_admin=pilot_application._is_super_admin_user(user),
)
return success_response(result, message="审批成功")
except ValueError as e:
return error_response(400, str(e))
except HTTPException as e:
return error_response(e.status_code, e.detail)
@router.post("/pilot-application/complete")
async def api_complete_application(
body: IdBody,
@@ -857,6 +944,32 @@ class ScheduleIdBody(BaseModel):
scheduleId: str
def _assert_schedule_app_approved(db: Session, schedule_id: str, tenant_no: str) -> None:
from app.models.models import BizPilotInfusionPlan, BizPilotInfusionSchedule
row = (
db.query(BizPilotApplication)
.join(
BizPilotInfusionPlan,
BizPilotInfusionPlan.pilot_application_id == BizPilotApplication.id,
)
.join(
BizPilotInfusionSchedule,
BizPilotInfusionSchedule.infusion_plan_id == BizPilotInfusionPlan.id,
)
.filter(
BizPilotInfusionSchedule.id == schedule_id,
BizPilotInfusionSchedule.tenant_no == tenant_no,
BizPilotInfusionSchedule.del_flag == 0,
BizPilotInfusionPlan.del_flag == 0,
BizPilotApplication.del_flag == 0,
)
.first()
)
if row:
pilot_application.assert_research_leader_approved(row)
@router.post("/pilot-infusion-schedule/create-production-work-order")
async def api_create_outbound_production(
body: ScheduleIdBody,
@@ -865,6 +978,7 @@ async def api_create_outbound_production(
):
try:
tenant_no = _get_tenant_no(db, user)
_assert_schedule_app_approved(db, body.scheduleId, tenant_no)
from app.crud import production_work_order as pwo_svc
from app.crud.qc_work_order import resolve_outbound_biz_type_for_schedule
@@ -903,6 +1017,7 @@ async def api_create_outbound_qc(
):
try:
tenant_no = _get_tenant_no(db, user)
_assert_schedule_app_approved(db, body.scheduleId, tenant_no)
from app.crud import qc_work_order as qc_svc
from app.crud.qc_work_order import resolve_outbound_biz_type_for_schedule
@@ -925,3 +1040,126 @@ async def api_create_outbound_qc(
except Exception as e:
db.rollback()
return error_response(400, str(e))
# ---------------------------------------------------------------------------
# 临床科研 / 委托加工 · 自定义业务类型
# ---------------------------------------------------------------------------
class ContractProcessingCategoryCreateBody(BaseModel):
model_config = ConfigDict(populate_by_name=True)
category_name: str = Field(..., alias="categoryName")
biz_type: str = Field(..., alias="bizType", description="basic_experiment | contract_processing")
order_num: Optional[int] = Field(None, alias="orderNum")
remark: Optional[str] = None
class ContractProcessingCategoryUpdateBody(BaseModel):
model_config = ConfigDict(populate_by_name=True)
category_name: Optional[str] = Field(None, alias="categoryName")
order_num: Optional[int] = Field(None, alias="orderNum")
remark: Optional[str] = None
@router.get("/contract-processing-categories")
async def list_contract_processing_categories(
page: int = Query(1, ge=1),
pageSize: int = Query(100, ge=1, le=200, alias="pageSize"),
keyword: Optional[str] = None,
bizType: str = Query(..., alias="bizType", description="basic_experiment | contract_processing"),
user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
from app.crud import contract_processing_category as cat_svc
try:
tenant_no = _get_tenant_no(db, user)
rows, total = cat_svc.list_categories(
db,
page=page,
page_size=pageSize,
keyword=keyword,
tenant_no=tenant_no,
biz_type=bizType,
)
return success_response(
{
"list": rows,
"total": total,
"page": page,
"pageSize": pageSize,
"totalPages": cat_svc.total_pages(total, pageSize),
}
)
except ValueError as e:
return error_response(400, str(e))
@router.post("/contract-processing-categories")
async def create_contract_processing_category(
body: ContractProcessingCategoryCreateBody,
user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
from app.crud import contract_processing_category as cat_svc
try:
tenant_no = _get_tenant_no(db, user)
obj = cat_svc.create_category(
db,
category_name=body.category_name,
biz_type=body.biz_type,
tenant_no=tenant_no,
order_num=body.order_num,
remark=body.remark,
user_id=user.get("user_id"),
create_dept_id=user.get("dept_id") or "",
)
return success_response(cat_svc._row_to_dict(obj), message="创建成功")
except ValueError as e:
return error_response(400, str(e))
@router.put("/contract-processing-categories/{category_id}")
async def update_contract_processing_category(
category_id: str,
body: ContractProcessingCategoryUpdateBody,
user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
from app.crud import contract_processing_category as cat_svc
try:
tenant_no = _get_tenant_no(db, user)
payload = body.model_dump(exclude_unset=True, by_alias=False)
obj = cat_svc.update_category(
db,
category_id,
category_name=payload.get("category_name"),
order_num=payload.get("order_num"),
remark=payload.get("remark"),
user_id=user.get("user_id"),
tenant_no=tenant_no,
)
return success_response(cat_svc._row_to_dict(obj), message="更新成功")
except ValueError as e:
return error_response(400, str(e))
@router.delete("/contract-processing-categories/{category_id}")
async def delete_contract_processing_category(
category_id: str,
user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
from app.crud import contract_processing_category as cat_svc
try:
tenant_no = _get_tenant_no(db, user)
cat_svc.soft_delete_category(db, category_id, tenant_no=tenant_no)
return success_response(None, message="删除成功")
except ValueError as e:
return error_response(400, str(e))
+8
View File
@@ -136,6 +136,8 @@ class CellProductSpecCreateBody(BaseModel):
spec_code: str = Field(..., alias="specCode")
spec_name: str = Field(..., alias="specName")
cell_count_qianwan: float = Field(..., alias="cellCountQianwan")
fill_volume_ml: float = Field(..., alias="fillVolumeMl")
order_num: Optional[int] = Field(0, alias="orderNum")
remark: Optional[str] = None
@@ -145,6 +147,8 @@ class CellProductSpecUpdateBody(BaseModel):
spec_code: Optional[str] = Field(None, alias="specCode")
spec_name: Optional[str] = Field(None, alias="specName")
cell_count_qianwan: Optional[float] = Field(None, alias="cellCountQianwan")
fill_volume_ml: Optional[float] = Field(None, alias="fillVolumeMl")
order_num: Optional[int] = Field(None, alias="orderNum")
remark: Optional[str] = None
@@ -179,6 +183,8 @@ async def create_cell_product_spec(
db,
spec_code=body.spec_code,
spec_name=body.spec_name,
cell_count_qianwan=body.cell_count_qianwan,
fill_volume_ml=body.fill_volume_ml,
tenant_no=tenant_no,
order_num=body.order_num,
remark=body.remark,
@@ -204,6 +210,8 @@ async def update_cell_product_spec(
row_id,
spec_code=payload.get("spec_code"),
spec_name=payload.get("spec_name"),
cell_count_qianwan=payload.get("cell_count_qianwan"),
fill_volume_ml=payload.get("fill_volume_ml"),
order_num=payload.get("order_num"),
remark=payload.get("remark"),
user_id=user.get("user_id"),
+4 -4
View File
@@ -56,7 +56,7 @@ class ProjectBody(Body):
class PreviewBody(Body):
bizType: Literal['presign', 'cell_storage', 'research_donation', 'pilot_service', 'basic_experiment']
bizType: Literal['presign', 'cell_storage', 'research_donation', 'pilot_service', 'basic_experiment', 'contract_processing']
id: str
projectId: str
@@ -68,7 +68,7 @@ class Snapshot(BaseModel):
class AssignmentBody(PreviewBody):
reason: str = Field(min_length=1, max_length=512)
reason: Optional[str] = Field(default='', max_length=512)
expectedAssignments: List[Snapshot]
@@ -162,7 +162,7 @@ def records(bizType: str, page: int=Query(1, ge=1), pageSize: int=Query(20, ge=1
@router.get(PREFIX + '/statistics/records')
def statistics_records(
bizType: Literal['cell_storage', 'research_donation', 'pilot_service', 'basic_experiment'],
bizType: Literal['cell_storage', 'research_donation', 'pilot_service', 'basic_experiment', 'contract_processing'],
page: int = Query(1, ge=1), pageSize: int = Query(20, ge=1, le=200),
teamId: Optional[str] = None, projectId: Optional[str] = None,
unassigned: bool = False, status: Optional[str] = None, keyword: Optional[str] = None,
@@ -182,7 +182,7 @@ def preview(body: PreviewBody, ctx=Depends(guard('project:assignment:edit')), db
@router.get(PREFIX + '/assignments/records')
def assignment_records(
bizType: Literal['cell_storage', 'research_donation', 'pilot_service', 'basic_experiment'],
bizType: Literal['cell_storage', 'research_donation', 'pilot_service', 'basic_experiment', 'contract_processing'],
page: int = Query(1, ge=1), pageSize: int = Query(20, ge=1, le=200),
teamId: Optional[str] = None, projectId: Optional[str] = None,
unassigned: bool = False, status: Optional[str] = None, keyword: Optional[str] = None,
+62
View File
@@ -29,6 +29,7 @@ from app.crud import qc_lab_test_item as lab_svc
from app.crud import qc_inspection_item_template as iit_svc
from app.crud import qc_item_param as param_svc
from app.crud import qc_task_result as result_svc
from app.crud import qc_task_result_change_log as result_change_log_svc
from app.crud import qc_task as task_svc
from app.crud import qc_third_party_company as tpc_svc
from app.crud import qc_third_party_item as tpi_svc
@@ -448,6 +449,7 @@ class TaskCompleteWithResultBody(BaseModel):
third_party_attachments: Optional[str] = Field(None, alias="thirdPartyAttachments")
material_usages: Optional[List[Dict[str, Any]]] = Field(None, alias="materialUsages")
task_status: Optional[str] = Field(None, alias="taskStatus")
operate_batch_id: Optional[str] = Field(None, alias="operateBatchId")
@router.get("/qc-lab-test-items")
@@ -978,6 +980,7 @@ async def update_qc_work_order(
external_target_code=body.external_target_code,
work_order_status=body.work_order_status,
qc_conclusion=body.qc_conclusion,
attachments=body.attachments,
remark=body.remark,
)
db.commit()
@@ -1176,6 +1179,9 @@ async def list_my_qc_tasks(
qcBizType: Optional[str] = None,
receptionSource: Optional[str] = Query(None, alias="receptionSource"),
bizType: Optional[str] = Query(None, alias="bizType"),
protocolStatus: Optional[str] = Query(
None, alias="protocolStatus", description="协议/捐赠状态,多个用英文逗号分隔"
),
db: Session = Depends(get_db),
user: dict = Depends(require_menu_code("biz:myQcTask:list")),
):
@@ -1192,6 +1198,7 @@ async def list_my_qc_tasks(
qc_biz_type=qcBizType,
reception_source=receptionSource,
biz_type=bizType,
protocol_status=protocolStatus,
tenant_no=tenant_no,
)
return success_response(_page_payload(items, total, page, pageSize))
@@ -1234,6 +1241,29 @@ async def list_qc_tasks(
return error_response(400, str(e))
@router.get("/qc-tasks/result-change-logs")
async def list_qc_task_result_change_logs_batch(
taskIds: str = Query("", description="逗号分隔的任务ID"),
db: Session = Depends(get_db),
user: dict = Depends(require_any_menu_code(*QC_TASK_READONLY_MENU_CODES)),
):
"""批量查询检测结果修改记录。须注册在 /qc-tasks/{task_id} 之前,避免被当成任务 ID。"""
try:
tenant_no = _get_tenant_no(db, user)
ids = [x.strip() for x in (taskIds or "").split(",") if x.strip()]
if not ids:
return success_response([])
return success_response(
result_change_log_svc.list_task_result_change_logs_by_task_ids(
db, task_ids=ids, tenant_no=tenant_no
)
)
except PermissionError as e:
return error_response(403, str(e))
except Exception as e:
return error_response(400, str(e))
@router.get("/qc-tasks/{task_id}")
async def get_qc_task_detail(
task_id: str,
@@ -1349,6 +1379,26 @@ async def get_task_material_usages(
return error_response(400, str(e))
@router.get("/qc-tasks/{task_id}/result-change-logs")
async def list_qc_task_result_change_logs(
task_id: str,
db: Session = Depends(get_db),
user: dict = Depends(require_any_menu_code(*QC_TASK_READONLY_MENU_CODES)),
):
try:
tenant_no = _get_tenant_no(db, user)
# 无任务或无留痕均返回空列表,避免前端把“暂无记录”当成错误
return success_response(
result_change_log_svc.list_task_result_change_logs(
db, task_id=task_id, tenant_no=tenant_no
)
)
except PermissionError as e:
return error_response(403, str(e))
except Exception as e:
return error_response(400, str(e))
@router.post("/qc-tasks/{task_id}/complete-with-result")
async def complete_task_with_result(
task_id: str,
@@ -1364,6 +1414,7 @@ async def complete_task_with_result(
if not t:
return error_response(404, "任务不存在")
was_done = (t.task_status or "").strip() == "ywc"
before = result_change_log_svc.snapshot_task_result_state(db, t, tenant_no)
if body.results:
result_svc.save_results_for_task(
db, task_id, body.results, tenant_no, user_id, commit=False,
@@ -1384,6 +1435,17 @@ async def complete_task_with_result(
task_status=body.task_status,
commit=False,
)
after = result_change_log_svc.snapshot_task_result_state(db, obj, tenant_no)
result_change_log_svc.append_task_result_change_log(
db,
task=obj,
tenant_no=tenant_no,
user_id=user_id,
operator_user_name=str(user.get("nickName") or user.get("nick_name") or ""),
before=before,
after=after,
operate_batch_id=body.operate_batch_id,
)
db.commit()
db.refresh(obj)
if (obj.task_status or "").strip() == "ywc":
+6
View File
@@ -241,6 +241,8 @@ async def list_received_samples(
pageSize: int = Query(10, ge=1, le=100),
keyword: Optional[str] = None,
sourceType: Optional[str] = None,
sampleTypeId: Optional[str] = Query(None, alias="sampleTypeId"),
isVoided: Optional[str] = Query(None, alias="isVoided"),
receptionTimeStart: Optional[str] = Query(None, alias="receptionTimeStart"),
receptionTimeEnd: Optional[str] = Query(None, alias="receptionTimeEnd"),
db: Session = Depends(get_db),
@@ -251,6 +253,8 @@ async def list_received_samples(
items, total = sr_svc.list_received_protocol_samples(
db, page=page, page_size=pageSize, tenant_no=tenant_no, keyword=keyword,
source_type=sourceType,
sample_type_id=sampleTypeId,
is_voided=sr_svc.parse_optional_bool(isVoided),
reception_time_start=receptionTimeStart,
reception_time_end=receptionTimeEnd,
user_info=user,
@@ -258,6 +262,8 @@ async def list_received_samples(
return success_response(_page_payload(items, total, page, pageSize))
except PermissionError as e:
return error_response(403, str(e))
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(400, str(e))
View File
Whitespace-only changes.
+51
View File
@@ -0,0 +1,51 @@
"""中试/临床/科研类申请单业务类型辅助。"""
from typing import Optional
# 临床科研与委托加工共用申请/交付/缴费/出库流程
RESEARCH_LIKE_BIZ_TYPES = ("basic_experiment", "contract_processing")
BIZ_TYPE_LABELS = {
"pilot_service": "中试服务",
"clinical_application": "临床应用",
"basic_experiment": "临床科研",
"contract_processing": "委托加工",
}
APPLICATION_NO_PREFIX = {
"clinical_application": "LCSQ",
"basic_experiment": "LCKY",
"contract_processing": "WTJG",
"pilot_service": "ZSSQ",
}
# 申请单项目组负责人审批(后续规则引擎可覆盖审批人,本期固定项目组负责人)
APPROVAL_PENDING = "dsp"
APPROVAL_PASSED = "ytg"
APPROVAL_REJECTED = "yth"
APPROVAL_STATUS_LABELS = {
APPROVAL_PENDING: "待审批",
APPROVAL_PASSED: "已通过",
APPROVAL_REJECTED: "已驳回",
}
def is_research_like_biz(biz_type: Optional[str]) -> bool:
return (biz_type or "") in RESEARCH_LIKE_BIZ_TYPES
def biz_type_label(biz_type: Optional[str]) -> str:
key = biz_type or ""
return BIZ_TYPE_LABELS.get(key, key or "")
def application_no_prefix(biz_type: Optional[str]) -> str:
key = biz_type or "pilot_service"
return APPLICATION_NO_PREFIX.get(key, APPLICATION_NO_PREFIX["pilot_service"])
def requires_leader_approval(biz_type: Optional[str]) -> bool:
return is_research_like_biz(biz_type)
def is_leader_approval_passed(approval_status: Optional[str]) -> bool:
return (approval_status or "") == APPROVAL_PASSED
@@ -0,0 +1,73 @@
"""申请单业务子类型(research_category)。
临床科研保留历史三项;委托加工使用产品四项,并支持「其他」自定义文本。
"""
from typing import Optional
from app.constants.pilot_biz import is_research_like_biz
CLINICAL_RESEARCH_CATEGORY_LABELS = {
"bio_tech_clinical": "生物新技术临床科研",
"joint_topic_declare": "临床课题联合申报",
"bio_pharma_rd": "生物制药研发",
}
CONTRACT_PROCESSING_CATEGORY_LABELS = {
"placenta_freeze_dried": "胎盘冻干粉",
"adipose_exosome": "脂肪外泌体",
"nk": "NK",
"msc": "MSC",
}
# 兼容旧导入名
RESEARCH_CATEGORY_LABELS = {
**CLINICAL_RESEARCH_CATEGORY_LABELS,
**CONTRACT_PROCESSING_CATEGORY_LABELS,
}
RESEARCH_CATEGORY_CODES = tuple(RESEARCH_CATEGORY_LABELS.keys())
CUSTOM_CATEGORY_MAX_LEN = 64
def research_category_label(code: Optional[str]) -> str:
if not code:
return ""
return RESEARCH_CATEGORY_LABELS.get(code, code)
def validate_research_category(
code: Optional[str],
required: bool = False,
*,
biz_type: Optional[str] = "basic_experiment",
) -> str:
value = (code or "").strip()
if not value:
if required:
raise ValueError("请选择业务类型")
return ""
bt = biz_type or "basic_experiment"
if bt == "contract_processing":
if value in CONTRACT_PROCESSING_CATEGORY_LABELS:
return value
if len(value) > CUSTOM_CATEGORY_MAX_LEN:
raise ValueError(f"业务类型不能超过{CUSTOM_CATEGORY_MAX_LEN}个字符")
# 自定义原文;禁止占用临床科研预置码
if value in CLINICAL_RESEARCH_CATEGORY_LABELS:
raise ValueError("业务类型无效")
return value
if bt == "basic_experiment" or is_research_like_biz(bt):
if value in CLINICAL_RESEARCH_CATEGORY_LABELS:
return value
if len(value) > CUSTOM_CATEGORY_MAX_LEN:
raise ValueError(f"业务类型不能超过{CUSTOM_CATEGORY_MAX_LEN}个字符")
# 自定义原文;禁止占用委托加工预置码
if value in CONTRACT_PROCESSING_CATEGORY_LABELS:
raise ValueError("业务类型无效")
return value
if value not in RESEARCH_CATEGORY_LABELS:
raise ValueError("业务类型无效")
return value
+3 -3
View File
@@ -136,14 +136,14 @@ class Settings(BaseSettings):
WX_TEMPLATE_DELIVERY_WARNING: str = "" # 配送时效预警模板ID
# 微信服务号(OA 审批/抄送通知)
# 总开关:false 时不发送审批/抄送/申请人进度/评论@提到/基础实验交付提醒/样本采集通知模板消息
# 总开关:false 时不发送审批/抄送/申请人进度/评论@提到/临床科研交付提醒/样本采集通知模板消息
WX_MP_NOTIFY_ENABLED: bool = False
WX_MP_APPID: str = ""
WX_MP_SECRET: str = ""
WX_MP_TEMPLATE_APPROVAL: str = ""
WX_MP_TEMPLATE_CC: str = ""
WX_MP_TEMPLATE_APPLICANT_PROGRESS: str = ""
# 基础实验交付日前一天提醒(出库提醒模板)
# 临床科研交付日前一天提醒(出库提醒模板)
WX_MP_TEMPLATE_BASIC_EXPERIMENT_DELIVERY: str = (
"oQNU3t0Q5kwc4KPJ8Z6yPA-k6qlsH9pikSCIb4eAwgM"
)
@@ -171,7 +171,7 @@ class Settings(BaseSettings):
WX_MP_TPL_PROGRESS_FIELD_APPROVER: str = "thing6"
WX_MP_TPL_PROGRESS_FIELD_RESULT: str = "const4"
WX_MP_TPL_PROGRESS_FIELD_TIME: str = "time11"
# 基础实验交付提醒:客户名称/产品名称/件数/收货联系人/出库时间
# 临床科研交付提醒:客户名称/产品名称/件数/收货联系人/出库时间
WX_MP_TPL_BE_DELIVERY_FIELD_CUSTOMER: str = "thing6"
WX_MP_TPL_BE_DELIVERY_FIELD_PRODUCT: str = "thing10"
WX_MP_TPL_BE_DELIVERY_FIELD_QTY: str = "character_string8"
+2 -2
View File
@@ -23,14 +23,14 @@ def resolve_research_donation_protocol_status_filter(
Returns:
("in", statuses) — 按所选状态 IN 过滤
("none", []) — 显式空选择,无匹配结果
("all", []) — 显式空选择,不限制协议状态
("default", DEFAULT_QC_DONATION_PROTOCOL_STATUSES) — 未传参,与列表默认一致
"""
if protocol_status is None:
return ("default", list(DEFAULT_QC_DONATION_PROTOCOL_STATUSES))
statuses = [s.strip() for s in str(protocol_status).split(",") if s.strip()]
if not statuses:
return ("none", [])
return ("all", [])
return ("in", statuses)
_PROTOCOL_STATUS_LABELS = {
+2 -2
View File
@@ -100,14 +100,14 @@ def _enrich_payment(db: Session, row: BizPilotPayment) -> Dict[str, Any]:
"applicationNo": app_row.application_no if app_row else "",
"applicationName": app_row.application_name if app_row else "",
"channelName": app_row.channel_name if app_row else "",
"patientName": "" if app_biz == "basic_experiment" else (patient_row.patient_name if patient_row else ""),
"patientName": "" if app_biz in ("basic_experiment", "contract_processing") else (patient_row.patient_name if patient_row else ""),
"cellType": cell_type,
"specText": spec_text,
"cellTypeSpec": cell_type_spec,
"paymentAmount": float(row.amount) if row.amount else 0,
"infusionTime": schedule_row.infusion_time.strftime("%Y-%m-%d %H:%M:%S") if schedule_row and schedule_row.infusion_time else "",
}
if app_biz == "basic_experiment" and app_row:
if app_biz in ("basic_experiment", "contract_processing") and app_row:
extra["projectTitle"] = app_row.project_title or ""
extra["customerName"] = app_row.customer_name or ""
extra["customerContact"] = app_row.customer_contact or ""
+3 -1
View File
@@ -739,6 +739,7 @@ def _sample_to_dict(s: BizProtocolSample) -> Dict[str, Any]:
"storageInDate": (s.storage_in_date or "").strip() if s.storage_in_date else "",
"detectStartDate": (s.detect_start_date or "").strip() if s.detect_start_date else "",
"voidDate": (s.void_date or "").strip() if s.void_date else "",
"voidDesc": (getattr(s, "void_desc", None) or "").strip() if (getattr(s, "void_desc", None) or "").strip() else "",
"storageExpireDate": (s.storage_expire_date or "").strip() if s.storage_expire_date else "",
**sample_special_to_dict(s),
"tenantNo": s.tenant_no,
@@ -1393,6 +1394,7 @@ def list_collection_protocols(
"sampleTypeName": type_name,
"sampleCode": code,
"sampleStatus": (s.sample_status or "").strip(),
"voidDesc": (getattr(s, "void_desc", None) or "").strip(),
"labStorageCode": lab_code_map.get(code, "") if code else "",
"transport": transport_dict,
"freight": freight_by_sample.get(s.id),
@@ -2677,7 +2679,7 @@ def update_collection_protocol(
next_status = protocol_status.strip()
assert_protocol_status_transition(obj.protocol_status or "", next_status, kind="protocol")
obj.protocol_status = next_status
if next_status == "yzf" and from_status != "yzf":
if next_status in ("yzf", "sdfq") and from_status not in ("yzf", "sdfq"):
voided_now = True
if next_status == "yzf" and void_time is not None:
if void_type is None or not str(void_type).strip():
@@ -0,0 +1,257 @@
"""临床科研/委托加工自定义业务类型 CRUD(biz_contract_processing_category)"""
from __future__ import annotations
import math
from datetime import datetime
from typing import Any, Dict, List, Optional, Tuple
from sqlalchemy import and_, func
from sqlalchemy.orm import Session
from app.constants.research_category import (
CLINICAL_RESEARCH_CATEGORY_LABELS,
CONTRACT_PROCESSING_CATEGORY_LABELS,
CUSTOM_CATEGORY_MAX_LEN,
)
from app.core.utils import generate_uuid
from app.models.models import BizContractProcessingCategory
_DEFAULT_BIZ_TYPE = "contract_processing"
_ALLOWED_BIZ_TYPES = ("basic_experiment", "contract_processing")
_RESERVED_NAMES = {
*CONTRACT_PROCESSING_CATEGORY_LABELS.keys(),
*CONTRACT_PROCESSING_CATEGORY_LABELS.values(),
*CLINICAL_RESEARCH_CATEGORY_LABELS.keys(),
*CLINICAL_RESEARCH_CATEGORY_LABELS.values(),
"__other__",
"其他",
}
def _normalize_biz_type(biz_type: Optional[str]) -> str:
value = (biz_type or _DEFAULT_BIZ_TYPE).strip()
if value not in _ALLOWED_BIZ_TYPES:
raise ValueError("业务类型所属业务线无效")
return value
def _row_to_dict(row: BizContractProcessingCategory) -> Dict[str, Any]:
return {
"id": row.id,
"categoryName": row.category_name or "",
"bizType": getattr(row, "biz_type", None) or _DEFAULT_BIZ_TYPE,
"tenantNo": row.tenant_no,
"orderNum": row.order_num if row.order_num is not None else 0,
"remark": row.remark or "",
"createTime": row.create_time.strftime("%Y-%m-%d %H:%M:%S") if row.create_time else "",
"updateTime": row.update_time.strftime("%Y-%m-%d %H:%M:%S") if row.update_time else "",
}
def _normalize_name(name: Optional[str]) -> str:
return (name or "").strip()
def _assert_valid_name(name: str) -> str:
value = _normalize_name(name)
if not value:
raise ValueError("业务类型名称不能为空")
if len(value) > CUSTOM_CATEGORY_MAX_LEN:
raise ValueError(f"业务类型不能超过{CUSTOM_CATEGORY_MAX_LEN}个字符")
if value in _RESERVED_NAMES:
raise ValueError("该名称与系统预置业务类型冲突,请更换")
return value
def _exists_name(
db: Session,
tenant_no: str,
name: str,
*,
biz_type: str,
exclude_id: Optional[str] = None,
) -> bool:
q = db.query(BizContractProcessingCategory.id).filter(
BizContractProcessingCategory.del_flag == 0,
BizContractProcessingCategory.tenant_no == tenant_no,
BizContractProcessingCategory.biz_type == biz_type,
BizContractProcessingCategory.category_name == name,
)
if exclude_id:
q = q.filter(BizContractProcessingCategory.id != exclude_id)
return q.first() is not None
def list_categories(
db: Session,
*,
page: int = 1,
page_size: int = 100,
keyword: Optional[str] = None,
tenant_no: Optional[str] = None,
biz_type: Optional[str] = None,
) -> Tuple[List[Dict[str, Any]], int]:
bt = _normalize_biz_type(biz_type)
def _filtered():
q0 = db.query(BizContractProcessingCategory).filter(
BizContractProcessingCategory.del_flag == 0,
BizContractProcessingCategory.biz_type == bt,
)
if tenant_no:
q0 = q0.filter(BizContractProcessingCategory.tenant_no == tenant_no)
kw = (keyword or "").strip()
if kw:
q0 = q0.filter(BizContractProcessingCategory.category_name.like(f"%{kw}%"))
return q0
total = (
_filtered()
.order_by(None)
.with_entities(func.count(BizContractProcessingCategory.id))
.scalar()
or 0
)
page = max(1, page)
page_size = min(max(1, page_size), 200)
rows = (
_filtered()
.order_by(
BizContractProcessingCategory.order_num.asc(),
BizContractProcessingCategory.create_time.desc(),
)
.offset((page - 1) * page_size)
.limit(page_size)
.all()
)
return [_row_to_dict(x) for x in rows], int(total)
def list_all_categories(
db: Session, *, tenant_no: str, biz_type: Optional[str] = None
) -> List[Dict[str, Any]]:
bt = _normalize_biz_type(biz_type)
rows = (
db.query(BizContractProcessingCategory)
.filter(
BizContractProcessingCategory.del_flag == 0,
BizContractProcessingCategory.tenant_no == tenant_no,
BizContractProcessingCategory.biz_type == bt,
)
.order_by(
BizContractProcessingCategory.order_num.asc(),
BizContractProcessingCategory.create_time.desc(),
)
.all()
)
return [_row_to_dict(x) for x in rows]
def get_category(
db: Session, category_id: str, tenant_no: Optional[str] = None
) -> Optional[BizContractProcessingCategory]:
q = db.query(BizContractProcessingCategory).filter(
and_(
BizContractProcessingCategory.id == category_id,
BizContractProcessingCategory.del_flag == 0,
)
)
if tenant_no:
q = q.filter(BizContractProcessingCategory.tenant_no == tenant_no)
return q.first()
def create_category(
db: Session,
*,
category_name: str,
tenant_no: str = "zkxw",
biz_type: Optional[str] = None,
order_num: Optional[int] = None,
remark: Optional[str] = None,
user_id: Optional[str] = None,
create_dept_id: str = "",
commit: bool = True,
) -> BizContractProcessingCategory:
bt = _normalize_biz_type(biz_type)
name = _assert_valid_name(category_name)
if _exists_name(db, tenant_no, name, biz_type=bt):
raise ValueError("业务类型已存在")
obj = BizContractProcessingCategory(
id=generate_uuid(),
category_name=name,
biz_type=bt,
tenant_no=tenant_no,
order_num=order_num if order_num is not None else 0,
remark=(remark or "").strip() or None,
create_by=user_id,
create_dept_id=create_dept_id or "",
create_time=datetime.now(),
update_by=user_id,
update_time=datetime.now(),
del_flag=0,
)
db.add(obj)
if commit:
db.commit()
db.refresh(obj)
else:
db.flush()
return obj
def update_category(
db: Session,
category_id: str,
*,
category_name: Optional[str] = None,
order_num: Optional[int] = None,
remark: Optional[str] = None,
user_id: Optional[str] = None,
tenant_no: Optional[str] = None,
) -> BizContractProcessingCategory:
obj = get_category(db, category_id, tenant_no=tenant_no)
if not obj:
raise ValueError("业务类型不存在")
bt = _normalize_biz_type(getattr(obj, "biz_type", None) or _DEFAULT_BIZ_TYPE)
if category_name is not None:
name = _assert_valid_name(category_name)
if _exists_name(db, obj.tenant_no, name, biz_type=bt, exclude_id=obj.id):
raise ValueError("业务类型已存在")
obj.category_name = name
if order_num is not None:
obj.order_num = order_num
if remark is not None:
obj.remark = remark.strip() or None
obj.update_by = user_id
obj.update_time = datetime.now()
db.add(obj)
db.commit()
db.refresh(obj)
return obj
def soft_delete_category(
db: Session,
category_id: str,
tenant_no: Optional[str] = None,
*,
commit: bool = True,
) -> None:
obj = get_category(db, category_id, tenant_no=tenant_no)
if not obj:
raise ValueError("业务类型不存在")
obj.del_flag = 1
obj.update_time = datetime.now()
db.add(obj)
if commit:
db.commit()
else:
db.flush()
def total_pages(total: int, page_size: int) -> int:
if total <= 0:
return 0
return int(math.ceil(total / float(page_size)))
+17
View File
@@ -179,6 +179,17 @@ def upsert_supplement(
del_flag=0,
)
db.add(row)
# 同步到新模块补充表/生产接收,保证实验室样本处理数据联动
from app.services.lab_sample_processing import sync_legacy_supplement_to_processing
sync_legacy_supplement_to_processing(
db,
tenant_no=tenant_no,
lab_storage_code=code,
sample_type_name=type_name,
payload=clean_payload,
operator_id=user_id,
)
db.commit()
db.refresh(row)
return get_supplement(db, tenant_no=tenant_no, lab_storage_code=code) or {}
@@ -258,10 +269,13 @@ def _build_cell_system(
clear_flag = checked
break
sample_status = str(getattr(sample, "sample_status", None) or "").strip()
base: Dict[str, Any] = {
"receptionId": rec.id,
"sampleCode": (rec.sample_code or sample.sample_code or "").strip(),
"labStorageCode": (rec.lab_storage_code or "").strip(),
"sampleStatus": sample_status,
"voidDesc": str(getattr(sample, "void_desc", None) or "").strip(),
"motherName": (party.mother_name if party else "") or "",
"collectionTime": ledger.format_cn_datetime(coll.sample_collect_time if coll else None),
"collectionTimeRaw": _fmt_raw(coll.sample_collect_time if coll else None),
@@ -342,10 +356,13 @@ def _build_donation_system(
qc_process: Dict[str, str],
) -> Dict[str, Any]:
prod = prod or {}
sample_status = str(getattr(sample, "sample_status", None) or "").strip()
base: Dict[str, Any] = {
"receptionId": rec.id,
"sampleCode": (rec.sample_code or sample.sample_code or "").strip(),
"labStorageCode": (rec.lab_storage_code or "").strip(),
"sampleStatus": sample_status,
"voidDesc": str(getattr(sample, "void_desc", None) or "").strip(),
"motherName": (party.mother_name if party else "") or "",
"receptionTime": ledger.format_cn_datetime(rec.reception_time),
"receptionTimeRaw": _fmt_raw(rec.reception_time),
+2 -1
View File
@@ -41,7 +41,8 @@ _QC_STATUS_LABELS = {
_BIZ_TYPE_LABELS = {
"pilot_service": "中试服务",
"clinical_application": "临床应用",
"basic_experiment": "基础实验",
"basic_experiment": "临床科研",
"contract_processing": "委托加工",
}
+187
View File
@@ -0,0 +1,187 @@
"""合作客户 CRUD(biz_partner_customer)"""
from __future__ import annotations
import math
from datetime import datetime
from typing import Any, Dict, List, Optional, Tuple
from sqlalchemy import and_, func, or_
from sqlalchemy.orm import Session
from app.core.utils import generate_uuid
from app.models.models import BizPartnerCustomer
def _row_to_dict(row: BizPartnerCustomer) -> Dict[str, Any]:
return {
"id": row.id,
"customerName": row.customer_name or "",
"customerContact": row.customer_contact or "",
"customerPhone": row.customer_phone or "",
"tenantNo": row.tenant_no,
"orderNum": row.order_num if row.order_num is not None else 0,
"remark": row.remark or "",
"createTime": row.create_time.strftime("%Y-%m-%d %H:%M:%S") if row.create_time else "",
"updateTime": row.update_time.strftime("%Y-%m-%d %H:%M:%S") if row.update_time else "",
}
def list_partner_customers(
db: Session,
*,
page: int = 1,
page_size: int = 10,
keyword: Optional[str] = None,
tenant_no: Optional[str] = None,
) -> Tuple[List[Dict[str, Any]], int]:
def _filtered():
q0 = db.query(BizPartnerCustomer).filter(BizPartnerCustomer.del_flag == 0)
if tenant_no:
q0 = q0.filter(BizPartnerCustomer.tenant_no == tenant_no)
kw = (keyword or "").strip()
if kw:
like = f"%{kw}%"
q0 = q0.filter(
or_(
BizPartnerCustomer.customer_name.like(like),
BizPartnerCustomer.customer_contact.like(like),
BizPartnerCustomer.customer_phone.like(like),
)
)
return q0
total = _filtered().order_by(None).with_entities(func.count(BizPartnerCustomer.id)).scalar() or 0
page = max(1, page)
page_size = min(max(1, page_size), 200)
rows = (
_filtered()
.order_by(BizPartnerCustomer.create_time.desc())
.offset((page - 1) * page_size)
.limit(page_size)
.all()
)
return [_row_to_dict(x) for x in rows], int(total)
def get_partner_customer(
db: Session, customer_id: str, tenant_no: Optional[str] = None
) -> Optional[BizPartnerCustomer]:
q = db.query(BizPartnerCustomer).filter(
and_(BizPartnerCustomer.id == customer_id, BizPartnerCustomer.del_flag == 0)
)
if tenant_no:
q = q.filter(BizPartnerCustomer.tenant_no == tenant_no)
return q.first()
def create_partner_customer(
db: Session,
*,
customer_name: str,
customer_contact: str,
customer_phone: str,
tenant_no: str = "zkxw",
order_num: Optional[int] = None,
remark: Optional[str] = None,
user_id: Optional[str] = None,
create_dept_id: str = "",
commit: bool = True,
) -> BizPartnerCustomer:
name = (customer_name or "").strip()
contact = (customer_contact or "").strip()
phone = (customer_phone or "").strip()
if not name:
raise ValueError("客户名称不能为空")
if not contact:
raise ValueError("客户联系人不能为空")
if not phone:
raise ValueError("客户联系方式不能为空")
obj = BizPartnerCustomer(
id=generate_uuid(),
customer_name=name,
customer_contact=contact,
customer_phone=phone,
tenant_no=tenant_no,
order_num=order_num if order_num is not None else 0,
remark=(remark or "").strip() or None,
create_by=user_id,
create_dept_id=create_dept_id or "",
create_time=datetime.now(),
update_by=user_id,
update_time=datetime.now(),
del_flag=0,
)
db.add(obj)
if commit:
db.commit()
db.refresh(obj)
else:
db.flush()
return obj
def update_partner_customer(
db: Session,
customer_id: str,
*,
customer_name: Optional[str] = None,
customer_contact: Optional[str] = None,
customer_phone: Optional[str] = None,
order_num: Optional[int] = None,
remark: Optional[str] = None,
user_id: Optional[str] = None,
tenant_no: Optional[str] = None,
) -> BizPartnerCustomer:
obj = get_partner_customer(db, customer_id, tenant_no=tenant_no)
if not obj:
raise ValueError("合作客户不存在")
if customer_name is not None:
name = customer_name.strip()
if not name:
raise ValueError("客户名称不能为空")
obj.customer_name = name
if customer_contact is not None:
contact = customer_contact.strip()
if not contact:
raise ValueError("客户联系人不能为空")
obj.customer_contact = contact
if customer_phone is not None:
phone = customer_phone.strip()
if not phone:
raise ValueError("客户联系方式不能为空")
obj.customer_phone = phone
if order_num is not None:
obj.order_num = order_num
if remark is not None:
obj.remark = remark.strip() or None
obj.update_by = user_id
obj.update_time = datetime.now()
db.add(obj)
db.commit()
db.refresh(obj)
return obj
def soft_delete_partner_customer(
db: Session,
customer_id: str,
tenant_no: Optional[str] = None,
*,
commit: bool = True,
) -> None:
obj = get_partner_customer(db, customer_id, tenant_no=tenant_no)
if not obj:
raise ValueError("合作客户不存在")
obj.del_flag = 1
obj.update_time = datetime.now()
db.add(obj)
if commit:
db.commit()
else:
db.flush()
def total_pages(total: int, page_size: int) -> int:
if total <= 0:
return 0
return int(math.ceil(total / float(page_size)))
+547 -60
View File
@@ -25,6 +25,17 @@ from app.models.models import (
)
from app.crud import pilot_checkup
from app.crud.collection_protocol import attachments_to_urls, urls_to_attachment_list
from app.constants.pilot_biz import (
APPROVAL_PASSED,
APPROVAL_PENDING,
APPROVAL_REJECTED,
application_no_prefix,
is_leader_approval_passed,
is_research_like_biz,
requires_leader_approval,
)
from app.constants.research_category import validate_research_category
from app.models.project_management import Project, ProjectTeam, ProjectTeamMember
# ────────────────────────────────────────────
@@ -76,12 +87,7 @@ def _release_application_no_for_soft_delete(application_no: str, row_id: str) ->
def _generate_application_no(db: Session, tenant_no: str, biz_type: str = "pilot_service") -> str:
today_str = datetime.now().strftime("%Y%m%d")
if biz_type == "clinical_application":
prefix = f"LCSQ{today_str}"
elif biz_type == "basic_experiment":
prefix = f"JCSY{today_str}"
else:
prefix = f"ZSSQ{today_str}"
prefix = f"{application_no_prefix(biz_type)}{today_str}"
existing = (
db.query(BizPilotApplication.application_no)
.filter(
@@ -114,7 +120,14 @@ def _resolve_application_attachment_payload(raw: dict) -> None:
raw["attachmentUrls"] = (raw["attachmentUrls"] or "").strip()
def _row_to_dict_application(row, db=None, tenant_no=None) -> Dict[str, Any]:
def _row_to_dict_application(
row,
db=None,
tenant_no=None,
current_user_id: Optional[str] = None,
*,
is_super_admin: bool = False,
) -> Dict[str, Any]:
tn = tenant_no or row.tenant_no
d: Dict[str, Any] = {
"id": row.id,
@@ -125,7 +138,16 @@ def _row_to_dict_application(row, db=None, tenant_no=None) -> Dict[str, Any]:
"customerName": row.customer_name or "",
"customerContact": row.customer_contact or "",
"customerPhone": row.customer_phone or "",
"researchCategory": getattr(row, "research_category", None) or "",
"applicationStatus": row.application_status or "",
"approvalStatus": getattr(row, "approval_status", None) or "",
"approvalUserId": getattr(row, "approval_user_id", None) or "",
"approvalTime": (
row.approval_time.strftime("%Y-%m-%d %H:%M:%S")
if getattr(row, "approval_time", None)
else ""
),
"approvalRemark": getattr(row, "approval_remark", None) or "",
"bizType": row.biz_type or "pilot_service",
"channelServiceOrderId": row.channel_service_order_id or "",
"channelId": row.channel_id or "",
@@ -192,6 +214,21 @@ def _row_to_dict_application(row, db=None, tenant_no=None) -> Dict[str, Any]:
d["serviceOrderNo"] = ""
d["orderType"] = ""
project_leader_uid = _project_leader_user_id(db, tenant_no, row.project_id)
team_leader_uid = _team_leader_user_id(db, tenant_no, row.project_id)
d["projectLeaderUserId"] = project_leader_uid
d["teamLeaderUserId"] = team_leader_uid
approval = (getattr(row, "approval_status", None) or "").strip()
uid = (current_user_id or "").strip()
# 项目组负责人或超管可批;待审批/已通过/已驳回均可改结论(data_scope=1 不可代批)
d["canApprove"] = bool(
requires_leader_approval(row.biz_type)
and (getattr(row, "application_status", None) or "") != "yzf"
and approval in (APPROVAL_PENDING, APPROVAL_PASSED, APPROVAL_REJECTED)
and team_leader_uid
and (is_super_admin or (uid and team_leader_uid == uid))
)
return d
@@ -318,6 +355,213 @@ def _row_to_dict_infusion_schedule(row, cell_products: Optional[List[Dict[str, A
# ────────────────────────────────────────────
def _is_super_admin_user(user_info: Optional[dict]) -> bool:
"""科研可见/审批跨组仅认超级管理员;角色 data_scope=1 不放开。"""
return bool(user_info) and (user_info.get("role") or "") == "super_admin"
def _led_team_ids(db: Session, tenant_no: str, user_id: str) -> List[str]:
rows = (
db.query(ProjectTeam.id)
.filter(
ProjectTeam.tenant_no == tenant_no,
ProjectTeam.del_flag == 0,
ProjectTeam.leader_user_id == user_id,
)
.all()
)
return [r[0] for r in rows if r[0]]
def _member_team_ids(db: Session, tenant_no: str, user_id: str) -> List[str]:
rows = (
db.query(ProjectTeamMember.team_id)
.filter(
ProjectTeamMember.tenant_no == tenant_no,
ProjectTeamMember.del_flag == 0,
ProjectTeamMember.user_id == user_id,
)
.all()
)
return [r[0] for r in rows if r[0]]
def _project_ids_for_teams(db: Session, tenant_no: str, team_ids: List[str]):
if not team_ids:
return db.query(Project.id).filter(False)
return db.query(Project.id).filter(
Project.tenant_no == tenant_no,
Project.del_flag == 0,
Project.team_id.in_(team_ids),
)
def apply_research_like_visibility(
q,
db: Session,
tenant_no: str,
user_info: Optional[dict],
*,
for_approval: bool = False,
):
"""临床科研/委托加工可见性:成员仅本人创建;项目组负责人看本项目组;仅超管全量。
审批列表(for_approval):仅项目组负责人看本项目组;成员为空;仅超管全量。
角色 data_scope=1 不视为跨组管理员。
"""
if _is_super_admin_user(user_info):
return q
uid = ((user_info or {}).get("user_id") or "").strip()
if not uid:
return q.filter(False)
led_ids = _led_team_ids(db, tenant_no, uid)
if for_approval:
if not led_ids:
return q.filter(False)
return q.filter(
BizPilotApplication.project_id.in_(
_project_ids_for_teams(db, tenant_no, led_ids)
)
)
member_ids = _member_team_ids(db, tenant_no, uid)
conditions = []
if led_ids:
conditions.append(
BizPilotApplication.project_id.in_(
_project_ids_for_teams(db, tenant_no, led_ids)
)
)
if member_ids:
conditions.append(
and_(
BizPilotApplication.create_by == uid,
BizPilotApplication.project_id.in_(
_project_ids_for_teams(db, tenant_no, member_ids)
),
)
)
if not conditions:
return q.filter(False)
return q.filter(or_(*conditions))
def user_can_access_research_application(
db: Session,
tenant_no: str,
user_info: Optional[dict],
app: BizPilotApplication,
*,
for_approval: bool = False,
) -> bool:
if not requires_leader_approval(getattr(app, "biz_type", None)):
return True
if _is_super_admin_user(user_info):
return True
uid = ((user_info or {}).get("user_id") or "").strip()
if not uid:
return False
team_leader = _team_leader_user_id(db, tenant_no, app.project_id)
if for_approval:
return bool(team_leader and team_leader == uid)
if team_leader and team_leader == uid:
return True
if (app.create_by or "").strip() != uid:
return False
# 本人创建:须仍属于该项目所在项目组(负责人或成员)
project = (
db.query(Project.team_id)
.filter(
Project.id == app.project_id,
Project.tenant_no == tenant_no,
Project.del_flag == 0,
)
.first()
)
if not project or not project[0]:
return False
team_id = project[0]
if team_id in _led_team_ids(db, tenant_no, uid):
return True
return team_id in _member_team_ids(db, tenant_no, uid)
def _require_research_project_with_leader(
db: Session, tenant_no: str, project_id: Optional[str]
) -> Project:
pid = (project_id or "").strip()
if not pid:
raise ValueError("请选择项目")
project = (
db.query(Project)
.filter(
Project.id == pid,
Project.tenant_no == tenant_no,
Project.del_flag == 0,
)
.first()
)
if not project:
raise ValueError("项目不存在")
team = (
db.query(ProjectTeam)
.filter(
ProjectTeam.id == project.team_id,
ProjectTeam.tenant_no == tenant_no,
ProjectTeam.del_flag == 0,
)
.first()
)
if not team or not (team.leader_user_id or "").strip():
raise ValueError("所选项目所属项目组未设置负责人,无法提交审批")
return project
def assert_research_leader_approved(app: BizPilotApplication) -> None:
"""未通过项目组负责人审批时,禁止开始/建交付计划/派发工单。"""
if not requires_leader_approval(getattr(app, "biz_type", None)):
return
if not is_leader_approval_passed(getattr(app, "approval_status", None)):
raise ValueError("申请单尚未通过项目组负责人审批,无法派发生产/质检工单")
def _project_leader_user_id(db: Session, tenant_no: str, project_id: Optional[str]) -> str:
if not project_id:
return ""
project = (
db.query(Project.leader_user_id)
.filter(
Project.id == project_id,
Project.tenant_no == tenant_no,
Project.del_flag == 0,
)
.first()
)
return (project[0] if project else "") or ""
def _team_leader_user_id(db: Session, tenant_no: str, project_id: Optional[str]) -> str:
if not project_id:
return ""
row = (
db.query(ProjectTeam.leader_user_id)
.join(
Project,
and_(
Project.team_id == ProjectTeam.id,
Project.tenant_no == tenant_no,
Project.del_flag == 0,
),
)
.filter(
Project.id == project_id,
ProjectTeam.tenant_no == tenant_no,
ProjectTeam.del_flag == 0,
)
.first()
)
return (row[0] if row else "") or ""
def list_applications(
db: Session,
tenant_no: str,
@@ -328,24 +572,47 @@ def list_applications(
page_size: int = 10,
channel_id: Optional[str] = None,
application_status: Optional[str] = None,
approval_status: Optional[str] = None,
pending_mine: bool = False,
channel_service_order_id: Optional[str] = None,
keyword: Optional[str] = None,
biz_type: Optional[str] = None,
for_approval: bool = False,
):
q = db.query(BizPilotApplication).filter(
BizPilotApplication.tenant_no == tenant_no,
BizPilotApplication.del_flag == 0,
)
q = filter_assignment(q, BizPilotApplication, db, tenant_no, project_id, team_id)
research_like = is_research_like_biz(biz_type)
if user_info is not None:
from app.core.data_scope import apply_data_scope
q = apply_data_scope(q, BizPilotApplication, user_info, db, tenant_no)
if research_like:
q = apply_research_like_visibility(
q, db, tenant_no, user_info, for_approval=for_approval
)
else:
from app.core.data_scope import apply_data_scope
q = apply_data_scope(q, BizPilotApplication, user_info, db, tenant_no)
if channel_id:
q = q.filter(BizPilotApplication.channel_id == channel_id)
if application_status:
statuses = [s.strip() for s in application_status.split(",") if s.strip()]
if statuses:
q = q.filter(BizPilotApplication.application_status.in_(statuses))
if approval_status:
statuses = [s.strip() for s in approval_status.split(",") if s.strip()]
if statuses:
q = q.filter(BizPilotApplication.approval_status.in_(statuses))
if pending_mine and user_info is not None:
uid = (user_info.get("user_id") or "").strip()
led_ids = _led_team_ids(db, tenant_no, uid)
q = q.filter(
BizPilotApplication.approval_status == APPROVAL_PENDING,
BizPilotApplication.project_id.in_(
_project_ids_for_teams(db, tenant_no, led_ids)
),
)
if channel_service_order_id:
q = q.filter(BizPilotApplication.channel_service_order_id == channel_service_order_id)
if biz_type:
@@ -390,7 +657,17 @@ def list_applications(
.limit(page_size)
.all()
)
items = [_row_to_dict_application(r, db, tenant_no) for r in rows]
current_uid = ""
is_admin = False
if user_info is not None:
current_uid = (user_info.get("user_id") or "").strip()
is_admin = _is_super_admin_user(user_info)
items = [
_row_to_dict_application(
r, db, tenant_no, current_user_id=current_uid, is_super_admin=is_admin
)
for r in rows
]
return {
"list": items,
"pagination": {"page": page, "pageSize": page_size, "total": total},
@@ -423,7 +700,10 @@ def get_application(db: Session, app_id: str, tenant_no: str) -> Optional[Dict[s
plan_id = plan.get("id")
if plan_id:
result["infusionSchedules"] = list_schedules_by_plan(db, plan_id, tenant_no)
if row.biz_type in ("clinical_application", "basic_experiment") and result["infusionSchedules"]:
if (
row.biz_type in ("clinical_application", "basic_experiment", "contract_processing")
and result["infusionSchedules"]
):
from app.crud import clinical_payment
payment_map = clinical_payment.map_payments_by_schedule_id(
@@ -455,9 +735,10 @@ def create_application(
customer_name = ""
customer_contact = ""
customer_phone = ""
research_category = ""
consent_form_urls = data.get("consentFormUrls") or None
if biz_type == "basic_experiment":
if is_research_like_biz(biz_type):
if not (data.get("projectTitle") or "").strip():
raise ValueError("请填写课题名称")
if not (data.get("customerName") or "").strip():
@@ -466,13 +747,30 @@ def create_application(
raise ValueError("请填写客户联系人")
if not (data.get("customerPhone") or "").strip():
raise ValueError("请填写客户联系方式")
research_category = validate_research_category(
data.get("researchCategory"), required=True, biz_type=biz_type
)
project_title = (data.get("projectTitle") or "").strip()
customer_name = (data.get("customerName") or "").strip()
customer_contact = (data.get("customerContact") or "").strip()
customer_phone = (data.get("customerPhone") or "").strip()
channel_service_order_id = ""
channel_id = ""
# 临床科研/委托加工申请单不再要求渠道
channel_id = (data.get("channelId") or "").strip()
channel_name = ""
if channel_id:
ch = (
db.query(BizChannel)
.filter(
BizChannel.id == channel_id,
BizChannel.tenant_no == tenant_no,
BizChannel.del_flag == 0,
)
.first()
)
if not ch:
raise ValueError("渠道不存在")
channel_name = ch.channel_name or ""
consent_form_urls = None
elif not channel_service_order_id and biz_type != "clinical_application":
raise ValueError("请选择渠道服务订单")
@@ -517,9 +815,14 @@ def create_application(
now = datetime.now()
application_no = _generate_application_no(db, tenant_no, biz_type=biz_type)
project_id = data.get("projectId", data.get("project_id")) or None
approval_status = None
if requires_leader_approval(biz_type):
_require_research_project_with_leader(db, tenant_no, project_id)
approval_status = APPROVAL_PENDING
row = BizPilotApplication(
project_id=data.get("projectId", data.get("project_id")) or None,
project_id=project_id,
id=str(uuid.uuid4()),
application_no=application_no,
application_name=data.get("applicationName") or "",
@@ -527,7 +830,9 @@ def create_application(
customer_name=customer_name or None,
customer_contact=customer_contact or None,
customer_phone=customer_phone or None,
research_category=research_category or None,
application_status="dks",
approval_status=approval_status,
channel_service_order_id=channel_service_order_id or "",
channel_id=(
(svc_order.channel_id or "" if svc_order else "")
@@ -586,11 +891,74 @@ def update_application(db: Session, app_id: str, data: dict, tenant_no: str) ->
row.customer_contact = (data["customerContact"] or "").strip() or None
if "customerPhone" in data and data["customerPhone"] is not None:
row.customer_phone = (data["customerPhone"] or "").strip() or None
if "researchCategory" in data and data["researchCategory"] is not None:
row_biz = row.biz_type or ""
if is_research_like_biz(row_biz):
row.research_category = validate_research_category(
data.get("researchCategory"), required=True, biz_type=row_biz
) or None
else:
row.research_category = validate_research_category(
data.get("researchCategory"), required=False, biz_type=row_biz
) or None
if "channelId" in data and data["channelId"] is not None:
row_biz = row.biz_type or ""
if is_research_like_biz(row_biz):
# 临床科研/委托加工允许清空或保留渠道(表单已去掉渠道栏)
new_channel_id = (data.get("channelId") or "").strip()
if not new_channel_id:
row.channel_id = ""
row.channel_name = ""
else:
ch = (
db.query(BizChannel)
.filter(
BizChannel.id == new_channel_id,
BizChannel.tenant_no == tenant_no,
BizChannel.del_flag == 0,
)
.first()
)
if not ch:
raise ValueError("渠道不存在")
row.channel_id = new_channel_id
row.channel_name = ch.channel_name or ""
row.channel_service_order_id = ""
elif row_biz == "clinical_application":
new_channel_id = (data.get("channelId") or "").strip()
if not new_channel_id:
raise ValueError("请选择渠道")
ch = (
db.query(BizChannel)
.filter(
BizChannel.id == new_channel_id,
BizChannel.tenant_no == tenant_no,
BizChannel.del_flag == 0,
)
.first()
)
if not ch:
raise ValueError("渠道不存在")
row.channel_id = new_channel_id
row.channel_name = ch.channel_name or ""
if "consentFormUrls" in data:
row.consent_form_urls = data.get("consentFormUrls") or None
if "attachmentUrls" in data:
row.attachment_urls = data.get("attachmentUrls") or None
# 驳回后保存即重新提交待审批(后续规则引擎可在此切换审批人)
if (
requires_leader_approval(row.biz_type)
and (row.approval_status or "") == APPROVAL_REJECTED
and row.application_status == "dks"
):
_require_research_project_with_leader(db, tenant_no, row.project_id)
row.approval_status = APPROVAL_PENDING
row.approval_user_id = None
row.approval_time = None
row.approval_remark = None
row.update_time = datetime.now()
db.commit()
db.refresh(row)
return _row_to_dict_application(row, db, tenant_no)
@@ -631,6 +999,7 @@ def start_application(db: Session, app_id: str, tenant_no: str, user_id: str) ->
raise ValueError("申请单不存在")
if row.application_status != "dks":
raise ValueError("当前状态不允许开始")
assert_research_leader_approved(row)
row.application_status = "jxz"
row.update_by = user_id
@@ -640,6 +1009,118 @@ def start_application(db: Session, app_id: str, tenant_no: str, user_id: str) ->
return _row_to_dict_application(row, db, tenant_no)
def approve_application(
db: Session,
app_id: str,
tenant_no: str,
user_id: str,
*,
approval_status: str,
approval_remark: Optional[str] = None,
is_super_admin: bool = False,
) -> Dict[str, Any]:
"""项目组负责人审批申请单。结论:ytg 通过 / yth 驳回。
普通用户仅该申请单所属项目组的负责人可批;仅超级管理员可代批(data_scope=1 不可代批)。
"""
conclusion = (approval_status or "").strip()
if conclusion not in (APPROVAL_PASSED, APPROVAL_REJECTED):
raise ValueError("请选择通过或驳回")
row = (
db.query(BizPilotApplication)
.filter(
BizPilotApplication.id == app_id,
BizPilotApplication.tenant_no == tenant_no,
BizPilotApplication.del_flag == 0,
)
.first()
)
if not row:
raise ValueError("申请单不存在")
if not requires_leader_approval(row.biz_type):
raise ValueError("当前业务类型无需项目组负责人审批")
if row.application_status == "yzf":
raise ValueError("已作废申请单不可审批")
current_approval = (row.approval_status or "").strip()
# 待审批、已通过、已驳回均可改结论(例如驳回后改为通过)
if current_approval not in (APPROVAL_PENDING, APPROVAL_PASSED, APPROVAL_REJECTED):
raise ValueError("当前审批状态不可提交结论")
_require_research_project_with_leader(db, tenant_no, row.project_id)
team_leader_uid = _team_leader_user_id(db, tenant_no, row.project_id)
if not is_super_admin and team_leader_uid != (user_id or "").strip():
raise ValueError("仅该项目组的负责人可审批")
now = datetime.now()
row.approval_status = conclusion
row.approval_user_id = user_id
row.approval_time = now
row.approval_remark = (approval_remark or "").strip() or None
row.update_by = user_id
row.update_time = now
if conclusion == APPROVAL_PASSED:
_backfill_outbound_work_orders_for_application(
db,
app=row,
tenant_no=tenant_no,
user_id=user_id,
dept_id=row.create_dept_id or "",
)
db.commit()
db.refresh(row)
return _row_to_dict_application(row, db, tenant_no)
def _backfill_outbound_work_orders_for_application(
db: Session,
*,
app: BizPilotApplication,
tenant_no: str,
user_id: str,
dept_id: str,
) -> None:
"""审批通过后,为已有交付计划补建出库生产/质检工单。"""
from app.crud import production_work_order as pwo_svc
from app.crud import qc_work_order as qc_svc
schedule_ids = (
db.query(BizPilotInfusionSchedule.id)
.join(
BizPilotInfusionPlan,
and_(
BizPilotInfusionSchedule.infusion_plan_id == BizPilotInfusionPlan.id,
BizPilotInfusionPlan.del_flag == 0,
),
)
.filter(
BizPilotInfusionPlan.pilot_application_id == app.id,
BizPilotInfusionPlan.tenant_no == tenant_no,
BizPilotInfusionSchedule.tenant_no == tenant_no,
BizPilotInfusionSchedule.del_flag == 0,
)
.all()
)
biz_type = app.biz_type or "pilot_service"
for (schedule_id,) in schedule_ids:
pwo_svc.create_outbound_production_work_order(
db,
schedule_id=schedule_id,
tenant_no=tenant_no,
user_id=user_id,
create_dept_id=dept_id,
biz_type=biz_type,
)
qc_svc.create_outbound_qc_work_order(
db,
schedule_id=schedule_id,
tenant_no=tenant_no,
user_id=user_id,
create_dept_id=dept_id,
biz_type=biz_type,
)
def complete_application(db: Session, app_id: str, tenant_no: str, user_id: str) -> Dict[str, Any]:
row = (
db.query(BizPilotApplication)
@@ -1161,12 +1642,18 @@ def auto_generate_schedules(
.first()
)
schedule_biz_type = (_app.biz_type if _app else None) or "pilot_service"
approval_ok = (not _app) or is_leader_approval_passed(
getattr(_app, "approval_status", None)
) or not requires_leader_approval(schedule_biz_type)
total = plan.total_course_count or 0
if total <= 0:
raise ValueError("总疗程数必须大于0")
now = datetime.now()
from app.crud import production_work_order as pwo_svc
from app.crud import qc_work_order as qc_svc
for i in range(1, total + 1):
sched = BizPilotInfusionSchedule(
id=str(uuid.uuid4()),
@@ -1187,26 +1674,23 @@ def auto_generate_schedules(
del_flag=0,
)
db.add(sched)
from app.crud import production_work_order as pwo_svc
pwo_svc.create_outbound_production_work_order(
db,
schedule_id=sched.id,
tenant_no=tenant_no,
user_id=user_id,
create_dept_id=dept_id,
biz_type=schedule_biz_type,
)
from app.crud import qc_work_order as qc_svc
qc_svc.create_outbound_qc_work_order(
db,
schedule_id=sched.id,
tenant_no=tenant_no,
user_id=user_id,
create_dept_id=dept_id,
biz_type=schedule_biz_type,
)
if approval_ok:
pwo_svc.create_outbound_production_work_order(
db,
schedule_id=sched.id,
tenant_no=tenant_no,
user_id=user_id,
create_dept_id=dept_id,
biz_type=schedule_biz_type,
)
qc_svc.create_outbound_qc_work_order(
db,
schedule_id=sched.id,
tenant_no=tenant_no,
user_id=user_id,
create_dept_id=dept_id,
biz_type=schedule_biz_type,
)
db.commit()
return {"generatedCount": total}
@@ -1284,6 +1768,9 @@ def create_schedule(
.first()
) if _plan else None
schedule_biz_type = (_app.biz_type if _app else None) or "pilot_service"
approval_ok = (not _app) or is_leader_approval_passed(
getattr(_app, "approval_status", None)
) or not requires_leader_approval(schedule_biz_type)
row = BizPilotInfusionSchedule(
id=schedule_id,
@@ -1314,35 +1801,35 @@ def create_schedule(
products = _create_schedule_products(
db, schedule_id, cell_products, tenant_no, user_id, dept_id, now
)
# 自动创建出库生产工单
from app.crud import production_work_order as pwo_svc
# 科研类未审批通过前不派发生产/质检工单(审批通过后补建)
if approval_ok:
from app.crud import production_work_order as pwo_svc
from app.crud import qc_work_order as qc_svc
pwo_svc.create_outbound_production_work_order(
db,
schedule_id=schedule_id,
tenant_no=tenant_no,
user_id=user_id,
create_dept_id=dept_id,
biz_type=schedule_biz_type,
)
# 自动创建出库质检工单
from app.crud import qc_work_order as qc_svc
qc_svc.create_outbound_qc_work_order(
db,
schedule_id=schedule_id,
tenant_no=tenant_no,
user_id=user_id,
create_dept_id=dept_id,
biz_type=schedule_biz_type,
)
pwo_svc.create_outbound_production_work_order(
db,
schedule_id=schedule_id,
tenant_no=tenant_no,
user_id=user_id,
create_dept_id=dept_id,
biz_type=schedule_biz_type,
)
qc_svc.create_outbound_qc_work_order(
db,
schedule_id=schedule_id,
tenant_no=tenant_no,
user_id=user_id,
create_dept_id=dept_id,
biz_type=schedule_biz_type,
)
# 临床应用自动创建缴费记录
plan_row = _plan
if plan_row:
application = _app
if (
application
and application.biz_type in ("clinical_application", "basic_experiment")
and application.biz_type
in ("clinical_application", "basic_experiment", "contract_processing")
and data.get("amount")
):
from app.crud.clinical_payment import auto_create_payment
@@ -1601,7 +2088,7 @@ def _get_or_create_infusion_plan(
user_id: str,
dept_id: str,
) -> BizPilotInfusionPlan:
"""获取或创建申请单下的输注/售卖方案(基础实验批量创建售卖计划用)。"""
"""获取或创建申请单下的输注/售卖方案(临床科研批量创建售卖计划用)。"""
plans = list_infusion_plans(db, application_id, tenant_no)
if plans:
plan_row = (
@@ -1647,7 +2134,7 @@ def create_basic_experiment_sale_schedules(
user_id: str,
dept_id: str,
) -> List[Dict[str, Any]]:
"""基础实验:每个产品行创建一条售卖计划(一产品一计划)。"""
"""临床科研:每个产品行创建一条售卖计划(一产品一计划)。"""
app = (
db.query(BizPilotApplication)
.filter(
@@ -1659,8 +2146,8 @@ def create_basic_experiment_sale_schedules(
)
if not app:
raise ValueError("申请单不存在")
if (app.biz_type or "") != "basic_experiment":
raise ValueError("仅基础实验申请单可批量创建售卖计划")
if not is_research_like_biz(app.biz_type):
raise ValueError("仅临床科研/委托加工申请单可批量创建售卖计划")
if not product_lines:
raise ValueError("请至少添加一行售卖产品")
@@ -78,6 +78,8 @@ def _row_to_dict_schedule(
"infusionStatus": row.infusion_status or "",
"cancelReason": row.cancel_reason or "",
"qcStatus": row.qc_status or "",
# 申请单费用(交付计划金额);勿与缴费 payment.amount 混淆
"feeAmount": float(row.amount) if row.amount is not None else None,
"attachments": row.attachments or "",
"remark": row.remark or "",
"createTime": row.create_time.strftime("%Y-%m-%d %H:%M:%S") if row.create_time else "",
@@ -385,17 +387,26 @@ def list_infusion_schedules_mgmt(
products = _get_products_for_schedule(db, row.id, tenant_no)
plan_meta = plan_course_meta.get(row.infusion_plan_id) if row.infusion_plan_id else None
items.append(
_row_to_dict_schedule(
row,
application,
plan_row,
patient,
products,
service_order,
plan_meta=plan_meta,
)
item = _row_to_dict_schedule(
row,
application,
plan_row,
patient,
products,
service_order,
plan_meta=plan_meta,
)
if products:
primary = products[0] or {}
item["projectName"] = primary.get("projectName") or ""
item["agreementPrice"] = primary.get("agreementPrice")
item["actualPrice"] = primary.get("actualPrice")
item["quantity"] = primary.get("quantity")
if not item.get("cellType"):
item["cellType"] = primary.get("cellTypeName") or ""
if not item.get("specText"):
item["specText"] = primary.get("specText") or ""
items.append(item)
schedule_ids = [item["id"] for item in items if item.get("id")]
if schedule_ids:
@@ -560,7 +571,7 @@ def get_infusion_schedule_detail(
"outboundHandover": handover_svc.get_outbound_handover_view(db, schedule_id, tenant_no),
"infusionConfirm": confirm_svc.get_confirm_by_schedule(db, schedule_id, tenant_no) or {},
}
if application and (application.biz_type or "") in ("clinical_application", "basic_experiment"):
if application and (application.biz_type or "") in ("clinical_application", "basic_experiment", "contract_processing"):
from app.crud import clinical_payment
payment = clinical_payment.get_payment_by_schedule(
@@ -918,8 +929,8 @@ def _deduct_fee_on_complete(db: Session, schedule_id: str, tenant_no: str, user_
if not application:
raise ValueError("中试申请单不存在")
# 临床应用/基础实验走缴费模块,不走服务订单扣费
if (application.biz_type or "") in ("clinical_application", "basic_experiment"):
# 临床应用/临床科研走缴费模块,不走服务订单扣费
if (application.biz_type or "") in ("clinical_application", "basic_experiment", "contract_processing"):
return
if not application.channel_service_order_id:
@@ -13,7 +13,7 @@ from app.models.models import (
)
_OUTBOUND_BIZ_TYPES = ("pilot_service", "clinical_application", "basic_experiment")
_OUTBOUND_BIZ_TYPES = ("pilot_service", "clinical_application", "basic_experiment", "contract_processing")
def _is_pilot_outbound_production(wo: BizProductionWorkOrder) -> bool:
+56 -2
View File
@@ -172,11 +172,34 @@ def soft_delete_cell_product_type(db, type_id, tenant_no=None):
# Entity 2: BizCellProductSpec 细胞产品规格
# ────────────────────────────────────────────
def _format_decimal(value) -> Optional[float]:
if value is None:
return None
try:
return float(value)
except (TypeError, ValueError):
return None
def _require_positive_decimal(value, label: str):
if value is None or value == "":
raise ValueError(f"请填写{label}")
try:
num = float(value)
except (TypeError, ValueError):
raise ValueError(f"{label}必须是数字")
if num <= 0:
raise ValueError(f"{label}必须大于0")
return num
def _row_to_dict_cell_product_spec(row) -> Dict[str, Any]:
return {
"id": row.id,
"specCode": row.spec_code or "",
"specName": row.spec_name or "",
"cellCountQianwan": _format_decimal(getattr(row, "cell_count_qianwan", None)),
"fillVolumeMl": _format_decimal(getattr(row, "fill_volume_ml", None)),
"tenantNo": row.tenant_no or "",
"orderNum": row.order_num if row.order_num is not None else 0,
"remark": row.remark or "",
@@ -229,13 +252,28 @@ def cell_product_spec_code_exists(db, code, tenant_no, exclude_id=None):
return db.query(q.exists()).scalar()
def create_cell_product_spec(db, *, spec_code, spec_name, tenant_no="zkxw", order_num=None, remark=None, user_id=None):
def create_cell_product_spec(
db,
*,
spec_code,
spec_name,
cell_count_qianwan,
fill_volume_ml,
tenant_no="zkxw",
order_num=None,
remark=None,
user_id=None,
):
if cell_product_spec_code_exists(db, spec_code, tenant_no):
raise ValueError(f"规格编码 {spec_code} 已存在")
cell_count = _require_positive_decimal(cell_count_qianwan, "细胞数量(千万)")
fill_volume = _require_positive_decimal(fill_volume_ml, "分装体积(ml)")
obj = BizCellProductSpec(
id=generate_uuid(),
spec_code=spec_code,
spec_name=spec_name,
cell_count_qianwan=cell_count,
fill_volume_ml=fill_volume,
tenant_no=tenant_no,
order_num=order_num or 0,
remark=remark or "",
@@ -251,7 +289,19 @@ def create_cell_product_spec(db, *, spec_code, spec_name, tenant_no="zkxw", orde
return obj
def update_cell_product_spec(db, spec_id, *, spec_code=None, spec_name=None, order_num=None, remark=None, user_id=None, tenant_no=None):
def update_cell_product_spec(
db,
spec_id,
*,
spec_code=None,
spec_name=None,
cell_count_qianwan=None,
fill_volume_ml=None,
order_num=None,
remark=None,
user_id=None,
tenant_no=None,
):
obj = get_cell_product_spec(db, spec_id, tenant_no)
if not obj:
raise ValueError("记录不存在")
@@ -261,6 +311,10 @@ def update_cell_product_spec(db, spec_id, *, spec_code=None, spec_name=None, ord
obj.spec_code = spec_code
if spec_name is not None:
obj.spec_name = spec_name
if cell_count_qianwan is not None:
obj.cell_count_qianwan = _require_positive_decimal(cell_count_qianwan, "细胞数量(千万)")
if fill_volume_ml is not None:
obj.fill_volume_ml = _require_positive_decimal(fill_volume_ml, "分装体积(ml)")
if order_num is not None:
obj.order_num = order_num
if remark is not None:
+5
View File
@@ -91,6 +91,8 @@ _RECEPTION_SOURCE_LABELS = {
_OUTBOUND_BIZ_TYPE_LABELS = {
"pilot_service": "中试服务",
"clinical_application": "临床应用",
"basic_experiment": "临床科研",
"contract_processing": "委托加工",
}
_APPLICATION_STATUS_LABELS = {
"dks": "待开始",
@@ -3328,6 +3330,7 @@ _PRODUCTION_TAB_STEP_COUNT_KEYS = (
"inbound_research_donation",
"outbound_pilot_service",
"outbound_basic_experiment",
"outbound_contract_processing",
"temporary",
)
@@ -3351,6 +3354,8 @@ def _resolve_production_tab_key(
bt = (biz_type or "pilot_service").strip() or "pilot_service"
if bt == "basic_experiment":
return "outbound_basic_experiment"
if bt == "contract_processing":
return "outbound_contract_processing"
if bt == "clinical_application":
return None
return "outbound_pilot_service"
+5 -3
View File
@@ -198,7 +198,8 @@ def _wo_to_dict(wo: BizProductionWorkOrder) -> Dict[str, Any]:
"bizTypeLabel": {
"pilot_service": "中试服务",
"clinical_application": "临床应用",
"basic_experiment": "基础实验",
"basic_experiment": "临床科研",
"contract_processing": "委托加工",
}.get(getattr(wo, "biz_type", None) or "", ""),
"workOrderStatus": wo.work_order_status,
"workOrderStatusLabel": _WORK_ORDER_STATUS_LABELS.get(wo.work_order_status, wo.work_order_status),
@@ -288,7 +289,8 @@ def _enrich_inbound_qc_conclusions(
_BIZ_TYPE_LABELS = {
"pilot_service": "中试服务",
"clinical_application": "临床应用",
"basic_experiment": "基础实验",
"basic_experiment": "临床科研",
"contract_processing": "委托加工",
}
@@ -545,7 +547,7 @@ def _attach_outbound_detail(
schedule_id = getattr(wo, "infusion_schedule_id", None) or ""
biz_type = getattr(wo, "biz_type", None) or ""
if schedule_id and biz_type in ("pilot_service", "clinical_application", "basic_experiment"):
if schedule_id and biz_type in ("pilot_service", "clinical_application", "basic_experiment", "contract_processing"):
pilot_ctx = build_outbound_pilot_context_by_schedule(
db, schedule_id, wo.tenant_no or ""
)
@@ -410,7 +410,8 @@ def list_protocol_sample_collections(
item["newbornDeliveryTime"] = _fmt_dt(party.newborn_delivery_time) if party else ""
item["protocolRemark"] = (proto.remark or "") if proto else ""
item["voidType"] = (proto.void_type or "") if proto else ""
item["voidDesc"] = (proto.void_desc or "") if proto else ""
# 样本状态问号展示样本作废原因,不用协议作废描述
item["voidDesc"] = (getattr(psample, "void_desc", None) or "").strip()
item["protocolAttachments"] = (proto.protocol_attachments or "") if proto else ""
item["consentFormUrls"] = (proto.consent_form_urls or "") if proto else ""
item["healthSurveyFormUrls"] = (proto.health_survey_form_urls or "") if proto else ""
+57 -1
View File
@@ -45,6 +45,14 @@ from app.services.sample_payment_progress import (
)
_SAMPLE_STATUS_LABELS = {
"ycj": "已采集",
"jcz": "检测中",
"yrk": "已入库",
"yzf": "已作废",
}
def _fmt_ymd8(v: Any) -> str:
s = str(v or "").strip()
if len(s) == 8 and s.isdigit():
@@ -1882,6 +1890,7 @@ def _build_list_summary_row(
]
receivable = float(sum(active_dues, Decimal("0"))) if active_dues else 0.0
discount = meta.get("discountAmount")
sample_status = str(meta.get("sampleStatus") or "").strip()
row: Dict[str, Any] = {
"id": sp.id,
"collectionProtocolId": sp.collection_protocol_id,
@@ -1891,6 +1900,10 @@ def _build_list_summary_row(
"motherName": (party.mother_name if party else "") or "",
"motherPhone": (party.mother_phone if party else "") or "",
"sampleCode": sp.sample_code or "",
"sampleStatus": sample_status,
"sampleStatusLabel": str(meta.get("sampleStatusLabel") or "").strip()
or _SAMPLE_STATUS_LABELS.get(sample_status, ""),
"voidDesc": str(meta.get("voidDesc") or "").strip(),
"payMode": sp.pay_mode or "",
"contractAmount": float(sp.contract_amount)
if sp.contract_amount is not None
@@ -2020,10 +2033,14 @@ def list_sample_payments_page(
discount = None
if orig is not None and price is not None and orig > price:
discount = round(orig - price, 2)
status = str(s.sample_status or "").strip()
sample_meta_by_key[key] = {
"storageYears": s.storage_years,
"sampleTypeName": type_name_map.get(s.sample_type_id or "", ""),
"discountAmount": discount,
"sampleStatus": status,
"sampleStatusLabel": _SAMPLE_STATUS_LABELS.get(status, ""),
"voidDesc": str(getattr(s, "void_desc", None) or "").strip(),
}
rows: List[Dict[str, Any]] = []
for sp, proto, party in candidates:
@@ -2228,6 +2245,40 @@ def list_payment_chase_page(
for u in db.query(SysUser.id, SysUser.nick_name).filter(SysUser.id.in_(sales_ids)).all():
sales_name_map[u.id] = u.nick_name or ""
sample_codes = list(
{
(sp.sample_code or sch.sample_code or "").strip()
for sch, sp, _, _, _ in candidates
if (sp.sample_code or sch.sample_code or "").strip()
}
)
sample_status_by_code: Dict[str, Dict[str, str]] = {}
if sample_codes:
s_rows = (
db.query(BizProtocolSample)
.filter(
BizProtocolSample.tenant_no == tenant_no,
BizProtocolSample.del_flag == 0,
BizProtocolSample.sample_code.in_(sample_codes),
)
.order_by(
BizProtocolSample.update_time.desc(),
BizProtocolSample.create_time.desc(),
BizProtocolSample.id.desc(),
)
.all()
)
for sample in s_rows:
code = str(sample.sample_code or "").strip()
if not code or code in sample_status_by_code:
continue
status = str(sample.sample_status or "").strip()
sample_status_by_code[code] = {
"sampleStatus": status,
"sampleStatusLabel": _SAMPLE_STATUS_LABELS.get(status, ""),
"voidDesc": str(getattr(sample, "void_desc", None) or "").strip(),
}
ct = (chase_type or "").strip()
rows: List[Dict[str, Any]] = []
for sch, sp, proto, party, ci in candidates:
@@ -2257,6 +2308,8 @@ def list_payment_chase_page(
continue
days_overdue = (today_d - due_d).days if overdue else 0
days_until = (due_d - today_d).days if not overdue else 0
sample_code = sp.sample_code or sch.sample_code or ""
sample_state = sample_status_by_code.get(str(sample_code).strip(), {})
rows.append(
{
"scheduleId": sch.id,
@@ -2265,7 +2318,10 @@ def list_payment_chase_page(
"protocolNo": (proto.protocol_no if proto else "") or "",
"motherName": (party.mother_name if party else "") or "",
"motherPhone": (party.mother_phone if party else "") or "",
"sampleCode": sp.sample_code or sch.sample_code or "",
"sampleCode": sample_code,
"sampleStatus": sample_state.get("sampleStatus", ""),
"sampleStatusLabel": sample_state.get("sampleStatusLabel", ""),
"voidDesc": sample_state.get("voidDesc", ""),
"salesUserId": (ci.sales_user_id if ci else "") or "",
"salesUserName": sales_name_map.get(
(ci.sales_user_id if ci else "") or "", ""
+38 -15
View File
@@ -19,6 +19,8 @@ from app.crud.qc_work_order import (
_sample_type_name_for_reception,
_work_order_qc_biz_type,
_OUTBOUND_BIZ_TYPE_LABELS,
apply_research_donation_protocol_status_filter,
build_qc_work_order_keyword_conditions,
build_work_order_list_summaries,
)
from app.core.db_collation import eq_unicode, unicode_ci
@@ -574,6 +576,7 @@ def list_mine_tasks(
qc_biz_type: Optional[str] = None,
reception_source: Optional[str] = None,
biz_type: Optional[str] = None,
protocol_status: Optional[str] = None,
tenant_no: Optional[str] = None,
) -> Tuple[List[Dict[str, Any]], int]:
def _filtered():
@@ -601,14 +604,21 @@ def list_mine_tasks(
kw = (keyword or "").strip()
if kw:
like = f"%{kw}%"
q0 = q0.filter(
or_(
BizQcTask.task_no.like(like),
BizQcTask.item_name.like(like),
BizQcWorkOrder.work_order_no.like(like),
BizQcWorkOrder.sample_code.like(like),
)
)
wt = (qc_biz_type or "").strip()
# temporary Tab 的 qcBizType=temporary,与工单 work_order_type 对齐
wo_type = "temporary" if wt == "temporary" else (wt or None)
keyword_conditions = [
BizQcTask.task_no.like(like),
BizQcTask.item_name.like(like),
*build_qc_work_order_keyword_conditions(
db,
tenant_no=tenant_no,
keyword=kw,
work_order_type=wo_type,
reception_source=(reception_source or "").strip() or None,
),
]
q0 = q0.filter(or_(*keyword_conditions))
tt = (task_type or "").strip()
if tt:
q0 = q0.filter(BizQcTask.task_type == tt)
@@ -632,6 +642,11 @@ def list_mine_tasks(
bt_out = (biz_type or "").strip()
if bt_out:
q0 = q0.filter(BizQcWorkOrder.biz_type == bt_out)
q0 = apply_research_donation_protocol_status_filter(
q0,
protocol_status,
reception_source=reception_source,
)
return q0
total = _filtered().order_by(None).with_entities(func.count(BizQcTask.id)).scalar() or 0
@@ -770,13 +785,8 @@ def _set_task_remark(t: BizQcTask, remark: Optional[str]) -> None:
def _require_dsfjc_attachments(t: BizQcTask, *, for_status: str = "ywc") -> None:
"""第三方检测且任务状态为已完成时,须至少有一个检测材料附件。"""
if (t.task_type or "").strip() != "dsfjc":
return
if (for_status or "").strip() != "ywc":
return
if not (t.third_party_attachments or "").strip():
raise ValueError("第三方检测须上传检测材料附件")
"""历史校验入口:第三方检测材料改为选填,工单级附件在工单卡片维护。"""
return
def complete_task(
@@ -1095,6 +1105,7 @@ def delete_qc_task(db: Session, task_id: str, tenant_no: str, user_id: Optional[
# 软删除任务结果
from app.models.qc_param import BizQcTaskResult
from app.models.models import BizQcTaskResultChangeLog
results = db.query(BizQcTaskResult).filter(
and_(BizQcTaskResult.task_id == task_id, BizQcTaskResult.del_flag == 0)
@@ -1104,6 +1115,18 @@ def delete_qc_task(db: Session, task_id: str, tenant_no: str, user_id: Optional[
r.update_by = user_id
r.update_time = now
change_logs = db.query(BizQcTaskResultChangeLog).filter(
and_(
BizQcTaskResultChangeLog.task_id == task_id,
BizQcTaskResultChangeLog.tenant_no == tenant_no,
BizQcTaskResultChangeLog.del_flag == 0,
)
).all()
for log in change_logs:
log.del_flag = 1
log.update_by = user_id
log.update_time = now
# 同步软删批次明细行(配置弹窗勾选来源)
_soft_delete_source_line_for_task(
db, task, tenant_no=tenant_no, user_id=user_id, now=now
@@ -0,0 +1,254 @@
"""质检任务检测结果操作留痕"""
from __future__ import annotations
import json
from datetime import datetime
from typing import Any, Dict, List, Optional
from sqlalchemy.orm import Session
from app.core.utils import generate_uuid
from app.models.models import BizQcTask, BizQcTaskResultChangeLog, SysUser
from app.models.qc_param import BizQcTaskResult
_TASK_STATUS_LABELS = {"dzx": "待执行", "jxz": "进行中", "ywc": "已完成"}
_CONCLUSION_LABELS = {"": "待结论", "tg": "通过", "btg": "不通过"}
def _fmt_dt(v: Optional[datetime]) -> str:
if not v:
return ""
return v.strftime("%Y-%m-%d %H:%M:%S")
def _display_status(code: Optional[str]) -> str:
c = (code or "").strip()
return _TASK_STATUS_LABELS.get(c, c or "—")
def _display_conclusion(code: Optional[str]) -> str:
c = (code or "").strip()
return _CONCLUSION_LABELS.get(c, c or "待结论")
def _norm_text(v: Any) -> str:
if v is None:
return ""
return str(v).strip()
def _param_key(param_id: Optional[str], param_code: Optional[str], param_name: Optional[str]) -> str:
pid = _norm_text(param_id)
if pid:
return f"paramId:{pid}"
code = _norm_text(param_code)
if code:
return f"paramCode:{code}"
return f"paramName:{_norm_text(param_name)}"
def snapshot_task_result_state(db: Session, task: BizQcTask, tenant_no: str) -> Dict[str, Any]:
"""保存前快照:任务结论字段 + 已存参数值。"""
rows = (
db.query(BizQcTaskResult)
.filter(
BizQcTaskResult.task_id == task.id,
BizQcTaskResult.tenant_no == tenant_no,
BizQcTaskResult.del_flag == 0,
)
.order_by(BizQcTaskResult.create_time.asc())
.all()
)
params: Dict[str, Dict[str, str]] = {}
for r in rows:
key = _param_key(r.param_id, r.param_code, r.param_name)
params[key] = {
"label": _norm_text(r.param_name) or key,
"value": _norm_text(r.param_value),
}
return {
"taskStatus": _norm_text(task.task_status),
"conclusion": _norm_text(task.conclusion),
"remark": _norm_text(task.remark),
"attachments": _norm_text(task.third_party_attachments),
"params": params,
}
def build_result_changes(
before: Dict[str, Any],
after: Dict[str, Any],
) -> List[Dict[str, str]]:
changes: List[Dict[str, str]] = []
def add(field_key: str, label: str, old_v: str, new_v: str) -> None:
if old_v == new_v:
return
changes.append(
{
"fieldKey": field_key,
"fieldLabel": label,
"oldValue": old_v,
"newValue": new_v,
}
)
add(
"taskStatus",
"任务状态",
_display_status(before.get("taskStatus")),
_display_status(after.get("taskStatus")),
)
add(
"conclusion",
"结论",
_display_conclusion(before.get("conclusion")),
_display_conclusion(after.get("conclusion")),
)
add("remark", "备注", _norm_text(before.get("remark")), _norm_text(after.get("remark")))
add(
"attachments",
"检测材料",
_norm_text(before.get("attachments")),
_norm_text(after.get("attachments")),
)
before_params: Dict[str, Dict[str, str]] = before.get("params") or {}
after_params: Dict[str, Dict[str, str]] = after.get("params") or {}
keys = sorted(set(before_params.keys()) | set(after_params.keys()))
for key in keys:
b = before_params.get(key) or {"label": key, "value": ""}
a = after_params.get(key) or {"label": b.get("label") or key, "value": ""}
label = _norm_text(a.get("label")) or _norm_text(b.get("label")) or key
add(key, label, _norm_text(b.get("value")), _norm_text(a.get("value")))
return changes
def _resolve_operator_name(db: Session, user_id: Optional[str], fallback: str = "") -> str:
uid = _norm_text(user_id)
if not uid:
return _norm_text(fallback)
row = db.query(SysUser.nick_name).filter(SysUser.id == uid).first()
if row and row[0]:
return str(row[0]).strip()
return _norm_text(fallback) or uid
def append_task_result_change_log(
db: Session,
*,
task: BizQcTask,
tenant_no: str,
user_id: Optional[str],
operator_user_name: str = "",
before: Dict[str, Any],
after: Dict[str, Any],
operate_time: Optional[datetime] = None,
operate_batch_id: Optional[str] = None,
) -> BizQcTaskResultChangeLog:
"""追加一条检测结果保存留痕(不 commit)。无字段差异也写入。"""
now = operate_time or datetime.now()
changes = build_result_changes(before, after)
has_change = "1" if changes else "0"
name = _resolve_operator_name(db, user_id, operator_user_name)
batch_id = _norm_text(operate_batch_id) or None
obj = BizQcTaskResultChangeLog(
id=generate_uuid(),
task_id=task.id,
work_order_id=_norm_text(task.work_order_id) or None,
sample_code=_norm_text(task.sample_code) or None,
item_name=_norm_text(task.item_name) or None,
operate_time=now,
operator_user_id=user_id,
operator_user_name=name or None,
operate_batch_id=batch_id,
has_field_change=has_change,
changes_json=json.dumps(changes, ensure_ascii=False),
tenant_no=tenant_no,
order_num=0,
remark=None,
create_by=user_id,
create_dept_id="",
create_time=now,
update_by=user_id,
update_time=now,
del_flag=0,
)
db.add(obj)
return obj
def _row_to_dict(row: BizQcTaskResultChangeLog) -> Dict[str, Any]:
changes: List[Dict[str, Any]] = []
raw = row.changes_json or ""
if raw.strip():
try:
parsed = json.loads(raw)
if isinstance(parsed, list):
changes = parsed
except json.JSONDecodeError:
changes = []
return {
"id": row.id,
"taskId": row.task_id,
"workOrderId": row.work_order_id or "",
"sampleCode": row.sample_code or "",
"itemName": row.item_name or "",
"operateTime": _fmt_dt(row.operate_time),
"operatorUserId": row.operator_user_id or "",
"operatorUserName": row.operator_user_name or "",
"operateBatchId": row.operate_batch_id or "",
"hasFieldChange": row.has_field_change == "1",
"changes": changes,
"createTime": _fmt_dt(row.create_time),
}
def list_task_result_change_logs(
db: Session,
*,
task_id: str,
tenant_no: str,
) -> List[Dict[str, Any]]:
tid = _norm_text(task_id)
if not tid:
return []
rows = (
db.query(BizQcTaskResultChangeLog)
.filter(
BizQcTaskResultChangeLog.task_id == tid,
BizQcTaskResultChangeLog.tenant_no == tenant_no,
BizQcTaskResultChangeLog.del_flag == 0,
)
.order_by(
BizQcTaskResultChangeLog.operate_time.desc(),
BizQcTaskResultChangeLog.create_time.desc(),
)
.all()
)
return [_row_to_dict(r) for r in rows]
def list_task_result_change_logs_by_task_ids(
db: Session,
*,
task_ids: List[str],
tenant_no: str,
) -> List[Dict[str, Any]]:
ids = [_norm_text(x) for x in task_ids if _norm_text(x)]
if not ids:
return []
rows = (
db.query(BizQcTaskResultChangeLog)
.filter(
BizQcTaskResultChangeLog.task_id.in_(ids),
BizQcTaskResultChangeLog.tenant_no == tenant_no,
BizQcTaskResultChangeLog.del_flag == 0,
)
.order_by(
BizQcTaskResultChangeLog.operate_time.desc(),
BizQcTaskResultChangeLog.create_time.desc(),
)
.all()
)
return [_row_to_dict(r) for r in rows]
+164 -40
View File
@@ -49,6 +49,7 @@ from app.models.models import (
BizPilotInfusionSchedule,
BizPilotInfusionScheduleProduct,
BizPilotPatient,
BizProtocolCollectionInfo,
BizProtocolPartyCustomer,
BizProtocolSample,
BizProductionTask,
@@ -69,6 +70,7 @@ from app.models.models import (
from app.models.qc_param import BizQcTaskResult
from app.models.research_donation import (
BizResearchDonation,
BizResearchDonationCollection,
BizResearchDonationParty,
BizResearchDonationSample,
)
@@ -106,7 +108,8 @@ _CONCLUSION_LABELS = {"tg": "通过", "btg": "不通过"}
_OUTBOUND_BIZ_TYPE_LABELS = {
"pilot_service": "中试服务",
"clinical_application": "临床应用",
"basic_experiment": "基础实验",
"basic_experiment": "临床科研",
"contract_processing": "委托加工",
}
_OUTBOUND_BIZ_TYPES = tuple(_OUTBOUND_BIZ_TYPE_LABELS.keys())
@@ -558,6 +561,56 @@ def _inbound_qc_work_order_ids_by_mother_name(
return list(ids)
def build_qc_work_order_keyword_conditions(
db: Optional[Session],
*,
tenant_no: Optional[str],
keyword: str,
work_order_type: Optional[str] = None,
reception_source: Optional[str] = None,
) -> List[Any]:
"""质检工单列表关键词 OR 条件(工单号/样本/协议号/外部编号 + 入库编码/母亲/出库申请字段)。
供质检工单列表与「我的质检任务」共用,避免两端口径漂移。
"""
kw = (keyword or "").strip()
if not kw:
return []
like = f"%{kw}%"
wt = (work_order_type or "").strip()
rs = (reception_source or "").strip()
conditions: List[Any] = [
BizQcWorkOrder.work_order_no.like(like),
BizQcWorkOrder.sample_code.like(like),
BizQcWorkOrder.protocol_no.like(like),
BizQcWorkOrder.external_target_code.like(like),
]
if db is not None and tenant_no:
from app.crud import sample_reception as reception_svc
rec_ids = reception_svc.reception_ids_matching_lab_storage_keyword(
db, tenant_no, kw
)
if rec_ids:
conditions.append(BizQcWorkOrder.reception_id.in_(rec_ids))
lab_codes = reception_svc.sample_codes_matching_lab_storage_keyword(
db, tenant_no, kw
)
if lab_codes:
conditions.append(BizQcWorkOrder.sample_code.in_(lab_codes))
if wt == "outbound" or not wt:
outbound_ids = _outbound_qc_work_order_ids_by_keyword(db, tenant_no, kw)
if outbound_ids:
conditions.append(BizQcWorkOrder.id.in_(outbound_ids))
if not wt or wt == "inbound":
inbound_mother_ids = _inbound_qc_work_order_ids_by_mother_name(
db, tenant_no, kw, reception_source=rs or None
)
if inbound_mother_ids:
conditions.append(BizQcWorkOrder.id.in_(inbound_mother_ids))
return conditions
def _accept_conclusion_label(v: Optional[str]) -> str:
key = (v or "").strip()
return _ACCEPT_CONCLUSION_LABELS.get(key, key)
@@ -677,9 +730,6 @@ def _enrich_work_order_list_items(
code = (r.sample_code or "").strip()
if code and code not in sample_code_rec_map:
sample_code_rec_map[code] = r
if not rec_map and not sample_code_rec_map:
return items
def _resolve_reception(item: Dict[str, Any]) -> Optional[BizSampleReception]:
rec = rec_map.get(item.get("receptionId") or "")
if rec:
@@ -695,7 +745,9 @@ def _enrich_work_order_list_items(
rec = _resolve_reception(item)
source = _effective_reception_source(item, rec)
if source == "research_donation":
dsid = _effective_donation_sample_id(item, rec)
dsid = _effective_donation_sample_id(item, rec) or (
item.get("protocolSampleId") or ""
).strip()
if dsid:
donation_sample_ids.append(dsid)
did = (
@@ -704,7 +756,9 @@ def _enrich_work_order_list_items(
if did:
donation_ids.append(did)
else:
psid = _effective_protocol_sample_id(item, rec)
psid = _effective_protocol_sample_id(item, rec) or (
item.get("protocolSampleId") or ""
).strip()
if psid:
cell_sample_ids.append(psid)
pid = (
@@ -808,12 +862,39 @@ def _enrich_work_order_list_items(
party.mother_name or "",
party.newborn_name or "",
)
cell_maternal_map: Dict[str, str] = {}
if cell_proto_ids:
for coll in (
db.query(BizProtocolCollectionInfo)
.filter(
BizProtocolCollectionInfo.collection_protocol_id.in_(cell_proto_ids),
BizProtocolCollectionInfo.del_flag == 0,
)
.all()
):
cell_maternal_map[coll.collection_protocol_id] = _fmt_dt(
coll.maternal_blood_collect_time
)
donation_maternal_map: Dict[str, str] = {}
if donation_ids:
for coll in (
db.query(BizResearchDonationCollection)
.filter(
BizResearchDonationCollection.research_donation_id.in_(donation_ids),
BizResearchDonationCollection.del_flag == 0,
)
.all()
):
donation_maternal_map[coll.research_donation_id] = _fmt_dt(
coll.maternal_blood_collect_time
)
for item in items:
if item.get("workOrderType") == "temporary":
item["receptionSource"] = ""
item["receptionSourceLabel"] = ""
item["motherName"] = ""
item["newbornName"] = ""
item["maternalBloodCollectTime"] = ""
continue
rec = _resolve_reception(item)
source = _effective_reception_source(item, rec)
@@ -826,6 +907,7 @@ def _enrich_work_order_list_items(
_mother, _newborn = donation_party_map.get(_did or "", ("", ""))
item["motherName"] = _mother
item["newbornName"] = _newborn
item["maternalBloodCollectTime"] = donation_maternal_map.get(_did or "", "") or ""
else:
_pid = (
(getattr(rec, "collection_protocol_id", None) if rec else None) or ""
@@ -833,11 +915,35 @@ def _enrich_work_order_list_items(
_mother, _newborn = cell_party_map.get(_pid or "", ("", ""))
item["motherName"] = _mother
item["newbornName"] = _newborn
item["maternalBloodCollectTime"] = cell_maternal_map.get(_pid or "", "") or ""
def _apply_sample_status_fields() -> None:
sample_obj = None
if source == "research_donation":
dsid = _effective_donation_sample_id(item, rec) or (
item.get("protocolSampleId") or ""
).strip()
sample_obj = donation_samples.get(dsid) if dsid else None
else:
psid = _effective_protocol_sample_id(item, rec) or (
item.get("protocolSampleId") or ""
).strip()
sample_obj = protocol_samples.get(psid) if psid else None
item["sampleStatus"] = (
(sample_obj.sample_status or "").strip() if sample_obj else ""
)
item["voidDesc"] = (
(getattr(sample_obj, "void_desc", None) or "").strip() if sample_obj else ""
)
item["voidDate"] = (
(sample_obj.void_date or "").strip() if sample_obj else ""
)
if not rec:
item.setdefault("receptionTime", "")
item.setdefault("handlerName", "")
item.setdefault("sampleTypeName", "")
item.setdefault("labStorageCode", "")
_apply_sample_status_fields()
continue
item["receptionTime"] = _fmt_dt(rec.reception_time)
item["handlerName"] = rec.handler_name or ""
@@ -858,6 +964,7 @@ def _enrich_work_order_list_items(
protocol_samples=protocol_samples,
donation_samples=donation_samples,
)
_apply_sample_status_fields()
if source == "research_donation":
_did = (
(getattr(rec, "research_donation_id", None) or "").strip()
@@ -1140,6 +1247,7 @@ def _wo_to_dict(
"receptionTime": "",
"handlerName": "",
"sampleTypeName": "",
"maternalBloodCollectTime": "",
"workOrderStatus": wo.work_order_status,
"workOrderStatusLabel": _WORK_ORDER_STATUS_LABELS.get(
wo.work_order_status or "", wo.work_order_status or ""
@@ -1156,6 +1264,7 @@ def _wo_to_dict(
"configuredBy": wo.configured_by or "",
"configuredByName": configured_by_name or wo.configured_by or "",
"thirdPartyFeeTotal": _dec(wo.third_party_fee_total),
"attachments": (getattr(wo, "attachments", None) or "").strip(),
"remark": wo.remark or "",
"createTime": _fmt_dt(wo.create_time),
"updateTime": _fmt_dt(wo.update_time),
@@ -1661,8 +1770,8 @@ def apply_research_donation_protocol_status_filter(
return query
mode, statuses = resolve_research_donation_protocol_status_filter(protocol_status)
if mode == "none":
return query.filter(BizQcWorkOrder.id.in_([]))
if mode == "all":
return query
if mode == "in":
return query.filter(_research_donation_status_exists(statuses))
# default:与前端默认勾选一致
@@ -1734,37 +1843,15 @@ def list_work_orders(
q0 = q0.filter(BizQcWorkOrder.trigger_source == ts)
kw = (keyword or "").strip()
if kw:
like = f"%{kw}%"
keyword_conditions = [
BizQcWorkOrder.work_order_no.like(like),
BizQcWorkOrder.sample_code.like(like),
BizQcWorkOrder.protocol_no.like(like),
BizQcWorkOrder.external_target_code.like(like),
]
if tenant_no:
from app.crud import sample_reception as reception_svc
rec_ids = reception_svc.reception_ids_matching_lab_storage_keyword(
db, tenant_no, kw
)
if rec_ids:
keyword_conditions.append(BizQcWorkOrder.reception_id.in_(rec_ids))
lab_codes = reception_svc.sample_codes_matching_lab_storage_keyword(
db, tenant_no, kw
)
if lab_codes:
keyword_conditions.append(BizQcWorkOrder.sample_code.in_(lab_codes))
if tenant_no and (wt == "outbound" or not wt):
outbound_ids = _outbound_qc_work_order_ids_by_keyword(db, tenant_no, kw)
if outbound_ids:
keyword_conditions.append(BizQcWorkOrder.id.in_(outbound_ids))
if tenant_no and (not wt or wt == "inbound"):
inbound_mother_ids = _inbound_qc_work_order_ids_by_mother_name(
db, tenant_no, kw, reception_source=rs or None
)
if inbound_mother_ids:
keyword_conditions.append(BizQcWorkOrder.id.in_(inbound_mother_ids))
q0 = q0.filter(or_(*keyword_conditions))
keyword_conditions = build_qc_work_order_keyword_conditions(
db,
tenant_no=tenant_no,
keyword=kw,
work_order_type=wt or None,
reception_source=rs or None,
)
if keyword_conditions:
q0 = q0.filter(or_(*keyword_conditions))
st_raw = (work_order_status or "").strip()
if st_raw:
statuses = [s.strip() for s in st_raw.split(",") if s.strip()]
@@ -1918,6 +2005,7 @@ _QC_TAB_COUNT_KEYS = (
"inbound_research_donation",
"outbound_pilot_service",
"outbound_basic_experiment",
"outbound_contract_processing",
"temporary",
)
@@ -1938,6 +2026,8 @@ def _resolve_wo_tab_key(
bt = (biz_type or "pilot_service").strip() or "pilot_service"
if bt == "basic_experiment":
return "outbound_basic_experiment"
if bt == "contract_processing":
return "outbound_contract_processing"
if bt == "clinical_application":
return "outbound_clinical_application"
return "outbound_pilot_service"
@@ -2601,6 +2691,7 @@ def get_work_order_detail(
"receptionSourceLabel": enriched.get("receptionSourceLabel", ""),
"motherName": enriched.get("motherName", ""),
"newbornName": enriched.get("newbornName", ""),
"maternalBloodCollectTime": enriched.get("maternalBloodCollectTime", ""),
"protocolStatus": enriched.get("protocolStatus", ""),
"protocolStatusLabel": enriched.get("protocolStatusLabel", ""),
"cellProductCode": enriched.get("cellProductCode", ""),
@@ -2695,6 +2786,16 @@ def _soft_delete_tasks_by_source_line_ids(
{"del_flag": 1, "update_time": now},
synchronize_session="fetch",
)
from app.models.models import BizQcTaskResultChangeLog
db.query(BizQcTaskResultChangeLog).filter(
BizQcTaskResultChangeLog.task_id.in_(task_ids),
BizQcTaskResultChangeLog.tenant_no == tenant_no,
BizQcTaskResultChangeLog.del_flag == 0,
).update(
{"del_flag": 1, "update_time": now},
synchronize_session="fetch",
)
for t in tasks:
t.del_flag = 1
t.update_time = now
@@ -3247,6 +3348,7 @@ def update_qc_work_order(
external_target_code: Optional[str] = None,
work_order_status: Optional[str] = None,
qc_conclusion: Optional[str] = None,
attachments: Optional[str] = None,
remark: Optional[str] = None,
) -> BizQcWorkOrder:
"""编辑质检工单:入库/出库可改备注、状态与质检结论;临时可改备注与质检对象"""
@@ -3277,6 +3379,15 @@ def update_qc_work_order(
if conc and conc not in _VALID_QC_WORK_ORDER_CONCLUSIONS:
raise ValueError("质检结论无效")
wo.conclusion = conc or None
if attachments is not None:
urls = ",".join(
p.strip()
for p in (attachments or "").replace(",", ",").split(",")
if p.strip()
)
if len(urls) > 4000:
raise ValueError("工单附件过多,请减少后重试")
wo.attachments = urls or None
if remark is not None:
wo.remark = (remark or "").strip() or None
wo.update_by = user_id
@@ -3617,7 +3728,7 @@ def build_outbound_pilot_context_by_schedule(
"bizType": app_biz,
"bizTypeLabel": _OUTBOUND_BIZ_TYPE_LABELS.get(app_biz, app_biz),
}
if app_biz == "basic_experiment":
if app_biz in ("basic_experiment", "contract_processing"):
out["application"]["projectTitle"] = app.project_title or ""
out["application"]["customerName"] = app.customer_name or ""
out["application"]["customerContact"] = app.customer_contact or ""
@@ -3826,6 +3937,8 @@ def delete_qc_work_order(db: Session, work_order_id: str, tenant_no: str, user_i
).all()
from app.models.qc_param import BizQcTaskResult
from app.models.models import BizQcTaskResultChangeLog
for task in tasks:
results = db.query(BizQcTaskResult).filter(
and_(BizQcTaskResult.task_id == task.id, BizQcTaskResult.del_flag == 0)
@@ -3834,6 +3947,17 @@ def delete_qc_work_order(db: Session, work_order_id: str, tenant_no: str, user_i
r.del_flag = 1
r.update_by = user_id
r.update_time = now
change_logs = db.query(BizQcTaskResultChangeLog).filter(
and_(
BizQcTaskResultChangeLog.task_id == task.id,
BizQcTaskResultChangeLog.tenant_no == tenant_no,
BizQcTaskResultChangeLog.del_flag == 0,
)
).all()
for log in change_logs:
log.del_flag = 1
log.update_by = user_id
log.update_time = now
task.del_flag = 1
task.update_by = user_id
task.update_time = now
+4 -1
View File
@@ -535,6 +535,7 @@ def _sample_to_dict(s: BizResearchDonationSample) -> Dict[str, Any]:
"storageInDate": (s.storage_in_date or "").strip() if s.storage_in_date else "",
"detectStartDate": (s.detect_start_date or "").strip() if s.detect_start_date else "",
"voidDate": (s.void_date or "").strip() if s.void_date else "",
"voidDesc": (getattr(s, "void_desc", None) or "").strip() if (getattr(s, "void_desc", None) or "").strip() else "",
"storageExpireDate": (s.storage_expire_date or "").strip() if s.storage_expire_date else "",
**sample_special_to_dict(s),
"tenantNo": s.tenant_no,
@@ -975,6 +976,7 @@ def list_donations(
"sampleTypeName": type_name,
"sampleCode": code,
"sampleStatus": (s.sample_status or "").strip(),
"voidDesc": (getattr(s, "void_desc", None) or "").strip(),
"labStorageCode": lab_code_map.get(code, "") if code else "",
"transport": transport_dict,
"freight": freight_by_sample.get(s.id),
@@ -1702,7 +1704,8 @@ def change_status(
)
db.add(obj)
if ns == "yzf" and (current or "").strip() != "yzf":
from_status = (current or "").strip()
if ns in ("yzf", "sdfq") and from_status not in ("yzf", "sdfq"):
from app.services.protocol_reception_discard_sync import after_protocol_voided
after_protocol_voided(
+29 -2
View File
@@ -194,6 +194,14 @@ def _item_to_dict(item: BizSampleFreightItem) -> Dict[str, Any]:
}
_SAMPLE_STATUS_LABELS = {
"ycj": "已采集",
"jcz": "检测中",
"yrk": "已入库",
"yzf": "已作废",
}
def _item_to_dict_enriched(
item: BizSampleFreightItem,
*,
@@ -201,12 +209,19 @@ def _item_to_dict_enriched(
sample_type_name: str = "",
mother_name: str = "",
newborn_name: str = "",
sample_status: str = "",
void_desc: str = "",
) -> Dict[str, Any]:
data = _item_to_dict(item)
data["protocolNo"] = protocol_no or ""
data["sampleTypeName"] = sample_type_name or ""
data["motherName"] = mother_name or ""
data["newbornName"] = newborn_name or ""
status = str(sample_status or "").strip()
if str(item.sample_code or "").strip():
data["sampleStatus"] = status
data["sampleStatusLabel"] = _SAMPLE_STATUS_LABELS.get(status, "")
data["voidDesc"] = str(void_desc or "").strip()
return data
@@ -257,6 +272,8 @@ def _enrich_items_maps(
BizCellSampleType.type_name,
BizProtocolPartyCustomer.mother_name,
BizProtocolPartyCustomer.newborn_name,
BizProtocolSample.sample_status,
BizProtocolSample.void_desc,
)
.outerjoin(
BizCollectionProtocol,
@@ -287,12 +304,14 @@ def _enrich_items_maps(
)
.all()
)
for sid, pno, tname, mname, nname in rows:
for sid, pno, tname, mname, nname, status, void_desc in rows:
out[f"{SAMPLE_SOURCE_CELL}|{sid}"] = {
"protocolNo": pno or "",
"sampleTypeName": tname or "",
"motherName": mname or "",
"newbornName": nname or "",
"sampleStatus": str(status or "").strip(),
"voidDesc": str(void_desc or "").strip(),
}
if donation_ids:
@@ -303,6 +322,8 @@ def _enrich_items_maps(
BizCellSampleType.type_name,
BizResearchDonationParty.mother_name,
BizResearchDonationParty.newborn_name,
BizResearchDonationSample.sample_status,
BizResearchDonationSample.void_desc,
)
.outerjoin(
BizResearchDonation,
@@ -334,12 +355,14 @@ def _enrich_items_maps(
)
.all()
)
for sid, dno, tname, mname, nname in rows:
for sid, dno, tname, mname, nname, status, void_desc in rows:
out[f"{SAMPLE_SOURCE_DONATION}|{sid}"] = {
"protocolNo": dno or "",
"sampleTypeName": tname or "",
"motherName": mname or "",
"newbornName": nname or "",
"sampleStatus": str(status or "").strip(),
"voidDesc": str(void_desc or "").strip(),
}
return out
@@ -541,6 +564,8 @@ def list_freights(
sample_type_name=info.get("sampleTypeName", ""),
mother_name=info.get("motherName", ""),
newborn_name=info.get("newbornName", ""),
sample_status=info.get("sampleStatus", ""),
void_desc=info.get("voidDesc", ""),
)
)
data["items"] = enriched
@@ -584,6 +609,8 @@ def get_freight_detail(
sample_type_name=info.get("sampleTypeName", ""),
mother_name=info.get("motherName", ""),
newborn_name=info.get("newbornName", ""),
sample_status=info.get("sampleStatus", ""),
void_desc=info.get("voidDesc", ""),
)
)
data["items"] = enriched
+112 -10
View File
@@ -444,6 +444,7 @@ def _rows_to_sample_list_items(
"sampleTypeName": type_map.get(sample.sample_type_id or "", ""),
"collectAmount": _dec(sample.collect_amount),
"sampleStatus": sample.sample_status or "",
"voidDesc": (getattr(sample, "void_desc", None) or "").strip(),
"motherName": (party.mother_name if party else "") or "",
"newbornName": (party.newborn_name if party else "") or "",
"sampleCollectTime": (
@@ -573,6 +574,99 @@ def list_pending_protocol_samples(
return page_items, int(total)
def parse_optional_bool(value: Optional[str]) -> Optional[bool]:
"""解析查询参数中的可选布尔:空=不限,true/1=是,false/0=否。"""
if value is None:
return None
text = str(value).strip().lower()
if not text:
return None
if text in ("1", "true", "yes", "y"):
return True
if text in ("0", "false", "no", "n"):
return False
raise ValueError(f"invalid boolean query value: {value}")
def _apply_received_sample_type_and_void_filters(
db: Session,
q_rec,
*,
tenant_no: str,
sample_type_id: Optional[str] = None,
is_voided: Optional[bool] = None,
):
"""按样本类型、是否废弃(协议/捐赠状态=yzf)过滤已接收记录。"""
type_id = (sample_type_id or "").strip()
if not type_id and is_voided is None:
return q_rec
cell_q = (
db.query(BizProtocolSample.id)
.join(
BizCollectionProtocol,
and_(
BizCollectionProtocol.id == BizProtocolSample.collection_protocol_id,
BizCollectionProtocol.del_flag == 0,
),
)
.filter(
BizProtocolSample.del_flag == 0,
BizProtocolSample.tenant_no == tenant_no,
BizCollectionProtocol.tenant_no == tenant_no,
)
)
donation_q = (
db.query(_donation_sample_id_col(BizResearchDonationSample.id))
.join(
BizResearchDonation,
and_(
BizResearchDonation.id == BizResearchDonationSample.research_donation_id,
BizResearchDonation.del_flag == 0,
),
)
.filter(
BizResearchDonationSample.del_flag == 0,
BizResearchDonationSample.tenant_no == tenant_no,
BizResearchDonation.tenant_no == tenant_no,
)
)
if type_id:
cell_q = cell_q.filter(BizProtocolSample.sample_type_id == type_id)
donation_q = donation_q.filter(BizResearchDonationSample.sample_type_id == type_id)
if is_voided is True:
cell_q = cell_q.filter(BizCollectionProtocol.protocol_status == "yzf")
donation_q = donation_q.filter(BizResearchDonation.donation_status == "yzf")
elif is_voided is False:
cell_q = cell_q.filter(
or_(
BizCollectionProtocol.protocol_status.is_(None),
BizCollectionProtocol.protocol_status != "yzf",
)
)
donation_q = donation_q.filter(
or_(
BizResearchDonation.donation_status.is_(None),
BizResearchDonation.donation_status != "yzf",
)
)
cell_ids = cell_q.subquery()
donation_ids = donation_q.subquery()
return q_rec.filter(
or_(
and_(
BizSampleReception.reception_source == "cell_storage",
BizSampleReception.protocol_sample_id.in_(cell_ids),
),
and_(
BizSampleReception.reception_source == "research_donation",
BizSampleReception.donation_sample_id.in_(donation_ids),
),
)
)
def list_received_protocol_samples(
db: Session,
*,
@@ -581,6 +675,8 @@ def list_received_protocol_samples(
tenant_no: Optional[str] = None,
keyword: Optional[str] = None,
source_type: Optional[str] = None,
sample_type_id: Optional[str] = None,
is_voided: Optional[bool] = None,
reception_time_start: Optional[str] = None,
reception_time_end: Optional[str] = None,
user_info=None,
@@ -636,6 +732,14 @@ def list_received_protocol_samples(
)
)
q_rec = _apply_received_sample_type_and_void_filters(
db,
q_rec,
tenant_no=tenant_no,
sample_type_id=sample_type_id,
is_voided=is_voided,
)
if user_info:
from app.core.data_scope import apply_data_scope
q_rec = apply_data_scope(q_rec, BizSampleReception, user_info, db, tenant_no)
@@ -1045,12 +1149,11 @@ def create_sample_reception(
user_id=user_id,
create_dept_id=create_dept_id or "",
)
if conclusion == "bj":
from app.services.protocol_reception_discard_sync import after_sample_reception_saved
from app.services.protocol_reception_discard_sync import after_sample_reception_saved
after_sample_reception_saved(
db, reception=obj, tenant_no=tenant_no, user_id=user_id
)
after_sample_reception_saved(
db, reception=obj, tenant_no=tenant_no, user_id=user_id
)
db.commit()
db.refresh(obj)
return obj
@@ -1169,12 +1272,11 @@ def update_sample_reception(
)
check_result_svc.sync_legacy_columns_from_results(db, rec, saved_rows)
db.add(rec)
if conclusion == "bj":
from app.services.protocol_reception_discard_sync import after_sample_reception_saved
from app.services.protocol_reception_discard_sync import after_sample_reception_saved
after_sample_reception_saved(
db, reception=rec, tenant_no=tenant_no, user_id=user_id
)
after_sample_reception_saved(
db, reception=rec, tenant_no=tenant_no, user_id=user_id
)
db.commit()
db.refresh(rec)
return rec
+2 -1
View File
@@ -13,7 +13,7 @@ from app.core.database import SessionLocal
from app.core.api_request_log_middleware import ApiRequestLogMiddleware
from app.core.api_crypto_middleware import ApiCryptoMiddleware
from app.models import models # noqa: F401
from app.api import public_router, menu_router, admin_router, workflow_router, basic_info_router, collection_protocol_router, protocol_sample_payment_router, protocol_refund_record_router, presign_order_router, sample_freight_router, leave_router, operations_router, ethnic_router, sample_reception_router, sample_production_reception_router, qc_router, research_donation_router, production_router, pilot_service_router, insurance_company_router, material_router, storage_release_review_router, sample_sms_notification_router, storage_entry_sms_notification_router, qc_sms_notification_router, protocol_sample_collection_router, research_donation_sample_collection_router, pilot_application_router, pilot_checkup_router, pilot_delivery_router, pilot_infusion_confirm_router, pilot_infusion_schedule_mgmt_router, outbound_release_review_router, clinical_payment_router, env_detect_router, cleanroom_garment_router, market_router, pre_transit_sample_router, oa_approval_router, mini_auth_router, mini_menu_router, market_mobile_router, sample_storage_cert_qc_router, customer_service_dict_router, sample_cert_insurance_router, sample_code_correction_router, lab_sample_process_router, lab_sample_processing_router, project_management_router
from app.api import public_router, menu_router, admin_router, workflow_router, basic_info_router, collection_protocol_router, protocol_sample_payment_router, protocol_refund_record_router, presign_order_router, sample_freight_router, leave_router, operations_router, ethnic_router, sample_reception_router, sample_production_reception_router, qc_router, research_donation_router, production_router, pilot_service_router, insurance_company_router, material_router, storage_release_review_router, sample_sms_notification_router, storage_entry_sms_notification_router, qc_sms_notification_router, protocol_sample_collection_router, research_donation_sample_collection_router, pilot_application_router, pilot_checkup_router, pilot_delivery_router, pilot_infusion_confirm_router, pilot_infusion_schedule_mgmt_router, outbound_release_review_router, clinical_payment_router, env_detect_router, cleanroom_garment_router, market_router, pre_transit_sample_router, oa_approval_router, mini_auth_router, mini_menu_router, market_mobile_router, sample_storage_cert_qc_router, customer_service_dict_router, sample_cert_insurance_router, sample_code_correction_router, lab_sample_process_router, lab_sample_processing_router, project_management_router, business_sample_router
@asynccontextmanager
@@ -125,6 +125,7 @@ app.include_router(leave_router, prefix=settings.API_V1_PREFIX)
app.include_router(operations_router, prefix=settings.API_V1_PREFIX)
app.include_router(ethnic_router, prefix=settings.API_V1_PREFIX)
app.include_router(sample_reception_router, prefix=settings.API_V1_PREFIX)
app.include_router(business_sample_router, prefix=settings.API_V1_PREFIX)
app.include_router(sample_production_reception_router, prefix=settings.API_V1_PREFIX)
app.include_router(qc_router, prefix=settings.API_V1_PREFIX)
app.include_router(research_donation_router, prefix=settings.API_V1_PREFIX)
+98 -5
View File
@@ -351,6 +351,50 @@ class BizCustomer(Base):
del_flag = Column(SmallInteger, nullable=False, default=0, comment="删除标记")
class BizPartnerCustomer(Base):
"""合作客户 biz_partner_customer(临床科研/委托加工)"""
__tablename__ = "biz_partner_customer"
id = Column(String(64), primary_key=True, comment="主键ID")
customer_name = Column(String(200), nullable=False, comment="客户名称")
customer_contact = Column(String(100), nullable=False, comment="客户联系人")
customer_phone = Column(String(32), nullable=False, comment="客户联系方式")
tenant_no = Column(String(64), nullable=False, default="zkxw", comment="租户编号")
order_num = Column(Integer, nullable=True, comment="排序号")
remark = Column(String(512), nullable=True, comment="备注")
create_by = Column(String(64), nullable=True, comment="创建人id")
create_dept_id = Column(String(64), nullable=False, default="", comment="创建人部门ID")
create_time = Column(DateTime, nullable=False, default=datetime.now, comment="创建时间")
update_by = Column(String(64), nullable=True, comment="更新人id")
update_time = Column(DateTime, nullable=False, default=datetime.now, onupdate=datetime.now, comment="更新时间")
del_flag = Column(SmallInteger, nullable=False, default=0, comment="删除标记")
class BizContractProcessingCategory(Base):
"""临床科研/委托加工自定义业务类型 biz_contract_processing_category"""
__tablename__ = "biz_contract_processing_category"
id = Column(String(64), primary_key=True, comment="主键ID")
category_name = Column(String(64), nullable=False, comment="业务类型名称(写入申请单 research_category)")
biz_type = Column(
String(32),
nullable=False,
default="contract_processing",
comment="业务线 basic_experiment / contract_processing",
)
tenant_no = Column(String(64), nullable=False, default="zkxw", comment="租户编号")
order_num = Column(Integer, nullable=True, comment="排序号")
remark = Column(String(512), nullable=True, comment="备注")
create_by = Column(String(64), nullable=True, comment="创建人id")
create_dept_id = Column(String(64), nullable=False, default="", comment="创建人部门ID")
create_time = Column(DateTime, nullable=False, default=datetime.now, comment="创建时间")
update_by = Column(String(64), nullable=True, comment="更新人id")
update_time = Column(DateTime, nullable=False, default=datetime.now, onupdate=datetime.now, comment="更新时间")
del_flag = Column(SmallInteger, nullable=False, default=0, comment="删除标记")
class BizCellSampleType(Base):
"""细胞样本类型 biz_cell_sample_type"""
@@ -1597,6 +1641,7 @@ class BizProtocolSample(Base):
storage_in_date = Column(CHAR(8), nullable=True, comment="入库日期YYYYMMDD")
detect_start_date = Column(CHAR(8), nullable=True, comment="检测开始日期YYYYMMDD")
void_date = Column(CHAR(8), nullable=True, comment="作废日期YYYYMMDD")
void_desc = Column(String(512), nullable=True, comment="样本作废原因")
storage_expire_date = Column(CHAR(8), nullable=True, comment="存储到期日期YYYYMMDD")
is_special = Column(SmallInteger, nullable=False, default=0, comment="是否特殊样本:0否 1是")
special_remark = Column(String(256), nullable=True, comment="特殊说明")
@@ -2259,6 +2304,7 @@ class BizQcWorkOrder(Base):
configured_time = Column(DateTime, nullable=True, comment="配置时间")
configured_by = Column(String(64), nullable=True, comment="配置人")
third_party_fee_total = Column(Numeric(18, 2), nullable=True, comment="第三方费用合计")
attachments = Column(String(4000), nullable=True, comment="工单附件(逗号分隔URL)")
tenant_no = Column(String(64), nullable=False, default="zkxw", comment="租户编号")
order_num = Column(Integer, nullable=True, comment="排序号")
remark = Column(String(512), nullable=True, comment="备注")
@@ -2393,6 +2439,33 @@ class BizQcTask(Base):
del_flag = Column(SmallInteger, nullable=False, default=0, comment="删除标记")
class BizQcTaskResultChangeLog(Base):
"""质检任务检测结果操作留痕 biz_qc_task_result_change_log(Issue #148/#149)"""
__tablename__ = "biz_qc_task_result_change_log"
id = Column(String(64), primary_key=True, comment="主键ID")
task_id = Column(String(64), nullable=False, comment="质检任务ID")
work_order_id = Column(String(64), nullable=True, comment="质检工单ID快照")
sample_code = Column(String(32), nullable=True, comment="样本编码快照")
item_name = Column(String(200), nullable=True, comment="检测项目名称快照")
operate_time = Column(DateTime, nullable=False, comment="业务操作时间")
operator_user_id = Column(String(64), nullable=True, comment="操作人用户ID")
operator_user_name = Column(String(64), nullable=True, comment="操作人姓名快照")
operate_batch_id = Column(String(64), nullable=True, comment="同一次保存批次ID(多任务共用)")
has_field_change = Column(CHAR(1), nullable=False, default="0", comment="1有字段变更 0仅保存无变更")
changes_json = Column(Text, nullable=True, comment="变更明细JSON")
tenant_no = Column(String(64), nullable=False, default="zkxw", comment="租户编号")
order_num = Column(Integer, nullable=True, comment="排序号")
remark = Column(String(512), nullable=True, comment="备注")
create_by = Column(String(64), nullable=True, comment="创建人id")
create_dept_id = Column(String(64), nullable=False, default="", comment="创建人部门ID")
create_time = Column(DateTime, nullable=False, default=datetime.now, comment="创建时间")
update_by = Column(String(64), nullable=True, comment="更新人id")
update_time = Column(DateTime, nullable=False, default=datetime.now, onupdate=datetime.now, comment="更新时间")
del_flag = Column(SmallInteger, nullable=False, default=0, comment="删除标记")
class BizQcTaskAssignee(Base):
"""质检任务负责人 biz_qc_task_assignee"""
@@ -2633,6 +2706,8 @@ class BizCellProductSpec(Base):
id = Column(String(64), primary_key=True, comment="主键ID")
spec_code = Column(String(64), nullable=False, comment="规格编码")
spec_name = Column(String(200), nullable=False, comment="规格名称")
cell_count_qianwan = Column(Numeric(18, 4), nullable=True, comment="细胞数量(单位:千万)")
fill_volume_ml = Column(Numeric(18, 4), nullable=True, comment="分装体积(单位:ml)")
tenant_no = Column(String(64), nullable=False, default="zkxw", comment="租户编号")
order_num = Column(Integer, nullable=True, comment="排序号")
remark = Column(String(512), nullable=True, comment="备注")
@@ -4150,15 +4225,33 @@ class BizPilotApplication(Base):
project_id = Column(String(64), nullable=True, index=True, comment="所属统计项目ID")
application_no = Column(String(64), nullable=True, comment="申请单号(自动生成,前缀ZSSQ)")
application_name = Column(String(200), nullable=True, comment="申请单名称")
project_title = Column(String(200), nullable=True, comment="课题名称(基础实验)")
customer_name = Column(String(200), nullable=True, comment="客户名称(基础实验)")
customer_contact = Column(String(100), nullable=True, comment="客户联系人(基础实验)")
customer_phone = Column(String(32), nullable=True, comment="客户联系方式(基础实验)")
project_title = Column(String(200), nullable=True, comment="课题名称(临床科研)")
customer_name = Column(String(200), nullable=True, comment="客户名称(临床科研)")
customer_contact = Column(String(100), nullable=True, comment="客户联系人(临床科研)")
customer_phone = Column(String(32), nullable=True, comment="客户联系方式(临床科研)")
research_category = Column(
String(64),
nullable=True,
comment="业务子类型;临床科研三项码/委托加工产品码或自定义其他",
)
application_status = Column(String(16), nullable=False, default="dks", comment="dks待开始 jxz进行中 ywc已完成 yzf已作废")
approval_status = Column(
String(16),
nullable=True,
comment="审批状态 dsp待审批 ytg已通过 yth已驳回;非科研类可空",
)
approval_user_id = Column(String(64), nullable=True, comment="审批人用户ID")
approval_time = Column(DateTime, nullable=True, comment="审批时间")
approval_remark = Column(String(1000), nullable=True, comment="审批备注")
channel_service_order_id = Column(String(64), nullable=False, comment="渠道服务购买订单ID")
channel_id = Column(String(64), nullable=True, comment="渠道ID(缓存自服务订单)")
channel_name = Column(String(200), nullable=True, comment="渠道名称(缓存)")
biz_type = Column(String(20), nullable=False, default="pilot_service", comment="业务类型: pilot_service=中试服务, clinical_application=临床应用, basic_experiment=基础实验")
biz_type = Column(
String(20),
nullable=False,
default="pilot_service",
comment="业务类型: pilot_service/clinical_application/basic_experiment/contract_processing",
)
tenant_no = Column(String(64), nullable=False, default="zkxw", comment="租户编号")
order_num = Column(Integer, nullable=True, comment="排序号")
remark = Column(String(512), nullable=True, comment="备注")
+1
View File
@@ -175,6 +175,7 @@ class BizResearchDonationSample(Base):
storage_in_date = Column(String(8), nullable=True, comment="入库日期YYYYMMDD")
detect_start_date = Column(String(8), nullable=True, comment="检测开始日期YYYYMMDD")
void_date = Column(String(8), nullable=True, comment="作废日期YYYYMMDD")
void_desc = Column(String(512), nullable=True, comment="样本作废原因")
storage_expire_date = Column(String(8), nullable=True, comment="存储到期日期YYYYMMDD")
is_special = Column(SmallInteger, nullable=False, default=0, comment="是否特殊样本:0否 1是")
special_remark = Column(String(256), nullable=True, comment="特殊说明")
+3
View File
@@ -111,4 +111,7 @@ class QcWorkOrderUpdateBody(BaseModel):
qc_conclusion: Optional[str] = Field(
None, alias="qcConclusion", description="质检结论 tg合格 btg不合格,空串清空"
)
attachments: Optional[str] = Field(
None, description="工单附件(逗号分隔URL),空串清空"
)
remark: Optional[str] = Field(None, description="备注")
@@ -1,4 +1,4 @@
"""基础实验交付日前一天:服务号模板提醒。"""
"""临床科研交付日前一天:服务号模板提醒。"""
from __future__ import annotations
import logging
@@ -126,7 +126,7 @@ def _iter_candidate_schedules(db: Session, *, delivery_day: date) -> List[Any]:
& (BizPilotInfusionScheduleProduct.del_flag == 0),
)
.filter(
BizPilotApplication.biz_type == "basic_experiment",
BizPilotApplication.biz_type in ("basic_experiment", "contract_processing"),
BizPilotApplication.del_flag == 0,
BizPilotInfusionPlan.del_flag == 0,
BizPilotInfusionSchedule.del_flag == 0,
@@ -137,7 +137,7 @@ def _iter_candidate_schedules(db: Session, *, delivery_day: date) -> List[Any]:
.order_by(BizPilotInfusionSchedule.infusion_time.asc())
.all()
)
# 一计划多产品时取首条产品行(基础实验通常一行)
# 一计划多产品时取首条产品行(临床科研通常一行)
seen: set = set()
out = []
for sched, app, prod in rows:
File diff suppressed because it is too large. Load diff
+15 -2
View File
@@ -56,6 +56,12 @@ from app.services.web_auth_roles import (
CELL = 'cell_storage'
DONATION = 'research_donation'
SOURCES = (CELL, DONATION)
_SAMPLE_STATUS_LABELS = {
'ycj': '已采集',
'jcz': '检测中',
'yrk': '已入库',
'yzf': '已作废',
}
def _current_tenant_user_info(
@@ -265,18 +271,25 @@ def _visible_rows(db: Session, freight_ids: List[str], ctx: MarketFieldContext,
def _item_dict(row) -> Dict[str, Any]:
item, sample, parent, party, sample_type = row
source = item.sample_source
return {
sample_code = sample.sample_code or ''
payload = {
'id': item.id,
'freightId': item.freight_id,
'sampleSource': source,
'sampleId': sample.id,
'sampleCode': sample.sample_code or '',
'sampleCode': sample_code,
'protocolId': parent.id,
'protocolNo': (parent.protocol_no if source == CELL else parent.donation_no) or '',
'sampleTypeName': sample_type.type_name if sample_type else '',
'motherName': party.mother_name if party else '',
'newbornName': party.newborn_name if party else '',
}
if sample_code:
status = str(getattr(sample, 'sample_status', None) or '').strip()
payload['sampleStatus'] = status
payload['sampleStatusLabel'] = _SAMPLE_STATUS_LABELS.get(status, '')
payload['voidDesc'] = str(getattr(sample, 'void_desc', None) or '')
return payload
def _label_map(db: Session, tenant_no: str, values: List[str]) -> Dict[str, str]:
+77 -3
View File
@@ -40,6 +40,51 @@ from app.services.market_support import (
)
_SAMPLE_STATUS_LABELS = {
'ycj': '已采集',
'jcz': '检测中',
'yrk': '已入库',
'yzf': '已作废',
}
def _sample_status_by_code(
db: Session,
tenant_no: str,
sample_codes: List[str],
) -> Dict[str, Dict[str, str]]:
"""按租户 + 样本编码取样本状态;同一编码多行时保留最近更新的一条。"""
wanted = [code for code in {str(code or '').strip() for code in sample_codes} if code]
if not wanted:
return {}
rows = (
db.query(BizProtocolSample)
.filter(
BizProtocolSample.tenant_no == tenant_no,
BizProtocolSample.del_flag == 0,
BizProtocolSample.sample_code.in_(wanted),
)
.order_by(
BizProtocolSample.update_time.desc(),
BizProtocolSample.create_time.desc(),
BizProtocolSample.id.desc(),
)
.all()
)
result: Dict[str, Dict[str, str]] = {}
for sample in rows:
code = str(sample.sample_code or '').strip()
if not code or code in result:
continue
status = str(sample.sample_status or '').strip()
result[code] = {
'sampleStatus': status,
'sampleStatusLabel': _SAMPLE_STATUS_LABELS.get(status, ''),
'voidDesc': sample.void_desc or '',
}
return result
def _current_dept_id(user_info: dict) -> str:
return str(
user_info.get('dept_id')
@@ -104,12 +149,16 @@ def _load_sample_meta(
discount = None
if original is not None and current is not None and original > current:
discount = original - current
status = str(sample.sample_status or '').strip()
result.setdefault(
sample.sample_code or '',
{
'storageYears': sample.storage_years,
'sampleTypeName': sample_type.type_name if sample_type else '',
'discountAmount': _money(discount),
'sampleStatus': status,
'sampleStatusLabel': _SAMPLE_STATUS_LABELS.get(status, ''),
'voidDesc': sample.void_desc or '',
},
)
return result
@@ -235,7 +284,8 @@ def _payment_dict(
'bfyj': '部分已缴',
'dfj': '待缴费',
}[progress_code]
return {
sample_code = payment.sample_code or ''
payload = {
'id': payment.id,
'collectionProtocolId': protocol.id,
'protocolNo': protocol.protocol_no or '',
@@ -243,7 +293,7 @@ def _payment_dict(
'paymentModelVersion': int(getattr(protocol, 'payment_model_version', None) or 1),
'motherName': (party.mother_name if party else '') or '',
'motherPhone': (party.mother_phone if party else '') or '',
'sampleCode': payment.sample_code or '',
'sampleCode': sample_code,
'payMode': payment.pay_mode or '',
'contractAmount': _money(payment.contract_amount),
'signDate': _display_ymd(getattr(protocol, 'register_date', None)),
@@ -262,6 +312,11 @@ def _payment_dict(
'periods': periods,
'schedules': schedule_rows,
}
if sample_code:
payload['sampleStatus'] = meta.get('sampleStatus') or ''
payload['sampleStatusLabel'] = meta.get('sampleStatusLabel') or ''
payload['voidDesc'] = meta.get('voidDesc') or ''
return payload
def _scoped_payment_query(
@@ -733,6 +788,14 @@ def list_payment_chase(
)
}
rows: List[Dict[str, Any]] = []
status_by_code = _sample_status_by_code(
db,
ctx.tenant_no,
[
payment.sample_code or schedule.sample_code or ''
for schedule, payment, _, _, _, _ in candidates
],
)
for schedule, payment, protocol, party, collection, paid in candidates:
due_date = parse_due_date_ymd(schedule.due_date)
if due_date is None:
@@ -741,6 +804,8 @@ def list_payment_chase(
due_value = Decimal(str(schedule.due_amount or 0))
arrears = max(due_value - paid_value, Decimal('0'))
is_overdue = due_date < today_value
sample_code = payment.sample_code or schedule.sample_code or ''
sample_state = status_by_code.get(sample_code, {}) if sample_code else {}
rows.append(
{
'scheduleId': schedule.id,
@@ -750,7 +815,16 @@ def list_payment_chase(
'protocolStatus': protocol.protocol_status or '',
'motherName': (party.mother_name if party else '') or '',
'motherPhone': (party.mother_phone if party else '') or '',
'sampleCode': payment.sample_code or schedule.sample_code or '',
'sampleCode': sample_code,
**(
{
'sampleStatus': sample_state.get('sampleStatus', ''),
'sampleStatusLabel': sample_state.get('sampleStatusLabel', ''),
'voidDesc': sample_state.get('voidDesc', ''),
}
if sample_code
else {}
),
'salesUserId': collection.sales_user_id or '',
'salesUserName': sales_user_names.get(
collection.sales_user_id or '', ''
+18
View File
@@ -641,6 +641,14 @@ def _party_name_donation(db: Session, ids: List[str], tenant_no: str) -> dict:
return {row.research_donation_id: row.mother_name or '' for row in rows}
_SAMPLE_STATUS_LABELS = {
'ycj': '已采集',
'jcz': '检测中',
'yrk': '已入库',
'yzf': '已作废',
}
def _enrich_protocol_cards(
db: Session, items: List[dict], tenant_no: str
) -> None:
@@ -795,6 +803,11 @@ def _enrich_protocol_cards(
payment_summary = payment_summaries.get(item['id']) or {}
transport = transport_by_sample.get(getattr(sample, 'id', ''))
sample_code = getattr(sample, 'sample_code', '') or ''
sample_status = ''
sample_void_desc = ''
if sample_code:
sample_status = str(getattr(sample, 'sample_status', None) or '').strip()
sample_void_desc = str(getattr(sample, 'void_desc', None) or '')
region_manager_name = user_names.get(
getattr(collection, 'region_manager_user_id', ''), ''
)
@@ -844,6 +857,11 @@ def _enrich_protocol_cards(
str(item.get('voidType') or ''), ''
),
)
if sample_code:
# 样本作废原因与协议级 voidDesc 分开,捐赠列表「废弃原因」仍读协议描述。
item['sampleStatus'] = sample_status
item['sampleStatusLabel'] = _SAMPLE_STATUS_LABELS.get(sample_status, '')
item['sampleVoidDesc'] = sample_void_desc
def list_protocols(
+4 -1
View File
@@ -5,12 +5,15 @@ from app.core.config import settings
def create_assignment(db, tenant_no, user, project_id, biz_type):
from app.services.project_management import validate_assignment
from app.constants.pilot_biz import requires_leader_approval
if biz_type == 'clinical_application':
if project_id:
raise HTTPException(400, '临床应用不支持项目归属')
return None
# 临床科研/委托加工须绑定项目,供项目组负责人审批
required = True if requires_leader_approval(biz_type) else settings.PROJECT_ASSIGNMENT_REQUIRED
return validate_assignment(db, tenant_no, user, project_id, biz_type,
required=settings.PROJECT_ASSIGNMENT_REQUIRED)
required=required)
def guard_project_edit(row, payload):
+3 -3
View File
@@ -19,6 +19,7 @@ BUSINESS = {
'research_donation': (BizResearchDonation, 'donation_no', 'donation_status'),
'pilot_service': (BizPilotApplication, 'application_no', 'application_status'),
'basic_experiment': (BizPilotApplication, 'application_no', 'application_status'),
'contract_processing': (BizPilotApplication, 'application_no', 'application_status'),
}
COUNT_TYPES = tuple(k for k in BUSINESS if k != 'presign')
ALL_PROJECTS_PERMISSION = 'project:project:all'
@@ -215,8 +216,7 @@ def preview_assignment(db, tenant, user, kind, row_id, project_id):
def assign(db, tenant, user, kind, row_id, project_id, reason, expected):
check_permission(db, tenant, user, 'project:assignment:edit')
if not reason or not reason.strip():
raise HTTPException(400, '请填写调整原因')
reason_text = (reason or '').strip()
rows = linked_records(db, tenant, user, kind, row_id, lock=True)
actual = {(k, r.id, r.project_id) for k, r in rows}
refreshed = linked_records(db, tenant, user, kind, row_id, current_read=True)
@@ -228,7 +228,7 @@ def assign(db, tenant, user, kind, row_id, project_id, reason, expected):
new_name = project_brief(db, tenant, project_id)['projectName']
operator = scoped(db, SysUser, tenant).filter(SysUser.id == user.get('user_id')).first()
for k, row in rows:
db.add(ProjectAssignmentAudit(id=generate_uuid(), tenant_no=tenant, biz_type=k, biz_id=row.id, old_project_id=row.project_id, new_project_id=project_id, old_project_name=project_brief(db, tenant, row.project_id)['projectName'], new_project_name=new_name, reason=reason.strip(), operator_name=operator.nick_name if operator else user.get('user_id'), create_by=user.get('user_id'), create_dept_id=user.get('dept_id') or ''))
db.add(ProjectAssignmentAudit(id=generate_uuid(), tenant_no=tenant, biz_type=k, biz_id=row.id, old_project_id=row.project_id, new_project_id=project_id, old_project_name=project_brief(db, tenant, row.project_id)['projectName'], new_project_name=new_name, reason=reason_text, operator_name=operator.nick_name if operator else user.get('user_id'), create_by=user.get('user_id'), create_dept_id=user.get('dept_id') or ''))
row.project_id = project_id
row.update_by = user.get('user_id')
row.update_time = datetime.now()
@@ -1,16 +1,24 @@
"""市场协议作废 ↔ 质检样本接收废弃双向联动。
"""市场协议无效态 ↔ 样本接收废弃 / 样本状态作废联动。
规则(细胞存储 / 科研捐赠):
1. 协议变为已作废(yzf)时,协议下全部样本接收结论自动为废弃(bj)。
2. 协议下全部有效样本均已废弃/拒收(bj)时,协议自动已作废,作废类型为「实验室废弃」。
1. 单条样本接收结论为废弃(bj)时:仅该样本 `sample_status` 置为已作废(yzf),
写 `void_date`,并将接收备注写入 `void_desc`(备注为空则作废原因为空);
协议状态保持不变。接收结论改回接收(js)且协议仍有效时:若该样本为 yzf,则清空状态、void_date 与 void_desc。
2. 协议变为已作废(yzf)或属地废弃(sdfq)时:
- 协议下全部样本接收结论自动为废弃(bj);
- 协议下全部有效样本 `sample_status` 置为已作废(yzf),并写入 `void_date`。
3. 协议下全部有效样本均已废弃/拒收(bj)时,协议自动已作废,作废类型为「实验室废弃」。
4. 人工【样本废弃】:仅将该样本置 yzf 并写 void_date/void_desc,不改接收结论;
若协议下有效样本全部为 yzf,则自动作废协议(不联动接收结论)。
"""
from __future__ import annotations
from datetime import datetime
from typing import List, Optional
from typing import List, Optional, Union
from sqlalchemy.orm import Session
from app.core.protocol_status_display import INACTIVE_PROTOCOL_STATUSES
from app.core.utils import generate_uuid
from app.models.models import (
BizCollectionProtocol,
@@ -23,9 +31,23 @@ from app.models.research_donation import BizResearchDonation, BizResearchDonatio
LAB_VOID_TYPE_CODE = "sysfq"
LAB_VOID_TYPE_LABEL = "实验室废弃"
VOID_TYPE_DICT = "xyzflx"
SAMPLE_VOID_STATUS = "yzf"
_AUTO_DISCARD_REMARK = "协议作废自动废弃"
_AUTO_VOID_DESC = "全部样本接收废弃/拒收,系统自动作废"
_AUTO_VOID_BY_SAMPLE_STATUS_DESC = "全部样本已作废,系统自动作废协议"
def _void_date_yyyymmdd(
*,
void_time: Optional[datetime] = None,
void_date: Optional[str] = None,
) -> str:
raw = (void_date or "").strip()
if len(raw) == 8 and raw.isdigit():
return raw
ts = void_time or datetime.now()
return ts.strftime("%Y%m%d")
def ensure_lab_void_type(db: Session, *, tenant_no: str) -> str:
@@ -204,7 +226,7 @@ def discard_receptions_for_voided_protocol(
tenant_no: str,
user_id: Optional[str] = None,
) -> int:
"""协议已作废后,将其下样本接收全部置为废弃。返回处理样本数。"""
"""协议无效后,将其下样本接收全部置为废弃。返回处理样本数。"""
src = (source or "").strip()
pid = (protocol_id or "").strip()
tenant = (tenant_no or "").strip()
@@ -242,6 +264,75 @@ def discard_receptions_for_voided_protocol(
return len(samples)
def void_samples_for_inactive_protocol(
db: Session,
*,
source: str,
protocol_id: str,
tenant_no: str,
user_id: Optional[str] = None,
void_time: Optional[datetime] = None,
void_date: Optional[str] = None,
) -> int:
"""协议无效后,将其下有效样本状态一律置为已作废并写入 void_date。返回处理样本数。"""
src = (source or "").strip()
pid = (protocol_id or "").strip()
tenant = (tenant_no or "").strip()
if src not in ("cell_storage", "research_donation") or not pid or not tenant:
return 0
date_s = _void_date_yyyymmdd(void_time=void_time, void_date=void_date)
now = datetime.now()
if src == "cell_storage":
samples: List[Union[BizProtocolSample, BizResearchDonationSample]] = list(
_list_cell_samples(db, protocol_id=pid, tenant_no=tenant)
)
else:
samples = list(_list_donation_samples(db, donation_id=pid, tenant_no=tenant))
for sample in samples:
sample.sample_status = SAMPLE_VOID_STATUS
sample.void_date = date_s
sample.update_by = user_id
sample.update_time = now
db.add(sample)
db.flush()
return len(samples)
def _resolve_protocol_void_time(
db: Session,
*,
source: str,
protocol_id: str,
tenant_no: str,
) -> Optional[datetime]:
src = (source or "").strip()
pid = (protocol_id or "").strip()
tenant = (tenant_no or "").strip()
if src == "cell_storage":
obj = (
db.query(BizCollectionProtocol)
.filter(
BizCollectionProtocol.id == pid,
BizCollectionProtocol.tenant_no == tenant,
BizCollectionProtocol.del_flag == 0,
)
.first()
)
return obj.void_time if obj else None
obj = (
db.query(BizResearchDonation)
.filter(
BizResearchDonation.id == pid,
BizResearchDonation.tenant_no == tenant,
BizResearchDonation.del_flag == 0,
)
.first()
)
return obj.void_time if obj else None
def _all_samples_discarded(
db: Session,
*,
@@ -299,7 +390,7 @@ def maybe_void_protocol_when_all_samples_discarded(
if not obj:
return False
status = (obj.protocol_status or "").strip()
if status in ("yzf", "sdfq"):
if status in INACTIVE_PROTOCOL_STATUSES:
return False
from app.core.protocol_status_display import assert_protocol_status_transition
from app.crud.collection_protocol import update_collection_protocol
@@ -319,7 +410,8 @@ def maybe_void_protocol_when_all_samples_discarded(
void_desc=_AUTO_VOID_DESC,
void_type=void_type,
commit=False,
sync_reception_discard=False,
# 接收已全部废弃;仍需同步样本状态为已作废
sync_reception_discard=True,
)
return True
@@ -335,7 +427,7 @@ def maybe_void_protocol_when_all_samples_discarded(
if not obj:
return False
status = (obj.donation_status or "").strip()
if status in ("yzf", "sdfq"):
if status in INACTIVE_PROTOCOL_STATUSES:
return False
# 捐赠 change_status 默认 commit;此处内联等价逻辑避免提前提交。
@@ -374,6 +466,173 @@ def maybe_void_protocol_when_all_samples_discarded(
)
db.add(obj)
db.flush()
# 接收已全部废弃;仍需同步样本状态为已作废
after_protocol_voided(
db,
source="research_donation",
protocol_id=pid,
tenant_no=tenant,
user_id=user_id,
)
return True
def _find_sample_for_reception(
db: Session,
*,
reception: BizSampleReception,
tenant_no: str,
) -> tuple[str, Optional[Union[BizProtocolSample, BizResearchDonationSample]]]:
source = (reception.reception_source or "cell_storage").strip() or "cell_storage"
tenant = (tenant_no or "").strip()
code = (reception.sample_code or "").strip()
if source == "cell_storage":
sid = (reception.protocol_sample_id or "").strip()
if sid:
obj = (
db.query(BizProtocolSample)
.filter(
BizProtocolSample.id == sid,
BizProtocolSample.tenant_no == tenant,
BizProtocolSample.del_flag == 0,
)
.first()
)
if obj:
return source, obj
pid = (reception.collection_protocol_id or "").strip()
if code and pid:
return source, (
db.query(BizProtocolSample)
.filter(
BizProtocolSample.collection_protocol_id == pid,
BizProtocolSample.sample_code == code,
BizProtocolSample.tenant_no == tenant,
BizProtocolSample.del_flag == 0,
)
.first()
)
return source, None
sid = (reception.donation_sample_id or "").strip()
if sid:
obj = (
db.query(BizResearchDonationSample)
.filter(
BizResearchDonationSample.id == sid,
BizResearchDonationSample.tenant_no == tenant,
BizResearchDonationSample.del_flag == 0,
)
.first()
)
if obj:
return source, obj
pid = (reception.research_donation_id or "").strip()
if code and pid:
return source, (
db.query(BizResearchDonationSample)
.filter(
BizResearchDonationSample.research_donation_id == pid,
BizResearchDonationSample.sample_code == code,
BizResearchDonationSample.tenant_no == tenant,
BizResearchDonationSample.del_flag == 0,
)
.first()
)
return source, None
def _protocol_is_inactive(
db: Session,
*,
source: str,
protocol_id: str,
tenant_no: str,
) -> bool:
src = (source or "").strip()
pid = (protocol_id or "").strip()
tenant = (tenant_no or "").strip()
if not pid or not tenant:
return False
if src == "cell_storage":
obj = (
db.query(BizCollectionProtocol)
.filter(
BizCollectionProtocol.id == pid,
BizCollectionProtocol.tenant_no == tenant,
BizCollectionProtocol.del_flag == 0,
)
.first()
)
status = (obj.protocol_status or "").strip() if obj else ""
else:
obj = (
db.query(BizResearchDonation)
.filter(
BizResearchDonation.id == pid,
BizResearchDonation.tenant_no == tenant,
BizResearchDonation.del_flag == 0,
)
.first()
)
status = (obj.donation_status or "").strip() if obj else ""
return status in INACTIVE_PROTOCOL_STATUSES
def void_sample_for_discarded_reception(
db: Session,
*,
reception: BizSampleReception,
tenant_no: str,
user_id: Optional[str] = None,
) -> bool:
"""单条接收废弃:将该样本置为已作废,作废原因取接收备注。"""
_source, sample = _find_sample_for_reception(db, reception=reception, tenant_no=tenant_no)
if not sample:
return False
now = datetime.now()
reason = (reception.remark or "").strip()
if len(reason) > 512:
reason = reason[:512]
sample.sample_status = SAMPLE_VOID_STATUS
sample.void_date = _void_date_yyyymmdd(void_time=reception.reception_time or now)
sample.void_desc = reason or None
sample.update_by = user_id
sample.update_time = now
db.add(sample)
db.flush()
return True
def clear_sample_void_for_accepted_reception(
db: Session,
*,
reception: BizSampleReception,
tenant_no: str,
user_id: Optional[str] = None,
) -> bool:
"""接收改回接收:协议仍有效且样本为 yzf 时,清空样本作废状态。"""
source, sample = _find_sample_for_reception(db, reception=reception, tenant_no=tenant_no)
if not sample:
return False
if (sample.sample_status or "").strip() != SAMPLE_VOID_STATUS:
return False
if source == "cell_storage":
protocol_id = (reception.collection_protocol_id or "").strip()
else:
protocol_id = (reception.research_donation_id or "").strip()
if _protocol_is_inactive(
db, source=source, protocol_id=protocol_id, tenant_no=tenant_no
):
return False
now = datetime.now()
sample.sample_status = None
sample.void_date = None
sample.void_desc = None
sample.update_by = user_id
sample.update_time = now
db.add(sample)
db.flush()
return True
@@ -384,23 +643,32 @@ def after_sample_reception_saved(
tenant_no: str,
user_id: Optional[str] = None,
) -> None:
"""样本接收保存后:若结论为废弃,尝试自动作废所属协议。"""
if (reception.accept_conclusion or "").strip() != "bj":
return
"""样本接收保存后:同步该样本状态;若全部废弃则尝试自动作废协议。"""
conclusion = (reception.accept_conclusion or "").strip()
source = (reception.reception_source or "cell_storage").strip() or "cell_storage"
if source == "cell_storage":
protocol_id = (reception.collection_protocol_id or "").strip()
else:
protocol_id = (reception.research_donation_id or "").strip()
if not protocol_id:
if conclusion == "bj":
void_sample_for_discarded_reception(
db, reception=reception, tenant_no=tenant_no, user_id=user_id
)
if protocol_id:
maybe_void_protocol_when_all_samples_discarded(
db,
source=source,
protocol_id=protocol_id,
tenant_no=tenant_no,
user_id=user_id,
)
return
maybe_void_protocol_when_all_samples_discarded(
db,
source=source,
protocol_id=protocol_id,
tenant_no=tenant_no,
user_id=user_id,
)
if conclusion == "js":
clear_sample_void_for_accepted_reception(
db, reception=reception, tenant_no=tenant_no, user_id=user_id
)
def after_protocol_voided(
@@ -411,7 +679,7 @@ def after_protocol_voided(
tenant_no: str,
user_id: Optional[str] = None,
) -> None:
"""协议作废后:同步废弃其下全部样本接收。"""
"""协议作废/属地废弃后:同步废弃样本接收,并将样本状态置为已作废。"""
discard_receptions_for_voided_protocol(
db,
source=source,
@@ -419,3 +687,234 @@ def after_protocol_voided(
tenant_no=tenant_no,
user_id=user_id,
)
void_samples_for_inactive_protocol(
db,
source=source,
protocol_id=protocol_id,
tenant_no=tenant_no,
user_id=user_id,
void_time=_resolve_protocol_void_time(
db, source=source, protocol_id=protocol_id, tenant_no=tenant_no
),
)
def _all_samples_status_voided(
db: Session,
*,
source: str,
protocol_id: str,
tenant_no: str,
) -> bool:
src = (source or "").strip()
if src == "cell_storage":
samples = _list_cell_samples(db, protocol_id=protocol_id, tenant_no=tenant_no)
else:
samples = _list_donation_samples(db, donation_id=protocol_id, tenant_no=tenant_no)
if not samples:
return False
for sample in samples:
if (sample.sample_status or "").strip() != SAMPLE_VOID_STATUS:
return False
return True
def maybe_void_protocol_when_all_samples_status_voided(
db: Session,
*,
source: str,
protocol_id: str,
tenant_no: str,
user_id: Optional[str] = None,
) -> bool:
"""若协议下有效样本全部已作废,则自动作废协议;不联动接收结论。"""
src = (source or "").strip()
pid = (protocol_id or "").strip()
tenant = (tenant_no or "").strip()
if src not in ("cell_storage", "research_donation") or not pid or not tenant:
return False
if not _all_samples_status_voided(db, source=src, protocol_id=pid, tenant_no=tenant):
return False
void_type = ensure_lab_void_type(db, tenant_no=tenant)
now = datetime.now()
if src == "cell_storage":
obj = (
db.query(BizCollectionProtocol)
.filter(
BizCollectionProtocol.id == pid,
BizCollectionProtocol.tenant_no == tenant,
BizCollectionProtocol.del_flag == 0,
)
.first()
)
if not obj:
return False
status = (obj.protocol_status or "").strip()
if status in INACTIVE_PROTOCOL_STATUSES:
return False
from app.core.protocol_status_display import assert_protocol_status_transition
from app.crud.collection_protocol import update_collection_protocol
try:
assert_protocol_status_transition(status, "yzf", kind="protocol")
except ValueError:
return False
update_collection_protocol(
db,
pid,
tenant_no=tenant,
user_id=user_id,
protocol_status="yzf",
void_time=now,
void_desc=_AUTO_VOID_BY_SAMPLE_STATUS_DESC,
void_type=void_type,
commit=False,
sync_reception_discard=False,
)
return True
obj = (
db.query(BizResearchDonation)
.filter(
BizResearchDonation.id == pid,
BizResearchDonation.tenant_no == tenant,
BizResearchDonation.del_flag == 0,
)
.first()
)
if not obj:
return False
status = (obj.donation_status or "").strip()
if status in INACTIVE_PROTOCOL_STATUSES:
return False
from app.core.protocol_status_display import assert_protocol_status_transition
from app.crud.dict_data import normalize_void_type
from app.crud.research_donation import (
_DONATION_STATUS_CHANGE_TYPE,
append_donation_status_change,
)
current = obj.donation_status or ""
try:
assert_protocol_status_transition(current, "yzf", kind="donation")
except ValueError:
return False
normalized = normalize_void_type(db, value=void_type, tenant_no=tenant)
obj.donation_status = "yzf"
obj.void_time = now
obj.void_desc = _AUTO_VOID_BY_SAMPLE_STATUS_DESC
obj.void_type = normalized
obj.update_by = user_id
obj.update_time = now
change_type = _DONATION_STATUS_CHANGE_TYPE.get("yzf")
if change_type:
append_donation_status_change(
db,
research_donation_id=obj.id,
change_type=change_type,
from_status=current,
to_status="yzf",
change_time=now,
change_desc=_AUTO_VOID_BY_SAMPLE_STATUS_DESC,
void_type=normalized,
tenant_no=tenant,
user_id=user_id,
)
db.add(obj)
db.flush()
return True
def void_sample_manually(
db: Session,
*,
source: str,
tenant_no: str,
void_desc: str,
user_id: Optional[str] = None,
sample_id: Optional[str] = None,
sample_code: Optional[str] = None,
protocol_id: Optional[str] = None,
commit: bool = True,
) -> Union[BizProtocolSample, BizResearchDonationSample]:
"""人工样本废弃:写 yzf/void_date/void_desc;不改接收;全作废则自动作废协议。"""
src = (source or "").strip()
tenant = (tenant_no or "").strip()
reason = (void_desc or "").strip()
sid = (sample_id or "").strip()
code = (sample_code or "").strip()
pid = (protocol_id or "").strip()
if src not in ("cell_storage", "research_donation"):
raise ValueError("来源类型无效")
if not tenant:
raise ValueError("租户编号不能为空")
if not reason:
raise ValueError("请填写作废原因")
if not sid and not code:
raise ValueError("样本标识不能为空")
now = datetime.now()
sample: Optional[Union[BizProtocolSample, BizResearchDonationSample]] = None
parent_id = ""
if src == "cell_storage":
q = db.query(BizProtocolSample).filter(
BizProtocolSample.tenant_no == tenant,
BizProtocolSample.del_flag == 0,
)
if sid:
q = q.filter(BizProtocolSample.id == sid)
else:
q = q.filter(BizProtocolSample.sample_code == code)
if pid:
q = q.filter(BizProtocolSample.collection_protocol_id == pid)
sample = q.first()
if not sample:
raise ValueError("样本不存在")
parent_id = (sample.collection_protocol_id or "").strip()
else:
q = db.query(BizResearchDonationSample).filter(
BizResearchDonationSample.tenant_no == tenant,
BizResearchDonationSample.del_flag == 0,
)
if sid:
q = q.filter(BizResearchDonationSample.id == sid)
else:
q = q.filter(BizResearchDonationSample.sample_code == code)
if pid:
q = q.filter(BizResearchDonationSample.research_donation_id == pid)
sample = q.first()
if not sample:
raise ValueError("样本不存在")
parent_id = (sample.research_donation_id or "").strip()
if _protocol_is_inactive(db, source=src, protocol_id=parent_id, tenant_no=tenant):
raise ValueError("所属协议已作废或属地废弃,无法操作")
sample.sample_status = SAMPLE_VOID_STATUS
sample.void_date = _void_date_yyyymmdd(void_time=now)
sample.void_desc = reason
sample.update_by = user_id
sample.update_time = now
db.add(sample)
db.flush()
if parent_id:
maybe_void_protocol_when_all_samples_status_voided(
db,
source=src,
protocol_id=parent_id,
tenant_no=tenant,
user_id=user_id,
)
if commit:
db.commit()
db.refresh(sample)
else:
db.flush()
return sample
@@ -1,4 +1,4 @@
"""质检工单 · 用户费用摘要(采集协议 / 基础实验)"""
"""质检工单 · 用户费用摘要(采集协议 / 临床科研)"""
from __future__ import annotations
from decimal import Decimal
@@ -27,8 +27,10 @@ _PAY_STATUS_LABELS = {
"ytf": "已退费",
}
# 出库工单:输注计划缴费(基础实验 / 临床应用共用 biz_pilot_payment)
_OUTBOUND_FEE_BIZ_TYPES = frozenset({"basic_experiment", "clinical_application"})
# 出库工单:输注计划缴费(临床科研 / 临床应用共用 biz_pilot_payment)
_OUTBOUND_FEE_BIZ_TYPES = frozenset(
{"basic_experiment", "contract_processing", "clinical_application"}
)
def _is_outbound_fee_biz_type(biz_type: Optional[str]) -> bool:
@@ -0,0 +1,472 @@
"""确保 UC 入库编码对应的 5 步内置工艺路线 / 任务组合存在。
步骤顺序(业务确认):
1. 脐带MSC原代细胞培养
2. 脐带MSC原代细胞培养半换液
3. 脐带MSC原代二次贴壁
4. 脐带MSC原代重铺操作
5. 干细胞冻存
内容从既有「干细胞培养(内置模版)」按工序代码拷贝,排除传代。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any, Dict, List, Optional
from sqlalchemy.orm import Session
from app.models.models import (
BizProcessRoute,
BizProcessRouteStep,
BizProcessRouteStepConsumable,
BizProcessRouteStepDataCollection,
BizProcessRouteStepOutput,
BizProcessRouteStepReagent,
BizProductionTaskSet,
BizProductionTaskSetItem,
)
from app.core.utils import generate_uuid
from app.utils.lab_storage_code_task_set import (
BC_MSC_BUILTIN_SET_NAME,
UC_MSC_BUILTIN_SET_NAME,
)
UC_MSC_ROUTE_CODE = "MSC原代-UC-BUILTIN"
UC_MSC_ROUTE_NAME = UC_MSC_BUILTIN_SET_NAME
SOURCE_MSC_ROUTE_CODE = "MSC培养-BUILTIN"
SOURCE_MSC_ROUTE_NAME = BC_MSC_BUILTIN_SET_NAME
# process_code → 目标 step_order
UC_MSC_STEP_ORDER: List[str] = [
"SOP-SC-003-E01-01", # 原代细胞培养
"SOP-SC-004-E01-01", # 半换液
"SOP-SC-006-E01-01", # 二次贴壁
"SOP-SC-005-E01-01", # 重铺
"SOP-SC-008-E01-01", # 冻存
]
def _now() -> datetime:
return datetime.now()
def get_uc_msc_builtin_set(
db: Session, *, tenant_no: str
) -> Optional[BizProductionTaskSet]:
return (
db.query(BizProductionTaskSet)
.filter(
BizProductionTaskSet.tenant_no == tenant_no,
BizProductionTaskSet.set_name == UC_MSC_BUILTIN_SET_NAME,
BizProductionTaskSet.is_builtin == "1",
BizProductionTaskSet.del_flag == 0,
)
.first()
)
def _find_source_route(db: Session, *, tenant_no: str) -> BizProcessRoute:
route = (
db.query(BizProcessRoute)
.filter(
BizProcessRoute.tenant_no == tenant_no,
BizProcessRoute.route_code == SOURCE_MSC_ROUTE_CODE,
BizProcessRoute.del_flag == 0,
)
.first()
)
if route:
return route
route = (
db.query(BizProcessRoute)
.filter(
BizProcessRoute.tenant_no == tenant_no,
BizProcessRoute.route_name == SOURCE_MSC_ROUTE_NAME,
BizProcessRoute.is_builtin == "1",
BizProcessRoute.del_flag == 0,
)
.first()
)
if not route:
raise ValueError(
f"缺少源工艺路线 {SOURCE_MSC_ROUTE_CODE}/{SOURCE_MSC_ROUTE_NAME},无法创建 UC 模版"
)
return route
def _clone_step_children(
db: Session,
*,
src_step_id: str,
dst_step_id: str,
tenant_no: str,
user_id: Optional[str],
create_dept_id: str,
now: datetime,
) -> None:
reagent_rows = (
db.query(BizProcessRouteStepReagent)
.filter(
BizProcessRouteStepReagent.step_id == src_step_id,
BizProcessRouteStepReagent.tenant_no == tenant_no,
BizProcessRouteStepReagent.del_flag == 0,
)
.all()
)
for r in reagent_rows:
db.add(
BizProcessRouteStepReagent(
id=generate_uuid(),
step_id=dst_step_id,
reagent_code=r.reagent_code,
reagent_name=r.reagent_name,
spec=r.spec,
standard_usage=r.standard_usage,
unit=r.unit,
is_key_material=r.is_key_material,
tenant_no=tenant_no,
order_num=r.order_num,
remark=r.remark,
create_by=user_id,
create_dept_id=create_dept_id or "",
create_time=now,
update_by=user_id,
update_time=now,
del_flag=0,
)
)
consumable_rows = (
db.query(BizProcessRouteStepConsumable)
.filter(
BizProcessRouteStepConsumable.step_id == src_step_id,
BizProcessRouteStepConsumable.tenant_no == tenant_no,
BizProcessRouteStepConsumable.del_flag == 0,
)
.all()
)
for c in consumable_rows:
db.add(
BizProcessRouteStepConsumable(
id=generate_uuid(),
step_id=dst_step_id,
consumable_code=c.consumable_code,
consumable_name=c.consumable_name,
spec_model=c.spec_model,
standard_usage=c.standard_usage,
unit=c.unit,
is_required=c.is_required,
remark=c.remark,
tenant_no=tenant_no,
order_num=c.order_num,
create_by=user_id,
create_dept_id=create_dept_id or "",
create_time=now,
update_by=user_id,
update_time=now,
del_flag=0,
)
)
output_rows = (
db.query(BizProcessRouteStepOutput)
.filter(
BizProcessRouteStepOutput.step_id == src_step_id,
BizProcessRouteStepOutput.tenant_no == tenant_no,
BizProcessRouteStepOutput.del_flag == 0,
)
.all()
)
for o in output_rows:
db.add(
BizProcessRouteStepOutput(
id=generate_uuid(),
step_id=dst_step_id,
output_type_id=o.output_type_id,
output_name=o.output_name,
output_barcode=o.output_barcode,
tenant_no=tenant_no,
order_num=o.order_num,
remark=o.remark,
create_by=user_id,
create_dept_id=create_dept_id or "",
create_time=now,
update_by=user_id,
update_time=now,
del_flag=0,
)
)
dc_rows = (
db.query(BizProcessRouteStepDataCollection)
.filter(
BizProcessRouteStepDataCollection.step_id == src_step_id,
BizProcessRouteStepDataCollection.tenant_no == tenant_no,
BizProcessRouteStepDataCollection.del_flag == 0,
)
.all()
)
for d in dc_rows:
db.add(
BizProcessRouteStepDataCollection(
id=generate_uuid(),
step_id=dst_step_id,
collection_name=d.collection_name,
unit=d.unit,
tenant_no=tenant_no,
order_num=d.order_num,
remark=d.remark,
create_by=user_id,
create_dept_id=create_dept_id or "",
create_time=now,
update_by=user_id,
update_time=now,
del_flag=0,
)
)
def _source_steps_by_code(
db: Session, *, route_id: str, tenant_no: str
) -> Dict[str, BizProcessRouteStep]:
rows = (
db.query(BizProcessRouteStep)
.filter(
BizProcessRouteStep.route_id == route_id,
BizProcessRouteStep.tenant_no == tenant_no,
BizProcessRouteStep.del_flag == 0,
)
.all()
)
out: Dict[str, BizProcessRouteStep] = {}
for row in rows:
code = (row.process_code or "").strip()
if code and code not in out:
out[code] = row
return out
def ensure_uc_msc_builtin_template(
db: Session,
*,
tenant_no: str,
user_id: Optional[str] = None,
create_dept_id: str = "",
) -> Dict[str, Any]:
"""幂等创建 UC 5 步内置路线与任务组合;已存在则直接返回。"""
existing = get_uc_msc_builtin_set(db, tenant_no=tenant_no)
if existing and (existing.status or "1") == "1":
item = (
db.query(BizProductionTaskSetItem)
.filter(
BizProductionTaskSetItem.set_id == existing.id,
BizProductionTaskSetItem.tenant_no == tenant_no,
BizProductionTaskSetItem.del_flag == 0,
)
.order_by(
BizProductionTaskSetItem.order_num.asc(),
BizProductionTaskSetItem.create_time.asc(),
)
.first()
)
if item and item.route_id:
route = (
db.query(BizProcessRoute)
.filter(
BizProcessRoute.id == item.route_id,
BizProcessRoute.tenant_no == tenant_no,
BizProcessRoute.del_flag == 0,
)
.first()
)
step_count = (
db.query(BizProcessRouteStep.id)
.filter(
BizProcessRouteStep.route_id == item.route_id,
BizProcessRouteStep.tenant_no == tenant_no,
BizProcessRouteStep.del_flag == 0,
)
.count()
)
if route and step_count >= len(UC_MSC_STEP_ORDER):
return {
"created": False,
"setId": existing.id,
"setName": existing.set_name,
"routeId": route.id,
"routeCode": route.route_code,
"stepCount": step_count,
}
source = _find_source_route(db, tenant_no=tenant_no)
by_code = _source_steps_by_code(db, route_id=source.id, tenant_no=tenant_no)
missing = [c for c in UC_MSC_STEP_ORDER if c not in by_code]
if missing:
raise ValueError(
"源工艺路线缺少工序,无法创建 UC 模版:" + "、".join(missing)
)
now = _now()
route = (
db.query(BizProcessRoute)
.filter(
BizProcessRoute.tenant_no == tenant_no,
BizProcessRoute.route_code == UC_MSC_ROUTE_CODE,
BizProcessRoute.del_flag == 0,
)
.first()
)
if not route:
route = BizProcessRoute(
id=generate_uuid(),
route_code=UC_MSC_ROUTE_CODE,
route_name=UC_MSC_ROUTE_NAME,
product_type_id=source.product_type_id,
version=source.version,
is_current="0",
equipment_ids=source.equipment_ids,
equipment_name=source.equipment_name,
tenant_no=tenant_no,
order_num=0,
remark="内置模版:UC 入库编码自动派发(5 步,不含传代)",
is_builtin="1",
create_by=user_id,
create_dept_id=create_dept_id or "",
create_time=now,
update_by=user_id,
update_time=now,
del_flag=0,
)
db.add(route)
db.flush()
else:
route.route_name = UC_MSC_ROUTE_NAME
route.is_builtin = "1"
route.update_by = user_id
route.update_time = now
db.add(route)
# 重建步骤(幂等:软删旧步骤后按目标顺序插入)
old_steps = (
db.query(BizProcessRouteStep)
.filter(
BizProcessRouteStep.route_id == route.id,
BizProcessRouteStep.tenant_no == tenant_no,
BizProcessRouteStep.del_flag == 0,
)
.all()
)
for s in old_steps:
s.del_flag = 1
s.update_by = user_id
s.update_time = now
db.add(s)
db.flush()
for order, code in enumerate(UC_MSC_STEP_ORDER, start=1):
src = by_code[code]
new_step = BizProcessRouteStep(
id=generate_uuid(),
route_id=route.id,
process_id=src.process_id,
step_order=order,
process_code=src.process_code,
category_id=src.category_id,
process_name=src.process_name,
description=src.description,
equipment_ids=src.equipment_ids,
equipment_name=src.equipment_name,
estimated_duration=src.estimated_duration,
sop_ids=src.sop_ids,
sop_content=src.sop_content,
tenant_no=tenant_no,
order_num=order,
remark=src.remark,
create_by=user_id,
create_dept_id=create_dept_id or "",
create_time=now,
update_by=user_id,
update_time=now,
del_flag=0,
)
db.add(new_step)
db.flush()
_clone_step_children(
db,
src_step_id=src.id,
dst_step_id=new_step.id,
tenant_no=tenant_no,
user_id=user_id,
create_dept_id=create_dept_id or "",
now=now,
)
header = existing or BizProductionTaskSet(
id=generate_uuid(),
set_name=UC_MSC_BUILTIN_SET_NAME,
status="1",
tenant_no=tenant_no,
order_num=0,
remark="内置模版:UC 入库编码自动派发",
is_builtin="1",
create_by=user_id,
create_dept_id=create_dept_id or "",
create_time=now,
update_by=user_id,
update_time=now,
del_flag=0,
)
if existing:
header.status = "1"
header.is_builtin = "1"
header.update_by = user_id
header.update_time = now
db.add(header)
db.flush()
items = (
db.query(BizProductionTaskSetItem)
.filter(
BizProductionTaskSetItem.set_id == header.id,
BizProductionTaskSetItem.tenant_no == tenant_no,
BizProductionTaskSetItem.del_flag == 0,
)
.all()
)
for it in items:
it.del_flag = 1
it.update_by = user_id
it.update_time = now
db.add(it)
db.flush()
item = BizProductionTaskSetItem(
id=generate_uuid(),
set_id=header.id,
task_name="{lab_storage_code}样本处理",
route_id=route.id,
route_name=route.route_name,
description=UC_MSC_BUILTIN_SET_NAME,
remark=None,
tenant_no=tenant_no,
order_num=1,
create_by=user_id,
create_dept_id=create_dept_id or "",
create_time=now,
update_by=user_id,
update_time=now,
del_flag=0,
)
db.add(item)
db.flush()
return {
"created": True,
"setId": header.id,
"setName": header.set_name,
"routeId": route.id,
"routeCode": route.route_code,
"stepCount": len(UC_MSC_STEP_ORDER),
}
@@ -0,0 +1,19 @@
"""用户下拉选项:同部门优先排序等轻量辅助。"""
from __future__ import annotations
from typing import Any, Dict, List, Sequence
def prioritize_caller_dept_options(
options: Sequence[Dict[str, Any]],
caller_dept_id: str,
) -> List[Dict[str, Any]]:
"""稳定排序:当前登录用户同部门在前,其余保持原相对顺序。"""
items = list(options)
dept = (caller_dept_id or "").strip()
if not dept or not items:
return items
return sorted(
items,
key=lambda item: 0 if str(item.get("deptId") or "").strip() == dept else 1,
)
+1 -1
View File
@@ -246,7 +246,7 @@ def send_basic_experiment_delivery_remind(
time_text: str,
pagepath: str = "",
) -> dict:
"""基础实验:交付日前一天出库提醒。"""
"""临床科研:交付日前一天出库提醒。"""
data: Dict[str, Dict[str, str]] = {}
customer_key = (settings.WX_MP_TPL_BE_DELIVERY_FIELD_CUSTOMER or "").strip()
product_key = (settings.WX_MP_TPL_BE_DELIVERY_FIELD_PRODUCT or "").strip()
+12 -4
View File
@@ -2,12 +2,20 @@
from typing import List, Optional, Tuple
# 科研捐赠脐带间充质:UC… → 5 步原代培养模版(与细胞存储 BC 的 6 步模版分离)
UC_MSC_BUILTIN_SET_NAME = "脐带MSC原代培养(内置模版)"
BC_MSC_BUILTIN_SET_NAME = "干细胞培养(内置模版)"
HSC_BUILTIN_SET_NAME = "造血干样本处理(内置模版)"
UBMC_BUILTIN_SET_NAME = "UBMC冻存(内置模版)"
PBMC_BUILTIN_SET_NAME = "PBMC冻存(内置模版)"
# 最长前缀优先:BC 必须在 B 之前,避免 BC… 误匹配造血干
_LAB_CODE_BUILTIN_SET_RULES: List[Tuple[str, str]] = [
("UBMC", "UBMC冻存(内置模版)"),
("PBMC", "PBMC冻存(内置模版)"),
("BC", "干细胞培养(内置模版)"),
("B", "造血干样本处理(内置模版)"),
("UBMC", UBMC_BUILTIN_SET_NAME),
("PBMC", PBMC_BUILTIN_SET_NAME),
("UC", UC_MSC_BUILTIN_SET_NAME),
("BC", BC_MSC_BUILTIN_SET_NAME),
("B", HSC_BUILTIN_SET_NAME),
]
@@ -0,0 +1,252 @@
#!/usr/bin/env python3
"""为 UC 开头实验室入库编码的入库生产工单补派 5 步脐带MSC原代任务。
默认 dry-run;加 --apply 才写库。会先幂等确保内置模版存在。
用法(在 backend 目录、已配置可连目标库的 .env):
python -m scripts.backfill_uc_msc_production_tasks
python -m scripts.backfill_uc_msc_production_tasks --apply
python -m scripts.backfill_uc_msc_production_tasks --tenant zkxw --apply
等价一次性 SQL(与种子脚本分开):
docs/sql/migrations/2026-11-13-uc-msc-production-task-backfill.sql
"""
from __future__ import annotations
import argparse
import os
import sys
from typing import Any, Dict, List, Optional, Tuple
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from sqlalchemy import or_
from sqlalchemy.orm import Session
from app.core.database import SessionLocal
from app.crud import production_task_set as production_task_set_svc
from app.models.models import (
BizProductionTask,
BizProductionTaskSet,
BizProductionWorkOrder,
BizSampleReception,
)
from app.services.uc_msc_builtin_template import ensure_uc_msc_builtin_template
from app.utils.lab_storage_code_task_set import UC_MSC_BUILTIN_SET_NAME
def _list_candidate_work_orders(
db: Session, *, tenant_no: str
) -> List[Tuple[BizProductionWorkOrder, BizSampleReception]]:
"""UC 接收记录关联的入库工单,且当前无有效生产任务。"""
q = (
db.query(BizProductionWorkOrder, BizSampleReception)
.join(
BizSampleReception,
BizSampleReception.id == BizProductionWorkOrder.reception_id,
)
.filter(
BizProductionWorkOrder.tenant_no == tenant_no,
BizProductionWorkOrder.del_flag == 0,
BizProductionWorkOrder.work_order_type == "inbound",
BizProductionWorkOrder.work_order_status.in_(("dpz", "jxz")),
BizSampleReception.tenant_no == tenant_no,
BizSampleReception.del_flag == 0,
BizSampleReception.accept_conclusion == "js",
BizSampleReception.lab_storage_code.isnot(None),
BizSampleReception.lab_storage_code != "",
or_(
BizSampleReception.lab_storage_code.like("UC%"),
BizSampleReception.lab_storage_code.like("uc%"),
),
)
.order_by(BizSampleReception.reception_time.asc())
)
rows = q.all()
out: List[Tuple[BizProductionWorkOrder, BizSampleReception]] = []
for wo, rec in rows:
has_task = (
db.query(BizProductionTask.id)
.filter(
BizProductionTask.work_order_id == wo.id,
BizProductionTask.tenant_no == tenant_no,
BizProductionTask.del_flag == 0,
)
.first()
)
if has_task:
continue
code = (rec.lab_storage_code or "").strip().upper()
if not code.startswith("UC"):
continue
out.append((wo, rec))
return out
def _dispatch_one(
db: Session,
*,
tenant_no: str,
user_id: Optional[str],
create_dept_id: str,
wo: BizProductionWorkOrder,
rec: BizSampleReception,
set_id: str,
) -> Dict[str, Any]:
result = production_task_set_svc.create_tasks_from_set(
db,
tenant_no=tenant_no,
user_id=user_id,
create_dept_id=create_dept_id or "",
work_order_id=wo.id,
set_id=set_id,
)
return {
"workOrderId": wo.id,
"workOrderNo": wo.work_order_no,
"sampleCode": wo.sample_code or rec.sample_code,
"labStorageCode": rec.lab_storage_code,
"createdCount": result.get("createdCount"),
"tasks": [
{"id": t.get("id"), "taskName": t.get("taskName"), "routeId": t.get("routeId")}
for t in (result.get("list") or [])
],
}
def run(
*,
tenant_no: str,
apply: bool,
user_id: Optional[str],
create_dept_id: str,
) -> Dict[str, Any]:
db = SessionLocal()
try:
ensure_info = ensure_uc_msc_builtin_template(
db,
tenant_no=tenant_no,
user_id=user_id,
create_dept_id=create_dept_id,
)
set_row = (
db.query(BizProductionTaskSet)
.filter(
BizProductionTaskSet.tenant_no == tenant_no,
BizProductionTaskSet.set_name == UC_MSC_BUILTIN_SET_NAME,
BizProductionTaskSet.is_builtin == "1",
BizProductionTaskSet.status == "1",
BizProductionTaskSet.del_flag == 0,
)
.first()
)
if not set_row:
raise RuntimeError("UC 内置任务组合创建失败")
candidates = _list_candidate_work_orders(db, tenant_no=tenant_no)
preview = [
{
"workOrderId": wo.id,
"workOrderNo": wo.work_order_no,
"workOrderStatus": wo.work_order_status,
"sampleCode": wo.sample_code or rec.sample_code,
"labStorageCode": rec.lab_storage_code,
"receptionId": rec.id,
"receptionTime": str(rec.reception_time) if rec.reception_time else None,
}
for wo, rec in candidates
]
if not apply:
db.rollback()
return {
"dryRun": True,
"template": ensure_info,
"candidateCount": len(preview),
"candidates": preview,
"message": "dry-run:未写库。确认后加 --apply 执行补派。",
}
dispatched: List[Dict[str, Any]] = []
errors: List[Dict[str, Any]] = []
for wo, rec in candidates:
try:
dispatched.append(
_dispatch_one(
db,
tenant_no=tenant_no,
user_id=user_id,
create_dept_id=create_dept_id,
wo=wo,
rec=rec,
set_id=set_row.id,
)
)
except Exception as exc: # noqa: BLE001 - 汇总后继续
errors.append(
{
"workOrderId": wo.id,
"workOrderNo": wo.work_order_no,
"labStorageCode": rec.lab_storage_code,
"error": str(exc),
}
)
db.commit()
return {
"dryRun": False,
"template": ensure_info,
"candidateCount": len(preview),
"dispatchedCount": len(dispatched),
"dispatched": dispatched,
"errorCount": len(errors),
"errors": errors,
}
except Exception:
db.rollback()
raise
finally:
db.close()
def main(argv: Optional[List[str]] = None) -> int:
parser = argparse.ArgumentParser(
description="回补 UC 入库编码生产工单的 5 步脐带MSC原代任务"
)
parser.add_argument(
"--tenant",
default="zkxw",
help="租户编号,默认 zkxw",
)
parser.add_argument(
"--apply",
action="store_true",
help="实际写库;默认仅 dry-run",
)
parser.add_argument(
"--user-id",
default=None,
help="写库 create_by/update_by,可选",
)
parser.add_argument(
"--create-dept-id",
default="",
help="写库 create_dept_id,可选",
)
args = parser.parse_args(argv)
result = run(
tenant_no=(args.tenant or "zkxw").strip() or "zkxw",
apply=bool(args.apply),
user_id=(args.user_id or None),
create_dept_id=(args.create_dept_id or ""),
)
import json
print(json.dumps(result, ensure_ascii=False, indent=2, default=str))
if result.get("errorCount"):
return 2
return 0
if __name__ == "__main__":
raise SystemExit(main())
@@ -0,0 +1,30 @@
"""恢复被误软删的 Excel 补充字段(真菌/内毒素/CD34 等)并同步旧台账。
用法:
ENV_FILE=.../backend/.env python backend/scripts/restore_lab_sample_processing_excel_extras.py
"""
from __future__ import annotations
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
BACKEND = ROOT / "backend"
if str(BACKEND) not in sys.path:
sys.path.insert(0, str(BACKEND))
from app.core.database import SessionLocal # noqa: E402
from app.services.lab_sample_processing import restore_retired_excel_extras # noqa: E402
def main() -> None:
db = SessionLocal()
try:
result = restore_retired_excel_extras(db, tenant_no="zkxw")
print(result)
finally:
db.close()
if __name__ == "__main__":
main()
@@ -0,0 +1,140 @@
"""一次性造数:临床科研 / 委托加工申请单各 5 条(本地开发用)。
用法(工程 backend 目录):
.\\venv\\Scripts\\python.exe scripts\\seed_research_like_applications.py
"""
from __future__ import annotations
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
from app.core.database import SessionLocal # noqa: E402
from app.crud import pilot_application as crud # noqa: E402
from app.models.models import SysUser # noqa: E402
from app.models.project_management import Project # noqa: E402
TENANT = "zkxw"
COUNT = 5
CLINICAL_CATEGORIES = [
"bio_tech_clinical",
"joint_topic_declare",
"bio_pharma_rd",
"bio_tech_clinical",
"joint_topic_declare",
]
CONTRACT_CATEGORIES = ["msc", "nk", "placenta_freeze_dried", "adipose_exosome", "msc"]
def _pick_admin(db) -> tuple[str, str]:
row = (
db.query(SysUser)
.filter(SysUser.tenant_no == TENANT, SysUser.del_flag == 0, SysUser.status == "1")
.order_by(SysUser.create_time.asc())
.first()
)
if not row:
raise SystemExit("未找到可用用户")
return row.id, row.dept_id or ""
def _pick_projects(db, need: int) -> list[Project]:
rows = (
db.query(Project)
.filter(
Project.tenant_no == TENANT,
Project.del_flag == 0,
Project.leader_user_id.isnot(None),
Project.leader_user_id != "",
)
.order_by(Project.create_time.desc())
.limit(max(need, 20))
.all()
)
rows = [p for p in rows if (p.leader_user_id or "").strip()]
if not rows:
raise SystemExit("未找到已设置项目负责人的项目,请先在项目管理中维护")
# 循环复用
out: list[Project] = []
i = 0
while len(out) < need:
out.append(rows[i % len(rows)])
i += 1
return out
def _seed_one(
db,
*,
biz_type: str,
idx: int,
project: Project,
user_id: str,
dept_id: str,
category: str,
) -> dict:
label = "临床科研" if biz_type == "basic_experiment" else "委托加工"
data = {
"bizType": biz_type,
"projectId": project.id,
"researchCategory": category,
"projectTitle": f"种子{label}课题{idx:02d}",
"customerName": f"种子客户{label}{idx:02d}",
"customerContact": f"联系人{idx}",
"customerPhone": f"1380000{idx:04d}",
"applicationName": f"种子{label}申请单{idx:02d}",
"remark": "seed-script-2026-11-27",
}
return crud.create_application(
db, data=data, tenant_no=TENANT, user_id=user_id, dept_id=dept_id
)
def main() -> None:
db = SessionLocal()
try:
user_id, dept_id = _pick_admin(db)
projects = _pick_projects(db, COUNT * 2)
created = []
for i in range(COUNT):
created.append(
_seed_one(
db,
biz_type="basic_experiment",
idx=i + 1,
project=projects[i],
user_id=user_id,
dept_id=dept_id,
category=CLINICAL_CATEGORIES[i],
)
)
for i in range(COUNT):
created.append(
_seed_one(
db,
biz_type="contract_processing",
idx=i + 1,
project=projects[COUNT + i],
user_id=user_id,
dept_id=dept_id,
category=CONTRACT_CATEGORIES[i],
)
)
print(f"created={len(created)}")
for row in created:
print(
f"{row.get('bizType')}\t{row.get('applicationNo')}\t"
f"{row.get('projectTitle')}\t{row.get('approvalStatus')}\t"
f"project={row.get('projectName') or row.get('projectId')}"
)
finally:
db.close()
if __name__ == "__main__":
main()
@@ -1,4 +1,4 @@
"""基础实验申请单与售卖计划批量创建"""
"""临床科研申请单与售卖计划批量创建"""
import unittest
from unittest.mock import MagicMock, patch
@@ -18,9 +18,9 @@ class TestBasicExperimentApplicationNo(unittest.TestCase):
result = crud._generate_application_no(db, "zkxw", biz_type="basic_experiment")
self.assertTrue(result.startswith("JCSY"))
self.assertNotIn("JCSQ", result)
self.assertEqual(result, "JCSY202606100001")
self.assertTrue(result.startswith("LCKY"))
self.assertNotIn("JCSY", result)
self.assertEqual(result, "LCKY202606100001")
class TestBasicExperimentCreateValidation(unittest.TestCase):
@@ -28,6 +28,8 @@ class TestBasicExperimentCreateValidation(unittest.TestCase):
db = MagicMock()
data = {
"bizType": "basic_experiment",
"researchCategory": "bio_tech_clinical",
"channelId": "ch-1",
"projectTitle": "课题A",
"customerName": "",
"customerContact": "张三",
@@ -43,6 +45,47 @@ class TestBasicExperimentCreateValidation(unittest.TestCase):
)
self.assertIn("客户名称", str(ctx.exception))
def test_create_basic_experiment_requires_research_category(self):
db = MagicMock()
data = {
"bizType": "basic_experiment",
"channelId": "ch-1",
"projectTitle": "课题A",
"customerName": "客户A",
"customerContact": "张三",
"customerPhone": "13800000000",
}
with self.assertRaises(ValueError) as ctx:
crud.create_application(
db,
data=data,
tenant_no="zkxw",
user_id="user-1",
dept_id="dept-1",
)
self.assertIn("业务类型", str(ctx.exception))
def test_create_basic_experiment_allows_missing_channel(self):
"""临床科研申请单不再要求渠道;缺项目负责人时仍会失败。"""
db = MagicMock()
data = {
"bizType": "basic_experiment",
"researchCategory": "bio_tech_clinical",
"projectTitle": "课题A",
"customerName": "客户A",
"customerContact": "张三",
"customerPhone": "13800000000",
}
with self.assertRaises(ValueError) as ctx:
crud.create_application(
db,
data=data,
tenant_no="zkxw",
user_id="user-1",
dept_id="dept-1",
)
self.assertNotIn("渠道", str(ctx.exception))
class TestBasicExperimentSaleSchedules(unittest.TestCase):
@patch("app.crud.pilot_application.create_schedule")
@@ -1,4 +1,4 @@
"""基础实验交付日前一天服务号提醒单测。"""
"""临床科研交付日前一天服务号提醒单测。"""
from datetime import date, datetime
from unittest.mock import MagicMock, patch
+211
View File
@@ -0,0 +1,211 @@
"""人工样本废弃:写状态/原因,全作废则协议作废,不联动接收。"""
from __future__ import annotations
import unittest
from datetime import datetime
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from app.core.database import Base
from app.models.models import (
BizCollectionProtocol,
BizProtocolSample,
BizProtocolStatusChange,
BizSampleReception,
SysDictData,
)
from app.services.protocol_reception_discard_sync import (
LAB_VOID_TYPE_CODE,
SAMPLE_VOID_STATUS,
void_sample_manually,
)
def _session():
engine = create_engine("sqlite://")
Base.metadata.create_all(
bind=engine,
tables=[
SysDictData.__table__,
BizCollectionProtocol.__table__,
BizProtocolSample.__table__,
BizProtocolStatusChange.__table__,
BizSampleReception.__table__,
],
)
return sessionmaker(bind=engine)()
def _now():
return datetime(2026, 11, 19, 12, 0, 0)
class TestBusinessSampleVoid(unittest.TestCase):
def test_void_one_sample_keeps_protocol_and_skips_reception(self):
db = _session()
now = _now()
db.add(
BizCollectionProtocol(
id="p1",
protocol_no="CP-1",
protocol_status="sxz",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
db.add(
BizProtocolSample(
id="sa",
collection_protocol_id="p1",
sample_code="A001",
sample_status="ycj",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
db.add(
BizProtocolSample(
id="sb",
collection_protocol_id="p1",
sample_code="B001",
sample_status="ycj",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
db.add(
BizSampleReception(
id="ra",
protocol_sample_id="sa",
collection_protocol_id="p1",
reception_time=now,
accept_conclusion="js",
reception_source="cell_storage",
sample_code="A001",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
check_packaging=0,
check_sealing=0,
check_no_damage=0,
check_no_leakage=0,
check_color=0,
check_tying_rope=0,
check_no_stratification=0,
)
)
db.commit()
void_sample_manually(
db,
source="cell_storage",
tenant_no="tenant-a",
void_desc="质检发现污染",
user_id="u1",
sample_id="sa",
)
a = db.query(BizProtocolSample).filter(BizProtocolSample.id == "sa").one()
b = db.query(BizProtocolSample).filter(BizProtocolSample.id == "sb").one()
proto = db.query(BizCollectionProtocol).filter(BizCollectionProtocol.id == "p1").one()
rec = db.query(BizSampleReception).filter(BizSampleReception.id == "ra").one()
self.assertEqual(a.sample_status, SAMPLE_VOID_STATUS)
self.assertEqual(a.void_desc, "质检发现污染")
self.assertTrue((a.void_date or "").strip())
self.assertEqual(b.sample_status, "ycj")
self.assertEqual(proto.protocol_status, "sxz")
self.assertEqual(rec.accept_conclusion, "js")
def test_void_all_samples_auto_voids_protocol_without_reception_change(self):
db = _session()
now = _now()
db.add(
BizCollectionProtocol(
id="p2",
protocol_no="CP-2",
protocol_status="sxz",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
for sid, code in (("s1", "C001"), ("s2", "C002")):
db.add(
BizProtocolSample(
id=sid,
collection_protocol_id="p2",
sample_code=code,
sample_status="ycj",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
db.add(
BizSampleReception(
id="r1",
protocol_sample_id="s1",
collection_protocol_id="p2",
reception_time=now,
accept_conclusion="js",
reception_source="cell_storage",
sample_code="C001",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
check_packaging=0,
check_sealing=0,
check_no_damage=0,
check_no_leakage=0,
check_color=0,
check_tying_rope=0,
check_no_stratification=0,
)
)
db.commit()
void_sample_manually(
db,
source="cell_storage",
tenant_no="tenant-a",
void_desc="原因1",
sample_id="s1",
commit=True,
)
void_sample_manually(
db,
source="cell_storage",
tenant_no="tenant-a",
void_desc="原因2",
sample_id="s2",
commit=True,
)
proto = db.query(BizCollectionProtocol).filter(BizCollectionProtocol.id == "p2").one()
rec = db.query(BizSampleReception).filter(BizSampleReception.id == "r1").one()
self.assertEqual(proto.protocol_status, "yzf")
self.assertEqual(proto.void_type, LAB_VOID_TYPE_CODE)
self.assertEqual(rec.accept_conclusion, "js")
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,81 @@
"""委托加工申请单:编号前缀、业务子类型校验、复用临床科研创建校验。"""
import unittest
from unittest.mock import MagicMock, patch
from app.constants.research_category import validate_research_category
from app.crud import pilot_application as crud
class TestContractProcessingApplicationNo(unittest.TestCase):
@patch("app.crud.pilot_application.datetime")
def test_generate_application_no_contract_processing_prefix(self, mock_dt):
mock_dt.now.return_value.strftime.return_value = "20261123"
db = MagicMock()
mock_query = MagicMock()
db.query.return_value = mock_query
mock_query.filter.return_value = mock_query
mock_query.order_by.return_value = mock_query
mock_query.first.return_value = None
result = crud._generate_application_no(db, "zkxw", biz_type="contract_processing")
self.assertEqual(result, "WTJG202611230001")
class TestContractProcessingResearchCategory(unittest.TestCase):
def test_fixed_categories(self):
self.assertEqual(
validate_research_category("placenta_freeze_dried", required=True, biz_type="contract_processing"),
"placenta_freeze_dried",
)
self.assertEqual(
validate_research_category("nk", required=True, biz_type="contract_processing"),
"nk",
)
def test_custom_other_text(self):
self.assertEqual(
validate_research_category("自定义产品A", required=True, biz_type="contract_processing"),
"自定义产品A",
)
def test_clinical_codes_rejected_for_contract_processing(self):
with self.assertRaises(ValueError):
validate_research_category(
"bio_tech_clinical", required=True, biz_type="contract_processing"
)
def test_clinical_still_uses_legacy_codes(self):
self.assertEqual(
validate_research_category("bio_tech_clinical", required=True, biz_type="basic_experiment"),
"bio_tech_clinical",
)
with self.assertRaises(ValueError):
validate_research_category("nk", required=True, biz_type="basic_experiment")
class TestContractProcessingCreateValidation(unittest.TestCase):
def test_create_requires_customer_fields(self):
db = MagicMock()
data = {
"bizType": "contract_processing",
"researchCategory": "msc",
"channelId": "ch-1",
"projectTitle": "课题A",
"customerName": "",
"customerContact": "张三",
"customerPhone": "13800000000",
}
with self.assertRaises(ValueError) as ctx:
crud.create_application(
db,
data=data,
tenant_no="zkxw",
user_id="user-1",
dept_id="dept-1",
)
self.assertIn("客户名称", str(ctx.exception))
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,62 @@
"""委托加工自定义业务类型 CRUD"""
import unittest
from unittest.mock import MagicMock, patch
from app.crud import contract_processing_category as crud
class TestContractProcessingCategoryValidation(unittest.TestCase):
def test_reject_reserved_fixed_code(self):
with self.assertRaises(ValueError) as ctx:
crud._assert_valid_name("nk")
self.assertIn("预置", str(ctx.exception))
def test_reject_reserved_fixed_label(self):
with self.assertRaises(ValueError) as ctx:
crud._assert_valid_name("胎盘冻干粉")
self.assertIn("预置", str(ctx.exception))
def test_reject_empty(self):
with self.assertRaises(ValueError):
crud._assert_valid_name(" ")
def test_accept_custom(self):
self.assertEqual(crud._assert_valid_name(" 外泌体定制A "), "外泌体定制A")
class TestContractProcessingCategoryCreate(unittest.TestCase):
@patch("app.crud.contract_processing_category._exists_name", return_value=False)
@patch("app.crud.contract_processing_category.generate_uuid", return_value="cat-1")
def test_create_ok(self, _uuid, _exists):
db = MagicMock()
obj = crud.create_category(
db,
category_name="定制产品B",
tenant_no="zkxw",
biz_type="contract_processing",
user_id="u1",
commit=False,
)
self.assertEqual(obj.category_name, "定制产品B")
self.assertEqual(obj.biz_type, "contract_processing")
db.add.assert_called()
db.flush.assert_called()
@patch("app.crud.contract_processing_category._exists_name", return_value=False)
@patch("app.crud.contract_processing_category.generate_uuid", return_value="cat-bex")
def test_create_basic_experiment_ok(self, _uuid, _exists):
db = MagicMock()
obj = crud.create_category(
db,
category_name="定制科研课题A",
tenant_no="zkxw",
biz_type="basic_experiment",
user_id="u1",
commit=False,
)
self.assertEqual(obj.biz_type, "basic_experiment")
self.assertEqual(obj.category_name, "定制科研课题A")
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,53 @@
"""市场下「中试服务」已从静态菜单树下线(Issue #158)。"""
import ast
import re
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
MENU_PY = ROOT / "backend/app/api/menu.py"
SQXP_TS = ROOT / "web-admin/src/router/modules/sqxp.ts"
HIDE_SQL = ROOT / "docs/sql/migrations/2026-11-20-hide-market-pilot-service-menus.sql"
def _market_children_titles_from_menu_py() -> list[str]:
source = MENU_PY.read_text(encoding="utf-8")
tree_match = re.search(r"STATIC_MENU_TREE\s*=\s*(\[[\s\S]*?\n\])\s*\n", source)
assert tree_match, "STATIC_MENU_TREE not found"
tree = ast.literal_eval(tree_match.group(1))
market = next(
node
for node in tree
if isinstance(node, dict) and (node.get("meta") or {}).get("menuCode") == "menu:market"
)
titles = []
for child in market.get("children") or []:
meta = child.get("meta") or {}
titles.append(str(meta.get("title") or ""))
return titles
def test_backend_static_menu_has_no_market_pilot_service():
titles = _market_children_titles_from_menu_py()
assert "中试服务" not in titles
assert "中试服务申请单" not in titles
def test_frontend_sqxp_has_no_market_pilot_service_block():
text = SQXP_TS.read_text(encoding="utf-8")
assert "name: 'PilotService'" not in text
assert "id: 'PIL00000000000000000000000000001'" not in text
assert "pilot-service:pilot-application:list" not in text
# 基础实验 / 临床仍可复用出库放行组件与权限码前缀
assert "basic-experiment:outbound-release-review:list" in text
assert "clinical-application:outbound-release-review:list" in text
def test_hide_sql_soft_deletes_sys_menu_only_under_market_pilot():
sql = HIDE_SQL.read_text(encoding="utf-8")
compact = re.sub(r"\s+", " ", re.sub(r"--[^\n]*", "", sql))
assert re.search(r"UPDATE\s+sys_menu", compact, re.IGNORECASE)
assert re.search(r"SET\s+m\.del_flag\s*=\s*1", compact, re.IGNORECASE)
assert "menu:market" in compact
assert "中试服务" in compact
assert not re.search(r"DELETE\s+FROM\s+sys_menu", compact, re.IGNORECASE)
+61
View File
@@ -3,6 +3,7 @@ from __future__ import annotations
import unittest
from datetime import datetime
from types import SimpleNamespace
from app.services.lab_sample_process import (
format_cn_datetime,
@@ -38,5 +39,65 @@ class LabSampleProcessServiceTests(unittest.TestCase):
self.assertEqual(merged["motherName"], "张三")
class LabSampleProcessRowStatusTests(unittest.TestCase):
def test_cell_and_donation_rows_expose_sample_status(self):
from app.crud.lab_sample_process import (
_build_cell_system,
_build_donation_system,
)
rec = SimpleNamespace(
id="r1",
sample_code="S1",
lab_storage_code="B0000108",
reception_time=None,
receive_temperature="",
handler_name="",
remark="",
create_time=None,
)
sample = SimpleNamespace(
sample_code="S1",
sample_status="yrk",
void_desc="",
)
voided = SimpleNamespace(
sample_code="S2",
sample_status="yzf",
void_desc="溶血",
)
cell = _build_cell_system(
tab_key="cell_hsc",
rec=rec,
sample=sample,
party=None,
coll=None,
protocol=None,
prod={},
hospital_name="",
check_flags={},
storage_status="已入库",
qc_mother={},
qc_process={},
)
self.assertEqual(cell["sampleStatus"], "yrk")
self.assertEqual(cell["voidDesc"], "")
self.assertEqual(cell["cellCode"], "B0000108")
donation = _build_donation_system(
tab_key="donation_hsc",
rec=rec,
sample=voided,
party=None,
coll=None,
prod={},
storage_status="",
qc_mother={},
qc_process={},
)
self.assertEqual(donation["sampleStatus"], "yzf")
self.assertEqual(donation["voidDesc"], "溶血")
if __name__ == "__main__":
unittest.main()
+177
View File
@@ -48,6 +48,183 @@ class LabSampleProcessingFieldsTest(unittest.TestCase):
self.assertEqual(fmap["cd34Count"].dept, DEPT_QC)
self.assertEqual(fmap["originalBloodWeightG"].dept, DEPT_PRODUCTION)
def test_source_fields_not_overridden_by_extra(self):
from datetime import datetime
from app.services.lab_sample_processing import _build_row
from types import SimpleNamespace
sample = SimpleNamespace(id="S1", sample_code="ZKZX34000865", collection_protocol_id="P1")
party = SimpleNamespace(mother_name="真实妈妈")
coll = SimpleNamespace(
sample_collect_time=None,
maternal_blood_collect_time=datetime(2026, 11, 4, 5, 20),
)
hospital = SimpleNamespace(hospital_name="真实医院")
protocol = SimpleNamespace(
consent_form_urls="protocol-consent/a",
health_survey_form_urls="",
)
reception = SimpleNamespace(
id="R1",
reception_time=None,
receive_temperature=None,
handler_name="接收人",
remark=None,
lab_storage_code="B0000103",
)
production = SimpleNamespace(
id="PR1",
original_blood_weight_g=72.08,
hes_volume_ml=None,
blood_type="B",
infectious_four_test_result="zc",
enriched_blood_weight_g=None,
cryopreservation_volume_ml=None,
handler_name="操作人",
remark=None,
original_blood_volume_ml=None,
nucleated_cell_count_1e8=None,
inoculation_amount=None,
cryopreservation_time=None,
storage_total_tubes=None,
available_cell_count_1e7=None,
)
row = _build_row(
dataset=DATASET_HSC,
sample=sample,
type_name="围产期造血干细胞",
party=party,
coll=coll,
hospital=hospital,
reception=reception,
production=production,
extra={
"motherName": "Excel妈妈",
"originalBloodWeightG": 1,
"cd34Count": "11.4",
},
protocol=protocol,
check_flags={
"健康调查表": True,
"样本信息正确,标识清晰": True,
"针路密闭": True,
"容器无破损": True,
},
)
self.assertEqual(row["sampleCode"], "B0000103")
self.assertEqual(row["protocolSampleCode"], "ZKZX34000865")
self.assertEqual(row["motherName"], "真实妈妈")
self.assertEqual(row["originalBloodWeightG"], 72.08)
self.assertEqual(row["bloodType"], "B")
self.assertEqual(row["cd34Count"], "11.4")
self.assertEqual(row["hasMaternalBlood"], "是")
self.assertEqual(row["hasConsent"], "是")
self.assertEqual(row["hasHealthSurvey"], "是")
self.assertEqual(row["labelClear"], "是")
self.assertEqual(row["infectiousFourCard"], "正常")
self.assertIn("针路密闭", row["receiveCheck"] or "")
self.assertFalse(row["fromExtraOnly"])
def test_infectious_code_roundtrip(self):
from app.services.lab_sample_processing import _infectious_code, _infectious_label
self.assertEqual(_infectious_label("zc"), "正常")
self.assertEqual(_infectious_label("bzc"), "不正常")
self.assertEqual(_infectious_code("正常"), "zc")
self.assertEqual(_infectious_code("不正常"), "bzc")
def test_extra_field_keys_include_fungus(self):
from app.services.lab_sample_processing import _extra_field_keys
keys = _extra_field_keys(DATASET_MSC)
self.assertIn("fungusTest", keys)
self.assertIn("endotoxinTest", keys)
self.assertIn("bacteriaTest", keys)
self.assertIn("mycoplasmaTest", keys)
def test_msc_donation_collect_and_transport_fallback(self):
from datetime import datetime
from app.services.lab_sample_processing import _build_row
from types import SimpleNamespace
sample = SimpleNamespace(id="D1", sample_code="KYJZ1", collection_protocol_id=None)
party = SimpleNamespace(mother_name="孙玲")
coll = SimpleNamespace(
sample_collect_time=datetime(2026, 10, 10, 10, 5),
maternal_blood_collect_time=None,
)
reception = SimpleNamespace(
id="R1",
reception_time=datetime(2026, 10, 10, 15, 40, 57),
receive_temperature="23.1",
handler_name="侯以婷",
remark=None,
lab_storage_code="UC2026006",
)
row = _build_row(
dataset=DATASET_MSC,
sample=sample,
type_name="脐带间充质干细胞",
party=party,
coll=coll,
hospital=None,
reception=reception,
production=None,
extra={},
)
self.assertEqual(row["sampleCode"], "UC2026006")
self.assertEqual(row["collectTime"], "2026-10-10 10:05:00")
self.assertEqual(row["transportTempC"], "23.1")
self.assertNotIn("导出自存", row["motherName"] or "")
def test_legacy_supplement_fills_empty_source_fields(self):
from app.services.lab_sample_processing import _build_row, _merge_extra_with_legacy
from types import SimpleNamespace
extra = _merge_extra_with_legacy(
{},
{"infectiousFourTestLabel": "正常", "labMaterialCode": "202611006"},
)
sample = SimpleNamespace(id="S1", sample_code="UBMC202611006", collection_protocol_id=None)
reception = SimpleNamespace(
id="R1",
reception_time=None,
receive_temperature=None,
handler_name=None,
remark=None,
lab_storage_code="UBMC202611006",
)
production = SimpleNamespace(
id="PR1",
original_blood_weight_g=None,
hes_volume_ml=None,
blood_type=None,
infectious_four_test_result=None,
enriched_blood_weight_g=None,
cryopreservation_volume_ml=None,
handler_name=None,
remark=None,
original_blood_volume_ml=None,
nucleated_cell_count_1e8=None,
inoculation_amount=None,
cryopreservation_time=None,
storage_total_tubes=None,
available_cell_count_1e7=None,
)
row = _build_row(
dataset=DATASET_UBMC,
sample=sample,
type_name="脐血单个核细胞",
party=None,
coll=None,
hospital=None,
reception=reception,
production=production,
extra=extra,
)
self.assertEqual(row["infectiousFourCard"], "正常")
self.assertEqual(row["labMaterialCode"], "202611006")
if __name__ == "__main__":
unittest.main()
@@ -1,19 +1,36 @@
import unittest
from app.utils.lab_storage_code_task_set import match_builtin_task_set_name_by_lab_storage_code
from app.utils.lab_storage_code_task_set import (
BC_MSC_BUILTIN_SET_NAME,
HSC_BUILTIN_SET_NAME,
UC_MSC_BUILTIN_SET_NAME,
match_builtin_task_set_name_by_lab_storage_code,
)
class TestMatchBuiltinTaskSetName(unittest.TestCase):
def test_bc_before_b(self):
self.assertEqual(
match_builtin_task_set_name_by_lab_storage_code("BC20260101"),
"干细胞培养(内置模版)",
BC_MSC_BUILTIN_SET_NAME,
)
def test_b_only(self):
self.assertEqual(
match_builtin_task_set_name_by_lab_storage_code("B20260101"),
"造血干样本处理(内置模版)",
HSC_BUILTIN_SET_NAME,
)
def test_uc_msc(self):
self.assertEqual(
match_builtin_task_set_name_by_lab_storage_code("UC2026010"),
UC_MSC_BUILTIN_SET_NAME,
)
def test_uc_case_insensitive(self):
self.assertEqual(
match_builtin_task_set_name_by_lab_storage_code("uc2026016"),
UC_MSC_BUILTIN_SET_NAME,
)
def test_ubmc(self):
@@ -35,7 +52,7 @@ class TestMatchBuiltinTaskSetName(unittest.TestCase):
def test_bc_case_insensitive(self):
self.assertEqual(
match_builtin_task_set_name_by_lab_storage_code("bc99"),
"干细胞培养(内置模版)",
BC_MSC_BUILTIN_SET_NAME,
)
@@ -99,12 +99,20 @@ def test_specialist_sees_shared_batch_but_only_own_items_and_count():
from app.services.market_freight import get_freight_detail, list_freights
db = _session()
own, own_parent = _sample(db, 'own')
own.sample_status = 'yzf'
own.void_desc = '冷链中断'
db.commit()
other, other_parent = _sample(db, 'other', sales='u2')
freight = _freight(db, 'mixed', [('cell_storage', own, own_parent), ('cell_storage', other, other_parent)])
rows, total = list_freights(db, ctx=_ctx(), user_info=_user(), include_items=True)
detail = get_freight_detail(db, freight.id, ctx=_ctx(), user_info=_user())
assert total == 1 and rows[0]['visibleItemCount'] == 1
assert [item['sampleCode'] for item in rows[0]['items']] == ['C-own']
assert rows[0]['items'][0]['sampleStatus'] == 'yzf'
assert rows[0]['items'][0]['sampleStatusLabel'] == '已作废'
assert rows[0]['items'][0]['voidDesc'] == '冷链中断'
assert detail['items'][0]['sampleStatus'] == 'yzf'
assert detail['items'][0]['voidDesc'] == '冷链中断'
assert [item['sampleCode'] for item in detail['items']] == ['C-own']
assert rows[0]['createBy'] == detail['createBy'] == 'u1'
assert rows[0]['createByName'] == detail['createByName'] == '专员'
+27
View File
@@ -674,6 +674,33 @@ def test_chase_filters_counts_orders_and_pages_in_sql_before_materialization():
)
def test_payment_and_chase_lists_include_sample_status_when_coded():
from app.services.market_payment import list_payment_chase, list_payments
db = _session()
today = date(2026, 10, 11)
_payment_tree(db, 'void-sample', due_date=today.strftime('%Y%m%d'))
sample = db.get(BizProtocolSample, 'sample-void-sample')
sample.sample_status = 'yzf'
sample.void_desc = '客户放弃'
db.commit()
payments, payment_total = list_payments(db, ctx=_ctx(), user_info=_user())
chase, chase_total = list_payment_chase(
db, ctx=_ctx(), user_info=_user(), today=today
)
assert payment_total == 1
assert payments[0]['sampleCode'] == 'S-void-sample'
assert payments[0]['sampleStatus'] == 'yzf'
assert payments[0]['sampleStatusLabel'] == '已作废'
assert payments[0]['voidDesc'] == '客户放弃'
assert chase_total == 1
assert chase[0]['sampleStatus'] == 'yzf'
assert chase[0]['sampleStatusLabel'] == '已作废'
assert chase[0]['voidDesc'] == '客户放弃'
def test_payment_list_includes_legacy_models_and_uses_parent_scope_not_transfer_department():
from app.services.market_payment import list_payments
+52
View File
@@ -3604,6 +3604,10 @@ def test_protocol_list_contains_mobile_card_fields():
assert items[0]['deliveryMode'] == 'sc'
assert items[0]['newbornWeightGram'] == 3200
assert items[0]['salesUserName'] == '当前用户'
assert items[0]['sampleStatus'] == ''
assert items[0]['sampleStatusLabel'] == ''
assert items[0]['sampleVoidDesc'] == ''
assert items[0]['voidDesc'] == ''
by_customer, customer_total = list_protocols(
db, ctx=_ctx('specialist'), user_info=_user(), keyword='李安然'
@@ -3626,6 +3630,54 @@ def test_protocol_list_contains_mobile_card_fields():
} == {row.id}
def test_protocol_list_returns_sample_status_without_replacing_donation_void_desc():
from app.services.market_protocol import list_protocols
db = _session()
cell = _cell(db, 'status-cell')
db.add(
BizProtocolSample(
id='sample-status-cell',
collection_protocol_id=cell.id,
sample_code='S-CELL',
sample_status='yzf',
void_desc='试管破裂',
tenant_no='tenant-a',
create_dept_id='',
del_flag=0,
)
)
donation = _donation(db, 'status-don')
donation.void_desc = '协议作废说明'
db.add(
BizResearchDonationSample(
id='sample-status-don',
research_donation_id=donation.id,
sample_code='S-DON',
sample_status='yrk',
void_desc='样本溶血',
tenant_no='tenant-a',
create_dept_id='',
del_flag=0,
)
)
db.commit()
items, total = list_protocols(db, ctx=_ctx('specialist'), user_info=_user())
assert total == 2
by_id = {item['id']: item for item in items}
assert by_id['status-cell']['sampleCode'] == 'S-CELL'
assert by_id['status-cell']['sampleStatus'] == 'yzf'
assert by_id['status-cell']['sampleStatusLabel'] == '已作废'
assert by_id['status-cell']['voidDesc'] == '试管破裂'
assert by_id['status-cell']['sampleVoidDesc'] == '试管破裂'
assert by_id['status-don']['sampleStatus'] == 'yrk'
assert by_id['status-don']['sampleStatusLabel'] == '已入库'
assert by_id['status-don']['voidDesc'] == '协议作废说明'
assert by_id['status-don']['sampleVoidDesc'] == '样本溶血'
@pytest.mark.parametrize('source', ['cell_storage', 'research_donation'])
def test_protocol_list_and_detail_resolve_tenant_void_type_label(source):
from app.services.market_protocol import get_protocol, list_protocols
@@ -0,0 +1,46 @@
"""协议/捐赠列表 sampleItems 须返回样本 voidDesc,供审核列表问号展示。"""
from __future__ import annotations
import inspect
import re
import unittest
_SAMPLE_ITEM_VOID_DESC = re.compile(
r'"sampleStatus"\s*:\s*\(s\.sample_status[^)]*\)\.strip\(\),\s*'
r'"voidDesc"\s*:\s*\(getattr\(s,\s*"void_desc"',
re.S,
)
class TestProtocolListSampleVoidDesc(unittest.TestCase):
def test_collection_protocol_list_includes_sample_void_desc(self):
from app.crud import collection_protocol as cp
src = inspect.getsource(cp.list_collection_protocols)
self.assertRegex(src, _SAMPLE_ITEM_VOID_DESC)
def test_research_donation_list_includes_sample_void_desc(self):
from app.crud import research_donation as rd
# 捐赠列表函数名
fn = None
for name, obj in inspect.getmembers(rd, inspect.isfunction):
if "list" in name and "donation" in name:
src = inspect.getsource(obj)
if "sample_items.append" in src and '"sampleStatus"' in src:
fn = obj
break
self.assertIsNotNone(fn, "未找到组装 sampleItems 的捐赠列表函数")
self.assertRegex(inspect.getsource(fn), _SAMPLE_ITEM_VOID_DESC)
def test_sample_collection_list_uses_sample_void_desc(self):
from app.crud import protocol_sample_collection as psc
src = inspect.getsource(psc)
self.assertIn('getattr(psample, "void_desc"', src)
self.assertNotIn('item["voidDesc"] = (proto.void_desc or "") if proto else ""', src)
if __name__ == "__main__":
unittest.main()
@@ -23,6 +23,7 @@ from app.models.research_donation import (
)
from app.services.protocol_reception_discard_sync import (
LAB_VOID_TYPE_CODE,
SAMPLE_VOID_STATUS,
after_protocol_voided,
after_sample_reception_saved,
ensure_lab_void_type,
@@ -77,6 +78,7 @@ class TestProtocolReceptionDiscardSync(unittest.TestCase):
id="p1",
protocol_no="CP-1",
protocol_status="sxz",
void_time=now,
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
@@ -89,6 +91,7 @@ class TestProtocolReceptionDiscardSync(unittest.TestCase):
id="s1",
collection_protocol_id="p1",
sample_code="ZK001",
sample_status="yrk",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
@@ -101,6 +104,7 @@ class TestProtocolReceptionDiscardSync(unittest.TestCase):
id="s2",
collection_protocol_id="p1",
sample_code="ZK002",
sample_status="jcz",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
@@ -152,6 +156,16 @@ class TestProtocolReceptionDiscardSync(unittest.TestCase):
self.assertEqual(by_code["ZK001"], "bj")
self.assertEqual(by_code["ZK002"], "bj")
samples = (
db.query(BizProtocolSample)
.filter(BizProtocolSample.collection_protocol_id == "p1")
.all()
)
self.assertEqual(len(samples), 2)
for s in samples:
self.assertEqual(s.sample_status, SAMPLE_VOID_STATUS)
self.assertEqual(s.void_date, "20261105")
def test_all_samples_discarded_auto_voids_protocol_with_lab_type(self):
db = _session()
now = _now()
@@ -172,6 +186,7 @@ class TestProtocolReceptionDiscardSync(unittest.TestCase):
id="s3",
collection_protocol_id="p2",
sample_code="ZK003",
sample_status="ycj",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
@@ -212,6 +227,9 @@ class TestProtocolReceptionDiscardSync(unittest.TestCase):
self.assertEqual(proto.protocol_status, "yzf")
self.assertEqual(proto.void_type, LAB_VOID_TYPE_CODE)
self.assertIn("全部样本接收", proto.void_desc or "")
sample = db.query(BizProtocolSample).filter(BizProtocolSample.id == "s3").one()
self.assertEqual(sample.sample_status, SAMPLE_VOID_STATUS)
self.assertTrue((sample.void_date or "").strip())
def test_partial_discard_does_not_void_protocol(self):
db = _session()
@@ -282,6 +300,7 @@ class TestProtocolReceptionDiscardSync(unittest.TestCase):
id="d1",
donation_no="RD-1",
donation_status="sxz",
void_time=now,
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
@@ -294,6 +313,7 @@ class TestProtocolReceptionDiscardSync(unittest.TestCase):
id="ds1",
research_donation_id="d1",
sample_code="RD001",
sample_status="yrk",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
@@ -322,6 +342,203 @@ class TestProtocolReceptionDiscardSync(unittest.TestCase):
)
self.assertEqual(rec.accept_conclusion, "bj")
self.assertEqual(rec.research_donation_id, "d1")
sample = (
db.query(BizResearchDonationSample)
.filter(BizResearchDonationSample.id == "ds1")
.one()
)
self.assertEqual(sample.sample_status, SAMPLE_VOID_STATUS)
self.assertEqual(sample.void_date, "20261105")
def test_sdfq_also_voids_sample_status(self):
db = _session()
now = _now()
db.add(
BizCollectionProtocol(
id="p-sdfq",
protocol_no="CP-SDFQ",
protocol_status="sdfq",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
db.add(
BizProtocolSample(
id="s-sdfq",
collection_protocol_id="p-sdfq",
sample_code="ZKSDFQ",
sample_status="ycj",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
db.commit()
after_protocol_voided(
db,
source="cell_storage",
protocol_id="p-sdfq",
tenant_no="tenant-a",
user_id="u1",
)
db.commit()
sample = db.query(BizProtocolSample).filter(BizProtocolSample.id == "s-sdfq").one()
self.assertEqual(sample.sample_status, SAMPLE_VOID_STATUS)
self.assertTrue((sample.void_date or "").strip())
rec = (
db.query(BizSampleReception)
.filter(BizSampleReception.sample_code == "ZKSDFQ")
.one()
)
self.assertEqual(rec.accept_conclusion, "bj")
def test_single_reception_discard_voids_only_that_sample(self):
db = _session()
now = _now()
db.add(
BizCollectionProtocol(
id="p-multi",
protocol_no="CP-MULTI",
protocol_status="sxz",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
for sid, code, status in (
("sa", "ZKA", "ycj"),
("sb", "ZKB", "ycj"),
("sc", "ZKC", "ycj"),
):
db.add(
BizProtocolSample(
id=sid,
collection_protocol_id="p-multi",
sample_code=code,
sample_status=status,
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
rec_a = BizSampleReception(
id="ra",
protocol_sample_id="sa",
collection_protocol_id="p-multi",
reception_time=now,
accept_conclusion="bj",
reception_source="cell_storage",
sample_code="ZKA",
remark="母血乙肝阳性",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
check_packaging=0,
check_sealing=0,
check_no_damage=0,
check_no_leakage=0,
check_color=0,
check_tying_rope=0,
check_no_stratification=0,
)
db.add(rec_a)
db.commit()
after_sample_reception_saved(
db, reception=rec_a, tenant_no="tenant-a", user_id="u1"
)
db.commit()
proto = db.query(BizCollectionProtocol).filter(BizCollectionProtocol.id == "p-multi").one()
self.assertEqual(proto.protocol_status, "sxz")
by_id = {
s.id: s
for s in db.query(BizProtocolSample)
.filter(BizProtocolSample.collection_protocol_id == "p-multi")
.all()
}
self.assertEqual(by_id["sa"].sample_status, SAMPLE_VOID_STATUS)
self.assertEqual(by_id["sa"].void_date, "20261105")
self.assertEqual(by_id["sa"].void_desc, "母血乙肝阳性")
self.assertEqual(by_id["sb"].sample_status, "ycj")
self.assertEqual(by_id["sc"].sample_status, "ycj")
def test_reception_accept_clears_sample_void_when_protocol_active(self):
db = _session()
now = _now()
db.add(
BizCollectionProtocol(
id="p-clear",
protocol_no="CP-CLEAR",
protocol_status="sxz",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
db.add(
BizProtocolSample(
id="s-clear",
collection_protocol_id="p-clear",
sample_code="ZKCLR",
sample_status=SAMPLE_VOID_STATUS,
void_date="20261101",
void_desc="旧作废原因",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
rec = BizSampleReception(
id="r-clear",
protocol_sample_id="s-clear",
collection_protocol_id="p-clear",
reception_time=now,
accept_conclusion="js",
reception_source="cell_storage",
sample_code="ZKCLR",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
check_packaging=0,
check_sealing=0,
check_no_damage=0,
check_no_leakage=0,
check_color=0,
check_tying_rope=0,
check_no_stratification=0,
)
db.add(rec)
db.commit()
after_sample_reception_saved(
db, reception=rec, tenant_no="tenant-a", user_id="u1"
)
db.commit()
sample = db.query(BizProtocolSample).filter(BizProtocolSample.id == "s-clear").one()
self.assertFalse((sample.sample_status or "").strip())
self.assertFalse((sample.void_date or "").strip())
self.assertFalse((sample.void_desc or "").strip())
if __name__ == "__main__":
@@ -17,8 +17,8 @@ def test_explicit_statuses_returned():
assert resolve_research_donation_protocol_status_filter("dsx,sxz") == ("in", ["dsx", "sxz"])
def test_explicit_empty_means_none():
assert resolve_research_donation_protocol_status_filter("") == ("none", [])
def test_explicit_empty_means_all():
assert resolve_research_donation_protocol_status_filter("") == ("all", [])
def test_missing_means_default_dsx_sxz():
@@ -27,5 +27,5 @@ def test_missing_means_default_dsx_sxz():
assert statuses == ["dsx", "sxz"]
def test_whitespace_only_means_none():
assert resolve_research_donation_protocol_status_filter(" , ") == ("none", [])
def test_whitespace_only_means_all():
assert resolve_research_donation_protocol_status_filter(" , ") == ("all", [])
@@ -0,0 +1,38 @@
"""质检检测结果留痕:字段差异与空保存。"""
from app.crud.qc_task_result_change_log import build_result_changes
def test_build_changes_for_status_and_param():
before = {
"taskStatus": "dzx",
"conclusion": "",
"remark": "",
"attachments": "",
"params": {"paramCode:HBsAg": {"label": "HBsAg", "value": "阴性"}},
}
after = {
"taskStatus": "ywc",
"conclusion": "tg",
"remark": "",
"attachments": "",
"params": {"paramCode:HBsAg": {"label": "HBsAg", "value": "阳性"}},
}
changes = build_result_changes(before, after)
keys = {c["fieldKey"] for c in changes}
assert "taskStatus" in keys
assert "conclusion" in keys
assert "paramCode:HBsAg" in keys
hbs = next(c for c in changes if c["fieldKey"] == "paramCode:HBsAg")
assert hbs["oldValue"] == "阴性"
assert hbs["newValue"] == "阳性"
def test_build_changes_empty_when_identical():
state = {
"taskStatus": "ywc",
"conclusion": "tg",
"remark": "ok",
"attachments": "a.png",
"params": {"paramCode:X": {"label": "X", "value": "1"}},
}
assert build_result_changes(state, state) == []
@@ -0,0 +1,142 @@
"""质检工单附件:序列化与第三方材料必填取消。"""
import os
# 避免导入 app 时 Settings 因缺 SECRET_KEY 失败
os.environ.setdefault(
"SECRET_KEY", "test-secret-key-for-qc-wo-attach-unit-tests-32c"
)
import unittest
from types import SimpleNamespace
from unittest.mock import MagicMock, patch
class TestQcWorkOrderAttachmentsDict(unittest.TestCase):
@classmethod
def setUpClass(cls):
# 先导入 qc_task 打破与 qc_work_order 的循环依赖
import app.crud.qc_task # noqa: F401
from app.crud import qc_work_order as wo_mod
cls.wo_mod = wo_mod
def _base_wo(self, **overrides):
wo = SimpleNamespace(
id="wo-1",
work_order_no="QC001",
work_order_type="inbound",
reception_id=None,
protocol_sample_id=None,
collection_protocol_id=None,
protocol_no="",
sample_code="S1",
reception_source="cell_storage",
qc_biz_type="inbound",
biz_type="",
cell_product_id=None,
external_target_code=None,
trigger_source="reception",
production_work_order_id=None,
production_task_id=None,
production_step_output_id=None,
infusion_schedule_id=None,
work_order_status="jxz",
conclusion=None,
has_lab="1",
has_third_party="0",
configured_time=None,
configured_by=None,
third_party_fee_total=None,
attachments=None,
remark=None,
create_time=None,
update_time=None,
)
for k, v in overrides.items():
setattr(wo, k, v)
return wo
def test_wo_to_dict_includes_attachments(self):
data = self.wo_mod._wo_to_dict(
self._base_wo(attachments="https://a/x.pdf, https://b/y.png")
)
self.assertEqual(data["attachments"], "https://a/x.pdf, https://b/y.png")
def test_wo_to_dict_attachments_default_empty(self):
data = self.wo_mod._wo_to_dict(self._base_wo(attachments=None, sample_code=""))
self.assertEqual(data["attachments"], "")
class TestRequireDsfjcAttachmentsOptional(unittest.TestCase):
def test_complete_without_third_party_attachments_ok(self):
from app.crud.qc_task import _require_dsfjc_attachments
task = SimpleNamespace(task_type="dsfjc", third_party_attachments="")
# 不再抛错
_require_dsfjc_attachments(task, for_status="ywc")
class TestUpdateQcWorkOrderAttachments(unittest.TestCase):
@patch("app.crud.qc_work_order.get_work_order")
def test_update_normalizes_and_sets_attachments(self, mock_get):
from app.crud.qc_work_order import update_qc_work_order
wo = SimpleNamespace(
id="wo-3",
work_order_type="inbound",
attachments=None,
remark=None,
work_order_status="jxz",
conclusion=None,
cell_product_id=None,
external_target_code=None,
update_by=None,
update_time=None,
)
mock_get.return_value = wo
db = MagicMock()
update_qc_work_order(
db,
"wo-3",
tenant_no="zkxw",
user_id="u1",
attachments=" https://a/1.pdf , https://b/2.pdf , ",
)
self.assertEqual(wo.attachments, "https://a/1.pdf,https://b/2.pdf")
self.assertEqual(wo.update_by, "u1")
db.add.assert_called()
db.flush.assert_called()
@patch("app.crud.qc_work_order.get_work_order")
def test_update_clear_attachments(self, mock_get):
from app.crud.qc_work_order import update_qc_work_order
wo = SimpleNamespace(
id="wo-4",
work_order_type="inbound",
attachments="https://a/1.pdf",
remark=None,
work_order_status="jxz",
conclusion=None,
cell_product_id=None,
external_target_code=None,
update_by=None,
update_time=None,
)
mock_get.return_value = wo
db = MagicMock()
update_qc_work_order(
db,
"wo-4",
tenant_no="zkxw",
user_id="u1",
attachments="",
)
self.assertIsNone(wo.attachments)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,34 @@
"""质检工单 / 我的质检任务共用关键词条件(无库路径)。"""
# qc_work_order ↔ qc_task 存在循环依赖:先经 qc_task 再取 helper
import app.crud.qc_task # noqa: F401
from app.crud.qc_work_order import build_qc_work_order_keyword_conditions
from app.models.models import BizQcWorkOrder
def test_empty_keyword_returns_no_conditions():
assert build_qc_work_order_keyword_conditions(
None, tenant_no=None, keyword=""
) == []
assert build_qc_work_order_keyword_conditions(
None, tenant_no="t1", keyword=" "
) == []
def test_base_conditions_without_tenant_cover_list_fields():
conds = build_qc_work_order_keyword_conditions(
None,
tenant_no=None,
keyword="ABC",
work_order_type="inbound",
reception_source="cell_storage",
)
assert len(conds) == 4
# 与质检工单列表一致的四列(无租户时不做入库/母亲/出库扩展)
cols = {str(c.left) for c in conds}
assert str(BizQcWorkOrder.work_order_no) in cols or any(
"work_order_no" in str(c) for c in conds
)
assert any("sample_code" in str(c) for c in conds)
assert any("protocol_no" in str(c) for c in conds)
assert any("external_target_code" in str(c) for c in conds)
@@ -0,0 +1,174 @@
"""入库质检工单列表:从协议/捐赠采集信息补齐母血采集时间。"""
import unittest
from datetime import datetime
from unittest import mock
import app.crud.qc_task # noqa: F401 先加载任务模块,避免与工单模块循环导入
from app.crud import qc_work_order as qc_wo
from app.crud.qc_work_order import _enrich_work_order_list_items
from app.models.models import (
BizCollectionProtocol,
BizProtocolCollectionInfo,
BizProtocolPartyCustomer,
BizSampleReception,
)
from app.models.research_donation import (
BizResearchDonation,
BizResearchDonationCollection,
BizResearchDonationParty,
)
def _item(**kwargs):
data = {
"id": "wo-1",
"workOrderType": "inbound",
"receptionId": "rec-1",
"sampleCode": "S001",
"collectionProtocolId": "proto-1",
"receptionSource": "cell_storage",
"protocolSampleId": "",
"maternalBloodCollectTime": "",
}
data.update(kwargs)
return data
def _query_router(mapping):
def _query(*entities):
q = mock.Mock()
q.filter.return_value = q
q.order_by.return_value = q
model = entities[0]
# db.query(Model.col, ...) → first entity is InstrumentedAttribute
cls = getattr(model, "class_", model)
key = getattr(cls, "__name__", str(cls))
rows = mapping.get(key, [])
q.all.return_value = rows
return q
return _query
class TestEnrichWorkOrderMaternalBlood(unittest.TestCase):
def test_cell_storage_fills_maternal_blood_collect_time(self):
rec = mock.Mock(
id="rec-1",
sample_code="S001",
reception_source="cell_storage",
collection_protocol_id="proto-1",
research_donation_id="",
protocol_sample_id="",
donation_sample_id="",
reception_time=datetime(2026, 11, 8, 13, 30, 41),
handler_name="质检员",
lab_storage_code="",
)
coll = mock.Mock(
collection_protocol_id="proto-1",
maternal_blood_collect_time=datetime(2026, 11, 7, 9, 15, 0),
del_flag=0,
)
db = mock.Mock()
db.query.side_effect = _query_router(
{
BizSampleReception.__name__: [rec],
BizProtocolCollectionInfo.__name__: [coll],
BizProtocolPartyCustomer.__name__: [],
BizCollectionProtocol.__name__: [],
}
)
with mock.patch.object(
qc_wo, "_enrich_protocol_sibling_samples", side_effect=lambda _db, items: items
), mock.patch.object(
qc_wo, "apply_special_to_item_from_samples", side_effect=lambda item, **_k: item
):
items = _enrich_work_order_list_items(db, [_item()])
self.assertEqual(items[0]["maternalBloodCollectTime"], "2026-11-07 09:15:00")
def test_missing_maternal_blood_stays_empty(self):
rec = mock.Mock(
id="rec-1",
sample_code="S001",
reception_source="cell_storage",
collection_protocol_id="proto-1",
research_donation_id="",
protocol_sample_id="",
donation_sample_id="",
reception_time=datetime(2026, 11, 8, 13, 30, 41),
handler_name="质检员",
lab_storage_code="",
)
db = mock.Mock()
db.query.side_effect = _query_router(
{
BizSampleReception.__name__: [rec],
BizProtocolCollectionInfo.__name__: [],
BizProtocolPartyCustomer.__name__: [],
BizCollectionProtocol.__name__: [],
}
)
with mock.patch.object(
qc_wo, "_enrich_protocol_sibling_samples", side_effect=lambda _db, items: items
), mock.patch.object(
qc_wo, "apply_special_to_item_from_samples", side_effect=lambda item, **_k: item
):
items = _enrich_work_order_list_items(db, [_item()])
self.assertEqual(items[0]["maternalBloodCollectTime"], "")
def test_research_donation_fills_maternal_blood_collect_time(self):
rec = mock.Mock(
id="rec-2",
sample_code="D001",
reception_source="research_donation",
collection_protocol_id="",
research_donation_id="don-1",
protocol_sample_id="",
donation_sample_id="",
reception_time=datetime(2026, 11, 8, 10, 0, 0),
handler_name="质检员",
lab_storage_code="",
)
coll = mock.Mock(
research_donation_id="don-1",
maternal_blood_collect_time=datetime(2026, 11, 6, 8, 0, 0),
del_flag=0,
)
db = mock.Mock()
db.query.side_effect = _query_router(
{
BizSampleReception.__name__: [rec],
BizResearchDonationCollection.__name__: [coll],
BizResearchDonationParty.__name__: [],
BizResearchDonation.__name__: [],
}
)
with mock.patch.object(
qc_wo, "_enrich_protocol_sibling_samples", side_effect=lambda _db, items: items
), mock.patch.object(
qc_wo, "apply_special_to_item_from_samples", side_effect=lambda item, **_k: item
):
items = _enrich_work_order_list_items(
db,
[
_item(
id="wo-2",
receptionId="rec-2",
sampleCode="D001",
collectionProtocolId="don-1",
receptionSource="research_donation",
)
],
)
self.assertEqual(items[0]["maternalBloodCollectTime"], "2026-11-06 08:00:00")
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,266 @@
"""临床科研/委托加工:项目组负责人审批卡点。"""
import unittest
from unittest.mock import MagicMock, patch
from app.constants.pilot_biz import (
APPROVAL_PASSED,
APPROVAL_PENDING,
APPROVAL_REJECTED,
)
from app.crud import pilot_application as crud
class TestResearchLeaderApprovalGate(unittest.TestCase):
def test_assert_blocks_when_pending(self):
app = MagicMock()
app.biz_type = "basic_experiment"
app.approval_status = APPROVAL_PENDING
with self.assertRaises(ValueError) as ctx:
crud.assert_research_leader_approved(app)
self.assertIn("项目组负责人审批", str(ctx.exception))
def test_assert_allows_when_passed(self):
app = MagicMock()
app.biz_type = "contract_processing"
app.approval_status = APPROVAL_PASSED
crud.assert_research_leader_approved(app)
def test_assert_skips_non_research(self):
app = MagicMock()
app.biz_type = "pilot_service"
app.approval_status = None
crud.assert_research_leader_approved(app)
class TestApproveApplication(unittest.TestCase):
def test_reject_requires_leader(self):
db = MagicMock()
app = MagicMock()
app.biz_type = "basic_experiment"
app.application_status = "dks"
app.approval_status = APPROVAL_PENDING
app.project_id = "proj-1"
app.create_dept_id = "dept-1"
project = MagicMock()
project.leader_user_id = "leader-1"
q_app = MagicMock()
q_app.filter.return_value = q_app
q_app.first.return_value = app
q_proj = MagicMock()
q_proj.filter.return_value = q_proj
q_proj.first.return_value = project
def query_side_effect(model, *args, **kwargs):
name = getattr(model, "__name__", str(model))
if "BizPilotApplication" in name or model is crud.BizPilotApplication:
return q_app
return q_proj
db.query.side_effect = query_side_effect
with patch.object(crud, "_require_research_project_with_leader", return_value=project):
with patch.object(crud, "_team_leader_user_id", return_value="team-leader-1"):
with patch.object(crud, "_row_to_dict_application", return_value={"id": "a1"}):
with self.assertRaises(ValueError) as ctx:
crud.approve_application(
db,
app_id="a1",
tenant_no="zkxw",
user_id="other-user",
approval_status=APPROVAL_REJECTED,
is_super_admin=False,
)
self.assertIn("项目组", str(ctx.exception))
def test_leader_can_pass(self):
db = MagicMock()
app = MagicMock()
app.biz_type = "contract_processing"
app.application_status = "dks"
app.approval_status = APPROVAL_PENDING
app.project_id = "proj-1"
app.create_dept_id = "dept-1"
app.id = "a1"
project = MagicMock()
project.leader_user_id = "leader-1"
q_app = MagicMock()
q_app.filter.return_value = q_app
q_app.first.return_value = app
db.query.return_value = q_app
with patch.object(crud, "_require_research_project_with_leader", return_value=project):
with patch.object(crud, "_team_leader_user_id", return_value="team-leader-1"):
with patch.object(crud, "_backfill_outbound_work_orders_for_application") as backfill:
with patch.object(crud, "_row_to_dict_application", return_value={"id": "a1"}):
result = crud.approve_application(
db,
app_id="a1",
tenant_no="zkxw",
user_id="team-leader-1",
approval_status=APPROVAL_PASSED,
approval_remark="ok",
is_super_admin=False,
)
self.assertEqual(app.approval_status, APPROVAL_PASSED)
backfill.assert_called_once()
self.assertEqual(result["id"], "a1")
def test_leader_can_change_rejected_to_passed(self):
db = MagicMock()
app = MagicMock()
app.biz_type = "basic_experiment"
app.application_status = "dks"
app.approval_status = APPROVAL_REJECTED
app.project_id = "proj-1"
app.create_dept_id = "dept-1"
app.id = "a1"
project = MagicMock()
project.leader_user_id = "leader-1"
q_app = MagicMock()
q_app.filter.return_value = q_app
q_app.first.return_value = app
db.query.return_value = q_app
with patch.object(crud, "_require_research_project_with_leader", return_value=project):
with patch.object(crud, "_team_leader_user_id", return_value="team-leader-1"):
with patch.object(crud, "_backfill_outbound_work_orders_for_application") as backfill:
with patch.object(crud, "_row_to_dict_application", return_value={"id": "a1"}):
crud.approve_application(
db,
app_id="a1",
tenant_no="zkxw",
user_id="team-leader-1",
approval_status=APPROVAL_PASSED,
is_super_admin=False,
)
self.assertEqual(app.approval_status, APPROVAL_PASSED)
backfill.assert_called_once()
def test_super_admin_can_approve_others_project(self):
db = MagicMock()
app = MagicMock()
app.biz_type = "basic_experiment"
app.application_status = "dks"
app.approval_status = APPROVAL_PENDING
app.project_id = "proj-1"
app.create_dept_id = "dept-1"
app.id = "a1"
project = MagicMock()
project.leader_user_id = "leader-1"
q_app = MagicMock()
q_app.filter.return_value = q_app
q_app.first.return_value = app
db.query.return_value = q_app
with patch.object(crud, "_require_research_project_with_leader", return_value=project):
with patch.object(crud, "_team_leader_user_id", return_value="team-leader-1"):
with patch.object(crud, "_backfill_outbound_work_orders_for_application") as backfill:
with patch.object(crud, "_row_to_dict_application", return_value={"id": "a1"}):
crud.approve_application(
db,
app_id="a1",
tenant_no="zkxw",
user_id="super-admin-user",
approval_status=APPROVAL_PASSED,
is_super_admin=True,
)
self.assertEqual(app.approval_status, APPROVAL_PASSED)
backfill.assert_called_once()
class TestResearchVisibilityScope(unittest.TestCase):
def test_super_admin_bypasses_visibility(self):
q = MagicMock()
out = crud.apply_research_like_visibility(
q,
MagicMock(),
"zkxw",
{"user_id": "u1", "role": "super_admin"},
for_approval=True,
)
self.assertIs(out, q)
def test_data_scope_admin_does_not_bypass_visibility(self):
q = MagicMock()
q.filter.return_value = "filtered"
db = MagicMock()
with patch.object(crud, "_led_team_ids", return_value=[]):
out = crud.apply_research_like_visibility(
q,
db,
"zkxw",
{"user_id": "leader-a", "role": "admin"},
for_approval=True,
)
self.assertEqual(out, "filtered")
q.filter.assert_called_once_with(False)
def test_data_scope_admin_cannot_access_other_team_for_approval(self):
app = MagicMock()
app.biz_type = "basic_experiment"
app.project_id = "proj-other"
app.create_by = "other"
with patch.object(crud, "_team_leader_user_id", return_value="team-leader-other"):
ok = crud.user_can_access_research_application(
MagicMock(),
"zkxw",
{"user_id": "leader-a", "role": "admin"},
app,
for_approval=True,
)
self.assertFalse(ok)
def test_super_admin_can_access_any_for_approval(self):
app = MagicMock()
app.biz_type = "basic_experiment"
app.project_id = "proj-other"
ok = crud.user_can_access_research_application(
MagicMock(),
"zkxw",
{"user_id": "sa", "role": "super_admin"},
app,
for_approval=True,
)
self.assertTrue(ok)
def test_is_super_admin_user_ignores_data_scope_roles(self):
self.assertTrue(crud._is_super_admin_user({"role": "super_admin"}))
self.assertFalse(crud._is_super_admin_user({"role": "admin"}))
self.assertFalse(crud._is_super_admin_user(None))
class TestCreateRequiresProject(unittest.TestCase):
def test_contract_processing_requires_project(self):
db = MagicMock()
data = {
"bizType": "contract_processing",
"researchCategory": "msc",
"channelId": "ch-1",
"projectTitle": "课题A",
"customerName": "客户",
"customerContact": "张三",
"customerPhone": "13800000000",
}
with patch.object(crud, "_generate_application_no", return_value="WTJG1"):
with self.assertRaises(ValueError) as ctx:
crud.create_application(
db,
data=data,
tenant_no="zkxw",
user_id="user-1",
dept_id="dept-1",
)
self.assertIn("项目", str(ctx.exception))
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,62 @@
"""Static checks for market/pilot-service role-menu revoke migration (#156)."""
import re
from pathlib import Path
MIGRATION = (
Path(__file__).resolve().parents[2]
/ "docs/sql/migrations/2026-11-20-revoke-market-pilot-service-role-menus.sql"
)
def _sql() -> str:
return MIGRATION.read_text(encoding="utf-8")
def _compact(sql: str) -> str:
return re.sub(r"\s+", " ", sql)
def _without_comments(sql: str) -> str:
return re.sub(r"--[^\n]*", "", sql)
def test_migration_file_exists():
assert MIGRATION.is_file()
def test_scopes_to_market_pilot_service_tree():
compact = _compact(_without_comments(_sql()))
assert "menu:market" in compact
assert "中试服务" in compact
assert re.search(r"pilot\.menu_name\s*=\s*'中试服务'", compact)
assert re.search(r"market\.perms\s*=\s*'menu:market'", compact)
def test_revokes_role_menu_by_soft_delete_only():
compact = _compact(_without_comments(_sql()))
assert re.search(r"UPDATE\s+sys_role_menu", compact, re.IGNORECASE)
assert re.search(
r"UPDATE\s+sys_role_menu\s+rm\b.*SET\s+rm\.del_flag\s*=\s*1",
compact,
re.IGNORECASE,
)
assert not re.search(r"DELETE\s+FROM\s+sys_role_menu", compact, re.IGNORECASE)
assert not re.search(r"UPDATE\s+sys_menu\s+SET\s+del_flag\s*=\s*1", compact, re.IGNORECASE)
assert not re.search(r"DELETE\s+FROM\s+sys_menu", compact, re.IGNORECASE)
def test_includes_children_and_button_descendants():
compact = _compact(_without_comments(_sql()))
assert re.search(r"child\.parent_id\s*=\s*pilot\.id", compact)
assert re.search(r"btn\.parent_id\s*=\s*child\.id", compact)
assert compact.count("UNION") >= 2
def test_update_only_touches_active_bindings():
compact = _compact(_without_comments(_sql()))
assert re.search(
r"SET\s+rm\.del_flag\s*=\s*1[\s\S]*WHERE\s+rm\.del_flag\s*=\s*0",
compact,
re.IGNORECASE,
)
+14
View File
@@ -79,12 +79,26 @@ class TestFreightListHelpers(unittest.TestCase):
sample_type_name="脐带血",
mother_name="张三",
newborn_name="张小宝",
sample_status="ycj",
void_desc="",
)
self.assertEqual(d["protocolNo"], "CP001")
self.assertEqual(d["sampleTypeName"], "脐带血")
self.assertEqual(d["sampleSource"], "cell_storage")
self.assertEqual(d["motherName"], "张三")
self.assertEqual(d["newbornName"], "张小宝")
self.assertEqual(d["sampleStatus"], "ycj")
self.assertEqual(d["sampleStatusLabel"], "已采集")
self.assertEqual(d["voidDesc"], "")
voided = _item_to_dict_enriched(
I(),
sample_status="yzf",
void_desc="运输破损",
)
self.assertEqual(voided["sampleStatus"], "yzf")
self.assertEqual(voided["sampleStatusLabel"], "已作废")
self.assertEqual(voided["voidDesc"], "运输破损")
def test_row_dict_includes_create_by(self):
from app.crud.sample_freight import _row_to_dict
@@ -1,8 +1,12 @@
"""样本缴费列表:进度过滤与分页顺序"""
"""样本缴费列表:进度过滤与分页顺序、样本状态汇总字段"""
from types import SimpleNamespace
import unittest
from app.crud.protocol_sample_payment import _filter_and_page_progress
from app.crud.protocol_sample_payment import (
_build_list_summary_row,
_filter_and_page_progress,
)
class TestFilterAndPageProgress(unittest.TestCase):
@@ -33,5 +37,73 @@ class TestFilterAndPageProgress(unittest.TestCase):
self.assertEqual([r["id"] for r in page], ["0", "1", "2"])
class TestPaymentListSampleStatus(unittest.TestCase):
def test_summary_row_exposes_sample_status_and_void_desc(self):
sp = SimpleNamespace(
id="sp1",
collection_protocol_id="p1",
sample_code="ZKZX34001028",
pay_mode="dj",
contract_amount=None,
remark="",
)
proto = SimpleNamespace(
protocol_no="CP-1",
protocol_status="sxz",
void_type="",
register_date="20261101",
)
party = SimpleNamespace(mother_name="张三", mother_phone="13800000000")
progress = {
"progressStatus": "dfj",
"paidAmount": 0,
"arrearsAmount": 0,
"dueAmount": 0,
}
row = _build_list_summary_row(
sp,
proto,
party,
progress,
schedules=[],
transfers=[],
sample_meta={
"storageYears": 20,
"sampleTypeName": "脐带血",
"discountAmount": None,
"sampleStatus": "ycj",
"sampleStatusLabel": "已采集",
"voidDesc": "",
},
)
self.assertEqual(row["sampleStatus"], "ycj")
self.assertEqual(row["sampleStatusLabel"], "已采集")
self.assertEqual(row["voidDesc"], "")
voided = _build_list_summary_row(
sp,
proto,
party,
progress,
schedules=[],
transfers=[],
sample_meta={
"sampleStatus": "yzf",
"voidDesc": "客户放弃存储",
},
)
self.assertEqual(voided["sampleStatus"], "yzf")
self.assertEqual(voided["sampleStatusLabel"], "已作废")
self.assertEqual(voided["voidDesc"], "客户放弃存储")
class TestPaymentChaseSampleStatusLabels(unittest.TestCase):
def test_status_label_map_covers_voided(self):
from app.crud.protocol_sample_payment import _SAMPLE_STATUS_LABELS
self.assertEqual(_SAMPLE_STATUS_LABELS.get("ycj"), "已采集")
self.assertEqual(_SAMPLE_STATUS_LABELS.get("yzf"), "已作废")
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,28 @@
"""样本接收已接收列表:样本类型 / 是否废弃筛选参数解析。"""
import unittest
from app.crud.sample_reception import parse_optional_bool
class TestSampleReceptionReceivedFilters(unittest.TestCase):
def test_parse_optional_bool_true_variants(self):
for raw in ("true", "TRUE", "1", "yes", "Y"):
self.assertIs(parse_optional_bool(raw), True)
def test_parse_optional_bool_false_variants(self):
for raw in ("false", "FALSE", "0", "no", "N"):
self.assertIs(parse_optional_bool(raw), False)
def test_parse_optional_bool_empty_means_unrestricted(self):
self.assertIsNone(parse_optional_bool(None))
self.assertIsNone(parse_optional_bool(""))
self.assertIsNone(parse_optional_bool(" "))
def test_parse_optional_bool_rejects_invalid(self):
with self.assertRaises(ValueError):
parse_optional_bool("maybe")
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,41 @@
import os
import unittest
# 避免导入 app.models 时 Settings 因缺 SECRET_KEY 失败
os.environ.setdefault(
"SECRET_KEY", "test-secret-key-for-uc-msc-unit-tests-32c"
)
class TestUcMscBuiltinTemplate(unittest.TestCase):
def test_step_order_matches_business_five_nodes(self):
from app.services.uc_msc_builtin_template import UC_MSC_STEP_ORDER
self.assertEqual(
UC_MSC_STEP_ORDER,
[
"SOP-SC-003-E01-01",
"SOP-SC-004-E01-01",
"SOP-SC-006-E01-01",
"SOP-SC-005-E01-01",
"SOP-SC-008-E01-01",
],
)
self.assertNotIn("SOP-SC-007-E01-01", UC_MSC_STEP_ORDER)
def test_uc_prefix_maps_to_uc_set_name(self):
from app.services.uc_msc_builtin_template import UC_MSC_ROUTE_CODE
from app.utils.lab_storage_code_task_set import (
UC_MSC_BUILTIN_SET_NAME,
match_builtin_task_set_name_by_lab_storage_code,
)
self.assertEqual(UC_MSC_ROUTE_CODE, "MSC原代-UC-BUILTIN")
self.assertEqual(
match_builtin_task_set_name_by_lab_storage_code("UC2026010"),
UC_MSC_BUILTIN_SET_NAME,
)
if __name__ == "__main__":
unittest.main()
+27
View File
@@ -0,0 +1,27 @@
"""用户下拉选项:同部门优先排序。"""
from app.services.user_select_options import prioritize_caller_dept_options
def test_prioritize_caller_dept_keeps_relative_order():
options = [
{"label": "外1", "value": "a", "deptId": "d2"},
{"label": "同1", "value": "b", "deptId": "d1"},
{"label": "外2", "value": "c", "deptId": "d3"},
{"label": "同2", "value": "d", "deptId": "d1"},
{"label": "无部门", "value": "e", "deptId": ""},
]
out = prioritize_caller_dept_options(options, "d1")
assert [x["value"] for x in out] == ["b", "d", "a", "c", "e"]
def test_prioritize_caller_dept_noop_without_caller_dept():
options = [
{"label": "a", "value": "a", "deptId": "d1"},
{"label": "b", "value": "b", "deptId": "d2"},
]
assert prioritize_caller_dept_options(options, "") == options
assert prioritize_caller_dept_options(options, " ") == options
def test_prioritize_caller_dept_empty_list():
assert prioritize_caller_dept_options([], "d1") == []
@@ -1,46 +0,0 @@
-- =============================================================================
-- 弱密码刷新说明:111111 → Zkxw@123
-- 日期:2026-10-16
-- =============================================================================
--
-- 重要:sys_user.password 存储 bcrypt 哈希(每次盐随机),
-- 不能用下列语句命中弱密码用户:
-- WHERE password = '111111' -- 无效
-- WHERE password LIKE '%111111%' -- 无效
--
-- 推荐:用 Python 脚本,并通过变量指定目标库(勿依赖本机默认 .env 误连生产)。
--
-- cd backend && source venv/bin/activate
--
-- # 方式 A:完整 URL
-- python scripts/reset_weak_password_111111.py \
-- --database-url 'mysql+pymysql://USER:PASS@HOST:3306/DBNAME' --dry-run
--
-- # 方式 B:分项变量
-- python scripts/reset_weak_password_111111.py \
-- --db-host HOST --db-port 3306 --db-user USER --db-password 'PASS' --db-name DBNAME --dry-run
--
-- # 方式 C:指定环境文件
-- python scripts/reset_weak_password_111111.py --env-file ./.env.test --dry-run
--
-- # 正式写入:去掉 --dry-run
--
-- 脚本行为:校验 del_flag=0 的用户口令是否为明文 111111(含停用账号),
-- 命中则更新为 Zkxw@123 的新 bcrypt 哈希。
--
-- =============================================================================
-- 以下仅为「已知单个用户 id」时的手工 UPDATE 模板。
-- 哈希由本机生成示例(明文 Zkxw@123,bcrypt cost 12),部署前请用 Python 重新生成:
-- python -c "from app.core.security import get_password_hash; print(get_password_hash('Zkxw@123'))"
-- =============================================================================
-- 示例哈希(仅供手工单用户更新参考;批量请用脚本):
-- $2b$12$ULvPCr6g9IUmI8K7nlGU5emk7hupaAz4WgFdEoQBe935Wh1pVYKCK
-- UPDATE sys_user
-- SET password = '$2b$12$ULvPCr6g9IUmI8K7nlGU5emk7hupaAz4WgFdEoQBe935Wh1pVYKCK',
-- update_time = NOW()
-- WHERE id = '<user_id>'
-- AND del_flag = 0;
-- 执行前请备份 sys_user;执行后通知用户使用新密码并建议登录后自行修改。
@@ -0,0 +1,175 @@
-- Issue #102:实验室样本处理数据挂到市场/生产/质检,权限码分端
-- 1) 质检管理:调到「入库放行审核」下方
-- 2) 存储服务:挂到「缴费财务确认」下方(cellStorage:labSampleProcess:*)
-- 3) 生产管理:挂到「废弃物管理」下方(production:labSampleProcess:*;若废弃物菜单缺失则先补齐)
-- 4) 拥有 menu:market / menu:production / menu:quality 的角色,授予对应大菜单下入口
-- MySQL 5.7,可重复执行
-- ── 0) 生产管理补齐「废弃物管理」(仅当缺失时,便于排序锚定)────────────────
INSERT INTO sys_menu (
id, menu_name, parent_id, menu_type, path, component, perms,
is_frame, visible, status, tenant_no, order_num, remark,
create_by, create_dept_id, create_time, update_by, update_time, del_flag
)
SELECT
INSERT(INSERT(MD5(CONCAT('prod-waste-output:', p.tenant_no, ':', p.id)), 13, 1, '3'), 17, 1, '8'),
'废弃物管理', p.id, 'C', 'waste-output',
'/production/waste-output/index', 'production:waste-output:list',
1, '1', '1', p.tenant_no,
COALESCE((SELECT MAX(c.order_num) FROM sys_menu c WHERE c.parent_id = p.id AND c.del_flag = 0), 0) + 1,
'issue#102 补齐生产废弃物管理以便台账排序',
'migration', '', NOW(), 'migration', NOW(), 0
FROM sys_menu p
WHERE p.del_flag = 0 AND p.status = '1' AND p.menu_name = '生产管理'
AND NOT EXISTS (
SELECT 1 FROM sys_menu e
WHERE e.tenant_no = p.tenant_no AND e.parent_id = p.id
AND e.perms = 'production:waste-output:list' AND e.del_flag = 0
);
-- ── 1) 质检:调到入库放行审核下方(可重复;不连带改动其他菜单 order)────────
UPDATE sys_menu lab
JOIN sys_menu release_m
ON release_m.parent_id = lab.parent_id
AND release_m.del_flag = 0
AND release_m.menu_name = '入库放行审核'
AND release_m.perms = 'quality:storageReleaseReview:list'
SET lab.order_num = release_m.order_num + 1,
lab.update_by = 'migration',
lab.update_time = NOW()
WHERE lab.del_flag = 0
AND lab.perms = 'biz:labSampleProcess:list'
AND lab.path = 'lab-sample-process'
AND (lab.order_num IS NULL OR lab.order_num <> release_m.order_num + 1);
-- ── 2) 存储服务:缴费财务确认下方 ───────────────────────────────────────────
INSERT INTO sys_menu (
id, menu_name, parent_id, menu_type, path, component, perms,
is_frame, visible, status, tenant_no, order_num, remark,
create_by, create_dept_id, create_time, update_by, update_time, del_flag
)
SELECT
INSERT(INSERT(MD5(CONCAT('cell-lab-sample-process:', anchor.tenant_no, ':', anchor.id)), 13, 1, '3'), 17, 1, '8'),
'实验室样本处理数据', anchor.parent_id, 'C', 'lab-sample-process',
'quality-inspection/lab-sample-process/index', 'cellStorage:labSampleProcess:list',
1, '1', '1', anchor.tenant_no, anchor.order_num + 1,
'市场-存储服务-实验室样本处理数据',
'migration', '', NOW(), 'migration', NOW(), 0
FROM sys_menu anchor
WHERE anchor.del_flag = 0 AND anchor.status = '1'
AND anchor.perms = 'biz:cellStoragePaymentConfirm:list'
AND anchor.menu_name = '缴费财务确认'
AND NOT EXISTS (
SELECT 1 FROM sys_menu e
WHERE e.tenant_no = anchor.tenant_no
AND e.parent_id = anchor.parent_id
AND e.perms = 'cellStorage:labSampleProcess:list'
AND e.del_flag = 0
);
-- ── 3) 生产管理:废弃物管理下方 ─────────────────────────────────────────────
INSERT INTO sys_menu (
id, menu_name, parent_id, menu_type, path, component, perms,
is_frame, visible, status, tenant_no, order_num, remark,
create_by, create_dept_id, create_time, update_by, update_time, del_flag
)
SELECT
INSERT(INSERT(MD5(CONCAT('prod-lab-sample-process:', anchor.tenant_no, ':', anchor.id)), 13, 1, '3'), 17, 1, '8'),
'实验室样本处理数据', anchor.parent_id, 'C', 'lab-sample-process',
'quality-inspection/lab-sample-process/index', 'production:labSampleProcess:list',
1, '1', '1', anchor.tenant_no, anchor.order_num + 1,
'生产-生产管理-实验室样本处理数据',
'migration', '', NOW(), 'migration', NOW(), 0
FROM sys_menu anchor
WHERE anchor.del_flag = 0 AND anchor.status = '1'
AND anchor.perms = 'production:waste-output:list'
AND anchor.menu_name = '废弃物管理'
AND NOT EXISTS (
SELECT 1 FROM sys_menu e
WHERE e.tenant_no = anchor.tenant_no
AND e.parent_id = anchor.parent_id
AND e.perms = 'production:labSampleProcess:list'
AND e.del_flag = 0
);
-- ── 4) 补录 / 导出按钮(三处列表菜单各挂一套)──────────────────────────────
INSERT INTO sys_menu (
id, menu_name, parent_id, menu_type, path, component, perms,
is_frame, visible, status, tenant_no, order_num, remark,
create_by, create_dept_id, create_time, update_by, update_time, del_flag
)
SELECT
INSERT(INSERT(MD5(CONCAT('lab-sp-btn:', m.tenant_no, ':', m.id, ':', btn.perms)), 13, 1, '3'), 17, 1, '8'),
btn.menu_name, m.id, 'F', '', NULL, btn.perms,
1, '1', '1', m.tenant_no, btn.order_num, btn.remark,
'migration', '', NOW(), 'migration', NOW(), 0
FROM sys_menu m
JOIN (
SELECT '补录' AS menu_name, 'cellStorage:labSampleProcess:supplement' AS perms, 10 AS order_num,
'存储服务-实验室样本处理数据-补录' AS remark, 'cellStorage:labSampleProcess:list' AS parent_perms
UNION ALL
SELECT '导出', 'cellStorage:labSampleProcess:export', 20,
'存储服务-实验室样本处理数据-导出', 'cellStorage:labSampleProcess:list'
UNION ALL
SELECT '补录', 'production:labSampleProcess:supplement', 10,
'生产-实验室样本处理数据-补录', 'production:labSampleProcess:list'
UNION ALL
SELECT '导出', 'production:labSampleProcess:export', 20,
'生产-实验室样本处理数据-导出', 'production:labSampleProcess:list'
) btn ON btn.parent_perms = m.perms
WHERE m.del_flag = 0 AND m.status = '1'
AND NOT EXISTS (
SELECT 1 FROM sys_menu e
WHERE e.tenant_no = m.tenant_no AND e.parent_id = m.id
AND e.perms = btn.perms AND e.del_flag = 0
);
-- ── 5) 按顶级大菜单授权对应入口(含列表/补录/导出)─────────────────────────
INSERT INTO sys_role_menu (
id, role_id, menu_id, tenant_no, order_num, remark,
create_by, create_dept_id, create_time, update_by, update_time, del_flag
)
SELECT
INSERT(INSERT(MD5(CONCAT('lab-sp-rm:', r.tenant_no, ':', r.id, ':', m.id)), 13, 1, '3'), 17, 1, '8'),
r.id, m.id, r.tenant_no, NULL,
CONCAT('issue#102 grant from ', map.top_perms),
'migration', '', NOW(), 'migration', NOW(), 0
FROM (
SELECT 'menu:market' AS top_perms, 'cellStorage:labSampleProcess:list' AS list_perms
UNION ALL SELECT 'menu:market', 'cellStorage:labSampleProcess:supplement'
UNION ALL SELECT 'menu:market', 'cellStorage:labSampleProcess:export'
UNION ALL SELECT 'menu:production', 'production:labSampleProcess:list'
UNION ALL SELECT 'menu:production', 'production:labSampleProcess:supplement'
UNION ALL SELECT 'menu:production', 'production:labSampleProcess:export'
UNION ALL SELECT 'menu:quality', 'biz:labSampleProcess:list'
UNION ALL SELECT 'menu:quality', 'biz:labSampleProcess:supplement'
UNION ALL SELECT 'menu:quality', 'biz:labSampleProcess:export'
) map
JOIN sys_role r ON r.del_flag = 0
JOIN sys_role_menu src
ON src.role_id = r.id AND src.tenant_no = r.tenant_no AND src.del_flag = 0
JOIN sys_menu top
ON top.id = src.menu_id AND top.tenant_no = src.tenant_no AND top.del_flag = 0
AND top.perms = map.top_perms
JOIN sys_menu m
ON m.tenant_no = r.tenant_no AND m.del_flag = 0 AND m.status = '1'
AND m.perms = map.list_perms
WHERE NOT EXISTS (
SELECT 1 FROM sys_role_menu existing
WHERE existing.role_id = r.id
AND existing.menu_id = m.id
AND existing.tenant_no = r.tenant_no
AND existing.del_flag = 0
);
-- 核对
SELECT p.menu_name AS parent_name, c.menu_name, c.path, c.perms, c.order_num
FROM sys_menu c
JOIN sys_menu p ON p.id = c.parent_id
WHERE c.del_flag = 0
AND (
c.perms LIKE '%labSampleProcess%'
OR (c.menu_name IN ('缴费财务确认', '废弃物管理', '入库放行审核')
AND p.menu_name IN ('存储服务', '生产管理', '质检管理'))
)
ORDER BY p.menu_name, c.order_num, c.menu_name;
@@ -1,12 +0,0 @@
-- 纠正实验室样本处理部门 ACL:
-- 「采集接受人」仅挂在「质检专员」职位上,不应再授予市场字段编辑权,
-- 否则质检人员经职位角色并集会同时可改市场+质检字段。
UPDATE sys_role_menu rm
JOIN sys_role r ON r.id = rm.role_id AND r.del_flag = 0 AND r.role_name = '采集接受人'
JOIN sys_menu m ON m.id = rm.menu_id AND m.del_flag = 0
AND m.perms = 'lab:sample-processing:market:edit'
SET rm.del_flag = 1,
rm.update_by = 'migration',
rm.update_time = NOW()
WHERE rm.del_flag = 0;
@@ -1,120 +0,0 @@
-- 实验室样本处理数据:补充表 + 一级模块菜单/按钮权限(不自动授权角色)
-- MySQL 5.7,可重复执行
CREATE TABLE IF NOT EXISTS biz_lab_sample_processing_extra (
id VARCHAR(64) NOT NULL,
dataset VARCHAR(16) NOT NULL COMMENT 'hsc|ubmc|msc',
sample_code VARCHAR(32) NOT NULL COMMENT '样本编码',
payload_json TEXT NULL COMMENT '补充字段 JSON',
tenant_no VARCHAR(64) NOT NULL,
order_num INT NULL,
remark VARCHAR(512) NULL,
create_by VARCHAR(64) NULL,
create_dept_id VARCHAR(64) NOT NULL DEFAULT '',
create_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
update_by VARCHAR(64) NULL,
update_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
del_flag SMALLINT NOT NULL DEFAULT 0,
PRIMARY KEY (id),
KEY ix_lab_sample_extra_tenant_ds_code (tenant_no, dataset, sample_code, del_flag)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- 挂到与「质检」同一 Web 虚拟根下(复用 menu:quality 的 parent_id)
INSERT INTO sys_menu (
id, menu_name, parent_id, menu_type, path, component, perms,
is_frame, visible, status, tenant_no, order_num, remark,
create_by, create_dept_id, create_time, update_by, update_time, del_flag
)
SELECT
MD5(CONCAT(quality.tenant_no, ':menu:lab-sample-processing')),
'实验室样本处理数据', quality.parent_id, 'M', '/lab-sample-processing', '/index/index',
'menu:lab-sample-processing', 1, '1', '1', quality.tenant_no,
COALESCE(quality.order_num, 50) + 1,
'20261104 会议:造血/单个核/间充质台账',
'migration', '', NOW(), 'migration', NOW(), 0
FROM sys_menu quality
WHERE quality.perms = 'menu:quality' AND quality.del_flag = 0 AND quality.status = '1'
AND NOT EXISTS (
SELECT 1 FROM sys_menu e
WHERE e.tenant_no = quality.tenant_no AND e.perms = 'menu:lab-sample-processing' AND e.del_flag = 0
);
INSERT INTO sys_menu (
id, menu_name, parent_id, menu_type, path, component, perms,
is_frame, visible, status, tenant_no, order_num, remark,
create_by, create_dept_id, create_time, update_by, update_time, del_flag
)
SELECT
MD5(CONCAT(p.tenant_no, ':lab:sample-processing:list')),
'造血干细胞数据', p.id, 'C', 'lab-sample-processing/hsc',
'/lab-sample-processing/hsc/index', 'lab:sample-processing:list',
1, '1', '1', p.tenant_no, 10, '造血干细胞数据列表',
'migration', '', NOW(), 'migration', NOW(), 0
FROM sys_menu p
WHERE p.perms = 'menu:lab-sample-processing' AND p.del_flag = 0 AND p.status = '1'
AND NOT EXISTS (
SELECT 1 FROM sys_menu e
WHERE e.tenant_no = p.tenant_no AND e.path = 'lab-sample-processing/hsc' AND e.del_flag = 0
);
INSERT INTO sys_menu (
id, menu_name, parent_id, menu_type, path, component, perms,
is_frame, visible, status, tenant_no, order_num, remark,
create_by, create_dept_id, create_time, update_by, update_time, del_flag
)
SELECT
MD5(CONCAT(p.tenant_no, ':lab:sample-processing:ubmc')),
'单个核数据', p.id, 'C', 'lab-sample-processing/ubmc',
'/lab-sample-processing/ubmc/index', 'lab:sample-processing:list',
1, '1', '1', p.tenant_no, 20, '单个核数据列表',
'migration', '', NOW(), 'migration', NOW(), 0
FROM sys_menu p
WHERE p.perms = 'menu:lab-sample-processing' AND p.del_flag = 0 AND p.status = '1'
AND NOT EXISTS (
SELECT 1 FROM sys_menu e
WHERE e.tenant_no = p.tenant_no AND e.path = 'lab-sample-processing/ubmc' AND e.del_flag = 0
);
INSERT INTO sys_menu (
id, menu_name, parent_id, menu_type, path, component, perms,
is_frame, visible, status, tenant_no, order_num, remark,
create_by, create_dept_id, create_time, update_by, update_time, del_flag
)
SELECT
MD5(CONCAT(p.tenant_no, ':lab:sample-processing:msc')),
'脐带间充质干细胞数据', p.id, 'C', 'lab-sample-processing/msc',
'/lab-sample-processing/msc/index', 'lab:sample-processing:list',
1, '1', '1', p.tenant_no, 30, '脐带间充质干细胞数据列表',
'migration', '', NOW(), 'migration', NOW(), 0
FROM sys_menu p
WHERE p.perms = 'menu:lab-sample-processing' AND p.del_flag = 0 AND p.status = '1'
AND NOT EXISTS (
SELECT 1 FROM sys_menu e
WHERE e.tenant_no = p.tenant_no AND e.path = 'lab-sample-processing/msc' AND e.del_flag = 0
);
-- 编辑按钮挂在列表菜单下(三页共用同一 list 权限父节点:造血页)
INSERT INTO sys_menu (
id, menu_name, parent_id, menu_type, path, component, perms,
is_frame, visible, status, tenant_no, order_num, remark,
create_by, create_dept_id, create_time, update_by, update_time, del_flag
)
SELECT
MD5(CONCAT(p.tenant_no, ':', btn.perms)),
btn.menu_name, p.id, 'F', '', NULL, btn.perms,
1, '0', '1', p.tenant_no, btn.order_num, btn.remark,
'migration', '', NOW(), 'migration', NOW(), 0
FROM sys_menu p
JOIN (
SELECT '市场字段编辑' AS menu_name, 'lab:sample-processing:market:edit' AS perms, 1 AS order_num, '仅可编辑市场部门字段' AS remark
UNION ALL SELECT '生产字段编辑', 'lab:sample-processing:production:edit', 2, '仅可编辑生产部门字段'
UNION ALL SELECT '质检字段编辑', 'lab:sample-processing:qc:edit', 3, '仅可编辑质检部门字段'
UNION ALL SELECT '部门主管', 'lab:sample-processing:manager', 4, '可编辑全部部门字段'
) btn
WHERE p.perms = 'lab:sample-processing:list'
AND p.path = 'lab-sample-processing/hsc'
AND p.del_flag = 0 AND p.status = '1'
AND NOT EXISTS (
SELECT 1 FROM sys_menu e
WHERE e.tenant_no = p.tenant_no AND e.perms = btn.perms AND e.del_flag = 0
);
@@ -0,0 +1,277 @@
-- UC 入库编码自动派发:脐带MSC原代培养(内置模版)5 步
-- 步骤:原代培养 → 半换液 → 二次贴壁 → 重铺 → 冻存(不含传代)
-- 内容从既有「干细胞培养(内置模版)」/ MSC培养-BUILTIN 按 process_code 拷贝
-- 幂等:已存在同名内置集合则跳过主数据创建-- 兼容:跨表比较统一 COLLATE utf8mb4_unicode_ci,避免 unicode_ci/general_ci 混用失败
-- 生产历史空任务工单回补(二选一,勿重复对同一工单各跑一遍):
-- SQL:docs/sql/migrations/2026-11-13-uc-msc-production-task-backfill.sql
-- 或 Python:
-- cd backend && python -m scripts.backfill_uc_msc_production_tasks
-- cd backend && python -m scripts.backfill_uc_msc_production_tasks --apply
SET NAMES utf8mb4;
-- 1) 工艺路线头
INSERT INTO biz_process_route (
id, route_code, route_name, product_type_id, version, is_current,
equipment_ids, equipment_name, tenant_no, order_num, remark, is_builtin,
create_by, create_dept_id, create_time, update_by, update_time, del_flag
)
SELECT
'UCMSCROUTEA5CC11F194118AC54085447A',
'MSC原代-UC-BUILTIN',
'脐带MSC原代培养(内置模版)',
src.product_type_id,
src.version,
'0',
src.equipment_ids,
src.equipment_name,
src.tenant_no,
0,
'内置模版:UC 入库编码自动派发(5 步,不含传代)',
'1',
src.create_by,
IFNULL(src.create_dept_id, ''),
NOW(),
src.update_by,
NOW(),
0
FROM biz_process_route src
WHERE src.del_flag = 0
AND (
src.route_code = 'MSC培养-BUILTIN'
OR (src.route_name = '干细胞培养(内置模版)' AND src.is_builtin = '1')
)
AND NOT EXISTS (
SELECT 1 FROM biz_process_route x
WHERE x.id = 'UCMSCROUTEA5CC11F194118AC54085447A' AND x.del_flag = 0
)
AND NOT EXISTS (
SELECT 1 FROM biz_process_route x
WHERE x.tenant_no COLLATE utf8mb4_unicode_ci = src.tenant_no COLLATE utf8mb4_unicode_ci
AND x.route_code = 'MSC原代-UC-BUILTIN'
AND x.del_flag = 0
)
ORDER BY CASE WHEN src.route_code = 'MSC培养-BUILTIN' THEN 0 ELSE 1 END
LIMIT 1;
-- 2) 路线步骤(按目标顺序)
-- step 1 SOP-SC-003
INSERT INTO biz_process_route_step (
id, route_id, process_id, step_order, process_code, category_id, process_name,
description, equipment_ids, equipment_name, estimated_duration, sop_ids, sop_content,
tenant_no, order_num, remark, create_by, create_dept_id, create_time, update_by, update_time, del_flag
)
SELECT
'UCMSCSTEP1A5CC11F194118AC54085447A',
'UCMSCROUTEA5CC11F194118AC54085447A',
s.process_id, 1, s.process_code, s.category_id, s.process_name,
s.description, s.equipment_ids, s.equipment_name, s.estimated_duration, s.sop_ids, s.sop_content,
s.tenant_no, 1, s.remark, s.create_by, IFNULL(s.create_dept_id, ''), NOW(), s.update_by, NOW(), 0
FROM biz_process_route_step s
JOIN biz_process_route r
ON r.id COLLATE utf8mb4_unicode_ci = s.route_id COLLATE utf8mb4_unicode_ci
AND r.del_flag = 0
WHERE s.del_flag = 0
AND s.process_code = 'SOP-SC-003-E01-01'
AND (
r.route_code = 'MSC培养-BUILTIN'
OR (r.route_name = '干细胞培养(内置模版)' AND r.is_builtin = '1')
)
AND EXISTS (
SELECT 1 FROM biz_process_route nr
WHERE nr.id = 'UCMSCROUTEA5CC11F194118AC54085447A' AND nr.del_flag = 0
)
AND NOT EXISTS (
SELECT 1 FROM biz_process_route_step x
WHERE x.id = 'UCMSCSTEP1A5CC11F194118AC54085447A' AND x.del_flag = 0
)
LIMIT 1;
-- step 2 SOP-SC-004
INSERT INTO biz_process_route_step (
id, route_id, process_id, step_order, process_code, category_id, process_name,
description, equipment_ids, equipment_name, estimated_duration, sop_ids, sop_content,
tenant_no, order_num, remark, create_by, create_dept_id, create_time, update_by, update_time, del_flag
)
SELECT
'UCMSCSTEP2A5CC11F194118AC54085447A',
'UCMSCROUTEA5CC11F194118AC54085447A',
s.process_id, 2, s.process_code, s.category_id, s.process_name,
s.description, s.equipment_ids, s.equipment_name, s.estimated_duration, s.sop_ids, s.sop_content,
s.tenant_no, 2, s.remark, s.create_by, IFNULL(s.create_dept_id, ''), NOW(), s.update_by, NOW(), 0
FROM biz_process_route_step s
JOIN biz_process_route r
ON r.id COLLATE utf8mb4_unicode_ci = s.route_id COLLATE utf8mb4_unicode_ci
AND r.del_flag = 0
WHERE s.del_flag = 0
AND s.process_code = 'SOP-SC-004-E01-01'
AND (
r.route_code = 'MSC培养-BUILTIN'
OR (r.route_name = '干细胞培养(内置模版)' AND r.is_builtin = '1')
)
AND EXISTS (
SELECT 1 FROM biz_process_route nr
WHERE nr.id = 'UCMSCROUTEA5CC11F194118AC54085447A' AND nr.del_flag = 0
)
AND NOT EXISTS (
SELECT 1 FROM biz_process_route_step x
WHERE x.id = 'UCMSCSTEP2A5CC11F194118AC54085447A' AND x.del_flag = 0
)
LIMIT 1;
-- step 3 SOP-SC-006 二次贴壁
INSERT INTO biz_process_route_step (
id, route_id, process_id, step_order, process_code, category_id, process_name,
description, equipment_ids, equipment_name, estimated_duration, sop_ids, sop_content,
tenant_no, order_num, remark, create_by, create_dept_id, create_time, update_by, update_time, del_flag
)
SELECT
'UCMSCSTEP3A5CC11F194118AC54085447A',
'UCMSCROUTEA5CC11F194118AC54085447A',
s.process_id, 3, s.process_code, s.category_id, s.process_name,
s.description, s.equipment_ids, s.equipment_name, s.estimated_duration, s.sop_ids, s.sop_content,
s.tenant_no, 3, s.remark, s.create_by, IFNULL(s.create_dept_id, ''), NOW(), s.update_by, NOW(), 0
FROM biz_process_route_step s
JOIN biz_process_route r
ON r.id COLLATE utf8mb4_unicode_ci = s.route_id COLLATE utf8mb4_unicode_ci
AND r.del_flag = 0
WHERE s.del_flag = 0
AND s.process_code = 'SOP-SC-006-E01-01'
AND (
r.route_code = 'MSC培养-BUILTIN'
OR (r.route_name = '干细胞培养(内置模版)' AND r.is_builtin = '1')
)
AND EXISTS (
SELECT 1 FROM biz_process_route nr
WHERE nr.id = 'UCMSCROUTEA5CC11F194118AC54085447A' AND nr.del_flag = 0
)
AND NOT EXISTS (
SELECT 1 FROM biz_process_route_step x
WHERE x.id = 'UCMSCSTEP3A5CC11F194118AC54085447A' AND x.del_flag = 0
)
LIMIT 1;
-- step 4 SOP-SC-005 重铺
INSERT INTO biz_process_route_step (
id, route_id, process_id, step_order, process_code, category_id, process_name,
description, equipment_ids, equipment_name, estimated_duration, sop_ids, sop_content,
tenant_no, order_num, remark, create_by, create_dept_id, create_time, update_by, update_time, del_flag
)
SELECT
'UCMSCSTEP4A5CC11F194118AC54085447A',
'UCMSCROUTEA5CC11F194118AC54085447A',
s.process_id, 4, s.process_code, s.category_id, s.process_name,
s.description, s.equipment_ids, s.equipment_name, s.estimated_duration, s.sop_ids, s.sop_content,
s.tenant_no, 4, s.remark, s.create_by, IFNULL(s.create_dept_id, ''), NOW(), s.update_by, NOW(), 0
FROM biz_process_route_step s
JOIN biz_process_route r
ON r.id COLLATE utf8mb4_unicode_ci = s.route_id COLLATE utf8mb4_unicode_ci
AND r.del_flag = 0
WHERE s.del_flag = 0
AND s.process_code = 'SOP-SC-005-E01-01'
AND (
r.route_code = 'MSC培养-BUILTIN'
OR (r.route_name = '干细胞培养(内置模版)' AND r.is_builtin = '1')
)
AND EXISTS (
SELECT 1 FROM biz_process_route nr
WHERE nr.id = 'UCMSCROUTEA5CC11F194118AC54085447A' AND nr.del_flag = 0
)
AND NOT EXISTS (
SELECT 1 FROM biz_process_route_step x
WHERE x.id = 'UCMSCSTEP4A5CC11F194118AC54085447A' AND x.del_flag = 0
)
LIMIT 1;
-- step 5 SOP-SC-008 冻存
INSERT INTO biz_process_route_step (
id, route_id, process_id, step_order, process_code, category_id, process_name,
description, equipment_ids, equipment_name, estimated_duration, sop_ids, sop_content,
tenant_no, order_num, remark, create_by, create_dept_id, create_time, update_by, update_time, del_flag
)
SELECT
'UCMSCSTEP5A5CC11F194118AC54085447A',
'UCMSCROUTEA5CC11F194118AC54085447A',
s.process_id, 5, s.process_code, s.category_id, s.process_name,
s.description, s.equipment_ids, s.equipment_name, s.estimated_duration, s.sop_ids, s.sop_content,
s.tenant_no, 5, s.remark, s.create_by, IFNULL(s.create_dept_id, ''), NOW(), s.update_by, NOW(), 0
FROM biz_process_route_step s
JOIN biz_process_route r
ON r.id COLLATE utf8mb4_unicode_ci = s.route_id COLLATE utf8mb4_unicode_ci
AND r.del_flag = 0
WHERE s.del_flag = 0
AND s.process_code = 'SOP-SC-008-E01-01'
AND (
r.route_code = 'MSC培养-BUILTIN'
OR (r.route_name = '干细胞培养(内置模版)' AND r.is_builtin = '1')
)
AND EXISTS (
SELECT 1 FROM biz_process_route nr
WHERE nr.id = 'UCMSCROUTEA5CC11F194118AC54085447A' AND nr.del_flag = 0
)
AND NOT EXISTS (
SELECT 1 FROM biz_process_route_step x
WHERE x.id = 'UCMSCSTEP5A5CC11F194118AC54085447A' AND x.del_flag = 0
)
LIMIT 1;
-- 3) 任务组合头
INSERT INTO biz_production_task_set (
id, set_name, status, tenant_no, order_num, remark, is_builtin,
create_by, create_dept_id, create_time, update_by, update_time, del_flag
)
SELECT
'UCMSCSET00A5CC11F194118AC54085447A',
'脐带MSC原代培养(内置模版)',
'1',
r.tenant_no,
0,
'内置模版:UC 入库编码自动派发',
'1',
r.create_by,
IFNULL(r.create_dept_id, ''),
NOW(),
r.update_by,
NOW(),
0
FROM biz_process_route r
WHERE r.id = 'UCMSCROUTEA5CC11F194118AC54085447A'
AND r.del_flag = 0
AND NOT EXISTS (
SELECT 1 FROM biz_production_task_set x
WHERE x.tenant_no COLLATE utf8mb4_unicode_ci = r.tenant_no COLLATE utf8mb4_unicode_ci
AND x.set_name = '脐带MSC原代培养(内置模版)'
AND x.is_builtin = '1'
AND x.del_flag = 0
);
-- 4) 任务组合条目
INSERT INTO biz_production_task_set_item (
id, set_id, task_name, route_id, route_name, description, remark,
tenant_no, order_num, create_by, create_dept_id, create_time, update_by, update_time, del_flag
)
SELECT
'UCMSCITEM0A5CC11F194118AC54085447A',
s.id,
'{lab_storage_code}样本处理',
'UCMSCROUTEA5CC11F194118AC54085447A',
'脐带MSC原代培养(内置模版)',
'脐带MSC原代培养(内置模版)',
NULL,
s.tenant_no,
1,
s.create_by,
IFNULL(s.create_dept_id, ''),
NOW(),
s.update_by,
NOW(),
0
FROM biz_production_task_set s
WHERE s.set_name = '脐带MSC原代培养(内置模版)'
AND s.is_builtin = '1'
AND s.del_flag = 0
AND NOT EXISTS (
SELECT 1 FROM biz_production_task_set_item x
WHERE x.set_id COLLATE utf8mb4_unicode_ci = s.id COLLATE utf8mb4_unicode_ci
AND x.del_flag = 0
);
@@ -0,0 +1,424 @@
-- 【一次性回补】UC 开头实验室入库编码 → 补派「脐带MSC原代培养」5 步生产任务
-- 与种子脚本分开:先执行 2026-11-13-uc-msc-builtin-task-set.sql(或确保模版已存在),再执行本文件。
-- 等价于 backend/scripts/backfill_uc_msc_production_tasks.py --apply 的候选范围。
--
-- 候选条件(须全部满足):
-- 1) 样本接收 accept_conclusion=js、del_flag=0
-- 2) lab_storage_code 以 UC/uc 开头(非空)
-- 3) 关联入库生产工单 work_order_type=inbound、状态 dpz/jxz、del_flag=0
-- 4) 该工单当前无任何有效生产任务(已有任务如 UC2026010 跳过)
--
-- 动作:
-- - 每工单插入 1 条 biz_production_task(状态 dpz,任务名 {入库编码}样本处理)
-- - 从 UC 内置路线复制 5 个步骤到 biz_production_task_step(及试剂/耗材/产出/采集子表)
-- - 工单状态 dpz → jxz(已是 jxz/ywc 的不改 ywc;本脚本候选不含 ywc)
--
-- 幂等:已有有效任务的工单不会进入候选;重复执行影响行数应为 0。
-- 前置:biz_process_route.route_code='MSC原代-UC-BUILTIN'(或固定 id UCMSCROUTE…)及 5 步须已存在。
-- MySQL 5.7 / utf8mb4。未在生产库执行;执行前请先跑下方「预览」SELECT。
-- 兼容:
-- 1) 跨表等值统一 COLLATE utf8mb4_general_ci,避免 unicode_ci/general_ci 混用失败
-- 2) 多行 ID 用 MD5(业务键) 生成,避免同语句多行 UUID() 撞主键
-- 3) task_no 序号用 UNSIGNED 整数拼接,避免用户变量浮点变成 RW…2.00
SET NAMES utf8mb4;
-- ---------------------------------------------------------------------------
-- 0. 解析 UC 内置工艺路线
-- ---------------------------------------------------------------------------
SET @uc_route_id := (
SELECT r.id
FROM biz_process_route r
WHERE r.del_flag = 0
AND (
r.id = 'UCMSCROUTEA5CC11F194118AC54085447A'
OR r.route_code = 'MSC原代-UC-BUILTIN'
OR (r.route_name = '脐带MSC原代培养(内置模版)' AND r.is_builtin = '1')
)
ORDER BY
CASE
WHEN r.id = 'UCMSCROUTEA5CC11F194118AC54085447A' THEN 0
WHEN r.route_code = 'MSC原代-UC-BUILTIN' THEN 1
ELSE 2
END
LIMIT 1
);
SET @uc_step_count := (
SELECT COUNT(*)
FROM biz_process_route_step s
WHERE s.route_id COLLATE utf8mb4_unicode_ci = @uc_route_id COLLATE utf8mb4_unicode_ci
AND s.del_flag = 0
);
-- 预览:模版是否就绪(应 route 非空且 step_count=5)
SELECT @uc_route_id AS uc_route_id, @uc_step_count AS uc_step_count;
-- 若模版未就绪则主动失败(避免插入无步骤任务)
SET @uc_ready := IF(@uc_route_id IS NOT NULL AND @uc_step_count = 5, 1, 0);
-- 下面用 @uc_ready 约束所有写操作;为 0 时 INSERT 选不出行
-- ---------------------------------------------------------------------------
-- 1. 候选工单临时表
-- ---------------------------------------------------------------------------
DROP TEMPORARY TABLE IF EXISTS tmp_uc_wo_backfill;
CREATE TEMPORARY TABLE tmp_uc_wo_backfill (
seq INT NOT NULL AUTO_INCREMENT,
work_order_id VARCHAR(64) NOT NULL,
reception_id VARCHAR(64) NOT NULL,
lab_storage_code VARCHAR(32) NOT NULL,
tenant_no VARCHAR(64) NOT NULL,
sample_code VARCHAR(32) NULL,
task_id VARCHAR(64) NULL,
task_no VARCHAR(32) NULL,
route_id VARCHAR(64) NULL,
PRIMARY KEY (seq),
UNIQUE KEY uk_wo (work_order_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
INSERT INTO tmp_uc_wo_backfill (
work_order_id, reception_id, lab_storage_code, tenant_no, sample_code, route_id
)
SELECT
wo.id,
rec.id,
TRIM(rec.lab_storage_code),
wo.tenant_no,
wo.sample_code,
@uc_route_id
FROM biz_production_work_order wo
INNER JOIN biz_sample_reception rec
ON rec.id COLLATE utf8mb4_general_ci = wo.reception_id COLLATE utf8mb4_general_ci
AND rec.tenant_no COLLATE utf8mb4_general_ci = wo.tenant_no COLLATE utf8mb4_general_ci
AND rec.del_flag = 0
WHERE @uc_ready = 1
AND wo.del_flag = 0
AND wo.work_order_type = 'inbound'
AND wo.work_order_status IN ('dpz', 'jxz')
AND rec.accept_conclusion = 'js'
AND rec.lab_storage_code IS NOT NULL
AND TRIM(rec.lab_storage_code) <> ''
AND (
rec.lab_storage_code LIKE 'UC%'
OR rec.lab_storage_code LIKE 'uc%'
)
AND NOT EXISTS (
SELECT 1
FROM biz_production_task t
WHERE t.work_order_id COLLATE utf8mb4_general_ci = wo.id COLLATE utf8mb4_general_ci
AND t.tenant_no COLLATE utf8mb4_general_ci = wo.tenant_no COLLATE utf8mb4_general_ci
AND t.del_flag = 0
)
ORDER BY rec.reception_time ASC, wo.create_time ASC;
-- 预览候选(执行写库前请核对)
SELECT
seq,
work_order_id,
lab_storage_code,
sample_code,
tenant_no,
reception_id
FROM tmp_uc_wo_backfill
ORDER BY seq;
SELECT COUNT(*) AS candidate_count FROM tmp_uc_wo_backfill;
-- 分配 task_id / task_no(RW + yyyymmdd + 4 位序号,接当日已有最大序号)
SET @task_day := DATE_FORMAT(NOW(), '%Y%m%d');
SET @task_no_base := (
SELECT IFNULL(MAX(CAST(SUBSTRING(t.task_no, 11) AS UNSIGNED)), 0)
FROM biz_production_task t
WHERE t.task_no REGEXP CONCAT('^RW', @task_day, '[0-9]{4}$')
);
SET @task_no_base := CAST(IFNULL(@task_no_base, 0) AS UNSIGNED);
UPDATE tmp_uc_wo_backfill
SET
task_id = UPPER(MD5(CONCAT('uc-msc-backfill-task:', work_order_id))),
task_no = CONCAT('RW', @task_day, LPAD(@task_no_base + seq, 4, '0'));
-- ---------------------------------------------------------------------------
-- 2. 插入生产任务
-- ---------------------------------------------------------------------------
INSERT INTO biz_production_task (
id, task_no, work_order_id, order_source, task_type, task_name, description,
route_id, task_status, current_assignee_user_id, started_time, completed_time,
conclusion, remark, attachments, equipment_ids, equipment_name,
tenant_no, order_num, create_by, create_dept_id, create_time, update_by, update_time, del_flag
)
SELECT
c.task_id,
c.task_no,
c.work_order_id,
'inbound',
'cell_storage',
CONCAT(c.lab_storage_code, '样本处理'),
'脐带MSC原代培养(内置模版)',
c.route_id,
'dpz',
NULL,
NULL,
NULL,
NULL,
'一次性SQL回补:UC入库编码自动派发',
NULL,
r.equipment_ids,
r.equipment_name,
c.tenant_no,
0,
NULL,
'',
NOW(),
NULL,
NOW(),
0
FROM tmp_uc_wo_backfill c
INNER JOIN biz_process_route r
ON r.id COLLATE utf8mb4_unicode_ci = c.route_id COLLATE utf8mb4_unicode_ci
AND r.del_flag = 0
WHERE @uc_ready = 1
AND c.task_id IS NOT NULL
AND NOT EXISTS (
SELECT 1 FROM biz_production_task t
WHERE t.work_order_id COLLATE utf8mb4_general_ci = c.work_order_id COLLATE utf8mb4_general_ci
AND t.tenant_no COLLATE utf8mb4_general_ci = c.tenant_no COLLATE utf8mb4_general_ci
AND t.del_flag = 0
);
-- ---------------------------------------------------------------------------
-- 3. 步骤映射:路线步骤 → 新任务步骤 ID
-- ---------------------------------------------------------------------------
DROP TEMPORARY TABLE IF EXISTS tmp_uc_step_map;
CREATE TEMPORARY TABLE tmp_uc_step_map (
task_id VARCHAR(64) NOT NULL,
work_order_id VARCHAR(64) NOT NULL,
tenant_no VARCHAR(64) NOT NULL,
route_step_id VARCHAR(64) NOT NULL,
task_step_id VARCHAR(64) NOT NULL,
step_order INT NOT NULL,
PRIMARY KEY (task_id, route_step_id),
KEY ix_route_step (route_step_id),
KEY ix_task_step (task_step_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
INSERT INTO tmp_uc_step_map (
task_id, work_order_id, tenant_no, route_step_id, task_step_id, step_order
)
SELECT
c.task_id,
c.work_order_id,
c.tenant_no,
rs.id,
UPPER(MD5(CONCAT('uc-msc-backfill-step:', c.work_order_id, ':', rs.id))),
rs.step_order
FROM tmp_uc_wo_backfill c
INNER JOIN biz_process_route_step rs
ON rs.route_id COLLATE utf8mb4_unicode_ci = c.route_id COLLATE utf8mb4_unicode_ci
AND rs.del_flag = 0
WHERE @uc_ready = 1
AND EXISTS (
SELECT 1 FROM biz_production_task t
WHERE t.id COLLATE utf8mb4_general_ci = c.task_id COLLATE utf8mb4_general_ci
AND t.del_flag = 0
);
-- ---------------------------------------------------------------------------
-- 4. 插入任务步骤
-- ---------------------------------------------------------------------------
INSERT INTO biz_production_task_step (
id, task_id, step_order, process_code, category_id, process_name, description,
equipment_ids, equipment_name, estimated_duration, actual_duration,
sop_ids, sop_content, step_status, planned_start_time, started_time,
completed_time, completed_by, tenant_no, order_num, remark,
create_by, create_dept_id, create_time, update_by, update_time, del_flag
)
SELECT
m.task_step_id,
m.task_id,
rs.step_order,
rs.process_code,
rs.category_id,
rs.process_name,
rs.description,
rs.equipment_ids,
rs.equipment_name,
rs.estimated_duration,
NULL,
rs.sop_ids,
rs.sop_content,
'dzx',
NULL,
NULL,
NULL,
NULL,
m.tenant_no,
IFNULL(rs.order_num, rs.step_order),
NULL,
NULL,
'',
NOW(),
NULL,
NOW(),
0
FROM tmp_uc_step_map m
INNER JOIN biz_process_route_step rs
ON rs.id COLLATE utf8mb4_unicode_ci = m.route_step_id COLLATE utf8mb4_unicode_ci
AND rs.del_flag = 0
WHERE NOT EXISTS (
SELECT 1 FROM biz_production_task_step x
WHERE x.id COLLATE utf8mb4_general_ci = m.task_step_id COLLATE utf8mb4_general_ci
);
-- ---------------------------------------------------------------------------
-- 5. 复制路线步骤子表 → 任务步骤子表
-- ---------------------------------------------------------------------------
INSERT INTO biz_production_task_step_reagent (
id, step_id, reagent_code, reagent_name, spec, standard_usage, unit,
is_key_material, tenant_no, order_num, remark,
create_by, create_dept_id, create_time, update_by, update_time, del_flag
)
SELECT
UPPER(MD5(CONCAT('uc-msc-backfill-reag:', m.task_step_id, ':', src.id))),
m.task_step_id,
src.reagent_code,
src.reagent_name,
src.spec,
src.standard_usage,
src.unit,
src.is_key_material,
m.tenant_no,
src.order_num,
src.remark,
NULL,
'',
NOW(),
NULL,
NOW(),
0
FROM tmp_uc_step_map m
INNER JOIN biz_process_route_step_reagent src
ON src.step_id COLLATE utf8mb4_unicode_ci = m.route_step_id COLLATE utf8mb4_unicode_ci
AND src.del_flag = 0;
INSERT INTO biz_production_task_step_consumable (
id, step_id, consumable_code, consumable_name, spec_model, standard_usage,
unit, is_required, remark, tenant_no, order_num,
create_by, create_dept_id, create_time, update_by, update_time, del_flag
)
SELECT
UPPER(MD5(CONCAT('uc-msc-backfill-cons:', m.task_step_id, ':', src.id))),
m.task_step_id,
src.consumable_code,
src.consumable_name,
src.spec_model,
src.standard_usage,
src.unit,
src.is_required,
src.remark,
m.tenant_no,
src.order_num,
NULL,
'',
NOW(),
NULL,
NOW(),
0
FROM tmp_uc_step_map m
INNER JOIN biz_process_route_step_consumable src
ON src.step_id COLLATE utf8mb4_unicode_ci = m.route_step_id COLLATE utf8mb4_unicode_ci
AND src.del_flag = 0;
INSERT INTO biz_production_task_step_output (
id, step_id, output_type_id, output_name, output_barcode,
tenant_no, order_num, remark,
create_by, create_dept_id, create_time, update_by, update_time, del_flag
)
SELECT
UPPER(MD5(CONCAT('uc-msc-backfill-out:', m.task_step_id, ':', src.id))),
m.task_step_id,
src.output_type_id,
src.output_name,
src.output_barcode,
m.tenant_no,
src.order_num,
src.remark,
NULL,
'',
NOW(),
NULL,
NOW(),
0
FROM tmp_uc_step_map m
INNER JOIN biz_process_route_step_output src
ON src.step_id COLLATE utf8mb4_unicode_ci = m.route_step_id COLLATE utf8mb4_unicode_ci
AND src.del_flag = 0;
INSERT INTO biz_production_task_step_data_collection (
id, step_id, collection_name, unit, tenant_no, order_num, remark,
create_by, create_dept_id, create_time, update_by, update_time, del_flag
)
SELECT
UPPER(MD5(CONCAT('uc-msc-backfill-dc:', m.task_step_id, ':', src.id))),
m.task_step_id,
src.collection_name,
src.unit,
m.tenant_no,
src.order_num,
src.remark,
NULL,
'',
NOW(),
NULL,
NOW(),
0
FROM tmp_uc_step_map m
INNER JOIN biz_process_route_step_data_collection src
ON src.step_id COLLATE utf8mb4_unicode_ci = m.route_step_id COLLATE utf8mb4_unicode_ci
AND src.del_flag = 0;
-- ---------------------------------------------------------------------------
-- 6. 回写工单状态:有任务则 jxz(不改 ywc)
-- ---------------------------------------------------------------------------
UPDATE biz_production_work_order wo
INNER JOIN tmp_uc_wo_backfill c
ON c.work_order_id COLLATE utf8mb4_general_ci = wo.id COLLATE utf8mb4_general_ci
SET
wo.work_order_status = 'jxz',
wo.update_time = NOW()
WHERE wo.del_flag = 0
AND wo.work_order_status = 'dpz'
AND EXISTS (
SELECT 1 FROM biz_production_task t
WHERE t.work_order_id COLLATE utf8mb4_general_ci = wo.id COLLATE utf8mb4_general_ci
AND t.tenant_no COLLATE utf8mb4_general_ci = wo.tenant_no COLLATE utf8mb4_general_ci
AND t.del_flag = 0
);
-- ---------------------------------------------------------------------------
-- 7. 结果核对
-- ---------------------------------------------------------------------------
SELECT
c.lab_storage_code,
c.work_order_id,
wo.work_order_no,
wo.work_order_status,
t.id AS task_id,
t.task_no,
t.task_name,
(
SELECT COUNT(*)
FROM biz_production_task_step s
WHERE s.task_id COLLATE utf8mb4_general_ci = t.id COLLATE utf8mb4_general_ci
AND s.del_flag = 0
) AS step_count
FROM tmp_uc_wo_backfill c
LEFT JOIN biz_production_work_order wo
ON wo.id COLLATE utf8mb4_general_ci = c.work_order_id COLLATE utf8mb4_general_ci
LEFT JOIN biz_production_task t
ON t.id COLLATE utf8mb4_general_ci = c.task_id COLLATE utf8mb4_general_ci
AND t.del_flag = 0
ORDER BY c.seq;
DROP TEMPORARY TABLE IF EXISTS tmp_uc_step_map;
DROP TEMPORARY TABLE IF EXISTS tmp_uc_wo_backfill;
@@ -0,0 +1,26 @@
-- 软删「中试服务」模块菜单定义(一级及其直接子菜单)。
-- 背景:仅收回 sys_role_menu 后,super_admin 仍因前端静态菜单全量展示可见;
-- 侧栏已对静态路由加 isHide,本脚本同步测试库菜单定义。
-- MySQL 5.7,可重复执行。目标库:测试库(如 zkxw-sc)。
UPDATE sys_menu m
SET m.del_flag = 1,
m.update_by = 'migration',
m.update_time = NOW()
WHERE m.del_flag = 0
AND (
m.id = 'PIL00000000000000000000000000001'
OR m.parent_id = 'PIL00000000000000000000000000001'
OR m.parent_id IN (
SELECT id FROM (
SELECT id FROM sys_menu WHERE parent_id = 'PIL00000000000000000000000000001'
) t
)
);
-- 核对:中试服务树应无有效菜单
SELECT id, menu_name, path, del_flag
FROM sys_menu
WHERE id = 'PIL00000000000000000000000000001'
OR parent_id = 'PIL00000000000000000000000000001'
ORDER BY menu_name;
@@ -0,0 +1,76 @@
-- 撤销所有角色对「中试服务」模块(一级菜单及其子孙)的菜单授权。
-- 范围:menu_name='中试服务' 且 path='pilot-service' 的模块树;
-- 不含市场基础信息中 perms 前缀为 pilot-service: 的其它菜单。
-- 仅软删 sys_role_menu,不删除菜单定义。
-- MySQL 5.7,可重复执行。目标库:测试库(如 zkxw-sc)。
-- 1) 软删角色授权
UPDATE sys_role_menu rm
INNER JOIN (
SELECT m.id AS menu_id
FROM sys_menu m
WHERE m.del_flag = 0
AND (
(m.menu_name = '中试服务' AND m.path = 'pilot-service')
OR m.parent_id IN (
SELECT r.id FROM sys_menu r
WHERE r.del_flag = 0 AND r.menu_name = '中试服务' AND r.path = 'pilot-service'
)
OR m.parent_id IN (
SELECT c.id FROM sys_menu c
WHERE c.del_flag = 0
AND c.parent_id IN (
SELECT r.id FROM sys_menu r
WHERE r.del_flag = 0 AND r.menu_name = '中试服务' AND r.path = 'pilot-service'
)
)
)
) tgt ON tgt.menu_id = rm.menu_id
SET rm.del_flag = 1,
rm.update_by = 'migration',
rm.update_time = NOW()
WHERE rm.del_flag = 0;
-- 2) 核对:中试服务树下有效授权应为 0
SELECT r.role_name, m.menu_name, m.path, m.perms, rm.del_flag
FROM sys_role_menu rm
JOIN sys_role r ON r.id = rm.role_id AND r.del_flag = 0
JOIN sys_menu m ON m.id = rm.menu_id
WHERE rm.del_flag = 0
AND (
(m.menu_name = '中试服务' AND m.path = 'pilot-service')
OR m.parent_id IN (
SELECT x.id FROM sys_menu x
WHERE x.del_flag = 0 AND x.menu_name = '中试服务' AND x.path = 'pilot-service'
)
OR m.parent_id IN (
SELECT c.id FROM sys_menu c
WHERE c.del_flag = 0
AND c.parent_id IN (
SELECT x.id FROM sys_menu x
WHERE x.del_flag = 0 AND x.menu_name = '中试服务' AND x.path = 'pilot-service'
)
)
)
ORDER BY r.role_name, m.menu_name;
SELECT
(SELECT COUNT(*) FROM sys_role_menu rm
JOIN sys_menu m ON m.id = rm.menu_id
WHERE rm.del_flag = 0
AND (
(m.menu_name = '中试服务' AND m.path = 'pilot-service')
OR m.parent_id IN (
SELECT x.id FROM sys_menu x
WHERE x.del_flag = 0 AND x.menu_name = '中试服务' AND x.path = 'pilot-service'
)
OR m.parent_id IN (
SELECT c.id FROM sys_menu c
WHERE c.del_flag = 0
AND c.parent_id IN (
SELECT x.id FROM sys_menu x
WHERE x.del_flag = 0 AND x.menu_name = '中试服务' AND x.path = 'pilot-service'
)
)
)
) AS remaining_active_grants;
@@ -0,0 +1,164 @@
-- 市场模块新增「器械销售」及三个子菜单;授权给已有 menu:market 的角色。
-- 不新建角色/用户;用户经现有 sys_user_role 自动带上菜单。
-- MySQL 5.7,可重复执行。目标库:测试库(如 zkxw-sc)。
-- 1) 二级目录:器械销售(挂在市场下,order_num=6 末位)
INSERT INTO sys_menu (
id, menu_name, parent_id, menu_type, path, component, perms,
is_frame, visible, status, tenant_no, order_num, remark,
create_by, create_dept_id, create_time, update_by, update_time, del_flag
)
SELECT
'DEV00000000000000000000000000001',
'器械销售',
m.id,
'M',
'device-sales',
NULL,
'menu:device-sales',
1, '1', '1', m.tenant_no, 6,
'市场-器械销售',
'migration', '', NOW(), 'migration', NOW(), 0
FROM sys_menu m
WHERE m.del_flag = 0 AND m.perms = 'menu:market'
AND NOT EXISTS (
SELECT 1 FROM sys_menu e
WHERE e.id = 'DEV00000000000000000000000000001' AND e.del_flag = 0
);
-- 2) 子菜单:三类 / 二类 / 化妆品
INSERT INTO sys_menu (
id, menu_name, parent_id, menu_type, path, component, perms,
is_frame, visible, status, tenant_no, order_num, remark,
create_by, create_dept_id, create_time, update_by, update_time, del_flag
)
SELECT
x.id, x.menu_name, 'DEV00000000000000000000000000001', 'C', x.path,
'device-sales/under-construction/index', x.perms,
1, '1', '1', p.tenant_no, x.order_num, x.remark,
'migration', '', NOW(), 'migration', NOW(), 0
FROM sys_menu p
JOIN (
SELECT 'DEV00000000000000000000000000002' AS id, '三类医疗器械' AS menu_name,
'class-iii' AS path, 'device-sales:class-iii:list' AS perms, 1 AS order_num,
'市场-器械销售-三类医疗器械' AS remark
UNION ALL
SELECT 'DEV00000000000000000000000000003', '二类医疗器械',
'class-ii', 'device-sales:class-ii:list', 2,
'市场-器械销售-二类医疗器械'
UNION ALL
SELECT 'DEV00000000000000000000000000004', '化妆品产品',
'cosmetics', 'device-sales:cosmetics:list', 3,
'市场-器械销售-化妆品产品'
) x ON 1 = 1
WHERE p.del_flag = 0 AND p.id = 'DEV00000000000000000000000000001'
AND NOT EXISTS (
SELECT 1 FROM sys_menu e WHERE e.id = x.id AND e.del_flag = 0
);
-- 3) 给已有「市场」顶级菜单授权的角色,授予器械销售目录+三个子菜单
-- (含祖先目录,满足选中子菜单须含祖先)
INSERT INTO sys_role_menu (
id, role_id, menu_id, tenant_no, order_num, remark,
create_by, create_dept_id, create_time, update_by, update_time, del_flag
)
SELECT
INSERT(INSERT(MD5(CONCAT('device-sales-rm:', r.tenant_no, ':', r.id, ':', m.id)), 13, 1, '3'), 17, 1, '8'),
r.id, m.id, r.tenant_no, NULL,
'grant device-sales from menu:market',
'migration', '', NOW(), 'migration', NOW(), 0
FROM sys_role r
JOIN sys_role_menu src
ON src.role_id = r.id AND src.tenant_no = r.tenant_no AND src.del_flag = 0
JOIN sys_menu top
ON top.id = src.menu_id AND top.tenant_no = src.tenant_no AND top.del_flag = 0
AND top.perms = 'menu:market'
JOIN sys_menu m
ON m.tenant_no = r.tenant_no AND m.del_flag = 0 AND m.status = '1'
AND m.id IN (
'DEV00000000000000000000000000001',
'DEV00000000000000000000000000002',
'DEV00000000000000000000000000003',
'DEV00000000000000000000000000004'
)
WHERE r.del_flag = 0
AND NOT EXISTS (
SELECT 1 FROM sys_role_menu existing
WHERE existing.role_id = r.id
AND existing.menu_id = m.id
AND existing.tenant_no = r.tenant_no
AND existing.del_flag = 0
);
-- 3b) 超级管理员同步授予(角色管理勾选与超管侧栏数据一致)
INSERT INTO sys_role_menu (
id, role_id, menu_id, tenant_no, order_num, remark,
create_by, create_dept_id, create_time, update_by, update_time, del_flag
)
SELECT
INSERT(INSERT(MD5(CONCAT('device-sales-sa:', r.tenant_no, ':', r.id, ':', m.id)), 13, 1, '3'), 17, 1, '8'),
r.id, m.id, r.tenant_no, NULL,
'grant device-sales to super admin',
'migration', '', NOW(), 'migration', NOW(), 0
FROM sys_role r
JOIN sys_menu m
ON m.del_flag = 0 AND m.status = '1'
AND m.id IN (
'DEV00000000000000000000000000001',
'DEV00000000000000000000000000002',
'DEV00000000000000000000000000003',
'DEV00000000000000000000000000004'
)
WHERE r.del_flag = 0 AND r.role_name = '超级管理员'
AND NOT EXISTS (
SELECT 1 FROM sys_role_menu existing
WHERE existing.role_id = r.id
AND existing.menu_id = m.id
AND existing.tenant_no = r.tenant_no
AND existing.del_flag = 0
);
-- 3c) 恢复已挂到上述角色、但被软删的用户-角色关联(打通 用户→角色→菜单)
UPDATE sys_user_role ur
JOIN sys_role r ON r.id = ur.role_id AND r.del_flag = 0
JOIN sys_role_menu rm
ON rm.role_id = r.id AND rm.del_flag = 0
AND rm.menu_id = 'DEV00000000000000000000000000001'
JOIN sys_user u ON u.id = ur.user_id AND u.del_flag = 0
SET ur.del_flag = 0,
ur.update_by = 'migration',
ur.update_time = NOW()
WHERE ur.del_flag = 1;
-- 4) 核对
SELECT id, menu_name, parent_id, path, perms, order_num, visible, del_flag
FROM sys_menu
WHERE id LIKE 'DEV0000000000000000000000000000%'
ORDER BY order_num, menu_name;
SELECT COUNT(DISTINCT rm.role_id) AS roles_granted,
COUNT(*) AS role_menu_rows
FROM sys_role_menu rm
WHERE rm.del_flag = 0
AND rm.menu_id IN (
'DEV00000000000000000000000000001',
'DEV00000000000000000000000000002',
'DEV00000000000000000000000000003',
'DEV00000000000000000000000000004'
);
-- 抽样:有市场权限的用户是否能通过角色落到器械销售菜单
SELECT u.nick_name, u.phone_no, r.role_name, m.menu_name, m.perms
FROM sys_user u
JOIN sys_user_role ur ON ur.user_id = u.id AND ur.del_flag = 0
JOIN sys_role r ON r.id = ur.role_id AND r.del_flag = 0
JOIN sys_role_menu rm ON rm.role_id = r.id AND rm.del_flag = 0
JOIN sys_menu m ON m.id = rm.menu_id AND m.del_flag = 0
WHERE u.del_flag = 0
AND m.id IN (
'DEV00000000000000000000000000002',
'DEV00000000000000000000000000003',
'DEV00000000000000000000000000004'
)
ORDER BY u.nick_name, m.order_num
LIMIT 30;
@@ -0,0 +1,59 @@
-- 中试服务:收回全部角色菜单授权,菜单定义保留并设为隐藏。
-- 范围:menu_name='中试服务' 且 path='pilot-service' 的模块树;
-- 不含市场基础信息中 perms 前缀为 pilot-service: 的其它菜单。
-- 不做:不删业务代码;不软删 sys_menu(菜单管理/角色管理仍可见,显示为「隐藏」)。
-- MySQL 5.7,可重复执行。目标库:测试库(如 zkxw-sc)。
-- 目标菜单 ID(中试服务模块树;可按库内实际子节点增补)
-- PIL00000000000000000000000000001 中试服务
-- 80000000000000000000000000000010 中试服务申请单
-- PIL00000000000000000000000000004 出库放行审核
-- 1) 菜单定义:保留记录,visible=0(隐藏)
UPDATE sys_menu
SET visible = '0',
update_by = 'migration',
update_time = NOW()
WHERE del_flag = 0
AND id IN (
'PIL00000000000000000000000000001',
'80000000000000000000000000000010',
'PIL00000000000000000000000000004'
);
-- 2) 软删角色-菜单授权(断开关系)
UPDATE sys_role_menu
SET del_flag = 1,
update_by = 'migration',
update_time = NOW()
WHERE del_flag = 0
AND menu_id IN (
'PIL00000000000000000000000000001',
'80000000000000000000000000000010',
'PIL00000000000000000000000000004'
);
-- 3) 核对
SELECT id, menu_name, path, del_flag, visible
FROM sys_menu
WHERE del_flag = 0
AND (
(menu_name = '中试服务' AND path = 'pilot-service')
OR parent_id IN (
SELECT id FROM sys_menu
WHERE del_flag = 0 AND menu_name = '中试服务' AND path = 'pilot-service'
)
)
ORDER BY menu_name;
SELECT COUNT(*) AS remaining_active_grants
FROM sys_role_menu rm
JOIN sys_menu m ON m.id = rm.menu_id AND m.del_flag = 0
WHERE rm.del_flag = 0
AND (
(m.menu_name = '中试服务' AND m.path = 'pilot-service')
OR m.parent_id IN (
SELECT id FROM sys_menu
WHERE del_flag = 0 AND menu_name = '中试服务' AND path = 'pilot-service'
)
);
@@ -0,0 +1,45 @@
-- 恢复「中试服务」模块菜单定义及此前 migration 软删的角色授权。
-- 对应回滚:2026-11-16-revoke-pilot-service-role-menus.sql、
-- 2026-11-16-hide-pilot-service-menus.sql
-- MySQL 5.7,可重复执行。目标库:测试库(如 zkxw-sc)。
UPDATE sys_menu
SET del_flag = 0,
update_by = 'migration-restore',
update_time = NOW()
WHERE del_flag = 1
AND id IN (
'PIL00000000000000000000000000001',
'80000000000000000000000000000010',
'PIL00000000000000000000000000004'
);
UPDATE sys_role_menu
SET del_flag = 0,
update_by = 'migration-restore',
update_time = NOW()
WHERE del_flag = 1
AND update_by = 'migration'
AND menu_id IN (
'PIL00000000000000000000000000001',
'80000000000000000000000000000010',
'PIL00000000000000000000000000004'
);
SELECT id, menu_name, path, del_flag
FROM sys_menu
WHERE id IN (
'PIL00000000000000000000000000001',
'80000000000000000000000000000010',
'PIL00000000000000000000000000004'
)
ORDER BY menu_name;
SELECT COUNT(*) AS active_grants
FROM sys_role_menu
WHERE del_flag = 0
AND menu_id IN (
'PIL00000000000000000000000000001',
'80000000000000000000000000000010',
'PIL00000000000000000000000000004'
);
@@ -0,0 +1,54 @@
-- Issue #127:已作废 / 属地废弃协议下样本状态回刷为已作废
-- 细胞存储 + 科研捐赠;可重复执行。
-- 规则:协议 status 为 yzf/sdfq 且样本未删除时,sample_status 置 yzf,
-- void_date 为空时按协议 void_time / update_time 补齐 YYYYMMDD。
-- 细胞存储协议样本
UPDATE biz_protocol_sample s
INNER JOIN biz_collection_protocol p
ON p.id = s.collection_protocol_id
AND p.tenant_no = s.tenant_no
AND p.del_flag = 0
SET
s.sample_status = 'yzf',
s.void_date = CASE
WHEN s.void_date IS NOT NULL AND TRIM(s.void_date) <> '' THEN s.void_date
WHEN p.void_time IS NOT NULL THEN DATE_FORMAT(p.void_time, '%Y%m%d')
WHEN p.update_time IS NOT NULL THEN DATE_FORMAT(p.update_time, '%Y%m%d')
ELSE DATE_FORMAT(NOW(), '%Y%m%d')
END,
s.update_time = NOW()
WHERE s.del_flag = 0
AND p.protocol_status IN ('yzf', 'sdfq')
AND (
s.sample_status IS NULL
OR TRIM(s.sample_status) = ''
OR s.sample_status <> 'yzf'
OR s.void_date IS NULL
OR TRIM(s.void_date) = ''
);
-- 科研捐赠样本
UPDATE biz_research_donation_sample s
INNER JOIN biz_research_donation d
ON d.id = s.research_donation_id
AND d.tenant_no = s.tenant_no
AND d.del_flag = 0
SET
s.sample_status = 'yzf',
s.void_date = CASE
WHEN s.void_date IS NOT NULL AND TRIM(s.void_date) <> '' THEN s.void_date
WHEN d.void_time IS NOT NULL THEN DATE_FORMAT(d.void_time, '%Y%m%d')
WHEN d.update_time IS NOT NULL THEN DATE_FORMAT(d.update_time, '%Y%m%d')
ELSE DATE_FORMAT(NOW(), '%Y%m%d')
END,
s.update_time = NOW()
WHERE s.del_flag = 0
AND d.donation_status IN ('yzf', 'sdfq')
AND (
s.sample_status IS NULL
OR TRIM(s.sample_status) = ''
OR s.sample_status <> 'yzf'
OR s.void_date IS NULL
OR TRIM(s.void_date) = ''
);
@@ -0,0 +1,67 @@
-- Issue #129:样本接收结论已为废弃(bj)、但样本状态尚未作废的历史回刷
-- 细胞存储 / 科研捐赠;可重复执行。
-- 仅处理协议仍有效(非 yzf/sdfq)的样本行;已作废协议样本由 #127 回刷脚本覆盖。
-- 细胞存储
UPDATE biz_protocol_sample s
INNER JOIN biz_sample_reception r
ON r.tenant_no = s.tenant_no
AND r.del_flag = 0
AND r.reception_source = 'cell_storage'
AND r.accept_conclusion = 'bj'
AND r.sample_code = s.sample_code
AND r.collection_protocol_id = s.collection_protocol_id
INNER JOIN biz_collection_protocol p
ON p.id = s.collection_protocol_id
AND p.tenant_no = s.tenant_no
AND p.del_flag = 0
SET
s.sample_status = 'yzf',
s.void_date = CASE
WHEN s.void_date IS NOT NULL AND TRIM(s.void_date) <> '' THEN s.void_date
WHEN r.reception_time IS NOT NULL THEN DATE_FORMAT(r.reception_time, '%Y%m%d')
WHEN s.update_time IS NOT NULL THEN DATE_FORMAT(s.update_time, '%Y%m%d')
ELSE DATE_FORMAT(NOW(), '%Y%m%d')
END,
s.update_time = NOW()
WHERE s.del_flag = 0
AND p.protocol_status NOT IN ('yzf', 'sdfq')
AND (
s.sample_status IS NULL
OR TRIM(s.sample_status) = ''
OR s.sample_status <> 'yzf'
OR s.void_date IS NULL
OR TRIM(s.void_date) = ''
);
-- 科研捐赠
UPDATE biz_research_donation_sample s
INNER JOIN biz_sample_reception r
ON r.tenant_no = s.tenant_no
AND r.del_flag = 0
AND r.reception_source = 'research_donation'
AND r.accept_conclusion = 'bj'
AND r.sample_code = s.sample_code
AND r.research_donation_id = s.research_donation_id
INNER JOIN biz_research_donation d
ON d.id = s.research_donation_id
AND d.tenant_no = s.tenant_no
AND d.del_flag = 0
SET
s.sample_status = 'yzf',
s.void_date = CASE
WHEN s.void_date IS NOT NULL AND TRIM(s.void_date) <> '' THEN s.void_date
WHEN r.reception_time IS NOT NULL THEN DATE_FORMAT(r.reception_time, '%Y%m%d')
WHEN s.update_time IS NOT NULL THEN DATE_FORMAT(s.update_time, '%Y%m%d')
ELSE DATE_FORMAT(NOW(), '%Y%m%d')
END,
s.update_time = NOW()
WHERE s.del_flag = 0
AND d.donation_status NOT IN ('yzf', 'sdfq')
AND (
s.sample_status IS NULL
OR TRIM(s.sample_status) = ''
OR s.sample_status <> 'yzf'
OR s.void_date IS NULL
OR TRIM(s.void_date) = ''
);
@@ -0,0 +1,26 @@
-- Issue #131:样本作废原因字段 void_desc
-- 细胞存储 / 科研捐赠样本表;按列是否已存在可重复执行。
SET @db := DATABASE();
SET @exists := (
SELECT COUNT(*) FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 'biz_protocol_sample' AND COLUMN_NAME = 'void_desc'
);
SET @sql := IF(
@exists = 0,
'ALTER TABLE biz_protocol_sample ADD COLUMN void_desc VARCHAR(512) NULL COMMENT ''样本作废原因'' AFTER void_date',
'SELECT 1'
);
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
SET @exists := (
SELECT COUNT(*) FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 'biz_research_donation_sample' AND COLUMN_NAME = 'void_desc'
);
SET @sql := IF(
@exists = 0,
'ALTER TABLE biz_research_donation_sample ADD COLUMN void_desc VARCHAR(512) NULL COMMENT ''样本作废原因'' AFTER void_date',
'SELECT 1'
);
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
@@ -0,0 +1,129 @@
-- 软删【市场】下【中试服务】目录及其子菜单(含按钮),与前端静态路由下线对齐。
-- Issue #158(承接 #156:仅解绑角色对超管侧栏无效)
-- MySQL 5.7,可重复执行;不影响基础实验/临床应用下同名菜单。
-- 0) 预览目标菜单
SELECT
m.tenant_no,
m.id AS menu_id,
m.menu_name,
m.menu_type,
m.perms,
m.parent_id,
m.del_flag
FROM sys_menu m
JOIN (
SELECT pilot.id AS menu_id, pilot.tenant_no
FROM sys_menu market
JOIN sys_menu pilot
ON pilot.parent_id = market.id
AND pilot.tenant_no = market.tenant_no
AND pilot.del_flag = 0
AND pilot.menu_name = '中试服务'
WHERE market.del_flag = 0
AND market.perms = 'menu:market'
UNION
SELECT child.id, child.tenant_no
FROM sys_menu market
JOIN sys_menu pilot
ON pilot.parent_id = market.id
AND pilot.tenant_no = market.tenant_no
AND pilot.del_flag = 0
AND pilot.menu_name = '中试服务'
JOIN sys_menu child
ON child.parent_id = pilot.id
AND child.tenant_no = market.tenant_no
AND child.del_flag = 0
WHERE market.del_flag = 0
AND market.perms = 'menu:market'
UNION
SELECT btn.id, btn.tenant_no
FROM sys_menu market
JOIN sys_menu pilot
ON pilot.parent_id = market.id
AND pilot.tenant_no = market.tenant_no
AND pilot.del_flag = 0
AND pilot.menu_name = '中试服务'
JOIN sys_menu child
ON child.parent_id = pilot.id
AND child.tenant_no = market.tenant_no
AND child.del_flag = 0
JOIN sys_menu btn
ON btn.parent_id = child.id
AND btn.tenant_no = market.tenant_no
AND btn.del_flag = 0
WHERE market.del_flag = 0
AND market.perms = 'menu:market'
) tgt
ON tgt.menu_id = m.id
AND tgt.tenant_no = m.tenant_no
WHERE m.del_flag = 0
ORDER BY m.tenant_no, m.menu_type, m.order_num, m.menu_name;
-- 1) 软删目标菜单
UPDATE sys_menu m
JOIN (
SELECT pilot.id AS menu_id, pilot.tenant_no
FROM sys_menu market
JOIN sys_menu pilot
ON pilot.parent_id = market.id
AND pilot.tenant_no = market.tenant_no
AND pilot.del_flag = 0
AND pilot.menu_name = '中试服务'
WHERE market.del_flag = 0
AND market.perms = 'menu:market'
UNION
SELECT child.id, child.tenant_no
FROM sys_menu market
JOIN sys_menu pilot
ON pilot.parent_id = market.id
AND pilot.tenant_no = market.tenant_no
AND pilot.del_flag = 0
AND pilot.menu_name = '中试服务'
JOIN sys_menu child
ON child.parent_id = pilot.id
AND child.tenant_no = market.tenant_no
AND child.del_flag = 0
WHERE market.del_flag = 0
AND market.perms = 'menu:market'
UNION
SELECT btn.id, btn.tenant_no
FROM sys_menu market
JOIN sys_menu pilot
ON pilot.parent_id = market.id
AND pilot.tenant_no = market.tenant_no
AND pilot.del_flag = 0
AND pilot.menu_name = '中试服务'
JOIN sys_menu child
ON child.parent_id = pilot.id
AND child.tenant_no = market.tenant_no
AND child.del_flag = 0
JOIN sys_menu btn
ON btn.parent_id = child.id
AND btn.tenant_no = market.tenant_no
AND btn.del_flag = 0
WHERE market.del_flag = 0
AND market.perms = 'menu:market'
) tgt
ON tgt.menu_id = m.id
AND tgt.tenant_no = m.tenant_no
SET
m.del_flag = 1,
m.update_by = 'migration',
m.update_time = NOW()
WHERE m.del_flag = 0;
-- 2) 核对:市场下不应再有有效「中试服务」目录(期望 0 行)
SELECT
market.tenant_no,
pilot.id,
pilot.menu_name,
pilot.del_flag
FROM sys_menu market
JOIN sys_menu pilot
ON pilot.parent_id = market.id
AND pilot.tenant_no = market.tenant_no
AND pilot.del_flag = 0
AND pilot.menu_name = '中试服务'
WHERE market.del_flag = 0
AND market.perms = 'menu:market';
@@ -0,0 +1,20 @@
-- 临床科研申请单:业务子类型 research_category
-- MySQL 5.7,可重复执行。
SET @col_exists := (
SELECT COUNT(*)
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'biz_pilot_application'
AND COLUMN_NAME = 'research_category'
);
SET @sql := IF(
@col_exists = 0,
"ALTER TABLE biz_pilot_application ADD COLUMN research_category VARCHAR(32) NULL COMMENT '临床科研业务子类型: bio_tech_clinical/joint_topic_declare/bio_pharma_rd' AFTER customer_phone",
'SELECT 1'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
@@ -0,0 +1,8 @@
-- 质检检测结果留痕:同一次批量保存共用 operate_batch_id(Issue #153)
-- 历史行可为空;前端对无批次号的旧数据做短时窗口合并兜底。
ALTER TABLE `biz_qc_task_result_change_log`
ADD COLUMN `operate_batch_id` varchar(64) DEFAULT NULL COMMENT '同一次保存批次ID(多任务共用)' AFTER `operator_user_name`;
ALTER TABLE `biz_qc_task_result_change_log`
ADD KEY `idx_qc_result_chg_batch` (`tenant_no`, `operate_batch_id`, `del_flag`);
Loaded 100 of 248 files, more files were not shown because too many files have changed in this diff. Show more