@timardex/cluemart-server-shared 5.1.0 → 5.3.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.
@@ -11,7 +11,7 @@ import {
11
11
  PushTokenModel,
12
12
  UserModel,
13
13
  VendorModel
14
- } from "../chunk-MYZL22GL.mjs";
14
+ } from "../chunk-JYBS6IOE.mjs";
15
15
  import "../chunk-F54NB7VH.mjs";
16
16
 
17
17
  // src/service/promoCode/constants.ts
@@ -488,6 +488,38 @@ var ASSOCIABLE_MODELS = {
488
488
  [EnumResourceType2.PARTNER]: PartnerModel,
489
489
  [EnumResourceType2.VENDOR]: VendorModel
490
490
  };
491
+ function pinAssociateTimestamp(value) {
492
+ return value == null ? null : { $in: [value, null] };
493
+ }
494
+ function buildAssociatesWriteGuard({
495
+ canManage,
496
+ nextAssociates,
497
+ snapshot
498
+ }) {
499
+ if (!canManage) {
500
+ return null;
501
+ }
502
+ const previous = snapshot ?? [];
503
+ const emptyListFilter = {
504
+ $or: [{ associates: { $size: 0 } }, { associates: null }]
505
+ };
506
+ return {
507
+ filter: previous.length > 0 ? {
508
+ $and: previous.map((associate) => ({
509
+ associates: {
510
+ $elemMatch: {
511
+ addedAt: pinAssociateTimestamp(associate.addedAt),
512
+ respondedAt: pinAssociateTimestamp(associate.respondedAt),
513
+ status: associate.status,
514
+ userId: associate.userId
515
+ }
516
+ }
517
+ })),
518
+ associates: { $size: previous.length }
519
+ } : emptyListFilter,
520
+ update: { associates: nextAssociates }
521
+ };
522
+ }
491
523
  function acceptedAssociateUserIds(associates) {
492
524
  return (associates ?? []).filter((associate) => associate.status === EnumAssociateStatus.ACCEPTED).map((associate) => associate.userId);
493
525
  }
@@ -527,7 +559,10 @@ async function acceptedUserIdsForResource({
527
559
  resourceType
528
560
  }) {
529
561
  const model = ASSOCIABLE_MODELS[resourceType];
530
- const resource = await model.findOne({ _id: resourceId, deletedAt: null }).select("associates").lean().exec();
562
+ const resource = await model.findOne({ _id: resourceId, deletedAt: null }).select("associates featuresDowngraded").lean().exec();
563
+ if (resource?.featuresDowngraded) {
564
+ return /* @__PURE__ */ new Set();
565
+ }
531
566
  return new Set(
532
567
  acceptedAssociateUserIds(resource?.associates).map(
533
568
  (userId) => String(userId)
@@ -677,12 +712,12 @@ async function reconcileUserBatch({
677
712
  _id: {
678
713
  $in: [...heldByResource.values()].map((entry) => entry.resourceId)
679
714
  }
680
- }).select("associates deletedAt").lean().exec();
715
+ }).select("associates deletedAt featuresDowngraded").lean().exec();
681
716
  const acceptedByResource = /* @__PURE__ */ new Map();
682
717
  for (const resource of resources) {
683
718
  acceptedByResource.set(
684
719
  String(resource._id),
685
- resource.deletedAt ? /* @__PURE__ */ new Set() : new Set(
720
+ resource.deletedAt || resource.featuresDowngraded ? /* @__PURE__ */ new Set() : new Set(
686
721
  acceptedAssociateUserIds(resource.associates).map(
687
722
  (userId) => String(userId)
688
723
  )
@@ -1764,17 +1799,19 @@ import {
1764
1799
  EnumSubscriptionStatus as EnumSubscriptionStatus2,
1765
1800
  EnumUserLicence as EnumUserLicence5,
1766
1801
  isNonVisitorResourceType,
1802
+ isProLicenceType,
1803
+ isStandardLicenceType,
1767
1804
  LicenceExpiryDate
1768
1805
  } from "@timardex/cluemart-shared";
1769
1806
  import dayjs5 from "dayjs";
1770
1807
  import { GraphQLError } from "graphql";
1771
- var LicenceCategory = /* @__PURE__ */ ((LicenceCategory3) => {
1772
- LicenceCategory3["EVENT"] = "event";
1773
- LicenceCategory3["PARTNER"] = "partner";
1774
- LicenceCategory3["VENDOR"] = "vendor";
1775
- LicenceCategory3["AFFILIATE"] = "affiliate";
1776
- LicenceCategory3["SCHOOL"] = "school";
1777
- return LicenceCategory3;
1808
+ var LicenceCategory = /* @__PURE__ */ ((LicenceCategory2) => {
1809
+ LicenceCategory2["EVENT"] = "event";
1810
+ LicenceCategory2["PARTNER"] = "partner";
1811
+ LicenceCategory2["VENDOR"] = "vendor";
1812
+ LicenceCategory2["AFFILIATE"] = "affiliate";
1813
+ LicenceCategory2["SCHOOL"] = "school";
1814
+ return LicenceCategory2;
1778
1815
  })(LicenceCategory || {});
1779
1816
  var licenceCategoryMapping = {
1780
1817
  [EnumUserLicence5.PRO_EVENT]: "event" /* EVENT */,
@@ -1798,25 +1835,8 @@ var licencePriority = {
1798
1835
  [EnumUserLicence5.STANDARD_AFFILIATE]: 1,
1799
1836
  [EnumUserLicence5.STANDARD_SCHOOL]: 1
1800
1837
  };
1801
- var standardLicences = [
1802
- EnumUserLicence5.STANDARD_VENDOR,
1803
- EnumUserLicence5.STANDARD_EVENT,
1804
- EnumUserLicence5.STANDARD_PARTNER
1805
- ];
1806
- var standardLicenceSet = new Set(standardLicences);
1807
- function isStandardLicence(licence) {
1808
- return standardLicenceSet.has(licence);
1809
- }
1810
- var proLicences = [
1811
- EnumUserLicence5.PRO_EVENT,
1812
- EnumUserLicence5.PRO_PLUS_EVENT,
1813
- EnumUserLicence5.PRO_VENDOR,
1814
- EnumUserLicence5.PRO_PLUS_VENDOR
1815
- ];
1816
- var proLicenceSet = new Set(proLicences);
1817
- function isProLicence(licence) {
1818
- return proLicenceSet.has(licence);
1819
- }
1838
+ var isStandardLicence = isStandardLicenceType;
1839
+ var isProLicence = isProLicenceType;
1820
1840
  var categoryRegexMapping = {
1821
1841
  ["event" /* EVENT */]: /_event$/,
1822
1842
  ["partner" /* PARTNER */]: /_partner$/,
@@ -2139,30 +2159,134 @@ async function findUserVendor(userId, logLabel) {
2139
2159
  }
2140
2160
  return vendor;
2141
2161
  }
2162
+ async function downgradeStillApplies(ownerUserId) {
2163
+ const hasActiveProLicence = await hasActiveProLicenceForResource({
2164
+ includeStripeProtected: true,
2165
+ resourceType: EnumResourceType4.VENDOR,
2166
+ userId: ownerUserId
2167
+ });
2168
+ return !hasActiveProLicence;
2169
+ }
2142
2170
  async function applyVendorDowngrade(vendor, ownerUserId) {
2143
- const updateData = {};
2144
- updateData.availability = {
2145
- corporate: false,
2146
- private: false,
2147
- school: false
2148
- };
2149
- updateData.products = {
2150
- active: false,
2151
- productsList: vendor.products?.productsList ?? []
2152
- };
2153
- updateData.calendar = {
2154
- active: false,
2155
- calendarData: vendor.calendar?.calendarData ?? []
2156
- };
2157
- updateData.downgradeSnapshot = {
2158
- availability: vendor.availability,
2159
- calendarActive: vendor.calendar?.active,
2160
- productsActive: vendor.products?.active
2171
+ let current = vendor;
2172
+ for (let attempt = 0; attempt < 2; attempt += 1) {
2173
+ if (!await downgradeStillApplies(ownerUserId)) {
2174
+ console.info(
2175
+ "[applyVendorDowngrade] owner holds an active PRO licence again; skipping the downgrade",
2176
+ { vendorId: String(current._id) }
2177
+ );
2178
+ return "skipped";
2179
+ }
2180
+ const associatesGuard = buildAssociatesWriteGuard({
2181
+ canManage: true,
2182
+ nextAssociates: [],
2183
+ snapshot: current.associates
2184
+ });
2185
+ if (!associatesGuard) {
2186
+ return "skipped";
2187
+ }
2188
+ const result = await VendorModel.updateOne(
2189
+ {
2190
+ _id: current._id,
2191
+ active: true,
2192
+ deletedAt: null,
2193
+ // Already downgraded: another run got there first and its snapshot is
2194
+ // the original state this one must not overwrite.
2195
+ featuresDowngraded: { $ne: true },
2196
+ // Upgrades bump this in their own write; `null` covers vendors that
2197
+ // predate the field.
2198
+ licenceEpoch: { $in: [current.licenceEpoch ?? 0, null] },
2199
+ "owner.userId": ownerUserId,
2200
+ ...associatesGuard.filter
2201
+ },
2202
+ {
2203
+ $inc: { licenceEpoch: 1 },
2204
+ $set: {
2205
+ ...associatesGuard.update,
2206
+ availability: {
2207
+ corporate: false,
2208
+ private: false,
2209
+ school: false
2210
+ },
2211
+ calendar: {
2212
+ active: false,
2213
+ calendarData: current.calendar?.calendarData ?? []
2214
+ },
2215
+ downgradeSnapshot: {
2216
+ availability: current.availability,
2217
+ calendarActive: current.calendar?.active,
2218
+ productsActive: current.products?.active
2219
+ },
2220
+ featuresDowngraded: true,
2221
+ // STANDARD_VENDOR keeps only the first 6 images active.
2222
+ images: (current.images ?? []).map((image, index) => ({
2223
+ ...image,
2224
+ active: index < 6
2225
+ })),
2226
+ products: {
2227
+ active: false,
2228
+ productsList: current.products?.productsList ?? []
2229
+ }
2230
+ }
2231
+ }
2232
+ );
2233
+ if ((result?.matchedCount ?? 0) > 0) {
2234
+ break;
2235
+ }
2236
+ const fresh = await VendorModel.findById(current._id).lean().exec();
2237
+ if (!fresh) {
2238
+ return "skipped";
2239
+ }
2240
+ if (fresh.featuresDowngraded === true) {
2241
+ console.info(
2242
+ "[applyVendorDowngrade] vendor is already downgraded; licence sync can proceed",
2243
+ { vendorId: String(fresh._id) }
2244
+ );
2245
+ return "already-downgraded";
2246
+ }
2247
+ current = fresh;
2248
+ if (attempt === 1) {
2249
+ console.warn(
2250
+ "[applyVendorDowngrade] vendor changed under the downgrade; left to the next compliance run",
2251
+ { vendorId: String(current._id) }
2252
+ );
2253
+ return "skipped";
2254
+ }
2255
+ }
2256
+ try {
2257
+ await detachStaleAssociateGrants({
2258
+ acceptedUserIds: [],
2259
+ resourceId: current._id,
2260
+ resourceType: EnumResourceType4.VENDOR
2261
+ });
2262
+ } catch (error) {
2263
+ console.error(
2264
+ "[applyVendorDowngrade] grant detach failed; left to reconciliation",
2265
+ error
2266
+ );
2267
+ }
2268
+ return "applied";
2269
+ }
2270
+ async function applyVendorRestore(vendor, ownerUserId) {
2271
+ const snapshot = vendor.downgradeSnapshot;
2272
+ const updateData = {
2273
+ availability: {
2274
+ corporate: snapshot?.availability?.corporate ?? true,
2275
+ private: snapshot?.availability?.private ?? true,
2276
+ school: snapshot?.availability?.school ?? true
2277
+ },
2278
+ calendar: {
2279
+ active: snapshot?.calendarActive ?? true,
2280
+ calendarData: vendor.calendar?.calendarData ?? []
2281
+ },
2282
+ downgradeNotifiedAt: null,
2283
+ featuresDowngraded: false,
2284
+ images: (vendor.images ?? []).map((image) => ({ ...image, active: true })),
2285
+ products: {
2286
+ active: snapshot?.productsActive ?? true,
2287
+ productsList: vendor.products?.productsList ?? []
2288
+ }
2161
2289
  };
2162
- updateData.images = (vendor.images ?? []).map((image, index) => ({
2163
- ...image,
2164
- active: index < 6
2165
- }));
2166
2290
  const result = await VendorModel.updateOne(
2167
2291
  {
2168
2292
  _id: vendor._id,
@@ -2170,7 +2294,7 @@ async function applyVendorDowngrade(vendor, ownerUserId) {
2170
2294
  deletedAt: null,
2171
2295
  "owner.userId": ownerUserId
2172
2296
  },
2173
- { $set: updateData }
2297
+ { $inc: { licenceEpoch: 1 }, $set: updateData }
2174
2298
  );
2175
2299
  return (result?.matchedCount ?? 0) > 0;
2176
2300
  }
@@ -2190,37 +2314,6 @@ async function downgradeVendorProFeatures(userId, licenceType) {
2190
2314
  throw error;
2191
2315
  }
2192
2316
  }
2193
- async function applyVendorRestore(vendor, ownerUserId) {
2194
- const updateData = {};
2195
- const snapshot = vendor.downgradeSnapshot;
2196
- updateData.availability = {
2197
- corporate: snapshot?.availability?.corporate ?? true,
2198
- private: snapshot?.availability?.private ?? true,
2199
- school: snapshot?.availability?.school ?? true
2200
- };
2201
- updateData.products = {
2202
- active: snapshot?.productsActive ?? true,
2203
- productsList: vendor.products?.productsList ?? []
2204
- };
2205
- updateData.calendar = {
2206
- active: snapshot?.calendarActive ?? true,
2207
- calendarData: vendor.calendar?.calendarData ?? []
2208
- };
2209
- updateData.images = (vendor.images ?? []).map((image) => ({
2210
- ...image,
2211
- active: true
2212
- }));
2213
- const result = await VendorModel.updateOne(
2214
- {
2215
- _id: vendor._id,
2216
- active: true,
2217
- deletedAt: null,
2218
- "owner.userId": ownerUserId
2219
- },
2220
- { $set: updateData }
2221
- );
2222
- return (result?.matchedCount ?? 0) > 0;
2223
- }
2224
2317
  async function restoreVendorProFeatures(userId, licenceType) {
2225
2318
  const isProVendor = licenceType === EnumUserLicence6.PRO_VENDOR || licenceType === EnumUserLicence6.PRO_PLUS_VENDOR;
2226
2319
  if (!isProVendor) {
@@ -2237,6 +2330,61 @@ async function restoreVendorProFeatures(userId, licenceType) {
2237
2330
  throw error;
2238
2331
  }
2239
2332
  }
2333
+ var NOTIFICATION_CLAIM_LEASE_MS = 60 * 60 * 1e3;
2334
+ async function notifyVendorDowngrade(vendorId, ownerUserId) {
2335
+ if (!await downgradeStillApplies(ownerUserId)) {
2336
+ return false;
2337
+ }
2338
+ const claimedAt = /* @__PURE__ */ new Date();
2339
+ const claimed = await VendorModel.findOneAndUpdate(
2340
+ {
2341
+ $or: [
2342
+ { downgradeNotifiedAt: null },
2343
+ {
2344
+ downgradeNotifiedAt: {
2345
+ $lt: new Date(claimedAt.getTime() - NOTIFICATION_CLAIM_LEASE_MS)
2346
+ }
2347
+ }
2348
+ ],
2349
+ _id: vendorId,
2350
+ active: true,
2351
+ deletedAt: null,
2352
+ // A re-upgrade that restored the vendor has flipped this back, so its
2353
+ // owner is not told about a downgrade that no longer holds.
2354
+ featuresDowngraded: true
2355
+ },
2356
+ { $set: { downgradeNotifiedAt: claimedAt } },
2357
+ { new: false }
2358
+ ).lean().exec();
2359
+ if (!claimed) {
2360
+ return false;
2361
+ }
2362
+ const sent = await sendDeactivationNotification(
2363
+ {
2364
+ data: {
2365
+ resourceId: String(claimed._id),
2366
+ resourceName: claimed.name,
2367
+ resourceType: EnumNotificationResourceType2.DOWNGRADED_VENDOR
2368
+ },
2369
+ message: `Your Vendor licence has been downgraded due to licence expiration.`,
2370
+ title: `Vendor Licence Downgraded`,
2371
+ type: EnumNotificationType2.SYSTEM,
2372
+ userIds: [ownerUserId]
2373
+ },
2374
+ ownerUserId,
2375
+ claimed.name,
2376
+ "vendor",
2377
+ claimed.downgradeNotifiedAt ?? null
2378
+ );
2379
+ if (sent) {
2380
+ return true;
2381
+ }
2382
+ await VendorModel.updateOne(
2383
+ { _id: vendorId, downgradeNotifiedAt: claimedAt },
2384
+ { $set: { downgradeNotifiedAt: null } }
2385
+ );
2386
+ return false;
2387
+ }
2240
2388
  async function handleVendorLicenceCompliance(user, now) {
2241
2389
  if (!user.licences || !user.vendor) {
2242
2390
  return;
@@ -2247,10 +2395,10 @@ async function handleVendorLicenceCompliance(user, now) {
2247
2395
  if (vendorLicencesOfUser.length === 0) {
2248
2396
  return;
2249
2397
  }
2250
- const proLicences2 = vendorLicencesOfUser.filter(
2398
+ const proLicences = vendorLicencesOfUser.filter(
2251
2399
  (licence) => licence.licenceType !== EnumUserLicence6.STANDARD_VENDOR
2252
2400
  );
2253
- const expiredProLicences = proLicences2.filter(
2401
+ const expiredProLicences = proLicences.filter(
2254
2402
  (licence) => !dayjs6(licence.expiryDate).isAfter(now)
2255
2403
  );
2256
2404
  const stripeProtectedLicenceTypes = new Set(
@@ -2261,7 +2409,7 @@ async function handleVendorLicenceCompliance(user, now) {
2261
2409
  const expiredProLicence = expiredProLicences.some(
2262
2410
  (licence) => !stripeProtectedLicenceTypes.has(licence.licenceType)
2263
2411
  );
2264
- const hasValidProLicence = stripeProtectedLicenceTypes.size > 0 || hasValidLicence(proLicences2, vendorLicences, now);
2412
+ const hasValidProLicence = stripeProtectedLicenceTypes.size > 0 || hasValidLicence(proLicences, vendorLicences, now);
2265
2413
  const hasExpiredVendorLicence = vendorLicencesOfUser.some(
2266
2414
  (licence) => !dayjs6(licence.expiryDate).isAfter(now) && !stripeProtectedLicenceTypes.has(licence.licenceType)
2267
2415
  );
@@ -2277,29 +2425,27 @@ async function handleVendorLicenceCompliance(user, now) {
2277
2425
  "owner.userId": user._id
2278
2426
  }).lean().exec();
2279
2427
  }
2428
+ const needsDowngrade = expiredProLicence && Boolean(vendor) && !hasValidProLicence;
2429
+ const outcome = needsDowngrade && vendor ? await applyVendorDowngrade(vendor, user._id) : "skipped";
2280
2430
  const licencesToSync = vendorLicences.filter(
2281
2431
  (licenceType) => !stripeProtectedLicenceTypes.has(licenceType)
2282
2432
  );
2283
- await syncUserLicencesAfterExpiry(user._id, licencesToSync, now, "downgrade");
2284
- if (!expiredProLicence || !vendor || hasValidProLicence) {
2433
+ if (!needsDowngrade) {
2434
+ await syncUserLicencesAfterExpiry(
2435
+ user._id,
2436
+ licencesToSync,
2437
+ now,
2438
+ "downgrade"
2439
+ );
2285
2440
  return;
2286
2441
  }
2287
- const downgraded = await applyVendorDowngrade(vendor, user._id);
2288
- if (!downgraded) {
2442
+ if (outcome === "skipped" || !vendor) {
2289
2443
  return;
2290
2444
  }
2291
- const payload = {
2292
- data: {
2293
- resourceId: String(vendor._id),
2294
- resourceName: vendor.name,
2295
- resourceType: EnumNotificationResourceType2.DOWNGRADED_VENDOR
2296
- },
2297
- message: `Your Vendor licence has been downgraded due to licence expiration.`,
2298
- title: `Vendor Licence Downgraded`,
2299
- type: EnumNotificationType2.SYSTEM,
2300
- userIds: [user._id]
2301
- };
2302
- await sendDeactivationNotification(payload, user._id, vendor.name, "vendor");
2445
+ if (!await notifyVendorDowngrade(vendor._id, user._id)) {
2446
+ return;
2447
+ }
2448
+ await syncUserLicencesAfterExpiry(user._id, licencesToSync, now, "downgrade");
2303
2449
  }
2304
2450
  async function vendorOwnerHasProLicence(vendorId) {
2305
2451
  const vendor = await VendorModel.findOne({
@@ -2344,17 +2490,35 @@ function hasValidLicence(licences, licenceTypes, now) {
2344
2490
  (licence) => licenceTypes.includes(licence.licenceType) && dayjs7(licence.expiryDate).isAfter(now)
2345
2491
  );
2346
2492
  }
2347
- async function sendDeactivationNotification(payload, userId, resourceName, resourceType) {
2493
+ async function deactivationNoticeStored(payload, userId, since) {
2494
+ const stored = await NotificationModel.exists({
2495
+ createdAt: { $gte: since },
2496
+ "data.resourceId": payload.data.resourceId,
2497
+ "data.resourceType": payload.data.resourceType,
2498
+ title: payload.title,
2499
+ type: payload.type,
2500
+ userId
2501
+ });
2502
+ return stored !== null;
2503
+ }
2504
+ async function sendDeactivationNotification(payload, userId, resourceName, resourceType, retryOf = null) {
2505
+ if (retryOf && await deactivationNoticeStored(payload, userId, retryOf)) {
2506
+ console.log(
2507
+ `\u{1F501} ${resourceType} notification already stored for user ${String(userId)} for "${resourceName}"`
2508
+ );
2509
+ return true;
2510
+ }
2348
2511
  const sent = await notifyUsers({ payload });
2349
2512
  if (!sent) {
2350
2513
  console.error(
2351
2514
  `\u274C ${resourceType} notification not confirmed for user ${String(userId)} for "${resourceName}"`
2352
2515
  );
2353
- return;
2516
+ return false;
2354
2517
  }
2355
2518
  console.log(
2356
2519
  `\u2705 Sent ${resourceType} notification to user ${String(userId)} for "${resourceName}"`
2357
2520
  );
2521
+ return true;
2358
2522
  }
2359
2523
  async function processUserCompliance(user, now) {
2360
2524
  if (!user.licences) {
@@ -2737,6 +2901,7 @@ export {
2737
2901
  acceptedAssociateUserIds,
2738
2902
  activeAffiliateCodeExists,
2739
2903
  awardAffiliateVendorSubscriptionRewards,
2904
+ buildAssociatesWriteGuard,
2740
2905
  buildLicenceExpiryPipeline,
2741
2906
  buildUserHasEnoughPointsFilter,
2742
2907
  buildUserPointAwardEntry,
@@ -2794,6 +2959,7 @@ export {
2794
2959
  notifyUsers,
2795
2960
  partnerLicences,
2796
2961
  persistArchivedEventDates,
2962
+ pinAssociateTimestamp,
2797
2963
  processLicenseReminder,
2798
2964
  processUserCompliance,
2799
2965
  processUserLicenseReminders,