@timardex/cluemart-server-shared 2.1.0 → 2.1.2

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
  /**
@@ -430,7 +432,9 @@ declare function getVendorResourceInfo(userId: ObjectId, vendorId: ObjectId): Pr
430
432
  declare enum LicenceExpiryDate {
431
433
  ONE_YEAR = "1 year",
432
434
  ONE_MONTH = "1 month",
433
- TWO_MONTHS = "2 months"
435
+ TWO_MONTHS = "2 months",
436
+ THREE_MONTHS = "3 months",
437
+ SIX_MONTHS = "6 months"
434
438
  }
435
439
  declare enum LicenceCategory {
436
440
  EVENT = "event",
@@ -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
  /**
@@ -430,7 +432,9 @@ declare function getVendorResourceInfo(userId: ObjectId, vendorId: ObjectId): Pr
430
432
  declare enum LicenceExpiryDate {
431
433
  ONE_YEAR = "1 year",
432
434
  ONE_MONTH = "1 month",
433
- TWO_MONTHS = "2 months"
435
+ TWO_MONTHS = "2 months",
436
+ THREE_MONTHS = "3 months",
437
+ SIX_MONTHS = "6 months"
434
438
  }
435
439
  declare enum LicenceCategory {
436
440
  EVENT = "event",
@@ -8,7 +8,7 @@ import {
8
8
  PushTokenModel,
9
9
  UserModel,
10
10
  VendorModel
11
- } from "../chunk-BEUTBR4H.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
 
@@ -997,6 +1040,8 @@ var LicenceExpiryDate = /* @__PURE__ */ ((LicenceExpiryDate2) => {
997
1040
  LicenceExpiryDate2["ONE_YEAR"] = "1 year";
998
1041
  LicenceExpiryDate2["ONE_MONTH"] = "1 month";
999
1042
  LicenceExpiryDate2["TWO_MONTHS"] = "2 months";
1043
+ LicenceExpiryDate2["THREE_MONTHS"] = "3 months";
1044
+ LicenceExpiryDate2["SIX_MONTHS"] = "6 months";
1000
1045
  return LicenceExpiryDate2;
1001
1046
  })(LicenceExpiryDate || {});
1002
1047
  var LicenceCategory = /* @__PURE__ */ ((LicenceCategory2) => {
@@ -1082,7 +1127,9 @@ function createLicenceObject(expiryDate, licenceType) {
1082
1127
  const expiryDateMapping = {
1083
1128
  ["1 year" /* ONE_YEAR */]: today.add(1, "year").endOf("day").toDate(),
1084
1129
  ["1 month" /* ONE_MONTH */]: today.add(1, "month").endOf("day").toDate(),
1085
- ["2 months" /* TWO_MONTHS */]: today.add(2, "month").endOf("day").toDate()
1130
+ ["2 months" /* TWO_MONTHS */]: today.add(2, "month").endOf("day").toDate(),
1131
+ ["3 months" /* THREE_MONTHS */]: today.add(3, "month").endOf("day").toDate(),
1132
+ ["6 months" /* SIX_MONTHS */]: today.add(6, "month").endOf("day").toDate()
1086
1133
  };
1087
1134
  const licenceObject = {
1088
1135
  expiryDate: expiryDateMapping[expiryDate],
@@ -1229,7 +1276,9 @@ async function findUserVendor(userId, logLabel) {
1229
1276
  "owner.userId": userId
1230
1277
  }).lean().exec();
1231
1278
  if (!vendor) {
1232
- console.warn(`[${logLabel}] Vendor not found for id=${user.vendor}`);
1279
+ console.warn(
1280
+ `[${logLabel}] Vendor not found for id=${user.vendor}, userId=${userId}`
1281
+ );
1233
1282
  return null;
1234
1283
  }
1235
1284
  return vendor;
@@ -1282,6 +1331,7 @@ async function downgradeVendorProFeatures(userId, licenceType) {
1282
1331
  await applyVendorDowngrade(vendor, userId);
1283
1332
  } catch (error) {
1284
1333
  console.error("[downgradeVendorProFeatures] Failed:", error);
1334
+ throw error;
1285
1335
  }
1286
1336
  }
1287
1337
  async function applyVendorRestore(vendor, ownerUserId) {
@@ -1328,6 +1378,7 @@ async function restoreVendorProFeatures(userId, licenceType) {
1328
1378
  await applyVendorRestore(vendor, userId);
1329
1379
  } catch (error) {
1330
1380
  console.error("[restoreVendorProFeatures] Failed:", error);
1381
+ throw error;
1331
1382
  }
1332
1383
  }
1333
1384
  var vendorLicences = [
@@ -1337,14 +1388,25 @@ var vendorLicences = [
1337
1388
  ];
1338
1389
  function isProtectedByCurrentStripeSubscription(user, licenceType, now) {
1339
1390
  const stripe = user.stripe;
1340
- if (!stripe?.subscriptionId || stripe.currentPlan !== licenceType || stripe.status !== EnumSubscriptionStatus2.ACTIVE && stripe.status !== EnumSubscriptionStatus2.TRIALING) {
1391
+ if (!stripe || stripe.currentPlan !== licenceType) {
1341
1392
  return false;
1342
1393
  }
1343
- if (stripe.cancelAtPeriodEnd !== true || !stripe.endDate) {
1394
+ const gracePeriodEndsAt = stripe.paymentGracePeriodEndsAt ? dayjs4(stripe.paymentGracePeriodEndsAt) : null;
1395
+ 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);
1396
+ if (hasActivePaymentGracePeriod) {
1344
1397
  return true;
1345
1398
  }
1399
+ if (!stripe.subscriptionId) {
1400
+ return false;
1401
+ }
1402
+ if (stripe.status !== EnumSubscriptionStatus2.ACTIVE) {
1403
+ return false;
1404
+ }
1405
+ if (!stripe.endDate) {
1406
+ return false;
1407
+ }
1346
1408
  const paidThrough = dayjs4(stripe.endDate);
1347
- return !paidThrough.isValid() || paidThrough.isAfter(now);
1409
+ return paidThrough.isValid() && paidThrough.isAfter(now);
1348
1410
  }
1349
1411
  async function handleVendorLicenceCompliance(user, now) {
1350
1412
  if (!user.licences || !user.vendor) {
@@ -1419,9 +1481,23 @@ async function vendorOwnerHasProLicence(vendorId) {
1419
1481
  if (!vendor) {
1420
1482
  return false;
1421
1483
  }
1422
- const owner = await UserModel.findById(vendor.owner.userId, { licences: 1 }).lean().exec();
1484
+ const owner = await UserModel.findById(vendor.owner.userId, {
1485
+ licences: 1,
1486
+ stripe: 1
1487
+ }).lean().exec();
1488
+ if (!owner) {
1489
+ return false;
1490
+ }
1491
+ const now = dayjs4();
1492
+ const effectiveVendorLicences = owner.licences?.filter(
1493
+ (licence) => licence?.licenceType && (dayjs4(licence.expiryDate).isAfter(now) || isProtectedByCurrentStripeSubscription(
1494
+ owner,
1495
+ licence.licenceType,
1496
+ now
1497
+ ))
1498
+ );
1423
1499
  const highestVendorLicence = getHighestLicenceForCategory(
1424
- owner?.licences,
1500
+ effectiveVendorLicences,
1425
1501
  "vendor" /* VENDOR */
1426
1502
  );
1427
1503
  return highestVendorLicence !== null && licencePriority[highestVendorLicence] >= licencePriority[EnumUserLicence6.PRO_VENDOR];