This commit is contained in:
zlwu committed 2026-05-28 08:37:37 +08:00
1 parent 2020f371f4
commit f1f5d24eff
31 files changed
+13600 -13813

No files matched your search

+2 -2
View File
@@ -212,7 +212,7 @@ STATIC_MENU_TREE = [
"name": "QualityInspectionQcWorkOrder",
"path": "qc-work-order",
"component": "/quality-inspection/qc-work-order/index",
"meta": {"title": "质检管理", "keepAlive": True, "menuCode": "biz:qcWorkOrder:list"},
"meta": {"title": "质检工单", "keepAlive": True, "menuCode": "biz:qcWorkOrder:list"},
},
],
},
@@ -251,7 +251,7 @@ STATIC_MENU_TREE = [
"name": "ProductionWorkOrder",
"path": "production-work-order",
"component": "/production/production-work-order/index",
"meta": {"title": "生产管理", "keepAlive": True, "menuCode": "production:work-order:list"},
"meta": {"title": "生产工单", "keepAlive": True, "menuCode": "production:work-order:list"},
},
],
},
@@ -7,7 +7,7 @@ from sqlalchemy.orm import Session
from app.core.database import get_db
from app.core.menu_guard import require_admin_or_super_admin
from app.core.response import error_response, success_response
from app.core.response import error_response, format_api_error_message, success_response
from app.crud import pilot_infusion_schedule_mgmt as crud
from app.crud import outbound_handover as handover_crud
from app.models.models import SysUser
@@ -218,8 +218,8 @@ async def api_get_outbound_handover(
return error_response(403, str(e))
except Exception as e:
if hasattr(e, "status_code") and getattr(e, "status_code") == 404:
return error_response(404, str(getattr(e, "detail", e)))
return error_response(400, str(getattr(e, "detail", e)))
return error_response(404, format_api_error_message(e, fallback="资源不存在"))
return error_response(400, format_api_error_message(e))
@router.put("/pilot-infusion-schedule-mgmt/{schedule_id}/outbound-handover")
@@ -258,6 +258,5 @@ async def api_save_outbound_handover(
db.rollback()
if hasattr(e, "status_code"):
code = int(getattr(e, "status_code", 400))
detail = getattr(e, "detail", str(e))
return error_response(code, detail if isinstance(detail, str) else str(detail))
return error_response(400, str(getattr(e, "detail", e)))
return error_response(code, format_api_error_message(e))
return error_response(400, format_api_error_message(e, fallback="出库交接保存失败"))
+17
View File
@@ -36,6 +36,23 @@ def success_response(data: Any = None, message: str = "success") -> dict:
}
def format_api_error_message(exc: Exception, *, fallback: str = "操作失败") -> str:
"""将 HTTP/SQLAlchemy 等异常转为可展示的错误文案(避免 str([]) 空列表)。"""
if isinstance(exc, PermissionError):
return str(exc) or fallback
status_code = getattr(exc, "status_code", None)
if status_code is not None:
detail = getattr(exc, "detail", None)
if isinstance(detail, str) and detail.strip():
return detail
if detail not in (None, "", []):
return str(detail)
msg = str(exc).strip()
if msg and msg != "[]":
return msg
return fallback
def error_response(code: int = 400, message: str = "error", data: Any = None) -> dict:
"""错误响应"""
from datetime import datetime
+75 -13
View File
@@ -20,6 +20,73 @@ from app.models.models import (
BizStorageFacilitySlot,
)
_CELL_PRODUCT_STATUSES = frozenset(
{"frozen", "in_production", "sold", "used", "voided", "thawed"}
)
_CELL_PRODUCT_RELEASE_STATUSES = frozenset({"sold", "used", "voided"})
_CELL_PRODUCT_STORE_STATUSES = frozenset({"frozen", "thawed", "in_production"})
def _apply_cell_product_status_change(
db: Session,
obj: BizCellProduct,
to_status: str,
tenant_no: str,
user_id: Optional[str],
now: datetime,
) -> None:
"""管理端手动改状态:允许在合法枚举间任意变更,并同步库位占用。"""
from_status = (obj.product_status or "").strip()
to_status = (to_status or "").strip()
if to_status == from_status:
return
if to_status not in _CELL_PRODUCT_STATUSES:
raise ValueError(
f"状态必须为 {'/'.join(sorted(_CELL_PRODUCT_STATUSES))}"
)
obj.product_status = to_status
slot_id = (obj.storage_slot_id or "").strip()
if to_status in _CELL_PRODUCT_RELEASE_STATUSES:
if slot_id:
try:
occupancy_svc.remove_by_item(
db, "cell_product", obj.id, user_id=user_id,
)
except Exception:
pass
return
if to_status in _CELL_PRODUCT_STORE_STATUSES and slot_id:
existing = db.query(BizStorageSlotOccupancy).filter(
BizStorageSlotOccupancy.item_type == "cell_product",
BizStorageSlotOccupancy.item_id == obj.id,
BizStorageSlotOccupancy.occupancy_status == "stored",
BizStorageSlotOccupancy.del_flag == 0,
).first()
if existing:
return
occ = BizStorageSlotOccupancy(
id=generate_uuid(),
slot_id=slot_id,
item_type="cell_product",
item_id=obj.id,
item_code=obj.product_code or "",
item_name=obj.product_name or "",
item_source=obj.source_type or "manual",
stored_at=now,
occupancy_status="stored",
tenant_no=tenant_no,
order_num=0,
create_by=user_id,
create_dept_id="",
create_time=now,
update_by=user_id,
update_time=now,
del_flag=0,
)
db.add(occ)
db.flush()
occupancy_svc._refresh_slot_cache(db, slot_id)
def _row_to_dict(c: BizCellProduct) -> Dict[str, Any]:
return {
@@ -393,19 +460,14 @@ def update_cell_product(
if hasattr(data, "viability") and data.viability is not None:
obj.viability = data.viability
if data.product_status is not None and data.product_status != obj.product_status:
allowed = {"frozen": {"sold", "used", "voided"}}
from_status = obj.product_status
to_status = data.product_status
if from_status not in allowed or to_status not in allowed[from_status]:
raise ValueError(f"不允许从状态 {from_status} 变更为 {to_status}")
obj.product_status = data.product_status
if obj.storage_slot_id:
try:
occupancy_svc.remove_by_item(
db, "cell_product", obj.id, user_id=user_id,
)
except Exception:
pass
_apply_cell_product_status_change(
db,
obj,
data.product_status,
tenant_no,
user_id,
datetime.now(),
)
if data.quantity is not None:
obj.quantity = data.quantity
if data.unit is not None:
@@ -66,7 +66,7 @@ def _restore_cell_occupancy_no_commit(
slot_id = (product.storage_slot_id or "").strip()
if not slot_id:
return
existing = (
existing_stored = (
db.query(BizStorageSlotOccupancy)
.filter(
BizStorageSlotOccupancy.item_type == "cell_product",
@@ -76,9 +76,29 @@ def _restore_cell_occupancy_no_commit(
)
.first()
)
if existing:
if existing_stored:
return
now = datetime.now()
latest_removed = (
db.query(BizStorageSlotOccupancy)
.filter(
BizStorageSlotOccupancy.item_type == "cell_product",
BizStorageSlotOccupancy.item_id == product.id,
BizStorageSlotOccupancy.occupancy_status == "removed",
BizStorageSlotOccupancy.del_flag == 0,
)
.order_by(BizStorageSlotOccupancy.removed_at.desc())
.first()
)
if latest_removed:
latest_removed.occupancy_status = "stored"
latest_removed.removed_at = None
latest_removed.update_by = user_id
latest_removed.update_time = now
db.add(latest_removed)
db.flush()
occupancy_svc._refresh_slot_cache(db, latest_removed.slot_id)
return
db.add(
BizStorageSlotOccupancy(
id=generate_uuid(),
+153 -56
View File
@@ -126,6 +126,73 @@ def _material_header_to_dict(
}
def _soft_delete_outbound_cells_not_in(
db: Session,
schedule_id: str,
tenant_no: str,
keep_cell_product_ids: set,
user_id: str,
now: datetime,
) -> None:
q = db.query(BizOutboundReleaseCell).filter(
BizOutboundReleaseCell.infusion_schedule_id == schedule_id,
BizOutboundReleaseCell.tenant_no == tenant_no,
BizOutboundReleaseCell.del_flag == 0,
)
if keep_cell_product_ids:
q = q.filter(BizOutboundReleaseCell.cell_product_id.notin_(keep_cell_product_ids))
q.update({"del_flag": 1, "update_by": user_id, "update_time": now}, synchronize_session=False)
def _soft_delete_outbound_qc_materials_not_in(
db: Session,
schedule_id: str,
tenant_no: str,
keep_qc_material_ids: set,
user_id: str,
now: datetime,
) -> None:
q = db.query(BizOutboundReleaseQcMaterial).filter(
BizOutboundReleaseQcMaterial.infusion_schedule_id == schedule_id,
BizOutboundReleaseQcMaterial.tenant_no == tenant_no,
BizOutboundReleaseQcMaterial.del_flag == 0,
)
if keep_qc_material_ids:
q = q.filter(BizOutboundReleaseQcMaterial.qc_material_id.notin_(keep_qc_material_ids))
q.update({"del_flag": 1, "update_by": user_id, "update_time": now}, synchronize_session=False)
def _find_outbound_cell_row(
db: Session, schedule_id: str, tenant_no: str, cell_product_id: str
) -> Optional[BizOutboundReleaseCell]:
"""按 schedule+cell 查找台账行(优先未删除)。"""
return (
db.query(BizOutboundReleaseCell)
.filter(
BizOutboundReleaseCell.infusion_schedule_id == schedule_id,
BizOutboundReleaseCell.cell_product_id == cell_product_id,
BizOutboundReleaseCell.tenant_no == tenant_no,
)
.order_by(BizOutboundReleaseCell.del_flag.asc())
.first()
)
def _find_outbound_qc_material_row(
db: Session, schedule_id: str, tenant_no: str, qc_material_id: str
) -> Optional[BizOutboundReleaseQcMaterial]:
return (
db.query(BizOutboundReleaseQcMaterial)
.filter(
BizOutboundReleaseQcMaterial.infusion_schedule_id == schedule_id,
BizOutboundReleaseQcMaterial.qc_material_id == qc_material_id,
BizOutboundReleaseQcMaterial.tenant_no == tenant_no,
)
.order_by(BizOutboundReleaseQcMaterial.del_flag.asc())
.first()
)
def _get_schedule(db: Session, schedule_id: str, tenant_no: str) -> Optional[BizPilotInfusionSchedule]:
sid = (schedule_id or "").strip()
if not sid:
@@ -277,17 +344,14 @@ def save_outbound_material(
header.remark = (remark or "").strip() or None
db.add(header)
db.query(BizOutboundReleaseCell).filter(
BizOutboundReleaseCell.infusion_schedule_id == schedule_id,
BizOutboundReleaseCell.tenant_no == tenant_no,
BizOutboundReleaseCell.del_flag == 0,
).update({"del_flag": 1, "update_by": user_id, "update_time": now}, synchronize_session=False)
db.query(BizOutboundReleaseQcMaterial).filter(
BizOutboundReleaseQcMaterial.infusion_schedule_id == schedule_id,
BizOutboundReleaseQcMaterial.tenant_no == tenant_no,
BizOutboundReleaseQcMaterial.del_flag == 0,
).update({"del_flag": 1, "update_by": user_id, "update_time": now}, synchronize_session=False)
incoming_cell_ids = {x for x in cell_ids if x}
incoming_qc_ids = {x for x in qc_ids if x}
_soft_delete_outbound_cells_not_in(
db, schedule_id, tenant_no, incoming_cell_ids, user_id, now
)
_soft_delete_outbound_qc_materials_not_in(
db, schedule_id, tenant_no, incoming_qc_ids, user_id, now
)
db.query(BizOutboundReleasePaper).filter(
BizOutboundReleasePaper.infusion_schedule_id == schedule_id,
@@ -319,31 +383,49 @@ def save_outbound_material(
[cell_product_svc._row_to_dict(product)],
)[0]
db.add(
BizOutboundReleaseCell(
id=generate_uuid(),
material_id=header.id,
infusion_schedule_id=schedule_id,
cell_product_id=cp_id,
product_code=enriched.get("productCode") or "",
product_name=enriched.get("productName") or "",
product_type_name=enriched.get("productTypeName") or "",
spec_name=enriched.get("specName") or "",
passage=enriched.get("passage") or "",
batch_no=enriched.get("batchNo") or "",
storage_slot_name=enriched.get("storageSlotName") or "",
product_status=enriched.get("productStatus") or "",
tenant_no=tenant_no,
order_num=idx + 1,
remark=(item.get("remark") or "").strip() or None,
create_by=user_id,
create_dept_id=create_dept_id or "",
create_time=now,
update_by=user_id,
update_time=now,
del_flag=0,
cell_row = _find_outbound_cell_row(db, schedule_id, tenant_no, cp_id)
if cell_row:
cell_row.material_id = header.id
cell_row.product_code = enriched.get("productCode") or ""
cell_row.product_name = enriched.get("productName") or ""
cell_row.product_type_name = enriched.get("productTypeName") or ""
cell_row.spec_name = enriched.get("specName") or ""
cell_row.passage = enriched.get("passage") or ""
cell_row.batch_no = enriched.get("batchNo") or ""
cell_row.storage_slot_name = enriched.get("storageSlotName") or ""
cell_row.product_status = enriched.get("productStatus") or ""
cell_row.order_num = idx + 1
cell_row.remark = (item.get("remark") or "").strip() or None
cell_row.del_flag = 0
cell_row.update_by = user_id
cell_row.update_time = now
db.add(cell_row)
else:
db.add(
BizOutboundReleaseCell(
id=generate_uuid(),
material_id=header.id,
infusion_schedule_id=schedule_id,
cell_product_id=cp_id,
product_code=enriched.get("productCode") or "",
product_name=enriched.get("productName") or "",
product_type_name=enriched.get("productTypeName") or "",
spec_name=enriched.get("specName") or "",
passage=enriched.get("passage") or "",
batch_no=enriched.get("batchNo") or "",
storage_slot_name=enriched.get("storageSlotName") or "",
product_status=enriched.get("productStatus") or "",
tenant_no=tenant_no,
order_num=idx + 1,
remark=(item.get("remark") or "").strip() or None,
create_by=user_id,
create_dept_id=create_dept_id or "",
create_time=now,
update_by=user_id,
update_time=now,
del_flag=0,
)
)
)
for idx, item in enumerate(qc_materials or []):
mid = (item.get("materialId") or item.get("material_id") or "").strip()
@@ -369,28 +451,43 @@ def save_outbound_material(
if not material:
raise HTTPException(status_code=400, detail=f"质检物料不存在或已删除(ID: {mid})")
db.add(
BizOutboundReleaseQcMaterial(
id=generate_uuid(),
material_id=header.id,
infusion_schedule_id=schedule_id,
qc_material_id=mid,
qty=qty_dec,
material_code=material.material_code or "",
material_name=material.material_name or "",
spec_model=material.spec_model or "",
unit=material.unit or "",
tenant_no=tenant_no,
order_num=idx + 1,
remark=(item.get("remark") or "").strip() or None,
create_by=user_id,
create_dept_id=create_dept_id or "",
create_time=now,
update_by=user_id,
update_time=now,
del_flag=0,
qc_row = _find_outbound_qc_material_row(db, schedule_id, tenant_no, mid)
if qc_row:
qc_row.material_id = header.id
qc_row.qty = qty_dec
qc_row.material_code = material.material_code or ""
qc_row.material_name = material.material_name or ""
qc_row.spec_model = material.spec_model or ""
qc_row.unit = material.unit or ""
qc_row.order_num = idx + 1
qc_row.remark = (item.get("remark") or "").strip() or None
qc_row.del_flag = 0
qc_row.update_by = user_id
qc_row.update_time = now
db.add(qc_row)
else:
db.add(
BizOutboundReleaseQcMaterial(
id=generate_uuid(),
material_id=header.id,
infusion_schedule_id=schedule_id,
qc_material_id=mid,
qty=qty_dec,
material_code=material.material_code or "",
material_name=material.material_name or "",
spec_model=material.spec_model or "",
unit=material.unit or "",
tenant_no=tenant_no,
order_num=idx + 1,
remark=(item.get("remark") or "").strip() or None,
create_by=user_id,
create_dept_id=create_dept_id or "",
create_time=now,
update_by=user_id,
update_time=now,
del_flag=0,
)
)
)
for idx, item in enumerate(paper_materials or []):
paper_name = (item.get("paperName") or item.get("paper_name") or "").strip()
+49
View File
@@ -981,6 +981,53 @@ def update_production_task(
return task
def _consume_task_input_cell_products(
db: Session,
task_id: str,
user_id: Optional[str],
now: datetime,
) -> None:
"""任务首次完成时,将原材料中的细胞产品标记为已使用并释放库位占用。"""
input_rows = db.query(BizProductionTaskInput).filter(
and_(
BizProductionTaskInput.task_id == task_id,
BizProductionTaskInput.del_flag == 0,
BizProductionTaskInput.input_type == "cell_product",
BizProductionTaskInput.input_id.isnot(None),
BizProductionTaskInput.input_id != "",
)
).all()
seen_ids: set = set()
consumable_from = frozenset({"frozen", "thawed", "in_production"})
for row in input_rows:
cp_id = (row.input_id or "").strip()
if not cp_id or cp_id in seen_ids:
continue
seen_ids.add(cp_id)
product = db.query(BizCellProduct).filter(
BizCellProduct.id == cp_id,
BizCellProduct.del_flag == 0,
).first()
if not product:
continue
current = (product.product_status or "").strip()
if current in ("used", "voided", "sold"):
continue
if current not in consumable_from:
continue
product.product_status = "used"
product.update_by = user_id
product.update_time = now
db.add(product)
if product.storage_slot_id:
try:
occupancy_svc.remove_by_item(
db, "cell_product", product.id, user_id=user_id,
)
except Exception:
pass
def update_task_status(
db: Session,
task_id: str,
@@ -1016,6 +1063,8 @@ def update_task_status(
task.remark = (remark or "").strip() or None
if previous_status != "ywc" and not task.completed_time:
task.completed_time = now
if previous_status != "ywc":
_consume_task_input_cell_products(db, task.id, user_id, now)
task.update_by = user_id
task.update_time = now
db.add(task)
+2 -2
View File
@@ -42,9 +42,9 @@ class BizQcMaterialUsage(Base):
receiver = Column(String(64), nullable=True, comment="领用人(手动出库)")
purpose = Column(String(512), nullable=True, comment="用途/事由(手动出库)")
source_type = Column(
String(16),
String(32),
nullable=False,
comment="来源:task_complete / manual_in / manual_out",
comment="来源:task_complete / manual_in / manual_out / outbound_handover",
)
tenant_no = Column(String(64), nullable=False, default="zkxw", comment="租户编号")
remark = Column(String(512), nullable=True, comment="备注")