@timardex/cluemart-server-shared 2.1.0 → 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
  /**
@@ -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
  /**
@@ -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
 
@@ -1229,7 +1272,9 @@ async function findUserVendor(userId, logLabel) {
1229
1272
  "owner.userId": userId
1230
1273
  }).lean().exec();
1231
1274
  if (!vendor) {
1232
- console.warn(`[${logLabel}] Vendor not found for id=${user.vendor}`);
1275
+ console.warn(
1276
+ `[${logLabel}] Vendor not found for id=${user.vendor}, userId=${userId}`
1277
+ );
1233
1278
  return null;
1234
1279
  }
1235
1280
  return vendor;
@@ -1282,6 +1327,7 @@ async function downgradeVendorProFeatures(userId, licenceType) {
1282
1327
  await applyVendorDowngrade(vendor, userId);
1283
1328
  } catch (error) {
1284
1329
  console.error("[downgradeVendorProFeatures] Failed:", error);
1330
+ throw error;
1285
1331
  }
1286
1332
  }
1287
1333
  async function applyVendorRestore(vendor, ownerUserId) {
@@ -1328,6 +1374,7 @@ async function restoreVendorProFeatures(userId, licenceType) {
1328
1374
  await applyVendorRestore(vendor, userId);
1329
1375
  } catch (error) {
1330
1376
  console.error("[restoreVendorProFeatures] Failed:", error);
1377
+ throw error;
1331
1378
  }
1332
1379
  }
1333
1380
  var vendorLicences = [
@@ -1337,14 +1384,25 @@ var vendorLicences = [
1337
1384
  ];
1338
1385
  function isProtectedByCurrentStripeSubscription(user, licenceType, now) {
1339
1386
  const stripe = user.stripe;
1340
- if (!stripe?.subscriptionId || stripe.currentPlan !== licenceType || stripe.status !== EnumSubscriptionStatus2.ACTIVE && stripe.status !== EnumSubscriptionStatus2.TRIALING) {
1387
+ if (!stripe || stripe.currentPlan !== licenceType) {
1341
1388
  return false;
1342
1389
  }
1343
- 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) {
1344
1393
  return true;
1345
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
+ }
1346
1404
  const paidThrough = dayjs4(stripe.endDate);
1347
- return !paidThrough.isValid() || paidThrough.isAfter(now);
1405
+ return paidThrough.isValid() && paidThrough.isAfter(now);
1348
1406
  }
1349
1407
  async function handleVendorLicenceCompliance(user, now) {
1350
1408
  if (!user.licences || !user.vendor) {
@@ -1419,9 +1477,23 @@ async function vendorOwnerHasProLicence(vendorId) {
1419
1477
  if (!vendor) {
1420
1478
  return false;
1421
1479
  }
1422
- 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
+ );
1423
1495
  const highestVendorLicence = getHighestLicenceForCategory(
1424
- owner?.licences,
1496
+ effectiveVendorLicences,
1425
1497
  "vendor" /* VENDOR */
1426
1498
  );
1427
1499
  return highestVendorLicence !== null && licencePriority[highestVendorLicence] >= licencePriority[EnumUserLicence6.PRO_VENDOR];