feat(pl): 实现合同产品用证与额度结转以支持购买证和运输证全流程管理。
This commit is contained in:
1 parent
cb0344498a
commit
fb866c7fa7
104 files changed
+10187
-3833
No files matched your search
@@ -14,8 +14,11 @@ from app.api.pl.vehicle_fuel_card import router as vehicle_fuel_card_router
|
||||
from app.api.pl.dispatch_calendar import router as dispatch_calendar_router
|
||||
from app.api.pl.site_dispatch_calendar import router as site_dispatch_calendar_router
|
||||
from app.api.wechat_notices import router as wechat_notices_router
|
||||
from app.api.pl.quota_cert import router as quota_cert_router, legal_router as legal_use_document_router
|
||||
|
||||
__all__ = [
|
||||
"quota_cert_router",
|
||||
"legal_use_document_router",
|
||||
"wechat_notices_router",
|
||||
"public_router",
|
||||
"menu_router",
|
||||
|
||||
+43
-61
@@ -1,3 +1,4 @@
|
||||
from app.services.pl_quota_business import atomic_plan_operation, apply_plan_quota, settle_plan_quota, validate_generic_status, retain_executed_quota
|
||||
"""运输计划管理 - 计划 API"""
|
||||
import re
|
||||
from collections import defaultdict
|
||||
@@ -449,11 +450,6 @@ def _filters_from_params(params: dict, *, db: Session, tenant_no: str) -> list:
|
||||
plan_date_to=_param_get(params, "planDateTo", "plan_date_to"),
|
||||
delivery_time_from=_param_get(params, "deliveryTimeFrom", "delivery_time_from"),
|
||||
delivery_time_to=_param_get(params, "deliveryTimeTo", "delivery_time_to"),
|
||||
cert_upload_status=_param_get(params, "certUploadStatus", "cert_upload_status"),
|
||||
hazard_cert_ready=_param_get(params, "hazardCertReady", "hazard_cert_ready"),
|
||||
hazard_cert_ready_in=_param_get(
|
||||
params, "hazardCertReadyIn", "hazard_cert_ready_in"
|
||||
),
|
||||
supplier_name=_param_get(params, "supplierName", "supplier_name"),
|
||||
destination_name=_param_get(params, "destinationName", "destination_name"),
|
||||
erp_entered=_param_get(params, "erpEntered", "erp_entered"),
|
||||
@@ -2152,6 +2148,7 @@ def create_plan(
|
||||
db: Session = Depends(get_db),
|
||||
user: DbUserContext = Depends(get_db_current_user),
|
||||
) -> PlanRead:
|
||||
validate_generic_status(payload)
|
||||
tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
|
||||
from app.services.pl_plan_stop_service import assert_plan_create_child_ids
|
||||
assert_plan_create_child_ids(payload)
|
||||
@@ -2683,7 +2680,13 @@ def update_plan(
|
||||
user: DbUserContext = Depends(get_db_current_user),
|
||||
) -> PlanWithProducts:
|
||||
tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
|
||||
plan = _get_plan(db, tenant_no, id, user)
|
||||
plan = _get_plan(db, tenant_no, id, user, lock=True)
|
||||
validate_generic_status(payload, plan)
|
||||
if plan.transport_status == "arranged" and payload.model_fields_set.intersection({
|
||||
'products', 'load', 'deliveries', 'vehicle_id', 'license_plate', 'trailer_no', 'plan_type', 'transport'
|
||||
}):
|
||||
raise HTTPException(409, "已安排计划的用证来源及运输资料请通过调整运输变更")
|
||||
|
||||
|
||||
if plan.follow_status == "cancelled":
|
||||
raise HTTPException(status_code=400, detail="已作废的计划不能修改")
|
||||
@@ -3139,29 +3142,7 @@ def patch_plan_hazard_cert_ready(
|
||||
db: Session = Depends(get_db),
|
||||
user: DbUserContext = Depends(get_db_current_user),
|
||||
) -> PlanWithProducts:
|
||||
"""标记或取消危化品证书齐备(人工确认)"""
|
||||
tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
|
||||
_get_plan(db, tenant_no, id, user)
|
||||
set_hazard_cert_ready(
|
||||
db,
|
||||
tenant_no=tenant_no,
|
||||
plan_id=id,
|
||||
ready=payload.ready,
|
||||
user_id=user.id,
|
||||
)
|
||||
plan = _get_plan(db, tenant_no, id, user)
|
||||
products = (
|
||||
db.query(PlPlanProduct)
|
||||
.filter(
|
||||
PlPlanProduct.plan_id == id,
|
||||
PlPlanProduct.del_flag == 0,
|
||||
)
|
||||
.order_by(PlPlanProduct.order_num)
|
||||
.all()
|
||||
)
|
||||
result = PlanWithProducts.model_validate(plan)
|
||||
result.products = products
|
||||
return result
|
||||
raise HTTPException(410, "人工齐备标记已停用,请配置并核验双证额度")
|
||||
|
||||
|
||||
@router.patch("/{id}/erp-entered", response_model=PlanWithProducts)
|
||||
@@ -3264,6 +3245,8 @@ def get_plan_arrange_info(
|
||||
db.query(PlPlanProduct)
|
||||
.filter(
|
||||
PlPlanProduct.id == link.plan_product_id,
|
||||
PlPlanProduct.tenant_no == tenant_no,
|
||||
PlPlanProduct.plan_id == id,
|
||||
PlPlanProduct.del_flag == 0,
|
||||
)
|
||||
.first()
|
||||
@@ -3406,7 +3389,10 @@ def force_plan_follow_status(
|
||||
)
|
||||
|
||||
tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
|
||||
plan = _get_plan(db, tenant_no, id, user)
|
||||
plan = _get_plan(db, tenant_no, id, user, lock=True)
|
||||
|
||||
if next_status != plan.follow_status and (plan.follow_status in ('arranged', 'completed', 'cancelled') or next_status in ('arranged', 'completed', 'cancelled') or plan.transport_status == 'arranged' or plan.archive_status in ('archived', 'exception')):
|
||||
raise HTTPException(409, "正式状态必须通过安排、归档或作废操作变更")
|
||||
|
||||
plan.follow_status = next_status
|
||||
plan.update_by = user.id
|
||||
@@ -3421,6 +3407,7 @@ def force_plan_follow_status(
|
||||
|
||||
|
||||
@router.post("/{id}/cancel", response_model=PlanRead)
|
||||
@atomic_plan_operation("cancel")
|
||||
def cancel_plan(
|
||||
id: str,
|
||||
body: Optional[CancelReasonBody] = Body(default=None),
|
||||
@@ -3443,6 +3430,8 @@ def cancel_plan(
|
||||
status_code=400, detail=execution_lock_message(lock_reason, "void")
|
||||
)
|
||||
|
||||
apply_plan_quota(db, user, plan, "release", body)
|
||||
|
||||
if plan.transport_id:
|
||||
transport = (
|
||||
db.query(PlTransport)
|
||||
@@ -3485,7 +3474,7 @@ def cancel_plan(
|
||||
plan.cancel_time = now
|
||||
plan.cancel_by = user.id
|
||||
plan.update_by = user.id
|
||||
db.commit()
|
||||
db.flush()
|
||||
db.refresh(plan)
|
||||
return plan
|
||||
|
||||
@@ -3532,6 +3521,7 @@ def preview_force_void_plan(
|
||||
|
||||
|
||||
@router.post("/{id}/force-void", response_model=PlanRead)
|
||||
@atomic_plan_operation("force_void")
|
||||
def force_void_plan(
|
||||
id: str,
|
||||
body: Optional[CancelReasonBody] = Body(default=None),
|
||||
@@ -3544,6 +3534,8 @@ def force_void_plan(
|
||||
if not reason:
|
||||
raise HTTPException(status_code=400, detail="请填写作废原因")
|
||||
|
||||
retain_executed_quota(db, user, plan, reason)
|
||||
|
||||
apply_force_void_downstream(
|
||||
db,
|
||||
tenant_no=tenant_no,
|
||||
@@ -3560,7 +3552,7 @@ def force_void_plan(
|
||||
plan.cancel_time = now
|
||||
plan.cancel_by = user.id
|
||||
plan.update_by = user.id
|
||||
db.commit()
|
||||
db.flush()
|
||||
db.refresh(plan)
|
||||
return plan
|
||||
|
||||
@@ -3652,6 +3644,7 @@ def archive_plan_draft(
|
||||
|
||||
|
||||
@router.post("/{id}/archive", response_model=PlanWithProducts)
|
||||
@atomic_plan_operation("archive")
|
||||
def archive_plan(
|
||||
id: str,
|
||||
payload: Optional[PlanArchiveBody] = Body(default=None),
|
||||
@@ -3680,17 +3673,9 @@ def archive_plan(
|
||||
.order_by(PlPlanProduct.order_num)
|
||||
.all()
|
||||
)
|
||||
validate_hazard_cert_ready_for_transport(db, tenant_no, plan, products)
|
||||
|
||||
if payload is None:
|
||||
if already_archived:
|
||||
raise HTTPException(status_code=400, detail="计划已归档,请提交归档表单以调整内容")
|
||||
plan.archive_status = "archived"
|
||||
plan.complete_status = "yes"
|
||||
plan.follow_status = "completed"
|
||||
plan.update_by = user.id
|
||||
db.commit()
|
||||
return get_plan(id, db, user)
|
||||
raise HTTPException(400, "请提交完整归档表单及实际数量")
|
||||
|
||||
use_stop_archive = payload.load is not None and payload.deliveries is not None
|
||||
if use_stop_archive:
|
||||
@@ -3736,26 +3721,14 @@ def archive_plan(
|
||||
items=payload.products,
|
||||
user_id=user.id,
|
||||
)
|
||||
apply_archive_inventory_for_plan_stops(
|
||||
db,
|
||||
tenant_no=tenant_no,
|
||||
plan=plan,
|
||||
user_id=user.id,
|
||||
dept_id=user.dept_id or "",
|
||||
)
|
||||
|
||||
else:
|
||||
if not payload.products:
|
||||
raise HTTPException(status_code=400, detail="请提交产品归档明细")
|
||||
apply_archive_product_quantities(
|
||||
db, tenant_no=tenant_no, plan=plan, items=payload.products, user_id=user.id
|
||||
)
|
||||
apply_archive_inventory_for_plan(
|
||||
db,
|
||||
tenant_no=tenant_no,
|
||||
plan=plan,
|
||||
user_id=user.id,
|
||||
dept_id=user.dept_id or "",
|
||||
)
|
||||
|
||||
if payload.freight is not None:
|
||||
apply_archive_freight(
|
||||
db, tenant_no=tenant_no, plan=plan, freight=payload.freight, user_id=user.id
|
||||
@@ -3774,7 +3747,11 @@ def archive_plan(
|
||||
dept_id=user.dept_id or "",
|
||||
)
|
||||
|
||||
if not already_archived:
|
||||
quota_settled = settle_plan_quota(db, user, plan, payload, adjustment=already_archived)
|
||||
if quota_settled:
|
||||
inventory_action = apply_archive_inventory_for_plan_stops if use_stop_archive else apply_archive_inventory_for_plan
|
||||
inventory_action(db, tenant_no=tenant_no, plan=plan, user_id=user.id, dept_id=user.dept_id or "")
|
||||
if not already_archived and quota_settled:
|
||||
plan.archive_status = "archived"
|
||||
plan.complete_status = "yes"
|
||||
plan.follow_status = "completed"
|
||||
@@ -3790,8 +3767,11 @@ def archive_plan(
|
||||
user_name=user.name or None,
|
||||
dept_id=user.dept_id,
|
||||
)
|
||||
db.commit()
|
||||
return get_plan(id, db, user)
|
||||
db.flush()
|
||||
result = get_plan(id, db, user)
|
||||
if not quota_settled:
|
||||
result.quota_settlement_error = "实际数量已保存,额度结转失败;请核对用证明细后重新提交"
|
||||
return result
|
||||
|
||||
|
||||
@router.patch("/{id}/driver-feedback", response_model=PlanWithProducts)
|
||||
@@ -4044,16 +4024,18 @@ def delete_plan(
|
||||
# =============================================================================
|
||||
|
||||
|
||||
def _get_plan(db: Session, tenant_no: str, plan_id: str, user: DbUserContext) -> PlPlan:
|
||||
plan = (
|
||||
def _get_plan(db: Session, tenant_no: str, plan_id: str, user: DbUserContext, *, lock: bool = False) -> PlPlan:
|
||||
query = (
|
||||
db.query(PlPlan)
|
||||
.filter(
|
||||
PlPlan.id == plan_id,
|
||||
PlPlan.tenant_no == tenant_no,
|
||||
PlPlan.del_flag == 0,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if lock:
|
||||
query = query.with_for_update().populate_existing()
|
||||
plan = query.first()
|
||||
if not plan:
|
||||
raise HTTPException(status_code=404, detail="计划不存在")
|
||||
assert_pl_row_in_scope(db, plan, PlPlan, user, tenant_no)
|
||||
|
||||
@@ -0,0 +1,229 @@
|
||||
"""共享证件档案、合同产品适用范围与合法使用证明入口。"""
|
||||
from dataclasses import replace
|
||||
from decimal import Decimal
|
||||
from typing import Literal, Optional
|
||||
|
||||
from fastapi import APIRouter, Body, Depends, HTTPException, Query
|
||||
from fastapi.encoders import jsonable_encoder
|
||||
from pydantic import ValidationError, Field
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.core.database import get_db
|
||||
from app.core.db_auth import DbUserContext, get_db_current_user
|
||||
from app.core.menu_guard import require_menu_code
|
||||
from app.core.oper_log_decorator import oper_log
|
||||
from app.core.tenant_context import get_tenant_no
|
||||
from app.schemas.pl.quota_cert import InputBody, CertConfirmBody, CertVerifyBody, CertTotalAdjustBody
|
||||
from app.schemas.pl.quota_scope import ContractCertBindingsBody
|
||||
from app.schemas.pl.legal_use_document import LegalDocumentsBody
|
||||
from app.schemas.pl.quota_planning import PlanQuotaConfiguration, PlanQuotaPreview
|
||||
from app.services import pl_quota_cert_service as certs
|
||||
from app.services import pl_quota_contract_service as scopes
|
||||
from app.services import pl_quota_contract_query as contract_query
|
||||
from app.services import pl_legal_use_document as documents
|
||||
from app.services import pl_quota_planning as planning
|
||||
from app.services import pl_quota_adjustment as adjustment
|
||||
from app.services import pl_quota_overview as overview
|
||||
from app.services.pl_quota_allocation import AllocationIncomplete, InsufficientQuota
|
||||
from app.services.pl_quota_attachments import read_image
|
||||
from app.services.pl_quota_recognition import recognize_quota_cert
|
||||
|
||||
router = APIRouter(prefix='/transport/quota-certs', tags=['购买证与运输证'],
|
||||
dependencies=[Depends(require_menu_code('pl:quota-cert:list'))])
|
||||
legal_router = APIRouter(prefix='/transport/legal-use-documents', tags=['合法使用证明'],
|
||||
dependencies=[Depends(require_menu_code('pl:legal-use-document:list'))])
|
||||
CertType = Literal['purchase', 'transport']
|
||||
|
||||
|
||||
def current_user(db: Session = Depends(get_db), user: DbUserContext = Depends(get_db_current_user)):
|
||||
return replace(user, tenant_no=get_tenant_no(db, user.to_tenant_user_dict()))
|
||||
|
||||
|
||||
def _wire(value):
|
||||
return jsonable_encoder(value, custom_encoder={Decimal: str})
|
||||
|
||||
|
||||
def _write(db, action):
|
||||
try:
|
||||
result = action()
|
||||
db.commit()
|
||||
return _wire(result)
|
||||
except ValidationError as error:
|
||||
db.rollback()
|
||||
# 不回显输入值,避免识别或附件请求中的敏感信息进入错误日志。
|
||||
raise HTTPException(422, [{'loc': e['loc'], 'msg': e['msg'], 'type': e['type']} for e in error.errors()]) from None
|
||||
except Exception:
|
||||
db.rollback()
|
||||
raise
|
||||
|
||||
|
||||
class RecognizeBody(InputBody):
|
||||
attachment_url: str = Field(min_length=1, max_length=2000)
|
||||
|
||||
|
||||
@router.get('/plans')
|
||||
def plan_overview(keyword: str = '', status: Optional[str] = None,
|
||||
page: int = Query(1, ge=1), page_size: int = Query(20, alias='pageSize', ge=1, le=100),
|
||||
db: Session = Depends(get_db), user: DbUserContext = Depends(current_user)):
|
||||
return _wire(overview.list_plans(db, user, keyword, status, page, page_size))
|
||||
|
||||
|
||||
@router.get('/plans/{plan_id}/usage')
|
||||
def plan_quota(plan_id: str, db: Session = Depends(get_db), user: DbUserContext = Depends(current_user)):
|
||||
return _wire(planning.get_plan_quota(db, user, plan_id))
|
||||
|
||||
|
||||
def _preview_body(body):
|
||||
values = body.model_dump(exclude={'target_license_plate', 'target_trailer_no'})
|
||||
vehicle = {}
|
||||
if 'target_license_plate' in body.model_fields_set:
|
||||
vehicle['licensePlate'] = body.target_license_plate
|
||||
if 'target_trailer_no' in body.model_fields_set:
|
||||
vehicle['trailerNo'] = body.target_trailer_no
|
||||
return PlanQuotaConfiguration.model_validate(values), vehicle or None
|
||||
|
||||
|
||||
@router.post('/plans/{plan_id}/context')
|
||||
def plan_configuration_context(plan_id: str, body: PlanQuotaPreview, db: Session = Depends(get_db),
|
||||
user: DbUserContext = Depends(current_user)):
|
||||
config, vehicle = _preview_body(body)
|
||||
return _wire(planning.configuration_context(db, user, plan_id, config, vehicle))
|
||||
|
||||
|
||||
@router.post('/plans/{plan_id}/preview')
|
||||
def preview_plan(plan_id: str, body: PlanQuotaPreview, db: Session = Depends(get_db),
|
||||
user: DbUserContext = Depends(current_user)):
|
||||
try:
|
||||
config, vehicle = _preview_body(body)
|
||||
return _wire(planning.preview_plan(db, user, plan_id, config, vehicle))
|
||||
except AllocationIncomplete:
|
||||
return {'status': 'calculation_incomplete', 'reasons': ['分配计算尚未完成,请缩小候选范围或调整后重试']}
|
||||
except InsufficientQuota as error:
|
||||
return {'status': 'insufficient', 'reasons': [str(error)],
|
||||
'diagnostics': getattr(error, 'diagnostics', [])}
|
||||
except ValueError as error:
|
||||
return {'status': 'needs_configuration', 'reasons': [str(error)]}
|
||||
|
||||
|
||||
@router.put('/plans/{plan_id}/configuration', dependencies=[Depends(require_menu_code('pl:quota-cert:edit'))])
|
||||
@oper_log('计划用证配置', business_type=2, path_param='plan_id')
|
||||
def save_plan_configuration(plan_id: str, body: PlanQuotaConfiguration,
|
||||
db: Session = Depends(get_db), user: DbUserContext = Depends(current_user)):
|
||||
return _write(db, lambda: planning.save_configuration(db, user, plan_id, body))
|
||||
|
||||
|
||||
@router.get('/contracts')
|
||||
def contract_options(keyword: Optional[str] = None, db: Session = Depends(get_db),
|
||||
user: DbUserContext = Depends(current_user)):
|
||||
return contract_query.contract_options(db, user, keyword)
|
||||
|
||||
|
||||
@router.get('/contracts/{contract_id}/products')
|
||||
def contract_products(contract_id: str, db: Session = Depends(get_db), user: DbUserContext = Depends(current_user)):
|
||||
return _wire(contract_query.contract_products(db, user, contract_id))
|
||||
|
||||
|
||||
@router.get('/contracts/{contract_id}/bindings')
|
||||
def get_bindings(contract_id: str, db: Session = Depends(get_db), user: DbUserContext = Depends(current_user)):
|
||||
return _wire(scopes.get_contract_bindings(db, user, contract_id))
|
||||
|
||||
|
||||
@router.put('/contracts/{contract_id}/bindings', dependencies=[Depends(require_menu_code('pl:quota-cert:edit'))])
|
||||
@oper_log('合同适用证件', business_type=2, path_param='contract_id')
|
||||
def save_bindings(contract_id: str, body: ContractCertBindingsBody,
|
||||
db: Session = Depends(get_db), user: DbUserContext = Depends(current_user)):
|
||||
return _write(db, lambda: scopes.save_contract_bindings(db, user, contract_id, body))
|
||||
|
||||
|
||||
@router.get('/{cert_type}')
|
||||
def list_certs(cert_type: CertType, keyword: Optional[str] = None, status: Optional[str] = None,
|
||||
db: Session = Depends(get_db), user: DbUserContext = Depends(current_user)):
|
||||
return _wire(certs.list_certs(db, user, cert_type, keyword, status))
|
||||
|
||||
|
||||
@router.post('/{cert_type}/recognize', dependencies=[Depends(require_menu_code('pl:quota-cert:edit'))])
|
||||
@oper_log('解析证件图片')
|
||||
def recognize(cert_type: CertType, body: RecognizeBody,
|
||||
db: Session = Depends(get_db), user: DbUserContext = Depends(current_user)):
|
||||
return _wire(recognize_quota_cert(cert_type, read_image(db, user, body.attachment_url)))
|
||||
|
||||
|
||||
@router.post('/{cert_type}', dependencies=[Depends(require_menu_code('pl:quota-cert:edit'))])
|
||||
@oper_log('证件档案', business_type=1)
|
||||
def create_cert(cert_type: CertType, body: dict = Body(...),
|
||||
db: Session = Depends(get_db), user: DbUserContext = Depends(current_user)):
|
||||
return _write(db, lambda: certs.save_cert(db, user, cert_type, body))
|
||||
|
||||
|
||||
@router.get('/{cert_type}/{cert_id}')
|
||||
def get_cert(cert_type: CertType, cert_id: str,
|
||||
db: Session = Depends(get_db), user: DbUserContext = Depends(current_user)):
|
||||
return _wire(certs.get_cert(db, user, cert_type, cert_id))
|
||||
|
||||
|
||||
@router.get('/{cert_type}/{cert_id}/contracts')
|
||||
def certificate_contracts(cert_type: CertType, cert_id: str, db: Session = Depends(get_db),
|
||||
user: DbUserContext = Depends(current_user)):
|
||||
return contract_query.certificate_contracts(db, user, cert_type, cert_id)
|
||||
|
||||
|
||||
@router.put('/{cert_type}/{cert_id}', dependencies=[Depends(require_menu_code('pl:quota-cert:edit'))])
|
||||
@oper_log('证件档案', business_type=2, path_param='cert_id')
|
||||
def update_cert(cert_type: CertType, cert_id: str, body: dict = Body(...),
|
||||
db: Session = Depends(get_db), user: DbUserContext = Depends(current_user)):
|
||||
return _write(db, lambda: certs.save_cert(db, user, cert_type, body, cert_id))
|
||||
|
||||
|
||||
@router.delete('/{cert_type}/{cert_id}', dependencies=[Depends(require_menu_code('pl:quota-cert:edit'))])
|
||||
@oper_log('证件档案', business_type=3, path_param='cert_id')
|
||||
def delete_cert(cert_type: CertType, cert_id: str,
|
||||
db: Session = Depends(get_db), user: DbUserContext = Depends(current_user)):
|
||||
def action():
|
||||
certs.delete_cert(db, user, cert_type, cert_id)
|
||||
return {'deleted': True}
|
||||
return _write(db, action)
|
||||
|
||||
|
||||
@router.post('/{cert_type}/{cert_id}/confirm', dependencies=[Depends(require_menu_code('pl:quota-cert:edit'))])
|
||||
@oper_log('证件期初确认', business_type=2, path_param='cert_id')
|
||||
def confirm_cert(cert_type: CertType, cert_id: str, body: CertConfirmBody,
|
||||
db: Session = Depends(get_db), user: DbUserContext = Depends(current_user)):
|
||||
return _write(db, lambda: certs.confirm_cert(db, user, cert_type, cert_id, body))
|
||||
|
||||
|
||||
@router.post('/{cert_type}/{cert_id}/verify', dependencies=[Depends(require_menu_code('pl:quota-cert:edit'))])
|
||||
@oper_log('证件复核', business_type=2, path_param='cert_id')
|
||||
def verify_cert(cert_type: CertType, cert_id: str, body: CertVerifyBody,
|
||||
db: Session = Depends(get_db), user: DbUserContext = Depends(current_user)):
|
||||
return _write(db, lambda: certs.verify_cert(db, user, cert_type, cert_id, body))
|
||||
|
||||
|
||||
@router.get('/{cert_type}/{cert_id}/logs')
|
||||
def cert_logs(cert_type: CertType, cert_id: str, db: Session = Depends(get_db),
|
||||
user: DbUserContext = Depends(current_user)):
|
||||
return _wire(adjustment.list_logs(db, user, cert_type, cert_id))
|
||||
|
||||
|
||||
@router.post('/{cert_type}/{cert_id}/total-adjust', dependencies=[Depends(require_menu_code('pl:quota-cert:edit'))])
|
||||
@oper_log('证件核定总量更正', business_type=2, path_param='cert_id')
|
||||
def adjust_cert_total(cert_type: CertType, cert_id: str, body: CertTotalAdjustBody,
|
||||
db: Session = Depends(get_db), user: DbUserContext = Depends(current_user)):
|
||||
return _write(db, lambda: adjustment.adjust_total(db, user, cert_type, cert_id, body))
|
||||
|
||||
|
||||
@legal_router.get('')
|
||||
def list_documents(keyword: Optional[str] = None, status: Optional[str] = None,
|
||||
db: Session = Depends(get_db), user: DbUserContext = Depends(current_user)):
|
||||
return documents.list_documents(db, user, keyword, status)
|
||||
|
||||
|
||||
@legal_router.get('/{plan_id}')
|
||||
def get_documents(plan_id: str, db: Session = Depends(get_db), user: DbUserContext = Depends(current_user)):
|
||||
return documents.get_documents(db, user, plan_id)
|
||||
|
||||
|
||||
@legal_router.patch('/{plan_id}')
|
||||
@oper_log('合法使用证明', business_type=2, path_param='plan_id')
|
||||
def save_documents(plan_id: str, body: LegalDocumentsBody,
|
||||
db: Session = Depends(get_db), user: DbUserContext = Depends(current_user)):
|
||||
return _write(db, lambda: documents.save_documents(db, user, plan_id, body))
|
||||
@@ -1,3 +1,4 @@
|
||||
from app.services.pl_quota_business import atomic_plan_operation, apply_plan_quota, assert_plan_can_arrange, assert_transport_exclusive_to_plan
|
||||
"""运输计划管理 - 运输 API"""
|
||||
from datetime import date, datetime
|
||||
from typing import List, Optional
|
||||
@@ -281,52 +282,19 @@ def _resolve_driver_info(db: Session, tenant_no: str, driver_id: Optional[str])
|
||||
|
||||
|
||||
def _get_vehicle_info(db: Session, vehicle_id: str, tenant_no: Optional[str] = None) -> dict:
|
||||
vehicle = db.query(PlVehicle).filter(PlVehicle.id == vehicle_id).first()
|
||||
if not tenant_no:
|
||||
raise HTTPException(400, "车辆查询必须提供当前租户")
|
||||
vehicle = db.query(PlVehicle).filter(
|
||||
PlVehicle.id == vehicle_id, PlVehicle.tenant_no == tenant_no, PlVehicle.del_flag == 0,
|
||||
).with_for_update().populate_existing().first()
|
||||
if not vehicle:
|
||||
return {}
|
||||
|
||||
info = {
|
||||
"license_plate": vehicle.license_plate,
|
||||
"carrier_id": vehicle.carrier_id,
|
||||
"carrier_name": vehicle.carrier_name,
|
||||
}
|
||||
|
||||
raise HTTPException(400, "车辆不存在")
|
||||
info = {"license_plate": vehicle.license_plate, "carrier_id": vehicle.carrier_id,
|
||||
"carrier_name": vehicle.carrier_name}
|
||||
if vehicle.default_driver_id:
|
||||
driver_info = (
|
||||
_resolve_driver_info(db, tenant_no, vehicle.default_driver_id)
|
||||
if tenant_no
|
||||
else None
|
||||
)
|
||||
if not driver_info:
|
||||
personnel = db.query(PlPersonnel).filter(
|
||||
PlPersonnel.id == vehicle.default_driver_id,
|
||||
PlPersonnel.del_flag == 0,
|
||||
).first()
|
||||
if personnel:
|
||||
driver_info = {
|
||||
"id": personnel.id,
|
||||
"name": personnel.personnel_name,
|
||||
"phone": personnel.phone_no,
|
||||
}
|
||||
else:
|
||||
legacy = db.query(PlDriver).filter(
|
||||
PlDriver.id == vehicle.default_driver_id,
|
||||
PlDriver.del_flag == 0,
|
||||
).first()
|
||||
if legacy:
|
||||
driver_info = {
|
||||
"id": legacy.id,
|
||||
"name": legacy.driver_name,
|
||||
"phone": legacy.phone_no,
|
||||
}
|
||||
driver_info = _resolve_driver_info(db, tenant_no, vehicle.default_driver_id)
|
||||
if driver_info:
|
||||
info["driver_id"] = driver_info["id"]
|
||||
info["driver_name"] = driver_info["name"]
|
||||
info["driver_phone"] = driver_info["phone"]
|
||||
elif vehicle.default_driver_name:
|
||||
info["driver_id"] = vehicle.default_driver_id
|
||||
info["driver_name"] = vehicle.default_driver_name
|
||||
|
||||
info.update(driver_id=driver_info['id'], driver_name=driver_info['name'], driver_phone=driver_info['phone'])
|
||||
return info
|
||||
|
||||
|
||||
@@ -344,7 +312,7 @@ def _assert_vehicle_carrier_eligible(
|
||||
PlVehicle.tenant_no == tenant_no,
|
||||
PlVehicle.del_flag == 0,
|
||||
)
|
||||
.first()
|
||||
.with_for_update().populate_existing().first()
|
||||
)
|
||||
if not vehicle:
|
||||
raise HTTPException(status_code=400, detail="车辆不存在")
|
||||
@@ -358,7 +326,7 @@ def _assert_vehicle_carrier_eligible(
|
||||
PlCarrier.tenant_no == tenant_no,
|
||||
PlCarrier.del_flag == 0,
|
||||
)
|
||||
.first()
|
||||
.with_for_update().populate_existing().first()
|
||||
)
|
||||
if not carrier:
|
||||
raise HTTPException(status_code=400, detail="承运商不存在")
|
||||
@@ -647,6 +615,9 @@ def create_transport(
|
||||
) -> TransportRead:
|
||||
tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
|
||||
|
||||
if payload.transport_status != "draft" or payload.approval_status != "none":
|
||||
raise HTTPException(409, "正式运输必须通过安排运输操作")
|
||||
|
||||
transport_no = _generate_transport_no(db)
|
||||
|
||||
transport = PlTransport(
|
||||
@@ -695,8 +666,13 @@ def create_transport(
|
||||
db.add(pt)
|
||||
|
||||
# 更新计划关联的运输信息
|
||||
plan = db.query(PlPlan).filter(PlPlan.id == pid, PlPlan.del_flag == 0).first()
|
||||
plan = db.query(PlPlan).filter(PlPlan.id == pid, PlPlan.tenant_no == tenant_no, PlPlan.del_flag == 0).with_for_update().populate_existing().first()
|
||||
if not plan:
|
||||
raise HTTPException(404, "计划不存在")
|
||||
if plan:
|
||||
assert_plan_can_arrange(plan)
|
||||
if plan.transport_status == "arranged" or plan.archive_status == "archived":
|
||||
raise HTTPException(409, "已安排计划必须通过调整运输操作")
|
||||
assert_pl_row_in_scope(db, plan, PlPlan, user, tenant_no)
|
||||
plan.transport_id = transport.id
|
||||
plan.transport_no = transport_no
|
||||
@@ -730,6 +706,7 @@ def create_transport(
|
||||
|
||||
|
||||
@router.post("/arrange/{plan_id}", response_model=TransportArrangeResult, status_code=status.HTTP_201_CREATED)
|
||||
@atomic_plan_operation("arrange")
|
||||
def arrange_transport(
|
||||
plan_id: str,
|
||||
payload: TransportArrange,
|
||||
@@ -747,6 +724,7 @@ def arrange_transport(
|
||||
if not plan:
|
||||
raise HTTPException(status_code=404, detail="计划不存在")
|
||||
assert_pl_row_in_scope(db, plan, PlPlan, user, tenant_no)
|
||||
assert_plan_can_arrange(plan)
|
||||
|
||||
assert_no_pending_stop_products(db, tenant_no, plan_id)
|
||||
|
||||
@@ -756,7 +734,10 @@ def arrange_transport(
|
||||
PlTransport.id == plan.transport_id,
|
||||
PlTransport.tenant_no == tenant_no,
|
||||
PlTransport.del_flag == 0,
|
||||
).first()
|
||||
).with_for_update().populate_existing().first()
|
||||
|
||||
if existing_transport:
|
||||
assert_transport_exclusive_to_plan(db, tenant_no, plan.id, existing_transport.id)
|
||||
|
||||
is_rearrange = _is_rearrange(plan, existing_transport)
|
||||
|
||||
@@ -801,10 +782,10 @@ def arrange_transport(
|
||||
# 检查产品属性(易制毒/易制爆需要证件,以 CRM 产品主数据为准)
|
||||
products = db.query(PlPlanProduct).filter(
|
||||
PlPlanProduct.plan_id == plan_id,
|
||||
PlPlanProduct.tenant_no == tenant_no,
|
||||
PlPlanProduct.del_flag == 0,
|
||||
).all()
|
||||
|
||||
validate_hazard_cert_ready_for_transport(db, tenant_no, plan, products)
|
||||
|
||||
from app.services.pl_contract_plan_qty import (
|
||||
assert_contract_qty_for_arrange,
|
||||
@@ -908,6 +889,7 @@ def arrange_transport(
|
||||
plan.follow_status = "arranged"
|
||||
plan.freight_amount = freight_amount or 0
|
||||
plan.update_by = user.id
|
||||
apply_plan_quota(db, user, plan, "resize" if is_rearrange else "reserve", payload)
|
||||
|
||||
# 安排运输时:关联且仍为「已审批」的合同自动开始执行
|
||||
from app.services.pl_contract_plan_qty import auto_start_execute_approved_contracts
|
||||
@@ -1088,7 +1070,7 @@ def arrange_transport(
|
||||
db, tenant_no=tenant_no, plan=plan, transport=transport
|
||||
)
|
||||
|
||||
db.commit()
|
||||
db.flush()
|
||||
db.refresh(transport)
|
||||
return _build_arrange_result(
|
||||
transport,
|
||||
@@ -1249,6 +1231,7 @@ def submit_approval(
|
||||
|
||||
|
||||
@router.post("/approval/{id}", response_model=ApprovalRecordRead)
|
||||
@atomic_plan_operation("approval")
|
||||
def process_approval(
|
||||
id: str,
|
||||
payload: ApprovalRequest,
|
||||
@@ -1269,6 +1252,10 @@ def process_approval(
|
||||
if not approval:
|
||||
raise HTTPException(status_code=404, detail="审批记录不存在")
|
||||
|
||||
# 指定审批人操作;平台超级管理员保留明确的管理代办权限。
|
||||
if approval.approver_id != user.id and getattr(user, 'role', None) != 'super_admin':
|
||||
raise HTTPException(403, "仅指定审批人可以处理该审批")
|
||||
|
||||
if approval.status != "pending":
|
||||
raise HTTPException(status_code=400, detail="该审批已处理")
|
||||
|
||||
@@ -1278,29 +1265,57 @@ def process_approval(
|
||||
approval.status = "approved" if payload.action == "approve" else "rejected"
|
||||
approval.comment = payload.comment
|
||||
approval.approval_time = datetime.now()
|
||||
db.flush()
|
||||
|
||||
# 更新运输审批状态
|
||||
transport = db.query(PlTransport).filter(PlTransport.id == approval.transport_id).first()
|
||||
transport = db.query(PlTransport).filter(PlTransport.id == approval.transport_id, PlTransport.tenant_no == tenant_no, PlTransport.del_flag == 0).first()
|
||||
if transport:
|
||||
if transport.transport_status in ('cancelled', 'completed', 'archived'):
|
||||
raise HTTPException(409, "已作废或完成的运输不能审批")
|
||||
if payload.action == "approve":
|
||||
# 检查是否所有审批人都通过了
|
||||
pending = (
|
||||
db.query(PlTransportApproval)
|
||||
.filter(
|
||||
PlTransportApproval.transport_id == approval.transport_id,
|
||||
PlTransportApproval.tenant_no == tenant_no,
|
||||
PlTransportApproval.status == "pending",
|
||||
PlTransportApproval.del_flag == 0,
|
||||
)
|
||||
.count()
|
||||
.with_for_update().populate_existing().all()
|
||||
)
|
||||
if pending == 0:
|
||||
if not pending:
|
||||
plans = db.query(PlPlan).filter(PlPlan.transport_id == transport.id, PlPlan.tenant_no == tenant_no, PlPlan.del_flag == 0).order_by(PlPlan.id).with_for_update().all()
|
||||
for plan in plans:
|
||||
assert_pl_row_in_scope(db, plan, PlPlan, user, tenant_no)
|
||||
assert_plan_can_arrange(plan)
|
||||
if not transport.vehicle_id:
|
||||
raise HTTPException(409, "正式审批必须选择车辆主数据")
|
||||
vehicle_info = _get_vehicle_info(db, transport.vehicle_id, tenant_no)
|
||||
_assert_vehicle_carrier_eligible(db, tenant_no, transport.vehicle_id)
|
||||
vehicle = db.query(PlVehicle).filter_by(id=transport.vehicle_id, tenant_no=tenant_no, del_flag=0).first()
|
||||
assert_pl_row_in_scope(db, vehicle, PlVehicle, user, tenant_no)
|
||||
transport.license_plate = vehicle_info['license_plate']
|
||||
transport.carrier_id = vehicle_info['carrier_id']
|
||||
transport.carrier_name = vehicle_info['carrier_name']
|
||||
snapshot = build_transport_resource_snapshot(db, tenant_no, transport.vehicle_id,
|
||||
selected_driver_id=transport.driver_id, selected_escort_id=transport.escort_id)
|
||||
for plan in plans:
|
||||
assert_pl_row_in_scope(db, plan, PlPlan, user, tenant_no)
|
||||
plan.vehicle_id = transport.vehicle_id
|
||||
plan.license_plate = transport.license_plate
|
||||
apply_resource_snapshot_json(plan=plan, transport=transport, snapshot=snapshot)
|
||||
apply_plan_quota(db, user, plan, "reserve", payload)
|
||||
plan.transport_status = "arranged"
|
||||
plan.follow_status = "arranged"
|
||||
plan.update_by = user.id
|
||||
transport.approval_status = "approved"
|
||||
transport.transport_status = "pending"
|
||||
else:
|
||||
transport.approval_status = "rejected"
|
||||
transport.transport_status = "draft"
|
||||
|
||||
db.commit()
|
||||
db.flush()
|
||||
db.refresh(approval)
|
||||
return approval
|
||||
|
||||
|
||||
Reference in new issue
Block a user