|
- // material-ui
- import {
- Button,
- Grid, TextField,
- Autocomplete,
- Typography
- } from '@mui/material';
- import MainCard from "components/MainCard";
- import { useForm } from "react-hook-form";
- import * as React from "react";
- import * as DateUtils from "utils/DateUtils";
- import * as ComboData from "utils/ComboData";
- import {PNSPS_BUTTON_THEME} from "../../../themes/buttonConst";
- import {ThemeProvider} from "@emotion/react";
-
- import {DatePicker} from "@mui/x-date-pickers/DatePicker";
- import dayjs from "dayjs";
- import {DemoItem} from "@mui/x-date-pickers/internals/demo";
- import {LocalizationProvider} from "@mui/x-date-pickers/LocalizationProvider";
- import {AdapterDayjs} from "@mui/x-date-pickers/AdapterDayjs";
-
- const getDefaultDateFrom = () => DateUtils.dateValue(new Date().setDate(new Date().getDate() - 14));
- const getDefaultDateTo = () => DateUtils.dateValue(new Date());
-
- const isSubmitDateEmpty = (value) =>
- value == null || value === "" || value === "dd / mm / yyyy";
-
- const isBlank = (value) => value == null || String(value).trim() === "";
-
- const toDayjsOrNull = (value) => {
- if (isSubmitDateEmpty(value)) return null;
- const d = dayjs(value);
- return d.isValid() ? d : null;
- };
-
- // ==============================|| DASHBOARD - DEFAULT ||============================== //
- const SearchPublicNoticeForm = ({ applySearch, searchCriteria, onGridReady }) => {
-
- const [minDate, setMinDate] = React.useState(searchCriteria.dateFrom);
- const [maxDate, setMaxDate] = React.useState(searchCriteria.dateTo);
- const [status, setStatus] = React.useState(ComboData.paymentStatus[0]);
- const [payMethod, setPayMethod] = React.useState(ComboData.payMethod[0]);
- const marginBottom = 2.5;
-
- const [fromDateValue, setFromDateValue] = React.useState("dd / mm / yyyy");
- const [toDateValue, setToDateValue] = React.useState("dd / mm / yyyy");
- const prevHasOtherRef = React.useRef(null);
-
- React.useEffect(() => {
- if(searchCriteria.status!=undefined){
- if(searchCriteria.status === ""){
- ComboData.paymentStatus[0]
- }else{
- setStatus(ComboData.paymentStatus.find(item => item.type === searchCriteria.status))
- }
- }else{
- setStatus(ComboData.paymentStatus[0])
- }
- }, [searchCriteria]);
-
- React.useEffect(() => {
- const defaultPayMethod = ComboData.payMethod[0];
- const value = searchCriteria?.payMethod; // may be [], null, undefined, or array of strings
-
- if (!value || value.length === 0) {
- setPayMethod(defaultPayMethod);
- return;
- }
-
- // Find the matching entry whose type array matches value contents
- const found = ComboData.payMethod.find(item =>
- Array.isArray(item.type) &&
- item.type.length === value.length &&
- item.type.every((v, i) => v === value[i]) // strict positional match
- );
-
- setPayMethod(found ?? defaultPayMethod);
- }, [searchCriteria?.payMethod]);
-
-
- React.useEffect(() => {
- setFromDateValue(minDate);
- }, [minDate]);
-
- React.useEffect(() => {
- setToDateValue(maxDate);
- }, [maxDate]);
-
- const { reset, register, handleSubmit, watch } = useForm({
- defaultValues: {
- code: searchCriteria.code || "",
- transNo: searchCriteria.transNo || ""
- }
- });
- const code = watch("code");
- const transNo = watch("transNo");
-
- // add near the top inside the component (after useState for payMethod)
- const toPayMethodArray = (opt) => {
- if (!opt || opt.type === 'all') return [];
- return Array.isArray(opt.type) ? opt.type : [opt.type];
- };
-
- const clearSubmitDates = () => {
- setMinDate(null);
- setMaxDate(null);
- };
-
- const restoreDefaultSubmitDates = () => {
- setMinDate(getDefaultDateFrom());
- setMaxDate(getDefaultDateTo());
- };
-
- const hasOtherCriteria = (textFields = {}) => {
- if (!isBlank(textFields.code)) return true;
- if (!isBlank(textFields.transNo)) return true;
- if (status?.type && status.type !== "all" && status.type !== "") return true;
- if (payMethod?.type && payMethod.type !== "all") return true;
- return false;
- };
-
- React.useEffect(() => {
- const hasOther = hasOtherCriteria({ code, transNo });
- if (prevHasOtherRef.current === null) {
- prevHasOtherRef.current = hasOther;
- return;
- }
- if (hasOther && !prevHasOtherRef.current) {
- clearSubmitDates();
- } else if (!hasOther && prevHasOtherRef.current) {
- // Only refill defaults when From or To is empty; keep user-entered dates otherwise
- if (isSubmitDateEmpty(minDate) || isSubmitDateEmpty(maxDate)) {
- restoreDefaultSubmitDates();
- }
- }
- prevHasOtherRef.current = hasOther;
- }, [code, transNo, status, payMethod]);
-
- const onSubmit = (data) => {
- let sentDateFrom = "";
- let sentDateTo = "";
-
- const hasOther = hasOtherCriteria({
- code: data.code,
- transNo: data.transNo
- });
- const datesEmpty = isSubmitDateEmpty(fromDateValue) || isSubmitDateEmpty(toDateValue)
- || minDate == null || maxDate == null;
-
- if (!hasOther && datesEmpty) {
- const dateFrom = getDefaultDateFrom();
- const dateTo = getDefaultDateTo();
- setMinDate(dateFrom);
- setMaxDate(dateTo);
- sentDateFrom = dateFrom;
- sentDateTo = dateTo;
- } else if (!datesEmpty) {
- sentDateFrom = DateUtils.dateValue(fromDateValue);
- sentDateTo = DateUtils.dateValue(toDateValue);
- }
-
- const temp = {
- code: data.code,
- transNo: data.transNo,
- dateFrom: sentDateFrom,
- dateTo: sentDateTo,
- status : (status?.type && status?.type != 'all') ? status?.type : "",
- payMethod : toPayMethodArray(payMethod),
- start:0,
- limit:10
- };
- if (searchCriteria?.sort && searchCriteria?.direction) {
- temp.sort = searchCriteria.sort;
- temp.direction = searchCriteria.direction;
- }
- applySearch(temp);
- };
-
- function resetForm() {
- setStatus(ComboData.paymentStatus[0]);
- setPayMethod(ComboData.payMethod[0]);
- const dateFrom = getDefaultDateFrom();
- const dateTo = getDefaultDateTo();
- setMinDate(dateFrom);
- setMaxDate(dateTo);
- reset({
- code:"",
- transNo:""
- });
- prevHasOtherRef.current = false;
- localStorage.setItem('searchCriteria',"");
- applySearch({
- code: "",
- transNo: "",
- dateFrom,
- dateTo,
- status: "",
- payMethod: [],
- start: 0,
- limit: 10
- });
- }
-
-
- return (
- <MainCard xs={12} md={12} lg={12}
- border={false}
- content={false}
- >
-
- <form onSubmit={handleSubmit(onSubmit)} >
- <Grid container sx={{ backgroundColor: '#ffffff', ml: 2, mt: 1, mb: marginBottom}} width="98%">
- {/*row 1*/}
- <Grid item justifyContent="space-between" alignItems="center" sx={{mt:1,ml:3,mb:2.5}}>
- <Typography variant="pnspsFormHeader" >
- Search
- </Typography>
- </Grid>
- {/*row 2*/}
-
- <Grid container display="flex" alignItems={"center"}>
- <Grid item xs={9} s={6} md={5} lg={3} sx={{ ml: 3, mr: 3,mb: marginBottom}}>
- <TextField
- fullWidth
- {...register("code")}
- id='code'
- label="Application No."
- defaultValue={searchCriteria.code}
- InputLabelProps={{
- shrink: true
- }}
- />
- </Grid>
-
- <Grid item xs={9} s={6} md={5} lg={3} sx={{ml:3, mr:3, mb:marginBottom}}>
- <Grid container spacing={1}>
- <Grid item xs={6}>
- <LocalizationProvider dateAdapter={AdapterDayjs}>
- <DemoItem components={['DatePicker']}>
- <DatePicker
- id="dateFrom"
- onError={() => {}}
- slotProps={{
- field: { readOnly: true, clearable: true },
- textField: {
- InputLabelProps: { shrink: true },
- error: false,
- helperText: null
- },
- }}
- format="DD/MM/YYYY"
- label="Payment Date (From)"
- value={toDayjsOrNull(minDate)}
- maxDate={toDayjsOrNull(maxDate)}
- onChange={(newValue) => {
- setMinDate(newValue && newValue.isValid?.() ? newValue : null);
- }}
- />
- </DemoItem >
- </LocalizationProvider>
- </Grid>
- <Grid item xs={6}>
- <LocalizationProvider dateAdapter={AdapterDayjs}>
- <DemoItem components={['DatePicker']}>
- <DatePicker
- id="dateTo"
- onError={() => {}}
- slotProps={{
- field: { readOnly: true, clearable: true },
- textField: {
- InputLabelProps: { shrink: true },
- error: false,
- helperText: null
- },
- }}
- format="DD/MM/YYYY"
- label="Payment Date (To)"
- value={toDayjsOrNull(maxDate)}
- minDate={toDayjsOrNull(minDate)}
- onChange={(newValue) => {
- setMaxDate(newValue && newValue.isValid?.() ? newValue : null);
- }}
- />
- </DemoItem >
- </LocalizationProvider>
- </Grid>
- </Grid>
- </Grid>
-
- <Grid item xs={9} s={6} md={5} lg={3} sx={{ ml: 3, mr: 3, mb: marginBottom}}>
- <TextField
- fullWidth
- {...register("transNo")}
- id='transNo'
- label="Payment No. / Payment Reference No."
- defaultValue={searchCriteria.transNo}
- InputLabelProps={{
- shrink: true
- }}
- />
- </Grid>
-
- <Grid item xs={9} s={6} md={5} lg={3} sx={{ ml: 3, mr: 3, mb: marginBottom }}>
- <Autocomplete
- {...register("status")}
- disablePortal={false}
- size="small"
- id="status"
- filterOptions={(options) => options}
- options={ComboData.paymentStatus}
- value={status}
- getOptionLabel={(option) => (option?.label != null ? String(option.label) : "")}
- inputValue={status?.label ? status?.label : ""}
- onChange={(event, newValue) => {
- if(newValue==null){
- setStatus(ComboData.paymentStatus[0]);
- }else{
- setStatus(newValue);
- }
- }}
- sx={{
- '& .MuiInputBase-root': { alignItems: 'center' },
- '& .MuiAutocomplete-endAdornment': { top: '50%', transform: 'translateY(-50%)' },
- '& .MuiOutlinedInput-root': { height: 40 }
- }}
- renderInput={(params) => (
- <TextField {...params}
- label="Status"
- InputLabelProps={{ shrink: true }}
- />
- )}
- />
- </Grid>
-
- <Grid item xs={9} s={6} md={5} lg={3} sx={{ ml: 3, mr: 3, mb: marginBottom }}>
- <Autocomplete
- {...register("payMethod")}
- disablePortal={false}
- size="small"
- id="payMethod"
- filterOptions={(options) => options}
- options={ComboData.payMethod}
- value={payMethod}
- getOptionLabel={(option) => (option?.label != null ? String(option.label) : "")}
- inputValue={payMethod?.label ? payMethod?.label : ""}
- onChange={(event, newValue) => {
- if(newValue==null){
- setPayMethod(ComboData.payMethod[0]);
- }else{
- setPayMethod(newValue);
- }
- }}
- sx={{
- '& .MuiInputBase-root': { alignItems: 'center' },
- '& .MuiAutocomplete-endAdornment': { top: '50%', transform: 'translateY(-50%)' },
- '& .MuiOutlinedInput-root': { height: 40 }
- }}
- renderInput={(params) => (
- <TextField {...params}
- label="Payment Method"
- InputLabelProps={{ shrink: true }}
- />
- )}
- />
- </Grid>
- </Grid>
- </Grid>
-
-
- {/*last row*/}
- <Grid container maxWidth justifyContent="flex-end">
- <ThemeProvider theme={PNSPS_BUTTON_THEME}>
- <Grid item sx={{ ml: 3, mb: 3}}>
- <Button
- variant="contained"
- color="cancel"
- onClick={resetForm}
- >
- Reset
- </Button>
- </Grid>
-
- <Grid item sx={{ ml: 3, mr: 3, mb: 3 }}>
- <Button
- variant="contained"
- type="submit"
- disabled={onGridReady}
- >
- Submit
- </Button>
- </Grid>
- </ThemeProvider>
- </Grid>
- </form>
- </MainCard>
- );
- };
-
- export default SearchPublicNoticeForm;
|