@timardex/cluemart-server-shared 4.1.0 → 4.2.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.mjs CHANGED
@@ -698,6 +698,7 @@ var ChatReportModel = mongoose8.models.ChatReport || mongoose8.model("ChatReport
698
698
 
699
699
  // src/mongoose/global.ts
700
700
  import {
701
+ EnumAssociateStatus,
701
702
  EnumEventDateStatus,
702
703
  EnumPostType,
703
704
  EnumUserLicence as EnumUserLicence2
@@ -716,6 +717,25 @@ var OwnerTypeSchema = new MongooseSchema5(
716
717
  { _id: false }
717
718
  // Prevents Mongoose from creating an additional _id field for subdocuments
718
719
  );
720
+ var AssociateTypeSchema = new MongooseSchema5(
721
+ {
722
+ addedAt: { default: Date.now, required: false, type: Date },
723
+ email: { lowercase: true, required: true, trim: true, type: String },
724
+ respondedAt: { default: null, required: false, type: Date },
725
+ status: {
726
+ default: EnumAssociateStatus.PENDING,
727
+ enum: Object.values(EnumAssociateStatus),
728
+ required: true,
729
+ type: String
730
+ },
731
+ userId: {
732
+ ref: "User",
733
+ required: true,
734
+ type: mongoose9.Schema.Types.ObjectId
735
+ }
736
+ },
737
+ { _id: false }
738
+ );
719
739
  var SocialMediaTypeSchema = new MongooseSchema5(
720
740
  {
721
741
  link: { required: true, type: String },
@@ -881,6 +901,7 @@ var baseResourceFields = {
881
901
  type: [mongoose9.Schema.Types.ObjectId]
882
902
  },
883
903
  approvedAt: { default: null, required: false, type: Date },
904
+ associates: { default: [], required: false, type: [AssociateTypeSchema] },
884
905
  contactDetails: { required: false, type: ContactDetailsSchema },
885
906
  cover: {
886
907
  required: true,
@@ -1796,6 +1817,29 @@ var userOverallPointsSchema = new MongooseSchema16(
1796
1817
  },
1797
1818
  { _id: false }
1798
1819
  );
1820
+ var userAssociatedResourcesSchema = new MongooseSchema16(
1821
+ {
1822
+ events: {
1823
+ default: [],
1824
+ ref: "Event",
1825
+ required: false,
1826
+ type: [mongoose20.Schema.Types.ObjectId]
1827
+ },
1828
+ partners: {
1829
+ default: [],
1830
+ ref: "Partner",
1831
+ required: false,
1832
+ type: [mongoose20.Schema.Types.ObjectId]
1833
+ },
1834
+ vendors: {
1835
+ default: [],
1836
+ ref: "Vendor",
1837
+ required: false,
1838
+ type: [mongoose20.Schema.Types.ObjectId]
1839
+ }
1840
+ },
1841
+ { _id: false }
1842
+ );
1799
1843
  var schema15 = new MongooseSchema16(
1800
1844
  {
1801
1845
  active: { default: false, required: true, type: Boolean },
@@ -1804,6 +1848,11 @@ var schema15 = new MongooseSchema16(
1804
1848
  required: false,
1805
1849
  type: mongoose20.Schema.Types.ObjectId
1806
1850
  },
1851
+ associatedResources: {
1852
+ default: () => ({ events: [], partners: [], vendors: [] }),
1853
+ required: false,
1854
+ type: userAssociatedResourcesSchema
1855
+ },
1807
1856
  avatar: {
1808
1857
  required: false,
1809
1858
  type: ResourceImageTypeSchema
@@ -1814,7 +1863,10 @@ var schema15 = new MongooseSchema16(
1814
1863
  type: mongoose20.Schema.Types.ObjectId
1815
1864
  },
1816
1865
  deletedAt: { default: null, required: false, type: Date },
1817
- email: { required: true, type: String },
1866
+ // `normalizeEmail` (`cluemart-shared`) is trim + lower-case; keeping the same
1867
+ // rule here means every write path — resolvers, seeds, scripts — stores the
1868
+ // comparable form, not only the clients that validate through `emailRequiredSchema`.
1869
+ email: { lowercase: true, required: true, trim: true, type: String },
1818
1870
  emailSentFor: {
1819
1871
  enum: Object.values(EnumNotificationResourceType2),
1820
1872
  required: false,
@@ -1929,6 +1981,9 @@ schema15.index({ "licences.expiryDate": 1 });
1929
1981
  schema15.index({ "licences.licenceType": 1 });
1930
1982
  schema15.index({ promoCodes: 1, active: 1, deletedAt: 1 });
1931
1983
  schema15.index({ email: "text", firstName: "text", lastName: "text" });
1984
+ schema15.index({ "associatedResources.events": 1 });
1985
+ schema15.index({ "associatedResources.partners": 1 });
1986
+ schema15.index({ "associatedResources.vendors": 1 });
1932
1987
  var UserModel = mongoose20.models.User || mongoose20.model("User", schema15);
1933
1988
 
1934
1989
  // src/mongoose/VerificationToken.ts
@@ -2065,6 +2120,7 @@ schema17.index({
2065
2120
  name: "text"
2066
2121
  });
2067
2122
  schema17.index({ deletedAt: 1, "owner.userId": 1 });
2123
+ schema17.index({ "associates.userId": 1, deletedAt: 1 });
2068
2124
  schema17.plugin(searchNamePlugin);
2069
2125
  var VendorModel = mongoose22.models.Vendor || mongoose22.model("Vendor", schema17);
2070
2126
 
@@ -2218,6 +2274,7 @@ schema20.index({ "dateTime.dateStatus": 1 });
2218
2274
  schema20.index({ slug: 1 });
2219
2275
  schema20.index({ description: "text", name: "text", tags: "text" });
2220
2276
  schema20.index({ deletedAt: 1, "owner.userId": 1 });
2277
+ schema20.index({ "associates.userId": 1, deletedAt: 1 });
2221
2278
  schema20.plugin(searchNamePlugin);
2222
2279
  var EventModel = mongoose25.models.Event || mongoose25.model("Event", schema20);
2223
2280
 
@@ -2264,6 +2321,7 @@ schema22.index({ "location.geo": "2dsphere" });
2264
2321
  schema22.index({ slug: 1 });
2265
2322
  schema22.index({ name: "text", description: "text" });
2266
2323
  schema22.index({ "owner.userId": 1, deletedAt: 1 });
2324
+ schema22.index({ "associates.userId": 1, deletedAt: 1 });
2267
2325
  schema22.plugin(searchNamePlugin);
2268
2326
  var PartnerModel = mongoose27.models.Partner || mongoose27.model("Partner", schema22);
2269
2327
 
@@ -3354,14 +3412,314 @@ function normalizeAffiliatePromoCodes(promoCodes) {
3354
3412
  return [...new Set(normalized)];
3355
3413
  }
3356
3414
 
3415
+ // src/service/associates/index.ts
3416
+ import {
3417
+ EnumAssociateStatus as EnumAssociateStatus2,
3418
+ EnumResourceType as EnumResourceType10,
3419
+ EnumUserRole as EnumUserRole2
3420
+ } from "@timardex/cluemart-shared";
3421
+ import mongoose39 from "mongoose";
3422
+ function isAssociableResourceType(resourceType) {
3423
+ return resourceType === EnumResourceType10.EVENT || resourceType === EnumResourceType10.PARTNER || resourceType === EnumResourceType10.VENDOR;
3424
+ }
3425
+ function getAssociateAccessMeta(resourceType) {
3426
+ if (resourceType === EnumResourceType10.EVENT) {
3427
+ return {
3428
+ associatedField: "events",
3429
+ associatedPath: "associatedResources.events",
3430
+ associateRole: EnumUserRole2.ASSOCIATED_EVENT
3431
+ };
3432
+ }
3433
+ if (resourceType === EnumResourceType10.PARTNER) {
3434
+ return {
3435
+ associatedField: "partners",
3436
+ associatedPath: "associatedResources.partners",
3437
+ associateRole: EnumUserRole2.ASSOCIATED_PARTNER
3438
+ };
3439
+ }
3440
+ return {
3441
+ associatedField: "vendors",
3442
+ associatedPath: "associatedResources.vendors",
3443
+ associateRole: EnumUserRole2.ASSOCIATED_VENDOR
3444
+ };
3445
+ }
3446
+ var ASSOCIABLE_MODELS = {
3447
+ [EnumResourceType10.EVENT]: EventModel,
3448
+ [EnumResourceType10.PARTNER]: PartnerModel,
3449
+ [EnumResourceType10.VENDOR]: VendorModel
3450
+ };
3451
+ function acceptedAssociateUserIds(associates) {
3452
+ return (associates ?? []).filter((associate) => associate.status === EnumAssociateStatus2.ACCEPTED).map((associate) => associate.userId);
3453
+ }
3454
+ async function detachUsersFromResource({
3455
+ resourceId,
3456
+ resourceType,
3457
+ userIds
3458
+ }) {
3459
+ if (userIds.length === 0) return;
3460
+ const { associateRole, associatedPath: path } = getAssociateAccessMeta(resourceType);
3461
+ const removedResourceId = typeof resourceId === "string" ? new mongoose39.Types.ObjectId(resourceId) : resourceId;
3462
+ await UserModel.updateMany({ _id: { $in: userIds } }, [
3463
+ {
3464
+ $set: {
3465
+ [path]: {
3466
+ $setDifference: [{ $ifNull: [`$${path}`, []] }, [removedResourceId]]
3467
+ }
3468
+ }
3469
+ },
3470
+ {
3471
+ $set: {
3472
+ roles: {
3473
+ $cond: [
3474
+ { $eq: [{ $size: { $ifNull: [`$${path}`, []] } }, 0] },
3475
+ {
3476
+ $setDifference: [{ $ifNull: ["$roles", []] }, [associateRole]]
3477
+ },
3478
+ "$roles"
3479
+ ]
3480
+ }
3481
+ }
3482
+ }
3483
+ ]).exec();
3484
+ }
3485
+ async function acceptedUserIdsForResource({
3486
+ resourceId,
3487
+ resourceType
3488
+ }) {
3489
+ const model = ASSOCIABLE_MODELS[resourceType];
3490
+ const resource = await model.findOne({ _id: resourceId, deletedAt: null }).select("associates").lean().exec();
3491
+ return new Set(
3492
+ acceptedAssociateUserIds(resource?.associates).map(
3493
+ (userId) => String(userId)
3494
+ )
3495
+ );
3496
+ }
3497
+ async function grantAssociateGrants({
3498
+ resourceId,
3499
+ resourceType,
3500
+ userIds
3501
+ }) {
3502
+ if (userIds.length === 0) return;
3503
+ const acceptedUserIds = await acceptedUserIdsForResource({
3504
+ resourceId,
3505
+ resourceType
3506
+ });
3507
+ const grantUserIds = userIds.filter(
3508
+ (userId) => acceptedUserIds.has(String(userId))
3509
+ );
3510
+ if (grantUserIds.length === 0) return;
3511
+ const { associateRole, associatedPath } = getAssociateAccessMeta(resourceType);
3512
+ await UserModel.updateMany(
3513
+ { _id: { $in: grantUserIds } },
3514
+ {
3515
+ $addToSet: {
3516
+ [associatedPath]: resourceId,
3517
+ roles: associateRole
3518
+ }
3519
+ }
3520
+ ).exec();
3521
+ }
3522
+ async function detachUnlessStillAccepted({
3523
+ resourceId,
3524
+ resourceType,
3525
+ userIds
3526
+ }) {
3527
+ if (userIds.length === 0) return [];
3528
+ await detachUsersFromResource({ resourceId, resourceType, userIds });
3529
+ const acceptedAfterDetach = await acceptedUserIdsForResource({
3530
+ resourceId,
3531
+ resourceType
3532
+ });
3533
+ const restoredUserIds = userIds.filter(
3534
+ (userId) => acceptedAfterDetach.has(String(userId))
3535
+ );
3536
+ if (restoredUserIds.length === 0) return userIds;
3537
+ await grantAssociateGrants({
3538
+ resourceId,
3539
+ resourceType,
3540
+ userIds: restoredUserIds
3541
+ });
3542
+ const acceptedAfterRestore = await acceptedUserIdsForResource({
3543
+ resourceId,
3544
+ resourceType
3545
+ });
3546
+ const regressedUserIds = restoredUserIds.filter(
3547
+ (userId) => !acceptedAfterRestore.has(String(userId))
3548
+ );
3549
+ if (regressedUserIds.length > 0) {
3550
+ await detachUsersFromResource({
3551
+ resourceId,
3552
+ resourceType,
3553
+ userIds: regressedUserIds
3554
+ });
3555
+ }
3556
+ return userIds.filter((userId) => !acceptedAfterRestore.has(String(userId)));
3557
+ }
3558
+ async function detachStaleAssociateGrants({
3559
+ acceptedUserIds,
3560
+ resourceId,
3561
+ resourceType
3562
+ }) {
3563
+ const { associatedPath } = getAssociateAccessMeta(resourceType);
3564
+ const stale = await UserModel.find({
3565
+ _id: { $nin: acceptedUserIds },
3566
+ [associatedPath]: resourceId
3567
+ }).select("_id").lean().exec();
3568
+ const staleUserIds = stale.map((user) => user._id);
3569
+ return detachUnlessStillAccepted({
3570
+ resourceId,
3571
+ resourceType,
3572
+ userIds: staleUserIds
3573
+ });
3574
+ }
3575
+ async function detachAssociateGrantsForResources({
3576
+ resources
3577
+ }) {
3578
+ const result = resources.map((resource) => ({
3579
+ detachedUserIds: [],
3580
+ resourceId: resource.resourceId,
3581
+ resourceType: resource.resourceType
3582
+ }));
3583
+ const indexByType = /* @__PURE__ */ new Map();
3584
+ resources.forEach((resource, index) => {
3585
+ const entries = indexByType.get(resource.resourceType) ?? [];
3586
+ entries.push({ index, resourceId: resource.resourceId });
3587
+ indexByType.set(resource.resourceType, entries);
3588
+ });
3589
+ for (const [resourceType, entries] of indexByType) {
3590
+ const { associatedField, associatedPath } = getAssociateAccessMeta(resourceType);
3591
+ const resourceIds = entries.map((entry) => entry.resourceId);
3592
+ const wanted = new Set(resourceIds.map((resourceId) => String(resourceId)));
3593
+ const holders = await UserModel.find({
3594
+ [associatedPath]: { $in: resourceIds }
3595
+ }).select("_id associatedResources").lean().exec();
3596
+ const userIdsByResource = /* @__PURE__ */ new Map();
3597
+ for (const user of holders) {
3598
+ for (const heldResourceId of user.associatedResources?.[associatedField] ?? []) {
3599
+ const key = String(heldResourceId);
3600
+ if (!wanted.has(key)) continue;
3601
+ const userIds = userIdsByResource.get(key) ?? [];
3602
+ userIds.push(user._id);
3603
+ userIdsByResource.set(key, userIds);
3604
+ }
3605
+ }
3606
+ for (const entry of entries) {
3607
+ const userIds = userIdsByResource.get(String(entry.resourceId));
3608
+ if (!userIds || userIds.length === 0) continue;
3609
+ await detachUsersFromResource({
3610
+ resourceId: entry.resourceId,
3611
+ resourceType,
3612
+ userIds
3613
+ });
3614
+ result[entry.index].detachedUserIds = userIds;
3615
+ }
3616
+ }
3617
+ return result;
3618
+ }
3619
+ var DEFAULT_RECONCILE_BATCH_SIZE = 500;
3620
+ async function reconcileUserBatch({
3621
+ associatedField,
3622
+ model,
3623
+ resourceType,
3624
+ users
3625
+ }) {
3626
+ const heldByResource = /* @__PURE__ */ new Map();
3627
+ for (const user of users) {
3628
+ for (const resourceId of user.associatedResources?.[associatedField] ?? []) {
3629
+ const key = String(resourceId);
3630
+ const entry = heldByResource.get(key) ?? { resourceId, userIds: [] };
3631
+ entry.userIds.push(user._id);
3632
+ heldByResource.set(key, entry);
3633
+ }
3634
+ }
3635
+ if (heldByResource.size === 0) return 0;
3636
+ const resources = await model.find({
3637
+ _id: {
3638
+ $in: [...heldByResource.values()].map((entry) => entry.resourceId)
3639
+ }
3640
+ }).select("associates deletedAt").lean().exec();
3641
+ const acceptedByResource = /* @__PURE__ */ new Map();
3642
+ for (const resource of resources) {
3643
+ acceptedByResource.set(
3644
+ String(resource._id),
3645
+ resource.deletedAt ? /* @__PURE__ */ new Set() : new Set(
3646
+ acceptedAssociateUserIds(resource.associates).map(
3647
+ (userId) => String(userId)
3648
+ )
3649
+ )
3650
+ );
3651
+ }
3652
+ let detachedGrants = 0;
3653
+ for (const [key, { resourceId, userIds }] of heldByResource) {
3654
+ const accepted = acceptedByResource.get(key);
3655
+ const staleUserIds = userIds.filter(
3656
+ (userId) => !accepted?.has(String(userId))
3657
+ );
3658
+ if (staleUserIds.length === 0) continue;
3659
+ const removedUserIds = await detachUnlessStillAccepted({
3660
+ resourceId,
3661
+ resourceType,
3662
+ userIds: staleUserIds
3663
+ });
3664
+ detachedGrants += removedUserIds.length;
3665
+ }
3666
+ return detachedGrants;
3667
+ }
3668
+ async function reconcileResourceType({
3669
+ batchSize,
3670
+ resourceType
3671
+ }) {
3672
+ const { associatedField, associatedPath } = getAssociateAccessMeta(resourceType);
3673
+ const model = ASSOCIABLE_MODELS[resourceType];
3674
+ const result = {
3675
+ detachedGrants: 0,
3676
+ scannedUsers: 0
3677
+ };
3678
+ let lastId = null;
3679
+ for (; ; ) {
3680
+ const users = await UserModel.find({
3681
+ ...lastId ? { _id: { $gt: lastId } } : {},
3682
+ [associatedPath]: { $exists: true, $ne: [] }
3683
+ }).sort({ _id: 1 }).limit(batchSize).select("_id associatedResources").lean().exec();
3684
+ if (users.length === 0) break;
3685
+ result.scannedUsers += users.length;
3686
+ lastId = users[users.length - 1]._id;
3687
+ result.detachedGrants += await reconcileUserBatch({
3688
+ associatedField,
3689
+ model,
3690
+ resourceType,
3691
+ users
3692
+ });
3693
+ }
3694
+ return result;
3695
+ }
3696
+ async function reconcileAssociateGrants({
3697
+ batchSize = DEFAULT_RECONCILE_BATCH_SIZE
3698
+ } = {}) {
3699
+ const totals = {
3700
+ detachedGrants: 0,
3701
+ scannedUsers: 0
3702
+ };
3703
+ for (const resourceType of [
3704
+ EnumResourceType10.EVENT,
3705
+ EnumResourceType10.VENDOR,
3706
+ EnumResourceType10.PARTNER
3707
+ ]) {
3708
+ const result = await reconcileResourceType({ batchSize, resourceType });
3709
+ totals.detachedGrants += result.detachedGrants;
3710
+ totals.scannedUsers += result.scannedUsers;
3711
+ }
3712
+ return totals;
3713
+ }
3714
+
3357
3715
  // src/service/database.ts
3358
- import mongoose40 from "mongoose";
3716
+ import mongoose41 from "mongoose";
3359
3717
 
3360
3718
  // src/service/indexes.ts
3361
- import mongoose39 from "mongoose";
3719
+ import mongoose40 from "mongoose";
3362
3720
  function registeredModels() {
3363
- return mongoose39.modelNames().map((modelName) => {
3364
- const model = mongoose39.model(modelName);
3721
+ return mongoose40.modelNames().map((modelName) => {
3722
+ const model = mongoose40.model(modelName);
3365
3723
  return { createIndexes: () => model.createIndexes(), modelName };
3366
3724
  });
3367
3725
  }
@@ -3403,7 +3761,7 @@ var connectToDatabase = async ({
3403
3761
  // Fallback to MongoDB Atlas connection string
3404
3762
  `mongodb+srv://${dbUser}:${dbPassword}@${dbName}.mongodb.net/?retryWrites=true&w=majority&appName=${appName}`
3405
3763
  );
3406
- await mongoose40.connect(mongoUri);
3764
+ await mongoose41.connect(mongoUri);
3407
3765
  const connectionType = mongodbUri ? "Local MongoDB" : "MongoDB Atlas";
3408
3766
  console.log(
3409
3767
  `${connectionType} connected from server/src/service/database.ts`
@@ -3419,7 +3777,7 @@ var connectToDatabase = async ({
3419
3777
 
3420
3778
  // src/types/index.ts
3421
3779
  import express from "express";
3422
- import mongoose41 from "mongoose";
3780
+ import mongoose42 from "mongoose";
3423
3781
  var EnumPubSubEvents = /* @__PURE__ */ ((EnumPubSubEvents2) => {
3424
3782
  EnumPubSubEvents2["GET_CHAT_MESSAGE"] = "GET_CHAT_MESSAGE";
3425
3783
  EnumPubSubEvents2["GET_NOTIFICATIONS"] = "GET_NOTIFICATIONS";
@@ -3541,15 +3899,15 @@ async function updateAdStatuses() {
3541
3899
  }
3542
3900
 
3543
3901
  // src/service/objectIdToString.ts
3544
- import mongoose42 from "mongoose";
3902
+ import mongoose43 from "mongoose";
3545
3903
  function isValidObjectId(value) {
3546
- return mongoose42.Types.ObjectId.isValid(value);
3904
+ return mongoose43.Types.ObjectId.isValid(value);
3547
3905
  }
3548
3906
  function convertObjectIdsToStrings(obj) {
3549
3907
  if (obj === null || obj === void 0) {
3550
3908
  return obj;
3551
3909
  }
3552
- if (obj instanceof mongoose42.Types.ObjectId) {
3910
+ if (obj instanceof mongoose43.Types.ObjectId) {
3553
3911
  return obj.toString();
3554
3912
  }
3555
3913
  if (obj instanceof Date) {
@@ -4306,7 +4664,7 @@ async function handlePartnerLicenceCompliance(user, now) {
4306
4664
  import {
4307
4665
  EnumNotificationResourceType as EnumNotificationResourceType4,
4308
4666
  EnumNotificationType as EnumNotificationType3,
4309
- EnumSubscriptionStatus as EnumSubscriptionStatus3,
4667
+ EnumResourceType as EnumResourceType12,
4310
4668
  EnumUserLicence as EnumUserLicence9,
4311
4669
  vendorLicences
4312
4670
  } from "@timardex/cluemart-shared";
@@ -4314,20 +4672,21 @@ import dayjs6 from "dayjs";
4314
4672
 
4315
4673
  // src/service/license/models.ts
4316
4674
  import {
4317
- EnumResourceType as EnumResourceType10,
4675
+ EnumResourceType as EnumResourceType11,
4676
+ EnumSubscriptionStatus as EnumSubscriptionStatus3,
4318
4677
  EnumUserLicence as EnumUserLicence8,
4319
4678
  isNonVisitorResourceType,
4320
4679
  LicenceExpiryDate
4321
4680
  } from "@timardex/cluemart-shared";
4322
4681
  import dayjs5 from "dayjs";
4323
4682
  import { GraphQLError } from "graphql";
4324
- var LicenceCategory = /* @__PURE__ */ ((LicenceCategory2) => {
4325
- LicenceCategory2["EVENT"] = "event";
4326
- LicenceCategory2["PARTNER"] = "partner";
4327
- LicenceCategory2["VENDOR"] = "vendor";
4328
- LicenceCategory2["AFFILIATE"] = "affiliate";
4329
- LicenceCategory2["SCHOOL"] = "school";
4330
- return LicenceCategory2;
4683
+ var LicenceCategory = /* @__PURE__ */ ((LicenceCategory3) => {
4684
+ LicenceCategory3["EVENT"] = "event";
4685
+ LicenceCategory3["PARTNER"] = "partner";
4686
+ LicenceCategory3["VENDOR"] = "vendor";
4687
+ LicenceCategory3["AFFILIATE"] = "affiliate";
4688
+ LicenceCategory3["SCHOOL"] = "school";
4689
+ return LicenceCategory3;
4331
4690
  })(LicenceCategory || {});
4332
4691
  var licenceCategoryMapping = {
4333
4692
  [EnumUserLicence8.PRO_EVENT]: "event" /* EVENT */,
@@ -4360,6 +4719,16 @@ var standardLicenceSet = new Set(standardLicences);
4360
4719
  function isStandardLicence(licence) {
4361
4720
  return standardLicenceSet.has(licence);
4362
4721
  }
4722
+ var proLicences = [
4723
+ EnumUserLicence8.PRO_EVENT,
4724
+ EnumUserLicence8.PRO_PLUS_EVENT,
4725
+ EnumUserLicence8.PRO_VENDOR,
4726
+ EnumUserLicence8.PRO_PLUS_VENDOR
4727
+ ];
4728
+ var proLicenceSet = new Set(proLicences);
4729
+ function isProLicence(licence) {
4730
+ return proLicenceSet.has(licence);
4731
+ }
4363
4732
  var categoryRegexMapping = {
4364
4733
  ["event" /* EVENT */]: /_event$/,
4365
4734
  ["partner" /* PARTNER */]: /_partner$/,
@@ -4510,11 +4879,11 @@ async function checkOwnerHasLicence({
4510
4879
  const owner = await UserModel.findById(userId);
4511
4880
  if (!owner) throw new GraphQLError("Owner not found");
4512
4881
  const categoryByResource = {
4513
- [EnumResourceType10.EVENT]: "event" /* EVENT */,
4514
- [EnumResourceType10.PARTNER]: "partner" /* PARTNER */,
4515
- [EnumResourceType10.VENDOR]: "vendor" /* VENDOR */,
4516
- [EnumResourceType10.AFFILIATE]: "affiliate" /* AFFILIATE */,
4517
- [EnumResourceType10.SCHOOL]: "school" /* SCHOOL */
4882
+ [EnumResourceType11.EVENT]: "event" /* EVENT */,
4883
+ [EnumResourceType11.PARTNER]: "partner" /* PARTNER */,
4884
+ [EnumResourceType11.VENDOR]: "vendor" /* VENDOR */,
4885
+ [EnumResourceType11.AFFILIATE]: "affiliate" /* AFFILIATE */,
4886
+ [EnumResourceType11.SCHOOL]: "school" /* SCHOOL */
4518
4887
  };
4519
4888
  if (!isNonVisitorResourceType(resourceType)) {
4520
4889
  throw new GraphQLError(`Invalid resource type: ${resourceType}.`);
@@ -4538,6 +4907,128 @@ async function checkOwnerHasLicence({
4538
4907
  );
4539
4908
  }
4540
4909
  }
4910
+ var resourceLicenceCategory = {
4911
+ [EnumResourceType11.EVENT]: "event" /* EVENT */,
4912
+ [EnumResourceType11.PARTNER]: "partner" /* PARTNER */,
4913
+ [EnumResourceType11.VENDOR]: "vendor" /* VENDOR */
4914
+ };
4915
+ function isProtectedByCurrentStripeSubscription(user, licenceType, now) {
4916
+ const stripe = user.stripe;
4917
+ if (!stripe || stripe.currentPlan !== licenceType) {
4918
+ return false;
4919
+ }
4920
+ const gracePeriodEndsAt = stripe.paymentGracePeriodEndsAt ? dayjs5(stripe.paymentGracePeriodEndsAt) : null;
4921
+ const hasActivePaymentGracePeriod = (stripe.status === EnumSubscriptionStatus3.PAST_DUE || stripe.status === EnumSubscriptionStatus3.INACTIVE) && Boolean(stripe.paymentGraceSubscriptionId) && (!stripe.subscriptionId || stripe.subscriptionId === stripe.paymentGraceSubscriptionId) && gracePeriodEndsAt !== null && gracePeriodEndsAt.isValid() && gracePeriodEndsAt.isAfter(now);
4922
+ if (hasActivePaymentGracePeriod) {
4923
+ return true;
4924
+ }
4925
+ if (!stripe.subscriptionId) {
4926
+ return false;
4927
+ }
4928
+ if (stripe.status !== EnumSubscriptionStatus3.ACTIVE) {
4929
+ return false;
4930
+ }
4931
+ if (!stripe.endDate) {
4932
+ return false;
4933
+ }
4934
+ const paidThrough = dayjs5(stripe.endDate);
4935
+ return paidThrough.isValid() && paidThrough.isAfter(now);
4936
+ }
4937
+ function effectiveLicences({
4938
+ includeStripeProtected = false,
4939
+ licences,
4940
+ now,
4941
+ owner
4942
+ }) {
4943
+ const nowDayjs = dayjs5(now);
4944
+ return (licences ?? []).filter((licence) => {
4945
+ if (!licence.licenceType || licence.expiryDate == null) {
4946
+ return false;
4947
+ }
4948
+ if (new Date(licence.expiryDate).getTime() > now.getTime()) {
4949
+ return true;
4950
+ }
4951
+ return Boolean(
4952
+ includeStripeProtected && owner && isProtectedByCurrentStripeSubscription(
4953
+ owner,
4954
+ licence.licenceType,
4955
+ nowDayjs
4956
+ )
4957
+ );
4958
+ });
4959
+ }
4960
+ async function getActiveLicenceForResource({
4961
+ includeStripeProtected = false,
4962
+ userId,
4963
+ resourceType,
4964
+ now = /* @__PURE__ */ new Date()
4965
+ }) {
4966
+ const category = resourceLicenceCategory[resourceType];
4967
+ if (!category) {
4968
+ return null;
4969
+ }
4970
+ const owner = await UserModel.findById(userId, {
4971
+ licences: 1,
4972
+ ...includeStripeProtected ? { stripe: 1 } : {}
4973
+ }).lean();
4974
+ if (!owner?.licences?.length) {
4975
+ return null;
4976
+ }
4977
+ return getHighestLicenceForCategory(
4978
+ effectiveLicences({
4979
+ includeStripeProtected,
4980
+ licences: owner.licences,
4981
+ now,
4982
+ owner
4983
+ }),
4984
+ category
4985
+ );
4986
+ }
4987
+ async function getUserIdsWithActiveProLicence({
4988
+ includeStripeProtected = false,
4989
+ resourceType,
4990
+ userIds,
4991
+ now = /* @__PURE__ */ new Date()
4992
+ }) {
4993
+ const category = resourceLicenceCategory[resourceType];
4994
+ if (!category || userIds.length === 0) {
4995
+ return /* @__PURE__ */ new Set();
4996
+ }
4997
+ const owners = await UserModel.find(
4998
+ { _id: { $in: userIds } },
4999
+ { licences: 1, ...includeStripeProtected ? { stripe: 1 } : {} }
5000
+ ).lean();
5001
+ const allowed = /* @__PURE__ */ new Set();
5002
+ for (const owner of owners ?? []) {
5003
+ const activeLicence = getHighestLicenceForCategory(
5004
+ effectiveLicences({
5005
+ includeStripeProtected,
5006
+ licences: owner.licences,
5007
+ now,
5008
+ owner
5009
+ }),
5010
+ category
5011
+ );
5012
+ if (activeLicence && isProLicence(activeLicence)) {
5013
+ allowed.add(String(owner._id));
5014
+ }
5015
+ }
5016
+ return allowed;
5017
+ }
5018
+ async function hasActiveProLicenceForResource({
5019
+ includeStripeProtected = false,
5020
+ userId,
5021
+ resourceType,
5022
+ now = /* @__PURE__ */ new Date()
5023
+ }) {
5024
+ const activeLicence = await getActiveLicenceForResource({
5025
+ includeStripeProtected,
5026
+ now,
5027
+ resourceType,
5028
+ userId
5029
+ });
5030
+ return activeLicence !== null && isProLicence(activeLicence);
5031
+ }
4541
5032
 
4542
5033
  // src/service/license/compliance/vendor.ts
4543
5034
  async function findUserVendor(userId, logLabel) {
@@ -4658,28 +5149,6 @@ async function restoreVendorProFeatures(userId, licenceType) {
4658
5149
  throw error;
4659
5150
  }
4660
5151
  }
4661
- function isProtectedByCurrentStripeSubscription(user, licenceType, now) {
4662
- const stripe = user.stripe;
4663
- if (!stripe || stripe.currentPlan !== licenceType) {
4664
- return false;
4665
- }
4666
- const gracePeriodEndsAt = stripe.paymentGracePeriodEndsAt ? dayjs6(stripe.paymentGracePeriodEndsAt) : null;
4667
- const hasActivePaymentGracePeriod = (stripe.status === EnumSubscriptionStatus3.PAST_DUE || stripe.status === EnumSubscriptionStatus3.INACTIVE) && Boolean(stripe.paymentGraceSubscriptionId) && (!stripe.subscriptionId || stripe.subscriptionId === stripe.paymentGraceSubscriptionId) && gracePeriodEndsAt !== null && gracePeriodEndsAt.isValid() && gracePeriodEndsAt.isAfter(now);
4668
- if (hasActivePaymentGracePeriod) {
4669
- return true;
4670
- }
4671
- if (!stripe.subscriptionId) {
4672
- return false;
4673
- }
4674
- if (stripe.status !== EnumSubscriptionStatus3.ACTIVE) {
4675
- return false;
4676
- }
4677
- if (!stripe.endDate) {
4678
- return false;
4679
- }
4680
- const paidThrough = dayjs6(stripe.endDate);
4681
- return paidThrough.isValid() && paidThrough.isAfter(now);
4682
- }
4683
5152
  async function handleVendorLicenceCompliance(user, now) {
4684
5153
  if (!user.licences || !user.vendor) {
4685
5154
  return;
@@ -4690,10 +5159,10 @@ async function handleVendorLicenceCompliance(user, now) {
4690
5159
  if (vendorLicencesOfUser.length === 0) {
4691
5160
  return;
4692
5161
  }
4693
- const proLicences = vendorLicencesOfUser.filter(
5162
+ const proLicences2 = vendorLicencesOfUser.filter(
4694
5163
  (licence) => licence.licenceType !== EnumUserLicence9.STANDARD_VENDOR
4695
5164
  );
4696
- const expiredProLicences = proLicences.filter(
5165
+ const expiredProLicences = proLicences2.filter(
4697
5166
  (licence) => !dayjs6(licence.expiryDate).isAfter(now)
4698
5167
  );
4699
5168
  const stripeProtectedLicenceTypes = new Set(
@@ -4704,7 +5173,7 @@ async function handleVendorLicenceCompliance(user, now) {
4704
5173
  const expiredProLicence = expiredProLicences.some(
4705
5174
  (licence) => !stripeProtectedLicenceTypes.has(licence.licenceType)
4706
5175
  );
4707
- const hasValidProLicence = stripeProtectedLicenceTypes.size > 0 || hasValidLicence(proLicences, vendorLicences, now);
5176
+ const hasValidProLicence = stripeProtectedLicenceTypes.size > 0 || hasValidLicence(proLicences2, vendorLicences, now);
4708
5177
  const hasExpiredVendorLicence = vendorLicencesOfUser.some(
4709
5178
  (licence) => !dayjs6(licence.expiryDate).isAfter(now) && !stripeProtectedLicenceTypes.has(licence.licenceType)
4710
5179
  );
@@ -4753,26 +5222,11 @@ async function vendorOwnerHasProLicence(vendorId) {
4753
5222
  if (!vendor) {
4754
5223
  return false;
4755
5224
  }
4756
- const owner = await UserModel.findById(vendor.owner.userId, {
4757
- licences: 1,
4758
- stripe: 1
4759
- }).lean().exec();
4760
- if (!owner) {
4761
- return false;
4762
- }
4763
- const now = dayjs6();
4764
- const effectiveVendorLicences = owner.licences?.filter(
4765
- (licence) => licence?.licenceType && (dayjs6(licence.expiryDate).isAfter(now) || isProtectedByCurrentStripeSubscription(
4766
- owner,
4767
- licence.licenceType,
4768
- now
4769
- ))
4770
- );
4771
- const highestVendorLicence = getHighestLicenceForCategory(
4772
- effectiveVendorLicences,
4773
- "vendor" /* VENDOR */
4774
- );
4775
- return highestVendorLicence !== null && licencePriority[highestVendorLicence] >= licencePriority[EnumUserLicence9.PRO_VENDOR];
5225
+ return hasActiveProLicenceForResource({
5226
+ includeStripeProtected: true,
5227
+ resourceType: EnumResourceType12.VENDOR,
5228
+ userId: vendor.owner.userId
5229
+ });
4776
5230
  }
4777
5231
 
4778
5232
  // src/service/license/compliance/utils.ts
@@ -5200,6 +5654,7 @@ export {
5200
5654
  AiImportRunModel,
5201
5655
  AiImportedMarketModel,
5202
5656
  AppSettingModel,
5657
+ AssociateTypeSchema,
5203
5658
  AuthHandoffTokenModel,
5204
5659
  BILLING_CATALOG_COLLECTION_NAME,
5205
5660
  BillingCatalogModel,
@@ -5239,6 +5694,7 @@ export {
5239
5694
  VendorInfoModel,
5240
5695
  VendorModel,
5241
5696
  VerificationTokenModel,
5697
+ acceptedAssociateUserIds,
5242
5698
  activeAffiliateCodeExists,
5243
5699
  awardAffiliateVendorSubscriptionRewards,
5244
5700
  baseResourceFields,
@@ -5255,6 +5711,9 @@ export {
5255
5711
  createLicenceObject,
5256
5712
  dateTimeSchema,
5257
5713
  dedupeArchivedSlotsByStartDateTime,
5714
+ detachAssociateGrantsForResources,
5715
+ detachStaleAssociateGrants,
5716
+ detachUsersFromResource,
5258
5717
  didRemoveAnyEventDates,
5259
5718
  didRemoveAnyStartedDates,
5260
5719
  downgradeVendorProFeatures,
@@ -5265,6 +5724,8 @@ export {
5265
5724
  express,
5266
5725
  findAffiliateByPromoCode,
5267
5726
  findEventOrImportedMarketById,
5727
+ getActiveLicenceForResource,
5728
+ getAssociateAccessMeta,
5268
5729
  getBillingCatalogDefinition,
5269
5730
  getEventResourceInfo,
5270
5731
  getHighestLicenceForCategory,
@@ -5275,11 +5736,17 @@ export {
5275
5736
  getPayingStripeSubscriptionPlan,
5276
5737
  getPayingVendorStripeSubscriptionPlan,
5277
5738
  getSubscriptionRewardPeriodBounds,
5739
+ getUserIdsWithActiveProLicence,
5278
5740
  getVendorResourceInfo,
5741
+ grantAssociateGrants,
5279
5742
  handleEventLicenceCompliance,
5280
5743
  handlePartnerLicenceCompliance,
5281
5744
  handleVendorLicenceCompliance,
5745
+ hasActiveProLicenceForResource,
5282
5746
  hasValidLicence,
5747
+ isAssociableResourceType,
5748
+ isProLicence,
5749
+ isProtectedByCurrentStripeSubscription,
5283
5750
  isStandardLicence,
5284
5751
  isValidObjectId,
5285
5752
  licenceCategoryMapping,
@@ -5287,7 +5754,7 @@ export {
5287
5754
  locationGeoSchema,
5288
5755
  locationsSchema,
5289
5756
  mapVendorLicenceToSubscriptionRewardType,
5290
- mongoose41 as mongoose,
5757
+ mongoose42 as mongoose,
5291
5758
  normalizeAffiliatePromoCodes,
5292
5759
  normalizePromoCode,
5293
5760
  notifyUsers,
@@ -5297,6 +5764,7 @@ export {
5297
5764
  processUserCompliance,
5298
5765
  processUserLicenseReminders,
5299
5766
  publishNotificationEvents,
5767
+ reconcileAssociateGrants,
5300
5768
  refundPolicySchema,
5301
5769
  relatedPostSchema,
5302
5770
  relationDatesSchema,