@timardex/cluemart-server-shared 2.1.8 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
1
  import * as mongoose from 'mongoose';
2
2
  import * as _timardex_cluemart_shared from '@timardex/cluemart-shared';
3
3
  import { PromoCodeType, EnumAffiliateRewardType, DateTimeType, EventListItemType, DateTimeWithPriceType, EnumUserLicence as EnumUserLicence$1, UserLicenceType, EnumNotificationResourceType, EnumNotificationType, EnumResourceType, LicenceExpiryDate } from '@timardex/cluemart-shared';
4
- import { d as SchemaAffiliateResourceType, S as SchemaOwnerType, g as SchemaRelationType, j as SchemaUserType } from '../Affiliate-B1mxoMeD.mjs';
4
+ import { d as SchemaAffiliateResourceType, S as SchemaOwnerType, g as SchemaRelationType, j as SchemaUserType } from '../Affiliate-i11rkfv5.mjs';
5
5
  import { O as ObjectId, G as GraphQLContext, e as SchemaCreateBulkNotificationInput } from '../index-Bq-lT7a2.mjs';
6
6
  import dayjs, { Dayjs } from 'dayjs';
7
7
  import { DateTimeType as DateTimeType$1 } from '@timardex/cluemart-shared/types';
@@ -160,16 +160,46 @@ declare function isValidObjectId(value: string): boolean;
160
160
  declare function convertObjectIdsToStrings(obj: any): any;
161
161
 
162
162
  /**
163
- * Updates the dateStatus field for a single DateTimeType object based on the current date/time
163
+ * Updates the dateStatus field for a single DateTimeType object based on the current date/time.
164
+ * Manual statuses (CANCELED, RE_SCHEDULED) are preserved and returned as-is.
164
165
  * @param dateTime The date-time object to update
165
- * @returns A new object with updated dateStatus value
166
+ * @returns A new object with an updated dateStatus value, or the original
167
+ * object when the stored status is a manual override
166
168
  */
167
169
  declare function updateSingleDateTimeStatus<T extends DateTimeType>(dateTime: T, now?: dayjs.Dayjs): T;
168
170
  /**
169
- * Recomputes dateStatus for every dateTime slot on events and google imported markets.
171
+ * Recomputes dateStatus for every dateTime slot on events and google imported
172
+ * markets, moves ended event date slots into the event date archive, and keeps
173
+ * `EventInfo.dateTime` future-only.
170
174
  */
171
175
  declare function updateAllEventDateTimeStatuses(): Promise<void>;
172
176
 
177
+ /**
178
+ * Splits a recomputed event schedule into three buckets: slots to keep on the
179
+ * Event document (future + STARTED), ended slots to archive (`ENDED`), and
180
+ * invalid slots to discard (`INVALID` — removed from the Event but *not*
181
+ * archived). `Event.dateTime` may become empty once an event has no future or
182
+ * in-progress dates.
183
+ */
184
+ declare function splitEventDatesForArchive(dateTime: DateTimeType[]): {
185
+ archive: DateTimeType[];
186
+ discard: DateTimeType[];
187
+ keep: DateTimeType[];
188
+ };
189
+ /**
190
+ * De-duplicates the *input* slots on (startDate, startTime), keeping the first
191
+ * occurrence. This prevents a single write from appending near-duplicate
192
+ * history (the archive's `$addToSet` only de-dupes by deep equality, not by
193
+ * startDate/startTime). It does not scan or clean duplicates already stored in
194
+ * the archive document.
195
+ */
196
+ declare function dedupeArchivedSlotsByStartDateTime(slots: DateTimeType[]): DateTimeType[];
197
+ /**
198
+ * Persists archived slots into the event's archive document. Idempotent: the
199
+ * archive document is keyed per event and slots are appended with `$addToSet`.
200
+ */
201
+ declare function persistArchivedEventDates(eventId: ObjectId | string, slots: DateTimeType[]): Promise<void>;
202
+
173
203
  type EventOrMarket = (Pick<EventListItemType, "_id" | "name" | "dateTime"> & {
174
204
  /** Present on owned EventModel docs; absent on Google-imported markets. */
175
205
  owner?: SchemaOwnerType;
@@ -471,4 +501,4 @@ declare function checkOwnerHasLicence({ userId, resourceType, }: {
471
501
  resourceType: EnumResourceType;
472
502
  }): Promise<void>;
473
503
 
474
- export { ACTIVE_NOT_DELETED_FILTER, type AwardAffiliateVendorSubscriptionRewardsResult, LicenceCategory, type NotificationPubSub, REMINDER_WINDOW_MAX_HOURS, REMINDER_WINDOW_MIN_HOURS, SUBSCRIPTION_REWARD_TIMEZONE, activeAffiliateCodeExists, awardAffiliateVendorSubscriptionRewards, buildLicenceExpiryPipeline, checkOwnerHasLicence, connectToDatabase, convertObjectIdsToStrings, createLicenceObject, didRemoveAnyEventDates, downgradeVendorProFeatures, ensureUserLicenseCompliance, ensureUserLicenseComplianceForUser, eventLicences, findAffiliateByPromoCode, findEventOrImportedMarketById, getEventResourceInfo, getHighestLicenceForCategory, getLicenceCategory, getLicenceExpiryMode, getPartnerResourceInfo, getPayingEventStripeSubscriptionPlan, getPayingStripeSubscriptionPlan, getPayingVendorStripeSubscriptionPlan, getSubscriptionRewardPeriodBounds, getVendorResourceInfo, handleEventLicenceCompliance, handlePartnerLicenceCompliance, handleVendorLicenceCompliance, hasValidLicence, isStandardLicence, isValidObjectId, licenceCategoryMapping, licencePriority, mapVendorLicenceToSubscriptionRewardType, normalizeAffiliatePromoCodes, normalizePromoCode, notifyUsers, partnerLicences, processLicenseReminder, processUserCompliance, processUserLicenseReminders, publishNotificationEvents, remindUsersAboutLicenseExpiration, replaceUserLicenceWithObject, restoreVendorProFeatures, saveNotificationsInDb, sendDeactivationNotification, sendLicenseReminder, sendPushNotifications, sendReminderSafely, syncUserLicencesAfterExpiry, updateAdStatuses, updateAllEventDateTimeStatuses, updateRelationDatesToUnavailable, updateSingleDateTimeStatus, upgradeUserToLicence, vendorOwnerHasProLicence };
504
+ export { ACTIVE_NOT_DELETED_FILTER, type AwardAffiliateVendorSubscriptionRewardsResult, LicenceCategory, type NotificationPubSub, REMINDER_WINDOW_MAX_HOURS, REMINDER_WINDOW_MIN_HOURS, SUBSCRIPTION_REWARD_TIMEZONE, activeAffiliateCodeExists, awardAffiliateVendorSubscriptionRewards, buildLicenceExpiryPipeline, checkOwnerHasLicence, connectToDatabase, convertObjectIdsToStrings, createLicenceObject, dedupeArchivedSlotsByStartDateTime, didRemoveAnyEventDates, downgradeVendorProFeatures, ensureUserLicenseCompliance, ensureUserLicenseComplianceForUser, eventLicences, findAffiliateByPromoCode, findEventOrImportedMarketById, getEventResourceInfo, getHighestLicenceForCategory, getLicenceCategory, getLicenceExpiryMode, getPartnerResourceInfo, getPayingEventStripeSubscriptionPlan, getPayingStripeSubscriptionPlan, getPayingVendorStripeSubscriptionPlan, getSubscriptionRewardPeriodBounds, getVendorResourceInfo, handleEventLicenceCompliance, handlePartnerLicenceCompliance, handleVendorLicenceCompliance, hasValidLicence, isStandardLicence, isValidObjectId, licenceCategoryMapping, licencePriority, mapVendorLicenceToSubscriptionRewardType, normalizeAffiliatePromoCodes, normalizePromoCode, notifyUsers, partnerLicences, persistArchivedEventDates, processLicenseReminder, processUserCompliance, processUserLicenseReminders, publishNotificationEvents, remindUsersAboutLicenseExpiration, replaceUserLicenceWithObject, restoreVendorProFeatures, saveNotificationsInDb, sendDeactivationNotification, sendLicenseReminder, sendPushNotifications, sendReminderSafely, splitEventDatesForArchive, syncUserLicencesAfterExpiry, updateAdStatuses, updateAllEventDateTimeStatuses, updateRelationDatesToUnavailable, updateSingleDateTimeStatus, upgradeUserToLicence, vendorOwnerHasProLicence };
@@ -1,7 +1,7 @@
1
1
  import * as mongoose from 'mongoose';
2
2
  import * as _timardex_cluemart_shared from '@timardex/cluemart-shared';
3
3
  import { PromoCodeType, EnumAffiliateRewardType, DateTimeType, EventListItemType, DateTimeWithPriceType, EnumUserLicence as EnumUserLicence$1, UserLicenceType, EnumNotificationResourceType, EnumNotificationType, EnumResourceType, LicenceExpiryDate } from '@timardex/cluemart-shared';
4
- import { d as SchemaAffiliateResourceType, S as SchemaOwnerType, g as SchemaRelationType, j as SchemaUserType } from '../Affiliate-Dlf_OLIh.js';
4
+ import { d as SchemaAffiliateResourceType, S as SchemaOwnerType, g as SchemaRelationType, j as SchemaUserType } from '../Affiliate-BSF7Wm6O.js';
5
5
  import { O as ObjectId, G as GraphQLContext, e as SchemaCreateBulkNotificationInput } from '../index-Bq-lT7a2.js';
6
6
  import dayjs, { Dayjs } from 'dayjs';
7
7
  import { DateTimeType as DateTimeType$1 } from '@timardex/cluemart-shared/types';
@@ -160,16 +160,46 @@ declare function isValidObjectId(value: string): boolean;
160
160
  declare function convertObjectIdsToStrings(obj: any): any;
161
161
 
162
162
  /**
163
- * Updates the dateStatus field for a single DateTimeType object based on the current date/time
163
+ * Updates the dateStatus field for a single DateTimeType object based on the current date/time.
164
+ * Manual statuses (CANCELED, RE_SCHEDULED) are preserved and returned as-is.
164
165
  * @param dateTime The date-time object to update
165
- * @returns A new object with updated dateStatus value
166
+ * @returns A new object with an updated dateStatus value, or the original
167
+ * object when the stored status is a manual override
166
168
  */
167
169
  declare function updateSingleDateTimeStatus<T extends DateTimeType>(dateTime: T, now?: dayjs.Dayjs): T;
168
170
  /**
169
- * Recomputes dateStatus for every dateTime slot on events and google imported markets.
171
+ * Recomputes dateStatus for every dateTime slot on events and google imported
172
+ * markets, moves ended event date slots into the event date archive, and keeps
173
+ * `EventInfo.dateTime` future-only.
170
174
  */
171
175
  declare function updateAllEventDateTimeStatuses(): Promise<void>;
172
176
 
177
+ /**
178
+ * Splits a recomputed event schedule into three buckets: slots to keep on the
179
+ * Event document (future + STARTED), ended slots to archive (`ENDED`), and
180
+ * invalid slots to discard (`INVALID` — removed from the Event but *not*
181
+ * archived). `Event.dateTime` may become empty once an event has no future or
182
+ * in-progress dates.
183
+ */
184
+ declare function splitEventDatesForArchive(dateTime: DateTimeType[]): {
185
+ archive: DateTimeType[];
186
+ discard: DateTimeType[];
187
+ keep: DateTimeType[];
188
+ };
189
+ /**
190
+ * De-duplicates the *input* slots on (startDate, startTime), keeping the first
191
+ * occurrence. This prevents a single write from appending near-duplicate
192
+ * history (the archive's `$addToSet` only de-dupes by deep equality, not by
193
+ * startDate/startTime). It does not scan or clean duplicates already stored in
194
+ * the archive document.
195
+ */
196
+ declare function dedupeArchivedSlotsByStartDateTime(slots: DateTimeType[]): DateTimeType[];
197
+ /**
198
+ * Persists archived slots into the event's archive document. Idempotent: the
199
+ * archive document is keyed per event and slots are appended with `$addToSet`.
200
+ */
201
+ declare function persistArchivedEventDates(eventId: ObjectId | string, slots: DateTimeType[]): Promise<void>;
202
+
173
203
  type EventOrMarket = (Pick<EventListItemType, "_id" | "name" | "dateTime"> & {
174
204
  /** Present on owned EventModel docs; absent on Google-imported markets. */
175
205
  owner?: SchemaOwnerType;
@@ -471,4 +501,4 @@ declare function checkOwnerHasLicence({ userId, resourceType, }: {
471
501
  resourceType: EnumResourceType;
472
502
  }): Promise<void>;
473
503
 
474
- export { ACTIVE_NOT_DELETED_FILTER, type AwardAffiliateVendorSubscriptionRewardsResult, LicenceCategory, type NotificationPubSub, REMINDER_WINDOW_MAX_HOURS, REMINDER_WINDOW_MIN_HOURS, SUBSCRIPTION_REWARD_TIMEZONE, activeAffiliateCodeExists, awardAffiliateVendorSubscriptionRewards, buildLicenceExpiryPipeline, checkOwnerHasLicence, connectToDatabase, convertObjectIdsToStrings, createLicenceObject, didRemoveAnyEventDates, downgradeVendorProFeatures, ensureUserLicenseCompliance, ensureUserLicenseComplianceForUser, eventLicences, findAffiliateByPromoCode, findEventOrImportedMarketById, getEventResourceInfo, getHighestLicenceForCategory, getLicenceCategory, getLicenceExpiryMode, getPartnerResourceInfo, getPayingEventStripeSubscriptionPlan, getPayingStripeSubscriptionPlan, getPayingVendorStripeSubscriptionPlan, getSubscriptionRewardPeriodBounds, getVendorResourceInfo, handleEventLicenceCompliance, handlePartnerLicenceCompliance, handleVendorLicenceCompliance, hasValidLicence, isStandardLicence, isValidObjectId, licenceCategoryMapping, licencePriority, mapVendorLicenceToSubscriptionRewardType, normalizeAffiliatePromoCodes, normalizePromoCode, notifyUsers, partnerLicences, processLicenseReminder, processUserCompliance, processUserLicenseReminders, publishNotificationEvents, remindUsersAboutLicenseExpiration, replaceUserLicenceWithObject, restoreVendorProFeatures, saveNotificationsInDb, sendDeactivationNotification, sendLicenseReminder, sendPushNotifications, sendReminderSafely, syncUserLicencesAfterExpiry, updateAdStatuses, updateAllEventDateTimeStatuses, updateRelationDatesToUnavailable, updateSingleDateTimeStatus, upgradeUserToLicence, vendorOwnerHasProLicence };
504
+ export { ACTIVE_NOT_DELETED_FILTER, type AwardAffiliateVendorSubscriptionRewardsResult, LicenceCategory, type NotificationPubSub, REMINDER_WINDOW_MAX_HOURS, REMINDER_WINDOW_MIN_HOURS, SUBSCRIPTION_REWARD_TIMEZONE, activeAffiliateCodeExists, awardAffiliateVendorSubscriptionRewards, buildLicenceExpiryPipeline, checkOwnerHasLicence, connectToDatabase, convertObjectIdsToStrings, createLicenceObject, dedupeArchivedSlotsByStartDateTime, didRemoveAnyEventDates, downgradeVendorProFeatures, ensureUserLicenseCompliance, ensureUserLicenseComplianceForUser, eventLicences, findAffiliateByPromoCode, findEventOrImportedMarketById, getEventResourceInfo, getHighestLicenceForCategory, getLicenceCategory, getLicenceExpiryMode, getPartnerResourceInfo, getPayingEventStripeSubscriptionPlan, getPayingStripeSubscriptionPlan, getPayingVendorStripeSubscriptionPlan, getSubscriptionRewardPeriodBounds, getVendorResourceInfo, handleEventLicenceCompliance, handlePartnerLicenceCompliance, handleVendorLicenceCompliance, hasValidLicence, isStandardLicence, isValidObjectId, licenceCategoryMapping, licencePriority, mapVendorLicenceToSubscriptionRewardType, normalizeAffiliatePromoCodes, normalizePromoCode, notifyUsers, partnerLicences, persistArchivedEventDates, processLicenseReminder, processUserCompliance, processUserLicenseReminders, publishNotificationEvents, remindUsersAboutLicenseExpiration, replaceUserLicenceWithObject, restoreVendorProFeatures, saveNotificationsInDb, sendDeactivationNotification, sendLicenseReminder, sendPushNotifications, sendReminderSafely, splitEventDatesForArchive, syncUserLicencesAfterExpiry, updateAdStatuses, updateAllEventDateTimeStatuses, updateRelationDatesToUnavailable, updateSingleDateTimeStatus, upgradeUserToLicence, vendorOwnerHasProLicence };
@@ -1,6 +1,8 @@
1
1
  import {
2
2
  AdModel,
3
3
  AffiliateModel,
4
+ EventDateArchiveModel,
5
+ EventInfoModel,
4
6
  EventModel,
5
7
  GoogleImportedMarketModel,
6
8
  NotificationModel,
@@ -8,7 +10,7 @@ import {
8
10
  PushTokenModel,
9
11
  UserModel,
10
12
  VendorModel
11
- } from "../chunk-OVAGFPTP.mjs";
13
+ } from "../chunk-HLRUWJLN.mjs";
12
14
  import "../chunk-6PNG5BI5.mjs";
13
15
 
14
16
  // src/service/promoCode/constants.ts
@@ -614,34 +616,84 @@ function convertObjectIdsToStrings(obj) {
614
616
  // src/service/event/updateAllEventDateTimeStatuses.ts
615
617
  import {
616
618
  dateFormat,
617
- EnumEventDateStatus,
619
+ EnumEventDateStatus as EnumEventDateStatus2,
620
+ filterDatesByFutureStatus,
618
621
  timeFormat
619
622
  } from "@timardex/cluemart-shared";
620
623
  import dayjs2 from "dayjs";
621
624
  import customParseFormat from "dayjs/plugin/customParseFormat";
622
625
  import isoWeek from "dayjs/plugin/isoWeek";
626
+
627
+ // src/service/event/archiveEndedEventDates.ts
628
+ import { EnumEventDateStatus } from "@timardex/cluemart-shared";
629
+ var ARCHIVED_STATUSES = /* @__PURE__ */ new Set([
630
+ EnumEventDateStatus.ENDED
631
+ ]);
632
+ var DISCARDED_STATUSES = /* @__PURE__ */ new Set([
633
+ EnumEventDateStatus.INVALID
634
+ ]);
635
+ function splitEventDatesForArchive(dateTime) {
636
+ return {
637
+ archive: dateTime.filter((slot) => ARCHIVED_STATUSES.has(slot.dateStatus)),
638
+ discard: dateTime.filter((slot) => DISCARDED_STATUSES.has(slot.dateStatus)),
639
+ keep: dateTime.filter(
640
+ (slot) => !ARCHIVED_STATUSES.has(slot.dateStatus) && !DISCARDED_STATUSES.has(slot.dateStatus)
641
+ )
642
+ };
643
+ }
644
+ function dedupeArchivedSlotsByStartDateTime(slots) {
645
+ const seen = /* @__PURE__ */ new Set();
646
+ return slots.filter((slot) => {
647
+ const key = `${slot.startDate}_${slot.startTime}`;
648
+ if (seen.has(key)) {
649
+ return false;
650
+ }
651
+ seen.add(key);
652
+ return true;
653
+ });
654
+ }
655
+ async function persistArchivedEventDates(eventId, slots) {
656
+ if (slots.length === 0) {
657
+ return;
658
+ }
659
+ const uniqueSlots = dedupeArchivedSlotsByStartDateTime(slots);
660
+ await EventDateArchiveModel.updateOne(
661
+ { eventId },
662
+ { $addToSet: { dateTime: { $each: uniqueSlots } } },
663
+ { upsert: true }
664
+ );
665
+ }
666
+
667
+ // src/service/event/updateAllEventDateTimeStatuses.ts
623
668
  dayjs2.extend(customParseFormat);
624
669
  dayjs2.extend(isoWeek);
670
+ var MANUAL_DATE_STATUSES = /* @__PURE__ */ new Set([
671
+ EnumEventDateStatus2.CANCELED,
672
+ EnumEventDateStatus2.RE_SCHEDULED
673
+ ]);
625
674
  function getFutureEventStatus(startDateTime, now) {
626
675
  const hoursUntilStart = startDateTime.diff(now, "hour", true);
627
676
  if (hoursUntilStart > 0 && hoursUntilStart <= 4) {
628
- return EnumEventDateStatus.STARTING_SOON;
677
+ return EnumEventDateStatus2.STARTING_SOON;
629
678
  }
630
679
  if (startDateTime.isSame(now, "day")) {
631
- return EnumEventDateStatus.TODAY;
680
+ return EnumEventDateStatus2.TODAY;
632
681
  }
633
682
  if (startDateTime.isSame(now.add(1, "day"), "day")) {
634
- return EnumEventDateStatus.TOMORROW;
683
+ return EnumEventDateStatus2.TOMORROW;
635
684
  }
636
685
  if (startDateTime.isSame(now, "isoWeek")) {
637
- return EnumEventDateStatus.THIS_WEEK;
686
+ return EnumEventDateStatus2.THIS_WEEK;
638
687
  }
639
688
  if (startDateTime.isSame(now.add(1, "week"), "isoWeek")) {
640
- return EnumEventDateStatus.NEXT_WEEK;
689
+ return EnumEventDateStatus2.NEXT_WEEK;
641
690
  }
642
- return EnumEventDateStatus.UPCOMING;
691
+ return EnumEventDateStatus2.UPCOMING;
643
692
  }
644
693
  function updateSingleDateTimeStatus(dateTime, now = dayjs2()) {
694
+ if (MANUAL_DATE_STATUSES.has(dateTime.dateStatus)) {
695
+ return dateTime;
696
+ }
645
697
  const dateTimeFormat = `${dateFormat} ${timeFormat}`;
646
698
  const startDateTime = dayjs2(
647
699
  `${dateTime.startDate} ${dateTime.startTime}`,
@@ -656,13 +708,13 @@ function updateSingleDateTimeStatus(dateTime, now = dayjs2()) {
656
708
  if (!startDateTime.isValid() || !endDateTime.isValid()) {
657
709
  return {
658
710
  ...dateTime,
659
- dateStatus: EnumEventDateStatus.INVALID
711
+ dateStatus: EnumEventDateStatus2.INVALID
660
712
  };
661
713
  }
662
714
  if (endDateTime.isBefore(startDateTime)) {
663
715
  return {
664
716
  ...dateTime,
665
- dateStatus: EnumEventDateStatus.INVALID
717
+ dateStatus: EnumEventDateStatus2.INVALID
666
718
  };
667
719
  }
668
720
  let dateStatus;
@@ -670,10 +722,10 @@ function updateSingleDateTimeStatus(dateTime, now = dayjs2()) {
670
722
  if (startDateTime.isAfter(now)) {
671
723
  dateStatus = getFutureEventStatus(startDateTime, now);
672
724
  } else {
673
- dateStatus = EnumEventDateStatus.STARTED;
725
+ dateStatus = EnumEventDateStatus2.STARTED;
674
726
  }
675
727
  } else {
676
- dateStatus = EnumEventDateStatus.ENDED;
728
+ dateStatus = EnumEventDateStatus2.ENDED;
677
729
  }
678
730
  return {
679
731
  ...dateTime,
@@ -729,6 +781,111 @@ async function updateModelDateTimeStatuses(model, now) {
729
781
  }
730
782
  return updated;
731
783
  }
784
+ var ARCHIVABLE_EVENT_FILTER = {
785
+ "dateTime.dateStatus": {
786
+ $in: [EnumEventDateStatus2.ENDED, EnumEventDateStatus2.INVALID]
787
+ },
788
+ deletedAt: null
789
+ };
790
+ async function archiveEndedAndDiscardInvalidEventDates(now) {
791
+ const cursor = EventModel.find(ARCHIVABLE_EVENT_FILTER).select({ _id: 1, dateTime: 1 }).lean().cursor({ batchSize: CURSOR_BATCH_SIZE });
792
+ let archivedCount = 0;
793
+ let archiveOps = [];
794
+ let eventOps = [];
795
+ const flushBulkWrites = async () => {
796
+ if (archiveOps.length) {
797
+ await EventDateArchiveModel.bulkWrite(archiveOps);
798
+ archiveOps = [];
799
+ }
800
+ if (eventOps.length) {
801
+ await EventModel.bulkWrite(eventOps);
802
+ eventOps = [];
803
+ }
804
+ };
805
+ try {
806
+ for await (const doc of cursor) {
807
+ const updated = doc.dateTime.map(
808
+ (slot) => updateSingleDateTimeStatus(slot, now)
809
+ );
810
+ const { archive, discard } = splitEventDatesForArchive(updated);
811
+ if (archive.length === 0 && discard.length === 0) {
812
+ continue;
813
+ }
814
+ if (archive.length > 0) {
815
+ const uniqueArchive = dedupeArchivedSlotsByStartDateTime(archive);
816
+ archiveOps.push({
817
+ updateOne: {
818
+ filter: { eventId: doc._id },
819
+ update: { $addToSet: { dateTime: { $each: uniqueArchive } } },
820
+ upsert: true
821
+ }
822
+ });
823
+ archivedCount += uniqueArchive.length;
824
+ }
825
+ eventOps.push({
826
+ updateOne: {
827
+ filter: { _id: doc._id },
828
+ update: {
829
+ $pull: {
830
+ dateTime: {
831
+ dateStatus: {
832
+ $in: [EnumEventDateStatus2.ENDED, EnumEventDateStatus2.INVALID]
833
+ }
834
+ }
835
+ }
836
+ }
837
+ }
838
+ });
839
+ if (archiveOps.length >= CURSOR_BATCH_SIZE || eventOps.length >= CURSOR_BATCH_SIZE) {
840
+ await flushBulkWrites();
841
+ }
842
+ }
843
+ await flushBulkWrites();
844
+ } finally {
845
+ await cursor.close().catch(() => void 0);
846
+ }
847
+ return archivedCount;
848
+ }
849
+ var EVENT_INFO_DATE_FILTER = {
850
+ dateTime: { $ne: [], $type: "array" }
851
+ };
852
+ async function cleanEventInfoDates(now) {
853
+ const cursor = EventInfoModel.find(EVENT_INFO_DATE_FILTER).select({ _id: 1, dateTime: 1 }).lean().cursor({ batchSize: CURSOR_BATCH_SIZE });
854
+ let removedCount = 0;
855
+ let bulkOps = [];
856
+ const flushBulkWrites = async () => {
857
+ if (!bulkOps.length) {
858
+ return;
859
+ }
860
+ await EventInfoModel.bulkWrite(bulkOps);
861
+ bulkOps = [];
862
+ };
863
+ try {
864
+ for await (const doc of cursor) {
865
+ const updated = doc.dateTime.map(
866
+ (slot) => updateSingleDateTimeStatus(slot, now)
867
+ );
868
+ const kept = filterDatesByFutureStatus(updated);
869
+ if (kept.length === updated.length) {
870
+ continue;
871
+ }
872
+ bulkOps.push({
873
+ updateOne: {
874
+ filter: { _id: doc._id },
875
+ update: { $set: { dateTime: kept } }
876
+ }
877
+ });
878
+ removedCount += updated.length - kept.length;
879
+ if (bulkOps.length >= CURSOR_BATCH_SIZE) {
880
+ await flushBulkWrites();
881
+ }
882
+ }
883
+ await flushBulkWrites();
884
+ } finally {
885
+ await cursor.close().catch(() => void 0);
886
+ }
887
+ return removedCount;
888
+ }
732
889
  async function updateAllEventDateTimeStatuses() {
733
890
  const now = dayjs2();
734
891
  const [eventCount, marketCount] = await Promise.all([
@@ -741,6 +898,16 @@ async function updateAllEventDateTimeStatuses() {
741
898
  console.log(
742
899
  `\u2705 Event dateTime statuses updated: events=${eventCount} changed, google imported markets=${marketCount} changed`
743
900
  );
901
+ const archivedCount = await archiveEndedAndDiscardInvalidEventDates(now);
902
+ if (archivedCount > 0) {
903
+ console.log(`\u2705 Archived ${archivedCount} ended event date slot(s)`);
904
+ }
905
+ const removedEventInfoCount = await cleanEventInfoDates(now);
906
+ if (removedEventInfoCount > 0) {
907
+ console.log(
908
+ `\u2705 Removed ${removedEventInfoCount} non-future event info date slot(s)`
909
+ );
910
+ }
744
911
  }
745
912
 
746
913
  // src/service/event/findEventOrImportedMarketById.ts
@@ -1915,6 +2082,7 @@ export {
1915
2082
  connectToDatabase,
1916
2083
  convertObjectIdsToStrings,
1917
2084
  createLicenceObject,
2085
+ dedupeArchivedSlotsByStartDateTime,
1918
2086
  didRemoveAnyEventDates,
1919
2087
  downgradeVendorProFeatures,
1920
2088
  ensureUserLicenseCompliance,
@@ -1945,6 +2113,7 @@ export {
1945
2113
  normalizePromoCode,
1946
2114
  notifyUsers,
1947
2115
  partnerLicences,
2116
+ persistArchivedEventDates,
1948
2117
  processLicenseReminder,
1949
2118
  processUserCompliance,
1950
2119
  processUserLicenseReminders,
@@ -1957,6 +2126,7 @@ export {
1957
2126
  sendLicenseReminder,
1958
2127
  sendPushNotifications,
1959
2128
  sendReminderSafely,
2129
+ splitEventDatesForArchive,
1960
2130
  syncUserLicencesAfterExpiry,
1961
2131
  updateAdStatuses,
1962
2132
  updateAllEventDateTimeStatuses,