@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.
package/dist/index.mjs CHANGED
@@ -2102,8 +2102,11 @@ var schema17 = new MongooseSchema18(
2102
2102
  categories: { required: true, type: [CategorySchema] },
2103
2103
  categoriesNames: { default: [], required: false, type: [String] },
2104
2104
  claimed: { default: true, required: false, type: Boolean },
2105
+ downgradeNotifiedAt: { default: null, required: false, type: Date },
2105
2106
  downgradeSnapshot: { required: false, type: downgradeSnapshotSchema },
2107
+ featuresDowngraded: { default: false, required: false, type: Boolean },
2106
2108
  foodTruck: { required: true, type: Boolean },
2109
+ licenceEpoch: { default: 0, required: false, type: Number },
2107
2110
  products: { required: false, type: productWrapperSchema },
2108
2111
  shareRelation: { required: false, type: socialShareResourceSchema },
2109
2112
  unregisteredVendorId: {
@@ -3463,6 +3466,38 @@ var ASSOCIABLE_MODELS = {
3463
3466
  [EnumResourceType10.PARTNER]: PartnerModel,
3464
3467
  [EnumResourceType10.VENDOR]: VendorModel
3465
3468
  };
3469
+ function pinAssociateTimestamp(value) {
3470
+ return value == null ? null : { $in: [value, null] };
3471
+ }
3472
+ function buildAssociatesWriteGuard({
3473
+ canManage,
3474
+ nextAssociates,
3475
+ snapshot
3476
+ }) {
3477
+ if (!canManage) {
3478
+ return null;
3479
+ }
3480
+ const previous = snapshot ?? [];
3481
+ const emptyListFilter = {
3482
+ $or: [{ associates: { $size: 0 } }, { associates: null }]
3483
+ };
3484
+ return {
3485
+ filter: previous.length > 0 ? {
3486
+ $and: previous.map((associate) => ({
3487
+ associates: {
3488
+ $elemMatch: {
3489
+ addedAt: pinAssociateTimestamp(associate.addedAt),
3490
+ respondedAt: pinAssociateTimestamp(associate.respondedAt),
3491
+ status: associate.status,
3492
+ userId: associate.userId
3493
+ }
3494
+ }
3495
+ })),
3496
+ associates: { $size: previous.length }
3497
+ } : emptyListFilter,
3498
+ update: { associates: nextAssociates }
3499
+ };
3500
+ }
3466
3501
  function acceptedAssociateUserIds(associates) {
3467
3502
  return (associates ?? []).filter((associate) => associate.status === EnumAssociateStatus2.ACCEPTED).map((associate) => associate.userId);
3468
3503
  }
@@ -3502,7 +3537,10 @@ async function acceptedUserIdsForResource({
3502
3537
  resourceType
3503
3538
  }) {
3504
3539
  const model = ASSOCIABLE_MODELS[resourceType];
3505
- const resource = await model.findOne({ _id: resourceId, deletedAt: null }).select("associates").lean().exec();
3540
+ const resource = await model.findOne({ _id: resourceId, deletedAt: null }).select("associates featuresDowngraded").lean().exec();
3541
+ if (resource?.featuresDowngraded) {
3542
+ return /* @__PURE__ */ new Set();
3543
+ }
3506
3544
  return new Set(
3507
3545
  acceptedAssociateUserIds(resource?.associates).map(
3508
3546
  (userId) => String(userId)
@@ -3652,12 +3690,12 @@ async function reconcileUserBatch({
3652
3690
  _id: {
3653
3691
  $in: [...heldByResource.values()].map((entry) => entry.resourceId)
3654
3692
  }
3655
- }).select("associates deletedAt").lean().exec();
3693
+ }).select("associates deletedAt featuresDowngraded").lean().exec();
3656
3694
  const acceptedByResource = /* @__PURE__ */ new Map();
3657
3695
  for (const resource of resources) {
3658
3696
  acceptedByResource.set(
3659
3697
  String(resource._id),
3660
- resource.deletedAt ? /* @__PURE__ */ new Set() : new Set(
3698
+ resource.deletedAt || resource.featuresDowngraded ? /* @__PURE__ */ new Set() : new Set(
3661
3699
  acceptedAssociateUserIds(resource.associates).map(
3662
3700
  (userId) => String(userId)
3663
3701
  )
@@ -4750,17 +4788,19 @@ import {
4750
4788
  EnumSubscriptionStatus as EnumSubscriptionStatus3,
4751
4789
  EnumUserLicence as EnumUserLicence8,
4752
4790
  isNonVisitorResourceType,
4791
+ isProLicenceType,
4792
+ isStandardLicenceType,
4753
4793
  LicenceExpiryDate
4754
4794
  } from "@timardex/cluemart-shared";
4755
4795
  import dayjs5 from "dayjs";
4756
4796
  import { GraphQLError } from "graphql";
4757
- var LicenceCategory = /* @__PURE__ */ ((LicenceCategory3) => {
4758
- LicenceCategory3["EVENT"] = "event";
4759
- LicenceCategory3["PARTNER"] = "partner";
4760
- LicenceCategory3["VENDOR"] = "vendor";
4761
- LicenceCategory3["AFFILIATE"] = "affiliate";
4762
- LicenceCategory3["SCHOOL"] = "school";
4763
- return LicenceCategory3;
4797
+ var LicenceCategory = /* @__PURE__ */ ((LicenceCategory2) => {
4798
+ LicenceCategory2["EVENT"] = "event";
4799
+ LicenceCategory2["PARTNER"] = "partner";
4800
+ LicenceCategory2["VENDOR"] = "vendor";
4801
+ LicenceCategory2["AFFILIATE"] = "affiliate";
4802
+ LicenceCategory2["SCHOOL"] = "school";
4803
+ return LicenceCategory2;
4764
4804
  })(LicenceCategory || {});
4765
4805
  var licenceCategoryMapping = {
4766
4806
  [EnumUserLicence8.PRO_EVENT]: "event" /* EVENT */,
@@ -4784,25 +4824,8 @@ var licencePriority = {
4784
4824
  [EnumUserLicence8.STANDARD_AFFILIATE]: 1,
4785
4825
  [EnumUserLicence8.STANDARD_SCHOOL]: 1
4786
4826
  };
4787
- var standardLicences = [
4788
- EnumUserLicence8.STANDARD_VENDOR,
4789
- EnumUserLicence8.STANDARD_EVENT,
4790
- EnumUserLicence8.STANDARD_PARTNER
4791
- ];
4792
- var standardLicenceSet = new Set(standardLicences);
4793
- function isStandardLicence(licence) {
4794
- return standardLicenceSet.has(licence);
4795
- }
4796
- var proLicences = [
4797
- EnumUserLicence8.PRO_EVENT,
4798
- EnumUserLicence8.PRO_PLUS_EVENT,
4799
- EnumUserLicence8.PRO_VENDOR,
4800
- EnumUserLicence8.PRO_PLUS_VENDOR
4801
- ];
4802
- var proLicenceSet = new Set(proLicences);
4803
- function isProLicence(licence) {
4804
- return proLicenceSet.has(licence);
4805
- }
4827
+ var isStandardLicence = isStandardLicenceType;
4828
+ var isProLicence = isProLicenceType;
4806
4829
  var categoryRegexMapping = {
4807
4830
  ["event" /* EVENT */]: /_event$/,
4808
4831
  ["partner" /* PARTNER */]: /_partner$/,
@@ -5125,30 +5148,134 @@ async function findUserVendor(userId, logLabel) {
5125
5148
  }
5126
5149
  return vendor;
5127
5150
  }
5151
+ async function downgradeStillApplies(ownerUserId) {
5152
+ const hasActiveProLicence = await hasActiveProLicenceForResource({
5153
+ includeStripeProtected: true,
5154
+ resourceType: EnumResourceType12.VENDOR,
5155
+ userId: ownerUserId
5156
+ });
5157
+ return !hasActiveProLicence;
5158
+ }
5128
5159
  async function applyVendorDowngrade(vendor, ownerUserId) {
5129
- const updateData = {};
5130
- updateData.availability = {
5131
- corporate: false,
5132
- private: false,
5133
- school: false
5134
- };
5135
- updateData.products = {
5136
- active: false,
5137
- productsList: vendor.products?.productsList ?? []
5138
- };
5139
- updateData.calendar = {
5140
- active: false,
5141
- calendarData: vendor.calendar?.calendarData ?? []
5142
- };
5143
- updateData.downgradeSnapshot = {
5144
- availability: vendor.availability,
5145
- calendarActive: vendor.calendar?.active,
5146
- productsActive: vendor.products?.active
5160
+ let current = vendor;
5161
+ for (let attempt = 0; attempt < 2; attempt += 1) {
5162
+ if (!await downgradeStillApplies(ownerUserId)) {
5163
+ console.info(
5164
+ "[applyVendorDowngrade] owner holds an active PRO licence again; skipping the downgrade",
5165
+ { vendorId: String(current._id) }
5166
+ );
5167
+ return "skipped";
5168
+ }
5169
+ const associatesGuard = buildAssociatesWriteGuard({
5170
+ canManage: true,
5171
+ nextAssociates: [],
5172
+ snapshot: current.associates
5173
+ });
5174
+ if (!associatesGuard) {
5175
+ return "skipped";
5176
+ }
5177
+ const result = await VendorModel.updateOne(
5178
+ {
5179
+ _id: current._id,
5180
+ active: true,
5181
+ deletedAt: null,
5182
+ // Already downgraded: another run got there first and its snapshot is
5183
+ // the original state this one must not overwrite.
5184
+ featuresDowngraded: { $ne: true },
5185
+ // Upgrades bump this in their own write; `null` covers vendors that
5186
+ // predate the field.
5187
+ licenceEpoch: { $in: [current.licenceEpoch ?? 0, null] },
5188
+ "owner.userId": ownerUserId,
5189
+ ...associatesGuard.filter
5190
+ },
5191
+ {
5192
+ $inc: { licenceEpoch: 1 },
5193
+ $set: {
5194
+ ...associatesGuard.update,
5195
+ availability: {
5196
+ corporate: false,
5197
+ private: false,
5198
+ school: false
5199
+ },
5200
+ calendar: {
5201
+ active: false,
5202
+ calendarData: current.calendar?.calendarData ?? []
5203
+ },
5204
+ downgradeSnapshot: {
5205
+ availability: current.availability,
5206
+ calendarActive: current.calendar?.active,
5207
+ productsActive: current.products?.active
5208
+ },
5209
+ featuresDowngraded: true,
5210
+ // STANDARD_VENDOR keeps only the first 6 images active.
5211
+ images: (current.images ?? []).map((image, index) => ({
5212
+ ...image,
5213
+ active: index < 6
5214
+ })),
5215
+ products: {
5216
+ active: false,
5217
+ productsList: current.products?.productsList ?? []
5218
+ }
5219
+ }
5220
+ }
5221
+ );
5222
+ if ((result?.matchedCount ?? 0) > 0) {
5223
+ break;
5224
+ }
5225
+ const fresh = await VendorModel.findById(current._id).lean().exec();
5226
+ if (!fresh) {
5227
+ return "skipped";
5228
+ }
5229
+ if (fresh.featuresDowngraded === true) {
5230
+ console.info(
5231
+ "[applyVendorDowngrade] vendor is already downgraded; licence sync can proceed",
5232
+ { vendorId: String(fresh._id) }
5233
+ );
5234
+ return "already-downgraded";
5235
+ }
5236
+ current = fresh;
5237
+ if (attempt === 1) {
5238
+ console.warn(
5239
+ "[applyVendorDowngrade] vendor changed under the downgrade; left to the next compliance run",
5240
+ { vendorId: String(current._id) }
5241
+ );
5242
+ return "skipped";
5243
+ }
5244
+ }
5245
+ try {
5246
+ await detachStaleAssociateGrants({
5247
+ acceptedUserIds: [],
5248
+ resourceId: current._id,
5249
+ resourceType: EnumResourceType12.VENDOR
5250
+ });
5251
+ } catch (error) {
5252
+ console.error(
5253
+ "[applyVendorDowngrade] grant detach failed; left to reconciliation",
5254
+ error
5255
+ );
5256
+ }
5257
+ return "applied";
5258
+ }
5259
+ async function applyVendorRestore(vendor, ownerUserId) {
5260
+ const snapshot = vendor.downgradeSnapshot;
5261
+ const updateData = {
5262
+ availability: {
5263
+ corporate: snapshot?.availability?.corporate ?? true,
5264
+ private: snapshot?.availability?.private ?? true,
5265
+ school: snapshot?.availability?.school ?? true
5266
+ },
5267
+ calendar: {
5268
+ active: snapshot?.calendarActive ?? true,
5269
+ calendarData: vendor.calendar?.calendarData ?? []
5270
+ },
5271
+ downgradeNotifiedAt: null,
5272
+ featuresDowngraded: false,
5273
+ images: (vendor.images ?? []).map((image) => ({ ...image, active: true })),
5274
+ products: {
5275
+ active: snapshot?.productsActive ?? true,
5276
+ productsList: vendor.products?.productsList ?? []
5277
+ }
5147
5278
  };
5148
- updateData.images = (vendor.images ?? []).map((image, index) => ({
5149
- ...image,
5150
- active: index < 6
5151
- }));
5152
5279
  const result = await VendorModel.updateOne(
5153
5280
  {
5154
5281
  _id: vendor._id,
@@ -5156,7 +5283,7 @@ async function applyVendorDowngrade(vendor, ownerUserId) {
5156
5283
  deletedAt: null,
5157
5284
  "owner.userId": ownerUserId
5158
5285
  },
5159
- { $set: updateData }
5286
+ { $inc: { licenceEpoch: 1 }, $set: updateData }
5160
5287
  );
5161
5288
  return (result?.matchedCount ?? 0) > 0;
5162
5289
  }
@@ -5176,37 +5303,6 @@ async function downgradeVendorProFeatures(userId, licenceType) {
5176
5303
  throw error;
5177
5304
  }
5178
5305
  }
5179
- async function applyVendorRestore(vendor, ownerUserId) {
5180
- const updateData = {};
5181
- const snapshot = vendor.downgradeSnapshot;
5182
- updateData.availability = {
5183
- corporate: snapshot?.availability?.corporate ?? true,
5184
- private: snapshot?.availability?.private ?? true,
5185
- school: snapshot?.availability?.school ?? true
5186
- };
5187
- updateData.products = {
5188
- active: snapshot?.productsActive ?? true,
5189
- productsList: vendor.products?.productsList ?? []
5190
- };
5191
- updateData.calendar = {
5192
- active: snapshot?.calendarActive ?? true,
5193
- calendarData: vendor.calendar?.calendarData ?? []
5194
- };
5195
- updateData.images = (vendor.images ?? []).map((image) => ({
5196
- ...image,
5197
- active: true
5198
- }));
5199
- const result = await VendorModel.updateOne(
5200
- {
5201
- _id: vendor._id,
5202
- active: true,
5203
- deletedAt: null,
5204
- "owner.userId": ownerUserId
5205
- },
5206
- { $set: updateData }
5207
- );
5208
- return (result?.matchedCount ?? 0) > 0;
5209
- }
5210
5306
  async function restoreVendorProFeatures(userId, licenceType) {
5211
5307
  const isProVendor = licenceType === EnumUserLicence9.PRO_VENDOR || licenceType === EnumUserLicence9.PRO_PLUS_VENDOR;
5212
5308
  if (!isProVendor) {
@@ -5223,6 +5319,61 @@ async function restoreVendorProFeatures(userId, licenceType) {
5223
5319
  throw error;
5224
5320
  }
5225
5321
  }
5322
+ var NOTIFICATION_CLAIM_LEASE_MS = 60 * 60 * 1e3;
5323
+ async function notifyVendorDowngrade(vendorId, ownerUserId) {
5324
+ if (!await downgradeStillApplies(ownerUserId)) {
5325
+ return false;
5326
+ }
5327
+ const claimedAt = /* @__PURE__ */ new Date();
5328
+ const claimed = await VendorModel.findOneAndUpdate(
5329
+ {
5330
+ $or: [
5331
+ { downgradeNotifiedAt: null },
5332
+ {
5333
+ downgradeNotifiedAt: {
5334
+ $lt: new Date(claimedAt.getTime() - NOTIFICATION_CLAIM_LEASE_MS)
5335
+ }
5336
+ }
5337
+ ],
5338
+ _id: vendorId,
5339
+ active: true,
5340
+ deletedAt: null,
5341
+ // A re-upgrade that restored the vendor has flipped this back, so its
5342
+ // owner is not told about a downgrade that no longer holds.
5343
+ featuresDowngraded: true
5344
+ },
5345
+ { $set: { downgradeNotifiedAt: claimedAt } },
5346
+ { new: false }
5347
+ ).lean().exec();
5348
+ if (!claimed) {
5349
+ return false;
5350
+ }
5351
+ const sent = await sendDeactivationNotification(
5352
+ {
5353
+ data: {
5354
+ resourceId: String(claimed._id),
5355
+ resourceName: claimed.name,
5356
+ resourceType: EnumNotificationResourceType4.DOWNGRADED_VENDOR
5357
+ },
5358
+ message: `Your Vendor licence has been downgraded due to licence expiration.`,
5359
+ title: `Vendor Licence Downgraded`,
5360
+ type: EnumNotificationType3.SYSTEM,
5361
+ userIds: [ownerUserId]
5362
+ },
5363
+ ownerUserId,
5364
+ claimed.name,
5365
+ "vendor",
5366
+ claimed.downgradeNotifiedAt ?? null
5367
+ );
5368
+ if (sent) {
5369
+ return true;
5370
+ }
5371
+ await VendorModel.updateOne(
5372
+ { _id: vendorId, downgradeNotifiedAt: claimedAt },
5373
+ { $set: { downgradeNotifiedAt: null } }
5374
+ );
5375
+ return false;
5376
+ }
5226
5377
  async function handleVendorLicenceCompliance(user, now) {
5227
5378
  if (!user.licences || !user.vendor) {
5228
5379
  return;
@@ -5233,10 +5384,10 @@ async function handleVendorLicenceCompliance(user, now) {
5233
5384
  if (vendorLicencesOfUser.length === 0) {
5234
5385
  return;
5235
5386
  }
5236
- const proLicences2 = vendorLicencesOfUser.filter(
5387
+ const proLicences = vendorLicencesOfUser.filter(
5237
5388
  (licence) => licence.licenceType !== EnumUserLicence9.STANDARD_VENDOR
5238
5389
  );
5239
- const expiredProLicences = proLicences2.filter(
5390
+ const expiredProLicences = proLicences.filter(
5240
5391
  (licence) => !dayjs6(licence.expiryDate).isAfter(now)
5241
5392
  );
5242
5393
  const stripeProtectedLicenceTypes = new Set(
@@ -5247,7 +5398,7 @@ async function handleVendorLicenceCompliance(user, now) {
5247
5398
  const expiredProLicence = expiredProLicences.some(
5248
5399
  (licence) => !stripeProtectedLicenceTypes.has(licence.licenceType)
5249
5400
  );
5250
- const hasValidProLicence = stripeProtectedLicenceTypes.size > 0 || hasValidLicence(proLicences2, vendorLicences, now);
5401
+ const hasValidProLicence = stripeProtectedLicenceTypes.size > 0 || hasValidLicence(proLicences, vendorLicences, now);
5251
5402
  const hasExpiredVendorLicence = vendorLicencesOfUser.some(
5252
5403
  (licence) => !dayjs6(licence.expiryDate).isAfter(now) && !stripeProtectedLicenceTypes.has(licence.licenceType)
5253
5404
  );
@@ -5263,29 +5414,27 @@ async function handleVendorLicenceCompliance(user, now) {
5263
5414
  "owner.userId": user._id
5264
5415
  }).lean().exec();
5265
5416
  }
5417
+ const needsDowngrade = expiredProLicence && Boolean(vendor) && !hasValidProLicence;
5418
+ const outcome = needsDowngrade && vendor ? await applyVendorDowngrade(vendor, user._id) : "skipped";
5266
5419
  const licencesToSync = vendorLicences.filter(
5267
5420
  (licenceType) => !stripeProtectedLicenceTypes.has(licenceType)
5268
5421
  );
5269
- await syncUserLicencesAfterExpiry(user._id, licencesToSync, now, "downgrade");
5270
- if (!expiredProLicence || !vendor || hasValidProLicence) {
5422
+ if (!needsDowngrade) {
5423
+ await syncUserLicencesAfterExpiry(
5424
+ user._id,
5425
+ licencesToSync,
5426
+ now,
5427
+ "downgrade"
5428
+ );
5271
5429
  return;
5272
5430
  }
5273
- const downgraded = await applyVendorDowngrade(vendor, user._id);
5274
- if (!downgraded) {
5431
+ if (outcome === "skipped" || !vendor) {
5275
5432
  return;
5276
5433
  }
5277
- const payload = {
5278
- data: {
5279
- resourceId: String(vendor._id),
5280
- resourceName: vendor.name,
5281
- resourceType: EnumNotificationResourceType4.DOWNGRADED_VENDOR
5282
- },
5283
- message: `Your Vendor licence has been downgraded due to licence expiration.`,
5284
- title: `Vendor Licence Downgraded`,
5285
- type: EnumNotificationType3.SYSTEM,
5286
- userIds: [user._id]
5287
- };
5288
- await sendDeactivationNotification(payload, user._id, vendor.name, "vendor");
5434
+ if (!await notifyVendorDowngrade(vendor._id, user._id)) {
5435
+ return;
5436
+ }
5437
+ await syncUserLicencesAfterExpiry(user._id, licencesToSync, now, "downgrade");
5289
5438
  }
5290
5439
  async function vendorOwnerHasProLicence(vendorId) {
5291
5440
  const vendor = await VendorModel.findOne({
@@ -5330,17 +5479,35 @@ function hasValidLicence(licences, licenceTypes, now) {
5330
5479
  (licence) => licenceTypes.includes(licence.licenceType) && dayjs7(licence.expiryDate).isAfter(now)
5331
5480
  );
5332
5481
  }
5333
- async function sendDeactivationNotification(payload, userId, resourceName, resourceType) {
5482
+ async function deactivationNoticeStored(payload, userId, since) {
5483
+ const stored = await NotificationModel.exists({
5484
+ createdAt: { $gte: since },
5485
+ "data.resourceId": payload.data.resourceId,
5486
+ "data.resourceType": payload.data.resourceType,
5487
+ title: payload.title,
5488
+ type: payload.type,
5489
+ userId
5490
+ });
5491
+ return stored !== null;
5492
+ }
5493
+ async function sendDeactivationNotification(payload, userId, resourceName, resourceType, retryOf = null) {
5494
+ if (retryOf && await deactivationNoticeStored(payload, userId, retryOf)) {
5495
+ console.log(
5496
+ `\u{1F501} ${resourceType} notification already stored for user ${String(userId)} for "${resourceName}"`
5497
+ );
5498
+ return true;
5499
+ }
5334
5500
  const sent = await notifyUsers({ payload });
5335
5501
  if (!sent) {
5336
5502
  console.error(
5337
5503
  `\u274C ${resourceType} notification not confirmed for user ${String(userId)} for "${resourceName}"`
5338
5504
  );
5339
- return;
5505
+ return false;
5340
5506
  }
5341
5507
  console.log(
5342
5508
  `\u2705 Sent ${resourceType} notification to user ${String(userId)} for "${resourceName}"`
5343
5509
  );
5510
+ return true;
5344
5511
  }
5345
5512
  async function processUserCompliance(user, now) {
5346
5513
  if (!user.licences) {
@@ -5773,6 +5940,7 @@ export {
5773
5940
  activeAffiliateCodeExists,
5774
5941
  awardAffiliateVendorSubscriptionRewards,
5775
5942
  baseResourceFields,
5943
+ buildAssociatesWriteGuard,
5776
5944
  buildInitialBillingCatalogEntries,
5777
5945
  buildLicenceExpiryPipeline,
5778
5946
  buildUserHasEnoughPointsFilter,
@@ -5837,6 +6005,7 @@ export {
5837
6005
  notifyUsers,
5838
6006
  partnerLicences,
5839
6007
  persistArchivedEventDates,
6008
+ pinAssociateTimestamp,
5840
6009
  processLicenseReminder,
5841
6010
  processUserCompliance,
5842
6011
  processUserLicenseReminders,