import io from datetime import date as date_cls from typing import List, Optional from urllib.parse import quote from fastapi import APIRouter, Depends, File, HTTPException, Query, UploadFile, status from fastapi.responses import StreamingResponse from sqlalchemy import or_ from sqlalchemy.orm import Session from app.api.bx.export_common import ( EXPORT_MAX_ROWS, ExportColumn, ExportValidationError, BxApplyListExportBody, dump_export_row, respond_xlsx, ) from app.core.bx_auth import BxUserContext, get_bx_current_user from app.core.database import get_db from app.core.tenant_context import get_tenant_no from app.models.bx_models import BxReimburseApply, BxWorkflowDef from app.schemas.bx.common import ApiResponse, PagedData from app.schemas.bx.reimburse import ( ReimburseApplyCreate, ReimburseApplyOut, ReimburseApplyUpdate, ReimburseApprovalCreate, ReimburseApprovalOut, ReimburseApproverPendingStatsOut, ReimburseMyStatsOut, ReimburseSubmitBody, ) from app.services.bx.expense_item import ExpenseItemService from app.services.bx.reimburse import ReimburseService from app.services.bx.reimburse_import import ( build_applicant_label, build_import_template_bytes, import_reimburse_workbook, load_applicant_options, load_expense_nodes_flat, ) from app.utils.bx_codegen import generate_apply_code, generate_title, parse_optional_date from app.utils.bx_date_range import append_create_time_filters router = APIRouter(prefix="/reimburses", tags=["报销管理"]) def _tenant(db: Session, user: BxUserContext) -> str: return get_tenant_no(db, user.to_tenant_user_dict()) REIMBURSE_EXPORT_COLUMNS = [ ExportColumn(title="申请单号", field="applyCode"), ExportColumn(title="申请时间", field="applyTime"), ExportColumn(title="申请人", field="applicantName"), ExportColumn(title="报销主题", field="title"), ExportColumn(title="费用科目", field="expenseName"), ExportColumn(title="金额(元)", field="amount"), ExportColumn(title="状态", field="status"), ExportColumn(title="当前节点", field="currentNode"), ] def _reimburse_list_filters(body: BxApplyListExportBody, db: Session, tenant_no: str) -> list: filters = [] if body.status: filters.append(BxReimburseApply.status == body.status) if body.keyword: filters.append( or_( BxReimburseApply.apply_code.contains(body.keyword), BxReimburseApply.applicant_name.contains(body.keyword), BxReimburseApply.title.contains(body.keyword), ) ) if body.expense_id: filters.append(BxReimburseApply.expense_id == str(body.expense_id).strip()) expense_filter = ReimburseService.build_expense_name_condition(db, tenant_no, body.expense_name) if expense_filter is not None: filters.append(expense_filter) if body.applicant_id: filters.append(BxReimburseApply.applicant_id == str(body.applicant_id).strip()) if body.ids: filters.append(BxReimburseApply.id.in_([str(i) for i in body.ids])) append_create_time_filters( filters, BxReimburseApply, apply_date=body.apply_date, apply_date_from=body.apply_date_from, apply_date_to=body.apply_date_to, ) return filters def _export_reimburse_rows(db: Session, tenant_no: str, rows) -> list: out_rows = ReimburseService.out_rows_with_attachment_counts(db, tenant_no, list(rows)) return [dump_export_row(r) for r in out_rows] def _build_details_data( db: Session, tenant_no: str, body_details, *, user: BxUserContext, ) -> List[dict]: details_data: List[dict] = [] for d in body_details: item = ExpenseItemService.get_by_id( db, d.expense_item_id, tenant_no, user=user, skip_scope=True ) if not item: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail=f"费用项目 {d.expense_item_id} 不存在", ) try: occur_date = parse_optional_date(d.occur_date) except ValueError: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="发生时间格式无效,请使用 YYYY-MM-DD", ) details_data.append( { "expense_id": d.expense_item_id, "expense_name": item.item_name, "amount": d.amount, "remark": d.remark, "occur_date": occur_date, } ) return details_data @router.get("/generate-title", response_model=ApiResponse[str]) def get_generated_title( reimburseDate: Optional[str] = None, excludeApplyId: Optional[str] = None, applicantId: Optional[str] = None, db: Session = Depends(get_db), user: BxUserContext = Depends(get_bx_current_user), ): tenant_no = _tenant(db, user) exclude_id = str(excludeApplyId).strip() if excludeApplyId else None _, applicant_name = ReimburseService.resolve_applicant( db, user, applicantId, tenant_no=tenant_no ) title = generate_title(db, applicant_name, tenant_no, reimburseDate, exclude_id) return ApiResponse(data=title) @router.get("/import-template") def download_reimburse_import_template( db: Session = Depends(get_db), user: BxUserContext = Depends(get_bx_current_user), ): tenant_no = _tenant(db, user) nodes = load_expense_nodes_flat(db, tenant_no) applicants = load_applicant_options(db, user=user, tenant_no=tenant_no) me = next((a for a in applicants if a["id"] == user.id), None) if me: cur_label = build_applicant_label(me["nick_name"], me["user_no"], me["id"]) else: cur_label = build_applicant_label(user.name or "", "", user.id) applicants = [ {"id": user.id, "nick_name": user.name or "", "user_no": ""} ] + applicants raw = build_import_template_bytes( expense_nodes=nodes, applicants=applicants, current_applicant_label=cur_label, today=date_cls.today(), ) filename = quote("报销申请导入模板.xlsx") return StreamingResponse( io.BytesIO(raw), media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", headers={ "Content-Disposition": f"attachment; filename={filename}; filename*=UTF-8''{filename}" }, ) @router.post("/import", response_model=ApiResponse[dict]) def import_reimburses( file: UploadFile = File(...), db: Session = Depends(get_db), user: BxUserContext = Depends(get_bx_current_user), ): content = file.file.read() if not content: raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="文件为空") try: result = import_reimburse_workbook(db, file_bytes=content, user=user) except ValueError as exc: raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)) from exc return ApiResponse(data=result) @router.get("/", response_model=ApiResponse[PagedData[ReimburseApplyOut]]) def list_reimburses( page: int = 1, pageSize: int = Query(10, ge=1, le=500), status: Optional[str] = None, keyword: str = "", expense_id: Optional[str] = None, expenseName: Optional[str] = None, applicantId: Optional[str] = None, applyDate: Optional[str] = None, applyDateFrom: Optional[str] = None, applyDateTo: Optional[str] = None, db: Session = Depends(get_db), user: BxUserContext = Depends(get_bx_current_user), ): tenant_no = _tenant(db, user) filters = [] if status: filters.append(BxReimburseApply.status == status) if keyword: filters.append( or_( BxReimburseApply.apply_code.contains(keyword), BxReimburseApply.applicant_name.contains(keyword), BxReimburseApply.title.contains(keyword), ) ) if expense_id: filters.append(BxReimburseApply.expense_id == str(expense_id).strip()) expense_filter = ReimburseService.build_expense_name_condition(db, tenant_no, expenseName) if expense_filter is not None: filters.append(expense_filter) if applicantId: filters.append(BxReimburseApply.applicant_id == str(applicantId).strip()) append_create_time_filters( filters, BxReimburseApply, apply_date=applyDate, apply_date_from=applyDateFrom, apply_date_to=applyDateTo, ) rows, total = ReimburseService.get_paged(db, tenant_no, page=page, page_size=pageSize, filters=filters, user=user) out_rows = ReimburseService.out_rows_with_attachment_counts(db, tenant_no, list(rows)) return ApiResponse(data=PagedData(rows=out_rows, total=total, page=page, page_size=pageSize)) @router.get("/my", response_model=ApiResponse[PagedData[ReimburseApplyOut]]) def my_reimburses( page: int = 1, pageSize: int = Query(10, ge=1, le=500), status: Optional[str] = None, keyword: str = "", expenseName: Optional[str] = None, applyDate: Optional[str] = None, applyDateFrom: Optional[str] = None, applyDateTo: Optional[str] = None, db: Session = Depends(get_db), user: BxUserContext = Depends(get_bx_current_user), ): tenant_no = _tenant(db, user) filters = [ or_( BxReimburseApply.applicant_id == user.id, BxReimburseApply.create_by == user.id, ) ] if status: filters.append(BxReimburseApply.status == status) if keyword: filters.append( or_( BxReimburseApply.apply_code.contains(keyword), BxReimburseApply.applicant_name.contains(keyword), BxReimburseApply.title.contains(keyword), ) ) expense_filter = ReimburseService.build_expense_name_condition(db, tenant_no, expenseName) if expense_filter is not None: filters.append(expense_filter) append_create_time_filters( filters, BxReimburseApply, apply_date=applyDate, apply_date_from=applyDateFrom, apply_date_to=applyDateTo, ) rows, total = ReimburseService.get_paged(db, tenant_no, page=page, page_size=pageSize, filters=filters, user=user) out_rows = ReimburseService.out_rows_with_attachment_counts(db, tenant_no, list(rows)) return ApiResponse(data=PagedData(rows=out_rows, total=total, page=page, page_size=pageSize)) @router.get("/my/stats", response_model=ApiResponse[ReimburseMyStatsOut]) def my_reimburse_stats( db: Session = Depends(get_db), user: BxUserContext = Depends(get_bx_current_user), ): tenant_no = _tenant(db, user) data = ReimburseService.my_apply_stats(db, user, tenant_no) return ApiResponse(data=ReimburseMyStatsOut.model_validate(data)) @router.get("/stats/status-counts", response_model=ApiResponse[dict]) def reimburse_status_counts( db: Session = Depends(get_db), user: BxUserContext = Depends(get_bx_current_user), ): tenant_no = _tenant(db, user) return ApiResponse(data=ReimburseService.global_status_counts(db, tenant_no, user=user)) @router.get("/pending-approval", response_model=ApiResponse[PagedData[ReimburseApplyOut]]) def pending_approval( page: int = 1, pageSize: int = Query(10, ge=1, le=500), keyword: str = "", applicantId: Optional[str] = None, expenseName: Optional[str] = None, applyDate: Optional[str] = None, applyDateFrom: Optional[str] = None, applyDateTo: Optional[str] = None, db: Session = Depends(get_db), user: BxUserContext = Depends(get_bx_current_user), ): tenant_no = _tenant(db, user) applicant_id = str(applicantId).strip() if applicantId else None rows, total = ReimburseService.pending_approval( db, user, tenant_no, page=page, page_size=pageSize, keyword=keyword, applicant_id=applicant_id, expense_name=expenseName, apply_date=applyDate, apply_date_from=applyDateFrom, apply_date_to=applyDateTo, ) out_rows = ReimburseService.out_rows_with_attachment_counts(db, tenant_no, list(rows)) return ApiResponse(data=PagedData(rows=out_rows, total=total, page=page, page_size=pageSize)) @router.get("/pending-approval/stats", response_model=ApiResponse[ReimburseApproverPendingStatsOut]) def pending_approval_stats( db: Session = Depends(get_db), user: BxUserContext = Depends(get_bx_current_user), ): tenant_no = _tenant(db, user) data = ReimburseService.pending_approval_stats(db, user, tenant_no) return ApiResponse(data=ReimburseApproverPendingStatsOut.model_validate(data)) @router.get("/approved-by-me", response_model=ApiResponse[PagedData[ReimburseApplyOut]]) def approved_by_me( page: int = 1, pageSize: int = Query(10, ge=1, le=500), keyword: str = "", applicantId: Optional[str] = None, expenseName: Optional[str] = None, applyDate: Optional[str] = None, applyDateFrom: Optional[str] = None, applyDateTo: Optional[str] = None, db: Session = Depends(get_db), user: BxUserContext = Depends(get_bx_current_user), ): tenant_no = _tenant(db, user) applicant_id = str(applicantId).strip() if applicantId else None rows, total = ReimburseService.approved_by_me( db, user, tenant_no, page=page, page_size=pageSize, keyword=keyword, applicant_id=applicant_id, expense_name=expenseName, apply_date=applyDate, apply_date_from=applyDateFrom, apply_date_to=applyDateTo, ) out_rows = ReimburseService.out_rows_with_attachment_counts(db, tenant_no, list(rows)) return ApiResponse(data=PagedData(rows=out_rows, total=total, page=page, page_size=pageSize)) @router.post("/export") def export_reimburses( body: BxApplyListExportBody, db: Session = Depends(get_db), user: BxUserContext = Depends(get_bx_current_user), ): try: tenant_no = _tenant(db, user) filters = _reimburse_list_filters(body, db, tenant_no) rows, _ = ReimburseService.get_paged( db, tenant_no, page=1, page_size=EXPORT_MAX_ROWS, filters=filters, user=user ) return respond_xlsx( db, tenant_no=tenant_no, sheet_title="报销申请", columns=REIMBURSE_EXPORT_COLUMNS, rows=_export_reimburse_rows(db, tenant_no, rows), filename_stem="报销申请", requested_columns=body.columns, ) except ExportValidationError as e: raise HTTPException(status_code=400, detail=str(e)) from e @router.post("/my/export") def export_my_reimburses( body: BxApplyListExportBody, db: Session = Depends(get_db), user: BxUserContext = Depends(get_bx_current_user), ): try: tenant_no = _tenant(db, user) filters = [ or_( BxReimburseApply.applicant_id == user.id, BxReimburseApply.create_by == user.id, ) ] filters.extend(_reimburse_list_filters(body, db, tenant_no)) rows, _ = ReimburseService.get_paged( db, tenant_no, page=1, page_size=EXPORT_MAX_ROWS, filters=filters, user=user ) return respond_xlsx( db, tenant_no=tenant_no, sheet_title="我的报销", columns=REIMBURSE_EXPORT_COLUMNS, rows=_export_reimburse_rows(db, tenant_no, rows), filename_stem="我的报销申请", requested_columns=body.columns, ) except ExportValidationError as e: raise HTTPException(status_code=400, detail=str(e)) from e @router.post("/pending-approval/export") def export_pending_approval_reimburses( body: BxApplyListExportBody, db: Session = Depends(get_db), user: BxUserContext = Depends(get_bx_current_user), ): try: tenant_no = _tenant(db, user) applicant_id = str(body.applicant_id).strip() if body.applicant_id else None rows, _ = ReimburseService.pending_approval( db, user, tenant_no, page=1, page_size=EXPORT_MAX_ROWS, keyword=body.keyword or "", applicant_id=applicant_id, expense_name=body.expense_name, apply_date=body.apply_date, apply_date_from=body.apply_date_from, apply_date_to=body.apply_date_to, ) if body.ids: id_set = {str(i) for i in body.ids} rows = [r for r in rows if str(r.id) in id_set] return respond_xlsx( db, tenant_no=tenant_no, sheet_title="报销待审批", columns=REIMBURSE_EXPORT_COLUMNS, rows=_export_reimburse_rows(db, tenant_no, rows), filename_stem="报销待审批", requested_columns=body.columns, ) except ExportValidationError as e: raise HTTPException(status_code=400, detail=str(e)) from e @router.post("/approved-by-me/export") def export_approved_by_me_reimburses( body: BxApplyListExportBody, db: Session = Depends(get_db), user: BxUserContext = Depends(get_bx_current_user), ): try: tenant_no = _tenant(db, user) applicant_id = str(body.applicant_id).strip() if body.applicant_id else None rows, _ = ReimburseService.approved_by_me( db, user, tenant_no, page=1, page_size=EXPORT_MAX_ROWS, keyword=body.keyword or "", applicant_id=applicant_id, expense_name=body.expense_name, apply_date=body.apply_date, apply_date_from=body.apply_date_from, apply_date_to=body.apply_date_to, ) if body.ids: id_set = {str(i) for i in body.ids} rows = [r for r in rows if str(r.id) in id_set] return respond_xlsx( db, tenant_no=tenant_no, sheet_title="报销已审批", columns=REIMBURSE_EXPORT_COLUMNS, rows=_export_reimburse_rows(db, tenant_no, rows), filename_stem="报销已审批", requested_columns=body.columns, ) except ExportValidationError as e: raise HTTPException(status_code=400, detail=str(e)) from e @router.get("/{reimburse_id}", response_model=ApiResponse[ReimburseApplyOut]) def get_reimburse( reimburse_id: str, db: Session = Depends(get_db), user: BxUserContext = Depends(get_bx_current_user), ): tenant_no = _tenant(db, user) reimburse = ReimburseService.get_by_id(db, reimburse_id, tenant_no, user=user) if not reimburse: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="报销单不存在") out = ReimburseService.build_apply_out_with_details(db, tenant_no, reimburse) return ApiResponse(data=out) @router.get("/{reimburse_id}/approvals", response_model=ApiResponse[List[ReimburseApprovalOut]]) def get_approvals( reimburse_id: str, db: Session = Depends(get_db), user: BxUserContext = Depends(get_bx_current_user), ): tenant_no = _tenant(db, user) if not ReimburseService.get_by_id(db, reimburse_id, tenant_no, user=user): raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="报销单不存在") approvals = ReimburseService.get_approvals(db, reimburse_id, tenant_no, user=user) return ApiResponse(data=[ReimburseApprovalOut.model_validate(a) for a in approvals]) @router.get("/{reimburse_id}/approval-history", response_model=ApiResponse[List[ReimburseApprovalOut]]) def get_approval_history( reimburse_id: str, db: Session = Depends(get_db), user: BxUserContext = Depends(get_bx_current_user), ): tenant_no = _tenant(db, user) if not ReimburseService.get_by_id(db, reimburse_id, tenant_no, user=user): raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="报销单不存在") history = ReimburseService.get_approval_history(db, reimburse_id, tenant_no, user=user) return ApiResponse(data=[ReimburseApprovalOut.model_validate(a) for a in history]) @router.post("/", response_model=ApiResponse[ReimburseApplyOut]) def create_reimburse( body: ReimburseApplyCreate, db: Session = Depends(get_db), user: BxUserContext = Depends(get_bx_current_user), ): tenant_no = _tenant(db, user) details_data = _build_details_data(db, tenant_no, body.details, user=user) data = { "apply_code": generate_apply_code(db, "BX", tenant_no), "status": "draft", "remark": body.remark, "reimburse_date": body.reimburse_date, } if body.title: data["title"] = body.title wf = ( db.query(BxWorkflowDef) .filter( BxWorkflowDef.biz_type == "reimburse", BxWorkflowDef.tenant_no == tenant_no, BxWorkflowDef.del_flag == 0, ) .first() ) if wf: data["wf_id"] = wf.id applicant_id, applicant_name = ReimburseService.resolve_applicant( db, user, body.applicant_id, tenant_no=tenant_no ) reimburse = ReimburseService.create_with_details( db, data, details_data, user=user, applicant_id=applicant_id, applicant_name=applicant_name, ) if body.invoice_links is not None or body.invoice_ids is not None: ReimburseService.sync_reimburse_invoices( db, reimburse.id, body.invoice_ids, tenant_no, user, applicant_id=applicant_id, invoice_links=body.invoice_links, ) db.commit() db.refresh(reimburse) out = ReimburseService.build_apply_out_with_details(db, tenant_no, reimburse) return ApiResponse(data=out) @router.put("/{reimburse_id}", response_model=ApiResponse[ReimburseApplyOut]) def update_reimburse( reimburse_id: str, body: ReimburseApplyUpdate, db: Session = Depends(get_db), user: BxUserContext = Depends(get_bx_current_user), ): tenant_no = _tenant(db, user) details_data = None if body.details is not None: details_data = _build_details_data(db, tenant_no, body.details, user=user) main_data = {} if body.remark is not None: main_data["remark"] = body.remark if body.reimburse_date is not None: main_data["reimburse_date"] = body.reimburse_date if body.title is not None: main_data["title"] = body.title if body.applicant_id is not None: applicant_id, applicant_name = ReimburseService.resolve_applicant( db, user, body.applicant_id, tenant_no=tenant_no ) main_data["applicant_id"] = applicant_id main_data["applicant_name"] = applicant_name reimburse = ReimburseService.update_with_details( db, reimburse_id, main_data, details_data, user=user ) if not reimburse: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="报销单不存在") if body.invoice_links is not None or body.invoice_ids is not None: ReimburseService.sync_reimburse_invoices( db, reimburse_id, body.invoice_ids, tenant_no, user, applicant_id=reimburse.applicant_id, invoice_links=body.invoice_links, ) db.commit() db.refresh(reimburse) out = ReimburseService.build_apply_out_with_details(db, tenant_no, reimburse) return ApiResponse(data=out) @router.post("/{reimburse_id}/submit", response_model=ApiResponse[ReimburseApplyOut]) def submit_reimburse( reimburse_id: str, body: ReimburseSubmitBody = ReimburseSubmitBody(), db: Session = Depends(get_db), user: BxUserContext = Depends(get_bx_current_user), ): tenant_no = _tenant(db, user) reimburse = ReimburseService.submit( db, reimburse_id, user, invoice_ids=body.invoice_ids, invoice_links=body.invoice_links, ) if not reimburse: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="报销单不存在") db.commit() db.refresh(reimburse) return ApiResponse(data=ReimburseService.build_apply_out_with_details(db, tenant_no, reimburse)) @router.post("/{reimburse_id}/approve", response_model=ApiResponse[ReimburseApplyOut]) def approve_reimburse( reimburse_id: str, body: ReimburseApprovalCreate, db: Session = Depends(get_db), user: BxUserContext = Depends(get_bx_current_user), ): tenant_no = _tenant(db, user) reimburse = ReimburseService.approve(db, reimburse_id, user, body.approval_opinion or "") if not reimburse: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="报销单不存在或无权审批") db.commit() db.refresh(reimburse) return ApiResponse(data=ReimburseService.out_one_with_attachment_counts(db, tenant_no, reimburse)) @router.post("/{reimburse_id}/reject", response_model=ApiResponse[ReimburseApplyOut]) def reject_reimburse( reimburse_id: str, body: ReimburseApprovalCreate, db: Session = Depends(get_db), user: BxUserContext = Depends(get_bx_current_user), ): tenant_no = _tenant(db, user) reimburse = ReimburseService.reject(db, reimburse_id, user, body.approval_opinion or "") if not reimburse: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="报销单不存在或无权审批") db.commit() db.refresh(reimburse) return ApiResponse(data=ReimburseService.out_one_with_attachment_counts(db, tenant_no, reimburse)) @router.post("/{reimburse_id}/withdraw", response_model=ApiResponse[ReimburseApplyOut]) def withdraw_reimburse( reimburse_id: str, db: Session = Depends(get_db), user: BxUserContext = Depends(get_bx_current_user), ): tenant_no = _tenant(db, user) reimburse = ReimburseService.withdraw(db, reimburse_id, user) if not reimburse: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="报销单不存在、非本人申请或当前状态不可撤回", ) db.commit() db.refresh(reimburse) return ApiResponse(data=ReimburseService.build_apply_out_with_details(db, tenant_no, reimburse)) @router.delete("/{reimburse_id}", response_model=ApiResponse[None]) def delete_reimburse( reimburse_id: str, db: Session = Depends(get_db), user: BxUserContext = Depends(get_bx_current_user), ): tenant_no = _tenant(db, user) if not ReimburseService.get_by_id(db, reimburse_id, tenant_no, user=user): raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="报销单不存在") ReimburseService.soft_delete(db, reimburse_id, user=user) db.commit() return ApiResponse(data=None)