@timardex/cluemart-server-shared 5.0.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-DfBYlDtn.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-DfBYlDtn.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-CisCDggv.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-CisCDggv.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-VM4B5D2I.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,
@@ -1120,6 +1122,11 @@ var schema7 = new MongooseSchema6(
1120
1122
  type: ResourceImageTypeSchema
1121
1123
  },
1122
1124
  dateTime: [dateTimeSchema],
1125
+ deactivatedReason: {
1126
+ enum: Object.values(import_cluemart_shared9.EnumImportedMarketDeactivationReason),
1127
+ required: false,
1128
+ type: String
1129
+ },
1123
1130
  deletedAt: { default: null, required: false, type: Date },
1124
1131
  description: { required: true, type: String },
1125
1132
  earliestStartDate: { default: null, required: false, type: Date },
@@ -2122,8 +2129,11 @@ var schema17 = new MongooseSchema18(
2122
2129
  categories: { required: true, type: [CategorySchema] },
2123
2130
  categoriesNames: { default: [], required: false, type: [String] },
2124
2131
  claimed: { default: true, required: false, type: Boolean },
2132
+ downgradeNotifiedAt: { default: null, required: false, type: Date },
2125
2133
  downgradeSnapshot: { required: false, type: downgradeSnapshotSchema },
2134
+ featuresDowngraded: { default: false, required: false, type: Boolean },
2126
2135
  foodTruck: { required: true, type: Boolean },
2136
+ licenceEpoch: { default: 0, required: false, type: Number },
2127
2137
  products: { required: false, type: productWrapperSchema },
2128
2138
  shareRelation: { required: false, type: socialShareResourceSchema },
2129
2139
  unregisteredVendorId: {
@@ -3452,6 +3462,38 @@ var ASSOCIABLE_MODELS = {
3452
3462
  [import_cluemart_shared28.EnumResourceType.PARTNER]: PartnerModel,
3453
3463
  [import_cluemart_shared28.EnumResourceType.VENDOR]: VendorModel
3454
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
+ }
3455
3497
  function acceptedAssociateUserIds(associates) {
3456
3498
  return (associates ?? []).filter((associate) => associate.status === import_cluemart_shared28.EnumAssociateStatus.ACCEPTED).map((associate) => associate.userId);
3457
3499
  }
@@ -3491,7 +3533,10 @@ async function acceptedUserIdsForResource({
3491
3533
  resourceType
3492
3534
  }) {
3493
3535
  const model = ASSOCIABLE_MODELS[resourceType];
3494
- 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
+ }
3495
3540
  return new Set(
3496
3541
  acceptedAssociateUserIds(resource?.associates).map(
3497
3542
  (userId) => String(userId)
@@ -3641,12 +3686,12 @@ async function reconcileUserBatch({
3641
3686
  _id: {
3642
3687
  $in: [...heldByResource.values()].map((entry) => entry.resourceId)
3643
3688
  }
3644
- }).select("associates deletedAt").lean().exec();
3689
+ }).select("associates deletedAt featuresDowngraded").lean().exec();
3645
3690
  const acceptedByResource = /* @__PURE__ */ new Map();
3646
3691
  for (const resource of resources) {
3647
3692
  acceptedByResource.set(
3648
3693
  String(resource._id),
3649
- resource.deletedAt ? /* @__PURE__ */ new Set() : new Set(
3694
+ resource.deletedAt || resource.featuresDowngraded ? /* @__PURE__ */ new Set() : new Set(
3650
3695
  acceptedAssociateUserIds(resource.associates).map(
3651
3696
  (userId) => String(userId)
3652
3697
  )
@@ -4705,13 +4750,13 @@ var import_dayjs6 = __toESM(require("dayjs"));
4705
4750
  var import_cluemart_shared36 = require("@timardex/cluemart-shared");
4706
4751
  var import_dayjs5 = __toESM(require("dayjs"));
4707
4752
  var import_graphql = require("graphql");
4708
- var LicenceCategory = /* @__PURE__ */ ((LicenceCategory3) => {
4709
- LicenceCategory3["EVENT"] = "event";
4710
- LicenceCategory3["PARTNER"] = "partner";
4711
- LicenceCategory3["VENDOR"] = "vendor";
4712
- LicenceCategory3["AFFILIATE"] = "affiliate";
4713
- LicenceCategory3["SCHOOL"] = "school";
4714
- 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;
4715
4760
  })(LicenceCategory || {});
4716
4761
  var licenceCategoryMapping = {
4717
4762
  [import_cluemart_shared36.EnumUserLicence.PRO_EVENT]: "event" /* EVENT */,
@@ -4735,25 +4780,8 @@ var licencePriority = {
4735
4780
  [import_cluemart_shared36.EnumUserLicence.STANDARD_AFFILIATE]: 1,
4736
4781
  [import_cluemart_shared36.EnumUserLicence.STANDARD_SCHOOL]: 1
4737
4782
  };
4738
- var standardLicences = [
4739
- import_cluemart_shared36.EnumUserLicence.STANDARD_VENDOR,
4740
- import_cluemart_shared36.EnumUserLicence.STANDARD_EVENT,
4741
- import_cluemart_shared36.EnumUserLicence.STANDARD_PARTNER
4742
- ];
4743
- var standardLicenceSet = new Set(standardLicences);
4744
- function isStandardLicence(licence) {
4745
- return standardLicenceSet.has(licence);
4746
- }
4747
- var proLicences = [
4748
- import_cluemart_shared36.EnumUserLicence.PRO_EVENT,
4749
- import_cluemart_shared36.EnumUserLicence.PRO_PLUS_EVENT,
4750
- import_cluemart_shared36.EnumUserLicence.PRO_VENDOR,
4751
- import_cluemart_shared36.EnumUserLicence.PRO_PLUS_VENDOR
4752
- ];
4753
- var proLicenceSet = new Set(proLicences);
4754
- function isProLicence(licence) {
4755
- return proLicenceSet.has(licence);
4756
- }
4783
+ var isStandardLicence = import_cluemart_shared36.isStandardLicenceType;
4784
+ var isProLicence = import_cluemart_shared36.isProLicenceType;
4757
4785
  var categoryRegexMapping = {
4758
4786
  ["event" /* EVENT */]: /_event$/,
4759
4787
  ["partner" /* PARTNER */]: /_partner$/,
@@ -5076,30 +5104,134 @@ async function findUserVendor(userId, logLabel) {
5076
5104
  }
5077
5105
  return vendor;
5078
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
+ }
5079
5115
  async function applyVendorDowngrade(vendor, ownerUserId) {
5080
- const updateData = {};
5081
- updateData.availability = {
5082
- corporate: false,
5083
- private: false,
5084
- school: false
5085
- };
5086
- updateData.products = {
5087
- active: false,
5088
- productsList: vendor.products?.productsList ?? []
5089
- };
5090
- updateData.calendar = {
5091
- active: false,
5092
- calendarData: vendor.calendar?.calendarData ?? []
5093
- };
5094
- updateData.downgradeSnapshot = {
5095
- availability: vendor.availability,
5096
- calendarActive: vendor.calendar?.active,
5097
- 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
+ }
5098
5234
  };
5099
- updateData.images = (vendor.images ?? []).map((image, index) => ({
5100
- ...image,
5101
- active: index < 6
5102
- }));
5103
5235
  const result = await VendorModel.updateOne(
5104
5236
  {
5105
5237
  _id: vendor._id,
@@ -5107,7 +5239,7 @@ async function applyVendorDowngrade(vendor, ownerUserId) {
5107
5239
  deletedAt: null,
5108
5240
  "owner.userId": ownerUserId
5109
5241
  },
5110
- { $set: updateData }
5242
+ { $inc: { licenceEpoch: 1 }, $set: updateData }
5111
5243
  );
5112
5244
  return (result?.matchedCount ?? 0) > 0;
5113
5245
  }
@@ -5127,37 +5259,6 @@ async function downgradeVendorProFeatures(userId, licenceType) {
5127
5259
  throw error;
5128
5260
  }
5129
5261
  }
5130
- async function applyVendorRestore(vendor, ownerUserId) {
5131
- const updateData = {};
5132
- const snapshot = vendor.downgradeSnapshot;
5133
- updateData.availability = {
5134
- corporate: snapshot?.availability?.corporate ?? true,
5135
- private: snapshot?.availability?.private ?? true,
5136
- school: snapshot?.availability?.school ?? true
5137
- };
5138
- updateData.products = {
5139
- active: snapshot?.productsActive ?? true,
5140
- productsList: vendor.products?.productsList ?? []
5141
- };
5142
- updateData.calendar = {
5143
- active: snapshot?.calendarActive ?? true,
5144
- calendarData: vendor.calendar?.calendarData ?? []
5145
- };
5146
- updateData.images = (vendor.images ?? []).map((image) => ({
5147
- ...image,
5148
- active: true
5149
- }));
5150
- const result = await VendorModel.updateOne(
5151
- {
5152
- _id: vendor._id,
5153
- active: true,
5154
- deletedAt: null,
5155
- "owner.userId": ownerUserId
5156
- },
5157
- { $set: updateData }
5158
- );
5159
- return (result?.matchedCount ?? 0) > 0;
5160
- }
5161
5262
  async function restoreVendorProFeatures(userId, licenceType) {
5162
5263
  const isProVendor = licenceType === import_cluemart_shared37.EnumUserLicence.PRO_VENDOR || licenceType === import_cluemart_shared37.EnumUserLicence.PRO_PLUS_VENDOR;
5163
5264
  if (!isProVendor) {
@@ -5174,6 +5275,61 @@ async function restoreVendorProFeatures(userId, licenceType) {
5174
5275
  throw error;
5175
5276
  }
5176
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
+ }
5177
5333
  async function handleVendorLicenceCompliance(user, now) {
5178
5334
  if (!user.licences || !user.vendor) {
5179
5335
  return;
@@ -5184,10 +5340,10 @@ async function handleVendorLicenceCompliance(user, now) {
5184
5340
  if (vendorLicencesOfUser.length === 0) {
5185
5341
  return;
5186
5342
  }
5187
- const proLicences2 = vendorLicencesOfUser.filter(
5343
+ const proLicences = vendorLicencesOfUser.filter(
5188
5344
  (licence) => licence.licenceType !== import_cluemart_shared37.EnumUserLicence.STANDARD_VENDOR
5189
5345
  );
5190
- const expiredProLicences = proLicences2.filter(
5346
+ const expiredProLicences = proLicences.filter(
5191
5347
  (licence) => !(0, import_dayjs6.default)(licence.expiryDate).isAfter(now)
5192
5348
  );
5193
5349
  const stripeProtectedLicenceTypes = new Set(
@@ -5198,7 +5354,7 @@ async function handleVendorLicenceCompliance(user, now) {
5198
5354
  const expiredProLicence = expiredProLicences.some(
5199
5355
  (licence) => !stripeProtectedLicenceTypes.has(licence.licenceType)
5200
5356
  );
5201
- 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);
5202
5358
  const hasExpiredVendorLicence = vendorLicencesOfUser.some(
5203
5359
  (licence) => !(0, import_dayjs6.default)(licence.expiryDate).isAfter(now) && !stripeProtectedLicenceTypes.has(licence.licenceType)
5204
5360
  );
@@ -5214,29 +5370,27 @@ async function handleVendorLicenceCompliance(user, now) {
5214
5370
  "owner.userId": user._id
5215
5371
  }).lean().exec();
5216
5372
  }
5373
+ const needsDowngrade = expiredProLicence && Boolean(vendor) && !hasValidProLicence;
5374
+ const outcome = needsDowngrade && vendor ? await applyVendorDowngrade(vendor, user._id) : "skipped";
5217
5375
  const licencesToSync = import_cluemart_shared37.vendorLicences.filter(
5218
5376
  (licenceType) => !stripeProtectedLicenceTypes.has(licenceType)
5219
5377
  );
5220
- await syncUserLicencesAfterExpiry(user._id, licencesToSync, now, "downgrade");
5221
- if (!expiredProLicence || !vendor || hasValidProLicence) {
5378
+ if (!needsDowngrade) {
5379
+ await syncUserLicencesAfterExpiry(
5380
+ user._id,
5381
+ licencesToSync,
5382
+ now,
5383
+ "downgrade"
5384
+ );
5222
5385
  return;
5223
5386
  }
5224
- const downgraded = await applyVendorDowngrade(vendor, user._id);
5225
- if (!downgraded) {
5387
+ if (outcome === "skipped" || !vendor) {
5226
5388
  return;
5227
5389
  }
5228
- const payload = {
5229
- data: {
5230
- resourceId: String(vendor._id),
5231
- resourceName: vendor.name,
5232
- resourceType: import_cluemart_shared37.EnumNotificationResourceType.DOWNGRADED_VENDOR
5233
- },
5234
- message: `Your Vendor licence has been downgraded due to licence expiration.`,
5235
- title: `Vendor Licence Downgraded`,
5236
- type: import_cluemart_shared37.EnumNotificationType.SYSTEM,
5237
- userIds: [user._id]
5238
- };
5239
- 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");
5240
5394
  }
5241
5395
  async function vendorOwnerHasProLicence(vendorId) {
5242
5396
  const vendor = await VendorModel.findOne({
@@ -5281,17 +5435,35 @@ function hasValidLicence(licences, licenceTypes, now) {
5281
5435
  (licence) => licenceTypes.includes(licence.licenceType) && (0, import_dayjs7.default)(licence.expiryDate).isAfter(now)
5282
5436
  );
5283
5437
  }
5284
- 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
+ }
5285
5456
  const sent = await notifyUsers({ payload });
5286
5457
  if (!sent) {
5287
5458
  console.error(
5288
5459
  `\u274C ${resourceType} notification not confirmed for user ${String(userId)} for "${resourceName}"`
5289
5460
  );
5290
- return;
5461
+ return false;
5291
5462
  }
5292
5463
  console.log(
5293
5464
  `\u2705 Sent ${resourceType} notification to user ${String(userId)} for "${resourceName}"`
5294
5465
  );
5466
+ return true;
5295
5467
  }
5296
5468
  async function processUserCompliance(user, now) {
5297
5469
  if (!user.licences) {
@@ -5668,6 +5840,7 @@ async function remindUsersAboutLicenseExpiration() {
5668
5840
  acceptedAssociateUserIds,
5669
5841
  activeAffiliateCodeExists,
5670
5842
  awardAffiliateVendorSubscriptionRewards,
5843
+ buildAssociatesWriteGuard,
5671
5844
  buildLicenceExpiryPipeline,
5672
5845
  buildUserHasEnoughPointsFilter,
5673
5846
  buildUserPointAwardEntry,
@@ -5725,6 +5898,7 @@ async function remindUsersAboutLicenseExpiration() {
5725
5898
  notifyUsers,
5726
5899
  partnerLicences,
5727
5900
  persistArchivedEventDates,
5901
+ pinAssociateTimestamp,
5728
5902
  processLicenseReminder,
5729
5903
  processUserCompliance,
5730
5904
  processUserLicenseReminders,