reimburse.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  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. )
  19. from app.services.bx.expense_item import ExpenseItemService
  20. from app.services.bx.reimburse import ReimburseService
  21. from app.utils.bx_codegen import generate_apply_code, generate_title
  22. from app.utils.bx_date_range import parse_create_time_day_bounds
  23. router = APIRouter(prefix="/reimburses", tags=["报销管理"])
  24. def _tenant(db: Session, user: BxUserContext) -> str:
  25. return get_tenant_no(db, user.to_tenant_user_dict())
  26. def _build_details_data(db: Session, tenant_no: str, body_details) -> List[dict]:
  27. details_data: List[dict] = []
  28. for d in body_details:
  29. item = ExpenseItemService.get_by_id(db, d.expense_item_id, tenant_no)
  30. if not item:
  31. raise HTTPException(
  32. status_code=status.HTTP_400_BAD_REQUEST,
  33. detail=f"费用项目 {d.expense_item_id} 不存在",
  34. )
  35. details_data.append(
  36. {
  37. "expense_id": d.expense_item_id,
  38. "expense_name": item.item_name,
  39. "amount": d.amount,
  40. "remark": d.remark,
  41. }
  42. )
  43. return details_data
  44. @router.get("/generate-title", response_model=ApiResponse[str])
  45. def get_generated_title(
  46. reimburseDate: Optional[str] = None,
  47. excludeApplyId: Optional[str] = None,
  48. db: Session = Depends(get_db),
  49. user: BxUserContext = Depends(get_bx_current_user),
  50. ):
  51. tenant_no = _tenant(db, user)
  52. exclude_id = str(excludeApplyId).strip() if excludeApplyId else None
  53. title = generate_title(db, user.name, tenant_no, reimburseDate, exclude_id)
  54. return ApiResponse(data=title)
  55. @router.get("/", response_model=ApiResponse[PagedData[ReimburseApplyOut]])
  56. def list_reimburses(
  57. page: int = 1,
  58. pageSize: int = 10,
  59. status: Optional[str] = None,
  60. keyword: str = "",
  61. expense_id: Optional[str] = None,
  62. applicantId: Optional[str] = None,
  63. applyDate: Optional[str] = None,
  64. db: Session = Depends(get_db),
  65. user: BxUserContext = Depends(get_bx_current_user),
  66. ):
  67. tenant_no = _tenant(db, user)
  68. filters = []
  69. if status:
  70. filters.append(BxReimburseApply.status == status)
  71. if keyword:
  72. filters.append(
  73. or_(
  74. BxReimburseApply.apply_code.contains(keyword),
  75. BxReimburseApply.applicant_name.contains(keyword),
  76. )
  77. )
  78. if expense_id:
  79. filters.append(BxReimburseApply.expense_id == str(expense_id).strip())
  80. if applicantId:
  81. filters.append(BxReimburseApply.applicant_id == str(applicantId).strip())
  82. bounds = parse_create_time_day_bounds(applyDate)
  83. if bounds:
  84. d0, d1 = bounds
  85. filters.append(BxReimburseApply.create_time >= d0)
  86. filters.append(BxReimburseApply.create_time < d1)
  87. rows, total = ReimburseService.get_paged(db, tenant_no, page=page, page_size=pageSize, filters=filters)
  88. out_rows = ReimburseService.out_rows_with_attachment_counts(db, tenant_no, list(rows))
  89. return ApiResponse(data=PagedData(rows=out_rows, total=total, page=page, page_size=pageSize))
  90. @router.get("/my", response_model=ApiResponse[PagedData[ReimburseApplyOut]])
  91. def my_reimburses(
  92. page: int = 1,
  93. pageSize: int = 10,
  94. status: Optional[str] = None,
  95. keyword: str = "",
  96. applyDate: Optional[str] = None,
  97. db: Session = Depends(get_db),
  98. user: BxUserContext = Depends(get_bx_current_user),
  99. ):
  100. tenant_no = _tenant(db, user)
  101. filters = [
  102. or_(
  103. BxReimburseApply.applicant_id == user.id,
  104. BxReimburseApply.create_by == user.id,
  105. )
  106. ]
  107. if status:
  108. filters.append(BxReimburseApply.status == status)
  109. if keyword:
  110. filters.append(
  111. or_(
  112. BxReimburseApply.apply_code.contains(keyword),
  113. BxReimburseApply.applicant_name.contains(keyword),
  114. )
  115. )
  116. bounds = parse_create_time_day_bounds(applyDate)
  117. if bounds:
  118. d0, d1 = bounds
  119. filters.append(BxReimburseApply.create_time >= d0)
  120. filters.append(BxReimburseApply.create_time < d1)
  121. rows, total = ReimburseService.get_paged(db, tenant_no, page=page, page_size=pageSize, filters=filters)
  122. out_rows = ReimburseService.out_rows_with_attachment_counts(db, tenant_no, list(rows))
  123. return ApiResponse(data=PagedData(rows=out_rows, total=total, page=page, page_size=pageSize))
  124. @router.get("/my/stats", response_model=ApiResponse[ReimburseMyStatsOut])
  125. def my_reimburse_stats(
  126. db: Session = Depends(get_db),
  127. user: BxUserContext = Depends(get_bx_current_user),
  128. ):
  129. tenant_no = _tenant(db, user)
  130. data = ReimburseService.my_apply_stats(db, user.id, tenant_no)
  131. return ApiResponse(data=ReimburseMyStatsOut.model_validate(data))
  132. @router.get("/stats/status-counts", response_model=ApiResponse[dict])
  133. def reimburse_status_counts(
  134. db: Session = Depends(get_db),
  135. user: BxUserContext = Depends(get_bx_current_user),
  136. ):
  137. tenant_no = _tenant(db, user)
  138. return ApiResponse(data=ReimburseService.global_status_counts(db, tenant_no))
  139. @router.get("/pending-approval", response_model=ApiResponse[PagedData[ReimburseApplyOut]])
  140. def pending_approval(
  141. page: int = 1,
  142. pageSize: int = 10,
  143. keyword: str = "",
  144. applicantId: Optional[str] = None,
  145. applyDate: Optional[str] = None,
  146. db: Session = Depends(get_db),
  147. user: BxUserContext = Depends(get_bx_current_user),
  148. ):
  149. tenant_no = _tenant(db, user)
  150. applicant_id = str(applicantId).strip() if applicantId else None
  151. rows, total = ReimburseService.pending_approval(
  152. db,
  153. user,
  154. tenant_no,
  155. page=page,
  156. page_size=pageSize,
  157. keyword=keyword,
  158. applicant_id=applicant_id,
  159. apply_date=applyDate,
  160. )
  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("/pending-approval/stats", response_model=ApiResponse[ReimburseApproverPendingStatsOut])
  164. def pending_approval_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.pending_approval_stats(db, user, tenant_no)
  170. return ApiResponse(data=ReimburseApproverPendingStatsOut.model_validate(data))
  171. @router.get("/approved-by-me", response_model=ApiResponse[PagedData[ReimburseApplyOut]])
  172. def approved_by_me(
  173. page: int = 1,
  174. pageSize: int = 10,
  175. keyword: str = "",
  176. applicantId: Optional[str] = None,
  177. applyDate: Optional[str] = None,
  178. db: Session = Depends(get_db),
  179. user: BxUserContext = Depends(get_bx_current_user),
  180. ):
  181. tenant_no = _tenant(db, user)
  182. applicant_id = str(applicantId).strip() if applicantId else None
  183. rows, total = ReimburseService.approved_by_me(
  184. db,
  185. user,
  186. tenant_no,
  187. page=page,
  188. page_size=pageSize,
  189. keyword=keyword,
  190. applicant_id=applicant_id,
  191. apply_date=applyDate,
  192. )
  193. out_rows = ReimburseService.out_rows_with_attachment_counts(db, tenant_no, list(rows))
  194. return ApiResponse(data=PagedData(rows=out_rows, total=total, page=page, page_size=pageSize))
  195. @router.get("/{reimburse_id}", response_model=ApiResponse[ReimburseApplyOut])
  196. def get_reimburse(
  197. reimburse_id: str,
  198. db: Session = Depends(get_db),
  199. user: BxUserContext = Depends(get_bx_current_user),
  200. ):
  201. tenant_no = _tenant(db, user)
  202. reimburse = ReimburseService.get_by_id(db, reimburse_id, tenant_no)
  203. if not reimburse:
  204. raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="报销单不存在")
  205. out = ReimburseService.build_apply_out_with_details(db, tenant_no, reimburse)
  206. return ApiResponse(data=out)
  207. @router.get("/{reimburse_id}/approvals", response_model=ApiResponse[List[ReimburseApprovalOut]])
  208. def get_approvals(
  209. reimburse_id: str,
  210. db: Session = Depends(get_db),
  211. user: BxUserContext = Depends(get_bx_current_user),
  212. ):
  213. tenant_no = _tenant(db, user)
  214. if not ReimburseService.get_by_id(db, reimburse_id, tenant_no):
  215. raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="报销单不存在")
  216. approvals = ReimburseService.get_approvals(db, reimburse_id, tenant_no)
  217. return ApiResponse(data=[ReimburseApprovalOut.model_validate(a) for a in approvals])
  218. @router.get("/{reimburse_id}/approval-history", response_model=ApiResponse[List[ReimburseApprovalOut]])
  219. def get_approval_history(
  220. reimburse_id: str,
  221. db: Session = Depends(get_db),
  222. user: BxUserContext = Depends(get_bx_current_user),
  223. ):
  224. tenant_no = _tenant(db, user)
  225. if not ReimburseService.get_by_id(db, reimburse_id, tenant_no):
  226. raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="报销单不存在")
  227. history = ReimburseService.get_approval_history(db, reimburse_id, tenant_no)
  228. return ApiResponse(data=[ReimburseApprovalOut.model_validate(a) for a in history])
  229. @router.post("/", response_model=ApiResponse[ReimburseApplyOut])
  230. def create_reimburse(
  231. body: ReimburseApplyCreate,
  232. db: Session = Depends(get_db),
  233. user: BxUserContext = Depends(get_bx_current_user),
  234. ):
  235. tenant_no = _tenant(db, user)
  236. details_data = _build_details_data(db, tenant_no, body.details)
  237. data = {
  238. "apply_code": generate_apply_code(db, "BX", tenant_no),
  239. "status": "draft",
  240. "remark": body.remark,
  241. "reimburse_date": body.reimburse_date,
  242. }
  243. if body.title:
  244. data["title"] = body.title
  245. wf = (
  246. db.query(BxWorkflowDef)
  247. .filter(
  248. BxWorkflowDef.biz_type == "reimburse",
  249. BxWorkflowDef.tenant_no == tenant_no,
  250. BxWorkflowDef.del_flag == 0,
  251. )
  252. .first()
  253. )
  254. if wf:
  255. data["wf_id"] = wf.id
  256. reimburse = ReimburseService.create_with_details(db, data, details_data, user=user)
  257. db.commit()
  258. db.refresh(reimburse)
  259. out = ReimburseService.build_apply_out_with_details(db, tenant_no, reimburse)
  260. return ApiResponse(data=out)
  261. @router.put("/{reimburse_id}", response_model=ApiResponse[ReimburseApplyOut])
  262. def update_reimburse(
  263. reimburse_id: str,
  264. body: ReimburseApplyUpdate,
  265. db: Session = Depends(get_db),
  266. user: BxUserContext = Depends(get_bx_current_user),
  267. ):
  268. tenant_no = _tenant(db, user)
  269. details_data = None
  270. if body.details is not None:
  271. details_data = _build_details_data(db, tenant_no, body.details)
  272. main_data = {}
  273. if body.remark is not None:
  274. main_data["remark"] = body.remark
  275. if body.reimburse_date is not None:
  276. main_data["reimburse_date"] = body.reimburse_date
  277. if body.title is not None:
  278. main_data["title"] = body.title
  279. reimburse = ReimburseService.update_with_details(
  280. db, reimburse_id, main_data, details_data, user=user
  281. )
  282. if not reimburse:
  283. raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="报销单不存在")
  284. db.commit()
  285. db.refresh(reimburse)
  286. out = ReimburseService.build_apply_out_with_details(db, tenant_no, reimburse)
  287. return ApiResponse(data=out)
  288. @router.post("/{reimburse_id}/submit", response_model=ApiResponse[ReimburseApplyOut])
  289. def submit_reimburse(
  290. reimburse_id: str,
  291. db: Session = Depends(get_db),
  292. user: BxUserContext = Depends(get_bx_current_user),
  293. ):
  294. tenant_no = _tenant(db, user)
  295. reimburse = ReimburseService.submit(db, reimburse_id, user)
  296. if not reimburse:
  297. raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="报销单不存在")
  298. db.commit()
  299. db.refresh(reimburse)
  300. return ApiResponse(data=ReimburseService.out_one_with_attachment_counts(db, tenant_no, reimburse))
  301. @router.post("/{reimburse_id}/approve", response_model=ApiResponse[ReimburseApplyOut])
  302. def approve_reimburse(
  303. reimburse_id: str,
  304. body: ReimburseApprovalCreate,
  305. db: Session = Depends(get_db),
  306. user: BxUserContext = Depends(get_bx_current_user),
  307. ):
  308. tenant_no = _tenant(db, user)
  309. reimburse = ReimburseService.approve(db, reimburse_id, user, body.approval_opinion or "")
  310. if not reimburse:
  311. raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="报销单不存在或无权审批")
  312. db.commit()
  313. db.refresh(reimburse)
  314. return ApiResponse(data=ReimburseService.out_one_with_attachment_counts(db, tenant_no, reimburse))
  315. @router.post("/{reimburse_id}/reject", response_model=ApiResponse[ReimburseApplyOut])
  316. def reject_reimburse(
  317. reimburse_id: str,
  318. body: ReimburseApprovalCreate,
  319. db: Session = Depends(get_db),
  320. user: BxUserContext = Depends(get_bx_current_user),
  321. ):
  322. tenant_no = _tenant(db, user)
  323. reimburse = ReimburseService.reject(db, reimburse_id, user, body.approval_opinion or "")
  324. if not reimburse:
  325. raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="报销单不存在或无权审批")
  326. db.commit()
  327. db.refresh(reimburse)
  328. return ApiResponse(data=ReimburseService.out_one_with_attachment_counts(db, tenant_no, reimburse))
  329. @router.delete("/{reimburse_id}", response_model=ApiResponse[None])
  330. def delete_reimburse(
  331. reimburse_id: str,
  332. db: Session = Depends(get_db),
  333. user: BxUserContext = Depends(get_bx_current_user),
  334. ):
  335. tenant_no = _tenant(db, user)
  336. if not ReimburseService.get_by_id(db, reimburse_id, tenant_no):
  337. raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="报销单不存在")
  338. ReimburseService.soft_delete(db, reimburse_id, user=user)
  339. db.commit()
  340. return ApiResponse(data=None)