All files / lib/lambda getAttachmentArchive.ts

88.37% Statements 38/43
84.78% Branches 39/46
100% Functions 5/5
88.37% Lines 38/43

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                              1x                     12x                           1x 4x   4x     4x                         4x       11x 11x 11x 11x   11x                 1x         11x 11x 11x   11x             11x   11x 1x           10x 10x 10x 10x   10x 1x           9x 1x           8x               8x               7x 2x 9x 9x 2x     7x     2x               7x          
import { APIGatewayEvent } from "shared-types";
import { opensearch, SEATOOL_STATUS } from "shared-types";
import { isCmsUser, isHelpDeskUser } from "shared-utils";
import { z } from "zod";
 
import { buildDraftAttachmentChangelog } from "../attachment-archive/draft-package";
import { sendAttachmentArchiveRebuildRequest } from "../attachment-archive/rebuild-queue";
import { getDraftPackage, getPackage, getPackageChangelog } from "../libs/api/package";
import {
  isActiveDraftPackage,
  isActiveMainNonDraftPackage,
} from "../libs/api/package/packageStatus";
import { getRequestedAttachmentArchiveStatus } from "./attachmentArchive-lib";
import { authenticatedMiddy, ContextWithAuthenticatedUser } from "./middleware";
 
const getAttachmentArchiveEventSchema = z
  .object({
    body: z
      .object({
        id: z.string(),
        scope: z.enum(["all", "section"]),
        sectionId: z.string().optional(),
        preferDraft: z.boolean().optional(),
      })
      .strict()
      .superRefine((value, ctx) => {
        Iif (value.scope === "section" && !value.sectionId) {
          ctx.addIssue({
            code: z.ZodIssueCode.custom,
            message: "sectionId is required when scope is 'section'",
            path: ["sectionId"],
          });
        }
      }),
  })
  .passthrough();
 
export type GetAttachmentArchiveEvent = APIGatewayEvent &
  z.infer<typeof getAttachmentArchiveEventSchema>;
 
const getPackageChangelogFilter = (packageResult: opensearch.main.ItemResult) => {
  const filter = [];
  const legacySubmissionTimestamp = (
    packageResult._source as { legacySubmissionTimestamp?: string }
  )?.legacySubmissionTimestamp;
 
  Iif (legacySubmissionTimestamp !== null && legacySubmissionTimestamp !== undefined) {
    const gte = new Date(legacySubmissionTimestamp).getTime();
    if (Number.isFinite(gte)) {
      filter.push({
        range: {
          timestamp: {
            gte,
          },
        },
      });
    }
  }
 
  return filter;
};
 
async function resolvePackageForArchive(packageId: string, preferDraft?: boolean) {
  const mainResult = await getPackage(packageId);
  const hasActiveMainNonDraft = isActiveMainNonDraftPackage(mainResult);
  const draftResult = await getDraftPackage(packageId);
  const hasActiveDraft = isActiveDraftPackage(draftResult);
 
  return preferDraft === true && hasActiveDraft
    ? draftResult
    : hasActiveMainNonDraft
      ? mainResult
      : hasActiveDraft
        ? draftResult
        : undefined;
}
 
export const handler = authenticatedMiddy({
  opensearch: true,
  setToContext: true,
  eventSchema: getAttachmentArchiveEventSchema,
}).handler(async (event: GetAttachmentArchiveEvent, context: ContextWithAuthenticatedUser) => {
  const body = event.body;
  const packageId = body.id.trim().toUpperCase();
  const authenticatedUser = context.authenticatedUser;
 
  Iif (!authenticatedUser) {
    return {
      statusCode: 401,
      body: { message: "User is not authenticated" },
    };
  }
 
  const resolvedPackage = await resolvePackageForArchive(packageId, body.preferDraft);
 
  if (!resolvedPackage || !resolvedPackage.found) {
    return {
      statusCode: 404,
      body: { message: "No record found for the given id" },
    };
  }
 
  const packageState = resolvedPackage._source?.state?.toUpperCase();
  const isDraftPackage = resolvedPackage._source?.seatoolStatus === SEATOOL_STATUS.DRAFT;
  const isCmsReviewer = isCmsUser(authenticatedUser);
  const isHelpDesk = isHelpDeskUser(authenticatedUser);
 
  if (isDraftPackage && isCmsReviewer && !isHelpDesk) {
    return {
      statusCode: 403,
      body: { message: "Not authorized to view this resource" },
    };
  }
 
  if (!isCmsReviewer && packageState && !authenticatedUser.states?.includes(packageState)) {
    return {
      statusCode: 403,
      body: { message: "Not authorized to view this resource" },
    };
  }
 
  const changelog = isDraftPackage
    ? buildDraftAttachmentChangelog({
        packageId,
        submission: resolvedPackage._source,
      })
    : ((await getPackageChangelog(packageId, getPackageChangelogFilter(resolvedPackage))).hits
        .hits as opensearch.changelog.ItemResult[]);
 
  const result = await getRequestedAttachmentArchiveStatus({
    packageId,
    scope: body.scope,
    sectionId: body.sectionId,
    changelog,
    archiveNamespace: isDraftPackage ? "draft" : "main",
  });
 
  if (result.needsRebuild) {
    const latestTimestamp = changelog.reduce<number | undefined>((latest, item) => {
      const timestamp = item._source?.timestamp;
      if (typeof timestamp !== "number") {
        return latest;
      }
 
      return latest === undefined ? timestamp : Math.max(latest, timestamp);
    }, undefined);
 
    await sendAttachmentArchiveRebuildRequest({
      packageId,
      latestTimestamp,
      preferDraft: isDraftPackage || undefined,
      source: "request",
    });
  }
 
  return {
    statusCode: 200,
    body: result.response,
  };
});