inventory.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. """运输计划管理 - 盘存统计 API"""
  2. from datetime import date
  3. from decimal import Decimal
  4. from typing import Optional
  5. from fastapi import APIRouter, Depends, HTTPException, Query
  6. from sqlalchemy import func
  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.services.pl_data_scope import apply_pl_scope, assert_pl_row_in_scope
  11. from app.core.tenant_context import get_tenant_no
  12. from app.core.utils import generate_uuid
  13. from app.models.pl_models import (
  14. PlDocumentReminder,
  15. PlInventory,
  16. PlInventoryTransaction,
  17. PlInventoryWarning,
  18. )
  19. from app.schemas.pl.inventory import (
  20. DocumentReminderRead,
  21. DocumentReminderStatsRead,
  22. DocumentReminderUpdate,
  23. InventoryLedgerQuery,
  24. InventoryLedgerResponse,
  25. InventoryRead,
  26. InventorySummaryItem,
  27. InventorySummaryResponse,
  28. InventoryTransactionQuery,
  29. InventoryTransactionRead,
  30. InventoryTransactionResponse,
  31. InventoryWarningRead,
  32. InventoryWarningThreshold,
  33. InventoryWarningUpdate,
  34. TransportStatsItem,
  35. TransportStatsResponse,
  36. )
  37. from app.services.pl_cert_service import scan_cert_expiry
  38. router = APIRouter(prefix="/inventory", tags=["运输计划-盘存统计"])
  39. # =============================================================================
  40. # 库存台账
  41. # =============================================================================
  42. @router.get("/ledger", response_model=InventoryLedgerResponse)
  43. def get_inventory_ledger(
  44. product_name: Optional[str] = Query(default=None, alias="productName", description="产品名称"),
  45. page: int = Query(default=1, ge=1),
  46. page_size: int = Query(default=20, ge=1, le=100, alias="pageSize"),
  47. db: Session = Depends(get_db),
  48. user: DbUserContext = Depends(get_db_current_user),
  49. ) -> InventoryLedgerResponse:
  50. tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
  51. query = db.query(PlInventory).filter(
  52. PlInventory.tenant_no == tenant_no,
  53. PlInventory.del_flag == 0,
  54. )
  55. if product_name:
  56. query = query.filter(PlInventory.product_name.contains(product_name))
  57. query = apply_pl_scope(query, PlInventory, user, db, tenant_no)
  58. total = query.count()
  59. offset = (page - 1) * page_size
  60. items = query.order_by(PlInventory.product_name).offset(offset).limit(page_size).all()
  61. return InventoryLedgerResponse(total=total, list=items)
  62. # =============================================================================
  63. # 库存预警阈值设置
  64. # =============================================================================
  65. @router.post("/warning-threshold")
  66. def set_warning_threshold(
  67. payload: InventoryWarningThreshold,
  68. db: Session = Depends(get_db),
  69. user: DbUserContext = Depends(get_db_current_user),
  70. ) -> dict:
  71. tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
  72. brand_id = payload.brand_id or ""
  73. inventory = (
  74. db.query(PlInventory)
  75. .filter(
  76. PlInventory.product_id == payload.product_id,
  77. PlInventory.brand_id == brand_id,
  78. PlInventory.tenant_no == tenant_no,
  79. PlInventory.del_flag == 0,
  80. )
  81. .first()
  82. )
  83. if inventory:
  84. assert_pl_row_in_scope(db, inventory, PlInventory, user, tenant_no)
  85. inventory.low_stock_warning = payload.low_stock_warning
  86. inventory.high_stock_warning = payload.high_stock_warning
  87. if payload.brand_name is not None:
  88. inventory.brand_name = payload.brand_name
  89. else:
  90. # 创建库存记录
  91. inventory = PlInventory(
  92. id=generate_uuid(),
  93. tenant_no=tenant_no,
  94. product_id=payload.product_id,
  95. brand_id=brand_id,
  96. brand_name=payload.brand_name,
  97. product_no="",
  98. product_name="",
  99. unit="吨",
  100. stock_qty=0,
  101. stock_amount=0,
  102. low_stock_warning=payload.low_stock_warning,
  103. high_stock_warning=payload.high_stock_warning,
  104. create_by=user.id,
  105. create_dept_id=user.dept_id,
  106. )
  107. db.add(inventory)
  108. db.commit()
  109. return {"success": True}
  110. # =============================================================================
  111. # 库存预警列表
  112. # =============================================================================
  113. @router.get("/warnings", response_model=list[InventoryWarningRead])
  114. def list_warnings(
  115. status: Optional[str] = Query(default=None, description="状态"),
  116. db: Session = Depends(get_db),
  117. user: DbUserContext = Depends(get_db_current_user),
  118. ) -> list[InventoryWarningRead]:
  119. tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
  120. query = db.query(PlInventoryWarning).filter(
  121. PlInventoryWarning.tenant_no == tenant_no,
  122. PlInventoryWarning.del_flag == 0,
  123. )
  124. if status:
  125. query = query.filter(PlInventoryWarning.status == status)
  126. query = apply_pl_scope(query, PlInventoryWarning, user, db, tenant_no)
  127. return query.order_by(PlInventoryWarning.create_time.desc()).all()
  128. @router.put("/warnings/{id}", response_model=InventoryWarningRead)
  129. def update_warning(
  130. id: str,
  131. payload: InventoryWarningUpdate,
  132. db: Session = Depends(get_db),
  133. user: DbUserContext = Depends(get_db_current_user),
  134. ) -> InventoryWarningRead:
  135. tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
  136. warning = (
  137. db.query(PlInventoryWarning)
  138. .filter(
  139. PlInventoryWarning.id == id,
  140. PlInventoryWarning.tenant_no == tenant_no,
  141. PlInventoryWarning.del_flag == 0,
  142. )
  143. .first()
  144. )
  145. if not warning:
  146. raise HTTPException(status_code=404, detail="预警不存在")
  147. assert_pl_row_in_scope(db, warning, PlInventoryWarning, user, tenant_no)
  148. if payload.status == "resolved":
  149. warning.status = "resolved"
  150. from datetime import datetime
  151. warning.resolve_time = datetime.now()
  152. warning.resolve_remark = payload.resolve_remark
  153. db.commit()
  154. db.refresh(warning)
  155. return warning
  156. # =============================================================================
  157. # 出入库明细
  158. # =============================================================================
  159. @router.get("/transactions", response_model=InventoryTransactionResponse)
  160. def list_transactions(
  161. product_id: Optional[str] = Query(default=None, alias="productId", description="产品ID"),
  162. transaction_type: Optional[str] = Query(default=None, alias="transactionType", description="事务类型"),
  163. date_from: Optional[date] = Query(default=None, alias="dateFrom", description="开始日期"),
  164. date_to: Optional[date] = Query(default=None, alias="dateTo", description="结束日期"),
  165. page: int = Query(default=1, ge=1),
  166. page_size: int = Query(default=20, ge=1, le=100, alias="pageSize"),
  167. db: Session = Depends(get_db),
  168. user: DbUserContext = Depends(get_db_current_user),
  169. ) -> InventoryTransactionResponse:
  170. tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
  171. query = db.query(PlInventoryTransaction).filter(
  172. PlInventoryTransaction.tenant_no == tenant_no,
  173. PlInventoryTransaction.del_flag == 0,
  174. )
  175. if product_id:
  176. query = query.filter(PlInventoryTransaction.product_id == product_id)
  177. if transaction_type:
  178. query = query.filter(PlInventoryTransaction.transaction_type == transaction_type)
  179. if date_from:
  180. query = query.filter(PlInventoryTransaction.create_time >= date_from)
  181. if date_to:
  182. query = query.filter(PlInventoryTransaction.create_time <= date_to)
  183. query = apply_pl_scope(query, PlInventoryTransaction, user, db, tenant_no)
  184. total = query.count()
  185. offset = (page - 1) * page_size
  186. items = query.order_by(PlInventoryTransaction.create_time.desc()).offset(offset).limit(page_size).all()
  187. return InventoryTransactionResponse(total=total, list=items)
  188. # =============================================================================
  189. # 出入库汇总
  190. # =============================================================================
  191. @router.get("/summary", response_model=InventorySummaryResponse)
  192. def get_summary(
  193. group_by: str = Query(default="month", description="汇总维度 month/week"),
  194. date_from: date = Query(..., alias="dateFrom", description="开始日期"),
  195. date_to: date = Query(..., alias="dateTo", description="结束日期"),
  196. product_id: Optional[str] = Query(default=None, alias="productId", description="产品ID"),
  197. db: Session = Depends(get_db),
  198. user: DbUserContext = Depends(get_db_current_user),
  199. ) -> InventorySummaryResponse:
  200. tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
  201. query = db.query(PlInventoryTransaction).filter(
  202. PlInventoryTransaction.tenant_no == tenant_no,
  203. PlInventoryTransaction.del_flag == 0,
  204. PlInventoryTransaction.create_time >= date_from,
  205. PlInventoryTransaction.create_time <= date_to,
  206. )
  207. query = apply_pl_scope(query, PlInventoryTransaction, user, db, tenant_no)
  208. if product_id:
  209. query = query.filter(PlInventoryTransaction.product_id == product_id)
  210. transactions = query.all()
  211. # 按产品分组汇总
  212. summary_map = {}
  213. for t in transactions:
  214. key = t.product_id
  215. if key not in summary_map:
  216. summary_map[key] = {
  217. "product_id": t.product_id,
  218. "product_name": t.product_name,
  219. "inbound_qty": Decimal("0"),
  220. "outbound_qty": Decimal("0"),
  221. }
  222. if t.transaction_type == "inbound":
  223. summary_map[key]["inbound_qty"] += t.qty
  224. else:
  225. summary_map[key]["outbound_qty"] += abs(t.qty)
  226. items = []
  227. for key, data in summary_map.items():
  228. net = data["inbound_qty"] - data["outbound_qty"]
  229. items.append(InventorySummaryItem(
  230. period="汇总",
  231. product_id=data["product_id"],
  232. product_name=data["product_name"],
  233. inbound_qty=data["inbound_qty"],
  234. outbound_qty=data["outbound_qty"],
  235. net_change=net,
  236. ))
  237. return InventorySummaryResponse(list=items)
  238. # =============================================================================
  239. # 证件到期提醒
  240. # =============================================================================
  241. @router.get("/document-reminders/stats", response_model=DocumentReminderStatsRead)
  242. def document_reminder_stats(
  243. db: Session = Depends(get_db),
  244. user: DbUserContext = Depends(get_db_current_user),
  245. ) -> DocumentReminderStatsRead:
  246. tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
  247. scan_cert_expiry(db, tenant_no)
  248. db.commit()
  249. query = db.query(PlDocumentReminder).filter(
  250. PlDocumentReminder.tenant_no == tenant_no,
  251. PlDocumentReminder.del_flag == 0,
  252. PlDocumentReminder.status == "pending",
  253. PlDocumentReminder.days_remaining <= 0,
  254. )
  255. query = apply_pl_scope(query, PlDocumentReminder, user, db, tenant_no)
  256. expired_pending_count = query.count()
  257. return DocumentReminderStatsRead(expired_pending_count=expired_pending_count)
  258. @router.get("/document-reminders", response_model=list[DocumentReminderRead])
  259. def list_document_reminders(
  260. status: Optional[str] = Query(default=None, description="状态"),
  261. db: Session = Depends(get_db),
  262. user: DbUserContext = Depends(get_db_current_user),
  263. ) -> list[DocumentReminderRead]:
  264. tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
  265. scan_cert_expiry(db, tenant_no)
  266. db.commit()
  267. query = db.query(PlDocumentReminder).filter(
  268. PlDocumentReminder.tenant_no == tenant_no,
  269. PlDocumentReminder.del_flag == 0,
  270. )
  271. if status:
  272. query = query.filter(PlDocumentReminder.status == status)
  273. query = apply_pl_scope(query, PlDocumentReminder, user, db, tenant_no)
  274. return query.order_by(PlDocumentReminder.expire_date.asc()).all()
  275. @router.put("/document-reminders/{id}", response_model=DocumentReminderRead)
  276. def update_document_reminder(
  277. id: str,
  278. payload: DocumentReminderUpdate,
  279. db: Session = Depends(get_db),
  280. user: DbUserContext = Depends(get_db_current_user),
  281. ) -> DocumentReminderRead:
  282. tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
  283. reminder = (
  284. db.query(PlDocumentReminder)
  285. .filter(
  286. PlDocumentReminder.id == id,
  287. PlDocumentReminder.tenant_no == tenant_no,
  288. PlDocumentReminder.del_flag == 0,
  289. )
  290. .first()
  291. )
  292. if not reminder:
  293. raise HTTPException(status_code=404, detail="提醒不存在")
  294. assert_pl_row_in_scope(db, reminder, PlDocumentReminder, user, tenant_no)
  295. reminder.status = payload.status
  296. if payload.remark:
  297. reminder.remark = payload.remark
  298. db.commit()
  299. db.refresh(reminder)
  300. return reminder
  301. # =============================================================================
  302. # 生成证件到期提醒(定时任务调用)
  303. # =============================================================================
  304. @router.post("/check-document-expiry")
  305. def check_document_expiry(db: Session = Depends(get_db)) -> dict:
  306. """检查证件到期,生成提醒(供定时任务调用)"""
  307. created_count = scan_cert_expiry(db)
  308. db.commit()
  309. return {"created_count": created_count}