From f843ad917ae06d90487013e82a3086e1319ea499 Mon Sep 17 00:00:00 2001 From: zlwu <704541015@qq.com> Date: Wed, 2 Dec 2026 15:21:26 +0800 Subject: [PATCH] =?UTF-8?q?feat(qc):=20=E7=BC=96=E8=BE=91=E6=8E=A5?= =?UTF-8?q?=E6=94=B6=E6=97=B6=E5=90=8C=E6=AD=A5=E6=94=B9=E5=86=99=E4=B8=8B?= =?UTF-8?q?=E6=B8=B8=E5=AE=9E=E9=AA=8C=E5=AE=A4=E5=85=A5=E5=BA=93=E7=BC=96?= =?UTF-8?q?=E7=A0=81=E5=89=AF=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 避免只改接收表编码后,生产/质检/库位等关联副本仍保留旧码。 Co-authored-by: Cursor --- backend/app/crud/sample_reception.py | 13 + .../app/services/lab_storage_code_rename.py | 399 +++++++++++++++ backend/tests/test_lab_storage_code_rename.py | 460 ++++++++++++++++++ 3 files changed, 872 insertions(+) create mode 100644 backend/app/services/lab_storage_code_rename.py create mode 100644 backend/tests/test_lab_storage_code_rename.py 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/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样本处理"