reimburse.py 17 KB

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