All files / react-app/src/features/package index.tsx

64.7% Statements 33/51
72.34% Branches 34/47
64.28% Functions 9/14
65.95% Lines 31/47

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                                                      4x               27x                         4x       5x   5x   5x 45x     5x                                       4x 7x 7x         7x         7x 7x 6x     7x 6x       7x 7x   1x                 7x                                                                                     4x       1x 1x       1x   1x 1x 1x                       1x     4x                         4x                                                        
import { useQuery } from "@tanstack/react-query";
import { PropsWithChildren, useMemo } from "react";
import { LoaderFunctionArgs, Navigate, redirect, useLoaderData } from "react-router";
import { Authority, opensearch, SEATOOL_STATUS } from "shared-types";
import { ItemResult } from "shared-types/opensearch/changelog";
 
import { getItem, itemExists, useGetItem } from "@/api";
import {
  Alert,
  AlertDescription,
  AlertTitle,
  CardWithTopBorder,
  ErrorAlert,
  LoadingSpinner,
} from "@/components";
import { BreadCrumbs } from "@/components/BreadCrumb";
import { useFeatureFlag } from "@/hooks/useFeatureFlag";
import { detailsAndActionsCrumbs, sendGAEvent } from "@/utils";
import { DRAFT_ID_CONFLICT_MESSAGE } from "@/utils/drafts";
 
import { AdminPackageActivities } from "./admin-changes";
import { useDetailsSidebarLinks } from "./hooks";
import { PackageActionsCard } from "./package-actions";
import { PackageActivities } from "./package-activity";
import { PackageDetails } from "./package-details";
import { PackageStatusCard } from "./package-status";
 
export const DetailCardWrapper = ({
  title,
  children,
  ariaLabel,
}: PropsWithChildren<{
  title: string;
  ariaLabel?: string;
}>) => (
  <CardWithTopBorder className="text-wrap my-0 sm:mt-6">
    <div className="p-4 py-1 min-h-36">
      <h2 id={ariaLabel}>{title}</h2>
      {children}
    </div>
  </CardWithTopBorder>
);
 
type DetailsContentProps = {
  id: string;
  preferDraft?: boolean;
};
 
const injectChipEligibilityAttachment = (
  submission: opensearch.main.Document,
  changelog: ItemResult[],
): opensearch.main.Document => {
  const alreadyHasChipEligibility = submission.attachments?.chipEligibility?.files?.length > 0;
 
  Iif (alreadyHasChipEligibility) return submission;
 
  const chipEligibilityAttachment = changelog.find((item) =>
    item._source.attachments?.some((att) => att.title.toLowerCase().includes("chip eligibility")),
  );
 
  Eif (!chipEligibilityAttachment) return submission;
 
  const chipAttachment = chipEligibilityAttachment._source.attachments.find((att) =>
    att.title.toLowerCase().includes("chip eligibility"),
  );
 
  if (!chipAttachment) return submission;
 
  return {
    ...submission,
    attachments: {
      ...submission.attachments,
      chipEligibility: {
        files: [chipAttachment],
        label: "CHIP Eligibility Template",
      },
    },
  };
};
 
export const DetailsContent = ({ id, preferDraft = false }: DetailsContentProps) => {
  const isSaveInProgressEnabled = useFeatureFlag("SAVE_IN_PROGRESS");
  const effectivePreferDraft = isSaveInProgressEnabled && preferDraft;
  const {
    data: record,
    isLoading,
    error,
  } = useGetItem(id, undefined, {
    includeDraft: isSaveInProgressEnabled,
    preferDraft: effectivePreferDraft,
  });
 
  const submission = record?._source;
  const normalizedSubmission = useMemo(
    () => (submission ? { ...submission, changelog: submission.changelog ?? [] } : undefined),
    [submission],
  );
  const updatedSubmission = useMemo(() => {
    return normalizedSubmission
      ? injectChipEligibilityAttachment(normalizedSubmission, normalizedSubmission.changelog)
      : undefined;
  }, [normalizedSubmission]);
  const isDraft = updatedSubmission?.seatoolStatus === SEATOOL_STATUS.DRAFT;
  const { data: hasDraftIdConflict = false } = useQuery(
    ["draft-id-conflict", id],
    () => itemExists(id, { includeDrafts: true, allowDraftId: id }),
    {
      enabled: Boolean(isSaveInProgressEnabled && isDraft && id),
      retry: false,
      staleTime: 30_000,
    },
  );
 
  if (isLoading) return <LoadingSpinner />;
  if (
    effectivePreferDraft &&
    (error || !record || !updatedSubmission || submission?.deleted === true)
  ) {
    return <Navigate to="/dashboard" replace />;
  }
  if (error || !record || !updatedSubmission) return <ErrorAlert error={error} />;
 
  return (
    <div className="w-full py-1 px-4 lg:px-8 grid grid-cols-1 gap-y-6 sm:gap-y-6">
      {isSaveInProgressEnabled && isDraft && hasDraftIdConflict && (
        <Alert variant="warning" className="my-2 sm:my-3">
          <AlertTitle>This package ID is already in use</AlertTitle>
          <AlertDescription>{DRAFT_ID_CONFLICT_MESSAGE}</AlertDescription>
        </Alert>
      )}
      <section id="package_overview" className="sm:mb-0 two-cols gap-y-3 sm:gap-y-3">
        <DetailCardWrapper title="Status" ariaLabel="package-status-heading">
          <PackageStatusCard submission={updatedSubmission} />
        </DetailCardWrapper>
        <DetailCardWrapper title="Package Actions" ariaLabel="package-actions-heading">
          <PackageActionsCard id={id} submission={updatedSubmission} />
        </DetailCardWrapper>
      </section>
      <div className="grid grid-cols-1 gap-y-3">
        <PackageDetails submission={updatedSubmission} />
        <PackageActivities
          id={id}
          changelog={updatedSubmission.changelog}
          submission={updatedSubmission}
        />
        <AdminPackageActivities changelog={updatedSubmission.changelog} />
      </div>
    </div>
  );
};
 
type LoaderData = {
  id: string;
  authority: Authority;
  preferDraft: boolean;
};
 
export const packageDetailsLoader = async ({
  params,
  request,
}: LoaderFunctionArgs): Promise<LoaderData | Response> => {
  const { id, authority } = params;
  Iif (id === undefined || authority === undefined) {
    return redirect("/dashboard");
  }
 
  const preferDraft = new URL(request.url).searchParams.get("preferDraft") === "true";
 
  try {
    const packageResult = await getItem(id, { includeDraft: true, preferDraft });
    Iif (!packageResult || packageResult._source.deleted === true || packageResult.found === false) {
      return redirect("/dashboard");
    }
  } catch (error) {
    if (error instanceof Error) {
      console.log("Error fetching package: ", error.message);
    } else {
      console.log("Unknown error fetching package: ", error);
    }
    return redirect("/dashboard");
  }
 
  return { id, authority: authority as Authority, preferDraft };
};
 
export const Details = () => {
  const { id, authority, preferDraft } = useLoaderData<LoaderData>();
  return (
    <div id="package_details_page" className="max-w-screen-xl mx-auto flex flex-col lg:flex-row">
      <div className="px-4 lg:px-8">
        <BreadCrumbs options={detailsAndActionsCrumbs({ id, authority })} />
        <DetailsSidebar />
      </div>
      <DetailsContent id={id} preferDraft={preferDraft} />
    </div>
  );
};
 
const DetailsSidebar = () => {
  const links = useDetailsSidebarLinks();
  const handleSidebarClick = (linkId: string) => {
    if (linkId === "package_activity" || linkId === "package_details") {
      sendGAEvent("package_detail_sidebar_link_click", {
        link: linkId,
      });
    }
  };
 
  return (
    <nav className="min-w-56 flex-none font-semibold mt-6 hidden lg:block mr-8">
      <ul>
        {links.map(({ id, href, displayName }) => (
          <li key={id}>
            <a
              className="block mb-2 text-blue-900 hover:underline"
              href={href}
              onClick={() => handleSidebarClick(id)}
            >
              {displayName}
            </a>
          </li>
        ))}
      </ul>
    </nav>
  );
};