@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.
@@ -1,8 +1,8 @@
1
1
  import * as mongoose from 'mongoose';
2
2
  import * as _timardex_cluemart_shared from '@timardex/cluemart-shared';
3
- import { PromoCodeType, EnumAffiliateRewardType, EnumPointType, UserOverallPointsEntry, DateTimeType, EventListItemType, DateTimeWithPriceType, EnumUserLicence as EnumUserLicence$1, UserLicenceType, EnumNotificationResourceType, EnumNotificationType, EnumResourceType, LicenceExpiryDate } from '@timardex/cluemart-shared';
3
+ import { PromoCodeType, EnumAffiliateRewardType, EnumResourceType, EnumUserRole, EnumPointType, UserOverallPointsEntry, DateTimeType, EventListItemType, DateTimeWithPriceType, EnumUserLicence as EnumUserLicence$1, UserLicenceType, EnumNotificationResourceType, EnumNotificationType, LicenceExpiryDate } from '@timardex/cluemart-shared';
4
4
  export { updateSingleDateTimeStatus } from '@timardex/cluemart-shared';
5
- import { d as SchemaAffiliateResourceType, S as SchemaOwnerType, g as SchemaRelationType, j as SchemaUserType } from '../Affiliate-CpoM9_Bb.mjs';
5
+ import { f as SchemaAffiliateResourceType, a as SchemaOwnerType, S as SchemaAssociateType, i as SchemaRelationType, m as SchemaUserType } from '../Affiliate-Bilg9mgw.mjs';
6
6
  import { O as ObjectId, G as GraphQLContext, e as SchemaCreateBulkNotificationInput } from '../index-BptxBl9x.mjs';
7
7
  import { DateTimeType as DateTimeType$1 } from '@timardex/cluemart-shared/types';
8
8
  import { EnumUserLicence } from '@timardex/cluemart-shared/enums';
@@ -99,6 +99,152 @@ declare function getSubscriptionRewardPeriodBounds(now?: Date): {
99
99
  periodStart: Date;
100
100
  };
101
101
 
102
+ /**
103
+ * Access-grant bookkeeping shared by `cluemart-server` (the mutations) and
104
+ * `cluemart-server-cron` (the reconciliation job).
105
+ *
106
+ * `User.associatedResources` and the `ASSOCIATED_*` role are a cache derived
107
+ * from the resource's `associates` array, which is the source of truth. The
108
+ * helpers here apply that rule in one direction only: anything the resource no
109
+ * longer lists as ACCEPTED is detached from the user. Because they read the
110
+ * stored state instead of a caller's before/after snapshot, they can be retried
111
+ * and they double as the periodic repair.
112
+ */
113
+ type AssociableResourceType = EnumResourceType.EVENT | EnumResourceType.PARTNER | EnumResourceType.VENDOR;
114
+ declare function isAssociableResourceType(resourceType: EnumResourceType): resourceType is AssociableResourceType;
115
+ /**
116
+ * The grant-relevant fields of an associable resource: where the user caches the
117
+ * grant, and the role that cache implies.
118
+ *
119
+ * Deliberately free of models and notification enums so this package stays the
120
+ * single source of truth for the mapping without owning either. `cluemart-server`
121
+ * builds its richer `getResourceMeta` on top of it.
122
+ */
123
+ declare function getAssociateAccessMeta(resourceType: AssociableResourceType): {
124
+ associatedField: "events";
125
+ associatedPath: string;
126
+ associateRole: EnumUserRole;
127
+ } | {
128
+ associatedField: "partners";
129
+ associatedPath: string;
130
+ associateRole: EnumUserRole;
131
+ } | {
132
+ associatedField: "vendors";
133
+ associatedPath: string;
134
+ associateRole: EnumUserRole;
135
+ };
136
+ /** The users a resource currently grants associate access to. */
137
+ declare function acceptedAssociateUserIds(associates?: SchemaAssociateType[] | null): ObjectId[];
138
+ /**
139
+ * Removes a resource from the given users' `associatedResources` and revokes
140
+ * their `ASSOCIATED_EVENT` / `ASSOCIATED_VENDOR` role if they have no remaining
141
+ * associated resources of that type.
142
+ *
143
+ * Both changes are applied in **one** document update (an aggregation pipeline,
144
+ * the same technique `syncUserLicencesAfterExpiry` uses). Detaching and revoking
145
+ * in separate updates leaves a window in which a concurrent accept adds another
146
+ * resource of the same type: the revocation then re-checks the emptied path and
147
+ * strips the role the user has just earned. With a single update the membership
148
+ * change and the `$size` check are atomic per user — a concurrent addition either
149
+ * lands before this write (the `$size` check sees it and the role stays) or after
150
+ * it (`$addToSet` re-adds the role).
151
+ */
152
+ declare function detachUsersFromResource({ resourceId, resourceType, userIds, }: {
153
+ resourceId: ObjectId | string;
154
+ resourceType: AssociableResourceType;
155
+ userIds: ObjectId[];
156
+ }): Promise<void>;
157
+ /**
158
+ * The single "grant" write: the resource id on `associatedResources` plus the
159
+ * associate role, for one or many users.
160
+ *
161
+ * Accept, the accept repair and the detach compensation
162
+ * (`detachUnlessStillAccepted`) all go through this one definition, so the three
163
+ * cannot drift apart. `$addToSet` makes every caller idempotent — which is what
164
+ * lets a retried accept and a restored grant both be safe.
165
+ *
166
+ * The role is **derived** from the accepted association: this write restores the
167
+ * invariant "holds an accepted association ⇒ holds the role". A role removed
168
+ * out-of-band while the resource still accepts the user is therefore re-added;
169
+ * that state is unreachable through the API, which always removes the
170
+ * association and the role together.
171
+ *
172
+ * **Revalidated against the resource first.** The grant is a write on a
173
+ * different document than the acceptance, so a revoke that landed after the
174
+ * caller's read has already finished its own detach — its candidate query could
175
+ * not see a grant that did not exist yet — and an unconditioned `$addToSet`
176
+ * would hand that access back for a resource that no longer accepts the user (or
177
+ * no longer exists). Only users the resource accepts *right now* are granted, so
178
+ * the cache can never be extended past a revocation the caller could not see.
179
+ * The read/write gap that remains is closed by the caller's post-grant
180
+ * verification (`withdrawGrantUnlessStillAccepted` in `cluemart-server`) and, for
181
+ * a request that dies inside it, by the reconciliation sweep.
182
+ */
183
+ declare function grantAssociateGrants({ resourceId, resourceType, userIds, }: {
184
+ resourceId: ObjectId | string;
185
+ resourceType: AssociableResourceType;
186
+ userIds: Array<ObjectId | string>;
187
+ }): Promise<void>;
188
+ /**
189
+ * Detaches every user whose `associatedResources` still points at `resourceId`
190
+ * but who the resource no longer lists as `ACCEPTED` — and returns the ids it
191
+ * detached.
192
+ *
193
+ * This is the **state-derived** half of a removal, deliberately not a diff of
194
+ * the caller's `prevAssociates` / `nextAssociates` snapshot. The resource is
195
+ * persisted before these side effects run, so a diff computed on retry reads
196
+ * the new list and reports no removal: a detach that failed once would never be
197
+ * retried, leaving the stale grant on the user forever. Reading the user side
198
+ * instead makes the call idempotent and convergent — the same call repairs a
199
+ * removal whose side effect was lost, whether it comes from a retry, the next
200
+ * edit of the resource, or the cron reconciliation job.
201
+ */
202
+ declare function detachStaleAssociateGrants({ acceptedUserIds, resourceId, resourceType, }: {
203
+ /** Users the resource currently lists as `ACCEPTED`. */
204
+ acceptedUserIds: ObjectId[] | string[];
205
+ resourceId: ObjectId | string;
206
+ resourceType: AssociableResourceType;
207
+ }): Promise<ObjectId[]>;
208
+ type DetachedAssociateGrants = {
209
+ detachedUserIds: ObjectId[];
210
+ resourceId: ObjectId | string;
211
+ resourceType: AssociableResourceType;
212
+ };
213
+ /**
214
+ * Detaches every grant held for a set of resources that are being destroyed, in
215
+ * one query per resource type instead of one per resource.
216
+ *
217
+ * Used by account deletion, where a user can own hundreds of events: asking
218
+ * `detachStaleAssociateGrants` per resource would issue one `User` read per
219
+ * resource. The candidate read is the only part that can be shared — the detach
220
+ * itself is per resource because the atomic pipeline removes a single id, and
221
+ * the role that follows is per user.
222
+ *
223
+ * There is intentionally **no** verification/restore here: every resource in
224
+ * `resources` is being hard-deleted, so "still accepted" is never true, and a
225
+ * restore would hand back a grant for a document that no longer exists. Callers
226
+ * must run the deletes before this call (see `deleteUser`), which also keeps the
227
+ * concurrent-accept verification honest.
228
+ *
229
+ * The result is aligned with `resources`, so a caller can report the removals
230
+ * per resource.
231
+ */
232
+ declare function detachAssociateGrantsForResources({ resources, }: {
233
+ resources: Array<{
234
+ resourceId: ObjectId | string;
235
+ resourceType: AssociableResourceType;
236
+ }>;
237
+ }): Promise<DetachedAssociateGrants[]>;
238
+ type ReconcileAssociateGrantsResult = {
239
+ /** Grants removed because the resource no longer lists them as accepted. */
240
+ detachedGrants: number;
241
+ /** User documents visited (each may hold resources of all three types). */
242
+ scannedUsers: number;
243
+ };
244
+ declare function reconcileAssociateGrants({ batchSize, }?: {
245
+ batchSize?: number;
246
+ }): Promise<ReconcileAssociateGrantsResult>;
247
+
102
248
  /**
103
249
  * Connect to MongoDB using Mongoose.
104
250
  * Supports both local MongoDB (via MONGODB_URI) and MongoDB Atlas (via individual env vars).
@@ -602,6 +748,8 @@ declare const licenceCategoryMapping: Record<EnumUserLicence$1, LicenceCategory>
602
748
  declare const licencePriority: Record<EnumUserLicence$1, number>;
603
749
  declare const standardLicences: readonly [EnumUserLicence$1.STANDARD_VENDOR, EnumUserLicence$1.STANDARD_EVENT, EnumUserLicence$1.STANDARD_PARTNER];
604
750
  declare function isStandardLicence(licence: EnumUserLicence$1): licence is (typeof standardLicences)[number];
751
+ declare const proLicences: readonly [EnumUserLicence$1.PRO_EVENT, EnumUserLicence$1.PRO_PLUS_EVENT, EnumUserLicence$1.PRO_VENDOR, EnumUserLicence$1.PRO_PLUS_VENDOR];
752
+ declare function isProLicence(licence: EnumUserLicence$1): licence is (typeof proLicences)[number];
605
753
  type LicenceUpgradeArgs = {
606
754
  expiryDate: LicenceExpiryDate;
607
755
  licenceType: EnumUserLicence$1;
@@ -633,5 +781,54 @@ declare function checkOwnerHasLicence({ userId, resourceType, }: {
633
781
  userId: ObjectId;
634
782
  resourceType: EnumResourceType;
635
783
  }): Promise<void>;
784
+ /**
785
+ * True while the owner's Stripe subscription still pays for `licenceType`: an
786
+ * active subscription that has not ended, or the matched post-deletion payment
787
+ * grace period. Licence *compliance* keeps a lapsed licence alive on this basis;
788
+ * access checks never do (see {@link ActiveLicenceOptions}).
789
+ */
790
+ declare function isProtectedByCurrentStripeSubscription(user: SchemaUserType, licenceType: EnumUserLicence$1, now: Dayjs): boolean;
791
+ type ActiveLicenceOptions = {
792
+ /**
793
+ * Also count a lapsed licence that the owner's Stripe subscription still pays
794
+ * for. Licence compliance keeps such a licence alive until Stripe ends it;
795
+ * access checks must not, or a downgraded owner would keep their associates.
796
+ */
797
+ includeStripeProtected?: boolean;
798
+ now?: Date;
799
+ };
800
+ /**
801
+ * Returns the owner's highest non-expired licence for an Event, Partner, or
802
+ * Vendor, or `null` if the user has no active licence for that category.
803
+ */
804
+ declare function getActiveLicenceForResource({ includeStripeProtected, userId, resourceType, now, }: {
805
+ includeStripeProtected?: boolean;
806
+ userId: ObjectId;
807
+ resourceType: EnumResourceType;
808
+ now?: Date;
809
+ }): Promise<EnumUserLicence$1 | null>;
810
+ /**
811
+ * Batch sibling of {@link hasActiveProLicenceForResource}: resolves, in a single
812
+ * user query, which of the given owners still hold an active PRO / PRO_PLUS
813
+ * licence for `resourceType`.
814
+ *
815
+ * List queries that include resources a user only *associates* on use this so a
816
+ * downgraded owner revokes associate access everywhere at once — exactly as the
817
+ * per-resource authorization check does — without an owner lookup per row.
818
+ * Returns the matching owner ids in their string form.
819
+ */
820
+ declare function getUserIdsWithActiveProLicence({ includeStripeProtected, resourceType, userIds, now, }: ActiveLicenceOptions & {
821
+ resourceType: EnumResourceType;
822
+ userIds: ObjectId[];
823
+ }): Promise<Set<string>>;
824
+ /**
825
+ * True when the resource owner holds an active, non-expired PRO or PRO_PLUS
826
+ * licence for the given resource type. Naturally false for Partner because
827
+ * Partner only has STANDARD_PARTNER.
828
+ */
829
+ declare function hasActiveProLicenceForResource({ includeStripeProtected, userId, resourceType, now, }: ActiveLicenceOptions & {
830
+ userId: ObjectId;
831
+ resourceType: EnumResourceType;
832
+ }): Promise<boolean>;
636
833
 
637
- export { ACTIVE_NOT_DELETED_FILTER, type AwardAffiliateVendorSubscriptionRewardsResult, type IndexBuildFailure, type IndexableModel, LicenceCategory, type NotificationPubSub, REMINDER_WINDOW_MAX_HOURS, REMINDER_WINDOW_MIN_HOURS, SUBSCRIPTION_REWARD_TIMEZONE, activeAffiliateCodeExists, awardAffiliateVendorSubscriptionRewards, buildLicenceExpiryPipeline, buildUserHasEnoughPointsFilter, buildUserPointAwardEntry, buildUserPointCreditFilter, buildUserPointDebitPipeline, buildUserPointEntryRemovalPipeline, checkOwnerHasLicence, connectToDatabase, convertObjectIdsToStrings, createLicenceObject, dedupeArchivedSlotsByStartDateTime, didRemoveAnyEventDates, didRemoveAnyStartedDates, downgradeVendorProFeatures, ensureDatabaseIndexes, ensureUserLicenseCompliance, ensureUserLicenseComplianceForUser, eventLicences, findAffiliateByPromoCode, findEventOrImportedMarketById, getEventResourceInfo, getHighestLicenceForCategory, getLicenceCategory, getLicenceExpiryMode, getPartnerResourceInfo, getPayingEventStripeSubscriptionPlan, getPayingStripeSubscriptionPlan, getPayingVendorStripeSubscriptionPlan, getSubscriptionRewardPeriodBounds, getVendorResourceInfo, handleEventLicenceCompliance, handlePartnerLicenceCompliance, handleVendorLicenceCompliance, hasValidLicence, isStandardLicence, isValidObjectId, licenceCategoryMapping, licencePriority, mapVendorLicenceToSubscriptionRewardType, normalizeAffiliatePromoCodes, normalizePromoCode, notifyUsers, partnerLicences, persistArchivedEventDates, processLicenseReminder, processUserCompliance, processUserLicenseReminders, publishNotificationEvents, remindUsersAboutLicenseExpiration, replaceUserLicenceWithObject, restoreVendorProFeatures, saveNotificationsInDb, sendDeactivationNotification, sendLicenseReminder, sendPushNotifications, sendReminderSafely, splitEventDatesForArchive, syncUserLicencesAfterExpiry, updateAdStatuses, updateAllEventDateTimeStatuses, updateRelationDatesToCanceled, upgradeUserToLicence, vendorOwnerHasProLicence };
834
+ export { ACTIVE_NOT_DELETED_FILTER, type ActiveLicenceOptions, type AssociableResourceType, type AwardAffiliateVendorSubscriptionRewardsResult, type DetachedAssociateGrants, type IndexBuildFailure, type IndexableModel, LicenceCategory, type NotificationPubSub, REMINDER_WINDOW_MAX_HOURS, REMINDER_WINDOW_MIN_HOURS, type ReconcileAssociateGrantsResult, SUBSCRIPTION_REWARD_TIMEZONE, acceptedAssociateUserIds, activeAffiliateCodeExists, awardAffiliateVendorSubscriptionRewards, buildLicenceExpiryPipeline, buildUserHasEnoughPointsFilter, buildUserPointAwardEntry, buildUserPointCreditFilter, buildUserPointDebitPipeline, buildUserPointEntryRemovalPipeline, checkOwnerHasLicence, connectToDatabase, convertObjectIdsToStrings, createLicenceObject, dedupeArchivedSlotsByStartDateTime, detachAssociateGrantsForResources, detachStaleAssociateGrants, detachUsersFromResource, didRemoveAnyEventDates, didRemoveAnyStartedDates, downgradeVendorProFeatures, ensureDatabaseIndexes, ensureUserLicenseCompliance, ensureUserLicenseComplianceForUser, eventLicences, findAffiliateByPromoCode, findEventOrImportedMarketById, getActiveLicenceForResource, getAssociateAccessMeta, getEventResourceInfo, getHighestLicenceForCategory, getLicenceCategory, getLicenceExpiryMode, getPartnerResourceInfo, getPayingEventStripeSubscriptionPlan, getPayingStripeSubscriptionPlan, getPayingVendorStripeSubscriptionPlan, getSubscriptionRewardPeriodBounds, getUserIdsWithActiveProLicence, getVendorResourceInfo, grantAssociateGrants, handleEventLicenceCompliance, handlePartnerLicenceCompliance, handleVendorLicenceCompliance, hasActiveProLicenceForResource, hasValidLicence, isAssociableResourceType, isProLicence, isProtectedByCurrentStripeSubscription, isStandardLicence, isValidObjectId, licenceCategoryMapping, licencePriority, mapVendorLicenceToSubscriptionRewardType, normalizeAffiliatePromoCodes, normalizePromoCode, notifyUsers, partnerLicences, persistArchivedEventDates, processLicenseReminder, processUserCompliance, processUserLicenseReminders, publishNotificationEvents, reconcileAssociateGrants, remindUsersAboutLicenseExpiration, replaceUserLicenceWithObject, restoreVendorProFeatures, saveNotificationsInDb, sendDeactivationNotification, sendLicenseReminder, sendPushNotifications, sendReminderSafely, splitEventDatesForArchive, syncUserLicencesAfterExpiry, updateAdStatuses, updateAllEventDateTimeStatuses, updateRelationDatesToCanceled, upgradeUserToLicence, vendorOwnerHasProLicence };
@@ -1,8 +1,8 @@
1
1
  import * as mongoose from 'mongoose';
2
2
  import * as _timardex_cluemart_shared from '@timardex/cluemart-shared';
3
- import { PromoCodeType, EnumAffiliateRewardType, EnumPointType, UserOverallPointsEntry, DateTimeType, EventListItemType, DateTimeWithPriceType, EnumUserLicence as EnumUserLicence$1, UserLicenceType, EnumNotificationResourceType, EnumNotificationType, EnumResourceType, LicenceExpiryDate } from '@timardex/cluemart-shared';
3
+ import { PromoCodeType, EnumAffiliateRewardType, EnumResourceType, EnumUserRole, EnumPointType, UserOverallPointsEntry, DateTimeType, EventListItemType, DateTimeWithPriceType, EnumUserLicence as EnumUserLicence$1, UserLicenceType, EnumNotificationResourceType, EnumNotificationType, LicenceExpiryDate } from '@timardex/cluemart-shared';
4
4
  export { updateSingleDateTimeStatus } from '@timardex/cluemart-shared';
5
- import { d as SchemaAffiliateResourceType, S as SchemaOwnerType, g as SchemaRelationType, j as SchemaUserType } from '../Affiliate-YoKkDGxN.js';
5
+ import { f as SchemaAffiliateResourceType, a as SchemaOwnerType, S as SchemaAssociateType, i as SchemaRelationType, m as SchemaUserType } from '../Affiliate-CfG8ctIo.js';
6
6
  import { O as ObjectId, G as GraphQLContext, e as SchemaCreateBulkNotificationInput } from '../index-BptxBl9x.js';
7
7
  import { DateTimeType as DateTimeType$1 } from '@timardex/cluemart-shared/types';
8
8
  import { EnumUserLicence } from '@timardex/cluemart-shared/enums';
@@ -99,6 +99,152 @@ declare function getSubscriptionRewardPeriodBounds(now?: Date): {
99
99
  periodStart: Date;
100
100
  };
101
101
 
102
+ /**
103
+ * Access-grant bookkeeping shared by `cluemart-server` (the mutations) and
104
+ * `cluemart-server-cron` (the reconciliation job).
105
+ *
106
+ * `User.associatedResources` and the `ASSOCIATED_*` role are a cache derived
107
+ * from the resource's `associates` array, which is the source of truth. The
108
+ * helpers here apply that rule in one direction only: anything the resource no
109
+ * longer lists as ACCEPTED is detached from the user. Because they read the
110
+ * stored state instead of a caller's before/after snapshot, they can be retried
111
+ * and they double as the periodic repair.
112
+ */
113
+ type AssociableResourceType = EnumResourceType.EVENT | EnumResourceType.PARTNER | EnumResourceType.VENDOR;
114
+ declare function isAssociableResourceType(resourceType: EnumResourceType): resourceType is AssociableResourceType;
115
+ /**
116
+ * The grant-relevant fields of an associable resource: where the user caches the
117
+ * grant, and the role that cache implies.
118
+ *
119
+ * Deliberately free of models and notification enums so this package stays the
120
+ * single source of truth for the mapping without owning either. `cluemart-server`
121
+ * builds its richer `getResourceMeta` on top of it.
122
+ */
123
+ declare function getAssociateAccessMeta(resourceType: AssociableResourceType): {
124
+ associatedField: "events";
125
+ associatedPath: string;
126
+ associateRole: EnumUserRole;
127
+ } | {
128
+ associatedField: "partners";
129
+ associatedPath: string;
130
+ associateRole: EnumUserRole;
131
+ } | {
132
+ associatedField: "vendors";
133
+ associatedPath: string;
134
+ associateRole: EnumUserRole;
135
+ };
136
+ /** The users a resource currently grants associate access to. */
137
+ declare function acceptedAssociateUserIds(associates?: SchemaAssociateType[] | null): ObjectId[];
138
+ /**
139
+ * Removes a resource from the given users' `associatedResources` and revokes
140
+ * their `ASSOCIATED_EVENT` / `ASSOCIATED_VENDOR` role if they have no remaining
141
+ * associated resources of that type.
142
+ *
143
+ * Both changes are applied in **one** document update (an aggregation pipeline,
144
+ * the same technique `syncUserLicencesAfterExpiry` uses). Detaching and revoking
145
+ * in separate updates leaves a window in which a concurrent accept adds another
146
+ * resource of the same type: the revocation then re-checks the emptied path and
147
+ * strips the role the user has just earned. With a single update the membership
148
+ * change and the `$size` check are atomic per user — a concurrent addition either
149
+ * lands before this write (the `$size` check sees it and the role stays) or after
150
+ * it (`$addToSet` re-adds the role).
151
+ */
152
+ declare function detachUsersFromResource({ resourceId, resourceType, userIds, }: {
153
+ resourceId: ObjectId | string;
154
+ resourceType: AssociableResourceType;
155
+ userIds: ObjectId[];
156
+ }): Promise<void>;
157
+ /**
158
+ * The single "grant" write: the resource id on `associatedResources` plus the
159
+ * associate role, for one or many users.
160
+ *
161
+ * Accept, the accept repair and the detach compensation
162
+ * (`detachUnlessStillAccepted`) all go through this one definition, so the three
163
+ * cannot drift apart. `$addToSet` makes every caller idempotent — which is what
164
+ * lets a retried accept and a restored grant both be safe.
165
+ *
166
+ * The role is **derived** from the accepted association: this write restores the
167
+ * invariant "holds an accepted association ⇒ holds the role". A role removed
168
+ * out-of-band while the resource still accepts the user is therefore re-added;
169
+ * that state is unreachable through the API, which always removes the
170
+ * association and the role together.
171
+ *
172
+ * **Revalidated against the resource first.** The grant is a write on a
173
+ * different document than the acceptance, so a revoke that landed after the
174
+ * caller's read has already finished its own detach — its candidate query could
175
+ * not see a grant that did not exist yet — and an unconditioned `$addToSet`
176
+ * would hand that access back for a resource that no longer accepts the user (or
177
+ * no longer exists). Only users the resource accepts *right now* are granted, so
178
+ * the cache can never be extended past a revocation the caller could not see.
179
+ * The read/write gap that remains is closed by the caller's post-grant
180
+ * verification (`withdrawGrantUnlessStillAccepted` in `cluemart-server`) and, for
181
+ * a request that dies inside it, by the reconciliation sweep.
182
+ */
183
+ declare function grantAssociateGrants({ resourceId, resourceType, userIds, }: {
184
+ resourceId: ObjectId | string;
185
+ resourceType: AssociableResourceType;
186
+ userIds: Array<ObjectId | string>;
187
+ }): Promise<void>;
188
+ /**
189
+ * Detaches every user whose `associatedResources` still points at `resourceId`
190
+ * but who the resource no longer lists as `ACCEPTED` — and returns the ids it
191
+ * detached.
192
+ *
193
+ * This is the **state-derived** half of a removal, deliberately not a diff of
194
+ * the caller's `prevAssociates` / `nextAssociates` snapshot. The resource is
195
+ * persisted before these side effects run, so a diff computed on retry reads
196
+ * the new list and reports no removal: a detach that failed once would never be
197
+ * retried, leaving the stale grant on the user forever. Reading the user side
198
+ * instead makes the call idempotent and convergent — the same call repairs a
199
+ * removal whose side effect was lost, whether it comes from a retry, the next
200
+ * edit of the resource, or the cron reconciliation job.
201
+ */
202
+ declare function detachStaleAssociateGrants({ acceptedUserIds, resourceId, resourceType, }: {
203
+ /** Users the resource currently lists as `ACCEPTED`. */
204
+ acceptedUserIds: ObjectId[] | string[];
205
+ resourceId: ObjectId | string;
206
+ resourceType: AssociableResourceType;
207
+ }): Promise<ObjectId[]>;
208
+ type DetachedAssociateGrants = {
209
+ detachedUserIds: ObjectId[];
210
+ resourceId: ObjectId | string;
211
+ resourceType: AssociableResourceType;
212
+ };
213
+ /**
214
+ * Detaches every grant held for a set of resources that are being destroyed, in
215
+ * one query per resource type instead of one per resource.
216
+ *
217
+ * Used by account deletion, where a user can own hundreds of events: asking
218
+ * `detachStaleAssociateGrants` per resource would issue one `User` read per
219
+ * resource. The candidate read is the only part that can be shared — the detach
220
+ * itself is per resource because the atomic pipeline removes a single id, and
221
+ * the role that follows is per user.
222
+ *
223
+ * There is intentionally **no** verification/restore here: every resource in
224
+ * `resources` is being hard-deleted, so "still accepted" is never true, and a
225
+ * restore would hand back a grant for a document that no longer exists. Callers
226
+ * must run the deletes before this call (see `deleteUser`), which also keeps the
227
+ * concurrent-accept verification honest.
228
+ *
229
+ * The result is aligned with `resources`, so a caller can report the removals
230
+ * per resource.
231
+ */
232
+ declare function detachAssociateGrantsForResources({ resources, }: {
233
+ resources: Array<{
234
+ resourceId: ObjectId | string;
235
+ resourceType: AssociableResourceType;
236
+ }>;
237
+ }): Promise<DetachedAssociateGrants[]>;
238
+ type ReconcileAssociateGrantsResult = {
239
+ /** Grants removed because the resource no longer lists them as accepted. */
240
+ detachedGrants: number;
241
+ /** User documents visited (each may hold resources of all three types). */
242
+ scannedUsers: number;
243
+ };
244
+ declare function reconcileAssociateGrants({ batchSize, }?: {
245
+ batchSize?: number;
246
+ }): Promise<ReconcileAssociateGrantsResult>;
247
+
102
248
  /**
103
249
  * Connect to MongoDB using Mongoose.
104
250
  * Supports both local MongoDB (via MONGODB_URI) and MongoDB Atlas (via individual env vars).
@@ -602,6 +748,8 @@ declare const licenceCategoryMapping: Record<EnumUserLicence$1, LicenceCategory>
602
748
  declare const licencePriority: Record<EnumUserLicence$1, number>;
603
749
  declare const standardLicences: readonly [EnumUserLicence$1.STANDARD_VENDOR, EnumUserLicence$1.STANDARD_EVENT, EnumUserLicence$1.STANDARD_PARTNER];
604
750
  declare function isStandardLicence(licence: EnumUserLicence$1): licence is (typeof standardLicences)[number];
751
+ declare const proLicences: readonly [EnumUserLicence$1.PRO_EVENT, EnumUserLicence$1.PRO_PLUS_EVENT, EnumUserLicence$1.PRO_VENDOR, EnumUserLicence$1.PRO_PLUS_VENDOR];
752
+ declare function isProLicence(licence: EnumUserLicence$1): licence is (typeof proLicences)[number];
605
753
  type LicenceUpgradeArgs = {
606
754
  expiryDate: LicenceExpiryDate;
607
755
  licenceType: EnumUserLicence$1;
@@ -633,5 +781,54 @@ declare function checkOwnerHasLicence({ userId, resourceType, }: {
633
781
  userId: ObjectId;
634
782
  resourceType: EnumResourceType;
635
783
  }): Promise<void>;
784
+ /**
785
+ * True while the owner's Stripe subscription still pays for `licenceType`: an
786
+ * active subscription that has not ended, or the matched post-deletion payment
787
+ * grace period. Licence *compliance* keeps a lapsed licence alive on this basis;
788
+ * access checks never do (see {@link ActiveLicenceOptions}).
789
+ */
790
+ declare function isProtectedByCurrentStripeSubscription(user: SchemaUserType, licenceType: EnumUserLicence$1, now: Dayjs): boolean;
791
+ type ActiveLicenceOptions = {
792
+ /**
793
+ * Also count a lapsed licence that the owner's Stripe subscription still pays
794
+ * for. Licence compliance keeps such a licence alive until Stripe ends it;
795
+ * access checks must not, or a downgraded owner would keep their associates.
796
+ */
797
+ includeStripeProtected?: boolean;
798
+ now?: Date;
799
+ };
800
+ /**
801
+ * Returns the owner's highest non-expired licence for an Event, Partner, or
802
+ * Vendor, or `null` if the user has no active licence for that category.
803
+ */
804
+ declare function getActiveLicenceForResource({ includeStripeProtected, userId, resourceType, now, }: {
805
+ includeStripeProtected?: boolean;
806
+ userId: ObjectId;
807
+ resourceType: EnumResourceType;
808
+ now?: Date;
809
+ }): Promise<EnumUserLicence$1 | null>;
810
+ /**
811
+ * Batch sibling of {@link hasActiveProLicenceForResource}: resolves, in a single
812
+ * user query, which of the given owners still hold an active PRO / PRO_PLUS
813
+ * licence for `resourceType`.
814
+ *
815
+ * List queries that include resources a user only *associates* on use this so a
816
+ * downgraded owner revokes associate access everywhere at once — exactly as the
817
+ * per-resource authorization check does — without an owner lookup per row.
818
+ * Returns the matching owner ids in their string form.
819
+ */
820
+ declare function getUserIdsWithActiveProLicence({ includeStripeProtected, resourceType, userIds, now, }: ActiveLicenceOptions & {
821
+ resourceType: EnumResourceType;
822
+ userIds: ObjectId[];
823
+ }): Promise<Set<string>>;
824
+ /**
825
+ * True when the resource owner holds an active, non-expired PRO or PRO_PLUS
826
+ * licence for the given resource type. Naturally false for Partner because
827
+ * Partner only has STANDARD_PARTNER.
828
+ */
829
+ declare function hasActiveProLicenceForResource({ includeStripeProtected, userId, resourceType, now, }: ActiveLicenceOptions & {
830
+ userId: ObjectId;
831
+ resourceType: EnumResourceType;
832
+ }): Promise<boolean>;
636
833
 
637
- export { ACTIVE_NOT_DELETED_FILTER, type AwardAffiliateVendorSubscriptionRewardsResult, type IndexBuildFailure, type IndexableModel, LicenceCategory, type NotificationPubSub, REMINDER_WINDOW_MAX_HOURS, REMINDER_WINDOW_MIN_HOURS, SUBSCRIPTION_REWARD_TIMEZONE, activeAffiliateCodeExists, awardAffiliateVendorSubscriptionRewards, buildLicenceExpiryPipeline, buildUserHasEnoughPointsFilter, buildUserPointAwardEntry, buildUserPointCreditFilter, buildUserPointDebitPipeline, buildUserPointEntryRemovalPipeline, checkOwnerHasLicence, connectToDatabase, convertObjectIdsToStrings, createLicenceObject, dedupeArchivedSlotsByStartDateTime, didRemoveAnyEventDates, didRemoveAnyStartedDates, downgradeVendorProFeatures, ensureDatabaseIndexes, ensureUserLicenseCompliance, ensureUserLicenseComplianceForUser, eventLicences, findAffiliateByPromoCode, findEventOrImportedMarketById, getEventResourceInfo, getHighestLicenceForCategory, getLicenceCategory, getLicenceExpiryMode, getPartnerResourceInfo, getPayingEventStripeSubscriptionPlan, getPayingStripeSubscriptionPlan, getPayingVendorStripeSubscriptionPlan, getSubscriptionRewardPeriodBounds, getVendorResourceInfo, handleEventLicenceCompliance, handlePartnerLicenceCompliance, handleVendorLicenceCompliance, hasValidLicence, isStandardLicence, isValidObjectId, licenceCategoryMapping, licencePriority, mapVendorLicenceToSubscriptionRewardType, normalizeAffiliatePromoCodes, normalizePromoCode, notifyUsers, partnerLicences, persistArchivedEventDates, processLicenseReminder, processUserCompliance, processUserLicenseReminders, publishNotificationEvents, remindUsersAboutLicenseExpiration, replaceUserLicenceWithObject, restoreVendorProFeatures, saveNotificationsInDb, sendDeactivationNotification, sendLicenseReminder, sendPushNotifications, sendReminderSafely, splitEventDatesForArchive, syncUserLicencesAfterExpiry, updateAdStatuses, updateAllEventDateTimeStatuses, updateRelationDatesToCanceled, upgradeUserToLicence, vendorOwnerHasProLicence };
834
+ export { ACTIVE_NOT_DELETED_FILTER, type ActiveLicenceOptions, type AssociableResourceType, type AwardAffiliateVendorSubscriptionRewardsResult, type DetachedAssociateGrants, type IndexBuildFailure, type IndexableModel, LicenceCategory, type NotificationPubSub, REMINDER_WINDOW_MAX_HOURS, REMINDER_WINDOW_MIN_HOURS, type ReconcileAssociateGrantsResult, SUBSCRIPTION_REWARD_TIMEZONE, acceptedAssociateUserIds, activeAffiliateCodeExists, awardAffiliateVendorSubscriptionRewards, buildLicenceExpiryPipeline, buildUserHasEnoughPointsFilter, buildUserPointAwardEntry, buildUserPointCreditFilter, buildUserPointDebitPipeline, buildUserPointEntryRemovalPipeline, checkOwnerHasLicence, connectToDatabase, convertObjectIdsToStrings, createLicenceObject, dedupeArchivedSlotsByStartDateTime, detachAssociateGrantsForResources, detachStaleAssociateGrants, detachUsersFromResource, didRemoveAnyEventDates, didRemoveAnyStartedDates, downgradeVendorProFeatures, ensureDatabaseIndexes, ensureUserLicenseCompliance, ensureUserLicenseComplianceForUser, eventLicences, findAffiliateByPromoCode, findEventOrImportedMarketById, getActiveLicenceForResource, getAssociateAccessMeta, getEventResourceInfo, getHighestLicenceForCategory, getLicenceCategory, getLicenceExpiryMode, getPartnerResourceInfo, getPayingEventStripeSubscriptionPlan, getPayingStripeSubscriptionPlan, getPayingVendorStripeSubscriptionPlan, getSubscriptionRewardPeriodBounds, getUserIdsWithActiveProLicence, getVendorResourceInfo, grantAssociateGrants, handleEventLicenceCompliance, handlePartnerLicenceCompliance, handleVendorLicenceCompliance, hasActiveProLicenceForResource, hasValidLicence, isAssociableResourceType, isProLicence, isProtectedByCurrentStripeSubscription, isStandardLicence, isValidObjectId, licenceCategoryMapping, licencePriority, mapVendorLicenceToSubscriptionRewardType, normalizeAffiliatePromoCodes, normalizePromoCode, notifyUsers, partnerLicences, persistArchivedEventDates, processLicenseReminder, processUserCompliance, processUserLicenseReminders, publishNotificationEvents, reconcileAssociateGrants, remindUsersAboutLicenseExpiration, replaceUserLicenceWithObject, restoreVendorProFeatures, saveNotificationsInDb, sendDeactivationNotification, sendLicenseReminder, sendPushNotifications, sendReminderSafely, splitEventDatesForArchive, syncUserLicencesAfterExpiry, updateAdStatuses, updateAllEventDateTimeStatuses, updateRelationDatesToCanceled, upgradeUserToLicence, vendorOwnerHasProLicence };