Files
shanxia2.0/backend/app/crud/pilot_checkup.py
T
2026-05-25 15:14:06 +08:00

478 lines
16 KiB
Python

"""中试申请单-体检 CRUD(体检信息、预约项目、实际项目)"""
from __future__ import annotations
import uuid
from datetime import datetime
from typing import Any, Dict, List, Optional
from sqlalchemy import func
from sqlalchemy.orm import Session
from app.models.models import (
BizCheckupInstitution,
BizPilotCheckup,
BizPilotCheckupActualItem,
BizPilotCheckupReserveItem,
)
# ────────────────────────────────────────────
# Helpers: _row_to_dict
# ────────────────────────────────────────────
def _generate_checkup_no(db: Session, tenant_no: str) -> str:
today_str = datetime.now().strftime("%Y%m%d")
prefix = f"ZSTJ{today_str}"
existing = (
db.query(BizPilotCheckup.checkup_status)
.filter(
BizPilotCheckup.tenant_no == tenant_no,
BizPilotCheckup.id.like(f"{prefix}%"),
BizPilotCheckup.del_flag == 0,
)
.order_by(BizPilotCheckup.create_time.desc())
.first()
)
seq = 1
if existing:
seq = 1
return f"{prefix}{seq:04d}"
def _row_to_dict_checkup(row, db=None, tenant_no=None) -> Dict[str, Any]:
d: Dict[str, Any] = {
"id": row.id,
"pilotApplicationId": row.pilot_application_id or "",
"checkupInstitutionId": row.checkup_institution_id or "",
"reserveTime": row.reserve_time.strftime("%Y-%m-%d %H:%M:%S") if row.reserve_time else "",
"reserveFee": float(row.reserve_fee) if row.reserve_fee is not None else None,
"actualCheckupTime": row.actual_checkup_time.strftime("%Y-%m-%d %H:%M:%S") if row.actual_checkup_time else "",
"actualCheckupFee": float(row.actual_checkup_fee) if row.actual_checkup_fee is not None else None,
"feeSettled": row.fee_settled if row.fee_settled is not None else 0,
"checkupStatus": row.checkup_status or "",
"feeStatus": row.fee_status or "",
"checkupRemark": row.checkup_remark or "",
"reportAttachments": row.report_attachments or "",
"tenantNo": row.tenant_no or "",
"remark": row.remark or "",
"createBy": row.create_by or "",
"createTime": row.create_time.strftime("%Y-%m-%d %H:%M:%S") if row.create_time else "",
"updateTime": row.update_time.strftime("%Y-%m-%d %H:%M:%S") if row.update_time else "",
}
if db and tenant_no:
# institutionName — lookup from BizCheckupInstitution
if row.checkup_institution_id:
inst = (
db.query(BizCheckupInstitution.institution_name)
.filter(
BizCheckupInstitution.id == row.checkup_institution_id,
BizCheckupInstitution.del_flag == 0,
)
.first()
)
d["institutionName"] = inst.institution_name if inst else ""
else:
d["institutionName"] = ""
# reserveItemCount
reserve_count = (
db.query(func.count(BizPilotCheckupReserveItem.id))
.filter(
BizPilotCheckupReserveItem.pilot_checkup_id == row.id,
BizPilotCheckupReserveItem.tenant_no == tenant_no,
BizPilotCheckupReserveItem.del_flag == 0,
)
.scalar()
) or 0
d["reserveItemCount"] = reserve_count
# actualItemCount
actual_count = (
db.query(func.count(BizPilotCheckupActualItem.id))
.filter(
BizPilotCheckupActualItem.pilot_checkup_id == row.id,
BizPilotCheckupActualItem.tenant_no == tenant_no,
BizPilotCheckupActualItem.del_flag == 0,
)
.scalar()
) or 0
d["actualItemCount"] = actual_count
return d
def _row_to_dict_reserve_item(row) -> Dict[str, Any]:
return {
"id": row.id,
"pilotCheckupId": row.pilot_checkup_id or "",
"projectName": row.project_name or "",
"projectFee": float(row.project_fee) if row.project_fee is not None else None,
"orderNum": row.order_num if row.order_num is not None else 0,
"remark": row.remark or "",
"createTime": row.create_time.strftime("%Y-%m-%d %H:%M:%S") if row.create_time else "",
"updateTime": row.update_time.strftime("%Y-%m-%d %H:%M:%S") if row.update_time else "",
}
def _row_to_dict_actual_item(row) -> Dict[str, Any]:
return {
"id": row.id,
"pilotCheckupId": row.pilot_checkup_id or "",
"projectName": row.project_name or "",
"projectFee": float(row.project_fee) if row.project_fee is not None else None,
"orderNum": row.order_num if row.order_num is not None else 0,
"remark": row.remark or "",
"createTime": row.create_time.strftime("%Y-%m-%d %H:%M:%S") if row.create_time else "",
"updateTime": row.update_time.strftime("%Y-%m-%d %H:%M:%S") if row.update_time else "",
}
# ────────────────────────────────────────────
# Checkup CRUD
# ────────────────────────────────────────────
def get_checkup_by_application(
db: Session, application_id: str, tenant_no: str
) -> Optional[Dict[str, Any]]:
row = (
db.query(BizPilotCheckup)
.filter(
BizPilotCheckup.pilot_application_id == application_id,
BizPilotCheckup.tenant_no == tenant_no,
BizPilotCheckup.del_flag == 0,
)
.first()
)
if not row:
return None
return _row_to_dict_checkup(row, db, tenant_no)
def create_checkup(
db: Session,
application_id: str,
data: dict,
tenant_no: str,
user_id: str,
) -> Dict[str, Any]:
now = datetime.now()
row = BizPilotCheckup(
id=uuid.uuid4().hex,
pilot_application_id=application_id,
checkup_institution_id=data.get("checkupInstitutionId") or "",
reserve_time=data.get("reserveTime") or None,
reserve_fee=data.get("reserveFee") if data.get("reserveFee") is not None else None,
actual_checkup_time=data.get("actualCheckupTime") or None,
actual_checkup_fee=data.get("actualCheckupFee") if data.get("actualCheckupFee") is not None else None,
fee_settled=0,
checkup_status="dtj",
fee_status="wjs",
checkup_remark=data.get("checkupRemark") or "",
report_attachments=data.get("reportAttachments") or "",
tenant_no=tenant_no,
order_num=0,
remark=data.get("remark") or "",
create_by=user_id,
create_dept_id="",
create_time=now,
update_by=user_id,
update_time=now,
del_flag=0,
)
db.add(row)
db.commit()
db.refresh(row)
return _row_to_dict_checkup(row, db, tenant_no)
def update_checkup(
db: Session, checkup_id: str, data: dict, tenant_no: str
) -> Dict[str, Any]:
row = (
db.query(BizPilotCheckup)
.filter(
BizPilotCheckup.id == checkup_id,
BizPilotCheckup.tenant_no == tenant_no,
BizPilotCheckup.del_flag == 0,
)
.first()
)
if not row:
raise ValueError("体检信息不存在")
fields = {
"checkupInstitutionId": "checkup_institution_id",
"reserveTime": "reserve_time",
"reserveFee": "reserve_fee",
"actualCheckupTime": "actual_checkup_time",
"actualCheckupFee": "actual_checkup_fee",
"checkupRemark": "checkup_remark",
"reportAttachments": "report_attachments",
"remark": "remark",
}
for camel, snake in fields.items():
if camel in data and data[camel] is not None:
setattr(row, snake, data[camel])
row.update_time = datetime.now()
db.commit()
db.refresh(row)
return _row_to_dict_checkup(row, db, tenant_no)
def soft_delete_checkup(db: Session, checkup_id: str, tenant_no: str) -> None:
now = datetime.now()
row = (
db.query(BizPilotCheckup)
.filter(
BizPilotCheckup.id == checkup_id,
BizPilotCheckup.tenant_no == tenant_no,
BizPilotCheckup.del_flag == 0,
)
.first()
)
if not row:
raise ValueError("体检信息不存在")
row.del_flag = 1
row.update_time = now
# Cascade soft-delete to reserve items
db.query(BizPilotCheckupReserveItem).filter(
BizPilotCheckupReserveItem.pilot_checkup_id == checkup_id,
BizPilotCheckupReserveItem.tenant_no == tenant_no,
BizPilotCheckupReserveItem.del_flag == 0,
).update({"del_flag": 1, "update_time": now}, synchronize_session=False)
# Cascade soft-delete to actual items
db.query(BizPilotCheckupActualItem).filter(
BizPilotCheckupActualItem.pilot_checkup_id == checkup_id,
BizPilotCheckupActualItem.tenant_no == tenant_no,
BizPilotCheckupActualItem.del_flag == 0,
).update({"del_flag": 1, "update_time": now}, synchronize_session=False)
db.commit()
def mark_checkup_checked(
db: Session, checkup_id: str, tenant_no: str, user_id: str
) -> Dict[str, Any]:
row = (
db.query(BizPilotCheckup)
.filter(
BizPilotCheckup.id == checkup_id,
BizPilotCheckup.tenant_no == tenant_no,
BizPilotCheckup.del_flag == 0,
)
.first()
)
if not row:
raise ValueError("体检信息不存在")
if row.checkup_status != "dtj":
raise ValueError("当前状态不允许标记已体检")
row.checkup_status = "ytj"
if not row.actual_checkup_time:
row.actual_checkup_time = datetime.now()
row.update_by = user_id
row.update_time = datetime.now()
db.commit()
db.refresh(row)
return _row_to_dict_checkup(row, db, tenant_no)
def settle_checkup_fee(
db: Session, checkup_id: str, tenant_no: str, user_id: str
) -> Dict[str, Any]:
row = (
db.query(BizPilotCheckup)
.filter(
BizPilotCheckup.id == checkup_id,
BizPilotCheckup.tenant_no == tenant_no,
BizPilotCheckup.del_flag == 0,
)
.first()
)
if not row:
raise ValueError("体检信息不存在")
if row.fee_status != "wjs":
raise ValueError("当前状态不允许结算")
row.fee_status = "yjs"
row.fee_settled = 1
row.update_by = user_id
row.update_time = datetime.now()
db.commit()
db.refresh(row)
return _row_to_dict_checkup(row, db, tenant_no)
# ────────────────────────────────────────────
# Reserve Items CRUD
# ────────────────────────────────────────────
def list_reserve_items(
db: Session, checkup_id: str, tenant_no: str
) -> List[Dict[str, Any]]:
rows = (
db.query(BizPilotCheckupReserveItem)
.filter(
BizPilotCheckupReserveItem.pilot_checkup_id == checkup_id,
BizPilotCheckupReserveItem.tenant_no == tenant_no,
BizPilotCheckupReserveItem.del_flag == 0,
)
.order_by(
BizPilotCheckupReserveItem.order_num.asc(),
BizPilotCheckupReserveItem.create_time.asc(),
)
.all()
)
return [_row_to_dict_reserve_item(r) for r in rows]
def save_reserve_items(
db: Session,
checkup_id: str,
items_json: list,
tenant_no: str,
user_id: str,
) -> List[Dict[str, Any]]:
now = datetime.now()
# Soft-delete existing items
db.query(BizPilotCheckupReserveItem).filter(
BizPilotCheckupReserveItem.pilot_checkup_id == checkup_id,
BizPilotCheckupReserveItem.tenant_no == tenant_no,
BizPilotCheckupReserveItem.del_flag == 0,
).update({"del_flag": 1, "update_time": now}, synchronize_session=False)
# Insert new items
for idx, item in enumerate(items_json):
row = BizPilotCheckupReserveItem(
id=uuid.uuid4().hex,
pilot_checkup_id=checkup_id,
project_name=item.get("projectName") or item.get("project_name") or "",
project_fee=item.get("projectFee") if item.get("projectFee") is not None else (
item.get("project_fee") if item.get("project_fee") is not None else None
),
tenant_no=tenant_no,
order_num=idx + 1,
remark=item.get("remark") or "",
create_by=user_id,
create_dept_id="",
create_time=now,
update_by=user_id,
update_time=now,
del_flag=0,
)
db.add(row)
db.commit()
return list_reserve_items(db, checkup_id, tenant_no)
def delete_reserve_item(db: Session, item_id: str, tenant_no: str) -> None:
row = (
db.query(BizPilotCheckupReserveItem)
.filter(
BizPilotCheckupReserveItem.id == item_id,
BizPilotCheckupReserveItem.tenant_no == tenant_no,
BizPilotCheckupReserveItem.del_flag == 0,
)
.first()
)
if not row:
raise ValueError("预约项目不存在")
row.del_flag = 1
row.update_time = datetime.now()
db.commit()
# ────────────────────────────────────────────
# Actual Items CRUD
# ────────────────────────────────────────────
def list_actual_items(
db: Session, checkup_id: str, tenant_no: str
) -> List[Dict[str, Any]]:
rows = (
db.query(BizPilotCheckupActualItem)
.filter(
BizPilotCheckupActualItem.pilot_checkup_id == checkup_id,
BizPilotCheckupActualItem.tenant_no == tenant_no,
BizPilotCheckupActualItem.del_flag == 0,
)
.order_by(
BizPilotCheckupActualItem.order_num.asc(),
BizPilotCheckupActualItem.create_time.asc(),
)
.all()
)
return [_row_to_dict_actual_item(r) for r in rows]
def save_actual_items(
db: Session,
checkup_id: str,
items_json: list,
tenant_no: str,
user_id: str,
) -> List[Dict[str, Any]]:
now = datetime.now()
# Soft-delete existing items
db.query(BizPilotCheckupActualItem).filter(
BizPilotCheckupActualItem.pilot_checkup_id == checkup_id,
BizPilotCheckupActualItem.tenant_no == tenant_no,
BizPilotCheckupActualItem.del_flag == 0,
).update({"del_flag": 1, "update_time": now}, synchronize_session=False)
# Insert new items
for idx, item in enumerate(items_json):
row = BizPilotCheckupActualItem(
id=uuid.uuid4().hex,
pilot_checkup_id=checkup_id,
project_name=item.get("projectName") or item.get("project_name") or "",
project_fee=item.get("projectFee") if item.get("projectFee") is not None else (
item.get("project_fee") if item.get("project_fee") is not None else None
),
tenant_no=tenant_no,
order_num=idx + 1,
remark=item.get("remark") or "",
create_by=user_id,
create_dept_id="",
create_time=now,
update_by=user_id,
update_time=now,
del_flag=0,
)
db.add(row)
db.commit()
return list_actual_items(db, checkup_id, tenant_no)
def delete_actual_item(db: Session, item_id: str, tenant_no: str) -> None:
row = (
db.query(BizPilotCheckupActualItem)
.filter(
BizPilotCheckupActualItem.id == item_id,
BizPilotCheckupActualItem.tenant_no == tenant_no,
BizPilotCheckupActualItem.del_flag == 0,
)
.first()
)
if not row:
raise ValueError("实际项目不存在")
row.del_flag = 1
row.update_time = datetime.now()
db.commit()