All files / pages/admin/AddAsset AddAsset.tsx

84.09% Statements 37/44
50% Branches 8/16
85.71% Functions 6/7
84.09% Lines 37/44

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 2211x 1x 1x                 1x   1x 1x   1x                     9x 8x 8x     8x         8x 7x           7x                       8x         8x 1x       8x 10x 8x   2x           8x 31x 31x 31x 31x 31x 31x   31x                         8x                                                                                                                                           445x 445x 445x 445x 445x 445x                                                                                             1x  
import { useState, useEffect } from "react";
import Selector from "./components/Selector";
import {
  Button,
  DatePicker,
  Form,
  Input,
  Radio,
  Typography,
  message,
} from "antd";
import { AssetAPICaller } from "@/services/apis/asset.api";
import APIResponse from "../../../types/APIResponse";
import { useMutation } from "react-query";
import { useNavigate } from "react-router-dom";
import { Asset } from "@/types/Asset";
import dayjs from "dayjs";
 
interface FormValues {
  name?: string;
  category?: string;
  specification?: string;
  installDate?: string;
  state: "available" | "not_available";
}
 
function AddAsset() {
  const [form] = Form.useForm<FormValues>();
  const [isButtonDisabled, setIsButtonDisabled] = useState(true);
  const navigate = useNavigate();
 
  // query
  const { mutate, data, isLoading, isError, error, isSuccess } = useMutation(
    AssetAPICaller.createNew
  );
 
  // effect
  useEffect(() => {
    Iif (isError) {
      const errorResponse = (error as { response: { data: APIResponse } })
        .response.data;
      message.error(errorResponse.message);
    }
 
    Iif (isSuccess) {
      const newAsset: Asset = data.data.result;
      message.success("Create success");
      navigate("/admin/assets", {
        state: {
          message: "Create success",
          asset: newAsset,
        },
      });
    }
  }, [isError, isSuccess]);
 
  const onFinish = (values: FormValues) => {
    values.installDate = dayjs(values.installDate).format("YYYY-MM-DD");
    mutate(values);
  };
 
  const handleCancel = () => {
    navigate("/admin/assets");
  };
 
  // Custom validator to check if the value is not null or whitespace
  const validateWhitespace = (_: unknown, value: string) => {
    if (value && !/^\s|\s$/.test(value)) {
      return Promise.resolve();
    }
    return Promise.reject(
      new Error("Cannot empty and no start and trailing spaces")
    );
  };
 
  // handlers
  const handleFieldsChange = async () => {
    const name = form.getFieldValue("name");
    const category = form.getFieldValue("category");
    const specification = form.getFieldValue("specification");
    const installDate = form.getFieldValue("installDate");
    const threeMonthsAgo = new Date();
    threeMonthsAgo.setMonth(new Date().getMonth() - 3);
 
    setIsButtonDisabled(
      !name ||
        /^\s|\s$/.test(name) ||
        !category ||
        !specification ||
        /^\s|\s$/.test(specification) ||
        !installDate ||
        installDate < threeMonthsAgo ||
        name.length > 255 ||
        specification.length > 1024
    );
  };
 
  return (
    <Form
      form={form}
      labelCol={{ span: 6 }}
      wrapperCol={{ span: 18 }}
      layout="horizontal"
      style={{ maxWidth: 800 }}
      colon={false}
      requiredMark={false}
      onFinish={onFinish}
      onFieldsChange={handleFieldsChange}
    >
      <Typography className="text-xl font-semibold text-[#cf2338] font-serif pb-5">
        Create New Asset
      </Typography>
 
      {/* Name */}
      <Form.Item
        label="Name"
        name="name"
        hasFeedback
        labelAlign="left"
        rules={[
          { validator: validateWhitespace },
          { max: 255, message: "Must be less than 255 characters!" },
        ]}
      >
        <Input />
      </Form.Item>
 
      {/* Category */}
      <Form.Item
        label="Category"
        name="category"
        hasFeedback
        labelAlign="left"
        rules={[{ required: true, message: "Please select a category!" }]}
      >
        <Selector />
      </Form.Item>
 
      {/* Specification */}
      <Form.Item
        label="Specification"
        name="specification"
        hasFeedback
        labelAlign="left"
        rules={[
          { max: 1024, message: "Must be less than 1024 characters!" },
          { validator: validateWhitespace },
        ]}
      >
        <Input.TextArea style={{ height: "100px", overflow: "auto" }} />
      </Form.Item>
 
      {/* Install Date */}
      <Form.Item
        label="Installed Date"
        name="installDate"
        hasFeedback
        rules={[
          { required: true, message: "Please select the installed date!" },
        ]}
        labelAlign="left"
      >
        <DatePicker
          type="date"
          data-testid="install-date"
          style={{ width: "100%" }}
          disabledDate={(current) => {
            const today = new Date();
            const threeMonthsAgo = new Date();
            threeMonthsAgo.setMonth(today.getMonth() - 3);
            threeMonthsAgo.setDate(today.getDate());
            const currentDate = current.toDate();
            return current && currentDate <= threeMonthsAgo;
          }}
        />
      </Form.Item>
 
      {/* State */}
      <Form.Item
        initialValue="available"
        name="state"
        // label="State"
        labelAlign="left"
      >
        <Radio.Group className="flex flex-col" aria-label="State">
          <Radio id="state" value="available" aria-label="Available">
            Available
          </Radio>
          <Radio id="state" value="not_available" aria-label="Not Available">
            Not Available
          </Radio>
        </Radio.Group>
      </Form.Item>
 
      {/* Button */}
      <div
        className="button-container"
        style={{ display: "flex", justifyContent: "flex-end", gap: "20px" }}
      >
        <Form.Item>
          <Button
            type="primary"
            name="save"
            danger
            htmlType="submit"
            disabled={isButtonDisabled}
            loading={isLoading}
          >
            Save
          </Button>
        </Form.Item>
        <Form.Item label="">
          <Button onClick={handleCancel}>Cancel</Button>
        </Form.Item>
      </div>
    </Form>
  );
}
 
export default AddAsset;