@dainamite/billing 0.17.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 (248) hide show
  1. package/CHANGELOG.md +658 -0
  2. package/LICENSE +21 -0
  3. package/README.md +77 -0
  4. package/dist/modules/billing/acl.js +20 -0
  5. package/dist/modules/billing/acl.js.map +7 -0
  6. package/dist/modules/billing/api/accounts/route.js +182 -0
  7. package/dist/modules/billing/api/accounts/route.js.map +7 -0
  8. package/dist/modules/billing/api/export/account/[id]/route.js +170 -0
  9. package/dist/modules/billing/api/export/account/[id]/route.js.map +7 -0
  10. package/dist/modules/billing/api/invoices/[id]/route.js +85 -0
  11. package/dist/modules/billing/api/invoices/[id]/route.js.map +7 -0
  12. package/dist/modules/billing/api/invoices/add-line/route.js +69 -0
  13. package/dist/modules/billing/api/invoices/add-line/route.js.map +7 -0
  14. package/dist/modules/billing/api/invoices/edit-line/route.js +78 -0
  15. package/dist/modules/billing/api/invoices/edit-line/route.js.map +7 -0
  16. package/dist/modules/billing/api/invoices/post/route.js +74 -0
  17. package/dist/modules/billing/api/invoices/post/route.js.map +7 -0
  18. package/dist/modules/billing/api/invoices/remove-line/route.js +69 -0
  19. package/dist/modules/billing/api/invoices/remove-line/route.js.map +7 -0
  20. package/dist/modules/billing/api/invoices/route.js +109 -0
  21. package/dist/modules/billing/api/invoices/route.js.map +7 -0
  22. package/dist/modules/billing/api/items/bulk/route.js +74 -0
  23. package/dist/modules/billing/api/items/bulk/route.js.map +7 -0
  24. package/dist/modules/billing/api/items/route.js +224 -0
  25. package/dist/modules/billing/api/items/route.js.map +7 -0
  26. package/dist/modules/billing/api/openapi.js +25 -0
  27. package/dist/modules/billing/api/openapi.js.map +7 -0
  28. package/dist/modules/billing/api/run-outcomes/route.js +122 -0
  29. package/dist/modules/billing/api/run-outcomes/route.js.map +7 -0
  30. package/dist/modules/billing/api/runs/retry-failed/route.js +70 -0
  31. package/dist/modules/billing/api/runs/retry-failed/route.js.map +7 -0
  32. package/dist/modules/billing/api/runs/route.js +143 -0
  33. package/dist/modules/billing/api/runs/route.js.map +7 -0
  34. package/dist/modules/billing/api/test-invoices/wipe/route.js +65 -0
  35. package/dist/modules/billing/api/test-invoices/wipe/route.js.map +7 -0
  36. package/dist/modules/billing/api/usage/route.js +138 -0
  37. package/dist/modules/billing/api/usage/route.js.map +7 -0
  38. package/dist/modules/billing/backend/billing/accounts/[id]/page.js +402 -0
  39. package/dist/modules/billing/backend/billing/accounts/[id]/page.js.map +7 -0
  40. package/dist/modules/billing/backend/billing/accounts/[id]/page.meta.js +25 -0
  41. package/dist/modules/billing/backend/billing/accounts/[id]/page.meta.js.map +7 -0
  42. package/dist/modules/billing/backend/billing/accounts/create/page.js +82 -0
  43. package/dist/modules/billing/backend/billing/accounts/create/page.js.map +7 -0
  44. package/dist/modules/billing/backend/billing/accounts/create/page.meta.js +25 -0
  45. package/dist/modules/billing/backend/billing/accounts/create/page.meta.js.map +7 -0
  46. package/dist/modules/billing/backend/billing/accounts/page.js +173 -0
  47. package/dist/modules/billing/backend/billing/accounts/page.js.map +7 -0
  48. package/dist/modules/billing/backend/billing/accounts/page.meta.js +18 -0
  49. package/dist/modules/billing/backend/billing/accounts/page.meta.js.map +7 -0
  50. package/dist/modules/billing/backend/billing/invoices/[id]/page.js +500 -0
  51. package/dist/modules/billing/backend/billing/invoices/[id]/page.js.map +7 -0
  52. package/dist/modules/billing/backend/billing/invoices/[id]/page.meta.js +25 -0
  53. package/dist/modules/billing/backend/billing/invoices/[id]/page.meta.js.map +7 -0
  54. package/dist/modules/billing/backend/billing/invoices/page.js +187 -0
  55. package/dist/modules/billing/backend/billing/invoices/page.js.map +7 -0
  56. package/dist/modules/billing/backend/billing/invoices/page.meta.js +18 -0
  57. package/dist/modules/billing/backend/billing/invoices/page.meta.js.map +7 -0
  58. package/dist/modules/billing/backend/billing/items/[id]/page.js +265 -0
  59. package/dist/modules/billing/backend/billing/items/[id]/page.js.map +7 -0
  60. package/dist/modules/billing/backend/billing/items/[id]/page.meta.js +25 -0
  61. package/dist/modules/billing/backend/billing/items/[id]/page.meta.js.map +7 -0
  62. package/dist/modules/billing/backend/billing/items/create/page.js +90 -0
  63. package/dist/modules/billing/backend/billing/items/create/page.js.map +7 -0
  64. package/dist/modules/billing/backend/billing/items/create/page.meta.js +25 -0
  65. package/dist/modules/billing/backend/billing/items/create/page.meta.js.map +7 -0
  66. package/dist/modules/billing/backend/billing/items/page.js +208 -0
  67. package/dist/modules/billing/backend/billing/items/page.js.map +7 -0
  68. package/dist/modules/billing/backend/billing/items/page.meta.js +18 -0
  69. package/dist/modules/billing/backend/billing/items/page.meta.js.map +7 -0
  70. package/dist/modules/billing/backend/billing/runs/[id]/page.js +293 -0
  71. package/dist/modules/billing/backend/billing/runs/[id]/page.js.map +7 -0
  72. package/dist/modules/billing/backend/billing/runs/[id]/page.meta.js +21 -0
  73. package/dist/modules/billing/backend/billing/runs/[id]/page.meta.js.map +7 -0
  74. package/dist/modules/billing/backend/billing/runs/page.js +341 -0
  75. package/dist/modules/billing/backend/billing/runs/page.js.map +7 -0
  76. package/dist/modules/billing/backend/billing/runs/page.meta.js +18 -0
  77. package/dist/modules/billing/backend/billing/runs/page.meta.js.map +7 -0
  78. package/dist/modules/billing/backend/billing/usage/create/page.js +100 -0
  79. package/dist/modules/billing/backend/billing/usage/create/page.js.map +7 -0
  80. package/dist/modules/billing/backend/billing/usage/create/page.meta.js +25 -0
  81. package/dist/modules/billing/backend/billing/usage/create/page.meta.js.map +7 -0
  82. package/dist/modules/billing/ce.js +56 -0
  83. package/dist/modules/billing/ce.js.map +7 -0
  84. package/dist/modules/billing/cli.js +67 -0
  85. package/dist/modules/billing/cli.js.map +7 -0
  86. package/dist/modules/billing/commands/accounts.js +157 -0
  87. package/dist/modules/billing/commands/accounts.js.map +7 -0
  88. package/dist/modules/billing/commands/index.js +6 -0
  89. package/dist/modules/billing/commands/index.js.map +7 -0
  90. package/dist/modules/billing/commands/invoices.js +401 -0
  91. package/dist/modules/billing/commands/invoices.js.map +7 -0
  92. package/dist/modules/billing/commands/items.js +317 -0
  93. package/dist/modules/billing/commands/items.js.map +7 -0
  94. package/dist/modules/billing/commands/runs.js +123 -0
  95. package/dist/modules/billing/commands/runs.js.map +7 -0
  96. package/dist/modules/billing/commands/usage.js +88 -0
  97. package/dist/modules/billing/commands/usage.js.map +7 -0
  98. package/dist/modules/billing/components/AccountForm.js +420 -0
  99. package/dist/modules/billing/components/AccountForm.js.map +7 -0
  100. package/dist/modules/billing/components/DetailFields.js +37 -0
  101. package/dist/modules/billing/components/DetailFields.js.map +7 -0
  102. package/dist/modules/billing/components/ItemForm.js +440 -0
  103. package/dist/modules/billing/components/ItemForm.js.map +7 -0
  104. package/dist/modules/billing/components/LineFormDialog.js +195 -0
  105. package/dist/modules/billing/components/LineFormDialog.js.map +7 -0
  106. package/dist/modules/billing/components/UsageForm.js +262 -0
  107. package/dist/modules/billing/components/UsageForm.js.map +7 -0
  108. package/dist/modules/billing/data/entities.js +433 -0
  109. package/dist/modules/billing/data/entities.js.map +7 -0
  110. package/dist/modules/billing/data/entityIds.js +12 -0
  111. package/dist/modules/billing/data/entityIds.js.map +7 -0
  112. package/dist/modules/billing/data/validators.js +396 -0
  113. package/dist/modules/billing/data/validators.js.map +7 -0
  114. package/dist/modules/billing/di.js +6 -0
  115. package/dist/modules/billing/di.js.map +7 -0
  116. package/dist/modules/billing/events.js +35 -0
  117. package/dist/modules/billing/events.js.map +7 -0
  118. package/dist/modules/billing/i18n/en.json +336 -0
  119. package/dist/modules/billing/i18n/pl.json +336 -0
  120. package/dist/modules/billing/index.js +17 -0
  121. package/dist/modules/billing/index.js.map +7 -0
  122. package/dist/modules/billing/lib/billPeriod.js +101 -0
  123. package/dist/modules/billing/lib/billPeriod.js.map +7 -0
  124. package/dist/modules/billing/lib/billRunEngine.js +256 -0
  125. package/dist/modules/billing/lib/billRunEngine.js.map +7 -0
  126. package/dist/modules/billing/lib/billRunLabel.js +8 -0
  127. package/dist/modules/billing/lib/billRunLabel.js.map +7 -0
  128. package/dist/modules/billing/lib/idempotency.js +13 -0
  129. package/dist/modules/billing/lib/idempotency.js.map +7 -0
  130. package/dist/modules/billing/lib/invoiceStatus.js +38 -0
  131. package/dist/modules/billing/lib/invoiceStatus.js.map +7 -0
  132. package/dist/modules/billing/lib/invoiceWriter.js +153 -0
  133. package/dist/modules/billing/lib/invoiceWriter.js.map +7 -0
  134. package/dist/modules/billing/lib/itemSelector.js +77 -0
  135. package/dist/modules/billing/lib/itemSelector.js.map +7 -0
  136. package/dist/modules/billing/lib/seeds/demo.js +130 -0
  137. package/dist/modules/billing/lib/seeds/demo.js.map +7 -0
  138. package/dist/modules/billing/lib/tenantLock.js +32 -0
  139. package/dist/modules/billing/lib/tenantLock.js.map +7 -0
  140. package/dist/modules/billing/lib/usageRater.js +150 -0
  141. package/dist/modules/billing/lib/usageRater.js.map +7 -0
  142. package/dist/modules/billing/lib/usageRunner.js +82 -0
  143. package/dist/modules/billing/lib/usageRunner.js.map +7 -0
  144. package/dist/modules/billing/migrations/Migration20260519000000_billing.js +144 -0
  145. package/dist/modules/billing/migrations/Migration20260519000000_billing.js.map +7 -0
  146. package/dist/modules/billing/setup.js +190 -0
  147. package/dist/modules/billing/setup.js.map +7 -0
  148. package/dist/modules/billing/subscribers/payment-captured-to-paid.js +47 -0
  149. package/dist/modules/billing/subscribers/payment-captured-to-paid.js.map +7 -0
  150. package/dist/modules/billing/translations.js +5 -0
  151. package/dist/modules/billing/translations.js.map +7 -0
  152. package/dist/modules/billing/workers/reap-stale-bill-runs.js +31 -0
  153. package/dist/modules/billing/workers/reap-stale-bill-runs.js.map +7 -0
  154. package/package.json +148 -0
  155. package/src/modules/billing/__integration__/TC-BILL-001.spec.ts +116 -0
  156. package/src/modules/billing/__integration__/TC-BILL-002.spec.ts +169 -0
  157. package/src/modules/billing/__integration__/TC-BILL-003.spec.ts +28 -0
  158. package/src/modules/billing/__integration__/meta.ts +4 -0
  159. package/src/modules/billing/__tests__/commands/invoices.test.ts +464 -0
  160. package/src/modules/billing/__tests__/commands/itemsBulk.test.ts +284 -0
  161. package/src/modules/billing/__tests__/lib/billPeriod.test.ts +131 -0
  162. package/src/modules/billing/__tests__/lib/billRunEngine.test.ts +561 -0
  163. package/src/modules/billing/__tests__/lib/idempotency.test.ts +81 -0
  164. package/src/modules/billing/__tests__/lib/invoiceStatus.test.ts +97 -0
  165. package/src/modules/billing/__tests__/lib/invoiceWriter.test.ts +119 -0
  166. package/src/modules/billing/__tests__/lib/itemSelector.test.ts +192 -0
  167. package/src/modules/billing/__tests__/lib/seedsDemo.test.ts +86 -0
  168. package/src/modules/billing/__tests__/lib/tenantLock.test.ts +126 -0
  169. package/src/modules/billing/__tests__/lib/usageRater.test.ts +190 -0
  170. package/src/modules/billing/__tests__/package-isolation.test.ts +223 -0
  171. package/src/modules/billing/__tests__/setup.test.ts +107 -0
  172. package/src/modules/billing/__tests__/validators.test.ts +594 -0
  173. package/src/modules/billing/acl.ts +16 -0
  174. package/src/modules/billing/api/accounts/route.ts +198 -0
  175. package/src/modules/billing/api/export/account/[id]/route.ts +233 -0
  176. package/src/modules/billing/api/invoices/[id]/route.ts +143 -0
  177. package/src/modules/billing/api/invoices/add-line/route.ts +74 -0
  178. package/src/modules/billing/api/invoices/edit-line/route.ts +97 -0
  179. package/src/modules/billing/api/invoices/post/route.ts +97 -0
  180. package/src/modules/billing/api/invoices/remove-line/route.ts +75 -0
  181. package/src/modules/billing/api/invoices/route.ts +167 -0
  182. package/src/modules/billing/api/items/bulk/route.ts +92 -0
  183. package/src/modules/billing/api/items/route.ts +255 -0
  184. package/src/modules/billing/api/openapi.ts +33 -0
  185. package/src/modules/billing/api/run-outcomes/route.ts +149 -0
  186. package/src/modules/billing/api/runs/retry-failed/route.ts +88 -0
  187. package/src/modules/billing/api/runs/route.ts +170 -0
  188. package/src/modules/billing/api/test-invoices/wipe/route.ts +87 -0
  189. package/src/modules/billing/api/usage/route.ts +148 -0
  190. package/src/modules/billing/backend/billing/accounts/[id]/page.meta.ts +23 -0
  191. package/src/modules/billing/backend/billing/accounts/[id]/page.tsx +574 -0
  192. package/src/modules/billing/backend/billing/accounts/create/page.meta.ts +23 -0
  193. package/src/modules/billing/backend/billing/accounts/create/page.tsx +101 -0
  194. package/src/modules/billing/backend/billing/accounts/page.meta.ts +16 -0
  195. package/src/modules/billing/backend/billing/accounts/page.tsx +222 -0
  196. package/src/modules/billing/backend/billing/invoices/[id]/page.meta.ts +23 -0
  197. package/src/modules/billing/backend/billing/invoices/[id]/page.tsx +613 -0
  198. package/src/modules/billing/backend/billing/invoices/page.meta.ts +16 -0
  199. package/src/modules/billing/backend/billing/invoices/page.tsx +245 -0
  200. package/src/modules/billing/backend/billing/items/[id]/page.meta.ts +23 -0
  201. package/src/modules/billing/backend/billing/items/[id]/page.tsx +366 -0
  202. package/src/modules/billing/backend/billing/items/create/page.meta.ts +23 -0
  203. package/src/modules/billing/backend/billing/items/create/page.tsx +110 -0
  204. package/src/modules/billing/backend/billing/items/page.meta.ts +16 -0
  205. package/src/modules/billing/backend/billing/items/page.tsx +272 -0
  206. package/src/modules/billing/backend/billing/runs/[id]/page.meta.ts +19 -0
  207. package/src/modules/billing/backend/billing/runs/[id]/page.tsx +404 -0
  208. package/src/modules/billing/backend/billing/runs/page.meta.ts +16 -0
  209. package/src/modules/billing/backend/billing/runs/page.tsx +426 -0
  210. package/src/modules/billing/backend/billing/usage/create/page.meta.ts +23 -0
  211. package/src/modules/billing/backend/billing/usage/create/page.tsx +120 -0
  212. package/src/modules/billing/ce.ts +74 -0
  213. package/src/modules/billing/cli.ts +89 -0
  214. package/src/modules/billing/commands/accounts.ts +205 -0
  215. package/src/modules/billing/commands/index.ts +13 -0
  216. package/src/modules/billing/commands/invoices.ts +542 -0
  217. package/src/modules/billing/commands/items.ts +438 -0
  218. package/src/modules/billing/commands/runs.ts +166 -0
  219. package/src/modules/billing/commands/usage.ts +118 -0
  220. package/src/modules/billing/components/AccountForm.tsx +517 -0
  221. package/src/modules/billing/components/DetailFields.tsx +60 -0
  222. package/src/modules/billing/components/ItemForm.tsx +558 -0
  223. package/src/modules/billing/components/LineFormDialog.tsx +253 -0
  224. package/src/modules/billing/components/UsageForm.tsx +326 -0
  225. package/src/modules/billing/data/entities.ts +533 -0
  226. package/src/modules/billing/data/entityIds.ts +25 -0
  227. package/src/modules/billing/data/validators.ts +562 -0
  228. package/src/modules/billing/di.ts +14 -0
  229. package/src/modules/billing/events.ts +47 -0
  230. package/src/modules/billing/i18n/en.json +336 -0
  231. package/src/modules/billing/i18n/pl.json +336 -0
  232. package/src/modules/billing/index.ts +22 -0
  233. package/src/modules/billing/lib/billPeriod.ts +181 -0
  234. package/src/modules/billing/lib/billRunEngine.ts +416 -0
  235. package/src/modules/billing/lib/billRunLabel.ts +14 -0
  236. package/src/modules/billing/lib/idempotency.ts +46 -0
  237. package/src/modules/billing/lib/invoiceStatus.ts +61 -0
  238. package/src/modules/billing/lib/invoiceWriter.ts +260 -0
  239. package/src/modules/billing/lib/itemSelector.ts +154 -0
  240. package/src/modules/billing/lib/seeds/demo.ts +199 -0
  241. package/src/modules/billing/lib/tenantLock.ts +87 -0
  242. package/src/modules/billing/lib/usageRater.ts +250 -0
  243. package/src/modules/billing/lib/usageRunner.ts +189 -0
  244. package/src/modules/billing/migrations/Migration20260519000000_billing.ts +175 -0
  245. package/src/modules/billing/setup.ts +252 -0
  246. package/src/modules/billing/subscribers/payment-captured-to-paid.ts +89 -0
  247. package/src/modules/billing/translations.ts +9 -0
  248. package/src/modules/billing/workers/reap-stale-bill-runs.ts +57 -0
@@ -0,0 +1,341 @@
1
+ "use client";
2
+ import { jsx, jsxs } from "react/jsx-runtime";
3
+ import * as React from "react";
4
+ import { useRouter } from "next/navigation";
5
+ import { Play } from "lucide-react";
6
+ import { useT } from "@open-mercato/shared/lib/i18n/context";
7
+ import { Page, PageBody } from "@open-mercato/ui/backend/Page";
8
+ import { DataTable } from "@open-mercato/ui/backend/DataTable";
9
+ import { Tag } from "@open-mercato/ui/primitives/tag";
10
+ import { Button } from "@open-mercato/ui/primitives/button";
11
+ import { Input } from "@open-mercato/ui/primitives/input";
12
+ import {
13
+ Select,
14
+ SelectContent,
15
+ SelectItem,
16
+ SelectTrigger,
17
+ SelectValue
18
+ } from "@open-mercato/ui/primitives/select";
19
+ import {
20
+ Dialog,
21
+ DialogContent,
22
+ DialogDescription,
23
+ DialogFooter,
24
+ DialogHeader,
25
+ DialogTitle
26
+ } from "@open-mercato/ui/primitives/dialog";
27
+ import { Kbd, KbdShortcut } from "@open-mercato/ui/primitives/kbd";
28
+ import { flash } from "@open-mercato/ui/backend/FlashMessages";
29
+ import { apiCallOrThrow, readApiResultOrThrow } from "@open-mercato/ui/backend/utils/apiCall";
30
+ import { normalizeCrudServerError } from "@open-mercato/ui/backend/utils/serverErrors";
31
+ import { billRunName } from "../../../lib/billRunLabel.js";
32
+ function todayIso() {
33
+ return (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
34
+ }
35
+ function formatDate(value) {
36
+ if (!value) return "\u2014";
37
+ const parsed = new Date(value);
38
+ return Number.isNaN(parsed.getTime()) ? value : parsed.toLocaleString();
39
+ }
40
+ function formatDateOnly(value) {
41
+ if (!value) return "\u2014";
42
+ const parsed = new Date(value);
43
+ return Number.isNaN(parsed.getTime()) ? value : parsed.toLocaleDateString();
44
+ }
45
+ function statusVariant(status) {
46
+ switch (status) {
47
+ case "completed":
48
+ return "success";
49
+ case "partial_failure":
50
+ return "warning";
51
+ case "failed":
52
+ return "error";
53
+ case "running":
54
+ default:
55
+ return "default";
56
+ }
57
+ }
58
+ function modeBadge(row) {
59
+ if (row.dry_run) return { label: "Dry-run", variant: "warning" };
60
+ if (row.test_mode) return { label: "Test", variant: "warning" };
61
+ return null;
62
+ }
63
+ function BillRunsListPage() {
64
+ const t = useT();
65
+ const router = useRouter();
66
+ const [rows, setRows] = React.useState([]);
67
+ const [page, setPage] = React.useState(1);
68
+ const [pageSize] = React.useState(25);
69
+ const [filters, setFilters] = React.useState({});
70
+ const [total, setTotal] = React.useState(0);
71
+ const [totalPages, setTotalPages] = React.useState(1);
72
+ const [loading, setLoading] = React.useState(true);
73
+ const [search, setSearch] = React.useState("");
74
+ const [triggerOpen, setTriggerOpen] = React.useState(false);
75
+ const [triggerMode, setTriggerMode] = React.useState("real");
76
+ const [triggerAsOfDate, setTriggerAsOfDate] = React.useState(todayIso());
77
+ const [triggering, setTriggering] = React.useState(false);
78
+ const filterDefs = React.useMemo(
79
+ () => [
80
+ {
81
+ id: "status",
82
+ label: t("billing.runs.filters.status", "Status"),
83
+ type: "select",
84
+ options: [
85
+ { value: "running", label: t("billing.runs.status.running", "Running") },
86
+ { value: "completed", label: t("billing.runs.status.completed", "Completed") },
87
+ {
88
+ value: "partial_failure",
89
+ label: t("billing.runs.status.partial_failure", "Partial failure")
90
+ },
91
+ { value: "failed", label: t("billing.runs.status.failed", "Failed") }
92
+ ]
93
+ },
94
+ {
95
+ id: "triggeredBy",
96
+ label: t("billing.runs.filters.triggered_by", "Trigger"),
97
+ type: "select",
98
+ options: [
99
+ { value: "schedule", label: t("billing.runs.trigger.schedule", "Schedule") },
100
+ { value: "manual", label: t("billing.runs.trigger.manual", "Manual") }
101
+ ]
102
+ }
103
+ ],
104
+ [t]
105
+ );
106
+ const loadRows = React.useCallback(async () => {
107
+ setLoading(true);
108
+ try {
109
+ const params = new URLSearchParams({
110
+ page: String(page),
111
+ pageSize: String(pageSize),
112
+ sortField: "startedAt",
113
+ sortDir: "desc"
114
+ });
115
+ if (search.trim()) params.set("search", search.trim());
116
+ if (typeof filters.status === "string" && filters.status) {
117
+ params.set("status", filters.status);
118
+ }
119
+ if (typeof filters.triggeredBy === "string" && filters.triggeredBy) {
120
+ params.set("triggeredBy", filters.triggeredBy);
121
+ }
122
+ const result = await readApiResultOrThrow(
123
+ `/api/billing/runs?${params.toString()}`
124
+ );
125
+ setRows(result.items ?? []);
126
+ setTotal(result.total ?? 0);
127
+ setTotalPages(result.totalPages ?? 1);
128
+ } finally {
129
+ setLoading(false);
130
+ }
131
+ }, [filters.status, filters.triggeredBy, page, pageSize, search]);
132
+ React.useEffect(() => {
133
+ void loadRows();
134
+ }, [loadRows]);
135
+ const handleTrigger = React.useCallback(async () => {
136
+ setTriggering(true);
137
+ try {
138
+ const payload = { mode: triggerMode };
139
+ if (triggerAsOfDate) payload.asOfDate = triggerAsOfDate;
140
+ const call = await apiCallOrThrow(
141
+ "/api/billing/runs",
142
+ {
143
+ method: "POST",
144
+ headers: { "Content-Type": "application/json" },
145
+ body: JSON.stringify(payload)
146
+ }
147
+ );
148
+ flash(t("billing.runs.trigger.success", "Bill Run triggered"), "success");
149
+ setTriggerOpen(false);
150
+ const newId = call.result?.billRunId;
151
+ if (newId) {
152
+ router.push(`/backend/billing/runs/${newId}`);
153
+ } else {
154
+ void loadRows();
155
+ }
156
+ } catch (err) {
157
+ const { message, fieldErrors } = normalizeCrudServerError(err);
158
+ const fieldDetail = fieldErrors && Object.keys(fieldErrors).length ? Object.entries(fieldErrors).map(([field, msg]) => `${field}: ${msg}`).join("; ") : null;
159
+ const detailed = fieldDetail && message ? `${message} \u2014 ${fieldDetail}` : fieldDetail || message;
160
+ flash(detailed || t("billing.runs.trigger.error", "Failed to trigger run"), "error");
161
+ } finally {
162
+ setTriggering(false);
163
+ }
164
+ }, [loadRows, router, t, triggerAsOfDate, triggerMode]);
165
+ const handleTriggerKeyDown = React.useCallback(
166
+ (event) => {
167
+ if ((event.metaKey || event.ctrlKey) && event.key === "Enter") {
168
+ event.preventDefault();
169
+ if (!triggering) void handleTrigger();
170
+ }
171
+ },
172
+ [handleTrigger, triggering]
173
+ );
174
+ const columns = React.useMemo(
175
+ () => [
176
+ {
177
+ id: "name",
178
+ header: t("billing.runs.columns.name", "Bill Run"),
179
+ cell: ({ row }) => /* @__PURE__ */ jsx("span", { className: "text-sm font-medium text-primary", children: billRunName(row.original.as_of_date) })
180
+ },
181
+ {
182
+ accessorKey: "status",
183
+ header: t("billing.runs.columns.status", "Status"),
184
+ cell: ({ row }) => {
185
+ const mode = modeBadge(row.original);
186
+ return /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
187
+ /* @__PURE__ */ jsx(Tag, { variant: statusVariant(row.original.status), children: row.original.status }),
188
+ mode ? /* @__PURE__ */ jsx(Tag, { variant: mode.variant, children: mode.label }) : null
189
+ ] });
190
+ }
191
+ },
192
+ {
193
+ accessorKey: "as_of_date",
194
+ header: t("billing.runs.columns.as_of_date", "As-of date"),
195
+ cell: ({ row }) => formatDateOnly(row.original.as_of_date)
196
+ },
197
+ {
198
+ accessorKey: "triggered_by",
199
+ header: t("billing.runs.columns.triggered_by", "Trigger")
200
+ },
201
+ {
202
+ id: "drafts_created",
203
+ header: t("billing.runs.columns.drafts", "Drafts"),
204
+ cell: ({ row }) => row.original.summary?.drafts_created ?? "\u2014"
205
+ },
206
+ {
207
+ id: "accounts_processed",
208
+ header: t("billing.runs.columns.accounts", "Accounts"),
209
+ cell: ({ row }) => row.original.summary?.accounts_processed ?? "\u2014"
210
+ },
211
+ {
212
+ id: "accounts_failed",
213
+ header: t("billing.runs.columns.failed", "Failed"),
214
+ cell: ({ row }) => {
215
+ const failed = row.original.summary?.accounts_failed ?? 0;
216
+ if (failed === 0) return "\u2014";
217
+ return /* @__PURE__ */ jsx(Tag, { variant: "error", children: failed });
218
+ }
219
+ },
220
+ {
221
+ accessorKey: "started_at",
222
+ header: t("billing.runs.columns.started_at", "Started"),
223
+ cell: ({ row }) => formatDate(row.original.started_at)
224
+ },
225
+ {
226
+ accessorKey: "finished_at",
227
+ header: t("billing.runs.columns.finished_at", "Finished"),
228
+ cell: ({ row }) => formatDate(row.original.finished_at)
229
+ }
230
+ ],
231
+ [t]
232
+ );
233
+ return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsxs(PageBody, { children: [
234
+ /* @__PURE__ */ jsx(
235
+ DataTable,
236
+ {
237
+ title: t("billing.runs.title", "Bill Runs"),
238
+ actions: /* @__PURE__ */ jsxs(Button, { onClick: () => setTriggerOpen(true), children: [
239
+ /* @__PURE__ */ jsx(Play, { size: 16 }),
240
+ t("billing.runs.trigger.action", "New run")
241
+ ] }),
242
+ refreshButton: {
243
+ label: t("billing.common.refresh", "Refresh"),
244
+ onRefresh: loadRows,
245
+ isRefreshing: loading
246
+ },
247
+ columnChooser: { auto: true },
248
+ perspective: { tableId: "billing-runs" },
249
+ columns,
250
+ data: rows,
251
+ onRowClick: (row) => router.push(`/backend/billing/runs/${row.id}`),
252
+ isLoading: loading,
253
+ pagination: {
254
+ page,
255
+ pageSize,
256
+ total,
257
+ totalPages,
258
+ onPageChange: setPage
259
+ },
260
+ filters: filterDefs,
261
+ filterValues: filters,
262
+ onFiltersApply: setFilters,
263
+ onFiltersClear: () => setFilters({}),
264
+ searchValue: search,
265
+ onSearchChange: setSearch
266
+ }
267
+ ),
268
+ /* @__PURE__ */ jsx(Dialog, { open: triggerOpen, onOpenChange: (next) => !triggering && setTriggerOpen(next), children: /* @__PURE__ */ jsxs(DialogContent, { onKeyDown: handleTriggerKeyDown, children: [
269
+ /* @__PURE__ */ jsxs(DialogHeader, { children: [
270
+ /* @__PURE__ */ jsx(DialogTitle, { children: t("billing.runs.trigger.dialog.title", "Trigger Bill Run") }),
271
+ /* @__PURE__ */ jsx(DialogDescription, { children: t(
272
+ "billing.runs.trigger.dialog.description",
273
+ "Runs the bill cycle for every account whose next bill date has passed. Dry-run / Test produce drafts without posting any invoices."
274
+ ) })
275
+ ] }),
276
+ /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
277
+ /* @__PURE__ */ jsxs("label", { className: "flex flex-col gap-1 text-sm", children: [
278
+ /* @__PURE__ */ jsx("span", { className: "text-muted-foreground", children: t("billing.runs.trigger.dialog.mode", "Mode") }),
279
+ /* @__PURE__ */ jsxs(
280
+ Select,
281
+ {
282
+ value: triggerMode,
283
+ onValueChange: (next) => setTriggerMode(next),
284
+ children: [
285
+ /* @__PURE__ */ jsx(SelectTrigger, { children: /* @__PURE__ */ jsx(SelectValue, {}) }),
286
+ /* @__PURE__ */ jsxs(SelectContent, { children: [
287
+ /* @__PURE__ */ jsx(SelectItem, { value: "real", children: t("billing.runs.trigger.dialog.mode.real", "Real \u2014 create draft invoices") }),
288
+ /* @__PURE__ */ jsx(SelectItem, { value: "dry", children: t("billing.runs.trigger.dialog.mode.dry", "Dry-run \u2014 no rows written") }),
289
+ /* @__PURE__ */ jsx(SelectItem, { value: "test", children: t("billing.runs.trigger.dialog.mode.test", "Test \u2014 drafts tagged for cleanup") })
290
+ ] })
291
+ ]
292
+ }
293
+ )
294
+ ] }),
295
+ /* @__PURE__ */ jsxs("label", { className: "flex flex-col gap-1 text-sm", children: [
296
+ /* @__PURE__ */ jsx("span", { className: "text-muted-foreground", children: t("billing.runs.trigger.dialog.as_of_date", "As-of date") }),
297
+ /* @__PURE__ */ jsx(
298
+ Input,
299
+ {
300
+ type: "date",
301
+ value: triggerAsOfDate,
302
+ onChange: (event) => setTriggerAsOfDate(event.currentTarget.value)
303
+ }
304
+ ),
305
+ /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: t(
306
+ "billing.runs.trigger.dialog.as_of_date.help",
307
+ "Accounts whose next bill date is on or before this date will be billed."
308
+ ) })
309
+ ] })
310
+ ] }),
311
+ /* @__PURE__ */ jsxs(DialogFooter, { className: "flex items-center justify-between gap-3 sm:justify-between", children: [
312
+ /* @__PURE__ */ jsxs("span", { className: "text-xs text-muted-foreground", children: [
313
+ /* @__PURE__ */ jsx(KbdShortcut, { keys: ["Ctrl/\u2318", "Enter"] }),
314
+ " ",
315
+ t("billing.runs.trigger.dialog.submit_hint", "to run,"),
316
+ " ",
317
+ /* @__PURE__ */ jsx(Kbd, { children: "Esc" }),
318
+ " ",
319
+ t("billing.runs.trigger.dialog.cancel_hint", "to cancel")
320
+ ] }),
321
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
322
+ /* @__PURE__ */ jsx(
323
+ Button,
324
+ {
325
+ type: "button",
326
+ variant: "outline",
327
+ onClick: () => setTriggerOpen(false),
328
+ disabled: triggering,
329
+ children: t("billing.common.cancel", "Cancel")
330
+ }
331
+ ),
332
+ /* @__PURE__ */ jsx(Button, { type: "button", onClick: () => void handleTrigger(), disabled: triggering, children: triggering ? t("billing.runs.trigger.dialog.running", "Running\u2026") : t("billing.runs.trigger.dialog.submit", "Run now") })
333
+ ] })
334
+ ] })
335
+ ] }) })
336
+ ] }) });
337
+ }
338
+ export {
339
+ BillRunsListPage as default
340
+ };
341
+ //# sourceMappingURL=page.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../../../src/modules/billing/backend/billing/runs/page.tsx"],
4
+ "sourcesContent": ["\"use client\"\nimport * as React from 'react'\nimport { useRouter } from 'next/navigation'\nimport { Play } from 'lucide-react'\nimport type { ColumnDef } from '@tanstack/react-table'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport type { FilterDef, FilterValues } from '@open-mercato/ui/backend/FilterBar'\nimport { Page, PageBody } from '@open-mercato/ui/backend/Page'\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 { Input } from '@open-mercato/ui/primitives/input'\nimport {\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n} from '@open-mercato/ui/primitives/select'\nimport {\n Dialog,\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogTitle,\n} from '@open-mercato/ui/primitives/dialog'\nimport { Kbd, KbdShortcut } from '@open-mercato/ui/primitives/kbd'\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 { billRunName } from '../../../lib/billRunLabel'\n\n/**\n * Bill Runs admin list page.\n *\n * Lists every Bill Run for the operator's tenant with status, mode,\n * summary stats, and a link into the detail page. The \"New run\" button\n * opens an inline trigger dialog that posts to `/api/billing/runs` \u2014\n * same endpoint operators previously had to curl by hand. Retry-failed\n * stays on the run detail page (scoped to a specific run's failures).\n */\n\ntype TriggerMode = 'real' | 'dry' | 'test'\n\nfunction todayIso(): string {\n return new Date().toISOString().slice(0, 10)\n}\n\n// API list rows are snake_case (see `api/runs/route.ts` `fields`).\ntype BillRunRow = {\n id: string\n triggered_by: 'schedule' | 'manual'\n parent_run_id: string | null\n dry_run: boolean\n test_mode: boolean\n catch_up: boolean\n as_of_date: string\n started_at: string | null\n finished_at: string | null\n status: 'running' | 'completed' | 'partial_failure' | 'failed'\n summary: {\n accounts_processed?: number\n drafts_created?: number\n drafts_skipped_existing?: number\n accounts_failed?: number\n accounts_with_warnings?: number\n usage_records_rated?: number\n } | null\n created_at: string\n updated_at: string\n}\n\ntype ListResponse = {\n items: BillRunRow[]\n total: number\n totalPages: number\n}\n\nfunction formatDate(value: string | null | undefined): string {\n if (!value) return '\u2014'\n const parsed = new Date(value)\n return Number.isNaN(parsed.getTime()) ? value : parsed.toLocaleString()\n}\n\nfunction formatDateOnly(value: string | null | undefined): string {\n if (!value) return '\u2014'\n const parsed = new Date(value)\n return Number.isNaN(parsed.getTime()) ? value : parsed.toLocaleDateString()\n}\n\nfunction statusVariant(\n status: BillRunRow['status'],\n): 'default' | 'success' | 'warning' | 'error' {\n switch (status) {\n case 'completed':\n return 'success'\n case 'partial_failure':\n return 'warning'\n case 'failed':\n return 'error'\n case 'running':\n default:\n return 'default'\n }\n}\n\nfunction modeBadge(row: BillRunRow): { label: string; variant: 'default' | 'warning' } | null {\n if (row.dry_run) return { label: 'Dry-run', variant: 'warning' }\n if (row.test_mode) return { label: 'Test', variant: 'warning' }\n return null\n}\n\nexport default function BillRunsListPage() {\n const t = useT()\n const router = useRouter()\n const [rows, setRows] = React.useState<BillRunRow[]>([])\n const [page, setPage] = React.useState(1)\n const [pageSize] = React.useState(25)\n const [filters, setFilters] = React.useState<FilterValues>({})\n const [total, setTotal] = React.useState(0)\n const [totalPages, setTotalPages] = React.useState(1)\n const [loading, setLoading] = React.useState(true)\n const [search, setSearch] = React.useState('')\n\n // Trigger dialog \u2014 controls the New-run modal and its submit state.\n const [triggerOpen, setTriggerOpen] = React.useState(false)\n const [triggerMode, setTriggerMode] = React.useState<TriggerMode>('real')\n const [triggerAsOfDate, setTriggerAsOfDate] = React.useState<string>(todayIso())\n const [triggering, setTriggering] = React.useState(false)\n\n const filterDefs = React.useMemo<FilterDef[]>(\n () => [\n {\n id: 'status',\n label: t('billing.runs.filters.status', 'Status'),\n type: 'select',\n options: [\n { value: 'running', label: t('billing.runs.status.running', 'Running') },\n { value: 'completed', label: t('billing.runs.status.completed', 'Completed') },\n {\n value: 'partial_failure',\n label: t('billing.runs.status.partial_failure', 'Partial failure'),\n },\n { value: 'failed', label: t('billing.runs.status.failed', 'Failed') },\n ],\n },\n {\n id: 'triggeredBy',\n label: t('billing.runs.filters.triggered_by', 'Trigger'),\n type: 'select',\n options: [\n { value: 'schedule', label: t('billing.runs.trigger.schedule', 'Schedule') },\n { value: 'manual', label: t('billing.runs.trigger.manual', 'Manual') },\n ],\n },\n ],\n [t],\n )\n\n const loadRows = React.useCallback(async () => {\n setLoading(true)\n try {\n const params = new URLSearchParams({\n page: String(page),\n pageSize: String(pageSize),\n sortField: 'startedAt',\n sortDir: 'desc',\n })\n if (search.trim()) params.set('search', search.trim())\n if (typeof filters.status === 'string' && filters.status) {\n params.set('status', filters.status)\n }\n if (typeof filters.triggeredBy === 'string' && filters.triggeredBy) {\n params.set('triggeredBy', filters.triggeredBy)\n }\n const result = await readApiResultOrThrow<ListResponse>(\n `/api/billing/runs?${params.toString()}`,\n )\n setRows(result.items ?? [])\n setTotal(result.total ?? 0)\n setTotalPages(result.totalPages ?? 1)\n } finally {\n setLoading(false)\n }\n }, [filters.status, filters.triggeredBy, page, pageSize, search])\n\n React.useEffect(() => {\n void loadRows()\n }, [loadRows])\n\n const handleTrigger = React.useCallback(async () => {\n setTriggering(true)\n try {\n const payload: Record<string, unknown> = { mode: triggerMode }\n if (triggerAsOfDate) payload.asOfDate = triggerAsOfDate\n const call = await apiCallOrThrow<{ billRunId: string | null }>(\n '/api/billing/runs',\n {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(payload),\n },\n )\n flash(t('billing.runs.trigger.success', 'Bill Run triggered'), 'success')\n setTriggerOpen(false)\n const newId = call.result?.billRunId\n if (newId) {\n router.push(`/backend/billing/runs/${newId}`)\n } else {\n void loadRows()\n }\n } catch (err) {\n const { message, fieldErrors } = normalizeCrudServerError(err)\n const fieldDetail =\n fieldErrors && Object.keys(fieldErrors).length\n ? Object.entries(fieldErrors)\n .map(([field, msg]) => `${field}: ${msg}`)\n .join('; ')\n : null\n const detailed =\n fieldDetail && message ? `${message} \u2014 ${fieldDetail}` : fieldDetail || message\n flash(detailed || t('billing.runs.trigger.error', 'Failed to trigger run'), 'error')\n } finally {\n setTriggering(false)\n }\n }, [loadRows, router, t, triggerAsOfDate, triggerMode])\n\n const handleTriggerKeyDown = React.useCallback(\n (event: React.KeyboardEvent<HTMLDivElement>) => {\n if ((event.metaKey || event.ctrlKey) && event.key === 'Enter') {\n event.preventDefault()\n if (!triggering) void handleTrigger()\n }\n },\n [handleTrigger, triggering],\n )\n\n const columns = React.useMemo<ColumnDef<BillRunRow>[]>(\n () => [\n {\n id: 'name',\n header: t('billing.runs.columns.name', 'Bill Run'),\n cell: ({ row }) => (\n <span className=\"text-sm font-medium text-primary\">\n {billRunName(row.original.as_of_date)}\n </span>\n ),\n },\n {\n accessorKey: 'status',\n header: t('billing.runs.columns.status', 'Status'),\n cell: ({ row }) => {\n const mode = modeBadge(row.original)\n return (\n <div className=\"flex items-center gap-2\">\n <Tag variant={statusVariant(row.original.status)}>\n {row.original.status}\n </Tag>\n {mode ? <Tag variant={mode.variant}>{mode.label}</Tag> : null}\n </div>\n )\n },\n },\n {\n accessorKey: 'as_of_date',\n header: t('billing.runs.columns.as_of_date', 'As-of date'),\n cell: ({ row }) => formatDateOnly(row.original.as_of_date),\n },\n {\n accessorKey: 'triggered_by',\n header: t('billing.runs.columns.triggered_by', 'Trigger'),\n },\n {\n id: 'drafts_created',\n header: t('billing.runs.columns.drafts', 'Drafts'),\n cell: ({ row }) => row.original.summary?.drafts_created ?? '\u2014',\n },\n {\n id: 'accounts_processed',\n header: t('billing.runs.columns.accounts', 'Accounts'),\n cell: ({ row }) => row.original.summary?.accounts_processed ?? '\u2014',\n },\n {\n id: 'accounts_failed',\n header: t('billing.runs.columns.failed', 'Failed'),\n cell: ({ row }) => {\n const failed = row.original.summary?.accounts_failed ?? 0\n if (failed === 0) return '\u2014'\n return <Tag variant=\"error\">{failed}</Tag>\n },\n },\n {\n accessorKey: 'started_at',\n header: t('billing.runs.columns.started_at', 'Started'),\n cell: ({ row }) => formatDate(row.original.started_at),\n },\n {\n accessorKey: 'finished_at',\n header: t('billing.runs.columns.finished_at', 'Finished'),\n cell: ({ row }) => formatDate(row.original.finished_at),\n },\n ],\n [t],\n )\n\n return (\n <Page>\n <PageBody>\n <DataTable\n title={t('billing.runs.title', 'Bill Runs')}\n actions={\n <Button onClick={() => setTriggerOpen(true)}>\n <Play size={16} />\n {t('billing.runs.trigger.action', 'New run')}\n </Button>\n }\n refreshButton={{\n label: t('billing.common.refresh', 'Refresh'),\n onRefresh: loadRows,\n isRefreshing: loading,\n }}\n columnChooser={{ auto: true }}\n perspective={{ tableId: 'billing-runs' }}\n columns={columns}\n data={rows}\n onRowClick={(row) => router.push(`/backend/billing/runs/${row.id}`)}\n isLoading={loading}\n pagination={{\n page,\n pageSize,\n total,\n totalPages,\n onPageChange: setPage,\n }}\n filters={filterDefs}\n filterValues={filters}\n onFiltersApply={setFilters}\n onFiltersClear={() => setFilters({})}\n searchValue={search}\n onSearchChange={setSearch}\n />\n\n <Dialog open={triggerOpen} onOpenChange={(next) => !triggering && setTriggerOpen(next)}>\n <DialogContent onKeyDown={handleTriggerKeyDown}>\n <DialogHeader>\n <DialogTitle>\n {t('billing.runs.trigger.dialog.title', 'Trigger Bill Run')}\n </DialogTitle>\n <DialogDescription>\n {t(\n 'billing.runs.trigger.dialog.description',\n 'Runs the bill cycle for every account whose next bill date has passed. Dry-run / Test produce drafts without posting any invoices.',\n )}\n </DialogDescription>\n </DialogHeader>\n <div className=\"space-y-4\">\n <label className=\"flex flex-col gap-1 text-sm\">\n <span className=\"text-muted-foreground\">\n {t('billing.runs.trigger.dialog.mode', 'Mode')}\n </span>\n <Select\n value={triggerMode}\n onValueChange={(next) => setTriggerMode(next as TriggerMode)}\n >\n <SelectTrigger>\n <SelectValue />\n </SelectTrigger>\n <SelectContent>\n <SelectItem value=\"real\">\n {t('billing.runs.trigger.dialog.mode.real', 'Real \u2014 create draft invoices')}\n </SelectItem>\n <SelectItem value=\"dry\">\n {t('billing.runs.trigger.dialog.mode.dry', 'Dry-run \u2014 no rows written')}\n </SelectItem>\n <SelectItem value=\"test\">\n {t('billing.runs.trigger.dialog.mode.test', 'Test \u2014 drafts tagged for cleanup')}\n </SelectItem>\n </SelectContent>\n </Select>\n </label>\n <label className=\"flex flex-col gap-1 text-sm\">\n <span className=\"text-muted-foreground\">\n {t('billing.runs.trigger.dialog.as_of_date', 'As-of date')}\n </span>\n <Input\n type=\"date\"\n value={triggerAsOfDate}\n onChange={(event) => setTriggerAsOfDate(event.currentTarget.value)}\n />\n <span className=\"text-xs text-muted-foreground\">\n {t(\n 'billing.runs.trigger.dialog.as_of_date.help',\n 'Accounts whose next bill date is on or before this date will be billed.',\n )}\n </span>\n </label>\n </div>\n <DialogFooter className=\"flex items-center justify-between gap-3 sm:justify-between\">\n <span className=\"text-xs text-muted-foreground\">\n <KbdShortcut keys={['Ctrl/\u2318', 'Enter']} />{' '}\n {t('billing.runs.trigger.dialog.submit_hint', 'to run,')} <Kbd>Esc</Kbd>{' '}\n {t('billing.runs.trigger.dialog.cancel_hint', 'to cancel')}\n </span>\n <div className=\"flex items-center gap-2\">\n <Button\n type=\"button\"\n variant=\"outline\"\n onClick={() => setTriggerOpen(false)}\n disabled={triggering}\n >\n {t('billing.common.cancel', 'Cancel')}\n </Button>\n <Button type=\"button\" onClick={() => void handleTrigger()} disabled={triggering}>\n {triggering\n ? t('billing.runs.trigger.dialog.running', 'Running\u2026')\n : t('billing.runs.trigger.dialog.submit', 'Run now')}\n </Button>\n </div>\n </DialogFooter>\n </DialogContent>\n </Dialog>\n </PageBody>\n </Page>\n )\n}\n"],
5
+ "mappings": ";AAoPU,cAWE,YAXF;AAnPV,YAAY,WAAW;AACvB,SAAS,iBAAiB;AAC1B,SAAS,YAAY;AAErB,SAAS,YAAY;AAErB,SAAS,MAAM,gBAAgB;AAC/B,SAAS,iBAAiB;AAC1B,SAAS,WAAW;AACpB,SAAS,cAAc;AACvB,SAAS,aAAa;AACtB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,KAAK,mBAAmB;AACjC,SAAS,aAAa;AACtB,SAAS,gBAAgB,4BAA4B;AACrD,SAAS,gCAAgC;AACzC,SAAS,mBAAmB;AAc5B,SAAS,WAAmB;AAC1B,UAAO,oBAAI,KAAK,GAAE,YAAY,EAAE,MAAM,GAAG,EAAE;AAC7C;AAgCA,SAAS,WAAW,OAA0C;AAC5D,MAAI,CAAC,MAAO,QAAO;AACnB,QAAM,SAAS,IAAI,KAAK,KAAK;AAC7B,SAAO,OAAO,MAAM,OAAO,QAAQ,CAAC,IAAI,QAAQ,OAAO,eAAe;AACxE;AAEA,SAAS,eAAe,OAA0C;AAChE,MAAI,CAAC,MAAO,QAAO;AACnB,QAAM,SAAS,IAAI,KAAK,KAAK;AAC7B,SAAO,OAAO,MAAM,OAAO,QAA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,KAAK;AAAA;AAAA,UACnE;AAAA,UACA,oBAAC,UAAK,WAAU,iCACb;AAAA,YACC;AAAA,YACA;AAAA,UACF,GACF;AAAA,WACF;AAAA,SACF;AAAA,MACA,qBAAC,gBAAa,WAAU,8DACtB;AAAA,6BAAC,UAAK,WAAU,iCACd;AAAA,8BAAC,eAAY,MAAM,CAAC,eAAU,OAAO,GAAG;AAAA,UAAG;AAAA,UAC1C,EAAE,2CAA2C,SAAS;AAAA,UAAE;AAAA,UAAC,oBAAC,OAAI,iBAAG;AAAA,UAAO;AAAA,UACxE,EAAE,2CAA2C,WAAW;AAAA,WAC3D;AAAA,QACA,qBAAC,SAAI,WAAU,2BACb;AAAA;AAAA,YAAC;AAAA;AAAA,cACC,MAAK;AAAA,cACL,SAAQ;AAAA,cACR,SAAS,MAAM,eAAe,KAAK;AAAA,cACnC,UAAU;AAAA,cAET,YAAE,yBAAyB,QAAQ;AAAA;AAAA,UACtC;AAAA,UACA,oBAAC,UAAO,MAAK,UAAS,SAAS,MAAM,KAAK,cAAc,GAAG,UAAU,YAClE,uBACG,EAAE,uCAAuC,eAAU,IACnD,EAAE,sCAAsC,SAAS,GACvD;AAAA,WACF;AAAA,SACF;AAAA,OACF,GACF;AAAA,KACF,GACF;AAEJ;",
6
+ "names": []
7
+ }
@@ -0,0 +1,18 @@
1
+ import React from "react";
2
+ import { PlayCircle } from "lucide-react";
3
+ const runsIcon = React.createElement(PlayCircle, { size: 16 });
4
+ const metadata = {
5
+ requireAuth: true,
6
+ requireFeatures: ["billing.run.view"],
7
+ pageTitle: "Bill Runs",
8
+ pageTitleKey: "billing.runs.title",
9
+ pageGroup: "Billing",
10
+ pageGroupKey: "billing.nav.group",
11
+ pageOrder: 30,
12
+ icon: runsIcon,
13
+ breadcrumb: [{ label: "Bill Runs", labelKey: "billing.runs.title" }]
14
+ };
15
+ export {
16
+ metadata
17
+ };
18
+ //# sourceMappingURL=page.meta.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../../../src/modules/billing/backend/billing/runs/page.meta.ts"],
4
+ "sourcesContent": ["import React from 'react'\nimport { PlayCircle } from 'lucide-react'\n\nconst runsIcon = React.createElement(PlayCircle, { size: 16 })\n\nexport const metadata = {\n requireAuth: true,\n requireFeatures: ['billing.run.view'],\n pageTitle: 'Bill Runs',\n pageTitleKey: 'billing.runs.title',\n pageGroup: 'Billing',\n pageGroupKey: 'billing.nav.group',\n pageOrder: 30,\n icon: runsIcon,\n breadcrumb: [{ label: 'Bill Runs', labelKey: 'billing.runs.title' }],\n} as const\n"],
5
+ "mappings": "AAAA,OAAO,WAAW;AAClB,SAAS,kBAAkB;AAE3B,MAAM,WAAW,MAAM,cAAc,YAAY,EAAE,MAAM,GAAG,CAAC;AAEtD,MAAM,WAAW;AAAA,EACtB,aAAa;AAAA,EACb,iBAAiB,CAAC,kBAAkB;AAAA,EACpC,WAAW;AAAA,EACX,cAAc;AAAA,EACd,WAAW;AAAA,EACX,cAAc;AAAA,EACd,WAAW;AAAA,EACX,MAAM;AAAA,EACN,YAAY,CAAC,EAAE,OAAO,aAAa,UAAU,qBAAqB,CAAC;AACrE;",
6
+ "names": []
7
+ }
@@ -0,0 +1,100 @@
1
+ "use client";
2
+ import { jsx, jsxs } from "react/jsx-runtime";
3
+ import * as React from "react";
4
+ import { useRouter, useSearchParams } from "next/navigation";
5
+ import { useT } from "@open-mercato/shared/lib/i18n/context";
6
+ import { Page, PageBody, PageHeader } from "@open-mercato/ui/backend/Page";
7
+ import { LoadingMessage } from "@open-mercato/ui/backend/detail";
8
+ import { flash } from "@open-mercato/ui/backend/FlashMessages";
9
+ import {
10
+ apiCallOrThrow,
11
+ readApiResultOrThrow
12
+ } from "@open-mercato/ui/backend/utils/apiCall";
13
+ import { normalizeCrudServerError } from "@open-mercato/ui/backend/utils/serverErrors";
14
+ import {
15
+ UsageForm
16
+ } from "../../../../components/UsageForm.js";
17
+ function CreateBillingUsagePage() {
18
+ const t = useT();
19
+ const router = useRouter();
20
+ const searchParams = useSearchParams();
21
+ const preselectedAccountId = searchParams.get("billAccountId") ?? "";
22
+ const [accounts, setAccounts] = React.useState(null);
23
+ const [submitting, setSubmitting] = React.useState(false);
24
+ React.useEffect(() => {
25
+ let cancelled = false;
26
+ void (async () => {
27
+ try {
28
+ const result = await readApiResultOrThrow(
29
+ "/api/billing/accounts?pageSize=100&sortField=name&sortDir=asc"
30
+ );
31
+ if (!cancelled) setAccounts(result.items ?? []);
32
+ } catch {
33
+ if (!cancelled) setAccounts([]);
34
+ }
35
+ })();
36
+ return () => {
37
+ cancelled = true;
38
+ };
39
+ }, []);
40
+ const handleSubmit = React.useCallback(
41
+ async (payload) => {
42
+ setSubmitting(true);
43
+ try {
44
+ const call = await apiCallOrThrow(
45
+ "/api/billing/usage",
46
+ {
47
+ method: "POST",
48
+ headers: { "Content-Type": "application/json" },
49
+ body: JSON.stringify(payload)
50
+ }
51
+ );
52
+ if (call.result?.deduplicated) {
53
+ flash(
54
+ t(
55
+ "billing.usage.create.deduplicated",
56
+ "A usage record with that source reference already existed \u2014 nothing was duplicated."
57
+ ),
58
+ "success"
59
+ );
60
+ } else {
61
+ flash(t("billing.usage.create.success", "Usage record created"), "success");
62
+ }
63
+ router.push(`/backend/billing/accounts/${payload.billAccountId}`);
64
+ } catch (err) {
65
+ const { message } = normalizeCrudServerError(err);
66
+ flash(
67
+ message || t("billing.usage.create.error", "Failed to record usage"),
68
+ "error"
69
+ );
70
+ } finally {
71
+ setSubmitting(false);
72
+ }
73
+ },
74
+ [router, t]
75
+ );
76
+ const handleCancel = React.useCallback(() => {
77
+ if (preselectedAccountId) {
78
+ router.push(`/backend/billing/accounts/${preselectedAccountId}`);
79
+ } else {
80
+ router.push("/backend/billing/accounts");
81
+ }
82
+ }, [preselectedAccountId, router]);
83
+ return /* @__PURE__ */ jsxs(Page, { children: [
84
+ /* @__PURE__ */ jsx(PageHeader, { title: t("billing.usage.create.title", "Record Usage") }),
85
+ /* @__PURE__ */ jsx(PageBody, { children: accounts === null ? /* @__PURE__ */ jsx(LoadingMessage, { label: t("billing.usage.create.loading", "Loading accounts\u2026") }) : /* @__PURE__ */ jsx(
86
+ UsageForm,
87
+ {
88
+ accountOptions: accounts,
89
+ initial: preselectedAccountId ? { billAccountId: preselectedAccountId } : void 0,
90
+ submitting,
91
+ onSubmit: handleSubmit,
92
+ onCancel: handleCancel
93
+ }
94
+ ) })
95
+ ] });
96
+ }
97
+ export {
98
+ CreateBillingUsagePage as default
99
+ };
100
+ //# sourceMappingURL=page.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../../../../src/modules/billing/backend/billing/usage/create/page.tsx"],
4
+ "sourcesContent": ["\"use client\"\nimport * as React from 'react'\nimport { useRouter, useSearchParams } from 'next/navigation'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport { Page, PageBody, PageHeader } from '@open-mercato/ui/backend/Page'\nimport { LoadingMessage } from '@open-mercato/ui/backend/detail'\nimport { flash } from '@open-mercato/ui/backend/FlashMessages'\nimport {\n apiCallOrThrow,\n readApiResultOrThrow,\n} from '@open-mercato/ui/backend/utils/apiCall'\nimport { normalizeCrudServerError } from '@open-mercato/ui/backend/utils/serverErrors'\nimport {\n UsageForm,\n type UsageAccountOption,\n type AssembledUsagePayload,\n} from '../../../../components/UsageForm'\n\n/**\n * `/backend/billing/usage/create` \u2014 manually record a usage entry.\n *\n * Mirrors `items/create`: loads the account list once to drive the\n * picker, supports `?billAccountId=<id>` deep-link from the account\n * detail page's \"Add usage\" CTA, and POSTs to `/api/billing/usage`\n * (the same endpoint external meters use). Usage has no detail page \u2014\n * on success we return to the account detail where the new record\n * shows up in the Usage section.\n */\nexport default function CreateBillingUsagePage() {\n const t = useT()\n const router = useRouter()\n const searchParams = useSearchParams()\n const preselectedAccountId = searchParams.get('billAccountId') ?? ''\n\n const [accounts, setAccounts] = React.useState<UsageAccountOption[] | null>(null)\n const [submitting, setSubmitting] = React.useState(false)\n\n React.useEffect(() => {\n let cancelled = false\n void (async () => {\n try {\n const result = await readApiResultOrThrow<{ items: UsageAccountOption[] }>(\n '/api/billing/accounts?pageSize=100&sortField=name&sortDir=asc',\n )\n if (!cancelled) setAccounts(result.items ?? [])\n } catch {\n if (!cancelled) setAccounts([])\n }\n })()\n return () => {\n cancelled = true\n }\n }, [])\n\n const handleSubmit = React.useCallback(\n async (payload: AssembledUsagePayload) => {\n setSubmitting(true)\n try {\n const call = await apiCallOrThrow<{ id: string; deduplicated: boolean }>(\n '/api/billing/usage',\n {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(payload),\n },\n )\n if (call.result?.deduplicated) {\n flash(\n t(\n 'billing.usage.create.deduplicated',\n 'A usage record with that source reference already existed \u2014 nothing was duplicated.',\n ),\n 'success',\n )\n } else {\n flash(t('billing.usage.create.success', 'Usage record created'), 'success')\n }\n router.push(`/backend/billing/accounts/${payload.billAccountId}`)\n } catch (err) {\n const { message } = normalizeCrudServerError(err)\n flash(\n message || t('billing.usage.create.error', 'Failed to record usage'),\n 'error',\n )\n } finally {\n setSubmitting(false)\n }\n },\n [router, t],\n )\n\n const handleCancel = React.useCallback(() => {\n if (preselectedAccountId) {\n router.push(`/backend/billing/accounts/${preselectedAccountId}`)\n } else {\n router.push('/backend/billing/accounts')\n }\n }, [preselectedAccountId, router])\n\n return (\n <Page>\n <PageHeader title={t('billing.usage.create.title', 'Record Usage')} />\n <PageBody>\n {accounts === null ? (\n <LoadingMessage label={t('billing.usage.create.loading', 'Loading accounts\u2026')} />\n ) : (\n <UsageForm\n accountOptions={accounts}\n initial={\n preselectedAccountId ? { billAccountId: preselectedAccountId } : undefined\n }\n submitting={submitting}\n onSubmit={handleSubmit}\n onCancel={handleCancel}\n />\n )}\n </PageBody>\n </Page>\n )\n}\n"],
5
+ "mappings": ";AAoGI,SACE,KADF;AAnGJ,YAAY,WAAW;AACvB,SAAS,WAAW,uBAAuB;AAC3C,SAAS,YAAY;AACrB,S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AAM,EAAE,QAAQ,IAAI,yBAAyB,GAAG;AAChD;AAAA,UACE,WAAW,EAAE,8BAA8B,wBAAwB;AAAA,UACnE;AAAA,QACF;AAAA,MACF,UAAE;AACA,sBAAc,KAAK;AAAA,MACrB;AAAA,IACF;AAAA,IACA,CAAC,QAAQ,CAAC;AAAA,EACZ;AAEA,QAAM,eAAe,MAAM,YAAY,MAAM;AAC3C,QAAI,sBAAsB;AACxB,aAAO,KAAK,6BAA6B,oBAAoB,EAAE;AAAA,IACjE,OAAO;AACL,aAAO,KAAK,2BAA2B;AAAA,IACzC;AAAA,EACF,GAAG,CAAC,sBAAsB,MAAM,CAAC;AAEjC,SACE,qBAAC,QACC;AAAA,wBAAC,cAAW,OAAO,EAAE,8BAA8B,cAAc,GAAG;AAAA,IACpE,oBAAC,YACE,uBAAa,OACZ,oBAAC,kBAAe,OAAO,EAAE,gCAAgC,wBAAmB,GAAG,IAE/E;AAAA,MAAC;AAAA;AAAA,QACC,gBAAgB;AAAA,QAChB,SACE,uBAAuB,EAAE,eAAe,qBAAqB,IAAI;AAAA,QAEnE;AAAA,QACA,UAAU;AAAA,QACV,UAAU;AAAA;AAAA,IACZ,GAEJ;AAAA,KACF;AAEJ;",
6
+ "names": []
7
+ }
@@ -0,0 +1,25 @@
1
+ import React from "react";
2
+ import { Gauge } from "lucide-react";
3
+ const usageIcon = React.createElement(Gauge, { size: 16 });
4
+ const metadata = {
5
+ requireAuth: true,
6
+ requireFeatures: ["billing.usage.ingest"],
7
+ pageTitle: "Record Usage",
8
+ pageTitleKey: "billing.usage.create.title",
9
+ pageGroup: "Billing",
10
+ pageGroupKey: "billing.nav.group",
11
+ navHidden: true,
12
+ icon: usageIcon,
13
+ breadcrumb: [
14
+ {
15
+ label: "Billing Accounts",
16
+ labelKey: "billing.accounts.title",
17
+ href: "/backend/billing/accounts"
18
+ },
19
+ { label: "Record Usage", labelKey: "billing.usage.create.title" }
20
+ ]
21
+ };
22
+ export {
23
+ metadata
24
+ };
25
+ //# sourceMappingURL=page.meta.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../../../../src/modules/billing/backend/billing/usage/create/page.meta.ts"],
4
+ "sourcesContent": ["import React from 'react'\nimport { Gauge } from 'lucide-react'\n\nconst usageIcon = React.createElement(Gauge, { size: 16 })\n\nexport const metadata = {\n requireAuth: true,\n requireFeatures: ['billing.usage.ingest'],\n pageTitle: 'Record Usage',\n pageTitleKey: 'billing.usage.create.title',\n pageGroup: 'Billing',\n pageGroupKey: 'billing.nav.group',\n navHidden: true,\n icon: usageIcon,\n breadcrumb: [\n {\n label: 'Billing Accounts',\n labelKey: 'billing.accounts.title',\n href: '/backend/billing/accounts',\n },\n { label: 'Record Usage', labelKey: 'billing.usage.create.title' },\n ],\n} as const\n"],
5
+ "mappings": "AAAA,OAAO,WAAW;AAClB,SAAS,aAAa;AAEtB,MAAM,YAAY,MAAM,cAAc,OAAO,EAAE,MAAM,GAAG,CAAC;AAElD,MAAM,WAAW;AAAA,EACtB,aAAa;AAAA,EACb,iBAAiB,CAAC,sBAAsB;AAAA,EACxC,WAAW;AAAA,EACX,cAAc;AAAA,EACd,WAAW;AAAA,EACX,cAAc;AAAA,EACd,WAAW;AAAA,EACX,MAAM;AAAA,EACN,YAAY;AAAA,IACV;AAAA,MACE,OAAO;AAAA,MACP,UAAU;AAAA,MACV,MAAM;AAAA,IACR;AAAA,IACA,EAAE,OAAO,gBAAgB,UAAU,6BAA6B;AAAA,EAClE;AACF;",
6
+ "names": []
7
+ }
@@ -0,0 +1,56 @@
1
+ const entities = [
2
+ {
3
+ id: "billing:billing_account",
4
+ label: "Billing Account",
5
+ description: "A per-customer container for billing items, usage, and bill-cycle metadata.",
6
+ labelField: "name",
7
+ showInSidebar: false,
8
+ fields: []
9
+ },
10
+ {
11
+ id: "billing:billing_item",
12
+ label: "Billing Item",
13
+ description: "A single charge (one_time / recurring / usage) attached to a Billing Account.",
14
+ labelField: "description",
15
+ showInSidebar: false,
16
+ fields: []
17
+ },
18
+ {
19
+ id: "billing:billing_account_usage",
20
+ label: "Billing Account Usage",
21
+ description: "A pre-aggregated usage record uploaded by external metering systems.",
22
+ labelField: "id",
23
+ showInSidebar: false,
24
+ fields: []
25
+ },
26
+ {
27
+ id: "billing:billing_run",
28
+ label: "Bill Run",
29
+ description: "A single execution of the Bill Run engine (schedule or manual trigger).",
30
+ labelField: "id",
31
+ showInSidebar: false,
32
+ fields: []
33
+ },
34
+ {
35
+ id: "billing:billing_run_outcome",
36
+ label: "Bill Run Outcome",
37
+ description: "Per-account outcome of a Bill Run \u2014 success / warnings / skipped / failed.",
38
+ labelField: "id",
39
+ showInSidebar: false,
40
+ fields: []
41
+ },
42
+ {
43
+ id: "billing:billing_draft_invoice_edit",
44
+ label: "Draft Invoice Edit",
45
+ description: "Append-only audit of operator edits on draft invoice lines.",
46
+ labelField: "id",
47
+ showInSidebar: false,
48
+ fields: []
49
+ }
50
+ ];
51
+ var ce_default = entities;
52
+ export {
53
+ ce_default as default,
54
+ entities
55
+ };
56
+ //# sourceMappingURL=ce.js.map