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