|
- // material-uistatus
- 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 ComboData from "utils/ComboData";
- import * as DateUtils from "utils/DateUtils";
- import {
- isORGLoggedIn,
- } from "utils/Utils";
- import {PNSPS_BUTTON_THEME} from "../../../themes/buttonConst";
- import {ThemeProvider} from "@emotion/react";
- import {FormattedMessage, useIntl} from "react-intl";
-
- 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 intl = useIntl();
- const [type, setType] = React.useState([]);
- const [status, setStatus] = React.useState(localStorage.getItem('userData').creditor?ComboData.publicNoticeStatic_Creditor[0]:ComboData.publicNoticeStatic[0]);
-
- const [minDate, setMinDate] = React.useState(searchCriteria.dateFrom);
- const [maxDate, setMaxDate] = React.useState(searchCriteria.dateTo);
- const [fromDateValue, setFromDateValue] = React.useState("dd / mm / yyyy");
- const [toDateValue, setToDateValue] = React.useState("dd / mm / yyyy");
- const prevHasOtherRef = React.useRef(null);
- // const [selectedLabelsString, setSelectedLabelsString] = React.useState('');
-
- const { reset, register, handleSubmit, watch } = useForm({
- defaultValues: {
- appNo: searchCriteria.appNo || "",
- careOf: searchCriteria.careOf || "",
- contact: searchCriteria.contact || ""
- }
- });
- const appNo = watch("appNo");
- const careOf = watch("careOf");
- const contact = watch("contact");
- const marginBottom = 2.5;
-
- React.useEffect(() => {
- if(searchCriteria.status!=undefined){
- if(localStorage.getItem('userData').creditor){
- if(searchCriteria.status === ""){
- ComboData.publicNoticeStatic_Creditor[0]
- }else{
- setStatus(ComboData.publicNoticeStatic_Creditor.find(item => item.type === searchCriteria.status))
- }
- }else{
- if(searchCriteria.status === ""){
- ComboData.publicNoticeStatic[0]
- }else{
- setStatus(ComboData.publicNoticeStatic.find(item => item.type === searchCriteria.status))
- }
- }
- }else{
- if(localStorage.getItem('userData').creditor){
- setStatus(ComboData.publicNoticeStatic_Creditor[0])
- }else{
- setStatus(ComboData.publicNoticeStatic[0])
- }
- }
- }, [searchCriteria]);
-
- React.useEffect(() => {
- setFromDateValue(minDate);
- }, [minDate]);
-
- React.useEffect(() => {
- setToDateValue(maxDate);
- }, [maxDate]);
-
- const clearSubmitDates = () => {
- setMinDate(null);
- setMaxDate(null);
- };
-
- const restoreDefaultSubmitDates = () => {
- setMinDate(getDefaultDateFrom());
- setMaxDate(getDefaultDateTo());
- };
-
- const hasOtherCriteria = (textFields = {}) => {
- if (!isBlank(textFields.appNo)) return true;
- if (!isBlank(textFields.contact)) return true;
- if (!isBlank(textFields.careOf)) return true;
- if (status?.type && status.type !== "all" && status.type !== "") return true;
- return false;
- };
-
- React.useEffect(() => {
- const hasOther = hasOtherCriteria({ appNo, contact, careOf });
- 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;
- }, [appNo, contact, careOf, status]);
-
- const onSubmit = (data) => {
- data.status = status.type;
- let typeArray = [];
- let sentDateFrom = "";
- let sentDateTo = "";
-
- for (let i = 0; i < type.length; i++) {
- typeArray.push(type[i].label);
- }
-
- const hasOther = hasOtherCriteria({
- appNo: data.appNo,
- contact: data.contact,
- careOf: data.careOf
- });
- 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 = {
- appNo: data.appNo,
- dateFrom: sentDateFrom,
- dateTo: sentDateTo,
- contact: data.contact,
- careOf: data.careOf?data.careOf:"",
- status: (data.status === "" || data.status.includes('all')) ? "" : data.status,
- start:0,
- limit:10
- };
- if (searchCriteria?.sort && searchCriteria?.direction) {
- temp.sort = searchCriteria.sort;
- temp.direction = searchCriteria.direction;
- }
- applySearch(temp);
- };
-
- function resetForm() {
- setType([]);
- setStatus(localStorage.getItem('userData').creditor?ComboData.publicNoticeStatic_Creditor[0]:ComboData.publicNoticeStatic[0]);
- const dateFrom = getDefaultDateFrom();
- const dateTo = getDefaultDateTo();
- setMinDate(dateFrom);
- setMaxDate(dateTo);
- reset({
- appNo: "",
- careOf: "",
- contact: ""
- });
- prevHasOtherRef.current = false;
- localStorage.setItem('searchCriteria', "");
- // Reset form criteria and sorting first, then reload with backend default sort
- applySearch({
- appNo: "",
- dateFrom,
- dateTo,
- contact: "",
- careOf: "",
- status: "",
- start: 0,
- limit: 10
- });
- }
-
- return (
- <MainCard xs={12} md={12} lg={12}
- border={false}
- content={false}>
-
- <form onSubmit={handleSubmit(onSubmit)}>
- {/*row 1*/}
- <Grid item justifyContent="space-between" alignItems="center" sx={{mt:1,ml:3,mb:marginBottom}}>
- <Typography variant="pnspsFormHeader" >
- <FormattedMessage id="searchForm"/>
- </Typography>
- </Grid>
- {/*row 2*/}
- <Grid container alignItems={"center"}>
- <Grid item xs={9} s={6} md={5} lg={3} sx={{ ml: 3, mr: 3, mb: 3 }}>
- <TextField
- fullWidth
- {...register("appNo")}
- id='appNo'
- aria-label={intl.formatMessage({id: 'applicationId'})}
- label={intl.formatMessage({id: 'applicationId'})}
- defaultValue={searchCriteria.appNo}
- InputLabelProps={{
- shrink: true
- }}
- />
- </Grid>
-
- <Grid item xs={9} s={6} md={5} lg={3} sx={{ ml: 3, mr: 3, mb: 3 }}>
- <LocalizationProvider dateAdapter={AdapterDayjs} localeText={DateUtils.getPickerLocaleText(intl.locale)}>
- <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"
- aria-label={intl.formatMessage({id: 'submitDateFrom'})}
- label={intl.formatMessage({id: 'submitDateFrom'})}
- value={toDayjsOrNull(minDate)}
- maxDate={toDayjsOrNull(maxDate)}
- onChange={(newValue) => {
- setMinDate(newValue && newValue.isValid?.() ? newValue : null);
- }}
- />
- </DemoItem >
- </LocalizationProvider>
- </Grid>
-
- <Grid item xs={9} s={6} md={5} lg={3} sx={{ ml: 3, mr: 3, mb: 3 }}>
- <LocalizationProvider dateAdapter={AdapterDayjs} localeText={DateUtils.getPickerLocaleText(intl.locale)}>
- <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={intl.formatMessage({id: 'submitDateTo'})}
- value={toDayjsOrNull(maxDate)}
- minDate={toDayjsOrNull(minDate)}
- onChange={(newValue) => {
- setMaxDate(newValue && newValue.isValid?.() ? newValue : null);
- }}
- />
- </DemoItem >
- </LocalizationProvider>
- </Grid>
- {isORGLoggedIn()?
- <Grid item xs={9} s={6} md={5} lg={3} sx={{ ml: 3, mr: 3, mb: 3 }}>
- <TextField
- fullWidth
- {...register("careOf")}
- id="careOf"
- label={intl.formatMessage({id: 'careOf'})}
- aria-label={intl.formatMessage({id: 'careOf'})}
- defaultValue={searchCriteria.careOf}
- InputLabelProps={{
- shrink: true
- }}
- />
- </Grid>:null
- }
-
- {/* <Grid item xs={9} s={6} md={5} lg={3} sx={{ ml: 3, mr: 3, mb: 3 }}>
- <TextField
- fullWidth
- {...register("contact")}
- id="contact"
- label={intl.formatMessage({id: 'contactPerson'})}
- aria-label={intl.formatMessage({id: 'contactPerson'})}
- defaultValue={searchCriteria.contact}
- InputLabelProps={{
- shrink: true
- }}
- />
- </Grid> */}
- <Grid item xs={9} s={6} md={5} lg={3} sx={{ ml: 3, mr: 3, mb: 3 }}>
- <Autocomplete
- {...register("status")}
- id="status"
- size="small"
- disableClearable
- // filterOptions={(options)=>options}
- options={
- localStorage.getItem('userData').creditor ?
- ComboData.publicNoticeStatic_Creditor :
- ComboData.publicNoticeStatic
- }
- value={status}
- // inputValue={status?.labelCht}
- getOptionLabel={(option) => {
- if (option == null || option.label == null) return "";
- const s = intl.formatMessage({ id: option.label });
- return typeof s === "string" ? s : String(s ?? "");
- }}
- onChange={(event, newValue) => {
- if(newValue ==null){
- setStatus(localStorage.getItem('userData').creditor?ComboData.publicNoticeStatic_Creditor[0]:ComboData.publicNoticeStatic[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={intl.formatMessage({id: 'status'})}
- aria-label={intl.formatMessage({id: 'status'})}
- InputLabelProps={{
- shrink: true
- }}
- />
- )}
- clearText={intl.formatMessage({ id: "muiClear" })}
- closeText={intl.formatMessage({ id: "muiClose" })}
- openText={intl.formatMessage({ id: "muiOpen" })}
- noOptionsText={intl.formatMessage({ id: "muiNoOptions" })}
- // InputLabelProps={{
- // shrink: true
- // }}
- />
- </Grid>
-
- {/* <Grid item xs={9} s={6} md={5} lg={3} sx={{ ml: 3, mr: 3, mb: 3 }}>
- <Autocomplete
- multiple
- {...register("status")}
- id="status"
- size="small"
- // filterOptions={(options)=>options}
- options={
- localStorage.getItem('userData').creditor ?
- ComboData.publicNoticeStatic_Creditor :
- ComboData.publicNoticeStatic
- }
- value={status}
- // inputValue={status?.labelCht}
- getOptionLabel={(option) => {
- if (option == null || option.label == null) return "";
- const s = intl.formatMessage({ id: option.label });
- return typeof s === "string" ? s : String(s ?? "");
- }}
- onChange={(event, newValue) => {
- console.log(newValue)
- const findAllIndex = newValue.findIndex((ele) => {
- return ele.type === "all"
- })
-
- if (findAllIndex > -1) {
- setStatus([newValue[findAllIndex]]);
- setSelectedLabelsString('all')
- } else {
- const selectedLabels = newValue.map(option => option.type);
- const selectedLabelsString = `${selectedLabels.join(',')}`;
- setStatus(newValue);
- console.log(newValue)
- setSelectedLabelsString(selectedLabelsString);
- }
- console.log(selectedLabelsString)
- console.log(status)
- }}
- renderInput={(params) => (
- <TextField {...params}
- label={intl.formatMessage({id: 'status'})}
- aria-label={intl.formatMessage({id: 'status'})}
- InputLabelProps={{
- shrink: true
- }}
- />
- )}
- // InputLabelProps={{
- // shrink: true
- // }}
- />
- </Grid> */}
-
-
- </Grid>
-
-
- {/*last row*/}
- <Grid container maxWidth justifyContent="flex-end">
- <ThemeProvider theme={PNSPS_BUTTON_THEME}>
- <Grid item sx={{ ml: 3, mr: 3 }}>
- <Button
- variant="contained"
- color="cancel"
- onClick={resetForm}
- aria-label={intl.formatMessage({id: 'reset'})}
- >
- <Typography variant="pnspsButtonText">
- <FormattedMessage id="reset"/>
- </Typography>
- </Button>
- </Grid>
-
- <Grid item>
- <Button
- variant="contained"
- type="submit"
- disabled={onGridReady}
- aria-label={intl.formatMessage({id: 'search'})}
- >
- <Typography variant="pnspsButtonText">
- <FormattedMessage id="search"/>
- </Typography>
- </Button>
- </Grid>
- </ThemeProvider>
- </Grid>
- </form>
- </MainCard>
- );
- };
-
- export default SearchPublicNoticeForm;
|