All files / react-app/src/features/dashboard/Lists/renderCells index.tsx

91.66% Statements 44/48
91.89% Branches 34/37
86.66% Functions 13/15
91.3% Lines 42/46

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                                                  7x 98x 6008x 2109x             7x 1293x 1293x 1293x 1293x 1x           1293x 1293x                         7x 40x 1539x   1538x         7x                 1009x 1009x 1009x   1009x 1009x 1009x 1009x     1009x                                     1009x 4x       4x                       1x 1x 1x 1x           1x         1x                         1009x 1x       1x       1x 1x   1x                                                                                                                               414x 1x                                                                    
import { EllipsisVerticalIcon } from "@heroicons/react/24/outline";
import * as DropdownMenu from "@radix-ui/react-dropdown-menu";
import { type MouseEvent, useState } from "react";
import { Link, useNavigate } from "react-router";
import { FullUser, opensearch, SEATOOL_STATUS } from "shared-types";
import { formatDateToET, getAvailableActions, isStateUser } from "shared-utils";
 
import { deleteDraft } from "@/api/deleteDraft";
import { banner, userPrompt } from "@/components";
import { OS_DASHBOARD_REFRESH_EVENT } from "@/components/Opensearch/main/useOpensearch";
import { useFeatureFlag } from "@/hooks/useFeatureFlag";
import { DASHBOARD_ORIGIN, mapActionLabel, ORIGIN, queryClient } from "@/utils";
import {
  DRAFT_CONTINUE_ACTION_LABEL,
  DRAFT_DELETE_ACTION_LABEL,
  DRAFT_DELETE_MODAL_BODY,
  DRAFT_DELETE_MODAL_HEADER,
  getDraftEditLink,
  getNonOwnerDraftDeleteModalBody,
  getNonOwnerDraftWarningModalBody,
  isCurrentUserDraftActor,
  markDraftContinueConfirmed,
} from "@/utils/drafts";
import { sendGAEvent } from "@/utils/ReactGA/SendGAEvent";
 
export const renderCellDate = (key: keyof opensearch.main.Document) =>
  function Cell(data: opensearch.main.Document) {
    if (!data[key]) return null;
    return formatDateToET(data[key] as string, "MM/dd/yyyy", false);
  };
 
export type CellIdLinkProps = {
  record: opensearch.main.Document;
};
 
export const CellDetailsLink = ({ record }: CellIdLinkProps) => {
  const { id, authority } = record;
  const isSaveInProgressEnabled = useFeatureFlag("SAVE_IN_PROGRESS");
  const isDraft = isSaveInProgressEnabled && record.seatoolStatus === SEATOOL_STATUS.DRAFT;
  const handleLinkClick = () => {
    sendGAEvent("dash_package_link", {
      package_type: authority, // The 'authority' prop is the package type
      package_id: id, // The 'id' prop is the package_id
    });
  };
 
  const detailsLink = `/details/${encodeURIComponent(authority)}/${encodeURIComponent(id)}`;
  const detailsSearch = isDraft ? "?preferDraft=true" : "";
 
  return (
    <Link
      className={`cursor-pointer text-blue-600 hover:underline ${isDraft ? "italic" : ""}`}
      to={`${detailsLink}${detailsSearch}`}
      onClick={handleLinkClick} // Track the click event for analytics
    >
      {id}
    </Link>
  );
};
 
export const renderCellActions = (user: FullUser | null) => {
  return function Cell(data: opensearch.main.Document) {
    if (!user) return null;
 
    const draftLink = getDraftEditLink(data);
    return <ActionMenuCell data={data} draftLink={draftLink} user={user} />;
  };
};
 
const ActionMenuCell = ({
  data,
  draftLink,
  user,
}: {
  data: opensearch.main.Document;
  draftLink: ReturnType<typeof getDraftEditLink>;
  user: FullUser;
}) => {
  const [isOpen, setIsOpen] = useState(false);
  const navigate = useNavigate();
  const isSaveInProgressEnabled = useFeatureFlag("SAVE_IN_PROGRESS");
  const canDeleteDraft =
    isSaveInProgressEnabled && data.seatoolStatus === SEATOOL_STATUS.DRAFT && isStateUser(user);
  const canContinueDraft = canDeleteDraft && !!draftLink;
  const actions = canDeleteDraft ? [] : getAvailableActions(user, data);
  const draftLinkState = {
    from: `${window.location.pathname}${window.location.search}`,
  };
  const isNonOwnerDraftUser = Boolean(
    canDeleteDraft &&
      user.email &&
      !isCurrentUserDraftActor(user, [
        {
          email: data.draft?.createdByEmail ?? data.draft?.draftOwnerEmail,
          name: data.draft?.createdByName ?? data.draft?.draftOwnerName,
        },
        {
          email: data.draft?.updatedByEmail,
          name: data.draft?.updatedByName,
        },
        {
          email: data.submitterEmail,
          name: data.submitterName,
        },
      ]),
  );
 
  const handleDraftDelete = () => {
    sendGAEvent("dash_ellipsis_click", {
      action: "delete-draft",
    });
 
    userPrompt({
      header: DRAFT_DELETE_MODAL_HEADER,
      body: isNonOwnerDraftUser
        ? getNonOwnerDraftDeleteModalBody(data.id)
        : DRAFT_DELETE_MODAL_BODY,
      acceptButtonText: "Delete",
      cancelButtonText: "Cancel",
      cancelVariant: "link",
      onCancel: () => {
        // Keep users on the dashboard when they dismiss the delete draft modal.
      },
      onAccept: async () => {
        try {
          await deleteDraft(data.id);
          queryClient.removeQueries({ queryKey: ["record", data.id] });
          banner({
            header: "Draft deleted",
            body: `Draft for ${data.id} has been deleted.`,
            variant: "success",
            pathnameToDisplayOn: window.location.pathname,
          });
          await Promise.all([
            queryClient.invalidateQueries({ queryKey: ["os-dashboard"] }),
            queryClient.invalidateQueries({ queryKey: ["spas"] }),
            queryClient.invalidateQueries({ queryKey: ["waivers"] }),
          ]);
          window.dispatchEvent(new Event(OS_DASHBOARD_REFRESH_EVENT));
        } catch (error) {
          banner({
            header: "Unable to delete draft",
            body: error instanceof Error ? error.message : String(error),
            variant: "destructive",
            pathnameToDisplayOn: window.location.pathname,
          });
        }
      },
    });
  };
 
  const handleContinueDraft = (event: MouseEvent<HTMLAnchorElement>) => {
    sendGAEvent("dash_ellipsis_click", {
      action: "continue-package",
    });
 
    Iif (!draftLink || !isNonOwnerDraftUser) {
      return;
    }
 
    event.preventDefault();
    setIsOpen(false);
 
    userPrompt({
      header: "Confirm action",
      body: getNonOwnerDraftWarningModalBody(data.id),
      acceptButtonText: "Yes, continue",
      cancelButtonText: "Cancel",
      cancelVariant: "link",
      onCancel: () => {
        // Keep users on the dashboard when they dismiss the continue draft modal.
      },
      onAccept: () => {
        markDraftContinueConfirmed(data.id, user.email);
        navigate(draftLink, { state: draftLinkState });
      },
    });
  };
 
  return (
    <DropdownMenu.Root open={isOpen} onOpenChange={setIsOpen}>
      <DropdownMenu.DropdownMenuTrigger
        disabled={!actions.length && !canDeleteDraft}
        aria-label="Available package actions"
        data-testid="available-actions"
        asChild
      >
        <button className="group ml-3" type="button" title="Expand Available Package Actions">
          <EllipsisVerticalIcon
            aria-hidden
            className="w-8 text-blue-700 group-disabled:text-gray-500"
          />
        </button>
      </DropdownMenu.DropdownMenuTrigger>
      <DropdownMenu.Content
        className="flex flex-col bg-white rounded-md shadow-lg p-4 border"
        align="start"
      >
        {canDeleteDraft ? (
          <>
            {canContinueDraft && (
              <DropdownMenu.Item
                asChild
                aria-label={`${DRAFT_CONTINUE_ACTION_LABEL} for ${data.id}`}
              >
                <Link
                  onClick={handleContinueDraft}
                  state={draftLinkState}
                  to={draftLink}
                  className="text-blue-500 flex select-none items-center rounded-sm px-2 py-2 text-sm hover:bg-accent"
                >
                  {DRAFT_CONTINUE_ACTION_LABEL}
                </Link>
              </DropdownMenu.Item>
            )}
            <DropdownMenu.Item asChild aria-label={`${DRAFT_DELETE_ACTION_LABEL} for ${data.id}`}>
              <button
                onClick={handleDraftDelete}
                className="text-blue-500 text-left flex select-none items-center rounded-sm px-2 py-2 text-sm hover:bg-accent"
                type="button"
              >
                {DRAFT_DELETE_ACTION_LABEL}
              </button>
            </DropdownMenu.Item>
          </>
        ) : (
          actions.map((action, idx) => {
            const handleActionClick = () => {
              sendGAEvent("dash_ellipsis_click", {
                action: action,
              });
            };
 
            return (
              <DropdownMenu.Item
                key={`${idx}-${action}`}
                asChild
                aria-label={`${mapActionLabel(action)} for ${data.id}`}
              >
                <Link
                  onClick={handleActionClick}
                  state={{
                    from: `${window.location.pathname}${window.location.search}`,
                  }}
                  to={{
                    pathname: `/actions/${action}/${data.authority}/${data.id}`,
                    search: new URLSearchParams({
                      [ORIGIN]: DASHBOARD_ORIGIN,
                    }).toString(),
                  }}
                  className="text-blue-500 flex select-none items-center rounded-sm px-2 py-2 text-sm hover:bg-accent"
                >
                  {mapActionLabel(action)}
                </Link>
              </DropdownMenu.Item>
            );
          })
        )}
      </DropdownMenu.Content>
    </DropdownMenu.Root>
  );
};