提交
This commit is contained in:
1 parent
1ca2668112
commit
5b3edb1700
278 files changed
+53761
-36931
No files matched your search
@@ -0,0 +1,559 @@
|
||||
#!/usr/bin/env python3
|
||||
"""历史细胞产品批量补录(细胞产品库 + 库位占用)。
|
||||
|
||||
规则(与业务约定一致):
|
||||
- 冻存位置 = 冻存盒 + 序号(序号去前导 0),如 1-1-1 + 001 → 1-1-1-1
|
||||
- 产品名称、批次号 = 细胞编码
|
||||
- 产品编码(系统唯一)= 细胞编码 + '-' + 序号(去前导 0),如 MSC011-P5-1
|
||||
- 预计细胞数量:万 → 千万(1000万 = 1,5000万 = 5);写入 biz_cell_product.expected_cell_count
|
||||
- 执行顺序:旧库先执行 docs/sql/migrate_expected_cell_count_to_qianwan.sql,再导入或正常使用
|
||||
- 冻存日期 = 操作时间;有效期 = 操作时间 + 20 年
|
||||
- 创建人默认周斌倩;备注保留 TSV 整行原文(含「备注」列,共 7 列)
|
||||
- 代次:从编码末尾 -P{n} 解析(PBMC/UBMC 等无代次则留空)
|
||||
|
||||
用法:
|
||||
cd backend && source venv/bin/activate
|
||||
python scripts/import_cell_products_historical.py --dry-run
|
||||
python scripts/import_cell_products_historical.py --execute
|
||||
python scripts/import_cell_products_historical.py --execute --replace # 先删后导
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import csv
|
||||
import re
|
||||
import sys
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from typing import Dict, List, Optional, Tuple
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
REPO = ROOT.parent
|
||||
DEFAULT_TSV = REPO / "docs/data/cell_products_historical_2025.tsv"
|
||||
|
||||
if str(ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.core.database import SessionLocal
|
||||
from app.crud import cell_product as cell_product_svc
|
||||
from app.crud import storage_occupancy as occupancy_svc
|
||||
from app.crud.storage_facility import _slot_to_dict, load_facility_map
|
||||
from app.models.models import (
|
||||
BizCellProduct,
|
||||
BizStorageFacilitySlot,
|
||||
BizStorageSlotOccupancy,
|
||||
SysUser,
|
||||
)
|
||||
|
||||
PASSAGE_RE = re.compile(r"-P([1-8])$", re.IGNORECASE)
|
||||
DATE_RE = re.compile(r"^(\d{4})\.(\d{1,2})\.(\d{1,2})$")
|
||||
DATE_YEAR_ONLY_RE = re.compile(r"^(\d{4})$")
|
||||
SLOT_CODE_LINE_RE = re.compile(r"^\d+-\d+-\d+-\d+$")
|
||||
DEFAULT_EXCLUDE_SLOTS_FILE = REPO / "细胞产品库数据刷新/特别注意.md"
|
||||
|
||||
|
||||
@dataclass
|
||||
class ImportRow:
|
||||
box: str
|
||||
seq_raw: str
|
||||
cell_code: str
|
||||
count_text: str
|
||||
op_date_raw: str
|
||||
operators: str
|
||||
client_remark: str
|
||||
seq_int: int
|
||||
storage_location: str
|
||||
product_code: str
|
||||
expected_cell_count_qianwan: Optional[float]
|
||||
freeze_date: Optional[datetime]
|
||||
expiry_date: Optional[datetime]
|
||||
passage: Optional[str]
|
||||
remark: str
|
||||
|
||||
|
||||
def parse_count_to_qianwan(text: str) -> Optional[float]:
|
||||
"""TSV「细胞数量」列 → 千万:1000万=1,1千万=1,1亿=10;空值返回 None。"""
|
||||
s = (text or "").strip().replace(",", "")
|
||||
if not s:
|
||||
return None
|
||||
if "亿" in s:
|
||||
return float(s.replace("亿", "").strip()) * 10.0
|
||||
if "千万" in s:
|
||||
return float(s.replace("千万", "").strip())
|
||||
if "百万" in s:
|
||||
return float(s.replace("百万", "").strip()) / 10.0
|
||||
if "万" in s:
|
||||
return float(s.replace("万", "").strip()) / 1000.0
|
||||
raise ValueError(f"无法解析细胞数量: {text!r}")
|
||||
|
||||
|
||||
def parse_op_date(text: str) -> Optional[datetime]:
|
||||
s = (text or "").strip()
|
||||
if not s:
|
||||
return None
|
||||
m = DATE_RE.match(s)
|
||||
if m:
|
||||
return datetime(int(m.group(1)), int(m.group(2)), int(m.group(3)))
|
||||
y = DATE_YEAR_ONLY_RE.match(s)
|
||||
if y:
|
||||
return datetime(int(y.group(1)), 1, 1)
|
||||
raise ValueError(f"无法解析操作时间: {text!r}")
|
||||
|
||||
|
||||
def add_years(dt: datetime, years: int) -> datetime:
|
||||
try:
|
||||
return dt.replace(year=dt.year + years)
|
||||
except ValueError:
|
||||
# 2 月 29 日等边界
|
||||
return dt.replace(month=2, day=28, year=dt.year + years)
|
||||
|
||||
|
||||
def extract_passage(cell_code: str) -> Optional[str]:
|
||||
m = PASSAGE_RE.search((cell_code or "").strip())
|
||||
return f"P{m.group(1)}" if m else None
|
||||
|
||||
|
||||
def build_storage_location(box: str, seq_raw: str) -> Tuple[int, str]:
|
||||
seq_int = int((seq_raw or "").strip())
|
||||
box = (box or "").strip()
|
||||
return seq_int, f"{box}-{seq_int}"
|
||||
|
||||
|
||||
def build_product_code(cell_code: str, seq_int: int, box: Optional[str] = None) -> str:
|
||||
cell = (cell_code or "").strip()
|
||||
if box:
|
||||
return f"{cell}-{(box or '').strip()}-{seq_int}"
|
||||
return f"{cell}-{seq_int}"
|
||||
|
||||
|
||||
def assign_product_codes(rows: List[ImportRow]) -> None:
|
||||
"""单冻存盒批次:{细胞编码}-{序号};多冻存盒批次加冻存盒前缀避免跨盒序号重复。"""
|
||||
multi_box = len({r.box for r in rows}) > 1
|
||||
for row in rows:
|
||||
row.product_code = build_product_code(
|
||||
row.cell_code, row.seq_int, row.box if multi_box else None
|
||||
)
|
||||
|
||||
|
||||
def load_exclude_slots(path: Optional[Path]) -> set[str]:
|
||||
"""从特别注意.md 等文件读取不刷新的储物格编号(每行一个,如 1-1-1-1)。"""
|
||||
if path is None or not path.is_file():
|
||||
return set()
|
||||
result: set[str] = set()
|
||||
for line in path.read_text(encoding="utf-8").splitlines():
|
||||
s = line.strip()
|
||||
if SLOT_CODE_LINE_RE.match(s):
|
||||
result.add(s)
|
||||
return result
|
||||
|
||||
|
||||
def split_rows_by_exclude(
|
||||
rows: List[ImportRow], exclude_locations: set[str]
|
||||
) -> Tuple[List[ImportRow], List[ImportRow]]:
|
||||
if not exclude_locations:
|
||||
return rows, []
|
||||
kept = [r for r in rows if r.storage_location not in exclude_locations]
|
||||
skipped = [r for r in rows if r.storage_location in exclude_locations]
|
||||
return kept, skipped
|
||||
|
||||
|
||||
def load_tsv(path: Path) -> List[ImportRow]:
|
||||
rows: List[ImportRow] = []
|
||||
with path.open("r", encoding="utf-8") as f:
|
||||
reader = csv.DictReader(f, delimiter="\t")
|
||||
for raw in reader:
|
||||
box = (raw.get("冻存盒") or "").strip()
|
||||
seq_raw = (raw.get("序号") or "").strip()
|
||||
cell_code = (raw.get("细胞编码") or "").strip()
|
||||
count_text = (raw.get("细胞数量") or "").strip()
|
||||
op_date_raw = (raw.get("操作时间") or "").strip()
|
||||
operators = (raw.get("操作人") or "").strip()
|
||||
client_remark = (raw.get("备注") or "").strip()
|
||||
if not box or not seq_raw or not cell_code:
|
||||
continue
|
||||
seq_int, storage_location = build_storage_location(box, seq_raw)
|
||||
freeze_date = parse_op_date(op_date_raw)
|
||||
remark = "\t".join(
|
||||
[box, seq_raw, cell_code, count_text, op_date_raw, operators, client_remark]
|
||||
)
|
||||
if len(remark) > 512:
|
||||
raise ValueError(
|
||||
f"备注超长(>{512} 字符): 序号 {seq_raw} @ {storage_location}"
|
||||
)
|
||||
rows.append(
|
||||
ImportRow(
|
||||
box=box,
|
||||
seq_raw=seq_raw,
|
||||
cell_code=cell_code,
|
||||
count_text=count_text,
|
||||
op_date_raw=op_date_raw,
|
||||
operators=operators,
|
||||
client_remark=client_remark,
|
||||
seq_int=seq_int,
|
||||
storage_location=storage_location,
|
||||
product_code="",
|
||||
expected_cell_count_qianwan=parse_count_to_qianwan(count_text),
|
||||
freeze_date=freeze_date,
|
||||
expiry_date=add_years(freeze_date, 20) if freeze_date else None,
|
||||
passage=extract_passage(cell_code),
|
||||
remark=remark,
|
||||
)
|
||||
)
|
||||
assign_product_codes(rows)
|
||||
return rows
|
||||
|
||||
|
||||
def build_slot_map(db: Session, tenant_no: str) -> Dict[str, str]:
|
||||
facility_by_id = load_facility_map(db, tenant_no)
|
||||
slots = (
|
||||
db.query(BizStorageFacilitySlot)
|
||||
.filter(
|
||||
BizStorageFacilitySlot.tenant_no == tenant_no,
|
||||
BizStorageFacilitySlot.del_flag == 0,
|
||||
)
|
||||
.all()
|
||||
)
|
||||
mapping: Dict[str, str] = {}
|
||||
dupes: Dict[str, List[str]] = {}
|
||||
for slot in slots:
|
||||
row = _slot_to_dict(slot, facility_by_id)
|
||||
full = (row.get("fullSlotCode") or "").strip()
|
||||
if not full:
|
||||
continue
|
||||
if full in mapping:
|
||||
dupes.setdefault(full, [mapping[full]]).append(slot.id)
|
||||
else:
|
||||
mapping[full] = slot.id
|
||||
if dupes:
|
||||
parts = [f"{code}: {ids}" for code, ids in dupes.items()]
|
||||
raise ValueError(f"储物格完整编号重复,无法导入: {'; '.join(parts)}")
|
||||
return mapping
|
||||
|
||||
|
||||
def resolve_operator(
|
||||
db: Session, tenant_no: str, nick_name: str
|
||||
) -> Tuple[str, str]:
|
||||
user = (
|
||||
db.query(SysUser)
|
||||
.filter(
|
||||
SysUser.tenant_no == tenant_no,
|
||||
SysUser.nick_name == nick_name,
|
||||
SysUser.del_flag == 0,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if not user:
|
||||
raise ValueError(f"未找到操作人用户: {nick_name!r}(tenant_no={tenant_no})")
|
||||
dept_id = (user.dept_id or "").strip() or ""
|
||||
return user.id, dept_id
|
||||
|
||||
|
||||
def purge_existing_products(
|
||||
db: Session,
|
||||
tenant_no: str,
|
||||
codes: List[str],
|
||||
user_id: Optional[str] = None,
|
||||
) -> int:
|
||||
"""软删除已有产品并释放库位占用,便于重新导入。"""
|
||||
removed = 0
|
||||
for code in codes:
|
||||
obj = (
|
||||
db.query(BizCellProduct)
|
||||
.filter(
|
||||
BizCellProduct.tenant_no == tenant_no,
|
||||
BizCellProduct.product_code == code,
|
||||
BizCellProduct.del_flag == 0,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if not obj:
|
||||
continue
|
||||
occupancy_svc.remove_by_item_no_commit(db, "cell_product", obj.id, user_id=user_id)
|
||||
obj.del_flag = 1
|
||||
obj.update_by = user_id
|
||||
obj.update_time = datetime.now()
|
||||
db.add(obj)
|
||||
removed += 1
|
||||
if removed:
|
||||
db.commit()
|
||||
return removed
|
||||
|
||||
|
||||
def existing_product_codes(db: Session, tenant_no: str, codes: List[str]) -> List[str]:
|
||||
if not codes:
|
||||
return []
|
||||
found = (
|
||||
db.query(BizCellProduct.product_code)
|
||||
.filter(
|
||||
BizCellProduct.tenant_no == tenant_no,
|
||||
BizCellProduct.product_code.in_(codes),
|
||||
BizCellProduct.del_flag == 0,
|
||||
)
|
||||
.all()
|
||||
)
|
||||
return [x[0] for x in found]
|
||||
|
||||
|
||||
def patch_timestamps(
|
||||
db: Session,
|
||||
*,
|
||||
product_id: str,
|
||||
user_id: str,
|
||||
op_dt: datetime,
|
||||
) -> None:
|
||||
product = (
|
||||
db.query(BizCellProduct)
|
||||
.filter(BizCellProduct.id == product_id, BizCellProduct.del_flag == 0)
|
||||
.first()
|
||||
)
|
||||
if product:
|
||||
product.create_by = user_id
|
||||
product.update_by = user_id
|
||||
product.create_time = op_dt
|
||||
product.update_time = op_dt
|
||||
|
||||
occ = (
|
||||
db.query(BizStorageSlotOccupancy)
|
||||
.filter(
|
||||
BizStorageSlotOccupancy.item_type == "cell_product",
|
||||
BizStorageSlotOccupancy.item_id == product_id,
|
||||
BizStorageSlotOccupancy.del_flag == 0,
|
||||
BizStorageSlotOccupancy.occupancy_status == "stored",
|
||||
)
|
||||
.order_by(BizStorageSlotOccupancy.create_time.desc())
|
||||
.first()
|
||||
)
|
||||
if occ:
|
||||
occ.create_by = user_id
|
||||
occ.update_by = user_id
|
||||
occ.stored_at = op_dt
|
||||
occ.create_time = op_dt
|
||||
occ.update_time = op_dt
|
||||
|
||||
slot_id = (product.storage_slot_id or "").strip() if product else ""
|
||||
if slot_id:
|
||||
slot = (
|
||||
db.query(BizStorageFacilitySlot)
|
||||
.filter(BizStorageFacilitySlot.id == slot_id, BizStorageFacilitySlot.del_flag == 0)
|
||||
.first()
|
||||
)
|
||||
if slot:
|
||||
slot.last_stored_at = op_dt
|
||||
|
||||
|
||||
def import_one(
|
||||
db: Session,
|
||||
*,
|
||||
tenant_no: str,
|
||||
user_id: str,
|
||||
dept_id: str,
|
||||
row: ImportRow,
|
||||
slot_id: str,
|
||||
) -> str:
|
||||
payload = SimpleNamespace(
|
||||
product_code=row.product_code,
|
||||
product_name=row.cell_code,
|
||||
product_type_id=None,
|
||||
spec_id=None,
|
||||
batch_no=row.cell_code,
|
||||
storage_slot_id=slot_id,
|
||||
passage=row.passage,
|
||||
freeze_date=row.freeze_date,
|
||||
expected_cell_count=row.expected_cell_count_qianwan,
|
||||
viability=None,
|
||||
product_status="frozen",
|
||||
source_type="manual",
|
||||
quantity=1,
|
||||
unit=None,
|
||||
expiry_date=row.expiry_date,
|
||||
product_images=None,
|
||||
remark=row.remark,
|
||||
)
|
||||
obj = cell_product_svc.create_cell_product(
|
||||
db,
|
||||
tenant_no=tenant_no,
|
||||
user_id=user_id,
|
||||
create_dept_id=dept_id,
|
||||
data=payload,
|
||||
)
|
||||
patch_timestamps(
|
||||
db,
|
||||
product_id=obj.id,
|
||||
user_id=user_id,
|
||||
op_dt=row.freeze_date or datetime.now(),
|
||||
)
|
||||
db.commit()
|
||||
return obj.id
|
||||
|
||||
|
||||
def validate_rows(
|
||||
db: Session,
|
||||
tenant_no: str,
|
||||
rows: List[ImportRow],
|
||||
slot_map: Dict[str, str],
|
||||
*,
|
||||
skip_existing_codes: bool = False,
|
||||
) -> List[str]:
|
||||
errors: List[str] = []
|
||||
codes = [r.product_code for r in rows]
|
||||
if len(codes) != len(set(codes)):
|
||||
errors.append("导入数据内产品编码重复")
|
||||
if not skip_existing_codes:
|
||||
dup_db = existing_product_codes(db, tenant_no, codes)
|
||||
if dup_db:
|
||||
errors.append(
|
||||
f"库中已存在产品编码 ({len(dup_db)}): {', '.join(dup_db[:5])}"
|
||||
f"{'…' if len(dup_db) > 5 else ''}(可加 --replace 先删后导)"
|
||||
)
|
||||
|
||||
slot_ids: List[str] = []
|
||||
for row in rows:
|
||||
slot_id = slot_map.get(row.storage_location)
|
||||
if not slot_id:
|
||||
errors.append(f"未找到储物格 {row.storage_location}(序号 {row.seq_raw})")
|
||||
continue
|
||||
slot_ids.append(slot_id)
|
||||
|
||||
if len(slot_ids) != len(set(slot_ids)):
|
||||
errors.append("导入数据内储物格重复")
|
||||
|
||||
missing_slots = set()
|
||||
for loc in {r.storage_location for r in rows}:
|
||||
if loc not in slot_map:
|
||||
missing_slots.add(loc)
|
||||
if missing_slots:
|
||||
sample = ", ".join(sorted(missing_slots)[:8])
|
||||
errors.append(f"缺失储物格编号 ({len(missing_slots)}): {sample}{'…' if len(missing_slots) > 8 else ''}")
|
||||
|
||||
return errors
|
||||
|
||||
|
||||
def print_preview(rows: List[ImportRow], slot_map: Dict[str, str], limit: int = 5) -> None:
|
||||
print(f"共 {len(rows)} 条待导入。")
|
||||
print("示例(前几条):")
|
||||
print(f"{'产品编码':<22} {'储物格':<12} {'千万':>6} {'冻存日':<12} {'代次':<4} 备注")
|
||||
for row in rows[:limit]:
|
||||
slot_ok = "✓" if row.storage_location in slot_map else "✗"
|
||||
count_str = (
|
||||
f"{row.expected_cell_count_qianwan:>6.4f}"
|
||||
if row.expected_cell_count_qianwan is not None
|
||||
else " -"
|
||||
)
|
||||
date_str = row.freeze_date.strftime("%Y-%m-%d") if row.freeze_date else "-"
|
||||
print(
|
||||
f"{row.product_code:<22} {row.storage_location:<10}{slot_ok} "
|
||||
f"{count_str} {date_str:<12} "
|
||||
f"{row.passage or '-':<4} {row.remark[:40]}…"
|
||||
)
|
||||
if len(rows) > limit:
|
||||
print(f"… 其余 {len(rows) - limit} 条略")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description="历史细胞产品批量补录")
|
||||
parser.add_argument(
|
||||
"--file",
|
||||
type=Path,
|
||||
default=DEFAULT_TSV,
|
||||
help=f"TSV 数据文件(默认 {DEFAULT_TSV.relative_to(REPO)})",
|
||||
)
|
||||
parser.add_argument("--tenant-no", default="zkxw")
|
||||
parser.add_argument("--operator", default="周斌倩", help="create_by 对应用户 nick_name")
|
||||
parser.add_argument(
|
||||
"--execute",
|
||||
action="store_true",
|
||||
help="实际写入数据库(默认仅 dry-run)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--replace",
|
||||
action="store_true",
|
||||
help="导入前先软删除同产品编码的已有记录并释放库位",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--exclude-slots-file",
|
||||
type=Path,
|
||||
default=None,
|
||||
help=f"不刷新的储物格列表文件(默认不读;可指向 {DEFAULT_EXCLUDE_SLOTS_FILE.name})",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
if not args.file.is_file():
|
||||
print(f"数据文件不存在: {args.file}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
all_rows = load_tsv(args.file)
|
||||
if not all_rows:
|
||||
print("未解析到任何数据行", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
exclude_locations = load_exclude_slots(args.exclude_slots_file)
|
||||
rows, skipped_rows = split_rows_by_exclude(all_rows, exclude_locations)
|
||||
if not rows:
|
||||
print("排除指定库位后无待导入数据", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
db = SessionLocal()
|
||||
try:
|
||||
slot_map = build_slot_map(db, args.tenant_no)
|
||||
user_id, dept_id = resolve_operator(db, args.tenant_no, args.operator)
|
||||
print(f"操作人: {args.operator} (id={user_id})")
|
||||
if exclude_locations:
|
||||
print(f"跳过不刷新的库位 ({len(exclude_locations)}): {', '.join(sorted(exclude_locations))}")
|
||||
if skipped_rows:
|
||||
print(f"因库位排除跳过 {len(skipped_rows)} 条: {', '.join(r.product_code for r in skipped_rows)}")
|
||||
|
||||
if args.replace and args.execute:
|
||||
codes = [r.product_code for r in rows]
|
||||
n = purge_existing_products(db, args.tenant_no, codes, user_id=user_id)
|
||||
print(f"已清理旧数据 {n} 条。")
|
||||
|
||||
errors = validate_rows(
|
||||
db, args.tenant_no, rows, slot_map, skip_existing_codes=args.replace
|
||||
)
|
||||
print_preview(rows, slot_map)
|
||||
|
||||
if errors:
|
||||
print("\n校验失败:")
|
||||
for err in errors:
|
||||
print(f" - {err}")
|
||||
return 1
|
||||
|
||||
if not args.execute:
|
||||
print("\n[dry-run] 校验通过,未写入。确认后请加 --execute 执行导入。")
|
||||
return 0
|
||||
|
||||
ok = 0
|
||||
for i, row in enumerate(rows, 1):
|
||||
slot_id = slot_map[row.storage_location]
|
||||
try:
|
||||
import_one(
|
||||
db,
|
||||
tenant_no=args.tenant_no,
|
||||
user_id=user_id,
|
||||
dept_id=dept_id,
|
||||
row=row,
|
||||
slot_id=slot_id,
|
||||
)
|
||||
ok += 1
|
||||
if i % 10 == 0 or i == len(rows):
|
||||
print(f" 已导入 {i}/{len(rows)} …")
|
||||
except Exception as e:
|
||||
db.rollback()
|
||||
print(
|
||||
f"\n第 {i} 条失败({row.product_code} @ {row.storage_location}): {e}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return 1
|
||||
|
||||
print(f"\n导入完成:成功 {ok} 条。" + (f"(跳过 {len(skipped_rows)} 条)" if skipped_rows else ""))
|
||||
return 0
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in new issue
Block a user