All files / brand-store/components/Model CreatePolicyForm.tsx

39.21% Statements 20/51
77.77% Branches 14/18
28.57% Functions 4/14
40% Lines 20/50

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                                                                  12x 12x 12x 12x 12x 12x 12x 12x 12x 12x   12x                   12x                                                                             12x 3x         12x 7x 3x       12x                                                             1x             3x                                                                                                  
import {
  useState,
  useEffect,
  ReactNode,
  Dispatch,
  SetStateAction,
} from "react";
import { useRecoilState, useRecoilValue } from "recoil";
import { useParams, Link, useNavigate, useLocation } from "react-router-dom";
import { useMutation, useQueryClient } from "react-query";
import { Button, Icon } from "@canonical/react-components";
 
import { setPageTitle } from "../../utils";
 
import { useSigningKeys } from "../../hooks";
import {
  signingKeysListState,
  newSigningKeyState,
  brandIdState,
} from "../../atoms";
import { brandStoreState } from "../../selectors";
 
type Props = {
  setShowNotification: Dispatch<SetStateAction<boolean>>;
  setShowErrorNotification: Dispatch<SetStateAction<boolean>>;
  refetchPolicies: () => void;
};
 
function CreatePolicyForm({
  setShowNotification,
  setShowErrorNotification,
  refetchPolicies,
}: Props): ReactNode {
  const { id, model_id } = useParams();
  const brandId = useRecoilValue(brandIdState);
  const navigate = useNavigate();
  const location = useLocation();
  const { isLoading, isError, error, data } = useSigningKeys(brandId);
  const [signingKeys, setSigningKeys] = useRecoilState(signingKeysListState);
  const [newSigningKey, setNewSigningKey] = useRecoilState(newSigningKeyState);
  const brandStore = useRecoilValue(brandStoreState(id));
  const [isSaving, setIsSaving] = useState(false);
  const queryClient = useQueryClient();
 
  const handleError = () => {
    setShowErrorNotification(true);
    navigate(`/admin/${id}/models/${model_id}/policies`);
    setNewSigningKey({ name: "" });
    setIsSaving(false);
    setTimeout(() => {
      setShowErrorNotification(false);
    }, 5000);
  };
 
  const mutation = useMutation({
    mutationFn: (policySigningKey: string) => {
      setIsSaving(true);
 
      const formData = new FormData();
 
      formData.set("csrf_token", window.CSRF_TOKEN);
      formData.set("signing_key", policySigningKey);
 
      setNewSigningKey({ name: "" });
 
      return fetch(`/admin/store/${brandId}/models/${model_id}/policies`, {
        method: "POST",
        body: formData,
      });
    },
    onMutate: async (newPolicy) => {
      await queryClient.cancelQueries({ queryKey: ["policies"] });
      const previousPolicies = queryClient.getQueryData(["policies"]);
      queryClient.setQueryData(["policies"], () => [newPolicy]);
      return { previousPolicies };
    },
    onError: ({ context }) => {
      queryClient.setQueryData(["policies"], context?.previousPolicies);
      handleError();
      throw new Error("Unable to create a new policy");
    },
    onSettled: async () => {
      queryClient.invalidateQueries({ queryKey: ["policies"] });
      setShowNotification(true);
      setIsSaving(false);
      refetchPolicies();
      navigate(`/admin/${id}/models/${model_id}/policies`);
      setTimeout(() => {
        setShowNotification(false);
      }, 5000);
    },
  });
 
  if (location.pathname.includes("/create")) {
    brandStore
      ? setPageTitle(`Create policy in ${brandStore.name}`)
      : setPageTitle("Create policy");
  }
 
  useEffect(() => {
    if (!isLoading && !error && data) {
      setSigningKeys(data);
    }
  }, [isLoading, error, data]);
 
  return (
    <form
      onSubmit={(event) => {
        event.preventDefault();
        mutation.mutate(newSigningKey.name);
      }}
      style={{ height: "100%" }}
    >
      <div className="p-panel is-flex-column">
        <div className="p-panel__header">
          <h4 className="p-panel__title p-muted-heading">Create new policy</h4>
        </div>
        <div className="p-panel__content">
          <div className="u-fixed-width" style={{ marginBottom: "30px" }}>
            {isLoading && <p>Fetching signing keys...</p>}
            {isError && error instanceof Error && <p>Error: {error.message}</p>}
            {isSaving && (
              <p>
                <Icon name="spinner" className="u-animation--spin" />
                &nbsp;Adding new policy...
              </p>
            )}
 
            <label htmlFor="signing-key">Signing key</label>
            <select
              name="signing-key"
              id="signing-key"
              required
              disabled={signingKeys.length < 1}
              value={newSigningKey.name}
              onChange={(event) => {
                setNewSigningKey({
                  name: event.target.value,
                });
              }}
            >
              <option value="">Select a signing key</option>
              {signingKeys.map((signingKey) => (
                <option
                  key={signingKey.fingerprint}
                  value={signingKey["sha3-384"]}
                >
                  {signingKey.name}
                </option>
              ))}
            </select>
 
            {signingKeys.length < 1 && (
              <p className="p-form-help-text">
                No signing keys available, please{" "}
                <Link to={`/admin/${id}/models/signing-keys/create`}>
                  create one
                </Link>{" "}
                first.
              </p>
            )}
          </div>
          <div className="u-fixed-width">
            <hr />
            <div className="u-align--right">
              <Link
                className="p-button u-no-margin--bottom"
                to={`/admin/${id}/models/${model_id}/policies`}
                onClick={() => {
                  setNewSigningKey({ name: "" });
                  setShowErrorNotification(false);
                }}
              >
                Cancel
              </Link>
              <Button
                type="submit"
                appearance="positive"
                className="u-no-margin--bottom u-no-margin--right"
                disabled={!newSigningKey.name}
              >
                Add policy
              </Button>
            </div>
          </div>
        </div>
      </div>
    </form>
  );
}
 
export default CreatePolicyForm;