All files / pages/admin/CreateAssignment CreateAssignment.tsx

73.33% Statements 33/45
45.45% Branches 5/11
55.55% Functions 5/9
73.33% Lines 33/45

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 2221x 1x 1x 1x 1x     1x 1x   1x 1x                       5x 4x 4x 4x 4x 4x 4x     4x           4x 4x           4x             4x 4x           4x                       4x       4x       4x                     4x 27x 27x   27x         4x                                                                                                                           258x                                                                                                                     1x  
import { SearchOutlined } from "@ant-design/icons";
import { Button, DatePicker, Form, Input, Typography, message } from "antd";
import ModalSelectUser from "./components/ModalSelectUser";
import { useEffect, useState } from "react";
import ModalSelectAsset from "./components/ModalSelectAsset";
import { User } from "@/types/User";
import { AssetResponse } from "@/types/Asset";
import { useMutation } from "react-query";
import { AssignmentAPICaller } from "@/services/apis/assignment.api";
import APIResponse from "@/types/APIResponse";
import dayjs from "dayjs";
import { useNavigate } from "react-router-dom";
import { AssignmentResponse } from "@/types/AssignmentResponse";
 
type CreateAssignmentBody = {
  fullName: string;
  assetName: string;
  assignedDate: Date;
  note: string;
};
 
function CreateAssignment() {
  // state
  const [isModalSelectUserOpen, setIsModalSelectUserOpen] = useState(false);
  const [isModalSelectAssetOpen, setIsModalSelectAssetOpen] = useState(false);
  const [userSelected, setUserSelected] = useState<User>();
  const [assetSelected, setAssetSelected] = useState<AssetResponse>();
  const [isButtonDisabled, setIsButtonDisabled] = useState<boolean>(true);
  const [form] = Form.useForm();
  const navigate = useNavigate();
 
  // query
  const { mutate, data, isLoading, isError, error, isSuccess } = useMutation(
    AssignmentAPICaller.createAssignment
  );
 
  // useEffect
 
  useEffect(() => {
    Iif (userSelected) {
      form.setFieldsValue({
        fullName: `${userSelected.firstName} ${userSelected.lastName}`,
      });
    }
 
    Iif (assetSelected) {
      form.setFieldsValue({
        assetName: assetSelected.name,
      });
    }
  }, [userSelected, assetSelected]);
 
  useEffect(() => {
    Iif (isError) {
      const errorResponse = (error as { response: { data: APIResponse } })
        .response.data;
      message.error(errorResponse.message);
    }
 
    Iif (isSuccess) {
      const newAssignment: AssignmentResponse = data.data.result;
      navigate("/admin/assignments", {
        state: {
          assignment: newAssignment,
        },
      });
      message.success("Create assignment success");
    }
  }, [isSuccess, isError]);
 
  // handlers
  const handleInputUser = () => {
    setIsModalSelectUserOpen(true);
  };
 
  const handleInputAsset = () => {
    setIsModalSelectAssetOpen(true);
  };
 
  const onFinish = (values: CreateAssignmentBody) => {
    // call api here
    const body = {
      ...values,
      userId: userSelected?.id,
      assetId: assetSelected?.id,
      assignedDate: dayjs(values.assignedDate).format("YYYY-MM-DD"),
    };
    mutate(body);
  };
 
  const handleFieldsChange = () => {
    const fields = form.getFieldsValue();
    const { fullName, assetName, assignedDate, note } = fields;
 
    setIsButtonDisabled(
      !fullName || !assetName || !assignedDate || (note && note.length > 1024)
    );
  };
 
  return (
    <>
      <Typography className="text-xl font-semibold text-[#cf2338] font-serif pb-5">
        Create New Assignment
      </Typography>
 
      <Form
        form={form}
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 18 }}
        layout="horizontal"
        style={{ maxWidth: 800 }}
        colon={false}
        requiredMark={false}
        onFinish={onFinish}
        onFieldsChange={handleFieldsChange}
      >
        <Form.Item
          label="User"
          name="fullName"
          hasFeedback
          labelAlign="left"
          rules={[{ required: true, message: "Please select the user!" }]}
        >
          <Input
            readOnly
            suffix={<SearchOutlined />}
            onClick={handleInputUser}
            value={userSelected?.username}
            placeholder="Select User"
          />
        </Form.Item>
 
        <Form.Item
          label="Asset"
          name="assetName"
          hasFeedback
          labelAlign="left"
          rules={[{ required: true, message: "Please select asset" }]}
        >
          <Input
            readOnly
            onClick={handleInputAsset}
            suffix={<SearchOutlined />}
            placeholder="Select Asset"
          />
        </Form.Item>
 
        <Form.Item
          label="Assigned Date"
          name="assignedDate"
          hasFeedback
          rules={[
            { required: true, message: "Please select the assigned date!" },
          ]}
          labelAlign="left"
        >
          <DatePicker
            type="date"
            data-testid="assigned-date"
            style={{ width: "100%" }}
            disabledDate={(current) => {
              return (
                current && current.endOf("day").isBefore(new Date(), "day")
              );
            }}
            placeholder="Select Date"
          />
        </Form.Item>
        <Form.Item
          name="note"
          label="Note"
          labelAlign="left"
          rules={[{ max: 1024, message: "Must be less than 1024 characters!" }]}
        >
          <Input.TextArea rows={4} placeholder="Note" />
        </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"
              loading={isLoading}
              disabled={isButtonDisabled}
            >
              Save
            </Button>
          </Form.Item>
          <Form.Item label="">
            <Button
              onClick={() => {
                navigate("/admin/assignments");
              }}
            >
              Cancel
            </Button>
          </Form.Item>
        </div>
      </Form>
 
      <ModalSelectUser
        isOpen={isModalSelectUserOpen}
        setIsOpenModal={setIsModalSelectUserOpen}
        setUserSelected={setUserSelected}
      />
      <ModalSelectAsset
        isOpen={isModalSelectAssetOpen}
        setIsOpenModal={setIsModalSelectAssetOpen}
        setAsset={setAssetSelected}
      />
    </>
  );
}
 
export default CreateAssignment;