Compare commits

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-19 13:14:10 +08:00
cykj 76ddb81818 Merge pull request 'fix(protocol): 协议作废/属地废弃同步样本状态为已作废 (#127)' (#128)
fix(protocol): 协议作废/属地废弃同步样本状态为已作废 (#127)
2026-11-19 04:33:48 +00:00
87 changed files with 3709 additions and 152 deletions

No files matched your search

+2
View File
@@ -47,10 +47,12 @@ from app.api.sample_cert_insurance import router as sample_cert_insurance_router
from app.api.sample_code_correction import router as sample_code_correction_router
from app.api.lab_sample_process import router as lab_sample_process_router
from app.api.lab_sample_processing import router as lab_sample_processing_router
from app.api.business_sample import router as business_sample_router
from app.api.project_management import router as project_management_router
__all__ = [
"business_sample_router",
"project_management_router",
"lab_sample_process_router",
"public_router",
+15 -2
View File
@@ -29,6 +29,7 @@ from app.crud import user as user_svc
from app.crud.collection_protocol import _lookup_attachment_by_url
from app.models.models import BizAttachment, SysDept, SysRole, SysUser, SysMenu, SysPost
from app.services.permission_administration import validate_tenant_references
from app.services.user_select_options import prioritize_caller_dept_options
from app.services.web_auth_roles import (
_map_role_name_to_web,
list_user_ids_with_effective_role_name,
@@ -77,12 +78,15 @@ async def list_roles_for_select(
@router.get("/users/options")
async def list_users_for_select(
roleName: Optional[str] = Query(None, alias="roleName"),
prioritizeCallerDept: bool = Query(False, alias="prioritizeCallerDept"),
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
"""返回用户下拉选项(label=昵称,value=用户ID),供流程设计器审批人选择使用。
"""返回用户下拉选项(label=昵称,value=用户ID,deptId=部门ID)。
供流程设计器审批人选择、OA 评论 @ 人员等使用。
可选 roleName:按有效角色(直接绑定 ∪ 职位继承)精确过滤。
可选 prioritizeCallerDept:当前登录用户同部门人员排在前面(组内仍按创建时间倒序)。
"""
tenant_no = _user.get("tenant_no", "")
q = db.query(SysUser).filter(SysUser.del_flag == 0, SysUser.status == "1")
@@ -97,7 +101,16 @@ async def list_users_for_select(
return success_response([])
q = q.filter(SysUser.id.in_(matched_ids))
rows = q.order_by(SysUser.create_time.desc()).distinct().all()
out = [{"label": (r.nick_name or r.user_no or ""), "value": r.id} for r in rows]
out = [
{
"label": (r.nick_name or r.user_no or ""),
"value": r.id,
"deptId": (r.dept_id or ""),
}
for r in rows
]
if prioritizeCallerDept:
out = prioritize_caller_dept_options(out, _user.get("region_id") or "")
return success_response(out)
+80
View File
@@ -0,0 +1,80 @@
"""业务样本:人工作废等跨模块入口。"""
from __future__ import annotations
from typing import Optional
from fastapi import APIRouter, Depends
from pydantic import BaseModel, ConfigDict, Field
from sqlalchemy.orm import Session
from app.core.database import get_db
from app.core.menu_guard import require_admin_or_super_admin
from app.core.response import error_response, success_response
from app.models.models import SysUser
from app.services.protocol_reception_discard_sync import SAMPLE_VOID_STATUS, void_sample_manually
router = APIRouter(prefix="/web/admin", tags=["业务样本"])
class VoidSampleBody(BaseModel):
model_config = ConfigDict(populate_by_name=True)
reception_source: str = Field(..., alias="receptionSource")
void_desc: str = Field(..., alias="voidDesc")
sample_id: Optional[str] = Field(None, alias="sampleId")
sample_code: Optional[str] = Field(None, alias="sampleCode")
protocol_id: Optional[str] = Field(None, alias="protocolId")
def _get_tenant_no(db: Session, user: dict) -> str:
user_id = user.get("user_id")
if not user_id:
raise PermissionError("用户身份信息缺失,无法确定租户")
sys_user = db.query(SysUser).filter(SysUser.id == user_id).first()
if not sys_user or not sys_user.tenant_no:
raise PermissionError("用户租户信息缺失")
return sys_user.tenant_no
def _get_current_user_id(user: dict) -> str:
user_id = user.get("user_id")
if not user_id:
raise PermissionError("用户身份信息缺失")
return str(user_id)
@router.put("/business-samples/void")
async def void_business_sample(
body: VoidSampleBody,
db: Session = Depends(get_db),
user: dict = Depends(require_admin_or_super_admin),
):
try:
tenant_no = _get_tenant_no(db, user)
user_id = _get_current_user_id(user)
sample = void_sample_manually(
db,
source=body.reception_source,
tenant_no=tenant_no,
void_desc=body.void_desc,
user_id=user_id,
sample_id=body.sample_id,
sample_code=body.sample_code,
protocol_id=body.protocol_id,
commit=True,
)
return success_response(
{
"id": sample.id,
"sampleCode": getattr(sample, "sample_code", None) or "",
"sampleStatus": SAMPLE_VOID_STATUS,
"voidDate": getattr(sample, "void_date", None) or "",
"voidDesc": getattr(sample, "void_desc", None) or "",
}
)
except PermissionError as e:
return error_response(403, str(e))
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(400, str(e))
+50 -2
View File
@@ -7,7 +7,7 @@ from app.core.response import success_response
router = APIRouter(prefix="/web/menu", tags=["菜单管理"])
# 与 web-admin/src/router/modules/sqxp.ts 一致:6 个一级菜单分组
# 市场二级顺序:存储服务、科研捐赠、市场基础信息、中试服务、基础实验
# 市场二级顺序:存储服务、科研捐赠、市场基础信息、中试服务、基础实验、器械销售
STATIC_MENU_TREE = [
{
"id": "TOP00000000000000000000000000006",
@@ -375,7 +375,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",
},
},
],
},
],
},
+57
View File
@@ -29,6 +29,7 @@ from app.crud import qc_lab_test_item as lab_svc
from app.crud import qc_inspection_item_template as iit_svc
from app.crud import qc_item_param as param_svc
from app.crud import qc_task_result as result_svc
from app.crud import qc_task_result_change_log as result_change_log_svc
from app.crud import qc_task as task_svc
from app.crud import qc_third_party_company as tpc_svc
from app.crud import qc_third_party_item as tpi_svc
@@ -448,6 +449,7 @@ class TaskCompleteWithResultBody(BaseModel):
third_party_attachments: Optional[str] = Field(None, alias="thirdPartyAttachments")
material_usages: Optional[List[Dict[str, Any]]] = Field(None, alias="materialUsages")
task_status: Optional[str] = Field(None, alias="taskStatus")
operate_batch_id: Optional[str] = Field(None, alias="operateBatchId")
@router.get("/qc-lab-test-items")
@@ -1234,6 +1236,29 @@ async def list_qc_tasks(
return error_response(400, str(e))
@router.get("/qc-tasks/result-change-logs")
async def list_qc_task_result_change_logs_batch(
taskIds: str = Query("", description="逗号分隔的任务ID"),
db: Session = Depends(get_db),
user: dict = Depends(require_any_menu_code(*QC_TASK_READONLY_MENU_CODES)),
):
"""批量查询检测结果修改记录。须注册在 /qc-tasks/{task_id} 之前,避免被当成任务 ID。"""
try:
tenant_no = _get_tenant_no(db, user)
ids = [x.strip() for x in (taskIds or "").split(",") if x.strip()]
if not ids:
return success_response([])
return success_response(
result_change_log_svc.list_task_result_change_logs_by_task_ids(
db, task_ids=ids, tenant_no=tenant_no
)
)
except PermissionError as e:
return error_response(403, str(e))
except Exception as e:
return error_response(400, str(e))
@router.get("/qc-tasks/{task_id}")
async def get_qc_task_detail(
task_id: str,
@@ -1349,6 +1374,26 @@ async def get_task_material_usages(
return error_response(400, str(e))
@router.get("/qc-tasks/{task_id}/result-change-logs")
async def list_qc_task_result_change_logs(
task_id: str,
db: Session = Depends(get_db),
user: dict = Depends(require_any_menu_code(*QC_TASK_READONLY_MENU_CODES)),
):
try:
tenant_no = _get_tenant_no(db, user)
# 无任务或无留痕均返回空列表,避免前端把“暂无记录”当成错误
return success_response(
result_change_log_svc.list_task_result_change_logs(
db, task_id=task_id, tenant_no=tenant_no
)
)
except PermissionError as e:
return error_response(403, str(e))
except Exception as e:
return error_response(400, str(e))
@router.post("/qc-tasks/{task_id}/complete-with-result")
async def complete_task_with_result(
task_id: str,
@@ -1364,6 +1409,7 @@ async def complete_task_with_result(
if not t:
return error_response(404, "任务不存在")
was_done = (t.task_status or "").strip() == "ywc"
before = result_change_log_svc.snapshot_task_result_state(db, t, tenant_no)
if body.results:
result_svc.save_results_for_task(
db, task_id, body.results, tenant_no, user_id, commit=False,
@@ -1384,6 +1430,17 @@ async def complete_task_with_result(
task_status=body.task_status,
commit=False,
)
after = result_change_log_svc.snapshot_task_result_state(db, obj, tenant_no)
result_change_log_svc.append_task_result_change_log(
db,
task=obj,
tenant_no=tenant_no,
user_id=user_id,
operator_user_name=str(user.get("nickName") or user.get("nick_name") or ""),
before=before,
after=after,
operate_batch_id=body.operate_batch_id,
)
db.commit()
db.refresh(obj)
if (obj.task_status or "").strip() == "ywc":
+2
View File
@@ -739,6 +739,7 @@ def _sample_to_dict(s: BizProtocolSample) -> Dict[str, Any]:
"storageInDate": (s.storage_in_date or "").strip() if s.storage_in_date else "",
"detectStartDate": (s.detect_start_date or "").strip() if s.detect_start_date else "",
"voidDate": (s.void_date or "").strip() if s.void_date else "",
"voidDesc": (getattr(s, "void_desc", None) or "").strip() if (getattr(s, "void_desc", None) or "").strip() else "",
"storageExpireDate": (s.storage_expire_date or "").strip() if s.storage_expire_date else "",
**sample_special_to_dict(s),
"tenantNo": s.tenant_no,
@@ -1393,6 +1394,7 @@ def list_collection_protocols(
"sampleTypeName": type_name,
"sampleCode": code,
"sampleStatus": (s.sample_status or "").strip(),
"voidDesc": (getattr(s, "void_desc", None) or "").strip(),
"labStorageCode": lab_code_map.get(code, "") if code else "",
"transport": transport_dict,
"freight": freight_by_sample.get(s.id),
+6
View File
@@ -269,10 +269,13 @@ def _build_cell_system(
clear_flag = checked
break
sample_status = str(getattr(sample, "sample_status", None) or "").strip()
base: Dict[str, Any] = {
"receptionId": rec.id,
"sampleCode": (rec.sample_code or sample.sample_code or "").strip(),
"labStorageCode": (rec.lab_storage_code or "").strip(),
"sampleStatus": sample_status,
"voidDesc": str(getattr(sample, "void_desc", None) or "").strip(),
"motherName": (party.mother_name if party else "") or "",
"collectionTime": ledger.format_cn_datetime(coll.sample_collect_time if coll else None),
"collectionTimeRaw": _fmt_raw(coll.sample_collect_time if coll else None),
@@ -353,10 +356,13 @@ def _build_donation_system(
qc_process: Dict[str, str],
) -> Dict[str, Any]:
prod = prod or {}
sample_status = str(getattr(sample, "sample_status", None) or "").strip()
base: Dict[str, Any] = {
"receptionId": rec.id,
"sampleCode": (rec.sample_code or sample.sample_code or "").strip(),
"labStorageCode": (rec.lab_storage_code or "").strip(),
"sampleStatus": sample_status,
"voidDesc": str(getattr(sample, "void_desc", None) or "").strip(),
"motherName": (party.mother_name if party else "") or "",
"receptionTime": ledger.format_cn_datetime(rec.reception_time),
"receptionTimeRaw": _fmt_raw(rec.reception_time),
@@ -410,7 +410,8 @@ def list_protocol_sample_collections(
item["newbornDeliveryTime"] = _fmt_dt(party.newborn_delivery_time) if party else ""
item["protocolRemark"] = (proto.remark or "") if proto else ""
item["voidType"] = (proto.void_type or "") if proto else ""
item["voidDesc"] = (proto.void_desc or "") if proto else ""
# 样本状态问号展示样本作废原因,不用协议作废描述
item["voidDesc"] = (getattr(psample, "void_desc", None) or "").strip()
item["protocolAttachments"] = (proto.protocol_attachments or "") if proto else ""
item["consentFormUrls"] = (proto.consent_form_urls or "") if proto else ""
item["healthSurveyFormUrls"] = (proto.health_survey_form_urls or "") if proto else ""
+57 -1
View File
@@ -45,6 +45,14 @@ from app.services.sample_payment_progress import (
)
_SAMPLE_STATUS_LABELS = {
"ycj": "已采集",
"jcz": "检测中",
"yrk": "已入库",
"yzf": "已作废",
}
def _fmt_ymd8(v: Any) -> str:
s = str(v or "").strip()
if len(s) == 8 and s.isdigit():
@@ -1882,6 +1890,7 @@ def _build_list_summary_row(
]
receivable = float(sum(active_dues, Decimal("0"))) if active_dues else 0.0
discount = meta.get("discountAmount")
sample_status = str(meta.get("sampleStatus") or "").strip()
row: Dict[str, Any] = {
"id": sp.id,
"collectionProtocolId": sp.collection_protocol_id,
@@ -1891,6 +1900,10 @@ def _build_list_summary_row(
"motherName": (party.mother_name if party else "") or "",
"motherPhone": (party.mother_phone if party else "") or "",
"sampleCode": sp.sample_code or "",
"sampleStatus": sample_status,
"sampleStatusLabel": str(meta.get("sampleStatusLabel") or "").strip()
or _SAMPLE_STATUS_LABELS.get(sample_status, ""),
"voidDesc": str(meta.get("voidDesc") or "").strip(),
"payMode": sp.pay_mode or "",
"contractAmount": float(sp.contract_amount)
if sp.contract_amount is not None
@@ -2020,10 +2033,14 @@ def list_sample_payments_page(
discount = None
if orig is not None and price is not None and orig > price:
discount = round(orig - price, 2)
status = str(s.sample_status or "").strip()
sample_meta_by_key[key] = {
"storageYears": s.storage_years,
"sampleTypeName": type_name_map.get(s.sample_type_id or "", ""),
"discountAmount": discount,
"sampleStatus": status,
"sampleStatusLabel": _SAMPLE_STATUS_LABELS.get(status, ""),
"voidDesc": str(getattr(s, "void_desc", None) or "").strip(),
}
rows: List[Dict[str, Any]] = []
for sp, proto, party in candidates:
@@ -2228,6 +2245,40 @@ def list_payment_chase_page(
for u in db.query(SysUser.id, SysUser.nick_name).filter(SysUser.id.in_(sales_ids)).all():
sales_name_map[u.id] = u.nick_name or ""
sample_codes = list(
{
(sp.sample_code or sch.sample_code or "").strip()
for sch, sp, _, _, _ in candidates
if (sp.sample_code or sch.sample_code or "").strip()
}
)
sample_status_by_code: Dict[str, Dict[str, str]] = {}
if sample_codes:
s_rows = (
db.query(BizProtocolSample)
.filter(
BizProtocolSample.tenant_no == tenant_no,
BizProtocolSample.del_flag == 0,
BizProtocolSample.sample_code.in_(sample_codes),
)
.order_by(
BizProtocolSample.update_time.desc(),
BizProtocolSample.create_time.desc(),
BizProtocolSample.id.desc(),
)
.all()
)
for sample in s_rows:
code = str(sample.sample_code or "").strip()
if not code or code in sample_status_by_code:
continue
status = str(sample.sample_status or "").strip()
sample_status_by_code[code] = {
"sampleStatus": status,
"sampleStatusLabel": _SAMPLE_STATUS_LABELS.get(status, ""),
"voidDesc": str(getattr(sample, "void_desc", None) or "").strip(),
}
ct = (chase_type or "").strip()
rows: List[Dict[str, Any]] = []
for sch, sp, proto, party, ci in candidates:
@@ -2257,6 +2308,8 @@ def list_payment_chase_page(
continue
days_overdue = (today_d - due_d).days if overdue else 0
days_until = (due_d - today_d).days if not overdue else 0
sample_code = sp.sample_code or sch.sample_code or ""
sample_state = sample_status_by_code.get(str(sample_code).strip(), {})
rows.append(
{
"scheduleId": sch.id,
@@ -2265,7 +2318,10 @@ def list_payment_chase_page(
"protocolNo": (proto.protocol_no if proto else "") or "",
"motherName": (party.mother_name if party else "") or "",
"motherPhone": (party.mother_phone if party else "") or "",
"sampleCode": sp.sample_code or sch.sample_code or "",
"sampleCode": sample_code,
"sampleStatus": sample_state.get("sampleStatus", ""),
"sampleStatusLabel": sample_state.get("sampleStatusLabel", ""),
"voidDesc": sample_state.get("voidDesc", ""),
"salesUserId": (ci.sales_user_id if ci else "") or "",
"salesUserName": sales_name_map.get(
(ci.sales_user_id if ci else "") or "", ""
+13
View File
@@ -1095,6 +1095,7 @@ def delete_qc_task(db: Session, task_id: str, tenant_no: str, user_id: Optional[
# 软删除任务结果
from app.models.qc_param import BizQcTaskResult
from app.models.models import BizQcTaskResultChangeLog
results = db.query(BizQcTaskResult).filter(
and_(BizQcTaskResult.task_id == task_id, BizQcTaskResult.del_flag == 0)
@@ -1104,6 +1105,18 @@ def delete_qc_task(db: Session, task_id: str, tenant_no: str, user_id: Optional[
r.update_by = user_id
r.update_time = now
change_logs = db.query(BizQcTaskResultChangeLog).filter(
and_(
BizQcTaskResultChangeLog.task_id == task_id,
BizQcTaskResultChangeLog.tenant_no == tenant_no,
BizQcTaskResultChangeLog.del_flag == 0,
)
).all()
for log in change_logs:
log.del_flag = 1
log.update_by = user_id
log.update_time = now
# 同步软删批次明细行(配置弹窗勾选来源)
_soft_delete_source_line_for_task(
db, task, tenant_no=tenant_no, user_id=user_id, now=now
@@ -0,0 +1,254 @@
"""质检任务检测结果操作留痕"""
from __future__ import annotations
import json
from datetime import datetime
from typing import Any, Dict, List, Optional
from sqlalchemy.orm import Session
from app.core.utils import generate_uuid
from app.models.models import BizQcTask, BizQcTaskResultChangeLog, SysUser
from app.models.qc_param import BizQcTaskResult
_TASK_STATUS_LABELS = {"dzx": "待执行", "jxz": "进行中", "ywc": "已完成"}
_CONCLUSION_LABELS = {"": "待结论", "tg": "通过", "btg": "不通过"}
def _fmt_dt(v: Optional[datetime]) -> str:
if not v:
return ""
return v.strftime("%Y-%m-%d %H:%M:%S")
def _display_status(code: Optional[str]) -> str:
c = (code or "").strip()
return _TASK_STATUS_LABELS.get(c, c or "—")
def _display_conclusion(code: Optional[str]) -> str:
c = (code or "").strip()
return _CONCLUSION_LABELS.get(c, c or "待结论")
def _norm_text(v: Any) -> str:
if v is None:
return ""
return str(v).strip()
def _param_key(param_id: Optional[str], param_code: Optional[str], param_name: Optional[str]) -> str:
pid = _norm_text(param_id)
if pid:
return f"paramId:{pid}"
code = _norm_text(param_code)
if code:
return f"paramCode:{code}"
return f"paramName:{_norm_text(param_name)}"
def snapshot_task_result_state(db: Session, task: BizQcTask, tenant_no: str) -> Dict[str, Any]:
"""保存前快照:任务结论字段 + 已存参数值。"""
rows = (
db.query(BizQcTaskResult)
.filter(
BizQcTaskResult.task_id == task.id,
BizQcTaskResult.tenant_no == tenant_no,
BizQcTaskResult.del_flag == 0,
)
.order_by(BizQcTaskResult.create_time.asc())
.all()
)
params: Dict[str, Dict[str, str]] = {}
for r in rows:
key = _param_key(r.param_id, r.param_code, r.param_name)
params[key] = {
"label": _norm_text(r.param_name) or key,
"value": _norm_text(r.param_value),
}
return {
"taskStatus": _norm_text(task.task_status),
"conclusion": _norm_text(task.conclusion),
"remark": _norm_text(task.remark),
"attachments": _norm_text(task.third_party_attachments),
"params": params,
}
def build_result_changes(
before: Dict[str, Any],
after: Dict[str, Any],
) -> List[Dict[str, str]]:
changes: List[Dict[str, str]] = []
def add(field_key: str, label: str, old_v: str, new_v: str) -> None:
if old_v == new_v:
return
changes.append(
{
"fieldKey": field_key,
"fieldLabel": label,
"oldValue": old_v,
"newValue": new_v,
}
)
add(
"taskStatus",
"任务状态",
_display_status(before.get("taskStatus")),
_display_status(after.get("taskStatus")),
)
add(
"conclusion",
"结论",
_display_conclusion(before.get("conclusion")),
_display_conclusion(after.get("conclusion")),
)
add("remark", "备注", _norm_text(before.get("remark")), _norm_text(after.get("remark")))
add(
"attachments",
"检测材料",
_norm_text(before.get("attachments")),
_norm_text(after.get("attachments")),
)
before_params: Dict[str, Dict[str, str]] = before.get("params") or {}
after_params: Dict[str, Dict[str, str]] = after.get("params") or {}
keys = sorted(set(before_params.keys()) | set(after_params.keys()))
for key in keys:
b = before_params.get(key) or {"label": key, "value": ""}
a = after_params.get(key) or {"label": b.get("label") or key, "value": ""}
label = _norm_text(a.get("label")) or _norm_text(b.get("label")) or key
add(key, label, _norm_text(b.get("value")), _norm_text(a.get("value")))
return changes
def _resolve_operator_name(db: Session, user_id: Optional[str], fallback: str = "") -> str:
uid = _norm_text(user_id)
if not uid:
return _norm_text(fallback)
row = db.query(SysUser.nick_name).filter(SysUser.id == uid).first()
if row and row[0]:
return str(row[0]).strip()
return _norm_text(fallback) or uid
def append_task_result_change_log(
db: Session,
*,
task: BizQcTask,
tenant_no: str,
user_id: Optional[str],
operator_user_name: str = "",
before: Dict[str, Any],
after: Dict[str, Any],
operate_time: Optional[datetime] = None,
operate_batch_id: Optional[str] = None,
) -> BizQcTaskResultChangeLog:
"""追加一条检测结果保存留痕(不 commit)。无字段差异也写入。"""
now = operate_time or datetime.now()
changes = build_result_changes(before, after)
has_change = "1" if changes else "0"
name = _resolve_operator_name(db, user_id, operator_user_name)
batch_id = _norm_text(operate_batch_id) or None
obj = BizQcTaskResultChangeLog(
id=generate_uuid(),
task_id=task.id,
work_order_id=_norm_text(task.work_order_id) or None,
sample_code=_norm_text(task.sample_code) or None,
item_name=_norm_text(task.item_name) or None,
operate_time=now,
operator_user_id=user_id,
operator_user_name=name or None,
operate_batch_id=batch_id,
has_field_change=has_change,
changes_json=json.dumps(changes, ensure_ascii=False),
tenant_no=tenant_no,
order_num=0,
remark=None,
create_by=user_id,
create_dept_id="",
create_time=now,
update_by=user_id,
update_time=now,
del_flag=0,
)
db.add(obj)
return obj
def _row_to_dict(row: BizQcTaskResultChangeLog) -> Dict[str, Any]:
changes: List[Dict[str, Any]] = []
raw = row.changes_json or ""
if raw.strip():
try:
parsed = json.loads(raw)
if isinstance(parsed, list):
changes = parsed
except json.JSONDecodeError:
changes = []
return {
"id": row.id,
"taskId": row.task_id,
"workOrderId": row.work_order_id or "",
"sampleCode": row.sample_code or "",
"itemName": row.item_name or "",
"operateTime": _fmt_dt(row.operate_time),
"operatorUserId": row.operator_user_id or "",
"operatorUserName": row.operator_user_name or "",
"operateBatchId": row.operate_batch_id or "",
"hasFieldChange": row.has_field_change == "1",
"changes": changes,
"createTime": _fmt_dt(row.create_time),
}
def list_task_result_change_logs(
db: Session,
*,
task_id: str,
tenant_no: str,
) -> List[Dict[str, Any]]:
tid = _norm_text(task_id)
if not tid:
return []
rows = (
db.query(BizQcTaskResultChangeLog)
.filter(
BizQcTaskResultChangeLog.task_id == tid,
BizQcTaskResultChangeLog.tenant_no == tenant_no,
BizQcTaskResultChangeLog.del_flag == 0,
)
.order_by(
BizQcTaskResultChangeLog.operate_time.desc(),
BizQcTaskResultChangeLog.create_time.desc(),
)
.all()
)
return [_row_to_dict(r) for r in rows]
def list_task_result_change_logs_by_task_ids(
db: Session,
*,
task_ids: List[str],
tenant_no: str,
) -> List[Dict[str, Any]]:
ids = [_norm_text(x) for x in task_ids if _norm_text(x)]
if not ids:
return []
rows = (
db.query(BizQcTaskResultChangeLog)
.filter(
BizQcTaskResultChangeLog.task_id.in_(ids),
BizQcTaskResultChangeLog.tenant_no == tenant_no,
BizQcTaskResultChangeLog.del_flag == 0,
)
.order_by(
BizQcTaskResultChangeLog.operate_time.desc(),
BizQcTaskResultChangeLog.create_time.desc(),
)
.all()
)
return [_row_to_dict(r) for r in rows]
+53 -5
View File
@@ -679,9 +679,6 @@ def _enrich_work_order_list_items(
code = (r.sample_code or "").strip()
if code and code not in sample_code_rec_map:
sample_code_rec_map[code] = r
if not rec_map and not sample_code_rec_map:
return items
def _resolve_reception(item: Dict[str, Any]) -> Optional[BizSampleReception]:
rec = rec_map.get(item.get("receptionId") or "")
if rec:
@@ -697,7 +694,9 @@ def _enrich_work_order_list_items(
rec = _resolve_reception(item)
source = _effective_reception_source(item, rec)
if source == "research_donation":
dsid = _effective_donation_sample_id(item, rec)
dsid = _effective_donation_sample_id(item, rec) or (
item.get("protocolSampleId") or ""
).strip()
if dsid:
donation_sample_ids.append(dsid)
did = (
@@ -706,7 +705,9 @@ def _enrich_work_order_list_items(
if did:
donation_ids.append(did)
else:
psid = _effective_protocol_sample_id(item, rec)
psid = _effective_protocol_sample_id(item, rec) or (
item.get("protocolSampleId") or ""
).strip()
if psid:
cell_sample_ids.append(psid)
pid = (
@@ -864,11 +865,34 @@ def _enrich_work_order_list_items(
item["motherName"] = _mother
item["newbornName"] = _newborn
item["maternalBloodCollectTime"] = cell_maternal_map.get(_pid or "", "") or ""
def _apply_sample_status_fields() -> None:
sample_obj = None
if source == "research_donation":
dsid = _effective_donation_sample_id(item, rec) or (
item.get("protocolSampleId") or ""
).strip()
sample_obj = donation_samples.get(dsid) if dsid else None
else:
psid = _effective_protocol_sample_id(item, rec) or (
item.get("protocolSampleId") or ""
).strip()
sample_obj = protocol_samples.get(psid) if psid else None
item["sampleStatus"] = (
(sample_obj.sample_status or "").strip() if sample_obj else ""
)
item["voidDesc"] = (
(getattr(sample_obj, "void_desc", None) or "").strip() if sample_obj else ""
)
item["voidDate"] = (
(sample_obj.void_date or "").strip() if sample_obj else ""
)
if not rec:
item.setdefault("receptionTime", "")
item.setdefault("handlerName", "")
item.setdefault("sampleTypeName", "")
item.setdefault("labStorageCode", "")
_apply_sample_status_fields()
continue
item["receptionTime"] = _fmt_dt(rec.reception_time)
item["handlerName"] = rec.handler_name or ""
@@ -889,6 +913,7 @@ def _enrich_work_order_list_items(
protocol_samples=protocol_samples,
donation_samples=donation_samples,
)
_apply_sample_status_fields()
if source == "research_donation":
_did = (
(getattr(rec, "research_donation_id", None) or "").strip()
@@ -2728,6 +2753,16 @@ def _soft_delete_tasks_by_source_line_ids(
{"del_flag": 1, "update_time": now},
synchronize_session="fetch",
)
from app.models.models import BizQcTaskResultChangeLog
db.query(BizQcTaskResultChangeLog).filter(
BizQcTaskResultChangeLog.task_id.in_(task_ids),
BizQcTaskResultChangeLog.tenant_no == tenant_no,
BizQcTaskResultChangeLog.del_flag == 0,
).update(
{"del_flag": 1, "update_time": now},
synchronize_session="fetch",
)
for t in tasks:
t.del_flag = 1
t.update_time = now
@@ -3859,6 +3894,8 @@ def delete_qc_work_order(db: Session, work_order_id: str, tenant_no: str, user_i
).all()
from app.models.qc_param import BizQcTaskResult
from app.models.models import BizQcTaskResultChangeLog
for task in tasks:
results = db.query(BizQcTaskResult).filter(
and_(BizQcTaskResult.task_id == task.id, BizQcTaskResult.del_flag == 0)
@@ -3867,6 +3904,17 @@ def delete_qc_work_order(db: Session, work_order_id: str, tenant_no: str, user_i
r.del_flag = 1
r.update_by = user_id
r.update_time = now
change_logs = db.query(BizQcTaskResultChangeLog).filter(
and_(
BizQcTaskResultChangeLog.task_id == task.id,
BizQcTaskResultChangeLog.tenant_no == tenant_no,
BizQcTaskResultChangeLog.del_flag == 0,
)
).all()
for log in change_logs:
log.del_flag = 1
log.update_by = user_id
log.update_time = now
task.del_flag = 1
task.update_by = user_id
task.update_time = now
+2
View File
@@ -535,6 +535,7 @@ def _sample_to_dict(s: BizResearchDonationSample) -> Dict[str, Any]:
"storageInDate": (s.storage_in_date or "").strip() if s.storage_in_date else "",
"detectStartDate": (s.detect_start_date or "").strip() if s.detect_start_date else "",
"voidDate": (s.void_date or "").strip() if s.void_date else "",
"voidDesc": (getattr(s, "void_desc", None) or "").strip() if (getattr(s, "void_desc", None) or "").strip() else "",
"storageExpireDate": (s.storage_expire_date or "").strip() if s.storage_expire_date else "",
**sample_special_to_dict(s),
"tenantNo": s.tenant_no,
@@ -975,6 +976,7 @@ def list_donations(
"sampleTypeName": type_name,
"sampleCode": code,
"sampleStatus": (s.sample_status or "").strip(),
"voidDesc": (getattr(s, "void_desc", None) or "").strip(),
"labStorageCode": lab_code_map.get(code, "") if code else "",
"transport": transport_dict,
"freight": freight_by_sample.get(s.id),
+29 -2
View File
@@ -194,6 +194,14 @@ def _item_to_dict(item: BizSampleFreightItem) -> Dict[str, Any]:
}
_SAMPLE_STATUS_LABELS = {
"ycj": "已采集",
"jcz": "检测中",
"yrk": "已入库",
"yzf": "已作废",
}
def _item_to_dict_enriched(
item: BizSampleFreightItem,
*,
@@ -201,12 +209,19 @@ def _item_to_dict_enriched(
sample_type_name: str = "",
mother_name: str = "",
newborn_name: str = "",
sample_status: str = "",
void_desc: str = "",
) -> Dict[str, Any]:
data = _item_to_dict(item)
data["protocolNo"] = protocol_no or ""
data["sampleTypeName"] = sample_type_name or ""
data["motherName"] = mother_name or ""
data["newbornName"] = newborn_name or ""
status = str(sample_status or "").strip()
if str(item.sample_code or "").strip():
data["sampleStatus"] = status
data["sampleStatusLabel"] = _SAMPLE_STATUS_LABELS.get(status, "")
data["voidDesc"] = str(void_desc or "").strip()
return data
@@ -257,6 +272,8 @@ def _enrich_items_maps(
BizCellSampleType.type_name,
BizProtocolPartyCustomer.mother_name,
BizProtocolPartyCustomer.newborn_name,
BizProtocolSample.sample_status,
BizProtocolSample.void_desc,
)
.outerjoin(
BizCollectionProtocol,
@@ -287,12 +304,14 @@ def _enrich_items_maps(
)
.all()
)
for sid, pno, tname, mname, nname in rows:
for sid, pno, tname, mname, nname, status, void_desc in rows:
out[f"{SAMPLE_SOURCE_CELL}|{sid}"] = {
"protocolNo": pno or "",
"sampleTypeName": tname or "",
"motherName": mname or "",
"newbornName": nname or "",
"sampleStatus": str(status or "").strip(),
"voidDesc": str(void_desc or "").strip(),
}
if donation_ids:
@@ -303,6 +322,8 @@ def _enrich_items_maps(
BizCellSampleType.type_name,
BizResearchDonationParty.mother_name,
BizResearchDonationParty.newborn_name,
BizResearchDonationSample.sample_status,
BizResearchDonationSample.void_desc,
)
.outerjoin(
BizResearchDonation,
@@ -334,12 +355,14 @@ def _enrich_items_maps(
)
.all()
)
for sid, dno, tname, mname, nname in rows:
for sid, dno, tname, mname, nname, status, void_desc in rows:
out[f"{SAMPLE_SOURCE_DONATION}|{sid}"] = {
"protocolNo": dno or "",
"sampleTypeName": tname or "",
"motherName": mname or "",
"newbornName": nname or "",
"sampleStatus": str(status or "").strip(),
"voidDesc": str(void_desc or "").strip(),
}
return out
@@ -541,6 +564,8 @@ def list_freights(
sample_type_name=info.get("sampleTypeName", ""),
mother_name=info.get("motherName", ""),
newborn_name=info.get("newbornName", ""),
sample_status=info.get("sampleStatus", ""),
void_desc=info.get("voidDesc", ""),
)
)
data["items"] = enriched
@@ -584,6 +609,8 @@ def get_freight_detail(
sample_type_name=info.get("sampleTypeName", ""),
mother_name=info.get("motherName", ""),
newborn_name=info.get("newbornName", ""),
sample_status=info.get("sampleStatus", ""),
void_desc=info.get("voidDesc", ""),
)
)
data["items"] = enriched
+9 -10
View File
@@ -444,6 +444,7 @@ def _rows_to_sample_list_items(
"sampleTypeName": type_map.get(sample.sample_type_id or "", ""),
"collectAmount": _dec(sample.collect_amount),
"sampleStatus": sample.sample_status or "",
"voidDesc": (getattr(sample, "void_desc", None) or "").strip(),
"motherName": (party.mother_name if party else "") or "",
"newbornName": (party.newborn_name if party else "") or "",
"sampleCollectTime": (
@@ -1045,12 +1046,11 @@ def create_sample_reception(
user_id=user_id,
create_dept_id=create_dept_id or "",
)
if conclusion == "bj":
from app.services.protocol_reception_discard_sync import after_sample_reception_saved
from app.services.protocol_reception_discard_sync import after_sample_reception_saved
after_sample_reception_saved(
db, reception=obj, tenant_no=tenant_no, user_id=user_id
)
after_sample_reception_saved(
db, reception=obj, tenant_no=tenant_no, user_id=user_id
)
db.commit()
db.refresh(obj)
return obj
@@ -1169,12 +1169,11 @@ def update_sample_reception(
)
check_result_svc.sync_legacy_columns_from_results(db, rec, saved_rows)
db.add(rec)
if conclusion == "bj":
from app.services.protocol_reception_discard_sync import after_sample_reception_saved
from app.services.protocol_reception_discard_sync import after_sample_reception_saved
after_sample_reception_saved(
db, reception=rec, tenant_no=tenant_no, user_id=user_id
)
after_sample_reception_saved(
db, reception=rec, tenant_no=tenant_no, user_id=user_id
)
db.commit()
db.refresh(rec)
return rec
+2 -1
View File
@@ -13,7 +13,7 @@ from app.core.database import SessionLocal
from app.core.api_request_log_middleware import ApiRequestLogMiddleware
from app.core.api_crypto_middleware import ApiCryptoMiddleware
from app.models import models # noqa: F401
from app.api import public_router, menu_router, admin_router, workflow_router, basic_info_router, collection_protocol_router, protocol_sample_payment_router, protocol_refund_record_router, presign_order_router, sample_freight_router, leave_router, operations_router, ethnic_router, sample_reception_router, sample_production_reception_router, qc_router, research_donation_router, production_router, pilot_service_router, insurance_company_router, material_router, storage_release_review_router, sample_sms_notification_router, storage_entry_sms_notification_router, qc_sms_notification_router, protocol_sample_collection_router, research_donation_sample_collection_router, pilot_application_router, pilot_checkup_router, pilot_delivery_router, pilot_infusion_confirm_router, pilot_infusion_schedule_mgmt_router, outbound_release_review_router, clinical_payment_router, env_detect_router, cleanroom_garment_router, market_router, pre_transit_sample_router, oa_approval_router, mini_auth_router, mini_menu_router, market_mobile_router, sample_storage_cert_qc_router, customer_service_dict_router, sample_cert_insurance_router, sample_code_correction_router, lab_sample_process_router, lab_sample_processing_router, project_management_router
from app.api import public_router, menu_router, admin_router, workflow_router, basic_info_router, collection_protocol_router, protocol_sample_payment_router, protocol_refund_record_router, presign_order_router, sample_freight_router, leave_router, operations_router, ethnic_router, sample_reception_router, sample_production_reception_router, qc_router, research_donation_router, production_router, pilot_service_router, insurance_company_router, material_router, storage_release_review_router, sample_sms_notification_router, storage_entry_sms_notification_router, qc_sms_notification_router, protocol_sample_collection_router, research_donation_sample_collection_router, pilot_application_router, pilot_checkup_router, pilot_delivery_router, pilot_infusion_confirm_router, pilot_infusion_schedule_mgmt_router, outbound_release_review_router, clinical_payment_router, env_detect_router, cleanroom_garment_router, market_router, pre_transit_sample_router, oa_approval_router, mini_auth_router, mini_menu_router, market_mobile_router, sample_storage_cert_qc_router, customer_service_dict_router, sample_cert_insurance_router, sample_code_correction_router, lab_sample_process_router, lab_sample_processing_router, project_management_router, business_sample_router
@asynccontextmanager
@@ -125,6 +125,7 @@ app.include_router(leave_router, prefix=settings.API_V1_PREFIX)
app.include_router(operations_router, prefix=settings.API_V1_PREFIX)
app.include_router(ethnic_router, prefix=settings.API_V1_PREFIX)
app.include_router(sample_reception_router, prefix=settings.API_V1_PREFIX)
app.include_router(business_sample_router, prefix=settings.API_V1_PREFIX)
app.include_router(sample_production_reception_router, prefix=settings.API_V1_PREFIX)
app.include_router(qc_router, prefix=settings.API_V1_PREFIX)
app.include_router(research_donation_router, prefix=settings.API_V1_PREFIX)
+28
View File
@@ -1597,6 +1597,7 @@ class BizProtocolSample(Base):
storage_in_date = Column(CHAR(8), nullable=True, comment="入库日期YYYYMMDD")
detect_start_date = Column(CHAR(8), nullable=True, comment="检测开始日期YYYYMMDD")
void_date = Column(CHAR(8), nullable=True, comment="作废日期YYYYMMDD")
void_desc = Column(String(512), nullable=True, comment="样本作废原因")
storage_expire_date = Column(CHAR(8), nullable=True, comment="存储到期日期YYYYMMDD")
is_special = Column(SmallInteger, nullable=False, default=0, comment="是否特殊样本:0否 1是")
special_remark = Column(String(256), nullable=True, comment="特殊说明")
@@ -2393,6 +2394,33 @@ class BizQcTask(Base):
del_flag = Column(SmallInteger, nullable=False, default=0, comment="删除标记")
class BizQcTaskResultChangeLog(Base):
"""质检任务检测结果操作留痕 biz_qc_task_result_change_log(Issue #148/#149)"""
__tablename__ = "biz_qc_task_result_change_log"
id = Column(String(64), primary_key=True, comment="主键ID")
task_id = Column(String(64), nullable=False, comment="质检任务ID")
work_order_id = Column(String(64), nullable=True, comment="质检工单ID快照")
sample_code = Column(String(32), nullable=True, comment="样本编码快照")
item_name = Column(String(200), nullable=True, comment="检测项目名称快照")
operate_time = Column(DateTime, nullable=False, comment="业务操作时间")
operator_user_id = Column(String(64), nullable=True, comment="操作人用户ID")
operator_user_name = Column(String(64), nullable=True, comment="操作人姓名快照")
operate_batch_id = Column(String(64), nullable=True, comment="同一次保存批次ID(多任务共用)")
has_field_change = Column(CHAR(1), nullable=False, default="0", comment="1有字段变更 0仅保存无变更")
changes_json = Column(Text, nullable=True, comment="变更明细JSON")
tenant_no = Column(String(64), nullable=False, default="zkxw", comment="租户编号")
order_num = Column(Integer, nullable=True, comment="排序号")
remark = Column(String(512), nullable=True, comment="备注")
create_by = Column(String(64), nullable=True, comment="创建人id")
create_dept_id = Column(String(64), nullable=False, default="", comment="创建人部门ID")
create_time = Column(DateTime, nullable=False, default=datetime.now, comment="创建时间")
update_by = Column(String(64), nullable=True, comment="更新人id")
update_time = Column(DateTime, nullable=False, default=datetime.now, onupdate=datetime.now, comment="更新时间")
del_flag = Column(SmallInteger, nullable=False, default=0, comment="删除标记")
class BizQcTaskAssignee(Base):
"""质检任务负责人 biz_qc_task_assignee"""
+1
View File
@@ -175,6 +175,7 @@ class BizResearchDonationSample(Base):
storage_in_date = Column(String(8), nullable=True, comment="入库日期YYYYMMDD")
detect_start_date = Column(String(8), nullable=True, comment="检测开始日期YYYYMMDD")
void_date = Column(String(8), nullable=True, comment="作废日期YYYYMMDD")
void_desc = Column(String(512), nullable=True, comment="样本作废原因")
storage_expire_date = Column(String(8), nullable=True, comment="存储到期日期YYYYMMDD")
is_special = Column(SmallInteger, nullable=False, default=0, comment="是否特殊样本:0否 1是")
special_remark = Column(String(256), nullable=True, comment="特殊说明")
+15 -2
View File
@@ -56,6 +56,12 @@ from app.services.web_auth_roles import (
CELL = 'cell_storage'
DONATION = 'research_donation'
SOURCES = (CELL, DONATION)
_SAMPLE_STATUS_LABELS = {
'ycj': '已采集',
'jcz': '检测中',
'yrk': '已入库',
'yzf': '已作废',
}
def _current_tenant_user_info(
@@ -265,18 +271,25 @@ def _visible_rows(db: Session, freight_ids: List[str], ctx: MarketFieldContext,
def _item_dict(row) -> Dict[str, Any]:
item, sample, parent, party, sample_type = row
source = item.sample_source
return {
sample_code = sample.sample_code or ''
payload = {
'id': item.id,
'freightId': item.freight_id,
'sampleSource': source,
'sampleId': sample.id,
'sampleCode': sample.sample_code or '',
'sampleCode': sample_code,
'protocolId': parent.id,
'protocolNo': (parent.protocol_no if source == CELL else parent.donation_no) or '',
'sampleTypeName': sample_type.type_name if sample_type else '',
'motherName': party.mother_name if party else '',
'newbornName': party.newborn_name if party else '',
}
if sample_code:
status = str(getattr(sample, 'sample_status', None) or '').strip()
payload['sampleStatus'] = status
payload['sampleStatusLabel'] = _SAMPLE_STATUS_LABELS.get(status, '')
payload['voidDesc'] = str(getattr(sample, 'void_desc', None) or '')
return payload
def _label_map(db: Session, tenant_no: str, values: List[str]) -> Dict[str, str]:
+77 -3
View File
@@ -40,6 +40,51 @@ from app.services.market_support import (
)
_SAMPLE_STATUS_LABELS = {
'ycj': '已采集',
'jcz': '检测中',
'yrk': '已入库',
'yzf': '已作废',
}
def _sample_status_by_code(
db: Session,
tenant_no: str,
sample_codes: List[str],
) -> Dict[str, Dict[str, str]]:
"""按租户 + 样本编码取样本状态;同一编码多行时保留最近更新的一条。"""
wanted = [code for code in {str(code or '').strip() for code in sample_codes} if code]
if not wanted:
return {}
rows = (
db.query(BizProtocolSample)
.filter(
BizProtocolSample.tenant_no == tenant_no,
BizProtocolSample.del_flag == 0,
BizProtocolSample.sample_code.in_(wanted),
)
.order_by(
BizProtocolSample.update_time.desc(),
BizProtocolSample.create_time.desc(),
BizProtocolSample.id.desc(),
)
.all()
)
result: Dict[str, Dict[str, str]] = {}
for sample in rows:
code = str(sample.sample_code or '').strip()
if not code or code in result:
continue
status = str(sample.sample_status or '').strip()
result[code] = {
'sampleStatus': status,
'sampleStatusLabel': _SAMPLE_STATUS_LABELS.get(status, ''),
'voidDesc': sample.void_desc or '',
}
return result
def _current_dept_id(user_info: dict) -> str:
return str(
user_info.get('dept_id')
@@ -104,12 +149,16 @@ def _load_sample_meta(
discount = None
if original is not None and current is not None and original > current:
discount = original - current
status = str(sample.sample_status or '').strip()
result.setdefault(
sample.sample_code or '',
{
'storageYears': sample.storage_years,
'sampleTypeName': sample_type.type_name if sample_type else '',
'discountAmount': _money(discount),
'sampleStatus': status,
'sampleStatusLabel': _SAMPLE_STATUS_LABELS.get(status, ''),
'voidDesc': sample.void_desc or '',
},
)
return result
@@ -235,7 +284,8 @@ def _payment_dict(
'bfyj': '部分已缴',
'dfj': '待缴费',
}[progress_code]
return {
sample_code = payment.sample_code or ''
payload = {
'id': payment.id,
'collectionProtocolId': protocol.id,
'protocolNo': protocol.protocol_no or '',
@@ -243,7 +293,7 @@ def _payment_dict(
'paymentModelVersion': int(getattr(protocol, 'payment_model_version', None) or 1),
'motherName': (party.mother_name if party else '') or '',
'motherPhone': (party.mother_phone if party else '') or '',
'sampleCode': payment.sample_code or '',
'sampleCode': sample_code,
'payMode': payment.pay_mode or '',
'contractAmount': _money(payment.contract_amount),
'signDate': _display_ymd(getattr(protocol, 'register_date', None)),
@@ -262,6 +312,11 @@ def _payment_dict(
'periods': periods,
'schedules': schedule_rows,
}
if sample_code:
payload['sampleStatus'] = meta.get('sampleStatus') or ''
payload['sampleStatusLabel'] = meta.get('sampleStatusLabel') or ''
payload['voidDesc'] = meta.get('voidDesc') or ''
return payload
def _scoped_payment_query(
@@ -733,6 +788,14 @@ def list_payment_chase(
)
}
rows: List[Dict[str, Any]] = []
status_by_code = _sample_status_by_code(
db,
ctx.tenant_no,
[
payment.sample_code or schedule.sample_code or ''
for schedule, payment, _, _, _, _ in candidates
],
)
for schedule, payment, protocol, party, collection, paid in candidates:
due_date = parse_due_date_ymd(schedule.due_date)
if due_date is None:
@@ -741,6 +804,8 @@ def list_payment_chase(
due_value = Decimal(str(schedule.due_amount or 0))
arrears = max(due_value - paid_value, Decimal('0'))
is_overdue = due_date < today_value
sample_code = payment.sample_code or schedule.sample_code or ''
sample_state = status_by_code.get(sample_code, {}) if sample_code else {}
rows.append(
{
'scheduleId': schedule.id,
@@ -750,7 +815,16 @@ def list_payment_chase(
'protocolStatus': protocol.protocol_status or '',
'motherName': (party.mother_name if party else '') or '',
'motherPhone': (party.mother_phone if party else '') or '',
'sampleCode': payment.sample_code or schedule.sample_code or '',
'sampleCode': sample_code,
**(
{
'sampleStatus': sample_state.get('sampleStatus', ''),
'sampleStatusLabel': sample_state.get('sampleStatusLabel', ''),
'voidDesc': sample_state.get('voidDesc', ''),
}
if sample_code
else {}
),
'salesUserId': collection.sales_user_id or '',
'salesUserName': sales_user_names.get(
collection.sales_user_id or '', ''
+18
View File
@@ -641,6 +641,14 @@ def _party_name_donation(db: Session, ids: List[str], tenant_no: str) -> dict:
return {row.research_donation_id: row.mother_name or '' for row in rows}
_SAMPLE_STATUS_LABELS = {
'ycj': '已采集',
'jcz': '检测中',
'yrk': '已入库',
'yzf': '已作废',
}
def _enrich_protocol_cards(
db: Session, items: List[dict], tenant_no: str
) -> None:
@@ -795,6 +803,11 @@ def _enrich_protocol_cards(
payment_summary = payment_summaries.get(item['id']) or {}
transport = transport_by_sample.get(getattr(sample, 'id', ''))
sample_code = getattr(sample, 'sample_code', '') or ''
sample_status = ''
sample_void_desc = ''
if sample_code:
sample_status = str(getattr(sample, 'sample_status', None) or '').strip()
sample_void_desc = str(getattr(sample, 'void_desc', None) or '')
region_manager_name = user_names.get(
getattr(collection, 'region_manager_user_id', ''), ''
)
@@ -844,6 +857,11 @@ def _enrich_protocol_cards(
str(item.get('voidType') or ''), ''
),
)
if sample_code:
# 样本作废原因与协议级 voidDesc 分开,捐赠列表「废弃原因」仍读协议描述。
item['sampleStatus'] = sample_status
item['sampleStatusLabel'] = _SAMPLE_STATUS_LABELS.get(sample_status, '')
item['sampleVoidDesc'] = sample_void_desc
def list_protocols(
@@ -1,10 +1,15 @@
"""市场协议无效态 ↔ 样本接收废弃 / 样本状态作废联动。
规则(细胞存储 / 科研捐赠):
1. 协议变为已作废(yzf)或属地废弃(sdfq)时:
1. 单条样本接收结论为废弃(bj)时:仅该样本 `sample_status` 置为已作废(yzf),
写 `void_date`,并将接收备注写入 `void_desc`(备注为空则作废原因为空);
协议状态保持不变。接收结论改回接收(js)且协议仍有效时:若该样本为 yzf,则清空状态、void_date 与 void_desc。
2. 协议变为已作废(yzf)或属地废弃(sdfq)时:
- 协议下全部样本接收结论自动为废弃(bj);
- 协议下全部有效样本 `sample_status` 置为已作废(yzf),并写入 `void_date`。
2. 协议下全部有效样本均已废弃/拒收(bj)时,协议自动已作废,作废类型为「实验室废弃」。
3. 协议下全部有效样本均已废弃/拒收(bj)时,协议自动已作废,作废类型为「实验室废弃」。
4. 人工【样本废弃】:仅将该样本置 yzf 并写 void_date/void_desc,不改接收结论;
若协议下有效样本全部为 yzf,则自动作废协议(不联动接收结论)。
"""
from __future__ import annotations
@@ -30,6 +35,7 @@ SAMPLE_VOID_STATUS = "yzf"
_AUTO_DISCARD_REMARK = "协议作废自动废弃"
_AUTO_VOID_DESC = "全部样本接收废弃/拒收,系统自动作废"
_AUTO_VOID_BY_SAMPLE_STATUS_DESC = "全部样本已作废,系统自动作废协议"
def _void_date_yyyymmdd(
@@ -471,6 +477,165 @@ def maybe_void_protocol_when_all_samples_discarded(
return True
def _find_sample_for_reception(
db: Session,
*,
reception: BizSampleReception,
tenant_no: str,
) -> tuple[str, Optional[Union[BizProtocolSample, BizResearchDonationSample]]]:
source = (reception.reception_source or "cell_storage").strip() or "cell_storage"
tenant = (tenant_no or "").strip()
code = (reception.sample_code or "").strip()
if source == "cell_storage":
sid = (reception.protocol_sample_id or "").strip()
if sid:
obj = (
db.query(BizProtocolSample)
.filter(
BizProtocolSample.id == sid,
BizProtocolSample.tenant_no == tenant,
BizProtocolSample.del_flag == 0,
)
.first()
)
if obj:
return source, obj
pid = (reception.collection_protocol_id or "").strip()
if code and pid:
return source, (
db.query(BizProtocolSample)
.filter(
BizProtocolSample.collection_protocol_id == pid,
BizProtocolSample.sample_code == code,
BizProtocolSample.tenant_no == tenant,
BizProtocolSample.del_flag == 0,
)
.first()
)
return source, None
sid = (reception.donation_sample_id or "").strip()
if sid:
obj = (
db.query(BizResearchDonationSample)
.filter(
BizResearchDonationSample.id == sid,
BizResearchDonationSample.tenant_no == tenant,
BizResearchDonationSample.del_flag == 0,
)
.first()
)
if obj:
return source, obj
pid = (reception.research_donation_id or "").strip()
if code and pid:
return source, (
db.query(BizResearchDonationSample)
.filter(
BizResearchDonationSample.research_donation_id == pid,
BizResearchDonationSample.sample_code == code,
BizResearchDonationSample.tenant_no == tenant,
BizResearchDonationSample.del_flag == 0,
)
.first()
)
return source, None
def _protocol_is_inactive(
db: Session,
*,
source: str,
protocol_id: str,
tenant_no: str,
) -> bool:
src = (source or "").strip()
pid = (protocol_id or "").strip()
tenant = (tenant_no or "").strip()
if not pid or not tenant:
return False
if src == "cell_storage":
obj = (
db.query(BizCollectionProtocol)
.filter(
BizCollectionProtocol.id == pid,
BizCollectionProtocol.tenant_no == tenant,
BizCollectionProtocol.del_flag == 0,
)
.first()
)
status = (obj.protocol_status or "").strip() if obj else ""
else:
obj = (
db.query(BizResearchDonation)
.filter(
BizResearchDonation.id == pid,
BizResearchDonation.tenant_no == tenant,
BizResearchDonation.del_flag == 0,
)
.first()
)
status = (obj.donation_status or "").strip() if obj else ""
return status in INACTIVE_PROTOCOL_STATUSES
def void_sample_for_discarded_reception(
db: Session,
*,
reception: BizSampleReception,
tenant_no: str,
user_id: Optional[str] = None,
) -> bool:
"""单条接收废弃:将该样本置为已作废,作废原因取接收备注。"""
_source, sample = _find_sample_for_reception(db, reception=reception, tenant_no=tenant_no)
if not sample:
return False
now = datetime.now()
reason = (reception.remark or "").strip()
if len(reason) > 512:
reason = reason[:512]
sample.sample_status = SAMPLE_VOID_STATUS
sample.void_date = _void_date_yyyymmdd(void_time=reception.reception_time or now)
sample.void_desc = reason or None
sample.update_by = user_id
sample.update_time = now
db.add(sample)
db.flush()
return True
def clear_sample_void_for_accepted_reception(
db: Session,
*,
reception: BizSampleReception,
tenant_no: str,
user_id: Optional[str] = None,
) -> bool:
"""接收改回接收:协议仍有效且样本为 yzf 时,清空样本作废状态。"""
source, sample = _find_sample_for_reception(db, reception=reception, tenant_no=tenant_no)
if not sample:
return False
if (sample.sample_status or "").strip() != SAMPLE_VOID_STATUS:
return False
if source == "cell_storage":
protocol_id = (reception.collection_protocol_id or "").strip()
else:
protocol_id = (reception.research_donation_id or "").strip()
if _protocol_is_inactive(
db, source=source, protocol_id=protocol_id, tenant_no=tenant_no
):
return False
now = datetime.now()
sample.sample_status = None
sample.void_date = None
sample.void_desc = None
sample.update_by = user_id
sample.update_time = now
db.add(sample)
db.flush()
return True
def after_sample_reception_saved(
db: Session,
*,
@@ -478,23 +643,32 @@ def after_sample_reception_saved(
tenant_no: str,
user_id: Optional[str] = None,
) -> None:
"""样本接收保存后:若结论为废弃,尝试自动作废所属协议。"""
if (reception.accept_conclusion or "").strip() != "bj":
return
"""样本接收保存后:同步该样本状态;若全部废弃则尝试自动作废协议。"""
conclusion = (reception.accept_conclusion or "").strip()
source = (reception.reception_source or "cell_storage").strip() or "cell_storage"
if source == "cell_storage":
protocol_id = (reception.collection_protocol_id or "").strip()
else:
protocol_id = (reception.research_donation_id or "").strip()
if not protocol_id:
if conclusion == "bj":
void_sample_for_discarded_reception(
db, reception=reception, tenant_no=tenant_no, user_id=user_id
)
if protocol_id:
maybe_void_protocol_when_all_samples_discarded(
db,
source=source,
protocol_id=protocol_id,
tenant_no=tenant_no,
user_id=user_id,
)
return
maybe_void_protocol_when_all_samples_discarded(
db,
source=source,
protocol_id=protocol_id,
tenant_no=tenant_no,
user_id=user_id,
)
if conclusion == "js":
clear_sample_void_for_accepted_reception(
db, reception=reception, tenant_no=tenant_no, user_id=user_id
)
def after_protocol_voided(
@@ -523,3 +697,224 @@ def after_protocol_voided(
db, source=source, protocol_id=protocol_id, tenant_no=tenant_no
),
)
def _all_samples_status_voided(
db: Session,
*,
source: str,
protocol_id: str,
tenant_no: str,
) -> bool:
src = (source or "").strip()
if src == "cell_storage":
samples = _list_cell_samples(db, protocol_id=protocol_id, tenant_no=tenant_no)
else:
samples = _list_donation_samples(db, donation_id=protocol_id, tenant_no=tenant_no)
if not samples:
return False
for sample in samples:
if (sample.sample_status or "").strip() != SAMPLE_VOID_STATUS:
return False
return True
def maybe_void_protocol_when_all_samples_status_voided(
db: Session,
*,
source: str,
protocol_id: str,
tenant_no: str,
user_id: Optional[str] = None,
) -> bool:
"""若协议下有效样本全部已作废,则自动作废协议;不联动接收结论。"""
src = (source or "").strip()
pid = (protocol_id or "").strip()
tenant = (tenant_no or "").strip()
if src not in ("cell_storage", "research_donation") or not pid or not tenant:
return False
if not _all_samples_status_voided(db, source=src, protocol_id=pid, tenant_no=tenant):
return False
void_type = ensure_lab_void_type(db, tenant_no=tenant)
now = datetime.now()
if src == "cell_storage":
obj = (
db.query(BizCollectionProtocol)
.filter(
BizCollectionProtocol.id == pid,
BizCollectionProtocol.tenant_no == tenant,
BizCollectionProtocol.del_flag == 0,
)
.first()
)
if not obj:
return False
status = (obj.protocol_status or "").strip()
if status in INACTIVE_PROTOCOL_STATUSES:
return False
from app.core.protocol_status_display import assert_protocol_status_transition
from app.crud.collection_protocol import update_collection_protocol
try:
assert_protocol_status_transition(status, "yzf", kind="protocol")
except ValueError:
return False
update_collection_protocol(
db,
pid,
tenant_no=tenant,
user_id=user_id,
protocol_status="yzf",
void_time=now,
void_desc=_AUTO_VOID_BY_SAMPLE_STATUS_DESC,
void_type=void_type,
commit=False,
sync_reception_discard=False,
)
return True
obj = (
db.query(BizResearchDonation)
.filter(
BizResearchDonation.id == pid,
BizResearchDonation.tenant_no == tenant,
BizResearchDonation.del_flag == 0,
)
.first()
)
if not obj:
return False
status = (obj.donation_status or "").strip()
if status in INACTIVE_PROTOCOL_STATUSES:
return False
from app.core.protocol_status_display import assert_protocol_status_transition
from app.crud.dict_data import normalize_void_type
from app.crud.research_donation import (
_DONATION_STATUS_CHANGE_TYPE,
append_donation_status_change,
)
current = obj.donation_status or ""
try:
assert_protocol_status_transition(current, "yzf", kind="donation")
except ValueError:
return False
normalized = normalize_void_type(db, value=void_type, tenant_no=tenant)
obj.donation_status = "yzf"
obj.void_time = now
obj.void_desc = _AUTO_VOID_BY_SAMPLE_STATUS_DESC
obj.void_type = normalized
obj.update_by = user_id
obj.update_time = now
change_type = _DONATION_STATUS_CHANGE_TYPE.get("yzf")
if change_type:
append_donation_status_change(
db,
research_donation_id=obj.id,
change_type=change_type,
from_status=current,
to_status="yzf",
change_time=now,
change_desc=_AUTO_VOID_BY_SAMPLE_STATUS_DESC,
void_type=normalized,
tenant_no=tenant,
user_id=user_id,
)
db.add(obj)
db.flush()
return True
def void_sample_manually(
db: Session,
*,
source: str,
tenant_no: str,
void_desc: str,
user_id: Optional[str] = None,
sample_id: Optional[str] = None,
sample_code: Optional[str] = None,
protocol_id: Optional[str] = None,
commit: bool = True,
) -> Union[BizProtocolSample, BizResearchDonationSample]:
"""人工样本废弃:写 yzf/void_date/void_desc;不改接收;全作废则自动作废协议。"""
src = (source or "").strip()
tenant = (tenant_no or "").strip()
reason = (void_desc or "").strip()
sid = (sample_id or "").strip()
code = (sample_code or "").strip()
pid = (protocol_id or "").strip()
if src not in ("cell_storage", "research_donation"):
raise ValueError("来源类型无效")
if not tenant:
raise ValueError("租户编号不能为空")
if not reason:
raise ValueError("请填写作废原因")
if not sid and not code:
raise ValueError("样本标识不能为空")
now = datetime.now()
sample: Optional[Union[BizProtocolSample, BizResearchDonationSample]] = None
parent_id = ""
if src == "cell_storage":
q = db.query(BizProtocolSample).filter(
BizProtocolSample.tenant_no == tenant,
BizProtocolSample.del_flag == 0,
)
if sid:
q = q.filter(BizProtocolSample.id == sid)
else:
q = q.filter(BizProtocolSample.sample_code == code)
if pid:
q = q.filter(BizProtocolSample.collection_protocol_id == pid)
sample = q.first()
if not sample:
raise ValueError("样本不存在")
parent_id = (sample.collection_protocol_id or "").strip()
else:
q = db.query(BizResearchDonationSample).filter(
BizResearchDonationSample.tenant_no == tenant,
BizResearchDonationSample.del_flag == 0,
)
if sid:
q = q.filter(BizResearchDonationSample.id == sid)
else:
q = q.filter(BizResearchDonationSample.sample_code == code)
if pid:
q = q.filter(BizResearchDonationSample.research_donation_id == pid)
sample = q.first()
if not sample:
raise ValueError("样本不存在")
parent_id = (sample.research_donation_id or "").strip()
if _protocol_is_inactive(db, source=src, protocol_id=parent_id, tenant_no=tenant):
raise ValueError("所属协议已作废或属地废弃,无法操作")
sample.sample_status = SAMPLE_VOID_STATUS
sample.void_date = _void_date_yyyymmdd(void_time=now)
sample.void_desc = reason
sample.update_by = user_id
sample.update_time = now
db.add(sample)
db.flush()
if parent_id:
maybe_void_protocol_when_all_samples_status_voided(
db,
source=src,
protocol_id=parent_id,
tenant_no=tenant,
user_id=user_id,
)
if commit:
db.commit()
db.refresh(sample)
else:
db.flush()
return sample
@@ -0,0 +1,19 @@
"""用户下拉选项:同部门优先排序等轻量辅助。"""
from __future__ import annotations
from typing import Any, Dict, List, Sequence
def prioritize_caller_dept_options(
options: Sequence[Dict[str, Any]],
caller_dept_id: str,
) -> List[Dict[str, Any]]:
"""稳定排序:当前登录用户同部门在前,其余保持原相对顺序。"""
items = list(options)
dept = (caller_dept_id or "").strip()
if not dept or not items:
return items
return sorted(
items,
key=lambda item: 0 if str(item.get("deptId") or "").strip() == dept else 1,
)
+211
View File
@@ -0,0 +1,211 @@
"""人工样本废弃:写状态/原因,全作废则协议作废,不联动接收。"""
from __future__ import annotations
import unittest
from datetime import datetime
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from app.core.database import Base
from app.models.models import (
BizCollectionProtocol,
BizProtocolSample,
BizProtocolStatusChange,
BizSampleReception,
SysDictData,
)
from app.services.protocol_reception_discard_sync import (
LAB_VOID_TYPE_CODE,
SAMPLE_VOID_STATUS,
void_sample_manually,
)
def _session():
engine = create_engine("sqlite://")
Base.metadata.create_all(
bind=engine,
tables=[
SysDictData.__table__,
BizCollectionProtocol.__table__,
BizProtocolSample.__table__,
BizProtocolStatusChange.__table__,
BizSampleReception.__table__,
],
)
return sessionmaker(bind=engine)()
def _now():
return datetime(2026, 11, 19, 12, 0, 0)
class TestBusinessSampleVoid(unittest.TestCase):
def test_void_one_sample_keeps_protocol_and_skips_reception(self):
db = _session()
now = _now()
db.add(
BizCollectionProtocol(
id="p1",
protocol_no="CP-1",
protocol_status="sxz",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
db.add(
BizProtocolSample(
id="sa",
collection_protocol_id="p1",
sample_code="A001",
sample_status="ycj",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
db.add(
BizProtocolSample(
id="sb",
collection_protocol_id="p1",
sample_code="B001",
sample_status="ycj",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
db.add(
BizSampleReception(
id="ra",
protocol_sample_id="sa",
collection_protocol_id="p1",
reception_time=now,
accept_conclusion="js",
reception_source="cell_storage",
sample_code="A001",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
check_packaging=0,
check_sealing=0,
check_no_damage=0,
check_no_leakage=0,
check_color=0,
check_tying_rope=0,
check_no_stratification=0,
)
)
db.commit()
void_sample_manually(
db,
source="cell_storage",
tenant_no="tenant-a",
void_desc="质检发现污染",
user_id="u1",
sample_id="sa",
)
a = db.query(BizProtocolSample).filter(BizProtocolSample.id == "sa").one()
b = db.query(BizProtocolSample).filter(BizProtocolSample.id == "sb").one()
proto = db.query(BizCollectionProtocol).filter(BizCollectionProtocol.id == "p1").one()
rec = db.query(BizSampleReception).filter(BizSampleReception.id == "ra").one()
self.assertEqual(a.sample_status, SAMPLE_VOID_STATUS)
self.assertEqual(a.void_desc, "质检发现污染")
self.assertTrue((a.void_date or "").strip())
self.assertEqual(b.sample_status, "ycj")
self.assertEqual(proto.protocol_status, "sxz")
self.assertEqual(rec.accept_conclusion, "js")
def test_void_all_samples_auto_voids_protocol_without_reception_change(self):
db = _session()
now = _now()
db.add(
BizCollectionProtocol(
id="p2",
protocol_no="CP-2",
protocol_status="sxz",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
for sid, code in (("s1", "C001"), ("s2", "C002")):
db.add(
BizProtocolSample(
id=sid,
collection_protocol_id="p2",
sample_code=code,
sample_status="ycj",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
db.add(
BizSampleReception(
id="r1",
protocol_sample_id="s1",
collection_protocol_id="p2",
reception_time=now,
accept_conclusion="js",
reception_source="cell_storage",
sample_code="C001",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
check_packaging=0,
check_sealing=0,
check_no_damage=0,
check_no_leakage=0,
check_color=0,
check_tying_rope=0,
check_no_stratification=0,
)
)
db.commit()
void_sample_manually(
db,
source="cell_storage",
tenant_no="tenant-a",
void_desc="原因1",
sample_id="s1",
commit=True,
)
void_sample_manually(
db,
source="cell_storage",
tenant_no="tenant-a",
void_desc="原因2",
sample_id="s2",
commit=True,
)
proto = db.query(BizCollectionProtocol).filter(BizCollectionProtocol.id == "p2").one()
rec = db.query(BizSampleReception).filter(BizSampleReception.id == "r1").one()
self.assertEqual(proto.protocol_status, "yzf")
self.assertEqual(proto.void_type, LAB_VOID_TYPE_CODE)
self.assertEqual(rec.accept_conclusion, "js")
if __name__ == "__main__":
unittest.main()
+61
View File
@@ -3,6 +3,7 @@ from __future__ import annotations
import unittest
from datetime import datetime
from types import SimpleNamespace
from app.services.lab_sample_process import (
format_cn_datetime,
@@ -38,5 +39,65 @@ class LabSampleProcessServiceTests(unittest.TestCase):
self.assertEqual(merged["motherName"], "张三")
class LabSampleProcessRowStatusTests(unittest.TestCase):
def test_cell_and_donation_rows_expose_sample_status(self):
from app.crud.lab_sample_process import (
_build_cell_system,
_build_donation_system,
)
rec = SimpleNamespace(
id="r1",
sample_code="S1",
lab_storage_code="B0000108",
reception_time=None,
receive_temperature="",
handler_name="",
remark="",
create_time=None,
)
sample = SimpleNamespace(
sample_code="S1",
sample_status="yrk",
void_desc="",
)
voided = SimpleNamespace(
sample_code="S2",
sample_status="yzf",
void_desc="溶血",
)
cell = _build_cell_system(
tab_key="cell_hsc",
rec=rec,
sample=sample,
party=None,
coll=None,
protocol=None,
prod={},
hospital_name="",
check_flags={},
storage_status="已入库",
qc_mother={},
qc_process={},
)
self.assertEqual(cell["sampleStatus"], "yrk")
self.assertEqual(cell["voidDesc"], "")
self.assertEqual(cell["cellCode"], "B0000108")
donation = _build_donation_system(
tab_key="donation_hsc",
rec=rec,
sample=voided,
party=None,
coll=None,
prod={},
storage_status="",
qc_mother={},
qc_process={},
)
self.assertEqual(donation["sampleStatus"], "yzf")
self.assertEqual(donation["voidDesc"], "溶血")
if __name__ == "__main__":
unittest.main()
@@ -99,12 +99,20 @@ def test_specialist_sees_shared_batch_but_only_own_items_and_count():
from app.services.market_freight import get_freight_detail, list_freights
db = _session()
own, own_parent = _sample(db, 'own')
own.sample_status = 'yzf'
own.void_desc = '冷链中断'
db.commit()
other, other_parent = _sample(db, 'other', sales='u2')
freight = _freight(db, 'mixed', [('cell_storage', own, own_parent), ('cell_storage', other, other_parent)])
rows, total = list_freights(db, ctx=_ctx(), user_info=_user(), include_items=True)
detail = get_freight_detail(db, freight.id, ctx=_ctx(), user_info=_user())
assert total == 1 and rows[0]['visibleItemCount'] == 1
assert [item['sampleCode'] for item in rows[0]['items']] == ['C-own']
assert rows[0]['items'][0]['sampleStatus'] == 'yzf'
assert rows[0]['items'][0]['sampleStatusLabel'] == '已作废'
assert rows[0]['items'][0]['voidDesc'] == '冷链中断'
assert detail['items'][0]['sampleStatus'] == 'yzf'
assert detail['items'][0]['voidDesc'] == '冷链中断'
assert [item['sampleCode'] for item in detail['items']] == ['C-own']
assert rows[0]['createBy'] == detail['createBy'] == 'u1'
assert rows[0]['createByName'] == detail['createByName'] == '专员'
+27
View File
@@ -674,6 +674,33 @@ def test_chase_filters_counts_orders_and_pages_in_sql_before_materialization():
)
def test_payment_and_chase_lists_include_sample_status_when_coded():
from app.services.market_payment import list_payment_chase, list_payments
db = _session()
today = date(2026, 10, 11)
_payment_tree(db, 'void-sample', due_date=today.strftime('%Y%m%d'))
sample = db.get(BizProtocolSample, 'sample-void-sample')
sample.sample_status = 'yzf'
sample.void_desc = '客户放弃'
db.commit()
payments, payment_total = list_payments(db, ctx=_ctx(), user_info=_user())
chase, chase_total = list_payment_chase(
db, ctx=_ctx(), user_info=_user(), today=today
)
assert payment_total == 1
assert payments[0]['sampleCode'] == 'S-void-sample'
assert payments[0]['sampleStatus'] == 'yzf'
assert payments[0]['sampleStatusLabel'] == '已作废'
assert payments[0]['voidDesc'] == '客户放弃'
assert chase_total == 1
assert chase[0]['sampleStatus'] == 'yzf'
assert chase[0]['sampleStatusLabel'] == '已作废'
assert chase[0]['voidDesc'] == '客户放弃'
def test_payment_list_includes_legacy_models_and_uses_parent_scope_not_transfer_department():
from app.services.market_payment import list_payments
+52
View File
@@ -3604,6 +3604,10 @@ def test_protocol_list_contains_mobile_card_fields():
assert items[0]['deliveryMode'] == 'sc'
assert items[0]['newbornWeightGram'] == 3200
assert items[0]['salesUserName'] == '当前用户'
assert items[0]['sampleStatus'] == ''
assert items[0]['sampleStatusLabel'] == ''
assert items[0]['sampleVoidDesc'] == ''
assert items[0]['voidDesc'] == ''
by_customer, customer_total = list_protocols(
db, ctx=_ctx('specialist'), user_info=_user(), keyword='李安然'
@@ -3626,6 +3630,54 @@ def test_protocol_list_contains_mobile_card_fields():
} == {row.id}
def test_protocol_list_returns_sample_status_without_replacing_donation_void_desc():
from app.services.market_protocol import list_protocols
db = _session()
cell = _cell(db, 'status-cell')
db.add(
BizProtocolSample(
id='sample-status-cell',
collection_protocol_id=cell.id,
sample_code='S-CELL',
sample_status='yzf',
void_desc='试管破裂',
tenant_no='tenant-a',
create_dept_id='',
del_flag=0,
)
)
donation = _donation(db, 'status-don')
donation.void_desc = '协议作废说明'
db.add(
BizResearchDonationSample(
id='sample-status-don',
research_donation_id=donation.id,
sample_code='S-DON',
sample_status='yrk',
void_desc='样本溶血',
tenant_no='tenant-a',
create_dept_id='',
del_flag=0,
)
)
db.commit()
items, total = list_protocols(db, ctx=_ctx('specialist'), user_info=_user())
assert total == 2
by_id = {item['id']: item for item in items}
assert by_id['status-cell']['sampleCode'] == 'S-CELL'
assert by_id['status-cell']['sampleStatus'] == 'yzf'
assert by_id['status-cell']['sampleStatusLabel'] == '已作废'
assert by_id['status-cell']['voidDesc'] == '试管破裂'
assert by_id['status-cell']['sampleVoidDesc'] == '试管破裂'
assert by_id['status-don']['sampleStatus'] == 'yrk'
assert by_id['status-don']['sampleStatusLabel'] == '已入库'
assert by_id['status-don']['voidDesc'] == '协议作废说明'
assert by_id['status-don']['sampleVoidDesc'] == '样本溶血'
@pytest.mark.parametrize('source', ['cell_storage', 'research_donation'])
def test_protocol_list_and_detail_resolve_tenant_void_type_label(source):
from app.services.market_protocol import get_protocol, list_protocols
@@ -0,0 +1,46 @@
"""协议/捐赠列表 sampleItems 须返回样本 voidDesc,供审核列表问号展示。"""
from __future__ import annotations
import inspect
import re
import unittest
_SAMPLE_ITEM_VOID_DESC = re.compile(
r'"sampleStatus"\s*:\s*\(s\.sample_status[^)]*\)\.strip\(\),\s*'
r'"voidDesc"\s*:\s*\(getattr\(s,\s*"void_desc"',
re.S,
)
class TestProtocolListSampleVoidDesc(unittest.TestCase):
def test_collection_protocol_list_includes_sample_void_desc(self):
from app.crud import collection_protocol as cp
src = inspect.getsource(cp.list_collection_protocols)
self.assertRegex(src, _SAMPLE_ITEM_VOID_DESC)
def test_research_donation_list_includes_sample_void_desc(self):
from app.crud import research_donation as rd
# 捐赠列表函数名
fn = None
for name, obj in inspect.getmembers(rd, inspect.isfunction):
if "list" in name and "donation" in name:
src = inspect.getsource(obj)
if "sample_items.append" in src and '"sampleStatus"' in src:
fn = obj
break
self.assertIsNotNone(fn, "未找到组装 sampleItems 的捐赠列表函数")
self.assertRegex(inspect.getsource(fn), _SAMPLE_ITEM_VOID_DESC)
def test_sample_collection_list_uses_sample_void_desc(self):
from app.crud import protocol_sample_collection as psc
src = inspect.getsource(psc)
self.assertIn('getattr(psample, "void_desc"', src)
self.assertNotIn('item["voidDesc"] = (proto.void_desc or "") if proto else ""', src)
if __name__ == "__main__":
unittest.main()
@@ -399,6 +399,147 @@ class TestProtocolReceptionDiscardSync(unittest.TestCase):
)
self.assertEqual(rec.accept_conclusion, "bj")
def test_single_reception_discard_voids_only_that_sample(self):
db = _session()
now = _now()
db.add(
BizCollectionProtocol(
id="p-multi",
protocol_no="CP-MULTI",
protocol_status="sxz",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
for sid, code, status in (
("sa", "ZKA", "ycj"),
("sb", "ZKB", "ycj"),
("sc", "ZKC", "ycj"),
):
db.add(
BizProtocolSample(
id=sid,
collection_protocol_id="p-multi",
sample_code=code,
sample_status=status,
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
rec_a = BizSampleReception(
id="ra",
protocol_sample_id="sa",
collection_protocol_id="p-multi",
reception_time=now,
accept_conclusion="bj",
reception_source="cell_storage",
sample_code="ZKA",
remark="母血乙肝阳性",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
check_packaging=0,
check_sealing=0,
check_no_damage=0,
check_no_leakage=0,
check_color=0,
check_tying_rope=0,
check_no_stratification=0,
)
db.add(rec_a)
db.commit()
after_sample_reception_saved(
db, reception=rec_a, tenant_no="tenant-a", user_id="u1"
)
db.commit()
proto = db.query(BizCollectionProtocol).filter(BizCollectionProtocol.id == "p-multi").one()
self.assertEqual(proto.protocol_status, "sxz")
by_id = {
s.id: s
for s in db.query(BizProtocolSample)
.filter(BizProtocolSample.collection_protocol_id == "p-multi")
.all()
}
self.assertEqual(by_id["sa"].sample_status, SAMPLE_VOID_STATUS)
self.assertEqual(by_id["sa"].void_date, "20261105")
self.assertEqual(by_id["sa"].void_desc, "母血乙肝阳性")
self.assertEqual(by_id["sb"].sample_status, "ycj")
self.assertEqual(by_id["sc"].sample_status, "ycj")
def test_reception_accept_clears_sample_void_when_protocol_active(self):
db = _session()
now = _now()
db.add(
BizCollectionProtocol(
id="p-clear",
protocol_no="CP-CLEAR",
protocol_status="sxz",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
db.add(
BizProtocolSample(
id="s-clear",
collection_protocol_id="p-clear",
sample_code="ZKCLR",
sample_status=SAMPLE_VOID_STATUS,
void_date="20261101",
void_desc="旧作废原因",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
rec = BizSampleReception(
id="r-clear",
protocol_sample_id="s-clear",
collection_protocol_id="p-clear",
reception_time=now,
accept_conclusion="js",
reception_source="cell_storage",
sample_code="ZKCLR",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
check_packaging=0,
check_sealing=0,
check_no_damage=0,
check_no_leakage=0,
check_color=0,
check_tying_rope=0,
check_no_stratification=0,
)
db.add(rec)
db.commit()
after_sample_reception_saved(
db, reception=rec, tenant_no="tenant-a", user_id="u1"
)
db.commit()
sample = db.query(BizProtocolSample).filter(BizProtocolSample.id == "s-clear").one()
self.assertFalse((sample.sample_status or "").strip())
self.assertFalse((sample.void_date or "").strip())
self.assertFalse((sample.void_desc or "").strip())
if __name__ == "__main__":
unittest.main()
@@ -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) == []
+14
View File
@@ -79,12 +79,26 @@ class TestFreightListHelpers(unittest.TestCase):
sample_type_name="脐带血",
mother_name="张三",
newborn_name="张小宝",
sample_status="ycj",
void_desc="",
)
self.assertEqual(d["protocolNo"], "CP001")
self.assertEqual(d["sampleTypeName"], "脐带血")
self.assertEqual(d["sampleSource"], "cell_storage")
self.assertEqual(d["motherName"], "张三")
self.assertEqual(d["newbornName"], "张小宝")
self.assertEqual(d["sampleStatus"], "ycj")
self.assertEqual(d["sampleStatusLabel"], "已采集")
self.assertEqual(d["voidDesc"], "")
voided = _item_to_dict_enriched(
I(),
sample_status="yzf",
void_desc="运输破损",
)
self.assertEqual(voided["sampleStatus"], "yzf")
self.assertEqual(voided["sampleStatusLabel"], "已作废")
self.assertEqual(voided["voidDesc"], "运输破损")
def test_row_dict_includes_create_by(self):
from app.crud.sample_freight import _row_to_dict
@@ -1,8 +1,12 @@
"""样本缴费列表:进度过滤与分页顺序"""
"""样本缴费列表:进度过滤与分页顺序、样本状态汇总字段"""
from types import SimpleNamespace
import unittest
from app.crud.protocol_sample_payment import _filter_and_page_progress
from app.crud.protocol_sample_payment import (
_build_list_summary_row,
_filter_and_page_progress,
)
class TestFilterAndPageProgress(unittest.TestCase):
@@ -33,5 +37,73 @@ class TestFilterAndPageProgress(unittest.TestCase):
self.assertEqual([r["id"] for r in page], ["0", "1", "2"])
class TestPaymentListSampleStatus(unittest.TestCase):
def test_summary_row_exposes_sample_status_and_void_desc(self):
sp = SimpleNamespace(
id="sp1",
collection_protocol_id="p1",
sample_code="ZKZX34001028",
pay_mode="dj",
contract_amount=None,
remark="",
)
proto = SimpleNamespace(
protocol_no="CP-1",
protocol_status="sxz",
void_type="",
register_date="20261101",
)
party = SimpleNamespace(mother_name="张三", mother_phone="13800000000")
progress = {
"progressStatus": "dfj",
"paidAmount": 0,
"arrearsAmount": 0,
"dueAmount": 0,
}
row = _build_list_summary_row(
sp,
proto,
party,
progress,
schedules=[],
transfers=[],
sample_meta={
"storageYears": 20,
"sampleTypeName": "脐带血",
"discountAmount": None,
"sampleStatus": "ycj",
"sampleStatusLabel": "已采集",
"voidDesc": "",
},
)
self.assertEqual(row["sampleStatus"], "ycj")
self.assertEqual(row["sampleStatusLabel"], "已采集")
self.assertEqual(row["voidDesc"], "")
voided = _build_list_summary_row(
sp,
proto,
party,
progress,
schedules=[],
transfers=[],
sample_meta={
"sampleStatus": "yzf",
"voidDesc": "客户放弃存储",
},
)
self.assertEqual(voided["sampleStatus"], "yzf")
self.assertEqual(voided["sampleStatusLabel"], "已作废")
self.assertEqual(voided["voidDesc"], "客户放弃存储")
class TestPaymentChaseSampleStatusLabels(unittest.TestCase):
def test_status_label_map_covers_voided(self):
from app.crud.protocol_sample_payment import _SAMPLE_STATUS_LABELS
self.assertEqual(_SAMPLE_STATUS_LABELS.get("ycj"), "已采集")
self.assertEqual(_SAMPLE_STATUS_LABELS.get("yzf"), "已作废")
if __name__ == "__main__":
unittest.main()
+27
View File
@@ -0,0 +1,27 @@
"""用户下拉选项:同部门优先排序。"""
from app.services.user_select_options import prioritize_caller_dept_options
def test_prioritize_caller_dept_keeps_relative_order():
options = [
{"label": "外1", "value": "a", "deptId": "d2"},
{"label": "同1", "value": "b", "deptId": "d1"},
{"label": "外2", "value": "c", "deptId": "d3"},
{"label": "同2", "value": "d", "deptId": "d1"},
{"label": "无部门", "value": "e", "deptId": ""},
]
out = prioritize_caller_dept_options(options, "d1")
assert [x["value"] for x in out] == ["b", "d", "a", "c", "e"]
def test_prioritize_caller_dept_noop_without_caller_dept():
options = [
{"label": "a", "value": "a", "deptId": "d1"},
{"label": "b", "value": "b", "deptId": "d2"},
]
assert prioritize_caller_dept_options(options, "") == options
assert prioritize_caller_dept_options(options, " ") == options
def test_prioritize_caller_dept_empty_list():
assert prioritize_caller_dept_options([], "d1") == []
@@ -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,67 @@
-- Issue #129:样本接收结论已为废弃(bj)、但样本状态尚未作废的历史回刷
-- 细胞存储 / 科研捐赠;可重复执行。
-- 仅处理协议仍有效(非 yzf/sdfq)的样本行;已作废协议样本由 #127 回刷脚本覆盖。
-- 细胞存储
UPDATE biz_protocol_sample s
INNER JOIN biz_sample_reception r
ON r.tenant_no = s.tenant_no
AND r.del_flag = 0
AND r.reception_source = 'cell_storage'
AND r.accept_conclusion = 'bj'
AND r.sample_code = s.sample_code
AND r.collection_protocol_id = s.collection_protocol_id
INNER JOIN biz_collection_protocol p
ON p.id = s.collection_protocol_id
AND p.tenant_no = s.tenant_no
AND p.del_flag = 0
SET
s.sample_status = 'yzf',
s.void_date = CASE
WHEN s.void_date IS NOT NULL AND TRIM(s.void_date) <> '' THEN s.void_date
WHEN r.reception_time IS NOT NULL THEN DATE_FORMAT(r.reception_time, '%Y%m%d')
WHEN s.update_time IS NOT NULL THEN DATE_FORMAT(s.update_time, '%Y%m%d')
ELSE DATE_FORMAT(NOW(), '%Y%m%d')
END,
s.update_time = NOW()
WHERE s.del_flag = 0
AND p.protocol_status NOT IN ('yzf', 'sdfq')
AND (
s.sample_status IS NULL
OR TRIM(s.sample_status) = ''
OR s.sample_status <> 'yzf'
OR s.void_date IS NULL
OR TRIM(s.void_date) = ''
);
-- 科研捐赠
UPDATE biz_research_donation_sample s
INNER JOIN biz_sample_reception r
ON r.tenant_no = s.tenant_no
AND r.del_flag = 0
AND r.reception_source = 'research_donation'
AND r.accept_conclusion = 'bj'
AND r.sample_code = s.sample_code
AND r.research_donation_id = s.research_donation_id
INNER JOIN biz_research_donation d
ON d.id = s.research_donation_id
AND d.tenant_no = s.tenant_no
AND d.del_flag = 0
SET
s.sample_status = 'yzf',
s.void_date = CASE
WHEN s.void_date IS NOT NULL AND TRIM(s.void_date) <> '' THEN s.void_date
WHEN r.reception_time IS NOT NULL THEN DATE_FORMAT(r.reception_time, '%Y%m%d')
WHEN s.update_time IS NOT NULL THEN DATE_FORMAT(s.update_time, '%Y%m%d')
ELSE DATE_FORMAT(NOW(), '%Y%m%d')
END,
s.update_time = NOW()
WHERE s.del_flag = 0
AND d.donation_status NOT IN ('yzf', 'sdfq')
AND (
s.sample_status IS NULL
OR TRIM(s.sample_status) = ''
OR s.sample_status <> 'yzf'
OR s.void_date IS NULL
OR TRIM(s.void_date) = ''
);
@@ -0,0 +1,26 @@
-- Issue #131:样本作废原因字段 void_desc
-- 细胞存储 / 科研捐赠样本表;按列是否已存在可重复执行。
SET @db := DATABASE();
SET @exists := (
SELECT COUNT(*) FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 'biz_protocol_sample' AND COLUMN_NAME = 'void_desc'
);
SET @sql := IF(
@exists = 0,
'ALTER TABLE biz_protocol_sample ADD COLUMN void_desc VARCHAR(512) NULL COMMENT ''样本作废原因'' AFTER void_date',
'SELECT 1'
);
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
SET @exists := (
SELECT COUNT(*) FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 'biz_research_donation_sample' AND COLUMN_NAME = 'void_desc'
);
SET @sql := IF(
@exists = 0,
'ALTER TABLE biz_research_donation_sample ADD COLUMN void_desc VARCHAR(512) NULL COMMENT ''样本作废原因'' AFTER void_date',
'SELECT 1'
);
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
@@ -0,0 +1,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='质检任务检测结果操作留痕';
@@ -23,23 +23,11 @@
</header>
<div class="market-list-card__fields">
<div
<MarketListField
v-for="field in previewFields"
:key="`${field.label}:${field.value}`"
class="market-list-card__field"
:class="{ 'is-wide': field.wide }"
>
<span>{{ field.label }}</span>
<van-tag
v-if="field.tag"
class="market-tag"
:type="resolveStatusTone(field.value, field.tagType)"
size="medium"
round
:title="field.value"
>{{ field.value }}</van-tag>
<b v-else :class="{ 'is-money': field.money }">{{ field.value }}</b>
</div>
:field="field"
/>
</div>
<!-- 每一期缴费:始终展示在「展开更多」上方,不收进总折叠 -->
@@ -70,15 +58,11 @@
</button>
<div v-show="periodOpenKeys[block.key]" class="market-list-card__period-body">
<div class="market-list-card__fields market-list-card__fields--compact">
<div
<MarketListField
v-for="field in block.fields"
:key="`${block.key}:${field.label}`"
class="market-list-card__field"
:class="{ 'is-wide': field.wide }"
>
<span>{{ field.label }}</span>
<b :class="{ 'is-money': field.money }">{{ field.value }}</b>
</div>
:field="field"
/>
</div>
</div>
</div>
@@ -102,44 +86,20 @@
<van-icon class="market-list-card__fields-toggle-chevron" name="arrow-down" />
</button>
<div v-show="fieldsOpen && collapsedFields.length" class="market-list-card__fields market-list-card__fields--folded">
<div
<MarketListField
v-for="field in collapsedFields"
:key="`more:${field.label}:${field.value}`"
class="market-list-card__field"
:class="{ 'is-wide': field.wide }"
>
<span>{{ field.label }}</span>
<van-tag
v-if="field.tag"
class="market-tag"
:type="resolveStatusTone(field.value, field.tagType)"
size="medium"
round
:title="field.value"
>{{ field.value }}</van-tag>
<b v-else :class="{ 'is-money': field.money }">{{ field.value }}</b>
</div>
:field="field"
/>
</div>
</div>
<div v-if="card.footerFields?.length && showFoldedFooter" class="market-list-card__fields">
<div
<MarketListField
v-for="field in card.footerFields"
:key="`footer:${field.label}:${field.value}`"
class="market-list-card__field"
:class="{ 'is-wide': field.wide }"
>
<span>{{ field.label }}</span>
<van-tag
v-if="field.tag"
class="market-tag"
:type="resolveStatusTone(field.value, field.tagType)"
size="medium"
round
:title="field.value"
>{{ field.value }}</van-tag>
<b v-else :class="{ 'is-money': field.money }">{{ field.value }}</b>
</div>
:field="field"
/>
</div>
<div
@@ -181,15 +141,11 @@
>{{ block.status }}</van-tag>
</div>
<div class="market-list-card__fields market-list-card__fields--compact">
<div
<MarketListField
v-for="field in block.fields"
:key="`${block.key}:${field.label}`"
class="market-list-card__field"
:class="{ 'is-wide': field.wide }"
>
<span>{{ field.label }}</span>
<b>{{ field.value }}</b>
</div>
:field="field"
/>
</div>
</div>
</div>
@@ -222,6 +178,7 @@
import { computed, ref, watch } from 'vue'
import { actionLabel, buildMarketCard } from '../list-presenter.js'
import { resolveStatusTone } from '../status-tone.js'
import MarketListField from './MarketListField.vue'
const props = defineProps({
item: { type: Object, required: true },
@@ -0,0 +1,44 @@
<template>
<div class="market-list-card__field" :class="{ 'is-wide': field.wide }">
<span>{{ field.label }}</span>
<span class="market-list-card__value">
<van-tag
v-if="field.tag"
class="market-tag"
:type="resolveStatusTone(field.value, field.tagType)"
size="medium"
round
:title="field.value"
>{{ field.value }}</van-tag>
<b v-else :class="{ 'is-money': field.money }">{{ field.value }}</b>
<button
v-if="field.helpTitle"
type="button"
class="market-list-card__help"
:aria-label="`查看${field.helpTitle}`"
:title="field.helpTitle"
@click="showHelp"
>
<van-icon name="question-o" />
</button>
</span>
</div>
</template>
<script setup>
import { showDialog } from 'vant'
import { resolveStatusTone } from '../status-tone.js'
const props = defineProps({
field: { type: Object, required: true }
})
function showHelp() {
showDialog({
title: props.field.helpTitle || '作废原因',
message: props.field.helpText || '—',
messageAlign: 'left',
confirmButtonText: '知道了'
})
}
</script>
+30 -1
View File
@@ -2,6 +2,7 @@ import { formatMoney } from './money.js'
import {
resolveStatusTag,
samplePaymentProgress,
sampleStatus,
payMode,
protocolStatus,
donationStatus,
@@ -94,6 +95,30 @@ const personName = (name, id) => {
: referenceId ? '未知人员' : '—'
}
const field = (labelText, value, options = {}) => ({ label: labelText, value: text(value), ...options })
function sampleVoidReason(item) {
if (item && Object.prototype.hasOwnProperty.call(item, 'sampleVoidDesc')) {
return String(item.sampleVoidDesc ?? '').trim()
}
return String(item?.voidDesc ?? '').trim()
}
/** 样本编码旁的样本状态;已作废时附带作废原因,供卡片问号展开 */
function sampleStatusField(item) {
const provided = String(item?.sampleStatusLabel ?? '').trim()
const code = String(item?.sampleStatus ?? '').trim()
if (!code && !provided) return field('样本状态', '')
const resolved = resolveStatusTag(sampleStatus, code)
const display = provided || resolved.label
const voided = code === 'yzf' || display === '已作废'
return field('样本状态', display, {
tag: true,
tagType: voided ? 'danger' : (code ? resolved.tagType : 'info'),
...(voided
? { helpTitle: '作废原因', helpText: sampleVoidReason(item) || '—' }
: {})
})
}
export function money(value) {
return formatMoney(value)
}
@@ -134,6 +159,7 @@ function protocolCard(item) {
field('所属项目', item.projectName || item.basic?.projectName || ((item.projectId || item.basic?.projectId) ? '历史项目' : '未归属')),
field('项目组', item.teamName || item.basic?.teamName),
field('样本编码', item.sampleCode || item.labStorageCode),
sampleStatusField(item),
field('采集日期', collectDate || item.donationDate),
field('当月核量号', item.monthlyVerifyNo),
field('实验室流转编号', item.labStorageCode || item.sampleCode),
@@ -172,6 +198,7 @@ function protocolCard(item) {
field('所属项目', item.projectName || item.basic?.projectName || ((item.projectId || item.basic?.projectId) ? '历史项目' : '未归属')),
field('项目组', item.teamName || item.basic?.teamName),
field('样本编码', item.sampleCode),
sampleStatusField(item),
field('登记日期', item.registerDate || item.donationDate),
field('母亲电话', item.motherPhone),
field('母亲身份证号', item.motherIdCard),
@@ -212,6 +239,7 @@ function chaseCard(item) {
field('客户', item.motherName),
field('联系电话', item.motherPhone),
field('样本编码', item.sampleCode),
sampleStatusField(item),
field('市场专员', personName(item.salesUserName, item.salesUserId)),
field('缴费方式', mode.label, { tag: true, tagType: mode.tagType }),
field('期次', `第 ${text(item.scheduleNo, '1')} 期`),
@@ -281,7 +309,7 @@ function paymentCard(item) {
statusTone: progress.tagType,
fields: [
field('姓名', item.motherName), field('手机号', item.motherPhone),
field('样本编码', item.sampleCode), field('签署日期', item.signDate),
field('样本编码', item.sampleCode), sampleStatusField(item), field('签署日期', item.signDate),
field('存储项目', item.sampleTypeName), field('合同总额', money(item.contractAmount), { money: true }),
field('缴费方式', mode.label, { tag: true, tagType: mode.tagType }),
field('应收总额', money(item.receivableAmount), { money: true })
@@ -311,6 +339,7 @@ function freightSampleBlock(row, index) {
field('母亲姓名', row?.motherName),
field('子女姓名', row?.newbornName),
field('样本编码', row?.sampleCode, { wide: true }),
sampleStatusField(row),
field('样本类型', row?.sampleTypeName, { wide: true })
]
}
+60 -1
View File
@@ -112,7 +112,7 @@ test('research donation protocol card matches excel-parity field set', () => {
const labels = card.fields.map((f) => f.label)
assert.equal(labels[2], '样本编码')
for (const label of [
'样本编码', '当月核量号', '实验室流转编号', '废弃原因', '样本类型',
'样本编码', '样本状态', '当月核量号', '实验室流转编号', '废弃原因', '样本类型',
'采集地区', '采集医院', '分娩时间', '采集时间', '市场专员', '地区经理',
'运输方式', '新生儿性别', '新生儿体重', '分娩方式', '胎次', '母血采集时间',
'知情同意书', '传染病检测报告', '协议书', '备注'
@@ -245,11 +245,70 @@ test('freight card shows the scope-safe visible count and collapsible sample blo
assert.equal(manager.sampleBlocks[1].fields.find((field) => field.label === '母亲姓名').value, '周雨桐')
assert.equal(manager.sampleBlocks[1].fields.find((field) => field.label === '子女姓名').value, '宝宝乙')
assert.equal(manager.sampleBlocks[1].fields.find((field) => field.label === '样本编码').value, 'S-2')
assert.equal(manager.sampleBlocks[1].fields.find((field) => field.label === '样本状态').value, '—')
assert.equal(manager.sampleBlocks[1].fields.find((field) => field.label === '样本类型').value, '脐带')
assert.ok(manager.fields.some((field) => field.label === '更新时间' && field.value === '2026-10-13 10:00:00'))
assert.ok(manager.fields.some((field) => field.label === '备注' && field.value === '同批送达'))
})
test('sample-coded list cards show sample status and a void reason affordance', () => {
const cases = [
['protocol', { source: 'cell_storage', sampleCode: 'S-1', sampleStatus: 'yrk', sampleStatusLabel: '已入库' }],
['payment-chase', { sampleCode: 'S-1', sampleStatus: 'jcz' }],
['payment', { sampleCode: 'S-1', motherName: '周雨桐', sampleStatus: 'ycj', sampleStatusLabel: '已采集' }]
]
for (const [module, item] of cases) {
const card = buildMarketCard(module, 'specialist', item)
const status = card.fields.find((field) => field.label === '样本状态')
assert.ok(status, module)
assert.equal(status.tag, true)
assert.equal(status.helpTitle, undefined)
}
assert.equal(
buildMarketCard('protocol', 'specialist', {
source: 'cell_storage', sampleCode: 'S-1', sampleStatus: 'yrk', sampleStatusLabel: '已入库'
}).fields.find((field) => field.label === '样本状态').value,
'已入库'
)
const detecting = buildMarketCard('payment-chase', 'specialist', {
sampleCode: 'S-1', sampleStatus: 'jcz'
}).fields.find((field) => field.label === '样本状态')
assert.equal(detecting.value, '检测中')
assert.equal(detecting.helpTitle, undefined)
assert.equal(detecting.helpText, undefined)
const voided = buildMarketCard('payment', 'specialist', {
motherName: '作废客户',
sampleCode: 'S-VOID',
sampleStatus: 'yzf',
voidDesc: '客户放弃存储'
})
const voidField = voided.fields.find((field) => field.label === '样本状态')
assert.equal(voidField.value, '已作废')
assert.equal(voidField.tagType, 'danger')
assert.equal(voidField.helpTitle, '作废原因')
assert.equal(voidField.helpText, '客户放弃存储')
const donation = buildMarketCard('protocol', 'specialist', {
source: 'research_donation',
sampleCode: 'S-D',
sampleStatus: 'yzf',
sampleStatusLabel: '已作废',
voidDesc: '协议级废弃说明',
sampleVoidDesc: '样本溶血'
})
assert.equal(donation.fields.find((field) => field.label === '废弃原因').value, '协议级废弃说明')
assert.equal(donation.fields.find((field) => field.label === '样本状态').helpText, '样本溶血')
const freight = buildMarketCard('freight', 'manager', {
freightNo: 'YF-VOID',
items: [{ sampleCode: 'S-V', sampleStatus: 'yzf', voidDesc: '运输破损' }]
})
const sampleStatus = freight.sampleBlocks[0].fields.find((field) => field.label === '样本状态')
assert.equal(sampleStatus.value, '已作废')
assert.equal(sampleStatus.helpText, '运输破损')
})
test('action labels cover module-specific operations', () => {
assert.equal(actionLabel('link'), '关联样本')
assert.equal(actionLabel('unlink'), '取消样本关联')
@@ -84,6 +84,7 @@ test('market list visual contract keeps search white, tags filled and actions ri
'./components/MarketDetailSection.vue',
'./components/MarketDetailNestedCard.vue',
'./components/MarketListCard.vue',
'./components/MarketListField.vue',
'./components/PresignOrderCard.vue',
'./components/PresignTransferCard.vue',
'./components/ProtocolSamplePaymentPanel.vue',
@@ -541,6 +542,16 @@ test('payment detail hosts PaymentDetailTransfersPanel and hides transfer bottom
assert.match(panel, /应缴批次/)
})
test('voided sample status uses a question icon and vant dialog', () => {
const field = source('./components/MarketListField.vue')
const card = source('./components/MarketListCard.vue')
assert.match(field, /name="question-o"/)
assert.match(field, /showDialog/)
assert.match(field, /field\.helpTitle/)
assert.match(field, /class="market-tag"/)
assert.match(card, /MarketListField/)
})
test('payment cards reproduce the Web Excel columns and operation labels', () => {
const presenter = source('./list-presenter.js')
const card = source('./components/MarketListCard.vue')
@@ -590,7 +601,7 @@ test('protocol cards expose the same business fields as the web list', async ()
})
assert.deepEqual(card.fields.map((field) => field.label), [
'所属项目', '项目组', '样本编码', '登记日期', '母亲电话', '母亲身份证号', '父亲姓名',
'所属项目', '项目组', '样本编码', '样本状态', '登记日期', '母亲电话', '母亲身份证号', '父亲姓名',
'新生儿性别', '分娩方式', '新生儿体重(克)', '采集地区', '采集医院',
'市场专员', '样本采集时间', '创建时间'
])
@@ -106,6 +106,14 @@ export const receptionSource = createRegistry({
basic_experiment: { label: '基础实验', tagType: 'primary' }
})
/** 协议/捐赠样本状态;与 Web sampleStatus 保持一致 */
export const sampleStatus = createRegistry({
ycj: { label: '已采集', tagType: 'primary' },
jcz: { label: '检测中', tagType: 'warning' },
yrk: { label: '已入库', tagType: 'success' },
yzf: { label: '已作废', tagType: 'danger' }
})
export const presignOrderStatus = createRegistry({
draft: { label: '草稿', tagType: 'info' },
active: { label: '进行中', tagType: 'warning' },
@@ -8,10 +8,19 @@ import {
payMode,
presignOrderStatus,
receptionSource,
sampleStatus,
transportType,
auditStatus
} from './status-tag-registry.js'
test('sample status yzf is 已作废/danger', () => {
assert.deepEqual(resolveStatusTag(sampleStatus, 'yzf'), {
label: '已作废',
tagType: 'danger'
})
assert.equal(resolveStatusTag(sampleStatus, 'yrk').label, '已入库')
})
test('sample progress dfj is 待缴费/info not 待缴清', () => {
assert.deepEqual(resolveStatusTag(samplePaymentProgress, 'dfj'), {
label: '待缴费',
@@ -216,7 +216,8 @@ async function ensureUserCache() {
if (userCachePromise) return userCachePromise
userCachePromise = (async () => {
try {
const res = await fetchUserOptions()
// 同部门优先:由后端按当前登录用户部门排序
const res = await fetchUserOptions({ prioritizeCallerDept: true })
const list = Array.isArray(res) ? res : res?.list || []
const next = []
const seen = new Set()
+23
View File
@@ -631,6 +631,29 @@ body.van-toast--unclickable .presign-order-page * {
font-weight: 700;
}
.market-list-card__value {
display: flex;
min-width: 0;
align-items: center;
gap: 0;
}
.market-list-card__help {
display: inline-flex;
width: 44px;
height: 44px;
flex: 0 0 44px;
align-items: center;
justify-content: center;
margin: -10px -8px -10px -4px;
padding: 0;
border: 0;
background: transparent;
color: var(--market-primary-dark, #087f57);
font-size: 18px;
cursor: pointer;
}
.market-list-card__samples {
margin: 0 0 12px;
overflow: hidden;
+6 -3
View File
@@ -22,9 +22,12 @@ export function fetchGetRoleList() {
})
}
/** 流程设计器:用户下拉选项(label=昵称,value=用户ID) */
export function fetchUserOptions(params?: { roleName?: string }) {
return request.get<Array<{ label: string; value: string }>>({
/** 用户下拉选项(label=昵称,value=用户ID;可选 deptId / prioritizeCallerDept) */
export function fetchUserOptions(params?: {
roleName?: string
prioritizeCallerDept?: boolean
}) {
return request.get<Array<{ label: string; value: string; deptId?: string }>>({
url: '/web/admin/users/options',
params
})
+29
View File
@@ -0,0 +1,29 @@
import request from '@/utils/http'
export type SampleVoidTarget = {
receptionSource: 'cell_storage' | 'research_donation'
sampleId?: string
sampleCode?: string
/** 仅弹窗展示,不参与作废请求 */
labStorageCode?: string
protocolId?: string
}
export type VoidBusinessSamplePayload = SampleVoidTarget & {
voidDesc: string
}
export type VoidBusinessSampleResult = {
id: string
sampleCode: string
sampleStatus: string
voidDate: string
voidDesc: string
}
export function fetchVoidBusinessSample(data: VoidBusinessSamplePayload) {
return request.put<VoidBusinessSampleResult>({
url: '/web/admin/business-samples/void',
data
})
}
@@ -17,6 +17,10 @@ export interface ProductionWorkOrderItem {
workOrderType?: string
protocolNo?: string
sampleCode?: string
sampleStatus?: string
voidDesc?: string
protocolSampleId?: string
collectionProtocolId?: string
receptionSource?: string
receptionSourceLabel?: string
sampleTypeName?: string
+37
View File
@@ -51,6 +51,7 @@ export function fetchCompleteTaskWithResult(
remark?: string
thirdPartyAttachments?: string
taskStatus?: 'dzx' | 'jxz' | 'ywc'
operateBatchId?: string
materialUsages?: Array<{
requisitionUsageId: string
qty: number
@@ -66,3 +67,39 @@ export function fetchCompleteTaskWithResult(
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
@@ -100,6 +100,8 @@ export type QcWorkOrder = {
collectionProtocolId: string
protocolNo: string
sampleCode: string
sampleStatus?: string
voidDesc?: string
labStorageCode?: string
receptionSource?: string
receptionSourceLabel?: string
+2
View File
@@ -5,6 +5,8 @@ export type SampleFreightItem = {
sampleId: string
protocolId?: string
sampleCode?: string
sampleStatus?: string
voidDesc?: string
protocolNo?: string
sampleTypeName?: string
motherName?: string
Binary file not shown.

After

Width:  |  Height:  |  Size: 95 KiB

@@ -0,0 +1,71 @@
<!-- 样本状态:标签;仅已作废时展示问号与作废原因 -->
<template>
<span class="sample-status-tag">
<el-tag :type="tagType" size="small">{{ label }}</el-tag>
<el-popover v-if="voided" placement="top" trigger="click" :width="240">
<template #reference>
<button type="button" class="sample-status-tag__q" aria-label="作废原因" @click.stop>
<el-icon><QuestionFilled /></el-icon>
</button>
</template>
<div class="sample-status-tag__reason">
<div class="sample-status-tag__reason-title">作废原因</div>
<div>{{ reasonText }}</div>
</div>
</el-popover>
</span>
</template>
<script setup lang="ts">
import { computed } from 'vue'
import { QuestionFilled } from '@element-plus/icons-vue'
import { sampleStatusLabel, sampleStatusTagType } from '@/utils/status-tag-registry'
defineOptions({ name: 'SampleStatusTag' })
const props = defineProps<{
status?: string | null
voidDesc?: string | null
}>()
const code = computed(() => String(props.status || '').trim())
const label = computed(() => (code.value ? sampleStatusLabel(code.value) : '—'))
const tagType = computed(() => (code.value ? sampleStatusTagType(code.value) : 'info'))
/** 问号仅已作废(yzf)展示 */
const voided = computed(() => code.value === 'yzf')
const reasonText = computed(() => String(props.voidDesc || '').trim() || '暂无作废原因')
</script>
<style scoped lang="scss">
.sample-status-tag {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 4px;
max-width: 100%;
vertical-align: middle;
}
.sample-status-tag__q {
display: inline-flex;
align-items: center;
justify-content: center;
padding: 0;
border: none;
background: transparent;
color: var(--mint-text-muted, #64748b);
cursor: pointer;
line-height: 1;
font-size: 14px;
&:hover {
color: #059669;
}
}
.sample-status-tag__reason-title {
margin-bottom: 4px;
font-size: 12px;
color: var(--mint-text-muted, #64748b);
}
</style>
@@ -0,0 +1,145 @@
<!-- 样本废弃:填写作废原因后提交 -->
<template>
<el-dialog
v-model="dialogVisible"
title="样本废弃"
width="560px"
class="dialog-form-layout"
align-center
append-to-body
modal-class="protocol-dialog-mask"
destroy-on-close
:close-on-click-modal="false"
@close="handleClose"
>
<el-form
ref="formRef"
:model="form"
:rules="rules"
label-position="top"
class="biz-dialog-form"
>
<div class="form-grid-2">
<el-form-item label="实验室入库编码" class="form-col-span-2">
<span class="sample-void-dialog__code">{{ labStorageCodeDisplay }}</span>
</el-form-item>
<el-form-item v-if="sampleCode" label="样本编码" class="form-col-span-2">
<span class="sample-void-dialog__code">{{ sampleCode }}</span>
</el-form-item>
<el-form-item label="作废原因" prop="voidDesc" class="form-col-span-2">
<el-input
v-model="form.voidDesc"
type="textarea"
:rows="4"
maxlength="512"
show-word-limit
placeholder="请填写作废原因"
/>
</el-form-item>
</div>
</el-form>
<template #footer>
<el-button class="btn-ghost" @click="handleClose">
<el-icon><Close /></el-icon>取消
</el-button>
<el-button class="btn-main" type="primary" :loading="submitting" @click="handleSubmit">
<el-icon><Check /></el-icon>确定
</el-button>
</template>
</el-dialog>
</template>
<script setup lang="ts">
import { computed, reactive, ref, watch } from 'vue'
import { Check, Close } from '@element-plus/icons-vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { fetchVoidBusinessSample, type SampleVoidTarget } from '@/api/business-sample'
defineOptions({ name: 'SampleVoidDialog' })
const props = defineProps<{
visible: boolean
target: SampleVoidTarget | null
}>()
const emit = defineEmits<{
'update:visible': [visible: boolean]
success: []
}>()
const dialogVisible = ref(false)
const submitting = ref(false)
const formRef = ref<FormInstance>()
const form = reactive({
voidDesc: ''
})
const rules: FormRules = {
voidDesc: [
{
required: true,
validator: (_rule, value, callback) => {
if (!String(value || '').trim()) callback(new Error('请填写作废原因'))
else callback()
},
trigger: 'blur'
}
]
}
const labStorageCodeDisplay = computed(
() => String(props.target?.labStorageCode || '').trim() || '—'
)
const sampleCode = computed(() => String(props.target?.sampleCode || '').trim())
watch(
() => props.visible,
(visible) => {
dialogVisible.value = visible
if (visible) form.voidDesc = ''
},
{ immediate: true }
)
watch(dialogVisible, (visible) => {
emit('update:visible', visible)
})
function handleClose() {
dialogVisible.value = false
}
async function handleSubmit() {
const target = props.target
if (!target?.receptionSource || (!target.sampleId && !target.sampleCode)) {
ElMessage.warning('缺少样本信息,无法废弃')
return
}
const valid = await formRef.value?.validate().catch(() => false)
if (!valid) return
submitting.value = true
try {
await fetchVoidBusinessSample({
receptionSource: target.receptionSource,
sampleId: target.sampleId,
sampleCode: target.sampleCode,
protocolId: target.protocolId,
voidDesc: form.voidDesc.trim()
})
ElMessage.success('样本已废弃')
emit('success')
handleClose()
} finally {
submitting.value = false
}
}
</script>
<style scoped lang="scss">
.sample-void-dialog__code {
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
font-size: 14px;
font-weight: 600;
color: #1e293b;
}
</style>
@@ -255,7 +255,8 @@
if (userCachePromise) return userCachePromise
userCachePromise = (async () => {
try {
const res = await fetchUserOptions()
// 同部门优先:由后端按当前登录用户部门排序
const res = await fetchUserOptions({ prioritizeCallerDept: true })
const list = Array.isArray(res) ? res : []
const next: MentionUser[] = []
const seen = new Set<string>()
+51 -2
View File
@@ -60,8 +60,8 @@ export const sqxpAdminRoutes: AppRouteRecord[] = [
},
// ═══════════════════════════════════════════════════════════════════════════
// 1. 市场 (menu:market)
// 二级菜单:存储服务、科研捐赠、市场基础信息、中试服务、基础实验
// (主推存储/捐赠在前;中试/基础实验及关联基础信息后置)
// 二级菜单:存储服务、科研捐赠、市场基础信息、中试服务、基础实验、器械销售
// (主推存储/捐赠在前;中试/基础实验及关联基础信息后置;器械销售在末位)
// ═══════════════════════════════════════════════════════════════════════════
{
id: 'TOP00000000000000000000000000001',
@@ -669,6 +669,55 @@ export const sqxpAdminRoutes: AppRouteRecord[] = [
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'
}
}
]
}
]
},
@@ -40,6 +40,7 @@ export const LAB_PROCESS_TABS: Array<{
const CELL_HSC_COLUMNS: LabColumn[] = [
{ prop: 'cellCode', label: '细胞编码', minWidth: 140 },
{ prop: 'sampleStatus', label: '样本状态', minWidth: 140 },
{ prop: 'motherName', label: '准妈妈姓名', minWidth: 110 },
{ prop: 'collectionTime', label: '采集时间', minWidth: 200 },
{ prop: 'hospitalName', label: '采集医院', minWidth: 140 },
@@ -72,6 +73,7 @@ const CELL_HSC_COLUMNS: LabColumn[] = [
const DONATION_HSC_COLUMNS: LabColumn[] = [
{ prop: 'cellCode', label: '细胞编码', minWidth: 140 },
{ prop: 'sampleStatus', label: '样本状态', minWidth: 140 },
{ prop: 'motherName', label: '准妈妈姓名', minWidth: 110 },
{ prop: 'labMaterialCode', label: '实验室物料编码', minWidth: 130 },
{ prop: 'inboundCode', label: '入库编码', minWidth: 140 },
@@ -98,6 +100,7 @@ const DONATION_HSC_COLUMNS: LabColumn[] = [
const MSC_COLUMNS: LabColumn[] = [
{ prop: 'labFlowCode', label: '实验室流转编码', minWidth: 140 },
{ prop: 'sampleStatus', label: '样本状态', minWidth: 140 },
{ prop: 'motherName', label: '母亲姓名', minWidth: 110 },
{ prop: 'cordCollectTime', label: '脐带采集时间', minWidth: 200 },
{ prop: 'transportTempC', label: '运输温度/℃', minWidth: 110 },
@@ -14,7 +14,7 @@ import type { ProductionWorkOrderTabKey } from '@/utils/production-work-order-ta
import { resolveTabKeyFromWorkOrder } from '@/utils/production-work-order-tabs'
import { formatMoneyDisplay } from '@/utils/money-format'
export type CardMetaFieldKind = 'text' | 'tag'
export type CardMetaFieldKind = 'text' | 'tag' | 'sample-status'
export type CardMetaField = {
label: string
@@ -84,6 +84,11 @@ function buildInboundMetaFields(tabKey: ProductionWorkOrderTabKey): CardMetaFiel
return [
{ label: '实验室入库编码', getValue: (row) => row.labStorageCode || '—' },
{ label: '样本类型', getValue: (row) => row.sampleTypeName || '—' },
{
label: '样本状态',
kind: 'sample-status',
getValue: (row) => String(row.sampleStatus || '')
},
{ label: '接收经手人', getValue: (row) => row.handlerName || '—' },
{ label: '接收时间', getValue: (row) => formatDisplayOrDash(row.receptionTime) },
{
@@ -63,6 +63,19 @@ describe('flattenProtocolAuditRows', () => {
assert.equal(rows[0].sampleCode, 'ZKZX34000199')
})
it('passes sample status and sample void reason from sample items', () => {
const rows = flattenProtocolAuditRows([
{
id: 'p-status',
voidDesc: '协议作废',
sampleItems: [{ sampleCode: 'S-VOID', sampleStatus: 'yzf', voidDesc: '样本破损' }]
}
])
assert.equal(rows[0].voidDesc, '协议作废')
assert.equal(rows[0].sampleStatus, 'yzf')
assert.equal(rows[0].sampleVoidDesc, '样本破损')
})
it('zero samples → one placeholder row, not co-stored', () => {
const rows = flattenProtocolAuditRows([{ id: 'p2', protocolNo: 'ZKZX2', sampleItems: [] }])
assert.equal(rows.length, 1)
@@ -34,6 +34,9 @@ export type ProtocolAuditFlatRow = {
regionManagerUserName: string
sampleTypeName: string
sampleCode: string
sampleStatus: string
/** 样本作废原因;协议作废原因仍用 voidDesc */
sampleVoidDesc: string
labStorageCode: string
transportType: string
transportLabel: string
@@ -120,6 +123,8 @@ export function flattenProtocolAuditRows(
regionManagerUserName: str(protocol.regionManagerUserName),
sampleTypeName: str(rec.sampleTypeName),
sampleCode: str(rec.sampleCode),
sampleStatus: str(rec.sampleStatus),
sampleVoidDesc: str(rec.voidDesc),
labStorageCode: str(rec.labStorageCode),
transportType,
transportLabel: '',
@@ -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
}
}
@@ -16,7 +16,7 @@ import {
type QcWorkOrderProtocolGroupModel
} from '@/utils/qc-work-order-groups'
export type CardMetaFieldKind = 'text' | 'tag'
export type CardMetaFieldKind = 'text' | 'tag' | 'sample-status'
export type CardMetaField = {
label: string
@@ -134,6 +134,12 @@ const inboundGroupedFields: CardMetaField[] = [
visible: (row) => (row.triggerSource || 'reception') === 'production'
},
{ label: '样本编码', getValue: (row) => row.sampleCode || '—', visible: isInboundUserInfoRow },
{
label: '样本状态',
kind: 'sample-status',
getValue: (row) => String(row.sampleStatus || ''),
visible: isInboundUserInfoRow
},
{
label: '样本类型',
getValue: (row) => row.sampleTypeName || '—',
@@ -21,6 +21,8 @@ export type SampleFreightFlatRow = {
motherName?: string
newbornName?: string
sampleCode?: string
sampleStatus?: string
voidDesc?: string
sampleTypeName?: string
sampleId?: string
protocolId?: string
@@ -53,6 +55,8 @@ export function flattenSampleFreights(list: SampleFreight[]): SampleFreightFlatR
motherName: it?.motherName,
newbornName: it?.newbornName,
sampleCode: it?.sampleCode,
sampleStatus: it?.sampleStatus,
voidDesc: it?.voidDesc,
sampleTypeName: it?.sampleTypeName,
sampleId: it?.sampleId,
protocolId: it?.protocolId,
+43
View File
@@ -0,0 +1,43 @@
import { describe, it } from 'node:test'
import assert from 'node:assert/strict'
import { isSampleAlreadyVoided, resolveSampleVoidTarget } from './sample-void'
describe('resolveSampleVoidTarget', () => {
it('uses protocol sample id, code and protocol id', () => {
const target = resolveSampleVoidTarget({
receptionSource: 'cell_storage',
protocolSampleId: 'ps-1',
sampleCode: 'S1',
labStorageCode: 'B0000108',
collectionProtocolId: 'p-1'
})
assert.deepEqual(target, {
receptionSource: 'cell_storage',
sampleId: 'ps-1',
sampleCode: 'S1',
labStorageCode: 'B0000108',
protocolId: 'p-1'
})
})
it('falls back to tab source when row source is empty', () => {
const target = resolveSampleVoidTarget({
sampleCode: 'S2',
fallbackSource: 'research_donation'
})
assert.equal(target?.receptionSource, 'research_donation')
assert.equal(target?.sampleCode, 'S2')
})
it('returns null without a sample identifier', () => {
assert.equal(resolveSampleVoidTarget({ receptionSource: 'cell_storage' }), null)
})
})
describe('isSampleAlreadyVoided', () => {
it('matches yzf only', () => {
assert.equal(isSampleAlreadyVoided('yzf'), true)
assert.equal(isSampleAlreadyVoided(' yzf '), true)
assert.equal(isSampleAlreadyVoided('ycj'), false)
})
})
+32
View File
@@ -0,0 +1,32 @@
import type { SampleVoidTarget } from '../api/business-sample'
export function isSampleAlreadyVoided(status?: string | null): boolean {
return String(status || '').trim() === 'yzf'
}
export function resolveSampleVoidTarget(input: {
receptionSource?: string | null
protocolSampleId?: string | null
sampleCode?: string | null
labStorageCode?: string | null
collectionProtocolId?: string | null
fallbackSource?: string | null
}): SampleVoidTarget | null {
let source = String(input.receptionSource || '').trim()
if (source !== 'cell_storage' && source !== 'research_donation') {
source = String(input.fallbackSource || '').trim()
}
if (source !== 'cell_storage' && source !== 'research_donation') return null
const sampleId = String(input.protocolSampleId || '').trim()
const sampleCode = String(input.sampleCode || '').trim()
const labStorageCode = String(input.labStorageCode || '').trim()
const protocolId = String(input.collectionProtocolId || '').trim()
if (!sampleId && !sampleCode) return null
return {
receptionSource: source,
sampleId: sampleId || undefined,
sampleCode: sampleCode || undefined,
labStorageCode: labStorageCode || undefined,
protocolId: protocolId || undefined
}
}
@@ -82,6 +82,11 @@
align="center"
show-overflow-tooltip
/>
<el-table-column label="样本状态" min-width="140" align="center">
<template #default="{ row }">
<SampleStatusTag :status="row.sampleStatus" :void-desc="row.voidDesc" />
</template>
</el-table-column>
<el-table-column label="市场专员" min-width="110" align="center">
<template #default="{ row }">{{ row.salesUserName || '—' }}</template>
</el-table-column>
@@ -265,6 +270,7 @@
<script setup lang="ts">
import { Search, RefreshLeft, Document, Close } from '@element-plus/icons-vue'
import ProtocolViewDialog from '../protocol/ProtocolViewDialog.vue'
import SampleStatusTag from '@/components/business/sample-status-tag/index.vue'
import ProtocolAttachmentReadonly from '../protocol/ProtocolAttachmentReadonly.vue'
import { downloadAttachmentFile } from '@/utils/download-attachment'
import {
@@ -90,6 +90,11 @@
align="center"
show-overflow-tooltip
/>
<el-table-column label="样本状态" min-width="140" align="center">
<template #default="{ row }">
<SampleStatusTag :status="row.sampleStatus" :void-desc="row.voidDesc" />
</template>
</el-table-column>
<el-table-column label="签署日期" min-width="110" align="center">
<template #default="{ row }">{{ row.signDate || '—' }}</template>
</el-table-column>
@@ -295,6 +300,7 @@
import ProtocolViewDialog from '../protocol/ProtocolViewDialog.vue'
import ProtocolAttachmentReadonly from '../protocol/ProtocolAttachmentReadonly.vue'
import SamplePaymentDetailDialog from '@/components/business/sample-payment-detail-dialog/index.vue'
import SampleStatusTag from '@/components/business/sample-status-tag/index.vue'
import { downloadAttachmentFile } from '@/utils/download-attachment'
import { fetchSamplePaymentList, fetchSamplePaymentDetail } from '@/api/protocol-sample-payment'
import { type CollectionProtocolRow } from '@/api/collection-protocol'
@@ -175,6 +175,11 @@
<span class="mono">{{ row.labStorageCode || '—' }}</span>
</template>
</el-table-column>
<el-table-column label="样本状态" min-width="140" align="center" header-align="center">
<template #default="{ row }">
<SampleStatusTag :status="row.sampleStatus" :void-desc="row.sampleVoidDesc" />
</template>
</el-table-column>
<el-table-column label="协议状态" min-width="100" align="center" header-align="center">
<template #default="{ row }">
<el-tag :type="donationStatusTagType(row.donationStatus)" size="small">
@@ -415,6 +420,7 @@
<script setup lang="ts">
import ProjectSelect from '@/components/business/ProjectSelect.vue'
import SampleStatusTag from '@/components/business/sample-status-tag/index.vue'
const projectFilter = ref('')
const teamFilter = ref('')
import { formatDisplayOrDash } from '@/utils/datetime-display'
@@ -197,6 +197,11 @@
<span class="mono">{{ row.sampleCode || '—' }}</span>
</template>
</el-table-column>
<el-table-column label="样本状态" min-width="140" align="center" header-align="center">
<template #default="{ row }">
<SampleStatusTag :status="row.sampleStatus" :void-desc="row.sampleVoidDesc" />
</template>
</el-table-column>
<el-table-column
prop="sampleTypeName"
label="样本类型"
@@ -383,6 +388,7 @@
<script setup lang="ts">
import ProjectSelect from '@/components/business/ProjectSelect.vue'
import SampleStatusTag from '@/components/business/sample-status-tag/index.vue'
const projectFilter = ref('')
const teamFilter = ref('')
import { formatDisplayOrDash } from '@/utils/datetime-display'
@@ -141,9 +141,10 @@
<span class="sample-card__seq">{{ sIdx + 1 }}</span>
{{ sampleTypeName(row.sampleTypeId) }}
</div>
<el-tag :type="sampleStatusTagType(String(row.sampleStatus || ''))" size="small">
{{ sampleStatusLabel(String(row.sampleStatus || '')) }}
</el-tag>
<SampleStatusTag
:status="row.sampleStatus"
:void-desc="row.voidDesc"
/>
</div>
<div class="sample-card__body">
<div class="sample-card__section">
@@ -1254,6 +1255,7 @@
import SampleQcInfoGroupedPanel from '@/components/business/sample-qc-info-grouped-panel/index.vue'
import SampleReceptionDualReadonlyPanel from '@/components/business/sample-reception-dual-readonly-panel/index.vue'
import SampleCodeWithSpecialDisplay from '@/components/business/sample-code-with-special-display/index.vue'
import SampleStatusTag from '@/components/business/sample-status-tag/index.vue'
import SampleProductionInfoCards from '@/components/business/sample-production-info-cards/index.vue'
import SampleStorageReleaseInfo from '@/components/business/sample-storage-release-info/index.vue'
import ProtocolHandlePanel from '@/components/business/protocol-handle-panel/index.vue'
@@ -1284,8 +1286,6 @@
payModeTagType,
newbornSexLabel,
deliveryModeLabel,
sampleStatusLabel,
sampleStatusTagType,
transportTypeLabel,
payStatusLabel,
payStatusTagType
@@ -206,6 +206,11 @@
<span class="cell-wrap-text">{{ row.sampleCode || '—' }}</span>
</template>
</el-table-column>
<el-table-column label="样本状态" min-width="140" align="center" header-align="center">
<template #default="{ row }">
<SampleStatusTag :status="row.sampleStatus" :void-desc="row.voidDesc" />
</template>
</el-table-column>
<el-table-column
prop="sampleTypeName"
label="样本类型"
@@ -320,6 +325,7 @@
sampleFreightSpanMethod,
type SampleFreightFlatRow
} from '@/utils/sample-freight-flatten'
import SampleStatusTag from '@/components/business/sample-status-tag/index.vue'
import FreightConfigDialog from './FreightConfigDialog.vue'
import FreightEditDialog from './FreightEditDialog.vue'
@@ -207,6 +207,11 @@
/>
</template>
</el-table-column>
<el-table-column label="样本状态" min-width="140" align="center">
<template #default="{ row }">
<SampleStatusTag :status="row.sampleStatus" :void-desc="row.voidDesc" />
</template>
</el-table-column>
<el-table-column prop="motherName" label="母亲姓名" min-width="100" align="center" />
<el-table-column prop="motherPhone" label="母亲电话" min-width="120" align="center">
<template #default="{ row }">{{ row.motherPhone || '—' }}</template>
@@ -368,6 +373,11 @@
/>
</template>
</el-table-column>
<el-table-column label="样本状态" min-width="140" align="center">
<template #default="{ row }">
<SampleStatusTag :status="row.sampleStatus" :void-desc="row.voidDesc" />
</template>
</el-table-column>
<el-table-column prop="labStorageCode" label="实验室入库编码" min-width="150" align="center">
<template #default="{ row }">{{ row.labStorageCode || '—' }}</template>
</el-table-column>
@@ -503,6 +513,7 @@
import ProtocolViewDialog from '@/views/cell-storage/protocol/ProtocolViewDialog.vue'
import DonationViewDialog from '@/views/research-donation/list/DonationViewDialog.vue'
import SampleCodeWithSpecialDisplay from '@/components/business/sample-code-with-special-display/index.vue'
import SampleStatusTag from '@/components/business/sample-status-tag/index.vue'
import SampleInfoQuickRegisterDialog from './SampleInfoQuickRegisterDialog.vue'
import SampleCodeCorrectionDialog from './SampleCodeCorrectionDialog.vue'
import {
@@ -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>
@@ -105,6 +105,13 @@
>
<el-icon><EditPen /></el-icon>样本接收信息填写
</el-button>
<el-button
v-if="showSampleVoidButton(row)"
class="btn-op-item"
@click="openSampleVoidDialog(row)"
>
<el-icon><Delete /></el-icon>样本废弃
</el-button>
<el-button
v-if="showCardComplete(row) && canComplete(row)"
class="btn-op-item"
@@ -169,8 +176,13 @@
>
<dt>{{ field.label }}</dt>
<dd>
<SampleStatusTag
v-if="field.kind === 'sample-status'"
:status="row.sampleStatus"
:void-desc="row.voidDesc"
/>
<el-tag
v-if="field.kind === 'tag'"
v-else-if="field.kind === 'tag'"
:type="field.getTagType?.(row) || 'info'"
size="small"
:class="{
@@ -319,6 +331,11 @@
:sample-code="storageCertQcSampleCode"
:sample-type-name="storageCertQcSampleTypeName"
/>
<SampleVoidDialog
v-model:visible="sampleVoidVisible"
:target="sampleVoidTarget"
@success="emit('sample-voided')"
/>
</div>
</template>
@@ -342,7 +359,11 @@
import type { OutboundQcDetailProduct } from '@/api/qc-work-order'
import type { ProductionWorkOrderCardMetaConfig } from '@/utils/production-work-order-card-meta'
import SampleCodeWithSpecialDisplay from '@/components/business/sample-code-with-special-display/index.vue'
import SampleStatusTag from '@/components/business/sample-status-tag/index.vue'
import SampleVoidDialog from '@/components/business/sample-void-dialog/index.vue'
import type { SampleVoidTarget } from '@/api/business-sample'
import StorageCertQcDialog from '@/components/business/storage-cert-qc-dialog/index.vue'
import { isSampleAlreadyVoided, resolveSampleVoidTarget } from '@/utils/sample-void'
import { supportsStorageCertQc } from '@/utils/storage-cert-qc-fields'
import {
getCardMetaConfigForLegacyTab,
@@ -411,6 +432,8 @@
const storageCertQcVisible = ref(false)
const storageCertQcSampleCode = ref('')
const storageCertQcSampleTypeName = ref('')
const sampleVoidVisible = ref(false)
const sampleVoidTarget = ref<SampleVoidTarget | null>(null)
function showStorageCertQcButton(row: ProductionWorkOrderItem) {
const tabKey = resolveEffectiveRowTabKey(listTabKey.value, row)
@@ -463,6 +486,39 @@
return INBOUND_SAMPLE_TITLE_TAB_KEYS.has(effectiveTabKey)
}
function productionVoidFallbackSource(row: ProductionWorkOrderItem) {
const tabKey = resolveEffectiveRowTabKey(listTabKey.value, row)
if (tabKey === 'inbound_research_donation') return 'research_donation'
if (tabKey === 'inbound_cell_storage') return 'cell_storage'
return ''
}
function showSampleVoidButton(row: ProductionWorkOrderItem) {
if (!isInboundSampleTitle(row) || isSampleAlreadyVoided(row.sampleStatus)) return false
return !!resolveSampleVoidTarget({
receptionSource: row.receptionSource,
protocolSampleId: row.protocolSampleId,
sampleCode: row.sampleCode,
labStorageCode: row.labStorageCode,
collectionProtocolId: row.collectionProtocolId,
fallbackSource: productionVoidFallbackSource(row)
})
}
function openSampleVoidDialog(row: ProductionWorkOrderItem) {
const target = resolveSampleVoidTarget({
receptionSource: row.receptionSource,
protocolSampleId: row.protocolSampleId,
sampleCode: row.sampleCode,
labStorageCode: row.labStorageCode,
collectionProtocolId: row.collectionProtocolId,
fallbackSource: productionVoidFallbackSource(row)
})
if (!target) return
sampleVoidTarget.value = target
sampleVoidVisible.value = true
}
function inboundCardTitleLab(row: ProductionWorkOrderItem) {
return (row.labStorageCode || '').trim() || '—'
}
@@ -500,6 +556,7 @@
'page-change': [page: number]
'page-size-change': [size: number]
'open-sample-reception': [row: ProductionWorkOrderItem]
'sample-voided': []
}>()
const showCardOpsRow = computed(() => true)
@@ -198,6 +198,7 @@
@tasks-changed="onTasksChanged"
@counts-changed="onCountsChanged"
@open-sample-reception="handleOpenSampleReception"
@sample-voided="handleSampleVoided"
@page-change="onWorkOrderPageChange"
@page-size-change="onWorkOrderPageSizeChange"
/>
@@ -371,6 +372,11 @@
emit('data-changed')
}
function handleSampleVoided() {
loadData()
emit('data-changed')
}
defineExpose({
reload: loadData,
bumpTaskRefresh,
@@ -93,9 +93,16 @@
:min-width="col.minWidth || 120"
align="center"
header-align="center"
show-overflow-tooltip
:show-overflow-tooltip="col.prop !== 'sampleStatus'"
>
<template #default="{ row }">{{ displayCell(row[col.prop]) }}</template>
<template #default="{ row }">
<SampleStatusTag
v-if="col.prop === 'sampleStatus'"
:status="String(row.sampleStatus || '')"
:void-desc="String(row.voidDesc || '')"
/>
<template v-else>{{ displayCell(row[col.prop]) }}</template>
</template>
</el-table-column>
<el-table-column
label="操作"
@@ -178,11 +185,13 @@
saveLabSampleProcessSupplement,
type LabSampleProcessTabKey
} from '@/api/lab-sample-process'
import SampleStatusTag from '@/components/business/sample-status-tag/index.vue'
import {
LAB_PROCESS_COLUMNS,
LAB_PROCESS_TABS,
SUPPLEMENT_FIELD_LABELS
} from '@/utils/lab-sample-process-columns'
import { sampleStatusLabel } from '@/utils/status-tag-registry'
defineOptions({ name: 'QualityInspectionLabSampleProcess' })
@@ -274,9 +283,9 @@
supplementForm.receptionSource = meta.source
supplementForm.sampleTypeName = meta.sampleTypeName
supplementForm.remark = ''
const keys = supplementKeys.value.length
? supplementKeys.value
: currentColumns.value.map((c) => c.prop)
const keys = (
supplementKeys.value.length ? supplementKeys.value : currentColumns.value.map((c) => c.prop)
).filter((k) => k !== 'sampleStatus' && k !== 'voidDesc')
const payload: Record<string, string> = {}
keys.forEach((k) => {
payload[k] = ''
@@ -324,6 +333,10 @@
}
cols.forEach((c) => {
const v = row[c.prop]
if (c.prop === 'sampleStatus') {
line[c.label] = v ? sampleStatusLabel(String(v)) : ''
return
}
line[c.label] = v === null || v === undefined || v === '' ? '' : String(v)
})
return line
@@ -154,6 +154,7 @@
type QcTaskResultItem
} from '@/api/qc-task-result'
import { taskStatusLabel, taskStatusTagType } from '@/utils/qc-labels'
import { resolveThirdPartyFillDefaults } from '@/utils/qc-result-fill-defaults'
import { parseQcParamOptions } from '@/utils/qc-item-param-options'
import {
pickSharedRemarkAndAttachments,
@@ -233,16 +234,6 @@
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[] {
return (items || []).map((p) => ({
...p,
@@ -319,13 +310,17 @@
companyId: detail?.companyId ?? task.companyId,
companyName: detail?.companyName ?? task.companyName
}
const fillDefaults = resolveThirdPartyFillDefaults({
taskStatus: merged.taskStatus,
conclusion: merged.conclusion
})
const item: ItemState = {
taskId: task.id,
itemName: merged.itemName || '—',
companyName: thirdPartyCompanyDisplayName(merged),
params: normalizeResultParams(results || []),
saveStatus: normalizeThirdPartySaveStatus(merged.taskStatus),
conclusion: normalizeConclusion(merged.conclusion)
saveStatus: fillDefaults.saveStatus,
conclusion: fillDefaults.conclusion
}
return { item, merged }
})
@@ -385,6 +380,11 @@
const thirdPartyAttachments = financeAttachmentsToUrlString(attachments.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
const failures: string[] = []
let successCount = 0
@@ -404,7 +404,8 @@
})),
remark: remarkVal,
thirdPartyAttachments,
taskStatus: item.saveStatus
taskStatus: item.saveStatus,
operateBatchId
},
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>
@@ -25,6 +25,7 @@
@command="(cmd, row) => emit('command', cmd, row)"
@tasks-changed="emit('tasks-changed')"
@sample-special-changed="emit('sample-special-changed')"
@sample-voided="emit('sample-voided')"
/>
<QcWorkOrderSampleGroup
v-for="ins in insertedCardsAfter(allTabInboundAnchorId(item.group))"
@@ -49,6 +50,7 @@
@command="(cmd, row) => emit('command', cmd, row)"
@tasks-changed="emit('tasks-changed')"
@sample-special-changed="emit('sample-special-changed')"
@sample-voided="emit('sample-voided')"
/>
</template>
<QcWorkOrderSingleCard
@@ -69,6 +71,7 @@
@command="(cmd, row) => emit('command', cmd, row)"
@tasks-changed="emit('tasks-changed')"
@sample-special-changed="emit('sample-special-changed')"
@sample-voided="emit('sample-voided')"
/>
</template>
</template>
@@ -96,6 +99,7 @@
@command="(cmd, row) => emit('command', cmd, row)"
@tasks-changed="emit('tasks-changed')"
@sample-special-changed="emit('sample-special-changed')"
@sample-voided="emit('sample-voided')"
/>
<QcWorkOrderSampleGroup
v-for="ins in insertedCardsAfter(item.cardAnchorId)"
@@ -120,6 +124,7 @@
@command="(cmd, row) => emit('command', cmd, row)"
@tasks-changed="emit('tasks-changed')"
@sample-special-changed="emit('sample-special-changed')"
@sample-voided="emit('sample-voided')"
/>
</template>
</template>
@@ -141,6 +146,7 @@
@command="(cmd, row) => emit('command', cmd, row)"
@tasks-changed="emit('tasks-changed')"
@sample-special-changed="emit('sample-special-changed')"
@sample-voided="emit('sample-voided')"
/>
</template>
</template>
@@ -163,6 +169,7 @@
@command="(cmd, row) => emit('command', cmd, row)"
@tasks-changed="emit('tasks-changed')"
@sample-special-changed="emit('sample-special-changed')"
@sample-voided="emit('sample-voided')"
/>
</template>
<el-empty
@@ -252,6 +259,7 @@
command: [cmd: string, row: QcWorkOrder]
'tasks-changed': []
'sample-special-changed': []
'sample-voided': []
'page-change': [page: number]
'page-size-change': [size: number]
'sibling-navigate': [payload: InboundSiblingNavigatePayload]
@@ -115,6 +115,7 @@
@command="(cmd, row) => emit('command', cmd, row)"
@tasks-changed="emit('tasks-changed')"
@sample-special-changed="emit('sample-special-changed')"
@sample-voided="emit('sample-voided')"
/>
<SampleSpecialMarkDialog
@@ -181,6 +182,7 @@
command: [cmd: string, row: QcWorkOrder]
'tasks-changed': []
'sample-special-changed': []
'sample-voided': []
}>()
const sampleSpecialDialogVisible = ref(false)
@@ -117,6 +117,7 @@
@command="(cmd, row) => emit('command', cmd, row)"
@tasks-changed="emit('tasks-changed')"
@sample-special-changed="emit('sample-special-changed')"
@sample-voided="emit('sample-voided')"
/>
<SampleSpecialMarkDialog
@@ -201,6 +202,7 @@
command: [cmd: string, row: QcWorkOrder]
'tasks-changed': []
'sample-special-changed': []
'sample-voided': []
'sibling-navigate': [payload: InboundSiblingNavigatePayload]
}>()
@@ -64,8 +64,13 @@
>
<dt>{{ field.label }}</dt>
<dd>
<SampleStatusTag
v-if="field.kind === 'sample-status'"
:status="row.sampleStatus"
:void-desc="row.voidDesc"
/>
<el-tag
v-if="field.kind === 'tag'"
v-else-if="field.kind === 'tag'"
:type="field.getTagType?.(row) || 'info'"
size="small"
>
@@ -162,6 +167,13 @@
>
<el-icon><EditPen /></el-icon>特殊样本
</el-button>
<el-button
v-if="showSampleVoidButton"
class="btn-op-item"
@click="openSampleVoidDialog"
>
<el-icon><Delete /></el-icon>样本废弃
</el-button>
<el-button
v-if="showStorageCertQcButton"
class="btn-op-item"
@@ -190,6 +202,13 @@
>
<el-icon><EditPen /></el-icon>特殊样本
</el-button>
<el-button
v-if="showSampleVoidButton"
class="btn-op-item"
@click="openSampleVoidDialog"
>
<el-icon><Delete /></el-icon>样本废弃
</el-button>
<el-button
v-if="showStorageCertQcButton"
class="btn-op-item"
@@ -254,6 +273,11 @@
:target="sampleSpecialMarkTarget"
@success="emit('sample-special-changed')"
/>
<SampleVoidDialog
v-model:visible="sampleVoidDialogVisible"
:target="sampleVoidTarget"
@success="emit('sample-voided')"
/>
<StorageCertQcDialog
v-model:visible="storageCertQcVisible"
mode="edit"
@@ -302,7 +326,11 @@
import QcWorkOrderProtocolPaymentPanel from './QcWorkOrderProtocolPaymentPanel.vue'
import SampleCodeWithSpecialDisplay from '@/components/business/sample-code-with-special-display/index.vue'
import SampleSpecialMarkDialog from '@/components/business/sample-special-mark-dialog/index.vue'
import SampleStatusTag from '@/components/business/sample-status-tag/index.vue'
import SampleVoidDialog from '@/components/business/sample-void-dialog/index.vue'
import type { SampleVoidTarget } from '@/api/business-sample'
import { resolveInboundSampleSpecialMarkTargetFromRow } from '@/utils/inbound-sample-special-mark'
import { isSampleAlreadyVoided, resolveSampleVoidTarget } from '@/utils/sample-void'
import QcWorkOrderSelectCheckbox from './QcWorkOrderSelectCheckbox.vue'
defineOptions({ name: 'QcWorkOrderSingleCard' })
@@ -340,9 +368,12 @@
command: [cmd: string, row: QcWorkOrder]
'tasks-changed': []
'sample-special-changed': []
'sample-voided': []
}>()
const sampleSpecialDialogVisible = ref(false)
const sampleVoidDialogVisible = ref(false)
const sampleVoidTarget = ref<SampleVoidTarget | null>(null)
const storageCertQcVisible = ref(false)
const showStorageCertQcButton = computed(() => {
@@ -377,6 +408,33 @@
resolveEffectiveRowTabKey(props.cardMetaConfig.tabKey, props.row)
)
function inboundVoidFallbackSource() {
if (effectiveRowTabKey.value === 'inbound_research_donation') return 'research_donation'
if (effectiveRowTabKey.value === 'inbound_cell_storage') return 'cell_storage'
return ''
}
const sampleVoidResolved = computed(() =>
resolveSampleVoidTarget({
receptionSource: props.row.receptionSource,
protocolSampleId: props.row.protocolSampleId,
sampleCode: props.row.sampleCode,
labStorageCode: props.row.labStorageCode,
collectionProtocolId: props.row.collectionProtocolId,
fallbackSource: inboundVoidFallbackSource()
})
)
const showSampleVoidButton = computed(
() => !!sampleVoidResolved.value && !isSampleAlreadyVoided(props.row.sampleStatus)
)
function openSampleVoidDialog() {
if (!sampleVoidResolved.value) return
sampleVoidTarget.value = sampleVoidResolved.value
sampleVoidDialogVisible.value = true
}
const visibleMetaFields = computed(() =>
effectiveCardMeta.value.metaFields.filter((field) => !field.visible || field.visible(props.row))
)
@@ -33,6 +33,16 @@
@click="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">
<span class="qc-task-card__name">{{ ALL_THIRD_PARTY_CARD_TITLE }}</span>
<div class="qc-task-card__sub">
@@ -77,6 +87,16 @@
class="qc-task-card qc-task-card--compact"
@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">
<span class="qc-task-card__name">{{ item.task.itemName || '—' }}</span>
<div class="qc-task-card__tags">
@@ -414,6 +434,12 @@
@saved="handleTaskMutationSuccess"
/>
<QcTaskResultChangeLogDialog
v-model:visible="changeLogVisible"
:task-ids="changeLogTaskIds"
:title-suffix="changeLogTitleSuffix"
/>
<SystemViewDialog
v-model:visible="viewVisible"
title="任务详情"
@@ -575,7 +601,8 @@
EditPen,
Plus,
More,
Delete
Delete,
Clock
} from '@element-plus/icons-vue'
import ProtocolFinanceConfirmFields from '@/components/business/protocol-finance-confirm-fields/index.vue'
import ProtocolAttachmentReadonly from '@/views/cell-storage/protocol/ProtocolAttachmentReadonly.vue'
@@ -612,6 +639,7 @@
import { fetchItemUnitList } from '@/api/admin'
import { SHOW_QC_TASK_MATERIAL_USAGE } from '@/utils/qc-material-ui'
import { parseQcParamOptions } from '@/utils/qc-item-param-options'
import { resolveQcResultFillDefaults } from '@/utils/qc-result-fill-defaults'
import {
taskTypeLabel,
taskTypeTagType,
@@ -656,6 +684,7 @@
type QcTaskListDisplayItem
} from '@/utils/qc-company-task-group'
import QcCompanyTaskResultDialog from './QcCompanyTaskResultDialog.vue'
import QcTaskResultChangeLogDialog from './QcTaskResultChangeLogDialog.vue'
/** 根据来源类型返回协议状态标签 */
function protocolStatusLabelBySource(status: string, source: string, voidType?: string): string {
@@ -739,6 +768,25 @@
const companyDialogReadonly = ref(false)
const companyDialogTasks = ref<QcTask[]>([])
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) {
let tasks = item.tasks
@@ -864,11 +912,6 @@
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) {
if (row.taskType === 'sysz') {
return row.taskStatus === 'jxz' || row.taskStatus === 'ywc'
@@ -1391,12 +1434,16 @@
}
return
}
const initialDefaults = resolveQcResultFillDefaults({
taskStatus: row.taskStatus,
conclusion: row.conclusion
})
resultTaskStatus.value = row.taskStatus
resultSaveStatus.value = normalizeResultSaveStatus(row.taskStatus)
resultSaveStatus.value = initialDefaults.saveStatus
resultTaskId.value = row.id
resultTaskType.value = row.taskType
resultRemark.value = row.remark || ''
resultConclusion.value = ''
resultConclusion.value = initialDefaults.conclusion
resultAttachments.value = apiFilesToFinanceItems(row.attachmentFiles)
materialUsages.value = []
requisitionOptions.value = []
@@ -1404,10 +1451,13 @@
try {
const detail = await fetchQcTaskDetail(row.id)
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 || ''
const c = (detail.conclusion || '').trim()
resultConclusion.value = c === 'tg' || c === 'btg' ? c : ''
resultConclusion.value = fillDefaults.conclusion
resultAttachments.value = apiFilesToFinanceItems(detail.attachmentFiles)
const results = await fetchQcTaskResults(row.id)
resultParams.value = normalizeResultParams(results || [])
@@ -1675,6 +1725,7 @@
}
.qc-task-card {
position: relative;
display: flex;
flex-direction: column;
gap: 6px;
@@ -1702,7 +1753,7 @@
width: 100%;
max-width: 220px;
gap: 4px;
padding: 6px 8px;
padding: 6px 28px 6px 8px;
}
&--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 {
width: 100%;
font-size: 11px;
@@ -362,6 +362,7 @@
@command="handleCommand"
@tasks-changed="onWorkOrderTasksChanged"
@sample-special-changed="onSampleSpecialChanged"
@sample-voided="onSampleVoided"
@page-change="handleWorkOrderPageChange"
@page-size-change="handleWorkOrderPageSizeChange"
/>
@@ -560,6 +561,11 @@
emit('data-changed')
}
async function onSampleVoided() {
await loadData()
emit('data-changed')
}
function handleCommand(command: string, row: QcWorkOrder) {
if (command === 'view') {
handleView(row)