reimburse.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839
  1. import io
  2. from datetime import date as date_cls
  3. from typing import Any, List, Optional
  4. from urllib.parse import quote
  5. from fastapi import APIRouter, Depends, File, HTTPException, Query, Request, UploadFile, status
  6. from pydantic import BaseModel, Field
  7. from fastapi.responses import StreamingResponse
  8. from sqlalchemy import or_
  9. from sqlalchemy.orm import Session
  10. from app.api.bx.export_common import (
  11. EXPORT_MAX_ROWS,
  12. ExportColumn,
  13. ExportValidationError,
  14. BxApplyListExportBody,
  15. dump_export_row,
  16. respond_xlsx,
  17. )
  18. from app.core.bx_auth import BxUserContext, get_bx_current_user
  19. from app.core.database import get_db
  20. from app.core.tenant_context import get_tenant_no
  21. from app.models.bx_models import BxReimburseApply, BxWorkflowDef
  22. from app.schemas.bx.common import ApiResponse, PagedData
  23. from app.schemas.bx.reimburse import (
  24. ReimburseApplyCreate,
  25. ReimburseApplyOut,
  26. ReimburseApplyUpdate,
  27. ReimburseApprovalCreate,
  28. ReimburseApprovalOut,
  29. ReimburseApproverPendingStatsOut,
  30. ReimburseMyStatsOut,
  31. ReimburseSubmitBody,
  32. )
  33. from app.services.bx.expense_item import ExpenseItemService
  34. from app.services.bx.list_sort import order_reimburse, parse_sort_params
  35. from app.services.bx.reimburse import ReimburseService
  36. from app.services.bx.reimburse_import import (
  37. build_applicant_label,
  38. build_import_template_bytes,
  39. import_reimburse_workbook,
  40. load_applicant_options,
  41. load_expense_nodes_flat,
  42. )
  43. from app.services.bx.reimburse_list_filters import build_reimburse_column_filters
  44. from app.utils.bx_codegen import generate_title, parse_optional_date
  45. router = APIRouter(prefix="/reimburses", tags=["报销管理"])
  46. def _tenant(db: Session, user: BxUserContext) -> str:
  47. return get_tenant_no(db, user.to_tenant_user_dict())
  48. def _reimburse_order(params: dict):
  49. sf, so = parse_sort_params(params)
  50. return order_reimburse(sf, so)
  51. REIMBURSE_EXPORT_COLUMNS = [
  52. ExportColumn(title="申请单号", field="applyCode"),
  53. ExportColumn(title="申请时间", field="applyTime"),
  54. ExportColumn(title="申请人", field="applicantName"),
  55. ExportColumn(title="报销主题", field="title"),
  56. ExportColumn(title="费用科目", field="expenseName"),
  57. ExportColumn(title="金额(元)", field="amount"),
  58. ExportColumn(title="状态", field="status"),
  59. ExportColumn(title="当前节点", field="currentNode"),
  60. ]
  61. def _merge_query(request: Request, **known) -> dict:
  62. out = {k: v for k, v in known.items() if v is not None and v != ""}
  63. for k, v in request.query_params.multi_items():
  64. if k in ("page", "pageSize"):
  65. continue
  66. if k not in out and v not in (None, ""):
  67. out[k] = v
  68. return out
  69. def _param_get(params: dict, *keys: str) -> Any:
  70. for key in keys:
  71. if key in params and params[key] not in (None, ""):
  72. return params[key]
  73. return None
  74. def _filters_from_params(params: dict, *, db: Session, tenant_no: str = "") -> list:
  75. ids = _param_get(params, "ids")
  76. if isinstance(ids, str):
  77. ids = [s.strip() for s in ids.split(",") if s.strip()]
  78. return build_reimburse_column_filters(
  79. db=db,
  80. tenant_no=tenant_no,
  81. keyword=str(_param_get(params, "keyword") or ""),
  82. status=_param_get(params, "status"),
  83. status_in=_param_get(params, "statusIn", "status_in"),
  84. apply_code=_param_get(params, "applyCode", "apply_code"),
  85. apply_code_in=_param_get(params, "applyCodeIn", "apply_code_in"),
  86. title=_param_get(params, "title"),
  87. title_in=_param_get(params, "titleIn", "title_in"),
  88. expense_name=_param_get(params, "expenseName", "expense_name"),
  89. expense_id=_param_get(params, "expenseId", "expense_id"),
  90. applicant_id=_param_get(params, "applicantId", "applicant_id"),
  91. applicant_name=_param_get(params, "applicantName", "applicant_name"),
  92. applicant_name_in=_param_get(params, "applicantNameIn", "applicant_name_in"),
  93. current_node=_param_get(params, "currentNode", "current_node"),
  94. current_node_in=_param_get(params, "currentNodeIn", "current_node_in"),
  95. amount_op=_param_get(params, "amountOp", "amount_op"),
  96. amount=_param_get(params, "amount"),
  97. amount_min=_param_get(params, "amountMin", "amount_min"),
  98. amount_max=_param_get(params, "amountMax", "amount_max"),
  99. apply_date=_param_get(params, "applyDate", "apply_date"),
  100. apply_date_from=_param_get(params, "applyDateFrom", "apply_date_from"),
  101. apply_date_to=_param_get(params, "applyDateTo", "apply_date_to"),
  102. ids=ids if isinstance(ids, list) else None,
  103. )
  104. def _body_to_params(body: BxApplyListExportBody) -> dict:
  105. data = body.model_dump(by_alias=True, exclude_none=True)
  106. extra = getattr(body, "model_extra", None) or {}
  107. for key, value in extra.items():
  108. if key not in data and value not in (None, ""):
  109. data[key] = value
  110. return data
  111. def _reimburse_list_filters(body: BxApplyListExportBody, db: Session, tenant_no: str) -> list:
  112. return _filters_from_params(_body_to_params(body), db=db, tenant_no=tenant_no)
  113. def _export_reimburse_rows(db: Session, tenant_no: str, rows) -> list:
  114. out_rows = ReimburseService.out_rows_with_attachment_counts(db, tenant_no, list(rows))
  115. return [dump_export_row(r) for r in out_rows]
  116. def _build_details_data(
  117. db: Session,
  118. tenant_no: str,
  119. body_details,
  120. *,
  121. user: BxUserContext,
  122. ) -> List[dict]:
  123. details_data: List[dict] = []
  124. for d in body_details:
  125. item = ExpenseItemService.get_by_id(
  126. db, d.expense_item_id, tenant_no, user=user, skip_scope=True
  127. )
  128. if not item:
  129. raise HTTPException(
  130. status_code=status.HTTP_400_BAD_REQUEST,
  131. detail=f"费用项目 {d.expense_item_id} 不存在",
  132. )
  133. try:
  134. occur_date = parse_optional_date(d.occur_date)
  135. except ValueError:
  136. raise HTTPException(
  137. status_code=status.HTTP_400_BAD_REQUEST,
  138. detail="发生时间格式无效,请使用 YYYY-MM-DD",
  139. )
  140. details_data.append(
  141. {
  142. "expense_id": d.expense_item_id,
  143. "expense_name": item.item_name,
  144. "amount": d.amount,
  145. "remark": d.remark,
  146. "occur_date": occur_date,
  147. }
  148. )
  149. return details_data
  150. @router.get("/generate-title", response_model=ApiResponse[str])
  151. def get_generated_title(
  152. reimburseDate: Optional[str] = None,
  153. excludeApplyId: Optional[str] = None,
  154. applicantId: Optional[str] = None,
  155. db: Session = Depends(get_db),
  156. user: BxUserContext = Depends(get_bx_current_user),
  157. ):
  158. tenant_no = _tenant(db, user)
  159. exclude_id = str(excludeApplyId).strip() if excludeApplyId else None
  160. _, applicant_name = ReimburseService.resolve_applicant(
  161. db, user, applicantId, tenant_no=tenant_no
  162. )
  163. title = generate_title(db, applicant_name, tenant_no, reimburseDate, exclude_id)
  164. return ApiResponse(data=title)
  165. @router.get("/import-template")
  166. def download_reimburse_import_template(
  167. db: Session = Depends(get_db),
  168. user: BxUserContext = Depends(get_bx_current_user),
  169. ):
  170. tenant_no = _tenant(db, user)
  171. nodes = load_expense_nodes_flat(db, tenant_no)
  172. applicants = load_applicant_options(db, user=user, tenant_no=tenant_no)
  173. me = next((a for a in applicants if a["id"] == user.id), None)
  174. if me:
  175. cur_label = build_applicant_label(me["nick_name"], me["user_no"], me["id"])
  176. else:
  177. cur_label = build_applicant_label(user.name or "", "", user.id)
  178. applicants = [
  179. {"id": user.id, "nick_name": user.name or "", "user_no": ""}
  180. ] + applicants
  181. raw = build_import_template_bytes(
  182. expense_nodes=nodes,
  183. applicants=applicants,
  184. current_applicant_label=cur_label,
  185. today=date_cls.today(),
  186. )
  187. filename = quote("报销申请导入模板.xlsx")
  188. return StreamingResponse(
  189. io.BytesIO(raw),
  190. media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  191. headers={
  192. "Content-Disposition": f"attachment; filename={filename}; filename*=UTF-8''{filename}"
  193. },
  194. )
  195. @router.post("/import", response_model=ApiResponse[dict])
  196. def import_reimburses(
  197. file: UploadFile = File(...),
  198. db: Session = Depends(get_db),
  199. user: BxUserContext = Depends(get_bx_current_user),
  200. ):
  201. content = file.file.read()
  202. if not content:
  203. raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="文件为空")
  204. try:
  205. result = import_reimburse_workbook(db, file_bytes=content, user=user)
  206. except ValueError as exc:
  207. raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)) from exc
  208. return ApiResponse(data=result)
  209. class ReimburseColumnFacetBody(BaseModel):
  210. """报销申请列头可选值(去重)"""
  211. field: str = Field(..., description="applyCode | applicantName | title | currentNode")
  212. keyword: Optional[str] = Field(default=None, description="可选值关键字")
  213. limit: Optional[int] = Field(default=500, ge=1, le=500, description="返回条数上限")
  214. _REIMBURSE_FACET_COLUMNS = {
  215. "applyCode": BxReimburseApply.apply_code,
  216. "applicantName": BxReimburseApply.applicant_name,
  217. "title": BxReimburseApply.title,
  218. "currentNode": BxReimburseApply.current_node,
  219. }
  220. @router.post("/column-facet-values", response_model=ApiResponse[dict])
  221. def reimburse_column_facet_values(
  222. body: ReimburseColumnFacetBody,
  223. db: Session = Depends(get_db),
  224. user: BxUserContext = Depends(get_bx_current_user),
  225. ):
  226. """报销申请列头可选值(单号/申请人/标题/节点去重,租户范围)"""
  227. from app.services.column_facet import list_column_facet_values
  228. column = _REIMBURSE_FACET_COLUMNS.get(body.field)
  229. if column is None:
  230. raise HTTPException(status_code=400, detail="不支持的列")
  231. tenant_no = _tenant(db, user)
  232. rows = list_column_facet_values(
  233. db,
  234. BxReimburseApply,
  235. column,
  236. tenant_no=tenant_no,
  237. keyword=body.keyword,
  238. limit=body.limit if body.limit is not None else 500,
  239. )
  240. return ApiResponse(data={"list": rows})
  241. @router.get("/", response_model=ApiResponse[PagedData[ReimburseApplyOut]])
  242. def list_reimburses(
  243. request: Request,
  244. page: int = 1,
  245. pageSize: int = Query(10, ge=1, le=500),
  246. status: Optional[str] = None,
  247. keyword: str = "",
  248. expense_id: Optional[str] = None,
  249. expenseName: Optional[str] = None,
  250. applicantId: Optional[str] = None,
  251. applyDate: Optional[str] = None,
  252. applyDateFrom: Optional[str] = None,
  253. applyDateTo: Optional[str] = None,
  254. db: Session = Depends(get_db),
  255. user: BxUserContext = Depends(get_bx_current_user),
  256. ):
  257. tenant_no = _tenant(db, user)
  258. params = _merge_query(
  259. request,
  260. status=status,
  261. keyword=keyword or None,
  262. expenseId=expense_id,
  263. expenseName=expenseName,
  264. applicantId=applicantId,
  265. applyDate=applyDate,
  266. applyDateFrom=applyDateFrom,
  267. applyDateTo=applyDateTo,
  268. )
  269. filters = _filters_from_params(params, db=db, tenant_no=tenant_no)
  270. rows, total = ReimburseService.get_paged(
  271. db, tenant_no, page=page, page_size=pageSize, filters=filters, user=user, order_by=_reimburse_order(params)
  272. )
  273. out_rows = ReimburseService.out_rows_with_attachment_counts(db, tenant_no, list(rows))
  274. return ApiResponse(data=PagedData(rows=out_rows, total=total, page=page, page_size=pageSize))
  275. @router.get("/my", response_model=ApiResponse[PagedData[ReimburseApplyOut]])
  276. def my_reimburses(
  277. request: Request,
  278. page: int = 1,
  279. pageSize: int = Query(10, ge=1, le=500),
  280. status: Optional[str] = None,
  281. keyword: str = "",
  282. expenseName: Optional[str] = None,
  283. applyCode: Optional[str] = None,
  284. title: Optional[str] = None,
  285. currentNode: Optional[str] = None,
  286. statusIn: Optional[str] = None,
  287. amountOp: Optional[str] = None,
  288. amount: Optional[str] = None,
  289. amountMin: Optional[str] = None,
  290. amountMax: Optional[str] = None,
  291. applyDate: Optional[str] = None,
  292. applyDateFrom: Optional[str] = None,
  293. applyDateTo: Optional[str] = None,
  294. db: Session = Depends(get_db),
  295. user: BxUserContext = Depends(get_bx_current_user),
  296. ):
  297. tenant_no = _tenant(db, user)
  298. params = _merge_query(
  299. request,
  300. status=status,
  301. keyword=keyword or None,
  302. expenseName=expenseName,
  303. applyCode=applyCode,
  304. title=title,
  305. currentNode=currentNode,
  306. statusIn=statusIn,
  307. amountOp=amountOp,
  308. amount=amount,
  309. amountMin=amountMin,
  310. amountMax=amountMax,
  311. applyDate=applyDate,
  312. applyDateFrom=applyDateFrom,
  313. applyDateTo=applyDateTo,
  314. )
  315. filters = [
  316. or_(
  317. BxReimburseApply.applicant_id == user.id,
  318. BxReimburseApply.create_by == user.id,
  319. )
  320. ]
  321. filters.extend(_filters_from_params(params, db=db, tenant_no=tenant_no))
  322. rows, total = ReimburseService.get_paged(
  323. db, tenant_no, page=page, page_size=pageSize, filters=filters, user=user, order_by=_reimburse_order(params)
  324. )
  325. out_rows = ReimburseService.out_rows_with_attachment_counts(db, tenant_no, list(rows))
  326. return ApiResponse(data=PagedData(rows=out_rows, total=total, page=page, page_size=pageSize))
  327. @router.get("/my/stats", response_model=ApiResponse[ReimburseMyStatsOut])
  328. def my_reimburse_stats(
  329. db: Session = Depends(get_db),
  330. user: BxUserContext = Depends(get_bx_current_user),
  331. ):
  332. tenant_no = _tenant(db, user)
  333. data = ReimburseService.my_apply_stats(db, user, tenant_no)
  334. return ApiResponse(data=ReimburseMyStatsOut.model_validate(data))
  335. @router.get("/stats/status-counts", response_model=ApiResponse[dict])
  336. def reimburse_status_counts(
  337. db: Session = Depends(get_db),
  338. user: BxUserContext = Depends(get_bx_current_user),
  339. ):
  340. tenant_no = _tenant(db, user)
  341. return ApiResponse(data=ReimburseService.global_status_counts(db, tenant_no, user=user))
  342. @router.get("/pending-approval", response_model=ApiResponse[PagedData[ReimburseApplyOut]])
  343. def pending_approval(
  344. request: Request,
  345. page: int = 1,
  346. pageSize: int = Query(10, ge=1, le=500),
  347. keyword: str = "",
  348. applicantId: Optional[str] = None,
  349. expenseName: Optional[str] = None,
  350. applyDate: Optional[str] = None,
  351. applyDateFrom: Optional[str] = None,
  352. applyDateTo: Optional[str] = None,
  353. db: Session = Depends(get_db),
  354. user: BxUserContext = Depends(get_bx_current_user),
  355. ):
  356. tenant_no = _tenant(db, user)
  357. params = _merge_query(
  358. request,
  359. keyword=keyword or None,
  360. applicantId=applicantId,
  361. expenseName=expenseName,
  362. applyDate=applyDate,
  363. applyDateFrom=applyDateFrom,
  364. applyDateTo=applyDateTo,
  365. )
  366. # Tab 语义固定 pending;不把 status 列参传入 builder
  367. params.pop("status", None)
  368. params.pop("statusIn", None)
  369. params.pop("status_in", None)
  370. extra_filters = _filters_from_params(params, db=db, tenant_no=tenant_no)
  371. rows, total = ReimburseService.pending_approval(
  372. db,
  373. user,
  374. tenant_no,
  375. page=page,
  376. page_size=pageSize,
  377. extra_filters=extra_filters,
  378. order_by=_reimburse_order(params),
  379. )
  380. out_rows = ReimburseService.out_rows_with_attachment_counts(db, tenant_no, list(rows))
  381. return ApiResponse(data=PagedData(rows=out_rows, total=total, page=page, page_size=pageSize))
  382. @router.get("/pending-approval/stats", response_model=ApiResponse[ReimburseApproverPendingStatsOut])
  383. def pending_approval_stats(
  384. db: Session = Depends(get_db),
  385. user: BxUserContext = Depends(get_bx_current_user),
  386. ):
  387. tenant_no = _tenant(db, user)
  388. data = ReimburseService.pending_approval_stats(db, user, tenant_no)
  389. return ApiResponse(data=ReimburseApproverPendingStatsOut.model_validate(data))
  390. @router.get("/approved-by-me", response_model=ApiResponse[PagedData[ReimburseApplyOut]])
  391. def approved_by_me(
  392. request: Request,
  393. page: int = 1,
  394. pageSize: int = Query(10, ge=1, le=500),
  395. keyword: str = "",
  396. applicantId: Optional[str] = None,
  397. expenseName: Optional[str] = None,
  398. applyDate: Optional[str] = None,
  399. applyDateFrom: Optional[str] = None,
  400. applyDateTo: Optional[str] = None,
  401. db: Session = Depends(get_db),
  402. user: BxUserContext = Depends(get_bx_current_user),
  403. ):
  404. tenant_no = _tenant(db, user)
  405. params = _merge_query(
  406. request,
  407. keyword=keyword or None,
  408. applicantId=applicantId,
  409. expenseName=expenseName,
  410. applyDate=applyDate,
  411. applyDateFrom=applyDateFrom,
  412. applyDateTo=applyDateTo,
  413. )
  414. extra_filters = _filters_from_params(params, db=db, tenant_no=tenant_no)
  415. rows, total = ReimburseService.approved_by_me(
  416. db,
  417. user,
  418. tenant_no,
  419. page=page,
  420. page_size=pageSize,
  421. extra_filters=extra_filters,
  422. order_by=_reimburse_order(params),
  423. )
  424. out_rows = ReimburseService.out_rows_with_attachment_counts(db, tenant_no, list(rows))
  425. return ApiResponse(data=PagedData(rows=out_rows, total=total, page=page, page_size=pageSize))
  426. @router.post("/export")
  427. def export_reimburses(
  428. body: BxApplyListExportBody,
  429. db: Session = Depends(get_db),
  430. user: BxUserContext = Depends(get_bx_current_user),
  431. ):
  432. try:
  433. tenant_no = _tenant(db, user)
  434. params = _body_to_params(body)
  435. filters = _filters_from_params(params, db=db, tenant_no=tenant_no)
  436. rows, _ = ReimburseService.get_paged(
  437. db,
  438. tenant_no,
  439. page=1,
  440. page_size=EXPORT_MAX_ROWS,
  441. filters=filters,
  442. user=user,
  443. order_by=_reimburse_order(params),
  444. )
  445. return respond_xlsx(
  446. db,
  447. tenant_no=tenant_no,
  448. sheet_title="报销申请",
  449. columns=REIMBURSE_EXPORT_COLUMNS,
  450. rows=_export_reimburse_rows(db, tenant_no, rows),
  451. filename_stem="报销申请",
  452. requested_columns=body.columns,
  453. )
  454. except ExportValidationError as e:
  455. raise HTTPException(status_code=400, detail=str(e)) from e
  456. @router.post("/my/export")
  457. def export_my_reimburses(
  458. body: BxApplyListExportBody,
  459. db: Session = Depends(get_db),
  460. user: BxUserContext = Depends(get_bx_current_user),
  461. ):
  462. try:
  463. tenant_no = _tenant(db, user)
  464. params = _body_to_params(body)
  465. filters = [
  466. or_(
  467. BxReimburseApply.applicant_id == user.id,
  468. BxReimburseApply.create_by == user.id,
  469. )
  470. ]
  471. filters.extend(_filters_from_params(params, db=db, tenant_no=tenant_no))
  472. rows, _ = ReimburseService.get_paged(
  473. db,
  474. tenant_no,
  475. page=1,
  476. page_size=EXPORT_MAX_ROWS,
  477. filters=filters,
  478. user=user,
  479. order_by=_reimburse_order(params),
  480. )
  481. return respond_xlsx(
  482. db,
  483. tenant_no=tenant_no,
  484. sheet_title="我的报销",
  485. columns=REIMBURSE_EXPORT_COLUMNS,
  486. rows=_export_reimburse_rows(db, tenant_no, rows),
  487. filename_stem="我的报销申请",
  488. requested_columns=body.columns,
  489. )
  490. except ExportValidationError as e:
  491. raise HTTPException(status_code=400, detail=str(e)) from e
  492. @router.post("/pending-approval/export")
  493. def export_pending_approval_reimburses(
  494. body: BxApplyListExportBody,
  495. db: Session = Depends(get_db),
  496. user: BxUserContext = Depends(get_bx_current_user),
  497. ):
  498. try:
  499. tenant_no = _tenant(db, user)
  500. params = _body_to_params(body)
  501. params.pop("status", None)
  502. params.pop("statusIn", None)
  503. params.pop("status_in", None)
  504. extra_filters = _filters_from_params(params, db=db, tenant_no=tenant_no)
  505. rows, _ = ReimburseService.pending_approval(
  506. db,
  507. user,
  508. tenant_no,
  509. page=1,
  510. page_size=EXPORT_MAX_ROWS,
  511. extra_filters=extra_filters,
  512. order_by=_reimburse_order(params),
  513. )
  514. return respond_xlsx(
  515. db,
  516. tenant_no=tenant_no,
  517. sheet_title="报销待审批",
  518. columns=REIMBURSE_EXPORT_COLUMNS,
  519. rows=_export_reimburse_rows(db, tenant_no, rows),
  520. filename_stem="报销待审批",
  521. requested_columns=body.columns,
  522. )
  523. except ExportValidationError as e:
  524. raise HTTPException(status_code=400, detail=str(e)) from e
  525. @router.post("/approved-by-me/export")
  526. def export_approved_by_me_reimburses(
  527. body: BxApplyListExportBody,
  528. db: Session = Depends(get_db),
  529. user: BxUserContext = Depends(get_bx_current_user),
  530. ):
  531. try:
  532. tenant_no = _tenant(db, user)
  533. params = _body_to_params(body)
  534. extra_filters = _filters_from_params(params, db=db, tenant_no=tenant_no)
  535. rows, _ = ReimburseService.approved_by_me(
  536. db,
  537. user,
  538. tenant_no,
  539. page=1,
  540. page_size=EXPORT_MAX_ROWS,
  541. extra_filters=extra_filters,
  542. order_by=_reimburse_order(params),
  543. )
  544. return respond_xlsx(
  545. db,
  546. tenant_no=tenant_no,
  547. sheet_title="报销已审批",
  548. columns=REIMBURSE_EXPORT_COLUMNS,
  549. rows=_export_reimburse_rows(db, tenant_no, rows),
  550. filename_stem="报销已审批",
  551. requested_columns=body.columns,
  552. )
  553. except ExportValidationError as e:
  554. raise HTTPException(status_code=400, detail=str(e)) from e
  555. @router.get("/{reimburse_id}", response_model=ApiResponse[ReimburseApplyOut])
  556. def get_reimburse(
  557. reimburse_id: str,
  558. db: Session = Depends(get_db),
  559. user: BxUserContext = Depends(get_bx_current_user),
  560. ):
  561. tenant_no = _tenant(db, user)
  562. reimburse = ReimburseService.get_by_id(db, reimburse_id, tenant_no, user=user)
  563. if not reimburse:
  564. raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="报销单不存在")
  565. out = ReimburseService.build_apply_out_with_details(db, tenant_no, reimburse)
  566. return ApiResponse(data=out)
  567. @router.get("/{reimburse_id}/approvals", response_model=ApiResponse[List[ReimburseApprovalOut]])
  568. def get_approvals(
  569. reimburse_id: str,
  570. db: Session = Depends(get_db),
  571. user: BxUserContext = Depends(get_bx_current_user),
  572. ):
  573. tenant_no = _tenant(db, user)
  574. if not ReimburseService.get_by_id(db, reimburse_id, tenant_no, user=user):
  575. raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="报销单不存在")
  576. approvals = ReimburseService.get_approvals(db, reimburse_id, tenant_no, user=user)
  577. return ApiResponse(data=[ReimburseApprovalOut.model_validate(a) for a in approvals])
  578. @router.get("/{reimburse_id}/approval-history", response_model=ApiResponse[List[ReimburseApprovalOut]])
  579. def get_approval_history(
  580. reimburse_id: str,
  581. db: Session = Depends(get_db),
  582. user: BxUserContext = Depends(get_bx_current_user),
  583. ):
  584. tenant_no = _tenant(db, user)
  585. if not ReimburseService.get_by_id(db, reimburse_id, tenant_no, user=user):
  586. raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="报销单不存在")
  587. history = ReimburseService.get_approval_history(db, reimburse_id, tenant_no, user=user)
  588. return ApiResponse(data=[ReimburseApprovalOut.model_validate(a) for a in history])
  589. @router.post("/", response_model=ApiResponse[ReimburseApplyOut])
  590. def create_reimburse(
  591. body: ReimburseApplyCreate,
  592. db: Session = Depends(get_db),
  593. user: BxUserContext = Depends(get_bx_current_user),
  594. ):
  595. tenant_no = _tenant(db, user)
  596. details_data = _build_details_data(db, tenant_no, body.details, user=user)
  597. data = {
  598. "status": "draft",
  599. "remark": body.remark,
  600. "reimburse_date": body.reimburse_date,
  601. }
  602. if body.title:
  603. data["title"] = body.title
  604. wf = (
  605. db.query(BxWorkflowDef)
  606. .filter(
  607. BxWorkflowDef.biz_type == "reimburse",
  608. BxWorkflowDef.tenant_no == tenant_no,
  609. BxWorkflowDef.del_flag == 0,
  610. )
  611. .first()
  612. )
  613. if wf:
  614. data["wf_id"] = wf.id
  615. applicant_id, applicant_name = ReimburseService.resolve_applicant(
  616. db, user, body.applicant_id, tenant_no=tenant_no
  617. )
  618. reimburse = ReimburseService.create_with_details(
  619. db,
  620. data,
  621. details_data,
  622. user=user,
  623. applicant_id=applicant_id,
  624. applicant_name=applicant_name,
  625. )
  626. if body.invoice_links is not None or body.invoice_ids is not None:
  627. ReimburseService.sync_reimburse_invoices(
  628. db,
  629. reimburse.id,
  630. body.invoice_ids,
  631. tenant_no,
  632. user,
  633. applicant_id=applicant_id,
  634. invoice_links=body.invoice_links,
  635. )
  636. db.commit()
  637. db.refresh(reimburse)
  638. out = ReimburseService.build_apply_out_with_details(db, tenant_no, reimburse)
  639. return ApiResponse(data=out)
  640. @router.put("/{reimburse_id}", response_model=ApiResponse[ReimburseApplyOut])
  641. def update_reimburse(
  642. reimburse_id: str,
  643. body: ReimburseApplyUpdate,
  644. db: Session = Depends(get_db),
  645. user: BxUserContext = Depends(get_bx_current_user),
  646. ):
  647. tenant_no = _tenant(db, user)
  648. details_data = None
  649. if body.details is not None:
  650. details_data = _build_details_data(db, tenant_no, body.details, user=user)
  651. main_data = {}
  652. if body.remark is not None:
  653. main_data["remark"] = body.remark
  654. if body.reimburse_date is not None:
  655. main_data["reimburse_date"] = body.reimburse_date
  656. if body.title is not None:
  657. main_data["title"] = body.title
  658. if body.applicant_id is not None:
  659. applicant_id, applicant_name = ReimburseService.resolve_applicant(
  660. db, user, body.applicant_id, tenant_no=tenant_no
  661. )
  662. main_data["applicant_id"] = applicant_id
  663. main_data["applicant_name"] = applicant_name
  664. reimburse = ReimburseService.update_with_details(
  665. db, reimburse_id, main_data, details_data, user=user
  666. )
  667. if not reimburse:
  668. raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="报销单不存在")
  669. if body.invoice_links is not None or body.invoice_ids is not None:
  670. ReimburseService.sync_reimburse_invoices(
  671. db,
  672. reimburse_id,
  673. body.invoice_ids,
  674. tenant_no,
  675. user,
  676. applicant_id=reimburse.applicant_id,
  677. invoice_links=body.invoice_links,
  678. )
  679. db.commit()
  680. db.refresh(reimburse)
  681. out = ReimburseService.build_apply_out_with_details(db, tenant_no, reimburse)
  682. return ApiResponse(data=out)
  683. @router.post("/{reimburse_id}/submit", response_model=ApiResponse[ReimburseApplyOut])
  684. def submit_reimburse(
  685. reimburse_id: str,
  686. body: ReimburseSubmitBody = ReimburseSubmitBody(),
  687. db: Session = Depends(get_db),
  688. user: BxUserContext = Depends(get_bx_current_user),
  689. ):
  690. tenant_no = _tenant(db, user)
  691. reimburse = ReimburseService.submit(
  692. db,
  693. reimburse_id,
  694. user,
  695. invoice_ids=body.invoice_ids,
  696. invoice_links=body.invoice_links,
  697. )
  698. if not reimburse:
  699. raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="报销单不存在")
  700. db.commit()
  701. db.refresh(reimburse)
  702. return ApiResponse(data=ReimburseService.build_apply_out_with_details(db, tenant_no, reimburse))
  703. @router.post("/{reimburse_id}/approve", response_model=ApiResponse[ReimburseApplyOut])
  704. def approve_reimburse(
  705. reimburse_id: str,
  706. body: ReimburseApprovalCreate,
  707. db: Session = Depends(get_db),
  708. user: BxUserContext = Depends(get_bx_current_user),
  709. ):
  710. tenant_no = _tenant(db, user)
  711. reimburse = ReimburseService.approve(db, reimburse_id, user, body.approval_opinion or "")
  712. if not reimburse:
  713. raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="报销单不存在或无权审批")
  714. db.commit()
  715. db.refresh(reimburse)
  716. return ApiResponse(data=ReimburseService.out_one_with_attachment_counts(db, tenant_no, reimburse))
  717. @router.post("/{reimburse_id}/reject", response_model=ApiResponse[ReimburseApplyOut])
  718. def reject_reimburse(
  719. reimburse_id: str,
  720. body: ReimburseApprovalCreate,
  721. db: Session = Depends(get_db),
  722. user: BxUserContext = Depends(get_bx_current_user),
  723. ):
  724. tenant_no = _tenant(db, user)
  725. reimburse = ReimburseService.reject(db, reimburse_id, user, body.approval_opinion or "")
  726. if not reimburse:
  727. raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="报销单不存在或无权审批")
  728. db.commit()
  729. db.refresh(reimburse)
  730. return ApiResponse(data=ReimburseService.out_one_with_attachment_counts(db, tenant_no, reimburse))
  731. @router.post("/{reimburse_id}/withdraw", response_model=ApiResponse[ReimburseApplyOut])
  732. def withdraw_reimburse(
  733. reimburse_id: str,
  734. db: Session = Depends(get_db),
  735. user: BxUserContext = Depends(get_bx_current_user),
  736. ):
  737. tenant_no = _tenant(db, user)
  738. reimburse = ReimburseService.withdraw(db, reimburse_id, user)
  739. if not reimburse:
  740. raise HTTPException(
  741. status_code=status.HTTP_400_BAD_REQUEST,
  742. detail="报销单不存在、非本人申请或当前状态不可撤回",
  743. )
  744. db.commit()
  745. db.refresh(reimburse)
  746. return ApiResponse(data=ReimburseService.build_apply_out_with_details(db, tenant_no, reimburse))
  747. @router.delete("/{reimburse_id}", response_model=ApiResponse[None])
  748. def delete_reimburse(
  749. reimburse_id: str,
  750. db: Session = Depends(get_db),
  751. user: BxUserContext = Depends(get_bx_current_user),
  752. ):
  753. tenant_no = _tenant(db, user)
  754. if not ReimburseService.get_by_id(db, reimburse_id, tenant_no, user=user):
  755. raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="报销单不存在")
  756. ReimburseService.soft_delete(db, reimburse_id, user=user)
  757. db.commit()
  758. return ApiResponse(data=None)