invoice.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. from __future__ import annotations
  2. import mimetypes
  3. from decimal import Decimal
  4. from typing import List, Optional, Sequence, Tuple
  5. from fastapi import HTTPException, status
  6. from sqlalchemy import or_
  7. from sqlalchemy.orm import Session
  8. from app.core.bx_auth import BxUserContext
  9. from app.core.menu_guard import SUPER_ADMIN_ROLE
  10. from app.core.tenant_context import get_tenant_no
  11. from app.models.bx_models import BxAttachment, BxInvoice, BxInvoiceLedger, BxInvoiceWalletSummary
  12. from app.models.models import SysUser
  13. from app.services.bx.attachment import AttachmentService
  14. from app.services.bx.base import BxCrudService
  15. from app.services.bx.invoice_ledger import (
  16. ENTRY_CREDIT_UPLOAD,
  17. ENTRY_DEBIT_DELETE,
  18. InvoiceLedgerService,
  19. )
  20. from app.services.bx.storage import upload_bx_file
  21. from app.services.web_auth_roles import iter_user_menu_perm_codes
  22. INVOICE_WALLET_ADMIN_PERM = "bx:invoiceWallet:admin"
  23. REIMBURSE_CHANGE_APPLICANT_PERM = "bx:reimburseApply:changeApplicant"
  24. class InvoiceService:
  25. @staticmethod
  26. def _tenant_no(db: Session, user: BxUserContext) -> str:
  27. return get_tenant_no(db, user.to_tenant_user_dict())
  28. @staticmethod
  29. def is_wallet_admin(db: Session, user: BxUserContext) -> bool:
  30. if user.role == SUPER_ADMIN_ROLE:
  31. return True
  32. codes = iter_user_menu_perm_codes(db, user.id, user.tenant_no)
  33. return INVOICE_WALLET_ADMIN_PERM in codes
  34. @staticmethod
  35. def can_query_others_wallet(db: Session, user: BxUserContext) -> bool:
  36. """发票夹管理 或 报销改选申请人 权限可查询他人发票/余额。"""
  37. if InvoiceService.is_wallet_admin(db, user):
  38. return True
  39. codes = iter_user_menu_perm_codes(db, user.id, user.tenant_no)
  40. return REIMBURSE_CHANGE_APPLICANT_PERM in set(codes)
  41. @staticmethod
  42. def _require_wallet_admin(db: Session, user: BxUserContext) -> None:
  43. if not InvoiceService.is_wallet_admin(db, user):
  44. raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="需要发票夹管理权限")
  45. @staticmethod
  46. def _lookup_user_name(db: Session, user_id: str) -> str:
  47. row = (
  48. db.query(SysUser)
  49. .filter(SysUser.id == user_id, SysUser.del_flag == 0)
  50. .first()
  51. )
  52. if not row:
  53. raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="目标用户不存在")
  54. return (row.nick_name or row.user_no or "").strip()
  55. @staticmethod
  56. def _resolve_owner(
  57. db: Session,
  58. user: BxUserContext,
  59. target_user_id: Optional[str],
  60. ) -> Tuple[str, str]:
  61. target = (target_user_id or "").strip()
  62. if not target or target == user.id:
  63. return user.id, user.name
  64. InvoiceService._require_wallet_admin(db, user)
  65. return target, InvoiceService._lookup_user_name(db, target)
  66. @staticmethod
  67. def _resolve_owner_for_query(
  68. db: Session,
  69. user: BxUserContext,
  70. user_id: Optional[str],
  71. ) -> str:
  72. owner_id = (user_id or "").strip() or user.id
  73. if owner_id != user.id and not InvoiceService.can_query_others_wallet(db, user):
  74. raise HTTPException(
  75. status_code=status.HTTP_403_FORBIDDEN,
  76. detail="无权查看他人发票夹",
  77. )
  78. return owner_id
  79. @staticmethod
  80. def _count_invoices(db: Session, tenant_no: str, owner_user_id: str) -> int:
  81. return (
  82. db.query(BxInvoice)
  83. .filter(
  84. BxInvoice.tenant_no == tenant_no,
  85. BxInvoice.owner_user_id == owner_user_id,
  86. BxInvoice.del_flag == 0,
  87. )
  88. .count()
  89. )
  90. @staticmethod
  91. def get_mine_summary(
  92. db: Session,
  93. *,
  94. user: BxUserContext,
  95. owner_user_id: Optional[str] = None,
  96. ) -> dict:
  97. tenant_no = InvoiceService._tenant_no(db, user)
  98. owner_id = InvoiceService._resolve_owner_for_query(db, user, owner_user_id)
  99. owner_name = (
  100. user.name
  101. if owner_id == user.id
  102. else InvoiceService._lookup_user_name(db, owner_id)
  103. )
  104. row = (
  105. db.query(BxInvoiceWalletSummary)
  106. .filter(
  107. BxInvoiceWalletSummary.tenant_no == tenant_no,
  108. BxInvoiceWalletSummary.owner_user_id == owner_id,
  109. BxInvoiceWalletSummary.del_flag == 0,
  110. )
  111. .first()
  112. )
  113. if row:
  114. return InvoiceService._summary_to_dict(row)
  115. totals = InvoiceLedgerService.calc_summary(db, tenant_no, owner_id)
  116. return {
  117. "id": "",
  118. "owner_user_id": owner_id,
  119. "owner_user_name": owner_name,
  120. "total_amount": totals["total_amount"],
  121. "used_amount": totals["used_amount"],
  122. "balance": totals["balance"],
  123. "invoice_count": InvoiceService._count_invoices(db, tenant_no, owner_id),
  124. "version": 0,
  125. "create_time": None,
  126. "update_time": None,
  127. }
  128. @staticmethod
  129. def list_wallets(
  130. db: Session,
  131. *,
  132. user: BxUserContext,
  133. page: int = 1,
  134. page_size: int = 10,
  135. keyword: str = "",
  136. ) -> Tuple[Sequence[BxInvoiceWalletSummary], int]:
  137. InvoiceService._require_wallet_admin(db, user)
  138. tenant_no = InvoiceService._tenant_no(db, user)
  139. query = db.query(BxInvoiceWalletSummary).filter(
  140. BxInvoiceWalletSummary.tenant_no == tenant_no,
  141. BxInvoiceWalletSummary.del_flag == 0,
  142. )
  143. kw = (keyword or "").strip()
  144. if kw:
  145. query = query.filter(
  146. or_(
  147. BxInvoiceWalletSummary.owner_user_name.contains(kw),
  148. BxInvoiceWalletSummary.owner_user_id.contains(kw),
  149. )
  150. )
  151. total = query.count()
  152. rows = (
  153. query.order_by(BxInvoiceWalletSummary.update_time.desc(), BxInvoiceWalletSummary.create_time.desc())
  154. .offset((page - 1) * page_size)
  155. .limit(page_size)
  156. .all()
  157. )
  158. return rows, total
  159. @staticmethod
  160. def list_invoices(
  161. db: Session,
  162. *,
  163. user: BxUserContext,
  164. owner_user_id: Optional[str] = None,
  165. page: int = 1,
  166. page_size: int = 10,
  167. ) -> Tuple[Sequence[BxInvoice], int]:
  168. tenant_no = InvoiceService._tenant_no(db, user)
  169. owner_id = InvoiceService._resolve_owner_for_query(db, user, owner_user_id)
  170. filters = [BxInvoice.owner_user_id == owner_id]
  171. rows, total = BxCrudService.get_paged(
  172. BxInvoice,
  173. db,
  174. tenant_no,
  175. page,
  176. page_size,
  177. filters=filters,
  178. user=user,
  179. )
  180. return rows, total
  181. @staticmethod
  182. def list_ledgers(
  183. db: Session,
  184. *,
  185. user: BxUserContext,
  186. owner_user_id: Optional[str] = None,
  187. ) -> List[BxInvoiceLedger]:
  188. tenant_no = InvoiceService._tenant_no(db, user)
  189. owner_id = InvoiceService._resolve_owner_for_query(db, user, owner_user_id)
  190. rows = InvoiceLedgerService.list_entries(db, tenant_no, owner_id)
  191. return list(reversed(rows))
  192. @staticmethod
  193. def create(
  194. db: Session,
  195. *,
  196. user: BxUserContext,
  197. amount: Decimal,
  198. files: Sequence[Tuple[bytes, str, str]],
  199. remark: Optional[str] = None,
  200. target_user_id: Optional[str] = None,
  201. ) -> BxInvoice:
  202. """一次上传创建一条发票档案:金额为总额,files 全部挂到同一 biz_id,只写一条 credit_upload。"""
  203. tenant_no = InvoiceService._tenant_no(db, user)
  204. owner_id, owner_name = InvoiceService._resolve_owner(db, user, target_user_id)
  205. amt = Decimal(str(amount))
  206. if amt <= 0:
  207. raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="金额必须大于0")
  208. if not files:
  209. raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="请选择文件")
  210. invoice = BxCrudService.create(
  211. BxInvoice,
  212. db,
  213. {
  214. "owner_user_id": owner_id,
  215. "owner_user_name": owner_name,
  216. "amount": amt,
  217. "upload_by": user.id,
  218. "upload_by_name": user.name,
  219. "remark": (remark or "").strip() or None,
  220. },
  221. tenant_no=tenant_no,
  222. user_id=user.id,
  223. dept_id=user.dept_id,
  224. )
  225. for file_data, filename, content_type in files:
  226. if not file_data:
  227. raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="文件内容为空")
  228. safe_name = filename or "unknown"
  229. mime = content_type or mimetypes.guess_type(safe_name)[0] or "application/octet-stream"
  230. relative_path, _full_url = upload_bx_file(file_data, safe_name, biz_type="invoice")
  231. AttachmentService.create(
  232. db,
  233. {
  234. "biz_type": "invoice",
  235. "biz_id": invoice.id,
  236. "file_name": safe_name,
  237. "file_path": relative_path,
  238. "file_type": mime,
  239. "file_size": len(file_data),
  240. "attach_type": "invoice",
  241. },
  242. user=user,
  243. )
  244. InvoiceLedgerService.add_entry(
  245. db,
  246. tenant_no=tenant_no,
  247. owner_user_id=owner_id,
  248. entry_type=ENTRY_CREDIT_UPLOAD,
  249. amount=amt,
  250. user=user,
  251. invoice_id=invoice.id,
  252. )
  253. invoice_count = InvoiceService._count_invoices(db, tenant_no, owner_id)
  254. InvoiceLedgerService.refresh_summary(
  255. db,
  256. tenant_no,
  257. owner_id,
  258. owner_name,
  259. invoice_count,
  260. user.id,
  261. user.dept_id,
  262. )
  263. return invoice
  264. @staticmethod
  265. def delete(db: Session, *, user: BxUserContext, invoice_id: str) -> bool:
  266. InvoiceService._require_wallet_admin(db, user)
  267. tenant_no = InvoiceService._tenant_no(db, user)
  268. invoice = BxCrudService.get_by_id(
  269. BxInvoice, db, invoice_id, tenant_no, user=user, skip_scope=True
  270. )
  271. if not invoice:
  272. raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="发票不存在")
  273. InvoiceLedgerService.assert_can_delete_invoice(
  274. db, tenant_no, invoice.owner_user_id, invoice.amount
  275. )
  276. InvoiceLedgerService.add_entry(
  277. db,
  278. tenant_no=tenant_no,
  279. owner_user_id=invoice.owner_user_id,
  280. entry_type=ENTRY_DEBIT_DELETE,
  281. amount=Decimal(str(invoice.amount)),
  282. user=user,
  283. invoice_id=invoice.id,
  284. )
  285. invoice.del_flag = 1
  286. invoice.update_by = user.id
  287. db.query(BxAttachment).filter(
  288. BxAttachment.biz_type == "invoice",
  289. BxAttachment.biz_id == invoice.id,
  290. BxAttachment.tenant_no == tenant_no,
  291. BxAttachment.del_flag == 0,
  292. ).update(
  293. {BxAttachment.del_flag: 1, BxAttachment.update_by: user.id},
  294. synchronize_session="fetch",
  295. )
  296. db.flush()
  297. invoice_count = InvoiceService._count_invoices(db, tenant_no, invoice.owner_user_id)
  298. InvoiceLedgerService.refresh_summary(
  299. db,
  300. tenant_no,
  301. invoice.owner_user_id,
  302. invoice.owner_user_name,
  303. invoice_count,
  304. user.id,
  305. user.dept_id,
  306. )
  307. return True
  308. @staticmethod
  309. def _summary_to_dict(row: BxInvoiceWalletSummary) -> dict:
  310. return {
  311. "id": row.id,
  312. "owner_user_id": row.owner_user_id,
  313. "owner_user_name": row.owner_user_name,
  314. "total_amount": row.total_amount,
  315. "used_amount": row.used_amount,
  316. "balance": row.balance,
  317. "invoice_count": row.invoice_count,
  318. "version": row.version,
  319. "create_time": row.create_time,
  320. "update_time": row.update_time,
  321. }
  322. @staticmethod
  323. def out_rows_with_attachments(
  324. db: Session, tenant_no: str, invoices: Sequence[BxInvoice]
  325. ) -> List[dict]:
  326. if not invoices:
  327. return []
  328. ids = [inv.id for inv in invoices]
  329. attachments = (
  330. db.query(BxAttachment)
  331. .filter(
  332. BxAttachment.biz_type == "invoice",
  333. BxAttachment.biz_id.in_(ids),
  334. BxAttachment.tenant_no == tenant_no,
  335. BxAttachment.del_flag == 0,
  336. )
  337. .order_by(BxAttachment.create_time.asc())
  338. .all()
  339. )
  340. att_map: dict[str, List[BxAttachment]] = {}
  341. for att in attachments:
  342. att_map.setdefault(att.biz_id, []).append(att)
  343. out: List[dict] = []
  344. for inv in invoices:
  345. atts = att_map.get(inv.id, [])
  346. first = atts[0] if atts else None
  347. out.append(
  348. {
  349. "id": inv.id,
  350. "owner_user_id": inv.owner_user_id,
  351. "owner_user_name": inv.owner_user_name,
  352. "amount": inv.amount,
  353. "upload_by": inv.upload_by,
  354. "upload_by_name": inv.upload_by_name,
  355. "remark": inv.remark,
  356. "create_time": inv.create_time,
  357. "update_time": inv.update_time,
  358. "attachment_id": first.id if first else None,
  359. "file_name": first.file_name if first else None,
  360. "file_path": first.file_path if first else None,
  361. "file_type": first.file_type if first else None,
  362. "attachments": [
  363. {
  364. "id": a.id,
  365. "file_name": a.file_name,
  366. "file_path": a.file_path,
  367. "file_type": a.file_type,
  368. }
  369. for a in atts
  370. ],
  371. }
  372. )
  373. return out