@timardex/cluemart-server-shared 2.2.23 → 2.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.
package/dist/index.cjs CHANGED
@@ -82,6 +82,11 @@ __export(index_exports, {
82
82
  baseResourceFields: () => baseResourceFields,
83
83
  buildInitialBillingCatalogEntries: () => buildInitialBillingCatalogEntries,
84
84
  buildLicenceExpiryPipeline: () => buildLicenceExpiryPipeline,
85
+ buildUserHasEnoughPointsFilter: () => buildUserHasEnoughPointsFilter,
86
+ buildUserPointAwardEntry: () => buildUserPointAwardEntry,
87
+ buildUserPointCreditFilter: () => buildUserPointCreditFilter,
88
+ buildUserPointDebitPipeline: () => buildUserPointDebitPipeline,
89
+ buildUserPointEntryRemovalPipeline: () => buildUserPointEntryRemovalPipeline,
85
90
  checkOwnerHasLicence: () => checkOwnerHasLicence,
86
91
  connectToDatabase: () => connectToDatabase,
87
92
  convertObjectIdsToStrings: () => convertObjectIdsToStrings,
@@ -1611,6 +1616,19 @@ var redeemedRewardSchema = new MongooseSchema12(
1611
1616
  },
1612
1617
  { _id: false }
1613
1618
  );
1619
+ var userOverallPointsSchema = new MongooseSchema12(
1620
+ {
1621
+ createdAt: { required: true, type: Date },
1622
+ points: { default: 0, required: true, type: Number },
1623
+ pointType: {
1624
+ enum: Object.values(import_cluemart_shared13.EnumPointType),
1625
+ required: true,
1626
+ type: String
1627
+ },
1628
+ sourceId: { required: false, type: String }
1629
+ },
1630
+ { _id: false }
1631
+ );
1614
1632
  var schema12 = new MongooseSchema12(
1615
1633
  {
1616
1634
  active: { default: false, required: true, type: Boolean },
@@ -1662,7 +1680,11 @@ var schema12 = new MongooseSchema12(
1662
1680
  type: locationsSchema
1663
1681
  },
1664
1682
  nickName: { required: false, type: String },
1665
- overallPoints: { default: 0, required: false, type: Number },
1683
+ overallPoints: {
1684
+ default: [],
1685
+ required: false,
1686
+ type: [userOverallPointsSchema]
1687
+ },
1666
1688
  partner: {
1667
1689
  ref: "Partner",
1668
1690
  required: false,
@@ -2304,7 +2326,10 @@ var gameTypeSchema = new MongooseSchema24(
2304
2326
  required: true,
2305
2327
  type: String
2306
2328
  },
2307
- gameTypeId: { required: true, type: String }
2329
+ gameTypeId: { required: true, type: String },
2330
+ // See `GameType.pointsCredited`: absent means "completed before the marker
2331
+ // existed", which must not be re-credited.
2332
+ pointsCredited: { required: false, type: Boolean }
2308
2333
  },
2309
2334
  { timestamps: true }
2310
2335
  );
@@ -3252,15 +3277,189 @@ function convertObjectIdsToStrings(obj) {
3252
3277
  return obj;
3253
3278
  }
3254
3279
 
3280
+ // src/service/userPoints.ts
3281
+ var import_dayjs2 = __toESM(require("dayjs"));
3282
+ function assertValidPointAmount(amount, label) {
3283
+ if (!Number.isFinite(amount) || amount < 0) {
3284
+ throw new RangeError(
3285
+ `Invalid user point ${label}: ${String(amount)}. Expected a finite, non-negative number.`
3286
+ );
3287
+ }
3288
+ }
3289
+ function buildUserPointAwardEntry(pointType, points, sourceId) {
3290
+ assertValidPointAmount(points, "award");
3291
+ return {
3292
+ createdAt: (0, import_dayjs2.default)().toDate(),
3293
+ points,
3294
+ pointType,
3295
+ ...sourceId === void 0 ? {} : { sourceId }
3296
+ };
3297
+ }
3298
+ function buildUserPointCreditFilter(userId, sourceId) {
3299
+ return {
3300
+ _id: userId,
3301
+ overallPoints: { $not: { $elemMatch: { sourceId } } }
3302
+ };
3303
+ }
3304
+ function buildUserHasEnoughPointsFilter(amount) {
3305
+ assertValidPointAmount(amount, "threshold");
3306
+ return {
3307
+ $expr: {
3308
+ $gte: [{ $sum: { $ifNull: ["$overallPoints.points", []] } }, amount]
3309
+ }
3310
+ };
3311
+ }
3312
+ function buildLedgerWriteExpr(computedLedger) {
3313
+ return {
3314
+ $cond: [
3315
+ { $isArray: "$overallPoints" },
3316
+ computedLedger,
3317
+ { $ifNull: ["$overallPoints", []] }
3318
+ ]
3319
+ };
3320
+ }
3321
+ function buildUserPointDebitPipeline(amount) {
3322
+ assertValidPointAmount(amount, "debit");
3323
+ const debitedLedger = {
3324
+ $let: {
3325
+ vars: {
3326
+ sorted: {
3327
+ $sortArray: {
3328
+ input: { $ifNull: ["$overallPoints", []] },
3329
+ sortBy: { createdAt: 1 }
3330
+ }
3331
+ }
3332
+ },
3333
+ in: {
3334
+ $let: {
3335
+ vars: {
3336
+ debited: {
3337
+ $reduce: {
3338
+ initialValue: { budget: amount, entries: [] },
3339
+ in: {
3340
+ $let: {
3341
+ vars: { available: { $ifNull: ["$$this.points", 0] } },
3342
+ in: {
3343
+ budget: {
3344
+ $subtract: [
3345
+ "$$value.budget",
3346
+ { $min: ["$$available", "$$value.budget"] }
3347
+ ]
3348
+ },
3349
+ entries: {
3350
+ $concatArrays: [
3351
+ "$$value.entries",
3352
+ [
3353
+ {
3354
+ $mergeObjects: [
3355
+ "$$this",
3356
+ {
3357
+ points: {
3358
+ $subtract: [
3359
+ "$$available",
3360
+ {
3361
+ $min: ["$$available", "$$value.budget"]
3362
+ }
3363
+ ]
3364
+ }
3365
+ }
3366
+ ]
3367
+ }
3368
+ ]
3369
+ ]
3370
+ }
3371
+ }
3372
+ }
3373
+ },
3374
+ input: "$$sorted"
3375
+ }
3376
+ }
3377
+ },
3378
+ in: {
3379
+ $filter: {
3380
+ as: "entry",
3381
+ cond: { $gt: ["$$entry.points", 0] },
3382
+ input: "$$debited.entries"
3383
+ }
3384
+ }
3385
+ }
3386
+ }
3387
+ }
3388
+ };
3389
+ return [
3390
+ {
3391
+ $set: {
3392
+ overallPoints: buildLedgerWriteExpr(debitedLedger)
3393
+ }
3394
+ }
3395
+ ];
3396
+ }
3397
+ function buildUserPointEntryRemovalPipeline(pointType, sourceId) {
3398
+ const indexExpression = sourceId === void 0 ? { $indexOfArray: ["$$entries.pointType", pointType] } : {
3399
+ $indexOfArray: [
3400
+ {
3401
+ $map: {
3402
+ as: "entry",
3403
+ in: {
3404
+ $and: [
3405
+ { $eq: ["$$entry.pointType", pointType] },
3406
+ { $eq: ["$$entry.sourceId", sourceId] }
3407
+ ]
3408
+ },
3409
+ input: "$$entries"
3410
+ }
3411
+ },
3412
+ true
3413
+ ]
3414
+ };
3415
+ const entriesAfterRemoval = {
3416
+ $let: {
3417
+ vars: { entries: { $ifNull: ["$overallPoints", []] } },
3418
+ in: {
3419
+ $let: {
3420
+ vars: {
3421
+ index: indexExpression
3422
+ },
3423
+ in: {
3424
+ $cond: [
3425
+ { $lt: ["$$index", 0] },
3426
+ "$$entries",
3427
+ {
3428
+ $concatArrays: [
3429
+ { $slice: ["$$entries", "$$index"] },
3430
+ {
3431
+ $slice: [
3432
+ "$$entries",
3433
+ { $add: ["$$index", 1] },
3434
+ { $size: "$$entries" }
3435
+ ]
3436
+ }
3437
+ ]
3438
+ }
3439
+ ]
3440
+ }
3441
+ }
3442
+ }
3443
+ }
3444
+ };
3445
+ return [
3446
+ {
3447
+ $set: {
3448
+ overallPoints: buildLedgerWriteExpr(entriesAfterRemoval)
3449
+ }
3450
+ }
3451
+ ];
3452
+ }
3453
+
3255
3454
  // src/service/event/updateAllEventDateTimeStatuses.ts
3256
3455
  var import_cluemart_shared27 = require("@timardex/cluemart-shared");
3257
- var import_dayjs3 = __toESM(require("dayjs"));
3456
+ var import_dayjs4 = __toESM(require("dayjs"));
3258
3457
 
3259
3458
  // src/service/event/archiveEndedEventDates.ts
3260
3459
  var import_cluemart_shared26 = require("@timardex/cluemart-shared");
3261
- var import_dayjs2 = __toESM(require("dayjs"));
3460
+ var import_dayjs3 = __toESM(require("dayjs"));
3262
3461
  var import_customParseFormat = __toESM(require("dayjs/plugin/customParseFormat"));
3263
- import_dayjs2.default.extend(import_customParseFormat.default);
3462
+ import_dayjs3.default.extend(import_customParseFormat.default);
3264
3463
  var ARCHIVED_STATUSES = /* @__PURE__ */ new Set([
3265
3464
  import_cluemart_shared26.EnumEventDateStatus.ENDED
3266
3465
  ]);
@@ -3291,7 +3490,7 @@ function isPastCanceledEventDate(slot, now) {
3291
3490
  if (slot.dateStatus !== import_cluemart_shared26.EnumEventDateStatus.CANCELED) {
3292
3491
  return false;
3293
3492
  }
3294
- const endDateTime = (0, import_dayjs2.default)(
3493
+ const endDateTime = (0, import_dayjs3.default)(
3295
3494
  `${slot.endDate} ${slot.endTime}`,
3296
3495
  `${import_cluemart_shared26.dateFormat} ${import_cluemart_shared26.timeFormat}`,
3297
3496
  true
@@ -3486,7 +3685,7 @@ async function cleanEventInfoDates(now) {
3486
3685
  return removedCount;
3487
3686
  }
3488
3687
  async function updateAllEventDateTimeStatuses() {
3489
- const now = (0, import_dayjs3.default)();
3688
+ const now = (0, import_dayjs4.default)();
3490
3689
  const [eventCount, marketCount] = await Promise.all([
3491
3690
  updateModelDateTimeStatuses(EventModel, now),
3492
3691
  updateModelDateTimeStatuses(
@@ -3560,11 +3759,11 @@ function updateRelationDatesToUnavailable(relationDates, eventDateTime) {
3560
3759
  }
3561
3760
 
3562
3761
  // src/service/license/compliance/ensureUserLicenseCompliance.ts
3563
- var import_dayjs7 = __toESM(require("dayjs"));
3762
+ var import_dayjs8 = __toESM(require("dayjs"));
3564
3763
 
3565
3764
  // src/service/license/compliance/utils.ts
3566
3765
  var import_cluemart_shared33 = require("@timardex/cluemart-shared");
3567
- var import_dayjs6 = __toESM(require("dayjs"));
3766
+ var import_dayjs7 = __toESM(require("dayjs"));
3568
3767
 
3569
3768
  // src/service/license/compliance/event.ts
3570
3769
  var import_cluemart_shared29 = require("@timardex/cluemart-shared");
@@ -3796,11 +3995,11 @@ async function handlePartnerLicenceCompliance(user, now) {
3796
3995
 
3797
3996
  // src/service/license/compliance/vendor.ts
3798
3997
  var import_cluemart_shared32 = require("@timardex/cluemart-shared");
3799
- var import_dayjs5 = __toESM(require("dayjs"));
3998
+ var import_dayjs6 = __toESM(require("dayjs"));
3800
3999
 
3801
4000
  // src/service/license/models.ts
3802
4001
  var import_cluemart_shared31 = require("@timardex/cluemart-shared");
3803
- var import_dayjs4 = __toESM(require("dayjs"));
4002
+ var import_dayjs5 = __toESM(require("dayjs"));
3804
4003
  var import_graphql = require("graphql");
3805
4004
  var LicenceCategory = /* @__PURE__ */ ((LicenceCategory2) => {
3806
4005
  LicenceCategory2["EVENT"] = "event";
@@ -3881,7 +4080,7 @@ function getHighestLicenceForCategory(licences, category) {
3881
4080
  return highestLicence;
3882
4081
  }
3883
4082
  function createLicenceObject(expiryDate, licenceType) {
3884
- const today = (0, import_dayjs4.default)();
4083
+ const today = (0, import_dayjs5.default)();
3885
4084
  const expiryDateMapping = {
3886
4085
  [import_cluemart_shared31.LicenceExpiryDate.ONE_YEAR]: today.add(1, "year").endOf("day").toDate(),
3887
4086
  [import_cluemart_shared31.LicenceExpiryDate.ONE_MONTH]: today.add(1, "month").endOf("day").toDate(),
@@ -4144,7 +4343,7 @@ function isProtectedByCurrentStripeSubscription(user, licenceType, now) {
4144
4343
  if (!stripe || stripe.currentPlan !== licenceType) {
4145
4344
  return false;
4146
4345
  }
4147
- const gracePeriodEndsAt = stripe.paymentGracePeriodEndsAt ? (0, import_dayjs5.default)(stripe.paymentGracePeriodEndsAt) : null;
4346
+ const gracePeriodEndsAt = stripe.paymentGracePeriodEndsAt ? (0, import_dayjs6.default)(stripe.paymentGracePeriodEndsAt) : null;
4148
4347
  const hasActivePaymentGracePeriod = (stripe.status === import_cluemart_shared32.EnumSubscriptionStatus.PAST_DUE || stripe.status === import_cluemart_shared32.EnumSubscriptionStatus.INACTIVE) && Boolean(stripe.paymentGraceSubscriptionId) && (!stripe.subscriptionId || stripe.subscriptionId === stripe.paymentGraceSubscriptionId) && gracePeriodEndsAt !== null && gracePeriodEndsAt.isValid() && gracePeriodEndsAt.isAfter(now);
4149
4348
  if (hasActivePaymentGracePeriod) {
4150
4349
  return true;
@@ -4158,7 +4357,7 @@ function isProtectedByCurrentStripeSubscription(user, licenceType, now) {
4158
4357
  if (!stripe.endDate) {
4159
4358
  return false;
4160
4359
  }
4161
- const paidThrough = (0, import_dayjs5.default)(stripe.endDate);
4360
+ const paidThrough = (0, import_dayjs6.default)(stripe.endDate);
4162
4361
  return paidThrough.isValid() && paidThrough.isAfter(now);
4163
4362
  }
4164
4363
  async function handleVendorLicenceCompliance(user, now) {
@@ -4175,7 +4374,7 @@ async function handleVendorLicenceCompliance(user, now) {
4175
4374
  (licence) => licence.licenceType !== import_cluemart_shared32.EnumUserLicence.STANDARD_VENDOR
4176
4375
  );
4177
4376
  const expiredProLicences = proLicences.filter(
4178
- (licence) => !(0, import_dayjs5.default)(licence.expiryDate).isAfter(now)
4377
+ (licence) => !(0, import_dayjs6.default)(licence.expiryDate).isAfter(now)
4179
4378
  );
4180
4379
  const stripeProtectedLicenceTypes = new Set(
4181
4380
  expiredProLicences.filter(
@@ -4187,7 +4386,7 @@ async function handleVendorLicenceCompliance(user, now) {
4187
4386
  );
4188
4387
  const hasValidProLicence = stripeProtectedLicenceTypes.size > 0 || hasValidLicence(proLicences, import_cluemart_shared32.vendorLicences, now);
4189
4388
  const hasExpiredVendorLicence = vendorLicencesOfUser.some(
4190
- (licence) => !(0, import_dayjs5.default)(licence.expiryDate).isAfter(now) && !stripeProtectedLicenceTypes.has(licence.licenceType)
4389
+ (licence) => !(0, import_dayjs6.default)(licence.expiryDate).isAfter(now) && !stripeProtectedLicenceTypes.has(licence.licenceType)
4191
4390
  );
4192
4391
  if (!hasExpiredVendorLicence) {
4193
4392
  return;
@@ -4241,9 +4440,9 @@ async function vendorOwnerHasProLicence(vendorId) {
4241
4440
  if (!owner) {
4242
4441
  return false;
4243
4442
  }
4244
- const now = (0, import_dayjs5.default)();
4443
+ const now = (0, import_dayjs6.default)();
4245
4444
  const effectiveVendorLicences = owner.licences?.filter(
4246
- (licence) => licence?.licenceType && ((0, import_dayjs5.default)(licence.expiryDate).isAfter(now) || isProtectedByCurrentStripeSubscription(
4445
+ (licence) => licence?.licenceType && ((0, import_dayjs6.default)(licence.expiryDate).isAfter(now) || isProtectedByCurrentStripeSubscription(
4247
4446
  owner,
4248
4447
  licence.licenceType,
4249
4448
  now
@@ -4280,7 +4479,7 @@ async function syncUserLicencesAfterExpiry(userId, licenceTypes, now, mode = "do
4280
4479
  }
4281
4480
  function hasValidLicence(licences, licenceTypes, now) {
4282
4481
  return licences.some(
4283
- (licence) => licenceTypes.includes(licence.licenceType) && (0, import_dayjs6.default)(licence.expiryDate).isAfter(now)
4482
+ (licence) => licenceTypes.includes(licence.licenceType) && (0, import_dayjs7.default)(licence.expiryDate).isAfter(now)
4284
4483
  );
4285
4484
  }
4286
4485
  async function sendDeactivationNotification(payload, userId, resourceName, resourceType) {
@@ -4307,7 +4506,7 @@ async function processUserCompliance(user, now) {
4307
4506
  }
4308
4507
 
4309
4508
  // src/service/license/compliance/ensureUserLicenseCompliance.ts
4310
- async function ensureUserLicenseComplianceForUser(userId, now = (0, import_dayjs7.default)()) {
4509
+ async function ensureUserLicenseComplianceForUser(userId, now = (0, import_dayjs8.default)()) {
4311
4510
  const user = await UserModel.findById(userId);
4312
4511
  if (!user) {
4313
4512
  return;
@@ -4315,7 +4514,7 @@ async function ensureUserLicenseComplianceForUser(userId, now = (0, import_dayjs
4315
4514
  await processUserCompliance(user, now);
4316
4515
  }
4317
4516
  async function ensureUserLicenseCompliance() {
4318
- const now = (0, import_dayjs7.default)();
4517
+ const now = (0, import_dayjs8.default)();
4319
4518
  console.log(`\u{1F50D} Checking license compliance at ${now.format()}`);
4320
4519
  const nowDate = now.toDate();
4321
4520
  const users = await UserModel.find({
@@ -4390,7 +4589,7 @@ async function getPartnerResourceInfo(userId, partnerId) {
4390
4589
  }
4391
4590
 
4392
4591
  // src/service/license/reminder/remindUsersAboutLicenseExpiration.ts
4393
- var import_dayjs9 = __toESM(require("dayjs"));
4592
+ var import_dayjs10 = __toESM(require("dayjs"));
4394
4593
 
4395
4594
  // src/service/license/reminder/reminderWindow.ts
4396
4595
  var REMINDER_WINDOW_MIN_HOURS = 6.5 * 24;
@@ -4399,7 +4598,7 @@ var REMINDER_WINDOW_MAX_HOURS = 7.5 * 24;
4399
4598
  // src/service/license/reminder/utils.ts
4400
4599
  var import_cluemart_shared34 = require("@timardex/cluemart-shared");
4401
4600
  var import_utils8 = require("@timardex/cluemart-shared/utils");
4402
- var import_dayjs8 = __toESM(require("dayjs"));
4601
+ var import_dayjs9 = __toESM(require("dayjs"));
4403
4602
 
4404
4603
  // src/service/license/reminder/vendor.ts
4405
4604
  async function getVendorResourceInfo(userId, vendorId) {
@@ -4458,7 +4657,7 @@ async function checkAndCreateNotification(payload) {
4458
4657
  }
4459
4658
  }
4460
4659
  function isLicenseExpiringIn7Days(expiryDate, now) {
4461
- const expiry = (0, import_dayjs8.default)(expiryDate);
4660
+ const expiry = (0, import_dayjs9.default)(expiryDate);
4462
4661
  const hoursUntilExpiry = expiry.diff(now, "hour", true);
4463
4662
  return hoursUntilExpiry >= REMINDER_WINDOW_MIN_HOURS && hoursUntilExpiry <= REMINDER_WINDOW_MAX_HOURS;
4464
4663
  }
@@ -4536,7 +4735,7 @@ function getLicenceExpiryMode(licenceType) {
4536
4735
  }
4537
4736
  async function sendLicenseReminder(user, licence) {
4538
4737
  const licenceName = getLicenseName(licence.licenceType);
4539
- const expiryDate = (0, import_dayjs8.default)(licence.expiryDate).format(import_cluemart_shared34.dateFormat);
4738
+ const expiryDate = (0, import_dayjs9.default)(licence.expiryDate).format(import_cluemart_shared34.dateFormat);
4540
4739
  const userId = String(user._id);
4541
4740
  const resourceInfo = await getLicenseResourceInfo(user, licence);
4542
4741
  if (!resourceInfo) {
@@ -4568,7 +4767,7 @@ async function sendLicenseReminder(user, licence) {
4568
4767
  console.log(`\u2705 Sent 7-day reminder to user ${userId} for ${licenceName}`);
4569
4768
  }
4570
4769
  async function processLicenseReminder(licence, now) {
4571
- if ((0, import_dayjs8.default)(licence.expiryDate).isBefore(now)) {
4770
+ if ((0, import_dayjs9.default)(licence.expiryDate).isBefore(now)) {
4572
4771
  return false;
4573
4772
  }
4574
4773
  if (!isLicenseExpiringIn7Days(licence.expiryDate, now)) {
@@ -4622,7 +4821,7 @@ async function processUserLicenseReminders(user, now) {
4622
4821
 
4623
4822
  // src/service/license/reminder/remindUsersAboutLicenseExpiration.ts
4624
4823
  async function remindUsersAboutLicenseExpiration() {
4625
- const now = (0, import_dayjs9.default)();
4824
+ const now = (0, import_dayjs10.default)();
4626
4825
  console.log(`\u{1F50D} Checking for licenses expiring in 7 days at ${now.format()}`);
4627
4826
  const minExpiryDate = now.add(REMINDER_WINDOW_MIN_HOURS, "hour").toDate();
4628
4827
  const maxExpiryDate = now.add(REMINDER_WINDOW_MAX_HOURS, "hour").toDate();
@@ -4713,6 +4912,11 @@ async function remindUsersAboutLicenseExpiration() {
4713
4912
  baseResourceFields,
4714
4913
  buildInitialBillingCatalogEntries,
4715
4914
  buildLicenceExpiryPipeline,
4915
+ buildUserHasEnoughPointsFilter,
4916
+ buildUserPointAwardEntry,
4917
+ buildUserPointCreditFilter,
4918
+ buildUserPointDebitPipeline,
4919
+ buildUserPointEntryRemovalPipeline,
4716
4920
  checkOwnerHasLicence,
4717
4921
  connectToDatabase,
4718
4922
  convertObjectIdsToStrings,