weighing.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  1. from __future__ import annotations
  2. from datetime import datetime
  3. from fastapi import APIRouter, Depends, HTTPException, Query, status
  4. from sqlmodel import select
  5. from sqlmodel.ext.asyncio.session import AsyncSession
  6. from app.db.session import get_async_session
  7. from app.models.weighing import WeighingSlip
  8. from app.models.plans import PurchasePlan
  9. from app.models.inventory import InboundOutbound
  10. from app.schemas.weighing import WeighingSlipCreate, WeighingSlipRead, WeighingSlipUpdate
  11. from app.schemas.plans import PurchasePlanRead
  12. from app.schemas.inventory import InboundOutboundRead
  13. from pydantic import BaseModel
  14. router = APIRouter(prefix="/weighing", tags=["weighing"])
  15. def _base_query():
  16. return select(WeighingSlip).where(WeighingSlip.is_voided == 0)
  17. @router.get("/", response_model=list[WeighingSlipRead])
  18. async def list_weighing(
  19. # 前端使用的是 dateFrom / dateTo,这里通过 alias 做映射
  20. date_from: str | None = Query(default=None, alias="dateFrom", description="开始日期"),
  21. date_to: str | None = Query(default=None, alias="dateTo", description="结束日期"),
  22. vehicle_no: str | None = Query(default=None, alias="vehicleNo", description="车牌号"),
  23. cargo_name: str | None = Query(default=None, alias="cargoName", description="货物名称"),
  24. business_type: str | None = Query(default=None, alias="businessType", description="业务类型"),
  25. session: AsyncSession = Depends(get_async_session),
  26. ) -> list[WeighingSlipRead]:
  27. query = _base_query().order_by(WeighingSlip.gross_weight_time.desc())
  28. if date_from:
  29. query = query.where(WeighingSlip.gross_weight_time >= date_from)
  30. if date_to:
  31. query = query.where(WeighingSlip.gross_weight_time <= date_to + " 23:59:59")
  32. if vehicle_no:
  33. query = query.where(WeighingSlip.vehicle_no.contains(vehicle_no))
  34. if cargo_name:
  35. query = query.where(WeighingSlip.cargo_name.contains(cargo_name))
  36. if business_type:
  37. query = query.where(WeighingSlip.business_type == business_type)
  38. result = await session.exec(query)
  39. weighings = result.all()
  40. # 收集所有需要查询的出入库单ID
  41. inventory_ids = [w.inbound_outbound_id for w in weighings if w.inbound_outbound_id]
  42. # 批量查询出入库单,构建ID到日期的映射
  43. inventory_date_map = {}
  44. if inventory_ids:
  45. inventory_result = await session.exec(
  46. select(InboundOutbound).where(
  47. InboundOutbound.id.in_(inventory_ids),
  48. InboundOutbound.is_deleted == 0
  49. )
  50. )
  51. for inventory in inventory_result.all():
  52. inventory_date_map[inventory.id] = inventory.date
  53. # 构建返回结果,添加出入库单日期
  54. result_list = []
  55. for weighing in weighings:
  56. weighing_dict = weighing.model_dump()
  57. # 添加出入库单日期
  58. if weighing.inbound_outbound_id and weighing.inbound_outbound_id in inventory_date_map:
  59. weighing_dict['inventory_date'] = inventory_date_map[weighing.inbound_outbound_id]
  60. else:
  61. weighing_dict['inventory_date'] = None
  62. result_list.append(WeighingSlipRead.model_validate(weighing_dict))
  63. return result_list
  64. @router.post("/", response_model=WeighingSlipRead, status_code=status.HTTP_201_CREATED)
  65. async def create_weighing(
  66. payload: WeighingSlipCreate,
  67. session: AsyncSession = Depends(get_async_session),
  68. ) -> WeighingSlip:
  69. print(
  70. "[weighing.create] payload",
  71. "vehicle_no=", payload.vehicle_no,
  72. "plan_no=", payload.plan_no,
  73. "purchase_plan_id=", payload.purchase_plan_id,
  74. "inbound_outbound_id=", payload.inbound_outbound_id,
  75. "net_weight=", payload.net_weight,
  76. "current_quantity=", payload.current_quantity,
  77. "planned_quantity=", payload.planned_quantity,
  78. )
  79. # 如果有关联的出入库单,检查是否已经存在地磅单(一对一关系)
  80. inbound_outbound_id = payload.inbound_outbound_id
  81. if inbound_outbound_id:
  82. print(
  83. "[weighing.create] has inbound_outbound_id, try load inventory, id=",
  84. inbound_outbound_id,
  85. )
  86. existing_weighing_result = await session.exec(
  87. select(WeighingSlip).where(
  88. WeighingSlip.inbound_outbound_id == inbound_outbound_id,
  89. WeighingSlip.is_voided == 0,
  90. )
  91. )
  92. existing_weighing = existing_weighing_result.first()
  93. if existing_weighing:
  94. raise HTTPException(
  95. status_code=status.HTTP_400_BAD_REQUEST,
  96. detail="该出入库单已经存在关联的地磅单,无法重复创建",
  97. )
  98. # 如果有关联的出入库单,自动填充相关字段
  99. planned_quantity = payload.planned_quantity
  100. current_quantity = payload.current_quantity
  101. purchase_plan_id = payload.purchase_plan_id
  102. batch_no = payload.batch_no.strip() if payload.batch_no else None
  103. if inbound_outbound_id:
  104. # 获取出入库单数据
  105. inventory_result = await session.exec(
  106. select(InboundOutbound).where(InboundOutbound.id == inbound_outbound_id)
  107. )
  108. inventory = inventory_result.one_or_none()
  109. if inventory:
  110. print(
  111. "[weighing.create] loaded inventory",
  112. "id=", inventory.id,
  113. "batch_no=", inventory.batch_no,
  114. "quantity(ton)=", inventory.quantity,
  115. "purchase_plan_id=", inventory.purchase_plan_id,
  116. )
  117. # 本次量就是出入库单的quantity(单位:吨),需要转换为kg
  118. if current_quantity is None:
  119. current_quantity = inventory.quantity * 1000
  120. # 如果有计划ID,获取计划数据(优先使用出入库单的计划ID,如果前端没有传递)
  121. if purchase_plan_id is None and inventory.purchase_plan_id:
  122. purchase_plan_id = inventory.purchase_plan_id
  123. # 如果现在有计划ID,获取计划数据
  124. if purchase_plan_id:
  125. plan_result = await session.exec(
  126. select(PurchasePlan).where(PurchasePlan.id == purchase_plan_id)
  127. )
  128. plan = plan_result.one_or_none()
  129. if plan:
  130. print(
  131. "[weighing.create] loaded plan",
  132. "id=", plan.id,
  133. "plan_no=", plan.plan_no,
  134. "planned_quantity(ton)=", plan.planned_quantity,
  135. "executed_quantity(kg)=", plan.executed_quantity,
  136. )
  137. # 计划量就是计划的planned_quantity(单位:吨),需要转换为kg
  138. if planned_quantity is None:
  139. planned_quantity = plan.planned_quantity * 1000
  140. # 如果前端没有传递 batch_no,使用出入库单的 batch_no(出入库单号)
  141. if not batch_no and inventory.batch_no:
  142. batch_no = inventory.batch_no
  143. weighing = WeighingSlip(
  144. vehicle_no=payload.vehicle_no.strip(),
  145. plan_no=payload.plan_no.strip() if payload.plan_no else None,
  146. cargo_name=payload.cargo_name.strip(),
  147. business_type=payload.business_type,
  148. batch_no=batch_no, # 使用出入库单号
  149. supplier=payload.supplier.strip(),
  150. consignee=payload.consignee.strip(),
  151. gross_weight=payload.gross_weight or 0,
  152. gross_weight_time=payload.gross_weight_time.strip() if payload.gross_weight_time else "",
  153. tare_weight=payload.tare_weight or 0,
  154. tare_weight_time=payload.tare_weight_time.strip() if payload.tare_weight_time else "",
  155. deduction=payload.deduction or 0,
  156. net_weight=payload.net_weight or 0,
  157. planned_quantity=planned_quantity,
  158. executed_quantity=payload.executed_quantity,
  159. purchase_plan_id=purchase_plan_id,
  160. inbound_outbound_id=inbound_outbound_id,
  161. weighing_point=payload.weighing_point or "山峡化工",
  162. remarks=payload.remarks,
  163. current_quantity=current_quantity,
  164. is_voided=0,
  165. created_at=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
  166. )
  167. session.add(weighing)
  168. await session.commit()
  169. await session.refresh(weighing)
  170. print(
  171. "[weighing.create] created weighing",
  172. "id=", weighing.id,
  173. "plan_no=", weighing.plan_no,
  174. "purchase_plan_id=", weighing.purchase_plan_id,
  175. "current_quantity(kg)=", weighing.current_quantity,
  176. "net_weight(kg)=", weighing.net_weight,
  177. "planned_quantity(kg)=", weighing.planned_quantity,
  178. )
  179. # 处理业务逻辑
  180. await _process_weighing_business_logic(weighing, session)
  181. await session.refresh(weighing)
  182. return weighing
  183. @router.get("/{id}", response_model=WeighingSlipRead)
  184. async def get_weighing(
  185. id: int,
  186. session: AsyncSession = Depends(get_async_session),
  187. ) -> WeighingSlip:
  188. return await _get_weighing(id, session)
  189. @router.patch("/{id}", response_model=WeighingSlipRead)
  190. async def update_weighing(
  191. id: int,
  192. payload: WeighingSlipUpdate,
  193. session: AsyncSession = Depends(get_async_session),
  194. ) -> WeighingSlip:
  195. print(
  196. "[weighing.update] id=", id,
  197. "payload.net_weight=", payload.net_weight,
  198. "payload.executed_quantity=", payload.executed_quantity,
  199. "payload.is_voided=", payload.is_voided,
  200. )
  201. weighing = await _get_weighing(id, session)
  202. if weighing.is_voided == 1:
  203. raise HTTPException(
  204. status_code=status.HTTP_400_BAD_REQUEST,
  205. detail="Cannot update voided weighing record",
  206. )
  207. payload_dict = payload.model_dump(exclude_unset=True)
  208. for key, value in payload_dict.items():
  209. if isinstance(value, str):
  210. value = value.strip()
  211. setattr(weighing, key, value)
  212. await session.commit()
  213. await session.refresh(weighing)
  214. # 处理业务逻辑
  215. await _process_weighing_business_logic(weighing, session)
  216. await session.refresh(weighing)
  217. return weighing
  218. @router.post("/{id}/void", status_code=status.HTTP_204_NO_CONTENT)
  219. async def void_weighing(
  220. id: int,
  221. session: AsyncSession = Depends(get_async_session),
  222. ) -> None:
  223. weighing = await _get_weighing(id, session)
  224. print("[weighing.void] id=", id, "current_is_voided=", weighing.is_voided)
  225. if weighing.is_voided == 1:
  226. raise HTTPException(
  227. status_code=status.HTTP_400_BAD_REQUEST,
  228. detail="Weighing record is already voided",
  229. )
  230. weighing.is_voided = 1
  231. await session.commit()
  232. # 处理业务逻辑(作废后需要重新计算)
  233. await _process_weighing_business_logic(weighing, session)
  234. @router.delete("/{id}", status_code=status.HTTP_204_NO_CONTENT)
  235. async def delete_weighing(
  236. id: int,
  237. session: AsyncSession = Depends(get_async_session),
  238. ) -> None:
  239. weighing = await _get_weighing(id, session)
  240. print("[weighing.delete] id=", id, "current_is_voided=", weighing.is_voided)
  241. weighing.is_voided = 1
  242. await session.commit()
  243. # 处理业务逻辑(删除后需要重新计算)
  244. await _process_weighing_business_logic(weighing, session)
  245. async def _get_weighing(id: int, session: AsyncSession) -> WeighingSlip:
  246. result = await session.exec(select(WeighingSlip).where(WeighingSlip.id == id))
  247. weighing = result.one_or_none()
  248. if weighing is None:
  249. raise HTTPException(
  250. status_code=status.HTTP_404_NOT_FOUND,
  251. detail=f"Weighing {id} not found",
  252. )
  253. return weighing
  254. class WeighingRelatedData(BaseModel):
  255. plan: PurchasePlanRead | None
  256. inventory: InboundOutboundRead | None
  257. @router.get("/{id}/related", response_model=WeighingRelatedData)
  258. async def get_weighing_related(
  259. id: int,
  260. session: AsyncSession = Depends(get_async_session),
  261. ) -> WeighingRelatedData:
  262. """获取地磅单关联的计划和出入库单"""
  263. weighing = await _get_weighing(id, session)
  264. # 获取关联的计划(通过 purchase_plan_id 或 plan_no)
  265. plan = None
  266. if weighing.purchase_plan_id:
  267. plan_result = await session.exec(
  268. select(PurchasePlan).where(
  269. PurchasePlan.id == weighing.purchase_plan_id,
  270. PurchasePlan.is_deleted == 0
  271. )
  272. )
  273. plan = plan_result.one_or_none()
  274. elif weighing.plan_no:
  275. plan_result = await session.exec(
  276. select(PurchasePlan).where(
  277. PurchasePlan.plan_no == weighing.plan_no,
  278. PurchasePlan.is_deleted == 0
  279. ).limit(1)
  280. )
  281. plan = plan_result.first()
  282. # 获取关联的出入库单(通过 inbound_outbound_id)
  283. inventory = None
  284. if weighing.inbound_outbound_id:
  285. inventory_result = await session.exec(
  286. select(InboundOutbound).where(
  287. InboundOutbound.id == weighing.inbound_outbound_id,
  288. InboundOutbound.is_deleted == 0
  289. )
  290. )
  291. inventory = inventory_result.one_or_none()
  292. return WeighingRelatedData(
  293. plan=PurchasePlanRead.model_validate(plan.model_dump()) if plan else None,
  294. inventory=InboundOutboundRead.model_validate(inventory.model_dump()) if inventory else None
  295. )
  296. async def _process_weighing_business_logic(
  297. weighing: WeighingSlip, session: AsyncSession
  298. ) -> None:
  299. """
  300. 处理地磅单的业务逻辑:
  301. 1. 更新计划单的已执行量(单位:kg)
  302. 2. 更新出入库单的状态(只有皮重和毛重都存在了,状态改成已完成,否则还原到待入库/待出库)
  303. 3. 重新计算地磅单的executed_quantity(按照创建时间顺序累计)
  304. """
  305. print(
  306. "[weighing.logic] start",
  307. "weighing_id=", weighing.id,
  308. "plan_no=", weighing.plan_no,
  309. "purchase_plan_id=", weighing.purchase_plan_id,
  310. "inbound_outbound_id=", weighing.inbound_outbound_id,
  311. "net_weight(kg)=", weighing.net_weight,
  312. )
  313. # 收集需要处理的计划ID和出入库单ID
  314. plan_ids_to_process = set()
  315. inventory_ids_to_process = set()
  316. # 如果当前地磅单有计划ID,添加到处理列表
  317. if weighing.purchase_plan_id:
  318. plan_ids_to_process.add(weighing.purchase_plan_id)
  319. # 如果当前地磅单有出入库单ID,添加到处理列表
  320. if weighing.inbound_outbound_id:
  321. inventory_ids_to_process.add(weighing.inbound_outbound_id)
  322. # 如果当前地磅单有计划号,查找所有使用该计划号的计划
  323. if weighing.plan_no:
  324. plans_result = await session.exec(
  325. select(PurchasePlan).where(
  326. PurchasePlan.plan_no == weighing.plan_no,
  327. PurchasePlan.is_deleted == 0
  328. )
  329. )
  330. plans = plans_result.all()
  331. print(
  332. "[weighing.logic] found plans by plan_no",
  333. "plan_no=", weighing.plan_no,
  334. "count=", len(plans),
  335. "ids=", [p.id for p in plans],
  336. )
  337. for plan in plans:
  338. plan_ids_to_process.add(plan.id)
  339. print(
  340. "[weighing.logic] ids_to_process",
  341. "plan_ids=", list(plan_ids_to_process),
  342. "inventory_ids=", list(inventory_ids_to_process),
  343. )
  344. # 1. 处理所有相关计划单的已执行量
  345. for plan_id in plan_ids_to_process:
  346. plan_result = await session.exec(
  347. select(PurchasePlan).where(PurchasePlan.id == plan_id)
  348. )
  349. plan = plan_result.one_or_none()
  350. if plan:
  351. # 获取该计划相关的所有未作废地磅单,按创建时间排序
  352. # 关联条件:同一个 plan_no 或 purchase_plan_id 指向该计划
  353. plan_weighings_result = await session.exec(
  354. select(WeighingSlip)
  355. .where(
  356. WeighingSlip.is_voided == 0,
  357. (
  358. (WeighingSlip.plan_no == plan.plan_no)
  359. | (WeighingSlip.purchase_plan_id == plan.id)
  360. ),
  361. )
  362. .order_by(WeighingSlip.created_at.asc())
  363. )
  364. plan_weighings = plan_weighings_result.all()
  365. print(
  366. "[weighing.logic] plan summary",
  367. "plan_id=", plan.id,
  368. "plan_no=", plan.plan_no,
  369. "business_type=", plan.business_type,
  370. "planned_quantity(ton)=", plan.planned_quantity,
  371. "found_weighings=", len(plan_weighings),
  372. "weighing_ids=", [w.id for w in plan_weighings],
  373. )
  374. # 计算已执行量(所有地磅单的净重总和,单位:kg)
  375. total_executed = sum(w.net_weight for w in plan_weighings if w.net_weight)
  376. print(
  377. "[weighing.logic] plan executed summary",
  378. "plan_id=", plan.id,
  379. "total_executed(kg)=", total_executed,
  380. "before_executed_quantity(kg)=", plan.executed_quantity,
  381. )
  382. plan.executed_quantity = total_executed
  383. # 更新计划的执行状态
  384. # 根据业务类型和执行量判断状态
  385. planned_quantity_kg = plan.planned_quantity * 1000 # 计划量转换为kg
  386. if total_executed >= planned_quantity_kg:
  387. # 已执行量达到或超过计划量,状态为已完成
  388. plan.execution_status = "已入库" if plan.business_type == "入库" else "已出库"
  389. elif total_executed > 0:
  390. # 有执行量但未完成,状态为进行中
  391. plan.execution_status = "入库中" if plan.business_type == "入库" else "出库中"
  392. else:
  393. # 没有执行量,状态为待执行
  394. plan.execution_status = "待入库" if plan.business_type == "入库" else "待出库"
  395. await session.commit()
  396. await session.refresh(plan)
  397. print(
  398. "[weighing.logic] plan final",
  399. "plan_id=", plan.id,
  400. "executed_quantity(kg)=", plan.executed_quantity,
  401. "execution_status=", plan.execution_status,
  402. )
  403. # 重新计算每个地磅单的executed_quantity(按创建时间顺序累计)
  404. cumulative_executed = 0.0
  405. for w in plan_weighings:
  406. cumulative_executed += w.net_weight if w.net_weight else 0.0
  407. w.executed_quantity = cumulative_executed
  408. await session.commit()
  409. # 2. 处理所有相关出入库单的状态
  410. for inventory_id in inventory_ids_to_process:
  411. inventory_result = await session.exec(
  412. select(InboundOutbound).where(InboundOutbound.id == inventory_id)
  413. )
  414. inventory = inventory_result.one_or_none()
  415. if inventory:
  416. # 检查该出入库单关联的所有地磅单
  417. related_weighings_result = await session.exec(
  418. select(WeighingSlip).where(
  419. WeighingSlip.inbound_outbound_id == inventory_id,
  420. WeighingSlip.is_voided == 0,
  421. )
  422. )
  423. related_weighings = related_weighings_result.all()
  424. # 检查是否所有地磅单都有皮重和毛重(非空字符串)
  425. all_complete = (
  426. len(related_weighings) > 0
  427. and all(
  428. w.gross_weight_time and w.gross_weight_time.strip()
  429. and w.tare_weight_time and w.tare_weight_time.strip()
  430. for w in related_weighings
  431. )
  432. )
  433. if all_complete and len(related_weighings) > 0:
  434. # 所有地磅单都完成了,状态改为已完成
  435. inventory.status = "已完成"
  436. else:
  437. # 否则还原到待入库/待出库
  438. inventory.status = "待入库" if inventory.business_type == "入库" else "待出库"
  439. await session.commit()
  440. await session.refresh(inventory)