plans.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  1. from typing import Optional
  2. from datetime import date, datetime
  3. from fastapi import APIRouter, Depends, HTTPException, Query, status
  4. from pydantic import BaseModel
  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.tenant_context import get_tenant_no
  10. from app.core.utils import generate_uuid
  11. from app.models.db_models import DbInboundOutbound, DbPurchasePlan, DbWeighingSlip
  12. from app.schemas.db.inventory import InboundOutboundRead
  13. from app.schemas.db.plans import (
  14. PurchasePlanCreate,
  15. PurchasePlanRead,
  16. PurchasePlanUpdate,
  17. PurchasePlanWithFillLink,
  18. )
  19. from app.schemas.db.weighing import WeighingSlipRead
  20. from app.services.db.mappers import (
  21. inventory_to_read,
  22. parse_date_str,
  23. parse_datetime_str,
  24. plan_to_read,
  25. plan_to_read_with_fill_link,
  26. weighing_to_read,
  27. )
  28. from app.services.db.product_helpers import (
  29. apply_product_snapshot_to_plan,
  30. resolve_crm_product,
  31. )
  32. router = APIRouter(prefix="/plans", tags=["plans"])
  33. STATUS_THIRD_PARTY_FILL = "待三方填写"
  34. _PLAN_DATE_FIELDS = {"plan_date", "start_date", "end_date"}
  35. _PLAN_REMARK_FIELD = "remarks"
  36. def _base_query(db: Session, tenant_no: str):
  37. return db.query(DbPurchasePlan).filter(
  38. DbPurchasePlan.tenant_no == tenant_no,
  39. DbPurchasePlan.del_flag == 0,
  40. )
  41. @router.get("/", response_model=list[PurchasePlanWithFillLink])
  42. def list_plans(
  43. q: Optional[str] = Query(default=None, description="模糊搜索往来单位或产品"),
  44. plan_no: Optional[str] = Query(default=None, alias="planNo", description="计划号"),
  45. customer_name: Optional[str] = Query(
  46. default=None, alias="customerName", description="往来单位"
  47. ),
  48. product: Optional[str] = Query(default=None, description="产品"),
  49. business_type: Optional[str] = Query(default=None, alias="businessType", description="业务类型"),
  50. execution_status: Optional[str] = Query(
  51. default=None, alias="executionStatus", description="执行状态"
  52. ),
  53. created_from: Optional[str] = Query(default=None, alias="createdFrom", description="创建开始日期"),
  54. created_to: Optional[str] = Query(default=None, alias="createdTo", description="创建结束日期"),
  55. start_date_from: Optional[str] = Query(
  56. default=None, alias="startDateFrom", description="计划起始日期开始"
  57. ),
  58. start_date_to: Optional[str] = Query(
  59. default=None, alias="startDateTo", description="计划起始日期结束"
  60. ),
  61. db: Session = Depends(get_db),
  62. user: DbUserContext = Depends(get_db_current_user),
  63. ) -> list[PurchasePlanWithFillLink]:
  64. tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
  65. query = _base_query(db, tenant_no).order_by(DbPurchasePlan.create_time.desc())
  66. if q:
  67. keyword = q.lower()
  68. query = query.filter(
  69. or_(
  70. func.lower(DbPurchasePlan.customer_name).contains(keyword),
  71. func.lower(DbPurchasePlan.product).contains(keyword),
  72. func.lower(DbPurchasePlan.plan_no).contains(keyword),
  73. )
  74. )
  75. if plan_no:
  76. query = query.filter(DbPurchasePlan.plan_no.contains(plan_no))
  77. if customer_name:
  78. query = query.filter(
  79. func.lower(DbPurchasePlan.customer_name).contains(customer_name.lower())
  80. )
  81. if product:
  82. query = query.filter(func.lower(DbPurchasePlan.product).contains(product.lower()))
  83. if business_type:
  84. query = query.filter(DbPurchasePlan.business_type == business_type)
  85. if execution_status:
  86. query = query.filter(DbPurchasePlan.execution_status == execution_status)
  87. if created_from:
  88. query = query.filter(DbPurchasePlan.create_time >= created_from)
  89. if created_to:
  90. query = query.filter(DbPurchasePlan.create_time <= f"{created_to} 23:59:59")
  91. if start_date_from:
  92. start_from = parse_date_str(start_date_from)
  93. if start_from:
  94. query = query.filter(DbPurchasePlan.start_date >= start_from)
  95. if start_date_to:
  96. start_to = parse_date_str(start_date_to)
  97. if start_to:
  98. query = query.filter(DbPurchasePlan.start_date <= start_to)
  99. plans = query.all()
  100. if not plans:
  101. return []
  102. plan_ids = [p.id for p in plans]
  103. fill_links = (
  104. db.query(DbInboundOutbound)
  105. .filter(
  106. DbInboundOutbound.tenant_no == tenant_no,
  107. DbInboundOutbound.del_flag == 0,
  108. DbInboundOutbound.purchase_plan_id.in_(plan_ids),
  109. DbInboundOutbound.status == STATUS_THIRD_PARTY_FILL,
  110. )
  111. .all()
  112. )
  113. plan_id_to_inv_id = {
  114. inv.purchase_plan_id: inv.id for inv in fill_links if inv.purchase_plan_id
  115. }
  116. plan_nos = [p.plan_no for p in plans if p.plan_no]
  117. executed_sum_map: dict[tuple[Optional[str], Optional[str]], float] = {}
  118. if plan_ids or plan_nos:
  119. weighing_filters = [DbWeighingSlip.is_voided == 0, DbWeighingSlip.del_flag == 0]
  120. weighing_filters.append(DbWeighingSlip.tenant_no == tenant_no)
  121. id_filters = []
  122. if plan_ids:
  123. id_filters.append(DbWeighingSlip.purchase_plan_id.in_(plan_ids))
  124. if plan_nos:
  125. id_filters.append(DbWeighingSlip.plan_no.in_(plan_nos))
  126. weighing_filters.append(or_(*id_filters))
  127. weighing_rows = (
  128. db.query(
  129. DbWeighingSlip.purchase_plan_id,
  130. DbWeighingSlip.plan_no,
  131. func.sum(DbWeighingSlip.net_weight).label("total_executed"),
  132. )
  133. .filter(*weighing_filters)
  134. .group_by(DbWeighingSlip.purchase_plan_id, DbWeighingSlip.plan_no)
  135. .all()
  136. )
  137. for row in weighing_rows:
  138. key = (row.purchase_plan_id, row.plan_no)
  139. executed_sum_map[key] = float(row.total_executed or 0)
  140. def calc_executed_for_plan(plan: DbPurchasePlan) -> float:
  141. if not executed_sum_map:
  142. return 0.0
  143. total = 0.0
  144. for (pid, pno), executed in executed_sum_map.items():
  145. if pid is not None and pid == plan.id:
  146. total += executed
  147. elif pno and plan.plan_no and pno == plan.plan_no:
  148. total += executed
  149. return total
  150. result_list: list[PurchasePlanWithFillLink] = []
  151. for plan in plans:
  152. result_list.append(
  153. plan_to_read_with_fill_link(
  154. plan,
  155. executed_quantity=calc_executed_for_plan(plan),
  156. fill_link_inventory_id=plan_id_to_inv_id.get(plan.id),
  157. )
  158. )
  159. return result_list
  160. def _generate_plan_no() -> str:
  161. from app.services.db.plan_helpers import generate_plan_no
  162. return generate_plan_no()
  163. @router.post("/", response_model=PurchasePlanRead, status_code=status.HTTP_201_CREATED)
  164. def create_plan(
  165. payload: PurchasePlanCreate,
  166. db: Session = Depends(get_db),
  167. user: DbUserContext = Depends(get_db_current_user),
  168. ) -> PurchasePlanRead:
  169. tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
  170. plan_no = payload.plan_no if payload.plan_no else _generate_plan_no()
  171. execution_status = payload.execution_status
  172. if not execution_status:
  173. execution_status = "待入库" if payload.business_type == "入库" else "待出库"
  174. snapshot = resolve_crm_product(db, tenant_no, payload.product_id)
  175. plan = DbPurchasePlan(
  176. id=generate_uuid(),
  177. tenant_no=tenant_no,
  178. plan_no=plan_no,
  179. plan_date=parse_date_str(payload.plan_date) or date.today(),
  180. start_date=parse_date_str(payload.start_date),
  181. end_date=parse_date_str(payload.end_date),
  182. business_type=payload.business_type,
  183. planned_quantity=payload.planned_quantity,
  184. vehicle_no=payload.vehicle_no or "",
  185. customer_name=payload.customer_name.strip() if payload.customer_name else None,
  186. remark=payload.remarks,
  187. execution_status=execution_status,
  188. executed_at=None,
  189. last_weighing_slip_id=None,
  190. executed_quantity=0,
  191. auto_generate_enabled=payload.auto_generate_enabled or 0,
  192. auto_generate_end_month=payload.auto_generate_end_month,
  193. auto_generate_last_month=None,
  194. create_by=user.id,
  195. create_dept_id=user.dept_id,
  196. )
  197. apply_product_snapshot_to_plan(plan, snapshot)
  198. db.add(plan)
  199. db.commit()
  200. db.refresh(plan)
  201. return plan_to_read(plan)
  202. class AutoGenerateMonthlyResult(BaseModel):
  203. created_count: int
  204. skipped_reason: Optional[str] = None
  205. current_month: str
  206. @router.post("/run-auto-generate", response_model=AutoGenerateMonthlyResult)
  207. def run_auto_generate_monthly(
  208. force: bool = Query(default=False, description="true 时跳过「仅每月1日」限制,供验收手动触发"),
  209. db: Session = Depends(get_db),
  210. user: DbUserContext = Depends(get_db_current_user),
  211. ) -> AutoGenerateMonthlyResult:
  212. """手动触发计划按月自动生成(定时任务同款逻辑)。"""
  213. get_tenant_no(db, user.to_tenant_user_dict())
  214. from app.services.db.auto_generate_plans import run_auto_generate_monthly_plans
  215. result = run_auto_generate_monthly_plans(db, force=force)
  216. return AutoGenerateMonthlyResult(**result)
  217. @router.get("/{id}", response_model=PurchasePlanRead)
  218. def get_plan(
  219. id: str,
  220. db: Session = Depends(get_db),
  221. user: DbUserContext = Depends(get_db_current_user),
  222. ) -> PurchasePlanRead:
  223. tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
  224. plan = _get_plan(db, tenant_no, id)
  225. return plan_to_read(plan)
  226. @router.patch("/{id}", response_model=PurchasePlanRead)
  227. def update_plan(
  228. id: str,
  229. payload: PurchasePlanUpdate,
  230. db: Session = Depends(get_db),
  231. user: DbUserContext = Depends(get_db_current_user),
  232. ) -> PurchasePlanRead:
  233. tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
  234. plan = _get_plan(db, tenant_no, id)
  235. payload_dict = payload.model_dump(exclude_unset=True)
  236. _apply_plan_product_update(db, tenant_no, plan, payload_dict)
  237. _apply_plan_update(plan, payload_dict)
  238. plan.update_by = user.id
  239. db.commit()
  240. db.refresh(plan)
  241. return plan_to_read(plan)
  242. @router.delete("/{id}", status_code=status.HTTP_204_NO_CONTENT)
  243. def delete_plan(
  244. id: str,
  245. db: Session = Depends(get_db),
  246. user: DbUserContext = Depends(get_db_current_user),
  247. ) -> None:
  248. tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
  249. plan = _get_plan(db, tenant_no, id)
  250. plan.del_flag = 1
  251. plan.update_by = user.id
  252. db.commit()
  253. def _get_plan(db: Session, tenant_no: str, plan_id: str) -> DbPurchasePlan:
  254. plan = (
  255. _base_query(db, tenant_no)
  256. .filter(DbPurchasePlan.id == plan_id)
  257. .one_or_none()
  258. )
  259. if plan is None:
  260. raise HTTPException(
  261. status_code=status.HTTP_404_NOT_FOUND,
  262. detail=f"Plan {plan_id} not found",
  263. )
  264. return plan
  265. def _get_plan_by_id_only(db: Session, plan_id: str) -> DbPurchasePlan:
  266. plan = (
  267. db.query(DbPurchasePlan)
  268. .filter(DbPurchasePlan.id == plan_id, DbPurchasePlan.del_flag == 0)
  269. .one_or_none()
  270. )
  271. if plan is None:
  272. raise HTTPException(
  273. status_code=status.HTTP_404_NOT_FOUND,
  274. detail=f"Plan {plan_id} not found",
  275. )
  276. return plan
  277. def _apply_plan_product_update(
  278. db: Session, tenant_no: str, plan: DbPurchasePlan, payload_dict: dict
  279. ) -> None:
  280. if "product" in payload_dict and "product_id" not in payload_dict:
  281. raise HTTPException(
  282. status_code=status.HTTP_400_BAD_REQUEST,
  283. detail="请从 CRM 重新选择产品",
  284. )
  285. product_id = payload_dict.pop("product_id", None)
  286. payload_dict.pop("product", None)
  287. payload_dict.pop("specification", None)
  288. if product_id is not None:
  289. snapshot = resolve_crm_product(db, tenant_no, product_id)
  290. apply_product_snapshot_to_plan(plan, snapshot)
  291. def _apply_plan_update(plan: DbPurchasePlan, payload_dict: dict) -> None:
  292. for key, value in payload_dict.items():
  293. if key == _PLAN_REMARK_FIELD:
  294. if isinstance(value, str):
  295. value = value.strip()
  296. plan.remark = value
  297. continue
  298. if key in _PLAN_DATE_FIELDS:
  299. if value is None:
  300. setattr(plan, key, None)
  301. else:
  302. setattr(plan, key, parse_date_str(str(value)))
  303. continue
  304. if key == "executed_at":
  305. plan.executed_at = parse_datetime_str(str(value)) if value else None
  306. continue
  307. if isinstance(value, str):
  308. value = value.strip()
  309. setattr(plan, key, value)
  310. class PlanRelatedData(BaseModel):
  311. inventories: list[InboundOutboundRead]
  312. weighings: list[WeighingSlipRead]
  313. @router.get("/{id}/related", response_model=PlanRelatedData)
  314. def get_plan_related(
  315. id: str,
  316. db: Session = Depends(get_db),
  317. user: DbUserContext = Depends(get_db_current_user),
  318. ) -> PlanRelatedData:
  319. tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
  320. plan = _get_plan(db, tenant_no, id)
  321. inventories = (
  322. db.query(DbInboundOutbound)
  323. .filter(
  324. DbInboundOutbound.tenant_no == tenant_no,
  325. DbInboundOutbound.del_flag == 0,
  326. DbInboundOutbound.purchase_plan_id == plan.id,
  327. )
  328. .order_by(DbInboundOutbound.date.desc(), DbInboundOutbound.id.desc())
  329. .all()
  330. )
  331. weighing_query = db.query(DbWeighingSlip).filter(
  332. DbWeighingSlip.tenant_no == tenant_no,
  333. DbWeighingSlip.del_flag == 0,
  334. DbWeighingSlip.is_voided == 0,
  335. )
  336. if plan.plan_no:
  337. weighing_query = weighing_query.filter(
  338. or_(
  339. DbWeighingSlip.plan_no == plan.plan_no,
  340. DbWeighingSlip.purchase_plan_id == plan.id,
  341. )
  342. )
  343. else:
  344. weighing_query = weighing_query.filter(DbWeighingSlip.purchase_plan_id == plan.id)
  345. weighings = weighing_query.order_by(DbWeighingSlip.create_time.desc()).all()
  346. return PlanRelatedData(
  347. inventories=[inventory_to_read(inv) for inv in inventories],
  348. weighings=[weighing_to_read(w) for w in weighings],
  349. )
  350. class ThirdPartyPlanPageData(BaseModel):
  351. plan: PurchasePlanRead
  352. today_inventories: list[InboundOutboundRead]
  353. month_inventories: list[InboundOutboundRead]
  354. @router.get("/{id}/third-party-page", response_model=ThirdPartyPlanPageData)
  355. def get_third_party_plan_page(
  356. id: str,
  357. db: Session = Depends(get_db),
  358. ) -> ThirdPartyPlanPageData:
  359. """三方 H5 填写页初始化数据(无需门户登录,与原系统一致)。"""
  360. plan = _get_plan_by_id_only(db, id)
  361. tenant_no = plan.tenant_no
  362. today = date.today()
  363. start = plan.start_date
  364. end = plan.end_date
  365. if start and today < start:
  366. raise HTTPException(
  367. status_code=status.HTTP_400_BAD_REQUEST,
  368. detail="计划尚未生效,当前日期不允许填写出入库单",
  369. )
  370. if end and today > end:
  371. raise HTTPException(
  372. status_code=status.HTTP_400_BAD_REQUEST,
  373. detail="计划已过期,当前日期不允许填写出入库单",
  374. )
  375. today_str = today.strftime("%Y-%m-%d")
  376. today_date = parse_date_str(today_str)
  377. inventories = (
  378. db.query(DbInboundOutbound)
  379. .filter(
  380. DbInboundOutbound.tenant_no == tenant_no,
  381. DbInboundOutbound.del_flag == 0,
  382. DbInboundOutbound.purchase_plan_id == plan.id,
  383. DbInboundOutbound.date == today_date,
  384. )
  385. .order_by(DbInboundOutbound.date.desc(), DbInboundOutbound.id.desc())
  386. .all()
  387. )
  388. month_start = today.replace(day=1)
  389. month_history = (
  390. db.query(DbInboundOutbound)
  391. .filter(
  392. DbInboundOutbound.tenant_no == tenant_no,
  393. DbInboundOutbound.del_flag == 0,
  394. DbInboundOutbound.purchase_plan_id == plan.id,
  395. DbInboundOutbound.date >= month_start,
  396. DbInboundOutbound.date < today,
  397. )
  398. .order_by(DbInboundOutbound.date.desc(), DbInboundOutbound.id.desc())
  399. .all()
  400. )
  401. return ThirdPartyPlanPageData(
  402. plan=plan_to_read(plan),
  403. today_inventories=[inventory_to_read(inv) for inv in inventories],
  404. month_inventories=[inventory_to_read(inv) for inv in month_history],
  405. )