reimburse.py 26 KB

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