Compare commits

...
Author SHA1 Message Date
cykj 964384108a fix(qc): 我的质检任务关键词与工单列表口径对齐 (#168)
fix(qc): 我的质检任务关键词与工单列表口径对齐

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

No files matched your search

+1 -1
View File
@@ -86,7 +86,7 @@ SECRET_KEY=
# WX_MP_TPL_PROGRESS_FIELD_APPROVER=thing6 # WX_MP_TPL_PROGRESS_FIELD_APPROVER=thing6
# WX_MP_TPL_PROGRESS_FIELD_RESULT=const4 # WX_MP_TPL_PROGRESS_FIELD_RESULT=const4
# WX_MP_TPL_PROGRESS_FIELD_TIME=time11 # WX_MP_TPL_PROGRESS_FIELD_TIME=time11
# 基础实验交付日前一天提醒(出库提醒模板) # 临床科研交付日前一天提醒(出库提醒模板)
# WX_MP_TEMPLATE_BASIC_EXPERIMENT_DELIVERY=oQNU3t0Q5kwc4KPJ8Z6yPA-k6qlsH9pikSCIb4eAwgM # WX_MP_TEMPLATE_BASIC_EXPERIMENT_DELIVERY=oQNU3t0Q5kwc4KPJ8Z6yPA-k6qlsH9pikSCIb4eAwgM
# WX_MP_TPL_BE_DELIVERY_FIELD_CUSTOMER=thing6 # WX_MP_TPL_BE_DELIVERY_FIELD_CUSTOMER=thing6
# WX_MP_TPL_BE_DELIVERY_FIELD_PRODUCT=thing10 # WX_MP_TPL_BE_DELIVERY_FIELD_PRODUCT=thing10
+54 -36
View File
@@ -7,7 +7,7 @@ from app.core.response import success_response
router = APIRouter(prefix="/web/menu", tags=["菜单管理"]) router = APIRouter(prefix="/web/menu", tags=["菜单管理"])
# 与 web-admin/src/router/modules/sqxp.ts 一致:6 个一级菜单分组 # 与 web-admin/src/router/modules/sqxp.ts 一致:6 个一级菜单分组
# 市场二级顺序:存储服务、科研捐赠、市场基础信息、中试服务、基础实验 # 市场二级顺序:存储服务、科研捐赠、市场基础信息、临床科研、器械销售
STATIC_MENU_TREE = [ STATIC_MENU_TREE = [
{ {
"id": "TOP00000000000000000000000000006", "id": "TOP00000000000000000000000000006",
@@ -199,7 +199,7 @@ STATIC_MENU_TREE = [
], ],
}, },
# 市场基础信息(前段:存储/捐赠相关;后段:中试/基础实验相关) # 市场基础信息(前段:存储/捐赠相关;后段:中试/临床科研相关)
{ {
"id": "MKT00000000000000000000000000001", "id": "MKT00000000000000000000000000001",
"name": "MarketInfo", "name": "MarketInfo",
@@ -298,44 +298,14 @@ STATIC_MENU_TREE = [
], ],
}, },
# 中试服务 # 临床科研
{
"id": "PIL00000000000000000000000000001",
"name": "PilotService",
"path": "pilot-service",
"component": "",
"meta": {
"title": "中试服务",
"icon": "ri:flask-line",
"keepAlive": False,
"roles": ["admin"],
},
"children": [
{
"id": "80000000000000000000000000000010",
"name": "PilotApplication",
"path": "pilot-application",
"component": "/pilot-service/pilot-application/index",
"meta": {"title": "中试服务申请单", "keepAlive": True, "menuCode": "pilot-service:pilot-application:list"},
},
{
"id": "PIL00000000000000000000000000004",
"name": "PilotOutboundRelease",
"path": "outbound-release-review",
"component": "/pilot-service/outbound-release-review/index",
"meta": {"title": "出库放行审核", "keepAlive": True, "menuCode": "pilot-service:outbound-release-review:list"},
},
],
},
# 基础实验
{ {
"id": "BEX00000000000000000000000000001", "id": "BEX00000000000000000000000000001",
"name": "BasicExperiment", "name": "BasicExperiment",
"path": "basic-experiment", "path": "basic-experiment",
"component": "", "component": "",
"meta": { "meta": {
"title": "基础实验", "title": "临床科研",
"icon": "ri:flask-line", "icon": "ri:flask-line",
"keepAlive": False, "keepAlive": False,
"roles": ["admin"], "roles": ["admin"],
@@ -347,7 +317,7 @@ STATIC_MENU_TREE = [
"path": "application", "path": "application",
"component": "/pilot-service/pilot-application/index", "component": "/pilot-service/pilot-application/index",
"meta": { "meta": {
"title": "基础实验申请单", "title": "临床科研申请单",
"keepAlive": True, "keepAlive": True,
"menuCode": "basic-experiment:application:list", "menuCode": "basic-experiment:application:list",
}, },
@@ -375,7 +345,55 @@ STATIC_MENU_TREE = [
}, },
}, },
], ],
} },
# 器械销售(市场侧栏末位)
{
"id": "DEV00000000000000000000000000001",
"name": "DeviceSales",
"path": "device-sales",
"component": "",
"meta": {
"title": "器械销售",
"icon": "ri:shopping-bag-3-line",
"keepAlive": False,
"roles": ["admin"],
},
"children": [
{
"id": "DEV00000000000000000000000000002",
"name": "DeviceSalesClassIii",
"path": "class-iii",
"component": "/device-sales/under-construction/index",
"meta": {
"title": "三类医疗器械",
"keepAlive": False,
"menuCode": "device-sales:class-iii:list",
},
},
{
"id": "DEV00000000000000000000000000003",
"name": "DeviceSalesClassIi",
"path": "class-ii",
"component": "/device-sales/under-construction/index",
"meta": {
"title": "二类医疗器械",
"keepAlive": False,
"menuCode": "device-sales:class-ii:list",
},
},
{
"id": "DEV00000000000000000000000000004",
"name": "DeviceSalesCosmetics",
"path": "cosmetics",
"component": "/device-sales/under-construction/index",
"meta": {
"title": "化妆品产品",
"keepAlive": False,
"menuCode": "device-sales:cosmetics:list",
},
},
],
},
], ],
}, },
+13 -1
View File
@@ -53,6 +53,7 @@ class ApplicationCreateBody(BaseModel):
customer_name: Optional[str] = Field(None, alias="customerName") customer_name: Optional[str] = Field(None, alias="customerName")
customer_contact: Optional[str] = Field(None, alias="customerContact") customer_contact: Optional[str] = Field(None, alias="customerContact")
customer_phone: Optional[str] = Field(None, alias="customerPhone") customer_phone: Optional[str] = Field(None, alias="customerPhone")
research_category: Optional[str] = Field(None, alias="researchCategory")
class ApplicationUpdateBody(BaseModel): class ApplicationUpdateBody(BaseModel):
@@ -65,6 +66,7 @@ class ApplicationUpdateBody(BaseModel):
customer_name: Optional[str] = Field(None, alias="customerName") customer_name: Optional[str] = Field(None, alias="customerName")
customer_contact: Optional[str] = Field(None, alias="customerContact") customer_contact: Optional[str] = Field(None, alias="customerContact")
customer_phone: Optional[str] = Field(None, alias="customerPhone") customer_phone: Optional[str] = Field(None, alias="customerPhone")
research_category: Optional[str] = Field(None, alias="researchCategory")
class PatientSaveBody(BaseModel): class PatientSaveBody(BaseModel):
@@ -206,6 +208,7 @@ class ApplicationSaveBody(BaseModel):
customer_name: Optional[str] = Field(None, alias="customerName") customer_name: Optional[str] = Field(None, alias="customerName")
customer_contact: Optional[str] = Field(None, alias="customerContact") customer_contact: Optional[str] = Field(None, alias="customerContact")
customer_phone: Optional[str] = Field(None, alias="customerPhone") customer_phone: Optional[str] = Field(None, alias="customerPhone")
research_category: Optional[str] = Field(None, alias="researchCategory")
remark: Optional[str] = None remark: Optional[str] = None
consent_form_urls: Optional[str] = Field(None, alias="consentFormUrls") consent_form_urls: Optional[str] = Field(None, alias="consentFormUrls")
consent_attachments: Optional[list] = Field(None, alias="consentAttachments") consent_attachments: Optional[list] = Field(None, alias="consentAttachments")
@@ -287,6 +290,7 @@ async def api_create_application(
"customerName": body.customer_name, "customerName": body.customer_name,
"customerContact": body.customer_contact, "customerContact": body.customer_contact,
"customerPhone": body.customer_phone, "customerPhone": body.customer_phone,
"researchCategory": body.research_category,
} }
result = pilot_application.create_application( result = pilot_application.create_application(
db, db,
@@ -322,6 +326,8 @@ async def api_update_application(
data["customerContact"] = body.customer_contact data["customerContact"] = body.customer_contact
if body.customer_phone is not None: if body.customer_phone is not None:
data["customerPhone"] = body.customer_phone data["customerPhone"] = body.customer_phone
if body.research_category is not None:
data["researchCategory"] = body.research_category
result = pilot_application.update_application( result = pilot_application.update_application(
db, app_id=body.id, data=data, tenant_no=tenant_no db, app_id=body.id, data=data, tenant_no=tenant_no
) )
@@ -364,6 +370,8 @@ async def api_save_application(
app_data["customerContact"] = body.customer_contact app_data["customerContact"] = body.customer_contact
if body.customer_phone is not None: if body.customer_phone is not None:
app_data["customerPhone"] = body.customer_phone app_data["customerPhone"] = body.customer_phone
if body.research_category is not None:
app_data["researchCategory"] = body.research_category
if body.consent_attachments is not None: if body.consent_attachments is not None:
app_data["consentAttachments"] = body.consent_attachments app_data["consentAttachments"] = body.consent_attachments
elif body.consent_form_urls is not None: elif body.consent_form_urls is not None:
@@ -380,7 +388,11 @@ async def api_save_application(
): ):
return error_response(400, "请选择渠道服务订单") return error_response(400, "请选择渠道服务订单")
if not is_edit and biz_type == "clinical_application" and not app_data["channelId"]: if (
not is_edit
and biz_type in ("clinical_application", "basic_experiment")
and not app_data["channelId"]
):
return error_response(400, "请选择渠道") return error_response(400, "请选择渠道")
if is_edit: if is_edit:
+52
View File
@@ -49,7 +49,9 @@ from app.schemas.production_work_order import (
ProductionWorkOrderCreate, ProductionWorkOrderCreate,
ProductionWorkOrderConfigureBody, ProductionWorkOrderConfigureBody,
ProductionWorkOrderUpdate, ProductionWorkOrderUpdate,
ProductionDeliveryCellOutboundBody,
) )
from app.crud import outbound_handover as outbound_handover_svc
from app.schemas.production_task_set import ( from app.schemas.production_task_set import (
ProductionTaskSetCreateBody, ProductionTaskSetCreateBody,
ProductionTaskSetFromWorkOrderBody, ProductionTaskSetFromWorkOrderBody,
@@ -2025,6 +2027,56 @@ async def list_production_work_order_cell_product_options(
return error_response(400, str(e)) return error_response(400, str(e))
@router.get("/production-work-orders/{wo_id}/delivery-cell-outbound")
async def get_production_delivery_cell_outbound_api(
wo_id: str,
user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
"""临床科研出库工单 — 获取已确认的交付出库细胞。"""
try:
tenant_no = _get_tenant_no(db, user)
data = outbound_handover_svc.get_production_delivery_cell_outbound(
db, wo_id, tenant_no
)
return success_response(data)
except HTTPException as e:
return error_response(e.status_code, e.detail)
except ValueError as e:
return error_response(400, str(e))
@router.put("/production-work-orders/{wo_id}/delivery-cell-outbound")
async def save_production_delivery_cell_outbound_api(
wo_id: str,
body: ProductionDeliveryCellOutboundBody,
user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
"""临床科研出库工单 — 确认出库细胞(写台账并联动库存)。"""
try:
tenant_no = _get_tenant_no(db, user)
data = outbound_handover_svc.save_production_delivery_cell_outbound(
db,
wo_id,
cells=body.cells or [],
tenant_no=tenant_no,
user_id=user.get("user_id") or "",
create_dept_id=user.get("dept_id") or "",
)
db.commit()
return success_response(data, message="出库细胞已确认")
except HTTPException as e:
db.rollback()
return error_response(e.status_code, e.detail)
except ValueError as e:
db.rollback()
return error_response(400, str(e))
except Exception as e:
db.rollback()
return error_response(400, str(e))
@router.get("/production-work-orders/{wo_id}/qc-info") @router.get("/production-work-orders/{wo_id}/qc-info")
async def get_production_work_order_qc_info_api( async def get_production_work_order_qc_info_api(
wo_id: str, wo_id: str,
+61
View File
@@ -29,6 +29,7 @@ from app.crud import qc_lab_test_item as lab_svc
from app.crud import qc_inspection_item_template as iit_svc from app.crud import qc_inspection_item_template as iit_svc
from app.crud import qc_item_param as param_svc from app.crud import qc_item_param as param_svc
from app.crud import qc_task_result as result_svc from app.crud import qc_task_result as result_svc
from app.crud import qc_task_result_change_log as result_change_log_svc
from app.crud import qc_task as task_svc from app.crud import qc_task as task_svc
from app.crud import qc_third_party_company as tpc_svc from app.crud import qc_third_party_company as tpc_svc
from app.crud import qc_third_party_item as tpi_svc from app.crud import qc_third_party_item as tpi_svc
@@ -448,6 +449,7 @@ class TaskCompleteWithResultBody(BaseModel):
third_party_attachments: Optional[str] = Field(None, alias="thirdPartyAttachments") third_party_attachments: Optional[str] = Field(None, alias="thirdPartyAttachments")
material_usages: Optional[List[Dict[str, Any]]] = Field(None, alias="materialUsages") material_usages: Optional[List[Dict[str, Any]]] = Field(None, alias="materialUsages")
task_status: Optional[str] = Field(None, alias="taskStatus") task_status: Optional[str] = Field(None, alias="taskStatus")
operate_batch_id: Optional[str] = Field(None, alias="operateBatchId")
@router.get("/qc-lab-test-items") @router.get("/qc-lab-test-items")
@@ -1176,6 +1178,9 @@ async def list_my_qc_tasks(
qcBizType: Optional[str] = None, qcBizType: Optional[str] = None,
receptionSource: Optional[str] = Query(None, alias="receptionSource"), receptionSource: Optional[str] = Query(None, alias="receptionSource"),
bizType: Optional[str] = Query(None, alias="bizType"), bizType: Optional[str] = Query(None, alias="bizType"),
protocolStatus: Optional[str] = Query(
None, alias="protocolStatus", description="协议/捐赠状态,多个用英文逗号分隔"
),
db: Session = Depends(get_db), db: Session = Depends(get_db),
user: dict = Depends(require_menu_code("biz:myQcTask:list")), user: dict = Depends(require_menu_code("biz:myQcTask:list")),
): ):
@@ -1192,6 +1197,7 @@ async def list_my_qc_tasks(
qc_biz_type=qcBizType, qc_biz_type=qcBizType,
reception_source=receptionSource, reception_source=receptionSource,
biz_type=bizType, biz_type=bizType,
protocol_status=protocolStatus,
tenant_no=tenant_no, tenant_no=tenant_no,
) )
return success_response(_page_payload(items, total, page, pageSize)) return success_response(_page_payload(items, total, page, pageSize))
@@ -1234,6 +1240,29 @@ async def list_qc_tasks(
return error_response(400, str(e)) return error_response(400, str(e))
@router.get("/qc-tasks/result-change-logs")
async def list_qc_task_result_change_logs_batch(
taskIds: str = Query("", description="逗号分隔的任务ID"),
db: Session = Depends(get_db),
user: dict = Depends(require_any_menu_code(*QC_TASK_READONLY_MENU_CODES)),
):
"""批量查询检测结果修改记录。须注册在 /qc-tasks/{task_id} 之前,避免被当成任务 ID。"""
try:
tenant_no = _get_tenant_no(db, user)
ids = [x.strip() for x in (taskIds or "").split(",") if x.strip()]
if not ids:
return success_response([])
return success_response(
result_change_log_svc.list_task_result_change_logs_by_task_ids(
db, task_ids=ids, tenant_no=tenant_no
)
)
except PermissionError as e:
return error_response(403, str(e))
except Exception as e:
return error_response(400, str(e))
@router.get("/qc-tasks/{task_id}") @router.get("/qc-tasks/{task_id}")
async def get_qc_task_detail( async def get_qc_task_detail(
task_id: str, task_id: str,
@@ -1349,6 +1378,26 @@ async def get_task_material_usages(
return error_response(400, str(e)) return error_response(400, str(e))
@router.get("/qc-tasks/{task_id}/result-change-logs")
async def list_qc_task_result_change_logs(
task_id: str,
db: Session = Depends(get_db),
user: dict = Depends(require_any_menu_code(*QC_TASK_READONLY_MENU_CODES)),
):
try:
tenant_no = _get_tenant_no(db, user)
# 无任务或无留痕均返回空列表,避免前端把“暂无记录”当成错误
return success_response(
result_change_log_svc.list_task_result_change_logs(
db, task_id=task_id, tenant_no=tenant_no
)
)
except PermissionError as e:
return error_response(403, str(e))
except Exception as e:
return error_response(400, str(e))
@router.post("/qc-tasks/{task_id}/complete-with-result") @router.post("/qc-tasks/{task_id}/complete-with-result")
async def complete_task_with_result( async def complete_task_with_result(
task_id: str, task_id: str,
@@ -1364,6 +1413,7 @@ async def complete_task_with_result(
if not t: if not t:
return error_response(404, "任务不存在") return error_response(404, "任务不存在")
was_done = (t.task_status or "").strip() == "ywc" was_done = (t.task_status or "").strip() == "ywc"
before = result_change_log_svc.snapshot_task_result_state(db, t, tenant_no)
if body.results: if body.results:
result_svc.save_results_for_task( result_svc.save_results_for_task(
db, task_id, body.results, tenant_no, user_id, commit=False, db, task_id, body.results, tenant_no, user_id, commit=False,
@@ -1384,6 +1434,17 @@ async def complete_task_with_result(
task_status=body.task_status, task_status=body.task_status,
commit=False, commit=False,
) )
after = result_change_log_svc.snapshot_task_result_state(db, obj, tenant_no)
result_change_log_svc.append_task_result_change_log(
db,
task=obj,
tenant_no=tenant_no,
user_id=user_id,
operator_user_name=str(user.get("nickName") or user.get("nick_name") or ""),
before=before,
after=after,
operate_batch_id=body.operate_batch_id,
)
db.commit() db.commit()
db.refresh(obj) db.refresh(obj)
if (obj.task_status or "").strip() == "ywc": if (obj.task_status or "").strip() == "ywc":
View File
Whitespace-only changes.
@@ -0,0 +1,27 @@
"""临床科研申请单 · 业务子类型(research_category)"""
from typing import Optional
RESEARCH_CATEGORY_LABELS = {
"bio_tech_clinical": "生物新技术临床科研",
"joint_topic_declare": "临床课题联合申报",
"bio_pharma_rd": "生物制药研发",
}
RESEARCH_CATEGORY_CODES = tuple(RESEARCH_CATEGORY_LABELS.keys())
def research_category_label(code: Optional[str]) -> str:
if not code:
return ""
return RESEARCH_CATEGORY_LABELS.get(code, code)
def validate_research_category(code: Optional[str], required: bool = False) -> str:
value = (code or "").strip()
if not value:
if required:
raise ValueError("请选择业务类型")
return ""
if value not in RESEARCH_CATEGORY_LABELS:
raise ValueError("业务类型无效")
return value
+3 -3
View File
@@ -136,14 +136,14 @@ class Settings(BaseSettings):
WX_TEMPLATE_DELIVERY_WARNING: str = "" # 配送时效预警模板ID WX_TEMPLATE_DELIVERY_WARNING: str = "" # 配送时效预警模板ID
# 微信服务号(OA 审批/抄送通知) # 微信服务号(OA 审批/抄送通知)
# 总开关:false 时不发送审批/抄送/申请人进度/评论@提到/基础实验交付提醒/样本采集通知模板消息 # 总开关:false 时不发送审批/抄送/申请人进度/评论@提到/临床科研交付提醒/样本采集通知模板消息
WX_MP_NOTIFY_ENABLED: bool = False WX_MP_NOTIFY_ENABLED: bool = False
WX_MP_APPID: str = "" WX_MP_APPID: str = ""
WX_MP_SECRET: str = "" WX_MP_SECRET: str = ""
WX_MP_TEMPLATE_APPROVAL: str = "" WX_MP_TEMPLATE_APPROVAL: str = ""
WX_MP_TEMPLATE_CC: str = "" WX_MP_TEMPLATE_CC: str = ""
WX_MP_TEMPLATE_APPLICANT_PROGRESS: str = "" WX_MP_TEMPLATE_APPLICANT_PROGRESS: str = ""
# 基础实验交付日前一天提醒(出库提醒模板) # 临床科研交付日前一天提醒(出库提醒模板)
WX_MP_TEMPLATE_BASIC_EXPERIMENT_DELIVERY: str = ( WX_MP_TEMPLATE_BASIC_EXPERIMENT_DELIVERY: str = (
"oQNU3t0Q5kwc4KPJ8Z6yPA-k6qlsH9pikSCIb4eAwgM" "oQNU3t0Q5kwc4KPJ8Z6yPA-k6qlsH9pikSCIb4eAwgM"
) )
@@ -171,7 +171,7 @@ class Settings(BaseSettings):
WX_MP_TPL_PROGRESS_FIELD_APPROVER: str = "thing6" WX_MP_TPL_PROGRESS_FIELD_APPROVER: str = "thing6"
WX_MP_TPL_PROGRESS_FIELD_RESULT: str = "const4" WX_MP_TPL_PROGRESS_FIELD_RESULT: str = "const4"
WX_MP_TPL_PROGRESS_FIELD_TIME: str = "time11" WX_MP_TPL_PROGRESS_FIELD_TIME: str = "time11"
# 基础实验交付提醒:客户名称/产品名称/件数/收货联系人/出库时间 # 临床科研交付提醒:客户名称/产品名称/件数/收货联系人/出库时间
WX_MP_TPL_BE_DELIVERY_FIELD_CUSTOMER: str = "thing6" WX_MP_TPL_BE_DELIVERY_FIELD_CUSTOMER: str = "thing6"
WX_MP_TPL_BE_DELIVERY_FIELD_PRODUCT: str = "thing10" WX_MP_TPL_BE_DELIVERY_FIELD_PRODUCT: str = "thing10"
WX_MP_TPL_BE_DELIVERY_FIELD_QTY: str = "character_string8" WX_MP_TPL_BE_DELIVERY_FIELD_QTY: str = "character_string8"
+2 -2
View File
@@ -23,14 +23,14 @@ def resolve_research_donation_protocol_status_filter(
Returns: Returns:
("in", statuses) — 按所选状态 IN 过滤 ("in", statuses) — 按所选状态 IN 过滤
("none", []) — 显式空选择,无匹配结果 ("all", []) — 显式空选择,不限制协议状态
("default", DEFAULT_QC_DONATION_PROTOCOL_STATUSES) — 未传参,与列表默认一致 ("default", DEFAULT_QC_DONATION_PROTOCOL_STATUSES) — 未传参,与列表默认一致
""" """
if protocol_status is None: if protocol_status is None:
return ("default", list(DEFAULT_QC_DONATION_PROTOCOL_STATUSES)) return ("default", list(DEFAULT_QC_DONATION_PROTOCOL_STATUSES))
statuses = [s.strip() for s in str(protocol_status).split(",") if s.strip()] statuses = [s.strip() for s in str(protocol_status).split(",") if s.strip()]
if not statuses: if not statuses:
return ("none", []) return ("all", [])
return ("in", statuses) return ("in", statuses)
_PROTOCOL_STATUS_LABELS = { _PROTOCOL_STATUS_LABELS = {
+127 -4
View File
@@ -179,23 +179,38 @@ def save_outbound_handover(
handover_person = handover_user_id handover_person = handover_user_id
om = outbound_material or {} om = outbound_material or {}
cells = om.get("cells") or []
qc_materials = om.get("qcMaterials") or om.get("qc_materials") or [] qc_materials = om.get("qcMaterials") or om.get("qc_materials") or []
paper_materials = om.get("paperMaterials") or om.get("paper_materials") or [] paper_materials = om.get("paperMaterials") or om.get("paper_materials") or []
material_remark = om.get("remark") material_remark = om.get("remark")
biz_type = (detail.get("bizType") or "").strip()
if not biz_type:
biz_type = ((detail.get("application") or {}).get("bizType") or "").strip()
# 临床科研:细胞出库由生产工单确认,市场交接只维护物料/交接信息
cells_owned_by_production = biz_type == "basic_experiment"
# 读取保存前台账,用于回滚上次出库交接的库存/状态变更 # 读取保存前台账,用于回滚上次出库交接的库存/状态变更
previous_material = orm_material_svc.get_outbound_material(db, schedule_id, tenant_no) previous_material = orm_material_svc.get_outbound_material(db, schedule_id, tenant_no)
previous_cells = previous_material.get("cells") or []
previous_cell_ids = [ previous_cell_ids = [
(c.get("cellProductId") or c.get("cell_product_id") or "").strip() (c.get("cellProductId") or c.get("cell_product_id") or "").strip()
for c in (previous_material.get("cells") or []) for c in previous_cells
] ]
had_previous_handover = get_handover_by_schedule(db, schedule_id, tenant_no) is not None had_previous_handover = get_handover_by_schedule(db, schedule_id, tenant_no) is not None
if cells_owned_by_production:
cells = previous_cells
revert_cell_ids: List[str] = []
apply_cells: List[Any] = []
else:
cells = om.get("cells") or []
revert_cell_ids = previous_cell_ids if had_previous_handover else []
apply_cells = cells
handover_inv_svc.revert_handover_inventory( handover_inv_svc.revert_handover_inventory(
db, db,
schedule_id, schedule_id,
cell_product_ids=previous_cell_ids if had_previous_handover else [], cell_product_ids=revert_cell_ids,
tenant_no=tenant_no, tenant_no=tenant_no,
user_id=user_id, user_id=user_id,
) )
@@ -216,7 +231,7 @@ def save_outbound_handover(
handover_inv_svc.apply_handover_inventory( handover_inv_svc.apply_handover_inventory(
db, db,
schedule_id, schedule_id,
cells=cells, cells=apply_cells,
qc_materials=qc_materials, qc_materials=qc_materials,
tenant_no=tenant_no, tenant_no=tenant_no,
user_id=user_id, user_id=user_id,
@@ -255,3 +270,111 @@ def save_outbound_handover(
db.flush() db.flush()
return get_outbound_handover(db, schedule_id, tenant_no) return get_outbound_handover(db, schedule_id, tenant_no)
def _assert_basic_experiment_outbound_wo(wo: Any) -> str:
"""校验临床科研出库工单,返回关联交付计划 ID。"""
if not wo:
raise HTTPException(status_code=404, detail="工单不存在")
if (getattr(wo, "work_order_type", None) or "") != "outbound":
raise HTTPException(status_code=400, detail="仅出库工单可确认出库细胞")
if (getattr(wo, "biz_type", None) or "") != "basic_experiment":
raise HTTPException(status_code=400, detail="仅临床科研出库工单可确认出库细胞")
if (getattr(wo, "work_order_status", None) or "") == "yzf":
raise HTTPException(status_code=400, detail="已作废工单不可确认出库细胞")
schedule_id = (getattr(wo, "infusion_schedule_id", None) or "").strip()
if not schedule_id:
raise HTTPException(status_code=400, detail="工单未关联交付计划,无法确认出库细胞")
return schedule_id
def get_production_delivery_cell_outbound(
db: Session,
work_order_id: str,
tenant_no: str,
) -> Dict[str, Any]:
"""生产工单 — 临床科研交付出库细胞编辑数据。"""
from app.crud import production_work_order as production_work_order_svc
wo = production_work_order_svc.get_production_work_order(db, work_order_id, tenant_no)
schedule_id = _assert_basic_experiment_outbound_wo(wo)
detail = schedule_mgmt_svc.get_infusion_schedule_detail(db, schedule_id, tenant_no)
if not detail:
raise HTTPException(status_code=404, detail="交付计划不存在")
outbound_material = orm_material_svc.get_outbound_material(db, schedule_id, tenant_no)
return {
"workOrderId": wo.id,
"workOrderNo": wo.work_order_no or "",
"infusionScheduleId": schedule_id,
"scheduleSummary": {
"applicationNo": detail.get("applicationNo") or "",
"patientName": detail.get("patientName") or "",
"infusionTime": detail.get("infusionTime") or "",
"projectTitle": detail.get("projectTitle")
or ((detail.get("application") or {}).get("projectTitle") or ""),
"customerName": detail.get("customerName")
or ((detail.get("application") or {}).get("customerName") or ""),
},
"cells": outbound_material.get("cells") or [],
}
def save_production_delivery_cell_outbound(
db: Session,
work_order_id: str,
*,
cells: List[Dict[str, Any]],
tenant_no: str,
user_id: str,
create_dept_id: str = "",
) -> Dict[str, Any]:
"""生产确认临床科研交付出库细胞:写台账并联动细胞产品库存(不 commit)。"""
from app.crud import production_work_order as production_work_order_svc
wo = production_work_order_svc.get_production_work_order(db, work_order_id, tenant_no)
schedule_id = _assert_basic_experiment_outbound_wo(wo)
detail = schedule_mgmt_svc.get_infusion_schedule_detail(db, schedule_id, tenant_no)
if not detail:
raise HTTPException(status_code=404, detail="交付计划不存在")
previous_material = orm_material_svc.get_outbound_material(db, schedule_id, tenant_no)
previous_cell_ids = [
(c.get("cellProductId") or c.get("cell_product_id") or "").strip()
for c in (previous_material.get("cells") or [])
]
# 仅回滚细胞;市场物料扣减由出库交接维护,不可一并撤销
handover_inv_svc.revert_handover_inventory(
db,
schedule_id,
cell_product_ids=previous_cell_ids,
tenant_no=tenant_no,
user_id=user_id,
skip_materials=True,
)
orm_material_svc.save_outbound_material(
db,
schedule_id,
paper_attachments=None,
paper_materials=previous_material.get("paperMaterials") or [],
remark=previous_material.get("remark"),
cells=cells or [],
qc_materials=previous_material.get("qcMaterials") or [],
tenant_no=tenant_no,
user_id=user_id,
create_dept_id=create_dept_id,
)
handover_inv_svc.apply_handover_inventory(
db,
schedule_id,
cells=cells or [],
qc_materials=[],
tenant_no=tenant_no,
user_id=user_id,
create_dept_id=create_dept_id,
receiver_person="",
)
return get_production_delivery_cell_outbound(db, work_order_id, tenant_no)
+22 -17
View File
@@ -264,30 +264,35 @@ def revert_handover_inventory(
cell_product_ids: Iterable[str], cell_product_ids: Iterable[str],
tenant_no: str, tenant_no: str,
user_id: Optional[str] = None, user_id: Optional[str] = None,
skip_materials: bool = False,
) -> None: ) -> None:
"""回滚本输注计划上次出库交接产生的库存/状态变更(不 commit)。""" """回滚本输注计划上次出库交接产生的库存/状态变更(不 commit)。
skip_materials=True 时仅回滚细胞产品状态(临床科研由生产单独出库细胞时使用)。
"""
sid = (schedule_id or "").strip() sid = (schedule_id or "").strip()
if not sid: if not sid:
return return
remark_prefix = _handover_usage_remark_prefix(sid) remark_prefix = _handover_usage_remark_prefix(sid)
now = datetime.now() now = datetime.now()
_revert_legacy_qc_handover_usages( if not skip_materials:
db, _revert_legacy_qc_handover_usages(
schedule_id=sid, db,
tenant_no=tenant_no, schedule_id=sid,
user_id=user_id, tenant_no=tenant_no,
remark_prefix=remark_prefix, user_id=user_id,
now=now, remark_prefix=remark_prefix,
) now=now,
_revert_market_handover_usages( )
db, _revert_market_handover_usages(
schedule_id=sid, db,
tenant_no=tenant_no, schedule_id=sid,
user_id=user_id, tenant_no=tenant_no,
remark_prefix=remark_prefix, user_id=user_id,
now=now, remark_prefix=remark_prefix,
) now=now,
)
seen: Set[str] = set() seen: Set[str] = set()
for raw_id in cell_product_ids: for raw_id in cell_product_ids:
+1 -1
View File
@@ -41,7 +41,7 @@ _QC_STATUS_LABELS = {
_BIZ_TYPE_LABELS = { _BIZ_TYPE_LABELS = {
"pilot_service": "中试服务", "pilot_service": "中试服务",
"clinical_application": "临床应用", "clinical_application": "临床应用",
"basic_experiment": "基础实验", "basic_experiment": "临床科研",
} }
+54 -5
View File
@@ -25,6 +25,7 @@ from app.models.models import (
) )
from app.crud import pilot_checkup from app.crud import pilot_checkup
from app.crud.collection_protocol import attachments_to_urls, urls_to_attachment_list from app.crud.collection_protocol import attachments_to_urls, urls_to_attachment_list
from app.constants.research_category import validate_research_category
# ──────────────────────────────────────────── # ────────────────────────────────────────────
@@ -125,6 +126,7 @@ def _row_to_dict_application(row, db=None, tenant_no=None) -> Dict[str, Any]:
"customerName": row.customer_name or "", "customerName": row.customer_name or "",
"customerContact": row.customer_contact or "", "customerContact": row.customer_contact or "",
"customerPhone": row.customer_phone or "", "customerPhone": row.customer_phone or "",
"researchCategory": getattr(row, "research_category", None) or "",
"applicationStatus": row.application_status or "", "applicationStatus": row.application_status or "",
"bizType": row.biz_type or "pilot_service", "bizType": row.biz_type or "pilot_service",
"channelServiceOrderId": row.channel_service_order_id or "", "channelServiceOrderId": row.channel_service_order_id or "",
@@ -455,6 +457,7 @@ def create_application(
customer_name = "" customer_name = ""
customer_contact = "" customer_contact = ""
customer_phone = "" customer_phone = ""
research_category = ""
consent_form_urls = data.get("consentFormUrls") or None consent_form_urls = data.get("consentFormUrls") or None
if biz_type == "basic_experiment": if biz_type == "basic_experiment":
@@ -466,13 +469,29 @@ def create_application(
raise ValueError("请填写客户联系人") raise ValueError("请填写客户联系人")
if not (data.get("customerPhone") or "").strip(): if not (data.get("customerPhone") or "").strip():
raise ValueError("请填写客户联系方式") raise ValueError("请填写客户联系方式")
research_category = validate_research_category(
data.get("researchCategory"), required=True
)
project_title = (data.get("projectTitle") or "").strip() project_title = (data.get("projectTitle") or "").strip()
customer_name = (data.get("customerName") or "").strip() customer_name = (data.get("customerName") or "").strip()
customer_contact = (data.get("customerContact") or "").strip() customer_contact = (data.get("customerContact") or "").strip()
customer_phone = (data.get("customerPhone") or "").strip() customer_phone = (data.get("customerPhone") or "").strip()
channel_service_order_id = "" channel_service_order_id = ""
channel_id = "" channel_id = (data.get("channelId") or "").strip()
channel_name = "" if not channel_id:
raise ValueError("请选择渠道")
ch = (
db.query(BizChannel)
.filter(
BizChannel.id == channel_id,
BizChannel.tenant_no == tenant_no,
BizChannel.del_flag == 0,
)
.first()
)
if not ch:
raise ValueError("渠道不存在")
channel_name = ch.channel_name or ""
consent_form_urls = None consent_form_urls = None
elif not channel_service_order_id and biz_type != "clinical_application": elif not channel_service_order_id and biz_type != "clinical_application":
raise ValueError("请选择渠道服务订单") raise ValueError("请选择渠道服务订单")
@@ -527,6 +546,7 @@ def create_application(
customer_name=customer_name or None, customer_name=customer_name or None,
customer_contact=customer_contact or None, customer_contact=customer_contact or None,
customer_phone=customer_phone or None, customer_phone=customer_phone or None,
research_category=research_category or None,
application_status="dks", application_status="dks",
channel_service_order_id=channel_service_order_id or "", channel_service_order_id=channel_service_order_id or "",
channel_id=( channel_id=(
@@ -586,6 +606,35 @@ def update_application(db: Session, app_id: str, data: dict, tenant_no: str) ->
row.customer_contact = (data["customerContact"] or "").strip() or None row.customer_contact = (data["customerContact"] or "").strip() or None
if "customerPhone" in data and data["customerPhone"] is not None: if "customerPhone" in data and data["customerPhone"] is not None:
row.customer_phone = (data["customerPhone"] or "").strip() or None row.customer_phone = (data["customerPhone"] or "").strip() or None
if "researchCategory" in data and data["researchCategory"] is not None:
if (row.biz_type or "") == "basic_experiment":
row.research_category = validate_research_category(
data.get("researchCategory"), required=True
) or None
else:
row.research_category = validate_research_category(
data.get("researchCategory"), required=False
) or None
if "channelId" in data and data["channelId"] is not None:
if (row.biz_type or "") in ("basic_experiment", "clinical_application"):
new_channel_id = (data.get("channelId") or "").strip()
if not new_channel_id:
raise ValueError("请选择渠道")
ch = (
db.query(BizChannel)
.filter(
BizChannel.id == new_channel_id,
BizChannel.tenant_no == tenant_no,
BizChannel.del_flag == 0,
)
.first()
)
if not ch:
raise ValueError("渠道不存在")
row.channel_id = new_channel_id
row.channel_name = ch.channel_name or ""
if (row.biz_type or "") == "basic_experiment":
row.channel_service_order_id = ""
if "consentFormUrls" in data: if "consentFormUrls" in data:
row.consent_form_urls = data.get("consentFormUrls") or None row.consent_form_urls = data.get("consentFormUrls") or None
if "attachmentUrls" in data: if "attachmentUrls" in data:
@@ -1601,7 +1650,7 @@ def _get_or_create_infusion_plan(
user_id: str, user_id: str,
dept_id: str, dept_id: str,
) -> BizPilotInfusionPlan: ) -> BizPilotInfusionPlan:
"""获取或创建申请单下的输注/售卖方案(基础实验批量创建售卖计划用)。""" """获取或创建申请单下的输注/售卖方案(临床科研批量创建售卖计划用)。"""
plans = list_infusion_plans(db, application_id, tenant_no) plans = list_infusion_plans(db, application_id, tenant_no)
if plans: if plans:
plan_row = ( plan_row = (
@@ -1647,7 +1696,7 @@ def create_basic_experiment_sale_schedules(
user_id: str, user_id: str,
dept_id: str, dept_id: str,
) -> List[Dict[str, Any]]: ) -> List[Dict[str, Any]]:
"""基础实验:每个产品行创建一条售卖计划(一产品一计划)。""" """临床科研:每个产品行创建一条售卖计划(一产品一计划)。"""
app = ( app = (
db.query(BizPilotApplication) db.query(BizPilotApplication)
.filter( .filter(
@@ -1660,7 +1709,7 @@ def create_basic_experiment_sale_schedules(
if not app: if not app:
raise ValueError("申请单不存在") raise ValueError("申请单不存在")
if (app.biz_type or "") != "basic_experiment": if (app.biz_type or "") != "basic_experiment":
raise ValueError("仅基础实验申请单可批量创建售卖计划") raise ValueError("仅临床科研申请单可批量创建售卖计划")
if not product_lines: if not product_lines:
raise ValueError("请至少添加一行售卖产品") raise ValueError("请至少添加一行售卖产品")
@@ -918,7 +918,7 @@ def _deduct_fee_on_complete(db: Session, schedule_id: str, tenant_no: str, user_
if not application: if not application:
raise ValueError("中试申请单不存在") raise ValueError("中试申请单不存在")
# 临床应用/基础实验走缴费模块,不走服务订单扣费 # 临床应用/临床科研走缴费模块,不走服务订单扣费
if (application.biz_type or "") in ("clinical_application", "basic_experiment"): if (application.biz_type or "") in ("clinical_application", "basic_experiment"):
return return
+2 -2
View File
@@ -198,7 +198,7 @@ def _wo_to_dict(wo: BizProductionWorkOrder) -> Dict[str, Any]:
"bizTypeLabel": { "bizTypeLabel": {
"pilot_service": "中试服务", "pilot_service": "中试服务",
"clinical_application": "临床应用", "clinical_application": "临床应用",
"basic_experiment": "基础实验", "basic_experiment": "临床科研",
}.get(getattr(wo, "biz_type", None) or "", ""), }.get(getattr(wo, "biz_type", None) or "", ""),
"workOrderStatus": wo.work_order_status, "workOrderStatus": wo.work_order_status,
"workOrderStatusLabel": _WORK_ORDER_STATUS_LABELS.get(wo.work_order_status, wo.work_order_status), "workOrderStatusLabel": _WORK_ORDER_STATUS_LABELS.get(wo.work_order_status, wo.work_order_status),
@@ -288,7 +288,7 @@ def _enrich_inbound_qc_conclusions(
_BIZ_TYPE_LABELS = { _BIZ_TYPE_LABELS = {
"pilot_service": "中试服务", "pilot_service": "中试服务",
"clinical_application": "临床应用", "clinical_application": "临床应用",
"basic_experiment": "基础实验", "basic_experiment": "临床科研",
} }
+36 -8
View File
@@ -19,6 +19,8 @@ from app.crud.qc_work_order import (
_sample_type_name_for_reception, _sample_type_name_for_reception,
_work_order_qc_biz_type, _work_order_qc_biz_type,
_OUTBOUND_BIZ_TYPE_LABELS, _OUTBOUND_BIZ_TYPE_LABELS,
apply_research_donation_protocol_status_filter,
build_qc_work_order_keyword_conditions,
build_work_order_list_summaries, build_work_order_list_summaries,
) )
from app.core.db_collation import eq_unicode, unicode_ci from app.core.db_collation import eq_unicode, unicode_ci
@@ -574,6 +576,7 @@ def list_mine_tasks(
qc_biz_type: Optional[str] = None, qc_biz_type: Optional[str] = None,
reception_source: Optional[str] = None, reception_source: Optional[str] = None,
biz_type: Optional[str] = None, biz_type: Optional[str] = None,
protocol_status: Optional[str] = None,
tenant_no: Optional[str] = None, tenant_no: Optional[str] = None,
) -> Tuple[List[Dict[str, Any]], int]: ) -> Tuple[List[Dict[str, Any]], int]:
def _filtered(): def _filtered():
@@ -601,14 +604,21 @@ def list_mine_tasks(
kw = (keyword or "").strip() kw = (keyword or "").strip()
if kw: if kw:
like = f"%{kw}%" like = f"%{kw}%"
q0 = q0.filter( wt = (qc_biz_type or "").strip()
or_( # temporary Tab 的 qcBizType=temporary,与工单 work_order_type 对齐
BizQcTask.task_no.like(like), wo_type = "temporary" if wt == "temporary" else (wt or None)
BizQcTask.item_name.like(like), keyword_conditions = [
BizQcWorkOrder.work_order_no.like(like), BizQcTask.task_no.like(like),
BizQcWorkOrder.sample_code.like(like), BizQcTask.item_name.like(like),
) *build_qc_work_order_keyword_conditions(
) db,
tenant_no=tenant_no,
keyword=kw,
work_order_type=wo_type,
reception_source=(reception_source or "").strip() or None,
),
]
q0 = q0.filter(or_(*keyword_conditions))
tt = (task_type or "").strip() tt = (task_type or "").strip()
if tt: if tt:
q0 = q0.filter(BizQcTask.task_type == tt) q0 = q0.filter(BizQcTask.task_type == tt)
@@ -632,6 +642,11 @@ def list_mine_tasks(
bt_out = (biz_type or "").strip() bt_out = (biz_type or "").strip()
if bt_out: if bt_out:
q0 = q0.filter(BizQcWorkOrder.biz_type == bt_out) q0 = q0.filter(BizQcWorkOrder.biz_type == bt_out)
q0 = apply_research_donation_protocol_status_filter(
q0,
protocol_status,
reception_source=reception_source,
)
return q0 return q0
total = _filtered().order_by(None).with_entities(func.count(BizQcTask.id)).scalar() or 0 total = _filtered().order_by(None).with_entities(func.count(BizQcTask.id)).scalar() or 0
@@ -1095,6 +1110,7 @@ def delete_qc_task(db: Session, task_id: str, tenant_no: str, user_id: Optional[
# 软删除任务结果 # 软删除任务结果
from app.models.qc_param import BizQcTaskResult from app.models.qc_param import BizQcTaskResult
from app.models.models import BizQcTaskResultChangeLog
results = db.query(BizQcTaskResult).filter( results = db.query(BizQcTaskResult).filter(
and_(BizQcTaskResult.task_id == task_id, BizQcTaskResult.del_flag == 0) and_(BizQcTaskResult.task_id == task_id, BizQcTaskResult.del_flag == 0)
@@ -1104,6 +1120,18 @@ def delete_qc_task(db: Session, task_id: str, tenant_no: str, user_id: Optional[
r.update_by = user_id r.update_by = user_id
r.update_time = now r.update_time = now
change_logs = db.query(BizQcTaskResultChangeLog).filter(
and_(
BizQcTaskResultChangeLog.task_id == task_id,
BizQcTaskResultChangeLog.tenant_no == tenant_no,
BizQcTaskResultChangeLog.del_flag == 0,
)
).all()
for log in change_logs:
log.del_flag = 1
log.update_by = user_id
log.update_time = now
# 同步软删批次明细行(配置弹窗勾选来源) # 同步软删批次明细行(配置弹窗勾选来源)
_soft_delete_source_line_for_task( _soft_delete_source_line_for_task(
db, task, tenant_no=tenant_no, user_id=user_id, now=now db, task, tenant_no=tenant_no, user_id=user_id, now=now
@@ -0,0 +1,254 @@
"""质检任务检测结果操作留痕"""
from __future__ import annotations
import json
from datetime import datetime
from typing import Any, Dict, List, Optional
from sqlalchemy.orm import Session
from app.core.utils import generate_uuid
from app.models.models import BizQcTask, BizQcTaskResultChangeLog, SysUser
from app.models.qc_param import BizQcTaskResult
_TASK_STATUS_LABELS = {"dzx": "待执行", "jxz": "进行中", "ywc": "已完成"}
_CONCLUSION_LABELS = {"": "待结论", "tg": "通过", "btg": "不通过"}
def _fmt_dt(v: Optional[datetime]) -> str:
if not v:
return ""
return v.strftime("%Y-%m-%d %H:%M:%S")
def _display_status(code: Optional[str]) -> str:
c = (code or "").strip()
return _TASK_STATUS_LABELS.get(c, c or "—")
def _display_conclusion(code: Optional[str]) -> str:
c = (code or "").strip()
return _CONCLUSION_LABELS.get(c, c or "待结论")
def _norm_text(v: Any) -> str:
if v is None:
return ""
return str(v).strip()
def _param_key(param_id: Optional[str], param_code: Optional[str], param_name: Optional[str]) -> str:
pid = _norm_text(param_id)
if pid:
return f"paramId:{pid}"
code = _norm_text(param_code)
if code:
return f"paramCode:{code}"
return f"paramName:{_norm_text(param_name)}"
def snapshot_task_result_state(db: Session, task: BizQcTask, tenant_no: str) -> Dict[str, Any]:
"""保存前快照:任务结论字段 + 已存参数值。"""
rows = (
db.query(BizQcTaskResult)
.filter(
BizQcTaskResult.task_id == task.id,
BizQcTaskResult.tenant_no == tenant_no,
BizQcTaskResult.del_flag == 0,
)
.order_by(BizQcTaskResult.create_time.asc())
.all()
)
params: Dict[str, Dict[str, str]] = {}
for r in rows:
key = _param_key(r.param_id, r.param_code, r.param_name)
params[key] = {
"label": _norm_text(r.param_name) or key,
"value": _norm_text(r.param_value),
}
return {
"taskStatus": _norm_text(task.task_status),
"conclusion": _norm_text(task.conclusion),
"remark": _norm_text(task.remark),
"attachments": _norm_text(task.third_party_attachments),
"params": params,
}
def build_result_changes(
before: Dict[str, Any],
after: Dict[str, Any],
) -> List[Dict[str, str]]:
changes: List[Dict[str, str]] = []
def add(field_key: str, label: str, old_v: str, new_v: str) -> None:
if old_v == new_v:
return
changes.append(
{
"fieldKey": field_key,
"fieldLabel": label,
"oldValue": old_v,
"newValue": new_v,
}
)
add(
"taskStatus",
"任务状态",
_display_status(before.get("taskStatus")),
_display_status(after.get("taskStatus")),
)
add(
"conclusion",
"结论",
_display_conclusion(before.get("conclusion")),
_display_conclusion(after.get("conclusion")),
)
add("remark", "备注", _norm_text(before.get("remark")), _norm_text(after.get("remark")))
add(
"attachments",
"检测材料",
_norm_text(before.get("attachments")),
_norm_text(after.get("attachments")),
)
before_params: Dict[str, Dict[str, str]] = before.get("params") or {}
after_params: Dict[str, Dict[str, str]] = after.get("params") or {}
keys = sorted(set(before_params.keys()) | set(after_params.keys()))
for key in keys:
b = before_params.get(key) or {"label": key, "value": ""}
a = after_params.get(key) or {"label": b.get("label") or key, "value": ""}
label = _norm_text(a.get("label")) or _norm_text(b.get("label")) or key
add(key, label, _norm_text(b.get("value")), _norm_text(a.get("value")))
return changes
def _resolve_operator_name(db: Session, user_id: Optional[str], fallback: str = "") -> str:
uid = _norm_text(user_id)
if not uid:
return _norm_text(fallback)
row = db.query(SysUser.nick_name).filter(SysUser.id == uid).first()
if row and row[0]:
return str(row[0]).strip()
return _norm_text(fallback) or uid
def append_task_result_change_log(
db: Session,
*,
task: BizQcTask,
tenant_no: str,
user_id: Optional[str],
operator_user_name: str = "",
before: Dict[str, Any],
after: Dict[str, Any],
operate_time: Optional[datetime] = None,
operate_batch_id: Optional[str] = None,
) -> BizQcTaskResultChangeLog:
"""追加一条检测结果保存留痕(不 commit)。无字段差异也写入。"""
now = operate_time or datetime.now()
changes = build_result_changes(before, after)
has_change = "1" if changes else "0"
name = _resolve_operator_name(db, user_id, operator_user_name)
batch_id = _norm_text(operate_batch_id) or None
obj = BizQcTaskResultChangeLog(
id=generate_uuid(),
task_id=task.id,
work_order_id=_norm_text(task.work_order_id) or None,
sample_code=_norm_text(task.sample_code) or None,
item_name=_norm_text(task.item_name) or None,
operate_time=now,
operator_user_id=user_id,
operator_user_name=name or None,
operate_batch_id=batch_id,
has_field_change=has_change,
changes_json=json.dumps(changes, ensure_ascii=False),
tenant_no=tenant_no,
order_num=0,
remark=None,
create_by=user_id,
create_dept_id="",
create_time=now,
update_by=user_id,
update_time=now,
del_flag=0,
)
db.add(obj)
return obj
def _row_to_dict(row: BizQcTaskResultChangeLog) -> Dict[str, Any]:
changes: List[Dict[str, Any]] = []
raw = row.changes_json or ""
if raw.strip():
try:
parsed = json.loads(raw)
if isinstance(parsed, list):
changes = parsed
except json.JSONDecodeError:
changes = []
return {
"id": row.id,
"taskId": row.task_id,
"workOrderId": row.work_order_id or "",
"sampleCode": row.sample_code or "",
"itemName": row.item_name or "",
"operateTime": _fmt_dt(row.operate_time),
"operatorUserId": row.operator_user_id or "",
"operatorUserName": row.operator_user_name or "",
"operateBatchId": row.operate_batch_id or "",
"hasFieldChange": row.has_field_change == "1",
"changes": changes,
"createTime": _fmt_dt(row.create_time),
}
def list_task_result_change_logs(
db: Session,
*,
task_id: str,
tenant_no: str,
) -> List[Dict[str, Any]]:
tid = _norm_text(task_id)
if not tid:
return []
rows = (
db.query(BizQcTaskResultChangeLog)
.filter(
BizQcTaskResultChangeLog.task_id == tid,
BizQcTaskResultChangeLog.tenant_no == tenant_no,
BizQcTaskResultChangeLog.del_flag == 0,
)
.order_by(
BizQcTaskResultChangeLog.operate_time.desc(),
BizQcTaskResultChangeLog.create_time.desc(),
)
.all()
)
return [_row_to_dict(r) for r in rows]
def list_task_result_change_logs_by_task_ids(
db: Session,
*,
task_ids: List[str],
tenant_no: str,
) -> List[Dict[str, Any]]:
ids = [_norm_text(x) for x in task_ids if _norm_text(x)]
if not ids:
return []
rows = (
db.query(BizQcTaskResultChangeLog)
.filter(
BizQcTaskResultChangeLog.task_id.in_(ids),
BizQcTaskResultChangeLog.tenant_no == tenant_no,
BizQcTaskResultChangeLog.del_flag == 0,
)
.order_by(
BizQcTaskResultChangeLog.operate_time.desc(),
BizQcTaskResultChangeLog.create_time.desc(),
)
.all()
)
return [_row_to_dict(r) for r in rows]
+85 -34
View File
@@ -108,7 +108,7 @@ _CONCLUSION_LABELS = {"tg": "通过", "btg": "不通过"}
_OUTBOUND_BIZ_TYPE_LABELS = { _OUTBOUND_BIZ_TYPE_LABELS = {
"pilot_service": "中试服务", "pilot_service": "中试服务",
"clinical_application": "临床应用", "clinical_application": "临床应用",
"basic_experiment": "基础实验", "basic_experiment": "临床科研",
} }
_OUTBOUND_BIZ_TYPES = tuple(_OUTBOUND_BIZ_TYPE_LABELS.keys()) _OUTBOUND_BIZ_TYPES = tuple(_OUTBOUND_BIZ_TYPE_LABELS.keys())
@@ -560,6 +560,56 @@ def _inbound_qc_work_order_ids_by_mother_name(
return list(ids) return list(ids)
def build_qc_work_order_keyword_conditions(
db: Optional[Session],
*,
tenant_no: Optional[str],
keyword: str,
work_order_type: Optional[str] = None,
reception_source: Optional[str] = None,
) -> List[Any]:
"""质检工单列表关键词 OR 条件(工单号/样本/协议号/外部编号 + 入库编码/母亲/出库申请字段)。
供质检工单列表与「我的质检任务」共用,避免两端口径漂移。
"""
kw = (keyword or "").strip()
if not kw:
return []
like = f"%{kw}%"
wt = (work_order_type or "").strip()
rs = (reception_source or "").strip()
conditions: List[Any] = [
BizQcWorkOrder.work_order_no.like(like),
BizQcWorkOrder.sample_code.like(like),
BizQcWorkOrder.protocol_no.like(like),
BizQcWorkOrder.external_target_code.like(like),
]
if db is not None and tenant_no:
from app.crud import sample_reception as reception_svc
rec_ids = reception_svc.reception_ids_matching_lab_storage_keyword(
db, tenant_no, kw
)
if rec_ids:
conditions.append(BizQcWorkOrder.reception_id.in_(rec_ids))
lab_codes = reception_svc.sample_codes_matching_lab_storage_keyword(
db, tenant_no, kw
)
if lab_codes:
conditions.append(BizQcWorkOrder.sample_code.in_(lab_codes))
if wt == "outbound" or not wt:
outbound_ids = _outbound_qc_work_order_ids_by_keyword(db, tenant_no, kw)
if outbound_ids:
conditions.append(BizQcWorkOrder.id.in_(outbound_ids))
if not wt or wt == "inbound":
inbound_mother_ids = _inbound_qc_work_order_ids_by_mother_name(
db, tenant_no, kw, reception_source=rs or None
)
if inbound_mother_ids:
conditions.append(BizQcWorkOrder.id.in_(inbound_mother_ids))
return conditions
def _accept_conclusion_label(v: Optional[str]) -> str: def _accept_conclusion_label(v: Optional[str]) -> str:
key = (v or "").strip() key = (v or "").strip()
return _ACCEPT_CONCLUSION_LABELS.get(key, key) return _ACCEPT_CONCLUSION_LABELS.get(key, key)
@@ -1718,8 +1768,8 @@ def apply_research_donation_protocol_status_filter(
return query return query
mode, statuses = resolve_research_donation_protocol_status_filter(protocol_status) mode, statuses = resolve_research_donation_protocol_status_filter(protocol_status)
if mode == "none": if mode == "all":
return query.filter(BizQcWorkOrder.id.in_([])) return query
if mode == "in": if mode == "in":
return query.filter(_research_donation_status_exists(statuses)) return query.filter(_research_donation_status_exists(statuses))
# default:与前端默认勾选一致 # default:与前端默认勾选一致
@@ -1791,37 +1841,15 @@ def list_work_orders(
q0 = q0.filter(BizQcWorkOrder.trigger_source == ts) q0 = q0.filter(BizQcWorkOrder.trigger_source == ts)
kw = (keyword or "").strip() kw = (keyword or "").strip()
if kw: if kw:
like = f"%{kw}%" keyword_conditions = build_qc_work_order_keyword_conditions(
keyword_conditions = [ db,
BizQcWorkOrder.work_order_no.like(like), tenant_no=tenant_no,
BizQcWorkOrder.sample_code.like(like), keyword=kw,
BizQcWorkOrder.protocol_no.like(like), work_order_type=wt or None,
BizQcWorkOrder.external_target_code.like(like), reception_source=rs or None,
] )
if tenant_no: if keyword_conditions:
from app.crud import sample_reception as reception_svc q0 = q0.filter(or_(*keyword_conditions))
rec_ids = reception_svc.reception_ids_matching_lab_storage_keyword(
db, tenant_no, kw
)
if rec_ids:
keyword_conditions.append(BizQcWorkOrder.reception_id.in_(rec_ids))
lab_codes = reception_svc.sample_codes_matching_lab_storage_keyword(
db, tenant_no, kw
)
if lab_codes:
keyword_conditions.append(BizQcWorkOrder.sample_code.in_(lab_codes))
if tenant_no and (wt == "outbound" or not wt):
outbound_ids = _outbound_qc_work_order_ids_by_keyword(db, tenant_no, kw)
if outbound_ids:
keyword_conditions.append(BizQcWorkOrder.id.in_(outbound_ids))
if tenant_no and (not wt or wt == "inbound"):
inbound_mother_ids = _inbound_qc_work_order_ids_by_mother_name(
db, tenant_no, kw, reception_source=rs or None
)
if inbound_mother_ids:
keyword_conditions.append(BizQcWorkOrder.id.in_(inbound_mother_ids))
q0 = q0.filter(or_(*keyword_conditions))
st_raw = (work_order_status or "").strip() st_raw = (work_order_status or "").strip()
if st_raw: if st_raw:
statuses = [s.strip() for s in st_raw.split(",") if s.strip()] statuses = [s.strip() for s in st_raw.split(",") if s.strip()]
@@ -2753,6 +2781,16 @@ def _soft_delete_tasks_by_source_line_ids(
{"del_flag": 1, "update_time": now}, {"del_flag": 1, "update_time": now},
synchronize_session="fetch", synchronize_session="fetch",
) )
from app.models.models import BizQcTaskResultChangeLog
db.query(BizQcTaskResultChangeLog).filter(
BizQcTaskResultChangeLog.task_id.in_(task_ids),
BizQcTaskResultChangeLog.tenant_no == tenant_no,
BizQcTaskResultChangeLog.del_flag == 0,
).update(
{"del_flag": 1, "update_time": now},
synchronize_session="fetch",
)
for t in tasks: for t in tasks:
t.del_flag = 1 t.del_flag = 1
t.update_time = now t.update_time = now
@@ -3884,6 +3922,8 @@ def delete_qc_work_order(db: Session, work_order_id: str, tenant_no: str, user_i
).all() ).all()
from app.models.qc_param import BizQcTaskResult from app.models.qc_param import BizQcTaskResult
from app.models.models import BizQcTaskResultChangeLog
for task in tasks: for task in tasks:
results = db.query(BizQcTaskResult).filter( results = db.query(BizQcTaskResult).filter(
and_(BizQcTaskResult.task_id == task.id, BizQcTaskResult.del_flag == 0) and_(BizQcTaskResult.task_id == task.id, BizQcTaskResult.del_flag == 0)
@@ -3892,6 +3932,17 @@ def delete_qc_work_order(db: Session, work_order_id: str, tenant_no: str, user_i
r.del_flag = 1 r.del_flag = 1
r.update_by = user_id r.update_by = user_id
r.update_time = now r.update_time = now
change_logs = db.query(BizQcTaskResultChangeLog).filter(
and_(
BizQcTaskResultChangeLog.task_id == task.id,
BizQcTaskResultChangeLog.tenant_no == tenant_no,
BizQcTaskResultChangeLog.del_flag == 0,
)
).all()
for log in change_logs:
log.del_flag = 1
log.update_by = user_id
log.update_time = now
task.del_flag = 1 task.del_flag = 1
task.update_by = user_id task.update_by = user_id
task.update_time = now task.update_time = now
+37 -5
View File
@@ -2394,6 +2394,33 @@ class BizQcTask(Base):
del_flag = Column(SmallInteger, nullable=False, default=0, comment="删除标记") del_flag = Column(SmallInteger, nullable=False, default=0, comment="删除标记")
class BizQcTaskResultChangeLog(Base):
"""质检任务检测结果操作留痕 biz_qc_task_result_change_log(Issue #148/#149)"""
__tablename__ = "biz_qc_task_result_change_log"
id = Column(String(64), primary_key=True, comment="主键ID")
task_id = Column(String(64), nullable=False, comment="质检任务ID")
work_order_id = Column(String(64), nullable=True, comment="质检工单ID快照")
sample_code = Column(String(32), nullable=True, comment="样本编码快照")
item_name = Column(String(200), nullable=True, comment="检测项目名称快照")
operate_time = Column(DateTime, nullable=False, comment="业务操作时间")
operator_user_id = Column(String(64), nullable=True, comment="操作人用户ID")
operator_user_name = Column(String(64), nullable=True, comment="操作人姓名快照")
operate_batch_id = Column(String(64), nullable=True, comment="同一次保存批次ID(多任务共用)")
has_field_change = Column(CHAR(1), nullable=False, default="0", comment="1有字段变更 0仅保存无变更")
changes_json = Column(Text, nullable=True, comment="变更明细JSON")
tenant_no = Column(String(64), nullable=False, default="zkxw", comment="租户编号")
order_num = Column(Integer, nullable=True, comment="排序号")
remark = Column(String(512), nullable=True, comment="备注")
create_by = Column(String(64), nullable=True, comment="创建人id")
create_dept_id = Column(String(64), nullable=False, default="", comment="创建人部门ID")
create_time = Column(DateTime, nullable=False, default=datetime.now, comment="创建时间")
update_by = Column(String(64), nullable=True, comment="更新人id")
update_time = Column(DateTime, nullable=False, default=datetime.now, onupdate=datetime.now, comment="更新时间")
del_flag = Column(SmallInteger, nullable=False, default=0, comment="删除标记")
class BizQcTaskAssignee(Base): class BizQcTaskAssignee(Base):
"""质检任务负责人 biz_qc_task_assignee""" """质检任务负责人 biz_qc_task_assignee"""
@@ -4151,15 +4178,20 @@ class BizPilotApplication(Base):
project_id = Column(String(64), nullable=True, index=True, comment="所属统计项目ID") project_id = Column(String(64), nullable=True, index=True, comment="所属统计项目ID")
application_no = Column(String(64), nullable=True, comment="申请单号(自动生成,前缀ZSSQ)") application_no = Column(String(64), nullable=True, comment="申请单号(自动生成,前缀ZSSQ)")
application_name = Column(String(200), nullable=True, comment="申请单名称") application_name = Column(String(200), nullable=True, comment="申请单名称")
project_title = Column(String(200), nullable=True, comment="课题名称(基础实验)") project_title = Column(String(200), nullable=True, comment="课题名称(临床科研)")
customer_name = Column(String(200), nullable=True, comment="客户名称(基础实验)") customer_name = Column(String(200), nullable=True, comment="客户名称(临床科研)")
customer_contact = Column(String(100), nullable=True, comment="客户联系人(基础实验)") customer_contact = Column(String(100), nullable=True, comment="客户联系人(临床科研)")
customer_phone = Column(String(32), nullable=True, comment="客户联系方式(基础实验)") customer_phone = Column(String(32), nullable=True, comment="客户联系方式(临床科研)")
research_category = Column(
String(32),
nullable=True,
comment="临床科研业务子类型: bio_tech_clinical/joint_topic_declare/bio_pharma_rd",
)
application_status = Column(String(16), nullable=False, default="dks", comment="dks待开始 jxz进行中 ywc已完成 yzf已作废") application_status = Column(String(16), nullable=False, default="dks", comment="dks待开始 jxz进行中 ywc已完成 yzf已作废")
channel_service_order_id = Column(String(64), nullable=False, comment="渠道服务购买订单ID") channel_service_order_id = Column(String(64), nullable=False, comment="渠道服务购买订单ID")
channel_id = Column(String(64), nullable=True, comment="渠道ID(缓存自服务订单)") channel_id = Column(String(64), nullable=True, comment="渠道ID(缓存自服务订单)")
channel_name = Column(String(200), nullable=True, comment="渠道名称(缓存)") channel_name = Column(String(200), nullable=True, comment="渠道名称(缓存)")
biz_type = Column(String(20), nullable=False, default="pilot_service", comment="业务类型: pilot_service=中试服务, clinical_application=临床应用, basic_experiment=基础实验") biz_type = Column(String(20), nullable=False, default="pilot_service", comment="业务类型: pilot_service=中试服务, clinical_application=临床应用, basic_experiment=临床科研")
tenant_no = Column(String(64), nullable=False, default="zkxw", comment="租户编号") tenant_no = Column(String(64), nullable=False, default="zkxw", comment="租户编号")
order_num = Column(Integer, nullable=True, comment="排序号") order_num = Column(Integer, nullable=True, comment="排序号")
remark = Column(String(512), nullable=True, comment="备注") remark = Column(String(512), nullable=True, comment="备注")
+9 -1
View File
@@ -1,5 +1,5 @@
from pydantic import BaseModel, ConfigDict, Field from pydantic import BaseModel, ConfigDict, Field
from typing import Optional from typing import Any, Dict, List, Optional
from datetime import datetime from datetime import datetime
@@ -57,3 +57,11 @@ class ProductionWorkOrderConfigureBody(BaseModel):
route_id: Optional[str] = Field(None, alias="routeId") route_id: Optional[str] = Field(None, alias="routeId")
description: Optional[str] = Field("", alias="description") description: Optional[str] = Field("", alias="description")
remark: Optional[str] = Field("", alias="remark") remark: Optional[str] = Field("", alias="remark")
class ProductionDeliveryCellOutboundBody(BaseModel):
"""临床科研出库工单 — 确认出库细胞。"""
model_config = ConfigDict(populate_by_name=True)
cells: List[Dict[str, Any]] = Field(default_factory=list, description="出库细胞产品列表")
@@ -1,4 +1,4 @@
"""基础实验交付日前一天:服务号模板提醒。""" """临床科研交付日前一天:服务号模板提醒。"""
from __future__ import annotations from __future__ import annotations
import logging import logging
@@ -137,7 +137,7 @@ def _iter_candidate_schedules(db: Session, *, delivery_day: date) -> List[Any]:
.order_by(BizPilotInfusionSchedule.infusion_time.asc()) .order_by(BizPilotInfusionSchedule.infusion_time.asc())
.all() .all()
) )
# 一计划多产品时取首条产品行(基础实验通常一行) # 一计划多产品时取首条产品行(临床科研通常一行)
seen: set = set() seen: set = set()
out = [] out = []
for sched, app, prod in rows: for sched, app, prod in rows:
@@ -1,4 +1,4 @@
"""质检工单 · 用户费用摘要(采集协议 / 基础实验)""" """质检工单 · 用户费用摘要(采集协议 / 临床科研)"""
from __future__ import annotations from __future__ import annotations
from decimal import Decimal from decimal import Decimal
@@ -27,7 +27,7 @@ _PAY_STATUS_LABELS = {
"ytf": "已退费", "ytf": "已退费",
} }
# 出库工单:输注计划缴费(基础实验 / 临床应用共用 biz_pilot_payment) # 出库工单:输注计划缴费(临床科研 / 临床应用共用 biz_pilot_payment)
_OUTBOUND_FEE_BIZ_TYPES = frozenset({"basic_experiment", "clinical_application"}) _OUTBOUND_FEE_BIZ_TYPES = frozenset({"basic_experiment", "clinical_application"})
+1 -1
View File
@@ -246,7 +246,7 @@ def send_basic_experiment_delivery_remind(
time_text: str, time_text: str,
pagepath: str = "", pagepath: str = "",
) -> dict: ) -> dict:
"""基础实验:交付日前一天出库提醒。""" """临床科研:交付日前一天出库提醒。"""
data: Dict[str, Dict[str, str]] = {} data: Dict[str, Dict[str, str]] = {}
customer_key = (settings.WX_MP_TPL_BE_DELIVERY_FIELD_CUSTOMER or "").strip() customer_key = (settings.WX_MP_TPL_BE_DELIVERY_FIELD_CUSTOMER or "").strip()
product_key = (settings.WX_MP_TPL_BE_DELIVERY_FIELD_PRODUCT or "").strip() product_key = (settings.WX_MP_TPL_BE_DELIVERY_FIELD_PRODUCT or "").strip()
@@ -1,4 +1,4 @@
"""基础实验申请单与售卖计划批量创建""" """临床科研申请单与售卖计划批量创建"""
import unittest import unittest
from unittest.mock import MagicMock, patch from unittest.mock import MagicMock, patch
@@ -28,6 +28,8 @@ class TestBasicExperimentCreateValidation(unittest.TestCase):
db = MagicMock() db = MagicMock()
data = { data = {
"bizType": "basic_experiment", "bizType": "basic_experiment",
"researchCategory": "bio_tech_clinical",
"channelId": "ch-1",
"projectTitle": "课题A", "projectTitle": "课题A",
"customerName": "", "customerName": "",
"customerContact": "张三", "customerContact": "张三",
@@ -43,6 +45,46 @@ class TestBasicExperimentCreateValidation(unittest.TestCase):
) )
self.assertIn("客户名称", str(ctx.exception)) self.assertIn("客户名称", str(ctx.exception))
def test_create_basic_experiment_requires_research_category(self):
db = MagicMock()
data = {
"bizType": "basic_experiment",
"channelId": "ch-1",
"projectTitle": "课题A",
"customerName": "客户A",
"customerContact": "张三",
"customerPhone": "13800000000",
}
with self.assertRaises(ValueError) as ctx:
crud.create_application(
db,
data=data,
tenant_no="zkxw",
user_id="user-1",
dept_id="dept-1",
)
self.assertIn("业务类型", str(ctx.exception))
def test_create_basic_experiment_requires_channel(self):
db = MagicMock()
data = {
"bizType": "basic_experiment",
"researchCategory": "bio_tech_clinical",
"projectTitle": "课题A",
"customerName": "客户A",
"customerContact": "张三",
"customerPhone": "13800000000",
}
with self.assertRaises(ValueError) as ctx:
crud.create_application(
db,
data=data,
tenant_no="zkxw",
user_id="user-1",
dept_id="dept-1",
)
self.assertIn("渠道", str(ctx.exception))
class TestBasicExperimentSaleSchedules(unittest.TestCase): class TestBasicExperimentSaleSchedules(unittest.TestCase):
@patch("app.crud.pilot_application.create_schedule") @patch("app.crud.pilot_application.create_schedule")
@@ -1,4 +1,4 @@
"""基础实验交付日前一天服务号提醒单测。""" """临床科研交付日前一天服务号提醒单测。"""
from datetime import date, datetime from datetime import date, datetime
from unittest.mock import MagicMock, patch from unittest.mock import MagicMock, patch
@@ -0,0 +1,53 @@
"""市场下「中试服务」已从静态菜单树下线(Issue #158)。"""
import ast
import re
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
MENU_PY = ROOT / "backend/app/api/menu.py"
SQXP_TS = ROOT / "web-admin/src/router/modules/sqxp.ts"
HIDE_SQL = ROOT / "docs/sql/migrations/2026-11-20-hide-market-pilot-service-menus.sql"
def _market_children_titles_from_menu_py() -> list[str]:
source = MENU_PY.read_text(encoding="utf-8")
tree_match = re.search(r"STATIC_MENU_TREE\s*=\s*(\[[\s\S]*?\n\])\s*\n", source)
assert tree_match, "STATIC_MENU_TREE not found"
tree = ast.literal_eval(tree_match.group(1))
market = next(
node
for node in tree
if isinstance(node, dict) and (node.get("meta") or {}).get("menuCode") == "menu:market"
)
titles = []
for child in market.get("children") or []:
meta = child.get("meta") or {}
titles.append(str(meta.get("title") or ""))
return titles
def test_backend_static_menu_has_no_market_pilot_service():
titles = _market_children_titles_from_menu_py()
assert "中试服务" not in titles
assert "中试服务申请单" not in titles
def test_frontend_sqxp_has_no_market_pilot_service_block():
text = SQXP_TS.read_text(encoding="utf-8")
assert "name: 'PilotService'" not in text
assert "id: 'PIL00000000000000000000000000001'" not in text
assert "pilot-service:pilot-application:list" not in text
# 基础实验 / 临床仍可复用出库放行组件与权限码前缀
assert "basic-experiment:outbound-release-review:list" in text
assert "clinical-application:outbound-release-review:list" in text
def test_hide_sql_soft_deletes_sys_menu_only_under_market_pilot():
sql = HIDE_SQL.read_text(encoding="utf-8")
compact = re.sub(r"\s+", " ", re.sub(r"--[^\n]*", "", sql))
assert re.search(r"UPDATE\s+sys_menu", compact, re.IGNORECASE)
assert re.search(r"SET\s+m\.del_flag\s*=\s*1", compact, re.IGNORECASE)
assert "menu:market" in compact
assert "中试服务" in compact
assert not re.search(r"DELETE\s+FROM\s+sys_menu", compact, re.IGNORECASE)
@@ -0,0 +1,172 @@
"""临床科研:生产确认出库细胞 / 市场交接不改细胞库存。"""
import unittest
from unittest.mock import MagicMock, patch
from fastapi import HTTPException
class TestAssertBasicExperimentOutboundWo(unittest.TestCase):
def test_rejects_non_outbound(self):
from app.crud.outbound_handover import _assert_basic_experiment_outbound_wo
wo = MagicMock(
work_order_type="inbound",
biz_type="basic_experiment",
work_order_status="jxz",
infusion_schedule_id="s1",
)
with self.assertRaises(HTTPException) as ctx:
_assert_basic_experiment_outbound_wo(wo)
self.assertEqual(ctx.exception.status_code, 400)
def test_rejects_other_biz_type(self):
from app.crud.outbound_handover import _assert_basic_experiment_outbound_wo
wo = MagicMock(
work_order_type="outbound",
biz_type="pilot_service",
work_order_status="jxz",
infusion_schedule_id="s1",
)
with self.assertRaises(HTTPException) as ctx:
_assert_basic_experiment_outbound_wo(wo)
self.assertEqual(ctx.exception.status_code, 400)
def test_ok_returns_schedule_id(self):
from app.crud.outbound_handover import _assert_basic_experiment_outbound_wo
wo = MagicMock(
work_order_type="outbound",
biz_type="basic_experiment",
work_order_status="jxz",
infusion_schedule_id="sched-1",
)
self.assertEqual(_assert_basic_experiment_outbound_wo(wo), "sched-1")
class TestSaveOutboundHandoverBasicExperiment(unittest.TestCase):
@patch("app.crud.outbound_handover.handover_inv_svc")
@patch("app.crud.outbound_handover.orm_material_svc")
@patch("app.crud.outbound_handover.get_outbound_handover")
@patch("app.crud.outbound_handover.get_handover_by_schedule")
@patch("app.crud.outbound_handover.schedule_mgmt_svc")
def test_market_keeps_previous_cells_and_skips_cell_inventory(
self,
schedule_mgmt_svc,
get_handover_by_schedule,
get_outbound_handover,
orm_material_svc,
handover_inv_svc,
):
from app.crud.outbound_handover import save_outbound_handover
schedule_mgmt_svc.get_infusion_schedule_detail.return_value = {
"bizType": "basic_experiment",
"applicationNo": "A1",
}
previous_cells = [{"cellProductId": "cp-prod", "productCode": "P1"}]
orm_material_svc.get_outbound_material.return_value = {
"cells": previous_cells,
"qcMaterials": [],
"paperMaterials": [],
"remark": "",
}
get_handover_by_schedule.return_value = None
get_outbound_handover.return_value = {"ok": True}
db = MagicMock()
sys_user = MagicMock(nick_name="张三", user_no="u1", del_flag=0)
db.query.return_value.filter.return_value.first.return_value = sys_user
save_outbound_handover(
db,
"sched-1",
outbound_material={
"cells": [{"cellProductId": "cp-market-tamper"}],
"qcMaterials": [{"materialId": "m1", "qty": 1}],
"paperMaterials": [],
},
handover={
"handoverUserId": "u1",
"receiverPerson": "李四",
"handoverTime": "2026-11-20 10:00:00",
},
tenant_no="t1",
user_id="u1",
)
handover_inv_svc.revert_handover_inventory.assert_called_once()
revert_kwargs = handover_inv_svc.revert_handover_inventory.call_args.kwargs
self.assertEqual(revert_kwargs["cell_product_ids"], [])
save_kwargs = orm_material_svc.save_outbound_material.call_args.kwargs
self.assertEqual(save_kwargs["cells"], previous_cells)
apply_kwargs = handover_inv_svc.apply_handover_inventory.call_args.kwargs
self.assertEqual(apply_kwargs["cells"], [])
self.assertEqual(apply_kwargs["qc_materials"], [{"materialId": "m1", "qty": 1}])
class TestSaveProductionDeliveryCellOutbound(unittest.TestCase):
@patch("app.crud.outbound_handover.get_production_delivery_cell_outbound")
@patch("app.crud.outbound_handover.handover_inv_svc")
@patch("app.crud.outbound_handover.orm_material_svc")
@patch("app.crud.outbound_handover.schedule_mgmt_svc")
@patch("app.crud.production_work_order.get_production_work_order")
def test_reverts_cells_only_then_applies(
self,
get_wo,
schedule_mgmt_svc,
orm_material_svc,
handover_inv_svc,
get_delivery,
):
from app.crud.outbound_handover import save_production_delivery_cell_outbound
get_wo.return_value = MagicMock(
id="wo1",
work_order_no="WO1",
work_order_type="outbound",
biz_type="basic_experiment",
work_order_status="jxz",
infusion_schedule_id="sched-1",
)
schedule_mgmt_svc.get_infusion_schedule_detail.return_value = {
"bizType": "basic_experiment"
}
orm_material_svc.get_outbound_material.return_value = {
"cells": [{"cellProductId": "old-cp"}],
"qcMaterials": [{"materialId": "m1", "qty": 2}],
"paperMaterials": [{"paperName": "出库单", "copies": 1}],
"remark": "keep",
}
get_delivery.return_value = {"cells": []}
cells = [{"cellProductId": "new-cp"}]
save_production_delivery_cell_outbound(
MagicMock(),
"wo1",
cells=cells,
tenant_no="t1",
user_id="u1",
create_dept_id="d1",
)
revert_kwargs = handover_inv_svc.revert_handover_inventory.call_args.kwargs
self.assertEqual(revert_kwargs["cell_product_ids"], ["old-cp"])
self.assertTrue(revert_kwargs["skip_materials"])
save_kwargs = orm_material_svc.save_outbound_material.call_args.kwargs
self.assertEqual(save_kwargs["cells"], cells)
self.assertEqual(save_kwargs["qc_materials"], [{"materialId": "m1", "qty": 2}])
self.assertEqual(
save_kwargs["paper_materials"], [{"paperName": "出库单", "copies": 1}]
)
apply_kwargs = handover_inv_svc.apply_handover_inventory.call_args.kwargs
self.assertEqual(apply_kwargs["cells"], cells)
self.assertEqual(apply_kwargs["qc_materials"], [])
if __name__ == "__main__":
unittest.main()
@@ -17,8 +17,8 @@ def test_explicit_statuses_returned():
assert resolve_research_donation_protocol_status_filter("dsx,sxz") == ("in", ["dsx", "sxz"]) assert resolve_research_donation_protocol_status_filter("dsx,sxz") == ("in", ["dsx", "sxz"])
def test_explicit_empty_means_none(): def test_explicit_empty_means_all():
assert resolve_research_donation_protocol_status_filter("") == ("none", []) assert resolve_research_donation_protocol_status_filter("") == ("all", [])
def test_missing_means_default_dsx_sxz(): def test_missing_means_default_dsx_sxz():
@@ -27,5 +27,5 @@ def test_missing_means_default_dsx_sxz():
assert statuses == ["dsx", "sxz"] assert statuses == ["dsx", "sxz"]
def test_whitespace_only_means_none(): def test_whitespace_only_means_all():
assert resolve_research_donation_protocol_status_filter(" , ") == ("none", []) assert resolve_research_donation_protocol_status_filter(" , ") == ("all", [])
@@ -0,0 +1,38 @@
"""质检检测结果留痕:字段差异与空保存。"""
from app.crud.qc_task_result_change_log import build_result_changes
def test_build_changes_for_status_and_param():
before = {
"taskStatus": "dzx",
"conclusion": "",
"remark": "",
"attachments": "",
"params": {"paramCode:HBsAg": {"label": "HBsAg", "value": "阴性"}},
}
after = {
"taskStatus": "ywc",
"conclusion": "tg",
"remark": "",
"attachments": "",
"params": {"paramCode:HBsAg": {"label": "HBsAg", "value": "阳性"}},
}
changes = build_result_changes(before, after)
keys = {c["fieldKey"] for c in changes}
assert "taskStatus" in keys
assert "conclusion" in keys
assert "paramCode:HBsAg" in keys
hbs = next(c for c in changes if c["fieldKey"] == "paramCode:HBsAg")
assert hbs["oldValue"] == "阴性"
assert hbs["newValue"] == "阳性"
def test_build_changes_empty_when_identical():
state = {
"taskStatus": "ywc",
"conclusion": "tg",
"remark": "ok",
"attachments": "a.png",
"params": {"paramCode:X": {"label": "X", "value": "1"}},
}
assert build_result_changes(state, state) == []
@@ -0,0 +1,34 @@
"""质检工单 / 我的质检任务共用关键词条件(无库路径)。"""
# qc_work_order ↔ qc_task 存在循环依赖:先经 qc_task 再取 helper
import app.crud.qc_task # noqa: F401
from app.crud.qc_work_order import build_qc_work_order_keyword_conditions
from app.models.models import BizQcWorkOrder
def test_empty_keyword_returns_no_conditions():
assert build_qc_work_order_keyword_conditions(
None, tenant_no=None, keyword=""
) == []
assert build_qc_work_order_keyword_conditions(
None, tenant_no="t1", keyword=" "
) == []
def test_base_conditions_without_tenant_cover_list_fields():
conds = build_qc_work_order_keyword_conditions(
None,
tenant_no=None,
keyword="ABC",
work_order_type="inbound",
reception_source="cell_storage",
)
assert len(conds) == 4
# 与质检工单列表一致的四列(无租户时不做入库/母亲/出库扩展)
cols = {str(c.left) for c in conds}
assert str(BizQcWorkOrder.work_order_no) in cols or any(
"work_order_no" in str(c) for c in conds
)
assert any("sample_code" in str(c) for c in conds)
assert any("protocol_no" in str(c) for c in conds)
assert any("external_target_code" in str(c) for c in conds)
@@ -0,0 +1,62 @@
"""Static checks for market/pilot-service role-menu revoke migration (#156)."""
import re
from pathlib import Path
MIGRATION = (
Path(__file__).resolve().parents[2]
/ "docs/sql/migrations/2026-11-20-revoke-market-pilot-service-role-menus.sql"
)
def _sql() -> str:
return MIGRATION.read_text(encoding="utf-8")
def _compact(sql: str) -> str:
return re.sub(r"\s+", " ", sql)
def _without_comments(sql: str) -> str:
return re.sub(r"--[^\n]*", "", sql)
def test_migration_file_exists():
assert MIGRATION.is_file()
def test_scopes_to_market_pilot_service_tree():
compact = _compact(_without_comments(_sql()))
assert "menu:market" in compact
assert "中试服务" in compact
assert re.search(r"pilot\.menu_name\s*=\s*'中试服务'", compact)
assert re.search(r"market\.perms\s*=\s*'menu:market'", compact)
def test_revokes_role_menu_by_soft_delete_only():
compact = _compact(_without_comments(_sql()))
assert re.search(r"UPDATE\s+sys_role_menu", compact, re.IGNORECASE)
assert re.search(
r"UPDATE\s+sys_role_menu\s+rm\b.*SET\s+rm\.del_flag\s*=\s*1",
compact,
re.IGNORECASE,
)
assert not re.search(r"DELETE\s+FROM\s+sys_role_menu", compact, re.IGNORECASE)
assert not re.search(r"UPDATE\s+sys_menu\s+SET\s+del_flag\s*=\s*1", compact, re.IGNORECASE)
assert not re.search(r"DELETE\s+FROM\s+sys_menu", compact, re.IGNORECASE)
def test_includes_children_and_button_descendants():
compact = _compact(_without_comments(_sql()))
assert re.search(r"child\.parent_id\s*=\s*pilot\.id", compact)
assert re.search(r"btn\.parent_id\s*=\s*child\.id", compact)
assert compact.count("UNION") >= 2
def test_update_only_touches_active_bindings():
compact = _compact(_without_comments(_sql()))
assert re.search(
r"SET\s+rm\.del_flag\s*=\s*1[\s\S]*WHERE\s+rm\.del_flag\s*=\s*0",
compact,
re.IGNORECASE,
)
@@ -0,0 +1,164 @@
-- 市场模块新增「器械销售」及三个子菜单;授权给已有 menu:market 的角色。
-- 不新建角色/用户;用户经现有 sys_user_role 自动带上菜单。
-- MySQL 5.7,可重复执行。目标库:测试库(如 zkxw-sc)。
-- 1) 二级目录:器械销售(挂在市场下,order_num=6 末位)
INSERT INTO sys_menu (
id, menu_name, parent_id, menu_type, path, component, perms,
is_frame, visible, status, tenant_no, order_num, remark,
create_by, create_dept_id, create_time, update_by, update_time, del_flag
)
SELECT
'DEV00000000000000000000000000001',
'器械销售',
m.id,
'M',
'device-sales',
NULL,
'menu:device-sales',
1, '1', '1', m.tenant_no, 6,
'市场-器械销售',
'migration', '', NOW(), 'migration', NOW(), 0
FROM sys_menu m
WHERE m.del_flag = 0 AND m.perms = 'menu:market'
AND NOT EXISTS (
SELECT 1 FROM sys_menu e
WHERE e.id = 'DEV00000000000000000000000000001' AND e.del_flag = 0
);
-- 2) 子菜单:三类 / 二类 / 化妆品
INSERT INTO sys_menu (
id, menu_name, parent_id, menu_type, path, component, perms,
is_frame, visible, status, tenant_no, order_num, remark,
create_by, create_dept_id, create_time, update_by, update_time, del_flag
)
SELECT
x.id, x.menu_name, 'DEV00000000000000000000000000001', 'C', x.path,
'device-sales/under-construction/index', x.perms,
1, '1', '1', p.tenant_no, x.order_num, x.remark,
'migration', '', NOW(), 'migration', NOW(), 0
FROM sys_menu p
JOIN (
SELECT 'DEV00000000000000000000000000002' AS id, '三类医疗器械' AS menu_name,
'class-iii' AS path, 'device-sales:class-iii:list' AS perms, 1 AS order_num,
'市场-器械销售-三类医疗器械' AS remark
UNION ALL
SELECT 'DEV00000000000000000000000000003', '二类医疗器械',
'class-ii', 'device-sales:class-ii:list', 2,
'市场-器械销售-二类医疗器械'
UNION ALL
SELECT 'DEV00000000000000000000000000004', '化妆品产品',
'cosmetics', 'device-sales:cosmetics:list', 3,
'市场-器械销售-化妆品产品'
) x ON 1 = 1
WHERE p.del_flag = 0 AND p.id = 'DEV00000000000000000000000000001'
AND NOT EXISTS (
SELECT 1 FROM sys_menu e WHERE e.id = x.id AND e.del_flag = 0
);
-- 3) 给已有「市场」顶级菜单授权的角色,授予器械销售目录+三个子菜单
-- (含祖先目录,满足选中子菜单须含祖先)
INSERT INTO sys_role_menu (
id, role_id, menu_id, tenant_no, order_num, remark,
create_by, create_dept_id, create_time, update_by, update_time, del_flag
)
SELECT
INSERT(INSERT(MD5(CONCAT('device-sales-rm:', r.tenant_no, ':', r.id, ':', m.id)), 13, 1, '3'), 17, 1, '8'),
r.id, m.id, r.tenant_no, NULL,
'grant device-sales from menu:market',
'migration', '', NOW(), 'migration', NOW(), 0
FROM sys_role r
JOIN sys_role_menu src
ON src.role_id = r.id AND src.tenant_no = r.tenant_no AND src.del_flag = 0
JOIN sys_menu top
ON top.id = src.menu_id AND top.tenant_no = src.tenant_no AND top.del_flag = 0
AND top.perms = 'menu:market'
JOIN sys_menu m
ON m.tenant_no = r.tenant_no AND m.del_flag = 0 AND m.status = '1'
AND m.id IN (
'DEV00000000000000000000000000001',
'DEV00000000000000000000000000002',
'DEV00000000000000000000000000003',
'DEV00000000000000000000000000004'
)
WHERE r.del_flag = 0
AND NOT EXISTS (
SELECT 1 FROM sys_role_menu existing
WHERE existing.role_id = r.id
AND existing.menu_id = m.id
AND existing.tenant_no = r.tenant_no
AND existing.del_flag = 0
);
-- 3b) 超级管理员同步授予(角色管理勾选与超管侧栏数据一致)
INSERT INTO sys_role_menu (
id, role_id, menu_id, tenant_no, order_num, remark,
create_by, create_dept_id, create_time, update_by, update_time, del_flag
)
SELECT
INSERT(INSERT(MD5(CONCAT('device-sales-sa:', r.tenant_no, ':', r.id, ':', m.id)), 13, 1, '3'), 17, 1, '8'),
r.id, m.id, r.tenant_no, NULL,
'grant device-sales to super admin',
'migration', '', NOW(), 'migration', NOW(), 0
FROM sys_role r
JOIN sys_menu m
ON m.del_flag = 0 AND m.status = '1'
AND m.id IN (
'DEV00000000000000000000000000001',
'DEV00000000000000000000000000002',
'DEV00000000000000000000000000003',
'DEV00000000000000000000000000004'
)
WHERE r.del_flag = 0 AND r.role_name = '超级管理员'
AND NOT EXISTS (
SELECT 1 FROM sys_role_menu existing
WHERE existing.role_id = r.id
AND existing.menu_id = m.id
AND existing.tenant_no = r.tenant_no
AND existing.del_flag = 0
);
-- 3c) 恢复已挂到上述角色、但被软删的用户-角色关联(打通 用户→角色→菜单)
UPDATE sys_user_role ur
JOIN sys_role r ON r.id = ur.role_id AND r.del_flag = 0
JOIN sys_role_menu rm
ON rm.role_id = r.id AND rm.del_flag = 0
AND rm.menu_id = 'DEV00000000000000000000000000001'
JOIN sys_user u ON u.id = ur.user_id AND u.del_flag = 0
SET ur.del_flag = 0,
ur.update_by = 'migration',
ur.update_time = NOW()
WHERE ur.del_flag = 1;
-- 4) 核对
SELECT id, menu_name, parent_id, path, perms, order_num, visible, del_flag
FROM sys_menu
WHERE id LIKE 'DEV0000000000000000000000000000%'
ORDER BY order_num, menu_name;
SELECT COUNT(DISTINCT rm.role_id) AS roles_granted,
COUNT(*) AS role_menu_rows
FROM sys_role_menu rm
WHERE rm.del_flag = 0
AND rm.menu_id IN (
'DEV00000000000000000000000000001',
'DEV00000000000000000000000000002',
'DEV00000000000000000000000000003',
'DEV00000000000000000000000000004'
);
-- 抽样:有市场权限的用户是否能通过角色落到器械销售菜单
SELECT u.nick_name, u.phone_no, r.role_name, m.menu_name, m.perms
FROM sys_user u
JOIN sys_user_role ur ON ur.user_id = u.id AND ur.del_flag = 0
JOIN sys_role r ON r.id = ur.role_id AND r.del_flag = 0
JOIN sys_role_menu rm ON rm.role_id = r.id AND rm.del_flag = 0
JOIN sys_menu m ON m.id = rm.menu_id AND m.del_flag = 0
WHERE u.del_flag = 0
AND m.id IN (
'DEV00000000000000000000000000002',
'DEV00000000000000000000000000003',
'DEV00000000000000000000000000004'
)
ORDER BY u.nick_name, m.order_num
LIMIT 30;
@@ -0,0 +1,129 @@
-- 软删【市场】下【中试服务】目录及其子菜单(含按钮),与前端静态路由下线对齐。
-- Issue #158(承接 #156:仅解绑角色对超管侧栏无效)
-- MySQL 5.7,可重复执行;不影响基础实验/临床应用下同名菜单。
-- 0) 预览目标菜单
SELECT
m.tenant_no,
m.id AS menu_id,
m.menu_name,
m.menu_type,
m.perms,
m.parent_id,
m.del_flag
FROM sys_menu m
JOIN (
SELECT pilot.id AS menu_id, pilot.tenant_no
FROM sys_menu market
JOIN sys_menu pilot
ON pilot.parent_id = market.id
AND pilot.tenant_no = market.tenant_no
AND pilot.del_flag = 0
AND pilot.menu_name = '中试服务'
WHERE market.del_flag = 0
AND market.perms = 'menu:market'
UNION
SELECT child.id, child.tenant_no
FROM sys_menu market
JOIN sys_menu pilot
ON pilot.parent_id = market.id
AND pilot.tenant_no = market.tenant_no
AND pilot.del_flag = 0
AND pilot.menu_name = '中试服务'
JOIN sys_menu child
ON child.parent_id = pilot.id
AND child.tenant_no = market.tenant_no
AND child.del_flag = 0
WHERE market.del_flag = 0
AND market.perms = 'menu:market'
UNION
SELECT btn.id, btn.tenant_no
FROM sys_menu market
JOIN sys_menu pilot
ON pilot.parent_id = market.id
AND pilot.tenant_no = market.tenant_no
AND pilot.del_flag = 0
AND pilot.menu_name = '中试服务'
JOIN sys_menu child
ON child.parent_id = pilot.id
AND child.tenant_no = market.tenant_no
AND child.del_flag = 0
JOIN sys_menu btn
ON btn.parent_id = child.id
AND btn.tenant_no = market.tenant_no
AND btn.del_flag = 0
WHERE market.del_flag = 0
AND market.perms = 'menu:market'
) tgt
ON tgt.menu_id = m.id
AND tgt.tenant_no = m.tenant_no
WHERE m.del_flag = 0
ORDER BY m.tenant_no, m.menu_type, m.order_num, m.menu_name;
-- 1) 软删目标菜单
UPDATE sys_menu m
JOIN (
SELECT pilot.id AS menu_id, pilot.tenant_no
FROM sys_menu market
JOIN sys_menu pilot
ON pilot.parent_id = market.id
AND pilot.tenant_no = market.tenant_no
AND pilot.del_flag = 0
AND pilot.menu_name = '中试服务'
WHERE market.del_flag = 0
AND market.perms = 'menu:market'
UNION
SELECT child.id, child.tenant_no
FROM sys_menu market
JOIN sys_menu pilot
ON pilot.parent_id = market.id
AND pilot.tenant_no = market.tenant_no
AND pilot.del_flag = 0
AND pilot.menu_name = '中试服务'
JOIN sys_menu child
ON child.parent_id = pilot.id
AND child.tenant_no = market.tenant_no
AND child.del_flag = 0
WHERE market.del_flag = 0
AND market.perms = 'menu:market'
UNION
SELECT btn.id, btn.tenant_no
FROM sys_menu market
JOIN sys_menu pilot
ON pilot.parent_id = market.id
AND pilot.tenant_no = market.tenant_no
AND pilot.del_flag = 0
AND pilot.menu_name = '中试服务'
JOIN sys_menu child
ON child.parent_id = pilot.id
AND child.tenant_no = market.tenant_no
AND child.del_flag = 0
JOIN sys_menu btn
ON btn.parent_id = child.id
AND btn.tenant_no = market.tenant_no
AND btn.del_flag = 0
WHERE market.del_flag = 0
AND market.perms = 'menu:market'
) tgt
ON tgt.menu_id = m.id
AND tgt.tenant_no = m.tenant_no
SET
m.del_flag = 1,
m.update_by = 'migration',
m.update_time = NOW()
WHERE m.del_flag = 0;
-- 2) 核对:市场下不应再有有效「中试服务」目录(期望 0 行)
SELECT
market.tenant_no,
pilot.id,
pilot.menu_name,
pilot.del_flag
FROM sys_menu market
JOIN sys_menu pilot
ON pilot.parent_id = market.id
AND pilot.tenant_no = market.tenant_no
AND pilot.del_flag = 0
AND pilot.menu_name = '中试服务'
WHERE market.del_flag = 0
AND market.perms = 'menu:market';
@@ -0,0 +1,20 @@
-- 临床科研申请单:业务子类型 research_category
-- MySQL 5.7,可重复执行。
SET @col_exists := (
SELECT COUNT(*)
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'biz_pilot_application'
AND COLUMN_NAME = 'research_category'
);
SET @sql := IF(
@col_exists = 0,
"ALTER TABLE biz_pilot_application ADD COLUMN research_category VARCHAR(32) NULL COMMENT '临床科研业务子类型: bio_tech_clinical/joint_topic_declare/bio_pharma_rd' AFTER customer_phone",
'SELECT 1'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
@@ -0,0 +1,8 @@
-- 质检检测结果留痕:同一次批量保存共用 operate_batch_id(Issue #153)
-- 历史行可为空;前端对无批次号的旧数据做短时窗口合并兜底。
ALTER TABLE `biz_qc_task_result_change_log`
ADD COLUMN `operate_batch_id` varchar(64) DEFAULT NULL COMMENT '同一次保存批次ID(多任务共用)' AFTER `operator_user_name`;
ALTER TABLE `biz_qc_task_result_change_log`
ADD KEY `idx_qc_result_chg_batch` (`tenant_no`, `operate_batch_id`, `del_flag`);
@@ -0,0 +1,27 @@
-- 质检任务检测结果操作留痕(Issue #148 / #149)
-- 每次「填写检测结果」保存追加一条;即使字段无变更也记录操作人与时间。
CREATE TABLE IF NOT EXISTS `biz_qc_task_result_change_log` (
`id` varchar(64) NOT NULL COMMENT '主键ID',
`task_id` varchar(64) NOT NULL COMMENT '质检任务ID',
`work_order_id` varchar(64) DEFAULT NULL COMMENT '质检工单ID快照',
`sample_code` varchar(32) DEFAULT NULL COMMENT '样本编码快照',
`item_name` varchar(200) DEFAULT NULL COMMENT '检测项目名称快照',
`operate_time` datetime NOT NULL COMMENT '业务操作时间',
`operator_user_id` varchar(64) DEFAULT NULL COMMENT '操作人用户ID',
`operator_user_name` varchar(64) DEFAULT NULL COMMENT '操作人姓名快照',
`has_field_change` char(1) NOT NULL DEFAULT '0' COMMENT '1有字段变更 0仅保存无变更',
`changes_json` mediumtext COMMENT '变更明细JSON:[{fieldKey,fieldLabel,oldValue,newValue}]',
`tenant_no` varchar(64) NOT NULL DEFAULT 'zkxw' COMMENT '租户编号',
`order_num` int(11) DEFAULT NULL COMMENT '排序号',
`remark` varchar(512) DEFAULT NULL COMMENT '备注',
`create_by` varchar(64) DEFAULT NULL COMMENT '创建人id',
`create_dept_id` varchar(64) NOT NULL DEFAULT '' COMMENT '创建人部门ID',
`create_time` datetime NOT NULL COMMENT '创建时间',
`update_by` varchar(64) DEFAULT NULL COMMENT '更新人id',
`update_time` datetime NOT NULL COMMENT '更新时间',
`del_flag` smallint(6) NOT NULL DEFAULT '0' COMMENT '删除标记',
PRIMARY KEY (`id`),
KEY `idx_qc_result_chg_task` (`tenant_no`,`task_id`,`del_flag`,`operate_time`),
KEY `idx_qc_result_chg_wo` (`tenant_no`,`work_order_id`,`del_flag`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='质检任务检测结果操作留痕';
@@ -0,0 +1,14 @@
-- 展示名:基础实验 → 临床科研(仅中文;不改 perms / path / component / id)
-- MySQL 5.7,可重复执行。目标库:测试库(如 zkxw-sc)。
UPDATE sys_menu
SET
menu_name = REPLACE(menu_name, '基础实验', '临床科研'),
remark = REPLACE(IFNULL(remark, ''), '基础实验', '临床科研'),
update_by = 'migration',
update_time = NOW()
WHERE del_flag = 0
AND (
menu_name LIKE '%基础实验%'
OR IFNULL(remark, '') LIKE '%基础实验%'
);
@@ -0,0 +1,256 @@
-- 解除【市场】下【中试服务】目录及其全部子菜单(含按钮)与角色的绑定。
-- Issue #156
-- 仅软删 sys_role_menu(del_flag=1),不删除/隐藏菜单本身。
-- 按树定位:menu:market → menu_name=中试服务 → 直系子菜单 → 孙级按钮;
-- 不匹配基础实验/临床应用等其他目录下的同名「出库放行审核」。
-- MySQL 5.7,可重复执行(只处理 del_flag=0 的绑定)。
-- ---------------------------------------------------------------------------
-- 0) 预览:将要解绑的目标菜单(目录 + 子菜单 + 按钮)
-- ---------------------------------------------------------------------------
SELECT
m.tenant_no,
m.id AS menu_id,
m.menu_name,
m.menu_type,
m.perms,
m.parent_id,
m.path
FROM sys_menu m
JOIN (
SELECT pilot.id AS menu_id, pilot.tenant_no
FROM sys_menu market
JOIN sys_menu pilot
ON pilot.parent_id = market.id
AND pilot.tenant_no = market.tenant_no
AND pilot.del_flag = 0
AND pilot.menu_name = '中试服务'
WHERE market.del_flag = 0
AND market.perms = 'menu:market'
UNION
SELECT child.id, child.tenant_no
FROM sys_menu market
JOIN sys_menu pilot
ON pilot.parent_id = market.id
AND pilot.tenant_no = market.tenant_no
AND pilot.del_flag = 0
AND pilot.menu_name = '中试服务'
JOIN sys_menu child
ON child.parent_id = pilot.id
AND child.tenant_no = market.tenant_no
AND child.del_flag = 0
WHERE market.del_flag = 0
AND market.perms = 'menu:market'
UNION
SELECT btn.id, btn.tenant_no
FROM sys_menu market
JOIN sys_menu pilot
ON pilot.parent_id = market.id
AND pilot.tenant_no = market.tenant_no
AND pilot.del_flag = 0
AND pilot.menu_name = '中试服务'
JOIN sys_menu child
ON child.parent_id = pilot.id
AND child.tenant_no = market.tenant_no
AND child.del_flag = 0
JOIN sys_menu btn
ON btn.parent_id = child.id
AND btn.tenant_no = market.tenant_no
AND btn.del_flag = 0
WHERE market.del_flag = 0
AND market.perms = 'menu:market'
) tgt
ON tgt.menu_id = m.id
AND tgt.tenant_no = m.tenant_no
WHERE m.del_flag = 0
ORDER BY m.tenant_no, m.menu_type, m.order_num, m.menu_name;
-- ---------------------------------------------------------------------------
-- 1) 预览:将要软删的角色-菜单绑定
-- ---------------------------------------------------------------------------
SELECT
rm.tenant_no,
r.id AS role_id,
r.role_name,
m.id AS menu_id,
m.menu_name,
m.menu_type,
m.perms,
rm.id AS role_menu_id
FROM sys_role_menu rm
JOIN sys_role r
ON r.id = rm.role_id
AND r.tenant_no = rm.tenant_no
AND r.del_flag = 0
JOIN sys_menu m
ON m.id = rm.menu_id
AND m.tenant_no = rm.tenant_no
AND m.del_flag = 0
JOIN (
SELECT pilot.id AS menu_id, pilot.tenant_no
FROM sys_menu market
JOIN sys_menu pilot
ON pilot.parent_id = market.id
AND pilot.tenant_no = market.tenant_no
AND pilot.del_flag = 0
AND pilot.menu_name = '中试服务'
WHERE market.del_flag = 0
AND market.perms = 'menu:market'
UNION
SELECT child.id, child.tenant_no
FROM sys_menu market
JOIN sys_menu pilot
ON pilot.parent_id = market.id
AND pilot.tenant_no = market.tenant_no
AND pilot.del_flag = 0
AND pilot.menu_name = '中试服务'
JOIN sys_menu child
ON child.parent_id = pilot.id
AND child.tenant_no = market.tenant_no
AND child.del_flag = 0
WHERE market.del_flag = 0
AND market.perms = 'menu:market'
UNION
SELECT btn.id, btn.tenant_no
FROM sys_menu market
JOIN sys_menu pilot
ON pilot.parent_id = market.id
AND pilot.tenant_no = market.tenant_no
AND pilot.del_flag = 0
AND pilot.menu_name = '中试服务'
JOIN sys_menu child
ON child.parent_id = pilot.id
AND child.tenant_no = market.tenant_no
AND child.del_flag = 0
JOIN sys_menu btn
ON btn.parent_id = child.id
AND btn.tenant_no = market.tenant_no
AND btn.del_flag = 0
WHERE market.del_flag = 0
AND market.perms = 'menu:market'
) tgt
ON tgt.menu_id = rm.menu_id
AND tgt.tenant_no = rm.tenant_no
WHERE rm.del_flag = 0
ORDER BY rm.tenant_no, r.role_name, m.menu_name;
-- ---------------------------------------------------------------------------
-- 2) 软删绑定(可重复执行)
-- ---------------------------------------------------------------------------
UPDATE sys_role_menu rm
JOIN (
SELECT pilot.id AS menu_id, pilot.tenant_no
FROM sys_menu market
JOIN sys_menu pilot
ON pilot.parent_id = market.id
AND pilot.tenant_no = market.tenant_no
AND pilot.del_flag = 0
AND pilot.menu_name = '中试服务'
WHERE market.del_flag = 0
AND market.perms = 'menu:market'
UNION
SELECT child.id, child.tenant_no
FROM sys_menu market
JOIN sys_menu pilot
ON pilot.parent_id = market.id
AND pilot.tenant_no = market.tenant_no
AND pilot.del_flag = 0
AND pilot.menu_name = '中试服务'
JOIN sys_menu child
ON child.parent_id = pilot.id
AND child.tenant_no = market.tenant_no
AND child.del_flag = 0
WHERE market.del_flag = 0
AND market.perms = 'menu:market'
UNION
SELECT btn.id, btn.tenant_no
FROM sys_menu market
JOIN sys_menu pilot
ON pilot.parent_id = market.id
AND pilot.tenant_no = market.tenant_no
AND pilot.del_flag = 0
AND pilot.menu_name = '中试服务'
JOIN sys_menu child
ON child.parent_id = pilot.id
AND child.tenant_no = market.tenant_no
AND child.del_flag = 0
JOIN sys_menu btn
ON btn.parent_id = child.id
AND btn.tenant_no = market.tenant_no
AND btn.del_flag = 0
WHERE market.del_flag = 0
AND market.perms = 'menu:market'
) tgt
ON tgt.menu_id = rm.menu_id
AND tgt.tenant_no = rm.tenant_no
SET
rm.del_flag = 1,
rm.update_by = 'migration',
rm.update_time = NOW()
WHERE rm.del_flag = 0;
-- ---------------------------------------------------------------------------
-- 3) 核对:目标菜单上不应再有有效角色绑定(期望 0 行)
-- ---------------------------------------------------------------------------
SELECT
rm.tenant_no,
r.role_name,
m.menu_name,
m.perms,
COUNT(*) AS active_role_menu_rows
FROM sys_role_menu rm
JOIN sys_role r
ON r.id = rm.role_id
AND r.tenant_no = rm.tenant_no
AND r.del_flag = 0
JOIN sys_menu m
ON m.id = rm.menu_id
AND m.tenant_no = rm.tenant_no
AND m.del_flag = 0
JOIN (
SELECT pilot.id AS menu_id, pilot.tenant_no
FROM sys_menu market
JOIN sys_menu pilot
ON pilot.parent_id = market.id
AND pilot.tenant_no = market.tenant_no
AND pilot.del_flag = 0
AND pilot.menu_name = '中试服务'
WHERE market.del_flag = 0
AND market.perms = 'menu:market'
UNION
SELECT child.id, child.tenant_no
FROM sys_menu market
JOIN sys_menu pilot
ON pilot.parent_id = market.id
AND pilot.tenant_no = market.tenant_no
AND pilot.del_flag = 0
AND pilot.menu_name = '中试服务'
JOIN sys_menu child
ON child.parent_id = pilot.id
AND child.tenant_no = market.tenant_no
AND child.del_flag = 0
WHERE market.del_flag = 0
AND market.perms = 'menu:market'
UNION
SELECT btn.id, btn.tenant_no
FROM sys_menu market
JOIN sys_menu pilot
ON pilot.parent_id = market.id
AND pilot.tenant_no = market.tenant_no
AND pilot.del_flag = 0
AND pilot.menu_name = '中试服务'
JOIN sys_menu child
ON child.parent_id = pilot.id
AND child.tenant_no = market.tenant_no
AND child.del_flag = 0
JOIN sys_menu btn
ON btn.parent_id = child.id
AND btn.tenant_no = market.tenant_no
AND btn.del_flag = 0
WHERE market.del_flag = 0
AND market.perms = 'menu:market'
) tgt
ON tgt.menu_id = rm.menu_id
AND tgt.tenant_no = rm.tenant_no
WHERE rm.del_flag = 0
GROUP BY rm.tenant_no, r.role_name, m.menu_name, m.perms;
@@ -103,7 +103,7 @@ export const receptionSource = createRegistry({
outbound: { label: '出库', tagType: 'primary' }, outbound: { label: '出库', tagType: 'primary' },
pilot_service: { label: '中试服务', tagType: 'primary' }, pilot_service: { label: '中试服务', tagType: 'primary' },
clinical_application: { label: '临床应用', tagType: 'warning' }, clinical_application: { label: '临床应用', tagType: 'warning' },
basic_experiment: { label: '基础实验', tagType: 'primary' } basic_experiment: { label: '临床科研', tagType: 'primary' }
}) })
/** 协议/捐赠样本状态;与 Web sampleStatus 保持一致 */ /** 协议/捐赠样本状态;与 Web sampleStatus 保持一致 */
@@ -12,7 +12,7 @@
用户明确采用 [Figma 原型 v2](https://www.figma.com/design/wOQLDAhr1gdlQEXnVaFO9S?node-id=13-23)。范围为 Web 历史归属维护及其后端读取接口,沿用用户先合入 V2.0 再自测的安排。复用 P02 列表和 `pilot-service/pilot-application/index.vue` 的 `panel-pill-tabs`,操作列固定右侧,搜索右对齐。 用户明确采用 [Figma 原型 v2](https://www.figma.com/design/wOQLDAhr1gdlQEXnVaFO9S?node-id=13-23)。范围为 Web 历史归属维护及其后端读取接口,沿用用户先合入 V2.0 再自测的安排。复用 P02 列表和 `pilot-service/pilot-application/index.vue` 的 `panel-pill-tabs`,操作列固定右侧,搜索右对齐。
`RecordList` 仅在 assignment 模式显示四类正式业务 tab 和业务识别列。细胞存储/科研捐赠展示母亲姓名、电话、采集医院、市场专员及采集/捐赠日期;中试展示申请名称、渠道、服务订单名称、患者姓名/电话;基础实验展示课题、客户名称/联系人/电话。公共列保留序号、主单号、状态、项目组、所属项目、创建时间。多个有效子记录以稳定顺序去重连接展示,缺失值显示破折号,采集日期来自采集信息的样本采集时间。 `RecordList` 仅在 assignment 模式显示四类正式业务 tab 和业务识别列。细胞存储/科研捐赠展示母亲姓名、电话、采集医院、市场专员及采集/捐赠日期;中试展示申请名称、渠道、服务订单名称、患者姓名/电话;临床科研展示课题、客户名称/联系人/电话。公共列保留序号、主单号、状态、项目组、所属项目、创建时间。多个有效子记录以稳定顺序去重连接展示,缺失值显示破折号,采集日期来自采集信息的样本采集时间。
新增 `GET /web/admin/project-management/assignments/records`,严格要求 `project:assignment:edit`,仅接受四类正式业务。原 `/records` 继续服务统计明细,不扩展联系信息;移动接口不变。专用服务复用主单租户、软删除、数据权限和归属筛选。关键词支持单号、姓名/电话、医院/专员、渠道/服务订单名称、课题/客户信息(日期使用现有创建日期条件);子表使用同租户未删除记录 EXISTS 匹配,不增加主单行数。分页后批量补充项目、医院、人员、患者和服务订单资料,避免逐行查询。 新增 `GET /web/admin/project-management/assignments/records`,严格要求 `project:assignment:edit`,仅接受四类正式业务。原 `/records` 继续服务统计明细,不扩展联系信息;移动接口不变。专用服务复用主单租户、软删除、数据权限和归属筛选。关键词支持单号、姓名/电话、医院/专员、渠道/服务订单名称、课题/客户信息(日期使用现有创建日期条件);子表使用同租户未删除记录 EXISTS 匹配,不增加主单行数。分页后批量补充项目、医院、人员、患者和服务订单资料,避免逐行查询。
@@ -20,7 +20,7 @@
## 模块边界 ## 模块边界
新增 models/project_management.py、services/project_management.py、api/project_management.py。现有四种主表(预签约、采集协议、科研捐赠、中试/基础实验申请)增加可空 project_id,不向下游样本表复制归属。不更改已有课题名称 project_title。 新增 models/project_management.py、services/project_management.py、api/project_management.py。现有四种主表(预签约、采集协议、科研捐赠、中试/临床科研申请)增加可空 project_id,不向下游样本表复制归属。不更改已有课题名称 project_title。
项目组包含 teamName、leaderUserId、members[{id?,userId}]、regions[{id?,regionId}]、hospitals[{id?,hospitalId}]、enabled、remark。子行按 sync_child_rows 与自然键更新。负责人应计入可选项目成员判断。项目包含 projectNo、projectName、teamId、leaderUserId、bizTypes[]、startDate、endDate、status(pending/active/completed/disabled)、remark。编号服务端生成。项目已有业务后禁止换组;引用中的项目和组只能停用,不能删除。所有引用租户内校验。 项目组包含 teamName、leaderUserId、members[{id?,userId}]、regions[{id?,regionId}]、hospitals[{id?,hospitalId}]、enabled、remark。子行按 sync_child_rows 与自然键更新。负责人应计入可选项目成员判断。项目包含 projectNo、projectName、teamId、leaderUserId、bizTypes[]、startDate、endDate、status(pending/active/completed/disabled)、remark。编号服务端生成。项目已有业务后禁止换组;引用中的项目和组只能停用,不能删除。所有引用租户内校验。
@@ -61,7 +61,7 @@ project_brief(db, tenant_no, project_id) -> dict # projectId/projectName/teamId
预签约转协议继承归属;存储/捐赠互转继承。归属维护将同租户的预签约→协议→捐赠转换记录组成关联集合,循环防重,锁定顺序固定;任一关联记录不可访问则拒绝整个操作,返回信息不暴露无权查看单据。历史软删除记录不参与活跃统计,不复活。 预签约转协议继承归属;存储/捐赠互转继承。归属维护将同租户的预签约→协议→捐赠转换记录组成关联集合,循环防重,锁定顺序固定;任一关联记录不可访问则拒绝整个操作,返回信息不暴露无权查看单据。历史软删除记录不参与活跃统计,不复活。
正式存储按协议、捐赠按主单、中试和基础实验按对应 biz_type 申请单计数;预签约另列,不把四类数量称为独立客户数。日期按创建日期(起日含、结束日次日不含),状态显示当前状态。查询先按租户、软删除、原有数据权限过滤,再聚合,不联接子行产生重复;金额不在本期。 正式存储按协议、捐赠按主单、中试和临床科研按对应 biz_type 申请单计数;预签约另列,不把四类数量称为独立客户数。日期按创建日期(起日含、结束日次日不含),状态显示当前状态。查询先按租户、软删除、原有数据权限过滤,再聚合,不联接子行产生重复;金额不在本期。
## 界面与验证 ## 界面与验证
@@ -1,7 +1,7 @@
## ADDED Requirements ## ADDED Requirements
### Requirement: 按业务识别历史归属单据 ### Requirement: 按业务识别历史归属单据
历史归属维护 SHALL 按细胞存储、科研捐赠、中试服务、基础实验展示四个 tab,并提供对应业务识别字段和关键词搜索;列表保持主单分页,右侧固定归属与审计操作。 历史归属维护 SHALL 按细胞存储、科研捐赠、中试服务、临床科研展示四个 tab,并提供对应业务识别字段和关键词搜索;列表保持主单分页,右侧固定归属与审计操作。
#### Scenario: 存储和捐赠以样本编码识别 #### Scenario: 存储和捐赠以样本编码识别
- **WHEN** 查看细胞存储或科研捐赠 tab - **WHEN** 查看细胞存储或科研捐赠 tab
- **THEN** 展示样本编码列而非协议单号/捐赠单号列;多个有效编码在同一主单行去重展示,无编码显示破折号,支持按任一编码搜索;跨租户或已删除的样本不用于展示和匹配,分页和归属仍以主单为单位。 - **THEN** 展示样本编码列而非协议单号/捐赠单号列;多个有效编码在同一主单行去重展示,无编码显示破折号,支持按任一编码搜索;跨租户或已删除的样本不用于展示和匹配,分页和归属仍以主单为单位。
@@ -54,7 +54,7 @@ Web SHALL 使用“项目 → 项目管理 → 项目组管理 / 项目管理 /
- **WHEN** 用户打开某项目的某类业务明细 - **WHEN** 用户打开某项目的某类业务明细
- **THEN** 明细总数与相同筛选条件汇总一致,不因子行联接重复计数。 - **THEN** 明细总数与相同筛选条件汇总一致,不因子行联接重复计数。
#### Scenario: 四类统计明细展示业务字段 #### Scenario: 四类统计明细展示业务字段
- **WHEN** 点击细胞存储、科研捐赠、中试服务、基础实验的统计数量 - **WHEN** 点击细胞存储、科研捐赠、中试服务、临床科研的统计数量
- **THEN** 原明细弹窗复用历史归属维护对应 tab 的业务列与关键词能力,存储/捐赠显示样本编码,保留汇总传入的筛选条件和只读权限,不显示归属维护操作;预签约仍沿用原行为。 - **THEN** 原明细弹窗复用历史归属维护对应 tab 的业务列与关键词能力,存储/捐赠显示样本编码,保留汇总传入的筛选条件和只读权限,不显示归属维护操作;预签约仍沿用原行为。
### Requirement: 沿用现有界面样式 ### Requirement: 沿用现有界面样式
+44 -2
View File
@@ -56,9 +56,9 @@ export interface ProductionWorkOrderItem {
/** 出库工单:输注计划总次数 */ /** 出库工单:输注计划总次数 */
totalCourseCount?: number | null totalCourseCount?: number | null
infusionTime?: string infusionTime?: string
/** 基础实验出库:课题名称(列表 enrich) */ /** 临床科研出库:课题名称(列表 enrich) */
projectTitle?: string projectTitle?: string
/** 基础实验出库:客户名称(列表 enrich) */ /** 临床科研出库:客户名称(列表 enrich) */
customerName?: string customerName?: string
/** 出库工单:输注计划细胞类型(列表 enrich,无产品明细时兜底) */ /** 出库工单:输注计划细胞类型(列表 enrich,无产品明细时兜底) */
cellType?: string cellType?: string
@@ -316,3 +316,45 @@ export function fetchMineProductionWorkOrderTabStepCountsDeduped() {
} }
return mineTabStepCountsInflight return mineTabStepCountsInflight
} }
/** 临床科研出库工单 — 交付出库细胞 */
export type ProductionDeliveryCellOutbound = {
workOrderId?: string
workOrderNo?: string
infusionScheduleId?: string
scheduleSummary?: {
applicationNo?: string
patientName?: string
infusionTime?: string
projectTitle?: string
customerName?: string
}
cells?: Array<{
cellProductId?: string
productCode?: string
productName?: string
productTypeName?: string
specName?: string
passage?: string
batchNo?: string
storageSlotName?: string
productStatus?: string
remark?: string
}>
}
export function fetchProductionDeliveryCellOutbound(workOrderId: string) {
return request.get<ProductionDeliveryCellOutbound>({
url: `/web/admin/production-work-orders/${workOrderId}/delivery-cell-outbound`
})
}
export function saveProductionDeliveryCellOutbound(
workOrderId: string,
data: { cells: Array<{ cellProductId: string; remark?: string }> }
) {
return request.put<ProductionDeliveryCellOutbound>({
url: `/web/admin/production-work-orders/${workOrderId}/delivery-cell-outbound`,
data
})
}
+1 -1
View File
@@ -10,7 +10,7 @@ export const bizLabels: Record<BizType, string> = {
cell_storage: '细胞存储', cell_storage: '细胞存储',
research_donation: '科研捐赠', research_donation: '科研捐赠',
pilot_service: '中试服务', pilot_service: '中试服务',
basic_experiment: '基础实验' basic_experiment: '临床科研'
} }
export type ProjectOption = { export type ProjectOption = {
id: string id: string
+37
View File
@@ -51,6 +51,7 @@ export function fetchCompleteTaskWithResult(
remark?: string remark?: string
thirdPartyAttachments?: string thirdPartyAttachments?: string
taskStatus?: 'dzx' | 'jxz' | 'ywc' taskStatus?: 'dzx' | 'jxz' | 'ywc'
operateBatchId?: string
materialUsages?: Array<{ materialUsages?: Array<{
requisitionUsageId: string requisitionUsageId: string
qty: number qty: number
@@ -66,3 +67,39 @@ export function fetchCompleteTaskWithResult(
data data
}) })
} }
export type QcTaskResultChangeItem = {
fieldKey: string
fieldLabel: string
oldValue: string
newValue: string
}
export type QcTaskResultChangeLog = {
id: string
taskId: string
workOrderId?: string
sampleCode?: string
itemName?: string
operateTime: string
operatorUserId?: string
operatorUserName?: string
operateBatchId?: string
hasFieldChange: boolean
changes: QcTaskResultChangeItem[]
createTime?: string
}
export function fetchQcTaskResultChangeLogs(taskId: string) {
return request.get<QcTaskResultChangeLog[]>({
url: `/web/admin/qc-tasks/${taskId}/result-change-logs`
})
}
export function fetchQcTaskResultChangeLogsBatch(taskIds: string[]) {
const ids = taskIds.map((x) => (x || '').trim()).filter(Boolean)
return request.get<QcTaskResultChangeLog[]>({
url: `/web/admin/qc-tasks/result-change-logs`,
params: { taskIds: ids.join(',') }
})
}
+2
View File
@@ -170,6 +170,8 @@ export function fetchMyQcTaskList(params?: {
qcBizType?: string qcBizType?: string
receptionSource?: string receptionSource?: string
bizType?: string bizType?: string
/** 科研捐赠:协议/捐赠状态,多个逗号分隔;空串=不限制 */
protocolStatus?: string
}) { }) {
return request.get<PageList<QcTask>>({ return request.get<PageList<QcTask>>({
url: '/web/admin/qc-tasks/mine', url: '/web/admin/qc-tasks/mine',
Binary file not shown.

After

Width:  |  Height:  |  Size: 95 KiB

+1 -1
View File
@@ -751,7 +751,7 @@ body {
} }
} }
// 面板级步骤胶囊 Tab(样本信息管理 / 采集协议单 / 中试·基础实验申请单等) // 面板级步骤胶囊 Tab(样本信息管理 / 采集协议单 / 中试·临床科研申请单等)
.pill-tab-nav { .pill-tab-nav {
padding: 16px 20px 0; padding: 16px 20px 0;
display: flex; display: flex;
@@ -4,10 +4,16 @@
<div class="outbound-material-form-sections"> <div class="outbound-material-form-sections">
<div class="material-sections"> <div class="material-sections">
<!-- 出库细胞 --> <!-- 出库细胞 -->
<section class="section-card"> <section v-if="showCells" class="section-card">
<div class="section-head"> <div class="section-head">
<h3 class="section-title section-title--mint-bar">出库细胞</h3> <h3 class="section-title section-title--mint-bar">出库细胞</h3>
<el-button type="primary" size="small" class="btn-main" @click="openCellSelect"> <el-button
v-if="!cellsReadonly"
type="primary"
size="small"
class="btn-main"
@click="openCellSelect"
>
<el-icon><Plus /></el-icon> <el-icon><Plus /></el-icon>
添加细胞产品 添加细胞产品
</el-button> </el-button>
@@ -18,7 +24,7 @@
class="list-table inner-table" class="list-table inner-table"
stripe stripe
max-height="280" max-height="280"
empty-text="请从细胞产品库勾选" :empty-text="cellsReadonly ? '暂无生产确认的出库细胞' : '请从细胞产品库勾选'"
> >
<el-table-column type="index" label="序号" min-width="56" align="center" /> <el-table-column type="index" label="序号" min-width="56" align="center" />
<el-table-column <el-table-column
@@ -56,7 +62,13 @@
<span v-else>—</span> <span v-else>—</span>
</template> </template>
</el-table-column> </el-table-column>
<el-table-column label="操作" min-width="80" align="center" fixed="right"> <el-table-column
v-if="!cellsReadonly"
label="操作"
min-width="80"
align="center"
fixed="right"
>
<template #default="{ $index }"> <template #default="{ $index }">
<el-button type="danger" link size="small" @click="removeCellRow($index)"> <el-button type="danger" link size="small" @click="removeCellRow($index)">
<el-icon><Delete /></el-icon> <el-icon><Delete /></el-icon>
@@ -69,7 +81,7 @@
</section> </section>
<!-- 使用的物料 --> <!-- 使用的物料 -->
<section class="section-card"> <section v-if="showMaterials" class="section-card">
<div class="section-head"> <div class="section-head">
<h3 class="section-title section-title--mint-bar">使用的物料</h3> <h3 class="section-title section-title--mint-bar">使用的物料</h3>
<el-button type="primary" size="small" class="btn-main" @click="addMaterialRow"> <el-button type="primary" size="small" class="btn-main" @click="addMaterialRow">
@@ -145,7 +157,7 @@
</section> </section>
<!-- 纸质材料 --> <!-- 纸质材料 -->
<section class="section-card"> <section v-if="showPapers" class="section-card">
<div class="section-head"> <div class="section-head">
<h3 class="section-title section-title--mint-bar">纸质材料</h3> <h3 class="section-title section-title--mint-bar">纸质材料</h3>
<el-button type="primary" size="small" class="btn-main" @click="addPaperRow"> <el-button type="primary" size="small" class="btn-main" @click="addPaperRow">
@@ -289,7 +301,7 @@
<p v-else class="section-empty-hint">点击「添加纸质材料」逐条填写名称、份数并上传附件;仅作台账留存,不扣库存</p> <p v-else class="section-empty-hint">点击「添加纸质材料」逐条填写名称、份数并上传附件;仅作台账留存,不扣库存</p>
</section> </section>
<el-form label-position="top" class="biz-dialog-form"> <el-form v-if="showRemark" label-position="top" class="biz-dialog-form">
<el-form-item label="备注"> <el-form-item label="备注">
<el-input <el-input
v-model="formRemark" v-model="formRemark"
@@ -424,9 +436,20 @@
defineProps<{ defineProps<{
/** 出库交接等需扣库存场景:仅允许选择已冻存细胞,且已选行保留可选 */ /** 出库交接等需扣库存场景:仅允许选择已冻存细胞,且已选行保留可选 */
requireFrozenCellProduct?: boolean requireFrozenCellProduct?: boolean
/** 临床科研市场交接:细胞由生产确认,仅只读展示 */
cellsReadonly?: boolean
showCells?: boolean
showMaterials?: boolean
showPapers?: boolean
showRemark?: boolean
}>(), }>(),
{ {
requireFrozenCellProduct: false requireFrozenCellProduct: false,
cellsReadonly: false,
showCells: true,
showMaterials: true,
showPapers: true,
showRemark: true
} }
) )
@@ -785,34 +808,38 @@
} }
function validateMaterial() { function validateMaterial() {
if (paperRows.value.some((r) => r._uploading)) { if (props.showPapers && paperRows.value.some((r) => r._uploading)) {
ElMessage.warning('纸质材料附件上传中,请稍候') ElMessage.warning('纸质材料附件上传中,请稍候')
return false return false
} }
for (const row of materialRows.value) { if (props.showMaterials) {
if (!row.materialId) { for (const row of materialRows.value) {
ElMessage.warning('请为每条物料选择名称') if (!row.materialId) {
return false ElMessage.warning('请为每条物料选择名称')
} return false
const qty = row.qty }
if (qty == null || !Number.isFinite(Number(qty)) || Number(qty) <= 0) { const qty = row.qty
ElMessage.warning('物料计划用量须大于 0') if (qty == null || !Number.isFinite(Number(qty)) || Number(qty) <= 0) {
return false ElMessage.warning('物料计划用量须大于 0')
return false
}
} }
} }
for (const row of paperRows.value) { if (props.showPapers) {
if (!row.paperName?.trim()) { for (const row of paperRows.value) {
ElMessage.warning('请填写每条纸质材料的名称') if (!row.paperName?.trim()) {
return false ElMessage.warning('请填写每条纸质材料的名称')
} return false
const copies = row.copies }
if (copies == null || !Number.isFinite(Number(copies)) || Number(copies) <= 0) { const copies = row.copies
ElMessage.warning('纸质材料份数须大于 0') if (copies == null || !Number.isFinite(Number(copies)) || Number(copies) <= 0) {
return false ElMessage.warning('纸质材料份数须大于 0')
} return false
if (!row.attachments.length) { }
ElMessage.warning('请为每条纸质材料上传附件') if (!row.attachments.length) {
return false ElMessage.warning('请为每条纸质材料上传附件')
return false
}
} }
} }
return true return true
+2 -2
View File
@@ -60,9 +60,9 @@ export const PILOT_BIZ_TYPE_CONFIG: Record<PilotBizType, PilotBizTypeConfig> = {
statusLabel: '输注状态' statusLabel: '输注状态'
}, },
basic_experiment: { basic_experiment: {
label: '基础实验', label: '临床科研',
applicationNoPrefix: 'JCSY', applicationNoPrefix: 'JCSY',
showChannel: false, showChannel: true,
showPatient: false, showPatient: false,
showConsent: false, showConsent: false,
showOtherAttachments: false, showOtherAttachments: false,
@@ -0,0 +1,18 @@
/** 临床科研申请单 · 业务子类型(researchCategory) */
export const CLINICAL_RESEARCH_CATEGORY_OPTIONS = [
{ value: 'bio_tech_clinical', label: '生物新技术临床科研' },
{ value: 'joint_topic_declare', label: '临床课题联合申报' },
{ value: 'bio_pharma_rd', label: '生物制药研发' }
] as const
export type ClinicalResearchCategory =
(typeof CLINICAL_RESEARCH_CATEGORY_OPTIONS)[number]['value']
const LABEL_MAP = Object.fromEntries(
CLINICAL_RESEARCH_CATEGORY_OPTIONS.map((o) => [o.value, o.label])
) as Record<string, string>
export function clinicalResearchCategoryLabel(code?: string | null): string {
if (!code) return ''
return LABEL_MAP[code] || code
}
+55 -72
View File
@@ -60,8 +60,8 @@ export const sqxpAdminRoutes: AppRouteRecord[] = [
}, },
// ═══════════════════════════════════════════════════════════════════════════ // ═══════════════════════════════════════════════════════════════════════════
// 1. 市场 (menu:market) // 1. 市场 (menu:market)
// 二级菜单:存储服务、科研捐赠、市场基础信息、中试服务、基础实验 // 二级菜单:存储服务、科研捐赠、市场基础信息、临床科研、器械销售
// (主推存储/捐赠在前;中试/基础实验及关联基础信息后置) // (主推存储/捐赠在前;中试/临床科研及关联基础信息后置;器械销售在末位)
// ═══════════════════════════════════════════════════════════════════════════ // ═══════════════════════════════════════════════════════════════════════════
{ {
id: 'TOP00000000000000000000000000001', id: 'TOP00000000000000000000000000001',
@@ -329,7 +329,7 @@ export const sqxpAdminRoutes: AppRouteRecord[] = [
] ]
}, },
// ── 市场基础信息(前段:存储/捐赠相关;后段:中试/基础实验相关)── // ── 市场基础信息(前段:存储/捐赠相关;后段:中试/临床科研相关)──
{ {
id: 'MKT00000000000000000000000000001', id: 'MKT00000000000000000000000000001',
name: 'MarketInfo', name: 'MarketInfo',
@@ -553,80 +553,14 @@ export const sqxpAdminRoutes: AppRouteRecord[] = [
] ]
}, },
// ── 中试服务 ────────────────────────────────────────────────────────── // ── 临床科研 ──────────────────────────────────────────────────────────
{
id: 'PIL00000000000000000000000000001',
name: 'PilotService',
path: 'pilot-service',
component: '',
meta: {
title: '中试服务',
icon: 'ri:flask-line',
keepAlive: false,
roles: ['admin']
},
children: [
{
id: '80000000000000000000000000000010',
name: 'PilotApplication',
path: 'pilot-application',
component: '/pilot-service/pilot-application/index',
meta: {
title: '中试服务申请单',
keepAlive: true,
menuCode: 'pilot-service:pilot-application:list'
},
props: { bizType: 'pilot_service' }
},
{
id: 'PIL00000000000000000000000000002',
name: 'PilotCheckupManagement',
path: 'checkup-management',
component: '/pilot-service/checkup-management/index',
meta: {
title: '体检管理',
keepAlive: false,
isHide: true,
menuCode: 'pilot-service:checkup-management:list'
},
props: { bizType: 'pilot_service' }
},
{
id: 'PIL00000000000000000000000000003',
name: 'PilotInfusionSchedule',
path: 'infusion-schedule-management',
component: '/pilot-service/infusion-schedule-management/index',
meta: {
title: '输注计划管理',
keepAlive: false,
isHide: true,
menuCode: 'pilot-service:infusion-schedule-management:list'
},
props: { bizType: 'pilot_service' }
},
{
id: 'PIL00000000000000000000000000004',
name: 'PilotOutboundRelease',
path: 'outbound-release-review',
component: '/pilot-service/outbound-release-review/index',
meta: {
title: '出库放行审核',
keepAlive: true,
menuCode: 'pilot-service:outbound-release-review:list'
},
props: { bizType: 'pilot_service' }
}
]
},
// ── 基础实验 ──────────────────────────────────────────────────────────
{ {
id: 'BEX00000000000000000000000000001', id: 'BEX00000000000000000000000000001',
name: 'BasicExperiment', name: 'BasicExperiment',
path: 'basic-experiment', path: 'basic-experiment',
component: '', component: '',
meta: { meta: {
title: '基础实验', title: '临床科研',
icon: 'ri:flask-line', icon: 'ri:flask-line',
keepAlive: false, keepAlive: false,
roles: ['admin'] roles: ['admin']
@@ -638,7 +572,7 @@ export const sqxpAdminRoutes: AppRouteRecord[] = [
path: 'application', path: 'application',
component: '/pilot-service/pilot-application/index', component: '/pilot-service/pilot-application/index',
meta: { meta: {
title: '基础实验申请单', title: '临床科研申请单',
keepAlive: true, keepAlive: true,
menuCode: 'basic-experiment:application:list' menuCode: 'basic-experiment:application:list'
}, },
@@ -669,6 +603,55 @@ export const sqxpAdminRoutes: AppRouteRecord[] = [
props: { bizType: 'basic_experiment' } props: { bizType: 'basic_experiment' }
} }
] ]
},
// ── 器械销售(市场侧栏末位;占位页待完善)────────────────────────────
{
id: 'DEV00000000000000000000000000001',
name: 'DeviceSales',
path: 'device-sales',
component: '',
meta: {
title: '器械销售',
icon: 'ri:shopping-bag-3-line',
keepAlive: false,
roles: ['admin']
},
children: [
{
id: 'DEV00000000000000000000000000002',
name: 'DeviceSalesClassIii',
path: 'class-iii',
component: '/device-sales/under-construction/index',
meta: {
title: '三类医疗器械',
keepAlive: false,
menuCode: 'device-sales:class-iii:list'
}
},
{
id: 'DEV00000000000000000000000000003',
name: 'DeviceSalesClassIi',
path: 'class-ii',
component: '/device-sales/under-construction/index',
meta: {
title: '二类医疗器械',
keepAlive: false,
menuCode: 'device-sales:class-ii:list'
}
},
{
id: 'DEV00000000000000000000000000004',
name: 'DeviceSalesCosmetics',
path: 'cosmetics',
component: '/device-sales/under-construction/index',
meta: {
title: '化妆品产品',
keepAlive: false,
menuCode: 'device-sales:cosmetics:list'
}
}
]
} }
] ]
}, },
@@ -25,7 +25,7 @@ describe('donation protocol status filter helpers', () => {
it('matchesProtocolStatusFilter semantics', () => { it('matchesProtocolStatusFilter semantics', () => {
assert.equal(matchesProtocolStatusFilter('yzf', undefined), true) assert.equal(matchesProtocolStatusFilter('yzf', undefined), true)
assert.equal(matchesProtocolStatusFilter('yzf', []), false) assert.equal(matchesProtocolStatusFilter('yzf', []), true)
assert.equal(matchesProtocolStatusFilter('sxz', ['dsx', 'sxz']), true) assert.equal(matchesProtocolStatusFilter('sxz', ['dsx', 'sxz']), true)
assert.equal(matchesProtocolStatusFilter('yzf', ['dsx', 'sxz']), false) assert.equal(matchesProtocolStatusFilter('yzf', ['dsx', 'sxz']), false)
assert.equal(matchesProtocolStatusFilter('', ['dsx']), false) assert.equal(matchesProtocolStatusFilter('', ['dsx']), false)
@@ -18,7 +18,7 @@ export const DEFAULT_DONATION_PROTOCOL_STATUS_FILTER = ['dsx', 'sxz']
/** /**
* 拼协议状态查询参数。 * 拼协议状态查询参数。
* - 有选中:逗号串 * - 有选中:逗号串
* - 空数组:返回 ''(显式空;勿当 undefined) * - 空数组:返回 ''(显式空=不限制;勿当 undefined,undefined 会走后端默认勾选)
*/ */
export function joinProtocolStatusFilter(statuses: string[]): string { export function joinProtocolStatusFilter(statuses: string[]): string {
return statuses.map((s) => s.trim()).filter(Boolean).join(',') return statuses.map((s) => s.trim()).filter(Boolean).join(',')
@@ -27,13 +27,12 @@ export function joinProtocolStatusFilter(statuses: string[]): string {
/** /**
* 协议状态是否命中筛选。 * 协议状态是否命中筛选。
* - filter === undefined:不限制 * - filter === undefined:不限制
* - filter 为空数组:无匹配 * - filter 为空数组:不限制(显式清空)
*/ */
export function matchesProtocolStatusFilter( export function matchesProtocolStatusFilter(
status: string, status: string,
filter: string[] | undefined filter: string[] | undefined
): boolean { ): boolean {
if (filter === undefined) return true if (filter === undefined || !filter.length) return true
if (!filter.length) return false
return filter.includes((status || '').trim()) return filter.includes((status || '').trim())
} }
@@ -32,7 +32,7 @@ const SECTION_TITLES: Record<
schedule: '临床应用输注计划信息' schedule: '临床应用输注计划信息'
}, },
basic_experiment: { basic_experiment: {
application: '基础实验申请信息', application: '临床科研申请信息',
schedule: '交付计划信息' schedule: '交付计划信息'
} }
} }
@@ -6,7 +6,8 @@ import {
resolveTabKeyFromWorkOrder, resolveTabKeyFromWorkOrder,
getProductionWorkOrderTab, getProductionWorkOrderTab,
toWorkOrderListQuery, toWorkOrderListQuery,
isAllProductionWorkOrderTab isAllProductionWorkOrderTab,
workOrderMatchesTab
} from '@/utils/production-work-order-tabs' } from '@/utils/production-work-order-tabs'
import { toAllTabListQuery, workOrderMatchesCategory } from '@/utils/production-work-order-category' import { toAllTabListQuery, workOrderMatchesCategory } from '@/utils/production-work-order-category'
import { matchesWorkOrderStatusFilter } from '@/utils/status-tag-registry' import { matchesWorkOrderStatusFilter } from '@/utils/status-tag-registry'
@@ -231,9 +232,7 @@ export function filterMineEntriesByWorkOrderSearch(
const tabKey = filters.tabKey const tabKey = filters.tabKey
return entries.filter((entry) => { return entries.filter((entry) => {
const row = entry.workOrder const row = entry.workOrder
if (!isAllProductionWorkOrderTab(tabKey) && resolveTabKeyFromWorkOrder(row) !== tabKey) { if (!workOrderMatchesTab(row, tabKey)) return false
return false
}
if ( if (
isAllProductionWorkOrderTab(tabKey) && isAllProductionWorkOrderTab(tabKey) &&
!workOrderMatchesCategory(row, filters.productionCategory || '') !workOrderMatchesCategory(row, filters.productionCategory || '')
@@ -25,7 +25,7 @@ const CATEGORY_LABELS: Record<ProductionWorkOrderCategoryKey, string> = {
inbound_cell_storage: '细胞存储', inbound_cell_storage: '细胞存储',
inbound_research_donation: '科研捐赠', inbound_research_donation: '科研捐赠',
outbound_pilot_service: '中试服务', outbound_pilot_service: '中试服务',
outbound_basic_experiment: '基础实验', outbound_basic_experiment: '临床科研',
temporary: '临时' temporary: '临时'
} }
@@ -0,0 +1,32 @@
import { describe, it } from 'node:test'
import assert from 'node:assert/strict'
import {
PRODUCTION_WORK_ORDER_VISIBLE_TABS,
parseProductionWorkOrderTabKey,
workOrderMatchesTab,
isPilotServiceOutboundWorkOrder
} from './production-work-order-tabs'
import { PRODUCTION_WORK_ORDER_CATEGORY_OPTIONS } from './production-work-order-category'
describe('production work order tabs — hide pilot service', () => {
it('visible tabs exclude outbound_pilot_service', () => {
assert.ok(!PRODUCTION_WORK_ORDER_VISIBLE_TABS.some((t) => t.key === 'outbound_pilot_service'))
assert.ok(!PRODUCTION_WORK_ORDER_CATEGORY_OPTIONS.some((o) => o.key === 'outbound_pilot_service'))
})
it('parse: hidden pilot key and outbound alias fall back safely', () => {
assert.equal(parseProductionWorkOrderTabKey('outbound_pilot_service'), 'all')
assert.equal(parseProductionWorkOrderTabKey('outbound'), 'outbound_basic_experiment')
})
it('「所有」excludes pilot outbound (incl. default bizType)', () => {
const pilot = { workOrderType: 'outbound', bizType: 'pilot_service' }
const defaultPilot = { workOrderType: 'outbound' }
const basic = { workOrderType: 'outbound', bizType: 'basic_experiment' }
assert.equal(isPilotServiceOutboundWorkOrder(pilot), true)
assert.equal(isPilotServiceOutboundWorkOrder(defaultPilot), true)
assert.equal(workOrderMatchesTab(pilot as any, 'all'), false)
assert.equal(workOrderMatchesTab(defaultPilot as any, 'all'), false)
assert.equal(workOrderMatchesTab(basic as any, 'all'), true)
})
})
@@ -53,11 +53,13 @@ export const PRODUCTION_WORK_ORDER_TABS: ProductionWorkOrderTabConfig[] = [
group: 'outbound', group: 'outbound',
workOrderType: 'outbound', workOrderType: 'outbound',
bizType: 'pilot_service', bizType: 'pilot_service',
listLayout: 'standalone' listLayout: 'standalone',
/** 客户已下线中试业务:侧栏不展示,路由 key 保留供历史解析 */
hidden: true
}, },
{ {
key: 'outbound_basic_experiment', key: 'outbound_basic_experiment',
label: '基础实验生产', label: '临床科研生产',
group: 'outbound', group: 'outbound',
workOrderType: 'outbound', workOrderType: 'outbound',
bizType: 'basic_experiment', bizType: 'basic_experiment',
@@ -97,7 +99,7 @@ export function parseProductionWorkOrderTabKey(raw?: string | null): ProductionW
const tab = getProductionWorkOrderTab(k) const tab = getProductionWorkOrderTab(k)
if (tab && !tab.hidden) return tab.key if (tab && !tab.hidden) return tab.key
if (k === 'inbound') return 'inbound_cell_storage' if (k === 'inbound') return 'inbound_cell_storage'
if (k === 'outbound') return 'outbound_pilot_service' if (k === 'outbound') return 'outbound_basic_experiment'
if (k === 'temporary') return 'temporary' if (k === 'temporary') return 'temporary'
return DEFAULT_PRODUCTION_WORK_ORDER_TAB return DEFAULT_PRODUCTION_WORK_ORDER_TAB
} }
@@ -145,11 +147,19 @@ export function keywordPlaceholderForTab(tab: ProductionWorkOrderTabConfig): str
return '工单号/样本编码/入库编码' return '工单号/样本编码/入库编码'
} }
/** 出库中试服务(含 bizType 缺省落成中试) */
export function isPilotServiceOutboundWorkOrder(row: {
workOrderType?: string
bizType?: string
}): boolean {
return resolveTabKeyFromWorkOrder(row) === 'outbound_pilot_service'
}
export function workOrderMatchesTab( export function workOrderMatchesTab(
row: ProductionWorkOrderItem, row: ProductionWorkOrderItem,
tabKey: ProductionWorkOrderTabKey tabKey: ProductionWorkOrderTabKey
): boolean { ): boolean {
if (tabKey === 'all') return true if (tabKey === 'all') return !isPilotServiceOutboundWorkOrder(row)
return resolveTabKeyFromWorkOrder(row) === tabKey return resolveTabKeyFromWorkOrder(row) === tabKey
} }
+18
View File
@@ -1,5 +1,23 @@
import type { BizType, ProjectRecord } from '@/api/project-management' import type { BizType, ProjectRecord } from '@/api/project-management'
/**
* 项目新建/编辑弹窗「业务类型」选项。
* 中试服务已下线:默认不可选;若旧项目已含 pilot_service 则保留展示。
*/
export function projectBizTypeSelectLabels(
allLabels: Record<string, string>,
selectedBizTypes?: string[] | null
): Record<string, string> {
const selected = new Set((selectedBizTypes || []).filter(Boolean))
return Object.fromEntries(
Object.entries(allLabels).filter(([key]) => {
if (key === 'presign') return false
if (key === 'pilot_service') return selected.has('pilot_service')
return true
})
)
}
/** Drill-down uses the last successful statistics query, never unsaved filter edits. */ /** Drill-down uses the last successful statistics query, never unsaved filter edits. */
export function buildDrillFilters( export function buildDrillFilters(
applied: ProjectRecord, applied: ProjectRecord,
+10 -6
View File
@@ -10,7 +10,8 @@ import {
tabUsesInfusionTimeFilter, tabUsesInfusionTimeFilter,
getQcWorkOrderTab, getQcWorkOrderTab,
toWorkOrderListQuery, toWorkOrderListQuery,
isAllQcWorkOrderTab isAllQcWorkOrderTab,
workOrderMatchesTab
} from '@/utils/qc-work-order-tabs' } from '@/utils/qc-work-order-tabs'
import { import {
matchesAllTabTriggerSource, matchesAllTabTriggerSource,
@@ -26,13 +27,15 @@ export type QcTaskMineFilters = {
keyword?: string keyword?: string
taskType?: string taskType?: string
taskStatus?: string taskStatus?: string
/** 科研捐赠:协议状态逗号串;''=不限制;缺省不传 */
protocolStatus?: string
tabKey: QcWorkOrderTabKey tabKey: QcWorkOrderTabKey
} }
export type MineWorkOrderSearchFilters = { export type MineWorkOrderSearchFilters = {
keyword?: string keyword?: string
workOrderStatus?: string | string[] workOrderStatus?: string | string[]
/** 科研捐赠 Tab:协议/捐赠状态多选;undefined=不限制;[]=无匹配 */ /** 科研捐赠 Tab:协议/捐赠状态多选;undefined/[]=不限制 */
protocolStatus?: string[] protocolStatus?: string[]
triggerSource?: string triggerSource?: string
qcCategory?: string qcCategory?: string
@@ -101,9 +104,7 @@ export function filterMineEntriesByWorkOrderSearch(
const tab = getQcWorkOrderTab(tabKey)! const tab = getQcWorkOrderTab(tabKey)!
return entries.filter((entry) => { return entries.filter((entry) => {
const row = entry.workOrder const row = entry.workOrder
if (!isAllQcWorkOrderTab(tabKey) && resolveTabKeyFromWorkOrder(row) !== tabKey) { if (!workOrderMatchesTab(row, tabKey)) return false
return false
}
if (isAllQcWorkOrderTab(tabKey) && !workOrderMatchesCategory(row, filters.qcCategory || '')) { if (isAllQcWorkOrderTab(tabKey) && !workOrderMatchesCategory(row, filters.qcCategory || '')) {
return false return false
} }
@@ -146,6 +147,8 @@ export async function fetchAllMineTasks(filters: QcTaskMineFilters): Promise<QcT
let page = 1 let page = 1
const all: QcTask[] = [] const all: QcTask[] = []
let total = 0 let total = 0
const protocolStatusParam =
filters.tabKey === 'inbound_research_donation' ? (filters.protocolStatus ?? '') : undefined
while (true) { while (true) {
const res = await fetchMyQcTaskList({ const res = await fetchMyQcTaskList({
page, page,
@@ -155,7 +158,8 @@ export async function fetchAllMineTasks(filters: QcTaskMineFilters): Promise<QcT
taskStatus: filters.taskStatus || undefined, taskStatus: filters.taskStatus || undefined,
qcBizType: listQuery.workOrderType, qcBizType: listQuery.workOrderType,
receptionSource: listQuery.receptionSource, receptionSource: listQuery.receptionSource,
bizType: listQuery.bizType bizType: listQuery.bizType,
...(protocolStatusParam !== undefined ? { protocolStatus: protocolStatusParam } : {})
}) })
const list = res.list || [] const list = res.list || []
all.push(...list) all.push(...list)
@@ -0,0 +1,43 @@
/** 填写检测结果弹窗默认值(Issue #148):未落结论时默认已完成 + 通过 */
export type QcResultFillStatus = 'dzx' | 'jxz' | 'ywc'
export type QcResultFillConclusion = '' | 'tg' | 'btg'
export function normalizeFillConclusion(raw?: string | null): QcResultFillConclusion {
const c = (raw || '').trim()
return c === 'tg' || c === 'btg' ? c : ''
}
/**
* 打开填写弹窗时的任务状态 / 结论默认。
* - 已有结论或已是已完成:回显实际值
* - 尚未落结论:默认 已完成 + 通过
*/
export function resolveQcResultFillDefaults(input: {
taskStatus?: string | null
conclusion?: string | null
}): { saveStatus: QcResultFillStatus; conclusion: QcResultFillConclusion } {
const status = (input.taskStatus || '').trim()
const conclusion = normalizeFillConclusion(input.conclusion)
if (conclusion || status === 'ywc') {
const saveStatus: QcResultFillStatus =
status === 'dzx' || status === 'jxz' || status === 'ywc' ? status : 'ywc'
return {
saveStatus: saveStatus === 'ywc' ? 'ywc' : saveStatus,
conclusion: conclusion || (saveStatus === 'ywc' ? 'tg' : '')
}
}
return { saveStatus: 'ywc', conclusion: 'tg' }
}
/** 第三方弹窗仅展示待执行/已完成 */
export function resolveThirdPartyFillDefaults(input: {
taskStatus?: string | null
conclusion?: string | null
}): { saveStatus: 'dzx' | 'ywc'; conclusion: QcResultFillConclusion } {
const resolved = resolveQcResultFillDefaults(input)
return {
saveStatus: resolved.saveStatus === 'ywc' ? 'ywc' : 'dzx',
conclusion: resolved.conclusion
}
}
@@ -24,7 +24,7 @@ const CATEGORY_LABELS: Record<QcWorkOrderCategoryKey, string> = {
inbound_cell_storage: '细胞存储', inbound_cell_storage: '细胞存储',
inbound_research_donation: '科研捐赠', inbound_research_donation: '科研捐赠',
outbound_pilot_service: '中试服务', outbound_pilot_service: '中试服务',
outbound_basic_experiment: '基础实验', outbound_basic_experiment: '临床科研',
temporary: '临时' temporary: '临时'
} }
@@ -0,0 +1,33 @@
import { describe, it } from 'node:test'
import assert from 'node:assert/strict'
import {
QC_WORK_ORDER_VISIBLE_TABS,
parseQcWorkOrderTabKey,
workOrderMatchesTab,
isPilotServiceOutboundWorkOrder
} from './qc-work-order-tabs'
import { QC_WORK_ORDER_CATEGORY_OPTIONS } from './qc-work-order-category'
describe('qc work order tabs — hide pilot service', () => {
it('visible tabs exclude outbound_pilot_service', () => {
assert.ok(!QC_WORK_ORDER_VISIBLE_TABS.some((t) => t.key === 'outbound_pilot_service'))
assert.ok(!QC_WORK_ORDER_CATEGORY_OPTIONS.some((o) => o.key === 'outbound_pilot_service'))
})
it('parse: hidden pilot key and outbound alias fall back safely', () => {
// 质检默认 Tab 为细胞存储(「所有」本身也是 hidden)
assert.equal(parseQcWorkOrderTabKey('outbound_pilot_service'), 'inbound_cell_storage')
assert.equal(parseQcWorkOrderTabKey('outbound'), 'outbound_basic_experiment')
})
it('「所有」excludes pilot outbound (incl. default bizType)', () => {
const pilot = { workOrderType: 'outbound', bizType: 'pilot_service' }
const defaultPilot = { workOrderType: 'outbound' }
const basic = { workOrderType: 'outbound', bizType: 'basic_experiment' }
assert.equal(isPilotServiceOutboundWorkOrder(pilot), true)
assert.equal(isPilotServiceOutboundWorkOrder(defaultPilot), true)
assert.equal(workOrderMatchesTab(pilot as any, 'all'), false)
assert.equal(workOrderMatchesTab(defaultPilot as any, 'all'), false)
assert.equal(workOrderMatchesTab(basic as any, 'all'), true)
})
})
+14 -4
View File
@@ -53,11 +53,13 @@ export const QC_WORK_ORDER_TABS: QcWorkOrderTabConfig[] = [
group: 'outbound', group: 'outbound',
workOrderType: 'outbound', workOrderType: 'outbound',
bizType: 'pilot_service', bizType: 'pilot_service',
listLayout: 'outbound-grouped' listLayout: 'outbound-grouped',
/** 客户已下线中试业务:侧栏不展示,路由 key 保留供历史解析 */
hidden: true
}, },
{ {
key: 'outbound_basic_experiment', key: 'outbound_basic_experiment',
label: '基础实验质检', label: '临床科研质检',
group: 'outbound', group: 'outbound',
workOrderType: 'outbound', workOrderType: 'outbound',
bizType: 'basic_experiment', bizType: 'basic_experiment',
@@ -95,7 +97,7 @@ export function parseQcWorkOrderTabKey(raw?: string | null): QcWorkOrderTabKey {
const tab = getQcWorkOrderTab(k) const tab = getQcWorkOrderTab(k)
if (tab && !tab.hidden) return tab.key if (tab && !tab.hidden) return tab.key
if (k === 'inbound') return 'inbound_cell_storage' if (k === 'inbound') return 'inbound_cell_storage'
if (k === 'outbound') return 'outbound_pilot_service' if (k === 'outbound') return 'outbound_basic_experiment'
if (k === 'temporary') return 'temporary' if (k === 'temporary') return 'temporary'
return DEFAULT_QC_WORK_ORDER_TAB return DEFAULT_QC_WORK_ORDER_TAB
} }
@@ -160,8 +162,16 @@ export function filterTimeLabelForTab(tab: QcWorkOrderTabConfig): string {
return '创建时间' return '创建时间'
} }
/** 出库中试服务(含 bizType 缺省落成中试) */
export function isPilotServiceOutboundWorkOrder(row: {
workOrderType?: string
bizType?: string
}): boolean {
return resolveTabKeyFromWorkOrder(row) === 'outbound_pilot_service'
}
export function workOrderMatchesTab(row: QcWorkOrder, tabKey: QcWorkOrderTabKey): boolean { export function workOrderMatchesTab(row: QcWorkOrder, tabKey: QcWorkOrderTabKey): boolean {
if (tabKey === 'all') return true if (tabKey === 'all') return !isPilotServiceOutboundWorkOrder(row)
return resolveTabKeyFromWorkOrder(row) === tabKey return resolveTabKeyFromWorkOrder(row) === tabKey
} }
+3 -3
View File
@@ -228,7 +228,7 @@ export const receptionSource: StatusRegistry = {
outbound: { label: '出库', tagType: 'primary' }, outbound: { label: '出库', tagType: 'primary' },
pilot_service: { label: '中试服务', tagType: 'primary' }, pilot_service: { label: '中试服务', tagType: 'primary' },
clinical_application: { label: '临床应用', tagType: 'warning' }, clinical_application: { label: '临床应用', tagType: 'warning' },
basic_experiment: { label: '基础实验', tagType: 'primary' } basic_experiment: { label: '临床科研', tagType: 'primary' }
} }
export const receptionSourceLabel = createLabelGetter(receptionSource) export const receptionSourceLabel = createLabelGetter(receptionSource)
export const receptionSourceTagType = createTagTypeGetter(receptionSource) export const receptionSourceTagType = createTagTypeGetter(receptionSource)
@@ -386,7 +386,7 @@ export const agreementType: StatusRegistry = {
kyxy: { label: '框架协议', tagType: 'primary' }, kyxy: { label: '框架协议', tagType: 'primary' },
zsxy: { label: '中试协议', tagType: 'success' }, zsxy: { label: '中试协议', tagType: 'success' },
lcxy: { label: '临床协议', tagType: 'warning' }, lcxy: { label: '临床协议', tagType: 'warning' },
jcsy: { label: '基础实验', tagType: 'primary' } jcsy: { label: '临床科研', tagType: 'primary' }
} }
export const agreementTypeLabel = createLabelGetter(agreementType) export const agreementTypeLabel = createLabelGetter(agreementType)
export const agreementTypeTagType = createTagTypeGetter(agreementType) export const agreementTypeTagType = createTagTypeGetter(agreementType)
@@ -761,7 +761,7 @@ export function bizTypeLabel(type: string): string {
const map: Record<string, string> = { const map: Record<string, string> = {
pilot_service: '中试服务', pilot_service: '中试服务',
clinical_application: '临床应用', clinical_application: '临床应用',
basic_experiment: '基础实验' basic_experiment: '临床科研'
} }
return map[type] || type || '-' return map[type] || type || '-'
} }
@@ -0,0 +1,63 @@
<!-- 器械销售占位页:施工中 -->
<template>
<div class="page-container under-construction-page">
<section class="panel under-construction-panel">
<img
class="under-construction-img"
src="@/assets/images/common/under-construction.jpg"
alt="正在施工"
/>
<p class="under-construction-title">{{ pageTitle }}</p>
<p class="under-construction-hint">待完善</p>
</section>
</div>
</template>
<script setup lang="ts">
import { computed } from 'vue'
import { useRoute } from 'vue-router'
defineOptions({ name: 'DeviceSalesUnderConstruction' })
const route = useRoute()
const pageTitle = computed(() => String(route.meta?.title || '器械销售'))
</script>
<style scoped lang="scss">
.under-construction-page {
min-height: calc(100vh - 140px);
display: flex;
}
.under-construction-panel {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 12px;
padding: 48px 24px;
text-align: center;
}
.under-construction-img {
width: min(420px, 70vw);
max-height: 280px;
object-fit: contain;
border-radius: 12px;
}
.under-construction-title {
margin: 8px 0 0;
font-size: 16px;
font-weight: 600;
color: #111827;
}
.under-construction-hint {
margin: 0;
font-size: 18px;
font-weight: 600;
color: #10b981;
}
</style>
@@ -31,7 +31,11 @@
</div> </div>
<div v-loading="loading" class="handover-body"> <div v-loading="loading" class="handover-body">
<OutboundMaterialFormSections ref="materialSectionsRef" require-frozen-cell-product /> <OutboundMaterialFormSections
ref="materialSectionsRef"
require-frozen-cell-product
:cells-readonly="isBasicExperiment"
/>
<section class="section-card handover-form-section"> <section class="section-card handover-form-section">
<h3 class="section-title section-title--mint-bar">交接信息</h3> <h3 class="section-title section-title--mint-bar">交接信息</h3>
@@ -264,6 +268,9 @@
const pickupTimeLabel = computed( const pickupTimeLabel = computed(
() => getPilotBizConfig(resolvePilotBizType(props.bizType)).pickupTimeLabel () => getPilotBizConfig(resolvePilotBizType(props.bizType)).pickupTimeLabel
) )
const isBasicExperiment = computed(
() => resolvePilotBizType(props.bizType) === 'basic_experiment'
)
const emit = defineEmits<{ const emit = defineEmits<{
(e: 'update:modelValue', val: boolean): void (e: 'update:modelValue', val: boolean): void
@@ -288,7 +288,7 @@
const contextSections: ViewSection[] = basic const contextSections: ViewSection[] = basic
? [ ? [
{ {
title: '基础实验申请信息', title: '临床科研申请信息',
fields: [ fields: [
{ label: '申请单号', value: app.applicationNo || d.applicationNo || '—' }, { label: '申请单号', value: app.applicationNo || d.applicationNo || '—' },
{ label: '课题名称', value: app.projectTitle || d.projectTitle || '—' }, { label: '课题名称', value: app.projectTitle || d.projectTitle || '—' },
@@ -256,7 +256,7 @@
total: number total: number
selectedIds: string[] selectedIds: string[]
pickupTimeLabel: string pickupTimeLabel: string
/** 中试/临床展示患者;基础实验展示课题与客户 */ /** 中试/临床展示患者;临床科研展示课题与客户 */
showPatient?: boolean showPatient?: boolean
bizType?: string bizType?: string
}>() }>()
@@ -71,6 +71,39 @@
/> />
</el-form-item> </el-form-item>
<template v-if="isBasicExperiment"> <template v-if="isBasicExperiment">
<el-form-item label="业务类型" prop="researchCategory">
<el-select
v-model="formData.researchCategory"
class="w-full"
clearable
placeholder="请选择业务类型"
>
<el-option
v-for="opt in clinicalResearchCategoryOptions"
:key="opt.value"
:label="opt.label"
:value="opt.value"
/>
</el-select>
</el-form-item>
<el-form-item label="渠道" prop="channelId">
<el-select
v-model="formData.channelId"
class="w-full"
filterable
clearable
placeholder="请选择渠道"
:loading="channelLoading"
@change="onChannelChange"
>
<el-option
v-for="ch in channelOptions"
:key="ch.id"
:label="ch.channelName"
:value="ch.id"
/>
</el-select>
</el-form-item>
<el-form-item label="课题名称" prop="projectTitle"> <el-form-item label="课题名称" prop="projectTitle">
<el-input v-model="formData.projectTitle" placeholder="请输入课题名称" /> <el-input v-model="formData.projectTitle" placeholder="请输入课题名称" />
</el-form-item> </el-form-item>
@@ -92,7 +125,11 @@
/> />
</el-form-item> </el-form-item>
</template> </template>
<el-form-item v-if="bizConfig.showChannel" label="渠道" prop="channelId"> <el-form-item
v-if="bizConfig.showChannel && !isBasicExperiment"
label="渠道"
prop="channelId"
>
<el-select <el-select
v-model="formData.channelId" v-model="formData.channelId"
class="w-full" class="w-full"
@@ -1284,9 +1321,12 @@
} from '@/utils/status-tag-registry' } from '@/utils/status-tag-registry'
import { formatMoneyDisplay } from '@/utils/money-format' import { formatMoneyDisplay } from '@/utils/money-format'
import { getPilotBizConfig } from '@/config/pilot-biz-type' import { getPilotBizConfig } from '@/config/pilot-biz-type'
import { CLINICAL_RESEARCH_CATEGORY_OPTIONS } from '@/constants/clinical-research-category'
defineOptions({ name: 'ApplicationFormDialog' }) defineOptions({ name: 'ApplicationFormDialog' })
const clinicalResearchCategoryOptions = CLINICAL_RESEARCH_CATEGORY_OPTIONS
const props = defineProps<{ const props = defineProps<{
modelValue: boolean modelValue: boolean
editId: string | null editId: string | null
@@ -1342,7 +1382,8 @@
projectTitle: '', projectTitle: '',
customerName: '', customerName: '',
customerContact: '', customerContact: '',
customerPhone: '' customerPhone: '',
researchCategory: ''
}) })
type SaleProductLine = { type SaleProductLine = {
@@ -1371,6 +1412,7 @@
channelServiceOrderId: [ channelServiceOrderId: [
{ required: true, message: '请选择服务订单', trigger: 'change' } { required: true, message: '请选择服务订单', trigger: 'change' }
], ],
researchCategory: [{ required: true, message: '请选择业务类型', trigger: 'change' }],
projectTitle: [{ required: true, message: '请填写课题名称', trigger: 'blur' }], projectTitle: [{ required: true, message: '请填写课题名称', trigger: 'blur' }],
customerName: [{ required: true, message: '请填写客户名称', trigger: 'blur' }], customerName: [{ required: true, message: '请填写客户名称', trigger: 'blur' }],
customerContact: [{ required: true, message: '请填写客户联系人', trigger: 'blur' }], customerContact: [{ required: true, message: '请填写客户联系人', trigger: 'blur' }],
@@ -1437,12 +1479,14 @@
formData.channelServiceOrderId = '' formData.channelServiceOrderId = ''
serviceOrderOptions.value = [] serviceOrderOptions.value = []
if (isClinical.value) { if (isClinical.value || isBasicExperiment.value) {
// 临床:价格池与渠道无关;切换渠道时勿清空 agreementPriceOptions(否则「添加细胞产品」会失效) // 临床/临床科研:不依赖服务订单;临床还需价格池
clearScheduleCellProducts() if (isClinical.value) {
if (!channelId) return clearScheduleCellProducts()
if (!agreementPriceOptions.value.length) { if (!channelId) return
await loadClinicalCellProductPrices() if (!agreementPriceOptions.value.length) {
await loadClinicalCellProductPrices()
}
} }
return return
} }
@@ -2798,6 +2842,7 @@
formData.customerName = '' formData.customerName = ''
formData.customerContact = '' formData.customerContact = ''
formData.customerPhone = '' formData.customerPhone = ''
formData.researchCategory = ''
saleProductLines.value = [] saleProductLines.value = []
saleLineSeq = 0 saleLineSeq = 0
patientForm.customerId = '' patientForm.customerId = ''
@@ -2850,6 +2895,7 @@
formData.customerName = detail.customerName || '' formData.customerName = detail.customerName || ''
formData.customerContact = detail.customerContact || '' formData.customerContact = detail.customerContact || ''
formData.customerPhone = detail.customerPhone || '' formData.customerPhone = detail.customerPhone || ''
formData.researchCategory = detail.researchCategory || ''
if (detail.consentAttachmentFiles?.length) { if (detail.consentAttachmentFiles?.length) {
consentFileList.value = mapAttachmentFilesFromDetail(detail.consentAttachmentFiles) consentFileList.value = mapAttachmentFilesFromDetail(detail.consentAttachmentFiles)
@@ -2866,8 +2912,8 @@
otherFileList.value = [] otherFileList.value = []
} }
// 加载渠道后加载服务订单 // 中试:加载渠道后加载服务订单(临床/临床科研不需要)
if (formData.channelId && !isClinical.value) { if (formData.channelId && !isClinical.value && !isBasicExperiment.value) {
try { try {
serviceOrderOptions.value = await fetchAllPagedRecords((page, pageSize) => serviceOrderOptions.value = await fetchAllPagedRecords((page, pageSize) =>
fetchChannelServiceOrderList({ fetchChannelServiceOrderList({
@@ -2963,7 +3009,7 @@
})) }))
})) }))
} }
if (formData.channelId && !isClinical.value) { if (formData.channelId && !isClinical.value && !isBasicExperiment.value) {
await loadAgreements(formData.channelId) await loadAgreements(formData.channelId)
} }
if (isBasicExperiment.value && detail.infusionSchedules?.length) { if (isBasicExperiment.value && detail.infusionSchedules?.length) {
@@ -3062,6 +3108,8 @@
} }
if (isBasicExperiment.value) { if (isBasicExperiment.value) {
payload.researchCategory = formData.researchCategory || undefined
payload.channelId = formData.channelId || undefined
payload.projectTitle = formData.projectTitle || undefined payload.projectTitle = formData.projectTitle || undefined
payload.customerName = formData.customerName || undefined payload.customerName = formData.customerName || undefined
payload.customerContact = formData.customerContact || undefined payload.customerContact = formData.customerContact || undefined
@@ -82,7 +82,7 @@
<div class="kpi-value">{{ dash(applicationDetail.customerName) }}</div> <div class="kpi-value">{{ dash(applicationDetail.customerName) }}</div>
</div> </div>
</div> </div>
<div v-if="!isBasicExperiment" class="kpi-card"> <div class="kpi-card">
<div class="kpi-card__icon" aria-hidden="true"> <div class="kpi-card__icon" aria-hidden="true">
<el-icon><User /></el-icon> <el-icon><User /></el-icon>
</div> </div>
@@ -121,6 +121,16 @@
<div class="data-label">申请单名称</div> <div class="data-label">申请单名称</div>
<div class="data-value">{{ dash(applicationDetail.applicationName) }}</div> <div class="data-value">{{ dash(applicationDetail.applicationName) }}</div>
</div> </div>
<div class="data-item">
<div class="data-label">业务类型</div>
<div class="data-value">
{{ dash(clinicalResearchCategoryLabel(applicationDetail.researchCategory)) }}
</div>
</div>
<div class="data-item">
<div class="data-label">渠道名称</div>
<div class="data-value">{{ dash(applicationDetail.channelName) }}</div>
</div>
<div class="data-item"> <div class="data-item">
<div class="data-label">课题名称</div> <div class="data-label">课题名称</div>
<div class="data-value">{{ dash(applicationDetail.projectTitle) }}</div> <div class="data-value">{{ dash(applicationDetail.projectTitle) }}</div>
@@ -888,6 +898,7 @@
import { downloadAttachmentFile } from '@/utils/download-attachment' import { downloadAttachmentFile } from '@/utils/download-attachment'
import { formatMoneyDisplay } from '@/utils/money-format' import { formatMoneyDisplay } from '@/utils/money-format'
import { getPilotBizConfig } from '@/config/pilot-biz-type' import { getPilotBizConfig } from '@/config/pilot-biz-type'
import { clinicalResearchCategoryLabel } from '@/constants/clinical-research-category'
import { import {
applicationStatusLabel, applicationStatusLabel,
applicationStatusTagType, applicationStatusTagType,
@@ -139,6 +139,17 @@
</el-button> </el-button>
</template> </template>
</el-table-column> </el-table-column>
<el-table-column
v-if="isBasicExperiment"
prop="researchCategory"
label="业务类型"
min-width="160"
show-overflow-tooltip
>
<template #default="{ row }">
{{ clinicalResearchCategoryLabel(row.researchCategory) || '—' }}
</template>
</el-table-column>
<el-table-column <el-table-column
v-if="isBasicExperiment" v-if="isBasicExperiment"
prop="projectTitle" prop="projectTitle"
@@ -330,6 +341,7 @@
import { applicationStatusLabel, applicationStatusTagType } from '@/utils/status-tag-registry' import { applicationStatusLabel, applicationStatusTagType } from '@/utils/status-tag-registry'
import { fetchAllPagedRecords } from '@/utils/fetch-paged-list' import { fetchAllPagedRecords } from '@/utils/fetch-paged-list'
import { getPilotBizConfig, resolvePilotBizType } from '@/config/pilot-biz-type' import { getPilotBizConfig, resolvePilotBizType } from '@/config/pilot-biz-type'
import { clinicalResearchCategoryLabel } from '@/constants/clinical-research-category'
defineOptions({ name: 'PilotApplicationTab' }) defineOptions({ name: 'PilotApplicationTab' })
@@ -1,4 +1,4 @@
<!-- 中试/临床/基础实验申请单页:Tab 由 bizType 策略配置驱动 --> <!-- 中试/临床/临床科研申请单页:Tab 由 bizType 策略配置驱动 -->
<template> <template>
<div class="page-container"> <div class="page-container">
<section class="panel"> <section class="panel">
@@ -0,0 +1,185 @@
<!-- 临床科研出库工单 — 确认出库细胞 -->
<!-- eslint-disable vue/no-v-model-argument vue/no-multiple-template-root -->
<template>
<el-dialog
:model-value="modelValue"
title="确认出库细胞"
width="1100px"
class="dialog-form-layout production-delivery-cell-outbound-dialog"
align-center
append-to-body
modal-class="protocol-dialog-mask"
destroy-on-close
:close-on-click-modal="false"
style="backdrop-filter: none"
@update:model-value="emit('update:modelValue', $event)"
@closed="handleClosed"
>
<div v-if="scheduleSummary" class="material-summary">
<div class="material-summary-row">
<span class="material-summary-label">工单号</span>
<span class="material-summary-value">{{ workOrderNo || '—' }}</span>
</div>
<div class="material-summary-row">
<span class="material-summary-label">申请单号</span>
<span class="material-summary-value">{{ scheduleSummary.applicationNo || '—' }}</span>
</div>
<div class="material-summary-row">
<span class="material-summary-label">课题名称</span>
<span class="material-summary-value">{{ scheduleSummary.projectTitle || '—' }}</span>
</div>
<div class="material-summary-row">
<span class="material-summary-label">客户名称</span>
<span class="material-summary-value">{{ scheduleSummary.customerName || '—' }}</span>
</div>
<div class="material-summary-row">
<span class="material-summary-label">交付时间</span>
<span class="material-summary-value">{{ scheduleSummary.infusionTime || '—' }}</span>
</div>
</div>
<div v-loading="loading" class="outbound-body">
<OutboundMaterialFormSections
ref="materialSectionsRef"
require-frozen-cell-product
:show-materials="false"
:show-papers="false"
:show-remark="false"
/>
</div>
<template #footer>
<el-button class="btn-ghost" @click="emit('update:modelValue', false)">
<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 { nextTick, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Check, Close } from '@element-plus/icons-vue'
import {
fetchProductionDeliveryCellOutbound,
saveProductionDeliveryCellOutbound
} from '@/api/production-work-order'
import OutboundMaterialFormSections from '@/components/business/outbound-material-form-sections/index.vue'
defineOptions({ name: 'ProductionDeliveryCellOutboundDialog' })
const props = defineProps<{
modelValue: boolean
workOrderId: string
}>()
const emit = defineEmits<{
(e: 'update:modelValue', val: boolean): void
(e: 'saved'): void
}>()
const materialSectionsRef = ref<InstanceType<typeof OutboundMaterialFormSections> | null>(null)
const loading = ref(false)
const submitting = ref(false)
const workOrderNo = ref('')
const scheduleSummary = ref<{
applicationNo?: string
patientName?: string
infusionTime?: string
projectTitle?: string
customerName?: string
} | null>(null)
async function loadData() {
if (!props.workOrderId) return
loading.value = true
try {
const data = await fetchProductionDeliveryCellOutbound(props.workOrderId)
workOrderNo.value = data.workOrderNo || ''
scheduleSummary.value = data.scheduleSummary || null
await nextTick()
materialSectionsRef.value?.loadFromApiData({
cells: data.cells as any
})
} catch (e: any) {
ElMessage.error(e?.message || '加载出库细胞失败')
emit('update:modelValue', false)
} finally {
loading.value = false
}
}
async function handleSubmit() {
if (!props.workOrderId) return
if (!materialSectionsRef.value?.validateMaterial()) return
const payload = materialSectionsRef.value.buildSavePayload()
submitting.value = true
try {
await saveProductionDeliveryCellOutbound(props.workOrderId, {
cells: (payload.cells || []).map((c: { cellProductId: string; remark?: string }) => ({
cellProductId: c.cellProductId,
remark: c.remark
}))
})
ElMessage.success('出库细胞已确认')
emit('saved')
emit('update:modelValue', false)
} catch (e: any) {
ElMessage.error(e?.message || '确认出库失败')
} finally {
submitting.value = false
}
}
function handleClosed() {
workOrderNo.value = ''
scheduleSummary.value = null
materialSectionsRef.value?.resetState()
}
watch(
() => props.modelValue,
(visible) => {
if (visible) void loadData()
}
)
</script>
<style scoped lang="scss">
.material-summary {
margin-bottom: 16px;
padding: 12px 16px;
background: var(--el-fill-color-lighter);
border-radius: 8px;
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 8px 24px;
}
.material-summary-row {
display: flex;
gap: 8px;
min-width: 0;
}
.material-summary-label {
flex: 0 0 auto;
color: var(--el-text-color-secondary);
}
.material-summary-value {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.outbound-body {
min-height: 160px;
}
</style>
@@ -75,6 +75,13 @@
<el-button class="btn-op-item" @click="emit('view-qc', row)"> <el-button class="btn-op-item" @click="emit('view-qc', row)">
<el-icon><DataLine /></el-icon>查看质检数据 <el-icon><DataLine /></el-icon>查看质检数据
</el-button> </el-button>
<el-button
v-if="showDeliveryCellOutbound(row)"
class="btn-op-item"
@click="emit('delivery-cell-outbound', row)"
>
<el-icon><Box /></el-icon>确认出库细胞
</el-button>
<el-button <el-button
v-if="showStorageCertQcButton(row)" v-if="showStorageCertQcButton(row)"
class="btn-op-item" class="btn-op-item"
@@ -353,7 +360,8 @@
ArrowDown, ArrowDown,
ArrowUp, ArrowUp,
DataLine, DataLine,
FolderAdd FolderAdd,
Box
} from '@element-plus/icons-vue' } from '@element-plus/icons-vue'
import type { ProductionWorkOrderItem } from '@/api/production-work-order' import type { ProductionWorkOrderItem } from '@/api/production-work-order'
import type { OutboundQcDetailProduct } from '@/api/qc-work-order' import type { OutboundQcDetailProduct } from '@/api/qc-work-order'
@@ -545,6 +553,7 @@
const emit = defineEmits<{ const emit = defineEmits<{
view: [row: ProductionWorkOrderItem] view: [row: ProductionWorkOrderItem]
'view-qc': [row: ProductionWorkOrderItem] 'view-qc': [row: ProductionWorkOrderItem]
'delivery-cell-outbound': [row: ProductionWorkOrderItem]
dispatch: [row: ProductionWorkOrderItem] dispatch: [row: ProductionWorkOrderItem]
'dispatch-qc': [row: ProductionWorkOrderItem] 'dispatch-qc': [row: ProductionWorkOrderItem]
complete: [row: ProductionWorkOrderItem] complete: [row: ProductionWorkOrderItem]
@@ -649,6 +658,14 @@
return row.workOrderStatus === 'dpz' || row.workOrderStatus === 'jxz' return row.workOrderStatus === 'dpz' || row.workOrderStatus === 'jxz'
} }
function showDeliveryCellOutbound(row: ProductionWorkOrderItem) {
if (isMineMode.value) return false
if (row.workOrderStatus === 'yzf') return false
const tabKey = resolveEffectiveRowTabKey(listTabKey.value, row)
if (tabKey === 'outbound_basic_experiment') return true
return row.bizType === 'basic_experiment' && (row.workOrderType || '') === 'outbound'
}
function canVoidWorkOrder(row: ProductionWorkOrderItem) { function canVoidWorkOrder(row: ProductionWorkOrderItem) {
return row.workOrderStatus === 'dpz' || row.workOrderStatus === 'jxz' return row.workOrderStatus === 'dpz' || row.workOrderStatus === 'jxz'
} }
@@ -22,6 +22,7 @@ import {
isAllProductionWorkOrderTab, isAllProductionWorkOrderTab,
tabSupportsInactiveProtocolFilter, tabSupportsInactiveProtocolFilter,
resolveTabKeyFromWorkOrder, resolveTabKeyFromWorkOrder,
workOrderMatchesTab,
type ProductionWorkOrderTabKey type ProductionWorkOrderTabKey
} from '@/utils/production-work-order-tabs' } from '@/utils/production-work-order-tabs'
import { toAllTabListQuery } from '@/utils/production-work-order-category' import { toAllTabListQuery } from '@/utils/production-work-order-category'
@@ -164,8 +165,16 @@ export function useProductionWorkOrderTabPage(
...listQuery, ...listQuery,
...buildPlannedStartTimeParams() ...buildPlannedStartTimeParams()
}) })
tableData.value = res.list || [] const rawList = res.list || []
pagination.total = res.total ?? 0 const list = isAllProductionWorkOrderTab(tabKey.value)
? rawList.filter((row) => workOrderMatchesTab(row, 'all'))
: rawList
tableData.value = list
// 「所有」前端排除中试时,按本页剔除量修正 total(后端未改)
pagination.total = Math.max(
0,
(res.total ?? 0) - (rawList.length - list.length)
)
selectedRows.value = selectedRows.value.filter((row) => selectedRows.value = selectedRows.value.filter((row) =>
tableData.value.some((item) => item.id === row.id) tableData.value.some((item) => item.id === row.id)
) )
@@ -189,6 +189,7 @@
:tasks-batch-loading="tasksBatchLoading" :tasks-batch-loading="tasksBatchLoading"
@view="handleView" @view="handleView"
@view-qc="handleViewQc" @view-qc="handleViewQc"
@delivery-cell-outbound="handleDeliveryCellOutbound"
@dispatch="(row) => emit('dispatch', row)" @dispatch="(row) => emit('dispatch', row)"
@dispatch-qc="(row) => emit('dispatch-qc', row)" @dispatch-qc="(row) => emit('dispatch-qc', row)"
@complete="(row) => emit('complete', row)" @complete="(row) => emit('complete', row)"
@@ -229,6 +230,12 @@
:tasks="saveSetTasks" :tasks="saveSetTasks"
:lab-storage-code="saveSetLabStorageCode" :lab-storage-code="saveSetLabStorageCode"
/> />
<ProductionDeliveryCellOutboundDialog
v-model="deliveryCellOutboundVisible"
:work-order-id="deliveryCellOutboundWorkOrderId"
@saved="handleDeliveryCellOutboundSaved"
/>
</div> </div>
</template> </template>
@@ -242,6 +249,7 @@
import { PRODUCTION_WORK_ORDER_STATUS_FILTER_OPTIONS } from '@/utils/status-tag-registry' import { PRODUCTION_WORK_ORDER_STATUS_FILTER_OPTIONS } from '@/utils/status-tag-registry'
import ProductionWorkOrderCardList from '../ProductionWorkOrderCardList.vue' import ProductionWorkOrderCardList from '../ProductionWorkOrderCardList.vue'
import ProductionWorkOrderQcViewDialog from '../ProductionWorkOrderQcViewDialog.vue' import ProductionWorkOrderQcViewDialog from '../ProductionWorkOrderQcViewDialog.vue'
import ProductionDeliveryCellOutboundDialog from '../ProductionDeliveryCellOutboundDialog.vue'
import SampleReceptionDialog from '../SampleReceptionDialog.vue' import SampleReceptionDialog from '../SampleReceptionDialog.vue'
import SaveProductionTaskSetDialog from '../SaveProductionTaskSetDialog.vue' import SaveProductionTaskSetDialog from '../SaveProductionTaskSetDialog.vue'
import { PRODUCTION_WORK_ORDER_VIEW_DIALOG_COMPONENTS } from '../view-dialogs/view-dialog-registry' import { PRODUCTION_WORK_ORDER_VIEW_DIALOG_COMPONENTS } from '../view-dialogs/view-dialog-registry'
@@ -283,6 +291,8 @@
const saveSetLabStorageCode = computed(() => const saveSetLabStorageCode = computed(() =>
resolveWorkOrderLabStorageCode(saveSetRow.value) resolveWorkOrderLabStorageCode(saveSetRow.value)
) )
const deliveryCellOutboundVisible = ref(false)
const deliveryCellOutboundWorkOrderId = ref('')
const { const {
cardMetaConfig, cardMetaConfig,
@@ -366,6 +376,16 @@
qcViewVisible.value = true qcViewVisible.value = true
} }
function handleDeliveryCellOutbound(row: ProductionWorkOrderItem) {
deliveryCellOutboundWorkOrderId.value = row.id || ''
deliveryCellOutboundVisible.value = true
}
function handleDeliveryCellOutboundSaved() {
loadData()
emit('data-changed')
}
function handleSampleReceptionSuccess() { function handleSampleReceptionSuccess() {
bumpTaskRefresh() bumpTaskRefresh()
loadData() loadData()
@@ -1,9 +1,9 @@
<!-- 基础实验生产工单 — 查看详情 --> <!-- 临床科研生产工单 — 查看详情 -->
<!-- eslint-disable vue/no-v-model-argument --> <!-- eslint-disable vue/no-v-model-argument -->
<template> <template>
<ProductionWorkOrderViewDialogFrame <ProductionWorkOrderViewDialogFrame
v-model:visible="dialogVisible" v-model:visible="dialogVisible"
title="基础实验生产工单详情" title="临床科研生产工单详情"
:loading="loading" :loading="loading"
:detail="detail" :detail="detail"
:sections="sections" :sections="sections"
@@ -260,7 +260,11 @@
> >
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { joinChildNames, managementPayload } from '@/utils/project-management' import {
joinChildNames,
managementPayload,
projectBizTypeSelectLabels
} from '@/utils/project-management'
import { useMenuPerm } from '@/hooks/core/useMenuPerm' import { useMenuPerm } from '@/hooks/core/useMenuPerm'
import { import {
Plus, Plus,
@@ -281,9 +285,6 @@
fetchProjectReferences, fetchProjectReferences,
type ProjectRecord type ProjectRecord
} from '@/api/project-management' } from '@/api/project-management'
const projectBizLabels = Object.fromEntries(
Object.entries(bizLabels).filter(([key]) => key !== 'presign')
)
const props = defineProps<{ kind: 'teams' | 'projects' }>() const props = defineProps<{ kind: 'teams' | 'projects' }>()
const isTeam = computed(() => props.kind === 'teams') const isTeam = computed(() => props.kind === 'teams')
const { hasMenuPerm } = useMenuPerm() const { hasMenuPerm } = useMenuPerm()
@@ -323,6 +324,10 @@
memberIds = ref<string[]>([]), memberIds = ref<string[]>([]),
regionIds = ref<string[]>([]), regionIds = ref<string[]>([]),
hospitalIds = ref<string[]>([]) hospitalIds = ref<string[]>([])
/** 默认不含中试;旧项目已选中试时保留该选项以展示 */
const projectBizLabels = computed(() =>
projectBizTypeSelectLabels(bizLabels, form.value.bizTypes as string[] | undefined)
)
async function load() { async function load() {
loading.value = true loading.value = true
try { try {
@@ -10,7 +10,7 @@ export const assignmentTabs: { key: AssignmentBizType; title: string }[] = [
{ key: 'cell_storage', title: '细胞存储' }, { key: 'cell_storage', title: '细胞存储' },
{ key: 'research_donation', title: '科研捐赠' }, { key: 'research_donation', title: '科研捐赠' },
{ key: 'pilot_service', title: '中试服务' }, { key: 'pilot_service', title: '中试服务' },
{ key: 'basic_experiment', title: '基础实验' } { key: 'basic_experiment', title: '临床科研' }
] ]
const collectionColumns: AssignmentColumn[] = [ const collectionColumns: AssignmentColumn[] = [
@@ -154,6 +154,7 @@
type QcTaskResultItem type QcTaskResultItem
} from '@/api/qc-task-result' } from '@/api/qc-task-result'
import { taskStatusLabel, taskStatusTagType } from '@/utils/qc-labels' import { taskStatusLabel, taskStatusTagType } from '@/utils/qc-labels'
import { resolveThirdPartyFillDefaults } from '@/utils/qc-result-fill-defaults'
import { parseQcParamOptions } from '@/utils/qc-item-param-options' import { parseQcParamOptions } from '@/utils/qc-item-param-options'
import { import {
pickSharedRemarkAndAttachments, pickSharedRemarkAndAttachments,
@@ -233,16 +234,6 @@
emit('update:visible', false) emit('update:visible', false)
} }
/** 第三方弹窗仅展示待执行/已完成;其它状态按待执行回显 */
function normalizeThirdPartySaveStatus(status?: string): 'dzx' | 'ywc' {
return (status || '').trim() === 'ywc' ? 'ywc' : 'dzx'
}
function normalizeConclusion(raw?: string): '' | 'tg' | 'btg' {
const c = (raw || '').trim()
return c === 'tg' || c === 'btg' ? c : ''
}
function normalizeResultParams(items: QcTaskResultItem[]): QcTaskResultItem[] { function normalizeResultParams(items: QcTaskResultItem[]): QcTaskResultItem[] {
return (items || []).map((p) => ({ return (items || []).map((p) => ({
...p, ...p,
@@ -319,13 +310,17 @@
companyId: detail?.companyId ?? task.companyId, companyId: detail?.companyId ?? task.companyId,
companyName: detail?.companyName ?? task.companyName companyName: detail?.companyName ?? task.companyName
} }
const fillDefaults = resolveThirdPartyFillDefaults({
taskStatus: merged.taskStatus,
conclusion: merged.conclusion
})
const item: ItemState = { const item: ItemState = {
taskId: task.id, taskId: task.id,
itemName: merged.itemName || '—', itemName: merged.itemName || '—',
companyName: thirdPartyCompanyDisplayName(merged), companyName: thirdPartyCompanyDisplayName(merged),
params: normalizeResultParams(results || []), params: normalizeResultParams(results || []),
saveStatus: normalizeThirdPartySaveStatus(merged.taskStatus), saveStatus: fillDefaults.saveStatus,
conclusion: normalizeConclusion(merged.conclusion) conclusion: fillDefaults.conclusion
} }
return { item, merged } return { item, merged }
}) })
@@ -385,6 +380,11 @@
const thirdPartyAttachments = financeAttachmentsToUrlString(attachments.value) const thirdPartyAttachments = financeAttachmentsToUrlString(attachments.value)
const remarkVal = remark.value const remarkVal = remark.value
// 同一次批量保存共用批次号,修改记录弹窗合并为一个时间线节点
const operateBatchId =
typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function'
? crypto.randomUUID().replace(/-/g, '').toUpperCase()
: `BATCH${Date.now()}${Math.random().toString(16).slice(2, 10)}`.toUpperCase()
saving.value = true saving.value = true
const failures: string[] = [] const failures: string[] = []
let successCount = 0 let successCount = 0
@@ -404,7 +404,8 @@
})), })),
remark: remarkVal, remark: remarkVal,
thirdPartyAttachments, thirdPartyAttachments,
taskStatus: item.saveStatus taskStatus: item.saveStatus,
operateBatchId
}, },
props.operateScope props.operateScope
) )
@@ -0,0 +1,445 @@
<!-- 质检任务 · 检测结果修改记录 -->
<template>
<el-dialog
:model-value="visible"
:title="dialogTitle"
width="800px"
class="dialog-form-layout qc-task-result-change-log-dialog"
align-center
modal-class="protocol-dialog-mask"
append-to-body
destroy-on-close
:close-on-click-modal="false"
@update:model-value="onVisibleChange"
>
<DialogFormBody :loading="loading" body-class="qc-result-chg-body">
<el-empty
v-if="!loading && !timelineNodes.length"
description="暂无修改记录"
:image-size="72"
/>
<div v-else class="qc-result-chg-tl">
<div
v-for="(node, idx) in timelineNodes"
:key="node.key"
class="qc-result-chg-tl__item"
>
<div class="qc-result-chg-tl__rail">
<span class="qc-result-chg-tl__dot" />
<span v-if="idx < timelineNodes.length - 1" class="qc-result-chg-tl__line" />
</div>
<div class="qc-result-chg-tl__content">
<div class="qc-result-chg-tl__meta">
{{ node.operateTime || '—' }} · {{ node.operatorUserName || '—' }}
<template v-if="node.entries.length > 1">
· 共 {{ node.entries.length }} 项
</template>
</div>
<div v-if="node.sharedAttachment" class="qc-result-chg-tl__change">
<div class="qc-result-chg-tl__line-text">
{{ node.sharedAttachment.fieldLabel }}:
<template
v-if="
node.sharedAttachment.oldValue &&
node.sharedAttachment.oldValue !== node.sharedAttachment.newValue
"
>
已更新
</template>
<template v-else-if="!node.sharedAttachment.newValue">已清空</template>
</div>
<ProtocolAttachmentReadonly
v-if="attachmentFilesFromValue(node.sharedAttachment.newValue).length"
size="compact"
:files="attachmentFilesFromValue(node.sharedAttachment.newValue)"
@preview="onAttachmentPreview"
@download="onAttachmentDownload"
/>
<span
v-else-if="!node.sharedAttachment.newValue"
class="qc-result-chg-tl__line-text"
>—</span>
</div>
<div
v-for="entry in node.entries"
:key="entry.id"
class="qc-result-chg-tl__entry"
>
<div
v-if="showItemName && entry.itemName"
class="qc-result-chg-tl__item-name"
>
{{ entry.itemName }}
</div>
<template v-if="visibleChanges(entry, node).length">
<div
v-for="(chg, cIdx) in visibleChanges(entry, node)"
:key="`${entry.id}-${cIdx}`"
class="qc-result-chg-tl__change"
>
<template v-if="isAttachmentChange(chg)">
<div class="qc-result-chg-tl__line-text">
{{ chg.fieldLabel }}:
<template v-if="chg.oldValue && chg.oldValue !== chg.newValue">
已更新
</template>
<template v-else-if="!chg.newValue">已清空</template>
</div>
<ProtocolAttachmentReadonly
v-if="attachmentFilesFromValue(chg.newValue).length"
size="compact"
:files="attachmentFilesFromValue(chg.newValue)"
@preview="onAttachmentPreview"
@download="onAttachmentDownload"
/>
<span
v-else-if="!chg.newValue"
class="qc-result-chg-tl__line-text"
>—</span>
</template>
<div v-else class="qc-result-chg-tl__line-text">
<template v-if="chg.oldValue">
{{ chg.fieldLabel }}:{{ chg.oldValue || '—' }} →
{{ chg.newValue || '—' }}
</template>
<template v-else>
{{ chg.fieldLabel }}:{{ chg.newValue || '—' }}
</template>
</div>
</div>
</template>
<div
v-else-if="!entry.hasFieldChange || !entry.changes?.length"
class="qc-result-chg-tl__line-text"
>
保存操作(字段无变更)
</div>
</div>
<div v-if="node.allNoFieldChange" class="qc-result-chg-tl__note">
即使未改值,点击保存也会记一条操作留痕
</div>
</div>
</div>
</div>
</DialogFormBody>
<template #footer>
<el-button class="btn-ghost" @click="close">
<el-icon><Close /></el-icon>关闭
</el-button>
</template>
</el-dialog>
</template>
<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Close } from '@element-plus/icons-vue'
import DialogFormBody from '@/components/business/dialog-form-body/index.vue'
import ProtocolAttachmentReadonly from '@/views/cell-storage/protocol/ProtocolAttachmentReadonly.vue'
import { downloadAttachmentFile } from '@/utils/download-attachment'
import {
qcAttachmentFullUrl,
qcPreviewAttachment
} from './composables/useQcViewAttachmentHelpers'
import {
fetchQcTaskResultChangeLogsBatch,
type QcTaskResultChangeItem,
type QcTaskResultChangeLog
} from '@/api/qc-task-result'
defineOptions({ name: 'QcTaskResultChangeLogDialog' })
type TimelineNode = {
key: string
operateTime: string
operatorUserName: string
entries: QcTaskResultChangeLog[]
allNoFieldChange: boolean
/** 多任务同次提交且检测材料一致时,提到节点级只展示一次 */
sharedAttachment: QcTaskResultChangeItem | null
}
/** 无批次号的旧数据:同操作人且时间差 ≤15s 合并为一次提交 */
const LEGACY_GROUP_WINDOW_MS = 15_000
const props = withDefaults(
defineProps<{
visible: boolean
taskIds: string[]
titleSuffix?: string
}>(),
{
titleSuffix: ''
}
)
const emit = defineEmits<{
'update:visible': [value: boolean]
}>()
const loading = ref(false)
const entries = ref<QcTaskResultChangeLog[]>([])
let loadSeq = 0
const showItemName = computed(() => (props.taskIds || []).length > 1)
const dialogTitle = computed(() => {
const suffix = (props.titleSuffix || '').trim()
return suffix ? `修改记录 · ${suffix}` : '修改记录'
})
const timelineNodes = computed(() => groupChangeLogs(entries.value))
function onVisibleChange(v: boolean) {
emit('update:visible', v)
}
function close() {
emit('update:visible', false)
}
function isAttachmentChange(chg: QcTaskResultChangeItem) {
return (chg.fieldKey || '') === 'attachments'
}
function pickSharedAttachment(rows: QcTaskResultChangeLog[]) {
if (rows.length < 2) return null
const attChanges = rows
.map((r) => (r.changes || []).find((c) => isAttachmentChange(c)))
.filter(Boolean) as QcTaskResultChangeItem[]
if (!attChanges.length || attChanges.length !== rows.length) return null
const first = attChanges[0]
const same = attChanges.every(
(c) => c.newValue === first.newValue && c.oldValue === first.oldValue
)
return same ? first : null
}
function visibleChanges(entry: QcTaskResultChangeLog, node: TimelineNode) {
const list = entry.changes || []
if (!node.sharedAttachment) return list
return list.filter((c) => !isAttachmentChange(c))
}
function attachmentFilesFromValue(raw: string | undefined) {
const text = String(raw || '').trim()
if (!text) return [] as Array<Record<string, unknown>>
return text
.split(',')
.map((u, i) => {
const url = u.trim()
if (!url) return null
const name = url.includes('/') ? url.split('/').pop() || `附件${i + 1}` : url
return {
id: `chg_att_${i}_${name}`,
fileUrl: url,
fileName: name
}
})
.filter(Boolean) as Array<Record<string, unknown>>
}
function onAttachmentPreview(file: Record<string, unknown>) {
qcPreviewAttachment(file)
}
function onAttachmentDownload(file: Record<string, unknown>) {
downloadAttachmentFile(file, { fullFileUrl: qcAttachmentFullUrl })
}
function parseOperateTimeMs(text: string | undefined) {
const s = String(text || '').trim()
if (!s) return NaN
const t = Date.parse(s.replace(/-/g, '/'))
return Number.isFinite(t) ? t : NaN
}
function groupChangeLogs(list: QcTaskResultChangeLog[]): TimelineNode[] {
const sorted = [...(list || [])].sort((a, b) => {
const tb = parseOperateTimeMs(b.operateTime)
const ta = parseOperateTimeMs(a.operateTime)
if (Number.isFinite(tb) && Number.isFinite(ta) && tb !== ta) return tb - ta
return String(b.id || '').localeCompare(String(a.id || ''))
})
const batchBuckets = new Map<string, QcTaskResultChangeLog[]>()
const orphans: QcTaskResultChangeLog[] = []
for (const row of sorted) {
const batch = String(row.operateBatchId || '').trim()
if (batch) {
const arr = batchBuckets.get(batch) || []
arr.push(row)
batchBuckets.set(batch, arr)
} else {
orphans.push(row)
}
}
const nodes: TimelineNode[] = []
for (const [batch, rows] of batchBuckets) {
nodes.push(toNode(`batch:${batch}`, rows))
}
// 旧数据兜底:按时间序贪心合并同操作人短窗口
const used = new Set<string>()
for (let i = 0; i < orphans.length; i++) {
const head = orphans[i]
if (used.has(head.id)) continue
const group = [head]
used.add(head.id)
const headTs = parseOperateTimeMs(head.operateTime)
const headOp = String(head.operatorUserId || head.operatorUserName || '')
for (let j = i + 1; j < orphans.length; j++) {
const cur = orphans[j]
if (used.has(cur.id)) continue
const curOp = String(cur.operatorUserId || cur.operatorUserName || '')
if (curOp !== headOp) continue
const curTs = parseOperateTimeMs(cur.operateTime)
if (!Number.isFinite(headTs) || !Number.isFinite(curTs)) continue
if (Math.abs(curTs - headTs) > LEGACY_GROUP_WINDOW_MS) continue
group.push(cur)
used.add(cur.id)
}
nodes.push(toNode(`legacy:${head.id}`, group))
}
return nodes.sort((a, b) => {
const tb = parseOperateTimeMs(b.operateTime)
const ta = parseOperateTimeMs(a.operateTime)
if (Number.isFinite(tb) && Number.isFinite(ta) && tb !== ta) return tb - ta
return a.key.localeCompare(b.key)
})
}
function toNode(key: string, rows: QcTaskResultChangeLog[]): TimelineNode {
const first = rows[0]
return {
key,
operateTime: first?.operateTime || '',
operatorUserName: first?.operatorUserName || '',
entries: rows,
allNoFieldChange: rows.every((r) => !r.hasFieldChange),
sharedAttachment: pickSharedAttachment(rows)
}
}
async function loadLogs() {
const seq = ++loadSeq
const ids = (props.taskIds || []).map((x) => (x || '').trim()).filter(Boolean)
loading.value = true
entries.value = []
try {
const list = ids.length ? await fetchQcTaskResultChangeLogsBatch(ids) : []
if (seq !== loadSeq) return
entries.value = Array.isArray(list) ? list : []
} catch {
if (seq !== loadSeq) return
entries.value = []
ElMessage.error('加载修改记录失败')
} finally {
if (seq === loadSeq) loading.value = false
}
}
watch(
() => [props.visible, (props.taskIds || []).join(',')] as const,
([vis]) => {
if (vis) void loadLogs()
}
)
</script>
<style scoped lang="scss">
:deep(.qc-result-chg-body) {
min-height: 480px;
max-height: min(70vh, 640px);
overflow-y: auto;
}
.qc-result-chg-tl {
display: flex;
flex-direction: column;
gap: 4px;
padding: 4px 0 8px;
min-height: 420px;
}
.qc-result-chg-tl__item {
display: flex;
gap: 12px;
}
.qc-result-chg-tl__rail {
display: flex;
flex-direction: column;
align-items: center;
width: 12px;
flex-shrink: 0;
}
.qc-result-chg-tl__dot {
width: 10px;
height: 10px;
margin-top: 4px;
border-radius: 50%;
background: var(--mint-primary, #10b981);
flex-shrink: 0;
}
.qc-result-chg-tl__line {
width: 2px;
flex: 1;
min-height: 36px;
margin-top: 4px;
background: var(--mint-primary-bg, #ecfdf5);
}
.qc-result-chg-tl__content {
flex: 1;
min-width: 0;
padding-bottom: 14px;
}
.qc-result-chg-tl__meta {
font-size: 12px;
font-weight: 600;
color: var(--mint-primary-dark, #059669);
margin-bottom: 8px;
}
.qc-result-chg-tl__entry {
margin-bottom: 10px;
&:last-child {
margin-bottom: 0;
}
}
.qc-result-chg-tl__item-name {
font-size: 13px;
font-weight: 600;
color: var(--mint-text, #1e293b);
margin-bottom: 4px;
}
.qc-result-chg-tl__change {
margin: 4px 0;
}
.qc-result-chg-tl__line-text {
font-size: 13px;
color: var(--mint-text, #1e293b);
margin: 2px 0;
word-break: break-word;
}
.qc-result-chg-tl__note {
margin-top: 6px;
font-size: 12px;
color: var(--mint-text-muted, #334155);
}
</style>
@@ -1,4 +1,4 @@
<!-- 质检工单 · 用户费用摘要条(采集协议 / 基础实验) --> <!-- 质检工单 · 用户费用摘要条(采集协议 / 临床科研) -->
<template> <template>
<div v-if="visible" class="qc-fee-summary"> <div v-if="visible" class="qc-fee-summary">
<span class="qc-fee-summary__label">{{ label }}</span> <span class="qc-fee-summary__label">{{ label }}</span>
@@ -33,6 +33,16 @@
@click="openAllThirdResult(item)" @click="openAllThirdResult(item)"
@dblclick="openAllThirdResult(item)" @dblclick="openAllThirdResult(item)"
> >
<el-button
class="qc-task-card__history-icon"
link
type="primary"
title="修改记录"
aria-label="修改记录"
@click.stop="openChangeLogForTasks(item.tasks, ALL_THIRD_PARTY_CARD_TITLE)"
>
<el-icon><Clock /></el-icon>
</el-button>
<div class="qc-task-card__line qc-task-card__line--top"> <div class="qc-task-card__line qc-task-card__line--top">
<span class="qc-task-card__name">{{ ALL_THIRD_PARTY_CARD_TITLE }}</span> <span class="qc-task-card__name">{{ ALL_THIRD_PARTY_CARD_TITLE }}</span>
<div class="qc-task-card__sub"> <div class="qc-task-card__sub">
@@ -77,6 +87,16 @@
class="qc-task-card qc-task-card--compact" class="qc-task-card qc-task-card--compact"
@dblclick="handleView(item.task)" @dblclick="handleView(item.task)"
> >
<el-button
class="qc-task-card__history-icon"
link
type="primary"
title="修改记录"
aria-label="修改记录"
@click.stop="openChangeLogForTask(item.task)"
>
<el-icon><Clock /></el-icon>
</el-button>
<div class="qc-task-card__line qc-task-card__line--top"> <div class="qc-task-card__line qc-task-card__line--top">
<span class="qc-task-card__name">{{ item.task.itemName || '—' }}</span> <span class="qc-task-card__name">{{ item.task.itemName || '—' }}</span>
<div class="qc-task-card__tags"> <div class="qc-task-card__tags">
@@ -414,6 +434,12 @@
@saved="handleTaskMutationSuccess" @saved="handleTaskMutationSuccess"
/> />
<QcTaskResultChangeLogDialog
v-model:visible="changeLogVisible"
:task-ids="changeLogTaskIds"
:title-suffix="changeLogTitleSuffix"
/>
<SystemViewDialog <SystemViewDialog
v-model:visible="viewVisible" v-model:visible="viewVisible"
title="任务详情" title="任务详情"
@@ -575,7 +601,8 @@
EditPen, EditPen,
Plus, Plus,
More, More,
Delete Delete,
Clock
} from '@element-plus/icons-vue' } from '@element-plus/icons-vue'
import ProtocolFinanceConfirmFields from '@/components/business/protocol-finance-confirm-fields/index.vue' import ProtocolFinanceConfirmFields from '@/components/business/protocol-finance-confirm-fields/index.vue'
import ProtocolAttachmentReadonly from '@/views/cell-storage/protocol/ProtocolAttachmentReadonly.vue' import ProtocolAttachmentReadonly from '@/views/cell-storage/protocol/ProtocolAttachmentReadonly.vue'
@@ -612,6 +639,7 @@
import { fetchItemUnitList } from '@/api/admin' import { fetchItemUnitList } from '@/api/admin'
import { SHOW_QC_TASK_MATERIAL_USAGE } from '@/utils/qc-material-ui' import { SHOW_QC_TASK_MATERIAL_USAGE } from '@/utils/qc-material-ui'
import { parseQcParamOptions } from '@/utils/qc-item-param-options' import { parseQcParamOptions } from '@/utils/qc-item-param-options'
import { resolveQcResultFillDefaults } from '@/utils/qc-result-fill-defaults'
import { import {
taskTypeLabel, taskTypeLabel,
taskTypeTagType, taskTypeTagType,
@@ -656,6 +684,7 @@
type QcTaskListDisplayItem type QcTaskListDisplayItem
} from '@/utils/qc-company-task-group' } from '@/utils/qc-company-task-group'
import QcCompanyTaskResultDialog from './QcCompanyTaskResultDialog.vue' import QcCompanyTaskResultDialog from './QcCompanyTaskResultDialog.vue'
import QcTaskResultChangeLogDialog from './QcTaskResultChangeLogDialog.vue'
/** 根据来源类型返回协议状态标签 */ /** 根据来源类型返回协议状态标签 */
function protocolStatusLabelBySource(status: string, source: string, voidType?: string): string { function protocolStatusLabelBySource(status: string, source: string, voidType?: string): string {
@@ -739,6 +768,25 @@
const companyDialogReadonly = ref(false) const companyDialogReadonly = ref(false)
const companyDialogTasks = ref<QcTask[]>([]) const companyDialogTasks = ref<QcTask[]>([])
const companyDialogName = ref(ALL_THIRD_PARTY_CARD_TITLE) const companyDialogName = ref(ALL_THIRD_PARTY_CARD_TITLE)
const changeLogVisible = ref(false)
const changeLogTaskIds = ref<string[]>([])
const changeLogTitleSuffix = ref('')
function openChangeLogForTask(task: QcTask) {
const id = (task.id || '').trim()
if (!id) return
changeLogTaskIds.value = [id]
changeLogTitleSuffix.value = task.itemName || task.taskNo || ''
changeLogVisible.value = true
}
function openChangeLogForTasks(tasks: QcTask[], title: string) {
const ids = tasks.map((t) => (t.id || '').trim()).filter(Boolean)
if (!ids.length) return
changeLogTaskIds.value = ids
changeLogTitleSuffix.value = title || ''
changeLogVisible.value = true
}
function openAllThirdResult(item: QcTaskListAllThirdItem, forceReadonly?: boolean) { function openAllThirdResult(item: QcTaskListAllThirdItem, forceReadonly?: boolean) {
let tasks = item.tasks let tasks = item.tasks
@@ -864,11 +912,6 @@
const resultDialogWidth = computed(() => (resultTaskType.value === 'sysz' ? '1200px' : '960px')) const resultDialogWidth = computed(() => (resultTaskType.value === 'sysz' ? '1200px' : '960px'))
function normalizeResultSaveStatus(status?: string): 'dzx' | 'jxz' | 'ywc' {
if (status === 'dzx' || status === 'jxz' || status === 'ywc') return status
return 'jxz'
}
function canFillResult(row: QcTask) { function canFillResult(row: QcTask) {
if (row.taskType === 'sysz') { if (row.taskType === 'sysz') {
return row.taskStatus === 'jxz' || row.taskStatus === 'ywc' return row.taskStatus === 'jxz' || row.taskStatus === 'ywc'
@@ -1391,12 +1434,16 @@
} }
return return
} }
const initialDefaults = resolveQcResultFillDefaults({
taskStatus: row.taskStatus,
conclusion: row.conclusion
})
resultTaskStatus.value = row.taskStatus resultTaskStatus.value = row.taskStatus
resultSaveStatus.value = normalizeResultSaveStatus(row.taskStatus) resultSaveStatus.value = initialDefaults.saveStatus
resultTaskId.value = row.id resultTaskId.value = row.id
resultTaskType.value = row.taskType resultTaskType.value = row.taskType
resultRemark.value = row.remark || '' resultRemark.value = row.remark || ''
resultConclusion.value = '' resultConclusion.value = initialDefaults.conclusion
resultAttachments.value = apiFilesToFinanceItems(row.attachmentFiles) resultAttachments.value = apiFilesToFinanceItems(row.attachmentFiles)
materialUsages.value = [] materialUsages.value = []
requisitionOptions.value = [] requisitionOptions.value = []
@@ -1404,10 +1451,13 @@
try { try {
const detail = await fetchQcTaskDetail(row.id) const detail = await fetchQcTaskDetail(row.id)
resultTaskStatus.value = detail.taskStatus || row.taskStatus resultTaskStatus.value = detail.taskStatus || row.taskStatus
resultSaveStatus.value = normalizeResultSaveStatus(detail.taskStatus || row.taskStatus) const fillDefaults = resolveQcResultFillDefaults({
taskStatus: detail.taskStatus || row.taskStatus,
conclusion: detail.conclusion ?? row.conclusion
})
resultSaveStatus.value = fillDefaults.saveStatus
resultRemark.value = detail.remark || row.remark || '' resultRemark.value = detail.remark || row.remark || ''
const c = (detail.conclusion || '').trim() resultConclusion.value = fillDefaults.conclusion
resultConclusion.value = c === 'tg' || c === 'btg' ? c : ''
resultAttachments.value = apiFilesToFinanceItems(detail.attachmentFiles) resultAttachments.value = apiFilesToFinanceItems(detail.attachmentFiles)
const results = await fetchQcTaskResults(row.id) const results = await fetchQcTaskResults(row.id)
resultParams.value = normalizeResultParams(results || []) resultParams.value = normalizeResultParams(results || [])
@@ -1675,6 +1725,7 @@
} }
.qc-task-card { .qc-task-card {
position: relative;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
gap: 6px; gap: 6px;
@@ -1702,7 +1753,7 @@
width: 100%; width: 100%;
max-width: 220px; max-width: 220px;
gap: 4px; gap: 4px;
padding: 6px 8px; padding: 6px 28px 6px 8px;
} }
&--company { &--company {
@@ -1717,6 +1768,26 @@
} }
} }
.qc-task-card__history-icon {
position: absolute;
top: 4px;
right: 4px;
z-index: 1;
width: 22px;
height: 22px;
padding: 0;
margin: 0;
color: var(--mint-primary-dark, #059669);
:deep(.el-icon) {
font-size: 14px;
}
&:hover {
color: var(--mint-primary, #10b981);
}
}
.qc-task-card__sub { .qc-task-card__sub {
width: 100%; width: 100%;
font-size: 11px; font-size: 11px;
@@ -20,6 +20,7 @@ import {
isAllQcWorkOrderTab, isAllQcWorkOrderTab,
isInboundSampleQcTab, isInboundSampleQcTab,
resolveTabKeyFromWorkOrder, resolveTabKeyFromWorkOrder,
workOrderMatchesTab,
type QcWorkOrderTabKey type QcWorkOrderTabKey
} from '@/utils/qc-work-order-tabs' } from '@/utils/qc-work-order-tabs'
import { toAllTabListQuery } from '@/utils/qc-work-order-category' import { toAllTabListQuery } from '@/utils/qc-work-order-category'
@@ -152,6 +153,10 @@ export function useQcWorkOrderTabPage(
keyword: searchForm.keyword || undefined, keyword: searchForm.keyword || undefined,
taskStatus: searchForm.taskStatus || undefined, taskStatus: searchForm.taskStatus || undefined,
taskType: searchForm.taskType || undefined, taskType: searchForm.taskType || undefined,
protocolStatus:
tabKey.value === 'inbound_research_donation'
? joinProtocolStatusFilter(searchForm.protocolStatus)
: undefined,
tabKey: tabKey.value tabKey: tabKey.value
}) })
let entries = groupMineTasksByWorkOrder(tasks) let entries = groupMineTasksByWorkOrder(tasks)
@@ -171,12 +176,6 @@ export function useQcWorkOrderTabPage(
} }
const tab = tabConfig.value const tab = tabConfig.value
if (tabKey.value === 'inbound_research_donation' && !searchForm.protocolStatus.length) {
tableData.value = []
presetBatchesByWorkOrderId.value = undefined
pagination.total = 0
return
}
const timeParams = const timeParams =
isAllQcWorkOrderTab(tabKey.value) || !tabUsesInfusionTimeFilter(tab) isAllQcWorkOrderTab(tabKey.value) || !tabUsesInfusionTimeFilter(tab)
? { ? {
@@ -210,7 +209,10 @@ export function useQcWorkOrderTabPage(
...listQuery, ...listQuery,
...timeParams ...timeParams
}) })
const list = res.list || [] const rawList = res.list || []
const list = isAllQcWorkOrderTab(tabKey.value)
? rawList.filter((row) => workOrderMatchesTab(row, 'all'))
: rawList
const ids = list.map((row) => row.id).filter(Boolean) const ids = list.map((row) => row.id).filter(Boolean)
const batchMap = ids.length const batchMap = ids.length
? (await fetchQcInspectionBatchesBatch(ids).catch(() => ({}))) || {} ? (await fetchQcInspectionBatchesBatch(ids).catch(() => ({}))) || {}
@@ -218,7 +220,8 @@ export function useQcWorkOrderTabPage(
// 先写入批次摘要,再渲染卡片,避免子组件在 preset 未就绪时逐条请求 inspection-batches // 先写入批次摘要,再渲染卡片,避免子组件在 preset 未就绪时逐条请求 inspection-batches
presetBatchesByWorkOrderId.value = batchMap presetBatchesByWorkOrderId.value = batchMap
tableData.value = list tableData.value = list
pagination.total = res.total ?? 0 // 「所有」前端排除中试时,按本页剔除量修正 total(后端未改)
pagination.total = Math.max(0, (res.total ?? 0) - (rawList.length - list.length))
} finally { } finally {
loading.value = false loading.value = false
} }
@@ -1,9 +1,9 @@
<!-- 基础实验出库质检工单 — 查看详情 --> <!-- 临床科研出库质检工单 — 查看详情 -->
<!-- eslint-disable vue/no-v-model-argument --> <!-- eslint-disable vue/no-v-model-argument -->
<template> <template>
<QcWorkOrderSystemViewDialog <QcWorkOrderSystemViewDialog
v-model:visible="dialogVisible" v-model:visible="dialogVisible"
title="基础实验出库质检工单详情" title="临床科研出库质检工单详情"
width="1200px" width="1200px"
:grid-columns="4" :grid-columns="4"
compact compact
@@ -75,7 +75,7 @@
defineProps<{ defineProps<{
products?: OutboundQcDetail['products'] products?: OutboundQcDetail['products']
/** 基础实验时产品状态 dtz 展示为「待交付」 */ /** 临床科研时产品状态 dtz 展示为「待交付」 */
bizType?: string bizType?: string
}>() }>()
</script> </script>
+21 -1
View File
@@ -3,7 +3,8 @@ import test from 'node:test'
import { import {
buildDrillFilters, buildDrillFilters,
assignmentSnapshot, assignmentSnapshot,
joinChildNames joinChildNames,
projectBizTypeSelectLabels
} from '../src/utils/project-management' } from '../src/utils/project-management'
test('drill preserves applied dates and selected project when a team is opened', () => { test('drill preserves applied dates and selected project when a team is opened', () => {
@@ -83,3 +84,22 @@ test('filter options use visible historical scope; create and reassignment remai
}) })
assert.deepEqual(projectOptionsParams('cell_storage', false), { bizType: 'cell_storage' }) assert.deepEqual(projectOptionsParams('cell_storage', false), { bizType: 'cell_storage' })
}) })
test('project biz type select hides pilot by default but keeps it when already selected', () => {
const labels = {
presign: '预签约',
cell_storage: '细胞存储',
research_donation: '科研捐赠',
pilot_service: '中试服务',
basic_experiment: '临床科研'
}
const fresh = projectBizTypeSelectLabels(labels, [])
assert.equal(fresh.pilot_service, undefined)
assert.equal(fresh.presign, undefined)
assert.equal(fresh.cell_storage, '细胞存储')
assert.equal(fresh.basic_experiment, '临床科研')
const legacy = projectBizTypeSelectLabels(labels, ['cell_storage', 'pilot_service'])
assert.equal(legacy.pilot_service, '中试服务')
assert.equal(legacy.cell_storage, '细胞存储')
})