|
- "use client";
- import { useCallback, useEffect, useState } from "react";
- import CustomInputForm from "../CustomInputForm";
- import { useRouter, useSearchParams } from "next/navigation";
- import { useTranslation } from "react-i18next";
- import {
- FieldErrors,
- FormProvider,
- SubmitErrorHandler,
- SubmitHandler,
- useForm,
- } from "react-hook-form";
- import { CreateStaffInputs, saveStaff, testing } from "@/app/api/staff/actions";
- import { Button, Stack, Typography } from "@mui/material";
- // import CreateStaffForm from "../CreateStaffForm";
- import { comboProp, fetchCompanyCombo } from "@/app/api/companys/actions";
- import { fetchTeamCombo } from "@/app/api/team/actions";
- import { fetchDepartmentCombo } from "@/app/api/departments/actions";
- import { fetchPositionCombo } from "@/app/api/positions/actions";
- import { fetchGradeCombo } from "@/app/api/grades/actions";
- import { fetchSkillCombo } from "@/app/api/skill/actions";
- import { fetchSalaryCombo } from "@/app/api/salarys/actions";
- // import StaffInfo from "./StaffInfo";
- import { Check, Close } from "@mui/icons-material";
- import { ServerFetchError } from "@/app/utils/fetchUtil";
- import StaffInfo from "./StaffInfo";
- import { IndividualStaff } from "@/app/api/staff";
- import dayjs from "dayjs";
- import { INPUT_DATE_FORMAT } from "@/app/utils/formatUtil";
- import { List, differenceBy } from "lodash";
-
- export interface comboItem {
- company: comboProp[];
- team: comboProp[];
- department: comboProp[];
- position: comboProp[];
- grade: comboProp[];
- skill: comboProp[];
- salary: comboProp[];
- }
-
- interface formProps {
- Staff: IndividualStaff
- combos: comboItem;
- }
-
-
- const EditStaff: React.FC<formProps> = ({ Staff, combos }) => {
- const defaultSkillset = Staff.skillset.map((s: any) => s.skill.id)
- const { t } = useTranslation();
- const searchParams = useSearchParams()
- const id = parseInt(searchParams.get("id") || "0");
- const formProps = useForm<CreateStaffInputs>({
- defaultValues: {
- staffId: Staff.staffId,
- name: Staff.name,
- companyId: Staff.company.id,
- teamId: Staff.team?.id,
- departmentId: Staff.department?.id,
- gradeId: Staff.grade?.id,
- skillSetId: defaultSkillset,
- // removeSkillSetId: [],
- currentPositionId: Staff.currentPosition?.id,
- salaryId: Staff.salary.id,
- employType: Staff.employType,
- email: Staff.email,
- phone1: Staff.phone1,
- phone2: Staff.phone2,
- emergContactName: Staff.emergContactName,
- emergContactPhone: Staff.emergContactPhone,
- joinDate: dayjs(Staff.joinDate).toString() || "",
- joinPositionId: Staff.joinPosition?.id,
- departDate: dayjs(Staff.departDate).toString() || "",
- departReason: Staff.departReason,
- remark: Staff.remark,
- }});
- const [serverError, setServerError] = useState("");
- const router = useRouter();
- // const [tabIndex, setTabIndex] = useState(0);
-
- const errors = formProps.formState.errors;
-
- const checkDuplicates = (str1: string, str2: string, str3: string) => {
- return str1 === str2 || str1 === str3 || str2 === str3;
- }
-
- const onSubmit = useCallback<SubmitHandler<CreateStaffInputs>>(
- async (data) => {
- try {
- console.log(data);
- let haveError = false;
- let regex_email = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/
- let regex_phone = /^\d{8}$/
- // let removeSkillSetId: List<number> = []
-
- // if (data.skillSetId && defaultSkillset.length > data.skillSetId) {
- // removeSkillSetId = differenceBy(defaultSkillset, data.skillSetId)
- // }
- console.log(data.skillSetId)
- console.log(defaultSkillset)
- console.log(differenceBy(data.skillSetId, defaultSkillset))
-
- if (!regex_email.test(data.email)) {
- haveError = true
- formProps.setError("email", { message: t("Please Enter Correct Email."), type: "required" })
- }
- if(!regex_phone.test(data.phone1)) {
- haveError = true
- formProps.setError("phone1", { message: t("Please Enter Correct Phone No.."), type: "required" })
- }
- if(!regex_phone.test(data.emergContactPhone)) {
- haveError = true
- formProps.setError("emergContactPhone", { message: t("Please Enter Correct Phone No.."), type: "required" })
- }
- if (data.phone2 && data.phone2?.length > 0) {
- if(!regex_phone.test(data.phone2)) {
- haveError = true
- formProps.setError("phone2", { message: t("Please Enter Correct Phone No.."), type: "required" })
- }
- }
- if (data.phone1 === data.phone2 || data.phone1 === data.emergContactPhone || data.phone2 === data.emergContactPhone) {
- haveError = true
- formProps.setError("phone1", { message: t("Please Enter Different Phone No.."), type: "required" })
- if (data.phone2!.length > 0) {
- formProps.setError("phone2", { message: t("Please Enter Different Phone No.."), type: "required" })
- }
- formProps.setError("emergContactPhone", { message: t("Please Enter Different Phone No.."), type: "required" })
- }
- if (!regex_email.test(data.email)) {
- haveError = true
- formProps.setError("email", { message: t("Please Enter Correct Email."), type: "required" })
- }
- if (!data.companyId) {
- haveError = true
- formProps.setError("companyId", { message: t("Please Enter Company."), type: "required" })
- }
- if (!data.employType) {
- haveError = true
- formProps.setError("employType", { message: t("Please Enter Employ Type."), type: "required" })
- }
- if (!data.departmentId) {
- haveError = true
- formProps.setError("departmentId", { message: t("Please Enter Department."), type: "required" })
- }
- if (!data.salaryId) {
- haveError = true
- formProps.setError("salaryId", { message: t("Please Enter Salary."), type: "required" })
- }
- if (!data.joinDate) {
- haveError = true
- formProps.setError("joinDate", { message: t("Please Enter Join Date."), type: "required" })
- }
- if (data.departDate && new Date(data.departDate) <= new Date(data.joinDate)) {
- haveError = true
- formProps.setError("departDate", { message: t("Depart Date cannot be earlier than Join Date."), type: "required" })
- }
- if (haveError) {
- return
- }
- console.log("passed")
- const postData = {
- id: id,
- ...data,
- // removeSkillSetId: removeSkillSetId
- }
- await saveStaff(postData)
- router.replace("/settings/staff")
- } catch (e: any) {
- console.log(e);
- formProps.setError("staffId", { message: t("Please Enter Employ Type."), type: "required" })
- let msg = ""
- if (e.message === "Duplicated StaffId Found") {
- msg = t("Duplicated StaffId Found")
- }
- setServerError(`${t("An error has occurred. Please try again later.")} ${msg} `);
- }
- },
- [router]
- );
-
- const handleCancel = () => {
- router.back();
- };
-
- const resetStaff = useCallback(() => {
- formProps.reset({
- staffId: Staff.staffId,
- name: Staff.name,
- companyId: Staff.company.id,
- teamId: Staff.team?.id,
- departmentId: Staff.department?.id,
- gradeId: Staff.grade?.id,
- skillSetId: defaultSkillset,
- // removeSkillSetId: [],
- currentPositionId: Staff.currentPosition?.id,
- salaryId: Staff.salary.id,
- employType: Staff.employType,
- email: Staff.email,
- phone1: Staff.phone1,
- phone2: Staff.phone2,
- emergContactName: Staff.emergContactName,
- emergContactPhone: Staff.emergContactPhone,
- joinDate: dayjs(Staff.joinDate).format(INPUT_DATE_FORMAT) || "",
- joinPositionId: Staff.joinPosition?.id,
- departDate: !Staff.departDate ? "" : dayjs(Staff.departDate).format(INPUT_DATE_FORMAT),
- departReason: Staff.departReason,
- remark: Staff.remark,
- });
- }, []);
-
- useEffect(() => {
- console.log(Staff)
- resetStaff()
- }, [Staff, combos]);
-
- return (
- <>
- <FormProvider {...formProps}>
- <Stack
- spacing={2}
- component="form"
- onSubmit={formProps.handleSubmit(onSubmit)}
- >
- {serverError && (
- <Typography variant="body2" color="error" alignSelf="flex-end">
- {serverError}
- </Typography>
- )}
- {Staff && <StaffInfo combos={combos}/>}
- <Stack direction="row" justifyContent="flex-end" gap={1}>
- <Button
- variant="outlined"
- startIcon={<Close />}
- onClick={handleCancel}
- >
- {t("Cancel")}
- </Button>
- <Button
- variant="contained"
- startIcon={<Check />}
- type="submit"
- // disabled={Boolean(formProps.watch("isGridEditing"))}
- >
- {t("Confirm")}
- </Button>
- </Stack>
- </Stack>
- </FormProvider>
- </>
- );
- };
-
- export default EditStaff;
|