You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

253 lines
8.9 KiB

  1. "use client";
  2. import { useCallback, useEffect, useState } from "react";
  3. import CustomInputForm from "../CustomInputForm";
  4. import { useRouter, useSearchParams } from "next/navigation";
  5. import { useTranslation } from "react-i18next";
  6. import {
  7. FieldErrors,
  8. FormProvider,
  9. SubmitErrorHandler,
  10. SubmitHandler,
  11. useForm,
  12. } from "react-hook-form";
  13. import { CreateStaffInputs, saveStaff, testing } from "@/app/api/staff/actions";
  14. import { Button, Stack, Typography } from "@mui/material";
  15. // import CreateStaffForm from "../CreateStaffForm";
  16. import { comboProp, fetchCompanyCombo } from "@/app/api/companys/actions";
  17. import { fetchTeamCombo } from "@/app/api/team/actions";
  18. import { fetchDepartmentCombo } from "@/app/api/departments/actions";
  19. import { fetchPositionCombo } from "@/app/api/positions/actions";
  20. import { fetchGradeCombo } from "@/app/api/grades/actions";
  21. import { fetchSkillCombo } from "@/app/api/skill/actions";
  22. import { fetchSalaryCombo } from "@/app/api/salarys/actions";
  23. // import StaffInfo from "./StaffInfo";
  24. import { Check, Close } from "@mui/icons-material";
  25. import { ServerFetchError } from "@/app/utils/fetchUtil";
  26. import StaffInfo from "./StaffInfo";
  27. import { IndividualStaff } from "@/app/api/staff";
  28. import dayjs from "dayjs";
  29. import { INPUT_DATE_FORMAT } from "@/app/utils/formatUtil";
  30. import { List, differenceBy } from "lodash";
  31. export interface comboItem {
  32. company: comboProp[];
  33. team: comboProp[];
  34. department: comboProp[];
  35. position: comboProp[];
  36. grade: comboProp[];
  37. skill: comboProp[];
  38. salary: comboProp[];
  39. }
  40. interface formProps {
  41. Staff: IndividualStaff
  42. combos: comboItem;
  43. }
  44. const EditStaff: React.FC<formProps> = ({ Staff, combos }) => {
  45. const defaultSkillset = Staff.skillset.map((s: any) => s.skill.id)
  46. const { t } = useTranslation();
  47. const searchParams = useSearchParams()
  48. const id = parseInt(searchParams.get("id") || "0");
  49. const formProps = useForm<CreateStaffInputs>({
  50. defaultValues: {
  51. staffId: Staff.staffId,
  52. name: Staff.name,
  53. companyId: Staff.company.id,
  54. teamId: Staff.team?.id,
  55. departmentId: Staff.department?.id,
  56. gradeId: Staff.grade?.id,
  57. skillSetId: defaultSkillset,
  58. // removeSkillSetId: [],
  59. currentPositionId: Staff.currentPosition?.id,
  60. salaryId: Staff.salary.id,
  61. employType: Staff.employType,
  62. email: Staff.email,
  63. phone1: Staff.phone1,
  64. phone2: Staff.phone2,
  65. emergContactName: Staff.emergContactName,
  66. emergContactPhone: Staff.emergContactPhone,
  67. joinDate: dayjs(Staff.joinDate).toString() || "",
  68. joinPositionId: Staff.joinPosition?.id,
  69. departDate: dayjs(Staff.departDate).toString() || "",
  70. departReason: Staff.departReason,
  71. remark: Staff.remark,
  72. }});
  73. const [serverError, setServerError] = useState("");
  74. const router = useRouter();
  75. // const [tabIndex, setTabIndex] = useState(0);
  76. const errors = formProps.formState.errors;
  77. const checkDuplicates = (str1: string, str2: string, str3: string) => {
  78. return str1 === str2 || str1 === str3 || str2 === str3;
  79. }
  80. const onSubmit = useCallback<SubmitHandler<CreateStaffInputs>>(
  81. async (data) => {
  82. try {
  83. console.log(data);
  84. let haveError = false;
  85. let regex_email = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/
  86. let regex_phone = /^\d{8}$/
  87. // let removeSkillSetId: List<number> = []
  88. // if (data.skillSetId && defaultSkillset.length > data.skillSetId) {
  89. // removeSkillSetId = differenceBy(defaultSkillset, data.skillSetId)
  90. // }
  91. console.log(data.skillSetId)
  92. console.log(defaultSkillset)
  93. console.log(differenceBy(data.skillSetId, defaultSkillset))
  94. if (!regex_email.test(data.email)) {
  95. haveError = true
  96. formProps.setError("email", { message: t("Please Enter Correct Email."), type: "required" })
  97. }
  98. if(!regex_phone.test(data.phone1)) {
  99. haveError = true
  100. formProps.setError("phone1", { message: t("Please Enter Correct Phone No.."), type: "required" })
  101. }
  102. if(!regex_phone.test(data.emergContactPhone)) {
  103. haveError = true
  104. formProps.setError("emergContactPhone", { message: t("Please Enter Correct Phone No.."), type: "required" })
  105. }
  106. if (data.phone2 && data.phone2?.length > 0) {
  107. if(!regex_phone.test(data.phone2)) {
  108. haveError = true
  109. formProps.setError("phone2", { message: t("Please Enter Correct Phone No.."), type: "required" })
  110. }
  111. }
  112. if (data.phone1 === data.phone2 || data.phone1 === data.emergContactPhone || data.phone2 === data.emergContactPhone) {
  113. haveError = true
  114. formProps.setError("phone1", { message: t("Please Enter Different Phone No.."), type: "required" })
  115. if (data.phone2!.length > 0) {
  116. formProps.setError("phone2", { message: t("Please Enter Different Phone No.."), type: "required" })
  117. }
  118. formProps.setError("emergContactPhone", { message: t("Please Enter Different Phone No.."), type: "required" })
  119. }
  120. if (!regex_email.test(data.email)) {
  121. haveError = true
  122. formProps.setError("email", { message: t("Please Enter Correct Email."), type: "required" })
  123. }
  124. if (!data.companyId) {
  125. haveError = true
  126. formProps.setError("companyId", { message: t("Please Enter Company."), type: "required" })
  127. }
  128. if (!data.employType) {
  129. haveError = true
  130. formProps.setError("employType", { message: t("Please Enter Employ Type."), type: "required" })
  131. }
  132. if (!data.departmentId) {
  133. haveError = true
  134. formProps.setError("departmentId", { message: t("Please Enter Department."), type: "required" })
  135. }
  136. if (!data.salaryId) {
  137. haveError = true
  138. formProps.setError("salaryId", { message: t("Please Enter Salary."), type: "required" })
  139. }
  140. if (!data.joinDate) {
  141. haveError = true
  142. formProps.setError("joinDate", { message: t("Please Enter Join Date."), type: "required" })
  143. }
  144. if (data.departDate && new Date(data.departDate) <= new Date(data.joinDate)) {
  145. haveError = true
  146. formProps.setError("departDate", { message: t("Depart Date cannot be earlier than Join Date."), type: "required" })
  147. }
  148. if (haveError) {
  149. return
  150. }
  151. console.log("passed")
  152. const postData = {
  153. id: id,
  154. ...data,
  155. // removeSkillSetId: removeSkillSetId
  156. }
  157. await saveStaff(postData)
  158. router.replace("/settings/staff")
  159. } catch (e: any) {
  160. console.log(e);
  161. formProps.setError("staffId", { message: t("Please Enter Employ Type."), type: "required" })
  162. let msg = ""
  163. if (e.message === "Duplicated StaffId Found") {
  164. msg = t("Duplicated StaffId Found")
  165. }
  166. setServerError(`${t("An error has occurred. Please try again later.")} ${msg} `);
  167. }
  168. },
  169. [router]
  170. );
  171. const handleCancel = () => {
  172. router.back();
  173. };
  174. const resetStaff = useCallback(() => {
  175. formProps.reset({
  176. staffId: Staff.staffId,
  177. name: Staff.name,
  178. companyId: Staff.company.id,
  179. teamId: Staff.team?.id,
  180. departmentId: Staff.department?.id,
  181. gradeId: Staff.grade?.id,
  182. skillSetId: defaultSkillset,
  183. // removeSkillSetId: [],
  184. currentPositionId: Staff.currentPosition?.id,
  185. salaryId: Staff.salary.id,
  186. employType: Staff.employType,
  187. email: Staff.email,
  188. phone1: Staff.phone1,
  189. phone2: Staff.phone2,
  190. emergContactName: Staff.emergContactName,
  191. emergContactPhone: Staff.emergContactPhone,
  192. joinDate: dayjs(Staff.joinDate).format(INPUT_DATE_FORMAT) || "",
  193. joinPositionId: Staff.joinPosition?.id,
  194. departDate: !Staff.departDate ? "" : dayjs(Staff.departDate).format(INPUT_DATE_FORMAT),
  195. departReason: Staff.departReason,
  196. remark: Staff.remark,
  197. });
  198. }, []);
  199. useEffect(() => {
  200. console.log(Staff)
  201. resetStaff()
  202. }, [Staff, combos]);
  203. return (
  204. <>
  205. <FormProvider {...formProps}>
  206. <Stack
  207. spacing={2}
  208. component="form"
  209. onSubmit={formProps.handleSubmit(onSubmit)}
  210. >
  211. {serverError && (
  212. <Typography variant="body2" color="error" alignSelf="flex-end">
  213. {serverError}
  214. </Typography>
  215. )}
  216. {Staff && <StaffInfo combos={combos}/>}
  217. <Stack direction="row" justifyContent="flex-end" gap={1}>
  218. <Button
  219. variant="outlined"
  220. startIcon={<Close />}
  221. onClick={handleCancel}
  222. >
  223. {t("Cancel")}
  224. </Button>
  225. <Button
  226. variant="contained"
  227. startIcon={<Check />}
  228. type="submit"
  229. // disabled={Boolean(formProps.watch("isGridEditing"))}
  230. >
  231. {t("Confirm")}
  232. </Button>
  233. </Stack>
  234. </Stack>
  235. </FormProvider>
  236. </>
  237. );
  238. };
  239. export default EditStaff;