| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552 |
- 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.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())
- 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 = 10,
- 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 = 10,
- 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 = 10,
- 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.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)
|