weighing.py 21 KB

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