weighing.py 20 KB

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