Newer
Older
import React from "react";
import { Redirect } from "react-router-dom";
import {
Container,
Form,
Col,
Row,
Button,
Alert,
Spinner,
InputGroup,
} from "react-bootstrap";
import AuthContext from "./AuthContext";
constructor(props) {
super(props);
this.state = {
numInvalid: false,
amount: 0,
comment: "",
transactionId: null,
isLoading: false,
badAuth: false,
error: null,
};
}
setNum(numStr) {
const num = parseInt(numStr);
const member = this.state.members.find((p) => p.num === num);
let name = "";
if (member) {
name = member.name;
this.setState({
num: numStr,
name: name,
numInvalid: name === undefined,
});
}
setName(member) {
this.setState({
num: member.num,
name: member.name,
numInvalid: false,
});
}
if (!this.state.member) {
this.setState({ error: "Falta seleccionar una socia" });
return;
}
this.setState({ isLoading: true, error: null });
const body = JSON.stringify({
member: parseInt(this.state.num),
comment: this.state.comment,
amount: parseInt(this.state.amount) * 100,
});
fetch("/api/topup", {
headers: { "x-authentication": this.context.token },
method: "POST",
body,
})
.then((response) => {
if (!response.ok) {
throw new Error(
response.status.toString() + " " + response.statusText
);
return response.json();
})
.then((transaction) => {
this.setState({ transactionId: transaction.ID, isLoading: false });
})
.catch((error) => {
this.setState({ isLoading: false, error: error.message });
});
}
render() {
if (this.state.isLoading) {
return <Spinner animation="border" />;
}
let alert;
if (this.state.error != null) {
alert = (
<Alert variant="danger">
Ha ocurrido un error enviando la compra: {this.state.error}
</Alert>
);
if (this.state.transactionId !== null) {
return <Redirect to={"/transaction/" + this.state.transactionId} />;
}
return (
<Container>
{alert}
<MemberPicker
member={this.state.member}
onChange={(member) => this.setState({ member })}
/>
<Form onSubmit={(e) => this.send(e)}>
<Form.Group as={Row}>
<Form.Label as="legend" column sm={2}>
Recarga
</Form.Label>
<Col sm={10}>
<InputGroup>
type="number"
placeholder="euros"
value={this.state.amount}
onChange={(e) => this.setState({ amount: e.target.value })}
<InputGroup.Append>
<InputGroup.Text>.00 €</InputGroup.Text>
</InputGroup.Append>
</InputGroup>
</Col>
</Form.Group>
<Form.Group as={Row}>
<Form.Label as="legend" column sm={2}>
Comentario
</Form.Label>
<Col sm={10}>
<Form.Control
placeholder="..."
value={this.state.comment}
onChange={(e) => this.setState({ comment: e.target.value })}
/>
</Col>
</Form.Group>
<Form.Group as={Row}>
<Col sm={{ span: 10, offset: 2 }}>
<Button type="submit">Recarga</Button>
</Col>
</Form.Group>
</Form>
</Container>