weighing.py 23 KB

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