qc.py 87 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498
  1. """质量检测 — 第三方/实验室主数据、质检工单、质检任务 API"""
  2. from typing import Any, Dict, Iterable, List, Optional
  3. from fastapi import APIRouter, Depends, HTTPException, Query
  4. from pydantic import BaseModel, ConfigDict, Field
  5. from sqlalchemy.orm import Session
  6. from datetime import datetime
  7. from decimal import Decimal
  8. from app.core.database import get_db
  9. from app.core.menu_guard import (
  10. require_admin_or_super_admin,
  11. require_any_menu_code,
  12. require_menu_code,
  13. strip_row_fields,
  14. user_has_menu_perm,
  15. )
  16. MY_QC_MATERIAL_USAGE_VIEW_AMOUNT_PERM = "biz:myQcMaterialUsage:viewAmount"
  17. QC_MATERIAL_VIEW_AMOUNT_PERM = "biz:qcMaterial:viewAmount"
  18. QC_THIRD_PARTY_VIEW_AMOUNT_PERM = "biz:qcThirdPartyCompany:viewAmount"
  19. QC_MATERIAL_AMOUNT_FIELD_NAMES = ("unitPrice", "amount", "remainingAmount", "unit_price")
  20. QC_THIRD_PARTY_FEE_FIELD_NAMES = ("feeAmount", "thirdPartyFeeTotal")
  21. from app.core.response import error_response, success_response
  22. from app.core.utils import parse_datetime
  23. from app.crud import qc_lab_test_item as lab_svc
  24. from app.crud import qc_inspection_item_template as iit_svc
  25. from app.crud import qc_item_param as param_svc
  26. from app.crud import qc_task_result as result_svc
  27. from app.crud import qc_task as task_svc
  28. from app.crud import qc_third_party_company as tpc_svc
  29. from app.crud import qc_third_party_item as tpi_svc
  30. from app.crud import qc_material as mat_svc
  31. from app.crud import qc_material_stock_batch as batch_svc
  32. from app.crud import qc_material_stock_check as stock_check_svc
  33. from app.crud import qc_material_usage as mu_svc
  34. from app.crud import qc_material_amount_auth as amount_auth_svc
  35. from app.core.qc_material_amount_auth_constants import QC_MATERIAL_AMOUNT_AUTH_LIST_PERM
  36. from app.crud import inbound_sample_special as inbound_sample_special_svc
  37. from app.crud import qc_work_order as wo_svc
  38. from app.crud.collection_protocol import total_pages
  39. from app.api.sample_reception import _get_current_user_id, _get_tenant_no, _page_payload
  40. from app.schemas.qc_work_order import QcWorkOrderCreateBody, QcWorkOrderUpdateBody
  41. from app.schemas.qc_task import QcTaskCreateBody
  42. router = APIRouter(prefix="/web/admin", tags=["质量检测"])
  43. # 协议/捐赠查看等场景只读打开质检任务详情(参数、附件)
  44. QC_TASK_READONLY_MENU_CODES = (
  45. "biz:qcTask:list",
  46. "biz:myQcTask:list",
  47. "biz:cellStorageProtocol:list",
  48. "biz:cellStorageProtocolAudit:list",
  49. "biz:researchDonation:list",
  50. "biz:researchDonationAudit:list",
  51. "biz:storageReleaseReview:list",
  52. "biz:qcWorkOrder:list",
  53. )
  54. # ---------- 第三方检测公司 ----------
  55. class ThirdPartyCompanyBody(BaseModel):
  56. model_config = ConfigDict(populate_by_name=True)
  57. company_code: str = Field(..., alias="companyCode")
  58. company_name: str = Field(..., alias="companyName")
  59. contact_name: Optional[str] = Field(None, alias="contactName")
  60. contact_phone: Optional[str] = Field(None, alias="contactPhone")
  61. company_logo: Optional[str] = Field(None, alias="companyLogo")
  62. address: Optional[str] = None
  63. invoice_title: Optional[str] = Field(None, alias="invoiceTitle")
  64. tax_id: Optional[str] = Field(None, alias="taxId")
  65. bank_name: Optional[str] = Field(None, alias="bankName")
  66. bank_account: Optional[str] = Field(None, alias="bankAccount")
  67. status: str = "1"
  68. order_num: Optional[int] = Field(None, alias="orderNum")
  69. remark: Optional[str] = None
  70. class ThirdPartyCompanyUpdateBody(BaseModel):
  71. model_config = ConfigDict(populate_by_name=True)
  72. company_code: Optional[str] = Field(None, alias="companyCode")
  73. company_name: Optional[str] = Field(None, alias="companyName")
  74. contact_name: Optional[str] = Field(None, alias="contactName")
  75. contact_phone: Optional[str] = Field(None, alias="contactPhone")
  76. company_logo: Optional[str] = Field(None, alias="companyLogo")
  77. address: Optional[str] = None
  78. invoice_title: Optional[str] = Field(None, alias="invoiceTitle")
  79. tax_id: Optional[str] = Field(None, alias="taxId")
  80. bank_name: Optional[str] = Field(None, alias="bankName")
  81. bank_account: Optional[str] = Field(None, alias="bankAccount")
  82. status: Optional[str] = None
  83. order_num: Optional[int] = Field(None, alias="orderNum")
  84. remark: Optional[str] = None
  85. @router.get("/qc-third-party-companies")
  86. async def list_qc_third_party_companies(
  87. page: int = Query(1, ge=1),
  88. pageSize: int = Query(10, ge=1, le=100),
  89. keyword: Optional[str] = None,
  90. status: Optional[str] = None,
  91. db: Session = Depends(get_db),
  92. user: dict = Depends(require_menu_code("biz:qcThirdPartyCompany:list")),
  93. ):
  94. try:
  95. tenant_no = _get_tenant_no(db, user)
  96. items, total = tpc_svc.list_companies(
  97. db, page=page, page_size=pageSize, keyword=keyword, status=status, tenant_no=tenant_no,
  98. user_info=user
  99. )
  100. return success_response(_page_payload(items, total, page, pageSize))
  101. except PermissionError as e:
  102. return error_response(403, str(e))
  103. except Exception as e:
  104. return error_response(400, str(e))
  105. @router.get("/qc-third-party-companies/options")
  106. async def list_qc_third_party_company_options(
  107. db: Session = Depends(get_db),
  108. user: dict = Depends(require_menu_code("biz:qcWorkOrder:list")),
  109. ):
  110. try:
  111. tenant_no = _get_tenant_no(db, user)
  112. return success_response(tpc_svc.list_company_options(db, tenant_no))
  113. except PermissionError as e:
  114. return error_response(403, str(e))
  115. except Exception as e:
  116. return error_response(400, str(e))
  117. @router.post("/qc-third-party-companies")
  118. async def create_qc_third_party_company(
  119. body: ThirdPartyCompanyBody,
  120. db: Session = Depends(get_db),
  121. user: dict = Depends(require_menu_code("biz:qcThirdPartyCompany:list")),
  122. ):
  123. try:
  124. tenant_no = _get_tenant_no(db, user)
  125. obj = tpc_svc.create_company(
  126. db,
  127. company_code=body.company_code,
  128. company_name=body.company_name,
  129. contact_name=body.contact_name,
  130. contact_phone=body.contact_phone,
  131. company_logo=body.company_logo,
  132. address=body.address,
  133. invoice_title=body.invoice_title,
  134. tax_id=body.tax_id,
  135. bank_name=body.bank_name,
  136. bank_account=body.bank_account,
  137. status=body.status,
  138. tenant_no=tenant_no,
  139. order_num=body.order_num,
  140. remark=body.remark,
  141. user_id=_get_current_user_id(user),
  142. )
  143. return success_response(tpc_svc._row_to_dict(obj), message="创建成功")
  144. except PermissionError as e:
  145. return error_response(403, str(e))
  146. except ValueError as e:
  147. return error_response(400, str(e))
  148. except Exception as e:
  149. return error_response(400, str(e))
  150. @router.put("/qc-third-party-companies/{company_id}")
  151. async def update_qc_third_party_company(
  152. company_id: str,
  153. body: ThirdPartyCompanyUpdateBody,
  154. db: Session = Depends(get_db),
  155. user: dict = Depends(require_menu_code("biz:qcThirdPartyCompany:list")),
  156. ):
  157. try:
  158. tenant_no = _get_tenant_no(db, user)
  159. obj = tpc_svc.update_company(
  160. db,
  161. company_id,
  162. company_code=body.company_code,
  163. company_name=body.company_name,
  164. contact_name=body.contact_name,
  165. contact_phone=body.contact_phone,
  166. company_logo=body.company_logo,
  167. address=body.address,
  168. invoice_title=body.invoice_title,
  169. tax_id=body.tax_id,
  170. bank_name=body.bank_name,
  171. bank_account=body.bank_account,
  172. status=body.status,
  173. order_num=body.order_num,
  174. remark=body.remark,
  175. user_id=_get_current_user_id(user),
  176. tenant_no=tenant_no,
  177. )
  178. return success_response(tpc_svc._row_to_dict(obj), message="更新成功")
  179. except PermissionError as e:
  180. return error_response(403, str(e))
  181. except ValueError as e:
  182. return error_response(400, str(e))
  183. except Exception as e:
  184. return error_response(400, str(e))
  185. @router.delete("/qc-third-party-companies/{company_id}")
  186. async def delete_qc_third_party_company(
  187. company_id: str,
  188. db: Session = Depends(get_db),
  189. user: dict = Depends(require_menu_code("biz:qcThirdPartyCompany:list")),
  190. ):
  191. try:
  192. tenant_no = _get_tenant_no(db, user)
  193. tpc_svc.soft_delete_company(db, company_id, tenant_no=tenant_no)
  194. return success_response(None, message="删除成功")
  195. except PermissionError as e:
  196. return error_response(403, str(e))
  197. except ValueError as e:
  198. return error_response(400, str(e))
  199. except Exception as e:
  200. return error_response(400, str(e))
  201. # ---------- 第三方检测项目 ----------
  202. class ThirdPartyItemBody(BaseModel):
  203. model_config = ConfigDict(populate_by_name=True)
  204. company_id: str = Field(..., alias="companyId")
  205. item_code: str = Field(..., alias="itemCode")
  206. item_name: str = Field(..., alias="itemName")
  207. fee_amount: float = Field(..., alias="feeAmount")
  208. status: str = "1"
  209. order_num: Optional[int] = Field(None, alias="orderNum")
  210. remark: Optional[str] = None
  211. class ThirdPartyItemUpdateBody(BaseModel):
  212. model_config = ConfigDict(populate_by_name=True)
  213. company_id: Optional[str] = Field(None, alias="companyId")
  214. item_code: Optional[str] = Field(None, alias="itemCode")
  215. item_name: Optional[str] = Field(None, alias="itemName")
  216. fee_amount: Optional[float] = Field(None, alias="feeAmount")
  217. status: Optional[str] = None
  218. order_num: Optional[int] = Field(None, alias="orderNum")
  219. remark: Optional[str] = None
  220. @router.get("/qc-third-party-items")
  221. async def list_qc_third_party_items(
  222. page: int = Query(1, ge=1),
  223. pageSize: int = Query(10, ge=1, le=100),
  224. keyword: Optional[str] = None,
  225. status: Optional[str] = None,
  226. companyId: Optional[str] = None,
  227. db: Session = Depends(get_db),
  228. user: dict = Depends(require_menu_code("biz:qcThirdPartyCompany:list")),
  229. ):
  230. try:
  231. tenant_no = _get_tenant_no(db, user)
  232. items, total = tpi_svc.list_items(
  233. db,
  234. page=page,
  235. page_size=pageSize,
  236. keyword=keyword,
  237. status=status,
  238. company_id=companyId,
  239. tenant_no=tenant_no,
  240. user_info=user,
  241. )
  242. return success_response(_page_payload(items, total, page, pageSize))
  243. except PermissionError as e:
  244. return error_response(403, str(e))
  245. except Exception as e:
  246. return error_response(400, str(e))
  247. @router.get("/qc-third-party-items/active")
  248. async def list_qc_third_party_items_active(
  249. companyId: Optional[str] = None,
  250. db: Session = Depends(get_db),
  251. user: dict = Depends(require_menu_code("biz:qcWorkOrder:list")),
  252. ):
  253. try:
  254. tenant_no = _get_tenant_no(db, user)
  255. return success_response(tpi_svc.list_active_items(db, tenant_no, company_id=companyId, user_info=user))
  256. except PermissionError as e:
  257. return error_response(403, str(e))
  258. except Exception as e:
  259. return error_response(400, str(e))
  260. @router.post("/qc-third-party-items")
  261. async def create_qc_third_party_item(
  262. body: ThirdPartyItemBody,
  263. db: Session = Depends(get_db),
  264. user: dict = Depends(require_menu_code("biz:qcThirdPartyCompany:list")),
  265. ):
  266. try:
  267. tenant_no = _get_tenant_no(db, user)
  268. obj = tpi_svc.create_item(
  269. db,
  270. company_id=body.company_id,
  271. item_code=body.item_code,
  272. item_name=body.item_name,
  273. fee_amount=body.fee_amount,
  274. status=body.status,
  275. tenant_no=tenant_no,
  276. order_num=body.order_num,
  277. remark=body.remark,
  278. user_id=_get_current_user_id(user),
  279. )
  280. return success_response(tpi_svc._row_to_dict(obj, ""), message="创建成功")
  281. except PermissionError as e:
  282. return error_response(403, str(e))
  283. except ValueError as e:
  284. return error_response(400, str(e))
  285. except Exception as e:
  286. return error_response(400, str(e))
  287. @router.put("/qc-third-party-items/{item_id}")
  288. async def update_qc_third_party_item(
  289. item_id: str,
  290. body: ThirdPartyItemUpdateBody,
  291. db: Session = Depends(get_db),
  292. user: dict = Depends(require_menu_code("biz:qcThirdPartyCompany:list")),
  293. ):
  294. try:
  295. tenant_no = _get_tenant_no(db, user)
  296. obj = tpi_svc.update_item(
  297. db,
  298. item_id,
  299. company_id=body.company_id,
  300. item_code=body.item_code,
  301. item_name=body.item_name,
  302. fee_amount=body.fee_amount,
  303. status=body.status,
  304. order_num=body.order_num,
  305. remark=body.remark,
  306. user_id=_get_current_user_id(user),
  307. tenant_no=tenant_no,
  308. )
  309. return success_response(tpi_svc._row_to_dict(obj, ""), message="更新成功")
  310. except PermissionError as e:
  311. return error_response(403, str(e))
  312. except ValueError as e:
  313. return error_response(400, str(e))
  314. except Exception as e:
  315. return error_response(400, str(e))
  316. @router.delete("/qc-third-party-items/{item_id}")
  317. async def delete_qc_third_party_item(
  318. item_id: str,
  319. db: Session = Depends(get_db),
  320. user: dict = Depends(require_menu_code("biz:qcThirdPartyCompany:list")),
  321. ):
  322. try:
  323. tenant_no = _get_tenant_no(db, user)
  324. tpi_svc.soft_delete_item(db, item_id, tenant_no=tenant_no)
  325. return success_response(None, message="删除成功")
  326. except PermissionError as e:
  327. return error_response(403, str(e))
  328. except ValueError as e:
  329. return error_response(400, str(e))
  330. except Exception as e:
  331. return error_response(400, str(e))
  332. # ---------- 实验室自检项目 ----------
  333. class LabTestItemBody(BaseModel):
  334. model_config = ConfigDict(populate_by_name=True)
  335. item_code: str = Field(..., alias="itemCode")
  336. item_name: str = Field(..., alias="itemName")
  337. description: Optional[str] = None
  338. status: str = "1"
  339. order_num: Optional[int] = Field(None, alias="orderNum")
  340. remark: Optional[str] = None
  341. class LabTestItemUpdateBody(BaseModel):
  342. model_config = ConfigDict(populate_by_name=True)
  343. item_code: Optional[str] = Field(None, alias="itemCode")
  344. item_name: Optional[str] = Field(None, alias="itemName")
  345. description: Optional[str] = None
  346. status: Optional[str] = None
  347. order_num: Optional[int] = Field(None, alias="orderNum")
  348. remark: Optional[str] = None
  349. # ---------- 检测项目模版(项目组合) ----------
  350. class InspectionItemTemplateBody(BaseModel):
  351. model_config = ConfigDict(populate_by_name=True)
  352. template_name: str = Field(..., alias="templateName")
  353. lab_item_ids: List[str] = Field(default_factory=list, alias="labItemIds")
  354. third_party_item_ids: List[str] = Field(default_factory=list, alias="thirdPartyItemIds")
  355. status: Optional[str] = "1"
  356. order_num: Optional[int] = Field(None, alias="orderNum")
  357. remark: Optional[str] = None
  358. class InspectionItemTemplateUpdateBody(BaseModel):
  359. model_config = ConfigDict(populate_by_name=True)
  360. template_name: Optional[str] = Field(None, alias="templateName")
  361. lab_item_ids: Optional[List[str]] = Field(None, alias="labItemIds")
  362. third_party_item_ids: Optional[List[str]] = Field(None, alias="thirdPartyItemIds")
  363. status: Optional[str] = None
  364. order_num: Optional[int] = Field(None, alias="orderNum")
  365. remark: Optional[str] = None
  366. # ---------- 检测项目参数模板 ----------
  367. class ItemParamBody(BaseModel):
  368. model_config = ConfigDict(populate_by_name=True)
  369. params: List[Dict[str, Any]] = Field(default_factory=list, alias="params")
  370. class TaskResultBody(BaseModel):
  371. model_config = ConfigDict(populate_by_name=True)
  372. results: List[Dict[str, Any]] = Field(default_factory=list, alias="results")
  373. class TaskCompleteWithResultBody(BaseModel):
  374. model_config = ConfigDict(populate_by_name=True)
  375. conclusion: Optional[str] = Field(None, alias="conclusion")
  376. results: List[Dict[str, Any]] = Field(default_factory=list, alias="results")
  377. remark: Optional[str] = Field(None, alias="remark")
  378. third_party_attachments: Optional[str] = Field(None, alias="thirdPartyAttachments")
  379. material_usages: Optional[List[Dict[str, Any]]] = Field(None, alias="materialUsages")
  380. task_status: Optional[str] = Field(None, alias="taskStatus")
  381. @router.get("/qc-lab-test-items")
  382. async def list_qc_lab_test_items(
  383. page: int = Query(1, ge=1),
  384. pageSize: int = Query(10, ge=1, le=100),
  385. keyword: Optional[str] = None,
  386. status: Optional[str] = None,
  387. db: Session = Depends(get_db),
  388. user: dict = Depends(require_menu_code("biz:qcLabTestItem:list")),
  389. ):
  390. try:
  391. tenant_no = _get_tenant_no(db, user)
  392. items, total = lab_svc.list_lab_items(
  393. db, page=page, page_size=pageSize, keyword=keyword, status=status, tenant_no=tenant_no,
  394. user_info=user
  395. )
  396. return success_response(_page_payload(items, total, page, pageSize))
  397. except PermissionError as e:
  398. return error_response(403, str(e))
  399. except Exception as e:
  400. return error_response(400, str(e))
  401. @router.get("/qc-lab-test-items/active")
  402. async def list_qc_lab_test_items_active(
  403. db: Session = Depends(get_db),
  404. user: dict = Depends(require_menu_code("biz:qcWorkOrder:list")),
  405. ):
  406. try:
  407. tenant_no = _get_tenant_no(db, user)
  408. return success_response(lab_svc.list_active_lab_items(db, tenant_no, user_info=user))
  409. except PermissionError as e:
  410. return error_response(403, str(e))
  411. except Exception as e:
  412. return error_response(400, str(e))
  413. @router.post("/qc-lab-test-items")
  414. async def create_qc_lab_test_item(
  415. body: LabTestItemBody,
  416. db: Session = Depends(get_db),
  417. user: dict = Depends(require_menu_code("biz:qcLabTestItem:list")),
  418. ):
  419. try:
  420. tenant_no = _get_tenant_no(db, user)
  421. obj = lab_svc.create_lab_item(
  422. db,
  423. item_code=body.item_code,
  424. item_name=body.item_name,
  425. description=body.description,
  426. status=body.status,
  427. tenant_no=tenant_no,
  428. order_num=body.order_num,
  429. remark=body.remark,
  430. user_id=_get_current_user_id(user),
  431. )
  432. return success_response(lab_svc._row_to_dict(obj), message="创建成功")
  433. except PermissionError as e:
  434. return error_response(403, str(e))
  435. except ValueError as e:
  436. return error_response(400, str(e))
  437. except Exception as e:
  438. return error_response(400, str(e))
  439. @router.put("/qc-lab-test-items/{item_id}")
  440. async def update_qc_lab_test_item(
  441. item_id: str,
  442. body: LabTestItemUpdateBody,
  443. db: Session = Depends(get_db),
  444. user: dict = Depends(require_menu_code("biz:qcLabTestItem:list")),
  445. ):
  446. try:
  447. tenant_no = _get_tenant_no(db, user)
  448. obj = lab_svc.update_lab_item(
  449. db,
  450. item_id,
  451. item_code=body.item_code,
  452. item_name=body.item_name,
  453. description=body.description,
  454. status=body.status,
  455. order_num=body.order_num,
  456. remark=body.remark,
  457. user_id=_get_current_user_id(user),
  458. tenant_no=tenant_no,
  459. )
  460. return success_response(lab_svc._row_to_dict(obj), message="更新成功")
  461. except PermissionError as e:
  462. return error_response(403, str(e))
  463. except ValueError as e:
  464. return error_response(400, str(e))
  465. except Exception as e:
  466. return error_response(400, str(e))
  467. @router.delete("/qc-lab-test-items/{item_id}")
  468. async def delete_qc_lab_test_item(
  469. item_id: str,
  470. db: Session = Depends(get_db),
  471. user: dict = Depends(require_menu_code("biz:qcLabTestItem:list")),
  472. ):
  473. try:
  474. tenant_no = _get_tenant_no(db, user)
  475. lab_svc.soft_delete_lab_item(db, item_id, tenant_no=tenant_no)
  476. return success_response(None, message="删除成功")
  477. except PermissionError as e:
  478. return error_response(403, str(e))
  479. except ValueError as e:
  480. return error_response(400, str(e))
  481. except Exception as e:
  482. return error_response(400, str(e))
  483. @router.get("/qc-inspection-item-templates")
  484. async def list_qc_inspection_item_templates(
  485. page: int = Query(1, ge=1),
  486. pageSize: int = Query(10, ge=1, le=100),
  487. keyword: Optional[str] = None,
  488. status: Optional[str] = None,
  489. db: Session = Depends(get_db),
  490. user: dict = Depends(require_menu_code("biz:qcInspectionItemTemplate:list")),
  491. ):
  492. try:
  493. tenant_no = _get_tenant_no(db, user)
  494. items, total = iit_svc.list_templates(
  495. db,
  496. page=page,
  497. page_size=pageSize,
  498. keyword=keyword,
  499. status=status,
  500. tenant_no=tenant_no,
  501. user_info=user,
  502. )
  503. return success_response(_page_payload(items, total, page, pageSize))
  504. except PermissionError as e:
  505. return error_response(403, str(e))
  506. except Exception as e:
  507. return error_response(400, str(e))
  508. @router.get("/qc-inspection-item-templates/active")
  509. async def list_qc_inspection_item_templates_active(
  510. db: Session = Depends(get_db),
  511. user: dict = Depends(
  512. require_any_menu_code(
  513. "biz:qcInspectionItemTemplate:list", "biz:qcWorkOrder:list"
  514. )
  515. ),
  516. ):
  517. try:
  518. tenant_no = _get_tenant_no(db, user)
  519. return success_response(
  520. iit_svc.list_active_templates(db, tenant_no, user_info=user)
  521. )
  522. except PermissionError as e:
  523. return error_response(403, str(e))
  524. except Exception as e:
  525. return error_response(400, str(e))
  526. @router.get("/qc-inspection-item-templates/{template_id}")
  527. async def get_qc_inspection_item_template(
  528. template_id: str,
  529. db: Session = Depends(get_db),
  530. user: dict = Depends(require_menu_code("biz:qcInspectionItemTemplate:list")),
  531. ):
  532. try:
  533. tenant_no = _get_tenant_no(db, user)
  534. obj = iit_svc.get_template(db, template_id, tenant_no=tenant_no)
  535. if not obj:
  536. return error_response(404, "模版不存在")
  537. return success_response(iit_svc._row_to_dict(obj))
  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.post("/qc-inspection-item-templates")
  543. async def create_qc_inspection_item_template(
  544. body: InspectionItemTemplateBody,
  545. db: Session = Depends(get_db),
  546. user: dict = Depends(require_menu_code("biz:qcInspectionItemTemplate:add")),
  547. ):
  548. try:
  549. tenant_no = _get_tenant_no(db, user)
  550. obj = iit_svc.create_template(
  551. db,
  552. template_name=body.template_name,
  553. lab_item_ids=body.lab_item_ids,
  554. third_party_item_ids=body.third_party_item_ids,
  555. status=body.status or "1",
  556. tenant_no=tenant_no,
  557. order_num=body.order_num,
  558. remark=body.remark,
  559. user_id=_get_current_user_id(user),
  560. create_dept_id=user.get("dept_id", "") or "",
  561. )
  562. return success_response(iit_svc._row_to_dict(obj), message="创建成功")
  563. except PermissionError as e:
  564. return error_response(403, str(e))
  565. except ValueError as e:
  566. return error_response(400, str(e))
  567. except Exception as e:
  568. return error_response(400, str(e))
  569. @router.put("/qc-inspection-item-templates/{template_id}")
  570. async def update_qc_inspection_item_template(
  571. template_id: str,
  572. body: InspectionItemTemplateUpdateBody,
  573. db: Session = Depends(get_db),
  574. user: dict = Depends(require_menu_code("biz:qcInspectionItemTemplate:edit")),
  575. ):
  576. try:
  577. tenant_no = _get_tenant_no(db, user)
  578. obj = iit_svc.update_template(
  579. db,
  580. template_id,
  581. template_name=body.template_name,
  582. lab_item_ids=body.lab_item_ids,
  583. third_party_item_ids=body.third_party_item_ids,
  584. status=body.status,
  585. order_num=body.order_num,
  586. remark=body.remark,
  587. user_id=_get_current_user_id(user),
  588. tenant_no=tenant_no,
  589. )
  590. return success_response(iit_svc._row_to_dict(obj), message="更新成功")
  591. except PermissionError as e:
  592. return error_response(403, str(e))
  593. except ValueError as e:
  594. return error_response(400, str(e))
  595. except Exception as e:
  596. return error_response(400, str(e))
  597. @router.delete("/qc-inspection-item-templates/{template_id}")
  598. async def delete_qc_inspection_item_template(
  599. template_id: str,
  600. db: Session = Depends(get_db),
  601. user: dict = Depends(require_menu_code("biz:qcInspectionItemTemplate:remove")),
  602. ):
  603. try:
  604. tenant_no = _get_tenant_no(db, user)
  605. iit_svc.soft_delete_template(db, template_id, tenant_no=tenant_no)
  606. return success_response(None, message="删除成功")
  607. except PermissionError as e:
  608. return error_response(403, str(e))
  609. except ValueError as e:
  610. return error_response(400, str(e))
  611. except Exception as e:
  612. return error_response(400, str(e))
  613. # ---------- 检测项目参数模板 ----------
  614. @router.get("/qc-item-params")
  615. async def list_item_params(
  616. itemSource: str = Query(...),
  617. itemId: str = Query(...),
  618. db: Session = Depends(get_db),
  619. user: dict = Depends(require_menu_code("biz:qcLabTestItem:list")),
  620. ):
  621. try:
  622. tenant_no = _get_tenant_no(db, user)
  623. return success_response(param_svc.list_params_by_item(db, itemSource, itemId, tenant_no, user_info=user))
  624. except PermissionError as e:
  625. return error_response(403, str(e))
  626. except Exception as e:
  627. return error_response(400, str(e))
  628. @router.put("/qc-item-params")
  629. async def save_item_params(
  630. body: ItemParamBody,
  631. itemSource: str = Query(...),
  632. itemId: str = Query(...),
  633. db: Session = Depends(get_db),
  634. user: dict = Depends(require_menu_code("biz:qcLabTestItem:list")),
  635. ):
  636. try:
  637. tenant_no = _get_tenant_no(db, user)
  638. return success_response(
  639. param_svc.save_params_for_item(db, itemSource, itemId, body.params, tenant_no, _get_current_user_id(user)),
  640. message="保存成功",
  641. )
  642. except PermissionError as e:
  643. return error_response(403, str(e))
  644. except Exception as e:
  645. return error_response(400, str(e))
  646. # ---------- 质检工单 ----------
  647. class WorkOrderConfigureBatchItem(BaseModel):
  648. model_config = ConfigDict(populate_by_name=True)
  649. id: Optional[str] = None
  650. batch_name: Optional[str] = Field(None, alias="batchName")
  651. assignee_user_ids: List[str] = Field(default_factory=list, alias="assigneeUserIds")
  652. has_lab: bool = Field(False, alias="hasLab")
  653. has_third_party: bool = Field(False, alias="hasThirdParty")
  654. lab_item_ids: List[str] = Field(default_factory=list, alias="labItemIds")
  655. third_party_item_ids: List[str] = Field(default_factory=list, alias="thirdPartyItemIds")
  656. class WorkOrderConfigureBody(BaseModel):
  657. model_config = ConfigDict(populate_by_name=True)
  658. batches: Optional[List[WorkOrderConfigureBatchItem]] = Field(None, alias="batches")
  659. has_lab: bool = Field(False, alias="hasLab")
  660. has_third_party: bool = Field(False, alias="hasThirdParty")
  661. lab_item_ids: List[str] = Field(default_factory=list, alias="labItemIds")
  662. third_party_item_ids: List[str] = Field(default_factory=list, alias="thirdPartyItemIds")
  663. lab_item_assignees: Dict[str, List[str]] = Field(default_factory=dict, alias="labItemAssignees")
  664. third_party_item_assignees: Dict[str, List[str]] = Field(
  665. default_factory=dict, alias="thirdPartyItemAssignees"
  666. )
  667. @router.post("/qc-work-orders")
  668. async def create_qc_work_order(
  669. body: QcWorkOrderCreateBody,
  670. db: Session = Depends(get_db),
  671. user: dict = Depends(require_menu_code("biz:qcWorkOrder:list")),
  672. ):
  673. try:
  674. tenant_no = _get_tenant_no(db, user)
  675. wo_type = (body.work_order_type or "inbound").strip()
  676. if wo_type == "temporary":
  677. wo = wo_svc.create_temp_qc_work_order(
  678. db,
  679. tenant_no=tenant_no,
  680. user_id=user.get("user_id"),
  681. create_dept_id=user.get("dept_id", ""),
  682. cell_product_id=body.cell_product_id or "",
  683. remark=body.remark or "",
  684. )
  685. else:
  686. wo = wo_svc.create_qc_work_order_manual(
  687. db,
  688. tenant_no=tenant_no,
  689. user_id=user.get("user_id"),
  690. create_dept_id=user.get("dept_id", ""),
  691. protocol_no=body.protocol_no or "",
  692. sample_code=body.sample_code or "",
  693. reception_source=body.reception_source or "cell_storage",
  694. qc_biz_type=body.qc_biz_type or "inbound",
  695. remark=body.remark or "",
  696. )
  697. db.commit()
  698. return success_response(wo_svc._wo_to_dict(wo), message="创建成功")
  699. except PermissionError as e:
  700. return error_response(403, str(e))
  701. except Exception as e:
  702. db.rollback()
  703. return error_response(400, str(e))
  704. @router.get("/qc-work-orders")
  705. async def list_qc_work_orders(
  706. page: int = Query(1, ge=1),
  707. pageSize: int = Query(10, ge=1, le=100),
  708. keyword: Optional[str] = None,
  709. workOrderStatus: Optional[str] = Query(None, description="工单状态,多个用英文逗号分隔"),
  710. workOrderType: Optional[str] = None,
  711. bizType: Optional[str] = Query(None, alias="bizType"),
  712. receptionSource: Optional[str] = Query(None, alias="receptionSource"),
  713. createTimeStart: Optional[str] = Query(None, alias="createTimeStart"),
  714. createTimeEnd: Optional[str] = Query(None, alias="createTimeEnd"),
  715. infusionTimeStart: Optional[str] = Query(None, alias="infusionTimeStart"),
  716. infusionTimeEnd: Optional[str] = Query(None, alias="infusionTimeEnd"),
  717. triggerSource: Optional[str] = Query(None, alias="triggerSource"),
  718. sampleTypeId: Optional[str] = Query(None, alias="sampleTypeId"),
  719. db: Session = Depends(get_db),
  720. user: dict = Depends(require_menu_code("biz:qcWorkOrder:list")),
  721. ):
  722. try:
  723. tenant_no = _get_tenant_no(db, user)
  724. items, total = wo_svc.list_work_orders(
  725. db,
  726. page=page,
  727. page_size=pageSize,
  728. keyword=keyword,
  729. work_order_status=workOrderStatus,
  730. work_order_type=workOrderType,
  731. biz_type=bizType,
  732. reception_source=receptionSource,
  733. trigger_source=triggerSource,
  734. sample_type_id=sampleTypeId,
  735. create_time_start=createTimeStart,
  736. create_time_end=createTimeEnd,
  737. infusion_time_start=infusionTimeStart,
  738. infusion_time_end=infusionTimeEnd,
  739. tenant_no=tenant_no,
  740. user_info=user,
  741. )
  742. return success_response(_page_payload(items, total, page, pageSize))
  743. except PermissionError as e:
  744. return error_response(403, str(e))
  745. except Exception as e:
  746. return error_response(400, str(e))
  747. @router.get("/qc-work-orders/tab-unfinished-counts")
  748. async def qc_work_order_tab_unfinished_counts(
  749. db: Session = Depends(get_db),
  750. user: dict = Depends(require_menu_code("biz:qcWorkOrder:list")),
  751. ):
  752. try:
  753. tenant_no = _get_tenant_no(db, user)
  754. counts = wo_svc.count_unfinished_work_orders_by_tab(
  755. db, tenant_no=tenant_no, user_info=user
  756. )
  757. return success_response(counts)
  758. except PermissionError as e:
  759. return error_response(403, str(e))
  760. except Exception as e:
  761. return error_response(400, str(e))
  762. @router.get("/qc-work-orders/mine-tab-unfinished-counts")
  763. async def qc_work_order_mine_tab_unfinished_counts(
  764. db: Session = Depends(get_db),
  765. user: dict = Depends(require_menu_code("biz:myQcTask:list")),
  766. ):
  767. try:
  768. tenant_no = _get_tenant_no(db, user)
  769. counts = wo_svc.count_mine_unfinished_work_orders_by_tab(
  770. db,
  771. tenant_no=tenant_no,
  772. assignee_user_id=_get_current_user_id(user),
  773. )
  774. return success_response(counts)
  775. except PermissionError as e:
  776. return error_response(403, str(e))
  777. except Exception as e:
  778. return error_response(400, str(e))
  779. @router.get("/qc-work-orders/by-sample")
  780. async def list_qc_work_orders_by_sample(
  781. sampleCode: str = Query(..., alias="sampleCode"),
  782. receptionSource: str = Query(..., alias="receptionSource"),
  783. db: Session = Depends(get_db),
  784. user: dict = Depends(
  785. require_any_menu_code("biz:qcWorkOrder:list", "biz:myQcTask:list")
  786. ),
  787. ):
  788. try:
  789. tenant_no = _get_tenant_no(db, user)
  790. items = wo_svc.list_work_orders_by_sample(
  791. db,
  792. sample_code=sampleCode,
  793. reception_source=receptionSource,
  794. tenant_no=tenant_no,
  795. user_info=user,
  796. )
  797. return success_response({"list": items})
  798. except PermissionError as e:
  799. return error_response(403, str(e))
  800. except Exception as e:
  801. return error_response(400, str(e))
  802. @router.get("/qc-work-orders/{work_order_id}")
  803. async def get_qc_work_order_detail(
  804. work_order_id: str,
  805. db: Session = Depends(get_db),
  806. user: dict = Depends(require_menu_code("biz:qcWorkOrder:list")),
  807. ):
  808. try:
  809. tenant_no = _get_tenant_no(db, user)
  810. data = wo_svc.get_work_order_detail(db, work_order_id, tenant_no)
  811. _maybe_strip_qc_third_party_fee_fields(db, user, data)
  812. return success_response(data)
  813. except PermissionError as e:
  814. return error_response(403, str(e))
  815. except ValueError as e:
  816. return error_response(400, str(e))
  817. except Exception as e:
  818. return error_response(400, str(e))
  819. @router.get("/qc-work-orders/{work_order_id}/outbound-detail")
  820. async def get_outbound_qc_detail(
  821. work_order_id: str,
  822. db: Session = Depends(get_db),
  823. user: dict = Depends(require_menu_code("biz:qcWorkOrder:list")),
  824. ):
  825. try:
  826. tenant_no = _get_tenant_no(db, user)
  827. data = wo_svc.get_outbound_qc_detail(db, work_order_id, tenant_no)
  828. _maybe_strip_qc_third_party_fee_fields(db, user, data)
  829. return success_response(data)
  830. except PermissionError as e:
  831. return error_response(403, str(e))
  832. except ValueError as e:
  833. return error_response(400, str(e))
  834. except Exception as e:
  835. return error_response(400, str(e))
  836. @router.put("/qc-work-orders/{work_order_id}")
  837. async def update_qc_work_order(
  838. work_order_id: str,
  839. body: QcWorkOrderUpdateBody,
  840. db: Session = Depends(get_db),
  841. user: dict = Depends(require_menu_code("biz:qcWorkOrder:list")),
  842. ):
  843. try:
  844. tenant_no = _get_tenant_no(db, user)
  845. wo = wo_svc.update_qc_work_order(
  846. db,
  847. work_order_id,
  848. tenant_no=tenant_no,
  849. user_id=_get_current_user_id(user),
  850. cell_product_id=body.cell_product_id,
  851. work_order_status=body.work_order_status,
  852. qc_conclusion=body.qc_conclusion,
  853. remark=body.remark,
  854. )
  855. db.commit()
  856. return success_response(wo_svc._wo_to_dict(wo), message="保存成功")
  857. except PermissionError as e:
  858. return error_response(403, str(e))
  859. except ValueError as e:
  860. db.rollback()
  861. return error_response(400, str(e))
  862. except Exception as e:
  863. db.rollback()
  864. return error_response(400, str(e))
  865. @router.delete("/qc-work-orders/{work_order_id}")
  866. async def delete_qc_work_order_api(
  867. work_order_id: str,
  868. user: dict = Depends(require_admin_or_super_admin),
  869. db: Session = Depends(get_db),
  870. ):
  871. try:
  872. tenant_no = _get_tenant_no(db, user)
  873. wo_svc.delete_qc_work_order(db, work_order_id, tenant_no, user.get("user_id"))
  874. return success_response(None, message="删除成功")
  875. except ValueError as e:
  876. return error_response(400, str(e))
  877. class InboundSampleSpecialMarkBody(BaseModel):
  878. model_config = ConfigDict(populate_by_name=True)
  879. reception_source: str = Field(..., alias="receptionSource")
  880. protocol_sample_id: str = Field(..., alias="protocolSampleId")
  881. is_special: bool = Field(..., alias="isSpecial")
  882. special_remark: Optional[str] = Field(None, alias="specialRemark")
  883. @router.put("/inbound-samples/special-mark")
  884. async def update_inbound_sample_special_mark(
  885. body: InboundSampleSpecialMarkBody,
  886. db: Session = Depends(get_db),
  887. user: dict = Depends(
  888. require_any_menu_code("biz:qcWorkOrder:list", "biz:myQcTask:list")
  889. ),
  890. ):
  891. try:
  892. tenant_no = _get_tenant_no(db, user)
  893. source = (body.reception_source or "").strip()
  894. if source not in ("cell_storage", "research_donation"):
  895. return error_response(400, "仅支持细胞存储或科研捐赠样本")
  896. data = inbound_sample_special_svc.update_inbound_sample_special_mark(
  897. db,
  898. tenant_no=tenant_no,
  899. reception_source=source,
  900. protocol_sample_id=body.protocol_sample_id,
  901. is_special=body.is_special,
  902. special_remark=body.special_remark,
  903. user_id=user.get("user_id") or "",
  904. )
  905. db.commit()
  906. return success_response(data, message="保存成功")
  907. except ValueError as e:
  908. db.rollback()
  909. return error_response(400, str(e))
  910. except Exception as e:
  911. db.rollback()
  912. return error_response(400, str(e))
  913. @router.post("/qc-work-orders/{work_order_id}/configure")
  914. async def configure_qc_work_order(
  915. work_order_id: str,
  916. body: WorkOrderConfigureBody,
  917. db: Session = Depends(get_db),
  918. user: dict = Depends(require_menu_code("biz:qcWorkOrder:list")),
  919. ):
  920. try:
  921. tenant_no = _get_tenant_no(db, user)
  922. obj = wo_svc.configure_work_order(
  923. db,
  924. work_order_id,
  925. has_lab=body.has_lab,
  926. has_third_party=body.has_third_party,
  927. lab_item_ids=body.lab_item_ids,
  928. third_party_item_ids=body.third_party_item_ids,
  929. lab_item_assignees=body.lab_item_assignees,
  930. third_party_item_assignees=body.third_party_item_assignees,
  931. batches=[b.model_dump(by_alias=True) for b in body.batches] if body.batches is not None else None,
  932. tenant_no=tenant_no,
  933. user_id=_get_current_user_id(user),
  934. create_dept_id=user.get("dept_id", ""),
  935. )
  936. return success_response(wo_svc._wo_to_dict(obj), message="配置成功")
  937. except PermissionError as e:
  938. return error_response(403, str(e))
  939. except ValueError as e:
  940. return error_response(400, str(e))
  941. except Exception as e:
  942. return error_response(400, str(e))
  943. class WorkOrderInspectionBatchesBatchBody(BaseModel):
  944. model_config = ConfigDict(populate_by_name=True)
  945. work_order_ids: List[str] = Field(default_factory=list, alias="workOrderIds")
  946. @router.post("/qc-work-orders/inspection-batches/batch")
  947. async def batch_list_qc_work_order_inspection_batches(
  948. body: WorkOrderInspectionBatchesBatchBody,
  949. db: Session = Depends(get_db),
  950. user: dict = Depends(require_any_menu_code(*QC_TASK_READONLY_MENU_CODES)),
  951. ):
  952. try:
  953. tenant_no = _get_tenant_no(db, user)
  954. from app.crud import qc_inspection_batch as batch_svc
  955. data = batch_svc.list_inspection_batches_by_work_order_ids(
  956. db, body.work_order_ids, tenant_no
  957. )
  958. return success_response(data)
  959. except PermissionError as e:
  960. return error_response(403, str(e))
  961. except Exception as e:
  962. return error_response(400, str(e))
  963. @router.get("/qc-work-orders/{work_order_id}/inspection-batches")
  964. async def list_qc_work_order_inspection_batches(
  965. work_order_id: str,
  966. db: Session = Depends(get_db),
  967. user: dict = Depends(require_any_menu_code(*QC_TASK_READONLY_MENU_CODES)),
  968. ):
  969. try:
  970. tenant_no = _get_tenant_no(db, user)
  971. from app.crud import qc_inspection_batch as batch_svc
  972. wo = wo_svc.get_work_order(db, work_order_id, tenant_no=tenant_no)
  973. if not wo:
  974. return error_response(404, "工单不存在")
  975. return success_response(batch_svc.list_inspection_batches(db, work_order_id, tenant_no))
  976. except PermissionError as e:
  977. return error_response(403, str(e))
  978. except Exception as e:
  979. return error_response(400, str(e))
  980. # ---------- 质检任务 ----------
  981. class TaskAttachmentsBody(BaseModel):
  982. model_config = ConfigDict(populate_by_name=True)
  983. third_party_attachments: str = Field("", alias="thirdPartyAttachments")
  984. @router.post("/qc-tasks")
  985. async def create_qc_task(
  986. body: QcTaskCreateBody,
  987. db: Session = Depends(get_db),
  988. user: dict = Depends(require_menu_code("biz:qcTask:list")),
  989. ):
  990. try:
  991. tenant_no = _get_tenant_no(db, user)
  992. task = task_svc.create_qc_task_manual(
  993. db,
  994. tenant_no=tenant_no,
  995. user_id=user.get("user_id"),
  996. create_dept_id=user.get("dept_id", ""),
  997. task_type=body.task_type,
  998. item_code=body.item_code,
  999. item_name=body.item_name,
  1000. company_id=body.company_id,
  1001. company_name=body.company_name,
  1002. fee_amount=body.fee_amount,
  1003. sample_code=body.sample_code or "",
  1004. work_order_id=body.work_order_id or "",
  1005. remark=body.remark or "",
  1006. )
  1007. db.commit()
  1008. return success_response(task_svc._task_to_dict(task), message="创建成功")
  1009. except PermissionError as e:
  1010. return error_response(403, str(e))
  1011. except Exception as e:
  1012. db.rollback()
  1013. return error_response(400, str(e))
  1014. @router.get("/qc-tasks/mine")
  1015. async def list_my_qc_tasks(
  1016. page: int = Query(1, ge=1),
  1017. pageSize: int = Query(10, ge=1, le=100),
  1018. keyword: Optional[str] = None,
  1019. taskType: Optional[str] = None,
  1020. taskStatus: Optional[str] = None,
  1021. qcBizType: Optional[str] = None,
  1022. receptionSource: Optional[str] = Query(None, alias="receptionSource"),
  1023. bizType: Optional[str] = Query(None, alias="bizType"),
  1024. db: Session = Depends(get_db),
  1025. user: dict = Depends(require_menu_code("biz:myQcTask:list")),
  1026. ):
  1027. try:
  1028. tenant_no = _get_tenant_no(db, user)
  1029. items, total = task_svc.list_mine_tasks(
  1030. db,
  1031. assignee_user_id=_get_current_user_id(user),
  1032. page=page,
  1033. page_size=pageSize,
  1034. keyword=keyword,
  1035. task_type=taskType,
  1036. task_status=taskStatus,
  1037. qc_biz_type=qcBizType,
  1038. reception_source=receptionSource,
  1039. biz_type=bizType,
  1040. tenant_no=tenant_no,
  1041. )
  1042. return success_response(_page_payload(items, total, page, pageSize))
  1043. except PermissionError as e:
  1044. return error_response(403, str(e))
  1045. except Exception as e:
  1046. return error_response(400, str(e))
  1047. @router.get("/qc-tasks")
  1048. async def list_qc_tasks(
  1049. page: int = Query(1, ge=1),
  1050. pageSize: int = Query(10, ge=1, le=100),
  1051. keyword: Optional[str] = None,
  1052. taskType: Optional[str] = None,
  1053. taskStatus: Optional[str] = None,
  1054. workOrderId: Optional[str] = None,
  1055. qcBizType: Optional[str] = None,
  1056. db: Session = Depends(get_db),
  1057. user: dict = Depends(require_menu_code("biz:qcTask:list")),
  1058. ):
  1059. try:
  1060. tenant_no = _get_tenant_no(db, user)
  1061. items, total = task_svc.list_tasks(
  1062. db,
  1063. page=page,
  1064. page_size=pageSize,
  1065. keyword=keyword,
  1066. task_type=taskType,
  1067. task_status=taskStatus,
  1068. work_order_id=workOrderId,
  1069. qc_biz_type=qcBizType,
  1070. tenant_no=tenant_no,
  1071. user_info=user,
  1072. )
  1073. return success_response(_page_payload(items, total, page, pageSize))
  1074. except PermissionError as e:
  1075. return error_response(403, str(e))
  1076. except Exception as e:
  1077. return error_response(400, str(e))
  1078. @router.get("/qc-tasks/{task_id}")
  1079. async def get_qc_task_detail(
  1080. task_id: str,
  1081. db: Session = Depends(get_db),
  1082. user: dict = Depends(require_any_menu_code(*QC_TASK_READONLY_MENU_CODES)),
  1083. ):
  1084. try:
  1085. tenant_no = _get_tenant_no(db, user)
  1086. data = task_svc.get_task_detail(db, task_id, tenant_no)
  1087. return success_response(data)
  1088. except PermissionError as e:
  1089. return error_response(403, str(e))
  1090. except ValueError as e:
  1091. return error_response(400, str(e))
  1092. except Exception as e:
  1093. return error_response(400, str(e))
  1094. @router.post("/qc-tasks/{task_id}/start")
  1095. async def start_qc_task(
  1096. task_id: str,
  1097. operateScope: Optional[str] = Query(None, alias="operateScope"),
  1098. db: Session = Depends(get_db),
  1099. user: dict = Depends(require_any_menu_code("biz:qcTask:list", "biz:myQcTask:list")),
  1100. ):
  1101. try:
  1102. tenant_no = _get_tenant_no(db, user)
  1103. obj = task_svc.start_task(db, task_id, tenant_no=tenant_no, user_id=_get_current_user_id(user))
  1104. return success_response(task_svc._task_to_dict(obj), message="已开始")
  1105. except PermissionError as e:
  1106. return error_response(403, str(e))
  1107. except ValueError as e:
  1108. return error_response(400, str(e))
  1109. except Exception as e:
  1110. return error_response(400, str(e))
  1111. @router.post("/qc-tasks/{task_id}/complete")
  1112. async def complete_qc_task(
  1113. task_id: str,
  1114. db: Session = Depends(get_db),
  1115. user: dict = Depends(require_menu_code("biz:qcTask:list")),
  1116. ):
  1117. try:
  1118. tenant_no = _get_tenant_no(db, user)
  1119. obj = task_svc.complete_task(
  1120. db, task_id, tenant_no=tenant_no, user_id=_get_current_user_id(user)
  1121. )
  1122. return success_response(task_svc._task_to_dict(obj), message="已完成")
  1123. except PermissionError as e:
  1124. return error_response(403, str(e))
  1125. except ValueError as e:
  1126. return error_response(400, str(e))
  1127. except Exception as e:
  1128. return error_response(400, str(e))
  1129. @router.get("/qc-tasks/{task_id}/results")
  1130. async def get_task_results(
  1131. task_id: str,
  1132. db: Session = Depends(get_db),
  1133. user: dict = Depends(require_any_menu_code(*QC_TASK_READONLY_MENU_CODES)),
  1134. ):
  1135. try:
  1136. tenant_no = _get_tenant_no(db, user)
  1137. return success_response(result_svc.list_results_by_task(db, task_id, tenant_no, user_info=user))
  1138. except PermissionError as e:
  1139. return error_response(403, str(e))
  1140. except Exception as e:
  1141. return error_response(400, str(e))
  1142. @router.get("/qc-material-requisition-options")
  1143. async def list_qc_material_requisition_options(
  1144. keyword: Optional[str] = None,
  1145. limit: int = Query(50, ge=1, le=100),
  1146. db: Session = Depends(get_db),
  1147. user: dict = Depends(require_any_menu_code("biz:qcTask:list", "biz:myQcTask:list")),
  1148. ):
  1149. try:
  1150. tenant_no = _get_tenant_no(db, user)
  1151. items = mu_svc.list_requisition_options(
  1152. db,
  1153. tenant_no,
  1154. keyword=keyword,
  1155. limit=limit,
  1156. user_info=user,
  1157. )
  1158. return success_response(items)
  1159. except PermissionError as e:
  1160. return error_response(403, str(e))
  1161. except Exception as e:
  1162. return error_response(400, str(e))
  1163. @router.get("/qc-tasks/{task_id}/material-usages")
  1164. async def get_task_material_usages(
  1165. task_id: str,
  1166. db: Session = Depends(get_db),
  1167. user: dict = Depends(require_any_menu_code(*QC_TASK_READONLY_MENU_CODES)),
  1168. ):
  1169. try:
  1170. tenant_no = _get_tenant_no(db, user)
  1171. t = task_svc.get_task(db, task_id, tenant_no=tenant_no)
  1172. if not t:
  1173. return error_response(404, "任务不存在")
  1174. return success_response(
  1175. mu_svc.list_usages_by_task(db, task_id, tenant_no, user_info=user)
  1176. )
  1177. except PermissionError as e:
  1178. return error_response(403, str(e))
  1179. except Exception as e:
  1180. return error_response(400, str(e))
  1181. @router.post("/qc-tasks/{task_id}/complete-with-result")
  1182. async def complete_task_with_result(
  1183. task_id: str,
  1184. body: TaskCompleteWithResultBody,
  1185. operateScope: Optional[str] = Query(None, alias="operateScope"),
  1186. db: Session = Depends(get_db),
  1187. user: dict = Depends(require_any_menu_code("biz:qcTask:list", "biz:myQcTask:list")),
  1188. ):
  1189. try:
  1190. tenant_no = _get_tenant_no(db, user)
  1191. user_id = _get_current_user_id(user)
  1192. t = task_svc.get_task(db, task_id, tenant_no=tenant_no)
  1193. if not t:
  1194. return error_response(404, "任务不存在")
  1195. was_done = (t.task_status or "").strip() == "ywc"
  1196. if body.results:
  1197. result_svc.save_results_for_task(
  1198. db, task_id, body.results, tenant_no, user_id, commit=False,
  1199. )
  1200. if body.third_party_attachments is not None:
  1201. task_svc.update_task_attachments(
  1202. db, task_id, attachments=body.third_party_attachments,
  1203. tenant_no=tenant_no, user_id=user_id, commit=False,
  1204. )
  1205. obj = task_svc.apply_task_result(
  1206. db,
  1207. task_id,
  1208. tenant_no=tenant_no,
  1209. user_id=user_id,
  1210. conclusion=body.conclusion,
  1211. remark=body.remark,
  1212. material_usages=body.material_usages,
  1213. task_status=body.task_status,
  1214. commit=False,
  1215. )
  1216. db.commit()
  1217. db.refresh(obj)
  1218. if (obj.task_status or "").strip() == "ywc":
  1219. wo_svc.try_complete_work_order(db, obj.work_order_id, tenant_no)
  1220. elif was_done:
  1221. wo_svc.try_reopen_work_order(db, obj.work_order_id, tenant_no)
  1222. return success_response(
  1223. task_svc._task_to_dict(obj, work_order_no="", db=db, tenant_no=tenant_no),
  1224. message="已保存",
  1225. )
  1226. except HTTPException as e:
  1227. db.rollback()
  1228. detail = e.detail
  1229. msg = detail if isinstance(detail, str) else str(detail)
  1230. return error_response(e.status_code, msg)
  1231. except PermissionError as e:
  1232. db.rollback()
  1233. return error_response(403, str(e))
  1234. except ValueError as e:
  1235. db.rollback()
  1236. return error_response(400, str(e))
  1237. except Exception as e:
  1238. db.rollback()
  1239. return error_response(400, str(e))
  1240. @router.put("/qc-tasks/{task_id}/attachments")
  1241. async def update_qc_task_attachments(
  1242. task_id: str,
  1243. body: TaskAttachmentsBody,
  1244. operateScope: Optional[str] = Query(None, alias="operateScope"),
  1245. db: Session = Depends(get_db),
  1246. user: dict = Depends(require_any_menu_code("biz:qcTask:list", "biz:myQcTask:list")),
  1247. ):
  1248. try:
  1249. tenant_no = _get_tenant_no(db, user)
  1250. obj = task_svc.update_task_attachments(
  1251. db,
  1252. task_id,
  1253. attachments=body.third_party_attachments,
  1254. tenant_no=tenant_no,
  1255. user_id=_get_current_user_id(user),
  1256. )
  1257. return success_response(task_svc._task_to_dict(obj), message="已保存")
  1258. except PermissionError as e:
  1259. return error_response(403, str(e))
  1260. except ValueError as e:
  1261. return error_response(400, str(e))
  1262. except Exception as e:
  1263. return error_response(400, str(e))
  1264. @router.delete("/qc-tasks/{task_id}")
  1265. async def delete_qc_task_api(
  1266. task_id: str,
  1267. user: dict = Depends(require_admin_or_super_admin),
  1268. db: Session = Depends(get_db),
  1269. ):
  1270. try:
  1271. tenant_no = _get_tenant_no(db, user)
  1272. task_svc.delete_qc_task(db, task_id, tenant_no, user.get("user_id"))
  1273. return success_response(None, message="删除成功")
  1274. except ValueError as e:
  1275. return error_response(400, str(e))
  1276. # ---------- 质检物料库 ----------
  1277. def _maybe_strip_qc_material_amount_fields(
  1278. db: Session, user: dict, rows: Iterable[Dict[str, Any]]
  1279. ) -> None:
  1280. if user_has_menu_perm(db, user, QC_MATERIAL_VIEW_AMOUNT_PERM):
  1281. return
  1282. strip_row_fields(rows, *QC_MATERIAL_AMOUNT_FIELD_NAMES)
  1283. def _user_can_view_qc_material_amount(db: Session, user: dict) -> bool:
  1284. return user_has_menu_perm(db, user, QC_MATERIAL_VIEW_AMOUNT_PERM)
  1285. def _strip_amount_from_write_data(db: Session, user: dict, data: Dict[str, Any]) -> None:
  1286. if _user_can_view_qc_material_amount(db, user):
  1287. return
  1288. for key in ("unit_price", "unitPrice", "amount"):
  1289. data.pop(key, None)
  1290. def _resolve_stock_in_amounts(
  1291. db: Session, user: dict, unit_price: Any, amount: Any
  1292. ) -> tuple:
  1293. if _user_can_view_qc_material_amount(db, user):
  1294. return unit_price, amount
  1295. return 0, 0
  1296. def _maybe_strip_qc_third_party_fee_fields(
  1297. db: Session, user: dict, data: Dict[str, Any]
  1298. ) -> None:
  1299. if user_has_menu_perm(db, user, QC_THIRD_PARTY_VIEW_AMOUNT_PERM):
  1300. return
  1301. strip_row_fields([data], "thirdPartyFeeTotal")
  1302. third_items = data.get("thirdPartyItems")
  1303. if isinstance(third_items, list):
  1304. strip_row_fields(third_items, "feeAmount")
  1305. tasks = data.get("tasks")
  1306. if isinstance(tasks, list):
  1307. for task in tasks:
  1308. if isinstance(task, dict) and (task.get("taskType") or "").strip() == "dsfjc":
  1309. strip_row_fields([task], "feeAmount")
  1310. work_order = data.get("workOrder")
  1311. if isinstance(work_order, dict):
  1312. strip_row_fields([work_order], "thirdPartyFeeTotal")
  1313. wo_tasks = work_order.get("tasks")
  1314. if isinstance(wo_tasks, list):
  1315. for task in wo_tasks:
  1316. if isinstance(task, dict) and (task.get("taskType") or "").strip() == "dsfjc":
  1317. strip_row_fields([task], "feeAmount")
  1318. def _maybe_strip_qc_material_stock_check_detail(db: Session, user: dict, data: Dict[str, Any]) -> None:
  1319. if user_has_menu_perm(db, user, QC_MATERIAL_VIEW_AMOUNT_PERM):
  1320. return
  1321. for key in ("batchLines", "unusedLines"):
  1322. lines = data.get(key)
  1323. if isinstance(lines, list):
  1324. strip_row_fields(lines, *QC_MATERIAL_AMOUNT_FIELD_NAMES)
  1325. class QcMaterialBody(BaseModel):
  1326. model_config = ConfigDict(populate_by_name=True)
  1327. material_code: str = Field(..., alias="materialCode")
  1328. material_name: str = Field(..., alias="materialName")
  1329. spec_model: Optional[str] = Field(None, alias="specModel")
  1330. unit: Optional[str] = None
  1331. warning_qty: Optional[float] = Field(0, alias="warningQty")
  1332. status: str = "1"
  1333. remark: Optional[str] = None
  1334. class QcMaterialUpdateBody(BaseModel):
  1335. model_config = ConfigDict(populate_by_name=True)
  1336. material_code: Optional[str] = Field(None, alias="materialCode")
  1337. material_name: Optional[str] = Field(None, alias="materialName")
  1338. spec_model: Optional[str] = Field(None, alias="specModel")
  1339. unit: Optional[str] = None
  1340. warning_qty: Optional[float] = Field(None, alias="warningQty")
  1341. status: Optional[str] = None
  1342. remark: Optional[str] = None
  1343. class StockInBody(BaseModel):
  1344. model_config = ConfigDict(populate_by_name=True)
  1345. stock_in_no: str = Field(..., alias="stockInNo")
  1346. stock_in_date: str = Field(..., alias="stockInDate")
  1347. expire_date: str = Field(..., alias="expireDate")
  1348. catalog_no: str = Field(..., alias="catalogNo")
  1349. batch_no: str = Field(..., alias="batchNo")
  1350. manufacturer: str
  1351. unit_price: float = Field(..., alias="unitPrice")
  1352. amount: float
  1353. qty: float = Field(..., gt=0)
  1354. remark: Optional[str] = None
  1355. stock_in_time: Optional[str] = Field(None, alias="stockInTime")
  1356. class BatchStockInItem(BaseModel):
  1357. model_config = ConfigDict(populate_by_name=True)
  1358. material_id: str = Field(..., alias="materialId")
  1359. stock_in_no: str = Field(..., alias="stockInNo")
  1360. stock_in_date: str = Field(..., alias="stockInDate")
  1361. expire_date: str = Field(..., alias="expireDate")
  1362. catalog_no: str = Field(..., alias="catalogNo")
  1363. batch_no: str = Field(..., alias="batchNo")
  1364. manufacturer: str
  1365. unit_price: float = Field(..., alias="unitPrice")
  1366. amount: float
  1367. qty: float = Field(..., gt=0)
  1368. remark: Optional[str] = None
  1369. class BatchStockInBody(BaseModel):
  1370. model_config = ConfigDict(populate_by_name=True)
  1371. items: List[BatchStockInItem] = Field(..., min_length=1)
  1372. remark: Optional[str] = None
  1373. stock_in_time: Optional[str] = Field(None, alias="stockInTime")
  1374. class BatchStockOutItem(BaseModel):
  1375. model_config = ConfigDict(populate_by_name=True)
  1376. batch_id: str = Field(..., alias="batchId")
  1377. qty: float = Field(..., gt=0)
  1378. remark: Optional[str] = None
  1379. class BatchStockOutBody(BaseModel):
  1380. model_config = ConfigDict(populate_by_name=True)
  1381. items: List[BatchStockOutItem] = Field(..., min_length=1)
  1382. receiver: Optional[str] = None
  1383. purpose: Optional[str] = None
  1384. remark: Optional[str] = None
  1385. stock_out_time: Optional[str] = Field(None, alias="stockOutTime")
  1386. class BatchDiscardItem(BaseModel):
  1387. model_config = ConfigDict(populate_by_name=True)
  1388. batch_id: str = Field(..., alias="batchId")
  1389. qty: float = Field(..., gt=0)
  1390. usage_unit: Optional[str] = Field(None, alias="usageUnit")
  1391. remark: Optional[str] = None
  1392. class BatchDiscardBody(BaseModel):
  1393. model_config = ConfigDict(populate_by_name=True)
  1394. items: List[BatchDiscardItem] = Field(..., min_length=1)
  1395. discard_reason: str = Field(..., alias="discardReason")
  1396. remark: Optional[str] = None
  1397. discard_time: Optional[str] = Field(None, alias="discardTime")
  1398. class QcMaterialBatchUpdateBody(BaseModel):
  1399. model_config = ConfigDict(populate_by_name=True)
  1400. stock_in_no: Optional[str] = Field(None, alias="stockInNo")
  1401. stock_in_date: Optional[str] = Field(None, alias="stockInDate")
  1402. expire_date: Optional[str] = Field(None, alias="expireDate")
  1403. catalog_no: Optional[str] = Field(None, alias="catalogNo")
  1404. batch_no: Optional[str] = Field(None, alias="batchNo")
  1405. manufacturer: Optional[str] = None
  1406. unit_price: Optional[float] = Field(None, alias="unitPrice")
  1407. amount: Optional[float] = None
  1408. in_qty: Optional[float] = Field(None, alias="inQty")
  1409. remaining_qty: Optional[float] = Field(None, alias="remainingQty")
  1410. remark: Optional[str] = None
  1411. qc_attachment_urls: Optional[str] = Field(None, alias="qcAttachmentUrls")
  1412. material_code: Optional[str] = Field(None, alias="materialCode")
  1413. material_name: Optional[str] = Field(None, alias="materialName")
  1414. spec_model: Optional[str] = Field(None, alias="specModel")
  1415. unit: Optional[str] = None
  1416. warning_qty: Optional[float] = Field(None, alias="warningQty")
  1417. status: Optional[str] = None
  1418. @router.get("/qc-material-batches")
  1419. async def list_qc_material_batches(
  1420. page: int = Query(1, ge=1),
  1421. pageSize: int = Query(10, ge=1, le=100),
  1422. keyword: Optional[str] = None,
  1423. materialId: Optional[str] = None,
  1424. status: Optional[str] = None,
  1425. stockStatus: Optional[str] = None,
  1426. db: Session = Depends(get_db),
  1427. user: dict = Depends(require_menu_code("biz:qcMaterial:list")),
  1428. ):
  1429. try:
  1430. tenant_no = _get_tenant_no(db, user)
  1431. items, total = batch_svc.list_batches(
  1432. db,
  1433. page=page,
  1434. page_size=pageSize,
  1435. keyword=keyword,
  1436. material_id=materialId,
  1437. status=status,
  1438. stock_status=stockStatus,
  1439. tenant_no=tenant_no,
  1440. user_info=user,
  1441. )
  1442. _maybe_strip_qc_material_amount_fields(db, user, items)
  1443. return success_response(_page_payload(items, total, page, pageSize))
  1444. except PermissionError as e:
  1445. return error_response(403, str(e))
  1446. except Exception as e:
  1447. return error_response(400, str(e))
  1448. @router.get("/qc-material-batches/options")
  1449. async def qc_material_batch_options(
  1450. keyword: Optional[str] = None,
  1451. materialId: Optional[str] = None,
  1452. onlyAvailable: bool = Query(True, alias="onlyAvailable"),
  1453. db: Session = Depends(get_db),
  1454. user: dict = Depends(require_menu_code("biz:qcMaterial:list")),
  1455. ):
  1456. try:
  1457. tenant_no = _get_tenant_no(db, user)
  1458. options = batch_svc.batch_options(
  1459. db,
  1460. tenant_no,
  1461. keyword=keyword,
  1462. material_id=materialId,
  1463. only_available=onlyAvailable,
  1464. )
  1465. _maybe_strip_qc_material_amount_fields(db, user, options)
  1466. return success_response(options)
  1467. except Exception as e:
  1468. return error_response(400, str(e))
  1469. @router.get("/qc-material-batches/{batch_id}")
  1470. async def get_qc_material_batch(
  1471. batch_id: str,
  1472. db: Session = Depends(get_db),
  1473. user: dict = Depends(require_menu_code("biz:qcMaterial:list")),
  1474. ):
  1475. try:
  1476. tenant_no = _get_tenant_no(db, user)
  1477. payload = batch_svc.get_batch_detail(db, batch_id, tenant_no=tenant_no)
  1478. _maybe_strip_qc_material_amount_fields(db, user, [payload])
  1479. return success_response(payload)
  1480. except ValueError as e:
  1481. return error_response(400, str(e))
  1482. except Exception as e:
  1483. return error_response(400, str(e))
  1484. @router.put("/qc-material-batches/{batch_id}")
  1485. async def update_qc_material_batch(
  1486. batch_id: str,
  1487. body: QcMaterialBatchUpdateBody,
  1488. db: Session = Depends(get_db),
  1489. user: dict = Depends(require_menu_code("biz:qcMaterial:list")),
  1490. ):
  1491. try:
  1492. tenant_no = _get_tenant_no(db, user)
  1493. user_id = _get_current_user_id(user)
  1494. data = body.model_dump(exclude_none=True)
  1495. _strip_amount_from_write_data(db, user, data)
  1496. obj = batch_svc.update_batch(
  1497. db,
  1498. batch_id,
  1499. tenant_no=tenant_no,
  1500. user_id=user_id,
  1501. **data,
  1502. )
  1503. material = mat_svc.get_material(db, obj.material_id, tenant_no=tenant_no)
  1504. payload = batch_svc._batch_row_to_dict(obj, material)
  1505. _maybe_strip_qc_material_amount_fields(db, user, [payload])
  1506. return success_response(
  1507. payload,
  1508. message="更新成功",
  1509. )
  1510. except ValueError as e:
  1511. return error_response(400, str(e))
  1512. except Exception as e:
  1513. return error_response(400, str(e))
  1514. @router.delete("/qc-material-batches/{batch_id}")
  1515. async def delete_qc_material_batch(
  1516. batch_id: str,
  1517. db: Session = Depends(get_db),
  1518. user: dict = Depends(require_menu_code("biz:qcMaterial:list")),
  1519. ):
  1520. try:
  1521. tenant_no = _get_tenant_no(db, user)
  1522. user_id = _get_current_user_id(user)
  1523. batch_svc.delete_batch(db, batch_id, tenant_no=tenant_no, user_id=user_id)
  1524. return success_response(None, message="删除成功")
  1525. except ValueError as e:
  1526. return error_response(400, str(e))
  1527. except Exception as e:
  1528. return error_response(400, str(e))
  1529. @router.get("/qc-materials")
  1530. async def list_qc_materials(
  1531. page: int = Query(1, ge=1),
  1532. pageSize: int = Query(10, ge=1, le=100),
  1533. keyword: Optional[str] = None,
  1534. status: Optional[str] = None,
  1535. db: Session = Depends(get_db),
  1536. user: dict = Depends(require_menu_code("biz:qcMaterial:list")),
  1537. ):
  1538. try:
  1539. tenant_no = _get_tenant_no(db, user)
  1540. items, total = mat_svc.list_materials(
  1541. db, page=page, page_size=pageSize, keyword=keyword, status=status, tenant_no=tenant_no,
  1542. user_info=user,
  1543. )
  1544. return success_response(_page_payload(items, total, page, pageSize))
  1545. except PermissionError as e:
  1546. return error_response(403, str(e))
  1547. except Exception as e:
  1548. return error_response(400, str(e))
  1549. @router.get("/qc-materials/options")
  1550. async def qc_material_options(
  1551. db: Session = Depends(get_db),
  1552. user: dict = Depends(require_menu_code("biz:qcMaterial:list")),
  1553. ):
  1554. try:
  1555. tenant_no = _get_tenant_no(db, user)
  1556. return success_response(mat_svc.options_list(db, tenant_no=tenant_no))
  1557. except Exception as e:
  1558. return error_response(400, str(e))
  1559. @router.post("/qc-materials")
  1560. async def create_qc_material(
  1561. body: QcMaterialBody,
  1562. db: Session = Depends(get_db),
  1563. user: dict = Depends(require_menu_code("biz:qcMaterial:list")),
  1564. ):
  1565. try:
  1566. tenant_no = _get_tenant_no(db, user)
  1567. user_id = _get_current_user_id(user)
  1568. obj = mat_svc.create_material(
  1569. db,
  1570. material_code=body.material_code,
  1571. material_name=body.material_name,
  1572. spec_model=body.spec_model,
  1573. unit=body.unit,
  1574. warning_qty=Decimal(str(body.warning_qty))
  1575. if body.warning_qty is not None
  1576. else None,
  1577. status=mat_svc._norm_status(body.status),
  1578. remark=body.remark,
  1579. tenant_no=tenant_no,
  1580. user_id=user_id,
  1581. )
  1582. return success_response(mat_svc._row_to_dict(obj), message="创建成功")
  1583. except ValueError as e:
  1584. return error_response(400, str(e))
  1585. except Exception as e:
  1586. return error_response(400, str(e))
  1587. @router.put("/qc-materials/{material_id}")
  1588. async def update_qc_material(
  1589. material_id: str,
  1590. body: QcMaterialUpdateBody,
  1591. db: Session = Depends(get_db),
  1592. user: dict = Depends(require_menu_code("biz:qcMaterial:list")),
  1593. ):
  1594. try:
  1595. tenant_no = _get_tenant_no(db, user)
  1596. user_id = _get_current_user_id(user)
  1597. data = body.model_dump(exclude_none=True)
  1598. if "warning_qty" in data:
  1599. data["warning_qty"] = Decimal(str(data["warning_qty"]))
  1600. if "status" in data:
  1601. data["status"] = mat_svc._norm_status(data["status"])
  1602. obj = mat_svc.update_material(
  1603. db,
  1604. material_id,
  1605. tenant_no=tenant_no,
  1606. user_id=user_id,
  1607. **data,
  1608. )
  1609. return success_response(mat_svc._row_to_dict(obj), message="更新成功")
  1610. except ValueError as e:
  1611. return error_response(400, str(e))
  1612. except Exception as e:
  1613. return error_response(400, str(e))
  1614. @router.delete("/qc-materials/{material_id}")
  1615. async def delete_qc_material(
  1616. material_id: str,
  1617. db: Session = Depends(get_db),
  1618. user: dict = Depends(require_menu_code("biz:qcMaterial:list")),
  1619. ):
  1620. try:
  1621. tenant_no = _get_tenant_no(db, user)
  1622. user_id = _get_current_user_id(user)
  1623. mat_svc.soft_delete_material(db, material_id, tenant_no=tenant_no)
  1624. return success_response(None, message="删除成功")
  1625. except ValueError as e:
  1626. return error_response(400, str(e))
  1627. except Exception as e:
  1628. return error_response(400, str(e))
  1629. @router.post("/qc-materials/batch-stock-in")
  1630. async def batch_stock_in_qc_material(
  1631. body: BatchStockInBody,
  1632. db: Session = Depends(get_db),
  1633. user: dict = Depends(require_menu_code("biz:qcMaterial:list")),
  1634. ):
  1635. try:
  1636. tenant_no = _get_tenant_no(db, user)
  1637. user_id = _get_current_user_id(user)
  1638. operate_time = datetime.now()
  1639. if body.stock_in_time:
  1640. rt = parse_datetime(body.stock_in_time)
  1641. if not rt:
  1642. return error_response(400, "入库时间格式无效")
  1643. operate_time = rt
  1644. items = []
  1645. for x in body.items:
  1646. unit_price, amount = _resolve_stock_in_amounts(
  1647. db, user, x.unit_price, x.amount
  1648. )
  1649. items.append(
  1650. {
  1651. "material_id": x.material_id,
  1652. "materialId": x.material_id,
  1653. "stock_in_no": x.stock_in_no,
  1654. "stockInNo": x.stock_in_no,
  1655. "stock_in_date": x.stock_in_date,
  1656. "stockInDate": x.stock_in_date,
  1657. "expire_date": x.expire_date,
  1658. "expireDate": x.expire_date,
  1659. "catalog_no": x.catalog_no,
  1660. "catalogNo": x.catalog_no,
  1661. "batch_no": x.batch_no,
  1662. "batchNo": x.batch_no,
  1663. "manufacturer": x.manufacturer,
  1664. "unit_price": unit_price,
  1665. "unitPrice": unit_price,
  1666. "amount": amount,
  1667. "qty": x.qty,
  1668. "remark": x.remark,
  1669. }
  1670. )
  1671. count = batch_svc.batch_stock_in(
  1672. db,
  1673. items=items,
  1674. remark=body.remark,
  1675. tenant_no=tenant_no,
  1676. user_id=user_id,
  1677. operate_time=operate_time,
  1678. )
  1679. return success_response({"count": count}, message=f"批量入库成功,共 {count} 项")
  1680. except ValueError as e:
  1681. return error_response(400, str(e))
  1682. except Exception as e:
  1683. return error_response(400, str(e))
  1684. @router.post("/qc-materials/batch-stock-out")
  1685. async def batch_stock_out_qc_material(
  1686. body: BatchStockOutBody,
  1687. db: Session = Depends(get_db),
  1688. user: dict = Depends(require_menu_code("biz:qcMaterial:list")),
  1689. ):
  1690. try:
  1691. tenant_no = _get_tenant_no(db, user)
  1692. user_id = _get_current_user_id(user)
  1693. operate_time = datetime.now()
  1694. if body.stock_out_time:
  1695. rt = parse_datetime(body.stock_out_time)
  1696. if not rt:
  1697. return error_response(400, "出库时间格式无效")
  1698. operate_time = rt
  1699. items = [
  1700. {"batch_id": x.batch_id, "batchId": x.batch_id, "qty": x.qty, "remark": x.remark}
  1701. for x in body.items
  1702. ]
  1703. count = batch_svc.batch_stock_out(
  1704. db,
  1705. items=items,
  1706. receiver=body.receiver,
  1707. purpose=body.purpose,
  1708. remark=body.remark,
  1709. tenant_no=tenant_no,
  1710. user_id=user_id,
  1711. operate_time=operate_time,
  1712. )
  1713. return success_response({"count": count}, message=f"批量出库成功,共 {count} 项")
  1714. except ValueError as e:
  1715. return error_response(400, str(e))
  1716. except Exception as e:
  1717. return error_response(400, str(e))
  1718. @router.post("/qc-materials/batch-discard")
  1719. async def batch_discard_qc_material(
  1720. body: BatchDiscardBody,
  1721. db: Session = Depends(get_db),
  1722. user: dict = Depends(require_menu_code("biz:qcMaterial:list")),
  1723. ):
  1724. try:
  1725. tenant_no = _get_tenant_no(db, user)
  1726. user_id = _get_current_user_id(user)
  1727. operate_time = datetime.now()
  1728. if body.discard_time:
  1729. rt = parse_datetime(body.discard_time)
  1730. if not rt:
  1731. return error_response(400, "废弃时间格式无效")
  1732. operate_time = rt
  1733. items = [
  1734. {
  1735. "batch_id": x.batch_id,
  1736. "batchId": x.batch_id,
  1737. "qty": x.qty,
  1738. "usageUnit": x.usage_unit,
  1739. "usage_unit": x.usage_unit,
  1740. "remark": x.remark,
  1741. }
  1742. for x in body.items
  1743. ]
  1744. count = batch_svc.batch_discard(
  1745. db,
  1746. items=items,
  1747. discard_reason=body.discard_reason,
  1748. remark=body.remark,
  1749. tenant_no=tenant_no,
  1750. user_id=user_id,
  1751. operate_time=operate_time,
  1752. )
  1753. return success_response({"count": count}, message=f"批量废弃成功,共 {count} 项")
  1754. except ValueError as e:
  1755. return error_response(400, str(e))
  1756. except Exception as e:
  1757. return error_response(400, str(e))
  1758. @router.post("/qc-materials/{material_id}/stock-in")
  1759. async def stock_in_qc_material(
  1760. material_id: str,
  1761. body: StockInBody,
  1762. db: Session = Depends(get_db),
  1763. user: dict = Depends(require_menu_code("biz:qcMaterial:list")),
  1764. ):
  1765. try:
  1766. tenant_no = _get_tenant_no(db, user)
  1767. user_id = _get_current_user_id(user)
  1768. operate_time = datetime.now()
  1769. if body.stock_in_time:
  1770. rt = parse_datetime(body.stock_in_time)
  1771. if not rt:
  1772. return error_response(400, "入库时间格式无效")
  1773. operate_time = rt
  1774. from decimal import Decimal
  1775. unit_price, amount = _resolve_stock_in_amounts(
  1776. db, user, body.unit_price, body.amount
  1777. )
  1778. obj = batch_svc.stock_in_one(
  1779. db,
  1780. material_id,
  1781. stock_in_no=body.stock_in_no,
  1782. stock_in_date=body.stock_in_date,
  1783. expire_date=body.expire_date,
  1784. catalog_no=body.catalog_no,
  1785. batch_no=body.batch_no,
  1786. manufacturer=body.manufacturer,
  1787. unit_price=unit_price,
  1788. amount=amount,
  1789. qty=Decimal(str(body.qty)),
  1790. remark=body.remark,
  1791. tenant_no=tenant_no,
  1792. user_id=user_id,
  1793. operate_time=operate_time,
  1794. )
  1795. return success_response(batch_svc._batch_row_to_dict(obj), message="入库成功")
  1796. except ValueError as e:
  1797. return error_response(400, str(e))
  1798. except Exception as e:
  1799. return error_response(400, str(e))
  1800. @router.post("/qc-material-batches/batch-stock-in")
  1801. async def batch_stock_in_qc_material_batches(
  1802. body: BatchStockInBody,
  1803. db: Session = Depends(get_db),
  1804. user: dict = Depends(require_menu_code("biz:qcMaterial:list")),
  1805. ):
  1806. """批量入库(与 /qc-materials/batch-stock-in 等价)。"""
  1807. return await batch_stock_in_qc_material(body, db, user)
  1808. @router.post("/qc-material-batches/batch-stock-out")
  1809. async def batch_stock_out_qc_material_batches(
  1810. body: BatchStockOutBody,
  1811. db: Session = Depends(get_db),
  1812. user: dict = Depends(require_menu_code("biz:qcMaterial:list")),
  1813. ):
  1814. """批量出库(与 /qc-materials/batch-stock-out 等价)。"""
  1815. return await batch_stock_out_qc_material(body, db, user)
  1816. @router.post("/qc-material-batches/batch-discard")
  1817. async def batch_discard_qc_material_batches(
  1818. body: BatchDiscardBody,
  1819. db: Session = Depends(get_db),
  1820. user: dict = Depends(require_menu_code("biz:qcMaterial:list")),
  1821. ):
  1822. """批量废弃(与 /qc-materials/batch-discard 等价)。"""
  1823. return await batch_discard_qc_material(body, db, user)
  1824. # ---------- 物料变动记录 ----------
  1825. @router.get("/qc-material-usages")
  1826. async def list_qc_material_usages(
  1827. page: int = Query(1, ge=1),
  1828. pageSize: int = Query(10, ge=1, le=100),
  1829. materialId: Optional[str] = None,
  1830. changeType: Optional[str] = None,
  1831. startTime: Optional[str] = None,
  1832. endTime: Optional[str] = None,
  1833. keyword: Optional[str] = None,
  1834. stockInNo: Optional[str] = None,
  1835. db: Session = Depends(get_db),
  1836. user: dict = Depends(require_menu_code("biz:qcMaterialUsage:list")),
  1837. ):
  1838. try:
  1839. tenant_no = _get_tenant_no(db, user)
  1840. items, total = mu_svc.list_usages(
  1841. db, tenant_no, page=page, page_size=pageSize,
  1842. material_id=materialId, change_type=changeType,
  1843. start_time=startTime, end_time=endTime,
  1844. keyword=keyword, stock_in_no=stockInNo,
  1845. user_info=user,
  1846. )
  1847. _maybe_strip_qc_material_amount_fields(db, user, items)
  1848. return success_response(_page_payload(items, total, page, pageSize))
  1849. except PermissionError as e:
  1850. return error_response(403, str(e))
  1851. except Exception as e:
  1852. return error_response(400, str(e))
  1853. @router.get("/my-qc-material-usages")
  1854. async def list_my_qc_material_usages(
  1855. page: int = Query(1, ge=1),
  1856. pageSize: int = Query(10, ge=1, le=100),
  1857. materialId: Optional[str] = None,
  1858. changeType: Optional[str] = None,
  1859. startTime: Optional[str] = None,
  1860. endTime: Optional[str] = None,
  1861. keyword: Optional[str] = None,
  1862. stockInNo: Optional[str] = None,
  1863. db: Session = Depends(get_db),
  1864. user: dict = Depends(require_menu_code("biz:myQcMaterialUsage:list")),
  1865. ):
  1866. """当前登录人的物料领用记录(手动出库领用人 / 任务使用填报人)。"""
  1867. try:
  1868. tenant_no = _get_tenant_no(db, user)
  1869. items, total = mu_svc.list_my_usages(
  1870. db,
  1871. tenant_no,
  1872. user_id=_get_current_user_id(user),
  1873. nick_name=(user.get("real_name") or "").strip(),
  1874. page=page,
  1875. page_size=pageSize,
  1876. material_id=materialId,
  1877. change_type=changeType,
  1878. start_time=startTime,
  1879. end_time=endTime,
  1880. keyword=keyword,
  1881. stock_in_no=stockInNo,
  1882. )
  1883. if not user_has_menu_perm(db, user, MY_QC_MATERIAL_USAGE_VIEW_AMOUNT_PERM):
  1884. strip_row_fields(items, "unitPrice", "amount")
  1885. return success_response(_page_payload(items, total, page, pageSize))
  1886. except PermissionError as e:
  1887. return error_response(403, str(e))
  1888. except Exception as e:
  1889. return error_response(400, str(e))
  1890. @router.get("/qc-material-usages/{usage_id}/linked-task-usages")
  1891. async def list_qc_material_linked_task_usages(
  1892. usage_id: str,
  1893. db: Session = Depends(get_db),
  1894. user: dict = Depends(
  1895. require_any_menu_code("biz:qcMaterialUsage:list", "biz:myQcMaterialUsage:list")
  1896. ),
  1897. ):
  1898. """领用记录下关联的质检任务物料消耗明细。"""
  1899. try:
  1900. tenant_no = _get_tenant_no(db, user)
  1901. items = mu_svc.list_linked_task_usages(
  1902. db, usage_id, tenant_no, user_info=user
  1903. )
  1904. if not (
  1905. user_has_menu_perm(db, user, QC_MATERIAL_VIEW_AMOUNT_PERM)
  1906. or user_has_menu_perm(db, user, MY_QC_MATERIAL_USAGE_VIEW_AMOUNT_PERM)
  1907. ):
  1908. strip_row_fields(items, *QC_MATERIAL_AMOUNT_FIELD_NAMES)
  1909. return success_response(items)
  1910. except HTTPException as e:
  1911. detail = e.detail
  1912. msg = detail if isinstance(detail, str) else str(detail)
  1913. return error_response(e.status_code, msg)
  1914. except PermissionError as e:
  1915. return error_response(403, str(e))
  1916. except Exception as e:
  1917. return error_response(400, str(e))
  1918. @router.get("/qc-material-stock-check-requisitions")
  1919. async def list_qc_material_stock_check_requisitions(
  1920. page: int = Query(1, ge=1),
  1921. pageSize: int = Query(50, ge=1, le=200),
  1922. keyword: Optional[str] = None,
  1923. db: Session = Depends(get_db),
  1924. user: dict = Depends(require_menu_code("biz:qcMaterial:list")),
  1925. ):
  1926. """盘点登记:待处理领用记录(未标记已使用完)。"""
  1927. try:
  1928. tenant_no = _get_tenant_no(db, user)
  1929. items, total = mu_svc.list_stock_check_requisitions(
  1930. db,
  1931. tenant_no,
  1932. page=page,
  1933. page_size=pageSize,
  1934. keyword=keyword,
  1935. user_info=user,
  1936. )
  1937. _maybe_strip_qc_material_amount_fields(db, user, items)
  1938. return success_response(_page_payload(items, total, page, pageSize))
  1939. except PermissionError as e:
  1940. return error_response(403, str(e))
  1941. except Exception as e:
  1942. return error_response(400, str(e))
  1943. @router.post("/qc-material-usages/{usage_id}/mark-fully-used")
  1944. async def mark_qc_material_usage_fully_used(
  1945. usage_id: str,
  1946. db: Session = Depends(get_db),
  1947. user: dict = Depends(
  1948. require_any_menu_code("biz:qcMaterial:list", "biz:qcMaterialUsage:list")
  1949. ),
  1950. ):
  1951. """标记领用记录已使用完(盘点登记 / 变动记录)。"""
  1952. try:
  1953. tenant_no = _get_tenant_no(db, user)
  1954. user_id = _get_current_user_id(user)
  1955. mu_svc.mark_requisition_fully_used(
  1956. db,
  1957. usage_id,
  1958. tenant_no=tenant_no,
  1959. user_id=user_id,
  1960. user_info=user,
  1961. )
  1962. return success_response(None, message="已标记为使用完")
  1963. except PermissionError as e:
  1964. return error_response(403, str(e))
  1965. except ValueError as e:
  1966. return error_response(400, str(e))
  1967. except Exception as e:
  1968. return error_response(400, str(e))
  1969. # ---------- 库存盘点 ----------
  1970. class StockCheckCreateBody(BaseModel):
  1971. model_config = ConfigDict(populate_by_name=True)
  1972. title: str
  1973. check_time: Optional[str] = Field(None, alias="checkTime")
  1974. remark: Optional[str] = None
  1975. class StockCheckUnusedLineItem(BaseModel):
  1976. model_config = ConfigDict(populate_by_name=True)
  1977. usage_id: Optional[str] = Field(None, alias="usageId")
  1978. batch_id: Optional[str] = Field(None, alias="batchId")
  1979. material_code: Optional[str] = Field(None, alias="materialCode")
  1980. material_name: str = Field(..., alias="materialName")
  1981. spec_model: Optional[str] = Field(None, alias="specModel")
  1982. unit: Optional[str] = None
  1983. stock_in_no: Optional[str] = Field(None, alias="stockInNo")
  1984. stock_in_date: Optional[str] = Field(None, alias="stockInDate")
  1985. expire_date: Optional[str] = Field(None, alias="expireDate")
  1986. catalog_no: Optional[str] = Field(None, alias="catalogNo")
  1987. batch_no: Optional[str] = Field(None, alias="batchNo")
  1988. manufacturer: Optional[str] = None
  1989. unit_price: Optional[float] = Field(None, alias="unitPrice")
  1990. holder: Optional[str] = None
  1991. unused_qty: float = Field(..., alias="unusedQty", gt=0)
  1992. remark: Optional[str] = None
  1993. class StockCheckUnusedLinesBody(BaseModel):
  1994. model_config = ConfigDict(populate_by_name=True)
  1995. items: List[StockCheckUnusedLineItem] = Field(default_factory=list)
  1996. @router.get("/qc-material-stock-checks")
  1997. async def list_qc_material_stock_checks(
  1998. page: int = Query(1, ge=1),
  1999. pageSize: int = Query(10, ge=1, le=100),
  2000. keyword: Optional[str] = None,
  2001. status: Optional[str] = None,
  2002. startTime: Optional[str] = None,
  2003. endTime: Optional[str] = None,
  2004. db: Session = Depends(get_db),
  2005. user: dict = Depends(require_menu_code("biz:qcMaterial:list")),
  2006. ):
  2007. try:
  2008. tenant_no = _get_tenant_no(db, user)
  2009. items, total = stock_check_svc.list_checks(
  2010. db,
  2011. tenant_no,
  2012. page=page,
  2013. page_size=pageSize,
  2014. keyword=keyword,
  2015. status=status,
  2016. start_time=startTime,
  2017. end_time=endTime,
  2018. user_info=user,
  2019. )
  2020. return success_response(_page_payload(items, total, page, pageSize))
  2021. except PermissionError as e:
  2022. return error_response(403, str(e))
  2023. except Exception as e:
  2024. return error_response(400, str(e))
  2025. @router.post("/qc-material-stock-checks")
  2026. async def create_qc_material_stock_check(
  2027. body: StockCheckCreateBody,
  2028. db: Session = Depends(get_db),
  2029. user: dict = Depends(require_menu_code("biz:qcMaterial:list")),
  2030. ):
  2031. try:
  2032. tenant_no = _get_tenant_no(db, user)
  2033. user_id = _get_current_user_id(user)
  2034. dept_id = user.get("deptId") or user.get("dept_id") or ""
  2035. res = stock_check_svc.create_check(
  2036. db,
  2037. title=body.title,
  2038. tenant_no=tenant_no,
  2039. user_id=user_id,
  2040. dept_id=dept_id,
  2041. check_time=body.check_time,
  2042. remark=body.remark,
  2043. )
  2044. return success_response(res, message="盘点单创建成功")
  2045. except ValueError as e:
  2046. return error_response(400, str(e))
  2047. except Exception as e:
  2048. return error_response(400, str(e))
  2049. @router.get("/qc-material-stock-checks/{check_id}")
  2050. async def get_qc_material_stock_check(
  2051. check_id: str,
  2052. db: Session = Depends(get_db),
  2053. user: dict = Depends(require_menu_code("biz:qcMaterial:list")),
  2054. ):
  2055. try:
  2056. tenant_no = _get_tenant_no(db, user)
  2057. data = stock_check_svc.get_check_detail(db, check_id, tenant_no)
  2058. _maybe_strip_qc_material_stock_check_detail(db, user, data)
  2059. return success_response(data)
  2060. except ValueError as e:
  2061. return error_response(400, str(e))
  2062. except Exception as e:
  2063. return error_response(400, str(e))
  2064. @router.put("/qc-material-stock-checks/{check_id}/unused-lines")
  2065. async def save_qc_material_stock_check_unused_lines(
  2066. check_id: str,
  2067. body: StockCheckUnusedLinesBody,
  2068. db: Session = Depends(get_db),
  2069. user: dict = Depends(require_menu_code("biz:qcMaterial:list")),
  2070. ):
  2071. try:
  2072. tenant_no = _get_tenant_no(db, user)
  2073. user_id = _get_current_user_id(user)
  2074. dept_id = user.get("deptId") or user.get("dept_id") or ""
  2075. count = stock_check_svc.save_unused_lines(
  2076. db,
  2077. check_id,
  2078. items=[x.model_dump(by_alias=False) for x in body.items],
  2079. tenant_no=tenant_no,
  2080. user_id=user_id,
  2081. dept_id=dept_id,
  2082. )
  2083. return success_response({"count": count}, message="登记保存成功")
  2084. except ValueError as e:
  2085. return error_response(400, str(e))
  2086. except Exception as e:
  2087. return error_response(400, str(e))
  2088. @router.post("/qc-material-stock-checks/{check_id}/complete")
  2089. async def complete_qc_material_stock_check(
  2090. check_id: str,
  2091. db: Session = Depends(get_db),
  2092. user: dict = Depends(require_menu_code("biz:qcMaterial:list")),
  2093. ):
  2094. try:
  2095. tenant_no = _get_tenant_no(db, user)
  2096. user_id = _get_current_user_id(user)
  2097. stock_check_svc.complete_check(db, check_id, tenant_no=tenant_no, user_id=user_id)
  2098. return success_response(None, message="盘点已完成")
  2099. except ValueError as e:
  2100. return error_response(400, str(e))
  2101. except Exception as e:
  2102. return error_response(400, str(e))
  2103. @router.post("/qc-material-stock-checks/{check_id}/cancel")
  2104. async def cancel_qc_material_stock_check(
  2105. check_id: str,
  2106. db: Session = Depends(get_db),
  2107. user: dict = Depends(require_menu_code("biz:qcMaterial:list")),
  2108. ):
  2109. try:
  2110. tenant_no = _get_tenant_no(db, user)
  2111. user_id = _get_current_user_id(user)
  2112. stock_check_svc.cancel_check(db, check_id, tenant_no=tenant_no, user_id=user_id)
  2113. return success_response(None, message="盘点已作废")
  2114. except ValueError as e:
  2115. return error_response(400, str(e))
  2116. except Exception as e:
  2117. return error_response(400, str(e))
  2118. # ---------- 质检物料金额查看授权 ----------
  2119. class QcMaterialAmountAuthGrantBody(BaseModel):
  2120. model_config = ConfigDict(populate_by_name=True)
  2121. user_id: str = Field(..., alias="userId")
  2122. class QcMaterialAmountAuthBatchBody(BaseModel):
  2123. model_config = ConfigDict(populate_by_name=True)
  2124. user_ids: List[str] = Field(..., alias="userIds", min_length=1)
  2125. @router.get("/qc-material-amount-auth/users")
  2126. async def list_qc_material_amount_auth_users(
  2127. page: int = Query(1, ge=1),
  2128. pageSize: int = Query(10, ge=1, le=100),
  2129. keyword: Optional[str] = None,
  2130. db: Session = Depends(get_db),
  2131. user: dict = Depends(require_menu_code(QC_MATERIAL_AMOUNT_AUTH_LIST_PERM)),
  2132. ):
  2133. """已授权「质检物料金额查看」角色的用户列表。"""
  2134. try:
  2135. tenant_no = _get_tenant_no(db, user)
  2136. items, total = amount_auth_svc.list_authorized_users(
  2137. db,
  2138. tenant_no=tenant_no,
  2139. page=page,
  2140. page_size=pageSize,
  2141. keyword=keyword,
  2142. )
  2143. return success_response(_page_payload(items, total, page, pageSize))
  2144. except Exception as e:
  2145. return error_response(400, str(e))
  2146. @router.post("/qc-material-amount-auth/users")
  2147. async def grant_qc_material_amount_auth(
  2148. body: QcMaterialAmountAuthGrantBody,
  2149. db: Session = Depends(get_db),
  2150. user: dict = Depends(require_menu_code(QC_MATERIAL_AMOUNT_AUTH_LIST_PERM)),
  2151. ):
  2152. """为用户绑定「质检物料金额查看」专用角色。"""
  2153. try:
  2154. tenant_no = _get_tenant_no(db, user)
  2155. operator_id = _get_current_user_id(user)
  2156. created = amount_auth_svc.grant_amount_view_role(
  2157. db,
  2158. tenant_no=tenant_no,
  2159. user_id=body.user_id.strip(),
  2160. operator_id=operator_id,
  2161. )
  2162. msg = "授权成功" if created else "该用户已授权"
  2163. return success_response({"created": created}, message=msg)
  2164. except ValueError as e:
  2165. return error_response(400, str(e))
  2166. except Exception as e:
  2167. return error_response(400, str(e))
  2168. @router.delete("/qc-material-amount-auth/users/{user_id}")
  2169. async def revoke_qc_material_amount_auth(
  2170. user_id: str,
  2171. db: Session = Depends(get_db),
  2172. user: dict = Depends(require_menu_code(QC_MATERIAL_AMOUNT_AUTH_LIST_PERM)),
  2173. ):
  2174. """解除用户的「质检物料金额查看」专用角色。"""
  2175. try:
  2176. tenant_no = _get_tenant_no(db, user)
  2177. operator_id = _get_current_user_id(user)
  2178. removed = amount_auth_svc.revoke_amount_view_role(
  2179. db,
  2180. tenant_no=tenant_no,
  2181. user_id=user_id.strip(),
  2182. operator_id=operator_id,
  2183. )
  2184. if not removed:
  2185. return error_response(400, "该用户未授权或已解除")
  2186. return success_response(None, message="已解除授权")
  2187. except ValueError as e:
  2188. return error_response(400, str(e))
  2189. except Exception as e:
  2190. return error_response(400, str(e))
  2191. @router.post("/qc-material-amount-auth/users/batch-revoke")
  2192. async def batch_revoke_qc_material_amount_auth(
  2193. body: QcMaterialAmountAuthBatchBody,
  2194. db: Session = Depends(get_db),
  2195. user: dict = Depends(require_menu_code(QC_MATERIAL_AMOUNT_AUTH_LIST_PERM)),
  2196. ):
  2197. """批量解除「质检物料金额查看」授权。"""
  2198. try:
  2199. tenant_no = _get_tenant_no(db, user)
  2200. operator_id = _get_current_user_id(user)
  2201. count = 0
  2202. for uid in body.user_ids:
  2203. uid = (uid or "").strip()
  2204. if not uid:
  2205. continue
  2206. if amount_auth_svc.revoke_amount_view_role(
  2207. db,
  2208. tenant_no=tenant_no,
  2209. user_id=uid,
  2210. operator_id=operator_id,
  2211. ):
  2212. count += 1
  2213. return success_response({"count": count}, message=f"已解除 {count} 项授权")
  2214. except ValueError as e:
  2215. return error_response(400, str(e))
  2216. except Exception as e:
  2217. return error_response(400, str(e))