invoice.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. import mimetypes
  2. from typing import Any, List, Optional, Set
  3. from fastapi import APIRouter, Depends, HTTPException, Request, status, Query
  4. from pydantic import ConfigDict
  5. from sqlalchemy.orm import Session
  6. from starlette.datastructures import UploadFile as StarletteUploadFile
  7. from app.api.bx.export_common import (
  8. EXPORT_MAX_ROWS,
  9. ExportColumn,
  10. ExportValidationError,
  11. BxExportBodyBase,
  12. dump_export_row,
  13. respond_xlsx,
  14. )
  15. from app.core.bx_auth import BxUserContext, get_bx_current_user
  16. from app.core.tenant_context import get_tenant_no
  17. from app.core.database import get_db
  18. from app.schemas.bx.common import ApiResponse, PagedData
  19. from app.schemas.bx.invoice import InvoiceOut, LedgerOut, WalletSummaryOut
  20. from app.services.bx.invoice import InvoiceService
  21. from app.services.bx.invoice_list_filters import (
  22. build_invoice_column_filters,
  23. build_ledger_column_filters,
  24. build_wallet_column_filters,
  25. )
  26. from app.services.bx.list_sort import order_invoice, order_ledger, parse_sort_params
  27. router = APIRouter(tags=["发票夹"])
  28. def _merge_query(request: Request, **known) -> dict:
  29. out = {k: v for k, v in known.items() if v is not None and v != ""}
  30. for k, v in request.query_params.multi_items():
  31. if k in ("page", "pageSize"):
  32. continue
  33. if k not in out and v not in (None, ""):
  34. out[k] = v
  35. return out
  36. def _param_get(params: dict, *keys: str) -> Any:
  37. for key in keys:
  38. if key in params and params[key] not in (None, ""):
  39. return params[key]
  40. return None
  41. def _wallet_filters_from_params(params: dict) -> list:
  42. return build_wallet_column_filters(
  43. keyword=str(_param_get(params, "keyword") or ""),
  44. owner_user_name=_param_get(params, "ownerUserName", "owner_user_name"),
  45. total_amount_op=_param_get(params, "totalAmountOp", "total_amount_op"),
  46. total_amount=_param_get(params, "totalAmount", "total_amount"),
  47. total_amount_min=_param_get(params, "totalAmountMin", "total_amount_min"),
  48. total_amount_max=_param_get(params, "totalAmountMax", "total_amount_max"),
  49. used_amount_op=_param_get(params, "usedAmountOp", "used_amount_op"),
  50. used_amount=_param_get(params, "usedAmount", "used_amount"),
  51. used_amount_min=_param_get(params, "usedAmountMin", "used_amount_min"),
  52. used_amount_max=_param_get(params, "usedAmountMax", "used_amount_max"),
  53. balance_op=_param_get(params, "balanceOp", "balance_op"),
  54. balance=_param_get(params, "balance"),
  55. balance_min=_param_get(params, "balanceMin", "balance_min"),
  56. balance_max=_param_get(params, "balanceMax", "balance_max"),
  57. invoice_count_op=_param_get(params, "invoiceCountOp", "invoice_count_op"),
  58. invoice_count=_param_get(params, "invoiceCount", "invoice_count"),
  59. invoice_count_min=_param_get(params, "invoiceCountMin", "invoice_count_min"),
  60. invoice_count_max=_param_get(params, "invoiceCountMax", "invoice_count_max"),
  61. )
  62. def _invoice_filters_from_params(params: dict, *, tenant_no: str = "") -> list:
  63. return build_invoice_column_filters(
  64. tenant_no=tenant_no,
  65. keyword=str(_param_get(params, "keyword") or ""),
  66. amount_op=_param_get(params, "amountOp", "amount_op"),
  67. amount=_param_get(params, "amount"),
  68. amount_min=_param_get(params, "amountMin", "amount_min"),
  69. amount_max=_param_get(params, "amountMax", "amount_max"),
  70. remark=_param_get(params, "remark"),
  71. upload_by_name=_param_get(params, "uploadByName", "upload_by_name"),
  72. create_time_from=_param_get(params, "createTimeFrom", "create_time_from"),
  73. create_time_to=_param_get(params, "createTimeTo", "create_time_to"),
  74. )
  75. def _ledger_filters_from_params(params: dict) -> list:
  76. return build_ledger_column_filters(
  77. keyword=str(_param_get(params, "keyword") or ""),
  78. entry_type=_param_get(params, "entryType", "entry_type"),
  79. entry_type_in=_param_get(params, "entryTypeIn", "entry_type_in"),
  80. amount_op=_param_get(params, "amountOp", "amount_op"),
  81. amount=_param_get(params, "amount"),
  82. amount_min=_param_get(params, "amountMin", "amount_min"),
  83. amount_max=_param_get(params, "amountMax", "amount_max"),
  84. remark=_param_get(params, "remark"),
  85. create_time_from=_param_get(params, "createTimeFrom", "create_time_from"),
  86. create_time_to=_param_get(params, "createTimeTo", "create_time_to"),
  87. )
  88. def _body_to_params(body: BxExportBodyBase) -> dict:
  89. data = body.model_dump(by_alias=True, exclude_none=True)
  90. extra = getattr(body, "model_extra", None) or {}
  91. for key, value in extra.items():
  92. if key not in data and value not in (None, ""):
  93. data[key] = value
  94. return data
  95. @router.get("/invoice-wallets/mine/summary", response_model=ApiResponse[WalletSummaryOut])
  96. def get_mine_wallet_summary(
  97. userId: Optional[str] = None,
  98. db: Session = Depends(get_db),
  99. user: BxUserContext = Depends(get_bx_current_user),
  100. ):
  101. data = InvoiceService.get_mine_summary(db, user=user, owner_user_id=userId)
  102. return ApiResponse(data=WalletSummaryOut.model_validate(data))
  103. @router.get("/invoice-wallets", response_model=ApiResponse[PagedData[WalletSummaryOut]])
  104. def list_invoice_wallets(
  105. request: Request,
  106. page: int = 1,
  107. pageSize: int = Query(10, ge=1, le=500),
  108. keyword: str = "",
  109. db: Session = Depends(get_db),
  110. user: BxUserContext = Depends(get_bx_current_user),
  111. ):
  112. params = _merge_query(request, keyword=keyword or None)
  113. extra_filters = _wallet_filters_from_params(params)
  114. rows, total = InvoiceService.list_wallets(
  115. db,
  116. user=user,
  117. page=page,
  118. page_size=pageSize,
  119. keyword="",
  120. extra_filters=extra_filters or None,
  121. )
  122. out_rows = [WalletSummaryOut.model_validate(InvoiceService._summary_to_dict(r)) for r in rows]
  123. return ApiResponse(data=PagedData(rows=out_rows, total=total, page=page, page_size=pageSize))
  124. WALLET_EXPORT_COLUMNS = [
  125. ExportColumn(title="员工", field="ownerUserName"),
  126. ExportColumn(title="总额(元)", field="totalAmount"),
  127. ExportColumn(title="已报销占用(元)", field="usedAmount"),
  128. ExportColumn(title="余额(元)", field="balance"),
  129. ExportColumn(title="发票张数", field="invoiceCount"),
  130. ]
  131. class WalletExportBody(BxExportBodyBase):
  132. model_config = ConfigDict(populate_by_name=True, extra="allow")
  133. keyword: str = ""
  134. @router.post("/invoice-wallets/export")
  135. def export_invoice_wallets(
  136. body: WalletExportBody,
  137. db: Session = Depends(get_db),
  138. user: BxUserContext = Depends(get_bx_current_user),
  139. ):
  140. try:
  141. tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
  142. params = _body_to_params(body)
  143. extra_filters = _wallet_filters_from_params(params)
  144. rows, _ = InvoiceService.list_wallets(
  145. db,
  146. user=user,
  147. page=1,
  148. page_size=EXPORT_MAX_ROWS,
  149. keyword="",
  150. extra_filters=extra_filters or None,
  151. )
  152. outs = [WalletSummaryOut.model_validate(InvoiceService._summary_to_dict(r)) for r in rows]
  153. if body.ids:
  154. id_set = {str(i) for i in body.ids}
  155. # wallet may key by ownerUserId
  156. outs = [o for o in outs if str(getattr(o, "owner_user_id", None) or getattr(o, "id", "")) in id_set or str(o.model_dump(by_alias=True).get("ownerUserId") or o.model_dump(by_alias=True).get("id") or "") in id_set]
  157. export_rows = [dump_export_row(o, status_fields=()) for o in outs]
  158. return respond_xlsx(
  159. db, tenant_no=tenant_no, sheet_title="发票夹", columns=WALLET_EXPORT_COLUMNS,
  160. rows=export_rows, filename_stem="发票夹汇总", requested_columns=body.columns,
  161. )
  162. except ExportValidationError as e:
  163. raise HTTPException(status_code=400, detail=str(e)) from e
  164. @router.get("/invoices", response_model=ApiResponse[PagedData[InvoiceOut]])
  165. def list_invoices(
  166. request: Request,
  167. page: int = 1,
  168. pageSize: int = Query(10, ge=1, le=500),
  169. userId: Optional[str] = None,
  170. keyword: str = "",
  171. db: Session = Depends(get_db),
  172. user: BxUserContext = Depends(get_bx_current_user),
  173. ):
  174. tenant_no = InvoiceService._tenant_no(db, user)
  175. params = _merge_query(request, userId=userId, keyword=keyword or None)
  176. extra_filters = _invoice_filters_from_params(params, tenant_no=tenant_no)
  177. sf, so = parse_sort_params(params)
  178. rows, total = InvoiceService.list_invoices(
  179. db,
  180. user=user,
  181. owner_user_id=userId,
  182. page=page,
  183. page_size=pageSize,
  184. extra_filters=extra_filters or None,
  185. order_by=order_invoice(sf, so),
  186. )
  187. out_rows = InvoiceService.out_rows_with_attachments(db, tenant_no, list(rows))
  188. return ApiResponse(
  189. data=PagedData(
  190. rows=[InvoiceOut.model_validate(r) for r in out_rows],
  191. total=total,
  192. page=page,
  193. page_size=pageSize,
  194. )
  195. )
  196. @router.post("/invoices", response_model=ApiResponse[InvoiceOut])
  197. async def create_invoice(
  198. request: Request,
  199. db: Session = Depends(get_db),
  200. user: BxUserContext = Depends(get_bx_current_user),
  201. ):
  202. """一次上传一条发票:多文件挂同一档案,金额为总额,只写一条额度流水。
  203. 使用 request.form().getlist,兼容只传 1 个文件时 FastAPI List[UploadFile] 的 422。
  204. """
  205. form = await request.form()
  206. amount_raw = form.get("amount")
  207. if amount_raw is None or str(amount_raw).strip() == "":
  208. raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="请填写金额")
  209. try:
  210. amount = float(amount_raw)
  211. except (TypeError, ValueError) as exc:
  212. raise HTTPException(
  213. status_code=status.HTTP_400_BAD_REQUEST, detail="金额格式不正确"
  214. ) from exc
  215. remark = str(form.get("remark") or "")
  216. target_raw = form.get("targetUserId")
  217. target_user_id = str(target_raw).strip() if target_raw not in (None, "") else None
  218. upload_files: List[StarletteUploadFile] = []
  219. seen_ids: Set[int] = set()
  220. for key in ("files", "file"):
  221. for item in form.getlist(key):
  222. if not isinstance(item, StarletteUploadFile):
  223. continue
  224. obj_id = id(item)
  225. if obj_id in seen_ids:
  226. continue
  227. seen_ids.add(obj_id)
  228. upload_files.append(item)
  229. if not upload_files:
  230. raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="请选择文件")
  231. file_payload = []
  232. for uf in upload_files:
  233. if not uf.filename:
  234. continue
  235. data = await uf.read()
  236. content_type = (
  237. uf.content_type
  238. or mimetypes.guess_type(uf.filename or "")[0]
  239. or "application/octet-stream"
  240. )
  241. file_payload.append((data, uf.filename or "unknown", content_type))
  242. if not file_payload:
  243. raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="请选择文件")
  244. try:
  245. invoice = InvoiceService.create(
  246. db,
  247. user=user,
  248. amount=amount,
  249. files=file_payload,
  250. remark=remark,
  251. target_user_id=target_user_id,
  252. )
  253. db.commit()
  254. db.refresh(invoice)
  255. except HTTPException:
  256. db.rollback()
  257. raise
  258. except Exception as exc:
  259. db.rollback()
  260. raise HTTPException(
  261. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="上传发票失败"
  262. ) from exc
  263. tenant_no = InvoiceService._tenant_no(db, user)
  264. out = InvoiceService.out_rows_with_attachments(db, tenant_no, [invoice])[0]
  265. return ApiResponse(data=InvoiceOut.model_validate(out))
  266. @router.delete("/invoices/{invoice_id}", response_model=ApiResponse[bool])
  267. def delete_invoice(
  268. invoice_id: str,
  269. db: Session = Depends(get_db),
  270. user: BxUserContext = Depends(get_bx_current_user),
  271. ):
  272. try:
  273. success = InvoiceService.delete(db, user=user, invoice_id=invoice_id)
  274. db.commit()
  275. except HTTPException:
  276. db.rollback()
  277. raise
  278. return ApiResponse(data=success)
  279. @router.get("/invoice-ledgers", response_model=ApiResponse[List[LedgerOut]])
  280. def list_invoice_ledgers(
  281. request: Request,
  282. userId: Optional[str] = None,
  283. keyword: str = "",
  284. db: Session = Depends(get_db),
  285. user: BxUserContext = Depends(get_bx_current_user),
  286. ):
  287. params = _merge_query(request, userId=userId, keyword=keyword or None)
  288. extra_filters = _ledger_filters_from_params(params)
  289. sf, so = parse_sort_params(params)
  290. rows = InvoiceService.list_ledgers(
  291. db,
  292. user=user,
  293. owner_user_id=userId,
  294. extra_filters=extra_filters or None,
  295. order_by=order_ledger(sf, so),
  296. )
  297. return ApiResponse(data=[LedgerOut.model_validate(r) for r in rows])