@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,143 @@
1
+ import { z } from "zod";
2
+ import { makeCrudRoute } from "@open-mercato/shared/lib/crud/factory";
3
+ import { withScopedPayload } from "@open-mercato/shared/lib/api/scoped";
4
+ import { resolveTranslations } from "@open-mercato/shared/lib/i18n/server";
5
+ import { BillRun } from "../../data/entities.js";
6
+ import { billingEntityIds } from "../../data/entityIds.js";
7
+ import {
8
+ billingRunListQuerySchema,
9
+ billingRunTriggerSchema
10
+ } from "../../data/validators.js";
11
+ import { createBillingCrudOpenApi, createPagedListResponseSchema } from "../openapi.js";
12
+ const routeMetadata = {
13
+ GET: { requireAuth: true, requireFeatures: ["billing.run.view"] },
14
+ POST: { requireAuth: true, requireFeatures: ["billing.run.trigger"] }
15
+ };
16
+ const metadata = routeMetadata;
17
+ const billRunListItemSchema = z.object({
18
+ id: z.string().uuid(),
19
+ triggered_by: z.string(),
20
+ parent_run_id: z.string().uuid().nullable(),
21
+ dry_run: z.boolean(),
22
+ test_mode: z.boolean(),
23
+ catch_up: z.boolean(),
24
+ scoped_account_ids: z.array(z.string().uuid()).nullable(),
25
+ as_of_date: z.string(),
26
+ started_at: z.string().nullable(),
27
+ finished_at: z.string().nullable(),
28
+ status: z.string(),
29
+ summary: z.record(z.string(), z.unknown()).nullable(),
30
+ organization_id: z.string().uuid(),
31
+ tenant_id: z.string().uuid(),
32
+ created_at: z.string(),
33
+ updated_at: z.string()
34
+ });
35
+ const triggerResponseSchema = z.object({
36
+ billRunId: z.string().uuid(),
37
+ status: z.string(),
38
+ outcomesCount: z.number().int().nonnegative()
39
+ });
40
+ const rawBodySchema = z.object({}).passthrough();
41
+ const crud = makeCrudRoute({
42
+ metadata: routeMetadata,
43
+ orm: {
44
+ entity: BillRun,
45
+ idField: "id",
46
+ orgField: "organizationId",
47
+ tenantField: "tenantId",
48
+ softDeleteField: "deletedAt"
49
+ },
50
+ list: {
51
+ schema: billingRunListQuerySchema,
52
+ entityId: billingEntityIds.run,
53
+ fields: [
54
+ "id",
55
+ "triggered_by",
56
+ "parent_run_id",
57
+ "dry_run",
58
+ "test_mode",
59
+ "catch_up",
60
+ "scoped_account_ids",
61
+ "as_of_date",
62
+ "started_at",
63
+ "finished_at",
64
+ "status",
65
+ "summary",
66
+ "organization_id",
67
+ "tenant_id",
68
+ "created_at",
69
+ "updated_at"
70
+ ],
71
+ sortFieldMap: {
72
+ startedAt: "started_at",
73
+ finishedAt: "finished_at",
74
+ asOfDate: "as_of_date",
75
+ createdAt: "created_at"
76
+ },
77
+ buildFilters: async (query) => {
78
+ const filters = {};
79
+ if (typeof query.id === "string" && query.id) {
80
+ filters.id = { $eq: query.id };
81
+ }
82
+ if (typeof query.search === "string" && /^[0-9a-fA-F-]{36}$/.test(query.search.trim())) {
83
+ filters.id = { $eq: query.search.trim() };
84
+ }
85
+ if (typeof query.status === "string") filters.status = { $eq: query.status };
86
+ if (typeof query.triggeredBy === "string") filters.triggered_by = { $eq: query.triggeredBy };
87
+ if (typeof query.parentRunId === "string") filters.parent_run_id = { $eq: query.parentRunId };
88
+ if (query.asOfDateFrom instanceof Date) {
89
+ filters.as_of_date = Object.assign(
90
+ filters.as_of_date ?? {},
91
+ { $gte: query.asOfDateFrom }
92
+ );
93
+ }
94
+ if (query.asOfDateTo instanceof Date) {
95
+ filters.as_of_date = Object.assign(
96
+ filters.as_of_date ?? {},
97
+ { $lte: query.asOfDateTo }
98
+ );
99
+ }
100
+ return filters;
101
+ }
102
+ },
103
+ actions: {
104
+ create: {
105
+ commandId: "billing.runs.trigger",
106
+ schema: rawBodySchema,
107
+ mapInput: async ({ raw, ctx }) => {
108
+ const { translate } = await resolveTranslations();
109
+ const scoped = withScopedPayload(raw ?? {}, ctx, translate);
110
+ return billingRunTriggerSchema.parse(scoped);
111
+ },
112
+ response: ({ result }) => ({
113
+ billRunId: result?.billRunId ?? null,
114
+ status: result?.status ?? null,
115
+ outcomesCount: result?.outcomesCount ?? 0
116
+ }),
117
+ status: 201
118
+ }
119
+ // Runs are append-only — no update / delete on this surface. A
120
+ // failed run is corrected by triggering a `retry-failed` (separate
121
+ // route).
122
+ }
123
+ });
124
+ const { POST } = crud;
125
+ const GET = crud.GET;
126
+ const openApi = createBillingCrudOpenApi({
127
+ resourceName: "BillRun",
128
+ pluralName: "BillRuns",
129
+ querySchema: billingRunListQuerySchema,
130
+ listResponseSchema: createPagedListResponseSchema(billRunListItemSchema),
131
+ create: {
132
+ schema: billingRunTriggerSchema,
133
+ responseSchema: triggerResponseSchema,
134
+ description: "Triggers a Bill Run. `mode=real` (default) persists drafts and advances state; `mode=test` persists test-flagged drafts without advancing state; `mode=dry` computes everything in memory and persists nothing. Returns HTTP 409 (`billing.run.lock_busy`) when another run is in flight for the same tenant."
135
+ }
136
+ });
137
+ export {
138
+ GET,
139
+ POST,
140
+ metadata,
141
+ openApi
142
+ };
143
+ //# sourceMappingURL=route.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../../src/modules/billing/api/runs/route.ts"],
4
+ "sourcesContent": ["import { z } from 'zod'\nimport { makeCrudRoute } from '@open-mercato/shared/lib/crud/factory'\nimport { withScopedPayload } from '@open-mercato/shared/lib/api/scoped'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { BillRun } from '../../data/entities'\nimport { billingEntityIds } from '../../data/entityIds'\nimport {\n billingRunListQuerySchema,\n billingRunTriggerSchema,\n} from '../../data/validators'\nimport { createBillingCrudOpenApi, createPagedListResponseSchema } from '../openapi'\n\n/**\n * `/api/billing/runs` \u2014 GET (history list) + POST (manual trigger).\n *\n * The triggered-by enum gate:\n * - `trigger` feature is required for `real` mode (which mutates\n * production state).\n * - `dry_run` feature alone is enough for `mode=dry` (finance auditor\n * persona). The route-level RBAC check on POST requires `trigger`,\n * so dry-run callers must hold both `dry_run` AND `trigger` here \u2014\n * a deliberate tightening over what the spec persona table suggests.\n *\n * If we ever want auditors to drive dry-runs without holding `trigger`,\n * we split into two routes (POST `/runs` for real, POST `/runs/dry` for\n * dry). Postponed until an operator actually asks.\n */\n\nconst routeMetadata = {\n GET: { requireAuth: true, requireFeatures: ['billing.run.view'] },\n POST: { requireAuth: true, requireFeatures: ['billing.run.trigger'] },\n}\n\nexport const metadata = routeMetadata\n\n// The list endpoint projects raw column names \u2014 snake_case.\nconst billRunListItemSchema = z.object({\n id: z.string().uuid(),\n triggered_by: z.string(),\n parent_run_id: z.string().uuid().nullable(),\n dry_run: z.boolean(),\n test_mode: z.boolean(),\n catch_up: z.boolean(),\n scoped_account_ids: z.array(z.string().uuid()).nullable(),\n as_of_date: z.string(),\n started_at: z.string().nullable(),\n finished_at: z.string().nullable(),\n status: z.string(),\n summary: z.record(z.string(), z.unknown()).nullable(),\n organization_id: z.string().uuid(),\n tenant_id: z.string().uuid(),\n created_at: z.string(),\n updated_at: z.string(),\n})\n\nconst triggerResponseSchema = z.object({\n billRunId: z.string().uuid(),\n status: z.string(),\n outcomesCount: z.number().int().nonnegative(),\n})\n\nconst rawBodySchema = z.object({}).passthrough()\n\nconst crud = makeCrudRoute({\n metadata: routeMetadata,\n orm: {\n entity: BillRun,\n idField: 'id',\n orgField: 'organizationId',\n tenantField: 'tenantId',\n softDeleteField: 'deletedAt',\n },\n list: {\n schema: billingRunListQuerySchema,\n entityId: billingEntityIds.run,\n fields: [\n 'id',\n 'triggered_by',\n 'parent_run_id',\n 'dry_run',\n 'test_mode',\n 'catch_up',\n 'scoped_account_ids',\n 'as_of_date',\n 'started_at',\n 'finished_at',\n 'status',\n 'summary',\n 'organization_id',\n 'tenant_id',\n 'created_at',\n 'updated_at',\n ],\n sortFieldMap: {\n startedAt: 'started_at',\n finishedAt: 'finished_at',\n asOfDate: 'as_of_date',\n createdAt: 'created_at',\n },\n buildFilters: async (query) => {\n const filters: Record<string, unknown> = {}\n // `?id=<uuid>` narrows the list to one row \u2014 the detail page\n // reads a single Bill Run through this filter.\n if (typeof query.id === 'string' && query.id) {\n filters.id = { $eq: query.id }\n }\n // Run ids are UUIDs \u2014 search matches a pasted id exactly.\n if (typeof query.search === 'string' && /^[0-9a-fA-F-]{36}$/.test(query.search.trim())) {\n filters.id = { $eq: query.search.trim() }\n }\n if (typeof query.status === 'string') filters.status = { $eq: query.status }\n if (typeof query.triggeredBy === 'string') filters.triggered_by = { $eq: query.triggeredBy }\n if (typeof query.parentRunId === 'string') filters.parent_run_id = { $eq: query.parentRunId }\n if (query.asOfDateFrom instanceof Date) {\n filters.as_of_date = Object.assign(\n (filters.as_of_date as Record<string, unknown>) ?? {},\n { $gte: query.asOfDateFrom },\n )\n }\n if (query.asOfDateTo instanceof Date) {\n filters.as_of_date = Object.assign(\n (filters.as_of_date as Record<string, unknown>) ?? {},\n { $lte: query.asOfDateTo },\n )\n }\n return filters\n },\n },\n actions: {\n create: {\n commandId: 'billing.runs.trigger',\n schema: rawBodySchema,\n mapInput: async ({ raw, ctx }) => {\n const { translate } = await resolveTranslations()\n const scoped = withScopedPayload(raw ?? {}, ctx, translate)\n return billingRunTriggerSchema.parse(scoped)\n },\n response: ({ result }) => ({\n billRunId: result?.billRunId ?? null,\n status: result?.status ?? null,\n outcomesCount: result?.outcomesCount ?? 0,\n }),\n status: 201,\n },\n // Runs are append-only \u2014 no update / delete on this surface. A\n // failed run is corrected by triggering a `retry-failed` (separate\n // route).\n },\n})\n\nconst { POST } = crud\nexport { POST }\nexport const GET = crud.GET\n\nexport const openApi = createBillingCrudOpenApi({\n resourceName: 'BillRun',\n pluralName: 'BillRuns',\n querySchema: billingRunListQuerySchema,\n listResponseSchema: createPagedListResponseSchema(billRunListItemSchema),\n create: {\n schema: billingRunTriggerSchema,\n responseSchema: triggerResponseSchema,\n description:\n 'Triggers a Bill Run. `mode=real` (default) persists drafts and ' +\n 'advances state; `mode=test` persists test-flagged drafts without ' +\n 'advancing state; `mode=dry` computes everything in memory and ' +\n 'persists nothing. Returns HTTP 409 (`billing.run.lock_busy`) when ' +\n 'another run is in flight for the same tenant.',\n },\n})\n"],
5
+ "mappings": "AAAA,SAAS,SAAS;AAClB,SAAS,qBAAqB;AAC9B,SAAS,yBAAyB;AAClC,SAAS,2BAA2B;AACpC,SAAS,eAAe;AACxB,SAAS,wBAAwB;AACjC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,0BAA0B,qCAAqC;AAkBxE,MAAM,gBAAgB;AAAA,EACpB,KAAK,EAAE,aAAa,MAAM,iBAAiB,CAAC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S;AAAA,IACP,QAAQ;AAAA,MACN,WAAW;AAAA,MACX,QAAQ;AAAA,MACR,UAAU,OAAO,EAAE,KAAK,IAAI,MAAM;AAChC,cAAM,EAAE,UAAU,IAAI,MAAM,oBAAoB;AAChD,cAAM,SAAS,kBAAkB,OAAO,CAAC,GAAG,KAAK,SAAS;AAC1D,eAAO,wBAAwB,MAAM,MAAM;AAAA,MAC7C;AAAA,MACA,UAAU,CAAC,EAAE,OAAO,OAAO;AAAA,QACzB,WAAW,QAAQ,aAAa;AAAA,QAChC,QAAQ,QAAQ,UAAU;AAAA,QAC1B,eAAe,QAAQ,iBAAiB;AAAA,MAC1C;AAAA,MACA,QAAQ;AAAA,IACV;AAAA;AAAA;AAAA;AAAA,EAIF;AACF,CAAC;AAED,MAAM,EAAE,KAAK,IAAI;AAEV,MAAM,MAAM,KAAK;AAEjB,MAAM,UAAU,yBAAyB;AAAA,EAC9C,cAAc;AAAA,EACd,YAAY;AAAA,EACZ,aAAa;AAAA,EACb,oBAAoB,8BAA8B,qBAAqB;AAAA,EACvE,QAAQ;AAAA,IACN,QAAQ;AAAA,IACR,gBAAgB;AAAA,IAChB,aACE;AAAA,EAKJ;AACF,CAAC;",
6
+ "names": []
7
+ }
@@ -0,0 +1,65 @@
1
+ import { z } from "zod";
2
+ import { makeCrudRoute } from "@open-mercato/shared/lib/crud/factory";
3
+ import { withScopedPayload } from "@open-mercato/shared/lib/api/scoped";
4
+ import { resolveTranslations } from "@open-mercato/shared/lib/i18n/server";
5
+ import { SalesInvoice } from "@open-mercato/core/modules/sales/data/entities";
6
+ import { billingEntityIds } from "../../../data/entityIds.js";
7
+ import { billingWipeTestInvoicesSchema } from "../../../data/validators.js";
8
+ import { createBillingCrudOpenApi } from "../../openapi.js";
9
+ const routeMetadata = {
10
+ POST: { requireAuth: true, requireFeatures: ["billing.run.trigger"] }
11
+ };
12
+ const metadata = routeMetadata;
13
+ const wipeResponseSchema = z.object({
14
+ invoicesRemoved: z.number().int().nonnegative()
15
+ });
16
+ const rawBodySchema = z.object({}).passthrough();
17
+ const crud = makeCrudRoute({
18
+ metadata: routeMetadata,
19
+ orm: {
20
+ entity: SalesInvoice,
21
+ idField: "id",
22
+ orgField: "organizationId",
23
+ tenantField: "tenantId",
24
+ softDeleteField: "deletedAt"
25
+ },
26
+ list: {
27
+ schema: z.object({}).passthrough(),
28
+ entityId: billingEntityIds.draftInvoiceEdit,
29
+ fields: ["id"],
30
+ buildFilters: async () => ({})
31
+ },
32
+ actions: {
33
+ create: {
34
+ commandId: "billing.invoices.wipe_test",
35
+ schema: rawBodySchema,
36
+ mapInput: async ({ raw, ctx }) => {
37
+ const { translate } = await resolveTranslations();
38
+ const scoped = withScopedPayload(raw ?? {}, ctx, translate);
39
+ return billingWipeTestInvoicesSchema.parse(scoped);
40
+ },
41
+ response: ({ result }) => ({
42
+ invoicesRemoved: result?.invoicesRemoved ?? 0
43
+ }),
44
+ status: 200
45
+ }
46
+ }
47
+ });
48
+ const POST = crud.POST;
49
+ const openApi = createBillingCrudOpenApi({
50
+ resourceName: "BillingTestInvoiceWipe",
51
+ pluralName: "BillingTestInvoiceWipes",
52
+ querySchema: z.object({}).passthrough(),
53
+ listResponseSchema: z.object({ items: z.array(z.unknown()) }),
54
+ create: {
55
+ schema: billingWipeTestInvoicesSchema,
56
+ responseSchema: wipeResponseSchema,
57
+ description: "Hard-deletes test invoices (`metadata.test_run=true`) for the authenticated tenant. Pass `billRunId` to wipe only invoices from a specific test Bill Run. Returns the count removed. Test data should not pollute production history, so this is a hard delete, not a soft delete."
58
+ }
59
+ });
60
+ export {
61
+ POST,
62
+ metadata,
63
+ openApi
64
+ };
65
+ //# sourceMappingURL=route.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../../../src/modules/billing/api/test-invoices/wipe/route.ts"],
4
+ "sourcesContent": ["import { z } from 'zod'\nimport { makeCrudRoute } from '@open-mercato/shared/lib/crud/factory'\nimport { withScopedPayload } from '@open-mercato/shared/lib/api/scoped'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { SalesInvoice } from '@open-mercato/core/modules/sales/data/entities'\nimport { billingEntityIds } from '../../../data/entityIds'\nimport { billingWipeTestInvoicesSchema } from '../../../data/validators'\nimport { createBillingCrudOpenApi } from '../../openapi'\n\n/**\n * `POST /api/billing/test-invoices/wipe` \u2014 hard-delete invoices\n * flagged `metadata.test_run=true` for this tenant. Optionally\n * scoped to a `billRunId` so an operator can wipe a single test run\n * without nuking other test data.\n *\n * Modelled as POST (not DELETE) because the body carries the scope\n * fields and modern Next.js routers reject DELETE-with-body more\n * consistently than they accept it; keeping POST keeps the surface\n * uniform with the rest of the billing API.\n *\n * Gated by `billing.run.trigger` (test mode is part of the\n * \"operate Bill Runs\" toolkit). Phase 4c admin UI exposes this\n * behind a confirm dialog on the Bill Run detail page.\n */\n\nconst routeMetadata = {\n POST: { requireAuth: true, requireFeatures: ['billing.run.trigger'] },\n}\n\nexport const metadata = routeMetadata\n\nconst wipeResponseSchema = z.object({\n invoicesRemoved: z.number().int().nonnegative(),\n})\n\nconst rawBodySchema = z.object({}).passthrough()\n\nconst crud = makeCrudRoute({\n metadata: routeMetadata,\n orm: {\n entity: SalesInvoice,\n idField: 'id',\n orgField: 'organizationId',\n tenantField: 'tenantId',\n softDeleteField: 'deletedAt',\n },\n list: {\n schema: z.object({}).passthrough(),\n entityId: billingEntityIds.draftInvoiceEdit,\n fields: ['id'],\n buildFilters: async () => ({}),\n },\n actions: {\n create: {\n commandId: 'billing.invoices.wipe_test',\n schema: rawBodySchema,\n mapInput: async ({ raw, ctx }) => {\n const { translate } = await resolveTranslations()\n const scoped = withScopedPayload(raw ?? {}, ctx, translate)\n return billingWipeTestInvoicesSchema.parse(scoped)\n },\n response: ({ result }) => ({\n invoicesRemoved: result?.invoicesRemoved ?? 0,\n }),\n status: 200,\n },\n },\n})\n\nexport const POST = crud.POST\n\nexport const openApi = createBillingCrudOpenApi({\n resourceName: 'BillingTestInvoiceWipe',\n pluralName: 'BillingTestInvoiceWipes',\n querySchema: z.object({}).passthrough(),\n listResponseSchema: z.object({ items: z.array(z.unknown()) }),\n create: {\n schema: billingWipeTestInvoicesSchema,\n responseSchema: wipeResponseSchema,\n description:\n 'Hard-deletes test invoices (`metadata.test_run=true`) for the ' +\n 'authenticated tenant. Pass `billRunId` to wipe only invoices ' +\n 'from a specific test Bill Run. Returns the count removed. ' +\n 'Test data should not pollute production history, so this is a ' +\n 'hard delete, not a soft delete.',\n },\n})\n"],
5
+ "mappings": "AAAA,SAAS,SAAS;AAClB,SAAS,qBAAqB;AAC9B,SAAS,yBAAyB;AAClC,SAAS,2BAA2B;AACpC,SAAS,oBAAoB;AAC7B,SAAS,wBAAwB;AACjC,SAAS,qCAAqC;AAC9C,SAAS,gCAAgC;AAkBzC,MAAM,gBAAgB;AAAA,EACpB,MAAM,EAAE,aAAa,MAAM,iBAAiB,CAAC,qBAAqB,EAAE;AACtE;AAEO,MAAM,WAAW;AAExB,MAAM,qBAAqB,EAAE,OAAO;AAAA,EAClC,iBAAiB,EAAE,OAAO,EAAE,IAAI,EAAE,YAAY;AAChD,CAAC;AAED,MAAM,gBAAgB,EAAE,OAAO,CAAC,CAAC,EAAE,YAAY;AAE/C,MAAM,OAAO,cAAc;AAAA,EACzB,UAAU;AAAA,EACV,KAAK;AAAA,IACH,QAAQ;AAAA,IACR,SAAS;AAAA,IACT,UAAU;AAAA,IACV,aAAa;AAAA,IACb,iBAAiB;AAAA,EACnB;AAAA,EACA,MAAM;AAAA,IACJ,QAAQ,EAAE,OAAO,CAAC,CAAC,EAAE,YAAY;AAAA,IACjC,UAAU,iBAAiB;AAAA,IAC3B,QAAQ,CAAC,IAAI;AAAA,IACb,cAAc,aAAa,CAAC;AAAA,EAC9B;AAAA,EACA,SAAS;AAAA,IACP,QAAQ;AAAA,MACN,WAAW;AAAA,MACX,QAAQ;AAAA,MACR,UAAU,OAAO,EAAE,KAAK,IAAI,MAAM;AAChC,cAAM,EAAE,UAAU,IAAI,MAAM,oBAAoB;AAChD,cAAM,SAAS,kBAAkB,OAAO,CAAC,GAAG,KAAK,SAAS;AAC1D,eAAO,8BAA8B,MAAM,MAAM;AAAA,MACnD;AAAA,MACA,UAAU,CAAC,EAAE,OAAO,OAAO;AAAA,QACzB,iBAAiB,QAAQ,mBAAmB;AAAA,MAC9C;AAAA,MACA,QAAQ;AAAA,IACV;AAAA,EACF;AACF,CAAC;AAEM,MAAM,OAAO,KAAK;AAElB,MAAM,UAAU,yBAAyB;AAAA,EAC9C,cAAc;AAAA,EACd,YAAY;AAAA,EACZ,aAAa,EAAE,OAAO,CAAC,CAAC,EAAE,YAAY;AAAA,EACtC,oBAAoB,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,CAAC;AAAA,EAC5D,QAAQ;AAAA,IACN,QAAQ;AAAA,IACR,gBAAgB;AAAA,IAChB,aACE;AAAA,EAKJ;AACF,CAAC;",
6
+ "names": []
7
+ }
@@ -0,0 +1,138 @@
1
+ import { z } from "zod";
2
+ import { makeCrudRoute } from "@open-mercato/shared/lib/crud/factory";
3
+ import { withScopedPayload } from "@open-mercato/shared/lib/api/scoped";
4
+ import { resolveTranslations } from "@open-mercato/shared/lib/i18n/server";
5
+ import { BillingAccountUsage } from "../../data/entities.js";
6
+ import { billingEntityIds } from "../../data/entityIds.js";
7
+ import {
8
+ billingUsageCreateSchema,
9
+ billingUsageListQuerySchema
10
+ } from "../../data/validators.js";
11
+ import {
12
+ createBillingCrudOpenApi,
13
+ createPagedListResponseSchema
14
+ } from "../openapi.js";
15
+ const routeMetadata = {
16
+ GET: { requireAuth: true, requireFeatures: ["billing.usage.view"] },
17
+ POST: { requireAuth: true, requireFeatures: ["billing.usage.ingest"] }
18
+ };
19
+ const metadata = routeMetadata;
20
+ const billingUsageListItemSchema = z.object({
21
+ id: z.string().uuid(),
22
+ billAccountId: z.string().uuid(),
23
+ uomCode: z.string(),
24
+ quantity: z.string(),
25
+ // numeric(18,4) → string
26
+ periodStart: z.string(),
27
+ periodEnd: z.string(),
28
+ lineDescription: z.string().nullable(),
29
+ sourceRef: z.string().nullable(),
30
+ ratedInBillRunId: z.string().uuid().nullable(),
31
+ isActive: z.boolean(),
32
+ organizationId: z.string().uuid(),
33
+ tenantId: z.string().uuid(),
34
+ createdAt: z.string(),
35
+ updatedAt: z.string()
36
+ });
37
+ const usageCreateResponseSchema = z.object({
38
+ id: z.string().uuid().nullable(),
39
+ deduplicated: z.boolean()
40
+ });
41
+ const rawBodySchema = z.object({}).passthrough();
42
+ const crud = makeCrudRoute({
43
+ metadata: routeMetadata,
44
+ orm: {
45
+ entity: BillingAccountUsage,
46
+ idField: "id",
47
+ orgField: "organizationId",
48
+ tenantField: "tenantId",
49
+ softDeleteField: "deletedAt"
50
+ },
51
+ list: {
52
+ schema: billingUsageListQuerySchema,
53
+ entityId: billingEntityIds.usage,
54
+ fields: [
55
+ "id",
56
+ "bill_account_id",
57
+ "uom_code",
58
+ "quantity",
59
+ "period_start",
60
+ "period_end",
61
+ "line_description",
62
+ "source_ref",
63
+ "rated_in_bill_run_id",
64
+ "is_active",
65
+ "organization_id",
66
+ "tenant_id",
67
+ "created_at",
68
+ "updated_at"
69
+ ],
70
+ sortFieldMap: {
71
+ createdAt: "created_at",
72
+ periodStart: "period_start",
73
+ periodEnd: "period_end"
74
+ },
75
+ buildFilters: async (query) => {
76
+ const filters = {};
77
+ if (typeof query.billAccountId === "string" && query.billAccountId) {
78
+ filters.bill_account_id = { $eq: query.billAccountId };
79
+ }
80
+ if (typeof query.uomCode === "string" && query.uomCode) {
81
+ filters.uom_code = { $eq: query.uomCode };
82
+ }
83
+ if (typeof query.rated === "boolean") {
84
+ filters.rated_in_bill_run_id = query.rated ? { $ne: null } : { $eq: null };
85
+ }
86
+ if (query.periodEndFrom instanceof Date) {
87
+ filters.period_end = Object.assign(
88
+ filters.period_end ?? {},
89
+ { $gte: query.periodEndFrom }
90
+ );
91
+ }
92
+ if (query.periodEndTo instanceof Date) {
93
+ filters.period_end = Object.assign(
94
+ filters.period_end ?? {},
95
+ { $lte: query.periodEndTo }
96
+ );
97
+ }
98
+ return filters;
99
+ }
100
+ },
101
+ actions: {
102
+ create: {
103
+ commandId: "billing.usage.create",
104
+ schema: rawBodySchema,
105
+ mapInput: async ({ raw, ctx }) => {
106
+ const { translate } = await resolveTranslations();
107
+ const scoped = withScopedPayload(raw ?? {}, ctx, translate);
108
+ return billingUsageCreateSchema.parse(scoped);
109
+ },
110
+ response: ({ result }) => ({
111
+ id: result?.id ?? null,
112
+ deduplicated: Boolean(result?.deduplicated)
113
+ }),
114
+ status: 200
115
+ }
116
+ // Usage has no update or delete by design — see file header.
117
+ }
118
+ });
119
+ const { POST } = crud;
120
+ const GET = crud.GET;
121
+ const openApi = createBillingCrudOpenApi({
122
+ resourceName: "BillingUsageRecord",
123
+ pluralName: "BillingUsageRecords",
124
+ querySchema: billingUsageListQuerySchema,
125
+ listResponseSchema: createPagedListResponseSchema(billingUsageListItemSchema),
126
+ create: {
127
+ schema: billingUsageCreateSchema,
128
+ responseSchema: usageCreateResponseSchema,
129
+ description: "Ingests a pre-aggregated usage record. Idempotent via `sourceRef`. Usage records are immutable once persisted \u2014 to correct a mis-aggregation, post a `one_time` Billing Item credit (the spec's refund model)."
130
+ }
131
+ });
132
+ export {
133
+ GET,
134
+ POST,
135
+ metadata,
136
+ openApi
137
+ };
138
+ //# sourceMappingURL=route.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../../src/modules/billing/api/usage/route.ts"],
4
+ "sourcesContent": ["import { z } from 'zod'\nimport { makeCrudRoute } from '@open-mercato/shared/lib/crud/factory'\nimport { withScopedPayload } from '@open-mercato/shared/lib/api/scoped'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { BillingAccountUsage } from '../../data/entities'\nimport { billingEntityIds } from '../../data/entityIds'\nimport {\n billingUsageCreateSchema,\n billingUsageListQuerySchema,\n} from '../../data/validators'\nimport {\n createBillingCrudOpenApi,\n createPagedListResponseSchema,\n} from '../openapi'\n\n// \u2500\u2500\u2500 Auth / RBAC \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n//\n// Usage is append-only \u2014 no update or delete. The narrow scope here\n// lets us mint API keys for external metering systems with ONLY\n// `billing.usage.ingest`, eliminating an entire blast radius.\n\nconst routeMetadata = {\n GET: { requireAuth: true, requireFeatures: ['billing.usage.view'] },\n POST: { requireAuth: true, requireFeatures: ['billing.usage.ingest'] },\n}\n\nexport const metadata = routeMetadata\n\nconst billingUsageListItemSchema = z.object({\n id: z.string().uuid(),\n billAccountId: z.string().uuid(),\n uomCode: z.string(),\n quantity: z.string(), // numeric(18,4) \u2192 string\n periodStart: z.string(),\n periodEnd: z.string(),\n lineDescription: z.string().nullable(),\n sourceRef: z.string().nullable(),\n ratedInBillRunId: z.string().uuid().nullable(),\n isActive: z.boolean(),\n organizationId: z.string().uuid(),\n tenantId: z.string().uuid(),\n createdAt: z.string(),\n updatedAt: z.string(),\n})\n\nconst usageCreateResponseSchema = z.object({\n id: z.string().uuid().nullable(),\n deduplicated: z.boolean(),\n})\n\nconst rawBodySchema = z.object({}).passthrough()\n\nconst crud = makeCrudRoute({\n metadata: routeMetadata,\n orm: {\n entity: BillingAccountUsage,\n idField: 'id',\n orgField: 'organizationId',\n tenantField: 'tenantId',\n softDeleteField: 'deletedAt',\n },\n list: {\n schema: billingUsageListQuerySchema,\n entityId: billingEntityIds.usage,\n fields: [\n 'id',\n 'bill_account_id',\n 'uom_code',\n 'quantity',\n 'period_start',\n 'period_end',\n 'line_description',\n 'source_ref',\n 'rated_in_bill_run_id',\n 'is_active',\n 'organization_id',\n 'tenant_id',\n 'created_at',\n 'updated_at',\n ],\n sortFieldMap: {\n createdAt: 'created_at',\n periodStart: 'period_start',\n periodEnd: 'period_end',\n },\n buildFilters: async (query) => {\n const filters: Record<string, unknown> = {}\n if (typeof query.billAccountId === 'string' && query.billAccountId) {\n filters.bill_account_id = { $eq: query.billAccountId }\n }\n if (typeof query.uomCode === 'string' && query.uomCode) {\n filters.uom_code = { $eq: query.uomCode }\n }\n if (typeof query.rated === 'boolean') {\n filters.rated_in_bill_run_id = query.rated ? { $ne: null } : { $eq: null }\n }\n if (query.periodEndFrom instanceof Date) {\n filters.period_end = Object.assign(\n (filters.period_end as Record<string, unknown>) ?? {},\n { $gte: query.periodEndFrom },\n )\n }\n if (query.periodEndTo instanceof Date) {\n filters.period_end = Object.assign(\n (filters.period_end as Record<string, unknown>) ?? {},\n { $lte: query.periodEndTo },\n )\n }\n return filters\n },\n },\n actions: {\n create: {\n commandId: 'billing.usage.create',\n schema: rawBodySchema,\n mapInput: async ({ raw, ctx }) => {\n const { translate } = await resolveTranslations()\n const scoped = withScopedPayload(raw ?? {}, ctx, translate)\n return billingUsageCreateSchema.parse(scoped)\n },\n response: ({ result }) => ({\n id: result?.id ?? null,\n deduplicated: Boolean(result?.deduplicated),\n }),\n status: 200,\n },\n // Usage has no update or delete by design \u2014 see file header.\n },\n})\n\nconst { POST } = crud\nexport { POST }\nexport const GET = crud.GET\n\nexport const openApi = createBillingCrudOpenApi({\n resourceName: 'BillingUsageRecord',\n pluralName: 'BillingUsageRecords',\n querySchema: billingUsageListQuerySchema,\n listResponseSchema: createPagedListResponseSchema(billingUsageListItemSchema),\n create: {\n schema: billingUsageCreateSchema,\n responseSchema: usageCreateResponseSchema,\n description:\n 'Ingests a pre-aggregated usage record. Idempotent via `sourceRef`. ' +\n 'Usage records are immutable once persisted \u2014 to correct a mis-aggregation, ' +\n \"post a `one_time` Billing Item credit (the spec's refund model).\",\n },\n})\n"],
5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