Files
zkxw/backend/scripts/repair_reception_downstream_after_bj_to_js.py
T
zlwuandCursor 3e32ba9085 chore(scripts): 增加合同重复单与接收下游补建修复脚本
供运维 dry-run/--apply 修历史数据,不改日常接口路径。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-12-02 15:21:27 +08:00

309 lines
9.9 KiB
Python

#!/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())