reimburse.py 27 KB

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