@timardex/cluemart-server-shared 2.0.2 → 2.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
1
  import * as mongoose from 'mongoose';
2
2
  import * as _timardex_cluemart_shared from '@timardex/cluemart-shared';
3
3
  import { PromoCodeType, EnumAffiliateRewardType, DateTimeType, EventListItemType, DateTimeWithPriceType, EnumUserLicence as EnumUserLicence$1, UserLicenceType, EnumNotificationResourceType, EnumNotificationType, EnumResourceType } from '@timardex/cluemart-shared';
4
- import { d as SchemaAffiliateResourceType, S as SchemaOwnerType, g as SchemaRelationType, j as SchemaUserType } from '../Affiliate-CMJdECzs.mjs';
4
+ import { d as SchemaAffiliateResourceType, S as SchemaOwnerType, g as SchemaRelationType, j as SchemaUserType } from '../Affiliate-B1mxoMeD.mjs';
5
5
  import { O as ObjectId, G as GraphQLContext, e as SchemaCreateBulkNotificationInput } from '../index-Bq-lT7a2.mjs';
6
6
  import dayjs, { Dayjs } from 'dayjs';
7
7
  import { DateTimeType as DateTimeType$1 } from '@timardex/cluemart-shared/types';
@@ -34,13 +34,14 @@ type AwardAffiliateVendorSubscriptionRewardsResult = {
34
34
  * - `affiliateResources.resourceOwner` has a non-expired Standard / Pro / Pro+ vendor licence
35
35
  *
36
36
  * Reward type follows the owner's highest valid licence + Stripe paying status:
37
- * - Pro / Pro+ with paying Stripe (ACTIVE/TRIALING) → `ACTIVE_VENDOR_PRO_SUBSCRIPTION` (3 pts)
37
+ * - Pro / Pro+ with paying Stripe (ACTIVE) → `ACTIVE_VENDOR_PRO_SUBSCRIPTION` (3 pts)
38
38
  * - Pro / Pro+ without paying Stripe → `ACTIVE_VENDOR_STANDARD_SUBSCRIPTION` (1 pt)
39
39
  * - Standard → `ACTIVE_VENDOR_STANDARD_SUBSCRIPTION` (1 pt)
40
40
  *
41
41
  * Idempotent per affiliate + vendor + calendar month — a mid-month licence
42
42
  * upgrade (Standard → paying Pro) takes effect from the following month.
43
- * On successful award, notifies the affiliate owner (best-effort).
43
+ * On successful awards, sends the affiliate owner a single aggregated
44
+ * notification per run (best-effort).
44
45
  *
45
46
  * @param now - Reference time for month bounds and licence expiry (defaults to now).
46
47
  * @returns Counts of awarded and skipped candidates.
@@ -202,7 +203,8 @@ type PayingStripeSubscriptionPlanResult = {
202
203
  };
203
204
  /**
204
205
  * Returns the paying Stripe plan when `currentPlan` is any PRO plan
205
- * (event or vendor) and the subscription is active/trialing.
206
+ * (event or vendor), the subscription is active, and its finite paid-through
207
+ * `endDate` is later than `now`. Status alone does not establish paid access.
206
208
  */
207
209
  declare function getPayingStripeSubscriptionPlan(userId: ObjectId | string, now?: Date): Promise<PayingStripeSubscriptionPlanResult>;
208
210
  /**
@@ -310,7 +312,15 @@ declare function sendDeactivationNotification(payload: {
310
312
  */
311
313
  declare function processUserCompliance(user: SchemaUserType, now: dayjs.Dayjs): Promise<void>;
312
314
 
313
- declare function updateVendorBasedOnUserLicense(userId: ObjectId, licenceType: EnumUserLicence$1): Promise<void>;
315
+ declare function downgradeVendorProFeatures(userId: ObjectId, licenceType: EnumUserLicence$1): Promise<void>;
316
+ /**
317
+ * Restores the PRO vendor features that are removed by
318
+ * downgradeVendorProFeatures when a vendor is downgraded to STANDARD_VENDOR.
319
+ * This is the opposite operation: it re-enables availability, products and
320
+ * calendar from the pre-downgrade snapshot (falling back to fully enabled when
321
+ * no snapshot exists), and keeps all images active.
322
+ */
323
+ declare function restoreVendorProFeatures(userId: ObjectId, licenceType: EnumUserLicence$1): Promise<void>;
314
324
  declare const vendorLicences: EnumUserLicence$1[];
315
325
  /**
316
326
  * Handles vendor licence compliance for a single user
@@ -467,4 +477,4 @@ declare function checkOwnerHasLicence({ userId, resourceType, }: {
467
477
  resourceType: EnumResourceType;
468
478
  }): Promise<void>;
469
479
 
470
- export { ACTIVE_NOT_DELETED_FILTER, type AwardAffiliateVendorSubscriptionRewardsResult, LicenceCategory, LicenceExpiryDate, type NotificationPubSub, REMINDER_WINDOW_MAX_HOURS, REMINDER_WINDOW_MIN_HOURS, SUBSCRIPTION_REWARD_TIMEZONE, activeAffiliateCodeExists, awardAffiliateVendorSubscriptionRewards, buildLicenceExpiryPipeline, checkOwnerHasLicence, connectToDatabase, convertObjectIdsToStrings, createLicenceObject, didRemoveAnyEventDates, ensureUserLicenseCompliance, ensureUserLicenseComplianceForUser, eventLicences, findAffiliateByPromoCode, findEventOrImportedMarketById, getEventResourceInfo, getHighestLicenceForCategory, getLicenceCategory, getLicenceExpiryMode, getPartnerResourceInfo, getPayingEventStripeSubscriptionPlan, getPayingStripeSubscriptionPlan, getPayingVendorStripeSubscriptionPlan, getSubscriptionRewardPeriodBounds, getVendorResourceInfo, handleEventLicenceCompliance, handlePartnerLicenceCompliance, handleVendorLicenceCompliance, hasValidLicence, isStandardLicence, isValidObjectId, licenceCategoryMapping, licencePriority, mapVendorLicenceToSubscriptionRewardType, normalizeAffiliatePromoCodes, normalizePromoCode, notifyUsers, partnerLicences, processLicenseReminder, processUserCompliance, processUserLicenseReminders, publishNotificationEvents, remindUsersAboutLicenseExpiration, replaceUserLicenceWithObject, saveNotificationsInDb, sendDeactivationNotification, sendLicenseReminder, sendPushNotifications, sendReminderSafely, syncUserLicencesAfterExpiry, updateAdStatuses, updateAllEventDateTimeStatuses, updateRelationDatesToUnavailable, updateSingleDateTimeStatus, updateVendorBasedOnUserLicense, upgradeUserToLicence, vendorLicences, vendorOwnerHasProLicence };
480
+ export { ACTIVE_NOT_DELETED_FILTER, type AwardAffiliateVendorSubscriptionRewardsResult, LicenceCategory, LicenceExpiryDate, type NotificationPubSub, REMINDER_WINDOW_MAX_HOURS, REMINDER_WINDOW_MIN_HOURS, SUBSCRIPTION_REWARD_TIMEZONE, activeAffiliateCodeExists, awardAffiliateVendorSubscriptionRewards, buildLicenceExpiryPipeline, checkOwnerHasLicence, connectToDatabase, convertObjectIdsToStrings, createLicenceObject, didRemoveAnyEventDates, downgradeVendorProFeatures, ensureUserLicenseCompliance, ensureUserLicenseComplianceForUser, eventLicences, findAffiliateByPromoCode, findEventOrImportedMarketById, getEventResourceInfo, getHighestLicenceForCategory, getLicenceCategory, getLicenceExpiryMode, getPartnerResourceInfo, getPayingEventStripeSubscriptionPlan, getPayingStripeSubscriptionPlan, getPayingVendorStripeSubscriptionPlan, getSubscriptionRewardPeriodBounds, getVendorResourceInfo, handleEventLicenceCompliance, handlePartnerLicenceCompliance, handleVendorLicenceCompliance, hasValidLicence, isStandardLicence, isValidObjectId, licenceCategoryMapping, licencePriority, mapVendorLicenceToSubscriptionRewardType, normalizeAffiliatePromoCodes, normalizePromoCode, notifyUsers, partnerLicences, processLicenseReminder, processUserCompliance, processUserLicenseReminders, publishNotificationEvents, remindUsersAboutLicenseExpiration, replaceUserLicenceWithObject, restoreVendorProFeatures, saveNotificationsInDb, sendDeactivationNotification, sendLicenseReminder, sendPushNotifications, sendReminderSafely, syncUserLicencesAfterExpiry, updateAdStatuses, updateAllEventDateTimeStatuses, updateRelationDatesToUnavailable, updateSingleDateTimeStatus, upgradeUserToLicence, vendorLicences, vendorOwnerHasProLicence };
@@ -1,7 +1,7 @@
1
1
  import * as mongoose from 'mongoose';
2
2
  import * as _timardex_cluemart_shared from '@timardex/cluemart-shared';
3
3
  import { PromoCodeType, EnumAffiliateRewardType, DateTimeType, EventListItemType, DateTimeWithPriceType, EnumUserLicence as EnumUserLicence$1, UserLicenceType, EnumNotificationResourceType, EnumNotificationType, EnumResourceType } from '@timardex/cluemart-shared';
4
- import { d as SchemaAffiliateResourceType, S as SchemaOwnerType, g as SchemaRelationType, j as SchemaUserType } from '../Affiliate-VLZdlt5K.js';
4
+ import { d as SchemaAffiliateResourceType, S as SchemaOwnerType, g as SchemaRelationType, j as SchemaUserType } from '../Affiliate-Dlf_OLIh.js';
5
5
  import { O as ObjectId, G as GraphQLContext, e as SchemaCreateBulkNotificationInput } from '../index-Bq-lT7a2.js';
6
6
  import dayjs, { Dayjs } from 'dayjs';
7
7
  import { DateTimeType as DateTimeType$1 } from '@timardex/cluemart-shared/types';
@@ -34,13 +34,14 @@ type AwardAffiliateVendorSubscriptionRewardsResult = {
34
34
  * - `affiliateResources.resourceOwner` has a non-expired Standard / Pro / Pro+ vendor licence
35
35
  *
36
36
  * Reward type follows the owner's highest valid licence + Stripe paying status:
37
- * - Pro / Pro+ with paying Stripe (ACTIVE/TRIALING) → `ACTIVE_VENDOR_PRO_SUBSCRIPTION` (3 pts)
37
+ * - Pro / Pro+ with paying Stripe (ACTIVE) → `ACTIVE_VENDOR_PRO_SUBSCRIPTION` (3 pts)
38
38
  * - Pro / Pro+ without paying Stripe → `ACTIVE_VENDOR_STANDARD_SUBSCRIPTION` (1 pt)
39
39
  * - Standard → `ACTIVE_VENDOR_STANDARD_SUBSCRIPTION` (1 pt)
40
40
  *
41
41
  * Idempotent per affiliate + vendor + calendar month — a mid-month licence
42
42
  * upgrade (Standard → paying Pro) takes effect from the following month.
43
- * On successful award, notifies the affiliate owner (best-effort).
43
+ * On successful awards, sends the affiliate owner a single aggregated
44
+ * notification per run (best-effort).
44
45
  *
45
46
  * @param now - Reference time for month bounds and licence expiry (defaults to now).
46
47
  * @returns Counts of awarded and skipped candidates.
@@ -202,7 +203,8 @@ type PayingStripeSubscriptionPlanResult = {
202
203
  };
203
204
  /**
204
205
  * Returns the paying Stripe plan when `currentPlan` is any PRO plan
205
- * (event or vendor) and the subscription is active/trialing.
206
+ * (event or vendor), the subscription is active, and its finite paid-through
207
+ * `endDate` is later than `now`. Status alone does not establish paid access.
206
208
  */
207
209
  declare function getPayingStripeSubscriptionPlan(userId: ObjectId | string, now?: Date): Promise<PayingStripeSubscriptionPlanResult>;
208
210
  /**
@@ -310,7 +312,15 @@ declare function sendDeactivationNotification(payload: {
310
312
  */
311
313
  declare function processUserCompliance(user: SchemaUserType, now: dayjs.Dayjs): Promise<void>;
312
314
 
313
- declare function updateVendorBasedOnUserLicense(userId: ObjectId, licenceType: EnumUserLicence$1): Promise<void>;
315
+ declare function downgradeVendorProFeatures(userId: ObjectId, licenceType: EnumUserLicence$1): Promise<void>;
316
+ /**
317
+ * Restores the PRO vendor features that are removed by
318
+ * downgradeVendorProFeatures when a vendor is downgraded to STANDARD_VENDOR.
319
+ * This is the opposite operation: it re-enables availability, products and
320
+ * calendar from the pre-downgrade snapshot (falling back to fully enabled when
321
+ * no snapshot exists), and keeps all images active.
322
+ */
323
+ declare function restoreVendorProFeatures(userId: ObjectId, licenceType: EnumUserLicence$1): Promise<void>;
314
324
  declare const vendorLicences: EnumUserLicence$1[];
315
325
  /**
316
326
  * Handles vendor licence compliance for a single user
@@ -467,4 +477,4 @@ declare function checkOwnerHasLicence({ userId, resourceType, }: {
467
477
  resourceType: EnumResourceType;
468
478
  }): Promise<void>;
469
479
 
470
- export { ACTIVE_NOT_DELETED_FILTER, type AwardAffiliateVendorSubscriptionRewardsResult, LicenceCategory, LicenceExpiryDate, type NotificationPubSub, REMINDER_WINDOW_MAX_HOURS, REMINDER_WINDOW_MIN_HOURS, SUBSCRIPTION_REWARD_TIMEZONE, activeAffiliateCodeExists, awardAffiliateVendorSubscriptionRewards, buildLicenceExpiryPipeline, checkOwnerHasLicence, connectToDatabase, convertObjectIdsToStrings, createLicenceObject, didRemoveAnyEventDates, ensureUserLicenseCompliance, ensureUserLicenseComplianceForUser, eventLicences, findAffiliateByPromoCode, findEventOrImportedMarketById, getEventResourceInfo, getHighestLicenceForCategory, getLicenceCategory, getLicenceExpiryMode, getPartnerResourceInfo, getPayingEventStripeSubscriptionPlan, getPayingStripeSubscriptionPlan, getPayingVendorStripeSubscriptionPlan, getSubscriptionRewardPeriodBounds, getVendorResourceInfo, handleEventLicenceCompliance, handlePartnerLicenceCompliance, handleVendorLicenceCompliance, hasValidLicence, isStandardLicence, isValidObjectId, licenceCategoryMapping, licencePriority, mapVendorLicenceToSubscriptionRewardType, normalizeAffiliatePromoCodes, normalizePromoCode, notifyUsers, partnerLicences, processLicenseReminder, processUserCompliance, processUserLicenseReminders, publishNotificationEvents, remindUsersAboutLicenseExpiration, replaceUserLicenceWithObject, saveNotificationsInDb, sendDeactivationNotification, sendLicenseReminder, sendPushNotifications, sendReminderSafely, syncUserLicencesAfterExpiry, updateAdStatuses, updateAllEventDateTimeStatuses, updateRelationDatesToUnavailable, updateSingleDateTimeStatus, updateVendorBasedOnUserLicense, upgradeUserToLicence, vendorLicences, vendorOwnerHasProLicence };
480
+ export { ACTIVE_NOT_DELETED_FILTER, type AwardAffiliateVendorSubscriptionRewardsResult, LicenceCategory, LicenceExpiryDate, type NotificationPubSub, REMINDER_WINDOW_MAX_HOURS, REMINDER_WINDOW_MIN_HOURS, SUBSCRIPTION_REWARD_TIMEZONE, activeAffiliateCodeExists, awardAffiliateVendorSubscriptionRewards, buildLicenceExpiryPipeline, checkOwnerHasLicence, connectToDatabase, convertObjectIdsToStrings, createLicenceObject, didRemoveAnyEventDates, downgradeVendorProFeatures, ensureUserLicenseCompliance, ensureUserLicenseComplianceForUser, eventLicences, findAffiliateByPromoCode, findEventOrImportedMarketById, getEventResourceInfo, getHighestLicenceForCategory, getLicenceCategory, getLicenceExpiryMode, getPartnerResourceInfo, getPayingEventStripeSubscriptionPlan, getPayingStripeSubscriptionPlan, getPayingVendorStripeSubscriptionPlan, getSubscriptionRewardPeriodBounds, getVendorResourceInfo, handleEventLicenceCompliance, handlePartnerLicenceCompliance, handleVendorLicenceCompliance, hasValidLicence, isStandardLicence, isValidObjectId, licenceCategoryMapping, licencePriority, mapVendorLicenceToSubscriptionRewardType, normalizeAffiliatePromoCodes, normalizePromoCode, notifyUsers, partnerLicences, processLicenseReminder, processUserCompliance, processUserLicenseReminders, publishNotificationEvents, remindUsersAboutLicenseExpiration, replaceUserLicenceWithObject, restoreVendorProFeatures, saveNotificationsInDb, sendDeactivationNotification, sendLicenseReminder, sendPushNotifications, sendReminderSafely, syncUserLicencesAfterExpiry, updateAdStatuses, updateAllEventDateTimeStatuses, updateRelationDatesToUnavailable, updateSingleDateTimeStatus, upgradeUserToLicence, vendorLicences, vendorOwnerHasProLicence };
@@ -8,7 +8,7 @@ import {
8
8
  PushTokenModel,
9
9
  UserModel,
10
10
  VendorModel
11
- } from "../chunk-IICIHY26.mjs";
11
+ } from "../chunk-MEEBCSMJ.mjs";
12
12
  import "../chunk-6PNG5BI5.mjs";
13
13
 
14
14
  // src/service/promoCode/constants.ts
@@ -208,8 +208,9 @@ async function getPayingStripePlanFor(userId, now, payingPlans) {
208
208
  if (stripe == null || stripe.subscriptionId == null) {
209
209
  return { hasSubscription: false, plan: null, validTypes };
210
210
  }
211
- const hasActiveStatus = stripe.status === EnumSubscriptionStatus.ACTIVE || stripe.status === EnumSubscriptionStatus.TRIALING;
212
- if (!hasActiveStatus || stripe.currentPlan == null) {
211
+ const hasActiveStatus = stripe.status === EnumSubscriptionStatus.ACTIVE;
212
+ const paidThrough = stripe.endDate ? new Date(stripe.endDate).getTime() : Number.NaN;
213
+ if (!hasActiveStatus || !Number.isFinite(paidThrough) || paidThrough <= now.getTime() || stripe.currentPlan == null) {
213
214
  return { hasSubscription: false, plan: null, validTypes };
214
215
  }
215
216
  const plan = payingPlans.has(stripe.currentPlan) ? stripe.currentPlan : null;
@@ -280,16 +281,22 @@ async function isEligibleReferredVendor({
280
281
  async function notifyAffiliateOwnerOfSubscriptionReward({
281
282
  affiliateId,
282
283
  affiliateOwnerUserId,
283
- resourceName,
284
- rewardValue
284
+ awards
285
285
  }) {
286
+ if (awards.length === 0) {
287
+ return;
288
+ }
289
+ const totalPoints = awards.reduce((sum, award) => sum + award.rewardValue, 0);
290
+ const resourceNames = awards.map((award) => award.resourceName);
291
+ const pointLabel = totalPoints === 1 ? "point" : "points";
292
+ const message = awards.length === 1 ? `You earned ${totalPoints} ${pointLabel}! Your referred vendor "${resourceNames[0]}" has an active subscription.` : `You earned ${totalPoints} ${pointLabel}! ${awards.length} of your referred vendors have an active subscription.`;
286
293
  const payload = {
287
294
  data: {
288
295
  resourceId: String(affiliateId),
289
- resourceName,
296
+ resourceName: resourceNames.join(", "),
290
297
  resourceType: EnumNotificationResourceType.AFFILIATE_REWARD_RECEIVED
291
298
  },
292
- message: `You earned ${rewardValue} points! Your referred vendor "${resourceName}" has an active subscription.`,
299
+ message,
293
300
  title: "Affiliate points earned",
294
301
  type: EnumNotificationType.SYSTEM,
295
302
  userIds: [affiliateOwnerUserId]
@@ -341,15 +348,12 @@ async function tryAwardSubscriptionReward({
341
348
  }
342
349
  ).exec();
343
350
  if (updateResult.modifiedCount === 0) {
344
- return "skipped";
351
+ return null;
345
352
  }
346
- await notifyAffiliateOwnerOfSubscriptionReward({
347
- affiliateId: affiliate._id,
348
- affiliateOwnerUserId: affiliate.owner.userId,
353
+ return {
349
354
  resourceName: resource.resourceName,
350
355
  rewardValue: reward.rewardValue
351
- });
352
- return "awarded";
356
+ };
353
357
  }
354
358
  async function processAffiliateVendorReferral({
355
359
  affiliate,
@@ -363,14 +367,14 @@ async function processAffiliateVendorReferral({
363
367
  resourceOwnerUserId: resource.resourceOwner.userId
364
368
  });
365
369
  if (!vendorEligible) {
366
- return "skipped";
370
+ return null;
367
371
  }
368
372
  const rewardType = await mapVendorLicenceToSubscriptionRewardType(
369
373
  resource.resourceOwner.userId,
370
374
  now
371
375
  );
372
376
  if (!rewardType) {
373
- return "skipped";
377
+ return null;
374
378
  }
375
379
  return tryAwardSubscriptionReward({
376
380
  affiliate,
@@ -386,8 +390,9 @@ async function awardAffiliateVendorSubscriptionRewards(now = /* @__PURE__ */ new
386
390
  const affiliates = await findAffiliatesWithActiveVendorReferrals();
387
391
  let awarded = 0;
388
392
  let skipped = 0;
389
- const seenPairs = /* @__PURE__ */ new Set();
390
393
  for (const affiliate of affiliates) {
394
+ const awards = [];
395
+ const seenPairs = /* @__PURE__ */ new Set();
391
396
  for (const resource of affiliate.affiliateResources) {
392
397
  if (!isEligibleVendorResource(resource)) {
393
398
  continue;
@@ -397,19 +402,27 @@ async function awardAffiliateVendorSubscriptionRewards(now = /* @__PURE__ */ new
397
402
  continue;
398
403
  }
399
404
  seenPairs.add(pairKey);
400
- const outcome = await processAffiliateVendorReferral({
405
+ const award = await processAffiliateVendorReferral({
401
406
  affiliate,
402
407
  createdAt,
403
408
  now,
404
409
  period,
405
410
  resource
406
411
  });
407
- if (outcome === "awarded") {
412
+ if (award) {
408
413
  awarded += 1;
414
+ awards.push(award);
409
415
  } else {
410
416
  skipped += 1;
411
417
  }
412
418
  }
419
+ if (awards.length > 0) {
420
+ await notifyAffiliateOwnerOfSubscriptionReward({
421
+ affiliateId: affiliate._id,
422
+ affiliateOwnerUserId: affiliate.owner.userId,
423
+ awards
424
+ });
425
+ }
413
426
  }
414
427
  return { awarded, skipped };
415
428
  }
@@ -505,7 +518,12 @@ async function notifyUsers({
505
518
  }
506
519
 
507
520
  // src/service/updateAdStatus.ts
508
- import { EnumAdStatus } from "@timardex/cluemart-shared";
521
+ import {
522
+ EnumAdApprovalStatus,
523
+ EnumAdBookingSlotKind,
524
+ EnumAdPaymentStatus,
525
+ EnumAdStatus
526
+ } from "@timardex/cluemart-shared";
509
527
  async function updateAdStatuses() {
510
528
  const now = /* @__PURE__ */ new Date();
511
529
  const invalidResult = await AdModel.updateMany(
@@ -523,11 +541,36 @@ async function updateAdStatuses() {
523
541
  { end: { $lte: now }, status: { $ne: EnumAdStatus.EXPIRED } },
524
542
  { $set: { status: EnumAdStatus.EXPIRED } }
525
543
  );
544
+ const eligibleBooking = {
545
+ $or: [
546
+ { bookingKind: { $exists: false } },
547
+ { bookingKind: null },
548
+ {
549
+ approvalStatus: EnumAdApprovalStatus.APPROVED,
550
+ bookingKind: EnumAdBookingSlotKind.RESERVED
551
+ },
552
+ {
553
+ approvalStatus: EnumAdApprovalStatus.APPROVED,
554
+ bookingKind: EnumAdBookingSlotKind.PAID,
555
+ paymentStatus: EnumAdPaymentStatus.PAID
556
+ }
557
+ ]
558
+ };
559
+ const awaitingApprovalResult = await AdModel.updateMany(
560
+ {
561
+ $nor: eligibleBooking.$or,
562
+ bookingKind: { $in: Object.values(EnumAdBookingSlotKind) },
563
+ end: { $gt: now },
564
+ status: EnumAdStatus.ACTIVE
565
+ },
566
+ { $set: { status: EnumAdStatus.PAUSED } }
567
+ );
526
568
  const activeResult = await AdModel.updateMany(
527
569
  {
528
570
  end: { $gt: now },
529
571
  start: { $lte: now },
530
- status: { $ne: EnumAdStatus.ACTIVE }
572
+ status: { $ne: EnumAdStatus.ACTIVE },
573
+ ...eligibleBooking
531
574
  },
532
575
  { $set: { status: EnumAdStatus.ACTIVE } }
533
576
  );
@@ -536,7 +579,7 @@ async function updateAdStatuses() {
536
579
  { $set: { status: EnumAdStatus.PAUSED } }
537
580
  );
538
581
  console.log(
539
- `\u2705 Ad statuses updated: invalid=${invalidResult.modifiedCount}, expired=${expiredResult.modifiedCount}, active=${activeResult.modifiedCount}, paused=${pausedResult.modifiedCount}`
582
+ `\u2705 Ad statuses updated: invalid=${invalidResult.modifiedCount}, expired=${expiredResult.modifiedCount}, awaitingApproval=${awaitingApprovalResult.modifiedCount}, active=${activeResult.modifiedCount}, paused=${pausedResult.modifiedCount}`
540
583
  );
541
584
  }
542
585
 
@@ -1216,42 +1259,122 @@ async function checkOwnerHasLicence({
1216
1259
  }
1217
1260
 
1218
1261
  // src/service/license/compliance/vendor.ts
1219
- async function updateVendorBasedOnUserLicense(userId, licenceType) {
1262
+ async function findUserVendor(userId, logLabel) {
1263
+ const user = await UserModel.findById(userId).select("vendor").lean().exec();
1264
+ if (!user?.vendor) {
1265
+ console.warn(`[${logLabel}] No vendor found for userId=${userId}`);
1266
+ return null;
1267
+ }
1268
+ const vendor = await VendorModel.findOne({
1269
+ _id: user.vendor,
1270
+ active: true,
1271
+ deletedAt: null,
1272
+ "owner.userId": userId
1273
+ }).lean().exec();
1274
+ if (!vendor) {
1275
+ console.warn(
1276
+ `[${logLabel}] Vendor not found for id=${user.vendor}, userId=${userId}`
1277
+ );
1278
+ return null;
1279
+ }
1280
+ return vendor;
1281
+ }
1282
+ async function applyVendorDowngrade(vendor, ownerUserId) {
1283
+ const updateData = {};
1284
+ updateData.availability = {
1285
+ corporate: false,
1286
+ private: false,
1287
+ school: false
1288
+ };
1289
+ updateData.products = {
1290
+ active: false,
1291
+ productsList: vendor.products?.productsList ?? []
1292
+ };
1293
+ updateData.calendar = {
1294
+ active: false,
1295
+ calendarData: vendor.calendar?.calendarData ?? []
1296
+ };
1297
+ updateData.downgradeSnapshot = {
1298
+ availability: vendor.availability,
1299
+ calendarActive: vendor.calendar?.active,
1300
+ productsActive: vendor.products?.active
1301
+ };
1302
+ updateData.images = (vendor.images ?? []).map((image, index) => ({
1303
+ ...image,
1304
+ active: index < 6
1305
+ }));
1306
+ const result = await VendorModel.updateOne(
1307
+ {
1308
+ _id: vendor._id,
1309
+ active: true,
1310
+ deletedAt: null,
1311
+ "owner.userId": ownerUserId
1312
+ },
1313
+ { $set: updateData }
1314
+ );
1315
+ return (result?.matchedCount ?? 0) > 0;
1316
+ }
1317
+ async function downgradeVendorProFeatures(userId, licenceType) {
1318
+ const isStandardVendor = licenceType === EnumUserLicence6.STANDARD_VENDOR;
1319
+ if (!isStandardVendor) {
1320
+ return;
1321
+ }
1220
1322
  try {
1221
- const user = await UserModel.findById(userId).select("vendor").lean().exec();
1222
- if (!user?.vendor) {
1223
- console.warn(`[updateVendor] No vendor found for userId=${userId}`);
1323
+ const vendor = await findUserVendor(userId, "downgradeVendorProFeatures");
1324
+ if (!vendor) {
1224
1325
  return;
1225
1326
  }
1226
- const vendor = await VendorModel.findById(user.vendor).lean().exec();
1327
+ await applyVendorDowngrade(vendor, userId);
1328
+ } catch (error) {
1329
+ console.error("[downgradeVendorProFeatures] Failed:", error);
1330
+ throw error;
1331
+ }
1332
+ }
1333
+ async function applyVendorRestore(vendor, ownerUserId) {
1334
+ const updateData = {};
1335
+ const snapshot = vendor.downgradeSnapshot;
1336
+ updateData.availability = {
1337
+ corporate: snapshot?.availability?.corporate ?? true,
1338
+ private: snapshot?.availability?.private ?? true,
1339
+ school: snapshot?.availability?.school ?? true
1340
+ };
1341
+ updateData.products = {
1342
+ active: snapshot?.productsActive ?? true,
1343
+ productsList: vendor.products?.productsList ?? []
1344
+ };
1345
+ updateData.calendar = {
1346
+ active: snapshot?.calendarActive ?? true,
1347
+ calendarData: vendor.calendar?.calendarData ?? []
1348
+ };
1349
+ updateData.images = (vendor.images ?? []).map((image) => ({
1350
+ ...image,
1351
+ active: true
1352
+ }));
1353
+ const result = await VendorModel.updateOne(
1354
+ {
1355
+ _id: vendor._id,
1356
+ active: true,
1357
+ deletedAt: null,
1358
+ "owner.userId": ownerUserId
1359
+ },
1360
+ { $set: updateData }
1361
+ );
1362
+ return (result?.matchedCount ?? 0) > 0;
1363
+ }
1364
+ async function restoreVendorProFeatures(userId, licenceType) {
1365
+ const isProVendor = licenceType === EnumUserLicence6.PRO_VENDOR || licenceType === EnumUserLicence6.PRO_PLUS_VENDOR;
1366
+ if (!isProVendor) {
1367
+ return;
1368
+ }
1369
+ try {
1370
+ const vendor = await findUserVendor(userId, "restoreVendorProFeatures");
1227
1371
  if (!vendor) {
1228
- console.warn(`[updateVendor] Vendor not found for id=${user.vendor}`);
1229
1372
  return;
1230
1373
  }
1231
- const updateData = {};
1232
- const isStandardVendor = licenceType === EnumUserLicence6.STANDARD_VENDOR;
1233
- if (isStandardVendor) {
1234
- updateData.availability = {
1235
- corporate: false,
1236
- private: false,
1237
- school: false
1238
- };
1239
- updateData.products = {
1240
- active: false,
1241
- productsList: vendor.products?.productsList ?? []
1242
- };
1243
- updateData.calendar = {
1244
- active: false,
1245
- calendarData: vendor.calendar?.calendarData ?? []
1246
- };
1247
- }
1248
- updateData.images = (vendor.images ?? []).map((image, index) => ({
1249
- ...image,
1250
- active: isStandardVendor ? index < 6 : true
1251
- }));
1252
- await VendorModel.updateOne({ _id: vendor._id }, { $set: updateData });
1374
+ await applyVendorRestore(vendor, userId);
1253
1375
  } catch (error) {
1254
- console.error("[updateVendorBasedOnUserLicense] Failed:", error);
1376
+ console.error("[restoreVendorProFeatures] Failed:", error);
1377
+ throw error;
1255
1378
  }
1256
1379
  }
1257
1380
  var vendorLicences = [
@@ -1261,14 +1384,25 @@ var vendorLicences = [
1261
1384
  ];
1262
1385
  function isProtectedByCurrentStripeSubscription(user, licenceType, now) {
1263
1386
  const stripe = user.stripe;
1264
- if (!stripe?.subscriptionId || stripe.currentPlan !== licenceType || stripe.status !== EnumSubscriptionStatus2.ACTIVE && stripe.status !== EnumSubscriptionStatus2.TRIALING) {
1387
+ if (!stripe || stripe.currentPlan !== licenceType) {
1265
1388
  return false;
1266
1389
  }
1267
- if (stripe.cancelAtPeriodEnd !== true || !stripe.endDate) {
1390
+ const gracePeriodEndsAt = stripe.paymentGracePeriodEndsAt ? dayjs4(stripe.paymentGracePeriodEndsAt) : null;
1391
+ const hasActivePaymentGracePeriod = (stripe.status === EnumSubscriptionStatus2.PAST_DUE || stripe.status === EnumSubscriptionStatus2.INACTIVE) && Boolean(stripe.paymentGraceSubscriptionId) && (!stripe.subscriptionId || stripe.subscriptionId === stripe.paymentGraceSubscriptionId) && gracePeriodEndsAt !== null && gracePeriodEndsAt.isValid() && gracePeriodEndsAt.isAfter(now);
1392
+ if (hasActivePaymentGracePeriod) {
1268
1393
  return true;
1269
1394
  }
1395
+ if (!stripe.subscriptionId) {
1396
+ return false;
1397
+ }
1398
+ if (stripe.status !== EnumSubscriptionStatus2.ACTIVE) {
1399
+ return false;
1400
+ }
1401
+ if (!stripe.endDate) {
1402
+ return false;
1403
+ }
1270
1404
  const paidThrough = dayjs4(stripe.endDate);
1271
- return !paidThrough.isValid() || paidThrough.isAfter(now);
1405
+ return paidThrough.isValid() && paidThrough.isAfter(now);
1272
1406
  }
1273
1407
  async function handleVendorLicenceCompliance(user, now) {
1274
1408
  if (!user.licences || !user.vendor) {
@@ -1317,10 +1451,10 @@ async function handleVendorLicenceCompliance(user, now) {
1317
1451
  if (!expiredProLicence || !vendor || hasValidProLicence) {
1318
1452
  return;
1319
1453
  }
1320
- await updateVendorBasedOnUserLicense(
1321
- user._id,
1322
- EnumUserLicence6.STANDARD_VENDOR
1323
- );
1454
+ const downgraded = await applyVendorDowngrade(vendor, user._id);
1455
+ if (!downgraded) {
1456
+ return;
1457
+ }
1324
1458
  const payload = {
1325
1459
  data: {
1326
1460
  resourceId: String(vendor._id),
@@ -1343,9 +1477,23 @@ async function vendorOwnerHasProLicence(vendorId) {
1343
1477
  if (!vendor) {
1344
1478
  return false;
1345
1479
  }
1346
- const owner = await UserModel.findById(vendor.owner.userId, { licences: 1 }).lean().exec();
1480
+ const owner = await UserModel.findById(vendor.owner.userId, {
1481
+ licences: 1,
1482
+ stripe: 1
1483
+ }).lean().exec();
1484
+ if (!owner) {
1485
+ return false;
1486
+ }
1487
+ const now = dayjs4();
1488
+ const effectiveVendorLicences = owner.licences?.filter(
1489
+ (licence) => licence?.licenceType && (dayjs4(licence.expiryDate).isAfter(now) || isProtectedByCurrentStripeSubscription(
1490
+ owner,
1491
+ licence.licenceType,
1492
+ now
1493
+ ))
1494
+ );
1347
1495
  const highestVendorLicence = getHighestLicenceForCategory(
1348
- owner?.licences,
1496
+ effectiveVendorLicences,
1349
1497
  "vendor" /* VENDOR */
1350
1498
  );
1351
1499
  return highestVendorLicence !== null && licencePriority[highestVendorLicence] >= licencePriority[EnumUserLicence6.PRO_VENDOR];
@@ -1775,6 +1923,7 @@ export {
1775
1923
  convertObjectIdsToStrings,
1776
1924
  createLicenceObject,
1777
1925
  didRemoveAnyEventDates,
1926
+ downgradeVendorProFeatures,
1778
1927
  ensureUserLicenseCompliance,
1779
1928
  ensureUserLicenseComplianceForUser,
1780
1929
  eventLicences,
@@ -1809,6 +1958,7 @@ export {
1809
1958
  publishNotificationEvents,
1810
1959
  remindUsersAboutLicenseExpiration,
1811
1960
  replaceUserLicenceWithObject,
1961
+ restoreVendorProFeatures,
1812
1962
  saveNotificationsInDb,
1813
1963
  sendDeactivationNotification,
1814
1964
  sendLicenseReminder,
@@ -1819,7 +1969,6 @@ export {
1819
1969
  updateAllEventDateTimeStatuses,
1820
1970
  updateRelationDatesToUnavailable,
1821
1971
  updateSingleDateTimeStatus,
1822
- updateVendorBasedOnUserLicense,
1823
1972
  upgradeUserToLicence,
1824
1973
  vendorLicences,
1825
1974
  vendorOwnerHasProLicence