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

94.11% Statements 32/34
92.3% Branches 36/39
87.5% Functions 7/8
94.11% Lines 32/34

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                                                                  4x 39x 39x 39x 39x 39x 39x 39x 39x                                   39x 39x 39x       39x         39x       32x 4x                   1x 1x 1x           1x           1x 1x     1x                           32x 1x       1x   1x                   1x 1x         32x                                                           24x                       13x                                                                              
import { type MouseEvent } from "react";
import { Link, useLocation, useNavigate } from "react-router";
import { opensearch, SEATOOL_STATUS } from "shared-types";
import { isStateUser } from "shared-utils";
 
import { deleteDraft, useGetPackageActions, useGetUser } from "@/api";
import { banner, LoadingSpinner, userPrompt } from "@/components";
import { useFeatureFlag } from "@/hooks/useFeatureFlag";
import {
  DETAILS_ORIGIN,
  mapActionLabel,
  ORIGIN,
  queryClient,
  WAIVER_SUBMISSION_ORIGIN,
} from "@/utils";
import {
  DRAFT_CONTINUE_ACTION_LABEL,
  DRAFT_DELETE_ACTION_LABEL,
  DRAFT_DELETE_MODAL_BODY,
  DRAFT_DELETE_MODAL_HEADER,
  getDraftDashboardLink,
  getDraftEditLink,
  getNonOwnerDraftDeleteModalBody,
  getNonOwnerDraftWarningModalBody,
  isCurrentUserDraftActor,
  markDraftContinueConfirmed,
} from "@/utils/drafts";
 
type PackageActionsCardProps = {
  id: string;
  submission: opensearch.main.Document;
};
 
export const PackageActionsCard = ({ submission, id }: PackageActionsCardProps) => {
  const location = useLocation();
  const navigate = useNavigate();
  const isSaveInProgressEnabled = useFeatureFlag("SAVE_IN_PROGRESS");
  const { data: oneMacUser, isLoading: isUserLoading } = useGetUser();
  const isDraftPackage = submission.seatoolStatus === SEATOOL_STATUS.DRAFT;
  const isDraft = isSaveInProgressEnabled && isDraftPackage;
  const draftLink = isDraft ? getDraftEditLink(submission) : null;
  const isNonOwnerDraftUser = Boolean(
    isDraft &&
      oneMacUser?.user?.email &&
      !isCurrentUserDraftActor(oneMacUser.user, [
        {
          email: submission.draft?.createdByEmail ?? submission.draft?.draftOwnerEmail,
          name: submission.draft?.createdByName ?? submission.draft?.draftOwnerName,
        },
        {
          email: submission.draft?.updatedByEmail,
          name: submission.draft?.updatedByName,
        },
        {
          email: submission.submitterEmail,
          name: submission.submitterName,
        },
      ]),
  );
  const canManageDraft = isDraft && !!oneMacUser?.user && isStateUser(oneMacUser.user);
  const draftDashboardLink = getDraftDashboardLink(submission);
  const draftLinkState = {
    from: `${location.pathname}${location.search}`,
  };
 
  const { data, isLoading } = useGetPackageActions(id, {
    retry: false,
    enabled: !isDraftPackage,
  });
 
  if (isDraft && isUserLoading) {
    return <LoadingSpinner />;
  }
 
  const handleDeleteDraft = () => {
    userPrompt({
      header: DRAFT_DELETE_MODAL_HEADER,
      body: isNonOwnerDraftUser ? getNonOwnerDraftDeleteModalBody(id) : DRAFT_DELETE_MODAL_BODY,
      acceptButtonText: "Delete",
      cancelButtonText: "Cancel",
      cancelVariant: "link",
      onCancel: () => {
        // Keep users on package details when they dismiss the delete draft modal.
      },
      onAccept: async () => {
        try {
          await deleteDraft(id);
          banner({
            header: "Draft deleted",
            body: `Draft for ${id} has been deleted.`,
            variant: "success",
            pathnameToDisplayOn: draftDashboardLink.split("?")[0],
          });
          await Promise.all([
            queryClient.invalidateQueries({ queryKey: ["os-dashboard"] }),
            queryClient.invalidateQueries({ queryKey: ["spas"] }),
            queryClient.invalidateQueries({ queryKey: ["waivers"] }),
          ]);
 
          navigate(draftDashboardLink, { replace: true });
          window.setTimeout(() => {
            // Clear the deleted draft cache after leaving details so the mounted page
            // does not briefly render its generic error state before navigation completes.
            queryClient.removeQueries({ queryKey: ["record", id] });
          }, 0);
        } catch (error) {
          banner({
            header: "Unable to delete draft",
            body: error instanceof Error ? error.message : String(error),
            variant: "destructive",
            pathnameToDisplayOn: location.pathname,
          });
        }
      },
    });
  };
 
  const handleContinueDraft = (event: MouseEvent<HTMLAnchorElement>) => {
    Iif (!draftLink || !isNonOwnerDraftUser) {
      return;
    }
 
    event.preventDefault();
 
    userPrompt({
      header: "Confirm action",
      body: getNonOwnerDraftWarningModalBody(id),
      acceptButtonText: "Yes, continue",
      cancelButtonText: "Cancel",
      cancelVariant: "link",
      onCancel: () => {
        // Keep users on package details when they dismiss the continue draft modal.
      },
      onAccept: () => {
        markDraftContinueConfirmed(id, oneMacUser?.user?.email);
        navigate(draftLink, { state: draftLinkState });
      },
    });
  };
 
  if (isDraft && canManageDraft) {
    return (
      <nav className="my-3 sm:text-nowrap sm:min-w-min" aria-labelledby="package-actions-heading">
        <ul className="my-3">
          {draftLink && (
            <li className="py-2">
              <Link
                state={draftLinkState}
                to={draftLink}
                onClick={handleContinueDraft}
                className="text-sky-700 font-semibold text-lg hover:underline hover:decoration-inherit"
              >
                {DRAFT_CONTINUE_ACTION_LABEL}
              </Link>
            </li>
          )}
          <li className="py-2">
            <button
              className="text-sky-700 font-semibold text-lg hover:underline hover:decoration-inherit"
              onClick={handleDeleteDraft}
              type="button"
            >
              {DRAFT_DELETE_ACTION_LABEL}
            </button>
          </li>
        </ul>
      </nav>
    );
  }
 
  if (isDraftPackage) {
    return (
      <div className="my-3" aria-labelledby="package-actions-heading">
        <em className="text-gray-400 my-3">
          No actions are currently available for this submission.
        </em>
      </div>
    );
  }
 
  if (isLoading) return <LoadingSpinner />;
 
  if (!data?.actions?.length) {
    return (
      <div className="my-3" aria-labelledby="package-actions-heading">
        <em className="text-gray-400 my-3">
          No actions are currently available for this submission.
        </em>
      </div>
    );
  }
 
  return (
    <nav className="my-3 sm:text-nowrap sm:min-w-min" aria-labelledby="package-actions-heading">
      <ul className="my-3">
        {data.actions.map((type, idx) => (
          <li className="py-2" key={`${type}-${idx}`}>
            <Link
              key={`${idx}-${type}`}
              state={{
                from: `${location.pathname}${location.search}`,
              }}
              to={{
                pathname: `/actions/${type}/${submission.authority}/${id}`,
                search: new URLSearchParams({
                  [ORIGIN]:
                    type === "amend-waiver" || type === "temporary-extension"
                      ? WAIVER_SUBMISSION_ORIGIN
                      : DETAILS_ORIGIN,
                }).toString(),
              }}
              className="text-sky-700 font-semibold text-lg hover:underline hover:decoration-inherit"
            >
              {mapActionLabel(type)}
            </Link>
          </li>
        ))}
      </ul>
    </nav>
  );
};