reimburse.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795
  1. import io
  2. from datetime import date as date_cls
  3. from typing import Any, List, Optional
  4. from urllib.parse import quote
  5. from fastapi import APIRouter, Depends, File, HTTPException, Query, Request, UploadFile, status
  6. from fastapi.responses import StreamingResponse
  7. from sqlalchemy import or_
  8. from sqlalchemy.orm import Session
  9. from app.api.bx.export_common import (
  10. EXPORT_MAX_ROWS,
  11. ExportColumn,
  12. ExportValidationError,
  13. BxApplyListExportBody,
  14. dump_export_row,
  15. respond_xlsx,
  16. )
  17. from app.core.bx_auth import BxUserContext, get_bx_current_user
  18. from app.core.database import get_db
  19. from app.core.tenant_context import get_tenant_no
  20. from app.models.bx_models import BxReimburseApply, BxWorkflowDef
  21. from app.schemas.bx.common import ApiResponse, PagedData
  22. from app.schemas.bx.reimburse import (
  23. ReimburseApplyCreate,
  24. ReimburseApplyOut,
  25. ReimburseApplyUpdate,
  26. ReimburseApprovalCreate,
  27. ReimburseApprovalOut,
  28. ReimburseApproverPendingStatsOut,
  29. ReimburseMyStatsOut,
  30. ReimburseSubmitBody,
  31. )
  32. from app.services.bx.expense_item import ExpenseItemService
  33. from app.services.bx.list_sort import order_reimburse, parse_sort_params
  34. from app.services.bx.reimburse import ReimburseService
  35. from app.services.bx.reimburse_import import (
  36. build_applicant_label,
  37. build_import_template_bytes,
  38. import_reimburse_workbook,
  39. load_applicant_options,
  40. load_expense_nodes_flat,
  41. )
  42. from app.services.bx.reimburse_list_filters import build_reimburse_column_filters
  43. from app.utils.bx_codegen import generate_apply_code, generate_title, parse_optional_date
  44. router = APIRouter(prefix="/reimburses", tags=["报销管理"])
  45. def _tenant(db: Session, user: BxUserContext) -> str:
  46. return get_tenant_no(db, user.to_tenant_user_dict())
  47. def _reimburse_order(params: dict):
  48. sf, so = parse_sort_params(params)
  49. return order_reimburse(sf, so)
  50. REIMBURSE_EXPORT_COLUMNS = [
  51. ExportColumn(title="申请单号", field="applyCode"),
  52. ExportColumn(title="申请时间", field="applyTime"),
  53. ExportColumn(title="申请人", field="applicantName"),
  54. ExportColumn(title="报销主题", field="title"),
  55. ExportColumn(title="费用科目", field="expenseName"),
  56. ExportColumn(title="金额(元)", field="amount"),
  57. ExportColumn(title="状态", field="status"),
  58. ExportColumn(title="当前节点", field="currentNode"),
  59. ]
  60. def _merge_query(request: Request, **known) -> dict:
  61. out = {k: v for k, v in known.items() if v is not None and v != ""}
  62. for k, v in request.query_params.multi_items():
  63. if k in ("page", "pageSize"):
  64. continue
  65. if k not in out and v not in (None, ""):
  66. out[k] = v
  67. return out
  68. def _param_get(params: dict, *keys: str) -> Any:
  69. for key in keys:
  70. if key in params and params[key] not in (None, ""):
  71. return params[key]
  72. return None
  73. def _filters_from_params(params: dict, *, db: Session, tenant_no: str = "") -> list:
  74. ids = _param_get(params, "ids")
  75. if isinstance(ids, str):
  76. ids = [s.strip() for s in ids.split(",") if s.strip()]
  77. return build_reimburse_column_filters(
  78. db=db,
  79. tenant_no=tenant_no,
  80. keyword=str(_param_get(params, "keyword") or ""),
  81. status=_param_get(params, "status"),
  82. status_in=_param_get(params, "statusIn", "status_in"),
  83. apply_code=_param_get(params, "applyCode", "apply_code"),
  84. title=_param_get(params, "title"),
  85. expense_name=_param_get(params, "expenseName", "expense_name"),
  86. expense_id=_param_get(params, "expenseId", "expense_id"),
  87. applicant_id=_param_get(params, "applicantId", "applicant_id"),
  88. applicant_name=_param_get(params, "applicantName", "applicant_name"),
  89. current_node=_param_get(params, "currentNode", "current_node"),
  90. amount_op=_param_get(params, "amountOp", "amount_op"),
  91. amount=_param_get(params, "amount"),
  92. amount_min=_param_get(params, "amountMin", "amount_min"),
  93. amount_max=_param_get(params, "amountMax", "amount_max"),
  94. apply_date=_param_get(params, "applyDate", "apply_date"),
  95. apply_date_from=_param_get(params, "applyDateFrom", "apply_date_from"),
  96. apply_date_to=_param_get(params, "applyDateTo", "apply_date_to"),
  97. ids=ids if isinstance(ids, list) else None,
  98. )
  99. def _body_to_params(body: BxApplyListExportBody) -> dict:
  100. data = body.model_dump(by_alias=True, exclude_none=True)
  101. extra = getattr(body, "model_extra", None) or {}
  102. for key, value in extra.items():
  103. if key not in data and value not in (None, ""):
  104. data[key] = value
  105. return data
  106. def _reimburse_list_filters(body: BxApplyListExportBody, db: Session, tenant_no: str) -> list:
  107. return _filters_from_params(_body_to_params(body), db=db, tenant_no=tenant_no)
  108. def _export_reimburse_rows(db: Session, tenant_no: str, rows) -> list:
  109. out_rows = ReimburseService.out_rows_with_attachment_counts(db, tenant_no, list(rows))
  110. return [dump_export_row(r) for r in out_rows]
  111. def _build_details_data(
  112. db: Session,
  113. tenant_no: str,
  114. body_details,
  115. *,
  116. user: BxUserContext,
  117. ) -> List[dict]:
  118. details_data: List[dict] = []
  119. for d in body_details:
  120. item = ExpenseItemService.get_by_id(
  121. db, d.expense_item_id, tenant_no, user=user, skip_scope=True
  122. )
  123. if not item:
  124. raise HTTPException(
  125. status_code=status.HTTP_400_BAD_REQUEST,
  126. detail=f"费用项目 {d.expense_item_id} 不存在",
  127. )
  128. try:
  129. occur_date = parse_optional_date(d.occur_date)
  130. except ValueError:
  131. raise HTTPException(
  132. status_code=status.HTTP_400_BAD_REQUEST,
  133. detail="发生时间格式无效,请使用 YYYY-MM-DD",
  134. )
  135. details_data.append(
  136. {
  137. "expense_id": d.expense_item_id,
  138. "expense_name": item.item_name,
  139. "amount": d.amount,
  140. "remark": d.remark,
  141. "occur_date": occur_date,
  142. }
  143. )
  144. return details_data
  145. @router.get("/generate-title", response_model=ApiResponse[str])
  146. def get_generated_title(
  147. reimburseDate: Optional[str] = None,
  148. excludeApplyId: Optional[str] = None,
  149. applicantId: Optional[str] = None,
  150. db: Session = Depends(get_db),
  151. user: BxUserContext = Depends(get_bx_current_user),
  152. ):
  153. tenant_no = _tenant(db, user)
  154. exclude_id = str(excludeApplyId).strip() if excludeApplyId else None
  155. _, applicant_name = ReimburseService.resolve_applicant(
  156. db, user, applicantId, tenant_no=tenant_no
  157. )
  158. title = generate_title(db, applicant_name, tenant_no, reimburseDate, exclude_id)
  159. return ApiResponse(data=title)
  160. @router.get("/import-template")
  161. def download_reimburse_import_template(
  162. db: Session = Depends(get_db),
  163. user: BxUserContext = Depends(get_bx_current_user),
  164. ):
  165. tenant_no = _tenant(db, user)
  166. nodes = load_expense_nodes_flat(db, tenant_no)
  167. applicants = load_applicant_options(db, user=user, tenant_no=tenant_no)
  168. me = next((a for a in applicants if a["id"] == user.id), None)
  169. if me:
  170. cur_label = build_applicant_label(me["nick_name"], me["user_no"], me["id"])
  171. else:
  172. cur_label = build_applicant_label(user.name or "", "", user.id)
  173. applicants = [
  174. {"id": user.id, "nick_name": user.name or "", "user_no": ""}
  175. ] + applicants
  176. raw = build_import_template_bytes(
  177. expense_nodes=nodes,
  178. applicants=applicants,
  179. current_applicant_label=cur_label,
  180. today=date_cls.today(),
  181. )
  182. filename = quote("报销申请导入模板.xlsx")
  183. return StreamingResponse(
  184. io.BytesIO(raw),
  185. media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  186. headers={
  187. "Content-Disposition": f"attachment; filename={filename}; filename*=UTF-8''{filename}"
  188. },
  189. )
  190. @router.post("/import", response_model=ApiResponse[dict])
  191. def import_reimburses(
  192. file: UploadFile = File(...),
  193. db: Session = Depends(get_db),
  194. user: BxUserContext = Depends(get_bx_current_user),
  195. ):
  196. content = file.file.read()
  197. if not content:
  198. raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="文件为空")
  199. try:
  200. result = import_reimburse_workbook(db, file_bytes=content, user=user)
  201. except ValueError as exc:
  202. raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)) from exc
  203. return ApiResponse(data=result)
  204. @router.get("/", response_model=ApiResponse[PagedData[ReimburseApplyOut]])
  205. def list_reimburses(
  206. request: Request,
  207. page: int = 1,
  208. pageSize: int = Query(10, ge=1, le=500),
  209. status: Optional[str] = None,
  210. keyword: str = "",
  211. expense_id: Optional[str] = None,
  212. expenseName: Optional[str] = None,
  213. applicantId: Optional[str] = None,
  214. applyDate: Optional[str] = None,
  215. applyDateFrom: Optional[str] = None,
  216. applyDateTo: Optional[str] = None,
  217. db: Session = Depends(get_db),
  218. user: BxUserContext = Depends(get_bx_current_user),
  219. ):
  220. tenant_no = _tenant(db, user)
  221. params = _merge_query(
  222. request,
  223. status=status,
  224. keyword=keyword or None,
  225. expenseId=expense_id,
  226. expenseName=expenseName,
  227. applicantId=applicantId,
  228. applyDate=applyDate,
  229. applyDateFrom=applyDateFrom,
  230. applyDateTo=applyDateTo,
  231. )
  232. filters = _filters_from_params(params, db=db, tenant_no=tenant_no)
  233. rows, total = ReimburseService.get_paged(
  234. db, tenant_no, page=page, page_size=pageSize, filters=filters, user=user, order_by=_reimburse_order(params)
  235. )
  236. out_rows = ReimburseService.out_rows_with_attachment_counts(db, tenant_no, list(rows))
  237. return ApiResponse(data=PagedData(rows=out_rows, total=total, page=page, page_size=pageSize))
  238. @router.get("/my", response_model=ApiResponse[PagedData[ReimburseApplyOut]])
  239. def my_reimburses(
  240. request: Request,
  241. page: int = 1,
  242. pageSize: int = Query(10, ge=1, le=500),
  243. status: Optional[str] = None,
  244. keyword: str = "",
  245. expenseName: Optional[str] = None,
  246. applyCode: Optional[str] = None,
  247. title: Optional[str] = None,
  248. currentNode: Optional[str] = None,
  249. statusIn: Optional[str] = None,
  250. amountOp: Optional[str] = None,
  251. amount: Optional[str] = None,
  252. amountMin: Optional[str] = None,
  253. amountMax: Optional[str] = None,
  254. applyDate: Optional[str] = None,
  255. applyDateFrom: Optional[str] = None,
  256. applyDateTo: Optional[str] = None,
  257. db: Session = Depends(get_db),
  258. user: BxUserContext = Depends(get_bx_current_user),
  259. ):
  260. tenant_no = _tenant(db, user)
  261. params = _merge_query(
  262. request,
  263. status=status,
  264. keyword=keyword or None,
  265. expenseName=expenseName,
  266. applyCode=applyCode,
  267. title=title,
  268. currentNode=currentNode,
  269. statusIn=statusIn,
  270. amountOp=amountOp,
  271. amount=amount,
  272. amountMin=amountMin,
  273. amountMax=amountMax,
  274. applyDate=applyDate,
  275. applyDateFrom=applyDateFrom,
  276. applyDateTo=applyDateTo,
  277. )
  278. filters = [
  279. or_(
  280. BxReimburseApply.applicant_id == user.id,
  281. BxReimburseApply.create_by == user.id,
  282. )
  283. ]
  284. filters.extend(_filters_from_params(params, db=db, tenant_no=tenant_no))
  285. rows, total = ReimburseService.get_paged(
  286. db, tenant_no, page=page, page_size=pageSize, filters=filters, user=user, order_by=_reimburse_order(params)
  287. )
  288. out_rows = ReimburseService.out_rows_with_attachment_counts(db, tenant_no, list(rows))
  289. return ApiResponse(data=PagedData(rows=out_rows, total=total, page=page, page_size=pageSize))
  290. @router.get("/my/stats", response_model=ApiResponse[ReimburseMyStatsOut])
  291. def my_reimburse_stats(
  292. db: Session = Depends(get_db),
  293. user: BxUserContext = Depends(get_bx_current_user),
  294. ):
  295. tenant_no = _tenant(db, user)
  296. data = ReimburseService.my_apply_stats(db, user, tenant_no)
  297. return ApiResponse(data=ReimburseMyStatsOut.model_validate(data))
  298. @router.get("/stats/status-counts", response_model=ApiResponse[dict])
  299. def reimburse_status_counts(
  300. db: Session = Depends(get_db),
  301. user: BxUserContext = Depends(get_bx_current_user),
  302. ):
  303. tenant_no = _tenant(db, user)
  304. return ApiResponse(data=ReimburseService.global_status_counts(db, tenant_no, user=user))
  305. @router.get("/pending-approval", response_model=ApiResponse[PagedData[ReimburseApplyOut]])
  306. def pending_approval(
  307. request: Request,
  308. page: int = 1,
  309. pageSize: int = Query(10, ge=1, le=500),
  310. keyword: str = "",
  311. applicantId: Optional[str] = None,
  312. expenseName: Optional[str] = None,
  313. applyDate: Optional[str] = None,
  314. applyDateFrom: Optional[str] = None,
  315. applyDateTo: Optional[str] = None,
  316. db: Session = Depends(get_db),
  317. user: BxUserContext = Depends(get_bx_current_user),
  318. ):
  319. tenant_no = _tenant(db, user)
  320. params = _merge_query(
  321. request,
  322. keyword=keyword or None,
  323. applicantId=applicantId,
  324. expenseName=expenseName,
  325. applyDate=applyDate,
  326. applyDateFrom=applyDateFrom,
  327. applyDateTo=applyDateTo,
  328. )
  329. # Tab 语义固定 pending;不把 status 列参传入 builder
  330. params.pop("status", None)
  331. params.pop("statusIn", None)
  332. params.pop("status_in", None)
  333. extra_filters = _filters_from_params(params, db=db, tenant_no=tenant_no)
  334. rows, total = ReimburseService.pending_approval(
  335. db,
  336. user,
  337. tenant_no,
  338. page=page,
  339. page_size=pageSize,
  340. extra_filters=extra_filters,
  341. order_by=_reimburse_order(params),
  342. )
  343. out_rows = ReimburseService.out_rows_with_attachment_counts(db, tenant_no, list(rows))
  344. return ApiResponse(data=PagedData(rows=out_rows, total=total, page=page, page_size=pageSize))
  345. @router.get("/pending-approval/stats", response_model=ApiResponse[ReimburseApproverPendingStatsOut])
  346. def pending_approval_stats(
  347. db: Session = Depends(get_db),
  348. user: BxUserContext = Depends(get_bx_current_user),
  349. ):
  350. tenant_no = _tenant(db, user)
  351. data = ReimburseService.pending_approval_stats(db, user, tenant_no)
  352. return ApiResponse(data=ReimburseApproverPendingStatsOut.model_validate(data))
  353. @router.get("/approved-by-me", response_model=ApiResponse[PagedData[ReimburseApplyOut]])
  354. def approved_by_me(
  355. request: Request,
  356. page: int = 1,
  357. pageSize: int = Query(10, ge=1, le=500),
  358. keyword: str = "",
  359. applicantId: Optional[str] = None,
  360. expenseName: Optional[str] = None,
  361. applyDate: Optional[str] = None,
  362. applyDateFrom: Optional[str] = None,
  363. applyDateTo: Optional[str] = None,
  364. db: Session = Depends(get_db),
  365. user: BxUserContext = Depends(get_bx_current_user),
  366. ):
  367. tenant_no = _tenant(db, user)
  368. params = _merge_query(
  369. request,
  370. keyword=keyword or None,
  371. applicantId=applicantId,
  372. expenseName=expenseName,
  373. applyDate=applyDate,
  374. applyDateFrom=applyDateFrom,
  375. applyDateTo=applyDateTo,
  376. )
  377. extra_filters = _filters_from_params(params, db=db, tenant_no=tenant_no)
  378. rows, total = ReimburseService.approved_by_me(
  379. db,
  380. user,
  381. tenant_no,
  382. page=page,
  383. page_size=pageSize,
  384. extra_filters=extra_filters,
  385. order_by=_reimburse_order(params),
  386. )
  387. out_rows = ReimburseService.out_rows_with_attachment_counts(db, tenant_no, list(rows))
  388. return ApiResponse(data=PagedData(rows=out_rows, total=total, page=page, page_size=pageSize))
  389. @router.post("/export")
  390. def export_reimburses(
  391. body: BxApplyListExportBody,
  392. db: Session = Depends(get_db),
  393. user: BxUserContext = Depends(get_bx_current_user),
  394. ):
  395. try:
  396. tenant_no = _tenant(db, user)
  397. params = _body_to_params(body)
  398. filters = _filters_from_params(params, db=db, tenant_no=tenant_no)
  399. rows, _ = ReimburseService.get_paged(
  400. db,
  401. tenant_no,
  402. page=1,
  403. page_size=EXPORT_MAX_ROWS,
  404. filters=filters,
  405. user=user,
  406. order_by=_reimburse_order(params),
  407. )
  408. return respond_xlsx(
  409. db,
  410. tenant_no=tenant_no,
  411. sheet_title="报销申请",
  412. columns=REIMBURSE_EXPORT_COLUMNS,
  413. rows=_export_reimburse_rows(db, tenant_no, rows),
  414. filename_stem="报销申请",
  415. requested_columns=body.columns,
  416. )
  417. except ExportValidationError as e:
  418. raise HTTPException(status_code=400, detail=str(e)) from e
  419. @router.post("/my/export")
  420. def export_my_reimburses(
  421. body: BxApplyListExportBody,
  422. db: Session = Depends(get_db),
  423. user: BxUserContext = Depends(get_bx_current_user),
  424. ):
  425. try:
  426. tenant_no = _tenant(db, user)
  427. params = _body_to_params(body)
  428. filters = [
  429. or_(
  430. BxReimburseApply.applicant_id == user.id,
  431. BxReimburseApply.create_by == user.id,
  432. )
  433. ]
  434. filters.extend(_filters_from_params(params, db=db, tenant_no=tenant_no))
  435. rows, _ = ReimburseService.get_paged(
  436. db,
  437. tenant_no,
  438. page=1,
  439. page_size=EXPORT_MAX_ROWS,
  440. filters=filters,
  441. user=user,
  442. order_by=_reimburse_order(params),
  443. )
  444. return respond_xlsx(
  445. db,
  446. tenant_no=tenant_no,
  447. sheet_title="我的报销",
  448. columns=REIMBURSE_EXPORT_COLUMNS,
  449. rows=_export_reimburse_rows(db, tenant_no, rows),
  450. filename_stem="我的报销申请",
  451. requested_columns=body.columns,
  452. )
  453. except ExportValidationError as e:
  454. raise HTTPException(status_code=400, detail=str(e)) from e
  455. @router.post("/pending-approval/export")
  456. def export_pending_approval_reimburses(
  457. body: BxApplyListExportBody,
  458. db: Session = Depends(get_db),
  459. user: BxUserContext = Depends(get_bx_current_user),
  460. ):
  461. try:
  462. tenant_no = _tenant(db, user)
  463. params = _body_to_params(body)
  464. params.pop("status", None)
  465. params.pop("statusIn", None)
  466. params.pop("status_in", None)
  467. extra_filters = _filters_from_params(params, db=db, tenant_no=tenant_no)
  468. rows, _ = ReimburseService.pending_approval(
  469. db,
  470. user,
  471. tenant_no,
  472. page=1,
  473. page_size=EXPORT_MAX_ROWS,
  474. extra_filters=extra_filters,
  475. order_by=_reimburse_order(params),
  476. )
  477. return respond_xlsx(
  478. db,
  479. tenant_no=tenant_no,
  480. sheet_title="报销待审批",
  481. columns=REIMBURSE_EXPORT_COLUMNS,
  482. rows=_export_reimburse_rows(db, tenant_no, rows),
  483. filename_stem="报销待审批",
  484. requested_columns=body.columns,
  485. )
  486. except ExportValidationError as e:
  487. raise HTTPException(status_code=400, detail=str(e)) from e
  488. @router.post("/approved-by-me/export")
  489. def export_approved_by_me_reimburses(
  490. body: BxApplyListExportBody,
  491. db: Session = Depends(get_db),
  492. user: BxUserContext = Depends(get_bx_current_user),
  493. ):
  494. try:
  495. tenant_no = _tenant(db, user)
  496. params = _body_to_params(body)
  497. extra_filters = _filters_from_params(params, db=db, tenant_no=tenant_no)
  498. rows, _ = ReimburseService.approved_by_me(
  499. db,
  500. user,
  501. tenant_no,
  502. page=1,
  503. page_size=EXPORT_MAX_ROWS,
  504. extra_filters=extra_filters,
  505. order_by=_reimburse_order(params),
  506. )
  507. return respond_xlsx(
  508. db,
  509. tenant_no=tenant_no,
  510. sheet_title="报销已审批",
  511. columns=REIMBURSE_EXPORT_COLUMNS,
  512. rows=_export_reimburse_rows(db, tenant_no, rows),
  513. filename_stem="报销已审批",
  514. requested_columns=body.columns,
  515. )
  516. except ExportValidationError as e:
  517. raise HTTPException(status_code=400, detail=str(e)) from e
  518. @router.get("/{reimburse_id}", response_model=ApiResponse[ReimburseApplyOut])
  519. def get_reimburse(
  520. reimburse_id: str,
  521. db: Session = Depends(get_db),
  522. user: BxUserContext = Depends(get_bx_current_user),
  523. ):
  524. tenant_no = _tenant(db, user)
  525. reimburse = ReimburseService.get_by_id(db, reimburse_id, tenant_no, user=user)
  526. if not reimburse:
  527. raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="报销单不存在")
  528. out = ReimburseService.build_apply_out_with_details(db, tenant_no, reimburse)
  529. return ApiResponse(data=out)
  530. @router.get("/{reimburse_id}/approvals", response_model=ApiResponse[List[ReimburseApprovalOut]])
  531. def get_approvals(
  532. reimburse_id: str,
  533. db: Session = Depends(get_db),
  534. user: BxUserContext = Depends(get_bx_current_user),
  535. ):
  536. tenant_no = _tenant(db, user)
  537. if not ReimburseService.get_by_id(db, reimburse_id, tenant_no, user=user):
  538. raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="报销单不存在")
  539. approvals = ReimburseService.get_approvals(db, reimburse_id, tenant_no, user=user)
  540. return ApiResponse(data=[ReimburseApprovalOut.model_validate(a) for a in approvals])
  541. @router.get("/{reimburse_id}/approval-history", response_model=ApiResponse[List[ReimburseApprovalOut]])
  542. def get_approval_history(
  543. reimburse_id: str,
  544. db: Session = Depends(get_db),
  545. user: BxUserContext = Depends(get_bx_current_user),
  546. ):
  547. tenant_no = _tenant(db, user)
  548. if not ReimburseService.get_by_id(db, reimburse_id, tenant_no, user=user):
  549. raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="报销单不存在")
  550. history = ReimburseService.get_approval_history(db, reimburse_id, tenant_no, user=user)
  551. return ApiResponse(data=[ReimburseApprovalOut.model_validate(a) for a in history])
  552. @router.post("/", response_model=ApiResponse[ReimburseApplyOut])
  553. def create_reimburse(
  554. body: ReimburseApplyCreate,
  555. db: Session = Depends(get_db),
  556. user: BxUserContext = Depends(get_bx_current_user),
  557. ):
  558. tenant_no = _tenant(db, user)
  559. details_data = _build_details_data(db, tenant_no, body.details, user=user)
  560. data = {
  561. "apply_code": generate_apply_code(db, "BX", tenant_no),
  562. "status": "draft",
  563. "remark": body.remark,
  564. "reimburse_date": body.reimburse_date,
  565. }
  566. if body.title:
  567. data["title"] = body.title
  568. wf = (
  569. db.query(BxWorkflowDef)
  570. .filter(
  571. BxWorkflowDef.biz_type == "reimburse",
  572. BxWorkflowDef.tenant_no == tenant_no,
  573. BxWorkflowDef.del_flag == 0,
  574. )
  575. .first()
  576. )
  577. if wf:
  578. data["wf_id"] = wf.id
  579. applicant_id, applicant_name = ReimburseService.resolve_applicant(
  580. db, user, body.applicant_id, tenant_no=tenant_no
  581. )
  582. reimburse = ReimburseService.create_with_details(
  583. db,
  584. data,
  585. details_data,
  586. user=user,
  587. applicant_id=applicant_id,
  588. applicant_name=applicant_name,
  589. )
  590. if body.invoice_links is not None or body.invoice_ids is not None:
  591. ReimburseService.sync_reimburse_invoices(
  592. db,
  593. reimburse.id,
  594. body.invoice_ids,
  595. tenant_no,
  596. user,
  597. applicant_id=applicant_id,
  598. invoice_links=body.invoice_links,
  599. )
  600. db.commit()
  601. db.refresh(reimburse)
  602. out = ReimburseService.build_apply_out_with_details(db, tenant_no, reimburse)
  603. return ApiResponse(data=out)
  604. @router.put("/{reimburse_id}", response_model=ApiResponse[ReimburseApplyOut])
  605. def update_reimburse(
  606. reimburse_id: str,
  607. body: ReimburseApplyUpdate,
  608. db: Session = Depends(get_db),
  609. user: BxUserContext = Depends(get_bx_current_user),
  610. ):
  611. tenant_no = _tenant(db, user)
  612. details_data = None
  613. if body.details is not None:
  614. details_data = _build_details_data(db, tenant_no, body.details, user=user)
  615. main_data = {}
  616. if body.remark is not None:
  617. main_data["remark"] = body.remark
  618. if body.reimburse_date is not None:
  619. main_data["reimburse_date"] = body.reimburse_date
  620. if body.title is not None:
  621. main_data["title"] = body.title
  622. if body.applicant_id is not None:
  623. applicant_id, applicant_name = ReimburseService.resolve_applicant(
  624. db, user, body.applicant_id, tenant_no=tenant_no
  625. )
  626. main_data["applicant_id"] = applicant_id
  627. main_data["applicant_name"] = applicant_name
  628. reimburse = ReimburseService.update_with_details(
  629. db, reimburse_id, main_data, details_data, user=user
  630. )
  631. if not reimburse:
  632. raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="报销单不存在")
  633. if body.invoice_links is not None or body.invoice_ids is not None:
  634. ReimburseService.sync_reimburse_invoices(
  635. db,
  636. reimburse_id,
  637. body.invoice_ids,
  638. tenant_no,
  639. user,
  640. applicant_id=reimburse.applicant_id,
  641. invoice_links=body.invoice_links,
  642. )
  643. db.commit()
  644. db.refresh(reimburse)
  645. out = ReimburseService.build_apply_out_with_details(db, tenant_no, reimburse)
  646. return ApiResponse(data=out)
  647. @router.post("/{reimburse_id}/submit", response_model=ApiResponse[ReimburseApplyOut])
  648. def submit_reimburse(
  649. reimburse_id: str,
  650. body: ReimburseSubmitBody = ReimburseSubmitBody(),
  651. db: Session = Depends(get_db),
  652. user: BxUserContext = Depends(get_bx_current_user),
  653. ):
  654. tenant_no = _tenant(db, user)
  655. reimburse = ReimburseService.submit(
  656. db,
  657. reimburse_id,
  658. user,
  659. invoice_ids=body.invoice_ids,
  660. invoice_links=body.invoice_links,
  661. )
  662. if not reimburse:
  663. raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="报销单不存在")
  664. db.commit()
  665. db.refresh(reimburse)
  666. return ApiResponse(data=ReimburseService.build_apply_out_with_details(db, tenant_no, reimburse))
  667. @router.post("/{reimburse_id}/approve", response_model=ApiResponse[ReimburseApplyOut])
  668. def approve_reimburse(
  669. reimburse_id: str,
  670. body: ReimburseApprovalCreate,
  671. db: Session = Depends(get_db),
  672. user: BxUserContext = Depends(get_bx_current_user),
  673. ):
  674. tenant_no = _tenant(db, user)
  675. reimburse = ReimburseService.approve(db, reimburse_id, user, body.approval_opinion or "")
  676. if not reimburse:
  677. raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="报销单不存在或无权审批")
  678. db.commit()
  679. db.refresh(reimburse)
  680. return ApiResponse(data=ReimburseService.out_one_with_attachment_counts(db, tenant_no, reimburse))
  681. @router.post("/{reimburse_id}/reject", response_model=ApiResponse[ReimburseApplyOut])
  682. def reject_reimburse(
  683. reimburse_id: str,
  684. body: ReimburseApprovalCreate,
  685. db: Session = Depends(get_db),
  686. user: BxUserContext = Depends(get_bx_current_user),
  687. ):
  688. tenant_no = _tenant(db, user)
  689. reimburse = ReimburseService.reject(db, reimburse_id, user, body.approval_opinion or "")
  690. if not reimburse:
  691. raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="报销单不存在或无权审批")
  692. db.commit()
  693. db.refresh(reimburse)
  694. return ApiResponse(data=ReimburseService.out_one_with_attachment_counts(db, tenant_no, reimburse))
  695. @router.post("/{reimburse_id}/withdraw", response_model=ApiResponse[ReimburseApplyOut])
  696. def withdraw_reimburse(
  697. reimburse_id: str,
  698. db: Session = Depends(get_db),
  699. user: BxUserContext = Depends(get_bx_current_user),
  700. ):
  701. tenant_no = _tenant(db, user)
  702. reimburse = ReimburseService.withdraw(db, reimburse_id, user)
  703. if not reimburse:
  704. raise HTTPException(
  705. status_code=status.HTTP_400_BAD_REQUEST,
  706. detail="报销单不存在、非本人申请或当前状态不可撤回",
  707. )
  708. db.commit()
  709. db.refresh(reimburse)
  710. return ApiResponse(data=ReimburseService.build_apply_out_with_details(db, tenant_no, reimburse))
  711. @router.delete("/{reimburse_id}", response_model=ApiResponse[None])
  712. def delete_reimburse(
  713. reimburse_id: str,
  714. db: Session = Depends(get_db),
  715. user: BxUserContext = Depends(get_bx_current_user),
  716. ):
  717. tenant_no = _tenant(db, user)
  718. if not ReimburseService.get_by_id(db, reimburse_id, tenant_no, user=user):
  719. raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="报销单不存在")
  720. ReimburseService.soft_delete(db, reimburse_id, user=user)
  721. db.commit()
  722. return ApiResponse(data=None)