98 lines
2.4 KiB
JavaScript
98 lines
2.4 KiB
JavaScript
|
import React from 'react';
|
||
|
import './App.css';
|
||
|
import './bootstrap.min.css';
|
||
|
|
||
|
|
||
|
function isCheckedIn(movements) {
|
||
|
if (movements.length === 0) {
|
||
|
return false;
|
||
|
}
|
||
|
const lastMov = movements[movements.length - 1].type;
|
||
|
if (lastMov === "Entrata") {
|
||
|
return true;
|
||
|
} else {
|
||
|
return false;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
class BadgePage extends React.Component {
|
||
|
constructor(props) {
|
||
|
super(props);
|
||
|
this.state = {loggedIn: props.loggedIn, checkedIn: false, loading: false};
|
||
|
}
|
||
|
|
||
|
_isMounted = false
|
||
|
|
||
|
componentDidMount() {
|
||
|
this._isMounted = true;
|
||
|
|
||
|
fetch(this.props.targetUrl + '/movements', {credentials: 'include'})
|
||
|
.then(response => response.json())
|
||
|
.then(data => {if (this._isMounted) {this.setState({
|
||
|
checkedIn: isCheckedIn(data.movements), loggedIn: data.logged_in
|
||
|
})}})
|
||
|
.catch(error => console.log(error));
|
||
|
}
|
||
|
|
||
|
componentWillUnmount() {
|
||
|
this._isMounted = false;
|
||
|
}
|
||
|
|
||
|
handleToggle = (event) => {
|
||
|
this.setState({loading: true})
|
||
|
|
||
|
var path;
|
||
|
if (this.state.checkedIn) {
|
||
|
path = '/checkout';
|
||
|
} else {
|
||
|
path = '/checkin';
|
||
|
}
|
||
|
fetch(this.props.targetUrl + path, {
|
||
|
method: 'POST'
|
||
|
})
|
||
|
.then(response => response.json())
|
||
|
.then(data => this.setState({
|
||
|
checkedIn: data.checked_in,
|
||
|
loggedIn: data.logged_in,
|
||
|
loading: false
|
||
|
}));
|
||
|
}
|
||
|
|
||
|
buttonValue() {
|
||
|
if (this.state.checkedIn) {
|
||
|
return "CHECKOUT";
|
||
|
} else {
|
||
|
return "CHECKIN";
|
||
|
}
|
||
|
}
|
||
|
|
||
|
dynButton() {
|
||
|
const badge = (
|
||
|
<div>
|
||
|
<button type="button" className="btn btn-primary" onClick={this.handleToggle}>{this.buttonValue()}</button>
|
||
|
</div>
|
||
|
);
|
||
|
|
||
|
const loading =
|
||
|
<div className="spinner-border text-primary" role="status">
|
||
|
<span className="sr-only">Loading...</span>
|
||
|
</div>;
|
||
|
|
||
|
if (this.state.loading) {
|
||
|
return loading;
|
||
|
} else {
|
||
|
return badge;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
render() {
|
||
|
if (this.state.loggedIn) {
|
||
|
return this.dynButton();
|
||
|
} else {
|
||
|
return (<div><h2>You have to login first!</h2></div>);
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
export default BadgePage;
|