weighing.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  1. from typing import List, Optional
  2. from datetime import datetime
  3. from fastapi import APIRouter, Depends, HTTPException, Query, status
  4. from pydantic import BaseModel, Field
  5. from sqlalchemy import func, or_
  6. from sqlalchemy.orm import Session
  7. from app.core.database import get_db
  8. from app.core.db_auth import DbUserContext, get_db_current_user
  9. from app.core.delete_guard import assert_row_deletable_by_creator, user_info_from_context
  10. from app.core.tenant_context import get_tenant_no
  11. from app.core.utils import generate_uuid
  12. from app.services.db_data_scope import apply_db_scope, assert_db_row_in_scope
  13. from app.models.db_models import DbInboundOutbound, DbPurchasePlan, DbWeighingSlip
  14. from app.schemas.db.inventory import InboundOutboundRead
  15. from app.schemas.db.plans import PurchasePlanRead
  16. from app.schemas.db.weighing import WeighingSlipCreate, WeighingSlipRead, WeighingSlipUpdate
  17. from app.services.db.mappers import (
  18. datetime_end_of_day,
  19. inventory_date_to_api,
  20. inventory_to_read,
  21. load_user_display_name_map,
  22. parse_date_str,
  23. parse_datetime_str,
  24. plan_to_read,
  25. weighing_to_read,
  26. )
  27. from app.services.db.weighing_logic import process_weighing_business_logic
  28. from app.services.db.product_helpers import (
  29. apply_product_snapshot_to_weighing,
  30. resolve_crm_product,
  31. )
  32. from app.utils.excel_export import (
  33. EXPORT_MAX_ROWS,
  34. ExportColumn,
  35. ExportValidationError,
  36. export_rows_to_xlsx_response,
  37. filter_export_columns,
  38. )
  39. router = APIRouter(prefix="/weighing", tags=["weighing"])
  40. _WEIGHING_REMARK_FIELD = "remarks"
  41. def _base_query(db: Session, tenant_no: str):
  42. return db.query(DbWeighingSlip).filter(
  43. DbWeighingSlip.tenant_no == tenant_no,
  44. DbWeighingSlip.del_flag == 0,
  45. DbWeighingSlip.is_voided == 0,
  46. )
  47. def _get_weighing(
  48. db: Session, tenant_no: str, weighing_id: str, user: DbUserContext
  49. ) -> DbWeighingSlip:
  50. row = (
  51. db.query(DbWeighingSlip)
  52. .filter(
  53. DbWeighingSlip.id == weighing_id,
  54. DbWeighingSlip.tenant_no == tenant_no,
  55. DbWeighingSlip.del_flag == 0,
  56. )
  57. .one_or_none()
  58. )
  59. if row is None:
  60. raise HTTPException(
  61. status_code=status.HTTP_404_NOT_FOUND,
  62. detail=f"Weighing {weighing_id} not found",
  63. )
  64. assert_db_row_in_scope(db, row, DbWeighingSlip, user, tenant_no)
  65. return row
  66. def _apply_weighing_product_update(
  67. db: Session, tenant_no: str, row: DbWeighingSlip, payload_dict: dict
  68. ) -> None:
  69. if "cargo_name" in payload_dict and "product_id" not in payload_dict:
  70. raise HTTPException(
  71. status_code=status.HTTP_400_BAD_REQUEST,
  72. detail="请从 CRM 重新选择产品",
  73. )
  74. product_id = payload_dict.pop("product_id", None)
  75. payload_dict.pop("cargo_name", None)
  76. payload_dict.pop("specification", None)
  77. if product_id is not None:
  78. snapshot = resolve_crm_product(db, tenant_no, product_id)
  79. apply_product_snapshot_to_weighing(row, snapshot)
  80. def _apply_weighing_update(row: DbWeighingSlip, payload_dict: dict) -> None:
  81. for key, value in payload_dict.items():
  82. if key == _WEIGHING_REMARK_FIELD:
  83. if isinstance(value, str):
  84. value = value.strip()
  85. row.remark = value
  86. continue
  87. if key in {"gross_weight_time", "tare_weight_time"}:
  88. if value is None or (isinstance(value, str) and not str(value).strip()):
  89. if key == "tare_weight_time":
  90. row.tare_weight_time = None
  91. else:
  92. parsed = parse_datetime_str(str(value))
  93. if parsed:
  94. setattr(row, key, parsed)
  95. continue
  96. if isinstance(value, str):
  97. value = value.strip()
  98. setattr(row, key, value)
  99. @router.get("/", response_model=list[WeighingSlipRead])
  100. def list_weighing(
  101. q: Optional[str] = Query(default=None, description="模糊搜索关键词"),
  102. date_from: Optional[str] = Query(default=None, alias="dateFrom", description="开始日期"),
  103. date_to: Optional[str] = Query(default=None, alias="dateTo", description="结束日期"),
  104. plan_no: Optional[str] = Query(default=None, alias="planNo", description="计划号"),
  105. batch_no: Optional[str] = Query(default=None, alias="batchNo", description="出入库单号"),
  106. vehicle_no: Optional[str] = Query(default=None, alias="vehicleNo", description="车牌号"),
  107. cargo_name: Optional[str] = Query(default=None, alias="cargoName", description="货物名称"),
  108. supplier: Optional[str] = Query(default=None, description="供货单位"),
  109. consignee: Optional[str] = Query(default=None, description="收货单位"),
  110. business_type: Optional[str] = Query(default=None, alias="businessType", description="业务类型"),
  111. db: Session = Depends(get_db),
  112. user: DbUserContext = Depends(get_db_current_user),
  113. ) -> list[WeighingSlipRead]:
  114. tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
  115. query = _base_query(db, tenant_no).order_by(DbWeighingSlip.gross_weight_time.desc())
  116. if q:
  117. keyword = q.lower()
  118. query = query.filter(
  119. or_(
  120. func.lower(DbWeighingSlip.vehicle_no).contains(keyword),
  121. func.lower(DbWeighingSlip.plan_no).contains(keyword),
  122. func.lower(DbWeighingSlip.batch_no).contains(keyword),
  123. func.lower(DbWeighingSlip.cargo_name).contains(keyword),
  124. func.lower(DbWeighingSlip.supplier).contains(keyword),
  125. func.lower(DbWeighingSlip.consignee).contains(keyword),
  126. )
  127. )
  128. if date_from:
  129. start_date = parse_date_str(date_from)
  130. if start_date:
  131. query = query.filter(
  132. DbWeighingSlip.gross_weight_time >= datetime.combine(start_date, datetime.min.time())
  133. )
  134. if date_to:
  135. end_date = parse_date_str(date_to)
  136. if end_date:
  137. query = query.filter(DbWeighingSlip.gross_weight_time <= datetime_end_of_day(end_date))
  138. if plan_no:
  139. query = query.filter(DbWeighingSlip.plan_no.contains(plan_no))
  140. if batch_no:
  141. query = query.filter(DbWeighingSlip.batch_no.contains(batch_no))
  142. if vehicle_no:
  143. query = query.filter(DbWeighingSlip.vehicle_no.contains(vehicle_no))
  144. if cargo_name:
  145. query = query.filter(DbWeighingSlip.cargo_name.contains(cargo_name))
  146. if supplier:
  147. query = query.filter(func.lower(DbWeighingSlip.supplier).contains(supplier.lower()))
  148. if consignee:
  149. query = query.filter(func.lower(DbWeighingSlip.consignee).contains(consignee.lower()))
  150. if business_type:
  151. query = query.filter(DbWeighingSlip.business_type == business_type)
  152. query = apply_db_scope(query, DbWeighingSlip, user, db, tenant_no)
  153. weighings = query.all()
  154. inventory_ids = [w.inbound_outbound_id for w in weighings if w.inbound_outbound_id]
  155. inventory_date_map: dict[str, str] = {}
  156. if inventory_ids:
  157. inventories = (
  158. db.query(DbInboundOutbound)
  159. .filter(
  160. DbInboundOutbound.id.in_(inventory_ids),
  161. DbInboundOutbound.del_flag == 0,
  162. )
  163. .all()
  164. )
  165. for inventory in inventories:
  166. inventory_date_map[inventory.id] = inventory_date_to_api(inventory.date)
  167. user_name_map = load_user_display_name_map(db, [w.create_by for w in weighings])
  168. return [
  169. weighing_to_read(
  170. weighing,
  171. inventory_date=inventory_date_map.get(weighing.inbound_outbound_id or ""),
  172. user_name_map=user_name_map,
  173. )
  174. for weighing in weighings
  175. ]
  176. WEIGHING_EXPORT_COLUMNS = [
  177. ExportColumn(title="日期", field="inventoryDate"),
  178. ExportColumn(title="计划单号", field="planNo"),
  179. ExportColumn(title="出入库单号", field="batchNo"),
  180. ExportColumn(title="车牌号", field="vehicleNo"),
  181. ExportColumn(title="货物名称", field="cargoName"),
  182. ExportColumn(title="规格", field="specification"),
  183. ExportColumn(title="业务类型", field="businessType"),
  184. ExportColumn(title="单据状态", field="docStatus"),
  185. ExportColumn(title="供货单位", field="supplier"),
  186. ExportColumn(title="收货单位", field="consignee"),
  187. ExportColumn(title="本次量(吨)", field="currentQuantity"),
  188. ExportColumn(title="净重(吨)", field="netWeight"),
  189. ExportColumn(title="毛重(kg)", field="grossWeight"),
  190. ExportColumn(title="毛重时间", field="grossWeightTime"),
  191. ExportColumn(title="皮重(kg)", field="tareWeight"),
  192. ExportColumn(title="皮重时间", field="tareWeightTime"),
  193. ExportColumn(title="扣杂(kg)", field="deduction"),
  194. ExportColumn(title="创建人", field="createByName"),
  195. ]
  196. class WeighingExportBody(BaseModel):
  197. q: Optional[str] = None
  198. date_from: Optional[str] = Field(default=None, alias="dateFrom")
  199. date_to: Optional[str] = Field(default=None, alias="dateTo")
  200. plan_no: Optional[str] = Field(default=None, alias="planNo")
  201. batch_no: Optional[str] = Field(default=None, alias="batchNo")
  202. vehicle_no: Optional[str] = Field(default=None, alias="vehicleNo")
  203. cargo_name: Optional[str] = Field(default=None, alias="cargoName")
  204. supplier: Optional[str] = None
  205. consignee: Optional[str] = None
  206. business_type: Optional[str] = Field(default=None, alias="businessType")
  207. ids: Optional[List[str]] = None
  208. columns: Optional[List[str]] = None
  209. model_config = {"populate_by_name": True}
  210. def _kg_to_ton(value) -> float:
  211. try:
  212. return round(float(value or 0) / 1000, 2)
  213. except (TypeError, ValueError):
  214. return 0.0
  215. @router.post("/export")
  216. def export_weighing(
  217. body: WeighingExportBody,
  218. db: Session = Depends(get_db),
  219. user: DbUserContext = Depends(get_db_current_user),
  220. ):
  221. """导出地磅单列表(当前筛选全量,或 ids 已选)。"""
  222. try:
  223. items = list_weighing(
  224. q=body.q,
  225. date_from=body.date_from,
  226. date_to=body.date_to,
  227. plan_no=body.plan_no,
  228. batch_no=body.batch_no,
  229. vehicle_no=body.vehicle_no,
  230. cargo_name=body.cargo_name,
  231. supplier=body.supplier,
  232. consignee=body.consignee,
  233. business_type=body.business_type,
  234. db=db,
  235. user=user,
  236. )
  237. if body.ids:
  238. id_set = set(body.ids)
  239. items = [x for x in items if x.id in id_set]
  240. if len(items) > EXPORT_MAX_ROWS:
  241. raise ExportValidationError(f"导出超过 {EXPORT_MAX_ROWS} 条,请缩小筛选范围")
  242. rows = []
  243. for item in items:
  244. data = item.model_dump(by_alias=True)
  245. data["docStatus"] = "已作废" if data.get("isVoided") == 1 else "正常"
  246. data["currentQuantity"] = _kg_to_ton(data.get("currentQuantity"))
  247. data["netWeight"] = _kg_to_ton(data.get("netWeight"))
  248. if not data.get("inventoryDate"):
  249. gwt = data.get("grossWeightTime") or ""
  250. data["inventoryDate"] = str(gwt)[:10] if gwt else ""
  251. if not data.get("createByName"):
  252. data["createByName"] = data.get("createBy") or ""
  253. rows.append(data)
  254. cols = filter_export_columns(WEIGHING_EXPORT_COLUMNS, body.columns)
  255. date_str = datetime.now().strftime("%Y%m%d")
  256. tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
  257. return export_rows_to_xlsx_response(
  258. db,
  259. tenant_no=tenant_no,
  260. sheet_title="地磅单列表",
  261. columns=cols,
  262. rows=rows,
  263. filename_stem=f"地磅单列表_{date_str}",
  264. )
  265. except ExportValidationError as e:
  266. raise HTTPException(status_code=400, detail=str(e)) from e
  267. @router.post("/", response_model=WeighingSlipRead, status_code=status.HTTP_201_CREATED)
  268. def create_weighing(
  269. payload: WeighingSlipCreate,
  270. db: Session = Depends(get_db),
  271. user: DbUserContext = Depends(get_db_current_user),
  272. ) -> WeighingSlipRead:
  273. tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
  274. inbound_outbound_id = payload.inbound_outbound_id
  275. if inbound_outbound_id:
  276. existing = (
  277. db.query(DbWeighingSlip)
  278. .filter(
  279. DbWeighingSlip.inbound_outbound_id == inbound_outbound_id,
  280. DbWeighingSlip.is_voided == 0,
  281. DbWeighingSlip.del_flag == 0,
  282. )
  283. .first()
  284. )
  285. if existing:
  286. raise HTTPException(
  287. status_code=status.HTTP_400_BAD_REQUEST,
  288. detail="该出入库单已经存在关联的地磅单,无法重复创建",
  289. )
  290. planned_quantity = payload.planned_quantity
  291. current_quantity = payload.current_quantity
  292. purchase_plan_id = payload.purchase_plan_id
  293. batch_no = payload.batch_no.strip() if payload.batch_no else None
  294. if inbound_outbound_id:
  295. inventory = (
  296. db.query(DbInboundOutbound)
  297. .filter(
  298. DbInboundOutbound.id == inbound_outbound_id,
  299. DbInboundOutbound.tenant_no == tenant_no,
  300. DbInboundOutbound.del_flag == 0,
  301. )
  302. .one_or_none()
  303. )
  304. if inventory:
  305. if current_quantity is None:
  306. current_quantity = inventory.quantity * 1000
  307. if purchase_plan_id is None and inventory.purchase_plan_id:
  308. purchase_plan_id = inventory.purchase_plan_id
  309. if purchase_plan_id:
  310. plan = (
  311. db.query(DbPurchasePlan)
  312. .filter(DbPurchasePlan.id == purchase_plan_id)
  313. .one_or_none()
  314. )
  315. if plan and planned_quantity is None:
  316. planned_quantity = plan.planned_quantity * 1000
  317. if not batch_no and inventory.batch_no:
  318. batch_no = inventory.batch_no
  319. gross_time = parse_datetime_str(payload.gross_weight_time) if payload.gross_weight_time else None
  320. tare_time = (
  321. parse_datetime_str(payload.tare_weight_time)
  322. if payload.tare_weight_time and payload.tare_weight_time.strip()
  323. else None
  324. )
  325. snapshot = resolve_crm_product(db, tenant_no, payload.product_id)
  326. row = DbWeighingSlip(
  327. id=generate_uuid(),
  328. tenant_no=tenant_no,
  329. vehicle_no=payload.vehicle_no.strip(),
  330. plan_no=payload.plan_no.strip() if payload.plan_no else None,
  331. business_type=payload.business_type,
  332. batch_no=batch_no,
  333. supplier=payload.supplier.strip(),
  334. consignee=payload.consignee.strip(),
  335. gross_weight=payload.gross_weight or 0,
  336. gross_weight_time=gross_time or datetime.now(),
  337. tare_weight=payload.tare_weight or 0,
  338. tare_weight_time=tare_time,
  339. deduction=payload.deduction or 0,
  340. net_weight=payload.net_weight or 0,
  341. planned_quantity=planned_quantity,
  342. executed_quantity=payload.executed_quantity,
  343. purchase_plan_id=purchase_plan_id,
  344. inbound_outbound_id=inbound_outbound_id,
  345. weighing_point=payload.weighing_point or "山峡化工",
  346. remark=payload.remarks,
  347. current_quantity=current_quantity,
  348. is_voided=0,
  349. create_by=user.id,
  350. create_dept_id=user.dept_id,
  351. )
  352. apply_product_snapshot_to_weighing(row, snapshot)
  353. db.add(row)
  354. db.commit()
  355. db.refresh(row)
  356. process_weighing_business_logic(db, row)
  357. db.refresh(row)
  358. return weighing_to_read(row, db=db)
  359. @router.get("/{id}", response_model=WeighingSlipRead)
  360. def get_weighing(
  361. id: str,
  362. db: Session = Depends(get_db),
  363. user: DbUserContext = Depends(get_db_current_user),
  364. ) -> WeighingSlipRead:
  365. tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
  366. row = _get_weighing(db, tenant_no, id, user)
  367. return weighing_to_read(row, db=db)
  368. @router.patch("/{id}", response_model=WeighingSlipRead)
  369. def update_weighing(
  370. id: str,
  371. payload: WeighingSlipUpdate,
  372. db: Session = Depends(get_db),
  373. user: DbUserContext = Depends(get_db_current_user),
  374. ) -> WeighingSlipRead:
  375. tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
  376. row = _get_weighing(db, tenant_no, id, user)
  377. if row.is_voided == 1:
  378. raise HTTPException(
  379. status_code=status.HTTP_400_BAD_REQUEST,
  380. detail="Cannot update voided weighing record",
  381. )
  382. payload_dict = payload.model_dump(exclude_unset=True)
  383. _apply_weighing_product_update(db, tenant_no, row, payload_dict)
  384. _apply_weighing_update(row, payload_dict)
  385. row.update_by = user.id
  386. db.commit()
  387. db.refresh(row)
  388. process_weighing_business_logic(db, row)
  389. db.refresh(row)
  390. return weighing_to_read(row, db=db)
  391. @router.post("/{id}/void", status_code=status.HTTP_204_NO_CONTENT)
  392. def void_weighing(
  393. id: str,
  394. db: Session = Depends(get_db),
  395. user: DbUserContext = Depends(get_db_current_user),
  396. ) -> None:
  397. tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
  398. row = _get_weighing(db, tenant_no, id, user)
  399. if row.is_voided == 1:
  400. raise HTTPException(
  401. status_code=status.HTTP_400_BAD_REQUEST,
  402. detail="Weighing record is already voided",
  403. )
  404. row.is_voided = 1
  405. row.update_by = user.id
  406. db.commit()
  407. process_weighing_business_logic(db, row)
  408. @router.delete("/{id}", status_code=status.HTTP_204_NO_CONTENT)
  409. def delete_weighing(
  410. id: str,
  411. db: Session = Depends(get_db),
  412. user: DbUserContext = Depends(get_db_current_user),
  413. ) -> None:
  414. tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
  415. row = _get_weighing(db, tenant_no, id, user)
  416. assert_row_deletable_by_creator(row, user_info_from_context(user))
  417. row.is_voided = 1
  418. row.update_by = user.id
  419. db.commit()
  420. process_weighing_business_logic(db, row)
  421. class WeighingRelatedData(BaseModel):
  422. plan: Optional[PurchasePlanRead]
  423. inventory: Optional[InboundOutboundRead]
  424. @router.get("/{id}/related", response_model=WeighingRelatedData)
  425. def get_weighing_related(
  426. id: str,
  427. db: Session = Depends(get_db),
  428. user: DbUserContext = Depends(get_db_current_user),
  429. ) -> WeighingRelatedData:
  430. tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
  431. row = _get_weighing(db, tenant_no, id, user)
  432. plan = None
  433. if row.purchase_plan_id:
  434. plan = (
  435. db.query(DbPurchasePlan)
  436. .filter(
  437. DbPurchasePlan.id == row.purchase_plan_id,
  438. DbPurchasePlan.del_flag == 0,
  439. )
  440. .one_or_none()
  441. )
  442. elif row.plan_no:
  443. plan = (
  444. db.query(DbPurchasePlan)
  445. .filter(
  446. DbPurchasePlan.plan_no == row.plan_no,
  447. DbPurchasePlan.tenant_no == tenant_no,
  448. DbPurchasePlan.del_flag == 0,
  449. )
  450. .limit(1)
  451. .first()
  452. )
  453. inventory = None
  454. if row.inbound_outbound_id:
  455. inventory = (
  456. db.query(DbInboundOutbound)
  457. .filter(
  458. DbInboundOutbound.id == row.inbound_outbound_id,
  459. DbInboundOutbound.del_flag == 0,
  460. )
  461. .one_or_none()
  462. )
  463. return WeighingRelatedData(
  464. plan=plan_to_read(plan, db=db) if plan else None,
  465. inventory=inventory_to_read(inventory, db=db) if inventory else None,
  466. )