Compare commits

...
Author SHA1 Message Date
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
zlwu 5fe1193a2c feat(lab-sample): 实验室样本处理三表台账与部门字段 ACL
按造血/单个核/间充质聚合展示,部门员工只改本部门、主管可改全部,并支持筛选与 Excel 导出;同步纠正采集接受人串权与严格菜单守卫。
2026-11-12 12:48:05 +08:00
zlwu 58b252ce6b merge: 合入 #98 实验室样本处理数据台账 2026-11-12 12:12:55 +08:00
zlwuandCursor acb81cadd5 feat(qc): 新增实验室样本处理数据台账(4 Tab + 补录 + 导出)
在质检管理下增加按来源×样本类型展示的台账页,聚合接收/生产/质检参数,
补录按实验室入库编码关联,支持 Excel 导出与中文时间格式。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 12:11:57 +08:00
zlwuandCursor a64dd563bd fix(sql): 储存证 ACL 配置按钮授权给全部角色
continuous-integration/drone/tag Build is passing
迁移脚本为各租户有效角色补齐 storage-cert-qc-acl 菜单,使质检/生产权限入口对全部角色可见。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-11 17:03:49 +08:00
zlwuandCursor 377e0981ab fix(web-admin): 储存证 ACL 配置人员支持姓名模糊检索
远程下拉改为用检索结果替换选项并保留已选,修复只追加导致输入姓名后列表不收缩的问题。质检/生产权限共用同一弹窗。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-11 17:01:28 +08:00
zlwuandCursor 4654678231 fix(cell-storage): 储存证 ACL 保存避免 collation 混用 503
ACL 表与 sys_user JOIN/条件比较统一 utf8mb4_unicode_ci,并补建表 COLLATE 与 CONVERT 修复脚本(#97)。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-11 16:56:58 +08:00
zlwu a6d3f6f610 merge: #96 储存证 ACL 字段勾选全选/取消全选 2026-11-11 16:42:25 +08:00
zlwu 6cd5ced688 feat(web-admin): 储存证 ACL 字段勾选支持全选/取消全选
质检/生产权限弹窗「勾选可编辑字段」Tab 增加一键全选与取消全选。关联 #96。
2026-11-11 16:42:10 +08:00
zlwuandCursor 843f44929c fix(web-admin): 储存证 ACL 字段勾选改为两列布局
质检/生产权限弹窗「勾选可编辑字段」Tab 使用两列网格,窄屏回退单列。关联 #95。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-11 16:37:30 +08:00
zlwu 87a22880e8 merge: #93 储存证质检字段级质检/生产权限 2026-11-11 16:15:07 +08:00
116 changed files with 10413 additions and 374 deletions

No files matched your search

+6
View File
@@ -45,11 +45,16 @@ from app.api.sample_storage_cert_qc import router as sample_storage_cert_qc_rout
from app.api.customer_service_dict import router as customer_service_dict_router
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",
"menu_router",
"admin_router",
@@ -96,4 +101,5 @@ __all__ = [
"customer_service_dict_router",
"sample_cert_insurance_router",
"sample_code_correction_router",
"lab_sample_processing_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)
+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))
+147
View File
@@ -0,0 +1,147 @@
"""实验室样本处理数据台账 API"""
from typing import Any, Dict, Optional
from fastapi import APIRouter, Depends, Query
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_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
from app.services import lab_sample_process as ledger
router = APIRouter(prefix="/web/admin", tags=["质检管理"])
# 市场/生产/质检三处菜单权限码不同,接口按并集鉴权
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:
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 _user_id(user: dict) -> str:
uid = user.get("user_id")
if not uid:
raise PermissionError("用户身份信息缺失")
return str(uid)
def _dept_id(user: dict) -> str:
return str(user.get("dept_id") or user.get("create_dept_id") or "")
class SupplementBody(BaseModel):
model_config = ConfigDict(populate_by_name=True)
lab_storage_code: str = Field(..., alias="labStorageCode")
reception_source: str = Field(..., alias="receptionSource")
sample_type_name: str = Field(..., alias="sampleTypeName")
payload: Dict[str, Any] = Field(default_factory=dict)
remark: Optional[str] = None
@router.get("/lab-sample-process/list")
def list_lab_sample_process(
tabKey: str = Query(..., description="cell_hsc|donation_hsc|cell_msc|donation_msc"),
page: int = Query(1, ge=1),
pageSize: int = Query(10, ge=1, le=200),
labStorageCode: Optional[str] = Query(None),
motherName: Optional[str] = Query(None),
createTimeStart: Optional[str] = Query(None),
createTimeEnd: Optional[str] = Query(None),
db: Session = Depends(get_db),
user=Depends(require_any_menu_code(*LIST_MENU_CODES)),
):
try:
tenant_no = _tenant_no(db, user)
items, total = svc.list_ledger(
db,
tab_key=tabKey,
page=page,
page_size=pageSize,
tenant_no=tenant_no,
lab_storage_code=labStorageCode,
mother_name=motherName,
create_time_start=createTimeStart,
create_time_end=createTimeEnd,
user_info=user,
)
return success_response(
data={
"list": items,
"total": total,
"page": page,
"pageSize": pageSize,
"tabKey": tabKey,
"tabMeta": ledger.TAB_META.get(tabKey),
"supplementKeys": ledger.SUPPLEMENT_KEYS.get(tabKey, []),
}
)
except PermissionError as e:
return error_response(str(e), code=403)
except ValueError as e:
return error_response(str(e))
except Exception as e:
return error_response(f"查询失败:{e}")
@router.get("/lab-sample-process/supplement")
def get_supplement(
labStorageCode: str = Query(...),
db: Session = Depends(get_db),
user=Depends(require_any_menu_code(*LIST_MENU_CODES)),
):
try:
tenant_no = _tenant_no(db, user)
data = svc.get_supplement(db, tenant_no=tenant_no, lab_storage_code=labStorageCode)
return success_response(data=data or {"labStorageCode": labStorageCode, "payload": {}})
except PermissionError as e:
return error_response(str(e), code=403)
except Exception as e:
return error_response(f"查询补录失败:{e}")
@router.put("/lab-sample-process/supplement")
def save_supplement(
body: SupplementBody,
db: Session = Depends(get_db),
user=Depends(require_any_menu_code(*SUPPLEMENT_MENU_CODES)),
):
try:
tenant_no = _tenant_no(db, user)
data = svc.upsert_supplement(
db,
tenant_no=tenant_no,
user_id=_user_id(user),
dept_id=_dept_id(user),
lab_storage_code=body.lab_storage_code,
reception_source=body.reception_source,
sample_type_name=body.sample_type_name,
payload=body.payload or {},
remark=body.remark,
)
return success_response(data=data, message="补录已保存")
except PermissionError as e:
return error_response(str(e), code=403)
except ValueError as e:
return error_response(str(e))
except Exception as e:
return error_response(f"保存补录失败:{e}")
+193
View File
@@ -0,0 +1,193 @@
"""实验室样本处理数据 API"""
from __future__ import annotations
import csv
import io
from typing import Any, Dict, Optional
from fastapi import APIRouter, Depends, Query
from fastapi.responses import StreamingResponse
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_strict_any_menu_code
from app.core.response import error_response, success_response
from app.models.models import SysUser
from app.services import lab_sample_processing as svc
from app.services.lab_sample_processing_fields import (
DATASETS,
DATASET_LABELS,
PERM_LIST,
PERM_MANAGER,
PERM_MARKET_EDIT,
PERM_PRODUCTION_EDIT,
PERM_QC_EDIT,
schema_payload,
)
router = APIRouter(prefix="/web/admin/lab-sample-processing", tags=["实验室样本处理数据"])
# 列表/导出:有列表、主管或任一部门编辑权即可查看全部字段
READ_MENUS = (
PERM_LIST,
PERM_MANAGER,
PERM_MARKET_EDIT,
PERM_PRODUCTION_EDIT,
PERM_QC_EDIT,
)
# 更新:至少要有主管或某一部门编辑权(字段级 ACL 在服务内再收紧)
WRITE_MENUS = (
PERM_MANAGER,
PERM_MARKET_EDIT,
PERM_PRODUCTION_EDIT,
PERM_QC_EDIT,
)
def _tenant_no(db: Session, user: dict) -> str:
user_id = user.get("user_id")
if not user_id:
raise PermissionError("用户身份信息缺失")
row = db.query(SysUser).filter(SysUser.id == user_id, SysUser.del_flag == 0).first()
if not row or not row.tenant_no:
raise PermissionError("用户租户信息缺失")
return row.tenant_no
def _ensure_dataset(dataset: str) -> Optional[str]:
ds = (dataset or "").strip().lower()
return ds if ds in DATASETS else None
class UpdateBody(BaseModel):
model_config = ConfigDict(populate_by_name=True)
payload: Dict[str, Any] = Field(default_factory=dict)
@router.get("/meta/{dataset}")
async def get_meta(
dataset: str,
user: dict = Depends(require_strict_any_menu_code(*READ_MENUS)),
db: Session = Depends(get_db),
):
ds = _ensure_dataset(dataset)
if not ds:
return error_response(400, "未知数据集")
acl = svc.user_acl(db, user)
return success_response(
{
"dataset": ds,
"label": DATASET_LABELS.get(ds),
"fields": schema_payload(ds),
"acl": acl,
}
)
@router.get("/{dataset}/list")
async def list_dataset(
dataset: str,
keyword: Optional[str] = Query(None),
dateFrom: Optional[str] = Query(None),
dateTo: Optional[str] = Query(None),
page: int = Query(1, ge=1),
pageSize: int = Query(20, ge=1, le=200),
user: dict = Depends(require_strict_any_menu_code(*READ_MENUS)),
db: Session = Depends(get_db),
):
ds = _ensure_dataset(dataset)
if not ds:
return error_response(400, "未知数据集")
tenant_no = _tenant_no(db, user)
rows, total = svc.list_rows(
db,
tenant_no=tenant_no,
dataset=ds,
keyword=keyword,
date_from=dateFrom,
date_to=dateTo,
page=page,
page_size=pageSize,
)
acl = svc.user_acl(db, user)
return success_response(
{
"list": rows,
"total": total,
"page": page,
"pageSize": pageSize,
"fields": schema_payload(ds),
"acl": acl,
}
)
@router.put("/{dataset}/{sample_code}")
async def update_dataset_row(
dataset: str,
sample_code: str,
body: UpdateBody,
user: dict = Depends(require_strict_any_menu_code(*WRITE_MENUS)),
db: Session = Depends(get_db),
):
ds = _ensure_dataset(dataset)
if not ds:
return error_response(400, "未知数据集")
tenant_no = _tenant_no(db, user)
acl = svc.user_acl(db, user)
editable = set(acl.get("editableDepts") or [])
if not editable:
return error_response(403, "无编辑权限")
try:
row = svc.update_row(
db,
tenant_no=tenant_no,
dataset=ds,
sample_code=sample_code,
payload=body.payload or {},
editable_depts=editable,
operator_id=str(user.get("user_id") or ""),
)
except PermissionError as exc:
return error_response(403, str(exc))
except LookupError as exc:
return error_response(404, str(exc))
except ValueError as exc:
return error_response(400, str(exc))
return success_response(row)
@router.get("/{dataset}/export")
async def export_dataset(
dataset: str,
keyword: Optional[str] = Query(None),
dateFrom: Optional[str] = Query(None),
dateTo: Optional[str] = Query(None),
user: dict = Depends(require_strict_any_menu_code(*READ_MENUS)),
db: Session = Depends(get_db),
):
ds = _ensure_dataset(dataset)
if not ds:
return error_response(400, "未知数据集")
tenant_no = _tenant_no(db, user)
headers, body = svc.export_rows(
db,
tenant_no=tenant_no,
dataset=ds,
keyword=keyword,
date_from=dateFrom,
date_to=dateTo,
)
buf = io.StringIO()
writer = csv.writer(buf)
writer.writerow(headers)
for row in body:
writer.writerow(["" if v is None else v for v in row])
raw = ("\ufeff" + buf.getvalue()).encode("utf-8")
filename = f"lab-sample-{ds}.csv"
return StreamingResponse(
io.BytesIO(raw),
media_type="text/csv; charset=utf-8",
headers={"Content-Disposition": f'attachment; filename="{filename}"'},
)
+13 -1
View File
@@ -9,7 +9,19 @@ def unicode_ci(col):
def eq_unicode(left, right):
"""跨表字符串等值比较(JOIN / WHERE)时统一为 utf8mb4_unicode_ci。"""
"""跨表字符串等值比较(JOIN / WHERE)时统一为 utf8mb4_unicode_ci。
列与列:两侧 collate。列与字面量:仅列侧 collate,避免连接 collation
(常见 utf8mb4_general_ci)与列 collation(utf8mb4_unicode_ci)混用。
"""
left_is_str = isinstance(left, str)
right_is_str = isinstance(right, str)
if left_is_str and right_is_str:
return left == right
if left_is_str:
return left == unicode_ci(right)
if right_is_str:
return unicode_ci(left) == right
return unicode_ci(left) == unicode_ci(right)
+2 -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,
@@ -2677,7 +2678,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():
+770
View File
@@ -0,0 +1,770 @@
"""实验室样本处理台账列表与补录 CRUD。"""
from __future__ import annotations
from datetime import datetime
from typing import Any, Dict, List, Optional, Tuple
from sqlalchemy import and_
from sqlalchemy.orm import Session
from app.core.data_scope import apply_data_scope
from app.core.utils import generate_uuid
from app.crud import sample_production_reception as prod_svc
from app.models.models import (
BizCellSampleType,
BizCollectionHospital,
BizCollectionProtocol,
BizLabSampleProcessSupplement,
BizProtocolCollectionInfo,
BizProtocolPartyCustomer,
BizProtocolSample,
BizSampleProductionReception,
BizSampleReception,
BizSampleReceptionCheckResult,
BizStorageReleaseReview,
)
from app.models.research_donation import (
BizResearchDonation,
BizResearchDonationCollection,
BizResearchDonationParty,
BizResearchDonationSample,
)
from app.services import lab_sample_process as ledger
def _fmt_raw(dt: Optional[datetime]) -> str:
return dt.strftime("%Y-%m-%d %H:%M:%S") if dt else ""
def _normalize_bound(value: Optional[str], *, end_of_day: bool = False) -> Optional[datetime]:
text = (value or "").strip()
if not text:
return None
for fmt in ("%Y-%m-%d %H:%M:%S", "%Y-%m-%d"):
try:
dt = datetime.strptime(text[:19] if " " in text else text[:10], fmt)
if end_of_day and fmt == "%Y-%m-%d":
return dt.replace(hour=23, minute=59, second=59)
return dt
except ValueError:
continue
return None
def _type_ids_by_name(db: Session, tenant_no: str, type_name: str) -> List[str]:
rows = (
db.query(BizCellSampleType.id)
.filter(
BizCellSampleType.tenant_no == tenant_no,
BizCellSampleType.del_flag == 0,
BizCellSampleType.type_name == type_name,
)
.all()
)
return [r.id for r in rows if r.id]
def _get_supplement_map(
db: Session, tenant_no: str, codes: List[str]
) -> Dict[str, Dict[str, Any]]:
codes = [c for c in {(x or "").strip() for x in codes} if c]
if not codes:
return {}
rows = (
db.query(BizLabSampleProcessSupplement)
.filter(
BizLabSampleProcessSupplement.tenant_no == tenant_no,
BizLabSampleProcessSupplement.del_flag == 0,
BizLabSampleProcessSupplement.lab_storage_code.in_(codes),
)
.all()
)
out: Dict[str, Dict[str, Any]] = {}
for row in rows:
out[row.lab_storage_code] = {
"id": row.id,
"payload": ledger.parse_payload(row.payload),
"remark": row.remark or "",
"updateTime": _fmt_raw(row.update_time),
}
return out
def get_supplement(
db: Session, *, tenant_no: str, lab_storage_code: str
) -> Optional[Dict[str, Any]]:
code = (lab_storage_code or "").strip()
if not code:
return None
row = (
db.query(BizLabSampleProcessSupplement)
.filter(
BizLabSampleProcessSupplement.tenant_no == tenant_no,
BizLabSampleProcessSupplement.lab_storage_code == code,
BizLabSampleProcessSupplement.del_flag == 0,
)
.first()
)
if not row:
return None
return {
"id": row.id,
"labStorageCode": row.lab_storage_code,
"receptionSource": row.reception_source,
"sampleTypeName": row.sample_type_name or "",
"payload": ledger.parse_payload(row.payload),
"remark": row.remark or "",
"createTime": _fmt_raw(row.create_time),
"updateTime": _fmt_raw(row.update_time),
}
def upsert_supplement(
db: Session,
*,
tenant_no: str,
user_id: str,
dept_id: str,
lab_storage_code: str,
reception_source: str,
sample_type_name: str,
payload: Dict[str, Any],
remark: Optional[str] = None,
) -> Dict[str, Any]:
code = (lab_storage_code or "").strip()
if not code:
raise ValueError("实验室入库编码不能为空")
src = (reception_source or "").strip() or "cell_storage"
if src not in ("cell_storage", "research_donation"):
raise ValueError("来源类型无效")
type_name = (sample_type_name or "").strip()
clean_payload = {
str(k): ("" if v is None else str(v).strip())
for k, v in (payload or {}).items()
if str(k).strip()
}
row = (
db.query(BizLabSampleProcessSupplement)
.filter(
BizLabSampleProcessSupplement.tenant_no == tenant_no,
BizLabSampleProcessSupplement.lab_storage_code == code,
BizLabSampleProcessSupplement.del_flag == 0,
)
.first()
)
now = datetime.now()
if row:
row.reception_source = src
row.sample_type_name = type_name or row.sample_type_name
row.payload = ledger.dumps_payload(clean_payload)
if remark is not None:
row.remark = (remark or "").strip() or None
row.update_by = user_id
row.update_time = now
else:
row = BizLabSampleProcessSupplement(
id=generate_uuid(),
lab_storage_code=code,
reception_source=src,
sample_type_name=type_name or None,
payload=ledger.dumps_payload(clean_payload),
tenant_no=tenant_no,
remark=(remark or "").strip() or None,
create_by=user_id,
create_dept_id=dept_id or "",
create_time=now,
update_by=user_id,
update_time=now,
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 {}
def _check_flag_map(db: Session, tenant_no: str, reception_ids: List[str]) -> Dict[str, Dict[str, bool]]:
ids = [i for i in reception_ids if i]
if not ids:
return {}
rows = (
db.query(BizSampleReceptionCheckResult)
.filter(
BizSampleReceptionCheckResult.tenant_no == tenant_no,
BizSampleReceptionCheckResult.del_flag == 0,
BizSampleReceptionCheckResult.reception_id.in_(ids),
)
.all()
)
out: Dict[str, Dict[str, bool]] = {}
for r in rows:
bucket = out.setdefault(r.reception_id, {})
name = (r.item_name or "").strip()
if name:
bucket[name] = bool(r.checked)
return out
def _storage_status_map(db: Session, tenant_no: str, sample_codes: List[str]) -> Dict[str, str]:
codes = [c for c in sample_codes if c]
if not codes:
return {}
rows = (
db.query(BizStorageReleaseReview.sample_code, BizStorageReleaseReview.storage_status)
.filter(
BizStorageReleaseReview.tenant_no == tenant_no,
BizStorageReleaseReview.del_flag == 0,
BizStorageReleaseReview.sample_code.in_(codes),
)
.all()
)
labels = {"drk": "待入库", "yrk": "已入库"}
return {r.sample_code: labels.get(r.storage_status or "", r.storage_status or "") for r in rows}
def _hospital_name_map(db: Session, hospital_ids: List[str]) -> Dict[str, str]:
ids = [i for i in hospital_ids if i]
if not ids:
return {}
rows = (
db.query(BizCollectionHospital.id, BizCollectionHospital.hospital_name)
.filter(BizCollectionHospital.id.in_(ids), BizCollectionHospital.del_flag == 0)
.all()
)
return {r.id: r.hospital_name or "" for r in rows}
def _build_cell_system(
*,
tab_key: str,
rec: BizSampleReception,
sample: BizProtocolSample,
party: Optional[BizProtocolPartyCustomer],
coll: Optional[BizProtocolCollectionInfo],
protocol: Optional[BizCollectionProtocol],
prod: Optional[Dict[str, Any]],
hospital_name: str,
check_flags: Dict[str, bool],
storage_status: str,
qc_mother: Dict[str, str],
qc_process: Dict[str, str],
) -> Dict[str, Any]:
prod = prod or {}
maternal_time = coll.maternal_blood_collect_time if coll else None
clear_flag = None
for name, checked in check_flags.items():
if "标识清晰" in name or "样本信息正确" in name:
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),
"hospitalName": hospital_name,
"receptionTime": ledger.format_cn_datetime(rec.reception_time),
"receptionTimeRaw": _fmt_raw(rec.reception_time),
"receiveTemperature": rec.receive_temperature or "",
"handlerName": rec.handler_name or "",
"remarkReception": rec.remark or "",
"createTime": ledger.format_cn_datetime(rec.create_time),
"createTimeRaw": _fmt_raw(rec.create_time),
"operatorName": prod.get("handlerName") or "",
"remarkProcess": prod.get("remark") or "",
"storageStatus": storage_status,
}
if tab_key == "cell_hsc":
base.update(
{
"cellCode": (rec.lab_storage_code or "").strip(),
"hasMaternalBlood": "是" if maternal_time else "否",
"remeasureMaternalBlood": "",
"consentForm": ledger.yes_no_from_urls(
protocol.consent_form_urls if protocol else None
),
"transportPackingList": "",
"cordBloodReceiveConfirm": "",
"healthSurvey": ledger.yes_no_from_urls(
protocol.health_survey_form_urls if protocol else None
),
"labelClear": ledger.yes_no_from_bool(clear_flag) if clear_flag is not None else "",
"receiveCheckText": "",
"originalBloodWeightG": prod.get("originalBloodWeightG"),
"hesVolumeMl": prod.get("hesVolumeMl"),
"bloodType": prod.get("bloodType") or "",
"infectiousFourTestLabel": prod.get("infectiousFourTestResultLabel")
or ledger.infectious_label(prod.get("infectiousFourTestResult")),
"infectiousFourExternal": "",
"preEnrichNucleatedCount": "",
"enrichedBloodWeightG": prod.get("enrichedBloodWeightG"),
"postEnrichNucleatedCount": "",
"cryopreservationVolumeMl": prod.get("cryopreservationVolumeMl"),
"cd34Count1e4": "",
}
)
else: # cell_msc
base.update(
{
"labFlowCode": (rec.lab_storage_code or "").strip(),
"cordCollectTime": ledger.format_cn_datetime(
coll.sample_collect_time if coll else None
),
"transportTempC": rec.receive_temperature or "",
"cordReceiveTime": ledger.format_cn_datetime(rec.reception_time),
"inoculationAmount": prod.get("inoculationAmount") or "",
"cryopreservationTime": ledger.format_cn_datetime(prod.get("cryopreservationTime")),
"storageTotalTubes": prod.get("storageTotalTubes"),
"availableCellCount1e7": prod.get("availableCellCount1e7"),
"remark": rec.remark or prod.get("remark") or "",
"storageDateP2": "",
}
)
base.update(qc_process)
base.update(qc_mother)
return base
def _build_donation_system(
*,
tab_key: str,
rec: BizSampleReception,
sample: BizResearchDonationSample,
party: Optional[BizResearchDonationParty],
coll: Optional[BizResearchDonationCollection],
prod: Optional[Dict[str, Any]],
storage_status: str,
qc_mother: Dict[str, str],
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),
"receiveTemperature": rec.receive_temperature or "",
"handlerName": rec.handler_name or "",
"remarkReception": rec.remark or "",
"createTime": ledger.format_cn_datetime(rec.create_time),
"createTimeRaw": _fmt_raw(rec.create_time),
"operatorName": prod.get("handlerName") or "",
"remarkProcess": prod.get("remark") or "",
"storageStatus": storage_status,
}
if tab_key == "donation_hsc":
base.update(
{
"cellCode": (rec.lab_storage_code or "").strip(),
"labMaterialCode": "",
"inboundCode": (rec.lab_storage_code or "").strip(),
"discardReason": "",
"receiveCheckText": "",
"originalBloodVolumeMl": prod.get("originalBloodVolumeMl"),
"nucleatedCellCount1e8": prod.get("nucleatedCellCount1e8"),
"preOpNucleatedCount": "",
"infectiousFourTestLabel": prod.get("infectiousFourTestResultLabel")
or ledger.infectious_label(prod.get("infectiousFourTestResult")),
}
)
# 科研捐赠母血 5 项(不含核酸)
for k in (
"motherHbsag",
"motherAntiHcv",
"motherAntiTp",
"motherAntiHiv",
"motherCmvIgm",
):
if qc_mother.get(k):
base[k] = qc_mother[k]
else:
base.update(
{
"labFlowCode": (rec.lab_storage_code or "").strip(),
"cordCollectTime": ledger.format_cn_datetime(
coll.sample_collect_time if coll else None
),
"transportTempC": rec.receive_temperature or "",
"cordReceiveTime": ledger.format_cn_datetime(rec.reception_time),
"inoculationAmount": prod.get("inoculationAmount") or "",
"cryopreservationTime": ledger.format_cn_datetime(prod.get("cryopreservationTime")),
"storageTotalTubes": prod.get("storageTotalTubes"),
"availableCellCount1e7": prod.get("availableCellCount1e7"),
"remark": rec.remark or prod.get("remark") or "",
"storageDateP2": "",
}
)
base.update(qc_process)
base.update(qc_mother)
return base
def list_ledger(
db: Session,
*,
tab_key: str,
page: int = 1,
page_size: int = 10,
tenant_no: str,
lab_storage_code: Optional[str] = None,
mother_name: Optional[str] = None,
create_time_start: Optional[str] = None,
create_time_end: Optional[str] = None,
user_info=None,
) -> Tuple[List[Dict[str, Any]], int]:
meta = ledger.TAB_META.get(tab_key)
if not meta:
raise ValueError("无效的 Tab")
source = meta["source"]
type_name = meta["sampleTypeName"]
type_ids = _type_ids_by_name(db, tenant_no, type_name)
if not type_ids:
return [], 0
q = db.query(BizSampleReception).filter(
BizSampleReception.tenant_no == tenant_no,
BizSampleReception.del_flag == 0,
BizSampleReception.reception_source == source,
BizSampleReception.lab_storage_code.isnot(None),
BizSampleReception.lab_storage_code != "",
BizSampleReception.accept_conclusion == "js",
)
code_kw = (lab_storage_code or "").strip()
if code_kw:
q = q.filter(BizSampleReception.lab_storage_code.like(f"%{code_kw}%"))
start = _normalize_bound(create_time_start)
end = _normalize_bound(create_time_end, end_of_day=True)
if start:
q = q.filter(BizSampleReception.create_time >= start)
if end:
q = q.filter(BizSampleReception.create_time <= end)
if user_info:
q = apply_data_scope(q, BizSampleReception, user_info, db, tenant_no)
mother_kw = (mother_name or "").strip()
# 按来源限制样本类型,并可选母亲姓名
if source == "cell_storage":
sample_q = (
db.query(BizProtocolSample.id)
.join(
BizCollectionProtocol,
and_(
BizCollectionProtocol.id == BizProtocolSample.collection_protocol_id,
BizCollectionProtocol.del_flag == 0,
BizCollectionProtocol.tenant_no == tenant_no,
),
)
.filter(
BizProtocolSample.tenant_no == tenant_no,
BizProtocolSample.del_flag == 0,
BizProtocolSample.sample_type_id.in_(type_ids),
)
)
if mother_kw:
sample_q = sample_q.join(
BizProtocolPartyCustomer,
and_(
BizProtocolPartyCustomer.collection_protocol_id
== BizProtocolSample.collection_protocol_id,
BizProtocolPartyCustomer.del_flag == 0,
BizProtocolPartyCustomer.tenant_no == tenant_no,
),
).filter(BizProtocolPartyCustomer.mother_name.like(f"%{mother_kw}%"))
sample_ids = [r.id for r in sample_q.all()]
if not sample_ids:
return [], 0
q = q.filter(BizSampleReception.protocol_sample_id.in_(sample_ids))
else:
sample_q = (
db.query(BizResearchDonationSample.id)
.join(
BizResearchDonation,
and_(
BizResearchDonation.id == BizResearchDonationSample.research_donation_id,
BizResearchDonation.del_flag == 0,
BizResearchDonation.tenant_no == tenant_no,
),
)
.filter(
BizResearchDonationSample.tenant_no == tenant_no,
BizResearchDonationSample.del_flag == 0,
BizResearchDonationSample.sample_type_id.in_(type_ids),
)
)
if mother_kw:
sample_q = sample_q.join(
BizResearchDonationParty,
and_(
BizResearchDonationParty.research_donation_id
== BizResearchDonationSample.research_donation_id,
BizResearchDonationParty.del_flag == 0,
BizResearchDonationParty.tenant_no == tenant_no,
),
).filter(BizResearchDonationParty.mother_name.like(f"%{mother_kw}%"))
sample_ids = [r.id for r in sample_q.all()]
if not sample_ids:
return [], 0
q = q.filter(BizSampleReception.donation_sample_id.in_(sample_ids))
total = q.count()
page = max(1, int(page or 1))
page_size = min(max(1, int(page_size or 10)), 200)
receptions = (
q.order_by(BizSampleReception.create_time.desc(), BizSampleReception.id.desc())
.offset((page - 1) * page_size)
.limit(page_size)
.all()
)
if not receptions:
return [], int(total)
reception_ids = [r.id for r in receptions]
codes = [(r.lab_storage_code or "").strip() for r in receptions]
sample_codes = [(r.sample_code or "").strip() for r in receptions]
prod_map = _prod_map(db, tenant_no, reception_ids)
check_map = _check_flag_map(db, tenant_no, reception_ids)
storage_map = _storage_status_map(db, tenant_no, [c for c in sample_codes if c])
sup_map = _get_supplement_map(db, tenant_no, codes)
items: List[Dict[str, Any]] = []
if source == "cell_storage":
items = _assemble_cell_rows(
db,
tenant_no=tenant_no,
tab_key=tab_key,
receptions=receptions,
prod_map=prod_map,
check_map=check_map,
storage_map=storage_map,
sup_map=sup_map,
)
else:
items = _assemble_donation_rows(
db,
tenant_no=tenant_no,
tab_key=tab_key,
receptions=receptions,
prod_map=prod_map,
storage_map=storage_map,
sup_map=sup_map,
)
return items, int(total)
def _prod_map(db: Session, tenant_no: str, reception_ids: List[str]) -> Dict[str, Dict[str, Any]]:
rows = (
db.query(BizSampleProductionReception)
.filter(
BizSampleProductionReception.tenant_no == tenant_no,
BizSampleProductionReception.del_flag == 0,
BizSampleProductionReception.reception_id.in_(reception_ids),
)
.all()
)
return {r.reception_id: prod_svc._row_to_dict(r) for r in rows}
def _assemble_cell_rows(
db: Session,
*,
tenant_no: str,
tab_key: str,
receptions: List[BizSampleReception],
prod_map: Dict[str, Dict[str, Any]],
check_map: Dict[str, Dict[str, bool]],
storage_map: Dict[str, str],
sup_map: Dict[str, Dict[str, Any]],
) -> List[Dict[str, Any]]:
sample_ids = [r.protocol_sample_id for r in receptions if r.protocol_sample_id]
samples = (
db.query(BizProtocolSample)
.filter(
BizProtocolSample.tenant_no == tenant_no,
BizProtocolSample.del_flag == 0,
BizProtocolSample.id.in_(sample_ids),
)
.all()
if sample_ids
else []
)
sample_map = {s.id: s for s in samples}
protocol_ids = list({s.collection_protocol_id for s in samples if s.collection_protocol_id})
parties = (
db.query(BizProtocolPartyCustomer)
.filter(
BizProtocolPartyCustomer.tenant_no == tenant_no,
BizProtocolPartyCustomer.del_flag == 0,
BizProtocolPartyCustomer.collection_protocol_id.in_(protocol_ids),
)
.all()
if protocol_ids
else []
)
party_map = {p.collection_protocol_id: p for p in parties}
colls = (
db.query(BizProtocolCollectionInfo)
.filter(
BizProtocolCollectionInfo.tenant_no == tenant_no,
BizProtocolCollectionInfo.del_flag == 0,
BizProtocolCollectionInfo.collection_protocol_id.in_(protocol_ids),
)
.all()
if protocol_ids
else []
)
coll_map = {c.collection_protocol_id: c for c in colls}
protocols = (
db.query(BizCollectionProtocol)
.filter(
BizCollectionProtocol.tenant_no == tenant_no,
BizCollectionProtocol.del_flag == 0,
BizCollectionProtocol.id.in_(protocol_ids),
)
.all()
if protocol_ids
else []
)
protocol_map = {p.id: p for p in protocols}
hospital_ids = [c.hospital_id for c in colls if c.hospital_id]
hospital_map = _hospital_name_map(db, hospital_ids)
out: List[Dict[str, Any]] = []
for rec in receptions:
sample = sample_map.get(rec.protocol_sample_id or "")
if not sample:
continue
pid = sample.collection_protocol_id
sample_code = (rec.sample_code or sample.sample_code or "").strip()
tasks = ledger.load_qc_tasks_for_sample(db, tenant_no, sample_code)
qc_mother = ledger.extract_mother_blood(tasks, include_nucleic=True)
qc_process = ledger.extract_process_tests(tasks)
system = _build_cell_system(
tab_key=tab_key,
rec=rec,
sample=sample,
party=party_map.get(pid),
coll=coll_map.get(pid),
protocol=protocol_map.get(pid),
prod=prod_map.get(rec.id),
hospital_name=hospital_map.get((coll_map.get(pid).hospital_id if coll_map.get(pid) else "") or "", ""),
check_flags=check_map.get(rec.id, {}),
storage_status=storage_map.get(sample_code, ""),
qc_mother=qc_mother,
qc_process=qc_process,
)
lab_code = system.get("labStorageCode") or ""
merged = ledger.merge_row(
tab_key=tab_key,
system_values=system,
supplement=(sup_map.get(lab_code) or {}).get("payload"),
)
merged["supplementId"] = (sup_map.get(lab_code) or {}).get("id") or ""
merged["hasSupplement"] = bool((sup_map.get(lab_code) or {}).get("payload"))
out.append(merged)
return out
def _assemble_donation_rows(
db: Session,
*,
tenant_no: str,
tab_key: str,
receptions: List[BizSampleReception],
prod_map: Dict[str, Dict[str, Any]],
storage_map: Dict[str, str],
sup_map: Dict[str, Dict[str, Any]],
) -> List[Dict[str, Any]]:
sample_ids = [r.donation_sample_id for r in receptions if r.donation_sample_id]
samples = (
db.query(BizResearchDonationSample)
.filter(
BizResearchDonationSample.tenant_no == tenant_no,
BizResearchDonationSample.del_flag == 0,
BizResearchDonationSample.id.in_(sample_ids),
)
.all()
if sample_ids
else []
)
sample_map = {s.id: s for s in samples}
donation_ids = list({s.research_donation_id for s in samples if s.research_donation_id})
parties = (
db.query(BizResearchDonationParty)
.filter(
BizResearchDonationParty.tenant_no == tenant_no,
BizResearchDonationParty.del_flag == 0,
BizResearchDonationParty.research_donation_id.in_(donation_ids),
)
.all()
if donation_ids
else []
)
party_map = {p.research_donation_id: p for p in parties}
colls = (
db.query(BizResearchDonationCollection)
.filter(
BizResearchDonationCollection.tenant_no == tenant_no,
BizResearchDonationCollection.del_flag == 0,
BizResearchDonationCollection.research_donation_id.in_(donation_ids),
)
.all()
if donation_ids
else []
)
coll_map = {c.research_donation_id: c for c in colls}
out: List[Dict[str, Any]] = []
for rec in receptions:
sample = sample_map.get(rec.donation_sample_id or "")
if not sample:
continue
did = sample.research_donation_id
sample_code = (rec.sample_code or sample.sample_code or "").strip()
tasks = ledger.load_qc_tasks_for_sample(db, tenant_no, sample_code)
qc_mother = ledger.extract_mother_blood(tasks, include_nucleic=True)
qc_process = ledger.extract_process_tests(tasks)
system = _build_donation_system(
tab_key=tab_key,
rec=rec,
sample=sample,
party=party_map.get(did),
coll=coll_map.get(did),
prod=prod_map.get(rec.id),
storage_status=storage_map.get(sample_code, ""),
qc_mother=qc_mother,
qc_process=qc_process,
)
lab_code = system.get("labStorageCode") or ""
merged = ledger.merge_row(
tab_key=tab_key,
system_values=system,
supplement=(sup_map.get(lab_code) or {}).get("payload"),
)
merged["supplementId"] = (sup_map.get(lab_code) or {}).get("id") or ""
merged["hasSupplement"] = bool((sup_map.get(lab_code) or {}).get("payload"))
out.append(merged)
return out
+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 "", ""
+63 -5
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,
)
@@ -677,9 +679,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 +694,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 +705,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 +811,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 +856,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 +864,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 +913,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 +1196,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 ""
@@ -2601,6 +2658,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", ""),
+3 -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,
@@ -1702,7 +1703,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
+8 -10
View File
@@ -1045,12 +1045,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 +1168,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
+17 -16
View File
@@ -6,6 +6,7 @@ from typing import Any, Dict, List, Optional, Set
from sqlalchemy.orm import Session
from app.core.db_collation import eq_unicode, unicode_ci
from app.core.utils import generate_uuid
from app.crud.child_row_sync import sync_child_rows
from app.models.models import BizStorageCertQcAcl, BizStorageCertQcAclUser, SysUser
@@ -22,8 +23,8 @@ def is_acl_strict(db: Session, tenant_no: str) -> bool:
row = (
db.query(BizStorageCertQcAcl.id)
.filter(
BizStorageCertQcAcl.tenant_no == tenant_no,
BizStorageCertQcAcl.configured_flag == "1",
eq_unicode(BizStorageCertQcAcl.tenant_no, tenant_no),
eq_unicode(BizStorageCertQcAcl.configured_flag, "1"),
BizStorageCertQcAcl.del_flag == 0,
)
.first()
@@ -48,8 +49,8 @@ def resolve_editable_field_keys(
acls = (
db.query(BizStorageCertQcAcl)
.filter(
BizStorageCertQcAcl.tenant_no == tenant_no,
BizStorageCertQcAcl.configured_flag == "1",
eq_unicode(BizStorageCertQcAcl.tenant_no, tenant_no),
eq_unicode(BizStorageCertQcAcl.configured_flag, "1"),
BizStorageCertQcAcl.del_flag == 0,
)
.all()
@@ -60,9 +61,9 @@ def resolve_editable_field_keys(
membership = (
db.query(BizStorageCertQcAclUser.acl_id)
.filter(
BizStorageCertQcAclUser.tenant_no == tenant_no,
BizStorageCertQcAclUser.acl_id.in_(acl_ids),
BizStorageCertQcAclUser.user_id == uid,
eq_unicode(BizStorageCertQcAclUser.tenant_no, tenant_no),
unicode_ci(BizStorageCertQcAclUser.acl_id).in_(acl_ids),
eq_unicode(BizStorageCertQcAclUser.user_id, uid),
BizStorageCertQcAclUser.del_flag == 0,
)
.all()
@@ -115,8 +116,8 @@ def _validate_user_ids(db: Session, tenant_no: str, user_ids: Any) -> List[str]:
rows = (
db.query(SysUser.id)
.filter(
SysUser.tenant_no == tenant_no,
SysUser.id.in_(out),
eq_unicode(SysUser.tenant_no, tenant_no),
unicode_ci(SysUser.id).in_(out),
SysUser.del_flag == 0,
)
.all()
@@ -133,8 +134,8 @@ def get_acl_detail(db: Session, tenant_no: str, scope: str) -> Dict[str, Any]:
row = (
db.query(BizStorageCertQcAcl)
.filter(
BizStorageCertQcAcl.tenant_no == tenant_no,
BizStorageCertQcAcl.scope == scope_key,
eq_unicode(BizStorageCertQcAcl.tenant_no, tenant_no),
eq_unicode(BizStorageCertQcAcl.scope, scope_key),
BizStorageCertQcAcl.del_flag == 0,
)
.first()
@@ -152,11 +153,11 @@ def get_acl_detail(db: Session, tenant_no: str, scope: str) -> Dict[str, Any]:
db.query(BizStorageCertQcAclUser, SysUser)
.outerjoin(
SysUser,
(SysUser.id == BizStorageCertQcAclUser.user_id) & (SysUser.del_flag == 0),
eq_unicode(SysUser.id, BizStorageCertQcAclUser.user_id) & (SysUser.del_flag == 0),
)
.filter(
BizStorageCertQcAclUser.tenant_no == tenant_no,
BizStorageCertQcAclUser.acl_id == row.id,
eq_unicode(BizStorageCertQcAclUser.tenant_no, tenant_no),
eq_unicode(BizStorageCertQcAclUser.acl_id, row.id),
BizStorageCertQcAclUser.del_flag == 0,
)
.order_by(BizStorageCertQcAclUser.order_num.asc(), BizStorageCertQcAclUser.create_time.asc())
@@ -202,8 +203,8 @@ def upsert_acl(
row = (
db.query(BizStorageCertQcAcl)
.filter(
BizStorageCertQcAcl.tenant_no == tenant_no,
BizStorageCertQcAcl.scope == scope_key,
eq_unicode(BizStorageCertQcAcl.tenant_no, tenant_no),
eq_unicode(BizStorageCertQcAcl.scope, scope_key),
BizStorageCertQcAcl.del_flag == 0,
)
.first()
+4 -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, 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)
@@ -157,6 +158,8 @@ app.include_router(sample_storage_cert_qc_router, prefix=settings.API_V1_PREFIX)
app.include_router(customer_service_dict_router, prefix=settings.API_V1_PREFIX)
app.include_router(sample_cert_insurance_router, prefix=settings.API_V1_PREFIX)
app.include_router(sample_code_correction_router, prefix=settings.API_V1_PREFIX)
app.include_router(lab_sample_process_router, prefix=settings.API_V1_PREFIX)
app.include_router(lab_sample_processing_router, prefix=settings.API_V1_PREFIX)
app.include_router(project_management_router, prefix=settings.API_V1_PREFIX)
+44
View File
@@ -1597,6 +1597,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="特殊说明")
@@ -1969,6 +1970,26 @@ class BizSampleReception(Base):
del_flag = Column(SmallInteger, nullable=False, default=0, comment="删除标记")
class BizLabSampleProcessingExtra(Base):
"""实验室样本处理数据补充字段 biz_lab_sample_processing_extra"""
__tablename__ = "biz_lab_sample_processing_extra"
id = Column(String(64), primary_key=True, comment="主键ID")
dataset = Column(String(16), nullable=False, comment="hsc|ubmc|msc")
sample_code = Column(String(32), nullable=False, comment="样本编码")
payload_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 BizSampleProductionReception(Base):
"""生产部门样本接收登记 biz_sample_production_reception"""
@@ -2007,6 +2028,29 @@ class BizSampleProductionReception(Base):
del_flag = Column(SmallInteger, nullable=False, default=0, comment="删除标记")
class BizLabSampleProcessSupplement(Base):
"""实验室样本处理台账补录 biz_lab_sample_process_supplement(键:tenant_no + lab_storage_code)"""
__tablename__ = "biz_lab_sample_process_supplement"
id = Column(String(64), primary_key=True, comment="主键ID")
lab_storage_code = Column(String(32), nullable=False, comment="实验室入库编码")
reception_source = Column(
String(20), nullable=False, default="cell_storage", comment="cell_storage|research_donation"
)
sample_type_name = Column(String(100), nullable=True, comment="样本类型名称快照")
payload = Column(Text, nullable=False, 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 BizSampleSmsNotification(Base):
__tablename__ = "biz_sample_sms_notification"
+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="特殊说明")
+374
View File
@@ -0,0 +1,374 @@
"""实验室样本处理台账:字段合并、质检参数匹配、中文时间格式。"""
from __future__ import annotations
import json
from datetime import datetime
from typing import Any, Dict, Iterable, List, Optional, Set
from sqlalchemy.orm import Session
from app.models.models import (
BizQcTask,
BizQcWorkOrder,
BizQcWorkOrderInspectionBatch,
)
from app.models.qc_param import BizQcTaskResult
from app.services.sample_storage_cert_qc_prefill import (
_MOTHER_SEROLOGY_RULES,
_process_qual_from_tasks,
_serology_from_tasks,
_stamp,
batch_kind_from_name,
normalize_negative_positive,
qual_yin_yang,
)
SAMPLE_TYPE_PERINATAL_HSC = "围产期造血干细胞"
SAMPLE_TYPE_UC_MSC = "脐带间充质干细胞"
TAB_KEYS = (
"cell_hsc",
"donation_hsc",
"cell_msc",
"donation_msc",
)
TAB_META = {
"cell_hsc": {
"source": "cell_storage",
"sampleTypeName": SAMPLE_TYPE_PERINATAL_HSC,
"label": "细胞存储·围产期造血干细胞",
},
"donation_hsc": {
"source": "research_donation",
"sampleTypeName": SAMPLE_TYPE_PERINATAL_HSC,
"label": "科研捐赠·围产期造血干细胞",
},
"cell_msc": {
"source": "cell_storage",
"sampleTypeName": SAMPLE_TYPE_UC_MSC,
"label": "细胞存储·脐带间充质干细胞",
},
"donation_msc": {
"source": "research_donation",
"sampleTypeName": SAMPLE_TYPE_UC_MSC,
"label": "科研捐赠·脐带间充质干细胞",
},
}
# 各 Tab 可补录字段(系统空或口径需覆盖时写入)
SUPPLEMENT_KEYS: Dict[str, List[str]] = {
"cell_hsc": [
"receiveCheckText",
"hasMaternalBlood",
"remeasureMaternalBlood",
"transportPackingList",
"cordBloodReceiveConfirm",
"infectiousFourExternal",
"preEnrichNucleatedCount",
"postEnrichNucleatedCount",
"cd34Count1e4",
"remarkProcess",
],
"donation_hsc": [
"labMaterialCode",
"storageStatus",
"discardReason",
"receiveCheckText",
"preOpNucleatedCount",
"infectiousFourTestLabel",
"motherHbsag",
"motherAntiHcv",
"motherAntiTp",
"motherAntiHiv",
"motherCmvIgm",
"remarkProcess",
],
"cell_msc": [
"storageStatus",
"endotoxinTest",
"bacteriaTest",
"fungusTest",
"mycoplasmaTest",
"motherHbsag",
"motherHbvDna",
"motherAntiHcv",
"motherHcvRna",
"motherAntiTp",
"motherCmvIgm",
"motherAntiHiv",
"motherHiv1Rna",
"storageDateP2",
"remark",
],
"donation_msc": [
"storageStatus",
"storageTotalTubes",
"availableCellCount1e7",
"endotoxinTest",
"bacteriaTest",
"fungusTest",
"mycoplasmaTest",
"motherHbsag",
"motherHbvDna",
"motherAntiHcv",
"motherHcvRna",
"motherAntiTp",
"motherCmvIgm",
"motherAntiHiv",
"motherHiv1Rna",
"storageDateP2",
"remark",
],
}
# 补录优先覆盖系统推导值的字段
SUPPLEMENT_OVERRIDE_KEYS: Dict[str, Set[str]] = {
"cell_hsc": {"receiveCheckText"},
"donation_hsc": {
"receiveCheckText",
"storageStatus",
"infectiousFourTestLabel",
"motherHbsag",
"motherAntiHcv",
"motherAntiTp",
"motherAntiHiv",
"motherCmvIgm",
},
"cell_msc": {
"storageStatus",
"endotoxinTest",
"bacteriaTest",
"fungusTest",
"mycoplasmaTest",
"motherHbsag",
"motherHbvDna",
"motherAntiHcv",
"motherHcvRna",
"motherAntiTp",
"motherCmvIgm",
"motherAntiHiv",
"motherHiv1Rna",
"storageDateP2",
},
"donation_msc": {
"storageStatus",
"storageTotalTubes",
"availableCellCount1e7",
"endotoxinTest",
"bacteriaTest",
"fungusTest",
"mycoplasmaTest",
"motherHbsag",
"motherHbvDna",
"motherAntiHcv",
"motherHcvRna",
"motherAntiTp",
"motherCmvIgm",
"motherAntiHiv",
"motherHiv1Rna",
"storageDateP2",
},
}
def format_cn_datetime(value: Any) -> str:
"""统一展示:2026年11月12日 00时00分00秒"""
if value is None or value == "":
return ""
if isinstance(value, datetime):
dt = value
else:
text = str(value).strip().replace("T", " ")
if not text:
return ""
dt = None
for candidate, fmt in (
(text[:19], "%Y-%m-%d %H:%M:%S"),
(text[:16], "%Y-%m-%d %H:%M"),
(text[:10], "%Y-%m-%d"),
):
try:
dt = datetime.strptime(candidate, fmt)
break
except ValueError:
continue
if dt is None:
return text
return (
f"{dt.year:04d}年{dt.month:02d}月{dt.day:02d}日 "
f"{dt.hour:02d}时{dt.minute:02d}分{dt.second:02d}秒"
)
def parse_payload(raw: Any) -> Dict[str, Any]:
if isinstance(raw, dict):
return dict(raw)
if not raw:
return {}
try:
data = json.loads(raw)
except (TypeError, ValueError, json.JSONDecodeError):
return {}
return data if isinstance(data, dict) else {}
def dumps_payload(payload: Dict[str, Any]) -> str:
return json.dumps(payload or {}, ensure_ascii=False, separators=(",", ":"))
def yes_no_from_urls(urls: Optional[str]) -> str:
return "是" if (urls or "").strip() else "否"
def yes_no_from_bool(flag: Optional[bool]) -> str:
if flag is None:
return ""
return "是" if flag else "否"
def merge_row(
*,
tab_key: str,
system_values: Dict[str, Any],
supplement: Optional[Dict[str, Any]],
) -> Dict[str, Any]:
"""系统值优先;override 键补录优先;空用补录填。"""
out = dict(system_values or {})
sup = supplement or {}
overrides = SUPPLEMENT_OVERRIDE_KEYS.get(tab_key, set())
for key, val in sup.items():
text = "" if val is None else str(val).strip()
if not text:
continue
cur = out.get(key)
cur_empty = cur is None or (isinstance(cur, str) and not cur.strip())
if key in overrides or cur_empty:
out[key] = text
return out
def load_qc_tasks_for_sample(db: Session, tenant_no: str, sample_code: str) -> List[Dict[str, Any]]:
code = (sample_code or "").strip()
if not code:
return []
rows = (
db.query(
BizQcTask.id,
BizQcTask.item_name,
BizQcTask.completed_time,
BizQcTask.update_time,
BizQcWorkOrderInspectionBatch.batch_name,
BizQcTaskResult.param_name,
BizQcTaskResult.param_value,
)
.join(BizQcWorkOrder, BizQcWorkOrder.id == BizQcTask.work_order_id)
.outerjoin(
BizQcWorkOrderInspectionBatch,
BizQcWorkOrderInspectionBatch.id == BizQcTask.batch_id,
)
.outerjoin(
BizQcTaskResult,
(BizQcTaskResult.task_id == BizQcTask.id) & (BizQcTaskResult.del_flag == 0),
)
.filter(
BizQcWorkOrder.tenant_no == tenant_no,
BizQcWorkOrder.sample_code == code,
BizQcWorkOrder.del_flag == 0,
BizQcTask.tenant_no == tenant_no,
BizQcTask.del_flag == 0,
BizQcTask.task_status == "ywc",
)
.all()
)
grouped: Dict[str, Dict[str, Any]] = {}
for row in rows:
task = grouped.setdefault(
row.id,
{
"item_name": row.item_name or "",
"batch_kind": batch_kind_from_name(row.batch_name),
"stamp": _stamp(row.completed_time, row.update_time),
"params": [],
"values": [],
},
)
if (row.param_name or "").strip() or (row.param_value or "").strip():
task["params"].append((row.param_name or "", row.param_value or ""))
if (row.param_value or "").strip():
task["values"].append(row.param_value or "")
return list(grouped.values())
def extract_mother_blood(tasks: List[Dict[str, Any]], *, include_nucleic: bool = True) -> Dict[str, str]:
rules = _MOTHER_SEROLOGY_RULES
if not include_nucleic:
rules = tuple(
r
for r in rules
if r[0] not in {"mother_hbv_dna", "mother_hcv_rna", "mother_hiv1_rna"}
)
raw = _serology_from_tasks(tasks, rules)
mapping = {
"mother_hbsag": "motherHbsag",
"mother_hbv_dna": "motherHbvDna",
"mother_anti_hcv": "motherAntiHcv",
"mother_hcv_rna": "motherHcvRna",
"mother_anti_tp": "motherAntiTp",
"mother_cmv_igm": "motherCmvIgm",
"mother_anti_hiv": "motherAntiHiv",
"mother_hiv1_rna": "motherHiv1Rna",
}
out: Dict[str, str] = {}
for src, dst in mapping.items():
val = normalize_negative_positive(raw.get(src) or "") or (raw.get(src) or "")
if val:
# 台账 Excel 多用「阴」
if val in ("阴性", "阴"):
out[dst] = "阴"
elif val in ("阳性", "阳"):
out[dst] = "阳"
else:
out[dst] = val
return out
def extract_process_tests(tasks: List[Dict[str, Any]]) -> Dict[str, str]:
raw = _process_qual_from_tasks(tasks)
bacteria_values: List[str] = []
for task in tasks:
name = task.get("item_name") or ""
params = task.get("params") or []
hit = "细菌" in name or any("细菌" in (pn or "") for pn, _ in params)
if not hit:
continue
for _, pv in params:
bacteria_values.append(pv)
bacteria_values.extend(task.get("values") or [])
bacteria = qual_yin_yang(bacteria_values)
out = {
"endotoxinTest": _to_yin(raw.get("endotoxin_test")),
"fungusTest": _to_yin(raw.get("fungus_test")),
"mycoplasmaTest": _to_yin(raw.get("mycoplasma_test")),
}
if bacteria:
out["bacteriaTest"] = _to_yin(bacteria)
return {k: v for k, v in out.items() if v}
def _to_yin(value: Optional[str]) -> str:
text = (value or "").strip()
if text in ("阴性", "阴"):
return "阴"
if text in ("阳性", "阳"):
return "阳"
return text
def infectious_label(code: Optional[str]) -> str:
c = (code or "").strip()
if c == "zc":
return "正常"
if c == "bzc":
return "不正常"
return c
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,176 @@
"""实验室样本处理数据 — 字段目录与部门归属。"""
from __future__ import annotations
from dataclasses import dataclass
from typing import Dict, List, Optional, Tuple
DATASET_HSC = "hsc"
DATASET_UBMC = "ubmc"
DATASET_MSC = "msc"
DATASETS = (DATASET_HSC, DATASET_UBMC, DATASET_MSC)
DEPT_MARKET = "market"
DEPT_PRODUCTION = "production"
DEPT_QC = "qc"
DEPTS = (DEPT_MARKET, DEPT_PRODUCTION, DEPT_QC)
PERM_LIST = "lab:sample-processing:list"
PERM_MARKET_EDIT = "lab:sample-processing:market:edit"
PERM_PRODUCTION_EDIT = "lab:sample-processing:production:edit"
PERM_QC_EDIT = "lab:sample-processing:qc:edit"
PERM_MANAGER = "lab:sample-processing:manager"
DEPT_EDIT_PERMS = {
DEPT_MARKET: PERM_MARKET_EDIT,
DEPT_PRODUCTION: PERM_PRODUCTION_EDIT,
DEPT_QC: PERM_QC_EDIT,
}
SOURCE_PROTOCOL = "protocol"
SOURCE_RECEPTION = "reception"
SOURCE_PRODUCTION = "production_reception"
SOURCE_EXTRA = "extra"
@dataclass(frozen=True)
class FieldDef:
key: str
label: str
dept: str
source: str
attr: Optional[str] = None # ORM attr on source object when applicable
def _f(key: str, label: str, dept: str, source: str, attr: Optional[str] = None) -> FieldDef:
return FieldDef(key=key, label=label, dept=dept, source=source, attr=attr or key)
HSC_FIELDS: Tuple[FieldDef, ...] = (
_f("sampleCode", "细胞编码", DEPT_MARKET, SOURCE_PROTOCOL, "sample_code"),
_f("motherName", "准妈妈姓名", DEPT_MARKET, SOURCE_PROTOCOL, "mother_name"),
_f("collectTime", "采集时间", DEPT_MARKET, SOURCE_PROTOCOL, "sample_collect_time"),
_f("collectHospital", "采集医院", DEPT_MARKET, SOURCE_PROTOCOL, "hospital_name"),
_f("receptionTime", "接收时间", DEPT_PRODUCTION, SOURCE_RECEPTION, "reception_time"),
_f("receiveTemperature", "样品温度到达/℃", DEPT_PRODUCTION, SOURCE_RECEPTION, "receive_temperature"),
_f("receiveCheck", "收样检查", DEPT_PRODUCTION, SOURCE_EXTRA),
_f("hasMaternalBlood", "是否有母血", DEPT_PRODUCTION, SOURCE_EXTRA),
_f("remeasureMaternalBlood", "是否重采母血", DEPT_PRODUCTION, SOURCE_EXTRA),
_f("hasConsent", "知情同意书或协议书", DEPT_MARKET, SOURCE_EXTRA),
_f("hasPackingList", "脐血运输装箱清单", DEPT_MARKET, SOURCE_EXTRA),
_f("hasReceiveConfirm", "脐带血接收确认单", DEPT_PRODUCTION, SOURCE_EXTRA),
_f("hasHealthSurvey", "孕妇健康调查表", DEPT_MARKET, SOURCE_EXTRA),
_f("labelClear", "标识清晰", DEPT_PRODUCTION, SOURCE_EXTRA),
_f("receptionHandler", "接收登记人", DEPT_PRODUCTION, SOURCE_RECEPTION, "handler_name"),
_f("receptionRemark", "备注", DEPT_PRODUCTION, SOURCE_RECEPTION, "remark"),
_f("originalBloodWeightG", "原血重量/g", DEPT_PRODUCTION, SOURCE_PRODUCTION, "original_blood_weight_g"),
_f("hesVolumeMl", "HES用量/ml", DEPT_PRODUCTION, SOURCE_PRODUCTION, "hes_volume_ml"),
_f("bloodType", "血型", DEPT_PRODUCTION, SOURCE_PRODUCTION, "blood_type"),
_f("infectiousFourCard", "传染四项检测(检测卡)", DEPT_QC, SOURCE_PRODUCTION, "infectious_four_test_result"),
_f("infectiousFourExternal", "传染四项检测(外检)", DEPT_QC, SOURCE_EXTRA),
_f("preEnrichTnc", "富集前有核细胞数/109/L", DEPT_PRODUCTION, SOURCE_EXTRA),
_f("enrichedBloodWeightG", "富集后血量/g", DEPT_PRODUCTION, SOURCE_PRODUCTION, "enriched_blood_weight_g"),
_f("postEnrichTnc", "富集后有核细胞数/109/L", DEPT_PRODUCTION, SOURCE_EXTRA),
_f("cryoVolumeMl", "冻存液用量/ml", DEPT_PRODUCTION, SOURCE_PRODUCTION, "cryopreservation_volume_ml"),
_f("cd34Count", "CD34+细胞计数/*10E4", DEPT_QC, SOURCE_EXTRA),
_f("operatorName", "操作人", DEPT_PRODUCTION, SOURCE_PRODUCTION, "handler_name"),
_f("processRemark", "备注", DEPT_PRODUCTION, SOURCE_PRODUCTION, "remark"),
)
UBMC_FIELDS: Tuple[FieldDef, ...] = (
_f("sampleCode", "细胞编码", DEPT_MARKET, SOURCE_PROTOCOL, "sample_code"),
_f("motherName", "准妈妈姓名", DEPT_MARKET, SOURCE_PROTOCOL, "mother_name"),
_f("labMaterialCode", "实验室物料编码", DEPT_PRODUCTION, SOURCE_EXTRA),
_f("labStorageCode", "入库编码", DEPT_PRODUCTION, SOURCE_RECEPTION, "lab_storage_code"),
_f("storageStatus", "储存状态", DEPT_PRODUCTION, SOURCE_EXTRA),
_f("discardReason", "废弃原因", DEPT_PRODUCTION, SOURCE_EXTRA),
_f("receptionTime", "接收时间", DEPT_PRODUCTION, SOURCE_RECEPTION, "reception_time"),
_f("receiveTemperature", "样品温度到达/℃", DEPT_PRODUCTION, SOURCE_RECEPTION, "receive_temperature"),
_f("receiveCheck", "收样检查", DEPT_PRODUCTION, SOURCE_EXTRA),
_f("receptionHandler", "接收登记人", DEPT_PRODUCTION, SOURCE_RECEPTION, "handler_name"),
_f("receptionRemark", "备注", DEPT_PRODUCTION, SOURCE_RECEPTION, "remark"),
_f("originalBloodVolumeMl", "原血体积/mL", DEPT_PRODUCTION, SOURCE_PRODUCTION, "original_blood_volume_ml"),
_f("nucleatedCellCount1e8", "有核细胞数/108", DEPT_PRODUCTION, SOURCE_PRODUCTION, "nucleated_cell_count_1e8"),
_f("preOpTnc", "操作前有核细胞数/109/L", DEPT_PRODUCTION, SOURCE_EXTRA),
_f("infectiousFourCard", "传染四项检测(检测卡)", DEPT_QC, SOURCE_PRODUCTION, "infectious_four_test_result"),
_f("hbsag", "乙型肝炎病毒表面抗原(HBsAg)", DEPT_QC, SOURCE_EXTRA),
_f("antiHcv", "丙型肝炎病毒抗体(抗HCV)", DEPT_QC, SOURCE_EXTRA),
_f("antiTp", "梅毒螺旋体特异性抗体(抗TP)", DEPT_QC, SOURCE_EXTRA),
_f("antiHiv", "人类免疫缺陷病毒抗体(抗HIV-1/2)", DEPT_QC, SOURCE_EXTRA),
_f("cmvIgm", "巨细胞病毒IgM 抗体 (CMV-IgM)", DEPT_QC, SOURCE_EXTRA),
_f("operatorName", "操作人", DEPT_PRODUCTION, SOURCE_PRODUCTION, "handler_name"),
_f("processRemark", "备注", DEPT_PRODUCTION, SOURCE_PRODUCTION, "remark"),
)
MSC_FIELDS: Tuple[FieldDef, ...] = (
_f("sampleCode", "实验室流转编码", DEPT_MARKET, SOURCE_PROTOCOL, "sample_code"),
_f("motherName", "母亲姓名", DEPT_MARKET, SOURCE_PROTOCOL, "mother_name"),
_f("collectTime", "脐带采集时间", DEPT_MARKET, SOURCE_PROTOCOL, "sample_collect_time"),
_f("transportTempC", "运输温度/℃", DEPT_PRODUCTION, SOURCE_EXTRA),
_f("receptionTime", "脐带接收时间", DEPT_PRODUCTION, SOURCE_RECEPTION, "reception_time"),
_f("receptionHandler", "接收登记人", DEPT_PRODUCTION, SOURCE_RECEPTION, "handler_name"),
_f("inoculationAmount", "接种量", DEPT_PRODUCTION, SOURCE_PRODUCTION, "inoculation_amount"),
_f("storageStatus", "储存状态", DEPT_PRODUCTION, SOURCE_EXTRA),
_f("cryoTime", "冻存时间", DEPT_PRODUCTION, SOURCE_PRODUCTION, "cryopreservation_time"),
_f("storageTotalTubes", "储存总量(管)", DEPT_PRODUCTION, SOURCE_PRODUCTION, "storage_total_tubes"),
_f("availableCellCount1e7", "可提供细胞数量/*10E7", DEPT_PRODUCTION, SOURCE_PRODUCTION, "available_cell_count_1e7"),
_f("endotoxinTest", "内毒素检测", DEPT_QC, SOURCE_EXTRA),
_f("bacteriaTest", "细菌检测", DEPT_QC, SOURCE_EXTRA),
_f("fungusTest", "真菌检测", DEPT_QC, SOURCE_EXTRA),
_f("mycoplasmaTest", "支原体检测", DEPT_QC, SOURCE_EXTRA),
_f("operatorName", "操作人", DEPT_PRODUCTION, SOURCE_PRODUCTION, "handler_name"),
_f("motherHbsag", "乙型肝炎病毒表面抗原(HBsAg)", DEPT_QC, SOURCE_EXTRA),
_f("motherHbvDna", "乙型肝炎病毒核酸(HBV DNA)", DEPT_QC, SOURCE_EXTRA),
_f("motherAntiHcv", "丙型肝炎病毒抗体(抗HCV)", DEPT_QC, SOURCE_EXTRA),
_f("motherHcvRna", "丙型肝炎病毒核酸(HCV RNA)", DEPT_QC, SOURCE_EXTRA),
_f("motherAntiTp", "梅毒螺旋体特异性抗体(抗TP)", DEPT_QC, SOURCE_EXTRA),
_f("motherCmvIgm", "巨细胞病毒lgM 抗体 (CMV lgM)", DEPT_QC, SOURCE_EXTRA),
_f("motherAntiHiv", "人类免疫缺陷病毒抗体(抗HIV-1/2)", DEPT_QC, SOURCE_EXTRA),
_f("motherHiv1Rna", "人类免疫缺陷病毒核酸(1型) (HIV-1RNA)", DEPT_QC, SOURCE_EXTRA),
_f("storageDateP2", "储存日期(P2冻存日期)", DEPT_PRODUCTION, SOURCE_EXTRA),
_f("processRemark", "备注", DEPT_PRODUCTION, SOURCE_PRODUCTION, "remark"),
)
FIELDS_BY_DATASET: Dict[str, Tuple[FieldDef, ...]] = {
DATASET_HSC: HSC_FIELDS,
DATASET_UBMC: UBMC_FIELDS,
DATASET_MSC: MSC_FIELDS,
}
DATASET_LABELS = {
DATASET_HSC: "造血干细胞数据",
DATASET_UBMC: "单个核数据",
DATASET_MSC: "脐带间充质干细胞数据",
}
def fields_for(dataset: str) -> Tuple[FieldDef, ...]:
return FIELDS_BY_DATASET.get(dataset) or ()
def field_map(dataset: str) -> Dict[str, FieldDef]:
return {f.key: f for f in fields_for(dataset)}
def editable_depts_for_user(*, is_manager: bool, dept_flags: Dict[str, bool]) -> set:
if is_manager:
return set(DEPTS)
return {d for d, ok in dept_flags.items() if ok}
def resolve_dataset_by_type_name(name: Optional[str], sample_code: Optional[str] = None) -> Optional[str]:
text = (name or "").strip()
code = (sample_code or "").strip().upper()
if "单个核" in text or "脐血单个核" in text or code.startswith("UBMC"):
return DATASET_UBMC
if "间充质" in text or code.startswith("BC") or code.startswith("UC"):
return DATASET_MSC
if "造血" in text or code.startswith("B"):
return DATASET_HSC
return None
def schema_payload(dataset: str) -> List[Dict[str, str]]:
return [
{"key": f.key, "label": f.label, "dept": f.dept, "source": f.source}
for f in fields_for(dataset)
]
+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(
@@ -1,16 +1,23 @@
"""市场协议作废 ↔ 质检样本接收废弃双向联动。
"""市场协议无效态 ↔ 样本接收废弃 / 样本状态作废联动。
规则(细胞存储 / 科研捐赠):
1. 协议变为已作废(yzf)时,协议下全部样本接收结论自动为废弃(bj)。
2. 协议下全部有效样本均已废弃/拒收(bj)时,协议自动已作废,作废类型为「实验室废弃」。
1. 单条样本接收结论为废弃(bj)时:仅该样本 `sample_status` 置为已作废(yzf)并写 `void_date`;
协议状态保持不变。接收结论改回接收(js)且协议仍有效时:若该样本为 yzf,则清空状态与 void_date。
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 +30,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 +225,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 +263,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 +389,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 +409,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 +426,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 +465,169 @@ 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()
sample.sample_status = SAMPLE_VOID_STATUS
sample.void_date = _void_date_yyyymmdd(void_time=reception.reception_time or now)
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 +638,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 +674,7 @@ def after_protocol_voided(
tenant_no: str,
user_id: Optional[str] = None,
) -> None:
"""协议作废后:同步废弃其下全部样本接收。"""
"""协议作废/属地废弃后:同步废弃样本接收,并将样本状态置为已作废。"""
discard_receptions_for_voided_protocol(
db,
source=source,
@@ -419,3 +682,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
@@ -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,
)
+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,324 @@
"""将会议 Excel 三张表导入实验室样本处理补充台账。
用法(工程/worktree 根或 backend 下):
ENV_FILE=.../backend/.env python backend/scripts/import_lab_sample_processing_xlsx.py --xlsx PATH
"""
from __future__ import annotations
import argparse
import re
import sys
import zipfile
import xml.etree.ElementTree as ET
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 sqlalchemy.orm import Session # noqa: E402
from app.core.config import settings # noqa: E402
from app.core.database import SessionLocal # noqa: E402
from app.services.lab_sample_processing import upsert_extra_payload # noqa: E402
from app.services.lab_sample_processing_fields import ( # noqa: E402
DATASET_HSC,
DATASET_MSC,
DATASET_UBMC,
fields_for,
)
NS = {
"m": "http://schemas.openxmlformats.org/spreadsheetml/2006/main",
"r": "http://schemas.openxmlformats.org/officeDocument/2006/relationships",
}
SHEET_DATASET = {
"造血干细胞数据": DATASET_HSC,
"单个核数据": DATASET_UBMC,
"脐带间充质干细胞数据": DATASET_MSC,
}
LABEL_ALIASES = {
"细胞编码": "sampleCode",
"实验室流转编码": "sampleCode",
"准妈妈姓名": "motherName",
"母亲姓名": "motherName",
"采集时间": "collectTime",
"脐带采集时间": "collectTime",
"采集医院": "collectHospital",
"接收时间": "receptionTime",
"脐带接收时间": "receptionTime",
"样品温度到达/℃": "receiveTemperature",
"运输温度/℃": "transportTempC",
"运输温度\n/℃": "transportTempC",
"收样检查": "receiveCheck",
"是否有母血": "hasMaternalBlood",
"是否重采母血": "remeasureMaternalBlood",
"知情同意书或协议书": "hasConsent",
"脐血运输装箱清单": "hasPackingList",
"脐带血接收确认单": "hasReceiveConfirm",
"孕妇健康调查表": "hasHealthSurvey",
"标识清晰": "labelClear",
"接收登记人": "receptionHandler",
"原血重量/g": "originalBloodWeightG",
"HES用量/ml": "hesVolumeMl",
"血型": "bloodType",
"传染四项检测(检测卡)": "infectiousFourCard",
"传染四项检测(外检)": "infectiousFourExternal",
"富集前有核细胞数/109/L": "preEnrichTnc",
"富集后血量/g": "enrichedBloodWeightG",
"富集后有核细胞数/109/L": "postEnrichTnc",
"冻存液用量/ml": "cryoVolumeMl",
"CD34+细胞计数/*10E4": "cd34Count",
"操作人": "operatorName",
"实验室物料编码": "labMaterialCode",
"入库编码": "labStorageCode",
"储存状态": "storageStatus",
"废弃原因": "discardReason",
"原血体积/mL": "originalBloodVolumeMl",
"有核细胞数/108": "nucleatedCellCount1e8",
"操作前有核细胞数/109/L": "preOpTnc",
"乙型肝炎病毒表面抗原(HBsAg)": "hbsag",
"丙型肝炎病毒抗体(抗HCV)": "antiHcv",
"梅毒螺旋体特异性抗体(抗TP)": "antiTp",
"人类免疫缺陷病毒抗体(抗HIV-1/2)": "antiHiv",
"巨细胞病毒IgM 抗体 (CMV-IgM)": "cmvIgm",
"接种量": "inoculationAmount",
"冻存时间": "cryoTime",
"储存总量(管)": "storageTotalTubes",
"储存总量\n(管)": "storageTotalTubes",
"可提供细胞数量/*10E7": "availableCellCount1e7",
"内毒素检测": "endotoxinTest",
"细菌检测": "bacteriaTest",
"真菌检测": "fungusTest",
"支原体检测": "mycoplasmaTest",
"乙型肝炎病毒表面抗原(HBsAg):": "motherHbsag",
"乙型肝炎病毒核酸(HBV DNA)": "motherHbvDna",
"丙型肝炎病毒核酸(HCV RNA)": "motherHcvRna",
"巨细胞病毒lgM 抗体 (CMV lgM)": "motherCmvIgm",
"人类免疫缺陷病毒核酸(1型) (HIV-1RNA)": "motherHiv1Rna",
"储存日期\n(P2冻存日期)": "storageDateP2",
"储存日期(P2冻存日期)": "storageDateP2",
}
def _norm_label(s: str) -> str:
return re.sub(r"\s+", "", (s or "").replace("\r", "").strip())
def _col_row(ref: str):
m = re.match(r"([A-Z]+)(\d+)", ref)
col = m.group(1)
row = int(m.group(2))
n = 0
for ch in col:
n = n * 26 + ord(ch) - 64
return n, row
def read_sheet_matrix(z: zipfile.ZipFile, target: str):
ss = []
if "xl/sharedStrings.xml" in z.namelist():
root = ET.fromstring(z.read("xl/sharedStrings.xml"))
for si in root.findall("m:si", NS):
texts = [
t.text or ""
for t in si.iter("{http://schemas.openxmlformats.org/spreadsheetml/2006/main}t")
]
ss.append("".join(texts))
root = ET.fromstring(z.read(target))
rows = {}
for c in root.findall(".//m:sheetData/m:row/m:c", NS):
ref = c.attrib.get("r")
t = c.attrib.get("t")
v = c.find("m:v", NS)
if v is None or ref is None:
continue
val = v.text or ""
if t == "s":
try:
val = ss[int(val)]
except Exception:
pass
cn, rn = _col_row(ref)
rows.setdefault(rn, {})[cn] = val
if not rows:
return []
max_r = max(rows)
max_c = max(max(cols) for cols in rows.values())
matrix = []
for rn in range(1, max_r + 1):
line = [str(rows.get(rn, {}).get(c, "") or "").strip() for c in range(1, max_c + 1)]
matrix.append(line)
return matrix
def build_header_map(header_rows: list, dataset: str):
"""合并多行表头,按列映射到字段 key。"""
width = max(len(r) for r in header_rows)
merged = [""] * width
for r in header_rows:
for i in range(width):
cell = r[i] if i < len(r) else ""
if cell:
merged[i] = cell if not merged[i] else merged[i]
# MSC: 第二行填充分组子列
if len(header_rows) >= 2:
for i in range(width):
top = header_rows[0][i] if i < len(header_rows[0]) else ""
sub = header_rows[1][i] if i < len(header_rows[1]) else ""
if sub:
merged[i] = sub
elif top and not merged[i]:
merged[i] = top
label_to_key = {_norm_label(f.label): f.key for f in fields_for(dataset)}
for alias, key in LABEL_ALIASES.items():
label_to_key[_norm_label(alias)] = key
# 备注列:第一处 receptionRemark,第二处 processRemark
remark_keys = []
col_map = {}
for idx, label in enumerate(merged):
n = _norm_label(label)
if not n or n in {"序号"}:
continue
if n == "备注":
remark_keys.append(idx)
continue
# 母血相关与单项同名字段在 MSC 中优先 mother*
key = label_to_key.get(n)
if not key and n.endswith(":"):
key = label_to_key.get(n[:-1])
if key:
col_map[idx] = key
if remark_keys:
col_map[remark_keys[0]] = "receptionRemark"
if len(remark_keys) > 1:
col_map[remark_keys[1]] = "processRemark"
elif "processRemark" in {f.key for f in fields_for(dataset)} and dataset != DATASET_UBMC:
# 单备注时,造血第二业务备注也可能只有一列;保留 receptionRemark
pass
# UBMC 仅一列备注时落到 receptionRemark;有操作备注需求时同步 processRemark
return col_map, merged
def parse_workbook(path: Path):
out = {}
with zipfile.ZipFile(path) as z:
wb = ET.fromstring(z.read("xl/workbook.xml"))
sheets = []
for sh in wb.findall("m:sheets/m:sheet", NS):
sheets.append(
(
sh.attrib.get("name"),
sh.attrib.get("{http://schemas.openxmlformats.org/officeDocument/2006/relationships}id"),
)
)
rels = ET.fromstring(z.read("xl/_rels/workbook.xml.rels"))
rid_to_target = {rel.attrib["Id"]: rel.attrib["Target"] for rel in rels}
for name, rid in sheets:
dataset = SHEET_DATASET.get(name)
if not dataset:
continue
target = rid_to_target[rid]
if not target.startswith("xl/"):
target = "xl/" + target
matrix = read_sheet_matrix(z, target)
if not matrix:
continue
# MSC 两行表头;其他一行(UBMC 可能首列分组)
if dataset == DATASET_MSC:
header_rows = matrix[:2]
data_rows = matrix[2:]
else:
header_rows = matrix[:1]
data_rows = matrix[1:]
col_map, merged = build_header_map(header_rows, dataset)
records = []
for row in data_rows:
payload = {}
for idx, key in col_map.items():
val = row[idx] if idx < len(row) else ""
if val != "":
payload[key] = val
code = str(payload.get("sampleCode") or "").strip()
if not code:
continue
# UBMC 同名母血检测字段:Excel 用的是非 mother 前缀,已映射
# MSC 母血字段别名
if dataset == DATASET_MSC:
if "antiHcv" in payload and "motherAntiHcv" not in payload:
payload["motherAntiHcv"] = payload.pop("antiHcv")
if "antiTp" in payload and "motherAntiTp" not in payload:
payload["motherAntiTp"] = payload.pop("antiTp")
if "antiHiv" in payload and "motherAntiHiv" not in payload:
payload["motherAntiHiv"] = payload.pop("antiHiv")
if "hbsag" in payload and "motherHbsag" not in payload:
payload["motherHbsag"] = payload.pop("hbsag")
payload["sampleCode"] = code
records.append(payload)
out[dataset] = {"headers": merged, "records": records, "col_map": col_map}
return out
def import_all(db: Session, tenant_no: str, parsed: dict) -> dict:
summary = {}
for dataset, pack in parsed.items():
n = 0
for payload in pack["records"]:
upsert_extra_payload(
db,
tenant_no=tenant_no,
dataset=dataset,
sample_code=payload["sampleCode"],
payload=payload,
operator_id="excel-import",
replace=True,
)
n += 1
summary[dataset] = n
db.commit()
return summary
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--xlsx", required=True)
parser.add_argument("--tenant", default=None)
args = parser.parse_args()
xlsx = Path(args.xlsx)
if not xlsx.exists():
raise SystemExit(f"xlsx not found: {xlsx}")
parsed = parse_workbook(xlsx)
if not parsed:
raise SystemExit("no sheets parsed")
db = SessionLocal()
try:
tenant_no = args.tenant
if not tenant_no:
# 取库中任一有效租户
from app.models.models import SysUser
u = (
db.query(SysUser)
.filter(SysUser.del_flag == 0, SysUser.status == "1", SysUser.tenant_no.isnot(None))
.first()
)
tenant_no = (u.tenant_no if u else None) or "zkxw"
summary = import_all(db, tenant_no, parsed)
print("tenant", tenant_no)
for ds, n in summary.items():
print(f"imported {ds}={n}")
print("ok")
finally:
db.close()
if __name__ == "__main__":
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()
+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()
+103
View File
@@ -0,0 +1,103 @@
"""实验室样本处理台账:时间格式与字段合并。"""
from __future__ import annotations
import unittest
from datetime import datetime
from types import SimpleNamespace
from app.services.lab_sample_process import (
format_cn_datetime,
infectious_label,
merge_row,
)
class LabSampleProcessServiceTests(unittest.TestCase):
def test_format_cn_datetime(self):
self.assertEqual(
format_cn_datetime(datetime(2026, 11, 12, 0, 0, 0)),
"2026年11月12日 00时00分00秒",
)
self.assertEqual(
format_cn_datetime("2026-11-12 08:30:01"),
"2026年11月12日 08时30分01秒",
)
self.assertEqual(format_cn_datetime(""), "")
def test_infectious_label(self):
self.assertEqual(infectious_label("zc"), "正常")
self.assertEqual(infectious_label("bzc"), "不正常")
def test_merge_row_system_first_and_override(self):
merged = merge_row(
tab_key="donation_hsc",
system_values={"receiveCheckText": "系统汇总", "motherName": "张三"},
supplement={"receiveCheckText": "补录文案", "labMaterialCode": "M001"},
)
self.assertEqual(merged["receiveCheckText"], "补录文案")
self.assertEqual(merged["labMaterialCode"], "M001")
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()
+230
View File
@@ -0,0 +1,230 @@
import unittest
from app.services.lab_sample_processing_fields import (
DATASET_HSC,
DATASET_MSC,
DATASET_UBMC,
DEPT_MARKET,
DEPT_PRODUCTION,
DEPT_QC,
editable_depts_for_user,
field_map,
resolve_dataset_by_type_name,
schema_payload,
)
class LabSampleProcessingFieldsTest(unittest.TestCase):
def test_resolve_dataset(self):
self.assertEqual(resolve_dataset_by_type_name("围产期造血干细胞", "B0000001"), DATASET_HSC)
self.assertEqual(resolve_dataset_by_type_name("脐带间充质干细胞", "BC0000003"), DATASET_MSC)
self.assertEqual(resolve_dataset_by_type_name("", "UBMC2025001"), DATASET_UBMC)
self.assertEqual(resolve_dataset_by_type_name("", "UC2026001"), DATASET_MSC)
def test_schema_not_empty(self):
self.assertGreater(len(schema_payload(DATASET_HSC)), 10)
self.assertGreater(len(schema_payload(DATASET_UBMC)), 10)
self.assertGreater(len(schema_payload(DATASET_MSC)), 10)
def test_dept_acl(self):
self.assertEqual(
editable_depts_for_user(
is_manager=True,
dept_flags={DEPT_MARKET: False, DEPT_PRODUCTION: False, DEPT_QC: False},
),
{DEPT_MARKET, DEPT_PRODUCTION, DEPT_QC},
)
self.assertEqual(
editable_depts_for_user(
is_manager=False,
dept_flags={DEPT_MARKET: False, DEPT_PRODUCTION: True, DEPT_QC: False},
),
{DEPT_PRODUCTION},
)
def test_hsc_market_and_qc_fields(self):
fmap = field_map(DATASET_HSC)
self.assertEqual(fmap["motherName"].dept, DEPT_MARKET)
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
@@ -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,199 @@ 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",
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["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",
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())
if __name__ == "__main__":
@@ -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()
+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()
@@ -1,6 +1,11 @@
"""储存证质检字段 ACL:合法字段与 scope。"""
import unittest
from unittest.mock import MagicMock
from sqlalchemy.dialects import mysql
from app.crud import sample_storage_cert_qc_acl as acl_svc
from app.models.models import BizStorageCertQcAcl, BizStorageCertQcAclUser, SysUser
from app.services.sample_storage_cert_qc import (
ACL_SCOPE_PRODUCTION,
ACL_SCOPE_QC,
@@ -31,5 +36,66 @@ class TestAclFieldKeys(unittest.TestCase):
self.assertEqual(ACL_SCOPE_PRODUCTION, "production")
class TestAclUserJoinCollation(unittest.TestCase):
def test_detail_user_join_uses_unicode_collate(self):
"""JOIN sys_user 时统一 utf8mb4_unicode_ci,避免 1267 mix of collations。"""
acl = MagicMock()
acl.id = "acl-1"
acl.field_keys = "[]"
acl.configured_flag = "1"
captured = {}
class _Query:
def __init__(self, *args, **kwargs):
pass
def filter(self, *args, **kwargs):
captured.setdefault("filters", []).extend(args)
return self
def first(self):
return acl
def outerjoin(self, *args, **kwargs):
captured["join_on"] = args[1] if len(args) > 1 else None
return self
def order_by(self, *args, **kwargs):
return self
def all(self):
return []
db = MagicMock()
db.query.side_effect = lambda *args, **kwargs: _Query()
detail = acl_svc.get_acl_detail(db, "t1", "qc")
self.assertEqual(detail["scope"], "qc")
join_on = captured.get("join_on")
self.assertIsNotNone(join_on)
sql = str(
join_on.compile(dialect=mysql.dialect(), compile_kwargs={"literal_binds": True})
).lower()
self.assertIn("utf8mb4_unicode_ci", sql)
filter_sql = " ".join(
str(f.compile(dialect=mysql.dialect(), compile_kwargs={"literal_binds": True})).lower()
for f in captured.get("filters", [])
)
self.assertIn("utf8mb4_unicode_ci", filter_sql)
self.assertIn("sys_user", SysUser.__tablename__)
self.assertIn("biz_storage_cert_qc_acl_user", BizStorageCertQcAclUser.__tablename__)
self.assertEqual(BizStorageCertQcAcl.__tablename__, "biz_storage_cert_qc_acl")
def test_eq_unicode_literal_only_collates_column(self):
from app.core.db_collation import eq_unicode
expr = eq_unicode(BizStorageCertQcAcl.tenant_no, "t1")
sql = str(
expr.compile(dialect=mysql.dialect(), compile_kwargs={"literal_binds": True})
).lower()
self.assertIn("utf8mb4_unicode_ci", sql)
self.assertEqual(sql.count("utf8mb4_unicode_ci"), 1)
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") == []
+7 -4
View File
@@ -79,10 +79,13 @@
"evidence": "用户确认既有 Gitea/Drone Tag 打包已完成,本次不复查或修改流水线。"
},
"permissions": {
"push_task_branch": false,
"create_pr": false,
"write_issue": false,
"merge": false,
"push_task_branch": true,
"create_pr": true,
"write_issue": true,
"close_issue": true,
"merge": true,
"manage_claims": true,
"update_issue_labels": true,
"push_tag": false,
"deploy": false
},
@@ -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,14 @@
-- Issue #97:将储存证质检 ACL 表 collation 对齐库默认 utf8mb4_unicode_ci。
-- 修复与 sys_user 等表 JOIN 时 Illegal mix of collations。可重复执行。
ALTER TABLE biz_storage_cert_qc_acl
CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
ALTER TABLE biz_storage_cert_qc_acl_user
CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
SELECT table_name, table_collation
FROM information_schema.tables
WHERE table_schema = DATABASE()
AND table_name IN ('biz_storage_cert_qc_acl', 'biz_storage_cert_qc_acl_user')
ORDER BY table_name;
@@ -1,5 +1,6 @@
-- Issue #93:储存证质检信息字段级 ACL(质检/生产)。MySQL 5.7,可重复执行。
-- 不自动授予任何角色;管理员在角色管理中勾选「储存证质检字段权限配置」。
-- 菜单按钮「储存证质检字段权限配置」控制弹窗 footer 的「质检权限」「生产权限」入口;
-- 本脚本会将该按钮授权给当前租户下全部有效角色。
CREATE TABLE IF NOT EXISTS biz_storage_cert_qc_acl (
id VARCHAR(64) NOT NULL,
@@ -17,7 +18,7 @@ CREATE TABLE IF NOT EXISTS biz_storage_cert_qc_acl (
del_flag SMALLINT NOT NULL DEFAULT 0,
PRIMARY KEY (id),
KEY ix_tenant_scope (tenant_no, scope, del_flag)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS biz_storage_cert_qc_acl_user (
id VARCHAR(64) NOT NULL,
@@ -35,7 +36,7 @@ CREATE TABLE IF NOT EXISTS biz_storage_cert_qc_acl_user (
PRIMARY KEY (id),
KEY ix_tenant_acl (tenant_no, acl_id, del_flag),
KEY ix_tenant_user (tenant_no, user_id, del_flag)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
INSERT INTO sys_menu (
id, menu_name, parent_id, menu_type, path, component, perms,
@@ -60,6 +61,48 @@ WHERE parent.del_flag = 0 AND parent.status = '1'
AND existing.del_flag = 0
);
-- 给所有有效角色授予「质检权限 / 生产权限」配置按钮(同一菜单码)
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('storage-cert-qc-acl-role:', r.tenant_no, ':', r.id, ':', m.id)),
13, 1, '3'), 17, 1, '8'),
r.id,
m.id,
r.tenant_no,
NULL,
'migration: grant storage-cert-qc-acl to all roles',
'migration',
'',
NOW(),
'migration',
NOW(),
0
FROM sys_role AS r
JOIN sys_menu AS m
ON m.tenant_no = r.tenant_no
AND m.perms = 'cell-storage:sample-info:storage-cert-qc-acl'
AND m.del_flag = 0
AND m.status = '1'
WHERE r.del_flag = 0
AND NOT EXISTS (
SELECT 1 FROM sys_role_menu AS 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 tenant_no, parent_id, id, menu_name, perms, status
FROM sys_menu
WHERE perms = 'cell-storage:sample-info:storage-cert-qc-acl' AND del_flag = 0;
SELECT r.tenant_no, r.role_name, m.perms, rm.id AS role_menu_id
FROM sys_role_menu AS rm
JOIN sys_role AS r ON r.id = rm.role_id AND r.tenant_no = rm.tenant_no AND r.del_flag = 0
JOIN sys_menu AS m ON m.id = rm.menu_id AND m.tenant_no = rm.tenant_no AND m.del_flag = 0
WHERE m.perms = 'cell-storage:sample-info:storage-cert-qc-acl'
AND rm.del_flag = 0
ORDER BY r.tenant_no, r.role_name;
@@ -0,0 +1,148 @@
-- Issue #98:实验室样本处理数据台账(补录表 + 质检管理菜单)
-- MySQL 5.7,可重复执行。
CREATE TABLE IF NOT EXISTS biz_lab_sample_process_supplement (
id VARCHAR(64) NOT NULL,
lab_storage_code VARCHAR(32) NOT NULL COMMENT '实验室入库编码(唯一业务键)',
reception_source VARCHAR(20) NOT NULL DEFAULT 'cell_storage' COMMENT 'cell_storage|research_donation',
sample_type_name VARCHAR(100) NULL COMMENT '样本类型名称快照',
payload TEXT NOT 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_tenant_lab_code (tenant_no, lab_storage_code, del_flag),
KEY ix_tenant_source_type (tenant_no, reception_source, sample_type_name, del_flag)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- 菜单:挂在「质检管理」下(以样本接收菜单同父节点为准)
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-sample-process:', parent.tenant_no, ':', parent.id)),
13, 1, '3'), 17, 1, '8'),
'实验室样本处理数据', parent.parent_id, 'C',
'lab-sample-process',
'quality-inspection/lab-sample-process/index',
'biz:labSampleProcess:list',
1, '1', '1', parent.tenant_no, 35,
'质检管理-实验室样本处理数据台账',
'migration', '', NOW(), 'migration', NOW(), 0
FROM sys_menu AS parent
WHERE parent.del_flag = 0 AND parent.status = '1'
AND parent.perms = 'biz:sampleReception:list'
AND parent.parent_id IS NOT NULL
AND parent.parent_id != ''
AND NOT EXISTS (
SELECT 1 FROM sys_menu AS existing
WHERE existing.tenant_no = parent.tenant_no
AND existing.perms = 'biz:labSampleProcess:list'
AND existing.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
INSERT(INSERT(MD5(CONCAT('lab-sample-process-sup:', m.tenant_no, ':', m.id)),
13, 1, '3'), 17, 1, '8'),
'补录', m.id, 'F', '', NULL,
'biz:labSampleProcess:supplement',
1, '1', '1', m.tenant_no, 10,
'实验室样本处理数据-补录',
'migration', '', NOW(), 'migration', NOW(), 0
FROM sys_menu AS m
WHERE m.del_flag = 0 AND m.status = '1'
AND m.perms = 'biz:labSampleProcess:list'
AND NOT EXISTS (
SELECT 1 FROM sys_menu AS existing
WHERE existing.parent_id = m.id
AND existing.tenant_no = m.tenant_no
AND existing.perms = 'biz:labSampleProcess:supplement'
AND existing.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
INSERT(INSERT(MD5(CONCAT('lab-sample-process-exp:', m.tenant_no, ':', m.id)),
13, 1, '3'), 17, 1, '8'),
'导出', m.id, 'F', '', NULL,
'biz:labSampleProcess:export',
1, '1', '1', m.tenant_no, 20,
'实验室样本处理数据-导出',
'migration', '', NOW(), 'migration', NOW(), 0
FROM sys_menu AS m
WHERE m.del_flag = 0 AND m.status = '1'
AND m.perms = 'biz:labSampleProcess:list'
AND NOT EXISTS (
SELECT 1 FROM sys_menu AS existing
WHERE existing.parent_id = m.id
AND existing.tenant_no = m.tenant_no
AND existing.perms = 'biz:labSampleProcess:export'
AND existing.del_flag = 0
);
-- 授权给拥有样本接收列表权限的角色
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-sample-process-rm:', r.tenant_no, ':', r.id, ':', m.id)),
13, 1, '3'), 17, 1, '8'),
r.id,
m.id,
r.tenant_no,
NULL,
'migration: grant lab sample process from sample reception roles',
'migration',
'',
NOW(),
'migration',
NOW(),
0
FROM sys_role AS r
JOIN sys_role_menu AS src
ON src.role_id = r.id AND src.tenant_no = r.tenant_no AND src.del_flag = 0
JOIN sys_menu AS srcm
ON srcm.id = src.menu_id AND srcm.tenant_no = src.tenant_no AND srcm.del_flag = 0
AND srcm.perms = 'biz:sampleReception:list'
JOIN sys_menu AS m
ON m.tenant_no = r.tenant_no
AND m.perms IN (
'biz:labSampleProcess:list',
'biz:labSampleProcess:supplement',
'biz:labSampleProcess:export'
)
AND m.del_flag = 0
AND m.status = '1'
WHERE r.del_flag = 0
AND NOT EXISTS (
SELECT 1 FROM sys_role_menu AS 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 tenant_no, parent_id, id, menu_name, path, component, perms
FROM sys_menu
WHERE perms LIKE 'biz:labSampleProcess:%' AND del_flag = 0
ORDER BY tenant_no, order_num, perms;
@@ -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;
@@ -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,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;
+11
View File
@@ -25,6 +25,17 @@ export function fetchCreateReceiveAccount(data) {
return post('/web/admin/oa-approval/receive-accounts', data)
}
export function fetchUpdateReceiveAccount(id, data) {
return put(`/web/admin/oa-approval/receive-accounts/${id}`, data)
}
export function fetchDeleteReceiveAccount(id) {
return request({
url: `/web/admin/oa-approval/receive-accounts/${id}`,
method: 'DELETE'
})
}
export function fetchRelatedCandidates(params) {
return get('/web/admin/oa-approval/related-candidates', params)
}
@@ -23,23 +23,11 @@
</header>
<div class="market-list-card__fields">
<div
<MarketListField
v-for="field in previewFields"
:key="`${field.label}:${field.value}`"
class="market-list-card__field"
:class="{ 'is-wide': field.wide }"
>
<span>{{ field.label }}</span>
<van-tag
v-if="field.tag"
class="market-tag"
:type="resolveStatusTone(field.value, field.tagType)"
size="medium"
round
:title="field.value"
>{{ field.value }}</van-tag>
<b v-else :class="{ 'is-money': field.money }">{{ field.value }}</b>
</div>
:field="field"
/>
</div>
<!-- 每一期缴费:始终展示在「展开更多」上方,不收进总折叠 -->
@@ -70,15 +58,11 @@
</button>
<div v-show="periodOpenKeys[block.key]" class="market-list-card__period-body">
<div class="market-list-card__fields market-list-card__fields--compact">
<div
<MarketListField
v-for="field in block.fields"
:key="`${block.key}:${field.label}`"
class="market-list-card__field"
:class="{ 'is-wide': field.wide }"
>
<span>{{ field.label }}</span>
<b :class="{ 'is-money': field.money }">{{ field.value }}</b>
</div>
:field="field"
/>
</div>
</div>
</div>
@@ -102,44 +86,20 @@
<van-icon class="market-list-card__fields-toggle-chevron" name="arrow-down" />
</button>
<div v-show="fieldsOpen && collapsedFields.length" class="market-list-card__fields market-list-card__fields--folded">
<div
<MarketListField
v-for="field in collapsedFields"
:key="`more:${field.label}:${field.value}`"
class="market-list-card__field"
:class="{ 'is-wide': field.wide }"
>
<span>{{ field.label }}</span>
<van-tag
v-if="field.tag"
class="market-tag"
:type="resolveStatusTone(field.value, field.tagType)"
size="medium"
round
:title="field.value"
>{{ field.value }}</van-tag>
<b v-else :class="{ 'is-money': field.money }">{{ field.value }}</b>
</div>
:field="field"
/>
</div>
</div>
<div v-if="card.footerFields?.length && showFoldedFooter" class="market-list-card__fields">
<div
<MarketListField
v-for="field in card.footerFields"
:key="`footer:${field.label}:${field.value}`"
class="market-list-card__field"
:class="{ 'is-wide': field.wide }"
>
<span>{{ field.label }}</span>
<van-tag
v-if="field.tag"
class="market-tag"
:type="resolveStatusTone(field.value, field.tagType)"
size="medium"
round
:title="field.value"
>{{ field.value }}</van-tag>
<b v-else :class="{ 'is-money': field.money }">{{ field.value }}</b>
</div>
:field="field"
/>
</div>
<div
@@ -181,15 +141,11 @@
>{{ block.status }}</van-tag>
</div>
<div class="market-list-card__fields market-list-card__fields--compact">
<div
<MarketListField
v-for="field in block.fields"
:key="`${block.key}:${field.label}`"
class="market-list-card__field"
:class="{ 'is-wide': field.wide }"
>
<span>{{ field.label }}</span>
<b>{{ field.value }}</b>
</div>
:field="field"
/>
</div>
</div>
</div>
@@ -222,6 +178,7 @@
import { computed, ref, watch } from 'vue'
import { actionLabel, buildMarketCard } from '../list-presenter.js'
import { resolveStatusTone } from '../status-tone.js'
import MarketListField from './MarketListField.vue'
const props = defineProps({
item: { type: Object, required: true },
@@ -0,0 +1,44 @@
<template>
<div class="market-list-card__field" :class="{ 'is-wide': field.wide }">
<span>{{ field.label }}</span>
<span class="market-list-card__value">
<van-tag
v-if="field.tag"
class="market-tag"
:type="resolveStatusTone(field.value, field.tagType)"
size="medium"
round
:title="field.value"
>{{ field.value }}</van-tag>
<b v-else :class="{ 'is-money': field.money }">{{ field.value }}</b>
<button
v-if="field.helpTitle"
type="button"
class="market-list-card__help"
:aria-label="`查看${field.helpTitle}`"
:title="field.helpTitle"
@click="showHelp"
>
<van-icon name="question-o" />
</button>
</span>
</div>
</template>
<script setup>
import { showDialog } from 'vant'
import { resolveStatusTone } from '../status-tone.js'
const props = defineProps({
field: { type: Object, required: true }
})
function showHelp() {
showDialog({
title: props.field.helpTitle || '作废原因',
message: props.field.helpText || '—',
messageAlign: 'left',
confirmButtonText: '知道了'
})
}
</script>
+30 -1
View File
@@ -2,6 +2,7 @@ import { formatMoney } from './money.js'
import {
resolveStatusTag,
samplePaymentProgress,
sampleStatus,
payMode,
protocolStatus,
donationStatus,
@@ -94,6 +95,30 @@ const personName = (name, id) => {
: referenceId ? '未知人员' : '—'
}
const field = (labelText, value, options = {}) => ({ label: labelText, value: text(value), ...options })
function sampleVoidReason(item) {
if (item && Object.prototype.hasOwnProperty.call(item, 'sampleVoidDesc')) {
return String(item.sampleVoidDesc ?? '').trim()
}
return String(item?.voidDesc ?? '').trim()
}
/** 样本编码旁的样本状态;已作废时附带作废原因,供卡片问号展开 */
function sampleStatusField(item) {
const provided = String(item?.sampleStatusLabel ?? '').trim()
const code = String(item?.sampleStatus ?? '').trim()
if (!code && !provided) return field('样本状态', '')
const resolved = resolveStatusTag(sampleStatus, code)
const display = provided || resolved.label
const voided = code === 'yzf' || display === '已作废'
return field('样本状态', display, {
tag: true,
tagType: voided ? 'danger' : (code ? resolved.tagType : 'info'),
...(voided
? { helpTitle: '作废原因', helpText: sampleVoidReason(item) || '—' }
: {})
})
}
export function money(value) {
return formatMoney(value)
}
@@ -134,6 +159,7 @@ function protocolCard(item) {
field('所属项目', item.projectName || item.basic?.projectName || ((item.projectId || item.basic?.projectId) ? '历史项目' : '未归属')),
field('项目组', item.teamName || item.basic?.teamName),
field('样本编码', item.sampleCode || item.labStorageCode),
sampleStatusField(item),
field('采集日期', collectDate || item.donationDate),
field('当月核量号', item.monthlyVerifyNo),
field('实验室流转编号', item.labStorageCode || item.sampleCode),
@@ -172,6 +198,7 @@ function protocolCard(item) {
field('所属项目', item.projectName || item.basic?.projectName || ((item.projectId || item.basic?.projectId) ? '历史项目' : '未归属')),
field('项目组', item.teamName || item.basic?.teamName),
field('样本编码', item.sampleCode),
sampleStatusField(item),
field('登记日期', item.registerDate || item.donationDate),
field('母亲电话', item.motherPhone),
field('母亲身份证号', item.motherIdCard),
@@ -212,6 +239,7 @@ function chaseCard(item) {
field('客户', item.motherName),
field('联系电话', item.motherPhone),
field('样本编码', item.sampleCode),
sampleStatusField(item),
field('市场专员', personName(item.salesUserName, item.salesUserId)),
field('缴费方式', mode.label, { tag: true, tagType: mode.tagType }),
field('期次', `第 ${text(item.scheduleNo, '1')} 期`),
@@ -281,7 +309,7 @@ function paymentCard(item) {
statusTone: progress.tagType,
fields: [
field('姓名', item.motherName), field('手机号', item.motherPhone),
field('样本编码', item.sampleCode), field('签署日期', item.signDate),
field('样本编码', item.sampleCode), sampleStatusField(item), field('签署日期', item.signDate),
field('存储项目', item.sampleTypeName), field('合同总额', money(item.contractAmount), { money: true }),
field('缴费方式', mode.label, { tag: true, tagType: mode.tagType }),
field('应收总额', money(item.receivableAmount), { money: true })
@@ -311,6 +339,7 @@ function freightSampleBlock(row, index) {
field('母亲姓名', row?.motherName),
field('子女姓名', row?.newbornName),
field('样本编码', row?.sampleCode, { wide: true }),
sampleStatusField(row),
field('样本类型', row?.sampleTypeName, { wide: true })
]
}
+60 -1
View File
@@ -112,7 +112,7 @@ test('research donation protocol card matches excel-parity field set', () => {
const labels = card.fields.map((f) => f.label)
assert.equal(labels[2], '样本编码')
for (const label of [
'样本编码', '当月核量号', '实验室流转编号', '废弃原因', '样本类型',
'样本编码', '样本状态', '当月核量号', '实验室流转编号', '废弃原因', '样本类型',
'采集地区', '采集医院', '分娩时间', '采集时间', '市场专员', '地区经理',
'运输方式', '新生儿性别', '新生儿体重', '分娩方式', '胎次', '母血采集时间',
'知情同意书', '传染病检测报告', '协议书', '备注'
@@ -245,11 +245,70 @@ test('freight card shows the scope-safe visible count and collapsible sample blo
assert.equal(manager.sampleBlocks[1].fields.find((field) => field.label === '母亲姓名').value, '周雨桐')
assert.equal(manager.sampleBlocks[1].fields.find((field) => field.label === '子女姓名').value, '宝宝乙')
assert.equal(manager.sampleBlocks[1].fields.find((field) => field.label === '样本编码').value, 'S-2')
assert.equal(manager.sampleBlocks[1].fields.find((field) => field.label === '样本状态').value, '—')
assert.equal(manager.sampleBlocks[1].fields.find((field) => field.label === '样本类型').value, '脐带')
assert.ok(manager.fields.some((field) => field.label === '更新时间' && field.value === '2026-10-13 10:00:00'))
assert.ok(manager.fields.some((field) => field.label === '备注' && field.value === '同批送达'))
})
test('sample-coded list cards show sample status and a void reason affordance', () => {
const cases = [
['protocol', { source: 'cell_storage', sampleCode: 'S-1', sampleStatus: 'yrk', sampleStatusLabel: '已入库' }],
['payment-chase', { sampleCode: 'S-1', sampleStatus: 'jcz' }],
['payment', { sampleCode: 'S-1', motherName: '周雨桐', sampleStatus: 'ycj', sampleStatusLabel: '已采集' }]
]
for (const [module, item] of cases) {
const card = buildMarketCard(module, 'specialist', item)
const status = card.fields.find((field) => field.label === '样本状态')
assert.ok(status, module)
assert.equal(status.tag, true)
assert.equal(status.helpTitle, undefined)
}
assert.equal(
buildMarketCard('protocol', 'specialist', {
source: 'cell_storage', sampleCode: 'S-1', sampleStatus: 'yrk', sampleStatusLabel: '已入库'
}).fields.find((field) => field.label === '样本状态').value,
'已入库'
)
const detecting = buildMarketCard('payment-chase', 'specialist', {
sampleCode: 'S-1', sampleStatus: 'jcz'
}).fields.find((field) => field.label === '样本状态')
assert.equal(detecting.value, '检测中')
assert.equal(detecting.helpTitle, undefined)
assert.equal(detecting.helpText, undefined)
const voided = buildMarketCard('payment', 'specialist', {
motherName: '作废客户',
sampleCode: 'S-VOID',
sampleStatus: 'yzf',
voidDesc: '客户放弃存储'
})
const voidField = voided.fields.find((field) => field.label === '样本状态')
assert.equal(voidField.value, '已作废')
assert.equal(voidField.tagType, 'danger')
assert.equal(voidField.helpTitle, '作废原因')
assert.equal(voidField.helpText, '客户放弃存储')
const donation = buildMarketCard('protocol', 'specialist', {
source: 'research_donation',
sampleCode: 'S-D',
sampleStatus: 'yzf',
sampleStatusLabel: '已作废',
voidDesc: '协议级废弃说明',
sampleVoidDesc: '样本溶血'
})
assert.equal(donation.fields.find((field) => field.label === '废弃原因').value, '协议级废弃说明')
assert.equal(donation.fields.find((field) => field.label === '样本状态').helpText, '样本溶血')
const freight = buildMarketCard('freight', 'manager', {
freightNo: 'YF-VOID',
items: [{ sampleCode: 'S-V', sampleStatus: 'yzf', voidDesc: '运输破损' }]
})
const sampleStatus = freight.sampleBlocks[0].fields.find((field) => field.label === '样本状态')
assert.equal(sampleStatus.value, '已作废')
assert.equal(sampleStatus.helpText, '运输破损')
})
test('action labels cover module-specific operations', () => {
assert.equal(actionLabel('link'), '关联样本')
assert.equal(actionLabel('unlink'), '取消样本关联')
@@ -84,6 +84,7 @@ test('market list visual contract keeps search white, tags filled and actions ri
'./components/MarketDetailSection.vue',
'./components/MarketDetailNestedCard.vue',
'./components/MarketListCard.vue',
'./components/MarketListField.vue',
'./components/PresignOrderCard.vue',
'./components/PresignTransferCard.vue',
'./components/ProtocolSamplePaymentPanel.vue',
@@ -541,6 +542,16 @@ test('payment detail hosts PaymentDetailTransfersPanel and hides transfer bottom
assert.match(panel, /应缴批次/)
})
test('voided sample status uses a question icon and vant dialog', () => {
const field = source('./components/MarketListField.vue')
const card = source('./components/MarketListCard.vue')
assert.match(field, /name="question-o"/)
assert.match(field, /showDialog/)
assert.match(field, /field\.helpTitle/)
assert.match(field, /class="market-tag"/)
assert.match(card, /MarketListField/)
})
test('payment cards reproduce the Web Excel columns and operation labels', () => {
const presenter = source('./list-presenter.js')
const card = source('./components/MarketListCard.vue')
@@ -590,7 +601,7 @@ test('protocol cards expose the same business fields as the web list', async ()
})
assert.deepEqual(card.fields.map((field) => field.label), [
'所属项目', '项目组', '样本编码', '登记日期', '母亲电话', '母亲身份证号', '父亲姓名',
'所属项目', '项目组', '样本编码', '样本状态', '登记日期', '母亲电话', '母亲身份证号', '父亲姓名',
'新生儿性别', '分娩方式', '新生儿体重(克)', '采集地区', '采集医院',
'市场专员', '样本采集时间', '创建时间'
])
@@ -106,6 +106,14 @@ export const receptionSource = createRegistry({
basic_experiment: { label: '基础实验', tagType: 'primary' }
})
/** 协议/捐赠样本状态;与 Web sampleStatus 保持一致 */
export const sampleStatus = createRegistry({
ycj: { label: '已采集', tagType: 'primary' },
jcz: { label: '检测中', tagType: 'warning' },
yrk: { label: '已入库', tagType: 'success' },
yzf: { label: '已作废', tagType: 'danger' }
})
export const presignOrderStatus = createRegistry({
draft: { label: '草稿', tagType: 'info' },
active: { label: '进行中', tagType: 'warning' },
@@ -8,10 +8,19 @@ import {
payMode,
presignOrderStatus,
receptionSource,
sampleStatus,
transportType,
auditStatus
} from './status-tag-registry.js'
test('sample status yzf is 已作废/danger', () => {
assert.deepEqual(resolveStatusTag(sampleStatus, 'yzf'), {
label: '已作废',
tagType: 'danger'
})
assert.equal(resolveStatusTag(sampleStatus, 'yrk').label, '已入库')
})
test('sample progress dfj is 待缴费/info not 待缴清', () => {
assert.deepEqual(resolveStatusTag(samplePaymentProgress, 'dfj'), {
label: '待缴费',
@@ -150,6 +150,7 @@ import {
uploadAttachment
} from '../../api/oa.js'
import OaCommentFileCards from './OaCommentFileCards.vue'
import { hasOaCommentDraft } from '../oa-comment-draft.js'
import { attachmentFullUrl } from '../../utils/attachment.js'
import { isHarmonyWechat } from '../../utils/harmony-file-picker.js'
import HarmonyFileSource from '../../components/HarmonyFileSource.vue'
@@ -215,7 +216,8 @@ async function ensureUserCache() {
if (userCachePromise) return userCachePromise
userCachePromise = (async () => {
try {
const res = await fetchUserOptions()
// 同部门优先:由后端按当前登录用户部门排序
const res = await fetchUserOptions({ prioritizeCallerDept: true })
const list = Array.isArray(res) ? res : res?.list || []
const next = []
const seen = new Set()
@@ -516,12 +518,25 @@ function confirmMention() {
mentionVisible.value = false
}
async function onSend() {
const content = draft.value.trim()
if (!content && !mentionUsers.value.length && !picked.value.length) {
showToast('请填写评论、@人员或添加附件')
return
function draftPending() {
return hasOaCommentDraft({
content: draft.value,
mentionCount: mentionUsers.value.length,
attachmentCount: picked.value.length
})
}
/**
* 审批动作前冲刷未发送草稿:无草稿直接成功;有草稿则等同点击「发送」。
* @returns {Promise<boolean>} false 表示发送失败或忙碌,调用方应中止审批动作
*/
async function flushDraft(opts = {}) {
if (!draftPending()) return true
if (sending.value || uploading.value) {
showToast(uploading.value ? '附件上传中,请稍后再试' : '评论发送中,请稍后再试')
return false
}
const content = draft.value.trim()
sending.value = true
try {
await fetchCreateOaComment(props.instanceId, {
@@ -533,15 +548,27 @@ async function onSend() {
picked.value = []
mentionUsers.value = []
closeAtSuggest()
showToast('已发送')
if (!opts.quiet) showToast('已发送')
emit('refresh')
return true
} catch (e) {
showToast(e?.message || '发送失败')
return false
} finally {
sending.value = false
}
}
async function onSend() {
if (!draftPending()) {
showToast('请填写评论、@人员或添加附件')
return
}
await flushDraft()
}
defineExpose({ flushDraft, draftPending })
onMounted(() => {
void ensureUserCache()
})
@@ -52,6 +52,24 @@
<div class="oa-sheet-row__title">{{ a.label }}</div>
<div v-if="a.sub" class="oa-sheet-row__meta">{{ a.sub }}</div>
</div>
<div class="oa-sheet-row__actions" @click.stop>
<button
type="button"
class="oa-sheet-row__icon is-edit"
aria-label="编辑"
@click="openEdit(a.id)"
>
<van-icon name="edit" />
</button>
<button
type="button"
class="oa-sheet-row__icon is-delete"
aria-label="删除"
@click="confirmDelete(a.id)"
>
<van-icon name="delete-o" />
</button>
</div>
</div>
</van-checkbox-group>
<van-empty v-if="!loading && !filtered.length" description="暂无本人的收款账户" />
@@ -63,17 +81,17 @@
</div>
</van-popup>
<van-popup v-model:show="createVisible" position="bottom" round>
<van-popup v-model:show="formVisible" position="bottom" round>
<div class="oa-recv__sheet oa-recv__sheet--create">
<div class="oa-recv__hd">
<span @click="createVisible = false">取消</span>
<strong>新增收款账户</strong>
<span @click="formVisible = false">取消</span>
<strong>{{ formTitle }}</strong>
<span
class="oa-recv__ok"
:class="{ 'is-busy': createLoading }"
@click="submitCreate"
:class="{ 'is-busy': formLoading }"
@click="submitForm"
>
{{ createLoading ? '提交中' : '确定' }}
{{ formLoading ? '提交中' : '确定' }}
</span>
</div>
<div class="oa-recv__form">
@@ -87,45 +105,45 @@
<label class="oa-recv-field">
<span class="oa-recv-field__label">户名<b>*</b></span>
<span class="oa-recv-field__box">
<input v-model="createForm.accountName" maxlength="128" placeholder="请输入户名" />
<input v-model="formModel.accountName" maxlength="128" placeholder="请输入户名" />
</span>
</label>
<label class="oa-recv-field">
<span class="oa-recv-field__label">账号<b>*</b></span>
<span class="oa-recv-field__box">
<input v-model="createForm.accountNo" maxlength="128" placeholder="请输入账号" />
<input v-model="formModel.accountNo" maxlength="128" placeholder="请输入账号" />
</span>
</label>
<template v-if="createForm.accountType !== 'alipay'">
<template v-if="formModel.accountType !== 'alipay'">
<label class="oa-recv-field">
<span class="oa-recv-field__label">银行<b>*</b></span>
<span class="oa-recv-field__box">
<input v-model="createForm.bankName" maxlength="128" placeholder="如:中国工商银行" />
<input v-model="formModel.bankName" maxlength="128" placeholder="如:中国工商银行" />
</span>
</label>
<label class="oa-recv-field">
<span class="oa-recv-field__label">银行所在省<b>*</b></span>
<span class="oa-recv-field__box">
<input v-model="createForm.bankProvince" maxlength="64" placeholder="如:安徽省" />
<input v-model="formModel.bankProvince" maxlength="64" placeholder="如:安徽省" />
</span>
</label>
<label class="oa-recv-field">
<span class="oa-recv-field__label">银行所在市<b>*</b></span>
<span class="oa-recv-field__box">
<input v-model="createForm.bankCity" maxlength="64" placeholder="如:合肥市" />
<input v-model="formModel.bankCity" maxlength="64" placeholder="如:合肥市" />
</span>
</label>
<label class="oa-recv-field">
<span class="oa-recv-field__label">银行支行<b>*</b></span>
<span class="oa-recv-field__box">
<input v-model="createForm.bankBranch" maxlength="256" placeholder="请输入开户支行全称" />
<input v-model="formModel.bankBranch" maxlength="256" placeholder="请输入开户支行全称" />
</span>
</label>
</template>
<label class="oa-recv-field">
<span class="oa-recv-field__label">备注</span>
<span class="oa-recv-field__box oa-recv-field__box--area">
<textarea v-model="createForm.remark" maxlength="512" rows="2" placeholder="选填" />
<textarea v-model="formModel.remark" maxlength="512" rows="2" placeholder="选填" />
</span>
</label>
</div>
@@ -135,7 +153,7 @@
<van-popup v-model:show="typePickerVisible" position="bottom" round>
<van-picker
:columns="accountTypeColumns"
:model-value="[createForm.accountType]"
:model-value="[formModel.accountType]"
@confirm="onTypeConfirm"
@cancel="typePickerVisible = false"
/>
@@ -145,8 +163,13 @@
<script setup>
import { computed, onMounted, ref } from 'vue'
import { showToast } from 'vant'
import { fetchCreateReceiveAccount, fetchReceiveAccountOptions } from '../../api/oa.js'
import { showConfirmDialog, showToast } from 'vant'
import {
fetchCreateReceiveAccount,
fetchDeleteReceiveAccount,
fetchReceiveAccountOptions,
fetchUpdateReceiveAccount
} from '../../api/oa.js'
import {
ACCOUNT_TYPE_LABEL,
formatReceiveAccountLine,
@@ -170,17 +193,19 @@ const keyword = ref('')
const pendingIds = ref([])
const snapshotMap = ref(new Map())
const accountOptions = ref([])
const createVisible = ref(false)
const createLoading = ref(false)
const formVisible = ref(false)
const formLoading = ref(false)
const formMode = ref('create')
const editingId = ref('')
const typePickerVisible = ref(false)
const accountTypeColumns = [
{ text: '支付宝', value: 'alipay' },
{ text: '个人银行卡', value: 'personal' },
{ text: '对公银行账户', value: 'corporate' }
]
const createForm = ref(emptyCreateForm())
const formModel = ref(emptyForm())
function emptyCreateForm() {
function emptyForm() {
return {
accountType: 'alipay',
accountName: '',
@@ -193,8 +218,12 @@ function emptyCreateForm() {
}
}
const formTitle = computed(() =>
formMode.value === 'edit' ? '编辑收款账户' : '新增收款账户'
)
const accountTypeLabel = computed(
() => ACCOUNT_TYPE_LABEL[createForm.value.accountType] || ''
() => ACCOUNT_TYPE_LABEL[formModel.value.accountType] || ''
)
const normalized = computed(() => normalizeReceiveAccountModelValue(props.modelValue))
@@ -260,26 +289,78 @@ function optionFromSnap(snap) {
}
}
function upsertLocalSnap(snap) {
if (!snap.id) return
const map = new Map(snapshotMap.value)
map.set(snap.id, snap)
snapshotMap.value = map
const opt = optionFromSnap(snap)
const idx = accountOptions.value.findIndex((x) => x.id === snap.id)
if (idx >= 0) {
const next = [...accountOptions.value]
next[idx] = opt
accountOptions.value = next
} else {
accountOptions.value = [...accountOptions.value, opt]
}
}
function fillFormFromSnap(snap) {
const form = {
accountType: snap.accountType || 'alipay',
accountName: snap.accountName || '',
accountNo: snap.accountNo || '',
bankName: snap.bankName || '',
bankProvince: snap.bankProvince || '',
bankCity: snap.bankCity || '',
bankBranch: snap.bankBranch || '',
remark: snap.remark || ''
}
if (form.accountType === 'alipay') {
form.bankName = ''
form.bankProvince = ''
form.bankCity = ''
form.bankBranch = ''
}
formModel.value = form
}
function openCreate() {
createForm.value = emptyCreateForm()
formMode.value = 'create'
editingId.value = ''
formModel.value = emptyForm()
typePickerVisible.value = false
createVisible.value = true
formVisible.value = true
}
function openEdit(id) {
const tid = String(id || '').trim()
const snap = snapshotMap.value.get(tid)
if (!snap) {
showToast('账户不存在或已删除')
return
}
formMode.value = 'edit'
editingId.value = tid
fillFormFromSnap(snap)
typePickerVisible.value = false
formVisible.value = true
}
function onTypeConfirm({ selectedOptions }) {
const next = selectedOptions?.[0]?.value || 'alipay'
const form = { ...createForm.value, accountType: next }
const form = { ...formModel.value, accountType: next }
if (next === 'alipay') {
form.bankName = ''
form.bankProvince = ''
form.bankCity = ''
form.bankBranch = ''
}
createForm.value = form
formModel.value = form
typePickerVisible.value = false
}
function validateCreate(form) {
function validateForm(form) {
if (!form.accountName.trim()) return '请输入户名'
if (!form.accountNo.trim()) return '请输入账号'
if (form.accountType !== 'alipay') {
@@ -291,14 +372,7 @@ function validateCreate(form) {
return ''
}
async function submitCreate() {
if (createLoading.value) return
const form = createForm.value
const invalid = validateCreate(form)
if (invalid) {
showToast(invalid)
return
}
function buildPayload(form) {
const payload = {
accountType: form.accountType,
accountName: form.accountName.trim(),
@@ -316,36 +390,80 @@ async function submitCreate() {
payload.bankCity = form.bankCity.trim()
payload.bankBranch = form.bankBranch.trim()
}
createLoading.value = true
return payload
}
async function submitForm() {
if (formLoading.value) return
const form = formModel.value
const invalid = validateForm(form)
if (invalid) {
showToast(invalid)
return
}
const payload = buildPayload(form)
formLoading.value = true
try {
const created = await fetchCreateReceiveAccount(payload)
const snap = snapshotFromRow(created)
const row =
formMode.value === 'edit' && editingId.value
? await fetchUpdateReceiveAccount(editingId.value, payload)
: await fetchCreateReceiveAccount(payload)
const snap = snapshotFromRow(row)
if (!snap.id) {
showToast('创建成功但未返回账户 ID')
showToast(formMode.value === 'edit' ? '更新成功但未返回账户 ID' : '创建成功但未返回账户 ID')
return
}
await loadOptions()
if (!snapshotMap.value.has(snap.id)) {
const map = new Map(snapshotMap.value)
map.set(snap.id, snap)
snapshotMap.value = map
if (!accountOptions.value.some((x) => x.id === snap.id)) {
accountOptions.value = [...accountOptions.value, optionFromSnap(snap)]
upsertLocalSnap(snap)
if (formMode.value === 'edit') {
const selected = normalized.value.map((x) => x.id)
if (selected.includes(snap.id)) {
emitItems(selected.map((id) => snapshotMap.value.get(id)).filter(Boolean))
}
showToast('更新成功')
} else {
const selected = new Set(normalized.value.map((x) => x.id))
selected.add(snap.id)
emitItems([...selected].map((id) => snapshotMap.value.get(id)).filter(Boolean))
if (!pendingIds.value.includes(snap.id)) {
pendingIds.value = [...pendingIds.value, snap.id]
}
keyword.value = ''
showToast('创建成功')
}
const selected = new Set(normalized.value.map((x) => x.id))
selected.add(snap.id)
emitItems([...selected].map((id) => snapshotMap.value.get(id)).filter(Boolean))
if (!pendingIds.value.includes(snap.id)) {
pendingIds.value = [...pendingIds.value, snap.id]
}
keyword.value = ''
createVisible.value = false
showToast('创建成功')
formVisible.value = false
} catch (e) {
showToast(e?.message || '新增收款账户失败')
showToast(e?.message || (formMode.value === 'edit' ? '编辑收款账户失败' : '新增收款账户失败'))
} finally {
createLoading.value = false
formLoading.value = false
}
}
async function confirmDelete(id) {
const tid = String(id || '').trim()
const snap = snapshotMap.value.get(tid)
const name = snap?.accountName || tid
try {
await showConfirmDialog({
title: '删除收款账户',
message: `确定删除收款账户「${name}」吗?删除后不可再选;已提交单据中的账户快照仍保留。`
})
} catch {
return
}
try {
await fetchDeleteReceiveAccount(tid)
await loadOptions()
const nextSelected = normalized.value
.map((x) => x.id)
.filter((x) => x !== tid)
.map((x) => snapshotMap.value.get(x))
.filter(Boolean)
emitItems(nextSelected)
pendingIds.value = pendingIds.value.filter((x) => x !== tid)
showToast('删除成功')
} catch (e) {
showToast(e?.message || '删除收款账户失败')
}
}
@@ -411,6 +529,39 @@ onMounted(() => {
line-height: 1.5;
}
.oa-sheet-row__actions {
display: inline-flex;
flex: none;
gap: 6px;
align-items: center;
margin-left: 4px;
}
.oa-sheet-row__icon {
display: inline-flex;
align-items: center;
justify-content: center;
width: 36px;
height: 36px;
margin: 0;
padding: 0;
border: 0;
border-radius: 8px;
background: transparent;
font-size: 18px;
cursor: pointer;
}
.oa-sheet-row__icon.is-edit {
background: #ecfdf5;
color: var(--brand-green-dark, #16a34a);
}
.oa-sheet-row__icon.is-delete {
background: #fef2f2;
color: #dc2626;
}
.oa-recv__add {
display: flex;
gap: 6px;
+7
View File
@@ -0,0 +1,7 @@
/** 评论区是否有未发送草稿(文字 / @ / 附件) */
export function hasOaCommentDraft(input = {}) {
const content = String(input.content || '').trim()
const mentionCount = Number(input.mentionCount || 0)
const attachmentCount = Number(input.attachmentCount || 0)
return !!(content || mentionCount > 0 || attachmentCount > 0)
}
@@ -0,0 +1,14 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { hasOaCommentDraft } from './oa-comment-draft.js'
test('empty draft is false', () => {
assert.equal(hasOaCommentDraft({}), false)
assert.equal(hasOaCommentDraft({ content: ' ', mentionCount: 0, attachmentCount: 0 }), false)
})
test('text / mention / attachment counts as draft', () => {
assert.equal(hasOaCommentDraft({ content: '@test' }), true)
assert.equal(hasOaCommentDraft({ mentionCount: 1 }), true)
assert.equal(hasOaCommentDraft({ attachmentCount: 2 }), true)
})
+23
View File
@@ -631,6 +631,29 @@ body.van-toast--unclickable .presign-order-page * {
font-weight: 700;
}
.market-list-card__value {
display: flex;
min-width: 0;
align-items: center;
gap: 0;
}
.market-list-card__help {
display: inline-flex;
width: 44px;
height: 44px;
flex: 0 0 44px;
align-items: center;
justify-content: center;
margin: -10px -8px -10px -4px;
padding: 0;
border: 0;
background: transparent;
color: var(--market-primary-dark, #087f57);
font-size: 18px;
cursor: pointer;
}
.market-list-card__samples {
margin: 0 0 12px;
overflow: hidden;
+11 -1
View File
@@ -29,6 +29,7 @@
@refresh="reloadDetail"
/>
<OaCommentComposer
ref="commentComposerRef"
:instance-id="instanceId"
:instance-status="detail?.status || ''"
@refresh="reloadDetail"
@@ -238,6 +239,7 @@ const currentUserId = ref('')
const currentUserName = ref('')
const autoPrinted = ref(false)
const commentComposerRef = ref(null)
const commentVisible = ref(false)
const commentKind = ref('approve') // approve | reject | return
const commentText = ref('')
@@ -492,8 +494,16 @@ function goCopyRestart() {
})
}
function openComment(kind) {
/** 同意/拒绝/打回前先发送评论区未提交草稿 */
async function flushPendingComment() {
const flush = commentComposerRef.value?.flushDraft
if (!flush) return true
return await flush()
}
async function openComment(kind) {
if (!myPendingTask.value) return
if (!(await flushPendingComment())) return
commentKind.value = kind
commentText.value = defaultComment(kind)
commentVisible.value = true
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-11-12
@@ -0,0 +1,23 @@
## Context
附件三张表字段覆盖市场采集信息、实验室接收/处理与质检结果。系统内对应源主要为:
- 市场:`biz_protocol_party_customer`、`biz_protocol_collection_info`、`biz_collection_hospital`、`biz_protocol_sample`
- 生产/接收:`biz_sample_reception`、`biz_sample_production_reception`
- 质检:生产接收传染四项、储存证质检 payload、检查项结果;缺口进补充表
## Decisions
1. **数据集**:`hsc`(造血)、`ubmc`(单个核)、`msc`(脐带间充质),以样本类型名 / 编码前缀识别。
2. **权限码**:
- 列表:`lab:sample-processing:list`(三子页共用读)
- 部门编辑:`lab:sample-processing:market:edit` / `production:edit` / `qc:edit`
- 主管:`lab:sample-processing:manager`(可编辑全部部门字段)
3. **读写**:列表聚合只读源表 + 补充 JSON;更新时按字段 `source` 回写源表或补充表,服务端强制部门 ACL。
4. **UI**:P01 列表 + 筛选 + 导出;行内编辑弹窗按部门分区,无权字段只读。
5. **Figma**:MCP 授权不可用,按现有 Fresh Mint 列表页实现;合入后用户做视觉验收。
## Risks
- 历史 Excel 手工列与系统字段不完全一一对应,未映射列落补充表,避免阻断上线。
- 菜单种子不自动授权角色,需管理员分配。
@@ -0,0 +1,27 @@
## Why
2026-11-04 需求会议要求按线上三张实验室样本处理表(造血干细胞 / 单个核 / 脐带间充质)在系统中单独建模块,按市场、生产、质检拆分可编辑字段,支持筛选与导出。现有业务数据分散在协议、样本接收、生产接收与质检等表,缺少统一台账视图。
## What Changes
- 新增 Web 一级模块「实验室样本处理数据」,下挂三个子模块对应三张表。
- 按样本编码从现有业务表聚合展示全字段;部门员工可读全部、只写本部门字段;主管可写全部部门字段。
- 支持关键词/时间筛选与 Excel 导出。
- 无法直接回写源表的字段写入补充表 `biz_lab_sample_processing_extra`。
## Capabilities
### New Capabilities
- `lab-sample-processing-data`: 实验室样本处理数据聚合台账、部门字段 ACL、筛选导出
### Modified Capabilities
- (无)
## Impact
- **backend**:聚合服务、API、补充表、菜单权限
- **web-admin**:三子模块列表页、编辑弹窗、导出
- **docs/sql**:结构 + 菜单种子
- **不改** mobile-h5 / mobile-oa-h5
@@ -0,0 +1,33 @@
## ADDED Requirements
### Requirement: 三子模块台账
系统 SHALL 提供「实验室样本处理数据」模块,包含造血干细胞、单个核、脐带间充质三个子模块;每个子模块按样本展示该表全部约定字段。
#### Scenario: 按数据集查询
- **WHEN** 用户打开造血干细胞子模块并具备列表权限
- **THEN** 系统仅返回造血干细胞数据集样本行,并包含市场/生产/质检字段聚合结果
### Requirement: 部门字段编辑权限
系统 SHALL 允许具备列表权限的用户查看全部字段;普通员工仅可编辑本部门字段;具备主管权限的用户可编辑全部部门字段。服务端 MUST 拒绝无权字段写入。
#### Scenario: 生产员工改市场字段被拒
- **WHEN** 仅有生产编辑权限的用户提交市场部门字段变更
- **THEN** 系统拒绝该请求且不持久化无权字段
#### Scenario: 主管可改全部
- **WHEN** 具备主管权限的用户提交跨部门字段变更
- **THEN** 系统接受并回写对应数据源或补充表
### Requirement: 筛选与导出
系统 SHALL 支持按样本编码、姓名关键词及接收/采集时间范围筛选,并导出当前筛选结果为 Excel。
#### Scenario: 导出当前筛选
- **WHEN** 用户在筛选条件下点击导出
- **THEN** 下载的表格列与当前子模块字段目录一致,行集与列表筛选一致
@@ -0,0 +1,21 @@
## 1. 规格与数据
- [x] 1.1 建立 OpenSpec 变更与字段/权限设计
- [x] 1.2 定义三数据集字段目录与部门归属、回写源
## 2. 后端
- [x] 2.1 补充表模型与迁移 SQL、菜单种子
- [x] 2.2 聚合列表 / 详情 / 更新 / 导出 API 与部门 ACL
- [x] 2.3 单元测试:数据集识别、字段 ACL、无权拒绝
## 3. 前端
- [x] 3.1 共享列表页组件(筛选、编辑、导出)
- [x] 3.2 三子模块路由与菜单码
- [x] 3.3 API 客户端
## 4. 验证
- [x] 4.1 受影响单元测试
- [ ] 4.2 字段一致性/菜单说明回写工单(凭据就绪后)
+6 -3
View File
@@ -22,9 +22,12 @@ export function fetchGetRoleList() {
})
}
/** 流程设计器:用户下拉选项(label=昵称,value=用户ID) */
export function fetchUserOptions(params?: { roleName?: string }) {
return request.get<Array<{ label: string; value: string }>>({
/** 用户下拉选项(label=昵称,value=用户ID;可选 deptId / prioritizeCallerDept) */
export function fetchUserOptions(params?: {
roleName?: string
prioritizeCallerDept?: boolean
}) {
return request.get<Array<{ label: string; value: string; deptId?: string }>>({
url: '/web/admin/users/options',
params
})
+29
View File
@@ -0,0 +1,29 @@
import request from '@/utils/http'
export type SampleVoidTarget = {
receptionSource: 'cell_storage' | 'research_donation'
sampleId?: string
sampleCode?: string
/** 仅弹窗展示,不参与作废请求 */
labStorageCode?: string
protocolId?: string
}
export type VoidBusinessSamplePayload = SampleVoidTarget & {
voidDesc: string
}
export type VoidBusinessSampleResult = {
id: string
sampleCode: string
sampleStatus: string
voidDate: string
voidDesc: string
}
export function fetchVoidBusinessSample(data: VoidBusinessSamplePayload) {
return request.put<VoidBusinessSampleResult>({
url: '/web/admin/business-samples/void',
data
})
}
+55
View File
@@ -0,0 +1,55 @@
import request from '@/utils/http'
export type LabSampleProcessTabKey =
| 'cell_hsc'
| 'donation_hsc'
| 'cell_msc'
| 'donation_msc'
export interface LabSampleProcessListParams {
tabKey: LabSampleProcessTabKey
page?: number
pageSize?: number
labStorageCode?: string
motherName?: string
createTimeStart?: string
createTimeEnd?: string
}
export function fetchLabSampleProcessList(params: LabSampleProcessListParams) {
return request.get<{
list: Record<string, unknown>[]
total: number
page: number
pageSize: number
tabKey: string
supplementKeys: string[]
}>({
url: '/web/admin/lab-sample-process/list',
params
})
}
export function fetchLabSampleProcessSupplement(labStorageCode: string) {
return request.get<{
labStorageCode?: string
payload?: Record<string, string>
remark?: string
}>({
url: '/web/admin/lab-sample-process/supplement',
params: { labStorageCode }
})
}
export function saveLabSampleProcessSupplement(body: {
labStorageCode: string
receptionSource: string
sampleTypeName: string
payload: Record<string, string>
remark?: string
}) {
return request.put({
url: '/web/admin/lab-sample-process/supplement',
data: body
})
}
@@ -0,0 +1,74 @@
import request from '@/utils/http'
export type LabSampleDataset = 'hsc' | 'ubmc' | 'msc'
export interface LabSampleFieldMeta {
key: string
label: string
dept: 'market' | 'production' | 'qc'
source: string
}
export interface LabSampleAcl {
canList?: boolean
isManager?: boolean
editableDepts?: string[]
deptFlags?: Record<string, boolean>
}
export function fetchLabSampleMeta(dataset: LabSampleDataset) {
return request.get<{
dataset: LabSampleDataset
label: string
fields: LabSampleFieldMeta[]
acl: LabSampleAcl
}>({
url: `/web/admin/lab-sample-processing/meta/${dataset}`
})
}
export function fetchLabSampleList(
dataset: LabSampleDataset,
params: {
keyword?: string
dateFrom?: string
dateTo?: string
page?: number
pageSize?: number
}
) {
return request.get<{
list: Record<string, any>[]
total: number
page: number
pageSize: number
fields: LabSampleFieldMeta[]
acl: LabSampleAcl
}>({
url: `/web/admin/lab-sample-processing/${dataset}/list`,
params
})
}
export function updateLabSampleRow(
dataset: LabSampleDataset,
sampleCode: string,
payload: Record<string, any>
) {
return request.put<Record<string, any>>({
url: `/web/admin/lab-sample-processing/${dataset}/${encodeURIComponent(sampleCode)}`,
data: { payload }
})
}
export function exportLabSampleUrl(
dataset: LabSampleDataset,
params: { keyword?: string; dateFrom?: string; dateTo?: string }
) {
const q = new URLSearchParams()
if (params.keyword) q.set('keyword', params.keyword)
if (params.dateFrom) q.set('dateFrom', params.dateFrom)
if (params.dateTo) q.set('dateTo', params.dateTo)
const qs = q.toString()
return `/api/web/admin/lab-sample-processing/${dataset}/export${qs ? `?${qs}` : ''}`
}
@@ -17,6 +17,10 @@ export interface ProductionWorkOrderItem {
workOrderType?: string
protocolNo?: string
sampleCode?: string
sampleStatus?: string
voidDesc?: string
protocolSampleId?: string
collectionProtocolId?: string
receptionSource?: string
receptionSourceLabel?: string
sampleTypeName?: string
+4
View File
@@ -100,6 +100,8 @@ export type QcWorkOrder = {
collectionProtocolId: string
protocolNo: string
sampleCode: string
sampleStatus?: string
voidDesc?: string
labStorageCode?: string
receptionSource?: string
receptionSourceLabel?: string
@@ -141,6 +143,8 @@ export type QcWorkOrder = {
patientName?: string
/** 入库工单(细胞存储/科研捐赠):母亲姓名 */
motherName?: string
/** 协议单母血采集时间;未录入时为空,前端展示为 — */
maternalBloodCollectTime?: string
/** 入库工单(细胞存储/科研捐赠):新生儿姓名 */
newbornName?: string
/** 出库工单:当前为第几次输注计划 */
+2
View File
@@ -5,6 +5,8 @@ export type SampleFreightItem = {
sampleId: string
protocolId?: string
sampleCode?: string
sampleStatus?: string
voidDesc?: string
protocolNo?: string
sampleTypeName?: string
motherName?: string
@@ -0,0 +1,71 @@
<!-- 样本状态:标签;仅已作废时展示问号与作废原因 -->
<template>
<span class="sample-status-tag">
<el-tag :type="tagType" size="small">{{ label }}</el-tag>
<el-popover v-if="voided" placement="top" trigger="click" :width="240">
<template #reference>
<button type="button" class="sample-status-tag__q" aria-label="作废原因" @click.stop>
<el-icon><QuestionFilled /></el-icon>
</button>
</template>
<div class="sample-status-tag__reason">
<div class="sample-status-tag__reason-title">作废原因</div>
<div>{{ reasonText }}</div>
</div>
</el-popover>
</span>
</template>
<script setup lang="ts">
import { computed } from 'vue'
import { QuestionFilled } from '@element-plus/icons-vue'
import { sampleStatusLabel, sampleStatusTagType } from '@/utils/status-tag-registry'
defineOptions({ name: 'SampleStatusTag' })
const props = defineProps<{
status?: string | null
voidDesc?: string | null
}>()
const code = computed(() => String(props.status || '').trim())
const label = computed(() => (code.value ? sampleStatusLabel(code.value) : '—'))
const tagType = computed(() => (code.value ? sampleStatusTagType(code.value) : 'info'))
/** 问号仅已作废(yzf)展示 */
const voided = computed(() => code.value === 'yzf')
const reasonText = computed(() => String(props.voidDesc || '').trim() || '暂无作废原因')
</script>
<style scoped lang="scss">
.sample-status-tag {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 4px;
max-width: 100%;
vertical-align: middle;
}
.sample-status-tag__q {
display: inline-flex;
align-items: center;
justify-content: center;
padding: 0;
border: none;
background: transparent;
color: var(--mint-text-muted, #64748b);
cursor: pointer;
line-height: 1;
font-size: 14px;
&:hover {
color: #059669;
}
}
.sample-status-tag__reason-title {
margin-bottom: 4px;
font-size: 12px;
color: var(--mint-text-muted, #64748b);
}
</style>
@@ -0,0 +1,145 @@
<!-- 样本废弃:填写作废原因后提交 -->
<template>
<el-dialog
v-model="dialogVisible"
title="样本废弃"
width="560px"
class="dialog-form-layout"
align-center
append-to-body
modal-class="protocol-dialog-mask"
destroy-on-close
:close-on-click-modal="false"
@close="handleClose"
>
<el-form
ref="formRef"
:model="form"
:rules="rules"
label-position="top"
class="biz-dialog-form"
>
<div class="form-grid-2">
<el-form-item label="实验室入库编码" class="form-col-span-2">
<span class="sample-void-dialog__code">{{ labStorageCodeDisplay }}</span>
</el-form-item>
<el-form-item v-if="sampleCode" label="样本编码" class="form-col-span-2">
<span class="sample-void-dialog__code">{{ sampleCode }}</span>
</el-form-item>
<el-form-item label="作废原因" prop="voidDesc" class="form-col-span-2">
<el-input
v-model="form.voidDesc"
type="textarea"
:rows="4"
maxlength="512"
show-word-limit
placeholder="请填写作废原因"
/>
</el-form-item>
</div>
</el-form>
<template #footer>
<el-button class="btn-ghost" @click="handleClose">
<el-icon><Close /></el-icon>取消
</el-button>
<el-button class="btn-main" type="primary" :loading="submitting" @click="handleSubmit">
<el-icon><Check /></el-icon>确定
</el-button>
</template>
</el-dialog>
</template>
<script setup lang="ts">
import { computed, reactive, ref, watch } from 'vue'
import { Check, Close } from '@element-plus/icons-vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { fetchVoidBusinessSample, type SampleVoidTarget } from '@/api/business-sample'
defineOptions({ name: 'SampleVoidDialog' })
const props = defineProps<{
visible: boolean
target: SampleVoidTarget | null
}>()
const emit = defineEmits<{
'update:visible': [visible: boolean]
success: []
}>()
const dialogVisible = ref(false)
const submitting = ref(false)
const formRef = ref<FormInstance>()
const form = reactive({
voidDesc: ''
})
const rules: FormRules = {
voidDesc: [
{
required: true,
validator: (_rule, value, callback) => {
if (!String(value || '').trim()) callback(new Error('请填写作废原因'))
else callback()
},
trigger: 'blur'
}
]
}
const labStorageCodeDisplay = computed(
() => String(props.target?.labStorageCode || '').trim() || '—'
)
const sampleCode = computed(() => String(props.target?.sampleCode || '').trim())
watch(
() => props.visible,
(visible) => {
dialogVisible.value = visible
if (visible) form.voidDesc = ''
},
{ immediate: true }
)
watch(dialogVisible, (visible) => {
emit('update:visible', visible)
})
function handleClose() {
dialogVisible.value = false
}
async function handleSubmit() {
const target = props.target
if (!target?.receptionSource || (!target.sampleId && !target.sampleCode)) {
ElMessage.warning('缺少样本信息,无法废弃')
return
}
const valid = await formRef.value?.validate().catch(() => false)
if (!valid) return
submitting.value = true
try {
await fetchVoidBusinessSample({
receptionSource: target.receptionSource,
sampleId: target.sampleId,
sampleCode: target.sampleCode,
protocolId: target.protocolId,
voidDesc: form.voidDesc.trim()
})
ElMessage.success('样本已废弃')
emit('success')
handleClose()
} finally {
submitting.value = false
}
}
</script>
<style scoped lang="scss">
.sample-void-dialog__code {
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
font-size: 14px;
font-weight: 600;
color: #1e293b;
}
</style>
@@ -13,9 +13,19 @@
<div v-loading="loading" class="storage-cert-qc-acl-dialog__body">
<el-tabs v-model="activeTab">
<el-tab-pane label="勾选可编辑字段" name="fields">
<div class="field-toolbar">
<el-button @click="selectAllFields">
<el-icon><Select /></el-icon>
全选
</el-button>
<el-button @click="clearAllFields">
<el-icon><RefreshLeft /></el-icon>
取消全选
</el-button>
</div>
<div v-for="(group, gi) in fieldGroups" :key="gi" class="field-block">
<div class="field-block__title">{{ group.title }}</div>
<el-checkbox-group v-model="selectedKeys">
<el-checkbox-group v-model="selectedKeys" class="field-check-grid">
<el-checkbox
v-for="field in group.fields"
:key="field.key"
@@ -66,7 +76,7 @@
</template>
<script setup lang="ts">
import { Check, Close } from '@element-plus/icons-vue'
import { Check, Close, RefreshLeft, Select } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { fetchUserList } from '@/api/admin'
import {
@@ -113,6 +123,40 @@
return Array.from(map.values())
})
const allFieldKeys = computed(() => {
const keys: string[] = []
const seen = new Set<string>()
for (const group of fieldGroups.value) {
for (const field of group.fields) {
if (seen.has(field.key)) continue
seen.add(field.key)
keys.push(field.key)
}
}
return keys
})
function selectAllFields() {
selectedKeys.value = [...allFieldKeys.value]
}
function clearAllFields() {
selectedKeys.value = []
}
function formatUserOption(row: {
id?: string
nickName?: string
userName?: string
userNo?: string
}) {
const id = String(row.id || '')
if (!id) return null
const name = String(row.nickName || row.userName || row.userNo || id)
const account = String(row.userName || row.userNo || '')
return { value: id, label: account ? `${name}(${account})` : name }
}
function upsertUserOption(id: string, label: string) {
if (!id) return
if (userOptions.value.some((u) => u.value === id)) return
@@ -126,15 +170,32 @@
page: 1,
pageSize: 50,
status: '1',
keyword: keyword || undefined
keyword: (keyword || '').trim() || undefined
})
const list = (res as any)?.list || []
const next: Array<{ label: string; value: string }> = []
const seen = new Set<string>()
for (const row of list) {
const id = String(row.id || '')
const name = String(row.nickName || row.userName || row.userNo || id)
const account = String(row.userName || row.userNo || '')
upsertUserOption(id, account ? `${name}(${account})` : name)
const opt = formatUserOption(row)
if (!opt || seen.has(opt.value)) continue
seen.add(opt.value)
next.push(opt)
}
// 已选人员不在本页结果中时保留,避免标签丢失且不影响远程模糊检索展示
for (const id of selectedUserIds.value) {
if (seen.has(id)) continue
const keep = userOptions.value.find((u) => u.value === id)
if (keep) {
seen.add(id)
next.unshift(keep)
}
}
userOptions.value = next
} catch {
// 检索失败时仍保留已选项,避免清空已配置人员标签
userOptions.value = userOptions.value.filter((u) =>
selectedUserIds.value.includes(u.value)
)
} finally {
userLoading.value = false
}
@@ -149,14 +210,15 @@
selectedUserIds.value = Array.isArray(detail?.userIds) ? [...detail.userIds] : []
userOptions.value = []
for (const u of detail?.users || []) {
const id = String(u.id || '')
const name = String(u.nickName || u.userName || id)
const account = String(u.userName || '')
upsertUserOption(id, account ? `${name}(${account})` : name)
}
if (!userOptions.value.length) {
await searchUsers('')
const opt = formatUserOption({
id: u.id,
nickName: u.nickName,
userName: u.userName
})
if (opt) upsertUserOption(opt.value, opt.label)
}
// 预拉一批启用用户;真正按姓名/账号模糊检索在输入时由 remote-method 触发
await searchUsers('')
} catch {
selectedKeys.value = []
selectedUserIds.value = []
@@ -193,6 +255,13 @@
min-height: 280px;
}
.field-toolbar {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin-bottom: 12px;
}
.field-block {
margin-bottom: 14px;
}
@@ -204,10 +273,31 @@
color: var(--el-color-primary-dark-2, #059669);
}
.field-check-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 6px 16px;
width: 100%;
}
.field-check {
display: flex;
align-items: flex-start;
margin-right: 0;
margin-bottom: 6px;
margin-bottom: 0;
height: auto;
white-space: normal;
:deep(.el-checkbox__label) {
white-space: normal;
line-height: 1.4;
}
}
@media (max-width: 560px) {
.field-check-grid {
grid-template-columns: 1fr;
}
}
.form-tip {
@@ -192,6 +192,7 @@
} from '@/api/oaApproval'
import OaCommentFileCards from '@/components/oa-approval/OaCommentFileCards.vue'
import { attachmentFullUrl } from '@/composables/useAttachmentActions'
import { hasOaCommentDraft } from '@/utils/oa-comment-draft'
import { isOaUploadImageFile, isOaUploadVideoFile } from '@/utils/oa-upload-file-type'
defineOptions({ name: 'OaCommentPanel' })
@@ -254,7 +255,8 @@
if (userCachePromise) return userCachePromise
userCachePromise = (async () => {
try {
const res = await fetchUserOptions()
// 同部门优先:由后端按当前登录用户部门排序
const res = await fetchUserOptions({ prioritizeCallerDept: true })
const list = Array.isArray(res) ? res : []
const next: MentionUser[] = []
const seen = new Set<string>()
@@ -546,12 +548,25 @@
}
}
async function onSend() {
const content = draft.value.trim()
if (!content && !mentionUsers.value.length && !picked.value.length) {
ElMessage.warning('请填写评论、@人员或添加附件')
return
function draftPending() {
return hasOaCommentDraft({
content: draft.value,
mentionCount: mentionUsers.value.length,
attachmentCount: picked.value.length
})
}
/**
* 审批动作前冲刷未发送草稿:无草稿直接成功;有草稿则等同点击「发送」。
* @returns false 表示发送失败或忙碌,调用方应中止审批动作
*/
async function flushDraft(opts?: { quiet?: boolean }): Promise<boolean> {
if (!draftPending()) return true
if (sending.value || uploading.value) {
ElMessage.warning(uploading.value ? '附件上传中,请稍后再试' : '评论发送中,请稍后再试')
return false
}
const content = draft.value.trim()
sending.value = true
try {
await fetchCreateOaComment(props.instanceId, {
@@ -565,15 +580,27 @@
picked.value = []
mentionUsers.value = []
closeAtSuggest()
ElMessage.success('已发送')
if (!opts?.quiet) ElMessage.success('已发送')
emit('refresh')
return true
} catch (e: any) {
ElMessage.error(e?.message || '发送失败')
return false
} finally {
sending.value = false
}
}
async function onSend() {
if (!draftPending()) {
ElMessage.warning('请填写评论、@人员或添加附件')
return
}
await flushDraft()
}
defineExpose({ flushDraft, draftPending })
onMounted(() => {
void ensureUserCache()
})
@@ -40,17 +40,39 @@
class="oa-receive-account-select__search"
/>
<div class="oa-receive-account-select__list">
<label
<div
v-for="a in filteredOptions"
:key="a.id"
class="oa-receive-account-select__row"
>
<el-checkbox
:model-value="pendingIds.includes(a.id)"
@change="(v: boolean | string | number) => onNarrowCheck(a.id, !!v)"
/>
<span class="oa-receive-account-select__row-label">{{ a.label }}</span>
</label>
<label class="oa-receive-account-select__row-main">
<el-checkbox
:model-value="pendingIds.includes(a.id)"
@change="(v: boolean | string | number) => onNarrowCheck(a.id, !!v)"
/>
<span class="oa-receive-account-select__row-label">{{ a.label }}</span>
</label>
<div class="oa-receive-account-select__row-actions">
<button
type="button"
class="oa-receive-account-select__icon-btn is-edit"
title="编辑"
aria-label="编辑"
@click="openEditDialog(a.id)"
>
<el-icon><Edit /></el-icon>
</button>
<button
type="button"
class="oa-receive-account-select__icon-btn is-delete"
title="删除"
aria-label="删除"
@click="confirmDelete(a.id)"
>
<el-icon><Delete /></el-icon>
</button>
</div>
</div>
<div v-if="!filteredOptions.length" class="oa-receive-account-select__empty">
暂无本人的收款账户
</div>
@@ -92,7 +114,31 @@
:key="a.id"
:label="a.label"
:value="a.id"
/>
>
<div class="oa-receive-account-select__option">
<span class="oa-receive-account-select__option-label">{{ a.label }}</span>
<span class="oa-receive-account-select__option-actions" @mousedown.prevent @click.stop>
<button
type="button"
class="oa-receive-account-select__icon-btn is-edit"
title="编辑"
aria-label="编辑"
@click="openEditDialog(a.id)"
>
<el-icon><Edit /></el-icon>
</button>
<button
type="button"
class="oa-receive-account-select__icon-btn is-delete"
title="删除"
aria-label="删除"
@click="confirmDelete(a.id)"
>
<el-icon><Delete /></el-icon>
</button>
</span>
</div>
</el-option>
<template #empty>
<div class="oa-receive-account-select__empty">
{{ accountOptions.length === 0 ? '暂无本人的收款账户' : '无匹配数据' }}
@@ -120,8 +166,8 @@
</template>
<el-dialog
v-model="createVisible"
title="新增收款账户"
v-model="formVisible"
:title="formTitle"
width="720px"
class="dialog-form-layout"
align-center
@@ -131,9 +177,9 @@
:close-on-click-modal="false"
>
<el-form
ref="createFormRef"
:model="createForm"
:rules="createRules"
ref="formRef"
:model="formModel"
:rules="formRules"
label-position="top"
scroll-to-error
:scroll-into-view-options="{ behavior: 'smooth', block: 'center' }"
@@ -141,9 +187,9 @@
<div class="form-grid-2">
<el-form-item label="账户类型" prop="accountType" class="form-col-span-2">
<el-select
v-model="createForm.accountType"
v-model="formModel.accountType"
placeholder="请选择"
@change="onCreateTypeChange"
@change="onFormTypeChange"
>
<el-option
v-for="(label, value) in ACCOUNT_TYPE_LABEL"
@@ -154,22 +200,22 @@
</el-select>
</el-form-item>
<el-form-item label="户名" prop="accountName">
<el-input v-model="createForm.accountName" placeholder="请输入户名" maxlength="128" />
<el-input v-model="formModel.accountName" placeholder="请输入户名" maxlength="128" />
</el-form-item>
<el-form-item label="账号" prop="accountNo">
<el-input v-model="createForm.accountNo" placeholder="请输入账号" maxlength="128" />
<el-input v-model="formModel.accountNo" placeholder="请输入账号" maxlength="128" />
</el-form-item>
<template v-if="createForm.accountType !== 'alipay'">
<template v-if="formModel.accountType !== 'alipay'">
<el-form-item label="银行" prop="bankName">
<el-input
v-model="createForm.bankName"
v-model="formModel.bankName"
placeholder="如:中国工商银行"
maxlength="128"
/>
</el-form-item>
<el-form-item label="银行所在省" prop="bankProvince">
<el-input
v-model="createForm.bankProvince"
v-model="formModel.bankProvince"
placeholder="如:安徽省"
maxlength="64"
clearable
@@ -177,7 +223,7 @@
</el-form-item>
<el-form-item label="银行所在市" prop="bankCity">
<el-input
v-model="createForm.bankCity"
v-model="formModel.bankCity"
placeholder="如:合肥市"
maxlength="64"
clearable
@@ -185,7 +231,7 @@
</el-form-item>
<el-form-item label="银行支行" prop="bankBranch" class="form-col-span-2">
<el-input
v-model="createForm.bankBranch"
v-model="formModel.bankBranch"
placeholder="请输入开户支行全称"
maxlength="256"
/>
@@ -193,7 +239,7 @@
</template>
<el-form-item label="备注" class="form-col-span-2">
<el-input
v-model="createForm.remark"
v-model="formModel.remark"
type="textarea"
:rows="2"
placeholder="选填"
@@ -203,15 +249,15 @@
</div>
</el-form>
<template #footer>
<el-button class="btn-ghost" @click="createVisible = false">
<el-button class="btn-ghost" @click="formVisible = false">
<el-icon><Close /></el-icon>
取消
</el-button>
<el-button
class="btn-main"
type="primary"
:loading="createLoading"
@click="submitCreate"
:loading="formLoading"
@click="submitForm"
>
<el-icon><Check /></el-icon>
确定
@@ -223,11 +269,13 @@
<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, onMounted, reactive, ref } from 'vue'
import { Check, Close, Plus } from '@element-plus/icons-vue'
import { Check, Close, Delete, Edit, Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
fetchCreateOaReceiveAccount,
fetchOaReceiveAccountOptions
fetchDeleteOaReceiveAccount,
fetchOaReceiveAccountOptions,
fetchUpdateOaReceiveAccount
} from '@/api/oaApproval'
import {
ACCOUNT_TYPE_LABEL,
@@ -253,6 +301,7 @@
}>()
type AccountOpt = { id: string; label: string }
type FormMode = 'create' | 'edit'
const snapshotMap = ref(new Map<string, ReceiveAccountSnapshot>())
const accountOptions = ref<AccountOpt[]>([])
@@ -263,10 +312,12 @@
const selectRef = ref<{ blur?: () => void } | null>(null)
let mql: MediaQueryList | null = null
const createVisible = ref(false)
const createLoading = ref(false)
const createFormRef = ref()
const createForm = reactive({
const formVisible = ref(false)
const formLoading = ref(false)
const formMode = ref<FormMode>('create')
const editingId = ref('')
const formRef = ref()
const formModel = reactive({
accountType: 'alipay' as ReceiveAccountType,
accountName: '',
accountNo: '',
@@ -277,8 +328,12 @@
remark: ''
})
const formTitle = computed(() =>
formMode.value === 'edit' ? '编辑收款账户' : '新增收款账户'
)
const requireWhenBank = (_rule: any, value: string, callback: (e?: Error) => void) => {
if (createForm.accountType === 'alipay') {
if (formModel.accountType === 'alipay') {
callback()
return
}
@@ -289,7 +344,7 @@
callback()
}
const createRules = computed(() => ({
const formRules = computed(() => ({
accountType: [{ required: true, message: '请选择账户类型', trigger: 'change' }],
accountName: [{ required: true, message: '请输入户名', trigger: 'blur' }],
accountNo: [{ required: true, message: '请输入账号', trigger: 'blur' }],
@@ -358,90 +413,161 @@
drawerVisible.value = false
}
function clearCreateBankFields() {
createForm.bankName = ''
createForm.bankProvince = ''
createForm.bankCity = ''
createForm.bankBranch = ''
function clearBankFields() {
formModel.bankName = ''
formModel.bankProvince = ''
formModel.bankCity = ''
formModel.bankBranch = ''
}
function resetCreateForm() {
createForm.accountType = 'alipay'
createForm.accountName = ''
createForm.accountNo = ''
clearCreateBankFields()
createForm.remark = ''
function resetFormModel() {
formModel.accountType = 'alipay'
formModel.accountName = ''
formModel.accountNo = ''
clearBankFields()
formModel.remark = ''
}
function onCreateTypeChange() {
if (createForm.accountType === 'alipay') clearCreateBankFields()
createFormRef.value?.clearValidate?.()
function fillFormFromSnap(snap: ReceiveAccountSnapshot) {
formModel.accountType = snap.accountType
formModel.accountName = snap.accountName
formModel.accountNo = snap.accountNo
formModel.bankName = snap.bankName
formModel.bankProvince = snap.bankProvince
formModel.bankCity = snap.bankCity
formModel.bankBranch = snap.bankBranch
formModel.remark = snap.remark
if (formModel.accountType === 'alipay') clearBankFields()
}
function onFormTypeChange() {
if (formModel.accountType === 'alipay') clearBankFields()
formRef.value?.clearValidate?.()
}
function buildPayload() {
const payload: Record<string, unknown> = {
accountType: formModel.accountType,
accountName: formModel.accountName.trim(),
accountNo: formModel.accountNo.trim(),
remark: formModel.remark?.trim() || undefined
}
if (formModel.accountType === 'alipay') {
payload.bankName = ''
payload.bankProvince = ''
payload.bankCity = ''
payload.bankBranch = ''
} else {
payload.bankName = formModel.bankName.trim()
payload.bankProvince = formModel.bankProvince.trim()
payload.bankCity = formModel.bankCity.trim()
payload.bankBranch = formModel.bankBranch.trim()
}
return payload
}
function upsertLocalSnap(snap: ReceiveAccountSnapshot) {
if (!snap.id) return
const map = new Map(snapshotMap.value)
map.set(snap.id, snap)
snapshotMap.value = map
const label = optionLabelFromRow(snap)
const idx = accountOptions.value.findIndex((x) => x.id === snap.id)
if (idx >= 0) {
const next = [...accountOptions.value]
next[idx] = { id: snap.id, label }
accountOptions.value = next
} else {
accountOptions.value = [...accountOptions.value, { id: snap.id, label }]
}
}
function openCreateDialog() {
selectRef.value?.blur?.()
resetCreateForm()
createVisible.value = true
nextTick(() => createFormRef.value?.clearValidate?.())
formMode.value = 'create'
editingId.value = ''
resetFormModel()
formVisible.value = true
nextTick(() => formRef.value?.clearValidate?.())
}
async function submitCreate() {
function openEditDialog(id: string) {
const tid = String(id || '').trim()
const snap = snapshotMap.value.get(tid)
if (!snap) {
ElMessage.error('账户不存在或已删除')
return
}
selectRef.value?.blur?.()
formMode.value = 'edit'
editingId.value = tid
fillFormFromSnap(snap)
formVisible.value = true
nextTick(() => formRef.value?.clearValidate?.())
}
async function submitForm() {
try {
await createFormRef.value?.validate?.()
await formRef.value?.validate?.()
} catch {
ElMessageBox.alert('请完善必填项后再提交', '提示', { type: 'warning' })
return
}
createLoading.value = true
formLoading.value = true
try {
const payload: Record<string, unknown> = {
accountType: createForm.accountType,
accountName: createForm.accountName.trim(),
accountNo: createForm.accountNo.trim(),
remark: createForm.remark?.trim() || undefined
}
if (createForm.accountType === 'alipay') {
payload.bankName = ''
payload.bankProvince = ''
payload.bankCity = ''
payload.bankBranch = ''
const payload = buildPayload()
let row: any
if (formMode.value === 'edit' && editingId.value) {
row = await fetchUpdateOaReceiveAccount(editingId.value, payload)
} else {
payload.bankName = createForm.bankName.trim()
payload.bankProvince = createForm.bankProvince.trim()
payload.bankCity = createForm.bankCity.trim()
payload.bankBranch = createForm.bankBranch.trim()
row = await fetchCreateOaReceiveAccount(payload)
}
const created = await fetchCreateOaReceiveAccount(payload)
const snap = snapshotFromRow(created)
const snap = snapshotFromRow(row)
if (!snap.id) {
ElMessage.error('创建成功但未返回账户 ID')
ElMessage.error(formMode.value === 'edit' ? '更新成功但未返回账户 ID' : '创建成功但未返回账户 ID')
return
}
await loadOptions()
// 确保新账户在 map 中(options 可能短暂未刷新)
if (!snapshotMap.value.has(snap.id)) {
const map = new Map(snapshotMap.value)
map.set(snap.id, snap)
snapshotMap.value = map
if (!accountOptions.value.some((x) => x.id === snap.id)) {
accountOptions.value = [
...accountOptions.value,
{ id: snap.id, label: optionLabelFromRow(snap) }
]
upsertLocalSnap(snap)
if (formMode.value === 'edit') {
if (selectModel.value.includes(snap.id)) {
emitFromIds(selectModel.value)
}
} else {
const nextIds = [...selectModel.value]
if (!nextIds.includes(snap.id)) nextIds.push(snap.id)
emitFromIds(nextIds)
if (drawerVisible.value && !pendingIds.value.includes(snap.id)) {
pendingIds.value = [...pendingIds.value, snap.id]
}
}
const nextIds = [...selectModel.value]
if (!nextIds.includes(snap.id)) nextIds.push(snap.id)
emitFromIds(nextIds)
if (drawerVisible.value && !pendingIds.value.includes(snap.id)) {
pendingIds.value = [...pendingIds.value, snap.id]
}
createVisible.value = false
formVisible.value = false
} finally {
createLoading.value = false
formLoading.value = false
}
}
async function confirmDelete(id: string) {
const tid = String(id || '').trim()
const snap = snapshotMap.value.get(tid)
const name = snap?.accountName || tid
try {
await ElMessageBox.confirm(
`确定删除收款账户「${name}」吗?删除后不可再选;已提交单据中的账户快照仍保留。`,
'删除收款账户',
{ type: 'warning', confirmButtonText: '删除', cancelButtonText: '取消' }
)
} catch {
return
}
selectRef.value?.blur?.()
await fetchDeleteOaReceiveAccount(tid)
await loadOptions()
const nextSelected = selectModel.value.filter((x) => x !== tid)
emitFromIds(nextSelected)
pendingIds.value = pendingIds.value.filter((x) => x !== tid)
}
async function loadOptions() {
try {
const res = await fetchOaReceiveAccountOptions()
@@ -512,6 +638,53 @@
min-height: 40px;
}
.oa-receive-account-select__option {
display: flex;
gap: 8px;
align-items: center;
justify-content: space-between;
width: 100%;
min-width: 0;
}
.oa-receive-account-select__option-label {
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.oa-receive-account-select__option-actions,
.oa-receive-account-select__row-actions {
display: inline-flex;
flex-shrink: 0;
gap: 4px;
align-items: center;
}
.oa-receive-account-select__icon-btn {
display: inline-flex;
align-items: center;
justify-content: center;
width: 28px;
height: 28px;
padding: 0;
border: 0;
border-radius: 6px;
cursor: pointer;
}
.oa-receive-account-select__icon-btn.is-edit {
background: var(--mint-primary-bg, #ecfdf5);
color: var(--mint-primary-dark, #059669);
}
.oa-receive-account-select__icon-btn.is-delete {
background: #fef2f2;
color: #dc2626;
}
.oa-receive-account-select__add-footer {
padding: 4px 8px 8px;
border-top: 1px solid var(--mint-border, #d9e8e2);
@@ -597,6 +770,14 @@
align-items: center;
min-height: 44px;
padding: 6px 4px;
}
.oa-receive-account-select__row-main {
display: flex;
flex: 1;
gap: 8px;
align-items: center;
min-width: 0;
cursor: pointer;
}
@@ -630,5 +811,10 @@
.oa-receive-account-select__trigger {
min-height: 44px;
}
.oa-receive-account-select__icon-btn {
width: 36px;
height: 36px;
}
}
</style>
+33
View File
@@ -190,6 +190,17 @@ export const sqxpAdminRoutes: AppRouteRecord[] = [
menuCode: 'biz:cellStoragePaymentConfirm:list'
}
},
{
id: 'CEL0000000000000000000000000LSP1',
name: 'CellStorageLabSampleProcess',
path: 'lab-sample-process',
component: '/quality-inspection/lab-sample-process/index',
meta: {
title: '实验室样本处理数据',
keepAlive: true,
menuCode: 'cellStorage:labSampleProcess:list'
}
},
// 市场侧入库放行审核(总览)暂下线:改由生产/质检入口审核
// {
// id: '70000000000000000000000000000011',
@@ -922,6 +933,17 @@ export const sqxpAdminRoutes: AppRouteRecord[] = [
keepAlive: true,
menuCode: 'production:waste-output:list'
}
},
{
id: 'PRM0000000000000000000000000LSP1',
name: 'ProductionLabSampleProcess',
path: 'lab-sample-process',
component: '/quality-inspection/lab-sample-process/index',
meta: {
title: '实验室样本处理数据',
keepAlive: true,
menuCode: 'production:labSampleProcess:list'
}
}
]
},
@@ -1190,6 +1212,17 @@ export const sqxpAdminRoutes: AppRouteRecord[] = [
menuCode: 'quality:storageReleaseReview:list'
},
props: { reviewRole: 'qc' }
},
{
id: '70000000000000000000000000000015',
name: 'QualityInspectionLabSampleProcess',
path: 'lab-sample-process',
component: '/quality-inspection/lab-sample-process/index',
meta: {
title: '实验室样本处理数据',
keepAlive: true,
menuCode: 'biz:labSampleProcess:list'
}
}
]
},
@@ -0,0 +1,141 @@
import type { LabSampleProcessTabKey } from '@/api/lab-sample-process'
export type LabColumn = {
prop: string
label: string
minWidth?: number
}
export const LAB_PROCESS_TABS: Array<{
key: LabSampleProcessTabKey
label: string
source: 'cell_storage' | 'research_donation'
sampleTypeName: string
}> = [
{
key: 'cell_hsc',
label: '细胞存储·围产期造血',
source: 'cell_storage',
sampleTypeName: '围产期造血干细胞'
},
{
key: 'donation_hsc',
label: '科研捐赠·围产期造血',
source: 'research_donation',
sampleTypeName: '围产期造血干细胞'
},
{
key: 'cell_msc',
label: '细胞存储·脐带间充质',
source: 'cell_storage',
sampleTypeName: '脐带间充质干细胞'
},
{
key: 'donation_msc',
label: '科研捐赠·脐带间充质',
source: 'research_donation',
sampleTypeName: '脐带间充质干细胞'
}
]
const CELL_HSC_COLUMNS: LabColumn[] = [
{ prop: 'cellCode', label: '细胞编码', minWidth: 140 },
{ prop: 'sampleStatus', label: '样本状态', minWidth: 140 },
{ prop: 'motherName', label: '准妈妈姓名', minWidth: 110 },
{ prop: 'collectionTime', label: '采集时间', minWidth: 200 },
{ prop: 'hospitalName', label: '采集医院', minWidth: 140 },
{ prop: 'receptionTime', label: '接收时间', minWidth: 200 },
{ prop: 'receiveTemperature', label: '样品温度到达/℃', minWidth: 130 },
{ prop: 'receiveCheckText', label: '收样检查', minWidth: 120 },
{ prop: 'hasMaternalBlood', label: '是否有母血', minWidth: 100 },
{ prop: 'remeasureMaternalBlood', label: '是否重采母血', minWidth: 110 },
{ prop: 'consentForm', label: '知情同意书或协议书', minWidth: 140 },
{ prop: 'transportPackingList', label: '脐血运输装箱清单', minWidth: 140 },
{ prop: 'cordBloodReceiveConfirm', label: '脐带血接收确认单', minWidth: 140 },
{ prop: 'healthSurvey', label: '孕妇健康调查表', minWidth: 120 },
{ prop: 'labelClear', label: '标识清晰', minWidth: 100 },
{ prop: 'handlerName', label: '接收登记人', minWidth: 110 },
{ prop: 'remarkReception', label: '备注', minWidth: 120 },
{ prop: 'originalBloodWeightG', label: '原血重量/g', minWidth: 110 },
{ prop: 'hesVolumeMl', label: 'HES用量/ml', minWidth: 110 },
{ prop: 'bloodType', label: '血型', minWidth: 80 },
{ prop: 'infectiousFourTestLabel', label: '传染四项检测(检测卡)', minWidth: 150 },
{ prop: 'infectiousFourExternal', label: '传染四项检测(外检)', minWidth: 150 },
{ prop: 'preEnrichNucleatedCount', label: '富集前有核细胞数/109/L', minWidth: 170 },
{ prop: 'enrichedBloodWeightG', label: '富集后血量/g', minWidth: 120 },
{ prop: 'postEnrichNucleatedCount', label: '富集后有核细胞数/109/L', minWidth: 170 },
{ prop: 'cryopreservationVolumeMl', label: '冻存液用量/ml', minWidth: 120 },
{ prop: 'cd34Count1e4', label: 'CD34+细胞计数/*10E4', minWidth: 160 },
{ prop: 'operatorName', label: '操作人', minWidth: 100 },
{ prop: 'remarkProcess', label: '备注', minWidth: 120 },
{ prop: 'createTime', label: '创建时间', minWidth: 200 }
]
const DONATION_HSC_COLUMNS: LabColumn[] = [
{ prop: 'cellCode', label: '细胞编码', minWidth: 140 },
{ prop: 'sampleStatus', label: '样本状态', minWidth: 140 },
{ prop: 'motherName', label: '准妈妈姓名', minWidth: 110 },
{ prop: 'labMaterialCode', label: '实验室物料编码', minWidth: 130 },
{ prop: 'inboundCode', label: '入库编码', minWidth: 140 },
{ prop: 'storageStatus', label: '储存状态', minWidth: 100 },
{ prop: 'discardReason', label: '废弃原因', minWidth: 120 },
{ prop: 'receptionTime', label: '接收时间', minWidth: 200 },
{ prop: 'receiveTemperature', label: '样品温度到达/℃', minWidth: 130 },
{ prop: 'receiveCheckText', label: '收样检查', minWidth: 120 },
{ prop: 'handlerName', label: '接收登记人', minWidth: 110 },
{ prop: 'remarkReception', label: '备注', minWidth: 120 },
{ prop: 'originalBloodVolumeMl', label: '原血体积/mL', minWidth: 120 },
{ prop: 'nucleatedCellCount1e8', label: '有核细胞数/108', minWidth: 130 },
{ prop: 'preOpNucleatedCount', label: '操作前有核细胞数/109/L', minWidth: 170 },
{ prop: 'infectiousFourTestLabel', label: '传染四项检测(检测卡)', minWidth: 150 },
{ prop: 'motherHbsag', label: '乙型肝炎病毒表面抗原(HBsAg)', minWidth: 180 },
{ prop: 'motherAntiHcv', label: '丙型肝炎病毒抗体(抗HCV)', minWidth: 170 },
{ prop: 'motherAntiTp', label: '梅毒螺旋体特异性抗体(抗TP)', minWidth: 180 },
{ prop: 'motherAntiHiv', label: '人类免疫缺陷病毒抗体(抗HIV-1/2)', minWidth: 200 },
{ prop: 'motherCmvIgm', label: '巨细胞病毒IgM抗体(CMV-IgM)', minWidth: 180 },
{ prop: 'operatorName', label: '操作人', minWidth: 100 },
{ prop: 'remarkProcess', label: '备注', minWidth: 120 },
{ prop: 'createTime', label: '创建时间', minWidth: 200 }
]
const MSC_COLUMNS: LabColumn[] = [
{ prop: 'labFlowCode', label: '实验室流转编码', minWidth: 140 },
{ prop: 'sampleStatus', label: '样本状态', minWidth: 140 },
{ prop: 'motherName', label: '母亲姓名', minWidth: 110 },
{ prop: 'cordCollectTime', label: '脐带采集时间', minWidth: 200 },
{ prop: 'transportTempC', label: '运输温度/℃', minWidth: 110 },
{ prop: 'cordReceiveTime', label: '脐带接收时间', minWidth: 200 },
{ prop: 'handlerName', label: '接收登记人', minWidth: 110 },
{ prop: 'inoculationAmount', label: '接种量', minWidth: 100 },
{ prop: 'storageStatus', label: '储存状态', minWidth: 100 },
{ prop: 'cryopreservationTime', label: '冻存时间', minWidth: 200 },
{ prop: 'storageTotalTubes', label: '储存总量(管)', minWidth: 120 },
{ prop: 'availableCellCount1e7', label: '可提供细胞数量/*10E7', minWidth: 160 },
{ prop: 'endotoxinTest', label: '内毒素检测', minWidth: 100 },
{ prop: 'bacteriaTest', label: '细菌检测', minWidth: 100 },
{ prop: 'fungusTest', label: '真菌检测', minWidth: 100 },
{ prop: 'mycoplasmaTest', label: '支原体检测', minWidth: 100 },
{ prop: 'operatorName', label: '操作人', minWidth: 100 },
{ prop: 'motherHbsag', label: '乙型肝炎病毒表面抗原(HBsAg)', minWidth: 180 },
{ prop: 'motherHbvDna', label: '乙型肝炎病毒核酸(HBV DNA)', minWidth: 180 },
{ prop: 'motherAntiHcv', label: '丙型肝炎病毒抗体(抗HCV)', minWidth: 170 },
{ prop: 'motherHcvRna', label: '丙型肝炎病毒核酸(HCV RNA)', minWidth: 180 },
{ prop: 'motherAntiTp', label: '梅毒螺旋体特异性抗体(抗TP)', minWidth: 180 },
{ prop: 'motherCmvIgm', label: '巨细胞病毒IgM抗体(CMV IgM)', minWidth: 180 },
{ prop: 'motherAntiHiv', label: '人类免疫缺陷病毒抗体(抗HIV-1/2)', minWidth: 200 },
{ prop: 'motherHiv1Rna', label: '人类免疫缺陷病毒核酸(1型)(HIV-1RNA)', minWidth: 210 },
{ prop: 'storageDateP2', label: '储存日期(P2冻存日期)', minWidth: 160 },
{ prop: 'remark', label: '备注', minWidth: 120 },
{ prop: 'createTime', label: '创建时间', minWidth: 200 }
]
export const LAB_PROCESS_COLUMNS: Record<LabSampleProcessTabKey, LabColumn[]> = {
cell_hsc: CELL_HSC_COLUMNS,
donation_hsc: DONATION_HSC_COLUMNS,
cell_msc: MSC_COLUMNS,
donation_msc: MSC_COLUMNS
}
export const SUPPLEMENT_FIELD_LABELS: Record<string, string> = Object.fromEntries(
[...CELL_HSC_COLUMNS, ...DONATION_HSC_COLUMNS, ...MSC_COLUMNS].map((c) => [c.prop, c.label])
)
@@ -0,0 +1,16 @@
import { describe, it } from 'node:test'
import assert from 'node:assert/strict'
import { hasOaCommentDraft } from './oa-comment-draft.ts'
describe('hasOaCommentDraft', () => {
it('treats blank content without mentions/files as empty', () => {
assert.equal(hasOaCommentDraft({}), false)
assert.equal(hasOaCommentDraft({ content: ' ', mentionCount: 0, attachmentCount: 0 }), false)
})
it('detects text, mentions and attachments', () => {
assert.equal(hasOaCommentDraft({ content: '@test' }), true)
assert.equal(hasOaCommentDraft({ mentionCount: 1 }), true)
assert.equal(hasOaCommentDraft({ attachmentCount: 2 }), true)
})
})
+12
View File
@@ -0,0 +1,12 @@
/** 评论区是否有未发送草稿(文字 / @ / 附件) */
export function hasOaCommentDraft(input: {
content?: string | null
mentionCount?: number
attachmentCount?: number
}): boolean {
return !!(
String(input.content || '').trim() ||
(input.mentionCount || 0) > 0 ||
(input.attachmentCount || 0) > 0
)
}
@@ -14,7 +14,7 @@ import type { ProductionWorkOrderTabKey } from '@/utils/production-work-order-ta
import { resolveTabKeyFromWorkOrder } from '@/utils/production-work-order-tabs'
import { formatMoneyDisplay } from '@/utils/money-format'
export type CardMetaFieldKind = 'text' | 'tag'
export type CardMetaFieldKind = 'text' | 'tag' | 'sample-status'
export type CardMetaField = {
label: string
@@ -84,6 +84,11 @@ function buildInboundMetaFields(tabKey: ProductionWorkOrderTabKey): CardMetaFiel
return [
{ label: '实验室入库编码', getValue: (row) => row.labStorageCode || '—' },
{ label: '样本类型', getValue: (row) => row.sampleTypeName || '—' },
{
label: '样本状态',
kind: 'sample-status',
getValue: (row) => String(row.sampleStatus || '')
},
{ label: '接收经手人', getValue: (row) => row.handlerName || '—' },
{ label: '接收时间', getValue: (row) => formatDisplayOrDash(row.receptionTime) },
{
@@ -63,6 +63,19 @@ describe('flattenProtocolAuditRows', () => {
assert.equal(rows[0].sampleCode, 'ZKZX34000199')
})
it('passes sample status and sample void reason from sample items', () => {
const rows = flattenProtocolAuditRows([
{
id: 'p-status',
voidDesc: '协议作废',
sampleItems: [{ sampleCode: 'S-VOID', sampleStatus: 'yzf', voidDesc: '样本破损' }]
}
])
assert.equal(rows[0].voidDesc, '协议作废')
assert.equal(rows[0].sampleStatus, 'yzf')
assert.equal(rows[0].sampleVoidDesc, '样本破损')
})
it('zero samples → one placeholder row, not co-stored', () => {
const rows = flattenProtocolAuditRows([{ id: 'p2', protocolNo: 'ZKZX2', sampleItems: [] }])
assert.equal(rows.length, 1)
@@ -34,6 +34,9 @@ export type ProtocolAuditFlatRow = {
regionManagerUserName: string
sampleTypeName: string
sampleCode: string
sampleStatus: string
/** 样本作废原因;协议作废原因仍用 voidDesc */
sampleVoidDesc: string
labStorageCode: string
transportType: string
transportLabel: string
@@ -120,6 +123,8 @@ export function flattenProtocolAuditRows(
regionManagerUserName: str(protocol.regionManagerUserName),
sampleTypeName: str(rec.sampleTypeName),
sampleCode: str(rec.sampleCode),
sampleStatus: str(rec.sampleStatus),
sampleVoidDesc: str(rec.voidDesc),
labStorageCode: str(rec.labStorageCode),
transportType,
transportLabel: '',
+15 -2
View File
@@ -16,7 +16,7 @@ import {
type QcWorkOrderProtocolGroupModel
} from '@/utils/qc-work-order-groups'
export type CardMetaFieldKind = 'text' | 'tag'
export type CardMetaFieldKind = 'text' | 'tag' | 'sample-status'
export type CardMetaField = {
label: string
@@ -127,18 +127,29 @@ const inboundGroupedFields: CardMetaField[] = [
{ label: '母亲姓名', getValue: (row) => row.motherName || '—', visible: isInboundUserInfoRow },
{ label: '新生儿姓名', getValue: (row) => row.newbornName || '—', visible: isInboundUserInfoRow },
inboundProtocolStatusField,
{ label: '质检对象', getValue: formatQcTarget, colSpan: 2 },
{ label: '质检对象', getValue: formatQcTarget },
{
label: '关联生产工单',
getValue: (row) => row.productionWorkOrderNo || '—',
visible: (row) => (row.triggerSource || 'reception') === 'production'
},
{ label: '样本编码', getValue: (row) => row.sampleCode || '—', visible: isInboundUserInfoRow },
{
label: '样本状态',
kind: 'sample-status',
getValue: (row) => String(row.sampleStatus || ''),
visible: isInboundUserInfoRow
},
{
label: '样本类型',
getValue: (row) => row.sampleTypeName || '—',
visible: isInboundUserInfoRow
},
{
label: '母血采集时间',
getValue: (row) => formatDisplayOrDash(row.maternalBloodCollectTime),
visible: isInboundUserInfoRow
},
...commonTailFields
]
@@ -197,6 +208,7 @@ function buildCellStorageGroupContext(row: QcWorkOrder): string[] {
if (row.newbornName) parts.push(`新生儿 ${row.newbornName}`)
if (row.sampleTypeName) parts.push(row.sampleTypeName)
if (row.receptionTime) parts.push(`接收 ${row.receptionTime}`)
parts.push(`母血采集 ${formatDisplayOrDash(row.maternalBloodCollectTime)}`)
if (row.handlerName) parts.push(row.handlerName)
return parts
}
@@ -207,6 +219,7 @@ function buildDonationGroupContext(row: QcWorkOrder): string[] {
if (row.newbornName) parts.push(`新生儿 ${row.newbornName}`)
if (row.sampleTypeName) parts.push(row.sampleTypeName)
if (row.receptionTime) parts.push(`接收 ${row.receptionTime}`)
parts.push(`母血采集 ${formatDisplayOrDash(row.maternalBloodCollectTime)}`)
if (row.handlerName) parts.push(row.handlerName)
return parts
}
@@ -21,6 +21,8 @@ export type SampleFreightFlatRow = {
motherName?: string
newbornName?: string
sampleCode?: string
sampleStatus?: string
voidDesc?: string
sampleTypeName?: string
sampleId?: string
protocolId?: string
@@ -53,6 +55,8 @@ export function flattenSampleFreights(list: SampleFreight[]): SampleFreightFlatR
motherName: it?.motherName,
newbornName: it?.newbornName,
sampleCode: it?.sampleCode,
sampleStatus: it?.sampleStatus,
voidDesc: it?.voidDesc,
sampleTypeName: it?.sampleTypeName,
sampleId: it?.sampleId,
protocolId: it?.protocolId,
+43
View File
@@ -0,0 +1,43 @@
import { describe, it } from 'node:test'
import assert from 'node:assert/strict'
import { isSampleAlreadyVoided, resolveSampleVoidTarget } from './sample-void'
describe('resolveSampleVoidTarget', () => {
it('uses protocol sample id, code and protocol id', () => {
const target = resolveSampleVoidTarget({
receptionSource: 'cell_storage',
protocolSampleId: 'ps-1',
sampleCode: 'S1',
labStorageCode: 'B0000108',
collectionProtocolId: 'p-1'
})
assert.deepEqual(target, {
receptionSource: 'cell_storage',
sampleId: 'ps-1',
sampleCode: 'S1',
labStorageCode: 'B0000108',
protocolId: 'p-1'
})
})
it('falls back to tab source when row source is empty', () => {
const target = resolveSampleVoidTarget({
sampleCode: 'S2',
fallbackSource: 'research_donation'
})
assert.equal(target?.receptionSource, 'research_donation')
assert.equal(target?.sampleCode, 'S2')
})
it('returns null without a sample identifier', () => {
assert.equal(resolveSampleVoidTarget({ receptionSource: 'cell_storage' }), null)
})
})
describe('isSampleAlreadyVoided', () => {
it('matches yzf only', () => {
assert.equal(isSampleAlreadyVoided('yzf'), true)
assert.equal(isSampleAlreadyVoided(' yzf '), true)
assert.equal(isSampleAlreadyVoided('ycj'), false)
})
})
+32
View File
@@ -0,0 +1,32 @@
import type { SampleVoidTarget } from '../api/business-sample'
export function isSampleAlreadyVoided(status?: string | null): boolean {
return String(status || '').trim() === 'yzf'
}
export function resolveSampleVoidTarget(input: {
receptionSource?: string | null
protocolSampleId?: string | null
sampleCode?: string | null
labStorageCode?: string | null
collectionProtocolId?: string | null
fallbackSource?: string | null
}): SampleVoidTarget | null {
let source = String(input.receptionSource || '').trim()
if (source !== 'cell_storage' && source !== 'research_donation') {
source = String(input.fallbackSource || '').trim()
}
if (source !== 'cell_storage' && source !== 'research_donation') return null
const sampleId = String(input.protocolSampleId || '').trim()
const sampleCode = String(input.sampleCode || '').trim()
const labStorageCode = String(input.labStorageCode || '').trim()
const protocolId = String(input.collectionProtocolId || '').trim()
if (!sampleId && !sampleCode) return null
return {
receptionSource: source,
sampleId: sampleId || undefined,
sampleCode: sampleCode || undefined,
labStorageCode: labStorageCode || undefined,
protocolId: protocolId || undefined
}
}
@@ -82,6 +82,11 @@
align="center"
show-overflow-tooltip
/>
<el-table-column label="样本状态" min-width="140" align="center">
<template #default="{ row }">
<SampleStatusTag :status="row.sampleStatus" :void-desc="row.voidDesc" />
</template>
</el-table-column>
<el-table-column label="市场专员" min-width="110" align="center">
<template #default="{ row }">{{ row.salesUserName || '—' }}</template>
</el-table-column>
@@ -265,6 +270,7 @@
<script setup lang="ts">
import { Search, RefreshLeft, Document, Close } from '@element-plus/icons-vue'
import ProtocolViewDialog from '../protocol/ProtocolViewDialog.vue'
import SampleStatusTag from '@/components/business/sample-status-tag/index.vue'
import ProtocolAttachmentReadonly from '../protocol/ProtocolAttachmentReadonly.vue'
import { downloadAttachmentFile } from '@/utils/download-attachment'
import {
@@ -90,6 +90,11 @@
align="center"
show-overflow-tooltip
/>
<el-table-column label="样本状态" min-width="140" align="center">
<template #default="{ row }">
<SampleStatusTag :status="row.sampleStatus" :void-desc="row.voidDesc" />
</template>
</el-table-column>
<el-table-column label="签署日期" min-width="110" align="center">
<template #default="{ row }">{{ row.signDate || '—' }}</template>
</el-table-column>
@@ -295,6 +300,7 @@
import ProtocolViewDialog from '../protocol/ProtocolViewDialog.vue'
import ProtocolAttachmentReadonly from '../protocol/ProtocolAttachmentReadonly.vue'
import SamplePaymentDetailDialog from '@/components/business/sample-payment-detail-dialog/index.vue'
import SampleStatusTag from '@/components/business/sample-status-tag/index.vue'
import { downloadAttachmentFile } from '@/utils/download-attachment'
import { fetchSamplePaymentList, fetchSamplePaymentDetail } from '@/api/protocol-sample-payment'
import { type CollectionProtocolRow } from '@/api/collection-protocol'
@@ -175,6 +175,11 @@
<span class="mono">{{ row.labStorageCode || '—' }}</span>
</template>
</el-table-column>
<el-table-column label="样本状态" min-width="140" align="center" header-align="center">
<template #default="{ row }">
<SampleStatusTag :status="row.sampleStatus" :void-desc="row.sampleVoidDesc" />
</template>
</el-table-column>
<el-table-column label="协议状态" min-width="100" align="center" header-align="center">
<template #default="{ row }">
<el-tag :type="donationStatusTagType(row.donationStatus)" size="small">
@@ -415,6 +420,7 @@
<script setup lang="ts">
import ProjectSelect from '@/components/business/ProjectSelect.vue'
import SampleStatusTag from '@/components/business/sample-status-tag/index.vue'
const projectFilter = ref('')
const teamFilter = ref('')
import { formatDisplayOrDash } from '@/utils/datetime-display'
Loaded 100 of 116 files, more files were not shown because too many files have changed in this diff. Show more