@timardex/cluemart-server-shared 2.2.0 → 2.2.12

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 +1 @@
1
- {"version":3,"sources":["../../src/service/promoCode/constants.ts","../../src/service/affiliate/activeAffiliateCodeExists.ts","../../src/service/affiliate/awardAffiliateVendorSubscriptionRewards.ts","../../src/service/saveNotificationsInDb.ts","../../src/service/sendPushNotifications.ts","../../src/service/affiliate/vendorSubscriptionRewards.ts","../../src/service/license/stripe/stripe.ts","../../src/service/affiliate/findAffiliateByPromoCode.ts","../../src/service/promoCode/normalizePromoCode.ts","../../src/service/affiliate/normalizeAffiliatePromoCodes.ts","../../src/service/database.ts","../../src/service/notifyUsers.ts","../../src/service/updateAdStatus.ts","../../src/service/objectIdToString.ts","../../src/service/event/updateAllEventDateTimeStatuses.ts","../../src/service/event/archiveEndedEventDates.ts","../../src/service/event/findEventOrImportedMarketById.ts","../../src/service/relations.ts","../../src/service/license/compliance/ensureUserLicenseCompliance.ts","../../src/service/license/compliance/utils.ts","../../src/service/license/compliance/event.ts","../../src/service/license/compliance/licenceExpiryPipeline.ts","../../src/service/license/compliance/partner.ts","../../src/service/license/compliance/vendor.ts","../../src/service/license/models.ts","../../src/service/license/reminder/event.ts","../../src/service/license/reminder/partner.ts","../../src/service/license/reminder/remindUsersAboutLicenseExpiration.ts","../../src/service/license/reminder/reminderWindow.ts","../../src/service/license/reminder/utils.ts","../../src/service/license/reminder/vendor.ts"],"sourcesContent":["/** Matches partial unique indexes for promo/affiliate codes on active documents. */\nexport const ACTIVE_NOT_DELETED_FILTER = {\n active: true,\n deletedAt: null,\n} as const;\n","import { AffiliateModel } from \"src/mongoose\";\n\nimport { ACTIVE_NOT_DELETED_FILTER } from \"../promoCode/constants\";\n\n/**\n * Checks whether an affiliate code is already taken by an active, non-deleted affiliate.\n *\n * Used when generating new affiliate codes so collisions are avoided before insert.\n * Matches the partial unique index on `affiliateCode` for active documents.\n *\n * @param affiliateCode - Candidate affiliate promo code to check.\n * @returns `true` when an active, non-deleted affiliate already uses this code.\n */\nexport async function activeAffiliateCodeExists(\n affiliateCode: string,\n): Promise<boolean> {\n const existing = await AffiliateModel.exists({\n ...ACTIVE_NOT_DELETED_FILTER,\n affiliateCode,\n }).exec();\n\n return existing !== null;\n}\n","import {\n AffiliateResourceType,\n EnumAffiliateRewardType,\n EnumNotificationResourceType,\n EnumNotificationType,\n EnumResourceType,\n} from \"@timardex/cluemart-shared\";\nimport { createAffiliateReward } from \"@timardex/cluemart-shared/utils\";\n\nimport { AffiliateModel, SchemaOwnerType, VendorModel } from \"src/mongoose\";\nimport { ObjectId } from \"src/types\";\n\nimport { saveNotificationsInDb } from \"../saveNotificationsInDb\";\nimport { sendPushNotifications } from \"../sendPushNotifications\";\n\nimport {\n getSubscriptionRewardPeriodBounds,\n mapVendorLicenceToSubscriptionRewardType,\n} from \"./vendorSubscriptionRewards\";\n\nexport type AwardAffiliateVendorSubscriptionRewardsResult = {\n awarded: number;\n skipped: number;\n};\n\ntype LeanAffiliateResource = Omit<\n AffiliateResourceType,\n \"resourceId\" | \"resourceOwner\" | \"rewards\"\n> & {\n resourceId: ObjectId;\n resourceOwner: SchemaOwnerType;\n};\n\ntype LeanAffiliate = {\n _id: ObjectId;\n affiliateResources: LeanAffiliateResource[];\n owner: SchemaOwnerType;\n};\n\ntype PeriodBounds = {\n periodEnd: Date;\n periodStart: Date;\n};\n\ntype AwardSummary = {\n resourceName: string;\n rewardValue: number;\n};\n\nfunction isEligibleVendorResource(resource: LeanAffiliateResource): boolean {\n return (\n resource.resourceType === EnumResourceType.VENDOR &&\n resource.resourceActive === true &&\n resource.resourceDeletedAt == null\n );\n}\n\nasync function findAffiliatesWithActiveVendorReferrals(): Promise<\n LeanAffiliate[]\n> {\n return (await AffiliateModel.find({\n active: true,\n affiliateResources: {\n $elemMatch: {\n resourceActive: true,\n resourceDeletedAt: null,\n resourceType: EnumResourceType.VENDOR,\n },\n },\n deletedAt: null,\n })\n .select(\"_id affiliateResources owner\")\n .lean()\n .exec()) as LeanAffiliate[];\n}\n\nasync function isEligibleReferredVendor({\n resourceId,\n resourceOwnerUserId,\n}: {\n resourceId: ObjectId;\n resourceOwnerUserId: ObjectId | string;\n}): Promise<boolean> {\n const match = await VendorModel.exists({\n _id: resourceId,\n active: true,\n deletedAt: null,\n \"owner.userId\": resourceOwnerUserId,\n }).exec();\n\n return Boolean(match);\n}\n\nasync function notifyAffiliateOwnerOfSubscriptionReward({\n affiliateId,\n affiliateOwnerUserId,\n awards,\n}: {\n affiliateId: ObjectId | string;\n affiliateOwnerUserId: ObjectId | string;\n awards: AwardSummary[];\n}): Promise<void> {\n if (awards.length === 0) {\n return;\n }\n\n const totalPoints = awards.reduce((sum, award) => sum + award.rewardValue, 0);\n const resourceNames = awards.map((award) => award.resourceName);\n const pointLabel = totalPoints === 1 ? \"point\" : \"points\";\n const message =\n awards.length === 1\n ? `You earned ${totalPoints} ${pointLabel}! Your referred vendor \"${resourceNames[0]}\" has an active subscription.`\n : `You earned ${totalPoints} ${pointLabel}! ${awards.length} of your referred vendors have an active subscription.`;\n\n const payload = {\n data: {\n resourceId: String(affiliateId),\n resourceName: resourceNames.join(\", \"),\n resourceType: EnumNotificationResourceType.AFFILIATE_REWARD_RECEIVED,\n },\n message,\n title: \"Affiliate points earned\",\n type: EnumNotificationType.SYSTEM,\n userIds: [affiliateOwnerUserId as ObjectId],\n };\n\n try {\n await saveNotificationsInDb(payload);\n await sendPushNotifications(payload);\n } catch (error) {\n console.error(\n `[affiliate] subscription reward notification failed for affiliate ${String(affiliateId)}:`,\n error instanceof Error ? error.message : error,\n );\n }\n}\n\nasync function tryAwardSubscriptionReward({\n affiliate,\n createdAt,\n period,\n resource,\n rewardType,\n}: {\n affiliate: LeanAffiliate;\n createdAt: Date;\n period: PeriodBounds;\n resource: LeanAffiliateResource;\n rewardType: EnumAffiliateRewardType;\n}): Promise<AwardSummary | null> {\n const reward = createAffiliateReward(rewardType, createdAt);\n\n const updateResult = await AffiliateModel.updateOne(\n {\n _id: affiliate._id,\n affiliateResources: {\n $elemMatch: {\n resourceActive: true,\n resourceDeletedAt: null,\n resourceId: resource.resourceId,\n resourceType: EnumResourceType.VENDOR,\n rewards: {\n $not: {\n $elemMatch: {\n createdAt: {\n $gte: period.periodStart,\n $lt: period.periodEnd,\n },\n },\n },\n },\n },\n },\n deletedAt: null,\n },\n {\n $inc: { overallPoints: reward.rewardValue },\n $push: { \"affiliateResources.$.rewards\": reward },\n },\n ).exec();\n\n if (updateResult.modifiedCount === 0) {\n return null;\n }\n\n return {\n resourceName: resource.resourceName,\n rewardValue: reward.rewardValue,\n };\n}\n\nasync function processAffiliateVendorReferral({\n affiliate,\n createdAt,\n now,\n period,\n resource,\n}: {\n affiliate: LeanAffiliate;\n createdAt: Date;\n now: Date;\n period: PeriodBounds;\n resource: LeanAffiliateResource;\n}): Promise<AwardSummary | null> {\n const vendorEligible = await isEligibleReferredVendor({\n resourceId: resource.resourceId,\n resourceOwnerUserId: resource.resourceOwner.userId,\n });\n if (!vendorEligible) {\n return null;\n }\n\n const rewardType = await mapVendorLicenceToSubscriptionRewardType(\n resource.resourceOwner.userId,\n now,\n );\n if (!rewardType) {\n return null;\n }\n\n return tryAwardSubscriptionReward({\n affiliate,\n createdAt,\n period,\n resource,\n rewardType,\n });\n}\n\n/**\n * Awards monthly vendor subscription rewards to affiliates with active referred vendors.\n *\n * Eligibility per affiliate resource:\n * - Affiliate is active and not soft-deleted\n * - Linked `affiliateResources` entry is vendor, `resourceActive`, and not deleted\n * - Vendor is active, not deleted, and `owner.userId` matches\n * `affiliateResources.resourceOwner.userId`\n * - `affiliateResources.resourceOwner` has a non-expired Standard / Pro / Pro+ vendor licence\n *\n * Reward type follows the owner's highest valid licence + Stripe paying status:\n * - Pro / Pro+ with paying Stripe (ACTIVE) → `ACTIVE_VENDOR_PRO_SUBSCRIPTION` (3 pts)\n * - Pro / Pro+ without paying Stripe → `ACTIVE_VENDOR_STANDARD_SUBSCRIPTION` (1 pt)\n * - Standard → `ACTIVE_VENDOR_STANDARD_SUBSCRIPTION` (1 pt)\n *\n * Idempotent per affiliate + vendor + calendar month — a mid-month licence\n * upgrade (Standard → paying Pro) takes effect from the following month.\n * On successful awards, sends the affiliate owner a single aggregated\n * notification per run (best-effort).\n *\n * @param now - Reference time for month bounds and licence expiry (defaults to now).\n * @returns Counts of awarded and skipped candidates.\n */\nexport async function awardAffiliateVendorSubscriptionRewards(\n now: Date = new Date(),\n): Promise<AwardAffiliateVendorSubscriptionRewardsResult> {\n const period = getSubscriptionRewardPeriodBounds(now);\n const createdAt = now;\n const affiliates = await findAffiliatesWithActiveVendorReferrals();\n\n let awarded = 0;\n let skipped = 0;\n\n for (const affiliate of affiliates) {\n const awards: AwardSummary[] = [];\n const seenPairs = new Set<string>();\n\n for (const resource of affiliate.affiliateResources) {\n if (!isEligibleVendorResource(resource)) {\n continue;\n }\n\n const pairKey = `${String(affiliate._id)}:${String(resource.resourceId)}`;\n if (seenPairs.has(pairKey)) {\n continue;\n }\n seenPairs.add(pairKey);\n\n const award = await processAffiliateVendorReferral({\n affiliate,\n createdAt,\n now,\n period,\n resource,\n });\n\n if (award) {\n awarded += 1;\n awards.push(award);\n } else {\n skipped += 1;\n }\n }\n\n if (awards.length > 0) {\n await notifyAffiliateOwnerOfSubscriptionReward({\n affiliateId: affiliate._id,\n affiliateOwnerUserId: affiliate.owner.userId,\n awards,\n });\n }\n }\n\n return { awarded, skipped };\n}\n","import {\n SchemaCreateBulkNotificationInput,\n NotificationModel,\n} from \"src/mongoose/Notification\";\nimport { ObjectId } from \"src/types\";\n\n/**\n * Create notifications in the database for multiple users\n * This is typically called when sending push notifications\n */\nexport async function saveNotificationsInDb(\n payload: SchemaCreateBulkNotificationInput,\n): Promise<ObjectId[]> {\n const { data, message, title, type, userIds } = payload;\n console.log('NOTIFICATION DATA', JSON.stringify(payload, null, 2));\n try {\n const notifications = userIds.map((userId) => ({\n data,\n isRead: false,\n message,\n title,\n type,\n userId,\n }));\n\n // Save notifications to database\n await NotificationModel.insertMany(notifications);\n console.log(\n `Created ${notifications.length} notifications for ${userIds.length} users`,\n );\n\n return [...new Set(userIds)];\n } catch (error) {\n console.error(\"Failed to create notifications:\", error);\n return [];\n //throw new Error(`Failed to create notifications: ${error}`);\n }\n}\n","import { NotificationDataType } from \"@timardex/cluemart-shared\";\nimport { Expo, ExpoPushMessage, ExpoPushTicket } from \"expo-server-sdk\";\n\nimport { SchemaCreateBulkNotificationInput } from \"src/mongoose/Notification\";\nimport { PushTokenModel } from \"src/mongoose/PushToken\";\n\nconst expo = new Expo();\n\n/**\n * Safely extract tokens from ExpoPushMessage handling both string and array cases\n */\nfunction extractTokensFromMessage(message: ExpoPushMessage): string[] {\n return Array.isArray(message.to) ? message.to : [message.to];\n}\n\ninterface CreatePushMessagesOptions {\n tokens: string[];\n message: string;\n title: string;\n data: NotificationDataType;\n}\n\n/**\n * Create push messages from valid tokens\n */\nfunction createPushMessages({\n tokens,\n message,\n title,\n data,\n}: CreatePushMessagesOptions): {\n messages: ExpoPushMessage[];\n invalidTokens: string[];\n} {\n const messages: ExpoPushMessage[] = [];\n const invalidTokens: string[] = [];\n\n for (const token of tokens) {\n if (!Expo.isExpoPushToken(token)) {\n invalidTokens.push(token);\n continue;\n }\n\n messages.push({\n body: message,\n data: { ...data },\n sound: \"tui.wav\",\n title,\n to: token,\n });\n }\n\n return { invalidTokens, messages };\n}\n\n/**\n * Process chunk results and extract failed tokens\n */\nfunction processChunkResults(\n tickets: ExpoPushTicket[],\n chunk: ExpoPushMessage[],\n): { successCount: number; failedTokens: string[] } {\n let successCount = 0;\n const failedTokens: string[] = [];\n\n for (const [ticketIndex, ticket] of tickets.entries()) {\n if (ticket.status === \"error\") {\n const message = chunk[ticketIndex];\n if (message) {\n const tokens = extractTokensFromMessage(message);\n if (ticket.details?.error === \"DeviceNotRegistered\") {\n failedTokens.push(...tokens);\n }\n console.log(\"Push notification error\", {\n error: ticket.details?.error,\n tokens,\n });\n }\n } else {\n successCount++;\n }\n }\n\n return { failedTokens, successCount };\n}\n\n/**\n * Send a single chunk of push notifications\n */\nasync function sendChunk(\n chunk: ExpoPushMessage[],\n chunkIndex: number,\n): Promise<{ successCount: number; failedTokens: string[] }> {\n try {\n const tickets = await expo.sendPushNotificationsAsync(chunk);\n const { successCount, failedTokens } = processChunkResults(tickets, chunk);\n\n console.log(\n `Chunk ${chunkIndex + 1}: Sent ${successCount}/${chunk.length} notifications successfully`,\n );\n\n return { failedTokens, successCount };\n } catch (error) {\n console.log(\"Error sending Expo push notification chunk\", {\n chunkIndex,\n chunkSize: chunk.length,\n error: error instanceof Error ? error.message : String(error),\n });\n return { failedTokens: [], successCount: 0 };\n }\n}\n\nexport async function sendPushNotifications({\n data,\n message,\n title,\n userIds,\n}: SchemaCreateBulkNotificationInput) {\n const pushTokens = await PushTokenModel.find({ userId: { $in: userIds } });\n const expoTokens = pushTokens.map((token) => token.token);\n\n if (!data) return;\n\n const { messages, invalidTokens } = createPushMessages({\n data,\n message,\n title,\n tokens: expoTokens,\n });\n\n // Log invalid tokens\n if (invalidTokens.length > 0) {\n console.log(`Found ${invalidTokens.length} invalid push tokens`);\n }\n\n if (messages.length === 0) {\n console.log(\"No valid messages to send after filtering tokens\");\n return;\n }\n\n // Send notifications in chunks\n const chunks = expo.chunkPushNotifications(messages);\n let totalSuccessCount = 0;\n const allFailedTokens: string[] = [];\n\n for (const [chunkIndex, chunk] of chunks.entries()) {\n const { successCount, failedTokens } = await sendChunk(\n chunk,\n chunkIndex + 1,\n );\n totalSuccessCount += successCount;\n allFailedTokens.push(...failedTokens);\n }\n\n // Log final results\n console.log(\n `Sent push notification to ${totalSuccessCount}/${messages.length} tokens across ${chunks.length} chunks`,\n );\n\n if (allFailedTokens.length > 0) {\n console.log(`Found ${allFailedTokens.length} failed push tokens`);\n }\n}\n","import {\n EnumAffiliateRewardType,\n EnumUserLicence,\n} from \"@timardex/cluemart-shared\";\nimport dayjs from \"dayjs\";\nimport timezone from \"dayjs/plugin/timezone\";\nimport utc from \"dayjs/plugin/utc\";\n\nimport { ObjectId } from \"src/types\";\n\nimport { getPayingVendorStripeSubscriptionPlan } from \"../license/stripe/stripe\";\n\ndayjs.extend(utc);\ndayjs.extend(timezone);\n\n/** Timezone the monthly reward window aligns to (matches the cron scheduler's `tz`). */\nexport const SUBSCRIPTION_REWARD_TIMEZONE = \"Pacific/Auckland\";\n\n/**\n * Maps a vendor owner's highest valid vendor licence to a monthly subscription reward.\n *\n * Prefer Pro / Pro+ over Standard when both are valid.\n * Pro / Pro+ only yields the Pro reward when the owner has an active Stripe subscription;\n * otherwise falls back to the Standard subscription reward.\n * Returns `null` when no non-expired vendor licence applies.\n */\nexport async function mapVendorLicenceToSubscriptionRewardType(\n userId: ObjectId | string,\n now: Date = new Date(),\n): Promise<EnumAffiliateRewardType | null> {\n const { hasSubscription, validTypes } =\n await getPayingVendorStripeSubscriptionPlan(userId, now);\n\n if (\n validTypes.has(EnumUserLicence.PRO_VENDOR) ||\n validTypes.has(EnumUserLicence.PRO_PLUS_VENDOR)\n ) {\n if (hasSubscription) {\n return EnumAffiliateRewardType.ACTIVE_VENDOR_PRO_SUBSCRIPTION;\n }\n return EnumAffiliateRewardType.ACTIVE_VENDOR_STANDARD_SUBSCRIPTION;\n }\n\n if (validTypes.has(EnumUserLicence.STANDARD_VENDOR)) {\n return EnumAffiliateRewardType.ACTIVE_VENDOR_STANDARD_SUBSCRIPTION;\n }\n\n return null;\n}\n\n/** Inclusive start / exclusive end of the {@link SUBSCRIPTION_REWARD_TIMEZONE} calendar month containing `now`. */\nexport function getSubscriptionRewardPeriodBounds(now: Date = new Date()): {\n periodEnd: Date;\n periodStart: Date;\n} {\n const periodStart = dayjs(now)\n .tz(SUBSCRIPTION_REWARD_TIMEZONE)\n .startOf(\"month\")\n .toDate();\n const periodEnd = dayjs(now)\n .tz(SUBSCRIPTION_REWARD_TIMEZONE)\n .startOf(\"month\")\n .add(1, \"month\")\n .toDate();\n return { periodEnd, periodStart };\n}\n","import {\n EnumSubscriptionStatus,\n EnumUserLicence,\n} from \"@timardex/cluemart-shared/enums\";\n\nimport { UserModel } from \"src/mongoose/User\";\nimport { ObjectId } from \"src/types\";\n\nconst PRO_EVENT_PLANS = new Set<EnumUserLicence>([\n EnumUserLicence.PRO_EVENT,\n EnumUserLicence.PRO_PLUS_EVENT,\n]);\n\nconst PRO_VENDOR_PLANS = new Set<EnumUserLicence>([\n EnumUserLicence.PRO_VENDOR,\n EnumUserLicence.PRO_PLUS_VENDOR,\n]);\n\nconst PRO_PLANS = new Set<EnumUserLicence>([\n ...PRO_EVENT_PLANS,\n ...PRO_VENDOR_PLANS,\n]);\n\ntype PayingStripeSubscriptionPlanResult = {\n hasSubscription: boolean;\n plan: EnumUserLicence | null;\n validTypes: Set<EnumUserLicence>;\n};\n\nasync function getPayingStripePlanFor(\n userId: ObjectId | string,\n now: Date,\n payingPlans: Set<EnumUserLicence>,\n): Promise<PayingStripeSubscriptionPlanResult> {\n const user = await UserModel.findById(userId)\n .select(\"licences stripe\")\n .lean()\n .exec();\n\n if (!user) {\n return { hasSubscription: false, plan: null, validTypes: new Set() };\n }\n\n const stripe = user.stripe;\n const licences = user.licences ?? [];\n\n const validTypes = new Set(\n licences\n .filter(\n (licence) => new Date(licence.expiryDate).getTime() > now.getTime(),\n )\n .map((licence) => licence.licenceType),\n );\n\n if (stripe == null || stripe.subscriptionId == null) {\n return { hasSubscription: false, plan: null, validTypes };\n }\n\n const hasActiveStatus = stripe.status === EnumSubscriptionStatus.ACTIVE;\n const paidThrough = stripe.endDate\n ? new Date(stripe.endDate).getTime()\n : Number.NaN;\n\n if (\n !hasActiveStatus ||\n !Number.isFinite(paidThrough) ||\n paidThrough <= now.getTime() ||\n stripe.currentPlan == null\n ) {\n return { hasSubscription: false, plan: null, validTypes };\n }\n\n const plan = payingPlans.has(stripe.currentPlan) ? stripe.currentPlan : null;\n\n return { hasSubscription: plan != null, plan, validTypes };\n}\n\n/**\n * Returns the paying Stripe plan when `currentPlan` is any PRO plan\n * (event or vendor), the subscription is active, and its finite paid-through\n * `endDate` is later than `now`. Status alone does not establish paid access.\n */\nexport async function getPayingStripeSubscriptionPlan(\n userId: ObjectId | string,\n now: Date = new Date(),\n): Promise<PayingStripeSubscriptionPlanResult> {\n return getPayingStripePlanFor(userId, now, PRO_PLANS);\n}\n\n/**\n * Like {@link getPayingStripeSubscriptionPlan} but only treats a vendor PRO\n * plan (`PRO_VENDOR` / `PRO_PLUS_VENDOR`) as paying.\n */\nexport async function getPayingVendorStripeSubscriptionPlan(\n userId: ObjectId | string,\n now: Date = new Date(),\n): Promise<PayingStripeSubscriptionPlanResult> {\n return getPayingStripePlanFor(userId, now, PRO_VENDOR_PLANS);\n}\n\n/**\n * Like {@link getPayingStripeSubscriptionPlan} but only treats an event PRO\n * plan (`PRO_EVENT` / `PRO_PLUS_EVENT`) as paying.\n */\nexport async function getPayingEventStripeSubscriptionPlan(\n userId: ObjectId | string,\n now: Date = new Date(),\n): Promise<PayingStripeSubscriptionPlanResult> {\n return getPayingStripePlanFor(userId, now, PRO_EVENT_PLANS);\n}\n","import { PromoCodeType } from \"@timardex/cluemart-shared\";\n\nimport { AffiliateModel } from \"src/mongoose\";\n\n/**\n * Loads the affiliate whose `affiliateCode` matches the given promo code.\n *\n * Affiliate codes are assigned on admin activation, so referrals only resolve after\n * a code exists. Soft-deleted affiliates (`deletedAt` set) are excluded.\n *\n * @param promoCode - Normalized affiliate promo code to resolve.\n * @returns The matching affiliate document, or `null` when not found.\n */\nexport async function findAffiliateByPromoCode(promoCode: PromoCodeType) {\n return AffiliateModel.findOne({\n affiliateCode: promoCode,\n deletedAt: null,\n }).exec();\n}\n","export function normalizePromoCode(\n decoratedPromoCode: string | null | undefined,\n): string | null {\n const normalized = decoratedPromoCode?.trim().toUpperCase();\n return normalized || null;\n}\n","import { PromoCodeType } from \"@timardex/cluemart-shared\";\n\nimport { normalizePromoCode } from \"../promoCode/normalizePromoCode\";\n\n/**\n * Normalizes, trims, uppercases, and deduplicates resource promo codes.\n *\n * @param promoCodes - Raw promo codes from a create-resource mutation input.\n * @returns Unique normalized codes; empty strings and whitespace-only values are removed.\n */\nexport function normalizeAffiliatePromoCodes(\n promoCodes: PromoCodeType[] | null | undefined,\n): PromoCodeType[] {\n const normalized = (promoCodes ?? [])\n .map((code) => normalizePromoCode(code))\n .filter((code): code is PromoCodeType => code !== null);\n\n return [...new Set(normalized)];\n}\n","import mongoose from \"mongoose\";\n\n/**\n * Connect to MongoDB using Mongoose.\n * Supports both local MongoDB (via MONGODB_URI) and MongoDB Atlas (via individual env vars).\n */\nexport const connectToDatabase = async ({\n appName,\n dbName,\n dbPassword,\n dbUser,\n mongodbUri,\n}: {\n appName: string;\n dbName: string;\n dbPassword: string;\n dbUser: string;\n mongodbUri: string;\n}) => {\n try {\n // Check if MONGODB_URI is provided (for local Docker MongoDB)\n const mongoUri = mongodbUri\n ? mongodbUri\n : // Fallback to MongoDB Atlas connection string\n `mongodb+srv://${dbUser}:${dbPassword}@${dbName}.mongodb.net/?retryWrites=true&w=majority&appName=${appName}`;\n\n await mongoose.connect(mongoUri);\n\n const connectionType = mongodbUri ? \"Local MongoDB\" : \"MongoDB Atlas\";\n console.log(\n `${connectionType} connected from server/src/service/database.ts`,\n );\n } catch (err) {\n console.error(\"Error connecting to MongoDB:\", err);\n throw err; // You can throw the error if you want to stop the server in case of connection failure\n }\n};\n","import {\n NotificationModel,\n SchemaCreateBulkNotificationInput,\n} from \"src/mongoose/Notification\";\nimport { EnumPubSubEvents, GraphQLContext, ObjectId } from \"src/types\";\n\nimport { saveNotificationsInDb } from \"./saveNotificationsInDb\";\nimport { sendPushNotifications } from \"./sendPushNotifications\";\n\n/**\n * Publish-only pubsub used to emit GraphQL subscription events. Optional in\n * {@link notifyUsers} because non-GraphQL processes (e.g. the cron worker) have\n * no subscribers to publish to.\n */\nexport type NotificationPubSub = Pick<GraphQLContext[\"pubsub\"], \"publish\">;\n\n/** Publishes notification list/count subscription events for a user. */\nexport async function publishNotificationEvents(\n userId: ObjectId,\n pubsub: NotificationPubSub,\n) {\n try {\n // Get user's notifications for the subscription\n const userNotifications = await NotificationModel.find({\n userId,\n }).sort({ createdAt: -1 });\n\n // Get notification count\n const [total, unread] = await Promise.all([\n NotificationModel.countDocuments({ userId }),\n NotificationModel.countDocuments({ isRead: false, userId }),\n ]);\n\n // Publish both events\n pubsub.publish(EnumPubSubEvents.GET_NOTIFICATIONS, {\n getNotifications: userNotifications,\n getNotificationsUserId: userId,\n });\n\n pubsub.publish(EnumPubSubEvents.GET_NOTIFICATIONS_COUNT, {\n getNotificationsCount: { total, unread, userId },\n });\n\n console.log(`Published notification events for user: ${String(userId)}`);\n } catch (error) {\n console.error(\n `Failed to publish notification events for user ${String(userId)}:`,\n error,\n );\n }\n}\n\n/**\n * Sends push notifications, saves them in the database, and (when a `pubsub`\n * is provided) publishes GraphQL subscription events for each affected user.\n *\n * Errors are logged and swallowed; this function never throws. Instead it\n * returns `false` when notifications were not confirmed (an error was thrown,\n * or `saveNotificationsInDb` failed to persist any rows for a non-empty\n * `userIds`), so callers can gate success logs/metrics on the result.\n */\nexport async function notifyUsers({\n payload,\n pubsub,\n}: {\n payload: SchemaCreateBulkNotificationInput;\n pubsub?: NotificationPubSub;\n}): Promise<boolean> {\n try {\n await sendPushNotifications(payload);\n\n const uniqueUserIds = await saveNotificationsInDb(payload);\n // saveNotificationsInDb swallows its own errors and returns []; treat an\n // empty result for a non-empty input as a persistence failure.\n const persisted = payload.userIds.length === 0 || uniqueUserIds.length > 0;\n\n if (pubsub) {\n for (const userId of uniqueUserIds) {\n await publishNotificationEvents(userId, pubsub);\n }\n }\n\n return persisted;\n } catch (error) {\n console.error(\"Error in notifyUsers:\", error);\n return false;\n }\n}\n","import {\n EnumAdApprovalStatus,\n EnumAdBookingSlotKind,\n EnumAdPaymentStatus,\n EnumAdStatus,\n} from \"@timardex/cluemart-shared\";\n\nimport { AdModel } from \"src/mongoose\";\n\n/**\n * Updates ad statuses based on start/end dates and validity\n */\nexport async function updateAdStatuses(): Promise<void> {\n const now = new Date();\n\n // invalid: normally `start`/`end` are always present, but `required` is only\n // enforced by Mongoose on writes through the app — legacy/corrupt docs (and\n // updateMany, which skips validation) can still miss them. Keep the `$exists`\n // guards so such docs get marked PAUSED instead of stuck in a non-terminal\n // status. A reversed window (start after end) is also invalid.\n const invalidResult = await AdModel.updateMany(\n {\n $or: [\n { start: { $exists: false } },\n { end: { $exists: false } },\n { $expr: { $gt: [\"$start\", \"$end\"] } },\n ],\n status: { $ne: EnumAdStatus.PAUSED },\n },\n { $set: { status: EnumAdStatus.PAUSED } },\n );\n\n // expired\n const expiredResult = await AdModel.updateMany(\n { end: { $lte: now }, status: { $ne: EnumAdStatus.EXPIRED } },\n { $set: { status: EnumAdStatus.EXPIRED } },\n );\n\n // Booking-backed ads must never be activated before payment and approval.\n // Ads without booking metadata belong to the existing admin-managed flow.\n const eligibleBooking = {\n $or: [\n { bookingKind: { $exists: false } },\n { bookingKind: null },\n {\n approvalStatus: EnumAdApprovalStatus.APPROVED,\n bookingKind: EnumAdBookingSlotKind.RESERVED,\n },\n {\n approvalStatus: EnumAdApprovalStatus.APPROVED,\n bookingKind: EnumAdBookingSlotKind.PAID,\n paymentStatus: EnumAdPaymentStatus.PAID,\n },\n ],\n };\n\n const awaitingApprovalResult = await AdModel.updateMany(\n {\n $nor: eligibleBooking.$or,\n bookingKind: { $in: Object.values(EnumAdBookingSlotKind) },\n end: { $gt: now },\n status: EnumAdStatus.ACTIVE,\n },\n { $set: { status: EnumAdStatus.PAUSED } },\n );\n\n // active\n const activeResult = await AdModel.updateMany(\n {\n end: { $gt: now },\n start: { $lte: now },\n status: { $ne: EnumAdStatus.ACTIVE },\n ...eligibleBooking,\n },\n { $set: { status: EnumAdStatus.ACTIVE } },\n );\n\n // paused\n const pausedResult = await AdModel.updateMany(\n { start: { $gt: now }, status: { $ne: EnumAdStatus.PAUSED } },\n { $set: { status: EnumAdStatus.PAUSED } },\n );\n\n console.log(\n `✅ Ad statuses updated: invalid=${invalidResult.modifiedCount}, expired=${expiredResult.modifiedCount}, awaitingApproval=${awaitingApprovalResult.modifiedCount}, active=${activeResult.modifiedCount}, paused=${pausedResult.modifiedCount}`,\n );\n}\n","import mongoose from \"mongoose\";\n\n/**\n * True when `value` is a valid Mongo ObjectId string.\n */\nexport function isValidObjectId(value: string): boolean {\n return mongoose.Types.ObjectId.isValid(value);\n}\n\n/**\n * Recursively converts all ObjectId fields to strings in an object\n * This is needed because GraphQL expects string IDs, not ObjectIds\n */\nexport function convertObjectIdsToStrings(obj: any): any {\n if (obj === null || obj === undefined) {\n return obj;\n }\n\n if (obj instanceof mongoose.Types.ObjectId) {\n return obj.toString();\n }\n\n if (obj instanceof Date) {\n return obj;\n }\n\n if (Array.isArray(obj)) {\n return obj.map(convertObjectIdsToStrings);\n }\n\n if (typeof obj === \"object\") {\n const converted: any = {};\n for (const [key, value] of Object.entries(obj)) {\n converted[key] = convertObjectIdsToStrings(value);\n }\n return converted;\n }\n\n return obj;\n}\n","import {\n dateFormat,\n DateTimeType,\n DateTimeWithPriceType,\n EnumEventDateStatus,\n filterDatesByFutureStatus,\n timeFormat,\n} from \"@timardex/cluemart-shared\";\nimport dayjs from \"dayjs\";\nimport customParseFormat from \"dayjs/plugin/customParseFormat\";\nimport isoWeek from \"dayjs/plugin/isoWeek\";\n\nimport {\n EventDateArchiveModel,\n EventInfoModel,\n EventModel,\n GoogleImportedMarketModel,\n} from \"src/mongoose\";\n\nimport {\n dedupeArchivedSlotsByStartDateTime,\n splitEventDatesForArchive,\n} from \"./archiveEndedEventDates\";\n\n// Enable dayjs plugins used by event date parsing/status logic\ndayjs.extend(customParseFormat);\ndayjs.extend(isoWeek);\n\n/**\n * Statuses set by an explicit user action rather than derived from the\n * schedule clock. The status recomputation below must leave them untouched,\n * otherwise a canceled/rescheduled date would silently flip back to a\n * time-derived status on the next run.\n */\nconst MANUAL_DATE_STATUSES: ReadonlySet<EnumEventDateStatus> = new Set([\n EnumEventDateStatus.CANCELED,\n EnumEventDateStatus.RE_SCHEDULED,\n]);\n\n/**\n * Determines the dateStatus for a future event date\n * @param startDateTime The start date-time of the event\n * @param now The current date-time\n * @returns The appropriate EnumEventDateStatus\n */\nexport function getFutureEventStatus(\n startDateTime: dayjs.Dayjs,\n now: dayjs.Dayjs,\n): EnumEventDateStatus {\n const hoursUntilStart = startDateTime.diff(now, \"hour\", true);\n if (hoursUntilStart > 0 && hoursUntilStart <= 4) {\n return EnumEventDateStatus.STARTING_SOON;\n }\n\n if (startDateTime.isSame(now, \"day\")) {\n return EnumEventDateStatus.TODAY;\n }\n\n if (startDateTime.isSame(now.add(1, \"day\"), \"day\")) {\n return EnumEventDateStatus.TOMORROW;\n }\n\n if (startDateTime.isSame(now, \"isoWeek\")) {\n return EnumEventDateStatus.THIS_WEEK;\n }\n\n if (startDateTime.isSame(now.add(1, \"week\"), \"isoWeek\")) {\n return EnumEventDateStatus.NEXT_WEEK;\n }\n\n return EnumEventDateStatus.UPCOMING;\n}\n\n/**\n * Updates the dateStatus field for a single DateTimeType object based on the current date/time.\n * Manual statuses (CANCELED, RE_SCHEDULED) are preserved and returned as-is.\n * @param dateTime The date-time object to update\n * @returns A new object with an updated dateStatus value, or the original\n * object when the stored status is a manual override\n */\nexport function updateSingleDateTimeStatus<T extends DateTimeType>(\n dateTime: T,\n now: dayjs.Dayjs = dayjs(),\n): T {\n if (MANUAL_DATE_STATUSES.has(dateTime.dateStatus)) {\n return dateTime;\n }\n\n // Parse start and end date-time\n const dateTimeFormat = `${dateFormat} ${timeFormat}`;\n const startDateTime = dayjs(\n `${dateTime.startDate} ${dateTime.startTime}`,\n dateTimeFormat,\n true,\n );\n const endDateTime = dayjs(\n `${dateTime.endDate} ${dateTime.endTime}`,\n dateTimeFormat,\n true,\n );\n\n // Skip if dates are invalid\n if (!startDateTime.isValid() || !endDateTime.isValid()) {\n return {\n ...dateTime,\n dateStatus: EnumEventDateStatus.INVALID,\n };\n }\n\n if (endDateTime.isBefore(startDateTime)) {\n return {\n ...dateTime,\n dateStatus: EnumEventDateStatus.INVALID,\n };\n }\n\n let dateStatus: EnumEventDateStatus;\n\n if (endDateTime.isAfter(now)) {\n if (startDateTime.isAfter(now)) {\n // Event has not started yet\n dateStatus = getFutureEventStatus(startDateTime, now);\n } else {\n // Event is in progress\n dateStatus = EnumEventDateStatus.STARTED;\n }\n } else {\n // Event has ended\n dateStatus = EnumEventDateStatus.ENDED;\n }\n\n return {\n ...dateTime,\n dateStatus,\n };\n}\n\nconst dateTimeStatusFilter = {\n dateTime: { $ne: [], $type: \"array\" },\n deletedAt: null,\n} as const;\n\nconst CURSOR_BATCH_SIZE = 50;\n\ntype DocWithDateTime = {\n _id: unknown;\n dateTime: DateTimeType[];\n};\n\ntype DateTimeBulkWriteOp = {\n updateOne: {\n filter: { _id: unknown };\n update: { $set: { dateTime: DateTimeType[] } };\n };\n};\n\ntype EventInfoBulkWriteOp = {\n updateOne: {\n filter: { _id: unknown };\n update: { $set: { dateTime: DateTimeWithPriceType[] } };\n };\n};\n\ntype DateTimeCursor = AsyncIterable<DocWithDateTime> & {\n close: () => Promise<unknown>;\n};\n\ntype DateTimeUpdatableModel = {\n bulkWrite: (ops: DateTimeBulkWriteOp[]) => Promise<unknown>;\n find: (filter: typeof dateTimeStatusFilter) => {\n select: (fields: { _id: 1; dateTime: 1 }) => {\n lean: () => {\n cursor: (opts: { batchSize: number }) => DateTimeCursor;\n };\n };\n };\n};\n\nfunction hasDateTimeStatusChanges(\n stored: DateTimeType[],\n updated: DateTimeType[],\n): boolean {\n if (stored.length !== updated.length) {\n return true;\n }\n\n return stored.some(\n (slot, index) => slot.dateStatus !== updated[index].dateStatus,\n );\n}\n\nasync function updateModelDateTimeStatuses(\n model: DateTimeUpdatableModel,\n now: dayjs.Dayjs,\n): Promise<number> {\n let updated = 0;\n const cursor = model\n .find(dateTimeStatusFilter)\n .select({ _id: 1, dateTime: 1 })\n .lean()\n .cursor({ batchSize: CURSOR_BATCH_SIZE });\n\n let bulkOps: DateTimeBulkWriteOp[] = [];\n\n const flushBulkWrites = async (): Promise<void> => {\n if (!bulkOps.length) {\n return;\n }\n\n await model.bulkWrite(bulkOps);\n updated += bulkOps.length;\n bulkOps = [];\n };\n\n try {\n for await (const doc of cursor) {\n const dateTime = doc.dateTime.map((slot) =>\n updateSingleDateTimeStatus(slot, now),\n );\n\n if (!hasDateTimeStatusChanges(doc.dateTime, dateTime)) {\n continue;\n }\n\n bulkOps.push({\n updateOne: {\n filter: { _id: doc._id },\n update: { $set: { dateTime } },\n },\n });\n\n if (bulkOps.length >= CURSOR_BATCH_SIZE) {\n await flushBulkWrites();\n }\n }\n\n await flushBulkWrites();\n } finally {\n await cursor.close().catch(() => undefined);\n }\n\n return updated;\n}\n\nconst ARCHIVABLE_EVENT_FILTER = {\n \"dateTime.dateStatus\": {\n $in: [EnumEventDateStatus.ENDED, EnumEventDateStatus.INVALID],\n },\n deletedAt: null,\n} as const;\n\ntype ArchiveUpsertOp = {\n updateOne: {\n filter: { eventId: unknown };\n update: { $addToSet: { dateTime: { $each: DateTimeType[] } } };\n upsert: true;\n };\n};\n\ntype EventDatePullOp = {\n updateOne: {\n filter: { _id: unknown };\n update: {\n $pull: {\n dateTime: { dateStatus: { $in: EnumEventDateStatus[] } };\n };\n };\n };\n};\n\n/**\n * Moves ended event date slots into the archive, discards invalid slots, and\n * pulls both from `Event.dateTime`, keeping future and in-progress (`STARTED`)\n * dates live. Archive upserts and event `$pull` updates are collected into\n * bulkWrite batches to avoid per-document round-trips. The event write is a\n * targeted `$pull` (by status) rather than a full-array `$set`, so concurrent\n * schedule changes are not clobbered.\n */\nasync function archiveEndedAndDiscardInvalidEventDates(\n now: dayjs.Dayjs,\n): Promise<number> {\n const cursor = EventModel.find(ARCHIVABLE_EVENT_FILTER)\n .select({ _id: 1, dateTime: 1 })\n .lean()\n .cursor({ batchSize: CURSOR_BATCH_SIZE });\n\n let archivedCount = 0;\n let archiveOps: ArchiveUpsertOp[] = [];\n let eventOps: EventDatePullOp[] = [];\n\n const flushBulkWrites = async (): Promise<void> => {\n if (archiveOps.length) {\n await EventDateArchiveModel.bulkWrite(archiveOps);\n archiveOps = [];\n }\n\n if (eventOps.length) {\n await EventModel.bulkWrite(eventOps);\n eventOps = [];\n }\n };\n\n try {\n for await (const doc of cursor) {\n const updated = doc.dateTime.map((slot) =>\n updateSingleDateTimeStatus(slot, now),\n );\n\n const { archive, discard } = splitEventDatesForArchive(updated);\n if (archive.length === 0 && discard.length === 0) {\n continue;\n }\n\n if (archive.length > 0) {\n const uniqueArchive = dedupeArchivedSlotsByStartDateTime(archive);\n archiveOps.push({\n updateOne: {\n filter: { eventId: doc._id },\n update: { $addToSet: { dateTime: { $each: uniqueArchive } } },\n upsert: true,\n },\n });\n archivedCount += uniqueArchive.length;\n }\n\n eventOps.push({\n updateOne: {\n filter: { _id: doc._id },\n update: {\n $pull: {\n dateTime: {\n dateStatus: {\n $in: [EnumEventDateStatus.ENDED, EnumEventDateStatus.INVALID],\n },\n },\n },\n },\n },\n });\n\n if (\n archiveOps.length >= CURSOR_BATCH_SIZE ||\n eventOps.length >= CURSOR_BATCH_SIZE\n ) {\n await flushBulkWrites();\n }\n }\n\n await flushBulkWrites();\n } finally {\n await cursor.close().catch(() => undefined);\n }\n\n return archivedCount;\n}\n\nconst EVENT_INFO_DATE_FILTER = {\n dateTime: { $ne: [], $type: \"array\" },\n} as const;\n\n/**\n * Removes non-future (`STARTED`, `ENDED`, `INVALID`, `CANCELED`,\n * `RE_SCHEDULED`) slots from `EventInfo.dateTime` so the stored data stays in\n * sync with the future-only invariant used on writes. Updates are collected\n * into bulkWrite batches to avoid per-document round-trips.\n */\nasync function cleanEventInfoDates(now: dayjs.Dayjs): Promise<number> {\n const cursor = EventInfoModel.find(EVENT_INFO_DATE_FILTER)\n .select({ _id: 1, dateTime: 1 })\n .lean()\n .cursor({ batchSize: CURSOR_BATCH_SIZE });\n\n let removedCount = 0;\n let bulkOps: EventInfoBulkWriteOp[] = [];\n\n const flushBulkWrites = async (): Promise<void> => {\n if (!bulkOps.length) {\n return;\n }\n\n await EventInfoModel.bulkWrite(bulkOps);\n bulkOps = [];\n };\n\n try {\n for await (const doc of cursor) {\n const updated = (doc.dateTime as DateTimeWithPriceType[]).map((slot) =>\n updateSingleDateTimeStatus(slot, now),\n );\n\n const kept = filterDatesByFutureStatus(updated);\n if (kept.length === updated.length) {\n continue;\n }\n\n bulkOps.push({\n updateOne: {\n filter: { _id: doc._id },\n update: { $set: { dateTime: kept } },\n },\n });\n removedCount += updated.length - kept.length;\n\n if (bulkOps.length >= CURSOR_BATCH_SIZE) {\n await flushBulkWrites();\n }\n }\n\n await flushBulkWrites();\n } finally {\n await cursor.close().catch(() => undefined);\n }\n\n return removedCount;\n}\n\n/**\n * Recomputes dateStatus for every dateTime slot on events and google imported\n * markets, moves ended event date slots into the event date archive, and keeps\n * `EventInfo.dateTime` future-only.\n */\nexport async function updateAllEventDateTimeStatuses(): Promise<void> {\n const now = dayjs();\n const [eventCount, marketCount] = await Promise.all([\n updateModelDateTimeStatuses(EventModel as DateTimeUpdatableModel, now),\n updateModelDateTimeStatuses(\n GoogleImportedMarketModel as DateTimeUpdatableModel,\n now,\n ),\n ]);\n\n console.log(\n `✅ Event dateTime statuses updated: events=${eventCount} changed, google imported markets=${marketCount} changed`,\n );\n\n const archivedCount = await archiveEndedAndDiscardInvalidEventDates(now);\n if (archivedCount > 0) {\n console.log(`✅ Archived ${archivedCount} ended event date slot(s)`);\n }\n\n const removedEventInfoCount = await cleanEventInfoDates(now);\n if (removedEventInfoCount > 0) {\n console.log(\n `✅ Removed ${removedEventInfoCount} non-future event info date slot(s)`,\n );\n }\n}\n","import { DateTimeType, EnumEventDateStatus } from \"@timardex/cluemart-shared\";\n\nimport { EventDateArchiveModel } from \"src/mongoose\";\nimport { ObjectId } from \"src/types\";\n\nconst ARCHIVED_STATUSES: ReadonlySet<EnumEventDateStatus> = new Set([\n EnumEventDateStatus.ENDED,\n]);\n\nconst DISCARDED_STATUSES: ReadonlySet<EnumEventDateStatus> = new Set([\n EnumEventDateStatus.INVALID,\n]);\n\n/**\n * Splits a recomputed event schedule into three buckets: slots to keep on the\n * Event document (future + STARTED), ended slots to archive (`ENDED`), and\n * invalid slots to discard (`INVALID` — removed from the Event but *not*\n * archived). `Event.dateTime` may become empty once an event has no future or\n * in-progress dates.\n */\nexport function splitEventDatesForArchive(dateTime: DateTimeType[]): {\n archive: DateTimeType[];\n discard: DateTimeType[];\n keep: DateTimeType[];\n} {\n return {\n archive: dateTime.filter((slot) => ARCHIVED_STATUSES.has(slot.dateStatus)),\n discard: dateTime.filter((slot) => DISCARDED_STATUSES.has(slot.dateStatus)),\n keep: dateTime.filter(\n (slot) =>\n !ARCHIVED_STATUSES.has(slot.dateStatus) &&\n !DISCARDED_STATUSES.has(slot.dateStatus),\n ),\n };\n}\n\n/**\n * De-duplicates the *input* slots on (startDate, startTime), keeping the first\n * occurrence. This prevents a single write from appending near-duplicate\n * history (the archive's `$addToSet` only de-dupes by deep equality, not by\n * startDate/startTime). It does not scan or clean duplicates already stored in\n * the archive document.\n */\nexport function dedupeArchivedSlotsByStartDateTime(\n slots: DateTimeType[],\n): DateTimeType[] {\n const seen = new Set<string>();\n\n return slots.filter((slot) => {\n const key = `${slot.startDate}_${slot.startTime}`;\n if (seen.has(key)) {\n return false;\n }\n seen.add(key);\n return true;\n });\n}\n\n/**\n * Persists archived slots into the event's archive document. Idempotent: the\n * archive document is keyed per event and slots are appended with `$addToSet`.\n */\nexport async function persistArchivedEventDates(\n eventId: ObjectId | string,\n slots: DateTimeType[],\n): Promise<void> {\n if (slots.length === 0) {\n return;\n }\n\n const uniqueSlots = dedupeArchivedSlotsByStartDateTime(slots);\n\n await EventDateArchiveModel.updateOne(\n { eventId },\n { $addToSet: { dateTime: { $each: uniqueSlots } } },\n { upsert: true },\n );\n}\n","import { EventListItemType } from \"@timardex/cluemart-shared\";\n\nimport {\n EventModel,\n GoogleImportedMarketModel,\n SchemaOwnerType,\n} from \"src/mongoose\";\nimport { ObjectId } from \"src/types\";\n\nimport { convertObjectIdsToStrings } from \"../objectIdToString\";\n\ntype EventOrMarket =\n | (Pick<EventListItemType, \"_id\" | \"name\" | \"dateTime\"> & {\n /** Present on owned EventModel docs; absent on Google-imported markets. */\n owner?: SchemaOwnerType;\n })\n | null;\n\n/**\n * This function attempts to find an Event or a Google Imported Market by the given resource ID.\n * It first normalizes the resource ID to a string format, then performs parallel queries to both collections.\n * If an Event is found, it returns that; otherwise, it checks for a Google Imported Market and returns it if found.\n * If neither is found, it returns null.\n * @param resourceId - The ID of the resource to find, which can be an ObjectId, string, null, or undefined.\n * @returns A promise that resolves to either an Event or a Google Imported Market object containing _id, name, dateTime, and owner (events only), or null if not found.\n */\n\nexport async function findEventOrImportedMarketById(\n resourceId: ObjectId | string | null | undefined,\n): Promise<EventOrMarket> {\n if (!resourceId) {\n return null;\n }\n\n const normalizedId = convertObjectIdsToStrings(resourceId) as string;\n\n const [eventDoc, googleImportedDoc] = await Promise.all([\n EventModel.findById(normalizedId)\n .select(\"_id name dateTime owner\")\n .lean<\n Pick<EventListItemType, \"_id\" | \"name\" | \"dateTime\"> & {\n owner?: SchemaOwnerType;\n }\n >()\n .exec(),\n GoogleImportedMarketModel.findById(normalizedId)\n .select(\"_id name dateTime\")\n .lean<Pick<EventListItemType, \"_id\" | \"name\" | \"dateTime\">>()\n .exec(),\n ]);\n\n return eventDoc ?? googleImportedDoc;\n}\n","import {\n DateTimeWithPriceType,\n EnumInviteStatus,\n} from \"@timardex/cluemart-shared\";\nimport { DateTimeType } from \"@timardex/cluemart-shared/types\";\n\nimport { SchemaRelationType } from \"src/mongoose/Relation\";\n\ntype EventDateSlot = Pick<DateTimeType, \"startDate\" | \"startTime\">;\n\n/**\n * Returns true when at least one startDate/startTime slot from the previous\n * schedule is absent from the next schedule (i.e. a date was removed).\n */\nexport function didRemoveAnyEventDates(\n previousDateTime: EventDateSlot[] | undefined,\n nextDateTime: EventDateSlot[] | undefined,\n): boolean {\n if (!previousDateTime?.length) {\n return false;\n }\n\n return previousDateTime.some(\n (prev) =>\n !nextDateTime?.some(\n (next) =>\n next.startDate === prev.startDate &&\n next.startTime === prev.startTime,\n ),\n );\n}\n\n/**\n * Helper: Update relationDates based on event's dateTime\n * Marks dates as UNAVAILABLE if they no longer exist in the event's dateTime.\n */\nexport function updateRelationDatesToUnavailable(\n relationDates: SchemaRelationType[\"relationDates\"],\n eventDateTime: DateTimeWithPriceType[] | undefined,\n): SchemaRelationType[\"relationDates\"] {\n return relationDates.map((relationDate) => {\n // Check if this relationDate exists in the event's dateTime\n const existsInEvent =\n eventDateTime?.some(\n (dt) =>\n dt.startDate === relationDate.dateTime.startDate &&\n dt.startTime === relationDate.dateTime.startTime,\n ) ?? false;\n\n return {\n ...relationDate,\n status: existsInEvent\n ? relationDate.status\n : EnumInviteStatus.UNAVAILABLE,\n };\n });\n}\n","import dayjs from \"dayjs\";\nimport type { Dayjs } from \"dayjs\";\n\nimport { UserModel } from \"src/mongoose/User\";\nimport { ObjectId } from \"src/types\";\n\nimport { processUserCompliance } from \"./utils\";\n\n/**\n * Runs the established compliance pipeline for one freshly loaded user.\n * Stripe webhooks use this at the actual paid-through boundary; the global\n * scheduled scan remains the fallback for missed or delayed webhook handling.\n */\nexport async function ensureUserLicenseComplianceForUser(\n userId: ObjectId,\n now: Dayjs = dayjs(),\n): Promise<void> {\n const user = await UserModel.findById(userId);\n if (!user) {\n return;\n }\n\n await processUserCompliance(user, now);\n}\n\nexport async function ensureUserLicenseCompliance(): Promise<void> {\n const now = dayjs();\n console.log(`🔍 Checking license compliance at ${now.format()}`);\n\n // Only fetch users with at least one expired license (or expiring today)\n // This significantly reduces the number of users to process\n const nowDate = now.toDate();\n\n // Performance Note: This query fetches users with at least one expired license,\n // but the compliance handlers (hasValidLicence) only deactivate resources if\n // the user has NO valid licenses of the required type. This means we may process\n // some users unnecessarily (e.g., users with one expired license but other valid licenses).\n //\n // This is an intentional trade-off:\n // - Query simplicity: Filtering for \"no valid licenses\" would require complex\n // MongoDB queries ($not with $elemMatch) that are harder to maintain and may\n // not use indexes efficiently\n // - Processing overhead: The hasValidLicence check is fast (in-memory array check),\n // so the overhead of processing extra users is minimal compared to query complexity\n // - For very large user bases: Consider adding a computed field (hasValidLicense)\n // or an index on licences.expiryDate to improve query performance\n const users = await UserModel.find({\n licences: {\n $elemMatch: {\n expiryDate: {\n $lte: nowDate, // Expired or expiring today\n },\n },\n },\n });\n\n console.log(\n `📊 Found ${users.length} users with expired or expiring licenses`,\n );\n\n if (!users.length) {\n console.log(\"No users with licenses to process.\");\n return;\n }\n\n let processedCount = 0;\n let errorCount = 0;\n\n for (const user of users) {\n try {\n await processUserCompliance(user, now);\n processedCount++;\n } catch (err) {\n errorCount++;\n console.error(\n `❌ Error processing license compliance for user ${String(user._id)}:`,\n err instanceof Error ? err.message : err,\n );\n // Continue processing other users even if one fails\n }\n }\n\n const errorMessage = errorCount > 0 ? `, ${errorCount} errors` : \"\";\n console.log(\n `✅ Processed ${processedCount} users successfully${errorMessage}`,\n );\n}\n","import {\n EnumNotificationResourceType,\n EnumNotificationType,\n EnumUserLicence,\n UserLicenceType,\n} from \"@timardex/cluemart-shared\";\nimport dayjs from \"dayjs\";\n\nimport { SchemaUserType, UserModel } from \"src/mongoose/User\";\nimport { ObjectId } from \"src/types\";\n\nimport { notifyUsers } from \"../../notifyUsers\";\n\nimport { handleEventLicenceCompliance } from \"./event\";\nimport { buildLicenceExpiryPipeline } from \"./licenceExpiryPipeline\";\nimport { handlePartnerLicenceCompliance } from \"./partner\";\nimport { handleVendorLicenceCompliance } from \"./vendor\";\n\n/**\n * Syncs the user's `licences` array\n * Uses a single atomic updateOne with an aggregation pipeline so it is safe under\n * concurrency (no read-modify-write, no lost updates).\n *\n * Rules (applied server-side only to licences whose licenceType is in licenceTypes):\n * - mode \"downgrade\" (vendor): expired STANDARD_* → extended to one year from now;\n * expired PRO_* or PRO_PLUS_* → downgraded to STANDARD_* with issuedDate=now and\n * expiryDate=one year from now\n * - mode \"extend\" (partner/event): expired licences are kept and their expiryDate\n * is extended to one year from now\n * - Non-expired or non-targeted licences are unchanged in both modes\n */\nexport async function syncUserLicencesAfterExpiry(\n userId: ObjectId,\n licenceTypes: EnumUserLicence[],\n now: dayjs.Dayjs,\n mode: \"downgrade\" | \"extend\" = \"downgrade\",\n): Promise<void> {\n const nowDate = now.toDate();\n const oneYearFromNow = now.add(1, \"year\").endOf(\"day\").toDate();\n\n const pipeline = buildLicenceExpiryPipeline({\n downgradeBranches: [\n {\n case: EnumUserLicence.PRO_PLUS_VENDOR,\n then: EnumUserLicence.STANDARD_VENDOR,\n },\n {\n case: EnumUserLicence.PRO_VENDOR,\n then: EnumUserLicence.STANDARD_VENDOR,\n },\n ],\n licenceTypes,\n mode,\n nowDate,\n oneYearFromNow,\n });\n\n await UserModel.updateOne({ _id: userId }, pipeline).exec();\n}\n\n/**\n * Checks if user has a valid licence of the given types\n */\nexport function hasValidLicence(\n licences: UserLicenceType[],\n licenceTypes: EnumUserLicence[],\n now: dayjs.Dayjs,\n): boolean {\n return licences.some(\n (licence) =>\n licenceTypes.includes(licence.licenceType) &&\n dayjs(licence.expiryDate).isAfter(now),\n );\n}\n\n/**\n * Sends a deactivation notification to the user\n */\nexport async function sendDeactivationNotification(\n payload: {\n data: {\n resourceId: string;\n resourceName: string;\n resourceType: EnumNotificationResourceType;\n };\n message: string;\n title: string;\n type: EnumNotificationType;\n userIds: ObjectId[];\n },\n userId: ObjectId,\n resourceName: string,\n resourceType: string,\n): Promise<void> {\n // No pubsub here: compliance runs in a process without GraphQL subscribers\n // (e.g. the cron worker), so notifyUsers is called without one. It logs and\n // swallows errors and reports success through its return value.\n const sent = await notifyUsers({ payload });\n if (!sent) {\n console.error(\n `❌ ${resourceType} notification not confirmed for user ${String(userId)} for \"${resourceName}\"`,\n );\n return;\n }\n console.log(\n `✅ Sent ${resourceType} notification to user ${String(userId)} for \"${resourceName}\"`,\n );\n}\n\n/**\n * Processes license compliance for a single user\n */\nexport async function processUserCompliance(\n user: SchemaUserType,\n now: dayjs.Dayjs,\n): Promise<void> {\n if (!user.licences) {\n return;\n }\n\n // Run compliance checks in parallel since they operate on different resources\n // (vendor, partner, events) and don't modify shared state\n await Promise.all([\n handleVendorLicenceCompliance(user, now),\n handlePartnerLicenceCompliance(user, now),\n handleEventLicenceCompliance(user, now),\n ]);\n}\n","import { EnumUserLicence } from \"@timardex/cluemart-shared\";\nimport type { Dayjs } from \"dayjs\";\n\nimport { SchemaUserType } from \"src/mongoose/User\";\n\nimport { syncUserLicencesAfterExpiry } from \"./utils\";\n\n// Group event licences\nexport const eventLicences: EnumUserLicence[] = [\n EnumUserLicence.STANDARD_EVENT,\n EnumUserLicence.PRO_EVENT,\n EnumUserLicence.PRO_PLUS_EVENT,\n];\n\n/**\n * Handles event licence compliance for a single user.\n *\n * Event licences are kept and extended on expiry — no deactivation.\n */\nexport async function handleEventLicenceCompliance(\n user: SchemaUserType,\n now: Dayjs,\n): Promise<void> {\n if (!user.licences || !user.events?.length) {\n return;\n }\n\n await syncUserLicencesAfterExpiry(user._id, eventLicences, now, \"extend\");\n}\n","/**\n * Builds an aggregation pipeline that atomically applies expiry rules to the\n * `licences` array. Used by syncUserLicencesAfterExpiry for a single\n * updateOne with no read-modify-write.\n *\n * downgradeBranches: PRO_* / PRO_PLUS_* licence types mapped to their STANDARD_*\n * counterpart (e.g. pro_plus_event → standard_event). Use EnumUserLicence in the\n * caller to avoid string drift.\n *\n * Note: Uses MongoDB aggregation keys \"then\"/\"case\" (required by $cond/$switch).\n *\n * Requires MongoDB 4.2+: this emits an updateOne aggregation pipeline (the\n * [ { $set: ... } ] form) and uses $reduce / $indexOfArray / $regexMatch in the\n * dedupe + standard-detection stages. The project runs MongoDB 8.0\n * (docker-compose.yml), well above the minimum.\n */\nexport function buildLicenceExpiryPipeline(params: {\n /** Pairs of (licenceType, standardCounterpart) for downgrade; e.g. PRO_PLUS_VENDOR → STANDARD_VENDOR */\n downgradeBranches: ReadonlyArray<{\n case: string;\n then: string;\n }>;\n licenceTypes: string[];\n /**\n * How expired, targeted licences are handled:\n * - \"downgrade\": extend expired STANDARD_* and downgrade expired PRO_* or PRO_PLUS_* (vendor)\n * - \"extend\": keep the licence as-is and extend expiryDate to oneYearFromNow (partner/event)\n */\n mode?: \"downgrade\" | \"extend\";\n nowDate: Date;\n oneYearFromNow: Date;\n}): object[] {\n const {\n downgradeBranches,\n licenceTypes,\n nowDate,\n oneYearFromNow,\n mode = \"downgrade\",\n } = params;\n\n // Value produced for a licence that is in the target set and expired.\n const expiredInTarget =\n mode === \"extend\"\n ? {\n // Extend: keep licenceType and all other fields, push expiry out by a year\n $mergeObjects: [\"$$lic\", { expiryDate: oneYearFromNow }],\n }\n : {\n $cond: {\n // Expired STANDARD_* → extend (keep, push expiry out by a year)\n if: \"$$isStandard\",\n then: {\n $mergeObjects: [\"$$lic\", { expiryDate: oneYearFromNow }],\n },\n else: {\n $cond: {\n // Expired PRO_* / PRO_PLUS_* → downgrade and set new dates\n if: { $ne: [\"$$downgrade\", null] },\n then: {\n $mergeObjects: [\n \"$$lic\",\n {\n expiryDate: oneYearFromNow,\n issuedDate: nowDate,\n licenceType: \"$$downgrade\",\n prevLicenceType: \"$$lic.licenceType\",\n },\n ],\n },\n // Unknown type in target set → keep as-is\n else: \"$$lic\",\n },\n },\n },\n };\n\n return [\n {\n // Stage 1: resolve each licence (extend / downgrade / keep)\n $set: {\n licences: {\n // Remove null entries (e.g. pre-existing null licences kept by the map)\n $filter: {\n as: \"x\",\n cond: { $ne: [\"$$x\", null] },\n input: {\n // Iterate over each licence in the document's licences array\n $map: {\n input: \"$licences\",\n as: \"lic\",\n in: {\n // Define variables once per licence for reuse in the condition tree\n $let: {\n vars: {\n // Target STANDARD_* type for this licence (from downgradeBranches)\n downgrade: {\n $switch: {\n branches: downgradeBranches.map((b) => ({\n case: {\n $eq: [\"$$lic.licenceType\", b.case],\n },\n then: b.then,\n })),\n default: null,\n },\n },\n // True if this licence has expiryDate <= now (expired)\n expired: {\n $and: [\n { $ne: [\"$$lic\", null] },\n { $lte: [\"$$lic.expiryDate\", nowDate] },\n ],\n },\n // True if this licence's type is in the list we're processing (e.g. vendor only)\n inTarget: { $in: [\"$$lic.licenceType\", licenceTypes] },\n // True if licenceType starts with \"standard_\" (e.g. standard_vendor)\n isStandard: {\n $regexMatch: {\n input: {\n $toString: { $ifNull: [\"$$lic.licenceType\", \"\"] },\n },\n regex: /^standard_/,\n },\n },\n },\n // Compute the new value for this array element\n in: {\n $cond: {\n // Keep as-is: null licence, or not in target set, or not expired\n if: {\n $or: [\n { $eq: [\"$$lic\", null] },\n { $not: \"$$inTarget\" },\n { $gt: [\"$$lic.expiryDate\", nowDate] },\n ],\n },\n then: \"$$lic\",\n // In target set and expired — apply the configured handling\n else: expiredInTarget,\n },\n },\n },\n },\n },\n },\n },\n },\n },\n },\n {\n // Stage 2: dedupe by licenceType — keep the entry with the latest expiryDate\n // (ties broken by the latest issuedDate). Runs inside the same atomic updateOne.\n $set: {\n licences: {\n $reduce: {\n input: \"$licences\",\n initialValue: [],\n in: {\n $let: {\n vars: {\n current: \"$$this\",\n index: {\n $indexOfArray: [\n {\n $map: {\n input: \"$$value\",\n as: \"item\",\n in: \"$$item.licenceType\",\n },\n },\n \"$$this.licenceType\",\n ],\n },\n },\n in: {\n $cond: {\n if: { $eq: [\"$$index\", -1] },\n then: { $concatArrays: [\"$$value\", [\"$$current\"]] },\n else: {\n $map: {\n input: \"$$value\",\n as: \"item\",\n in: {\n $cond: {\n if: {\n $eq: [\n \"$$item.licenceType\",\n \"$$current.licenceType\",\n ],\n },\n then: {\n $cond: {\n if: {\n $or: [\n {\n $gt: [\n \"$$current.expiryDate\",\n \"$$item.expiryDate\",\n ],\n },\n {\n $and: [\n {\n $eq: [\n \"$$current.expiryDate\",\n \"$$item.expiryDate\",\n ],\n },\n {\n $gt: [\n \"$$current.issuedDate\",\n \"$$item.issuedDate\",\n ],\n },\n ],\n },\n ],\n },\n then: \"$$current\",\n else: \"$$item\",\n },\n },\n else: \"$$item\",\n },\n },\n },\n },\n },\n },\n },\n },\n },\n },\n },\n },\n ];\n}\n","import { EnumUserLicence } from \"@timardex/cluemart-shared\";\nimport type { Dayjs } from \"dayjs\";\n\nimport { SchemaUserType } from \"src/mongoose/User\";\n\nimport { syncUserLicencesAfterExpiry } from \"./utils\";\n\n// Group partner licences\nexport const partnerLicences: EnumUserLicence[] = [\n EnumUserLicence.STANDARD_PARTNER,\n];\n\n/**\n * Handles partner licence compliance for a single user.\n *\n * Partner licences are kept and extended on expiry — no deactivation.\n */\nexport async function handlePartnerLicenceCompliance(\n user: SchemaUserType,\n now: Dayjs,\n): Promise<void> {\n if (!user.licences || !user.partner) {\n return;\n }\n\n await syncUserLicencesAfterExpiry(user._id, partnerLicences, now, \"extend\");\n}\n","import {\n EnumNotificationResourceType,\n EnumNotificationType,\n EnumSubscriptionStatus,\n EnumUserLicence,\n vendorLicences,\n} from \"@timardex/cluemart-shared\";\nimport dayjs from \"dayjs\";\nimport type { Dayjs } from \"dayjs\";\n\nimport { SchemaUserType, UserModel } from \"src/mongoose/User\";\nimport { SchemaVendorType, VendorModel } from \"src/mongoose/vendor/Vendor\";\nimport { ObjectId } from \"src/types\";\n\nimport {\n getHighestLicenceForCategory,\n LicenceCategory,\n licencePriority,\n} from \"../models\";\n\nimport {\n hasValidLicence,\n sendDeactivationNotification,\n syncUserLicencesAfterExpiry,\n} from \"./utils\";\n\n/**\n * Fetches the live vendor referenced by a user's `vendor` field.\n * Returns null when the user has no vendor, or when the referenced vendor is not\n * live (active), has been soft-deleted, or is no longer owned by the user — the\n * same constraints used elsewhere in this module, so a stale `user.vendor`\n * reference never triggers feature downgrade/restore writes.\n */\nasync function findUserVendor(\n userId: ObjectId,\n logLabel: string,\n): Promise<SchemaVendorType | null> {\n const user = await UserModel.findById(userId).select(\"vendor\").lean().exec();\n\n if (!user?.vendor) {\n console.warn(`[${logLabel}] No vendor found for userId=${userId}`);\n return null;\n }\n\n const vendor = await VendorModel.findOne({\n _id: user.vendor,\n active: true,\n deletedAt: null,\n \"owner.userId\": userId,\n })\n .lean<SchemaVendorType>()\n .exec();\n\n if (!vendor) {\n console.warn(\n `[${logLabel}] Vendor not found for id=${user.vendor}, userId=${userId}`,\n );\n return null;\n }\n\n return vendor;\n}\n\n/**\n * Applies the STANDARD_VENDOR feature downgrade to an already-resolved vendor.\n * The write is guarded by the same live-vendor constraints used by\n * findUserVendor, so it no-ops atomically if the vendor was deactivated or\n * soft-deleted between the read and the write. Returns true when a matching\n * live vendor was actually updated.\n */\nasync function applyVendorDowngrade(\n vendor: SchemaVendorType,\n ownerUserId: ObjectId,\n): Promise<boolean> {\n /**\n * Build vendor update payload\n */\n const updateData: Partial<SchemaVendorType> = {};\n\n updateData.availability = {\n corporate: false,\n private: false,\n school: false,\n };\n\n updateData.products = {\n active: false,\n productsList: vendor.products?.productsList ?? [],\n };\n\n updateData.calendar = {\n active: false,\n calendarData: vendor.calendar?.calendarData ?? [],\n };\n\n /**\n * Preserve the pre-downgrade state so a later PRO upgrade can restore the\n * vendor's own configuration (a vendor may have had some PRO features\n * disabled before being downgraded) instead of blindly re-enabling them.\n * Raw (possibly undefined) values are stored, so absent features fall back\n * to their enabled default during restore rather than being forced off.\n */\n updateData.downgradeSnapshot = {\n availability: vendor.availability,\n calendarActive: vendor.calendar?.active,\n productsActive: vendor.products?.active,\n };\n\n /**\n * Image rules\n * STANDARD_VENDOR => only first 6 active, 6 is the default image limit for standard vendors\n */\n updateData.images = (vendor.images ?? []).map((image, index) => ({\n ...image,\n active: index < 6,\n }));\n\n /**\n * Persist vendor updates\n */\n const result = await VendorModel.updateOne(\n {\n _id: vendor._id,\n active: true,\n deletedAt: null,\n \"owner.userId\": ownerUserId,\n },\n { $set: updateData },\n );\n\n return (result?.matchedCount ?? 0) > 0;\n}\n\nexport async function downgradeVendorProFeatures(\n userId: ObjectId,\n licenceType: EnumUserLicence,\n): Promise<void> {\n /**\n * This function only handles STANDARD_VENDOR (feature downgrade). PRO/PLUS\n * upgrades are handled by restoreVendorProFeatures, so return early before\n * touching the user/vendor models.\n */\n const isStandardVendor = licenceType === EnumUserLicence.STANDARD_VENDOR;\n\n if (!isStandardVendor) {\n return;\n }\n\n try {\n const vendor = await findUserVendor(userId, \"downgradeVendorProFeatures\");\n\n if (!vendor) {\n return;\n }\n\n await applyVendorDowngrade(vendor, userId);\n } catch (error) {\n console.error(\"[downgradeVendorProFeatures] Failed:\", error);\n throw error;\n }\n}\n\n/**\n * Applies the PRO feature restore to an already-resolved vendor. The write is\n * guarded by the same live-vendor constraints used by findUserVendor, so it\n * no-ops atomically if the vendor was deactivated or soft-deleted between the\n * read and the write. Returns true when a matching live vendor was actually\n * updated.\n */\nasync function applyVendorRestore(\n vendor: SchemaVendorType,\n ownerUserId: ObjectId,\n): Promise<boolean> {\n /**\n * Build vendor update payload\n */\n const updateData: Partial<SchemaVendorType> = {};\n\n const snapshot = vendor.downgradeSnapshot;\n\n updateData.availability = {\n corporate: snapshot?.availability?.corporate ?? true,\n private: snapshot?.availability?.private ?? true,\n school: snapshot?.availability?.school ?? true,\n };\n\n updateData.products = {\n active: snapshot?.productsActive ?? true,\n productsList: vendor.products?.productsList ?? [],\n };\n\n updateData.calendar = {\n active: snapshot?.calendarActive ?? true,\n calendarData: vendor.calendar?.calendarData ?? [],\n };\n\n updateData.images = (vendor.images ?? []).map((image) => ({\n ...image,\n active: true,\n }));\n\n /**\n * Persist vendor updates\n */\n const result = await VendorModel.updateOne(\n {\n _id: vendor._id,\n active: true,\n deletedAt: null,\n \"owner.userId\": ownerUserId,\n },\n { $set: updateData },\n );\n\n return (result?.matchedCount ?? 0) > 0;\n}\n\n/**\n * Restores the PRO vendor features that are removed by\n * downgradeVendorProFeatures when a vendor is downgraded to STANDARD_VENDOR.\n * This is the opposite operation: it re-enables availability, products and\n * calendar from the pre-downgrade snapshot (falling back to fully enabled when\n * no snapshot exists), and keeps all images active.\n */\nexport async function restoreVendorProFeatures(\n userId: ObjectId,\n licenceType: EnumUserLicence,\n): Promise<void> {\n /**\n * Only PRO_VENDOR / PRO_PLUS_VENDOR restore the vendor's PRO features. Any\n * other licence (STANDARD_VENDOR, event/partner tiers, etc.) is a no-op, so\n * return early before touching the user/vendor models.\n */\n const isProVendor =\n licenceType === EnumUserLicence.PRO_VENDOR ||\n licenceType === EnumUserLicence.PRO_PLUS_VENDOR;\n\n if (!isProVendor) {\n return;\n }\n\n try {\n const vendor = await findUserVendor(userId, \"restoreVendorProFeatures\");\n\n if (!vendor) {\n return;\n }\n\n await applyVendorRestore(vendor, userId);\n } catch (error) {\n console.error(\"[restoreVendorProFeatures] Failed:\", error);\n throw error;\n }\n}\n\nfunction isProtectedByCurrentStripeSubscription(\n user: SchemaUserType,\n licenceType: EnumUserLicence,\n now: Dayjs,\n): boolean {\n const stripe = user.stripe;\n if (!stripe || stripe.currentPlan !== licenceType) {\n return false;\n }\n\n const gracePeriodEndsAt = stripe.paymentGracePeriodEndsAt\n ? dayjs(stripe.paymentGracePeriodEndsAt)\n : null;\n const hasActivePaymentGracePeriod =\n (stripe.status === EnumSubscriptionStatus.PAST_DUE ||\n stripe.status === EnumSubscriptionStatus.INACTIVE) &&\n Boolean(stripe.paymentGraceSubscriptionId) &&\n (!stripe.subscriptionId ||\n stripe.subscriptionId === stripe.paymentGraceSubscriptionId) &&\n gracePeriodEndsAt !== null &&\n gracePeriodEndsAt.isValid() &&\n gracePeriodEndsAt.isAfter(now);\n\n if (hasActivePaymentGracePeriod) {\n return true;\n }\n\n if (!stripe.subscriptionId) {\n return false;\n }\n\n if (stripe.status !== EnumSubscriptionStatus.ACTIVE) {\n return false;\n }\n\n if (!stripe.endDate) {\n return false;\n }\n\n const paidThrough = dayjs(stripe.endDate);\n return paidThrough.isValid() && paidThrough.isAfter(now);\n}\n\n/**\n * Handles vendor licence compliance for a single user\n */\nexport async function handleVendorLicenceCompliance(\n user: SchemaUserType,\n now: Dayjs,\n): Promise<void> {\n if (!user.licences || !user.vendor) {\n return;\n }\n\n const vendorLicencesOfUser = user.licences.filter((licence) =>\n licence?.licenceType?.includes(\"vendor\"),\n );\n\n if (vendorLicencesOfUser.length === 0) {\n return;\n }\n\n const proLicences = vendorLicencesOfUser.filter(\n (licence) => licence.licenceType !== EnumUserLicence.STANDARD_VENDOR,\n );\n\n const expiredProLicences = proLicences.filter(\n (licence) => !dayjs(licence.expiryDate).isAfter(now),\n );\n\n const stripeProtectedLicenceTypes = new Set(\n expiredProLicences\n .filter((licence) =>\n isProtectedByCurrentStripeSubscription(user, licence.licenceType, now),\n )\n .map((licence) => licence.licenceType),\n );\n\n const expiredProLicence = expiredProLicences.some(\n (licence) => !stripeProtectedLicenceTypes.has(licence.licenceType),\n );\n\n const hasValidProLicence =\n stripeProtectedLicenceTypes.size > 0 ||\n hasValidLicence(proLicences, vendorLicences, now);\n\n const hasExpiredVendorLicence = vendorLicencesOfUser.some(\n (licence) =>\n !dayjs(licence.expiryDate).isAfter(now) &&\n !stripeProtectedLicenceTypes.has(licence.licenceType),\n );\n\n if (!hasExpiredVendorLicence) {\n return;\n }\n\n // Resolve the vendor up-front only when a PRO licence actually expired, so the\n // PRO-downgrade-and-notify path never runs without a vendor to update/notify.\n // A STANDARD-only expiry skips this lookup entirely (no vendor mutation happens).\n // The active:true + deletedAt:null filter matches getVendorResourceInfo and the\n // rest of the codebase: a soft-deleted (deleteVendor) or admin-deactivated\n // (applyAdminResourceActiveUpdate) vendor must not be downgraded/notified, since\n // there is no live vendor to update or notify about. Commit 384f31d removed these\n // conditions as \"redundant\", but deleteVendor's clearOwnerResourceOnDelete unset\n // of user.vendor is not atomic with the soft-delete, and admin deactivation never\n // unsets user.vendor — so an inactive vendor can still be referenced here.\n let vendor: SchemaVendorType | null = null;\n if (expiredProLicence) {\n vendor = await VendorModel.findOne({\n _id: user.vendor,\n active: true,\n deletedAt: null,\n \"owner.userId\": user._id,\n })\n .lean<SchemaVendorType>()\n .exec();\n }\n\n // Extend expired STANDARD_VENDOR and downgrade expired PRO_*/PRO_PLUS_*\n // atomically, regardless of vendor presence. The currently paid Stripe tier\n // is excluded while it remains ACTIVE and within its paid-through\n // period; pending transitions are therefore left for Stripe reconciliation.\n // When the vendor is missing or inactive, eligible PRO entries are still\n // downgraded, but the feature update + notification below are skipped.\n const licencesToSync = vendorLicences.filter(\n (licenceType) => !stripeProtectedLicenceTypes.has(licenceType),\n );\n await syncUserLicencesAfterExpiry(user._id, licencesToSync, now, \"downgrade\");\n\n // Only downgrade the vendor + notify when a PRO licence actually expired AND the\n // user has no remaining valid PRO licence AND the vendor is present/active.\n if (!expiredProLicence || !vendor || hasValidProLicence) {\n return;\n }\n\n const downgraded = await applyVendorDowngrade(vendor, user._id);\n\n // The vendor was resolved above, but it may have been deactivated or\n // soft-deleted between the read and the write. Only notify when the update\n // actually matched a live vendor, so the notification never claims a\n // downgrade that didn't happen.\n if (!downgraded) {\n return;\n }\n\n const payload = {\n data: {\n resourceId: String(vendor._id),\n resourceName: vendor.name,\n resourceType: EnumNotificationResourceType.DOWNGRADED_VENDOR,\n },\n message: `Your Vendor licence has been downgraded due to licence expiration.`,\n title: `Vendor Licence Downgraded`,\n type: EnumNotificationType.SYSTEM,\n userIds: [user._id],\n };\n\n await sendDeactivationNotification(payload, user._id, vendor.name, \"vendor\");\n}\n\n/**\n * Checks whether a vendor's owner currently holds a PRO (or higher) vendor licence.\n */\nexport async function vendorOwnerHasProLicence(\n vendorId: string,\n): Promise<boolean> {\n const vendor = await VendorModel.findOne({\n _id: vendorId,\n active: true,\n deletedAt: null,\n })\n .lean<SchemaVendorType>()\n .exec();\n\n if (!vendor) {\n return false;\n }\n\n const owner = await UserModel.findById(vendor.owner.userId, {\n licences: 1,\n stripe: 1,\n })\n .lean()\n .exec();\n\n if (!owner) {\n return false;\n }\n\n const now = dayjs();\n const effectiveVendorLicences = owner.licences?.filter(\n (licence) =>\n licence?.licenceType &&\n (dayjs(licence.expiryDate).isAfter(now) ||\n isProtectedByCurrentStripeSubscription(\n owner,\n licence.licenceType,\n now,\n )),\n );\n\n const highestVendorLicence = getHighestLicenceForCategory(\n effectiveVendorLicences,\n LicenceCategory.VENDOR,\n );\n\n return (\n highestVendorLicence !== null &&\n licencePriority[highestVendorLicence] >=\n licencePriority[EnumUserLicence.PRO_VENDOR]\n );\n}\n","import {\n EnumResourceType,\n EnumUserLicence,\n isNonVisitorResourceType,\n LicenceExpiryDate,\n NonVisitorResourceType,\n UserLicenceType,\n} from \"@timardex/cluemart-shared\";\nimport dayjs from \"dayjs\";\nimport { GraphQLError } from \"graphql\";\n\nimport { SchemaUserType, UserModel } from \"src/mongoose/User\";\nimport { ObjectId } from \"src/types\";\n\nexport enum LicenceCategory {\n EVENT = \"event\",\n PARTNER = \"partner\",\n VENDOR = \"vendor\",\n AFFILIATE = \"affiliate\",\n SCHOOL = \"school\",\n}\n\nexport const licenceCategoryMapping: Record<EnumUserLicence, LicenceCategory> =\n {\n [EnumUserLicence.PRO_EVENT]: LicenceCategory.EVENT,\n [EnumUserLicence.PRO_PLUS_EVENT]: LicenceCategory.EVENT,\n [EnumUserLicence.PRO_PLUS_VENDOR]: LicenceCategory.VENDOR,\n [EnumUserLicence.PRO_VENDOR]: LicenceCategory.VENDOR,\n [EnumUserLicence.STANDARD_EVENT]: LicenceCategory.EVENT,\n [EnumUserLicence.STANDARD_PARTNER]: LicenceCategory.PARTNER,\n [EnumUserLicence.STANDARD_VENDOR]: LicenceCategory.VENDOR,\n [EnumUserLicence.STANDARD_AFFILIATE]: LicenceCategory.AFFILIATE,\n [EnumUserLicence.STANDARD_SCHOOL]: LicenceCategory.SCHOOL,\n };\n\nexport const licencePriority: Record<EnumUserLicence, number> = {\n [EnumUserLicence.PRO_PLUS_EVENT]: 3,\n [EnumUserLicence.PRO_EVENT]: 2,\n [EnumUserLicence.STANDARD_EVENT]: 1,\n [EnumUserLicence.PRO_PLUS_VENDOR]: 3,\n [EnumUserLicence.PRO_VENDOR]: 2,\n [EnumUserLicence.STANDARD_VENDOR]: 1,\n [EnumUserLicence.STANDARD_PARTNER]: 1,\n [EnumUserLicence.STANDARD_AFFILIATE]: 1,\n [EnumUserLicence.STANDARD_SCHOOL]: 1,\n};\n\nconst standardLicences = [\n EnumUserLicence.STANDARD_VENDOR,\n EnumUserLicence.STANDARD_EVENT,\n EnumUserLicence.STANDARD_PARTNER,\n] as const;\n\nconst standardLicenceSet = new Set<EnumUserLicence>(standardLicences);\n\nexport function isStandardLicence(\n licence: EnumUserLicence,\n): licence is (typeof standardLicences)[number] {\n return standardLicenceSet.has(licence);\n}\n\nconst categoryRegexMapping: Record<LicenceCategory, RegExp> = {\n [LicenceCategory.EVENT]: /_event$/,\n [LicenceCategory.PARTNER]: /_partner$/,\n [LicenceCategory.VENDOR]: /_vendor$/,\n [LicenceCategory.AFFILIATE]: /_affiliate$/,\n [LicenceCategory.SCHOOL]: /_school$/,\n};\n\nconst categoryFallbackLicence: Record<LicenceCategory, EnumUserLicence> = {\n [LicenceCategory.EVENT]: EnumUserLicence.STANDARD_EVENT,\n [LicenceCategory.PARTNER]: EnumUserLicence.STANDARD_PARTNER,\n [LicenceCategory.VENDOR]: EnumUserLicence.STANDARD_VENDOR,\n [LicenceCategory.AFFILIATE]: EnumUserLicence.STANDARD_AFFILIATE,\n [LicenceCategory.SCHOOL]: EnumUserLicence.STANDARD_SCHOOL,\n};\n\nconst LicenceFilterInput = {\n INPUT_USER_LICENCES: \"$licences\",\n} as const;\n\ntype LicenceFilterInputType =\n (typeof LicenceFilterInput)[keyof typeof LicenceFilterInput];\n\ntype LicenceReplacePipelineArgs = {\n fallbackType: EnumUserLicence;\n inputField: LicenceFilterInputType;\n licenceObject: UserLicenceType;\n typeRegex: RegExp;\n};\n\ntype LicenceUpgradeArgs = {\n expiryDate: LicenceExpiryDate;\n licenceType: EnumUserLicence;\n userId: ObjectId;\n};\n\ntype LicenceUpgradeResult = {\n licenceObject: UserLicenceType;\n updatedUser: SchemaUserType | null;\n};\n\nexport function getLicenceCategory(licence: EnumUserLicence): LicenceCategory {\n const category = licenceCategoryMapping[licence];\n\n if (!category) {\n throw new Error(`Missing licence category mapping for ${licence}`);\n }\n\n return category;\n}\n\nexport function getHighestLicenceForCategory(\n licences: UserLicenceType[] | null | undefined,\n category: LicenceCategory,\n): EnumUserLicence | null {\n const categoryLicences = (licences ?? [])\n .map((licence) => licence.licenceType)\n .filter((licenceType): licenceType is EnumUserLicence =>\n Boolean(licenceType && getLicenceCategory(licenceType) === category),\n );\n\n let highestLicence: EnumUserLicence | null = null;\n let highestPriority = Number.NEGATIVE_INFINITY;\n\n for (const licenceType of categoryLicences) {\n const priority = licencePriority[licenceType];\n if (priority > highestPriority) {\n highestPriority = priority;\n highestLicence = licenceType;\n }\n }\n\n return highestLicence;\n}\n\nexport function createLicenceObject(\n expiryDate: LicenceExpiryDate,\n licenceType: EnumUserLicence,\n): UserLicenceType {\n const today = dayjs();\n const expiryDateMapping: Record<LicenceExpiryDate, Date> = {\n [LicenceExpiryDate.ONE_YEAR]: today.add(1, \"year\").endOf(\"day\").toDate(),\n [LicenceExpiryDate.ONE_MONTH]: today.add(1, \"month\").endOf(\"day\").toDate(),\n [LicenceExpiryDate.TWO_MONTHS]: today.add(2, \"month\").endOf(\"day\").toDate(),\n [LicenceExpiryDate.THREE_MONTHS]: today\n .add(3, \"month\")\n .endOf(\"day\")\n .toDate(),\n [LicenceExpiryDate.SIX_MONTHS]: today.add(6, \"month\").endOf(\"day\").toDate(),\n };\n const licenceObject: UserLicenceType = {\n expiryDate: expiryDateMapping[expiryDate],\n issuedDate: today.toDate(),\n licenceType: licenceType,\n };\n return licenceObject;\n}\n\n/**\n * Builds an aggregation pipeline to replace a user's license while preserving other licenses of different types.\n * It filters out existing licenses that match the specified type regex and appends the new license object.\n * @param fallbackType - A fallback license type used when existing licenses don't have a defined type.\n * @param licenceObject - The new license object to be added to the user's licenses.\n * @param typeRegex - A regular expression used to identify licenses of the same type that should be replaced.\n * @returns An array representing the aggregation pipeline for updating the user's licenses.\n */\nconst buildLicenceReplacePipeline = ({\n fallbackType,\n inputField,\n licenceObject,\n typeRegex,\n}: LicenceReplacePipelineArgs) => [\n {\n $set: {\n licences: {\n $concatArrays: [\n {\n $filter: {\n as: \"licence\",\n cond: {\n $not: {\n $regexMatch: {\n input: {\n $toString: {\n $ifNull: [\"$$licence.licenceType\", fallbackType],\n },\n },\n regex: typeRegex,\n },\n },\n },\n input: { $ifNull: [inputField, []] },\n },\n },\n [licenceObject],\n ],\n },\n },\n },\n];\n\nexport async function replaceUserLicenceWithObject({\n userId,\n licenceObject,\n protectHigherLicence = true,\n refreshExistingLicence = false,\n}: {\n userId: ObjectId;\n licenceObject: UserLicenceType;\n protectHigherLicence?: boolean;\n refreshExistingLicence?: boolean;\n}) {\n const user = await UserModel.findById(userId, { licences: 1 }).lean();\n\n if (!user) throw new GraphQLError(\"User not found\");\n\n const existingLicence = user.licences?.find(\n (licence) => licence.licenceType === licenceObject.licenceType,\n );\n\n if (existingLicence && !refreshExistingLicence) {\n return;\n }\n\n const category = getLicenceCategory(licenceObject.licenceType);\n const updatedLicenceObject = {\n ...licenceObject,\n prevLicenceType:\n existingLicence && refreshExistingLicence\n ? existingLicence.prevLicenceType\n : user.licences?.find(\n (licence) =>\n licence.licenceType &&\n getLicenceCategory(licence.licenceType) === category,\n )?.licenceType,\n };\n\n if (protectHigherLicence) {\n const highestLicence = getHighestLicenceForCategory(\n user.licences,\n category,\n );\n if (\n highestLicence &&\n licencePriority[highestLicence] >\n licencePriority[updatedLicenceObject.licenceType]\n ) {\n return;\n }\n }\n\n await UserModel.updateOne(\n { _id: userId },\n buildLicenceReplacePipeline({\n fallbackType: categoryFallbackLicence[category],\n inputField: LicenceFilterInput.INPUT_USER_LICENCES,\n licenceObject: updatedLicenceObject,\n typeRegex: categoryRegexMapping[category],\n }),\n );\n}\n\n/**\n * Upgrades a user's license by adding a new license object to their account.\n * It calculates the expiry date based on the provided expiry duration and updates the user's licenses in the database.\n * @param licenceType - The licence type to upgrade the user to.\n * @param expiryDate - The expiry duration for the license being upgraded.\n * @param userId - The ID of the user whose license is being upgraded.\n * @returns An object containing the updated user and the new license object.\n */\nexport const upgradeUserToLicence = async ({\n licenceType,\n expiryDate,\n userId,\n}: LicenceUpgradeArgs): Promise<LicenceUpgradeResult> => {\n const licenceObject = createLicenceObject(expiryDate, licenceType);\n\n await replaceUserLicenceWithObject({ licenceObject, userId });\n\n const user = await UserModel.findById(userId).exec();\n\n return {\n licenceObject,\n updatedUser: user,\n };\n};\n\nexport async function checkOwnerHasLicence({\n userId,\n resourceType,\n}: {\n userId: ObjectId;\n resourceType: EnumResourceType;\n}): Promise<void> {\n try {\n const owner = await UserModel.findById(userId);\n if (!owner) throw new GraphQLError(\"Owner not found\");\n\n const categoryByResource: Record<NonVisitorResourceType, LicenceCategory> =\n {\n [EnumResourceType.EVENT]: LicenceCategory.EVENT,\n [EnumResourceType.PARTNER]: LicenceCategory.PARTNER,\n [EnumResourceType.VENDOR]: LicenceCategory.VENDOR,\n [EnumResourceType.AFFILIATE]: LicenceCategory.AFFILIATE,\n [EnumResourceType.SCHOOL]: LicenceCategory.SCHOOL,\n };\n\n if (!isNonVisitorResourceType(resourceType)) {\n throw new GraphQLError(`Invalid resource type: ${resourceType}.`);\n }\n\n const requiredCategory = categoryByResource[resourceType];\n\n const activeLicence = owner.licences?.some((licence) => {\n if (!licence.licenceType) return false;\n return getLicenceCategory(licence.licenceType) === requiredCategory;\n });\n\n if (!activeLicence) {\n throw new GraphQLError(\n `Owner does not have an active licence. Cannot update ${resourceType}.`,\n );\n }\n } catch (error) {\n // Re-throw GraphQLErrors as-is\n if (error instanceof GraphQLError) {\n throw error;\n }\n // Convert database or other errors to GraphQLError\n throw new GraphQLError(\n error instanceof Error\n ? `Failed to check user licence: ${error.message}`\n : \"Failed to check user licence\",\n );\n }\n}\n","import { EventModel, SchemaEventType } from \"src/mongoose/event/Event\";\nimport { ObjectId } from \"src/types\";\n\n/**\n * Gets event resource information for a reminder\n */\nexport async function getEventResourceInfo(\n userId: ObjectId,\n eventIds: ObjectId[],\n): Promise<{ resourceId: string; resourceName: string } | null> {\n const event = await EventModel.findOne({\n _id: { $in: eventIds },\n active: true,\n deletedAt: null,\n \"owner.userId\": userId,\n })\n .lean<SchemaEventType>()\n .exec();\n\n if (!event) {\n return null;\n }\n\n return {\n resourceId: String(event._id),\n resourceName: event.name,\n };\n}\n","import { PartnerModel, SchemaPartnerType } from \"src/mongoose/Partner\";\nimport { ObjectId } from \"src/types\";\n\n/**\n * Gets partner resource information for a reminder\n */\nexport async function getPartnerResourceInfo(\n userId: ObjectId,\n partnerId: ObjectId,\n): Promise<{ resourceId: string; resourceName: string } | null> {\n const partner = await PartnerModel.findOne({\n _id: partnerId,\n active: true,\n deletedAt: null,\n \"owner.userId\": userId,\n })\n .lean<SchemaPartnerType>()\n .exec();\n\n if (!partner) {\n return null;\n }\n\n return {\n resourceId: String(partner._id),\n resourceName: partner.name,\n };\n}\n","import dayjs from \"dayjs\";\n\nimport { UserModel } from \"src/mongoose/User\";\n\nimport {\n REMINDER_WINDOW_MAX_HOURS,\n REMINDER_WINDOW_MIN_HOURS,\n} from \"./reminderWindow\";\nimport { processUserLicenseReminders } from \"./utils\";\n\n/**\n * Sends license expiration reminders to users whose licenses expire in 7 days\n */\nexport async function remindUsersAboutLicenseExpiration(): Promise<void> {\n const now = dayjs();\n console.log(`🔍 Checking for licenses expiring in 7 days at ${now.format()}`);\n\n // Calculate date range: 6.5 to 7.5 days from now (matches isLicenseExpiringIn7Days filter).\n // Use hours instead of fractional days: dayjs `add(6.5, \"day\")` rounds to 7 days\n // and `add(7.5, \"day\")` rounds to 8 days, which silently shifted the reminder window.\n const minExpiryDate = now.add(REMINDER_WINDOW_MIN_HOURS, \"hour\").toDate(); // 6.5 days\n const maxExpiryDate = now.add(REMINDER_WINDOW_MAX_HOURS, \"hour\").toDate(); // 7.5 days\n\n // Only fetch users with licenses expiring within the reminder window\n // $elemMatch already implies the array exists and is not empty\n const users = await UserModel.find({\n licences: {\n $elemMatch: {\n expiryDate: {\n $gte: minExpiryDate,\n $lte: maxExpiryDate,\n },\n },\n },\n });\n\n console.log(\n `📊 Found ${users.length} users with licenses expiring in 7 days`,\n );\n\n if (!users.length) {\n console.log(\"No users with licenses to process.\");\n return;\n }\n\n let totalReminderCount = 0;\n\n for (const user of users) {\n try {\n const reminderCount = await processUserLicenseReminders(user, now);\n totalReminderCount += reminderCount;\n } catch (err) {\n console.error(\n `❌ Error processing license reminders for user ${String(user._id)}:`,\n err instanceof Error ? err.message : err,\n );\n // Continue processing other users even if one fails\n }\n }\n\n console.log(\n `✅ Processed ${users.length} users, sent ${totalReminderCount} license expiration reminders`,\n );\n}\n","/**\n * License expiration reminder window bounds.\n *\n * A licence qualifies for the \"7 days before expiry\" reminder when its expiry is\n * between {@link REMINDER_WINDOW_MIN_HOURS} and {@link REMINDER_WINDOW_MAX_HOURS}\n * away.\n *\n * Expressed in hours (derived from days) because dayjs rounds fractional \"day\"\n * adds: `now.add(6.5, \"day\")` becomes 7 days and `now.add(7.5, \"day\")` 8 days.\n */\nexport const REMINDER_WINDOW_MIN_HOURS = 6.5 * 24; // 156 hours\nexport const REMINDER_WINDOW_MAX_HOURS = 7.5 * 24; // 180 hours\n","import {\n dateFormat,\n EnumNotificationResourceType,\n EnumNotificationType,\n EnumUserLicence,\n licenseNiceNames,\n UserLicenceType,\n vendorLicences,\n} from \"@timardex/cluemart-shared\";\nimport { formatDate } from \"@timardex/cluemart-shared/utils\";\nimport dayjs from \"dayjs\";\n\nimport { SchemaUserType, UserModel } from \"src/mongoose/User\";\nimport { ObjectId } from \"src/types\";\n\nimport { sendPushNotifications } from \"../../sendPushNotifications\";\nimport { eventLicences, partnerLicences } from \"../compliance\";\n\nimport { getEventResourceInfo } from \"./event\";\nimport { getPartnerResourceInfo } from \"./partner\";\nimport {\n REMINDER_WINDOW_MAX_HOURS,\n REMINDER_WINDOW_MIN_HOURS,\n} from \"./reminderWindow\";\nimport { getVendorResourceInfo } from \"./vendor\";\n\n/**\n * Checks whether a matching notification exists and inserts one if not, via\n * `findOneAndUpdate` + `upsert` + `$setOnInsert`.\n *\n * **Concurrency:** Upsert alone does not guarantee a single insert under parallel\n * workers unless a **unique** index covers the same fields as `query` (otherwise two\n * operations can both insert). Treat duplicate prevention as requiring that index\n * (or a deterministic `_id`), not upsert semantics by themselves.\n *\n * Uses direct MongoDB access. The inserted document includes the fields needed for\n * a complete notification row.\n *\n * @returns `true` if the notification already existed (or on error, assumed sent),\n * `false` if this call inserted it\n */\nasync function checkAndCreateNotification(payload: {\n data: {\n resourceId: string;\n resourceName: string;\n resourceType: EnumNotificationResourceType;\n };\n message: string;\n title: string;\n type: EnumNotificationType;\n userIds: ObjectId[];\n}): Promise<boolean> {\n // Build query to check if notification already exists\n const query: any = {\n message: payload.message,\n title: payload.title,\n userId: payload.userIds[0],\n };\n\n if (payload.data.resourceId) {\n query[\"data.resourceId\"] = payload.data.resourceId;\n }\n\n // Build the complete notification document to insert if it doesn't exist\n // This includes all required fields for a complete notification\n const notificationDoc: any = {\n createdAt: new Date(),\n data: payload.data,\n isRead: false,\n message: payload.message,\n title: payload.title,\n type: payload.type,\n userId: payload.userIds[0],\n };\n\n // Upsert is not duplicate-proof under concurrency without a matching unique index\n try {\n const result = await UserModel.db\n .collection(\"notifications\")\n .findOneAndUpdate(\n query,\n { $setOnInsert: notificationDoc },\n {\n includeResultMetadata: true,\n returnDocument: \"after\",\n upsert: true,\n },\n );\n\n // Check if the document was inserted (upserted) or already existed\n // If lastErrorObject.upserted exists, the document was just inserted\n const wasInserted = result?.lastErrorObject?.upserted != null;\n\n // If document was inserted, this is the first time (not already sent)\n // If document already existed, notification was already sent\n return !wasInserted;\n } catch (error) {\n // If upsert fails, assume notification already exists to be safe\n console.error(\n `❌ Error atomically checking notification:`,\n error instanceof Error ? error.message : error,\n );\n return true; // Assume already sent to prevent duplicates\n }\n}\n\n/**\n * Checks if a license expires in exactly 7 days (within a day range)\n *\n * Uses a 1-day window (6.5 to 7.5 days) to account for job timing variations.\n * Since the reminder job runs daily at noon (every 24 hours), a license expiring\n * at 6.5 days from now could receive a reminder, and then when the job runs again\n * 24 hours later (at 5.5 days remaining), it would fall outside the window.\n *\n * This ensures reminders are sent once within the 6.5-7.5 day window, not\n * guaranteed to be exactly 7 days before expiration. Duplicate prevention is\n * handled atomically in sendLicenseReminder to prevent race conditions.\n */\nfunction isLicenseExpiringIn7Days(\n expiryDate: Date | string,\n now: dayjs.Dayjs,\n): boolean {\n const expiry = dayjs(expiryDate);\n // Check if expiry is within the reminder window (hours before expiry).\n // Uses hours to stay consistent with the DB query window in\n // remindUsersAboutLicenseExpiration (dayjs rounds fractional \"day\" adds).\n const hoursUntilExpiry = expiry.diff(now, \"hour\", true);\n return (\n hoursUntilExpiry >= REMINDER_WINDOW_MIN_HOURS &&\n hoursUntilExpiry <= REMINDER_WINDOW_MAX_HOURS\n );\n}\n\n/**\n * Gets a human-readable license name\n */\nfunction getLicenseName(licenceType: EnumUserLicence): string {\n return licenseNiceNames[licenceType] || licenceType;\n}\n\n/**\n * Gets notification types based on license type\n */\nfunction getNotificationTypes(\n isVendorLicense: boolean,\n isPartnerLicense: boolean,\n): {\n notificationType: EnumNotificationType;\n resourceType: EnumNotificationResourceType;\n} {\n if (isVendorLicense) {\n return {\n notificationType: EnumNotificationType.SYSTEM,\n resourceType: EnumNotificationResourceType.EXPIRATION_REMINDER_VENDOR,\n };\n }\n if (isPartnerLicense) {\n return {\n notificationType: EnumNotificationType.SYSTEM,\n resourceType: EnumNotificationResourceType.EXPIRATION_REMINDER_PARTNER,\n };\n }\n return {\n notificationType: EnumNotificationType.SYSTEM,\n resourceType: EnumNotificationResourceType.EXPIRATION_REMINDER_EVENT,\n };\n}\n\n/**\n * Gets resource information for a license reminder\n */\nasync function getLicenseResourceInfo(\n user: {\n _id: ObjectId;\n vendor?: ObjectId;\n events?: ObjectId[];\n partner?: ObjectId;\n },\n licence: { licenceType: EnumUserLicence },\n): Promise<{\n notificationType: EnumNotificationType;\n resourceId: string;\n resourceName: string;\n resourceType: EnumNotificationResourceType;\n} | null> {\n const isVendorLicense = vendorLicences.includes(licence.licenceType);\n const isPartnerLicense = partnerLicences.includes(licence.licenceType);\n const licenceName = getLicenseName(licence.licenceType);\n const { notificationType, resourceType } = getNotificationTypes(\n isVendorLicense,\n isPartnerLicense,\n );\n\n if (isVendorLicense && user.vendor) {\n const vendorInfo = await getVendorResourceInfo(user._id, user.vendor);\n if (!vendorInfo) {\n return null;\n }\n return {\n ...vendorInfo,\n notificationType,\n resourceType,\n };\n }\n\n if (eventLicences.includes(licence.licenceType) && user.events?.length) {\n const eventInfo = await getEventResourceInfo(user._id, user.events);\n if (!eventInfo) {\n return null;\n }\n return {\n ...eventInfo,\n notificationType,\n resourceType,\n };\n }\n\n if (isPartnerLicense && user.partner) {\n const partnerInfo = await getPartnerResourceInfo(user._id, user.partner);\n if (!partnerInfo) {\n return null;\n }\n return {\n ...partnerInfo,\n notificationType,\n resourceType,\n };\n }\n\n // Fallback: use license name and user ID\n return {\n notificationType,\n resourceId: String(user._id),\n resourceName: licenceName,\n resourceType,\n };\n}\n\n/**\n * Single source of truth for how a licence type is handled on expiry.\n *\n * - \"downgrade\": PRO_VENDOR / PRO_PLUS_VENDOR → downgraded to STANDARD_VENDOR.\n * - \"extend\": every other licence type is auto-extended for another year.\n *\n * Note: `cluemart-server`'s `licenceCategoryMapping` / `licencePriority`\n * (ModelHelpers/licenses/index.ts) is a SEPARATE concern (entitlement priority,\n * not expiry behaviour) and is intentionally not merged here.\n */\nexport function getLicenceExpiryMode(\n licenceType: EnumUserLicence,\n): \"downgrade\" | \"extend\" {\n return licenceType === EnumUserLicence.PRO_VENDOR ||\n licenceType === EnumUserLicence.PRO_PLUS_VENDOR\n ? \"downgrade\"\n : \"extend\";\n}\n\n/**\n * Sends a reminder notification for a license.\n *\n * Intentionally does NOT use the shared `notifyUsers` helper: that helper\n * persists via `saveNotificationsInDb` (plain `insertMany`), whereas this job\n * must claim the dedupe slot atomically through\n * {@link checkAndCreateNotification} (upsert) so a reminder is only sent once.\n * Push is therefore sent directly via `sendPushNotifications` only after the\n * claim succeeds.\n */\nexport async function sendLicenseReminder(\n user: {\n _id: ObjectId;\n vendor?: ObjectId;\n events?: ObjectId[];\n partner?: ObjectId;\n },\n licence: { licenceType: EnumUserLicence; expiryDate: Date | string },\n): Promise<void> {\n const licenceName = getLicenseName(licence.licenceType);\n const expiryDate = dayjs(licence.expiryDate).format(dateFormat);\n const userId = String(user._id);\n\n const resourceInfo = await getLicenseResourceInfo(user, licence);\n\n if (!resourceInfo) {\n console.log(\n `⏭️ Skipping 7-day reminder for user ${userId}, license ${licence.licenceType} (no resource info)`,\n );\n return;\n }\n\n const isExtension = getLicenceExpiryMode(licence.licenceType) === \"extend\";\n\n const payload = {\n data: {\n resourceId: resourceInfo.resourceId,\n resourceName: resourceInfo.resourceName,\n resourceType: resourceInfo.resourceType,\n },\n message: isExtension\n ? `Your ${licenceName} will be automatically extended for another year on ${formatDate(expiryDate, \"date\")}.`\n : `Your ${licenceName} expires in 7 days (${formatDate(expiryDate, \"date\")}). Renew now to avoid deactivation.`,\n title: isExtension ? \"Licence Extension Reminder\" : \"Licence Expiring Soon\",\n type: resourceInfo.notificationType,\n userIds: [user._id],\n };\n\n // Atomically check and create notification to prevent race conditions\n // If notification already exists, skip sending to avoid duplicates\n const alreadyExists = await checkAndCreateNotification(payload);\n if (alreadyExists) {\n console.log(\n `⏭️ Skipping 7-day reminder to user ${userId} for ${licenceName} (notification already exists)`,\n );\n return;\n }\n\n // Notification was successfully created atomically. Now send push notification.\n await sendPushNotifications(payload);\n console.log(`✅ Sent 7-day reminder to user ${userId} for ${licenceName}`);\n}\n\n/**\n * Processes a single license and sends reminder if needed\n *\n * Checks if a license expires within the 6.5-7.5 day window and hasn't already\n * received a reminder. See isLicenseExpiringIn7Days for details on the reminder window.\n *\n * @returns true if a reminder should be sent, false otherwise\n */\nexport async function processLicenseReminder(\n licence: { licenceType: EnumUserLicence; expiryDate: Date | string },\n now: dayjs.Dayjs,\n): Promise<boolean> {\n // Skip if license is already expired\n if (dayjs(licence.expiryDate).isBefore(now)) {\n return false;\n }\n\n // Check if license expires in 7 days (within 6.5-7.5 day window)\n if (!isLicenseExpiringIn7Days(licence.expiryDate, now)) {\n return false;\n }\n\n // Note: Duplicate checking is handled atomically in sendLicenseReminder\n // to prevent race conditions when multiple job instances run concurrently\n return true;\n}\n\n/**\n * Sends a reminder for a single license, handling errors gracefully\n */\nexport async function sendReminderSafely(\n user: {\n _id: ObjectId;\n vendor?: ObjectId;\n events?: ObjectId[];\n partner?: ObjectId;\n },\n licence: UserLicenceType,\n): Promise<boolean> {\n try {\n await sendLicenseReminder(user, licence);\n return true;\n } catch (err) {\n console.error(\n `❌ Error sending reminder to user ${String(user._id)} for license ${licence.licenceType}:`,\n err instanceof Error ? err.message : err,\n );\n return false;\n }\n}\n\n/**\n * Processes reminders for a single user's licenses\n */\nexport async function processUserLicenseReminders(\n user: SchemaUserType,\n now: dayjs.Dayjs,\n): Promise<number> {\n if (!user.licences) {\n return 0;\n }\n\n // Filter out null/undefined licenses before processing\n const validLicences = user.licences.filter((licence) => licence !== null);\n\n if (validLicences.length === 0) {\n return 0;\n }\n\n const licenceChecks = await Promise.all(\n validLicences.map(async (licence) => {\n try {\n const shouldSend = await processLicenseReminder(licence, now);\n return { licence, shouldSend };\n } catch (err) {\n console.error(\n `❌ Error checking license reminder for user ${String(user._id)} for license ${licence.licenceType}:`,\n err instanceof Error ? err.message : err,\n );\n // Return false to skip this license but continue processing others\n return { licence, shouldSend: false };\n }\n }),\n );\n\n const licencesToNotify = licenceChecks\n .filter((check) => check.shouldSend)\n .map((check) => check.licence);\n\n if (!licencesToNotify.length) {\n return 0;\n }\n\n // Process reminders individually to prevent one failure from blocking others\n const results = await Promise.all(\n licencesToNotify.map((licence) => sendReminderSafely(user, licence)),\n );\n\n return results.filter(Boolean).length;\n}\n","import { SchemaVendorType, VendorModel } from \"src/mongoose/vendor/Vendor\";\nimport { ObjectId } from \"src/types\";\n\n/**\n * Gets vendor resource information for a reminder\n */\nexport async function getVendorResourceInfo(\n userId: ObjectId,\n vendorId: ObjectId,\n): Promise<{ resourceId: string; resourceName: string } | null> {\n const vendor = await VendorModel.findOne({\n _id: vendorId,\n active: true,\n deletedAt: null,\n \"owner.userId\": userId,\n })\n .lean<SchemaVendorType>()\n .exec();\n\n if (!vendor) {\n return null;\n }\n return {\n resourceId: String(vendor._id),\n resourceName: vendor.name,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;AACO,IAAM,4BAA4B;AAAA,EACvC,QAAQ;AAAA,EACR,WAAW;AACb;;;ACSA,eAAsB,0BACpB,eACkB;AAClB,QAAM,WAAW,MAAM,eAAe,OAAO;AAAA,IAC3C,GAAG;AAAA,IACH;AAAA,EACF,CAAC,EAAE,KAAK;AAER,SAAO,aAAa;AACtB;;;ACtBA;AAAA,EAGE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,6BAA6B;;;ACGtC,eAAsB,sBACpB,SACqB;AACrB,QAAM,EAAE,MAAM,SAAS,OAAO,MAAM,QAAQ,IAAI;AAChD,UAAQ,IAAI,qBAAqB,KAAK,UAAU,SAAS,MAAM,CAAC,CAAC;AACjE,MAAI;AACF,UAAM,gBAAgB,QAAQ,IAAI,CAAC,YAAY;AAAA,MAC7C;AAAA,MACA,QAAQ;AAAA,MACR;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF,EAAE;AAGF,UAAM,kBAAkB,WAAW,aAAa;AAChD,YAAQ;AAAA,MACN,WAAW,cAAc,MAAM,sBAAsB,QAAQ,MAAM;AAAA,IACrE;AAEA,WAAO,CAAC,GAAG,IAAI,IAAI,OAAO,CAAC;AAAA,EAC7B,SAAS,OAAO;AACd,YAAQ,MAAM,mCAAmC,KAAK;AACtD,WAAO,CAAC;A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,YAAM,gBAAgB,MAAM,4BAA4B,MAAM,GAAG;AACjE,4BAAsB;AAAA,IACxB,SAAS,KAAK;AACZ,cAAQ;AAAA,QACN,sDAAiD,OAAO,KAAK,GAAG,CAAC;AAAA,QACjE,eAAe,QAAQ,IAAI,UAAU;AAAA,MACvC;AAAA,IAEF;AAAA,EACF;AAEA,UAAQ;AAAA,IACN,oBAAe,MAAM,MAAM,gBAAgB,kBAAkB;AAAA,EAC/D;AACF;","names":["EnumUserLicence","EnumUserLicence","mongoose","EnumEventDateStatus","dayjs","dayjs","EnumEventDateStatus","dayjs","EnumUserLicence","dayjs","EnumUserLicence","EnumUserLicence","EnumUserLicence","EnumUserLicence","EnumNotificationResourceType","EnumNotificationType","EnumSubscriptionStatus","EnumUserLicence","dayjs","EnumResourceType","EnumUserLicence","dayjs","LicenceCategory","EnumUserLicence","dayjs","EnumResourceType","EnumUserLicence","dayjs","EnumSubscriptionStatus","EnumNotificationResourceType","EnumNotificationType","EnumUserLicence","dayjs","dayjs","dayjs","dateFormat","EnumNotificationResourceType","EnumNotificationType","EnumUserLicence","vendorLicences","dayjs","dayjs","EnumNotificationType","EnumNotificationResourceType","vendorLicences","EnumUserLicence","dateFormat","dayjs"]}
1
+ {"version":3,"sources":["../../src/service/promoCode/constants.ts","../../src/service/affiliate/activeAffiliateCodeExists.ts","../../src/service/affiliate/awardAffiliateVendorSubscriptionRewards.ts","../../src/service/saveNotificationsInDb.ts","../../src/service/sendPushNotifications.ts","../../src/service/affiliate/vendorSubscriptionRewards.ts","../../src/service/license/stripe/stripe.ts","../../src/service/affiliate/findAffiliateByPromoCode.ts","../../src/service/promoCode/normalizePromoCode.ts","../../src/service/affiliate/normalizeAffiliatePromoCodes.ts","../../src/service/database.ts","../../src/service/notifyUsers.ts","../../src/service/updateAdStatus.ts","../../src/service/objectIdToString.ts","../../src/service/event/updateAllEventDateTimeStatuses.ts","../../src/service/event/archiveEndedEventDates.ts","../../src/service/index.ts","../../src/service/event/findEventOrImportedMarketById.ts","../../src/service/relations.ts","../../src/service/license/compliance/ensureUserLicenseCompliance.ts","../../src/service/license/compliance/utils.ts","../../src/service/license/compliance/event.ts","../../src/service/license/compliance/licenceExpiryPipeline.ts","../../src/service/license/compliance/partner.ts","../../src/service/license/compliance/vendor.ts","../../src/service/license/models.ts","../../src/service/license/reminder/event.ts","../../src/service/license/reminder/partner.ts","../../src/service/license/reminder/remindUsersAboutLicenseExpiration.ts","../../src/service/license/reminder/reminderWindow.ts","../../src/service/license/reminder/utils.ts","../../src/service/license/reminder/vendor.ts"],"sourcesContent":["/** Matches partial unique indexes for promo/affiliate codes on active documents. */\nexport const ACTIVE_NOT_DELETED_FILTER = {\n active: true,\n deletedAt: null,\n} as const;\n","import { AffiliateModel } from \"src/mongoose\";\n\nimport { ACTIVE_NOT_DELETED_FILTER } from \"../promoCode/constants\";\n\n/**\n * Checks whether an affiliate code is already taken by an active, non-deleted affiliate.\n *\n * Used when generating new affiliate codes so collisions are avoided before insert.\n * Matches the partial unique index on `affiliateCode` for active documents.\n *\n * @param affiliateCode - Candidate affiliate promo code to check.\n * @returns `true` when an active, non-deleted affiliate already uses this code.\n */\nexport async function activeAffiliateCodeExists(\n affiliateCode: string,\n): Promise<boolean> {\n const existing = await AffiliateModel.exists({\n ...ACTIVE_NOT_DELETED_FILTER,\n affiliateCode,\n }).exec();\n\n return existing !== null;\n}\n","import {\n AffiliateResourceType,\n EnumAffiliateRewardType,\n EnumNotificationResourceType,\n EnumNotificationType,\n EnumResourceType,\n} from \"@timardex/cluemart-shared\";\nimport { createAffiliateReward } from \"@timardex/cluemart-shared/utils\";\n\nimport { AffiliateModel, SchemaOwnerType, VendorModel } from \"src/mongoose\";\nimport { ObjectId } from \"src/types\";\n\nimport { saveNotificationsInDb } from \"../saveNotificationsInDb\";\nimport { sendPushNotifications } from \"../sendPushNotifications\";\n\nimport {\n getSubscriptionRewardPeriodBounds,\n mapVendorLicenceToSubscriptionRewardType,\n} from \"./vendorSubscriptionRewards\";\n\nexport type AwardAffiliateVendorSubscriptionRewardsResult = {\n awarded: number;\n skipped: number;\n};\n\ntype LeanAffiliateResource = Omit<\n AffiliateResourceType,\n \"resourceId\" | \"resourceOwner\" | \"rewards\"\n> & {\n resourceId: ObjectId;\n resourceOwner: SchemaOwnerType;\n};\n\ntype LeanAffiliate = {\n _id: ObjectId;\n affiliateResources: LeanAffiliateResource[];\n owner: SchemaOwnerType;\n};\n\ntype PeriodBounds = {\n periodEnd: Date;\n periodStart: Date;\n};\n\ntype AwardSummary = {\n resourceName: string;\n rewardValue: number;\n};\n\nfunction isEligibleVendorResource(resource: LeanAffiliateResource): boolean {\n return (\n resource.resourceType === EnumResourceType.VENDOR &&\n resource.resourceActive === true &&\n resource.resourceDeletedAt == null\n );\n}\n\nasync function findAffiliatesWithActiveVendorReferrals(): Promise<\n LeanAffiliate[]\n> {\n return (await AffiliateModel.find({\n active: true,\n affiliateResources: {\n $elemMatch: {\n resourceActive: true,\n resourceDeletedAt: null,\n resourceType: EnumResourceType.VENDOR,\n },\n },\n deletedAt: null,\n })\n .select(\"_id affiliateResources owner\")\n .lean()\n .exec()) as LeanAffiliate[];\n}\n\nasync function isEligibleReferredVendor({\n resourceId,\n resourceOwnerUserId,\n}: {\n resourceId: ObjectId;\n resourceOwnerUserId: ObjectId | string;\n}): Promise<boolean> {\n const match = await VendorModel.exists({\n _id: resourceId,\n active: true,\n deletedAt: null,\n \"owner.userId\": resourceOwnerUserId,\n }).exec();\n\n return Boolean(match);\n}\n\nasync function notifyAffiliateOwnerOfSubscriptionReward({\n affiliateId,\n affiliateOwnerUserId,\n awards,\n}: {\n affiliateId: ObjectId | string;\n affiliateOwnerUserId: ObjectId | string;\n awards: AwardSummary[];\n}): Promise<void> {\n if (awards.length === 0) {\n return;\n }\n\n const totalPoints = awards.reduce((sum, award) => sum + award.rewardValue, 0);\n const resourceNames = awards.map((award) => award.resourceName);\n const pointLabel = totalPoints === 1 ? \"point\" : \"points\";\n const message =\n awards.length === 1\n ? `You earned ${totalPoints} ${pointLabel}! Your referred vendor \"${resourceNames[0]}\" has an active subscription.`\n : `You earned ${totalPoints} ${pointLabel}! ${awards.length} of your referred vendors have an active subscription.`;\n\n const payload = {\n data: {\n resourceId: String(affiliateId),\n resourceName: resourceNames.join(\", \"),\n resourceType: EnumNotificationResourceType.AFFILIATE_REWARD_RECEIVED,\n },\n message,\n title: \"Affiliate points earned\",\n type: EnumNotificationType.SYSTEM,\n userIds: [affiliateOwnerUserId as ObjectId],\n };\n\n try {\n await saveNotificationsInDb(payload);\n await sendPushNotifications(payload);\n } catch (error) {\n console.error(\n `[affiliate] subscription reward notification failed for affiliate ${String(affiliateId)}:`,\n error instanceof Error ? error.message : error,\n );\n }\n}\n\nasync function tryAwardSubscriptionReward({\n affiliate,\n createdAt,\n period,\n resource,\n rewardType,\n}: {\n affiliate: LeanAffiliate;\n createdAt: Date;\n period: PeriodBounds;\n resource: LeanAffiliateResource;\n rewardType: EnumAffiliateRewardType;\n}): Promise<AwardSummary | null> {\n const reward = createAffiliateReward(rewardType, createdAt);\n\n const updateResult = await AffiliateModel.updateOne(\n {\n _id: affiliate._id,\n affiliateResources: {\n $elemMatch: {\n resourceActive: true,\n resourceDeletedAt: null,\n resourceId: resource.resourceId,\n resourceType: EnumResourceType.VENDOR,\n rewards: {\n $not: {\n $elemMatch: {\n createdAt: {\n $gte: period.periodStart,\n $lt: period.periodEnd,\n },\n },\n },\n },\n },\n },\n deletedAt: null,\n },\n {\n $inc: { overallPoints: reward.rewardValue },\n $push: { \"affiliateResources.$.rewards\": reward },\n },\n ).exec();\n\n if (updateResult.modifiedCount === 0) {\n return null;\n }\n\n return {\n resourceName: resource.resourceName,\n rewardValue: reward.rewardValue,\n };\n}\n\nasync function processAffiliateVendorReferral({\n affiliate,\n createdAt,\n now,\n period,\n resource,\n}: {\n affiliate: LeanAffiliate;\n createdAt: Date;\n now: Date;\n period: PeriodBounds;\n resource: LeanAffiliateResource;\n}): Promise<AwardSummary | null> {\n const vendorEligible = await isEligibleReferredVendor({\n resourceId: resource.resourceId,\n resourceOwnerUserId: resource.resourceOwner.userId,\n });\n if (!vendorEligible) {\n return null;\n }\n\n const rewardType = await mapVendorLicenceToSubscriptionRewardType(\n resource.resourceOwner.userId,\n now,\n );\n if (!rewardType) {\n return null;\n }\n\n return tryAwardSubscriptionReward({\n affiliate,\n createdAt,\n period,\n resource,\n rewardType,\n });\n}\n\n/**\n * Awards monthly vendor subscription rewards to affiliates with active referred vendors.\n *\n * Eligibility per affiliate resource:\n * - Affiliate is active and not soft-deleted\n * - Linked `affiliateResources` entry is vendor, `resourceActive`, and not deleted\n * - Vendor is active, not deleted, and `owner.userId` matches\n * `affiliateResources.resourceOwner.userId`\n * - `affiliateResources.resourceOwner` has a non-expired Standard / Pro / Pro+ vendor licence\n *\n * Reward type follows the owner's highest valid licence + Stripe paying status:\n * - Pro / Pro+ with paying Stripe (ACTIVE) → `ACTIVE_VENDOR_PRO_SUBSCRIPTION` (3 pts)\n * - Pro / Pro+ without paying Stripe → `ACTIVE_VENDOR_STANDARD_SUBSCRIPTION` (1 pt)\n * - Standard → `ACTIVE_VENDOR_STANDARD_SUBSCRIPTION` (1 pt)\n *\n * Idempotent per affiliate + vendor + calendar month — a mid-month licence\n * upgrade (Standard → paying Pro) takes effect from the following month.\n * On successful awards, sends the affiliate owner a single aggregated\n * notification per run (best-effort).\n *\n * @param now - Reference time for month bounds and licence expiry (defaults to now).\n * @returns Counts of awarded and skipped candidates.\n */\nexport async function awardAffiliateVendorSubscriptionRewards(\n now: Date = new Date(),\n): Promise<AwardAffiliateVendorSubscriptionRewardsResult> {\n const period = getSubscriptionRewardPeriodBounds(now);\n const createdAt = now;\n const affiliates = await findAffiliatesWithActiveVendorReferrals();\n\n let awarded = 0;\n let skipped = 0;\n\n for (const affiliate of affiliates) {\n const awards: AwardSummary[] = [];\n const seenPairs = new Set<string>();\n\n for (const resource of affiliate.affiliateResources) {\n if (!isEligibleVendorResource(resource)) {\n continue;\n }\n\n const pairKey = `${String(affiliate._id)}:${String(resource.resourceId)}`;\n if (seenPairs.has(pairKey)) {\n continue;\n }\n seenPairs.add(pairKey);\n\n const award = await processAffiliateVendorReferral({\n affiliate,\n createdAt,\n now,\n period,\n resource,\n });\n\n if (award) {\n awarded += 1;\n awards.push(award);\n } else {\n skipped += 1;\n }\n }\n\n if (awards.length > 0) {\n await notifyAffiliateOwnerOfSubscriptionReward({\n affiliateId: affiliate._id,\n affiliateOwnerUserId: affiliate.owner.userId,\n awards,\n });\n }\n }\n\n return { awarded, skipped };\n}\n","import {\n SchemaCreateBulkNotificationInput,\n NotificationModel,\n} from \"src/mongoose/Notification\";\nimport { ObjectId } from \"src/types\";\n\n/**\n * Create notifications in the database for multiple users\n * This is typically called when sending push notifications\n */\nexport async function saveNotificationsInDb(\n payload: SchemaCreateBulkNotificationInput,\n): Promise<ObjectId[]> {\n const { data, message, title, type, userIds } = payload;\n const notifications = userIds.map((userId) => ({\n data,\n isRead: false,\n message,\n title,\n type,\n userId,\n }));\n\n try {\n await NotificationModel.insertMany(notifications);\n } catch (error) {\n console.error(\"Failed to create notifications:\", error);\n throw error;\n }\n\n console.log(\n `Created ${notifications.length} notifications for ${userIds.length} users`,\n );\n\n return [...new Set(userIds)];\n}\n","import { NotificationDataType } from \"@timardex/cluemart-shared\";\nimport { Expo, ExpoPushMessage, ExpoPushTicket } from \"expo-server-sdk\";\n\nimport { SchemaCreateBulkNotificationInput } from \"src/mongoose/Notification\";\nimport { PushTokenModel } from \"src/mongoose/PushToken\";\n\nconst expo = new Expo();\n\n/**\n * Safely extract tokens from ExpoPushMessage handling both string and array cases\n */\nfunction extractTokensFromMessage(message: ExpoPushMessage): string[] {\n return Array.isArray(message.to) ? message.to : [message.to];\n}\n\ninterface CreatePushMessagesOptions {\n tokens: string[];\n message: string;\n title: string;\n data: NotificationDataType | null;\n}\n\n/**\n * Create push messages from valid tokens\n */\nfunction createPushMessages({\n tokens,\n message,\n title,\n data,\n}: CreatePushMessagesOptions): {\n messages: ExpoPushMessage[];\n invalidTokens: string[];\n} {\n const messages: ExpoPushMessage[] = [];\n const invalidTokens: string[] = [];\n\n for (const token of tokens) {\n if (!Expo.isExpoPushToken(token)) {\n invalidTokens.push(token);\n continue;\n }\n\n messages.push({\n body: message,\n ...(data ? { data: { ...data } } : {}),\n sound: \"tui.wav\",\n title,\n to: token,\n });\n }\n\n return { invalidTokens, messages };\n}\n\n/**\n * Process chunk results and extract failed tokens\n */\nfunction processChunkResults(\n tickets: ExpoPushTicket[],\n chunk: ExpoPushMessage[],\n): { successCount: number; failedTokens: string[] } {\n let successCount = 0;\n const failedTokens: string[] = [];\n\n for (const [ticketIndex, ticket] of tickets.entries()) {\n if (ticket.status === \"error\") {\n const message = chunk[ticketIndex];\n if (message) {\n const tokens = extractTokensFromMessage(message);\n if (ticket.details?.error === \"DeviceNotRegistered\") {\n failedTokens.push(...tokens);\n }\n console.log(\"Push notification error\", {\n error: ticket.details?.error,\n tokens,\n });\n }\n } else {\n successCount++;\n }\n }\n\n return { failedTokens, successCount };\n}\n\n/**\n * Send a single chunk of push notifications\n */\nasync function sendChunk(\n chunk: ExpoPushMessage[],\n chunkIndex: number,\n): Promise<{ successCount: number; failedTokens: string[] }> {\n try {\n const tickets = await expo.sendPushNotificationsAsync(chunk);\n const { successCount, failedTokens } = processChunkResults(tickets, chunk);\n\n console.log(\n `Chunk ${chunkIndex + 1}: Sent ${successCount}/${chunk.length} notifications successfully`,\n );\n\n return { failedTokens, successCount };\n } catch (error) {\n console.log(\"Error sending Expo push notification chunk\", {\n chunkIndex,\n chunkSize: chunk.length,\n error: error instanceof Error ? error.message : String(error),\n });\n return { failedTokens: [], successCount: 0 };\n }\n}\n\nexport async function sendPushNotifications({\n data,\n message,\n title,\n userIds,\n}: SchemaCreateBulkNotificationInput) {\n const pushTokens = await PushTokenModel.find({ userId: { $in: userIds } });\n const expoTokens = pushTokens.map((token) => token.token);\n\n const { messages, invalidTokens } = createPushMessages({\n data,\n message,\n title,\n tokens: expoTokens,\n });\n\n // Log invalid tokens\n if (invalidTokens.length > 0) {\n console.log(`Found ${invalidTokens.length} invalid push tokens`);\n }\n\n if (messages.length === 0) {\n console.log(\"No valid messages to send after filtering tokens\");\n return;\n }\n\n // Send notifications in chunks\n const chunks = expo.chunkPushNotifications(messages);\n let totalSuccessCount = 0;\n const allFailedTokens: string[] = [];\n\n for (const [chunkIndex, chunk] of chunks.entries()) {\n const { successCount, failedTokens } = await sendChunk(\n chunk,\n chunkIndex + 1,\n );\n totalSuccessCount += successCount;\n allFailedTokens.push(...failedTokens);\n }\n\n // Log final results\n console.log(\n `Sent push notification to ${totalSuccessCount}/${messages.length} tokens across ${chunks.length} chunks`,\n );\n\n if (allFailedTokens.length > 0) {\n console.log(`Found ${allFailedTokens.length} failed push tokens`);\n }\n}\n","import {\n EnumAffiliateRewardType,\n EnumUserLicence,\n} from \"@timardex/cluemart-shared\";\nimport dayjs from \"dayjs\";\nimport timezone from \"dayjs/plugin/timezone\";\nimport utc from \"dayjs/plugin/utc\";\n\nimport { ObjectId } from \"src/types\";\n\nimport { getPayingVendorStripeSubscriptionPlan } from \"../license/stripe/stripe\";\n\ndayjs.extend(utc);\ndayjs.extend(timezone);\n\n/** Timezone the monthly reward window aligns to (matches the cron scheduler's `tz`). */\nexport const SUBSCRIPTION_REWARD_TIMEZONE = \"Pacific/Auckland\";\n\n/**\n * Maps a vendor owner's highest valid vendor licence to a monthly subscription reward.\n *\n * Prefer Pro / Pro+ over Standard when both are valid.\n * Pro / Pro+ only yields the Pro reward when the owner has an active Stripe subscription;\n * otherwise falls back to the Standard subscription reward.\n * Returns `null` when no non-expired vendor licence applies.\n */\nexport async function mapVendorLicenceToSubscriptionRewardType(\n userId: ObjectId | string,\n now: Date = new Date(),\n): Promise<EnumAffiliateRewardType | null> {\n const { hasSubscription, validTypes } =\n await getPayingVendorStripeSubscriptionPlan(userId, now);\n\n if (\n validTypes.has(EnumUserLicence.PRO_VENDOR) ||\n validTypes.has(EnumUserLicence.PRO_PLUS_VENDOR)\n ) {\n if (hasSubscription) {\n return EnumAffiliateRewardType.ACTIVE_VENDOR_PRO_SUBSCRIPTION;\n }\n return EnumAffiliateRewardType.ACTIVE_VENDOR_STANDARD_SUBSCRIPTION;\n }\n\n if (validTypes.has(EnumUserLicence.STANDARD_VENDOR)) {\n return EnumAffiliateRewardType.ACTIVE_VENDOR_STANDARD_SUBSCRIPTION;\n }\n\n return null;\n}\n\n/** Inclusive start / exclusive end of the {@link SUBSCRIPTION_REWARD_TIMEZONE} calendar month containing `now`. */\nexport function getSubscriptionRewardPeriodBounds(now: Date = new Date()): {\n periodEnd: Date;\n periodStart: Date;\n} {\n const periodStart = dayjs(now)\n .tz(SUBSCRIPTION_REWARD_TIMEZONE)\n .startOf(\"month\")\n .toDate();\n const periodEnd = dayjs(now)\n .tz(SUBSCRIPTION_REWARD_TIMEZONE)\n .startOf(\"month\")\n .add(1, \"month\")\n .toDate();\n return { periodEnd, periodStart };\n}\n","import {\n EnumSubscriptionStatus,\n EnumUserLicence,\n} from \"@timardex/cluemart-shared/enums\";\n\nimport { UserModel } from \"src/mongoose/User\";\nimport { ObjectId } from \"src/types\";\n\nconst PRO_EVENT_PLANS = new Set<EnumUserLicence>([\n EnumUserLicence.PRO_EVENT,\n EnumUserLicence.PRO_PLUS_EVENT,\n]);\n\nconst PRO_VENDOR_PLANS = new Set<EnumUserLicence>([\n EnumUserLicence.PRO_VENDOR,\n EnumUserLicence.PRO_PLUS_VENDOR,\n]);\n\nconst PRO_PLANS = new Set<EnumUserLicence>([\n ...PRO_EVENT_PLANS,\n ...PRO_VENDOR_PLANS,\n]);\n\ntype PayingStripeSubscriptionPlanResult = {\n hasSubscription: boolean;\n plan: EnumUserLicence | null;\n validTypes: Set<EnumUserLicence>;\n};\n\nasync function getPayingStripePlanFor(\n userId: ObjectId | string,\n now: Date,\n payingPlans: Set<EnumUserLicence>,\n): Promise<PayingStripeSubscriptionPlanResult> {\n const user = await UserModel.findById(userId)\n .select(\"licences stripe\")\n .lean()\n .exec();\n\n if (!user) {\n return { hasSubscription: false, plan: null, validTypes: new Set() };\n }\n\n const stripe = user.stripe;\n const licences = user.licences ?? [];\n\n const validTypes = new Set(\n licences\n .filter(\n (licence) => new Date(licence.expiryDate).getTime() > now.getTime(),\n )\n .map((licence) => licence.licenceType),\n );\n\n if (stripe == null || stripe.subscriptionId == null) {\n return { hasSubscription: false, plan: null, validTypes };\n }\n\n const hasActiveStatus = stripe.status === EnumSubscriptionStatus.ACTIVE;\n const paidThrough = stripe.endDate\n ? new Date(stripe.endDate).getTime()\n : Number.NaN;\n\n if (\n !hasActiveStatus ||\n !Number.isFinite(paidThrough) ||\n paidThrough <= now.getTime() ||\n stripe.currentPlan == null\n ) {\n return { hasSubscription: false, plan: null, validTypes };\n }\n\n const plan = payingPlans.has(stripe.currentPlan) ? stripe.currentPlan : null;\n\n return { hasSubscription: plan != null, plan, validTypes };\n}\n\n/**\n * Returns the paying Stripe plan when `currentPlan` is any PRO plan\n * (event or vendor), the subscription is active, and its finite paid-through\n * `endDate` is later than `now`. Status alone does not establish paid access.\n */\nexport async function getPayingStripeSubscriptionPlan(\n userId: ObjectId | string,\n now: Date = new Date(),\n): Promise<PayingStripeSubscriptionPlanResult> {\n return getPayingStripePlanFor(userId, now, PRO_PLANS);\n}\n\n/**\n * Like {@link getPayingStripeSubscriptionPlan} but only treats a vendor PRO\n * plan (`PRO_VENDOR` / `PRO_PLUS_VENDOR`) as paying.\n */\nexport async function getPayingVendorStripeSubscriptionPlan(\n userId: ObjectId | string,\n now: Date = new Date(),\n): Promise<PayingStripeSubscriptionPlanResult> {\n return getPayingStripePlanFor(userId, now, PRO_VENDOR_PLANS);\n}\n\n/**\n * Like {@link getPayingStripeSubscriptionPlan} but only treats an event PRO\n * plan (`PRO_EVENT` / `PRO_PLUS_EVENT`) as paying.\n */\nexport async function getPayingEventStripeSubscriptionPlan(\n userId: ObjectId | string,\n now: Date = new Date(),\n): Promise<PayingStripeSubscriptionPlanResult> {\n return getPayingStripePlanFor(userId, now, PRO_EVENT_PLANS);\n}\n","import { PromoCodeType } from \"@timardex/cluemart-shared\";\n\nimport { AffiliateModel } from \"src/mongoose\";\n\n/**\n * Loads the affiliate whose `affiliateCode` matches the given promo code.\n *\n * Affiliate codes are assigned on admin activation, so referrals only resolve after\n * a code exists. Soft-deleted affiliates (`deletedAt` set) are excluded.\n *\n * @param promoCode - Normalized affiliate promo code to resolve.\n * @returns The matching affiliate document, or `null` when not found.\n */\nexport async function findAffiliateByPromoCode(promoCode: PromoCodeType) {\n return AffiliateModel.findOne({\n affiliateCode: promoCode,\n deletedAt: null,\n }).exec();\n}\n","export function normalizePromoCode(\n decoratedPromoCode: string | null | undefined,\n): string | null {\n const normalized = decoratedPromoCode?.trim().toUpperCase();\n return normalized || null;\n}\n","import { PromoCodeType } from \"@timardex/cluemart-shared\";\n\nimport { normalizePromoCode } from \"../promoCode/normalizePromoCode\";\n\n/**\n * Normalizes, trims, uppercases, and deduplicates resource promo codes.\n *\n * @param promoCodes - Raw promo codes from a create-resource mutation input.\n * @returns Unique normalized codes; empty strings and whitespace-only values are removed.\n */\nexport function normalizeAffiliatePromoCodes(\n promoCodes: PromoCodeType[] | null | undefined,\n): PromoCodeType[] {\n const normalized = (promoCodes ?? [])\n .map((code) => normalizePromoCode(code))\n .filter((code): code is PromoCodeType => code !== null);\n\n return [...new Set(normalized)];\n}\n","import mongoose from \"mongoose\";\n\n/**\n * Connect to MongoDB using Mongoose.\n * Supports both local MongoDB (via MONGODB_URI) and MongoDB Atlas (via individual env vars).\n */\nexport const connectToDatabase = async ({\n appName,\n dbName,\n dbPassword,\n dbUser,\n mongodbUri,\n}: {\n appName: string;\n dbName: string;\n dbPassword: string;\n dbUser: string;\n mongodbUri: string;\n}) => {\n try {\n // Check if MONGODB_URI is provided (for local Docker MongoDB)\n const mongoUri = mongodbUri\n ? mongodbUri\n : // Fallback to MongoDB Atlas connection string\n `mongodb+srv://${dbUser}:${dbPassword}@${dbName}.mongodb.net/?retryWrites=true&w=majority&appName=${appName}`;\n\n await mongoose.connect(mongoUri);\n\n const connectionType = mongodbUri ? \"Local MongoDB\" : \"MongoDB Atlas\";\n console.log(\n `${connectionType} connected from server/src/service/database.ts`,\n );\n } catch (err) {\n console.error(\"Error connecting to MongoDB:\", err);\n throw err; // You can throw the error if you want to stop the server in case of connection failure\n }\n};\n","import {\n NotificationModel,\n SchemaCreateBulkNotificationInput,\n} from \"src/mongoose/Notification\";\nimport { EnumPubSubEvents, GraphQLContext, ObjectId } from \"src/types\";\n\nimport { saveNotificationsInDb } from \"./saveNotificationsInDb\";\nimport { sendPushNotifications } from \"./sendPushNotifications\";\n\n/**\n * Publish-only pubsub used to emit GraphQL subscription events. Optional in\n * {@link notifyUsers} because non-GraphQL processes (e.g. the cron worker) have\n * no subscribers to publish to.\n */\nexport type NotificationPubSub = Pick<GraphQLContext[\"pubsub\"], \"publish\">;\n\n/** Publishes notification list/count subscription events for a user. */\nexport async function publishNotificationEvents(\n userId: ObjectId,\n pubsub: NotificationPubSub,\n) {\n try {\n // Get user's notifications for the subscription\n const userNotifications = await NotificationModel.find({\n userId,\n }).sort({ createdAt: -1 });\n\n // Get notification count\n const [total, unread] = await Promise.all([\n NotificationModel.countDocuments({ userId }),\n NotificationModel.countDocuments({ isRead: false, userId }),\n ]);\n\n // Publish both events\n pubsub.publish(EnumPubSubEvents.GET_NOTIFICATIONS, {\n getNotifications: userNotifications,\n getNotificationsUserId: userId,\n });\n\n pubsub.publish(EnumPubSubEvents.GET_NOTIFICATIONS_COUNT, {\n getNotificationsCount: { total, unread, userId },\n });\n\n console.log(`Published notification events for user: ${String(userId)}`);\n } catch (error) {\n console.error(\n `Failed to publish notification events for user ${String(userId)}:`,\n error,\n );\n }\n}\n\n/**\n * Sends push notifications, saves them in the database, and (when a `pubsub`\n * is provided) publishes GraphQL subscription events for each affected user.\n *\n * Errors are logged and swallowed; this function never throws. Instead it\n * returns `false` when notifications were not confirmed, so callers can gate\n * success logs/metrics on the result.\n */\nexport async function notifyUsers({\n payload,\n pubsub,\n}: {\n payload: SchemaCreateBulkNotificationInput;\n pubsub?: NotificationPubSub;\n}): Promise<boolean> {\n try {\n await sendPushNotifications(payload);\n\n const uniqueUserIds = await saveNotificationsInDb(payload);\n const persisted = payload.userIds.length === 0 || uniqueUserIds.length > 0;\n\n if (pubsub) {\n for (const userId of uniqueUserIds) {\n await publishNotificationEvents(userId, pubsub);\n }\n }\n\n return persisted;\n } catch (error) {\n console.error(\"Error in notifyUsers:\", error);\n return false;\n }\n}\n","import {\n EnumAdApprovalStatus,\n EnumAdBookingSlotKind,\n EnumAdPaymentStatus,\n EnumAdStatus,\n} from \"@timardex/cluemart-shared\";\n\nimport { AdModel } from \"src/mongoose\";\n\n/**\n * Updates ad statuses based on start/end dates and validity\n */\nexport async function updateAdStatuses(): Promise<void> {\n const now = new Date();\n\n // invalid: normally `start`/`end` are always present, but `required` is only\n // enforced by Mongoose on writes through the app — legacy/corrupt docs (and\n // updateMany, which skips validation) can still miss them. Keep the `$exists`\n // guards so such docs get marked PAUSED instead of stuck in a non-terminal\n // status. A reversed window (start after end) is also invalid.\n const invalidResult = await AdModel.updateMany(\n {\n $or: [\n { start: { $exists: false } },\n { end: { $exists: false } },\n { $expr: { $gt: [\"$start\", \"$end\"] } },\n ],\n status: { $ne: EnumAdStatus.PAUSED },\n },\n { $set: { status: EnumAdStatus.PAUSED } },\n );\n\n // expired\n const expiredResult = await AdModel.updateMany(\n { end: { $lte: now }, status: { $ne: EnumAdStatus.EXPIRED } },\n { $set: { status: EnumAdStatus.EXPIRED } },\n );\n\n // Booking-backed ads must never be activated before payment and approval.\n // Ads without booking metadata belong to the existing admin-managed flow.\n const eligibleBooking = {\n $or: [\n { bookingKind: { $exists: false } },\n { bookingKind: null },\n {\n approvalStatus: EnumAdApprovalStatus.APPROVED,\n bookingKind: EnumAdBookingSlotKind.RESERVED,\n },\n {\n approvalStatus: EnumAdApprovalStatus.APPROVED,\n bookingKind: EnumAdBookingSlotKind.PAID,\n paymentStatus: EnumAdPaymentStatus.PAID,\n },\n ],\n };\n\n const awaitingApprovalResult = await AdModel.updateMany(\n {\n $nor: eligibleBooking.$or,\n bookingKind: { $in: Object.values(EnumAdBookingSlotKind) },\n end: { $gt: now },\n status: EnumAdStatus.ACTIVE,\n },\n { $set: { status: EnumAdStatus.PAUSED } },\n );\n\n // active\n const activeResult = await AdModel.updateMany(\n {\n end: { $gt: now },\n start: { $lte: now },\n status: { $ne: EnumAdStatus.ACTIVE },\n ...eligibleBooking,\n },\n { $set: { status: EnumAdStatus.ACTIVE } },\n );\n\n // paused\n const pausedResult = await AdModel.updateMany(\n { start: { $gt: now }, status: { $ne: EnumAdStatus.PAUSED } },\n { $set: { status: EnumAdStatus.PAUSED } },\n );\n\n console.log(\n `✅ Ad statuses updated: invalid=${invalidResult.modifiedCount}, expired=${expiredResult.modifiedCount}, awaitingApproval=${awaitingApprovalResult.modifiedCount}, active=${activeResult.modifiedCount}, paused=${pausedResult.modifiedCount}`,\n );\n}\n","import mongoose from \"mongoose\";\n\n/**\n * True when `value` is a valid Mongo ObjectId string.\n */\nexport function isValidObjectId(value: string): boolean {\n return mongoose.Types.ObjectId.isValid(value);\n}\n\n/**\n * Recursively converts all ObjectId fields to strings in an object\n * This is needed because GraphQL expects string IDs, not ObjectIds\n */\nexport function convertObjectIdsToStrings(obj: any): any {\n if (obj === null || obj === undefined) {\n return obj;\n }\n\n if (obj instanceof mongoose.Types.ObjectId) {\n return obj.toString();\n }\n\n if (obj instanceof Date) {\n return obj;\n }\n\n if (Array.isArray(obj)) {\n return obj.map(convertObjectIdsToStrings);\n }\n\n if (typeof obj === \"object\") {\n const converted: any = {};\n for (const [key, value] of Object.entries(obj)) {\n converted[key] = convertObjectIdsToStrings(value);\n }\n return converted;\n }\n\n return obj;\n}\n","import {\n DateTimeType,\n DateTimeWithPriceType,\n EnumEventDateStatus,\n filterDatesByFutureStatus,\n updateSingleDateTimeStatus,\n} from \"@timardex/cluemart-shared\";\nimport dayjs from \"dayjs\";\n\nimport {\n EventDateArchiveModel,\n EventInfoModel,\n EventModel,\n GoogleImportedMarketModel,\n} from \"src/mongoose\";\n\nimport {\n dedupeArchivedSlotsByStartDateTime,\n splitEventDatesForArchive,\n} from \"./archiveEndedEventDates\";\n\nconst dateTimeStatusFilter = {\n dateTime: { $ne: [], $type: \"array\" },\n deletedAt: null,\n} as const;\n\nconst CURSOR_BATCH_SIZE = 50;\n\ntype DocWithDateTime = {\n _id: unknown;\n dateTime: DateTimeType[];\n};\n\ntype DateTimeBulkWriteOp = {\n updateOne: {\n filter: { _id: unknown };\n update: { $set: { dateTime: DateTimeType[] } };\n };\n};\n\ntype EventInfoBulkWriteOp = {\n updateOne: {\n filter: { _id: unknown };\n update: { $set: { dateTime: DateTimeWithPriceType[] } };\n };\n};\n\ntype DateTimeCursor = AsyncIterable<DocWithDateTime> & {\n close: () => Promise<unknown>;\n};\n\ntype DateTimeUpdatableModel = {\n bulkWrite: (ops: DateTimeBulkWriteOp[]) => Promise<unknown>;\n find: (filter: typeof dateTimeStatusFilter) => {\n select: (fields: { _id: 1; dateTime: 1 }) => {\n lean: () => {\n cursor: (opts: { batchSize: number }) => DateTimeCursor;\n };\n };\n };\n};\n\nfunction hasDateTimeStatusChanges(\n stored: DateTimeType[],\n updated: DateTimeType[],\n): boolean {\n if (stored.length !== updated.length) {\n return true;\n }\n\n return stored.some(\n (slot, index) => slot.dateStatus !== updated[index].dateStatus,\n );\n}\n\nasync function updateModelDateTimeStatuses(\n model: DateTimeUpdatableModel,\n now: dayjs.Dayjs,\n): Promise<number> {\n let updated = 0;\n const cursor = model\n .find(dateTimeStatusFilter)\n .select({ _id: 1, dateTime: 1 })\n .lean()\n .cursor({ batchSize: CURSOR_BATCH_SIZE });\n\n let bulkOps: DateTimeBulkWriteOp[] = [];\n\n const flushBulkWrites = async (): Promise<void> => {\n if (!bulkOps.length) {\n return;\n }\n\n await model.bulkWrite(bulkOps);\n updated += bulkOps.length;\n bulkOps = [];\n };\n\n try {\n for await (const doc of cursor) {\n const dateTime = doc.dateTime.map((slot) =>\n updateSingleDateTimeStatus(slot, now),\n );\n\n if (!hasDateTimeStatusChanges(doc.dateTime, dateTime)) {\n continue;\n }\n\n bulkOps.push({\n updateOne: {\n filter: { _id: doc._id },\n update: { $set: { dateTime } },\n },\n });\n\n if (bulkOps.length >= CURSOR_BATCH_SIZE) {\n await flushBulkWrites();\n }\n }\n\n await flushBulkWrites();\n } finally {\n await cursor.close().catch(() => undefined);\n }\n\n return updated;\n}\n\nconst ARCHIVABLE_EVENT_FILTER = {\n \"dateTime.dateStatus\": {\n $in: [EnumEventDateStatus.ENDED, EnumEventDateStatus.INVALID],\n },\n deletedAt: null,\n} as const;\n\ntype ArchiveUpsertOp = {\n updateOne: {\n filter: { eventId: unknown };\n update: { $addToSet: { dateTime: { $each: DateTimeType[] } } };\n upsert: true;\n };\n};\n\ntype EventDatePullOp = {\n updateOne: {\n filter: { _id: unknown };\n update: {\n $pull: {\n dateTime: {\n dateStatus: {\n $in: EnumEventDateStatus[];\n };\n };\n };\n };\n };\n};\n\n/**\n * Moves ended event date slots into the archive, discards invalid slots, and\n * pulls both from `Event.dateTime`, keeping future and in-progress (`STARTED`)\n * dates live. Archive upserts and event `$pull` updates are collected into\n * bulkWrite batches to avoid per-document round-trips. The event write is a\n * targeted `$pull` (by status) rather than a full-array `$set`, so concurrent\n * schedule changes are not clobbered.\n */\nasync function archiveEndedAndDiscardInvalidEventDates(\n now: dayjs.Dayjs,\n): Promise<number> {\n const cursor = EventModel.find(ARCHIVABLE_EVENT_FILTER)\n .select({ _id: 1, dateTime: 1 })\n .lean()\n .cursor({ batchSize: CURSOR_BATCH_SIZE });\n\n let archivedCount = 0;\n let archiveOps: ArchiveUpsertOp[] = [];\n let eventOps: EventDatePullOp[] = [];\n\n const flushBulkWrites = async (): Promise<void> => {\n if (archiveOps.length) {\n await EventDateArchiveModel.bulkWrite(archiveOps);\n archiveOps = [];\n }\n\n if (eventOps.length) {\n await EventModel.bulkWrite(eventOps);\n eventOps = [];\n }\n };\n\n try {\n for await (const doc of cursor) {\n const updated = doc.dateTime.map((slot) =>\n updateSingleDateTimeStatus(slot, now),\n );\n\n const { archive, discard } = splitEventDatesForArchive(updated);\n if (archive.length === 0 && discard.length === 0) {\n continue;\n }\n\n if (archive.length > 0) {\n const uniqueArchive = dedupeArchivedSlotsByStartDateTime(archive);\n archiveOps.push({\n updateOne: {\n filter: { eventId: doc._id },\n update: { $addToSet: { dateTime: { $each: uniqueArchive } } },\n upsert: true,\n },\n });\n archivedCount += uniqueArchive.length;\n }\n\n eventOps.push({\n updateOne: {\n filter: { _id: doc._id },\n update: {\n $pull: {\n dateTime: {\n dateStatus: {\n $in: [EnumEventDateStatus.ENDED, EnumEventDateStatus.INVALID],\n },\n },\n },\n },\n },\n });\n\n if (\n archiveOps.length >= CURSOR_BATCH_SIZE ||\n eventOps.length >= CURSOR_BATCH_SIZE\n ) {\n await flushBulkWrites();\n }\n }\n\n await flushBulkWrites();\n } finally {\n await cursor.close().catch(() => undefined);\n }\n\n return archivedCount;\n}\n\nconst EVENT_INFO_DATE_FILTER = {\n dateTime: { $ne: [], $type: \"array\" },\n} as const;\n\n/**\n * Removes non-future (`STARTED`, `ENDED`, `INVALID`, `CANCELED`,\n * `RE_SCHEDULED`) slots from `EventInfo.dateTime` so the stored data stays in\n * sync with the future-only invariant used on writes. Updates are collected\n * into bulkWrite batches to avoid per-document round-trips.\n */\nasync function cleanEventInfoDates(now: dayjs.Dayjs): Promise<number> {\n const cursor = EventInfoModel.find(EVENT_INFO_DATE_FILTER)\n .select({ _id: 1, dateTime: 1 })\n .lean()\n .cursor({ batchSize: CURSOR_BATCH_SIZE });\n\n let removedCount = 0;\n let bulkOps: EventInfoBulkWriteOp[] = [];\n\n const flushBulkWrites = async (): Promise<void> => {\n if (!bulkOps.length) {\n return;\n }\n\n await EventInfoModel.bulkWrite(bulkOps);\n bulkOps = [];\n };\n\n try {\n for await (const doc of cursor) {\n const updated = (doc.dateTime as DateTimeWithPriceType[]).map((slot) =>\n updateSingleDateTimeStatus(slot, now),\n );\n\n const kept = filterDatesByFutureStatus(updated);\n if (kept.length === updated.length) {\n continue;\n }\n\n bulkOps.push({\n updateOne: {\n filter: { _id: doc._id },\n update: { $set: { dateTime: kept } },\n },\n });\n removedCount += updated.length - kept.length;\n\n if (bulkOps.length >= CURSOR_BATCH_SIZE) {\n await flushBulkWrites();\n }\n }\n\n await flushBulkWrites();\n } finally {\n await cursor.close().catch(() => undefined);\n }\n\n return removedCount;\n}\n\n/**\n * Recomputes dateStatus for every dateTime slot on events and google imported\n * markets, moves ended event date slots into the event date archive, and keeps\n * `EventInfo.dateTime` future-only.\n */\nexport async function updateAllEventDateTimeStatuses(): Promise<void> {\n const now = dayjs();\n const [eventCount, marketCount] = await Promise.all([\n updateModelDateTimeStatuses(EventModel as DateTimeUpdatableModel, now),\n updateModelDateTimeStatuses(\n GoogleImportedMarketModel as DateTimeUpdatableModel,\n now,\n ),\n ]);\n\n console.log(\n `✅ Event dateTime statuses updated: events=${eventCount} changed, google imported markets=${marketCount} changed`,\n );\n\n const archivedCount = await archiveEndedAndDiscardInvalidEventDates(now);\n if (archivedCount > 0) {\n console.log(`✅ Archived ${archivedCount} ended event date slot(s)`);\n }\n\n const removedEventInfoCount = await cleanEventInfoDates(now);\n if (removedEventInfoCount > 0) {\n console.log(\n `✅ Removed ${removedEventInfoCount} non-future event info date slot(s)`,\n );\n }\n}\n","import { DateTimeType, EnumEventDateStatus } from \"@timardex/cluemart-shared\";\n\nimport { EventDateArchiveModel } from \"src/mongoose\";\nimport { ObjectId } from \"src/types\";\n\nconst ARCHIVED_STATUSES: ReadonlySet<EnumEventDateStatus> = new Set([\n EnumEventDateStatus.ENDED,\n]);\n\nconst DISCARDED_STATUSES: ReadonlySet<EnumEventDateStatus> = new Set([\n EnumEventDateStatus.INVALID,\n]);\n\n/**\n * Splits a recomputed event schedule into three buckets: slots to keep on the\n * Event document (future + STARTED), ended slots to archive (`ENDED`), and\n * invalid slots to discard (`INVALID` — removed from the Event but *not*\n * archived). `Event.dateTime` may become empty once an event has no future or\n * in-progress dates.\n */\nexport function splitEventDatesForArchive(dateTime: DateTimeType[]): {\n archive: DateTimeType[];\n discard: DateTimeType[];\n keep: DateTimeType[];\n} {\n return {\n archive: dateTime.filter((slot) => ARCHIVED_STATUSES.has(slot.dateStatus)),\n discard: dateTime.filter((slot) => DISCARDED_STATUSES.has(slot.dateStatus)),\n keep: dateTime.filter(\n (slot) =>\n !ARCHIVED_STATUSES.has(slot.dateStatus) &&\n !DISCARDED_STATUSES.has(slot.dateStatus),\n ),\n };\n}\n\n/**\n * De-duplicates the *input* slots on (startDate, startTime), keeping the first\n * occurrence. This prevents a single write from appending near-duplicate\n * history (the archive's `$addToSet` only de-dupes by deep equality, not by\n * startDate/startTime). It does not scan or clean duplicates already stored in\n * the archive document.\n */\nexport function dedupeArchivedSlotsByStartDateTime(\n slots: DateTimeType[],\n): DateTimeType[] {\n const seen = new Set<string>();\n\n return slots.filter((slot) => {\n const key = `${slot.startDate}_${slot.startTime}`;\n if (seen.has(key)) {\n return false;\n }\n seen.add(key);\n return true;\n });\n}\n\n/**\n * Persists archived slots into the event's archive document. Idempotent: the\n * archive document is keyed per event and slots are appended with `$addToSet`.\n */\nexport async function persistArchivedEventDates(\n eventId: ObjectId | string,\n slots: DateTimeType[],\n): Promise<void> {\n if (slots.length === 0) {\n return;\n }\n\n const uniqueSlots = dedupeArchivedSlotsByStartDateTime(slots);\n\n await EventDateArchiveModel.updateOne(\n { eventId },\n { $addToSet: { dateTime: { $each: uniqueSlots } } },\n { upsert: true },\n );\n}\n","export * from \"./affiliate\";\nexport * from \"./database\";\nexport * from \"./promoCode/constants\";\nexport * from \"./promoCode/normalizePromoCode\";\nexport * from \"./notifyUsers\";\nexport * from \"./saveNotificationsInDb\";\nexport * from \"./sendPushNotifications\";\nexport * from \"./updateAdStatus\";\nexport * from \"./objectIdToString\";\nexport { updateAllEventDateTimeStatuses } from \"./event/updateAllEventDateTimeStatuses\";\nexport { updateSingleDateTimeStatus } from \"@timardex/cluemart-shared\";\nexport {\n dedupeArchivedSlotsByStartDateTime,\n persistArchivedEventDates,\n splitEventDatesForArchive,\n} from \"./event/archiveEndedEventDates\";\nexport * from \"./event/findEventOrImportedMarketById\";\nexport * from \"./relations\";\nexport {\n getPayingEventStripeSubscriptionPlan,\n getPayingStripeSubscriptionPlan,\n getPayingVendorStripeSubscriptionPlan,\n} from \"./license/stripe/stripe\";\nexport * from \"./license/compliance\";\nexport * from \"./license/reminder\";\nexport * from \"./license/models\";\n","import { EventListItemType } from \"@timardex/cluemart-shared\";\n\nimport {\n EventModel,\n GoogleImportedMarketModel,\n SchemaOwnerType,\n} from \"src/mongoose\";\nimport { ObjectId } from \"src/types\";\n\nimport { convertObjectIdsToStrings } from \"../objectIdToString\";\n\ntype EventOrMarket =\n | (Pick<EventListItemType, \"_id\" | \"name\" | \"dateTime\"> & {\n /** Present on owned EventModel docs; absent on Google-imported markets. */\n owner?: SchemaOwnerType;\n })\n | null;\n\n/**\n * This function attempts to find an Event or a Google Imported Market by the given resource ID.\n * It first normalizes the resource ID to a string format, then performs parallel queries to both collections.\n * If an Event is found, it returns that; otherwise, it checks for a Google Imported Market and returns it if found.\n * If neither is found, it returns null.\n * @param resourceId - The ID of the resource to find, which can be an ObjectId, string, null, or undefined.\n * @returns A promise that resolves to either an Event or a Google Imported Market object containing _id, name, dateTime, and owner (events only), or null if not found.\n */\n\nexport async function findEventOrImportedMarketById(\n resourceId: ObjectId | string | null | undefined,\n): Promise<EventOrMarket> {\n if (!resourceId) {\n return null;\n }\n\n const normalizedId = convertObjectIdsToStrings(resourceId) as string;\n\n const [eventDoc, googleImportedDoc] = await Promise.all([\n EventModel.findById(normalizedId)\n .select(\"_id name dateTime owner\")\n .lean<\n Pick<EventListItemType, \"_id\" | \"name\" | \"dateTime\"> & {\n owner?: SchemaOwnerType;\n }\n >()\n .exec(),\n GoogleImportedMarketModel.findById(normalizedId)\n .select(\"_id name dateTime\")\n .lean<Pick<EventListItemType, \"_id\" | \"name\" | \"dateTime\">>()\n .exec(),\n ]);\n\n return eventDoc ?? googleImportedDoc;\n}\n","import {\n DateTimeWithPriceType,\n EnumInviteStatus,\n} from \"@timardex/cluemart-shared\";\nimport { DateTimeType } from \"@timardex/cluemart-shared/types\";\n\nimport { SchemaRelationType } from \"src/mongoose/Relation\";\n\ntype EventDateSlot = Pick<DateTimeType, \"startDate\" | \"startTime\">;\n\n/**\n * Returns true when at least one startDate/startTime slot from the previous\n * schedule is absent from the next schedule (i.e. a date was removed).\n */\nexport function didRemoveAnyEventDates(\n previousDateTime: EventDateSlot[] | undefined,\n nextDateTime: EventDateSlot[] | undefined,\n): boolean {\n if (!previousDateTime?.length) {\n return false;\n }\n\n return previousDateTime.some(\n (prev) =>\n !nextDateTime?.some(\n (next) =>\n next.startDate === prev.startDate &&\n next.startTime === prev.startTime,\n ),\n );\n}\n\n/**\n * Helper: Update relationDates based on event's dateTime\n * Marks dates as UNAVAILABLE if they no longer exist in the event's dateTime.\n */\nexport function updateRelationDatesToUnavailable(\n relationDates: SchemaRelationType[\"relationDates\"],\n eventDateTime: DateTimeWithPriceType[] | undefined,\n): SchemaRelationType[\"relationDates\"] {\n return relationDates.map((relationDate) => {\n // Check if this relationDate exists in the event's dateTime\n const existsInEvent =\n eventDateTime?.some(\n (dt) =>\n dt.startDate === relationDate.dateTime.startDate &&\n dt.startTime === relationDate.dateTime.startTime,\n ) ?? false;\n\n return {\n ...relationDate,\n status: existsInEvent\n ? relationDate.status\n : EnumInviteStatus.UNAVAILABLE,\n };\n });\n}\n","import dayjs from \"dayjs\";\nimport type { Dayjs } from \"dayjs\";\n\nimport { UserModel } from \"src/mongoose/User\";\nimport { ObjectId } from \"src/types\";\n\nimport { processUserCompliance } from \"./utils\";\n\n/**\n * Runs the established compliance pipeline for one freshly loaded user.\n * Stripe webhooks use this at the actual paid-through boundary; the global\n * scheduled scan remains the fallback for missed or delayed webhook handling.\n */\nexport async function ensureUserLicenseComplianceForUser(\n userId: ObjectId,\n now: Dayjs = dayjs(),\n): Promise<void> {\n const user = await UserModel.findById(userId);\n if (!user) {\n return;\n }\n\n await processUserCompliance(user, now);\n}\n\nexport async function ensureUserLicenseCompliance(): Promise<void> {\n const now = dayjs();\n console.log(`🔍 Checking license compliance at ${now.format()}`);\n\n // Only fetch users with at least one expired license (or expiring today)\n // This significantly reduces the number of users to process\n const nowDate = now.toDate();\n\n // Performance Note: This query fetches users with at least one expired license,\n // but the compliance handlers (hasValidLicence) only deactivate resources if\n // the user has NO valid licenses of the required type. This means we may process\n // some users unnecessarily (e.g., users with one expired license but other valid licenses).\n //\n // This is an intentional trade-off:\n // - Query simplicity: Filtering for \"no valid licenses\" would require complex\n // MongoDB queries ($not with $elemMatch) that are harder to maintain and may\n // not use indexes efficiently\n // - Processing overhead: The hasValidLicence check is fast (in-memory array check),\n // so the overhead of processing extra users is minimal compared to query complexity\n // - For very large user bases: Consider adding a computed field (hasValidLicense)\n // or an index on licences.expiryDate to improve query performance\n const users = await UserModel.find({\n licences: {\n $elemMatch: {\n expiryDate: {\n $lte: nowDate, // Expired or expiring today\n },\n },\n },\n });\n\n console.log(\n `📊 Found ${users.length} users with expired or expiring licenses`,\n );\n\n if (!users.length) {\n console.log(\"No users with licenses to process.\");\n return;\n }\n\n let processedCount = 0;\n let errorCount = 0;\n\n for (const user of users) {\n try {\n await processUserCompliance(user, now);\n processedCount++;\n } catch (err) {\n errorCount++;\n console.error(\n `❌ Error processing license compliance for user ${String(user._id)}:`,\n err instanceof Error ? err.message : err,\n );\n // Continue processing other users even if one fails\n }\n }\n\n const errorMessage = errorCount > 0 ? `, ${errorCount} errors` : \"\";\n console.log(\n `✅ Processed ${processedCount} users successfully${errorMessage}`,\n );\n}\n","import {\n EnumNotificationResourceType,\n EnumNotificationType,\n EnumUserLicence,\n UserLicenceType,\n} from \"@timardex/cluemart-shared\";\nimport dayjs from \"dayjs\";\n\nimport { SchemaUserType, UserModel } from \"src/mongoose/User\";\nimport { ObjectId } from \"src/types\";\n\nimport { notifyUsers } from \"../../notifyUsers\";\n\nimport { handleEventLicenceCompliance } from \"./event\";\nimport { buildLicenceExpiryPipeline } from \"./licenceExpiryPipeline\";\nimport { handlePartnerLicenceCompliance } from \"./partner\";\nimport { handleVendorLicenceCompliance } from \"./vendor\";\n\n/**\n * Syncs the user's `licences` array\n * Uses a single atomic updateOne with an aggregation pipeline so it is safe under\n * concurrency (no read-modify-write, no lost updates).\n *\n * Rules (applied server-side only to licences whose licenceType is in licenceTypes):\n * - mode \"downgrade\" (vendor): expired STANDARD_* → extended to one year from now;\n * expired PRO_* or PRO_PLUS_* → downgraded to STANDARD_* with issuedDate=now and\n * expiryDate=one year from now\n * - mode \"extend\" (partner/event): expired licences are kept and their expiryDate\n * is extended to one year from now\n * - Non-expired or non-targeted licences are unchanged in both modes\n */\nexport async function syncUserLicencesAfterExpiry(\n userId: ObjectId,\n licenceTypes: EnumUserLicence[],\n now: dayjs.Dayjs,\n mode: \"downgrade\" | \"extend\" = \"downgrade\",\n): Promise<void> {\n const nowDate = now.toDate();\n const oneYearFromNow = now.add(1, \"year\").endOf(\"day\").toDate();\n\n const pipeline = buildLicenceExpiryPipeline({\n downgradeBranches: [\n {\n case: EnumUserLicence.PRO_PLUS_VENDOR,\n then: EnumUserLicence.STANDARD_VENDOR,\n },\n {\n case: EnumUserLicence.PRO_VENDOR,\n then: EnumUserLicence.STANDARD_VENDOR,\n },\n ],\n licenceTypes,\n mode,\n nowDate,\n oneYearFromNow,\n });\n\n await UserModel.updateOne({ _id: userId }, pipeline).exec();\n}\n\n/**\n * Checks if user has a valid licence of the given types\n */\nexport function hasValidLicence(\n licences: UserLicenceType[],\n licenceTypes: EnumUserLicence[],\n now: dayjs.Dayjs,\n): boolean {\n return licences.some(\n (licence) =>\n licenceTypes.includes(licence.licenceType) &&\n dayjs(licence.expiryDate).isAfter(now),\n );\n}\n\n/**\n * Sends a deactivation notification to the user\n */\nexport async function sendDeactivationNotification(\n payload: {\n data: {\n resourceId: string;\n resourceName: string;\n resourceType: EnumNotificationResourceType;\n };\n message: string;\n title: string;\n type: EnumNotificationType;\n userIds: ObjectId[];\n },\n userId: ObjectId,\n resourceName: string,\n resourceType: string,\n): Promise<void> {\n // No pubsub here: compliance runs in a process without GraphQL subscribers\n // (e.g. the cron worker), so notifyUsers is called without one. It logs and\n // swallows errors and reports success through its return value.\n const sent = await notifyUsers({ payload });\n if (!sent) {\n console.error(\n `❌ ${resourceType} notification not confirmed for user ${String(userId)} for \"${resourceName}\"`,\n );\n return;\n }\n console.log(\n `✅ Sent ${resourceType} notification to user ${String(userId)} for \"${resourceName}\"`,\n );\n}\n\n/**\n * Processes license compliance for a single user\n */\nexport async function processUserCompliance(\n user: SchemaUserType,\n now: dayjs.Dayjs,\n): Promise<void> {\n if (!user.licences) {\n return;\n }\n\n // Run compliance checks in parallel since they operate on different resources\n // (vendor, partner, events) and don't modify shared state\n await Promise.all([\n handleVendorLicenceCompliance(user, now),\n handlePartnerLicenceCompliance(user, now),\n handleEventLicenceCompliance(user, now),\n ]);\n}\n","import { EnumUserLicence } from \"@timardex/cluemart-shared\";\nimport type { Dayjs } from \"dayjs\";\n\nimport { SchemaUserType } from \"src/mongoose/User\";\n\nimport { syncUserLicencesAfterExpiry } from \"./utils\";\n\n// Group event licences\nexport const eventLicences: EnumUserLicence[] = [\n EnumUserLicence.STANDARD_EVENT,\n EnumUserLicence.PRO_EVENT,\n EnumUserLicence.PRO_PLUS_EVENT,\n];\n\n/**\n * Handles event licence compliance for a single user.\n *\n * Event licences are kept and extended on expiry — no deactivation.\n */\nexport async function handleEventLicenceCompliance(\n user: SchemaUserType,\n now: Dayjs,\n): Promise<void> {\n if (!user.licences || !user.events?.length) {\n return;\n }\n\n await syncUserLicencesAfterExpiry(user._id, eventLicences, now, \"extend\");\n}\n","/**\n * Builds an aggregation pipeline that atomically applies expiry rules to the\n * `licences` array. Used by syncUserLicencesAfterExpiry for a single\n * updateOne with no read-modify-write.\n *\n * downgradeBranches: PRO_* / PRO_PLUS_* licence types mapped to their STANDARD_*\n * counterpart (e.g. pro_plus_event → standard_event). Use EnumUserLicence in the\n * caller to avoid string drift.\n *\n * Note: Uses MongoDB aggregation keys \"then\"/\"case\" (required by $cond/$switch).\n *\n * Requires MongoDB 4.2+: this emits an updateOne aggregation pipeline (the\n * [ { $set: ... } ] form) and uses $reduce / $indexOfArray / $regexMatch in the\n * dedupe + standard-detection stages. The project runs MongoDB 8.0\n * (docker-compose.yml), well above the minimum.\n */\nexport function buildLicenceExpiryPipeline(params: {\n /** Pairs of (licenceType, standardCounterpart) for downgrade; e.g. PRO_PLUS_VENDOR → STANDARD_VENDOR */\n downgradeBranches: ReadonlyArray<{\n case: string;\n then: string;\n }>;\n licenceTypes: string[];\n /**\n * How expired, targeted licences are handled:\n * - \"downgrade\": extend expired STANDARD_* and downgrade expired PRO_* or PRO_PLUS_* (vendor)\n * - \"extend\": keep the licence as-is and extend expiryDate to oneYearFromNow (partner/event)\n */\n mode?: \"downgrade\" | \"extend\";\n nowDate: Date;\n oneYearFromNow: Date;\n}): object[] {\n const {\n downgradeBranches,\n licenceTypes,\n nowDate,\n oneYearFromNow,\n mode = \"downgrade\",\n } = params;\n\n // Value produced for a licence that is in the target set and expired.\n const expiredInTarget =\n mode === \"extend\"\n ? {\n // Extend: keep licenceType and all other fields, push expiry out by a year\n $mergeObjects: [\"$$lic\", { expiryDate: oneYearFromNow }],\n }\n : {\n $cond: {\n // Expired STANDARD_* → extend (keep, push expiry out by a year)\n if: \"$$isStandard\",\n then: {\n $mergeObjects: [\"$$lic\", { expiryDate: oneYearFromNow }],\n },\n else: {\n $cond: {\n // Expired PRO_* / PRO_PLUS_* → downgrade and set new dates\n if: { $ne: [\"$$downgrade\", null] },\n then: {\n $mergeObjects: [\n \"$$lic\",\n {\n expiryDate: oneYearFromNow,\n issuedDate: nowDate,\n licenceType: \"$$downgrade\",\n prevLicenceType: \"$$lic.licenceType\",\n },\n ],\n },\n // Unknown type in target set → keep as-is\n else: \"$$lic\",\n },\n },\n },\n };\n\n return [\n {\n // Stage 1: resolve each licence (extend / downgrade / keep)\n $set: {\n licences: {\n // Remove null entries (e.g. pre-existing null licences kept by the map)\n $filter: {\n as: \"x\",\n cond: { $ne: [\"$$x\", null] },\n input: {\n // Iterate over each licence in the document's licences array\n $map: {\n input: \"$licences\",\n as: \"lic\",\n in: {\n // Define variables once per licence for reuse in the condition tree\n $let: {\n vars: {\n // Target STANDARD_* type for this licence (from downgradeBranches)\n downgrade: {\n $switch: {\n branches: downgradeBranches.map((b) => ({\n case: {\n $eq: [\"$$lic.licenceType\", b.case],\n },\n then: b.then,\n })),\n default: null,\n },\n },\n // True if this licence has expiryDate <= now (expired)\n expired: {\n $and: [\n { $ne: [\"$$lic\", null] },\n { $lte: [\"$$lic.expiryDate\", nowDate] },\n ],\n },\n // True if this licence's type is in the list we're processing (e.g. vendor only)\n inTarget: { $in: [\"$$lic.licenceType\", licenceTypes] },\n // True if licenceType starts with \"standard_\" (e.g. standard_vendor)\n isStandard: {\n $regexMatch: {\n input: {\n $toString: { $ifNull: [\"$$lic.licenceType\", \"\"] },\n },\n regex: /^standard_/,\n },\n },\n },\n // Compute the new value for this array element\n in: {\n $cond: {\n // Keep as-is: null licence, or not in target set, or not expired\n if: {\n $or: [\n { $eq: [\"$$lic\", null] },\n { $not: \"$$inTarget\" },\n { $gt: [\"$$lic.expiryDate\", nowDate] },\n ],\n },\n then: \"$$lic\",\n // In target set and expired — apply the configured handling\n else: expiredInTarget,\n },\n },\n },\n },\n },\n },\n },\n },\n },\n },\n {\n // Stage 2: dedupe by licenceType — keep the entry with the latest expiryDate\n // (ties broken by the latest issuedDate). Runs inside the same atomic updateOne.\n $set: {\n licences: {\n $reduce: {\n input: \"$licences\",\n initialValue: [],\n in: {\n $let: {\n vars: {\n current: \"$$this\",\n index: {\n $indexOfArray: [\n {\n $map: {\n input: \"$$value\",\n as: \"item\",\n in: \"$$item.licenceType\",\n },\n },\n \"$$this.licenceType\",\n ],\n },\n },\n in: {\n $cond: {\n if: { $eq: [\"$$index\", -1] },\n then: { $concatArrays: [\"$$value\", [\"$$current\"]] },\n else: {\n $map: {\n input: \"$$value\",\n as: \"item\",\n in: {\n $cond: {\n if: {\n $eq: [\n \"$$item.licenceType\",\n \"$$current.licenceType\",\n ],\n },\n then: {\n $cond: {\n if: {\n $or: [\n {\n $gt: [\n \"$$current.expiryDate\",\n \"$$item.expiryDate\",\n ],\n },\n {\n $and: [\n {\n $eq: [\n \"$$current.expiryDate\",\n \"$$item.expiryDate\",\n ],\n },\n {\n $gt: [\n \"$$current.issuedDate\",\n \"$$item.issuedDate\",\n ],\n },\n ],\n },\n ],\n },\n then: \"$$current\",\n else: \"$$item\",\n },\n },\n else: \"$$item\",\n },\n },\n },\n },\n },\n },\n },\n },\n },\n },\n },\n },\n ];\n}\n","import { EnumUserLicence } from \"@timardex/cluemart-shared\";\nimport type { Dayjs } from \"dayjs\";\n\nimport { SchemaUserType } from \"src/mongoose/User\";\n\nimport { syncUserLicencesAfterExpiry } from \"./utils\";\n\n// Group partner licences\nexport const partnerLicences: EnumUserLicence[] = [\n EnumUserLicence.STANDARD_PARTNER,\n];\n\n/**\n * Handles partner licence compliance for a single user.\n *\n * Partner licences are kept and extended on expiry — no deactivation.\n */\nexport async function handlePartnerLicenceCompliance(\n user: SchemaUserType,\n now: Dayjs,\n): Promise<void> {\n if (!user.licences || !user.partner) {\n return;\n }\n\n await syncUserLicencesAfterExpiry(user._id, partnerLicences, now, \"extend\");\n}\n","import {\n EnumNotificationResourceType,\n EnumNotificationType,\n EnumSubscriptionStatus,\n EnumUserLicence,\n vendorLicences,\n} from \"@timardex/cluemart-shared\";\nimport dayjs from \"dayjs\";\nimport type { Dayjs } from \"dayjs\";\n\nimport { SchemaUserType, UserModel } from \"src/mongoose/User\";\nimport { SchemaVendorType, VendorModel } from \"src/mongoose/vendor/Vendor\";\nimport { ObjectId } from \"src/types\";\n\nimport {\n getHighestLicenceForCategory,\n LicenceCategory,\n licencePriority,\n} from \"../models\";\n\nimport {\n hasValidLicence,\n sendDeactivationNotification,\n syncUserLicencesAfterExpiry,\n} from \"./utils\";\n\n/**\n * Fetches the live vendor referenced by a user's `vendor` field.\n * Returns null when the user has no vendor, or when the referenced vendor is not\n * live (active), has been soft-deleted, or is no longer owned by the user — the\n * same constraints used elsewhere in this module, so a stale `user.vendor`\n * reference never triggers feature downgrade/restore writes.\n */\nasync function findUserVendor(\n userId: ObjectId,\n logLabel: string,\n): Promise<SchemaVendorType | null> {\n const user = await UserModel.findById(userId).select(\"vendor\").lean().exec();\n\n if (!user?.vendor) {\n console.warn(`[${logLabel}] No vendor found for userId=${userId}`);\n return null;\n }\n\n const vendor = await VendorModel.findOne({\n _id: user.vendor,\n active: true,\n deletedAt: null,\n \"owner.userId\": userId,\n })\n .lean<SchemaVendorType>()\n .exec();\n\n if (!vendor) {\n console.warn(\n `[${logLabel}] Vendor not found for id=${user.vendor}, userId=${userId}`,\n );\n return null;\n }\n\n return vendor;\n}\n\n/**\n * Applies the STANDARD_VENDOR feature downgrade to an already-resolved vendor.\n * The write is guarded by the same live-vendor constraints used by\n * findUserVendor, so it no-ops atomically if the vendor was deactivated or\n * soft-deleted between the read and the write. Returns true when a matching\n * live vendor was actually updated.\n */\nasync function applyVendorDowngrade(\n vendor: SchemaVendorType,\n ownerUserId: ObjectId,\n): Promise<boolean> {\n /**\n * Build vendor update payload\n */\n const updateData: Partial<SchemaVendorType> = {};\n\n updateData.availability = {\n corporate: false,\n private: false,\n school: false,\n };\n\n updateData.products = {\n active: false,\n productsList: vendor.products?.productsList ?? [],\n };\n\n updateData.calendar = {\n active: false,\n calendarData: vendor.calendar?.calendarData ?? [],\n };\n\n /**\n * Preserve the pre-downgrade state so a later PRO upgrade can restore the\n * vendor's own configuration (a vendor may have had some PRO features\n * disabled before being downgraded) instead of blindly re-enabling them.\n * Raw (possibly undefined) values are stored, so absent features fall back\n * to their enabled default during restore rather than being forced off.\n */\n updateData.downgradeSnapshot = {\n availability: vendor.availability,\n calendarActive: vendor.calendar?.active,\n productsActive: vendor.products?.active,\n };\n\n /**\n * Image rules\n * STANDARD_VENDOR => only first 6 active, 6 is the default image limit for standard vendors\n */\n updateData.images = (vendor.images ?? []).map((image, index) => ({\n ...image,\n active: index < 6,\n }));\n\n /**\n * Persist vendor updates\n */\n const result = await VendorModel.updateOne(\n {\n _id: vendor._id,\n active: true,\n deletedAt: null,\n \"owner.userId\": ownerUserId,\n },\n { $set: updateData },\n );\n\n return (result?.matchedCount ?? 0) > 0;\n}\n\nexport async function downgradeVendorProFeatures(\n userId: ObjectId,\n licenceType: EnumUserLicence,\n): Promise<void> {\n /**\n * This function only handles STANDARD_VENDOR (feature downgrade). PRO/PLUS\n * upgrades are handled by restoreVendorProFeatures, so return early before\n * touching the user/vendor models.\n */\n const isStandardVendor = licenceType === EnumUserLicence.STANDARD_VENDOR;\n\n if (!isStandardVendor) {\n return;\n }\n\n try {\n const vendor = await findUserVendor(userId, \"downgradeVendorProFeatures\");\n\n if (!vendor) {\n return;\n }\n\n await applyVendorDowngrade(vendor, userId);\n } catch (error) {\n console.error(\"[downgradeVendorProFeatures] Failed:\", error);\n throw error;\n }\n}\n\n/**\n * Applies the PRO feature restore to an already-resolved vendor. The write is\n * guarded by the same live-vendor constraints used by findUserVendor, so it\n * no-ops atomically if the vendor was deactivated or soft-deleted between the\n * read and the write. Returns true when a matching live vendor was actually\n * updated.\n */\nasync function applyVendorRestore(\n vendor: SchemaVendorType,\n ownerUserId: ObjectId,\n): Promise<boolean> {\n /**\n * Build vendor update payload\n */\n const updateData: Partial<SchemaVendorType> = {};\n\n const snapshot = vendor.downgradeSnapshot;\n\n updateData.availability = {\n corporate: snapshot?.availability?.corporate ?? true,\n private: snapshot?.availability?.private ?? true,\n school: snapshot?.availability?.school ?? true,\n };\n\n updateData.products = {\n active: snapshot?.productsActive ?? true,\n productsList: vendor.products?.productsList ?? [],\n };\n\n updateData.calendar = {\n active: snapshot?.calendarActive ?? true,\n calendarData: vendor.calendar?.calendarData ?? [],\n };\n\n updateData.images = (vendor.images ?? []).map((image) => ({\n ...image,\n active: true,\n }));\n\n /**\n * Persist vendor updates\n */\n const result = await VendorModel.updateOne(\n {\n _id: vendor._id,\n active: true,\n deletedAt: null,\n \"owner.userId\": ownerUserId,\n },\n { $set: updateData },\n );\n\n return (result?.matchedCount ?? 0) > 0;\n}\n\n/**\n * Restores the PRO vendor features that are removed by\n * downgradeVendorProFeatures when a vendor is downgraded to STANDARD_VENDOR.\n * This is the opposite operation: it re-enables availability, products and\n * calendar from the pre-downgrade snapshot (falling back to fully enabled when\n * no snapshot exists), and keeps all images active.\n */\nexport async function restoreVendorProFeatures(\n userId: ObjectId,\n licenceType: EnumUserLicence,\n): Promise<void> {\n /**\n * Only PRO_VENDOR / PRO_PLUS_VENDOR restore the vendor's PRO features. Any\n * other licence (STANDARD_VENDOR, event/partner tiers, etc.) is a no-op, so\n * return early before touching the user/vendor models.\n */\n const isProVendor =\n licenceType === EnumUserLicence.PRO_VENDOR ||\n licenceType === EnumUserLicence.PRO_PLUS_VENDOR;\n\n if (!isProVendor) {\n return;\n }\n\n try {\n const vendor = await findUserVendor(userId, \"restoreVendorProFeatures\");\n\n if (!vendor) {\n return;\n }\n\n await applyVendorRestore(vendor, userId);\n } catch (error) {\n console.error(\"[restoreVendorProFeatures] Failed:\", error);\n throw error;\n }\n}\n\nfunction isProtectedByCurrentStripeSubscription(\n user: SchemaUserType,\n licenceType: EnumUserLicence,\n now: Dayjs,\n): boolean {\n const stripe = user.stripe;\n if (!stripe || stripe.currentPlan !== licenceType) {\n return false;\n }\n\n const gracePeriodEndsAt = stripe.paymentGracePeriodEndsAt\n ? dayjs(stripe.paymentGracePeriodEndsAt)\n : null;\n const hasActivePaymentGracePeriod =\n (stripe.status === EnumSubscriptionStatus.PAST_DUE ||\n stripe.status === EnumSubscriptionStatus.INACTIVE) &&\n Boolean(stripe.paymentGraceSubscriptionId) &&\n (!stripe.subscriptionId ||\n stripe.subscriptionId === stripe.paymentGraceSubscriptionId) &&\n gracePeriodEndsAt !== null &&\n gracePeriodEndsAt.isValid() &&\n gracePeriodEndsAt.isAfter(now);\n\n if (hasActivePaymentGracePeriod) {\n return true;\n }\n\n if (!stripe.subscriptionId) {\n return false;\n }\n\n if (stripe.status !== EnumSubscriptionStatus.ACTIVE) {\n return false;\n }\n\n if (!stripe.endDate) {\n return false;\n }\n\n const paidThrough = dayjs(stripe.endDate);\n return paidThrough.isValid() && paidThrough.isAfter(now);\n}\n\n/**\n * Handles vendor licence compliance for a single user\n */\nexport async function handleVendorLicenceCompliance(\n user: SchemaUserType,\n now: Dayjs,\n): Promise<void> {\n if (!user.licences || !user.vendor) {\n return;\n }\n\n const vendorLicencesOfUser = user.licences.filter((licence) =>\n licence?.licenceType?.includes(\"vendor\"),\n );\n\n if (vendorLicencesOfUser.length === 0) {\n return;\n }\n\n const proLicences = vendorLicencesOfUser.filter(\n (licence) => licence.licenceType !== EnumUserLicence.STANDARD_VENDOR,\n );\n\n const expiredProLicences = proLicences.filter(\n (licence) => !dayjs(licence.expiryDate).isAfter(now),\n );\n\n const stripeProtectedLicenceTypes = new Set(\n expiredProLicences\n .filter((licence) =>\n isProtectedByCurrentStripeSubscription(user, licence.licenceType, now),\n )\n .map((licence) => licence.licenceType),\n );\n\n const expiredProLicence = expiredProLicences.some(\n (licence) => !stripeProtectedLicenceTypes.has(licence.licenceType),\n );\n\n const hasValidProLicence =\n stripeProtectedLicenceTypes.size > 0 ||\n hasValidLicence(proLicences, vendorLicences, now);\n\n const hasExpiredVendorLicence = vendorLicencesOfUser.some(\n (licence) =>\n !dayjs(licence.expiryDate).isAfter(now) &&\n !stripeProtectedLicenceTypes.has(licence.licenceType),\n );\n\n if (!hasExpiredVendorLicence) {\n return;\n }\n\n // Resolve the vendor up-front only when a PRO licence actually expired, so the\n // PRO-downgrade-and-notify path never runs without a vendor to update/notify.\n // A STANDARD-only expiry skips this lookup entirely (no vendor mutation happens).\n // The active:true + deletedAt:null filter matches getVendorResourceInfo and the\n // rest of the codebase: a soft-deleted (deleteVendor) or admin-deactivated\n // (applyAdminResourceActiveUpdate) vendor must not be downgraded/notified, since\n // there is no live vendor to update or notify about. Commit 384f31d removed these\n // conditions as \"redundant\", but deleteVendor's clearOwnerResourceOnDelete unset\n // of user.vendor is not atomic with the soft-delete, and admin deactivation never\n // unsets user.vendor — so an inactive vendor can still be referenced here.\n let vendor: SchemaVendorType | null = null;\n if (expiredProLicence) {\n vendor = await VendorModel.findOne({\n _id: user.vendor,\n active: true,\n deletedAt: null,\n \"owner.userId\": user._id,\n })\n .lean<SchemaVendorType>()\n .exec();\n }\n\n // Extend expired STANDARD_VENDOR and downgrade expired PRO_*/PRO_PLUS_*\n // atomically, regardless of vendor presence. The currently paid Stripe tier\n // is excluded while it remains ACTIVE and within its paid-through\n // period; pending transitions are therefore left for Stripe reconciliation.\n // When the vendor is missing or inactive, eligible PRO entries are still\n // downgraded, but the feature update + notification below are skipped.\n const licencesToSync = vendorLicences.filter(\n (licenceType) => !stripeProtectedLicenceTypes.has(licenceType),\n );\n await syncUserLicencesAfterExpiry(user._id, licencesToSync, now, \"downgrade\");\n\n // Only downgrade the vendor + notify when a PRO licence actually expired AND the\n // user has no remaining valid PRO licence AND the vendor is present/active.\n if (!expiredProLicence || !vendor || hasValidProLicence) {\n return;\n }\n\n const downgraded = await applyVendorDowngrade(vendor, user._id);\n\n // The vendor was resolved above, but it may have been deactivated or\n // soft-deleted between the read and the write. Only notify when the update\n // actually matched a live vendor, so the notification never claims a\n // downgrade that didn't happen.\n if (!downgraded) {\n return;\n }\n\n const payload = {\n data: {\n resourceId: String(vendor._id),\n resourceName: vendor.name,\n resourceType: EnumNotificationResourceType.DOWNGRADED_VENDOR,\n },\n message: `Your Vendor licence has been downgraded due to licence expiration.`,\n title: `Vendor Licence Downgraded`,\n type: EnumNotificationType.SYSTEM,\n userIds: [user._id],\n };\n\n await sendDeactivationNotification(payload, user._id, vendor.name, \"vendor\");\n}\n\n/**\n * Checks whether a vendor's owner currently holds a PRO (or higher) vendor licence.\n */\nexport async function vendorOwnerHasProLicence(\n vendorId: string,\n): Promise<boolean> {\n const vendor = await VendorModel.findOne({\n _id: vendorId,\n active: true,\n deletedAt: null,\n })\n .lean<SchemaVendorType>()\n .exec();\n\n if (!vendor) {\n return false;\n }\n\n const owner = await UserModel.findById(vendor.owner.userId, {\n licences: 1,\n stripe: 1,\n })\n .lean()\n .exec();\n\n if (!owner) {\n return false;\n }\n\n const now = dayjs();\n const effectiveVendorLicences = owner.licences?.filter(\n (licence) =>\n licence?.licenceType &&\n (dayjs(licence.expiryDate).isAfter(now) ||\n isProtectedByCurrentStripeSubscription(\n owner,\n licence.licenceType,\n now,\n )),\n );\n\n const highestVendorLicence = getHighestLicenceForCategory(\n effectiveVendorLicences,\n LicenceCategory.VENDOR,\n );\n\n return (\n highestVendorLicence !== null &&\n licencePriority[highestVendorLicence] >=\n licencePriority[EnumUserLicence.PRO_VENDOR]\n );\n}\n","import {\n EnumResourceType,\n EnumUserLicence,\n isNonVisitorResourceType,\n LicenceExpiryDate,\n NonVisitorResourceType,\n UserLicenceType,\n} from \"@timardex/cluemart-shared\";\nimport dayjs from \"dayjs\";\nimport { GraphQLError } from \"graphql\";\n\nimport { SchemaUserType, UserModel } from \"src/mongoose/User\";\nimport { ObjectId } from \"src/types\";\n\nexport enum LicenceCategory {\n EVENT = \"event\",\n PARTNER = \"partner\",\n VENDOR = \"vendor\",\n AFFILIATE = \"affiliate\",\n SCHOOL = \"school\",\n}\n\nexport const licenceCategoryMapping: Record<EnumUserLicence, LicenceCategory> =\n {\n [EnumUserLicence.PRO_EVENT]: LicenceCategory.EVENT,\n [EnumUserLicence.PRO_PLUS_EVENT]: LicenceCategory.EVENT,\n [EnumUserLicence.PRO_PLUS_VENDOR]: LicenceCategory.VENDOR,\n [EnumUserLicence.PRO_VENDOR]: LicenceCategory.VENDOR,\n [EnumUserLicence.STANDARD_EVENT]: LicenceCategory.EVENT,\n [EnumUserLicence.STANDARD_PARTNER]: LicenceCategory.PARTNER,\n [EnumUserLicence.STANDARD_VENDOR]: LicenceCategory.VENDOR,\n [EnumUserLicence.STANDARD_AFFILIATE]: LicenceCategory.AFFILIATE,\n [EnumUserLicence.STANDARD_SCHOOL]: LicenceCategory.SCHOOL,\n };\n\nexport const licencePriority: Record<EnumUserLicence, number> = {\n [EnumUserLicence.PRO_PLUS_EVENT]: 3,\n [EnumUserLicence.PRO_EVENT]: 2,\n [EnumUserLicence.STANDARD_EVENT]: 1,\n [EnumUserLicence.PRO_PLUS_VENDOR]: 3,\n [EnumUserLicence.PRO_VENDOR]: 2,\n [EnumUserLicence.STANDARD_VENDOR]: 1,\n [EnumUserLicence.STANDARD_PARTNER]: 1,\n [EnumUserLicence.STANDARD_AFFILIATE]: 1,\n [EnumUserLicence.STANDARD_SCHOOL]: 1,\n};\n\nconst standardLicences = [\n EnumUserLicence.STANDARD_VENDOR,\n EnumUserLicence.STANDARD_EVENT,\n EnumUserLicence.STANDARD_PARTNER,\n] as const;\n\nconst standardLicenceSet = new Set<EnumUserLicence>(standardLicences);\n\nexport function isStandardLicence(\n licence: EnumUserLicence,\n): licence is (typeof standardLicences)[number] {\n return standardLicenceSet.has(licence);\n}\n\nconst categoryRegexMapping: Record<LicenceCategory, RegExp> = {\n [LicenceCategory.EVENT]: /_event$/,\n [LicenceCategory.PARTNER]: /_partner$/,\n [LicenceCategory.VENDOR]: /_vendor$/,\n [LicenceCategory.AFFILIATE]: /_affiliate$/,\n [LicenceCategory.SCHOOL]: /_school$/,\n};\n\nconst categoryFallbackLicence: Record<LicenceCategory, EnumUserLicence> = {\n [LicenceCategory.EVENT]: EnumUserLicence.STANDARD_EVENT,\n [LicenceCategory.PARTNER]: EnumUserLicence.STANDARD_PARTNER,\n [LicenceCategory.VENDOR]: EnumUserLicence.STANDARD_VENDOR,\n [LicenceCategory.AFFILIATE]: EnumUserLicence.STANDARD_AFFILIATE,\n [LicenceCategory.SCHOOL]: EnumUserLicence.STANDARD_SCHOOL,\n};\n\nconst LicenceFilterInput = {\n INPUT_USER_LICENCES: \"$licences\",\n} as const;\n\ntype LicenceFilterInputType =\n (typeof LicenceFilterInput)[keyof typeof LicenceFilterInput];\n\ntype LicenceReplacePipelineArgs = {\n fallbackType: EnumUserLicence;\n inputField: LicenceFilterInputType;\n licenceObject: UserLicenceType;\n typeRegex: RegExp;\n};\n\ntype LicenceUpgradeArgs = {\n expiryDate: LicenceExpiryDate;\n licenceType: EnumUserLicence;\n userId: ObjectId;\n};\n\ntype LicenceUpgradeResult = {\n licenceObject: UserLicenceType;\n updatedUser: SchemaUserType | null;\n};\n\nexport function getLicenceCategory(licence: EnumUserLicence): LicenceCategory {\n const category = licenceCategoryMapping[licence];\n\n if (!category) {\n throw new Error(`Missing licence category mapping for ${licence}`);\n }\n\n return category;\n}\n\nexport function getHighestLicenceForCategory(\n licences: UserLicenceType[] | null | undefined,\n category: LicenceCategory,\n): EnumUserLicence | null {\n const categoryLicences = (licences ?? [])\n .map((licence) => licence.licenceType)\n .filter((licenceType): licenceType is EnumUserLicence =>\n Boolean(licenceType && getLicenceCategory(licenceType) === category),\n );\n\n let highestLicence: EnumUserLicence | null = null;\n let highestPriority = Number.NEGATIVE_INFINITY;\n\n for (const licenceType of categoryLicences) {\n const priority = licencePriority[licenceType];\n if (priority > highestPriority) {\n highestPriority = priority;\n highestLicence = licenceType;\n }\n }\n\n return highestLicence;\n}\n\nexport function createLicenceObject(\n expiryDate: LicenceExpiryDate,\n licenceType: EnumUserLicence,\n): UserLicenceType {\n const today = dayjs();\n const expiryDateMapping: Record<LicenceExpiryDate, Date> = {\n [LicenceExpiryDate.ONE_YEAR]: today.add(1, \"year\").endOf(\"day\").toDate(),\n [LicenceExpiryDate.ONE_MONTH]: today.add(1, \"month\").endOf(\"day\").toDate(),\n [LicenceExpiryDate.TWO_MONTHS]: today.add(2, \"month\").endOf(\"day\").toDate(),\n [LicenceExpiryDate.THREE_MONTHS]: today\n .add(3, \"month\")\n .endOf(\"day\")\n .toDate(),\n [LicenceExpiryDate.SIX_MONTHS]: today.add(6, \"month\").endOf(\"day\").toDate(),\n };\n const licenceObject: UserLicenceType = {\n expiryDate: expiryDateMapping[expiryDate],\n issuedDate: today.toDate(),\n licenceType: licenceType,\n };\n return licenceObject;\n}\n\n/**\n * Builds an aggregation pipeline to replace a user's license while preserving other licenses of different types.\n * It filters out existing licenses that match the specified type regex and appends the new license object.\n * @param fallbackType - A fallback license type used when existing licenses don't have a defined type.\n * @param licenceObject - The new license object to be added to the user's licenses.\n * @param typeRegex - A regular expression used to identify licenses of the same type that should be replaced.\n * @returns An array representing the aggregation pipeline for updating the user's licenses.\n */\nconst buildLicenceReplacePipeline = ({\n fallbackType,\n inputField,\n licenceObject,\n typeRegex,\n}: LicenceReplacePipelineArgs) => [\n {\n $set: {\n licences: {\n $concatArrays: [\n {\n $filter: {\n as: \"licence\",\n cond: {\n $not: {\n $regexMatch: {\n input: {\n $toString: {\n $ifNull: [\"$$licence.licenceType\", fallbackType],\n },\n },\n regex: typeRegex,\n },\n },\n },\n input: { $ifNull: [inputField, []] },\n },\n },\n [licenceObject],\n ],\n },\n },\n },\n];\n\nexport async function replaceUserLicenceWithObject({\n userId,\n licenceObject,\n protectHigherLicence = true,\n refreshExistingLicence = false,\n}: {\n userId: ObjectId;\n licenceObject: UserLicenceType;\n protectHigherLicence?: boolean;\n refreshExistingLicence?: boolean;\n}) {\n const user = await UserModel.findById(userId, { licences: 1 }).lean();\n\n if (!user) throw new GraphQLError(\"User not found\");\n\n const existingLicence = user.licences?.find(\n (licence) => licence.licenceType === licenceObject.licenceType,\n );\n\n if (existingLicence && !refreshExistingLicence) {\n return;\n }\n\n const category = getLicenceCategory(licenceObject.licenceType);\n const updatedLicenceObject = {\n ...licenceObject,\n prevLicenceType:\n existingLicence && refreshExistingLicence\n ? existingLicence.prevLicenceType\n : user.licences?.find(\n (licence) =>\n licence.licenceType &&\n getLicenceCategory(licence.licenceType) === category,\n )?.licenceType,\n };\n\n if (protectHigherLicence) {\n const highestLicence = getHighestLicenceForCategory(\n user.licences,\n category,\n );\n if (\n highestLicence &&\n licencePriority[highestLicence] >\n licencePriority[updatedLicenceObject.licenceType]\n ) {\n return;\n }\n }\n\n await UserModel.updateOne(\n { _id: userId },\n buildLicenceReplacePipeline({\n fallbackType: categoryFallbackLicence[category],\n inputField: LicenceFilterInput.INPUT_USER_LICENCES,\n licenceObject: updatedLicenceObject,\n typeRegex: categoryRegexMapping[category],\n }),\n );\n}\n\n/**\n * Upgrades a user's license by adding a new license object to their account.\n * It calculates the expiry date based on the provided expiry duration and updates the user's licenses in the database.\n * @param licenceType - The licence type to upgrade the user to.\n * @param expiryDate - The expiry duration for the license being upgraded.\n * @param userId - The ID of the user whose license is being upgraded.\n * @returns An object containing the updated user and the new license object.\n */\nexport const upgradeUserToLicence = async ({\n licenceType,\n expiryDate,\n userId,\n}: LicenceUpgradeArgs): Promise<LicenceUpgradeResult> => {\n const licenceObject = createLicenceObject(expiryDate, licenceType);\n\n await replaceUserLicenceWithObject({ licenceObject, userId });\n\n const user = await UserModel.findById(userId).exec();\n\n return {\n licenceObject,\n updatedUser: user,\n };\n};\n\nexport async function checkOwnerHasLicence({\n userId,\n resourceType,\n}: {\n userId: ObjectId;\n resourceType: EnumResourceType;\n}): Promise<void> {\n try {\n const owner = await UserModel.findById(userId);\n if (!owner) throw new GraphQLError(\"Owner not found\");\n\n const categoryByResource: Record<NonVisitorResourceType, LicenceCategory> =\n {\n [EnumResourceType.EVENT]: LicenceCategory.EVENT,\n [EnumResourceType.PARTNER]: LicenceCategory.PARTNER,\n [EnumResourceType.VENDOR]: LicenceCategory.VENDOR,\n [EnumResourceType.AFFILIATE]: LicenceCategory.AFFILIATE,\n [EnumResourceType.SCHOOL]: LicenceCategory.SCHOOL,\n };\n\n if (!isNonVisitorResourceType(resourceType)) {\n throw new GraphQLError(`Invalid resource type: ${resourceType}.`);\n }\n\n const requiredCategory = categoryByResource[resourceType];\n\n const activeLicence = owner.licences?.some((licence) => {\n if (!licence.licenceType) return false;\n return getLicenceCategory(licence.licenceType) === requiredCategory;\n });\n\n if (!activeLicence) {\n throw new GraphQLError(\n `Owner does not have an active licence. Cannot update ${resourceType}.`,\n );\n }\n } catch (error) {\n // Re-throw GraphQLErrors as-is\n if (error instanceof GraphQLError) {\n throw error;\n }\n // Convert database or other errors to GraphQLError\n throw new GraphQLError(\n error instanceof Error\n ? `Failed to check user licence: ${error.message}`\n : \"Failed to check user licence\",\n );\n }\n}\n","import { EventModel, SchemaEventType } from \"src/mongoose/event/Event\";\nimport { ObjectId } from \"src/types\";\n\n/**\n * Gets event resource information for a reminder\n */\nexport async function getEventResourceInfo(\n userId: ObjectId,\n eventIds: ObjectId[],\n): Promise<{ resourceId: string; resourceName: string } | null> {\n const event = await EventModel.findOne({\n _id: { $in: eventIds },\n active: true,\n deletedAt: null,\n \"owner.userId\": userId,\n })\n .lean<SchemaEventType>()\n .exec();\n\n if (!event) {\n return null;\n }\n\n return {\n resourceId: String(event._id),\n resourceName: event.name,\n };\n}\n","import { PartnerModel, SchemaPartnerType } from \"src/mongoose/Partner\";\nimport { ObjectId } from \"src/types\";\n\n/**\n * Gets partner resource information for a reminder\n */\nexport async function getPartnerResourceInfo(\n userId: ObjectId,\n partnerId: ObjectId,\n): Promise<{ resourceId: string; resourceName: string } | null> {\n const partner = await PartnerModel.findOne({\n _id: partnerId,\n active: true,\n deletedAt: null,\n \"owner.userId\": userId,\n })\n .lean<SchemaPartnerType>()\n .exec();\n\n if (!partner) {\n return null;\n }\n\n return {\n resourceId: String(partner._id),\n resourceName: partner.name,\n };\n}\n","import dayjs from \"dayjs\";\n\nimport { UserModel } from \"src/mongoose/User\";\n\nimport {\n REMINDER_WINDOW_MAX_HOURS,\n REMINDER_WINDOW_MIN_HOURS,\n} from \"./reminderWindow\";\nimport { processUserLicenseReminders } from \"./utils\";\n\n/**\n * Sends license expiration reminders to users whose licenses expire in 7 days\n */\nexport async function remindUsersAboutLicenseExpiration(): Promise<void> {\n const now = dayjs();\n console.log(`🔍 Checking for licenses expiring in 7 days at ${now.format()}`);\n\n // Calculate date range: 6.5 to 7.5 days from now (matches isLicenseExpiringIn7Days filter).\n // Use hours instead of fractional days: dayjs `add(6.5, \"day\")` rounds to 7 days\n // and `add(7.5, \"day\")` rounds to 8 days, which silently shifted the reminder window.\n const minExpiryDate = now.add(REMINDER_WINDOW_MIN_HOURS, \"hour\").toDate(); // 6.5 days\n const maxExpiryDate = now.add(REMINDER_WINDOW_MAX_HOURS, \"hour\").toDate(); // 7.5 days\n\n // Only fetch users with licenses expiring within the reminder window\n // $elemMatch already implies the array exists and is not empty\n const users = await UserModel.find({\n licences: {\n $elemMatch: {\n expiryDate: {\n $gte: minExpiryDate,\n $lte: maxExpiryDate,\n },\n },\n },\n });\n\n console.log(\n `📊 Found ${users.length} users with licenses expiring in 7 days`,\n );\n\n if (!users.length) {\n console.log(\"No users with licenses to process.\");\n return;\n }\n\n let totalReminderCount = 0;\n\n for (const user of users) {\n try {\n const reminderCount = await processUserLicenseReminders(user, now);\n totalReminderCount += reminderCount;\n } catch (err) {\n console.error(\n `❌ Error processing license reminders for user ${String(user._id)}:`,\n err instanceof Error ? err.message : err,\n );\n // Continue processing other users even if one fails\n }\n }\n\n console.log(\n `✅ Processed ${users.length} users, sent ${totalReminderCount} license expiration reminders`,\n );\n}\n","/**\n * License expiration reminder window bounds.\n *\n * A licence qualifies for the \"7 days before expiry\" reminder when its expiry is\n * between {@link REMINDER_WINDOW_MIN_HOURS} and {@link REMINDER_WINDOW_MAX_HOURS}\n * away.\n *\n * Expressed in hours (derived from days) because dayjs rounds fractional \"day\"\n * adds: `now.add(6.5, \"day\")` becomes 7 days and `now.add(7.5, \"day\")` 8 days.\n */\nexport const REMINDER_WINDOW_MIN_HOURS = 6.5 * 24; // 156 hours\nexport const REMINDER_WINDOW_MAX_HOURS = 7.5 * 24; // 180 hours\n","import {\n dateFormat,\n EnumNotificationResourceType,\n EnumNotificationType,\n EnumUserLicence,\n licenseNiceNames,\n UserLicenceType,\n vendorLicences,\n} from \"@timardex/cluemart-shared\";\nimport { formatDate } from \"@timardex/cluemart-shared/utils\";\nimport dayjs from \"dayjs\";\n\nimport { SchemaUserType, UserModel } from \"src/mongoose/User\";\nimport { ObjectId } from \"src/types\";\n\nimport { sendPushNotifications } from \"../../sendPushNotifications\";\nimport { eventLicences, partnerLicences } from \"../compliance\";\n\nimport { getEventResourceInfo } from \"./event\";\nimport { getPartnerResourceInfo } from \"./partner\";\nimport {\n REMINDER_WINDOW_MAX_HOURS,\n REMINDER_WINDOW_MIN_HOURS,\n} from \"./reminderWindow\";\nimport { getVendorResourceInfo } from \"./vendor\";\n\n/**\n * Checks whether a matching notification exists and inserts one if not, via\n * `findOneAndUpdate` + `upsert` + `$setOnInsert`.\n *\n * **Concurrency:** Upsert alone does not guarantee a single insert under parallel\n * workers unless a **unique** index covers the same fields as `query` (otherwise two\n * operations can both insert). Treat duplicate prevention as requiring that index\n * (or a deterministic `_id`), not upsert semantics by themselves.\n *\n * Uses direct MongoDB access. The inserted document includes the fields needed for\n * a complete notification row.\n *\n * @returns `true` if the notification already existed (or on error, assumed sent),\n * `false` if this call inserted it\n */\nasync function checkAndCreateNotification(payload: {\n data: {\n resourceId: string;\n resourceName: string;\n resourceType: EnumNotificationResourceType;\n };\n message: string;\n title: string;\n type: EnumNotificationType;\n userIds: ObjectId[];\n}): Promise<boolean> {\n // Build query to check if notification already exists\n const query: any = {\n message: payload.message,\n title: payload.title,\n userId: payload.userIds[0],\n };\n\n if (payload.data.resourceId) {\n query[\"data.resourceId\"] = payload.data.resourceId;\n }\n\n // Build the complete notification document to insert if it doesn't exist\n // This includes all required fields for a complete notification\n const notificationDoc: any = {\n createdAt: new Date(),\n data: payload.data,\n isRead: false,\n message: payload.message,\n title: payload.title,\n type: payload.type,\n userId: payload.userIds[0],\n };\n\n // Upsert is not duplicate-proof under concurrency without a matching unique index\n try {\n const result = await UserModel.db\n .collection(\"notifications\")\n .findOneAndUpdate(\n query,\n { $setOnInsert: notificationDoc },\n {\n includeResultMetadata: true,\n returnDocument: \"after\",\n upsert: true,\n },\n );\n\n // Check if the document was inserted (upserted) or already existed\n // If lastErrorObject.upserted exists, the document was just inserted\n const wasInserted = result?.lastErrorObject?.upserted != null;\n\n // If document was inserted, this is the first time (not already sent)\n // If document already existed, notification was already sent\n return !wasInserted;\n } catch (error) {\n // If upsert fails, assume notification already exists to be safe\n console.error(\n `❌ Error atomically checking notification:`,\n error instanceof Error ? error.message : error,\n );\n return true; // Assume already sent to prevent duplicates\n }\n}\n\n/**\n * Checks if a license expires in exactly 7 days (within a day range)\n *\n * Uses a 1-day window (6.5 to 7.5 days) to account for job timing variations.\n * Since the reminder job runs daily at noon (every 24 hours), a license expiring\n * at 6.5 days from now could receive a reminder, and then when the job runs again\n * 24 hours later (at 5.5 days remaining), it would fall outside the window.\n *\n * This ensures reminders are sent once within the 6.5-7.5 day window, not\n * guaranteed to be exactly 7 days before expiration. Duplicate prevention is\n * handled atomically in sendLicenseReminder to prevent race conditions.\n */\nfunction isLicenseExpiringIn7Days(\n expiryDate: Date | string,\n now: dayjs.Dayjs,\n): boolean {\n const expiry = dayjs(expiryDate);\n // Check if expiry is within the reminder window (hours before expiry).\n // Uses hours to stay consistent with the DB query window in\n // remindUsersAboutLicenseExpiration (dayjs rounds fractional \"day\" adds).\n const hoursUntilExpiry = expiry.diff(now, \"hour\", true);\n return (\n hoursUntilExpiry >= REMINDER_WINDOW_MIN_HOURS &&\n hoursUntilExpiry <= REMINDER_WINDOW_MAX_HOURS\n );\n}\n\n/**\n * Gets a human-readable license name\n */\nfunction getLicenseName(licenceType: EnumUserLicence): string {\n return licenseNiceNames[licenceType] || licenceType;\n}\n\n/**\n * Gets notification types based on license type\n */\nfunction getNotificationTypes(\n isVendorLicense: boolean,\n isPartnerLicense: boolean,\n): {\n notificationType: EnumNotificationType;\n resourceType: EnumNotificationResourceType;\n} {\n if (isVendorLicense) {\n return {\n notificationType: EnumNotificationType.SYSTEM,\n resourceType: EnumNotificationResourceType.EXPIRATION_REMINDER_VENDOR,\n };\n }\n if (isPartnerLicense) {\n return {\n notificationType: EnumNotificationType.SYSTEM,\n resourceType: EnumNotificationResourceType.EXPIRATION_REMINDER_PARTNER,\n };\n }\n return {\n notificationType: EnumNotificationType.SYSTEM,\n resourceType: EnumNotificationResourceType.EXPIRATION_REMINDER_EVENT,\n };\n}\n\n/**\n * Gets resource information for a license reminder\n */\nasync function getLicenseResourceInfo(\n user: {\n _id: ObjectId;\n vendor?: ObjectId;\n events?: ObjectId[];\n partner?: ObjectId;\n },\n licence: { licenceType: EnumUserLicence },\n): Promise<{\n notificationType: EnumNotificationType;\n resourceId: string;\n resourceName: string;\n resourceType: EnumNotificationResourceType;\n} | null> {\n const isVendorLicense = vendorLicences.includes(licence.licenceType);\n const isPartnerLicense = partnerLicences.includes(licence.licenceType);\n const licenceName = getLicenseName(licence.licenceType);\n const { notificationType, resourceType } = getNotificationTypes(\n isVendorLicense,\n isPartnerLicense,\n );\n\n if (isVendorLicense && user.vendor) {\n const vendorInfo = await getVendorResourceInfo(user._id, user.vendor);\n if (!vendorInfo) {\n return null;\n }\n return {\n ...vendorInfo,\n notificationType,\n resourceType,\n };\n }\n\n if (eventLicences.includes(licence.licenceType) && user.events?.length) {\n const eventInfo = await getEventResourceInfo(user._id, user.events);\n if (!eventInfo) {\n return null;\n }\n return {\n ...eventInfo,\n notificationType,\n resourceType,\n };\n }\n\n if (isPartnerLicense && user.partner) {\n const partnerInfo = await getPartnerResourceInfo(user._id, user.partner);\n if (!partnerInfo) {\n return null;\n }\n return {\n ...partnerInfo,\n notificationType,\n resourceType,\n };\n }\n\n // Fallback: use license name and user ID\n return {\n notificationType,\n resourceId: String(user._id),\n resourceName: licenceName,\n resourceType,\n };\n}\n\n/**\n * Single source of truth for how a licence type is handled on expiry.\n *\n * - \"downgrade\": PRO_VENDOR / PRO_PLUS_VENDOR → downgraded to STANDARD_VENDOR.\n * - \"extend\": every other licence type is auto-extended for another year.\n *\n * Note: `cluemart-server`'s `licenceCategoryMapping` / `licencePriority`\n * (ModelHelpers/licenses/index.ts) is a SEPARATE concern (entitlement priority,\n * not expiry behaviour) and is intentionally not merged here.\n */\nexport function getLicenceExpiryMode(\n licenceType: EnumUserLicence,\n): \"downgrade\" | \"extend\" {\n return licenceType === EnumUserLicence.PRO_VENDOR ||\n licenceType === EnumUserLicence.PRO_PLUS_VENDOR\n ? \"downgrade\"\n : \"extend\";\n}\n\n/**\n * Sends a reminder notification for a license.\n *\n * Intentionally does NOT use the shared `notifyUsers` helper: that helper\n * persists via `saveNotificationsInDb` (plain `insertMany`), whereas this job\n * must claim the dedupe slot atomically through\n * {@link checkAndCreateNotification} (upsert) so a reminder is only sent once.\n * Push is therefore sent directly via `sendPushNotifications` only after the\n * claim succeeds.\n */\nexport async function sendLicenseReminder(\n user: {\n _id: ObjectId;\n vendor?: ObjectId;\n events?: ObjectId[];\n partner?: ObjectId;\n },\n licence: { licenceType: EnumUserLicence; expiryDate: Date | string },\n): Promise<void> {\n const licenceName = getLicenseName(licence.licenceType);\n const expiryDate = dayjs(licence.expiryDate).format(dateFormat);\n const userId = String(user._id);\n\n const resourceInfo = await getLicenseResourceInfo(user, licence);\n\n if (!resourceInfo) {\n console.log(\n `⏭️ Skipping 7-day reminder for user ${userId}, license ${licence.licenceType} (no resource info)`,\n );\n return;\n }\n\n const isExtension = getLicenceExpiryMode(licence.licenceType) === \"extend\";\n\n const payload = {\n data: {\n resourceId: resourceInfo.resourceId,\n resourceName: resourceInfo.resourceName,\n resourceType: resourceInfo.resourceType,\n },\n message: isExtension\n ? `Your ${licenceName} will be automatically extended for another year on ${formatDate(expiryDate, \"date\")}.`\n : `Your ${licenceName} expires in 7 days (${formatDate(expiryDate, \"date\")}). Renew now to avoid deactivation.`,\n title: isExtension ? \"Licence Extension Reminder\" : \"Licence Expiring Soon\",\n type: resourceInfo.notificationType,\n userIds: [user._id],\n };\n\n // Atomically check and create notification to prevent race conditions\n // If notification already exists, skip sending to avoid duplicates\n const alreadyExists = await checkAndCreateNotification(payload);\n if (alreadyExists) {\n console.log(\n `⏭️ Skipping 7-day reminder to user ${userId} for ${licenceName} (notification already exists)`,\n );\n return;\n }\n\n // Notification was successfully created atomically. Now send push notification.\n await sendPushNotifications(payload);\n console.log(`✅ Sent 7-day reminder to user ${userId} for ${licenceName}`);\n}\n\n/**\n * Processes a single license and sends reminder if needed\n *\n * Checks if a license expires within the 6.5-7.5 day window and hasn't already\n * received a reminder. See isLicenseExpiringIn7Days for details on the reminder window.\n *\n * @returns true if a reminder should be sent, false otherwise\n */\nexport async function processLicenseReminder(\n licence: { licenceType: EnumUserLicence; expiryDate: Date | string },\n now: dayjs.Dayjs,\n): Promise<boolean> {\n // Skip if license is already expired\n if (dayjs(licence.expiryDate).isBefore(now)) {\n return false;\n }\n\n // Check if license expires in 7 days (within 6.5-7.5 day window)\n if (!isLicenseExpiringIn7Days(licence.expiryDate, now)) {\n return false;\n }\n\n // Note: Duplicate checking is handled atomically in sendLicenseReminder\n // to prevent race conditions when multiple job instances run concurrently\n return true;\n}\n\n/**\n * Sends a reminder for a single license, handling errors gracefully\n */\nexport async function sendReminderSafely(\n user: {\n _id: ObjectId;\n vendor?: ObjectId;\n events?: ObjectId[];\n partner?: ObjectId;\n },\n licence: UserLicenceType,\n): Promise<boolean> {\n try {\n await sendLicenseReminder(user, licence);\n return true;\n } catch (err) {\n console.error(\n `❌ Error sending reminder to user ${String(user._id)} for license ${licence.licenceType}:`,\n err instanceof Error ? err.message : err,\n );\n return false;\n }\n}\n\n/**\n * Processes reminders for a single user's licenses\n */\nexport async function processUserLicenseReminders(\n user: SchemaUserType,\n now: dayjs.Dayjs,\n): Promise<number> {\n if (!user.licences) {\n return 0;\n }\n\n // Filter out null/undefined licenses before processing\n const validLicences = user.licences.filter((licence) => licence !== null);\n\n if (validLicences.length === 0) {\n return 0;\n }\n\n const licenceChecks = await Promise.all(\n validLicences.map(async (licence) => {\n try {\n const shouldSend = await processLicenseReminder(licence, now);\n return { licence, shouldSend };\n } catch (err) {\n console.error(\n `❌ Error checking license reminder for user ${String(user._id)} for license ${licence.licenceType}:`,\n err instanceof Error ? err.message : err,\n );\n // Return false to skip this license but continue processing others\n return { licence, shouldSend: false };\n }\n }),\n );\n\n const licencesToNotify = licenceChecks\n .filter((check) => check.shouldSend)\n .map((check) => check.licence);\n\n if (!licencesToNotify.length) {\n return 0;\n }\n\n // Process reminders individually to prevent one failure from blocking others\n const results = await Promise.all(\n licencesToNotify.map((licence) => sendReminderSafely(user, licence)),\n );\n\n return results.filter(Boolean).length;\n}\n","import { SchemaVendorType, VendorModel } from \"src/mongoose/vendor/Vendor\";\nimport { ObjectId } from \"src/types\";\n\n/**\n * Gets vendor resource information for a reminder\n */\nexport async function getVendorResourceInfo(\n userId: ObjectId,\n vendorId: ObjectId,\n): Promise<{ resourceId: string; resourceName: string } | null> {\n const vendor = await VendorModel.findOne({\n _id: vendorId,\n active: true,\n deletedAt: null,\n \"owner.userId\": userId,\n })\n .lean<SchemaVendorType>()\n .exec();\n\n if (!vendor) {\n return null;\n }\n return {\n resourceId: String(vendor._id),\n resourceName: vendor.name,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;AACO,IAAM,4BAA4B;AAAA,EACvC,QAAQ;AAAA,EACR,WAAW;AACb;;;ACSA,eAAsB,0BACpB,eACkB;AAClB,QAAM,WAAW,MAAM,eAAe,OAAO;AAAA,IAC3C,GAAG;AAAA,IACH;AAAA,EACF,CAAC,EAAE,KAAK;AAER,SAAO,aAAa;AACtB;;;ACtBA;AAAA,EAGE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,6BAA6B;;;ACGtC,eAAsB,sBACpB,SACqB;AACrB,QAAM,EAAE,MAAM,SAAS,OAAO,MAAM,QAAQ,IAAI;AAChD,QAAM,gBAAgB,QAAQ,I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4BAA4B,MAAM,GAAG;AACjE,4BAAsB;AAAA,IACxB,SAAS,KAAK;AACZ,cAAQ;AAAA,QACN,sDAAiD,OAAO,KAAK,GAAG,CAAC;AAAA,QACjE,eAAe,QAAQ,IAAI,UAAU;AAAA,MACvC;AAAA,IAEF;AAAA,EACF;AAEA,UAAQ;AAAA,IACN,oBAAe,MAAM,MAAM,gBAAgB,kBAAkB;AAAA,EAC/D;AACF;","names":["EnumUserLicence","EnumUserLicence","mongoose","EnumEventDateStatus","dayjs","EnumEventDateStatus","dayjs","updateSingleDateTimeStatus","dayjs","EnumUserLicence","dayjs","EnumUserLicence","EnumUserLicence","EnumUserLicence","EnumUserLicence","EnumNotificationResourceType","EnumNotificationType","EnumSubscriptionStatus","EnumUserLicence","dayjs","EnumResourceType","EnumUserLicence","dayjs","LicenceCategory","EnumUserLicence","dayjs","EnumResourceType","EnumUserLicence","dayjs","EnumSubscriptionStatus","EnumNotificationResourceType","EnumNotificationType","EnumUserLicence","dayjs","dayjs","dayjs","EnumNotificationResourceType","EnumNotificationType","EnumUserLicence","vendorLicences","dayjs","dayjs","EnumNotificationType","EnumNotificationResourceType","vendorLicences","EnumUserLicence","dayjs"]}