|
- "use client";
-
- import Check from "@mui/icons-material/Check";
- import Close from "@mui/icons-material/Close";
- import Button from "@mui/material/Button";
- import Stack from "@mui/material/Stack";
- import Tab from "@mui/material/Tab";
- import Tabs, { TabsProps } from "@mui/material/Tabs";
- import { useRouter } from "next/navigation";
- import React, { useCallback, useState } from "react";
- import { useTranslation } from "react-i18next";
- import { Task, TaskTemplate } from "@/app/api/tasks";
- import {
- FieldErrors,
- FormProvider,
- SubmitErrorHandler,
- SubmitHandler,
- useForm,
- } from "react-hook-form";
- import { CreateDepartmentInputs, saveDepartment } from "@/app/api/departments/actions";
- import { Error } from "@mui/icons-material";
- import { ProjectCategory } from "@/app/api/projects";
- import { Typography } from "@mui/material";
- import DepartmentDetails from "./DepartmentDetails";
- import { DepartmentResult } from "@/app/api/departments";
-
- interface Props {
- isEdit: Boolean;
- department?: CreateDepartmentInputs;
- depCodes: string[]
- }
-
- const CreateDepartment: React.FC<Props> = ({
- isEdit,
- department,
- depCodes,
- }) => {
- const [serverError, setServerError] = useState("");
- const { t } = useTranslation();
- const router = useRouter();
-
- console.log(department)
- console.log(depCodes)
-
- const handleCancel = () => {
- router.back();
- };
-
- const onSubmit = useCallback<SubmitHandler<CreateDepartmentInputs>>(
- async (data) => {
- try {
- console.log(data);
- let haveError = false
- if (depCodes.includes(data.code.toLowerCase().trim())) {
- formProps.setError("code", { message: t("Duplicated code."), type: "required" })
- haveError = true
- }
- if (haveError) {
- return
- }
- console.log("passed")
- setServerError("");
- // console.log(JSON.stringify(data));
- await saveDepartment(data)
- router.replace("/settings/department");
- } catch (e) {
- setServerError(t("An error has occurred. Please try again later."));
- }
- },
- [router, t],
- );
-
- const onSubmitError = useCallback<SubmitErrorHandler<CreateDepartmentInputs>>(
- (errors) => {
- console.log(errors)
- },
- [],
- );
-
- const formProps = useForm<CreateDepartmentInputs>({
- defaultValues: {
- id: department?.id,
- code: department?.code,
- name: department?.name,
- description: department?.description,
- },
- });
-
- const errors = formProps.formState.errors;
-
- return (
- <FormProvider {...formProps}>
- <Stack
- spacing={2}
- component="form"
- onSubmit={formProps.handleSubmit(onSubmit, onSubmitError)}
- >
- {
- <DepartmentDetails />
- }
-
- <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">
- {t("Confirm")}
- </Button>
- </Stack>
- </Stack>
- </FormProvider>
- );
- };
-
- export default CreateDepartment;
|