@timardex/cluemart-server-shared 4.0.1 → 4.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-J7ZINA3I.mjs → chunk-3ICI65FJ.mjs} +350 -242
- package/dist/chunk-3ICI65FJ.mjs.map +1 -0
- package/dist/index.cjs +540 -432
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.mts +92 -10
- package/dist/index.d.ts +92 -10
- package/dist/index.mjs +356 -248
- package/dist/index.mjs.map +1 -1
- package/dist/mongoose/index.cjs +410 -302
- package/dist/mongoose/index.cjs.map +1 -1
- package/dist/mongoose/index.d.mts +88 -7
- package/dist/mongoose/index.d.ts +88 -7
- package/dist/mongoose/index.mjs +9 -3
- package/dist/service/index.cjs +529 -428
- package/dist/service/index.cjs.map +1 -1
- package/dist/service/index.d.mts +4 -3
- package/dist/service/index.d.ts +4 -3
- package/dist/service/index.mjs +1 -1
- package/dist/service/index.mjs.map +1 -1
- package/package.json +2 -2
- package/dist/chunk-J7ZINA3I.mjs.map +0 -1
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/mongoose/ad/Ad.ts","../src/mongoose/ad/AdBillingCatalog.ts","../src/mongoose/ad/AdBooking.ts","../src/mongoose/ad/AdPurchase.ts","../src/mongoose/ad/AdMetrics.ts","../src/mongoose/BillingCatalog.ts","../src/mongoose/chat/Chat.ts","../src/mongoose/chat/ChatReport.ts","../src/mongoose/global.ts","../src/mongoose/GoogleImportedMarket.ts","../src/mongoose/searchNamePlugin.ts","../src/mongoose/AiImportedMarket.ts","../src/mongoose/ScrapeSite.ts","../src/mongoose/Notification.ts","../src/mongoose/PushToken.ts","../src/mongoose/Relation.ts","../src/mongoose/event/EventInfo.ts","../src/mongoose/ResourceActivity.ts","../src/mongoose/User.ts","../src/mongoose/VerificationToken.ts","../src/mongoose/vendor/Vendor.ts","../src/mongoose/vendor/VendorInfo.ts","../src/mongoose/vendor/UnregisteredVendor.ts","../src/mongoose/event/Event.ts","../src/mongoose/event/EventDateArchive.ts","../src/mongoose/Partner.ts","../src/mongoose/Post.ts","../src/mongoose/AppSetting.ts","../src/mongoose/AuthHandoffToken.ts","../src/mongoose/game/Game.ts","../src/mongoose/game/DailyClue.ts","../src/mongoose/game/utils.ts","../src/mongoose/game/PuzzleGame.ts","../src/mongoose/School.ts","../src/mongoose/Affiliate.ts","../src/mongoose/Coupon.ts","../src/mongoose/Impersonation.ts","../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/types/index.ts","../src/service/notifyUsers.ts","../src/service/updateAdStatus.ts","../src/service/objectIdToString.ts","../src/service/userPoints.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":["export * from \"./mongoose\";\nexport * from \"./service\";\nexport * from \"./types\";\n","import {\n EnumAdApprovalStatus,\n EnumAdBookingSlotKind,\n EnumAdPaymentStatus,\n AdType,\n EnumAdShowOn,\n EnumAdStatus,\n EnumAdStyle,\n EnumAdType,\n EnumResourceType,\n isUtcMidnight,\n} from \"@timardex/cluemart-shared\";\nimport mongoose from \"mongoose\";\n\nconst MongooseSchema = mongoose.Schema;\n\nexport const schemaAdresource = new MongooseSchema<AdType[\"resource\"]>({\n adDescription: { required: true, type: String },\n adImage: { required: true, type: String },\n adStyle: {\n default: EnumAdStyle.BLOOM,\n enum: Object.values(EnumAdStyle),\n required: true,\n type: String,\n },\n adTitle: { required: true, type: String },\n adType: {\n default: EnumAdType.SPONSORED,\n enum: Object.values(EnumAdType),\n required: true,\n type: String,\n },\n resourceId: { required: true, type: String },\n resourceName: { required: true, type: String },\n resourceRegion: { required: true, type: String },\n resourceSlug: { required: true, type: String },\n resourceType: {\n enum: Object.values(EnumResourceType),\n required: true,\n type: String,\n },\n});\n\nconst schema = new MongooseSchema<AdType>(\n {\n active: { default: true, type: Boolean },\n approvalStatus: {\n enum: Object.values(EnumAdApprovalStatus),\n required: false,\n type: String,\n },\n bookingIds: {\n default: undefined,\n ref: \"AdBooking\",\n type: [mongoose.Schema.Types.ObjectId],\n },\n bookingKind: {\n enum: Object.values(EnumAdBookingSlotKind),\n required: false,\n type: String,\n },\n end: {\n required: true,\n type: Date,\n validate: {\n message: \"end must be a UTC-midnight day key.\",\n validator: isUtcMidnight,\n },\n },\n paymentStatus: {\n enum: Object.values(EnumAdPaymentStatus),\n required: false,\n type: String,\n },\n resource: { required: true, type: schemaAdresource },\n showOn: {\n default: [EnumAdShowOn.FRONT_PAGE],\n enum: Object.values(EnumAdShowOn),\n required: true,\n type: [String],\n },\n start: {\n required: true,\n type: Date,\n validate: {\n message: \"start must be a UTC-midnight day key.\",\n validator: isUtcMidnight,\n },\n },\n status: {\n default: EnumAdStatus.ACTIVE,\n enum: Object.values(EnumAdStatus),\n required: true,\n type: String,\n },\n targetRegion: { required: false, type: [String] },\n },\n {\n timestamps: true,\n },\n);\n\n// Background job queries (updateAdStatuses): filter on `end` first\n// (`expired`: end <= now, `active`: end > now && start <= now), so `end` must\n// lead, followed by the next range/equality keys in order of use.\nschema.index({\n end: 1,\n start: 1,\n status: 1,\n});\n\n// Hot read path (getAdsByRegion): `{ status, targetRegion: $in, active }`\n// sorted by `start` desc. Equality/$in keys must come before the sort key, so\n// `status` leads (most selective), then `targetRegion`, then `start` for the\n// sort. Order matters: with `start` leading, Mongo could only sort, not bound\n// the scan by status/region.\nschema.index({\n status: 1,\n targetRegion: 1,\n // eslint-disable-next-line sort-keys\n start: -1,\n});\n\nschema.index(\n { bookingIds: 1 },\n {\n partialFilterExpression: { bookingIds: { $exists: true } },\n unique: true,\n },\n);\n\nexport const AdModel =\n (mongoose.models.Ad as mongoose.Model<AdType>) ||\n mongoose.model<AdType>(\"Ad\", schema);\n","import { AdDailyPriceType, EnumAdShowOn } from \"@timardex/cluemart-shared\";\nimport mongoose from \"mongoose\";\n\nexport const AD_BILLING_CATALOG_COLLECTION_NAME = \"adBillingCatalog\";\n\nconst schema = new mongoose.Schema<AdDailyPriceType>(\n {\n active: { default: true, required: true, type: Boolean },\n currency: {\n default: \"nzd\",\n enum: [\"nzd\"],\n immutable: true,\n required: true,\n type: String,\n },\n key: {\n enum: Object.values(EnumAdShowOn),\n immutable: true,\n required: true,\n type: String,\n unique: true,\n },\n revision: { default: 1, min: 1, required: true, type: Number },\n unitAmount: {\n min: 1,\n required: true,\n type: Number,\n validate: {\n message: \"Daily ad price must be a positive integer amount of cents.\",\n validator: Number.isInteger,\n },\n },\n },\n { collection: AD_BILLING_CATALOG_COLLECTION_NAME, timestamps: true },\n);\n\nexport const AdBillingCatalogModel =\n (mongoose.models.AdBillingCatalog as mongoose.Model<AdDailyPriceType>) ||\n mongoose.model<AdDailyPriceType>(\n \"AdBillingCatalog\",\n schema,\n AD_BILLING_CATALOG_COLLECTION_NAME,\n );\n","import {\n AdBookingType,\n EnumAdApprovalStatus,\n EnumAdBookingSlotKind,\n EnumAdBookingState,\n EnumAdShowOn,\n isUtcMidnight,\n} from \"@timardex/cluemart-shared\";\nimport mongoose from \"mongoose\";\n\nimport { schemaAdresource } from \"./Ad\";\n\nconst liveStates = [\n EnumAdBookingState.HELD,\n EnumAdBookingState.PENDING_APPROVAL,\n EnumAdBookingState.APPROVED,\n];\n\nconst schema = new mongoose.Schema<AdBookingType>(\n {\n adId: { default: null, ref: \"Ad\", type: String },\n approvalStatus: {\n default: EnumAdApprovalStatus.PENDING,\n enum: Object.values(EnumAdApprovalStatus),\n required: true,\n type: String,\n },\n checkoutAttemptId: { default: null, type: String },\n currency: { default: null, lowercase: true, type: String },\n dayKey: {\n immutable: true,\n required: true,\n type: Date,\n validate: {\n message: \"dayKey must be a UTC-midnight day key.\",\n validator: isUtcMidnight,\n },\n },\n expiresAt: { default: null, type: Date },\n placement: {\n enum: Object.values(EnumAdShowOn),\n immutable: true,\n required: true,\n type: String,\n },\n purchaseKey: { default: null, immutable: true, type: String },\n region: {\n immutable: true,\n lowercase: true,\n required: true,\n trim: true,\n type: String,\n },\n resource: { required: true, type: schemaAdresource },\n slotKind: {\n default: EnumAdBookingSlotKind.PAID,\n enum: Object.values(EnumAdBookingSlotKind),\n immutable: true,\n required: true,\n type: String,\n },\n slotNumber: { immutable: true, min: 1, required: true, type: Number },\n state: {\n default: EnumAdBookingState.HELD,\n enum: Object.values(EnumAdBookingState),\n required: true,\n type: String,\n },\n stripeCheckoutSessionId: { default: null, type: String },\n stripePaymentIntentId: { default: null, type: String },\n unitAmount: { default: null, min: 1, type: Number },\n userId: { immutable: true, ref: \"User\", required: true, type: String },\n },\n { timestamps: true },\n);\n\nschema.pre(\n \"validate\",\n function validateSlot(this: mongoose.HydratedDocument<AdBookingType>) {\n if (!Number.isInteger(this.slotNumber)) {\n this.invalidate(\"slotNumber\", \"Ad booking slot must be an integer.\");\n return;\n }\n\n const maximum = 30;\n if (this.slotNumber < 1 || this.slotNumber > maximum) {\n this.invalidate(\n \"slotNumber\",\n `Ad booking slot must be between 1 and ${maximum}.`,\n );\n }\n\n if (\n this.slotKind === EnumAdBookingSlotKind.PAID &&\n this.state !== EnumAdBookingState.HELD &&\n this.state !== EnumAdBookingState.FAILED &&\n this.state !== EnumAdBookingState.CANCELLED &&\n (!this.unitAmount || !this.currency)\n ) {\n this.invalidate(\n \"unitAmount\",\n \"Paid ad booking must retain its checkout price.\",\n );\n }\n },\n);\n\n// A released slot can be reused while retaining failed/cancelled/rejected history.\n/* eslint-disable sort-keys -- Compound-index field order controls slot lookups. */\nschema.index(\n { region: 1, placement: 1, dayKey: 1, slotKind: 1, slotNumber: 1 },\n { unique: true, partialFilterExpression: { state: { $in: liveStates } } },\n);\nschema.index({ userId: 1, dayKey: -1 });\nschema.index(\n { checkoutAttemptId: 1 },\n {\n partialFilterExpression: { checkoutAttemptId: { $type: \"string\" } },\n unique: true,\n },\n);\nschema.index(\n { purchaseKey: 1 },\n {\n partialFilterExpression: {\n purchaseKey: { $type: \"string\" },\n state: { $in: liveStates },\n },\n unique: true,\n },\n);\n/* eslint-enable sort-keys */\nschema.index(\n { stripeCheckoutSessionId: 1 },\n {\n partialFilterExpression: { stripeCheckoutSessionId: { $type: \"string\" } },\n unique: true,\n },\n);\n\nexport const AdBookingModel =\n (mongoose.models.AdBooking as mongoose.Model<AdBookingType>) ||\n mongoose.model<AdBookingType>(\"AdBooking\", schema);\n","import mongoose from \"mongoose\";\n\nimport { schemaAdresource } from \"./Ad\";\n\n/** One Stripe payment covers individually capacity-guarded daily bookings. */\nconst schema = new mongoose.Schema(\n {\n _id: { required: true, type: String },\n approvalRequired: { type: Boolean },\n bookingIds: { required: true, type: [String] },\n checkoutAttemptId: { required: true, type: String },\n checkoutLeaseUntil: { type: Date },\n checkoutLeaseToken: { type: String },\n createdAt: { default: Date.now, required: true, type: Date },\n expiresAt: { required: true, type: Date },\n holdsReleased: { type: Boolean },\n quote: { required: true, type: mongoose.Schema.Types.Mixed },\n resource: { required: true, type: schemaAdresource },\n selectionKey: { required: true, type: String },\n state: {\n enum: [\"reserving\", \"checkout\", \"paid\", \"failed\", \"cancelled\"],\n required: true,\n type: String,\n },\n stripeCheckoutSessionId: { default: null, type: String },\n stripePaymentIntentId: { default: null, type: String },\n stripeRequestStartedAt: { type: Date },\n userId: { required: true, type: String },\n },\n { collection: \"adPurchases\" },\n);\n\n/* eslint-disable sort-keys -- Unique index matches checkout ownership and attempt. */\nschema.index({ userId: 1, checkoutAttemptId: 1 }, { unique: true });\n/* eslint-enable sort-keys */\nschema.index(\n { stripeCheckoutSessionId: 1 },\n {\n unique: true,\n partialFilterExpression: { stripeCheckoutSessionId: { $type: \"string\" } },\n },\n);\n/* eslint-disable sort-keys -- Expired purchase scan. */\nschema.index({ state: 1, expiresAt: 1 });\n/* eslint-enable sort-keys */\n\nexport const AdPurchaseModel =\n mongoose.models.AdPurchase || mongoose.model(\"AdPurchase\", schema);\n","import {\n AdMetricsResourceType,\n AdMetricsType,\n EnumAdPlatform,\n EnumAdShowOn,\n isUtcMidnight,\n} from \"@timardex/cluemart-shared\";\nimport mongoose from \"mongoose\";\n\nconst ResourceMetricsSchema = new mongoose.Schema<AdMetricsResourceType>(\n {\n clicks: { default: 0, required: true, type: Number },\n date: {\n immutable: true,\n required: true,\n type: Date,\n validate: {\n message: \"date must be a UTC-midnight day key.\",\n validator: isUtcMidnight,\n },\n },\n impressions: { default: 0, required: true, type: Number },\n placement: {\n enum: Object.values(EnumAdShowOn),\n immutable: true,\n required: true,\n type: String,\n },\n platform: {\n enum: Object.values(EnumAdPlatform),\n immutable: true,\n required: true,\n type: String,\n },\n },\n { _id: false },\n);\n\nconst schema = new mongoose.Schema<AdMetricsType>(\n {\n adId: { ref: \"Ad\", required: true, type: String },\n resource: { default: [], type: [ResourceMetricsSchema] },\n },\n { timestamps: true },\n);\n\n// One metrics document per ad, with a bucket per NZ calendar day, placement\n// and platform inside its `resource` array.\n//\n// The `adId` unique index enforces one document per ad so concurrent `$push`\n// upserts can't create duplicate parent documents; the compound multikey index\n// enforces one bucket per (ad, day, placement, platform) across documents.\nschema.index({ adId: 1 }, { unique: true });\nschema.index(\n {\n adId: 1,\n \"resource.date\": 1,\n \"resource.placement\": 1,\n \"resource.platform\": 1,\n },\n { unique: true },\n);\n\nexport const AdMetricsModel =\n (mongoose.models.AdMetrics as mongoose.Model<AdMetricsType>) ||\n mongoose.model<AdMetricsType>(\"AdMetrics\", schema);\n","import {\n BILLING_CATALOG_CURRENCY,\n BILLING_CATALOG_DEFINITIONS,\n BILLING_CATALOG_KEYS,\n billingCatalogDefinitionMatches,\n BillingCatalogEntryType,\n BillingCatalogPriceHistoryEntry,\n EnumBillingPeriod,\n EnumUserLicence,\n INITIAL_BILLING_CATALOG,\n} from \"@timardex/cluemart-shared\";\nimport mongoose from \"mongoose\";\n\nimport { ObjectId } from \"src/types\";\n\nconst MongooseSchema = mongoose.Schema;\n\nexport const BILLING_CATALOG_COLLECTION_NAME = \"billingCatalog\";\n\nexport type SchemaBillingCatalogPriceHistoryEntry = Omit<\n BillingCatalogPriceHistoryEntry,\n \"changedBy\"\n> & {\n changedBy?: ObjectId | null;\n};\n\nexport type SchemaBillingCatalogEntry = Omit<\n BillingCatalogEntryType,\n \"_id\" | \"priceHistory\" | \"updatedBy\"\n> & {\n _id: ObjectId;\n priceHistory: SchemaBillingCatalogPriceHistoryEntry[];\n updatedBy?: ObjectId | null;\n};\n\nconst paidVendorLicences = [\n EnumUserLicence.PRO_VENDOR,\n EnumUserLicence.PRO_PLUS_VENDOR,\n] as const;\n\nconst supportedBillingPeriods = [\n EnumBillingPeriod.MONTHLY_CANCEL_ANYTIME,\n EnumBillingPeriod.YEARLY_ANNUAL_BILLED,\n] as const;\n\nconst unitAmountField = {\n min: 1,\n required: true,\n type: Number,\n validate: {\n message: \"Billing catalogue price must be a positive integer.\",\n validator: Number.isInteger,\n },\n} as const;\n\nconst currencyField = {\n default: BILLING_CATALOG_CURRENCY,\n enum: [BILLING_CATALOG_CURRENCY],\n immutable: true,\n lowercase: true,\n required: true,\n trim: true,\n type: String,\n} as const;\n\nconst stripePriceIdField = {\n default: null,\n required: false,\n trim: true,\n type: String,\n} as const;\n\nconst stripeProductIdField = {\n default: null,\n required: false,\n trim: true,\n type: String,\n} as const;\n\nconst priceHistorySchema =\n new MongooseSchema<SchemaBillingCatalogPriceHistoryEntry>(\n {\n changedAt: { required: true, type: Date },\n changedBy: {\n default: null,\n ref: \"User\",\n required: false,\n type: mongoose.Schema.Types.ObjectId,\n },\n currency: currencyField,\n effectiveFrom: { required: true, type: Date },\n effectiveTo: { required: true, type: Date },\n stripePriceId: stripePriceIdField,\n stripeProductId: stripeProductIdField,\n unitAmount: unitAmountField,\n },\n { _id: false },\n );\n\nconst schema = new MongooseSchema<SchemaBillingCatalogEntry>(\n {\n active: { default: true, required: true, type: Boolean },\n billingPeriod: {\n enum: supportedBillingPeriods,\n immutable: true,\n required: true,\n type: String,\n },\n currency: currencyField,\n effectiveFrom: { default: Date.now, required: true, type: Date },\n key: {\n enum: BILLING_CATALOG_KEYS,\n immutable: true,\n required: true,\n type: String,\n unique: true,\n },\n licenceType: {\n enum: paidVendorLicences,\n immutable: true,\n required: true,\n type: String,\n },\n priceHistory: {\n default: [],\n required: true,\n type: [priceHistorySchema],\n },\n revision: {\n default: 1,\n min: 1,\n required: true,\n type: Number,\n validate: {\n message: \"Billing catalogue revision must be a positive integer.\",\n validator: Number.isInteger,\n },\n },\n stripePriceId: stripePriceIdField,\n stripeProductId: stripeProductIdField,\n taxInclusive: {\n default: true,\n immutable: true,\n required: true,\n type: Boolean,\n validate: {\n message: \"Billing catalogue prices must include GST.\",\n validator: (value: boolean) => value === true,\n },\n },\n unitAmount: unitAmountField,\n updatedBy: {\n default: null,\n ref: \"User\",\n required: false,\n type: mongoose.Schema.Types.ObjectId,\n },\n },\n {\n collection: BILLING_CATALOG_COLLECTION_NAME,\n strict: true,\n timestamps: true,\n },\n);\n\nschema.pre(\"validate\", function validateDefinition() {\n if (!billingCatalogDefinitionMatches(this)) {\n this.invalidate(\n \"key\",\n \"Billing catalogue key does not match its licence and billing period.\",\n );\n }\n});\n\nschema.index({ billingPeriod: 1, licenceType: 1 }, { unique: true });\nschema.index({ active: 1, licenceType: 1 });\nschema.index(\n { stripePriceId: 1 },\n {\n partialFilterExpression: { stripePriceId: { $type: \"string\" } },\n unique: true,\n },\n);\n\nexport const BillingCatalogModel =\n (mongoose.models\n .BillingCatalogEntry as mongoose.Model<SchemaBillingCatalogEntry>) ||\n mongoose.model<SchemaBillingCatalogEntry>(\n \"BillingCatalogEntry\",\n schema,\n BILLING_CATALOG_COLLECTION_NAME,\n );\n\n/**\n * Produces the four records used for an idempotent `$setOnInsert` catalogue\n * initialisation. Stripe identifiers deliberately start empty and are attached\n * only after Stripe successfully creates the matching Product and Price.\n */\nexport function buildInitialBillingCatalogEntries(now: Date = new Date()) {\n return INITIAL_BILLING_CATALOG.map((entry) => ({\n active: entry.active,\n billingPeriod: entry.billingPeriod,\n currency: entry.currency,\n effectiveFrom: new Date(now.getTime()),\n key: entry.key,\n licenceType: entry.licenceType,\n priceHistory: [],\n revision: 1,\n stripePriceId: null,\n stripeProductId: null,\n taxInclusive: entry.taxInclusive,\n unitAmount: entry.unitAmount,\n updatedBy: null,\n }));\n}\n\nexport function getBillingCatalogDefinition(\n key: (typeof BILLING_CATALOG_KEYS)[number],\n) {\n return BILLING_CATALOG_DEFINITIONS[key];\n}\n","import {\n ChatMessageType,\n ChatType,\n EnumChatType,\n ParticipantType,\n} from \"@timardex/cluemart-shared\";\nimport mongoose from \"mongoose\";\n\nimport { ObjectId } from \"src/types\";\n\nconst MongooseSchema = mongoose.Schema;\n\nexport type SchemaChatMessageReplyPreviewType = Omit<\n NonNullable<ChatMessageType[\"replyPreview\"]>,\n \"senderId\"\n> & {\n senderId: ObjectId;\n};\n\nexport type SchemaChatMessageReactionType = Omit<\n NonNullable<ChatMessageType[\"likedBy\"]>[number],\n \"userId\"\n> & {\n userId: ObjectId;\n};\n\nexport type SchemaChatMessageSeenType = Omit<\n NonNullable<ChatMessageType[\"seenBy\"]>[number],\n \"userId\"\n> & {\n userId: ObjectId;\n};\n\nexport type SchemaChatMessageType = Omit<\n ChatMessageType,\n \"senderId\" | \"replyToMessageId\" | \"replyPreview\" | \"likedBy\" | \"seenBy\"\n> & {\n senderId: ObjectId;\n replyToMessageId?: ObjectId | null;\n replyPreview?: SchemaChatMessageReplyPreviewType | null;\n likedBy?: SchemaChatMessageReactionType[];\n seenBy?: SchemaChatMessageSeenType[];\n};\n\nexport type SchemaParticipantType = Omit<ParticipantType, \"userId\"> & {\n userId: ObjectId;\n};\n\nconst MessageReplyPreviewSchema =\n new MongooseSchema<SchemaChatMessageReplyPreviewType>(\n {\n contentPreview: { required: true, type: String },\n senderId: {\n ref: \"User\",\n required: true,\n type: mongoose.Schema.Types.ObjectId,\n },\n senderName: { required: true, type: String },\n },\n { _id: false },\n );\n\nconst MessageReactionSchema = new MongooseSchema<SchemaChatMessageReactionType>(\n {\n createdAt: { required: true, type: Date },\n userId: {\n ref: \"User\",\n required: true,\n type: mongoose.Schema.Types.ObjectId,\n },\n },\n { _id: false },\n);\n\nconst MessageSeenSchema = new MongooseSchema<SchemaChatMessageSeenType>(\n {\n seenAt: { required: true, type: Date },\n userId: {\n ref: \"User\",\n required: true,\n type: mongoose.Schema.Types.ObjectId,\n },\n },\n { _id: false },\n);\n\nconst MessageSchema = new MongooseSchema<SchemaChatMessageType>(\n {\n content: { required: true, type: String },\n likedBy: { default: [], required: false, type: [MessageReactionSchema] },\n replyPreview: {\n required: false,\n type: MessageReplyPreviewSchema,\n },\n replyToMessageId: {\n ref: \"Chat.messages\",\n required: false,\n type: mongoose.Schema.Types.ObjectId,\n },\n seenBy: { default: [], required: false, type: [MessageSeenSchema] },\n senderId: {\n ref: \"User\",\n required: true,\n type: mongoose.Schema.Types.ObjectId,\n },\n },\n { timestamps: true },\n);\n\nexport type SchemaChatType = Omit<ChatType, \"participants\" | \"messages\"> & {\n participants: SchemaParticipantType[];\n messages: SchemaChatMessageType[];\n};\n\nconst ParticipantSchema = new MongooseSchema<SchemaParticipantType>(\n {\n active: { default: true, required: true, type: Boolean },\n userAvatar: { required: false, type: String },\n userEmail: { required: true, type: String },\n userId: {\n ref: \"User\",\n required: true,\n type: mongoose.Schema.Types.ObjectId,\n },\n userName: { required: true, type: String },\n },\n { _id: false }, // Prevents Mongoose from creating an additional _id field for subdocuments\n);\n\nconst ChatSchema = new MongooseSchema<SchemaChatType>(\n {\n active: { default: true, required: true, type: Boolean },\n chatDescription: { required: false, type: String },\n chatName: { required: true, type: String },\n chatType: {\n enum: Object.values(EnumChatType),\n required: true,\n type: String,\n },\n deletedAt: { default: null, required: false, type: Date },\n messages: [MessageSchema],\n participants: [ParticipantSchema],\n region: { default: null, required: false, type: String },\n },\n {\n timestamps: true,\n },\n);\n\nChatSchema.index({\n \"participants.active\": 1,\n \"participants.userId\": 1,\n updatedAt: -1,\n});\n\nexport const ChatModel =\n (mongoose.models.Chat as mongoose.Model<SchemaChatType>) ||\n mongoose.model<SchemaChatType>(\"Chat\", ChatSchema);\n","import {\n EnumChatReportReason,\n ReportChatUser,\n} from \"@timardex/cluemart-shared\";\nimport mongoose from \"mongoose\";\n\nimport { ObjectId } from \"src/types\";\n\nconst MongooseSchema = mongoose.Schema;\n\nexport type SchemaChatReportType = Omit<\n ReportChatUser,\n \"reporterUserId\" | \"reportedUserId\" | \"chatId\"\n> & {\n reporterUserId: ObjectId;\n reportedUserId: ObjectId;\n chatId: ObjectId;\n};\n\nconst ReasonSchema = new MongooseSchema<\n NonNullable<ReportChatUser[\"reason\"]>,\n null,\n unknown\n>(\n {\n details: { default: null, required: false, type: String },\n reasonType: {\n enum: Object.values(EnumChatReportReason),\n required: true,\n type: String,\n },\n },\n { _id: false },\n);\n\nconst ChatReportSchema = new MongooseSchema<SchemaChatReportType>(\n {\n chatId: {\n ref: \"Chat\",\n required: true,\n type: mongoose.Schema.Types.ObjectId,\n },\n reason: { required: true, type: ReasonSchema },\n reportedUserId: {\n ref: \"User\",\n required: true,\n type: mongoose.Schema.Types.ObjectId,\n },\n reporterUserId: {\n ref: \"User\",\n required: true,\n type: mongoose.Schema.Types.ObjectId,\n },\n resolved: { default: false, required: true, type: Boolean },\n },\n { timestamps: true },\n);\n\nChatReportSchema.index({ chatId: 1, reportedUserId: 1 });\nChatReportSchema.index({ createdAt: -1, reporterUserId: 1 });\n\nexport const ChatReportModel =\n (mongoose.models.ChatReport as mongoose.Model<SchemaChatReportType>) ||\n mongoose.model<SchemaChatReportType>(\"ChatReport\", ChatReportSchema);\n","import {\n Category,\n DateTimeType,\n EnumEventDateStatus,\n EnumPostType,\n EnumUserLicence,\n LocationGeoType,\n LocationType,\n OwnerType,\n PosterUsageType,\n RelatedPostType,\n ResourceContactDetailsType,\n ResourceImageType,\n SocialMediaType,\n SocialShareResourceType,\n Subcategory,\n TermsAgreement,\n UserLicenceType,\n} from \"@timardex/cluemart-shared\";\nimport mongoose from \"mongoose\";\n\nimport { ObjectId } from \"src/types\";\n\nconst MongooseSchema = mongoose.Schema;\n\nexport type SchemaRelatedPostType = Omit<RelatedPostType, \"postId\"> & {\n postId: ObjectId;\n};\n\nexport type SchemaOwnerType = Omit<OwnerType, \"userId\"> & {\n userId: ObjectId;\n};\n\nexport const OwnerTypeSchema = new MongooseSchema<SchemaOwnerType>(\n {\n email: { required: true, type: String },\n userId: {\n ref: \"User\",\n required: true,\n type: mongoose.Schema.Types.ObjectId,\n },\n },\n { _id: false }, // Prevents Mongoose from creating an additional _id field for subdocuments\n);\n\nexport const SocialMediaTypeSchema = new MongooseSchema<SocialMediaType>(\n {\n link: { required: true, type: String },\n name: { required: true, type: String },\n },\n { _id: false }, // Prevents Mongoose from creating an additional _id field\n);\n\nexport const ResourceImageTypeSchema = new MongooseSchema<ResourceImageType>(\n {\n active: { default: true, required: true, type: Boolean },\n source: { required: false, type: String },\n title: { required: false, type: String },\n },\n { _id: false }, // Prevents Mongoose from creating an additional _id field for subdocuments\n);\n\nconst SubCategorySchema = new MongooseSchema<Subcategory>(\n {\n id: { required: false, type: String },\n items: [\n {\n id: { required: false, type: String },\n name: { required: false, type: String },\n },\n ],\n name: { required: false, type: String },\n },\n { _id: false }, // Prevents Mongoose from creating an additional _id field for subdocuments\n);\n\nexport const CategorySchema = new MongooseSchema<Category>(\n {\n id: { required: true, type: String },\n name: { required: true, type: String },\n subcategories: [SubCategorySchema],\n },\n { _id: false }, // Prevents Mongoose from creating an additional _id field for subdocuments\n);\n\nconst PosterUsageTypeSchema = new MongooseSchema<PosterUsageType>(\n {\n count: { default: 0, required: false, type: Number },\n month: { required: false, type: String },\n },\n { _id: false }, // Prevents Mongoose from creating an additional _id field for subdocuments\n);\n\nexport const userLicenseSchema = new MongooseSchema<UserLicenceType>(\n {\n expiryDate: { required: true, type: Date },\n issuedDate: { required: true, type: Date },\n licenceType: {\n enum: Object.values(EnumUserLicence),\n required: true,\n type: String,\n },\n prevLicenceType: {\n enum: Object.values(EnumUserLicence),\n required: false,\n type: String,\n },\n },\n { _id: false, timestamps: false },\n);\n\nexport const ContactDetailsSchema =\n new MongooseSchema<ResourceContactDetailsType>(\n {\n email: { required: false, type: String },\n landlinePhone: { required: false, type: String },\n mobilePhone: { required: false, type: String },\n },\n { _id: false }, // Prevents Mongoose from creating an additional _id field for subdocuments\n );\n\nexport const termsAgreementSchema = new MongooseSchema<TermsAgreement>(\n {\n appBuildNumber: { required: true, type: String },\n appId: { required: true, type: String },\n appVersion: { required: true, type: String },\n brand: { required: true, type: String },\n deviceName: { required: true, type: String },\n installationId: { required: true, type: String },\n manufacturer: { required: true, type: String },\n modelName: { required: true, type: String },\n osName: { required: true, type: String },\n osVersion: { required: true, type: String },\n termVersion: { required: true, type: String },\n timestamp: { required: true, type: Date },\n },\n { _id: false },\n);\n\nexport const dateTimeSchema = new MongooseSchema<DateTimeType>(\n {\n dateStatus: {\n enum: Object.values(EnumEventDateStatus),\n required: false,\n type: String,\n },\n endDate: { required: true, type: String },\n endTime: { required: true, type: String },\n startDate: { required: true, type: String },\n startTime: { required: true, type: String },\n },\n { _id: false }, // Prevents Mongoose from creating an additional _id field for subdocuments\n);\n\nexport const locationGeoSchema = new MongooseSchema<LocationGeoType>(\n {\n coordinates: { required: true, type: [Number] }, // [longitude, latitude]\n type: { default: \"Point\", enum: [\"Point\"], required: true, type: String },\n },\n { _id: false }, // Prevents Mongoose from creating an additional _id field for subdocuments\n);\n\nexport const locationsSchema = new MongooseSchema<LocationType>(\n {\n city: { required: true, type: String },\n country: { required: true, type: String },\n fullAddress: { required: true, type: String },\n geo: {\n required: true,\n type: locationGeoSchema,\n },\n latitude: { required: true, type: Number },\n longitude: { required: true, type: Number },\n region: { required: true, type: String },\n },\n { _id: false }, // Prevents Mongoose from creating an additional _id field for subdocuments\n);\n\nexport const relatedPostSchema = new MongooseSchema<SchemaRelatedPostType>(\n {\n postActive: { default: true, required: true, type: Boolean },\n postId: {\n ref: \"Post\",\n required: true,\n type: mongoose.Schema.Types.ObjectId,\n },\n postSlug: { required: true, type: String },\n postType: {\n enum: Object.values(EnumPostType),\n required: true,\n type: String,\n },\n },\n { _id: false }, // Prevents Mongoose from creating an additional _id field for subdocuments\n);\n\nexport const socialShareResourceSchema =\n new MongooseSchema<SocialShareResourceType>(\n {\n qrCode: { required: true, type: ResourceImageTypeSchema },\n socialImage: { required: true, type: ResourceImageTypeSchema },\n },\n { _id: false }, // Prevents Mongoose from creating an additional _id field for subdocuments\n );\n\nexport const baseResourceFields = {\n active: { default: false, required: true, type: Boolean },\n adIds: {\n ref: \"Ad\",\n required: false,\n type: [mongoose.Schema.Types.ObjectId],\n },\n approvedAt: { default: null, required: false, type: Date },\n contactDetails: { required: false, type: ContactDetailsSchema },\n cover: {\n required: true,\n type: ResourceImageTypeSchema,\n },\n deletedAt: { default: null, required: false, type: Date },\n description: { required: true, type: String },\n images: { required: false, type: [ResourceImageTypeSchema] },\n logo: { required: false, type: ResourceImageTypeSchema },\n name: { required: true, type: String },\n owner: {\n required: true,\n type: OwnerTypeSchema,\n },\n posterUsage: { required: false, type: PosterUsageTypeSchema },\n promoCodes: { required: false, type: [String] },\n rating: { required: false, type: Number },\n region: { required: true, type: String },\n relatedPost: { required: false, type: relatedPostSchema },\n reviewCount: { required: false, type: Number },\n sharePublic: { required: false, type: socialShareResourceSchema },\n slug: { required: true, type: String },\n socialMedia: { required: false, type: [SocialMediaTypeSchema] },\n termsAgreement: { required: true, type: termsAgreementSchema },\n};\n","import {\n EnumEventType,\n GoogleAddressComponent,\n GoogleImportedMarket,\n} from \"@timardex/cluemart-shared\";\nimport mongoose from \"mongoose\";\n\nimport {\n dateTimeSchema,\n locationsSchema,\n ResourceImageTypeSchema,\n} from \"./global\";\nimport { searchNamePlugin } from \"./searchNamePlugin\";\n\nexport type SchemaGoogleImportedMarket = Omit<\n GoogleImportedMarket,\n \"eventId\" | \"claimedByUserId\"\n> & {\n eventId?: mongoose.Types.ObjectId;\n claimedByUserId?: mongoose.Types.ObjectId;\n /** Lowercase `name` mirror for prefix type-ahead (see searchNamePlugin). */\n searchName?: string;\n /** Indexed earliest `dateTime` start instant for chronological pagination. */\n earliestStartDate?: Date | null;\n};\n\nconst MongooseSchema = mongoose.Schema;\n\nconst addressComponentSchema = new MongooseSchema<GoogleAddressComponent>(\n {\n longName: { required: false, type: String },\n shortName: { required: false, type: String },\n types: { required: false, type: [String] },\n },\n { _id: false },\n);\n\n/**\n * This is the schema for the GoogleImportedMarket type.\n * It is used to define the structure of the GoogleImportedMarket type in the database.\n * The schema is used by Mongoose to create a model for the GoogleImportedMarket type.\n */\nconst schema = new MongooseSchema<SchemaGoogleImportedMarket>(\n {\n active: { default: false, required: true, type: Boolean },\n address: { required: true, type: String },\n addressComponents: { required: false, type: [addressComponentSchema] },\n approvedAt: { default: null, required: false, type: Date },\n businessStatus: { required: false, type: String },\n claimed: { default: false, required: true, type: Boolean },\n claimedAt: { default: null, required: false, type: Date },\n claimedByUserId: {\n ref: \"User\",\n required: false,\n type: mongoose.Schema.Types.ObjectId,\n },\n cover: {\n required: false,\n type: ResourceImageTypeSchema,\n },\n dateTime: [dateTimeSchema],\n deletedAt: { default: null, required: false, type: Date },\n description: { required: true, type: String },\n earliestStartDate: { default: null, required: false, type: Date },\n eventId: {\n ref: \"Event\",\n required: false,\n type: mongoose.Schema.Types.ObjectId,\n },\n eventType: {\n enum: Object.values(EnumEventType),\n required: true,\n type: String,\n },\n googleMapsUrl: { required: false, type: String },\n googlePlaceId: {\n required: true,\n type: String,\n unique: true, // unique, indexed\n },\n images: { required: false, type: [ResourceImageTypeSchema] }, // array of photo_reference\n importedAt: { default: () => new Date(), required: true, type: Date },\n location: {\n required: true, // optional because lat/lng may expire after 30 days\n type: locationsSchema,\n },\n logo: { required: false, type: ResourceImageTypeSchema },\n name: { required: true, type: String },\n openingHours: { required: false, type: [String] },\n rainOrShine: { required: true, type: Boolean },\n rating: { required: false, type: Number },\n region: { required: false, type: String },\n reviewCount: { required: false, type: Number },\n slug: { required: true, type: String },\n website: { required: false, type: String },\n },\n { timestamps: true },\n);\n\n// Indexes for search, geo, soft-delete, and dateTime status queries.\nschema.index({ \"location.geo\": \"2dsphere\" });\nschema.index({ name: 1 });\nschema.index({ region: 1 });\nschema.index({ deletedAt: 1 });\nschema.index({ \"dateTime.dateStatus\": 1 });\n// eslint-disable-next-line sort-keys\nschema.index({ earliestStartDate: 1, _id: 1 });\nschema.index({ slug: 1 });\n\n// Full-text search across name/description (see eventsSearch google branch).\nschema.index({ description: \"text\", name: \"text\" });\n\nschema.plugin(searchNamePlugin);\n\nexport const GoogleImportedMarketModel =\n (mongoose.models\n .GoogleImportedMarket as mongoose.Model<SchemaGoogleImportedMarket>) ||\n mongoose.model<SchemaGoogleImportedMarket>(\"GoogleImportedMarket\", schema);\n","import mongoose from \"mongoose\";\n\n/**\n * Derives the lowercase prefix mirror used for type-ahead search.\n * `name` is required on every searchable resource, so a missing/blank name\n * yields \"\".\n */\nexport function deriveSearchName(name: unknown): string {\n return typeof name === \"string\" ? name.trim().toLowerCase() : \"\";\n}\n\n/**\n * Returns a copy of a Mongo update with `searchName` synced from `name`, or\n * `null` when the update has no string `name` to derive from. Supports the\n * three update shapes: `$set` operator objects, direct field replacement\n * (`{ name: \"x\" }`), and aggregation-pipeline arrays (`[{ $set: ... }]`).\n */\nfunction syncSearchNameInUpdate(update: unknown): any {\n if (Array.isArray(update)) {\n let changed = false;\n const next = update.map((stage) => {\n if (!stage || typeof stage !== \"object\") {\n return stage;\n }\n const $set = (stage as { $set?: Record<string, unknown> }).$set;\n const name = $set && typeof $set.name === \"string\" ? $set.name : null;\n // In an aggregation pipeline, a string starting with `$` is a field-path\n // expression, not a literal value. The computed name isn't known here, so\n // leave `searchName` alone rather than desynchronizing it from `name`.\n if (!name || name.startsWith(\"$\")) {\n return stage;\n }\n changed = true;\n return {\n ...(stage as Record<string, unknown>),\n $set: { ...$set, searchName: deriveSearchName(name) },\n };\n });\n return changed ? next : null;\n }\n\n if (!update || typeof update !== \"object\") {\n return null;\n }\n\n const obj = update as Record<string, unknown>;\n const $set = obj.$set;\n\n if ($set && typeof $set === \"object\" && !Array.isArray($set)) {\n const setObj = $set as Record<string, unknown>;\n if (typeof setObj.name === \"string\") {\n return {\n ...obj,\n $set: { ...setObj, searchName: deriveSearchName(setObj.name) },\n };\n }\n return null;\n }\n\n // Direct field replacement (no operator prefix): Mongoose casts top-level\n // non-operator keys into `$set`, so mirror `searchName` at the same level.\n if (typeof obj.name === \"string\") {\n return { ...obj, searchName: deriveSearchName(obj.name) };\n }\n\n return null;\n}\n\n/**\n * Mongoose schema plugin that keeps `searchName` (lowercase `name`) in sync\n * with `name` and indexes it for anchored prefix queries.\n *\n * Why: MongoDB `$text` matches whole, stemmed words — partial terms like \"cof\"\n * no longer match \"coffee\". Search resolvers OR an anchored\n * `{ searchName: /^term/ }` clause together with their `$text` clause so\n * type-ahead prefix matching keeps working, backed by the regular\n * `{ searchName: 1 }` index (case-sensitive regex + pre-lowercased field).\n *\n * Coverage: `save`, `insertMany`, `bulkWrite` (insertOne/replaceOne documents\n * and updateOne/updateMany updates in `$set`, direct-field, and pipeline\n * forms), `findOneAndUpdate`, `updateOne`, and `updateMany` are kept in sync.\n */\nexport function searchNamePlugin(schema: mongoose.Schema): void {\n schema.add({ searchName: { default: \"\", required: false, type: String } });\n schema.index({ searchName: 1 });\n\n schema.pre(\"save\", function syncSearchNameOnSave(next) {\n const doc = this as unknown as { name?: string; searchName?: string };\n doc.searchName = deriveSearchName(doc.name);\n next();\n });\n\n schema.pre(\"insertMany\", function syncSearchNameOnInsertMany(next, docs) {\n const list = Array.isArray(docs) ? docs : [docs];\n for (const doc of list as Array<{ name?: string; searchName?: string }>) {\n if (doc && typeof doc.name === \"string\") {\n doc.searchName = deriveSearchName(doc.name);\n }\n }\n next();\n });\n\n schema.pre(\"bulkWrite\", function syncSearchNameOnBulkWrite(next, ops) {\n for (const op of ops as Array<Record<string, any>>) {\n const doc = op.insertOne?.document ?? op.replaceOne?.replacement;\n if (doc && typeof doc.name === \"string\") {\n doc.searchName = deriveSearchName(doc.name);\n }\n\n for (const key of [\"updateOne\", \"updateMany\"] as const) {\n const update = op[key]?.update;\n if (update === undefined) {\n continue;\n }\n const synced = syncSearchNameInUpdate(update);\n if (synced !== null) {\n op[key].update = synced;\n }\n }\n }\n next();\n });\n\n const syncSearchNameOnUpdate = function (\n this: mongoose.Query<unknown, unknown>,\n next: () => void,\n ) {\n const synced = syncSearchNameInUpdate(this.getUpdate());\n if (synced !== null) {\n this.setUpdate(synced);\n }\n next();\n };\n\n schema.pre(\n [\"findOneAndUpdate\", \"updateOne\", \"updateMany\"],\n syncSearchNameOnUpdate,\n );\n}\n","import {\n AiImportedMarket,\n EnumEventType,\n EnumImportedMarketReviewStatus,\n GoogleAddressComponent,\n} from \"@timardex/cluemart-shared\";\nimport mongoose from \"mongoose\";\n\nimport {\n dateTimeSchema,\n locationsSchema,\n ResourceImageTypeSchema,\n} from \"./global\";\nimport { searchNamePlugin } from \"./searchNamePlugin\";\n\nexport type SchemaAiImportedMarket = Omit<\n AiImportedMarket,\n \"eventId\" | \"claimedByUserId\" | \"reviewedByUserId\"\n> & {\n eventId?: mongoose.Types.ObjectId;\n claimedByUserId?: mongoose.Types.ObjectId;\n reviewedByUserId?: mongoose.Types.ObjectId;\n /** Lowercase `name` mirror for prefix type-ahead (see searchNamePlugin). */\n searchName?: string;\n /** Indexed earliest `dateTime` start instant for chronological pagination. */\n earliestStartDate?: Date | null;\n};\n\nconst MongooseSchema = mongoose.Schema;\n\nconst addressComponentSchema = new MongooseSchema<GoogleAddressComponent>(\n {\n longName: { required: false, type: String },\n shortName: { required: false, type: String },\n types: { required: false, type: [String] },\n },\n { _id: false },\n);\n\n/**\n * Schema for AI-imported markets (scraped from admin-defined websites via the\n * DeepSeek API). Mirrors GoogleImportedMarket so approved markets can ride the\n * same combined read paths, but adds review/provenance fields and uses\n * `sourceKey` as the unique dedupe key instead of `googlePlaceId`.\n */\nconst schema = new MongooseSchema<SchemaAiImportedMarket>(\n {\n active: { default: false, required: true, type: Boolean },\n address: { required: true, type: String },\n addressComponents: { required: false, type: [addressComponentSchema] },\n approvedAt: { default: null, required: false, type: Date },\n claimed: { default: false, required: true, type: Boolean },\n claimedAt: { default: null, required: false, type: Date },\n claimedByUserId: {\n ref: \"User\",\n required: false,\n type: mongoose.Schema.Types.ObjectId,\n },\n cover: {\n required: false,\n type: ResourceImageTypeSchema,\n },\n dateTime: [dateTimeSchema],\n deletedAt: { default: null, required: false, type: Date },\n description: { required: true, type: String },\n earliestStartDate: { default: null, required: false, type: Date },\n eventId: {\n ref: \"Event\",\n required: false,\n type: mongoose.Schema.Types.ObjectId,\n },\n eventType: {\n enum: Object.values(EnumEventType),\n required: true,\n type: String,\n },\n images: { required: false, type: [ResourceImageTypeSchema] },\n location: {\n required: true,\n type: locationsSchema,\n },\n logo: { required: false, type: ResourceImageTypeSchema },\n name: { required: true, type: String },\n openingHours: { required: false, type: [String] },\n rainOrShine: { required: true, type: Boolean },\n rating: { required: false, type: Number },\n region: { required: false, type: String },\n rejectReason: { required: false, type: String },\n reviewCount: { required: false, type: Number },\n reviewedAt: { default: null, required: false, type: Date },\n reviewedByUserId: {\n ref: \"User\",\n required: false,\n type: mongoose.Schema.Types.ObjectId,\n },\n reviewStatus: {\n default: EnumImportedMarketReviewStatus.PENDING,\n enum: Object.values(EnumImportedMarketReviewStatus),\n required: true,\n type: String,\n },\n scrapedAt: { default: () => new Date(), required: true, type: Date },\n slug: { required: true, type: String },\n sourceKey: {\n required: true,\n type: String,\n unique: true, // unique, indexed\n },\n sourceName: { required: true, type: String },\n sourceUrl: { required: true, type: String },\n website: { required: false, type: String },\n },\n { timestamps: true },\n);\n\n// Indexes for search, geo, soft-delete, review, and dateTime status queries.\nschema.index({ \"location.geo\": \"2dsphere\" });\nschema.index({ name: 1 });\nschema.index({ region: 1 });\nschema.index({ deletedAt: 1 });\nschema.index({ \"dateTime.dateStatus\": 1 });\n// eslint-disable-next-line sort-keys\nschema.index({ earliestStartDate: 1, _id: 1 });\nschema.index({ slug: 1 });\nschema.index({ reviewStatus: 1 });\n\n// Full-text search across name/description (see eventsSearch ai branch).\nschema.index({ description: \"text\", name: \"text\" });\n\nschema.plugin(searchNamePlugin);\n\nexport const AiImportedMarketModel =\n (mongoose.models\n .AiImportedMarket as mongoose.Model<SchemaAiImportedMarket>) ||\n mongoose.model<SchemaAiImportedMarket>(\"AiImportedMarket\", schema);\n","import { ScrapeSite } from \"@timardex/cluemart-shared\";\nimport mongoose from \"mongoose\";\n\nexport const SCRAPE_SITES_CONFIG_KEY = \"scrapeSites\";\n\nconst MongooseSchema = mongoose.Schema;\n\ntype SchemaScrapeSiteItem = Omit<ScrapeSite, \"_id\" | \"createdAt\" | \"updatedAt\">;\n\ntype SchemaScrapeSiteConfig = {\n key: string;\n sites: Array<SchemaScrapeSiteItem & { _id: mongoose.Types.ObjectId }>;\n};\n\nconst scrapeSiteItemSchema = new MongooseSchema<SchemaScrapeSiteItem>(\n {\n enabled: { default: true, required: true, type: Boolean },\n lastError: { required: false, type: String },\n lastScrapedAt: { required: false, type: Date },\n lastScrapeStatus: { required: false, type: String },\n name: { required: true, type: String },\n regionHint: { required: false, type: String },\n url: { required: true, type: String },\n },\n { timestamps: true },\n);\n\n/**\n * Single-document store for the admin-managed AI scrape-site list. Keeping the\n * whole list in one document makes replacement a single atomic `$set` (the\n * local MongoDB deployment is standalone, so multi-document transactions are\n * not available).\n */\nconst configSchema = new MongooseSchema(\n {\n key: { required: true, type: String, unique: true },\n sites: {\n default: [],\n required: true,\n type: [scrapeSiteItemSchema],\n },\n },\n { timestamps: true },\n);\n\nexport const ScrapeSiteConfigModel =\n (mongoose.models\n .ScrapeSiteConfig as mongoose.Model<SchemaScrapeSiteConfig>) ||\n mongoose.model<SchemaScrapeSiteConfig>(\"ScrapeSiteConfig\", configSchema);\n","import {\n CreateBulkNotificationInput,\n NotificationType,\n EnumNotificationResourceType,\n EnumNotificationType,\n} from \"@timardex/cluemart-shared\";\nimport mongoose from \"mongoose\";\n\nimport { ObjectId } from \"src/types\";\n\nconst MongooseSchema = mongoose.Schema;\n\nconst notificationDataSchema = new MongooseSchema(\n {\n resourceId: { required: true, type: String },\n resourceName: { required: true, type: String },\n resourceType: {\n enum: Object.values(EnumNotificationResourceType),\n required: true,\n type: String,\n },\n },\n { _id: false },\n);\n\nexport type SchemaCreateBulkNotificationInput = Omit<\n CreateBulkNotificationInput,\n \"userIds\"\n> & {\n userIds: ObjectId[];\n};\n\nexport type SchemaNotificationType = Omit<NotificationType, \"userId\"> & {\n userId: ObjectId;\n};\n/**\n * Schema for storing in-app notifications\n * Each notification is tied to a specific user and can be marked as read/unread\n */\nconst schema = new MongooseSchema<SchemaNotificationType>(\n {\n data: {\n default: null,\n required: false,\n type: notificationDataSchema,\n },\n isRead: { default: false, index: true, required: true, type: Boolean },\n message: { required: true, type: String },\n title: { required: true, type: String },\n type: {\n default: EnumNotificationType.SYSTEM,\n enum: Object.values(EnumNotificationType),\n required: true,\n type: String,\n },\n userId: {\n ref: \"User\",\n required: true,\n type: mongoose.Schema.Types.ObjectId,\n },\n },\n { timestamps: true },\n);\n\n// Compound index for efficient queries\nschema.index({ isRead: 1, userId: 1 });\nschema.index({ createdAt: -1, userId: 1 });\n\nexport const NotificationModel =\n (mongoose.models.Notification as mongoose.Model<SchemaNotificationType>) ||\n mongoose.model<SchemaNotificationType>(\"Notification\", schema);\n","import { PushTokenType } from \"@timardex/cluemart-shared\";\nimport { EnumOSPlatform } from \"@timardex/cluemart-shared/enums\";\nimport mongoose from \"mongoose\";\n\nimport { ObjectId } from \"src/types\";\n\nconst MongooseSchema = mongoose.Schema;\n\nexport type SchemaPushTokenType = Omit<PushTokenType, \"userId\"> & {\n userId: ObjectId;\n};\n\n/**\n * This is the schema for the push token type.\n * It is used to define the structure of the push token type in the database.\n * The schema is used by Mongoose to create a model for the push token type.\n */\nconst schema = new MongooseSchema<SchemaPushTokenType>(\n {\n platform: {\n enum: Object.values(EnumOSPlatform),\n required: true,\n type: String,\n },\n token: { required: true, type: String },\n userId: {\n ref: \"User\",\n required: true,\n type: mongoose.Schema.Types.ObjectId,\n },\n },\n { timestamps: true },\n);\n\nexport const PushTokenModel =\n (mongoose.models.PushToken as mongoose.Model<SchemaPushTokenType>) ||\n mongoose.model<SchemaPushTokenType>(\"PushToken\", schema);\n","import {\n EnumEventDateStatus,\n EnumInviteStatus,\n EnumRelationResource,\n EnumResourceType,\n RelationDate,\n RelationType,\n} from \"@timardex/cluemart-shared\";\nimport mongoose from \"mongoose\";\n\nimport { ObjectId } from \"src/types\";\n\nimport { StallTypeSchema } from \"./event/EventInfo\";\n\nconst MongooseSchema = mongoose.Schema;\n\nconst relationDateTimeSchema = new MongooseSchema<RelationDate[\"dateTime\"]>(\n {\n dateStatus: {\n enum: Object.values(EnumEventDateStatus),\n required: true,\n type: String,\n },\n endDate: { required: true, type: String },\n endTime: { required: true, type: String },\n stallType: StallTypeSchema,\n startDate: { required: true, type: String },\n startTime: { required: true, type: String },\n },\n { _id: false },\n);\n\nexport const relationDatesSchema = new MongooseSchema<RelationDate>(\n {\n dateTime: {\n required: true,\n type: relationDateTimeSchema,\n },\n lastUpdateBy: {\n resourceId: { required: false, type: String },\n userEmail: { required: false, type: String },\n },\n paymentReference: { required: false, type: String },\n status: {\n enum: Object.values(EnumInviteStatus),\n required: false,\n type: String,\n },\n },\n { _id: false },\n);\n\nexport type SchemaRelationType = Omit<\n RelationType,\n \"eventId\" | \"vendorId\" | \"chatId\"\n> & {\n eventId: ObjectId;\n vendorId: ObjectId;\n chatId: ObjectId;\n};\n/**\n * This is the schema for the relation type.\n * It is used to define the structure of the relation type in the database.\n * The schema is used by Mongoose to create a model for the relation type.\n */\nexport const RelationTypeSchema = new MongooseSchema<SchemaRelationType>(\n {\n active: { default: true, required: true, type: Boolean },\n chatId: {\n ref: \"Chat\",\n required: true,\n type: mongoose.Schema.Types.ObjectId,\n },\n deletedAt: { default: null, required: false, type: Date },\n eventId: {\n ref: \"Event\",\n required: true,\n type: mongoose.Schema.Types.ObjectId,\n },\n lastUpdateBy: {\n enum: Object.values(EnumResourceType),\n required: true,\n type: String,\n },\n relationDates: [relationDatesSchema],\n relationType: {\n enum: Object.values(EnumRelationResource),\n required: true,\n type: String,\n },\n vendorId: {\n ref: \"Vendor\",\n required: true,\n type: mongoose.Schema.Types.ObjectId,\n },\n },\n { timestamps: true },\n);\n\nRelationTypeSchema.index({\n eventId: 1,\n \"relationDates.startDate\": 1,\n \"relationDates.startTime\": 1,\n \"relationDates.status\": 1,\n vendorId: 1,\n});\n\n// --- IMPORTANT: bind custom model type ---\nexport const RelationModel =\n (mongoose.models.Relation as mongoose.Model<SchemaRelationType>) ||\n mongoose.model<SchemaRelationType>(\"Relation\", RelationTypeSchema);\n","import {\n DateTimeWithPriceType,\n EnumEventDateStatus,\n EnumPaymentMethod,\n EventInfoType,\n PaymentInfoType,\n RefundPolicy,\n Requirement,\n StallType,\n} from \"@timardex/cluemart-shared\";\nimport mongoose from \"mongoose\";\n\nimport { ObjectId } from \"src/types\";\n\nconst MongooseSchema = mongoose.Schema;\n\nexport const StallTypeSchema = new MongooseSchema<StallType>(\n {\n label: { required: false, type: String },\n price: { required: false, type: Number },\n stallCapacity: { required: false, type: Number },\n },\n {\n _id: false, // Prevents Mongoose from creating an additional _id field for subdocuments\n },\n);\n\nconst dateTimeSchema = new MongooseSchema<DateTimeWithPriceType>(\n {\n dateStatus: {\n enum: Object.values(EnumEventDateStatus),\n required: false,\n type: String,\n },\n endDate: { required: true, type: String },\n endTime: { required: true, type: String },\n stallTypes: [StallTypeSchema],\n startDate: { required: true, type: String },\n startTime: { required: true, type: String },\n },\n { _id: false }, // Prevents Mongoose from creating an additional _id field for subdocuments\n);\n\nconst paymentInfoSchema = new MongooseSchema<PaymentInfoType>(\n {\n accountHolderName: { required: false, type: String },\n accountNumber: { required: false, type: String },\n link: { required: false, type: String },\n paymentMethod: {\n enum: Object.values(EnumPaymentMethod),\n required: true,\n type: String,\n },\n },\n { _id: false }, // Prevents Mongoose from creating an additional _id field\n);\n\nconst requirementsSchema = new MongooseSchema<Requirement>(\n {\n category: { required: true, type: String },\n label: { required: true, type: String },\n value: { required: true, type: Boolean },\n },\n {\n _id: false, // Prevents Mongoose from creating an additional _id field for\n },\n);\n\nexport const refundPolicySchema = new MongooseSchema<RefundPolicy>(\n {\n category: { required: true, type: String },\n label: { required: true, type: String },\n value: { required: true, type: Boolean },\n },\n { _id: false },\n);\n\nexport type SchemaEventInfoType = Omit<EventInfoType, \"eventId\"> & {\n eventId: ObjectId;\n};\n\n/**\n * This is the schema for the event info type.\n * It is used to define the structure of the event info type in the database.\n * The schema is used by Mongoose to create a model for the event info type.\n */\nconst schema = new MongooseSchema<SchemaEventInfoType>(\n {\n active: { default: true, type: Boolean },\n applicationDeadlineHours: { required: true, type: Number },\n dateTime: { required: true, type: [dateTimeSchema] },\n eventId: {\n ref: \"Event\",\n required: true,\n type: mongoose.Schema.Types.ObjectId,\n },\n packInTime: { required: true, type: Number },\n paymentDueHours: { required: true, type: Number },\n paymentInfo: { required: true, type: [paymentInfoSchema] },\n refundPolicy: { required: true, type: [refundPolicySchema] },\n requirements: { required: false, type: [requirementsSchema] },\n },\n { timestamps: true },\n);\n\n// Serves `getEventInfo` / `createRelation` / relation resolvers / user deletion:\n// every read/write is `findOne({ eventId })` equality.\nschema.index({ eventId: 1 });\n\nexport const EventInfoModel =\n (mongoose.models.EventInfo as mongoose.Model<SchemaEventInfoType>) ||\n mongoose.model<SchemaEventInfoType>(\"EventInfo\", schema);\n","import {\n EnumActivity,\n EnumEventDateStatus,\n EnumOSPlatform,\n EnumResourceType,\n ResourceActivityEntry,\n ResourceActivityType,\n} from \"@timardex/cluemart-shared\";\nimport mongoose from \"mongoose\";\n\nimport { locationGeoSchema } from \"./global\";\n\nconst MongooseSchema = mongoose.Schema;\n\nconst ActivitySchema = new MongooseSchema<ResourceActivityEntry>(\n {\n activityType: {\n enum: Object.values(EnumActivity),\n required: true,\n type: String,\n },\n dateStatus: {\n enum: Object.values(EnumEventDateStatus),\n required: false,\n type: String,\n },\n location: {\n required: false,\n type: locationGeoSchema,\n },\n startDate: { required: false, type: String },\n startTime: { required: false, type: String },\n timestamp: { default: Date.now, type: Date },\n userAgent: {\n enum: Object.values(EnumOSPlatform),\n required: true,\n type: String,\n },\n userId: { required: false, type: String },\n },\n { _id: false },\n);\n\nconst schema = new MongooseSchema<ResourceActivityType>(\n {\n activity: { default: [], type: [ActivitySchema] },\n resourceId: { required: true, type: String },\n resourceType: {\n enum: Object.values(EnumResourceType),\n required: true,\n type: String,\n },\n },\n { timestamps: true },\n);\n\nschema.index({ resourceId: 1, resourceType: 1 }, { unique: true }); // one per entity\nschema.index({ \"views.location\": \"2dsphere\" });\n\nexport const ResourceActivityModel =\n (mongoose.models.ResourceActivity as mongoose.Model<ResourceActivityType>) ||\n mongoose.model<ResourceActivityType>(\"ResourceActivity\", schema);\n","import {\n EnumBillingPeriod,\n EnumNotificationResourceType,\n EnumOSPlatform,\n EnumPointType,\n EnumResourceType,\n EnumReward,\n EnumSubscriptionStatus,\n EnumUserLicence,\n EnumUserRole,\n RedeemedReward,\n StripeSubscription,\n UserActivityEvent,\n UserOverallPointsEntry,\n UserType,\n} from \"@timardex/cluemart-shared\";\nimport mongoose from \"mongoose\";\n\nimport { ObjectId } from \"src/types\";\n\nimport {\n dateTimeSchema,\n locationsSchema,\n ResourceImageTypeSchema,\n termsAgreementSchema,\n userLicenseSchema,\n} from \"./global\";\n\nconst MongooseSchema = mongoose.Schema;\n\nexport type SchemaUserActivityEvent = Omit<UserActivityEvent, \"resourceId\"> & {\n resourceId: ObjectId;\n};\n\nexport type SchemaUserType = Omit<\n UserType,\n | \"vendor\"\n | \"coupon\"\n | \"events\"\n | \"partner\"\n | \"userActivity\"\n | \"_id\"\n | \"game\"\n | \"school\"\n | \"affiliate\"\n | \"permissions\"\n | \"stripe\"\n | \"totalOverallPoints\"\n> & {\n _id: ObjectId;\n affiliate: ObjectId;\n coupon: ObjectId;\n events: ObjectId[];\n game: ObjectId;\n partner: ObjectId;\n /** Server-only hashed refresh tokens; never exposed to clients. */\n refreshTokenAdmin?: string | null;\n refreshTokenMobile?: string | null;\n school: ObjectId;\n stripe?: SchemaStripeSubscription;\n vendor: ObjectId;\n userActivity: {\n favourites: {\n events: ObjectId[];\n vendors: ObjectId[];\n partners: ObjectId[];\n };\n interested: {\n events: SchemaUserActivityEvent[];\n };\n going: {\n events: SchemaUserActivityEvent[];\n };\n present: {\n events: SchemaUserActivityEvent[];\n };\n };\n};\n\nexport type SchemaStripeSubscription = StripeSubscription & {\n billingPeriod?: EnumBillingPeriod;\n cancelAtPeriodEnd?: boolean;\n paymentFailedAt?: Date;\n paymentGracePeriodEndsAt?: Date;\n paymentGraceSubscriptionId?: string;\n pendingBillingPeriod?: EnumBillingPeriod;\n pendingChangeEffectiveAt?: Date;\n pendingPlan?: EnumUserLicence;\n priceId?: string;\n scheduleId?: string;\n subscriptionMutationLockExpiresAt?: Date;\n subscriptionMutationLockId?: string;\n};\n\nconst userActivityEventSchema = new MongooseSchema<SchemaUserActivityEvent>(\n {\n dateTime: dateTimeSchema,\n resourceId: {\n ref: \"Event\",\n required: false,\n type: mongoose.Schema.Types.ObjectId,\n },\n },\n { _id: false },\n);\n\nconst userActivityFavouritesSchema = new MongooseSchema(\n {\n events: {\n ref: \"Event\",\n required: false,\n type: [mongoose.Schema.Types.ObjectId],\n },\n partners: {\n ref: \"Partner\",\n required: false,\n type: [mongoose.Schema.Types.ObjectId],\n },\n vendors: {\n ref: \"Vendor\",\n required: false,\n type: [mongoose.Schema.Types.ObjectId],\n },\n },\n { _id: false },\n);\n\nconst stripeSchema = new MongooseSchema<SchemaStripeSubscription>(\n {\n billingPeriod: {\n enum: Object.values(EnumBillingPeriod),\n required: false,\n type: String,\n },\n cancelAtPeriodEnd: {\n required: false,\n type: Boolean,\n },\n currentPlan: {\n enum: Object.values(EnumUserLicence),\n required: false,\n type: String,\n },\n customerId: {\n required: false,\n type: String,\n },\n endDate: {\n required: false,\n type: Date,\n },\n paymentFailedAt: {\n required: false,\n type: Date,\n },\n paymentGracePeriodEndsAt: {\n required: false,\n type: Date,\n },\n paymentGraceSubscriptionId: {\n required: false,\n type: String,\n },\n pendingBillingPeriod: {\n enum: Object.values(EnumBillingPeriod),\n required: false,\n type: String,\n },\n pendingChangeEffectiveAt: {\n required: false,\n type: Date,\n },\n pendingPlan: {\n enum: Object.values(EnumUserLicence),\n required: false,\n type: String,\n },\n priceId: {\n required: false,\n type: String,\n },\n scheduleId: {\n required: false,\n type: String,\n },\n startDate: {\n required: false,\n type: Date,\n },\n status: {\n enum: Object.values(EnumSubscriptionStatus),\n required: false,\n type: String,\n },\n subscriptionId: {\n required: false,\n type: String,\n },\n subscriptionMutationLockExpiresAt: {\n required: false,\n type: Date,\n },\n subscriptionMutationLockId: {\n required: false,\n type: String,\n },\n },\n { _id: false },\n);\n\nconst redeemedRewardSchema = new MongooseSchema<RedeemedReward>(\n {\n name: {\n enum: Object.values(EnumReward),\n required: true,\n type: String,\n },\n pointsUsed: { required: true, type: Number },\n redeemedAt: { required: true, type: Date },\n },\n { _id: false },\n);\n\nconst userOverallPointsSchema = new MongooseSchema<UserOverallPointsEntry>(\n {\n createdAt: { required: true, type: Date },\n points: { default: 0, required: true, type: Number },\n pointType: {\n enum: Object.values(EnumPointType),\n required: true,\n type: String,\n },\n sourceId: { required: false, type: String },\n },\n { _id: false },\n);\n\n/**\n * This is the schema for the user type.\n * It is used to define the structure of the user type in the database.\n * The schema is used by Mongoose to create a model for the user type.\n */\nconst schema = new MongooseSchema<SchemaUserType>(\n {\n active: { default: false, required: true, type: Boolean },\n affiliate: {\n ref: \"Affiliate\",\n required: false,\n type: mongoose.Schema.Types.ObjectId,\n },\n avatar: {\n required: false,\n type: ResourceImageTypeSchema,\n },\n coupon: {\n ref: \"Coupon\",\n required: false,\n type: mongoose.Schema.Types.ObjectId,\n },\n deletedAt: { default: null, required: false, type: Date },\n email: { required: true, type: String },\n emailSentFor: {\n enum: Object.values(EnumNotificationResourceType),\n required: false,\n type: [String],\n },\n events: {\n ref: \"Event\",\n required: false,\n type: [mongoose.Schema.Types.ObjectId],\n },\n firstName: { required: true, type: String },\n game: {\n ref: \"Game\",\n required: false,\n type: mongoose.Schema.Types.ObjectId,\n },\n interests: {\n enum: Object.values(EnumResourceType),\n required: false,\n type: [String],\n },\n isTester: { default: false, required: true, type: Boolean },\n lastName: { required: true, type: String },\n licences: {\n required: false,\n type: [userLicenseSchema],\n },\n location: {\n required: false,\n type: locationsSchema,\n },\n nickName: { required: false, type: String },\n overallPoints: {\n default: [],\n required: false,\n type: [userOverallPointsSchema],\n },\n partner: {\n ref: \"Partner\",\n required: false,\n type: mongoose.Schema.Types.ObjectId,\n },\n password: { required: true, type: String },\n platform: {\n enum: Object.values(EnumOSPlatform),\n required: false,\n type: String,\n },\n preferredRegion: {\n required: true,\n type: String,\n },\n promoCodes: {\n required: false,\n type: [String],\n },\n redeemedRewards: {\n required: false,\n type: [redeemedRewardSchema],\n },\n // Per-client slots: a mobile session and an in-app WebView admin session\n // coexist without rotating each other out.\n refreshTokenAdmin: {\n default: null,\n required: false,\n type: String,\n },\n refreshTokenMobile: {\n default: null,\n required: false,\n type: String,\n },\n roles: {\n default: [EnumUserRole.CUSTOMER],\n enum: Object.values(EnumUserRole),\n required: true,\n type: [String],\n },\n school: {\n ref: \"School\",\n required: false,\n type: mongoose.Schema.Types.ObjectId,\n },\n stripe: {\n required: false,\n type: stripeSchema,\n },\n termsAgreement: termsAgreementSchema,\n userActivity: {\n favourites: {\n default: () => ({ events: [], vendors: [] }),\n type: userActivityFavouritesSchema,\n },\n going: {\n events: [userActivityEventSchema],\n },\n interested: {\n events: [userActivityEventSchema],\n },\n present: {\n events: [userActivityEventSchema],\n },\n },\n vendor: {\n ref: \"Vendor\",\n required: false,\n type: mongoose.Schema.Types.ObjectId,\n },\n },\n { strict: false, timestamps: true },\n);\n\nschema.index({ \"licences.expiryDate\": 1 });\nschema.index({ \"licences.licenceType\": 1 });\n// Serves `usersByPromoCode` (`{ promoCodes: code }` — promoCodes is the only\n// predicate, so it must lead the index) and the school member list\n// (`{ active: true, deletedAt: null, promoCodes: { $in: [code] } }`, where all\n// three are equality/`$in` predicates and any field order is usable).\n/* eslint-disable-next-line sort-keys -- Compound-index field order controls promo-code lookups. */\nschema.index({ promoCodes: 1, active: 1, deletedAt: 1 });\n// Backs the super-admin `getUsers` search (`{ $text: { $search } }`) so the\n// search clause is served by an index instead of a collection scan. `$text`\n// matches whole, stemmed words — partial type-ahead would need a lowercase\n// mirror field, so keep this in mind before tightening search semantics.\nschema.index({ email: \"text\", firstName: \"text\", lastName: \"text\" });\n\nexport const UserModel =\n (mongoose.models.User as mongoose.Model<SchemaUserType>) ||\n mongoose.model<SchemaUserType>(\"User\", schema);\n","import mongoose from \"mongoose\";\n\nconst MongooseSchema = mongoose.Schema;\n\nexport interface VerificationTokenType {\n email: string;\n verificationToken: string;\n createdAt: Date;\n}\n\nconst schema = new MongooseSchema<VerificationTokenType>(\n {\n createdAt: {\n default: Date.now,\n expires: 24 * 60 * 60, // 24 hours in seconds (MongoDB TTL expects seconds)\n required: true,\n type: Date,\n }, // Token expires after 1 day\n email: { required: true, type: String },\n verificationToken: { required: true, type: String },\n },\n { timestamps: true },\n);\n\nexport const VerificationTokenModel =\n (mongoose.models\n .VerificationToken as mongoose.Model<VerificationTokenType>) ||\n mongoose.model<VerificationTokenType>(\"VerificationToken\", schema);\n","import {\n EnumEventDateStatus,\n EnumVendorType,\n VendorCalendarData,\n VendorProductList,\n VendorType,\n VendorDowngradeSnapshot,\n VendorAvailability,\n} from \"@timardex/cluemart-shared\";\nimport mongoose from \"mongoose\";\n\nimport { ObjectId } from \"src/types\";\n\nimport {\n baseResourceFields,\n CategorySchema,\n locationsSchema,\n SchemaOwnerType,\n socialShareResourceSchema,\n} from \"../global\";\nimport { searchNamePlugin } from \"../searchNamePlugin\";\n\nconst MongooseSchema = mongoose.Schema;\n\nexport const vendorProductTypeSchema = new MongooseSchema<VendorProductList>(\n {\n description: { required: false, type: String },\n name: { required: true, type: String },\n price: { required: true, type: Number },\n priceMax: { required: false, type: Number },\n priceUnit: { required: true, type: String },\n productGroups: { required: false, type: [String] },\n },\n { timestamps: true },\n);\n\nconst productWrapperSchema = new MongooseSchema<VendorType[\"products\"]>(\n {\n active: { default: false, required: false, type: Boolean },\n productsList: { required: false, type: [vendorProductTypeSchema] },\n },\n { _id: false },\n);\n\nconst calendarSchema = new MongooseSchema<VendorCalendarData>(\n {\n dateTime: {\n dateStatus: {\n enum: Object.values(EnumEventDateStatus),\n required: false,\n type: String,\n },\n endDate: { required: false, type: String },\n endTime: { required: false, type: String },\n startDate: { required: false, type: String },\n startTime: { required: false, type: String },\n },\n description: { required: false, type: String },\n location: {\n required: false,\n type: locationsSchema,\n },\n },\n { _id: false },\n);\n\nconst calendarWrapperSchema = new MongooseSchema<VendorType[\"calendar\"]>(\n {\n active: { default: false, required: true, type: Boolean },\n calendarData: { required: false, type: [calendarSchema] },\n },\n { _id: false },\n);\n\nconst vendorAvailabilitySchema = new MongooseSchema<VendorAvailability>(\n {\n corporate: { default: false, required: false, type: Boolean },\n private: { default: false, required: false, type: Boolean },\n school: { default: false, required: false, type: Boolean },\n },\n { _id: false },\n);\n\n/**\n * Snapshot of licence-gated fields captured when a vendor is downgraded to\n * STANDARD_VENDOR, used to restore the vendor's own configuration on a later\n * PRO upgrade (see downgradeVendorProFeatures / restoreVendorProFeatures).\n */\nconst downgradeSnapshotSchema = new MongooseSchema<VendorDowngradeSnapshot>(\n {\n availability: { required: false, type: vendorAvailabilitySchema },\n calendarActive: { required: false, type: Boolean },\n productsActive: { required: false, type: Boolean },\n },\n { _id: false },\n);\n\nexport type SchemaVendorType = Omit<\n VendorType,\n \"vendorInfoId\" | \"owner\" | \"adIds\" | \"unregisteredVendorId\"\n> & {\n adIds?: ObjectId[];\n /** Mirror of `categories[].name` for $text search (see vendorSearch). */\n categoriesNames?: string[];\n owner: SchemaOwnerType;\n /** Lowercase `name` mirror for prefix type-ahead (see searchNamePlugin). */\n searchName?: string;\n vendorInfoId: ObjectId;\n unregisteredVendorId?: ObjectId | null;\n};\n\nconst schema = new MongooseSchema<SchemaVendorType>(\n {\n ...baseResourceFields, // Importing base resource fields from global.ts\n availability: { required: false, type: vendorAvailabilitySchema },\n calendar: {\n required: false,\n type: calendarWrapperSchema,\n },\n categories: { required: true, type: [CategorySchema] },\n categoriesNames: { default: [], required: false, type: [String] },\n claimed: { default: true, required: false, type: Boolean },\n downgradeSnapshot: { required: false, type: downgradeSnapshotSchema },\n foodTruck: { required: true, type: Boolean },\n products: { required: false, type: productWrapperSchema },\n shareRelation: { required: false, type: socialShareResourceSchema },\n unregisteredVendorId: {\n ref: \"UnregisteredVendor\",\n required: false,\n type: mongoose.Schema.Types.ObjectId,\n },\n vendorInfoId: {\n ref: \"VendorInfo\",\n required: false,\n type: mongoose.Schema.Types.ObjectId,\n },\n vendorType: {\n enum: Object.values(EnumVendorType),\n required: true,\n type: String,\n },\n },\n { timestamps: true },\n);\n\n// 🔹 Add indexes to speed up regex-based searches\nschema.index({ name: 1 });\nschema.index({ description: 1 });\nschema.index({ region: 1 });\nschema.index({ \"categories.name\": 1 });\nschema.index({ slug: 1 });\n\n// Full-text search across name/description/categoriesNames (see vendorSearch).\nschema.index({\n categoriesNames: \"text\",\n description: \"text\",\n name: \"text\",\n});\n\n// Serves getUserVendors / ownedCoupons' Vendor lookups:\n// `{ deletedAt: null, \"owner.userId\": <id> }` (and ownedCoupons' additional\n// `active: true` is a residual filter).\nschema.index({ deletedAt: 1, \"owner.userId\": 1 });\n\nschema.plugin(searchNamePlugin);\n\nexport const VendorModel =\n (mongoose.models.Vendor as mongoose.Model<SchemaVendorType>) ||\n mongoose.model<SchemaVendorType>(\"Vendor\", schema);\n","import {\n EnumFoodFlavor,\n VendorAttributes,\n VendorInfoType,\n} from \"@timardex/cluemart-shared\";\nimport mongoose from \"mongoose\";\n\nimport { ObjectId } from \"src/types\";\n\nimport { ResourceImageTypeSchema } from \"../global\";\n\nconst MongooseSchema = mongoose.Schema;\n\nexport type SchemaVendorInfoType = Omit<VendorInfoType, \"vendorId\"> & {\n vendorId: ObjectId;\n};\n\nconst AttributesSchema = new MongooseSchema<VendorAttributes>(\n {\n details: { required: false, type: String },\n isRequired: { default: false, required: true, type: Boolean },\n },\n { _id: false },\n);\n\nconst schema = new MongooseSchema<SchemaVendorInfoType>(\n {\n active: { default: true, type: Boolean },\n compliance: {\n foodBeverageLicense: { default: false, required: false, type: Boolean },\n liabilityInsurance: { default: false, required: false, type: Boolean },\n },\n documents: [ResourceImageTypeSchema],\n product: {\n foodFlavors: {\n enum: Object.values(EnumFoodFlavor),\n required: true,\n type: [String],\n },\n packaging: { required: true, type: [String] },\n priceRange: {\n max: { required: true, type: String },\n min: { required: true, type: String },\n },\n producedIn: { required: true, type: [String] },\n },\n requirements: {\n electricity: AttributesSchema,\n gazebo: AttributesSchema,\n table: AttributesSchema,\n },\n stallInfo: {\n size: {\n depth: { required: true, type: String },\n width: { required: true, type: String },\n },\n },\n vendorId: {\n ref: \"Vendor\",\n required: true,\n type: mongoose.Schema.Types.ObjectId,\n },\n },\n { timestamps: true },\n);\n\n// Serves `getVendorInfo` / user deletion: `findOne({ vendorId })` equality.\nschema.index({ vendorId: 1 });\n\nexport const VendorInfoModel =\n (mongoose.models.VendorInfo as mongoose.Model<SchemaVendorInfoType>) ||\n mongoose.model<SchemaVendorInfoType>(\"VendorInfo\", schema);\n","import {\n UnregisteredVendorInvitationType,\n UnregisteredVendorType,\n} from \"@timardex/cluemart-shared\";\nimport mongoose from \"mongoose\";\n\nimport { ObjectId } from \"src/types\";\n\nimport { dateTimeSchema } from \"../global\";\n\nconst MongooseSchema = mongoose.Schema;\n\nexport type SchemaUnregisteredVendorInvitationType = Omit<\n UnregisteredVendorInvitationType,\n \"inviterId\"\n> & {\n inviterId: ObjectId;\n};\n\nexport type SchemaUnregisteredVendorType = Omit<\n UnregisteredVendorType,\n \"invitations\" | \"claimedByUserId\"\n> & {\n claimInitiatedAt?: Date | null;\n claimToken?: string | null;\n claimTokenExpiresAt?: Date | null;\n claimedByUserId?: mongoose.Types.ObjectId;\n invitations: SchemaUnregisteredVendorInvitationType[];\n};\n\nconst invitationSchema =\n new MongooseSchema<SchemaUnregisteredVendorInvitationType>(\n {\n dateTime: { required: true, type: [dateTimeSchema] },\n inviterId: {\n ref: \"Event\",\n required: true,\n type: mongoose.Schema.Types.ObjectId,\n },\n },\n { _id: false },\n );\n\nconst schema = new MongooseSchema<SchemaUnregisteredVendorType>(\n {\n active: { default: true, required: true, type: Boolean },\n categoryIds: { required: true, type: [String] },\n claimed: { default: false, required: true, type: Boolean },\n claimedAt: { default: null, required: false, type: Date },\n claimedByUserId: {\n ref: \"User\",\n required: false,\n type: mongoose.Schema.Types.ObjectId,\n },\n claimInitiatedAt: { default: null, required: false, type: Date },\n claimToken: { default: null, required: false, type: String },\n claimTokenExpiresAt: { default: null, required: false, type: Date },\n deletedAt: { default: null, required: false, type: Date },\n email: { required: true, type: String },\n invitations: { required: true, type: [invitationSchema] },\n name: { required: true, type: String },\n region: { required: true, type: String },\n },\n { timestamps: true },\n);\n\nschema.index({ name: 1 });\nschema.index({ email: 1 });\n\nexport const UnregisteredVendorModel =\n (mongoose.models\n .UnregisteredVendor as mongoose.Model<SchemaUnregisteredVendorType>) ||\n mongoose.model<SchemaUnregisteredVendorType>(\"UnregisteredVendor\", schema);\n","import { EnumEventType, EventType } from \"@timardex/cluemart-shared\";\nimport mongoose from \"mongoose\";\n\nimport { ObjectId } from \"src/types\";\n\nimport {\n baseResourceFields,\n dateTimeSchema,\n locationsSchema,\n SchemaOwnerType,\n socialShareResourceSchema,\n} from \"../global\";\nimport { searchNamePlugin } from \"../searchNamePlugin\";\n\nconst MongooseSchema = mongoose.Schema;\n\nexport type SchemaEventType = Omit<\n EventType,\n \"eventInfoId\" | \"owner\" | \"adIds\"\n> & {\n adIds?: ObjectId[];\n eventInfoId: ObjectId;\n owner: SchemaOwnerType;\n /** Lowercase `name` mirror for prefix type-ahead (see searchNamePlugin). */\n searchName?: string;\n};\n\n/**\n * This is the schema for the event type.\n * It is used to define the structure of the event type in the database.\n * The schema is used by Mongoose to create a model for the event type.\n */\nconst schema = new MongooseSchema<SchemaEventType>(\n {\n ...baseResourceFields, // Importing base resource fields from global.ts\n claimed: { default: true, required: false, type: Boolean },\n dateTime: { required: true, type: [dateTimeSchema] },\n eventInfoId: {\n ref: \"EventInfo\",\n required: false,\n type: mongoose.Schema.Types.ObjectId,\n },\n eventType: {\n enum: Object.values(EnumEventType),\n required: true,\n type: String,\n },\n googlePlaceId: {\n default: null,\n required: false,\n type: String,\n },\n location: {\n required: true,\n type: locationsSchema,\n },\n nzbn: { required: true, type: String },\n provider: { required: false, type: String },\n rainOrShine: { required: true, type: Boolean },\n shareRelation: { required: false, type: socialShareResourceSchema },\n tags: { required: true, type: [String] },\n },\n { timestamps: true },\n);\n\n// Indexes for search, geo, soft-delete, and dateTime status queries.\nschema.index({ name: 1 });\nschema.index({ description: 1 });\nschema.index({ region: 1 });\nschema.index({ \"location.geo\": \"2dsphere\" });\nschema.index({ tags: 1 });\nschema.index({ deletedAt: 1 });\nschema.index({ \"dateTime.dateStatus\": 1 });\nschema.index({ slug: 1 });\n\n// Full-text search across name/description/tags (see eventsSearch resolver).\nschema.index({ description: \"text\", name: \"text\", tags: \"text\" });\n\n// Serves getUserEvents / ownedCoupons' Event lookups:\n// `{ deletedAt: null, \"owner.userId\": <id> }` (and ownedCoupons' additional\n// `active: true` is a residual filter).\nschema.index({ deletedAt: 1, \"owner.userId\": 1 });\n\nschema.plugin(searchNamePlugin);\n\nexport const EventModel =\n (mongoose.models.Event as mongoose.Model<SchemaEventType>) ||\n mongoose.model<SchemaEventType>(\"Event\", schema);\n","import { DateTimeType } from \"@timardex/cluemart-shared\";\nimport mongoose from \"mongoose\";\n\nimport { ObjectId } from \"src/types\";\n\nimport { dateTimeSchema } from \"../global\";\n\nexport type SchemaEventDateArchiveType = {\n dateTime: DateTimeType[];\n eventId: ObjectId;\n};\n\n/**\n * Archived (ended) event date slots removed from `Event.dateTime` so the Event\n * document only carries the live schedule. One document per event, mirroring\n * the Event model's `dateTime` array shape.\n */\nconst schema = new mongoose.Schema<SchemaEventDateArchiveType>(\n {\n dateTime: { required: true, type: [dateTimeSchema] },\n eventId: {\n ref: \"Event\",\n required: true,\n type: mongoose.Schema.Types.ObjectId,\n },\n },\n { timestamps: true },\n);\n\n// One archive document per event.\nschema.index({ eventId: 1 }, { unique: true });\n\nexport const EventDateArchiveModel =\n (mongoose.models\n .EventDateArchive as mongoose.Model<SchemaEventDateArchiveType>) ||\n mongoose.model<SchemaEventDateArchiveType>(\"EventDateArchive\", schema);\n","import { EnumPartnerType, PartnerType } from \"@timardex/cluemart-shared\";\nimport mongoose from \"mongoose\";\n\nimport { ObjectId } from \"src/types\";\n\nimport { baseResourceFields, locationsSchema, SchemaOwnerType } from \"./global\";\nimport { searchNamePlugin } from \"./searchNamePlugin\";\n\nconst MongooseSchema = mongoose.Schema;\n\nexport type SchemaPartnerType = Omit<PartnerType, \"owner\" | \"adIds\"> & {\n adIds?: ObjectId[];\n owner: SchemaOwnerType;\n /** Lowercase `name` mirror for prefix type-ahead (see searchNamePlugin). */\n searchName?: string;\n};\n\nconst schema = new MongooseSchema<SchemaPartnerType>(\n {\n ...baseResourceFields,\n location: {\n required: true,\n type: locationsSchema,\n },\n nzbn: { required: true, type: String },\n partnerType: {\n enum: Object.values(EnumPartnerType),\n required: true,\n type: String,\n },\n },\n { timestamps: true },\n);\n\n// 🔹 Add indexes to speed up regex-based searches\nschema.index({ name: 1 });\nschema.index({ description: 1 });\nschema.index({ region: 1 });\nschema.index({ \"location.geo\": \"2dsphere\" });\nschema.index({ slug: 1 });\n\n// Full-text search across name/description (see partnersSearch resolver).\nschema.index({ name: \"text\", description: \"text\" });\n\n// Serves getUserPartners / ownedCoupons' Partner lookups:\n// `{ deletedAt: null, \"owner.userId\": <id> }`.\nschema.index({ \"owner.userId\": 1, deletedAt: 1 });\n\nschema.plugin(searchNamePlugin);\n\nexport const PartnerModel =\n (mongoose.models.Partner as mongoose.Model<SchemaPartnerType>) ||\n mongoose.model<SchemaPartnerType>(\"Partner\", schema);\n","import {\n EnumPostContentType,\n EnumPostType,\n EnumResourceType,\n PostContentType,\n PostResource,\n PostType,\n} from \"@timardex/cluemart-shared\";\nimport mongoose, { Schema } from \"mongoose\";\n\nimport { ResourceImageTypeSchema, socialShareResourceSchema } from \"./global\";\n\nconst MongooseSchema = mongoose.Schema;\n\nexport type SchemaPostType = PostType;\n\nconst contentSchema = new MongooseSchema<PostContentType>(\n {\n contentData: Schema.Types.Mixed,\n contentOrder: { required: true, type: Number },\n contentType: {\n enum: Object.values(EnumPostContentType),\n required: true,\n type: String,\n },\n },\n { _id: false },\n);\n\nconst resourceSchema = new MongooseSchema<PostResource>(\n {\n resourceId: { required: true, type: String },\n resourceRegion: { required: true, type: String },\n resourceSlug: { required: true, type: String },\n resourceType: {\n enum: Object.values(EnumResourceType),\n required: true,\n type: String,\n },\n },\n { _id: false },\n);\n\nconst schema = new MongooseSchema<SchemaPostType>(\n {\n active: { default: false, required: true, type: Boolean },\n approvedAt: { default: null, required: false, type: Date },\n caption: { required: true, type: String },\n content: {\n default: [],\n required: false,\n type: [contentSchema],\n },\n cover: {\n required: false,\n type: ResourceImageTypeSchema,\n },\n deletedAt: { default: null, required: false, type: Date },\n postType: {\n enum: Object.values(EnumPostType),\n required: true,\n type: String,\n },\n resource: {\n required: false,\n type: resourceSchema,\n },\n sharePublic: { required: false, type: socialShareResourceSchema },\n slug: { required: true, type: String },\n tags: { default: [], required: false, type: [String] },\n title: { required: true, type: String },\n },\n { timestamps: true },\n);\n\n// 🔹 Add indexes to speed up searches by title and tags\nschema.index({ title: 1 });\nschema.index({ tags: 1 });\nschema.index({ postType: 1, slug: 1 }, { unique: true });\n\nexport const PostModel =\n (mongoose.models.Post as mongoose.Model<SchemaPostType>) ||\n mongoose.model<SchemaPostType>(\"Post\", schema);\n","import { AppSettingsType } from \"@timardex/cluemart-shared\";\nimport mongoose from \"mongoose\";\n\nconst MongooseSchema = mongoose.Schema;\n\nexport const APP_SETTINGS_ID = \"APP_SETTINGS_DOCUMENT_ID\";\n\nexport type SchemaAppSettingsType = AppSettingsType & {\n adSettings: {\n approvalRequired: boolean;\n minAppearancesPerHour?: number;\n mobileDisplayEnabled: boolean;\n purchasePricing?: Record<string, unknown>;\n regionPricing?: Record<string, unknown>;\n paidSlotsPerPlacement?: number;\n reservedSlotsPerPlacement?: number;\n rotationSeconds?: number;\n webDisplayEnabled: boolean;\n };\n};\n\nconst AppSettingSchema = new MongooseSchema<SchemaAppSettingsType>(\n {\n activeSchoolsStudentCountTotal: {\n default: 0,\n required: true,\n type: Number,\n },\n activeSchoolsStudentCountUpdatedAt: {\n default: Date.now,\n required: true,\n type: Date,\n },\n adSettings: {\n approvalRequired: { default: true, required: true, type: Boolean },\n // Kept for older API clients; these fields do not control ad delivery.\n minAppearancesPerHour: {\n max: 12,\n min: 1,\n type: Number,\n validate: Number.isInteger,\n },\n mobileDisplayEnabled: { default: false, required: true, type: Boolean },\n purchasePricing: { type: MongooseSchema.Types.Mixed },\n regionPricing: { type: MongooseSchema.Types.Mixed },\n paidSlotsPerPlacement: { enum: [30], type: Number },\n reservedSlotsPerPlacement: { enum: [7], type: Number },\n rotationSeconds: { enum: [8], type: Number },\n webDisplayEnabled: { default: false, required: true, type: Boolean },\n },\n appVersion: { default: \"1.0.1\", required: true, type: String },\n isOfflineMode: { default: false, required: true, type: Boolean },\n key: {\n default: APP_SETTINGS_ID,\n immutable: true, // ✅ prevents changes after creation\n required: true,\n type: String,\n unique: true, // ✅ allowed here\n },\n minimumRedeemableAffiliatePoints: {\n default: 500,\n required: true,\n type: Number,\n },\n },\n { timestamps: true },\n);\n\nexport const AppSettingModel =\n (mongoose.models.AppSetting as mongoose.Model<SchemaAppSettingsType>) ||\n mongoose.model<SchemaAppSettingsType>(\"AppSetting\", AppSettingSchema);\n","import mongoose from \"mongoose\";\n\nimport type { ObjectId } from \"src/types\";\n\nconst MongooseSchema = mongoose.Schema;\n\n/**\n * Single-use record backing a WebView auto-login handoff.\n *\n * The app mints a short-lived signed token and opens the admin site with it;\n * the admin site exchanges the token for its own admin-slot session. Keeping\n * the `jti` here (with an atomic `usedAt` update) makes the token replay-proof\n * across server instances — a purely in-memory store would not.\n */\nexport interface AuthHandoffTokenType {\n createdAt: Date;\n expiresAt: Date;\n jti: string;\n updatedAt: Date;\n usedAt: Date | null;\n userId: ObjectId;\n}\n\nconst schema = new MongooseSchema<AuthHandoffTokenType>(\n {\n expiresAt: { required: true, type: Date },\n jti: { index: true, required: true, type: String, unique: true },\n usedAt: { default: null, required: false, type: Date },\n userId: {\n index: true,\n ref: \"User\",\n required: true,\n type: mongoose.Schema.Types.ObjectId,\n },\n },\n { timestamps: true },\n);\n\n// MongoDB removes the record once the handoff lifetime is over.\nschema.index({ expiresAt: 1 }, { expireAfterSeconds: 0 });\n\nexport const AuthHandoffTokenModel =\n (mongoose.models.AuthHandoffToken as mongoose.Model<AuthHandoffTokenType>) ||\n mongoose.model<AuthHandoffTokenType>(\"AuthHandoffToken\", schema);\n","import {\n EnumGameStatus,\n EnumGameType,\n GameDocType,\n GameHistory,\n GameType,\n} from \"@timardex/cluemart-shared\";\nimport mongoose from \"mongoose\";\n\nimport { ObjectId } from \"src/types\";\n\nimport { OwnerTypeSchema } from \"../global\";\n\nimport { schemaDailyClueGameData } from \"./DailyClue\";\nimport { schemaPuzzleGameData } from \"./PuzzleGame\";\nimport { schemaGameDate } from \"./utils\";\n\nconst MongooseSchema = mongoose.Schema;\n\nexport type SchemaGameType = Omit<GameType, \"_id\"> & {\n _id: ObjectId;\n};\n\n// REMOVE partial when other game types are added\nconst gameDataSchemas: Partial<Record<EnumGameType, any>> = {\n [EnumGameType.DAILY_CLUE]: schemaDailyClueGameData,\n [EnumGameType.MINI_QUIZ]: schemaPuzzleGameData,\n [EnumGameType.ODD_ONE_OUT]: schemaPuzzleGameData,\n};\n\nconst gameDataDefinition = Object.fromEntries(\n Object.entries(gameDataSchemas).map(([key, schema]) => [\n key,\n { default: null, required: false, type: schema },\n ]),\n);\n\nconst gameHistorySchema = new MongooseSchema<GameHistory>(\n {\n createdAt: { required: true, type: Date },\n gameDate: { required: true, type: schemaGameDate },\n gameStatus: {\n enum: Object.values(EnumGameStatus),\n required: true,\n type: String,\n },\n gameTitle: { required: true, type: String },\n gameType: {\n enum: Object.values(EnumGameType),\n required: true,\n type: String,\n },\n gameTypeId: { required: true, type: String },\n pointsEarned: { default: 0, required: true, type: Number },\n },\n { _id: false },\n);\n\nconst gameTypeSchema = new MongooseSchema<SchemaGameType>(\n {\n active: { default: true, required: true, type: Boolean },\n gameData: gameDataDefinition,\n gameHistory: { default: [], required: true, type: [gameHistorySchema] },\n gameTitle: { required: true, type: String },\n gameType: {\n enum: Object.values(EnumGameType),\n required: true,\n type: String,\n },\n gameTypeId: { required: true, type: String },\n // See `GameType.pointsCredited`: absent means \"completed before the marker\n // existed\", which must not be re-credited.\n pointsCredited: { required: false, type: Boolean },\n },\n { timestamps: true },\n);\n\nconst schema = new MongooseSchema<GameDocType>(\n {\n active: { default: false, required: true, type: Boolean },\n deletedAt: { default: null, required: false, type: Date },\n games: { default: [], required: false, type: [gameTypeSchema] },\n owner: {\n required: true,\n type: OwnerTypeSchema,\n },\n points: { default: 0, required: true, type: Number },\n },\n { timestamps: true },\n);\n\nexport const GameModel =\n (mongoose.models.Game as mongoose.Model<GameDocType>) ||\n mongoose.model<GameDocType>(\"Game\", schema);\n","import {\n DailyClueBaseGame,\n DailyClueGameData,\n} from \"@timardex/cluemart-shared\";\nimport mongoose from \"mongoose\";\n\nimport { schemaGameDate } from \"./utils\";\n\nconst MongooseSchema = mongoose.Schema;\n\n/*\n DAILY CLUE GAME DATA SCHEMA\n**/\nconst schemaLetters = new MongooseSchema<DailyClueGameData[\"letterInfo\"]>(\n {\n collected: { required: false, type: [String] },\n solutionShuffled: { required: true, type: [String] },\n // todaysLetter and todaysPlacement is generated in the backend, so they are not required\n },\n { _id: false },\n);\n\n/**\n * ✅ Shared definition (THIS replaces .obj usage)\n * related to Post Model, PostContentData is using BaseGame\n */\nconst schemaDailyClueBaseGame = new MongooseSchema<DailyClueBaseGame>(\n {\n gameDate: { required: true, type: schemaGameDate },\n gameSolution: { required: true, type: String },\n },\n { _id: false },\n);\n\nexport const schemaDailyClueGameData = new MongooseSchema<DailyClueGameData>(\n {\n gameFields: { required: true, type: schemaDailyClueBaseGame },\n lastFoundDate: { default: null, required: false, type: Date },\n letterInfo: {\n required: true,\n type: schemaLetters,\n },\n points: { default: 0, required: true, type: Number },\n streak: { default: 0, required: true, type: Number },\n },\n { _id: false },\n);\n","import { GameDate } from \"@timardex/cluemart-shared\";\nimport mongoose from \"mongoose\";\n\nconst MongooseSchema = mongoose.Schema;\n\n// ✅ Shared definition\nexport const schemaGameDate = new MongooseSchema<GameDate>(\n {\n endDate: { required: true, type: Date },\n startDate: { required: true, type: Date },\n },\n { _id: false },\n);\n","import {\n PuzzleAnswer,\n PuzzleAnsweredQuestion,\n PuzzleBaseGame,\n PuzzleGameData,\n PuzzleQuestion,\n} from \"@timardex/cluemart-shared\";\nimport mongoose from \"mongoose\";\n\nconst MongooseSchema = mongoose.Schema;\n\nconst schemaPuzzleAnswer = new MongooseSchema<PuzzleAnswer>(\n {\n answer: { required: true, type: String },\n answerId: { required: true, type: String },\n correct: { required: true, type: Boolean },\n },\n { _id: false },\n);\n\nconst schemaPuzzleQuestion = new MongooseSchema<PuzzleQuestion>(\n {\n answers: { required: true, type: [schemaPuzzleAnswer] },\n question: { required: true, type: String },\n questionId: { required: true, type: String },\n },\n { _id: false },\n);\n\nconst schemaPuzzleBaseGame = new MongooseSchema<PuzzleBaseGame>(\n {\n questions: { required: true, type: [schemaPuzzleQuestion] },\n },\n { _id: false },\n);\n\nconst schemaPuzzleAnsweredQuestion = new MongooseSchema<PuzzleAnsweredQuestion>(\n {\n questionId: { required: true, type: String },\n selectedAnswerId: { required: true, type: String },\n },\n { _id: false },\n);\n\nexport const schemaPuzzleGameData = new MongooseSchema<PuzzleGameData>(\n {\n answeredQuestions: {\n default: null,\n required: false,\n type: [schemaPuzzleAnsweredQuestion],\n },\n gameFields: { required: true, type: schemaPuzzleBaseGame },\n points: { default: 0, required: true, type: Number },\n streak: { default: 0, required: true, type: Number },\n },\n { _id: false },\n);\n","import { SchoolCampaignType, SchoolType } from \"@timardex/cluemart-shared\";\nimport mongoose from \"mongoose\";\n\nimport {\n ContactDetailsSchema,\n locationsSchema,\n OwnerTypeSchema,\n ResourceImageTypeSchema,\n SocialMediaTypeSchema,\n termsAgreementSchema,\n} from \"./global\";\n\nconst MongooseSchema = mongoose.Schema;\n\ntype SchoolDocument = Omit<SchoolType, \"ranking\">;\n\nconst campaignsSchema = new MongooseSchema<SchoolCampaignType>(\n {\n endDate: { required: true, type: Date },\n name: { required: true, type: String },\n startDate: { required: true, type: Date },\n },\n { _id: false },\n);\n\nconst schema = new MongooseSchema<SchoolDocument>(\n {\n // New schools are active by default\n active: { default: false, required: true, type: Boolean },\n approvedAt: { default: null, required: false, type: Date },\n campaigns: { required: false, type: [campaignsSchema] },\n contactDetails: { required: false, type: ContactDetailsSchema },\n deletedAt: { default: null, required: false, type: Date },\n location: {\n required: true,\n type: locationsSchema,\n },\n logo: { required: false, type: ResourceImageTypeSchema },\n name: { required: true, type: String },\n overallPoints: { default: 0, required: false, type: Number },\n owner: {\n required: true,\n type: OwnerTypeSchema,\n },\n region: { required: true, type: String },\n schoolCode: { required: true, type: String },\n socialMedia: { required: false, type: [SocialMediaTypeSchema] },\n studentCount: { default: 0, required: true, type: Number },\n termsAgreement: { required: true, type: termsAgreementSchema },\n },\n { timestamps: true },\n);\n\nschema.index(\n { schoolCode: 1 },\n {\n partialFilterExpression: { active: true, deletedAt: null },\n unique: true,\n },\n);\n\nexport const SchoolModel =\n (mongoose.models.School as mongoose.Model<SchoolDocument>) ||\n mongoose.model<SchoolDocument>(\"School\", schema);\n","import {\n AffiliateBankAccountDetailsType,\n AffiliateContactDetails,\n AffiliateDetailsType,\n AffiliateResourceType,\n AffiliateRewardType,\n AffiliateType,\n EnumAffiliateParticipantType,\n EnumAffiliateRewardType,\n EnumResourceType,\n RedeemHistoryType,\n} from \"@timardex/cluemart-shared\";\nimport mongoose from \"mongoose\";\n\nimport { ObjectId } from \"src/types\";\n\nimport {\n locationsSchema,\n OwnerTypeSchema,\n SchemaOwnerType,\n SocialMediaTypeSchema,\n termsAgreementSchema,\n} from \"./global\";\n\nconst MongooseSchema = mongoose.Schema;\n\nexport type SchemaAffiliateReward = AffiliateRewardType;\n\nexport type SchemaAffiliateResourceType = Omit<\n AffiliateResourceType,\n \"resourceId\" | \"resourceOwner\"\n> & {\n resourceId: ObjectId;\n resourceOwner: SchemaOwnerType;\n};\n\ntype AffiliateDocument = Omit<\n AffiliateType,\n \"_id\" | \"owner\" | \"affiliateResources\"\n> & {\n affiliateResources: SchemaAffiliateResourceType[];\n owner: SchemaOwnerType;\n};\n\nconst affiliateRewardSchema = new MongooseSchema<SchemaAffiliateReward>(\n {\n createdAt: { required: true, type: Date },\n redeemedAt: { default: null, required: false, type: Date },\n rewardDescription: { required: true, type: String },\n rewardType: {\n enum: Object.values(EnumAffiliateRewardType),\n required: true,\n type: String,\n },\n rewardValue: { required: true, type: Number },\n },\n { _id: false },\n);\n\nconst affiliateResourceSchema = new MongooseSchema<SchemaAffiliateResourceType>(\n {\n resourceActive: { default: true, required: true, type: Boolean },\n resourceDeletedAt: { default: null, required: false, type: Date },\n resourceId: {\n required: true,\n type: mongoose.Schema.Types.ObjectId,\n },\n resourceName: { required: true, type: String },\n resourceOwner: {\n required: true,\n type: OwnerTypeSchema,\n },\n resourceType: {\n enum: Object.values(EnumResourceType),\n required: true,\n type: String,\n },\n rewards: {\n default: [],\n required: false,\n type: [affiliateRewardSchema],\n },\n },\n { _id: false },\n);\n\nconst affiliateContactDetailsSchema =\n new MongooseSchema<AffiliateContactDetails>(\n {\n mobilePhone: { required: true, type: String },\n },\n { _id: false },\n );\n\nconst affiliateBankAccountDetailsSchema =\n new MongooseSchema<AffiliateBankAccountDetailsType>(\n {\n accountHolderName: { required: true, type: String },\n accountNumber: { required: true, type: String },\n },\n { _id: false },\n );\n\nconst affiliateDetailsSchema = new MongooseSchema<AffiliateDetailsType>(\n {\n bankAccountDetails: {\n required: true,\n type: affiliateBankAccountDetailsSchema,\n },\n contactDetails: { required: true, type: affiliateContactDetailsSchema },\n email: { required: true, type: String },\n firstName: { required: true, type: String },\n irdNumber: { required: true, type: String },\n lastName: { required: true, type: String },\n location: { required: true, type: locationsSchema },\n participantType: {\n enum: Object.values(EnumAffiliateParticipantType),\n required: true,\n type: String,\n },\n socialMedia: { required: false, type: [SocialMediaTypeSchema] },\n termsAgreement: { required: true, type: termsAgreementSchema },\n },\n { _id: false },\n);\n\nconst redeemHistorySchema = new MongooseSchema<RedeemHistoryType>(\n {\n paidAt: { default: null, required: false, type: Date },\n redeemedAt: { required: true, type: Date },\n rewardValue: { required: true, type: Number },\n },\n { _id: false },\n);\n\nconst schema = new MongooseSchema<AffiliateDocument>(\n {\n active: { default: false, required: true, type: Boolean },\n affiliateBonusRewards: {\n default: [],\n required: false,\n type: [affiliateRewardSchema],\n },\n affiliateCode: { default: null, required: false, type: String },\n affiliateDetails: { required: false, type: affiliateDetailsSchema },\n affiliateResources: {\n default: [],\n required: false,\n type: [affiliateResourceSchema],\n },\n approvedAt: { default: null, required: false, type: Date },\n deletedAt: { default: null, required: false, type: Date },\n overallPoints: { default: 0, required: true, type: Number },\n owner: {\n required: true,\n type: OwnerTypeSchema,\n },\n redeemHistory: {\n default: [],\n required: false,\n type: [redeemHistorySchema],\n },\n },\n { timestamps: true },\n);\n\nschema.index(\n { affiliateCode: 1 },\n {\n partialFilterExpression: { active: true, deletedAt: null },\n unique: true,\n },\n);\n\nexport const AffiliateModel =\n (mongoose.models.Affiliate as mongoose.Model<AffiliateDocument>) ||\n mongoose.model<AffiliateDocument>(\"Affiliate\", schema);\n","import {\n CouponCodeType,\n CouponDataType,\n CouponOption,\n CouponParticipantUserType,\n CouponType,\n EnumCouponQualificationType,\n EnumResourceType,\n} from \"@timardex/cluemart-shared\";\nimport mongoose from \"mongoose\";\n\nimport { ObjectId } from \"src/types\";\n\nimport { OwnerTypeSchema, ResourceImageTypeSchema } from \"./global\";\n\nconst MongooseSchema = mongoose.Schema;\n\ntype SchemaCouponParticipantUserType = Omit<\n CouponParticipantUserType,\n \"userId\"\n> & {\n userId: ObjectId;\n};\n\ntype SchemaCouponVendorProductType = {\n couponId: ObjectId;\n productId: ObjectId;\n vendorCouponId?: ObjectId;\n vendorId: ObjectId;\n};\n\ntype SchemaCouponDataType = Omit<\n CouponDataType,\n \"participantUsers\" | \"couponVendorProducts\"\n> & {\n couponVendorProducts?: SchemaCouponVendorProductType[];\n participantUsers: SchemaCouponParticipantUserType[] | null;\n};\n\nexport type CouponDocument = Omit<CouponType, \"couponData\"> & {\n couponData: SchemaCouponDataType[];\n};\n\nconst couponOptionSchema = new MongooseSchema<CouponOption>(\n {\n buy: { required: false, type: Number },\n get: { required: false, type: Number },\n maxRewardCount: { required: false, type: Number },\n type: {\n enum: Object.values(EnumCouponQualificationType),\n required: true,\n type: String,\n },\n unit: { required: false, type: String },\n visits: { required: false, type: Number },\n },\n { _id: false },\n);\n\nconst couponVendorProductSchema =\n new MongooseSchema<SchemaCouponVendorProductType>(\n {\n couponId: {\n required: true,\n type: mongoose.Schema.Types.ObjectId,\n },\n productId: {\n required: true,\n type: mongoose.Schema.Types.ObjectId,\n },\n vendorCouponId: {\n required: false,\n type: mongoose.Schema.Types.ObjectId,\n },\n vendorId: {\n ref: \"Vendor\",\n required: true,\n type: mongoose.Schema.Types.ObjectId,\n },\n },\n { _id: false },\n );\n\nconst couponCodeSchema = new MongooseSchema<CouponCodeType>(\n {\n code: { required: true, type: String },\n qrCode: { required: true, type: ResourceImageTypeSchema },\n shareableQrCode: { required: true, type: ResourceImageTypeSchema },\n },\n { _id: false },\n);\n\nconst couponParticipantUserSchema =\n new MongooseSchema<SchemaCouponParticipantUserType>(\n {\n couponCollectedCount: { default: 0, required: true, type: Number },\n couponCycleRedeemed: { default: false, required: true, type: Boolean },\n couponRedeemedAt: { default: null, required: false, type: Date },\n couponRedeemedCount: { default: 0, required: true, type: Number },\n userId: {\n ref: \"User\",\n required: true,\n type: mongoose.Schema.Types.ObjectId,\n },\n },\n { timestamps: true },\n );\n\nconst couponDataSchema = new MongooseSchema<SchemaCouponDataType>(\n {\n active: { default: true, required: true, type: Boolean },\n couponCode: { required: false, type: couponCodeSchema },\n couponDescription: { required: true, type: String },\n couponOption: { required: true, type: couponOptionSchema },\n couponVendorProducts: {\n required: false,\n type: [couponVendorProductSchema],\n },\n deletedAt: { default: null, required: false, type: Date },\n endDate: { required: true, type: Date },\n participantUsers: {\n default: null,\n required: false,\n type: [couponParticipantUserSchema],\n },\n resourceId: { required: true, type: String },\n resourceType: {\n enum: Object.values(EnumResourceType),\n required: true,\n type: String,\n },\n startDate: { required: true, type: Date },\n },\n { timestamps: true },\n);\n\nconst schema = new MongooseSchema<CouponDocument>(\n {\n active: { default: true, required: true, type: Boolean },\n couponData: { default: [], required: false, type: [couponDataSchema] },\n deletedAt: { default: null, required: false, type: Date },\n owner: {\n required: true,\n type: OwnerTypeSchema,\n },\n },\n { timestamps: true },\n);\n\n// Indexes for the getCoupons aggregations. All three (activeCoupons,\n// scannedCoupons, ownedCoupons) open with `{ active: true, deletedAt: null }`,\n// so one compound index serves that shared prefix; `owner.userId` (a top-level\n// embedded field, NOT inside `couponData`) covers ownedCoupons' equality match.\n// The nested participant filter used by scannedCoupons lives inside the\n// `couponData` array of subdocuments, so it needs its own multikey index.\n//\n// Note: the `$sort: { updatedAt: -1 }` at the end of each aggregation cannot\n// use an index because it follows `$addFields`/`$match` stages — only the\n// leading `$match` is indexable.\nschema.index({ active: 1, deletedAt: 1, \"owner.userId\": 1 });\nschema.index({ \"couponData.participantUsers.userId\": 1 });\n\nexport const CouponModel =\n (mongoose.models.Coupon as mongoose.Model<CouponDocument>) ||\n mongoose.model<CouponDocument>(\"Coupon\", schema);\n","import { EnumResourceType } from \"@timardex/cluemart-shared\";\nimport mongoose from \"mongoose\";\n\nimport { ObjectId } from \"src/types\";\n\nconst MongooseSchema = mongoose.Schema;\n\nexport type SchemaImpersonationSessionType = {\n /** The SUPER_ADMIN who is impersonating. */\n impersonatorUserId: ObjectId;\n /** The resource owner being impersonated. */\n impersonatedUserId: ObjectId;\n /** Hashed impersonation refresh token (stored here, not on the User doc). */\n refreshToken: string;\n expiresAt: Date;\n};\n\nconst impersonationSessionSchema =\n new MongooseSchema<SchemaImpersonationSessionType>(\n {\n expiresAt: { expires: 0, required: true, type: Date },\n impersonatedUserId: {\n index: true,\n ref: \"User\",\n required: true,\n type: mongoose.Schema.Types.ObjectId,\n },\n impersonatorUserId: {\n index: true,\n ref: \"User\",\n required: true,\n type: mongoose.Schema.Types.ObjectId,\n },\n refreshToken: { required: true, type: String },\n },\n { timestamps: true },\n );\n\nexport const ImpersonationSessionModel =\n (mongoose.models\n .ImpersonationSession as mongoose.Model<SchemaImpersonationSessionType>) ||\n mongoose.model<SchemaImpersonationSessionType>(\n \"ImpersonationSession\",\n impersonationSessionSchema,\n );\n\nexport type SchemaImpersonationAuditType = {\n action: \"start\" | \"end\";\n /** Reason for an `end` record (manual, logout, reuse_revoked, expired). */\n endReason?: string | null;\n impersonatedUserId: ObjectId;\n impersonatorUserId: ObjectId;\n resourceId?: ObjectId | null;\n resourceType?: EnumResourceType | null;\n sessionId: ObjectId;\n};\n\nconst impersonationAuditSchema =\n new MongooseSchema<SchemaImpersonationAuditType>(\n {\n action: { enum: [\"start\", \"end\"], required: true, type: String },\n endReason: { type: String },\n impersonatedUserId: {\n ref: \"User\",\n required: true,\n type: mongoose.Schema.Types.ObjectId,\n },\n impersonatorUserId: {\n ref: \"User\",\n required: true,\n type: mongoose.Schema.Types.ObjectId,\n },\n resourceId: { type: mongoose.Schema.Types.ObjectId },\n resourceType: { enum: Object.values(EnumResourceType), type: String },\n sessionId: {\n ref: \"ImpersonationSession\",\n required: true,\n type: mongoose.Schema.Types.ObjectId,\n },\n },\n { timestamps: true },\n );\n\nexport const ImpersonationAuditModel =\n (mongoose.models\n .ImpersonationAudit as mongoose.Model<SchemaImpersonationAuditType>) ||\n mongoose.model<SchemaImpersonationAuditType>(\n \"ImpersonationAudit\",\n impersonationAuditSchema,\n );\n","/** 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 subscription status:\n * - Pro / Pro+ with Stripe (ACTIVE/TRIALING) → `ACTIVE_VENDOR_PRO_SUBSCRIPTION` (3 pts)\n * - Pro / Pro+ without an eligible Stripe subscription → `ACTIVE_VENDOR_STANDARD_SUBSCRIPTION` (1 pt)\n * - Standard → `ACTIVE_VENDOR_STANDARD_SUBSCRIPTION` (1 pt)\n *\n * Stripe eligibility requires a subscription ID and a vendor Pro / Pro+ plan,\n * but not a future paid-through endDate. It does not establish paid licence access.\n * Idempotent per affiliate + vendor + calendar month — a mid-month upgrade\n * (Standard → Pro with an eligible Stripe subscription) affects the next 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 NZ_TZ,\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 { getVendorStripeSubscriptionPlanForRewards } 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 = NZ_TZ;\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+ yields the Pro reward when the owner has a Stripe subscription ID,\n * a vendor Pro / Pro+ plan, and ACTIVE or TRIALING subscription status.\n * A future paid-through endDate is not required for rewards; this does not\n * establish paid access for licence compliance. Otherwise falls back to Standard.\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 getVendorStripeSubscriptionPlanForRewards(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 StripeSubscriptionPlanResult = {\n /** Meets the caller's eligibility policy; reward eligibility is not paid access. */\n hasSubscription: boolean;\n plan: EnumUserLicence | null;\n validTypes: Set<EnumUserLicence>;\n};\n\nasync function getStripePlanFor(\n userId: ObjectId | string,\n now: Date,\n allowedPlans: Set<EnumUserLicence>,\n requirePaidAccess: boolean = true,\n): Promise<StripeSubscriptionPlanResult> {\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 =\n stripe.status === EnumSubscriptionStatus.ACTIVE ||\n (!requirePaidAccess && stripe.status === EnumSubscriptionStatus.TRIALING);\n const paidThrough = stripe.endDate\n ? new Date(stripe.endDate).getTime()\n : Number.NaN;\n\n if (\n !hasActiveStatus ||\n (requirePaidAccess &&\n (!Number.isFinite(paidThrough) || paidThrough <= now.getTime())) ||\n stripe.currentPlan == null\n ) {\n return { hasSubscription: false, plan: null, validTypes };\n }\n\n const plan = allowedPlans.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<StripeSubscriptionPlanResult> {\n return getStripePlanFor(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<StripeSubscriptionPlanResult> {\n return getStripePlanFor(userId, now, PRO_VENDOR_PLANS);\n}\n\n/**\n * Preserves affiliate reward eligibility for active or trialing vendor plans.\n * This does not establish paid access and must not be used for licence compliance.\n */\nexport async function getVendorStripeSubscriptionPlanForRewards(\n userId: ObjectId | string,\n now: Date = new Date(),\n): Promise<StripeSubscriptionPlanResult> {\n return getStripePlanFor(userId, now, PRO_VENDOR_PLANS, false);\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<StripeSubscriptionPlanResult> {\n return getStripePlanFor(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 { EnumUserRole } from \"@timardex/cluemart-shared\";\nimport { NotificationCount } from \"@timardex/cluemart-shared/types\";\nimport express from \"express\";\nimport mongoose from \"mongoose\";\n\nimport { SchemaChatType } from \"../mongoose/chat/Chat\";\nimport { SchemaNotificationType } from \"../mongoose/Notification\";\n\n// chnage to export type ObjectId = mongoose.Types.ObjectId;\n// chnage in server when setting decideGameType\nexport type ObjectId = mongoose.Types.ObjectId;\n\nexport enum EnumPubSubEvents {\n GET_CHAT_MESSAGE = \"GET_CHAT_MESSAGE\",\n GET_NOTIFICATIONS = \"GET_NOTIFICATIONS\",\n GET_NOTIFICATIONS_COUNT = \"GET_NOTIFICATIONS_COUNT\",\n USER_TYPING = \"USER_TYPING\",\n}\n\n/** Clients that own their own refresh-token slot on the user document. */\nexport type AuthTokenClient = \"mobile\" | \"admin\";\n\nexport interface AuthUser {\n email: string;\n roles: EnumUserRole[];\n userId: ObjectId;\n /**\n * Which client slot this token belongs to. Absent only on tokens issued\n * before the per-client rollout; those can no longer refresh.\n */\n client?: AuthTokenClient;\n /** Set when this token represents an impersonation session. */\n impersonationSessionId?: string;\n /** The SUPER_ADMIN who started the impersonation session. */\n impersonatorUserId?: ObjectId;\n}\n\nexport interface SubscriptionPayload {\n getChatMessage?: SchemaChatType;\n userTyping?: SchemaChatType; // NOT USED\n getNotifications?: SchemaNotificationType[];\n // Used only for filtering; not part of the GraphQL schema output\n getNotificationsUserId?: ObjectId;\n getNotificationsCount?: NotificationCount & { userId: ObjectId };\n}\n\nexport interface GraphQLContext {\n appVersion: string | null;\n user: AuthUser | null;\n pubsub: {\n publish: (\n eventName: EnumPubSubEvents,\n payload: SubscriptionPayload,\n ) => void;\n subscribe: (eventName: EnumPubSubEvents) => AsyncIterable<any>;\n };\n request: express.Request;\n response: express.Response;\n}\n\nexport { mongoose, express };\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 nzDayKey,\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 * `start`/`end` are UTC-midnight NZ day keys, so comparisons run against\n * today's NZ day key rather than the current instant.\n */\nexport async function updateAdStatuses(): Promise<void> {\n const now = nzDayKey();\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 EnumPointType,\n UserOverallPointsEntry,\n} from \"@timardex/cluemart-shared\";\nimport dayjs from \"dayjs\";\n\n/**\n * Rejects amounts that would corrupt the ledger: a negative award silently\n * reduces the balance, and `NaN`/`Infinity` poison every later `$sum`/`$reduce`\n * (a single `NaN` makes the whole spendable total `NaN`).\n */\nfunction assertValidPointAmount(amount: number, label: string): void {\n if (!Number.isFinite(amount) || amount < 0) {\n throw new RangeError(\n `Invalid user point ${label}: ${String(amount)}. Expected a finite, non-negative number.`,\n );\n }\n}\n\n/**\n * One ledger entry for an award.\n *\n * `User.overallPoints` is append-only: awarding points must push a new entry so\n * previously earned points are never replaced.\n *\n * `sourceId` is the idempotency key for the award (e.g. the game row `_id`).\n * Pass it whenever the award can be retried, so `buildUserPointCreditFilter`\n * can dedupe it.\n *\n * `undefined` is the only \"no key\" value: an empty string is stored as-is so the\n * entry always matches what `buildUserPointCreditFilter` searches for (a\n * truthiness check here would drop `\"\"` from the entry while the filter still\n * looked for it, silently disabling dedupe).\n */\nexport function buildUserPointAwardEntry(\n pointType: EnumPointType,\n points: number,\n sourceId?: string,\n): UserOverallPointsEntry {\n assertValidPointAmount(points, \"award\");\n return {\n createdAt: dayjs().toDate(),\n points,\n pointType,\n ...(sourceId === undefined ? {} : { sourceId }),\n };\n}\n\n/**\n * Filter for an idempotent award: matches the user only when no ledger entry\n * already carries `sourceId`.\n *\n * Uses `$not` + `$elemMatch` rather than a dotted `$ne` so the \"no entry with\n * this key\" intent is explicit and cannot be mistaken for a per-element\n * comparison. Combined with `$push` of\n * `buildUserPointAwardEntry(..., sourceId)`, running the award twice credits it\n * once. This replaces a cross-document transaction (unavailable on standalone\n * MongoDB) for \"credit points, then mark the source as done\" flows.\n */\nexport function buildUserPointCreditFilter(userId: unknown, sourceId: string) {\n return {\n _id: userId,\n overallPoints: { $not: { $elemMatch: { sourceId } } },\n };\n}\n\n/**\n * Matches users whose spendable total (sum of every ledger entry) covers\n * `amount`. Legacy numeric values contribute 0 until the startup migration runs.\n */\nexport function buildUserHasEnoughPointsFilter(amount: number) {\n assertValidPointAmount(amount, \"threshold\");\n return {\n $expr: {\n $gte: [{ $sum: { $ifNull: [\"$overallPoints.points\", []] } }, amount],\n },\n };\n}\n\n/**\n * Write expression for the ledger field, guarded against unexpected stored\n * shapes:\n * - array: store the computed ledger.\n * - null/missing: normalized to an empty ledger, otherwise a later `$push`\n * fails with \"must be an array\" and the field stays null forever.\n * - any other value: written back unchanged rather than replaced with `[]`, so\n * an unexpected shape is surfaced rather than silently wiping a balance.\n */\nfunction buildLedgerWriteExpr(computedLedger: object) {\n return {\n $cond: [\n { $isArray: \"$overallPoints\" },\n computedLedger,\n { $ifNull: [\"$overallPoints\", []] },\n ],\n };\n}\n\n/**\n * Debits `amount` from the oldest entries first (FIFO), flooring every entry at\n * 0 and dropping emptied ones. Pair with `buildUserHasEnoughPointsFilter` so\n * the full amount is always covered.\n *\n * Non-array `overallPoints` values are handled by `buildLedgerWriteExpr`:\n * null/missing becomes an empty ledger, while any other shape is left untouched\n * rather than replaced.\n */\nexport function buildUserPointDebitPipeline(amount: number) {\n assertValidPointAmount(amount, \"debit\");\n const debitedLedger = {\n $let: {\n vars: {\n sorted: {\n $sortArray: {\n input: { $ifNull: [\"$overallPoints\", []] },\n sortBy: { createdAt: 1 },\n },\n },\n },\n in: {\n $let: {\n vars: {\n debited: {\n $reduce: {\n initialValue: { budget: amount, entries: [] },\n in: {\n $let: {\n vars: { available: { $ifNull: [\"$$this.points\", 0] } },\n in: {\n budget: {\n $subtract: [\n \"$$value.budget\",\n { $min: [\"$$available\", \"$$value.budget\"] },\n ],\n },\n entries: {\n $concatArrays: [\n \"$$value.entries\",\n [\n {\n $mergeObjects: [\n \"$$this\",\n {\n points: {\n $subtract: [\n \"$$available\",\n {\n $min: [\"$$available\", \"$$value.budget\"],\n },\n ],\n },\n },\n ],\n },\n ],\n ],\n },\n },\n },\n },\n input: \"$$sorted\",\n },\n },\n },\n in: {\n $filter: {\n as: \"entry\",\n cond: { $gt: [\"$$entry.points\", 0] },\n input: \"$$debited.entries\",\n },\n },\n },\n },\n },\n };\n\n return [\n {\n $set: {\n overallPoints: buildLedgerWriteExpr(debitedLedger),\n },\n },\n ];\n}\n\n/**\n * Removes the first ledger entry matching `pointType` (and `sourceId`, when\n * given), reversing a single award. `$pull` cannot be used because it would\n * remove every entry of that type.\n *\n * Always pass `sourceId` when the award carries one: matching on `pointType`\n * alone would remove an unrelated award of the same type (e.g. checking out of\n * one event stripping a different event's check-in points).\n *\n * Non-array `overallPoints` values are handled by `buildLedgerWriteExpr`:\n * null/missing becomes an empty ledger, while any other shape is left untouched\n * rather than replaced.\n */\nexport function buildUserPointEntryRemovalPipeline(\n pointType: EnumPointType,\n sourceId?: string,\n) {\n // Compare entries by `pointType` + `sourceId` via a boolean map, then locate\n // the first `true`. Matching both fields is what keeps the removal specific.\n const indexExpression =\n sourceId === undefined\n ? { $indexOfArray: [\"$$entries.pointType\", pointType] }\n : {\n $indexOfArray: [\n {\n $map: {\n as: \"entry\",\n in: {\n $and: [\n { $eq: [\"$$entry.pointType\", pointType] },\n { $eq: [\"$$entry.sourceId\", sourceId] },\n ],\n },\n input: \"$$entries\",\n },\n },\n true,\n ],\n };\n\n const entriesAfterRemoval = {\n $let: {\n vars: { entries: { $ifNull: [\"$overallPoints\", []] } },\n in: {\n $let: {\n vars: {\n index: indexExpression,\n },\n in: {\n $cond: [\n { $lt: [\"$$index\", 0] },\n \"$$entries\",\n {\n $concatArrays: [\n { $slice: [\"$$entries\", \"$$index\"] },\n {\n $slice: [\n \"$$entries\",\n { $add: [\"$$index\", 1] },\n { $size: \"$$entries\" },\n ],\n },\n ],\n },\n ],\n },\n },\n },\n },\n };\n\n return [\n {\n $set: {\n overallPoints: buildLedgerWriteExpr(entriesAfterRemoval),\n },\n },\n ];\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 AiImportedMarketModel,\n EventDateArchiveModel,\n EventInfoModel,\n EventModel,\n GoogleImportedMarketModel,\n} from \"src/mongoose\";\n\nimport {\n dedupeArchivedSlotsByStartDateTime,\n isPastCanceledEventDate,\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: [\n EnumEventDateStatus.ENDED,\n EnumEventDateStatus.INVALID,\n EnumEventDateStatus.CANCELED,\n ],\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 EventDatePullCondition = {\n $or: Array<\n | { dateStatus: { $in: EnumEventDateStatus[] } }\n | {\n dateStatus: EnumEventDateStatus;\n startDate: string;\n startTime: string;\n }\n >;\n};\n\ntype EventDatePullOp = {\n updateOne: {\n filter: { _id: unknown };\n update: {\n $pull: {\n dateTime: EventDatePullCondition;\n };\n };\n };\n};\n\ntype EventDatePullableModel = {\n bulkWrite: (ops: EventDatePullOp[]) => Promise<unknown>;\n};\n\n/**\n * Moves ended event date slots into the archive, discards invalid slots, deletes\n * past canceled slots, and pulls all three from `Event.dateTime`, keeping future,\n * in-progress (`STARTED`), and future `CANCELED` dates live. Archive upserts and\n * event `$pull` updates are collected into bulkWrite batches to avoid\n * per-document round-trips. The event write is a targeted `$pull` (by status or\n * by start date/time) rather than a full-array `$set`, so concurrent schedule\n * 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 as unknown as EventDatePullableModel).bulkWrite(\n eventOps,\n );\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 const pastCanceled = updated.filter((slot) =>\n isPastCanceledEventDate(slot, now),\n );\n if (\n archive.length === 0 &&\n discard.length === 0 &&\n pastCanceled.length === 0\n ) {\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 const pullConditions: EventDatePullCondition[\"$or\"] = [];\n if (archive.length > 0 || discard.length > 0) {\n pullConditions.push({\n dateStatus: {\n $in: [EnumEventDateStatus.ENDED, EnumEventDateStatus.INVALID],\n },\n });\n }\n for (const slot of pastCanceled) {\n pullConditions.push({\n dateStatus: EnumEventDateStatus.CANCELED,\n startDate: slot.startDate,\n startTime: slot.startTime,\n });\n }\n\n eventOps.push({\n updateOne: {\n filter: { _id: doc._id },\n update: {\n $pull: {\n dateTime: { $or: pullConditions },\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, aiMarketCount] = await Promise.all([\n updateModelDateTimeStatuses(EventModel as DateTimeUpdatableModel, now),\n updateModelDateTimeStatuses(\n GoogleImportedMarketModel as DateTimeUpdatableModel,\n now,\n ),\n updateModelDateTimeStatuses(\n AiImportedMarketModel as DateTimeUpdatableModel,\n now,\n ),\n ]);\n\n console.log(\n `✅ Event dateTime statuses updated: events=${eventCount} changed, google imported markets=${marketCount} changed, ai imported markets=${aiMarketCount} 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 {\n DateTimeType,\n EnumEventDateStatus,\n dateFormat,\n timeFormat,\n} from \"@timardex/cluemart-shared\";\nimport dayjs from \"dayjs\";\nimport customParseFormat from \"dayjs/plugin/customParseFormat\";\n\nimport { EventDateArchiveModel } from \"src/mongoose\";\nimport { ObjectId } from \"src/types\";\n\ndayjs.extend(customParseFormat);\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 * A CANCELED slot is \"past\" once its end date/time has passed. Past canceled\n * slots can be deleted from the live schedule without touching future canceled\n * slots or accidentally removing malformed manual cancellations (missing or\n * unparseable end dates are not considered past).\n */\nexport function isPastCanceledEventDate(\n slot: DateTimeType,\n now: dayjs.Dayjs,\n): boolean {\n if (slot.dateStatus !== EnumEventDateStatus.CANCELED) {\n return false;\n }\n\n const endDateTime = dayjs(\n `${slot.endDate} ${slot.endTime}`,\n `${dateFormat} ${timeFormat}`,\n true,\n );\n\n return endDateTime.isValid() && endDateTime.isBefore(now);\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 * from \"./userPoints\";\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 AiImportedMarketModel,\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, Google Imported Market, or AI\n * Imported Market by the given resource ID.\n * It first normalizes the resource ID to a string format, then performs parallel queries to all three collections.\n * If an Event is found, it returns that; otherwise it checks the imported-market collections and returns the first match.\n * If none 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 an 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, aiImportedDoc] = 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 AiImportedMarketModel.findById(normalizedId)\n .select(\"_id name dateTime\")\n .lean<Pick<EventListItemType, \"_id\" | \"name\" | \"dateTime\">>()\n .exec(),\n ]);\n\n return eventDoc ?? googleImportedDoc ?? aiImportedDoc;\n}\n","import {\n DateTimeWithPriceType,\n EnumEventDateStatus,\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\ntype StartedDateSlot = Pick<\n DateTimeType,\n \"dateStatus\" | \"startDate\" | \"startTime\"\n>;\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 * Returns true when a slot that was `STARTED` in the previous schedule is no\n * longer `STARTED` in the next schedule (e.g. canceled or rescheduled).\n *\n * This catches the `STARTED → CANCELED` transition that\n * {@link didRemoveAnyEventDates} misses: that function only compares\n * `startDate`/`startTime` presence, so a slot that still exists but whose\n * `dateStatus` changed is not flagged. (Its callers filter to future-only\n * schedules, which also drop `STARTED`.) Without this extra status check, a\n * started slot that gets canceled would leave its relation dates untouched.\n */\nexport function didRemoveAnyStartedDates(\n previousDateTime: StartedDateSlot[] | undefined,\n nextDateTime: StartedDateSlot[] | undefined,\n): boolean {\n if (!previousDateTime?.length) {\n return false;\n }\n\n return previousDateTime.some(\n (prev) =>\n prev.dateStatus === EnumEventDateStatus.STARTED &&\n !nextDateTime?.some(\n (next) =>\n next.startDate === prev.startDate &&\n next.startTime === prev.startTime &&\n next.dateStatus === EnumEventDateStatus.STARTED,\n ),\n );\n}\n\n/**\n * Helper: Update relationDates based on event's dateTime\n * Marks dates as CANCELED if they no longer exist in the event's dateTime.\n */\nexport function updateRelationDatesToCanceled(\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 ? relationDate.status : EnumInviteStatus.CANCELED,\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":";;;;;;;;;;;;;;;;;;;;;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AAEA,UAAQ;AAAA,IACN,oBAAe,MAAM,MAAM,gBAAgB,kBAAkB;AAAA,EAC/D;AACF;","names":["express","mongoose","mongoose","import_cluemart_shared","import_mongoose","schema","mongoose","import_cluemart_shared","import_mongoose","schema","mongoose","import_mongoose","schema","mongoose","import_cluemart_shared","import_mongoose","mongoose","schema","import_cluemart_shared","import_mongoose","MongooseSchema","mongoose","schema","import_cluemart_shared","import_mongoose","MongooseSchema","mongoose","import_cluemart_shared","import_mongoose","MongooseSchema","mongoose","import_cluemart_shared","import_mongoose","MongooseSchema","mongoose","import_cluemart_shared","import_mongoose","$set","schema","MongooseSchema","mongoose","schema","import_cluemart_shared","import_mongoose","MongooseSchema","mongoose","addressComponentSchema","schema","import_mongoose","MongooseSchema","mongoose","import_cluemart_shared","import_mongoose","MongooseSchema","mongoose","schema","import_mongoose","MongooseSchema","mongoose","schema","import_cluemart_shared","import_mongoose","import_cluemart_shared","import_mongoose","MongooseSchema","mongoose","dateTimeSchema","schema","MongooseSchema","mongoose","import_cluemart_shared","import_mongoose","MongooseSchema","mongoose","schema","import_cluemart_shared","import_mongoose","MongooseSchema","mongoose","schema","import_mongoose","MongooseSchema","mongoose","schema","import_cluemart_shared","import_mongoose","MongooseSchema","mongoose","schema","import_cluemart_shared","import_mongoose","MongooseSchema","mongoose","schema","import_mongoose","MongooseSchema","mongoose","schema","import_cluemart_shared","import_mongoose","MongooseSchema","mongoose","schema","import_mongoose","schema","mongoose","import_cluemart_shared","import_mongoose","MongooseSchema","mongoose","schema","import_cluemart_shared","import_mongoose","MongooseSchema","mongoose","schema","import_mongoose","MongooseSchema","mongoose","import_mongoose","MongooseSchema","mongoose","schema","import_cluemart_shared","import_mongoose","import_mongoose","import_mongoose","MongooseSchema","mongoose","MongooseSchema","mongoose","import_mongoose","MongooseSchema","mongoose","MongooseSchema","mongoose","schema","import_mongoose","MongooseSchema","mongoose","schema","import_cluemart_shared","import_mongoose","MongooseSchema","mongoose","schema","import_cluemart_shared","import_mongoose","MongooseSchema","mongoose","schema","import_cluemart_shared","import_mongoose","MongooseSchema","mongoose","import_cluemart_shared","import_utils","import_cluemart_shared","import_enums","dayjs","utc","timezone","import_mongoose","mongoose","import_mongoose","EnumPubSubEvents","import_cluemart_shared","import_mongoose","mongoose","import_dayjs","dayjs","import_cluemart_shared","import_dayjs","import_cluemart_shared","import_dayjs","dayjs","customParseFormat","dayjs","import_cluemart_shared","import_cluemart_shared","import_dayjs","import_cluemart_shared","import_dayjs","import_cluemart_shared","import_cluemart_shared","import_cluemart_shared","import_dayjs","import_cluemart_shared","import_dayjs","LicenceCategory","dayjs","dayjs","dayjs","dayjs","import_dayjs","import_cluemart_shared","import_utils","import_dayjs","dayjs","dayjs"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/mongoose/ad/Ad.ts","../src/mongoose/ad/AdBillingCatalog.ts","../src/mongoose/ad/AdBooking.ts","../src/mongoose/ad/AdPurchase.ts","../src/mongoose/ad/AdMetrics.ts","../src/mongoose/BillingCatalog.ts","../src/mongoose/chat/Chat.ts","../src/mongoose/chat/ChatReport.ts","../src/mongoose/global.ts","../src/mongoose/GoogleImportedMarket.ts","../src/mongoose/searchNamePlugin.ts","../src/mongoose/AiImportedMarket.ts","../src/mongoose/AiImportRun.ts","../src/mongoose/AiImportRunLock.ts","../src/mongoose/ScrapeSite.ts","../src/mongoose/Notification.ts","../src/mongoose/PushToken.ts","../src/mongoose/Relation.ts","../src/mongoose/event/EventInfo.ts","../src/mongoose/ResourceActivity.ts","../src/mongoose/User.ts","../src/mongoose/VerificationToken.ts","../src/mongoose/vendor/Vendor.ts","../src/mongoose/vendor/VendorInfo.ts","../src/mongoose/vendor/UnregisteredVendor.ts","../src/mongoose/event/Event.ts","../src/mongoose/event/EventDateArchive.ts","../src/mongoose/Partner.ts","../src/mongoose/Post.ts","../src/mongoose/AppSetting.ts","../src/mongoose/AuthHandoffToken.ts","../src/mongoose/game/Game.ts","../src/mongoose/game/DailyClue.ts","../src/mongoose/game/utils.ts","../src/mongoose/game/PuzzleGame.ts","../src/mongoose/School.ts","../src/mongoose/Affiliate.ts","../src/mongoose/Coupon.ts","../src/mongoose/Impersonation.ts","../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/types/index.ts","../src/service/notifyUsers.ts","../src/service/updateAdStatus.ts","../src/service/objectIdToString.ts","../src/service/userPoints.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":["export * from \"./mongoose\";\nexport * from \"./service\";\nexport * from \"./types\";\n","import {\n EnumAdApprovalStatus,\n EnumAdBookingSlotKind,\n EnumAdPaymentStatus,\n AdType,\n EnumAdShowOn,\n EnumAdStatus,\n EnumAdStyle,\n EnumAdType,\n EnumResourceType,\n isUtcMidnight,\n} from \"@timardex/cluemart-shared\";\nimport mongoose from \"mongoose\";\n\nconst MongooseSchema = mongoose.Schema;\n\nexport const schemaAdresource = new MongooseSchema<AdType[\"resource\"]>({\n adDescription: { required: true, type: String },\n adImage: { required: true, type: String },\n adStyle: {\n default: EnumAdStyle.BLOOM,\n enum: Object.values(EnumAdStyle),\n required: true,\n type: String,\n },\n adTitle: { required: true, type: String },\n adType: {\n default: EnumAdType.SPONSORED,\n enum: Object.values(EnumAdType),\n required: true,\n type: String,\n },\n resourceId: { required: true, type: String },\n resourceName: { required: true, type: String },\n resourceRegion: { required: true, type: String },\n resourceSlug: { required: true, type: String },\n resourceType: {\n enum: Object.values(EnumResourceType),\n required: true,\n type: String,\n },\n});\n\nconst schema = new MongooseSchema<AdType>(\n {\n active: { default: true, type: Boolean },\n approvalStatus: {\n enum: Object.values(EnumAdApprovalStatus),\n required: false,\n type: String,\n },\n bookingIds: {\n default: undefined,\n ref: \"AdBooking\",\n type: [mongoose.Schema.Types.ObjectId],\n },\n bookingKind: {\n enum: Object.values(EnumAdBookingSlotKind),\n required: false,\n type: String,\n },\n end: {\n required: true,\n type: Date,\n validate: {\n message: \"end must be a UTC-midnight day key.\",\n validator: isUtcMidnight,\n },\n },\n paymentStatus: {\n enum: Object.values(EnumAdPaymentStatus),\n required: false,\n type: String,\n },\n resource: { required: true, type: schemaAdresource },\n showOn: {\n default: [EnumAdShowOn.FRONT_PAGE],\n enum: Object.values(EnumAdShowOn),\n required: true,\n type: [String],\n },\n start: {\n required: true,\n type: Date,\n validate: {\n message: \"start must be a UTC-midnight day key.\",\n validator: isUtcMidnight,\n },\n },\n status: {\n default: EnumAdStatus.ACTIVE,\n enum: Object.values(EnumAdStatus),\n required: true,\n type: String,\n },\n targetRegion: { required: false, type: [String] },\n },\n {\n timestamps: true,\n },\n);\n\n// Background job queries (updateAdStatuses): filter on `end` first\n// (`expired`: end <= now, `active`: end > now && start <= now), so `end` must\n// lead, followed by the next range/equality keys in order of use.\nschema.index({\n end: 1,\n start: 1,\n status: 1,\n});\n\n// Hot read path (getAdsByRegion): `{ status, targetRegion: $in, active }`\n// sorted by `start` desc. Equality/$in keys must come before the sort key, so\n// `status` leads (most selective), then `targetRegion`, then `start` for the\n// sort. Order matters: with `start` leading, Mongo could only sort, not bound\n// the scan by status/region.\nschema.index({\n status: 1,\n targetRegion: 1,\n // eslint-disable-next-line sort-keys\n start: -1,\n});\n\nschema.index(\n { bookingIds: 1 },\n {\n partialFilterExpression: { bookingIds: { $exists: true } },\n unique: true,\n },\n);\n\nexport const AdModel =\n (mongoose.models.Ad as mongoose.Model<AdType>) ||\n mongoose.model<AdType>(\"Ad\", schema);\n","import { AdDailyPriceType, EnumAdShowOn } from \"@timardex/cluemart-shared\";\nimport mongoose from \"mongoose\";\n\nexport const AD_BILLING_CATALOG_COLLECTION_NAME = \"adBillingCatalog\";\n\nconst schema = new mongoose.Schema<AdDailyPriceType>(\n {\n active: { default: true, required: true, type: Boolean },\n currency: {\n default: \"nzd\",\n enum: [\"nzd\"],\n immutable: true,\n required: true,\n type: String,\n },\n key: {\n enum: Object.values(EnumAdShowOn),\n immutable: true,\n required: true,\n type: String,\n unique: true,\n },\n revision: { default: 1, min: 1, required: true, type: Number },\n unitAmount: {\n min: 1,\n required: true,\n type: Number,\n validate: {\n message: \"Daily ad price must be a positive integer amount of cents.\",\n validator: Number.isInteger,\n },\n },\n },\n { collection: AD_BILLING_CATALOG_COLLECTION_NAME, timestamps: true },\n);\n\nexport const AdBillingCatalogModel =\n (mongoose.models.AdBillingCatalog as mongoose.Model<AdDailyPriceType>) ||\n mongoose.model<AdDailyPriceType>(\n \"AdBillingCatalog\",\n schema,\n AD_BILLING_CATALOG_COLLECTION_NAME,\n );\n","import {\n AdBookingType,\n EnumAdApprovalStatus,\n EnumAdBookingSlotKind,\n EnumAdBookingState,\n EnumAdShowOn,\n isUtcMidnight,\n} from \"@timardex/cluemart-shared\";\nimport mongoose from \"mongoose\";\n\nimport { schemaAdresource } from \"./Ad\";\n\nconst liveStates = [\n EnumAdBookingState.HELD,\n EnumAdBookingState.PENDING_APPROVAL,\n EnumAdBookingState.APPROVED,\n];\n\nconst schema = new mongoose.Schema<AdBookingType>(\n {\n adId: { default: null, ref: \"Ad\", type: String },\n approvalStatus: {\n default: EnumAdApprovalStatus.PENDING,\n enum: Object.values(EnumAdApprovalStatus),\n required: true,\n type: String,\n },\n checkoutAttemptId: { default: null, type: String },\n currency: { default: null, lowercase: true, type: String },\n dayKey: {\n immutable: true,\n required: true,\n type: Date,\n validate: {\n message: \"dayKey must be a UTC-midnight day key.\",\n validator: isUtcMidnight,\n },\n },\n expiresAt: { default: null, type: Date },\n placement: {\n enum: Object.values(EnumAdShowOn),\n immutable: true,\n required: true,\n type: String,\n },\n purchaseKey: { default: null, immutable: true, type: String },\n region: {\n immutable: true,\n lowercase: true,\n required: true,\n trim: true,\n type: String,\n },\n resource: { required: true, type: schemaAdresource },\n slotKind: {\n default: EnumAdBookingSlotKind.PAID,\n enum: Object.values(EnumAdBookingSlotKind),\n immutable: true,\n required: true,\n type: String,\n },\n slotNumber: { immutable: true, min: 1, required: true, type: Number },\n state: {\n default: EnumAdBookingState.HELD,\n enum: Object.values(EnumAdBookingState),\n required: true,\n type: String,\n },\n stripeCheckoutSessionId: { default: null, type: String },\n stripePaymentIntentId: { default: null, type: String },\n unitAmount: { default: null, min: 1, type: Number },\n userId: { immutable: true, ref: \"User\", required: true, type: String },\n },\n { timestamps: true },\n);\n\nschema.pre(\n \"validate\",\n function validateSlot(this: mongoose.HydratedDocument<AdBookingType>) {\n if (!Number.isInteger(this.slotNumber)) {\n this.invalidate(\"slotNumber\", \"Ad booking slot must be an integer.\");\n return;\n }\n\n const maximum = 30;\n if (this.slotNumber < 1 || this.slotNumber > maximum) {\n this.invalidate(\n \"slotNumber\",\n `Ad booking slot must be between 1 and ${maximum}.`,\n );\n }\n\n if (\n this.slotKind === EnumAdBookingSlotKind.PAID &&\n this.state !== EnumAdBookingState.HELD &&\n this.state !== EnumAdBookingState.FAILED &&\n this.state !== EnumAdBookingState.CANCELLED &&\n (!this.unitAmount || !this.currency)\n ) {\n this.invalidate(\n \"unitAmount\",\n \"Paid ad booking must retain its checkout price.\",\n );\n }\n },\n);\n\n// A released slot can be reused while retaining failed/cancelled/rejected history.\n/* eslint-disable sort-keys -- Compound-index field order controls slot lookups. */\nschema.index(\n { region: 1, placement: 1, dayKey: 1, slotKind: 1, slotNumber: 1 },\n { unique: true, partialFilterExpression: { state: { $in: liveStates } } },\n);\nschema.index({ userId: 1, dayKey: -1 });\nschema.index(\n { checkoutAttemptId: 1 },\n {\n partialFilterExpression: { checkoutAttemptId: { $type: \"string\" } },\n unique: true,\n },\n);\nschema.index(\n { purchaseKey: 1 },\n {\n partialFilterExpression: {\n purchaseKey: { $type: \"string\" },\n state: { $in: liveStates },\n },\n unique: true,\n },\n);\n/* eslint-enable sort-keys */\nschema.index(\n { stripeCheckoutSessionId: 1 },\n {\n partialFilterExpression: { stripeCheckoutSessionId: { $type: \"string\" } },\n unique: true,\n },\n);\n\nexport const AdBookingModel =\n (mongoose.models.AdBooking as mongoose.Model<AdBookingType>) ||\n mongoose.model<AdBookingType>(\"AdBooking\", schema);\n","import mongoose from \"mongoose\";\n\nimport { schemaAdresource } from \"./Ad\";\n\n/** One Stripe payment covers individually capacity-guarded daily bookings. */\nconst schema = new mongoose.Schema(\n {\n _id: { required: true, type: String },\n approvalRequired: { type: Boolean },\n bookingIds: { required: true, type: [String] },\n checkoutAttemptId: { required: true, type: String },\n checkoutLeaseUntil: { type: Date },\n checkoutLeaseToken: { type: String },\n createdAt: { default: Date.now, required: true, type: Date },\n expiresAt: { required: true, type: Date },\n holdsReleased: { type: Boolean },\n quote: { required: true, type: mongoose.Schema.Types.Mixed },\n resource: { required: true, type: schemaAdresource },\n selectionKey: { required: true, type: String },\n state: {\n enum: [\"reserving\", \"checkout\", \"paid\", \"failed\", \"cancelled\"],\n required: true,\n type: String,\n },\n stripeCheckoutSessionId: { default: null, type: String },\n stripePaymentIntentId: { default: null, type: String },\n stripeRequestStartedAt: { type: Date },\n userId: { required: true, type: String },\n },\n { collection: \"adPurchases\" },\n);\n\n/* eslint-disable sort-keys -- Unique index matches checkout ownership and attempt. */\nschema.index({ userId: 1, checkoutAttemptId: 1 }, { unique: true });\n/* eslint-enable sort-keys */\nschema.index(\n { stripeCheckoutSessionId: 1 },\n {\n unique: true,\n partialFilterExpression: { stripeCheckoutSessionId: { $type: \"string\" } },\n },\n);\n/* eslint-disable sort-keys -- Expired purchase scan. */\nschema.index({ state: 1, expiresAt: 1 });\n/* eslint-enable sort-keys */\n\nexport const AdPurchaseModel =\n mongoose.models.AdPurchase || mongoose.model(\"AdPurchase\", schema);\n","import {\n AdMetricsResourceType,\n AdMetricsType,\n EnumAdPlatform,\n EnumAdShowOn,\n isUtcMidnight,\n} from \"@timardex/cluemart-shared\";\nimport mongoose from \"mongoose\";\n\nconst ResourceMetricsSchema = new mongoose.Schema<AdMetricsResourceType>(\n {\n clicks: { default: 0, required: true, type: Number },\n date: {\n immutable: true,\n required: true,\n type: Date,\n validate: {\n message: \"date must be a UTC-midnight day key.\",\n validator: isUtcMidnight,\n },\n },\n impressions: { default: 0, required: true, type: Number },\n placement: {\n enum: Object.values(EnumAdShowOn),\n immutable: true,\n required: true,\n type: String,\n },\n platform: {\n enum: Object.values(EnumAdPlatform),\n immutable: true,\n required: true,\n type: String,\n },\n },\n { _id: false },\n);\n\nconst schema = new mongoose.Schema<AdMetricsType>(\n {\n adId: { ref: \"Ad\", required: true, type: String },\n resource: { default: [], type: [ResourceMetricsSchema] },\n },\n { timestamps: true },\n);\n\n// One metrics document per ad, with a bucket per NZ calendar day, placement\n// and platform inside its `resource` array.\n//\n// The `adId` unique index enforces one document per ad so concurrent `$push`\n// upserts can't create duplicate parent documents; the compound multikey index\n// enforces one bucket per (ad, day, placement, platform) across documents.\nschema.index({ adId: 1 }, { unique: true });\nschema.index(\n {\n adId: 1,\n \"resource.date\": 1,\n \"resource.placement\": 1,\n \"resource.platform\": 1,\n },\n { unique: true },\n);\n\nexport const AdMetricsModel =\n (mongoose.models.AdMetrics as mongoose.Model<AdMetricsType>) ||\n mongoose.model<AdMetricsType>(\"AdMetrics\", schema);\n","import {\n BILLING_CATALOG_CURRENCY,\n BILLING_CATALOG_DEFINITIONS,\n BILLING_CATALOG_KEYS,\n billingCatalogDefinitionMatches,\n BillingCatalogEntryType,\n BillingCatalogPriceHistoryEntry,\n EnumBillingPeriod,\n EnumUserLicence,\n INITIAL_BILLING_CATALOG,\n} from \"@timardex/cluemart-shared\";\nimport mongoose from \"mongoose\";\n\nimport { ObjectId } from \"src/types\";\n\nconst MongooseSchema = mongoose.Schema;\n\nexport const BILLING_CATALOG_COLLECTION_NAME = \"billingCatalog\";\n\nexport type SchemaBillingCatalogPriceHistoryEntry = Omit<\n BillingCatalogPriceHistoryEntry,\n \"changedBy\"\n> & {\n changedBy?: ObjectId | null;\n};\n\nexport type SchemaBillingCatalogEntry = Omit<\n BillingCatalogEntryType,\n \"_id\" | \"priceHistory\" | \"updatedBy\"\n> & {\n _id: ObjectId;\n priceHistory: SchemaBillingCatalogPriceHistoryEntry[];\n updatedBy?: ObjectId | null;\n};\n\nconst paidVendorLicences = [\n EnumUserLicence.PRO_VENDOR,\n EnumUserLicence.PRO_PLUS_VENDOR,\n] as const;\n\nconst supportedBillingPeriods = [\n EnumBillingPeriod.MONTHLY_CANCEL_ANYTIME,\n EnumBillingPeriod.YEARLY_ANNUAL_BILLED,\n] as const;\n\nconst unitAmountField = {\n min: 1,\n required: true,\n type: Number,\n validate: {\n message: \"Billing catalogue price must be a positive integer.\",\n validator: Number.isInteger,\n },\n} as const;\n\nconst currencyField = {\n default: BILLING_CATALOG_CURRENCY,\n enum: [BILLING_CATALOG_CURRENCY],\n immutable: true,\n lowercase: true,\n required: true,\n trim: true,\n type: String,\n} as const;\n\nconst stripePriceIdField = {\n default: null,\n required: false,\n trim: true,\n type: String,\n} as const;\n\nconst stripeProductIdField = {\n default: null,\n required: false,\n trim: true,\n type: String,\n} as const;\n\nconst priceHistorySchema =\n new MongooseSchema<SchemaBillingCatalogPriceHistoryEntry>(\n {\n changedAt: { required: true, type: Date },\n changedBy: {\n default: null,\n ref: \"User\",\n required: false,\n type: mongoose.Schema.Types.ObjectId,\n },\n currency: currencyField,\n effectiveFrom: { required: true, type: Date },\n effectiveTo: { required: true, type: Date },\n stripePriceId: stripePriceIdField,\n stripeProductId: stripeProductIdField,\n unitAmount: unitAmountField,\n },\n { _id: false },\n );\n\nconst schema = new MongooseSchema<SchemaBillingCatalogEntry>(\n {\n active: { default: true, required: true, type: Boolean },\n billingPeriod: {\n enum: supportedBillingPeriods,\n immutable: true,\n required: true,\n type: String,\n },\n currency: currencyField,\n effectiveFrom: { default: Date.now, required: true, type: Date },\n key: {\n enum: BILLING_CATALOG_KEYS,\n immutable: true,\n required: true,\n type: String,\n unique: true,\n },\n licenceType: {\n enum: paidVendorLicences,\n immutable: true,\n required: true,\n type: String,\n },\n priceHistory: {\n default: [],\n required: true,\n type: [priceHistorySchema],\n },\n revision: {\n default: 1,\n min: 1,\n required: true,\n type: Number,\n validate: {\n message: \"Billing catalogue revision must be a positive integer.\",\n validator: Number.isInteger,\n },\n },\n stripePriceId: stripePriceIdField,\n stripeProductId: stripeProductIdField,\n taxInclusive: {\n default: true,\n immutable: true,\n required: true,\n type: Boolean,\n validate: {\n message: \"Billing catalogue prices must include GST.\",\n validator: (value: boolean) => value === true,\n },\n },\n unitAmount: unitAmountField,\n updatedBy: {\n default: null,\n ref: \"User\",\n required: false,\n type: mongoose.Schema.Types.ObjectId,\n },\n },\n {\n collection: BILLING_CATALOG_COLLECTION_NAME,\n strict: true,\n timestamps: true,\n },\n);\n\nschema.pre(\"validate\", function validateDefinition() {\n if (!billingCatalogDefinitionMatches(this)) {\n this.invalidate(\n \"key\",\n \"Billing catalogue key does not match its licence and billing period.\",\n );\n }\n});\n\nschema.index({ billingPeriod: 1, licenceType: 1 }, { unique: true });\nschema.index({ active: 1, licenceType: 1 });\nschema.index(\n { stripePriceId: 1 },\n {\n partialFilterExpression: { stripePriceId: { $type: \"string\" } },\n unique: true,\n },\n);\n\nexport const BillingCatalogModel =\n (mongoose.models\n .BillingCatalogEntry as mongoose.Model<SchemaBillingCatalogEntry>) ||\n mongoose.model<SchemaBillingCatalogEntry>(\n \"BillingCatalogEntry\",\n schema,\n BILLING_CATALOG_COLLECTION_NAME,\n );\n\n/**\n * Produces the four records used for an idempotent `$setOnInsert` catalogue\n * initialisation. Stripe identifiers deliberately start empty and are attached\n * only after Stripe successfully creates the matching Product and Price.\n */\nexport function buildInitialBillingCatalogEntries(now: Date = new Date()) {\n return INITIAL_BILLING_CATALOG.map((entry) => ({\n active: entry.active,\n billingPeriod: entry.billingPeriod,\n currency: entry.currency,\n effectiveFrom: new Date(now.getTime()),\n key: entry.key,\n licenceType: entry.licenceType,\n priceHistory: [],\n revision: 1,\n stripePriceId: null,\n stripeProductId: null,\n taxInclusive: entry.taxInclusive,\n unitAmount: entry.unitAmount,\n updatedBy: null,\n }));\n}\n\nexport function getBillingCatalogDefinition(\n key: (typeof BILLING_CATALOG_KEYS)[number],\n) {\n return BILLING_CATALOG_DEFINITIONS[key];\n}\n","import {\n ChatMessageType,\n ChatType,\n EnumChatType,\n ParticipantType,\n} from \"@timardex/cluemart-shared\";\nimport mongoose from \"mongoose\";\n\nimport { ObjectId } from \"src/types\";\n\nconst MongooseSchema = mongoose.Schema;\n\nexport type SchemaChatMessageReplyPreviewType = Omit<\n NonNullable<ChatMessageType[\"replyPreview\"]>,\n \"senderId\"\n> & {\n senderId: ObjectId;\n};\n\nexport type SchemaChatMessageReactionType = Omit<\n NonNullable<ChatMessageType[\"likedBy\"]>[number],\n \"userId\"\n> & {\n userId: ObjectId;\n};\n\nexport type SchemaChatMessageSeenType = Omit<\n NonNullable<ChatMessageType[\"seenBy\"]>[number],\n \"userId\"\n> & {\n userId: ObjectId;\n};\n\nexport type SchemaChatMessageType = Omit<\n ChatMessageType,\n \"senderId\" | \"replyToMessageId\" | \"replyPreview\" | \"likedBy\" | \"seenBy\"\n> & {\n senderId: ObjectId;\n replyToMessageId?: ObjectId | null;\n replyPreview?: SchemaChatMessageReplyPreviewType | null;\n likedBy?: SchemaChatMessageReactionType[];\n seenBy?: SchemaChatMessageSeenType[];\n};\n\nexport type SchemaParticipantType = Omit<ParticipantType, \"userId\"> & {\n userId: ObjectId;\n};\n\nconst MessageReplyPreviewSchema =\n new MongooseSchema<SchemaChatMessageReplyPreviewType>(\n {\n contentPreview: { required: true, type: String },\n senderId: {\n ref: \"User\",\n required: true,\n type: mongoose.Schema.Types.ObjectId,\n },\n senderName: { required: true, type: String },\n },\n { _id: false },\n );\n\nconst MessageReactionSchema = new MongooseSchema<SchemaChatMessageReactionType>(\n {\n createdAt: { required: true, type: Date },\n userId: {\n ref: \"User\",\n required: true,\n type: mongoose.Schema.Types.ObjectId,\n },\n },\n { _id: false },\n);\n\nconst MessageSeenSchema = new MongooseSchema<SchemaChatMessageSeenType>(\n {\n seenAt: { required: true, type: Date },\n userId: {\n ref: \"User\",\n required: true,\n type: mongoose.Schema.Types.ObjectId,\n },\n },\n { _id: false },\n);\n\nconst MessageSchema = new MongooseSchema<SchemaChatMessageType>(\n {\n content: { required: true, type: String },\n likedBy: { default: [], required: false, type: [MessageReactionSchema] },\n replyPreview: {\n required: false,\n type: MessageReplyPreviewSchema,\n },\n replyToMessageId: {\n ref: \"Chat.messages\",\n required: false,\n type: mongoose.Schema.Types.ObjectId,\n },\n seenBy: { default: [], required: false, type: [MessageSeenSchema] },\n senderId: {\n ref: \"User\",\n required: true,\n type: mongoose.Schema.Types.ObjectId,\n },\n },\n { timestamps: true },\n);\n\nexport type SchemaChatType = Omit<ChatType, \"participants\" | \"messages\"> & {\n participants: SchemaParticipantType[];\n messages: SchemaChatMessageType[];\n};\n\nconst ParticipantSchema = new MongooseSchema<SchemaParticipantType>(\n {\n active: { default: true, required: true, type: Boolean },\n userAvatar: { required: false, type: String },\n userEmail: { required: true, type: String },\n userId: {\n ref: \"User\",\n required: true,\n type: mongoose.Schema.Types.ObjectId,\n },\n userName: { required: true, type: String },\n },\n { _id: false }, // Prevents Mongoose from creating an additional _id field for subdocuments\n);\n\nconst ChatSchema = new MongooseSchema<SchemaChatType>(\n {\n active: { default: true, required: true, type: Boolean },\n chatDescription: { required: false, type: String },\n chatName: { required: true, type: String },\n chatType: {\n enum: Object.values(EnumChatType),\n required: true,\n type: String,\n },\n deletedAt: { default: null, required: false, type: Date },\n messages: [MessageSchema],\n participants: [ParticipantSchema],\n region: { default: null, required: false, type: String },\n },\n {\n timestamps: true,\n },\n);\n\nChatSchema.index({\n \"participants.active\": 1,\n \"participants.userId\": 1,\n updatedAt: -1,\n});\n\nexport const ChatModel =\n (mongoose.models.Chat as mongoose.Model<SchemaChatType>) ||\n mongoose.model<SchemaChatType>(\"Chat\", ChatSchema);\n","import {\n EnumChatReportReason,\n ReportChatUser,\n} from \"@timardex/cluemart-shared\";\nimport mongoose from \"mongoose\";\n\nimport { ObjectId } from \"src/types\";\n\nconst MongooseSchema = mongoose.Schema;\n\nexport type SchemaChatReportType = Omit<\n ReportChatUser,\n \"reporterUserId\" | \"reportedUserId\" | \"chatId\"\n> & {\n reporterUserId: ObjectId;\n reportedUserId: ObjectId;\n chatId: ObjectId;\n};\n\nconst ReasonSchema = new MongooseSchema<\n NonNullable<ReportChatUser[\"reason\"]>,\n null,\n unknown\n>(\n {\n details: { default: null, required: false, type: String },\n reasonType: {\n enum: Object.values(EnumChatReportReason),\n required: true,\n type: String,\n },\n },\n { _id: false },\n);\n\nconst ChatReportSchema = new MongooseSchema<SchemaChatReportType>(\n {\n chatId: {\n ref: \"Chat\",\n required: true,\n type: mongoose.Schema.Types.ObjectId,\n },\n reason: { required: true, type: ReasonSchema },\n reportedUserId: {\n ref: \"User\",\n required: true,\n type: mongoose.Schema.Types.ObjectId,\n },\n reporterUserId: {\n ref: \"User\",\n required: true,\n type: mongoose.Schema.Types.ObjectId,\n },\n resolved: { default: false, required: true, type: Boolean },\n },\n { timestamps: true },\n);\n\nChatReportSchema.index({ chatId: 1, reportedUserId: 1 });\nChatReportSchema.index({ createdAt: -1, reporterUserId: 1 });\n\nexport const ChatReportModel =\n (mongoose.models.ChatReport as mongoose.Model<SchemaChatReportType>) ||\n mongoose.model<SchemaChatReportType>(\"ChatReport\", ChatReportSchema);\n","import {\n Category,\n DateTimeType,\n EnumEventDateStatus,\n EnumPostType,\n EnumUserLicence,\n LocationGeoType,\n LocationType,\n OwnerType,\n PosterUsageType,\n RelatedPostType,\n ResourceContactDetailsType,\n ResourceImageType,\n SocialMediaType,\n SocialShareResourceType,\n Subcategory,\n TermsAgreement,\n UserLicenceType,\n} from \"@timardex/cluemart-shared\";\nimport mongoose from \"mongoose\";\n\nimport { ObjectId } from \"src/types\";\n\nconst MongooseSchema = mongoose.Schema;\n\nexport type SchemaRelatedPostType = Omit<RelatedPostType, \"postId\"> & {\n postId: ObjectId;\n};\n\nexport type SchemaOwnerType = Omit<OwnerType, \"userId\"> & {\n userId: ObjectId;\n};\n\nexport const OwnerTypeSchema = new MongooseSchema<SchemaOwnerType>(\n {\n email: { required: true, type: String },\n userId: {\n ref: \"User\",\n required: true,\n type: mongoose.Schema.Types.ObjectId,\n },\n },\n { _id: false }, // Prevents Mongoose from creating an additional _id field for subdocuments\n);\n\nexport const SocialMediaTypeSchema = new MongooseSchema<SocialMediaType>(\n {\n link: { required: true, type: String },\n name: { required: true, type: String },\n },\n { _id: false }, // Prevents Mongoose from creating an additional _id field\n);\n\nexport const ResourceImageTypeSchema = new MongooseSchema<ResourceImageType>(\n {\n active: { default: true, required: true, type: Boolean },\n source: { required: false, type: String },\n title: { required: false, type: String },\n },\n { _id: false }, // Prevents Mongoose from creating an additional _id field for subdocuments\n);\n\nconst SubCategorySchema = new MongooseSchema<Subcategory>(\n {\n id: { required: false, type: String },\n items: [\n {\n id: { required: false, type: String },\n name: { required: false, type: String },\n },\n ],\n name: { required: false, type: String },\n },\n { _id: false }, // Prevents Mongoose from creating an additional _id field for subdocuments\n);\n\nexport const CategorySchema = new MongooseSchema<Category>(\n {\n id: { required: true, type: String },\n name: { required: true, type: String },\n subcategories: [SubCategorySchema],\n },\n { _id: false }, // Prevents Mongoose from creating an additional _id field for subdocuments\n);\n\nconst PosterUsageTypeSchema = new MongooseSchema<PosterUsageType>(\n {\n count: { default: 0, required: false, type: Number },\n month: { required: false, type: String },\n },\n { _id: false }, // Prevents Mongoose from creating an additional _id field for subdocuments\n);\n\nexport const userLicenseSchema = new MongooseSchema<UserLicenceType>(\n {\n expiryDate: { required: true, type: Date },\n issuedDate: { required: true, type: Date },\n licenceType: {\n enum: Object.values(EnumUserLicence),\n required: true,\n type: String,\n },\n prevLicenceType: {\n enum: Object.values(EnumUserLicence),\n required: false,\n type: String,\n },\n },\n { _id: false, timestamps: false },\n);\n\nexport const ContactDetailsSchema =\n new MongooseSchema<ResourceContactDetailsType>(\n {\n email: { required: false, type: String },\n landlinePhone: { required: false, type: String },\n mobilePhone: { required: false, type: String },\n },\n { _id: false }, // Prevents Mongoose from creating an additional _id field for subdocuments\n );\n\nexport const termsAgreementSchema = new MongooseSchema<TermsAgreement>(\n {\n appBuildNumber: { required: true, type: String },\n appId: { required: true, type: String },\n appVersion: { required: true, type: String },\n brand: { required: true, type: String },\n deviceName: { required: true, type: String },\n installationId: { required: true, type: String },\n manufacturer: { required: true, type: String },\n modelName: { required: true, type: String },\n osName: { required: true, type: String },\n osVersion: { required: true, type: String },\n termVersion: { required: true, type: String },\n timestamp: { required: true, type: Date },\n },\n { _id: false },\n);\n\nexport const dateTimeSchema = new MongooseSchema<DateTimeType>(\n {\n dateStatus: {\n enum: Object.values(EnumEventDateStatus),\n required: false,\n type: String,\n },\n endDate: { required: true, type: String },\n endTime: { required: true, type: String },\n startDate: { required: true, type: String },\n startTime: { required: true, type: String },\n },\n { _id: false }, // Prevents Mongoose from creating an additional _id field for subdocuments\n);\n\nexport const locationGeoSchema = new MongooseSchema<LocationGeoType>(\n {\n coordinates: { required: true, type: [Number] }, // [longitude, latitude]\n type: { default: \"Point\", enum: [\"Point\"], required: true, type: String },\n },\n { _id: false }, // Prevents Mongoose from creating an additional _id field for subdocuments\n);\n\nexport const locationsSchema = new MongooseSchema<LocationType>(\n {\n city: { required: true, type: String },\n country: { required: true, type: String },\n fullAddress: { required: true, type: String },\n geo: {\n required: true,\n type: locationGeoSchema,\n },\n latitude: { required: true, type: Number },\n longitude: { required: true, type: Number },\n region: { required: true, type: String },\n },\n { _id: false }, // Prevents Mongoose from creating an additional _id field for subdocuments\n);\n\nexport const relatedPostSchema = new MongooseSchema<SchemaRelatedPostType>(\n {\n postActive: { default: true, required: true, type: Boolean },\n postId: {\n ref: \"Post\",\n required: true,\n type: mongoose.Schema.Types.ObjectId,\n },\n postSlug: { required: true, type: String },\n postType: {\n enum: Object.values(EnumPostType),\n required: true,\n type: String,\n },\n },\n { _id: false }, // Prevents Mongoose from creating an additional _id field for subdocuments\n);\n\nexport const socialShareResourceSchema =\n new MongooseSchema<SocialShareResourceType>(\n {\n qrCode: { required: true, type: ResourceImageTypeSchema },\n socialImage: { required: true, type: ResourceImageTypeSchema },\n },\n { _id: false }, // Prevents Mongoose from creating an additional _id field for subdocuments\n );\n\nexport const baseResourceFields = {\n active: { default: false, required: true, type: Boolean },\n adIds: {\n ref: \"Ad\",\n required: false,\n type: [mongoose.Schema.Types.ObjectId],\n },\n approvedAt: { default: null, required: false, type: Date },\n contactDetails: { required: false, type: ContactDetailsSchema },\n cover: {\n required: true,\n type: ResourceImageTypeSchema,\n },\n deletedAt: { default: null, required: false, type: Date },\n description: { required: true, type: String },\n images: { required: false, type: [ResourceImageTypeSchema] },\n logo: { required: false, type: ResourceImageTypeSchema },\n name: { required: true, type: String },\n owner: {\n required: true,\n type: OwnerTypeSchema,\n },\n posterUsage: { required: false, type: PosterUsageTypeSchema },\n promoCodes: { required: false, type: [String] },\n rating: { required: false, type: Number },\n region: { required: true, type: String },\n relatedPost: { required: false, type: relatedPostSchema },\n reviewCount: { required: false, type: Number },\n sharePublic: { required: false, type: socialShareResourceSchema },\n slug: { required: true, type: String },\n socialMedia: { required: false, type: [SocialMediaTypeSchema] },\n termsAgreement: { required: true, type: termsAgreementSchema },\n};\n","import {\n EnumEventType,\n GoogleAddressComponent,\n GoogleImportedMarket,\n} from \"@timardex/cluemart-shared\";\nimport mongoose from \"mongoose\";\n\nimport {\n dateTimeSchema,\n locationsSchema,\n ResourceImageTypeSchema,\n} from \"./global\";\nimport { searchNamePlugin } from \"./searchNamePlugin\";\n\nexport type SchemaGoogleImportedMarket = Omit<\n GoogleImportedMarket,\n \"eventId\" | \"claimedByUserId\"\n> & {\n eventId?: mongoose.Types.ObjectId;\n claimedByUserId?: mongoose.Types.ObjectId;\n /** Lowercase `name` mirror for prefix type-ahead (see searchNamePlugin). */\n searchName?: string;\n /** Indexed earliest `dateTime` start instant for chronological pagination. */\n earliestStartDate?: Date | null;\n};\n\nconst MongooseSchema = mongoose.Schema;\n\nconst addressComponentSchema = new MongooseSchema<GoogleAddressComponent>(\n {\n longName: { required: false, type: String },\n shortName: { required: false, type: String },\n types: { required: false, type: [String] },\n },\n { _id: false },\n);\n\n/**\n * This is the schema for the GoogleImportedMarket type.\n * It is used to define the structure of the GoogleImportedMarket type in the database.\n * The schema is used by Mongoose to create a model for the GoogleImportedMarket type.\n */\nconst schema = new MongooseSchema<SchemaGoogleImportedMarket>(\n {\n active: { default: false, required: true, type: Boolean },\n address: { required: true, type: String },\n addressComponents: { required: false, type: [addressComponentSchema] },\n approvedAt: { default: null, required: false, type: Date },\n businessStatus: { required: false, type: String },\n claimed: { default: false, required: true, type: Boolean },\n claimedAt: { default: null, required: false, type: Date },\n claimedByUserId: {\n ref: \"User\",\n required: false,\n type: mongoose.Schema.Types.ObjectId,\n },\n cover: {\n required: false,\n type: ResourceImageTypeSchema,\n },\n dateTime: [dateTimeSchema],\n deletedAt: { default: null, required: false, type: Date },\n description: { required: true, type: String },\n earliestStartDate: { default: null, required: false, type: Date },\n eventId: {\n ref: \"Event\",\n required: false,\n type: mongoose.Schema.Types.ObjectId,\n },\n eventType: {\n enum: Object.values(EnumEventType),\n required: true,\n type: String,\n },\n googleMapsUrl: { required: false, type: String },\n googlePlaceId: {\n required: true,\n type: String,\n unique: true, // unique, indexed\n },\n images: { required: false, type: [ResourceImageTypeSchema] }, // array of photo_reference\n importedAt: { default: () => new Date(), required: true, type: Date },\n location: {\n required: true, // optional because lat/lng may expire after 30 days\n type: locationsSchema,\n },\n logo: { required: false, type: ResourceImageTypeSchema },\n name: { required: true, type: String },\n openingHours: { required: false, type: [String] },\n rainOrShine: { required: true, type: Boolean },\n rating: { required: false, type: Number },\n region: { required: false, type: String },\n reviewCount: { required: false, type: Number },\n slug: { required: true, type: String },\n website: { required: false, type: String },\n },\n { timestamps: true },\n);\n\n// Indexes for search, geo, soft-delete, and dateTime status queries.\nschema.index({ \"location.geo\": \"2dsphere\" });\nschema.index({ name: 1 });\nschema.index({ region: 1 });\nschema.index({ deletedAt: 1 });\nschema.index({ \"dateTime.dateStatus\": 1 });\n// eslint-disable-next-line sort-keys\nschema.index({ earliestStartDate: 1, _id: 1 });\nschema.index({ slug: 1 });\n\n// Full-text search across name/description (see eventsSearch google branch).\nschema.index({ description: \"text\", name: \"text\" });\n\nschema.plugin(searchNamePlugin);\n\nexport const GoogleImportedMarketModel =\n (mongoose.models\n .GoogleImportedMarket as mongoose.Model<SchemaGoogleImportedMarket>) ||\n mongoose.model<SchemaGoogleImportedMarket>(\"GoogleImportedMarket\", schema);\n","import mongoose from \"mongoose\";\n\n/**\n * Derives the lowercase prefix mirror used for type-ahead search.\n * `name` is required on every searchable resource, so a missing/blank name\n * yields \"\".\n */\nexport function deriveSearchName(name: unknown): string {\n return typeof name === \"string\" ? name.trim().toLowerCase() : \"\";\n}\n\n/**\n * Returns a copy of a Mongo update with `searchName` synced from `name`, or\n * `null` when the update has no string `name` to derive from. Supports the\n * three update shapes: `$set` operator objects, direct field replacement\n * (`{ name: \"x\" }`), and aggregation-pipeline arrays (`[{ $set: ... }]`).\n */\nfunction syncSearchNameInUpdate(update: unknown): any {\n if (Array.isArray(update)) {\n let changed = false;\n const next = update.map((stage) => {\n if (!stage || typeof stage !== \"object\") {\n return stage;\n }\n const $set = (stage as { $set?: Record<string, unknown> }).$set;\n const name = $set && typeof $set.name === \"string\" ? $set.name : null;\n // In an aggregation pipeline, a string starting with `$` is a field-path\n // expression, not a literal value. The computed name isn't known here, so\n // leave `searchName` alone rather than desynchronizing it from `name`.\n if (!name || name.startsWith(\"$\")) {\n return stage;\n }\n changed = true;\n return {\n ...(stage as Record<string, unknown>),\n $set: { ...$set, searchName: deriveSearchName(name) },\n };\n });\n return changed ? next : null;\n }\n\n if (!update || typeof update !== \"object\") {\n return null;\n }\n\n const obj = update as Record<string, unknown>;\n const $set = obj.$set;\n\n if ($set && typeof $set === \"object\" && !Array.isArray($set)) {\n const setObj = $set as Record<string, unknown>;\n if (typeof setObj.name === \"string\") {\n return {\n ...obj,\n $set: { ...setObj, searchName: deriveSearchName(setObj.name) },\n };\n }\n return null;\n }\n\n // Direct field replacement (no operator prefix): Mongoose casts top-level\n // non-operator keys into `$set`, so mirror `searchName` at the same level.\n if (typeof obj.name === \"string\") {\n return { ...obj, searchName: deriveSearchName(obj.name) };\n }\n\n return null;\n}\n\n/**\n * Mongoose schema plugin that keeps `searchName` (lowercase `name`) in sync\n * with `name` and indexes it for anchored prefix queries.\n *\n * Why: MongoDB `$text` matches whole, stemmed words — partial terms like \"cof\"\n * no longer match \"coffee\". Search resolvers OR an anchored\n * `{ searchName: /^term/ }` clause together with their `$text` clause so\n * type-ahead prefix matching keeps working, backed by the regular\n * `{ searchName: 1 }` index (case-sensitive regex + pre-lowercased field).\n *\n * Coverage: `save`, `insertMany`, `bulkWrite` (insertOne/replaceOne documents\n * and updateOne/updateMany updates in `$set`, direct-field, and pipeline\n * forms), `findOneAndUpdate`, `updateOne`, and `updateMany` are kept in sync.\n */\nexport function searchNamePlugin(schema: mongoose.Schema): void {\n schema.add({ searchName: { default: \"\", required: false, type: String } });\n schema.index({ searchName: 1 });\n\n schema.pre(\"save\", function syncSearchNameOnSave(next) {\n const doc = this as unknown as { name?: string; searchName?: string };\n doc.searchName = deriveSearchName(doc.name);\n next();\n });\n\n schema.pre(\"insertMany\", function syncSearchNameOnInsertMany(next, docs) {\n const list = Array.isArray(docs) ? docs : [docs];\n for (const doc of list as Array<{ name?: string; searchName?: string }>) {\n if (doc && typeof doc.name === \"string\") {\n doc.searchName = deriveSearchName(doc.name);\n }\n }\n next();\n });\n\n schema.pre(\"bulkWrite\", function syncSearchNameOnBulkWrite(next, ops) {\n for (const op of ops as Array<Record<string, any>>) {\n const doc = op.insertOne?.document ?? op.replaceOne?.replacement;\n if (doc && typeof doc.name === \"string\") {\n doc.searchName = deriveSearchName(doc.name);\n }\n\n for (const key of [\"updateOne\", \"updateMany\"] as const) {\n const update = op[key]?.update;\n if (update === undefined) {\n continue;\n }\n const synced = syncSearchNameInUpdate(update);\n if (synced !== null) {\n op[key].update = synced;\n }\n }\n }\n next();\n });\n\n const syncSearchNameOnUpdate = function (\n this: mongoose.Query<unknown, unknown>,\n next: () => void,\n ) {\n const synced = syncSearchNameInUpdate(this.getUpdate());\n if (synced !== null) {\n this.setUpdate(synced);\n }\n next();\n };\n\n schema.pre(\n [\"findOneAndUpdate\", \"updateOne\", \"updateMany\"],\n syncSearchNameOnUpdate,\n );\n}\n","import {\n AiImportedMarket,\n EnumEventType,\n EnumImportedMarketDeactivationReason,\n EnumImportedMarketReviewStatus,\n GoogleAddressComponent,\n} from \"@timardex/cluemart-shared\";\nimport mongoose from \"mongoose\";\n\nimport {\n dateTimeSchema,\n locationsSchema,\n ResourceImageTypeSchema,\n} from \"./global\";\nimport { searchNamePlugin } from \"./searchNamePlugin\";\n\nexport type SchemaAiImportedMarket = Omit<\n AiImportedMarket,\n \"eventId\" | \"claimedByUserId\" | \"reviewedByUserId\"\n> & {\n eventId?: mongoose.Types.ObjectId;\n claimedByUserId?: mongoose.Types.ObjectId;\n reviewedByUserId?: mongoose.Types.ObjectId;\n /** Lowercase `name` mirror for prefix type-ahead (see searchNamePlugin). */\n searchName?: string;\n /** Indexed earliest `dateTime` start instant for chronological pagination. */\n earliestStartDate?: Date | null;\n /** Set to the run timestamp each time the market appears on its source. */\n lastSeenAt?: Date | null;\n /** Consecutive successful runs where the market did not appear. */\n missedRuns?: number;\n /** Hash of the raw model description used to skip unchanged re-rewrites. */\n descriptionSourceHash?: string | null;\n /** Why an active market was deactivated (null while active). */\n deactivatedReason?: EnumImportedMarketDeactivationReason | null;\n /** sourceKey of an existing AI market this one may duplicate (soft flag). */\n duplicateHint?: string | null;\n};\n\nconst MongooseSchema = mongoose.Schema;\n\nconst addressComponentSchema = new MongooseSchema<GoogleAddressComponent>(\n {\n longName: { required: false, type: String },\n shortName: { required: false, type: String },\n types: { required: false, type: [String] },\n },\n { _id: false },\n);\n\n/**\n * Schema for AI-imported markets (scraped from admin-defined websites via the\n * DeepSeek API). Mirrors GoogleImportedMarket so approved markets can ride the\n * same combined read paths, but adds review/provenance fields and uses\n * `sourceKey` as the unique dedupe key instead of `googlePlaceId`.\n */\nconst schema = new MongooseSchema<SchemaAiImportedMarket>(\n {\n active: { default: false, required: true, type: Boolean },\n address: { required: true, type: String },\n addressComponents: { required: false, type: [addressComponentSchema] },\n approvedAt: { default: null, required: false, type: Date },\n claimed: { default: false, required: true, type: Boolean },\n claimedAt: { default: null, required: false, type: Date },\n claimedByUserId: {\n ref: \"User\",\n required: false,\n type: mongoose.Schema.Types.ObjectId,\n },\n cover: {\n required: false,\n type: ResourceImageTypeSchema,\n },\n dateTime: [dateTimeSchema],\n deactivatedReason: {\n enum: Object.values(EnumImportedMarketDeactivationReason),\n required: false,\n type: String,\n },\n deletedAt: { default: null, required: false, type: Date },\n description: { required: true, type: String },\n descriptionSourceHash: { required: false, type: String },\n duplicateHint: { required: false, type: String },\n earliestStartDate: { default: null, required: false, type: Date },\n eventId: {\n ref: \"Event\",\n required: false,\n type: mongoose.Schema.Types.ObjectId,\n },\n eventType: {\n enum: Object.values(EnumEventType),\n required: true,\n type: String,\n },\n images: { required: false, type: [ResourceImageTypeSchema] },\n lastSeenAt: { default: null, required: false, type: Date },\n location: {\n required: true,\n type: locationsSchema,\n },\n logo: { required: false, type: ResourceImageTypeSchema },\n missedRuns: { default: 0, required: true, type: Number },\n name: { required: true, type: String },\n openingHours: { required: false, type: [String] },\n rainOrShine: { required: true, type: Boolean },\n rating: { required: false, type: Number },\n region: { required: false, type: String },\n rejectReason: { required: false, type: String },\n reviewCount: { required: false, type: Number },\n reviewedAt: { default: null, required: false, type: Date },\n reviewedByUserId: {\n ref: \"User\",\n required: false,\n type: mongoose.Schema.Types.ObjectId,\n },\n reviewStatus: {\n default: EnumImportedMarketReviewStatus.PENDING,\n enum: Object.values(EnumImportedMarketReviewStatus),\n required: true,\n type: String,\n },\n scrapedAt: { default: () => new Date(), required: true, type: Date },\n slug: { required: true, type: String },\n sourceKey: {\n required: true,\n type: String,\n unique: true, // unique, indexed\n },\n sourceName: { required: true, type: String },\n sourceUrl: { required: true, type: String },\n tags: { required: false, type: [String] },\n website: { required: false, type: String },\n },\n { timestamps: true },\n);\n\n// Indexes for search, geo, soft-delete, review, and dateTime status queries.\nschema.index({ \"location.geo\": \"2dsphere\" });\nschema.index({ name: 1 });\nschema.index({ region: 1 });\nschema.index({ deletedAt: 1 });\nschema.index({ \"dateTime.dateStatus\": 1 });\n// eslint-disable-next-line sort-keys\nschema.index({ earliestStartDate: 1, _id: 1 });\n// Public list reads filter reviewStatus + active (and region) and sort by\n// earliestStartDate; these compounds keep those scans index-backed as the\n// collection grows.\n// eslint-disable-next-line sort-keys\nschema.index({ reviewStatus: 1, active: 1, earliestStartDate: 1, _id: 1 });\n/* eslint-disable sort-keys -- index key order is semantic */\nschema.index({\n region: 1,\n reviewStatus: 1,\n active: 1,\n earliestStartDate: 1,\n _id: 1,\n});\n/* eslint-enable sort-keys */\n// `{ region, searchName }` is intentionally NOT unique: two different markets\n// can legitimately share a name within a region (e.g. two \"Farmers Market\"s\n// in different suburbs). Cross-source duplicates are flagged softly for admin\n// review instead of enforced by a hard index (see scrapeConfiguredSites).\nschema.index({ region: 1, searchName: 1 });\nschema.index({ slug: 1 });\nschema.index({ reviewStatus: 1 });\n\n// Full-text search across name/description (see eventsSearch ai branch).\nschema.index({ description: \"text\", name: \"text\" });\n\nschema.plugin(searchNamePlugin);\n\nexport const AiImportedMarketModel =\n (mongoose.models\n .AiImportedMarket as mongoose.Model<SchemaAiImportedMarket>) ||\n mongoose.model<SchemaAiImportedMarket>(\"AiImportedMarket\", schema);\n","import {\n AiImportUsage,\n EnumAiImportRunStatus,\n} from \"@timardex/cluemart-shared\";\nimport mongoose from \"mongoose\";\n\nconst MongooseSchema = mongoose.Schema;\n\nexport type AiImportRunStatus = EnumAiImportRunStatus;\n\nexport type AiImportSiteResult = {\n errors: number;\n found: number;\n imported: number;\n name: string;\n skipped: number;\n status: EnumAiImportRunStatus.SUCCESS | EnumAiImportRunStatus.ERROR;\n usage: AiImportUsage;\n url: string;\n};\n\nexport type SchemaAiImportRun = {\n _id: mongoose.Types.ObjectId;\n createdAt: Date;\n updatedAt: Date;\n error?: string | null;\n finishedAt?: Date | null;\n result?: {\n errors: number;\n totalFound: number;\n totalImported: number;\n totalSkipped: number;\n } | null;\n siteResults: AiImportSiteResult[];\n startedAt: Date;\n status: AiImportRunStatus;\n triggeredByUserId?: mongoose.Types.ObjectId | null;\n usage?: AiImportUsage | null;\n};\n\nconst usageSchema = new MongooseSchema<AiImportUsage>(\n {\n completionTokens: { default: 0, required: true, type: Number },\n promptTokens: { default: 0, required: true, type: Number },\n totalTokens: { default: 0, required: true, type: Number },\n },\n { _id: false },\n);\n\nconst siteResultSchema = new MongooseSchema<AiImportSiteResult>(\n {\n errors: { default: 0, required: true, type: Number },\n found: { default: 0, required: true, type: Number },\n imported: { default: 0, required: true, type: Number },\n name: { required: true, type: String },\n skipped: { default: 0, required: true, type: Number },\n status: {\n enum: [EnumAiImportRunStatus.SUCCESS, EnumAiImportRunStatus.ERROR],\n required: true,\n type: String,\n },\n url: { required: true, type: String },\n usage: { required: true, type: usageSchema },\n },\n { _id: false, suppressReservedKeysWarning: true },\n);\n\nconst resultSchema = new MongooseSchema(\n {\n errors: { default: 0, required: true, type: Number },\n totalFound: { default: 0, required: true, type: Number },\n totalImported: { default: 0, required: true, type: Number },\n totalSkipped: { default: 0, required: true, type: Number },\n },\n { _id: false, suppressReservedKeysWarning: true },\n);\n\nconst schema = new MongooseSchema<SchemaAiImportRun>(\n {\n error: { required: false, type: String },\n finishedAt: { required: false, type: Date },\n result: { required: false, type: resultSchema },\n siteResults: { default: [], required: true, type: [siteResultSchema] },\n startedAt: { default: () => new Date(), required: true, type: Date },\n status: {\n default: EnumAiImportRunStatus.PENDING,\n enum: Object.values(EnumAiImportRunStatus),\n required: true,\n type: String,\n },\n triggeredByUserId: {\n ref: \"User\",\n required: false,\n type: mongoose.Schema.Types.ObjectId,\n },\n usage: { required: false, type: usageSchema },\n },\n { timestamps: true },\n);\n\nschema.index({ createdAt: -1 });\n\nexport const AiImportRunModel =\n (mongoose.models.AiImportRun as mongoose.Model<SchemaAiImportRun>) ||\n mongoose.model<SchemaAiImportRun>(\"AiImportRun\", schema);\n","import mongoose from \"mongoose\";\n\n/** Fixed `_id` of the single-document lock guarding AI import runs. */\nexport const AI_IMPORT_RUN_LOCK_KEY = \"ai-import-run\";\n\nconst MongooseSchema = mongoose.Schema;\n\nconst schema = new MongooseSchema(\n {\n _id: { required: true, type: String },\n lockedAt: { required: false, type: Date },\n token: { required: false, type: String },\n },\n { timestamps: true },\n);\n\nexport const AiImportRunLockModel =\n (mongoose.models.AiImportRunLock as mongoose.Model<{\n _id: string;\n lockedAt?: Date | null;\n token?: string | null;\n }>) || mongoose.model(\"AiImportRunLock\", schema);\n","import { ScrapeSite } from \"@timardex/cluemart-shared\";\nimport mongoose from \"mongoose\";\n\n/**\n * Fixed `_id` of the single-document AI scrape-site config. Using `_id`\n * (rather than a free-form `key` field) makes the singleton structural: the\n * collection can only ever contain one configuration document.\n */\nexport const SCRAPE_SITES_CONFIG_ID = \"scrapeSites\";\n\nconst MongooseSchema = mongoose.Schema;\n\ntype SchemaScrapeSiteItem = Omit<ScrapeSite, \"_id\" | \"createdAt\" | \"updatedAt\">;\n\ntype SchemaScrapeSiteConfig = {\n _id: string;\n sites: Array<SchemaScrapeSiteItem & { _id: mongoose.Types.ObjectId }>;\n updatedByUserId?: mongoose.Types.ObjectId;\n};\n\nconst scrapeSiteItemSchema = new MongooseSchema<SchemaScrapeSiteItem>(\n {\n enabled: { default: true, required: true, type: Boolean },\n lastCount: { required: false, type: Number },\n lastError: { required: false, type: String },\n lastScrapedAt: { required: false, type: Date },\n lastScrapeStatus: { required: false, type: String },\n name: { required: true, type: String },\n regionHint: { required: false, type: String },\n url: { required: true, type: String },\n },\n { timestamps: true },\n);\n\n/**\n * Single-document store for the admin-managed AI scrape-site list, keyed by\n * `_id === SCRAPE_SITES_CONFIG_ID`. Keeping the whole list in one document\n * makes replacement a single atomic `$set` (the local MongoDB deployment is\n * standalone, so multi-document transactions are not available).\n */\nconst configSchema = new MongooseSchema<SchemaScrapeSiteConfig>(\n {\n _id: { required: true, type: String },\n sites: {\n default: [],\n required: true,\n type: [scrapeSiteItemSchema],\n },\n updatedByUserId: {\n ref: \"User\",\n required: false,\n type: mongoose.Schema.Types.ObjectId,\n },\n },\n { timestamps: true },\n);\n\nexport const ScrapeSiteConfigModel =\n (mongoose.models\n .ScrapeSiteConfig as mongoose.Model<SchemaScrapeSiteConfig>) ||\n mongoose.model<SchemaScrapeSiteConfig>(\"ScrapeSiteConfig\", configSchema);\n","import {\n CreateBulkNotificationInput,\n NotificationType,\n EnumNotificationResourceType,\n EnumNotificationType,\n} from \"@timardex/cluemart-shared\";\nimport mongoose from \"mongoose\";\n\nimport { ObjectId } from \"src/types\";\n\nconst MongooseSchema = mongoose.Schema;\n\nconst notificationDataSchema = new MongooseSchema(\n {\n resourceId: { required: true, type: String },\n resourceName: { required: true, type: String },\n resourceType: {\n enum: Object.values(EnumNotificationResourceType),\n required: true,\n type: String,\n },\n },\n { _id: false },\n);\n\nexport type SchemaCreateBulkNotificationInput = Omit<\n CreateBulkNotificationInput,\n \"userIds\"\n> & {\n userIds: ObjectId[];\n};\n\nexport type SchemaNotificationType = Omit<NotificationType, \"userId\"> & {\n userId: ObjectId;\n};\n/**\n * Schema for storing in-app notifications\n * Each notification is tied to a specific user and can be marked as read/unread\n */\nconst schema = new MongooseSchema<SchemaNotificationType>(\n {\n data: {\n default: null,\n required: false,\n type: notificationDataSchema,\n },\n isRead: { default: false, index: true, required: true, type: Boolean },\n message: { required: true, type: String },\n title: { required: true, type: String },\n type: {\n default: EnumNotificationType.SYSTEM,\n enum: Object.values(EnumNotificationType),\n required: true,\n type: String,\n },\n userId: {\n ref: \"User\",\n required: true,\n type: mongoose.Schema.Types.ObjectId,\n },\n },\n { timestamps: true },\n);\n\n// Compound index for efficient queries\nschema.index({ isRead: 1, userId: 1 });\nschema.index({ createdAt: -1, userId: 1 });\n\nexport const NotificationModel =\n (mongoose.models.Notification as mongoose.Model<SchemaNotificationType>) ||\n mongoose.model<SchemaNotificationType>(\"Notification\", schema);\n","import { PushTokenType } from \"@timardex/cluemart-shared\";\nimport { EnumOSPlatform } from \"@timardex/cluemart-shared/enums\";\nimport mongoose from \"mongoose\";\n\nimport { ObjectId } from \"src/types\";\n\nconst MongooseSchema = mongoose.Schema;\n\nexport type SchemaPushTokenType = Omit<PushTokenType, \"userId\"> & {\n userId: ObjectId;\n};\n\n/**\n * This is the schema for the push token type.\n * It is used to define the structure of the push token type in the database.\n * The schema is used by Mongoose to create a model for the push token type.\n */\nconst schema = new MongooseSchema<SchemaPushTokenType>(\n {\n platform: {\n enum: Object.values(EnumOSPlatform),\n required: true,\n type: String,\n },\n token: { required: true, type: String },\n userId: {\n ref: \"User\",\n required: true,\n type: mongoose.Schema.Types.ObjectId,\n },\n },\n { timestamps: true },\n);\n\nexport const PushTokenModel =\n (mongoose.models.PushToken as mongoose.Model<SchemaPushTokenType>) ||\n mongoose.model<SchemaPushTokenType>(\"PushToken\", schema);\n","import {\n EnumEventDateStatus,\n EnumInviteStatus,\n EnumRelationResource,\n EnumResourceType,\n RelationDate,\n RelationType,\n} from \"@timardex/cluemart-shared\";\nimport mongoose from \"mongoose\";\n\nimport { ObjectId } from \"src/types\";\n\nimport { StallTypeSchema } from \"./event/EventInfo\";\n\nconst MongooseSchema = mongoose.Schema;\n\nconst relationDateTimeSchema = new MongooseSchema<RelationDate[\"dateTime\"]>(\n {\n dateStatus: {\n enum: Object.values(EnumEventDateStatus),\n required: true,\n type: String,\n },\n endDate: { required: true, type: String },\n endTime: { required: true, type: String },\n stallType: StallTypeSchema,\n startDate: { required: true, type: String },\n startTime: { required: true, type: String },\n },\n { _id: false },\n);\n\nexport const relationDatesSchema = new MongooseSchema<RelationDate>(\n {\n dateTime: {\n required: true,\n type: relationDateTimeSchema,\n },\n lastUpdateBy: {\n resourceId: { required: false, type: String },\n userEmail: { required: false, type: String },\n },\n paymentReference: { required: false, type: String },\n status: {\n enum: Object.values(EnumInviteStatus),\n required: false,\n type: String,\n },\n },\n { _id: false },\n);\n\nexport type SchemaRelationType = Omit<\n RelationType,\n \"eventId\" | \"vendorId\" | \"chatId\"\n> & {\n eventId: ObjectId;\n vendorId: ObjectId;\n chatId: ObjectId;\n};\n/**\n * This is the schema for the relation type.\n * It is used to define the structure of the relation type in the database.\n * The schema is used by Mongoose to create a model for the relation type.\n */\nexport const RelationTypeSchema = new MongooseSchema<SchemaRelationType>(\n {\n active: { default: true, required: true, type: Boolean },\n chatId: {\n ref: \"Chat\",\n required: true,\n type: mongoose.Schema.Types.ObjectId,\n },\n deletedAt: { default: null, required: false, type: Date },\n eventId: {\n ref: \"Event\",\n required: true,\n type: mongoose.Schema.Types.ObjectId,\n },\n lastUpdateBy: {\n enum: Object.values(EnumResourceType),\n required: true,\n type: String,\n },\n relationDates: [relationDatesSchema],\n relationType: {\n enum: Object.values(EnumRelationResource),\n required: true,\n type: String,\n },\n vendorId: {\n ref: \"Vendor\",\n required: true,\n type: mongoose.Schema.Types.ObjectId,\n },\n },\n { timestamps: true },\n);\n\nRelationTypeSchema.index({\n eventId: 1,\n \"relationDates.startDate\": 1,\n \"relationDates.startTime\": 1,\n \"relationDates.status\": 1,\n vendorId: 1,\n});\n\n// --- IMPORTANT: bind custom model type ---\nexport const RelationModel =\n (mongoose.models.Relation as mongoose.Model<SchemaRelationType>) ||\n mongoose.model<SchemaRelationType>(\"Relation\", RelationTypeSchema);\n","import {\n DateTimeWithPriceType,\n EnumEventDateStatus,\n EnumPaymentMethod,\n EventInfoType,\n PaymentInfoType,\n RefundPolicy,\n Requirement,\n StallType,\n} from \"@timardex/cluemart-shared\";\nimport mongoose from \"mongoose\";\n\nimport { ObjectId } from \"src/types\";\n\nconst MongooseSchema = mongoose.Schema;\n\nexport const StallTypeSchema = new MongooseSchema<StallType>(\n {\n label: { required: false, type: String },\n price: { required: false, type: Number },\n stallCapacity: { required: false, type: Number },\n },\n {\n _id: false, // Prevents Mongoose from creating an additional _id field for subdocuments\n },\n);\n\nconst dateTimeSchema = new MongooseSchema<DateTimeWithPriceType>(\n {\n dateStatus: {\n enum: Object.values(EnumEventDateStatus),\n required: false,\n type: String,\n },\n endDate: { required: true, type: String },\n endTime: { required: true, type: String },\n stallTypes: [StallTypeSchema],\n startDate: { required: true, type: String },\n startTime: { required: true, type: String },\n },\n { _id: false }, // Prevents Mongoose from creating an additional _id field for subdocuments\n);\n\nconst paymentInfoSchema = new MongooseSchema<PaymentInfoType>(\n {\n accountHolderName: { required: false, type: String },\n accountNumber: { required: false, type: String },\n link: { required: false, type: String },\n paymentMethod: {\n enum: Object.values(EnumPaymentMethod),\n required: true,\n type: String,\n },\n },\n { _id: false }, // Prevents Mongoose from creating an additional _id field\n);\n\nconst requirementsSchema = new MongooseSchema<Requirement>(\n {\n category: { required: true, type: String },\n label: { required: true, type: String },\n value: { required: true, type: Boolean },\n },\n {\n _id: false, // Prevents Mongoose from creating an additional _id field for\n },\n);\n\nexport const refundPolicySchema = new MongooseSchema<RefundPolicy>(\n {\n category: { required: true, type: String },\n label: { required: true, type: String },\n value: { required: true, type: Boolean },\n },\n { _id: false },\n);\n\nexport type SchemaEventInfoType = Omit<EventInfoType, \"eventId\"> & {\n eventId: ObjectId;\n};\n\n/**\n * This is the schema for the event info type.\n * It is used to define the structure of the event info type in the database.\n * The schema is used by Mongoose to create a model for the event info type.\n */\nconst schema = new MongooseSchema<SchemaEventInfoType>(\n {\n active: { default: true, type: Boolean },\n applicationDeadlineHours: { required: true, type: Number },\n dateTime: { required: true, type: [dateTimeSchema] },\n eventId: {\n ref: \"Event\",\n required: true,\n type: mongoose.Schema.Types.ObjectId,\n },\n packInTime: { required: true, type: Number },\n paymentDueHours: { required: true, type: Number },\n paymentInfo: { required: true, type: [paymentInfoSchema] },\n refundPolicy: { required: true, type: [refundPolicySchema] },\n requirements: { required: false, type: [requirementsSchema] },\n },\n { timestamps: true },\n);\n\n// Serves `getEventInfo` / `createRelation` / relation resolvers / user deletion:\n// every read/write is `findOne({ eventId })` equality.\nschema.index({ eventId: 1 });\n\nexport const EventInfoModel =\n (mongoose.models.EventInfo as mongoose.Model<SchemaEventInfoType>) ||\n mongoose.model<SchemaEventInfoType>(\"EventInfo\", schema);\n","import {\n EnumActivity,\n EnumEventDateStatus,\n EnumOSPlatform,\n EnumResourceType,\n ResourceActivityEntry,\n ResourceActivityType,\n} from \"@timardex/cluemart-shared\";\nimport mongoose from \"mongoose\";\n\nimport { locationGeoSchema } from \"./global\";\n\nconst MongooseSchema = mongoose.Schema;\n\nconst ActivitySchema = new MongooseSchema<ResourceActivityEntry>(\n {\n activityType: {\n enum: Object.values(EnumActivity),\n required: true,\n type: String,\n },\n dateStatus: {\n enum: Object.values(EnumEventDateStatus),\n required: false,\n type: String,\n },\n location: {\n required: false,\n type: locationGeoSchema,\n },\n startDate: { required: false, type: String },\n startTime: { required: false, type: String },\n timestamp: { default: Date.now, type: Date },\n userAgent: {\n enum: Object.values(EnumOSPlatform),\n required: true,\n type: String,\n },\n userId: { required: false, type: String },\n },\n { _id: false },\n);\n\nconst schema = new MongooseSchema<ResourceActivityType>(\n {\n activity: { default: [], type: [ActivitySchema] },\n resourceId: { required: true, type: String },\n resourceType: {\n enum: Object.values(EnumResourceType),\n required: true,\n type: String,\n },\n },\n { timestamps: true },\n);\n\nschema.index({ resourceId: 1, resourceType: 1 }, { unique: true }); // one per entity\nschema.index({ \"views.location\": \"2dsphere\" });\n\nexport const ResourceActivityModel =\n (mongoose.models.ResourceActivity as mongoose.Model<ResourceActivityType>) ||\n mongoose.model<ResourceActivityType>(\"ResourceActivity\", schema);\n","import {\n EnumBillingPeriod,\n EnumNotificationResourceType,\n EnumOSPlatform,\n EnumPointType,\n EnumResourceType,\n EnumReward,\n EnumSubscriptionStatus,\n EnumUserLicence,\n EnumUserRole,\n RedeemedReward,\n StripeSubscription,\n UserActivityEvent,\n UserOverallPointsEntry,\n UserType,\n} from \"@timardex/cluemart-shared\";\nimport mongoose from \"mongoose\";\n\nimport { ObjectId } from \"src/types\";\n\nimport {\n dateTimeSchema,\n locationsSchema,\n ResourceImageTypeSchema,\n termsAgreementSchema,\n userLicenseSchema,\n} from \"./global\";\n\nconst MongooseSchema = mongoose.Schema;\n\nexport type SchemaUserActivityEvent = Omit<UserActivityEvent, \"resourceId\"> & {\n resourceId: ObjectId;\n};\n\nexport type SchemaUserType = Omit<\n UserType,\n | \"vendor\"\n | \"coupon\"\n | \"events\"\n | \"partner\"\n | \"userActivity\"\n | \"_id\"\n | \"game\"\n | \"school\"\n | \"affiliate\"\n | \"permissions\"\n | \"stripe\"\n | \"totalOverallPoints\"\n> & {\n _id: ObjectId;\n affiliate: ObjectId;\n coupon: ObjectId;\n events: ObjectId[];\n game: ObjectId;\n partner: ObjectId;\n /** Server-only hashed refresh tokens; never exposed to clients. */\n refreshTokenAdmin?: string | null;\n refreshTokenMobile?: string | null;\n school: ObjectId;\n stripe?: SchemaStripeSubscription;\n vendor: ObjectId;\n userActivity: {\n favourites: {\n events: ObjectId[];\n vendors: ObjectId[];\n partners: ObjectId[];\n };\n interested: {\n events: SchemaUserActivityEvent[];\n };\n going: {\n events: SchemaUserActivityEvent[];\n };\n present: {\n events: SchemaUserActivityEvent[];\n };\n };\n};\n\nexport type SchemaStripeSubscription = StripeSubscription & {\n billingPeriod?: EnumBillingPeriod;\n cancelAtPeriodEnd?: boolean;\n paymentFailedAt?: Date;\n paymentGracePeriodEndsAt?: Date;\n paymentGraceSubscriptionId?: string;\n pendingBillingPeriod?: EnumBillingPeriod;\n pendingChangeEffectiveAt?: Date;\n pendingPlan?: EnumUserLicence;\n priceId?: string;\n scheduleId?: string;\n subscriptionMutationLockExpiresAt?: Date;\n subscriptionMutationLockId?: string;\n};\n\nconst userActivityEventSchema = new MongooseSchema<SchemaUserActivityEvent>(\n {\n dateTime: dateTimeSchema,\n resourceId: {\n ref: \"Event\",\n required: false,\n type: mongoose.Schema.Types.ObjectId,\n },\n },\n { _id: false },\n);\n\nconst userActivityFavouritesSchema = new MongooseSchema(\n {\n events: {\n ref: \"Event\",\n required: false,\n type: [mongoose.Schema.Types.ObjectId],\n },\n partners: {\n ref: \"Partner\",\n required: false,\n type: [mongoose.Schema.Types.ObjectId],\n },\n vendors: {\n ref: \"Vendor\",\n required: false,\n type: [mongoose.Schema.Types.ObjectId],\n },\n },\n { _id: false },\n);\n\nconst stripeSchema = new MongooseSchema<SchemaStripeSubscription>(\n {\n billingPeriod: {\n enum: Object.values(EnumBillingPeriod),\n required: false,\n type: String,\n },\n cancelAtPeriodEnd: {\n required: false,\n type: Boolean,\n },\n currentPlan: {\n enum: Object.values(EnumUserLicence),\n required: false,\n type: String,\n },\n customerId: {\n required: false,\n type: String,\n },\n endDate: {\n required: false,\n type: Date,\n },\n paymentFailedAt: {\n required: false,\n type: Date,\n },\n paymentGracePeriodEndsAt: {\n required: false,\n type: Date,\n },\n paymentGraceSubscriptionId: {\n required: false,\n type: String,\n },\n pendingBillingPeriod: {\n enum: Object.values(EnumBillingPeriod),\n required: false,\n type: String,\n },\n pendingChangeEffectiveAt: {\n required: false,\n type: Date,\n },\n pendingPlan: {\n enum: Object.values(EnumUserLicence),\n required: false,\n type: String,\n },\n priceId: {\n required: false,\n type: String,\n },\n scheduleId: {\n required: false,\n type: String,\n },\n startDate: {\n required: false,\n type: Date,\n },\n status: {\n enum: Object.values(EnumSubscriptionStatus),\n required: false,\n type: String,\n },\n subscriptionId: {\n required: false,\n type: String,\n },\n subscriptionMutationLockExpiresAt: {\n required: false,\n type: Date,\n },\n subscriptionMutationLockId: {\n required: false,\n type: String,\n },\n },\n { _id: false },\n);\n\nconst redeemedRewardSchema = new MongooseSchema<RedeemedReward>(\n {\n name: {\n enum: Object.values(EnumReward),\n required: true,\n type: String,\n },\n pointsUsed: { required: true, type: Number },\n redeemedAt: { required: true, type: Date },\n },\n { _id: false },\n);\n\nconst userOverallPointsSchema = new MongooseSchema<UserOverallPointsEntry>(\n {\n createdAt: { required: true, type: Date },\n points: { default: 0, required: true, type: Number },\n pointType: {\n enum: Object.values(EnumPointType),\n required: true,\n type: String,\n },\n sourceId: { required: false, type: String },\n },\n { _id: false },\n);\n\n/**\n * This is the schema for the user type.\n * It is used to define the structure of the user type in the database.\n * The schema is used by Mongoose to create a model for the user type.\n */\nconst schema = new MongooseSchema<SchemaUserType>(\n {\n active: { default: false, required: true, type: Boolean },\n affiliate: {\n ref: \"Affiliate\",\n required: false,\n type: mongoose.Schema.Types.ObjectId,\n },\n avatar: {\n required: false,\n type: ResourceImageTypeSchema,\n },\n coupon: {\n ref: \"Coupon\",\n required: false,\n type: mongoose.Schema.Types.ObjectId,\n },\n deletedAt: { default: null, required: false, type: Date },\n email: { required: true, type: String },\n emailSentFor: {\n enum: Object.values(EnumNotificationResourceType),\n required: false,\n type: [String],\n },\n events: {\n ref: \"Event\",\n required: false,\n type: [mongoose.Schema.Types.ObjectId],\n },\n firstName: { required: true, type: String },\n game: {\n ref: \"Game\",\n required: false,\n type: mongoose.Schema.Types.ObjectId,\n },\n interests: {\n enum: Object.values(EnumResourceType),\n required: false,\n type: [String],\n },\n isTester: { default: false, required: true, type: Boolean },\n lastName: { required: true, type: String },\n licences: {\n required: false,\n type: [userLicenseSchema],\n },\n location: {\n required: false,\n type: locationsSchema,\n },\n nickName: { required: false, type: String },\n overallPoints: {\n default: [],\n required: false,\n type: [userOverallPointsSchema],\n },\n partner: {\n ref: \"Partner\",\n required: false,\n type: mongoose.Schema.Types.ObjectId,\n },\n password: { required: true, type: String },\n platform: {\n enum: Object.values(EnumOSPlatform),\n required: false,\n type: String,\n },\n preferredRegion: {\n required: true,\n type: String,\n },\n promoCodes: {\n required: false,\n type: [String],\n },\n redeemedRewards: {\n required: false,\n type: [redeemedRewardSchema],\n },\n // Per-client slots: a mobile session and an in-app WebView admin session\n // coexist without rotating each other out.\n refreshTokenAdmin: {\n default: null,\n required: false,\n type: String,\n },\n refreshTokenMobile: {\n default: null,\n required: false,\n type: String,\n },\n roles: {\n default: [EnumUserRole.CUSTOMER],\n enum: Object.values(EnumUserRole),\n required: true,\n type: [String],\n },\n school: {\n ref: \"School\",\n required: false,\n type: mongoose.Schema.Types.ObjectId,\n },\n stripe: {\n required: false,\n type: stripeSchema,\n },\n termsAgreement: termsAgreementSchema,\n userActivity: {\n favourites: {\n default: () => ({ events: [], vendors: [] }),\n type: userActivityFavouritesSchema,\n },\n going: {\n events: [userActivityEventSchema],\n },\n interested: {\n events: [userActivityEventSchema],\n },\n present: {\n events: [userActivityEventSchema],\n },\n },\n vendor: {\n ref: \"Vendor\",\n required: false,\n type: mongoose.Schema.Types.ObjectId,\n },\n },\n { strict: false, timestamps: true },\n);\n\nschema.index({ \"licences.expiryDate\": 1 });\nschema.index({ \"licences.licenceType\": 1 });\n// Serves `usersByPromoCode` (`{ promoCodes: code }` — promoCodes is the only\n// predicate, so it must lead the index) and the school member list\n// (`{ active: true, deletedAt: null, promoCodes: { $in: [code] } }`, where all\n// three are equality/`$in` predicates and any field order is usable).\n/* eslint-disable-next-line sort-keys -- Compound-index field order controls promo-code lookups. */\nschema.index({ promoCodes: 1, active: 1, deletedAt: 1 });\n// Backs the super-admin `getUsers` search (`{ $text: { $search } }`) so the\n// search clause is served by an index instead of a collection scan. `$text`\n// matches whole, stemmed words — partial type-ahead would need a lowercase\n// mirror field, so keep this in mind before tightening search semantics.\nschema.index({ email: \"text\", firstName: \"text\", lastName: \"text\" });\n\nexport const UserModel =\n (mongoose.models.User as mongoose.Model<SchemaUserType>) ||\n mongoose.model<SchemaUserType>(\"User\", schema);\n","import mongoose from \"mongoose\";\n\nconst MongooseSchema = mongoose.Schema;\n\nexport interface VerificationTokenType {\n email: string;\n verificationToken: string;\n createdAt: Date;\n}\n\nconst schema = new MongooseSchema<VerificationTokenType>(\n {\n createdAt: {\n default: Date.now,\n expires: 24 * 60 * 60, // 24 hours in seconds (MongoDB TTL expects seconds)\n required: true,\n type: Date,\n }, // Token expires after 1 day\n email: { required: true, type: String },\n verificationToken: { required: true, type: String },\n },\n { timestamps: true },\n);\n\nexport const VerificationTokenModel =\n (mongoose.models\n .VerificationToken as mongoose.Model<VerificationTokenType>) ||\n mongoose.model<VerificationTokenType>(\"VerificationToken\", schema);\n","import {\n EnumEventDateStatus,\n EnumVendorType,\n VendorCalendarData,\n VendorProductList,\n VendorType,\n VendorDowngradeSnapshot,\n VendorAvailability,\n} from \"@timardex/cluemart-shared\";\nimport mongoose from \"mongoose\";\n\nimport { ObjectId } from \"src/types\";\n\nimport {\n baseResourceFields,\n CategorySchema,\n locationsSchema,\n SchemaOwnerType,\n socialShareResourceSchema,\n} from \"../global\";\nimport { searchNamePlugin } from \"../searchNamePlugin\";\n\nconst MongooseSchema = mongoose.Schema;\n\nexport const vendorProductTypeSchema = new MongooseSchema<VendorProductList>(\n {\n description: { required: false, type: String },\n name: { required: true, type: String },\n price: { required: true, type: Number },\n priceMax: { required: false, type: Number },\n priceUnit: { required: true, type: String },\n productGroups: { required: false, type: [String] },\n },\n { timestamps: true },\n);\n\nconst productWrapperSchema = new MongooseSchema<VendorType[\"products\"]>(\n {\n active: { default: false, required: false, type: Boolean },\n productsList: { required: false, type: [vendorProductTypeSchema] },\n },\n { _id: false },\n);\n\nconst calendarSchema = new MongooseSchema<VendorCalendarData>(\n {\n dateTime: {\n dateStatus: {\n enum: Object.values(EnumEventDateStatus),\n required: false,\n type: String,\n },\n endDate: { required: false, type: String },\n endTime: { required: false, type: String },\n startDate: { required: false, type: String },\n startTime: { required: false, type: String },\n },\n description: { required: false, type: String },\n location: {\n required: false,\n type: locationsSchema,\n },\n },\n { _id: false },\n);\n\nconst calendarWrapperSchema = new MongooseSchema<VendorType[\"calendar\"]>(\n {\n active: { default: false, required: true, type: Boolean },\n calendarData: { required: false, type: [calendarSchema] },\n },\n { _id: false },\n);\n\nconst vendorAvailabilitySchema = new MongooseSchema<VendorAvailability>(\n {\n corporate: { default: false, required: false, type: Boolean },\n private: { default: false, required: false, type: Boolean },\n school: { default: false, required: false, type: Boolean },\n },\n { _id: false },\n);\n\n/**\n * Snapshot of licence-gated fields captured when a vendor is downgraded to\n * STANDARD_VENDOR, used to restore the vendor's own configuration on a later\n * PRO upgrade (see downgradeVendorProFeatures / restoreVendorProFeatures).\n */\nconst downgradeSnapshotSchema = new MongooseSchema<VendorDowngradeSnapshot>(\n {\n availability: { required: false, type: vendorAvailabilitySchema },\n calendarActive: { required: false, type: Boolean },\n productsActive: { required: false, type: Boolean },\n },\n { _id: false },\n);\n\nexport type SchemaVendorType = Omit<\n VendorType,\n \"vendorInfoId\" | \"owner\" | \"adIds\" | \"unregisteredVendorId\"\n> & {\n adIds?: ObjectId[];\n /** Mirror of `categories[].name` for $text search (see vendorSearch). */\n categoriesNames?: string[];\n owner: SchemaOwnerType;\n /** Lowercase `name` mirror for prefix type-ahead (see searchNamePlugin). */\n searchName?: string;\n vendorInfoId: ObjectId;\n unregisteredVendorId?: ObjectId | null;\n};\n\nconst schema = new MongooseSchema<SchemaVendorType>(\n {\n ...baseResourceFields, // Importing base resource fields from global.ts\n availability: { required: false, type: vendorAvailabilitySchema },\n calendar: {\n required: false,\n type: calendarWrapperSchema,\n },\n categories: { required: true, type: [CategorySchema] },\n categoriesNames: { default: [], required: false, type: [String] },\n claimed: { default: true, required: false, type: Boolean },\n downgradeSnapshot: { required: false, type: downgradeSnapshotSchema },\n foodTruck: { required: true, type: Boolean },\n products: { required: false, type: productWrapperSchema },\n shareRelation: { required: false, type: socialShareResourceSchema },\n unregisteredVendorId: {\n ref: \"UnregisteredVendor\",\n required: false,\n type: mongoose.Schema.Types.ObjectId,\n },\n vendorInfoId: {\n ref: \"VendorInfo\",\n required: false,\n type: mongoose.Schema.Types.ObjectId,\n },\n vendorType: {\n enum: Object.values(EnumVendorType),\n required: true,\n type: String,\n },\n },\n { timestamps: true },\n);\n\n// 🔹 Add indexes to speed up regex-based searches\nschema.index({ name: 1 });\nschema.index({ description: 1 });\nschema.index({ region: 1 });\nschema.index({ \"categories.name\": 1 });\nschema.index({ slug: 1 });\n\n// Full-text search across name/description/categoriesNames (see vendorSearch).\nschema.index({\n categoriesNames: \"text\",\n description: \"text\",\n name: \"text\",\n});\n\n// Serves getUserVendors / ownedCoupons' Vendor lookups:\n// `{ deletedAt: null, \"owner.userId\": <id> }` (and ownedCoupons' additional\n// `active: true` is a residual filter).\nschema.index({ deletedAt: 1, \"owner.userId\": 1 });\n\nschema.plugin(searchNamePlugin);\n\nexport const VendorModel =\n (mongoose.models.Vendor as mongoose.Model<SchemaVendorType>) ||\n mongoose.model<SchemaVendorType>(\"Vendor\", schema);\n","import {\n EnumFoodFlavor,\n VendorAttributes,\n VendorInfoType,\n} from \"@timardex/cluemart-shared\";\nimport mongoose from \"mongoose\";\n\nimport { ObjectId } from \"src/types\";\n\nimport { ResourceImageTypeSchema } from \"../global\";\n\nconst MongooseSchema = mongoose.Schema;\n\nexport type SchemaVendorInfoType = Omit<VendorInfoType, \"vendorId\"> & {\n vendorId: ObjectId;\n};\n\nconst AttributesSchema = new MongooseSchema<VendorAttributes>(\n {\n details: { required: false, type: String },\n isRequired: { default: false, required: true, type: Boolean },\n },\n { _id: false },\n);\n\nconst schema = new MongooseSchema<SchemaVendorInfoType>(\n {\n active: { default: true, type: Boolean },\n compliance: {\n foodBeverageLicense: { default: false, required: false, type: Boolean },\n liabilityInsurance: { default: false, required: false, type: Boolean },\n },\n documents: [ResourceImageTypeSchema],\n product: {\n foodFlavors: {\n enum: Object.values(EnumFoodFlavor),\n required: true,\n type: [String],\n },\n packaging: { required: true, type: [String] },\n priceRange: {\n max: { required: true, type: String },\n min: { required: true, type: String },\n },\n producedIn: { required: true, type: [String] },\n },\n requirements: {\n electricity: AttributesSchema,\n gazebo: AttributesSchema,\n table: AttributesSchema,\n },\n stallInfo: {\n size: {\n depth: { required: true, type: String },\n width: { required: true, type: String },\n },\n },\n vendorId: {\n ref: \"Vendor\",\n required: true,\n type: mongoose.Schema.Types.ObjectId,\n },\n },\n { timestamps: true },\n);\n\n// Serves `getVendorInfo` / user deletion: `findOne({ vendorId })` equality.\nschema.index({ vendorId: 1 });\n\nexport const VendorInfoModel =\n (mongoose.models.VendorInfo as mongoose.Model<SchemaVendorInfoType>) ||\n mongoose.model<SchemaVendorInfoType>(\"VendorInfo\", schema);\n","import {\n UnregisteredVendorInvitationType,\n UnregisteredVendorType,\n} from \"@timardex/cluemart-shared\";\nimport mongoose from \"mongoose\";\n\nimport { ObjectId } from \"src/types\";\n\nimport { dateTimeSchema } from \"../global\";\n\nconst MongooseSchema = mongoose.Schema;\n\nexport type SchemaUnregisteredVendorInvitationType = Omit<\n UnregisteredVendorInvitationType,\n \"inviterId\"\n> & {\n inviterId: ObjectId;\n};\n\nexport type SchemaUnregisteredVendorType = Omit<\n UnregisteredVendorType,\n \"invitations\" | \"claimedByUserId\"\n> & {\n claimInitiatedAt?: Date | null;\n claimToken?: string | null;\n claimTokenExpiresAt?: Date | null;\n claimedByUserId?: mongoose.Types.ObjectId;\n invitations: SchemaUnregisteredVendorInvitationType[];\n};\n\nconst invitationSchema =\n new MongooseSchema<SchemaUnregisteredVendorInvitationType>(\n {\n dateTime: { required: true, type: [dateTimeSchema] },\n inviterId: {\n ref: \"Event\",\n required: true,\n type: mongoose.Schema.Types.ObjectId,\n },\n },\n { _id: false },\n );\n\nconst schema = new MongooseSchema<SchemaUnregisteredVendorType>(\n {\n active: { default: true, required: true, type: Boolean },\n categoryIds: { required: true, type: [String] },\n claimed: { default: false, required: true, type: Boolean },\n claimedAt: { default: null, required: false, type: Date },\n claimedByUserId: {\n ref: \"User\",\n required: false,\n type: mongoose.Schema.Types.ObjectId,\n },\n claimInitiatedAt: { default: null, required: false, type: Date },\n claimToken: { default: null, required: false, type: String },\n claimTokenExpiresAt: { default: null, required: false, type: Date },\n deletedAt: { default: null, required: false, type: Date },\n email: { required: true, type: String },\n invitations: { required: true, type: [invitationSchema] },\n name: { required: true, type: String },\n region: { required: true, type: String },\n },\n { timestamps: true },\n);\n\nschema.index({ name: 1 });\nschema.index({ email: 1 });\n\nexport const UnregisteredVendorModel =\n (mongoose.models\n .UnregisteredVendor as mongoose.Model<SchemaUnregisteredVendorType>) ||\n mongoose.model<SchemaUnregisteredVendorType>(\"UnregisteredVendor\", schema);\n","import { EnumEventType, EventType } from \"@timardex/cluemart-shared\";\nimport mongoose from \"mongoose\";\n\nimport { ObjectId } from \"src/types\";\n\nimport {\n baseResourceFields,\n dateTimeSchema,\n locationsSchema,\n SchemaOwnerType,\n socialShareResourceSchema,\n} from \"../global\";\nimport { searchNamePlugin } from \"../searchNamePlugin\";\n\nconst MongooseSchema = mongoose.Schema;\n\nexport type SchemaEventType = Omit<\n EventType,\n \"eventInfoId\" | \"owner\" | \"adIds\"\n> & {\n adIds?: ObjectId[];\n eventInfoId: ObjectId;\n owner: SchemaOwnerType;\n /** Lowercase `name` mirror for prefix type-ahead (see searchNamePlugin). */\n searchName?: string;\n};\n\n/**\n * This is the schema for the event type.\n * It is used to define the structure of the event type in the database.\n * The schema is used by Mongoose to create a model for the event type.\n */\nconst schema = new MongooseSchema<SchemaEventType>(\n {\n ...baseResourceFields, // Importing base resource fields from global.ts\n claimed: { default: true, required: false, type: Boolean },\n dateTime: { required: true, type: [dateTimeSchema] },\n eventInfoId: {\n ref: \"EventInfo\",\n required: false,\n type: mongoose.Schema.Types.ObjectId,\n },\n eventType: {\n enum: Object.values(EnumEventType),\n required: true,\n type: String,\n },\n googlePlaceId: {\n default: null,\n required: false,\n type: String,\n },\n location: {\n required: true,\n type: locationsSchema,\n },\n nzbn: { required: true, type: String },\n provider: { required: false, type: String },\n rainOrShine: { required: true, type: Boolean },\n shareRelation: { required: false, type: socialShareResourceSchema },\n tags: { required: true, type: [String] },\n },\n { timestamps: true },\n);\n\n// Indexes for search, geo, soft-delete, and dateTime status queries.\nschema.index({ name: 1 });\nschema.index({ description: 1 });\nschema.index({ region: 1 });\nschema.index({ \"location.geo\": \"2dsphere\" });\nschema.index({ tags: 1 });\nschema.index({ deletedAt: 1 });\nschema.index({ \"dateTime.dateStatus\": 1 });\nschema.index({ slug: 1 });\n\n// Full-text search across name/description/tags (see eventsSearch resolver).\nschema.index({ description: \"text\", name: \"text\", tags: \"text\" });\n\n// Serves getUserEvents / ownedCoupons' Event lookups:\n// `{ deletedAt: null, \"owner.userId\": <id> }` (and ownedCoupons' additional\n// `active: true` is a residual filter).\nschema.index({ deletedAt: 1, \"owner.userId\": 1 });\n\nschema.plugin(searchNamePlugin);\n\nexport const EventModel =\n (mongoose.models.Event as mongoose.Model<SchemaEventType>) ||\n mongoose.model<SchemaEventType>(\"Event\", schema);\n","import { DateTimeType } from \"@timardex/cluemart-shared\";\nimport mongoose from \"mongoose\";\n\nimport { ObjectId } from \"src/types\";\n\nimport { dateTimeSchema } from \"../global\";\n\nexport type SchemaEventDateArchiveType = {\n dateTime: DateTimeType[];\n eventId: ObjectId;\n};\n\n/**\n * Archived (ended) event date slots removed from `Event.dateTime` so the Event\n * document only carries the live schedule. One document per event, mirroring\n * the Event model's `dateTime` array shape.\n */\nconst schema = new mongoose.Schema<SchemaEventDateArchiveType>(\n {\n dateTime: { required: true, type: [dateTimeSchema] },\n eventId: {\n ref: \"Event\",\n required: true,\n type: mongoose.Schema.Types.ObjectId,\n },\n },\n { timestamps: true },\n);\n\n// One archive document per event.\nschema.index({ eventId: 1 }, { unique: true });\n\nexport const EventDateArchiveModel =\n (mongoose.models\n .EventDateArchive as mongoose.Model<SchemaEventDateArchiveType>) ||\n mongoose.model<SchemaEventDateArchiveType>(\"EventDateArchive\", schema);\n","import { EnumPartnerType, PartnerType } from \"@timardex/cluemart-shared\";\nimport mongoose from \"mongoose\";\n\nimport { ObjectId } from \"src/types\";\n\nimport { baseResourceFields, locationsSchema, SchemaOwnerType } from \"./global\";\nimport { searchNamePlugin } from \"./searchNamePlugin\";\n\nconst MongooseSchema = mongoose.Schema;\n\nexport type SchemaPartnerType = Omit<PartnerType, \"owner\" | \"adIds\"> & {\n adIds?: ObjectId[];\n owner: SchemaOwnerType;\n /** Lowercase `name` mirror for prefix type-ahead (see searchNamePlugin). */\n searchName?: string;\n};\n\nconst schema = new MongooseSchema<SchemaPartnerType>(\n {\n ...baseResourceFields,\n location: {\n required: true,\n type: locationsSchema,\n },\n nzbn: { required: true, type: String },\n partnerType: {\n enum: Object.values(EnumPartnerType),\n required: true,\n type: String,\n },\n },\n { timestamps: true },\n);\n\n// 🔹 Add indexes to speed up regex-based searches\nschema.index({ name: 1 });\nschema.index({ description: 1 });\nschema.index({ region: 1 });\nschema.index({ \"location.geo\": \"2dsphere\" });\nschema.index({ slug: 1 });\n\n// Full-text search across name/description (see partnersSearch resolver).\nschema.index({ name: \"text\", description: \"text\" });\n\n// Serves getUserPartners / ownedCoupons' Partner lookups:\n// `{ deletedAt: null, \"owner.userId\": <id> }`.\nschema.index({ \"owner.userId\": 1, deletedAt: 1 });\n\nschema.plugin(searchNamePlugin);\n\nexport const PartnerModel =\n (mongoose.models.Partner as mongoose.Model<SchemaPartnerType>) ||\n mongoose.model<SchemaPartnerType>(\"Partner\", schema);\n","import {\n EnumPostContentType,\n EnumPostType,\n EnumResourceType,\n PostContentType,\n PostResource,\n PostType,\n} from \"@timardex/cluemart-shared\";\nimport mongoose, { Schema } from \"mongoose\";\n\nimport { ResourceImageTypeSchema, socialShareResourceSchema } from \"./global\";\n\nconst MongooseSchema = mongoose.Schema;\n\nexport type SchemaPostType = PostType;\n\nconst contentSchema = new MongooseSchema<PostContentType>(\n {\n contentData: Schema.Types.Mixed,\n contentOrder: { required: true, type: Number },\n contentType: {\n enum: Object.values(EnumPostContentType),\n required: true,\n type: String,\n },\n },\n { _id: false },\n);\n\nconst resourceSchema = new MongooseSchema<PostResource>(\n {\n resourceId: { required: true, type: String },\n resourceRegion: { required: true, type: String },\n resourceSlug: { required: true, type: String },\n resourceType: {\n enum: Object.values(EnumResourceType),\n required: true,\n type: String,\n },\n },\n { _id: false },\n);\n\nconst schema = new MongooseSchema<SchemaPostType>(\n {\n active: { default: false, required: true, type: Boolean },\n approvedAt: { default: null, required: false, type: Date },\n caption: { required: true, type: String },\n content: {\n default: [],\n required: false,\n type: [contentSchema],\n },\n cover: {\n required: false,\n type: ResourceImageTypeSchema,\n },\n deletedAt: { default: null, required: false, type: Date },\n postType: {\n enum: Object.values(EnumPostType),\n required: true,\n type: String,\n },\n resource: {\n required: false,\n type: resourceSchema,\n },\n sharePublic: { required: false, type: socialShareResourceSchema },\n slug: { required: true, type: String },\n tags: { default: [], required: false, type: [String] },\n title: { required: true, type: String },\n },\n { timestamps: true },\n);\n\n// 🔹 Add indexes to speed up searches by title and tags\nschema.index({ title: 1 });\nschema.index({ tags: 1 });\nschema.index({ postType: 1, slug: 1 }, { unique: true });\n\nexport const PostModel =\n (mongoose.models.Post as mongoose.Model<SchemaPostType>) ||\n mongoose.model<SchemaPostType>(\"Post\", schema);\n","import { AppSettingsType } from \"@timardex/cluemart-shared\";\nimport mongoose from \"mongoose\";\n\nconst MongooseSchema = mongoose.Schema;\n\nexport const APP_SETTINGS_ID = \"APP_SETTINGS_DOCUMENT_ID\";\n\nexport type SchemaAppSettingsType = AppSettingsType & {\n adSettings: {\n approvalRequired: boolean;\n minAppearancesPerHour?: number;\n mobileDisplayEnabled: boolean;\n purchasePricing?: Record<string, unknown>;\n regionPricing?: Record<string, unknown>;\n paidSlotsPerPlacement?: number;\n reservedSlotsPerPlacement?: number;\n rotationSeconds?: number;\n webDisplayEnabled: boolean;\n };\n};\n\nconst AppSettingSchema = new MongooseSchema<SchemaAppSettingsType>(\n {\n activeSchoolsStudentCountTotal: {\n default: 0,\n required: true,\n type: Number,\n },\n activeSchoolsStudentCountUpdatedAt: {\n default: Date.now,\n required: true,\n type: Date,\n },\n adSettings: {\n approvalRequired: { default: true, required: true, type: Boolean },\n // Kept for older API clients; these fields do not control ad delivery.\n minAppearancesPerHour: {\n max: 12,\n min: 1,\n type: Number,\n validate: Number.isInteger,\n },\n mobileDisplayEnabled: { default: false, required: true, type: Boolean },\n purchasePricing: { type: MongooseSchema.Types.Mixed },\n regionPricing: { type: MongooseSchema.Types.Mixed },\n paidSlotsPerPlacement: { enum: [30], type: Number },\n reservedSlotsPerPlacement: { enum: [7], type: Number },\n rotationSeconds: { enum: [8], type: Number },\n webDisplayEnabled: { default: false, required: true, type: Boolean },\n },\n appVersion: { default: \"1.0.1\", required: true, type: String },\n isOfflineMode: { default: false, required: true, type: Boolean },\n key: {\n default: APP_SETTINGS_ID,\n immutable: true, // ✅ prevents changes after creation\n required: true,\n type: String,\n unique: true, // ✅ allowed here\n },\n minimumRedeemableAffiliatePoints: {\n default: 500,\n required: true,\n type: Number,\n },\n },\n { timestamps: true },\n);\n\nexport const AppSettingModel =\n (mongoose.models.AppSetting as mongoose.Model<SchemaAppSettingsType>) ||\n mongoose.model<SchemaAppSettingsType>(\"AppSetting\", AppSettingSchema);\n","import mongoose from \"mongoose\";\n\nimport type { ObjectId } from \"src/types\";\n\nconst MongooseSchema = mongoose.Schema;\n\n/**\n * Single-use record backing a WebView auto-login handoff.\n *\n * The app mints a short-lived signed token and opens the admin site with it;\n * the admin site exchanges the token for its own admin-slot session. Keeping\n * the `jti` here (with an atomic `usedAt` update) makes the token replay-proof\n * across server instances — a purely in-memory store would not.\n */\nexport interface AuthHandoffTokenType {\n createdAt: Date;\n expiresAt: Date;\n jti: string;\n updatedAt: Date;\n usedAt: Date | null;\n userId: ObjectId;\n}\n\nconst schema = new MongooseSchema<AuthHandoffTokenType>(\n {\n expiresAt: { required: true, type: Date },\n jti: { index: true, required: true, type: String, unique: true },\n usedAt: { default: null, required: false, type: Date },\n userId: {\n index: true,\n ref: \"User\",\n required: true,\n type: mongoose.Schema.Types.ObjectId,\n },\n },\n { timestamps: true },\n);\n\n// MongoDB removes the record once the handoff lifetime is over.\nschema.index({ expiresAt: 1 }, { expireAfterSeconds: 0 });\n\nexport const AuthHandoffTokenModel =\n (mongoose.models.AuthHandoffToken as mongoose.Model<AuthHandoffTokenType>) ||\n mongoose.model<AuthHandoffTokenType>(\"AuthHandoffToken\", schema);\n","import {\n EnumGameStatus,\n EnumGameType,\n GameDocType,\n GameHistory,\n GameType,\n} from \"@timardex/cluemart-shared\";\nimport mongoose from \"mongoose\";\n\nimport { ObjectId } from \"src/types\";\n\nimport { OwnerTypeSchema } from \"../global\";\n\nimport { schemaDailyClueGameData } from \"./DailyClue\";\nimport { schemaPuzzleGameData } from \"./PuzzleGame\";\nimport { schemaGameDate } from \"./utils\";\n\nconst MongooseSchema = mongoose.Schema;\n\nexport type SchemaGameType = Omit<GameType, \"_id\"> & {\n _id: ObjectId;\n};\n\n// REMOVE partial when other game types are added\nconst gameDataSchemas: Partial<Record<EnumGameType, any>> = {\n [EnumGameType.DAILY_CLUE]: schemaDailyClueGameData,\n [EnumGameType.MINI_QUIZ]: schemaPuzzleGameData,\n [EnumGameType.ODD_ONE_OUT]: schemaPuzzleGameData,\n};\n\nconst gameDataDefinition = Object.fromEntries(\n Object.entries(gameDataSchemas).map(([key, schema]) => [\n key,\n { default: null, required: false, type: schema },\n ]),\n);\n\nconst gameHistorySchema = new MongooseSchema<GameHistory>(\n {\n createdAt: { required: true, type: Date },\n gameDate: { required: true, type: schemaGameDate },\n gameStatus: {\n enum: Object.values(EnumGameStatus),\n required: true,\n type: String,\n },\n gameTitle: { required: true, type: String },\n gameType: {\n enum: Object.values(EnumGameType),\n required: true,\n type: String,\n },\n gameTypeId: { required: true, type: String },\n pointsEarned: { default: 0, required: true, type: Number },\n },\n { _id: false },\n);\n\nconst gameTypeSchema = new MongooseSchema<SchemaGameType>(\n {\n active: { default: true, required: true, type: Boolean },\n gameData: gameDataDefinition,\n gameHistory: { default: [], required: true, type: [gameHistorySchema] },\n gameTitle: { required: true, type: String },\n gameType: {\n enum: Object.values(EnumGameType),\n required: true,\n type: String,\n },\n gameTypeId: { required: true, type: String },\n // See `GameType.pointsCredited`: absent means \"completed before the marker\n // existed\", which must not be re-credited.\n pointsCredited: { required: false, type: Boolean },\n },\n { timestamps: true },\n);\n\nconst schema = new MongooseSchema<GameDocType>(\n {\n active: { default: false, required: true, type: Boolean },\n deletedAt: { default: null, required: false, type: Date },\n games: { default: [], required: false, type: [gameTypeSchema] },\n owner: {\n required: true,\n type: OwnerTypeSchema,\n },\n points: { default: 0, required: true, type: Number },\n },\n { timestamps: true },\n);\n\nexport const GameModel =\n (mongoose.models.Game as mongoose.Model<GameDocType>) ||\n mongoose.model<GameDocType>(\"Game\", schema);\n","import {\n DailyClueBaseGame,\n DailyClueGameData,\n} from \"@timardex/cluemart-shared\";\nimport mongoose from \"mongoose\";\n\nimport { schemaGameDate } from \"./utils\";\n\nconst MongooseSchema = mongoose.Schema;\n\n/*\n DAILY CLUE GAME DATA SCHEMA\n**/\nconst schemaLetters = new MongooseSchema<DailyClueGameData[\"letterInfo\"]>(\n {\n collected: { required: false, type: [String] },\n solutionShuffled: { required: true, type: [String] },\n // todaysLetter and todaysPlacement is generated in the backend, so they are not required\n },\n { _id: false },\n);\n\n/**\n * ✅ Shared definition (THIS replaces .obj usage)\n * related to Post Model, PostContentData is using BaseGame\n */\nconst schemaDailyClueBaseGame = new MongooseSchema<DailyClueBaseGame>(\n {\n gameDate: { required: true, type: schemaGameDate },\n gameSolution: { required: true, type: String },\n },\n { _id: false },\n);\n\nexport const schemaDailyClueGameData = new MongooseSchema<DailyClueGameData>(\n {\n gameFields: { required: true, type: schemaDailyClueBaseGame },\n lastFoundDate: { default: null, required: false, type: Date },\n letterInfo: {\n required: true,\n type: schemaLetters,\n },\n points: { default: 0, required: true, type: Number },\n streak: { default: 0, required: true, type: Number },\n },\n { _id: false },\n);\n","import { GameDate } from \"@timardex/cluemart-shared\";\nimport mongoose from \"mongoose\";\n\nconst MongooseSchema = mongoose.Schema;\n\n// ✅ Shared definition\nexport const schemaGameDate = new MongooseSchema<GameDate>(\n {\n endDate: { required: true, type: Date },\n startDate: { required: true, type: Date },\n },\n { _id: false },\n);\n","import {\n PuzzleAnswer,\n PuzzleAnsweredQuestion,\n PuzzleBaseGame,\n PuzzleGameData,\n PuzzleQuestion,\n} from \"@timardex/cluemart-shared\";\nimport mongoose from \"mongoose\";\n\nconst MongooseSchema = mongoose.Schema;\n\nconst schemaPuzzleAnswer = new MongooseSchema<PuzzleAnswer>(\n {\n answer: { required: true, type: String },\n answerId: { required: true, type: String },\n correct: { required: true, type: Boolean },\n },\n { _id: false },\n);\n\nconst schemaPuzzleQuestion = new MongooseSchema<PuzzleQuestion>(\n {\n answers: { required: true, type: [schemaPuzzleAnswer] },\n question: { required: true, type: String },\n questionId: { required: true, type: String },\n },\n { _id: false },\n);\n\nconst schemaPuzzleBaseGame = new MongooseSchema<PuzzleBaseGame>(\n {\n questions: { required: true, type: [schemaPuzzleQuestion] },\n },\n { _id: false },\n);\n\nconst schemaPuzzleAnsweredQuestion = new MongooseSchema<PuzzleAnsweredQuestion>(\n {\n questionId: { required: true, type: String },\n selectedAnswerId: { required: true, type: String },\n },\n { _id: false },\n);\n\nexport const schemaPuzzleGameData = new MongooseSchema<PuzzleGameData>(\n {\n answeredQuestions: {\n default: null,\n required: false,\n type: [schemaPuzzleAnsweredQuestion],\n },\n gameFields: { required: true, type: schemaPuzzleBaseGame },\n points: { default: 0, required: true, type: Number },\n streak: { default: 0, required: true, type: Number },\n },\n { _id: false },\n);\n","import { SchoolCampaignType, SchoolType } from \"@timardex/cluemart-shared\";\nimport mongoose from \"mongoose\";\n\nimport {\n ContactDetailsSchema,\n locationsSchema,\n OwnerTypeSchema,\n ResourceImageTypeSchema,\n SocialMediaTypeSchema,\n termsAgreementSchema,\n} from \"./global\";\n\nconst MongooseSchema = mongoose.Schema;\n\ntype SchoolDocument = Omit<SchoolType, \"ranking\">;\n\nconst campaignsSchema = new MongooseSchema<SchoolCampaignType>(\n {\n endDate: { required: true, type: Date },\n name: { required: true, type: String },\n startDate: { required: true, type: Date },\n },\n { _id: false },\n);\n\nconst schema = new MongooseSchema<SchoolDocument>(\n {\n // New schools are active by default\n active: { default: false, required: true, type: Boolean },\n approvedAt: { default: null, required: false, type: Date },\n campaigns: { required: false, type: [campaignsSchema] },\n contactDetails: { required: false, type: ContactDetailsSchema },\n deletedAt: { default: null, required: false, type: Date },\n location: {\n required: true,\n type: locationsSchema,\n },\n logo: { required: false, type: ResourceImageTypeSchema },\n name: { required: true, type: String },\n overallPoints: { default: 0, required: false, type: Number },\n owner: {\n required: true,\n type: OwnerTypeSchema,\n },\n region: { required: true, type: String },\n schoolCode: { required: true, type: String },\n socialMedia: { required: false, type: [SocialMediaTypeSchema] },\n studentCount: { default: 0, required: true, type: Number },\n termsAgreement: { required: true, type: termsAgreementSchema },\n },\n { timestamps: true },\n);\n\nschema.index(\n { schoolCode: 1 },\n {\n partialFilterExpression: { active: true, deletedAt: null },\n unique: true,\n },\n);\n\nexport const SchoolModel =\n (mongoose.models.School as mongoose.Model<SchoolDocument>) ||\n mongoose.model<SchoolDocument>(\"School\", schema);\n","import {\n AffiliateBankAccountDetailsType,\n AffiliateContactDetails,\n AffiliateDetailsType,\n AffiliateResourceType,\n AffiliateRewardType,\n AffiliateType,\n EnumAffiliateParticipantType,\n EnumAffiliateRewardType,\n EnumResourceType,\n RedeemHistoryType,\n} from \"@timardex/cluemart-shared\";\nimport mongoose from \"mongoose\";\n\nimport { ObjectId } from \"src/types\";\n\nimport {\n locationsSchema,\n OwnerTypeSchema,\n SchemaOwnerType,\n SocialMediaTypeSchema,\n termsAgreementSchema,\n} from \"./global\";\n\nconst MongooseSchema = mongoose.Schema;\n\nexport type SchemaAffiliateReward = AffiliateRewardType;\n\nexport type SchemaAffiliateResourceType = Omit<\n AffiliateResourceType,\n \"resourceId\" | \"resourceOwner\"\n> & {\n resourceId: ObjectId;\n resourceOwner: SchemaOwnerType;\n};\n\ntype AffiliateDocument = Omit<\n AffiliateType,\n \"_id\" | \"owner\" | \"affiliateResources\"\n> & {\n affiliateResources: SchemaAffiliateResourceType[];\n owner: SchemaOwnerType;\n};\n\nconst affiliateRewardSchema = new MongooseSchema<SchemaAffiliateReward>(\n {\n createdAt: { required: true, type: Date },\n redeemedAt: { default: null, required: false, type: Date },\n rewardDescription: { required: true, type: String },\n rewardType: {\n enum: Object.values(EnumAffiliateRewardType),\n required: true,\n type: String,\n },\n rewardValue: { required: true, type: Number },\n },\n { _id: false },\n);\n\nconst affiliateResourceSchema = new MongooseSchema<SchemaAffiliateResourceType>(\n {\n resourceActive: { default: true, required: true, type: Boolean },\n resourceDeletedAt: { default: null, required: false, type: Date },\n resourceId: {\n required: true,\n type: mongoose.Schema.Types.ObjectId,\n },\n resourceName: { required: true, type: String },\n resourceOwner: {\n required: true,\n type: OwnerTypeSchema,\n },\n resourceType: {\n enum: Object.values(EnumResourceType),\n required: true,\n type: String,\n },\n rewards: {\n default: [],\n required: false,\n type: [affiliateRewardSchema],\n },\n },\n { _id: false },\n);\n\nconst affiliateContactDetailsSchema =\n new MongooseSchema<AffiliateContactDetails>(\n {\n mobilePhone: { required: true, type: String },\n },\n { _id: false },\n );\n\nconst affiliateBankAccountDetailsSchema =\n new MongooseSchema<AffiliateBankAccountDetailsType>(\n {\n accountHolderName: { required: true, type: String },\n accountNumber: { required: true, type: String },\n },\n { _id: false },\n );\n\nconst affiliateDetailsSchema = new MongooseSchema<AffiliateDetailsType>(\n {\n bankAccountDetails: {\n required: true,\n type: affiliateBankAccountDetailsSchema,\n },\n contactDetails: { required: true, type: affiliateContactDetailsSchema },\n email: { required: true, type: String },\n firstName: { required: true, type: String },\n irdNumber: { required: true, type: String },\n lastName: { required: true, type: String },\n location: { required: true, type: locationsSchema },\n participantType: {\n enum: Object.values(EnumAffiliateParticipantType),\n required: true,\n type: String,\n },\n socialMedia: { required: false, type: [SocialMediaTypeSchema] },\n termsAgreement: { required: true, type: termsAgreementSchema },\n },\n { _id: false },\n);\n\nconst redeemHistorySchema = new MongooseSchema<RedeemHistoryType>(\n {\n paidAt: { default: null, required: false, type: Date },\n redeemedAt: { required: true, type: Date },\n rewardValue: { required: true, type: Number },\n },\n { _id: false },\n);\n\nconst schema = new MongooseSchema<AffiliateDocument>(\n {\n active: { default: false, required: true, type: Boolean },\n affiliateBonusRewards: {\n default: [],\n required: false,\n type: [affiliateRewardSchema],\n },\n affiliateCode: { default: null, required: false, type: String },\n affiliateDetails: { required: false, type: affiliateDetailsSchema },\n affiliateResources: {\n default: [],\n required: false,\n type: [affiliateResourceSchema],\n },\n approvedAt: { default: null, required: false, type: Date },\n deletedAt: { default: null, required: false, type: Date },\n overallPoints: { default: 0, required: true, type: Number },\n owner: {\n required: true,\n type: OwnerTypeSchema,\n },\n redeemHistory: {\n default: [],\n required: false,\n type: [redeemHistorySchema],\n },\n },\n { timestamps: true },\n);\n\nschema.index(\n { affiliateCode: 1 },\n {\n partialFilterExpression: { active: true, deletedAt: null },\n unique: true,\n },\n);\n\nexport const AffiliateModel =\n (mongoose.models.Affiliate as mongoose.Model<AffiliateDocument>) ||\n mongoose.model<AffiliateDocument>(\"Affiliate\", schema);\n","import {\n CouponCodeType,\n CouponDataType,\n CouponOption,\n CouponParticipantUserType,\n CouponType,\n EnumCouponQualificationType,\n EnumResourceType,\n} from \"@timardex/cluemart-shared\";\nimport mongoose from \"mongoose\";\n\nimport { ObjectId } from \"src/types\";\n\nimport { OwnerTypeSchema, ResourceImageTypeSchema } from \"./global\";\n\nconst MongooseSchema = mongoose.Schema;\n\ntype SchemaCouponParticipantUserType = Omit<\n CouponParticipantUserType,\n \"userId\"\n> & {\n userId: ObjectId;\n};\n\ntype SchemaCouponVendorProductType = {\n couponId: ObjectId;\n productId: ObjectId;\n vendorCouponId?: ObjectId;\n vendorId: ObjectId;\n};\n\ntype SchemaCouponDataType = Omit<\n CouponDataType,\n \"participantUsers\" | \"couponVendorProducts\"\n> & {\n couponVendorProducts?: SchemaCouponVendorProductType[];\n participantUsers: SchemaCouponParticipantUserType[] | null;\n};\n\nexport type CouponDocument = Omit<CouponType, \"couponData\"> & {\n couponData: SchemaCouponDataType[];\n};\n\nconst couponOptionSchema = new MongooseSchema<CouponOption>(\n {\n buy: { required: false, type: Number },\n get: { required: false, type: Number },\n maxRewardCount: { required: false, type: Number },\n type: {\n enum: Object.values(EnumCouponQualificationType),\n required: true,\n type: String,\n },\n unit: { required: false, type: String },\n visits: { required: false, type: Number },\n },\n { _id: false },\n);\n\nconst couponVendorProductSchema =\n new MongooseSchema<SchemaCouponVendorProductType>(\n {\n couponId: {\n required: true,\n type: mongoose.Schema.Types.ObjectId,\n },\n productId: {\n required: true,\n type: mongoose.Schema.Types.ObjectId,\n },\n vendorCouponId: {\n required: false,\n type: mongoose.Schema.Types.ObjectId,\n },\n vendorId: {\n ref: \"Vendor\",\n required: true,\n type: mongoose.Schema.Types.ObjectId,\n },\n },\n { _id: false },\n );\n\nconst couponCodeSchema = new MongooseSchema<CouponCodeType>(\n {\n code: { required: true, type: String },\n qrCode: { required: true, type: ResourceImageTypeSchema },\n shareableQrCode: { required: true, type: ResourceImageTypeSchema },\n },\n { _id: false },\n);\n\nconst couponParticipantUserSchema =\n new MongooseSchema<SchemaCouponParticipantUserType>(\n {\n couponCollectedCount: { default: 0, required: true, type: Number },\n couponCycleRedeemed: { default: false, required: true, type: Boolean },\n couponRedeemedAt: { default: null, required: false, type: Date },\n couponRedeemedCount: { default: 0, required: true, type: Number },\n userId: {\n ref: \"User\",\n required: true,\n type: mongoose.Schema.Types.ObjectId,\n },\n },\n { timestamps: true },\n );\n\nconst couponDataSchema = new MongooseSchema<SchemaCouponDataType>(\n {\n active: { default: true, required: true, type: Boolean },\n couponCode: { required: false, type: couponCodeSchema },\n couponDescription: { required: true, type: String },\n couponOption: { required: true, type: couponOptionSchema },\n couponVendorProducts: {\n required: false,\n type: [couponVendorProductSchema],\n },\n deletedAt: { default: null, required: false, type: Date },\n endDate: { required: true, type: Date },\n participantUsers: {\n default: null,\n required: false,\n type: [couponParticipantUserSchema],\n },\n resourceId: { required: true, type: String },\n resourceType: {\n enum: Object.values(EnumResourceType),\n required: true,\n type: String,\n },\n startDate: { required: true, type: Date },\n },\n { timestamps: true },\n);\n\nconst schema = new MongooseSchema<CouponDocument>(\n {\n active: { default: true, required: true, type: Boolean },\n couponData: { default: [], required: false, type: [couponDataSchema] },\n deletedAt: { default: null, required: false, type: Date },\n owner: {\n required: true,\n type: OwnerTypeSchema,\n },\n },\n { timestamps: true },\n);\n\n// Indexes for the getCoupons aggregations. All three (activeCoupons,\n// scannedCoupons, ownedCoupons) open with `{ active: true, deletedAt: null }`,\n// so one compound index serves that shared prefix; `owner.userId` (a top-level\n// embedded field, NOT inside `couponData`) covers ownedCoupons' equality match.\n// The nested participant filter used by scannedCoupons lives inside the\n// `couponData` array of subdocuments, so it needs its own multikey index.\n//\n// Note: the `$sort: { updatedAt: -1 }` at the end of each aggregation cannot\n// use an index because it follows `$addFields`/`$match` stages — only the\n// leading `$match` is indexable.\nschema.index({ active: 1, deletedAt: 1, \"owner.userId\": 1 });\nschema.index({ \"couponData.participantUsers.userId\": 1 });\n\nexport const CouponModel =\n (mongoose.models.Coupon as mongoose.Model<CouponDocument>) ||\n mongoose.model<CouponDocument>(\"Coupon\", schema);\n","import { EnumResourceType } from \"@timardex/cluemart-shared\";\nimport mongoose from \"mongoose\";\n\nimport { ObjectId } from \"src/types\";\n\nconst MongooseSchema = mongoose.Schema;\n\nexport type SchemaImpersonationSessionType = {\n /** The SUPER_ADMIN who is impersonating. */\n impersonatorUserId: ObjectId;\n /** The resource owner being impersonated. */\n impersonatedUserId: ObjectId;\n /** Hashed impersonation refresh token (stored here, not on the User doc). */\n refreshToken: string;\n expiresAt: Date;\n};\n\nconst impersonationSessionSchema =\n new MongooseSchema<SchemaImpersonationSessionType>(\n {\n expiresAt: { expires: 0, required: true, type: Date },\n impersonatedUserId: {\n index: true,\n ref: \"User\",\n required: true,\n type: mongoose.Schema.Types.ObjectId,\n },\n impersonatorUserId: {\n index: true,\n ref: \"User\",\n required: true,\n type: mongoose.Schema.Types.ObjectId,\n },\n refreshToken: { required: true, type: String },\n },\n { timestamps: true },\n );\n\nexport const ImpersonationSessionModel =\n (mongoose.models\n .ImpersonationSession as mongoose.Model<SchemaImpersonationSessionType>) ||\n mongoose.model<SchemaImpersonationSessionType>(\n \"ImpersonationSession\",\n impersonationSessionSchema,\n );\n\nexport type SchemaImpersonationAuditType = {\n action: \"start\" | \"end\";\n /** Reason for an `end` record (manual, logout, reuse_revoked, expired). */\n endReason?: string | null;\n impersonatedUserId: ObjectId;\n impersonatorUserId: ObjectId;\n resourceId?: ObjectId | null;\n resourceType?: EnumResourceType | null;\n sessionId: ObjectId;\n};\n\nconst impersonationAuditSchema =\n new MongooseSchema<SchemaImpersonationAuditType>(\n {\n action: { enum: [\"start\", \"end\"], required: true, type: String },\n endReason: { type: String },\n impersonatedUserId: {\n ref: \"User\",\n required: true,\n type: mongoose.Schema.Types.ObjectId,\n },\n impersonatorUserId: {\n ref: \"User\",\n required: true,\n type: mongoose.Schema.Types.ObjectId,\n },\n resourceId: { type: mongoose.Schema.Types.ObjectId },\n resourceType: { enum: Object.values(EnumResourceType), type: String },\n sessionId: {\n ref: \"ImpersonationSession\",\n required: true,\n type: mongoose.Schema.Types.ObjectId,\n },\n },\n { timestamps: true },\n );\n\nexport const ImpersonationAuditModel =\n (mongoose.models\n .ImpersonationAudit as mongoose.Model<SchemaImpersonationAuditType>) ||\n mongoose.model<SchemaImpersonationAuditType>(\n \"ImpersonationAudit\",\n impersonationAuditSchema,\n );\n","/** 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 subscription status:\n * - Pro / Pro+ with Stripe (ACTIVE/TRIALING) → `ACTIVE_VENDOR_PRO_SUBSCRIPTION` (3 pts)\n * - Pro / Pro+ without an eligible Stripe subscription → `ACTIVE_VENDOR_STANDARD_SUBSCRIPTION` (1 pt)\n * - Standard → `ACTIVE_VENDOR_STANDARD_SUBSCRIPTION` (1 pt)\n *\n * Stripe eligibility requires a subscription ID and a vendor Pro / Pro+ plan,\n * but not a future paid-through endDate. It does not establish paid licence access.\n * Idempotent per affiliate + vendor + calendar month — a mid-month upgrade\n * (Standard → Pro with an eligible Stripe subscription) affects the next 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 NZ_TZ,\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 { getVendorStripeSubscriptionPlanForRewards } 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 = NZ_TZ;\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+ yields the Pro reward when the owner has a Stripe subscription ID,\n * a vendor Pro / Pro+ plan, and ACTIVE or TRIALING subscription status.\n * A future paid-through endDate is not required for rewards; this does not\n * establish paid access for licence compliance. Otherwise falls back to Standard.\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 getVendorStripeSubscriptionPlanForRewards(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 StripeSubscriptionPlanResult = {\n /** Meets the caller's eligibility policy; reward eligibility is not paid access. */\n hasSubscription: boolean;\n plan: EnumUserLicence | null;\n validTypes: Set<EnumUserLicence>;\n};\n\nasync function getStripePlanFor(\n userId: ObjectId | string,\n now: Date,\n allowedPlans: Set<EnumUserLicence>,\n requirePaidAccess: boolean = true,\n): Promise<StripeSubscriptionPlanResult> {\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 =\n stripe.status === EnumSubscriptionStatus.ACTIVE ||\n (!requirePaidAccess && stripe.status === EnumSubscriptionStatus.TRIALING);\n const paidThrough = stripe.endDate\n ? new Date(stripe.endDate).getTime()\n : Number.NaN;\n\n if (\n !hasActiveStatus ||\n (requirePaidAccess &&\n (!Number.isFinite(paidThrough) || paidThrough <= now.getTime())) ||\n stripe.currentPlan == null\n ) {\n return { hasSubscription: false, plan: null, validTypes };\n }\n\n const plan = allowedPlans.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<StripeSubscriptionPlanResult> {\n return getStripePlanFor(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<StripeSubscriptionPlanResult> {\n return getStripePlanFor(userId, now, PRO_VENDOR_PLANS);\n}\n\n/**\n * Preserves affiliate reward eligibility for active or trialing vendor plans.\n * This does not establish paid access and must not be used for licence compliance.\n */\nexport async function getVendorStripeSubscriptionPlanForRewards(\n userId: ObjectId | string,\n now: Date = new Date(),\n): Promise<StripeSubscriptionPlanResult> {\n return getStripePlanFor(userId, now, PRO_VENDOR_PLANS, false);\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<StripeSubscriptionPlanResult> {\n return getStripePlanFor(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 { EnumUserRole } from \"@timardex/cluemart-shared\";\nimport { NotificationCount } from \"@timardex/cluemart-shared/types\";\nimport express from \"express\";\nimport mongoose from \"mongoose\";\n\nimport { SchemaChatType } from \"../mongoose/chat/Chat\";\nimport { SchemaNotificationType } from \"../mongoose/Notification\";\n\n// chnage to export type ObjectId = mongoose.Types.ObjectId;\n// chnage in server when setting decideGameType\nexport type ObjectId = mongoose.Types.ObjectId;\n\nexport enum EnumPubSubEvents {\n GET_CHAT_MESSAGE = \"GET_CHAT_MESSAGE\",\n GET_NOTIFICATIONS = \"GET_NOTIFICATIONS\",\n GET_NOTIFICATIONS_COUNT = \"GET_NOTIFICATIONS_COUNT\",\n USER_TYPING = \"USER_TYPING\",\n}\n\n/** Clients that own their own refresh-token slot on the user document. */\nexport type AuthTokenClient = \"mobile\" | \"admin\";\n\nexport interface AuthUser {\n email: string;\n roles: EnumUserRole[];\n userId: ObjectId;\n /**\n * Which client slot this token belongs to. Absent only on tokens issued\n * before the per-client rollout; those can no longer refresh.\n */\n client?: AuthTokenClient;\n /** Set when this token represents an impersonation session. */\n impersonationSessionId?: string;\n /** The SUPER_ADMIN who started the impersonation session. */\n impersonatorUserId?: ObjectId;\n}\n\nexport interface SubscriptionPayload {\n getChatMessage?: SchemaChatType;\n userTyping?: SchemaChatType; // NOT USED\n getNotifications?: SchemaNotificationType[];\n // Used only for filtering; not part of the GraphQL schema output\n getNotificationsUserId?: ObjectId;\n getNotificationsCount?: NotificationCount & { userId: ObjectId };\n}\n\nexport interface GraphQLContext {\n appVersion: string | null;\n user: AuthUser | null;\n pubsub: {\n publish: (\n eventName: EnumPubSubEvents,\n payload: SubscriptionPayload,\n ) => void;\n subscribe: (eventName: EnumPubSubEvents) => AsyncIterable<any>;\n };\n request: express.Request;\n response: express.Response;\n}\n\nexport { mongoose, express };\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 nzDayKey,\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 * `start`/`end` are UTC-midnight NZ day keys, so comparisons run against\n * today's NZ day key rather than the current instant.\n */\nexport async function updateAdStatuses(): Promise<void> {\n const now = nzDayKey();\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 EnumPointType,\n UserOverallPointsEntry,\n} from \"@timardex/cluemart-shared\";\nimport dayjs from \"dayjs\";\n\n/**\n * Rejects amounts that would corrupt the ledger: a negative award silently\n * reduces the balance, and `NaN`/`Infinity` poison every later `$sum`/`$reduce`\n * (a single `NaN` makes the whole spendable total `NaN`).\n */\nfunction assertValidPointAmount(amount: number, label: string): void {\n if (!Number.isFinite(amount) || amount < 0) {\n throw new RangeError(\n `Invalid user point ${label}: ${String(amount)}. Expected a finite, non-negative number.`,\n );\n }\n}\n\n/**\n * One ledger entry for an award.\n *\n * `User.overallPoints` is append-only: awarding points must push a new entry so\n * previously earned points are never replaced.\n *\n * `sourceId` is the idempotency key for the award (e.g. the game row `_id`).\n * Pass it whenever the award can be retried, so `buildUserPointCreditFilter`\n * can dedupe it.\n *\n * `undefined` is the only \"no key\" value: an empty string is stored as-is so the\n * entry always matches what `buildUserPointCreditFilter` searches for (a\n * truthiness check here would drop `\"\"` from the entry while the filter still\n * looked for it, silently disabling dedupe).\n */\nexport function buildUserPointAwardEntry(\n pointType: EnumPointType,\n points: number,\n sourceId?: string,\n): UserOverallPointsEntry {\n assertValidPointAmount(points, \"award\");\n return {\n createdAt: dayjs().toDate(),\n points,\n pointType,\n ...(sourceId === undefined ? {} : { sourceId }),\n };\n}\n\n/**\n * Filter for an idempotent award: matches the user only when no ledger entry\n * already carries `sourceId`.\n *\n * Uses `$not` + `$elemMatch` rather than a dotted `$ne` so the \"no entry with\n * this key\" intent is explicit and cannot be mistaken for a per-element\n * comparison. Combined with `$push` of\n * `buildUserPointAwardEntry(..., sourceId)`, running the award twice credits it\n * once. This replaces a cross-document transaction (unavailable on standalone\n * MongoDB) for \"credit points, then mark the source as done\" flows.\n */\nexport function buildUserPointCreditFilter(userId: unknown, sourceId: string) {\n return {\n _id: userId,\n overallPoints: { $not: { $elemMatch: { sourceId } } },\n };\n}\n\n/**\n * Matches users whose spendable total (sum of every ledger entry) covers\n * `amount`. Legacy numeric values contribute 0 until the startup migration runs.\n */\nexport function buildUserHasEnoughPointsFilter(amount: number) {\n assertValidPointAmount(amount, \"threshold\");\n return {\n $expr: {\n $gte: [{ $sum: { $ifNull: [\"$overallPoints.points\", []] } }, amount],\n },\n };\n}\n\n/**\n * Write expression for the ledger field, guarded against unexpected stored\n * shapes:\n * - array: store the computed ledger.\n * - null/missing: normalized to an empty ledger, otherwise a later `$push`\n * fails with \"must be an array\" and the field stays null forever.\n * - any other value: written back unchanged rather than replaced with `[]`, so\n * an unexpected shape is surfaced rather than silently wiping a balance.\n */\nfunction buildLedgerWriteExpr(computedLedger: object) {\n return {\n $cond: [\n { $isArray: \"$overallPoints\" },\n computedLedger,\n { $ifNull: [\"$overallPoints\", []] },\n ],\n };\n}\n\n/**\n * Debits `amount` from the oldest entries first (FIFO), flooring every entry at\n * 0 and dropping emptied ones. Pair with `buildUserHasEnoughPointsFilter` so\n * the full amount is always covered.\n *\n * Non-array `overallPoints` values are handled by `buildLedgerWriteExpr`:\n * null/missing becomes an empty ledger, while any other shape is left untouched\n * rather than replaced.\n */\nexport function buildUserPointDebitPipeline(amount: number) {\n assertValidPointAmount(amount, \"debit\");\n const debitedLedger = {\n $let: {\n vars: {\n sorted: {\n $sortArray: {\n input: { $ifNull: [\"$overallPoints\", []] },\n sortBy: { createdAt: 1 },\n },\n },\n },\n in: {\n $let: {\n vars: {\n debited: {\n $reduce: {\n initialValue: { budget: amount, entries: [] },\n in: {\n $let: {\n vars: { available: { $ifNull: [\"$$this.points\", 0] } },\n in: {\n budget: {\n $subtract: [\n \"$$value.budget\",\n { $min: [\"$$available\", \"$$value.budget\"] },\n ],\n },\n entries: {\n $concatArrays: [\n \"$$value.entries\",\n [\n {\n $mergeObjects: [\n \"$$this\",\n {\n points: {\n $subtract: [\n \"$$available\",\n {\n $min: [\"$$available\", \"$$value.budget\"],\n },\n ],\n },\n },\n ],\n },\n ],\n ],\n },\n },\n },\n },\n input: \"$$sorted\",\n },\n },\n },\n in: {\n $filter: {\n as: \"entry\",\n cond: { $gt: [\"$$entry.points\", 0] },\n input: \"$$debited.entries\",\n },\n },\n },\n },\n },\n };\n\n return [\n {\n $set: {\n overallPoints: buildLedgerWriteExpr(debitedLedger),\n },\n },\n ];\n}\n\n/**\n * Removes the first ledger entry matching `pointType` (and `sourceId`, when\n * given), reversing a single award. `$pull` cannot be used because it would\n * remove every entry of that type.\n *\n * Always pass `sourceId` when the award carries one: matching on `pointType`\n * alone would remove an unrelated award of the same type (e.g. checking out of\n * one event stripping a different event's check-in points).\n *\n * Non-array `overallPoints` values are handled by `buildLedgerWriteExpr`:\n * null/missing becomes an empty ledger, while any other shape is left untouched\n * rather than replaced.\n */\nexport function buildUserPointEntryRemovalPipeline(\n pointType: EnumPointType,\n sourceId?: string,\n) {\n // Compare entries by `pointType` + `sourceId` via a boolean map, then locate\n // the first `true`. Matching both fields is what keeps the removal specific.\n const indexExpression =\n sourceId === undefined\n ? { $indexOfArray: [\"$$entries.pointType\", pointType] }\n : {\n $indexOfArray: [\n {\n $map: {\n as: \"entry\",\n in: {\n $and: [\n { $eq: [\"$$entry.pointType\", pointType] },\n { $eq: [\"$$entry.sourceId\", sourceId] },\n ],\n },\n input: \"$$entries\",\n },\n },\n true,\n ],\n };\n\n const entriesAfterRemoval = {\n $let: {\n vars: { entries: { $ifNull: [\"$overallPoints\", []] } },\n in: {\n $let: {\n vars: {\n index: indexExpression,\n },\n in: {\n $cond: [\n { $lt: [\"$$index\", 0] },\n \"$$entries\",\n {\n $concatArrays: [\n { $slice: [\"$$entries\", \"$$index\"] },\n {\n $slice: [\n \"$$entries\",\n { $add: [\"$$index\", 1] },\n { $size: \"$$entries\" },\n ],\n },\n ],\n },\n ],\n },\n },\n },\n },\n };\n\n return [\n {\n $set: {\n overallPoints: buildLedgerWriteExpr(entriesAfterRemoval),\n },\n },\n ];\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 AiImportedMarketModel,\n EventDateArchiveModel,\n EventInfoModel,\n EventModel,\n GoogleImportedMarketModel,\n} from \"src/mongoose\";\n\nimport {\n dedupeArchivedSlotsByStartDateTime,\n isPastCanceledEventDate,\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: [\n EnumEventDateStatus.ENDED,\n EnumEventDateStatus.INVALID,\n EnumEventDateStatus.CANCELED,\n ],\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 EventDatePullCondition = {\n $or: Array<\n | { dateStatus: { $in: EnumEventDateStatus[] } }\n | {\n dateStatus: EnumEventDateStatus;\n startDate: string;\n startTime: string;\n }\n >;\n};\n\ntype EventDatePullOp = {\n updateOne: {\n filter: { _id: unknown };\n update: {\n $pull: {\n dateTime: EventDatePullCondition;\n };\n };\n };\n};\n\ntype EventDatePullableModel = {\n bulkWrite: (ops: EventDatePullOp[]) => Promise<unknown>;\n};\n\n/**\n * Moves ended event date slots into the archive, discards invalid slots, deletes\n * past canceled slots, and pulls all three from `Event.dateTime`, keeping future,\n * in-progress (`STARTED`), and future `CANCELED` dates live. Archive upserts and\n * event `$pull` updates are collected into bulkWrite batches to avoid\n * per-document round-trips. The event write is a targeted `$pull` (by status or\n * by start date/time) rather than a full-array `$set`, so concurrent schedule\n * 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 as unknown as EventDatePullableModel).bulkWrite(\n eventOps,\n );\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 const pastCanceled = updated.filter((slot) =>\n isPastCanceledEventDate(slot, now),\n );\n if (\n archive.length === 0 &&\n discard.length === 0 &&\n pastCanceled.length === 0\n ) {\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 const pullConditions: EventDatePullCondition[\"$or\"] = [];\n if (archive.length > 0 || discard.length > 0) {\n pullConditions.push({\n dateStatus: {\n $in: [EnumEventDateStatus.ENDED, EnumEventDateStatus.INVALID],\n },\n });\n }\n for (const slot of pastCanceled) {\n pullConditions.push({\n dateStatus: EnumEventDateStatus.CANCELED,\n startDate: slot.startDate,\n startTime: slot.startTime,\n });\n }\n\n eventOps.push({\n updateOne: {\n filter: { _id: doc._id },\n update: {\n $pull: {\n dateTime: { $or: pullConditions },\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, Google-imported\n * markets, and AI-imported markets (run on a schedule by\n * `cluemart-server-cron`), moves ended event date slots into the event date\n * archive, and keeps `EventInfo.dateTime` future-only.\n */\nexport async function updateAllEventDateTimeStatuses(): Promise<void> {\n const now = dayjs();\n const [eventCount, marketCount, aiMarketCount] = await Promise.all([\n updateModelDateTimeStatuses(EventModel as DateTimeUpdatableModel, now),\n updateModelDateTimeStatuses(\n GoogleImportedMarketModel as DateTimeUpdatableModel,\n now,\n ),\n updateModelDateTimeStatuses(\n AiImportedMarketModel as DateTimeUpdatableModel,\n now,\n ),\n ]);\n\n console.log(\n `✅ Event dateTime statuses updated: events=${eventCount} changed, google imported markets=${marketCount} changed, ai imported markets=${aiMarketCount} 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 {\n DateTimeType,\n EnumEventDateStatus,\n dateFormat,\n timeFormat,\n} from \"@timardex/cluemart-shared\";\nimport dayjs from \"dayjs\";\nimport customParseFormat from \"dayjs/plugin/customParseFormat\";\n\nimport { EventDateArchiveModel } from \"src/mongoose\";\nimport { ObjectId } from \"src/types\";\n\ndayjs.extend(customParseFormat);\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 * A CANCELED slot is \"past\" once its end date/time has passed. Past canceled\n * slots can be deleted from the live schedule without touching future canceled\n * slots or accidentally removing malformed manual cancellations (missing or\n * unparseable end dates are not considered past).\n */\nexport function isPastCanceledEventDate(\n slot: DateTimeType,\n now: dayjs.Dayjs,\n): boolean {\n if (slot.dateStatus !== EnumEventDateStatus.CANCELED) {\n return false;\n }\n\n const endDateTime = dayjs(\n `${slot.endDate} ${slot.endTime}`,\n `${dateFormat} ${timeFormat}`,\n true,\n );\n\n return endDateTime.isValid() && endDateTime.isBefore(now);\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 * from \"./userPoints\";\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 AiImportedMarketModel,\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, Google Imported Market, or AI\n * Imported Market by the given resource ID.\n * It first normalizes the resource ID to a string format, then performs parallel queries to all three collections.\n * If an Event is found, it returns that; otherwise it checks the imported-market collections and returns the first match.\n * If none 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 an 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, aiImportedDoc] = 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 AiImportedMarketModel.findById(normalizedId)\n .select(\"_id name dateTime\")\n .lean<Pick<EventListItemType, \"_id\" | \"name\" | \"dateTime\">>()\n .exec(),\n ]);\n\n return eventDoc ?? googleImportedDoc ?? aiImportedDoc;\n}\n","import {\n DateTimeWithPriceType,\n EnumEventDateStatus,\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\ntype StartedDateSlot = Pick<\n DateTimeType,\n \"dateStatus\" | \"startDate\" | \"startTime\"\n>;\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 * Returns true when a slot that was `STARTED` in the previous schedule is no\n * longer `STARTED` in the next schedule (e.g. canceled or rescheduled).\n *\n * This catches the `STARTED → CANCELED` transition that\n * {@link didRemoveAnyEventDates} misses: that function only compares\n * `startDate`/`startTime` presence, so a slot that still exists but whose\n * `dateStatus` changed is not flagged. (Its callers filter to future-only\n * schedules, which also drop `STARTED`.) Without this extra status check, a\n * started slot that gets canceled would leave its relation dates untouched.\n */\nexport function didRemoveAnyStartedDates(\n previousDateTime: StartedDateSlot[] | undefined,\n nextDateTime: StartedDateSlot[] | undefined,\n): boolean {\n if (!previousDateTime?.length) {\n return false;\n }\n\n return previousDateTime.some(\n (prev) =>\n prev.dateStatus === EnumEventDateStatus.STARTED &&\n !nextDateTime?.some(\n (next) =>\n next.startDate === prev.startDate &&\n next.startTime === prev.startTime &&\n next.dateStatus === EnumEventDateStatus.STARTED,\n ),\n );\n}\n\n/**\n * Helper: Update relationDates based on event's dateTime\n * Marks dates as CANCELED if they no longer exist in the event's dateTime.\n */\nexport function updateRelationDatesToCanceled(\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 ? relationDate.status : EnumInviteStatus.CANCELED,\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,gCAAAA;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oCAAAC;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA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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":["express","mongoose","mongoose","import_cluemart_shared","import_mongoose","schema","mongoose","import_cluemart_shared","import_mongoose","schema","mongoose","import_mongoose","schema","mongoose","import_cluemart_shared","import_mongoose","mongoose","schema","import_cluemart_shared","import_mongoose","MongooseSchema","mongoose","schema","import_cluemart_shared","import_mongoose","MongooseSchema","mongoose","import_cluemart_shared","import_mongoose","MongooseSchema","mongoose","import_cluemart_shared","import_mongoose","MongooseSchema","mongoose","import_cluemart_shared","import_mongoose","$set","schema","MongooseSchema","mongoose","schema","import_cluemart_shared","import_mongoose","MongooseSchema","mongoose","addressComponentSchema","schema","import_cluemart_shared","import_mongoose","MongooseSchema","mongoose","schema","import_mongoose","MongooseSchema","mongoose","schema","import_mongoose","MongooseSchema","mongoose","import_cluemart_shared","import_mongoose","MongooseSchema","mongoose","schema","import_mongoose","MongooseSchema","mongoose","schema","import_cluemart_shared","import_mongoose","import_cluemart_shared","import_mongoose","MongooseSchema","mongoose","dateTimeSchema","schema","MongooseSchema","mongoose","import_cluemart_shared","import_mongoose","MongooseSchema","mongoose","schema","import_cluemart_shared","import_mongoose","MongooseSchema","mongoose","schema","import_mongoose","MongooseSchema","mongoose","schema","import_cluemart_shared","import_mongoose","MongooseSchema","mongoose","schema","import_cluemart_shared","import_mongoose","MongooseSchema","mongoose","schema","import_mongoose","MongooseSchema","mongoose","schema","import_cluemart_shared","import_mongoose","MongooseSchema","mongoose","schema","import_mongoose","schema","mongoose","import_cluemart_shared","import_mongoose","MongooseSchema","mongoose","schema","import_cluemart_shared","import_mongoose","MongooseSchema","mongoose","schema","import_mongoose","MongooseSchema","mongoose","import_mongoose","MongooseSchema","mongoose","schema","import_cluemart_shared","import_mongoose","import_mongoose","import_mongoose","MongooseSchema","mongoose","MongooseSchema","mongoose","import_mongoose","MongooseSchema","mongoose","MongooseSchema","mongoose","schema","import_mongoose","MongooseSchema","mongoose","schema","import_cluemart_shared","import_mongoose","MongooseSchema","mongoose","schema","import_cluemart_shared","import_mongoose","MongooseSchema","mongoose","schema","import_cluemart_shared","import_mongoose","MongooseSchema","mongoose","import_cluemart_shared","import_utils","import_cluemart_shared","import_enums","dayjs","utc","timezone","import_mongoose","mongoose","import_mongoose","EnumPubSubEvents","import_cluemart_shared","import_mongoose","mongoose","import_dayjs","dayjs","import_cluemart_shared","import_dayjs","import_cluemart_shared","import_dayjs","dayjs","customParseFormat","dayjs","import_cluemart_shared","import_cluemart_shared","import_dayjs","import_cluemart_shared","import_dayjs","import_cluemart_shared","import_cluemart_shared","import_cluemart_shared","import_dayjs","import_cluemart_shared","import_dayjs","LicenceCategory","dayjs","dayjs","dayjs","dayjs","import_dayjs","import_cluemart_shared","import_utils","import_dayjs","dayjs","dayjs"]}
|