reimburse.py 26 KB

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