All files / pages/admin/AddAsset/components AddCategoryButton.tsx

67.34% Statements 33/49
66.66% Branches 16/24
75% Functions 6/8
67.34% Lines 33/49

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 1773x 3x 3x 3x 3x                                   8x 8x 8x   8x         8x 4x           4x                         8x 4x 4x 4x                   8x 3x     8x                 8x       8x 1x       1x       1x       1x     8x 1x       1x       1x       1x     8x                                                                                                                       8x   3x  
import { Button, Form, FormProps, Input, message } from "antd";
import { useEffect, useState } from "react";
import { CategoryAPICaller } from "../../../../services/apis/category.api";
import { useMutation } from "react-query";
import { CheckOutlined, CloseOutlined } from "@ant-design/icons";
import APIResponse from "../../../../types/APIResponse";
import { Category } from "@/types/Category";
 
// type
type FieldType = {
  name?: string;
  code?: string;
};
 
// prepare for send and get data from parent
interface ClickableTextProps {
  items: Category[];
  setItems: React.Dispatch<React.SetStateAction<Category[]>>;
}
 
function AddCategoryButton({ items, setItems }: ClickableTextProps) {
  // state
  const [isButtonDisabled, setIsButtonDisabled] = useState(true);
  const [showInputs, setShowInputs] = useState(false);
  const [form] = Form.useForm<FieldType>();
  // query
  const { mutate, data, isLoading, isError, error, isSuccess } = useMutation(
    CategoryAPICaller.createNew
  );
 
  // effect
  useEffect(() => {
    Iif (isError) {
      const errorResponse = (error as { response: { data: APIResponse } })
        .response.data;
      message.error(errorResponse.message);
    }
 
    Iif (isSuccess) {
      form.setFieldsValue({
        name: "",
        code: "",
      });
      const newCategory: Category = data.data.result;
      setShowInputs(false);
      setItems([...items, newCategory]);
      message.success("Category added successfully");
    }
  }, [isError, isSuccess]);
 
  // handlers
  const handleFieldsChange = () => {
    const name = form.getFieldValue("name");
    const code = form.getFieldValue("code");
    setIsButtonDisabled(
      !name ||
        !code ||
        !name.trim() ||
        !(code.length === 2) ||
        !(code.trim().length === 2) ||
        name.length > 255
    );
  };
 
  const handleTextClick = () => {
    setShowInputs(true);
  };
 
  const handleCancelClick = () => {
    setShowInputs(false);
    form.setFieldsValue({
      name: "",
      code: "",
    });
  };
 
  // trigger Mutation to post request
  const onFinish: FormProps<FieldType>["onFinish"] = (values) => {
    mutate(values);
  };
 
  const validateCode = (_: unknown, value: string) => {
    Iif (!value) {
      return Promise.reject(new Error("Not null"));
    }
 
    Iif (value && /^\s|\s$/.test(value)) {
      return Promise.reject(new Error("No spaces"));
    }
 
    Iif (value && value.length != 2) {
      return Promise.reject(new Error("Length is 2"));
    }
 
    return Promise.resolve();
  };
 
  const validateName = (_: unknown, value: string) => {
    Iif (!value) {
      return Promise.reject(new Error("Not null"));
    }
 
    Iif (value && /^\s|\s$/.test(value)) {
      return Promise.reject(new Error("No spaces"));
    }
 
    Iif (value && value.length > 255) {
      return Promise.reject(new Error("Length less than 255"));
    }
 
    return Promise.resolve();
  };
 
  const content = showInputs ? (
    <>
      <div
        style={{
          display: "flex",
          alignItems: "center",
        }}
      >
        <Form
          form={form}
          name="basic"
          onFinish={onFinish}
          autoComplete="on"
          onFieldsChange={handleFieldsChange}
        >
          <div style={{ display: "flex", alignItems: "center", gap: "1rem" }}>
            <Form.Item<FieldType>
              aria-label="Name"
              name="name"
              rules={[{ validator: validateName }]}
              style={{ width: "80%" }}
            >
              <Input placeholder="Category" />
            </Form.Item>
 
            <Form.Item<FieldType>
              arial-label="Code"
              name="code"
              rules={[{ validator: validateCode }]}
            >
              <Input placeholder="Prefix" />
            </Form.Item>
 
            <Form.Item className="flex justify-end">
              <Button
                type="default"
                htmlType="submit"
                name="save"
                className="bg-[#E20D1]"
                disabled={isButtonDisabled}
                loading={isLoading}
              >
                <CheckOutlined style={{ fontSize: "16px", color: "green" }} />
              </Button>
            </Form.Item>
            <Form.Item className="flex justify-end">
              <Button onClick={handleCancelClick} className="bg-[#E20D1]">
                <CloseOutlined style={{ fontSize: "16px", color: "red" }} />
              </Button>
            </Form.Item>
          </div>
        </Form>
      </div>
    </>
  ) : (
    <span onClick={handleTextClick} style={{ color: "red" }}>
      Add new category
    </span>
  );
 
  return <div>{content}</div>;
}
export default AddCategoryButton;