production_material.py 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165
  1. """生产物料库 API"""
  2. from typing import List, Optional
  3. from datetime import datetime
  4. from decimal import Decimal
  5. from fastapi import APIRouter, Depends, HTTPException, Query
  6. from pydantic import BaseModel, ConfigDict, Field
  7. from sqlalchemy.orm import Session
  8. from app.core.database import get_db
  9. from app.core.menu_guard import require_any_menu_code, require_menu_code
  10. from app.core.response import error_response, success_response
  11. from app.core.utils import parse_datetime
  12. from app.crud import production_material as mat_svc
  13. from app.crud import production_material_stock_batch as batch_svc
  14. from app.crud import production_material_stock_check as stock_check_svc
  15. from app.crud import production_material_usage as mu_svc
  16. from app.crud import production_material_formula as formula_svc
  17. from app.crud import production_material_prep as prep_svc
  18. from app.api.sample_reception import _get_current_user_id, _get_tenant_no, _page_payload
  19. router = APIRouter(tags=["生产物料库"])
  20. # ---------- 生产物料库 ----------
  21. class ProductionMaterialBody(BaseModel):
  22. model_config = ConfigDict(populate_by_name=True)
  23. material_type: str = Field(..., alias="materialType")
  24. material_code: str = Field(..., alias="materialCode")
  25. material_name: str = Field(..., alias="materialName")
  26. spec_model: Optional[str] = Field(None, alias="specModel")
  27. unit: Optional[str] = None
  28. warning_qty: Optional[float] = Field(0, alias="warningQty")
  29. status: str = "1"
  30. remark: Optional[str] = None
  31. class ProductionMaterialUpdateBody(BaseModel):
  32. model_config = ConfigDict(populate_by_name=True)
  33. material_type: Optional[str] = Field(None, alias="materialType")
  34. material_code: Optional[str] = Field(None, alias="materialCode")
  35. material_name: Optional[str] = Field(None, alias="materialName")
  36. spec_model: Optional[str] = Field(None, alias="specModel")
  37. unit: Optional[str] = None
  38. warning_qty: Optional[float] = Field(None, alias="warningQty")
  39. status: Optional[str] = None
  40. remark: Optional[str] = None
  41. class StockInBody(BaseModel):
  42. model_config = ConfigDict(populate_by_name=True)
  43. stock_in_no: str = Field(..., alias="stockInNo")
  44. stock_in_date: str = Field(..., alias="stockInDate")
  45. expire_date: str = Field(..., alias="expireDate")
  46. catalog_no: str = Field(..., alias="catalogNo")
  47. batch_no: str = Field(..., alias="batchNo")
  48. manufacturer: str
  49. storage_location: Optional[str] = Field(None, alias="storageLocation")
  50. unit_price: float = Field(..., alias="unitPrice")
  51. amount: float
  52. qty: float = Field(..., gt=0)
  53. remark: Optional[str] = None
  54. stock_in_time: Optional[str] = Field(None, alias="stockInTime")
  55. class BatchStockInItem(BaseModel):
  56. model_config = ConfigDict(populate_by_name=True)
  57. material_id: str = Field(..., alias="materialId")
  58. stock_in_no: str = Field(..., alias="stockInNo")
  59. stock_in_date: str = Field(..., alias="stockInDate")
  60. expire_date: str = Field(..., alias="expireDate")
  61. catalog_no: str = Field(..., alias="catalogNo")
  62. batch_no: str = Field(..., alias="batchNo")
  63. manufacturer: str
  64. storage_location: Optional[str] = Field(None, alias="storageLocation")
  65. unit_price: float = Field(..., alias="unitPrice")
  66. amount: float
  67. qty: float = Field(..., gt=0)
  68. remark: Optional[str] = None
  69. class BatchStockInBody(BaseModel):
  70. model_config = ConfigDict(populate_by_name=True)
  71. items: List[BatchStockInItem] = Field(..., min_length=1)
  72. remark: Optional[str] = None
  73. stock_in_time: Optional[str] = Field(None, alias="stockInTime")
  74. class BatchStockOutItem(BaseModel):
  75. model_config = ConfigDict(populate_by_name=True)
  76. batch_id: str = Field(..., alias="batchId")
  77. qty: float = Field(..., gt=0)
  78. remark: Optional[str] = None
  79. class BatchStockOutBody(BaseModel):
  80. model_config = ConfigDict(populate_by_name=True)
  81. items: List[BatchStockOutItem] = Field(..., min_length=1)
  82. receiver: Optional[str] = None
  83. purpose: Optional[str] = None
  84. remark: Optional[str] = None
  85. stock_out_time: Optional[str] = Field(None, alias="stockOutTime")
  86. class BatchDiscardItem(BaseModel):
  87. model_config = ConfigDict(populate_by_name=True)
  88. batch_id: str = Field(..., alias="batchId")
  89. qty: float = Field(..., gt=0)
  90. usage_unit: Optional[str] = Field(None, alias="usageUnit")
  91. remark: Optional[str] = None
  92. class BatchDiscardBody(BaseModel):
  93. model_config = ConfigDict(populate_by_name=True)
  94. items: List[BatchDiscardItem] = Field(..., min_length=1)
  95. discard_reason: str = Field(..., alias="discardReason")
  96. remark: Optional[str] = None
  97. discard_time: Optional[str] = Field(None, alias="discardTime")
  98. class ProductionMaterialBatchUpdateBody(BaseModel):
  99. model_config = ConfigDict(populate_by_name=True)
  100. stock_in_no: Optional[str] = Field(None, alias="stockInNo")
  101. stock_in_date: Optional[str] = Field(None, alias="stockInDate")
  102. expire_date: Optional[str] = Field(None, alias="expireDate")
  103. catalog_no: Optional[str] = Field(None, alias="catalogNo")
  104. batch_no: Optional[str] = Field(None, alias="batchNo")
  105. manufacturer: Optional[str] = None
  106. storage_location: Optional[str] = Field(None, alias="storageLocation")
  107. unit_price: Optional[float] = Field(None, alias="unitPrice")
  108. amount: Optional[float] = None
  109. remark: Optional[str] = None
  110. material_code: Optional[str] = Field(None, alias="materialCode")
  111. material_name: Optional[str] = Field(None, alias="materialName")
  112. spec_model: Optional[str] = Field(None, alias="specModel")
  113. unit: Optional[str] = None
  114. warning_qty: Optional[float] = Field(None, alias="warningQty")
  115. status: Optional[str] = None
  116. @router.get("/production-material-batches")
  117. async def list_production_material_batches(
  118. page: int = Query(1, ge=1),
  119. pageSize: int = Query(10, ge=1, le=100),
  120. keyword: Optional[str] = None,
  121. materialId: Optional[str] = None,
  122. materialType: Optional[str] = None,
  123. status: Optional[str] = None,
  124. db: Session = Depends(get_db),
  125. user: dict = Depends(require_menu_code("production:material:list")),
  126. ):
  127. try:
  128. tenant_no = _get_tenant_no(db, user)
  129. items, total = batch_svc.list_batches(
  130. db,
  131. page=page,
  132. page_size=pageSize,
  133. keyword=keyword,
  134. material_id=materialId,
  135. material_type=materialType,
  136. status=status,
  137. tenant_no=tenant_no,
  138. user_info=user,
  139. )
  140. return success_response(_page_payload(items, total, page, pageSize))
  141. except PermissionError as e:
  142. return error_response(403, str(e))
  143. except Exception as e:
  144. return error_response(400, str(e))
  145. @router.get("/production-material-batches/options")
  146. async def production_material_batch_options(
  147. keyword: Optional[str] = None,
  148. materialId: Optional[str] = None,
  149. materialType: Optional[str] = None,
  150. onlyAvailable: bool = Query(True, alias="onlyAvailable"),
  151. db: Session = Depends(get_db),
  152. user: dict = Depends(require_menu_code("production:material:list")),
  153. ):
  154. try:
  155. tenant_no = _get_tenant_no(db, user)
  156. return success_response(
  157. batch_svc.batch_options(
  158. db,
  159. tenant_no,
  160. keyword=keyword,
  161. material_id=materialId,
  162. material_type=materialType,
  163. only_available=onlyAvailable,
  164. )
  165. )
  166. except Exception as e:
  167. return error_response(400, str(e))
  168. @router.put("/production-material-batches/{batch_id}")
  169. async def update_production_material_batch(
  170. batch_id: str,
  171. body: ProductionMaterialBatchUpdateBody,
  172. db: Session = Depends(get_db),
  173. user: dict = Depends(require_menu_code("production:material:list")),
  174. ):
  175. try:
  176. tenant_no = _get_tenant_no(db, user)
  177. user_id = _get_current_user_id(user)
  178. data = body.model_dump(exclude_none=True)
  179. obj = batch_svc.update_batch(
  180. db,
  181. batch_id,
  182. tenant_no=tenant_no,
  183. user_id=user_id,
  184. **data,
  185. )
  186. material = mat_svc.get_material(db, obj.material_id, tenant_no=tenant_no)
  187. return success_response(
  188. batch_svc._batch_row_to_dict(obj, material),
  189. message="更新成功",
  190. )
  191. except ValueError as e:
  192. return error_response(400, str(e))
  193. except Exception as e:
  194. return error_response(400, str(e))
  195. @router.delete("/production-material-batches/{batch_id}")
  196. async def delete_production_material_batch(
  197. batch_id: str,
  198. db: Session = Depends(get_db),
  199. user: dict = Depends(require_menu_code("production:material:list")),
  200. ):
  201. try:
  202. tenant_no = _get_tenant_no(db, user)
  203. user_id = _get_current_user_id(user)
  204. batch_svc.delete_batch(db, batch_id, tenant_no=tenant_no, user_id=user_id)
  205. return success_response(None, message="删除成功")
  206. except ValueError as e:
  207. return error_response(400, str(e))
  208. except Exception as e:
  209. return error_response(400, str(e))
  210. @router.get("/production-materials")
  211. async def list_production_materials(
  212. page: int = Query(1, ge=1),
  213. pageSize: int = Query(10, ge=1, le=100),
  214. keyword: Optional[str] = None,
  215. materialType: Optional[str] = None,
  216. status: Optional[str] = None,
  217. db: Session = Depends(get_db),
  218. user: dict = Depends(require_menu_code("production:material:list")),
  219. ):
  220. try:
  221. tenant_no = _get_tenant_no(db, user)
  222. items, total = mat_svc.list_materials(
  223. db,
  224. page=page,
  225. page_size=pageSize,
  226. keyword=keyword,
  227. material_type=materialType,
  228. status=status,
  229. tenant_no=tenant_no,
  230. user_info=user,
  231. )
  232. return success_response(_page_payload(items, total, page, pageSize))
  233. except PermissionError as e:
  234. return error_response(403, str(e))
  235. except Exception as e:
  236. return error_response(400, str(e))
  237. @router.get("/production-materials/options")
  238. async def production_material_options(
  239. materialType: Optional[str] = None,
  240. db: Session = Depends(get_db),
  241. user: dict = Depends(require_menu_code("production:material:list")),
  242. ):
  243. try:
  244. tenant_no = _get_tenant_no(db, user)
  245. return success_response(
  246. mat_svc.options_list(db, tenant_no=tenant_no, material_type=materialType)
  247. )
  248. except Exception as e:
  249. return error_response(400, str(e))
  250. @router.post("/production-materials")
  251. async def create_production_material(
  252. body: ProductionMaterialBody,
  253. db: Session = Depends(get_db),
  254. user: dict = Depends(require_menu_code("production:material:list")),
  255. ):
  256. try:
  257. tenant_no = _get_tenant_no(db, user)
  258. user_id = _get_current_user_id(user)
  259. obj = mat_svc.create_material(
  260. db,
  261. material_type=body.material_type,
  262. material_code=body.material_code,
  263. material_name=body.material_name,
  264. spec_model=body.spec_model,
  265. unit=body.unit,
  266. warning_qty=Decimal(str(body.warning_qty))
  267. if body.warning_qty is not None
  268. else None,
  269. status=mat_svc._norm_status(body.status),
  270. remark=body.remark,
  271. tenant_no=tenant_no,
  272. user_id=user_id,
  273. )
  274. return success_response(mat_svc._row_to_dict(obj), message="创建成功")
  275. except ValueError as e:
  276. return error_response(400, str(e))
  277. except Exception as e:
  278. return error_response(400, str(e))
  279. @router.put("/production-materials/{material_id}")
  280. async def update_production_material(
  281. material_id: str,
  282. body: ProductionMaterialUpdateBody,
  283. db: Session = Depends(get_db),
  284. user: dict = Depends(require_menu_code("production:material:list")),
  285. ):
  286. try:
  287. tenant_no = _get_tenant_no(db, user)
  288. user_id = _get_current_user_id(user)
  289. data = body.model_dump(exclude_none=True)
  290. if "warning_qty" in data:
  291. data["warning_qty"] = Decimal(str(data["warning_qty"]))
  292. if "status" in data:
  293. data["status"] = mat_svc._norm_status(data["status"])
  294. obj = mat_svc.update_material(
  295. db,
  296. material_id,
  297. tenant_no=tenant_no,
  298. user_id=user_id,
  299. **data,
  300. )
  301. return success_response(mat_svc._row_to_dict(obj), message="更新成功")
  302. except ValueError as e:
  303. return error_response(400, str(e))
  304. except Exception as e:
  305. return error_response(400, str(e))
  306. @router.delete("/production-materials/{material_id}")
  307. async def delete_production_material(
  308. material_id: str,
  309. db: Session = Depends(get_db),
  310. user: dict = Depends(require_menu_code("production:material:list")),
  311. ):
  312. try:
  313. tenant_no = _get_tenant_no(db, user)
  314. user_id = _get_current_user_id(user)
  315. mat_svc.soft_delete_material(db, material_id, tenant_no=tenant_no)
  316. return success_response(None, message="删除成功")
  317. except ValueError as e:
  318. return error_response(400, str(e))
  319. except Exception as e:
  320. return error_response(400, str(e))
  321. @router.post("/production-materials/batch-stock-in")
  322. async def batch_stock_in_production_material(
  323. body: BatchStockInBody,
  324. db: Session = Depends(get_db),
  325. user: dict = Depends(require_menu_code("production:material:list")),
  326. ):
  327. try:
  328. tenant_no = _get_tenant_no(db, user)
  329. user_id = _get_current_user_id(user)
  330. operate_time = datetime.now()
  331. if body.stock_in_time:
  332. rt = parse_datetime(body.stock_in_time)
  333. if not rt:
  334. return error_response(400, "入库时间格式无效")
  335. operate_time = rt
  336. items = [
  337. {
  338. "material_id": x.material_id,
  339. "materialId": x.material_id,
  340. "stock_in_no": x.stock_in_no,
  341. "stockInNo": x.stock_in_no,
  342. "stock_in_date": x.stock_in_date,
  343. "stockInDate": x.stock_in_date,
  344. "expire_date": x.expire_date,
  345. "expireDate": x.expire_date,
  346. "catalog_no": x.catalog_no,
  347. "catalogNo": x.catalog_no,
  348. "batch_no": x.batch_no,
  349. "batchNo": x.batch_no,
  350. "manufacturer": x.manufacturer,
  351. "storage_location": x.storage_location,
  352. "storageLocation": x.storage_location,
  353. "unit_price": x.unit_price,
  354. "unitPrice": x.unit_price,
  355. "amount": x.amount,
  356. "qty": x.qty,
  357. "remark": x.remark,
  358. }
  359. for x in body.items
  360. ]
  361. count = batch_svc.batch_stock_in(
  362. db,
  363. items=items,
  364. remark=body.remark,
  365. tenant_no=tenant_no,
  366. user_id=user_id,
  367. operate_time=operate_time,
  368. )
  369. return success_response({"count": count}, message=f"批量入库成功,共 {count} 项")
  370. except ValueError as e:
  371. return error_response(400, str(e))
  372. except Exception as e:
  373. return error_response(400, str(e))
  374. @router.post("/production-materials/batch-stock-out")
  375. async def batch_stock_out_production_material(
  376. body: BatchStockOutBody,
  377. db: Session = Depends(get_db),
  378. user: dict = Depends(require_menu_code("production:material:list")),
  379. ):
  380. try:
  381. tenant_no = _get_tenant_no(db, user)
  382. user_id = _get_current_user_id(user)
  383. operate_time = datetime.now()
  384. if body.stock_out_time:
  385. rt = parse_datetime(body.stock_out_time)
  386. if not rt:
  387. return error_response(400, "出库时间格式无效")
  388. operate_time = rt
  389. items = [
  390. {"batch_id": x.batch_id, "batchId": x.batch_id, "qty": x.qty, "remark": x.remark}
  391. for x in body.items
  392. ]
  393. count = batch_svc.batch_stock_out(
  394. db,
  395. items=items,
  396. receiver=body.receiver,
  397. purpose=body.purpose,
  398. remark=body.remark,
  399. tenant_no=tenant_no,
  400. user_id=user_id,
  401. operate_time=operate_time,
  402. )
  403. return success_response({"count": count}, message=f"批量出库成功,共 {count} 项")
  404. except ValueError as e:
  405. return error_response(400, str(e))
  406. except Exception as e:
  407. return error_response(400, str(e))
  408. @router.post("/production-materials/batch-discard")
  409. async def batch_discard_production_material(
  410. body: BatchDiscardBody,
  411. db: Session = Depends(get_db),
  412. user: dict = Depends(require_menu_code("production:material:list")),
  413. ):
  414. try:
  415. tenant_no = _get_tenant_no(db, user)
  416. user_id = _get_current_user_id(user)
  417. operate_time = datetime.now()
  418. if body.discard_time:
  419. rt = parse_datetime(body.discard_time)
  420. if not rt:
  421. return error_response(400, "废弃时间格式无效")
  422. operate_time = rt
  423. items = [
  424. {
  425. "batch_id": x.batch_id,
  426. "batchId": x.batch_id,
  427. "qty": x.qty,
  428. "usageUnit": x.usage_unit,
  429. "usage_unit": x.usage_unit,
  430. "remark": x.remark,
  431. }
  432. for x in body.items
  433. ]
  434. count = batch_svc.batch_discard(
  435. db,
  436. items=items,
  437. discard_reason=body.discard_reason,
  438. remark=body.remark,
  439. tenant_no=tenant_no,
  440. user_id=user_id,
  441. operate_time=operate_time,
  442. )
  443. return success_response({"count": count}, message=f"批量废弃成功,共 {count} 项")
  444. except ValueError as e:
  445. return error_response(400, str(e))
  446. except Exception as e:
  447. return error_response(400, str(e))
  448. @router.post("/production-materials/{material_id}/stock-in")
  449. async def stock_in_production_material(
  450. material_id: str,
  451. body: StockInBody,
  452. db: Session = Depends(get_db),
  453. user: dict = Depends(require_menu_code("production:material:list")),
  454. ):
  455. try:
  456. tenant_no = _get_tenant_no(db, user)
  457. user_id = _get_current_user_id(user)
  458. operate_time = datetime.now()
  459. if body.stock_in_time:
  460. rt = parse_datetime(body.stock_in_time)
  461. if not rt:
  462. return error_response(400, "入库时间格式无效")
  463. operate_time = rt
  464. from decimal import Decimal
  465. obj = batch_svc.stock_in_one(
  466. db,
  467. material_id,
  468. stock_in_no=body.stock_in_no,
  469. stock_in_date=body.stock_in_date,
  470. expire_date=body.expire_date,
  471. catalog_no=body.catalog_no,
  472. batch_no=body.batch_no,
  473. manufacturer=body.manufacturer,
  474. storage_location=body.storage_location,
  475. unit_price=body.unit_price,
  476. amount=body.amount,
  477. qty=Decimal(str(body.qty)),
  478. remark=body.remark,
  479. tenant_no=tenant_no,
  480. user_id=user_id,
  481. operate_time=operate_time,
  482. )
  483. return success_response(batch_svc._batch_row_to_dict(obj), message="入库成功")
  484. except ValueError as e:
  485. return error_response(400, str(e))
  486. except Exception as e:
  487. return error_response(400, str(e))
  488. @router.post("/production-material-batches/batch-stock-in")
  489. async def batch_stock_in_production_material_batches(
  490. body: BatchStockInBody,
  491. db: Session = Depends(get_db),
  492. user: dict = Depends(require_menu_code("production:material:list")),
  493. ):
  494. """批量入库(与 /production-materials/batch-stock-in 等价)。"""
  495. return await batch_stock_in_production_material(body, db, user)
  496. @router.post("/production-material-batches/batch-stock-out")
  497. async def batch_stock_out_production_material_batches(
  498. body: BatchStockOutBody,
  499. db: Session = Depends(get_db),
  500. user: dict = Depends(require_menu_code("production:material:list")),
  501. ):
  502. """批量出库(与 /production-materials/batch-stock-out 等价)。"""
  503. return await batch_stock_out_production_material(body, db, user)
  504. @router.post("/production-material-batches/batch-discard")
  505. async def batch_discard_production_material_batches(
  506. body: BatchDiscardBody,
  507. db: Session = Depends(get_db),
  508. user: dict = Depends(require_menu_code("production:material:list")),
  509. ):
  510. """批量废弃(与 /production-materials/batch-discard 等价)。"""
  511. return await batch_discard_production_material(body, db, user)
  512. # ---------- 物料变动记录 ----------
  513. @router.get("/production-material-requisition-options")
  514. async def list_production_material_requisition_options(
  515. materialType: Optional[str] = None,
  516. keyword: Optional[str] = None,
  517. limit: int = Query(50, ge=1, le=100),
  518. db: Session = Depends(get_db),
  519. user: dict = Depends(
  520. require_any_menu_code(
  521. "production:work-order:list",
  522. "production:my-task:list",
  523. "production:material:list",
  524. )
  525. ),
  526. ):
  527. try:
  528. tenant_no = _get_tenant_no(db, user)
  529. items = mu_svc.list_requisition_options(
  530. db,
  531. tenant_no,
  532. keyword=keyword,
  533. material_type=materialType,
  534. limit=limit,
  535. user_info=user,
  536. )
  537. return success_response(items)
  538. except PermissionError as e:
  539. return error_response(403, str(e))
  540. except Exception as e:
  541. return error_response(400, str(e))
  542. @router.get("/production-material-usages")
  543. async def list_production_material_usages(
  544. page: int = Query(1, ge=1),
  545. pageSize: int = Query(10, ge=1, le=100),
  546. materialId: Optional[str] = None,
  547. materialType: Optional[str] = None,
  548. changeType: Optional[str] = None,
  549. startTime: Optional[str] = None,
  550. endTime: Optional[str] = None,
  551. keyword: Optional[str] = None,
  552. stockInNo: Optional[str] = None,
  553. db: Session = Depends(get_db),
  554. user: dict = Depends(require_menu_code("production:material:list")),
  555. ):
  556. try:
  557. tenant_no = _get_tenant_no(db, user)
  558. items, total = mu_svc.list_usages(
  559. db, tenant_no, page=page, page_size=pageSize,
  560. material_id=materialId, material_type=materialType, change_type=changeType,
  561. start_time=startTime, end_time=endTime,
  562. keyword=keyword, stock_in_no=stockInNo,
  563. user_info=user,
  564. )
  565. return success_response(_page_payload(items, total, page, pageSize))
  566. except PermissionError as e:
  567. return error_response(403, str(e))
  568. except Exception as e:
  569. return error_response(400, str(e))
  570. @router.post("/production-material-usages/{usage_id}/mark-fully-used")
  571. async def mark_production_material_usage_fully_used(
  572. usage_id: str,
  573. db: Session = Depends(get_db),
  574. user: dict = Depends(require_menu_code("production:material:list")),
  575. ):
  576. """标记领用记录已使用完(盘点登记 / 变动记录)。"""
  577. try:
  578. tenant_no = _get_tenant_no(db, user)
  579. user_id = _get_current_user_id(user)
  580. mu_svc.mark_requisition_fully_used(
  581. db,
  582. usage_id,
  583. tenant_no=tenant_no,
  584. user_id=user_id,
  585. user_info=user,
  586. )
  587. return success_response(None, message="已标记为使用完")
  588. except PermissionError as e:
  589. return error_response(403, str(e))
  590. except ValueError as e:
  591. return error_response(400, str(e))
  592. except Exception as e:
  593. return error_response(400, str(e))
  594. @router.get("/my-production-material-usages")
  595. async def list_my_production_material_usages(
  596. page: int = Query(1, ge=1),
  597. pageSize: int = Query(10, ge=1, le=100),
  598. materialId: Optional[str] = None,
  599. materialType: Optional[str] = None,
  600. changeType: Optional[str] = None,
  601. startTime: Optional[str] = None,
  602. endTime: Optional[str] = None,
  603. keyword: Optional[str] = None,
  604. stockInNo: Optional[str] = None,
  605. db: Session = Depends(get_db),
  606. user: dict = Depends(require_menu_code("production:my-material-usage:list")),
  607. ):
  608. """当前登录人的物料领用记录(手动出库领用人 / 任务使用填报人)。"""
  609. try:
  610. tenant_no = _get_tenant_no(db, user)
  611. items, total = mu_svc.list_my_usages(
  612. db,
  613. tenant_no,
  614. user_id=_get_current_user_id(user),
  615. nick_name=(user.get("real_name") or "").strip(),
  616. page=page,
  617. page_size=pageSize,
  618. material_id=materialId,
  619. material_type=materialType,
  620. change_type=changeType,
  621. start_time=startTime,
  622. end_time=endTime,
  623. keyword=keyword,
  624. stock_in_no=stockInNo,
  625. )
  626. return success_response(_page_payload(items, total, page, pageSize))
  627. except PermissionError as e:
  628. return error_response(403, str(e))
  629. except Exception as e:
  630. return error_response(400, str(e))
  631. @router.get("/production-material-usages/{usage_id}/linked-step-usages")
  632. async def list_production_material_linked_step_usages(
  633. usage_id: str,
  634. db: Session = Depends(get_db),
  635. user: dict = Depends(
  636. require_any_menu_code("production:material:list", "production:my-material-usage:list")
  637. ),
  638. ):
  639. """领用记录下关联的生产步骤物料消耗明细。"""
  640. try:
  641. tenant_no = _get_tenant_no(db, user)
  642. items = mu_svc.list_linked_step_usages(
  643. db, usage_id, tenant_no, user_info=user
  644. )
  645. return success_response(items)
  646. except HTTPException as e:
  647. detail = e.detail
  648. msg = detail if isinstance(detail, str) else str(detail)
  649. return error_response(e.status_code, msg)
  650. except PermissionError as e:
  651. return error_response(403, str(e))
  652. except Exception as e:
  653. return error_response(400, str(e))
  654. # ---------- 库存盘点 ----------
  655. class StockCheckCreateBody(BaseModel):
  656. model_config = ConfigDict(populate_by_name=True)
  657. title: str
  658. check_time: Optional[str] = Field(None, alias="checkTime")
  659. remark: Optional[str] = None
  660. class StockCheckUnusedLineItem(BaseModel):
  661. model_config = ConfigDict(populate_by_name=True)
  662. usage_id: Optional[str] = Field(None, alias="usageId")
  663. batch_id: Optional[str] = Field(None, alias="batchId")
  664. material_code: Optional[str] = Field(None, alias="materialCode")
  665. material_name: str = Field(..., alias="materialName")
  666. spec_model: Optional[str] = Field(None, alias="specModel")
  667. unit: Optional[str] = None
  668. stock_in_no: Optional[str] = Field(None, alias="stockInNo")
  669. stock_in_date: Optional[str] = Field(None, alias="stockInDate")
  670. expire_date: Optional[str] = Field(None, alias="expireDate")
  671. catalog_no: Optional[str] = Field(None, alias="catalogNo")
  672. batch_no: Optional[str] = Field(None, alias="batchNo")
  673. manufacturer: Optional[str] = None
  674. unit_price: Optional[float] = Field(None, alias="unitPrice")
  675. holder: Optional[str] = None
  676. unused_qty: float = Field(..., alias="unusedQty", gt=0)
  677. remark: Optional[str] = None
  678. class StockCheckUnusedLinesBody(BaseModel):
  679. model_config = ConfigDict(populate_by_name=True)
  680. items: List[StockCheckUnusedLineItem] = Field(default_factory=list)
  681. @router.get("/production-material-stock-check-requisitions")
  682. async def list_production_material_stock_check_requisitions(
  683. page: int = Query(1, ge=1),
  684. pageSize: int = Query(50, ge=1, le=200),
  685. keyword: Optional[str] = None,
  686. db: Session = Depends(get_db),
  687. user: dict = Depends(require_menu_code("production:material:list")),
  688. ):
  689. """盘点登记:待处理领用记录(未标记已使用完)。"""
  690. try:
  691. tenant_no = _get_tenant_no(db, user)
  692. items, total = mu_svc.list_stock_check_requisitions(
  693. db,
  694. tenant_no,
  695. page=page,
  696. page_size=pageSize,
  697. keyword=keyword,
  698. user_info=user,
  699. )
  700. return success_response(_page_payload(items, total, page, pageSize))
  701. except PermissionError as e:
  702. return error_response(403, str(e))
  703. except Exception as e:
  704. return error_response(400, str(e))
  705. @router.get("/production-material-stock-checks")
  706. async def list_production_material_stock_checks(
  707. page: int = Query(1, ge=1),
  708. pageSize: int = Query(10, ge=1, le=100),
  709. keyword: Optional[str] = None,
  710. status: Optional[str] = None,
  711. startTime: Optional[str] = None,
  712. endTime: Optional[str] = None,
  713. db: Session = Depends(get_db),
  714. user: dict = Depends(require_menu_code("production:material:list")),
  715. ):
  716. try:
  717. tenant_no = _get_tenant_no(db, user)
  718. items, total = stock_check_svc.list_checks(
  719. db,
  720. tenant_no,
  721. page=page,
  722. page_size=pageSize,
  723. keyword=keyword,
  724. status=status,
  725. start_time=startTime,
  726. end_time=endTime,
  727. user_info=user,
  728. )
  729. return success_response(_page_payload(items, total, page, pageSize))
  730. except PermissionError as e:
  731. return error_response(403, str(e))
  732. except Exception as e:
  733. return error_response(400, str(e))
  734. @router.post("/production-material-stock-checks")
  735. async def create_production_material_stock_check(
  736. body: StockCheckCreateBody,
  737. db: Session = Depends(get_db),
  738. user: dict = Depends(require_menu_code("production:material:list")),
  739. ):
  740. try:
  741. tenant_no = _get_tenant_no(db, user)
  742. user_id = _get_current_user_id(user)
  743. dept_id = user.get("deptId") or user.get("dept_id") or ""
  744. res = stock_check_svc.create_check(
  745. db,
  746. title=body.title,
  747. tenant_no=tenant_no,
  748. user_id=user_id,
  749. dept_id=dept_id,
  750. check_time=body.check_time,
  751. remark=body.remark,
  752. )
  753. return success_response(res, message="盘点单创建成功")
  754. except ValueError as e:
  755. return error_response(400, str(e))
  756. except Exception as e:
  757. return error_response(400, str(e))
  758. @router.get("/production-material-stock-checks/{check_id}")
  759. async def get_production_material_stock_check(
  760. check_id: str,
  761. db: Session = Depends(get_db),
  762. user: dict = Depends(require_menu_code("production:material:list")),
  763. ):
  764. try:
  765. tenant_no = _get_tenant_no(db, user)
  766. data = stock_check_svc.get_check_detail(db, check_id, tenant_no)
  767. return success_response(data)
  768. except ValueError as e:
  769. return error_response(400, str(e))
  770. except Exception as e:
  771. return error_response(400, str(e))
  772. @router.put("/production-material-stock-checks/{check_id}/unused-lines")
  773. async def save_production_material_stock_check_unused_lines(
  774. check_id: str,
  775. body: StockCheckUnusedLinesBody,
  776. db: Session = Depends(get_db),
  777. user: dict = Depends(require_menu_code("production:material:list")),
  778. ):
  779. try:
  780. tenant_no = _get_tenant_no(db, user)
  781. user_id = _get_current_user_id(user)
  782. dept_id = user.get("deptId") or user.get("dept_id") or ""
  783. count = stock_check_svc.save_unused_lines(
  784. db,
  785. check_id,
  786. items=[x.model_dump(by_alias=False) for x in body.items],
  787. tenant_no=tenant_no,
  788. user_id=user_id,
  789. dept_id=dept_id,
  790. )
  791. return success_response({"count": count}, message="登记保存成功")
  792. except ValueError as e:
  793. return error_response(400, str(e))
  794. except Exception as e:
  795. return error_response(400, str(e))
  796. @router.post("/production-material-stock-checks/{check_id}/complete")
  797. async def complete_production_material_stock_check(
  798. check_id: str,
  799. db: Session = Depends(get_db),
  800. user: dict = Depends(require_menu_code("production:material:list")),
  801. ):
  802. try:
  803. tenant_no = _get_tenant_no(db, user)
  804. user_id = _get_current_user_id(user)
  805. stock_check_svc.complete_check(db, check_id, tenant_no=tenant_no, user_id=user_id)
  806. return success_response(None, message="盘点已完成")
  807. except ValueError as e:
  808. return error_response(400, str(e))
  809. except Exception as e:
  810. return error_response(400, str(e))
  811. @router.post("/production-material-stock-checks/{check_id}/cancel")
  812. async def cancel_production_material_stock_check(
  813. check_id: str,
  814. db: Session = Depends(get_db),
  815. user: dict = Depends(require_menu_code("production:material:list")),
  816. ):
  817. try:
  818. tenant_no = _get_tenant_no(db, user)
  819. user_id = _get_current_user_id(user)
  820. stock_check_svc.cancel_check(db, check_id, tenant_no=tenant_no, user_id=user_id)
  821. return success_response(None, message="盘点已作废")
  822. except ValueError as e:
  823. return error_response(400, str(e))
  824. except Exception as e:
  825. return error_response(400, str(e))
  826. # ---------- 配置试剂配方 ----------
  827. class FormulaLineBody(BaseModel):
  828. model_config = ConfigDict(populate_by_name=True)
  829. component_material_id: str = Field(..., alias="componentMaterialId")
  830. component_material_type: str = Field(..., alias="componentMaterialType")
  831. standard_qty: float = Field(..., gt=0, alias="standardQty")
  832. usage_unit: Optional[str] = Field(None, alias="usageUnit")
  833. remark: Optional[str] = None
  834. class FormulaReplaceBody(BaseModel):
  835. model_config = ConfigDict(populate_by_name=True)
  836. lines: List[FormulaLineBody] = Field(default_factory=list)
  837. @router.get("/production-materials/{material_id}/formula")
  838. async def get_production_material_formula(
  839. material_id: str,
  840. db: Session = Depends(get_db),
  841. user: dict = Depends(require_menu_code("production:material:list")),
  842. ):
  843. try:
  844. tenant_no = _get_tenant_no(db, user)
  845. items = formula_svc.get_formula(db, material_id, tenant_no)
  846. return success_response(items)
  847. except ValueError as e:
  848. return error_response(400, str(e))
  849. except Exception as e:
  850. return error_response(400, str(e))
  851. @router.put("/production-materials/{material_id}/formula")
  852. async def replace_production_material_formula(
  853. material_id: str,
  854. body: FormulaReplaceBody,
  855. db: Session = Depends(get_db),
  856. user: dict = Depends(require_menu_code("production:material:list")),
  857. ):
  858. try:
  859. tenant_no = _get_tenant_no(db, user)
  860. user_id = _get_current_user_id(user)
  861. dept_id = user.get("deptId") or user.get("dept_id") or ""
  862. lines = [ln.model_dump(by_alias=True) for ln in body.lines]
  863. items = formula_svc.replace_formula(
  864. db,
  865. material_id,
  866. lines=lines,
  867. tenant_no=tenant_no,
  868. user_id=user_id,
  869. dept_id=dept_id,
  870. )
  871. return success_response(items, message="配方已保存")
  872. except ValueError as e:
  873. return error_response(400, str(e))
  874. except Exception as e:
  875. return error_response(400, str(e))
  876. # ---------- 配置试剂配制单 ----------
  877. class PrepLineBody(BaseModel):
  878. model_config = ConfigDict(populate_by_name=True)
  879. component_material_id: str = Field(..., alias="componentMaterialId")
  880. component_material_type: str = Field(..., alias="componentMaterialType")
  881. requisition_usage_id: str = Field(..., alias="requisitionUsageId")
  882. actual_qty: float = Field(..., gt=0, alias="actualQty")
  883. usage_unit: Optional[str] = Field(None, alias="usageUnit")
  884. remark: Optional[str] = None
  885. class PrepBody(BaseModel):
  886. model_config = ConfigDict(populate_by_name=True)
  887. configured_material_id: str = Field(..., alias="configuredMaterialId")
  888. prep_time: Optional[str] = Field(None, alias="prepTime")
  889. output_qty: float = Field(..., gt=0, alias="outputQty")
  890. output_unit: Optional[str] = Field(None, alias="outputUnit")
  891. batch_no: str = Field(..., alias="batchNo")
  892. storage_location: Optional[str] = Field(None, alias="storageLocation")
  893. expire_date: str = Field(..., alias="expireDate")
  894. remark: Optional[str] = None
  895. lines: List[PrepLineBody] = Field(..., min_length=1)
  896. class PrepUpdateBody(BaseModel):
  897. model_config = ConfigDict(populate_by_name=True)
  898. prep_time: Optional[str] = Field(None, alias="prepTime")
  899. output_qty: Optional[float] = Field(None, gt=0, alias="outputQty")
  900. output_unit: Optional[str] = Field(None, alias="outputUnit")
  901. batch_no: Optional[str] = Field(None, alias="batchNo")
  902. storage_location: Optional[str] = Field(None, alias="storageLocation")
  903. expire_date: Optional[str] = Field(None, alias="expireDate")
  904. remark: Optional[str] = None
  905. lines: Optional[List[PrepLineBody]] = None
  906. @router.get("/production-material-preps")
  907. async def list_production_material_preps(
  908. page: int = Query(1, ge=1),
  909. pageSize: int = Query(10, ge=1, le=100),
  910. keyword: Optional[str] = None,
  911. status: Optional[str] = None,
  912. configuredMaterialId: Optional[str] = None,
  913. db: Session = Depends(get_db),
  914. user: dict = Depends(require_menu_code("production:material:list")),
  915. ):
  916. try:
  917. tenant_no = _get_tenant_no(db, user)
  918. items, total = prep_svc.list_preps(
  919. db,
  920. tenant_no,
  921. page=page,
  922. page_size=pageSize,
  923. keyword=keyword,
  924. status=status,
  925. configured_material_id=configuredMaterialId,
  926. )
  927. return success_response(_page_payload(items, total, page, pageSize))
  928. except Exception as e:
  929. return error_response(400, str(e))
  930. @router.get("/production-material-preps/{prep_id}")
  931. async def get_production_material_prep(
  932. prep_id: str,
  933. db: Session = Depends(get_db),
  934. user: dict = Depends(require_menu_code("production:material:list")),
  935. ):
  936. try:
  937. tenant_no = _get_tenant_no(db, user)
  938. data = prep_svc.get_prep_detail(db, prep_id, tenant_no)
  939. return success_response(data)
  940. except ValueError as e:
  941. return error_response(400, str(e))
  942. except Exception as e:
  943. return error_response(400, str(e))
  944. @router.post("/production-material-preps")
  945. async def create_production_material_prep(
  946. body: PrepBody,
  947. db: Session = Depends(get_db),
  948. user: dict = Depends(require_menu_code("production:material:list")),
  949. ):
  950. try:
  951. tenant_no = _get_tenant_no(db, user)
  952. user_id = _get_current_user_id(user)
  953. dept_id = user.get("deptId") or user.get("dept_id") or ""
  954. data = prep_svc.create_prep(
  955. db,
  956. data=body.model_dump(by_alias=True),
  957. tenant_no=tenant_no,
  958. user_id=user_id,
  959. dept_id=dept_id,
  960. )
  961. return success_response(data, message="配制单已创建")
  962. except ValueError as e:
  963. return error_response(400, str(e))
  964. except Exception as e:
  965. return error_response(400, str(e))
  966. @router.put("/production-material-preps/{prep_id}")
  967. async def update_production_material_prep(
  968. prep_id: str,
  969. body: PrepUpdateBody,
  970. db: Session = Depends(get_db),
  971. user: dict = Depends(require_menu_code("production:material:list")),
  972. ):
  973. try:
  974. tenant_no = _get_tenant_no(db, user)
  975. user_id = _get_current_user_id(user)
  976. dept_id = user.get("deptId") or user.get("dept_id") or ""
  977. data = prep_svc.update_prep(
  978. db,
  979. prep_id,
  980. data=body.model_dump(by_alias=True, exclude_none=True),
  981. tenant_no=tenant_no,
  982. user_id=user_id,
  983. dept_id=dept_id,
  984. )
  985. return success_response(data, message="配制单已更新")
  986. except ValueError as e:
  987. return error_response(400, str(e))
  988. except Exception as e:
  989. return error_response(400, str(e))
  990. @router.post("/production-material-preps/{prep_id}/complete")
  991. async def complete_production_material_prep(
  992. prep_id: str,
  993. db: Session = Depends(get_db),
  994. user: dict = Depends(require_menu_code("production:material:list")),
  995. ):
  996. try:
  997. tenant_no = _get_tenant_no(db, user)
  998. user_id = _get_current_user_id(user)
  999. dept_id = user.get("deptId") or user.get("dept_id") or ""
  1000. data = prep_svc.complete_prep(
  1001. db,
  1002. prep_id,
  1003. tenant_no=tenant_no,
  1004. user_id=user_id,
  1005. dept_id=dept_id,
  1006. )
  1007. return success_response(data, message="配制已完成")
  1008. except ValueError as e:
  1009. return error_response(400, str(e))
  1010. except Exception as e:
  1011. return error_response(400, str(e))
  1012. @router.post("/production-material-preps/{prep_id}/cancel")
  1013. async def cancel_production_material_prep(
  1014. prep_id: str,
  1015. db: Session = Depends(get_db),
  1016. user: dict = Depends(require_menu_code("production:material:list")),
  1017. ):
  1018. try:
  1019. tenant_no = _get_tenant_no(db, user)
  1020. user_id = _get_current_user_id(user)
  1021. prep_svc.cancel_prep(db, prep_id, tenant_no=tenant_no, user_id=user_id)
  1022. return success_response(None, message="配制单已作废")
  1023. except ValueError as e:
  1024. return error_response(400, str(e))
  1025. except Exception as e:
  1026. return error_response(400, str(e))
  1027. @router.delete("/production-material-preps/{prep_id}")
  1028. async def delete_production_material_prep(
  1029. prep_id: str,
  1030. db: Session = Depends(get_db),
  1031. user: dict = Depends(require_menu_code("production:material:list")),
  1032. ):
  1033. try:
  1034. tenant_no = _get_tenant_no(db, user)
  1035. user_id = _get_current_user_id(user)
  1036. prep_svc.delete_prep(db, prep_id, tenant_no=tenant_no, user_id=user_id)
  1037. return success_response(None, message="配制单已删除")
  1038. except ValueError as e:
  1039. return error_response(400, str(e))
  1040. except Exception as e:
  1041. return error_response(400, str(e))