finance_budget.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. """Budget validation helpers for finance-aware print dispatch."""
  2. import calendar
  3. from datetime import datetime, timezone
  4. from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
  5. from fastapi import HTTPException
  6. from sqlalchemy import case, func, select
  7. from sqlalchemy.ext.asyncio import AsyncSession
  8. from backend.app.models.finance import BudgetReservation, CostCenter, CostCenterMember, WalletTransaction
  9. from backend.app.models.print_queue import PrintQueueItem
  10. from backend.app.models.settings import Settings
  11. from backend.app.models.user import User
  12. async def is_billing_enabled(db: AsyncSession) -> bool:
  13. # Consider any 'billing_enabled' setting with a true-ish value as enabling billing.
  14. result = await db.execute(
  15. select(func.count())
  16. .select_from(Settings)
  17. .where(Settings.key == "billing_enabled", func.lower(func.coalesce(Settings.value, "")) == "true")
  18. )
  19. count = int(result.scalar_one() or 0)
  20. return count > 0
  21. async def is_printer_kill_switch_enabled(db: AsyncSession) -> bool:
  22. """Return True when billing and the printer kill-switch are both enabled."""
  23. result = await db.execute(
  24. select(Settings.key, Settings.value).where(Settings.key.in_(("billing_enabled", "printer_kill_switch_enabled")))
  25. )
  26. values = {key: (value or "").strip().lower() for key, value in result.all()}
  27. return values.get("billing_enabled") == "true" and values.get("printer_kill_switch_enabled") == "true"
  28. async def _get_budget_window_start_utc(db: AsyncSession) -> datetime:
  29. result = await db.execute(
  30. select(Settings).where(Settings.key.in_(["finance_budget_reset_day", "finance_budget_reset_timezone"]))
  31. )
  32. values = {setting.key: setting.value for setting in result.scalars().all()}
  33. desired_day = 1
  34. try:
  35. parsed = int(values.get("finance_budget_reset_day") or 1)
  36. if 1 <= parsed <= 31:
  37. desired_day = parsed
  38. except (TypeError, ValueError):
  39. pass
  40. timezone_name = values.get("finance_budget_reset_timezone") or "UTC"
  41. try:
  42. tz = ZoneInfo(timezone_name)
  43. except ZoneInfoNotFoundError:
  44. tz = ZoneInfo("UTC")
  45. now = datetime.now(tz)
  46. current_month_reset_day = min(desired_day, calendar.monthrange(now.year, now.month)[1])
  47. if now.day < current_month_reset_day:
  48. month = now.month - 1
  49. year = now.year
  50. if month == 0:
  51. month = 12
  52. year -= 1
  53. else:
  54. month = now.month
  55. year = now.year
  56. reset_day = min(desired_day, calendar.monthrange(year, month)[1])
  57. return datetime(year, month, reset_day, tzinfo=tz).astimezone(timezone.utc)
  58. async def _cost_center_spend(db: AsyncSession, cost_center_id: int, *, monthly: bool) -> float:
  59. spend_expr = case((WalletTransaction.amount < 0, -WalletTransaction.amount), else_=0.0)
  60. conditions = [
  61. WalletTransaction.cost_center_id == cost_center_id,
  62. WalletTransaction.cost_center_id.is_not(None),
  63. ]
  64. if monthly:
  65. conditions.append(WalletTransaction.created_at >= await _get_budget_window_start_utc(db))
  66. result = await db.execute(select(func.coalesce(func.sum(spend_expr), 0.0)).where(*conditions))
  67. return float(result.scalar() or 0.0)
  68. async def _cost_center_open_queue_reservations(
  69. db: AsyncSession,
  70. cost_center_id: int,
  71. *,
  72. exclude_queue_item_id: int | None = None,
  73. ) -> float:
  74. active_queue_reservation = (
  75. select(BudgetReservation.id)
  76. .where(
  77. BudgetReservation.status == "active",
  78. BudgetReservation.source_type == "print_queue",
  79. BudgetReservation.source_id == PrintQueueItem.id,
  80. )
  81. .exists()
  82. )
  83. conditions = [
  84. PrintQueueItem.cost_center_id == cost_center_id,
  85. PrintQueueItem.status.in_(("pending", "printing")),
  86. ~active_queue_reservation,
  87. ]
  88. if exclude_queue_item_id is not None:
  89. conditions.append(PrintQueueItem.id != exclude_queue_item_id)
  90. result = await db.execute(select(func.coalesce(func.sum(PrintQueueItem.estimated_cost), 0.0)).where(*conditions))
  91. return float(result.scalar() or 0.0)
  92. async def _cost_center_active_budget_reservations(
  93. db: AsyncSession,
  94. cost_center_id: int,
  95. *,
  96. exclude_source_type: str | None = None,
  97. exclude_source_id: int | None = None,
  98. ) -> float:
  99. conditions = [
  100. BudgetReservation.cost_center_id == cost_center_id,
  101. BudgetReservation.status == "active",
  102. ]
  103. if exclude_source_type is not None and exclude_source_id is not None:
  104. conditions.append(
  105. ~(
  106. (BudgetReservation.source_type == exclude_source_type)
  107. & (BudgetReservation.source_id == exclude_source_id)
  108. )
  109. )
  110. result = await db.execute(select(func.coalesce(func.sum(BudgetReservation.amount), 0.0)).where(*conditions))
  111. return float(result.scalar() or 0.0)
  112. async def validate_print_budget(
  113. db: AsyncSession,
  114. *,
  115. cost_center_id: int | None,
  116. estimated_cost: float | None,
  117. current_user: User | None,
  118. quantity: int = 1,
  119. exclude_queue_item_id: int | None = None,
  120. exclude_reservation_source_type: str | None = None,
  121. exclude_reservation_source_id: int | None = None,
  122. ) -> None:
  123. """Validate that a print can be assigned to a cost center budget."""
  124. if not await is_billing_enabled(db):
  125. return
  126. if cost_center_id is None:
  127. raise HTTPException(status_code=400, detail="Cost center is required when billing is enabled")
  128. if estimated_cost is None or estimated_cost <= 0:
  129. raise HTTPException(status_code=400, detail="Estimated cost is required for cost center prints")
  130. center = await db.scalar(select(CostCenter).where(CostCenter.id == cost_center_id).with_for_update())
  131. if not center:
  132. raise HTTPException(status_code=404, detail="Cost center not found")
  133. if not center.is_active:
  134. raise HTTPException(status_code=400, detail="Cost center is inactive")
  135. if current_user is not None and not current_user.is_admin:
  136. if center.is_private:
  137. if center.owner_user_id != current_user.id:
  138. raise HTTPException(status_code=403, detail="You cannot print with this private cost center")
  139. else:
  140. member = await db.scalar(
  141. select(CostCenterMember).where(
  142. CostCenterMember.cost_center_id == cost_center_id,
  143. CostCenterMember.user_id == current_user.id,
  144. )
  145. )
  146. if not member or not member.can_print:
  147. raise HTTPException(status_code=403, detail="You cannot print with this cost center")
  148. budget_limit = center.monthly_budget if center.monthly_budget is not None else center.total_budget
  149. if budget_limit is None:
  150. return
  151. used = await _cost_center_spend(db, cost_center_id, monthly=center.monthly_budget is not None)
  152. reserved = await _cost_center_open_queue_reservations(
  153. db,
  154. cost_center_id,
  155. exclude_queue_item_id=exclude_queue_item_id,
  156. )
  157. reserved += await _cost_center_active_budget_reservations(
  158. db,
  159. cost_center_id,
  160. exclude_source_type=exclude_reservation_source_type,
  161. exclude_source_id=exclude_reservation_source_id,
  162. )
  163. requested = estimated_cost * max(1, quantity)
  164. available = float(budget_limit) - used - reserved
  165. if requested > available:
  166. raise HTTPException(
  167. status_code=400,
  168. detail=f"Estimated print cost exceeds available cost center budget ({requested:.2f} > {available:.2f})",
  169. )
  170. async def create_budget_reservation(
  171. db: AsyncSession,
  172. *,
  173. cost_center_id: int | None,
  174. estimated_cost: float | None,
  175. current_user: User | None,
  176. source_type: str,
  177. source_id: int | None,
  178. print_archive_id: int | None = None,
  179. exclude_queue_item_id: int | None = None,
  180. ) -> BudgetReservation | None:
  181. if not await is_billing_enabled(db):
  182. return None
  183. if cost_center_id is None:
  184. raise HTTPException(status_code=400, detail="Cost center is required when billing is enabled")
  185. await validate_print_budget(
  186. db,
  187. cost_center_id=cost_center_id,
  188. estimated_cost=estimated_cost,
  189. current_user=current_user,
  190. exclude_queue_item_id=exclude_queue_item_id,
  191. exclude_reservation_source_type=source_type,
  192. exclude_reservation_source_id=source_id,
  193. )
  194. existing = None
  195. if source_id is not None:
  196. existing = await db.scalar(
  197. select(BudgetReservation).where(
  198. BudgetReservation.status == "active",
  199. BudgetReservation.source_type == source_type,
  200. BudgetReservation.source_id == source_id,
  201. )
  202. )
  203. if existing is not None:
  204. existing.cost_center_id = cost_center_id
  205. existing.amount = float(estimated_cost or 0.0)
  206. if print_archive_id is not None:
  207. existing.print_archive_id = print_archive_id
  208. await db.flush()
  209. return existing
  210. reservation = BudgetReservation(
  211. cost_center_id=cost_center_id,
  212. amount=float(estimated_cost or 0.0),
  213. status="active",
  214. source_type=source_type,
  215. source_id=source_id,
  216. print_archive_id=print_archive_id,
  217. )
  218. db.add(reservation)
  219. await db.flush()
  220. return reservation
  221. async def release_budget_reservation(
  222. db: AsyncSession,
  223. *,
  224. source_type: str | None = None,
  225. source_id: int | None = None,
  226. print_archive_id: int | None = None,
  227. status: str = "released",
  228. ) -> int:
  229. conditions = [BudgetReservation.status == "active"]
  230. if print_archive_id is not None:
  231. conditions.append(BudgetReservation.print_archive_id == print_archive_id)
  232. else:
  233. conditions.extend(
  234. [
  235. BudgetReservation.source_type == source_type,
  236. BudgetReservation.source_id == source_id,
  237. ]
  238. )
  239. result = await db.execute(select(BudgetReservation).where(*conditions))
  240. reservations = result.scalars().all()
  241. for reservation in reservations:
  242. reservation.status = status
  243. reservation.released_at = datetime.now(timezone.utc)
  244. if reservations:
  245. await db.flush()
  246. return len(reservations)