reimburse.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. from typing import List, Optional
  2. from fastapi import APIRouter, Depends, HTTPException, status
  3. from sqlalchemy import or_
  4. from sqlalchemy.orm import Session
  5. from app.core.bx_auth import BxUserContext, get_bx_current_user
  6. from app.core.database import get_db
  7. from app.core.tenant_context import get_tenant_no
  8. from app.models.bx_models import BxReimburseApply, BxWorkflowDef
  9. from app.schemas.bx.common import ApiResponse, PagedData
  10. from app.schemas.bx.reimburse import (
  11. ReimburseApplyCreate,
  12. ReimburseApplyOut,
  13. ReimburseApplyUpdate,
  14. ReimburseApprovalCreate,
  15. ReimburseApprovalOut,
  16. ReimburseApproverPendingStatsOut,
  17. ReimburseMyStatsOut,
  18. ReimburseSubmitBody,
  19. )
  20. from app.services.bx.expense_item import ExpenseItemService
  21. from app.services.bx.reimburse import ReimburseService
  22. from app.utils.bx_codegen import generate_apply_code, generate_title, parse_optional_date
  23. from app.utils.bx_date_range import append_create_time_filters
  24. router = APIRouter(prefix="/reimburses", tags=["报销管理"])
  25. def _tenant(db: Session, user: BxUserContext) -> str:
  26. return get_tenant_no(db, user.to_tenant_user_dict())
  27. def _build_details_data(
  28. db: Session,
  29. tenant_no: str,
  30. body_details,
  31. *,
  32. user: BxUserContext,
  33. ) -> List[dict]:
  34. details_data: List[dict] = []
  35. for d in body_details:
  36. item = ExpenseItemService.get_by_id(
  37. db, d.expense_item_id, tenant_no, user=user, skip_scope=True
  38. )
  39. if not item:
  40. raise HTTPException(
  41. status_code=status.HTTP_400_BAD_REQUEST,
  42. detail=f"费用项目 {d.expense_item_id} 不存在",
  43. )
  44. try:
  45. occur_date = parse_optional_date(d.occur_date)
  46. except ValueError:
  47. raise HTTPException(
  48. status_code=status.HTTP_400_BAD_REQUEST,
  49. detail="发生时间格式无效,请使用 YYYY-MM-DD",
  50. )
  51. details_data.append(
  52. {
  53. "expense_id": d.expense_item_id,
  54. "expense_name": item.item_name,
  55. "amount": d.amount,
  56. "remark": d.remark,
  57. "occur_date": occur_date,
  58. }
  59. )
  60. return details_data
  61. @router.get("/generate-title", response_model=ApiResponse[str])
  62. def get_generated_title(
  63. reimburseDate: Optional[str] = None,
  64. excludeApplyId: Optional[str] = None,
  65. applicantId: Optional[str] = None,
  66. db: Session = Depends(get_db),
  67. user: BxUserContext = Depends(get_bx_current_user),
  68. ):
  69. tenant_no = _tenant(db, user)
  70. exclude_id = str(excludeApplyId).strip() if excludeApplyId else None
  71. _, applicant_name = ReimburseService.resolve_applicant(
  72. db, user, applicantId, tenant_no=tenant_no
  73. )
  74. title = generate_title(db, applicant_name, tenant_no, reimburseDate, exclude_id)
  75. return ApiResponse(data=title)
  76. @router.get("/", response_model=ApiResponse[PagedData[ReimburseApplyOut]])
  77. def list_reimburses(
  78. page: int = 1,
  79. pageSize: int = 10,
  80. status: Optional[str] = None,
  81. keyword: str = "",
  82. expense_id: Optional[str] = None,
  83. expenseName: Optional[str] = None,
  84. applicantId: Optional[str] = None,
  85. applyDate: Optional[str] = None,
  86. applyDateFrom: Optional[str] = None,
  87. applyDateTo: Optional[str] = None,
  88. db: Session = Depends(get_db),
  89. user: BxUserContext = Depends(get_bx_current_user),
  90. ):
  91. tenant_no = _tenant(db, user)
  92. filters = []
  93. if status:
  94. filters.append(BxReimburseApply.status == status)
  95. if keyword:
  96. filters.append(
  97. or_(
  98. BxReimburseApply.apply_code.contains(keyword),
  99. BxReimburseApply.applicant_name.contains(keyword),
  100. BxReimburseApply.title.contains(keyword),
  101. )
  102. )
  103. if expense_id:
  104. filters.append(BxReimburseApply.expense_id == str(expense_id).strip())
  105. expense_filter = ReimburseService.build_expense_name_condition(db, tenant_no, expenseName)
  106. if expense_filter is not None:
  107. filters.append(expense_filter)
  108. if applicantId:
  109. filters.append(BxReimburseApply.applicant_id == str(applicantId).strip())
  110. append_create_time_filters(
  111. filters,
  112. BxReimburseApply,
  113. apply_date=applyDate,
  114. apply_date_from=applyDateFrom,
  115. apply_date_to=applyDateTo,
  116. )
  117. rows, total = ReimburseService.get_paged(db, tenant_no, page=page, page_size=pageSize, filters=filters, user=user)
  118. out_rows = ReimburseService.out_rows_with_attachment_counts(db, tenant_no, list(rows))
  119. return ApiResponse(data=PagedData(rows=out_rows, total=total, page=page, page_size=pageSize))
  120. @router.get("/my", response_model=ApiResponse[PagedData[ReimburseApplyOut]])
  121. def my_reimburses(
  122. page: int = 1,
  123. pageSize: int = 10,
  124. status: Optional[str] = None,
  125. keyword: str = "",
  126. expenseName: Optional[str] = None,
  127. applyDate: Optional[str] = None,
  128. applyDateFrom: Optional[str] = None,
  129. applyDateTo: Optional[str] = None,
  130. db: Session = Depends(get_db),
  131. user: BxUserContext = Depends(get_bx_current_user),
  132. ):
  133. tenant_no = _tenant(db, user)
  134. filters = [
  135. or_(
  136. BxReimburseApply.applicant_id == user.id,
  137. BxReimburseApply.create_by == user.id,
  138. )
  139. ]
  140. if status:
  141. filters.append(BxReimburseApply.status == status)
  142. if keyword:
  143. filters.append(
  144. or_(
  145. BxReimburseApply.apply_code.contains(keyword),
  146. BxReimburseApply.applicant_name.contains(keyword),
  147. BxReimburseApply.title.contains(keyword),
  148. )
  149. )
  150. expense_filter = ReimburseService.build_expense_name_condition(db, tenant_no, expenseName)
  151. if expense_filter is not None:
  152. filters.append(expense_filter)
  153. append_create_time_filters(
  154. filters,
  155. BxReimburseApply,
  156. apply_date=applyDate,
  157. apply_date_from=applyDateFrom,
  158. apply_date_to=applyDateTo,
  159. )
  160. rows, total = ReimburseService.get_paged(db, tenant_no, page=page, page_size=pageSize, filters=filters, user=user)
  161. out_rows = ReimburseService.out_rows_with_attachment_counts(db, tenant_no, list(rows))
  162. return ApiResponse(data=PagedData(rows=out_rows, total=total, page=page, page_size=pageSize))
  163. @router.get("/my/stats", response_model=ApiResponse[ReimburseMyStatsOut])
  164. def my_reimburse_stats(
  165. db: Session = Depends(get_db),
  166. user: BxUserContext = Depends(get_bx_current_user),
  167. ):
  168. tenant_no = _tenant(db, user)
  169. data = ReimburseService.my_apply_stats(db, user, tenant_no)
  170. return ApiResponse(data=ReimburseMyStatsOut.model_validate(data))
  171. @router.get("/stats/status-counts", response_model=ApiResponse[dict])
  172. def reimburse_status_counts(
  173. db: Session = Depends(get_db),
  174. user: BxUserContext = Depends(get_bx_current_user),
  175. ):
  176. tenant_no = _tenant(db, user)
  177. return ApiResponse(data=ReimburseService.global_status_counts(db, tenant_no, user=user))
  178. @router.get("/pending-approval", response_model=ApiResponse[PagedData[ReimburseApplyOut]])
  179. def pending_approval(
  180. page: int = 1,
  181. pageSize: int = 10,
  182. keyword: str = "",
  183. applicantId: Optional[str] = None,
  184. expenseName: Optional[str] = None,
  185. applyDate: Optional[str] = None,
  186. applyDateFrom: Optional[str] = None,
  187. applyDateTo: Optional[str] = None,
  188. db: Session = Depends(get_db),
  189. user: BxUserContext = Depends(get_bx_current_user),
  190. ):
  191. tenant_no = _tenant(db, user)
  192. applicant_id = str(applicantId).strip() if applicantId else None
  193. rows, total = ReimburseService.pending_approval(
  194. db,
  195. user,
  196. tenant_no,
  197. page=page,
  198. page_size=pageSize,
  199. keyword=keyword,
  200. applicant_id=applicant_id,
  201. expense_name=expenseName,
  202. apply_date=applyDate,
  203. apply_date_from=applyDateFrom,
  204. apply_date_to=applyDateTo,
  205. )
  206. out_rows = ReimburseService.out_rows_with_attachment_counts(db, tenant_no, list(rows))
  207. return ApiResponse(data=PagedData(rows=out_rows, total=total, page=page, page_size=pageSize))
  208. @router.get("/pending-approval/stats", response_model=ApiResponse[ReimburseApproverPendingStatsOut])
  209. def pending_approval_stats(
  210. db: Session = Depends(get_db),
  211. user: BxUserContext = Depends(get_bx_current_user),
  212. ):
  213. tenant_no = _tenant(db, user)
  214. data = ReimburseService.pending_approval_stats(db, user, tenant_no)
  215. return ApiResponse(data=ReimburseApproverPendingStatsOut.model_validate(data))
  216. @router.get("/approved-by-me", response_model=ApiResponse[PagedData[ReimburseApplyOut]])
  217. def approved_by_me(
  218. page: int = 1,
  219. pageSize: int = 10,
  220. keyword: str = "",
  221. applicantId: Optional[str] = None,
  222. expenseName: Optional[str] = None,
  223. applyDate: Optional[str] = None,
  224. applyDateFrom: Optional[str] = None,
  225. applyDateTo: Optional[str] = None,
  226. db: Session = Depends(get_db),
  227. user: BxUserContext = Depends(get_bx_current_user),
  228. ):
  229. tenant_no = _tenant(db, user)
  230. applicant_id = str(applicantId).strip() if applicantId else None
  231. rows, total = ReimburseService.approved_by_me(
  232. db,
  233. user,
  234. tenant_no,
  235. page=page,
  236. page_size=pageSize,
  237. keyword=keyword,
  238. applicant_id=applicant_id,
  239. expense_name=expenseName,
  240. apply_date=applyDate,
  241. apply_date_from=applyDateFrom,
  242. apply_date_to=applyDateTo,
  243. )
  244. out_rows = ReimburseService.out_rows_with_attachment_counts(db, tenant_no, list(rows))
  245. return ApiResponse(data=PagedData(rows=out_rows, total=total, page=page, page_size=pageSize))
  246. @router.get("/{reimburse_id}", response_model=ApiResponse[ReimburseApplyOut])
  247. def get_reimburse(
  248. reimburse_id: str,
  249. db: Session = Depends(get_db),
  250. user: BxUserContext = Depends(get_bx_current_user),
  251. ):
  252. tenant_no = _tenant(db, user)
  253. reimburse = ReimburseService.get_by_id(db, reimburse_id, tenant_no, user=user)
  254. if not reimburse:
  255. raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="报销单不存在")
  256. out = ReimburseService.build_apply_out_with_details(db, tenant_no, reimburse)
  257. return ApiResponse(data=out)
  258. @router.get("/{reimburse_id}/approvals", response_model=ApiResponse[List[ReimburseApprovalOut]])
  259. def get_approvals(
  260. reimburse_id: str,
  261. db: Session = Depends(get_db),
  262. user: BxUserContext = Depends(get_bx_current_user),
  263. ):
  264. tenant_no = _tenant(db, user)
  265. if not ReimburseService.get_by_id(db, reimburse_id, tenant_no, user=user):
  266. raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="报销单不存在")
  267. approvals = ReimburseService.get_approvals(db, reimburse_id, tenant_no, user=user)
  268. return ApiResponse(data=[ReimburseApprovalOut.model_validate(a) for a in approvals])
  269. @router.get("/{reimburse_id}/approval-history", response_model=ApiResponse[List[ReimburseApprovalOut]])
  270. def get_approval_history(
  271. reimburse_id: str,
  272. db: Session = Depends(get_db),
  273. user: BxUserContext = Depends(get_bx_current_user),
  274. ):
  275. tenant_no = _tenant(db, user)
  276. if not ReimburseService.get_by_id(db, reimburse_id, tenant_no, user=user):
  277. raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="报销单不存在")
  278. history = ReimburseService.get_approval_history(db, reimburse_id, tenant_no, user=user)
  279. return ApiResponse(data=[ReimburseApprovalOut.model_validate(a) for a in history])
  280. @router.post("/", response_model=ApiResponse[ReimburseApplyOut])
  281. def create_reimburse(
  282. body: ReimburseApplyCreate,
  283. db: Session = Depends(get_db),
  284. user: BxUserContext = Depends(get_bx_current_user),
  285. ):
  286. tenant_no = _tenant(db, user)
  287. details_data = _build_details_data(db, tenant_no, body.details, user=user)
  288. data = {
  289. "apply_code": generate_apply_code(db, "BX", tenant_no),
  290. "status": "draft",
  291. "remark": body.remark,
  292. "reimburse_date": body.reimburse_date,
  293. }
  294. if body.title:
  295. data["title"] = body.title
  296. wf = (
  297. db.query(BxWorkflowDef)
  298. .filter(
  299. BxWorkflowDef.biz_type == "reimburse",
  300. BxWorkflowDef.tenant_no == tenant_no,
  301. BxWorkflowDef.del_flag == 0,
  302. )
  303. .first()
  304. )
  305. if wf:
  306. data["wf_id"] = wf.id
  307. applicant_id, applicant_name = ReimburseService.resolve_applicant(
  308. db, user, body.applicant_id, tenant_no=tenant_no
  309. )
  310. reimburse = ReimburseService.create_with_details(
  311. db,
  312. data,
  313. details_data,
  314. user=user,
  315. applicant_id=applicant_id,
  316. applicant_name=applicant_name,
  317. )
  318. if body.invoice_links is not None or body.invoice_ids is not None:
  319. ReimburseService.sync_reimburse_invoices(
  320. db,
  321. reimburse.id,
  322. body.invoice_ids,
  323. tenant_no,
  324. user,
  325. applicant_id=applicant_id,
  326. invoice_links=body.invoice_links,
  327. )
  328. db.commit()
  329. db.refresh(reimburse)
  330. out = ReimburseService.build_apply_out_with_details(db, tenant_no, reimburse)
  331. return ApiResponse(data=out)
  332. @router.put("/{reimburse_id}", response_model=ApiResponse[ReimburseApplyOut])
  333. def update_reimburse(
  334. reimburse_id: str,
  335. body: ReimburseApplyUpdate,
  336. db: Session = Depends(get_db),
  337. user: BxUserContext = Depends(get_bx_current_user),
  338. ):
  339. tenant_no = _tenant(db, user)
  340. details_data = None
  341. if body.details is not None:
  342. details_data = _build_details_data(db, tenant_no, body.details, user=user)
  343. main_data = {}
  344. if body.remark is not None:
  345. main_data["remark"] = body.remark
  346. if body.reimburse_date is not None:
  347. main_data["reimburse_date"] = body.reimburse_date
  348. if body.title is not None:
  349. main_data["title"] = body.title
  350. if body.applicant_id is not None:
  351. applicant_id, applicant_name = ReimburseService.resolve_applicant(
  352. db, user, body.applicant_id, tenant_no=tenant_no
  353. )
  354. main_data["applicant_id"] = applicant_id
  355. main_data["applicant_name"] = applicant_name
  356. reimburse = ReimburseService.update_with_details(
  357. db, reimburse_id, main_data, details_data, user=user
  358. )
  359. if not reimburse:
  360. raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="报销单不存在")
  361. if body.invoice_links is not None or body.invoice_ids is not None:
  362. ReimburseService.sync_reimburse_invoices(
  363. db,
  364. reimburse_id,
  365. body.invoice_ids,
  366. tenant_no,
  367. user,
  368. applicant_id=reimburse.applicant_id,
  369. invoice_links=body.invoice_links,
  370. )
  371. db.commit()
  372. db.refresh(reimburse)
  373. out = ReimburseService.build_apply_out_with_details(db, tenant_no, reimburse)
  374. return ApiResponse(data=out)
  375. @router.post("/{reimburse_id}/submit", response_model=ApiResponse[ReimburseApplyOut])
  376. def submit_reimburse(
  377. reimburse_id: str,
  378. body: ReimburseSubmitBody = ReimburseSubmitBody(),
  379. db: Session = Depends(get_db),
  380. user: BxUserContext = Depends(get_bx_current_user),
  381. ):
  382. tenant_no = _tenant(db, user)
  383. reimburse = ReimburseService.submit(
  384. db,
  385. reimburse_id,
  386. user,
  387. invoice_ids=body.invoice_ids,
  388. invoice_links=body.invoice_links,
  389. )
  390. if not reimburse:
  391. raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="报销单不存在")
  392. db.commit()
  393. db.refresh(reimburse)
  394. return ApiResponse(data=ReimburseService.build_apply_out_with_details(db, tenant_no, reimburse))
  395. @router.post("/{reimburse_id}/approve", response_model=ApiResponse[ReimburseApplyOut])
  396. def approve_reimburse(
  397. reimburse_id: str,
  398. body: ReimburseApprovalCreate,
  399. db: Session = Depends(get_db),
  400. user: BxUserContext = Depends(get_bx_current_user),
  401. ):
  402. tenant_no = _tenant(db, user)
  403. reimburse = ReimburseService.approve(db, reimburse_id, user, body.approval_opinion or "")
  404. if not reimburse:
  405. raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="报销单不存在或无权审批")
  406. db.commit()
  407. db.refresh(reimburse)
  408. return ApiResponse(data=ReimburseService.out_one_with_attachment_counts(db, tenant_no, reimburse))
  409. @router.post("/{reimburse_id}/reject", response_model=ApiResponse[ReimburseApplyOut])
  410. def reject_reimburse(
  411. reimburse_id: str,
  412. body: ReimburseApprovalCreate,
  413. db: Session = Depends(get_db),
  414. user: BxUserContext = Depends(get_bx_current_user),
  415. ):
  416. tenant_no = _tenant(db, user)
  417. reimburse = ReimburseService.reject(db, reimburse_id, user, body.approval_opinion or "")
  418. if not reimburse:
  419. raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="报销单不存在或无权审批")
  420. db.commit()
  421. db.refresh(reimburse)
  422. return ApiResponse(data=ReimburseService.out_one_with_attachment_counts(db, tenant_no, reimburse))
  423. @router.post("/{reimburse_id}/withdraw", response_model=ApiResponse[ReimburseApplyOut])
  424. def withdraw_reimburse(
  425. reimburse_id: str,
  426. db: Session = Depends(get_db),
  427. user: BxUserContext = Depends(get_bx_current_user),
  428. ):
  429. tenant_no = _tenant(db, user)
  430. reimburse = ReimburseService.withdraw(db, reimburse_id, user)
  431. if not reimburse:
  432. raise HTTPException(
  433. status_code=status.HTTP_400_BAD_REQUEST,
  434. detail="报销单不存在、非本人申请或当前状态不可撤回",
  435. )
  436. db.commit()
  437. db.refresh(reimburse)
  438. return ApiResponse(data=ReimburseService.build_apply_out_with_details(db, tenant_no, reimburse))
  439. @router.delete("/{reimburse_id}", response_model=ApiResponse[None])
  440. def delete_reimburse(
  441. reimburse_id: str,
  442. db: Session = Depends(get_db),
  443. user: BxUserContext = Depends(get_bx_current_user),
  444. ):
  445. tenant_no = _tenant(db, user)
  446. if not ReimburseService.get_by_id(db, reimburse_id, tenant_no, user=user):
  447. raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="报销单不存在")
  448. ReimburseService.soft_delete(db, reimburse_id, user=user)
  449. db.commit()
  450. return ApiResponse(data=None)