All files / server/src/features/program-item programItemRepository.ts

76.27% Statements 90/118
64.7% Branches 22/34
100% Functions 17/17
76.27% Lines 90/118

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 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398                                                  60x     525x       525x 525x     525x                 60x     603x   603x 603x     603x     603x       603x           603x           603x       603x       603x             603x 603x     603x   603x         603x     603x 603x 335x                   603x     603x       603x       8743x                                                               8743x           8743x                           603x 603x 603x               603x     2637x     603x     603x 456x   603x     8743x   2377x   603x   502x     502x         603x     60x     1830x 1830x 1830x   1830x 26988x 26988x                 26988x     1830x                 60x     524x   524x 524x     524x 8x   520x 520x               520x                               60x     114x 102x     60x 12x       12x     12x                             60x     114x 5x     109x 109x 181x                 109x     109x                         60x     1x 1x       1x 1x                 60x     28x 3x                       28x 28x 28x     28x                
import { MongoDbError } from "shared/types/api/errors";
import { Popularity, ProgramItem } from "shared/types/models/programItem";
import { differenceBy } from "shared/utils/remedaExtend";
import {
  Result,
  makeErrorResult,
  makeSuccessResult,
} from "shared/utils/result";
import { removeCancelledDeletedProgramItemsFromUsers } from "server/features/assignment/utils/removeInvalidProgramItemsFromUsers";
import { updateMovedProgramItems } from "server/features/assignment/utils/updateMovedProgramItems";
import {
  createEmptyDirectSignupDocumentForProgramItems,
  findDirectSignups,
} from "server/features/direct-signup/directSignupRepository";
import {
  getPassedOverProgramItems,
  removePassedOverLotterySignups,
} from "server/features/program-item/passedOverProgramItems";
import {
  ProgramItemModel,
  ProgramItemSchemaDb,
} from "server/features/program-item/programItemSchema";
import { handleCancelledDeletedProgramItems } from "server/features/program-item/programItemUtils";
import { logger } from "server/utils/logger";
 
export const removeProgramItems = async (
  programItemIds?: string[],
): Promise<Result<void, MongoDbError>> => {
  logger.info(
    `MongoDB: remove program items from db: ${programItemIds ? programItemIds.join(", ") : "ALL"}`,
  );
 
  try {
    await ProgramItemModel.deleteMany(
      programItemIds ? { programItemId: { $in: programItemIds } } : {},
    );
    return makeSuccessResult();
  } catch (error) {
    logger.error(
      new Error("MongoDB: Error removing program items", { cause: error }),
    );
    return makeErrorResult(MongoDbError.UNKNOWN_ERROR);
  }
};
 
export const saveProgramItems = async (
  updatedProgramItems: readonly ProgramItem[],
): Promise<Result<void, MongoDbError>> => {
  logger.info("MongoDB: Store program items to DB");
 
  const currentProgramItemsResult = await findProgramItems();
  Iif (!currentProgramItemsResult.ok) {
    return currentProgramItemsResult;
  }
  const currentProgramItems = currentProgramItemsResult.value;
 
  // If program item was cancelled or deleted, remove program item and direct sign-ups
  const deletedProgramItemsResult = await handleCancelledDeletedProgramItems(
    updatedProgramItems,
    currentProgramItems,
  );
  Iif (!deletedProgramItemsResult.ok) {
    return deletedProgramItemsResult;
  }
 
  // If program item was cancelled or deleted, remove lottery sign-ups and favorite program items
  const removeCancelledDeletedProgramItemsFromUsersResult =
    await removeCancelledDeletedProgramItemsFromUsers({
      programItems: updatedProgramItems,
      currentProgramItems,
      notifyAffectedDirectSignups: deletedProgramItemsResult.value,
      notify: true,
    });
  Iif (!removeCancelledDeletedProgramItemsFromUsersResult.ok) {
    return removeCancelledDeletedProgramItemsFromUsersResult;
  }
 
  const updateMovedProgramItemsResult = await updateMovedProgramItems(
    updatedProgramItems,
    currentProgramItems,
  );
  Iif (!updateMovedProgramItemsResult.ok) {
    return updateMovedProgramItemsResult;
  }
 
  // Read before the write, so the marks below go in with the change that makes them true and the
  // program item is never stored as a lottery item without one. Direct sign-ups are settled by
  // now: the cancelled and deleted handling above is what last touched them.
  const directSignupsResult = await findDirectSignups();
  Iif (!directSignupsResult.ok) {
    return directSignupsResult;
  }
  const directSignups = directSignupsResult.value;
 
  const passedOverProgramItemsResult = await getPassedOverProgramItems(
    updatedProgramItems,
    currentProgramItems,
    directSignups,
  );
  Iif (!passedOverProgramItemsResult.ok) {
    return passedOverProgramItemsResult;
  }
  const passedOverProgramItems = passedOverProgramItemsResult.value;
  const passedOverProgramItemIds = new Set(
    passedOverProgramItems.map((programItem) => programItem.programItemId),
  );
 
  // Normally there is nothing to remove: a program item is passed over for holding direct
  // sign-ups, and having those means its lottery is over, so any sign-up for it is a past one
  // this leaves alone. Defence in depth for the orders that arrive out of the ordinary.
  //
  // Done before the decision is stored, so a failure here leaves the program item undecided and
  // the next import tries again. Recording it first and failing after would strand the sign-ups
  // for good: the item would be filtered out as already decided every time from then on.
  const removeLotterySignupsResult = await removePassedOverLotterySignups(
    passedOverProgramItems,
  );
  Iif (!removeLotterySignupsResult.ok) {
    return removeLotterySignupsResult;
  }
 
  const bulkOps = updatedProgramItems.map((programItem) => {
    const newProgramItem: Omit<
      ProgramItem,
      "popularity" | "lotteryRanForStartTime" | "passedOverForLottery"
    > = {
      programItemId: programItem.programItemId,
      parentId: programItem.parentId,
      title: programItem.title,
      description: programItem.description,
      location: programItem.location,
      startTime: programItem.startTime,
      mins: programItem.mins,
      tags: programItem.tags,
      ageGroups: programItem.ageGroups,
      genres: programItem.genres,
      styles: programItem.styles,
      languages: programItem.languages,
      endTime: programItem.endTime,
      people: programItem.people,
      minAttendance: programItem.minAttendance,
      maxAttendance: programItem.maxAttendance,
      gameSystem: programItem.gameSystem,
      shortDescription: programItem.shortDescription,
      revolvingDoor: programItem.revolvingDoor,
      programType: programItem.programType,
      contentWarnings: programItem.contentWarnings,
      otherAuthor: programItem.otherAuthor,
      accessibilityValues: programItem.accessibilityValues,
      otherAccessibilityInformation: programItem.otherAccessibilityInformation,
      entryFee: programItem.entryFee,
      signupType: programItem.signupType,
      state: programItem.state,
    };
 
    // Otherwise the import's to leave alone, so it is set here only for a program item this
    // save is what turns into a passed over one
    const passedOverForLottery = passedOverProgramItemIds.has(
      programItem.programItemId,
    )
      ? { passedOverForLottery: true }
      : {};
 
    return {
      updateOne: {
        filter: {
          programItemId: programItem.programItemId,
        },
        update: {
          ...newProgramItem,
          ...passedOverForLottery,
        },
        upsert: true,
      },
    };
  });
 
  try {
    await ProgramItemModel.bulkWrite(bulkOps);
    logger.debug("MongoDB: Program items saved to DB successfully");
  } catch (error) {
    logger.error(
      new Error("Error saving program items to DB", { cause: error }),
    );
    return makeErrorResult(MongoDbError.UNKNOWN_ERROR);
  }
 
  const newProgramItems = differenceBy(
    updatedProgramItems,
    currentProgramItems,
    (programItem) => programItem.programItemId,
  );
 
  logger.info(`MongoDB: Found ${newProgramItems.length} new program items`);
 
  // Create sign-up document for all program items missing sign-up document
  const programItemIdsWithSignupDoc = new Set(
    directSignups.map((directSignup) => directSignup.programItemId),
  );
  const directSignupDocMissingProgramItemIds = updatedProgramItems
    .filter(
      (updatedProgramItem) =>
        !programItemIdsWithSignupDoc.has(updatedProgramItem.programItemId),
    )
    .map((updatedProgramItem) => updatedProgramItem.programItemId);
 
  if (directSignupDocMissingProgramItemIds.length > 0) {
    const createEmptySignupResult =
      await createEmptyDirectSignupDocumentForProgramItems(
        directSignupDocMissingProgramItemIds,
      );
    Iif (!createEmptySignupResult.ok) {
      return createEmptySignupResult;
    }
  }
 
  return makeSuccessResult();
};
 
export const findProgramItems = async (): Promise<
  Result<ProgramItem[], MongoDbError>
> => {
  try {
    const response = await ProgramItemModel.find({}).lean();
    logger.debug("MongoDB: Find all program items");
 
    const programItems = response.flatMap((programItem) => {
      const result = ProgramItemSchemaDb.safeParse(programItem);
      Iif (!result.success) {
        logger.error(
          new Error(
            `Error validating findProgramItems DB value: programItemId: ${programItem.programItemId}`,
            { cause: result.error },
          ),
        );
        return [];
      }
      return result.data;
    });
 
    return makeSuccessResult(programItems);
  } catch (error) {
    logger.error(
      new Error("MongoDB: Error fetching program items", { cause: error }),
    );
    return makeErrorResult(MongoDbError.UNKNOWN_ERROR);
  }
};
 
export const findProgramItemById = async (
  programItemId: string,
): Promise<Result<ProgramItem, MongoDbError>> => {
  logger.debug(`MongoDB: Find program item with id ${programItemId}`);
 
  try {
    const response = await ProgramItemModel.findOne({
      programItemId,
    }).lean();
    if (!response) {
      return makeErrorResult(MongoDbError.PROGRAM_ITEM_NOT_FOUND);
    }
    const result = ProgramItemSchemaDb.safeParse(response);
    Iif (!result.success) {
      logger.error(
        new Error(`Error validating findProgramItemById DB value`, {
          cause: result.error,
        }),
      );
      return makeErrorResult(MongoDbError.UNKNOWN_ERROR);
    }
    return makeSuccessResult(result.data);
  } catch (error) {
    logger.error(
      new Error("MongoDB: Error fetching programItemId", { cause: error }),
    );
    return makeErrorResult(MongoDbError.UNKNOWN_ERROR);
  }
};
 
interface PopularityUpdate {
  programItemId: string;
  popularity: Popularity;
}
 
// Recorded rather than worked out later: whether a lottery will take a program item must not
// change as the clock moves past its sign-up window
export const savePassedOverForLottery = async (
  programItemIds: readonly string[],
): Promise<Result<void, MongoDbError>> => {
  if (programItemIds.length === 0) {
    return makeSuccessResult();
  }
 
  try {
    await ProgramItemModel.updateMany(
      { programItemId: { $in: programItemIds } },
      { passedOverForLottery: true },
    );
    logger.info(
      `MongoDB: Recorded ${programItemIds.length} program items as passed over for the lottery`,
    );
    return makeSuccessResult();
  } catch (error) {
    logger.error(
      new Error("MongoDB: Error recording program items as passed over", {
        cause: error,
      }),
    );
    return makeErrorResult(MongoDbError.UNKNOWN_ERROR);
  }
};
 
// The start time each program item was sitting at when its lottery ran. A time rather than a
// flag, so one moved onto another slot afterwards can be told from one still where it was
// lotteried - and each item's own start time rather than the run's, because a batch's parent
// time is the same before and after a move and so could never tell the two apart.
export const saveLotteryRanForStartTime = async (
  programItems: readonly ProgramItem[],
): Promise<Result<void, MongoDbError>> => {
  if (programItems.length === 0) {
    return makeSuccessResult();
  }
 
  try {
    await ProgramItemModel.bulkWrite(
      programItems.map((programItem) => ({
        updateOne: {
          filter: { programItemId: programItem.programItemId },
          update: {
            lotteryRanForStartTime: new Date(programItem.startTime),
          },
        },
      })),
    );
    logger.info(
      `MongoDB: Marked ${programItems.length} program items as lotteried`,
    );
    return makeSuccessResult();
  } catch (error) {
    logger.error(
      new Error("MongoDB: Error marking program items as lotteried", {
        cause: error,
      }),
    );
    return makeErrorResult(MongoDbError.UNKNOWN_ERROR);
  }
};
 
// Undoes both lottery marks across the collection. Only the data generators need this: they
// simulate a lottery and must be able to re-simulate it without dropping the program items.
export const removeLotteryMarks = async (): Promise<
  Result<void, MongoDbError>
> => {
  try {
    await ProgramItemModel.updateMany(
      {},
      { $unset: { lotteryRanForStartTime: "", passedOverForLottery: "" } },
    );
    logger.info("MongoDB: Lottery marks removed from program items");
    return makeSuccessResult();
  } catch (error) {
    logger.error(
      new Error("MongoDB: Error removing lottery marks", { cause: error }),
    );
    return makeErrorResult(MongoDbError.UNKNOWN_ERROR);
  }
};
 
export const saveProgramItemPopularity = async (
  popularityUpdates: PopularityUpdate[],
): Promise<Result<void, MongoDbError>> => {
  const bulkOps = popularityUpdates.map((popularityUpdate) => {
    return {
      updateOne: {
        filter: {
          programItemId: popularityUpdate.programItemId,
        },
        update: {
          popularity: popularityUpdate.popularity,
        },
      },
    };
  });
 
  try {
    await ProgramItemModel.bulkWrite(bulkOps);
    logger.info(
      `MongoDB: Updated popularity for ${popularityUpdates.length} program items`,
    );
    return makeSuccessResult();
  } catch (error) {
    logger.error(
      new Error("Error updating program item popularity", { cause: error }),
    );
    return makeErrorResult(MongoDbError.UNKNOWN_ERROR);
  }
};