invoice.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  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[dict]:
  188. """返回流水字典列表;流水备注为空时回填关联发票备注(含已软删发票)。"""
  189. tenant_no = InvoiceService._tenant_no(db, user)
  190. owner_id = InvoiceService._resolve_owner_for_query(db, user, owner_user_id)
  191. rows = list(reversed(InvoiceLedgerService.list_entries(db, tenant_no, owner_id)))
  192. invoice_ids = {r.invoice_id for r in rows if r.invoice_id}
  193. inv_remark_map: dict[str, str] = {}
  194. if invoice_ids:
  195. inv_rows = (
  196. db.query(BxInvoice.id, BxInvoice.remark)
  197. .filter(BxInvoice.id.in_(list(invoice_ids)), BxInvoice.tenant_no == tenant_no)
  198. .all()
  199. )
  200. for inv_id, inv_remark in inv_rows:
  201. text = (inv_remark or "").strip()
  202. if text:
  203. inv_remark_map[inv_id] = text
  204. out: List[dict] = []
  205. for r in rows:
  206. remark = (r.remark or "").strip()
  207. if not remark and r.invoice_id:
  208. remark = inv_remark_map.get(r.invoice_id, "")
  209. out.append(
  210. {
  211. "id": r.id,
  212. "owner_user_id": r.owner_user_id,
  213. "entry_type": r.entry_type,
  214. "amount": r.amount,
  215. "invoice_id": r.invoice_id,
  216. "reimburse_id": r.reimburse_id,
  217. "ref_ledger_id": r.ref_ledger_id,
  218. "remark": remark or None,
  219. "create_time": r.create_time,
  220. }
  221. )
  222. return out
  223. @staticmethod
  224. def create(
  225. db: Session,
  226. *,
  227. user: BxUserContext,
  228. amount: Decimal,
  229. files: Sequence[Tuple[bytes, str, str]],
  230. remark: Optional[str] = None,
  231. target_user_id: Optional[str] = None,
  232. ) -> BxInvoice:
  233. """一次上传创建一条发票档案:金额为总额,files 全部挂到同一 biz_id,只写一条 credit_upload。"""
  234. tenant_no = InvoiceService._tenant_no(db, user)
  235. owner_id, owner_name = InvoiceService._resolve_owner(db, user, target_user_id)
  236. amt = Decimal(str(amount))
  237. if amt <= 0:
  238. raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="金额必须大于0")
  239. if not files:
  240. raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="请选择文件")
  241. invoice = BxCrudService.create(
  242. BxInvoice,
  243. db,
  244. {
  245. "owner_user_id": owner_id,
  246. "owner_user_name": owner_name,
  247. "amount": amt,
  248. "upload_by": user.id,
  249. "upload_by_name": user.name,
  250. "remark": (remark or "").strip() or None,
  251. },
  252. tenant_no=tenant_no,
  253. user_id=user.id,
  254. dept_id=user.dept_id,
  255. )
  256. for file_data, filename, content_type in files:
  257. if not file_data:
  258. raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="文件内容为空")
  259. safe_name = filename or "unknown"
  260. mime = content_type or mimetypes.guess_type(safe_name)[0] or "application/octet-stream"
  261. relative_path, _full_url = upload_bx_file(file_data, safe_name, biz_type="invoice")
  262. AttachmentService.create(
  263. db,
  264. {
  265. "biz_type": "invoice",
  266. "biz_id": invoice.id,
  267. "file_name": safe_name,
  268. "file_path": relative_path,
  269. "file_type": mime,
  270. "file_size": len(file_data),
  271. "attach_type": "invoice",
  272. },
  273. user=user,
  274. )
  275. InvoiceLedgerService.add_entry(
  276. db,
  277. tenant_no=tenant_no,
  278. owner_user_id=owner_id,
  279. entry_type=ENTRY_CREDIT_UPLOAD,
  280. amount=amt,
  281. user=user,
  282. invoice_id=invoice.id,
  283. remark=(remark or "").strip() or None,
  284. )
  285. invoice_count = InvoiceService._count_invoices(db, tenant_no, owner_id)
  286. InvoiceLedgerService.refresh_summary(
  287. db,
  288. tenant_no,
  289. owner_id,
  290. owner_name,
  291. invoice_count,
  292. user.id,
  293. user.dept_id,
  294. )
  295. return invoice
  296. @staticmethod
  297. def delete(db: Session, *, user: BxUserContext, invoice_id: str) -> bool:
  298. InvoiceService._require_wallet_admin(db, user)
  299. tenant_no = InvoiceService._tenant_no(db, user)
  300. invoice = BxCrudService.get_by_id(
  301. BxInvoice, db, invoice_id, tenant_no, user=user, skip_scope=True
  302. )
  303. if not invoice:
  304. raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="发票不存在")
  305. InvoiceLedgerService.assert_can_delete_invoice(
  306. db, tenant_no, invoice.owner_user_id, invoice.amount
  307. )
  308. InvoiceLedgerService.add_entry(
  309. db,
  310. tenant_no=tenant_no,
  311. owner_user_id=invoice.owner_user_id,
  312. entry_type=ENTRY_DEBIT_DELETE,
  313. amount=Decimal(str(invoice.amount)),
  314. user=user,
  315. invoice_id=invoice.id,
  316. remark=(invoice.remark or "").strip() or "删除发票冲减",
  317. )
  318. invoice.del_flag = 1
  319. invoice.update_by = user.id
  320. db.query(BxAttachment).filter(
  321. BxAttachment.biz_type == "invoice",
  322. BxAttachment.biz_id == invoice.id,
  323. BxAttachment.tenant_no == tenant_no,
  324. BxAttachment.del_flag == 0,
  325. ).update(
  326. {BxAttachment.del_flag: 1, BxAttachment.update_by: user.id},
  327. synchronize_session="fetch",
  328. )
  329. db.flush()
  330. invoice_count = InvoiceService._count_invoices(db, tenant_no, invoice.owner_user_id)
  331. InvoiceLedgerService.refresh_summary(
  332. db,
  333. tenant_no,
  334. invoice.owner_user_id,
  335. invoice.owner_user_name,
  336. invoice_count,
  337. user.id,
  338. user.dept_id,
  339. )
  340. return True
  341. @staticmethod
  342. def _summary_to_dict(row: BxInvoiceWalletSummary) -> dict:
  343. return {
  344. "id": row.id,
  345. "owner_user_id": row.owner_user_id,
  346. "owner_user_name": row.owner_user_name,
  347. "total_amount": row.total_amount,
  348. "used_amount": row.used_amount,
  349. "balance": row.balance,
  350. "invoice_count": row.invoice_count,
  351. "version": row.version,
  352. "create_time": row.create_time,
  353. "update_time": row.update_time,
  354. }
  355. @staticmethod
  356. def out_rows_with_attachments(
  357. db: Session, tenant_no: str, invoices: Sequence[BxInvoice]
  358. ) -> List[dict]:
  359. if not invoices:
  360. return []
  361. ids = [inv.id for inv in invoices]
  362. attachments = (
  363. db.query(BxAttachment)
  364. .filter(
  365. BxAttachment.biz_type == "invoice",
  366. BxAttachment.biz_id.in_(ids),
  367. BxAttachment.tenant_no == tenant_no,
  368. BxAttachment.del_flag == 0,
  369. )
  370. .order_by(BxAttachment.create_time.asc())
  371. .all()
  372. )
  373. att_map: dict[str, List[BxAttachment]] = {}
  374. for att in attachments:
  375. att_map.setdefault(att.biz_id, []).append(att)
  376. out: List[dict] = []
  377. for inv in invoices:
  378. atts = att_map.get(inv.id, [])
  379. first = atts[0] if atts else None
  380. out.append(
  381. {
  382. "id": inv.id,
  383. "owner_user_id": inv.owner_user_id,
  384. "owner_user_name": inv.owner_user_name,
  385. "amount": inv.amount,
  386. "upload_by": inv.upload_by,
  387. "upload_by_name": inv.upload_by_name,
  388. "remark": inv.remark,
  389. "create_time": inv.create_time,
  390. "update_time": inv.update_time,
  391. "attachment_id": first.id if first else None,
  392. "file_name": first.file_name if first else None,
  393. "file_path": first.file_path if first else None,
  394. "file_type": first.file_type if first else None,
  395. "attachments": [
  396. {
  397. "id": a.id,
  398. "file_name": a.file_name,
  399. "file_path": a.file_path,
  400. "file_type": a.file_type,
  401. }
  402. for a in atts
  403. ],
  404. }
  405. )
  406. return out