Files
frontend/src/components/dashboard/roadMissions/violations/Actions/EditViolation/EditViolationForm.jsx

118 lines
4.8 KiB
JavaScript

import { Controller, useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import StyledForm from "@/core/components/StyledForm";
import { Box, Button, DialogActions, DialogContent, Grid, Stack } from "@mui/material";
import MissionDates from "./MissionDates";
import * as yup from "yup";
import LtrTextField from "@/core/components/LtrTextField";
export const schema = yup
.object({
start_date: yup.string().nullable(),
start_time: yup.string().nullable(),
end_date: yup.string().nullable(),
end_time: yup.string().nullable(),
})
.test("valid-dates", function (values) {
if (!values) return false;
const hasStartDate = !!values.start_date;
const hasStartTime = !!values.start_time;
const hasEndDate = !!values.end_date;
const hasEndTime = !!values.end_time;
if (hasStartDate !== hasStartTime) {
return this.createError({
message: "تاریخ و زمان شروع باید هر دو وارد شوند",
});
}
if (hasEndDate !== hasEndTime) {
return this.createError({
message: "تاریخ و زمان پایان باید هر دو وارد شوند",
});
}
if (!((hasStartDate && hasStartTime) || (hasEndDate && hasEndTime))) {
return this.createError({
message: "حداقل تاریخ و زمان شروع یا پایان باید مشخص شود",
});
}
return true;
});
const EditViolationForm = ({ setOpenMachinesDialog, defaultValues, onSubmitBase }) => {
const {
control,
handleSubmit,
formState: { isSubmitting, errors },
} = useForm({ defaultValues, resolver: yupResolver(schema), mode: "all" });
const handleOnSubmit = async (data) => {
await onSubmitBase(data);
};
return (
<>
<StyledForm onSubmit={handleSubmit(handleOnSubmit)}>
<DialogContent dividers>
<Stack spacing={2} sx={{ flex: 1 }}>
<Stack>
<Grid container spacing={2}>
<MissionDates control={control} />
</Grid>
{errors?.[""]?.message && (
<Box
sx={{
color: "error.main",
textAlign: "center",
mb: 2,
fontSize: 14,
}}
>
{errors?.[""]?.message}
</Box>
)}
</Stack>
<Stack>
<Controller
control={control}
name={"end_km"}
render={({ field, fieldState: { error } }) => (
<LtrTextField
autoComplete="off"
type="tel"
value={field.value}
onChange={(e) => {
if (isNaN(Number(e.target.value))) return;
field.onChange(e.target.value);
}}
size="small"
fullWidth
label="کیلومتر خودرو / ساعت کار"
InputLabelProps={{ shrink: true }}
/>
)}
/>
</Stack>
</Stack>
</DialogContent>
<DialogActions sx={{ alignItems: "center", justifyContent: "center" }}>
<Button
onClick={() => setOpenMachinesDialog(false)}
variant="outlined"
color="secondary"
size="large"
>
{"بستن"}
</Button>
<Button disabled={isSubmitting} variant="contained" size="large" type="submit">
ثبت
</Button>
</DialogActions>
</StyledForm>
</>
);
};
export default EditViolationForm;