Compare commits
17
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e4b62d6406 | ||
|
|
808f7dcf03 | ||
|
|
50679fa75e | ||
|
|
2124ce9208 | ||
|
|
e7b3876db6 | ||
|
|
c0aba421da | ||
|
|
2aecb69cc4 | ||
|
|
2878c6889d | ||
|
|
4aee2b1fe5 | ||
|
|
5698a9dfc4 | ||
|
|
77d45d0bc5 | ||
|
|
dc0f8541c4 | ||
|
|
4fd6ef4be5 | ||
|
|
b3c191ee99 | ||
|
|
bbef46b645 | ||
|
|
5fe1193a2c | ||
|
|
58b252ce6b |
No files matched your search
@@ -46,6 +46,7 @@ from app.api.customer_service_dict import router as customer_service_dict_router
|
|||||||
from app.api.sample_cert_insurance import router as sample_cert_insurance_router
|
from app.api.sample_cert_insurance import router as sample_cert_insurance_router
|
||||||
from app.api.sample_code_correction import router as sample_code_correction_router
|
from app.api.sample_code_correction import router as sample_code_correction_router
|
||||||
from app.api.lab_sample_process import router as lab_sample_process_router
|
from app.api.lab_sample_process import router as lab_sample_process_router
|
||||||
|
from app.api.lab_sample_processing import router as lab_sample_processing_router
|
||||||
|
|
||||||
from app.api.project_management import router as project_management_router
|
from app.api.project_management import router as project_management_router
|
||||||
|
|
||||||
@@ -98,4 +99,5 @@ __all__ = [
|
|||||||
"customer_service_dict_router",
|
"customer_service_dict_router",
|
||||||
"sample_cert_insurance_router",
|
"sample_cert_insurance_router",
|
||||||
"sample_code_correction_router",
|
"sample_code_correction_router",
|
||||||
|
"lab_sample_processing_router",
|
||||||
]
|
]
|
||||||
@@ -6,7 +6,7 @@ from pydantic import BaseModel, ConfigDict, Field
|
|||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
from app.core.database import get_db
|
from app.core.database import get_db
|
||||||
from app.core.menu_guard import require_menu_code
|
from app.core.menu_guard import require_any_menu_code
|
||||||
from app.core.response import error_response, success_response
|
from app.core.response import error_response, success_response
|
||||||
from app.crud import lab_sample_process as svc
|
from app.crud import lab_sample_process as svc
|
||||||
from app.models.models import SysUser
|
from app.models.models import SysUser
|
||||||
@@ -14,8 +14,17 @@ from app.services import lab_sample_process as ledger
|
|||||||
|
|
||||||
router = APIRouter(prefix="/web/admin", tags=["质检管理"])
|
router = APIRouter(prefix="/web/admin", tags=["质检管理"])
|
||||||
|
|
||||||
LIST_MENU = "biz:labSampleProcess:list"
|
# 市场/生产/质检三处菜单权限码不同,接口按并集鉴权
|
||||||
SUPPLEMENT_MENU = "biz:labSampleProcess:supplement"
|
LIST_MENU_CODES = (
|
||||||
|
"biz:labSampleProcess:list",
|
||||||
|
"production:labSampleProcess:list",
|
||||||
|
"cellStorage:labSampleProcess:list",
|
||||||
|
)
|
||||||
|
SUPPLEMENT_MENU_CODES = (
|
||||||
|
"biz:labSampleProcess:supplement",
|
||||||
|
"production:labSampleProcess:supplement",
|
||||||
|
"cellStorage:labSampleProcess:supplement",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def _tenant_no(db: Session, user: dict) -> str:
|
def _tenant_no(db: Session, user: dict) -> str:
|
||||||
@@ -59,7 +68,7 @@ def list_lab_sample_process(
|
|||||||
createTimeStart: Optional[str] = Query(None),
|
createTimeStart: Optional[str] = Query(None),
|
||||||
createTimeEnd: Optional[str] = Query(None),
|
createTimeEnd: Optional[str] = Query(None),
|
||||||
db: Session = Depends(get_db),
|
db: Session = Depends(get_db),
|
||||||
user=Depends(require_menu_code(LIST_MENU)),
|
user=Depends(require_any_menu_code(*LIST_MENU_CODES)),
|
||||||
):
|
):
|
||||||
try:
|
try:
|
||||||
tenant_no = _tenant_no(db, user)
|
tenant_no = _tenant_no(db, user)
|
||||||
@@ -98,7 +107,7 @@ def list_lab_sample_process(
|
|||||||
def get_supplement(
|
def get_supplement(
|
||||||
labStorageCode: str = Query(...),
|
labStorageCode: str = Query(...),
|
||||||
db: Session = Depends(get_db),
|
db: Session = Depends(get_db),
|
||||||
user=Depends(require_menu_code(LIST_MENU)),
|
user=Depends(require_any_menu_code(*LIST_MENU_CODES)),
|
||||||
):
|
):
|
||||||
try:
|
try:
|
||||||
tenant_no = _tenant_no(db, user)
|
tenant_no = _tenant_no(db, user)
|
||||||
@@ -114,7 +123,7 @@ def get_supplement(
|
|||||||
def save_supplement(
|
def save_supplement(
|
||||||
body: SupplementBody,
|
body: SupplementBody,
|
||||||
db: Session = Depends(get_db),
|
db: Session = Depends(get_db),
|
||||||
user=Depends(require_menu_code(SUPPLEMENT_MENU)),
|
user=Depends(require_any_menu_code(*SUPPLEMENT_MENU_CODES)),
|
||||||
):
|
):
|
||||||
try:
|
try:
|
||||||
tenant_no = _tenant_no(db, user)
|
tenant_no = _tenant_no(db, user)
|
||||||
|
|||||||
@@ -0,0 +1,193 @@
|
|||||||
|
"""实验室样本处理数据 API"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import csv
|
||||||
|
import io
|
||||||
|
from typing import Any, Dict, Optional
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, Query
|
||||||
|
from fastapi.responses import StreamingResponse
|
||||||
|
from pydantic import BaseModel, ConfigDict, Field
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from app.core.database import get_db
|
||||||
|
from app.core.menu_guard import require_strict_any_menu_code
|
||||||
|
from app.core.response import error_response, success_response
|
||||||
|
from app.models.models import SysUser
|
||||||
|
from app.services import lab_sample_processing as svc
|
||||||
|
from app.services.lab_sample_processing_fields import (
|
||||||
|
DATASETS,
|
||||||
|
DATASET_LABELS,
|
||||||
|
PERM_LIST,
|
||||||
|
PERM_MANAGER,
|
||||||
|
PERM_MARKET_EDIT,
|
||||||
|
PERM_PRODUCTION_EDIT,
|
||||||
|
PERM_QC_EDIT,
|
||||||
|
schema_payload,
|
||||||
|
)
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/web/admin/lab-sample-processing", tags=["实验室样本处理数据"])
|
||||||
|
|
||||||
|
# 列表/导出:有列表、主管或任一部门编辑权即可查看全部字段
|
||||||
|
READ_MENUS = (
|
||||||
|
PERM_LIST,
|
||||||
|
PERM_MANAGER,
|
||||||
|
PERM_MARKET_EDIT,
|
||||||
|
PERM_PRODUCTION_EDIT,
|
||||||
|
PERM_QC_EDIT,
|
||||||
|
)
|
||||||
|
# 更新:至少要有主管或某一部门编辑权(字段级 ACL 在服务内再收紧)
|
||||||
|
WRITE_MENUS = (
|
||||||
|
PERM_MANAGER,
|
||||||
|
PERM_MARKET_EDIT,
|
||||||
|
PERM_PRODUCTION_EDIT,
|
||||||
|
PERM_QC_EDIT,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _tenant_no(db: Session, user: dict) -> str:
|
||||||
|
user_id = user.get("user_id")
|
||||||
|
if not user_id:
|
||||||
|
raise PermissionError("用户身份信息缺失")
|
||||||
|
row = db.query(SysUser).filter(SysUser.id == user_id, SysUser.del_flag == 0).first()
|
||||||
|
if not row or not row.tenant_no:
|
||||||
|
raise PermissionError("用户租户信息缺失")
|
||||||
|
return row.tenant_no
|
||||||
|
|
||||||
|
|
||||||
|
def _ensure_dataset(dataset: str) -> Optional[str]:
|
||||||
|
ds = (dataset or "").strip().lower()
|
||||||
|
return ds if ds in DATASETS else None
|
||||||
|
|
||||||
|
|
||||||
|
class UpdateBody(BaseModel):
|
||||||
|
model_config = ConfigDict(populate_by_name=True)
|
||||||
|
payload: Dict[str, Any] = Field(default_factory=dict)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/meta/{dataset}")
|
||||||
|
async def get_meta(
|
||||||
|
dataset: str,
|
||||||
|
user: dict = Depends(require_strict_any_menu_code(*READ_MENUS)),
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
):
|
||||||
|
ds = _ensure_dataset(dataset)
|
||||||
|
if not ds:
|
||||||
|
return error_response(400, "未知数据集")
|
||||||
|
acl = svc.user_acl(db, user)
|
||||||
|
return success_response(
|
||||||
|
{
|
||||||
|
"dataset": ds,
|
||||||
|
"label": DATASET_LABELS.get(ds),
|
||||||
|
"fields": schema_payload(ds),
|
||||||
|
"acl": acl,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{dataset}/list")
|
||||||
|
async def list_dataset(
|
||||||
|
dataset: str,
|
||||||
|
keyword: Optional[str] = Query(None),
|
||||||
|
dateFrom: Optional[str] = Query(None),
|
||||||
|
dateTo: Optional[str] = Query(None),
|
||||||
|
page: int = Query(1, ge=1),
|
||||||
|
pageSize: int = Query(20, ge=1, le=200),
|
||||||
|
user: dict = Depends(require_strict_any_menu_code(*READ_MENUS)),
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
):
|
||||||
|
ds = _ensure_dataset(dataset)
|
||||||
|
if not ds:
|
||||||
|
return error_response(400, "未知数据集")
|
||||||
|
tenant_no = _tenant_no(db, user)
|
||||||
|
rows, total = svc.list_rows(
|
||||||
|
db,
|
||||||
|
tenant_no=tenant_no,
|
||||||
|
dataset=ds,
|
||||||
|
keyword=keyword,
|
||||||
|
date_from=dateFrom,
|
||||||
|
date_to=dateTo,
|
||||||
|
page=page,
|
||||||
|
page_size=pageSize,
|
||||||
|
)
|
||||||
|
acl = svc.user_acl(db, user)
|
||||||
|
return success_response(
|
||||||
|
{
|
||||||
|
"list": rows,
|
||||||
|
"total": total,
|
||||||
|
"page": page,
|
||||||
|
"pageSize": pageSize,
|
||||||
|
"fields": schema_payload(ds),
|
||||||
|
"acl": acl,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/{dataset}/{sample_code}")
|
||||||
|
async def update_dataset_row(
|
||||||
|
dataset: str,
|
||||||
|
sample_code: str,
|
||||||
|
body: UpdateBody,
|
||||||
|
user: dict = Depends(require_strict_any_menu_code(*WRITE_MENUS)),
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
):
|
||||||
|
ds = _ensure_dataset(dataset)
|
||||||
|
if not ds:
|
||||||
|
return error_response(400, "未知数据集")
|
||||||
|
tenant_no = _tenant_no(db, user)
|
||||||
|
acl = svc.user_acl(db, user)
|
||||||
|
editable = set(acl.get("editableDepts") or [])
|
||||||
|
if not editable:
|
||||||
|
return error_response(403, "无编辑权限")
|
||||||
|
try:
|
||||||
|
row = svc.update_row(
|
||||||
|
db,
|
||||||
|
tenant_no=tenant_no,
|
||||||
|
dataset=ds,
|
||||||
|
sample_code=sample_code,
|
||||||
|
payload=body.payload or {},
|
||||||
|
editable_depts=editable,
|
||||||
|
operator_id=str(user.get("user_id") or ""),
|
||||||
|
)
|
||||||
|
except PermissionError as exc:
|
||||||
|
return error_response(403, str(exc))
|
||||||
|
except LookupError as exc:
|
||||||
|
return error_response(404, str(exc))
|
||||||
|
except ValueError as exc:
|
||||||
|
return error_response(400, str(exc))
|
||||||
|
return success_response(row)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{dataset}/export")
|
||||||
|
async def export_dataset(
|
||||||
|
dataset: str,
|
||||||
|
keyword: Optional[str] = Query(None),
|
||||||
|
dateFrom: Optional[str] = Query(None),
|
||||||
|
dateTo: Optional[str] = Query(None),
|
||||||
|
user: dict = Depends(require_strict_any_menu_code(*READ_MENUS)),
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
):
|
||||||
|
ds = _ensure_dataset(dataset)
|
||||||
|
if not ds:
|
||||||
|
return error_response(400, "未知数据集")
|
||||||
|
tenant_no = _tenant_no(db, user)
|
||||||
|
headers, body = svc.export_rows(
|
||||||
|
db,
|
||||||
|
tenant_no=tenant_no,
|
||||||
|
dataset=ds,
|
||||||
|
keyword=keyword,
|
||||||
|
date_from=dateFrom,
|
||||||
|
date_to=dateTo,
|
||||||
|
)
|
||||||
|
buf = io.StringIO()
|
||||||
|
writer = csv.writer(buf)
|
||||||
|
writer.writerow(headers)
|
||||||
|
for row in body:
|
||||||
|
writer.writerow(["" if v is None else v for v in row])
|
||||||
|
raw = ("\ufeff" + buf.getvalue()).encode("utf-8")
|
||||||
|
filename = f"lab-sample-{ds}.csv"
|
||||||
|
return StreamingResponse(
|
||||||
|
io.BytesIO(raw),
|
||||||
|
media_type="text/csv; charset=utf-8",
|
||||||
|
headers={"Content-Disposition": f'attachment; filename="{filename}"'},
|
||||||
|
)
|
||||||
@@ -179,6 +179,17 @@ def upsert_supplement(
|
|||||||
del_flag=0,
|
del_flag=0,
|
||||||
)
|
)
|
||||||
db.add(row)
|
db.add(row)
|
||||||
|
# 同步到新模块补充表/生产接收,保证实验室样本处理数据联动
|
||||||
|
from app.services.lab_sample_processing import sync_legacy_supplement_to_processing
|
||||||
|
|
||||||
|
sync_legacy_supplement_to_processing(
|
||||||
|
db,
|
||||||
|
tenant_no=tenant_no,
|
||||||
|
lab_storage_code=code,
|
||||||
|
sample_type_name=type_name,
|
||||||
|
payload=clean_payload,
|
||||||
|
operator_id=user_id,
|
||||||
|
)
|
||||||
db.commit()
|
db.commit()
|
||||||
db.refresh(row)
|
db.refresh(row)
|
||||||
return get_supplement(db, tenant_no=tenant_no, lab_storage_code=code) or {}
|
return get_supplement(db, tenant_no=tenant_no, lab_storage_code=code) or {}
|
||||||
|
|||||||
+2
-1
@@ -13,7 +13,7 @@ from app.core.database import SessionLocal
|
|||||||
from app.core.api_request_log_middleware import ApiRequestLogMiddleware
|
from app.core.api_request_log_middleware import ApiRequestLogMiddleware
|
||||||
from app.core.api_crypto_middleware import ApiCryptoMiddleware
|
from app.core.api_crypto_middleware import ApiCryptoMiddleware
|
||||||
from app.models import models # noqa: F401
|
from app.models import models # noqa: F401
|
||||||
from app.api import public_router, menu_router, admin_router, workflow_router, basic_info_router, collection_protocol_router, protocol_sample_payment_router, protocol_refund_record_router, presign_order_router, sample_freight_router, leave_router, operations_router, ethnic_router, sample_reception_router, sample_production_reception_router, qc_router, research_donation_router, production_router, pilot_service_router, insurance_company_router, material_router, storage_release_review_router, sample_sms_notification_router, storage_entry_sms_notification_router, qc_sms_notification_router, protocol_sample_collection_router, research_donation_sample_collection_router, pilot_application_router, pilot_checkup_router, pilot_delivery_router, pilot_infusion_confirm_router, pilot_infusion_schedule_mgmt_router, outbound_release_review_router, clinical_payment_router, env_detect_router, cleanroom_garment_router, market_router, pre_transit_sample_router, oa_approval_router, mini_auth_router, mini_menu_router, market_mobile_router, sample_storage_cert_qc_router, customer_service_dict_router, sample_cert_insurance_router, sample_code_correction_router, lab_sample_process_router, project_management_router
|
from app.api import public_router, menu_router, admin_router, workflow_router, basic_info_router, collection_protocol_router, protocol_sample_payment_router, protocol_refund_record_router, presign_order_router, sample_freight_router, leave_router, operations_router, ethnic_router, sample_reception_router, sample_production_reception_router, qc_router, research_donation_router, production_router, pilot_service_router, insurance_company_router, material_router, storage_release_review_router, sample_sms_notification_router, storage_entry_sms_notification_router, qc_sms_notification_router, protocol_sample_collection_router, research_donation_sample_collection_router, pilot_application_router, pilot_checkup_router, pilot_delivery_router, pilot_infusion_confirm_router, pilot_infusion_schedule_mgmt_router, outbound_release_review_router, clinical_payment_router, env_detect_router, cleanroom_garment_router, market_router, pre_transit_sample_router, oa_approval_router, mini_auth_router, mini_menu_router, market_mobile_router, sample_storage_cert_qc_router, customer_service_dict_router, sample_cert_insurance_router, sample_code_correction_router, lab_sample_process_router, lab_sample_processing_router, project_management_router
|
||||||
|
|
||||||
|
|
||||||
@asynccontextmanager
|
@asynccontextmanager
|
||||||
@@ -158,6 +158,7 @@ app.include_router(customer_service_dict_router, prefix=settings.API_V1_PREFIX)
|
|||||||
app.include_router(sample_cert_insurance_router, prefix=settings.API_V1_PREFIX)
|
app.include_router(sample_cert_insurance_router, prefix=settings.API_V1_PREFIX)
|
||||||
app.include_router(sample_code_correction_router, prefix=settings.API_V1_PREFIX)
|
app.include_router(sample_code_correction_router, prefix=settings.API_V1_PREFIX)
|
||||||
app.include_router(lab_sample_process_router, prefix=settings.API_V1_PREFIX)
|
app.include_router(lab_sample_process_router, prefix=settings.API_V1_PREFIX)
|
||||||
|
app.include_router(lab_sample_processing_router, prefix=settings.API_V1_PREFIX)
|
||||||
app.include_router(project_management_router, prefix=settings.API_V1_PREFIX)
|
app.include_router(project_management_router, prefix=settings.API_V1_PREFIX)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1969,6 +1969,26 @@ class BizSampleReception(Base):
|
|||||||
del_flag = Column(SmallInteger, nullable=False, default=0, comment="删除标记")
|
del_flag = Column(SmallInteger, nullable=False, default=0, comment="删除标记")
|
||||||
|
|
||||||
|
|
||||||
|
class BizLabSampleProcessingExtra(Base):
|
||||||
|
"""实验室样本处理数据补充字段 biz_lab_sample_processing_extra"""
|
||||||
|
|
||||||
|
__tablename__ = "biz_lab_sample_processing_extra"
|
||||||
|
|
||||||
|
id = Column(String(64), primary_key=True, comment="主键ID")
|
||||||
|
dataset = Column(String(16), nullable=False, comment="hsc|ubmc|msc")
|
||||||
|
sample_code = Column(String(32), nullable=False, comment="样本编码")
|
||||||
|
payload_json = Column(Text, nullable=True, comment="补充字段 JSON")
|
||||||
|
tenant_no = Column(String(64), nullable=False, default="zkxw", comment="租户编号")
|
||||||
|
order_num = Column(Integer, nullable=True, comment="排序号")
|
||||||
|
remark = Column(String(512), nullable=True, comment="备注")
|
||||||
|
create_by = Column(String(64), nullable=True, comment="创建人id")
|
||||||
|
create_dept_id = Column(String(64), nullable=False, default="", comment="创建人部门ID")
|
||||||
|
create_time = Column(DateTime, nullable=False, default=datetime.now, comment="创建时间")
|
||||||
|
update_by = Column(String(64), nullable=True, comment="更新人id")
|
||||||
|
update_time = Column(DateTime, nullable=False, default=datetime.now, onupdate=datetime.now, comment="更新时间")
|
||||||
|
del_flag = Column(SmallInteger, nullable=False, default=0, comment="删除标记")
|
||||||
|
|
||||||
|
|
||||||
class BizSampleProductionReception(Base):
|
class BizSampleProductionReception(Base):
|
||||||
"""生产部门样本接收登记 biz_sample_production_reception"""
|
"""生产部门样本接收登记 biz_sample_production_reception"""
|
||||||
|
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,176 @@
|
|||||||
|
"""实验室样本处理数据 — 字段目录与部门归属。"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from typing import Dict, List, Optional, Tuple
|
||||||
|
|
||||||
|
DATASET_HSC = "hsc"
|
||||||
|
DATASET_UBMC = "ubmc"
|
||||||
|
DATASET_MSC = "msc"
|
||||||
|
DATASETS = (DATASET_HSC, DATASET_UBMC, DATASET_MSC)
|
||||||
|
|
||||||
|
DEPT_MARKET = "market"
|
||||||
|
DEPT_PRODUCTION = "production"
|
||||||
|
DEPT_QC = "qc"
|
||||||
|
DEPTS = (DEPT_MARKET, DEPT_PRODUCTION, DEPT_QC)
|
||||||
|
|
||||||
|
PERM_LIST = "lab:sample-processing:list"
|
||||||
|
PERM_MARKET_EDIT = "lab:sample-processing:market:edit"
|
||||||
|
PERM_PRODUCTION_EDIT = "lab:sample-processing:production:edit"
|
||||||
|
PERM_QC_EDIT = "lab:sample-processing:qc:edit"
|
||||||
|
PERM_MANAGER = "lab:sample-processing:manager"
|
||||||
|
|
||||||
|
DEPT_EDIT_PERMS = {
|
||||||
|
DEPT_MARKET: PERM_MARKET_EDIT,
|
||||||
|
DEPT_PRODUCTION: PERM_PRODUCTION_EDIT,
|
||||||
|
DEPT_QC: PERM_QC_EDIT,
|
||||||
|
}
|
||||||
|
|
||||||
|
SOURCE_PROTOCOL = "protocol"
|
||||||
|
SOURCE_RECEPTION = "reception"
|
||||||
|
SOURCE_PRODUCTION = "production_reception"
|
||||||
|
SOURCE_EXTRA = "extra"
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class FieldDef:
|
||||||
|
key: str
|
||||||
|
label: str
|
||||||
|
dept: str
|
||||||
|
source: str
|
||||||
|
attr: Optional[str] = None # ORM attr on source object when applicable
|
||||||
|
|
||||||
|
|
||||||
|
def _f(key: str, label: str, dept: str, source: str, attr: Optional[str] = None) -> FieldDef:
|
||||||
|
return FieldDef(key=key, label=label, dept=dept, source=source, attr=attr or key)
|
||||||
|
|
||||||
|
|
||||||
|
HSC_FIELDS: Tuple[FieldDef, ...] = (
|
||||||
|
_f("sampleCode", "细胞编码", DEPT_MARKET, SOURCE_PROTOCOL, "sample_code"),
|
||||||
|
_f("motherName", "准妈妈姓名", DEPT_MARKET, SOURCE_PROTOCOL, "mother_name"),
|
||||||
|
_f("collectTime", "采集时间", DEPT_MARKET, SOURCE_PROTOCOL, "sample_collect_time"),
|
||||||
|
_f("collectHospital", "采集医院", DEPT_MARKET, SOURCE_PROTOCOL, "hospital_name"),
|
||||||
|
_f("receptionTime", "接收时间", DEPT_PRODUCTION, SOURCE_RECEPTION, "reception_time"),
|
||||||
|
_f("receiveTemperature", "样品温度到达/℃", DEPT_PRODUCTION, SOURCE_RECEPTION, "receive_temperature"),
|
||||||
|
_f("receiveCheck", "收样检查", DEPT_PRODUCTION, SOURCE_EXTRA),
|
||||||
|
_f("hasMaternalBlood", "是否有母血", DEPT_PRODUCTION, SOURCE_EXTRA),
|
||||||
|
_f("remeasureMaternalBlood", "是否重采母血", DEPT_PRODUCTION, SOURCE_EXTRA),
|
||||||
|
_f("hasConsent", "知情同意书或协议书", DEPT_MARKET, SOURCE_EXTRA),
|
||||||
|
_f("hasPackingList", "脐血运输装箱清单", DEPT_MARKET, SOURCE_EXTRA),
|
||||||
|
_f("hasReceiveConfirm", "脐带血接收确认单", DEPT_PRODUCTION, SOURCE_EXTRA),
|
||||||
|
_f("hasHealthSurvey", "孕妇健康调查表", DEPT_MARKET, SOURCE_EXTRA),
|
||||||
|
_f("labelClear", "标识清晰", DEPT_PRODUCTION, SOURCE_EXTRA),
|
||||||
|
_f("receptionHandler", "接收登记人", DEPT_PRODUCTION, SOURCE_RECEPTION, "handler_name"),
|
||||||
|
_f("receptionRemark", "备注", DEPT_PRODUCTION, SOURCE_RECEPTION, "remark"),
|
||||||
|
_f("originalBloodWeightG", "原血重量/g", DEPT_PRODUCTION, SOURCE_PRODUCTION, "original_blood_weight_g"),
|
||||||
|
_f("hesVolumeMl", "HES用量/ml", DEPT_PRODUCTION, SOURCE_PRODUCTION, "hes_volume_ml"),
|
||||||
|
_f("bloodType", "血型", DEPT_PRODUCTION, SOURCE_PRODUCTION, "blood_type"),
|
||||||
|
_f("infectiousFourCard", "传染四项检测(检测卡)", DEPT_QC, SOURCE_PRODUCTION, "infectious_four_test_result"),
|
||||||
|
_f("infectiousFourExternal", "传染四项检测(外检)", DEPT_QC, SOURCE_EXTRA),
|
||||||
|
_f("preEnrichTnc", "富集前有核细胞数/109/L", DEPT_PRODUCTION, SOURCE_EXTRA),
|
||||||
|
_f("enrichedBloodWeightG", "富集后血量/g", DEPT_PRODUCTION, SOURCE_PRODUCTION, "enriched_blood_weight_g"),
|
||||||
|
_f("postEnrichTnc", "富集后有核细胞数/109/L", DEPT_PRODUCTION, SOURCE_EXTRA),
|
||||||
|
_f("cryoVolumeMl", "冻存液用量/ml", DEPT_PRODUCTION, SOURCE_PRODUCTION, "cryopreservation_volume_ml"),
|
||||||
|
_f("cd34Count", "CD34+细胞计数/*10E4", DEPT_QC, SOURCE_EXTRA),
|
||||||
|
_f("operatorName", "操作人", DEPT_PRODUCTION, SOURCE_PRODUCTION, "handler_name"),
|
||||||
|
_f("processRemark", "备注", DEPT_PRODUCTION, SOURCE_PRODUCTION, "remark"),
|
||||||
|
)
|
||||||
|
|
||||||
|
UBMC_FIELDS: Tuple[FieldDef, ...] = (
|
||||||
|
_f("sampleCode", "细胞编码", DEPT_MARKET, SOURCE_PROTOCOL, "sample_code"),
|
||||||
|
_f("motherName", "准妈妈姓名", DEPT_MARKET, SOURCE_PROTOCOL, "mother_name"),
|
||||||
|
_f("labMaterialCode", "实验室物料编码", DEPT_PRODUCTION, SOURCE_EXTRA),
|
||||||
|
_f("labStorageCode", "入库编码", DEPT_PRODUCTION, SOURCE_RECEPTION, "lab_storage_code"),
|
||||||
|
_f("storageStatus", "储存状态", DEPT_PRODUCTION, SOURCE_EXTRA),
|
||||||
|
_f("discardReason", "废弃原因", DEPT_PRODUCTION, SOURCE_EXTRA),
|
||||||
|
_f("receptionTime", "接收时间", DEPT_PRODUCTION, SOURCE_RECEPTION, "reception_time"),
|
||||||
|
_f("receiveTemperature", "样品温度到达/℃", DEPT_PRODUCTION, SOURCE_RECEPTION, "receive_temperature"),
|
||||||
|
_f("receiveCheck", "收样检查", DEPT_PRODUCTION, SOURCE_EXTRA),
|
||||||
|
_f("receptionHandler", "接收登记人", DEPT_PRODUCTION, SOURCE_RECEPTION, "handler_name"),
|
||||||
|
_f("receptionRemark", "备注", DEPT_PRODUCTION, SOURCE_RECEPTION, "remark"),
|
||||||
|
_f("originalBloodVolumeMl", "原血体积/mL", DEPT_PRODUCTION, SOURCE_PRODUCTION, "original_blood_volume_ml"),
|
||||||
|
_f("nucleatedCellCount1e8", "有核细胞数/108", DEPT_PRODUCTION, SOURCE_PRODUCTION, "nucleated_cell_count_1e8"),
|
||||||
|
_f("preOpTnc", "操作前有核细胞数/109/L", DEPT_PRODUCTION, SOURCE_EXTRA),
|
||||||
|
_f("infectiousFourCard", "传染四项检测(检测卡)", DEPT_QC, SOURCE_PRODUCTION, "infectious_four_test_result"),
|
||||||
|
_f("hbsag", "乙型肝炎病毒表面抗原(HBsAg)", DEPT_QC, SOURCE_EXTRA),
|
||||||
|
_f("antiHcv", "丙型肝炎病毒抗体(抗HCV)", DEPT_QC, SOURCE_EXTRA),
|
||||||
|
_f("antiTp", "梅毒螺旋体特异性抗体(抗TP)", DEPT_QC, SOURCE_EXTRA),
|
||||||
|
_f("antiHiv", "人类免疫缺陷病毒抗体(抗HIV-1/2)", DEPT_QC, SOURCE_EXTRA),
|
||||||
|
_f("cmvIgm", "巨细胞病毒IgM 抗体 (CMV-IgM)", DEPT_QC, SOURCE_EXTRA),
|
||||||
|
_f("operatorName", "操作人", DEPT_PRODUCTION, SOURCE_PRODUCTION, "handler_name"),
|
||||||
|
_f("processRemark", "备注", DEPT_PRODUCTION, SOURCE_PRODUCTION, "remark"),
|
||||||
|
)
|
||||||
|
|
||||||
|
MSC_FIELDS: Tuple[FieldDef, ...] = (
|
||||||
|
_f("sampleCode", "实验室流转编码", DEPT_MARKET, SOURCE_PROTOCOL, "sample_code"),
|
||||||
|
_f("motherName", "母亲姓名", DEPT_MARKET, SOURCE_PROTOCOL, "mother_name"),
|
||||||
|
_f("collectTime", "脐带采集时间", DEPT_MARKET, SOURCE_PROTOCOL, "sample_collect_time"),
|
||||||
|
_f("transportTempC", "运输温度/℃", DEPT_PRODUCTION, SOURCE_EXTRA),
|
||||||
|
_f("receptionTime", "脐带接收时间", DEPT_PRODUCTION, SOURCE_RECEPTION, "reception_time"),
|
||||||
|
_f("receptionHandler", "接收登记人", DEPT_PRODUCTION, SOURCE_RECEPTION, "handler_name"),
|
||||||
|
_f("inoculationAmount", "接种量", DEPT_PRODUCTION, SOURCE_PRODUCTION, "inoculation_amount"),
|
||||||
|
_f("storageStatus", "储存状态", DEPT_PRODUCTION, SOURCE_EXTRA),
|
||||||
|
_f("cryoTime", "冻存时间", DEPT_PRODUCTION, SOURCE_PRODUCTION, "cryopreservation_time"),
|
||||||
|
_f("storageTotalTubes", "储存总量(管)", DEPT_PRODUCTION, SOURCE_PRODUCTION, "storage_total_tubes"),
|
||||||
|
_f("availableCellCount1e7", "可提供细胞数量/*10E7", DEPT_PRODUCTION, SOURCE_PRODUCTION, "available_cell_count_1e7"),
|
||||||
|
_f("endotoxinTest", "内毒素检测", DEPT_QC, SOURCE_EXTRA),
|
||||||
|
_f("bacteriaTest", "细菌检测", DEPT_QC, SOURCE_EXTRA),
|
||||||
|
_f("fungusTest", "真菌检测", DEPT_QC, SOURCE_EXTRA),
|
||||||
|
_f("mycoplasmaTest", "支原体检测", DEPT_QC, SOURCE_EXTRA),
|
||||||
|
_f("operatorName", "操作人", DEPT_PRODUCTION, SOURCE_PRODUCTION, "handler_name"),
|
||||||
|
_f("motherHbsag", "乙型肝炎病毒表面抗原(HBsAg)", DEPT_QC, SOURCE_EXTRA),
|
||||||
|
_f("motherHbvDna", "乙型肝炎病毒核酸(HBV DNA)", DEPT_QC, SOURCE_EXTRA),
|
||||||
|
_f("motherAntiHcv", "丙型肝炎病毒抗体(抗HCV)", DEPT_QC, SOURCE_EXTRA),
|
||||||
|
_f("motherHcvRna", "丙型肝炎病毒核酸(HCV RNA)", DEPT_QC, SOURCE_EXTRA),
|
||||||
|
_f("motherAntiTp", "梅毒螺旋体特异性抗体(抗TP)", DEPT_QC, SOURCE_EXTRA),
|
||||||
|
_f("motherCmvIgm", "巨细胞病毒lgM 抗体 (CMV lgM)", DEPT_QC, SOURCE_EXTRA),
|
||||||
|
_f("motherAntiHiv", "人类免疫缺陷病毒抗体(抗HIV-1/2)", DEPT_QC, SOURCE_EXTRA),
|
||||||
|
_f("motherHiv1Rna", "人类免疫缺陷病毒核酸(1型) (HIV-1RNA)", DEPT_QC, SOURCE_EXTRA),
|
||||||
|
_f("storageDateP2", "储存日期(P2冻存日期)", DEPT_PRODUCTION, SOURCE_EXTRA),
|
||||||
|
_f("processRemark", "备注", DEPT_PRODUCTION, SOURCE_PRODUCTION, "remark"),
|
||||||
|
)
|
||||||
|
|
||||||
|
FIELDS_BY_DATASET: Dict[str, Tuple[FieldDef, ...]] = {
|
||||||
|
DATASET_HSC: HSC_FIELDS,
|
||||||
|
DATASET_UBMC: UBMC_FIELDS,
|
||||||
|
DATASET_MSC: MSC_FIELDS,
|
||||||
|
}
|
||||||
|
|
||||||
|
DATASET_LABELS = {
|
||||||
|
DATASET_HSC: "造血干细胞数据",
|
||||||
|
DATASET_UBMC: "单个核数据",
|
||||||
|
DATASET_MSC: "脐带间充质干细胞数据",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def fields_for(dataset: str) -> Tuple[FieldDef, ...]:
|
||||||
|
return FIELDS_BY_DATASET.get(dataset) or ()
|
||||||
|
|
||||||
|
|
||||||
|
def field_map(dataset: str) -> Dict[str, FieldDef]:
|
||||||
|
return {f.key: f for f in fields_for(dataset)}
|
||||||
|
|
||||||
|
|
||||||
|
def editable_depts_for_user(*, is_manager: bool, dept_flags: Dict[str, bool]) -> set:
|
||||||
|
if is_manager:
|
||||||
|
return set(DEPTS)
|
||||||
|
return {d for d, ok in dept_flags.items() if ok}
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_dataset_by_type_name(name: Optional[str], sample_code: Optional[str] = None) -> Optional[str]:
|
||||||
|
text = (name or "").strip()
|
||||||
|
code = (sample_code or "").strip().upper()
|
||||||
|
if "单个核" in text or "脐血单个核" in text or code.startswith("UBMC"):
|
||||||
|
return DATASET_UBMC
|
||||||
|
if "间充质" in text or code.startswith("BC") or code.startswith("UC"):
|
||||||
|
return DATASET_MSC
|
||||||
|
if "造血" in text or code.startswith("B"):
|
||||||
|
return DATASET_HSC
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def schema_payload(dataset: str) -> List[Dict[str, str]]:
|
||||||
|
return [
|
||||||
|
{"key": f.key, "label": f.label, "dept": f.dept, "source": f.source}
|
||||||
|
for f in fields_for(dataset)
|
||||||
|
]
|
||||||
@@ -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),
|
||||||
|
}
|
||||||
@@ -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())
|
||||||
@@ -0,0 +1,324 @@
|
|||||||
|
"""将会议 Excel 三张表导入实验室样本处理补充台账。
|
||||||
|
|
||||||
|
用法(工程/worktree 根或 backend 下):
|
||||||
|
ENV_FILE=.../backend/.env python backend/scripts/import_lab_sample_processing_xlsx.py --xlsx PATH
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import re
|
||||||
|
import sys
|
||||||
|
import zipfile
|
||||||
|
import xml.etree.ElementTree as ET
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
# 允许直接脚本运行
|
||||||
|
ROOT = Path(__file__).resolve().parents[2]
|
||||||
|
BACKEND = ROOT / "backend"
|
||||||
|
if str(BACKEND) not in sys.path:
|
||||||
|
sys.path.insert(0, str(BACKEND))
|
||||||
|
|
||||||
|
from sqlalchemy.orm import Session # noqa: E402
|
||||||
|
|
||||||
|
from app.core.config import settings # noqa: E402
|
||||||
|
from app.core.database import SessionLocal # noqa: E402
|
||||||
|
from app.services.lab_sample_processing import upsert_extra_payload # noqa: E402
|
||||||
|
from app.services.lab_sample_processing_fields import ( # noqa: E402
|
||||||
|
DATASET_HSC,
|
||||||
|
DATASET_MSC,
|
||||||
|
DATASET_UBMC,
|
||||||
|
fields_for,
|
||||||
|
)
|
||||||
|
|
||||||
|
NS = {
|
||||||
|
"m": "http://schemas.openxmlformats.org/spreadsheetml/2006/main",
|
||||||
|
"r": "http://schemas.openxmlformats.org/officeDocument/2006/relationships",
|
||||||
|
}
|
||||||
|
|
||||||
|
SHEET_DATASET = {
|
||||||
|
"造血干细胞数据": DATASET_HSC,
|
||||||
|
"单个核数据": DATASET_UBMC,
|
||||||
|
"脐带间充质干细胞数据": DATASET_MSC,
|
||||||
|
}
|
||||||
|
|
||||||
|
LABEL_ALIASES = {
|
||||||
|
"细胞编码": "sampleCode",
|
||||||
|
"实验室流转编码": "sampleCode",
|
||||||
|
"准妈妈姓名": "motherName",
|
||||||
|
"母亲姓名": "motherName",
|
||||||
|
"采集时间": "collectTime",
|
||||||
|
"脐带采集时间": "collectTime",
|
||||||
|
"采集医院": "collectHospital",
|
||||||
|
"接收时间": "receptionTime",
|
||||||
|
"脐带接收时间": "receptionTime",
|
||||||
|
"样品温度到达/℃": "receiveTemperature",
|
||||||
|
"运输温度/℃": "transportTempC",
|
||||||
|
"运输温度\n/℃": "transportTempC",
|
||||||
|
"收样检查": "receiveCheck",
|
||||||
|
"是否有母血": "hasMaternalBlood",
|
||||||
|
"是否重采母血": "remeasureMaternalBlood",
|
||||||
|
"知情同意书或协议书": "hasConsent",
|
||||||
|
"脐血运输装箱清单": "hasPackingList",
|
||||||
|
"脐带血接收确认单": "hasReceiveConfirm",
|
||||||
|
"孕妇健康调查表": "hasHealthSurvey",
|
||||||
|
"标识清晰": "labelClear",
|
||||||
|
"接收登记人": "receptionHandler",
|
||||||
|
"原血重量/g": "originalBloodWeightG",
|
||||||
|
"HES用量/ml": "hesVolumeMl",
|
||||||
|
"血型": "bloodType",
|
||||||
|
"传染四项检测(检测卡)": "infectiousFourCard",
|
||||||
|
"传染四项检测(外检)": "infectiousFourExternal",
|
||||||
|
"富集前有核细胞数/109/L": "preEnrichTnc",
|
||||||
|
"富集后血量/g": "enrichedBloodWeightG",
|
||||||
|
"富集后有核细胞数/109/L": "postEnrichTnc",
|
||||||
|
"冻存液用量/ml": "cryoVolumeMl",
|
||||||
|
"CD34+细胞计数/*10E4": "cd34Count",
|
||||||
|
"操作人": "operatorName",
|
||||||
|
"实验室物料编码": "labMaterialCode",
|
||||||
|
"入库编码": "labStorageCode",
|
||||||
|
"储存状态": "storageStatus",
|
||||||
|
"废弃原因": "discardReason",
|
||||||
|
"原血体积/mL": "originalBloodVolumeMl",
|
||||||
|
"有核细胞数/108": "nucleatedCellCount1e8",
|
||||||
|
"操作前有核细胞数/109/L": "preOpTnc",
|
||||||
|
"乙型肝炎病毒表面抗原(HBsAg)": "hbsag",
|
||||||
|
"丙型肝炎病毒抗体(抗HCV)": "antiHcv",
|
||||||
|
"梅毒螺旋体特异性抗体(抗TP)": "antiTp",
|
||||||
|
"人类免疫缺陷病毒抗体(抗HIV-1/2)": "antiHiv",
|
||||||
|
"巨细胞病毒IgM 抗体 (CMV-IgM)": "cmvIgm",
|
||||||
|
"接种量": "inoculationAmount",
|
||||||
|
"冻存时间": "cryoTime",
|
||||||
|
"储存总量(管)": "storageTotalTubes",
|
||||||
|
"储存总量\n(管)": "storageTotalTubes",
|
||||||
|
"可提供细胞数量/*10E7": "availableCellCount1e7",
|
||||||
|
"内毒素检测": "endotoxinTest",
|
||||||
|
"细菌检测": "bacteriaTest",
|
||||||
|
"真菌检测": "fungusTest",
|
||||||
|
"支原体检测": "mycoplasmaTest",
|
||||||
|
"乙型肝炎病毒表面抗原(HBsAg):": "motherHbsag",
|
||||||
|
"乙型肝炎病毒核酸(HBV DNA)": "motherHbvDna",
|
||||||
|
"丙型肝炎病毒核酸(HCV RNA)": "motherHcvRna",
|
||||||
|
"巨细胞病毒lgM 抗体 (CMV lgM)": "motherCmvIgm",
|
||||||
|
"人类免疫缺陷病毒核酸(1型) (HIV-1RNA)": "motherHiv1Rna",
|
||||||
|
"储存日期\n(P2冻存日期)": "storageDateP2",
|
||||||
|
"储存日期(P2冻存日期)": "storageDateP2",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _norm_label(s: str) -> str:
|
||||||
|
return re.sub(r"\s+", "", (s or "").replace("\r", "").strip())
|
||||||
|
|
||||||
|
|
||||||
|
def _col_row(ref: str):
|
||||||
|
m = re.match(r"([A-Z]+)(\d+)", ref)
|
||||||
|
col = m.group(1)
|
||||||
|
row = int(m.group(2))
|
||||||
|
n = 0
|
||||||
|
for ch in col:
|
||||||
|
n = n * 26 + ord(ch) - 64
|
||||||
|
return n, row
|
||||||
|
|
||||||
|
|
||||||
|
def read_sheet_matrix(z: zipfile.ZipFile, target: str):
|
||||||
|
ss = []
|
||||||
|
if "xl/sharedStrings.xml" in z.namelist():
|
||||||
|
root = ET.fromstring(z.read("xl/sharedStrings.xml"))
|
||||||
|
for si in root.findall("m:si", NS):
|
||||||
|
texts = [
|
||||||
|
t.text or ""
|
||||||
|
for t in si.iter("{http://schemas.openxmlformats.org/spreadsheetml/2006/main}t")
|
||||||
|
]
|
||||||
|
ss.append("".join(texts))
|
||||||
|
root = ET.fromstring(z.read(target))
|
||||||
|
rows = {}
|
||||||
|
for c in root.findall(".//m:sheetData/m:row/m:c", NS):
|
||||||
|
ref = c.attrib.get("r")
|
||||||
|
t = c.attrib.get("t")
|
||||||
|
v = c.find("m:v", NS)
|
||||||
|
if v is None or ref is None:
|
||||||
|
continue
|
||||||
|
val = v.text or ""
|
||||||
|
if t == "s":
|
||||||
|
try:
|
||||||
|
val = ss[int(val)]
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
cn, rn = _col_row(ref)
|
||||||
|
rows.setdefault(rn, {})[cn] = val
|
||||||
|
if not rows:
|
||||||
|
return []
|
||||||
|
max_r = max(rows)
|
||||||
|
max_c = max(max(cols) for cols in rows.values())
|
||||||
|
matrix = []
|
||||||
|
for rn in range(1, max_r + 1):
|
||||||
|
line = [str(rows.get(rn, {}).get(c, "") or "").strip() for c in range(1, max_c + 1)]
|
||||||
|
matrix.append(line)
|
||||||
|
return matrix
|
||||||
|
|
||||||
|
|
||||||
|
def build_header_map(header_rows: list, dataset: str):
|
||||||
|
"""合并多行表头,按列映射到字段 key。"""
|
||||||
|
width = max(len(r) for r in header_rows)
|
||||||
|
merged = [""] * width
|
||||||
|
for r in header_rows:
|
||||||
|
for i in range(width):
|
||||||
|
cell = r[i] if i < len(r) else ""
|
||||||
|
if cell:
|
||||||
|
merged[i] = cell if not merged[i] else merged[i]
|
||||||
|
# MSC: 第二行填充分组子列
|
||||||
|
if len(header_rows) >= 2:
|
||||||
|
for i in range(width):
|
||||||
|
top = header_rows[0][i] if i < len(header_rows[0]) else ""
|
||||||
|
sub = header_rows[1][i] if i < len(header_rows[1]) else ""
|
||||||
|
if sub:
|
||||||
|
merged[i] = sub
|
||||||
|
elif top and not merged[i]:
|
||||||
|
merged[i] = top
|
||||||
|
|
||||||
|
label_to_key = {_norm_label(f.label): f.key for f in fields_for(dataset)}
|
||||||
|
for alias, key in LABEL_ALIASES.items():
|
||||||
|
label_to_key[_norm_label(alias)] = key
|
||||||
|
|
||||||
|
# 备注列:第一处 receptionRemark,第二处 processRemark
|
||||||
|
remark_keys = []
|
||||||
|
col_map = {}
|
||||||
|
for idx, label in enumerate(merged):
|
||||||
|
n = _norm_label(label)
|
||||||
|
if not n or n in {"序号"}:
|
||||||
|
continue
|
||||||
|
if n == "备注":
|
||||||
|
remark_keys.append(idx)
|
||||||
|
continue
|
||||||
|
# 母血相关与单项同名字段在 MSC 中优先 mother*
|
||||||
|
key = label_to_key.get(n)
|
||||||
|
if not key and n.endswith(":"):
|
||||||
|
key = label_to_key.get(n[:-1])
|
||||||
|
if key:
|
||||||
|
col_map[idx] = key
|
||||||
|
if remark_keys:
|
||||||
|
col_map[remark_keys[0]] = "receptionRemark"
|
||||||
|
if len(remark_keys) > 1:
|
||||||
|
col_map[remark_keys[1]] = "processRemark"
|
||||||
|
elif "processRemark" in {f.key for f in fields_for(dataset)} and dataset != DATASET_UBMC:
|
||||||
|
# 单备注时,造血第二业务备注也可能只有一列;保留 receptionRemark
|
||||||
|
pass
|
||||||
|
# UBMC 仅一列备注时落到 receptionRemark;有操作备注需求时同步 processRemark
|
||||||
|
return col_map, merged
|
||||||
|
|
||||||
|
|
||||||
|
def parse_workbook(path: Path):
|
||||||
|
out = {}
|
||||||
|
with zipfile.ZipFile(path) as z:
|
||||||
|
wb = ET.fromstring(z.read("xl/workbook.xml"))
|
||||||
|
sheets = []
|
||||||
|
for sh in wb.findall("m:sheets/m:sheet", NS):
|
||||||
|
sheets.append(
|
||||||
|
(
|
||||||
|
sh.attrib.get("name"),
|
||||||
|
sh.attrib.get("{http://schemas.openxmlformats.org/officeDocument/2006/relationships}id"),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
rels = ET.fromstring(z.read("xl/_rels/workbook.xml.rels"))
|
||||||
|
rid_to_target = {rel.attrib["Id"]: rel.attrib["Target"] for rel in rels}
|
||||||
|
for name, rid in sheets:
|
||||||
|
dataset = SHEET_DATASET.get(name)
|
||||||
|
if not dataset:
|
||||||
|
continue
|
||||||
|
target = rid_to_target[rid]
|
||||||
|
if not target.startswith("xl/"):
|
||||||
|
target = "xl/" + target
|
||||||
|
matrix = read_sheet_matrix(z, target)
|
||||||
|
if not matrix:
|
||||||
|
continue
|
||||||
|
# MSC 两行表头;其他一行(UBMC 可能首列分组)
|
||||||
|
if dataset == DATASET_MSC:
|
||||||
|
header_rows = matrix[:2]
|
||||||
|
data_rows = matrix[2:]
|
||||||
|
else:
|
||||||
|
header_rows = matrix[:1]
|
||||||
|
data_rows = matrix[1:]
|
||||||
|
col_map, merged = build_header_map(header_rows, dataset)
|
||||||
|
records = []
|
||||||
|
for row in data_rows:
|
||||||
|
payload = {}
|
||||||
|
for idx, key in col_map.items():
|
||||||
|
val = row[idx] if idx < len(row) else ""
|
||||||
|
if val != "":
|
||||||
|
payload[key] = val
|
||||||
|
code = str(payload.get("sampleCode") or "").strip()
|
||||||
|
if not code:
|
||||||
|
continue
|
||||||
|
# UBMC 同名母血检测字段:Excel 用的是非 mother 前缀,已映射
|
||||||
|
# MSC 母血字段别名
|
||||||
|
if dataset == DATASET_MSC:
|
||||||
|
if "antiHcv" in payload and "motherAntiHcv" not in payload:
|
||||||
|
payload["motherAntiHcv"] = payload.pop("antiHcv")
|
||||||
|
if "antiTp" in payload and "motherAntiTp" not in payload:
|
||||||
|
payload["motherAntiTp"] = payload.pop("antiTp")
|
||||||
|
if "antiHiv" in payload and "motherAntiHiv" not in payload:
|
||||||
|
payload["motherAntiHiv"] = payload.pop("antiHiv")
|
||||||
|
if "hbsag" in payload and "motherHbsag" not in payload:
|
||||||
|
payload["motherHbsag"] = payload.pop("hbsag")
|
||||||
|
payload["sampleCode"] = code
|
||||||
|
records.append(payload)
|
||||||
|
out[dataset] = {"headers": merged, "records": records, "col_map": col_map}
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def import_all(db: Session, tenant_no: str, parsed: dict) -> dict:
|
||||||
|
summary = {}
|
||||||
|
for dataset, pack in parsed.items():
|
||||||
|
n = 0
|
||||||
|
for payload in pack["records"]:
|
||||||
|
upsert_extra_payload(
|
||||||
|
db,
|
||||||
|
tenant_no=tenant_no,
|
||||||
|
dataset=dataset,
|
||||||
|
sample_code=payload["sampleCode"],
|
||||||
|
payload=payload,
|
||||||
|
operator_id="excel-import",
|
||||||
|
replace=True,
|
||||||
|
)
|
||||||
|
n += 1
|
||||||
|
summary[dataset] = n
|
||||||
|
db.commit()
|
||||||
|
return summary
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
parser = argparse.ArgumentParser()
|
||||||
|
parser.add_argument("--xlsx", required=True)
|
||||||
|
parser.add_argument("--tenant", default=None)
|
||||||
|
args = parser.parse_args()
|
||||||
|
xlsx = Path(args.xlsx)
|
||||||
|
if not xlsx.exists():
|
||||||
|
raise SystemExit(f"xlsx not found: {xlsx}")
|
||||||
|
|
||||||
|
parsed = parse_workbook(xlsx)
|
||||||
|
if not parsed:
|
||||||
|
raise SystemExit("no sheets parsed")
|
||||||
|
|
||||||
|
db = SessionLocal()
|
||||||
|
try:
|
||||||
|
tenant_no = args.tenant
|
||||||
|
if not tenant_no:
|
||||||
|
# 取库中任一有效租户
|
||||||
|
from app.models.models import SysUser
|
||||||
|
|
||||||
|
u = (
|
||||||
|
db.query(SysUser)
|
||||||
|
.filter(SysUser.del_flag == 0, SysUser.status == "1", SysUser.tenant_no.isnot(None))
|
||||||
|
.first()
|
||||||
|
)
|
||||||
|
tenant_no = (u.tenant_no if u else None) or "zkxw"
|
||||||
|
summary = import_all(db, tenant_no, parsed)
|
||||||
|
print("tenant", tenant_no)
|
||||||
|
for ds, n in summary.items():
|
||||||
|
print(f"imported {ds}={n}")
|
||||||
|
print("ok")
|
||||||
|
finally:
|
||||||
|
db.close()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
"""恢复被误软删的 Excel 补充字段(真菌/内毒素/CD34 等)并同步旧台账。
|
||||||
|
|
||||||
|
用法:
|
||||||
|
ENV_FILE=.../backend/.env python backend/scripts/restore_lab_sample_processing_excel_extras.py
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[2]
|
||||||
|
BACKEND = ROOT / "backend"
|
||||||
|
if str(BACKEND) not in sys.path:
|
||||||
|
sys.path.insert(0, str(BACKEND))
|
||||||
|
|
||||||
|
from app.core.database import SessionLocal # noqa: E402
|
||||||
|
from app.services.lab_sample_processing import restore_retired_excel_extras # noqa: E402
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
db = SessionLocal()
|
||||||
|
try:
|
||||||
|
result = restore_retired_excel_extras(db, tenant_no="zkxw")
|
||||||
|
print(result)
|
||||||
|
finally:
|
||||||
|
db.close()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,230 @@
|
|||||||
|
import unittest
|
||||||
|
|
||||||
|
from app.services.lab_sample_processing_fields import (
|
||||||
|
DATASET_HSC,
|
||||||
|
DATASET_MSC,
|
||||||
|
DATASET_UBMC,
|
||||||
|
DEPT_MARKET,
|
||||||
|
DEPT_PRODUCTION,
|
||||||
|
DEPT_QC,
|
||||||
|
editable_depts_for_user,
|
||||||
|
field_map,
|
||||||
|
resolve_dataset_by_type_name,
|
||||||
|
schema_payload,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class LabSampleProcessingFieldsTest(unittest.TestCase):
|
||||||
|
def test_resolve_dataset(self):
|
||||||
|
self.assertEqual(resolve_dataset_by_type_name("围产期造血干细胞", "B0000001"), DATASET_HSC)
|
||||||
|
self.assertEqual(resolve_dataset_by_type_name("脐带间充质干细胞", "BC0000003"), DATASET_MSC)
|
||||||
|
self.assertEqual(resolve_dataset_by_type_name("", "UBMC2025001"), DATASET_UBMC)
|
||||||
|
self.assertEqual(resolve_dataset_by_type_name("", "UC2026001"), DATASET_MSC)
|
||||||
|
|
||||||
|
def test_schema_not_empty(self):
|
||||||
|
self.assertGreater(len(schema_payload(DATASET_HSC)), 10)
|
||||||
|
self.assertGreater(len(schema_payload(DATASET_UBMC)), 10)
|
||||||
|
self.assertGreater(len(schema_payload(DATASET_MSC)), 10)
|
||||||
|
|
||||||
|
def test_dept_acl(self):
|
||||||
|
self.assertEqual(
|
||||||
|
editable_depts_for_user(
|
||||||
|
is_manager=True,
|
||||||
|
dept_flags={DEPT_MARKET: False, DEPT_PRODUCTION: False, DEPT_QC: False},
|
||||||
|
),
|
||||||
|
{DEPT_MARKET, DEPT_PRODUCTION, DEPT_QC},
|
||||||
|
)
|
||||||
|
self.assertEqual(
|
||||||
|
editable_depts_for_user(
|
||||||
|
is_manager=False,
|
||||||
|
dept_flags={DEPT_MARKET: False, DEPT_PRODUCTION: True, DEPT_QC: False},
|
||||||
|
),
|
||||||
|
{DEPT_PRODUCTION},
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_hsc_market_and_qc_fields(self):
|
||||||
|
fmap = field_map(DATASET_HSC)
|
||||||
|
self.assertEqual(fmap["motherName"].dept, DEPT_MARKET)
|
||||||
|
self.assertEqual(fmap["cd34Count"].dept, DEPT_QC)
|
||||||
|
self.assertEqual(fmap["originalBloodWeightG"].dept, DEPT_PRODUCTION)
|
||||||
|
|
||||||
|
def test_source_fields_not_overridden_by_extra(self):
|
||||||
|
from datetime import datetime
|
||||||
|
from app.services.lab_sample_processing import _build_row
|
||||||
|
from types import SimpleNamespace
|
||||||
|
|
||||||
|
sample = SimpleNamespace(id="S1", sample_code="ZKZX34000865", collection_protocol_id="P1")
|
||||||
|
party = SimpleNamespace(mother_name="真实妈妈")
|
||||||
|
coll = SimpleNamespace(
|
||||||
|
sample_collect_time=None,
|
||||||
|
maternal_blood_collect_time=datetime(2026, 11, 4, 5, 20),
|
||||||
|
)
|
||||||
|
hospital = SimpleNamespace(hospital_name="真实医院")
|
||||||
|
protocol = SimpleNamespace(
|
||||||
|
consent_form_urls="protocol-consent/a",
|
||||||
|
health_survey_form_urls="",
|
||||||
|
)
|
||||||
|
reception = SimpleNamespace(
|
||||||
|
id="R1",
|
||||||
|
reception_time=None,
|
||||||
|
receive_temperature=None,
|
||||||
|
handler_name="接收人",
|
||||||
|
remark=None,
|
||||||
|
lab_storage_code="B0000103",
|
||||||
|
)
|
||||||
|
production = SimpleNamespace(
|
||||||
|
id="PR1",
|
||||||
|
original_blood_weight_g=72.08,
|
||||||
|
hes_volume_ml=None,
|
||||||
|
blood_type="B",
|
||||||
|
infectious_four_test_result="zc",
|
||||||
|
enriched_blood_weight_g=None,
|
||||||
|
cryopreservation_volume_ml=None,
|
||||||
|
handler_name="操作人",
|
||||||
|
remark=None,
|
||||||
|
original_blood_volume_ml=None,
|
||||||
|
nucleated_cell_count_1e8=None,
|
||||||
|
inoculation_amount=None,
|
||||||
|
cryopreservation_time=None,
|
||||||
|
storage_total_tubes=None,
|
||||||
|
available_cell_count_1e7=None,
|
||||||
|
)
|
||||||
|
row = _build_row(
|
||||||
|
dataset=DATASET_HSC,
|
||||||
|
sample=sample,
|
||||||
|
type_name="围产期造血干细胞",
|
||||||
|
party=party,
|
||||||
|
coll=coll,
|
||||||
|
hospital=hospital,
|
||||||
|
reception=reception,
|
||||||
|
production=production,
|
||||||
|
extra={
|
||||||
|
"motherName": "Excel妈妈",
|
||||||
|
"originalBloodWeightG": 1,
|
||||||
|
"cd34Count": "11.4",
|
||||||
|
},
|
||||||
|
protocol=protocol,
|
||||||
|
check_flags={
|
||||||
|
"健康调查表": True,
|
||||||
|
"样本信息正确,标识清晰": True,
|
||||||
|
"针路密闭": True,
|
||||||
|
"容器无破损": True,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
self.assertEqual(row["sampleCode"], "B0000103")
|
||||||
|
self.assertEqual(row["protocolSampleCode"], "ZKZX34000865")
|
||||||
|
self.assertEqual(row["motherName"], "真实妈妈")
|
||||||
|
self.assertEqual(row["originalBloodWeightG"], 72.08)
|
||||||
|
self.assertEqual(row["bloodType"], "B")
|
||||||
|
self.assertEqual(row["cd34Count"], "11.4")
|
||||||
|
self.assertEqual(row["hasMaternalBlood"], "是")
|
||||||
|
self.assertEqual(row["hasConsent"], "是")
|
||||||
|
self.assertEqual(row["hasHealthSurvey"], "是")
|
||||||
|
self.assertEqual(row["labelClear"], "是")
|
||||||
|
self.assertEqual(row["infectiousFourCard"], "正常")
|
||||||
|
self.assertIn("针路密闭", row["receiveCheck"] or "")
|
||||||
|
self.assertFalse(row["fromExtraOnly"])
|
||||||
|
|
||||||
|
def test_infectious_code_roundtrip(self):
|
||||||
|
from app.services.lab_sample_processing import _infectious_code, _infectious_label
|
||||||
|
|
||||||
|
self.assertEqual(_infectious_label("zc"), "正常")
|
||||||
|
self.assertEqual(_infectious_label("bzc"), "不正常")
|
||||||
|
self.assertEqual(_infectious_code("正常"), "zc")
|
||||||
|
self.assertEqual(_infectious_code("不正常"), "bzc")
|
||||||
|
|
||||||
|
def test_extra_field_keys_include_fungus(self):
|
||||||
|
from app.services.lab_sample_processing import _extra_field_keys
|
||||||
|
|
||||||
|
keys = _extra_field_keys(DATASET_MSC)
|
||||||
|
self.assertIn("fungusTest", keys)
|
||||||
|
self.assertIn("endotoxinTest", keys)
|
||||||
|
self.assertIn("bacteriaTest", keys)
|
||||||
|
self.assertIn("mycoplasmaTest", keys)
|
||||||
|
|
||||||
|
def test_msc_donation_collect_and_transport_fallback(self):
|
||||||
|
from datetime import datetime
|
||||||
|
from app.services.lab_sample_processing import _build_row
|
||||||
|
from types import SimpleNamespace
|
||||||
|
|
||||||
|
sample = SimpleNamespace(id="D1", sample_code="KYJZ1", collection_protocol_id=None)
|
||||||
|
party = SimpleNamespace(mother_name="孙玲")
|
||||||
|
coll = SimpleNamespace(
|
||||||
|
sample_collect_time=datetime(2026, 10, 10, 10, 5),
|
||||||
|
maternal_blood_collect_time=None,
|
||||||
|
)
|
||||||
|
reception = SimpleNamespace(
|
||||||
|
id="R1",
|
||||||
|
reception_time=datetime(2026, 10, 10, 15, 40, 57),
|
||||||
|
receive_temperature="23.1",
|
||||||
|
handler_name="侯以婷",
|
||||||
|
remark=None,
|
||||||
|
lab_storage_code="UC2026006",
|
||||||
|
)
|
||||||
|
row = _build_row(
|
||||||
|
dataset=DATASET_MSC,
|
||||||
|
sample=sample,
|
||||||
|
type_name="脐带间充质干细胞",
|
||||||
|
party=party,
|
||||||
|
coll=coll,
|
||||||
|
hospital=None,
|
||||||
|
reception=reception,
|
||||||
|
production=None,
|
||||||
|
extra={},
|
||||||
|
)
|
||||||
|
self.assertEqual(row["sampleCode"], "UC2026006")
|
||||||
|
self.assertEqual(row["collectTime"], "2026-10-10 10:05:00")
|
||||||
|
self.assertEqual(row["transportTempC"], "23.1")
|
||||||
|
self.assertNotIn("导出自存", row["motherName"] or "")
|
||||||
|
|
||||||
|
def test_legacy_supplement_fills_empty_source_fields(self):
|
||||||
|
from app.services.lab_sample_processing import _build_row, _merge_extra_with_legacy
|
||||||
|
from types import SimpleNamespace
|
||||||
|
|
||||||
|
extra = _merge_extra_with_legacy(
|
||||||
|
{},
|
||||||
|
{"infectiousFourTestLabel": "正常", "labMaterialCode": "202611006"},
|
||||||
|
)
|
||||||
|
sample = SimpleNamespace(id="S1", sample_code="UBMC202611006", collection_protocol_id=None)
|
||||||
|
reception = SimpleNamespace(
|
||||||
|
id="R1",
|
||||||
|
reception_time=None,
|
||||||
|
receive_temperature=None,
|
||||||
|
handler_name=None,
|
||||||
|
remark=None,
|
||||||
|
lab_storage_code="UBMC202611006",
|
||||||
|
)
|
||||||
|
production = SimpleNamespace(
|
||||||
|
id="PR1",
|
||||||
|
original_blood_weight_g=None,
|
||||||
|
hes_volume_ml=None,
|
||||||
|
blood_type=None,
|
||||||
|
infectious_four_test_result=None,
|
||||||
|
enriched_blood_weight_g=None,
|
||||||
|
cryopreservation_volume_ml=None,
|
||||||
|
handler_name=None,
|
||||||
|
remark=None,
|
||||||
|
original_blood_volume_ml=None,
|
||||||
|
nucleated_cell_count_1e8=None,
|
||||||
|
inoculation_amount=None,
|
||||||
|
cryopreservation_time=None,
|
||||||
|
storage_total_tubes=None,
|
||||||
|
available_cell_count_1e7=None,
|
||||||
|
)
|
||||||
|
row = _build_row(
|
||||||
|
dataset=DATASET_UBMC,
|
||||||
|
sample=sample,
|
||||||
|
type_name="脐血单个核细胞",
|
||||||
|
party=None,
|
||||||
|
coll=None,
|
||||||
|
hospital=None,
|
||||||
|
reception=reception,
|
||||||
|
production=production,
|
||||||
|
extra=extra,
|
||||||
|
)
|
||||||
|
self.assertEqual(row["infectiousFourCard"], "正常")
|
||||||
|
self.assertEqual(row["labMaterialCode"], "202611006")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -1,19 +1,36 @@
|
|||||||
import unittest
|
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,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -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()
|
||||||
@@ -79,10 +79,13 @@
|
|||||||
"evidence": "用户确认既有 Gitea/Drone Tag 打包已完成,本次不复查或修改流水线。"
|
"evidence": "用户确认既有 Gitea/Drone Tag 打包已完成,本次不复查或修改流水线。"
|
||||||
},
|
},
|
||||||
"permissions": {
|
"permissions": {
|
||||||
"push_task_branch": false,
|
"push_task_branch": true,
|
||||||
"create_pr": false,
|
"create_pr": true,
|
||||||
"write_issue": false,
|
"write_issue": true,
|
||||||
"merge": false,
|
"close_issue": true,
|
||||||
|
"merge": true,
|
||||||
|
"manage_claims": true,
|
||||||
|
"update_issue_labels": true,
|
||||||
"push_tag": false,
|
"push_tag": false,
|
||||||
"deploy": false
|
"deploy": false
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -0,0 +1,21 @@
|
|||||||
|
-- 实验室样本处理 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'
|
||||||
|
);
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
# 恢复 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`
|
||||||
|
|
||||||
|
列表侧同时会从质检完成任务填空(内毒素/真菌/支原体/细菌及母血相关)。
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
-- 软删除实验室样本处理 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;
|
||||||
@@ -0,0 +1,175 @@
|
|||||||
|
-- Issue #102:实验室样本处理数据挂到市场/生产/质检,权限码分端
|
||||||
|
-- 1) 质检管理:调到「入库放行审核」下方
|
||||||
|
-- 2) 存储服务:挂到「缴费财务确认」下方(cellStorage:labSampleProcess:*)
|
||||||
|
-- 3) 生产管理:挂到「废弃物管理」下方(production:labSampleProcess:*;若废弃物菜单缺失则先补齐)
|
||||||
|
-- 4) 拥有 menu:market / menu:production / menu:quality 的角色,授予对应大菜单下入口
|
||||||
|
-- MySQL 5.7,可重复执行
|
||||||
|
|
||||||
|
-- ── 0) 生产管理补齐「废弃物管理」(仅当缺失时,便于排序锚定)────────────────
|
||||||
|
INSERT INTO sys_menu (
|
||||||
|
id, menu_name, parent_id, menu_type, path, component, perms,
|
||||||
|
is_frame, visible, status, tenant_no, order_num, remark,
|
||||||
|
create_by, create_dept_id, create_time, update_by, update_time, del_flag
|
||||||
|
)
|
||||||
|
SELECT
|
||||||
|
INSERT(INSERT(MD5(CONCAT('prod-waste-output:', p.tenant_no, ':', p.id)), 13, 1, '3'), 17, 1, '8'),
|
||||||
|
'废弃物管理', p.id, 'C', 'waste-output',
|
||||||
|
'/production/waste-output/index', 'production:waste-output:list',
|
||||||
|
1, '1', '1', p.tenant_no,
|
||||||
|
COALESCE((SELECT MAX(c.order_num) FROM sys_menu c WHERE c.parent_id = p.id AND c.del_flag = 0), 0) + 1,
|
||||||
|
'issue#102 补齐生产废弃物管理以便台账排序',
|
||||||
|
'migration', '', NOW(), 'migration', NOW(), 0
|
||||||
|
FROM sys_menu p
|
||||||
|
WHERE p.del_flag = 0 AND p.status = '1' AND p.menu_name = '生产管理'
|
||||||
|
AND NOT EXISTS (
|
||||||
|
SELECT 1 FROM sys_menu e
|
||||||
|
WHERE e.tenant_no = p.tenant_no AND e.parent_id = p.id
|
||||||
|
AND e.perms = 'production:waste-output:list' AND e.del_flag = 0
|
||||||
|
);
|
||||||
|
|
||||||
|
-- ── 1) 质检:调到入库放行审核下方(可重复;不连带改动其他菜单 order)────────
|
||||||
|
UPDATE sys_menu lab
|
||||||
|
JOIN sys_menu release_m
|
||||||
|
ON release_m.parent_id = lab.parent_id
|
||||||
|
AND release_m.del_flag = 0
|
||||||
|
AND release_m.menu_name = '入库放行审核'
|
||||||
|
AND release_m.perms = 'quality:storageReleaseReview:list'
|
||||||
|
SET lab.order_num = release_m.order_num + 1,
|
||||||
|
lab.update_by = 'migration',
|
||||||
|
lab.update_time = NOW()
|
||||||
|
WHERE lab.del_flag = 0
|
||||||
|
AND lab.perms = 'biz:labSampleProcess:list'
|
||||||
|
AND lab.path = 'lab-sample-process'
|
||||||
|
AND (lab.order_num IS NULL OR lab.order_num <> release_m.order_num + 1);
|
||||||
|
|
||||||
|
-- ── 2) 存储服务:缴费财务确认下方 ───────────────────────────────────────────
|
||||||
|
INSERT INTO sys_menu (
|
||||||
|
id, menu_name, parent_id, menu_type, path, component, perms,
|
||||||
|
is_frame, visible, status, tenant_no, order_num, remark,
|
||||||
|
create_by, create_dept_id, create_time, update_by, update_time, del_flag
|
||||||
|
)
|
||||||
|
SELECT
|
||||||
|
INSERT(INSERT(MD5(CONCAT('cell-lab-sample-process:', anchor.tenant_no, ':', anchor.id)), 13, 1, '3'), 17, 1, '8'),
|
||||||
|
'实验室样本处理数据', anchor.parent_id, 'C', 'lab-sample-process',
|
||||||
|
'quality-inspection/lab-sample-process/index', 'cellStorage:labSampleProcess:list',
|
||||||
|
1, '1', '1', anchor.tenant_no, anchor.order_num + 1,
|
||||||
|
'市场-存储服务-实验室样本处理数据',
|
||||||
|
'migration', '', NOW(), 'migration', NOW(), 0
|
||||||
|
FROM sys_menu anchor
|
||||||
|
WHERE anchor.del_flag = 0 AND anchor.status = '1'
|
||||||
|
AND anchor.perms = 'biz:cellStoragePaymentConfirm:list'
|
||||||
|
AND anchor.menu_name = '缴费财务确认'
|
||||||
|
AND NOT EXISTS (
|
||||||
|
SELECT 1 FROM sys_menu e
|
||||||
|
WHERE e.tenant_no = anchor.tenant_no
|
||||||
|
AND e.parent_id = anchor.parent_id
|
||||||
|
AND e.perms = 'cellStorage:labSampleProcess:list'
|
||||||
|
AND e.del_flag = 0
|
||||||
|
);
|
||||||
|
|
||||||
|
-- ── 3) 生产管理:废弃物管理下方 ─────────────────────────────────────────────
|
||||||
|
INSERT INTO sys_menu (
|
||||||
|
id, menu_name, parent_id, menu_type, path, component, perms,
|
||||||
|
is_frame, visible, status, tenant_no, order_num, remark,
|
||||||
|
create_by, create_dept_id, create_time, update_by, update_time, del_flag
|
||||||
|
)
|
||||||
|
SELECT
|
||||||
|
INSERT(INSERT(MD5(CONCAT('prod-lab-sample-process:', anchor.tenant_no, ':', anchor.id)), 13, 1, '3'), 17, 1, '8'),
|
||||||
|
'实验室样本处理数据', anchor.parent_id, 'C', 'lab-sample-process',
|
||||||
|
'quality-inspection/lab-sample-process/index', 'production:labSampleProcess:list',
|
||||||
|
1, '1', '1', anchor.tenant_no, anchor.order_num + 1,
|
||||||
|
'生产-生产管理-实验室样本处理数据',
|
||||||
|
'migration', '', NOW(), 'migration', NOW(), 0
|
||||||
|
FROM sys_menu anchor
|
||||||
|
WHERE anchor.del_flag = 0 AND anchor.status = '1'
|
||||||
|
AND anchor.perms = 'production:waste-output:list'
|
||||||
|
AND anchor.menu_name = '废弃物管理'
|
||||||
|
AND NOT EXISTS (
|
||||||
|
SELECT 1 FROM sys_menu e
|
||||||
|
WHERE e.tenant_no = anchor.tenant_no
|
||||||
|
AND e.parent_id = anchor.parent_id
|
||||||
|
AND e.perms = 'production:labSampleProcess:list'
|
||||||
|
AND e.del_flag = 0
|
||||||
|
);
|
||||||
|
|
||||||
|
-- ── 4) 补录 / 导出按钮(三处列表菜单各挂一套)──────────────────────────────
|
||||||
|
INSERT INTO sys_menu (
|
||||||
|
id, menu_name, parent_id, menu_type, path, component, perms,
|
||||||
|
is_frame, visible, status, tenant_no, order_num, remark,
|
||||||
|
create_by, create_dept_id, create_time, update_by, update_time, del_flag
|
||||||
|
)
|
||||||
|
SELECT
|
||||||
|
INSERT(INSERT(MD5(CONCAT('lab-sp-btn:', m.tenant_no, ':', m.id, ':', btn.perms)), 13, 1, '3'), 17, 1, '8'),
|
||||||
|
btn.menu_name, m.id, 'F', '', NULL, btn.perms,
|
||||||
|
1, '1', '1', m.tenant_no, btn.order_num, btn.remark,
|
||||||
|
'migration', '', NOW(), 'migration', NOW(), 0
|
||||||
|
FROM sys_menu m
|
||||||
|
JOIN (
|
||||||
|
SELECT '补录' AS menu_name, 'cellStorage:labSampleProcess:supplement' AS perms, 10 AS order_num,
|
||||||
|
'存储服务-实验室样本处理数据-补录' AS remark, 'cellStorage:labSampleProcess:list' AS parent_perms
|
||||||
|
UNION ALL
|
||||||
|
SELECT '导出', 'cellStorage:labSampleProcess:export', 20,
|
||||||
|
'存储服务-实验室样本处理数据-导出', 'cellStorage:labSampleProcess:list'
|
||||||
|
UNION ALL
|
||||||
|
SELECT '补录', 'production:labSampleProcess:supplement', 10,
|
||||||
|
'生产-实验室样本处理数据-补录', 'production:labSampleProcess:list'
|
||||||
|
UNION ALL
|
||||||
|
SELECT '导出', 'production:labSampleProcess:export', 20,
|
||||||
|
'生产-实验室样本处理数据-导出', 'production:labSampleProcess:list'
|
||||||
|
) btn ON btn.parent_perms = m.perms
|
||||||
|
WHERE m.del_flag = 0 AND m.status = '1'
|
||||||
|
AND NOT EXISTS (
|
||||||
|
SELECT 1 FROM sys_menu e
|
||||||
|
WHERE e.tenant_no = m.tenant_no AND e.parent_id = m.id
|
||||||
|
AND e.perms = btn.perms AND e.del_flag = 0
|
||||||
|
);
|
||||||
|
|
||||||
|
-- ── 5) 按顶级大菜单授权对应入口(含列表/补录/导出)─────────────────────────
|
||||||
|
INSERT INTO sys_role_menu (
|
||||||
|
id, role_id, menu_id, tenant_no, order_num, remark,
|
||||||
|
create_by, create_dept_id, create_time, update_by, update_time, del_flag
|
||||||
|
)
|
||||||
|
SELECT
|
||||||
|
INSERT(INSERT(MD5(CONCAT('lab-sp-rm:', r.tenant_no, ':', r.id, ':', m.id)), 13, 1, '3'), 17, 1, '8'),
|
||||||
|
r.id, m.id, r.tenant_no, NULL,
|
||||||
|
CONCAT('issue#102 grant from ', map.top_perms),
|
||||||
|
'migration', '', NOW(), 'migration', NOW(), 0
|
||||||
|
FROM (
|
||||||
|
SELECT 'menu:market' AS top_perms, 'cellStorage:labSampleProcess:list' AS list_perms
|
||||||
|
UNION ALL SELECT 'menu:market', 'cellStorage:labSampleProcess:supplement'
|
||||||
|
UNION ALL SELECT 'menu:market', 'cellStorage:labSampleProcess:export'
|
||||||
|
UNION ALL SELECT 'menu:production', 'production:labSampleProcess:list'
|
||||||
|
UNION ALL SELECT 'menu:production', 'production:labSampleProcess:supplement'
|
||||||
|
UNION ALL SELECT 'menu:production', 'production:labSampleProcess:export'
|
||||||
|
UNION ALL SELECT 'menu:quality', 'biz:labSampleProcess:list'
|
||||||
|
UNION ALL SELECT 'menu:quality', 'biz:labSampleProcess:supplement'
|
||||||
|
UNION ALL SELECT 'menu:quality', 'biz:labSampleProcess:export'
|
||||||
|
) map
|
||||||
|
JOIN sys_role r ON r.del_flag = 0
|
||||||
|
JOIN sys_role_menu src
|
||||||
|
ON src.role_id = r.id AND src.tenant_no = r.tenant_no AND src.del_flag = 0
|
||||||
|
JOIN sys_menu top
|
||||||
|
ON top.id = src.menu_id AND top.tenant_no = src.tenant_no AND top.del_flag = 0
|
||||||
|
AND top.perms = map.top_perms
|
||||||
|
JOIN sys_menu m
|
||||||
|
ON m.tenant_no = r.tenant_no AND m.del_flag = 0 AND m.status = '1'
|
||||||
|
AND m.perms = map.list_perms
|
||||||
|
WHERE NOT EXISTS (
|
||||||
|
SELECT 1 FROM sys_role_menu existing
|
||||||
|
WHERE existing.role_id = r.id
|
||||||
|
AND existing.menu_id = m.id
|
||||||
|
AND existing.tenant_no = r.tenant_no
|
||||||
|
AND existing.del_flag = 0
|
||||||
|
);
|
||||||
|
|
||||||
|
-- 核对
|
||||||
|
SELECT p.menu_name AS parent_name, c.menu_name, c.path, c.perms, c.order_num
|
||||||
|
FROM sys_menu c
|
||||||
|
JOIN sys_menu p ON p.id = c.parent_id
|
||||||
|
WHERE c.del_flag = 0
|
||||||
|
AND (
|
||||||
|
c.perms LIKE '%labSampleProcess%'
|
||||||
|
OR (c.menu_name IN ('缴费财务确认', '废弃物管理', '入库放行审核')
|
||||||
|
AND p.menu_name IN ('存储服务', '生产管理', '质检管理'))
|
||||||
|
)
|
||||||
|
ORDER BY p.menu_name, c.order_num, c.menu_name;
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
-- 纠正实验室样本处理部门 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;
|
||||||
@@ -0,0 +1,120 @@
|
|||||||
|
-- 实验室样本处理数据:补充表 + 一级模块菜单/按钮权限(不自动授权角色)
|
||||||
|
-- MySQL 5.7,可重复执行
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS biz_lab_sample_processing_extra (
|
||||||
|
id VARCHAR(64) NOT NULL,
|
||||||
|
dataset VARCHAR(16) NOT NULL COMMENT 'hsc|ubmc|msc',
|
||||||
|
sample_code VARCHAR(32) NOT NULL COMMENT '样本编码',
|
||||||
|
payload_json TEXT NULL COMMENT '补充字段 JSON',
|
||||||
|
tenant_no VARCHAR(64) NOT NULL,
|
||||||
|
order_num INT NULL,
|
||||||
|
remark VARCHAR(512) NULL,
|
||||||
|
create_by VARCHAR(64) NULL,
|
||||||
|
create_dept_id VARCHAR(64) NOT NULL DEFAULT '',
|
||||||
|
create_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
update_by VARCHAR(64) NULL,
|
||||||
|
update_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||||
|
del_flag SMALLINT NOT NULL DEFAULT 0,
|
||||||
|
PRIMARY KEY (id),
|
||||||
|
KEY ix_lab_sample_extra_tenant_ds_code (tenant_no, dataset, sample_code, del_flag)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||||
|
|
||||||
|
-- 挂到与「质检」同一 Web 虚拟根下(复用 menu:quality 的 parent_id)
|
||||||
|
INSERT INTO sys_menu (
|
||||||
|
id, menu_name, parent_id, menu_type, path, component, perms,
|
||||||
|
is_frame, visible, status, tenant_no, order_num, remark,
|
||||||
|
create_by, create_dept_id, create_time, update_by, update_time, del_flag
|
||||||
|
)
|
||||||
|
SELECT
|
||||||
|
MD5(CONCAT(quality.tenant_no, ':menu:lab-sample-processing')),
|
||||||
|
'实验室样本处理数据', quality.parent_id, 'M', '/lab-sample-processing', '/index/index',
|
||||||
|
'menu:lab-sample-processing', 1, '1', '1', quality.tenant_no,
|
||||||
|
COALESCE(quality.order_num, 50) + 1,
|
||||||
|
'20261104 会议:造血/单个核/间充质台账',
|
||||||
|
'migration', '', NOW(), 'migration', NOW(), 0
|
||||||
|
FROM sys_menu quality
|
||||||
|
WHERE quality.perms = 'menu:quality' AND quality.del_flag = 0 AND quality.status = '1'
|
||||||
|
AND NOT EXISTS (
|
||||||
|
SELECT 1 FROM sys_menu e
|
||||||
|
WHERE e.tenant_no = quality.tenant_no AND e.perms = 'menu:lab-sample-processing' AND e.del_flag = 0
|
||||||
|
);
|
||||||
|
|
||||||
|
INSERT INTO sys_menu (
|
||||||
|
id, menu_name, parent_id, menu_type, path, component, perms,
|
||||||
|
is_frame, visible, status, tenant_no, order_num, remark,
|
||||||
|
create_by, create_dept_id, create_time, update_by, update_time, del_flag
|
||||||
|
)
|
||||||
|
SELECT
|
||||||
|
MD5(CONCAT(p.tenant_no, ':lab:sample-processing:list')),
|
||||||
|
'造血干细胞数据', p.id, 'C', 'lab-sample-processing/hsc',
|
||||||
|
'/lab-sample-processing/hsc/index', 'lab:sample-processing:list',
|
||||||
|
1, '1', '1', p.tenant_no, 10, '造血干细胞数据列表',
|
||||||
|
'migration', '', NOW(), 'migration', NOW(), 0
|
||||||
|
FROM sys_menu p
|
||||||
|
WHERE p.perms = 'menu:lab-sample-processing' AND p.del_flag = 0 AND p.status = '1'
|
||||||
|
AND NOT EXISTS (
|
||||||
|
SELECT 1 FROM sys_menu e
|
||||||
|
WHERE e.tenant_no = p.tenant_no AND e.path = 'lab-sample-processing/hsc' AND e.del_flag = 0
|
||||||
|
);
|
||||||
|
|
||||||
|
INSERT INTO sys_menu (
|
||||||
|
id, menu_name, parent_id, menu_type, path, component, perms,
|
||||||
|
is_frame, visible, status, tenant_no, order_num, remark,
|
||||||
|
create_by, create_dept_id, create_time, update_by, update_time, del_flag
|
||||||
|
)
|
||||||
|
SELECT
|
||||||
|
MD5(CONCAT(p.tenant_no, ':lab:sample-processing:ubmc')),
|
||||||
|
'单个核数据', p.id, 'C', 'lab-sample-processing/ubmc',
|
||||||
|
'/lab-sample-processing/ubmc/index', 'lab:sample-processing:list',
|
||||||
|
1, '1', '1', p.tenant_no, 20, '单个核数据列表',
|
||||||
|
'migration', '', NOW(), 'migration', NOW(), 0
|
||||||
|
FROM sys_menu p
|
||||||
|
WHERE p.perms = 'menu:lab-sample-processing' AND p.del_flag = 0 AND p.status = '1'
|
||||||
|
AND NOT EXISTS (
|
||||||
|
SELECT 1 FROM sys_menu e
|
||||||
|
WHERE e.tenant_no = p.tenant_no AND e.path = 'lab-sample-processing/ubmc' AND e.del_flag = 0
|
||||||
|
);
|
||||||
|
|
||||||
|
INSERT INTO sys_menu (
|
||||||
|
id, menu_name, parent_id, menu_type, path, component, perms,
|
||||||
|
is_frame, visible, status, tenant_no, order_num, remark,
|
||||||
|
create_by, create_dept_id, create_time, update_by, update_time, del_flag
|
||||||
|
)
|
||||||
|
SELECT
|
||||||
|
MD5(CONCAT(p.tenant_no, ':lab:sample-processing:msc')),
|
||||||
|
'脐带间充质干细胞数据', p.id, 'C', 'lab-sample-processing/msc',
|
||||||
|
'/lab-sample-processing/msc/index', 'lab:sample-processing:list',
|
||||||
|
1, '1', '1', p.tenant_no, 30, '脐带间充质干细胞数据列表',
|
||||||
|
'migration', '', NOW(), 'migration', NOW(), 0
|
||||||
|
FROM sys_menu p
|
||||||
|
WHERE p.perms = 'menu:lab-sample-processing' AND p.del_flag = 0 AND p.status = '1'
|
||||||
|
AND NOT EXISTS (
|
||||||
|
SELECT 1 FROM sys_menu e
|
||||||
|
WHERE e.tenant_no = p.tenant_no AND e.path = 'lab-sample-processing/msc' AND e.del_flag = 0
|
||||||
|
);
|
||||||
|
|
||||||
|
-- 编辑按钮挂在列表菜单下(三页共用同一 list 权限父节点:造血页)
|
||||||
|
INSERT INTO sys_menu (
|
||||||
|
id, menu_name, parent_id, menu_type, path, component, perms,
|
||||||
|
is_frame, visible, status, tenant_no, order_num, remark,
|
||||||
|
create_by, create_dept_id, create_time, update_by, update_time, del_flag
|
||||||
|
)
|
||||||
|
SELECT
|
||||||
|
MD5(CONCAT(p.tenant_no, ':', btn.perms)),
|
||||||
|
btn.menu_name, p.id, 'F', '', NULL, btn.perms,
|
||||||
|
1, '0', '1', p.tenant_no, btn.order_num, btn.remark,
|
||||||
|
'migration', '', NOW(), 'migration', NOW(), 0
|
||||||
|
FROM sys_menu p
|
||||||
|
JOIN (
|
||||||
|
SELECT '市场字段编辑' AS menu_name, 'lab:sample-processing:market:edit' AS perms, 1 AS order_num, '仅可编辑市场部门字段' AS remark
|
||||||
|
UNION ALL SELECT '生产字段编辑', 'lab:sample-processing:production:edit', 2, '仅可编辑生产部门字段'
|
||||||
|
UNION ALL SELECT '质检字段编辑', 'lab:sample-processing:qc:edit', 3, '仅可编辑质检部门字段'
|
||||||
|
UNION ALL SELECT '部门主管', 'lab:sample-processing:manager', 4, '可编辑全部部门字段'
|
||||||
|
) btn
|
||||||
|
WHERE p.perms = 'lab:sample-processing:list'
|
||||||
|
AND p.path = 'lab-sample-processing/hsc'
|
||||||
|
AND p.del_flag = 0 AND p.status = '1'
|
||||||
|
AND NOT EXISTS (
|
||||||
|
SELECT 1 FROM sys_menu e
|
||||||
|
WHERE e.tenant_no = p.tenant_no AND e.perms = btn.perms AND e.del_flag = 0
|
||||||
|
);
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
-- 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,265 @@
|
|||||||
|
-- UC 入库编码自动派发:脐带MSC原代培养(内置模版)5 步
|
||||||
|
-- 步骤:原代培养 → 半换液 → 二次贴壁 → 重铺 → 冻存(不含传代)
|
||||||
|
-- 内容从既有「干细胞培养(内置模版)」/ MSC培养-BUILTIN 按 process_code 拷贝
|
||||||
|
-- 幂等:已存在同名内置集合则跳过主数据创建-- 生产历史空任务工单回补(二选一,勿重复对同一工单各跑一遍):
|
||||||
|
-- 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 = src.tenant_no
|
||||||
|
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 = s.route_id 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 = s.route_id 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 = s.route_id 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 = s.route_id 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 = s.route_id 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 = r.tenant_no
|
||||||
|
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 = s.id AND x.del_flag = 0
|
||||||
|
);
|
||||||
@@ -0,0 +1,409 @@
|
|||||||
|
-- 【一次性回补】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。
|
||||||
|
|
||||||
|
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 = @uc_route_id
|
||||||
|
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_unicode_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 = wo.reception_id
|
||||||
|
AND rec.tenant_no = wo.tenant_no
|
||||||
|
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 = wo.id
|
||||||
|
AND t.tenant_no = wo.tenant_no
|
||||||
|
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 LIKE CONCAT('RW', @task_day, '%')
|
||||||
|
);
|
||||||
|
|
||||||
|
UPDATE tmp_uc_wo_backfill
|
||||||
|
SET
|
||||||
|
task_id = UPPER(REPLACE(UUID(), '-', '')),
|
||||||
|
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 = c.route_id
|
||||||
|
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 = c.work_order_id
|
||||||
|
AND t.tenant_no = c.tenant_no
|
||||||
|
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_unicode_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(REPLACE(UUID(), '-', '')),
|
||||||
|
rs.step_order
|
||||||
|
FROM tmp_uc_wo_backfill c
|
||||||
|
INNER JOIN biz_process_route_step rs
|
||||||
|
ON rs.route_id = c.route_id
|
||||||
|
AND rs.del_flag = 0
|
||||||
|
WHERE @uc_ready = 1
|
||||||
|
AND EXISTS (
|
||||||
|
SELECT 1 FROM biz_production_task t
|
||||||
|
WHERE t.id = c.task_id 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 = m.route_step_id
|
||||||
|
AND rs.del_flag = 0
|
||||||
|
WHERE NOT EXISTS (
|
||||||
|
SELECT 1 FROM biz_production_task_step x
|
||||||
|
WHERE x.id = m.task_step_id
|
||||||
|
);
|
||||||
|
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
-- 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(REPLACE(UUID(), '-', '')),
|
||||||
|
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 = m.route_step_id
|
||||||
|
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(REPLACE(UUID(), '-', '')),
|
||||||
|
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 = m.route_step_id
|
||||||
|
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(REPLACE(UUID(), '-', '')),
|
||||||
|
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 = m.route_step_id
|
||||||
|
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(REPLACE(UUID(), '-', '')),
|
||||||
|
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 = m.route_step_id
|
||||||
|
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 = wo.id
|
||||||
|
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 = wo.id
|
||||||
|
AND t.tenant_no = wo.tenant_no
|
||||||
|
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 = t.id AND s.del_flag = 0) AS step_count
|
||||||
|
FROM tmp_uc_wo_backfill c
|
||||||
|
LEFT JOIN biz_production_work_order wo ON wo.id = c.work_order_id
|
||||||
|
LEFT JOIN biz_production_task t ON t.id = c.task_id 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,2 @@
|
|||||||
|
schema: spec-driven
|
||||||
|
created: 2026-11-12
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
## Context
|
||||||
|
|
||||||
|
附件三张表字段覆盖市场采集信息、实验室接收/处理与质检结果。系统内对应源主要为:
|
||||||
|
|
||||||
|
- 市场:`biz_protocol_party_customer`、`biz_protocol_collection_info`、`biz_collection_hospital`、`biz_protocol_sample`
|
||||||
|
- 生产/接收:`biz_sample_reception`、`biz_sample_production_reception`
|
||||||
|
- 质检:生产接收传染四项、储存证质检 payload、检查项结果;缺口进补充表
|
||||||
|
|
||||||
|
## Decisions
|
||||||
|
|
||||||
|
1. **数据集**:`hsc`(造血)、`ubmc`(单个核)、`msc`(脐带间充质),以样本类型名 / 编码前缀识别。
|
||||||
|
2. **权限码**:
|
||||||
|
- 列表:`lab:sample-processing:list`(三子页共用读)
|
||||||
|
- 部门编辑:`lab:sample-processing:market:edit` / `production:edit` / `qc:edit`
|
||||||
|
- 主管:`lab:sample-processing:manager`(可编辑全部部门字段)
|
||||||
|
3. **读写**:列表聚合只读源表 + 补充 JSON;更新时按字段 `source` 回写源表或补充表,服务端强制部门 ACL。
|
||||||
|
4. **UI**:P01 列表 + 筛选 + 导出;行内编辑弹窗按部门分区,无权字段只读。
|
||||||
|
5. **Figma**:MCP 授权不可用,按现有 Fresh Mint 列表页实现;合入后用户做视觉验收。
|
||||||
|
|
||||||
|
## Risks
|
||||||
|
|
||||||
|
- 历史 Excel 手工列与系统字段不完全一一对应,未映射列落补充表,避免阻断上线。
|
||||||
|
- 菜单种子不自动授权角色,需管理员分配。
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
## Why
|
||||||
|
|
||||||
|
2026-11-04 需求会议要求按线上三张实验室样本处理表(造血干细胞 / 单个核 / 脐带间充质)在系统中单独建模块,按市场、生产、质检拆分可编辑字段,支持筛选与导出。现有业务数据分散在协议、样本接收、生产接收与质检等表,缺少统一台账视图。
|
||||||
|
|
||||||
|
## What Changes
|
||||||
|
|
||||||
|
- 新增 Web 一级模块「实验室样本处理数据」,下挂三个子模块对应三张表。
|
||||||
|
- 按样本编码从现有业务表聚合展示全字段;部门员工可读全部、只写本部门字段;主管可写全部部门字段。
|
||||||
|
- 支持关键词/时间筛选与 Excel 导出。
|
||||||
|
- 无法直接回写源表的字段写入补充表 `biz_lab_sample_processing_extra`。
|
||||||
|
|
||||||
|
## Capabilities
|
||||||
|
|
||||||
|
### New Capabilities
|
||||||
|
|
||||||
|
- `lab-sample-processing-data`: 实验室样本处理数据聚合台账、部门字段 ACL、筛选导出
|
||||||
|
|
||||||
|
### Modified Capabilities
|
||||||
|
|
||||||
|
- (无)
|
||||||
|
|
||||||
|
## Impact
|
||||||
|
|
||||||
|
- **backend**:聚合服务、API、补充表、菜单权限
|
||||||
|
- **web-admin**:三子模块列表页、编辑弹窗、导出
|
||||||
|
- **docs/sql**:结构 + 菜单种子
|
||||||
|
- **不改** mobile-h5 / mobile-oa-h5
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
## ADDED Requirements
|
||||||
|
|
||||||
|
### Requirement: 三子模块台账
|
||||||
|
|
||||||
|
系统 SHALL 提供「实验室样本处理数据」模块,包含造血干细胞、单个核、脐带间充质三个子模块;每个子模块按样本展示该表全部约定字段。
|
||||||
|
|
||||||
|
#### Scenario: 按数据集查询
|
||||||
|
|
||||||
|
- **WHEN** 用户打开造血干细胞子模块并具备列表权限
|
||||||
|
- **THEN** 系统仅返回造血干细胞数据集样本行,并包含市场/生产/质检字段聚合结果
|
||||||
|
|
||||||
|
### Requirement: 部门字段编辑权限
|
||||||
|
|
||||||
|
系统 SHALL 允许具备列表权限的用户查看全部字段;普通员工仅可编辑本部门字段;具备主管权限的用户可编辑全部部门字段。服务端 MUST 拒绝无权字段写入。
|
||||||
|
|
||||||
|
#### Scenario: 生产员工改市场字段被拒
|
||||||
|
|
||||||
|
- **WHEN** 仅有生产编辑权限的用户提交市场部门字段变更
|
||||||
|
- **THEN** 系统拒绝该请求且不持久化无权字段
|
||||||
|
|
||||||
|
#### Scenario: 主管可改全部
|
||||||
|
|
||||||
|
- **WHEN** 具备主管权限的用户提交跨部门字段变更
|
||||||
|
- **THEN** 系统接受并回写对应数据源或补充表
|
||||||
|
|
||||||
|
### Requirement: 筛选与导出
|
||||||
|
|
||||||
|
系统 SHALL 支持按样本编码、姓名关键词及接收/采集时间范围筛选,并导出当前筛选结果为 Excel。
|
||||||
|
|
||||||
|
#### Scenario: 导出当前筛选
|
||||||
|
|
||||||
|
- **WHEN** 用户在筛选条件下点击导出
|
||||||
|
- **THEN** 下载的表格列与当前子模块字段目录一致,行集与列表筛选一致
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
## 1. 规格与数据
|
||||||
|
|
||||||
|
- [x] 1.1 建立 OpenSpec 变更与字段/权限设计
|
||||||
|
- [x] 1.2 定义三数据集字段目录与部门归属、回写源
|
||||||
|
|
||||||
|
## 2. 后端
|
||||||
|
|
||||||
|
- [x] 2.1 补充表模型与迁移 SQL、菜单种子
|
||||||
|
- [x] 2.2 聚合列表 / 详情 / 更新 / 导出 API 与部门 ACL
|
||||||
|
- [x] 2.3 单元测试:数据集识别、字段 ACL、无权拒绝
|
||||||
|
|
||||||
|
## 3. 前端
|
||||||
|
|
||||||
|
- [x] 3.1 共享列表页组件(筛选、编辑、导出)
|
||||||
|
- [x] 3.2 三子模块路由与菜单码
|
||||||
|
- [x] 3.3 API 客户端
|
||||||
|
|
||||||
|
## 4. 验证
|
||||||
|
|
||||||
|
- [x] 4.1 受影响单元测试
|
||||||
|
- [ ] 4.2 字段一致性/菜单说明回写工单(凭据就绪后)
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
import request from '@/utils/http'
|
||||||
|
|
||||||
|
export type LabSampleDataset = 'hsc' | 'ubmc' | 'msc'
|
||||||
|
|
||||||
|
export interface LabSampleFieldMeta {
|
||||||
|
key: string
|
||||||
|
label: string
|
||||||
|
dept: 'market' | 'production' | 'qc'
|
||||||
|
source: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface LabSampleAcl {
|
||||||
|
canList?: boolean
|
||||||
|
isManager?: boolean
|
||||||
|
editableDepts?: string[]
|
||||||
|
deptFlags?: Record<string, boolean>
|
||||||
|
}
|
||||||
|
|
||||||
|
export function fetchLabSampleMeta(dataset: LabSampleDataset) {
|
||||||
|
return request.get<{
|
||||||
|
dataset: LabSampleDataset
|
||||||
|
label: string
|
||||||
|
fields: LabSampleFieldMeta[]
|
||||||
|
acl: LabSampleAcl
|
||||||
|
}>({
|
||||||
|
url: `/web/admin/lab-sample-processing/meta/${dataset}`
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export function fetchLabSampleList(
|
||||||
|
dataset: LabSampleDataset,
|
||||||
|
params: {
|
||||||
|
keyword?: string
|
||||||
|
dateFrom?: string
|
||||||
|
dateTo?: string
|
||||||
|
page?: number
|
||||||
|
pageSize?: number
|
||||||
|
}
|
||||||
|
) {
|
||||||
|
return request.get<{
|
||||||
|
list: Record<string, any>[]
|
||||||
|
total: number
|
||||||
|
page: number
|
||||||
|
pageSize: number
|
||||||
|
fields: LabSampleFieldMeta[]
|
||||||
|
acl: LabSampleAcl
|
||||||
|
}>({
|
||||||
|
url: `/web/admin/lab-sample-processing/${dataset}/list`,
|
||||||
|
params
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export function updateLabSampleRow(
|
||||||
|
dataset: LabSampleDataset,
|
||||||
|
sampleCode: string,
|
||||||
|
payload: Record<string, any>
|
||||||
|
) {
|
||||||
|
return request.put<Record<string, any>>({
|
||||||
|
url: `/web/admin/lab-sample-processing/${dataset}/${encodeURIComponent(sampleCode)}`,
|
||||||
|
data: { payload }
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export function exportLabSampleUrl(
|
||||||
|
dataset: LabSampleDataset,
|
||||||
|
params: { keyword?: string; dateFrom?: string; dateTo?: string }
|
||||||
|
) {
|
||||||
|
const q = new URLSearchParams()
|
||||||
|
if (params.keyword) q.set('keyword', params.keyword)
|
||||||
|
if (params.dateFrom) q.set('dateFrom', params.dateFrom)
|
||||||
|
if (params.dateTo) q.set('dateTo', params.dateTo)
|
||||||
|
const qs = q.toString()
|
||||||
|
return `/api/web/admin/lab-sample-processing/${dataset}/export${qs ? `?${qs}` : ''}`
|
||||||
|
}
|
||||||
@@ -190,6 +190,17 @@ export const sqxpAdminRoutes: AppRouteRecord[] = [
|
|||||||
menuCode: 'biz:cellStoragePaymentConfirm:list'
|
menuCode: 'biz:cellStoragePaymentConfirm:list'
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
id: 'CEL0000000000000000000000000LSP1',
|
||||||
|
name: 'CellStorageLabSampleProcess',
|
||||||
|
path: 'lab-sample-process',
|
||||||
|
component: '/quality-inspection/lab-sample-process/index',
|
||||||
|
meta: {
|
||||||
|
title: '实验室样本处理数据',
|
||||||
|
keepAlive: true,
|
||||||
|
menuCode: 'cellStorage:labSampleProcess:list'
|
||||||
|
}
|
||||||
|
},
|
||||||
// 市场侧入库放行审核(总览)暂下线:改由生产/质检入口审核
|
// 市场侧入库放行审核(总览)暂下线:改由生产/质检入口审核
|
||||||
// {
|
// {
|
||||||
// id: '70000000000000000000000000000011',
|
// id: '70000000000000000000000000000011',
|
||||||
@@ -922,6 +933,17 @@ export const sqxpAdminRoutes: AppRouteRecord[] = [
|
|||||||
keepAlive: true,
|
keepAlive: true,
|
||||||
menuCode: 'production:waste-output:list'
|
menuCode: 'production:waste-output:list'
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'PRM0000000000000000000000000LSP1',
|
||||||
|
name: 'ProductionLabSampleProcess',
|
||||||
|
path: 'lab-sample-process',
|
||||||
|
component: '/quality-inspection/lab-sample-process/index',
|
||||||
|
meta: {
|
||||||
|
title: '实验室样本处理数据',
|
||||||
|
keepAlive: true,
|
||||||
|
menuCode: 'production:labSampleProcess:list'
|
||||||
|
}
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -1123,17 +1145,6 @@ export const sqxpAdminRoutes: AppRouteRecord[] = [
|
|||||||
menuCode: 'biz:sampleReception:list'
|
menuCode: 'biz:sampleReception:list'
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
{
|
|
||||||
id: '70000000000000000000000000000015',
|
|
||||||
name: 'QualityInspectionLabSampleProcess',
|
|
||||||
path: 'lab-sample-process',
|
|
||||||
component: '/quality-inspection/lab-sample-process/index',
|
|
||||||
meta: {
|
|
||||||
title: '实验室样本处理数据',
|
|
||||||
keepAlive: true,
|
|
||||||
menuCode: 'biz:labSampleProcess:list'
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
id: '70000000000000000000000000000007',
|
id: '70000000000000000000000000000007',
|
||||||
name: 'QualityInspectionQcWorkOrder',
|
name: 'QualityInspectionQcWorkOrder',
|
||||||
@@ -1201,6 +1212,17 @@ export const sqxpAdminRoutes: AppRouteRecord[] = [
|
|||||||
menuCode: 'quality:storageReleaseReview:list'
|
menuCode: 'quality:storageReleaseReview:list'
|
||||||
},
|
},
|
||||||
props: { reviewRole: 'qc' }
|
props: { reviewRole: 'qc' }
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: '70000000000000000000000000000015',
|
||||||
|
name: 'QualityInspectionLabSampleProcess',
|
||||||
|
path: 'lab-sample-process',
|
||||||
|
component: '/quality-inspection/lab-sample-process/index',
|
||||||
|
meta: {
|
||||||
|
title: '实验室样本处理数据',
|
||||||
|
keepAlive: true,
|
||||||
|
menuCode: 'biz:labSampleProcess:list'
|
||||||
|
}
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -1313,6 +1335,59 @@ 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,342 @@
|
|||||||
|
<!-- 实验室样本处理数据 — 共享列表页 -->
|
||||||
|
<template>
|
||||||
|
<div class="page-container">
|
||||||
|
<section class="panel">
|
||||||
|
<div class="panel-top">
|
||||||
|
<h2 class="title-bar-heading">{{ pageTitle }}</h2>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="filter-block">
|
||||||
|
<el-form :model="searchForm" class="filter-form" @submit.prevent>
|
||||||
|
<div class="filter-grid">
|
||||||
|
<el-form-item label="关键词">
|
||||||
|
<el-input
|
||||||
|
v-model="searchForm.keyword"
|
||||||
|
placeholder="样本编码/姓名"
|
||||||
|
clearable
|
||||||
|
/>
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="时间范围">
|
||||||
|
<el-date-picker
|
||||||
|
v-model="dateRange"
|
||||||
|
type="daterange"
|
||||||
|
range-separator="至"
|
||||||
|
start-placeholder="开始日期"
|
||||||
|
end-placeholder="结束日期"
|
||||||
|
value-format="YYYY-MM-DD"
|
||||||
|
style="width: 100%"
|
||||||
|
/>
|
||||||
|
</el-form-item>
|
||||||
|
</div>
|
||||||
|
<div class="filter-actions-row">
|
||||||
|
<div class="filter-actions-end">
|
||||||
|
<el-button class="btn-ghost" @click="handleReset">
|
||||||
|
<el-icon><RefreshLeft /></el-icon>重置
|
||||||
|
</el-button>
|
||||||
|
<el-button class="btn-main" type="primary" @click="handleSearch">
|
||||||
|
<el-icon><Search /></el-icon>搜索
|
||||||
|
</el-button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</el-form>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="list-toolbar">
|
||||||
|
<div class="list-toolbar-row">
|
||||||
|
<div class="list-toolbar-selected">
|
||||||
|
共 <span class="sel-num">{{ pagination.total }}</span> 条
|
||||||
|
</div>
|
||||||
|
<el-button class="btn-main" type="primary" :loading="exporting" @click="handleExport">
|
||||||
|
<el-icon><Download /></el-icon>
|
||||||
|
导出
|
||||||
|
</el-button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="list-body list-wrap">
|
||||||
|
<el-table
|
||||||
|
class="list-table"
|
||||||
|
:data="tableData"
|
||||||
|
v-loading="loading"
|
||||||
|
stripe
|
||||||
|
size="small"
|
||||||
|
row-key="id"
|
||||||
|
>
|
||||||
|
<el-table-column
|
||||||
|
type="index"
|
||||||
|
label="序号"
|
||||||
|
min-width="68"
|
||||||
|
align="center"
|
||||||
|
header-align="center"
|
||||||
|
:index="(index) => (pagination.page - 1) * pagination.pageSize + index + 1"
|
||||||
|
/>
|
||||||
|
<el-table-column
|
||||||
|
v-for="col in visibleColumns"
|
||||||
|
:key="col.key"
|
||||||
|
:prop="col.key"
|
||||||
|
:label="col.label"
|
||||||
|
min-width="140"
|
||||||
|
align="center"
|
||||||
|
header-align="center"
|
||||||
|
show-overflow-tooltip
|
||||||
|
/>
|
||||||
|
<el-table-column
|
||||||
|
label="操作"
|
||||||
|
fixed="right"
|
||||||
|
min-width="260"
|
||||||
|
align="center"
|
||||||
|
header-align="center"
|
||||||
|
>
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-button
|
||||||
|
v-if="(acl.editableDepts || []).length"
|
||||||
|
class="btn-ghost"
|
||||||
|
link
|
||||||
|
type="primary"
|
||||||
|
@click="openEdit(row)"
|
||||||
|
>
|
||||||
|
<el-icon><Edit /></el-icon>
|
||||||
|
编辑
|
||||||
|
</el-button>
|
||||||
|
<span v-else class="text-muted">只读</span>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
</el-table>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="pagination list-pager-bar">
|
||||||
|
<el-pagination
|
||||||
|
v-model:current-page="pagination.page"
|
||||||
|
v-model:page-size="pagination.pageSize"
|
||||||
|
:total="pagination.total"
|
||||||
|
:page-sizes="[10, 20, 50, 100]"
|
||||||
|
layout="total, sizes, prev, pager, next, jumper"
|
||||||
|
@size-change="loadData"
|
||||||
|
@current-change="loadData"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<el-dialog
|
||||||
|
v-model="editVisible"
|
||||||
|
class="dialog-form-layout"
|
||||||
|
:title="`编辑 — ${editRow?.sampleCode || ''}`"
|
||||||
|
width="860px"
|
||||||
|
align-center
|
||||||
|
destroy-on-close
|
||||||
|
append-to-body
|
||||||
|
>
|
||||||
|
<el-form label-position="top" class="form-grid-2" v-loading="saving">
|
||||||
|
<template v-for="group in editGroups" :key="group.dept">
|
||||||
|
<div class="form-col-span-2 dept-title">{{ group.label }}</div>
|
||||||
|
<el-form-item v-for="f in group.fields" :key="f.key" :label="f.label">
|
||||||
|
<el-input
|
||||||
|
v-model="editForm[f.key]"
|
||||||
|
:disabled="!canEditDept(f.dept)"
|
||||||
|
clearable
|
||||||
|
/>
|
||||||
|
</el-form-item>
|
||||||
|
</template>
|
||||||
|
</el-form>
|
||||||
|
<template #footer>
|
||||||
|
<el-button class="btn-ghost" @click="editVisible = false">
|
||||||
|
<el-icon><Close /></el-icon>取消
|
||||||
|
</el-button>
|
||||||
|
<el-button class="btn-main" type="primary" :loading="saving" @click="submitEdit">
|
||||||
|
<el-icon><Check /></el-icon>确定
|
||||||
|
</el-button>
|
||||||
|
</template>
|
||||||
|
</el-dialog>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, onMounted, reactive, ref } from 'vue'
|
||||||
|
import { Check, Close, Download, Edit, RefreshLeft, Search } from '@element-plus/icons-vue'
|
||||||
|
import { ElMessage } from 'element-plus'
|
||||||
|
import {
|
||||||
|
fetchLabSampleList,
|
||||||
|
updateLabSampleRow,
|
||||||
|
type LabSampleAcl,
|
||||||
|
type LabSampleDataset,
|
||||||
|
type LabSampleFieldMeta
|
||||||
|
} from '@/api/lab-sample-processing'
|
||||||
|
|
||||||
|
const props = defineProps<{
|
||||||
|
dataset: LabSampleDataset
|
||||||
|
title: string
|
||||||
|
}>()
|
||||||
|
|
||||||
|
const pageTitle = computed(() => props.title)
|
||||||
|
|
||||||
|
const loading = ref(false)
|
||||||
|
const saving = ref(false)
|
||||||
|
const exporting = ref(false)
|
||||||
|
const tableData = ref<Record<string, any>[]>([])
|
||||||
|
const fields = ref<LabSampleFieldMeta[]>([])
|
||||||
|
const acl = ref<LabSampleAcl>({})
|
||||||
|
const searchForm = reactive({ keyword: '' })
|
||||||
|
const dateRange = ref<string[] | null>(null)
|
||||||
|
const pagination = reactive({ page: 1, pageSize: 20, total: 0 })
|
||||||
|
|
||||||
|
const editVisible = ref(false)
|
||||||
|
const editRow = ref<Record<string, any> | null>(null)
|
||||||
|
const editForm = reactive<Record<string, any>>({})
|
||||||
|
|
||||||
|
const deptLabel: Record<string, string> = {
|
||||||
|
market: '市场字段',
|
||||||
|
production: '生产字段',
|
||||||
|
qc: '质检字段'
|
||||||
|
}
|
||||||
|
|
||||||
|
const visibleColumns = computed(() => fields.value)
|
||||||
|
|
||||||
|
const editGroups = computed(() => {
|
||||||
|
const groups = ['market', 'production', 'qc'].map((dept) => ({
|
||||||
|
dept,
|
||||||
|
label: deptLabel[dept] || dept,
|
||||||
|
fields: fields.value.filter((f) => f.dept === dept)
|
||||||
|
}))
|
||||||
|
return groups.filter((g) => g.fields.length > 0)
|
||||||
|
})
|
||||||
|
|
||||||
|
function canEditDept(dept: string) {
|
||||||
|
const list = acl.value.editableDepts || []
|
||||||
|
return list.includes(dept)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadData() {
|
||||||
|
loading.value = true
|
||||||
|
try {
|
||||||
|
const res = await fetchLabSampleList(props.dataset, {
|
||||||
|
keyword: searchForm.keyword || undefined,
|
||||||
|
dateFrom: dateRange.value?.[0],
|
||||||
|
dateTo: dateRange.value?.[1],
|
||||||
|
page: pagination.page,
|
||||||
|
pageSize: pagination.pageSize
|
||||||
|
})
|
||||||
|
tableData.value = res?.list || []
|
||||||
|
pagination.total = res?.total || 0
|
||||||
|
fields.value = res?.fields || []
|
||||||
|
acl.value = res?.acl || {}
|
||||||
|
} catch (e: any) {
|
||||||
|
ElMessage.error(e?.message || '加载失败')
|
||||||
|
} finally {
|
||||||
|
loading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleSearch() {
|
||||||
|
pagination.page = 1
|
||||||
|
void loadData()
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleReset() {
|
||||||
|
searchForm.keyword = ''
|
||||||
|
dateRange.value = null
|
||||||
|
handleSearch()
|
||||||
|
}
|
||||||
|
|
||||||
|
function openEdit(row: Record<string, any>) {
|
||||||
|
editRow.value = row
|
||||||
|
Object.keys(editForm).forEach((k) => delete editForm[k])
|
||||||
|
for (const f of fields.value) {
|
||||||
|
editForm[f.key] = row[f.key] ?? ''
|
||||||
|
}
|
||||||
|
editVisible.value = true
|
||||||
|
}
|
||||||
|
|
||||||
|
async function submitEdit() {
|
||||||
|
if (!editRow.value?.sampleCode) return
|
||||||
|
const editableKeys = fields.value
|
||||||
|
.filter((f) => canEditDept(f.dept))
|
||||||
|
.map((f) => f.key)
|
||||||
|
if (!editableKeys.length) {
|
||||||
|
ElMessage.warning('当前账号无可编辑字段')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const payload: Record<string, any> = {}
|
||||||
|
for (const key of editableKeys) {
|
||||||
|
payload[key] = editForm[key]
|
||||||
|
}
|
||||||
|
saving.value = true
|
||||||
|
try {
|
||||||
|
await updateLabSampleRow(props.dataset, editRow.value.sampleCode, payload)
|
||||||
|
ElMessage.success('保存成功')
|
||||||
|
editVisible.value = false
|
||||||
|
await loadData()
|
||||||
|
} catch (e: any) {
|
||||||
|
ElMessage.error(e?.message || '保存失败')
|
||||||
|
} finally {
|
||||||
|
saving.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleExport() {
|
||||||
|
exporting.value = true
|
||||||
|
try {
|
||||||
|
// 列表接口 pageSize 上限为 200,导出需分页拉全量后再生成 xlsx
|
||||||
|
const pageSize = 200
|
||||||
|
let page = 1
|
||||||
|
let total = Number.POSITIVE_INFINITY
|
||||||
|
const rows: Record<string, any>[] = []
|
||||||
|
let cols = fields.value
|
||||||
|
while (rows.length < total) {
|
||||||
|
const res = await fetchLabSampleList(props.dataset, {
|
||||||
|
keyword: searchForm.keyword || undefined,
|
||||||
|
dateFrom: dateRange.value?.[0],
|
||||||
|
dateTo: dateRange.value?.[1],
|
||||||
|
page,
|
||||||
|
pageSize
|
||||||
|
})
|
||||||
|
if (res?.fields?.length) cols = res.fields
|
||||||
|
total = Number(res?.total ?? 0)
|
||||||
|
const batch = res?.list || []
|
||||||
|
rows.push(...batch)
|
||||||
|
if (!batch.length || batch.length < pageSize) break
|
||||||
|
page += 1
|
||||||
|
if (page > 500) break
|
||||||
|
}
|
||||||
|
const ExcelJS = (await import('exceljs')).default
|
||||||
|
const workbook = new ExcelJS.Workbook()
|
||||||
|
const sheet = workbook.addWorksheet(props.title || props.dataset)
|
||||||
|
sheet.addRow(cols.map((c) => c.label))
|
||||||
|
for (const row of rows) {
|
||||||
|
sheet.addRow(cols.map((c) => row[c.key] ?? ''))
|
||||||
|
}
|
||||||
|
const header = sheet.getRow(1)
|
||||||
|
header.font = { bold: true }
|
||||||
|
const buffer = await workbook.xlsx.writeBuffer()
|
||||||
|
const blob = new Blob([buffer], {
|
||||||
|
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
|
||||||
|
})
|
||||||
|
const a = document.createElement('a')
|
||||||
|
a.href = URL.createObjectURL(blob)
|
||||||
|
a.download = `${props.title || props.dataset}.xlsx`
|
||||||
|
a.click()
|
||||||
|
URL.revokeObjectURL(a.href)
|
||||||
|
ElMessage.success(`已导出 ${rows.length} 条`)
|
||||||
|
} catch (e: any) {
|
||||||
|
ElMessage.error(e?.message || '导出失败')
|
||||||
|
} finally {
|
||||||
|
exporting.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(() => {
|
||||||
|
void loadData()
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped lang="scss">
|
||||||
|
.dept-title {
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--el-color-primary);
|
||||||
|
margin: 4px 0 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.text-muted {
|
||||||
|
color: var(--el-text-color-secondary);
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
<template>
|
||||||
|
<LabSampleProcessingPage dataset="hsc" title="造血干细胞数据" />
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import LabSampleProcessingPage from '../LabSampleProcessingPage.vue'
|
||||||
|
</script>
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
<template>
|
||||||
|
<LabSampleProcessingPage dataset="msc" title="脐带间充质干细胞数据" />
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import LabSampleProcessingPage from '../LabSampleProcessingPage.vue'
|
||||||
|
</script>
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
<template>
|
||||||
|
<LabSampleProcessingPage dataset="ubmc" title="单个核数据" />
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import LabSampleProcessingPage from '../LabSampleProcessingPage.vue'
|
||||||
|
</script>
|
||||||
@@ -3,18 +3,22 @@
|
|||||||
<template>
|
<template>
|
||||||
<div class="page-container">
|
<div class="page-container">
|
||||||
<section class="panel">
|
<section class="panel">
|
||||||
<div class="panel-top">
|
<div class="panel-pill-tabs panel-pill-tabs--lg">
|
||||||
<h2 class="title-bar-heading">实验室样本处理数据</h2>
|
<div class="panel-pill-tabs__track" role="tablist">
|
||||||
</div>
|
<button
|
||||||
|
|
||||||
<el-tabs v-model="activeTab" class="lab-process-tabs" @tab-change="handleTabChange">
|
|
||||||
<el-tab-pane
|
|
||||||
v-for="tab in LAB_PROCESS_TABS"
|
v-for="tab in LAB_PROCESS_TABS"
|
||||||
:key="tab.key"
|
:key="tab.key"
|
||||||
:label="tab.label"
|
type="button"
|
||||||
:name="tab.key"
|
role="tab"
|
||||||
/>
|
class="panel-pill-tabs__btn"
|
||||||
</el-tabs>
|
:class="{ 'is-active': activeTab === tab.key }"
|
||||||
|
:aria-selected="activeTab === tab.key"
|
||||||
|
@click="handleTabChange(tab.key)"
|
||||||
|
>
|
||||||
|
{{ tab.label }}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div class="filter-block">
|
<div class="filter-block">
|
||||||
<el-form :model="searchForm" class="filter-form" @submit.prevent>
|
<el-form :model="searchForm" class="filter-form" @submit.prevent>
|
||||||
@@ -252,7 +256,9 @@
|
|||||||
handleSearch()
|
handleSearch()
|
||||||
}
|
}
|
||||||
|
|
||||||
function handleTabChange() {
|
function handleTabChange(name: LabSampleProcessTabKey) {
|
||||||
|
if (activeTab.value === name) return
|
||||||
|
activeTab.value = name
|
||||||
pagination.page = 1
|
pagination.page = 1
|
||||||
loadData()
|
loadData()
|
||||||
}
|
}
|
||||||
@@ -335,10 +341,6 @@
|
|||||||
</script>
|
</script>
|
||||||
|
|
||||||
<style scoped lang="scss">
|
<style scoped lang="scss">
|
||||||
.lab-process-tabs {
|
|
||||||
margin: 0 0 12px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.form-tip {
|
.form-tip {
|
||||||
margin: 0 0 12px;
|
margin: 0 0 12px;
|
||||||
color: var(--mint-text-muted, #6b7280);
|
color: var(--mint-text-muted, #6b7280);
|
||||||
|
|||||||
Reference in new issue
Block a user