@dainamite/billing 0.17.0 → 0.18.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 (205) hide show
  1. package/CHANGELOG.md +81 -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 +1 -1
  129. package/src/modules/billing/__tests__/commands/topups.test.ts +104 -0
  130. package/src/modules/billing/__tests__/commands/transactions.test.ts +84 -0
  131. package/src/modules/billing/__tests__/helpers/prepaidMockEm.ts +235 -0
  132. package/src/modules/billing/__tests__/lib/accountStatus.test.ts +93 -0
  133. package/src/modules/billing/__tests__/lib/balanceLedger.test.ts +125 -0
  134. package/src/modules/billing/__tests__/lib/balanceStatus.test.ts +65 -0
  135. package/src/modules/billing/__tests__/lib/creditStatus.test.ts +111 -0
  136. package/src/modules/billing/__tests__/lib/money.test.ts +56 -0
  137. package/src/modules/billing/__tests__/lib/prepaidConsume.test.ts +179 -0
  138. package/src/modules/billing/__tests__/lib/prepaidPeriodClose.test.ts +232 -0
  139. package/src/modules/billing/__tests__/lib/topupCapture.test.ts +123 -0
  140. package/src/modules/billing/__tests__/lib/topupReceipt.test.ts +84 -0
  141. package/src/modules/billing/__tests__/setup.test.ts +28 -2
  142. package/src/modules/billing/acl.ts +8 -0
  143. package/src/modules/billing/api/accounts/[id]/balance/route.ts +74 -0
  144. package/src/modules/billing/api/accounts/[id]/credit-status/route.ts +71 -0
  145. package/src/modules/billing/api/accounts/[id]/topups/route.ts +49 -0
  146. package/src/modules/billing/api/accounts/route.ts +7 -0
  147. package/src/modules/billing/api/export/account/[id]/route.ts +47 -2
  148. package/src/modules/billing/api/statements/generate/route.ts +78 -0
  149. package/src/modules/billing/api/statements/route.ts +117 -0
  150. package/src/modules/billing/api/topups/route.ts +154 -0
  151. package/src/modules/billing/api/transactions/adjust/route.ts +80 -0
  152. package/src/modules/billing/api/transactions/route.ts +116 -0
  153. package/src/modules/billing/api/usage/route.ts +36 -5
  154. package/src/modules/billing/backend/billing/accounts/[id]/page.tsx +28 -0
  155. package/src/modules/billing/backend/billing/accounts/create/page.tsx +7 -0
  156. package/src/modules/billing/backend/billing/accounts/page.tsx +32 -1
  157. package/src/modules/billing/backend/billing/statements/[id]/page.meta.ts +19 -0
  158. package/src/modules/billing/backend/billing/statements/[id]/page.tsx +198 -0
  159. package/src/modules/billing/backend/billing/statements/page.meta.ts +16 -0
  160. package/src/modules/billing/backend/billing/statements/page.tsx +190 -0
  161. package/src/modules/billing/backend/billing/topups/[id]/page.meta.ts +19 -0
  162. package/src/modules/billing/backend/billing/topups/[id]/page.tsx +151 -0
  163. package/src/modules/billing/backend/billing/topups/page.meta.ts +16 -0
  164. package/src/modules/billing/backend/billing/topups/page.tsx +182 -0
  165. package/src/modules/billing/backend/billing/transactions/[id]/page.meta.ts +19 -0
  166. package/src/modules/billing/backend/billing/transactions/[id]/page.tsx +179 -0
  167. package/src/modules/billing/backend/billing/transactions/page.meta.ts +16 -0
  168. package/src/modules/billing/backend/billing/transactions/page.tsx +187 -0
  169. package/src/modules/billing/commands/accounts.ts +42 -1
  170. package/src/modules/billing/commands/index.ts +3 -0
  171. package/src/modules/billing/commands/invoices.ts +26 -2
  172. package/src/modules/billing/commands/statements.ts +101 -0
  173. package/src/modules/billing/commands/topups.ts +181 -0
  174. package/src/modules/billing/commands/transactions.ts +152 -0
  175. package/src/modules/billing/commands/usage.ts +114 -4
  176. package/src/modules/billing/components/AccountForm.tsx +66 -0
  177. package/src/modules/billing/components/PrepaidPanel.tsx +382 -0
  178. package/src/modules/billing/components/accountNames.ts +23 -0
  179. package/src/modules/billing/data/entities.ts +383 -0
  180. package/src/modules/billing/data/entityIds.ts +5 -0
  181. package/src/modules/billing/data/validators.ts +144 -0
  182. package/src/modules/billing/events.ts +52 -0
  183. package/src/modules/billing/i18n/en.json +112 -4
  184. package/src/modules/billing/i18n/pl.json +112 -4
  185. package/src/modules/billing/index.ts +1 -1
  186. package/src/modules/billing/lib/accountStatus.ts +155 -0
  187. package/src/modules/billing/lib/balanceEvents.ts +74 -0
  188. package/src/modules/billing/lib/balanceLedger.ts +258 -0
  189. package/src/modules/billing/lib/balanceStatus.ts +78 -0
  190. package/src/modules/billing/lib/billRunEngine.ts +66 -5
  191. package/src/modules/billing/lib/creditStatus.ts +153 -0
  192. package/src/modules/billing/lib/money.ts +73 -0
  193. package/src/modules/billing/lib/prepaidConfig.ts +58 -0
  194. package/src/modules/billing/lib/prepaidConsume.ts +299 -0
  195. package/src/modules/billing/lib/prepaidPeriodClose.ts +453 -0
  196. package/src/modules/billing/lib/topupCapture.ts +117 -0
  197. package/src/modules/billing/lib/topupReceipt.ts +153 -0
  198. package/src/modules/billing/lib/topupTransition.ts +31 -0
  199. package/src/modules/billing/migrations/Migration20260619000000_billing_prepaid.ts +131 -0
  200. package/src/modules/billing/setup.ts +45 -0
  201. package/src/modules/billing/subscribers/prepaid-topup-cancelled.ts +31 -0
  202. package/src/modules/billing/subscribers/prepaid-topup-captured.ts +120 -0
  203. package/src/modules/billing/subscribers/prepaid-topup-expired.ts +31 -0
  204. package/src/modules/billing/subscribers/prepaid-topup-failed.ts +32 -0
  205. package/src/modules/billing/workers/reconcile-prepaid-balances.ts +68 -0
@@ -0,0 +1,314 @@
1
+ "use client";
2
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
3
+ import * as React from "react";
4
+ import { useRouter } from "next/navigation";
5
+ import { Plus, SlidersHorizontal } from "lucide-react";
6
+ import { useT } from "@open-mercato/shared/lib/i18n/context";
7
+ import { DataTable } from "@open-mercato/ui/backend/DataTable";
8
+ import { Tag } from "@open-mercato/ui/primitives/tag";
9
+ import { Button } from "@open-mercato/ui/primitives/button";
10
+ import { flash } from "@open-mercato/ui/backend/FlashMessages";
11
+ import { apiCallOrThrow, readApiResultOrThrow } from "@open-mercato/ui/backend/utils/apiCall";
12
+ import { normalizeCrudServerError } from "@open-mercato/ui/backend/utils/serverErrors";
13
+ import { StatCard, Stat } from "./DetailFields.js";
14
+ function balanceVariant(status) {
15
+ if (status === "low") return "warning";
16
+ if (status === "exhausted") return "error";
17
+ return "success";
18
+ }
19
+ function creditVariant(status) {
20
+ if (status === "near_limit") return "warning";
21
+ if (status === "over_limit") return "error";
22
+ return "success";
23
+ }
24
+ function txnVariant(type) {
25
+ if (type === "topup" || type === "adjustment") return "success";
26
+ if (type === "usage") return "info";
27
+ return "neutral";
28
+ }
29
+ function formatDateTime(value) {
30
+ if (!value) return "\u2014";
31
+ const d = new Date(value);
32
+ return Number.isNaN(d.getTime()) ? value : d.toLocaleString();
33
+ }
34
+ function PrepaidPanel({
35
+ accountId,
36
+ currencyCode
37
+ }) {
38
+ const t = useT();
39
+ const router = useRouter();
40
+ const [balance, setBalance] = React.useState(null);
41
+ const [credit, setCredit] = React.useState(null);
42
+ const [rows, setRows] = React.useState([]);
43
+ const [page, setPage] = React.useState(1);
44
+ const [total, setTotal] = React.useState(0);
45
+ const [totalPages, setTotalPages] = React.useState(1);
46
+ const [loading, setLoading] = React.useState(true);
47
+ const [topupOpen, setTopupOpen] = React.useState(false);
48
+ const [amount, setAmount] = React.useState("");
49
+ const [submitting, setSubmitting] = React.useState(false);
50
+ const [adjustOpen, setAdjustOpen] = React.useState(false);
51
+ const [adjAmount, setAdjAmount] = React.useState("");
52
+ const [adjReason, setAdjReason] = React.useState("");
53
+ const [adjSubmitting, setAdjSubmitting] = React.useState(false);
54
+ const pageSize = 10;
55
+ const loadStatus = React.useCallback(async () => {
56
+ const [bal, cred] = await Promise.all([
57
+ readApiResultOrThrow(`/api/billing/accounts/${accountId}/balance`),
58
+ readApiResultOrThrow(`/api/billing/accounts/${accountId}/credit-status`)
59
+ ]);
60
+ setBalance(bal);
61
+ setCredit(cred);
62
+ }, [accountId]);
63
+ const loadTransactions = React.useCallback(async () => {
64
+ setLoading(true);
65
+ try {
66
+ const result = await readApiResultOrThrow(
67
+ `/api/billing/transactions?billAccountId=${accountId}&page=${page}&pageSize=${pageSize}&sortField=createdAt&sortDir=desc`
68
+ );
69
+ setRows(result.items ?? []);
70
+ setTotal(result.total ?? 0);
71
+ setTotalPages(result.totalPages ?? 1);
72
+ } finally {
73
+ setLoading(false);
74
+ }
75
+ }, [accountId, page]);
76
+ React.useEffect(() => {
77
+ void loadStatus().catch(() => void 0);
78
+ }, [loadStatus]);
79
+ React.useEffect(() => {
80
+ void loadTransactions();
81
+ }, [loadTransactions]);
82
+ const handleTopup = React.useCallback(async () => {
83
+ const value = Number.parseFloat(amount);
84
+ if (!Number.isFinite(value) || value <= 0) {
85
+ flash(t("billing.prepaid.topup.invalid", "Enter a positive amount"), "error");
86
+ return;
87
+ }
88
+ setSubmitting(true);
89
+ try {
90
+ const res = await apiCallOrThrow(
91
+ `/api/billing/accounts/${accountId}/topups`,
92
+ {
93
+ method: "POST",
94
+ headers: { "Content-Type": "application/json" },
95
+ body: JSON.stringify({
96
+ amount: value,
97
+ successUrl: typeof window !== "undefined" ? window.location.href : void 0,
98
+ cancelUrl: typeof window !== "undefined" ? window.location.href : void 0
99
+ })
100
+ }
101
+ );
102
+ const redirectUrl = res.result?.redirectUrl;
103
+ if (redirectUrl && typeof window !== "undefined") {
104
+ window.location.href = redirectUrl;
105
+ return;
106
+ }
107
+ flash(t("billing.prepaid.topup.created", "Top-up session created"), "success");
108
+ setTopupOpen(false);
109
+ setAmount("");
110
+ void loadStatus().catch(() => void 0);
111
+ void loadTransactions();
112
+ } catch (err) {
113
+ const { message } = normalizeCrudServerError(err);
114
+ flash(message || t("billing.prepaid.topup.error", "Top-up failed"), "error");
115
+ } finally {
116
+ setSubmitting(false);
117
+ }
118
+ }, [accountId, amount, loadStatus, loadTransactions, t]);
119
+ const handleAdjust = React.useCallback(async () => {
120
+ const value = Number.parseFloat(adjAmount);
121
+ if (!Number.isFinite(value) || value === 0) {
122
+ flash(t("billing.prepaid.adjust.invalid_amount", "Enter a non-zero amount"), "error");
123
+ return;
124
+ }
125
+ if (!adjReason.trim()) {
126
+ flash(t("billing.prepaid.adjust.invalid_description", "Enter a reason"), "error");
127
+ return;
128
+ }
129
+ setAdjSubmitting(true);
130
+ try {
131
+ await apiCallOrThrow("/api/billing/transactions/adjust", {
132
+ method: "POST",
133
+ headers: { "Content-Type": "application/json" },
134
+ body: JSON.stringify({
135
+ billAccountId: accountId,
136
+ amount: value,
137
+ description: adjReason.trim()
138
+ })
139
+ });
140
+ flash(t("billing.prepaid.adjust.success", "Balance adjusted"), "success");
141
+ setAdjustOpen(false);
142
+ setAdjAmount("");
143
+ setAdjReason("");
144
+ void loadStatus().catch(() => void 0);
145
+ void loadTransactions();
146
+ } catch (err) {
147
+ const { message } = normalizeCrudServerError(err);
148
+ flash(message || t("billing.prepaid.adjust.error", "Adjustment failed"), "error");
149
+ } finally {
150
+ setAdjSubmitting(false);
151
+ }
152
+ }, [accountId, adjAmount, adjReason, loadStatus, loadTransactions, t]);
153
+ const columns = React.useMemo(
154
+ () => [
155
+ {
156
+ accessorKey: "created_at",
157
+ header: t("billing.transactions.columns.when", "When"),
158
+ cell: ({ row }) => formatDateTime(row.original.created_at)
159
+ },
160
+ {
161
+ accessorKey: "type",
162
+ header: t("billing.transactions.columns.type", "Type"),
163
+ cell: ({ row }) => /* @__PURE__ */ jsx(Tag, { variant: txnVariant(row.original.type), children: t(`billing.transactions.type.${row.original.type}`, row.original.type) })
164
+ },
165
+ {
166
+ accessorKey: "description",
167
+ header: t("billing.transactions.columns.description", "Description"),
168
+ cell: ({ row }) => /* @__PURE__ */ jsx("span", { className: "text-sm", children: row.original.description })
169
+ },
170
+ {
171
+ accessorKey: "amount",
172
+ header: t("billing.transactions.columns.amount", "Amount"),
173
+ cell: ({ row }) => /* @__PURE__ */ jsx("span", { className: "font-mono tabular-nums", children: row.original.amount })
174
+ },
175
+ {
176
+ accessorKey: "balance_after",
177
+ header: t("billing.transactions.columns.balance_after", "Balance"),
178
+ cell: ({ row }) => /* @__PURE__ */ jsx("span", { className: "font-mono tabular-nums", children: row.original.balance_after })
179
+ }
180
+ ],
181
+ [t]
182
+ );
183
+ return /* @__PURE__ */ jsxs("div", { className: "mt-6 space-y-4", children: [
184
+ /* @__PURE__ */ jsxs(StatCard, { title: t("billing.prepaid.panel.title", "Prepaid balance"), children: [
185
+ /* @__PURE__ */ jsx(
186
+ Stat,
187
+ {
188
+ label: t("billing.prepaid.panel.balance", "Balance"),
189
+ value: /* @__PURE__ */ jsxs("span", { className: "flex items-center gap-2", children: [
190
+ /* @__PURE__ */ jsxs("span", { className: "font-mono tabular-nums", children: [
191
+ balance?.balance ?? "\u2014",
192
+ " ",
193
+ currencyCode
194
+ ] }),
195
+ balance ? /* @__PURE__ */ jsx(Tag, { variant: balanceVariant(balance.balanceStatus), children: t(`billing.prepaid.status.${balance.balanceStatus}`, balance.balanceStatus) }) : null
196
+ ] })
197
+ }
198
+ ),
199
+ /* @__PURE__ */ jsx(
200
+ Stat,
201
+ {
202
+ label: t("billing.prepaid.panel.threshold", "Low threshold"),
203
+ value: /* @__PURE__ */ jsx("span", { className: "font-mono tabular-nums", children: balance?.lowBalanceThreshold ?? "\u2014" })
204
+ }
205
+ ),
206
+ credit ? /* @__PURE__ */ jsx(
207
+ Stat,
208
+ {
209
+ label: t("billing.prepaid.panel.credit", "Credit"),
210
+ value: /* @__PURE__ */ jsxs("span", { className: "flex items-center gap-2", children: [
211
+ /* @__PURE__ */ jsxs("span", { className: "font-mono tabular-nums", children: [
212
+ credit.creditUsed,
213
+ " / ",
214
+ credit.creditLimit
215
+ ] }),
216
+ /* @__PURE__ */ jsx(Tag, { variant: creditVariant(credit.creditStatus), children: t(`billing.prepaid.credit.${credit.creditStatus}`, credit.creditStatus) })
217
+ ] })
218
+ }
219
+ ) : null,
220
+ /* @__PURE__ */ jsx(
221
+ Stat,
222
+ {
223
+ label: t("billing.prepaid.panel.last_movement", "Last movement"),
224
+ value: formatDateTime(balance?.lastMovementAt)
225
+ }
226
+ )
227
+ ] }),
228
+ /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [
229
+ !topupOpen && !adjustOpen ? /* @__PURE__ */ jsxs(Fragment, { children: [
230
+ /* @__PURE__ */ jsxs(Button, { type: "button", onClick: () => setTopupOpen(true), children: [
231
+ /* @__PURE__ */ jsx(Plus, { size: 16 }),
232
+ t("billing.prepaid.topup.action", "Top up")
233
+ ] }),
234
+ /* @__PURE__ */ jsxs(Button, { type: "button", variant: "outline", onClick: () => setAdjustOpen(true), children: [
235
+ /* @__PURE__ */ jsx(SlidersHorizontal, { size: 16 }),
236
+ t("billing.prepaid.adjust.action", "Adjust")
237
+ ] })
238
+ ] }) : null,
239
+ topupOpen ? /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
240
+ /* @__PURE__ */ jsx(
241
+ "input",
242
+ {
243
+ type: "number",
244
+ min: "0",
245
+ step: "0.01",
246
+ autoFocus: true,
247
+ value: amount,
248
+ onChange: (e) => setAmount(e.target.value),
249
+ onKeyDown: (e) => {
250
+ if (e.key === "Enter") void handleTopup();
251
+ if (e.key === "Escape") setTopupOpen(false);
252
+ },
253
+ placeholder: t("billing.prepaid.topup.amount", "Amount"),
254
+ className: "h-9 w-32 rounded-md border border-border bg-background px-3 text-sm"
255
+ }
256
+ ),
257
+ /* @__PURE__ */ jsx(Button, { type: "button", onClick: handleTopup, disabled: submitting, children: submitting ? t("billing.prepaid.topup.submitting", "Starting\u2026") : t("billing.prepaid.topup.confirm", "Start checkout") }),
258
+ /* @__PURE__ */ jsx(Button, { type: "button", variant: "outline", onClick: () => setTopupOpen(false), children: t("billing.common.cancel", "Cancel") })
259
+ ] }) : null,
260
+ adjustOpen ? /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [
261
+ /* @__PURE__ */ jsx(
262
+ "input",
263
+ {
264
+ type: "number",
265
+ step: "0.01",
266
+ autoFocus: true,
267
+ value: adjAmount,
268
+ onChange: (e) => setAdjAmount(e.target.value),
269
+ onKeyDown: (e) => {
270
+ if (e.key === "Enter") void handleAdjust();
271
+ if (e.key === "Escape") setAdjustOpen(false);
272
+ },
273
+ placeholder: t("billing.prepaid.adjust.amount", "Amount (+credit / \u2212debit)"),
274
+ className: "h-9 w-48 rounded-md border border-border bg-background px-3 text-sm"
275
+ }
276
+ ),
277
+ /* @__PURE__ */ jsx(
278
+ "input",
279
+ {
280
+ type: "text",
281
+ value: adjReason,
282
+ onChange: (e) => setAdjReason(e.target.value),
283
+ onKeyDown: (e) => {
284
+ if (e.key === "Enter") void handleAdjust();
285
+ if (e.key === "Escape") setAdjustOpen(false);
286
+ },
287
+ placeholder: t("billing.prepaid.adjust.description", "Reason"),
288
+ className: "h-9 w-64 rounded-md border border-border bg-background px-3 text-sm"
289
+ }
290
+ ),
291
+ /* @__PURE__ */ jsx(Button, { type: "button", onClick: handleAdjust, disabled: adjSubmitting, children: adjSubmitting ? t("billing.prepaid.adjust.submitting", "Applying\u2026") : t("billing.prepaid.adjust.confirm", "Apply adjustment") }),
292
+ /* @__PURE__ */ jsx(Button, { type: "button", variant: "outline", onClick: () => setAdjustOpen(false), children: t("billing.common.cancel", "Cancel") })
293
+ ] }) : null
294
+ ] }),
295
+ /* @__PURE__ */ jsx(
296
+ DataTable,
297
+ {
298
+ title: t("billing.prepaid.panel.transactions", "Balance transactions"),
299
+ columns,
300
+ data: rows,
301
+ isLoading: loading,
302
+ onRowClick: (row) => router.push(`/backend/billing/transactions/${row.id}`),
303
+ pagination: { page, pageSize, total, totalPages, onPageChange: setPage },
304
+ emptyState: /* @__PURE__ */ jsx("div", { className: "rounded-lg border bg-card p-6 text-center text-sm text-muted-foreground", children: t("billing.prepaid.panel.no_transactions", "No balance movements yet.") })
305
+ }
306
+ )
307
+ ] });
308
+ }
309
+ var PrepaidPanel_default = PrepaidPanel;
310
+ export {
311
+ PrepaidPanel,
312
+ PrepaidPanel_default as default
313
+ };
314
+ //# sourceMappingURL=PrepaidPanel.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/modules/billing/components/PrepaidPanel.tsx"],
4
+ "sourcesContent": ["\"use client\"\nimport * as React from 'react'\nimport { useRouter } from 'next/navigation'\nimport { Plus, SlidersHorizontal } from 'lucide-react'\nimport type { ColumnDef } from '@tanstack/react-table'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport { DataTable } from '@open-mercato/ui/backend/DataTable'\nimport { Tag } from '@open-mercato/ui/primitives/tag'\nimport { Button } from '@open-mercato/ui/primitives/button'\nimport { flash } from '@open-mercato/ui/backend/FlashMessages'\nimport { apiCallOrThrow, readApiResultOrThrow } from '@open-mercato/ui/backend/utils/apiCall'\nimport { normalizeCrudServerError } from '@open-mercato/ui/backend/utils/serverErrors'\nimport { StatCard, Stat } from './DetailFields'\n\n/**\n * Prepaid panel (SPEC-002 P4) injected into the Billing Account detail page\n * for `billing_mode='prepaid'` accounts: balance + status, credit status,\n * a top-up launcher, and the recent balance transactions.\n */\n\ntype BalanceSnapshot = {\n balance: string\n balanceStatus: 'ok' | 'low' | 'exhausted'\n lowBalanceThreshold: string\n lastMovementAt: string | null\n}\n\ntype CreditSnapshot = {\n mode: string\n creditLimit: string\n creditUsed: string\n availableCredit: string\n creditStatus: 'within_limit' | 'near_limit' | 'over_limit'\n}\n\ntype TransactionRow = {\n id: string\n type: string\n amount: string\n balance_after: string\n description: string\n created_at: string\n}\n\nfunction balanceVariant(status: string): 'success' | 'warning' | 'error' {\n if (status === 'low') return 'warning'\n if (status === 'exhausted') return 'error'\n return 'success'\n}\n\nfunction creditVariant(status: string): 'success' | 'warning' | 'error' {\n if (status === 'near_limit') return 'warning'\n if (status === 'over_limit') return 'error'\n return 'success'\n}\n\nfunction txnVariant(type: string): 'success' | 'info' | 'neutral' {\n if (type === 'topup' || type === 'adjustment') return 'success'\n if (type === 'usage') return 'info'\n return 'neutral'\n}\n\nfunction formatDateTime(value: string | null | undefined): string {\n if (!value) return '\u2014'\n const d = new Date(value)\n return Number.isNaN(d.getTime()) ? value : d.toLocaleString()\n}\n\nexport function PrepaidPanel({\n accountId,\n currencyCode,\n}: {\n accountId: string\n currencyCode: string\n}) {\n const t = useT()\n const router = useRouter()\n const [balance, setBalance] = React.useState<BalanceSnapshot | null>(null)\n const [credit, setCredit] = React.useState<CreditSnapshot | null>(null)\n const [rows, setRows] = React.useState<TransactionRow[]>([])\n const [page, setPage] = React.useState(1)\n const [total, setTotal] = React.useState(0)\n const [totalPages, setTotalPages] = React.useState(1)\n const [loading, setLoading] = React.useState(true)\n const [topupOpen, setTopupOpen] = React.useState(false)\n const [amount, setAmount] = React.useState('')\n const [submitting, setSubmitting] = React.useState(false)\n const [adjustOpen, setAdjustOpen] = React.useState(false)\n const [adjAmount, setAdjAmount] = React.useState('')\n const [adjReason, setAdjReason] = React.useState('')\n const [adjSubmitting, setAdjSubmitting] = React.useState(false)\n const pageSize = 10\n\n const loadStatus = React.useCallback(async () => {\n const [bal, cred] = await Promise.all([\n readApiResultOrThrow<BalanceSnapshot>(`/api/billing/accounts/${accountId}/balance`),\n readApiResultOrThrow<CreditSnapshot>(`/api/billing/accounts/${accountId}/credit-status`),\n ])\n setBalance(bal)\n setCredit(cred)\n }, [accountId])\n\n const loadTransactions = React.useCallback(async () => {\n setLoading(true)\n try {\n const result = await readApiResultOrThrow<{\n items: TransactionRow[]\n total: number\n totalPages: number\n }>(\n `/api/billing/transactions?billAccountId=${accountId}&page=${page}` +\n `&pageSize=${pageSize}&sortField=createdAt&sortDir=desc`,\n )\n setRows(result.items ?? [])\n setTotal(result.total ?? 0)\n setTotalPages(result.totalPages ?? 1)\n } finally {\n setLoading(false)\n }\n }, [accountId, page])\n\n React.useEffect(() => {\n void loadStatus().catch(() => undefined)\n }, [loadStatus])\n React.useEffect(() => {\n void loadTransactions()\n }, [loadTransactions])\n\n const handleTopup = React.useCallback(async () => {\n const value = Number.parseFloat(amount)\n if (!Number.isFinite(value) || value <= 0) {\n flash(t('billing.prepaid.topup.invalid', 'Enter a positive amount'), 'error')\n return\n }\n setSubmitting(true)\n try {\n const res = await apiCallOrThrow<{ redirectUrl?: string | null }>(\n `/api/billing/accounts/${accountId}/topups`,\n {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n amount: value,\n successUrl: typeof window !== 'undefined' ? window.location.href : undefined,\n cancelUrl: typeof window !== 'undefined' ? window.location.href : undefined,\n }),\n },\n )\n const redirectUrl = res.result?.redirectUrl\n if (redirectUrl && typeof window !== 'undefined') {\n window.location.href = redirectUrl\n return\n }\n flash(t('billing.prepaid.topup.created', 'Top-up session created'), 'success')\n setTopupOpen(false)\n setAmount('')\n void loadStatus().catch(() => undefined)\n void loadTransactions()\n } catch (err) {\n const { message } = normalizeCrudServerError(err)\n flash(message || t('billing.prepaid.topup.error', 'Top-up failed'), 'error')\n } finally {\n setSubmitting(false)\n }\n }, [accountId, amount, loadStatus, loadTransactions, t])\n\n const handleAdjust = React.useCallback(async () => {\n const value = Number.parseFloat(adjAmount)\n if (!Number.isFinite(value) || value === 0) {\n flash(t('billing.prepaid.adjust.invalid_amount', 'Enter a non-zero amount'), 'error')\n return\n }\n if (!adjReason.trim()) {\n flash(t('billing.prepaid.adjust.invalid_description', 'Enter a reason'), 'error')\n return\n }\n setAdjSubmitting(true)\n try {\n await apiCallOrThrow('/api/billing/transactions/adjust', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n billAccountId: accountId,\n amount: value,\n description: adjReason.trim(),\n }),\n })\n flash(t('billing.prepaid.adjust.success', 'Balance adjusted'), 'success')\n setAdjustOpen(false)\n setAdjAmount('')\n setAdjReason('')\n void loadStatus().catch(() => undefined)\n void loadTransactions()\n } catch (err) {\n const { message } = normalizeCrudServerError(err)\n flash(message || t('billing.prepaid.adjust.error', 'Adjustment failed'), 'error')\n } finally {\n setAdjSubmitting(false)\n }\n }, [accountId, adjAmount, adjReason, loadStatus, loadTransactions, t])\n\n const columns = React.useMemo<ColumnDef<TransactionRow>[]>(\n () => [\n {\n accessorKey: 'created_at',\n header: t('billing.transactions.columns.when', 'When'),\n cell: ({ row }) => formatDateTime(row.original.created_at),\n },\n {\n accessorKey: 'type',\n header: t('billing.transactions.columns.type', 'Type'),\n cell: ({ row }) => (\n <Tag variant={txnVariant(row.original.type)}>\n {t(`billing.transactions.type.${row.original.type}`, row.original.type)}\n </Tag>\n ),\n },\n {\n accessorKey: 'description',\n header: t('billing.transactions.columns.description', 'Description'),\n cell: ({ row }) => <span className=\"text-sm\">{row.original.description}</span>,\n },\n {\n accessorKey: 'amount',\n header: t('billing.transactions.columns.amount', 'Amount'),\n cell: ({ row }) => (\n <span className=\"font-mono tabular-nums\">{row.original.amount}</span>\n ),\n },\n {\n accessorKey: 'balance_after',\n header: t('billing.transactions.columns.balance_after', 'Balance'),\n cell: ({ row }) => (\n <span className=\"font-mono tabular-nums\">{row.original.balance_after}</span>\n ),\n },\n ],\n [t],\n )\n\n return (\n <div className=\"mt-6 space-y-4\">\n <StatCard title={t('billing.prepaid.panel.title', 'Prepaid balance')}>\n <Stat\n label={t('billing.prepaid.panel.balance', 'Balance')}\n value={\n <span className=\"flex items-center gap-2\">\n <span className=\"font-mono tabular-nums\">\n {balance?.balance ?? '\u2014'} {currencyCode}\n </span>\n {balance ? (\n <Tag variant={balanceVariant(balance.balanceStatus)}>\n {t(`billing.prepaid.status.${balance.balanceStatus}`, balance.balanceStatus)}\n </Tag>\n ) : null}\n </span>\n }\n />\n <Stat\n label={t('billing.prepaid.panel.threshold', 'Low threshold')}\n value={\n <span className=\"font-mono tabular-nums\">{balance?.lowBalanceThreshold ?? '\u2014'}</span>\n }\n />\n {credit ? (\n <Stat\n label={t('billing.prepaid.panel.credit', 'Credit')}\n value={\n <span className=\"flex items-center gap-2\">\n <span className=\"font-mono tabular-nums\">\n {credit.creditUsed} / {credit.creditLimit}\n </span>\n <Tag variant={creditVariant(credit.creditStatus)}>\n {t(`billing.prepaid.credit.${credit.creditStatus}`, credit.creditStatus)}\n </Tag>\n </span>\n }\n />\n ) : null}\n <Stat\n label={t('billing.prepaid.panel.last_movement', 'Last movement')}\n value={formatDateTime(balance?.lastMovementAt)}\n />\n </StatCard>\n\n <div className=\"flex flex-wrap items-center gap-2\">\n {!topupOpen && !adjustOpen ? (\n <>\n <Button type=\"button\" onClick={() => setTopupOpen(true)}>\n <Plus size={16} />\n {t('billing.prepaid.topup.action', 'Top up')}\n </Button>\n <Button type=\"button\" variant=\"outline\" onClick={() => setAdjustOpen(true)}>\n <SlidersHorizontal size={16} />\n {t('billing.prepaid.adjust.action', 'Adjust')}\n </Button>\n </>\n ) : null}\n\n {topupOpen ? (\n <div className=\"flex items-center gap-2\">\n <input\n type=\"number\"\n min=\"0\"\n step=\"0.01\"\n autoFocus\n value={amount}\n onChange={(e) => setAmount(e.target.value)}\n onKeyDown={(e) => {\n if (e.key === 'Enter') void handleTopup()\n if (e.key === 'Escape') setTopupOpen(false)\n }}\n placeholder={t('billing.prepaid.topup.amount', 'Amount')}\n className=\"h-9 w-32 rounded-md border border-border bg-background px-3 text-sm\"\n />\n <Button type=\"button\" onClick={handleTopup} disabled={submitting}>\n {submitting\n ? t('billing.prepaid.topup.submitting', 'Starting\u2026')\n : t('billing.prepaid.topup.confirm', 'Start checkout')}\n </Button>\n <Button type=\"button\" variant=\"outline\" onClick={() => setTopupOpen(false)}>\n {t('billing.common.cancel', 'Cancel')}\n </Button>\n </div>\n ) : null}\n\n {adjustOpen ? (\n <div className=\"flex flex-wrap items-center gap-2\">\n <input\n type=\"number\"\n step=\"0.01\"\n autoFocus\n value={adjAmount}\n onChange={(e) => setAdjAmount(e.target.value)}\n onKeyDown={(e) => {\n if (e.key === 'Enter') void handleAdjust()\n if (e.key === 'Escape') setAdjustOpen(false)\n }}\n placeholder={t('billing.prepaid.adjust.amount', 'Amount (+credit / \u2212debit)')}\n className=\"h-9 w-48 rounded-md border border-border bg-background px-3 text-sm\"\n />\n <input\n type=\"text\"\n value={adjReason}\n onChange={(e) => setAdjReason(e.target.value)}\n onKeyDown={(e) => {\n if (e.key === 'Enter') void handleAdjust()\n if (e.key === 'Escape') setAdjustOpen(false)\n }}\n placeholder={t('billing.prepaid.adjust.description', 'Reason')}\n className=\"h-9 w-64 rounded-md border border-border bg-background px-3 text-sm\"\n />\n <Button type=\"button\" onClick={handleAdjust} disabled={adjSubmitting}>\n {adjSubmitting\n ? t('billing.prepaid.adjust.submitting', 'Applying\u2026')\n : t('billing.prepaid.adjust.confirm', 'Apply adjustment')}\n </Button>\n <Button type=\"button\" variant=\"outline\" onClick={() => setAdjustOpen(false)}>\n {t('billing.common.cancel', 'Cancel')}\n </Button>\n </div>\n ) : null}\n </div>\n\n <DataTable\n title={t('billing.prepaid.panel.transactions', 'Balance transactions')}\n columns={columns}\n data={rows}\n isLoading={loading}\n onRowClick={(row) => router.push(`/backend/billing/transactions/${row.id}`)}\n pagination={{ page, pageSize, total, totalPages, onPageChange: setPage }}\n emptyState={\n <div className=\"rounded-lg border bg-card p-6 text-center text-sm text-muted-foreground\">\n {t('billing.prepaid.panel.no_transactions', 'No balance movements yet.')}\n </div>\n }\n />\n </div>\n )\n}\n\nexport default PrepaidPanel\n"],
5
+ "mappings": ";AAoNU,SA2EA,UA3EA,KAmCI,YAnCJ;AAnNV,YAAY,WAAW;AACvB,SAAS,iBAAiB;AAC1B,SAAS,MAAM,yBAAyB;AAExC,SAAS,YAAY;AACrB,SAAS,iBAAiB;AAC1B,SAAS,WAAW;AACpB,SAAS,cAAc;AACvB,SAAS,aAAa;AACtB,SAAS,gBAAgB,4BAA4B;AACrD,SAAS,gCAAgC;AACzC,SAAS,UAAU,YAAY;AAgC/B,SAAS,eAAe,QAAiD;AACvE,MAAI,WAAW,MAAO,QAAO;AAC7B,MAAI,WAAW,YAAa,QAAO;AACnC,SAAO;AACT;AAEA,SAAS,cAAc,QAAiD;AACtE,MAAI,WAAW,aAAc,QAAO;AACpC,MAAI,WAAW,aAAc,QAAO;AACpC,SAAO;AACT;AAEA,SAAS,WAAW,MAA8C;AAChE,MAAI,SAAS,WAAW,SAAS,aAAc,QAAO;AACtD,MAAI,SAAS,QAAS,QAAO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AAC,MAAM,aAAa,EAAE,OAAO,KAAK;AAAA,YAC5C,WAAW,CAAC,MAAM;AAChB,kBAAI,EAAE,QAAQ,QAAS,MAAK,aAAa;AACzC,kBAAI,EAAE,QAAQ,SAAU,eAAc,KAAK;AAAA,YAC7C;AAAA,YACA,aAAa,EAAE,sCAAsC,QAAQ;AAAA,YAC7D,WAAU;AAAA;AAAA,QACZ;AAAA,QACA,oBAAC,UAAO,MAAK,UAAS,SAAS,cAAc,UAAU,eACpD,0BACG,EAAE,qCAAqC,gBAAW,IAClD,EAAE,kCAAkC,kBAAkB,GAC5D;AAAA,QACA,oBAAC,UAAO,MAAK,UAAS,SAAQ,WAAU,SAAS,MAAM,cAAc,KAAK,GACvE,YAAE,yBAAyB,QAAQ,GACtC;AAAA,SACF,IACE;AAAA,OACN;AAAA,IAEA;AAAA,MAAC;AAAA;AAAA,QACC,OAAO,EAAE,sCAAsC,sBAAsB;AAAA,QACrE;AAAA,QACA,MAAM;AAAA,QACN,WAAW;AAAA,QACX,YAAY,CAAC,QAAQ,OAAO,KAAK,iCAAiC,IAAI,EAAE,EAAE;AAAA,QAC1E,YAAY,EAAE,MAAM,UAAU,OAAO,YAAY,cAAc,QAAQ;AAAA,QACvE,YACE,oBAAC,SAAI,WAAU,2EACZ,YAAE,yCAAyC,2BAA2B,GACzE;AAAA;AAAA,IAEJ;AAAA,KACF;AAEJ;AAEA,IAAO,uBAAQ;",
6
+ "names": []
7
+ }
@@ -0,0 +1,20 @@
1
+ import { readApiResultOrThrow } from "@open-mercato/ui/backend/utils/apiCall";
2
+ async function fetchAccountNames(ids) {
3
+ const unique = Array.from(new Set(ids.filter((id) => !!id)));
4
+ if (!unique.length) return {};
5
+ const map = {};
6
+ for (let i = 0; i < unique.length; i += 100) {
7
+ const chunk = unique.slice(i, i + 100);
8
+ const result = await readApiResultOrThrow(
9
+ `/api/billing/accounts?ids=${chunk.join(",")}&pageSize=${chunk.length}`
10
+ );
11
+ for (const a of result.items ?? []) {
12
+ if (a?.id) map[a.id] = a.name ?? a.id;
13
+ }
14
+ }
15
+ return map;
16
+ }
17
+ export {
18
+ fetchAccountNames
19
+ };
20
+ //# sourceMappingURL=accountNames.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/modules/billing/components/accountNames.ts"],
4
+ "sourcesContent": ["import { readApiResultOrThrow } from '@open-mercato/ui/backend/utils/apiCall'\n\n/**\n * Batch-resolve billing account ids \u2192 display names for list views that only\n * carry the FK (`bill_account_id`). One request per page (\u2264100 ids via the\n * CRUD factory's `ids` filter) \u2014 never a per-row fetch.\n */\nexport async function fetchAccountNames(ids: Array<string | null | undefined>): Promise<Record<string, string>> {\n const unique = Array.from(new Set(ids.filter((id): id is string => !!id)))\n if (!unique.length) return {}\n const map: Record<string, string> = {}\n // The factory caps page sizes; chunk to stay within the 100 limit.\n for (let i = 0; i < unique.length; i += 100) {\n const chunk = unique.slice(i, i + 100)\n const result = await readApiResultOrThrow<{ items: Array<{ id: string; name: string }> }>(\n `/api/billing/accounts?ids=${chunk.join(',')}&pageSize=${chunk.length}`,\n )\n for (const a of result.items ?? []) {\n if (a?.id) map[a.id] = a.name ?? a.id\n }\n }\n return map\n}\n"],
5
+ "mappings": "AAAA,SAAS,4BAA4B;AAOrC,eAAsB,kBAAkB,KAAwE;AAC9G,QAAM,SAAS,MAAM,KAAK,IAAI,IAAI,IAAI,OAAO,CAAC,OAAqB,CAAC,CAAC,EAAE,CAAC,CAAC;AACzE,MAAI,CAAC,OAAO,OAAQ,QAAO,CAAC;AAC5B,QAAM,MAA8B,CAAC;AAErC,WAAS,IAAI,GAAG,IAAI,OAAO,QAAQ,KAAK,KAAK;AAC3C,UAAM,QAAQ,OAAO,MAAM,GAAG,IAAI,GAAG;AACrC,UAAM,SAAS,MAAM;AAAA,MACnB,6BAA6B,MAAM,KAAK,GAAG,CAAC,aAAa,MAAM,MAAM;AAAA,IACvE;AACA,eAAW,KAAK,OAAO,SAAS,CAAC,GAAG;AAClC,UAAI,GAAG,GAAI,KAAI,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE;AAAA,IACrC;AAAA,EACF;AACA,SAAO;AACT;",
6
+ "names": []
7
+ }