diff --git a/backend/app/crud/sample_reception.py b/backend/app/crud/sample_reception.py index e5d37f42..f9e65a23 100644 --- a/backend/app/crud/sample_reception.py +++ b/backend/app/crud/sample_reception.py @@ -1213,7 +1213,9 @@ def update_sample_reception( raise ValueError("接收结论无效") from app.crud import sample_reception_lab_code as lab_code_svc + from app.services.lab_storage_code_rename import rename_lab_storage_code_copies + old_lab_code = (rec.lab_storage_code or "").strip() code_raw = (lab_storage_code or "").strip() if conclusion == "js": parsed_code = lab_code_svc.validate_lab_storage_code(code_raw) @@ -1234,7 +1236,18 @@ def update_sample_reception( ) rec.lab_storage_code = parsed_code else: + parsed_code = None rec.lab_storage_code = None + new_lab_code = (parsed_code or "").strip() + if old_lab_code and new_lab_code and old_lab_code != new_lab_code: + rename_lab_storage_code_copies( + db, + tenant_no=tenant_no, + reception_id=reception_id, + old_code=old_lab_code, + new_code=new_lab_code, + user_id=user_id, + ) handler_display = (handler_name or "").strip() if handler_user_id and not handler_display: diff --git a/backend/app/services/lab_storage_code_rename.py b/backend/app/services/lab_storage_code_rename.py new file mode 100644 index 00000000..1db607bf --- /dev/null +++ b/backend/app/services/lab_storage_code_rename.py @@ -0,0 +1,399 @@ +"""编辑样本接收时,把实验室入库编码同步到已落库的关联副本。""" +from __future__ import annotations + +from datetime import datetime +from typing import Iterable, List, Optional, Sequence + +from sqlalchemy.orm import Session + +from app.models.models import ( + BizCellProduct, + BizLabSampleProcessingExtra, + BizLabSampleProcessSupplement, + BizOutboundReleaseCell, + BizProductionTask, + BizProductionTaskInput, + BizProductionTaskOutput, + BizProductionTaskStep, + BizProductionTaskStepOutput, + BizProductionWorkOrder, + BizQcWorkOrder, + BizQcWorkOrderInspectionBatch, + BizSampleReception, + BizStorageSlotOccupancy, +) + +DUPLICATE_MESSAGE = "实验室入库编码已存在" + + +def _ascii_alnum(ch: str) -> bool: + return bool(ch) and ch.isascii() and ch.isalnum() + + +def replace_lab_code_token(text: Optional[str], old: str, new: str) -> Optional[str]: + """替换完整编码。前后紧挨 ASCII 字母或数字时不替换,避免改掉更长的编码。""" + if text is None or not old or old == new or old not in text: + return text + out: List[str] = [] + i = 0 + size = len(old) + while i < len(text): + if text.startswith(old, i): + prev_ok = i == 0 or not _ascii_alnum(text[i - 1]) + end = i + size + next_ok = end == len(text) or not _ascii_alnum(text[end]) + if prev_ok and next_ok: + out.append(new) + i = end + continue + out.append(text[i]) + i += 1 + return "".join(out) + + +def _occupies_new_code(value: Optional[str], new: str) -> bool: + """批次名等于新编码,或是「新编码 + 非字母数字后缀」。""" + text = (value or "").strip() + if not text or not new: + return False + if text == new: + return True + if not text.startswith(new) or len(text) == len(new): + return False + return not _ascii_alnum(text[len(new)]) + + +def _like_prefix(code: str) -> str: + escaped = code.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + return escaped + "%" + + +def _ids(values: Iterable[str]) -> List[str]: + return [v for v in values if v] + + +def _touch(row, user_id: Optional[str], now: datetime) -> None: + row.update_by = user_id + row.update_time = now + + +def _rewrite_fields(row, fields: Sequence[str], old: str, new: str, user_id: Optional[str], now: datetime) -> bool: + changed = False + for field in fields: + current = getattr(row, field) + updated = replace_lab_code_token(current, old, new) + if updated != current: + setattr(row, field, updated) + changed = True + if changed: + _touch(row, user_id, now) + return changed + + +def _raise_if_duplicate() -> None: + raise ValueError(DUPLICATE_MESSAGE) + + +def rename_lab_storage_code_copies( + db: Session, + *, + tenant_no: str, + reception_id: str, + old_code: str, + new_code: str, + user_id: Optional[str] = None, +) -> int: + """把本条接收记录关联出去的旧编码副本改成新编码。冲突时不写任何副本。""" + old = (old_code or "").strip() + new = (new_code or "").strip() + if not old or not new or old == new: + return 0 + + other_reception = ( + db.query(BizSampleReception.id) + .filter( + BizSampleReception.tenant_no == tenant_no, + BizSampleReception.del_flag == 0, + BizSampleReception.lab_storage_code == new, + BizSampleReception.id != reception_id, + ) + .first() + ) + if other_reception: + _raise_if_duplicate() + + prod_orders = ( + db.query(BizProductionWorkOrder) + .filter( + BizProductionWorkOrder.tenant_no == tenant_no, + BizProductionWorkOrder.del_flag == 0, + BizProductionWorkOrder.reception_id == reception_id, + ) + .all() + ) + qc_orders = ( + db.query(BizQcWorkOrder) + .filter( + BizQcWorkOrder.tenant_no == tenant_no, + BizQcWorkOrder.del_flag == 0, + BizQcWorkOrder.reception_id == reception_id, + ) + .all() + ) + prod_ids = [row.id for row in prod_orders] + qc_ids = [row.id for row in qc_orders] + tasks = ( + db.query(BizProductionTask) + .filter( + BizProductionTask.tenant_no == tenant_no, + BizProductionTask.del_flag == 0, + BizProductionTask.work_order_id.in_(prod_ids), + ) + .all() + if prod_ids + else [] + ) + task_ids = [row.id for row in tasks] + steps = ( + db.query(BizProductionTaskStep) + .filter( + BizProductionTaskStep.tenant_no == tenant_no, + BizProductionTaskStep.del_flag == 0, + BizProductionTaskStep.task_id.in_(task_ids), + ) + .all() + if task_ids + else [] + ) + step_ids = [row.id for row in steps] + inputs = ( + db.query(BizProductionTaskInput) + .filter( + BizProductionTaskInput.tenant_no == tenant_no, + BizProductionTaskInput.del_flag == 0, + BizProductionTaskInput.task_id.in_(task_ids), + ) + .all() + if task_ids + else [] + ) + task_outputs = ( + db.query(BizProductionTaskOutput) + .filter( + BizProductionTaskOutput.tenant_no == tenant_no, + BizProductionTaskOutput.del_flag == 0, + BizProductionTaskOutput.task_id.in_(task_ids), + ) + .all() + if task_ids + else [] + ) + step_outputs = ( + db.query(BizProductionTaskStepOutput) + .filter( + BizProductionTaskStepOutput.tenant_no == tenant_no, + BizProductionTaskStepOutput.del_flag == 0, + BizProductionTaskStepOutput.step_id.in_(step_ids), + ) + .all() + if step_ids + else [] + ) + products = ( + db.query(BizCellProduct) + .filter( + BizCellProduct.tenant_no == tenant_no, + BizCellProduct.del_flag == 0, + BizCellProduct.production_task_id.in_(task_ids), + ) + .all() + if task_ids + else [] + ) + product_ids = [row.id for row in products] + occupancies = ( + db.query(BizStorageSlotOccupancy) + .filter( + BizStorageSlotOccupancy.tenant_no == tenant_no, + BizStorageSlotOccupancy.del_flag == 0, + BizStorageSlotOccupancy.item_id.in_(product_ids), + ) + .all() + if product_ids + else [] + ) + outbound_cells = ( + db.query(BizOutboundReleaseCell) + .filter( + BizOutboundReleaseCell.tenant_no == tenant_no, + BizOutboundReleaseCell.del_flag == 0, + BizOutboundReleaseCell.cell_product_id.in_(product_ids), + ) + .all() + if product_ids + else [] + ) + batches = ( + db.query(BizQcWorkOrderInspectionBatch) + .filter( + BizQcWorkOrderInspectionBatch.tenant_no == tenant_no, + BizQcWorkOrderInspectionBatch.del_flag == 0, + BizQcWorkOrderInspectionBatch.work_order_id.in_(qc_ids), + ) + .all() + if qc_ids + else [] + ) + supplements = ( + db.query(BizLabSampleProcessSupplement) + .filter( + BizLabSampleProcessSupplement.tenant_no == tenant_no, + BizLabSampleProcessSupplement.del_flag == 0, + BizLabSampleProcessSupplement.lab_storage_code == old, + ) + .all() + ) + extras = ( + db.query(BizLabSampleProcessingExtra) + .filter( + BizLabSampleProcessingExtra.tenant_no == tenant_no, + BizLabSampleProcessingExtra.del_flag == 0, + BizLabSampleProcessingExtra.sample_code == old, + ) + .all() + ) + + _assert_copies_available( + db, + tenant_no=tenant_no, + new=new, + product_ids=product_ids, + task_output_ids=[row.id for row in task_outputs], + step_output_ids=[row.id for row in step_outputs], + occupancy_ids=[row.id for row in occupancies], + qc_ids=qc_ids, + ) + if ( + db.query(BizLabSampleProcessSupplement.id) + .filter( + BizLabSampleProcessSupplement.tenant_no == tenant_no, + BizLabSampleProcessSupplement.del_flag == 0, + BizLabSampleProcessSupplement.lab_storage_code == new, + ) + .first() + ): + _raise_if_duplicate() + if ( + db.query(BizLabSampleProcessingExtra.id) + .filter( + BizLabSampleProcessingExtra.tenant_no == tenant_no, + BizLabSampleProcessingExtra.del_flag == 0, + BizLabSampleProcessingExtra.sample_code == new, + ) + .first() + ): + _raise_if_duplicate() + + now = datetime.now() + changed = 0 + for row in tasks: + if _rewrite_fields(row, ("task_name", "description", "remark"), old, new, user_id, now): + changed += 1 + for row in steps: + if _rewrite_fields(row, ("description", "remark", "sop_content"), old, new, user_id, now): + changed += 1 + for row in inputs: + if _rewrite_fields(row, ("input_name", "input_code"), old, new, user_id, now): + changed += 1 + for row in task_outputs: + if _rewrite_fields(row, ("output_name", "output_barcode"), old, new, user_id, now): + changed += 1 + for row in step_outputs: + if _rewrite_fields(row, ("output_name", "output_barcode"), old, new, user_id, now): + changed += 1 + for row in products: + if _rewrite_fields(row, ("product_code", "product_name", "batch_no"), old, new, user_id, now): + changed += 1 + for row in occupancies: + if _rewrite_fields(row, ("item_code", "item_name"), old, new, user_id, now): + changed += 1 + for row in outbound_cells: + if _rewrite_fields(row, ("product_code", "product_name", "batch_no"), old, new, user_id, now): + changed += 1 + for row in batches: + if _rewrite_fields(row, ("batch_name",), old, new, user_id, now): + changed += 1 + for row in supplements: + row.lab_storage_code = new + _touch(row, user_id, now) + changed += 1 + for row in extras: + row.sample_code = new + _touch(row, user_id, now) + changed += 1 + if changed: + db.flush() + return changed + + +def _assert_copies_available( + db: Session, + *, + tenant_no: str, + new: str, + product_ids: Sequence[str], + task_output_ids: Sequence[str], + step_output_ids: Sequence[str], + occupancy_ids: Sequence[str], + qc_ids: Sequence[str], +) -> None: + product_q = db.query(BizCellProduct.id).filter( + BizCellProduct.tenant_no == tenant_no, + BizCellProduct.del_flag == 0, + BizCellProduct.product_code == new, + ) + if product_ids: + product_q = product_q.filter(~BizCellProduct.id.in_(_ids(product_ids))) + if product_q.first(): + _raise_if_duplicate() + + task_barcode_q = db.query(BizProductionTaskOutput.id).filter( + BizProductionTaskOutput.tenant_no == tenant_no, + BizProductionTaskOutput.del_flag == 0, + BizProductionTaskOutput.output_barcode == new, + ) + if task_output_ids: + task_barcode_q = task_barcode_q.filter(~BizProductionTaskOutput.id.in_(_ids(task_output_ids))) + if task_barcode_q.first(): + _raise_if_duplicate() + + step_barcode_q = db.query(BizProductionTaskStepOutput.id).filter( + BizProductionTaskStepOutput.tenant_no == tenant_no, + BizProductionTaskStepOutput.del_flag == 0, + BizProductionTaskStepOutput.output_barcode == new, + ) + if step_output_ids: + step_barcode_q = step_barcode_q.filter(~BizProductionTaskStepOutput.id.in_(_ids(step_output_ids))) + if step_barcode_q.first(): + _raise_if_duplicate() + + occupancy_q = db.query(BizStorageSlotOccupancy.id).filter( + BizStorageSlotOccupancy.tenant_no == tenant_no, + BizStorageSlotOccupancy.del_flag == 0, + BizStorageSlotOccupancy.item_code == new, + ) + if occupancy_ids: + occupancy_q = occupancy_q.filter(~BizStorageSlotOccupancy.id.in_(_ids(occupancy_ids))) + if occupancy_q.first(): + _raise_if_duplicate() + + batch_q = db.query(BizQcWorkOrderInspectionBatch.batch_name).filter( + BizQcWorkOrderInspectionBatch.tenant_no == tenant_no, + BizQcWorkOrderInspectionBatch.del_flag == 0, + BizQcWorkOrderInspectionBatch.batch_name.like(_like_prefix(new), escape="\\"), + ) + if qc_ids: + batch_q = batch_q.filter(~BizQcWorkOrderInspectionBatch.work_order_id.in_(_ids(qc_ids))) + for (name,) in batch_q.all(): + if _occupies_new_code(name, new): + _raise_if_duplicate() diff --git a/backend/scripts/repair_oa_void_unlinked_contract_duplicate.py b/backend/scripts/repair_oa_void_unlinked_contract_duplicate.py new file mode 100644 index 00000000..57e62cde --- /dev/null +++ b/backend/scripts/repair_oa_void_unlinked_contract_duplicate.py @@ -0,0 +1,467 @@ +#!/usr/bin/env python3 +"""作废「已完成合同审批」中未被付款审批关联的重复单。 + +背景:发起人误提两张相同合同审批,其中一张已被付款单通过 oa_relation 关联, +另一张未关联。产品撤回 API 仅允许 running→cancelled,无法作废已完成单。 + +本脚本: + 1) 按申请人昵称 + 流程名「合同审批」定位候选实例 + 2) 用 oa_relation.to_instance_id 区分已关联 / 未关联 + 3) 断言恰好 1 张已关联、1 张未关联后,对未关联单软删除作废 + +用法(backend 目录、已配置目标库): + python -m scripts.repair_oa_void_unlinked_contract_duplicate \\ + --nick-name 胡倩茜 --create-time '2026-11-25 12:00:56' + + python -m scripts.repair_oa_void_unlinked_contract_duplicate \\ + --nick-name 胡倩茜 --create-time '2026-11-25 12:00:56' --apply +""" +from __future__ import annotations + +import argparse +import json +import os +import sys +from datetime import datetime +from typing import Any, Dict, List, Optional + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +from sqlalchemy.orm import Session + +from app.core.database import SessionLocal +from app.core.utils import generate_uuid +from app.models.models import ( + OaApp, + OaInstance, + OaInstanceEvent, + OaRelation, + SysUser, +) + +CONTRACT_APP_NAME = "合同审批" +PAYMENT_APP_NAME = "付款审批" + + +def _parse_create_time(raw: Optional[str]) -> Optional[datetime]: + text = (raw or "").strip() + if not text: + return None + for fmt in ("%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M", "%Y-%m-%d"): + try: + return datetime.strptime(text, fmt) + except ValueError: + continue + raise RuntimeError( + f"无法解析 --create-time={raw!r},请用 'YYYY-MM-DD HH:MM:SS'" + ) + + +def _find_user(db: Session, *, nick_name: str, tenant_no: Optional[str]) -> SysUser: + q = db.query(SysUser).filter( + SysUser.del_flag == 0, + SysUser.nick_name == nick_name, + ) + if tenant_no: + q = q.filter(SysUser.tenant_no == tenant_no) + rows = q.all() + if not rows: + raise RuntimeError(f"未找到用户 nick_name={nick_name!r}") + if len(rows) > 1 and not tenant_no: + raise RuntimeError( + "匹配到多名用户,请加 --tenant。" + f" 候选: {[{'id': u.id, 'tenantNo': u.tenant_no, 'userNo': u.user_no} for u in rows]}" + ) + return rows[0] + + +def _find_app(db: Session, *, app_name: str, tenant_no: str) -> OaApp: + row = ( + db.query(OaApp) + .filter( + OaApp.del_flag == 0, + OaApp.tenant_no == tenant_no, + OaApp.app_name == app_name, + ) + .first() + ) + if not row: + # 宽松匹配,便于生产命名略有差异时定位 + cands = ( + db.query(OaApp) + .filter( + OaApp.del_flag == 0, + OaApp.tenant_no == tenant_no, + OaApp.app_name.like(f"%{app_name}%"), + ) + .all() + ) + names = [a.app_name for a in cands] + raise RuntimeError( + f"未找到应用 app_name={app_name!r} tenant={tenant_no!r};近似: {names}" + ) + return row + + +def _list_contract_instances( + db: Session, + *, + user: SysUser, + contract_app: OaApp, + create_time: Optional[datetime], +) -> List[OaInstance]: + q = db.query(OaInstance).filter( + OaInstance.del_flag == 0, + OaInstance.tenant_no == user.tenant_no, + OaInstance.app_id == contract_app.id, + OaInstance.initiator_user_id == user.id, + OaInstance.status == "completed", + ) + if create_time is not None: + q = q.filter(OaInstance.create_time == create_time) + rows = q.order_by(OaInstance.create_time.asc(), OaInstance.id.asc()).all() + if not rows: + raise RuntimeError( + "未找到已完成的合同审批实例。" + f" user={user.nick_name} app={contract_app.app_name}" + f" create_time={create_time}" + ) + if len(rows) < 2: + raise RuntimeError( + f"仅找到 {len(rows)} 张已完成合同审批,预期至少 2 张重复单。" + f" ids={[r.id for r in rows]}" + ) + if create_time is None and len(rows) > 2: + raise RuntimeError( + f"未指定 --create-time 时匹配到 {len(rows)} 张,请加上精确申请时间缩小范围。" + f" ids={[r.id for r in rows]}" + ) + return rows + + +def _linked_contract_ids( + db: Session, *, contract_ids: List[str], tenant_no: str +) -> Dict[str, List[Dict[str, Any]]]: + """返回 contract_id -> 关联边摘要(付款 from → 合同 to)。""" + if not contract_ids: + return {} + rels = ( + db.query(OaRelation) + .filter( + OaRelation.del_flag == 0, + OaRelation.tenant_no == tenant_no, + OaRelation.to_instance_id.in_(contract_ids), + ) + .all() + ) + out: Dict[str, List[Dict[str, Any]]] = {cid: [] for cid in contract_ids} + if not rels: + return out + + from_ids = list({r.from_instance_id for r in rels}) + from_inst = { + i.id: i + for i in db.query(OaInstance) + .filter(OaInstance.id.in_(from_ids), OaInstance.del_flag == 0) + .all() + } + app_ids = list({i.app_id for i in from_inst.values()}) + apps = { + a.id: a + for a in db.query(OaApp).filter(OaApp.id.in_(app_ids), OaApp.del_flag == 0).all() + } + for r in rels: + fi = from_inst.get(r.from_instance_id) + app = apps.get(fi.app_id) if fi else None + out.setdefault(r.to_instance_id, []).append( + { + "relationId": r.id, + "paymentInstanceId": r.from_instance_id, + "paymentStatus": getattr(fi, "status", None), + "paymentAppName": getattr(app, "app_name", None), + "fieldKey": r.field_key, + "relationCreateTime": str(r.create_time) if r.create_time else None, + } + ) + return out + + +def _void_instance( + db: Session, + *, + inst: OaInstance, + actor_user_id: Optional[str], + mode: str, +) -> Dict[str, Any]: + now = datetime.now() + before = {"id": inst.id, "status": inst.status, "delFlag": inst.del_flag} + if mode == "soft-delete": + inst.del_flag = 1 + inst.status = "cancelled" + elif mode == "cancel": + inst.status = "cancelled" + else: + raise RuntimeError(f"未知 --mode={mode!r}") + inst.update_by = actor_user_id + inst.update_time = now + remark = ( + "生产数据修复:重复合同审批未关联付款,软删除作废" + if mode == "soft-delete" + else "生产数据修复:重复合同审批未关联付款,状态改为已撤销" + ) + if not (inst.remark or "").strip(): + inst.remark = remark + db.add(inst) + ev = OaInstanceEvent( + id=generate_uuid(), + instance_id=inst.id, + round_no=int(getattr(inst, "current_round", None) or 1), + event_type="withdraw", + actor_user_id=actor_user_id, + task_id=None, + node_key=None, + comment_text=remark, + tenant_no=inst.tenant_no, + order_num=0, + remark="repair_oa_void_unlinked_contract_duplicate", + create_by=actor_user_id, + create_dept_id=inst.initiator_dept_id or "", + create_time=now, + update_by=actor_user_id, + update_time=now, + del_flag=0, + ) + db.add(ev) + return { + "before": before, + "after": {"id": inst.id, "status": inst.status, "delFlag": inst.del_flag}, + "eventId": ev.id, + "mode": mode, + } + + +def analyze( + db: Session, + *, + nick_name: str, + create_time: Optional[datetime], + tenant_no: Optional[str], + contract_app_name: str, +) -> Dict[str, Any]: + user = _find_user(db, nick_name=nick_name, tenant_no=tenant_no) + tn = user.tenant_no + contract_app = _find_app(db, app_name=contract_app_name, tenant_no=tn) + payment_app = ( + db.query(OaApp) + .filter( + OaApp.del_flag == 0, + OaApp.tenant_no == tn, + OaApp.app_name == PAYMENT_APP_NAME, + ) + .first() + ) + instances = _list_contract_instances( + db, user=user, contract_app=contract_app, create_time=create_time + ) + ids = [i.id for i in instances] + links = _linked_contract_ids(db, contract_ids=ids, tenant_no=tn) + + linked_ids: List[str] = [cid for cid, rels in links.items() if rels] + unlinked_ids: List[str] = [cid for cid in ids if cid not in linked_ids] + + candidates = [ + { + "id": i.id, + "title": i.title, + "status": i.status, + "createTime": str(i.create_time) if i.create_time else None, + "updateTime": str(i.update_time) if i.update_time else None, + "linkedPayments": links.get(i.id) or [], + "decision": "keep" if i.id in linked_ids else "void_candidate", + } + for i in instances + ] + + errors: List[str] = [] + if len(linked_ids) != 1: + errors.append( + f"期望恰好 1 张已被付款关联的合同,实际 {len(linked_ids)}: {linked_ids}" + ) + if len(unlinked_ids) != 1: + errors.append( + f"期望恰好 1 张未关联合同待作废,实际 {len(unlinked_ids)}: {unlinked_ids}" + ) + # 关联来源最好是付款审批(非硬失败,仅警告) + warnings: List[str] = [] + for cid in linked_ids: + for rel in links.get(cid) or []: + pname = (rel.get("paymentAppName") or "").strip() + if payment_app and pname and pname != PAYMENT_APP_NAME: + warnings.append( + f"合同 {cid} 被非付款应用关联: {pname} ({rel.get('paymentInstanceId')})" + ) + if not pname: + warnings.append( + f"合同 {cid} 关联来源应用名未知: {rel.get('paymentInstanceId')}" + ) + + return { + "user": { + "id": user.id, + "nickName": user.nick_name, + "userNo": user.user_no, + "tenantNo": tn, + }, + "contractApp": {"id": contract_app.id, "appName": contract_app.app_name}, + "paymentApp": ( + {"id": payment_app.id, "appName": payment_app.app_name} + if payment_app + else None + ), + "createTimeFilter": str(create_time) if create_time else None, + "candidates": candidates, + "linkedContractIds": linked_ids, + "unlinkedContractIds": unlinked_ids, + "voidTargetId": unlinked_ids[0] if len(unlinked_ids) == 1 else None, + "keepTargetId": linked_ids[0] if len(linked_ids) == 1 else None, + "errors": errors, + "warnings": warnings, + "safeToApply": len(errors) == 0, + } + + +def run( + *, + nick_name: str, + create_time_raw: Optional[str], + tenant_no: Optional[str], + contract_app_name: str, + apply: bool, + mode: str, + actor_user_id: Optional[str], +) -> Dict[str, Any]: + create_time = _parse_create_time(create_time_raw) + db = SessionLocal() + try: + report = analyze( + db, + nick_name=nick_name.strip(), + create_time=create_time, + tenant_no=(tenant_no or "").strip() or None, + contract_app_name=(contract_app_name or CONTRACT_APP_NAME).strip() + or CONTRACT_APP_NAME, + ) + if not apply: + db.rollback() + return { + "dryRun": True, + "mode": mode, + "analysis": report, + "message": ( + "dry-run:未写库。" + "确认 voidTargetId 正确且 safeToApply=true 后加 --apply。" + ), + } + if not report.get("safeToApply"): + db.rollback() + return { + "dryRun": False, + "applied": False, + "mode": mode, + "analysis": report, + "message": "分析未通过安全断言,已回滚,未写库。", + } + target_id = report["voidTargetId"] + inst = ( + db.query(OaInstance) + .filter( + OaInstance.id == target_id, + OaInstance.del_flag == 0, + ) + .one() + ) + # 二次校验:写库前再确认仍未被关联 + still_linked = ( + db.query(OaRelation.id) + .filter( + OaRelation.del_flag == 0, + OaRelation.tenant_no == inst.tenant_no, + OaRelation.to_instance_id == inst.id, + ) + .first() + ) + if still_linked: + db.rollback() + raise RuntimeError( + f"写库前发现目标 {inst.id} 已被关联,中止作废以防误伤" + ) + actor = actor_user_id or inst.initiator_user_id + void_result = _void_instance( + db, inst=inst, actor_user_id=actor, mode=mode + ) + db.commit() + return { + "dryRun": False, + "applied": True, + "mode": mode, + "analysis": report, + "voidResult": void_result, + "message": "已作废未关联合同审批;已关联付款的合同未改动。", + } + except Exception: + db.rollback() + raise + finally: + db.close() + + +def main(argv: Optional[List[str]] = None) -> int: + parser = argparse.ArgumentParser( + description="作废未被付款关联的重复已完成合同审批" + ) + parser.add_argument("--nick-name", required=True, help="申请人昵称,如 胡倩茜") + parser.add_argument( + "--create-time", + default=None, + help="申请时间,精确匹配 oa_instance.create_time,如 '2026-11-25 12:00:56'", + ) + parser.add_argument("--tenant", default=None, help="租户编号;重名用户时必填") + parser.add_argument( + "--contract-app-name", + default=CONTRACT_APP_NAME, + help=f"合同审批应用名,默认 {CONTRACT_APP_NAME}", + ) + parser.add_argument( + "--mode", + choices=("soft-delete", "cancel"), + default="soft-delete", + help="soft-delete=列表消失(默认);cancel=仅改为已撤销仍可见", + ) + parser.add_argument("--apply", action="store_true", help="实际写库;默认 dry-run") + parser.add_argument( + "--actor-user-id", + default=None, + help="事件操作人;默认用发起人", + ) + args = parser.parse_args(argv) + + result = run( + nick_name=args.nick_name, + create_time_raw=args.create_time, + tenant_no=args.tenant, + contract_app_name=args.contract_app_name, + apply=bool(args.apply), + mode=args.mode, + actor_user_id=args.actor_user_id, + ) + print(json.dumps(result, ensure_ascii=False, indent=2, default=str)) + analysis = result.get("analysis") or {} + if analysis.get("errors"): + return 2 + if result.get("dryRun") is False and not result.get("applied"): + return 2 + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/backend/scripts/repair_reception_downstream_after_bj_to_js.py b/backend/scripts/repair_reception_downstream_after_bj_to_js.py new file mode 100644 index 00000000..dc148c47 --- /dev/null +++ b/backend/scripts/repair_reception_downstream_after_bj_to_js.py @@ -0,0 +1,308 @@ +#!/usr/bin/env python3 +"""补建「先废弃后改接收」漏掉的下游单据。 + +样本接收编辑接口不会重复创建质检/生产工单、入库放行与内置任务派发。 +本脚本对指定接收记录回放首次「接收」路径(幂等): + + 1) 质检工单 create_work_order_from_reception + 2) 生产工单 create_production_work_order_from_reception + 3) UBMC/UC/... 内置任务 try_auto_dispatch_builtin_tasks_after_reception + 4) 入库放行审核 create_review_from_reception(已存在则跳过) + 5) after_sample_reception_saved(清样本作废态) + +用法(在 backend 目录、已配置目标库连接): + python -m scripts.repair_reception_downstream_after_bj_to_js \\ + --sample-code KYJZ2026110105 --lab-storage-code UBMC202611048 + + # 确认输出后写库 + python -m scripts.repair_reception_downstream_after_bj_to_js \\ + --sample-code KYJZ2026110105 --lab-storage-code UBMC202611048 --apply +""" +from __future__ import annotations + +import argparse +import json +import os +import sys +from typing import Any, Dict, Optional + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +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.crud import production_work_order as prod_wo_svc +from app.crud import qc_work_order as qc_wo_svc +from app.crud import storage_release_review as srr_svc +from app.models.models import ( + BizProductionTask, + BizProductionWorkOrder, + BizQcWorkOrder, + BizResearchDonation, + BizResearchDonationSample, + BizSampleReception, + BizStorageReleaseReview, +) +from app.services.protocol_reception_discard_sync import after_sample_reception_saved + + +def _find_reception( + db: Session, + *, + sample_code: str, + lab_storage_code: str, + tenant_no: Optional[str], +) -> BizSampleReception: + q = db.query(BizSampleReception).filter( + BizSampleReception.del_flag == 0, + BizSampleReception.sample_code == sample_code, + BizSampleReception.lab_storage_code == lab_storage_code, + ) + if tenant_no: + q = q.filter(BizSampleReception.tenant_no == tenant_no) + rows = q.order_by(BizSampleReception.create_time.desc()).all() + if not rows: + raise RuntimeError( + f"未找到接收记录 sample_code={sample_code!r} " + f"lab_storage_code={lab_storage_code!r}" + ) + if len(rows) > 1 and not tenant_no: + tenants = sorted({r.tenant_no for r in rows}) + raise RuntimeError( + f"匹配到多条接收记录,请加 --tenant。tenant_no 候选: {tenants}" + ) + return rows[0] + + +def _srr_snapshot(db: Session, rec: BizSampleReception) -> Dict[str, str]: + protocol_no = "" + sample_name = "" + source = (rec.reception_source or "cell_storage").strip() or "cell_storage" + if source == "research_donation": + d = ( + db.query(BizResearchDonation) + .filter( + BizResearchDonation.id == (rec.research_donation_id or ""), + BizResearchDonation.del_flag == 0, + ) + .first() + ) + if d: + protocol_no = d.donation_no or "" + ds = ( + db.query(BizResearchDonationSample) + .filter( + BizResearchDonationSample.id == (rec.donation_sample_id or ""), + BizResearchDonationSample.del_flag == 0, + ) + .first() + ) + if ds: + sample_name = ds.sample_code or "" + else: + sample_name = rec.sample_code or "" + protocol_no = "" + return {"protocol_no": protocol_no, "sample_name": sample_name} + + +def _existing_summary(db: Session, *, rec: BizSampleReception) -> Dict[str, Any]: + tn = rec.tenant_no + qc = ( + db.query(BizQcWorkOrder) + .filter( + BizQcWorkOrder.reception_id == rec.id, + BizQcWorkOrder.tenant_no == tn, + BizQcWorkOrder.del_flag == 0, + ) + .first() + ) + prod = ( + db.query(BizProductionWorkOrder) + .filter( + BizProductionWorkOrder.reception_id == rec.id, + BizProductionWorkOrder.tenant_no == tn, + BizProductionWorkOrder.del_flag == 0, + ) + .first() + ) + task_count = 0 + if prod: + task_count = ( + db.query(BizProductionTask.id) + .filter( + BizProductionTask.work_order_id == prod.id, + BizProductionTask.tenant_no == tn, + BizProductionTask.del_flag == 0, + ) + .count() + ) + srr = ( + db.query(BizStorageReleaseReview) + .filter( + BizStorageReleaseReview.reception_id == rec.id, + BizStorageReleaseReview.tenant_no == tn, + BizStorageReleaseReview.del_flag == 0, + ) + .first() + ) + return { + "receptionId": rec.id, + "tenantNo": tn, + "acceptConclusion": rec.accept_conclusion, + "receptionSource": rec.reception_source, + "qcWorkOrderNo": getattr(qc, "work_order_no", None), + "productionWorkOrderNo": getattr(prod, "work_order_no", None), + "productionTaskCount": task_count, + "storageReleaseReviewId": getattr(srr, "id", None), + "storageStatus": getattr(srr, "storage_status", None), + } + + +def run( + *, + sample_code: str, + lab_storage_code: str, + tenant_no: Optional[str], + apply: bool, + user_id: Optional[str], + create_dept_id: Optional[str], +) -> Dict[str, Any]: + db = SessionLocal() + try: + rec = _find_reception( + db, + sample_code=sample_code.strip(), + lab_storage_code=lab_storage_code.strip(), + tenant_no=(tenant_no or "").strip() or None, + ) + before = _existing_summary(db, rec=rec) + conclusion = (rec.accept_conclusion or "").strip() + if conclusion != "js": + raise RuntimeError( + f"接收结论当前为 {conclusion!r},须先为 js(接收)再回补下游" + ) + + uid = user_id if user_id is not None else rec.create_by + dept = ( + create_dept_id + if create_dept_id is not None + else (rec.create_dept_id or "") + ) + tn = rec.tenant_no + + if not apply: + db.rollback() + return { + "dryRun": True, + "before": before, + "message": ( + "dry-run:未写库。确认 before 后加 --apply。" + "将补建缺失的质检/生产工单、内置任务与入库放行。" + ), + } + + qc = qc_wo_svc.create_work_order_from_reception( + db, + reception=rec, + tenant_no=tn, + user_id=uid, + create_dept_id=dept or "", + ) + prod = prod_wo_svc.create_production_work_order_from_reception( + db, + reception=rec, + tenant_no=tn, + user_id=uid, + create_dept_id=dept or "", + ) + dispatch = None + if prod is not None: + dispatch = production_task_set_svc.try_auto_dispatch_builtin_tasks_after_reception( + db, + tenant_no=tn, + user_id=uid, + create_dept_id=dept or "", + work_order=prod, + lab_storage_code=rec.lab_storage_code, + ) + + srr_row = ( + db.query(BizStorageReleaseReview) + .filter( + BizStorageReleaseReview.reception_id == rec.id, + BizStorageReleaseReview.tenant_no == tn, + BizStorageReleaseReview.del_flag == 0, + ) + .first() + ) + srr_created = False + if srr_row is None: + snap = _srr_snapshot(db, rec) + srr_row = srr_svc.create_review_from_reception( + db, + reception=rec, + protocol_no=snap["protocol_no"], + sample_name=snap["sample_name"], + tenant_no=tn, + user_id=uid, + create_dept_id=dept or "", + ) + srr_created = True + + after_sample_reception_saved( + db, reception=rec, tenant_no=tn, user_id=uid + ) + db.commit() + after = _existing_summary(db, rec=rec) + return { + "dryRun": False, + "before": before, + "after": after, + "qcWorkOrderNo": getattr(qc, "work_order_no", None), + "productionWorkOrderNo": getattr(prod, "work_order_no", None), + "dispatch": dispatch, + "storageReleaseReviewId": getattr(srr_row, "id", None), + "storageReleaseCreated": srr_created, + } + except Exception: + db.rollback() + raise + finally: + db.close() + + +def main(argv: Optional[list] = None) -> int: + parser = argparse.ArgumentParser( + description="补建样本接收 bj→js 后缺失的质检/生产/入库放行下游" + ) + parser.add_argument("--sample-code", required=True, help="样本编码") + parser.add_argument("--lab-storage-code", required=True, help="实验室入库编码") + parser.add_argument("--tenant", default=None, help="租户编号;多租户命中时必填") + parser.add_argument( + "--apply", + action="store_true", + help="实际写库;默认仅 dry-run", + ) + parser.add_argument("--user-id", default=None, help="写库 create_by;默认用接收记录") + parser.add_argument( + "--create-dept-id", + default=None, + help="写库 create_dept_id;默认用接收记录", + ) + args = parser.parse_args(argv) + + result = run( + sample_code=args.sample_code, + lab_storage_code=args.lab_storage_code, + tenant_no=args.tenant, + apply=bool(args.apply), + user_id=args.user_id, + create_dept_id=args.create_dept_id, + ) + print(json.dumps(result, ensure_ascii=False, indent=2, default=str)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/backend/tests/test_lab_storage_code_rename.py b/backend/tests/test_lab_storage_code_rename.py new file mode 100644 index 00000000..98ae56a0 --- /dev/null +++ b/backend/tests/test_lab_storage_code_rename.py @@ -0,0 +1,460 @@ +"""编辑样本接收时同步实验室入库编码副本。""" +from datetime import datetime + +import pytest +from sqlalchemy import create_engine +from sqlalchemy.orm import sessionmaker + +from app.crud import sample_reception as reception_svc +from app.models.base import Base +from app.models.models import ( + BizCellProduct, + BizLabSampleProcessingExtra, + BizLabSampleProcessSupplement, + BizOutboundReleaseCell, + BizProductionTask, + BizProductionTaskInput, + BizProductionTaskOutput, + BizProductionTaskStep, + BizProductionTaskStepOutput, + BizProductionWorkOrder, + BizQcWorkOrder, + BizQcWorkOrderInspectionBatch, + BizSampleReception, + BizSampleReceptionCheckResult, + BizStorageSlotOccupancy, +) +from app.services.lab_storage_code_rename import replace_lab_code_token + + +def _session(): + engine = create_engine("sqlite:///:memory:") + Base.metadata.create_all( + engine, + tables=[ + BizSampleReception.__table__, + BizSampleReceptionCheckResult.__table__, + BizProductionWorkOrder.__table__, + BizProductionTask.__table__, + BizProductionTaskInput.__table__, + BizProductionTaskStep.__table__, + BizProductionTaskStepOutput.__table__, + BizProductionTaskOutput.__table__, + BizCellProduct.__table__, + BizStorageSlotOccupancy.__table__, + BizOutboundReleaseCell.__table__, + BizQcWorkOrder.__table__, + BizQcWorkOrderInspectionBatch.__table__, + BizLabSampleProcessSupplement.__table__, + BizLabSampleProcessingExtra.__table__, + ], + ) + return sessionmaker(bind=engine)() + + +def _now(): + return datetime(2026, 11, 20, 9, 33, 18) + + +def _seed(db): + now = _now() + db.add( + BizSampleReception( + id="recv-1", + protocol_sample_id="ps-1", + collection_protocol_id="cp-1", + reception_time=now, + accept_conclusion="js", + reception_source="cell_storage", + sample_code="ZKZX34000957", + lab_storage_code="B00001112", + tenant_no="tenant-a", + create_dept_id="", + create_time=now, + update_time=now, + del_flag=0, + ) + ) + db.add( + BizProductionWorkOrder( + id="pwo-1", + work_order_no="SC202611200001", + reception_id="recv-1", + sample_code="ZKZX34000957", + work_order_status="ywc", + tenant_no="tenant-a", + create_dept_id="", + create_time=now, + update_time=now, + del_flag=0, + ) + ) + db.add( + BizProductionTask( + id="task-1", + task_no="T-1", + work_order_id="pwo-1", + task_name="B00001112样本处理", + description="编码B00001112", + task_status="ywc", + tenant_no="tenant-a", + create_dept_id="", + create_time=now, + update_time=now, + del_flag=0, + ) + ) + db.add( + BizProductionTask( + id="task-other", + task_no="T-2", + work_order_id="pwo-other", + task_name="B00001112样本处理", + task_status="ywc", + tenant_no="tenant-a", + create_dept_id="", + create_time=now, + update_time=now, + del_flag=0, + ) + ) + db.add( + BizProductionTaskInput( + id="in-1", + task_id="task-1", + input_name="B0000112", + tenant_no="tenant-a", + create_dept_id="", + create_time=now, + update_time=now, + del_flag=0, + ) + ) + db.add( + BizProductionTaskStep( + id="step-1", + task_id="task-1", + sop_content="请处理 B00001112,不要改 B000011120", + tenant_no="tenant-a", + create_dept_id="", + create_time=now, + update_time=now, + del_flag=0, + ) + ) + db.add( + BizProductionTaskStepOutput( + id="so-1", + step_id="step-1", + output_name="脐血", + output_barcode="B0000112", + tenant_no="tenant-a", + create_dept_id="", + create_time=now, + update_time=now, + del_flag=0, + ) + ) + db.add( + BizProductionTaskOutput( + id="out-1", + task_id="task-1", + output_name="B00001112", + output_barcode="B00001112", + tenant_no="tenant-a", + create_dept_id="", + create_time=now, + update_time=now, + del_flag=0, + ) + ) + db.add( + BizCellProduct( + id="cp-1", + product_code="B00001112", + product_name="B00001112", + batch_no="B00001112", + production_task_id="task-1", + tenant_no="tenant-a", + create_dept_id="", + create_time=now, + update_time=now, + del_flag=0, + ) + ) + db.add( + BizCellProduct( + id="cp-long", + product_code="B000011120", + product_name="其他更长编码", + production_task_id="task-other", + tenant_no="tenant-a", + create_dept_id="", + create_time=now, + update_time=now, + del_flag=0, + ) + ) + db.add( + BizStorageSlotOccupancy( + id="occ-1", + slot_id="slot-1", + item_type="cell_product", + item_id="cp-1", + item_code="B00001112", + item_name="B00001112", + occupancy_status="stored", + tenant_no="tenant-a", + create_dept_id="", + create_time=now, + update_time=now, + del_flag=0, + ) + ) + db.add( + BizOutboundReleaseCell( + id="ob-1", + material_id="mat-1", + infusion_schedule_id="inf-1", + cell_product_id="cp-1", + product_code="B00001112", + product_name="B00001112", + batch_no="B00001112", + tenant_no="tenant-a", + create_dept_id="", + create_time=now, + update_time=now, + del_flag=0, + ) + ) + db.add( + BizQcWorkOrder( + id="qc-1", + work_order_no="ZJ202611200001", + reception_id="recv-1", + sample_code="ZKZX34000957", + work_order_status="ypz", + tenant_no="tenant-a", + create_dept_id="", + create_time=now, + update_time=now, + del_flag=0, + ) + ) + db.add( + BizQcWorkOrderInspectionBatch( + id="batch-1", + work_order_id="qc-1", + batch_no="B1", + batch_name="B00001112-脐血", + tenant_no="tenant-a", + create_dept_id="", + create_time=now, + update_time=now, + del_flag=0, + ) + ) + db.add( + BizQcWorkOrderInspectionBatch( + id="batch-2", + work_order_id="qc-1", + batch_no="B2", + batch_name="B00001112", + tenant_no="tenant-a", + create_dept_id="", + create_time=now, + update_time=now, + del_flag=0, + ) + ) + db.add( + BizLabSampleProcessSupplement( + id="sup-1", + lab_storage_code="B00001112", + payload="{}", + tenant_no="tenant-a", + create_dept_id="", + create_time=now, + update_time=now, + del_flag=0, + ) + ) + db.add( + BizLabSampleProcessingExtra( + id="extra-1", + dataset="hsc", + sample_code="B00001112", + tenant_no="tenant-a", + create_dept_id="", + create_time=now, + update_time=now, + del_flag=0, + ) + ) + db.commit() + + +def test_replace_keeps_longer_code_and_chinese_suffix(): + assert replace_lab_code_token("B00001112样本处理", "B00001112", "B0000112") == "B0000112样本处理" + assert replace_lab_code_token("B00001112-脐血", "B00001112", "B0000112") == "B0000112-脐血" + assert replace_lab_code_token("B000011120", "B00001112", "B0000112") == "B000011120" + assert replace_lab_code_token("B00001112", "B0000112", "B0000999") == "B00001112" + + +def test_edit_renames_linked_copies_and_skips_unrelated_rows(monkeypatch): + db = _session() + _seed(db) + monkeypatch.setattr(reception_svc, "_can_edit_sample_reception", lambda *args, **kwargs: True) + monkeypatch.setattr( + "app.crud.sample_reception_check_result.save_reception_check_results", + lambda *args, **kwargs: None, + ) + monkeypatch.setattr( + "app.services.protocol_reception_discard_sync.after_sample_reception_saved", + lambda *args, **kwargs: None, + ) + + reception_svc.update_sample_reception( + db, + reception_id="recv-1", + tenant_no="tenant-a", + user_id="user-1", + reception_time=_now(), + handler_user_id=None, + handler_name="质检主管", + receive_temperature="4", + checks=[], + accept_conclusion="js", + receive_attachments=None, + remark=None, + lab_storage_code="B0000112", + ) + + rec = db.query(BizSampleReception).filter_by(id="recv-1").one() + task = db.query(BizProductionTask).filter_by(id="task-1").one() + other = db.query(BizProductionTask).filter_by(id="task-other").one() + step = db.query(BizProductionTaskStep).filter_by(id="step-1").one() + step_out = db.query(BizProductionTaskStepOutput).filter_by(id="so-1").one() + output = db.query(BizProductionTaskOutput).filter_by(id="out-1").one() + product = db.query(BizCellProduct).filter_by(id="cp-1").one() + longer = db.query(BizCellProduct).filter_by(id="cp-long").one() + occ = db.query(BizStorageSlotOccupancy).filter_by(id="occ-1").one() + outbound = db.query(BizOutboundReleaseCell).filter_by(id="ob-1").one() + batches = { + row.id: row.batch_name + for row in db.query(BizQcWorkOrderInspectionBatch).all() + } + wo = db.query(BizProductionWorkOrder).filter_by(id="pwo-1").one() + qc = db.query(BizQcWorkOrder).filter_by(id="qc-1").one() + supplement = db.query(BizLabSampleProcessSupplement).filter_by(id="sup-1").one() + extra = db.query(BizLabSampleProcessingExtra).filter_by(id="extra-1").one() + kept_input = db.query(BizProductionTaskInput).filter_by(id="in-1").one() + + assert rec.lab_storage_code == "B0000112" + assert rec.sample_code == "ZKZX34000957" + assert task.task_name == "B0000112样本处理" + assert task.description == "编码B0000112" + assert other.task_name == "B00001112样本处理" + assert step.sop_content == "请处理 B0000112,不要改 B000011120" + assert step_out.output_barcode == "B0000112" + assert kept_input.input_name == "B0000112" + assert output.output_name == "B0000112" + assert output.output_barcode == "B0000112" + assert product.product_code == "B0000112" + assert product.batch_no == "B0000112" + assert longer.product_code == "B000011120" + assert occ.item_code == "B0000112" + assert outbound.product_code == "B0000112" + assert batches["batch-1"] == "B0000112-脐血" + assert batches["batch-2"] == "B0000112" + assert wo.sample_code == "ZKZX34000957" + assert qc.sample_code == "ZKZX34000957" + assert supplement.lab_storage_code == "B0000112" + assert extra.sample_code == "B0000112" + + +def test_unchanged_code_does_not_rewrite_copies(monkeypatch): + db = _session() + _seed(db) + monkeypatch.setattr(reception_svc, "_can_edit_sample_reception", lambda *args, **kwargs: True) + monkeypatch.setattr( + "app.crud.sample_reception_check_result.save_reception_check_results", + lambda *args, **kwargs: None, + ) + monkeypatch.setattr( + "app.services.protocol_reception_discard_sync.after_sample_reception_saved", + lambda *args, **kwargs: None, + ) + before = db.query(BizProductionTask).filter_by(id="task-1").one().update_time + + reception_svc.update_sample_reception( + db, + reception_id="recv-1", + tenant_no="tenant-a", + user_id="user-1", + reception_time=_now(), + handler_user_id=None, + handler_name="质检主管", + receive_temperature="4", + checks=[], + accept_conclusion="js", + receive_attachments=None, + remark=None, + lab_storage_code="B00001112", + ) + + task = db.query(BizProductionTask).filter_by(id="task-1").one() + assert task.task_name == "B00001112样本处理" + assert task.update_time == before + + +def test_duplicate_product_code_rejects_and_keeps_old_copies(monkeypatch): + db = _session() + _seed(db) + now = _now() + db.add( + BizCellProduct( + id="cp-taken", + product_code="B0000112", + product_name="已被占用", + production_task_id="task-other", + tenant_no="tenant-a", + create_dept_id="", + create_time=now, + update_time=now, + del_flag=0, + ) + ) + db.commit() + monkeypatch.setattr(reception_svc, "_can_edit_sample_reception", lambda *args, **kwargs: True) + monkeypatch.setattr( + "app.crud.sample_reception_check_result.save_reception_check_results", + lambda *args, **kwargs: None, + ) + monkeypatch.setattr( + "app.services.protocol_reception_discard_sync.after_sample_reception_saved", + lambda *args, **kwargs: None, + ) + + with pytest.raises(ValueError, match="实验室入库编码已存在"): + reception_svc.update_sample_reception( + db, + reception_id="recv-1", + tenant_no="tenant-a", + user_id="user-1", + reception_time=_now(), + handler_user_id=None, + handler_name="质检主管", + receive_temperature="4", + checks=[], + accept_conclusion="js", + receive_attachments=None, + remark=None, + lab_storage_code="B0000112", + ) + + db.rollback() + rec = db.query(BizSampleReception).filter_by(id="recv-1").one() + task = db.query(BizProductionTask).filter_by(id="task-1").one() + assert rec.lab_storage_code == "B00001112" + assert task.task_name == "B00001112样本处理"