@material-ui/pickers#KeyboardDatePicker JavaScript Examples
The following examples show how to use
@material-ui/pickers#KeyboardDatePicker.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: InlineDatePicker.js From medha-STPC with GNU Affero General Public License v3.0 | 6 votes |
function InlineDatePicker(props) {
return (
<MuiThemeProvider theme={customTheme}>
<MuiPickersUtilsProvider utils={DateFnsUtils}>
<KeyboardDatePicker
autoOk
// disableToolbar
variant="inline"
inputVariant="outlined"
format="dd/MM/yyyy"
id={props.id}
color={props.color}
label={props.label}
value={props.value}
error={props.error}
placeholder={props.placeholder}
helperText={props.helperText}
onChange={props.onChange}
KeyboardButtonProps={{
"aria-label": "change date",
}}
/>
</MuiPickersUtilsProvider>
</MuiThemeProvider>
);
}
Example #2
Source File: KeyDatePickerContainer.js From resilience-app with GNU General Public License v3.0 | 6 votes |
KeyDatePickerContainer = ({ id, label, margin, onChange, value, ...rest }) => {
const [isOpen, setIsOpen] = useState(false);
return (
<KeyboardDatePicker
variant="inline"
margin={margin}
id={id}
value={value}
label={label}
format="MM/dd/yyyy"
disablePast={true}
onChange={(newDate) => {
onChange(newDate);
setIsOpen(false);
}}
KeyboardButtonProps={{
onFocus: (e) => {
setIsOpen(true);
},
"aria-label": "change date",
}}
PopoverProps={{
disableRestoreFocus: true,
onClose: () => {
setIsOpen(false);
},
}}
InputProps={{
onFocus: () => {
setIsOpen(true);
},
}}
open={isOpen}
{...rest}
/>
);
}
Example #3
Source File: index.js From hook-form-mui with MIT License | 6 votes |
MuiDatePicker = (props) => {
const { name, required, errorobj } = props;
let isError = false;
let errorMessage = "";
if (errorobj && errorobj.hasOwnProperty(name)) {
isError = true;
errorMessage = errorobj[name].message;
}
return (
<React.Fragment>
<KeyboardDatePicker
format="DD-MM-YYYY"
fullWidth={true}
InputLabelProps={{
className: required ? "required-label" : "",
required: required || false,
}}
error={isError}
helperText={errorMessage}
{...props}
/>
</React.Fragment>
);
}
Example #4
Source File: CreateNewAuction.js From BidKaroNa with MIT License | 5 votes |
render() {
return (
<ThemeProvider theme = {theme}>
<div>
<Navbar
history = {this.props.history}/>
<br/>
<div style = {{"textAlign" : "center",'color' : '#006064'}}>
<form className="form">
<h3>Create New Auction</h3>
<TextField
variant="outlined"
label = "Auction Title"
type = "text"
name = "title"
style = {{"width" : "60%", "margin":"10px"}}
placeholder = "Enter Auction Title"
value = {this.state.title}
onChange = {this.handleInputChange}
required
/>
<br/>
<TextField
variant="outlined"
label = "Asset Address"
type = "text"
name = "asset_addr"
style = {{"width" : "60%", "margin":"10px"}}
placeholder = "Enter Address of the asset you wish to sell"
value = {this.state.asset_addr}
onChange = {this.handleInputChange}
required
/>
<br/>
<TextField
variant="outlined"
label = "Reserved Price"
type = "number"
name = "reserved_price"
style = {{"width" : "60%", "margin":"10px"}}
placeholder = "Enter Reserved Price in Ethers"
value = {this.state.reserved_price}
onChange = {this.handleInputChange}
required
/>
<br/>
<MuiPickersUtilsProvider utils={DateFnsUtils}>
<KeyboardDatePicker
clearable
value={this.state.selectedDate}
label = "Select deadline for the auction"
onChange={date => this.handleDateChange(date)}
minDate={new Date()}
format="dd/MM/yyyy"
style = {{"width" : "40%", "margin":"10px"}}
/>
</MuiPickersUtilsProvider>
<br/>
<br/>
<Button variant = "contained" style = {{'color' : '#FFFFFF', 'background' : '#006064'}} onClick = {this.createAuction}>Create Auction</Button>
<br/>
<br/>
</form>
</div>
</div>
</ThemeProvider>
);
}
Example #5
Source File: ReminderAction.js From react-sample-projects with MIT License | 5 votes |
ReminderAction = ({ onAddReminder }) => {
const [open, setOpen] = useState(false);
const [selectedDate, setSelectedDate] = useState(new Date());
const handleDateChange = (date) => {
setSelectedDate(date);
};
const toggleReminder = () => {
setOpen(() => !open);
};
const handleSave = () => {
onAddReminder(selectedDate);
toggleReminder();
};
return (
<Box>
<IconButton aria-label="Remind" onClick={toggleReminder}>
<AlarmIcon />
</IconButton>
<Dialog
open={open}
onClose={toggleReminder}
aria-labelledby="form-dialog-title"
>
<DialogTitle id="form-dialog-title">Remind</DialogTitle>
<DialogContent>
<DialogContentText>
<MuiPickersUtilsProvider utils={DateFnsUtils}>
<KeyboardDatePicker
margin="normal"
label="Date"
format="MM/dd/yyyy"
value={selectedDate}
onChange={handleDateChange}
KeyboardButtonProps={{
'aria-label': 'change date',
}}
/>
<KeyboardTimePicker
margin="normal"
label="Time"
value={selectedDate}
onChange={handleDateChange}
KeyboardButtonProps={{
'aria-label': 'change time',
}}
/>
</MuiPickersUtilsProvider>
</DialogContentText>
</DialogContent>
<DialogActions>
<Button onClick={toggleReminder} color="primary">
Cancel
</Button>
<Button onClick={handleSave} color="primary">
Save
</Button>
</DialogActions>
</Dialog>
</Box>
);
}
Example #6
Source File: CoinChartsConvert.js From crypto-red.github.io with MIT License | 5 votes |
render() {
const { classes, selected_currency, _selected_date, coin_data, coin_id } = this.state;
const { _cryptocurrency_input_value, _fiat_input_value, _min_date } = this.state;
const date_format = this._get_date_format();
const market_convert_card = coin_data !== null ?
<Fade in>
<Card>
<CardHeader title={t( "components.coin_charts_convert.title")} />
<CardContent>
<TextField className={classes.convertInput}
id="cryptocurrency-input"
type="number"
label={coin_data.symbol.toUpperCase()}
value={_cryptocurrency_input_value}
onChange={this._handle_cryptocurrency_input_value_change}
/>
<TextField
className={classes.convertInput}
id="fiat-input"
type="number"
label={selected_currency}
value={_fiat_input_value}
onChange={this._handle_fiat_input_value_change}
/>
<MuiPickersUtilsProvider utils={DateFnsUtils} locale={DATE_FNS_LOCALE_MAP[document.documentElement.lang] || DATE_FNS_LOCALE_MAP["en"]}>
<KeyboardDatePicker
cancelLabel={t("words.cancel")}
okLabel={t("words.ok")}
minDate={_min_date}
maxDate={Date.now()}
disableFuture={true}
invalidDateMessage={t("sentences.invalid date message")}
className={classes.noTopMargin}
margin="normal"
id="date-picker-dialog"
label={t( "sentences.pick a date")}
format={date_format}
value={_selected_date}
onChange={this._handle_selected_date_change}
/>
</MuiPickersUtilsProvider>
<Button className={classes.buyButton}
onClick={(event) => {this._open_buy()}}
fullWidth
variant="contained"
color="primary">
{t( "components.coin_charts_convert.buy_x", {coin_name: coin_data.name})}
</Button>
</CardContent>
</Card>
</Fade>: null;
return (
<div className={classes.fullHeight}>{market_convert_card}</div>
);
}
Example #7
Source File: SchedulePost.js From social-media-strategy-fe with MIT License | 5 votes |
SchedulePost = ({ postId, scheduledTime }) => {
const [schedule, setSchedule] = useState(scheduledTime || new Date());
const [invalidDate, setInvalidDate] = useState(false);
const [modalOpen, setModalOpen] = useState(false);
const dispatch = useDispatch();
const handleChange = (date, e) => {
console.log(e);
setInvalidDate(false);
setSchedule(date);
};
const handleSchedulePost = async () => {
if (schedule > Date.now()) {
await dispatch(scheduleTweet(postId, schedule));
} else {
setInvalidDate(true);
}
};
return (
<>
<Button onClick={() => setModalOpen(true)} color="primary">
{scheduledTime ? "Reschedule" : "Schedule"}
</Button>
<Modal
open={modalOpen}
handleClose={() => setModalOpen(false)}
title="Schedule Post"
handleConfirmation={handleSchedulePost}
>
<MuiPickersUtilsProvider utils={DateFnsUtils}>
<Grid container direction="column" justify="space-around">
<KeyboardDatePicker
minDate={new Date()}
margin="normal"
id="date-picker-dialog"
label="Date"
format="MM/dd/yyyy"
value={schedule}
onChange={handleChange}
KeyboardButtonProps={{
"aria-label": "change date",
}}
/>
<KeyboardTimePicker
minDate={new Date()}
margin="normal"
id="time-picker"
label="Time"
value={schedule}
onChange={handleChange}
KeyboardButtonProps={{
"aria-label": "change time",
}}
/>
{invalidDate && (
<Typography variant="caption" color="error">
Invalid time
</Typography>
)}
</Grid>
</MuiPickersUtilsProvider>
</Modal>
</>
);
}
Example #8
Source File: TimeContainer.js From git-brunching with GNU General Public License v3.0 | 4 votes |
TimeContainer = (props) => {
const history = useHistory();
const {
oldSeats, oldDate, oldTime, onConfirmClick, getHours, restaurantHours, getAvailable,
availableTimes, onSeatChange, onDateChange, isLoading, mainHistory, tableCapacity, getCapacity,
} = props;
const [seats, changeSeats] = useState(oldSeats);
const [selectedDate, setSelectedDate] = useState(oldDate);
const [selectedTime, setSelectedTime] = useState(oldTime);
const [overCapacity, setOverCapacity] = useState(false);
const [capacityMsg, setCapacityMsg] = useState("");
useEffect(getHours, []);
useEffect(getCapacity, []);
const day = getDayForDate(new Date(selectedDate));
const month = new Date(selectedDate).getMonth();
const dates = new Date(selectedDate).getDate();
const times = restaurantHours.find((x) => x.DayOfWeek === day);
const today = new Date();
const todaysMonth = today.getMonth();
const todaysDate = today.getDate();
const todaystime = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
const todaystimeInt = Number.parseInt(todaystime.substring(0, 2), 10);
// There will be no times when the restaurant is closed
const noTimes = times == null;
const hideTimes = seats.length === 0 || selectedDate == null;
const dateError = selectedDate == null;
const maxGuest = tableCapacity.maximum;
const minGuest = tableCapacity.minimum;
let openTime = "";
let closeTime = "";
if (!noTimes) {
openTime = Number.parseInt(times.OpenTime.substring(0, 2), 10);
closeTime = Number.parseInt(times.CloseTime.substring(0, 2), 10);
}
const handleTimeConfirmation = () => {
changePath("/details", history);
onConfirmClick(selectedTime);
};
const handleTime = (value) => {
setSelectedTime(value);
};
const handleGuestChange = (e) => {
const currentSeats = (e.target.validity.valid) ? e.target.value : seats;
changeSeats(currentSeats);
};
const handleCapacity = (seat) => {
if (seat > maxGuest || seat < minGuest) {
if (seat < minGuest) setCapacityMsg(messages.time.minGuestMsg + minGuest);
else setCapacityMsg(messages.time.maxGuestMsg + maxGuest);
setOverCapacity(true);
} else {
getAvailable();
setOverCapacity(false);
}
};
return (
<div className={style.stylingParent}>
<div className={style.bookingDetailsContainer}>
<div className={style.bookingDetail}>
<TextField
type="text"
inputProps={{ pattern: "[0-9]*" }}
className={style.textField}
label="Number of Guests"
variant="outlined"
value={seats}
onChange={(e) => {
handleGuestChange(e);
onSeatChange(e.target.value)
handleCapacity(e.target.value)
getAvailable();
}}
/>
</div>
<div className={style.bookingDetail}>
<MuiPickersUtilsProvider utils={DateFnsUtils}>
<KeyboardDatePicker
disableToolbar
style={{ width: "100%" }}
inputVariant="outlined"
format="dd-MM-yyyy"
margin="normal"
label="Select a Date"
value={selectedDate}
error={dateError}
disablePast = "true"
onChange={(e) => {
try {
const formattedDate = format(e, "yyyy-MM-dd");
setSelectedDate(formattedDate);
onDateChange(formattedDate);
getAvailable();
} catch (RangeError) {
setSelectedDate(null);
getAvailable();
}
}}
KeyboardButtonProps={{
"aria-label": "change date",
}}
/>
</MuiPickersUtilsProvider>
</div>
{hideTimes ? null
: (
<div className={classNames(style.buttonContainer, isLoading ? style.loading : "")}>
{isLoading ? <div className={style.loading}><CircularProgress /></div> : (
<>
{overCapacity ? <div className = {style.capacityMsg}>{capacityMsg}</div> :
noTimes || availableTimes.availableHours == null ? <div>Closed</div>
: generateAllTimes(openTime, closeTime).map((time) => {
const available = availableTimes.availableHours;
const hour = Number.parseInt(time.time.substring(0, 2), 10);
return (
<Button
key={`time_button_${time.time}`}
variant="contained"
disabled={(available.indexOf(hour) === -1) || (hour <= todaystimeInt && month === todaysMonth && dates === todaysDate) }
value={time}
color={time.time === selectedTime ? "secondary" : "primary"}
onClick={() => handleTime(time.time)}
>
{time.time}
</Button>
);
})}
</>
)}
</div>
)}
<div className={style.submitButtonContainer}>
<Button
className={style.submitButton}
variant="contained"
color="primary"
onClick={() => { if (window.confirm('Are you sure you want to leave before booking? Progress will not be saved'))changePath("/", mainHistory)}}
>
Cancel
</Button>
<Button
className={style.submitButton}
variant="contained"
color="primary"
onClick={handleTimeConfirmation}
disabled={seats.length === 0 || selectedTime.length === 0 || overCapacity === true}
>
{timeMessages.buttonNextText}
</Button>
</div>
</div>
</div>
);
}
Example #9
Source File: localdomain.js From FLINT.JSON_Interface with Mozilla Public License 2.0 | 4 votes |
export default function LocalDomain(props){
ipcRenderer.on('title-reply', (event, arg) => {
console.log(arg+" "+props.directory);
if(arg==props.directory)
save();
})
const classes = useStyles();
console.log(props.json.LocalDomain);
const [Libraries, setLibraries] = React.useState(
// [{
// libraryName : "moja.modules.cbm",
// libraryType: "external"
// },
// {
// libraryName : "",
// libraryType: ""
// }
// ]
getLibraries()
);
function getLibraries(){
const tempL=[];
for (const [key, value] of Object.entries(props.json.Libraries)) {
tempL.push(
{
libraryName: key,
libraryType: value
}
)
}
return tempL;
}
const [open, setOpen] = React.useState(false);
const handleClickSnack = () => {
setOpen(true);
};
const handleClose = (event, reason) => {
if (reason === 'clickaway') {
return;
}
setOpen(false);
};
const [LocalDomain, setLocalDomain] = React.useState(
// {
// start_date : new Date('2014-08-18T21:11:54'),
// end_date : new Date('2014-08-19T21:11:54'),
// landUnitBuildSuccess: "landUnitBuildSuccess",
// simulateLandUnit: "simulateLandUnit",
// sequencer_library: "moja.modules.cbm",
// sequencer: "CBMSequencer",
// timing: "annual",
// type: "spatial_tiled",
// landscape: {
// "provider": "RasterTiled",
// "num_threads": 4,
// "tiles": [],
// "x_pixels": 1000,
// "y_pixels": 1000,
// "tile_size_x": 1.0,
// "tile_size_y": 1.0
// }
props.json.LocalDomain
);
const [tempLibrary, setTempLibrary] = React.useState({});
useEffect(()=>{console.log(Libraries);
const temp={};
Libraries.map(inp => temp[inp.libraryName]=inp.libraryType);
const temp1={};
temp1["Libraries"]=temp;
temp1["LocalDomain"]=LocalDomain;
console.log(JSON.stringify(temp1));
setTempLibrary(temp1);
},[Libraries, LocalDomain]);
function handleChangeLibrary(index, libraryName, libraryType)
{
const tempLibraries = [...Libraries];
tempLibraries[index].libraryName = libraryName!=="" ? libraryName : tempLibraries[index].libraryName ;
tempLibraries[index].libraryType = libraryType!=="" ? libraryType : tempLibraries[index].libraryType ;
setLibraries(tempLibraries);
}
function addLibrary()
{
const tempLibraries = [...Libraries];
tempLibraries.push({
libraryName : "",
libraryType: ""
});
setLibraries(tempLibraries);
}
function deleteLibrary(index)
{
const tempLibraries = [...Libraries];
tempLibraries.splice(index,1);
setLibraries(tempLibraries);
}
function handleChangeLocalDomain(key, value)
{
const tempLibraries = {...LocalDomain};
tempLibraries[key] = value;
setLocalDomain(tempLibraries);
console.log(LocalDomain);
}
const save = ()=>
{
console.log("save from localdomain");
fs.writeFileSync(props.directory, JSON.stringify(tempLibrary, null, 2),{encoding: "utf-8"});
handleClickSnack();
}
return(
<div id="container">
<div id="jsonEditor">
<h1>Libraries:</h1>
<Paper elevation={5} className={classes.paper}>
{
Libraries.map((inputField, index) => (
<div>
<FormControl className={classes.formControl}>
<InputLabel id="demo-simple-select-label">Library Name</InputLabel>
<Select
labelId="demo-simple-select-label"
id="demo-simple-select"
className={classes.libraryName}
value={(inputField.libraryName=="" || inputField.libraryName=="moja.modules.cbm" || inputField.libraryName=="moja.modules.zipper" || inputField.libraryName=="moja.modules.gdal")?inputField.libraryName : "other"}
onChange={event => {if(event.target.value=="other"){handleChangeLibrary(index, event.target.value, "");document.getElementById("other"+index).style.display="block";document.getElementById("other-val"+index).value=""} else {document.getElementById("other"+index).style.display="none";handleChangeLibrary(index, event.target.value, "")}}}
>
<MenuItem value={"moja.modules.cbm"}>moja.modules.cbm</MenuItem>
<MenuItem value={"moja.modules.zipper"}>moja.modules.zipper</MenuItem>
<MenuItem value={"moja.modules.gdal"}>moja.modules.gdal</MenuItem>
<MenuItem value={"other"}>other</MenuItem>
</Select>
</FormControl>
<FormControl className={classes.formControl}>
<div id={"other"+index} style={{display: "none"}}><TextField id={"other-val"+index} label="library name" onChange={event => handleChangeLibrary(index, event.target.value, "")} /></div>
</FormControl>
<FormControl className={classes.formControl}>
<InputLabel id="demo-simple-select-label">Library Type</InputLabel>
<Select
labelId="demo-simple-select-label"
id="demo-simple-select"
className={classes.libraryType}
value={inputField.libraryType}
onChange={event => handleChangeLibrary(index, "", event.target.value)}
>
<MenuItem value={"internal"}>internal</MenuItem>
<MenuItem value={"external"}>external</MenuItem>
</Select>
</FormControl>
<IconButton color="primary" aria-label="add library" style={{marginTop: "10px"}} onClick={()=>{document.getElementById("other"+index).style.display="none";deleteLibrary(index)}}>
<CancelIcon />
</IconButton>
</div>
))}
<IconButton color="primary" aria-label="add library" style={{marginLeft: "16vw"}} onClick={()=>addLibrary()}>
<AddCircleIcon />
</IconButton>
</Paper>
<h1>LocalDomain:</h1>
<Paper elevation={5} className={classes.paper}>
<div>
<FormControl className={classes.formControl}>
<MuiPickersUtilsProvider utils={DateFnsUtils}>
<KeyboardDatePicker
margin="normal"
id="start_date"
label="start_date(yy/mm/dd)"
format="yyyy/MM/dd"
value={LocalDomain.start_date}
onChange={date => handleChangeLocalDomain("start_date",date)}
KeyboardButtonProps={{
'aria-label': 'change time',
}}
/>
</MuiPickersUtilsProvider>
</FormControl>
{/* <br /> */}
<FormControl className={classes.formControl}>
<MuiPickersUtilsProvider utils={DateFnsUtils}>
<KeyboardDatePicker
margin="normal"
id="end_date"
label="end_date(yy/mm/dd)"
format="yyyy/MM/dd"
value={LocalDomain.end_date}
onChange={date => handleChangeLocalDomain("end_date",date)}
KeyboardButtonProps={{
'aria-label': 'change time',
}}
/>
</MuiPickersUtilsProvider>
</FormControl>
<br />
<FormControl className={classes.formControl}>
<TextField id="landUnitBuildSuccess" label="landUnitBuildSuccess" variant="filled" defaultValue={LocalDomain.landUnitBuildSuccess} onChange={event => handleChangeLocalDomain("landUnitBuildSuccess",event.target.value)} />
</FormControl>
<FormControl className={classes.formControl}>
<TextField id="simulateLandUnit" label="simulateLandUnit" variant="filled" defaultValue={LocalDomain.simulateLandUnit} onChange={event => handleChangeLocalDomain("simulateLandUnit",event.target.value)} />
</FormControl>
<FormControl className={classes.formControl}>
<TextField id="filled-basic" label="sequencer_library" variant="filled" defaultValue={LocalDomain.sequencer_library} onChange={event => handleChangeLocalDomain("sequencer_library",event.target.value)} />
</FormControl>
<FormControl className={classes.formControl}>
<TextField id="filled-basic" label="sequencer" variant="filled" defaultValue={LocalDomain.sequencer} onChange={event => handleChangeLocalDomain("sequencer",event.target.value)}/>
</FormControl>
<FormControl className={classes.formControl}>
<InputLabel id="demo-simple-select-label">timing</InputLabel>
<Select
labelId="demo-simple-select-label"
id="timing"
className={classes.libraryName}
value={LocalDomain.timing}
onChange={event => handleChangeLocalDomain("timing",event.target.value)}
>
<MenuItem value={"annual"}>annual</MenuItem>
<MenuItem value={"monthly"}>monthly</MenuItem>
<MenuItem value={"daily"}>daily</MenuItem>
</Select>
</FormControl>
<FormControl className={classes.formControl}>
{/* <TextField id="filled-basic" label="type" variant="filled" defaultValue={LocalDomain.type} /> */}
<InputLabel id="demo-simple-select-label">type</InputLabel>
<Select
labelId="demo"
id="type"
className={classes.libraryName}
value={LocalDomain.type}
onChange={event => handleChangeLocalDomain("type",event.target.value)}
style = {{width: "300px"}}
>
<MenuItem value={"spatial_tiled"}>spatial_tiled</MenuItem>
<MenuItem value={"spatially_referenced_sql"}>spatially_referenced_sql</MenuItem>
<MenuItem value={"spatially_referenced_nosql"}>spatially_referenced_nosql</MenuItem>
<MenuItem value={"threaded_spatially_referenced_nosql"}>threaded_spatially_referenced_nosql</MenuItem>
</Select>
</FormControl>
</div>
</Paper>
</div>
<div id="jsonViewer"><pre>
{JSON.stringify(tempLibrary, null, 2)}
</pre></div>
<Snackbar open={open} autoHideDuration={2000} onClose={handleClose}>
<Alert onClose={handleClose} severity="success">
{props.directory+" Saved Successfully!"}
</Alert>
</Snackbar>
</div>
);
}
Example #10
Source File: DashboardPage.jsx From frontend with MIT License | 4 votes |
DashboardPage = () => {
const [selectedFacilityId, setSelectedFacilityId] = useState('');
const [selectedContactId, setSelectedContactId] = useState('');
const [selectedCategory, setSelectedCategory] = useState('');
const [modalOpen, setModalOpen] = useState(false);
const [resourceEditId, setResourceEditId] = useState(0);
const [requests, setRequests] = useState([]);
const [facilities, setFacilites] = useState([]);
const [contacts, setContacts] = useState([]);
const [categories, setCategories] = useState([]);
const [amount, setAmount] = useState(0);
const selectedFacility = facilities.find((x) => x.name === selectedFacilityId);
const selectedContact = contacts.find((x) => x.name === selectedContactId);
useEffect(() => {
if (modalOpen) {
setSelectedFacilityId('');
setSelectedContactId('');
setSelectedCategory('');
setAmount(0);
} else if (resourceEditId) {
setTimeout(() => setResourceEditId(0), 50);
}
}, [modalOpen]);
useEffect(() => {
if (resourceEditId) {
const {
name,
quantity,
beneficiary,
contactPerson,
} = requests.find(({ id }) => id === resourceEditId);
setSelectedFacilityId(beneficiary.name);
setSelectedContactId(contactPerson.name);
setSelectedCategory(name);
setAmount(quantity);
}
}, [resourceEditId]);
const getData = () => {
fetch(`${apiUrl}/resources`)
.then((x) => x.json())
.then((x) => x.list.filter((a) => a.name))
.then((x) => {
setRequests(x);
const facilitiesX = x
.reduce((res, next) => res.set(next.beneficiary.name, next.beneficiary), new Map());
setFacilites([...facilitiesX.values()]);
const contactsX = x
.reduce((res, next) => res.set(next.contactPerson.name, next.contactPerson), new Map());
setContacts([...contactsX.values()]);
const categoriesX = x
.reduce((res, next) => res.set(next.name, next.name), new Map());
setCategories([...categoriesX.values()]);
});
};
const init = useRef(false);
useEffect(() => {
if (!init.current) {
getData();
init.current = true;
}
}, [init]);
const submit = (modalClose) => {
const req = {
beneficiary: selectedFacility,
contactPerson: selectedContact,
status: 'OPEN',
items: [{
name: selectedCategory,
quantity: parseInt(amount, 10),
}],
};
/* if (resourceEditId) {
fetch(`${apiUrl}/resources/${resourceEditId}`, {
method: 'PUT',
body: JSON.stringify(req),
}).then((response) => {
setRequests(requests.reduce((acc, rowData) => {
if (rowData.id === resourceEditId) {
acc.push(response);
} else {
acc.push(rowData);
}
return acc;
}), []);
}).then(() => modalClose())
.catch((e) => console.log(e));
} else {
fetch(`${apiUrl}/resources`, {
method: 'POST',
body: JSON.stringify(req),
}).then((x) => setRequests(x.list.filter((a) => a.name)))
.then(() => modalClose())
.catch((e) => console.log(e));
} */
// temporarily until the server is implemented
modalClose();
};
return (
<>
<Box mb={4} display="flex" justifyContent="space-between">
<Typography variant="h4">Dashboard</Typography>
<Button color="primary" variant="contained" onClick={() => setModalOpen(true)}>
<Icon>add</Icon>
{' '}
Create Request
</Button>
</Box>
{/* <Box mb={2}>
<Paper elevation={2}>
<Box p={2}>
<Typography variant="h5" gutterBottom>Filter</Typography>
<Grid container spacing={2}>
<Grid item xs>
<FormControl>
<InputLabel>Facility</InputLabel>
<Input />
</FormControl>
</Grid>
<Grid item xs>
<FormControl>
<InputLabel>Region</InputLabel>
<Input />
</FormControl>
</Grid>
<Grid item xs>
<FormControl>
<MuiPickersUtilsProvider utils={DateFnsUtils}>
<KeyboardDatePicker label="Deadline" onChange={() => {}} />
</MuiPickersUtilsProvider>
</FormControl>
</Grid>
</Grid>
</Box>
</Paper>
</Box> */}
<Paper elevation={2}>
<Table>
<TableHead>
<TableRow>
{columns.map((c) => <TableCell key={c.label}>{c.label}</TableCell>)}
</TableRow>
</TableHead>
<TableBody>
{requests.map((x) => (
<TableRow key={x.id}>
<TableCell>{x.beneficiary.name}</TableCell>
<TableCell>{x.name}</TableCell>
<TableCell>{x.quantity}</TableCell>
<TableCell>{x.deadline}</TableCell>
<TableCell>
{x.contactPerson ? x.contactPerson.name : (
<Button color="secondary" variant="contained">
Assign
</Button>
)}
</TableCell>
<TableCell align="right">
<IconButton
variant="icon"
onClick={() => {
setResourceEditId(x.id);
setModalOpen(true);
}}
>
<Icon>edit</Icon>
</IconButton>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</Paper>
<Dialog open={modalOpen} fullWidth>
<DialogTitle>
{resourceEditId ? 'Update' : 'New'}
{' '}
Request
</DialogTitle>
<DialogContent>
<Box mb={2}>
<FormControl fullWidth>
<InputLabel>Facility</InputLabel>
<Select
value={selectedFacilityId}
fullWidth
onChange={({ target: { value } }) => setSelectedFacilityId(value)}
>
{facilities.map((x) => <MenuItem key={x.name} value={x.name}>{x.name}</MenuItem>)}
</Select>
</FormControl>
{
selectedFacilityId
? (
<>
<Typography color="textSecondary" variant="subtitle1">{selectedFacility.name}</Typography>
<Typography color="textSecondary" variant="subtitle2">{selectedFacility.address}</Typography>
</>
) : null
}
</Box>
<Box mb={2}>
<FormControl fullWidth>
<InputLabel>Contact person</InputLabel>
<Select
value={selectedContactId}
fullWidth
onChange={({ target: { value } }) => setSelectedContactId(value)}
>
{contacts.map((x) => <MenuItem key={x.name} value={x.name}>{x.name}</MenuItem>)}
</Select>
</FormControl>
{
selectedContactId
? (
<>
<Typography color="textSecondary" variant="subtitle1">{selectedContact.name}</Typography>
<Typography color="textSecondary" variant="subtitle2">{selectedContact.phone}</Typography>
</>
) : null
}
</Box>
<Typography variant="h6">Request</Typography>
<Box mb={2}>
<FormControl fullWidth>
<InputLabel>Category</InputLabel>
<Select
value={selectedCategory}
fullWidth
onChange={({ target: { value } }) => setSelectedCategory(value)}
>
{categories.map((x) => <MenuItem key={x} value={x}>{x}</MenuItem>)}
</Select>
</FormControl>
</Box>
<Box mb={2}>
<FormControl fullWidth>
<InputLabel>Amount</InputLabel>
<Input value={amount} onChange={(({ target: { value } }) => setAmount(value))} />
</FormControl>
</Box>
<Box mb={2}>
<FormControl fullWidth>
<MuiPickersUtilsProvider utils={DateFnsUtils}>
<KeyboardDatePicker fullWidth label="Deadline" onChange={() => {}} />
</MuiPickersUtilsProvider>
</FormControl>
</Box>
</DialogContent>
<DialogActions>
<Button
color="secondary"
onClick={() => {
setModalOpen(false);
}}
>
Cancel
</Button>
<Button
variant="contained"
color="primary"
onClick={() => {
submit(() => setModalOpen(false));
}}
>
{resourceEditId ? 'Update' : 'Create'}
</Button>
</DialogActions>
</Dialog>
</>
);
}
Example #11
Source File: Dashboard.js From Smart-Vehicle-Fleet-Manager with MIT License | 4 votes |
function Dashboard() {
// Layout and Menu
const { Content, Sider } = Layout;
const { SubMenu } = Menu;
// report an issue preventDefault
const preventDefault = (event) => {
event.preventDefault();
window.location.href =
"https://github.com/abhishekpatel946/Smart-Vehicle-Fleet-Manager/issues/new/choose";
};
// snakbar state
const [vehicleAddSuccess, setvehicleAddSuccess] = React.useState(false);
const [vehicleAddError, setvehicleAddError] = React.useState(false);
const [maintainanceAddSuccess, setmaintainanceAddSuccess] = React.useState(
false
);
const [maintainanceAddError, setmaintainanceAddError] = React.useState(false);
const handleClose = (event, reason) => {
if (reason === "clickaway") {
return;
}
setvehicleAddSuccess(false);
setvehicleAddError(false);
setmaintainanceAddSuccess(false);
setmaintainanceAddError(false);
};
// vehicleId & vehicleName for addVehicle
const [vehicleNAME, setVehicleNAME] = useState("");
const [vehicleID, setVehicleID] = useState("");
// vehicleName, dateTime & cost for maintenace
const [vehicleRegNumber, setVehicleRegNumber] = useState("");
const [date, setDate] = useState(moment().toString());
const [cost, setCost] = useState("");
// set date
const onDateChange = (val) => {
setDate(val);
};
const [collapseState, setCollapseState] = useState(false);
const onCollapse = (collapsed) => {
setCollapseState({ collapsed });
};
// form onSubmit handler
const submitHandler = (event) => {
event.preventDefault();
event.target.className += " was-validated";
};
// fetch vehicle model & regid
// const [vehicleInfo, setVehicleInfo] = useState([]);
// let vehicleModel = "";
// let vehicleModelId = "";
// db.collection("data")
// .doc("MP10ME7969")
// .get()
// .then((snapshot) => {
// const currentInfo = [];
// snapshot.forEach((doc) => {
// currentInfo.push(doc.data());
// });
// setVehicleInfo(currentInfo);
// });
// vehicleInfo.forEach((data) => {
// vehicleModel = data.vehicleId;
// vehicleModelId = data.vehicleName;
// });
// fetch moduleState
const [moduleState, setModuleState] = useState([]);
let liveState = false;
db.collection("data")
.doc("MP10ME7969")
.collection("module_state")
.onSnapshot((docs) => {
const currentState = [];
docs.forEach((doc) => {
currentState.push(doc.data());
});
setModuleState(currentState);
});
moduleState.forEach((data) => {
liveState = data.state;
});
// form vehicleRegister submitHandler
const vehicleRegister = (event) => {
if (vehicleID && vehicleNAME) {
// check if the doc are already available in the DB... then just give the warning to the user!
// create a doc in DB with vehicleID and set it fields
db.collection("data").doc(vehicleID).set({
vehicleId: vehicleID,
vehicleName: vehicleNAME,
});
// create a dummy collection for newly created vehicleID
db.collection("data").doc(vehicleID).collection("fuel").doc().set({
id: "0",
amount: "0",
timestamp: "0",
});
db.collection("data").doc(vehicleID).collection("fuel_refill").doc().set({
id: "0",
amount: "0",
timestamp: "0",
});
db.collection("data")
.doc(vehicleID)
.collection("maintainance")
.doc()
.set({
id: "0",
amount: "0",
timestamp: "0",
});
db.collection("data").doc(vehicleID).collection("overspeed").doc().set({
id: "0",
speed: "0",
timestamp: "0",
});
db.collection("data").doc(vehicleID).collection("speed").doc().set({
id: "0",
speed: "0",
timestamp: "0",
});
db.collection("data")
.doc(vehicleID)
.collection("accident_alert")
.doc()
.set({
id: "0",
accident: "0",
geolocation_lat: "0",
geolocation_long: "0",
timestamp: "0",
});
db.collection("data")
.doc(vehicleID)
.collection("fuel_theft_alert")
.doc()
.set({
id: "0",
fuelTheft: "0",
geolocation_lat: "0",
geolocation_long: "0",
timestamp: "0",
});
db.collection("data")
.doc(vehicleID)
.collection("module_state")
.doc()
.set({
state: "0",
});
// success mgs for the all are right
setvehicleAddError(false);
setmaintainanceAddSuccess(false);
setmaintainanceAddError(false);
setvehicleAddSuccess(true);
// set it to defualt to state
setVehicleNAME("");
setVehicleID("");
} else {
// alert("Both the fields are mandatory!!!");
setvehicleAddSuccess(false);
setmaintainanceAddSuccess(false);
setmaintainanceAddError(false);
setvehicleAddError(true);
}
};
// from vehicleMaintenace submitHandler
const addCost = (event) => {
// store maintainance-cost into database
db.collection("data")
.doc(vehicleRegNumber)
.collection("maintainance")
.add({
id: vehicleRegNumber,
cose: cost,
timestamp: date,
})
.then(function () {
// success mgs for the all are right
setvehicleAddSuccess(false);
setvehicleAddError(false);
setmaintainanceAddError(false);
setmaintainanceAddSuccess(true);
})
.catch(function (error) {
setvehicleAddSuccess(false);
setvehicleAddError(false);
setmaintainanceAddSuccess(false);
setmaintainanceAddError(true);
});
};
// render() {
return (
<Layout id="header">
{/* Header Section */}
<HeaderLayout className="header" />
<Layout style={{ minHeight: "100vh" }}>
<Sider
collapsible
collapsed={collapseState.collapsed}
onCollapse={onCollapse}
>
<div className="logo" />
<Menu
theme="dark"
defaultSelectedKeys={["stats"]}
defaultOpenKeys={["track"]}
mode="inline"
>
<Menu.Item key="stats" icon={<PieChartOutlined />}>
Stats
</Menu.Item>
<SubMenu key="track" icon={<DesktopOutlined />} title="Track">
<Menu.Item key="speed">
<Link href="#speedSection">Speed</Link>
</Menu.Item>
<Menu.Item key="fuel">
<Link href="#fuelSection">Fuel</Link>
</Menu.Item>
<Menu.Item key="fuel_refill">
<Link href="#fuelRefillSection">Fuel Refill</Link>
</Menu.Item>
<Menu.Item key="overspeeding">
<Link href="#overSpeedingSection">OverSpeeding</Link>
</Menu.Item>
<Menu.Item key="maintainance">
<Link href="#maintainanceSection">Maintainance</Link>
</Menu.Item>
</SubMenu>
<Menu.Item
key="accidentAlert"
icon={<NotificationsActiveOutlinedIcon />}
>
<Link href="#accidentAlertSection">Accident alert</Link>
</Menu.Item>
<Menu.Item
key="fuelTheftAlert"
icon={<NotificationImportantIcon />}
>
<Link href="#fuelTheftAlertSection">FuelTheft alert</Link>
</Menu.Item>
<Menu.Item key="addVehicle" icon={<LocalTaxiIcon />}>
<Link href="#addVehicleSection">Add Vehicle</Link>
</Menu.Item>
<Menu.Item key="addMaintainance" icon={<PostAddIcon />}>
<Link href="#addVehicleSection">Add Maintainance</Link>
</Menu.Item>
<Menu.Item key="reportIssue" icon={<ReportProblemOutlinedIcon />}>
<Link
href="https://github.com/abhishekpatel946/Smart-Vehicle-Fleet-Manager/issues/new/choose"
onClick={preventDefault}
>
Report an issue
</Link>
</Menu.Item>
</Menu>
</Sider>
{/* Breadcrum Naming */}
<Layout className="site-layout">
<Content style={{ margin: "0 16px" }}>
<Breadcrumb style={{ margin: "16px 0" }}>
<Breadcrumb.Item>User</Breadcrumb.Item>
<Breadcrumb.Item>Dashboard</Breadcrumb.Item>
<div>
<p className="h6 text-left mb-1">
Status : {liveState ? "Active" : "Inactive"}
{/* {vehicleModel}
{vehicleModelId} */}
</p>
</div>
</Breadcrumb>
<div
className="site-layout-background"
style={{ padding: 24, minHeight: 560 }}
>
{/* Speed Section */}
<Divider orientation="left" id="speedSection">
Speed area
</Divider>
<MDBContainer>
<SpeedLog />
</MDBContainer>
{/* Fuel Section */}
<Divider orientation="left" id="fuelSection">
Fuel area
</Divider>
<MDBContainer>
<MDBRow>
<FuelLog />
</MDBRow>
</MDBContainer>
{/* OverSpeeding Section */}
<Divider orientation="left" id="overSpeedingSection">
OverSpeeding area
</Divider>
<MDBContainer>
<MDBRow>
<OverSpeedLog />
</MDBRow>
</MDBContainer>
{/* Fuel Refill Section */}
<Divider orientation="left" id="fuelRefillSection">
Fuel Refill area
</Divider>
<MDBContainer>
<MDBRow>
<FuelRefillLog />
</MDBRow>
</MDBContainer>
{/* Maintainence Section */}
<Divider orientation="left" id="maintainanceSection">
Maintainance area
</Divider>
<MDBContainer>
<MDBRow>
<MaintainenceLog />
</MDBRow>
</MDBContainer>
{/* Accident Section */}
<Divider orientation="left" id="accidentAlertSection">
Accident Alert area
</Divider>
<MDBContainer>
<MDBRow>
<AccidentAlert />
</MDBRow>
</MDBContainer>
{/* FuelTheft Section */}
<Divider orientation="left" id="fuelTheftAlertSection">
FuelTheft Alert area
</Divider>
<MDBContainer>
<MDBRow>
<FuelTheftAlert />
</MDBRow>
</MDBContainer>
{/* addVehicle Section */}
<Divider orientation="left" id="addVehicleSection">
Add Vehicle
</Divider>
<MDBContainer>
<MDBRow>
<MDBCol md="6">
<form
className="needs-validation"
onSubmit={submitHandler}
noValidate
>
<p className="h5 text-center mb-4">Register Vehicle</p>
<div className="grey-text">
<MDBInput
className="addVehicle_vehicleNAME"
name="vehicleNAME"
onChange={(event) =>
setVehicleNAME(event.target.value)
}
value={vehicleNAME}
label="Your vehicle name"
icon="car"
group
type="text"
validate
error="wrong"
success="right"
required
/>
<MDBInput
className="addVehicle_vehicleID"
name="vehicleID"
onChange={(event) => setVehicleID(event.target.value)}
value={vehicleID}
label="Your vechile reg. number"
icon="registered"
group
type="text"
validate
error="wrong"
success="right"
required
/>
</div>
<div className="text-center">
<MDBBtn outline type="submit" onClick={vehicleRegister}>
Register
<MDBIcon className="ml-1" />
</MDBBtn>
</div>
</form>
</MDBCol>
<MDBCol md="6">
<form
className="needs-validation"
onSubmit={submitHandler}
noValidate
>
<p className="h5 text-center mb-4">
Register Maintainance
</p>
<div className="grey-text">
<MDBInput
className="addVehicle_vehicleNAME"
name="vehicleName"
onChange={(event) =>
setVehicleRegNumber(event.target.value)
}
value={vehicleRegNumber}
label="Your vehicle Reg number"
icon="registered"
group
type="text"
validate
error="wrong"
success="right"
required
/>
<div>
<MuiPickersUtilsProvider utils={DateFnsUtils}>
<KeyboardDatePicker
disableToolbar
fullWidth
variant="inline"
format="dd/MM/yyyy"
margin="normal"
id="date-picker-inline"
label="DD/MM/YYYY"
value={date}
onChange={onDateChange}
KeyboardButtonProps={{
"aria-label": "change date",
}}
/>
</MuiPickersUtilsProvider>
</div>
<MDBInput
className="addVehicle_vehicleID"
name="cost"
onChange={(event) => setCost(event.target.value)}
value={cost}
label="Your mainatenace cost..."
icon="rupee-sign"
group
type="text"
validate
error="wrong"
success="right"
required
/>
</div>
<div className="text-center">
<MDBBtn outline type="submit" onClick={addCost}>
Add Cost
<MDBIcon className="ml-1" />
</MDBBtn>
</div>
</form>
</MDBCol>
</MDBRow>
</MDBContainer>
{/* back to top */}
<Link href="#header">
<Button
// ghost
icon={<NavigationIcon />}
style={{
float: "right",
margin: "auto 20px 10px 20px",
}}
>
{" "}
Back to top{" "}
</Button>
</Link>
{/* End */}
</div>
</Content>
{/* snakbar notifiers */}
<Snackbar
open={vehicleAddSuccess}
autoHideDuration={3000}
onClose={handleClose}
>
<Alert onClose={handleClose} severity="success">
Vehicle added successfully.
</Alert>
</Snackbar>
<Snackbar
open={vehicleAddError}
autoHideDuration={3000}
onClose={handleClose}
>
<Alert onClose={handleClose} severity="error">
All the field's are mendatory!!!
</Alert>
</Snackbar>
<Snackbar
open={maintainanceAddSuccess}
autoHideDuration={3000}
onClose={handleClose}
>
<Alert onClose={handleClose} severity="success">
Maintainance added successfully.
</Alert>
</Snackbar>
<Snackbar
open={maintainanceAddError}
autoHideDuration={3000}
onClose={handleClose}
>
<Alert onClose={handleClose} severity="error">
All the field's are mendatory!!!
</Alert>
</Snackbar>
{/* footer */}
<FooterLayout />
</Layout>
</Layout>
</Layout>
);
}
Example #12
Source File: Scheduling.js From TSS with MIT License | 4 votes |
render() {
function Alert(props) {
return <MuiAlert elevation={6} variant="filled" {...props} />;
}
const {sched} = data;
const fin = localStorage.getItem("language");
return (
<div className="schedulingRoot">
<Modal open={this.state.state!=='ready'?true:false} onClick={this.handleBackdropClick}>
<Backdrop open={this.state.state!=='ready'?true:false} onClick={this.handleBackdropClick}>
<CircularProgress disableShrink />
</Backdrop>
</Modal>
{/* Section for selecting date */}
<div className="firstSection">
<form onSubmit={this.continueWithDate}>
{ /* Datepicker */}
<MuiPickersUtilsProvider utils={MomentUtils} locale={lang} key={this.state.datePickerKey}>
<KeyboardDatePicker
autoOk
margin="normal"
name="date"
label={sched.Day[fin]}
value={this.state.date}
onChange={date => this.handleDateChange(date)}
onAccept={this.handleDatePickChange}
format="DD.MM.YYYY"
showTodayButton
/>
</MuiPickersUtilsProvider>
<div className="continue">
<Button type="submit" variant="contained" style={{backgroundColor:'#d1ccc2'}}>{sched.Day[fin]}</Button>
</div>
</form>
</div>
<hr/>
{/* Section for setting range officer status and open/close times of the tracks */}
<div className="secondSection">
<div className="topRow">
<div className="text">{sched.Open[fin]}</div>
<Switch
checked={ this.state.available }
onChange={this.handleSwitchChange}
name="available"
color="primary"
style={{color:'#5f77a1'}} />
</div>
<div className="middleRow">
<div className="roSwitch">
<div className="text">{sched.Supervisor[fin]}</div>
<Switch
className="officerSwitch"
checked={this.state.rangeSupervisorSwitch}
onChange={this.handleSwitchChange}
name="rangeSupervisorSwitch"
color="primary"
style={{color:'#5f77a1'}} />
</div>
{this.createSupervisorSelect()}
</div>
<div className="bottomRow">
<div className="text">{sched.OpenHours[fin]}</div>
<MuiPickersUtilsProvider utils={MomentUtils} locale={'fi'}>
<KeyboardTimePicker
autoOk
ampm={false}
margin="normal"
name="start"
label={sched.Start[fin]}
value={this.state.open}
onChange={this.handleTimeStartChange}
minutesStep={5}
showTodayButton
/>
</MuiPickersUtilsProvider>
<div className="dash">-</div>
<MuiPickersUtilsProvider utils={MomentUtils} locale={'fi'}>
<KeyboardTimePicker
autoOk
ampm={false}
margin="normal"
name="end"
label={sched.Stop[fin]}
value={this.state.close}
onChange={this.handleTimeEndChange}
minutesStep={5}
showTodayButton
/>
</MuiPickersUtilsProvider>
</div>
</div>
<hr/>
{/* Section for setting track-specific open/close/absent statuses */}
<div className="thirdSection">
<div className="leftSide">
{this.createTrackList()}
</div>
<div className="rightSide">
<Button variant="contained" color="primary" onClick={this.openAllTracks} style={{color:'black', backgroundColor:'#5f77a1'}}>{sched.OpenAll[fin]}</Button>
<Button variant="contained" onClick={this.emptyAllTracks} style={{backgroundColor:'#d1ccc2'}}>{sched.ClearAll[fin]}</Button>
<Button variant="contained" color="secondary" onClick={this.closeAllTracks} style={{color:'black', backgroundColor:'#c97b7b'}}>{sched.CloseAll[fin]}</Button>
</div>
</div>
<hr/>
<div className="fourthSection">
<div className="repetition">
<div className="daily">
{sched.RepeatDaily[fin]}
<Switch
checked={ this.state.daily }
onChange={this.handleRepeatChange}
id='daily'
color="primary"
style={{color:'#5f77a1'}}
/>
</div>
<div className="weekly">
{sched.RepeatWeekly[fin]}
<Switch
checked={ this.state.weekly }
onChange={this.handleRepeatChange}
id='weekly'
color="primary"
style={{color:'#5f77a1'}}
/>
</div>
<div className="monthly">
{sched.RepeatMonthly[fin]}
<Switch
checked={ this.state.monthly }
onChange={this.handleRepeatChange}
id='monthly'
color="primary"
style={{color:'#5f77a1'}}
/>
</div>
<div className="repeatCount">
{sched.Amount[fin]}
<TextField
name="repeatCount"
type="number"
value={this.state.repeatCount}
onChange={this.handleValueChange}
InputProps={{ inputProps: { min: 1, max: 100 } }}
/>
</div>
</div>
<div className="save">
<Button variant="contained" onClick={this.saveChanges} style={{backgroundColor:'#d1ccc2'}}>{sched.Save[fin]}</Button>
<div
className="hoverHand arrow-right"
onClick={() => this.handleDatePickChange(moment(this.state.date).add(1, 'days').format('YYYY-MM-DD'))}
></div>
<div className="toast">
<Snackbar open={this.state.toast} autoHideDuration={5000} onClose={this.handleSnackbarClose}>
<Alert onClose={this.handleSnackbarClose} severity={this.state.toastSeverity}>
{this.state.toastMessage}!
</Alert>
</Snackbar>
</div>
</div>
</div>
</div>
);
}
Example #13
Source File: FilterTop.js From treetracker-admin-client with GNU Affero General Public License v3.0 | 4 votes |
function Filter(props) {
// console.log('render: filter top');
const speciesContext = useContext(SpeciesContext);
const tagsContext = useContext(TagsContext);
const { classes, filter = new FilterModel() } = props;
const filterOptionAll = 'All';
const dateStartDefault = null;
const dateEndDefault = null;
const [uuid, setUUID] = useState(filter?.uuid || '');
const [captureId, setCaptureId] = useState(filter?.captureId || '');
const [growerId, setGrowerId] = useState(filter?.planterId || '');
const [deviceId, setDeviceId] = useState(filter?.deviceIdentifier || '');
const [growerIdentifier, setGrowerIdentifier] = useState(
filter?.planterIdentifier || ''
);
const [approved, setApproved] = useState(filter?.approved);
const [active, setActive] = useState(filter?.active);
const [dateStart, setDateStart] = useState(
filter?.dateStart || dateStartDefault
);
const [dateEnd, setDateEnd] = useState(filter?.dateEnd || dateEndDefault);
const [speciesId, setSpeciesId] = useState(filter?.speciesId || ALL_SPECIES);
const [tag, setTag] = useState(null);
const [tagSearchString, setTagSearchString] = useState('');
const [organizationId, setOrganizationId] = useState(
filter.organizationId || ALL_ORGANIZATIONS
);
const [stakeholderUUID, setStakeholderUUID] = useState(
filter.stakeholderUUID || ALL_ORGANIZATIONS
);
const [tokenId, setTokenId] = useState(filter?.tokenId || filterOptionAll);
const handleDateStartChange = (date) => {
setDateStart(date);
};
const handleDateEndChange = (date) => {
setDateEnd(date);
};
const formatDate = (date) => {
return convertDateToDefaultSqlDate(date);
};
function handleSubmit(e) {
e.preventDefault();
// save the filer to context for editing & submit
const filter = new FilterModel();
filter.uuid = uuid;
filter.captureId = captureId;
filter.planterId = growerId;
filter.deviceIdentifier = deviceId;
filter.planterIdentifier = growerIdentifier;
filter.dateStart = dateStart ? formatDate(dateStart) : undefined;
filter.dateEnd = dateEnd ? formatDate(dateEnd) : undefined;
filter.approved = approved;
filter.active = active;
filter.speciesId = speciesId;
filter.tagId = tag ? tag.id : 0;
filter.organizationId = organizationId;
filter.stakeholderUUID = stakeholderUUID;
filter.tokenId = tokenId;
props.onSubmit && props.onSubmit(filter);
}
function handleReset() {
// reset form values, except 'approved' and 'active' which we'll keep
setUUID('');
setCaptureId('');
setGrowerId('');
setDeviceId('');
setGrowerIdentifier('');
setDateStart(dateStartDefault);
setDateEnd(dateEndDefault);
setSpeciesId(ALL_SPECIES);
setTag(null);
setTagSearchString('');
setOrganizationId(ALL_ORGANIZATIONS);
setStakeholderUUID(ALL_ORGANIZATIONS);
setTokenId(filterOptionAll);
const filter = new FilterModel();
filter.approved = approved; // keeps last value set
filter.active = active; // keeps last value set
props.onSubmit && props.onSubmit(filter);
}
return (
<>
{
<form onSubmit={handleSubmit}>
<Grid container wrap="nowrap" direction="row">
<Grid item className={classes.inputContainer}>
<TextField
select
htmlFor="verification-status"
id="verification-status"
label="Verification Status"
value={
active === undefined && approved === undefined
? filterOptionAll
: getVerificationStatus(active, approved)
}
onChange={(e) => {
setApproved(
e.target.value === filterOptionAll
? undefined
: e.target.value === verificationStates.AWAITING ||
e.target.value === verificationStates.REJECTED
? false
: true
);
setActive(
e.target.value === filterOptionAll
? undefined
: e.target.value === verificationStates.AWAITING ||
e.target.value === verificationStates.APPROVED
? true
: false
);
}}
>
{[
filterOptionAll,
verificationStates.APPROVED,
verificationStates.AWAITING,
verificationStates.REJECTED,
].map((name) => (
<MenuItem key={name} value={name}>
{name}
</MenuItem>
))}
</TextField>
<TextField
select
htmlFor="token-status"
id="token-status"
label="Token Status"
value={tokenId}
onChange={(e) => {
setTokenId(e.target.value);
}}
>
{[
filterOptionAll,
tokenizationStates.NOT_TOKENIZED,
tokenizationStates.TOKENIZED,
].map((name) => (
<MenuItem key={name} value={name}>
{name}
</MenuItem>
))}
</TextField>
<MuiPickersUtilsProvider
utils={DateFnsUtils}
locale={getDatePickerLocale()}
>
<KeyboardDatePicker
margin="normal"
id="start-date-picker"
htmlFor="start-date-picker"
label="Start Date"
format={getDateFormatLocale(true)}
value={dateStart}
onChange={handleDateStartChange}
maxDate={dateEnd || Date()} // Don't allow selection after today
KeyboardButtonProps={{
'aria-label': 'change date',
}}
/>
<KeyboardDatePicker
margin="normal"
id="end-date-picker"
htmlFor="end-date-picker"
label="End Date"
format={getDateFormatLocale(true)}
value={dateEnd}
onChange={handleDateEndChange}
minDate={dateStart || datePickerDefaultMinDate}
maxDate={Date()} // Don't allow selection after today
KeyboardButtonProps={{
'aria-label': 'change date',
}}
/>
</MuiPickersUtilsProvider>
<TextField
htmlFor="grower-id"
id="grower-id"
label="Grower ID"
placeholder="e.g. 7"
value={growerId}
onChange={(e) => setGrowerId(e.target.value)}
/>
<TextField
htmlFor="capture-id"
id="capture-id"
label="Capture ID"
placeholder="e.g. 80"
value={captureId}
onChange={(e) => setCaptureId(e.target.value)}
/>
<TextField
htmlFor="uuid"
id="uuid"
label="Capture UUID"
placeholder=""
value={uuid}
onChange={(e) => setUUID(e.target.value)}
/>
<TextField
htmlFor="device-identifier"
id="device-identifier"
label="Device Identifier"
placeholder="e.g. 1234abcd"
value={deviceId}
onChange={(e) => setDeviceId(e.target.value)}
/>
<TextField
htmlFor="grower-identifier"
id="grower-identifier"
label="Grower Identifier"
placeholder="e.g. [email protected]"
value={growerIdentifier}
onChange={(e) => setGrowerIdentifier(e.target.value)}
/>
<TextField
data-testid="species-dropdown"
select
htmlFor="species"
id="species"
label="Species"
value={speciesId}
onChange={(e) => setSpeciesId(e.target.value)}
>
{speciesContext.isLoading ? (
<CircularProgress />
) : (
[
{ id: ALL_SPECIES, name: 'All' },
{
id: SPECIES_NOT_SET,
name: 'Not set',
},
...speciesContext.speciesList,
].map((species) => (
<MenuItem
data-testid="species-item"
key={species.id}
value={species.id}
>
{species.name}
</MenuItem>
))
)}
</TextField>
<Autocomplete
data-testid="tag-dropdown"
label="Tag"
htmlFor="tag"
id="tag"
classes={{
inputRoot: classes.autocompleteInputRoot,
}}
options={[
{
id: TAG_NOT_SET,
tagName: 'Not set',
active: true,
public: true,
},
{
id: ANY_TAG_SET,
tagName: 'Any tag set',
active: true,
public: true,
},
...tagsContext.tagList.filter((t) =>
t.tagName
.toLowerCase()
.startsWith(tagSearchString.toLowerCase())
),
]}
value={tag}
defaultValue={'Not set'}
getOptionLabel={(tag) => {
// if (tag === 'Not set') {
// return 'Not set';
// }
return tag.tagName;
}}
onChange={(_oldVal, newVal) => {
//triggered by onInputChange
console.log('newVal -- ', newVal);
setTag(newVal);
}}
onInputChange={(_oldVal, newVal) => {
setTagSearchString(newVal);
}}
renderInput={(params) => {
return <TextField {...params} label="Tag" />;
}}
getOptionSelected={(option, value) => option.id === value.id}
// selectOnFocus
// clearOnBlur
// handleHomeEndKeys
/>
<SelectOrg
orgId={organizationId}
handleSelection={(org) => {
setStakeholderUUID(org.stakeholder_uuid);
setOrganizationId(org.id);
}}
/>
</Grid>
<Grid className={classes.inputContainer}>
<Button
className={classes.apply}
type="submit"
label="submit"
htmlFor="submit"
id="submit"
variant="outlined"
color="primary"
onClick={(e) => handleSubmit(e)}
>
Apply
</Button>
<Button
className={classes.apply}
label="reset"
htmlFor="reset"
id="reset"
variant="outlined"
color="primary"
onClick={handleReset}
>
Reset
</Button>
</Grid>
</Grid>
</form>
}
</>
);
}
Example #14
Source File: Filter.js From treetracker-admin-client with GNU Affero General Public License v3.0 | 4 votes |
function Filter(props) {
const { classes, filter } = props;
// console.log('filter', filter);
const filterOptionAll = 'All';
const dateStartDefault = null;
const dateEndDefault = null;
const [captureId, setCaptureId] = useState(filter?.captureId || '');
const [growerId, setGrowerId] = useState(filter?.planterId || '');
const [deviceIdentifier, setDeviceIdentifier] = useState(
filter?.deviceIdentifier || '',
);
const [growerIdentifier, setGrowerIdentifier] = useState(
filter?.planterIdentifier || '',
);
const [status, setStatus] = useState(filter?.status);
const [approved, setApproved] = useState(filter?.approved);
const [active, setActive] = useState(filter?.active);
const [dateStart, setDateStart] = useState(
filter?.dateStart || dateStartDefault,
);
const [dateEnd, setDateEnd] = useState(filter?.dateEnd || dateEndDefault);
const [tokenId, setTokenId] = useState(filter?.tokenId || filterOptionAll);
const handleDateStartChange = (date) => {
setDateStart(date);
};
const handleDateEndChange = (date) => {
setDateEnd(date);
};
const formatDate = (date) => {
return convertDateToDefaultSqlDate(date);
};
function handleCloseClick() {
props.onClose && props.onClose();
}
function handleSubmit(e) {
e.preventDefault();
const filter = new FilterModel();
filter.captureId = captureId;
filter.planterId = growerId;
filter.deviceIdentifier = deviceIdentifier;
filter.planterIdentifier = growerIdentifier;
filter.dateStart = dateStart ? formatDate(dateStart) : undefined;
filter.dateEnd = dateEnd ? formatDate(dateEnd) : undefined;
filter.approved = approved;
filter.active = active;
filter.tokenId = tokenId;
filter.status = status;
props.onSubmit && props.onSubmit(filter);
}
function handleClear() {
setCaptureId('');
setGrowerId('');
setDeviceIdentifier('');
setGrowerIdentifier('');
setDateStart(dateStartDefault);
setDateEnd(dateEndDefault);
setApproved();
setActive();
setTokenId(filterOptionAll);
setStatus('All');
const filter = new FilterModel();
props.onSubmit && props.onSubmit(filter);
}
return (
<Drawer
className={classes.drawer}
classes={{
paper: classes.drawerPaper,
}}
open={props.isOpen}
variant="persistent"
anchor="right"
PaperProps={{
elevation: props.isOpen ? 6 : 0,
}}
>
<Grid container justify="space-between">
<Grid item>
<Typography variant="h5">Filters</Typography>
</Grid>
{props.onClose && (
<Grid item>
<IconButton
color="primary"
classes={{
colorPrimary: classes.close,
}}
onClick={handleCloseClick}
>
<IconClose />
</IconButton>
</Grid>
)}
</Grid>
<Button variant="outlined" color="primary" onClick={handleSubmit}>
Apply Filters
</Button>
<Button
variant="outlined"
color="primary"
onClick={handleClear}
className={classNames(classes.button)}
>
Clear Filters
</Button>
<GSInputLabel text="Capture ID" />
<TextField
placeholder="e.g. 80"
InputLabelProps={{
shrink: true,
}}
value={captureId}
onChange={(e) => setCaptureId(e.target.value)}
/>
<GSInputLabel text="Grower ID" />
<TextField
placeholder="grower id"
InputLabelProps={{
shrink: true,
}}
value={growerId}
onChange={(e) => setGrowerId(e.target.value)}
/>
<GSInputLabel text="Device Identifier" />
<TextField
placeholder="device identifier"
InputLabelProps={{
shrink: true,
}}
value={deviceIdentifier}
onChange={(e) => setDeviceIdentifier(e.target.value)}
/>
<GSInputLabel text="Grower Identifier" />
<TextField
placeholder="grower identifier"
InputLabelProps={{
shrink: true,
}}
value={growerIdentifier}
onChange={(e) => setGrowerIdentifier(e.target.value)}
/>
<GSInputLabel text="Verification Status" />
<TextField
select
value={
active === undefined && approved === undefined
? filterOptionAll
: getVerificationStatus(active, approved)
}
onChange={(e) => {
setApproved(
e.target.value === filterOptionAll
? undefined
: e.target.value === verificationStates.AWAITING ||
e.target.value === verificationStates.REJECTED
? false
: true,
);
setActive(
e.target.value === filterOptionAll
? undefined
: e.target.value === verificationStates.AWAITING ||
e.target.value === verificationStates.APPROVED
? true
: false,
);
}}
>
{[
filterOptionAll,
verificationStates.APPROVED,
verificationStates.AWAITING,
verificationStates.REJECTED,
].map((name) => (
<MenuItem key={name} value={name}>
{name}
</MenuItem>
))}
</TextField>
<GSInputLabel text="Token Status" />
<TextField
select
value={tokenId}
onChange={(e) => {
setTokenId(e.target.value);
}}
>
{[
filterOptionAll,
tokenizationStates.NOT_TOKENIZED,
tokenizationStates.TOKENIZED,
].map((name) => (
<MenuItem key={name} value={name}>
{name}
</MenuItem>
))}
</TextField>
<GSInputLabel text="Time created" />
<MuiPickersUtilsProvider
utils={DateFnsUtils}
locale={getDatePickerLocale()}
>
<Grid container justify="space-between">
<KeyboardDatePicker
margin="normal"
id="start-date-picker"
label="Start Date"
value={dateStart}
onChange={handleDateStartChange}
format={getDateFormatLocale(true)}
maxDate={dateEnd || Date()} // Don't allow selection after today
KeyboardButtonProps={{
'aria-label': 'change date',
}}
className={classes.dateInput}
/>
<KeyboardDatePicker
margin="normal"
id="end-date-picker"
label="End Date"
value={dateEnd}
onChange={handleDateEndChange}
format={getDateFormatLocale(true)}
minDate={dateStart || datePickerDefaultMinDate}
maxDate={Date()} // Don't allow selection after today
KeyboardButtonProps={{
'aria-label': 'change date',
}}
className={classes.dateInput}
/>
</Grid>
</MuiPickersUtilsProvider>
</Drawer>
);
}
Example #15
Source File: CaptureFilter.js From treetracker-admin-client with GNU Affero General Public License v3.0 | 4 votes |
function Filter(props) {
const speciesContext = useContext(SpeciesContext);
const tagsContext = useContext(TagsContext);
const { classes, filter = new FilterModel() } = props;
const filterOptionAll = 'All';
const dateStartDefault = null;
const dateEndDefault = null;
const [uuid, setUUID] = useState(filter?.uuid || '');
const [captureId, setCaptureId] = useState(filter?.captureId || '');
const [growerId, setGrowerId] = useState(filter?.planterId || '');
const [deviceId, setDeviceId] = useState(filter?.deviceIdentifier || '');
const [growerIdentifier, setGrowerIdentifier] = useState(
filter?.planterIdentifier || ''
);
const [verifyStatus, setVerifyStatus] = useState([
{ active: true, approved: true },
{ active: true, approved: false },
]);
const [dateStart, setDateStart] = useState(
filter?.dateStart || dateStartDefault
);
const [dateEnd, setDateEnd] = useState(filter?.dateEnd || dateEndDefault);
const [speciesId, setSpeciesId] = useState(filter?.speciesId || ALL_SPECIES);
const [tag, setTag] = useState(null);
const [tagSearchString, setTagSearchString] = useState('');
const [organizationId, setOrganizationId] = useState(
filter.organizationId || ALL_ORGANIZATIONS
);
const [stakeholderUUID, setStakeholderUUID] = useState(
filter.stakeholderUUID || ALL_ORGANIZATIONS
);
const [tokenId, setTokenId] = useState(filter?.tokenId || filterOptionAll);
const [verificationStatus, setVerificationStatus] = useState([
verificationStates.APPROVED,
verificationStates.AWAITING,
]);
const isAllVerification =
verificationStatus.length &&
verificationStatus.length === verificationStatesArr.length;
const handleDateStartChange = (date) => {
setDateStart(date);
};
const handleDateEndChange = (date) => {
setDateEnd(date);
};
const formatDate = (date) => {
return convertDateToDefaultSqlDate(date);
};
const handleVerificationStatusChange = (event) => {
let value = event.target.value;
let status = [];
if (
value[value.length - 1] === 'all' ||
(value.length === 3 && value[value.length - 1] !== 'all')
) {
setVerificationStatus(
verificationStatus.length === verificationStatesArr.length
? []
: verificationStatesArr
);
value = verificationStatesArr;
} else {
setVerificationStatus(value);
}
value.forEach((val) => {
if (val === verificationStates.APPROVED) {
status.push({ active: true, approved: true });
} else if (val === verificationStates.AWAITING) {
status.push({ active: true, approved: false });
} else if (val === verificationStates.REJECTED) {
status.push({ active: false, approved: false });
}
});
setVerifyStatus(status);
};
function handleSubmit(e) {
e.preventDefault();
// save the filer to context for editing & submit
const filter = new FilterModel();
filter.uuid = uuid;
filter.captureId = captureId;
filter.planterId = growerId;
filter.deviceIdentifier = deviceId;
filter.planterIdentifier = growerIdentifier;
filter.dateStart = dateStart ? formatDate(dateStart) : undefined;
filter.dateEnd = dateEnd ? formatDate(dateEnd) : undefined;
filter.speciesId = speciesId;
filter.tagId = tag ? tag.id : 0;
filter.organizationId = organizationId;
filter.stakeholderUUID = stakeholderUUID;
filter.tokenId = tokenId;
filter.verifyStatus = verifyStatus;
props.onSubmit && props.onSubmit(filter);
}
function handleReset() {
// reset form values, except 'approved' and 'active' which we'll keep
setUUID('');
setCaptureId('');
setGrowerId('');
setDeviceId('');
setGrowerIdentifier('');
setDateStart(dateStartDefault);
setDateEnd(dateEndDefault);
setSpeciesId(ALL_SPECIES);
setTag(null);
setTagSearchString('');
setOrganizationId(ALL_ORGANIZATIONS);
setStakeholderUUID(ALL_ORGANIZATIONS);
setTokenId(filterOptionAll);
setVerifyStatus([
{ active: true, approved: true },
{ active: true, approved: false },
]);
const filter = new FilterModel();
props.onSubmit && props.onSubmit(filter);
}
return (
<>
{
<form onSubmit={handleSubmit}>
<Grid container wrap="nowrap" direction="row">
<Grid item className={classes.inputContainer}>
<TextField
select
htmlFor="verification-status"
id="verification-status"
label="Verification Status"
SelectProps={{
multiple: true,
value: verificationStatus,
onChange: handleVerificationStatusChange,
renderValue: (verificationStatus) =>
verificationStatus.join(', '),
}}
>
<MenuItem value="all">
<ListItemIcon>
<Checkbox
checked={
isAllVerification === 0 ? false : isAllVerification
}
indeterminate={
verificationStatus.length > 0 &&
verificationStatus.length < verificationStatesArr.length
}
/>
</ListItemIcon>
<ListItemText primary="Select All" />
</MenuItem>
{verificationStatesArr.map((name) => (
<MenuItem key={name} value={name}>
<ListItemIcon>
<Checkbox
checked={verificationStatus.indexOf(name) > -1}
/>
</ListItemIcon>
<ListItemText primary={name} />
</MenuItem>
))}
</TextField>
<TextField
select
htmlFor="token-status"
id="token-status"
label="Token Status"
value={tokenId}
onChange={(e) => {
setTokenId(e.target.value);
}}
>
{[
filterOptionAll,
tokenizationStates.NOT_TOKENIZED,
tokenizationStates.TOKENIZED,
].map((name) => (
<MenuItem key={name} value={name}>
{name}
</MenuItem>
))}
</TextField>
<MuiPickersUtilsProvider
utils={DateFnsUtils}
locale={getDatePickerLocale()}
>
<KeyboardDatePicker
margin="normal"
id="start-date-picker"
htmlFor="start-date-picker"
label="Start Date"
format={getDateFormatLocale(true)}
value={dateStart}
onChange={handleDateStartChange}
maxDate={dateEnd || Date()} // Don't allow selection after today
KeyboardButtonProps={{
'aria-label': 'change date',
}}
/>
<KeyboardDatePicker
margin="normal"
id="end-date-picker"
htmlFor="end-date-picker"
label="End Date"
format={getDateFormatLocale(true)}
value={dateEnd}
onChange={handleDateEndChange}
minDate={dateStart || datePickerDefaultMinDate}
maxDate={Date()} // Don't allow selection after today
KeyboardButtonProps={{
'aria-label': 'change date',
}}
/>
</MuiPickersUtilsProvider>
<TextField
htmlFor="grower-id"
id="grower-id"
label="Grower ID"
placeholder="e.g. 2, 7"
value={growerId}
onChange={(e) => setGrowerId(e.target.value)}
/>
<TextField
htmlFor="capture-id"
id="capture-id"
label="Capture ID"
placeholder="e.g. 80"
value={captureId}
onChange={(e) => setCaptureId(e.target.value)}
/>
<TextField
htmlFor="uuid"
id="uuid"
label="Capture UUID"
placeholder=""
value={uuid}
onChange={(e) => setUUID(e.target.value)}
/>
<TextField
htmlFor="device-identifier"
id="device-identifier"
label="Device Identifier"
placeholder="e.g. 1234abcd"
value={deviceId}
onChange={(e) => setDeviceId(e.target.value)}
/>
<TextField
htmlFor="grower-identifier"
id="grower-identifier"
label="Grower Identifier"
placeholder="e.g. [email protected]"
value={growerIdentifier}
onChange={(e) => setGrowerIdentifier(e.target.value)}
/>
<TextField
data-testid="species-dropdown"
select
htmlFor="species"
id="species"
label="Species"
value={speciesId}
onChange={(e) => setSpeciesId(e.target.value)}
>
{speciesContext.isLoading ? (
<CircularProgress />
) : (
[
{ id: ALL_SPECIES, name: 'All' },
{
id: SPECIES_NOT_SET,
name: 'Not set',
},
...speciesContext.speciesList,
].map((species) => (
<MenuItem
data-testid="species-item"
key={species.id}
value={species.id}
>
{species.name}
</MenuItem>
))
)}
</TextField>
<Autocomplete
data-testid="tag-dropdown"
label="Tag"
htmlFor="tag"
id="tag"
classes={{
inputRoot: classes.autocompleteInputRoot,
}}
options={[
...tagsContext.tagList.filter((t) =>
t.tagName
.toLowerCase()
.startsWith(tagSearchString.toLowerCase())
),
]}
value={tag}
defaultValue={'Not set'}
getOptionLabel={(tag) => {
return tag.tagName;
}}
onChange={(_oldVal, newVal) => {
//triggered by onInputChange
if (newVal && newVal.tagName === 'Not set') {
setTag('Not set');
} else {
setTag(newVal);
}
}}
onInputChange={(_oldVal, newVal) => {
setTagSearchString(newVal);
}}
renderInput={(params) => {
return <TextField {...params} label="Tag" />;
}}
// selectOnFocus
// clearOnBlur
// handleHomeEndKeys
/>
<SelectOrg
orgId={organizationId}
handleSelection={(org) => {
setStakeholderUUID(org.stakeholder_uuid);
setOrganizationId(org.id);
}}
/>
</Grid>
<Grid className={classes.inputContainer}>
<Button
className={classes.apply}
type="submit"
label="submit"
htmlFor="submit"
id="submit"
variant="outlined"
color="primary"
onClick={(e) => handleSubmit(e)}
>
Apply
</Button>
<Button
className={classes.apply}
label="reset"
htmlFor="reset"
id="reset"
variant="outlined"
color="primary"
onClick={handleReset}
>
Reset
</Button>
</Grid>
</Grid>
</form>
}
</>
);
}
Example #16
Source File: index.js From flame-coach-web with MIT License | 4 votes |
TaskTool = ({
task,
notification,
notificationCollapseHandler,
updateNotificationHandler,
addTasksHandler,
addMultipleTasksHandler,
updateTaskHandler,
selectUpdateTaskHandler
}) => {
const classes = useStyles();
const [startDateState, setStartDate] = useState(moment()
.format(moment.HTML5_FMT.DATE));
const [endDateState, setEndDate] = useState(moment()
.format(moment.HTML5_FMT.DATE));
useEffect(() => {
// FIXME: This not allow change the date of task.
if (task) {
setStartDate(task.date);
setEndDate(task.date);
}
logDebug("TaskTool", "render", "task", task, startDateState, endDateState);
});
const resetFormValues = (setFieldValue) => {
setStartDate(moment()
.utc()
.format(moment.HTML5_FMT.DATE));
setEndDate(moment()
.utc()
.format(moment.HTML5_FMT.DATE));
setFieldValue("button", "ADD", false);
setFieldValue("taskName", "", false);
setFieldValue("taskDescription", "", false);
setFieldValue("multipleDays", false, false);
setFieldValue("isUpdate", false, false);
updateNotificationHandler(false, "", "");
selectUpdateTaskHandler(null);
};
return (
<Card className={clsx(classes.root)}>
<CardHeader
title="Plan Daily Routine"
/>
<Divider />
<CardContent>
<Formik
// FIXME: Please remote the init values
initialValues={{
taskName: task !== null ? task.taskName : "",
taskDescription: task !== null ? task.taskDescription : "",
multipleDays: false,
button: null,
isUpdate: task !== null
}}
validationSchema={Yup.object()
.shape({
taskName: Yup.string()
.max(255)
.required("Name is required")
})}
enableReinitialize
onSubmit={(values, { setSubmitting }) => {
if (values.multipleDays) {
if (moment(startDateState)
.isSameOrAfter(moment(endDateState))) {
const errorCode = ErrorMessage.CODE_0001;
updateNotificationHandler(true, errorCode.msg, errorCode.level);
} else {
const dailyTask = {
name: values.taskName,
description: values.taskDescription,
date: startDateState,
toDate: endDateState
};
addMultipleTasksHandler(dailyTask);
}
} else if (values.isUpdate) {
const dailyTask = {
name: values.taskName,
description: values.taskDescription,
date: startDateState
};
logDebug("TaskTool", "update", "dailyTask", dailyTask);
updateTaskHandler(dailyTask);
} else {
const dailyTask = {
name: values.taskName,
description: values.taskDescription,
date: startDateState
};
addTasksHandler(dailyTask);
}
setSubmitting(false);
}}
>
{({
errors,
handleBlur,
handleChange,
handleSubmit,
touched,
values,
setFieldValue
}) => (
<form onSubmit={handleSubmit}>
<Box>
<Grid
container
spacing={1}
>
<Grid item xs={12} lg={5} md={5}>
<TextField
error={Boolean(touched.taskName && errors.taskName)}
fullWidth
helperText={touched.taskName && errors.taskName}
label="Routine Name"
margin="dense"
name="taskName"
onBlur={handleBlur}
onChange={handleChange}
type="text"
value={values.taskName}
variant="outlined"
/>
</Grid>
<Grid item xs={12}>
<TextField
fullWidth
helperText="A simple description/instructions for routine"
label="Routine Description"
margin="dense"
name="taskDescription"
onBlur={handleBlur}
onChange={handleChange}
type="text"
value={values.taskDescription}
variant="outlined"
/>
</Grid>
<Grid item sm={12} md={3}>
<FormGroup row>
<FormControlLabel
control={(
<Checkbox
name="multipleDays"
onBlur={handleBlur}
onChange={handleChange}
disabled={values.isUpdate}
checked={values.multipleDays}
/>
)}
labelPlacement="start"
label="Multiple Days"
/>
<FormHelperText className={classes.multipleDaysHelper}>
Enable this to add same routine into multiple days
</FormHelperText>
</FormGroup>
</Grid>
<Grid item sm={12} md={3}>
<KeyboardDatePicker
autoOk
helperText="Start Date"
margin="dense"
format="YYYY/MM/DD"
onChange={(date) => {
setStartDate(moment(date)
.format(moment.HTML5_FMT.DATE));
}}
value={startDateState}
inputVariant="outlined"
variant="inline"
/>
</Grid>
<Grid item sm={12} md={3}>
<KeyboardDatePicker
autoOk
disabled={!values.multipleDays}
helperText="End Date"
margin="dense"
format="YYYY/MM/DD"
onChange={(date) => {
setEndDate(moment(date)
.format(moment.HTML5_FMT.DATE));
}}
value={endDateState}
inputVariant="outlined"
variant="inline"
/>
</Grid>
</Grid>
</Box>
<Box
display="flex"
justifyContent="flex-end"
className={clsx(classes.actionButtons)}
>
<Grid
container
justifyContent="flex-end"
spacing={2}
>
<Grid item>
<Button
className={classes.addButton}
fullWidth
disabled={values.isUpdate}
size="large"
onClick={() => {
setFieldValue("button", "ADD", false);
handleSubmit();
}}
variant="contained"
>
Add
</Button>
</Grid>
<Grid item>
<Button
className={classes.updateButton}
color="inherit"
fullWidth
disabled={!values.isUpdate}
size="large"
onClick={() => {
setFieldValue("button", "UPDATE", false);
handleSubmit();
}}
variant="contained"
>
Update
</Button>
</Grid>
<Grid item>
<Button
className={classes.resetButton}
color="inherit"
fullWidth
size="large"
onClick={() => {
resetFormValues(setFieldValue);
}}
variant="contained"
>
Reset
</Button>
</Grid>
</Grid>
</Box>
{notification.enable
? (
<Notification
collapse
open={notification.enable}
openHandler={notificationCollapseHandler}
level={notification.level}
message={notification.message}
/>
)
: null}
</form>
)}
</Formik>
</CardContent>
</Card>
);
}
Example #17
Source File: index.js From flame-coach-web with MIT License | 4 votes |
IncomeView = ({
coachIdentifier
}) => {
const classes = useStyles();
const isMobile = useIsMediumMobile();
const [fromDate, setFromDate] = useState(getDefaultTimezoneDateTime(moment.tz()));
const [toDate, setToDate] = useState(getDefaultTimezoneDateTime(moment.tz()
.add(1, "month")));
// region Code with queries to API
const appointments = useFetchAppointmentsCoachWithFilter(
coachIdentifier,
displayDateWithDash(fromDate),
displayDateWithDash(toDate),
{
select: (data) => {
if (data === undefined || !data.appointments) {
return [];
}
let totalPending = 0;
let totalAccepted = 0;
let totalMoney = 0.0;
const appointmentsTable = data.appointments.map((item) => {
const date = displayDateWithSlash(moment.tz(item.dttmStarts, defaultTimezone));
if (item.incomeStatus === "ACCEPTED") {
totalAccepted++;
totalMoney = totalMoney + item.price;
}
if (item.incomeStatus === "PENDING") {
totalPending++;
}
return [date, `${item.client.firstName} ${item.client.lastName}`, `${item.price} £`, item.incomeStatus, item];
}
);
return {
appointments: appointmentsTable,
totalPending: totalPending,
totalAccepted: totalAccepted,
totalMoney: totalMoney
};
}
}
);
const editAppointment = useEditAppointmentClient();
// endregion
// region General methods
const updateAppointmentStatus = (value, status) => {
editAppointment.mutate({
appointmentIdentifier: value.identifier,
appointment: {
"dttmStarts": convertDateToTimezoneInstance(value.dttmStarts),
"dttmEnds": convertDateToTimezoneInstance(value.dttmEnds),
resource: {
"price": value.price,
"notes": value.notes
},
"incomeStatus": status
}
}, {
onSuccess: () => {
appointments.refetch();
},
onError: (error) => {
logError("Appointments", "useMutation editAppointment", "Error Details:", error.response.data.detail);
}
}
);
};
const columns = [
"Date",
"Appointment",
"Price",
"Status",
{
label: "Actions",
options: {
filter: false,
sort: false,
setCellHeaderProps: () => {
return {
className: clsx({
[classes.rightTableHead]: true
})
};
},
// eslint-disable-next-line react/display-name
customBodyRender: (value) => {
return (
<Grid
container
justifyContent={isMobile ? "flex-start" : "flex-end"}
spacing={1}
className={clsx({
[classes.actionColumnTable]: true
})}
>
<Grid item>
<Button
className={classes.acceptButton}
variant="contained"
disabled={value.incomeStatus === "ACCEPTED"}
onClick={() => updateAppointmentStatus(value, "ACCEPTED")}
>
<SvgIcon
fontSize="small"
color="inherit"
>
<AcceptIcon />
</SvgIcon>
</Button>
</Grid>
<Grid item>
<Button
className={classes.rejectButton}
variant="contained"
disabled={value.incomeStatus === "REJECTED"}
onClick={() => updateAppointmentStatus(value, "REJECTED")}
>
<SvgIcon
fontSize="small"
color="inherit"
>
<RejectIcon />
</SvgIcon>
</Button>
</Grid>
</Grid>
);
}
}
}
];
// endregion
return (
<Page
title="Income"
isError={appointments.isError}
isLoading={false}>
<Grid
direction="row"
container
spacing={1}
>
<Grid item xs={12} md={9} lg={9}>
<LoadingBox isLoading={appointments.isFetching}>
<Table
title="Income Status"
data={appointments.data?.appointments}
columns={columns}
options={options}
/>
</LoadingBox>
</Grid>
<Grid item xs={12} md={3} lg={3}>
<Grid
direction="row"
container
spacing={1}
>
<Grid item xs={12}>
<Card>
<CardContent>
<Typography component="h2" variant="h5" gutterBottom>
Filter
</Typography>
<Box>
<KeyboardDatePicker
autoOk
allowKeyboardControl={false}
fullWidth
helperText="from"
margin="dense"
format="YYYY/MM/DD"
value={fromDate}
placeholder={displayDateWithSlash(fromDate)}
onChange={(date) => {
if (date !== null) {
setFromDate(date);
}
}}
/>
</Box>
<Box>
<KeyboardDatePicker
autoOk
allowKeyboardControl={false}
fullWidth
helperText="to"
margin="dense"
format="YYYY/MM/DD"
value={toDate}
placeholder={displayDateWithSlash(toDate)}
onChange={(date) => {
if (date !== null) {
setToDate(date);
}
}}
/>
</Box>
<Box
display="flex"
flexDirection="column"
justifyContent="flex-end"
textAlign="right"
>
<Box>
Income Accepted: {appointments.data?.totalAccepted}
</Box>
<Box>
Income Pending: {appointments.data?.totalPending}
</Box>
<Typography component="h2" variant="h5" gutterBottom>
Total: {appointments.data?.totalMoney}£
</Typography>
</Box>
</CardContent>
</Card>
</Grid>
</Grid>
</Grid>
</Grid>
</Page>
);
}
Example #18
Source File: index.js From flame-coach-web with MIT License | 4 votes |
Filters = ({
timeFrame,
date,
onChangeDateHandler,
weight,
onChangeWeightHandler,
onChangeTimeFrameHandler,
enableAddingWeight,
onAddWeightHandler,
className
}) => {
const classes = useStyles();
return (
<Card className={clsx(classes.root)}>
<CardContent className={className}>
<div className={classes.filterSession}>
<Grid
container
spacing={1}
direction="row"
>
<Grid
item
xs={12}
>
<Typography component="h2" variant="h5" gutterBottom>
Filters
</Typography>
</Grid>
<Grid
item
xs={12}
>
<FormControl variant="outlined">
<InputLabel>Time Frame</InputLabel>
<Select
labelId="time-frame-weight"
id="time-frame-weight-select"
value={timeFrame}
onChange={(event) => onChangeTimeFrameHandler(event.target.value)}
label="Time Frame"
>
<MenuItem value="1_WEEK">1 Week</MenuItem>
<MenuItem value="1_MONTH">1 Month</MenuItem>
<MenuItem value="2_MONTH">2 Month</MenuItem>
<MenuItem value="6_MONTH">6 Month</MenuItem>
</Select>
</FormControl>
</Grid>
</Grid>
</div>
{enableAddingWeight
? (
<>
<Divider variant="fullWidth" />
<div className={classes.addSession}>
<Typography component="h2" variant="h5" gutterBottom>
Add
</Typography>
<TextField
fullWidth
helperText="Please specify your weight"
label="Weight"
name="weight"
type="number"
required
inputProps={{
step: 0.05,
min: 0
}}
onChange={(event) => {
onChangeWeightHandler(event.target.valueAsNumber);
}}
value={weight}
/>
<KeyboardDatePicker
autoOk
fullWidth
helperText="Date"
margin="dense"
format="YYYY/MM/DD"
onChange={(newDate) => onChangeDateHandler(newDate)}
value={date}
/>
<Box
display="flex"
justifyContent="flex-end"
m={1}
>
<Button
color="primary"
variant="contained"
startIcon={<AddIcon />}
onClick={() => onAddWeightHandler(weight, date)}
>
Add
</Button>
</Box>
</div>
</>
)
: null}
</CardContent>
</Card>
);
}
Example #19
Source File: updateQuizDetails.js From Quizzie with MIT License | 4 votes |
function UpdateQuizDetails(props) {
const [quizId, setQuizId] = useState(props.match.params.id);
const [quizName, setQuizName] = useState("");
const [quizDate, setQuizDate] = useState(new Date());
const [duration, setDuration] = useState(5);
const [type, setType] = useState("private");
const [loading, setLoading] = useState(true);
const [redirect, setRedirect] = useState(false);
const { executeRecaptcha } = useGoogleReCaptcha();
const onQuizNameChange = (event) => {
setQuizName(event.target.value);
};
const handleDateChange = (date) => {
setQuizDate(date);
};
const handleTimeChange = (e, val) => {
setDuration(val);
};
const onTypeChange = (event) => {
setType(event.target.value);
};
const handleSubmit = async () => {
setLoading(true);
let token = localStorage.getItem("authToken");
let url = `https://quizzie-api.herokuapp.com/quiz/updateDetails/${quizId}`;
let captcha = await executeRecaptcha("update_quiz_details");
let updateOps = [
{ propName: "quizName", value: quizName },
{ propName: "scheduledFor", value: quizDate.getTime() },
{ propName: "quizDuration", value: duration },
];
let data = {
updateOps,
captcha,
};
try {
await axios
.patch(url, data, {
headers: {
"auth-token": token,
},
})
.then((res) => {
setLoading(false);
setRedirect(true);
});
} catch (error) {
console.log(error);
setLoading(false);
}
};
const getQuizDetails = async () => {
setLoading(true);
let token = localStorage.getItem("authToken");
let url = `https://quizzie-api.herokuapp.com/quiz/${quizId}`;
try {
await axios
.get(url, {
headers: {
"auth-token": token,
},
})
.then((res) => {
let details = res.data.result;
setQuizName(details.quizName);
setQuizDate(new Date(Number(details.scheduledFor)));
setDuration(details.quizDuration);
setType(details.quizType);
setLoading(false);
});
} catch (error) {
console.log(error);
setLoading(false);
}
};
useEffect(() => {
getQuizDetails();
}, []);
useEffect(() => {
let token = localStorage.getItem("authToken");
if (token === null) {
setLoading(false);
setRedirect(true);
return;
}
}, []);
if (loading) {
return <Loading />;
} else if (redirect) {
return <Redirect to={`/editQuiz/${quizId}`} />;
} else {
return (
<Container className="create-quiz-page">
<div className="create-form">
<Typography variant="h4" className="create-head">
Quiz Details
</Typography>
<div className="create-form-inputs">
<TextInput
variant="outlined"
label="Quiz Name"
value={quizName}
onChange={onQuizNameChange}
name="Quiz Name"
className="form-input"
/>
<MuiPickersUtilsProvider utils={DateFnsUtils}>
<Grid
className="date-time-select"
container
spacing={3}
>
<Grid item xs={12} sm={6}>
<KeyboardDatePicker
disableToolbar
variant="inline"
format="MM/dd/yyyy"
margin="normal"
label="Select Quiz Date"
value={quizDate}
onChange={handleDateChange}
/>
</Grid>
<Grid item xs={12} sm={6}>
<KeyboardTimePicker
margin="normal"
label="Select Quiz Start Time"
value={quizDate}
onChange={handleDateChange}
/>
</Grid>
</Grid>
</MuiPickersUtilsProvider>
<p style={{ marginTop: "5%", marginBottom: "5%" }}>
Quiz Time (in minutes):
</p>
<Slider
defaultValue={5}
aria-labelledby="quiz time slider"
step={5}
min={5}
max={60}
valueLabelDisplay="on"
marks
className="time-slider"
value={duration}
onChange={handleTimeChange}
/>
<p style={{ color: "#777" }}>Select quiz type: </p>
<Tooltip title="Cannot change quiz type">
<Select
disabled
value={type}
onChange={onTypeChange}
className="type-select"
>
<MenuItem value="public">Public</MenuItem>
<MenuItem value="private">Private</MenuItem>
</Select>
</Tooltip>
<Button
className="login-btn create-btn"
onClick={handleSubmit}
>
Update Quiz
</Button>
</div>
</div>
</Container>
);
}
}
Example #20
Source File: CreateQuiz.js From Quizzie with MIT License | 4 votes |
function CreateQuiz() {
const [quizName, setQuizName] = useState("");
const [quizDate, setQuizDate] = useState(new Date());
const [duration, setDuration] = useState(5);
const [type, setType] = useState("private");
const [loading, setLoading] = useState(false);
const [redirect, setRedirect] = useState(false);
const [redirectEdit, setRedirectEdit] = useState(false);
const [quizId, setQuizId] = useState("");
const [error, setError] = useState(false);
const { executeRecaptcha } = useGoogleReCaptcha();
const onQuizNameChange = (event) => {
setQuizName(event.target.value);
};
const handleDateChange = (date) => {
setQuizDate(date);
};
const handleTimeChange = (e, val) => {
setDuration(val);
};
const onTypeChange = (event) => {
setType(event.target.value);
};
const handleSubmit = async () => {
setLoading(true);
let token = localStorage.getItem("authToken");
let url = "https://quizzie-api.herokuapp.com/quiz/createQuiz";
let captcha = await executeRecaptcha("create_quiz");
let data = {
quizName: quizName,
scheduledFor: quizDate.getTime(),
quizDuration: duration,
quizType: type,
captcha: captcha,
};
try {
await axios
.post(url, data, {
headers: {
"auth-token": token,
},
})
.then((res) => {
setQuizId(res.data.result._id);
setLoading(false);
setRedirectEdit(true);
});
} catch (error) {
console.log(error);
setLoading(false);
}
};
useEffect(() => {
let token = localStorage.getItem("authToken");
if (token === null) {
setLoading(false);
setRedirect(true);
return;
}
}, []);
if (loading) {
return <Loading />;
} else if (redirect) {
return <Redirect to="/dashboard" />;
} else if (redirectEdit) {
return <Redirect to={`/editQuiz/${quizId}`} />;
} else {
return (
<Container className="create-quiz-page">
<div className="create-form">
<Typography variant="h4" className="create-head">
Quiz Details
</Typography>
<div className="create-form-inputs">
<TextInput
variant="outlined"
label="Quiz Name"
value={quizName}
onChange={onQuizNameChange}
name="Quiz Name"
className="form-input"
/>
<MuiPickersUtilsProvider utils={DateFnsUtils}>
<Grid
className="date-time-select"
container
spacing={3}
>
<Grid item xs={12} sm={6}>
<KeyboardDatePicker
disableToolbar
variant="inline"
format="MM/dd/yyyy"
margin="normal"
label="Select Quiz Date"
value={quizDate}
onChange={handleDateChange}
/>
</Grid>
<Grid item xs={12} sm={6}>
<KeyboardTimePicker
ampm={true}
format="hh:mm:ss aa"
views={["hours", "minutes", "seconds"]}
margin="normal"
label="Select Quiz Start Time"
value={quizDate}
onChange={handleDateChange}
keyboardIcon={<AccessAlarm />}
/>
</Grid>
</Grid>
</MuiPickersUtilsProvider>
<p style={{ marginTop: "5%", marginBottom: "5%" }}>
Quiz Time (in minutes):
</p>
<Slider
defaultValue={5}
aria-labelledby="quiz time slider"
step={5}
min={5}
max={60}
valueLabelDisplay="on"
marks
className="time-slider"
value={duration}
onChange={handleTimeChange}
/>
<p>Select quiz type: </p>
<Select
value={type}
onChange={onTypeChange}
className="type-select"
>
<MenuItem value="public">Public</MenuItem>
<MenuItem value="private">Private</MenuItem>
</Select>
<Button
className="login-btn create-btn"
onClick={handleSubmit}
>
Create Quiz
</Button>
<Typography
variant="subtitle1"
className="create-subtitle"
>
NOTE: After creating the quiz, you can add questions
by editing the quiz in YOUR QUIZZES section of the
dashboard.
</Typography>
</div>
</div>
<Snackbar
open={error}
autoHideDuration={5000}
onClose={() => setError(false)}
>
<Alert
variant="filled"
severity="error"
onClose={() => setError(false)}
>
There was a problem. Please try again!
</Alert>
</Snackbar>
</Container>
);
}
}