@qazuor/qzpay-drizzle 1.5.0 → 1.7.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.
package/dist/index.cjs CHANGED
@@ -130,13 +130,13 @@ function firstOrThrow(results, entityType, id) {
130
130
  }
131
131
  async function updateWithVersionHelper(db, table, id, expectedVersion, updateData, options) {
132
132
  const { entityType, entityId, includeSoftDeleted = false, transform } = options;
133
- const { and: and18, eq: eq17, isNull: isNull13 } = await import('drizzle-orm');
133
+ const { and: and19, eq: eq18, isNull: isNull13 } = await import('drizzle-orm');
134
134
  const { generateVersion: generateVersion2 } = await Promise.resolve().then(() => (init_optimistic_locking(), optimistic_locking_exports));
135
- const conditions = [eq17(table.id, id), eq17(table.version, expectedVersion)];
135
+ const conditions = [eq18(table.id, id), eq18(table.version, expectedVersion)];
136
136
  if (!includeSoftDeleted && "deletedAt" in table) {
137
137
  conditions.push(isNull13(table.deletedAt));
138
138
  }
139
- const whereClause = and18(...conditions);
139
+ const whereClause = and19(...conditions);
140
140
  if (!whereClause) {
141
141
  throw new Error("Failed to build WHERE clause for version update");
142
142
  }
@@ -150,7 +150,7 @@ async function updateWithVersionHelper(db, table, id, expectedVersion, updateDat
150
150
  result = await db.update(table).set(dataWithVersion).where(whereClause).returning();
151
151
  } catch (_error) {
152
152
  try {
153
- const existsQuery = await db.select().from(table).where(includeSoftDeleted ? eq17(table.id, id) : and18(eq17(table.id, id), isNull13(table.deletedAt))).limit(1);
153
+ const existsQuery = await db.select().from(table).where(includeSoftDeleted ? eq18(table.id, id) : and19(eq18(table.id, id), isNull13(table.deletedAt))).limit(1);
154
154
  if (existsQuery.length > 0) {
155
155
  throw new exports.QZPayOptimisticLockError(entityType, entityId);
156
156
  }
@@ -159,7 +159,7 @@ async function updateWithVersionHelper(db, table, id, expectedVersion, updateDat
159
159
  throw new exports.QZPayEntityNotFoundError(entityType, entityId);
160
160
  }
161
161
  if (result.length === 0) {
162
- const existsQuery = await db.select().from(table).where(includeSoftDeleted ? eq17(table.id, id) : and18(eq17(table.id, id), isNull13(table.deletedAt))).limit(1);
162
+ const existsQuery = await db.select().from(table).where(includeSoftDeleted ? eq18(table.id, id) : and19(eq18(table.id, id), isNull13(table.deletedAt))).limit(1);
163
163
  if (existsQuery.length > 0) {
164
164
  throw new exports.QZPayOptimisticLockError(entityType, entityId);
165
165
  }
@@ -319,6 +319,69 @@ function mapCoreSubscriptionAddonUpdateToDrizzle(update) {
319
319
  return result;
320
320
  }
321
321
 
322
+ // src/mappers/checkout.mapper.ts
323
+ function mapDrizzleCheckoutToCore(drizzle3) {
324
+ return {
325
+ id: drizzle3.id,
326
+ customerId: drizzle3.customerId ?? null,
327
+ customerEmail: drizzle3.customerEmail ?? null,
328
+ mode: drizzle3.mode,
329
+ status: drizzle3.status,
330
+ currency: drizzle3.currency,
331
+ lineItems: drizzle3.lineItems ?? [],
332
+ successUrl: drizzle3.successUrl,
333
+ cancelUrl: drizzle3.cancelUrl,
334
+ expiresAt: drizzle3.expiresAt,
335
+ paymentId: drizzle3.paymentId ?? null,
336
+ subscriptionId: drizzle3.subscriptionId ?? null,
337
+ providerSessionIds: drizzle3.providerSessionIds ?? {},
338
+ metadata: drizzle3.metadata ?? {},
339
+ livemode: drizzle3.livemode,
340
+ createdAt: drizzle3.createdAt,
341
+ completedAt: drizzle3.completedAt ?? null
342
+ };
343
+ }
344
+ function mapCoreCheckoutToDrizzle(session) {
345
+ return {
346
+ id: session.id,
347
+ customerId: session.customerId ?? null,
348
+ customerEmail: session.customerEmail ?? null,
349
+ mode: session.mode,
350
+ status: session.status,
351
+ currency: session.currency,
352
+ lineItems: session.lineItems,
353
+ successUrl: session.successUrl,
354
+ cancelUrl: session.cancelUrl,
355
+ expiresAt: session.expiresAt,
356
+ paymentId: session.paymentId ?? null,
357
+ subscriptionId: session.subscriptionId ?? null,
358
+ providerSessionIds: session.providerSessionIds,
359
+ metadata: session.metadata,
360
+ livemode: session.livemode,
361
+ createdAt: session.createdAt,
362
+ completedAt: session.completedAt ?? null
363
+ };
364
+ }
365
+ function mapCoreCheckoutUpdateToDrizzle(input) {
366
+ const update = {};
367
+ if (input.customerId !== void 0) update.customerId = input.customerId;
368
+ if (input.customerEmail !== void 0) update.customerEmail = input.customerEmail;
369
+ if (input.mode !== void 0) update.mode = input.mode;
370
+ if (input.status !== void 0) update.status = input.status;
371
+ if (input.currency !== void 0) update.currency = input.currency;
372
+ if (input.lineItems !== void 0) update.lineItems = input.lineItems;
373
+ if (input.successUrl !== void 0) update.successUrl = input.successUrl;
374
+ if (input.cancelUrl !== void 0) update.cancelUrl = input.cancelUrl;
375
+ if (input.expiresAt !== void 0) update.expiresAt = input.expiresAt;
376
+ if (input.paymentId !== void 0) update.paymentId = input.paymentId;
377
+ if (input.subscriptionId !== void 0) update.subscriptionId = input.subscriptionId;
378
+ if (input.providerSessionIds !== void 0) update.providerSessionIds = input.providerSessionIds;
379
+ if (input.metadata !== void 0) update.metadata = input.metadata;
380
+ if (input.livemode !== void 0) update.livemode = input.livemode;
381
+ if (input.completedAt !== void 0) update.completedAt = input.completedAt;
382
+ return update;
383
+ }
384
+
322
385
  // src/mappers/customer.mapper.ts
323
386
  function mapDrizzleCustomerToCore(drizzle3) {
324
387
  const providerCustomerIds = {};
@@ -1071,6 +1134,7 @@ function mapDrizzleSubscriptionToCore(drizzle3) {
1071
1134
  cancelAtPeriodEnd: drizzle3.cancelAtPeriodEnd ?? false,
1072
1135
  providerSubscriptionIds,
1073
1136
  metadata: drizzle3.metadata ?? {},
1137
+ scheduledPlanChange: drizzle3.scheduledPlanChange ?? null,
1074
1138
  livemode: drizzle3.livemode,
1075
1139
  createdAt: drizzle3.createdAt,
1076
1140
  updatedAt: drizzle3.updatedAt,
@@ -1141,6 +1205,9 @@ function mapCoreSubscriptionUpdateToDrizzle(input) {
1141
1205
  update.mpSubscriptionId = mpId;
1142
1206
  }
1143
1207
  }
1208
+ if (input.scheduledPlanChange !== void 0) {
1209
+ update.scheduledPlanChange = input.scheduledPlanChange;
1210
+ }
1144
1211
  return update;
1145
1212
  }
1146
1213
 
@@ -1347,6 +1414,15 @@ var billingSubscriptions = pgCore.pgTable(
1347
1414
  nextRetryAt: pgCore.timestamp("next_retry_at", { withTimezone: true }),
1348
1415
  stripeSubscriptionId: pgCore.varchar("stripe_subscription_id", { length: 255 }),
1349
1416
  mpSubscriptionId: pgCore.varchar("mp_subscription_id", { length: 255 }),
1417
+ /**
1418
+ * Plan change scheduled to apply at a future point in time
1419
+ * (typically `current_period_end`). Stored as JSONB so the
1420
+ * shape can evolve without a migration; conforms to
1421
+ * `QZPayScheduledPlanChange` in qzpay-core. Null when no
1422
+ * change is pending. The application-level scheduler (cron)
1423
+ * owns the lifecycle — qzpay-drizzle provides storage only.
1424
+ */
1425
+ scheduledPlanChange: pgCore.jsonb("scheduled_plan_change"),
1350
1426
  livemode: pgCore.boolean("livemode").notNull().default(true),
1351
1427
  metadata: pgCore.jsonb("metadata").default({}),
1352
1428
  version: pgCore.uuid("version").notNull().defaultRandom(),
@@ -1377,7 +1453,12 @@ var billingSubscriptions = pgCore.pgTable(
1377
1453
  // Supports findTrialsEndingSoon() query
1378
1454
  lifecycleTrialIdx: pgCore.index("idx_subscriptions_lifecycle_trial").on(table.status, table.trialEnd),
1379
1455
  // Supports findScheduledForCancellation() query
1380
- lifecycleCancelIdx: pgCore.index("idx_subscriptions_lifecycle_cancel").on(table.cancelAtPeriodEnd, table.status, table.currentPeriodEnd)
1456
+ lifecycleCancelIdx: pgCore.index("idx_subscriptions_lifecycle_cancel").on(table.cancelAtPeriodEnd, table.status, table.currentPeriodEnd),
1457
+ // Partial index for the scheduled-plan-change cron query —
1458
+ // only rows with a pending scheduled change need to be
1459
+ // scanned, so a partial index keeps the per-tick cost O(k)
1460
+ // where k = #pending changes (NOT O(n) full table scan).
1461
+ lifecyclePendingPlanChangeIdx: pgCore.index("idx_subscriptions_pending_plan_change").on(table.scheduledPlanChange).where(drizzleOrm.sql`scheduled_plan_change IS NOT NULL AND (scheduled_plan_change->>'status') = 'pending'`)
1381
1462
  })
1382
1463
  );
1383
1464
  var billingSubscriptionInsertSchema = drizzleZod.createInsertSchema(billingSubscriptions);
@@ -1466,6 +1547,93 @@ var billingAuditLogs = pgCore.pgTable(
1466
1547
  );
1467
1548
  var billingAuditLogInsertSchema = drizzleZod.createInsertSchema(billingAuditLogs);
1468
1549
  var billingAuditLogSelectSchema = drizzleZod.createSelectSchema(billingAuditLogs);
1550
+ var billingPayments = pgCore.pgTable(
1551
+ "billing_payments",
1552
+ {
1553
+ id: pgCore.uuid("id").primaryKey().defaultRandom(),
1554
+ customerId: pgCore.uuid("customer_id").notNull().references(() => billingCustomers.id, { onDelete: "restrict" }),
1555
+ subscriptionId: pgCore.uuid("subscription_id").references(() => billingSubscriptions.id),
1556
+ invoiceId: pgCore.uuid("invoice_id"),
1557
+ amount: pgCore.integer("amount").notNull(),
1558
+ currency: pgCore.varchar("currency", { length: 3 }).notNull(),
1559
+ baseAmount: pgCore.integer("base_amount"),
1560
+ baseCurrency: pgCore.varchar("base_currency", { length: 3 }),
1561
+ exchangeRate: pgCore.numeric("exchange_rate", { precision: 18, scale: 8 }),
1562
+ status: pgCore.varchar("status", { length: 50 }).notNull(),
1563
+ provider: pgCore.varchar("provider", { length: 50 }).notNull(),
1564
+ providerPaymentIds: pgCore.jsonb("provider_payment_ids").default({}),
1565
+ paymentMethodId: pgCore.uuid("payment_method_id"),
1566
+ refundedAmount: pgCore.integer("refunded_amount").default(0),
1567
+ failureCode: pgCore.varchar("failure_code", { length: 100 }),
1568
+ failureMessage: pgCore.text("failure_message"),
1569
+ idempotencyKey: pgCore.varchar("idempotency_key", { length: 255 }),
1570
+ livemode: pgCore.boolean("livemode").notNull().default(true),
1571
+ metadata: pgCore.jsonb("metadata").default({}),
1572
+ version: pgCore.uuid("version").notNull().defaultRandom(),
1573
+ createdAt: pgCore.timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1574
+ updatedAt: pgCore.timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
1575
+ deletedAt: pgCore.timestamp("deleted_at", { withTimezone: true })
1576
+ },
1577
+ (table) => ({
1578
+ customerIdx: pgCore.index("idx_payments_customer").on(table.customerId),
1579
+ subscriptionIdx: pgCore.index("idx_payments_subscription").on(table.subscriptionId),
1580
+ statusIdx: pgCore.index("idx_payments_status").on(table.status),
1581
+ idempotencyIdx: pgCore.index("idx_payments_idempotency").on(table.idempotencyKey)
1582
+ })
1583
+ );
1584
+ var billingRefunds = pgCore.pgTable(
1585
+ "billing_refunds",
1586
+ {
1587
+ id: pgCore.uuid("id").primaryKey().defaultRandom(),
1588
+ paymentId: pgCore.uuid("payment_id").notNull().references(() => billingPayments.id, { onDelete: "restrict" }),
1589
+ amount: pgCore.integer("amount").notNull(),
1590
+ currency: pgCore.varchar("currency", { length: 3 }).notNull(),
1591
+ status: pgCore.varchar("status", { length: 50 }).notNull(),
1592
+ reason: pgCore.varchar("reason", { length: 100 }),
1593
+ providerRefundId: pgCore.varchar("provider_refund_id", { length: 255 }),
1594
+ livemode: pgCore.boolean("livemode").notNull().default(true),
1595
+ metadata: pgCore.jsonb("metadata").default({}),
1596
+ createdAt: pgCore.timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
1597
+ },
1598
+ (table) => ({
1599
+ paymentIdx: pgCore.index("idx_refunds_payment").on(table.paymentId),
1600
+ providerIdIdx: pgCore.index("idx_refunds_provider_id").on(table.providerRefundId)
1601
+ })
1602
+ );
1603
+ var billingPaymentInsertSchema = drizzleZod.createInsertSchema(billingPayments);
1604
+ var billingPaymentSelectSchema = drizzleZod.createSelectSchema(billingPayments);
1605
+
1606
+ // src/schema/checkouts.schema.ts
1607
+ var billingCheckouts = pgCore.pgTable(
1608
+ "billing_checkouts",
1609
+ {
1610
+ id: pgCore.uuid("id").primaryKey().defaultRandom(),
1611
+ customerId: pgCore.uuid("customer_id").references(() => billingCustomers.id, { onDelete: "set null" }),
1612
+ customerEmail: pgCore.varchar("customer_email", { length: 255 }),
1613
+ mode: pgCore.varchar("mode", { length: 50 }).notNull(),
1614
+ status: pgCore.varchar("status", { length: 50 }).notNull(),
1615
+ currency: pgCore.varchar("currency", { length: 10 }).notNull(),
1616
+ lineItems: pgCore.jsonb("line_items").notNull().default([]),
1617
+ successUrl: pgCore.text("success_url").notNull(),
1618
+ cancelUrl: pgCore.text("cancel_url").notNull(),
1619
+ expiresAt: pgCore.timestamp("expires_at", { withTimezone: true }).notNull(),
1620
+ paymentId: pgCore.uuid("payment_id").references(() => billingPayments.id),
1621
+ subscriptionId: pgCore.uuid("subscription_id").references(() => billingSubscriptions.id),
1622
+ providerSessionIds: pgCore.jsonb("provider_session_ids").notNull().default({}),
1623
+ metadata: pgCore.jsonb("metadata").default({}),
1624
+ livemode: pgCore.boolean("livemode").notNull().default(true),
1625
+ createdAt: pgCore.timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1626
+ completedAt: pgCore.timestamp("completed_at", { withTimezone: true })
1627
+ },
1628
+ (table) => ({
1629
+ customerIdx: pgCore.index("idx_checkouts_customer").on(table.customerId),
1630
+ statusIdx: pgCore.index("idx_checkouts_status").on(table.status),
1631
+ customerStatusIdx: pgCore.index("idx_checkouts_customer_status").on(table.customerId, table.status),
1632
+ expirationIdx: pgCore.index("idx_checkouts_expiration").on(table.expiresAt)
1633
+ })
1634
+ );
1635
+ var billingCheckoutInsertSchema = drizzleZod.createInsertSchema(billingCheckouts);
1636
+ var billingCheckoutSelectSchema = drizzleZod.createSelectSchema(billingCheckouts);
1469
1637
  var billingEntitlements = pgCore.pgTable(
1470
1638
  "billing_entitlements",
1471
1639
  {
@@ -1669,61 +1837,6 @@ var billingPaymentMethods = pgCore.pgTable(
1669
1837
  );
1670
1838
  var billingPaymentMethodInsertSchema = drizzleZod.createInsertSchema(billingPaymentMethods);
1671
1839
  var billingPaymentMethodSelectSchema = drizzleZod.createSelectSchema(billingPaymentMethods);
1672
- var billingPayments = pgCore.pgTable(
1673
- "billing_payments",
1674
- {
1675
- id: pgCore.uuid("id").primaryKey().defaultRandom(),
1676
- customerId: pgCore.uuid("customer_id").notNull().references(() => billingCustomers.id, { onDelete: "restrict" }),
1677
- subscriptionId: pgCore.uuid("subscription_id").references(() => billingSubscriptions.id),
1678
- invoiceId: pgCore.uuid("invoice_id"),
1679
- amount: pgCore.integer("amount").notNull(),
1680
- currency: pgCore.varchar("currency", { length: 3 }).notNull(),
1681
- baseAmount: pgCore.integer("base_amount"),
1682
- baseCurrency: pgCore.varchar("base_currency", { length: 3 }),
1683
- exchangeRate: pgCore.numeric("exchange_rate", { precision: 18, scale: 8 }),
1684
- status: pgCore.varchar("status", { length: 50 }).notNull(),
1685
- provider: pgCore.varchar("provider", { length: 50 }).notNull(),
1686
- providerPaymentIds: pgCore.jsonb("provider_payment_ids").default({}),
1687
- paymentMethodId: pgCore.uuid("payment_method_id"),
1688
- refundedAmount: pgCore.integer("refunded_amount").default(0),
1689
- failureCode: pgCore.varchar("failure_code", { length: 100 }),
1690
- failureMessage: pgCore.text("failure_message"),
1691
- idempotencyKey: pgCore.varchar("idempotency_key", { length: 255 }),
1692
- livemode: pgCore.boolean("livemode").notNull().default(true),
1693
- metadata: pgCore.jsonb("metadata").default({}),
1694
- version: pgCore.uuid("version").notNull().defaultRandom(),
1695
- createdAt: pgCore.timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1696
- updatedAt: pgCore.timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
1697
- deletedAt: pgCore.timestamp("deleted_at", { withTimezone: true })
1698
- },
1699
- (table) => ({
1700
- customerIdx: pgCore.index("idx_payments_customer").on(table.customerId),
1701
- subscriptionIdx: pgCore.index("idx_payments_subscription").on(table.subscriptionId),
1702
- statusIdx: pgCore.index("idx_payments_status").on(table.status),
1703
- idempotencyIdx: pgCore.index("idx_payments_idempotency").on(table.idempotencyKey)
1704
- })
1705
- );
1706
- var billingRefunds = pgCore.pgTable(
1707
- "billing_refunds",
1708
- {
1709
- id: pgCore.uuid("id").primaryKey().defaultRandom(),
1710
- paymentId: pgCore.uuid("payment_id").notNull().references(() => billingPayments.id, { onDelete: "restrict" }),
1711
- amount: pgCore.integer("amount").notNull(),
1712
- currency: pgCore.varchar("currency", { length: 3 }).notNull(),
1713
- status: pgCore.varchar("status", { length: 50 }).notNull(),
1714
- reason: pgCore.varchar("reason", { length: 100 }),
1715
- providerRefundId: pgCore.varchar("provider_refund_id", { length: 255 }),
1716
- livemode: pgCore.boolean("livemode").notNull().default(true),
1717
- metadata: pgCore.jsonb("metadata").default({}),
1718
- createdAt: pgCore.timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
1719
- },
1720
- (table) => ({
1721
- paymentIdx: pgCore.index("idx_refunds_payment").on(table.paymentId),
1722
- providerIdIdx: pgCore.index("idx_refunds_provider_id").on(table.providerRefundId)
1723
- })
1724
- );
1725
- var billingPaymentInsertSchema = drizzleZod.createInsertSchema(billingPayments);
1726
- var billingPaymentSelectSchema = drizzleZod.createSelectSchema(billingPayments);
1727
1840
  var billingPlans = pgCore.pgTable(
1728
1841
  "billing_plans",
1729
1842
  {
@@ -2050,6 +2163,7 @@ var qzpaySchema = {
2050
2163
  billingAddons,
2051
2164
  billingSubscriptionAddons,
2052
2165
  billingAuditLogs,
2166
+ billingCheckouts,
2053
2167
  billingCustomers,
2054
2168
  billingCustomerEntitlements,
2055
2169
  billingEntitlements,
@@ -2548,6 +2662,72 @@ var QZPayAuditLogsRepository = class {
2548
2662
  // src/repositories/index.ts
2549
2663
  init_base_repository();
2550
2664
  init_base_repository();
2665
+ var QZPayCheckoutsRepository = class {
2666
+ constructor(db) {
2667
+ this.db = db;
2668
+ }
2669
+ /**
2670
+ * Find a checkout by ID.
2671
+ */
2672
+ async findById(id) {
2673
+ const result = await this.db.select().from(billingCheckouts).where(drizzleOrm.eq(billingCheckouts.id, id)).limit(1);
2674
+ return firstOrNull(result);
2675
+ }
2676
+ /**
2677
+ * Insert a new checkout.
2678
+ */
2679
+ async create(input) {
2680
+ const result = await this.db.insert(billingCheckouts).values(input).returning();
2681
+ return firstOrThrow(result, "Checkout", "new");
2682
+ }
2683
+ /**
2684
+ * Partial update.
2685
+ */
2686
+ async update(id, input) {
2687
+ const result = await this.db.update(billingCheckouts).set(input).where(drizzleOrm.eq(billingCheckouts.id, id)).returning();
2688
+ return firstOrThrow(result, "Checkout", id);
2689
+ }
2690
+ /**
2691
+ * List all checkouts for a customer, newest first.
2692
+ */
2693
+ async findByCustomerId(customerId, options = {}) {
2694
+ const { limit = 100, offset = 0, status } = options;
2695
+ const conditions = [drizzleOrm.eq(billingCheckouts.customerId, customerId)];
2696
+ if (status && status.length > 0) {
2697
+ conditions.push(drizzleOrm.inArray(billingCheckouts.status, status));
2698
+ }
2699
+ const countResult = await this.db.select({ count: drizzleOrm.count() }).from(billingCheckouts).where(drizzleOrm.and(...conditions));
2700
+ const total = countResult[0]?.count ?? 0;
2701
+ const data = await this.db.select().from(billingCheckouts).where(drizzleOrm.and(...conditions)).orderBy(drizzleOrm.sql`${billingCheckouts.createdAt} DESC`).limit(limit).offset(offset);
2702
+ return { data, total };
2703
+ }
2704
+ /**
2705
+ * Paginated search across all checkouts.
2706
+ */
2707
+ async search(options) {
2708
+ const { customerId, status, livemode, limit = 100, offset = 0 } = options;
2709
+ const conditions = [];
2710
+ if (customerId) {
2711
+ conditions.push(drizzleOrm.eq(billingCheckouts.customerId, customerId));
2712
+ }
2713
+ if (status) {
2714
+ if (Array.isArray(status)) {
2715
+ conditions.push(drizzleOrm.inArray(billingCheckouts.status, status));
2716
+ } else {
2717
+ conditions.push(drizzleOrm.eq(billingCheckouts.status, status));
2718
+ }
2719
+ }
2720
+ if (livemode !== void 0) {
2721
+ conditions.push(drizzleOrm.eq(billingCheckouts.livemode, livemode));
2722
+ }
2723
+ const where = conditions.length > 0 ? drizzleOrm.and(...conditions) : void 0;
2724
+ const countResult = await this.db.select({ count: drizzleOrm.count() }).from(billingCheckouts).where(where);
2725
+ const total = countResult[0]?.count ?? 0;
2726
+ const data = await this.db.select().from(billingCheckouts).where(where).orderBy(drizzleOrm.sql`${billingCheckouts.createdAt} DESC`).limit(limit).offset(offset);
2727
+ return { data, total };
2728
+ }
2729
+ };
2730
+ init_base_repository();
2551
2731
  var QZPayCustomersRepository = class {
2552
2732
  constructor(db) {
2553
2733
  this.db = db;
@@ -5577,6 +5757,7 @@ var QZPayDrizzleStorageAdapter = class {
5577
5757
  livemode;
5578
5758
  // Repositories
5579
5759
  addonsRepo;
5760
+ checkoutsRepo;
5580
5761
  customersRepo;
5581
5762
  subscriptionsRepo;
5582
5763
  paymentsRepo;
@@ -5591,6 +5772,7 @@ var QZPayDrizzleStorageAdapter = class {
5591
5772
  usageRecordsRepo;
5592
5773
  // Storage implementations
5593
5774
  addons;
5775
+ checkouts;
5594
5776
  customers;
5595
5777
  subscriptions;
5596
5778
  payments;
@@ -5607,6 +5789,7 @@ var QZPayDrizzleStorageAdapter = class {
5607
5789
  this.livemode = config.livemode ?? true;
5608
5790
  const typedDb = this.db;
5609
5791
  this.addonsRepo = new QZPayAddonsRepository(this.db);
5792
+ this.checkoutsRepo = new QZPayCheckoutsRepository(this.db);
5610
5793
  this.customersRepo = new QZPayCustomersRepository(typedDb);
5611
5794
  this.subscriptionsRepo = new QZPaySubscriptionsRepository(typedDb);
5612
5795
  this.paymentsRepo = new QZPayPaymentsRepository(this.db);
@@ -5620,6 +5803,7 @@ var QZPayDrizzleStorageAdapter = class {
5620
5803
  this.limitsRepo = new QZPayLimitsRepository(this.db);
5621
5804
  this.usageRecordsRepo = new QZPayUsageRecordsRepository(this.db);
5622
5805
  this.addons = this.createAddOnStorage();
5806
+ this.checkouts = this.createCheckoutStorage();
5623
5807
  this.customers = this.createCustomerStorage();
5624
5808
  this.subscriptions = this.createSubscriptionStorage();
5625
5809
  this.payments = this.createPaymentStorage();
@@ -5680,6 +5864,37 @@ var QZPayDrizzleStorageAdapter = class {
5680
5864
  }
5681
5865
  };
5682
5866
  }
5867
+ // ==================== Checkout Storage ====================
5868
+ createCheckoutStorage() {
5869
+ const repo = this.checkoutsRepo;
5870
+ const livemode = this.livemode;
5871
+ return {
5872
+ async create(session) {
5873
+ const drizzleInput = mapCoreCheckoutToDrizzle(session);
5874
+ const result = await repo.create(drizzleInput);
5875
+ return mapDrizzleCheckoutToCore(result);
5876
+ },
5877
+ async update(id, input) {
5878
+ const drizzleInput = mapCoreCheckoutUpdateToDrizzle(input);
5879
+ const result = await repo.update(id, drizzleInput);
5880
+ return mapDrizzleCheckoutToCore(result);
5881
+ },
5882
+ async findById(id) {
5883
+ const result = await repo.findById(id);
5884
+ return result ? mapDrizzleCheckoutToCore(result) : null;
5885
+ },
5886
+ async findByCustomerId(customerId) {
5887
+ const result = await repo.findByCustomerId(customerId);
5888
+ return result.data.map(mapDrizzleCheckoutToCore);
5889
+ },
5890
+ async list(options) {
5891
+ const limit = options?.limit ?? 20;
5892
+ const offset = options?.offset ?? 0;
5893
+ const result = await repo.search({ livemode, limit, offset });
5894
+ return toPaginatedResult(result, mapDrizzleCheckoutToCore, limit, offset);
5895
+ }
5896
+ };
5897
+ }
5683
5898
  // ==================== Subscription Storage ====================
5684
5899
  createSubscriptionStorage() {
5685
5900
  const repo = this.subscriptionsRepo;
@@ -6281,9 +6496,9 @@ async function runMigrations(config) {
6281
6496
  if (verbose) {
6282
6497
  console.log("[QZPay] Starting database migrations...");
6283
6498
  }
6284
- const sql18 = postgres2__default.default(connectionUrl, { max: 1 });
6499
+ const sql20 = postgres2__default.default(connectionUrl, { max: 1 });
6285
6500
  try {
6286
- const db = postgresJs.drizzle(sql18);
6501
+ const db = postgresJs.drizzle(sql20);
6287
6502
  await migrator.migrate(db, {
6288
6503
  migrationsFolder
6289
6504
  });
@@ -6294,14 +6509,14 @@ async function runMigrations(config) {
6294
6509
  console.error("[QZPay] Migration failed:", error);
6295
6510
  throw error;
6296
6511
  } finally {
6297
- await sql18.end();
6512
+ await sql20.end();
6298
6513
  }
6299
6514
  }
6300
6515
  async function hasPendingMigrations(connectionUrl) {
6301
- const sql18 = postgres2__default.default(connectionUrl, { max: 1 });
6516
+ const sql20 = postgres2__default.default(connectionUrl, { max: 1 });
6302
6517
  try {
6303
- postgresJs.drizzle(sql18);
6304
- const result = await sql18`
6518
+ postgresJs.drizzle(sql20);
6519
+ const result = await sql20`
6305
6520
  SELECT EXISTS (
6306
6521
  SELECT FROM information_schema.tables
6307
6522
  WHERE table_name = 'drizzle_migrations'
@@ -6312,24 +6527,24 @@ async function hasPendingMigrations(connectionUrl) {
6312
6527
  }
6313
6528
  return false;
6314
6529
  } finally {
6315
- await sql18.end();
6530
+ await sql20.end();
6316
6531
  }
6317
6532
  }
6318
6533
  async function ensureDatabase(config) {
6319
6534
  const { connectionUrl, databaseName } = config;
6320
- const sql18 = postgres2__default.default(connectionUrl, { max: 1 });
6535
+ const sql20 = postgres2__default.default(connectionUrl, { max: 1 });
6321
6536
  try {
6322
- const result = await sql18`
6537
+ const result = await sql20`
6323
6538
  SELECT 1 FROM pg_database WHERE datname = ${databaseName}
6324
6539
  `;
6325
6540
  if (result.length === 0) {
6326
- await sql18.unsafe(`CREATE DATABASE "${databaseName}"`);
6541
+ await sql20.unsafe(`CREATE DATABASE "${databaseName}"`);
6327
6542
  console.log(`[QZPay] Created database: ${databaseName}`);
6328
6543
  return true;
6329
6544
  }
6330
6545
  return false;
6331
6546
  } finally {
6332
- await sql18.end();
6547
+ await sql20.end();
6333
6548
  }
6334
6549
  }
6335
6550
 
@@ -6568,6 +6783,7 @@ exports.QZPAY_DRIZZLE_SCHEMA_VERSION = QZPAY_DRIZZLE_SCHEMA_VERSION;
6568
6783
  exports.QZPAY_PAGINATION_DEFAULTS = QZPAY_PAGINATION_DEFAULTS;
6569
6784
  exports.QZPayAddonsRepository = QZPayAddonsRepository;
6570
6785
  exports.QZPayAuditLogsRepository = QZPayAuditLogsRepository;
6786
+ exports.QZPayCheckoutsRepository = QZPayCheckoutsRepository;
6571
6787
  exports.QZPayCustomersRepository = QZPayCustomersRepository;
6572
6788
  exports.QZPayDrizzleStorageAdapter = QZPayDrizzleStorageAdapter;
6573
6789
  exports.QZPayEntitlementsRepository = QZPayEntitlementsRepository;
@@ -6592,6 +6808,9 @@ exports.billingAddonsRelations = billingAddonsRelations;
6592
6808
  exports.billingAuditLogInsertSchema = billingAuditLogInsertSchema;
6593
6809
  exports.billingAuditLogSelectSchema = billingAuditLogSelectSchema;
6594
6810
  exports.billingAuditLogs = billingAuditLogs;
6811
+ exports.billingCheckoutInsertSchema = billingCheckoutInsertSchema;
6812
+ exports.billingCheckoutSelectSchema = billingCheckoutSelectSchema;
6813
+ exports.billingCheckouts = billingCheckouts;
6595
6814
  exports.billingCustomerEntitlementInsertSchema = billingCustomerEntitlementInsertSchema;
6596
6815
  exports.billingCustomerEntitlementSelectSchema = billingCustomerEntitlementSelectSchema;
6597
6816
  exports.billingCustomerEntitlements = billingCustomerEntitlements;
@@ -6695,6 +6914,8 @@ exports.isSoftDeleted = isSoftDeleted;
6695
6914
  exports.isTransaction = isTransaction;
6696
6915
  exports.mapCoreAddonCreateToDrizzle = mapCoreAddonCreateToDrizzle;
6697
6916
  exports.mapCoreAddonUpdateToDrizzle = mapCoreAddonUpdateToDrizzle;
6917
+ exports.mapCoreCheckoutToDrizzle = mapCoreCheckoutToDrizzle;
6918
+ exports.mapCoreCheckoutUpdateToDrizzle = mapCoreCheckoutUpdateToDrizzle;
6698
6919
  exports.mapCoreCustomerCreateToDrizzle = mapCoreCustomerCreateToDrizzle;
6699
6920
  exports.mapCoreCustomerUpdateToDrizzle = mapCoreCustomerUpdateToDrizzle;
6700
6921
  exports.mapCoreEntitlementToDrizzle = mapCoreEntitlementToDrizzle;
@@ -6723,6 +6944,7 @@ exports.mapCoreVendorCreateToDrizzle = mapCoreVendorCreateToDrizzle;
6723
6944
  exports.mapCoreVendorPayoutToDrizzle = mapCoreVendorPayoutToDrizzle;
6724
6945
  exports.mapCoreVendorUpdateToDrizzle = mapCoreVendorUpdateToDrizzle;
6725
6946
  exports.mapDrizzleAddonToCore = mapDrizzleAddonToCore;
6947
+ exports.mapDrizzleCheckoutToCore = mapDrizzleCheckoutToCore;
6726
6948
  exports.mapDrizzleCustomerEntitlementToCore = mapDrizzleCustomerEntitlementToCore;
6727
6949
  exports.mapDrizzleCustomerLimitToCore = mapDrizzleCustomerLimitToCore;
6728
6950
  exports.mapDrizzleCustomerToCore = mapDrizzleCustomerToCore;