@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.
@@ -3,8 +3,8 @@ import { AdType, AdDailyPriceType, AdBookingType, AdMetricsType, BillingCatalogE
3
3
  import mongoose__default from 'mongoose';
4
4
  import { O as ObjectId } from '../index-BptxBl9x.mjs';
5
5
  export { C as ChatModel, N as NotificationModel, S as SchemaChatMessageReactionType, a as SchemaChatMessageReplyPreviewType, b as SchemaChatMessageSeenType, c as SchemaChatMessageType, d as SchemaChatType, e as SchemaCreateBulkNotificationInput, f as SchemaNotificationType, g as SchemaParticipantType } from '../index-BptxBl9x.mjs';
6
- import { S as SchemaAssociateType, a as SchemaOwnerType } from '../Affiliate-C1bp5oR3.mjs';
7
- export { A as AffiliateModel, b as AiImportedMarketModel, c as AssociateTypeSchema, C as CategorySchema, d as ContactDetailsSchema, E as EventModel, G as GoogleImportedMarketModel, O as OwnerTypeSchema, R as RelationModel, e as RelationTypeSchema, f as ResourceImageTypeSchema, g as SchemaAffiliateResourceType, h as SchemaAffiliateReward, i as SchemaAiImportedMarket, j as SchemaEventType, k as SchemaGoogleImportedMarket, l as SchemaRelatedPostType, m as SchemaRelationType, n as SchemaStripeSubscription, o as SchemaUserActivityEvent, p as SchemaUserAssociatedResourcesType, q as SchemaUserType, r as SocialMediaTypeSchema, U as UserModel, s as baseResourceFields, t as dateTimeSchema, u as locationGeoSchema, v as locationsSchema, w as relatedPostSchema, x as relationDatesSchema, y as socialShareResourceSchema, z as termsAgreementSchema, B as userLicenseSchema } from '../Affiliate-C1bp5oR3.mjs';
6
+ import { S as SchemaAssociateType, a as SchemaOwnerType } from '../Affiliate-DmLBN3lW.mjs';
7
+ export { A as AffiliateModel, b as AiImportedMarketModel, c as AssociateTypeSchema, C as CategorySchema, d as ContactDetailsSchema, E as EventModel, G as GoogleImportedMarketModel, O as OwnerTypeSchema, R as RelationModel, e as RelationTypeSchema, f as ResourceImageTypeSchema, g as SchemaAffiliateResourceType, h as SchemaAffiliateReward, i as SchemaAiImportedMarket, j as SchemaEventType, k as SchemaGoogleImportedMarket, l as SchemaRelatedPostType, m as SchemaRelationType, n as SchemaStripeSubscription, o as SchemaUserActivityEvent, p as SchemaUserAssociatedResourcesType, q as SchemaUserType, r as SocialMediaTypeSchema, U as UserModel, s as baseResourceFields, t as dateTimeSchema, u as locationGeoSchema, v as locationsSchema, w as relatedPostSchema, x as relationDatesSchema, y as socialShareResourceSchema, z as termsAgreementSchema, B as userLicenseSchema } from '../Affiliate-DmLBN3lW.mjs';
8
8
  import '@timardex/cluemart-shared/types';
9
9
  import 'express';
10
10
 
@@ -219,6 +219,19 @@ declare const vendorProductTypeSchema: mongoose__default.Schema<VendorProductLis
219
219
  type SchemaVendorType = Omit<VendorType, "vendorInfoId" | "owner" | "ownerLicenceType" | "adIds" | "associates" | "unregisteredVendorId"> & {
220
220
  adIds?: ObjectId[];
221
221
  associates?: SchemaAssociateType[] | null;
222
+ /** When the owner was told their vendor licence was downgraded. */
223
+ downgradeNotifiedAt?: Date | null;
224
+ /**
225
+ * True while the vendor runs the downgraded feature set. Written by the
226
+ * downgrade and cleared by the upgrade, so a second downgrade can tell it has
227
+ * nothing left to do instead of snapshotting the already-downgraded state.
228
+ */
229
+ featuresDowngraded?: boolean;
230
+ /**
231
+ * Bumped by every licence-driven feature write (downgrade and restore), so a
232
+ * downgrade can tell whether an upgrade landed after it read the vendor.
233
+ */
234
+ licenceEpoch?: number;
222
235
  /** Mirror of `categories[].name` for $text search (see vendorSearch). */
223
236
  categoriesNames?: string[];
224
237
  owner: SchemaOwnerType;
@@ -230,6 +243,19 @@ type SchemaVendorType = Omit<VendorType, "vendorInfoId" | "owner" | "ownerLicenc
230
243
  declare const VendorModel: mongoose__default.Model<SchemaVendorType, {}, {}, {}, mongoose__default.Document<unknown, {}, SchemaVendorType, {}, {}> & Omit<VendorType, "adIds" | "associates" | "owner" | "ownerLicenceType" | "vendorInfoId" | "unregisteredVendorId"> & {
231
244
  adIds?: ObjectId[];
232
245
  associates?: SchemaAssociateType[] | null;
246
+ /** When the owner was told their vendor licence was downgraded. */
247
+ downgradeNotifiedAt?: Date | null;
248
+ /**
249
+ * True while the vendor runs the downgraded feature set. Written by the
250
+ * downgrade and cleared by the upgrade, so a second downgrade can tell it has
251
+ * nothing left to do instead of snapshotting the already-downgraded state.
252
+ */
253
+ featuresDowngraded?: boolean;
254
+ /**
255
+ * Bumped by every licence-driven feature write (downgrade and restore), so a
256
+ * downgrade can tell whether an upgrade landed after it read the vendor.
257
+ */
258
+ licenceEpoch?: number;
233
259
  /** Mirror of `categories[].name` for $text search (see vendorSearch). */
234
260
  categoriesNames?: string[];
235
261
  owner: SchemaOwnerType;
@@ -3,8 +3,8 @@ import { AdType, AdDailyPriceType, AdBookingType, AdMetricsType, BillingCatalogE
3
3
  import mongoose__default from 'mongoose';
4
4
  import { O as ObjectId } from '../index-BptxBl9x.js';
5
5
  export { C as ChatModel, N as NotificationModel, S as SchemaChatMessageReactionType, a as SchemaChatMessageReplyPreviewType, b as SchemaChatMessageSeenType, c as SchemaChatMessageType, d as SchemaChatType, e as SchemaCreateBulkNotificationInput, f as SchemaNotificationType, g as SchemaParticipantType } from '../index-BptxBl9x.js';
6
- import { S as SchemaAssociateType, a as SchemaOwnerType } from '../Affiliate-DXLwbX9Z.js';
7
- export { A as AffiliateModel, b as AiImportedMarketModel, c as AssociateTypeSchema, C as CategorySchema, d as ContactDetailsSchema, E as EventModel, G as GoogleImportedMarketModel, O as OwnerTypeSchema, R as RelationModel, e as RelationTypeSchema, f as ResourceImageTypeSchema, g as SchemaAffiliateResourceType, h as SchemaAffiliateReward, i as SchemaAiImportedMarket, j as SchemaEventType, k as SchemaGoogleImportedMarket, l as SchemaRelatedPostType, m as SchemaRelationType, n as SchemaStripeSubscription, o as SchemaUserActivityEvent, p as SchemaUserAssociatedResourcesType, q as SchemaUserType, r as SocialMediaTypeSchema, U as UserModel, s as baseResourceFields, t as dateTimeSchema, u as locationGeoSchema, v as locationsSchema, w as relatedPostSchema, x as relationDatesSchema, y as socialShareResourceSchema, z as termsAgreementSchema, B as userLicenseSchema } from '../Affiliate-DXLwbX9Z.js';
6
+ import { S as SchemaAssociateType, a as SchemaOwnerType } from '../Affiliate-BRwzOt3b.js';
7
+ export { A as AffiliateModel, b as AiImportedMarketModel, c as AssociateTypeSchema, C as CategorySchema, d as ContactDetailsSchema, E as EventModel, G as GoogleImportedMarketModel, O as OwnerTypeSchema, R as RelationModel, e as RelationTypeSchema, f as ResourceImageTypeSchema, g as SchemaAffiliateResourceType, h as SchemaAffiliateReward, i as SchemaAiImportedMarket, j as SchemaEventType, k as SchemaGoogleImportedMarket, l as SchemaRelatedPostType, m as SchemaRelationType, n as SchemaStripeSubscription, o as SchemaUserActivityEvent, p as SchemaUserAssociatedResourcesType, q as SchemaUserType, r as SocialMediaTypeSchema, U as UserModel, s as baseResourceFields, t as dateTimeSchema, u as locationGeoSchema, v as locationsSchema, w as relatedPostSchema, x as relationDatesSchema, y as socialShareResourceSchema, z as termsAgreementSchema, B as userLicenseSchema } from '../Affiliate-BRwzOt3b.js';
8
8
  import '@timardex/cluemart-shared/types';
9
9
  import 'express';
10
10
 
@@ -219,6 +219,19 @@ declare const vendorProductTypeSchema: mongoose__default.Schema<VendorProductLis
219
219
  type SchemaVendorType = Omit<VendorType, "vendorInfoId" | "owner" | "ownerLicenceType" | "adIds" | "associates" | "unregisteredVendorId"> & {
220
220
  adIds?: ObjectId[];
221
221
  associates?: SchemaAssociateType[] | null;
222
+ /** When the owner was told their vendor licence was downgraded. */
223
+ downgradeNotifiedAt?: Date | null;
224
+ /**
225
+ * True while the vendor runs the downgraded feature set. Written by the
226
+ * downgrade and cleared by the upgrade, so a second downgrade can tell it has
227
+ * nothing left to do instead of snapshotting the already-downgraded state.
228
+ */
229
+ featuresDowngraded?: boolean;
230
+ /**
231
+ * Bumped by every licence-driven feature write (downgrade and restore), so a
232
+ * downgrade can tell whether an upgrade landed after it read the vendor.
233
+ */
234
+ licenceEpoch?: number;
222
235
  /** Mirror of `categories[].name` for $text search (see vendorSearch). */
223
236
  categoriesNames?: string[];
224
237
  owner: SchemaOwnerType;
@@ -230,6 +243,19 @@ type SchemaVendorType = Omit<VendorType, "vendorInfoId" | "owner" | "ownerLicenc
230
243
  declare const VendorModel: mongoose__default.Model<SchemaVendorType, {}, {}, {}, mongoose__default.Document<unknown, {}, SchemaVendorType, {}, {}> & Omit<VendorType, "adIds" | "associates" | "owner" | "ownerLicenceType" | "vendorInfoId" | "unregisteredVendorId"> & {
231
244
  adIds?: ObjectId[];
232
245
  associates?: SchemaAssociateType[] | null;
246
+ /** When the owner was told their vendor licence was downgraded. */
247
+ downgradeNotifiedAt?: Date | null;
248
+ /**
249
+ * True while the vendor runs the downgraded feature set. Written by the
250
+ * downgrade and cleared by the upgrade, so a second downgrade can tell it has
251
+ * nothing left to do instead of snapshotting the already-downgraded state.
252
+ */
253
+ featuresDowngraded?: boolean;
254
+ /**
255
+ * Bumped by every licence-driven feature write (downgrade and restore), so a
256
+ * downgrade can tell whether an upgrade landed after it read the vendor.
257
+ */
258
+ licenceEpoch?: number;
233
259
  /** Mirror of `categories[].name` for $text search (see vendorSearch). */
234
260
  categoriesNames?: string[];
235
261
  owner: SchemaOwnerType;
@@ -61,7 +61,7 @@ import {
61
61
  termsAgreementSchema,
62
62
  userLicenseSchema,
63
63
  vendorProductTypeSchema
64
- } from "../chunk-MYZL22GL.mjs";
64
+ } from "../chunk-JYBS6IOE.mjs";
65
65
  export {
66
66
  AD_BILLING_CATALOG_COLLECTION_NAME,
67
67
  AI_IMPORT_RUN_LOCK_KEY,
@@ -39,6 +39,7 @@ __export(service_exports, {
39
39
  acceptedAssociateUserIds: () => acceptedAssociateUserIds,
40
40
  activeAffiliateCodeExists: () => activeAffiliateCodeExists,
41
41
  awardAffiliateVendorSubscriptionRewards: () => awardAffiliateVendorSubscriptionRewards,
42
+ buildAssociatesWriteGuard: () => buildAssociatesWriteGuard,
42
43
  buildLicenceExpiryPipeline: () => buildLicenceExpiryPipeline,
43
44
  buildUserHasEnoughPointsFilter: () => buildUserHasEnoughPointsFilter,
44
45
  buildUserPointAwardEntry: () => buildUserPointAwardEntry,
@@ -96,6 +97,7 @@ __export(service_exports, {
96
97
  notifyUsers: () => notifyUsers,
97
98
  partnerLicences: () => partnerLicences,
98
99
  persistArchivedEventDates: () => persistArchivedEventDates,
100
+ pinAssociateTimestamp: () => pinAssociateTimestamp,
99
101
  processLicenseReminder: () => processLicenseReminder,
100
102
  processUserCompliance: () => processUserCompliance,
101
103
  processUserLicenseReminders: () => processUserLicenseReminders,
@@ -2127,8 +2129,11 @@ var schema17 = new MongooseSchema18(
2127
2129
  categories: { required: true, type: [CategorySchema] },
2128
2130
  categoriesNames: { default: [], required: false, type: [String] },
2129
2131
  claimed: { default: true, required: false, type: Boolean },
2132
+ downgradeNotifiedAt: { default: null, required: false, type: Date },
2130
2133
  downgradeSnapshot: { required: false, type: downgradeSnapshotSchema },
2134
+ featuresDowngraded: { default: false, required: false, type: Boolean },
2131
2135
  foodTruck: { required: true, type: Boolean },
2136
+ licenceEpoch: { default: 0, required: false, type: Number },
2132
2137
  products: { required: false, type: productWrapperSchema },
2133
2138
  shareRelation: { required: false, type: socialShareResourceSchema },
2134
2139
  unregisteredVendorId: {
@@ -3457,6 +3462,38 @@ var ASSOCIABLE_MODELS = {
3457
3462
  [import_cluemart_shared28.EnumResourceType.PARTNER]: PartnerModel,
3458
3463
  [import_cluemart_shared28.EnumResourceType.VENDOR]: VendorModel
3459
3464
  };
3465
+ function pinAssociateTimestamp(value) {
3466
+ return value == null ? null : { $in: [value, null] };
3467
+ }
3468
+ function buildAssociatesWriteGuard({
3469
+ canManage,
3470
+ nextAssociates,
3471
+ snapshot
3472
+ }) {
3473
+ if (!canManage) {
3474
+ return null;
3475
+ }
3476
+ const previous = snapshot ?? [];
3477
+ const emptyListFilter = {
3478
+ $or: [{ associates: { $size: 0 } }, { associates: null }]
3479
+ };
3480
+ return {
3481
+ filter: previous.length > 0 ? {
3482
+ $and: previous.map((associate) => ({
3483
+ associates: {
3484
+ $elemMatch: {
3485
+ addedAt: pinAssociateTimestamp(associate.addedAt),
3486
+ respondedAt: pinAssociateTimestamp(associate.respondedAt),
3487
+ status: associate.status,
3488
+ userId: associate.userId
3489
+ }
3490
+ }
3491
+ })),
3492
+ associates: { $size: previous.length }
3493
+ } : emptyListFilter,
3494
+ update: { associates: nextAssociates }
3495
+ };
3496
+ }
3460
3497
  function acceptedAssociateUserIds(associates) {
3461
3498
  return (associates ?? []).filter((associate) => associate.status === import_cluemart_shared28.EnumAssociateStatus.ACCEPTED).map((associate) => associate.userId);
3462
3499
  }
@@ -3496,7 +3533,10 @@ async function acceptedUserIdsForResource({
3496
3533
  resourceType
3497
3534
  }) {
3498
3535
  const model = ASSOCIABLE_MODELS[resourceType];
3499
- const resource = await model.findOne({ _id: resourceId, deletedAt: null }).select("associates").lean().exec();
3536
+ const resource = await model.findOne({ _id: resourceId, deletedAt: null }).select("associates featuresDowngraded").lean().exec();
3537
+ if (resource?.featuresDowngraded) {
3538
+ return /* @__PURE__ */ new Set();
3539
+ }
3500
3540
  return new Set(
3501
3541
  acceptedAssociateUserIds(resource?.associates).map(
3502
3542
  (userId) => String(userId)
@@ -3646,12 +3686,12 @@ async function reconcileUserBatch({
3646
3686
  _id: {
3647
3687
  $in: [...heldByResource.values()].map((entry) => entry.resourceId)
3648
3688
  }
3649
- }).select("associates deletedAt").lean().exec();
3689
+ }).select("associates deletedAt featuresDowngraded").lean().exec();
3650
3690
  const acceptedByResource = /* @__PURE__ */ new Map();
3651
3691
  for (const resource of resources) {
3652
3692
  acceptedByResource.set(
3653
3693
  String(resource._id),
3654
- resource.deletedAt ? /* @__PURE__ */ new Set() : new Set(
3694
+ resource.deletedAt || resource.featuresDowngraded ? /* @__PURE__ */ new Set() : new Set(
3655
3695
  acceptedAssociateUserIds(resource.associates).map(
3656
3696
  (userId) => String(userId)
3657
3697
  )
@@ -4710,13 +4750,13 @@ var import_dayjs6 = __toESM(require("dayjs"));
4710
4750
  var import_cluemart_shared36 = require("@timardex/cluemart-shared");
4711
4751
  var import_dayjs5 = __toESM(require("dayjs"));
4712
4752
  var import_graphql = require("graphql");
4713
- var LicenceCategory = /* @__PURE__ */ ((LicenceCategory3) => {
4714
- LicenceCategory3["EVENT"] = "event";
4715
- LicenceCategory3["PARTNER"] = "partner";
4716
- LicenceCategory3["VENDOR"] = "vendor";
4717
- LicenceCategory3["AFFILIATE"] = "affiliate";
4718
- LicenceCategory3["SCHOOL"] = "school";
4719
- return LicenceCategory3;
4753
+ var LicenceCategory = /* @__PURE__ */ ((LicenceCategory2) => {
4754
+ LicenceCategory2["EVENT"] = "event";
4755
+ LicenceCategory2["PARTNER"] = "partner";
4756
+ LicenceCategory2["VENDOR"] = "vendor";
4757
+ LicenceCategory2["AFFILIATE"] = "affiliate";
4758
+ LicenceCategory2["SCHOOL"] = "school";
4759
+ return LicenceCategory2;
4720
4760
  })(LicenceCategory || {});
4721
4761
  var licenceCategoryMapping = {
4722
4762
  [import_cluemart_shared36.EnumUserLicence.PRO_EVENT]: "event" /* EVENT */,
@@ -4740,25 +4780,8 @@ var licencePriority = {
4740
4780
  [import_cluemart_shared36.EnumUserLicence.STANDARD_AFFILIATE]: 1,
4741
4781
  [import_cluemart_shared36.EnumUserLicence.STANDARD_SCHOOL]: 1
4742
4782
  };
4743
- var standardLicences = [
4744
- import_cluemart_shared36.EnumUserLicence.STANDARD_VENDOR,
4745
- import_cluemart_shared36.EnumUserLicence.STANDARD_EVENT,
4746
- import_cluemart_shared36.EnumUserLicence.STANDARD_PARTNER
4747
- ];
4748
- var standardLicenceSet = new Set(standardLicences);
4749
- function isStandardLicence(licence) {
4750
- return standardLicenceSet.has(licence);
4751
- }
4752
- var proLicences = [
4753
- import_cluemart_shared36.EnumUserLicence.PRO_EVENT,
4754
- import_cluemart_shared36.EnumUserLicence.PRO_PLUS_EVENT,
4755
- import_cluemart_shared36.EnumUserLicence.PRO_VENDOR,
4756
- import_cluemart_shared36.EnumUserLicence.PRO_PLUS_VENDOR
4757
- ];
4758
- var proLicenceSet = new Set(proLicences);
4759
- function isProLicence(licence) {
4760
- return proLicenceSet.has(licence);
4761
- }
4783
+ var isStandardLicence = import_cluemart_shared36.isStandardLicenceType;
4784
+ var isProLicence = import_cluemart_shared36.isProLicenceType;
4762
4785
  var categoryRegexMapping = {
4763
4786
  ["event" /* EVENT */]: /_event$/,
4764
4787
  ["partner" /* PARTNER */]: /_partner$/,
@@ -5081,30 +5104,134 @@ async function findUserVendor(userId, logLabel) {
5081
5104
  }
5082
5105
  return vendor;
5083
5106
  }
5107
+ async function downgradeStillApplies(ownerUserId) {
5108
+ const hasActiveProLicence = await hasActiveProLicenceForResource({
5109
+ includeStripeProtected: true,
5110
+ resourceType: import_cluemart_shared37.EnumResourceType.VENDOR,
5111
+ userId: ownerUserId
5112
+ });
5113
+ return !hasActiveProLicence;
5114
+ }
5084
5115
  async function applyVendorDowngrade(vendor, ownerUserId) {
5085
- const updateData = {};
5086
- updateData.availability = {
5087
- corporate: false,
5088
- private: false,
5089
- school: false
5090
- };
5091
- updateData.products = {
5092
- active: false,
5093
- productsList: vendor.products?.productsList ?? []
5094
- };
5095
- updateData.calendar = {
5096
- active: false,
5097
- calendarData: vendor.calendar?.calendarData ?? []
5098
- };
5099
- updateData.downgradeSnapshot = {
5100
- availability: vendor.availability,
5101
- calendarActive: vendor.calendar?.active,
5102
- productsActive: vendor.products?.active
5116
+ let current = vendor;
5117
+ for (let attempt = 0; attempt < 2; attempt += 1) {
5118
+ if (!await downgradeStillApplies(ownerUserId)) {
5119
+ console.info(
5120
+ "[applyVendorDowngrade] owner holds an active PRO licence again; skipping the downgrade",
5121
+ { vendorId: String(current._id) }
5122
+ );
5123
+ return "skipped";
5124
+ }
5125
+ const associatesGuard = buildAssociatesWriteGuard({
5126
+ canManage: true,
5127
+ nextAssociates: [],
5128
+ snapshot: current.associates
5129
+ });
5130
+ if (!associatesGuard) {
5131
+ return "skipped";
5132
+ }
5133
+ const result = await VendorModel.updateOne(
5134
+ {
5135
+ _id: current._id,
5136
+ active: true,
5137
+ deletedAt: null,
5138
+ // Already downgraded: another run got there first and its snapshot is
5139
+ // the original state this one must not overwrite.
5140
+ featuresDowngraded: { $ne: true },
5141
+ // Upgrades bump this in their own write; `null` covers vendors that
5142
+ // predate the field.
5143
+ licenceEpoch: { $in: [current.licenceEpoch ?? 0, null] },
5144
+ "owner.userId": ownerUserId,
5145
+ ...associatesGuard.filter
5146
+ },
5147
+ {
5148
+ $inc: { licenceEpoch: 1 },
5149
+ $set: {
5150
+ ...associatesGuard.update,
5151
+ availability: {
5152
+ corporate: false,
5153
+ private: false,
5154
+ school: false
5155
+ },
5156
+ calendar: {
5157
+ active: false,
5158
+ calendarData: current.calendar?.calendarData ?? []
5159
+ },
5160
+ downgradeSnapshot: {
5161
+ availability: current.availability,
5162
+ calendarActive: current.calendar?.active,
5163
+ productsActive: current.products?.active
5164
+ },
5165
+ featuresDowngraded: true,
5166
+ // STANDARD_VENDOR keeps only the first 6 images active.
5167
+ images: (current.images ?? []).map((image, index) => ({
5168
+ ...image,
5169
+ active: index < 6
5170
+ })),
5171
+ products: {
5172
+ active: false,
5173
+ productsList: current.products?.productsList ?? []
5174
+ }
5175
+ }
5176
+ }
5177
+ );
5178
+ if ((result?.matchedCount ?? 0) > 0) {
5179
+ break;
5180
+ }
5181
+ const fresh = await VendorModel.findById(current._id).lean().exec();
5182
+ if (!fresh) {
5183
+ return "skipped";
5184
+ }
5185
+ if (fresh.featuresDowngraded === true) {
5186
+ console.info(
5187
+ "[applyVendorDowngrade] vendor is already downgraded; licence sync can proceed",
5188
+ { vendorId: String(fresh._id) }
5189
+ );
5190
+ return "already-downgraded";
5191
+ }
5192
+ current = fresh;
5193
+ if (attempt === 1) {
5194
+ console.warn(
5195
+ "[applyVendorDowngrade] vendor changed under the downgrade; left to the next compliance run",
5196
+ { vendorId: String(current._id) }
5197
+ );
5198
+ return "skipped";
5199
+ }
5200
+ }
5201
+ try {
5202
+ await detachStaleAssociateGrants({
5203
+ acceptedUserIds: [],
5204
+ resourceId: current._id,
5205
+ resourceType: import_cluemart_shared37.EnumResourceType.VENDOR
5206
+ });
5207
+ } catch (error) {
5208
+ console.error(
5209
+ "[applyVendorDowngrade] grant detach failed; left to reconciliation",
5210
+ error
5211
+ );
5212
+ }
5213
+ return "applied";
5214
+ }
5215
+ async function applyVendorRestore(vendor, ownerUserId) {
5216
+ const snapshot = vendor.downgradeSnapshot;
5217
+ const updateData = {
5218
+ availability: {
5219
+ corporate: snapshot?.availability?.corporate ?? true,
5220
+ private: snapshot?.availability?.private ?? true,
5221
+ school: snapshot?.availability?.school ?? true
5222
+ },
5223
+ calendar: {
5224
+ active: snapshot?.calendarActive ?? true,
5225
+ calendarData: vendor.calendar?.calendarData ?? []
5226
+ },
5227
+ downgradeNotifiedAt: null,
5228
+ featuresDowngraded: false,
5229
+ images: (vendor.images ?? []).map((image) => ({ ...image, active: true })),
5230
+ products: {
5231
+ active: snapshot?.productsActive ?? true,
5232
+ productsList: vendor.products?.productsList ?? []
5233
+ }
5103
5234
  };
5104
- updateData.images = (vendor.images ?? []).map((image, index) => ({
5105
- ...image,
5106
- active: index < 6
5107
- }));
5108
5235
  const result = await VendorModel.updateOne(
5109
5236
  {
5110
5237
  _id: vendor._id,
@@ -5112,7 +5239,7 @@ async function applyVendorDowngrade(vendor, ownerUserId) {
5112
5239
  deletedAt: null,
5113
5240
  "owner.userId": ownerUserId
5114
5241
  },
5115
- { $set: updateData }
5242
+ { $inc: { licenceEpoch: 1 }, $set: updateData }
5116
5243
  );
5117
5244
  return (result?.matchedCount ?? 0) > 0;
5118
5245
  }
@@ -5132,37 +5259,6 @@ async function downgradeVendorProFeatures(userId, licenceType) {
5132
5259
  throw error;
5133
5260
  }
5134
5261
  }
5135
- async function applyVendorRestore(vendor, ownerUserId) {
5136
- const updateData = {};
5137
- const snapshot = vendor.downgradeSnapshot;
5138
- updateData.availability = {
5139
- corporate: snapshot?.availability?.corporate ?? true,
5140
- private: snapshot?.availability?.private ?? true,
5141
- school: snapshot?.availability?.school ?? true
5142
- };
5143
- updateData.products = {
5144
- active: snapshot?.productsActive ?? true,
5145
- productsList: vendor.products?.productsList ?? []
5146
- };
5147
- updateData.calendar = {
5148
- active: snapshot?.calendarActive ?? true,
5149
- calendarData: vendor.calendar?.calendarData ?? []
5150
- };
5151
- updateData.images = (vendor.images ?? []).map((image) => ({
5152
- ...image,
5153
- active: true
5154
- }));
5155
- const result = await VendorModel.updateOne(
5156
- {
5157
- _id: vendor._id,
5158
- active: true,
5159
- deletedAt: null,
5160
- "owner.userId": ownerUserId
5161
- },
5162
- { $set: updateData }
5163
- );
5164
- return (result?.matchedCount ?? 0) > 0;
5165
- }
5166
5262
  async function restoreVendorProFeatures(userId, licenceType) {
5167
5263
  const isProVendor = licenceType === import_cluemart_shared37.EnumUserLicence.PRO_VENDOR || licenceType === import_cluemart_shared37.EnumUserLicence.PRO_PLUS_VENDOR;
5168
5264
  if (!isProVendor) {
@@ -5179,6 +5275,61 @@ async function restoreVendorProFeatures(userId, licenceType) {
5179
5275
  throw error;
5180
5276
  }
5181
5277
  }
5278
+ var NOTIFICATION_CLAIM_LEASE_MS = 60 * 60 * 1e3;
5279
+ async function notifyVendorDowngrade(vendorId, ownerUserId) {
5280
+ if (!await downgradeStillApplies(ownerUserId)) {
5281
+ return false;
5282
+ }
5283
+ const claimedAt = /* @__PURE__ */ new Date();
5284
+ const claimed = await VendorModel.findOneAndUpdate(
5285
+ {
5286
+ $or: [
5287
+ { downgradeNotifiedAt: null },
5288
+ {
5289
+ downgradeNotifiedAt: {
5290
+ $lt: new Date(claimedAt.getTime() - NOTIFICATION_CLAIM_LEASE_MS)
5291
+ }
5292
+ }
5293
+ ],
5294
+ _id: vendorId,
5295
+ active: true,
5296
+ deletedAt: null,
5297
+ // A re-upgrade that restored the vendor has flipped this back, so its
5298
+ // owner is not told about a downgrade that no longer holds.
5299
+ featuresDowngraded: true
5300
+ },
5301
+ { $set: { downgradeNotifiedAt: claimedAt } },
5302
+ { new: false }
5303
+ ).lean().exec();
5304
+ if (!claimed) {
5305
+ return false;
5306
+ }
5307
+ const sent = await sendDeactivationNotification(
5308
+ {
5309
+ data: {
5310
+ resourceId: String(claimed._id),
5311
+ resourceName: claimed.name,
5312
+ resourceType: import_cluemart_shared37.EnumNotificationResourceType.DOWNGRADED_VENDOR
5313
+ },
5314
+ message: `Your Vendor licence has been downgraded due to licence expiration.`,
5315
+ title: `Vendor Licence Downgraded`,
5316
+ type: import_cluemart_shared37.EnumNotificationType.SYSTEM,
5317
+ userIds: [ownerUserId]
5318
+ },
5319
+ ownerUserId,
5320
+ claimed.name,
5321
+ "vendor",
5322
+ claimed.downgradeNotifiedAt ?? null
5323
+ );
5324
+ if (sent) {
5325
+ return true;
5326
+ }
5327
+ await VendorModel.updateOne(
5328
+ { _id: vendorId, downgradeNotifiedAt: claimedAt },
5329
+ { $set: { downgradeNotifiedAt: null } }
5330
+ );
5331
+ return false;
5332
+ }
5182
5333
  async function handleVendorLicenceCompliance(user, now) {
5183
5334
  if (!user.licences || !user.vendor) {
5184
5335
  return;
@@ -5189,10 +5340,10 @@ async function handleVendorLicenceCompliance(user, now) {
5189
5340
  if (vendorLicencesOfUser.length === 0) {
5190
5341
  return;
5191
5342
  }
5192
- const proLicences2 = vendorLicencesOfUser.filter(
5343
+ const proLicences = vendorLicencesOfUser.filter(
5193
5344
  (licence) => licence.licenceType !== import_cluemart_shared37.EnumUserLicence.STANDARD_VENDOR
5194
5345
  );
5195
- const expiredProLicences = proLicences2.filter(
5346
+ const expiredProLicences = proLicences.filter(
5196
5347
  (licence) => !(0, import_dayjs6.default)(licence.expiryDate).isAfter(now)
5197
5348
  );
5198
5349
  const stripeProtectedLicenceTypes = new Set(
@@ -5203,7 +5354,7 @@ async function handleVendorLicenceCompliance(user, now) {
5203
5354
  const expiredProLicence = expiredProLicences.some(
5204
5355
  (licence) => !stripeProtectedLicenceTypes.has(licence.licenceType)
5205
5356
  );
5206
- const hasValidProLicence = stripeProtectedLicenceTypes.size > 0 || hasValidLicence(proLicences2, import_cluemart_shared37.vendorLicences, now);
5357
+ const hasValidProLicence = stripeProtectedLicenceTypes.size > 0 || hasValidLicence(proLicences, import_cluemart_shared37.vendorLicences, now);
5207
5358
  const hasExpiredVendorLicence = vendorLicencesOfUser.some(
5208
5359
  (licence) => !(0, import_dayjs6.default)(licence.expiryDate).isAfter(now) && !stripeProtectedLicenceTypes.has(licence.licenceType)
5209
5360
  );
@@ -5219,29 +5370,27 @@ async function handleVendorLicenceCompliance(user, now) {
5219
5370
  "owner.userId": user._id
5220
5371
  }).lean().exec();
5221
5372
  }
5373
+ const needsDowngrade = expiredProLicence && Boolean(vendor) && !hasValidProLicence;
5374
+ const outcome = needsDowngrade && vendor ? await applyVendorDowngrade(vendor, user._id) : "skipped";
5222
5375
  const licencesToSync = import_cluemart_shared37.vendorLicences.filter(
5223
5376
  (licenceType) => !stripeProtectedLicenceTypes.has(licenceType)
5224
5377
  );
5225
- await syncUserLicencesAfterExpiry(user._id, licencesToSync, now, "downgrade");
5226
- if (!expiredProLicence || !vendor || hasValidProLicence) {
5378
+ if (!needsDowngrade) {
5379
+ await syncUserLicencesAfterExpiry(
5380
+ user._id,
5381
+ licencesToSync,
5382
+ now,
5383
+ "downgrade"
5384
+ );
5227
5385
  return;
5228
5386
  }
5229
- const downgraded = await applyVendorDowngrade(vendor, user._id);
5230
- if (!downgraded) {
5387
+ if (outcome === "skipped" || !vendor) {
5231
5388
  return;
5232
5389
  }
5233
- const payload = {
5234
- data: {
5235
- resourceId: String(vendor._id),
5236
- resourceName: vendor.name,
5237
- resourceType: import_cluemart_shared37.EnumNotificationResourceType.DOWNGRADED_VENDOR
5238
- },
5239
- message: `Your Vendor licence has been downgraded due to licence expiration.`,
5240
- title: `Vendor Licence Downgraded`,
5241
- type: import_cluemart_shared37.EnumNotificationType.SYSTEM,
5242
- userIds: [user._id]
5243
- };
5244
- await sendDeactivationNotification(payload, user._id, vendor.name, "vendor");
5390
+ if (!await notifyVendorDowngrade(vendor._id, user._id)) {
5391
+ return;
5392
+ }
5393
+ await syncUserLicencesAfterExpiry(user._id, licencesToSync, now, "downgrade");
5245
5394
  }
5246
5395
  async function vendorOwnerHasProLicence(vendorId) {
5247
5396
  const vendor = await VendorModel.findOne({
@@ -5286,17 +5435,35 @@ function hasValidLicence(licences, licenceTypes, now) {
5286
5435
  (licence) => licenceTypes.includes(licence.licenceType) && (0, import_dayjs7.default)(licence.expiryDate).isAfter(now)
5287
5436
  );
5288
5437
  }
5289
- async function sendDeactivationNotification(payload, userId, resourceName, resourceType) {
5438
+ async function deactivationNoticeStored(payload, userId, since) {
5439
+ const stored = await NotificationModel.exists({
5440
+ createdAt: { $gte: since },
5441
+ "data.resourceId": payload.data.resourceId,
5442
+ "data.resourceType": payload.data.resourceType,
5443
+ title: payload.title,
5444
+ type: payload.type,
5445
+ userId
5446
+ });
5447
+ return stored !== null;
5448
+ }
5449
+ async function sendDeactivationNotification(payload, userId, resourceName, resourceType, retryOf = null) {
5450
+ if (retryOf && await deactivationNoticeStored(payload, userId, retryOf)) {
5451
+ console.log(
5452
+ `\u{1F501} ${resourceType} notification already stored for user ${String(userId)} for "${resourceName}"`
5453
+ );
5454
+ return true;
5455
+ }
5290
5456
  const sent = await notifyUsers({ payload });
5291
5457
  if (!sent) {
5292
5458
  console.error(
5293
5459
  `\u274C ${resourceType} notification not confirmed for user ${String(userId)} for "${resourceName}"`
5294
5460
  );
5295
- return;
5461
+ return false;
5296
5462
  }
5297
5463
  console.log(
5298
5464
  `\u2705 Sent ${resourceType} notification to user ${String(userId)} for "${resourceName}"`
5299
5465
  );
5466
+ return true;
5300
5467
  }
5301
5468
  async function processUserCompliance(user, now) {
5302
5469
  if (!user.licences) {
@@ -5673,6 +5840,7 @@ async function remindUsersAboutLicenseExpiration() {
5673
5840
  acceptedAssociateUserIds,
5674
5841
  activeAffiliateCodeExists,
5675
5842
  awardAffiliateVendorSubscriptionRewards,
5843
+ buildAssociatesWriteGuard,
5676
5844
  buildLicenceExpiryPipeline,
5677
5845
  buildUserHasEnoughPointsFilter,
5678
5846
  buildUserPointAwardEntry,
@@ -5730,6 +5898,7 @@ async function remindUsersAboutLicenseExpiration() {
5730
5898
  notifyUsers,
5731
5899
  partnerLicences,
5732
5900
  persistArchivedEventDates,
5901
+ pinAssociateTimestamp,
5733
5902
  processLicenseReminder,
5734
5903
  processUserCompliance,
5735
5904
  processUserLicenseReminders,