@dainamite/billing 0.17.0 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (206) hide show
  1. package/CHANGELOG.md +99 -19
  2. package/dist/modules/billing/acl.js +9 -1
  3. package/dist/modules/billing/acl.js.map +2 -2
  4. package/dist/modules/billing/api/accounts/[id]/balance/route.js +62 -0
  5. package/dist/modules/billing/api/accounts/[id]/balance/route.js.map +7 -0
  6. package/dist/modules/billing/api/accounts/[id]/credit-status/route.js +56 -0
  7. package/dist/modules/billing/api/accounts/[id]/credit-status/route.js.map +7 -0
  8. package/dist/modules/billing/api/accounts/[id]/topups/route.js +36 -0
  9. package/dist/modules/billing/api/accounts/[id]/topups/route.js.map +7 -0
  10. package/dist/modules/billing/api/accounts/route.js +7 -0
  11. package/dist/modules/billing/api/accounts/route.js.map +2 -2
  12. package/dist/modules/billing/api/export/account/[id]/route.js +48 -3
  13. package/dist/modules/billing/api/export/account/[id]/route.js.map +2 -2
  14. package/dist/modules/billing/api/statements/generate/route.js +68 -0
  15. package/dist/modules/billing/api/statements/generate/route.js.map +7 -0
  16. package/dist/modules/billing/api/statements/route.js +110 -0
  17. package/dist/modules/billing/api/statements/route.js.map +7 -0
  18. package/dist/modules/billing/api/topups/route.js +139 -0
  19. package/dist/modules/billing/api/topups/route.js.map +7 -0
  20. package/dist/modules/billing/api/transactions/adjust/route.js +71 -0
  21. package/dist/modules/billing/api/transactions/adjust/route.js.map +7 -0
  22. package/dist/modules/billing/api/transactions/route.js +109 -0
  23. package/dist/modules/billing/api/transactions/route.js.map +7 -0
  24. package/dist/modules/billing/api/usage/route.js +30 -6
  25. package/dist/modules/billing/api/usage/route.js.map +2 -2
  26. package/dist/modules/billing/backend/billing/accounts/[id]/page.js +16 -1
  27. package/dist/modules/billing/backend/billing/accounts/[id]/page.js.map +2 -2
  28. package/dist/modules/billing/backend/billing/accounts/create/page.js +8 -1
  29. package/dist/modules/billing/backend/billing/accounts/create/page.js.map +2 -2
  30. package/dist/modules/billing/backend/billing/accounts/page.js +26 -1
  31. package/dist/modules/billing/backend/billing/accounts/page.js.map +2 -2
  32. package/dist/modules/billing/backend/billing/statements/[id]/page.js +129 -0
  33. package/dist/modules/billing/backend/billing/statements/[id]/page.js.map +7 -0
  34. package/dist/modules/billing/backend/billing/statements/[id]/page.meta.js +21 -0
  35. package/dist/modules/billing/backend/billing/statements/[id]/page.meta.js.map +7 -0
  36. package/dist/modules/billing/backend/billing/statements/page.js +152 -0
  37. package/dist/modules/billing/backend/billing/statements/page.js.map +7 -0
  38. package/dist/modules/billing/backend/billing/statements/page.meta.js +18 -0
  39. package/dist/modules/billing/backend/billing/statements/page.meta.js.map +7 -0
  40. package/dist/modules/billing/backend/billing/topups/[id]/page.js +90 -0
  41. package/dist/modules/billing/backend/billing/topups/[id]/page.js.map +7 -0
  42. package/dist/modules/billing/backend/billing/topups/[id]/page.meta.js +21 -0
  43. package/dist/modules/billing/backend/billing/topups/[id]/page.meta.js.map +7 -0
  44. package/dist/modules/billing/backend/billing/topups/page.js +147 -0
  45. package/dist/modules/billing/backend/billing/topups/page.js.map +7 -0
  46. package/dist/modules/billing/backend/billing/topups/page.meta.js +18 -0
  47. package/dist/modules/billing/backend/billing/topups/page.meta.js.map +7 -0
  48. package/dist/modules/billing/backend/billing/transactions/[id]/page.js +114 -0
  49. package/dist/modules/billing/backend/billing/transactions/[id]/page.js.map +7 -0
  50. package/dist/modules/billing/backend/billing/transactions/[id]/page.meta.js +21 -0
  51. package/dist/modules/billing/backend/billing/transactions/[id]/page.meta.js.map +7 -0
  52. package/dist/modules/billing/backend/billing/transactions/page.js +149 -0
  53. package/dist/modules/billing/backend/billing/transactions/page.js.map +7 -0
  54. package/dist/modules/billing/backend/billing/transactions/page.meta.js +18 -0
  55. package/dist/modules/billing/backend/billing/transactions/page.meta.js.map +7 -0
  56. package/dist/modules/billing/commands/accounts.js +26 -1
  57. package/dist/modules/billing/commands/accounts.js.map +2 -2
  58. package/dist/modules/billing/commands/index.js +3 -0
  59. package/dist/modules/billing/commands/index.js.map +2 -2
  60. package/dist/modules/billing/commands/invoices.js +21 -1
  61. package/dist/modules/billing/commands/invoices.js.map +2 -2
  62. package/dist/modules/billing/commands/statements.js +74 -0
  63. package/dist/modules/billing/commands/statements.js.map +7 -0
  64. package/dist/modules/billing/commands/topups.js +139 -0
  65. package/dist/modules/billing/commands/topups.js.map +7 -0
  66. package/dist/modules/billing/commands/transactions.js +119 -0
  67. package/dist/modules/billing/commands/transactions.js.map +7 -0
  68. package/dist/modules/billing/commands/usage.js +72 -0
  69. package/dist/modules/billing/commands/usage.js.map +2 -2
  70. package/dist/modules/billing/components/AccountForm.js +53 -1
  71. package/dist/modules/billing/components/AccountForm.js.map +2 -2
  72. package/dist/modules/billing/components/PrepaidPanel.js +314 -0
  73. package/dist/modules/billing/components/PrepaidPanel.js.map +7 -0
  74. package/dist/modules/billing/components/accountNames.js +20 -0
  75. package/dist/modules/billing/components/accountNames.js.map +7 -0
  76. package/dist/modules/billing/data/entities.js +290 -0
  77. package/dist/modules/billing/data/entities.js.map +2 -2
  78. package/dist/modules/billing/data/entityIds.js +6 -1
  79. package/dist/modules/billing/data/entityIds.js.map +2 -2
  80. package/dist/modules/billing/data/validators.js +107 -2
  81. package/dist/modules/billing/data/validators.js.map +2 -2
  82. package/dist/modules/billing/events.js +52 -0
  83. package/dist/modules/billing/events.js.map +2 -2
  84. package/dist/modules/billing/i18n/en.json +112 -4
  85. package/dist/modules/billing/i18n/pl.json +112 -4
  86. package/dist/modules/billing/index.js +1 -1
  87. package/dist/modules/billing/index.js.map +2 -2
  88. package/dist/modules/billing/lib/accountStatus.js +106 -0
  89. package/dist/modules/billing/lib/accountStatus.js.map +7 -0
  90. package/dist/modules/billing/lib/balanceEvents.js +48 -0
  91. package/dist/modules/billing/lib/balanceEvents.js.map +7 -0
  92. package/dist/modules/billing/lib/balanceLedger.js +136 -0
  93. package/dist/modules/billing/lib/balanceLedger.js.map +7 -0
  94. package/dist/modules/billing/lib/balanceStatus.js +29 -0
  95. package/dist/modules/billing/lib/balanceStatus.js.map +7 -0
  96. package/dist/modules/billing/lib/billRunEngine.js +40 -2
  97. package/dist/modules/billing/lib/billRunEngine.js.map +2 -2
  98. package/dist/modules/billing/lib/creditStatus.js +65 -0
  99. package/dist/modules/billing/lib/creditStatus.js.map +7 -0
  100. package/dist/modules/billing/lib/money.js +47 -0
  101. package/dist/modules/billing/lib/money.js.map +7 -0
  102. package/dist/modules/billing/lib/prepaidConfig.js +45 -0
  103. package/dist/modules/billing/lib/prepaidConfig.js.map +7 -0
  104. package/dist/modules/billing/lib/prepaidConsume.js +214 -0
  105. package/dist/modules/billing/lib/prepaidConsume.js.map +7 -0
  106. package/dist/modules/billing/lib/prepaidPeriodClose.js +285 -0
  107. package/dist/modules/billing/lib/prepaidPeriodClose.js.map +7 -0
  108. package/dist/modules/billing/lib/topupCapture.js +62 -0
  109. package/dist/modules/billing/lib/topupCapture.js.map +7 -0
  110. package/dist/modules/billing/lib/topupReceipt.js +97 -0
  111. package/dist/modules/billing/lib/topupReceipt.js.map +7 -0
  112. package/dist/modules/billing/lib/topupTransition.js +19 -0
  113. package/dist/modules/billing/lib/topupTransition.js.map +7 -0
  114. package/dist/modules/billing/migrations/Migration20260619000000_billing_prepaid.js +110 -0
  115. package/dist/modules/billing/migrations/Migration20260619000000_billing_prepaid.js.map +7 -0
  116. package/dist/modules/billing/setup.js +32 -1
  117. package/dist/modules/billing/setup.js.map +2 -2
  118. package/dist/modules/billing/subscribers/prepaid-topup-cancelled.js +26 -0
  119. package/dist/modules/billing/subscribers/prepaid-topup-cancelled.js.map +7 -0
  120. package/dist/modules/billing/subscribers/prepaid-topup-captured.js +87 -0
  121. package/dist/modules/billing/subscribers/prepaid-topup-captured.js.map +7 -0
  122. package/dist/modules/billing/subscribers/prepaid-topup-expired.js +26 -0
  123. package/dist/modules/billing/subscribers/prepaid-topup-expired.js.map +7 -0
  124. package/dist/modules/billing/subscribers/prepaid-topup-failed.js +26 -0
  125. package/dist/modules/billing/subscribers/prepaid-topup-failed.js.map +7 -0
  126. package/dist/modules/billing/workers/reconcile-prepaid-balances.js +50 -0
  127. package/dist/modules/billing/workers/reconcile-prepaid-balances.js.map +7 -0
  128. package/package.json +9 -9
  129. package/src/modules/billing/__tests__/commands/invoices.test.ts +3 -3
  130. package/src/modules/billing/__tests__/commands/topups.test.ts +104 -0
  131. package/src/modules/billing/__tests__/commands/transactions.test.ts +107 -0
  132. package/src/modules/billing/__tests__/helpers/prepaidMockEm.ts +235 -0
  133. package/src/modules/billing/__tests__/lib/accountStatus.test.ts +93 -0
  134. package/src/modules/billing/__tests__/lib/balanceLedger.test.ts +125 -0
  135. package/src/modules/billing/__tests__/lib/balanceStatus.test.ts +65 -0
  136. package/src/modules/billing/__tests__/lib/creditStatus.test.ts +111 -0
  137. package/src/modules/billing/__tests__/lib/money.test.ts +56 -0
  138. package/src/modules/billing/__tests__/lib/prepaidConsume.test.ts +179 -0
  139. package/src/modules/billing/__tests__/lib/prepaidPeriodClose.test.ts +232 -0
  140. package/src/modules/billing/__tests__/lib/topupCapture.test.ts +123 -0
  141. package/src/modules/billing/__tests__/lib/topupReceipt.test.ts +84 -0
  142. package/src/modules/billing/__tests__/setup.test.ts +28 -2
  143. package/src/modules/billing/acl.ts +8 -0
  144. package/src/modules/billing/api/accounts/[id]/balance/route.ts +74 -0
  145. package/src/modules/billing/api/accounts/[id]/credit-status/route.ts +71 -0
  146. package/src/modules/billing/api/accounts/[id]/topups/route.ts +49 -0
  147. package/src/modules/billing/api/accounts/route.ts +7 -0
  148. package/src/modules/billing/api/export/account/[id]/route.ts +47 -2
  149. package/src/modules/billing/api/statements/generate/route.ts +78 -0
  150. package/src/modules/billing/api/statements/route.ts +117 -0
  151. package/src/modules/billing/api/topups/route.ts +154 -0
  152. package/src/modules/billing/api/transactions/adjust/route.ts +80 -0
  153. package/src/modules/billing/api/transactions/route.ts +116 -0
  154. package/src/modules/billing/api/usage/route.ts +36 -5
  155. package/src/modules/billing/backend/billing/accounts/[id]/page.tsx +28 -0
  156. package/src/modules/billing/backend/billing/accounts/create/page.tsx +7 -0
  157. package/src/modules/billing/backend/billing/accounts/page.tsx +32 -1
  158. package/src/modules/billing/backend/billing/statements/[id]/page.meta.ts +19 -0
  159. package/src/modules/billing/backend/billing/statements/[id]/page.tsx +198 -0
  160. package/src/modules/billing/backend/billing/statements/page.meta.ts +16 -0
  161. package/src/modules/billing/backend/billing/statements/page.tsx +190 -0
  162. package/src/modules/billing/backend/billing/topups/[id]/page.meta.ts +19 -0
  163. package/src/modules/billing/backend/billing/topups/[id]/page.tsx +151 -0
  164. package/src/modules/billing/backend/billing/topups/page.meta.ts +16 -0
  165. package/src/modules/billing/backend/billing/topups/page.tsx +182 -0
  166. package/src/modules/billing/backend/billing/transactions/[id]/page.meta.ts +19 -0
  167. package/src/modules/billing/backend/billing/transactions/[id]/page.tsx +179 -0
  168. package/src/modules/billing/backend/billing/transactions/page.meta.ts +16 -0
  169. package/src/modules/billing/backend/billing/transactions/page.tsx +187 -0
  170. package/src/modules/billing/commands/accounts.ts +42 -1
  171. package/src/modules/billing/commands/index.ts +3 -0
  172. package/src/modules/billing/commands/invoices.ts +26 -2
  173. package/src/modules/billing/commands/statements.ts +101 -0
  174. package/src/modules/billing/commands/topups.ts +181 -0
  175. package/src/modules/billing/commands/transactions.ts +152 -0
  176. package/src/modules/billing/commands/usage.ts +114 -4
  177. package/src/modules/billing/components/AccountForm.tsx +66 -0
  178. package/src/modules/billing/components/PrepaidPanel.tsx +382 -0
  179. package/src/modules/billing/components/accountNames.ts +23 -0
  180. package/src/modules/billing/data/entities.ts +383 -0
  181. package/src/modules/billing/data/entityIds.ts +5 -0
  182. package/src/modules/billing/data/validators.ts +144 -0
  183. package/src/modules/billing/events.ts +52 -0
  184. package/src/modules/billing/i18n/en.json +112 -4
  185. package/src/modules/billing/i18n/pl.json +112 -4
  186. package/src/modules/billing/index.ts +1 -1
  187. package/src/modules/billing/lib/accountStatus.ts +155 -0
  188. package/src/modules/billing/lib/balanceEvents.ts +74 -0
  189. package/src/modules/billing/lib/balanceLedger.ts +258 -0
  190. package/src/modules/billing/lib/balanceStatus.ts +78 -0
  191. package/src/modules/billing/lib/billRunEngine.ts +66 -5
  192. package/src/modules/billing/lib/creditStatus.ts +153 -0
  193. package/src/modules/billing/lib/money.ts +73 -0
  194. package/src/modules/billing/lib/prepaidConfig.ts +58 -0
  195. package/src/modules/billing/lib/prepaidConsume.ts +299 -0
  196. package/src/modules/billing/lib/prepaidPeriodClose.ts +453 -0
  197. package/src/modules/billing/lib/topupCapture.ts +117 -0
  198. package/src/modules/billing/lib/topupReceipt.ts +153 -0
  199. package/src/modules/billing/lib/topupTransition.ts +31 -0
  200. package/src/modules/billing/migrations/Migration20260619000000_billing_prepaid.ts +131 -0
  201. package/src/modules/billing/setup.ts +45 -0
  202. package/src/modules/billing/subscribers/prepaid-topup-cancelled.ts +31 -0
  203. package/src/modules/billing/subscribers/prepaid-topup-captured.ts +120 -0
  204. package/src/modules/billing/subscribers/prepaid-topup-expired.ts +31 -0
  205. package/src/modules/billing/subscribers/prepaid-topup-failed.ts +32 -0
  206. package/src/modules/billing/workers/reconcile-prepaid-balances.ts +68 -0
@@ -3,8 +3,12 @@ import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
3
3
  import { getAuthFromRequest } from "@open-mercato/shared/lib/auth/server";
4
4
  import {
5
5
  BillingAccount,
6
+ BillingAccountBalance,
7
+ BillingAccountTransaction,
6
8
  BillingAccountUsage,
7
9
  BillingItem,
10
+ BillingStatement,
11
+ BillingTopup,
8
12
  BillRunOutcome,
9
13
  DraftInvoiceEdit
10
14
  } from "../../../../data/entities.js";
@@ -41,7 +45,7 @@ async function GET(req, { params }) {
41
45
  const url = new URL(req.url);
42
46
  const since = parseDate(url.searchParams.get("since")) ?? defaultSince();
43
47
  const until = parseDate(url.searchParams.get("until")) ?? /* @__PURE__ */ new Date();
44
- const [items, usage, outcomes] = await Promise.all([
48
+ const [items, usage, outcomes, balance, transactions, topups, statements] = await Promise.all([
45
49
  // Items are bounded by integration volume (typically <100 per
46
50
  // account); no time-window needed — they often outlive a single
47
51
  // export window and the operator needs to see active items
@@ -70,6 +74,41 @@ async function GET(req, { params }) {
70
74
  createdAt: { $gte: since, $lte: until }
71
75
  },
72
76
  { limit: EXPORT_HARD_LIMIT, orderBy: { createdAt: "DESC" } }
77
+ ),
78
+ // SPEC-002 prepaid data — the balance row + the windowed money trail.
79
+ em.findOne(BillingAccountBalance, {
80
+ tenantId,
81
+ billAccountId: account.id
82
+ }),
83
+ em.find(
84
+ BillingAccountTransaction,
85
+ {
86
+ tenantId,
87
+ organizationId,
88
+ billAccountId: account.id,
89
+ createdAt: { $gte: since, $lte: until }
90
+ },
91
+ { limit: EXPORT_HARD_LIMIT, orderBy: { createdAt: "DESC" } }
92
+ ),
93
+ em.find(
94
+ BillingTopup,
95
+ {
96
+ tenantId,
97
+ organizationId,
98
+ billAccountId: account.id,
99
+ createdAt: { $gte: since, $lte: until }
100
+ },
101
+ { limit: EXPORT_HARD_LIMIT, orderBy: { createdAt: "DESC" } }
102
+ ),
103
+ em.find(
104
+ BillingStatement,
105
+ {
106
+ tenantId,
107
+ organizationId,
108
+ billAccountId: account.id,
109
+ periodEnd: { $gte: since, $lte: until }
110
+ },
111
+ { limit: EXPORT_HARD_LIMIT, orderBy: { periodEnd: "DESC" } }
73
112
  )
74
113
  ]);
75
114
  const invoiceRows = await em.execute(
@@ -100,7 +139,8 @@ async function GET(req, { params }) {
100
139
  ) : [];
101
140
  return NextResponse.json({
102
141
  exportedAt: (/* @__PURE__ */ new Date()).toISOString(),
103
- schemaVersion: 1,
142
+ // v2 adds prepaid balance / transactions / top-ups / statements (SPEC-002).
143
+ schemaVersion: 2,
104
144
  tenantId,
105
145
  organizationId,
106
146
  window: {
@@ -113,7 +153,12 @@ async function GET(req, { params }) {
113
153
  usage,
114
154
  runOutcomes: outcomes,
115
155
  invoices: invoiceRows,
116
- draftInvoiceEdits: draftEdits
156
+ draftInvoiceEdits: draftEdits,
157
+ // SPEC-002 prepaid section.
158
+ balance,
159
+ transactions,
160
+ topups,
161
+ statements
117
162
  });
118
163
  } catch (err) {
119
164
  console.error("[billing/export/account.GET]", err);
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../../src/modules/billing/api/export/account/%5Bid%5D/route.ts"],
4
- "sourcesContent": ["import { NextResponse } from 'next/server'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport {\n BillingAccount,\n BillingAccountUsage,\n BillingItem,\n BillRunOutcome,\n DraftInvoiceEdit,\n} from '../../../../data/entities'\n\n/**\n * `GET /api/billing/export/account/[id]` \u2014 GDPR portability dump.\n *\n * Returns a full JSON serialization of a single Billing Account\n * including:\n * - The account row itself.\n * - Every active + soft-deleted `BillingItem` for the account.\n * - Every `BillingAccountUsage` record.\n * - Every `BillRunOutcome` row referencing the account.\n * - Every `core/sales` invoice the engine emitted for the account\n * (matched via `metadata->>'bill_account_id'`).\n * - Every `DraftInvoiceEdit` audit row for those invoices.\n *\n * Scope: the caller's auth tenant/organization is the authority \u2014 a\n * 404 is returned even for valid UUIDs that belong to a different\n * tenant (no cross-tenant leak).\n *\n * Soft-deleted rows are included on purpose: GDPR portability is\n * about the data we still hold, not just the data the UI shows.\n */\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['billing.account.view'] },\n}\n\nexport async function GET(\n req: Request,\n { params }: { params: Promise<{ id: string }> },\n) {\n let container: Awaited<ReturnType<typeof createRequestContainer>> | null = null\n try {\n container = await createRequestContainer()\n const auth = await getAuthFromRequest(req)\n if (!auth || !auth.tenantId) {\n return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n }\n const tenantId = auth.tenantId\n const organizationId = (auth as { orgId?: string }).orgId ?? null\n if (!organizationId) {\n return NextResponse.json(\n { error: 'Organization scope required' },\n { status: 403 },\n )\n }\n\n const { id: accountId } = await params\n\n const em = (container.resolve('em') as EntityManager).fork()\n const account = await em.findOne(BillingAccount, {\n id: accountId,\n tenantId,\n organizationId,\n deletedAt: null,\n })\n if (!account) {\n return NextResponse.json({ error: 'Account not found' }, { status: 404 })\n }\n\n // Time-window cap for usage records, run outcomes and invoices.\n //\n // Scale note: a telco account can carry millions of usage rows.\n // Returning everything would OOM on the export path. We default\n // to the last 12 months and let the caller override via `since` /\n // `until` for full GDPR-compliance dumps (a regulator request that\n // legitimately needs the lifetime export should set `since=1970-01-01`).\n // Each query is independently capped by `EXPORT_HARD_LIMIT` so a\n // single year of pathological volume still returns rather than\n // hanging.\n const url = new URL(req.url)\n const since = parseDate(url.searchParams.get('since'))\n ?? defaultSince()\n const until = parseDate(url.searchParams.get('until')) ?? new Date()\n\n const [items, usage, outcomes] = await Promise.all([\n // Items are bounded by integration volume (typically <100 per\n // account); no time-window needed \u2014 they often outlive a single\n // export window and the operator needs to see active items\n // regardless of when they were created.\n em.find(\n BillingItem,\n { tenantId, organizationId, billAccountId: account.id } as never,\n { limit: EXPORT_HARD_LIMIT },\n ),\n em.find(\n BillingAccountUsage,\n {\n tenantId,\n organizationId,\n billAccountId: account.id,\n periodEnd: { $gte: since, $lte: until },\n } as never,\n { limit: EXPORT_HARD_LIMIT, orderBy: { periodEnd: 'DESC' } },\n ),\n em.find(\n BillRunOutcome,\n {\n tenantId,\n organizationId,\n billAccountId: account.id,\n createdAt: { $gte: since, $lte: until },\n } as never,\n { limit: EXPORT_HARD_LIMIT, orderBy: { createdAt: 'DESC' } },\n ),\n ])\n\n // Invoices created in the window. The `metadata->>'bill_account_id'`\n // predicate keeps non-billing core/sales invoices out.\n const invoiceRows = (await em.execute(\n `SELECT id, invoice_number, status, status_entry_id, issue_date, due_date,\n currency_code, subtotal_net_amount, grand_total_net_amount,\n grand_total_gross_amount, paid_total_amount, outstanding_amount,\n metadata, created_at, updated_at, deleted_at\n FROM sales_invoices\n WHERE tenant_id = ?\n AND organization_id = ?\n AND deleted_at IS NULL\n AND metadata->>'bill_account_id' = ?\n AND created_at >= ?\n AND created_at <= ?\n ORDER BY created_at DESC\n LIMIT ?`,\n [tenantId, organizationId, account.id, since, until, EXPORT_HARD_LIMIT],\n )) as unknown as Array<{ id: string }>\n\n const invoiceIds = invoiceRows.map((r) => r.id)\n const draftEdits =\n invoiceIds.length > 0\n ? await em.find(\n DraftInvoiceEdit,\n {\n tenantId,\n organizationId,\n invoiceId: { $in: invoiceIds },\n } as never,\n { limit: EXPORT_HARD_LIMIT, orderBy: { createdAt: 'DESC' } },\n )\n : []\n\n return NextResponse.json({\n exportedAt: new Date().toISOString(),\n schemaVersion: 1,\n tenantId,\n organizationId,\n window: {\n since: since.toISOString(),\n until: until.toISOString(),\n hardLimit: EXPORT_HARD_LIMIT,\n },\n account,\n items,\n usage,\n runOutcomes: outcomes,\n invoices: invoiceRows,\n draftInvoiceEdits: draftEdits,\n })\n } catch (err) {\n console.error('[billing/export/account.GET]', err)\n return NextResponse.json({ error: 'Internal error' }, { status: 500 })\n }\n}\n\n/**\n * Per-collection cap to keep a single export bounded in size and time\n * even when the caller asks for `since=1970-01-01`. The full GDPR\n * lifetime dump for an outlier account requires a follow-up\n * background-job approach (chunked NDJSON to object storage) \u2014 out of\n * scope for the v1 admin export endpoint.\n */\nconst EXPORT_HARD_LIMIT = 50_000\n\n/**\n * Default time window for the export \u2014 last 12 months. Operators\n * pulling for routine GDPR requests almost always want a finite\n * window; the regulator-compliance \"lifetime\" case overrides via\n * `?since=1970-01-01`.\n */\nfunction defaultSince(): Date {\n const d = new Date()\n d.setUTCFullYear(d.getUTCFullYear() - 1)\n return d\n}\n\nfunction parseDate(value: string | null | undefined): Date | null {\n if (!value) return null\n const d = new Date(value)\n return Number.isNaN(d.getTime()) ? null : d\n}\n\nexport const openApi = {\n methods: {\n GET: {\n tags: ['Billing'],\n summary: 'Export a billing account (GDPR portability)',\n parameters: [\n {\n name: 'id',\n in: 'path',\n required: true,\n schema: { type: 'string', format: 'uuid' },\n },\n {\n name: 'since',\n in: 'query',\n required: false,\n description:\n 'ISO timestamp; lower bound for usage / outcomes / invoices windows. Defaults to today \u2212 12 months.',\n schema: { type: 'string', format: 'date-time' },\n },\n {\n name: 'until',\n in: 'query',\n required: false,\n description: 'ISO timestamp; upper bound. Defaults to now.',\n schema: { type: 'string', format: 'date-time' },\n },\n ],\n description:\n \"Returns a JSON dump of a single Billing Account: the account itself, every Billing Item (no time cap \u2014 items often outlive a single export window), and the Usage records / BillRunOutcomes / emitted core/sales invoices / DraftInvoiceEdit rows whose timestamps fall in the [since, until] window (defaults to the last 12 months). Each collection is independently capped by EXPORT_HARD_LIMIT = 50,000 rows. Lifetime dumps for outlier accounts need a follow-up chunked background-job approach \u2014 out of scope for this v1 endpoint.\",\n },\n },\n}\n"],
5
- "mappings": "AAAA,SAAS,oBAAoB;AAE7B,SAAS,8BAA8B;AACvC,SAAS,0BAA0B;AACnC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAuBA,MAAM,WAAW;AAAA,EACtB,KAAK,EAAE,aAAa,MAAM,iBAAiB,CAAC,sBAAsB,EAAE;AACtE;AAEA,eAAsB,IACpB,KACA,EAAE,OAAO,GACT;AACA,MAAI,YAAuE;AAC3E,MAAI;AACF,gBAAY,MAAM,uBAAuB;AACzC,UAAM,OAAO,MAAM,mBAAmB,GAAG;AACzC,QAAI,CAAC,QAAQ,CAAC,KAAK,UAAU;AAC3B,aAAO,aAAa,KAAK,EAAE,OAAO,eAAe,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,IACrE;AACA,UAAM,WAAW,KAAK;AACtB,UAAM,iBAAkB,KAA4B,SAAS;AAC7D,QAAI,CAAC,gBAAgB;AACnB,aAAO,aAAa;AAAA,QAClB,EAAE,OAAO,8BAA8B;AAAA,QACvC,EAAE,QAAQ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rB,SAAS;AAAA,IACP,KAAK;AAAA,MACH,MAAM,CAAC,SAAS;AAAA,MAChB,SAAS;AAAA,MACT,YAAY;AAAA,QACV;AAAA,UACE,MAAM;AAAA,UACN,IAAI;AAAA,UACJ,UAAU;AAAA,UACV,QAAQ,EAAE,MAAM,UAAU,QAAQ,OAAO;AAAA,QAC3C;AAAA,QACA;AAAA,UACE,MAAM;AAAA,UACN,IAAI;AAAA,UACJ,UAAU;AAAA,UACV,aACE;AAAA,UACF,QAAQ,EAAE,MAAM,UAAU,QAAQ,YAAY;AAAA,QAChD;AAAA,QACA;AAAA,UACE,MAAM;AAAA,UACN,IAAI;AAAA,UACJ,UAAU;AAAA,UACV,aAAa;AAAA,UACb,QAAQ,EAAE,MAAM,UAAU,QAAQ,YAAY;AAAA,QAChD;AAAA,MACF;AAAA,MACA,aACE;AAAA,IACJ;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["import { NextResponse } from 'next/server'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport {\n BillingAccount,\n BillingAccountBalance,\n BillingAccountTransaction,\n BillingAccountUsage,\n BillingItem,\n BillingStatement,\n BillingTopup,\n BillRunOutcome,\n DraftInvoiceEdit,\n} from '../../../../data/entities'\n\n/**\n * `GET /api/billing/export/account/[id]` \u2014 GDPR portability dump.\n *\n * Returns a full JSON serialization of a single Billing Account\n * including:\n * - The account row itself.\n * - Every active + soft-deleted `BillingItem` for the account.\n * - Every `BillingAccountUsage` record.\n * - Every `BillRunOutcome` row referencing the account.\n * - Every `core/sales` invoice the engine emitted for the account\n * (matched via `metadata->>'bill_account_id'`).\n * - Every `DraftInvoiceEdit` audit row for those invoices.\n *\n * Scope: the caller's auth tenant/organization is the authority \u2014 a\n * 404 is returned even for valid UUIDs that belong to a different\n * tenant (no cross-tenant leak).\n *\n * Soft-deleted rows are included on purpose: GDPR portability is\n * about the data we still hold, not just the data the UI shows.\n */\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['billing.account.view'] },\n}\n\nexport async function GET(\n req: Request,\n { params }: { params: Promise<{ id: string }> },\n) {\n let container: Awaited<ReturnType<typeof createRequestContainer>> | null = null\n try {\n container = await createRequestContainer()\n const auth = await getAuthFromRequest(req)\n if (!auth || !auth.tenantId) {\n return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n }\n const tenantId = auth.tenantId\n const organizationId = (auth as { orgId?: string }).orgId ?? null\n if (!organizationId) {\n return NextResponse.json(\n { error: 'Organization scope required' },\n { status: 403 },\n )\n }\n\n const { id: accountId } = await params\n\n const em = (container.resolve('em') as EntityManager).fork()\n const account = await em.findOne(BillingAccount, {\n id: accountId,\n tenantId,\n organizationId,\n deletedAt: null,\n })\n if (!account) {\n return NextResponse.json({ error: 'Account not found' }, { status: 404 })\n }\n\n // Time-window cap for usage records, run outcomes and invoices.\n //\n // Scale note: a telco account can carry millions of usage rows.\n // Returning everything would OOM on the export path. We default\n // to the last 12 months and let the caller override via `since` /\n // `until` for full GDPR-compliance dumps (a regulator request that\n // legitimately needs the lifetime export should set `since=1970-01-01`).\n // Each query is independently capped by `EXPORT_HARD_LIMIT` so a\n // single year of pathological volume still returns rather than\n // hanging.\n const url = new URL(req.url)\n const since = parseDate(url.searchParams.get('since'))\n ?? defaultSince()\n const until = parseDate(url.searchParams.get('until')) ?? new Date()\n\n const [items, usage, outcomes, balance, transactions, topups, statements] = await Promise.all([\n // Items are bounded by integration volume (typically <100 per\n // account); no time-window needed \u2014 they often outlive a single\n // export window and the operator needs to see active items\n // regardless of when they were created.\n em.find(\n BillingItem,\n { tenantId, organizationId, billAccountId: account.id } as never,\n { limit: EXPORT_HARD_LIMIT },\n ),\n em.find(\n BillingAccountUsage,\n {\n tenantId,\n organizationId,\n billAccountId: account.id,\n periodEnd: { $gte: since, $lte: until },\n } as never,\n { limit: EXPORT_HARD_LIMIT, orderBy: { periodEnd: 'DESC' } },\n ),\n em.find(\n BillRunOutcome,\n {\n tenantId,\n organizationId,\n billAccountId: account.id,\n createdAt: { $gte: since, $lte: until },\n } as never,\n { limit: EXPORT_HARD_LIMIT, orderBy: { createdAt: 'DESC' } },\n ),\n // SPEC-002 prepaid data \u2014 the balance row + the windowed money trail.\n em.findOne(BillingAccountBalance, {\n tenantId,\n billAccountId: account.id,\n } as never),\n em.find(\n BillingAccountTransaction,\n {\n tenantId,\n organizationId,\n billAccountId: account.id,\n createdAt: { $gte: since, $lte: until },\n } as never,\n { limit: EXPORT_HARD_LIMIT, orderBy: { createdAt: 'DESC' } },\n ),\n em.find(\n BillingTopup,\n {\n tenantId,\n organizationId,\n billAccountId: account.id,\n createdAt: { $gte: since, $lte: until },\n } as never,\n { limit: EXPORT_HARD_LIMIT, orderBy: { createdAt: 'DESC' } },\n ),\n em.find(\n BillingStatement,\n {\n tenantId,\n organizationId,\n billAccountId: account.id,\n periodEnd: { $gte: since, $lte: until },\n } as never,\n { limit: EXPORT_HARD_LIMIT, orderBy: { periodEnd: 'DESC' } },\n ),\n ])\n\n // Invoices created in the window. The `metadata->>'bill_account_id'`\n // predicate keeps non-billing core/sales invoices out.\n const invoiceRows = (await em.execute(\n `SELECT id, invoice_number, status, status_entry_id, issue_date, due_date,\n currency_code, subtotal_net_amount, grand_total_net_amount,\n grand_total_gross_amount, paid_total_amount, outstanding_amount,\n metadata, created_at, updated_at, deleted_at\n FROM sales_invoices\n WHERE tenant_id = ?\n AND organization_id = ?\n AND deleted_at IS NULL\n AND metadata->>'bill_account_id' = ?\n AND created_at >= ?\n AND created_at <= ?\n ORDER BY created_at DESC\n LIMIT ?`,\n [tenantId, organizationId, account.id, since, until, EXPORT_HARD_LIMIT],\n )) as unknown as Array<{ id: string }>\n\n const invoiceIds = invoiceRows.map((r) => r.id)\n const draftEdits =\n invoiceIds.length > 0\n ? await em.find(\n DraftInvoiceEdit,\n {\n tenantId,\n organizationId,\n invoiceId: { $in: invoiceIds },\n } as never,\n { limit: EXPORT_HARD_LIMIT, orderBy: { createdAt: 'DESC' } },\n )\n : []\n\n return NextResponse.json({\n exportedAt: new Date().toISOString(),\n // v2 adds prepaid balance / transactions / top-ups / statements (SPEC-002).\n schemaVersion: 2,\n tenantId,\n organizationId,\n window: {\n since: since.toISOString(),\n until: until.toISOString(),\n hardLimit: EXPORT_HARD_LIMIT,\n },\n account,\n items,\n usage,\n runOutcomes: outcomes,\n invoices: invoiceRows,\n draftInvoiceEdits: draftEdits,\n // SPEC-002 prepaid section.\n balance,\n transactions,\n topups,\n statements,\n })\n } catch (err) {\n console.error('[billing/export/account.GET]', err)\n return NextResponse.json({ error: 'Internal error' }, { status: 500 })\n }\n}\n\n/**\n * Per-collection cap to keep a single export bounded in size and time\n * even when the caller asks for `since=1970-01-01`. The full GDPR\n * lifetime dump for an outlier account requires a follow-up\n * background-job approach (chunked NDJSON to object storage) \u2014 out of\n * scope for the v1 admin export endpoint.\n */\nconst EXPORT_HARD_LIMIT = 50_000\n\n/**\n * Default time window for the export \u2014 last 12 months. Operators\n * pulling for routine GDPR requests almost always want a finite\n * window; the regulator-compliance \"lifetime\" case overrides via\n * `?since=1970-01-01`.\n */\nfunction defaultSince(): Date {\n const d = new Date()\n d.setUTCFullYear(d.getUTCFullYear() - 1)\n return d\n}\n\nfunction parseDate(value: string | null | undefined): Date | null {\n if (!value) return null\n const d = new Date(value)\n return Number.isNaN(d.getTime()) ? null : d\n}\n\nexport const openApi = {\n methods: {\n GET: {\n tags: ['Billing'],\n summary: 'Export a billing account (GDPR portability)',\n parameters: [\n {\n name: 'id',\n in: 'path',\n required: true,\n schema: { type: 'string', format: 'uuid' },\n },\n {\n name: 'since',\n in: 'query',\n required: false,\n description:\n 'ISO timestamp; lower bound for usage / outcomes / invoices windows. Defaults to today \u2212 12 months.',\n schema: { type: 'string', format: 'date-time' },\n },\n {\n name: 'until',\n in: 'query',\n required: false,\n description: 'ISO timestamp; upper bound. Defaults to now.',\n schema: { type: 'string', format: 'date-time' },\n },\n ],\n description:\n \"Returns a JSON dump of a single Billing Account: the account itself, every Billing Item (no time cap \u2014 items often outlive a single export window), and the Usage records / BillRunOutcomes / emitted core/sales invoices / DraftInvoiceEdit rows whose timestamps fall in the [since, until] window (defaults to the last 12 months). Each collection is independently capped by EXPORT_HARD_LIMIT = 50,000 rows. Lifetime dumps for outlier accounts need a follow-up chunked background-job approach \u2014 out of scope for this v1 endpoint.\",\n },\n },\n}\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB;AAE7B,SAAS,8BAA8B;AACvC,SAAS,0BAA0B;AACnC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAuBA,MAAM,WAAW;AAAA,EACtB,KAAK,EAAE,aAAa,MAAM,iBAAiB,CAAC,sBAAsB,EAAE;AACtE;AAEA,eAAsB,IACpB,KACA,EAAE,OAAO,GACT;AACA,MAAI,YAAuE;AAC3E,MAAI;AACF,gBAAY,MAAM,uBAAuB;AACzC,UAAM,OAAO,MAAM,mBAAmB,GAAG;AACzC,QAAI,CAAC,QAAQ,CAAC,KAAK,UAAU;AAC3B,aAAO,aAAa,KAAK,EAAE,OAAO,eAAe,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,IACrE;AACA,UAAM,WAAW,KAAK;AACtB,UAAM,iBAAkB,KAA4B,SAAS;AAC7D,QAAI,CAAC,gBAAgB;AACnB,aAAO,aAAa;AAAA,QAClB,EAAE,OAAO,8BAA8B;AAAA,QACvC,EAAE,QAAQ,IAAI;AAAA,MAChB;AAAA,IACF;AAEA,UAAM,EAAE,IAAI,UAAU,IAAI,MAAM;AAEhC,UAAM,KAAM,UAAU,QAAQ,IAAI,EAAoB,KAAK;AAC3D,UAAM,UAAU,MAAM,GAAG,QAAQ,gBAAgB;AAAA,MAC/C,IAAI;AAAA,MACJ;AAAA,MACA;AAAA,MACA,WAAW;AAAA,IACb,CA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ib/crud/factory";
3
+ import { withScopedPayload } from "@open-mercato/shared/lib/api/scoped";
4
+ import { resolveTranslations } from "@open-mercato/shared/lib/i18n/server";
5
+ import { BillingStatement } from "../../../data/entities.js";
6
+ import { billingEntityIds } from "../../../data/entityIds.js";
7
+ import { billingStatementGenerateSchema } from "../../../data/validators.js";
8
+ import { createBillingCrudOpenApi } from "../../openapi.js";
9
+ const routeMetadata = {
10
+ POST: { requireAuth: true, requireFeatures: ["billing.statement.generate"] }
11
+ };
12
+ const metadata = routeMetadata;
13
+ const generateResponseSchema = z.object({
14
+ statementId: z.string().uuid().nullable(),
15
+ billRunId: z.string().uuid(),
16
+ status: z.string()
17
+ });
18
+ const rawBodySchema = z.object({}).passthrough();
19
+ const crud = makeCrudRoute({
20
+ metadata: routeMetadata,
21
+ orm: {
22
+ entity: BillingStatement,
23
+ idField: "id",
24
+ orgField: "organizationId",
25
+ tenantField: "tenantId"
26
+ },
27
+ list: {
28
+ schema: z.object({}).passthrough(),
29
+ entityId: billingEntityIds.statement,
30
+ fields: ["id"],
31
+ buildFilters: async () => ({})
32
+ },
33
+ actions: {
34
+ create: {
35
+ commandId: "billing.statements.generate",
36
+ schema: rawBodySchema,
37
+ mapInput: async ({ raw, ctx }) => {
38
+ const { translate } = await resolveTranslations();
39
+ const scoped = withScopedPayload(raw ?? {}, ctx, translate);
40
+ return billingStatementGenerateSchema.parse(scoped);
41
+ },
42
+ response: ({ result }) => ({
43
+ statementId: result?.statementId ?? null,
44
+ billRunId: result?.billRunId ?? null,
45
+ status: result?.status ?? null
46
+ }),
47
+ status: 201
48
+ }
49
+ }
50
+ });
51
+ const POST = crud.POST;
52
+ const openApi = createBillingCrudOpenApi({
53
+ resourceName: "BillingStatementGenerate",
54
+ pluralName: "BillingStatementGenerations",
55
+ querySchema: z.object({}).passthrough(),
56
+ listResponseSchema: z.object({ items: z.array(z.unknown()) }),
57
+ create: {
58
+ schema: billingStatementGenerateSchema,
59
+ responseSchema: generateResponseSchema,
60
+ description: "Generates a consumption statement for a prepaid account by running the period close (recurring charges \u2192 balance + statement) scoped to that account. Returns the statement id (null when the account is not due)."
61
+ }
62
+ });
63
+ export {
64
+ POST,
65
+ metadata,
66
+ openApi
67
+ };
68
+ //# sourceMappingURL=route.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../../../src/modules/billing/api/statements/generate/route.ts"],
4
+ "sourcesContent": ["import { z } from 'zod'\nimport { makeCrudRoute } from '@open-mercato/shared/lib/crud/factory'\nimport { withScopedPayload } from '@open-mercato/shared/lib/api/scoped'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { BillingStatement } from '../../../data/entities'\nimport { billingEntityIds } from '../../../data/entityIds'\nimport { billingStatementGenerateSchema } from '../../../data/validators'\nimport { createBillingCrudOpenApi } from '../../openapi'\n\n/**\n * `POST /api/billing/statements/generate` (SPEC-002 P3) \u2014 manual statement\n * generation for a prepaid account. Reuses the Bill Run engine scoped to the\n * one account (same recurring-charge + anti-duplicate machinery).\n */\n\nconst routeMetadata = {\n POST: { requireAuth: true, requireFeatures: ['billing.statement.generate'] },\n}\n\nexport const metadata = routeMetadata\n\nconst generateResponseSchema = z.object({\n statementId: z.string().uuid().nullable(),\n billRunId: z.string().uuid(),\n status: z.string(),\n})\n\nconst rawBodySchema = z.object({}).passthrough()\n\nconst crud = makeCrudRoute({\n metadata: routeMetadata,\n orm: {\n entity: BillingStatement,\n idField: 'id',\n orgField: 'organizationId',\n tenantField: 'tenantId',\n },\n list: {\n schema: z.object({}).passthrough(),\n entityId: billingEntityIds.statement,\n fields: ['id'],\n buildFilters: async () => ({}),\n },\n actions: {\n create: {\n commandId: 'billing.statements.generate',\n schema: rawBodySchema,\n mapInput: async ({ raw, ctx }) => {\n const { translate } = await resolveTranslations()\n const scoped = withScopedPayload(raw ?? {}, ctx, translate)\n return billingStatementGenerateSchema.parse(scoped)\n },\n response: ({ result }) => ({\n statementId: result?.statementId ?? null,\n billRunId: result?.billRunId ?? null,\n status: result?.status ?? null,\n }),\n status: 201,\n },\n },\n})\n\nexport const POST = crud.POST\n\nexport const openApi = createBillingCrudOpenApi({\n resourceName: 'BillingStatementGenerate',\n pluralName: 'BillingStatementGenerations',\n querySchema: z.object({}).passthrough(),\n listResponseSchema: z.object({ items: z.array(z.unknown()) }),\n create: {\n schema: billingStatementGenerateSchema,\n responseSchema: generateResponseSchema,\n description:\n 'Generates a consumption statement for a prepaid account by running the ' +\n 'period close (recurring charges \u2192 balance + statement) scoped to that ' +\n 'account. Returns the statement id (null when the account is not due).',\n },\n})\n"],
5
+ "mappings": "AAAA,SAAS,SAAS;AAClB,SAAS,qBAAqB;AAC9B,SAAS,yBAAyB;AAClC,SAAS,2BAA2B;AACpC,SAAS,wBAAwB;AACjC,SAAS,wBAAwB;AACjC,SAAS,sCAAsC;AAC/C,SAAS,gCAAgC;AAQzC,MAAM,gBAAgB;AAAA,EACpB,MAAM,EAAE,aAAa,MAAM,iBAAiB,CAAC,4BAA4B,EAAE;AAC7E;AAEO,MAAM,WAAW;AAExB,MAAM,yBAAyB,EAAE,OAAO;AAAA,EACtC,aAAa,EAAE,OAAO,EAAE,KAAK,EAAE,SAAS;AAAA,EACxC,WAAW,EAAE,OAAO,EAAE,KAAK;AAAA,EAC3B,QAAQ,EAAE,OAAO;AACnB,CAAC;AAED,MAAM,gBAAgB,EAAE,OAAO,CAAC,CAAC,EAAE,YAAY;AAE/C,MAAM,OAAO,cAAc;AAAA,EACzB,UAAU;AAAA,EACV,KAAK;AAAA,IACH,QAAQ;AAAA,IACR,SAAS;AAAA,IACT,UAAU;AAAA,IACV,aAAa;AAAA,EACf;AAAA,EACA,MAAM;AAAA,IACJ,QAAQ,EAAE,OAAO,CAAC,CAAC,EAAE,YAAY;AAAA,IACjC,UAAU,iBAAiB;AAAA,IAC3B,QAAQ,CAAC,IAAI;AAAA,IACb,cAAc,aAAa,CAAC;AAAA,EAC9B;AAAA,EACA,SAAS;AAAA,IACP,QAAQ;AAAA,MACN,WAAW;AAAA,MACX,QAAQ;AAAA,MACR,UAAU,OAAO,EAAE,KAAK,IAAI,MAAM;AAChC,cAAM,EAAE,UAAU,IAAI,MAAM,oBAAoB;AAChD,cAAM,SAAS,kBAAkB,OAAO,CAAC,GAAG,KAAK,SAAS;AAC1D,eAAO,+BAA+B,MAAM,MAAM;AAAA,MACpD;AAAA,MACA,UAAU,CAAC,EAAE,OAAO,OAAO;AAAA,QACzB,aAAa,QAAQ,eAAe;AAAA,QACpC,WAAW,QAAQ,aAAa;AAAA,QAChC,QAAQ,QAAQ,UAAU;AAAA,MAC5B;AAAA,MACA,QAAQ;AAAA,IACV;AAAA,EACF;AACF,CAAC;AAEM,MAAM,OAAO,KAAK;AAElB,MAAM,UAAU,yBAAyB;AAAA,EAC9C,cAAc;AAAA,EACd,YAAY;AAAA,EACZ,aAAa,EAAE,OAAO,CAAC,CAAC,EAAE,YAAY;AAAA,EACtC,oBAAoB,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,CAAC;AAAA,EAC5D,QAAQ;AAAA,IACN,QAAQ;AAAA,IACR,gBAAgB;AAAA,IAChB,aACE;AAAA,EAGJ;AACF,CAAC;",
6
+ "names": []
7
+ }
@@ -0,0 +1,110 @@
1
+ import { z } from "zod";
2
+ import { makeCrudRoute } from "@open-mercato/shared/lib/crud/factory";
3
+ import { BillingStatement } from "../../data/entities.js";
4
+ import { billingEntityIds } from "../../data/entityIds.js";
5
+ import { billingStatementListQuerySchema } from "../../data/validators.js";
6
+ import {
7
+ createBillingCrudOpenApi,
8
+ createPagedListResponseSchema
9
+ } from "../openapi.js";
10
+ const routeMetadata = {
11
+ GET: { requireAuth: true, requireFeatures: ["billing.statement.view"] }
12
+ };
13
+ const metadata = routeMetadata;
14
+ const billingStatementListItemSchema = z.object({
15
+ id: z.string().uuid(),
16
+ bill_account_id: z.string().uuid(),
17
+ bill_run_id: z.string().uuid().nullable(),
18
+ period_start: z.string(),
19
+ period_end: z.string(),
20
+ currency_code: z.string(),
21
+ opening_balance: z.string(),
22
+ total_topups: z.string(),
23
+ total_usage: z.string(),
24
+ total_recurring: z.string(),
25
+ total_adjustments: z.string(),
26
+ closing_balance: z.string(),
27
+ debit_breakdown: z.record(z.string(), z.unknown()).nullable(),
28
+ status: z.string(),
29
+ organization_id: z.string().uuid(),
30
+ tenant_id: z.string().uuid(),
31
+ created_at: z.string(),
32
+ updated_at: z.string()
33
+ });
34
+ const crud = makeCrudRoute({
35
+ metadata: routeMetadata,
36
+ orm: {
37
+ entity: BillingStatement,
38
+ idField: "id",
39
+ orgField: "organizationId",
40
+ tenantField: "tenantId"
41
+ },
42
+ list: {
43
+ schema: billingStatementListQuerySchema,
44
+ entityId: billingEntityIds.statement,
45
+ fields: [
46
+ "id",
47
+ "bill_account_id",
48
+ "bill_run_id",
49
+ "period_start",
50
+ "period_end",
51
+ "currency_code",
52
+ "opening_balance",
53
+ "total_topups",
54
+ "total_usage",
55
+ "total_recurring",
56
+ "total_adjustments",
57
+ "closing_balance",
58
+ "debit_breakdown",
59
+ "status",
60
+ "organization_id",
61
+ "tenant_id",
62
+ "created_at",
63
+ "updated_at"
64
+ ],
65
+ sortFieldMap: {
66
+ periodEnd: "period_end",
67
+ periodStart: "period_start",
68
+ createdAt: "created_at"
69
+ },
70
+ buildFilters: async (query) => {
71
+ const filters = {};
72
+ if (typeof query.id === "string" && query.id) {
73
+ filters.id = { $eq: query.id };
74
+ }
75
+ if (typeof query.billAccountId === "string" && query.billAccountId) {
76
+ filters.bill_account_id = { $eq: query.billAccountId };
77
+ }
78
+ if (typeof query.status === "string" && query.status) {
79
+ filters.status = { $eq: query.status };
80
+ }
81
+ if (query.periodEndFrom instanceof Date) {
82
+ filters.period_end = Object.assign(
83
+ filters.period_end ?? {},
84
+ { $gte: query.periodEndFrom }
85
+ );
86
+ }
87
+ if (query.periodEndTo instanceof Date) {
88
+ filters.period_end = Object.assign(
89
+ filters.period_end ?? {},
90
+ { $lte: query.periodEndTo }
91
+ );
92
+ }
93
+ return filters;
94
+ }
95
+ },
96
+ actions: {}
97
+ });
98
+ const GET = crud.GET;
99
+ const openApi = createBillingCrudOpenApi({
100
+ resourceName: "BillingStatement",
101
+ pluralName: "BillingStatements",
102
+ querySchema: billingStatementListQuerySchema,
103
+ listResponseSchema: createPagedListResponseSchema(billingStatementListItemSchema)
104
+ });
105
+ export {
106
+ GET,
107
+ metadata,
108
+ openApi
109
+ };
110
+ //# sourceMappingURL=route.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../../src/modules/billing/api/statements/route.ts"],
4
+ "sourcesContent": ["import { z } from 'zod'\nimport { makeCrudRoute } from '@open-mercato/shared/lib/crud/factory'\nimport { BillingStatement } from '../../data/entities'\nimport { billingEntityIds } from '../../data/entityIds'\nimport { billingStatementListQuerySchema } from '../../data/validators'\nimport {\n createBillingCrudOpenApi,\n createPagedListResponseSchema,\n} from '../openapi'\n\n/**\n * `GET /api/billing/statements` \u2014 paged consumption statements (SPEC-002 P3).\n * Filter by account, status, and a `period_end` window. `?id=` narrows to one\n * row for the detail page. Generation goes through\n * POST /api/billing/statements/generate.\n */\n\nconst routeMetadata = {\n GET: { requireAuth: true, requireFeatures: ['billing.statement.view'] },\n}\n\nexport const metadata = routeMetadata\n\nconst billingStatementListItemSchema = z.object({\n id: z.string().uuid(),\n bill_account_id: z.string().uuid(),\n bill_run_id: z.string().uuid().nullable(),\n period_start: z.string(),\n period_end: z.string(),\n currency_code: z.string(),\n opening_balance: z.string(),\n total_topups: z.string(),\n total_usage: z.string(),\n total_recurring: z.string(),\n total_adjustments: z.string(),\n closing_balance: z.string(),\n debit_breakdown: z.record(z.string(), z.unknown()).nullable(),\n status: z.string(),\n organization_id: z.string().uuid(),\n tenant_id: z.string().uuid(),\n created_at: z.string(),\n updated_at: z.string(),\n})\n\nconst crud = makeCrudRoute({\n metadata: routeMetadata,\n orm: {\n entity: BillingStatement,\n idField: 'id',\n orgField: 'organizationId',\n tenantField: 'tenantId',\n },\n list: {\n schema: billingStatementListQuerySchema,\n entityId: billingEntityIds.statement,\n fields: [\n 'id',\n 'bill_account_id',\n 'bill_run_id',\n 'period_start',\n 'period_end',\n 'currency_code',\n 'opening_balance',\n 'total_topups',\n 'total_usage',\n 'total_recurring',\n 'total_adjustments',\n 'closing_balance',\n 'debit_breakdown',\n 'status',\n 'organization_id',\n 'tenant_id',\n 'created_at',\n 'updated_at',\n ],\n sortFieldMap: {\n periodEnd: 'period_end',\n periodStart: 'period_start',\n createdAt: 'created_at',\n },\n buildFilters: async (query) => {\n const filters: Record<string, unknown> = {}\n if (typeof query.id === 'string' && query.id) {\n filters.id = { $eq: query.id }\n }\n if (typeof query.billAccountId === 'string' && query.billAccountId) {\n filters.bill_account_id = { $eq: query.billAccountId }\n }\n if (typeof query.status === 'string' && query.status) {\n filters.status = { $eq: query.status }\n }\n if (query.periodEndFrom instanceof Date) {\n filters.period_end = Object.assign(\n (filters.period_end as Record<string, unknown>) ?? {},\n { $gte: query.periodEndFrom },\n )\n }\n if (query.periodEndTo instanceof Date) {\n filters.period_end = Object.assign(\n (filters.period_end as Record<string, unknown>) ?? {},\n { $lte: query.periodEndTo },\n )\n }\n return filters\n },\n },\n actions: {},\n})\n\nexport const GET = crud.GET\n\nexport const openApi = createBillingCrudOpenApi({\n resourceName: 'BillingStatement',\n pluralName: 'BillingStatements',\n querySchema: billingStatementListQuerySchema,\n listResponseSchema: createPagedListResponseSchema(billingStatementListItemSchema),\n})\n"],
5
+ "mappings": "AAAA,SAAS,SAAS;AAClB,SAAS,qBAAqB;AAC9B,SAAS,wBAAwB;AACjC,SAAS,wBAAwB;AACjC,SAAS,uCAAuC;AAChD;AAAA,EACE;AAAA,EACA;AAAA,OACK;AASP,MAAM,gBAAgB;AAAA,EACpB,KAAK,EAAE,aAAa,MAAM,iBAAiB,CAAC,wBAAwB,EAAE;AACxE;AAEO,MAAM,WAAW;AAExB,MAAM,iCAAiC,EA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OAAO,UAAU;AAC7B,YAAM,UAAmC,CAAC;AAC1C,UAAI,OAAO,MAAM,OAAO,YAAY,MAAM,IAAI;AAC5C,gBAAQ,KAAK,EAAE,KAAK,MAAM,GAAG;AAAA,MAC/B;AACA,UAAI,OAAO,MAAM,kBAAkB,YAAY,MAAM,eAAe;AAClE,gBAAQ,kBAAkB,EAAE,KAAK,MAAM,cAAc;AAAA,MACvD;AACA,UAAI,OAAO,MAAM,WAAW,YAAY,MAAM,QAAQ;AACpD,gBAAQ,SAAS,EAAE,KAAK,MAAM,OAAO;AAAA,MACvC;AACA,UAAI,MAAM,yBAAyB,MAAM;AACvC,gBAAQ,aAAa,OAAO;AAAA,UACzB,QAAQ,cAA0C,CAAC;AAAA,UACpD,EAAE,MAAM,MAAM,cAAc;AAAA,QAC9B;AAAA,MACF;AACA,UAAI,MAAM,uBAAuB,MAAM;AACrC,gBAAQ,aAAa,OAAO;AAAA,UACzB,QAAQ,cAA0C,CAAC;AAAA,UACpD,EAAE,MAAM,MAAM,YAAY;AAAA,QAC5B;AAAA,MACF;AACA,aAAO;AAAA,IACT;AAAA,EACF;AAAA,EACA,SAAS,CAAC;AACZ,CAAC;AAEM,MAAM,MAAM,KAAK;AAEjB,MAAM,UAAU,yBAAyB;AAAA,EAC9C,cAAc;AAAA,EACd,YAAY;AAAA,EACZ,aAAa;AAAA,EACb,oBAAoB,8BAA8B,8BAA8B;AAClF,CAAC;",
6
+ "names": []
7
+ }
@@ -0,0 +1,139 @@
1
+ import { z } from "zod";
2
+ import { makeCrudRoute } from "@open-mercato/shared/lib/crud/factory";
3
+ import { withScopedPayload } from "@open-mercato/shared/lib/api/scoped";
4
+ import { resolveTranslations } from "@open-mercato/shared/lib/i18n/server";
5
+ import { BillingTopup } from "../../data/entities.js";
6
+ import { billingEntityIds } from "../../data/entityIds.js";
7
+ import {
8
+ billingTopupCreateSchema,
9
+ billingTopupListQuerySchema
10
+ } from "../../data/validators.js";
11
+ import {
12
+ createBillingCrudOpenApi,
13
+ createPagedListResponseSchema
14
+ } from "../openapi.js";
15
+ const routeMetadata = {
16
+ GET: { requireAuth: true, requireFeatures: ["billing.topup.view"] },
17
+ POST: { requireAuth: true, requireFeatures: ["billing.topup.create"] }
18
+ };
19
+ const metadata = routeMetadata;
20
+ const billingTopupListItemSchema = z.object({
21
+ id: z.string().uuid(),
22
+ bill_account_id: z.string().uuid(),
23
+ status: z.string(),
24
+ amount: z.string(),
25
+ currency_code: z.string(),
26
+ provider_key: z.string(),
27
+ payment_id: z.string().uuid(),
28
+ gateway_transaction_id: z.string().uuid().nullable(),
29
+ transaction_id: z.string().uuid().nullable(),
30
+ receipt_invoice_id: z.string().uuid().nullable(),
31
+ source_ref: z.string().nullable(),
32
+ metadata: z.record(z.string(), z.unknown()).nullable(),
33
+ organization_id: z.string().uuid(),
34
+ tenant_id: z.string().uuid(),
35
+ created_at: z.string(),
36
+ updated_at: z.string()
37
+ });
38
+ const topupCreateResponseSchema = z.object({
39
+ topupId: z.string().uuid(),
40
+ paymentId: z.string().uuid(),
41
+ status: z.string(),
42
+ transactionId: z.string().uuid().nullable(),
43
+ redirectUrl: z.string().nullable(),
44
+ clientSecret: z.string().nullable()
45
+ });
46
+ const rawBodySchema = z.object({}).passthrough();
47
+ const crud = makeCrudRoute({
48
+ metadata: routeMetadata,
49
+ orm: {
50
+ entity: BillingTopup,
51
+ idField: "id",
52
+ orgField: "organizationId",
53
+ tenantField: "tenantId",
54
+ softDeleteField: "deletedAt"
55
+ },
56
+ list: {
57
+ schema: billingTopupListQuerySchema,
58
+ entityId: billingEntityIds.topup,
59
+ fields: [
60
+ "id",
61
+ "bill_account_id",
62
+ "status",
63
+ "amount",
64
+ "currency_code",
65
+ "provider_key",
66
+ "payment_id",
67
+ "gateway_transaction_id",
68
+ "transaction_id",
69
+ "receipt_invoice_id",
70
+ "source_ref",
71
+ "metadata",
72
+ "organization_id",
73
+ "tenant_id",
74
+ "created_at",
75
+ "updated_at"
76
+ ],
77
+ sortFieldMap: {
78
+ createdAt: "created_at",
79
+ updatedAt: "updated_at",
80
+ amount: "amount"
81
+ },
82
+ buildFilters: async (query) => {
83
+ const filters = {};
84
+ if (typeof query.id === "string" && query.id) {
85
+ filters.id = { $eq: query.id };
86
+ }
87
+ if (typeof query.billAccountId === "string" && query.billAccountId) {
88
+ filters.bill_account_id = { $eq: query.billAccountId };
89
+ }
90
+ if (typeof query.status === "string" && query.status) {
91
+ filters.status = { $eq: query.status };
92
+ }
93
+ if (typeof query.search === "string" && /^[0-9a-fA-F-]{36}$/.test(query.search.trim())) {
94
+ filters.id = { $eq: query.search.trim() };
95
+ }
96
+ return filters;
97
+ }
98
+ },
99
+ actions: {
100
+ create: {
101
+ commandId: "billing.topups.create",
102
+ schema: rawBodySchema,
103
+ mapInput: async ({ raw, ctx }) => {
104
+ const { translate } = await resolveTranslations();
105
+ const scoped = withScopedPayload(raw ?? {}, ctx, translate);
106
+ return billingTopupCreateSchema.parse(scoped);
107
+ },
108
+ response: ({ result }) => ({
109
+ topupId: result?.topupId ?? null,
110
+ paymentId: result?.paymentId ?? null,
111
+ status: result?.status ?? null,
112
+ transactionId: result?.transactionId ?? null,
113
+ redirectUrl: result?.redirectUrl ?? null,
114
+ clientSecret: result?.clientSecret ?? null
115
+ }),
116
+ status: 201
117
+ }
118
+ }
119
+ });
120
+ const { POST } = crud;
121
+ const GET = crud.GET;
122
+ const openApi = createBillingCrudOpenApi({
123
+ resourceName: "BillingTopup",
124
+ pluralName: "BillingTopups",
125
+ querySchema: billingTopupListQuerySchema,
126
+ listResponseSchema: createPagedListResponseSchema(billingTopupListItemSchema),
127
+ create: {
128
+ schema: billingTopupCreateSchema,
129
+ responseSchema: topupCreateResponseSchema,
130
+ description: "Registers a prepaid top-up (status=pending) and opens a payment session via core/payment_gateways. The balance is credited only on `payment_gateways.payment.captured` (the capture subscriber issues the VAT receipt). Returns the topup id, the payment session redirect URL / client secret, and the gateway transaction id."
131
+ }
132
+ });
133
+ export {
134
+ GET,
135
+ POST,
136
+ metadata,
137
+ openApi
138
+ };
139
+ //# sourceMappingURL=route.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../../src/modules/billing/api/topups/route.ts"],
4
+ "sourcesContent": ["import { z } from 'zod'\nimport { makeCrudRoute } from '@open-mercato/shared/lib/crud/factory'\nimport { withScopedPayload } from '@open-mercato/shared/lib/api/scoped'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { BillingTopup } from '../../data/entities'\nimport { billingEntityIds } from '../../data/entityIds'\nimport {\n billingTopupCreateSchema,\n billingTopupListQuerySchema,\n} from '../../data/validators'\nimport {\n createBillingCrudOpenApi,\n createPagedListResponseSchema,\n} from '../openapi'\n\n/**\n * `/api/billing/topups` \u2014 GET (list registered top-ups) + POST (initiate).\n *\n * The nested, spec-faithful `POST /api/billing/accounts/{id}/topups` is a thin\n * wrapper that injects the path id as `billAccountId` and delegates here, so\n * all the RBAC / command-bus / side-effect plumbing lives in one place.\n */\n\nconst routeMetadata = {\n GET: { requireAuth: true, requireFeatures: ['billing.topup.view'] },\n POST: { requireAuth: true, requireFeatures: ['billing.topup.create'] },\n}\n\nexport const metadata = routeMetadata\n\nconst billingTopupListItemSchema = z.object({\n id: z.string().uuid(),\n bill_account_id: z.string().uuid(),\n status: z.string(),\n amount: z.string(),\n currency_code: z.string(),\n provider_key: z.string(),\n payment_id: z.string().uuid(),\n gateway_transaction_id: z.string().uuid().nullable(),\n transaction_id: z.string().uuid().nullable(),\n receipt_invoice_id: z.string().uuid().nullable(),\n source_ref: z.string().nullable(),\n metadata: z.record(z.string(), z.unknown()).nullable(),\n organization_id: z.string().uuid(),\n tenant_id: z.string().uuid(),\n created_at: z.string(),\n updated_at: z.string(),\n})\n\nconst topupCreateResponseSchema = z.object({\n topupId: z.string().uuid(),\n paymentId: z.string().uuid(),\n status: z.string(),\n transactionId: z.string().uuid().nullable(),\n redirectUrl: z.string().nullable(),\n clientSecret: z.string().nullable(),\n})\n\nconst rawBodySchema = z.object({}).passthrough()\n\nconst crud = makeCrudRoute({\n metadata: routeMetadata,\n orm: {\n entity: BillingTopup,\n idField: 'id',\n orgField: 'organizationId',\n tenantField: 'tenantId',\n softDeleteField: 'deletedAt',\n },\n list: {\n schema: billingTopupListQuerySchema,\n entityId: billingEntityIds.topup,\n fields: [\n 'id',\n 'bill_account_id',\n 'status',\n 'amount',\n 'currency_code',\n 'provider_key',\n 'payment_id',\n 'gateway_transaction_id',\n 'transaction_id',\n 'receipt_invoice_id',\n 'source_ref',\n 'metadata',\n 'organization_id',\n 'tenant_id',\n 'created_at',\n 'updated_at',\n ],\n sortFieldMap: {\n createdAt: 'created_at',\n updatedAt: 'updated_at',\n amount: 'amount',\n },\n buildFilters: async (query) => {\n const filters: Record<string, unknown> = {}\n if (typeof query.id === 'string' && query.id) {\n filters.id = { $eq: query.id }\n }\n if (typeof query.billAccountId === 'string' && query.billAccountId) {\n filters.bill_account_id = { $eq: query.billAccountId }\n }\n if (typeof query.status === 'string' && query.status) {\n filters.status = { $eq: query.status }\n }\n if (typeof query.search === 'string' && /^[0-9a-fA-F-]{36}$/.test(query.search.trim())) {\n filters.id = { $eq: query.search.trim() }\n }\n return filters\n },\n },\n actions: {\n create: {\n commandId: 'billing.topups.create',\n schema: rawBodySchema,\n mapInput: async ({ raw, ctx }) => {\n const { translate } = await resolveTranslations()\n const scoped = withScopedPayload(raw ?? {}, ctx, translate)\n return billingTopupCreateSchema.parse(scoped)\n },\n response: ({ result }) => ({\n topupId: result?.topupId ?? null,\n paymentId: result?.paymentId ?? null,\n status: result?.status ?? null,\n transactionId: result?.transactionId ?? null,\n redirectUrl: result?.redirectUrl ?? null,\n clientSecret: result?.clientSecret ?? null,\n }),\n status: 201,\n },\n },\n})\n\nconst { POST } = crud\nexport { POST }\nexport const GET = crud.GET\n\nexport const openApi = createBillingCrudOpenApi({\n resourceName: 'BillingTopup',\n pluralName: 'BillingTopups',\n querySchema: billingTopupListQuerySchema,\n listResponseSchema: createPagedListResponseSchema(billingTopupListItemSchema),\n create: {\n schema: billingTopupCreateSchema,\n responseSchema: topupCreateResponseSchema,\n description:\n 'Registers a prepaid top-up (status=pending) and opens a payment ' +\n 'session via core/payment_gateways. The balance is credited only on ' +\n '`payment_gateways.payment.captured` (the capture subscriber issues the ' +\n 'VAT receipt). Returns the topup id, the payment session redirect URL / ' +\n 'client secret, and the gateway transaction id.',\n },\n})\n"],
5
+ "mappings": "AAAA,SAAS,SAAS;AAClB,SAAS,qBAAqB;AAC9B,SAAS,yBAAyB;AAClC,SAAS,2BAA2B;AACpC,SAAS,oBAAoB;AAC7B,SAAS,wBAAwB;AACjC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAUP,MAAM,gBAAgB;AAAA,EACpB,KAAK,EAAE,aAAa,MAAM,iBAAiB,CAAC,oBAAoB,EAAE;AAAA,EAClE,MAAM,EAAE,aAAa,MAAM,iBAAiB,CAAC,sBAAsB,EAAE;AACvE;AAEO,MAAM,WAAW;AAExB,MAAM,6BAA6B,EAAE,OAAO;AAAA,EAC1C,IAAI,EAAE,OAAO,EAAE,KAAK;AAAA,EACpB,iBAAiB,EAAE,OAAO,EAAE,KAAK;AAAA,EACjC,QAAQ,EAAE,OAAO;AAAA,EACjB,QAAQ,EAAE,OAAO;AAAA,EACjB,eAAe,EAAE,OAAO;AAAA,EACxB,cAAc,EAAE,OAAO;AAAA,EACvB,YAAY,EAAE,OAAO,EAAE,KAAK;AAAA,EAC5B,wBAAwB,EAAE,OAAO,EAAE,KAAK,EAAE,SAAS;AAAA,EACnD,gBAAgB,EAAE,OAAO,EAAE,KAAK,EAAE,SAAS;AAAA,EAC3C,oBAAoB,EAAE,OAAO,EAAE,KAAK,EAAE,SAAS;AAAA,EAC/C,YAAY,EAAE,OAAO,EAAE,SAAS;AAAA,EAChC,UAAU,EAAE,OAAO,EAAE,OAAO,GAAG,EAAE,QAAQ,CAAC,EAAE,SAAS;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"zod";
2
+ import { makeCrudRoute } from "@open-mercato/shared/lib/crud/factory";
3
+ import { withScopedPayload } from "@open-mercato/shared/lib/api/scoped";
4
+ import { resolveTranslations } from "@open-mercato/shared/lib/i18n/server";
5
+ import { BillingAccountTransaction } from "../../../data/entities.js";
6
+ import { billingEntityIds } from "../../../data/entityIds.js";
7
+ import { billingTransactionAdjustSchema } from "../../../data/validators.js";
8
+ import { createBillingCrudOpenApi } from "../../openapi.js";
9
+ const routeMetadata = {
10
+ POST: { requireAuth: true, requireFeatures: ["billing.balance.adjust"] }
11
+ };
12
+ const metadata = routeMetadata;
13
+ const adjustResponseSchema = z.object({
14
+ transactionId: z.string().uuid(),
15
+ balance: z.string(),
16
+ balanceStatus: z.enum(["ok", "low", "exhausted"]),
17
+ deduplicated: z.boolean()
18
+ });
19
+ const rawBodySchema = z.object({}).passthrough();
20
+ const crud = makeCrudRoute({
21
+ metadata: routeMetadata,
22
+ orm: {
23
+ entity: BillingAccountTransaction,
24
+ idField: "id",
25
+ orgField: "organizationId",
26
+ tenantField: "tenantId",
27
+ softDeleteField: "deletedAt"
28
+ },
29
+ list: {
30
+ schema: z.object({}).passthrough(),
31
+ entityId: billingEntityIds.transaction,
32
+ fields: ["id"],
33
+ buildFilters: async () => ({})
34
+ },
35
+ actions: {
36
+ create: {
37
+ commandId: "billing.transactions.adjust",
38
+ schema: rawBodySchema,
39
+ mapInput: async ({ raw, ctx }) => {
40
+ const { translate } = await resolveTranslations();
41
+ const scoped = withScopedPayload(raw ?? {}, ctx, translate);
42
+ return billingTransactionAdjustSchema.parse(scoped);
43
+ },
44
+ response: ({ result }) => ({
45
+ transactionId: result?.transactionId ?? null,
46
+ balance: result?.balance ?? null,
47
+ balanceStatus: result?.balanceStatus ?? null,
48
+ deduplicated: Boolean(result?.deduplicated)
49
+ }),
50
+ status: 201
51
+ }
52
+ }
53
+ });
54
+ const POST = crud.POST;
55
+ const openApi = createBillingCrudOpenApi({
56
+ resourceName: "BillingBalanceAdjustment",
57
+ pluralName: "BillingBalanceAdjustments",
58
+ querySchema: z.object({}).passthrough(),
59
+ listResponseSchema: z.object({ items: z.array(z.unknown()) }),
60
+ create: {
61
+ schema: billingTransactionAdjustSchema,
62
+ responseSchema: adjustResponseSchema,
63
+ description: "Manually credits (amount > 0) or debits (amount < 0) a prepaid account's balance. Audited with the operator's user id. Non-fiscal \u2014 no receipt is issued. Returns the new balance + status."
64
+ }
65
+ });
66
+ export {
67
+ POST,
68
+ metadata,
69
+ openApi
70
+ };
71
+ //# sourceMappingURL=route.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../../../src/modules/billing/api/transactions/adjust/route.ts"],
4
+ "sourcesContent": ["import { z } from 'zod'\nimport { makeCrudRoute } from '@open-mercato/shared/lib/crud/factory'\nimport { withScopedPayload } from '@open-mercato/shared/lib/api/scoped'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { BillingAccountTransaction } from '../../../data/entities'\nimport { billingEntityIds } from '../../../data/entityIds'\nimport { billingTransactionAdjustSchema } from '../../../data/validators'\nimport { createBillingCrudOpenApi } from '../../openapi'\n\n/**\n * `POST /api/billing/transactions/adjust` (SPEC-002 P5) \u2014 manual balance\n * credit/debit (`type='adjustment'`), audited with the operator's `user_id`.\n */\n\nconst routeMetadata = {\n POST: { requireAuth: true, requireFeatures: ['billing.balance.adjust'] },\n}\n\nexport const metadata = routeMetadata\n\nconst adjustResponseSchema = z.object({\n transactionId: z.string().uuid(),\n balance: z.string(),\n balanceStatus: z.enum(['ok', 'low', 'exhausted']),\n deduplicated: z.boolean(),\n})\n\nconst rawBodySchema = z.object({}).passthrough()\n\nconst crud = makeCrudRoute({\n metadata: routeMetadata,\n orm: {\n entity: BillingAccountTransaction,\n idField: 'id',\n orgField: 'organizationId',\n tenantField: 'tenantId',\n softDeleteField: 'deletedAt',\n },\n list: {\n schema: z.object({}).passthrough(),\n entityId: billingEntityIds.transaction,\n fields: ['id'],\n buildFilters: async () => ({}),\n },\n actions: {\n create: {\n commandId: 'billing.transactions.adjust',\n schema: rawBodySchema,\n mapInput: async ({ raw, ctx }) => {\n const { translate } = await resolveTranslations()\n const scoped = withScopedPayload(raw ?? {}, ctx, translate)\n return billingTransactionAdjustSchema.parse(scoped)\n },\n response: ({ result }) => ({\n transactionId: result?.transactionId ?? null,\n balance: result?.balance ?? null,\n balanceStatus: result?.balanceStatus ?? null,\n deduplicated: Boolean(result?.deduplicated),\n }),\n status: 201,\n },\n },\n})\n\nexport const POST = crud.POST\n\nexport const openApi = createBillingCrudOpenApi({\n resourceName: 'BillingBalanceAdjustment',\n pluralName: 'BillingBalanceAdjustments',\n querySchema: z.object({}).passthrough(),\n listResponseSchema: z.object({ items: z.array(z.unknown()) }),\n create: {\n schema: billingTransactionAdjustSchema,\n responseSchema: adjustResponseSchema,\n description:\n 'Manually credits (amount > 0) or debits (amount < 0) a prepaid ' +\n \"account's balance. Audited with the operator's user id. Non-fiscal \u2014 \" +\n 'no receipt is issued. Returns the new balance + status.',\n },\n})\n"],
5
+ "mappings": "AAAA,SAAS,SAAS;AAClB,SAAS,qBAAqB;AAC9B,SAAS,yBAAyB;AAClC,SAAS,2BAA2B;AACpC,SAAS,iCAAiC;AAC1C,SAAS,wBAAwB;AACjC,SAAS,sCAAsC;AAC/C,SAAS,gCAAgC;AAOzC,MAAM,gBAAgB;AAAA,EACpB,MAAM,EAAE,aAAa,MAAM,iBAAiB,CAAC,wBAAwB,EAAE;AACzE;AAEO,MAAM,WAAW;AAExB,MAAM,uBAAuB,EAAE,OAAO;AAAA,EACpC,eAAe,EAAE,OAAO,EAAE,KAAK;AAAA,EAC/B,SAAS,EAAE,OAAO;AAAA,EAClB,eAAe,EAAE,KAAK,CAAC,MAAM,OAAO,WAAW,CAAC;AAAA,EAChD,cAAc,EAAE,QAAQ;AAC1B,CAAC;AAED,MAAM,gBAAgB,EAAE,OAAO,CAAC,CAAC,EAAE,YAAY;AAE/C,MAAM,OAAO,cAAc;A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