All files / pages/admin/EditAssignment EditAssignment.tsx

86.15% Statements 56/65
78.26% Branches 18/23
76.92% Functions 10/13
86.15% Lines 56/65

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 2891x 1x                 1x 1x 1x 1x     1x 1x   1x   1x                       5x   5x 5x     5x 1x       4x 3x 3x 3x 3x 3x 3x     3x                 3x   2x         3x 2x 1x 1x   1x             1x 1x       3x 3x 1x         3x 1x           3x 2x           2x                       3x       3x       3x 1x             1x     3x 2x 2x   2x         3x 1x                     2x       2x                                                                                                               3x             3x                                                                                                                         1x  
import { LoadingOutlined, SearchOutlined } from "@ant-design/icons";
import {
  Button,
  DatePicker,
  Form,
  Input,
  Spin,
  Typography,
  message,
} from "antd";
import { useNavigate, useParams } from "react-router-dom";
import ModalSelectUser from "../CreateAssignment/components/ModalSelectUser";
import ModalSelectAsset from "../CreateAssignment/components/ModalSelectAsset";
import { useEffect, useState } from "react";
import { User } from "@/types/User";
import { AssetResponse } from "@/types/Asset";
import { AssignmentAPICaller } from "@/services/apis/assignment.api";
import { useMutation, useQuery } from "react-query";
import APIResponse from "@/types/APIResponse";
import dayjs from "dayjs";
import { Assignment } from "@/types/Assignment";
import NotFoundPage from "@/components/404NotFound/NotFoundPage";
import { AssignmentResponse } from "@/types/AssignmentResponse";
 
type CreateAssignmentBody = {
  fullName: string;
  assetName: string;
  assignedDate: Date;
  note: string;
};
 
function EditAssignment() {
  // state
  const { id } = useParams<{ id: string }>();
 
  const isValidId = (id: string) => {
    return !isNaN(Number(id));
  };
 
  if (!isValidId(id as string)) {
    return <NotFoundPage />;
  }
 
  // 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>(false);
  const [form] = Form.useForm();
  const navigate = useNavigate();
 
  // query
  const { mutate, data, isLoading, isError, error, isSuccess } = useMutation(
    AssignmentAPICaller.updateAssignment
  );
 
  const {
    data: assignmentData,
    isSuccess: isGetAssignmentSuccess,
    isLoading: isGetAssignmentLoading,
    error: getAssignmentError,
  } = useQuery(
    ["getAssignment", { id }],
    () => AssignmentAPICaller.getAssignment(Number.parseInt(id ?? "0")),
    { retry: false }
  );
 
  // useEffect
  useEffect(() => {
    if (isGetAssignmentSuccess && assignmentData) {
      const data = assignmentData?.data as APIResponse;
      const assignment = data.result as Assignment;
 
      form.setFieldsValue({
        fullName: `${assignment.assignTo.firstName} ${assignment.assignTo.lastName}`,
        assetName: assignment.asset.name,
        assignedDate: dayjs(assignment.assignedDate).valueOf(),
        note: assignment.note,
      });
 
      setUserSelected(assignment.assignTo);
      setAssetSelected(assignment.asset);
    }
  }, [isGetAssignmentSuccess, assignmentData]);
 
  useEffect(() => {
    if (userSelected) {
      form.setFieldsValue({
        fullName: `${userSelected.firstName} ${userSelected.lastName}`,
      });
    }
 
    if (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("Update assignment success");
    }
  }, [isSuccess, isError]);
 
  // handlers
  const handleInputUser = () => {
    setIsModalSelectUserOpen(true);
  };
 
  const handleInputAsset = () => {
    setIsModalSelectAssetOpen(true);
  };
 
  const onFinish = (values: CreateAssignmentBody) => {
    const body = {
      userId: userSelected?.id,
      assetId: assetSelected?.id,
      assignedDate: dayjs(values.assignedDate).format("YYYY-MM-DD"),
      note: values.note,
    };
 
    mutate({ assignmentId: Number.parseInt(id ?? "0"), body });
  };
 
  const handleFieldsChange = () => {
    const fields = form.getFieldsValue();
    const { fullName, assetName, assignedDate, note } = fields;
 
    setIsButtonDisabled(
      !fullName || !assetName || !assignedDate || (note && note.length > 1024)
    );
  };
 
  if (isGetAssignmentLoading) {
    return (
      <div className="flex justify-center items-center">
        <Spin
          size="large"
          indicator={<LoadingOutlined spin />}
          className="text-[#cf2338]"
        />
      </div>
    );
  }
 
  Iif (getAssignmentError) {
    return <div>Assignment Not Found</div>;
  }
 
  return (
    <>
      <Typography className="text-xl font-semibold text-[#cf2338] font-serif pb-5">
        Edit 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"
          getValueProps={(value) => ({ value: value && dayjs(Number(value)) })}
        >
          <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"
          hasFeedback
          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 EditAssignment;