All files / lib/lambda saveDraft.ts

84.55% Statements 115/136
81.01% Branches 128/158
100% Functions 11/11
84.09% Lines 111/132

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 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530                                      1x   1x 18x   18x 1x             1x                         1x   1x                     1x                                     1x     1x                                     1x 1x     1x 7x 7x             1x 2x     1x         11x 11x   2x 2x       2x               2x 2x         1x     1x     1x 1x 1x   1x 1x                     10x   1x       2x 2x       2x 2x             5x     1x         17x                             17x 17x             17x 17x 17x   17x 2x           15x 15x 1x           14x 1x           13x 13x   13x       13x             13x               13x 13x   13x         13x 2x 1x                           1x           11x 11x 11x   11x             11x 11x 11x 11x   11x 1x                     10x 10x 10x     10x           10x       10x     10x 6x 1x             5x     5x       1x             8x 8x   8x         8x         8x                                                               8x 8x 8x 8x   8x             8x     8x 8x                                             1x 1x                 7x 2x             2x 2x                                                                                                   7x 7x   7x   7x                  
import { APIGatewayEvent } from "aws-lambda";
import { getAuthDetails, lookupUserAttributes } from "libs/api/auth/user";
import {
  getDraftPackage,
  getPackage,
  isActiveDraftPackage,
  isActiveMainNonDraftPackage,
  isDeletedDraftPackage,
} from "libs/api/package";
import { response } from "libs/handler-lib";
import * as os from "libs/opensearch-lib";
import { getDomainAndNamespace } from "libs/utils";
import { getStatus, SEATOOL_STATUS } from "shared-types";
import { DRAFTABLE_EVENTS, type DraftableEvent, isStateUser } from "shared-utils";
import { z } from "zod";
 
import { authenticatedMiddy, ContextWithAuthenticatedUser } from "./middleware";
import { getUserByEmail } from "./user-management/userManagementService";
 
const MAX_DRAFT_DATA_BYTES = 1_000_000;
 
const draftDataSchema = z.record(z.unknown()).superRefine((draftData, ctx) => {
  const draftDataBytes = Buffer.byteLength(JSON.stringify(draftData), "utf8");
 
  if (draftDataBytes > MAX_DRAFT_DATA_BYTES) {
    ctx.addIssue({
      code: z.ZodIssueCode.custom,
      message: `Draft data cannot exceed ${MAX_DRAFT_DATA_BYTES} bytes.`,
    });
  }
});
 
const eventToAuthority: Partial<Record<DraftableEvent, string>> = {
  "new-medicaid-submission": "Medicaid SPA",
  "new-chip-submission": "CHIP SPA",
  "new-chip-details-submission": "CHIP SPA",
  "capitated-initial": "1915(b)",
  "capitated-renewal": "1915(b)",
  "capitated-amendment": "1915(b)",
  "contracting-initial": "1915(b)",
  "contracting-renewal": "1915(b)",
  "contracting-amendment": "1915(b)",
  "app-k": "1915(c)",
};
 
const knownDraftAuthorities = new Set(["Medicaid SPA", "CHIP SPA", "1915(b)", "1915(c)"]);
 
const eventToActionType: Partial<Record<DraftableEvent, string>> = {
  "capitated-initial": "New",
  "capitated-renewal": "Renew",
  "capitated-amendment": "Amend",
  "contracting-initial": "New",
  "contracting-renewal": "Renew",
  "contracting-amendment": "Amend",
  "temporary-extension": "Extend",
  "app-k": "Amend",
};
 
const saveDraftEventSchema = z
  .object({
    body: z
      .object({
        id: z.string().trim().min(1),
        originalDraftId: z.string().trim().min(1).optional(),
        event: z.string(),
        authority: z.string().optional(),
        draftData: draftDataSchema,
        ifSeqNo: z.number().int().nonnegative().optional(),
        ifPrimaryTerm: z.number().int().nonnegative().optional(),
      })
      .strict(),
  })
  .passthrough();
 
export type SaveDraftEvent = APIGatewayEvent & z.infer<typeof saveDraftEventSchema>;
 
const DRAFT_ID_CONFLICT_MESSAGE =
  "This package ID is already in use. Update the ID before saving or submitting.";
 
const DRAFT_CONCURRENCY_MESSAGE =
  "Draft was updated by another user. Refresh this page and try saving again.";
 
type TemporaryExtensionDraftData = {
  ids?: {
    validAuthority?: {
      authority?: unknown;
    };
  };
};
 
type OsUpdateVersionResponse = {
  _seq_no?: number;
  _primary_term?: number;
  body?: {
    _seq_no?: number;
    _primary_term?: number;
  };
};
 
const areJsonValuesEqual = (left: unknown, right: unknown) => {
  return JSON.stringify(left) === JSON.stringify(right);
};
 
const unwrapUpdateVersionResponse = (updateResponse: unknown): OsUpdateVersionResponse => {
  Eif (!updateResponse || typeof updateResponse !== "object") {
    return {};
  }
 
  const result = updateResponse as OsUpdateVersionResponse;
  return result.body ?? result;
};
 
const getTemporaryExtensionAuthority = (draftData: Record<string, unknown>) => {
  return (draftData as TemporaryExtensionDraftData).ids?.validAuthority?.authority;
};
 
const resolveAuthority = (
  eventName: DraftableEvent,
  authority: string | undefined,
  draftData: Record<string, unknown>,
) => {
  const eventAuthority = eventToAuthority[eventName];
  if (eventAuthority) return eventAuthority;
 
  const normalizedAuthority = authority?.trim();
  Iif (normalizedAuthority && knownDraftAuthorities.has(normalizedAuthority)) {
    return normalizedAuthority;
  }
 
  Iif (
    typeof draftData.authority === "string" &&
    draftData.authority.trim() &&
    knownDraftAuthorities.has(draftData.authority.trim())
  ) {
    return draftData.authority.trim();
  }
 
  const nestedAuthority = getTemporaryExtensionAuthority(draftData);
  if (
    typeof nestedAuthority === "string" &&
    nestedAuthority.trim() &&
    knownDraftAuthorities.has(nestedAuthority.trim())
  ) {
    return nestedAuthority.trim();
  }
 
  return undefined;
};
 
const isVersionConflictError = (error: unknown) => {
  Eif (error && typeof error === "object") {
    const osType = (error as { meta?: { body?: { error?: { type?: string } } } }).meta?.body?.error
      ?.type;
    Eif (osType === "version_conflict_engine_exception") {
      return true;
    }
  }
 
  if (error instanceof Error) {
    return error.message.includes("version_conflict_engine_exception");
  }
 
  return false;
};
 
const normalizeEmail = (email?: string | null) => email?.trim().toLowerCase() || "";
 
const canUserModifyDraft = (
  sourceDraftPackage: Awaited<ReturnType<typeof getDraftPackage>>,
  email: string,
) => {
  const currentEmail = normalizeEmail(email);
  Iif (!currentEmail || !isActiveDraftPackage(sourceDraftPackage)) {
    return false;
  }
 
  const source = sourceDraftPackage?._source;
  const actorEmails = [
    source?.draft?.createdByEmail,
    source?.draft?.draftOwnerEmail,
    source?.draft?.updatedByEmail,
    source?.submitterEmail,
  ].map(normalizeEmail);
 
  return actorEmails.some((actorEmail) => actorEmail && actorEmail === currentEmail);
};
 
export const handler = authenticatedMiddy({
  opensearch: true,
  setToContext: true,
  eventSchema: saveDraftEventSchema,
}).handler(async (event: SaveDraftEvent, context: ContextWithAuthenticatedUser) => {
  Iif (!event.body) {
    return response({
      statusCode: 400,
      body: { message: "Event body required" },
    });
  }
 
  const {
    id,
    originalDraftId,
    event: eventName,
    authority,
    draftData,
    ifSeqNo,
    ifPrimaryTerm,
  } = event.body;
  Iif (!DRAFTABLE_EVENTS.includes(eventName as DraftableEvent)) {
    return response({
      statusCode: 400,
      body: { message: `Drafts are not supported for event ${eventName}` },
    });
  }
 
  const normalizedId = id.toUpperCase();
  const normalizedOriginalDraftId = originalDraftId?.toUpperCase();
  const stateCode = normalizedId.slice(0, 2);
 
  if (!context.authenticatedUser || !isStateUser(context.authenticatedUser)) {
    return response({
      statusCode: 403,
      body: { message: "Only state users can save drafts." },
    });
  }
 
  const userStates = context.authenticatedUser.states?.map((state) => state.toUpperCase()) || [];
  if (!userStates.includes(stateCode)) {
    return response({
      statusCode: 403,
      body: { message: "Not authorized to view this resource" },
    });
  }
 
  if (normalizedOriginalDraftId && !userStates.includes(normalizedOriginalDraftId.slice(0, 2))) {
    return response({
      statusCode: 403,
      body: { message: "Not authorized to view this resource" },
    });
  }
 
  const existingMainPackage = await getPackage(normalizedId);
  const existingDraftPackage = await getDraftPackage(normalizedId);
  const sourceDraftPackage =
    normalizedOriginalDraftId && normalizedOriginalDraftId !== normalizedId
      ? await getDraftPackage(normalizedOriginalDraftId)
      : existingDraftPackage;
 
  Iif (isActiveMainNonDraftPackage(existingMainPackage)) {
    return response({
      statusCode: 409,
      body: { message: DRAFT_ID_CONFLICT_MESSAGE },
    });
  }
 
  Iif (normalizedOriginalDraftId && !isActiveDraftPackage(sourceDraftPackage)) {
    return response({
      statusCode: 404,
      body: { message: "No record found for the given id" },
    });
  }
 
  const isSavingExistingDraftAtSameId =
    normalizedOriginalDraftId !== undefined && normalizedOriginalDraftId === normalizedId;
  const hasActiveDraftAtTarget = isActiveDraftPackage(existingDraftPackage);
  const isRetryOfOwnedNewDraftSave =
    normalizedOriginalDraftId === undefined &&
    hasActiveDraftAtTarget &&
    canUserModifyDraft(existingDraftPackage, context.authenticatedUser.email) &&
    areJsonValuesEqual(existingDraftPackage?._source?.draft?.data, draftData);
 
  if (hasActiveDraftAtTarget && !isSavingExistingDraftAtSameId) {
    if (isRetryOfOwnedNewDraftSave) {
      return response({
        statusCode: 200,
        body: {
          message: "Draft saved",
          id: normalizedId,
          ...(typeof existingDraftPackage?._seq_no === "number" &&
            typeof existingDraftPackage?._primary_term === "number" && {
              seqNo: existingDraftPackage._seq_no,
              primaryTerm: existingDraftPackage._primary_term,
            }),
        },
      });
    }
 
    return response({
      statusCode: 409,
      body: { message: DRAFT_ID_CONFLICT_MESSAGE },
    });
  }
 
  const authDetails = getAuthDetails(event);
  const userAttr = await lookupUserAttributes(authDetails.userId, authDetails.poolId);
  const user = await getUserByEmail(userAttr.email);
 
  Iif (!user) {
    return response({
      statusCode: 400,
      body: { message: "User does not exist in User OpenSearch Index" },
    });
  }
 
  const savedAt = new Date().toISOString();
  const { stateStatus, cmsStatus } = getStatus(SEATOOL_STATUS.DRAFT);
  const draftEventName = eventName as DraftableEvent;
  const resolvedAuthority = resolveAuthority(draftEventName, authority, draftData);
 
  if (!resolvedAuthority) {
    return response({
      statusCode: 400,
      body: {
        message:
          draftEventName === "temporary-extension"
            ? "Please select a Temporary Extension Type before saving."
            : "Authority is required before saving.",
      },
    });
  }
 
  const hasActiveSourceDraft = isActiveDraftPackage(sourceDraftPackage);
  const activeSourceDraft = hasActiveSourceDraft ? sourceDraftPackage : undefined;
  const hasDeletedDraftInDraftIndex = isDeletedDraftPackage(existingDraftPackage);
 
  const hasVersionFromRequest =
    typeof ifSeqNo === "number" &&
    typeof ifPrimaryTerm === "number" &&
    Number.isInteger(ifSeqNo) &&
    Number.isInteger(ifPrimaryTerm) &&
    ifSeqNo >= 0 &&
    ifPrimaryTerm >= 0;
  const requestVersion = hasVersionFromRequest
    ? { if_seq_no: ifSeqNo, if_primary_term: ifPrimaryTerm }
    : undefined;
  const hasVersionInExistingDraft =
    typeof existingDraftPackage?._seq_no === "number" &&
    typeof existingDraftPackage?._primary_term === "number";
 
  if (hasActiveSourceDraft) {
    if (!hasVersionFromRequest) {
      return response({
        statusCode: 409,
        body: { message: DRAFT_CONCURRENCY_MESSAGE },
      });
    }
 
    const hasVersionInSourceDraft =
      typeof sourceDraftPackage?._seq_no === "number" &&
      typeof sourceDraftPackage?._primary_term === "number";
 
    if (
      hasVersionInSourceDraft &&
      (ifSeqNo !== activeSourceDraft?._seq_no || ifPrimaryTerm !== activeSourceDraft?._primary_term)
    ) {
      return response({
        statusCode: 409,
        body: { message: DRAFT_CONCURRENCY_MESSAGE },
      });
    }
  }
 
  const sourceDraft = activeSourceDraft?._source?.draft;
  const createdAt = sourceDraft?.createdAt ?? sourceDraft?.savedAt ?? savedAt;
  const createdByEmail =
    sourceDraft?.createdByEmail ??
    sourceDraft?.draftOwnerEmail ??
    activeSourceDraft?._source?.submitterEmail ??
    user.email;
  const createdByName =
    sourceDraft?.createdByName ??
    sourceDraft?.draftOwnerName ??
    activeSourceDraft?._source?.submitterName ??
    user.fullName;
 
  const record = {
    id: normalizedId,
    authority: resolvedAuthority,
    state: stateCode,
    deleted: false,
    seatoolStatus: SEATOOL_STATUS.DRAFT,
    stateStatus,
    cmsStatus,
    origin: "OneMAC",
    makoChangedDate: savedAt,
    changedDate: savedAt,
    statusDate: savedAt,
    submitterName: user.fullName,
    submitterEmail: user.email,
    ...(eventToActionType[draftEventName] && {
      actionType: eventToActionType[draftEventName],
    }),
    event: draftEventName,
    draft: {
      savedAt,
      createdAt,
      createdByEmail,
      createdByName,
      updatedAt: savedAt,
      updatedByEmail: user.email,
      updatedByName: user.fullName,
      draftOwnerEmail: createdByEmail,
      draftOwnerName: createdByName,
      data: draftData,
    },
  };
 
  const { domain, index } = getDomainAndNamespace("draftmain");
  const shouldUpsert = existingDraftPackage?.found !== true;
  const shouldUseCompareAndWrite = hasActiveDraftAtTarget && isSavingExistingDraftAtSameId;
  const shouldReplaceDeletedDraft = hasDeletedDraftInDraftIndex;
  const deletedDraftVersion =
    shouldReplaceDeletedDraft && hasVersionInExistingDraft
      ? {
          if_seq_no: existingDraftPackage?._seq_no,
          if_primary_term: existingDraftPackage?._primary_term,
        }
      : undefined;
  const updateVersion =
    shouldUseCompareAndWrite && requestVersion ? requestVersion : (deletedDraftVersion ?? {});
 
  let updateResponse;
  try {
    updateResponse = await os.updateData(domain, {
      index,
      id: normalizedId,
      refresh: true,
      ...updateVersion,
      body: {
        ...(shouldReplaceDeletedDraft
          ? {
              script: {
                lang: "painless",
                source: "ctx._source = params.record",
                params: {
                  record,
                },
              },
            }
          : {
              doc: record,
              doc_as_upsert: shouldUpsert,
            }),
      },
    });
  } catch (error) {
    Eif (isVersionConflictError(error)) {
      return response({
        statusCode: 409,
        body: { message: DRAFT_CONCURRENCY_MESSAGE },
      });
    }
 
    throw error;
  }
 
  if (normalizedOriginalDraftId && normalizedOriginalDraftId !== normalizedId) {
    Iif (!userStates.includes(normalizedOriginalDraftId.slice(0, 2))) {
      return response({
        statusCode: 403,
        body: { message: "Not authorized to view this resource" },
      });
    }
 
    try {
      await os.updateData(domain, {
        index,
        id: normalizedOriginalDraftId,
        refresh: true,
        ...(hasVersionFromRequest && requestVersion ? requestVersion : {}),
        body: {
          doc: {
            deleted: true,
            changedDate: savedAt,
            makoChangedDate: savedAt,
            statusDate: savedAt,
          },
          doc_as_upsert: false,
        },
      });
    } catch (error) {
      try {
        await os.updateData(domain, {
          index,
          id: normalizedId,
          refresh: true,
          body: {
            doc: {
              deleted: true,
              changedDate: savedAt,
              makoChangedDate: savedAt,
              statusDate: savedAt,
            },
            doc_as_upsert: false,
          },
        });
      } catch (rollbackError) {
        console.error("Failed to roll back moved draft after source draft delete failed", {
          originalDraftId: normalizedOriginalDraftId,
          newDraftId: normalizedId,
          rollbackError,
        });
      }
 
      if (isVersionConflictError(error)) {
        return response({
          statusCode: 409,
          body: { message: DRAFT_CONCURRENCY_MESSAGE },
        });
      }
 
      throw error;
    }
  }
 
  const updateResult = unwrapUpdateVersionResponse(updateResponse);
  const seqNo = typeof updateResult?._seq_no === "number" ? updateResult._seq_no : undefined;
  const primaryTerm =
    typeof updateResult?._primary_term === "number" ? updateResult._primary_term : undefined;
 
  return response({
    statusCode: 200,
    body: {
      message: "Draft saved",
      id: normalizedId,
      ...(typeof seqNo === "number" && typeof primaryTerm === "number" && { seqNo, primaryTerm }),
    },
  });
});