@timardex/cluemart-server-shared 4.0.8 → 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,
@@ -1153,6 +1174,8 @@ var schema8 = new MongooseSchema7(
1153
1174
  missingFields: { required: false, type: [String] },
1154
1175
  name: { required: true, type: String },
1155
1176
  openingHours: { required: false, type: [String] },
1177
+ publicationCityUnknown: { default: false, required: false, type: Boolean },
1178
+ publicationKey: { required: false, type: String },
1156
1179
  rainOrShine: { required: true, type: Boolean },
1157
1180
  rating: { required: false, type: Number },
1158
1181
  region: { required: false, type: String },
@@ -1164,6 +1187,7 @@ var schema8 = new MongooseSchema7(
1164
1187
  required: false,
1165
1188
  type: mongoose11.Schema.Types.ObjectId
1166
1189
  },
1190
+ reviewerEditedAt: { default: null, required: false, type: Date },
1167
1191
  reviewStatus: {
1168
1192
  default: EnumImportedMarketReviewStatus.PENDING,
1169
1193
  enum: Object.values(EnumImportedMarketReviewStatus),
@@ -1200,6 +1224,16 @@ schema8.index({
1200
1224
  _id: 1
1201
1225
  });
1202
1226
  schema8.index({ region: 1, searchName: 1 });
1227
+ schema8.index(
1228
+ { publicationKey: 1 },
1229
+ {
1230
+ name: "ai_market_publication_key",
1231
+ partialFilterExpression: {
1232
+ publicationKey: { $exists: true, $type: "string" }
1233
+ },
1234
+ unique: true
1235
+ }
1236
+ );
1203
1237
  schema8.index({ slug: 1 });
1204
1238
  schema8.index({ reviewStatus: 1 });
1205
1239
  schema8.index({ description: "text", name: "text" });
@@ -1783,6 +1817,29 @@ var userOverallPointsSchema = new MongooseSchema16(
1783
1817
  },
1784
1818
  { _id: false }
1785
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
+ );
1786
1843
  var schema15 = new MongooseSchema16(
1787
1844
  {
1788
1845
  active: { default: false, required: true, type: Boolean },
@@ -1791,6 +1848,11 @@ var schema15 = new MongooseSchema16(
1791
1848
  required: false,
1792
1849
  type: mongoose20.Schema.Types.ObjectId
1793
1850
  },
1851
+ associatedResources: {
1852
+ default: () => ({ events: [], partners: [], vendors: [] }),
1853
+ required: false,
1854
+ type: userAssociatedResourcesSchema
1855
+ },
1794
1856
  avatar: {
1795
1857
  required: false,
1796
1858
  type: ResourceImageTypeSchema
@@ -1801,7 +1863,10 @@ var schema15 = new MongooseSchema16(
1801
1863
  type: mongoose20.Schema.Types.ObjectId
1802
1864
  },
1803
1865
  deletedAt: { default: null, required: false, type: Date },
1804
- 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 },
1805
1870
  emailSentFor: {
1806
1871
  enum: Object.values(EnumNotificationResourceType2),
1807
1872
  required: false,
@@ -1916,6 +1981,9 @@ schema15.index({ "licences.expiryDate": 1 });
1916
1981
  schema15.index({ "licences.licenceType": 1 });
1917
1982
  schema15.index({ promoCodes: 1, active: 1, deletedAt: 1 });
1918
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 });
1919
1987
  var UserModel = mongoose20.models.User || mongoose20.model("User", schema15);
1920
1988
 
1921
1989
  // src/mongoose/VerificationToken.ts
@@ -2052,6 +2120,7 @@ schema17.index({
2052
2120
  name: "text"
2053
2121
  });
2054
2122
  schema17.index({ deletedAt: 1, "owner.userId": 1 });
2123
+ schema17.index({ "associates.userId": 1, deletedAt: 1 });
2055
2124
  schema17.plugin(searchNamePlugin);
2056
2125
  var VendorModel = mongoose22.models.Vendor || mongoose22.model("Vendor", schema17);
2057
2126
 
@@ -2159,6 +2228,13 @@ var schema20 = new MongooseSchema21(
2159
2228
  {
2160
2229
  ...baseResourceFields,
2161
2230
  // Importing base resource fields from global.ts
2231
+ // Claim link of the AI-imported market this event was created from, the
2232
+ // counterpart of `googlePlaceId`. Written once by `createEvent`.
2233
+ aiImportedMarketSourceKey: {
2234
+ default: null,
2235
+ required: false,
2236
+ type: String
2237
+ },
2162
2238
  claimed: { default: true, required: false, type: Boolean },
2163
2239
  dateTime: { required: true, type: [dateTimeSchema] },
2164
2240
  eventInfoId: {
@@ -2198,6 +2274,7 @@ schema20.index({ "dateTime.dateStatus": 1 });
2198
2274
  schema20.index({ slug: 1 });
2199
2275
  schema20.index({ description: "text", name: "text", tags: "text" });
2200
2276
  schema20.index({ deletedAt: 1, "owner.userId": 1 });
2277
+ schema20.index({ "associates.userId": 1, deletedAt: 1 });
2201
2278
  schema20.plugin(searchNamePlugin);
2202
2279
  var EventModel = mongoose25.models.Event || mongoose25.model("Event", schema20);
2203
2280
 
@@ -2244,6 +2321,7 @@ schema22.index({ "location.geo": "2dsphere" });
2244
2321
  schema22.index({ slug: 1 });
2245
2322
  schema22.index({ name: "text", description: "text" });
2246
2323
  schema22.index({ "owner.userId": 1, deletedAt: 1 });
2324
+ schema22.index({ "associates.userId": 1, deletedAt: 1 });
2247
2325
  schema22.plugin(searchNamePlugin);
2248
2326
  var PartnerModel = mongoose27.models.Partner || mongoose27.model("Partner", schema22);
2249
2327
 
@@ -3334,14 +3412,314 @@ function normalizeAffiliatePromoCodes(promoCodes) {
3334
3412
  return [...new Set(normalized)];
3335
3413
  }
3336
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
+
3337
3715
  // src/service/database.ts
3338
- import mongoose40 from "mongoose";
3716
+ import mongoose41 from "mongoose";
3339
3717
 
3340
3718
  // src/service/indexes.ts
3341
- import mongoose39 from "mongoose";
3719
+ import mongoose40 from "mongoose";
3342
3720
  function registeredModels() {
3343
- return mongoose39.modelNames().map((modelName) => {
3344
- const model = mongoose39.model(modelName);
3721
+ return mongoose40.modelNames().map((modelName) => {
3722
+ const model = mongoose40.model(modelName);
3345
3723
  return { createIndexes: () => model.createIndexes(), modelName };
3346
3724
  });
3347
3725
  }
@@ -3383,7 +3761,7 @@ var connectToDatabase = async ({
3383
3761
  // Fallback to MongoDB Atlas connection string
3384
3762
  `mongodb+srv://${dbUser}:${dbPassword}@${dbName}.mongodb.net/?retryWrites=true&w=majority&appName=${appName}`
3385
3763
  );
3386
- await mongoose40.connect(mongoUri);
3764
+ await mongoose41.connect(mongoUri);
3387
3765
  const connectionType = mongodbUri ? "Local MongoDB" : "MongoDB Atlas";
3388
3766
  console.log(
3389
3767
  `${connectionType} connected from server/src/service/database.ts`
@@ -3399,7 +3777,7 @@ var connectToDatabase = async ({
3399
3777
 
3400
3778
  // src/types/index.ts
3401
3779
  import express from "express";
3402
- import mongoose41 from "mongoose";
3780
+ import mongoose42 from "mongoose";
3403
3781
  var EnumPubSubEvents = /* @__PURE__ */ ((EnumPubSubEvents2) => {
3404
3782
  EnumPubSubEvents2["GET_CHAT_MESSAGE"] = "GET_CHAT_MESSAGE";
3405
3783
  EnumPubSubEvents2["GET_NOTIFICATIONS"] = "GET_NOTIFICATIONS";
@@ -3521,15 +3899,15 @@ async function updateAdStatuses() {
3521
3899
  }
3522
3900
 
3523
3901
  // src/service/objectIdToString.ts
3524
- import mongoose42 from "mongoose";
3902
+ import mongoose43 from "mongoose";
3525
3903
  function isValidObjectId(value) {
3526
- return mongoose42.Types.ObjectId.isValid(value);
3904
+ return mongoose43.Types.ObjectId.isValid(value);
3527
3905
  }
3528
3906
  function convertObjectIdsToStrings(obj) {
3529
3907
  if (obj === null || obj === void 0) {
3530
3908
  return obj;
3531
3909
  }
3532
- if (obj instanceof mongoose42.Types.ObjectId) {
3910
+ if (obj instanceof mongoose43.Types.ObjectId) {
3533
3911
  return obj.toString();
3534
3912
  }
3535
3913
  if (obj instanceof Date) {
@@ -4286,7 +4664,7 @@ async function handlePartnerLicenceCompliance(user, now) {
4286
4664
  import {
4287
4665
  EnumNotificationResourceType as EnumNotificationResourceType4,
4288
4666
  EnumNotificationType as EnumNotificationType3,
4289
- EnumSubscriptionStatus as EnumSubscriptionStatus3,
4667
+ EnumResourceType as EnumResourceType12,
4290
4668
  EnumUserLicence as EnumUserLicence9,
4291
4669
  vendorLicences
4292
4670
  } from "@timardex/cluemart-shared";
@@ -4294,20 +4672,21 @@ import dayjs6 from "dayjs";
4294
4672
 
4295
4673
  // src/service/license/models.ts
4296
4674
  import {
4297
- EnumResourceType as EnumResourceType10,
4675
+ EnumResourceType as EnumResourceType11,
4676
+ EnumSubscriptionStatus as EnumSubscriptionStatus3,
4298
4677
  EnumUserLicence as EnumUserLicence8,
4299
4678
  isNonVisitorResourceType,
4300
4679
  LicenceExpiryDate
4301
4680
  } from "@timardex/cluemart-shared";
4302
4681
  import dayjs5 from "dayjs";
4303
4682
  import { GraphQLError } from "graphql";
4304
- var LicenceCategory = /* @__PURE__ */ ((LicenceCategory2) => {
4305
- LicenceCategory2["EVENT"] = "event";
4306
- LicenceCategory2["PARTNER"] = "partner";
4307
- LicenceCategory2["VENDOR"] = "vendor";
4308
- LicenceCategory2["AFFILIATE"] = "affiliate";
4309
- LicenceCategory2["SCHOOL"] = "school";
4310
- 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;
4311
4690
  })(LicenceCategory || {});
4312
4691
  var licenceCategoryMapping = {
4313
4692
  [EnumUserLicence8.PRO_EVENT]: "event" /* EVENT */,
@@ -4340,6 +4719,16 @@ var standardLicenceSet = new Set(standardLicences);
4340
4719
  function isStandardLicence(licence) {
4341
4720
  return standardLicenceSet.has(licence);
4342
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
+ }
4343
4732
  var categoryRegexMapping = {
4344
4733
  ["event" /* EVENT */]: /_event$/,
4345
4734
  ["partner" /* PARTNER */]: /_partner$/,
@@ -4490,11 +4879,11 @@ async function checkOwnerHasLicence({
4490
4879
  const owner = await UserModel.findById(userId);
4491
4880
  if (!owner) throw new GraphQLError("Owner not found");
4492
4881
  const categoryByResource = {
4493
- [EnumResourceType10.EVENT]: "event" /* EVENT */,
4494
- [EnumResourceType10.PARTNER]: "partner" /* PARTNER */,
4495
- [EnumResourceType10.VENDOR]: "vendor" /* VENDOR */,
4496
- [EnumResourceType10.AFFILIATE]: "affiliate" /* AFFILIATE */,
4497
- [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 */
4498
4887
  };
4499
4888
  if (!isNonVisitorResourceType(resourceType)) {
4500
4889
  throw new GraphQLError(`Invalid resource type: ${resourceType}.`);
@@ -4518,6 +4907,128 @@ async function checkOwnerHasLicence({
4518
4907
  );
4519
4908
  }
4520
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
+ }
4521
5032
 
4522
5033
  // src/service/license/compliance/vendor.ts
4523
5034
  async function findUserVendor(userId, logLabel) {
@@ -4638,28 +5149,6 @@ async function restoreVendorProFeatures(userId, licenceType) {
4638
5149
  throw error;
4639
5150
  }
4640
5151
  }
4641
- function isProtectedByCurrentStripeSubscription(user, licenceType, now) {
4642
- const stripe = user.stripe;
4643
- if (!stripe || stripe.currentPlan !== licenceType) {
4644
- return false;
4645
- }
4646
- const gracePeriodEndsAt = stripe.paymentGracePeriodEndsAt ? dayjs6(stripe.paymentGracePeriodEndsAt) : null;
4647
- 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);
4648
- if (hasActivePaymentGracePeriod) {
4649
- return true;
4650
- }
4651
- if (!stripe.subscriptionId) {
4652
- return false;
4653
- }
4654
- if (stripe.status !== EnumSubscriptionStatus3.ACTIVE) {
4655
- return false;
4656
- }
4657
- if (!stripe.endDate) {
4658
- return false;
4659
- }
4660
- const paidThrough = dayjs6(stripe.endDate);
4661
- return paidThrough.isValid() && paidThrough.isAfter(now);
4662
- }
4663
5152
  async function handleVendorLicenceCompliance(user, now) {
4664
5153
  if (!user.licences || !user.vendor) {
4665
5154
  return;
@@ -4670,10 +5159,10 @@ async function handleVendorLicenceCompliance(user, now) {
4670
5159
  if (vendorLicencesOfUser.length === 0) {
4671
5160
  return;
4672
5161
  }
4673
- const proLicences = vendorLicencesOfUser.filter(
5162
+ const proLicences2 = vendorLicencesOfUser.filter(
4674
5163
  (licence) => licence.licenceType !== EnumUserLicence9.STANDARD_VENDOR
4675
5164
  );
4676
- const expiredProLicences = proLicences.filter(
5165
+ const expiredProLicences = proLicences2.filter(
4677
5166
  (licence) => !dayjs6(licence.expiryDate).isAfter(now)
4678
5167
  );
4679
5168
  const stripeProtectedLicenceTypes = new Set(
@@ -4684,7 +5173,7 @@ async function handleVendorLicenceCompliance(user, now) {
4684
5173
  const expiredProLicence = expiredProLicences.some(
4685
5174
  (licence) => !stripeProtectedLicenceTypes.has(licence.licenceType)
4686
5175
  );
4687
- const hasValidProLicence = stripeProtectedLicenceTypes.size > 0 || hasValidLicence(proLicences, vendorLicences, now);
5176
+ const hasValidProLicence = stripeProtectedLicenceTypes.size > 0 || hasValidLicence(proLicences2, vendorLicences, now);
4688
5177
  const hasExpiredVendorLicence = vendorLicencesOfUser.some(
4689
5178
  (licence) => !dayjs6(licence.expiryDate).isAfter(now) && !stripeProtectedLicenceTypes.has(licence.licenceType)
4690
5179
  );
@@ -4733,26 +5222,11 @@ async function vendorOwnerHasProLicence(vendorId) {
4733
5222
  if (!vendor) {
4734
5223
  return false;
4735
5224
  }
4736
- const owner = await UserModel.findById(vendor.owner.userId, {
4737
- licences: 1,
4738
- stripe: 1
4739
- }).lean().exec();
4740
- if (!owner) {
4741
- return false;
4742
- }
4743
- const now = dayjs6();
4744
- const effectiveVendorLicences = owner.licences?.filter(
4745
- (licence) => licence?.licenceType && (dayjs6(licence.expiryDate).isAfter(now) || isProtectedByCurrentStripeSubscription(
4746
- owner,
4747
- licence.licenceType,
4748
- now
4749
- ))
4750
- );
4751
- const highestVendorLicence = getHighestLicenceForCategory(
4752
- effectiveVendorLicences,
4753
- "vendor" /* VENDOR */
4754
- );
4755
- 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
+ });
4756
5230
  }
4757
5231
 
4758
5232
  // src/service/license/compliance/utils.ts
@@ -5180,6 +5654,7 @@ export {
5180
5654
  AiImportRunModel,
5181
5655
  AiImportedMarketModel,
5182
5656
  AppSettingModel,
5657
+ AssociateTypeSchema,
5183
5658
  AuthHandoffTokenModel,
5184
5659
  BILLING_CATALOG_COLLECTION_NAME,
5185
5660
  BillingCatalogModel,
@@ -5219,6 +5694,7 @@ export {
5219
5694
  VendorInfoModel,
5220
5695
  VendorModel,
5221
5696
  VerificationTokenModel,
5697
+ acceptedAssociateUserIds,
5222
5698
  activeAffiliateCodeExists,
5223
5699
  awardAffiliateVendorSubscriptionRewards,
5224
5700
  baseResourceFields,
@@ -5235,6 +5711,9 @@ export {
5235
5711
  createLicenceObject,
5236
5712
  dateTimeSchema,
5237
5713
  dedupeArchivedSlotsByStartDateTime,
5714
+ detachAssociateGrantsForResources,
5715
+ detachStaleAssociateGrants,
5716
+ detachUsersFromResource,
5238
5717
  didRemoveAnyEventDates,
5239
5718
  didRemoveAnyStartedDates,
5240
5719
  downgradeVendorProFeatures,
@@ -5245,6 +5724,8 @@ export {
5245
5724
  express,
5246
5725
  findAffiliateByPromoCode,
5247
5726
  findEventOrImportedMarketById,
5727
+ getActiveLicenceForResource,
5728
+ getAssociateAccessMeta,
5248
5729
  getBillingCatalogDefinition,
5249
5730
  getEventResourceInfo,
5250
5731
  getHighestLicenceForCategory,
@@ -5255,11 +5736,17 @@ export {
5255
5736
  getPayingStripeSubscriptionPlan,
5256
5737
  getPayingVendorStripeSubscriptionPlan,
5257
5738
  getSubscriptionRewardPeriodBounds,
5739
+ getUserIdsWithActiveProLicence,
5258
5740
  getVendorResourceInfo,
5741
+ grantAssociateGrants,
5259
5742
  handleEventLicenceCompliance,
5260
5743
  handlePartnerLicenceCompliance,
5261
5744
  handleVendorLicenceCompliance,
5745
+ hasActiveProLicenceForResource,
5262
5746
  hasValidLicence,
5747
+ isAssociableResourceType,
5748
+ isProLicence,
5749
+ isProtectedByCurrentStripeSubscription,
5263
5750
  isStandardLicence,
5264
5751
  isValidObjectId,
5265
5752
  licenceCategoryMapping,
@@ -5267,7 +5754,7 @@ export {
5267
5754
  locationGeoSchema,
5268
5755
  locationsSchema,
5269
5756
  mapVendorLicenceToSubscriptionRewardType,
5270
- mongoose41 as mongoose,
5757
+ mongoose42 as mongoose,
5271
5758
  normalizeAffiliatePromoCodes,
5272
5759
  normalizePromoCode,
5273
5760
  notifyUsers,
@@ -5277,6 +5764,7 @@ export {
5277
5764
  processUserCompliance,
5278
5765
  processUserLicenseReminders,
5279
5766
  publishNotificationEvents,
5767
+ reconcileAssociateGrants,
5280
5768
  refundPolicySchema,
5281
5769
  relatedPostSchema,
5282
5770
  relationDatesSchema,