@codelitdev/platform-cli 0.1.0-alpha.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 (90) hide show
  1. package/LICENSE +21 -0
  2. package/dist/bin.d.ts +2 -0
  3. package/dist/bin.js +43 -0
  4. package/dist/codemod-readme-title.d.ts +5 -0
  5. package/dist/codemod-readme-title.js +21 -0
  6. package/dist/create.d.ts +6 -0
  7. package/dist/create.js +124 -0
  8. package/dist/doctor.d.ts +12 -0
  9. package/dist/doctor.js +111 -0
  10. package/dist/fs.d.ts +5 -0
  11. package/dist/fs.js +42 -0
  12. package/dist/git.d.ts +1 -0
  13. package/dist/git.js +19 -0
  14. package/dist/hash.d.ts +2 -0
  15. package/dist/hash.js +8 -0
  16. package/dist/index.d.ts +4 -0
  17. package/dist/index.js +4 -0
  18. package/dist/manifest.d.ts +12 -0
  19. package/dist/manifest.js +31 -0
  20. package/dist/template.d.ts +2 -0
  21. package/dist/template.js +23 -0
  22. package/dist/upgrade.d.ts +13 -0
  23. package/dist/upgrade.js +97 -0
  24. package/package.json +41 -0
  25. package/template/.github/workflows/platform-conformance.yml +28 -0
  26. package/template/README.md +5 -0
  27. package/template/apps/api/.env.example +18 -0
  28. package/template/apps/api/README.md +3 -0
  29. package/template/apps/api/billing.config.ts +25 -0
  30. package/template/apps/api/drizzle.config.ts +7 -0
  31. package/template/apps/api/package.json +53 -0
  32. package/template/apps/api/scripts/generate-auth-schema.mjs +173 -0
  33. package/template/apps/api/scripts/migrate.mjs +15 -0
  34. package/template/apps/api/src/app.test.ts +479 -0
  35. package/template/apps/api/src/auth/api-keys.ts +131 -0
  36. package/template/apps/api/src/auth/authenticate.ts +166 -0
  37. package/template/apps/api/src/auth/better-auth.ts +38 -0
  38. package/template/apps/api/src/auth/oauth.ts +9 -0
  39. package/template/apps/api/src/auth/options.ts +69 -0
  40. package/template/apps/api/src/billing.ts +58 -0
  41. package/template/apps/api/src/conformance-adapter.ts +335 -0
  42. package/template/apps/api/src/db/migrate.ts +26 -0
  43. package/template/apps/api/src/db/migrations/0000_application.sql +72 -0
  44. package/template/apps/api/src/db/migrations/0000_auth.sql +178 -0
  45. package/template/apps/api/src/db/migrations/0001_billing.sql +234 -0
  46. package/template/apps/api/src/db/schema/auth.generated.ts +185 -0
  47. package/template/apps/api/src/db/schema/billing.generated.ts +447 -0
  48. package/template/apps/api/src/db/schema/index.ts +3 -0
  49. package/template/apps/api/src/db/schema/notes.ts +31 -0
  50. package/template/apps/api/src/db/schema/tenants.ts +83 -0
  51. package/template/apps/api/src/deps.ts +12 -0
  52. package/template/apps/api/src/dispatch.ts +476 -0
  53. package/template/apps/api/src/express-app.ts +161 -0
  54. package/template/apps/api/src/invitations.ts +217 -0
  55. package/template/apps/api/src/logger.ts +26 -0
  56. package/template/apps/api/src/main.ts +98 -0
  57. package/template/apps/api/src/mcp.ts +127 -0
  58. package/template/apps/api/src/notes.ts +251 -0
  59. package/template/apps/api/src/openapi.ts +12 -0
  60. package/template/apps/api/src/permissions.ts +35 -0
  61. package/template/apps/api/src/runtime.ts +167 -0
  62. package/template/apps/api/src/seed.ts +340 -0
  63. package/template/apps/api/src/tenancy.ts +116 -0
  64. package/template/apps/api/src/types.ts +20 -0
  65. package/template/apps/api/src/worker.ts +57 -0
  66. package/template/apps/api/tsconfig.json +14 -0
  67. package/template/apps/web/.env.example +7 -0
  68. package/template/apps/web/app/api/[...path]/route.ts +51 -0
  69. package/template/apps/web/app/globals.css +156 -0
  70. package/template/apps/web/app/layout.tsx +34 -0
  71. package/template/apps/web/app/login/page.tsx +127 -0
  72. package/template/apps/web/app/notes/page.tsx +93 -0
  73. package/template/apps/web/app/page.tsx +80 -0
  74. package/template/apps/web/components/auth-gate.tsx +34 -0
  75. package/template/apps/web/components/browser-observability.tsx +53 -0
  76. package/template/apps/web/components/tenant-switcher.tsx +51 -0
  77. package/template/apps/web/lib/observability-config.ts +15 -0
  78. package/template/apps/web/next-env.d.ts +2 -0
  79. package/template/apps/web/next.config.ts +7 -0
  80. package/template/apps/web/package.json +26 -0
  81. package/template/apps/web/tsconfig.json +21 -0
  82. package/template/biome.template.json +50 -0
  83. package/template/docker-compose.yml +14 -0
  84. package/template/package.json +40 -0
  85. package/template/packages/api-contract/package.json +23 -0
  86. package/template/packages/api-contract/src/index.ts +256 -0
  87. package/template/packages/api-contract/src/mcp-parity.ts +158 -0
  88. package/template/packages/api-contract/tsconfig.json +11 -0
  89. package/template/patches/@anatine__zod-openapi@1.14.2.patch +14 -0
  90. package/template/tooling/platform/config.ts +2 -0
@@ -0,0 +1,447 @@
1
+ /**
2
+ * AUTO-GENERATED FILE. DO NOT EDIT.
3
+ * Generated by @codelitdev/billing schema version 2.
4
+ */
5
+ import { sql } from "drizzle-orm";
6
+ import {
7
+ boolean,
8
+ check,
9
+ index,
10
+ integer,
11
+ pgTable,
12
+ text,
13
+ timestamp,
14
+ uniqueIndex,
15
+ uuid,
16
+ } from "drizzle-orm/pg-core";
17
+ // The generated artifact is also loaded directly by drizzle-kit, which resolves
18
+ // extensionless application TypeScript imports. Keep those imports portable for
19
+ // the consuming application's module resolver.
20
+ // @ts-ignore drizzle-kit resolves the extensionless TypeScript import.
21
+ import { tenants } from "./tenants";
22
+ // @ts-ignore drizzle-kit resolves the extensionless TypeScript import.
23
+ import { user } from "./auth.generated";
24
+
25
+ const timestamps = {
26
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
27
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
28
+ };
29
+
30
+ export const billingPriceEntries = pgTable(
31
+ "billing_price_entries",
32
+ {
33
+ id: uuid("id").primaryKey().defaultRandom(),
34
+ offerKey: text("offer_key").notNull(),
35
+ plan: text("plan").notNull(),
36
+ billingInterval: text("billing_interval").notNull(),
37
+ currency: text("currency").notNull(),
38
+ amountMinor: integer("amount_minor").notNull(),
39
+ providerTrialDays: integer("provider_trial_days").notNull().default(0),
40
+ provider: text("provider").notNull(),
41
+ providerProductId: text("provider_product_id").notNull(),
42
+ verifiedAt: timestamp("verified_at", { withTimezone: true }),
43
+ ...timestamps,
44
+ },
45
+ (table) => ({
46
+ providerProductUnique: uniqueIndex("billing_price_entries_provider_product_uidx").on(
47
+ table.provider,
48
+ table.providerProductId,
49
+ ),
50
+ offerKeyIdx: index("billing_price_entries_offer_key_idx").on(table.offerKey),
51
+ amountCheck: check("billing_price_entries_amount_check", sql`${table.amountMinor} > 0`),
52
+ trialDaysCheck: check("billing_price_entries_trial_days_check", sql`${table.providerTrialDays} >= 0`),
53
+ currencyCheck: check("billing_price_entries_currency_check", sql`${table.currency} ~ '^[A-Z]{3}$'`),
54
+ planCheck: check("billing_price_entries_plan_check", sql`${table.plan} IN ('pro', 'business')`),
55
+ intervalCheck: check(
56
+ "billing_price_entries_interval_check",
57
+ sql`${table.billingInterval} IN ('month', 'year')`,
58
+ ),
59
+ }),
60
+ );
61
+
62
+ export const billingCatalogRevisions = pgTable(
63
+ "billing_catalog_revisions",
64
+ {
65
+ id: uuid("id").primaryKey().defaultRandom(),
66
+ revision: integer("revision").notNull().unique(),
67
+ checkoutProvider: text("checkout_provider").notNull(),
68
+ status: text("status").notNull().default("pending_verification"),
69
+ verifiedAt: timestamp("verified_at", { withTimezone: true }),
70
+ activatedAt: timestamp("activated_at", { withTimezone: true }),
71
+ retiredAt: timestamp("retired_at", { withTimezone: true }),
72
+ ...timestamps,
73
+ },
74
+ (table) => ({
75
+ statusCheck: check(
76
+ "billing_catalog_revisions_status_check",
77
+ sql`${table.status} IN ('pending_verification', 'active', 'retired', 'invalid', 'abandoned')`,
78
+ ),
79
+ revisionCheck: check("billing_catalog_revisions_revision_check", sql`${table.revision} > 0`),
80
+ activeProviderUnique: uniqueIndex("billing_catalog_revisions_active_provider_uidx")
81
+ .on(table.checkoutProvider)
82
+ .where(sql`${table.status} = 'active'`),
83
+ }),
84
+ );
85
+
86
+ export const billingCatalogRevisionItems = pgTable(
87
+ "billing_catalog_revision_items",
88
+ {
89
+ id: uuid("id").primaryKey().defaultRandom(),
90
+ catalogRevisionId: uuid("catalog_revision_id")
91
+ .notNull()
92
+ .references(() => billingCatalogRevisions.id, { onDelete: "cascade" }),
93
+ offerKey: text("offer_key").notNull(),
94
+ billingPriceEntryId: uuid("billing_price_entry_id")
95
+ .notNull()
96
+ .references(() => billingPriceEntries.id, { onDelete: "restrict" }),
97
+ },
98
+ (table) => ({
99
+ revisionKeyUnique: uniqueIndex("billing_catalog_revision_items_revision_key_uidx").on(
100
+ table.catalogRevisionId,
101
+ table.offerKey,
102
+ ),
103
+ revisionPriceUnique: uniqueIndex("billing_catalog_revision_items_revision_price_uidx").on(
104
+ table.catalogRevisionId,
105
+ table.billingPriceEntryId,
106
+ ),
107
+ }),
108
+ );
109
+
110
+ export const billingProviderCustomers = pgTable(
111
+ "billing_provider_customers",
112
+ {
113
+ id: uuid("id").primaryKey().defaultRandom(),
114
+ provider: text("provider").notNull(),
115
+ payerId: text("payer_id")
116
+ .notNull()
117
+ .references(() => user.id, { onDelete: "restrict" }),
118
+ payerEmail: text("payer_email").notNull().default(""),
119
+ providerCustomerId: text("provider_customer_id"),
120
+ idempotencyKey: text("idempotency_key").notNull(),
121
+ status: text("status").notNull().default("creating"),
122
+ lastError: text("last_error"),
123
+ ...timestamps,
124
+ },
125
+ (table) => ({
126
+ providerPayerUnique: uniqueIndex("billing_provider_customers_provider_payer_uidx").on(
127
+ table.provider,
128
+ table.payerId,
129
+ ),
130
+ providerCustomerUnique: uniqueIndex("billing_provider_customers_provider_customer_uidx")
131
+ .on(table.provider, table.providerCustomerId)
132
+ .where(sql`${table.providerCustomerId} IS NOT NULL`),
133
+ idempotencyUnique: uniqueIndex("billing_provider_customers_idempotency_uidx").on(
134
+ table.idempotencyKey,
135
+ ),
136
+ statusCheck: check(
137
+ "billing_provider_customers_status_check",
138
+ sql`${table.status} IN ('creating', 'active', 'conflicted')`,
139
+ ),
140
+ }),
141
+ );
142
+
143
+ export const billingCheckoutAttempts = pgTable(
144
+ "billing_checkout_attempts",
145
+ {
146
+ id: uuid("id").primaryKey().defaultRandom(),
147
+ attemptId: text("attempt_id").notNull().unique(),
148
+ billableEntityId: uuid("billable_entity_id")
149
+ .notNull()
150
+ .references(() => tenants.id, { onDelete: "restrict" }),
151
+ payerId: text("payer_id")
152
+ .notNull()
153
+ .references(() => user.id, { onDelete: "restrict" }),
154
+ payerEmail: text("payer_email").notNull().default(""),
155
+ returnUrl: text("return_url").notNull().default(""),
156
+ provider: text("provider").notNull(),
157
+ catalogRevision: integer("catalog_revision").notNull(),
158
+ offerKey: text("offer_key").notNull(),
159
+ requestedPlan: text("requested_plan").notNull(),
160
+ requestedInterval: text("requested_interval").notNull(),
161
+ billingPriceEntryId: uuid("billing_price_entry_id")
162
+ .notNull()
163
+ .references(() => billingPriceEntries.id, { onDelete: "restrict" }),
164
+ quotedAmountMinor: integer("quoted_amount_minor").notNull(),
165
+ quotedCurrency: text("quoted_currency").notNull(),
166
+ billingCustomerId: uuid("billing_customer_id").references(
167
+ () => billingProviderCustomers.id,
168
+ { onDelete: "restrict" },
169
+ ),
170
+ providerCheckoutSessionId: text("provider_checkout_session_id"),
171
+ checkoutUrlEncrypted: text("checkout_url_encrypted"),
172
+ idempotencyKey: text("idempotency_key").notNull(),
173
+ status: text("status").notNull().default("creating"),
174
+ expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
175
+ lastError: text("last_error"),
176
+ completedAt: timestamp("completed_at", { withTimezone: true }),
177
+ ...timestamps,
178
+ },
179
+ (table) => ({
180
+ providerSessionUnique: uniqueIndex("billing_checkout_attempts_provider_session_uidx")
181
+ .on(table.provider, table.providerCheckoutSessionId)
182
+ .where(sql`${table.providerCheckoutSessionId} IS NOT NULL`),
183
+ idempotencyUnique: uniqueIndex("billing_checkout_attempts_idempotency_uidx").on(
184
+ table.idempotencyKey,
185
+ ),
186
+ entityNonterminalUnique: uniqueIndex("billing_checkout_attempts_entity_nonterminal_uidx")
187
+ .on(table.billableEntityId)
188
+ .where(sql`${table.status} IN ('creating', 'open')`),
189
+ statusCheck: check(
190
+ "billing_checkout_attempts_status_check",
191
+ sql`${table.status} IN ('creating', 'open', 'completed', 'expired', 'abandoned', 'conflicted')`,
192
+ ),
193
+ amountCheck: check(
194
+ "billing_checkout_attempts_amount_check",
195
+ sql`${table.quotedAmountMinor} > 0`,
196
+ ),
197
+ planCheck: check(
198
+ "billing_checkout_attempts_plan_check",
199
+ sql`${table.requestedPlan} IN ('pro', 'business')`,
200
+ ),
201
+ intervalCheck: check(
202
+ "billing_checkout_attempts_interval_check",
203
+ sql`${table.requestedInterval} IN ('month', 'year')`,
204
+ ),
205
+ }),
206
+ );
207
+
208
+ export const billingSubscriptions = pgTable(
209
+ "billing_subscriptions",
210
+ {
211
+ id: uuid("id").primaryKey().defaultRandom(),
212
+ billableEntityId: uuid("billable_entity_id")
213
+ .notNull()
214
+ .references(() => tenants.id, { onDelete: "restrict" }),
215
+ billingCustomerId: uuid("billing_customer_id")
216
+ .notNull()
217
+ .references(() => billingProviderCustomers.id, { onDelete: "restrict" }),
218
+ payerId: text("payer_id")
219
+ .notNull()
220
+ .references(() => user.id, { onDelete: "restrict" }),
221
+ originCheckoutAttemptId: uuid("origin_checkout_attempt_id").references(
222
+ () => billingCheckoutAttempts.id,
223
+ { onDelete: "restrict" },
224
+ ),
225
+ provider: text("provider").notNull(),
226
+ providerSubscriptionId: text("provider_subscription_id").notNull(),
227
+ providerProductId: text("provider_product_id").notNull(),
228
+ billingPriceEntryId: uuid("billing_price_entry_id")
229
+ .notNull()
230
+ .references(() => billingPriceEntries.id, { onDelete: "restrict" }),
231
+ catalogRevision: integer("catalog_revision").notNull(),
232
+ offerKey: text("offer_key").notNull(),
233
+ plan: text("plan").notNull(),
234
+ billingInterval: text("billing_interval").notNull(),
235
+ status: text("status").notNull().default("pending"),
236
+ currentPeriodStartsAt: timestamp("current_period_starts_at", { withTimezone: true }),
237
+ currentPeriodEndsAt: timestamp("current_period_ends_at", { withTimezone: true }),
238
+ paidThroughAt: timestamp("paid_through_at", { withTimezone: true }),
239
+ trialEndsAt: timestamp("trial_ends_at", { withTimezone: true }),
240
+ cancelAtPeriodEnd: boolean("cancel_at_period_end").notNull().default(false),
241
+ isEntitlementSource: boolean("is_entitlement_source").notNull().default(false),
242
+ providerOccurredAt: timestamp("provider_occurred_at", { withTimezone: true }),
243
+ providerVersion: text("provider_version"),
244
+ lastObservedAt: timestamp("last_observed_at", { withTimezone: true }),
245
+ lastReconciledAt: timestamp("last_reconciled_at", { withTimezone: true }),
246
+ ...timestamps,
247
+ },
248
+ (table) => ({
249
+ providerSubscriptionUnique: uniqueIndex("billing_subscriptions_provider_subscription_uidx").on(
250
+ table.provider,
251
+ table.providerSubscriptionId,
252
+ ),
253
+ entitySourceUnique: uniqueIndex("billing_subscriptions_entity_source_uidx")
254
+ .on(table.billableEntityId)
255
+ .where(sql`${table.isEntitlementSource} = true`),
256
+ statusCheck: check(
257
+ "billing_subscriptions_status_check",
258
+ sql`${table.status} IN ('pending', 'trialing', 'active', 'past_due', 'cancelled', 'expired')`,
259
+ ),
260
+ planCheck: check("billing_subscriptions_plan_check", sql`${table.plan} IN ('pro', 'business')`),
261
+ intervalCheck: check(
262
+ "billing_subscriptions_interval_check",
263
+ sql`${table.billingInterval} IN ('month', 'year')`,
264
+ ),
265
+ }),
266
+ );
267
+
268
+ export const billingPlanChangeAttempts = pgTable(
269
+ "billing_plan_change_attempts",
270
+ {
271
+ id: uuid("id").primaryKey().defaultRandom(),
272
+ changeId: text("change_id").notNull().unique(),
273
+ billableEntityId: uuid("billable_entity_id")
274
+ .notNull()
275
+ .references(() => tenants.id, { onDelete: "restrict" }),
276
+ subscriptionId: uuid("subscription_id")
277
+ .notNull()
278
+ .references(() => billingSubscriptions.id, { onDelete: "restrict" }),
279
+ actorId: text("actor_id").notNull(),
280
+ payerId: text("payer_id")
281
+ .notNull()
282
+ .references(() => user.id, { onDelete: "restrict" }),
283
+ provider: text("provider").notNull(),
284
+ idempotencyKey: text("idempotency_key").notNull(),
285
+ currentCatalogRevision: integer("current_catalog_revision").notNull(),
286
+ currentBillingPriceEntryId: uuid("current_billing_price_entry_id")
287
+ .notNull()
288
+ .references(() => billingPriceEntries.id, { onDelete: "restrict" }),
289
+ currentPlan: text("current_plan").notNull(),
290
+ currentInterval: text("current_interval").notNull(),
291
+ targetCatalogRevision: integer("target_catalog_revision").notNull(),
292
+ targetBillingPriceEntryId: uuid("target_billing_price_entry_id")
293
+ .notNull()
294
+ .references(() => billingPriceEntries.id, { onDelete: "restrict" }),
295
+ targetPlan: text("target_plan").notNull(),
296
+ targetInterval: text("target_interval").notNull(),
297
+ targetOfferKey: text("target_offer_key").notNull(),
298
+ effectiveAt: text("effective_at").notNull(),
299
+ prorationMode: text("proration_mode").notNull(),
300
+ providerPaymentId: text("provider_payment_id"),
301
+ paymentUrlEncrypted: text("payment_url_encrypted"),
302
+ status: text("status").notNull().default("creating"),
303
+ lastError: text("last_error"),
304
+ completedAt: timestamp("completed_at", { withTimezone: true }),
305
+ ...timestamps,
306
+ },
307
+ (table) => ({
308
+ idempotencyUnique: uniqueIndex("billing_plan_change_attempts_idempotency_uidx").on(
309
+ table.idempotencyKey,
310
+ ),
311
+ entityNonterminalUnique: uniqueIndex("billing_plan_change_attempts_entity_nonterminal_uidx")
312
+ .on(table.billableEntityId)
313
+ .where(sql`${table.status} IN ('creating', 'pending')`),
314
+ statusCheck: check(
315
+ "billing_plan_change_attempts_status_check",
316
+ sql`${table.status} IN ('creating', 'pending', 'succeeded', 'failed', 'conflicted')`,
317
+ ),
318
+ effectiveAtCheck: check(
319
+ "billing_plan_change_attempts_effective_at_check",
320
+ sql`${table.effectiveAt} IN ('immediately', 'next_billing_date')`,
321
+ ),
322
+ prorationModeCheck: check(
323
+ "billing_plan_change_attempts_proration_mode_check",
324
+ sql`${table.prorationMode} IN ('prorated_immediately', 'do_not_bill')`,
325
+ ),
326
+ currentPlanCheck: check(
327
+ "billing_plan_change_attempts_current_plan_check",
328
+ sql`${table.currentPlan} IN ('pro', 'business')`,
329
+ ),
330
+ targetPlanCheck: check(
331
+ "billing_plan_change_attempts_target_plan_check",
332
+ sql`${table.targetPlan} IN ('pro', 'business')`,
333
+ ),
334
+ }),
335
+ );
336
+
337
+ export const billingPlanStates = pgTable(
338
+ "billing_plan_states",
339
+ {
340
+ id: uuid("id").primaryKey().defaultRandom(),
341
+ billableEntityId: uuid("billable_entity_id")
342
+ .notNull()
343
+ .unique()
344
+ .references(() => tenants.id, { onDelete: "restrict" }),
345
+ activeSubscriptionId: uuid("active_subscription_id").references(
346
+ () => billingSubscriptions.id,
347
+ { onDelete: "restrict" },
348
+ ),
349
+ projectionVersion: integer("projection_version").notNull().default(0),
350
+ ...timestamps,
351
+ },
352
+ );
353
+
354
+ export const billingWebhookEvents = pgTable(
355
+ "billing_webhook_events",
356
+ {
357
+ id: uuid("id").primaryKey().defaultRandom(),
358
+ provider: text("provider").notNull(),
359
+ providerEventId: text("provider_event_id").notNull(),
360
+ eventType: text("event_type").notNull(),
361
+ occurredAt: timestamp("occurred_at", { withTimezone: true }).notNull(),
362
+ subscriptionId: text("subscription_id"),
363
+ checkoutAttemptId: text("checkout_attempt_id"),
364
+ payloadEncrypted: text("payload_encrypted"),
365
+ payloadKeyVersion: text("payload_key_version"),
366
+ verifiedKeyVersion: text("verified_key_version"),
367
+ status: text("status").notNull().default("pending"),
368
+ processingAttempts: integer("processing_attempts").notNull().default(0),
369
+ lastError: text("last_error"),
370
+ availableAt: timestamp("available_at", { withTimezone: true }).notNull().defaultNow(),
371
+ lockedAt: timestamp("locked_at", { withTimezone: true }),
372
+ leaseExpiresAt: timestamp("lease_expires_at", { withTimezone: true }),
373
+ workerId: text("worker_id"),
374
+ receivedAt: timestamp("received_at", { withTimezone: true }).notNull().defaultNow(),
375
+ processedAt: timestamp("processed_at", { withTimezone: true }),
376
+ },
377
+ (table) => ({
378
+ providerEventUnique: uniqueIndex("billing_webhook_events_provider_event_uidx").on(
379
+ table.provider,
380
+ table.providerEventId,
381
+ ),
382
+ queueIdx: index("billing_webhook_events_queue_idx").on(table.status, table.availableAt),
383
+ statusCheck: check(
384
+ "billing_webhook_events_status_check",
385
+ sql`${table.status} IN ('pending', 'processing', 'processed', 'ignored', 'quarantined', 'failed')`,
386
+ ),
387
+ }),
388
+ );
389
+
390
+ export const billingReconciliationJobs = pgTable(
391
+ "billing_reconciliation_jobs",
392
+ {
393
+ id: uuid("id").primaryKey().defaultRandom(),
394
+ provider: text("provider").notNull(),
395
+ checkoutAttemptId: uuid("checkout_attempt_id").references(
396
+ () => billingCheckoutAttempts.id,
397
+ { onDelete: "restrict" },
398
+ ),
399
+ planChangeAttemptId: uuid("plan_change_attempt_id").references(
400
+ () => billingPlanChangeAttempts.id,
401
+ { onDelete: "restrict" },
402
+ ),
403
+ subscriptionId: uuid("subscription_id").references(
404
+ () => billingSubscriptions.id,
405
+ { onDelete: "restrict" },
406
+ ),
407
+ providerCustomerId: uuid("provider_customer_id").references(
408
+ () => billingProviderCustomers.id,
409
+ { onDelete: "restrict" },
410
+ ),
411
+ operation: text("operation").notNull().default("reconcile"),
412
+ status: text("status").notNull().default("pending"),
413
+ attemptCount: integer("attempt_count").notNull().default(0),
414
+ availableAt: timestamp("available_at", { withTimezone: true }).notNull().defaultNow(),
415
+ lockedAt: timestamp("locked_at", { withTimezone: true }),
416
+ leaseExpiresAt: timestamp("lease_expires_at", { withTimezone: true }),
417
+ workerId: text("worker_id"),
418
+ lastError: text("last_error"),
419
+ ...timestamps,
420
+ },
421
+ (table) => ({
422
+ exactlyOneSubject: check(
423
+ "billing_reconciliation_jobs_exactly_one_subject",
424
+ sql`((CASE WHEN ${table.checkoutAttemptId} IS NOT NULL THEN 1 ELSE 0 END) + (CASE WHEN ${table.planChangeAttemptId} IS NOT NULL THEN 1 ELSE 0 END) + (CASE WHEN ${table.subscriptionId} IS NOT NULL THEN 1 ELSE 0 END) + (CASE WHEN ${table.providerCustomerId} IS NOT NULL THEN 1 ELSE 0 END)) = 1`,
425
+ ),
426
+ liveCheckoutUnique: uniqueIndex("billing_reconciliation_jobs_live_checkout_uidx")
427
+ .on(table.checkoutAttemptId)
428
+ .where(sql`${table.checkoutAttemptId} IS NOT NULL AND ${table.status} IN ('pending', 'processing', 'failed')`),
429
+ livePlanChangeUnique: uniqueIndex("billing_reconciliation_jobs_live_plan_change_uidx")
430
+ .on(table.planChangeAttemptId)
431
+ .where(sql`${table.planChangeAttemptId} IS NOT NULL AND ${table.status} IN ('pending', 'processing', 'failed')`),
432
+ liveSubscriptionUnique: uniqueIndex("billing_reconciliation_jobs_live_subscription_uidx")
433
+ .on(table.subscriptionId)
434
+ .where(sql`${table.subscriptionId} IS NOT NULL AND ${table.status} IN ('pending', 'processing', 'failed')`),
435
+ liveCustomerUnique: uniqueIndex("billing_reconciliation_jobs_live_customer_uidx")
436
+ .on(table.providerCustomerId)
437
+ .where(sql`${table.providerCustomerId} IS NOT NULL AND ${table.status} IN ('pending', 'processing', 'failed')`),
438
+ statusCheck: check(
439
+ "billing_reconciliation_jobs_status_check",
440
+ sql`${table.status} IN ('pending', 'processing', 'failed', 'completed', 'quarantined')`,
441
+ ),
442
+ operationCheck: check(
443
+ "billing_reconciliation_jobs_operation_check",
444
+ sql`${table.operation} = 'reconcile' OR (${table.operation} = 'cancellation' AND ${table.subscriptionId} IS NOT NULL)`,
445
+ ),
446
+ }),
447
+ );
@@ -0,0 +1,3 @@
1
+ export * from "./auth.generated.js";
2
+ export * from "./notes.js";
3
+ export * from "./tenants.js";
@@ -0,0 +1,31 @@
1
+ import { pgTable, text, timestamp, uuid } from "drizzle-orm/pg-core";
2
+ import { user } from "./auth.generated.js";
3
+ import { tenants } from "./tenants.js";
4
+
5
+ export const notes = pgTable("notes", {
6
+ id: uuid("id").primaryKey(),
7
+ publicId: text("public_id").notNull().unique(),
8
+ tenantId: uuid("tenant_id")
9
+ .notNull()
10
+ .references(() => tenants.id, { onDelete: "cascade" }),
11
+ title: text("title").notNull(),
12
+ body: text("body").notNull(),
13
+ createdBy: text("created_by")
14
+ .notNull()
15
+ .references(() => user.id),
16
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull(),
17
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull(),
18
+ });
19
+
20
+ export const auditEvents = pgTable("audit_events", {
21
+ id: uuid("id").primaryKey(),
22
+ tenantId: uuid("tenant_id").references(() => tenants.id, {
23
+ onDelete: "cascade",
24
+ }),
25
+ actorId: text("actor_id").notNull(),
26
+ action: text("action").notNull(),
27
+ resourceType: text("resource_type").notNull(),
28
+ resourceId: text("resource_id").notNull(),
29
+ requestId: text("request_id").notNull(),
30
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull(),
31
+ });
@@ -0,0 +1,83 @@
1
+ import {
2
+ boolean,
3
+ pgTable,
4
+ text,
5
+ timestamp,
6
+ uniqueIndex,
7
+ uuid,
8
+ } from "drizzle-orm/pg-core";
9
+ import { user } from "./auth.generated.js";
10
+
11
+ export const tenants = pgTable("tenants", {
12
+ id: uuid("id").primaryKey(),
13
+ publicId: text("public_id").notNull().unique(),
14
+ name: text("name").notNull(),
15
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull(),
16
+ });
17
+
18
+ export const memberships = pgTable(
19
+ "memberships",
20
+ {
21
+ id: uuid("id").primaryKey(),
22
+ tenantId: uuid("tenant_id")
23
+ .notNull()
24
+ .references(() => tenants.id, { onDelete: "cascade" }),
25
+ userId: text("user_id")
26
+ .notNull()
27
+ .references(() => user.id, { onDelete: "cascade" }),
28
+ role: text("role").notNull(),
29
+ isOwner: boolean("is_owner").notNull().default(false),
30
+ permissions: text("permissions").notNull(),
31
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull(),
32
+ },
33
+ (table) => ({
34
+ tenantUser: uniqueIndex("memberships_tenant_user_uidx").on(
35
+ table.tenantId,
36
+ table.userId,
37
+ ),
38
+ }),
39
+ );
40
+
41
+ export const selectedTenants = pgTable("selected_tenants", {
42
+ userId: text("user_id")
43
+ .primaryKey()
44
+ .references(() => user.id, { onDelete: "cascade" }),
45
+ tenantId: uuid("tenant_id")
46
+ .notNull()
47
+ .references(() => tenants.id, { onDelete: "cascade" }),
48
+ });
49
+
50
+ export const invitations = pgTable("invitations", {
51
+ id: uuid("id").primaryKey(),
52
+ tenantId: uuid("tenant_id")
53
+ .notNull()
54
+ .references(() => tenants.id, { onDelete: "cascade" }),
55
+ email: text("email").notNull(),
56
+ role: text("role").notNull(),
57
+ permissions: text("permissions").notNull(),
58
+ tokenDigest: text("token_digest").notNull(),
59
+ inviterId: text("inviter_id")
60
+ .notNull()
61
+ .references(() => user.id),
62
+ expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
63
+ acceptedAt: timestamp("accepted_at", { withTimezone: true }),
64
+ revokedAt: timestamp("revoked_at", { withTimezone: true }),
65
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull(),
66
+ });
67
+
68
+ export const apiKeys = pgTable("api_keys", {
69
+ id: uuid("id").primaryKey(),
70
+ publicId: text("public_id").notNull().unique(),
71
+ tenantId: uuid("tenant_id")
72
+ .notNull()
73
+ .references(() => tenants.id, { onDelete: "cascade" }),
74
+ userId: text("user_id")
75
+ .notNull()
76
+ .references(() => user.id, { onDelete: "cascade" }),
77
+ digest: text("digest").notNull(),
78
+ permissions: text("permissions").notNull(),
79
+ expiresAt: timestamp("expires_at", { withTimezone: true }),
80
+ revokedAt: timestamp("revoked_at", { withTimezone: true }),
81
+ lastUsedAt: timestamp("last_used_at", { withTimezone: true }),
82
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull(),
83
+ });
@@ -0,0 +1,12 @@
1
+ import type { Observability } from "@codelitdev/observability";
2
+ import type { Clock } from "@codelitdev/platform";
3
+ import type { AuthRuntime } from "./auth/authenticate.js";
4
+ import type { BillingBundle } from "./billing.js";
5
+
6
+ export type DispatchDeps = AuthRuntime & {
7
+ clock: Clock;
8
+ billing: BillingBundle;
9
+ serviceName: string;
10
+ databaseReady: boolean;
11
+ observability?: Observability;
12
+ };