| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510 |
- from __future__ import annotations
- from datetime import datetime
- from fastapi import APIRouter, Depends, HTTPException, Query, status
- from sqlmodel import select
- from sqlmodel.ext.asyncio.session import AsyncSession
- from app.db.session import get_async_session
- from app.models.weighing import WeighingSlip
- from app.models.plans import PurchasePlan
- from app.models.inventory import InboundOutbound
- from app.schemas.weighing import WeighingSlipCreate, WeighingSlipRead, WeighingSlipUpdate
- from app.schemas.plans import PurchasePlanRead
- from app.schemas.inventory import InboundOutboundRead
- from pydantic import BaseModel
- router = APIRouter(prefix="/weighing", tags=["weighing"])
- def _base_query():
- return select(WeighingSlip).where(WeighingSlip.is_voided == 0)
- @router.get("/", response_model=list[WeighingSlipRead])
- async def list_weighing(
- # 前端使用的是 dateFrom / dateTo,这里通过 alias 做映射
- date_from: str | None = Query(default=None, alias="dateFrom", description="开始日期"),
- date_to: str | None = Query(default=None, alias="dateTo", description="结束日期"),
- vehicle_no: str | None = Query(default=None, alias="vehicleNo", description="车牌号"),
- cargo_name: str | None = Query(default=None, alias="cargoName", description="货物名称"),
- business_type: str | None = Query(default=None, alias="businessType", description="业务类型"),
- session: AsyncSession = Depends(get_async_session),
- ) -> list[WeighingSlipRead]:
- query = _base_query().order_by(WeighingSlip.gross_weight_time.desc())
- if date_from:
- query = query.where(WeighingSlip.gross_weight_time >= date_from)
- if date_to:
- query = query.where(WeighingSlip.gross_weight_time <= date_to + " 23:59:59")
- if vehicle_no:
- query = query.where(WeighingSlip.vehicle_no.contains(vehicle_no))
- if cargo_name:
- query = query.where(WeighingSlip.cargo_name.contains(cargo_name))
- if business_type:
- query = query.where(WeighingSlip.business_type == business_type)
- result = await session.exec(query)
- weighings = result.all()
-
- # 收集所有需要查询的出入库单ID
- inventory_ids = [w.inbound_outbound_id for w in weighings if w.inbound_outbound_id]
-
- # 批量查询出入库单,构建ID到日期的映射
- inventory_date_map = {}
- if inventory_ids:
- inventory_result = await session.exec(
- select(InboundOutbound).where(
- InboundOutbound.id.in_(inventory_ids),
- InboundOutbound.is_deleted == 0
- )
- )
- for inventory in inventory_result.all():
- inventory_date_map[inventory.id] = inventory.date
-
- # 构建返回结果,添加出入库单日期
- result_list = []
- for weighing in weighings:
- weighing_dict = weighing.model_dump()
- # 添加出入库单日期
- if weighing.inbound_outbound_id and weighing.inbound_outbound_id in inventory_date_map:
- weighing_dict['inventory_date'] = inventory_date_map[weighing.inbound_outbound_id]
- else:
- weighing_dict['inventory_date'] = None
- result_list.append(WeighingSlipRead.model_validate(weighing_dict))
-
- return result_list
- @router.post("/", response_model=WeighingSlipRead, status_code=status.HTTP_201_CREATED)
- async def create_weighing(
- payload: WeighingSlipCreate,
- session: AsyncSession = Depends(get_async_session),
- ) -> WeighingSlip:
- print(
- "[weighing.create] payload",
- "vehicle_no=", payload.vehicle_no,
- "plan_no=", payload.plan_no,
- "purchase_plan_id=", payload.purchase_plan_id,
- "inbound_outbound_id=", payload.inbound_outbound_id,
- "net_weight=", payload.net_weight,
- "current_quantity=", payload.current_quantity,
- "planned_quantity=", payload.planned_quantity,
- )
- # 如果有关联的出入库单,检查是否已经存在地磅单(一对一关系)
- inbound_outbound_id = payload.inbound_outbound_id
- if inbound_outbound_id:
- print(
- "[weighing.create] has inbound_outbound_id, try load inventory, id=",
- inbound_outbound_id,
- )
- existing_weighing_result = await session.exec(
- select(WeighingSlip).where(
- WeighingSlip.inbound_outbound_id == inbound_outbound_id,
- WeighingSlip.is_voided == 0,
- )
- )
- existing_weighing = existing_weighing_result.first()
- if existing_weighing:
- raise HTTPException(
- status_code=status.HTTP_400_BAD_REQUEST,
- detail="该出入库单已经存在关联的地磅单,无法重复创建",
- )
-
- # 如果有关联的出入库单,自动填充相关字段
- planned_quantity = payload.planned_quantity
- current_quantity = payload.current_quantity
- purchase_plan_id = payload.purchase_plan_id
- batch_no = payload.batch_no.strip() if payload.batch_no else None
-
- if inbound_outbound_id:
- # 获取出入库单数据
- inventory_result = await session.exec(
- select(InboundOutbound).where(InboundOutbound.id == inbound_outbound_id)
- )
- inventory = inventory_result.one_or_none()
- if inventory:
- print(
- "[weighing.create] loaded inventory",
- "id=", inventory.id,
- "batch_no=", inventory.batch_no,
- "quantity(ton)=", inventory.quantity,
- "purchase_plan_id=", inventory.purchase_plan_id,
- )
- # 本次量就是出入库单的quantity(单位:吨),需要转换为kg
- if current_quantity is None:
- current_quantity = inventory.quantity * 1000
-
- # 如果有计划ID,获取计划数据(优先使用出入库单的计划ID,如果前端没有传递)
- if purchase_plan_id is None and inventory.purchase_plan_id:
- purchase_plan_id = inventory.purchase_plan_id
-
- # 如果现在有计划ID,获取计划数据
- if purchase_plan_id:
- plan_result = await session.exec(
- select(PurchasePlan).where(PurchasePlan.id == purchase_plan_id)
- )
- plan = plan_result.one_or_none()
- if plan:
- print(
- "[weighing.create] loaded plan",
- "id=", plan.id,
- "plan_no=", plan.plan_no,
- "planned_quantity(ton)=", plan.planned_quantity,
- "executed_quantity(kg)=", plan.executed_quantity,
- )
- # 计划量就是计划的planned_quantity(单位:吨),需要转换为kg
- if planned_quantity is None:
- planned_quantity = plan.planned_quantity * 1000
-
- # 如果前端没有传递 batch_no,使用出入库单的 batch_no(出入库单号)
- if not batch_no and inventory.batch_no:
- batch_no = inventory.batch_no
-
- weighing = WeighingSlip(
- vehicle_no=payload.vehicle_no.strip(),
- plan_no=payload.plan_no.strip() if payload.plan_no else None,
- cargo_name=payload.cargo_name.strip(),
- business_type=payload.business_type,
- batch_no=batch_no, # 使用出入库单号
- supplier=payload.supplier.strip(),
- consignee=payload.consignee.strip(),
- gross_weight=payload.gross_weight or 0,
- gross_weight_time=payload.gross_weight_time.strip() if payload.gross_weight_time else "",
- tare_weight=payload.tare_weight or 0,
- tare_weight_time=payload.tare_weight_time.strip() if payload.tare_weight_time else "",
- deduction=payload.deduction or 0,
- net_weight=payload.net_weight or 0,
- planned_quantity=planned_quantity,
- executed_quantity=payload.executed_quantity,
- purchase_plan_id=purchase_plan_id,
- inbound_outbound_id=inbound_outbound_id,
- weighing_point=payload.weighing_point or "山峡化工",
- remarks=payload.remarks,
- current_quantity=current_quantity,
- is_voided=0,
- created_at=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
- )
- session.add(weighing)
- await session.commit()
- await session.refresh(weighing)
- print(
- "[weighing.create] created weighing",
- "id=", weighing.id,
- "plan_no=", weighing.plan_no,
- "purchase_plan_id=", weighing.purchase_plan_id,
- "current_quantity(kg)=", weighing.current_quantity,
- "net_weight(kg)=", weighing.net_weight,
- "planned_quantity(kg)=", weighing.planned_quantity,
- )
-
- # 处理业务逻辑
- await _process_weighing_business_logic(weighing, session)
- await session.refresh(weighing)
-
- return weighing
- @router.get("/{id}", response_model=WeighingSlipRead)
- async def get_weighing(
- id: int,
- session: AsyncSession = Depends(get_async_session),
- ) -> WeighingSlip:
- return await _get_weighing(id, session)
- @router.patch("/{id}", response_model=WeighingSlipRead)
- async def update_weighing(
- id: int,
- payload: WeighingSlipUpdate,
- session: AsyncSession = Depends(get_async_session),
- ) -> WeighingSlip:
- print(
- "[weighing.update] id=", id,
- "payload.net_weight=", payload.net_weight,
- "payload.executed_quantity=", payload.executed_quantity,
- "payload.is_voided=", payload.is_voided,
- )
- weighing = await _get_weighing(id, session)
- if weighing.is_voided == 1:
- raise HTTPException(
- status_code=status.HTTP_400_BAD_REQUEST,
- detail="Cannot update voided weighing record",
- )
- payload_dict = payload.model_dump(exclude_unset=True)
- for key, value in payload_dict.items():
- if isinstance(value, str):
- value = value.strip()
- setattr(weighing, key, value)
- await session.commit()
- await session.refresh(weighing)
-
- # 处理业务逻辑
- await _process_weighing_business_logic(weighing, session)
- await session.refresh(weighing)
-
- return weighing
- @router.post("/{id}/void", status_code=status.HTTP_204_NO_CONTENT)
- async def void_weighing(
- id: int,
- session: AsyncSession = Depends(get_async_session),
- ) -> None:
- weighing = await _get_weighing(id, session)
- print("[weighing.void] id=", id, "current_is_voided=", weighing.is_voided)
- if weighing.is_voided == 1:
- raise HTTPException(
- status_code=status.HTTP_400_BAD_REQUEST,
- detail="Weighing record is already voided",
- )
- weighing.is_voided = 1
- await session.commit()
-
- # 处理业务逻辑(作废后需要重新计算)
- await _process_weighing_business_logic(weighing, session)
- @router.delete("/{id}", status_code=status.HTTP_204_NO_CONTENT)
- async def delete_weighing(
- id: int,
- session: AsyncSession = Depends(get_async_session),
- ) -> None:
- weighing = await _get_weighing(id, session)
- print("[weighing.delete] id=", id, "current_is_voided=", weighing.is_voided)
- weighing.is_voided = 1
- await session.commit()
-
- # 处理业务逻辑(删除后需要重新计算)
- await _process_weighing_business_logic(weighing, session)
- async def _get_weighing(id: int, session: AsyncSession) -> WeighingSlip:
- result = await session.exec(select(WeighingSlip).where(WeighingSlip.id == id))
- weighing = result.one_or_none()
- if weighing is None:
- raise HTTPException(
- status_code=status.HTTP_404_NOT_FOUND,
- detail=f"Weighing {id} not found",
- )
- return weighing
- class WeighingRelatedData(BaseModel):
- plan: PurchasePlanRead | None
- inventory: InboundOutboundRead | None
- @router.get("/{id}/related", response_model=WeighingRelatedData)
- async def get_weighing_related(
- id: int,
- session: AsyncSession = Depends(get_async_session),
- ) -> WeighingRelatedData:
- """获取地磅单关联的计划和出入库单"""
- weighing = await _get_weighing(id, session)
-
- # 获取关联的计划(通过 purchase_plan_id 或 plan_no)
- plan = None
- if weighing.purchase_plan_id:
- plan_result = await session.exec(
- select(PurchasePlan).where(
- PurchasePlan.id == weighing.purchase_plan_id,
- PurchasePlan.is_deleted == 0
- )
- )
- plan = plan_result.one_or_none()
- elif weighing.plan_no:
- plan_result = await session.exec(
- select(PurchasePlan).where(
- PurchasePlan.plan_no == weighing.plan_no,
- PurchasePlan.is_deleted == 0
- ).limit(1)
- )
- plan = plan_result.first()
-
- # 获取关联的出入库单(通过 inbound_outbound_id)
- inventory = None
- if weighing.inbound_outbound_id:
- inventory_result = await session.exec(
- select(InboundOutbound).where(
- InboundOutbound.id == weighing.inbound_outbound_id,
- InboundOutbound.is_deleted == 0
- )
- )
- inventory = inventory_result.one_or_none()
-
- return WeighingRelatedData(
- plan=PurchasePlanRead.model_validate(plan.model_dump()) if plan else None,
- inventory=InboundOutboundRead.model_validate(inventory.model_dump()) if inventory else None
- )
- async def _process_weighing_business_logic(
- weighing: WeighingSlip, session: AsyncSession
- ) -> None:
- """
- 处理地磅单的业务逻辑:
- 1. 更新计划单的已执行量(单位:kg)
- 2. 更新出入库单的状态(只有皮重和毛重都存在了,状态改成已完成,否则还原到待入库/待出库)
- 3. 重新计算地磅单的executed_quantity(按照创建时间顺序累计)
- """
- print(
- "[weighing.logic] start",
- "weighing_id=", weighing.id,
- "plan_no=", weighing.plan_no,
- "purchase_plan_id=", weighing.purchase_plan_id,
- "inbound_outbound_id=", weighing.inbound_outbound_id,
- "net_weight(kg)=", weighing.net_weight,
- )
- # 收集需要处理的计划ID和出入库单ID
- plan_ids_to_process = set()
- inventory_ids_to_process = set()
-
- # 如果当前地磅单有计划ID,添加到处理列表
- if weighing.purchase_plan_id:
- plan_ids_to_process.add(weighing.purchase_plan_id)
-
- # 如果当前地磅单有出入库单ID,添加到处理列表
- if weighing.inbound_outbound_id:
- inventory_ids_to_process.add(weighing.inbound_outbound_id)
-
- # 如果当前地磅单有计划号,查找所有使用该计划号的计划
- if weighing.plan_no:
- plans_result = await session.exec(
- select(PurchasePlan).where(
- PurchasePlan.plan_no == weighing.plan_no,
- PurchasePlan.is_deleted == 0
- )
- )
- plans = plans_result.all()
- print(
- "[weighing.logic] found plans by plan_no",
- "plan_no=", weighing.plan_no,
- "count=", len(plans),
- "ids=", [p.id for p in plans],
- )
- for plan in plans:
- plan_ids_to_process.add(plan.id)
- print(
- "[weighing.logic] ids_to_process",
- "plan_ids=", list(plan_ids_to_process),
- "inventory_ids=", list(inventory_ids_to_process),
- )
-
- # 1. 处理所有相关计划单的已执行量
- for plan_id in plan_ids_to_process:
- plan_result = await session.exec(
- select(PurchasePlan).where(PurchasePlan.id == plan_id)
- )
- plan = plan_result.one_or_none()
- if plan:
- # 获取该计划相关的所有未作废地磅单,按创建时间排序
- # 关联条件:同一个 plan_no 或 purchase_plan_id 指向该计划
- plan_weighings_result = await session.exec(
- select(WeighingSlip)
- .where(
- WeighingSlip.is_voided == 0,
- (
- (WeighingSlip.plan_no == plan.plan_no)
- | (WeighingSlip.purchase_plan_id == plan.id)
- ),
- )
- .order_by(WeighingSlip.created_at.asc())
- )
- plan_weighings = plan_weighings_result.all()
- print(
- "[weighing.logic] plan summary",
- "plan_id=", plan.id,
- "plan_no=", plan.plan_no,
- "business_type=", plan.business_type,
- "planned_quantity(ton)=", plan.planned_quantity,
- "found_weighings=", len(plan_weighings),
- "weighing_ids=", [w.id for w in plan_weighings],
- )
-
- # 计算已执行量(所有地磅单的净重总和,单位:kg)
- total_executed = sum(w.net_weight for w in plan_weighings if w.net_weight)
- print(
- "[weighing.logic] plan executed summary",
- "plan_id=", plan.id,
- "total_executed(kg)=", total_executed,
- "before_executed_quantity(kg)=", plan.executed_quantity,
- )
- plan.executed_quantity = total_executed
-
- # 更新计划的执行状态
- # 根据业务类型和执行量判断状态
- planned_quantity_kg = plan.planned_quantity * 1000 # 计划量转换为kg
- if total_executed >= planned_quantity_kg:
- # 已执行量达到或超过计划量,状态为已完成
- plan.execution_status = "已入库" if plan.business_type == "入库" else "已出库"
- elif total_executed > 0:
- # 有执行量但未完成,状态为进行中
- plan.execution_status = "入库中" if plan.business_type == "入库" else "出库中"
- else:
- # 没有执行量,状态为待执行
- plan.execution_status = "待入库" if plan.business_type == "入库" else "待出库"
-
- await session.commit()
- await session.refresh(plan)
- print(
- "[weighing.logic] plan final",
- "plan_id=", plan.id,
- "executed_quantity(kg)=", plan.executed_quantity,
- "execution_status=", plan.execution_status,
- )
-
- # 重新计算每个地磅单的executed_quantity(按创建时间顺序累计)
- cumulative_executed = 0.0
- for w in plan_weighings:
- cumulative_executed += w.net_weight if w.net_weight else 0.0
- w.executed_quantity = cumulative_executed
- await session.commit()
- # 2. 处理所有相关出入库单的状态
- for inventory_id in inventory_ids_to_process:
- inventory_result = await session.exec(
- select(InboundOutbound).where(InboundOutbound.id == inventory_id)
- )
- inventory = inventory_result.one_or_none()
- if inventory:
- # 检查该出入库单关联的所有地磅单
- related_weighings_result = await session.exec(
- select(WeighingSlip).where(
- WeighingSlip.inbound_outbound_id == inventory_id,
- WeighingSlip.is_voided == 0,
- )
- )
- related_weighings = related_weighings_result.all()
-
- # 检查是否所有地磅单都有皮重和毛重(非空字符串)
- all_complete = (
- len(related_weighings) > 0
- and all(
- w.gross_weight_time and w.gross_weight_time.strip()
- and w.tare_weight_time and w.tare_weight_time.strip()
- for w in related_weighings
- )
- )
-
- if all_complete and len(related_weighings) > 0:
- # 所有地磅单都完成了,状态改为已完成
- inventory.status = "已完成"
- else:
- # 否则还原到待入库/待出库
- inventory.status = "待入库" if inventory.business_type == "入库" else "待出库"
-
- await session.commit()
- await session.refresh(inventory)
|