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

46.34% Statements 19/41
58.06% Branches 18/31
30.76% Functions 4/13
46.34% Lines 19/41

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 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292                                                    17x 17x 17x 17x 17x 17x 17x 17x   17x                                                                           17x   17x             17x       17x 12x 6x     12x             17x                                                                               1x                                                                                                                                           4x                                                                                                                                                                      
import { useState, useEffect } from "react";
import { useParams } from "react-router-dom";
import { useRecoilValue, useSetRecoilState } from "recoil";
import { useMutation } from "react-query";
import { format } from "date-fns";
import randomstring from "randomstring";
import {
  Row,
  Col,
  Button,
  Input,
  Notification,
} from "@canonical/react-components";
 
import { modelsListState, brandIdState } from "../../atoms";
import { currentModelState, brandStoreState } from "../../selectors";
 
import ModelNav from "./ModelNav";
import ModelBreadcrumb from "./ModelBreadcrumb";
import Navigation from "../Navigation";
 
import { useModels } from "../../hooks";
import { setPageTitle } from "../../utils";
import type { Model as ModelType } from "../../types/shared";
 
function Model() {
  const { id, model_id } = useParams();
  const brandId = useRecoilValue(brandIdState);
  const currentModel = useRecoilValue(currentModelState(model_id));
  const [newApiKey, setNewApiKey] = useState("");
  const [showSuccessNotification, setShowSuccessNotificaton] = useState(false);
  const [showErrorNotification, setShowErrorNotificaton] = useState(false);
  const setModelsList = useSetRecoilState<ModelType[]>(modelsListState);
  const brandStore = useRecoilValue(brandStoreState(id));
 
  const mutation = useMutation({
    mutationFn: (apiKey: string) => {
      const formData = new FormData();
      formData.set("csrf_token", window.CSRF_TOKEN);
      formData.set("api_key", apiKey);
 
      return fetch(`/admin/store/${brandId}/models/${model_id}`, {
        method: "PATCH",
        body: formData,
      });
    },
    onSuccess: (response) => {
      if (!response.ok) {
        handleError();
        throw new Error(`${response.status} ${response.statusText}`);
      }
 
      if (response.ok) {
        setShowSuccessNotificaton(true);
        setTimeout(() => {
          setShowSuccessNotificaton(false);
        }, 5000);
      }
    },
    onError: () => {
      handleError();
      throw new Error("Unable to create a new model");
    },
  });
 
  const {
    data: models,
    isLoading: modelsIsLoading,
    error: modelsError,
  }: {
    data: ModelType[] | undefined;
    isLoading: boolean;
    error: unknown;
  } = useModels(brandId);
 
  const handleError = () => {
    setShowErrorNotificaton(true);
    setTimeout(() => {
      setShowErrorNotificaton(false);
    }, 5000);
  };
 
  currentModel && brandStore
    ? setPageTitle(`${currentModel.name} in ${brandStore.name}`)
    : setPageTitle("Model");
 
  useEffect(() => {
    if (!currentModel && !modelsIsLoading && models) {
      setModelsList(models);
    }
 
    Iif (modelsError) {
      if (modelsError instanceof Error) {
        console.error(modelsError.message);
      }
    }
  }, [currentModel, modelsIsLoading, modelsError, models]);
 
  return (
    <div className="l-application" role="presentation">
      <Navigation sectionName="models" />
      <main className="l-main">
        <div className="p-panel">
          <div className="p-panel__content">
            <div className="u-fixed-width">
              <ModelBreadcrumb />
            </div>
            <div className="u-fixed-width">
              <ModelNav sectionName="overview" />
            </div>
            {showSuccessNotification && (
              <div className="u-fixed-width">
                <Notification
                  severity="positive"
                  onDismiss={() => {
                    setShowSuccessNotificaton(false);
                  }}
                >
                  Model updated successfully
                </Notification>
              </div>
            )}
            {showErrorNotification && (
              <div className="u-fixed-width">
                <Notification
                  severity="negative"
                  onDismiss={() => {
                    setShowErrorNotificaton(false);
                  }}
                >
                  Unable to update model
                </Notification>
              </div>
            )}
            <div className="u-fixed-width u-align--right">
              <Button
                type="button"
                onClick={() => {
                  setNewApiKey("");
                }}
                disabled={!newApiKey}
              >
                Revert
              </Button>
              <Button
                type="submit"
                appearance="positive"
                className="u-no-margin--right"
                disabled={!newApiKey}
                form="save-model-form"
              >
                Save
              </Button>
            </div>
 
            {currentModel && (
              <form
                className="p-form p-form--stacked"
                id="save-model-form"
                onSubmit={(event) => {
                  event.preventDefault();
                  mutation.mutate(newApiKey);
                }}
              >
                <Row>
                  <Col size={3}>
                    <p>Name</p>
                  </Col>
                  <Col size={9}>
                    <p>{currentModel.name}</p>
                  </Col>
                </Row>
                <div className="u-fixed-width">
                  <hr />
                </div>
                <Row>
                  <Col size={3}>
                    <p>Series</p>
                  </Col>
                  <Col size={9}>
                    <p>{currentModel.series}</p>
                  </Col>
                </Row>
                <div className="u-fixed-width">
                  <hr />
                </div>
                <Row>
                  <Col size={3}>
                    <p>API key</p>
                  </Col>
                  <Col size={6}>
                    <Input
                      type="text"
                      id="api-key-field"
                      label="API key"
                      labelClassName="u-off-screen"
                      value={newApiKey || currentModel["api-key"] || ""}
                      placeholder="yx6dnxsWQ3XUB5gza8idCuMvwmxtk1xBpa9by8TuMit5dgGnv"
                      className="read-only-dark u-no-margin--bottom"
                      style={{ color: "#000" }}
                      readOnly
                    />
                  </Col>
                  <Col size={3} className="u-align--right">
                    <Button
                      type="button"
                      className="u-no-margin--bottom"
                      onClick={() => {
                        setNewApiKey(
                          randomstring.generate({
                            length: 50,
                          }),
                        );
                      }}
                    >
                      Generate key
                    </Button>
                  </Col>
                </Row>
                <div className="u-fixed-width">
                  <hr />
                </div>
                <Row>
                  <Col size={3}>
                    <p>Creation date</p>
                  </Col>
                  <Col size={9}>
                    <p>
                      {format(
                        new Date(currentModel["created-at"]),
                        "dd/MM/yyyy",
                      )}
                    </p>
                  </Col>
                </Row>
                {currentModel["created-by"] && (
                  <>
                    <div className="u-fixed-width">
                      <hr />
                    </div>
                    <Row>
                      <Col size={3}>
                        <p>Created by</p>
                      </Col>
                      <Col size={9}>
                        <p>{currentModel["created-by"]["display-name"]}</p>
                      </Col>
                    </Row>
                  </>
                )}
                {currentModel["modified-at"] && currentModel["modified-by"] && (
                  <>
                    <div className="u-fixed-width">
                      <hr />
                    </div>
                    <Row>
                      <Col size={3}>
                        <p>Last updated</p>
                      </Col>
                      <Col size={9}>
                        <p>
                          {format(
                            new Date(currentModel["modified-at"]),
                            "dd/MM/yyyy",
                          )}
                        </p>
                      </Col>
                    </Row>
                    <div className="u-fixed-width">
                      <hr />
                    </div>
                    <Row>
                      <Col size={3}>
                        <p>Modified by</p>
                      </Col>
                      <Col size={9}>
                        <p>{currentModel["modified-by"]["display-name"]}</p>
                      </Col>
                    </Row>
                  </>
                )}
              </form>
            )}
          </div>
        </div>
      </main>
    </div>
  );
}
 
export default Model;