All files / server/src/features/assignment/utils removeInvalidProgramItemsFromUsers.ts

93.67% Statements 74/79
88.88% Branches 40/45
100% Functions 18/18
93.67% Lines 74/79

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261                                                                                  54x               400x   400x 400x     400x 400x     400x   400x     26177x   2615x   218144x   2615x         2615x           2615x       26177x 28130x 28122x   26177x   2615x                     26177x   26177x 20x               26177x 18x 20x   18x       26177x   26177x 5x           26177x       23x           23x             26172x     400x 400x         400x 23x 35x         23x         23x         400x       54x     2615x 9x   2612x 7x   2608x 7x   2600x 9x   2593x     54x         23x   23x   22x 16x   22x 1x   21x       23x   23x 1x   22x                 23x   6x 1x     5x                 23x   27x       23x 22x 22x       22x     23x    
import dayjs from "dayjs";
import { partition, uniqueBy } from "remeda";
import { DirectSignupsForProgramItem } from "server/features/direct-signup/directSignupTypes";
import { addEventLogItems } from "server/features/user/event-log/eventLogRepository";
import { queueCancelledDeletedEmails } from "server/features/notifications/queueCancelledDeletedEmails";
import {
  findUsers,
  updateUsersByUsername,
} from "server/features/user/userRepository";
import { logger } from "server/utils/logger";
import { MongoDbError } from "shared/types/api/errors";
import { EventLogAction } from "shared/types/models/eventLog";
import {
  ProgramItem,
  SignupType,
  State,
} from "shared/types/models/programItem";
import { FavoriteProgramItemId, LotterySignup } from "shared/types/models/user";
import { Result, makeSuccessResult } from "shared/utils/result";
import { getTimeNow } from "server/features/assignment/utils/getTimeNow";
import { getLotterySignupEndTime } from "shared/utils/signupTimes";
import { isLotterySignupProgramItem } from "shared/utils/isLotterySignupProgramItem";
 
interface InvalidLotterySignup {
  lotterySignup: LotterySignup;
  action: EventLogAction;
}
 
interface UserToNofify {
  username: string;
  invalidLotterySignups: InvalidLotterySignup[];
  invalidFavoriteProgramItemIds: FavoriteProgramItemId[];
}
 
interface RemoveCancelledDeletedProgramItemsFromUsersParams {
  programItems: readonly ProgramItem[];
  currentProgramItems: readonly ProgramItem[];
  notifyAffectedDirectSignups: DirectSignupsForProgramItem[];
  notify: boolean;
}
 
export const removeCancelledDeletedProgramItemsFromUsers = async ({
  programItems,
  currentProgramItems,
  notifyAffectedDirectSignups,
  notify,
}: RemoveCancelledDeletedProgramItemsFromUsersParams): Promise<
  Result<void, MongoDbError>
> => {
  logger.info("Remove invalid program items from users");
 
  const timeNowResult = await getTimeNow();
  Iif (!timeNowResult.ok) {
    return timeNowResult;
  }
  const usersResult = await findUsers();
  Iif (!usersResult.ok) {
    return usersResult;
  }
  const usersToNofify: UserToNofify[] = [];
 
  const usersToUpdate = usersResult.value.flatMap((user) => {
    // LOTTERY SIGNUPS
 
    const classifiedLotterySignups = user.lotterySignups.map(
      (lotterySignup) => {
        const foundProgramItem = programItems.find(
          (programItem) =>
            programItem.programItemId === lotterySignup.programItemId,
        );
        const cancellationAction = getCancellationAction(foundProgramItem);
 
        // Valid signups are kept. Invalid ones are preserved only if the item still
        // exists and its lottery has already run; deleted items are always removed
        const keep =
          cancellationAction === undefined ||
          (foundProgramItem !== undefined &&
            !timeNowResult.value.isBefore(
              getLotterySignupEndTime(foundProgramItem),
            ));
 
        return { lotterySignup, keep, cancellationAction };
      },
    );
 
    const keepLotterySignups = classifiedLotterySignups
      .filter((classified) => classified.keep)
      .map((classified) => classified.lotterySignup);
 
    const removeLotterySignups = classifiedLotterySignups.flatMap(
      (classified) =>
        !classified.keep && classified.cancellationAction !== undefined
          ? [
              {
                lotterySignup: classified.lotterySignup,
                action: classified.cancellationAction,
              },
            ]
          : [],
    );
 
    const changedLotterySignupsCount =
      user.lotterySignups.length - keepLotterySignups.length;
 
    if (changedLotterySignupsCount > 0) {
      logger.info(
        `Remove ${changedLotterySignupsCount} cancelled/removed lotterySignups from user ${user.username}`,
      );
    }
 
    // FAVORITES — removed only when the program item is deleted from DB
 
    const [validFavoriteProgramItemIds, invalidFavoriteProgramItemIds] =
      partition(user.favoriteProgramItemIds, (favoriteProgramItemId) => {
        const foundProgramItem = programItems.find(
          (programItem) => programItem.programItemId === favoriteProgramItemId,
        );
        return foundProgramItem !== undefined;
      });
 
    const changedFavoriteProgramItemIdsCount =
      user.favoriteProgramItemIds.length - validFavoriteProgramItemIds.length;
 
    if (changedFavoriteProgramItemIdsCount > 0) {
      logger.info(
        `Remove ${changedFavoriteProgramItemIdsCount} cancelled/removed favorite program items from user ${user.username}`,
      );
    }
 
    // UPDATES
    if (
      changedLotterySignupsCount > 0 ||
      changedFavoriteProgramItemIdsCount > 0
    ) {
      usersToNofify.push({
        username: user.username,
        invalidLotterySignups: removeLotterySignups,
        invalidFavoriteProgramItemIds,
      });
 
      return {
        ...user,
        lotterySignups: keepLotterySignups,
        favoriteProgramItemIds: validFavoriteProgramItemIds,
      };
    }
 
    return [];
  });
 
  const updateUsersResult = await updateUsersByUsername(usersToUpdate);
  Iif (!updateUsersResult.ok) {
    return updateUsersResult;
  }
 
  // Nofify users with cancelled or deleted program items
  if (notify && usersToNofify.length > 0) {
    const programItemTitlesById = new Map(
      [...programItems, ...currentProgramItems].map((programItem) => [
        programItem.programItemId,
        programItem.title,
      ]),
    );
    const notifyUsersResult = await notifyUsersWithLotterySignupOrFavorite(
      usersToNofify,
      notifyAffectedDirectSignups,
      programItemTitlesById,
    );
    Iif (!notifyUsersResult.ok) {
      return notifyUsersResult;
    }
  }
 
  return makeSuccessResult();
};
 
// Classifies why a lottery signup program item is invalid, or undefined when it is still valid
const getCancellationAction = (
  programItem: ProgramItem | undefined,
): EventLogAction | undefined => {
  if (!programItem) {
    return EventLogAction.PROGRAM_ITEM_DELETED;
  }
  if (programItem.state !== State.ACCEPTED) {
    return EventLogAction.PROGRAM_ITEM_CANCELLED;
  }
  if (programItem.signupType !== SignupType.KONSTI) {
    return EventLogAction.PROGRAM_ITEM_NO_KONSTI_SIGNUP_ANYMORE;
  }
  if (!isLotterySignupProgramItem(programItem)) {
    return EventLogAction.PROGRAM_ITEM_NO_LOTTERY_ANYMORE;
  }
  return undefined;
};
 
const notifyUsersWithLotterySignupOrFavorite = async (
  usersToNofify: UserToNofify[],
  affectedDirectSignups: DirectSignupsForProgramItem[],
  programItemTitlesById: Map<string, string>,
): Promise<Result<void, MongoDbError>> => {
  const eventUpdates = usersToNofify.flatMap((user) => {
    // If user has already been notified of program item cancel/delete because of a direct signup, don't resend
    const userDirectSignups = new Set(
      affectedDirectSignups.flatMap((directSignup) => {
        const found = directSignup.userSignups.some(
          (userSignup) => userSignup.username === user.username,
        );
        if (found) {
          return directSignup.programItemId;
        }
        return [];
      }),
    );
 
    const lotteryUpdates = user.invalidLotterySignups.flatMap(
      ({ lotterySignup, action }) => {
        if (userDirectSignups.has(lotterySignup.programItemId)) {
          return [];
        }
        return {
          username: user.username,
          programItemId: lotterySignup.programItemId,
          programItemStartTime: lotterySignup.signedToStartTime,
          createdAt: dayjs().toISOString(),
          action,
        };
      },
    );
    const favoriteUpdates = user.invalidFavoriteProgramItemIds.flatMap(
      (favorite) => {
        if (userDirectSignups.has(favorite)) {
          return [];
        }
        // Favorites are removed only when the program item is deleted
        return {
          username: user.username,
          programItemId: favorite,
          programItemStartTime: dayjs().toISOString(),
          createdAt: dayjs().toISOString(),
          action: EventLogAction.PROGRAM_ITEM_DELETED,
        };
      },
    );
    return uniqueBy(
      [...lotteryUpdates, ...favoriteUpdates],
      (update) => update.programItemId,
    );
  });
 
  if (eventUpdates.length > 0) {
    const addEventLogItemsResult = await addEventLogItems(eventUpdates);
    Iif (!addEventLogItemsResult.ok) {
      return addEventLogItemsResult;
    }
 
    await queueCancelledDeletedEmails(eventUpdates, programItemTitlesById);
  }
 
  return makeSuccessResult();
};