@coursebuilder/adapter-drizzle 0.5.0 → 0.5.1

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 (69) hide show
  1. package/dist/{chunk-BM5UKWXI.js → chunk-7ISZNMPU.js} +2 -2
  2. package/dist/{chunk-TBM3AK3P.js → chunk-7X7TMG4A.js} +2 -2
  3. package/dist/{chunk-CQNKTFXE.js → chunk-DAP5KOAO.js} +2 -2
  4. package/dist/{chunk-JZQ666KH.js → chunk-KDOSK7KN.js} +2 -2
  5. package/dist/{chunk-O6JECJRY.js → chunk-QPXUGIXO.js} +2 -2
  6. package/dist/{chunk-FRA4ZCRA.js → chunk-UHH4OVKA.js} +4 -14
  7. package/dist/{chunk-QTGVGIRO.js → chunk-UK6EHYS5.js} +2 -2
  8. package/dist/{chunk-Z245DYMP.js → chunk-VUS77FG3.js} +493 -198
  9. package/dist/index.d.ts +2 -1
  10. package/dist/index.js +12 -12
  11. package/dist/lib/mysql/index.cjs +498 -202
  12. package/dist/lib/mysql/index.cjs.map +1 -1
  13. package/dist/lib/mysql/index.d.cts +8 -30
  14. package/dist/lib/mysql/index.d.ts +8 -30
  15. package/dist/lib/mysql/index.js +10 -8
  16. package/dist/lib/mysql/schemas/auth/accounts.cjs.map +1 -1
  17. package/dist/lib/mysql/schemas/auth/accounts.js +1 -1
  18. package/dist/lib/mysql/schemas/auth/device-access-token.cjs.map +1 -1
  19. package/dist/lib/mysql/schemas/auth/device-access-token.js +2 -2
  20. package/dist/lib/mysql/schemas/auth/device-verification.cjs.map +1 -1
  21. package/dist/lib/mysql/schemas/auth/device-verification.js +2 -2
  22. package/dist/lib/mysql/schemas/auth/role-permissions.cjs.map +1 -1
  23. package/dist/lib/mysql/schemas/auth/role-permissions.js +2 -2
  24. package/dist/lib/mysql/schemas/auth/roles.cjs.map +1 -1
  25. package/dist/lib/mysql/schemas/auth/roles.js +1 -1
  26. package/dist/lib/mysql/schemas/auth/sessions.cjs.map +1 -1
  27. package/dist/lib/mysql/schemas/auth/sessions.js +2 -2
  28. package/dist/lib/mysql/schemas/auth/user-permissions.cjs.map +1 -1
  29. package/dist/lib/mysql/schemas/auth/user-permissions.js +1 -1
  30. package/dist/lib/mysql/schemas/auth/user-prefs.cjs.map +1 -1
  31. package/dist/lib/mysql/schemas/auth/user-prefs.js +1 -1
  32. package/dist/lib/mysql/schemas/auth/user-roles.cjs.map +1 -1
  33. package/dist/lib/mysql/schemas/auth/user-roles.js +1 -1
  34. package/dist/lib/mysql/schemas/auth/users.cjs.map +1 -1
  35. package/dist/lib/mysql/schemas/auth/users.js +1 -1
  36. package/dist/lib/mysql/schemas/commerce/coupon.cjs +3 -13
  37. package/dist/lib/mysql/schemas/commerce/coupon.cjs.map +1 -1
  38. package/dist/lib/mysql/schemas/commerce/coupon.d.cts +2 -14
  39. package/dist/lib/mysql/schemas/commerce/coupon.d.ts +2 -14
  40. package/dist/lib/mysql/schemas/commerce/coupon.js +1 -1
  41. package/dist/lib/mysql/schemas/commerce/price.cjs.map +1 -1
  42. package/dist/lib/mysql/schemas/commerce/price.js +1 -1
  43. package/dist/lib/mysql/schemas/commerce/product.cjs.map +1 -1
  44. package/dist/lib/mysql/schemas/commerce/product.js +1 -1
  45. package/dist/lib/mysql/schemas/commerce/purchase-user-transfer.cjs.map +1 -1
  46. package/dist/lib/mysql/schemas/commerce/purchase-user-transfer.js +2 -2
  47. package/dist/lib/mysql/schemas/commerce/purchase.cjs +0 -4
  48. package/dist/lib/mysql/schemas/commerce/purchase.cjs.map +1 -1
  49. package/dist/lib/mysql/schemas/commerce/purchase.js +1 -1
  50. package/dist/lib/mysql/schemas/commerce/upgradable-products.cjs.map +1 -1
  51. package/dist/lib/mysql/schemas/commerce/upgradable-products.js +2 -2
  52. package/dist/lib/mysql/schemas/communication/comment.cjs.map +1 -1
  53. package/dist/lib/mysql/schemas/communication/comment.js +1 -1
  54. package/dist/lib/mysql/schemas/communication/communication-preferences.cjs.map +1 -1
  55. package/dist/lib/mysql/schemas/communication/communication-preferences.js +1 -1
  56. package/dist/lib/mysql/schemas/content/content-contributions.cjs.map +1 -1
  57. package/dist/lib/mysql/schemas/content/content-contributions.js +1 -1
  58. package/dist/lib/mysql/schemas/content/content-resource-product.cjs.map +1 -1
  59. package/dist/lib/mysql/schemas/content/content-resource-product.js +1 -1
  60. package/dist/lib/mysql/schemas/content/content-resource-resource.cjs.map +1 -1
  61. package/dist/lib/mysql/schemas/content/content-resource-resource.js +1 -1
  62. package/dist/lib/mysql/schemas/content/content-resource.cjs.map +1 -1
  63. package/dist/lib/mysql/schemas/content/content-resource.js +1 -1
  64. package/dist/lib/utils.d.cts +1 -0
  65. package/dist/lib/utils.d.ts +1 -0
  66. package/package.json +4 -2
  67. package/src/index.ts +14 -4
  68. package/src/lib/mysql/index.ts +601 -182
  69. package/src/lib/mysql/schemas/commerce/coupon.ts +3 -9
@@ -1,7 +1,9 @@
1
1
  "use strict";
2
+ var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
3
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
5
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
8
  var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
7
9
  var __export = (target, all) => {
@@ -16,6 +18,14 @@ var __copyProps = (to, from, except, desc2) => {
16
18
  }
17
19
  return to;
18
20
  };
21
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
+ // If the importer is in node compatibility mode or this is not an ESM
23
+ // file that has been converted to a CommonJS file using a Babel-
24
+ // compatible transform (i.e. "__esModule" has not been set), then set
25
+ // "default" to the CommonJS "module.exports" for node compatibility.
26
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
+ mod
28
+ ));
19
29
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
30
 
21
31
  // src/lib/mysql/index.ts
@@ -23,12 +33,15 @@ var mysql_exports = {};
23
33
  __export(mysql_exports, {
24
34
  createTables: () => createTables,
25
35
  getCourseBuilderSchema: () => getCourseBuilderSchema,
36
+ guid: () => guid,
26
37
  mySqlDrizzleAdapter: () => mySqlDrizzleAdapter
27
38
  });
28
39
  module.exports = __toCommonJS(mysql_exports);
40
+ var import_slugify = __toESM(require("@sindresorhus/slugify"), 1);
29
41
  var import_date_fns2 = require("date-fns");
30
42
  var import_drizzle_orm32 = require("drizzle-orm");
31
43
  var import_mysql_core37 = require("drizzle-orm/mysql-core");
44
+ var import_nanoid = require("nanoid");
32
45
  var import_uuid = require("uuid");
33
46
 
34
47
  // ../../node_modules/.pnpm/zod@3.22.4/node_modules/zod/lib/index.mjs
@@ -8044,6 +8057,29 @@ var z2 = /* @__PURE__ */ Object.freeze({
8044
8057
  ZodError: ZodError2
8045
8058
  });
8046
8059
 
8060
+ // ../core/dist/chunk-CMH4QQ3R.js
8061
+ var VideoResourceSchema = z2.object({
8062
+ id: z2.string(),
8063
+ updatedAt: z2.coerce.date().optional(),
8064
+ createdAt: z2.coerce.date().optional(),
8065
+ title: z2.string().optional().nullable(),
8066
+ duration: z2.number().optional().nullable(),
8067
+ muxPlaybackId: z2.string().optional().nullable(),
8068
+ muxAssetId: z2.string().optional().nullable(),
8069
+ transcript: z2.string().optional().nullable(),
8070
+ transcriptWithScreenshots: z2.string().optional().nullable(),
8071
+ srt: z2.string().optional().nullable(),
8072
+ wordLevelSrt: z2.string().optional().nullable(),
8073
+ state: z2.enum([
8074
+ "new",
8075
+ "processing",
8076
+ "preparing",
8077
+ "ready",
8078
+ "errored",
8079
+ "deleted"
8080
+ ])
8081
+ });
8082
+
8047
8083
  // ../core/dist/chunk-CHYUPSYW.js
8048
8084
  var userSchema = z2.object({
8049
8085
  id: z2.string().max(255),
@@ -8078,15 +8114,15 @@ var priceSchema = z2.object({
8078
8114
  fields: z2.record(z2.any()).default({})
8079
8115
  });
8080
8116
 
8081
- // ../core/dist/chunk-YYIPQN6H.js
8117
+ // ../core/dist/chunk-5BAEWUNU.js
8082
8118
  var ContentResourceResourceSchema = z2.object({
8083
8119
  resourceId: z2.string(),
8084
8120
  resourceOfId: z2.string(),
8085
8121
  position: z2.number().default(0),
8086
8122
  metadata: z2.record(z2.string(), z2.any()).default({}).nullable(),
8087
- createdAt: z2.date().nullable(),
8088
- updatedAt: z2.date().nullable(),
8089
- deletedAt: z2.date().nullable(),
8123
+ createdAt: z2.coerce.date().nullable(),
8124
+ updatedAt: z2.coerce.date().nullable(),
8125
+ deletedAt: z2.coerce.date().nullable(),
8090
8126
  resource: z2.any()
8091
8127
  });
8092
8128
  var ContentResourceSchema = z2.object({
@@ -8094,9 +8130,9 @@ var ContentResourceSchema = z2.object({
8094
8130
  type: z2.string(),
8095
8131
  createdById: z2.string(),
8096
8132
  fields: z2.record(z2.string(), z2.any()).default({}).nullable().optional(),
8097
- createdAt: z2.date().nullable(),
8098
- updatedAt: z2.date().nullable(),
8099
- deletedAt: z2.date().nullable(),
8133
+ createdAt: z2.coerce.date().nullable(),
8134
+ updatedAt: z2.coerce.date().nullable(),
8135
+ deletedAt: z2.coerce.date().nullable(),
8100
8136
  resources: z2.array(ContentResourceResourceSchema).default([]).nullable()
8101
8137
  });
8102
8138
  var ContentResourceProductSchema = z2.object({
@@ -8104,9 +8140,9 @@ var ContentResourceProductSchema = z2.object({
8104
8140
  productId: z2.string(),
8105
8141
  position: z2.number().default(0),
8106
8142
  metadata: z2.record(z2.string(), z2.any()).default({}).nullable(),
8107
- createdAt: z2.date().nullable(),
8108
- updatedAt: z2.date().nullable(),
8109
- deletedAt: z2.date().nullable(),
8143
+ createdAt: z2.coerce.date().nullable(),
8144
+ updatedAt: z2.coerce.date().nullable(),
8145
+ deletedAt: z2.coerce.date().nullable(),
8110
8146
  resource: z2.any(),
8111
8147
  product: z2.any()
8112
8148
  });
@@ -8122,7 +8158,7 @@ var ResourceVisibilitySchema = z2.union([
8122
8158
  z2.literal("unlisted")
8123
8159
  ]);
8124
8160
 
8125
- // ../core/dist/chunk-DGMGNBW7.js
8161
+ // ../core/dist/chunk-SVQMPVCK.js
8126
8162
  var productSchema = z2.object({
8127
8163
  id: z2.string().max(191),
8128
8164
  name: z2.string().max(191),
@@ -8133,10 +8169,10 @@ var productSchema = z2.object({
8133
8169
  ]).default("self-paced"),
8134
8170
  fields: z2.object({
8135
8171
  body: z2.string().nullable().optional(),
8136
- description: z2.string().optional().nullable(),
8172
+ description: z2.string().nullish(),
8137
8173
  slug: z2.string(),
8138
8174
  image: z2.object({
8139
- url: z2.string().url(),
8175
+ url: z2.string(),
8140
8176
  alt: z2.string().optional().nullable(),
8141
8177
  width: z2.number().optional().nullable(),
8142
8178
  height: z2.number().optional().nullable()
@@ -8154,14 +8190,19 @@ var productSchema = z2.object({
8154
8190
  "unlisted"
8155
8191
  ]).default("unlisted")
8156
8192
  }),
8157
- createdAt: z2.date().nullable(),
8193
+ createdAt: z2.coerce.date().nullable(),
8158
8194
  status: z2.number().int().default(0),
8159
8195
  quantityAvailable: z2.number().int().default(-1),
8160
8196
  price: priceSchema.nullable().optional(),
8161
8197
  resources: z2.array(ContentResourceProductSchema).default([]).nullable()
8162
8198
  });
8199
+ var NewProductSchema = z2.object({
8200
+ name: z2.string().min(2).max(90),
8201
+ quantityAvailable: z2.coerce.number().default(-1),
8202
+ price: z2.coerce.number().gte(0).default(0)
8203
+ });
8163
8204
 
8164
- // ../core/dist/chunk-VDB4YSMY.js
8205
+ // ../core/dist/chunk-RCFZC3SN.js
8165
8206
  var couponSchema = z2.object({
8166
8207
  id: z2.string(),
8167
8208
  code: z2.string().max(191).optional().nullable(),
@@ -8178,11 +8219,12 @@ var couponSchema = z2.object({
8178
8219
  return decimalPlaces <= 2;
8179
8220
  }),
8180
8221
  restrictedToProductId: z2.string().max(191).optional().nullable(),
8181
- bulkPurchaseId: z2.string().max(191).optional().nullable(),
8182
- bulkCouponPurchases: z2.any().optional().nullable()
8222
+ bulkPurchases: z2.array(z2.any()).default([]),
8223
+ redeemedBulkCouponPurchases: z2.array(z2.any()).default([]),
8224
+ bulkPurchaseId: z2.string().max(191).optional().nullable()
8183
8225
  });
8184
8226
 
8185
- // ../core/dist/chunk-OUYYSWMK.js
8227
+ // ../core/dist/chunk-5OFQV6YX.js
8186
8228
  var purchaseSchema = z2.object({
8187
8229
  id: z2.string().max(191),
8188
8230
  userId: z2.string().max(191).optional().nullable(),
@@ -8231,18 +8273,15 @@ var purchaseUserTransferSchema = z2.object({
8231
8273
  completedAt: z2.date().nullable()
8232
8274
  });
8233
8275
 
8234
- // ../core/dist/chunk-K6G2HAJT.js
8276
+ // ../core/dist/chunk-CWQHSOPP.js
8235
8277
  var resourceProgressSchema = z2.object({
8236
8278
  userId: z2.string().max(191),
8237
8279
  resourceId: z2.string().max(191).optional().nullable(),
8238
- fields: z2.record(z2.any()).default({}),
8239
- completedAt: z2.date().nullable(),
8240
- updatedAt: z2.date().nullable(),
8241
- createdAt: z2.date().nullable()
8280
+ completedAt: z2.date().nullable()
8242
8281
  });
8243
8282
  var moduleProgressSchema = z2.object({
8244
8283
  completedLessons: z2.array(resourceProgressSchema),
8245
- nextResource: ContentResourceSchema.nullable(),
8284
+ nextResource: ContentResourceSchema.partial().nullable(),
8246
8285
  percentCompleted: z2.number().default(0),
8247
8286
  completedLessonsCount: z2.number().default(0),
8248
8287
  totalLessonsCount: z2.number().default(0)
@@ -8259,29 +8298,6 @@ var upgradableProductSchema = z2.object({
8259
8298
  deletedAt: z2.date().nullable()
8260
8299
  });
8261
8300
 
8262
- // ../core/dist/chunk-5QZXOTEH.js
8263
- var VideoResourceSchema = z2.object({
8264
- id: z2.string(),
8265
- updatedAt: z2.string().optional(),
8266
- createdAt: z2.string().optional(),
8267
- title: z2.string().optional().nullable(),
8268
- duration: z2.number().optional().nullable(),
8269
- muxPlaybackId: z2.string().optional().nullable(),
8270
- muxAssetId: z2.string().optional().nullable(),
8271
- transcript: z2.string().optional().nullable(),
8272
- transcriptWithScreenshots: z2.string().optional().nullable(),
8273
- srt: z2.string().optional().nullable(),
8274
- wordLevelSrt: z2.string().optional().nullable(),
8275
- state: z2.enum([
8276
- "new",
8277
- "processing",
8278
- "preparing",
8279
- "ready",
8280
- "errored",
8281
- "deleted"
8282
- ])
8283
- });
8284
-
8285
8301
  // ../core/dist/chunk-EDDT2FFU.js
8286
8302
  var merchantCustomerSchema = z2.object({
8287
8303
  id: z2.string().max(191),
@@ -9054,9 +9070,6 @@ function getCouponSchema(mysqlTable) {
9054
9070
  }).notNull(),
9055
9071
  restrictedToProductId: (0, import_mysql_core11.varchar)("restrictedToProductId", {
9056
9072
  length: 191
9057
- }),
9058
- bulkPurchaseId: (0, import_mysql_core11.varchar)("bulkPurchaseId", {
9059
- length: 191
9060
9073
  })
9061
9074
  }, (table) => {
9062
9075
  return {
@@ -9067,7 +9080,6 @@ function getCouponSchema(mysqlTable) {
9067
9080
  ],
9068
9081
  name: "Coupon_id"
9069
9082
  }),
9070
- couponBulkPurchaseIdKey: (0, import_mysql_core11.unique)("Coupon_bulkPurchaseId_key").on(table.bulkPurchaseId),
9071
9083
  couponCodeKey: (0, import_mysql_core11.unique)("Coupon_code_key").on(table.code)
9072
9084
  };
9073
9085
  });
@@ -9078,7 +9090,7 @@ function getCouponRelationsSchema(mysqlTable) {
9078
9090
  const coupon = getCouponSchema(mysqlTable);
9079
9091
  const merchantCoupon = getMerchantCouponSchema(mysqlTable);
9080
9092
  return (0, import_drizzle_orm10.relations)(coupon, ({ many, one }) => ({
9081
- bulkCouponPurchases: many(purchase, {
9093
+ redeemedBulkCouponPurchases: many(purchase, {
9082
9094
  relationName: "redeemedBulkCoupon"
9083
9095
  }),
9084
9096
  merchantCoupon: one(merchantCoupon, {
@@ -9099,14 +9111,8 @@ function getCouponRelationsSchema(mysqlTable) {
9099
9111
  ],
9100
9112
  relationName: "product"
9101
9113
  }),
9102
- bulkPurchase: one(purchase, {
9103
- fields: [
9104
- coupon.bulkPurchaseId
9105
- ],
9106
- references: [
9107
- purchase.id
9108
- ],
9109
- relationName: "bulkPurchase"
9114
+ bulkPurchases: many(purchase, {
9115
+ relationName: "bulkCoupon"
9110
9116
  })
9111
9117
  }));
9112
9118
  }
@@ -10481,6 +10487,7 @@ function getResourceProgressSchema(mysqlTable) {
10481
10487
  __name(getResourceProgressSchema, "getResourceProgressSchema");
10482
10488
 
10483
10489
  // src/lib/mysql/index.ts
10490
+ var guid = (0, import_nanoid.customAlphabet)("1234567890abcdefghijklmnopqrstuvwxyz", 5);
10484
10491
  function getCourseBuilderSchema(mysqlTable) {
10485
10492
  return {
10486
10493
  accounts: getAccountsSchema(mysqlTable),
@@ -10550,8 +10557,8 @@ function createTables(mySqlTable) {
10550
10557
  return getCourseBuilderSchema(mySqlTable);
10551
10558
  }
10552
10559
  __name(createTables, "createTables");
10553
- function mySqlDrizzleAdapter(client, tableFn = import_mysql_core37.mysqlTable) {
10554
- const { users, accounts, sessions, verificationTokens, contentResource, contentResourceResource, purchases: purchaseTable, purchaseUserTransfer, coupon, merchantCoupon, merchantCharge, merchantAccount, merchantPrice, merchantCustomer, merchantSession, merchantProduct, prices, products, upgradableProducts, resourceProgress, comments } = createTables(tableFn);
10560
+ function mySqlDrizzleAdapter(client, tableFn = import_mysql_core37.mysqlTable, paymentProvider) {
10561
+ const { users, accounts, sessions, verificationTokens, contentResource, contentResourceResource, contentResourceProduct, purchases: purchaseTable, purchaseUserTransfer, coupon, merchantCoupon, merchantCharge, merchantAccount, merchantPrice, merchantCustomer, merchantSession, merchantProduct, prices, products, upgradableProducts, resourceProgress, comments } = createTables(tableFn);
10555
10562
  const adapter = {
10556
10563
  client,
10557
10564
  async redeemFullPriceCoupon(options) {
@@ -10563,7 +10570,7 @@ function mySqlDrizzleAdapter(client, tableFn = import_mysql_core37.mysqlTable) {
10563
10570
  throw new Error(`unable-to-find-any-product-id`);
10564
10571
  const couponValidation = validateCoupon(coupon2, productIds);
10565
10572
  if (coupon2 && couponValidation.isRedeemable) {
10566
- const bulkCouponRedemption = Boolean(coupon2.bulkPurchase?.bulkCouponId);
10573
+ const bulkCouponRedemption = Boolean(coupon2.maxUses > 1);
10567
10574
  const { user } = await adapter.findOrCreateUser(email);
10568
10575
  if (!user)
10569
10576
  throw new Error(`unable-to-create-user-${email}`);
@@ -10573,8 +10580,18 @@ function mySqlDrizzleAdapter(client, tableFn = import_mysql_core37.mysqlTable) {
10573
10580
  userId: user.id,
10574
10581
  productId
10575
10582
  });
10576
- if (existingPurchases.length > 0)
10577
- throw new Error(`already-purchased-${email}`);
10583
+ if (existingPurchases.length > 0) {
10584
+ const errorMessage = `already-purchased-${email}`;
10585
+ console.error(errorMessage);
10586
+ return {
10587
+ error: {
10588
+ message: errorMessage
10589
+ },
10590
+ redeemingForCurrentUser,
10591
+ purchase: null
10592
+ };
10593
+ throw new Error(errorMessage);
10594
+ }
10578
10595
  const purchaseId = `purchase-${(0, import_uuid.v4)()}`;
10579
10596
  await adapter.createPurchase({
10580
10597
  id: purchaseId,
@@ -10640,7 +10657,7 @@ function mySqlDrizzleAdapter(client, tableFn = import_mysql_core37.mysqlTable) {
10640
10657
  },
10641
10658
  getMerchantPriceForProductId: async (productId) => {
10642
10659
  const merchantPriceData = await client.query.merchantPrice.findFirst({
10643
- where: (0, import_drizzle_orm32.eq)(merchantPrice.merchantProductId, productId)
10660
+ where: (0, import_drizzle_orm32.and)((0, import_drizzle_orm32.eq)(merchantPrice.merchantProductId, productId), (0, import_drizzle_orm32.eq)(merchantPrice.status, 1))
10644
10661
  });
10645
10662
  const parsedMerchantPrice = merchantPriceSchema.safeParse(merchantPriceData);
10646
10663
  if (!parsedMerchantPrice.success) {
@@ -10674,7 +10691,7 @@ function mySqlDrizzleAdapter(client, tableFn = import_mysql_core37.mysqlTable) {
10674
10691
  async availableUpgradesForProduct(purchases, productId) {
10675
10692
  const previousPurchaseProductIds = purchases.map(({ productId: productId2 }) => productId2);
10676
10693
  if (previousPurchaseProductIds.length > 0) {
10677
- return await client.query.upgradableProducts.findMany({
10694
+ return client.query.upgradableProducts.findMany({
10678
10695
  where: (0, import_drizzle_orm32.and)((0, import_drizzle_orm32.eq)(upgradableProducts.upgradableToId, productId), (0, import_drizzle_orm32.inArray)(upgradableProducts.upgradableFromId, previousPurchaseProductIds))
10679
10696
  });
10680
10697
  }
@@ -10896,18 +10913,31 @@ function mySqlDrizzleAdapter(client, tableFn = import_mysql_core37.mysqlTable) {
10896
10913
  couponId
10897
10914
  });
10898
10915
  let couponData;
10916
+ let bulkCouponPurchases;
10899
10917
  try {
10900
10918
  couponData = await client.query.coupon.findFirst({
10901
10919
  where: (0, import_drizzle_orm32.eq)(coupon.id, couponId),
10902
10920
  with: {
10903
- bulkPurchase: true,
10904
- bulkCouponPurchases: true
10921
+ bulkPurchases: true,
10922
+ redeemedBulkCouponPurchases: true
10905
10923
  }
10906
10924
  }) || null;
10907
10925
  } catch (e) {
10908
10926
  console.log("getCouponWithBulkPurchases");
10909
10927
  logger.error(e);
10910
10928
  }
10929
+ try {
10930
+ bulkCouponPurchases = await client.query.purchases.findMany({
10931
+ where: (0, import_drizzle_orm32.eq)(purchaseTable.redeemedBulkCouponId, couponId),
10932
+ with: {
10933
+ user: true
10934
+ }
10935
+ });
10936
+ console.log("purchases with redeemedBulkCouponId", bulkCouponPurchases);
10937
+ } catch (e) {
10938
+ console.log("getCouponWithBulkPurchases");
10939
+ logger.error(e);
10940
+ }
10911
10941
  if (!couponData) {
10912
10942
  logger.debug("getCouponWithBulkPurchases", {
10913
10943
  couponId,
@@ -10915,12 +10945,15 @@ function mySqlDrizzleAdapter(client, tableFn = import_mysql_core37.mysqlTable) {
10915
10945
  });
10916
10946
  return null;
10917
10947
  }
10948
+ const couponWithBulkPurchases = {
10949
+ ...couponData,
10950
+ redeemedBulkCouponPurchases: bulkCouponPurchases || []
10951
+ };
10918
10952
  const parsedCoupon = couponSchema.merge(z.object({
10919
- bulkCouponPurchases: z.array(purchaseSchema),
10920
- bulkPurchase: purchaseSchema.nullable().optional()
10921
- })).nullable().safeParse(couponData);
10953
+ redeemedBulkCouponPurchases: z.array(purchaseSchema)
10954
+ })).nullable().safeParse(couponWithBulkPurchases);
10922
10955
  if (!parsedCoupon.success) {
10923
- console.error("Error parsing coupon", couponData);
10956
+ console.error("Error parsing coupon", JSON.stringify(parsedCoupon.error), couponData);
10924
10957
  return null;
10925
10958
  }
10926
10959
  return parsedCoupon.data;
@@ -10962,109 +10995,65 @@ function mySqlDrizzleAdapter(client, tableFn = import_mysql_core37.mysqlTable) {
10962
10995
  return parsed.data;
10963
10996
  },
10964
10997
  async getModuleProgressForUser(userIdOrEmail, moduleIdOrSlug) {
10965
- const ALLOWED_MODULE_RESOURCE_TYPES = [
10966
- "lesson",
10967
- "exercise",
10968
- "solution"
10969
- ];
10970
- const COUNTABLE_MODULE_RESOURCE_TYPES = [
10971
- "lesson",
10972
- "exercise"
10973
- ];
10974
- const module2 = await client.query.contentResource.findFirst({
10975
- where: (0, import_drizzle_orm32.or)((0, import_drizzle_orm32.eq)(contentResource.id, moduleIdOrSlug), (0, import_drizzle_orm32.eq)(import_drizzle_orm32.sql`JSON_EXTRACT (${contentResource.fields}, "$.slug")`, moduleIdOrSlug)),
10976
- with: {
10977
- resources: {
10978
- with: {
10979
- resource: {
10980
- with: {
10981
- resources: {
10982
- with: {
10983
- resource: {
10984
- with: {
10985
- resources: {
10986
- with: {
10987
- resource: true
10988
- }
10989
- }
10990
- }
10991
- }
10992
- },
10993
- orderBy: (0, import_drizzle_orm32.asc)(contentResourceResource.position)
10994
- }
10995
- }
10996
- }
10997
- },
10998
- orderBy: (0, import_drizzle_orm32.asc)(contentResourceResource.position)
10999
- }
11000
- }
11001
- });
11002
- const parsedModule = ContentResourceSchema.parse(module2);
11003
- function flattenResources(resources) {
11004
- const result = [];
11005
- function recurse(resources2) {
11006
- for (const nestedResource of resources2) {
11007
- const resource = nestedResource.resource;
11008
- result.push(resource);
11009
- if (resource.resources) {
11010
- recurse(resource.resources);
11011
- }
11012
- }
11013
- }
11014
- __name(recurse, "recurse");
11015
- recurse(resources);
11016
- return result;
11017
- }
11018
- __name(flattenResources, "flattenResources");
11019
- const allResources = parsedModule?.resources && flattenResources(parsedModule.resources);
11020
- const filteredResources = allResources?.filter((resource) => {
11021
- return ALLOWED_MODULE_RESOURCE_TYPES.includes(resource.type);
11022
- });
11023
- const parsedResources = z.array(ContentResourceSchema).safeParse(filteredResources);
11024
- if (!parsedResources.success) {
11025
- console.error("Error parsing module resources", parsedResources.error);
11026
- return {
11027
- completedLessons: [],
11028
- nextResource: null,
11029
- percentCompleted: 0,
11030
- completedLessonsCount: 0,
11031
- totalLessonsCount: 0
11032
- };
11033
- }
11034
- const progressResources = parsedResources.data.filter((r) => {
11035
- return COUNTABLE_MODULE_RESOURCE_TYPES.includes(r.type);
11036
- });
11037
- const totalLessonsCount = progressResources.length;
11038
10998
  const user = await client.query.users.findFirst({
11039
10999
  where: (0, import_drizzle_orm32.or)((0, import_drizzle_orm32.eq)(users.id, userIdOrEmail), (0, import_drizzle_orm32.eq)(users.email, userIdOrEmail)),
11040
- with: {
11041
- roles: {
11042
- with: {
11043
- role: true
11044
- }
11045
- }
11046
- }
11047
- }).then(async (res) => {
11048
- if (res) {
11049
- return {
11050
- ...res,
11051
- roles: res.roles.map((r) => r.role)
11052
- };
11000
+ columns: {
11001
+ id: true
11053
11002
  }
11054
11003
  });
11055
11004
  if (!user) {
11056
- console.error("User not found", userIdOrEmail);
11057
- return {
11058
- completedLessons: [],
11059
- nextResource: null,
11060
- percentCompleted: 0,
11061
- completedLessonsCount: 0,
11062
- totalLessonsCount
11063
- };
11005
+ return null;
11064
11006
  }
11065
- const parsedUser = userSchema.safeParse(user);
11066
- if (!parsedUser.success) {
11067
- console.error("Error parsing user", parsedUser.error);
11007
+ const ResultRowSchema = z.object({
11008
+ resource_id: z.string(),
11009
+ resource_type: z.enum([
11010
+ "lesson",
11011
+ "exercise"
11012
+ ]),
11013
+ resource_slug: z.string().nullable(),
11014
+ completed_at: z.string().nullable().transform((val) => val ? new Date(val) : null)
11015
+ });
11016
+ const results = await client.execute(import_drizzle_orm32.sql`
11017
+ SELECT
11018
+ cr.id AS resource_id,
11019
+ cr.type AS resource_type,
11020
+ cr.fields->>'$.slug' AS resource_slug,
11021
+ rp.completedAt AS completed_at
11022
+ FROM
11023
+ (SELECT id, fields->>'$.slug' AS slug
11024
+ FROM ${contentResource}
11025
+ WHERE id = ${moduleIdOrSlug}
11026
+ OR fields->>'$.slug' = ${moduleIdOrSlug}) AS w
11027
+ LEFT JOIN
11028
+ (SELECT
11029
+ crr.resourceOfId AS workshop_id,
11030
+ crr.resourceId,
11031
+ crr.position
11032
+ FROM ${contentResourceResource} crr) AS tlr ON w.id = tlr.workshop_id
11033
+ LEFT JOIN ${contentResource} sections ON sections.id = tlr.resourceId AND sections.type = 'section'
11034
+ LEFT JOIN
11035
+ (SELECT
11036
+ crr.resourceOfId AS section_id,
11037
+ crr.resourceId AS resource_id,
11038
+ crr.position AS position_in_section,
11039
+ section_crr.position AS section_position
11040
+ FROM ${contentResourceResource} crr
11041
+ JOIN ${contentResourceResource} section_crr ON crr.resourceOfId = section_crr.resourceId) AS sr
11042
+ ON sr.section_id = sections.id
11043
+ JOIN ${contentResource} cr ON cr.id = COALESCE(sr.resource_id, tlr.resourceId)
11044
+ LEFT JOIN ${resourceProgress} rp ON rp.resourceId = cr.id
11045
+ AND rp.userId = ${user.id}
11046
+ WHERE
11047
+ cr.type IN ('lesson', 'exercise')
11048
+
11049
+ `);
11050
+ const completedLessons = [];
11051
+ let nextResource = null;
11052
+ let completedLessonsCount = 0;
11053
+ let totalLessonsCount = results.rows.length;
11054
+ const parsedRows = z.array(ResultRowSchema).safeParse(results.rows);
11055
+ if (!parsedRows.success) {
11056
+ console.error("Error parsing rows", parsedRows.error);
11068
11057
  return {
11069
11058
  completedLessons: [],
11070
11059
  nextResource: null,
@@ -11073,34 +11062,30 @@ function mySqlDrizzleAdapter(client, tableFn = import_mysql_core37.mysqlTable) {
11073
11062
  totalLessonsCount
11074
11063
  };
11075
11064
  }
11076
- const userProgress = await client.query.resourceProgress.findMany({
11077
- where: (0, import_drizzle_orm32.and)((0, import_drizzle_orm32.eq)(resourceProgress.userId, parsedUser.data.id), (0, import_drizzle_orm32.isNotNull)(resourceProgress.completedAt), (0, import_drizzle_orm32.inArray)(resourceProgress.resourceId, progressResources.map((r) => r.id))),
11078
- orderBy: (0, import_drizzle_orm32.asc)(resourceProgress.completedAt)
11079
- });
11080
- const nextResourceId = parsedResources.data.filter((r) => {
11081
- return COUNTABLE_MODULE_RESOURCE_TYPES.includes(r.type);
11082
- }).find((r) => !userProgress.find((p) => p.resourceId === r.id))?.id;
11083
- const nextResource = await client.query.contentResource.findFirst({
11084
- where: (0, import_drizzle_orm32.eq)(contentResource.id, nextResourceId)
11085
- });
11086
- const parsedNextResource = ContentResourceSchema.nullable().optional().default(null).parse(nextResource);
11087
- const parsedProgress = z.array(resourceProgressSchema).safeParse(userProgress);
11088
- if (!parsedProgress.success) {
11089
- console.error("Error parsing user progress", parsedProgress.error);
11090
- return {
11091
- completedLessons: [],
11092
- nextResource: null,
11093
- percentCompleted: 0,
11094
- completedLessonsCount: 0,
11095
- totalLessonsCount
11096
- };
11065
+ for (const row of parsedRows.data) {
11066
+ if (row.completed_at) {
11067
+ completedLessonsCount++;
11068
+ completedLessons.push({
11069
+ userId: user.id,
11070
+ resourceId: row.resource_id,
11071
+ completedAt: new Date(row.completed_at)
11072
+ });
11073
+ } else if (!nextResource) {
11074
+ nextResource = {
11075
+ id: row.resource_id,
11076
+ type: row.resource_type,
11077
+ fields: {
11078
+ slug: row.resource_slug
11079
+ }
11080
+ };
11081
+ }
11097
11082
  }
11098
- const percentCompleted = Math.round(parsedProgress.data.length / parsedResources.data.length * 100);
11083
+ const percentCompleted = totalLessonsCount > 0 ? Math.ceil(completedLessonsCount / totalLessonsCount * 100) : 0;
11099
11084
  return {
11100
- completedLessons: parsedProgress.data,
11101
- nextResource: parsedNextResource,
11085
+ completedLessons,
11086
+ nextResource,
11102
11087
  percentCompleted,
11103
- completedLessonsCount: parsedProgress.data.length,
11088
+ completedLessonsCount,
11104
11089
  totalLessonsCount
11105
11090
  };
11106
11091
  },
@@ -11113,7 +11098,7 @@ function mySqlDrizzleAdapter(client, tableFn = import_mysql_core37.mysqlTable) {
11113
11098
  });
11114
11099
  const parsed = merchantChargeSchema.safeParse(mCharge);
11115
11100
  if (!parsed.success) {
11116
- console.error("Error parsing merchantCharge", mCharge);
11101
+ console.info("Error parsing merchantCharge", mCharge);
11117
11102
  return null;
11118
11103
  }
11119
11104
  return parsed.data;
@@ -11156,10 +11141,249 @@ function mySqlDrizzleAdapter(client, tableFn = import_mysql_core37.mysqlTable) {
11156
11141
  where: (0, import_drizzle_orm32.eq)(prices.productId, productId)
11157
11142
  }));
11158
11143
  },
11159
- async getProduct(productId) {
11160
- return productSchema.nullable().parse(await client.query.products.findFirst({
11161
- where: (0, import_drizzle_orm32.eq)(products.id, productId)
11144
+ async archiveProduct(productId) {
11145
+ if (!paymentProvider)
11146
+ throw new Error("Payment provider not found");
11147
+ const product = await adapter.getProduct(productId);
11148
+ if (!product) {
11149
+ throw new Error(`Product not found for id (${productId})`);
11150
+ }
11151
+ if (!product.price) {
11152
+ throw new Error(`Product has no price`);
11153
+ }
11154
+ await client.update(products).set({
11155
+ status: 0,
11156
+ name: `${product.name} (Archived)`
11157
+ }).where((0, import_drizzle_orm32.eq)(products.id, productId));
11158
+ await client.update(prices).set({
11159
+ status: 0,
11160
+ nickname: `${product.name} (Archived)`
11161
+ }).where((0, import_drizzle_orm32.eq)(prices.productId, productId));
11162
+ await client.update(merchantProduct).set({
11163
+ status: 0
11164
+ }).where((0, import_drizzle_orm32.eq)(merchantProduct.productId, productId));
11165
+ await client.update(merchantPrice).set({
11166
+ status: 0
11167
+ }).where((0, import_drizzle_orm32.eq)(merchantPrice.priceId, product.price.id));
11168
+ const currentMerchantProduct = merchantProductSchema.nullish().parse(await client.query.merchantProduct.findFirst({
11169
+ where: (0, import_drizzle_orm32.eq)(merchantProduct.productId, productId)
11170
+ }));
11171
+ if (!currentMerchantProduct || !currentMerchantProduct.identifier) {
11172
+ throw new Error(`Merchant product not found for id (${productId})`);
11173
+ }
11174
+ await paymentProvider.updateProduct(currentMerchantProduct.identifier, {
11175
+ active: false
11176
+ });
11177
+ const currentMerchantPrice = merchantPriceSchema.nullish().parse(await client.query.merchantPrice.findFirst({
11178
+ where: (0, import_drizzle_orm32.and)((0, import_drizzle_orm32.eq)(merchantPrice.priceId, product.price.id), (0, import_drizzle_orm32.eq)(merchantPrice.status, 1))
11179
+ }));
11180
+ if (!currentMerchantPrice || !currentMerchantPrice.identifier) {
11181
+ throw new Error(`Merchant price not found for id (${productId})`);
11182
+ }
11183
+ await paymentProvider.updatePrice(currentMerchantPrice.identifier, {
11184
+ active: false
11185
+ });
11186
+ return adapter.getProduct(productId);
11187
+ },
11188
+ async updateProduct(input) {
11189
+ if (!paymentProvider)
11190
+ throw new Error("Payment provider not found");
11191
+ const currentProduct = await adapter.getProduct(input.id);
11192
+ if (!currentProduct) {
11193
+ throw new Error(`Product not found`);
11194
+ }
11195
+ if (!currentProduct.price) {
11196
+ throw new Error(`Product has no price`);
11197
+ }
11198
+ const merchantProduct2 = merchantProductSchema.nullish().parse(await client.query.merchantProduct.findFirst({
11199
+ where: (merchantProduct3, { eq: eq2 }) => eq2(merchantProduct3.productId, input.id)
11162
11200
  }));
11201
+ if (!merchantProduct2 || !merchantProduct2.identifier) {
11202
+ throw new Error(`Merchant product not found`);
11203
+ }
11204
+ const stripeProduct = await paymentProvider.getProduct(merchantProduct2.identifier);
11205
+ const priceChanged = currentProduct.price.unitAmount.toString() !== input.price?.unitAmount.toString();
11206
+ if (priceChanged) {
11207
+ const currentMerchantPrice = merchantPriceSchema.nullish().parse(await client.query.merchantPrice.findFirst({
11208
+ where: (merchantPrice2, { eq: eq2, and: and2 }) => and2(eq2(merchantPrice2.merchantProductId, merchantProduct2.id), eq2(merchantPrice2.status, 1))
11209
+ }));
11210
+ if (!currentMerchantPrice || !currentMerchantPrice.identifier) {
11211
+ throw new Error(`Merchant price not found`);
11212
+ }
11213
+ const currentStripePrice = await paymentProvider.getPrice(currentMerchantPrice.identifier);
11214
+ const newStripePrice = await paymentProvider.createPrice({
11215
+ product: stripeProduct.id,
11216
+ unit_amount: Math.floor(Number(input.price?.unitAmount || 0) * 100),
11217
+ currency: "usd",
11218
+ metadata: {
11219
+ slug: input.fields.slug
11220
+ },
11221
+ active: true
11222
+ });
11223
+ await paymentProvider.updateProduct(stripeProduct.id, {
11224
+ default_price: newStripePrice.id
11225
+ });
11226
+ const newMerchantPriceId = `mprice_${(0, import_uuid.v4)()}`;
11227
+ await client.insert(merchantPrice).values({
11228
+ id: newMerchantPriceId,
11229
+ merchantProductId: merchantProduct2.id,
11230
+ merchantAccountId: merchantProduct2.merchantAccountId,
11231
+ priceId: currentProduct.price.id,
11232
+ status: 1,
11233
+ identifier: newStripePrice.id
11234
+ });
11235
+ if (currentMerchantPrice) {
11236
+ await client.update(merchantPrice).set({
11237
+ status: 0
11238
+ }).where((0, import_drizzle_orm32.eq)(merchantPrice.id, currentMerchantPrice.id));
11239
+ }
11240
+ await client.update(prices).set({
11241
+ unitAmount: Math.floor(Number(input.price?.unitAmount || 0)).toString(),
11242
+ nickname: input.name
11243
+ }).where((0, import_drizzle_orm32.eq)(prices.id, currentProduct.price.id));
11244
+ if (currentStripePrice) {
11245
+ await paymentProvider.updatePrice(currentStripePrice.id, {
11246
+ active: false
11247
+ });
11248
+ }
11249
+ }
11250
+ await paymentProvider.updateProduct(stripeProduct.id, {
11251
+ name: input.name,
11252
+ active: true,
11253
+ images: input.fields.image?.url ? [
11254
+ input.fields.image.url
11255
+ ] : void 0,
11256
+ description: input.fields.description || "",
11257
+ metadata: {
11258
+ slug: input.fields.slug
11259
+ }
11260
+ });
11261
+ const { image, ...fieldsNoImage } = input.fields;
11262
+ await client.update(products).set({
11263
+ name: input.name,
11264
+ quantityAvailable: input.quantityAvailable,
11265
+ status: 1,
11266
+ fields: {
11267
+ ...fieldsNoImage,
11268
+ ...image?.url && {
11269
+ image
11270
+ }
11271
+ }
11272
+ }).where((0, import_drizzle_orm32.eq)(products.id, currentProduct.id));
11273
+ return adapter.getProduct(currentProduct.id);
11274
+ },
11275
+ async createProduct(input) {
11276
+ if (!paymentProvider)
11277
+ throw new Error("Payment provider not found");
11278
+ const merchantAccount2 = merchantAccountSchema.nullish().parse(await client.query.merchantAccount.findFirst({
11279
+ where: (merchantAccount3, { eq: eq2 }) => eq2(merchantAccount3.label, "stripe")
11280
+ }));
11281
+ if (!merchantAccount2) {
11282
+ throw new Error("Merchant account not found");
11283
+ }
11284
+ const hash = guid();
11285
+ const newProductId = (0, import_slugify.default)(`product-${hash}`);
11286
+ const newProduct = {
11287
+ id: newProductId,
11288
+ name: input.name,
11289
+ status: 1,
11290
+ type: "self-paced",
11291
+ quantityAvailable: input.quantityAvailable,
11292
+ fields: {
11293
+ state: "draft",
11294
+ visibility: "unlisted",
11295
+ slug: (0, import_slugify.default)(`${input.name}-${hash}`)
11296
+ }
11297
+ };
11298
+ await client.insert(products).values(newProduct);
11299
+ const priceHash = guid();
11300
+ const newPriceId = `price-${priceHash}`;
11301
+ await client.insert(prices).values({
11302
+ id: newPriceId,
11303
+ productId: newProductId,
11304
+ unitAmount: input.price.toString(),
11305
+ status: 1
11306
+ });
11307
+ const product = await adapter.getProduct(newProductId);
11308
+ const stripeProduct = await paymentProvider.createProduct({
11309
+ name: input.name,
11310
+ metadata: {
11311
+ slug: product?.fields?.slug || null
11312
+ }
11313
+ });
11314
+ const stripePrice = await paymentProvider.createPrice({
11315
+ product: stripeProduct.id,
11316
+ unit_amount: Math.floor(Number(input.price) * 100),
11317
+ currency: "usd",
11318
+ nickname: input.name,
11319
+ metadata: {
11320
+ slug: product?.fields?.slug || null
11321
+ }
11322
+ });
11323
+ const newMerchantProductId = `mproduct_${(0, import_uuid.v4)()}`;
11324
+ await client.insert(merchantProduct).values({
11325
+ id: newMerchantProductId,
11326
+ merchantAccountId: merchantAccount2.id,
11327
+ productId: newProductId,
11328
+ identifier: stripeProduct.id,
11329
+ status: 1
11330
+ });
11331
+ const newMerchantPriceId = `mprice_${(0, import_uuid.v4)()}`;
11332
+ await client.insert(merchantPrice).values({
11333
+ id: newMerchantPriceId,
11334
+ merchantAccountId: merchantAccount2.id,
11335
+ merchantProductId: newMerchantProductId,
11336
+ priceId: newPriceId,
11337
+ identifier: stripePrice.id,
11338
+ status: 1
11339
+ });
11340
+ return product;
11341
+ },
11342
+ async getProduct(productSlugOrId, withResources = true) {
11343
+ if (!productSlugOrId) {
11344
+ return null;
11345
+ }
11346
+ try {
11347
+ const productData = await client.query.products.findFirst({
11348
+ where: (0, import_drizzle_orm32.and)((0, import_drizzle_orm32.or)((0, import_drizzle_orm32.eq)(import_drizzle_orm32.sql`JSON_EXTRACT (${products.fields}, "$.slug")`, `${productSlugOrId}`), (0, import_drizzle_orm32.eq)(products.id, productSlugOrId))),
11349
+ with: {
11350
+ price: true,
11351
+ ...withResources && {
11352
+ resources: {
11353
+ with: {
11354
+ resource: {
11355
+ with: {
11356
+ resources: true
11357
+ }
11358
+ }
11359
+ }
11360
+ }
11361
+ }
11362
+ }
11363
+ });
11364
+ const parsedProduct = productSchema.safeParse(productData);
11365
+ if (!parsedProduct.success) {
11366
+ console.error("Error parsing product", JSON.stringify(parsedProduct.error), JSON.stringify(productData));
11367
+ return null;
11368
+ }
11369
+ return parsedProduct.data;
11370
+ } catch (e) {
11371
+ console.log("getProduct error", e);
11372
+ return null;
11373
+ }
11374
+ },
11375
+ async getProductResources(productId) {
11376
+ const contentResourceProductsForProduct = z.array(ContentResourceProductSchema).nullable().parse(await client.query.contentResourceProduct.findMany({
11377
+ where: (0, import_drizzle_orm32.eq)(contentResourceProduct.productId, productId)
11378
+ }));
11379
+ if (!contentResourceProductsForProduct) {
11380
+ return null;
11381
+ } else {
11382
+ const contentResources = z.array(ContentResourceSchema).parse(await client.query.contentResource.findMany({
11383
+ where: (0, import_drizzle_orm32.inArray)(contentResource.id, contentResourceProductsForProduct.map((crp) => crp.resourceId))
11384
+ }));
11385
+ return contentResources;
11386
+ }
11163
11387
  },
11164
11388
  async getPurchaseCountForProduct(productId) {
11165
11389
  return await client.query.purchases.findMany({
@@ -11192,7 +11416,7 @@ function mySqlDrizzleAdapter(client, tableFn = import_mysql_core37.mysqlTable) {
11192
11416
  where: (0, import_drizzle_orm32.eq)(merchantCharge.identifier, stripeChargeId)
11193
11417
  }) || null);
11194
11418
  if (!chargeForPurchase) {
11195
- logger.error(new Error("No charge found for purchase"));
11419
+ logger.error(new Error(`No charge found for purchase: Stripe Charge ID: ${stripeChargeId}`));
11196
11420
  return null;
11197
11421
  }
11198
11422
  const purchase = purchaseSchema.safeParse(await client.query.purchases.findFirst({
@@ -11327,6 +11551,33 @@ function mySqlDrizzleAdapter(client, tableFn = import_mysql_core37.mysqlTable) {
11327
11551
  purchase: parsedPurchase.data
11328
11552
  };
11329
11553
  },
11554
+ async getUserWithPurchasersByEmail(email) {
11555
+ const user = await client.query.users.findFirst({
11556
+ where: (0, import_drizzle_orm32.eq)(users.email, email.trim().toLowerCase()),
11557
+ with: {
11558
+ // merchantCustomer: true,
11559
+ roles: {
11560
+ with: {
11561
+ role: true
11562
+ }
11563
+ },
11564
+ purchases: {
11565
+ with: {
11566
+ bulkCoupon: true,
11567
+ merchantCharge: true,
11568
+ product: {
11569
+ columns: {
11570
+ id: true,
11571
+ name: true,
11572
+ key: true
11573
+ }
11574
+ }
11575
+ }
11576
+ }
11577
+ }
11578
+ });
11579
+ return user;
11580
+ },
11330
11581
  async getUserById(userId) {
11331
11582
  const user = await client.query.users.findFirst({
11332
11583
  where: (0, import_drizzle_orm32.eq)(users.id, userId),
@@ -11403,8 +11654,40 @@ function mySqlDrizzleAdapter(client, tableFn = import_mysql_core37.mysqlTable) {
11403
11654
  transferPurchasesToNewUser(options) {
11404
11655
  throw new Error("Method not implemented.");
11405
11656
  },
11406
- updatePurchaseStatusForCharge(chargeId, status) {
11407
- throw new Error("updatePurchaseStatusForCharge Method not implemented.");
11657
+ async updatePurchaseStatusForCharge(chargeId, status) {
11658
+ try {
11659
+ console.log("updatePurchaseStatusForCharge", {
11660
+ chargeId,
11661
+ status
11662
+ });
11663
+ const merchantChargeForPurchase = await client.query.merchantCharge.findFirst({
11664
+ where: (0, import_drizzle_orm32.or)((0, import_drizzle_orm32.eq)(merchantCharge.identifier, chargeId), (0, import_drizzle_orm32.eq)(merchantCharge.id, chargeId))
11665
+ });
11666
+ console.log("merchantChargeForPurchase", {
11667
+ merchantChargeForPurchase
11668
+ });
11669
+ const parsedMerchantChargeForPurchase = merchantChargeSchema.parse(merchantChargeForPurchase);
11670
+ if (!parsedMerchantChargeForPurchase)
11671
+ throw new Error(`no-charge-found-for-purchase ${chargeId}`);
11672
+ const purchase = await client.query.purchases.findFirst({
11673
+ where: (0, import_drizzle_orm32.eq)(purchaseTable.merchantChargeId, parsedMerchantChargeForPurchase.id)
11674
+ });
11675
+ const parsedPurchase = purchaseSchema.nullable().parse(purchase);
11676
+ if (parsedPurchase) {
11677
+ await client.update(purchaseTable).set({
11678
+ status
11679
+ }).where((0, import_drizzle_orm32.eq)(purchaseTable.id, parsedPurchase.id));
11680
+ const newPurchase = await client.query.purchases.findFirst({
11681
+ where: (0, import_drizzle_orm32.eq)(purchaseTable.id, parsedPurchase.id)
11682
+ });
11683
+ return purchaseSchema.optional().parse(newPurchase);
11684
+ } else {
11685
+ throw new Error(`no-purchase-found-for-charge ${chargeId}`);
11686
+ }
11687
+ } catch (e) {
11688
+ console.log("error updating purchase status", e);
11689
+ throw e;
11690
+ }
11408
11691
  },
11409
11692
  async updatePurchaseUserTransferTransferState(options) {
11410
11693
  await client.update(purchaseUserTransfer).set({
@@ -11441,6 +11724,18 @@ function mySqlDrizzleAdapter(client, tableFn = import_mysql_core37.mysqlTable) {
11441
11724
  }
11442
11725
  return parsedResourceJoin.data;
11443
11726
  },
11727
+ async removeResourceFromResource(options) {
11728
+ const { childResourceId, parentResourceId } = options;
11729
+ const resourceJoin = await client.query.contentResourceResource.findFirst({
11730
+ where: (0, import_drizzle_orm32.and)((0, import_drizzle_orm32.eq)(contentResourceResource.resourceOfId, parentResourceId), (0, import_drizzle_orm32.eq)(contentResourceResource.resourceId, childResourceId))
11731
+ });
11732
+ const parsedResourceJoin = ContentResourceResourceSchema.safeParse(resourceJoin);
11733
+ if (!parsedResourceJoin.success) {
11734
+ return null;
11735
+ }
11736
+ await client.delete(contentResourceResource).where((0, import_drizzle_orm32.and)((0, import_drizzle_orm32.eq)(contentResourceResource.resourceOfId, parentResourceId), (0, import_drizzle_orm32.eq)(contentResourceResource.resourceId, childResourceId)));
11737
+ return parsedResourceJoin.data.resource;
11738
+ },
11444
11739
  async updateContentResourceFields(options) {
11445
11740
  if (!options.id) {
11446
11741
  throw new Error("No content resource id.");
@@ -11675,6 +11970,7 @@ __name(mySqlDrizzleAdapter, "mySqlDrizzleAdapter");
11675
11970
  0 && (module.exports = {
11676
11971
  createTables,
11677
11972
  getCourseBuilderSchema,
11973
+ guid,
11678
11974
  mySqlDrizzleAdapter
11679
11975
  });
11680
11976
  //# sourceMappingURL=index.cjs.map