All files / lib/lambda/update updatePackage.ts

96.84% Statements 92/95
89.39% Branches 59/66
100% Functions 8/8
96.84% Lines 92/95

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 399                                  1x         3x 3x 1x     2x 1x         1x 1x     1x                                     1x                       1x           3x 3x 1x   2x 2x       2x                                     2x                               2x                               1x                     7x 7x 1x   6x 6x           6x 6x   6x 1x           5x 3x 1x         2x   2x           2x 2x   2x 1x             3x 1x           2x 2x       2x   2x                                 2x                           1x                     7x 7x 1x               6x 6x 2x           4x 4x 1x           3x 3x   2x 2x   2x 1x           1x   1x                                   1x 1x           1x                 1x 23x 1x         22x 22x 20x   22x       22x 22x       22x 2x                       20x   20x 20x 1x           19x 2x   17x 3x   14x 7x     7x 7x               5x 5x           5x            
import { APIGatewayEvent } from "aws-lambda";
import { produceMessage } from "libs/api/kafka";
import { getPackage } from "libs/api/package";
import { response } from "libs/handler-lib";
import { events } from "shared-types";
import { ItemResult } from "shared-types/opensearch/main";
import { z } from "zod";
 
import { getPackageType } from "./getPackageType";
 
/** @typedef {object} json
 * @property {object} body
 * @property {string} body.packageId
 * @property {string} body.action
 * @property {string} body.changeMade
 * @property {string} body.changeReason
 */
const sendRecoverMessage = async (
  currentPackage: ItemResult,
  changeMade: string,
  changeReason: string,
) => {
  const topicName = process.env.topicName as string;
  if (!topicName) {
    throw new Error("Topic name is not defined");
  }
 
  if (!currentPackage._source.id.endsWith("del")) {
    return response({
      statusCode: 200,
      body: { message: `${currentPackage._source.id} is not a deleted package.` },
    });
  }
  const packageId = currentPackage._source.id.split(/-del/i)[0];
  const currentTime = Date.now();
 
  // Making a copy of the previous package and deleting it
  await produceMessage(
    topicName,
    packageId,
    JSON.stringify({
      ...currentPackage._source,
      id: packageId,
      idToBeUpdated: currentPackage._id,
      deleted: false,
      isAdminChange: true,
      adminChangeType: "update-id",
      changeMade,
      changeReason,
      makoChangedDate: currentTime,
      changedDate: currentTime,
      statusDate: currentTime,
      timestamp: currentTime,
    }),
  );
 
  return response({
    statusCode: 200,
    body: { message: `${packageId} has been recovered.` },
  });
};
/** @typedef {object} json
 * @property {object} body
 * @property {string} body.packageId
 * @property {string} body.action
 * @property {string} body.changeMade
 * @property {string} body.changeReason
 */
const sendDeleteMessage = async (
  currentPackage: ItemResult,
  changeMade: string,
  changeReason: string,
  timestamp?: number,
) => {
  const topicName = process.env.topicName as string;
  if (!topicName) {
    throw new Error("Topic name is not defined");
  }
  const packageId = currentPackage._source.id;
  const currentTime = timestamp || Date.now();
 
  // Making a copy of the previous package and deleting it
 
  await produceMessage(
    topicName,
    packageId + "-del",
    JSON.stringify({
      ...currentPackage._source,
      id: packageId + "-del",
      deleted: true,
      idToBeUpdated: currentPackage._id,
      origin: "OneMAC",
      changeMade,
      changeReason,
      isAdminChange: true,
      adminChangeType: "update-id",
      makoChangedDate: currentTime,
      changedDate: currentTime,
      statusDate: currentTime,
      timestamp: currentTime,
    }),
  );
  await produceMessage(
    topicName,
    packageId,
    JSON.stringify({
      id: packageId,
      deleted: true,
      isAdminChange: true,
      adminChangeType: "delete",
      changeMade,
      changeReason,
      makoChangedDate: currentTime,
      changedDate: currentTime,
      statusDate: currentTime,
      timestamp: currentTime,
    }),
  );
  return response({
    statusCode: 200,
    body: { message: `${packageId} has been deleted.` },
  });
};
 
/** @typedef {object} json
 * @property {object} body
 * @property {string} body.packageId
 * @property {string} body.action
 * @property {object} body.updatedFields
 * @property {string} body.updatedFields.title
 * @property {string} body.changeMade
 * @property {string} body.changeReason
 */
 
const sendUpdateValuesMessage = async ({
  currentPackage,
  updatedFields,
  changeMade,
  changeReason,
}: {
  currentPackage: ItemResult;
  updatedFields: object;
  changeMade: string;
  changeReason: string;
}) => {
  const topicName = process.env.topicName as string;
  if (!topicName) {
    throw new Error("Topic name is not defined");
  }
  const allowedNewFields = new Set(["chipSubmissionType"]);
  const allowedChipSubmissionTypes = new Set([
    "MAGI Eligibility and Methods",
    "Non-Financial Eligibility",
    "XXI Medicaid Expansion",
    "Eligibility Process",
  ]);
  const invalidFields = Object.keys(updatedFields).filter(
    (field) => !(field in currentPackage._source) && !allowedNewFields.has(field),
  );
  if (invalidFields.length > 0) {
    return response({
      statusCode: 400,
      body: { message: `Cannot update invalid field(s): ${invalidFields.join(", ")}` },
    });
  }
 
  if ("chipSubmissionType" in updatedFields) {
    if (currentPackage._source.authority !== "CHIP SPA") {
      return response({
        statusCode: 400,
        body: { message: "CHIP Submission Type updates are only allowed for CHIP SPA packages." },
      });
    }
    const chipSubmissionType = (updatedFields as { chipSubmissionType?: unknown })
      .chipSubmissionType;
    Iif (!Array.isArray(chipSubmissionType) || chipSubmissionType.length === 0) {
      return response({
        statusCode: 400,
        body: { message: "CHIP Submission Type must include at least one value." },
      });
    }
    const invalidTypes = chipSubmissionType.filter(
      (type) => typeof type !== "string" || !allowedChipSubmissionTypes.has(type),
    );
    if (invalidTypes.length > 0) {
      return response({
        statusCode: 400,
        body: { message: "Invalid CHIP Submission Type value(s)." },
      });
    }
  }
 
  if ("id" in updatedFields) {
    return response({
      statusCode: 400,
      body: { message: "ID is not a valid field to update" },
    });
  }
 
  const fieldNames = Object.keys(updatedFields).join(", ");
  const changeMadeText = `${fieldNames} ${
    Object.keys(updatedFields).length > 1 ? "have" : "has"
  } been updated`;
 
  const currentTime = Date.now();
 
  await produceMessage(
    topicName,
    currentPackage._id,
    JSON.stringify({
      id: currentPackage._id,
      isAdminChange: true,
      adminChangeType: "update-values",
      changeMade,
      changeReason,
      makoChangedDate: currentTime,
      changedDate: currentTime,
      statusDate: currentTime,
      timestamp: currentTime,
      ...updatedFields,
    }),
  );
 
  return response({
    statusCode: 200,
    body: { message: `${changeMadeText} in package ${currentPackage._id}.` },
  });
};
 
/** @typedef {object} json
 * @property {object} body
 * @property {string} body.packageId
 * @property {string} body.action
 * @property {string} body.updatedId
 * @property {string} body.changeMade
 * @property {string} body.changeReason
 */
const sendUpdateIdMessage = async ({
  currentPackage,
  updatedId,
  changeMade,
  changeReason,
}: {
  currentPackage: ItemResult;
  updatedId: string;
  changeMade: string;
  changeReason: string;
}) => {
  const topicName = process.env.topicName as string;
  if (!topicName) {
    throw new Error("Topic name is not defined");
  }
  // ID and changeMade are excluded; the rest of the object has to be spread into the new package
  const {
    id: _id,
    changeMade: _changeMade,
    origin: _origin,
    ...remainingFields
  } = currentPackage._source;
  if (updatedId === currentPackage._id) {
    return response({
      statusCode: 400,
      body: { message: "New ID required to update package" },
    });
  }
  // check if a package with this new ID already exists
  const packageExists = await getPackage(updatedId);
  if (packageExists?.found) {
    return response({
      statusCode: 400,
      body: { message: "This ID already exists" },
    });
  }
  // use event of current package to determine how ID should be formatted
  const packageEvent = await getPackageType(currentPackage._id);
  const packageSubmissionTypeSchema = events[packageEvent as keyof typeof events].baseSchema;
 
  const idSchema = packageSubmissionTypeSchema.shape.id;
  const parsedId = idSchema.safeParse(updatedId);
 
  if (!parsedId.success) {
    return response({
      statusCode: 400,
      body: parsedId.error.message,
    });
  }
 
  const currentTime = Date.now();
 
  await produceMessage(
    topicName,
    updatedId,
    JSON.stringify({
      id: updatedId,
      ...remainingFields,
      idToBeUpdated: currentPackage._id,
      origin: "OneMAC",
      changeMade,
      changeReason,
      isAdminChange: true,
      adminChangeType: "update-id",
      makoChangedDate: currentTime,
      changedDate: currentTime,
      statusDate: currentTime,
      timestamp: currentTime,
    }),
  );
  await sendDeleteMessage(currentPackage, changeMade, changeReason, currentTime);
  return response({
    statusCode: 200,
    body: { message: `The ID of package ${currentPackage._id} has been updated to ${updatedId}.` },
  });
};
 
const updatePackageEventBodySchema = z.object({
  packageId: z.string(),
  action: z.enum(["update-values", "update-id", "delete", "recover"]),
  updatedId: z.string().optional(),
  updatedFields: z.record(z.unknown()).optional(),
  changeMade: z.string().trim().min(1),
  changeReason: z.string().trim().min(1),
});
 
export const handler = async (event: APIGatewayEvent) => {
  if (!event.body) {
    return response({
      statusCode: 400,
      body: { message: "Event body required" },
    });
  }
  try {
    const parseEventBody = (body: unknown) => {
      return updatePackageEventBodySchema.parse(typeof body === "string" ? JSON.parse(body) : body);
    };
    let body = {
      packageId: "",
      action: "",
    };
    if (typeof event.body === "string") {
      body = JSON.parse(event.body);
    } else E{
      body = event.body;
    }
    if (!body.packageId || !body.action) {
      return response({
        statusCode: 400,
        body: { message: "Package ID and action are required" },
      });
    }
    const {
      packageId,
      action,
      updatedId = packageId,
      updatedFields = {},
      changeMade,
      changeReason,
    } = parseEventBody(event.body);
 
    const currentPackage = await getPackage(packageId);
    if (!currentPackage || currentPackage.found == false) {
      return response({
        statusCode: 404,
        body: { message: "No record found for the given id" },
      });
    }
 
    if (action === "delete") {
      return await sendDeleteMessage(currentPackage, changeMade, changeReason);
    }
    if (action === "recover") {
      return await sendRecoverMessage(currentPackage, changeMade, changeReason);
    }
    if (action === "update-id") {
      return await sendUpdateIdMessage({ currentPackage, updatedId, changeMade, changeReason });
    }
 
    Eif (action === "update-values") {
      return await sendUpdateValuesMessage({
        currentPackage,
        updatedFields,
        changeMade,
        changeReason,
      });
    }
  } catch (err) {
    console.error("Error has occured modifying package:", err);
    Iif (err instanceof z.ZodError) {
      return response({
        statusCode: 400,
        body: { message: err.errors },
      });
    }
    return response({
      statusCode: 500,
      body: { message: err.message || "Internal Server Error" },
    });
  }
};