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

93.97% Statements 78/83
89.36% Branches 42/47
100% Functions 20/20
93.97% Lines 78/83

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 262 263 264 265 266 267 268 269 270 271                                                                                      60x               717x   717x 717x     717x 717x         717x   5397x 440x   717x   717x     50342x   3056x   141024x   3056x           3056x       3056x   3056x       50342x 52478x 52469x   50342x   3056x                     50342x   50342x 21x               50342x 18x 20x   18x       50342x   50342x 5x           50342x       24x           24x             50336x     717x 717x         717x 23x 35x         23x         23x         717x       60x     3056x 10x   3052x 8x   3047x 7x   3043x 12x   3037x     60x         23x   23x   22x 16x   22x 1x   21x       23x   23x 1x   22x                 23x   6x 1x     5x                 23x   27x       23x 22x 22x       22x     23x    
import { partition, uniqueBy } from "remeda";
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 { isLotterySignupProgramItem } from "shared/utils/isLotterySignupProgramItem";
import { Result, makeSuccessResult } from "shared/utils/result";
import {
  getLotterySignupEnded,
  lotteryRanForProgramItem,
} from "shared/utils/signupTimes";
import { getTimeNow } from "server/features/assignment/utils/getTimeNow";
import { DirectSignupsForProgramItem } from "server/features/direct-signup/directSignupTypes";
import { queueCancelledDeletedEmails } from "server/features/notifications/queueCancelledDeletedEmails";
import { addEventLogItems } from "server/features/user/event-log/eventLogRepository";
import {
  findUsers,
  updateUsersByUsername,
} from "server/features/user/userRepository";
import { logger } from "server/utils/logger";
 
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;
  }
  // From whichever list carries the mark: the incoming programme never does, and the
  // pre-assignment caller passes no stored programme but reads its items from the database
  const lotteriedProgramItemIds = new Set(
    [...programItems, ...currentProgramItems]
      .filter((programItem) => lotteryRanForProgramItem(programItem))
      .map((programItem) => programItem.programItemId),
  );
  const usersToNofify: UserToNofify[] = [];
 
  const usersToUpdate = usersResult.value.flatMap((user) => {
    // LOTTERY SIGN-UPS
 
    const classifiedLotterySignups = user.lotterySignups.map(
      (lotterySignup) => {
        const foundProgramItem = programItems.find(
          (programItem) =>
            programItem.programItemId === lotterySignup.programItemId,
        );
        const cancellationAction = getCancellationAction(foundProgramItem);
 
        // Valid sign-ups are kept. Invalid ones are preserved once their lottery has run;
        // a deleted program item has none to ask, so those are always removed. The mark is
        // asked alongside the window, which a move to a later slot reopens.
        const lotteryAlreadyRan =
          foundProgramItem !== undefined &&
          (lotteriedProgramItemIds.has(lotterySignup.programItemId) ||
            getLotterySignupEnded(foundProgramItem, timeNowResult.value));
 
        const keep = cancellationAction === undefined || lotteryAlreadyRan;
 
        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 sign-up 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 sign-up, 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: new Date().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: new Date().toISOString(),
          createdAt: new Date().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();
};