Files
shanxia2.0/backend/app/services/pl_vehicle_recharge_service.py
T

1160 lines
38 KiB
Python

"""车辆 ETC/油卡充值业务逻辑"""
from __future__ import annotations
from datetime import date, datetime
from typing import Optional
from fastapi import HTTPException
from sqlalchemy import and_, func, or_
from sqlalchemy.orm import Session
from app.core.db_auth import DbUserContext
from app.core.utils import generate_uuid
from app.models.bx_models import BxWorkflowDef, BxWorkflowNode
from app.models.models import SysUser
from app.models.pl_models import (
PlVehicle,
PlVehicleRechargeApply,
PlVehicleRechargeApproval,
PlVehicleRechargeRecord,
)
from app.schemas.pl.vehicle_recharge import (
VehicleRechargeApplyCreate,
VehicleRechargeApplyRead,
VehicleRechargeApplyUpdate,
VehicleRechargeApprovalFlowItem,
VehicleRechargeApprovalRead,
VehicleRechargeDisburseBoardItem,
VehicleRechargeRecordCreate,
VehicleRechargeRecordRead,
VehicleRechargeRecordUpdate,
)
from app.services.pl_data_scope import apply_pl_scope, assert_pl_row_in_scope
from app.services.pl_vehicle_mine_vehicles import (
license_plates_for_user_personnel,
should_restrict_mine_vehicles,
)
_EDITABLE_STATUSES = frozenset({"draft", "rejected"})
_BIZ_TYPE_VEHICLE_RECHARGE = "vehicle_recharge"
def _generate_seq_no(
db: Session, model, column_attr: str, prefix: str, *, seq_width: int = 6
) -> str:
column = getattr(model, column_attr)
last = (
db.query(model)
.filter(column.like(f"{prefix}%"))
.order_by(column.desc())
.first()
)
seq = int(getattr(last, column_attr)[-seq_width:]) + 1 if last else 1
return f"{prefix}{seq:0{seq_width}d}"
def generate_apply_no(db: Session) -> str:
return _generate_seq_no(
db,
PlVehicleRechargeApply,
"apply_no",
f"ETC{date.today():%Y%m%d}",
seq_width=2,
)
def generate_recharge_order_no(db: Session) -> str:
return _generate_seq_no(
db,
PlVehicleRechargeRecord,
"recharge_order_no",
f"SXCL{date.today():%Y%m%d}",
)
def _resolve_user_name(db: Session, user_id: Optional[str]) -> Optional[str]:
if not user_id:
return None
row = (
db.query(SysUser)
.filter(SysUser.id == user_id, SysUser.del_flag == 0)
.first()
)
return row.nick_name or row.user_no if row else None
def _assert_vehicle_exists(db: Session, tenant_no: str, license_plate: str) -> None:
exists = (
db.query(PlVehicle.id)
.filter(
PlVehicle.tenant_no == tenant_no,
PlVehicle.license_plate == license_plate,
PlVehicle.del_flag == 0,
)
.first()
)
if not exists:
raise HTTPException(status_code=400, detail="车牌号不存在")
def _resolve_applicant_id(
db: Session,
tenant_no: str,
applicant_id: Optional[str],
user: DbUserContext,
) -> str:
target = (applicant_id or "").strip() or user.id
row = (
db.query(SysUser.id)
.filter(
SysUser.id == target,
SysUser.tenant_no == tenant_no,
SysUser.del_flag == 0,
SysUser.status == "1",
)
.first()
)
if not row:
raise HTTPException(status_code=400, detail="申请人不存在或已停用")
return target
def _get_apply_row(
db: Session,
tenant_no: str,
apply_id: str,
user: DbUserContext,
*,
mine_vehicles: bool = False,
) -> PlVehicleRechargeApply:
row = (
db.query(PlVehicleRechargeApply)
.filter(
PlVehicleRechargeApply.id == apply_id,
PlVehicleRechargeApply.tenant_no == tenant_no,
PlVehicleRechargeApply.del_flag == 0,
)
.first()
)
if not row:
raise HTTPException(status_code=404, detail="申请单不存在")
if should_restrict_mine_vehicles(
db, tenant_no, user.id, mine_vehicles=mine_vehicles
):
plates = license_plates_for_user_personnel(db, tenant_no, user.id)
if row.license_plate not in plates:
raise HTTPException(status_code=403, detail="无权查看该申请")
elif not mine_vehicles:
assert_pl_row_in_scope(db, row, PlVehicleRechargeApply, user, tenant_no)
return row
def _get_record_row(
db: Session, tenant_no: str, record_id: str, user: DbUserContext
) -> PlVehicleRechargeRecord:
row = (
db.query(PlVehicleRechargeRecord)
.filter(
PlVehicleRechargeRecord.id == record_id,
PlVehicleRechargeRecord.tenant_no == tenant_no,
PlVehicleRechargeRecord.del_flag == 0,
)
.first()
)
if not row:
raise HTTPException(status_code=404, detail="发放登记不存在")
assert_pl_row_in_scope(db, row, PlVehicleRechargeRecord, user, tenant_no)
return row
def _has_active_record(db: Session, tenant_no: str, apply_id: str) -> bool:
return (
db.query(PlVehicleRechargeRecord.id)
.filter(
PlVehicleRechargeRecord.apply_id == apply_id,
PlVehicleRechargeRecord.tenant_no == tenant_no,
PlVehicleRechargeRecord.del_flag == 0,
)
.first()
is not None
)
def approval_to_read(row: PlVehicleRechargeApproval) -> VehicleRechargeApprovalRead:
return VehicleRechargeApprovalRead(
id=row.id,
applyId=row.apply_id,
approvalRound=row.approval_round,
nodeId=row.node_id,
nodeName=row.node_name,
approverId=row.approver_id,
approverName=row.approver_name,
approvalStatus=row.approval_status,
approvalOpinion=row.approval_opinion,
approvalTime=row.approval_time,
)
def _list_approval_rows(
db: Session, tenant_no: str, apply_id: str
) -> list[PlVehicleRechargeApproval]:
return (
db.query(PlVehicleRechargeApproval)
.filter(
PlVehicleRechargeApproval.apply_id == apply_id,
PlVehicleRechargeApproval.tenant_no == tenant_no,
PlVehicleRechargeApproval.del_flag == 0,
)
.order_by(
PlVehicleRechargeApproval.approval_round.asc(),
PlVehicleRechargeApproval.approval_time.asc(),
PlVehicleRechargeApproval.create_time.asc(),
)
.all()
)
def _list_approvals(
db: Session, tenant_no: str, apply_id: str
) -> list[VehicleRechargeApprovalRead]:
return [approval_to_read(row) for row in _list_approval_rows(db, tenant_no, apply_id)]
def _approval_flow_item_from_row(
row: PlVehicleRechargeApproval,
*,
node_order: int,
) -> VehicleRechargeApprovalFlowItem:
return VehicleRechargeApprovalFlowItem(
id=row.id,
applyId=row.apply_id,
nodeName=row.node_name or "节点",
nodeOrder=node_order,
approvalRound=row.approval_round,
approvalStatus=row.approval_status,
approvalOpinion=row.approval_opinion,
approverName=row.approver_name or "",
approvalTime=row.approval_time,
)
def _build_approval_flow(
db: Session,
row: PlVehicleRechargeApply,
approval_rows: list[PlVehicleRechargeApproval],
) -> list[VehicleRechargeApprovalFlowItem]:
"""当前轮:流程全部节点;已审带信息,未审为 pending。"""
if not row.wf_id or not (row.approval_round or 0):
return []
nodes = _workflow_nodes(db, row.wf_id, row.tenant_no)
if not nodes:
return []
current_round = row.approval_round or 0
round_approvals = [a for a in approval_rows if (a.approval_round or 0) == current_round]
by_node_id: dict[str, PlVehicleRechargeApproval] = {}
for a in round_approvals:
if not a.node_id:
continue
existing = by_node_id.get(a.node_id)
if existing is None or (a.approval_time or datetime.min) >= (
existing.approval_time or datetime.min
):
by_node_id[a.node_id] = a
result: list[VehicleRechargeApprovalFlowItem] = []
for node in nodes:
approval = by_node_id.get(node.id)
if approval:
result.append(
_approval_flow_item_from_row(approval, node_order=node.node_order or 0)
)
else:
result.append(
VehicleRechargeApprovalFlowItem(
id="0",
applyId=row.id,
nodeName=node.node_name,
nodeOrder=node.node_order or 0,
approvalRound=current_round,
approvalStatus="pending",
approvalOpinion=None,
approverName=node.approver_name or "",
approvalTime=None,
)
)
return result
def _build_approval_history(
db: Session,
row: PlVehicleRechargeApply,
approval_rows: list[PlVehicleRechargeApproval],
) -> list[VehicleRechargeApprovalFlowItem]:
"""全部历史审批动作(含打回前各轮),按时间正序。"""
node_order_map: dict[str, int] = {}
if row.wf_id:
for node in _workflow_nodes(db, row.wf_id, row.tenant_no):
node_order_map[node.id] = node.node_order or 0
result: list[VehicleRechargeApprovalFlowItem] = []
for idx, a in enumerate(approval_rows):
order = node_order_map.get(a.node_id or "", 0) or (idx + 1)
result.append(_approval_flow_item_from_row(a, node_order=order))
return result
def _get_linked_record(
db: Session, tenant_no: str, apply_id: str
) -> Optional[PlVehicleRechargeRecord]:
return (
db.query(PlVehicleRechargeRecord)
.filter(
PlVehicleRechargeRecord.apply_id == apply_id,
PlVehicleRechargeRecord.tenant_no == tenant_no,
PlVehicleRechargeRecord.del_flag == 0,
)
.first()
)
def apply_to_read(
row: PlVehicleRechargeApply,
db: Session,
*,
include_detail: bool = False,
) -> VehicleRechargeApplyRead:
approvals: list[VehicleRechargeApprovalRead] = []
approval_flow: list[VehicleRechargeApprovalFlowItem] = []
approval_history: list[VehicleRechargeApprovalFlowItem] = []
record_read: Optional[VehicleRechargeRecordRead] = None
current_node_name: Optional[str] = None
current_node_action_type: Optional[str] = None
if row.current_node:
node = (
db.query(BxWorkflowNode)
.filter(
BxWorkflowNode.id == row.current_node,
BxWorkflowNode.del_flag == 0,
)
.first()
)
if node:
current_node_name = node.node_name
current_node_action_type = (node.action_type or "approve").strip() or "approve"
if include_detail:
approval_rows = _list_approval_rows(db, row.tenant_no, row.id)
approvals = [approval_to_read(a) for a in approval_rows]
approval_flow = _build_approval_flow(db, row, approval_rows)
approval_history = _build_approval_history(db, row, approval_rows)
record_row = _get_linked_record(db, row.tenant_no, row.id)
if record_row:
record_read = record_to_read(record_row, db, apply_no=row.apply_no)
return VehicleRechargeApplyRead(
id=row.id,
applyNo=row.apply_no,
licensePlate=row.license_plate,
rechargeType=row.recharge_type,
applyDate=row.apply_date,
odometerKm=row.odometer_km,
attachmentUrls=row.attachment_urls,
applicantId=row.applicant_id,
applicantName=_resolve_user_name(db, row.applicant_id),
status=row.status,
cancelReason=row.cancel_reason,
cancelTime=row.cancel_time,
cancelBy=row.cancel_by,
wfId=row.wf_id,
currentNode=row.current_node,
currentNodeName=current_node_name,
currentNodeActionType=current_node_action_type,
approvalRound=row.approval_round or 0,
approvals=approvals,
approvalFlow=approval_flow,
approvalHistory=approval_history,
record=record_read,
remark=row.remark,
createTime=row.create_time,
updateTime=row.update_time,
)
def _workflow_nodes(db: Session, wf_id: str, tenant_no: str) -> list[BxWorkflowNode]:
return (
db.query(BxWorkflowNode)
.filter(
BxWorkflowNode.wf_id == wf_id,
BxWorkflowNode.tenant_no == tenant_no,
BxWorkflowNode.del_flag == 0,
)
.order_by(BxWorkflowNode.node_order.asc())
.all()
)
def _get_vehicle_recharge_workflow(
db: Session, tenant_no: str
) -> BxWorkflowDef:
workflow = (
db.query(BxWorkflowDef)
.filter(
BxWorkflowDef.biz_type == _BIZ_TYPE_VEHICLE_RECHARGE,
BxWorkflowDef.tenant_no == tenant_no,
BxWorkflowDef.del_flag == 0,
BxWorkflowDef.status == 1,
)
.first()
)
if not workflow:
raise HTTPException(status_code=400, detail="未配置启用中的充值审批流程")
return workflow
def record_to_read(
row: PlVehicleRechargeRecord, db: Session, apply_no: Optional[str] = None
) -> VehicleRechargeRecordRead:
if apply_no is None and row.apply_id:
apply = (
db.query(PlVehicleRechargeApply.apply_no)
.filter(
PlVehicleRechargeApply.id == row.apply_id,
PlVehicleRechargeApply.del_flag == 0,
)
.first()
)
apply_no = apply.apply_no if apply else None
return VehicleRechargeRecordRead(
id=row.id,
rechargeOrderNo=row.recharge_order_no,
rechargeDate=row.recharge_date,
rechargeType=row.recharge_type,
cardNo=row.card_no,
gasStation=row.gas_station,
amount=row.amount,
attachmentUrls=row.attachment_urls,
applyId=row.apply_id,
applyNo=apply_no,
licensePlate=row.license_plate,
remark=row.remark,
createBy=row.create_by,
createByName=_resolve_user_name(db, row.create_by),
createTime=row.create_time,
updateTime=row.update_time,
)
def _resolve_apply_for_record(
db: Session,
tenant_no: str,
payload: VehicleRechargeRecordCreate | VehicleRechargeRecordUpdate,
user: DbUserContext,
*,
current_record_id: Optional[str] = None,
) -> tuple[Optional[PlVehicleRechargeApply], str, str]:
license_plate = (payload.license_plate or "").strip()
recharge_type = payload.recharge_type
if payload.apply_id:
apply = _get_apply_row(db, tenant_no, payload.apply_id, user)
if apply.status == "in_approval":
raise HTTPException(
status_code=400,
detail="审批中的申请请在「ETC/油卡充值审批」中完成发放登记",
)
if apply.status != "pending":
raise HTTPException(status_code=400, detail="仅待发放申请可关联")
existing = (
db.query(PlVehicleRechargeRecord)
.filter(
PlVehicleRechargeRecord.apply_id == apply.id,
PlVehicleRechargeRecord.tenant_no == tenant_no,
PlVehicleRechargeRecord.del_flag == 0,
)
.first()
)
if existing and existing.id != current_record_id:
raise HTTPException(status_code=400, detail="该申请单已被关联")
if apply.recharge_type != recharge_type:
raise HTTPException(status_code=400, detail="充值类型与申请单不一致")
return apply, apply.license_plate, apply.recharge_type
if not license_plate:
raise HTTPException(status_code=400, detail="请填写车牌号或关联申请单")
_assert_vehicle_exists(db, tenant_no, license_plate)
return None, license_plate, recharge_type
def list_applies(
db: Session,
tenant_no: str,
user: DbUserContext,
*,
q: Optional[str] = None,
apply_no: Optional[str] = None,
license_plate: Optional[str] = None,
recharge_type: Optional[str] = None,
recharge_type_in: Optional[str] = None,
status: Optional[str] = None,
status_in: Optional[str] = None,
apply_date_from: Optional[date] = None,
apply_date_to: Optional[date] = None,
applicant_id: Optional[str] = None,
applicant_name: Optional[str] = None,
remark: Optional[str] = None,
odometer_km_op: Optional[str] = None,
odometer_km: Optional[str] = None,
odometer_km_min: Optional[str] = None,
odometer_km_max: Optional[str] = None,
create_time_from: Optional[date] = None,
create_time_to: Optional[date] = None,
ids: Optional[list[str]] = None,
page: int = 1,
page_size: int = 20,
max_page_size: Optional[int] = None,
sort_field: Optional[str] = None,
sort_order: Optional[str] = None,
mine_vehicles: bool = False,
) -> tuple[list[VehicleRechargeApplyRead], int]:
query = db.query(PlVehicleRechargeApply).filter(
PlVehicleRechargeApply.tenant_no == tenant_no,
PlVehicleRechargeApply.del_flag == 0,
)
if q:
query = query.filter(
or_(
PlVehicleRechargeApply.apply_no.contains(q),
PlVehicleRechargeApply.license_plate.contains(q),
)
)
from app.services.pl.vehicle_recharge_list_filters import (
build_recharge_apply_column_filters,
)
from app.services.pl.list_sort import order_recharge_apply
column_filters = build_recharge_apply_column_filters(
apply_no=apply_no,
license_plate=license_plate,
recharge_type=recharge_type,
recharge_type_in=recharge_type_in,
status=status,
status_in=status_in,
apply_date_from=apply_date_from,
apply_date_to=apply_date_to,
applicant_name=applicant_name,
remark=remark,
odometer_km_op=odometer_km_op,
odometer_km=odometer_km,
odometer_km_min=odometer_km_min,
odometer_km_max=odometer_km_max,
create_time_from=create_time_from,
create_time_to=create_time_to,
)
if column_filters:
query = query.filter(*column_filters)
if applicant_id:
query = query.filter(PlVehicleRechargeApply.applicant_id == applicant_id)
if ids:
query = query.filter(PlVehicleRechargeApply.id.in_(ids))
if should_restrict_mine_vehicles(
db, tenant_no, user.id, mine_vehicles=mine_vehicles
):
plates = license_plates_for_user_personnel(db, tenant_no, user.id)
if not plates:
return [], 0
query = query.filter(PlVehicleRechargeApply.license_plate.in_(plates))
elif mine_vehicles:
# 管理员 + mineVehicles:本租户全量,跳过挂靠与数据范围
pass
else:
query = apply_pl_scope(query, PlVehicleRechargeApply, user, db, tenant_no)
total = query.count()
page = max(1, page)
cap = int(max_page_size) if max_page_size else 500
page_size = min(max(1, page_size), cap)
rows = (
query.order_by(order_recharge_apply(sort_field, sort_order))
.offset((page - 1) * page_size)
.limit(page_size)
.all()
)
return [apply_to_read(row, db) for row in rows], total
def get_apply(
db: Session,
tenant_no: str,
user: DbUserContext,
apply_id: str,
*,
mine_vehicles: bool = False,
) -> VehicleRechargeApplyRead:
row = _get_apply_row(
db, tenant_no, apply_id, user, mine_vehicles=mine_vehicles
)
return apply_to_read(row, db, include_detail=True)
def _assert_mine_vehicle_plate(
db: Session, tenant_no: str, user: DbUserContext, plate: str
) -> None:
if not should_restrict_mine_vehicles(
db, tenant_no, user.id, mine_vehicles=True
):
return
plates = license_plates_for_user_personnel(db, tenant_no, user.id)
if (plate or "").strip() not in plates:
raise HTTPException(status_code=403, detail="只能选择本人车辆")
def _assert_own_apply_for_write(row: PlVehicleRechargeApply, user: DbUserContext) -> None:
if (row.applicant_id or "").strip() != (user.id or "").strip():
raise HTTPException(status_code=403, detail="只能操作本人申请")
def create_apply(
db: Session,
tenant_no: str,
user: DbUserContext,
payload: VehicleRechargeApplyCreate,
*,
mine_vehicles: bool = False,
) -> VehicleRechargeApplyRead:
license_plate = payload.license_plate.strip()
if mine_vehicles:
_assert_mine_vehicle_plate(db, tenant_no, user, license_plate)
_assert_vehicle_exists(db, tenant_no, license_plate)
if mine_vehicles:
applicant_id = user.id
else:
applicant_id = _resolve_applicant_id(db, tenant_no, payload.applicant_id, user)
now = datetime.now()
row = PlVehicleRechargeApply(
id=generate_uuid(),
apply_no=generate_apply_no(db),
license_plate=license_plate,
recharge_type=payload.recharge_type,
apply_date=payload.apply_date,
odometer_km=payload.odometer_km,
attachment_urls=payload.attachment_urls,
applicant_id=applicant_id,
status="draft",
wf_id=None,
current_node=None,
approval_round=0,
tenant_no=tenant_no,
remark=payload.remark,
create_by=user.id,
create_dept_id=user.dept_id or "",
create_time=now,
update_by=user.id,
update_time=now,
del_flag=0,
)
db.add(row)
db.commit()
db.refresh(row)
return apply_to_read(row, db)
def update_apply(
db: Session,
tenant_no: str,
user: DbUserContext,
apply_id: str,
payload: VehicleRechargeApplyUpdate,
*,
mine_vehicles: bool = False,
) -> VehicleRechargeApplyRead:
row = _get_apply_row(
db, tenant_no, apply_id, user, mine_vehicles=mine_vehicles
)
if mine_vehicles:
_assert_own_apply_for_write(row, user)
if row.status not in _EDITABLE_STATUSES:
raise HTTPException(status_code=400, detail="仅草稿或已驳回申请可编辑")
license_plate = payload.license_plate.strip()
if mine_vehicles:
_assert_mine_vehicle_plate(db, tenant_no, user, license_plate)
_assert_vehicle_exists(db, tenant_no, license_plate)
row.license_plate = license_plate
row.recharge_type = payload.recharge_type
row.apply_date = payload.apply_date
row.odometer_km = payload.odometer_km
row.attachment_urls = payload.attachment_urls
if mine_vehicles:
row.applicant_id = user.id
else:
row.applicant_id = _resolve_applicant_id(
db, tenant_no, payload.applicant_id, user
)
row.remark = payload.remark
row.update_by = user.id
row.update_time = datetime.now()
db.commit()
db.refresh(row)
return apply_to_read(row, db)
def cancel_apply(
db: Session,
tenant_no: str,
user: DbUserContext,
apply_id: str,
*,
mine_vehicles: bool = False,
cancel_reason: Optional[str] = None,
) -> VehicleRechargeApplyRead:
from app.schemas.pl.cancel_reason import normalize_optional_reason
row = _get_apply_row(
db, tenant_no, apply_id, user, mine_vehicles=mine_vehicles
)
if mine_vehicles:
_assert_own_apply_for_write(row, user)
if row.status not in _EDITABLE_STATUSES:
raise HTTPException(status_code=400, detail="仅草稿或已驳回申请可作废")
now = datetime.now()
row.status = "cancelled"
row.cancel_reason = normalize_optional_reason(cancel_reason)
row.cancel_time = now
row.cancel_by = user.id
row.update_by = user.id
row.update_time = now
db.commit()
db.refresh(row)
return apply_to_read(row, db)
def withdraw_apply(
db: Session,
tenant_no: str,
user: DbUserContext,
apply_id: str,
*,
mine_vehicles: bool = False,
) -> VehicleRechargeApplyRead:
row = _get_apply_row(
db, tenant_no, apply_id, user, mine_vehicles=mine_vehicles
)
if (row.applicant_id or "").strip() != (user.id or "").strip():
raise HTTPException(status_code=403, detail="仅申请人可撤回")
if row.status != "in_approval":
raise HTTPException(status_code=400, detail="仅审批中的申请可撤回")
row.status = "draft"
row.current_node = None
row.update_by = user.id
row.update_time = datetime.now()
db.commit()
db.refresh(row)
return apply_to_read(row, db, include_detail=True)
def submit_apply(
db: Session,
tenant_no: str,
user: DbUserContext,
apply_id: str,
*,
mine_vehicles: bool = False,
) -> VehicleRechargeApplyRead:
row = _get_apply_row(
db, tenant_no, apply_id, user, mine_vehicles=mine_vehicles
)
if mine_vehicles:
_assert_own_apply_for_write(row, user)
if row.status not in _EDITABLE_STATUSES:
raise HTTPException(status_code=400, detail="仅草稿或已驳回申请可提交")
workflow = _get_vehicle_recharge_workflow(db, tenant_no)
nodes = _workflow_nodes(db, workflow.id, tenant_no)
if not nodes:
raise HTTPException(status_code=400, detail="充值审批流程未配置节点")
first = nodes[0]
now = datetime.now()
row.wf_id = workflow.id
row.current_node = first.id
row.approval_round = (row.approval_round or 0) + 1
row.status = "in_approval"
row.update_by = user.id
row.update_time = now
db.commit()
db.refresh(row)
return apply_to_read(row, db, include_detail=True)
def delete_applies(
db: Session, tenant_no: str, user: DbUserContext, apply_ids: list[str]
) -> None:
for apply_id in apply_ids:
row = _get_apply_row(db, tenant_no, apply_id, user)
if row.status not in _EDITABLE_STATUSES:
raise HTTPException(status_code=400, detail="仅草稿或已驳回申请可删除")
if _has_active_record(db, tenant_no, apply_id):
raise HTTPException(status_code=400, detail="已关联发放记录的申请不可删除")
row.del_flag = 1
row.update_by = user.id
row.update_time = datetime.now()
db.commit()
def list_pending_apply_options(
db: Session, tenant_no: str, user: DbUserContext
) -> list[dict]:
query = db.query(PlVehicleRechargeApply).filter(
PlVehicleRechargeApply.tenant_no == tenant_no,
PlVehicleRechargeApply.del_flag == 0,
PlVehicleRechargeApply.status == "pending",
)
query = apply_pl_scope(query, PlVehicleRechargeApply, user, db, tenant_no)
rows = query.order_by(PlVehicleRechargeApply.create_time.desc()).all()
return [
{
"id": row.id,
"applyNo": row.apply_no,
"licensePlate": row.license_plate,
"rechargeType": row.recharge_type,
}
for row in rows
]
def list_records(
db: Session,
tenant_no: str,
user: DbUserContext,
*,
q: Optional[str] = None,
recharge_type: Optional[str] = None,
recharge_date_from: Optional[date] = None,
recharge_date_to: Optional[date] = None,
gas_station: Optional[str] = None,
apply_no: Optional[str] = None,
page: int = 1,
page_size: int = 20,
) -> tuple[list[VehicleRechargeRecordRead], int]:
query = db.query(PlVehicleRechargeRecord).filter(
PlVehicleRechargeRecord.tenant_no == tenant_no,
PlVehicleRechargeRecord.del_flag == 0,
)
if q:
query = query.filter(
or_(
PlVehicleRechargeRecord.recharge_order_no.contains(q),
func.coalesce(PlVehicleRechargeRecord.license_plate, "").contains(q),
func.coalesce(PlVehicleRechargeRecord.card_no, "").contains(q),
)
)
if recharge_type:
query = query.filter(PlVehicleRechargeRecord.recharge_type == recharge_type)
if recharge_date_from:
query = query.filter(PlVehicleRechargeRecord.recharge_date >= recharge_date_from)
if recharge_date_to:
query = query.filter(PlVehicleRechargeRecord.recharge_date <= recharge_date_to)
if gas_station:
query = query.filter(
func.coalesce(PlVehicleRechargeRecord.gas_station, "").contains(gas_station)
)
if apply_no:
query = query.join(
PlVehicleRechargeApply,
PlVehicleRechargeApply.id == PlVehicleRechargeRecord.apply_id,
).filter(PlVehicleRechargeApply.apply_no.contains(apply_no))
query = apply_pl_scope(query, PlVehicleRechargeRecord, user, db, tenant_no)
total = query.count()
rows = (
query.order_by(PlVehicleRechargeRecord.create_time.desc())
.offset((page - 1) * page_size)
.limit(page_size)
.all()
)
return [record_to_read(row, db) for row in rows], total
def board_item_to_read(
apply_row: PlVehicleRechargeApply,
record_row: Optional[PlVehicleRechargeRecord],
db: Session,
) -> VehicleRechargeDisburseBoardItem:
return VehicleRechargeDisburseBoardItem(
applyId=apply_row.id,
applyNo=apply_row.apply_no,
licensePlate=apply_row.license_plate,
rechargeType=apply_row.recharge_type,
applyDate=apply_row.apply_date,
odometerKm=apply_row.odometer_km,
applicantName=_resolve_user_name(db, apply_row.applicant_id),
applyStatus=apply_row.status,
applyRemark=apply_row.remark,
recordId=record_row.id if record_row else None,
rechargeOrderNo=record_row.recharge_order_no if record_row else None,
rechargeDate=record_row.recharge_date if record_row else None,
cardNo=record_row.card_no if record_row else None,
gasStation=record_row.gas_station if record_row else None,
amount=record_row.amount if record_row else None,
recordCreateByName=_resolve_user_name(db, record_row.create_by) if record_row else None,
recordRemark=record_row.remark if record_row else None,
recordAttachmentUrls=record_row.attachment_urls if record_row else None,
)
def list_disburse_board(
db: Session,
tenant_no: str,
user: DbUserContext,
*,
q: Optional[str] = None,
apply_no: Optional[str] = None,
license_plate: Optional[str] = None,
recharge_type: Optional[str] = None,
recharge_type_in: Optional[str] = None,
apply_status: Optional[str] = None,
apply_status_in: Optional[str] = None,
apply_date_from: Optional[date] = None,
apply_date_to: Optional[date] = None,
recharge_date_from: Optional[date] = None,
recharge_date_to: Optional[date] = None,
applicant_name: Optional[str] = None,
odometer_km_op: Optional[str] = None,
odometer_km: Optional[str] = None,
odometer_km_min: Optional[str] = None,
odometer_km_max: Optional[str] = None,
recharge_order_no: Optional[str] = None,
card_no: Optional[str] = None,
gas_station: Optional[str] = None,
amount_op: Optional[str] = None,
amount: Optional[str] = None,
amount_min: Optional[str] = None,
amount_max: Optional[str] = None,
record_create_by_name: Optional[str] = None,
ids: Optional[list[str]] = None,
page: int = 1,
page_size: int = 20,
max_page_size: Optional[int] = None,
sort_field: Optional[str] = None,
sort_order: Optional[str] = None,
) -> tuple[list[VehicleRechargeDisburseBoardItem], int]:
query = (
db.query(PlVehicleRechargeApply, PlVehicleRechargeRecord)
.outerjoin(
PlVehicleRechargeRecord,
and_(
PlVehicleRechargeRecord.apply_id == PlVehicleRechargeApply.id,
PlVehicleRechargeRecord.tenant_no == tenant_no,
PlVehicleRechargeRecord.del_flag == 0,
),
)
.filter(
PlVehicleRechargeApply.tenant_no == tenant_no,
PlVehicleRechargeApply.del_flag == 0,
)
)
if q:
query = query.filter(
or_(
PlVehicleRechargeApply.apply_no.contains(q),
PlVehicleRechargeApply.license_plate.contains(q),
func.coalesce(PlVehicleRechargeRecord.recharge_order_no, "").contains(q),
func.coalesce(PlVehicleRechargeRecord.card_no, "").contains(q),
)
)
from app.services.pl.vehicle_recharge_list_filters import (
build_recharge_disburse_board_column_filters,
)
from app.services.pl.list_sort import order_recharge_board
column_filters = build_recharge_disburse_board_column_filters(
apply_no=apply_no,
license_plate=license_plate,
recharge_type=recharge_type,
recharge_type_in=recharge_type_in,
apply_status=apply_status,
apply_status_in=apply_status_in,
apply_date_from=apply_date_from,
apply_date_to=apply_date_to,
recharge_date_from=recharge_date_from,
recharge_date_to=recharge_date_to,
applicant_name=applicant_name,
odometer_km_op=odometer_km_op,
odometer_km=odometer_km,
odometer_km_min=odometer_km_min,
odometer_km_max=odometer_km_max,
recharge_order_no=recharge_order_no,
card_no=card_no,
gas_station=gas_station,
amount_op=amount_op,
amount=amount,
amount_min=amount_min,
amount_max=amount_max,
record_create_by_name=record_create_by_name,
)
if column_filters:
query = query.filter(*column_filters)
if ids:
query = query.filter(PlVehicleRechargeApply.id.in_(ids))
query = apply_pl_scope(query, PlVehicleRechargeApply, user, db, tenant_no)
total = query.count()
page = max(1, page)
cap = int(max_page_size) if max_page_size else 500
page_size = min(max(1, page_size), cap)
rows = (
query.order_by(order_recharge_board(sort_field, sort_order))
.offset((page - 1) * page_size)
.limit(page_size)
.all()
)
return [board_item_to_read(apply_row, record_row, db) for apply_row, record_row in rows], total
def get_record(
db: Session, tenant_no: str, user: DbUserContext, record_id: str
) -> VehicleRechargeRecordRead:
row = _get_record_row(db, tenant_no, record_id, user)
return record_to_read(row, db)
def create_record(
db: Session,
tenant_no: str,
user: DbUserContext,
payload: VehicleRechargeRecordCreate,
) -> VehicleRechargeRecordRead:
apply_row, license_plate, recharge_type = _resolve_apply_for_record(
db, tenant_no, payload, user
)
now = datetime.now()
row = PlVehicleRechargeRecord(
id=generate_uuid(),
recharge_order_no=generate_recharge_order_no(db),
recharge_date=payload.recharge_date,
recharge_type=recharge_type,
card_no=(payload.card_no or "").strip() or None,
gas_station=(payload.gas_station or "").strip() or None,
amount=payload.amount,
attachment_urls=payload.attachment_urls,
apply_id=apply_row.id if apply_row else None,
license_plate=license_plate,
tenant_no=tenant_no,
remark=payload.remark,
create_by=user.id,
create_dept_id=user.dept_id or "",
create_time=now,
update_by=user.id,
update_time=now,
del_flag=0,
)
db.add(row)
if apply_row:
apply_row.status = "disbursed"
apply_row.update_by = user.id
apply_row.update_time = now
db.commit()
db.refresh(row)
return record_to_read(row, db)
def update_record(
db: Session,
tenant_no: str,
user: DbUserContext,
record_id: str,
payload: VehicleRechargeRecordUpdate,
) -> VehicleRechargeRecordRead:
row = _get_record_row(db, tenant_no, record_id, user)
old_apply_id = row.apply_id
apply_row, license_plate, recharge_type = _resolve_apply_for_record(
db, tenant_no, payload, user, current_record_id=record_id
)
now = datetime.now()
if old_apply_id and old_apply_id != (apply_row.id if apply_row else None):
old_apply = (
db.query(PlVehicleRechargeApply)
.filter(
PlVehicleRechargeApply.id == old_apply_id,
PlVehicleRechargeApply.tenant_no == tenant_no,
PlVehicleRechargeApply.del_flag == 0,
)
.first()
)
if old_apply:
if old_apply.wf_id:
nodes = _workflow_nodes(db, old_apply.wf_id, tenant_no)
disburse = next(
(
n
for n in nodes
if (n.action_type or "approve") == "disburse"
),
nodes[-1] if nodes else None,
)
old_apply.status = "in_approval"
old_apply.current_node = disburse.id if disburse else None
else:
old_apply.status = "pending"
old_apply.update_by = user.id
old_apply.update_time = now
row.recharge_date = payload.recharge_date
row.recharge_type = recharge_type
row.card_no = (payload.card_no or "").strip() or None
row.gas_station = (payload.gas_station or "").strip() or None
row.amount = payload.amount
row.attachment_urls = payload.attachment_urls
row.apply_id = apply_row.id if apply_row else None
row.license_plate = license_plate
row.remark = payload.remark
row.update_by = user.id
row.update_time = now
if apply_row:
apply_row.status = "disbursed"
apply_row.update_by = user.id
apply_row.update_time = now
db.commit()
db.refresh(row)
return record_to_read(row, db)
def delete_records(
db: Session, tenant_no: str, user: DbUserContext, record_ids: list[str]
) -> None:
now = datetime.now()
for record_id in record_ids:
row = _get_record_row(db, tenant_no, record_id, user)
apply_id = row.apply_id
row.del_flag = 1
# 释放 uk_apply_id:软删后仍占唯一键会导致「撤销后再发放」撞 Duplicate entry
row.apply_id = None
row.update_by = user.id
row.update_time = now
if apply_id:
apply = (
db.query(PlVehicleRechargeApply)
.filter(
PlVehicleRechargeApply.id == apply_id,
PlVehicleRechargeApply.tenant_no == tenant_no,
PlVehicleRechargeApply.del_flag == 0,
)
.first()
)
if apply and apply.status == "disbursed":
if apply.wf_id:
nodes = _workflow_nodes(db, apply.wf_id, tenant_no)
disburse = next(
(
n
for n in nodes
if (n.action_type or "approve") == "disburse"
),
nodes[-1] if nodes else None,
)
apply.status = "in_approval"
apply.current_node = disburse.id if disburse else None
else:
apply.status = "pending"
apply.update_by = user.id
apply.update_time = now
db.commit()