Compare commits

...
Author SHA1 Message Date
zlwuandCursor 3f16a8ab3e fix(protocol): 协议作废/属地废弃同步样本状态为已作废
协议变为 yzf 或 sdfq 时,除样本接收废弃联动外,将下属有效样本 sample_status 置为 yzf 并写入 void_date;补充历史回刷 SQL 与单测(#127)。

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

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

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

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

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

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

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

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

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

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

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

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

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

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-13 11:01:48 +08:00
35 changed files with 2576 additions and 501 deletions

No files matched your search

+1 -1
View File
@@ -2677,7 +2677,7 @@ def update_collection_protocol(
next_status = protocol_status.strip() next_status = protocol_status.strip()
assert_protocol_status_transition(obj.protocol_status or "", next_status, kind="protocol") assert_protocol_status_transition(obj.protocol_status or "", next_status, kind="protocol")
obj.protocol_status = next_status obj.protocol_status = next_status
if next_status == "yzf" and from_status != "yzf": if next_status in ("yzf", "sdfq") and from_status not in ("yzf", "sdfq"):
voided_now = True voided_now = True
if next_status == "yzf" and void_time is not None: if next_status == "yzf" and void_time is not None:
if void_type is None or not str(void_type).strip(): if void_type is None or not str(void_type).strip():
+33
View File
@@ -49,6 +49,7 @@ from app.models.models import (
BizPilotInfusionSchedule, BizPilotInfusionSchedule,
BizPilotInfusionScheduleProduct, BizPilotInfusionScheduleProduct,
BizPilotPatient, BizPilotPatient,
BizProtocolCollectionInfo,
BizProtocolPartyCustomer, BizProtocolPartyCustomer,
BizProtocolSample, BizProtocolSample,
BizProductionTask, BizProductionTask,
@@ -69,6 +70,7 @@ from app.models.models import (
from app.models.qc_param import BizQcTaskResult from app.models.qc_param import BizQcTaskResult
from app.models.research_donation import ( from app.models.research_donation import (
BizResearchDonation, BizResearchDonation,
BizResearchDonationCollection,
BizResearchDonationParty, BizResearchDonationParty,
BizResearchDonationSample, BizResearchDonationSample,
) )
@@ -808,12 +810,39 @@ def _enrich_work_order_list_items(
party.mother_name or "", party.mother_name or "",
party.newborn_name or "", party.newborn_name or "",
) )
cell_maternal_map: Dict[str, str] = {}
if cell_proto_ids:
for coll in (
db.query(BizProtocolCollectionInfo)
.filter(
BizProtocolCollectionInfo.collection_protocol_id.in_(cell_proto_ids),
BizProtocolCollectionInfo.del_flag == 0,
)
.all()
):
cell_maternal_map[coll.collection_protocol_id] = _fmt_dt(
coll.maternal_blood_collect_time
)
donation_maternal_map: Dict[str, str] = {}
if donation_ids:
for coll in (
db.query(BizResearchDonationCollection)
.filter(
BizResearchDonationCollection.research_donation_id.in_(donation_ids),
BizResearchDonationCollection.del_flag == 0,
)
.all()
):
donation_maternal_map[coll.research_donation_id] = _fmt_dt(
coll.maternal_blood_collect_time
)
for item in items: for item in items:
if item.get("workOrderType") == "temporary": if item.get("workOrderType") == "temporary":
item["receptionSource"] = "" item["receptionSource"] = ""
item["receptionSourceLabel"] = "" item["receptionSourceLabel"] = ""
item["motherName"] = "" item["motherName"] = ""
item["newbornName"] = "" item["newbornName"] = ""
item["maternalBloodCollectTime"] = ""
continue continue
rec = _resolve_reception(item) rec = _resolve_reception(item)
source = _effective_reception_source(item, rec) source = _effective_reception_source(item, rec)
@@ -826,6 +855,7 @@ def _enrich_work_order_list_items(
_mother, _newborn = donation_party_map.get(_did or "", ("", "")) _mother, _newborn = donation_party_map.get(_did or "", ("", ""))
item["motherName"] = _mother item["motherName"] = _mother
item["newbornName"] = _newborn item["newbornName"] = _newborn
item["maternalBloodCollectTime"] = donation_maternal_map.get(_did or "", "") or ""
else: else:
_pid = ( _pid = (
(getattr(rec, "collection_protocol_id", None) if rec else None) or "" (getattr(rec, "collection_protocol_id", None) if rec else None) or ""
@@ -833,6 +863,7 @@ def _enrich_work_order_list_items(
_mother, _newborn = cell_party_map.get(_pid or "", ("", "")) _mother, _newborn = cell_party_map.get(_pid or "", ("", ""))
item["motherName"] = _mother item["motherName"] = _mother
item["newbornName"] = _newborn item["newbornName"] = _newborn
item["maternalBloodCollectTime"] = cell_maternal_map.get(_pid or "", "") or ""
if not rec: if not rec:
item.setdefault("receptionTime", "") item.setdefault("receptionTime", "")
item.setdefault("handlerName", "") item.setdefault("handlerName", "")
@@ -1140,6 +1171,7 @@ def _wo_to_dict(
"receptionTime": "", "receptionTime": "",
"handlerName": "", "handlerName": "",
"sampleTypeName": "", "sampleTypeName": "",
"maternalBloodCollectTime": "",
"workOrderStatus": wo.work_order_status, "workOrderStatus": wo.work_order_status,
"workOrderStatusLabel": _WORK_ORDER_STATUS_LABELS.get( "workOrderStatusLabel": _WORK_ORDER_STATUS_LABELS.get(
wo.work_order_status or "", wo.work_order_status or "" wo.work_order_status or "", wo.work_order_status or ""
@@ -2601,6 +2633,7 @@ def get_work_order_detail(
"receptionSourceLabel": enriched.get("receptionSourceLabel", ""), "receptionSourceLabel": enriched.get("receptionSourceLabel", ""),
"motherName": enriched.get("motherName", ""), "motherName": enriched.get("motherName", ""),
"newbornName": enriched.get("newbornName", ""), "newbornName": enriched.get("newbornName", ""),
"maternalBloodCollectTime": enriched.get("maternalBloodCollectTime", ""),
"protocolStatus": enriched.get("protocolStatus", ""), "protocolStatus": enriched.get("protocolStatus", ""),
"protocolStatusLabel": enriched.get("protocolStatusLabel", ""), "protocolStatusLabel": enriched.get("protocolStatusLabel", ""),
"cellProductCode": enriched.get("cellProductCode", ""), "cellProductCode": enriched.get("cellProductCode", ""),
+2 -1
View File
@@ -1702,7 +1702,8 @@ def change_status(
) )
db.add(obj) db.add(obj)
if ns == "yzf" and (current or "").strip() != "yzf": from_status = (current or "").strip()
if ns in ("yzf", "sdfq") and from_status not in ("yzf", "sdfq"):
from app.services.protocol_reception_discard_sync import after_protocol_voided from app.services.protocol_reception_discard_sync import after_protocol_voided
after_protocol_voided( after_protocol_voided(
@@ -1,16 +1,19 @@
"""市场协议作废 ↔ 质检样本接收废弃双向联动。 """市场协议无效态 ↔ 样本接收废弃 / 样本状态作废联动。
规则(细胞存储 / 科研捐赠): 规则(细胞存储 / 科研捐赠):
1. 协议变为已作废(yzf)时,协议下全部样本接收结论自动为废弃(bj)。 1. 协议变为已作废(yzf)或属地废弃(sdfq)时:
- 协议下全部样本接收结论自动为废弃(bj);
- 协议下全部有效样本 `sample_status` 置为已作废(yzf),并写入 `void_date`。
2. 协议下全部有效样本均已废弃/拒收(bj)时,协议自动已作废,作废类型为「实验室废弃」。 2. 协议下全部有效样本均已废弃/拒收(bj)时,协议自动已作废,作废类型为「实验室废弃」。
""" """
from __future__ import annotations from __future__ import annotations
from datetime import datetime from datetime import datetime
from typing import List, Optional from typing import List, Optional, Union
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from app.core.protocol_status_display import INACTIVE_PROTOCOL_STATUSES
from app.core.utils import generate_uuid from app.core.utils import generate_uuid
from app.models.models import ( from app.models.models import (
BizCollectionProtocol, BizCollectionProtocol,
@@ -23,11 +26,24 @@ from app.models.research_donation import BizResearchDonation, BizResearchDonatio
LAB_VOID_TYPE_CODE = "sysfq" LAB_VOID_TYPE_CODE = "sysfq"
LAB_VOID_TYPE_LABEL = "实验室废弃" LAB_VOID_TYPE_LABEL = "实验室废弃"
VOID_TYPE_DICT = "xyzflx" VOID_TYPE_DICT = "xyzflx"
SAMPLE_VOID_STATUS = "yzf"
_AUTO_DISCARD_REMARK = "协议作废自动废弃" _AUTO_DISCARD_REMARK = "协议作废自动废弃"
_AUTO_VOID_DESC = "全部样本接收废弃/拒收,系统自动作废" _AUTO_VOID_DESC = "全部样本接收废弃/拒收,系统自动作废"
def _void_date_yyyymmdd(
*,
void_time: Optional[datetime] = None,
void_date: Optional[str] = None,
) -> str:
raw = (void_date or "").strip()
if len(raw) == 8 and raw.isdigit():
return raw
ts = void_time or datetime.now()
return ts.strftime("%Y%m%d")
def ensure_lab_void_type(db: Session, *, tenant_no: str) -> str: def ensure_lab_void_type(db: Session, *, tenant_no: str) -> str:
"""确保租户字典 xyzflx 存在「实验室废弃」,返回 dict_value。""" """确保租户字典 xyzflx 存在「实验室废弃」,返回 dict_value。"""
tenant = (tenant_no or "").strip() tenant = (tenant_no or "").strip()
@@ -204,7 +220,7 @@ def discard_receptions_for_voided_protocol(
tenant_no: str, tenant_no: str,
user_id: Optional[str] = None, user_id: Optional[str] = None,
) -> int: ) -> int:
"""协议已作废后,将其下样本接收全部置为废弃。返回处理样本数。""" """协议无效后,将其下样本接收全部置为废弃。返回处理样本数。"""
src = (source or "").strip() src = (source or "").strip()
pid = (protocol_id or "").strip() pid = (protocol_id or "").strip()
tenant = (tenant_no or "").strip() tenant = (tenant_no or "").strip()
@@ -242,6 +258,75 @@ def discard_receptions_for_voided_protocol(
return len(samples) return len(samples)
def void_samples_for_inactive_protocol(
db: Session,
*,
source: str,
protocol_id: str,
tenant_no: str,
user_id: Optional[str] = None,
void_time: Optional[datetime] = None,
void_date: Optional[str] = None,
) -> int:
"""协议无效后,将其下有效样本状态一律置为已作废并写入 void_date。返回处理样本数。"""
src = (source or "").strip()
pid = (protocol_id or "").strip()
tenant = (tenant_no or "").strip()
if src not in ("cell_storage", "research_donation") or not pid or not tenant:
return 0
date_s = _void_date_yyyymmdd(void_time=void_time, void_date=void_date)
now = datetime.now()
if src == "cell_storage":
samples: List[Union[BizProtocolSample, BizResearchDonationSample]] = list(
_list_cell_samples(db, protocol_id=pid, tenant_no=tenant)
)
else:
samples = list(_list_donation_samples(db, donation_id=pid, tenant_no=tenant))
for sample in samples:
sample.sample_status = SAMPLE_VOID_STATUS
sample.void_date = date_s
sample.update_by = user_id
sample.update_time = now
db.add(sample)
db.flush()
return len(samples)
def _resolve_protocol_void_time(
db: Session,
*,
source: str,
protocol_id: str,
tenant_no: str,
) -> Optional[datetime]:
src = (source or "").strip()
pid = (protocol_id or "").strip()
tenant = (tenant_no or "").strip()
if src == "cell_storage":
obj = (
db.query(BizCollectionProtocol)
.filter(
BizCollectionProtocol.id == pid,
BizCollectionProtocol.tenant_no == tenant,
BizCollectionProtocol.del_flag == 0,
)
.first()
)
return obj.void_time if obj else None
obj = (
db.query(BizResearchDonation)
.filter(
BizResearchDonation.id == pid,
BizResearchDonation.tenant_no == tenant,
BizResearchDonation.del_flag == 0,
)
.first()
)
return obj.void_time if obj else None
def _all_samples_discarded( def _all_samples_discarded(
db: Session, db: Session,
*, *,
@@ -299,7 +384,7 @@ def maybe_void_protocol_when_all_samples_discarded(
if not obj: if not obj:
return False return False
status = (obj.protocol_status or "").strip() status = (obj.protocol_status or "").strip()
if status in ("yzf", "sdfq"): if status in INACTIVE_PROTOCOL_STATUSES:
return False return False
from app.core.protocol_status_display import assert_protocol_status_transition from app.core.protocol_status_display import assert_protocol_status_transition
from app.crud.collection_protocol import update_collection_protocol from app.crud.collection_protocol import update_collection_protocol
@@ -319,7 +404,8 @@ def maybe_void_protocol_when_all_samples_discarded(
void_desc=_AUTO_VOID_DESC, void_desc=_AUTO_VOID_DESC,
void_type=void_type, void_type=void_type,
commit=False, commit=False,
sync_reception_discard=False, # 接收已全部废弃;仍需同步样本状态为已作废
sync_reception_discard=True,
) )
return True return True
@@ -335,7 +421,7 @@ def maybe_void_protocol_when_all_samples_discarded(
if not obj: if not obj:
return False return False
status = (obj.donation_status or "").strip() status = (obj.donation_status or "").strip()
if status in ("yzf", "sdfq"): if status in INACTIVE_PROTOCOL_STATUSES:
return False return False
# 捐赠 change_status 默认 commit;此处内联等价逻辑避免提前提交。 # 捐赠 change_status 默认 commit;此处内联等价逻辑避免提前提交。
@@ -374,6 +460,14 @@ def maybe_void_protocol_when_all_samples_discarded(
) )
db.add(obj) db.add(obj)
db.flush() db.flush()
# 接收已全部废弃;仍需同步样本状态为已作废
after_protocol_voided(
db,
source="research_donation",
protocol_id=pid,
tenant_no=tenant,
user_id=user_id,
)
return True return True
@@ -411,7 +505,7 @@ def after_protocol_voided(
tenant_no: str, tenant_no: str,
user_id: Optional[str] = None, user_id: Optional[str] = None,
) -> None: ) -> None:
"""协议作废后:同步废弃其下全部样本接收。""" """协议作废/属地废弃后:同步废弃样本接收,并将样本状态置为已作废。"""
discard_receptions_for_voided_protocol( discard_receptions_for_voided_protocol(
db, db,
source=source, source=source,
@@ -419,3 +513,13 @@ def after_protocol_voided(
tenant_no=tenant_no, tenant_no=tenant_no,
user_id=user_id, user_id=user_id,
) )
void_samples_for_inactive_protocol(
db,
source=source,
protocol_id=protocol_id,
tenant_no=tenant_no,
user_id=user_id,
void_time=_resolve_protocol_void_time(
db, source=source, protocol_id=protocol_id, tenant_no=tenant_no
),
)
@@ -0,0 +1,472 @@
"""确保 UC 入库编码对应的 5 步内置工艺路线 / 任务组合存在。
步骤顺序(业务确认):
1. 脐带MSC原代细胞培养
2. 脐带MSC原代细胞培养半换液
3. 脐带MSC原代二次贴壁
4. 脐带MSC原代重铺操作
5. 干细胞冻存
内容从既有「干细胞培养(内置模版)」按工序代码拷贝,排除传代。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any, Dict, List, Optional
from sqlalchemy.orm import Session
from app.models.models import (
BizProcessRoute,
BizProcessRouteStep,
BizProcessRouteStepConsumable,
BizProcessRouteStepDataCollection,
BizProcessRouteStepOutput,
BizProcessRouteStepReagent,
BizProductionTaskSet,
BizProductionTaskSetItem,
)
from app.core.utils import generate_uuid
from app.utils.lab_storage_code_task_set import (
BC_MSC_BUILTIN_SET_NAME,
UC_MSC_BUILTIN_SET_NAME,
)
UC_MSC_ROUTE_CODE = "MSC原代-UC-BUILTIN"
UC_MSC_ROUTE_NAME = UC_MSC_BUILTIN_SET_NAME
SOURCE_MSC_ROUTE_CODE = "MSC培养-BUILTIN"
SOURCE_MSC_ROUTE_NAME = BC_MSC_BUILTIN_SET_NAME
# process_code → 目标 step_order
UC_MSC_STEP_ORDER: List[str] = [
"SOP-SC-003-E01-01", # 原代细胞培养
"SOP-SC-004-E01-01", # 半换液
"SOP-SC-006-E01-01", # 二次贴壁
"SOP-SC-005-E01-01", # 重铺
"SOP-SC-008-E01-01", # 冻存
]
def _now() -> datetime:
return datetime.now()
def get_uc_msc_builtin_set(
db: Session, *, tenant_no: str
) -> Optional[BizProductionTaskSet]:
return (
db.query(BizProductionTaskSet)
.filter(
BizProductionTaskSet.tenant_no == tenant_no,
BizProductionTaskSet.set_name == UC_MSC_BUILTIN_SET_NAME,
BizProductionTaskSet.is_builtin == "1",
BizProductionTaskSet.del_flag == 0,
)
.first()
)
def _find_source_route(db: Session, *, tenant_no: str) -> BizProcessRoute:
route = (
db.query(BizProcessRoute)
.filter(
BizProcessRoute.tenant_no == tenant_no,
BizProcessRoute.route_code == SOURCE_MSC_ROUTE_CODE,
BizProcessRoute.del_flag == 0,
)
.first()
)
if route:
return route
route = (
db.query(BizProcessRoute)
.filter(
BizProcessRoute.tenant_no == tenant_no,
BizProcessRoute.route_name == SOURCE_MSC_ROUTE_NAME,
BizProcessRoute.is_builtin == "1",
BizProcessRoute.del_flag == 0,
)
.first()
)
if not route:
raise ValueError(
f"缺少源工艺路线 {SOURCE_MSC_ROUTE_CODE}/{SOURCE_MSC_ROUTE_NAME},无法创建 UC 模版"
)
return route
def _clone_step_children(
db: Session,
*,
src_step_id: str,
dst_step_id: str,
tenant_no: str,
user_id: Optional[str],
create_dept_id: str,
now: datetime,
) -> None:
reagent_rows = (
db.query(BizProcessRouteStepReagent)
.filter(
BizProcessRouteStepReagent.step_id == src_step_id,
BizProcessRouteStepReagent.tenant_no == tenant_no,
BizProcessRouteStepReagent.del_flag == 0,
)
.all()
)
for r in reagent_rows:
db.add(
BizProcessRouteStepReagent(
id=generate_uuid(),
step_id=dst_step_id,
reagent_code=r.reagent_code,
reagent_name=r.reagent_name,
spec=r.spec,
standard_usage=r.standard_usage,
unit=r.unit,
is_key_material=r.is_key_material,
tenant_no=tenant_no,
order_num=r.order_num,
remark=r.remark,
create_by=user_id,
create_dept_id=create_dept_id or "",
create_time=now,
update_by=user_id,
update_time=now,
del_flag=0,
)
)
consumable_rows = (
db.query(BizProcessRouteStepConsumable)
.filter(
BizProcessRouteStepConsumable.step_id == src_step_id,
BizProcessRouteStepConsumable.tenant_no == tenant_no,
BizProcessRouteStepConsumable.del_flag == 0,
)
.all()
)
for c in consumable_rows:
db.add(
BizProcessRouteStepConsumable(
id=generate_uuid(),
step_id=dst_step_id,
consumable_code=c.consumable_code,
consumable_name=c.consumable_name,
spec_model=c.spec_model,
standard_usage=c.standard_usage,
unit=c.unit,
is_required=c.is_required,
remark=c.remark,
tenant_no=tenant_no,
order_num=c.order_num,
create_by=user_id,
create_dept_id=create_dept_id or "",
create_time=now,
update_by=user_id,
update_time=now,
del_flag=0,
)
)
output_rows = (
db.query(BizProcessRouteStepOutput)
.filter(
BizProcessRouteStepOutput.step_id == src_step_id,
BizProcessRouteStepOutput.tenant_no == tenant_no,
BizProcessRouteStepOutput.del_flag == 0,
)
.all()
)
for o in output_rows:
db.add(
BizProcessRouteStepOutput(
id=generate_uuid(),
step_id=dst_step_id,
output_type_id=o.output_type_id,
output_name=o.output_name,
output_barcode=o.output_barcode,
tenant_no=tenant_no,
order_num=o.order_num,
remark=o.remark,
create_by=user_id,
create_dept_id=create_dept_id or "",
create_time=now,
update_by=user_id,
update_time=now,
del_flag=0,
)
)
dc_rows = (
db.query(BizProcessRouteStepDataCollection)
.filter(
BizProcessRouteStepDataCollection.step_id == src_step_id,
BizProcessRouteStepDataCollection.tenant_no == tenant_no,
BizProcessRouteStepDataCollection.del_flag == 0,
)
.all()
)
for d in dc_rows:
db.add(
BizProcessRouteStepDataCollection(
id=generate_uuid(),
step_id=dst_step_id,
collection_name=d.collection_name,
unit=d.unit,
tenant_no=tenant_no,
order_num=d.order_num,
remark=d.remark,
create_by=user_id,
create_dept_id=create_dept_id or "",
create_time=now,
update_by=user_id,
update_time=now,
del_flag=0,
)
)
def _source_steps_by_code(
db: Session, *, route_id: str, tenant_no: str
) -> Dict[str, BizProcessRouteStep]:
rows = (
db.query(BizProcessRouteStep)
.filter(
BizProcessRouteStep.route_id == route_id,
BizProcessRouteStep.tenant_no == tenant_no,
BizProcessRouteStep.del_flag == 0,
)
.all()
)
out: Dict[str, BizProcessRouteStep] = {}
for row in rows:
code = (row.process_code or "").strip()
if code and code not in out:
out[code] = row
return out
def ensure_uc_msc_builtin_template(
db: Session,
*,
tenant_no: str,
user_id: Optional[str] = None,
create_dept_id: str = "",
) -> Dict[str, Any]:
"""幂等创建 UC 5 步内置路线与任务组合;已存在则直接返回。"""
existing = get_uc_msc_builtin_set(db, tenant_no=tenant_no)
if existing and (existing.status or "1") == "1":
item = (
db.query(BizProductionTaskSetItem)
.filter(
BizProductionTaskSetItem.set_id == existing.id,
BizProductionTaskSetItem.tenant_no == tenant_no,
BizProductionTaskSetItem.del_flag == 0,
)
.order_by(
BizProductionTaskSetItem.order_num.asc(),
BizProductionTaskSetItem.create_time.asc(),
)
.first()
)
if item and item.route_id:
route = (
db.query(BizProcessRoute)
.filter(
BizProcessRoute.id == item.route_id,
BizProcessRoute.tenant_no == tenant_no,
BizProcessRoute.del_flag == 0,
)
.first()
)
step_count = (
db.query(BizProcessRouteStep.id)
.filter(
BizProcessRouteStep.route_id == item.route_id,
BizProcessRouteStep.tenant_no == tenant_no,
BizProcessRouteStep.del_flag == 0,
)
.count()
)
if route and step_count >= len(UC_MSC_STEP_ORDER):
return {
"created": False,
"setId": existing.id,
"setName": existing.set_name,
"routeId": route.id,
"routeCode": route.route_code,
"stepCount": step_count,
}
source = _find_source_route(db, tenant_no=tenant_no)
by_code = _source_steps_by_code(db, route_id=source.id, tenant_no=tenant_no)
missing = [c for c in UC_MSC_STEP_ORDER if c not in by_code]
if missing:
raise ValueError(
"源工艺路线缺少工序,无法创建 UC 模版:" + "、".join(missing)
)
now = _now()
route = (
db.query(BizProcessRoute)
.filter(
BizProcessRoute.tenant_no == tenant_no,
BizProcessRoute.route_code == UC_MSC_ROUTE_CODE,
BizProcessRoute.del_flag == 0,
)
.first()
)
if not route:
route = BizProcessRoute(
id=generate_uuid(),
route_code=UC_MSC_ROUTE_CODE,
route_name=UC_MSC_ROUTE_NAME,
product_type_id=source.product_type_id,
version=source.version,
is_current="0",
equipment_ids=source.equipment_ids,
equipment_name=source.equipment_name,
tenant_no=tenant_no,
order_num=0,
remark="内置模版:UC 入库编码自动派发(5 步,不含传代)",
is_builtin="1",
create_by=user_id,
create_dept_id=create_dept_id or "",
create_time=now,
update_by=user_id,
update_time=now,
del_flag=0,
)
db.add(route)
db.flush()
else:
route.route_name = UC_MSC_ROUTE_NAME
route.is_builtin = "1"
route.update_by = user_id
route.update_time = now
db.add(route)
# 重建步骤(幂等:软删旧步骤后按目标顺序插入)
old_steps = (
db.query(BizProcessRouteStep)
.filter(
BizProcessRouteStep.route_id == route.id,
BizProcessRouteStep.tenant_no == tenant_no,
BizProcessRouteStep.del_flag == 0,
)
.all()
)
for s in old_steps:
s.del_flag = 1
s.update_by = user_id
s.update_time = now
db.add(s)
db.flush()
for order, code in enumerate(UC_MSC_STEP_ORDER, start=1):
src = by_code[code]
new_step = BizProcessRouteStep(
id=generate_uuid(),
route_id=route.id,
process_id=src.process_id,
step_order=order,
process_code=src.process_code,
category_id=src.category_id,
process_name=src.process_name,
description=src.description,
equipment_ids=src.equipment_ids,
equipment_name=src.equipment_name,
estimated_duration=src.estimated_duration,
sop_ids=src.sop_ids,
sop_content=src.sop_content,
tenant_no=tenant_no,
order_num=order,
remark=src.remark,
create_by=user_id,
create_dept_id=create_dept_id or "",
create_time=now,
update_by=user_id,
update_time=now,
del_flag=0,
)
db.add(new_step)
db.flush()
_clone_step_children(
db,
src_step_id=src.id,
dst_step_id=new_step.id,
tenant_no=tenant_no,
user_id=user_id,
create_dept_id=create_dept_id or "",
now=now,
)
header = existing or BizProductionTaskSet(
id=generate_uuid(),
set_name=UC_MSC_BUILTIN_SET_NAME,
status="1",
tenant_no=tenant_no,
order_num=0,
remark="内置模版:UC 入库编码自动派发",
is_builtin="1",
create_by=user_id,
create_dept_id=create_dept_id or "",
create_time=now,
update_by=user_id,
update_time=now,
del_flag=0,
)
if existing:
header.status = "1"
header.is_builtin = "1"
header.update_by = user_id
header.update_time = now
db.add(header)
db.flush()
items = (
db.query(BizProductionTaskSetItem)
.filter(
BizProductionTaskSetItem.set_id == header.id,
BizProductionTaskSetItem.tenant_no == tenant_no,
BizProductionTaskSetItem.del_flag == 0,
)
.all()
)
for it in items:
it.del_flag = 1
it.update_by = user_id
it.update_time = now
db.add(it)
db.flush()
item = BizProductionTaskSetItem(
id=generate_uuid(),
set_id=header.id,
task_name="{lab_storage_code}样本处理",
route_id=route.id,
route_name=route.route_name,
description=UC_MSC_BUILTIN_SET_NAME,
remark=None,
tenant_no=tenant_no,
order_num=1,
create_by=user_id,
create_dept_id=create_dept_id or "",
create_time=now,
update_by=user_id,
update_time=now,
del_flag=0,
)
db.add(item)
db.flush()
return {
"created": True,
"setId": header.id,
"setName": header.set_name,
"routeId": route.id,
"routeCode": route.route_code,
"stepCount": len(UC_MSC_STEP_ORDER),
}
+12 -4
View File
@@ -2,12 +2,20 @@
from typing import List, Optional, Tuple from typing import List, Optional, Tuple
# 科研捐赠脐带间充质:UC… → 5 步原代培养模版(与细胞存储 BC 的 6 步模版分离)
UC_MSC_BUILTIN_SET_NAME = "脐带MSC原代培养(内置模版)"
BC_MSC_BUILTIN_SET_NAME = "干细胞培养(内置模版)"
HSC_BUILTIN_SET_NAME = "造血干样本处理(内置模版)"
UBMC_BUILTIN_SET_NAME = "UBMC冻存(内置模版)"
PBMC_BUILTIN_SET_NAME = "PBMC冻存(内置模版)"
# 最长前缀优先:BC 必须在 B 之前,避免 BC… 误匹配造血干 # 最长前缀优先:BC 必须在 B 之前,避免 BC… 误匹配造血干
_LAB_CODE_BUILTIN_SET_RULES: List[Tuple[str, str]] = [ _LAB_CODE_BUILTIN_SET_RULES: List[Tuple[str, str]] = [
("UBMC", "UBMC冻存(内置模版)"), ("UBMC", UBMC_BUILTIN_SET_NAME),
("PBMC", "PBMC冻存(内置模版)"), ("PBMC", PBMC_BUILTIN_SET_NAME),
("BC", "干细胞培养(内置模版)"), ("UC", UC_MSC_BUILTIN_SET_NAME),
("B", "造血干样本处理(内置模版)"), ("BC", BC_MSC_BUILTIN_SET_NAME),
("B", HSC_BUILTIN_SET_NAME),
] ]
@@ -0,0 +1,252 @@
#!/usr/bin/env python3
"""为 UC 开头实验室入库编码的入库生产工单补派 5 步脐带MSC原代任务。
默认 dry-run;加 --apply 才写库。会先幂等确保内置模版存在。
用法(在 backend 目录、已配置可连目标库的 .env):
python -m scripts.backfill_uc_msc_production_tasks
python -m scripts.backfill_uc_msc_production_tasks --apply
python -m scripts.backfill_uc_msc_production_tasks --tenant zkxw --apply
等价一次性 SQL(与种子脚本分开):
docs/sql/migrations/2026-11-13-uc-msc-production-task-backfill.sql
"""
from __future__ import annotations
import argparse
import os
import sys
from typing import Any, Dict, List, Optional, Tuple
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from sqlalchemy import or_
from sqlalchemy.orm import Session
from app.core.database import SessionLocal
from app.crud import production_task_set as production_task_set_svc
from app.models.models import (
BizProductionTask,
BizProductionTaskSet,
BizProductionWorkOrder,
BizSampleReception,
)
from app.services.uc_msc_builtin_template import ensure_uc_msc_builtin_template
from app.utils.lab_storage_code_task_set import UC_MSC_BUILTIN_SET_NAME
def _list_candidate_work_orders(
db: Session, *, tenant_no: str
) -> List[Tuple[BizProductionWorkOrder, BizSampleReception]]:
"""UC 接收记录关联的入库工单,且当前无有效生产任务。"""
q = (
db.query(BizProductionWorkOrder, BizSampleReception)
.join(
BizSampleReception,
BizSampleReception.id == BizProductionWorkOrder.reception_id,
)
.filter(
BizProductionWorkOrder.tenant_no == tenant_no,
BizProductionWorkOrder.del_flag == 0,
BizProductionWorkOrder.work_order_type == "inbound",
BizProductionWorkOrder.work_order_status.in_(("dpz", "jxz")),
BizSampleReception.tenant_no == tenant_no,
BizSampleReception.del_flag == 0,
BizSampleReception.accept_conclusion == "js",
BizSampleReception.lab_storage_code.isnot(None),
BizSampleReception.lab_storage_code != "",
or_(
BizSampleReception.lab_storage_code.like("UC%"),
BizSampleReception.lab_storage_code.like("uc%"),
),
)
.order_by(BizSampleReception.reception_time.asc())
)
rows = q.all()
out: List[Tuple[BizProductionWorkOrder, BizSampleReception]] = []
for wo, rec in rows:
has_task = (
db.query(BizProductionTask.id)
.filter(
BizProductionTask.work_order_id == wo.id,
BizProductionTask.tenant_no == tenant_no,
BizProductionTask.del_flag == 0,
)
.first()
)
if has_task:
continue
code = (rec.lab_storage_code or "").strip().upper()
if not code.startswith("UC"):
continue
out.append((wo, rec))
return out
def _dispatch_one(
db: Session,
*,
tenant_no: str,
user_id: Optional[str],
create_dept_id: str,
wo: BizProductionWorkOrder,
rec: BizSampleReception,
set_id: str,
) -> Dict[str, Any]:
result = production_task_set_svc.create_tasks_from_set(
db,
tenant_no=tenant_no,
user_id=user_id,
create_dept_id=create_dept_id or "",
work_order_id=wo.id,
set_id=set_id,
)
return {
"workOrderId": wo.id,
"workOrderNo": wo.work_order_no,
"sampleCode": wo.sample_code or rec.sample_code,
"labStorageCode": rec.lab_storage_code,
"createdCount": result.get("createdCount"),
"tasks": [
{"id": t.get("id"), "taskName": t.get("taskName"), "routeId": t.get("routeId")}
for t in (result.get("list") or [])
],
}
def run(
*,
tenant_no: str,
apply: bool,
user_id: Optional[str],
create_dept_id: str,
) -> Dict[str, Any]:
db = SessionLocal()
try:
ensure_info = ensure_uc_msc_builtin_template(
db,
tenant_no=tenant_no,
user_id=user_id,
create_dept_id=create_dept_id,
)
set_row = (
db.query(BizProductionTaskSet)
.filter(
BizProductionTaskSet.tenant_no == tenant_no,
BizProductionTaskSet.set_name == UC_MSC_BUILTIN_SET_NAME,
BizProductionTaskSet.is_builtin == "1",
BizProductionTaskSet.status == "1",
BizProductionTaskSet.del_flag == 0,
)
.first()
)
if not set_row:
raise RuntimeError("UC 内置任务组合创建失败")
candidates = _list_candidate_work_orders(db, tenant_no=tenant_no)
preview = [
{
"workOrderId": wo.id,
"workOrderNo": wo.work_order_no,
"workOrderStatus": wo.work_order_status,
"sampleCode": wo.sample_code or rec.sample_code,
"labStorageCode": rec.lab_storage_code,
"receptionId": rec.id,
"receptionTime": str(rec.reception_time) if rec.reception_time else None,
}
for wo, rec in candidates
]
if not apply:
db.rollback()
return {
"dryRun": True,
"template": ensure_info,
"candidateCount": len(preview),
"candidates": preview,
"message": "dry-run:未写库。确认后加 --apply 执行补派。",
}
dispatched: List[Dict[str, Any]] = []
errors: List[Dict[str, Any]] = []
for wo, rec in candidates:
try:
dispatched.append(
_dispatch_one(
db,
tenant_no=tenant_no,
user_id=user_id,
create_dept_id=create_dept_id,
wo=wo,
rec=rec,
set_id=set_row.id,
)
)
except Exception as exc: # noqa: BLE001 - 汇总后继续
errors.append(
{
"workOrderId": wo.id,
"workOrderNo": wo.work_order_no,
"labStorageCode": rec.lab_storage_code,
"error": str(exc),
}
)
db.commit()
return {
"dryRun": False,
"template": ensure_info,
"candidateCount": len(preview),
"dispatchedCount": len(dispatched),
"dispatched": dispatched,
"errorCount": len(errors),
"errors": errors,
}
except Exception:
db.rollback()
raise
finally:
db.close()
def main(argv: Optional[List[str]] = None) -> int:
parser = argparse.ArgumentParser(
description="回补 UC 入库编码生产工单的 5 步脐带MSC原代任务"
)
parser.add_argument(
"--tenant",
default="zkxw",
help="租户编号,默认 zkxw",
)
parser.add_argument(
"--apply",
action="store_true",
help="实际写库;默认仅 dry-run",
)
parser.add_argument(
"--user-id",
default=None,
help="写库 create_by/update_by,可选",
)
parser.add_argument(
"--create-dept-id",
default="",
help="写库 create_dept_id,可选",
)
args = parser.parse_args(argv)
result = run(
tenant_no=(args.tenant or "zkxw").strip() or "zkxw",
apply=bool(args.apply),
user_id=(args.user_id or None),
create_dept_id=(args.create_dept_id or ""),
)
import json
print(json.dumps(result, ensure_ascii=False, indent=2, default=str))
if result.get("errorCount"):
return 2
return 0
if __name__ == "__main__":
raise SystemExit(main())
@@ -1,19 +1,36 @@
import unittest import unittest
from app.utils.lab_storage_code_task_set import match_builtin_task_set_name_by_lab_storage_code from app.utils.lab_storage_code_task_set import (
BC_MSC_BUILTIN_SET_NAME,
HSC_BUILTIN_SET_NAME,
UC_MSC_BUILTIN_SET_NAME,
match_builtin_task_set_name_by_lab_storage_code,
)
class TestMatchBuiltinTaskSetName(unittest.TestCase): class TestMatchBuiltinTaskSetName(unittest.TestCase):
def test_bc_before_b(self): def test_bc_before_b(self):
self.assertEqual( self.assertEqual(
match_builtin_task_set_name_by_lab_storage_code("BC20260101"), match_builtin_task_set_name_by_lab_storage_code("BC20260101"),
"干细胞培养(内置模版)", BC_MSC_BUILTIN_SET_NAME,
) )
def test_b_only(self): def test_b_only(self):
self.assertEqual( self.assertEqual(
match_builtin_task_set_name_by_lab_storage_code("B20260101"), match_builtin_task_set_name_by_lab_storage_code("B20260101"),
"造血干样本处理(内置模版)", HSC_BUILTIN_SET_NAME,
)
def test_uc_msc(self):
self.assertEqual(
match_builtin_task_set_name_by_lab_storage_code("UC2026010"),
UC_MSC_BUILTIN_SET_NAME,
)
def test_uc_case_insensitive(self):
self.assertEqual(
match_builtin_task_set_name_by_lab_storage_code("uc2026016"),
UC_MSC_BUILTIN_SET_NAME,
) )
def test_ubmc(self): def test_ubmc(self):
@@ -35,7 +52,7 @@ class TestMatchBuiltinTaskSetName(unittest.TestCase):
def test_bc_case_insensitive(self): def test_bc_case_insensitive(self):
self.assertEqual( self.assertEqual(
match_builtin_task_set_name_by_lab_storage_code("bc99"), match_builtin_task_set_name_by_lab_storage_code("bc99"),
"干细胞培养(内置模版)", BC_MSC_BUILTIN_SET_NAME,
) )
@@ -23,6 +23,7 @@ from app.models.research_donation import (
) )
from app.services.protocol_reception_discard_sync import ( from app.services.protocol_reception_discard_sync import (
LAB_VOID_TYPE_CODE, LAB_VOID_TYPE_CODE,
SAMPLE_VOID_STATUS,
after_protocol_voided, after_protocol_voided,
after_sample_reception_saved, after_sample_reception_saved,
ensure_lab_void_type, ensure_lab_void_type,
@@ -77,6 +78,7 @@ class TestProtocolReceptionDiscardSync(unittest.TestCase):
id="p1", id="p1",
protocol_no="CP-1", protocol_no="CP-1",
protocol_status="sxz", protocol_status="sxz",
void_time=now,
tenant_no="tenant-a", tenant_no="tenant-a",
create_dept_id="", create_dept_id="",
create_time=now, create_time=now,
@@ -89,6 +91,7 @@ class TestProtocolReceptionDiscardSync(unittest.TestCase):
id="s1", id="s1",
collection_protocol_id="p1", collection_protocol_id="p1",
sample_code="ZK001", sample_code="ZK001",
sample_status="yrk",
tenant_no="tenant-a", tenant_no="tenant-a",
create_dept_id="", create_dept_id="",
create_time=now, create_time=now,
@@ -101,6 +104,7 @@ class TestProtocolReceptionDiscardSync(unittest.TestCase):
id="s2", id="s2",
collection_protocol_id="p1", collection_protocol_id="p1",
sample_code="ZK002", sample_code="ZK002",
sample_status="jcz",
tenant_no="tenant-a", tenant_no="tenant-a",
create_dept_id="", create_dept_id="",
create_time=now, create_time=now,
@@ -152,6 +156,16 @@ class TestProtocolReceptionDiscardSync(unittest.TestCase):
self.assertEqual(by_code["ZK001"], "bj") self.assertEqual(by_code["ZK001"], "bj")
self.assertEqual(by_code["ZK002"], "bj") self.assertEqual(by_code["ZK002"], "bj")
samples = (
db.query(BizProtocolSample)
.filter(BizProtocolSample.collection_protocol_id == "p1")
.all()
)
self.assertEqual(len(samples), 2)
for s in samples:
self.assertEqual(s.sample_status, SAMPLE_VOID_STATUS)
self.assertEqual(s.void_date, "20261105")
def test_all_samples_discarded_auto_voids_protocol_with_lab_type(self): def test_all_samples_discarded_auto_voids_protocol_with_lab_type(self):
db = _session() db = _session()
now = _now() now = _now()
@@ -172,6 +186,7 @@ class TestProtocolReceptionDiscardSync(unittest.TestCase):
id="s3", id="s3",
collection_protocol_id="p2", collection_protocol_id="p2",
sample_code="ZK003", sample_code="ZK003",
sample_status="ycj",
tenant_no="tenant-a", tenant_no="tenant-a",
create_dept_id="", create_dept_id="",
create_time=now, create_time=now,
@@ -212,6 +227,9 @@ class TestProtocolReceptionDiscardSync(unittest.TestCase):
self.assertEqual(proto.protocol_status, "yzf") self.assertEqual(proto.protocol_status, "yzf")
self.assertEqual(proto.void_type, LAB_VOID_TYPE_CODE) self.assertEqual(proto.void_type, LAB_VOID_TYPE_CODE)
self.assertIn("全部样本接收", proto.void_desc or "") self.assertIn("全部样本接收", proto.void_desc or "")
sample = db.query(BizProtocolSample).filter(BizProtocolSample.id == "s3").one()
self.assertEqual(sample.sample_status, SAMPLE_VOID_STATUS)
self.assertTrue((sample.void_date or "").strip())
def test_partial_discard_does_not_void_protocol(self): def test_partial_discard_does_not_void_protocol(self):
db = _session() db = _session()
@@ -282,6 +300,7 @@ class TestProtocolReceptionDiscardSync(unittest.TestCase):
id="d1", id="d1",
donation_no="RD-1", donation_no="RD-1",
donation_status="sxz", donation_status="sxz",
void_time=now,
tenant_no="tenant-a", tenant_no="tenant-a",
create_dept_id="", create_dept_id="",
create_time=now, create_time=now,
@@ -294,6 +313,7 @@ class TestProtocolReceptionDiscardSync(unittest.TestCase):
id="ds1", id="ds1",
research_donation_id="d1", research_donation_id="d1",
sample_code="RD001", sample_code="RD001",
sample_status="yrk",
tenant_no="tenant-a", tenant_no="tenant-a",
create_dept_id="", create_dept_id="",
create_time=now, create_time=now,
@@ -322,6 +342,62 @@ class TestProtocolReceptionDiscardSync(unittest.TestCase):
) )
self.assertEqual(rec.accept_conclusion, "bj") self.assertEqual(rec.accept_conclusion, "bj")
self.assertEqual(rec.research_donation_id, "d1") self.assertEqual(rec.research_donation_id, "d1")
sample = (
db.query(BizResearchDonationSample)
.filter(BizResearchDonationSample.id == "ds1")
.one()
)
self.assertEqual(sample.sample_status, SAMPLE_VOID_STATUS)
self.assertEqual(sample.void_date, "20261105")
def test_sdfq_also_voids_sample_status(self):
db = _session()
now = _now()
db.add(
BizCollectionProtocol(
id="p-sdfq",
protocol_no="CP-SDFQ",
protocol_status="sdfq",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
db.add(
BizProtocolSample(
id="s-sdfq",
collection_protocol_id="p-sdfq",
sample_code="ZKSDFQ",
sample_status="ycj",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
db.commit()
after_protocol_voided(
db,
source="cell_storage",
protocol_id="p-sdfq",
tenant_no="tenant-a",
user_id="u1",
)
db.commit()
sample = db.query(BizProtocolSample).filter(BizProtocolSample.id == "s-sdfq").one()
self.assertEqual(sample.sample_status, SAMPLE_VOID_STATUS)
self.assertTrue((sample.void_date or "").strip())
rec = (
db.query(BizSampleReception)
.filter(BizSampleReception.sample_code == "ZKSDFQ")
.one()
)
self.assertEqual(rec.accept_conclusion, "bj")
if __name__ == "__main__": if __name__ == "__main__":
@@ -0,0 +1,174 @@
"""入库质检工单列表:从协议/捐赠采集信息补齐母血采集时间。"""
import unittest
from datetime import datetime
from unittest import mock
import app.crud.qc_task # noqa: F401 先加载任务模块,避免与工单模块循环导入
from app.crud import qc_work_order as qc_wo
from app.crud.qc_work_order import _enrich_work_order_list_items
from app.models.models import (
BizCollectionProtocol,
BizProtocolCollectionInfo,
BizProtocolPartyCustomer,
BizSampleReception,
)
from app.models.research_donation import (
BizResearchDonation,
BizResearchDonationCollection,
BizResearchDonationParty,
)
def _item(**kwargs):
data = {
"id": "wo-1",
"workOrderType": "inbound",
"receptionId": "rec-1",
"sampleCode": "S001",
"collectionProtocolId": "proto-1",
"receptionSource": "cell_storage",
"protocolSampleId": "",
"maternalBloodCollectTime": "",
}
data.update(kwargs)
return data
def _query_router(mapping):
def _query(*entities):
q = mock.Mock()
q.filter.return_value = q
q.order_by.return_value = q
model = entities[0]
# db.query(Model.col, ...) → first entity is InstrumentedAttribute
cls = getattr(model, "class_", model)
key = getattr(cls, "__name__", str(cls))
rows = mapping.get(key, [])
q.all.return_value = rows
return q
return _query
class TestEnrichWorkOrderMaternalBlood(unittest.TestCase):
def test_cell_storage_fills_maternal_blood_collect_time(self):
rec = mock.Mock(
id="rec-1",
sample_code="S001",
reception_source="cell_storage",
collection_protocol_id="proto-1",
research_donation_id="",
protocol_sample_id="",
donation_sample_id="",
reception_time=datetime(2026, 11, 8, 13, 30, 41),
handler_name="质检员",
lab_storage_code="",
)
coll = mock.Mock(
collection_protocol_id="proto-1",
maternal_blood_collect_time=datetime(2026, 11, 7, 9, 15, 0),
del_flag=0,
)
db = mock.Mock()
db.query.side_effect = _query_router(
{
BizSampleReception.__name__: [rec],
BizProtocolCollectionInfo.__name__: [coll],
BizProtocolPartyCustomer.__name__: [],
BizCollectionProtocol.__name__: [],
}
)
with mock.patch.object(
qc_wo, "_enrich_protocol_sibling_samples", side_effect=lambda _db, items: items
), mock.patch.object(
qc_wo, "apply_special_to_item_from_samples", side_effect=lambda item, **_k: item
):
items = _enrich_work_order_list_items(db, [_item()])
self.assertEqual(items[0]["maternalBloodCollectTime"], "2026-11-07 09:15:00")
def test_missing_maternal_blood_stays_empty(self):
rec = mock.Mock(
id="rec-1",
sample_code="S001",
reception_source="cell_storage",
collection_protocol_id="proto-1",
research_donation_id="",
protocol_sample_id="",
donation_sample_id="",
reception_time=datetime(2026, 11, 8, 13, 30, 41),
handler_name="质检员",
lab_storage_code="",
)
db = mock.Mock()
db.query.side_effect = _query_router(
{
BizSampleReception.__name__: [rec],
BizProtocolCollectionInfo.__name__: [],
BizProtocolPartyCustomer.__name__: [],
BizCollectionProtocol.__name__: [],
}
)
with mock.patch.object(
qc_wo, "_enrich_protocol_sibling_samples", side_effect=lambda _db, items: items
), mock.patch.object(
qc_wo, "apply_special_to_item_from_samples", side_effect=lambda item, **_k: item
):
items = _enrich_work_order_list_items(db, [_item()])
self.assertEqual(items[0]["maternalBloodCollectTime"], "")
def test_research_donation_fills_maternal_blood_collect_time(self):
rec = mock.Mock(
id="rec-2",
sample_code="D001",
reception_source="research_donation",
collection_protocol_id="",
research_donation_id="don-1",
protocol_sample_id="",
donation_sample_id="",
reception_time=datetime(2026, 11, 8, 10, 0, 0),
handler_name="质检员",
lab_storage_code="",
)
coll = mock.Mock(
research_donation_id="don-1",
maternal_blood_collect_time=datetime(2026, 11, 6, 8, 0, 0),
del_flag=0,
)
db = mock.Mock()
db.query.side_effect = _query_router(
{
BizSampleReception.__name__: [rec],
BizResearchDonationCollection.__name__: [coll],
BizResearchDonationParty.__name__: [],
BizResearchDonation.__name__: [],
}
)
with mock.patch.object(
qc_wo, "_enrich_protocol_sibling_samples", side_effect=lambda _db, items: items
), mock.patch.object(
qc_wo, "apply_special_to_item_from_samples", side_effect=lambda item, **_k: item
):
items = _enrich_work_order_list_items(
db,
[
_item(
id="wo-2",
receptionId="rec-2",
sampleCode="D001",
collectionProtocolId="don-1",
receptionSource="research_donation",
)
],
)
self.assertEqual(items[0]["maternalBloodCollectTime"], "2026-11-06 08:00:00")
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,41 @@
import os
import unittest
# 避免导入 app.models 时 Settings 因缺 SECRET_KEY 失败
os.environ.setdefault(
"SECRET_KEY", "test-secret-key-for-uc-msc-unit-tests-32c"
)
class TestUcMscBuiltinTemplate(unittest.TestCase):
def test_step_order_matches_business_five_nodes(self):
from app.services.uc_msc_builtin_template import UC_MSC_STEP_ORDER
self.assertEqual(
UC_MSC_STEP_ORDER,
[
"SOP-SC-003-E01-01",
"SOP-SC-004-E01-01",
"SOP-SC-006-E01-01",
"SOP-SC-005-E01-01",
"SOP-SC-008-E01-01",
],
)
self.assertNotIn("SOP-SC-007-E01-01", UC_MSC_STEP_ORDER)
def test_uc_prefix_maps_to_uc_set_name(self):
from app.services.uc_msc_builtin_template import UC_MSC_ROUTE_CODE
from app.utils.lab_storage_code_task_set import (
UC_MSC_BUILTIN_SET_NAME,
match_builtin_task_set_name_by_lab_storage_code,
)
self.assertEqual(UC_MSC_ROUTE_CODE, "MSC原代-UC-BUILTIN")
self.assertEqual(
match_builtin_task_set_name_by_lab_storage_code("UC2026010"),
UC_MSC_BUILTIN_SET_NAME,
)
if __name__ == "__main__":
unittest.main()
@@ -1,46 +0,0 @@
-- =============================================================================
-- 弱密码刷新说明:111111 → Zkxw@123
-- 日期:2026-10-16
-- =============================================================================
--
-- 重要:sys_user.password 存储 bcrypt 哈希(每次盐随机),
-- 不能用下列语句命中弱密码用户:
-- WHERE password = '111111' -- 无效
-- WHERE password LIKE '%111111%' -- 无效
--
-- 推荐:用 Python 脚本,并通过变量指定目标库(勿依赖本机默认 .env 误连生产)。
--
-- cd backend && source venv/bin/activate
--
-- # 方式 A:完整 URL
-- python scripts/reset_weak_password_111111.py \
-- --database-url 'mysql+pymysql://USER:PASS@HOST:3306/DBNAME' --dry-run
--
-- # 方式 B:分项变量
-- python scripts/reset_weak_password_111111.py \
-- --db-host HOST --db-port 3306 --db-user USER --db-password 'PASS' --db-name DBNAME --dry-run
--
-- # 方式 C:指定环境文件
-- python scripts/reset_weak_password_111111.py --env-file ./.env.test --dry-run
--
-- # 正式写入:去掉 --dry-run
--
-- 脚本行为:校验 del_flag=0 的用户口令是否为明文 111111(含停用账号),
-- 命中则更新为 Zkxw@123 的新 bcrypt 哈希。
--
-- =============================================================================
-- 以下仅为「已知单个用户 id」时的手工 UPDATE 模板。
-- 哈希由本机生成示例(明文 Zkxw@123,bcrypt cost 12),部署前请用 Python 重新生成:
-- python -c "from app.core.security import get_password_hash; print(get_password_hash('Zkxw@123'))"
-- =============================================================================
-- 示例哈希(仅供手工单用户更新参考;批量请用脚本):
-- $2b$12$ULvPCr6g9IUmI8K7nlGU5emk7hupaAz4WgFdEoQBe935Wh1pVYKCK
-- UPDATE sys_user
-- SET password = '$2b$12$ULvPCr6g9IUmI8K7nlGU5emk7hupaAz4WgFdEoQBe935Wh1pVYKCK',
-- update_time = NOW()
-- WHERE id = '<user_id>'
-- AND del_flag = 0;
-- 执行前请备份 sys_user;执行后通知用户使用新密码并建议登录后自行修改。
@@ -1,21 +0,0 @@
-- 实验室样本处理 ACL 归一化(可重复执行)
-- 1) 撤销所有 lab:sample-processing* / menu:lab-sample-processing 角色菜单
-- 2) 仅按下列角色重授:
-- 市场编辑:市场专员/临床销售/销售助理/客服/采集专员
-- 生产编辑:生产专员/实验专员/细胞实验员/研发专员
-- 质检编辑:质检专员/质量安全员
-- 主管:生产主管/质量主管/采集主管/采集经理/研发主管/研发总监/总经理/副总经理/董事长/超级管理员
-- 只读:采集接受人
-- 说明:正式执行请用 Agent 脚本 tmp_normalize_lab_acl.py(含幂等 undelete/insert)。
-- 本文件作为规则记录;勿在未核对角色名时直接全量套用到其他环境。
UPDATE sys_role_menu rm
JOIN sys_menu m ON m.id = rm.menu_id
SET rm.del_flag = 1,
rm.update_by = 'normalize-acl',
rm.update_time = NOW()
WHERE rm.del_flag = 0
AND (
m.perms LIKE 'lab:sample-processing%'
OR m.perms = 'menu:lab-sample-processing'
);
@@ -1,23 +0,0 @@
# 恢复 Excel 补充字段(真菌等)
## 原因
`20261112_lab_sample_processing_retire_excel_demo.sql` 按「补充表 sample_code = 协议样本号」软删演示行。
会议 Excel 实际多用实验室入库编码(`B000*` / `BC*` / `UBMC*`),与协议号不一致,导致真实样本的真菌/内毒素/CD34 等补充字段被误删。
## 处理
运行:
```bash
ENV_FILE=backend/.env python backend/scripts/restore_lab_sample_processing_excel_extras.py
```
脚本会:
1. 找出 `update_by=retire-excel-demo` 且 `del_flag=1` 的补充行
2. 仅恢复仍能关联到当前有效协议/接收编码的行
3. 只写回 `SOURCE_EXTRA` 字段到有效补充表
4. 同步旧台账 `biz_lab_sample_process_supplement`
列表侧同时会从质检完成任务填空(内毒素/真菌/支原体/细菌及母血相关)。
@@ -1,14 +0,0 @@
-- 软删除实验室样本处理 Excel 演示补充行:
-- 仅删除在协议样本表中不存在对应 sample_code 的补充记录。
-- Excel 列结构仍由代码字段目录维护;真实列表只聚合协议/接收/生产源数据。
UPDATE biz_lab_sample_processing_extra e
LEFT JOIN biz_protocol_sample s
ON s.sample_code = e.sample_code
AND s.tenant_no = e.tenant_no
AND s.del_flag = 0
SET e.del_flag = 1,
e.update_by = 'retire-excel-demo',
e.update_time = NOW()
WHERE e.del_flag = 0
AND s.id IS NULL;
@@ -1,12 +0,0 @@
-- 纠正实验室样本处理部门 ACL:
-- 「采集接受人」仅挂在「质检专员」职位上,不应再授予市场字段编辑权,
-- 否则质检人员经职位角色并集会同时可改市场+质检字段。
UPDATE sys_role_menu rm
JOIN sys_role r ON r.id = rm.role_id AND r.del_flag = 0 AND r.role_name = '采集接受人'
JOIN sys_menu m ON m.id = rm.menu_id AND m.del_flag = 0
AND m.perms = 'lab:sample-processing:market:edit'
SET rm.del_flag = 1,
rm.update_by = 'migration',
rm.update_time = NOW()
WHERE rm.del_flag = 0;
@@ -1,120 +0,0 @@
-- 实验室样本处理数据:补充表 + 一级模块菜单/按钮权限(不自动授权角色)
-- MySQL 5.7,可重复执行
CREATE TABLE IF NOT EXISTS biz_lab_sample_processing_extra (
id VARCHAR(64) NOT NULL,
dataset VARCHAR(16) NOT NULL COMMENT 'hsc|ubmc|msc',
sample_code VARCHAR(32) NOT NULL COMMENT '样本编码',
payload_json TEXT NULL COMMENT '补充字段 JSON',
tenant_no VARCHAR(64) NOT NULL,
order_num INT NULL,
remark VARCHAR(512) NULL,
create_by VARCHAR(64) NULL,
create_dept_id VARCHAR(64) NOT NULL DEFAULT '',
create_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
update_by VARCHAR(64) NULL,
update_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
del_flag SMALLINT NOT NULL DEFAULT 0,
PRIMARY KEY (id),
KEY ix_lab_sample_extra_tenant_ds_code (tenant_no, dataset, sample_code, del_flag)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- 挂到与「质检」同一 Web 虚拟根下(复用 menu:quality 的 parent_id)
INSERT INTO sys_menu (
id, menu_name, parent_id, menu_type, path, component, perms,
is_frame, visible, status, tenant_no, order_num, remark,
create_by, create_dept_id, create_time, update_by, update_time, del_flag
)
SELECT
MD5(CONCAT(quality.tenant_no, ':menu:lab-sample-processing')),
'实验室样本处理数据', quality.parent_id, 'M', '/lab-sample-processing', '/index/index',
'menu:lab-sample-processing', 1, '1', '1', quality.tenant_no,
COALESCE(quality.order_num, 50) + 1,
'20261104 会议:造血/单个核/间充质台账',
'migration', '', NOW(), 'migration', NOW(), 0
FROM sys_menu quality
WHERE quality.perms = 'menu:quality' AND quality.del_flag = 0 AND quality.status = '1'
AND NOT EXISTS (
SELECT 1 FROM sys_menu e
WHERE e.tenant_no = quality.tenant_no AND e.perms = 'menu:lab-sample-processing' AND e.del_flag = 0
);
INSERT INTO sys_menu (
id, menu_name, parent_id, menu_type, path, component, perms,
is_frame, visible, status, tenant_no, order_num, remark,
create_by, create_dept_id, create_time, update_by, update_time, del_flag
)
SELECT
MD5(CONCAT(p.tenant_no, ':lab:sample-processing:list')),
'造血干细胞数据', p.id, 'C', 'lab-sample-processing/hsc',
'/lab-sample-processing/hsc/index', 'lab:sample-processing:list',
1, '1', '1', p.tenant_no, 10, '造血干细胞数据列表',
'migration', '', NOW(), 'migration', NOW(), 0
FROM sys_menu p
WHERE p.perms = 'menu:lab-sample-processing' AND p.del_flag = 0 AND p.status = '1'
AND NOT EXISTS (
SELECT 1 FROM sys_menu e
WHERE e.tenant_no = p.tenant_no AND e.path = 'lab-sample-processing/hsc' AND e.del_flag = 0
);
INSERT INTO sys_menu (
id, menu_name, parent_id, menu_type, path, component, perms,
is_frame, visible, status, tenant_no, order_num, remark,
create_by, create_dept_id, create_time, update_by, update_time, del_flag
)
SELECT
MD5(CONCAT(p.tenant_no, ':lab:sample-processing:ubmc')),
'单个核数据', p.id, 'C', 'lab-sample-processing/ubmc',
'/lab-sample-processing/ubmc/index', 'lab:sample-processing:list',
1, '1', '1', p.tenant_no, 20, '单个核数据列表',
'migration', '', NOW(), 'migration', NOW(), 0
FROM sys_menu p
WHERE p.perms = 'menu:lab-sample-processing' AND p.del_flag = 0 AND p.status = '1'
AND NOT EXISTS (
SELECT 1 FROM sys_menu e
WHERE e.tenant_no = p.tenant_no AND e.path = 'lab-sample-processing/ubmc' AND e.del_flag = 0
);
INSERT INTO sys_menu (
id, menu_name, parent_id, menu_type, path, component, perms,
is_frame, visible, status, tenant_no, order_num, remark,
create_by, create_dept_id, create_time, update_by, update_time, del_flag
)
SELECT
MD5(CONCAT(p.tenant_no, ':lab:sample-processing:msc')),
'脐带间充质干细胞数据', p.id, 'C', 'lab-sample-processing/msc',
'/lab-sample-processing/msc/index', 'lab:sample-processing:list',
1, '1', '1', p.tenant_no, 30, '脐带间充质干细胞数据列表',
'migration', '', NOW(), 'migration', NOW(), 0
FROM sys_menu p
WHERE p.perms = 'menu:lab-sample-processing' AND p.del_flag = 0 AND p.status = '1'
AND NOT EXISTS (
SELECT 1 FROM sys_menu e
WHERE e.tenant_no = p.tenant_no AND e.path = 'lab-sample-processing/msc' AND e.del_flag = 0
);
-- 编辑按钮挂在列表菜单下(三页共用同一 list 权限父节点:造血页)
INSERT INTO sys_menu (
id, menu_name, parent_id, menu_type, path, component, perms,
is_frame, visible, status, tenant_no, order_num, remark,
create_by, create_dept_id, create_time, update_by, update_time, del_flag
)
SELECT
MD5(CONCAT(p.tenant_no, ':', btn.perms)),
btn.menu_name, p.id, 'F', '', NULL, btn.perms,
1, '0', '1', p.tenant_no, btn.order_num, btn.remark,
'migration', '', NOW(), 'migration', NOW(), 0
FROM sys_menu p
JOIN (
SELECT '市场字段编辑' AS menu_name, 'lab:sample-processing:market:edit' AS perms, 1 AS order_num, '仅可编辑市场部门字段' AS remark
UNION ALL SELECT '生产字段编辑', 'lab:sample-processing:production:edit', 2, '仅可编辑生产部门字段'
UNION ALL SELECT '质检字段编辑', 'lab:sample-processing:qc:edit', 3, '仅可编辑质检部门字段'
UNION ALL SELECT '部门主管', 'lab:sample-processing:manager', 4, '可编辑全部部门字段'
) btn
WHERE p.perms = 'lab:sample-processing:list'
AND p.path = 'lab-sample-processing/hsc'
AND p.del_flag = 0 AND p.status = '1'
AND NOT EXISTS (
SELECT 1 FROM sys_menu e
WHERE e.tenant_no = p.tenant_no AND e.perms = btn.perms AND e.del_flag = 0
);
@@ -1,50 +0,0 @@
-- Issue #100:移除多余一级菜单「实验室样本处理数据」及其子菜单/按钮
-- 软删除 sys_menu 与对应 sys_role_menu;不影响质检管理下 lab-sample-process 台账
-- MySQL 5.7,可重复执行
-- 1) 角色菜单授权
UPDATE sys_role_menu rm
JOIN sys_menu m ON m.id = rm.menu_id
SET rm.del_flag = 1,
rm.update_by = 'migration',
rm.update_time = NOW()
WHERE rm.del_flag = 0
AND (
m.perms IN (
'menu:lab-sample-processing',
'lab:sample-processing:list',
'lab:sample-processing:market:edit',
'lab:sample-processing:production:edit',
'lab:sample-processing:qc:edit',
'lab:sample-processing:manager'
)
OR m.path IN (
'/lab-sample-processing',
'lab-sample-processing/hsc',
'lab-sample-processing/ubmc',
'lab-sample-processing/msc'
)
);
-- 2) 按钮 / 子菜单 / 一级菜单(先叶子后父级,同批软删即可)
UPDATE sys_menu
SET del_flag = 1,
update_by = 'migration',
update_time = NOW()
WHERE del_flag = 0
AND (
perms IN (
'menu:lab-sample-processing',
'lab:sample-processing:list',
'lab:sample-processing:market:edit',
'lab:sample-processing:production:edit',
'lab:sample-processing:qc:edit',
'lab:sample-processing:manager'
)
OR path IN (
'/lab-sample-processing',
'lab-sample-processing/hsc',
'lab-sample-processing/ubmc',
'lab-sample-processing/msc'
)
);
@@ -0,0 +1,277 @@
-- UC 入库编码自动派发:脐带MSC原代培养(内置模版)5 步
-- 步骤:原代培养 → 半换液 → 二次贴壁 → 重铺 → 冻存(不含传代)
-- 内容从既有「干细胞培养(内置模版)」/ MSC培养-BUILTIN 按 process_code 拷贝
-- 幂等:已存在同名内置集合则跳过主数据创建-- 兼容:跨表比较统一 COLLATE utf8mb4_unicode_ci,避免 unicode_ci/general_ci 混用失败
-- 生产历史空任务工单回补(二选一,勿重复对同一工单各跑一遍):
-- SQL:docs/sql/migrations/2026-11-13-uc-msc-production-task-backfill.sql
-- 或 Python:
-- cd backend && python -m scripts.backfill_uc_msc_production_tasks
-- cd backend && python -m scripts.backfill_uc_msc_production_tasks --apply
SET NAMES utf8mb4;
-- 1) 工艺路线头
INSERT INTO biz_process_route (
id, route_code, route_name, product_type_id, version, is_current,
equipment_ids, equipment_name, tenant_no, order_num, remark, is_builtin,
create_by, create_dept_id, create_time, update_by, update_time, del_flag
)
SELECT
'UCMSCROUTEA5CC11F194118AC54085447A',
'MSC原代-UC-BUILTIN',
'脐带MSC原代培养(内置模版)',
src.product_type_id,
src.version,
'0',
src.equipment_ids,
src.equipment_name,
src.tenant_no,
0,
'内置模版:UC 入库编码自动派发(5 步,不含传代)',
'1',
src.create_by,
IFNULL(src.create_dept_id, ''),
NOW(),
src.update_by,
NOW(),
0
FROM biz_process_route src
WHERE src.del_flag = 0
AND (
src.route_code = 'MSC培养-BUILTIN'
OR (src.route_name = '干细胞培养(内置模版)' AND src.is_builtin = '1')
)
AND NOT EXISTS (
SELECT 1 FROM biz_process_route x
WHERE x.id = 'UCMSCROUTEA5CC11F194118AC54085447A' AND x.del_flag = 0
)
AND NOT EXISTS (
SELECT 1 FROM biz_process_route x
WHERE x.tenant_no COLLATE utf8mb4_unicode_ci = src.tenant_no COLLATE utf8mb4_unicode_ci
AND x.route_code = 'MSC原代-UC-BUILTIN'
AND x.del_flag = 0
)
ORDER BY CASE WHEN src.route_code = 'MSC培养-BUILTIN' THEN 0 ELSE 1 END
LIMIT 1;
-- 2) 路线步骤(按目标顺序)
-- step 1 SOP-SC-003
INSERT INTO biz_process_route_step (
id, route_id, process_id, step_order, process_code, category_id, process_name,
description, equipment_ids, equipment_name, estimated_duration, sop_ids, sop_content,
tenant_no, order_num, remark, create_by, create_dept_id, create_time, update_by, update_time, del_flag
)
SELECT
'UCMSCSTEP1A5CC11F194118AC54085447A',
'UCMSCROUTEA5CC11F194118AC54085447A',
s.process_id, 1, s.process_code, s.category_id, s.process_name,
s.description, s.equipment_ids, s.equipment_name, s.estimated_duration, s.sop_ids, s.sop_content,
s.tenant_no, 1, s.remark, s.create_by, IFNULL(s.create_dept_id, ''), NOW(), s.update_by, NOW(), 0
FROM biz_process_route_step s
JOIN biz_process_route r
ON r.id COLLATE utf8mb4_unicode_ci = s.route_id COLLATE utf8mb4_unicode_ci
AND r.del_flag = 0
WHERE s.del_flag = 0
AND s.process_code = 'SOP-SC-003-E01-01'
AND (
r.route_code = 'MSC培养-BUILTIN'
OR (r.route_name = '干细胞培养(内置模版)' AND r.is_builtin = '1')
)
AND EXISTS (
SELECT 1 FROM biz_process_route nr
WHERE nr.id = 'UCMSCROUTEA5CC11F194118AC54085447A' AND nr.del_flag = 0
)
AND NOT EXISTS (
SELECT 1 FROM biz_process_route_step x
WHERE x.id = 'UCMSCSTEP1A5CC11F194118AC54085447A' AND x.del_flag = 0
)
LIMIT 1;
-- step 2 SOP-SC-004
INSERT INTO biz_process_route_step (
id, route_id, process_id, step_order, process_code, category_id, process_name,
description, equipment_ids, equipment_name, estimated_duration, sop_ids, sop_content,
tenant_no, order_num, remark, create_by, create_dept_id, create_time, update_by, update_time, del_flag
)
SELECT
'UCMSCSTEP2A5CC11F194118AC54085447A',
'UCMSCROUTEA5CC11F194118AC54085447A',
s.process_id, 2, s.process_code, s.category_id, s.process_name,
s.description, s.equipment_ids, s.equipment_name, s.estimated_duration, s.sop_ids, s.sop_content,
s.tenant_no, 2, s.remark, s.create_by, IFNULL(s.create_dept_id, ''), NOW(), s.update_by, NOW(), 0
FROM biz_process_route_step s
JOIN biz_process_route r
ON r.id COLLATE utf8mb4_unicode_ci = s.route_id COLLATE utf8mb4_unicode_ci
AND r.del_flag = 0
WHERE s.del_flag = 0
AND s.process_code = 'SOP-SC-004-E01-01'
AND (
r.route_code = 'MSC培养-BUILTIN'
OR (r.route_name = '干细胞培养(内置模版)' AND r.is_builtin = '1')
)
AND EXISTS (
SELECT 1 FROM biz_process_route nr
WHERE nr.id = 'UCMSCROUTEA5CC11F194118AC54085447A' AND nr.del_flag = 0
)
AND NOT EXISTS (
SELECT 1 FROM biz_process_route_step x
WHERE x.id = 'UCMSCSTEP2A5CC11F194118AC54085447A' AND x.del_flag = 0
)
LIMIT 1;
-- step 3 SOP-SC-006 二次贴壁
INSERT INTO biz_process_route_step (
id, route_id, process_id, step_order, process_code, category_id, process_name,
description, equipment_ids, equipment_name, estimated_duration, sop_ids, sop_content,
tenant_no, order_num, remark, create_by, create_dept_id, create_time, update_by, update_time, del_flag
)
SELECT
'UCMSCSTEP3A5CC11F194118AC54085447A',
'UCMSCROUTEA5CC11F194118AC54085447A',
s.process_id, 3, s.process_code, s.category_id, s.process_name,
s.description, s.equipment_ids, s.equipment_name, s.estimated_duration, s.sop_ids, s.sop_content,
s.tenant_no, 3, s.remark, s.create_by, IFNULL(s.create_dept_id, ''), NOW(), s.update_by, NOW(), 0
FROM biz_process_route_step s
JOIN biz_process_route r
ON r.id COLLATE utf8mb4_unicode_ci = s.route_id COLLATE utf8mb4_unicode_ci
AND r.del_flag = 0
WHERE s.del_flag = 0
AND s.process_code = 'SOP-SC-006-E01-01'
AND (
r.route_code = 'MSC培养-BUILTIN'
OR (r.route_name = '干细胞培养(内置模版)' AND r.is_builtin = '1')
)
AND EXISTS (
SELECT 1 FROM biz_process_route nr
WHERE nr.id = 'UCMSCROUTEA5CC11F194118AC54085447A' AND nr.del_flag = 0
)
AND NOT EXISTS (
SELECT 1 FROM biz_process_route_step x
WHERE x.id = 'UCMSCSTEP3A5CC11F194118AC54085447A' AND x.del_flag = 0
)
LIMIT 1;
-- step 4 SOP-SC-005 重铺
INSERT INTO biz_process_route_step (
id, route_id, process_id, step_order, process_code, category_id, process_name,
description, equipment_ids, equipment_name, estimated_duration, sop_ids, sop_content,
tenant_no, order_num, remark, create_by, create_dept_id, create_time, update_by, update_time, del_flag
)
SELECT
'UCMSCSTEP4A5CC11F194118AC54085447A',
'UCMSCROUTEA5CC11F194118AC54085447A',
s.process_id, 4, s.process_code, s.category_id, s.process_name,
s.description, s.equipment_ids, s.equipment_name, s.estimated_duration, s.sop_ids, s.sop_content,
s.tenant_no, 4, s.remark, s.create_by, IFNULL(s.create_dept_id, ''), NOW(), s.update_by, NOW(), 0
FROM biz_process_route_step s
JOIN biz_process_route r
ON r.id COLLATE utf8mb4_unicode_ci = s.route_id COLLATE utf8mb4_unicode_ci
AND r.del_flag = 0
WHERE s.del_flag = 0
AND s.process_code = 'SOP-SC-005-E01-01'
AND (
r.route_code = 'MSC培养-BUILTIN'
OR (r.route_name = '干细胞培养(内置模版)' AND r.is_builtin = '1')
)
AND EXISTS (
SELECT 1 FROM biz_process_route nr
WHERE nr.id = 'UCMSCROUTEA5CC11F194118AC54085447A' AND nr.del_flag = 0
)
AND NOT EXISTS (
SELECT 1 FROM biz_process_route_step x
WHERE x.id = 'UCMSCSTEP4A5CC11F194118AC54085447A' AND x.del_flag = 0
)
LIMIT 1;
-- step 5 SOP-SC-008 冻存
INSERT INTO biz_process_route_step (
id, route_id, process_id, step_order, process_code, category_id, process_name,
description, equipment_ids, equipment_name, estimated_duration, sop_ids, sop_content,
tenant_no, order_num, remark, create_by, create_dept_id, create_time, update_by, update_time, del_flag
)
SELECT
'UCMSCSTEP5A5CC11F194118AC54085447A',
'UCMSCROUTEA5CC11F194118AC54085447A',
s.process_id, 5, s.process_code, s.category_id, s.process_name,
s.description, s.equipment_ids, s.equipment_name, s.estimated_duration, s.sop_ids, s.sop_content,
s.tenant_no, 5, s.remark, s.create_by, IFNULL(s.create_dept_id, ''), NOW(), s.update_by, NOW(), 0
FROM biz_process_route_step s
JOIN biz_process_route r
ON r.id COLLATE utf8mb4_unicode_ci = s.route_id COLLATE utf8mb4_unicode_ci
AND r.del_flag = 0
WHERE s.del_flag = 0
AND s.process_code = 'SOP-SC-008-E01-01'
AND (
r.route_code = 'MSC培养-BUILTIN'
OR (r.route_name = '干细胞培养(内置模版)' AND r.is_builtin = '1')
)
AND EXISTS (
SELECT 1 FROM biz_process_route nr
WHERE nr.id = 'UCMSCROUTEA5CC11F194118AC54085447A' AND nr.del_flag = 0
)
AND NOT EXISTS (
SELECT 1 FROM biz_process_route_step x
WHERE x.id = 'UCMSCSTEP5A5CC11F194118AC54085447A' AND x.del_flag = 0
)
LIMIT 1;
-- 3) 任务组合头
INSERT INTO biz_production_task_set (
id, set_name, status, tenant_no, order_num, remark, is_builtin,
create_by, create_dept_id, create_time, update_by, update_time, del_flag
)
SELECT
'UCMSCSET00A5CC11F194118AC54085447A',
'脐带MSC原代培养(内置模版)',
'1',
r.tenant_no,
0,
'内置模版:UC 入库编码自动派发',
'1',
r.create_by,
IFNULL(r.create_dept_id, ''),
NOW(),
r.update_by,
NOW(),
0
FROM biz_process_route r
WHERE r.id = 'UCMSCROUTEA5CC11F194118AC54085447A'
AND r.del_flag = 0
AND NOT EXISTS (
SELECT 1 FROM biz_production_task_set x
WHERE x.tenant_no COLLATE utf8mb4_unicode_ci = r.tenant_no COLLATE utf8mb4_unicode_ci
AND x.set_name = '脐带MSC原代培养(内置模版)'
AND x.is_builtin = '1'
AND x.del_flag = 0
);
-- 4) 任务组合条目
INSERT INTO biz_production_task_set_item (
id, set_id, task_name, route_id, route_name, description, remark,
tenant_no, order_num, create_by, create_dept_id, create_time, update_by, update_time, del_flag
)
SELECT
'UCMSCITEM0A5CC11F194118AC54085447A',
s.id,
'{lab_storage_code}样本处理',
'UCMSCROUTEA5CC11F194118AC54085447A',
'脐带MSC原代培养(内置模版)',
'脐带MSC原代培养(内置模版)',
NULL,
s.tenant_no,
1,
s.create_by,
IFNULL(s.create_dept_id, ''),
NOW(),
s.update_by,
NOW(),
0
FROM biz_production_task_set s
WHERE s.set_name = '脐带MSC原代培养(内置模版)'
AND s.is_builtin = '1'
AND s.del_flag = 0
AND NOT EXISTS (
SELECT 1 FROM biz_production_task_set_item x
WHERE x.set_id COLLATE utf8mb4_unicode_ci = s.id COLLATE utf8mb4_unicode_ci
AND x.del_flag = 0
);
@@ -0,0 +1,424 @@
-- 【一次性回补】UC 开头实验室入库编码 → 补派「脐带MSC原代培养」5 步生产任务
-- 与种子脚本分开:先执行 2026-11-13-uc-msc-builtin-task-set.sql(或确保模版已存在),再执行本文件。
-- 等价于 backend/scripts/backfill_uc_msc_production_tasks.py --apply 的候选范围。
--
-- 候选条件(须全部满足):
-- 1) 样本接收 accept_conclusion=js、del_flag=0
-- 2) lab_storage_code 以 UC/uc 开头(非空)
-- 3) 关联入库生产工单 work_order_type=inbound、状态 dpz/jxz、del_flag=0
-- 4) 该工单当前无任何有效生产任务(已有任务如 UC2026010 跳过)
--
-- 动作:
-- - 每工单插入 1 条 biz_production_task(状态 dpz,任务名 {入库编码}样本处理)
-- - 从 UC 内置路线复制 5 个步骤到 biz_production_task_step(及试剂/耗材/产出/采集子表)
-- - 工单状态 dpz → jxz(已是 jxz/ywc 的不改 ywc;本脚本候选不含 ywc)
--
-- 幂等:已有有效任务的工单不会进入候选;重复执行影响行数应为 0。
-- 前置:biz_process_route.route_code='MSC原代-UC-BUILTIN'(或固定 id UCMSCROUTE…)及 5 步须已存在。
-- MySQL 5.7 / utf8mb4。未在生产库执行;执行前请先跑下方「预览」SELECT。
-- 兼容:
-- 1) 跨表等值统一 COLLATE utf8mb4_general_ci,避免 unicode_ci/general_ci 混用失败
-- 2) 多行 ID 用 MD5(业务键) 生成,避免同语句多行 UUID() 撞主键
-- 3) task_no 序号用 UNSIGNED 整数拼接,避免用户变量浮点变成 RW…2.00
SET NAMES utf8mb4;
-- ---------------------------------------------------------------------------
-- 0. 解析 UC 内置工艺路线
-- ---------------------------------------------------------------------------
SET @uc_route_id := (
SELECT r.id
FROM biz_process_route r
WHERE r.del_flag = 0
AND (
r.id = 'UCMSCROUTEA5CC11F194118AC54085447A'
OR r.route_code = 'MSC原代-UC-BUILTIN'
OR (r.route_name = '脐带MSC原代培养(内置模版)' AND r.is_builtin = '1')
)
ORDER BY
CASE
WHEN r.id = 'UCMSCROUTEA5CC11F194118AC54085447A' THEN 0
WHEN r.route_code = 'MSC原代-UC-BUILTIN' THEN 1
ELSE 2
END
LIMIT 1
);
SET @uc_step_count := (
SELECT COUNT(*)
FROM biz_process_route_step s
WHERE s.route_id COLLATE utf8mb4_unicode_ci = @uc_route_id COLLATE utf8mb4_unicode_ci
AND s.del_flag = 0
);
-- 预览:模版是否就绪(应 route 非空且 step_count=5)
SELECT @uc_route_id AS uc_route_id, @uc_step_count AS uc_step_count;
-- 若模版未就绪则主动失败(避免插入无步骤任务)
SET @uc_ready := IF(@uc_route_id IS NOT NULL AND @uc_step_count = 5, 1, 0);
-- 下面用 @uc_ready 约束所有写操作;为 0 时 INSERT 选不出行
-- ---------------------------------------------------------------------------
-- 1. 候选工单临时表
-- ---------------------------------------------------------------------------
DROP TEMPORARY TABLE IF EXISTS tmp_uc_wo_backfill;
CREATE TEMPORARY TABLE tmp_uc_wo_backfill (
seq INT NOT NULL AUTO_INCREMENT,
work_order_id VARCHAR(64) NOT NULL,
reception_id VARCHAR(64) NOT NULL,
lab_storage_code VARCHAR(32) NOT NULL,
tenant_no VARCHAR(64) NOT NULL,
sample_code VARCHAR(32) NULL,
task_id VARCHAR(64) NULL,
task_no VARCHAR(32) NULL,
route_id VARCHAR(64) NULL,
PRIMARY KEY (seq),
UNIQUE KEY uk_wo (work_order_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
INSERT INTO tmp_uc_wo_backfill (
work_order_id, reception_id, lab_storage_code, tenant_no, sample_code, route_id
)
SELECT
wo.id,
rec.id,
TRIM(rec.lab_storage_code),
wo.tenant_no,
wo.sample_code,
@uc_route_id
FROM biz_production_work_order wo
INNER JOIN biz_sample_reception rec
ON rec.id COLLATE utf8mb4_general_ci = wo.reception_id COLLATE utf8mb4_general_ci
AND rec.tenant_no COLLATE utf8mb4_general_ci = wo.tenant_no COLLATE utf8mb4_general_ci
AND rec.del_flag = 0
WHERE @uc_ready = 1
AND wo.del_flag = 0
AND wo.work_order_type = 'inbound'
AND wo.work_order_status IN ('dpz', 'jxz')
AND rec.accept_conclusion = 'js'
AND rec.lab_storage_code IS NOT NULL
AND TRIM(rec.lab_storage_code) <> ''
AND (
rec.lab_storage_code LIKE 'UC%'
OR rec.lab_storage_code LIKE 'uc%'
)
AND NOT EXISTS (
SELECT 1
FROM biz_production_task t
WHERE t.work_order_id COLLATE utf8mb4_general_ci = wo.id COLLATE utf8mb4_general_ci
AND t.tenant_no COLLATE utf8mb4_general_ci = wo.tenant_no COLLATE utf8mb4_general_ci
AND t.del_flag = 0
)
ORDER BY rec.reception_time ASC, wo.create_time ASC;
-- 预览候选(执行写库前请核对)
SELECT
seq,
work_order_id,
lab_storage_code,
sample_code,
tenant_no,
reception_id
FROM tmp_uc_wo_backfill
ORDER BY seq;
SELECT COUNT(*) AS candidate_count FROM tmp_uc_wo_backfill;
-- 分配 task_id / task_no(RW + yyyymmdd + 4 位序号,接当日已有最大序号)
SET @task_day := DATE_FORMAT(NOW(), '%Y%m%d');
SET @task_no_base := (
SELECT IFNULL(MAX(CAST(SUBSTRING(t.task_no, 11) AS UNSIGNED)), 0)
FROM biz_production_task t
WHERE t.task_no REGEXP CONCAT('^RW', @task_day, '[0-9]{4}$')
);
SET @task_no_base := CAST(IFNULL(@task_no_base, 0) AS UNSIGNED);
UPDATE tmp_uc_wo_backfill
SET
task_id = UPPER(MD5(CONCAT('uc-msc-backfill-task:', work_order_id))),
task_no = CONCAT('RW', @task_day, LPAD(@task_no_base + seq, 4, '0'));
-- ---------------------------------------------------------------------------
-- 2. 插入生产任务
-- ---------------------------------------------------------------------------
INSERT INTO biz_production_task (
id, task_no, work_order_id, order_source, task_type, task_name, description,
route_id, task_status, current_assignee_user_id, started_time, completed_time,
conclusion, remark, attachments, equipment_ids, equipment_name,
tenant_no, order_num, create_by, create_dept_id, create_time, update_by, update_time, del_flag
)
SELECT
c.task_id,
c.task_no,
c.work_order_id,
'inbound',
'cell_storage',
CONCAT(c.lab_storage_code, '样本处理'),
'脐带MSC原代培养(内置模版)',
c.route_id,
'dpz',
NULL,
NULL,
NULL,
NULL,
'一次性SQL回补:UC入库编码自动派发',
NULL,
r.equipment_ids,
r.equipment_name,
c.tenant_no,
0,
NULL,
'',
NOW(),
NULL,
NOW(),
0
FROM tmp_uc_wo_backfill c
INNER JOIN biz_process_route r
ON r.id COLLATE utf8mb4_unicode_ci = c.route_id COLLATE utf8mb4_unicode_ci
AND r.del_flag = 0
WHERE @uc_ready = 1
AND c.task_id IS NOT NULL
AND NOT EXISTS (
SELECT 1 FROM biz_production_task t
WHERE t.work_order_id COLLATE utf8mb4_general_ci = c.work_order_id COLLATE utf8mb4_general_ci
AND t.tenant_no COLLATE utf8mb4_general_ci = c.tenant_no COLLATE utf8mb4_general_ci
AND t.del_flag = 0
);
-- ---------------------------------------------------------------------------
-- 3. 步骤映射:路线步骤 → 新任务步骤 ID
-- ---------------------------------------------------------------------------
DROP TEMPORARY TABLE IF EXISTS tmp_uc_step_map;
CREATE TEMPORARY TABLE tmp_uc_step_map (
task_id VARCHAR(64) NOT NULL,
work_order_id VARCHAR(64) NOT NULL,
tenant_no VARCHAR(64) NOT NULL,
route_step_id VARCHAR(64) NOT NULL,
task_step_id VARCHAR(64) NOT NULL,
step_order INT NOT NULL,
PRIMARY KEY (task_id, route_step_id),
KEY ix_route_step (route_step_id),
KEY ix_task_step (task_step_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
INSERT INTO tmp_uc_step_map (
task_id, work_order_id, tenant_no, route_step_id, task_step_id, step_order
)
SELECT
c.task_id,
c.work_order_id,
c.tenant_no,
rs.id,
UPPER(MD5(CONCAT('uc-msc-backfill-step:', c.work_order_id, ':', rs.id))),
rs.step_order
FROM tmp_uc_wo_backfill c
INNER JOIN biz_process_route_step rs
ON rs.route_id COLLATE utf8mb4_unicode_ci = c.route_id COLLATE utf8mb4_unicode_ci
AND rs.del_flag = 0
WHERE @uc_ready = 1
AND EXISTS (
SELECT 1 FROM biz_production_task t
WHERE t.id COLLATE utf8mb4_general_ci = c.task_id COLLATE utf8mb4_general_ci
AND t.del_flag = 0
);
-- ---------------------------------------------------------------------------
-- 4. 插入任务步骤
-- ---------------------------------------------------------------------------
INSERT INTO biz_production_task_step (
id, task_id, step_order, process_code, category_id, process_name, description,
equipment_ids, equipment_name, estimated_duration, actual_duration,
sop_ids, sop_content, step_status, planned_start_time, started_time,
completed_time, completed_by, tenant_no, order_num, remark,
create_by, create_dept_id, create_time, update_by, update_time, del_flag
)
SELECT
m.task_step_id,
m.task_id,
rs.step_order,
rs.process_code,
rs.category_id,
rs.process_name,
rs.description,
rs.equipment_ids,
rs.equipment_name,
rs.estimated_duration,
NULL,
rs.sop_ids,
rs.sop_content,
'dzx',
NULL,
NULL,
NULL,
NULL,
m.tenant_no,
IFNULL(rs.order_num, rs.step_order),
NULL,
NULL,
'',
NOW(),
NULL,
NOW(),
0
FROM tmp_uc_step_map m
INNER JOIN biz_process_route_step rs
ON rs.id COLLATE utf8mb4_unicode_ci = m.route_step_id COLLATE utf8mb4_unicode_ci
AND rs.del_flag = 0
WHERE NOT EXISTS (
SELECT 1 FROM biz_production_task_step x
WHERE x.id COLLATE utf8mb4_general_ci = m.task_step_id COLLATE utf8mb4_general_ci
);
-- ---------------------------------------------------------------------------
-- 5. 复制路线步骤子表 → 任务步骤子表
-- ---------------------------------------------------------------------------
INSERT INTO biz_production_task_step_reagent (
id, step_id, reagent_code, reagent_name, spec, standard_usage, unit,
is_key_material, tenant_no, order_num, remark,
create_by, create_dept_id, create_time, update_by, update_time, del_flag
)
SELECT
UPPER(MD5(CONCAT('uc-msc-backfill-reag:', m.task_step_id, ':', src.id))),
m.task_step_id,
src.reagent_code,
src.reagent_name,
src.spec,
src.standard_usage,
src.unit,
src.is_key_material,
m.tenant_no,
src.order_num,
src.remark,
NULL,
'',
NOW(),
NULL,
NOW(),
0
FROM tmp_uc_step_map m
INNER JOIN biz_process_route_step_reagent src
ON src.step_id COLLATE utf8mb4_unicode_ci = m.route_step_id COLLATE utf8mb4_unicode_ci
AND src.del_flag = 0;
INSERT INTO biz_production_task_step_consumable (
id, step_id, consumable_code, consumable_name, spec_model, standard_usage,
unit, is_required, remark, tenant_no, order_num,
create_by, create_dept_id, create_time, update_by, update_time, del_flag
)
SELECT
UPPER(MD5(CONCAT('uc-msc-backfill-cons:', m.task_step_id, ':', src.id))),
m.task_step_id,
src.consumable_code,
src.consumable_name,
src.spec_model,
src.standard_usage,
src.unit,
src.is_required,
src.remark,
m.tenant_no,
src.order_num,
NULL,
'',
NOW(),
NULL,
NOW(),
0
FROM tmp_uc_step_map m
INNER JOIN biz_process_route_step_consumable src
ON src.step_id COLLATE utf8mb4_unicode_ci = m.route_step_id COLLATE utf8mb4_unicode_ci
AND src.del_flag = 0;
INSERT INTO biz_production_task_step_output (
id, step_id, output_type_id, output_name, output_barcode,
tenant_no, order_num, remark,
create_by, create_dept_id, create_time, update_by, update_time, del_flag
)
SELECT
UPPER(MD5(CONCAT('uc-msc-backfill-out:', m.task_step_id, ':', src.id))),
m.task_step_id,
src.output_type_id,
src.output_name,
src.output_barcode,
m.tenant_no,
src.order_num,
src.remark,
NULL,
'',
NOW(),
NULL,
NOW(),
0
FROM tmp_uc_step_map m
INNER JOIN biz_process_route_step_output src
ON src.step_id COLLATE utf8mb4_unicode_ci = m.route_step_id COLLATE utf8mb4_unicode_ci
AND src.del_flag = 0;
INSERT INTO biz_production_task_step_data_collection (
id, step_id, collection_name, unit, tenant_no, order_num, remark,
create_by, create_dept_id, create_time, update_by, update_time, del_flag
)
SELECT
UPPER(MD5(CONCAT('uc-msc-backfill-dc:', m.task_step_id, ':', src.id))),
m.task_step_id,
src.collection_name,
src.unit,
m.tenant_no,
src.order_num,
src.remark,
NULL,
'',
NOW(),
NULL,
NOW(),
0
FROM tmp_uc_step_map m
INNER JOIN biz_process_route_step_data_collection src
ON src.step_id COLLATE utf8mb4_unicode_ci = m.route_step_id COLLATE utf8mb4_unicode_ci
AND src.del_flag = 0;
-- ---------------------------------------------------------------------------
-- 6. 回写工单状态:有任务则 jxz(不改 ywc)
-- ---------------------------------------------------------------------------
UPDATE biz_production_work_order wo
INNER JOIN tmp_uc_wo_backfill c
ON c.work_order_id COLLATE utf8mb4_general_ci = wo.id COLLATE utf8mb4_general_ci
SET
wo.work_order_status = 'jxz',
wo.update_time = NOW()
WHERE wo.del_flag = 0
AND wo.work_order_status = 'dpz'
AND EXISTS (
SELECT 1 FROM biz_production_task t
WHERE t.work_order_id COLLATE utf8mb4_general_ci = wo.id COLLATE utf8mb4_general_ci
AND t.tenant_no COLLATE utf8mb4_general_ci = wo.tenant_no COLLATE utf8mb4_general_ci
AND t.del_flag = 0
);
-- ---------------------------------------------------------------------------
-- 7. 结果核对
-- ---------------------------------------------------------------------------
SELECT
c.lab_storage_code,
c.work_order_id,
wo.work_order_no,
wo.work_order_status,
t.id AS task_id,
t.task_no,
t.task_name,
(
SELECT COUNT(*)
FROM biz_production_task_step s
WHERE s.task_id COLLATE utf8mb4_general_ci = t.id COLLATE utf8mb4_general_ci
AND s.del_flag = 0
) AS step_count
FROM tmp_uc_wo_backfill c
LEFT JOIN biz_production_work_order wo
ON wo.id COLLATE utf8mb4_general_ci = c.work_order_id COLLATE utf8mb4_general_ci
LEFT JOIN biz_production_task t
ON t.id COLLATE utf8mb4_general_ci = c.task_id COLLATE utf8mb4_general_ci
AND t.del_flag = 0
ORDER BY c.seq;
DROP TEMPORARY TABLE IF EXISTS tmp_uc_step_map;
DROP TEMPORARY TABLE IF EXISTS tmp_uc_wo_backfill;
@@ -0,0 +1,54 @@
-- Issue #127:已作废 / 属地废弃协议下样本状态回刷为已作废
-- 细胞存储 + 科研捐赠;可重复执行。
-- 规则:协议 status 为 yzf/sdfq 且样本未删除时,sample_status 置 yzf,
-- void_date 为空时按协议 void_time / update_time 补齐 YYYYMMDD。
-- 细胞存储协议样本
UPDATE biz_protocol_sample s
INNER JOIN biz_collection_protocol p
ON p.id = s.collection_protocol_id
AND p.tenant_no = s.tenant_no
AND p.del_flag = 0
SET
s.sample_status = 'yzf',
s.void_date = CASE
WHEN s.void_date IS NOT NULL AND TRIM(s.void_date) <> '' THEN s.void_date
WHEN p.void_time IS NOT NULL THEN DATE_FORMAT(p.void_time, '%Y%m%d')
WHEN p.update_time IS NOT NULL THEN DATE_FORMAT(p.update_time, '%Y%m%d')
ELSE DATE_FORMAT(NOW(), '%Y%m%d')
END,
s.update_time = NOW()
WHERE s.del_flag = 0
AND p.protocol_status IN ('yzf', 'sdfq')
AND (
s.sample_status IS NULL
OR TRIM(s.sample_status) = ''
OR s.sample_status <> 'yzf'
OR s.void_date IS NULL
OR TRIM(s.void_date) = ''
);
-- 科研捐赠样本
UPDATE biz_research_donation_sample s
INNER JOIN biz_research_donation d
ON d.id = s.research_donation_id
AND d.tenant_no = s.tenant_no
AND d.del_flag = 0
SET
s.sample_status = 'yzf',
s.void_date = CASE
WHEN s.void_date IS NOT NULL AND TRIM(s.void_date) <> '' THEN s.void_date
WHEN d.void_time IS NOT NULL THEN DATE_FORMAT(d.void_time, '%Y%m%d')
WHEN d.update_time IS NOT NULL THEN DATE_FORMAT(d.update_time, '%Y%m%d')
ELSE DATE_FORMAT(NOW(), '%Y%m%d')
END,
s.update_time = NOW()
WHERE s.del_flag = 0
AND d.donation_status IN ('yzf', 'sdfq')
AND (
s.sample_status IS NULL
OR TRIM(s.sample_status) = ''
OR s.sample_status <> 'yzf'
OR s.void_date IS NULL
OR TRIM(s.void_date) = ''
);
+11
View File
@@ -25,6 +25,17 @@ export function fetchCreateReceiveAccount(data) {
return post('/web/admin/oa-approval/receive-accounts', data) return post('/web/admin/oa-approval/receive-accounts', data)
} }
export function fetchUpdateReceiveAccount(id, data) {
return put(`/web/admin/oa-approval/receive-accounts/${id}`, data)
}
export function fetchDeleteReceiveAccount(id) {
return request({
url: `/web/admin/oa-approval/receive-accounts/${id}`,
method: 'DELETE'
})
}
export function fetchRelatedCandidates(params) { export function fetchRelatedCandidates(params) {
return get('/web/admin/oa-approval/related-candidates', params) return get('/web/admin/oa-approval/related-candidates', params)
} }
@@ -150,6 +150,7 @@ import {
uploadAttachment uploadAttachment
} from '../../api/oa.js' } from '../../api/oa.js'
import OaCommentFileCards from './OaCommentFileCards.vue' import OaCommentFileCards from './OaCommentFileCards.vue'
import { hasOaCommentDraft } from '../oa-comment-draft.js'
import { attachmentFullUrl } from '../../utils/attachment.js' import { attachmentFullUrl } from '../../utils/attachment.js'
import { isHarmonyWechat } from '../../utils/harmony-file-picker.js' import { isHarmonyWechat } from '../../utils/harmony-file-picker.js'
import HarmonyFileSource from '../../components/HarmonyFileSource.vue' import HarmonyFileSource from '../../components/HarmonyFileSource.vue'
@@ -516,12 +517,25 @@ function confirmMention() {
mentionVisible.value = false mentionVisible.value = false
} }
async function onSend() { function draftPending() {
const content = draft.value.trim() return hasOaCommentDraft({
if (!content && !mentionUsers.value.length && !picked.value.length) { content: draft.value,
showToast('请填写评论、@人员或添加附件') mentionCount: mentionUsers.value.length,
return attachmentCount: picked.value.length
})
} }
/**
* 审批动作前冲刷未发送草稿:无草稿直接成功;有草稿则等同点击「发送」。
* @returns {Promise<boolean>} false 表示发送失败或忙碌,调用方应中止审批动作
*/
async function flushDraft(opts = {}) {
if (!draftPending()) return true
if (sending.value || uploading.value) {
showToast(uploading.value ? '附件上传中,请稍后再试' : '评论发送中,请稍后再试')
return false
}
const content = draft.value.trim()
sending.value = true sending.value = true
try { try {
await fetchCreateOaComment(props.instanceId, { await fetchCreateOaComment(props.instanceId, {
@@ -533,15 +547,27 @@ async function onSend() {
picked.value = [] picked.value = []
mentionUsers.value = [] mentionUsers.value = []
closeAtSuggest() closeAtSuggest()
showToast('已发送') if (!opts.quiet) showToast('已发送')
emit('refresh') emit('refresh')
return true
} catch (e) { } catch (e) {
showToast(e?.message || '发送失败') showToast(e?.message || '发送失败')
return false
} finally { } finally {
sending.value = false sending.value = false
} }
} }
async function onSend() {
if (!draftPending()) {
showToast('请填写评论、@人员或添加附件')
return
}
await flushDraft()
}
defineExpose({ flushDraft, draftPending })
onMounted(() => { onMounted(() => {
void ensureUserCache() void ensureUserCache()
}) })
@@ -52,6 +52,24 @@
<div class="oa-sheet-row__title">{{ a.label }}</div> <div class="oa-sheet-row__title">{{ a.label }}</div>
<div v-if="a.sub" class="oa-sheet-row__meta">{{ a.sub }}</div> <div v-if="a.sub" class="oa-sheet-row__meta">{{ a.sub }}</div>
</div> </div>
<div class="oa-sheet-row__actions" @click.stop>
<button
type="button"
class="oa-sheet-row__icon is-edit"
aria-label="编辑"
@click="openEdit(a.id)"
>
<van-icon name="edit" />
</button>
<button
type="button"
class="oa-sheet-row__icon is-delete"
aria-label="删除"
@click="confirmDelete(a.id)"
>
<van-icon name="delete-o" />
</button>
</div>
</div> </div>
</van-checkbox-group> </van-checkbox-group>
<van-empty v-if="!loading && !filtered.length" description="暂无本人的收款账户" /> <van-empty v-if="!loading && !filtered.length" description="暂无本人的收款账户" />
@@ -63,17 +81,17 @@
</div> </div>
</van-popup> </van-popup>
<van-popup v-model:show="createVisible" position="bottom" round> <van-popup v-model:show="formVisible" position="bottom" round>
<div class="oa-recv__sheet oa-recv__sheet--create"> <div class="oa-recv__sheet oa-recv__sheet--create">
<div class="oa-recv__hd"> <div class="oa-recv__hd">
<span @click="createVisible = false">取消</span> <span @click="formVisible = false">取消</span>
<strong>新增收款账户</strong> <strong>{{ formTitle }}</strong>
<span <span
class="oa-recv__ok" class="oa-recv__ok"
:class="{ 'is-busy': createLoading }" :class="{ 'is-busy': formLoading }"
@click="submitCreate" @click="submitForm"
> >
{{ createLoading ? '提交中' : '确定' }} {{ formLoading ? '提交中' : '确定' }}
</span> </span>
</div> </div>
<div class="oa-recv__form"> <div class="oa-recv__form">
@@ -87,45 +105,45 @@
<label class="oa-recv-field"> <label class="oa-recv-field">
<span class="oa-recv-field__label">户名<b>*</b></span> <span class="oa-recv-field__label">户名<b>*</b></span>
<span class="oa-recv-field__box"> <span class="oa-recv-field__box">
<input v-model="createForm.accountName" maxlength="128" placeholder="请输入户名" /> <input v-model="formModel.accountName" maxlength="128" placeholder="请输入户名" />
</span> </span>
</label> </label>
<label class="oa-recv-field"> <label class="oa-recv-field">
<span class="oa-recv-field__label">账号<b>*</b></span> <span class="oa-recv-field__label">账号<b>*</b></span>
<span class="oa-recv-field__box"> <span class="oa-recv-field__box">
<input v-model="createForm.accountNo" maxlength="128" placeholder="请输入账号" /> <input v-model="formModel.accountNo" maxlength="128" placeholder="请输入账号" />
</span> </span>
</label> </label>
<template v-if="createForm.accountType !== 'alipay'"> <template v-if="formModel.accountType !== 'alipay'">
<label class="oa-recv-field"> <label class="oa-recv-field">
<span class="oa-recv-field__label">银行<b>*</b></span> <span class="oa-recv-field__label">银行<b>*</b></span>
<span class="oa-recv-field__box"> <span class="oa-recv-field__box">
<input v-model="createForm.bankName" maxlength="128" placeholder="如:中国工商银行" /> <input v-model="formModel.bankName" maxlength="128" placeholder="如:中国工商银行" />
</span> </span>
</label> </label>
<label class="oa-recv-field"> <label class="oa-recv-field">
<span class="oa-recv-field__label">银行所在省<b>*</b></span> <span class="oa-recv-field__label">银行所在省<b>*</b></span>
<span class="oa-recv-field__box"> <span class="oa-recv-field__box">
<input v-model="createForm.bankProvince" maxlength="64" placeholder="如:安徽省" /> <input v-model="formModel.bankProvince" maxlength="64" placeholder="如:安徽省" />
</span> </span>
</label> </label>
<label class="oa-recv-field"> <label class="oa-recv-field">
<span class="oa-recv-field__label">银行所在市<b>*</b></span> <span class="oa-recv-field__label">银行所在市<b>*</b></span>
<span class="oa-recv-field__box"> <span class="oa-recv-field__box">
<input v-model="createForm.bankCity" maxlength="64" placeholder="如:合肥市" /> <input v-model="formModel.bankCity" maxlength="64" placeholder="如:合肥市" />
</span> </span>
</label> </label>
<label class="oa-recv-field"> <label class="oa-recv-field">
<span class="oa-recv-field__label">银行支行<b>*</b></span> <span class="oa-recv-field__label">银行支行<b>*</b></span>
<span class="oa-recv-field__box"> <span class="oa-recv-field__box">
<input v-model="createForm.bankBranch" maxlength="256" placeholder="请输入开户支行全称" /> <input v-model="formModel.bankBranch" maxlength="256" placeholder="请输入开户支行全称" />
</span> </span>
</label> </label>
</template> </template>
<label class="oa-recv-field"> <label class="oa-recv-field">
<span class="oa-recv-field__label">备注</span> <span class="oa-recv-field__label">备注</span>
<span class="oa-recv-field__box oa-recv-field__box--area"> <span class="oa-recv-field__box oa-recv-field__box--area">
<textarea v-model="createForm.remark" maxlength="512" rows="2" placeholder="选填" /> <textarea v-model="formModel.remark" maxlength="512" rows="2" placeholder="选填" />
</span> </span>
</label> </label>
</div> </div>
@@ -135,7 +153,7 @@
<van-popup v-model:show="typePickerVisible" position="bottom" round> <van-popup v-model:show="typePickerVisible" position="bottom" round>
<van-picker <van-picker
:columns="accountTypeColumns" :columns="accountTypeColumns"
:model-value="[createForm.accountType]" :model-value="[formModel.accountType]"
@confirm="onTypeConfirm" @confirm="onTypeConfirm"
@cancel="typePickerVisible = false" @cancel="typePickerVisible = false"
/> />
@@ -145,8 +163,13 @@
<script setup> <script setup>
import { computed, onMounted, ref } from 'vue' import { computed, onMounted, ref } from 'vue'
import { showToast } from 'vant' import { showConfirmDialog, showToast } from 'vant'
import { fetchCreateReceiveAccount, fetchReceiveAccountOptions } from '../../api/oa.js' import {
fetchCreateReceiveAccount,
fetchDeleteReceiveAccount,
fetchReceiveAccountOptions,
fetchUpdateReceiveAccount
} from '../../api/oa.js'
import { import {
ACCOUNT_TYPE_LABEL, ACCOUNT_TYPE_LABEL,
formatReceiveAccountLine, formatReceiveAccountLine,
@@ -170,17 +193,19 @@ const keyword = ref('')
const pendingIds = ref([]) const pendingIds = ref([])
const snapshotMap = ref(new Map()) const snapshotMap = ref(new Map())
const accountOptions = ref([]) const accountOptions = ref([])
const createVisible = ref(false) const formVisible = ref(false)
const createLoading = ref(false) const formLoading = ref(false)
const formMode = ref('create')
const editingId = ref('')
const typePickerVisible = ref(false) const typePickerVisible = ref(false)
const accountTypeColumns = [ const accountTypeColumns = [
{ text: '支付宝', value: 'alipay' }, { text: '支付宝', value: 'alipay' },
{ text: '个人银行卡', value: 'personal' }, { text: '个人银行卡', value: 'personal' },
{ text: '对公银行账户', value: 'corporate' } { text: '对公银行账户', value: 'corporate' }
] ]
const createForm = ref(emptyCreateForm()) const formModel = ref(emptyForm())
function emptyCreateForm() { function emptyForm() {
return { return {
accountType: 'alipay', accountType: 'alipay',
accountName: '', accountName: '',
@@ -193,8 +218,12 @@ function emptyCreateForm() {
} }
} }
const formTitle = computed(() =>
formMode.value === 'edit' ? '编辑收款账户' : '新增收款账户'
)
const accountTypeLabel = computed( const accountTypeLabel = computed(
() => ACCOUNT_TYPE_LABEL[createForm.value.accountType] || '' () => ACCOUNT_TYPE_LABEL[formModel.value.accountType] || ''
) )
const normalized = computed(() => normalizeReceiveAccountModelValue(props.modelValue)) const normalized = computed(() => normalizeReceiveAccountModelValue(props.modelValue))
@@ -260,26 +289,78 @@ function optionFromSnap(snap) {
} }
} }
function upsertLocalSnap(snap) {
if (!snap.id) return
const map = new Map(snapshotMap.value)
map.set(snap.id, snap)
snapshotMap.value = map
const opt = optionFromSnap(snap)
const idx = accountOptions.value.findIndex((x) => x.id === snap.id)
if (idx >= 0) {
const next = [...accountOptions.value]
next[idx] = opt
accountOptions.value = next
} else {
accountOptions.value = [...accountOptions.value, opt]
}
}
function fillFormFromSnap(snap) {
const form = {
accountType: snap.accountType || 'alipay',
accountName: snap.accountName || '',
accountNo: snap.accountNo || '',
bankName: snap.bankName || '',
bankProvince: snap.bankProvince || '',
bankCity: snap.bankCity || '',
bankBranch: snap.bankBranch || '',
remark: snap.remark || ''
}
if (form.accountType === 'alipay') {
form.bankName = ''
form.bankProvince = ''
form.bankCity = ''
form.bankBranch = ''
}
formModel.value = form
}
function openCreate() { function openCreate() {
createForm.value = emptyCreateForm() formMode.value = 'create'
editingId.value = ''
formModel.value = emptyForm()
typePickerVisible.value = false typePickerVisible.value = false
createVisible.value = true formVisible.value = true
}
function openEdit(id) {
const tid = String(id || '').trim()
const snap = snapshotMap.value.get(tid)
if (!snap) {
showToast('账户不存在或已删除')
return
}
formMode.value = 'edit'
editingId.value = tid
fillFormFromSnap(snap)
typePickerVisible.value = false
formVisible.value = true
} }
function onTypeConfirm({ selectedOptions }) { function onTypeConfirm({ selectedOptions }) {
const next = selectedOptions?.[0]?.value || 'alipay' const next = selectedOptions?.[0]?.value || 'alipay'
const form = { ...createForm.value, accountType: next } const form = { ...formModel.value, accountType: next }
if (next === 'alipay') { if (next === 'alipay') {
form.bankName = '' form.bankName = ''
form.bankProvince = '' form.bankProvince = ''
form.bankCity = '' form.bankCity = ''
form.bankBranch = '' form.bankBranch = ''
} }
createForm.value = form formModel.value = form
typePickerVisible.value = false typePickerVisible.value = false
} }
function validateCreate(form) { function validateForm(form) {
if (!form.accountName.trim()) return '请输入户名' if (!form.accountName.trim()) return '请输入户名'
if (!form.accountNo.trim()) return '请输入账号' if (!form.accountNo.trim()) return '请输入账号'
if (form.accountType !== 'alipay') { if (form.accountType !== 'alipay') {
@@ -291,14 +372,7 @@ function validateCreate(form) {
return '' return ''
} }
async function submitCreate() { function buildPayload(form) {
if (createLoading.value) return
const form = createForm.value
const invalid = validateCreate(form)
if (invalid) {
showToast(invalid)
return
}
const payload = { const payload = {
accountType: form.accountType, accountType: form.accountType,
accountName: form.accountName.trim(), accountName: form.accountName.trim(),
@@ -316,23 +390,38 @@ async function submitCreate() {
payload.bankCity = form.bankCity.trim() payload.bankCity = form.bankCity.trim()
payload.bankBranch = form.bankBranch.trim() payload.bankBranch = form.bankBranch.trim()
} }
createLoading.value = true return payload
}
async function submitForm() {
if (formLoading.value) return
const form = formModel.value
const invalid = validateForm(form)
if (invalid) {
showToast(invalid)
return
}
const payload = buildPayload(form)
formLoading.value = true
try { try {
const created = await fetchCreateReceiveAccount(payload) const row =
const snap = snapshotFromRow(created) formMode.value === 'edit' && editingId.value
? await fetchUpdateReceiveAccount(editingId.value, payload)
: await fetchCreateReceiveAccount(payload)
const snap = snapshotFromRow(row)
if (!snap.id) { if (!snap.id) {
showToast('创建成功但未返回账户 ID') showToast(formMode.value === 'edit' ? '更新成功但未返回账户 ID' : '创建成功但未返回账户 ID')
return return
} }
await loadOptions() await loadOptions()
if (!snapshotMap.value.has(snap.id)) { upsertLocalSnap(snap)
const map = new Map(snapshotMap.value) if (formMode.value === 'edit') {
map.set(snap.id, snap) const selected = normalized.value.map((x) => x.id)
snapshotMap.value = map if (selected.includes(snap.id)) {
if (!accountOptions.value.some((x) => x.id === snap.id)) { emitItems(selected.map((id) => snapshotMap.value.get(id)).filter(Boolean))
accountOptions.value = [...accountOptions.value, optionFromSnap(snap)]
}
} }
showToast('更新成功')
} else {
const selected = new Set(normalized.value.map((x) => x.id)) const selected = new Set(normalized.value.map((x) => x.id))
selected.add(snap.id) selected.add(snap.id)
emitItems([...selected].map((id) => snapshotMap.value.get(id)).filter(Boolean)) emitItems([...selected].map((id) => snapshotMap.value.get(id)).filter(Boolean))
@@ -340,12 +429,41 @@ async function submitCreate() {
pendingIds.value = [...pendingIds.value, snap.id] pendingIds.value = [...pendingIds.value, snap.id]
} }
keyword.value = '' keyword.value = ''
createVisible.value = false
showToast('创建成功') showToast('创建成功')
}
formVisible.value = false
} catch (e) { } catch (e) {
showToast(e?.message || '新增收款账户失败') showToast(e?.message || (formMode.value === 'edit' ? '编辑收款账户失败' : '新增收款账户失败'))
} finally { } finally {
createLoading.value = false formLoading.value = false
}
}
async function confirmDelete(id) {
const tid = String(id || '').trim()
const snap = snapshotMap.value.get(tid)
const name = snap?.accountName || tid
try {
await showConfirmDialog({
title: '删除收款账户',
message: `确定删除收款账户「${name}」吗?删除后不可再选;已提交单据中的账户快照仍保留。`
})
} catch {
return
}
try {
await fetchDeleteReceiveAccount(tid)
await loadOptions()
const nextSelected = normalized.value
.map((x) => x.id)
.filter((x) => x !== tid)
.map((x) => snapshotMap.value.get(x))
.filter(Boolean)
emitItems(nextSelected)
pendingIds.value = pendingIds.value.filter((x) => x !== tid)
showToast('删除成功')
} catch (e) {
showToast(e?.message || '删除收款账户失败')
} }
} }
@@ -411,6 +529,39 @@ onMounted(() => {
line-height: 1.5; line-height: 1.5;
} }
.oa-sheet-row__actions {
display: inline-flex;
flex: none;
gap: 6px;
align-items: center;
margin-left: 4px;
}
.oa-sheet-row__icon {
display: inline-flex;
align-items: center;
justify-content: center;
width: 36px;
height: 36px;
margin: 0;
padding: 0;
border: 0;
border-radius: 8px;
background: transparent;
font-size: 18px;
cursor: pointer;
}
.oa-sheet-row__icon.is-edit {
background: #ecfdf5;
color: var(--brand-green-dark, #16a34a);
}
.oa-sheet-row__icon.is-delete {
background: #fef2f2;
color: #dc2626;
}
.oa-recv__add { .oa-recv__add {
display: flex; display: flex;
gap: 6px; gap: 6px;
+7
View File
@@ -0,0 +1,7 @@
/** 评论区是否有未发送草稿(文字 / @ / 附件) */
export function hasOaCommentDraft(input = {}) {
const content = String(input.content || '').trim()
const mentionCount = Number(input.mentionCount || 0)
const attachmentCount = Number(input.attachmentCount || 0)
return !!(content || mentionCount > 0 || attachmentCount > 0)
}
@@ -0,0 +1,14 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { hasOaCommentDraft } from './oa-comment-draft.js'
test('empty draft is false', () => {
assert.equal(hasOaCommentDraft({}), false)
assert.equal(hasOaCommentDraft({ content: ' ', mentionCount: 0, attachmentCount: 0 }), false)
})
test('text / mention / attachment counts as draft', () => {
assert.equal(hasOaCommentDraft({ content: '@test' }), true)
assert.equal(hasOaCommentDraft({ mentionCount: 1 }), true)
assert.equal(hasOaCommentDraft({ attachmentCount: 2 }), true)
})
+11 -1
View File
@@ -29,6 +29,7 @@
@refresh="reloadDetail" @refresh="reloadDetail"
/> />
<OaCommentComposer <OaCommentComposer
ref="commentComposerRef"
:instance-id="instanceId" :instance-id="instanceId"
:instance-status="detail?.status || ''" :instance-status="detail?.status || ''"
@refresh="reloadDetail" @refresh="reloadDetail"
@@ -238,6 +239,7 @@ const currentUserId = ref('')
const currentUserName = ref('') const currentUserName = ref('')
const autoPrinted = ref(false) const autoPrinted = ref(false)
const commentComposerRef = ref(null)
const commentVisible = ref(false) const commentVisible = ref(false)
const commentKind = ref('approve') // approve | reject | return const commentKind = ref('approve') // approve | reject | return
const commentText = ref('') const commentText = ref('')
@@ -492,8 +494,16 @@ function goCopyRestart() {
}) })
} }
function openComment(kind) { /** 同意/拒绝/打回前先发送评论区未提交草稿 */
async function flushPendingComment() {
const flush = commentComposerRef.value?.flushDraft
if (!flush) return true
return await flush()
}
async function openComment(kind) {
if (!myPendingTask.value) return if (!myPendingTask.value) return
if (!(await flushPendingComment())) return
commentKind.value = kind commentKind.value = kind
commentText.value = defaultComment(kind) commentText.value = defaultComment(kind)
commentVisible.value = true commentVisible.value = true
+2
View File
@@ -141,6 +141,8 @@ export type QcWorkOrder = {
patientName?: string patientName?: string
/** 入库工单(细胞存储/科研捐赠):母亲姓名 */ /** 入库工单(细胞存储/科研捐赠):母亲姓名 */
motherName?: string motherName?: string
/** 协议单母血采集时间;未录入时为空,前端展示为 — */
maternalBloodCollectTime?: string
/** 入库工单(细胞存储/科研捐赠):新生儿姓名 */ /** 入库工单(细胞存储/科研捐赠):新生儿姓名 */
newbornName?: string newbornName?: string
/** 出库工单:当前为第几次输注计划 */ /** 出库工单:当前为第几次输注计划 */
@@ -192,6 +192,7 @@
} from '@/api/oaApproval' } from '@/api/oaApproval'
import OaCommentFileCards from '@/components/oa-approval/OaCommentFileCards.vue' import OaCommentFileCards from '@/components/oa-approval/OaCommentFileCards.vue'
import { attachmentFullUrl } from '@/composables/useAttachmentActions' import { attachmentFullUrl } from '@/composables/useAttachmentActions'
import { hasOaCommentDraft } from '@/utils/oa-comment-draft'
import { isOaUploadImageFile, isOaUploadVideoFile } from '@/utils/oa-upload-file-type' import { isOaUploadImageFile, isOaUploadVideoFile } from '@/utils/oa-upload-file-type'
defineOptions({ name: 'OaCommentPanel' }) defineOptions({ name: 'OaCommentPanel' })
@@ -546,12 +547,25 @@
} }
} }
async function onSend() { function draftPending() {
const content = draft.value.trim() return hasOaCommentDraft({
if (!content && !mentionUsers.value.length && !picked.value.length) { content: draft.value,
ElMessage.warning('请填写评论、@人员或添加附件') mentionCount: mentionUsers.value.length,
return attachmentCount: picked.value.length
})
} }
/**
* 审批动作前冲刷未发送草稿:无草稿直接成功;有草稿则等同点击「发送」。
* @returns false 表示发送失败或忙碌,调用方应中止审批动作
*/
async function flushDraft(opts?: { quiet?: boolean }): Promise<boolean> {
if (!draftPending()) return true
if (sending.value || uploading.value) {
ElMessage.warning(uploading.value ? '附件上传中,请稍后再试' : '评论发送中,请稍后再试')
return false
}
const content = draft.value.trim()
sending.value = true sending.value = true
try { try {
await fetchCreateOaComment(props.instanceId, { await fetchCreateOaComment(props.instanceId, {
@@ -565,15 +579,27 @@
picked.value = [] picked.value = []
mentionUsers.value = [] mentionUsers.value = []
closeAtSuggest() closeAtSuggest()
ElMessage.success('已发送') if (!opts?.quiet) ElMessage.success('已发送')
emit('refresh') emit('refresh')
return true
} catch (e: any) { } catch (e: any) {
ElMessage.error(e?.message || '发送失败') ElMessage.error(e?.message || '发送失败')
return false
} finally { } finally {
sending.value = false sending.value = false
} }
} }
async function onSend() {
if (!draftPending()) {
ElMessage.warning('请填写评论、@人员或添加附件')
return
}
await flushDraft()
}
defineExpose({ flushDraft, draftPending })
onMounted(() => { onMounted(() => {
void ensureUserCache() void ensureUserCache()
}) })
@@ -40,17 +40,39 @@
class="oa-receive-account-select__search" class="oa-receive-account-select__search"
/> />
<div class="oa-receive-account-select__list"> <div class="oa-receive-account-select__list">
<label <div
v-for="a in filteredOptions" v-for="a in filteredOptions"
:key="a.id" :key="a.id"
class="oa-receive-account-select__row" class="oa-receive-account-select__row"
> >
<label class="oa-receive-account-select__row-main">
<el-checkbox <el-checkbox
:model-value="pendingIds.includes(a.id)" :model-value="pendingIds.includes(a.id)"
@change="(v: boolean | string | number) => onNarrowCheck(a.id, !!v)" @change="(v: boolean | string | number) => onNarrowCheck(a.id, !!v)"
/> />
<span class="oa-receive-account-select__row-label">{{ a.label }}</span> <span class="oa-receive-account-select__row-label">{{ a.label }}</span>
</label> </label>
<div class="oa-receive-account-select__row-actions">
<button
type="button"
class="oa-receive-account-select__icon-btn is-edit"
title="编辑"
aria-label="编辑"
@click="openEditDialog(a.id)"
>
<el-icon><Edit /></el-icon>
</button>
<button
type="button"
class="oa-receive-account-select__icon-btn is-delete"
title="删除"
aria-label="删除"
@click="confirmDelete(a.id)"
>
<el-icon><Delete /></el-icon>
</button>
</div>
</div>
<div v-if="!filteredOptions.length" class="oa-receive-account-select__empty"> <div v-if="!filteredOptions.length" class="oa-receive-account-select__empty">
暂无本人的收款账户 暂无本人的收款账户
</div> </div>
@@ -92,7 +114,31 @@
:key="a.id" :key="a.id"
:label="a.label" :label="a.label"
:value="a.id" :value="a.id"
/> >
<div class="oa-receive-account-select__option">
<span class="oa-receive-account-select__option-label">{{ a.label }}</span>
<span class="oa-receive-account-select__option-actions" @mousedown.prevent @click.stop>
<button
type="button"
class="oa-receive-account-select__icon-btn is-edit"
title="编辑"
aria-label="编辑"
@click="openEditDialog(a.id)"
>
<el-icon><Edit /></el-icon>
</button>
<button
type="button"
class="oa-receive-account-select__icon-btn is-delete"
title="删除"
aria-label="删除"
@click="confirmDelete(a.id)"
>
<el-icon><Delete /></el-icon>
</button>
</span>
</div>
</el-option>
<template #empty> <template #empty>
<div class="oa-receive-account-select__empty"> <div class="oa-receive-account-select__empty">
{{ accountOptions.length === 0 ? '暂无本人的收款账户' : '无匹配数据' }} {{ accountOptions.length === 0 ? '暂无本人的收款账户' : '无匹配数据' }}
@@ -120,8 +166,8 @@
</template> </template>
<el-dialog <el-dialog
v-model="createVisible" v-model="formVisible"
title="新增收款账户" :title="formTitle"
width="720px" width="720px"
class="dialog-form-layout" class="dialog-form-layout"
align-center align-center
@@ -131,9 +177,9 @@
:close-on-click-modal="false" :close-on-click-modal="false"
> >
<el-form <el-form
ref="createFormRef" ref="formRef"
:model="createForm" :model="formModel"
:rules="createRules" :rules="formRules"
label-position="top" label-position="top"
scroll-to-error scroll-to-error
:scroll-into-view-options="{ behavior: 'smooth', block: 'center' }" :scroll-into-view-options="{ behavior: 'smooth', block: 'center' }"
@@ -141,9 +187,9 @@
<div class="form-grid-2"> <div class="form-grid-2">
<el-form-item label="账户类型" prop="accountType" class="form-col-span-2"> <el-form-item label="账户类型" prop="accountType" class="form-col-span-2">
<el-select <el-select
v-model="createForm.accountType" v-model="formModel.accountType"
placeholder="请选择" placeholder="请选择"
@change="onCreateTypeChange" @change="onFormTypeChange"
> >
<el-option <el-option
v-for="(label, value) in ACCOUNT_TYPE_LABEL" v-for="(label, value) in ACCOUNT_TYPE_LABEL"
@@ -154,22 +200,22 @@
</el-select> </el-select>
</el-form-item> </el-form-item>
<el-form-item label="户名" prop="accountName"> <el-form-item label="户名" prop="accountName">
<el-input v-model="createForm.accountName" placeholder="请输入户名" maxlength="128" /> <el-input v-model="formModel.accountName" placeholder="请输入户名" maxlength="128" />
</el-form-item> </el-form-item>
<el-form-item label="账号" prop="accountNo"> <el-form-item label="账号" prop="accountNo">
<el-input v-model="createForm.accountNo" placeholder="请输入账号" maxlength="128" /> <el-input v-model="formModel.accountNo" placeholder="请输入账号" maxlength="128" />
</el-form-item> </el-form-item>
<template v-if="createForm.accountType !== 'alipay'"> <template v-if="formModel.accountType !== 'alipay'">
<el-form-item label="银行" prop="bankName"> <el-form-item label="银行" prop="bankName">
<el-input <el-input
v-model="createForm.bankName" v-model="formModel.bankName"
placeholder="如:中国工商银行" placeholder="如:中国工商银行"
maxlength="128" maxlength="128"
/> />
</el-form-item> </el-form-item>
<el-form-item label="银行所在省" prop="bankProvince"> <el-form-item label="银行所在省" prop="bankProvince">
<el-input <el-input
v-model="createForm.bankProvince" v-model="formModel.bankProvince"
placeholder="如:安徽省" placeholder="如:安徽省"
maxlength="64" maxlength="64"
clearable clearable
@@ -177,7 +223,7 @@
</el-form-item> </el-form-item>
<el-form-item label="银行所在市" prop="bankCity"> <el-form-item label="银行所在市" prop="bankCity">
<el-input <el-input
v-model="createForm.bankCity" v-model="formModel.bankCity"
placeholder="如:合肥市" placeholder="如:合肥市"
maxlength="64" maxlength="64"
clearable clearable
@@ -185,7 +231,7 @@
</el-form-item> </el-form-item>
<el-form-item label="银行支行" prop="bankBranch" class="form-col-span-2"> <el-form-item label="银行支行" prop="bankBranch" class="form-col-span-2">
<el-input <el-input
v-model="createForm.bankBranch" v-model="formModel.bankBranch"
placeholder="请输入开户支行全称" placeholder="请输入开户支行全称"
maxlength="256" maxlength="256"
/> />
@@ -193,7 +239,7 @@
</template> </template>
<el-form-item label="备注" class="form-col-span-2"> <el-form-item label="备注" class="form-col-span-2">
<el-input <el-input
v-model="createForm.remark" v-model="formModel.remark"
type="textarea" type="textarea"
:rows="2" :rows="2"
placeholder="选填" placeholder="选填"
@@ -203,15 +249,15 @@
</div> </div>
</el-form> </el-form>
<template #footer> <template #footer>
<el-button class="btn-ghost" @click="createVisible = false"> <el-button class="btn-ghost" @click="formVisible = false">
<el-icon><Close /></el-icon> <el-icon><Close /></el-icon>
取消 取消
</el-button> </el-button>
<el-button <el-button
class="btn-main" class="btn-main"
type="primary" type="primary"
:loading="createLoading" :loading="formLoading"
@click="submitCreate" @click="submitForm"
> >
<el-icon><Check /></el-icon> <el-icon><Check /></el-icon>
确定 确定
@@ -223,11 +269,13 @@
<script setup lang="ts"> <script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, onMounted, reactive, ref } from 'vue' import { computed, nextTick, onBeforeUnmount, onMounted, reactive, ref } from 'vue'
import { Check, Close, Plus } from '@element-plus/icons-vue' import { Check, Close, Delete, Edit, Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus' import { ElMessage, ElMessageBox } from 'element-plus'
import { import {
fetchCreateOaReceiveAccount, fetchCreateOaReceiveAccount,
fetchOaReceiveAccountOptions fetchDeleteOaReceiveAccount,
fetchOaReceiveAccountOptions,
fetchUpdateOaReceiveAccount
} from '@/api/oaApproval' } from '@/api/oaApproval'
import { import {
ACCOUNT_TYPE_LABEL, ACCOUNT_TYPE_LABEL,
@@ -253,6 +301,7 @@
}>() }>()
type AccountOpt = { id: string; label: string } type AccountOpt = { id: string; label: string }
type FormMode = 'create' | 'edit'
const snapshotMap = ref(new Map<string, ReceiveAccountSnapshot>()) const snapshotMap = ref(new Map<string, ReceiveAccountSnapshot>())
const accountOptions = ref<AccountOpt[]>([]) const accountOptions = ref<AccountOpt[]>([])
@@ -263,10 +312,12 @@
const selectRef = ref<{ blur?: () => void } | null>(null) const selectRef = ref<{ blur?: () => void } | null>(null)
let mql: MediaQueryList | null = null let mql: MediaQueryList | null = null
const createVisible = ref(false) const formVisible = ref(false)
const createLoading = ref(false) const formLoading = ref(false)
const createFormRef = ref() const formMode = ref<FormMode>('create')
const createForm = reactive({ const editingId = ref('')
const formRef = ref()
const formModel = reactive({
accountType: 'alipay' as ReceiveAccountType, accountType: 'alipay' as ReceiveAccountType,
accountName: '', accountName: '',
accountNo: '', accountNo: '',
@@ -277,8 +328,12 @@
remark: '' remark: ''
}) })
const formTitle = computed(() =>
formMode.value === 'edit' ? '编辑收款账户' : '新增收款账户'
)
const requireWhenBank = (_rule: any, value: string, callback: (e?: Error) => void) => { const requireWhenBank = (_rule: any, value: string, callback: (e?: Error) => void) => {
if (createForm.accountType === 'alipay') { if (formModel.accountType === 'alipay') {
callback() callback()
return return
} }
@@ -289,7 +344,7 @@
callback() callback()
} }
const createRules = computed(() => ({ const formRules = computed(() => ({
accountType: [{ required: true, message: '请选择账户类型', trigger: 'change' }], accountType: [{ required: true, message: '请选择账户类型', trigger: 'change' }],
accountName: [{ required: true, message: '请输入户名', trigger: 'blur' }], accountName: [{ required: true, message: '请输入户名', trigger: 'blur' }],
accountNo: [{ required: true, message: '请输入账号', trigger: 'blur' }], accountNo: [{ required: true, message: '请输入账号', trigger: 'blur' }],
@@ -358,88 +413,159 @@
drawerVisible.value = false drawerVisible.value = false
} }
function clearCreateBankFields() { function clearBankFields() {
createForm.bankName = '' formModel.bankName = ''
createForm.bankProvince = '' formModel.bankProvince = ''
createForm.bankCity = '' formModel.bankCity = ''
createForm.bankBranch = '' formModel.bankBranch = ''
} }
function resetCreateForm() { function resetFormModel() {
createForm.accountType = 'alipay' formModel.accountType = 'alipay'
createForm.accountName = '' formModel.accountName = ''
createForm.accountNo = '' formModel.accountNo = ''
clearCreateBankFields() clearBankFields()
createForm.remark = '' formModel.remark = ''
} }
function onCreateTypeChange() { function fillFormFromSnap(snap: ReceiveAccountSnapshot) {
if (createForm.accountType === 'alipay') clearCreateBankFields() formModel.accountType = snap.accountType
createFormRef.value?.clearValidate?.() formModel.accountName = snap.accountName
formModel.accountNo = snap.accountNo
formModel.bankName = snap.bankName
formModel.bankProvince = snap.bankProvince
formModel.bankCity = snap.bankCity
formModel.bankBranch = snap.bankBranch
formModel.remark = snap.remark
if (formModel.accountType === 'alipay') clearBankFields()
} }
function openCreateDialog() { function onFormTypeChange() {
selectRef.value?.blur?.() if (formModel.accountType === 'alipay') clearBankFields()
resetCreateForm() formRef.value?.clearValidate?.()
createVisible.value = true
nextTick(() => createFormRef.value?.clearValidate?.())
} }
async function submitCreate() { function buildPayload() {
try {
await createFormRef.value?.validate?.()
} catch {
ElMessageBox.alert('请完善必填项后再提交', '提示', { type: 'warning' })
return
}
createLoading.value = true
try {
const payload: Record<string, unknown> = { const payload: Record<string, unknown> = {
accountType: createForm.accountType, accountType: formModel.accountType,
accountName: createForm.accountName.trim(), accountName: formModel.accountName.trim(),
accountNo: createForm.accountNo.trim(), accountNo: formModel.accountNo.trim(),
remark: createForm.remark?.trim() || undefined remark: formModel.remark?.trim() || undefined
} }
if (createForm.accountType === 'alipay') { if (formModel.accountType === 'alipay') {
payload.bankName = '' payload.bankName = ''
payload.bankProvince = '' payload.bankProvince = ''
payload.bankCity = '' payload.bankCity = ''
payload.bankBranch = '' payload.bankBranch = ''
} else { } else {
payload.bankName = createForm.bankName.trim() payload.bankName = formModel.bankName.trim()
payload.bankProvince = createForm.bankProvince.trim() payload.bankProvince = formModel.bankProvince.trim()
payload.bankCity = createForm.bankCity.trim() payload.bankCity = formModel.bankCity.trim()
payload.bankBranch = createForm.bankBranch.trim() payload.bankBranch = formModel.bankBranch.trim()
} }
const created = await fetchCreateOaReceiveAccount(payload) return payload
const snap = snapshotFromRow(created)
if (!snap.id) {
ElMessage.error('创建成功但未返回账户 ID')
return
} }
await loadOptions()
// 确保新账户在 map 中(options 可能短暂未刷新) function upsertLocalSnap(snap: ReceiveAccountSnapshot) {
if (!snapshotMap.value.has(snap.id)) { if (!snap.id) return
const map = new Map(snapshotMap.value) const map = new Map(snapshotMap.value)
map.set(snap.id, snap) map.set(snap.id, snap)
snapshotMap.value = map snapshotMap.value = map
if (!accountOptions.value.some((x) => x.id === snap.id)) { const label = optionLabelFromRow(snap)
accountOptions.value = [ const idx = accountOptions.value.findIndex((x) => x.id === snap.id)
...accountOptions.value, if (idx >= 0) {
{ id: snap.id, label: optionLabelFromRow(snap) } const next = [...accountOptions.value]
] next[idx] = { id: snap.id, label }
accountOptions.value = next
} else {
accountOptions.value = [...accountOptions.value, { id: snap.id, label }]
} }
} }
function openCreateDialog() {
selectRef.value?.blur?.()
formMode.value = 'create'
editingId.value = ''
resetFormModel()
formVisible.value = true
nextTick(() => formRef.value?.clearValidate?.())
}
function openEditDialog(id: string) {
const tid = String(id || '').trim()
const snap = snapshotMap.value.get(tid)
if (!snap) {
ElMessage.error('账户不存在或已删除')
return
}
selectRef.value?.blur?.()
formMode.value = 'edit'
editingId.value = tid
fillFormFromSnap(snap)
formVisible.value = true
nextTick(() => formRef.value?.clearValidate?.())
}
async function submitForm() {
try {
await formRef.value?.validate?.()
} catch {
ElMessageBox.alert('请完善必填项后再提交', '提示', { type: 'warning' })
return
}
formLoading.value = true
try {
const payload = buildPayload()
let row: any
if (formMode.value === 'edit' && editingId.value) {
row = await fetchUpdateOaReceiveAccount(editingId.value, payload)
} else {
row = await fetchCreateOaReceiveAccount(payload)
}
const snap = snapshotFromRow(row)
if (!snap.id) {
ElMessage.error(formMode.value === 'edit' ? '更新成功但未返回账户 ID' : '创建成功但未返回账户 ID')
return
}
await loadOptions()
upsertLocalSnap(snap)
if (formMode.value === 'edit') {
if (selectModel.value.includes(snap.id)) {
emitFromIds(selectModel.value)
}
} else {
const nextIds = [...selectModel.value] const nextIds = [...selectModel.value]
if (!nextIds.includes(snap.id)) nextIds.push(snap.id) if (!nextIds.includes(snap.id)) nextIds.push(snap.id)
emitFromIds(nextIds) emitFromIds(nextIds)
if (drawerVisible.value && !pendingIds.value.includes(snap.id)) { if (drawerVisible.value && !pendingIds.value.includes(snap.id)) {
pendingIds.value = [...pendingIds.value, snap.id] pendingIds.value = [...pendingIds.value, snap.id]
} }
createVisible.value = false
} finally {
createLoading.value = false
} }
formVisible.value = false
} finally {
formLoading.value = false
}
}
async function confirmDelete(id: string) {
const tid = String(id || '').trim()
const snap = snapshotMap.value.get(tid)
const name = snap?.accountName || tid
try {
await ElMessageBox.confirm(
`确定删除收款账户「${name}」吗?删除后不可再选;已提交单据中的账户快照仍保留。`,
'删除收款账户',
{ type: 'warning', confirmButtonText: '删除', cancelButtonText: '取消' }
)
} catch {
return
}
selectRef.value?.blur?.()
await fetchDeleteOaReceiveAccount(tid)
await loadOptions()
const nextSelected = selectModel.value.filter((x) => x !== tid)
emitFromIds(nextSelected)
pendingIds.value = pendingIds.value.filter((x) => x !== tid)
} }
async function loadOptions() { async function loadOptions() {
@@ -512,6 +638,53 @@
min-height: 40px; min-height: 40px;
} }
.oa-receive-account-select__option {
display: flex;
gap: 8px;
align-items: center;
justify-content: space-between;
width: 100%;
min-width: 0;
}
.oa-receive-account-select__option-label {
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.oa-receive-account-select__option-actions,
.oa-receive-account-select__row-actions {
display: inline-flex;
flex-shrink: 0;
gap: 4px;
align-items: center;
}
.oa-receive-account-select__icon-btn {
display: inline-flex;
align-items: center;
justify-content: center;
width: 28px;
height: 28px;
padding: 0;
border: 0;
border-radius: 6px;
cursor: pointer;
}
.oa-receive-account-select__icon-btn.is-edit {
background: var(--mint-primary-bg, #ecfdf5);
color: var(--mint-primary-dark, #059669);
}
.oa-receive-account-select__icon-btn.is-delete {
background: #fef2f2;
color: #dc2626;
}
.oa-receive-account-select__add-footer { .oa-receive-account-select__add-footer {
padding: 4px 8px 8px; padding: 4px 8px 8px;
border-top: 1px solid var(--mint-border, #d9e8e2); border-top: 1px solid var(--mint-border, #d9e8e2);
@@ -597,6 +770,14 @@
align-items: center; align-items: center;
min-height: 44px; min-height: 44px;
padding: 6px 4px; padding: 6px 4px;
}
.oa-receive-account-select__row-main {
display: flex;
flex: 1;
gap: 8px;
align-items: center;
min-width: 0;
cursor: pointer; cursor: pointer;
} }
@@ -630,5 +811,10 @@
.oa-receive-account-select__trigger { .oa-receive-account-select__trigger {
min-height: 44px; min-height: 44px;
} }
.oa-receive-account-select__icon-btn {
width: 36px;
height: 36px;
}
} }
</style> </style>
-53
View File
@@ -1335,59 +1335,6 @@ export const sqxpAdminRoutes: AppRouteRecord[] = [
] ]
}, },
// ═══════════════════════════════════════════════════════════════════════════
// 3b. 实验室样本处理数据 (menu:lab-sample-processing)
// ═══════════════════════════════════════════════════════════════════════════
{
id: 'TOP0000000000000000000000000000L1',
name: 'LabSampleProcessing',
path: '/lab-sample-processing',
component: '/index/index',
meta: {
title: '实验室样本处理数据',
icon: 'ri:test-tube-line',
keepAlive: false,
isTopMenu: true,
menuCode: 'menu:lab-sample-processing',
roles: ['admin']
},
children: [
{
id: 'LAB00000000000000000000000000001',
name: 'LabSampleProcessingHsc',
path: 'hsc',
component: '/lab-sample-processing/hsc/index',
meta: {
title: '造血干细胞数据',
keepAlive: true,
menuCode: 'lab:sample-processing:list'
}
},
{
id: 'LAB00000000000000000000000000002',
name: 'LabSampleProcessingUbmc',
path: 'ubmc',
component: '/lab-sample-processing/ubmc/index',
meta: {
title: '单个核数据',
keepAlive: true,
menuCode: 'lab:sample-processing:list'
}
},
{
id: 'LAB00000000000000000000000000003',
name: 'LabSampleProcessingMsc',
path: 'msc',
component: '/lab-sample-processing/msc/index',
meta: {
title: '脐带间充质干细胞数据',
keepAlive: true,
menuCode: 'lab:sample-processing:list'
}
}
]
},
// ═══════════════════════════════════════════════════════════════════════════ // ═══════════════════════════════════════════════════════════════════════════
// 4. 运营支撑 (menu:operations) // 4. 运营支撑 (menu:operations)
// 二级菜单:系统基础信息、运营支撑 // 二级菜单:系统基础信息、运营支撑
@@ -0,0 +1,16 @@
import { describe, it } from 'node:test'
import assert from 'node:assert/strict'
import { hasOaCommentDraft } from './oa-comment-draft.ts'
describe('hasOaCommentDraft', () => {
it('treats blank content without mentions/files as empty', () => {
assert.equal(hasOaCommentDraft({}), false)
assert.equal(hasOaCommentDraft({ content: ' ', mentionCount: 0, attachmentCount: 0 }), false)
})
it('detects text, mentions and attachments', () => {
assert.equal(hasOaCommentDraft({ content: '@test' }), true)
assert.equal(hasOaCommentDraft({ mentionCount: 1 }), true)
assert.equal(hasOaCommentDraft({ attachmentCount: 2 }), true)
})
})
+12
View File
@@ -0,0 +1,12 @@
/** 评论区是否有未发送草稿(文字 / @ / 附件) */
export function hasOaCommentDraft(input: {
content?: string | null
mentionCount?: number
attachmentCount?: number
}): boolean {
return !!(
String(input.content || '').trim() ||
(input.mentionCount || 0) > 0 ||
(input.attachmentCount || 0) > 0
)
}
@@ -127,7 +127,7 @@ const inboundGroupedFields: CardMetaField[] = [
{ label: '母亲姓名', getValue: (row) => row.motherName || '—', visible: isInboundUserInfoRow }, { label: '母亲姓名', getValue: (row) => row.motherName || '—', visible: isInboundUserInfoRow },
{ label: '新生儿姓名', getValue: (row) => row.newbornName || '—', visible: isInboundUserInfoRow }, { label: '新生儿姓名', getValue: (row) => row.newbornName || '—', visible: isInboundUserInfoRow },
inboundProtocolStatusField, inboundProtocolStatusField,
{ label: '质检对象', getValue: formatQcTarget, colSpan: 2 }, { label: '质检对象', getValue: formatQcTarget },
{ {
label: '关联生产工单', label: '关联生产工单',
getValue: (row) => row.productionWorkOrderNo || '—', getValue: (row) => row.productionWorkOrderNo || '—',
@@ -139,6 +139,11 @@ const inboundGroupedFields: CardMetaField[] = [
getValue: (row) => row.sampleTypeName || '—', getValue: (row) => row.sampleTypeName || '—',
visible: isInboundUserInfoRow visible: isInboundUserInfoRow
}, },
{
label: '母血采集时间',
getValue: (row) => formatDisplayOrDash(row.maternalBloodCollectTime),
visible: isInboundUserInfoRow
},
...commonTailFields ...commonTailFields
] ]
@@ -197,6 +202,7 @@ function buildCellStorageGroupContext(row: QcWorkOrder): string[] {
if (row.newbornName) parts.push(`新生儿 ${row.newbornName}`) if (row.newbornName) parts.push(`新生儿 ${row.newbornName}`)
if (row.sampleTypeName) parts.push(row.sampleTypeName) if (row.sampleTypeName) parts.push(row.sampleTypeName)
if (row.receptionTime) parts.push(`接收 ${row.receptionTime}`) if (row.receptionTime) parts.push(`接收 ${row.receptionTime}`)
parts.push(`母血采集 ${formatDisplayOrDash(row.maternalBloodCollectTime)}`)
if (row.handlerName) parts.push(row.handlerName) if (row.handlerName) parts.push(row.handlerName)
return parts return parts
} }
@@ -207,6 +213,7 @@ function buildDonationGroupContext(row: QcWorkOrder): string[] {
if (row.newbornName) parts.push(`新生儿 ${row.newbornName}`) if (row.newbornName) parts.push(`新生儿 ${row.newbornName}`)
if (row.sampleTypeName) parts.push(row.sampleTypeName) if (row.sampleTypeName) parts.push(row.sampleTypeName)
if (row.receptionTime) parts.push(`接收 ${row.receptionTime}`) if (row.receptionTime) parts.push(`接收 ${row.receptionTime}`)
parts.push(`母血采集 ${formatDisplayOrDash(row.maternalBloodCollectTime)}`)
if (row.handlerName) parts.push(row.handlerName) if (row.handlerName) parts.push(row.handlerName)
return parts return parts
} }
@@ -99,6 +99,7 @@
/> />
<OaCommentPanel <OaCommentPanel
v-if="detail?.id" v-if="detail?.id"
ref="commentPanelRef"
:instance-id="detail.id" :instance-id="detail.id"
:instance-status="detail.status || ''" :instance-status="detail.status || ''"
@refresh="load" @refresh="load"
@@ -236,6 +237,9 @@
const userStore = useUserStore() const userStore = useUserStore()
const loading = ref(false) const loading = ref(false)
const acting = ref(false) const acting = ref(false)
const commentPanelRef = ref<{ flushDraft?: (opts?: { quiet?: boolean }) => Promise<boolean> } | null>(
null
)
const detail = ref<any>(null) const detail = ref<any>(null)
const viewFormData = ref<Record<string, any>>({}) const viewFormData = ref<Record<string, any>>({})
const viewRule = ref<any[]>([]) const viewRule = ref<any[]>([])
@@ -392,9 +396,17 @@
} }
} }
/** 同意/拒绝/打回前先发送评论区未提交草稿 */
async function flushPendingComment(): Promise<boolean> {
const flush = commentPanelRef.value?.flushDraft
if (!flush) return true
return await flush()
}
async function act(kind: 'approve' | 'reject') { async function act(kind: 'approve' | 'reject') {
const task = myPendingTask.value const task = myPendingTask.value
if (!task) return if (!task) return
if (!(await flushPendingComment())) return
let comment = '' let comment = ''
try { try {
const res = await ElMessageBox.prompt( const res = await ElMessageBox.prompt(
@@ -436,6 +448,7 @@
async function doReturn() { async function doReturn() {
const task = myPendingTask.value const task = myPendingTask.value
if (!task) return if (!task) return
if (!(await flushPendingComment())) return
let comment = '' let comment = ''
try { try {
const res = await ElMessageBox.prompt('请填写打回意见(必填)', '打回', { const res = await ElMessageBox.prompt('请填写打回意见(必填)', '打回', {