提交“
This commit is contained in:
1 parent
69ee0f505c
commit
9b88581450
614 files changed
+90318
-689022
No files matched your search
@@ -1,56 +1,14 @@
|
||||
"""API 路由包(骨架:公共鉴权 + 静态菜单 + 运营端占位)"""
|
||||
"""API 路由包 — 山峡化工生产一体化门户"""
|
||||
from app.api.public import router as public_router
|
||||
from app.api.menu import router as menu_router
|
||||
from app.api.admin import router as admin_router
|
||||
from app.api.workflow import router as workflow_router
|
||||
from app.api.basic_info import router as basic_info_router
|
||||
from app.api.collection_protocol import router as collection_protocol_router
|
||||
from app.api.leave import router as leave_router
|
||||
from app.api.operations import router as operations_router
|
||||
from app.api.ethnic import router as ethnic_router
|
||||
from app.api.sample_reception import router as sample_reception_router
|
||||
from app.api.qc import router as qc_router
|
||||
from app.api.research_donation import router as research_donation_router
|
||||
from app.api.production import router as production_router
|
||||
from app.api.pilot_service import router as pilot_service_router
|
||||
from app.api.insurance_company import router as insurance_company_router
|
||||
from app.api.material import router as material_router
|
||||
from app.api.storage_release_review import router as storage_release_review_router
|
||||
from app.api.sample_sms_notification import router as sample_sms_notification_router
|
||||
from app.api.storage_entry_sms_notification import router as storage_entry_sms_notification_router
|
||||
from app.api.pilot_application import router as pilot_application_router
|
||||
from app.api.pilot_checkup import router as pilot_checkup_router
|
||||
from app.api.pilot_delivery import router as pilot_delivery_router
|
||||
from app.api.pilot_infusion_confirm import router as pilot_infusion_confirm_router
|
||||
from app.api.pilot_infusion_schedule_mgmt import router as pilot_infusion_schedule_mgmt_router
|
||||
from app.api.outbound_release_review import router as outbound_release_review_router
|
||||
from app.api.clinical_payment import router as clinical_payment_router
|
||||
|
||||
__all__ = [
|
||||
"public_router",
|
||||
"menu_router",
|
||||
"admin_router",
|
||||
"workflow_router",
|
||||
"basic_info_router",
|
||||
"collection_protocol_router",
|
||||
"leave_router",
|
||||
"operations_router",
|
||||
"ethnic_router",
|
||||
"sample_reception_router",
|
||||
"qc_router",
|
||||
"research_donation_router",
|
||||
"production_router",
|
||||
"pilot_service_router",
|
||||
"insurance_company_router",
|
||||
"material_router",
|
||||
"storage_release_review_router",
|
||||
"sample_sms_notification_router",
|
||||
"storage_entry_sms_notification_router",
|
||||
"pilot_application_router",
|
||||
"pilot_checkup_router",
|
||||
"pilot_delivery_router",
|
||||
"pilot_infusion_confirm_router",
|
||||
"pilot_infusion_schedule_mgmt_router",
|
||||
"outbound_release_review_router",
|
||||
"clinical_payment_router",
|
||||
]
|
||||
+35
-198
@@ -5,7 +5,7 @@ from typing import Any, List, Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, Query, UploadFile, File, Form
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
from sqlalchemy import or_
|
||||
from sqlalchemy import and_, or_
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.core.config import settings
|
||||
@@ -20,13 +20,12 @@ from app.crud import dict_data as dict_data_svc
|
||||
from app.crud import dept as dept_svc
|
||||
from app.crud import site as site_svc
|
||||
from app.crud import post as post_svc
|
||||
from app.crud import item_unit as item_unit_svc
|
||||
from app.crud import express_company as express_company_svc
|
||||
from app.crud import menu as menu_svc
|
||||
from app.crud import role as role_svc
|
||||
from app.crud import user as user_svc
|
||||
from app.crud.collection_protocol import _lookup_attachment_by_url
|
||||
from app.models.models import BizAttachment, SysDept, SysRole, SysUser
|
||||
from app.crud import role as role_svc
|
||||
from app.crud import user as user_svc
|
||||
from app.models.models import BizAttachment, SysDept, SysDictData, SysRole, SysUser
|
||||
from app.services.web_auth_roles import _map_role_name_to_web
|
||||
|
||||
router = APIRouter(prefix="/web/admin", tags=["运营端管理"])
|
||||
@@ -216,9 +215,9 @@ async def delete_tenant(
|
||||
def _get_tenant_no(db: Session, user: dict) -> str:
|
||||
user_id = user.get("user_id")
|
||||
if not user_id:
|
||||
return "zkxw"
|
||||
return "shanxia2.0"
|
||||
sys_user = db.query(SysUser).filter(SysUser.id == user_id).first()
|
||||
return (sys_user.tenant_no if sys_user else None) or "zkxw"
|
||||
return (sys_user.tenant_no if sys_user else None) or "shanxia2.0"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -517,6 +516,7 @@ class DictDataCreateBody(BaseModel):
|
||||
dict_label: str = Field(..., alias="dictLabel")
|
||||
dict_value: str = Field(..., alias="dictValue")
|
||||
dict_type: str = Field(..., alias="dictType")
|
||||
tag_type: Optional[str] = Field("", alias="tagType")
|
||||
order_num: Optional[int] = Field(0, alias="orderNum")
|
||||
remark: Optional[str] = None
|
||||
|
||||
@@ -526,6 +526,7 @@ class DictDataUpdateBody(BaseModel):
|
||||
|
||||
dict_label: Optional[str] = Field(None, alias="dictLabel")
|
||||
dict_value: Optional[str] = Field(None, alias="dictValue")
|
||||
tag_type: Optional[str] = Field(None, alias="tagType")
|
||||
order_num: Optional[int] = Field(None, alias="orderNum")
|
||||
remark: Optional[str] = None
|
||||
|
||||
@@ -560,6 +561,7 @@ async def create_dict_data(
|
||||
dict_label=body.dict_label,
|
||||
dict_value=body.dict_value,
|
||||
dict_type=body.dict_type,
|
||||
tag_type=body.tag_type,
|
||||
tenant_no=tenant_no,
|
||||
order_num=body.order_num,
|
||||
remark=body.remark,
|
||||
@@ -584,6 +586,7 @@ async def update_dict_data(
|
||||
data_id,
|
||||
dict_label=payload.get("dict_label"),
|
||||
dict_value=payload.get("dict_value"),
|
||||
tag_type=payload.get("tag_type"),
|
||||
order_num=payload.get("order_num"),
|
||||
remark=payload.get("remark"),
|
||||
user_id=user.get("user_id"),
|
||||
@@ -617,6 +620,28 @@ async def dict_data_options(
|
||||
return success_response(items)
|
||||
|
||||
|
||||
@router.get("/dict-data/all")
|
||||
async def dict_data_all(
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
rows = db.query(SysDictData).filter(
|
||||
and_(SysDictData.tenant_no == tenant_no, SysDictData.del_flag == 0)
|
||||
).order_by(SysDictData.order_num.asc()).all()
|
||||
grouped = {}
|
||||
for r in rows:
|
||||
key = r.dict_type
|
||||
if key not in grouped:
|
||||
grouped[key] = []
|
||||
grouped[key].append({
|
||||
"label": r.dict_label,
|
||||
"value": r.dict_value,
|
||||
"tagType": r.tag_type or ""
|
||||
})
|
||||
return success_response(grouped)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 组织管理
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -981,196 +1006,6 @@ async def update_post_bound_users(
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 物品单位管理
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class ItemUnitCreateBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
unit_code: str = Field(..., alias="unitCode")
|
||||
unit_name: str = Field(..., alias="unitName")
|
||||
order_num: Optional[int] = Field(0, alias="orderNum")
|
||||
remark: Optional[str] = None
|
||||
|
||||
|
||||
class ItemUnitUpdateBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
unit_code: Optional[str] = Field(None, alias="unitCode")
|
||||
unit_name: Optional[str] = Field(None, alias="unitName")
|
||||
order_num: Optional[int] = Field(None, alias="orderNum")
|
||||
remark: Optional[str] = None
|
||||
|
||||
|
||||
@router.get("/item-units")
|
||||
async def list_item_units(
|
||||
page: int = Query(1, ge=1),
|
||||
pageSize: int = Query(10, ge=1, le=100, alias="pageSize"),
|
||||
keyword: Optional[str] = None,
|
||||
user: dict = Depends(require_menu_code("system:unit:list")),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
items, total = item_unit_svc.list_item_units(db, page=page, page_size=pageSize, keyword=keyword, tenant_no=tenant_no, user_info=user)
|
||||
tp = item_unit_svc.total_pages(total, pageSize)
|
||||
return success_response({"list": items, "total": total, "page": page, "pageSize": pageSize, "totalPages": tp})
|
||||
|
||||
|
||||
@router.post("/item-units")
|
||||
async def create_item_unit(
|
||||
body: ItemUnitCreateBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
obj = item_unit_svc.create_item_unit(
|
||||
db,
|
||||
unit_code=body.unit_code,
|
||||
unit_name=body.unit_name,
|
||||
tenant_no=tenant_no,
|
||||
order_num=body.order_num,
|
||||
remark=body.remark,
|
||||
user_id=user.get("user_id"),
|
||||
)
|
||||
return success_response(item_unit_svc._row_to_dict(obj), message="创建成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.put("/item-units/{unit_id}")
|
||||
async def update_item_unit(
|
||||
unit_id: str,
|
||||
body: ItemUnitUpdateBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
payload: dict[str, Any] = body.model_dump(exclude_unset=True, by_alias=False)
|
||||
obj = item_unit_svc.update_item_unit(
|
||||
db,
|
||||
unit_id,
|
||||
unit_code=payload.get("unit_code"),
|
||||
unit_name=payload.get("unit_name"),
|
||||
order_num=payload.get("order_num"),
|
||||
remark=payload.get("remark"),
|
||||
user_id=user.get("user_id"),
|
||||
)
|
||||
return success_response(item_unit_svc._row_to_dict(obj), message="更新成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.delete("/item-units/{unit_id}")
|
||||
async def delete_item_unit(
|
||||
unit_id: str,
|
||||
_user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
item_unit_svc.soft_delete_item_unit(db, unit_id)
|
||||
return success_response(None, message="删除成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 快递公司管理
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class ExpressCompanyCreateBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
express_code: str = Field(..., alias="expressCode")
|
||||
express_name: str = Field(..., alias="expressName")
|
||||
order_num: Optional[int] = Field(0, alias="orderNum")
|
||||
remark: Optional[str] = None
|
||||
|
||||
|
||||
class ExpressCompanyUpdateBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
express_code: Optional[str] = Field(None, alias="expressCode")
|
||||
express_name: Optional[str] = Field(None, alias="expressName")
|
||||
order_num: Optional[int] = Field(None, alias="orderNum")
|
||||
remark: Optional[str] = None
|
||||
|
||||
|
||||
@router.get("/express-companies")
|
||||
async def list_express_companies(
|
||||
page: int = Query(1, ge=1),
|
||||
pageSize: int = Query(10, ge=1, le=100, alias="pageSize"),
|
||||
keyword: Optional[str] = None,
|
||||
user: dict = Depends(require_menu_code("system:express:list")),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
items, total = express_company_svc.list_express_companies(db, page=page, page_size=pageSize, keyword=keyword, tenant_no=tenant_no, user_info=user)
|
||||
tp = express_company_svc.total_pages(total, pageSize)
|
||||
return success_response({"list": items, "total": total, "page": page, "pageSize": pageSize, "totalPages": tp})
|
||||
|
||||
|
||||
@router.post("/express-companies")
|
||||
async def create_express_company(
|
||||
body: ExpressCompanyCreateBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
obj = express_company_svc.create_express_company(
|
||||
db,
|
||||
express_code=body.express_code,
|
||||
express_name=body.express_name,
|
||||
tenant_no=tenant_no,
|
||||
order_num=body.order_num,
|
||||
remark=body.remark,
|
||||
user_id=user.get("user_id"),
|
||||
)
|
||||
return success_response(express_company_svc._row_to_dict(obj), message="创建成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.put("/express-companies/{company_id}")
|
||||
async def update_express_company(
|
||||
company_id: str,
|
||||
body: ExpressCompanyUpdateBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
payload: dict[str, Any] = body.model_dump(exclude_unset=True, by_alias=False)
|
||||
obj = express_company_svc.update_express_company(
|
||||
db,
|
||||
company_id,
|
||||
express_code=payload.get("express_code"),
|
||||
express_name=payload.get("express_name"),
|
||||
order_num=payload.get("order_num"),
|
||||
remark=payload.get("remark"),
|
||||
user_id=user.get("user_id"),
|
||||
)
|
||||
return success_response(express_company_svc._row_to_dict(obj), message="更新成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.delete("/express-companies/{company_id}")
|
||||
async def delete_express_company(
|
||||
company_id: str,
|
||||
_user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
express_company_svc.soft_delete_express_company(db, company_id)
|
||||
return success_response(None, message="删除成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 菜单管理
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -1539,7 +1374,9 @@ async def attachment_download_url(
|
||||
if not file_url:
|
||||
return error_response(400, "文件地址不能为空")
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
att = _lookup_attachment_by_url(db, file_url, tenant_no)
|
||||
att = db.query(BizAttachment).filter(
|
||||
and_(BizAttachment.file_url == file_url, BizAttachment.tenant_no == tenant_no, BizAttachment.del_flag == 0)
|
||||
).first()
|
||||
download_name = (body.file_name or "").strip()
|
||||
if not download_name and att:
|
||||
download_name = (att.original_name or "").strip()
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,356 +0,0 @@
|
||||
from typing import List, Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
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.crud import clinical_payment
|
||||
from app.models.models import SysUser
|
||||
|
||||
router = APIRouter(prefix="/web/admin", tags=["临床应用缴费管理"])
|
||||
|
||||
|
||||
def _get_tenant_no(db: Session, user: dict) -> str:
|
||||
user_id = user.get("user_id")
|
||||
if not user_id:
|
||||
raise PermissionError("用户身份信息缺失,无法确定租户")
|
||||
sys_user = db.query(SysUser).filter(SysUser.id == user_id).first()
|
||||
if not sys_user or not sys_user.tenant_no:
|
||||
raise PermissionError("用户租户信息缺失")
|
||||
return sys_user.tenant_no
|
||||
|
||||
|
||||
class PaymentIdBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
id: str
|
||||
|
||||
|
||||
class BatchPaymentIdsBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
payment_ids: List[str] = Field(..., alias="paymentIds")
|
||||
|
||||
|
||||
class SubmitReceiptBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
transfer_amount: Optional[float] = Field(None, alias="transferAmount")
|
||||
remark: Optional[str] = None
|
||||
transfer_attachments: Optional[str] = Field(None, alias="transferAttachments")
|
||||
|
||||
|
||||
class BatchSubmitReceiptBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
payment_ids: List[str] = Field(..., alias="paymentIds")
|
||||
remark: Optional[str] = None
|
||||
transfer_attachments: Optional[str] = Field(None, alias="transferAttachments")
|
||||
|
||||
|
||||
class ConfirmReceiptBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
finance_confirm_attachments: Optional[str] = Field(None, alias="financeConfirmAttachments")
|
||||
finance_remark: Optional[str] = Field(None, alias="financeRemark")
|
||||
|
||||
|
||||
class SubmitRefundBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
refund_amount: float = Field(..., alias="refundAmount")
|
||||
refund_remark: Optional[str] = Field(None, alias="refundRemark")
|
||||
refund_attachments: Optional[str] = Field(None, alias="refundAttachments")
|
||||
|
||||
|
||||
class BatchSubmitRefundBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
payment_ids: List[str] = Field(..., alias="paymentIds")
|
||||
refund_amount: float = Field(..., alias="refundAmount")
|
||||
refund_remark: Optional[str] = Field(None, alias="refundRemark")
|
||||
refund_attachments: Optional[str] = Field(None, alias="refundAttachments")
|
||||
|
||||
|
||||
class ConfirmRefundBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
refund_finance_confirm_attachments: Optional[str] = Field(
|
||||
None, alias="refundFinanceConfirmAttachments"
|
||||
)
|
||||
refund_finance_remark: Optional[str] = Field(None, alias="refundFinanceRemark")
|
||||
|
||||
|
||||
@router.get("/clinical-payments")
|
||||
async def api_list_payments(
|
||||
page: int = Query(1, ge=1),
|
||||
pageSize: int = Query(10, ge=1, le=100, alias="pageSize"),
|
||||
payStatus: Optional[str] = Query(None, alias="payStatus"),
|
||||
keyword: Optional[str] = Query(None, alias="keyword"),
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
try:
|
||||
rows, total = clinical_payment.list_payments(
|
||||
db,
|
||||
page=page,
|
||||
page_size=pageSize,
|
||||
pay_status=payStatus,
|
||||
keyword=keyword,
|
||||
tenant_no=tenant_no,
|
||||
user_info=user,
|
||||
)
|
||||
return success_response({"list": rows, "total": total})
|
||||
except Exception as e:
|
||||
return error_response(500, str(e))
|
||||
|
||||
|
||||
@router.get("/clinical-payments/receipt-pending")
|
||||
async def api_receipt_pending(
|
||||
page: int = Query(1, ge=1),
|
||||
pageSize: int = Query(10, ge=1, le=100, alias="pageSize"),
|
||||
keyword: Optional[str] = Query(None, alias="keyword"),
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
try:
|
||||
rows, total = clinical_payment.list_payments(
|
||||
db,
|
||||
page=page,
|
||||
page_size=pageSize,
|
||||
pay_status="jfqrz",
|
||||
keyword=keyword,
|
||||
tenant_no=tenant_no,
|
||||
user_info=user,
|
||||
)
|
||||
return success_response({"list": rows, "total": total})
|
||||
except Exception as e:
|
||||
return error_response(500, str(e))
|
||||
|
||||
|
||||
@router.get("/clinical-payments/receipt-confirmed")
|
||||
async def api_receipt_confirmed(
|
||||
page: int = Query(1, ge=1),
|
||||
pageSize: int = Query(10, ge=1, le=100, alias="pageSize"),
|
||||
keyword: Optional[str] = Query(None, alias="keyword"),
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
try:
|
||||
rows, total = clinical_payment.list_payments(
|
||||
db,
|
||||
page=page,
|
||||
page_size=pageSize,
|
||||
pay_status="yjf",
|
||||
keyword=keyword,
|
||||
tenant_no=tenant_no,
|
||||
user_info=user,
|
||||
)
|
||||
return success_response({"list": rows, "total": total})
|
||||
except Exception as e:
|
||||
return error_response(500, str(e))
|
||||
|
||||
|
||||
@router.get("/clinical-payments/refund-pending")
|
||||
async def api_refund_pending(
|
||||
page: int = Query(1, ge=1),
|
||||
pageSize: int = Query(10, ge=1, le=100, alias="pageSize"),
|
||||
keyword: Optional[str] = Query(None, alias="keyword"),
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
try:
|
||||
rows, total = clinical_payment.list_payments(
|
||||
db,
|
||||
page=page,
|
||||
page_size=pageSize,
|
||||
pay_status="tfqrz",
|
||||
keyword=keyword,
|
||||
tenant_no=tenant_no,
|
||||
user_info=user,
|
||||
)
|
||||
return success_response({"list": rows, "total": total})
|
||||
except Exception as e:
|
||||
return error_response(500, str(e))
|
||||
|
||||
|
||||
@router.get("/clinical-payments/refund-confirmed")
|
||||
async def api_refund_confirmed(
|
||||
page: int = Query(1, ge=1),
|
||||
pageSize: int = Query(10, ge=1, le=100, alias="pageSize"),
|
||||
keyword: Optional[str] = Query(None, alias="keyword"),
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
try:
|
||||
rows, total = clinical_payment.list_payments(
|
||||
db,
|
||||
page=page,
|
||||
page_size=pageSize,
|
||||
pay_status="ytf",
|
||||
keyword=keyword,
|
||||
tenant_no=tenant_no,
|
||||
user_info=user,
|
||||
)
|
||||
return success_response({"list": rows, "total": total})
|
||||
except Exception as e:
|
||||
return error_response(500, str(e))
|
||||
|
||||
|
||||
@router.get("/clinical-payments/{payment_id}")
|
||||
async def api_get_payment_detail(
|
||||
payment_id: str,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
try:
|
||||
result = clinical_payment.get_payment_detail(
|
||||
db, payment_id=payment_id, tenant_no=tenant_no
|
||||
)
|
||||
if result is None:
|
||||
return error_response(404, "缴费记录不存在")
|
||||
return success_response(result)
|
||||
except ValueError as e:
|
||||
return error_response(404, str(e))
|
||||
|
||||
|
||||
@router.post("/clinical-payments/{payment_id}/submit-receipt")
|
||||
async def api_submit_receipt(
|
||||
payment_id: str,
|
||||
body: SubmitReceiptBody = SubmitReceiptBody(),
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
try:
|
||||
clinical_payment.submit_receipt(
|
||||
db,
|
||||
payment_id=payment_id,
|
||||
tenant_no=tenant_no,
|
||||
user_id=user.get("user_id"),
|
||||
remark=body.remark,
|
||||
transfer_attachments=body.transfer_attachments,
|
||||
transfer_amount=body.transfer_amount,
|
||||
)
|
||||
return success_response(None, message="提交缴费确认成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.post("/clinical-payments/submit-receipt-batch")
|
||||
async def api_batch_submit_receipt(
|
||||
body: BatchSubmitReceiptBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
try:
|
||||
count = clinical_payment.batch_submit_receipt(
|
||||
db,
|
||||
payment_ids=body.payment_ids,
|
||||
tenant_no=tenant_no,
|
||||
user_id=user.get("user_id"),
|
||||
remark=body.remark,
|
||||
transfer_attachments=body.transfer_attachments,
|
||||
)
|
||||
return success_response({"count": count}, message=f"批量提交成功,共{count}条")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.post("/clinical-payments/{payment_id}/confirm-receipt")
|
||||
async def api_confirm_receipt(
|
||||
payment_id: str,
|
||||
body: ConfirmReceiptBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
try:
|
||||
clinical_payment.confirm_receipt(
|
||||
db,
|
||||
payment_id=payment_id,
|
||||
tenant_no=tenant_no,
|
||||
user_id=user.get("user_id"),
|
||||
finance_confirm_attachments=body.finance_confirm_attachments,
|
||||
finance_remark=body.finance_remark,
|
||||
)
|
||||
return success_response(None, message="确认收款成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.post("/clinical-payments/{payment_id}/submit-refund")
|
||||
async def api_submit_refund(
|
||||
payment_id: str,
|
||||
body: SubmitRefundBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
try:
|
||||
clinical_payment.submit_refund(
|
||||
db,
|
||||
payment_id=payment_id,
|
||||
tenant_no=tenant_no,
|
||||
user_id=user.get("user_id"),
|
||||
refund_amount=body.refund_amount,
|
||||
refund_remark=body.refund_remark,
|
||||
refund_attachments=body.refund_attachments,
|
||||
)
|
||||
return success_response(None, message="提交退费申请成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.post("/clinical-payments/submit-refund-batch")
|
||||
async def api_batch_submit_refund(
|
||||
body: BatchSubmitRefundBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
try:
|
||||
count = clinical_payment.batch_submit_refund(
|
||||
db,
|
||||
payment_ids=body.payment_ids,
|
||||
tenant_no=tenant_no,
|
||||
user_id=user.get("user_id"),
|
||||
refund_amount=body.refund_amount,
|
||||
refund_remark=body.refund_remark,
|
||||
refund_attachments=body.refund_attachments,
|
||||
)
|
||||
return success_response({"count": count}, message=f"批量提交退费成功,共{count}条")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.post("/clinical-payments/{payment_id}/confirm-refund")
|
||||
async def api_confirm_refund(
|
||||
payment_id: str,
|
||||
body: ConfirmRefundBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
try:
|
||||
clinical_payment.confirm_refund(
|
||||
db,
|
||||
payment_id=payment_id,
|
||||
tenant_no=tenant_no,
|
||||
user_id=user.get("user_id"),
|
||||
refund_finance_confirm_attachments=body.refund_finance_confirm_attachments,
|
||||
refund_finance_remark=body.refund_finance_remark,
|
||||
)
|
||||
return success_response(None, message="确认退费成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
@@ -1,924 +0,0 @@
|
||||
"""细胞存储 — 采集协议单 / 审核 / 财务确认 / 分期预警 API"""
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from sqlalchemy import and_ as sa_and, func as sa_func, or_ as sa_or
|
||||
|
||||
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.utils import parse_datetime
|
||||
from app.crud import collection_protocol as cp_svc
|
||||
from app.crud import customer as customer_crud
|
||||
from app.models.models import (
|
||||
BizCollectionProtocol,
|
||||
BizCustomer,
|
||||
BizProtocolPartyCustomer,
|
||||
BizProtocolSample,
|
||||
BizProtocolStorageCert,
|
||||
SysUser,
|
||||
)
|
||||
|
||||
router = APIRouter(prefix="/web/admin", tags=["细胞存储"])
|
||||
|
||||
|
||||
def _get_tenant_no(db: Session, user: dict) -> str:
|
||||
user_id = user.get("user_id")
|
||||
if not user_id:
|
||||
raise PermissionError("用户身份信息缺失,无法确定租户")
|
||||
sys_user = db.query(SysUser).filter(SysUser.id == user_id).first()
|
||||
if not sys_user or not sys_user.tenant_no:
|
||||
raise PermissionError("用户租户信息缺失")
|
||||
return sys_user.tenant_no
|
||||
|
||||
|
||||
def _get_current_user_id(user: dict) -> str:
|
||||
user_id = user.get("user_id")
|
||||
if not user_id:
|
||||
raise PermissionError("用户身份信息缺失")
|
||||
return str(user_id)
|
||||
|
||||
|
||||
_CAMEL_TO_SNAKE_DATETIME = {
|
||||
"newbornDeliveryTime": "newborn_delivery_time",
|
||||
"sampleCollectTime": "sample_collect_time",
|
||||
"maternalBloodCollectTime": "maternal_blood_collect_time",
|
||||
}
|
||||
|
||||
|
||||
def _parse_datetime_fields(d: dict, camel_keys: list) -> None:
|
||||
for camel in camel_keys:
|
||||
val = d.get(camel)
|
||||
if val is not None and isinstance(val, str):
|
||||
snake = _CAMEL_TO_SNAKE_DATETIME.get(camel, camel)
|
||||
parsed = parse_datetime(val)
|
||||
if parsed:
|
||||
d.pop(camel, None)
|
||||
d[snake] = parsed
|
||||
else:
|
||||
d.pop(camel, None)
|
||||
d[snake] = None
|
||||
|
||||
|
||||
def _ensure_customer_for_mother(db: Session, party_customer: dict, tenant_no: str, user_id: str) -> dict:
|
||||
"""If mother info exists but no customerId, create a customer record and link it."""
|
||||
if not party_customer:
|
||||
return party_customer
|
||||
customer_id = party_customer.get("customer_id") or party_customer.get("customerId")
|
||||
mother_name = (party_customer.get("mother_name") or party_customer.get("motherName") or "").strip()
|
||||
if customer_id or not mother_name:
|
||||
return party_customer
|
||||
# Build customer fields from mother info
|
||||
mother_phone = (party_customer.get("mother_phone") or party_customer.get("motherPhone") or "").strip() or None
|
||||
mother_id_card = (party_customer.get("mother_id_card") or party_customer.get("motherIdCard") or "").strip() or None
|
||||
|
||||
# Check if customer with this id_card already exists
|
||||
if mother_id_card and customer_crud.id_card_taken(db, mother_id_card, tenant_no):
|
||||
existing = db.query(BizCustomer).filter(
|
||||
sa_and(
|
||||
BizCustomer.id_card_no == mother_id_card,
|
||||
BizCustomer.tenant_no == tenant_no,
|
||||
BizCustomer.del_flag == 0,
|
||||
)
|
||||
).first()
|
||||
if existing:
|
||||
party_customer["customer_id"] = existing.id
|
||||
return party_customer
|
||||
|
||||
# Create new customer
|
||||
try:
|
||||
obj = customer_crud.create_customer(
|
||||
db,
|
||||
customer_name=mother_name,
|
||||
sex="1", # female (mother)
|
||||
id_card_no=mother_id_card,
|
||||
phone_no=mother_phone,
|
||||
tenant_no=tenant_no,
|
||||
user_id=user_id,
|
||||
)
|
||||
party_customer["customer_id"] = obj.id
|
||||
except ValueError:
|
||||
# If creation fails (e.g. duplicate), try to find existing
|
||||
pass
|
||||
return party_customer
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 采集协议单
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@router.get("/collection-protocols")
|
||||
async def list_collection_protocols(
|
||||
page: int = Query(1, ge=1),
|
||||
pageSize: int = Query(10, ge=1, le=100, alias="pageSize"),
|
||||
keyword: Optional[str] = None,
|
||||
protocolStatus: Optional[str] = Query(None, alias="protocolStatus"),
|
||||
createTimeStart: Optional[str] = Query(None, alias="createTimeStart"),
|
||||
createTimeEnd: Optional[str] = Query(None, alias="createTimeEnd"),
|
||||
sampleCollectTimeStart: Optional[str] = Query(None, alias="sampleCollectTimeStart"),
|
||||
sampleCollectTimeEnd: Optional[str] = Query(None, alias="sampleCollectTimeEnd"),
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
current_user_id = _get_current_user_id(user)
|
||||
items, total = cp_svc.list_collection_protocols(
|
||||
db,
|
||||
page=page,
|
||||
page_size=pageSize,
|
||||
keyword=keyword,
|
||||
protocol_status=protocolStatus,
|
||||
create_time_start=createTimeStart,
|
||||
create_time_end=createTimeEnd,
|
||||
sample_collect_time_start=sampleCollectTimeStart,
|
||||
sample_collect_time_end=sampleCollectTimeEnd,
|
||||
tenant_no=tenant_no,
|
||||
scope_collector_user_id=current_user_id,
|
||||
user_info=user,
|
||||
)
|
||||
tp = cp_svc.total_pages(total, pageSize)
|
||||
return success_response({"list": items, "total": total, "page": page, "pageSize": pageSize, "totalPages": tp})
|
||||
|
||||
|
||||
@router.get("/collection-protocols/{protocol_id}")
|
||||
async def get_collection_protocol_detail(
|
||||
protocol_id: str,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
current_user_id = _get_current_user_id(user)
|
||||
bundle = cp_svc.get_protocol_detail_bundle(
|
||||
db, protocol_id, tenant_no, scope_collector_user_id=current_user_id
|
||||
)
|
||||
if not bundle:
|
||||
return error_response(404, "协议单不存在或无权查看")
|
||||
return success_response(bundle)
|
||||
|
||||
|
||||
class ProtocolCreateBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
protocol_no: Optional[str] = Field(None, alias="protocolNo")
|
||||
protocol_no_id: Optional[str] = Field(None, alias="protocolNoId")
|
||||
protocol_status: str = Field("dsx", alias="protocolStatus")
|
||||
protocol_attachments: Optional[str] = Field(None, alias="protocolAttachments")
|
||||
register_date: Optional[str] = Field(None, alias="registerDate")
|
||||
collector_user_id: Optional[str] = Field(None, alias="collectorUserId")
|
||||
remark: Optional[str] = None
|
||||
party_customer: Optional[dict] = Field(None, alias="partyCustomer")
|
||||
collection_info: Optional[dict] = Field(None, alias="collectionInfo")
|
||||
samples: Optional[list] = Field(None, alias="samples")
|
||||
payment: Optional[dict] = Field(None, alias="payment")
|
||||
payment_details: Optional[list] = Field(None, alias="paymentDetails")
|
||||
attachments: Optional[list] = Field(None, alias="attachments")
|
||||
storage_cert: Optional[dict] = Field(None, alias="storageCert")
|
||||
|
||||
|
||||
class ProtocolUpdateBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
protocol_no: Optional[str] = Field(None, alias="protocolNo")
|
||||
protocol_status: Optional[str] = Field(None, alias="protocolStatus")
|
||||
protocol_attachments: Optional[str] = Field(None, alias="protocolAttachments")
|
||||
register_date: Optional[str] = Field(None, alias="registerDate")
|
||||
effective_time: Optional[str] = Field(None, alias="effectiveTime")
|
||||
effective_desc: Optional[str] = Field(None, alias="effectiveDesc")
|
||||
expire_time: Optional[str] = Field(None, alias="expireTime")
|
||||
expire_desc: Optional[str] = Field(None, alias="expireDesc")
|
||||
void_time: Optional[str] = Field(None, alias="voidTime")
|
||||
void_desc: Optional[str] = Field(None, alias="voidDesc")
|
||||
to_research_time: Optional[str] = Field(None, alias="toResearchTime")
|
||||
to_research_desc: Optional[str] = Field(None, alias="toResearchDesc")
|
||||
collector_user_id: Optional[str] = Field(None, alias="collectorUserId")
|
||||
remark: Optional[str] = None
|
||||
party_customer: Optional[dict] = Field(None, alias="partyCustomer")
|
||||
collection_info: Optional[dict] = Field(None, alias="collectionInfo")
|
||||
samples: Optional[list] = Field(None, alias="samples")
|
||||
payment: Optional[dict] = Field(None, alias="payment")
|
||||
payment_details: Optional[list] = Field(None, alias="paymentDetails")
|
||||
attachments: Optional[list] = Field(None, alias="attachments")
|
||||
storage_cert: Optional[dict] = Field(None, alias="storageCert")
|
||||
|
||||
|
||||
def _resolve_protocol_attachments(
|
||||
protocol_attachments: Optional[str],
|
||||
attachments: Optional[list],
|
||||
) -> Optional[str]:
|
||||
from_urls = cp_svc.attachments_to_urls(attachments)
|
||||
if from_urls:
|
||||
return from_urls
|
||||
return protocol_attachments
|
||||
|
||||
|
||||
def _persist_protocol_sub_resources(
|
||||
db: Session,
|
||||
protocol_id: str,
|
||||
tenant_no: str,
|
||||
user_id: str,
|
||||
*,
|
||||
party_customer: Optional[dict],
|
||||
collection_info: Optional[dict],
|
||||
samples: Optional[list],
|
||||
payment: Optional[dict],
|
||||
payment_details: Optional[list],
|
||||
storage_cert: Optional[dict],
|
||||
) -> None:
|
||||
if party_customer:
|
||||
_parse_datetime_fields(party_customer, ["newbornDeliveryTime"])
|
||||
party_customer = _ensure_customer_for_mother(db, party_customer, tenant_no, user_id)
|
||||
cp_svc.upsert_party_customer(db, protocol_id, tenant_no, user_id, **party_customer)
|
||||
if collection_info:
|
||||
_parse_datetime_fields(collection_info, ["sampleCollectTime", "maternalBloodCollectTime"])
|
||||
cp_svc.upsert_collection_info(db, protocol_id, tenant_no, user_id, **collection_info)
|
||||
if samples is not None:
|
||||
cp_svc.save_samples(db, protocol_id, tenant_no, user_id, samples)
|
||||
pay = None
|
||||
if payment:
|
||||
pay = cp_svc.upsert_payment(db, protocol_id, tenant_no, user_id, **payment)
|
||||
if payment_details is not None:
|
||||
if not pay and payment:
|
||||
pay = cp_svc.upsert_payment(db, protocol_id, tenant_no, user_id, **payment)
|
||||
if pay:
|
||||
aligned_details = cp_svc.align_fq_payment_details_payload(pay, payment_details)
|
||||
cp_svc.save_payment_details(db, pay.id, tenant_no, user_id, aligned_details)
|
||||
if storage_cert:
|
||||
cp_svc.upsert_storage_cert(db, protocol_id, tenant_no, user_id, **storage_cert)
|
||||
|
||||
|
||||
@router.post("/collection-protocols")
|
||||
async def create_collection_protocol(
|
||||
body: ProtocolCreateBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
user_id = _get_current_user_id(user)
|
||||
try:
|
||||
protocol_attachments = _resolve_protocol_attachments(
|
||||
body.protocol_attachments,
|
||||
body.attachments,
|
||||
)
|
||||
obj = cp_svc.create_collection_protocol(
|
||||
db,
|
||||
protocol_no=body.protocol_no or "",
|
||||
protocol_no_id=body.protocol_no_id,
|
||||
protocol_status=body.protocol_status,
|
||||
protocol_attachments=protocol_attachments,
|
||||
register_date=body.register_date,
|
||||
collector_user_id=user_id,
|
||||
remark=body.remark,
|
||||
tenant_no=tenant_no,
|
||||
user_id=user_id,
|
||||
)
|
||||
protocol_id = obj.id
|
||||
_persist_protocol_sub_resources(
|
||||
db,
|
||||
protocol_id,
|
||||
tenant_no,
|
||||
user_id,
|
||||
party_customer=body.party_customer,
|
||||
collection_info=body.collection_info,
|
||||
samples=body.samples,
|
||||
payment=body.payment,
|
||||
payment_details=body.payment_details,
|
||||
storage_cert=body.storage_cert,
|
||||
)
|
||||
return success_response(cp_svc._protocol_to_dict(obj), message="创建成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.put("/collection-protocols/{protocol_id}")
|
||||
async def update_collection_protocol(
|
||||
protocol_id: str,
|
||||
body: ProtocolUpdateBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
user_id = _get_current_user_id(user)
|
||||
try:
|
||||
payload = body.model_dump(exclude_unset=True, by_alias=False)
|
||||
sub_keys = {
|
||||
"party_customer", "collection_info", "samples",
|
||||
"payment", "payment_details", "attachments", "storage_cert",
|
||||
}
|
||||
main_payload = {k: v for k, v in payload.items() if k not in sub_keys}
|
||||
main_payload.pop("collector_user_id", None)
|
||||
if body.attachments is not None:
|
||||
resolved = _resolve_protocol_attachments(
|
||||
main_payload.get("protocol_attachments"),
|
||||
body.attachments,
|
||||
)
|
||||
if resolved is not None:
|
||||
main_payload["protocol_attachments"] = resolved
|
||||
obj = cp_svc.update_collection_protocol(
|
||||
db,
|
||||
protocol_id,
|
||||
tenant_no=tenant_no,
|
||||
user_id=user_id,
|
||||
scope_collector_user_id=user_id,
|
||||
**{k: v for k, v in main_payload.items() if v is not None},
|
||||
)
|
||||
_persist_protocol_sub_resources(
|
||||
db,
|
||||
protocol_id,
|
||||
tenant_no,
|
||||
user_id,
|
||||
party_customer=body.party_customer,
|
||||
collection_info=body.collection_info,
|
||||
samples=body.samples,
|
||||
payment=body.payment,
|
||||
payment_details=body.payment_details,
|
||||
storage_cert=body.storage_cert,
|
||||
)
|
||||
return success_response(cp_svc._protocol_to_dict(obj), message="更新成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.delete("/collection-protocols/{protocol_id}")
|
||||
async def delete_collection_protocol(
|
||||
protocol_id: str,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
user_id = _get_current_user_id(user)
|
||||
try:
|
||||
cp_svc.soft_delete_collection_protocol(
|
||||
db,
|
||||
protocol_id,
|
||||
tenant_no=tenant_no,
|
||||
scope_collector_user_id=user_id,
|
||||
user_id=user_id,
|
||||
)
|
||||
return success_response(None, message="删除成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 审核
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@router.get("/collection-protocol-audits")
|
||||
async def list_collection_protocol_audits(
|
||||
page: int = Query(1, ge=1),
|
||||
pageSize: int = Query(10, ge=1, le=100, alias="pageSize"),
|
||||
keyword: Optional[str] = None,
|
||||
auditStatus: Optional[str] = Query(None, alias="auditStatus"),
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
items, total = cp_svc.list_audits(
|
||||
db,
|
||||
page=page,
|
||||
page_size=pageSize,
|
||||
keyword=keyword,
|
||||
audit_status=auditStatus,
|
||||
tenant_no=tenant_no,
|
||||
user_info=user,
|
||||
)
|
||||
tp = cp_svc.total_pages(total, pageSize)
|
||||
return success_response({"list": items, "total": total, "page": page, "pageSize": pageSize, "totalPages": tp})
|
||||
|
||||
|
||||
class AuditCreateBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
audit_status: str = Field(..., alias="auditStatus")
|
||||
audit_remark: Optional[str] = Field(None, alias="auditRemark")
|
||||
|
||||
|
||||
@router.post("/collection-protocols/{protocol_id}/audit")
|
||||
async def submit_collection_protocol_audit(
|
||||
protocol_id: str,
|
||||
body: AuditCreateBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
try:
|
||||
cp_svc.create_audit(
|
||||
db,
|
||||
collection_protocol_id=protocol_id,
|
||||
audit_status=body.audit_status,
|
||||
audit_remark=body.audit_remark,
|
||||
tenant_no=tenant_no,
|
||||
user_id=user.get("user_id"),
|
||||
)
|
||||
p = db.query(BizCollectionProtocol).filter(BizCollectionProtocol.id == protocol_id).first()
|
||||
pn = (p.protocol_no if p else "") or ""
|
||||
return success_response({"protocolNo": pn}, message="审核已提交")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 收款确认
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@router.get("/protocol-payment-details")
|
||||
async def list_payment_details(
|
||||
page: int = Query(1, ge=1),
|
||||
pageSize: int = Query(10, ge=1, le=100, alias="pageSize"),
|
||||
payStatus: str = Query("dfj", alias="payStatus"),
|
||||
keyword: str = Query("", alias="keyword"),
|
||||
transferType: str = Query("", alias="transferType"),
|
||||
installmentDueDateStart: Optional[str] = Query(None, alias="installmentDueDateStart"),
|
||||
installmentDueDateEnd: Optional[str] = Query(None, alias="installmentDueDateEnd"),
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
items, total = cp_svc.list_payment_details_page(
|
||||
db,
|
||||
page=page,
|
||||
page_size=pageSize,
|
||||
pay_status=payStatus,
|
||||
keyword=keyword or None,
|
||||
transfer_type=transferType or None,
|
||||
installment_due_date_start=installmentDueDateStart,
|
||||
installment_due_date_end=installmentDueDateEnd,
|
||||
tenant_no=tenant_no,
|
||||
user_info=user,
|
||||
)
|
||||
tp = cp_svc.total_pages(total, pageSize)
|
||||
return success_response({"list": items, "total": total, "page": page, "pageSize": pageSize, "totalPages": tp})
|
||||
|
||||
|
||||
class BatchDetailIdsBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
detail_ids: List[str] = Field(..., alias="detailIds", min_length=1)
|
||||
|
||||
|
||||
class RefundFinanceSubmitBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
refund_amount: float = Field(..., alias="refundAmount", gt=0)
|
||||
refund_remark: Optional[str] = Field(None, alias="refundRemark")
|
||||
refund_attachments: Optional[str] = Field(None, alias="refundAttachments")
|
||||
|
||||
|
||||
class BatchRefundFinanceSubmitBody(RefundFinanceSubmitBody):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
detail_ids: List[str] = Field(..., alias="detailIds", min_length=1)
|
||||
|
||||
|
||||
@router.post("/protocol-payment-details/{detail_id}/submit-receipt-finance")
|
||||
async def post_submit_receipt_finance(
|
||||
detail_id: str,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
try:
|
||||
cp_svc.submit_receipt_finance(
|
||||
db,
|
||||
detail_id=detail_id,
|
||||
tenant_no=tenant_no,
|
||||
user_id=user.get("user_id"),
|
||||
)
|
||||
return success_response(None, message="提交成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.post("/protocol-payment-details/submit-receipt-finance-batch")
|
||||
async def post_submit_receipt_finance_batch(
|
||||
body: BatchDetailIdsBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
try:
|
||||
count = cp_svc.batch_submit_receipt_finance(
|
||||
db,
|
||||
detail_ids=body.detail_ids,
|
||||
tenant_no=tenant_no,
|
||||
user_id=user.get("user_id"),
|
||||
)
|
||||
return success_response({"count": count}, message=f"已成功提交 {count} 条")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.post("/protocol-payment-details/{detail_id}/submit-refund-finance")
|
||||
async def post_submit_refund_finance(
|
||||
detail_id: str,
|
||||
body: RefundFinanceSubmitBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
try:
|
||||
cp_svc.submit_refund_finance(
|
||||
db,
|
||||
detail_id=detail_id,
|
||||
tenant_no=tenant_no,
|
||||
user_id=user.get("user_id"),
|
||||
refund_amount=body.refund_amount,
|
||||
refund_remark=body.refund_remark,
|
||||
refund_attachments=body.refund_attachments,
|
||||
)
|
||||
return success_response(None, message="提交成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.post("/protocol-payment-details/submit-refund-finance-batch")
|
||||
async def post_submit_refund_finance_batch(
|
||||
body: BatchRefundFinanceSubmitBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
try:
|
||||
count = cp_svc.batch_submit_refund_finance(
|
||||
db,
|
||||
detail_ids=body.detail_ids,
|
||||
tenant_no=tenant_no,
|
||||
user_id=user.get("user_id"),
|
||||
refund_amount=body.refund_amount,
|
||||
refund_remark=body.refund_remark,
|
||||
refund_attachments=body.refund_attachments,
|
||||
)
|
||||
return success_response({"count": count}, message=f"已成功提交 {count} 条")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.get("/protocol-payment-details/receipt-confirm")
|
||||
async def list_receipt_confirm(
|
||||
page: int = Query(1, ge=1),
|
||||
pageSize: int = Query(10, ge=1, le=100, alias="pageSize"),
|
||||
keyword: Optional[str] = None,
|
||||
installmentDueDateStart: Optional[str] = Query(None, alias="installmentDueDateStart"),
|
||||
installmentDueDateEnd: Optional[str] = Query(None, alias="installmentDueDateEnd"),
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
items, total = cp_svc.list_receipt_confirm_details(
|
||||
db,
|
||||
page=page,
|
||||
page_size=pageSize,
|
||||
keyword=keyword or None,
|
||||
installment_due_date_start=installmentDueDateStart,
|
||||
installment_due_date_end=installmentDueDateEnd,
|
||||
tenant_no=tenant_no,
|
||||
user_info=user,
|
||||
)
|
||||
tp = cp_svc.total_pages(total, pageSize)
|
||||
return success_response({"list": items, "total": total, "page": page, "pageSize": pageSize, "totalPages": tp})
|
||||
|
||||
|
||||
@router.get("/protocol-payment-details/receipt-confirmed")
|
||||
async def list_receipt_confirmed(
|
||||
page: int = Query(1, ge=1),
|
||||
pageSize: int = Query(10, ge=1, le=100, alias="pageSize"),
|
||||
keyword: Optional[str] = None,
|
||||
installmentDueDateStart: Optional[str] = Query(None, alias="installmentDueDateStart"),
|
||||
installmentDueDateEnd: Optional[str] = Query(None, alias="installmentDueDateEnd"),
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
items, total = cp_svc.list_receipt_confirmed_details(
|
||||
db,
|
||||
page=page,
|
||||
page_size=pageSize,
|
||||
keyword=keyword or None,
|
||||
installment_due_date_start=installmentDueDateStart,
|
||||
installment_due_date_end=installmentDueDateEnd,
|
||||
tenant_no=tenant_no,
|
||||
user_info=user,
|
||||
)
|
||||
tp = cp_svc.total_pages(total, pageSize)
|
||||
return success_response({"list": items, "total": total, "page": page, "pageSize": pageSize, "totalPages": tp})
|
||||
|
||||
|
||||
class FinanceConfirmBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
finance_confirm_attachments: Optional[str] = Field(None, alias="financeConfirmAttachments")
|
||||
finance_remark: Optional[str] = Field(None, alias="financeRemark")
|
||||
|
||||
|
||||
class RefundFinanceConfirmBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
refund_finance_confirm_attachments: Optional[str] = Field(
|
||||
None, alias="refundFinanceConfirmAttachments"
|
||||
)
|
||||
refund_finance_remark: Optional[str] = Field(None, alias="refundFinanceRemark")
|
||||
|
||||
|
||||
@router.post("/protocol-payment-details/{detail_id}/receipt-confirm")
|
||||
async def post_receipt_confirm(
|
||||
detail_id: str,
|
||||
body: FinanceConfirmBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
try:
|
||||
cp_svc.confirm_receipt(
|
||||
db,
|
||||
detail_id=detail_id,
|
||||
tenant_no=tenant_no,
|
||||
user_id=user.get("user_id"),
|
||||
finance_confirm_attachments=body.finance_confirm_attachments,
|
||||
finance_remark=body.finance_remark,
|
||||
)
|
||||
return success_response(None, message="确认成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 退费确认
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@router.get("/protocol-payment-details/refund-confirm")
|
||||
async def list_refund_confirm(
|
||||
page: int = Query(1, ge=1),
|
||||
pageSize: int = Query(10, ge=1, le=100, alias="pageSize"),
|
||||
keyword: Optional[str] = None,
|
||||
installmentDueDateStart: Optional[str] = Query(None, alias="installmentDueDateStart"),
|
||||
installmentDueDateEnd: Optional[str] = Query(None, alias="installmentDueDateEnd"),
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
items, total = cp_svc.list_refund_confirm_details(
|
||||
db,
|
||||
page=page,
|
||||
page_size=pageSize,
|
||||
keyword=keyword or None,
|
||||
installment_due_date_start=installmentDueDateStart,
|
||||
installment_due_date_end=installmentDueDateEnd,
|
||||
tenant_no=tenant_no,
|
||||
user_info=user,
|
||||
)
|
||||
tp = cp_svc.total_pages(total, pageSize)
|
||||
return success_response({"list": items, "total": total, "page": page, "pageSize": pageSize, "totalPages": tp})
|
||||
|
||||
|
||||
@router.get("/protocol-payment-details/refund-confirmed")
|
||||
async def list_refund_confirmed(
|
||||
page: int = Query(1, ge=1),
|
||||
pageSize: int = Query(10, ge=1, le=100, alias="pageSize"),
|
||||
keyword: Optional[str] = None,
|
||||
installmentDueDateStart: Optional[str] = Query(None, alias="installmentDueDateStart"),
|
||||
installmentDueDateEnd: Optional[str] = Query(None, alias="installmentDueDateEnd"),
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
items, total = cp_svc.list_refund_confirmed_details(
|
||||
db,
|
||||
page=page,
|
||||
page_size=pageSize,
|
||||
keyword=keyword or None,
|
||||
installment_due_date_start=installmentDueDateStart,
|
||||
installment_due_date_end=installmentDueDateEnd,
|
||||
tenant_no=tenant_no,
|
||||
user_info=user,
|
||||
)
|
||||
tp = cp_svc.total_pages(total, pageSize)
|
||||
return success_response({"list": items, "total": total, "page": page, "pageSize": pageSize, "totalPages": tp})
|
||||
|
||||
|
||||
@router.post("/protocol-payment-details/{detail_id}/refund-confirm")
|
||||
async def post_refund_confirm(
|
||||
detail_id: str,
|
||||
body: RefundFinanceConfirmBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
try:
|
||||
cp_svc.confirm_refund(
|
||||
db,
|
||||
detail_id=detail_id,
|
||||
tenant_no=tenant_no,
|
||||
user_id=user.get("user_id"),
|
||||
refund_finance_confirm_attachments=body.refund_finance_confirm_attachments,
|
||||
refund_finance_remark=body.refund_finance_remark,
|
||||
)
|
||||
return success_response(None, message="确认成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 储存证明管理 / 满月待办
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@router.get("/storage-certs")
|
||||
async def list_storage_certs(
|
||||
page: int = Query(1, ge=1),
|
||||
pageSize: int = Query(10, ge=1, le=100, alias="pageSize"),
|
||||
keyword: Optional[str] = None,
|
||||
makeStatus: Optional[str] = Query(None, alias="makeStatus"),
|
||||
storageInDateStart: Optional[str] = Query(None, alias="storageInDateStart"),
|
||||
storageInDateEnd: Optional[str] = Query(None, alias="storageInDateEnd"),
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
page_items, total = cp_svc.list_storage_certs(
|
||||
db,
|
||||
tenant_no=tenant_no,
|
||||
keyword=keyword,
|
||||
make_status=makeStatus,
|
||||
storage_in_date_start=storageInDateStart,
|
||||
storage_in_date_end=storageInDateEnd,
|
||||
page=page,
|
||||
page_size=pageSize,
|
||||
user_info=user,
|
||||
)
|
||||
page_safe = max(1, page)
|
||||
page_size_safe = min(max(1, pageSize), 100)
|
||||
tp = cp_svc.total_pages(total, page_size_safe)
|
||||
return success_response(
|
||||
{"list": page_items, "total": total, "page": page_safe, "pageSize": page_size_safe, "totalPages": tp}
|
||||
)
|
||||
|
||||
|
||||
@router.get("/fullmoon-todos")
|
||||
async def list_fullmoon_todos(
|
||||
page: int = Query(1, ge=1),
|
||||
pageSize: int = Query(10, ge=1, le=100, alias="pageSize"),
|
||||
keyword: Optional[str] = None,
|
||||
todoStatus: Optional[str] = Query(None, alias="todoStatus"),
|
||||
fullmoonDateStart: Optional[str] = Query(None, alias="fullmoonDateStart"),
|
||||
fullmoonDateEnd: Optional[str] = Query(None, alias="fullmoonDateEnd"),
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
party_join = sa_and(
|
||||
BizProtocolPartyCustomer.collection_protocol_id == BizCollectionProtocol.id,
|
||||
BizProtocolPartyCustomer.del_flag == 0,
|
||||
BizProtocolPartyCustomer.tenant_no == tenant_no,
|
||||
)
|
||||
q = (
|
||||
db.query(BizCollectionProtocol, BizProtocolPartyCustomer)
|
||||
.outerjoin(BizProtocolPartyCustomer, party_join)
|
||||
.filter(
|
||||
BizCollectionProtocol.del_flag == 0,
|
||||
BizCollectionProtocol.tenant_no == tenant_no,
|
||||
BizCollectionProtocol.protocol_status == "sxz",
|
||||
)
|
||||
)
|
||||
kw = (keyword or "").strip()
|
||||
if kw:
|
||||
like = f"%{kw}%"
|
||||
q = q.filter(
|
||||
sa_or(
|
||||
BizCollectionProtocol.protocol_no.like(like),
|
||||
BizProtocolPartyCustomer.mother_name.like(like),
|
||||
)
|
||||
)
|
||||
|
||||
from app.core.data_scope import apply_data_scope
|
||||
q = apply_data_scope(q, BizCollectionProtocol, user, db, tenant_no)
|
||||
|
||||
rows = q.order_by(BizCollectionProtocol.create_time.desc()).all()
|
||||
|
||||
protocol_ids = [r.id for r, _ in rows]
|
||||
ft_map: Dict[str, Any] = {}
|
||||
if protocol_ids:
|
||||
from app.models.models import BizProtocolFullmoonTodo
|
||||
ft_rows = (
|
||||
db.query(BizProtocolFullmoonTodo)
|
||||
.filter(
|
||||
BizProtocolFullmoonTodo.collection_protocol_id.in_(protocol_ids),
|
||||
BizProtocolFullmoonTodo.tenant_no == tenant_no,
|
||||
BizProtocolFullmoonTodo.del_flag == 0,
|
||||
)
|
||||
.all()
|
||||
)
|
||||
for ft in ft_rows:
|
||||
ft_map[ft.collection_protocol_id] = ft
|
||||
|
||||
now = datetime.now()
|
||||
_empty_ft: Dict[str, Any] = {
|
||||
"todoStatus": "0",
|
||||
"handleDate": "",
|
||||
"handleRemark": "",
|
||||
"insuranceAttachments": "",
|
||||
"insuranceCompanyId": "",
|
||||
"insuranceCompanyName": "",
|
||||
"insuranceType": "",
|
||||
"insurancePolicyNo": "",
|
||||
"insuranceEffectiveDate": "",
|
||||
"insuranceExpiryDate": "",
|
||||
"insuranceSubscribed": "0",
|
||||
"insuranceFee": None,
|
||||
}
|
||||
items: List[Dict[str, Any]] = []
|
||||
for proto, pc in rows:
|
||||
dt = pc.newborn_delivery_time if pc else None
|
||||
fullmoon_date_str = ""
|
||||
is_fullmoon_passed = False
|
||||
if dt:
|
||||
fullmoon_date = dt + timedelta(days=30)
|
||||
fullmoon_date_str = fullmoon_date.strftime("%Y-%m-%d")
|
||||
is_fullmoon_passed = fullmoon_date <= now
|
||||
ft = ft_map.get(proto.id)
|
||||
ts = (ft.todo_status or "0") if ft else "0"
|
||||
if todoStatus and todoStatus.strip() and ts != todoStatus.strip():
|
||||
continue
|
||||
fm_start = (fullmoonDateStart or "").strip()[:10]
|
||||
fm_end = (fullmoonDateEnd or "").strip()[:10]
|
||||
if fm_start or fm_end:
|
||||
if not fullmoon_date_str:
|
||||
continue
|
||||
if fm_start and fullmoon_date_str < fm_start:
|
||||
continue
|
||||
if fm_end and fullmoon_date_str > fm_end:
|
||||
continue
|
||||
ft_dict = cp_svc._fullmoon_todo_to_dict(ft) if ft else dict(_empty_ft)
|
||||
items.append(
|
||||
{
|
||||
"protocolId": proto.id,
|
||||
"id": proto.id,
|
||||
"protocolNo": proto.protocol_no or "",
|
||||
"protocolStatus": proto.protocol_status or "",
|
||||
"motherName": (pc.mother_name if pc else "") or "",
|
||||
"motherPhone": (pc.mother_phone if pc else "") or "",
|
||||
"newbornName": (pc.newborn_name if pc else "") or "",
|
||||
"newbornDeliveryTime": cp_svc._fmt_dt(dt) if dt else "",
|
||||
"fullmoonDate": fullmoon_date_str,
|
||||
"isFullmoonPassed": is_fullmoon_passed,
|
||||
**ft_dict,
|
||||
}
|
||||
)
|
||||
|
||||
total = len(items)
|
||||
page_safe = max(1, page)
|
||||
page_size_safe = min(max(1, pageSize), 100)
|
||||
start = (page_safe - 1) * page_size_safe
|
||||
page_items = items[start : start + page_size_safe]
|
||||
tp = cp_svc.total_pages(total, page_size_safe)
|
||||
return success_response(
|
||||
{"list": page_items, "total": total, "page": page_safe, "pageSize": page_size_safe, "totalPages": tp}
|
||||
)
|
||||
|
||||
|
||||
class FullmoonTodoInsuranceBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
insurance_company_id: Optional[str] = Field(None, alias="insuranceCompanyId")
|
||||
insurance_company_name: Optional[str] = Field(None, alias="insuranceCompanyName")
|
||||
insurance_type: Optional[str] = Field(None, alias="insuranceType")
|
||||
insurance_policy_no: Optional[str] = Field(None, alias="insurancePolicyNo")
|
||||
insurance_effective_date: Optional[str] = Field(None, alias="insuranceEffectiveDate")
|
||||
insurance_expiry_date: Optional[str] = Field(None, alias="insuranceExpiryDate")
|
||||
insurance_subscribed: Optional[str] = Field(None, alias="insuranceSubscribed")
|
||||
insurance_fee: Optional[float] = Field(None, alias="insuranceFee")
|
||||
insurance_attachments: Optional[str] = Field(None, alias="insuranceAttachments")
|
||||
todo_status: Optional[str] = Field(None, alias="todoStatus")
|
||||
handle_date: Optional[str] = Field(None, alias="handleDate")
|
||||
handle_remark: Optional[str] = Field(None, alias="handleRemark")
|
||||
|
||||
|
||||
@router.put("/fullmoon-todos/{protocol_id}/insurance")
|
||||
async def update_fullmoon_todo_insurance(
|
||||
protocol_id: str,
|
||||
body: FullmoonTodoInsuranceBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
user_id = _get_current_user_id(user)
|
||||
try:
|
||||
payload = body.model_dump(exclude_unset=True, by_alias=False)
|
||||
ft = cp_svc.upsert_fullmoon_todo(
|
||||
db,
|
||||
protocol_id,
|
||||
tenant_no,
|
||||
user_id,
|
||||
**payload,
|
||||
)
|
||||
return success_response(cp_svc._fullmoon_todo_to_dict(ft), message="更新成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
"""民族码表(下拉检索)"""
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
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 success_response
|
||||
from app.crud import ethnic as ethnic_svc
|
||||
|
||||
router = APIRouter(prefix="/web/admin", tags=["民族码表"])
|
||||
|
||||
|
||||
@router.get("/ethnics")
|
||||
async def list_ethnics_for_select(
|
||||
keyword: Optional[str] = Query(None, description="民族名称模糊检索"),
|
||||
limit: int = Query(200, ge=1, le=500),
|
||||
_user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""返回民族码表选项(按排序号升序)。"""
|
||||
rows = ethnic_svc.list_ethnics(db, keyword=keyword, limit=limit, user_info=_user)
|
||||
return success_response({"list": rows})
|
||||
@@ -1,857 +0,0 @@
|
||||
"""保险公司及险种价格管理 API(保险公司 + 开票信息 + 险种价格)"""
|
||||
import math
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from typing import Any, List, Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
from sqlalchemy import or_
|
||||
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.models.models import (
|
||||
BizInsuranceCompany,
|
||||
BizInsuranceCompanyInvoice,
|
||||
BizInsuranceProjectPrice,
|
||||
SysUser,
|
||||
)
|
||||
|
||||
router = APIRouter(prefix="/web/admin", tags=["保险公司及险种价格管理"])
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _get_tenant_no(db: Session, user: dict) -> str:
|
||||
user_id = user.get("user_id")
|
||||
if not user_id:
|
||||
raise PermissionError("用户身份信息缺失,无法确定租户")
|
||||
sys_user = db.query(SysUser).filter(SysUser.id == user_id).first()
|
||||
if not sys_user or not sys_user.tenant_no:
|
||||
raise PermissionError("用户租户信息缺失")
|
||||
return sys_user.tenant_no
|
||||
|
||||
|
||||
def _generate_uuid() -> str:
|
||||
return str(uuid.uuid4()).replace("-", "")
|
||||
|
||||
|
||||
def _fmt_dt(v) -> Optional[str]:
|
||||
if v is None:
|
||||
return None
|
||||
if isinstance(v, datetime):
|
||||
return v.strftime("%Y-%m-%d %H:%M:%S")
|
||||
return str(v)
|
||||
|
||||
|
||||
def _total_pages(total: int, page_size: int) -> int:
|
||||
return math.ceil(total / page_size) if page_size > 0 else 0
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Row-to-dict helpers (camelCase JSON)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _row_to_dict_company(row: BizInsuranceCompany) -> dict:
|
||||
return {
|
||||
"id": row.id,
|
||||
"companyName": row.company_name,
|
||||
"companyAddress": row.company_address,
|
||||
"contactName": row.contact_name,
|
||||
"contactPhone": row.contact_phone,
|
||||
"status": row.status,
|
||||
"tenantNo": row.tenant_no,
|
||||
"orderNum": row.order_num,
|
||||
"remark": row.remark,
|
||||
"createBy": row.create_by,
|
||||
"createDeptId": row.create_dept_id,
|
||||
"createTime": _fmt_dt(row.create_time),
|
||||
"updateBy": row.update_by,
|
||||
"updateTime": _fmt_dt(row.update_time),
|
||||
}
|
||||
|
||||
|
||||
def _row_to_dict_invoice(row: BizInsuranceCompanyInvoice) -> dict:
|
||||
return {
|
||||
"id": row.id,
|
||||
"insuranceCompanyId": row.insurance_company_id,
|
||||
"companyName": row.company_name,
|
||||
"taxNo": row.tax_no,
|
||||
"companyAddress": row.company_address,
|
||||
"companyPhone": row.company_phone,
|
||||
"bankName": row.bank_name,
|
||||
"bankAccount": row.bank_account,
|
||||
"tenantNo": row.tenant_no,
|
||||
"orderNum": row.order_num,
|
||||
"remark": row.remark,
|
||||
"createBy": row.create_by,
|
||||
"createDeptId": row.create_dept_id,
|
||||
"createTime": _fmt_dt(row.create_time),
|
||||
"updateBy": row.update_by,
|
||||
"updateTime": _fmt_dt(row.update_time),
|
||||
}
|
||||
|
||||
|
||||
def _row_to_dict_project_price(row: BizInsuranceProjectPrice) -> dict:
|
||||
return {
|
||||
"id": row.id,
|
||||
"insuranceCompanyId": row.insurance_company_id,
|
||||
"projectName": row.project_name,
|
||||
"projectFee": float(row.project_fee) if row.project_fee is not None else None,
|
||||
"status": row.status,
|
||||
"tenantNo": row.tenant_no,
|
||||
"orderNum": row.order_num,
|
||||
"remark": row.remark,
|
||||
"createBy": row.create_by,
|
||||
"createDeptId": row.create_dept_id,
|
||||
"createTime": _fmt_dt(row.create_time),
|
||||
"updateBy": row.update_by,
|
||||
"updateTime": _fmt_dt(row.update_time),
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Inline CRUD — 保险公司主表
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _list_insurance_companies(
|
||||
db: Session,
|
||||
*,
|
||||
page: int,
|
||||
page_size: int,
|
||||
keyword: Optional[str],
|
||||
status: Optional[str],
|
||||
tenant_no: str,
|
||||
user_info=None,
|
||||
):
|
||||
q = db.query(BizInsuranceCompany).filter(
|
||||
BizInsuranceCompany.tenant_no == tenant_no,
|
||||
BizInsuranceCompany.del_flag == 0,
|
||||
)
|
||||
kw = (keyword or "").strip()
|
||||
if kw:
|
||||
like = f"%{kw}%"
|
||||
q = q.filter(
|
||||
or_(
|
||||
BizInsuranceCompany.company_name.like(like),
|
||||
BizInsuranceCompany.contact_name.like(like),
|
||||
)
|
||||
)
|
||||
st = (status or "").strip()
|
||||
if st in ("0", "1"):
|
||||
q = q.filter(BizInsuranceCompany.status == st)
|
||||
if user_info:
|
||||
from app.core.data_scope import apply_data_scope
|
||||
q = apply_data_scope(q, BizInsuranceCompany, user_info, db, tenant_no)
|
||||
total = q.count()
|
||||
rows = (
|
||||
q.order_by(BizInsuranceCompany.create_time.desc())
|
||||
.offset((page - 1) * page_size)
|
||||
.limit(page_size)
|
||||
.all()
|
||||
)
|
||||
return [_row_to_dict_company(r) for r in rows], total
|
||||
|
||||
|
||||
def _create_insurance_company(
|
||||
db: Session,
|
||||
*,
|
||||
company_name: str,
|
||||
company_address: Optional[str],
|
||||
contact_name: Optional[str],
|
||||
contact_phone: Optional[str],
|
||||
status: Optional[str],
|
||||
tenant_no: str,
|
||||
order_num: Optional[int],
|
||||
remark: Optional[str],
|
||||
user_id: str,
|
||||
) -> BizInsuranceCompany:
|
||||
obj = BizInsuranceCompany(
|
||||
id=_generate_uuid(),
|
||||
company_name=company_name,
|
||||
company_address=company_address,
|
||||
contact_name=contact_name,
|
||||
contact_phone=contact_phone,
|
||||
status=status or "1",
|
||||
tenant_no=tenant_no,
|
||||
order_num=order_num or 0,
|
||||
remark=remark,
|
||||
create_by=user_id,
|
||||
create_dept_id="",
|
||||
create_time=datetime.now(),
|
||||
update_by=user_id,
|
||||
update_time=datetime.now(),
|
||||
del_flag=0,
|
||||
)
|
||||
db.add(obj)
|
||||
db.commit()
|
||||
db.refresh(obj)
|
||||
return obj
|
||||
|
||||
|
||||
def _update_insurance_company(
|
||||
db: Session,
|
||||
row_id: str,
|
||||
*,
|
||||
company_name: Optional[str],
|
||||
company_address: Optional[str],
|
||||
contact_name: Optional[str],
|
||||
contact_phone: Optional[str],
|
||||
status: Optional[str],
|
||||
order_num: Optional[int],
|
||||
remark: Optional[str],
|
||||
user_id: str,
|
||||
tenant_no: str,
|
||||
) -> BizInsuranceCompany:
|
||||
obj = (
|
||||
db.query(BizInsuranceCompany)
|
||||
.filter(
|
||||
BizInsuranceCompany.id == row_id,
|
||||
BizInsuranceCompany.tenant_no == tenant_no,
|
||||
BizInsuranceCompany.del_flag == 0,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if not obj:
|
||||
raise ValueError("记录不存在")
|
||||
if company_name is not None:
|
||||
obj.company_name = company_name
|
||||
if company_address is not None:
|
||||
obj.company_address = company_address
|
||||
if contact_name is not None:
|
||||
obj.contact_name = contact_name
|
||||
if contact_phone is not None:
|
||||
obj.contact_phone = contact_phone
|
||||
if status is not None:
|
||||
obj.status = status
|
||||
if order_num is not None:
|
||||
obj.order_num = order_num
|
||||
if remark is not None:
|
||||
obj.remark = remark
|
||||
obj.update_by = user_id
|
||||
obj.update_time = datetime.now()
|
||||
db.commit()
|
||||
db.refresh(obj)
|
||||
return obj
|
||||
|
||||
|
||||
def _soft_delete_insurance_company(db: Session, row_id: str, *, tenant_no: str):
|
||||
obj = (
|
||||
db.query(BizInsuranceCompany)
|
||||
.filter(
|
||||
BizInsuranceCompany.id == row_id,
|
||||
BizInsuranceCompany.tenant_no == tenant_no,
|
||||
BizInsuranceCompany.del_flag == 0,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if not obj:
|
||||
raise ValueError("记录不存在")
|
||||
obj.del_flag = 1
|
||||
db.commit()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Inline CRUD — 险种开票信息
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _list_insurance_company_invoices(
|
||||
db: Session, insurance_company_id: str, *, tenant_no: str, user_info=None
|
||||
):
|
||||
# Verify parent exists
|
||||
parent = (
|
||||
db.query(BizInsuranceCompany)
|
||||
.filter(
|
||||
BizInsuranceCompany.id == insurance_company_id,
|
||||
BizInsuranceCompany.tenant_no == tenant_no,
|
||||
BizInsuranceCompany.del_flag == 0,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if not parent:
|
||||
raise ValueError("保险公司不存在")
|
||||
q = db.query(BizInsuranceCompanyInvoice).filter(
|
||||
BizInsuranceCompanyInvoice.insurance_company_id == insurance_company_id,
|
||||
BizInsuranceCompanyInvoice.tenant_no == tenant_no,
|
||||
BizInsuranceCompanyInvoice.del_flag == 0,
|
||||
)
|
||||
if user_info:
|
||||
from app.core.data_scope import apply_data_scope
|
||||
q = apply_data_scope(q, BizInsuranceCompanyInvoice, user_info, db, tenant_no)
|
||||
rows = q.order_by(BizInsuranceCompanyInvoice.create_time.desc()).all()
|
||||
return [_row_to_dict_invoice(r) for r in rows]
|
||||
|
||||
|
||||
def _create_insurance_company_invoice(
|
||||
db: Session,
|
||||
*,
|
||||
insurance_company_id: str,
|
||||
company_name: str,
|
||||
tax_no: Optional[str],
|
||||
company_address: Optional[str],
|
||||
company_phone: Optional[str],
|
||||
bank_name: Optional[str],
|
||||
bank_account: Optional[str],
|
||||
tenant_no: str,
|
||||
order_num: Optional[int],
|
||||
remark: Optional[str],
|
||||
user_id: str,
|
||||
) -> BizInsuranceCompanyInvoice:
|
||||
obj = BizInsuranceCompanyInvoice(
|
||||
id=_generate_uuid(),
|
||||
insurance_company_id=insurance_company_id,
|
||||
company_name=company_name,
|
||||
tax_no=tax_no,
|
||||
company_address=company_address,
|
||||
company_phone=company_phone,
|
||||
bank_name=bank_name,
|
||||
bank_account=bank_account,
|
||||
tenant_no=tenant_no,
|
||||
order_num=order_num or 0,
|
||||
remark=remark,
|
||||
create_by=user_id,
|
||||
create_dept_id="",
|
||||
create_time=datetime.now(),
|
||||
update_by=user_id,
|
||||
update_time=datetime.now(),
|
||||
del_flag=0,
|
||||
)
|
||||
db.add(obj)
|
||||
db.commit()
|
||||
db.refresh(obj)
|
||||
return obj
|
||||
|
||||
|
||||
def _update_insurance_company_invoice(
|
||||
db: Session,
|
||||
row_id: str,
|
||||
*,
|
||||
company_name: Optional[str],
|
||||
tax_no: Optional[str],
|
||||
company_address: Optional[str],
|
||||
company_phone: Optional[str],
|
||||
bank_name: Optional[str],
|
||||
bank_account: Optional[str],
|
||||
order_num: Optional[int],
|
||||
remark: Optional[str],
|
||||
user_id: str,
|
||||
tenant_no: str,
|
||||
) -> BizInsuranceCompanyInvoice:
|
||||
obj = (
|
||||
db.query(BizInsuranceCompanyInvoice)
|
||||
.filter(
|
||||
BizInsuranceCompanyInvoice.id == row_id,
|
||||
BizInsuranceCompanyInvoice.tenant_no == tenant_no,
|
||||
BizInsuranceCompanyInvoice.del_flag == 0,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if not obj:
|
||||
raise ValueError("记录不存在")
|
||||
if company_name is not None:
|
||||
obj.company_name = company_name
|
||||
if tax_no is not None:
|
||||
obj.tax_no = tax_no
|
||||
if company_address is not None:
|
||||
obj.company_address = company_address
|
||||
if company_phone is not None:
|
||||
obj.company_phone = company_phone
|
||||
if bank_name is not None:
|
||||
obj.bank_name = bank_name
|
||||
if bank_account is not None:
|
||||
obj.bank_account = bank_account
|
||||
if order_num is not None:
|
||||
obj.order_num = order_num
|
||||
if remark is not None:
|
||||
obj.remark = remark
|
||||
obj.update_by = user_id
|
||||
obj.update_time = datetime.now()
|
||||
db.commit()
|
||||
db.refresh(obj)
|
||||
return obj
|
||||
|
||||
|
||||
def _soft_delete_insurance_company_invoice(db: Session, row_id: str, *, tenant_no: str):
|
||||
obj = (
|
||||
db.query(BizInsuranceCompanyInvoice)
|
||||
.filter(
|
||||
BizInsuranceCompanyInvoice.id == row_id,
|
||||
BizInsuranceCompanyInvoice.tenant_no == tenant_no,
|
||||
BizInsuranceCompanyInvoice.del_flag == 0,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if not obj:
|
||||
raise ValueError("记录不存在")
|
||||
obj.del_flag = 1
|
||||
db.commit()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Inline CRUD — 险种价格
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _list_insurance_project_prices(
|
||||
db: Session, insurance_company_id: str, *, tenant_no: str, user_info=None
|
||||
):
|
||||
parent = (
|
||||
db.query(BizInsuranceCompany)
|
||||
.filter(
|
||||
BizInsuranceCompany.id == insurance_company_id,
|
||||
BizInsuranceCompany.tenant_no == tenant_no,
|
||||
BizInsuranceCompany.del_flag == 0,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if not parent:
|
||||
raise ValueError("保险公司不存在")
|
||||
q = db.query(BizInsuranceProjectPrice).filter(
|
||||
BizInsuranceProjectPrice.insurance_company_id == insurance_company_id,
|
||||
BizInsuranceProjectPrice.tenant_no == tenant_no,
|
||||
BizInsuranceProjectPrice.del_flag == 0,
|
||||
)
|
||||
if user_info:
|
||||
from app.core.data_scope import apply_data_scope
|
||||
q = apply_data_scope(q, BizInsuranceProjectPrice, user_info, db, tenant_no)
|
||||
rows = q.order_by(BizInsuranceProjectPrice.create_time.desc()).all()
|
||||
return [_row_to_dict_project_price(r) for r in rows]
|
||||
|
||||
|
||||
def _create_insurance_project_price(
|
||||
db: Session,
|
||||
*,
|
||||
insurance_company_id: str,
|
||||
project_name: str,
|
||||
project_fee: Optional[float],
|
||||
status: Optional[str],
|
||||
tenant_no: str,
|
||||
order_num: Optional[int],
|
||||
remark: Optional[str],
|
||||
user_id: str,
|
||||
) -> BizInsuranceProjectPrice:
|
||||
obj = BizInsuranceProjectPrice(
|
||||
id=_generate_uuid(),
|
||||
insurance_company_id=insurance_company_id,
|
||||
project_name=project_name,
|
||||
project_fee=project_fee,
|
||||
status=status or "1",
|
||||
tenant_no=tenant_no,
|
||||
order_num=order_num or 0,
|
||||
remark=remark,
|
||||
create_by=user_id,
|
||||
create_dept_id="",
|
||||
create_time=datetime.now(),
|
||||
update_by=user_id,
|
||||
update_time=datetime.now(),
|
||||
del_flag=0,
|
||||
)
|
||||
db.add(obj)
|
||||
db.commit()
|
||||
db.refresh(obj)
|
||||
return obj
|
||||
|
||||
|
||||
def _update_insurance_project_price(
|
||||
db: Session,
|
||||
row_id: str,
|
||||
*,
|
||||
project_name: Optional[str],
|
||||
project_fee: Optional[float],
|
||||
status: Optional[str],
|
||||
order_num: Optional[int],
|
||||
remark: Optional[str],
|
||||
user_id: str,
|
||||
tenant_no: str,
|
||||
) -> BizInsuranceProjectPrice:
|
||||
obj = (
|
||||
db.query(BizInsuranceProjectPrice)
|
||||
.filter(
|
||||
BizInsuranceProjectPrice.id == row_id,
|
||||
BizInsuranceProjectPrice.tenant_no == tenant_no,
|
||||
BizInsuranceProjectPrice.del_flag == 0,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if not obj:
|
||||
raise ValueError("记录不存在")
|
||||
if project_name is not None:
|
||||
obj.project_name = project_name
|
||||
if project_fee is not None:
|
||||
obj.project_fee = project_fee
|
||||
if status is not None:
|
||||
obj.status = status
|
||||
if order_num is not None:
|
||||
obj.order_num = order_num
|
||||
if remark is not None:
|
||||
obj.remark = remark
|
||||
obj.update_by = user_id
|
||||
obj.update_time = datetime.now()
|
||||
db.commit()
|
||||
db.refresh(obj)
|
||||
return obj
|
||||
|
||||
|
||||
def _soft_delete_insurance_project_price(db: Session, row_id: str, *, tenant_no: str):
|
||||
obj = (
|
||||
db.query(BizInsuranceProjectPrice)
|
||||
.filter(
|
||||
BizInsuranceProjectPrice.id == row_id,
|
||||
BizInsuranceProjectPrice.tenant_no == tenant_no,
|
||||
BizInsuranceProjectPrice.del_flag == 0,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if not obj:
|
||||
raise ValueError("记录不存在")
|
||||
obj.del_flag = 1
|
||||
db.commit()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 1. 保险公司(主表)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class InsuranceCompanyCreateBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
company_name: str = Field(..., alias="companyName")
|
||||
company_address: Optional[str] = Field(None, alias="companyAddress")
|
||||
contact_name: Optional[str] = Field(None, alias="contactName")
|
||||
contact_phone: Optional[str] = Field(None, alias="contactPhone")
|
||||
status: Optional[str] = Field("1", alias="status")
|
||||
order_num: Optional[int] = Field(0, alias="orderNum")
|
||||
remark: Optional[str] = None
|
||||
|
||||
|
||||
class InsuranceCompanyUpdateBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
company_name: Optional[str] = Field(None, alias="companyName")
|
||||
company_address: Optional[str] = Field(None, alias="companyAddress")
|
||||
contact_name: Optional[str] = Field(None, alias="contactName")
|
||||
contact_phone: Optional[str] = Field(None, alias="contactPhone")
|
||||
status: Optional[str] = Field(None, alias="status")
|
||||
order_num: Optional[int] = Field(None, alias="orderNum")
|
||||
remark: Optional[str] = None
|
||||
|
||||
|
||||
@router.get("/insurance-companies")
|
||||
async def list_insurance_companies(
|
||||
page: int = Query(1, ge=1),
|
||||
pageSize: int = Query(10, ge=1, le=100, alias="pageSize"),
|
||||
keyword: Optional[str] = None,
|
||||
status: Optional[str] = None,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
items, total = _list_insurance_companies(
|
||||
db,
|
||||
page=page,
|
||||
page_size=pageSize,
|
||||
keyword=keyword,
|
||||
status=status,
|
||||
tenant_no=tenant_no,
|
||||
user_info=user,
|
||||
)
|
||||
tp = _total_pages(total, pageSize)
|
||||
return success_response(
|
||||
{"list": items, "total": total, "page": page, "pageSize": pageSize, "totalPages": tp}
|
||||
)
|
||||
|
||||
|
||||
@router.post("/insurance-companies")
|
||||
async def create_insurance_company(
|
||||
body: InsuranceCompanyCreateBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
obj = _create_insurance_company(
|
||||
db,
|
||||
company_name=body.company_name,
|
||||
company_address=body.company_address,
|
||||
contact_name=body.contact_name,
|
||||
contact_phone=body.contact_phone,
|
||||
status=body.status,
|
||||
tenant_no=tenant_no,
|
||||
order_num=body.order_num,
|
||||
remark=body.remark,
|
||||
user_id=user.get("user_id"),
|
||||
)
|
||||
return success_response(_row_to_dict_company(obj), message="创建成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.put("/insurance-companies/{row_id}")
|
||||
async def update_insurance_company(
|
||||
row_id: str,
|
||||
body: InsuranceCompanyUpdateBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
payload: dict[str, Any] = body.model_dump(exclude_unset=True, by_alias=False)
|
||||
obj = _update_insurance_company(
|
||||
db,
|
||||
row_id,
|
||||
company_name=payload.get("company_name"),
|
||||
company_address=payload.get("company_address"),
|
||||
contact_name=payload.get("contact_name"),
|
||||
contact_phone=payload.get("contact_phone"),
|
||||
status=payload.get("status"),
|
||||
order_num=payload.get("order_num"),
|
||||
remark=payload.get("remark"),
|
||||
user_id=user.get("user_id"),
|
||||
tenant_no=tenant_no,
|
||||
)
|
||||
return success_response(_row_to_dict_company(obj), message="更新成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.delete("/insurance-companies/{row_id}")
|
||||
async def delete_insurance_company(
|
||||
row_id: str,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
_soft_delete_insurance_company(db, row_id, tenant_no=tenant_no)
|
||||
return success_response(None, message="删除成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 2. 保险公司开票信息(子表)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class InsuranceCompanyInvoiceCreateBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
company_name: str = Field(..., alias="companyName")
|
||||
tax_no: Optional[str] = Field(None, alias="taxNo")
|
||||
company_address: Optional[str] = Field(None, alias="companyAddress")
|
||||
company_phone: Optional[str] = Field(None, alias="companyPhone")
|
||||
bank_name: Optional[str] = Field(None, alias="bankName")
|
||||
bank_account: Optional[str] = Field(None, alias="bankAccount")
|
||||
order_num: Optional[int] = Field(0, alias="orderNum")
|
||||
remark: Optional[str] = None
|
||||
|
||||
|
||||
class InsuranceCompanyInvoiceUpdateBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
company_name: Optional[str] = Field(None, alias="companyName")
|
||||
tax_no: Optional[str] = Field(None, alias="taxNo")
|
||||
company_address: Optional[str] = Field(None, alias="companyAddress")
|
||||
company_phone: Optional[str] = Field(None, alias="companyPhone")
|
||||
bank_name: Optional[str] = Field(None, alias="bankName")
|
||||
bank_account: Optional[str] = Field(None, alias="bankAccount")
|
||||
order_num: Optional[int] = Field(None, alias="orderNum")
|
||||
remark: Optional[str] = None
|
||||
|
||||
|
||||
@router.get("/insurance-companies/{company_id}/invoices")
|
||||
async def list_insurance_company_invoices(
|
||||
company_id: str,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
items = _list_insurance_company_invoices(db, company_id, tenant_no=tenant_no, user_info=user)
|
||||
return success_response(items)
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.post("/insurance-companies/{company_id}/invoices")
|
||||
async def create_insurance_company_invoice(
|
||||
company_id: str,
|
||||
body: InsuranceCompanyInvoiceCreateBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
obj = _create_insurance_company_invoice(
|
||||
db,
|
||||
insurance_company_id=company_id,
|
||||
company_name=body.company_name,
|
||||
tax_no=body.tax_no,
|
||||
company_address=body.company_address,
|
||||
company_phone=body.company_phone,
|
||||
bank_name=body.bank_name,
|
||||
bank_account=body.bank_account,
|
||||
tenant_no=tenant_no,
|
||||
order_num=body.order_num,
|
||||
remark=body.remark,
|
||||
user_id=user.get("user_id"),
|
||||
)
|
||||
return success_response(_row_to_dict_invoice(obj), message="创建成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.put("/insurance-company-invoices/{invoice_id}")
|
||||
async def update_insurance_company_invoice(
|
||||
invoice_id: str,
|
||||
body: InsuranceCompanyInvoiceUpdateBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
payload: dict[str, Any] = body.model_dump(exclude_unset=True, by_alias=False)
|
||||
obj = _update_insurance_company_invoice(
|
||||
db,
|
||||
invoice_id,
|
||||
company_name=payload.get("company_name"),
|
||||
tax_no=payload.get("tax_no"),
|
||||
company_address=payload.get("company_address"),
|
||||
company_phone=payload.get("company_phone"),
|
||||
bank_name=payload.get("bank_name"),
|
||||
bank_account=payload.get("bank_account"),
|
||||
order_num=payload.get("order_num"),
|
||||
remark=payload.get("remark"),
|
||||
user_id=user.get("user_id"),
|
||||
tenant_no=tenant_no,
|
||||
)
|
||||
return success_response(_row_to_dict_invoice(obj), message="更新成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.delete("/insurance-company-invoices/{invoice_id}")
|
||||
async def delete_insurance_company_invoice(
|
||||
invoice_id: str,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
_soft_delete_insurance_company_invoice(db, invoice_id, tenant_no=tenant_no)
|
||||
return success_response(None, message="删除成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 3. 险种价格(子表)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class InsuranceProjectPriceCreateBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
project_name: str = Field(..., alias="projectName")
|
||||
project_fee: Optional[float] = Field(None, alias="projectFee")
|
||||
status: Optional[str] = Field("1", alias="status")
|
||||
order_num: Optional[int] = Field(0, alias="orderNum")
|
||||
remark: Optional[str] = None
|
||||
|
||||
|
||||
class InsuranceProjectPriceUpdateBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
project_name: Optional[str] = Field(None, alias="projectName")
|
||||
project_fee: Optional[float] = Field(None, alias="projectFee")
|
||||
status: Optional[str] = Field(None, alias="status")
|
||||
order_num: Optional[int] = Field(None, alias="orderNum")
|
||||
remark: Optional[str] = None
|
||||
|
||||
|
||||
@router.get("/insurance-companies/{company_id}/project-prices")
|
||||
async def list_insurance_project_prices(
|
||||
company_id: str,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
items = _list_insurance_project_prices(db, company_id, tenant_no=tenant_no, user_info=user)
|
||||
return success_response(items)
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.post("/insurance-companies/{company_id}/project-prices")
|
||||
async def create_insurance_project_price(
|
||||
company_id: str,
|
||||
body: InsuranceProjectPriceCreateBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
obj = _create_insurance_project_price(
|
||||
db,
|
||||
insurance_company_id=company_id,
|
||||
project_name=body.project_name,
|
||||
project_fee=body.project_fee,
|
||||
status=body.status,
|
||||
tenant_no=tenant_no,
|
||||
order_num=body.order_num,
|
||||
remark=body.remark,
|
||||
user_id=user.get("user_id"),
|
||||
)
|
||||
return success_response(_row_to_dict_project_price(obj), message="创建成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.put("/insurance-project-prices/{price_id}")
|
||||
async def update_insurance_project_price(
|
||||
price_id: str,
|
||||
body: InsuranceProjectPriceUpdateBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
payload: dict[str, Any] = body.model_dump(exclude_unset=True, by_alias=False)
|
||||
obj = _update_insurance_project_price(
|
||||
db,
|
||||
price_id,
|
||||
project_name=payload.get("project_name"),
|
||||
project_fee=payload.get("project_fee"),
|
||||
status=payload.get("status"),
|
||||
order_num=payload.get("order_num"),
|
||||
remark=payload.get("remark"),
|
||||
user_id=user.get("user_id"),
|
||||
tenant_no=tenant_no,
|
||||
)
|
||||
return success_response(_row_to_dict_project_price(obj), message="更新成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.delete("/insurance-project-prices/{price_id}")
|
||||
async def delete_insurance_project_price(
|
||||
price_id: str,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
_soft_delete_insurance_project_price(db, price_id, tenant_no=tenant_no)
|
||||
return success_response(None, message="删除成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
@@ -1,344 +0,0 @@
|
||||
"""市场物料库 API"""
|
||||
from datetime import datetime
|
||||
from typing import List, Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.api.sample_reception import _get_current_user_id, _get_tenant_no, _page_payload
|
||||
from app.core.database import get_db
|
||||
from app.core.utils import parse_datetime
|
||||
from app.core.menu_guard import require_admin_or_super_admin, require_menu_code
|
||||
from app.core.response import error_response, success_response
|
||||
from app.crud import material as mat_svc
|
||||
from app.crud import material_stock_log as msl_svc
|
||||
|
||||
router = APIRouter(prefix="/web/admin", tags=["市场物料"])
|
||||
|
||||
|
||||
# ---------- Body models ----------
|
||||
|
||||
|
||||
class MaterialBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
material_code: str = Field(..., alias="materialCode")
|
||||
material_name: str = Field(..., alias="materialName")
|
||||
category: Optional[str] = None
|
||||
spec_model: Optional[str] = Field(None, alias="specModel")
|
||||
unit: Optional[str] = None
|
||||
warning_qty: Optional[float] = Field(0, alias="warningQty")
|
||||
status: str = "1"
|
||||
order_num: Optional[int] = Field(None, alias="orderNum")
|
||||
remark: Optional[str] = None
|
||||
image_urls: Optional[str] = Field(None, alias="imageUrls")
|
||||
|
||||
|
||||
class MaterialUpdateBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
material_code: Optional[str] = Field(None, alias="materialCode")
|
||||
material_name: Optional[str] = Field(None, alias="materialName")
|
||||
category: Optional[str] = None
|
||||
spec_model: Optional[str] = Field(None, alias="specModel")
|
||||
unit: Optional[str] = None
|
||||
warning_qty: Optional[float] = Field(None, alias="warningQty")
|
||||
status: Optional[str] = None
|
||||
order_num: Optional[int] = Field(None, alias="orderNum")
|
||||
remark: Optional[str] = None
|
||||
image_urls: Optional[str] = Field(None, alias="imageUrls")
|
||||
|
||||
|
||||
class StockInBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
qty: float = Field(..., gt=0)
|
||||
remark: Optional[str] = None
|
||||
stock_in_time: Optional[str] = Field(None, alias="stockInTime")
|
||||
|
||||
|
||||
class StockOutBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
qty: float = Field(..., gt=0)
|
||||
receiver: Optional[str] = None
|
||||
purpose: Optional[str] = None
|
||||
remark: Optional[str] = None
|
||||
stock_out_time: Optional[str] = Field(None, alias="stockOutTime")
|
||||
|
||||
|
||||
class BatchStockInItem(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
material_id: str = Field(..., alias="materialId")
|
||||
qty: float = Field(..., gt=0)
|
||||
remark: Optional[str] = None
|
||||
|
||||
|
||||
class BatchStockInBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
items: List[BatchStockInItem] = Field(..., min_length=1)
|
||||
remark: Optional[str] = None
|
||||
stock_in_time: Optional[str] = Field(None, alias="stockInTime")
|
||||
|
||||
|
||||
class BatchStockOutItem(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
material_id: str = Field(..., alias="materialId")
|
||||
qty: float = Field(..., gt=0)
|
||||
remark: Optional[str] = None
|
||||
|
||||
|
||||
class BatchStockOutBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
items: List[BatchStockOutItem] = Field(..., min_length=1)
|
||||
receiver: Optional[str] = None
|
||||
purpose: Optional[str] = None
|
||||
remark: Optional[str] = None
|
||||
stock_out_time: Optional[str] = Field(None, alias="stockOutTime")
|
||||
|
||||
|
||||
# ---------- 物料 CRUD ----------
|
||||
|
||||
|
||||
@router.get("/materials")
|
||||
async def list_materials(
|
||||
page: int = Query(1, ge=1),
|
||||
pageSize: int = Query(10, ge=1, le=100),
|
||||
keyword: Optional[str] = None,
|
||||
category: Optional[str] = None,
|
||||
status: Optional[str] = None,
|
||||
db: Session = Depends(get_db),
|
||||
user: dict = Depends(require_menu_code("biz:material:list")),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
items, total = mat_svc.list_materials(
|
||||
db, tenant_no, page=page, page_size=pageSize,
|
||||
keyword=keyword, category=category, status=status, user_info=user,
|
||||
)
|
||||
return success_response(_page_payload(items, total, page, pageSize))
|
||||
except PermissionError as e:
|
||||
return error_response(403, str(e))
|
||||
except Exception as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.get("/materials/options")
|
||||
async def material_options(
|
||||
db: Session = Depends(get_db),
|
||||
user: dict = Depends(require_menu_code("biz:material:list")),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
return success_response(mat_svc.options_list(db, tenant_no=tenant_no))
|
||||
except Exception as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.post("/materials")
|
||||
async def create_material(
|
||||
body: MaterialBody,
|
||||
db: Session = Depends(get_db),
|
||||
user: dict = Depends(require_menu_code("biz:material:list")),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
user_id = _get_current_user_id(user)
|
||||
obj = mat_svc.create_material(
|
||||
db, body.model_dump(by_alias=True, exclude_none=True),
|
||||
tenant_no=tenant_no, user_id=user_id,
|
||||
)
|
||||
return success_response(obj, message="创建成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
except Exception as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.put("/materials/{material_id}")
|
||||
async def update_material(
|
||||
material_id: str,
|
||||
body: MaterialUpdateBody,
|
||||
db: Session = Depends(get_db),
|
||||
user: dict = Depends(require_menu_code("biz:material:list")),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
user_id = _get_current_user_id(user)
|
||||
obj = mat_svc.update_material(
|
||||
db, material_id, body.model_dump(by_alias=True, exclude_none=True),
|
||||
tenant_no=tenant_no, user_id=user_id,
|
||||
)
|
||||
return success_response(obj, message="更新成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
except Exception as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.delete("/materials/{material_id}")
|
||||
async def delete_material(
|
||||
material_id: str,
|
||||
db: Session = Depends(get_db),
|
||||
user: dict = Depends(require_menu_code("biz:material:list")),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
user_id = _get_current_user_id(user)
|
||||
mat_svc.soft_delete_material(db, material_id, tenant_no=tenant_no, user_id=user_id)
|
||||
return success_response(None, message="删除成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
except Exception as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.post("/materials/batch-stock-in")
|
||||
async def batch_stock_in_material(
|
||||
body: BatchStockInBody,
|
||||
db: Session = Depends(get_db),
|
||||
user: dict = Depends(require_menu_code("biz:material:list")),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
user_id = _get_current_user_id(user)
|
||||
operate_time = datetime.now()
|
||||
if body.stock_in_time:
|
||||
rt = parse_datetime(body.stock_in_time)
|
||||
if not rt:
|
||||
return error_response(400, "入库时间格式无效")
|
||||
operate_time = rt
|
||||
items = [
|
||||
{"material_id": x.material_id, "qty": x.qty, "remark": x.remark}
|
||||
for x in body.items
|
||||
]
|
||||
count = mat_svc.batch_stock_in(
|
||||
db,
|
||||
items=items,
|
||||
remark=body.remark,
|
||||
tenant_no=tenant_no,
|
||||
user_id=user_id,
|
||||
operate_time=operate_time,
|
||||
)
|
||||
return success_response({"count": count}, message=f"批量入库成功,共 {count} 项")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
except Exception as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.post("/materials/batch-stock-out")
|
||||
async def batch_stock_out_material(
|
||||
body: BatchStockOutBody,
|
||||
db: Session = Depends(get_db),
|
||||
user: dict = Depends(require_menu_code("biz:material:list")),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
user_id = _get_current_user_id(user)
|
||||
operate_time = datetime.now()
|
||||
if body.stock_out_time:
|
||||
rt = parse_datetime(body.stock_out_time)
|
||||
if not rt:
|
||||
return error_response(400, "出库时间格式无效")
|
||||
operate_time = rt
|
||||
items = [
|
||||
{"material_id": x.material_id, "qty": x.qty, "remark": x.remark}
|
||||
for x in body.items
|
||||
]
|
||||
count = mat_svc.batch_stock_out(
|
||||
db,
|
||||
items=items,
|
||||
receiver=body.receiver,
|
||||
purpose=body.purpose,
|
||||
remark=body.remark,
|
||||
tenant_no=tenant_no,
|
||||
user_id=user_id,
|
||||
operate_time=operate_time,
|
||||
)
|
||||
return success_response({"count": count}, message=f"批量出库成功,共 {count} 项")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
except Exception as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.post("/materials/{material_id}/stock-in")
|
||||
async def stock_in_material(
|
||||
material_id: str,
|
||||
body: StockInBody,
|
||||
db: Session = Depends(get_db),
|
||||
user: dict = Depends(require_menu_code("biz:material:list")),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
user_id = _get_current_user_id(user)
|
||||
operate_time = datetime.now()
|
||||
if body.stock_in_time:
|
||||
rt = parse_datetime(body.stock_in_time)
|
||||
if not rt:
|
||||
return error_response(400, "入库时间格式无效")
|
||||
operate_time = rt
|
||||
obj = mat_svc.stock_in(
|
||||
db, material_id, qty=body.qty, remark=body.remark,
|
||||
tenant_no=tenant_no, user_id=user_id, operate_time=operate_time,
|
||||
)
|
||||
return success_response(obj, message="入库成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
except Exception as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.post("/materials/{material_id}/stock-out")
|
||||
async def stock_out_material(
|
||||
material_id: str,
|
||||
body: StockOutBody,
|
||||
db: Session = Depends(get_db),
|
||||
user: dict = Depends(require_menu_code("biz:material:list")),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
user_id = _get_current_user_id(user)
|
||||
operate_time = datetime.now()
|
||||
if body.stock_out_time:
|
||||
rt = parse_datetime(body.stock_out_time)
|
||||
if not rt:
|
||||
return error_response(400, "出库时间格式无效")
|
||||
operate_time = rt
|
||||
obj = mat_svc.stock_out(
|
||||
db, material_id, qty=body.qty, receiver=body.receiver,
|
||||
purpose=body.purpose, remark=body.remark,
|
||||
tenant_no=tenant_no, user_id=user_id, operate_time=operate_time,
|
||||
)
|
||||
return success_response(obj, message="出库成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
except Exception as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
# ---------- 库存变动记录 ----------
|
||||
|
||||
|
||||
@router.get("/material-stock-logs")
|
||||
async def list_stock_logs(
|
||||
page: int = Query(1, ge=1),
|
||||
pageSize: int = Query(10, ge=1, le=100),
|
||||
materialId: Optional[str] = None,
|
||||
changeType: Optional[str] = None,
|
||||
startTime: Optional[str] = None,
|
||||
endTime: Optional[str] = None,
|
||||
keyword: Optional[str] = None,
|
||||
db: Session = Depends(get_db),
|
||||
user: dict = Depends(require_menu_code("biz:materialStockLog:list")),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
items, total = msl_svc.list_stock_logs(
|
||||
db, tenant_no, page=page, page_size=pageSize,
|
||||
material_id=materialId, change_type=changeType,
|
||||
start_time=startTime, end_time=endTime, keyword=keyword, user_info=user,
|
||||
)
|
||||
return success_response(_page_payload(items, total, page, pageSize))
|
||||
except PermissionError as e:
|
||||
return error_response(403, str(e))
|
||||
except Exception as e:
|
||||
return error_response(400, str(e))
|
||||
@@ -1,845 +0,0 @@
|
||||
"""运营支撑 API(洁净室、进出记录、仓储设施、储位、展厅预约)"""
|
||||
from datetime import datetime
|
||||
from typing import Any, Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
from sqlalchemy import or_
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.core.data_scope import apply_data_scope
|
||||
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.crud import clean_room as clean_room_svc
|
||||
from app.crud import exhibition_appointment as exhibition_svc
|
||||
from app.crud import storage_facility as storage_facility_svc
|
||||
from app.crud import storage_occupancy as occupancy_svc
|
||||
from app.core.utils import generate_uuid
|
||||
from app.models.models import BizCleanRoom, BizCleanRoomAccessLog, BizExhibitionAppointment, BizStorageFacility, BizStorageFacilitySlot, SysUser
|
||||
|
||||
router = APIRouter(prefix="/web/admin", tags=["运营支撑"])
|
||||
|
||||
|
||||
def _get_tenant_no(db: Session, user: dict) -> str:
|
||||
user_id = user.get("user_id")
|
||||
if not user_id:
|
||||
raise PermissionError("用户身份信息缺失,无法确定租户")
|
||||
sys_user = db.query(SysUser).filter(SysUser.id == user_id).first()
|
||||
if not sys_user or not sys_user.tenant_no:
|
||||
raise PermissionError("用户租户信息缺失")
|
||||
return sys_user.tenant_no
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 洁净室
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class CleanRoomCreateBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
room_code: str = Field(..., alias="roomCode")
|
||||
room_name: str = Field(..., alias="roomName")
|
||||
room_grade: Optional[str] = Field(None, alias="roomGrade")
|
||||
room_status: Optional[str] = Field("zc", alias="roomStatus")
|
||||
area_sqm: Optional[float] = Field(None, alias="areaSqm")
|
||||
order_num: Optional[int] = Field(0, alias="orderNum")
|
||||
remark: Optional[str] = None
|
||||
|
||||
|
||||
class CleanRoomUpdateBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
room_code: Optional[str] = Field(None, alias="roomCode")
|
||||
room_name: Optional[str] = Field(None, alias="roomName")
|
||||
room_grade: Optional[str] = Field(None, alias="roomGrade")
|
||||
room_status: Optional[str] = Field(None, alias="roomStatus")
|
||||
area_sqm: Optional[float] = Field(None, alias="areaSqm")
|
||||
order_num: Optional[int] = Field(None, alias="orderNum")
|
||||
remark: Optional[str] = None
|
||||
|
||||
|
||||
@router.get("/clean-rooms")
|
||||
async def list_clean_rooms(
|
||||
page: int = Query(1, ge=1),
|
||||
pageSize: int = Query(10, ge=1, le=100, alias="pageSize"),
|
||||
keyword: Optional[str] = None,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
query = db.query(BizCleanRoom).filter(
|
||||
BizCleanRoom.del_flag == 0,
|
||||
BizCleanRoom.tenant_no == tenant_no,
|
||||
)
|
||||
kw = (keyword or "").strip()
|
||||
if kw:
|
||||
like = f"%{kw}%"
|
||||
query = query.filter(or_(BizCleanRoom.room_code.like(like), BizCleanRoom.room_name.like(like)))
|
||||
query = apply_data_scope(query, BizCleanRoom, user, db, tenant_no)
|
||||
total = query.count()
|
||||
items = query.order_by(BizCleanRoom.create_time.desc()).offset((page - 1) * pageSize).limit(pageSize).all()
|
||||
result_list = [clean_room_svc._row_to_dict(r) for r in items]
|
||||
tp = clean_room_svc.total_pages(total, pageSize)
|
||||
return success_response({"list": result_list, "total": total, "page": page, "pageSize": pageSize, "totalPages": tp})
|
||||
|
||||
|
||||
@router.post("/clean-rooms")
|
||||
async def create_clean_room(
|
||||
body: CleanRoomCreateBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
obj = clean_room_svc.create_clean_room(
|
||||
db,
|
||||
room_code=body.room_code,
|
||||
room_name=body.room_name,
|
||||
room_grade=body.room_grade,
|
||||
room_status=body.room_status or "zc",
|
||||
area_sqm=body.area_sqm,
|
||||
tenant_no=tenant_no,
|
||||
order_num=body.order_num,
|
||||
remark=body.remark,
|
||||
user_id=user.get("user_id"),
|
||||
)
|
||||
return success_response(clean_room_svc._row_to_dict(obj), message="创建成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.put("/clean-rooms/{room_id}")
|
||||
async def update_clean_room(
|
||||
room_id: str,
|
||||
body: CleanRoomUpdateBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
payload: dict[str, Any] = body.model_dump(exclude_unset=True, by_alias=False)
|
||||
obj = clean_room_svc.update_clean_room(
|
||||
db,
|
||||
room_id,
|
||||
room_code=payload.get("room_code"),
|
||||
room_name=payload.get("room_name"),
|
||||
room_grade=payload.get("room_grade"),
|
||||
room_status=payload.get("room_status"),
|
||||
area_sqm=payload.get("area_sqm"),
|
||||
order_num=payload.get("order_num"),
|
||||
remark=payload.get("remark"),
|
||||
user_id=user.get("user_id"),
|
||||
tenant_no=tenant_no,
|
||||
)
|
||||
return success_response(clean_room_svc._row_to_dict(obj), message="更新成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.delete("/clean-rooms/{room_id}")
|
||||
async def delete_clean_room(
|
||||
room_id: str,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
clean_room_svc.soft_delete_clean_room(db, room_id, tenant_no=tenant_no)
|
||||
return success_response(None, message="删除成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 进出记录
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class AccessLogCreateBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
clean_room_id: str = Field(..., alias="cleanRoomId")
|
||||
person_name: Optional[str] = Field(None, alias="personName")
|
||||
dept_name: Optional[str] = Field(None, alias="deptName")
|
||||
enter_time: Optional[str] = Field(None, alias="enterTime")
|
||||
purpose: Optional[str] = None
|
||||
leave_time: Optional[str] = Field(None, alias="leaveTime")
|
||||
body_temp: Optional[str] = Field(None, alias="bodyTemp")
|
||||
order_num: Optional[int] = Field(0, alias="orderNum")
|
||||
remark: Optional[str] = None
|
||||
|
||||
|
||||
class AccessLogUpdateBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
person_name: Optional[str] = Field(None, alias="personName")
|
||||
dept_name: Optional[str] = Field(None, alias="deptName")
|
||||
enter_time: Optional[str] = Field(None, alias="enterTime")
|
||||
purpose: Optional[str] = None
|
||||
leave_time: Optional[str] = Field(None, alias="leaveTime")
|
||||
body_temp: Optional[str] = Field(None, alias="bodyTemp")
|
||||
order_num: Optional[int] = Field(None, alias="orderNum")
|
||||
remark: Optional[str] = None
|
||||
|
||||
|
||||
def _parse_optional_dt(value: Optional[str]) -> Optional[datetime]:
|
||||
if not value:
|
||||
return None
|
||||
return datetime.fromisoformat(value)
|
||||
|
||||
|
||||
@router.get("/clean-room-access-logs")
|
||||
async def list_access_logs(
|
||||
page: int = Query(1, ge=1),
|
||||
pageSize: int = Query(10, ge=1, le=100, alias="pageSize"),
|
||||
cleanRoomId: str = Query(..., alias="cleanRoomId"),
|
||||
keyword: Optional[str] = None,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
query = db.query(BizCleanRoomAccessLog).filter(
|
||||
BizCleanRoomAccessLog.del_flag == 0,
|
||||
BizCleanRoomAccessLog.tenant_no == tenant_no,
|
||||
BizCleanRoomAccessLog.clean_room_id == cleanRoomId,
|
||||
)
|
||||
if keyword:
|
||||
kw = f"%{keyword}%"
|
||||
query = query.filter(
|
||||
BizCleanRoomAccessLog.person_name.like(kw)
|
||||
| BizCleanRoomAccessLog.dept_name.like(kw)
|
||||
)
|
||||
query = apply_data_scope(query, BizCleanRoomAccessLog, user, db, tenant_no)
|
||||
total = query.count()
|
||||
items = query.order_by(BizCleanRoomAccessLog.create_time.desc()).offset((page - 1) * pageSize).limit(pageSize).all()
|
||||
result_list = [clean_room_svc._access_log_to_dict(r) for r in items]
|
||||
tp = clean_room_svc.total_pages(total, pageSize)
|
||||
return success_response({"list": result_list, "total": total, "page": page, "pageSize": pageSize, "totalPages": tp})
|
||||
|
||||
|
||||
@router.post("/clean-room-access-logs")
|
||||
async def create_access_log(
|
||||
body: AccessLogCreateBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
obj = clean_room_svc.create_access_log(
|
||||
db,
|
||||
clean_room_id=body.clean_room_id,
|
||||
person_name=body.person_name,
|
||||
dept_name=body.dept_name,
|
||||
enter_time=_parse_optional_dt(body.enter_time),
|
||||
purpose=body.purpose,
|
||||
leave_time=_parse_optional_dt(body.leave_time),
|
||||
body_temp=body.body_temp,
|
||||
tenant_no=tenant_no,
|
||||
order_num=body.order_num,
|
||||
remark=body.remark,
|
||||
user_id_param=user.get("user_id"),
|
||||
)
|
||||
return success_response(clean_room_svc._access_log_to_dict(obj), message="创建成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.put("/clean-room-access-logs/{log_id}")
|
||||
async def update_access_log(
|
||||
log_id: str,
|
||||
body: AccessLogUpdateBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
payload: dict[str, Any] = body.model_dump(exclude_unset=True, by_alias=False)
|
||||
obj = clean_room_svc.update_access_log(
|
||||
db,
|
||||
log_id,
|
||||
person_name=payload.get("person_name"),
|
||||
dept_name=payload.get("dept_name"),
|
||||
enter_time=_parse_optional_dt(payload.get("enter_time")) if "enter_time" in payload else None,
|
||||
purpose=payload.get("purpose"),
|
||||
leave_time=_parse_optional_dt(payload.get("leave_time")) if "leave_time" in payload else None,
|
||||
body_temp=payload.get("body_temp"),
|
||||
order_num=payload.get("order_num"),
|
||||
remark=payload.get("remark"),
|
||||
user_id_param=user.get("user_id"),
|
||||
tenant_no=tenant_no,
|
||||
)
|
||||
return success_response(clean_room_svc._access_log_to_dict(obj), message="更新成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.delete("/clean-room-access-logs/{log_id}")
|
||||
async def delete_access_log(
|
||||
log_id: str,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
clean_room_svc.soft_delete_access_log(db, log_id, tenant_no=tenant_no)
|
||||
return success_response(None, message="删除成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 仓储设施
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class StorageFacilityCreateBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
parent_id: str = Field("0", alias="parentId")
|
||||
node_name: str = Field(..., alias="nodeName")
|
||||
node_type: Optional[str] = Field(None, alias="nodeType")
|
||||
is_leaf: Optional[int] = Field(0, alias="isLeaf")
|
||||
order_num: Optional[int] = Field(0, alias="orderNum")
|
||||
remark: Optional[str] = None
|
||||
|
||||
|
||||
class StorageFacilityUpdateBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
node_name: Optional[str] = Field(None, alias="nodeName")
|
||||
node_type: Optional[str] = Field(None, alias="nodeType")
|
||||
is_leaf: Optional[int] = Field(None, alias="isLeaf")
|
||||
order_num: Optional[int] = Field(None, alias="orderNum")
|
||||
remark: Optional[str] = None
|
||||
|
||||
|
||||
@router.get("/storage-facilities")
|
||||
async def list_storage_facilities(
|
||||
keyword: Optional[str] = None,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
query = db.query(BizStorageFacility).filter(
|
||||
BizStorageFacility.del_flag == 0,
|
||||
BizStorageFacility.tenant_no == tenant_no,
|
||||
)
|
||||
if keyword:
|
||||
query = query.filter(BizStorageFacility.node_name.like(f"%{keyword}%"))
|
||||
query = apply_data_scope(query, BizStorageFacility, user, db, tenant_no)
|
||||
items = query.order_by(
|
||||
BizStorageFacility.order_num.asc(),
|
||||
BizStorageFacility.create_time.asc(),
|
||||
).all()
|
||||
result_list = [storage_facility_svc._row_to_dict(r) for r in items]
|
||||
return success_response(result_list)
|
||||
|
||||
|
||||
@router.post("/storage-facilities")
|
||||
async def create_storage_facility(
|
||||
body: StorageFacilityCreateBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
obj = storage_facility_svc.create_facility(
|
||||
db,
|
||||
parent_id=body.parent_id,
|
||||
node_name=body.node_name,
|
||||
node_type=body.node_type,
|
||||
is_leaf=body.is_leaf,
|
||||
tenant_no=tenant_no,
|
||||
order_num=body.order_num,
|
||||
remark=body.remark,
|
||||
user_id=user.get("user_id"),
|
||||
)
|
||||
return success_response(storage_facility_svc._row_to_dict(obj), message="创建成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.put("/storage-facilities/{node_id}")
|
||||
async def update_storage_facility(
|
||||
node_id: str,
|
||||
body: StorageFacilityUpdateBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
payload: dict[str, Any] = body.model_dump(exclude_unset=True, by_alias=False)
|
||||
obj = storage_facility_svc.update_facility(
|
||||
db,
|
||||
node_id,
|
||||
node_name=payload.get("node_name"),
|
||||
node_type=payload.get("node_type"),
|
||||
is_leaf=payload.get("is_leaf"),
|
||||
order_num=payload.get("order_num"),
|
||||
remark=payload.get("remark"),
|
||||
user_id=user.get("user_id"),
|
||||
tenant_no=tenant_no,
|
||||
)
|
||||
return success_response(storage_facility_svc._row_to_dict(obj), message="更新成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.delete("/storage-facilities/{node_id}")
|
||||
async def delete_storage_facility(
|
||||
node_id: str,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
storage_facility_svc.soft_delete_facility(db, node_id, tenant_no=tenant_no)
|
||||
return success_response(None, message="删除成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 储位
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class StorageSlotCreateBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
facility_node_id: str = Field(..., alias="facilityNodeId")
|
||||
slot_code: Optional[str] = Field(None, alias="slotCode")
|
||||
slot_status: Optional[str] = Field(None, alias="slotStatus")
|
||||
order_num: Optional[int] = Field(0, alias="orderNum")
|
||||
remark: Optional[str] = None
|
||||
|
||||
|
||||
class StorageSlotBatchCreateBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
facility_node_id: str = Field(..., alias="facilityNodeId")
|
||||
rows: int = Field(..., ge=1, le=50)
|
||||
cols: int = Field(..., ge=1, le=50)
|
||||
code_prefix: Optional[str] = Field("", alias="codePrefix")
|
||||
|
||||
|
||||
class StorageSlotUpdateBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
slot_code: Optional[str] = Field(None, alias="slotCode")
|
||||
slot_status: Optional[str] = Field(None, alias="slotStatus")
|
||||
order_num: Optional[int] = Field(None, alias="orderNum")
|
||||
remark: Optional[str] = None
|
||||
|
||||
|
||||
class StorageSlotClearBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
facility_node_id: str = Field(..., alias="facilityNodeId")
|
||||
|
||||
|
||||
class StorageSlotInsertRowBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
facility_node_id: str = Field(..., alias="facilityNodeId")
|
||||
after_row_num: int = Field(..., ge=0, alias="afterRowNum")
|
||||
cols: int = Field(..., ge=1)
|
||||
code_prefix: Optional[str] = Field("", alias="codePrefix")
|
||||
|
||||
|
||||
@router.get("/storage-facility-slots")
|
||||
async def list_storage_slots(
|
||||
facilityNodeId: str = Query(..., alias="facilityNodeId"),
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
query = db.query(BizStorageFacilitySlot).filter(
|
||||
BizStorageFacilitySlot.del_flag == 0,
|
||||
BizStorageFacilitySlot.tenant_no == tenant_no,
|
||||
BizStorageFacilitySlot.facility_node_id == facilityNodeId,
|
||||
)
|
||||
query = apply_data_scope(query, BizStorageFacilitySlot, user, db, tenant_no)
|
||||
items = query.order_by(BizStorageFacilitySlot.order_num.asc(), BizStorageFacilitySlot.create_time.asc()).all()
|
||||
result_list = [storage_facility_svc._slot_to_dict(r) for r in items]
|
||||
return success_response(result_list)
|
||||
|
||||
|
||||
@router.post("/storage-facility-slots/batch")
|
||||
async def batch_create_storage_slots(
|
||||
body: StorageSlotBatchCreateBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
items = storage_facility_svc.batch_create_slots(
|
||||
db,
|
||||
facility_node_id=body.facility_node_id,
|
||||
rows=body.rows,
|
||||
cols=body.cols,
|
||||
code_prefix=body.code_prefix,
|
||||
tenant_no=tenant_no,
|
||||
user_id=user.get("user_id"),
|
||||
)
|
||||
return success_response(items, message=f"批量创建 {len(items)} 个格子成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.post("/storage-facility-slots")
|
||||
async def create_storage_slot(
|
||||
body: StorageSlotCreateBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
obj = storage_facility_svc.create_slot(
|
||||
db,
|
||||
facility_node_id=body.facility_node_id,
|
||||
slot_code=body.slot_code,
|
||||
slot_status=body.slot_status,
|
||||
tenant_no=tenant_no,
|
||||
order_num=body.order_num,
|
||||
remark=body.remark,
|
||||
user_id=user.get("user_id"),
|
||||
)
|
||||
return success_response(storage_facility_svc._slot_to_dict(obj), message="创建成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.put("/storage-facility-slots/{slot_id}")
|
||||
async def update_storage_slot(
|
||||
slot_id: str,
|
||||
body: StorageSlotUpdateBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
payload: dict[str, Any] = body.model_dump(exclude_unset=True, by_alias=False)
|
||||
obj = storage_facility_svc.update_slot(
|
||||
db,
|
||||
slot_id,
|
||||
slot_code=payload.get("slot_code"),
|
||||
slot_status=payload.get("slot_status"),
|
||||
order_num=payload.get("order_num"),
|
||||
remark=payload.get("remark"),
|
||||
user_id=user.get("user_id"),
|
||||
tenant_no=tenant_no,
|
||||
)
|
||||
return success_response(storage_facility_svc._slot_to_dict(obj), message="更新成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.post("/storage-facility-slots/insert-row")
|
||||
async def insert_storage_slot_row(
|
||||
body: StorageSlotInsertRowBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
result = storage_facility_svc.insert_row_and_shift_slots(
|
||||
db,
|
||||
facility_node_id=body.facility_node_id,
|
||||
after_row_num=body.after_row_num,
|
||||
cols=body.cols,
|
||||
code_prefix=body.code_prefix or "",
|
||||
tenant_no=tenant_no,
|
||||
user_id=user.get("user_id"),
|
||||
)
|
||||
return success_response(result, message="新增行成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.post("/storage-facility-slots/clear")
|
||||
async def clear_storage_slots(
|
||||
body: StorageSlotClearBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
cleared_count = storage_facility_svc.clear_slots_by_facility_node(
|
||||
db,
|
||||
facility_node_id=body.facility_node_id,
|
||||
tenant_no=tenant_no,
|
||||
user_id=user.get("user_id"),
|
||||
)
|
||||
return success_response(
|
||||
{"clearedCount": cleared_count},
|
||||
message=f"已清空 {cleared_count} 个格子",
|
||||
)
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.delete("/storage-facility-slots/{slot_id}")
|
||||
async def delete_storage_slot(
|
||||
slot_id: str,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
storage_facility_svc.soft_delete_slot(db, slot_id, tenant_no=tenant_no)
|
||||
return success_response(None, message="删除成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 库位占用记录
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class OccupancyCreateBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
slot_id: str = Field(..., alias="slotId")
|
||||
item_type: str = Field("other", alias="itemType")
|
||||
item_code: str = Field(..., alias="itemCode")
|
||||
item_name: str = Field(..., alias="itemName")
|
||||
item_source: str = Field("manual", alias="itemSource")
|
||||
remark: Optional[str] = None
|
||||
|
||||
|
||||
@router.get("/storage-slot-occupancies")
|
||||
async def list_occupancies(
|
||||
slotId: str = Query(..., alias="slotId"),
|
||||
occupancyStatus: Optional[str] = Query("stored", alias="occupancyStatus"),
|
||||
itemType: Optional[str] = Query(None, alias="itemType"),
|
||||
page: int = Query(1),
|
||||
pageSize: int = Query(20, alias="pageSize"),
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
result = occupancy_svc.list_occupancies(
|
||||
db,
|
||||
slot_id=slotId,
|
||||
occupancy_status=occupancyStatus,
|
||||
item_type=itemType,
|
||||
tenant_no=tenant_no,
|
||||
page=page,
|
||||
page_size=pageSize,
|
||||
)
|
||||
return success_response(result)
|
||||
|
||||
|
||||
@router.get("/storage-slot-occupancies/history")
|
||||
async def list_occupancy_history(
|
||||
slotId: Optional[str] = Query(None, alias="slotId"),
|
||||
facilityNodeId: Optional[str] = Query(None, alias="facilityNodeId"),
|
||||
itemType: Optional[str] = Query(None, alias="itemType"),
|
||||
startDate: Optional[str] = Query(None, alias="startDate"),
|
||||
endDate: Optional[str] = Query(None, alias="endDate"),
|
||||
page: int = Query(1),
|
||||
pageSize: int = Query(20, alias="pageSize"),
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
result = occupancy_svc.list_occupancy_history(
|
||||
db,
|
||||
slot_id=slotId,
|
||||
facility_node_id=facilityNodeId,
|
||||
item_type=itemType,
|
||||
start_date=startDate,
|
||||
end_date=endDate,
|
||||
tenant_no=tenant_no,
|
||||
page=page,
|
||||
page_size=pageSize,
|
||||
)
|
||||
return success_response(result)
|
||||
|
||||
|
||||
@router.post("/storage-slot-occupancies")
|
||||
async def create_occupancy(
|
||||
body: OccupancyCreateBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
item_id = generate_uuid()
|
||||
obj = occupancy_svc.create_occupancy(
|
||||
db,
|
||||
slot_id=body.slot_id,
|
||||
item_type=body.item_type,
|
||||
item_id=item_id,
|
||||
item_code=body.item_code,
|
||||
item_name=body.item_name,
|
||||
item_source=body.item_source,
|
||||
tenant_no=tenant_no,
|
||||
user_id=user.get("user_id"),
|
||||
remark=body.remark,
|
||||
)
|
||||
return success_response(occupancy_svc._row_to_dict(obj), message="入库成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.put("/storage-slot-occupancies/{occupancy_id}/remove")
|
||||
async def remove_occupancy(
|
||||
occupancy_id: str,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
obj = occupancy_svc.remove_occupancy(
|
||||
db,
|
||||
occupancy_id,
|
||||
user_id=user.get("user_id"),
|
||||
)
|
||||
return success_response(occupancy_svc._row_to_dict(obj), message="出库成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 展厅预约
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class ExhibitionAppointmentCreateBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
appointment_no: Optional[str] = Field(None, alias="appointmentNo")
|
||||
visit_org: Optional[str] = Field(None, alias="visitOrg")
|
||||
contact_name: Optional[str] = Field(None, alias="contactName")
|
||||
visit_date: Optional[str] = Field(None, alias="visitDate")
|
||||
visitor_count: Optional[int] = Field(None, alias="visitorCount")
|
||||
reception_user_id: Optional[str] = Field(None, alias="receptionUserId")
|
||||
order_num: Optional[int] = Field(0, alias="orderNum")
|
||||
remark: Optional[str] = None
|
||||
|
||||
|
||||
class ExhibitionAppointmentUpdateBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
visit_org: Optional[str] = Field(None, alias="visitOrg")
|
||||
contact_name: Optional[str] = Field(None, alias="contactName")
|
||||
visit_date: Optional[str] = Field(None, alias="visitDate")
|
||||
visitor_count: Optional[int] = Field(None, alias="visitorCount")
|
||||
reception_user_id: Optional[str] = Field(None, alias="receptionUserId")
|
||||
order_num: Optional[int] = Field(None, alias="orderNum")
|
||||
remark: Optional[str] = None
|
||||
|
||||
|
||||
def _normalize_visit_date_bound(value: str, *, end_of_day: bool = False) -> str:
|
||||
val = (value or "").strip()
|
||||
if len(val) == 10:
|
||||
return f"{val} 23:59:59" if end_of_day else f"{val} 00:00:00"
|
||||
return val
|
||||
|
||||
|
||||
@router.get("/exhibition-appointments")
|
||||
async def list_exhibition_appointments(
|
||||
page: int = Query(1, ge=1),
|
||||
pageSize: int = Query(10, ge=1, le=100, alias="pageSize"),
|
||||
keyword: Optional[str] = None,
|
||||
visitDateStart: Optional[str] = Query(None, alias="visitDateStart"),
|
||||
visitDateEnd: Optional[str] = Query(None, alias="visitDateEnd"),
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
query = db.query(BizExhibitionAppointment).filter(
|
||||
BizExhibitionAppointment.del_flag == 0,
|
||||
BizExhibitionAppointment.tenant_no == tenant_no,
|
||||
)
|
||||
kw = (keyword or "").strip()
|
||||
if kw:
|
||||
like = f"%{kw}%"
|
||||
query = query.filter(
|
||||
or_(
|
||||
BizExhibitionAppointment.appointment_no.like(like),
|
||||
BizExhibitionAppointment.contact_name.like(like),
|
||||
BizExhibitionAppointment.visit_org.like(like),
|
||||
)
|
||||
)
|
||||
if visitDateStart:
|
||||
query = query.filter(
|
||||
BizExhibitionAppointment.visit_date >= _normalize_visit_date_bound(visitDateStart)
|
||||
)
|
||||
if visitDateEnd:
|
||||
query = query.filter(
|
||||
BizExhibitionAppointment.visit_date <= _normalize_visit_date_bound(visitDateEnd, end_of_day=True)
|
||||
)
|
||||
query = apply_data_scope(query, BizExhibitionAppointment, user, db, tenant_no)
|
||||
total = query.count()
|
||||
items = query.order_by(BizExhibitionAppointment.create_time.desc()).offset((page - 1) * pageSize).limit(pageSize).all()
|
||||
result_list = [exhibition_svc._row_to_dict(r) for r in items]
|
||||
tp = exhibition_svc.total_pages(total, pageSize)
|
||||
return success_response({"list": result_list, "total": total, "page": page, "pageSize": pageSize, "totalPages": tp})
|
||||
|
||||
|
||||
@router.post("/exhibition-appointments")
|
||||
async def create_exhibition_appointment(
|
||||
body: ExhibitionAppointmentCreateBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
obj = exhibition_svc.create_exhibition_appointment(
|
||||
db,
|
||||
appointment_no=body.appointment_no,
|
||||
visit_org=body.visit_org,
|
||||
contact_name=body.contact_name,
|
||||
visit_date=body.visit_date,
|
||||
visitor_count=body.visitor_count,
|
||||
reception_user_id=body.reception_user_id,
|
||||
tenant_no=tenant_no,
|
||||
order_num=body.order_num,
|
||||
remark=body.remark,
|
||||
user_id=user.get("user_id"),
|
||||
)
|
||||
return success_response(exhibition_svc._row_to_dict(obj), message="创建成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.put("/exhibition-appointments/{appointment_id}")
|
||||
async def update_exhibition_appointment(
|
||||
appointment_id: str,
|
||||
body: ExhibitionAppointmentUpdateBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
payload: dict[str, Any] = body.model_dump(exclude_unset=True, by_alias=False)
|
||||
obj = exhibition_svc.update_exhibition_appointment(
|
||||
db,
|
||||
appointment_id,
|
||||
visit_org=payload.get("visit_org"),
|
||||
contact_name=payload.get("contact_name"),
|
||||
visit_date=payload.get("visit_date"),
|
||||
visitor_count=payload.get("visitor_count"),
|
||||
reception_user_id=payload.get("reception_user_id"),
|
||||
order_num=payload.get("order_num"),
|
||||
remark=payload.get("remark"),
|
||||
user_id=user.get("user_id"),
|
||||
)
|
||||
return success_response(exhibition_svc._row_to_dict(obj), message="更新成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.delete("/exhibition-appointments/{appointment_id}")
|
||||
async def delete_exhibition_appointment(
|
||||
appointment_id: str,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
exhibition_svc.soft_delete_exhibition_appointment(db, appointment_id)
|
||||
return success_response(None, message="删除成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
@@ -1,203 +0,0 @@
|
||||
"""出库放行审核 API"""
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.core.database import get_db
|
||||
from app.core.menu_guard import require_admin_or_super_admin, require_menu_code
|
||||
from app.core.response import error_response, success_response
|
||||
from app.crud import outbound_release_review as svc
|
||||
from app.models.models import SysUser
|
||||
from app.schemas.outbound_release_review import (
|
||||
OutboundBatchReviewBody,
|
||||
OutboundReviewSubmitBody,
|
||||
)
|
||||
from app.schemas.outbound_release_material import OutboundReleaseMaterialSaveBody
|
||||
from app.crud import outbound_release_material as orm_svc
|
||||
|
||||
router = APIRouter(prefix="/web/admin", tags=["出库放行审核"])
|
||||
|
||||
|
||||
def _get_tenant_no(db: Session, user: dict) -> str:
|
||||
user_id = user.get("user_id")
|
||||
if not user_id:
|
||||
raise PermissionError("用户身份信息缺失")
|
||||
sys_user = db.query(SysUser).filter(SysUser.id == user_id).first()
|
||||
if not sys_user or not sys_user.tenant_no:
|
||||
raise PermissionError("用户租户信息缺失")
|
||||
return sys_user.tenant_no
|
||||
|
||||
|
||||
def _get_current_user_id(user: dict) -> str:
|
||||
user_id = user.get("user_id")
|
||||
if not user_id:
|
||||
raise PermissionError("用户身份信息缺失")
|
||||
return str(user_id)
|
||||
|
||||
|
||||
@router.get("/pilot-release-reviews")
|
||||
async def list_pilot_release_reviews(
|
||||
page: int = Query(1, ge=1),
|
||||
pageSize: int = Query(10, ge=1, le=100),
|
||||
keyword: Optional[str] = None,
|
||||
reviewConclusion: Optional[str] = None,
|
||||
scheduleStatus: Optional[str] = None,
|
||||
qcStatus: Optional[str] = None,
|
||||
bizType: Optional[str] = None,
|
||||
infusionTimeStart: Optional[str] = None,
|
||||
infusionTimeEnd: Optional[str] = None,
|
||||
db: Session = Depends(get_db),
|
||||
user: dict = Depends(require_menu_code("biz:outboundReleaseReview:list")),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
result = svc.list_reviews_paginated(
|
||||
db,
|
||||
tenant_no=tenant_no,
|
||||
keyword=keyword,
|
||||
review_conclusion=reviewConclusion,
|
||||
schedule_status=scheduleStatus,
|
||||
qc_status=qcStatus,
|
||||
biz_type=bizType,
|
||||
infusion_time_start=infusionTimeStart,
|
||||
infusion_time_end=infusionTimeEnd,
|
||||
page=page,
|
||||
page_size=pageSize,
|
||||
user_info=user,
|
||||
)
|
||||
return success_response(result)
|
||||
except PermissionError as e:
|
||||
return error_response(403, str(e))
|
||||
except Exception as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.get("/pilot-release-reviews/{schedule_id}/detail")
|
||||
async def get_pilot_release_review_detail(
|
||||
schedule_id: str,
|
||||
db: Session = Depends(get_db),
|
||||
user: dict = Depends(require_menu_code("biz:outboundReleaseReview:list")),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
detail = svc.get_schedule_detail(db, schedule_id, tenant_no)
|
||||
if not detail:
|
||||
return error_response(404, "输注计划不存在")
|
||||
return success_response(detail)
|
||||
except PermissionError as e:
|
||||
return error_response(403, str(e))
|
||||
except Exception as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.put("/pilot-release-reviews/{schedule_id}/review")
|
||||
async def submit_single_review(
|
||||
schedule_id: str,
|
||||
body: OutboundReviewSubmitBody,
|
||||
db: Session = Depends(get_db),
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
user_id = _get_current_user_id(user)
|
||||
result = svc.review_schedule(
|
||||
db,
|
||||
schedule_id,
|
||||
conclusion=body.reviewConclusion,
|
||||
remark=body.reviewRemark,
|
||||
attachments=body.reviewAttachments,
|
||||
tenant_no=tenant_no,
|
||||
user_id=user_id,
|
||||
)
|
||||
db.commit()
|
||||
return success_response(result)
|
||||
except PermissionError as e:
|
||||
return error_response(403, str(e))
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
except Exception as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.put("/pilot-release-reviews/batch-review")
|
||||
async def batch_review(
|
||||
body: OutboundBatchReviewBody,
|
||||
db: Session = Depends(get_db),
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
user_id = _get_current_user_id(user)
|
||||
result = svc.batch_review(
|
||||
db,
|
||||
body.scheduleIds,
|
||||
conclusion=body.reviewConclusion,
|
||||
remark=body.reviewRemark,
|
||||
attachments=body.reviewAttachments,
|
||||
tenant_no=tenant_no,
|
||||
user_id=user_id,
|
||||
)
|
||||
db.commit()
|
||||
return success_response(result)
|
||||
except PermissionError as e:
|
||||
return error_response(403, str(e))
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
except Exception as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.get("/pilot-release-reviews/{schedule_id}/outbound-materials")
|
||||
async def get_outbound_release_materials(
|
||||
schedule_id: str,
|
||||
db: Session = Depends(get_db),
|
||||
user: dict = Depends(require_menu_code("biz:outboundReleaseReview:list")),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
result = orm_svc.get_outbound_material(db, schedule_id, tenant_no)
|
||||
return success_response(result)
|
||||
except PermissionError as e:
|
||||
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)))
|
||||
|
||||
|
||||
@router.put("/pilot-release-reviews/{schedule_id}/outbound-materials")
|
||||
async def save_outbound_release_materials(
|
||||
schedule_id: str,
|
||||
body: OutboundReleaseMaterialSaveBody,
|
||||
db: Session = Depends(get_db),
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
user_id = _get_current_user_id(user)
|
||||
sys_user = db.query(SysUser).filter(SysUser.id == user_id).first()
|
||||
dept_id = (sys_user.dept_id or "") if sys_user else ""
|
||||
result = orm_svc.save_outbound_material(
|
||||
db,
|
||||
schedule_id,
|
||||
paper_attachments=body.paperAttachments,
|
||||
paper_materials=[p.model_dump(by_alias=True) for p in body.paperMaterials],
|
||||
remark=body.remark,
|
||||
cells=[c.model_dump(by_alias=True) for c in body.cells],
|
||||
qc_materials=[m.model_dump(by_alias=True) for m in body.qcMaterials],
|
||||
tenant_no=tenant_no,
|
||||
user_id=user_id,
|
||||
create_dept_id=dept_id,
|
||||
)
|
||||
db.commit()
|
||||
return success_response(result)
|
||||
except PermissionError as e:
|
||||
return error_response(403, str(e))
|
||||
except Exception as e:
|
||||
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)))
|
||||
@@ -1,804 +0,0 @@
|
||||
"""中试服务申请单管理 API(申请单、患者信息、输注方案、输注计划、出库联动)"""
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
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.crud import pilot_application
|
||||
from app.models.models import SysUser
|
||||
|
||||
router = APIRouter(prefix="/web/admin", tags=["中试服务申请单管理"])
|
||||
|
||||
|
||||
def _get_tenant_no(db: Session, user: dict) -> str:
|
||||
user_id = user.get("user_id")
|
||||
if not user_id:
|
||||
raise PermissionError("用户身份信息缺失,无法确定租户")
|
||||
sys_user = db.query(SysUser).filter(SysUser.id == user_id).first()
|
||||
if not sys_user or not sys_user.tenant_no:
|
||||
raise PermissionError("用户租户信息缺失")
|
||||
return sys_user.tenant_no
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Pydantic Schemas
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class IdBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
id: str
|
||||
|
||||
|
||||
class PlanIdBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
plan_id: str = Field(..., alias="infusionPlanId")
|
||||
|
||||
|
||||
class ApplicationCreateBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
channel_service_order_id: Optional[str] = Field(None, alias="channelServiceOrderId")
|
||||
remark: Optional[str] = None
|
||||
biz_type: Optional[str] = Field(None, alias="bizType")
|
||||
|
||||
|
||||
class ApplicationUpdateBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
id: str
|
||||
remark: Optional[str] = None
|
||||
|
||||
|
||||
class PatientSaveBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
application_id: str = Field(..., alias="pilotApplicationId")
|
||||
customer_id: Optional[str] = Field(None, alias="customerId")
|
||||
patient_name: str = Field(..., alias="patientName")
|
||||
sex: Optional[str] = None
|
||||
age: Optional[int] = None
|
||||
id_card_no: Optional[str] = Field(None, alias="idCardNo")
|
||||
phone_no: Optional[str] = Field(None, alias="phoneNo")
|
||||
emergency_contact: Optional[str] = Field(None, alias="emergencyContact")
|
||||
emergency_phone: Optional[str] = Field(None, alias="emergencyPhone")
|
||||
clinical_diagnosis: Optional[str] = Field(None, alias="clinicalDiagnosis")
|
||||
diagnosis_attachments: Optional[str] = Field(None, alias="diagnosisAttachments")
|
||||
need_checkup: int = Field(1, alias="needCheckup")
|
||||
|
||||
|
||||
class InfusionPlanCreateBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
pilot_application_id: str = Field(..., alias="pilotApplicationId")
|
||||
cell_type: str = Field(..., alias="cellType")
|
||||
spec_text: Optional[str] = Field(None, alias="specText")
|
||||
total_course_count: int = Field(..., alias="totalCourseCount")
|
||||
course_interval: Optional[str] = Field(None, alias="courseInterval")
|
||||
infusion_route: Optional[str] = Field(None, alias="infusionRoute")
|
||||
infusion_start_date: Optional[str] = Field(None, alias="infusionStartDate")
|
||||
|
||||
|
||||
class InfusionPlanUpdateBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
id: str
|
||||
cell_type: Optional[str] = Field(None, alias="cellType")
|
||||
spec_text: Optional[str] = Field(None, alias="specText")
|
||||
total_course_count: Optional[int] = Field(None, alias="totalCourseCount")
|
||||
course_interval: Optional[str] = Field(None, alias="courseInterval")
|
||||
infusion_route: Optional[str] = Field(None, alias="infusionRoute")
|
||||
infusion_start_date: Optional[str] = Field(None, alias="infusionStartDate")
|
||||
|
||||
|
||||
class InfusionScheduleUpdateBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
id: str
|
||||
infusion_time: Optional[str] = Field(None, alias="infusionTime")
|
||||
remark: Optional[str] = None
|
||||
attachments: Optional[str] = None
|
||||
|
||||
|
||||
class ScheduleCreateBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
plan_id: str = Field(..., alias="infusionPlanId")
|
||||
infusion_time: Optional[str] = Field(None, alias="infusionTime")
|
||||
remark: Optional[str] = None
|
||||
amount: Optional[float] = None
|
||||
|
||||
|
||||
# --- 复合保存 Schema(参考采集协议单一次性保存模式)---
|
||||
|
||||
|
||||
class PatientNestedBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
customer_id: Optional[str] = Field(None, alias="customerId")
|
||||
patient_name: Optional[str] = Field(None, alias="patientName")
|
||||
sex: Optional[str] = None
|
||||
age: Optional[int] = None
|
||||
id_card_no: Optional[str] = Field(None, alias="idCardNo")
|
||||
phone_no: Optional[str] = Field(None, alias="phoneNo")
|
||||
emergency_contact: Optional[str] = Field(None, alias="emergencyContact")
|
||||
emergency_phone: Optional[str] = Field(None, alias="emergencyPhone")
|
||||
clinical_diagnosis: Optional[str] = Field(None, alias="clinicalDiagnosis")
|
||||
diagnosis_attachments: Optional[str] = Field(None, alias="diagnosisAttachments")
|
||||
need_checkup: int = Field(1, alias="needCheckup")
|
||||
|
||||
|
||||
class ScheduleProductNestedBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
id: Optional[str] = None
|
||||
price_id: Optional[str] = Field(None, alias="priceId")
|
||||
project_code: Optional[str] = Field(None, alias="projectCode")
|
||||
project_name: Optional[str] = Field(None, alias="projectName")
|
||||
cell_type_name: Optional[str] = Field(None, alias="cellTypeName")
|
||||
spec_text: Optional[str] = Field(None, alias="specText")
|
||||
agreement_price: Optional[float] = Field(None, alias="agreementPrice")
|
||||
actual_price: Optional[float] = Field(None, alias="actualPrice")
|
||||
quantity: Optional[int] = 1
|
||||
status: Optional[str] = None
|
||||
remark: Optional[str] = None
|
||||
|
||||
|
||||
class InfusionScheduleNestedBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
id: Optional[str] = None
|
||||
sort_no: Optional[int] = Field(None, alias="sortNo")
|
||||
infusion_time: Optional[str] = Field(None, alias="infusionTime")
|
||||
infusion_location: Optional[str] = Field(None, alias="infusionLocation")
|
||||
infusion_method: Optional[str] = Field(None, alias="infusionMethod")
|
||||
amount: Optional[float] = None
|
||||
cell_products: Optional[list[ScheduleProductNestedBody]] = Field(None, alias="cellProducts")
|
||||
|
||||
|
||||
class InfusionPlanNestedBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
id: Optional[str] = None
|
||||
cell_type: Optional[str] = Field(None, alias="cellType")
|
||||
spec_text: Optional[str] = Field(None, alias="specText")
|
||||
total_course_count: Optional[int] = Field(None, alias="totalCourseCount")
|
||||
course_interval: Optional[str] = Field(None, alias="courseInterval")
|
||||
infusion_route: Optional[str] = Field(None, alias="infusionRoute")
|
||||
infusion_start_date: Optional[str] = Field(None, alias="infusionStartDate")
|
||||
channel_agreement_id: Optional[str] = Field(None, alias="channelAgreementId")
|
||||
|
||||
|
||||
class ApplicationSaveBody(BaseModel):
|
||||
"""一揽子保存:申请单 + 患者信息 + 输注方案 + 输注计划(含细胞产品)"""
|
||||
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
id: Optional[str] = None
|
||||
application_name: Optional[str] = Field(None, alias="applicationName")
|
||||
channel_service_order_id: Optional[str] = Field(None, alias="channelServiceOrderId")
|
||||
channel_id: Optional[str] = Field(None, alias="channelId")
|
||||
biz_type: Optional[str] = Field(None, alias="bizType")
|
||||
remark: Optional[str] = None
|
||||
patient: Optional[PatientNestedBody] = None
|
||||
infusion_plan: Optional[InfusionPlanNestedBody] = Field(None, alias="infusionPlan")
|
||||
infusion_schedules: Optional[list[InfusionScheduleNestedBody]] = Field(
|
||||
None, alias="infusionSchedules"
|
||||
)
|
||||
infusion_plans: Optional[list[InfusionPlanNestedBody]] = Field(None, alias="infusionPlans")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 1. 申请单 CRUD + 状态变更
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@router.get("/pilot-application/list")
|
||||
async def api_list_applications(
|
||||
page: int = Query(1, ge=1),
|
||||
pageSize: int = Query(10, ge=1, le=100, alias="pageSize"),
|
||||
keyword: Optional[str] = Query(None, alias="keyword"),
|
||||
channelId: Optional[str] = Query(None, alias="channelId"),
|
||||
applicationStatus: Optional[str] = Query(None, alias="applicationStatus"),
|
||||
channelServiceOrderId: Optional[str] = Query(None, alias="channelServiceOrderId"),
|
||||
bizType: Optional[str] = Query(None, alias="bizType"),
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
result = pilot_application.list_applications(
|
||||
db,
|
||||
tenant_no=tenant_no,
|
||||
page=page,
|
||||
page_size=pageSize,
|
||||
channel_id=channelId,
|
||||
application_status=applicationStatus,
|
||||
channel_service_order_id=channelServiceOrderId,
|
||||
keyword=keyword,
|
||||
biz_type=bizType,
|
||||
)
|
||||
return success_response(result)
|
||||
|
||||
|
||||
@router.get("/pilot-application/detail")
|
||||
async def api_get_application(
|
||||
id: str = Query(...),
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
result = pilot_application.get_application(db, app_id=id, tenant_no=tenant_no)
|
||||
if result is None:
|
||||
return error_response(404, "申请单不存在")
|
||||
return success_response(result)
|
||||
|
||||
|
||||
@router.post("/pilot-application/create")
|
||||
async def api_create_application(
|
||||
body: ApplicationCreateBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
data = {
|
||||
"channelServiceOrderId": body.channel_service_order_id or "",
|
||||
"remark": body.remark,
|
||||
"bizType": body.biz_type or "pilot_service",
|
||||
}
|
||||
result = pilot_application.create_application(
|
||||
db,
|
||||
data=data,
|
||||
tenant_no=tenant_no,
|
||||
user_id=user.get("user_id"),
|
||||
dept_id=user.get("region_id", ""),
|
||||
)
|
||||
return success_response(result, message="创建成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.put("/pilot-application/update")
|
||||
async def api_update_application(
|
||||
body: ApplicationUpdateBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
data = {}
|
||||
if body.remark is not None:
|
||||
data["remark"] = body.remark
|
||||
result = pilot_application.update_application(
|
||||
db, app_id=body.id, data=data, tenant_no=tenant_no
|
||||
)
|
||||
return success_response(result, message="更新成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.post("/pilot-application/save")
|
||||
async def api_save_application(
|
||||
body: ApplicationSaveBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
user_id = user.get("user_id")
|
||||
dept_id = user.get("region_id", "")
|
||||
is_edit = bool(body.id)
|
||||
|
||||
biz_type = body.biz_type or "pilot_service"
|
||||
app_data: dict = {
|
||||
"channelServiceOrderId": body.channel_service_order_id or "",
|
||||
"channelId": body.channel_id or "",
|
||||
"bizType": biz_type,
|
||||
"remark": body.remark,
|
||||
}
|
||||
if body.application_name is not None:
|
||||
app_data["applicationName"] = body.application_name
|
||||
|
||||
if not is_edit and biz_type != "clinical_application" and not app_data["channelServiceOrderId"]:
|
||||
return error_response(400, "请选择渠道服务订单")
|
||||
|
||||
if not is_edit and biz_type == "clinical_application" and not app_data["channelId"]:
|
||||
return error_response(400, "请选择渠道")
|
||||
|
||||
if is_edit:
|
||||
app_result = pilot_application.update_application(
|
||||
db,
|
||||
app_id=body.id,
|
||||
data=app_data,
|
||||
tenant_no=tenant_no,
|
||||
)
|
||||
app_id = body.id
|
||||
else:
|
||||
app_result = pilot_application.create_application(
|
||||
db,
|
||||
data=app_data,
|
||||
tenant_no=tenant_no,
|
||||
user_id=user_id,
|
||||
dept_id=dept_id,
|
||||
)
|
||||
app_id = app_result.get("id")
|
||||
if not app_id:
|
||||
return error_response(500, "创建申请单失败,未获取到ID")
|
||||
|
||||
if body.patient:
|
||||
pilot_application.save_patient(
|
||||
db,
|
||||
app_id=app_id,
|
||||
data=body.patient.model_dump(by_alias=True),
|
||||
tenant_no=tenant_no,
|
||||
user_id=user_id,
|
||||
dept_id=dept_id,
|
||||
)
|
||||
|
||||
if body.infusion_plan is not None or body.infusion_schedules:
|
||||
plan_dict = (
|
||||
body.infusion_plan.model_dump(by_alias=True) if body.infusion_plan else {}
|
||||
)
|
||||
schedules = [
|
||||
s.model_dump(by_alias=True) for s in (body.infusion_schedules or [])
|
||||
]
|
||||
if is_edit:
|
||||
pilot_application.upsert_application_infusion(
|
||||
db,
|
||||
app_id=app_id,
|
||||
plan_data=plan_dict,
|
||||
schedules_data=schedules,
|
||||
tenant_no=tenant_no,
|
||||
user_id=user_id,
|
||||
dept_id=dept_id,
|
||||
)
|
||||
else:
|
||||
pilot_application.save_application_infusion(
|
||||
db,
|
||||
app_id=app_id,
|
||||
plan_data=plan_dict,
|
||||
schedules_data=schedules,
|
||||
tenant_no=tenant_no,
|
||||
user_id=user_id,
|
||||
dept_id=dept_id,
|
||||
replace_existing=False,
|
||||
)
|
||||
elif body.infusion_plans:
|
||||
for plan_data in body.infusion_plans:
|
||||
plan_result = pilot_application.create_infusion_plan(
|
||||
db,
|
||||
app_id=app_id,
|
||||
data=plan_data.model_dump(by_alias=True),
|
||||
tenant_no=tenant_no,
|
||||
user_id=user_id,
|
||||
dept_id=dept_id,
|
||||
)
|
||||
plan_id = plan_result.get("id")
|
||||
if plan_id and (plan_data.total_course_count or 0) > 0:
|
||||
pilot_application.auto_generate_schedules(
|
||||
db,
|
||||
plan_id=plan_id,
|
||||
tenant_no=tenant_no,
|
||||
user_id=user_id,
|
||||
dept_id=dept_id,
|
||||
)
|
||||
|
||||
app_result = pilot_application.get_application(db, app_id=app_id, tenant_no=tenant_no)
|
||||
|
||||
return success_response(app_result, message="保存成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
except Exception as e:
|
||||
return error_response(500, str(e))
|
||||
|
||||
|
||||
@router.delete("/pilot-application/delete")
|
||||
async def api_delete_application(
|
||||
body: IdBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
pilot_application.soft_delete_application(db, app_id=body.id, tenant_no=tenant_no)
|
||||
return success_response(None, message="删除成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.post("/pilot-application/start")
|
||||
async def api_start_application(
|
||||
body: IdBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
result = pilot_application.start_application(
|
||||
db, app_id=body.id, tenant_no=tenant_no, user_id=user.get("user_id")
|
||||
)
|
||||
return success_response(result, message="操作成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.post("/pilot-application/complete")
|
||||
async def api_complete_application(
|
||||
body: IdBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
result = pilot_application.complete_application(
|
||||
db, app_id=body.id, tenant_no=tenant_no, user_id=user.get("user_id")
|
||||
)
|
||||
return success_response(result, message="操作成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.post("/pilot-application/void")
|
||||
async def api_void_application(
|
||||
body: IdBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
result = pilot_application.void_application(
|
||||
db, app_id=body.id, tenant_no=tenant_no, user_id=user.get("user_id")
|
||||
)
|
||||
return success_response(result, message="操作成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 2. 患者信息
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@router.get("/pilot-patient/detail")
|
||||
async def api_get_patient(
|
||||
application_id: str = Query(..., alias="pilotApplicationId"),
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
result = pilot_application.get_patient_by_application(
|
||||
db, app_id=application_id, tenant_no=tenant_no
|
||||
)
|
||||
if result is None:
|
||||
return success_response(None)
|
||||
return success_response(result)
|
||||
|
||||
|
||||
@router.post("/pilot-patient/save")
|
||||
async def api_save_patient(
|
||||
body: PatientSaveBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
data = {
|
||||
"customerId": body.customer_id,
|
||||
"patientName": body.patient_name,
|
||||
"sex": body.sex,
|
||||
"age": body.age,
|
||||
"idCardNo": body.id_card_no,
|
||||
"phoneNo": body.phone_no,
|
||||
"emergencyContact": body.emergency_contact,
|
||||
"emergencyPhone": body.emergency_phone,
|
||||
"clinicalDiagnosis": body.clinical_diagnosis,
|
||||
"diagnosisAttachments": body.diagnosis_attachments,
|
||||
"needCheckup": body.need_checkup,
|
||||
}
|
||||
result = pilot_application.save_patient(
|
||||
db,
|
||||
app_id=body.application_id,
|
||||
data=data,
|
||||
tenant_no=tenant_no,
|
||||
user_id=user.get("user_id"),
|
||||
dept_id=user.get("region_id", ""),
|
||||
)
|
||||
return success_response(result, message="保存成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 3. 输注方案
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@router.get("/pilot-infusion-plan/list")
|
||||
async def api_list_plans(
|
||||
application_id: str = Query(..., alias="pilotApplicationId"),
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
result = pilot_application.list_infusion_plans(
|
||||
db, app_id=application_id, tenant_no=tenant_no
|
||||
)
|
||||
return success_response(result)
|
||||
|
||||
|
||||
@router.post("/pilot-infusion-plan/create")
|
||||
async def api_create_plan(
|
||||
body: InfusionPlanCreateBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
data = {
|
||||
"cellType": body.cell_type,
|
||||
"specText": body.spec_text,
|
||||
"totalCourseCount": body.total_course_count,
|
||||
"courseInterval": body.course_interval,
|
||||
"infusionRoute": body.infusion_route,
|
||||
"infusionStartDate": body.infusion_start_date,
|
||||
}
|
||||
result = pilot_application.create_infusion_plan(
|
||||
db,
|
||||
app_id=body.pilot_application_id,
|
||||
data=data,
|
||||
tenant_no=tenant_no,
|
||||
user_id=user.get("user_id"),
|
||||
dept_id=user.get("region_id", ""),
|
||||
)
|
||||
return success_response(result, message="创建成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.put("/pilot-infusion-plan/update")
|
||||
async def api_update_plan(
|
||||
body: InfusionPlanUpdateBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
data = {}
|
||||
if body.cell_type is not None:
|
||||
data["cellType"] = body.cell_type
|
||||
if body.spec_text is not None:
|
||||
data["specText"] = body.spec_text
|
||||
if body.total_course_count is not None:
|
||||
data["totalCourseCount"] = body.total_course_count
|
||||
if body.course_interval is not None:
|
||||
data["courseInterval"] = body.course_interval
|
||||
if body.infusion_route is not None:
|
||||
data["infusionRoute"] = body.infusion_route
|
||||
if body.infusion_start_date is not None:
|
||||
data["infusionStartDate"] = body.infusion_start_date
|
||||
result = pilot_application.update_infusion_plan(
|
||||
db, plan_id=body.id, data=data, tenant_no=tenant_no
|
||||
)
|
||||
return success_response(result, message="更新成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.delete("/pilot-infusion-plan/delete")
|
||||
async def api_delete_plan(
|
||||
body: IdBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
pilot_application.soft_delete_infusion_plan(
|
||||
db, plan_id=body.id, tenant_no=tenant_no
|
||||
)
|
||||
return success_response(None, message="删除成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 4. 输注计划
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@router.get("/pilot-infusion-schedule/list")
|
||||
async def api_list_schedules(
|
||||
plan_id: str = Query(..., alias="infusionPlanId"),
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
result = pilot_application.list_schedules_by_plan(
|
||||
db, plan_id=plan_id, tenant_no=tenant_no
|
||||
)
|
||||
return success_response(result)
|
||||
|
||||
|
||||
@router.post("/pilot-infusion-schedule/auto-generate")
|
||||
async def api_auto_generate(
|
||||
body: PlanIdBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
result = pilot_application.auto_generate_schedules(
|
||||
db,
|
||||
plan_id=body.plan_id,
|
||||
tenant_no=tenant_no,
|
||||
user_id=user.get("user_id"),
|
||||
dept_id=user.get("region_id", ""),
|
||||
)
|
||||
return success_response(result, message="生成成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.post("/pilot-infusion-schedule/create")
|
||||
async def api_create_schedule(
|
||||
body: ScheduleCreateBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
data = {
|
||||
"infusionTime": body.infusion_time,
|
||||
"remark": body.remark,
|
||||
"amount": body.amount,
|
||||
}
|
||||
result = pilot_application.create_schedule(
|
||||
db,
|
||||
plan_id=body.plan_id,
|
||||
data=data,
|
||||
tenant_no=tenant_no,
|
||||
user_id=user.get("user_id"),
|
||||
dept_id=user.get("region_id", ""),
|
||||
)
|
||||
return success_response(result, message="创建成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.put("/pilot-infusion-schedule/update")
|
||||
async def api_update_schedule(
|
||||
body: InfusionScheduleUpdateBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
data = {}
|
||||
if body.infusion_time is not None:
|
||||
data["infusionTime"] = body.infusion_time
|
||||
if body.remark is not None:
|
||||
data["remark"] = body.remark
|
||||
if body.attachments is not None:
|
||||
data["attachments"] = body.attachments
|
||||
result = pilot_application.update_schedule(
|
||||
db, schedule_id=body.id, data=data, tenant_no=tenant_no
|
||||
)
|
||||
return success_response(result, message="更新成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.delete("/pilot-infusion-schedule/delete")
|
||||
async def api_delete_schedule(
|
||||
body: IdBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
pilot_application.soft_delete_schedule(
|
||||
db, schedule_id=body.id, tenant_no=tenant_no
|
||||
)
|
||||
return success_response(None, message="删除成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.post("/pilot-infusion-schedule/mark-complete")
|
||||
async def api_mark_complete(
|
||||
body: IdBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
result = pilot_application.mark_schedule_complete(
|
||||
db, schedule_id=body.id, tenant_no=tenant_no, user_id=user.get("user_id")
|
||||
)
|
||||
return success_response(result, message="操作成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 出库生产工单 / 出库质检工单 联动
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class ScheduleIdBody(BaseModel):
|
||||
scheduleId: str
|
||||
|
||||
|
||||
@router.post("/pilot-infusion-schedule/create-production-work-order")
|
||||
async def api_create_outbound_production(
|
||||
body: ScheduleIdBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
from app.crud import production_work_order as pwo_svc
|
||||
|
||||
from app.crud.qc_work_order import resolve_outbound_biz_type_for_schedule
|
||||
|
||||
outbound_biz_type = resolve_outbound_biz_type_for_schedule(
|
||||
db, body.scheduleId, tenant_no
|
||||
)
|
||||
wo = pwo_svc.create_outbound_production_work_order(
|
||||
db,
|
||||
schedule_id=body.scheduleId,
|
||||
tenant_no=tenant_no,
|
||||
user_id=user.get("user_id"),
|
||||
create_dept_id=user.get("dept_id", ""),
|
||||
biz_type=outbound_biz_type,
|
||||
)
|
||||
db.commit()
|
||||
db.refresh(wo)
|
||||
return success_response(pwo_svc._wo_to_dict(wo), message="创建出库生产工单成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
except Exception as e:
|
||||
db.rollback()
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
class OutboundQcBody(BaseModel):
|
||||
scheduleId: str
|
||||
cellProductId: str = ""
|
||||
|
||||
|
||||
@router.post("/pilot-infusion-schedule/create-qc-work-order")
|
||||
async def api_create_outbound_qc(
|
||||
body: OutboundQcBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
from app.crud import qc_work_order as qc_svc
|
||||
|
||||
from app.crud.qc_work_order import resolve_outbound_biz_type_for_schedule
|
||||
|
||||
outbound_biz_type = resolve_outbound_biz_type_for_schedule(
|
||||
db, body.scheduleId, tenant_no
|
||||
)
|
||||
wo = qc_svc.create_outbound_qc_work_order(
|
||||
db,
|
||||
schedule_id=body.scheduleId,
|
||||
cell_product_id=body.cellProductId,
|
||||
tenant_no=tenant_no,
|
||||
user_id=user.get("user_id"),
|
||||
create_dept_id=user.get("dept_id", ""),
|
||||
biz_type=outbound_biz_type,
|
||||
)
|
||||
return success_response(qc_svc._wo_to_dict(wo), message="创建出库质检工单成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
except Exception as e:
|
||||
db.rollback()
|
||||
return error_response(400, str(e))
|
||||
@@ -1,419 +0,0 @@
|
||||
"""中试服务体检管理 API(体检信息、预约项目、实际项目)"""
|
||||
from typing import List, Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
from pydantic import AliasChoices, BaseModel, ConfigDict, Field
|
||||
from starlette.requests import Request
|
||||
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.crud import pilot_checkup
|
||||
from app.models.models import SysUser
|
||||
|
||||
router = APIRouter(prefix="/web/admin", tags=["中试服务体检管理"])
|
||||
|
||||
|
||||
def _get_tenant_no(db: Session, user: dict) -> str:
|
||||
user_id = user.get("user_id")
|
||||
if not user_id:
|
||||
raise PermissionError("用户身份信息缺失,无法确定租户")
|
||||
sys_user = db.query(SysUser).filter(SysUser.id == user_id).first()
|
||||
if not sys_user or not sys_user.tenant_no:
|
||||
raise PermissionError("用户租户信息缺失")
|
||||
return sys_user.tenant_no
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Pydantic Schemas
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class IdBody(BaseModel):
|
||||
id: str
|
||||
|
||||
|
||||
class CheckupSaveBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
application_id: Optional[str] = Field(
|
||||
None, validation_alias=AliasChoices("applicationId", "application_id")
|
||||
)
|
||||
checkup_id: Optional[str] = Field(
|
||||
None, validation_alias=AliasChoices("checkupId", "checkup_id")
|
||||
)
|
||||
patient_id: Optional[str] = Field(
|
||||
None, validation_alias=AliasChoices("patientId", "patient_id")
|
||||
)
|
||||
checkup_institution_id: Optional[str] = Field(
|
||||
None, validation_alias=AliasChoices("checkupInstitutionId", "checkup_institution_id")
|
||||
)
|
||||
reserve_time: Optional[str] = Field(
|
||||
None, validation_alias=AliasChoices("reserveTime", "reserve_time")
|
||||
)
|
||||
reserve_fee: Optional[float] = Field(
|
||||
None, validation_alias=AliasChoices("reserveFee", "reserve_fee")
|
||||
)
|
||||
actual_checkup_time: Optional[str] = Field(
|
||||
None, validation_alias=AliasChoices("actualCheckupTime", "actual_checkup_time")
|
||||
)
|
||||
actual_checkup_fee: Optional[float] = Field(
|
||||
None, validation_alias=AliasChoices("actualCheckupFee", "actual_checkup_fee")
|
||||
)
|
||||
checkup_remark: Optional[str] = Field(
|
||||
None, validation_alias=AliasChoices("checkupRemark", "checkup_remark")
|
||||
)
|
||||
report_attachments: Optional[str] = Field(
|
||||
None, validation_alias=AliasChoices("reportAttachments", "report_attachments")
|
||||
)
|
||||
|
||||
|
||||
class CheckupItemBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
project_name: str = Field(..., validation_alias=AliasChoices("projectName", "project_name"))
|
||||
project_fee: Optional[float] = Field(
|
||||
None, validation_alias=AliasChoices("projectFee", "project_fee")
|
||||
)
|
||||
|
||||
|
||||
class CheckupItemsSaveBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
pilot_checkup_id: str = Field(
|
||||
..., validation_alias=AliasChoices("pilotCheckupId", "pilot_checkup_id")
|
||||
)
|
||||
items: List[CheckupItemBody]
|
||||
|
||||
|
||||
class BatchCheckupSaveBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
patient_ids: List[str] = Field(..., validation_alias=AliasChoices("patientIds", "patient_ids"))
|
||||
checkup_institution_id: Optional[str] = Field(
|
||||
None, validation_alias=AliasChoices("checkupInstitutionId", "checkup_institution_id")
|
||||
)
|
||||
reserve_time: Optional[str] = Field(
|
||||
None, validation_alias=AliasChoices("reserveTime", "reserve_time")
|
||||
)
|
||||
reserve_items: Optional[List[CheckupItemBody]] = Field(
|
||||
None, validation_alias=AliasChoices("reserveItems", "reserve_items")
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 1. 体检信息 CRUD + 状态变更
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@router.get("/pilot-checkup/detail")
|
||||
async def api_get_checkup_detail(
|
||||
application_id: Optional[str] = Query(None, alias="applicationId"),
|
||||
checkup_id: Optional[str] = Query(None, alias="checkupId"),
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
if checkup_id:
|
||||
result = pilot_checkup.get_checkup_by_id(
|
||||
db, checkup_id=checkup_id, tenant_no=tenant_no
|
||||
)
|
||||
elif application_id:
|
||||
result = pilot_checkup.get_checkup_by_application(
|
||||
db, application_id=application_id, tenant_no=tenant_no
|
||||
)
|
||||
else:
|
||||
return error_response(400, "请提供 application_id 或 checkupId")
|
||||
if result is None:
|
||||
return success_response(None)
|
||||
return success_response(result)
|
||||
|
||||
|
||||
@router.post("/pilot-checkup/save")
|
||||
async def api_save_checkup(
|
||||
request: Request,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
payload = await request.json()
|
||||
if not isinstance(payload, dict):
|
||||
return error_response(400, "请求体格式错误")
|
||||
body = CheckupSaveBody.model_validate(payload)
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
data = {
|
||||
"checkupInstitutionId": body.checkup_institution_id,
|
||||
"pilotPatientId": body.patient_id,
|
||||
"reserveTime": body.reserve_time,
|
||||
"reserveFee": body.reserve_fee,
|
||||
"actualCheckupTime": body.actual_checkup_time,
|
||||
"actualCheckupFee": body.actual_checkup_fee,
|
||||
"checkupRemark": body.checkup_remark,
|
||||
"reportAttachments": body.report_attachments,
|
||||
}
|
||||
|
||||
if body.checkup_id:
|
||||
result = pilot_checkup.update_checkup(
|
||||
db, checkup_id=body.checkup_id, data=data, tenant_no=tenant_no
|
||||
)
|
||||
return success_response(result, message="更新成功")
|
||||
|
||||
if not body.application_id:
|
||||
return error_response(400, "请提供 application_id 或 checkup_id")
|
||||
|
||||
existing = pilot_checkup.get_checkup_by_application(
|
||||
db, application_id=body.application_id, tenant_no=tenant_no
|
||||
)
|
||||
if existing:
|
||||
result = pilot_checkup.update_checkup(
|
||||
db, checkup_id=existing["id"], data=data, tenant_no=tenant_no
|
||||
)
|
||||
return success_response(result, message="更新成功")
|
||||
else:
|
||||
result = pilot_checkup.create_checkup(
|
||||
db,
|
||||
application_id=body.application_id,
|
||||
data=data,
|
||||
tenant_no=tenant_no,
|
||||
user_id=user.get("user_id"),
|
||||
)
|
||||
return success_response(result, message="创建成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.delete("/pilot-checkup/delete")
|
||||
async def api_delete_checkup(
|
||||
body: IdBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
pilot_checkup.soft_delete_checkup(db, checkup_id=body.id, tenant_no=tenant_no)
|
||||
return success_response(None, message="删除成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.post("/pilot-checkup/mark-checked")
|
||||
async def api_mark_checked(
|
||||
body: IdBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
result = pilot_checkup.mark_checkup_checked(
|
||||
db, checkup_id=body.id, tenant_no=tenant_no, user_id=user.get("user_id")
|
||||
)
|
||||
return success_response(result, message="操作成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.post("/pilot-checkup/settle-fee")
|
||||
async def api_settle_fee(
|
||||
body: IdBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
result = pilot_checkup.settle_checkup_fee(
|
||||
db, checkup_id=body.id, tenant_no=tenant_no, user_id=user.get("user_id")
|
||||
)
|
||||
return success_response(result, message="结算成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 2. 预约项目
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@router.get("/pilot-checkup/reserve-items")
|
||||
async def api_list_reserve_items(
|
||||
pilot_checkup_id: str = Query(..., alias="pilotCheckupId"),
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
result = pilot_checkup.list_reserve_items(
|
||||
db, checkup_id=pilot_checkup_id, tenant_no=tenant_no
|
||||
)
|
||||
return success_response(result)
|
||||
|
||||
|
||||
@router.post("/pilot-checkup/reserve-items/save")
|
||||
async def api_save_reserve_items(
|
||||
body: CheckupItemsSaveBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
items_json = [item.model_dump(by_alias=False) for item in body.items]
|
||||
result = pilot_checkup.save_reserve_items(
|
||||
db,
|
||||
checkup_id=body.pilot_checkup_id,
|
||||
items_json=items_json,
|
||||
tenant_no=tenant_no,
|
||||
user_id=user.get("user_id"),
|
||||
)
|
||||
return success_response(result, message="保存成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.delete("/pilot-checkup/reserve-item/delete")
|
||||
async def api_delete_reserve_item(
|
||||
body: IdBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
pilot_checkup.delete_reserve_item(db, item_id=body.id, tenant_no=tenant_no)
|
||||
return success_response(None, message="删除成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 3. 实际项目
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@router.get("/pilot-checkup/actual-items")
|
||||
async def api_list_actual_items(
|
||||
pilot_checkup_id: str = Query(..., alias="pilotCheckupId"),
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
result = pilot_checkup.list_actual_items(
|
||||
db, checkup_id=pilot_checkup_id, tenant_no=tenant_no
|
||||
)
|
||||
return success_response(result)
|
||||
|
||||
|
||||
@router.post("/pilot-checkup/actual-items/save")
|
||||
async def api_save_actual_items(
|
||||
body: CheckupItemsSaveBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
items_json = [item.model_dump(by_alias=False) for item in body.items]
|
||||
result = pilot_checkup.save_actual_items(
|
||||
db,
|
||||
checkup_id=body.pilot_checkup_id,
|
||||
items_json=items_json,
|
||||
tenant_no=tenant_no,
|
||||
user_id=user.get("user_id"),
|
||||
)
|
||||
return success_response(result, message="保存成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.delete("/pilot-checkup/actual-item/delete")
|
||||
async def api_delete_actual_item(
|
||||
body: IdBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
pilot_checkup.delete_actual_item(db, item_id=body.id, tenant_no=tenant_no)
|
||||
return success_response(None, message="删除成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 4. 体检管理列表、待体检患者、批量创建
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@router.get("/pilot-checkup/list")
|
||||
async def api_list_checkups(
|
||||
page: int = Query(1, ge=1),
|
||||
pageSize: int = Query(10, ge=1, le=100, alias="pageSize"),
|
||||
checkupStatus: Optional[str] = Query(None, alias="checkupStatus"),
|
||||
feeStatus: Optional[str] = Query(None, alias="feeStatus"),
|
||||
checkupInstitutionId: Optional[str] = Query(None, alias="checkupInstitutionId"),
|
||||
keyword: Optional[str] = Query(None, alias="keyword"),
|
||||
applicationNo: Optional[str] = Query(None, alias="applicationNo"),
|
||||
patientName: Optional[str] = Query(None, alias="patientName"),
|
||||
channelId: Optional[str] = Query(None, alias="channelId"),
|
||||
bizType: Optional[str] = Query(None, alias="bizType"),
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
result = pilot_checkup.list_checkups_paginated(
|
||||
db,
|
||||
tenant_no=tenant_no,
|
||||
page=page,
|
||||
page_size=pageSize,
|
||||
checkup_status=checkupStatus,
|
||||
fee_status=feeStatus,
|
||||
checkup_institution_id=checkupInstitutionId,
|
||||
keyword=keyword,
|
||||
application_no=applicationNo,
|
||||
patient_name=patientName,
|
||||
channel_id=channelId,
|
||||
biz_type=bizType,
|
||||
)
|
||||
return success_response(result)
|
||||
|
||||
|
||||
@router.get("/pilot-checkup/pending-patients")
|
||||
async def api_list_pending_patients(
|
||||
page: int = Query(1, ge=1),
|
||||
pageSize: int = Query(10, ge=1, le=100, alias="pageSize"),
|
||||
applicationNo: Optional[str] = Query(None, alias="applicationNo"),
|
||||
patientName: Optional[str] = Query(None, alias="patientName"),
|
||||
channelId: Optional[str] = Query(None, alias="channelId"),
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
result = pilot_checkup.list_pending_patients(
|
||||
db,
|
||||
tenant_no=tenant_no,
|
||||
page=page,
|
||||
page_size=pageSize,
|
||||
application_no=applicationNo,
|
||||
patient_name=patientName,
|
||||
channel_id=channelId,
|
||||
)
|
||||
return success_response(result)
|
||||
|
||||
|
||||
@router.post("/pilot-checkup/batch-save")
|
||||
async def api_batch_save_checkup(
|
||||
body: BatchCheckupSaveBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
items_json = [item.model_dump(by_alias=False) for item in body.reserve_items] if body.reserve_items else []
|
||||
result = pilot_checkup.batch_create_checkups(
|
||||
db,
|
||||
patient_ids=body.patient_ids,
|
||||
checkup_institution_id=body.checkup_institution_id or "",
|
||||
reserve_time=body.reserve_time or None,
|
||||
reserve_items=items_json,
|
||||
tenant_no=tenant_no,
|
||||
user_id=user.get("user_id"),
|
||||
)
|
||||
return success_response(result, message=f"成功为 {len(result)} 名患者创建体检记录")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
@@ -1,234 +0,0 @@
|
||||
"""中试服务交付管理 API(交付信息、交付物料、交付方式)"""
|
||||
from typing import List, Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
from pydantic import BaseModel
|
||||
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.crud import pilot_delivery
|
||||
from app.models.models import SysUser
|
||||
|
||||
router = APIRouter(prefix="/web/admin", tags=["中试服务交付管理"])
|
||||
|
||||
|
||||
def _get_tenant_no(db: Session, user: dict) -> str:
|
||||
user_id = user.get("user_id")
|
||||
if not user_id:
|
||||
raise PermissionError("用户身份信息缺失,无法确定租户")
|
||||
sys_user = db.query(SysUser).filter(SysUser.id == user_id).first()
|
||||
if not sys_user or not sys_user.tenant_no:
|
||||
raise PermissionError("用户租户信息缺失")
|
||||
return sys_user.tenant_no
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Pydantic Schemas
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class IdBody(BaseModel):
|
||||
id: str
|
||||
|
||||
|
||||
class DeliverySaveBody(BaseModel):
|
||||
remark: Optional[str] = None
|
||||
|
||||
|
||||
class DeliveryMaterialItem(BaseModel):
|
||||
material_name: str
|
||||
qty: Optional[float] = None
|
||||
unit_id: Optional[str] = None
|
||||
remark: Optional[str] = None
|
||||
|
||||
|
||||
class DeliveryMaterialSaveBody(BaseModel):
|
||||
delivery_id: str
|
||||
items: List[DeliveryMaterialItem]
|
||||
|
||||
|
||||
class DeliveryMethodSaveBody(BaseModel):
|
||||
delivery_id: str
|
||||
delivery_mode: str
|
||||
delivery_attachments: Optional[str] = None
|
||||
ship_time: Optional[str] = None
|
||||
handover_temp: Optional[str] = None
|
||||
pickup_person: Optional[str] = None
|
||||
pickup_phone: Optional[str] = None
|
||||
sender_name: Optional[str] = None
|
||||
express_company_id: Optional[str] = None
|
||||
waybill_no: Optional[str] = None
|
||||
express_fee: Optional[float] = None
|
||||
eta_time: Optional[str] = None
|
||||
remark: Optional[str] = None
|
||||
|
||||
|
||||
class DeliveryCreateBody(BaseModel):
|
||||
infusion_schedule_id: str
|
||||
remark: Optional[str] = None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 1. 交付信息 CRUD
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@router.get("/pilot-delivery/detail")
|
||||
async def get_by_schedule(
|
||||
infusion_schedule_id: str = Query(...),
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
result = pilot_delivery.get_delivery_by_schedule(
|
||||
db, schedule_id=infusion_schedule_id, tenant_no=tenant_no
|
||||
)
|
||||
if result is None:
|
||||
return success_response(None)
|
||||
return success_response(result)
|
||||
|
||||
|
||||
@router.get("/pilot-delivery/list-by-application")
|
||||
async def list_by_application(
|
||||
application_id: str = Query(...),
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
result = pilot_delivery.list_deliveries_by_application(
|
||||
db, application_id=application_id, tenant_no=tenant_no
|
||||
)
|
||||
return success_response(result)
|
||||
|
||||
|
||||
@router.post("/pilot-delivery/create")
|
||||
async def create_delivery(
|
||||
body: DeliveryCreateBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
data = {"remark": body.remark}
|
||||
result = pilot_delivery.create_delivery(
|
||||
db,
|
||||
schedule_id=body.infusion_schedule_id,
|
||||
data=data,
|
||||
tenant_no=tenant_no,
|
||||
user_id=user.get("user_id"),
|
||||
dept_id=user.get("region_id", ""),
|
||||
)
|
||||
return success_response(result, message="创建成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.delete("/pilot-delivery/delete")
|
||||
async def soft_delete(
|
||||
body: IdBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
pilot_delivery.soft_delete_delivery(
|
||||
db, delivery_id=body.id, tenant_no=tenant_no
|
||||
)
|
||||
return success_response(None, message="删除成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 2. 交付物料
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@router.get("/pilot-delivery/materials")
|
||||
async def list_materials(
|
||||
delivery_id: str = Query(...),
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
result = pilot_delivery.list_delivery_materials(
|
||||
db, delivery_id=delivery_id, tenant_no=tenant_no
|
||||
)
|
||||
return success_response(result)
|
||||
|
||||
|
||||
@router.post("/pilot-delivery/materials/save")
|
||||
async def save_materials(
|
||||
body: DeliveryMaterialSaveBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
items_json = [item.dict() for item in body.items]
|
||||
result = pilot_delivery.save_delivery_materials(
|
||||
db,
|
||||
delivery_id=body.delivery_id,
|
||||
items_json=items_json,
|
||||
tenant_no=tenant_no,
|
||||
user_id=user.get("user_id"),
|
||||
)
|
||||
return success_response(result, message="保存成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 3. 交付方式
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@router.get("/pilot-delivery/method")
|
||||
async def get_method(
|
||||
delivery_id: str = Query(...),
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
result = pilot_delivery.get_delivery_method(
|
||||
db, delivery_id=delivery_id, tenant_no=tenant_no
|
||||
)
|
||||
if result is None:
|
||||
return success_response(None)
|
||||
return success_response(result)
|
||||
|
||||
|
||||
@router.post("/pilot-delivery/method/save")
|
||||
async def save_method(
|
||||
body: DeliveryMethodSaveBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
data = {
|
||||
"delivery_mode": body.delivery_mode,
|
||||
"delivery_attachments": body.delivery_attachments,
|
||||
"ship_time": body.ship_time,
|
||||
"handover_temp": body.handover_temp,
|
||||
"pickup_person": body.pickup_person,
|
||||
"pickup_phone": body.pickup_phone,
|
||||
"sender_name": body.sender_name,
|
||||
"express_company_id": body.express_company_id,
|
||||
"waybill_no": body.waybill_no,
|
||||
"express_fee": body.express_fee,
|
||||
"eta_time": body.eta_time,
|
||||
"remark": body.remark,
|
||||
}
|
||||
result = pilot_delivery.save_delivery_method(
|
||||
db,
|
||||
delivery_id=body.delivery_id,
|
||||
data=data,
|
||||
tenant_no=tenant_no,
|
||||
user_id=user.get("user_id"),
|
||||
)
|
||||
return success_response(result, message="保存成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
@@ -1,142 +0,0 @@
|
||||
"""中试应用确认 API"""
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
from pydantic import BaseModel
|
||||
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.crud import pilot_infusion_confirm as svc
|
||||
from app.models.models import SysUser
|
||||
|
||||
router = APIRouter(prefix="/web/admin", tags=["中试应用确认"])
|
||||
|
||||
|
||||
def _get_tenant_no(db: Session, user: dict) -> str:
|
||||
user_id = user.get("user_id")
|
||||
if not user_id:
|
||||
raise PermissionError("用户身份信息缺失")
|
||||
sys_user = db.query(SysUser).filter(SysUser.id == user_id).first()
|
||||
if not sys_user or not sys_user.tenant_no:
|
||||
raise PermissionError("用户租户信息缺失")
|
||||
return sys_user.tenant_no
|
||||
|
||||
|
||||
class IdBody(BaseModel):
|
||||
id: str
|
||||
|
||||
|
||||
class ConfirmCreateBody(BaseModel):
|
||||
infusionScheduleId: str
|
||||
confirmDesc: Optional[str] = None
|
||||
remark: Optional[str] = None
|
||||
|
||||
|
||||
class ConfirmUpdateBody(BaseModel):
|
||||
id: str
|
||||
confirmDesc: Optional[str] = None
|
||||
remark: Optional[str] = None
|
||||
|
||||
|
||||
@router.post("/pilot-infusion-confirm/create")
|
||||
async def api_create(
|
||||
body: ConfirmCreateBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
result = svc.create_infusion_confirm(
|
||||
db,
|
||||
schedule_id=body.infusionScheduleId,
|
||||
tenant_no=tenant_no,
|
||||
user_id=user.get("user_id"),
|
||||
create_dept_id=user.get("region_id", ""),
|
||||
confirm_desc=body.confirmDesc or "",
|
||||
remark=body.remark or "",
|
||||
)
|
||||
db.commit()
|
||||
return success_response(result, message="创建成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.get("/pilot-infusion-confirm/list")
|
||||
async def api_list(
|
||||
applicationId: str = Query(...),
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
result = svc.list_confirms_by_application(
|
||||
db, application_id=applicationId, tenant_no=tenant_no
|
||||
)
|
||||
return success_response(result)
|
||||
|
||||
|
||||
@router.get("/pilot-infusion-confirm/detail")
|
||||
async def api_detail(
|
||||
id: str = Query(...),
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
result = svc.get_confirm_by_id(db, confirm_id=id, tenant_no=tenant_no)
|
||||
if result is None:
|
||||
return success_response(None)
|
||||
return success_response(result)
|
||||
|
||||
|
||||
@router.post("/pilot-infusion-confirm/confirm")
|
||||
async def api_confirm(
|
||||
body: IdBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
result = svc.confirm_infusion(
|
||||
db, confirm_id=body.id, tenant_no=tenant_no, user_id=user.get("user_id")
|
||||
)
|
||||
return success_response(result, message="确认成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.put("/pilot-infusion-confirm/update")
|
||||
async def api_update(
|
||||
body: ConfirmUpdateBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
result = svc.update_infusion_confirm(
|
||||
db,
|
||||
confirm_id=body.id,
|
||||
tenant_no=tenant_no,
|
||||
user_id=user.get("user_id"),
|
||||
confirmDesc=body.confirmDesc,
|
||||
remark=body.remark,
|
||||
)
|
||||
return success_response(result, message="更新成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.delete("/pilot-infusion-confirm/delete")
|
||||
async def api_delete(
|
||||
body: IdBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
svc.delete_infusion_confirm(
|
||||
db, confirm_id=body.id, tenant_no=tenant_no, user_id=user.get("user_id")
|
||||
)
|
||||
return success_response(None, message="删除成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
@@ -1,264 +0,0 @@
|
||||
"""中试输注计划管理 API"""
|
||||
from typing import List, Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
from pydantic import AliasChoices, BaseModel, ConfigDict, Field
|
||||
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, 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
|
||||
from app.schemas.outbound_handover import OutboundHandoverSaveBody
|
||||
|
||||
router = APIRouter(prefix="/web/admin", tags=["中试输注计划管理"])
|
||||
|
||||
|
||||
def _get_tenant_no(db: Session, user: dict) -> str:
|
||||
user_id = user.get("user_id")
|
||||
if not user_id:
|
||||
raise PermissionError("用户身份信息缺失")
|
||||
sys_user = db.query(SysUser).filter(SysUser.id == user_id).first()
|
||||
if not sys_user or not sys_user.tenant_no:
|
||||
raise PermissionError("用户租户信息缺失")
|
||||
return sys_user.tenant_no
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Pydantic Schemas
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class UpdateStatusBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
schedule_id: str = Field(..., validation_alias=AliasChoices("scheduleId", "schedule_id"))
|
||||
infusion_status: str = Field(..., validation_alias=AliasChoices("infusionStatus", "infusion_status"))
|
||||
cancel_reason: Optional[str] = Field(
|
||||
None, validation_alias=AliasChoices("cancelReason", "cancel_reason")
|
||||
)
|
||||
|
||||
|
||||
class UpdateQcStatusBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
schedule_id: str = Field(..., validation_alias=AliasChoices("scheduleId", "schedule_id"))
|
||||
qc_status: str = Field(..., validation_alias=AliasChoices("qcStatus", "qc_status"))
|
||||
|
||||
|
||||
class ProductItemBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
price_id: Optional[str] = Field(None, validation_alias=AliasChoices("priceId", "price_id"))
|
||||
project_code: Optional[str] = Field(None, validation_alias=AliasChoices("projectCode", "project_code"))
|
||||
project_name: Optional[str] = Field(None, validation_alias=AliasChoices("projectName", "project_name"))
|
||||
cell_type_name: Optional[str] = Field(
|
||||
None, validation_alias=AliasChoices("cellTypeName", "cell_type_name")
|
||||
)
|
||||
spec_text: Optional[str] = Field(None, validation_alias=AliasChoices("specText", "spec_text"))
|
||||
agreement_price: Optional[float] = Field(
|
||||
None, validation_alias=AliasChoices("agreementPrice", "agreement_price")
|
||||
)
|
||||
actual_price: Optional[float] = Field(
|
||||
None, validation_alias=AliasChoices("actualPrice", "actual_price")
|
||||
)
|
||||
quantity: Optional[int] = Field(None, validation_alias=AliasChoices("quantity", "quantity"))
|
||||
remark: Optional[str] = Field(None, validation_alias=AliasChoices("remark", "remark"))
|
||||
|
||||
|
||||
class UpdateScheduleBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
id: str = Field(...)
|
||||
cell_type: Optional[str] = Field(None, validation_alias=AliasChoices("cellType", "cell_type"))
|
||||
spec_text: Optional[str] = Field(None, validation_alias=AliasChoices("specText", "spec_text"))
|
||||
infusion_time: Optional[str] = Field(
|
||||
None, validation_alias=AliasChoices("infusionTime", "infusion_time")
|
||||
)
|
||||
infusion_location: Optional[str] = Field(
|
||||
None, validation_alias=AliasChoices("infusionLocation", "infusion_location")
|
||||
)
|
||||
infusion_method: Optional[str] = Field(
|
||||
None, validation_alias=AliasChoices("infusionMethod", "infusion_method")
|
||||
)
|
||||
products: Optional[List[ProductItemBody]] = None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Endpoints
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@router.get("/pilot-infusion-schedule-mgmt/list")
|
||||
async def api_list(
|
||||
page: int = Query(1, ge=1),
|
||||
pageSize: int = Query(10, ge=1, le=100, alias="pageSize"),
|
||||
keyword: Optional[str] = Query(None, alias="keyword"),
|
||||
infusionStatus: Optional[str] = Query(None, alias="infusionStatus"),
|
||||
qcStatus: Optional[str] = Query(None, alias="qcStatus"),
|
||||
infusionTimeStart: Optional[str] = Query(None, alias="infusionTimeStart"),
|
||||
infusionTimeEnd: Optional[str] = Query(None, alias="infusionTimeEnd"),
|
||||
bizType: Optional[str] = Query(None, alias="bizType"),
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
result = crud.list_infusion_schedules_mgmt(
|
||||
db,
|
||||
tenant_no=tenant_no,
|
||||
page=page,
|
||||
page_size=pageSize,
|
||||
keyword=keyword,
|
||||
infusion_status=infusionStatus,
|
||||
qc_status=qcStatus,
|
||||
infusion_time_start=infusionTimeStart,
|
||||
infusion_time_end=infusionTimeEnd,
|
||||
biz_type=bizType,
|
||||
)
|
||||
return success_response(result)
|
||||
|
||||
|
||||
@router.get("/pilot-infusion-schedule-mgmt/detail")
|
||||
async def api_detail(
|
||||
scheduleId: str = Query(..., alias="scheduleId"),
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
result = crud.get_infusion_schedule_detail(
|
||||
db, schedule_id=scheduleId, tenant_no=tenant_no
|
||||
)
|
||||
if result is None:
|
||||
return success_response(None)
|
||||
return success_response(result)
|
||||
|
||||
|
||||
@router.put("/pilot-infusion-schedule-mgmt/update-status")
|
||||
async def api_update_status(
|
||||
body: UpdateStatusBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
result = crud.update_infusion_status(
|
||||
db,
|
||||
schedule_id=body.schedule_id,
|
||||
infusion_status=body.infusion_status,
|
||||
cancel_reason=body.cancel_reason,
|
||||
tenant_no=tenant_no,
|
||||
user_id=user.get("user_id"),
|
||||
)
|
||||
return success_response(result, message="状态更新成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.put("/pilot-infusion-schedule-mgmt/update-qc-status")
|
||||
async def api_update_qc_status(
|
||||
body: UpdateQcStatusBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
result = crud.update_qc_status(
|
||||
db,
|
||||
schedule_id=body.schedule_id,
|
||||
qc_status=body.qc_status,
|
||||
tenant_no=tenant_no,
|
||||
user_id=user.get("user_id"),
|
||||
)
|
||||
return success_response(result, message="质检状态更新成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.put("/pilot-infusion-schedule-mgmt/update")
|
||||
async def api_update(
|
||||
body: UpdateScheduleBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
data = {
|
||||
"cellType": body.cell_type,
|
||||
"specText": body.spec_text,
|
||||
"infusionTime": body.infusion_time,
|
||||
"infusionLocation": body.infusion_location,
|
||||
"infusionMethod": body.infusion_method,
|
||||
}
|
||||
if body.products is not None:
|
||||
data["products"] = [p.model_dump(by_alias=False) for p in body.products]
|
||||
|
||||
result = crud.update_infusion_schedule_mgmt(
|
||||
db,
|
||||
schedule_id=body.id,
|
||||
data=data,
|
||||
tenant_no=tenant_no,
|
||||
user_id=user.get("user_id"),
|
||||
)
|
||||
return success_response(result, message="更新成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.get("/pilot-infusion-schedule-mgmt/{schedule_id}/outbound-handover")
|
||||
async def api_get_outbound_handover(
|
||||
schedule_id: str,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
result = handover_crud.get_outbound_handover(db, schedule_id, tenant_no)
|
||||
return success_response(result)
|
||||
except PermissionError as e:
|
||||
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, 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")
|
||||
async def api_save_outbound_handover(
|
||||
schedule_id: str,
|
||||
body: OutboundHandoverSaveBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
user_id = user.get("user_id") or ""
|
||||
sys_user = db.query(SysUser).filter(SysUser.id == user_id).first()
|
||||
dept_id = (sys_user.dept_id or "") if sys_user else ""
|
||||
om = body.outboundMaterial
|
||||
result = handover_crud.save_outbound_handover(
|
||||
db,
|
||||
schedule_id,
|
||||
outbound_material={
|
||||
"remark": om.remark,
|
||||
"cells": [c.model_dump(by_alias=True) for c in om.cells],
|
||||
"qcMaterials": [m.model_dump(by_alias=True) for m in om.qcMaterials],
|
||||
"paperMaterials": [p.model_dump(by_alias=True) for p in om.paperMaterials],
|
||||
},
|
||||
handover=body.handover.model_dump(by_alias=True),
|
||||
tenant_no=tenant_no,
|
||||
user_id=user_id,
|
||||
create_dept_id=dept_id,
|
||||
)
|
||||
db.commit()
|
||||
return success_response(result, message="出库交接已保存")
|
||||
except PermissionError as e:
|
||||
db.rollback()
|
||||
return error_response(403, str(e))
|
||||
except Exception as e:
|
||||
db.rollback()
|
||||
if hasattr(e, "status_code"):
|
||||
code = int(getattr(e, "status_code", 400))
|
||||
return error_response(code, format_api_error_message(e))
|
||||
return error_response(400, format_api_error_message(e, fallback="出库交接保存失败"))
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -1,4 +1,4 @@
|
||||
"""公共接口(Web 登录、刷新 Token、登出;用户模型对齐 docs/sql/zkxw.sql 基线)"""
|
||||
"""公共接口(Web 登录、刷新 Token、登出;用户模型对齐 docs/sql/shanxia2.0.sql 基线)"""
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,420 +0,0 @@
|
||||
"""科研捐赠管理 — 捐赠单 CRUD / 审核 / 状态变更 / 转换 API"""
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
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.crud import research_donation as rd_svc
|
||||
from app.models.models import SysUser
|
||||
from app.models.research_donation import BizResearchDonation
|
||||
|
||||
router = APIRouter(prefix="/web/admin", tags=["科研捐赠管理"])
|
||||
|
||||
|
||||
def _get_tenant_no(db: Session, user: dict) -> str:
|
||||
user_id = user.get("user_id")
|
||||
if not user_id:
|
||||
raise PermissionError("用户身份信息缺失,无法确定租户")
|
||||
sys_user = db.query(SysUser).filter(SysUser.id == user_id).first()
|
||||
if not sys_user or not sys_user.tenant_no:
|
||||
raise PermissionError("用户租户信息缺失")
|
||||
return sys_user.tenant_no
|
||||
|
||||
|
||||
def _get_current_user_id(user: dict) -> str:
|
||||
user_id = user.get("user_id")
|
||||
if not user_id:
|
||||
raise PermissionError("用户身份信息缺失")
|
||||
return str(user_id)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Pydantic bodies
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class DonationCreateBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
donation_no: Optional[str] = Field(None, alias="donationNo")
|
||||
donation_status: Optional[str] = Field("dsx", alias="donationStatus")
|
||||
donation_date: Optional[str] = Field(None, alias="donationDate")
|
||||
source_type: Optional[str] = Field("direct", alias="sourceType")
|
||||
source_protocol_id: Optional[str] = Field(None, alias="sourceProtocolId")
|
||||
consent_form_urls: Optional[str] = Field(None, alias="consentFormUrls")
|
||||
consent_attachments: Optional[list] = Field(None, alias="consentAttachments")
|
||||
attachment_urls: Optional[str] = Field(None, alias="attachmentUrls")
|
||||
other_attachments: Optional[list] = Field(None, alias="otherAttachments")
|
||||
remark: Optional[str] = None
|
||||
party: Optional[dict] = None
|
||||
party_customer: Optional[dict] = Field(None, alias="partyCustomer")
|
||||
collection: Optional[dict] = None
|
||||
collection_info: Optional[dict] = Field(None, alias="collectionInfo")
|
||||
samples: Optional[list] = None
|
||||
collector_user_id: Optional[str] = Field(None, alias="collectorUserId")
|
||||
|
||||
|
||||
class DonationUpdateBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
donation_no: Optional[str] = Field(None, alias="donationNo")
|
||||
donation_status: Optional[str] = Field(None, alias="donationStatus")
|
||||
donation_date: Optional[str] = Field(None, alias="donationDate")
|
||||
source_type: Optional[str] = Field(None, alias="sourceType")
|
||||
source_protocol_id: Optional[str] = Field(None, alias="sourceProtocolId")
|
||||
consent_form_urls: Optional[str] = Field(None, alias="consentFormUrls")
|
||||
consent_attachments: Optional[list] = Field(None, alias="consentAttachments")
|
||||
attachment_urls: Optional[str] = Field(None, alias="attachmentUrls")
|
||||
other_attachments: Optional[list] = Field(None, alias="otherAttachments")
|
||||
remark: Optional[str] = None
|
||||
party: Optional[dict] = None
|
||||
party_customer: Optional[dict] = Field(None, alias="partyCustomer")
|
||||
collection: Optional[dict] = None
|
||||
collection_info: Optional[dict] = Field(None, alias="collectionInfo")
|
||||
samples: Optional[list] = None
|
||||
collector_user_id: Optional[str] = Field(None, alias="collectorUserId")
|
||||
|
||||
|
||||
class BatchDeleteBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
ids: List[str] = Field(..., alias="ids", min_length=1)
|
||||
|
||||
|
||||
class AuditSubmitBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
audit_status: str = Field(..., alias="auditStatus")
|
||||
audit_remark: Optional[str] = Field(None, alias="auditRemark")
|
||||
|
||||
|
||||
class StatusChangeBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
new_status: str = Field(..., alias="newStatus")
|
||||
desc: Optional[str] = Field(None, alias="desc")
|
||||
time_val: Optional[str] = Field(None, alias="timeVal")
|
||||
|
||||
|
||||
class ConvertFromStorageBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
protocol_id: str = Field(..., alias="protocolId")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 1. 列表
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@router.get("/research-donations")
|
||||
async def list_research_donations(
|
||||
page: int = Query(1, ge=1),
|
||||
pageSize: int = Query(20, ge=1, le=200, alias="pageSize"),
|
||||
keyword: Optional[str] = Query(None, alias="keyword"),
|
||||
donationStatus: Optional[str] = Query(None, alias="donationStatus"),
|
||||
createTimeStart: Optional[str] = Query(None, alias="createTimeStart"),
|
||||
createTimeEnd: Optional[str] = Query(None, alias="createTimeEnd"),
|
||||
sampleCollectTimeStart: Optional[str] = Query(None, alias="sampleCollectTimeStart"),
|
||||
sampleCollectTimeEnd: Optional[str] = Query(None, alias="sampleCollectTimeEnd"),
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
collector_user_id = _get_current_user_id(user)
|
||||
result = rd_svc.list_donations(
|
||||
db,
|
||||
tenant_no=tenant_no,
|
||||
page=page,
|
||||
page_size=pageSize,
|
||||
keyword=keyword,
|
||||
donation_status=donationStatus,
|
||||
create_time_start=createTimeStart,
|
||||
create_time_end=createTimeEnd,
|
||||
sample_collect_time_start=sampleCollectTimeStart,
|
||||
sample_collect_time_end=sampleCollectTimeEnd,
|
||||
collector_user_id=collector_user_id,
|
||||
user_info=user,
|
||||
)
|
||||
return success_response(result)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 2. 审核列表(须在 {donation_id} 详情路由之前注册,避免 audits 被当作 id)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@router.get("/research-donations/audits")
|
||||
async def list_research_donation_audits(
|
||||
page: int = Query(1, ge=1),
|
||||
pageSize: int = Query(20, ge=1, le=200, alias="pageSize"),
|
||||
keyword: Optional[str] = Query(None, alias="keyword"),
|
||||
auditStatus: Optional[str] = Query(None, alias="auditStatus"),
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
result = rd_svc.list_audits(
|
||||
db,
|
||||
tenant_no=tenant_no,
|
||||
page=page,
|
||||
page_size=pageSize,
|
||||
keyword=keyword,
|
||||
audit_status=auditStatus,
|
||||
user_info=user,
|
||||
)
|
||||
return success_response(result)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 3. 详情
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@router.get("/research-donations/{donation_id}")
|
||||
async def get_research_donation_detail(
|
||||
donation_id: str,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
result = rd_svc.get_donation_detail(db, donation_id, tenant_no)
|
||||
if not result:
|
||||
return error_response(404, "捐赠单不存在或无权查看")
|
||||
return success_response(result)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 4. 创建
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@router.post("/research-donations")
|
||||
async def create_research_donation(
|
||||
body: DonationCreateBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
user_id = _get_current_user_id(user)
|
||||
try:
|
||||
data = body.model_dump(exclude_none=False, by_alias=True)
|
||||
data["collector_user_id"] = user_id
|
||||
obj = rd_svc.create_donation(
|
||||
db,
|
||||
data=data,
|
||||
tenant_no=tenant_no,
|
||||
user_id=user_id,
|
||||
)
|
||||
return success_response(
|
||||
rd_svc._donation_to_dict(obj, db, tenant_no),
|
||||
message="创建成功",
|
||||
)
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 5. 更新
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@router.put("/research-donations/{donation_id}")
|
||||
async def update_research_donation(
|
||||
donation_id: str,
|
||||
body: DonationUpdateBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
user_id = _get_current_user_id(user)
|
||||
try:
|
||||
data = body.model_dump(exclude_unset=True, by_alias=True)
|
||||
obj = rd_svc.update_donation(
|
||||
db,
|
||||
donation_id,
|
||||
data=data,
|
||||
tenant_no=tenant_no,
|
||||
user_id=user_id,
|
||||
)
|
||||
return success_response(
|
||||
rd_svc._donation_to_dict(obj, db, tenant_no),
|
||||
message="更新成功",
|
||||
)
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 6. 删除
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@router.delete("/research-donations/{donation_id}")
|
||||
async def delete_research_donation(
|
||||
donation_id: str,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
user_id = _get_current_user_id(user)
|
||||
try:
|
||||
rd_svc.delete_donation(
|
||||
db,
|
||||
donation_id,
|
||||
tenant_no=tenant_no,
|
||||
user_id=user_id,
|
||||
)
|
||||
return success_response(None, message="删除成功")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 7. 批量删除
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@router.post("/research-donations/batch-delete")
|
||||
async def batch_delete_research_donations(
|
||||
body: BatchDeleteBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
user_id = _get_current_user_id(user)
|
||||
try:
|
||||
count = rd_svc.batch_delete_donations(
|
||||
db,
|
||||
ids=body.ids,
|
||||
tenant_no=tenant_no,
|
||||
user_id=user_id,
|
||||
)
|
||||
return success_response({"count": count}, message=f"已成功删除 {count} 条")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 8. 提交审核
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@router.post("/research-donations/{donation_id}/audit")
|
||||
async def submit_donation_audit(
|
||||
donation_id: str,
|
||||
body: AuditSubmitBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
try:
|
||||
rd_svc.submit_audit(
|
||||
db,
|
||||
donation_id,
|
||||
audit_status=body.audit_status,
|
||||
audit_remark=body.audit_remark,
|
||||
user_id=user.get("user_id"),
|
||||
tenant_no=tenant_no,
|
||||
)
|
||||
d = (
|
||||
db.query(BizResearchDonation)
|
||||
.filter(BizResearchDonation.id == donation_id)
|
||||
.first()
|
||||
)
|
||||
dn = (d.donation_no if d else "") or ""
|
||||
return success_response({"donationNo": dn}, message="审核已提交")
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 9. 状态变更
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@router.post("/research-donations/{donation_id}/status-change")
|
||||
async def change_donation_status(
|
||||
donation_id: str,
|
||||
body: StatusChangeBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
user_id = _get_current_user_id(user)
|
||||
try:
|
||||
obj = rd_svc.change_status(
|
||||
db,
|
||||
donation_id,
|
||||
new_status=body.new_status,
|
||||
desc=body.desc,
|
||||
time_val=body.time_val,
|
||||
user_id=user_id,
|
||||
tenant_no=tenant_no,
|
||||
)
|
||||
return success_response(
|
||||
rd_svc._donation_to_dict(obj, db, tenant_no),
|
||||
message="状态变更成功",
|
||||
)
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 10. 细胞存储 → 科研捐赠
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@router.post("/research-donations/convert-from-storage")
|
||||
async def convert_from_storage(
|
||||
body: ConvertFromStorageBody,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
user_id = _get_current_user_id(user)
|
||||
try:
|
||||
obj = rd_svc.convert_from_storage(
|
||||
db,
|
||||
body.protocol_id,
|
||||
tenant_no=tenant_no,
|
||||
user_id=user_id,
|
||||
)
|
||||
return success_response(
|
||||
rd_svc._donation_to_dict(obj, db, tenant_no),
|
||||
message="转换成功",
|
||||
)
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 11. 科研捐赠 → 细胞存储
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@router.post("/research-donations/{donation_id}/convert-to-storage")
|
||||
async def convert_to_storage(
|
||||
donation_id: str,
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
user_id = _get_current_user_id(user)
|
||||
try:
|
||||
obj = rd_svc.convert_to_storage(
|
||||
db,
|
||||
donation_id,
|
||||
tenant_no=tenant_no,
|
||||
user_id=user_id,
|
||||
)
|
||||
return success_response(
|
||||
rd_svc._donation_to_dict(obj, db, tenant_no),
|
||||
message="转换成功",
|
||||
)
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
@@ -1,445 +0,0 @@
|
||||
"""质量检测 — 样本接收 API"""
|
||||
from typing import List, Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
from sqlalchemy import or_
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.core.data_scope import apply_data_scope
|
||||
from app.core.database import get_db
|
||||
from app.core.menu_guard import require_admin_or_super_admin, require_menu_code
|
||||
from app.core.response import error_response, success_response
|
||||
from app.core.utils import parse_datetime
|
||||
from app.crud import sample_reception as sr_svc
|
||||
from app.crud import sample_reception_check_item as check_item_svc
|
||||
from app.crud.collection_protocol import total_pages
|
||||
from app.models.models import BizSampleReception, BizSampleReceptionCheckItem, SysUser
|
||||
|
||||
router = APIRouter(prefix="/web/admin", tags=["质量检测"])
|
||||
|
||||
|
||||
def _get_tenant_no(db: Session, user: dict) -> str:
|
||||
user_id = user.get("user_id")
|
||||
if not user_id:
|
||||
raise PermissionError("用户身份信息缺失,无法确定租户")
|
||||
sys_user = db.query(SysUser).filter(SysUser.id == user_id).first()
|
||||
if not sys_user or not sys_user.tenant_no:
|
||||
raise PermissionError("用户租户信息缺失")
|
||||
return sys_user.tenant_no
|
||||
|
||||
|
||||
def _get_current_user_id(user: dict) -> str:
|
||||
user_id = user.get("user_id")
|
||||
if not user_id:
|
||||
raise PermissionError("用户身份信息缺失")
|
||||
return str(user_id)
|
||||
|
||||
|
||||
def _page_payload(items: list, total: int, page: int, page_size: int) -> dict:
|
||||
return {
|
||||
"list": items,
|
||||
"total": total,
|
||||
"page": page,
|
||||
"pageSize": page_size,
|
||||
"totalPages": total_pages(total, page_size),
|
||||
}
|
||||
|
||||
|
||||
# ---------- 检查项配置 ----------
|
||||
|
||||
|
||||
class CheckItemBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
item_code: str = Field(..., alias="itemCode")
|
||||
item_name: str = Field(..., alias="itemName")
|
||||
status: str = Field("1", alias="status")
|
||||
order_num: Optional[int] = Field(None, alias="orderNum")
|
||||
remark: Optional[str] = None
|
||||
|
||||
|
||||
class CheckItemUpdateBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
item_code: Optional[str] = Field(None, alias="itemCode")
|
||||
item_name: Optional[str] = Field(None, alias="itemName")
|
||||
status: Optional[str] = None
|
||||
order_num: Optional[int] = Field(None, alias="orderNum")
|
||||
remark: Optional[str] = None
|
||||
|
||||
|
||||
@router.get("/sample-reception-check-items")
|
||||
async def list_check_items(
|
||||
page: int = Query(1, ge=1),
|
||||
pageSize: int = Query(10, ge=1, le=100),
|
||||
keyword: Optional[str] = None,
|
||||
status: Optional[str] = None,
|
||||
db: Session = Depends(get_db),
|
||||
user: dict = Depends(require_menu_code("biz:sampleReception:list")),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
query = db.query(BizSampleReceptionCheckItem).filter(
|
||||
BizSampleReceptionCheckItem.del_flag == 0,
|
||||
BizSampleReceptionCheckItem.tenant_no == tenant_no,
|
||||
)
|
||||
kw = (keyword or "").strip()
|
||||
if kw:
|
||||
like = f"%{kw}%"
|
||||
query = query.filter(
|
||||
or_(
|
||||
BizSampleReceptionCheckItem.item_code.like(like),
|
||||
BizSampleReceptionCheckItem.item_name.like(like),
|
||||
)
|
||||
)
|
||||
if status:
|
||||
query = query.filter(BizSampleReceptionCheckItem.status == status)
|
||||
query = apply_data_scope(query, BizSampleReceptionCheckItem, user, db, tenant_no)
|
||||
total = query.count()
|
||||
items = query.order_by(BizSampleReceptionCheckItem.create_time.desc()).offset((page - 1) * pageSize).limit(pageSize).all()
|
||||
result_list = [check_item_svc._row_to_dict(r) for r in items]
|
||||
return success_response(_page_payload(result_list, total, page, pageSize))
|
||||
except PermissionError as e:
|
||||
return error_response(403, str(e))
|
||||
except Exception as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.get("/sample-reception-check-items/active")
|
||||
async def list_active_check_items(
|
||||
db: Session = Depends(get_db),
|
||||
user: dict = Depends(require_menu_code("biz:sampleReception:list")),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
items = check_item_svc.list_active_check_items(db, tenant_no)
|
||||
return success_response(items)
|
||||
except PermissionError as e:
|
||||
return error_response(403, str(e))
|
||||
except Exception as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.post("/sample-reception-check-items")
|
||||
async def create_check_item(
|
||||
body: CheckItemBody,
|
||||
db: Session = Depends(get_db),
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
user_id = _get_current_user_id(user)
|
||||
sys_user = db.query(SysUser).filter(SysUser.id == user_id).first()
|
||||
dept_id = (sys_user.dept_id or "") if sys_user else ""
|
||||
obj = check_item_svc.create_check_item(
|
||||
db,
|
||||
item_code=body.item_code,
|
||||
item_name=body.item_name,
|
||||
status=body.status,
|
||||
tenant_no=tenant_no,
|
||||
order_num=body.order_num,
|
||||
remark=body.remark,
|
||||
user_id=user_id,
|
||||
create_dept_id=dept_id,
|
||||
)
|
||||
return success_response(check_item_svc._row_to_dict(obj))
|
||||
except PermissionError as e:
|
||||
return error_response(403, str(e))
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
except Exception as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.put("/sample-reception-check-items/{row_id}")
|
||||
async def update_check_item(
|
||||
row_id: str,
|
||||
body: CheckItemUpdateBody,
|
||||
db: Session = Depends(get_db),
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
user_id = _get_current_user_id(user)
|
||||
obj = check_item_svc.update_check_item(
|
||||
db,
|
||||
row_id,
|
||||
item_code=body.item_code,
|
||||
item_name=body.item_name,
|
||||
status=body.status,
|
||||
order_num=body.order_num,
|
||||
remark=body.remark,
|
||||
user_id=user_id,
|
||||
tenant_no=tenant_no,
|
||||
)
|
||||
return success_response(check_item_svc._row_to_dict(obj))
|
||||
except PermissionError as e:
|
||||
return error_response(403, str(e))
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
except Exception as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.delete("/sample-reception-check-items/{row_id}")
|
||||
async def delete_check_item(
|
||||
row_id: str,
|
||||
db: Session = Depends(get_db),
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
check_item_svc.soft_delete_check_item(db, row_id, tenant_no=tenant_no)
|
||||
return success_response(None)
|
||||
except PermissionError as e:
|
||||
return error_response(403, str(e))
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
except Exception as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
# ---------- 样本接收 ----------
|
||||
|
||||
|
||||
@router.get("/sample-receptions/pending")
|
||||
async def list_pending_samples(
|
||||
page: int = Query(1, ge=1),
|
||||
pageSize: int = Query(10, ge=1, le=100),
|
||||
keyword: Optional[str] = None,
|
||||
sourceType: Optional[str] = None,
|
||||
etaTimeStart: Optional[str] = Query(None, alias="etaTimeStart"),
|
||||
etaTimeEnd: Optional[str] = Query(None, alias="etaTimeEnd"),
|
||||
db: Session = Depends(get_db),
|
||||
user: dict = Depends(require_menu_code("biz:sampleReception:list")),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
items, total = sr_svc.list_pending_protocol_samples(
|
||||
db, page=page, page_size=pageSize, tenant_no=tenant_no, keyword=keyword,
|
||||
source_type=sourceType,
|
||||
eta_time_start=etaTimeStart,
|
||||
eta_time_end=etaTimeEnd,
|
||||
user_info=user,
|
||||
)
|
||||
return success_response(_page_payload(items, total, page, pageSize))
|
||||
except PermissionError as e:
|
||||
return error_response(403, str(e))
|
||||
except Exception as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.get("/sample-receptions/received")
|
||||
async def list_received_samples(
|
||||
page: int = Query(1, ge=1),
|
||||
pageSize: int = Query(10, ge=1, le=100),
|
||||
keyword: Optional[str] = None,
|
||||
sourceType: Optional[str] = None,
|
||||
receptionTimeStart: Optional[str] = Query(None, alias="receptionTimeStart"),
|
||||
receptionTimeEnd: Optional[str] = Query(None, alias="receptionTimeEnd"),
|
||||
db: Session = Depends(get_db),
|
||||
user: dict = Depends(require_menu_code("biz:sampleReception:list")),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
items, total = sr_svc.list_received_protocol_samples(
|
||||
db, page=page, page_size=pageSize, tenant_no=tenant_no, keyword=keyword,
|
||||
source_type=sourceType,
|
||||
reception_time_start=receptionTimeStart,
|
||||
reception_time_end=receptionTimeEnd,
|
||||
user_info=user,
|
||||
)
|
||||
return success_response(_page_payload(items, total, page, pageSize))
|
||||
except PermissionError as e:
|
||||
return error_response(403, str(e))
|
||||
except Exception as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.get("/sample-receptions/{reception_id}")
|
||||
async def get_sample_reception_detail(
|
||||
reception_id: str,
|
||||
db: Session = Depends(get_db),
|
||||
user: dict = Depends(require_menu_code("biz:sampleReception:list")),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
item = sr_svc.get_reception_by_id(db, reception_id, tenant_no)
|
||||
if not item:
|
||||
return error_response(404, "接收记录不存在")
|
||||
return success_response(item)
|
||||
except PermissionError as e:
|
||||
return error_response(403, str(e))
|
||||
except Exception as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
class ReceptionCheckSubmit(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
check_item_id: str = Field(..., alias="checkItemId")
|
||||
checked: bool = False
|
||||
|
||||
|
||||
class SampleReceptionUpdateBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
reception_time: str = Field(..., alias="receptionTime")
|
||||
handler_user_id: Optional[str] = Field(None, alias="handlerUserId")
|
||||
handler_name: Optional[str] = Field(None, alias="handlerName")
|
||||
receive_temperature: Optional[str] = Field(None, alias="receiveTemperature")
|
||||
volume_ml: Optional[float] = Field(None, alias="volumeMl")
|
||||
net_weight_g: Optional[float] = Field(None, alias="netWeightG")
|
||||
checks: List[ReceptionCheckSubmit] = Field(default_factory=list)
|
||||
accept_conclusion: str = Field(..., alias="acceptConclusion")
|
||||
receive_attachments: Optional[str] = Field(None, alias="receiveAttachments")
|
||||
remark: Optional[str] = None
|
||||
|
||||
|
||||
class SampleReceptionCreateBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
protocol_sample_id: Optional[str] = Field(None, alias="protocolSampleId")
|
||||
reception_time: str = Field(..., alias="receptionTime")
|
||||
handler_user_id: Optional[str] = Field(None, alias="handlerUserId")
|
||||
handler_name: Optional[str] = Field(None, alias="handlerName")
|
||||
receive_temperature: Optional[str] = Field(None, alias="receiveTemperature")
|
||||
volume_ml: Optional[float] = Field(None, alias="volumeMl")
|
||||
net_weight_g: Optional[float] = Field(None, alias="netWeightG")
|
||||
checks: List[ReceptionCheckSubmit] = Field(default_factory=list)
|
||||
accept_conclusion: str = Field(..., alias="acceptConclusion")
|
||||
receive_attachments: Optional[str] = Field(None, alias="receiveAttachments")
|
||||
remark: Optional[str] = None
|
||||
source_type: Optional[str] = Field("cell_storage", alias="sourceType")
|
||||
donation_sample_id: Optional[str] = Field(None, alias="donationSampleId")
|
||||
|
||||
|
||||
@router.post("/sample-receptions")
|
||||
async def post_sample_reception(
|
||||
body: SampleReceptionCreateBody,
|
||||
db: Session = Depends(get_db),
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
user_id = _get_current_user_id(user)
|
||||
sys_user = db.query(SysUser).filter(SysUser.id == user_id).first()
|
||||
dept_id = (sys_user.dept_id or "") if sys_user else ""
|
||||
rt = parse_datetime(body.reception_time)
|
||||
if not rt:
|
||||
return error_response(400, "样本接收时间格式无效")
|
||||
checks_payload = [
|
||||
{"checkItemId": c.check_item_id, "checked": c.checked} for c in body.checks
|
||||
]
|
||||
obj = sr_svc.create_sample_reception(
|
||||
db,
|
||||
reception_source=body.source_type or "cell_storage",
|
||||
protocol_sample_id=body.protocol_sample_id if body.source_type != "research_donation" else None,
|
||||
donation_sample_id=body.donation_sample_id if body.source_type == "research_donation" else None,
|
||||
tenant_no=tenant_no,
|
||||
user_id=user_id,
|
||||
create_dept_id=dept_id,
|
||||
reception_time=rt,
|
||||
handler_user_id=body.handler_user_id or user_id,
|
||||
handler_name=body.handler_name,
|
||||
receive_temperature=body.receive_temperature,
|
||||
volume_ml=body.volume_ml,
|
||||
net_weight_g=body.net_weight_g,
|
||||
checks=checks_payload,
|
||||
accept_conclusion=body.accept_conclusion,
|
||||
receive_attachments=body.receive_attachments,
|
||||
remark=body.remark,
|
||||
)
|
||||
detail = sr_svc.get_reception_by_id(db, obj.id, tenant_no)
|
||||
return success_response(detail or {"id": obj.id})
|
||||
except PermissionError as e:
|
||||
return error_response(403, str(e))
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
except Exception as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.put("/sample-receptions/{reception_id}")
|
||||
async def put_sample_reception(
|
||||
reception_id: str,
|
||||
body: SampleReceptionUpdateBody,
|
||||
db: Session = Depends(get_db),
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
user_id = _get_current_user_id(user)
|
||||
rt = parse_datetime(body.reception_time)
|
||||
if not rt:
|
||||
return error_response(400, "样本接收时间格式无效")
|
||||
checks_payload = [
|
||||
{"checkItemId": c.check_item_id, "checked": c.checked} for c in body.checks
|
||||
]
|
||||
obj = sr_svc.update_sample_reception(
|
||||
db,
|
||||
reception_id=reception_id,
|
||||
tenant_no=tenant_no,
|
||||
user_id=user_id,
|
||||
reception_time=rt,
|
||||
handler_user_id=body.handler_user_id or user_id,
|
||||
handler_name=body.handler_name,
|
||||
receive_temperature=body.receive_temperature,
|
||||
volume_ml=body.volume_ml,
|
||||
net_weight_g=body.net_weight_g,
|
||||
checks=checks_payload,
|
||||
accept_conclusion=body.accept_conclusion,
|
||||
receive_attachments=body.receive_attachments,
|
||||
remark=body.remark,
|
||||
)
|
||||
detail = sr_svc.get_reception_by_id(db, obj.id, tenant_no)
|
||||
return success_response(detail or {"id": obj.id})
|
||||
except PermissionError as e:
|
||||
return error_response(403, str(e))
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
except Exception as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.put("/sample-receptions/{reception_id}")
|
||||
async def put_sample_reception(
|
||||
reception_id: str,
|
||||
body: SampleReceptionUpdateBody,
|
||||
db: Session = Depends(get_db),
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
user_id = _get_current_user_id(user)
|
||||
rt = parse_datetime(body.reception_time)
|
||||
if not rt:
|
||||
return error_response(400, "样本接收时间格式无效")
|
||||
checks_payload = [
|
||||
{"checkItemId": c.check_item_id, "checked": c.checked} for c in body.checks
|
||||
]
|
||||
obj = sr_svc.update_sample_reception(
|
||||
db,
|
||||
reception_id=reception_id,
|
||||
tenant_no=tenant_no,
|
||||
user_id=user_id,
|
||||
reception_time=rt,
|
||||
handler_user_id=body.handler_user_id or user_id,
|
||||
handler_name=body.handler_name,
|
||||
receive_temperature=body.receive_temperature,
|
||||
volume_ml=body.volume_ml,
|
||||
net_weight_g=body.net_weight_g,
|
||||
checks=checks_payload,
|
||||
accept_conclusion=body.accept_conclusion,
|
||||
receive_attachments=body.receive_attachments,
|
||||
remark=body.remark,
|
||||
)
|
||||
detail = sr_svc.get_reception_by_id(db, obj.id, tenant_no)
|
||||
return success_response(detail or {"id": obj.id})
|
||||
except PermissionError as e:
|
||||
return error_response(403, str(e))
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
except Exception as e:
|
||||
return error_response(400, str(e))
|
||||
@@ -1,135 +0,0 @@
|
||||
"""样本接收短信通知 API"""
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.core.database import get_db
|
||||
from app.core.menu_guard import require_menu_code
|
||||
from app.core.response import error_response, success_response
|
||||
from app.crud import sample_sms_notification as svc
|
||||
from app.crud.collection_protocol import total_pages
|
||||
from app.models.models import SysUser
|
||||
|
||||
router = APIRouter(prefix="/web/admin", tags=["样本接收短信通知"])
|
||||
|
||||
|
||||
def _get_tenant_no(db: Session, user: dict) -> str:
|
||||
user_id = user.get("user_id")
|
||||
if not user_id:
|
||||
raise PermissionError("用户身份信息缺失,无法确定租户")
|
||||
sys_user = db.query(SysUser).filter(SysUser.id == user_id).first()
|
||||
if not sys_user or not sys_user.tenant_no:
|
||||
raise PermissionError("用户租户信息缺失")
|
||||
return sys_user.tenant_no
|
||||
|
||||
|
||||
def _get_current_user_id(user: dict) -> str:
|
||||
user_id = user.get("user_id")
|
||||
if not user_id:
|
||||
raise PermissionError("用户身份信息缺失")
|
||||
return str(user_id)
|
||||
|
||||
|
||||
def _page_payload(items: list, total: int, page: int, page_size: int) -> dict:
|
||||
return {
|
||||
"list": items,
|
||||
"total": total,
|
||||
"page": page,
|
||||
"pageSize": page_size,
|
||||
"totalPages": total_pages(total, page_size),
|
||||
}
|
||||
|
||||
|
||||
class ToggleStatusBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
sms_notified: int = Field(..., alias="smsNotified")
|
||||
sample_reception_id: Optional[str] = Field(None, alias="sampleReceptionId")
|
||||
|
||||
|
||||
@router.get("/sample-sms-notifications/list")
|
||||
async def list_notifications(
|
||||
page: int = Query(1, ge=1),
|
||||
pageSize: int = Query(10, ge=1, le=100),
|
||||
keyword: Optional[str] = None,
|
||||
acceptConclusion: Optional[str] = None,
|
||||
smsNotified: Optional[int] = None,
|
||||
receptionTimeStart: Optional[str] = Query(None, alias="receptionTimeStart"),
|
||||
receptionTimeEnd: Optional[str] = Query(None, alias="receptionTimeEnd"),
|
||||
db: Session = Depends(get_db),
|
||||
user: dict = Depends(require_menu_code("cell-storage:sample-reception-info:list")),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
items, total = svc.list_notifications(
|
||||
db,
|
||||
page=page,
|
||||
page_size=pageSize,
|
||||
tenant_no=tenant_no,
|
||||
keyword=keyword,
|
||||
accept_conclusion=acceptConclusion,
|
||||
sms_notified=smsNotified,
|
||||
reception_time_start=receptionTimeStart,
|
||||
reception_time_end=receptionTimeEnd,
|
||||
user_info=user,
|
||||
)
|
||||
return success_response(_page_payload(items, total, page, pageSize))
|
||||
except PermissionError as e:
|
||||
return error_response(403, str(e))
|
||||
except Exception as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.put("/sample-sms-notifications/{notification_id}/toggle-status")
|
||||
async def toggle_status(
|
||||
notification_id: str,
|
||||
body: ToggleStatusBody,
|
||||
db: Session = Depends(get_db),
|
||||
user: dict = Depends(require_menu_code("cell-storage:sample-reception-info:list")),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
user_id = _get_current_user_id(user)
|
||||
result = svc.toggle_notification_status(
|
||||
db,
|
||||
notification_id=notification_id,
|
||||
tenant_no=tenant_no,
|
||||
sms_notified=body.sms_notified,
|
||||
user_id=user_id,
|
||||
sample_reception_id=body.sample_reception_id,
|
||||
)
|
||||
if not result:
|
||||
return error_response(404, "通知记录不存在")
|
||||
return success_response(None)
|
||||
except PermissionError as e:
|
||||
return error_response(403, str(e))
|
||||
except Exception as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.post("/sample-sms-notifications/{notification_id}/generate-sms")
|
||||
async def generate_sms(
|
||||
notification_id: str,
|
||||
sampleReceptionId: Optional[str] = Query(None),
|
||||
db: Session = Depends(get_db),
|
||||
user: dict = Depends(require_menu_code("cell-storage:sample-reception-info:list")),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
user_id = _get_current_user_id(user)
|
||||
content = svc.generate_sms_content(
|
||||
db,
|
||||
notification_id=notification_id,
|
||||
tenant_no=tenant_no,
|
||||
sample_reception_id=sampleReceptionId,
|
||||
user_id=user_id,
|
||||
)
|
||||
if content is None:
|
||||
return error_response(404, "通知记录不存在")
|
||||
return success_response({"smsContent": content})
|
||||
except PermissionError as e:
|
||||
return error_response(403, str(e))
|
||||
except Exception as e:
|
||||
return error_response(400, str(e))
|
||||
@@ -1,135 +0,0 @@
|
||||
"""样本入库短信通知 API"""
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.core.database import get_db
|
||||
from app.core.menu_guard import require_menu_code
|
||||
from app.core.response import error_response, success_response
|
||||
from app.crud import storage_entry_sms_notification as svc
|
||||
from app.crud.collection_protocol import total_pages
|
||||
from app.models.models import SysUser
|
||||
|
||||
router = APIRouter(prefix="/web/admin", tags=["样本入库短信通知"])
|
||||
|
||||
|
||||
def _get_tenant_no(db: Session, user: dict) -> str:
|
||||
user_id = user.get("user_id")
|
||||
if not user_id:
|
||||
raise PermissionError("用户身份信息缺失,无法确定租户")
|
||||
sys_user = db.query(SysUser).filter(SysUser.id == user_id).first()
|
||||
if not sys_user or not sys_user.tenant_no:
|
||||
raise PermissionError("用户租户信息缺失")
|
||||
return sys_user.tenant_no
|
||||
|
||||
|
||||
def _get_current_user_id(user: dict) -> str:
|
||||
user_id = user.get("user_id")
|
||||
if not user_id:
|
||||
raise PermissionError("用户身份信息缺失")
|
||||
return str(user_id)
|
||||
|
||||
|
||||
def _page_payload(items: list, total: int, page: int, page_size: int) -> dict:
|
||||
return {
|
||||
"list": items,
|
||||
"total": total,
|
||||
"page": page,
|
||||
"pageSize": page_size,
|
||||
"totalPages": total_pages(total, page_size),
|
||||
}
|
||||
|
||||
|
||||
class ToggleStatusBody(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
sms_notified: int = Field(..., alias="smsNotified")
|
||||
storage_review_id: Optional[str] = Field(None, alias="storageReviewId")
|
||||
|
||||
|
||||
@router.get("/storage-entry-sms-notifications/list")
|
||||
async def list_notifications(
|
||||
page: int = Query(1, ge=1),
|
||||
pageSize: int = Query(10, ge=1, le=100),
|
||||
keyword: Optional[str] = None,
|
||||
storageStatus: Optional[str] = None,
|
||||
smsNotified: Optional[int] = None,
|
||||
storageTimeStart: Optional[str] = Query(None, alias="storageTimeStart"),
|
||||
storageTimeEnd: Optional[str] = Query(None, alias="storageTimeEnd"),
|
||||
db: Session = Depends(get_db),
|
||||
user: dict = Depends(require_menu_code("cell-storage:storage-entry-info:list")),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
items, total = svc.list_notifications(
|
||||
db,
|
||||
page=page,
|
||||
page_size=pageSize,
|
||||
tenant_no=tenant_no,
|
||||
keyword=keyword,
|
||||
storage_status=storageStatus,
|
||||
sms_notified=smsNotified,
|
||||
storage_time_start=storageTimeStart,
|
||||
storage_time_end=storageTimeEnd,
|
||||
user_info=user,
|
||||
)
|
||||
return success_response(_page_payload(items, total, page, pageSize))
|
||||
except PermissionError as e:
|
||||
return error_response(403, str(e))
|
||||
except Exception as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.put("/storage-entry-sms-notifications/{notification_id}/toggle-status")
|
||||
async def toggle_status(
|
||||
notification_id: str,
|
||||
body: ToggleStatusBody,
|
||||
db: Session = Depends(get_db),
|
||||
user: dict = Depends(require_menu_code("cell-storage:storage-entry-info:list")),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
user_id = _get_current_user_id(user)
|
||||
result = svc.toggle_notification_status(
|
||||
db,
|
||||
notification_id=notification_id,
|
||||
tenant_no=tenant_no,
|
||||
sms_notified=body.sms_notified,
|
||||
user_id=user_id,
|
||||
storage_review_id=body.storage_review_id,
|
||||
)
|
||||
if not result:
|
||||
return error_response(404, "通知记录不存在")
|
||||
return success_response(None)
|
||||
except PermissionError as e:
|
||||
return error_response(403, str(e))
|
||||
except Exception as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.post("/storage-entry-sms-notifications/{notification_id}/generate-sms")
|
||||
async def generate_sms(
|
||||
notification_id: str,
|
||||
storageReviewId: Optional[str] = Query(None),
|
||||
db: Session = Depends(get_db),
|
||||
user: dict = Depends(require_menu_code("cell-storage:storage-entry-info:list")),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
user_id = _get_current_user_id(user)
|
||||
content = svc.generate_sms_content(
|
||||
db,
|
||||
notification_id=notification_id,
|
||||
tenant_no=tenant_no,
|
||||
storage_review_id=storageReviewId,
|
||||
user_id=user_id,
|
||||
)
|
||||
if content is None:
|
||||
return error_response(404, "通知记录不存在")
|
||||
return success_response({"smsContent": content})
|
||||
except PermissionError as e:
|
||||
return error_response(403, str(e))
|
||||
except Exception as e:
|
||||
return error_response(400, str(e))
|
||||
@@ -1,190 +0,0 @@
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.core.database import get_db
|
||||
from app.core.menu_guard import require_admin_or_super_admin, require_menu_code
|
||||
from app.core.response import error_response, success_response
|
||||
from app.crud import storage_release_review as srr_svc
|
||||
from app.models.models import SysUser
|
||||
from app.schemas.storage_release_review import (
|
||||
BatchReviewBody,
|
||||
BatchStoreBody,
|
||||
ReviewSubmitBody,
|
||||
)
|
||||
|
||||
router = APIRouter(prefix="/web/admin", tags=["入库放行审核"])
|
||||
|
||||
|
||||
def _get_tenant_no(db: Session, user: dict) -> str:
|
||||
user_id = user.get("user_id")
|
||||
if not user_id:
|
||||
raise PermissionError("用户身份信息缺失,无法确定租户")
|
||||
sys_user = db.query(SysUser).filter(SysUser.id == user_id).first()
|
||||
if not sys_user or not sys_user.tenant_no:
|
||||
raise PermissionError("用户租户信息缺失")
|
||||
return sys_user.tenant_no
|
||||
|
||||
|
||||
def _get_current_user_id(user: dict) -> str:
|
||||
user_id = user.get("user_id")
|
||||
if not user_id:
|
||||
raise PermissionError("用户身份信息缺失")
|
||||
return str(user_id)
|
||||
|
||||
|
||||
@router.get("/storage-release-reviews")
|
||||
async def list_storage_release_reviews(
|
||||
page: int = Query(1, ge=1),
|
||||
pageSize: int = Query(10, ge=1, le=100),
|
||||
keyword: Optional[str] = None,
|
||||
receptionSource: Optional[str] = None,
|
||||
reviewConclusion: Optional[str] = None,
|
||||
storageStatus: Optional[str] = None,
|
||||
db: Session = Depends(get_db),
|
||||
user: dict = Depends(require_menu_code("biz:storageReleaseReview:list")),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
result = srr_svc.list_reviews(
|
||||
db,
|
||||
tenant_no=tenant_no,
|
||||
page=page,
|
||||
page_size=pageSize,
|
||||
reception_source=receptionSource,
|
||||
review_conclusion=reviewConclusion,
|
||||
storage_status=storageStatus,
|
||||
keyword=keyword,
|
||||
user_info=user,
|
||||
)
|
||||
return success_response(result)
|
||||
except PermissionError as e:
|
||||
return error_response(403, str(e))
|
||||
except Exception as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.get("/storage-release-reviews/{review_id}")
|
||||
async def get_storage_release_review_detail(
|
||||
review_id: str,
|
||||
db: Session = Depends(get_db),
|
||||
user: dict = Depends(require_menu_code("biz:storageReleaseReview:list")),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
detail = srr_svc.get_review_detail(db, review_id, tenant_no)
|
||||
if not detail:
|
||||
return error_response(404, "审核记录不存在")
|
||||
return success_response(detail)
|
||||
except PermissionError as e:
|
||||
return error_response(403, str(e))
|
||||
except Exception as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.put("/storage-release-reviews/{review_id}/review")
|
||||
async def submit_single_review(
|
||||
review_id: str,
|
||||
body: ReviewSubmitBody,
|
||||
db: Session = Depends(get_db),
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
user_id = _get_current_user_id(user)
|
||||
rev = srr_svc.submit_review(
|
||||
db,
|
||||
review_id,
|
||||
review_conclusion=body.reviewConclusion,
|
||||
review_remark=body.reviewRemark,
|
||||
review_attachments=body.reviewAttachments,
|
||||
tenant_no=tenant_no,
|
||||
user_id=user_id,
|
||||
)
|
||||
db.commit()
|
||||
return success_response(srr_svc._row_to_dict(rev))
|
||||
except PermissionError as e:
|
||||
return error_response(403, str(e))
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
except Exception as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.put("/storage-release-reviews/batch-review")
|
||||
async def batch_review(
|
||||
body: BatchReviewBody,
|
||||
db: Session = Depends(get_db),
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
user_id = _get_current_user_id(user)
|
||||
result = srr_svc.batch_submit_review(
|
||||
db,
|
||||
body.ids,
|
||||
review_conclusion=body.reviewConclusion,
|
||||
review_remark=body.reviewRemark,
|
||||
review_attachments=body.reviewAttachments,
|
||||
tenant_no=tenant_no,
|
||||
user_id=user_id,
|
||||
)
|
||||
db.commit()
|
||||
return success_response(result)
|
||||
except PermissionError as e:
|
||||
return error_response(403, str(e))
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
except Exception as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.put("/storage-release-reviews/{review_id}/store")
|
||||
async def store_single_sample(
|
||||
review_id: str,
|
||||
db: Session = Depends(get_db),
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
user_id = _get_current_user_id(user)
|
||||
rev = srr_svc.store_sample(
|
||||
db,
|
||||
review_id,
|
||||
tenant_no=tenant_no,
|
||||
user_id=user_id,
|
||||
)
|
||||
db.commit()
|
||||
return success_response(srr_svc._row_to_dict(rev))
|
||||
except PermissionError as e:
|
||||
return error_response(403, str(e))
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
except Exception as e:
|
||||
return error_response(400, str(e))
|
||||
|
||||
|
||||
@router.put("/storage-release-reviews/batch-store")
|
||||
async def batch_store_samples(
|
||||
body: BatchStoreBody,
|
||||
db: Session = Depends(get_db),
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
):
|
||||
try:
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
user_id = _get_current_user_id(user)
|
||||
result = srr_svc.batch_store_samples(
|
||||
db,
|
||||
body.ids,
|
||||
tenant_no=tenant_no,
|
||||
user_id=user_id,
|
||||
)
|
||||
db.commit()
|
||||
return success_response(result)
|
||||
except PermissionError as e:
|
||||
return error_response(403, str(e))
|
||||
except ValueError as e:
|
||||
return error_response(400, str(e))
|
||||
except Exception as e:
|
||||
return error_response(400, str(e))
|
||||
+11
-11
@@ -156,7 +156,7 @@ async def list_process_defs(
|
||||
_user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _user.get("tenant_no", "zkxw")
|
||||
tenant_no = _user.get("tenant_no", "shanxia2.0")
|
||||
items, total = wf_crud.list_process_defs(
|
||||
db, page=page, page_size=pageSize, keyword=keyword, status=status, tenant_no=tenant_no, user_info=_user
|
||||
)
|
||||
@@ -171,7 +171,7 @@ async def create_process_def(
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = user.get("tenant_no", "zkxw")
|
||||
tenant_no = user.get("tenant_no", "shanxia2.0")
|
||||
obj = wf_crud.create_process_def(
|
||||
db,
|
||||
process_code=body.processCode,
|
||||
@@ -205,7 +205,7 @@ async def update_process_def(
|
||||
order_num=payload.get("orderNum"),
|
||||
remark=payload.get("remark"),
|
||||
user_id=user.get("user_id"),
|
||||
tenant_no=user.get("tenant_no", "zkxw"),
|
||||
tenant_no=user.get("tenant_no", "shanxia2.0"),
|
||||
)
|
||||
return success_response(wf_crud._row_to_dict(obj), message="更新成功")
|
||||
except ValueError as e:
|
||||
@@ -238,7 +238,7 @@ async def publish_version(
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = user.get("tenant_no", "zkxw")
|
||||
tenant_no = user.get("tenant_no", "shanxia2.0")
|
||||
ver = wf_crud.publish_version(
|
||||
db,
|
||||
process_def_id=def_id,
|
||||
@@ -260,7 +260,7 @@ async def list_versions(
|
||||
_user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _user.get("tenant_no", "zkxw")
|
||||
tenant_no = _user.get("tenant_no", "shanxia2.0")
|
||||
items = wf_crud.list_versions(db, def_id, tenant_no=tenant_no, user_info=_user)
|
||||
return success_response(items)
|
||||
|
||||
@@ -303,7 +303,7 @@ async def start_instance(
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = user.get("tenant_no", "zkxw")
|
||||
tenant_no = user.get("tenant_no", "shanxia2.0")
|
||||
user_id = user.get("user_id") or user.get("id")
|
||||
defn = (
|
||||
db.query(WfProcessDef)
|
||||
@@ -344,7 +344,7 @@ async def list_my_instances(
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
user_id = user.get("user_id") or user.get("id")
|
||||
tenant_no = user.get("tenant_no", "zkxw")
|
||||
tenant_no = user.get("tenant_no", "shanxia2.0")
|
||||
items, total = wf_crud.list_my_instances(
|
||||
db, user_id, page=page, page_size=pageSize,
|
||||
keyword=keyword, status=status, tenant_no=tenant_no, user_info=user,
|
||||
@@ -426,7 +426,7 @@ async def list_pending_tasks(
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
user_id = user.get("user_id") or user.get("id")
|
||||
tenant_no = user.get("tenant_no", "zkxw")
|
||||
tenant_no = user.get("tenant_no", "shanxia2.0")
|
||||
items, total = wf_crud.list_pending_tasks(
|
||||
db, user_id, page=page, page_size=pageSize, keyword=keyword, tenant_no=tenant_no, user_info=user
|
||||
)
|
||||
@@ -444,7 +444,7 @@ async def list_completed_tasks(
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
user_id = user.get("user_id") or user.get("id")
|
||||
tenant_no = user.get("tenant_no", "zkxw")
|
||||
tenant_no = user.get("tenant_no", "shanxia2.0")
|
||||
items, total = wf_crud.list_completed_tasks(
|
||||
db, user_id, page=page, page_size=pageSize, keyword=keyword, tenant_no=tenant_no, user_info=user
|
||||
)
|
||||
@@ -466,7 +466,7 @@ async def approve_task(
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = user.get("tenant_no", "zkxw")
|
||||
tenant_no = user.get("tenant_no", "shanxia2.0")
|
||||
engine = WorkflowEngine(db)
|
||||
instance = engine.approve_task(task_id, body.comment or "", tenant_no)
|
||||
return success_response({"instanceId": instance.id, "status": instance.status}, message="审批成功")
|
||||
@@ -482,7 +482,7 @@ async def reject_task(
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
tenant_no = user.get("tenant_no", "zkxw")
|
||||
tenant_no = user.get("tenant_no", "shanxia2.0")
|
||||
engine = WorkflowEngine(db)
|
||||
instance = engine.reject_task(task_id, body.comment or "", tenant_no)
|
||||
return success_response({"instanceId": instance.id, "status": instance.status}, message="已驳回")
|
||||
|
||||
Reference in new issue
Block a user