Fix simplify buy/sell toggle buttons. Run prettier and lint.

This commit is contained in:
Reckless_Satoshi 2022-09-16 09:24:14 -07:00
parent c770d231d1
commit 91e5db2bb9
No known key found for this signature in database
GPG Key ID: 9C4585B561315571
10 changed files with 257 additions and 361 deletions

View File

@ -1,14 +1,12 @@
import React, { Component } from 'react'; import React, { Component } from 'react';
import { withTranslation } from 'react-i18next'; import { withTranslation } from 'react-i18next';
import { import {
Badge,
Tooltip, Tooltip,
Stack, Stack,
Paper, Paper,
Button, Button,
FormControlLabel, ToggleButtonGroup,
Checkbox, ToggleButton,
RadioGroup,
ListItemButton, ListItemButton,
Typography, Typography,
Grid, Grid,
@ -35,7 +33,6 @@ import { apiClient } from '../services/api/index';
// Icons // Icons
import { BarChart, FormatListBulleted, Refresh } from '@mui/icons-material'; import { BarChart, FormatListBulleted, Refresh } from '@mui/icons-material';
import { BuySatsCheckedIcon, BuySatsIcon, SellSatsCheckedIcon, SellSatsIcon } from './Icons';
class BookPage extends Component { class BookPage extends Component {
constructor(props) { constructor(props) {
@ -52,14 +49,13 @@ class BookPage extends Component {
getOrderDetails(type, currency) { getOrderDetails(type, currency) {
this.props.setAppState({ bookLoading: true }); this.props.setAppState({ bookLoading: true });
apiClient.get('/api/book?currency=' + currency + '&type=' + type) apiClient.get('/api/book/').then((data) =>
.then((data) => this.props.setAppState({
this.props.setAppState({ bookNotFound: data.not_found,
bookNotFound: data.not_found, bookLoading: false,
bookLoading: false, bookOrders: data,
bookOrders: data, }),
}), );
);
} }
handleRowClick = (e) => { handleRowClick = (e) => {
@ -152,12 +148,12 @@ class BookPage extends Component {
bookListTableDesktop = () => { bookListTableDesktop = () => {
const { t } = this.props; const { t } = this.props;
return ( return (
<div style={{ height: 422, width: '100%' }}> <div style={{ height: 424, width: '100%' }}>
<DataGrid <DataGrid
localeText={this.dataGridLocaleText()} localeText={this.dataGridLocaleText()}
rows={this.props.bookOrders.filter( rows={this.props.bookOrders.filter(
(order) => (order) =>
(order.type == this.props.type || this.props.type == 2) && (order.type == this.props.type || this.props.type == null) &&
(order.currency == this.props.currency || this.props.currency == 0), (order.currency == this.props.currency || this.props.currency == 0),
)} )}
loading={this.props.bookLoading} loading={this.props.bookLoading}
@ -293,7 +289,7 @@ class BookPage extends Component {
bookListTablePhone = () => { bookListTablePhone = () => {
const { t } = this.props; const { t } = this.props;
return ( return (
<div style={{ height: 422, width: '100%' }}> <div style={{ height: 424, width: '100%' }}>
<DataGrid <DataGrid
localeText={this.dataGridLocaleText()} localeText={this.dataGridLocaleText()}
loading={this.props.bookLoading} loading={this.props.bookLoading}
@ -437,35 +433,14 @@ class BookPage extends Component {
); );
}; };
handleTypeChange = (buyChecked, sellChecked) => { handleTypeChange = (mouseEvent, val) => {
this.props.setAppState({ buyChecked, sellChecked }); this.props.setAppState({ type: val });
if (buyChecked & sellChecked || !buyChecked & !sellChecked) {
var type = 2;
} else if (buyChecked) {
var type = 1;
} else if (sellChecked) {
var type = 0;
}
this.props.setAppState({ type });
};
handleClickBuy = (e) => {
const buyChecked = e.target.checked;
const sellChecked = this.props.sellChecked;
this.handleTypeChange(buyChecked, sellChecked);
}; };
handleClickView = () => { handleClickView = () => {
this.setState({ view: this.state.view == 'depth' ? 'list' : 'depth' }); this.setState({ view: this.state.view == 'depth' ? 'list' : 'depth' });
}; };
handleClickSell = (e) => {
const buyChecked = this.props.buyChecked;
const sellChecked = e.target.checked;
this.handleTypeChange(buyChecked, sellChecked);
};
NoOrdersFound = () => { NoOrdersFound = () => {
const { t } = this.props; const { t } = this.props;
@ -529,14 +504,14 @@ class BookPage extends Component {
<> <>
{/* Desktop */} {/* Desktop */}
<MediaQuery minWidth={930}> <MediaQuery minWidth={930}>
<Paper elevation={0} style={{ width: 925, maxHeight: 500, overflow: 'auto' }}> <Paper elevation={0} style={{ width: 925, maxHeight: 510, overflow: 'auto' }}>
<div style={{ height: 422, width: '100%' }}>{components[0]}</div> <div style={{ height: 424, width: '100%' }}>{components[0]}</div>
</Paper> </Paper>
</MediaQuery> </MediaQuery>
{/* Smartphone */} {/* Smartphone */}
<MediaQuery maxWidth={929}> <MediaQuery maxWidth={929}>
<Paper elevation={0} style={{ width: 395, maxHeight: 450, overflow: 'auto' }}> <Paper elevation={0} style={{ width: 395, maxHeight: 460, overflow: 'auto' }}>
<div style={{ height: 422, width: '100%' }}>{components[1]}</div> <div style={{ height: 424, width: '100%' }}>{components[1]}</div>
</Paper> </Paper>
</MediaQuery> </MediaQuery>
</> </>
@ -576,74 +551,25 @@ class BookPage extends Component {
<Grid item xs={6} align='right'> <Grid item xs={6} align='right'>
<FormControl align='center'> <FormControl align='center'>
<FormHelperText <FormHelperText align='center' sx={{ textAlign: 'center' }}>
align='center'
sx={{ position: 'relative', left: '10px', textAlign: 'center' }}
>
{t('I want to')} {t('I want to')}
</FormHelperText> </FormHelperText>
<RadioGroup row> <div style={{ textAlign: 'center' }}>
<div style={{ position: 'relative', left: '20px' }}> <ToggleButtonGroup
<FormControlLabel sx={{ height: '3.52em' }}
control={ size='large'
<Checkbox exclusive={true}
icon={<BuySatsIcon sx={{ width: '30px', height: '30px' }} color='inherit' />} value={this.props.type}
checkedIcon={ onChange={this.handleTypeChange}
<BuySatsCheckedIcon >
sx={{ width: '30px', height: '30px' }} <ToggleButton value={1} color={'primary'}>
color='primary' {t('Buy')}
/> </ToggleButton>
} <ToggleButton value={0} color={'secondary'}>
/> {t('Sell')}
} </ToggleButton>
label={ </ToggleButtonGroup>
<div style={{ position: 'relative', top: '-13px' }}> </div>
{this.props.buyChecked ? (
<Typography variant='caption' color='primary'>
<b>{t('Buy')}</b>
</Typography>
) : (
<Typography variant='caption' color='text.secondary'>
{t('Buy')}
</Typography>
)}
</div>
}
labelPlacement='bottom'
checked={this.props.buyChecked}
onChange={this.handleClickBuy}
/>
</div>
<FormControlLabel
control={
<Checkbox
icon={<SellSatsIcon sx={{ width: '30px', height: '30px' }} color='inherit' />}
checkedIcon={
<SellSatsCheckedIcon
sx={{ width: '30px', height: '30px' }}
color='secondary'
/>
}
/>
}
label={
<div style={{ position: 'relative', top: '-13px' }}>
{this.props.sellChecked ? (
<Typography variant='caption' color='secondary'>
<b>{t('Sell')}</b>
</Typography>
) : (
<Typography variant='caption' color='text.secondary'>
{t('Sell')}
</Typography>
)}
</div>
}
labelPlacement='bottom'
checked={this.props.sellChecked}
onChange={this.handleClickSell}
/>
</RadioGroup>
</FormControl> </FormControl>
</Grid> </Grid>

View File

@ -72,23 +72,22 @@ class BottomBar extends Component {
getInfo() { getInfo() {
this.setState(null); this.setState(null);
apiClient.get('/api/info/') apiClient.get('/api/info/').then(
.then( (data) =>
(data) => this.setState(data) &
this.setState(data) & this.props.setAppState({
this.props.setAppState({ nickname: data.nickname,
nickname: data.nickname, loading: false,
loading: false, activeOrderId: data.active_order_id ? data.active_order_id : null,
activeOrderId: data.active_order_id ? data.active_order_id : null, lastOrderId: data.last_order_id ? data.last_order_id : null,
lastOrderId: data.last_order_id ? data.last_order_id : null, referralCode: data.referral_code,
referralCode: data.referral_code, tgEnabled: data.tg_enabled,
tgEnabled: data.tg_enabled, tgBotName: data.tg_bot_name,
tgBotName: data.tg_bot_name, tgToken: data.tg_token,
tgToken: data.tg_token, earnedRewards: data.earned_rewards,
earnedRewards: data.earned_rewards, lastDayPremium: data.last_day_nonkyc_btc_premium,
lastDayPremium: data.last_day_nonkyc_btc_premium, }),
}), );
);
} }
handleClickOpenStatsForNerds = () => { handleClickOpenStatsForNerds = () => {
@ -122,9 +121,11 @@ class BottomBar extends Component {
showRewardsSpinner: true, showRewardsSpinner: true,
}); });
apiClient.post('/api/reward/', { apiClient
invoice: rewardInvoice, .post('/api/reward/', {
}).then( invoice: rewardInvoice,
})
.then(
(data) => (data) =>
this.setState({ this.setState({
badInvoice: data.bad_invoice, badInvoice: data.bad_invoice,
@ -140,7 +141,8 @@ class BottomBar extends Component {
}; };
handleSetStealthInvoice = (wantsStealth) => { handleSetStealthInvoice = (wantsStealth) => {
apiClient.put('/api/stealth/', { wantsStealth }) apiClient
.put('/api/stealth/', { wantsStealth })
.then((data) => this.props.setAppState({ stealthInvoices: data.wantsStealth })); .then((data) => this.props.setAppState({ stealthInvoices: data.wantsStealth }));
}; };

View File

@ -63,10 +63,9 @@ const DepthChart: React.FC<DepthChartProps> = ({
useEffect(() => { useEffect(() => {
if (Object.keys(limits).length === 0) { if (Object.keys(limits).length === 0) {
apiClient.get('/api/limits/') apiClient.get('/api/limits/').then((data) => {
.then((data) => { setAppState({ limits: data });
setAppState({ limits: data }); });
});
} }
}, []); }, []);

View File

@ -24,7 +24,7 @@ export default class HomePage extends Component {
avatarLoaded: false, avatarLoaded: false,
buyChecked: false, buyChecked: false,
sellChecked: false, sellChecked: false,
type: 2, type: null,
currency: 0, currency: 0,
bookCurrencyCode: 'ANY', bookCurrencyCode: 'ANY',
bookOrders: new Array(), bookOrders: new Array(),

View File

@ -3,12 +3,7 @@ import { withTranslation } from 'react-i18next';
import { import {
InputAdornment, InputAdornment,
LinearProgress, LinearProgress,
Dialog, ButtonGroup,
IconButton,
DialogActions,
DialogContent,
DialogContentText,
DialogTitle,
Accordion, Accordion,
AccordionDetails, AccordionDetails,
AccordionSummary, AccordionSummary,
@ -47,7 +42,6 @@ import currencyDict from '../../static/assets/currencies.json';
import LockIcon from '@mui/icons-material/Lock'; import LockIcon from '@mui/icons-material/Lock';
import HourglassTopIcon from '@mui/icons-material/HourglassTop'; import HourglassTopIcon from '@mui/icons-material/HourglassTop';
import ExpandMoreIcon from '@mui/icons-material/ExpandMore'; import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
import { BuySatsCheckedIcon, BuySatsIcon, SellSatsCheckedIcon, SellSatsIcon } from './Icons';
import { getCookie } from '../utils/cookies'; import { getCookie } from '../utils/cookies';
import { pn } from '../utils/prettyNumbers'; import { pn } from '../utils/prettyNumbers';
@ -99,28 +93,26 @@ class MakerPage extends Component {
// if currency or type have changed in HomePage state, change in MakerPage state too. // if currency or type have changed in HomePage state, change in MakerPage state too.
this.setState({ this.setState({
currency: !this.props.currency === 0 ? this.props.currency : this.state.currency, currency: !this.props.currency === 0 ? this.props.currency : this.state.currency,
type: !this.props.type == 2 ? (this.props.type == 1 ? 0 : 1) : this.state.type,
}); });
} }
getLimits() { getLimits() {
this.setState({ loadingLimits: true }); this.setState({ loadingLimits: true });
apiClient.get('/api/limits/') apiClient.get('/api/limits/').then((data) =>
.then((data) => this.setState({
this.setState({ limits: data,
limits: data, loadingLimits: false,
loadingLimits: false, minAmount: this.state.amount
minAmount: this.state.amount ? parseFloat((this.state.amount / 2).toPrecision(2))
? parseFloat((this.state.amount / 2).toPrecision(2)) : parseFloat(Number(data[this.state.currency].max_amount * 0.25).toPrecision(2)),
: parseFloat(Number(data[this.state.currency].max_amount * 0.25).toPrecision(2)), maxAmount: this.state.amount
maxAmount: this.state.amount ? this.state.amount
? this.state.amount : parseFloat(Number(data[this.state.currency].max_amount * 0.75).toPrecision(2)),
: parseFloat(Number(data[this.state.currency].max_amount * 0.75).toPrecision(2)), minTradeSats: data['1000'].min_amount * 100000000,
minTradeSats: data['1000'].min_amount * 100000000, maxTradeSats: data['1000'].max_amount * 100000000,
maxTradeSats: data['1000'].max_amount * 100000000, maxBondlessSats: data['1000'].max_bondless_amount * 100000000,
maxBondlessSats: data['1000'].max_bondless_amount * 100000000, }),
}), );
);
} }
recalcBounds = () => { recalcBounds = () => {
@ -145,19 +137,6 @@ class MakerPage extends Component {
}; };
} }
handleTypeChange = (e) => {
this.setState({
type: e.target.value,
});
// Share state with HomePage and OrderPage
this.props.setAppState({
// maker and book page type values 0:1 are reversed
type: e.target.value == 1 ? 0 : 1,
buyChecked: e.target.value == 0,
sellChecked: e.target.value == 1,
});
};
handleCurrencyChange = (e) => { handleCurrencyChange = (e) => {
const currencyCode = this.getCurrencyCode(e.target.value); const currencyCode = this.getCurrencyCode(e.target.value);
this.setState({ this.setState({
@ -304,7 +283,7 @@ class MakerPage extends Component {
handleCreateOfferButtonPressed = () => { handleCreateOfferButtonPressed = () => {
this.state.amount == null ? this.setState({ amount: 0 }) : null; this.state.amount == null ? this.setState({ amount: 0 }) : null;
const body = { const body = {
type: this.state.type, type: this.props.type == 0 ? 1 : 0,
currency: this.state.currency, currency: this.state.currency,
amount: this.state.has_range ? null : this.state.amount, amount: this.state.has_range ? null : this.state.amount,
has_range: this.state.enableAmountRange, has_range: this.state.enableAmountRange,
@ -320,7 +299,8 @@ class MakerPage extends Component {
bond_size: this.state.bondSize, bond_size: this.state.bondSize,
bondless_taker: this.state.allowBondless, bondless_taker: this.state.allowBondless,
}; };
apiClient.post('/api/make/', body) apiClient
.post('/api/make/', body)
.then( .then(
(data) => (data) =>
this.setState({ badRequest: data.bad_request }) & this.setState({ badRequest: data.bad_request }) &
@ -356,79 +336,46 @@ class MakerPage extends Component {
return ( return (
<Paper elevation={12} style={{ padding: 8, width: `${260 / 16}em`, align: 'center' }}> <Paper elevation={12} style={{ padding: 8, width: `${260 / 16}em`, align: 'center' }}>
<Grid item xs={12} align='center'> <Grid item xs={12} align='center'>
<div style={{ position: 'relative' }}> <FormControl component='fieldset'>
<FormControl component='fieldset'> <FormHelperText sx={{ textAlign: 'center' }}>
<FormHelperText sx={{ textAlign: 'center' }}> {t('Buy or Sell Bitcoin?')}
{t('Buy or Sell Bitcoin?')} </FormHelperText>
</FormHelperText> <div style={{ textAlign: 'center' }}>
<ButtonGroup>
<RadioGroup row value={this.state.type} onChange={this.handleTypeChange}> <Button
<FormControlLabel size='large'
value={0} variant='contained'
control={ onClick={() =>
<Radio this.props.setAppState({
icon={ type: 1,
<BuySatsIcon })
sx={{ width: `${30 / 24}em`, height: `${30 / 24}em` }}
color='text.secondary'
/>
}
checkedIcon={
<BuySatsCheckedIcon
sx={{ width: `${30 / 24}em`, height: `${30 / 24}em` }}
color='primary'
/>
}
/>
} }
label={ disableElevation={this.props.type == 1}
this.state.type == 0 ? ( color={this.props.type == 1 ? 'primary' : 'inherit'}
<Typography color='primary'> >
<b>{t('Buy')}</b> {t('Buy')}
</Typography> </Button>
) : ( <Button
<Typography color='text.secondary'>{t('Buy')}</Typography> size='large'
) variant='contained'
onClick={() =>
this.props.setAppState({
type: 0,
})
} }
labelPlacement='end' disableElevation={this.props.type == 0}
/> color={this.props.type == 0 ? 'secondary' : 'inherit'}
<FormControlLabel >
value={1} {t('Sell')}
control={ </Button>
<Radio </ButtonGroup>
color='secondary' </div>
icon={ </FormControl>
<SellSatsIcon <div style={{ height: '1em' }} />
sx={{ width: `${30 / 24}em`, height: `${30 / 24}em` }}
color='text.secondary'
/>
}
checkedIcon={
<SellSatsCheckedIcon
sx={{ width: `${30 / 24}em`, height: `${30 / 24}em` }}
color='secondary'
/>
}
/>
}
label={
this.state.type == 1 ? (
<Typography color='secondary'>
<b>{t('Sell')}</b>
</Typography>
) : (
<Typography color='text.secondary'>{t('Sell')}</Typography>
)
}
labelPlacement='end'
/>
</RadioGroup>
</FormControl>
</div>
</Grid> </Grid>
<Grid alignItems='stretch' style={{ display: 'flex' }}> <Grid alignItems='stretch' style={{ display: 'flex' }}>
<div style={{}}> <div>
<Tooltip <Tooltip
placement='top' placement='top'
enterTouchDelay={500} enterTouchDelay={500}
@ -501,11 +448,12 @@ class MakerPage extends Component {
listHeaderText={t('You can add new methods')} listHeaderText={t('You can add new methods')}
addNewButtonText={t('Add New')} addNewButtonText={t('Add New')}
/> />
<div style={{ height: '0.3em' }} />
</Grid> </Grid>
<Grid item xs={12} align='center'> <Grid item xs={12} align='center'>
<FormControl component='fieldset'> <FormControl component='fieldset'>
<FormHelperText sx={{ textAlign: 'center' }}> <FormHelperText sx={{ textAlign: 'center', position: 'relative', top: '0.5em' }}>
{t('Choose a Pricing Method')} {t('Choose a Pricing Method')}
</FormHelperText> </FormHelperText>
<RadioGroup row defaultValue='relative'> <RadioGroup row defaultValue='relative'>
@ -916,7 +864,7 @@ class MakerPage extends Component {
control={ control={
<Checkbox <Checkbox
disabled disabled
// disabled={this.state.type==0 || this.state.type === null} // disabled={this.props.type==0 || this.props.type === null}
color='secondary' color='secondary'
checked={this.state.allowBondless} checked={this.state.allowBondless}
onChange={() => this.setState({ allowBondless: !this.state.allowBondless })} onChange={() => this.setState({ allowBondless: !this.state.allowBondless })}
@ -989,7 +937,7 @@ class MakerPage extends Component {
<Grid item xs={12} align='center'> <Grid item xs={12} align='center'>
{/* conditions to disable the make button */} {/* conditions to disable the make button */}
{this.state.type == null || {this.props.type == null ||
(this.state.amount == null) & (this.state.amount == null) &
(this.state.enableAmountRange == false || this.state.loadingLimits) || (this.state.enableAmountRange == false || this.state.loadingLimits) ||
this.state.enableAmountRange & (this.minAmountError() || this.maxAmountError()) || this.state.enableAmountRange & (this.minAmountError() || this.maxAmountError()) ||
@ -1028,9 +976,9 @@ class MakerPage extends Component {
)} )}
<Typography component='h2' variant='subtitle2'> <Typography component='h2' variant='subtitle2'>
<div align='center'> <div align='center'>
{this.state.type == null {this.props.type == null
? t('Create an order for ') ? t('Create an order for ')
: this.state.type == 0 : this.props.type == 1
? t('Create a BTC buy order for ') ? t('Create a BTC buy order for ')
: t('Create a BTC sell order for ')} : t('Create a BTC sell order for ')}
{this.state.enableAmountRange & (this.state.minAmount != null) {this.state.enableAmountRange & (this.state.minAmount != null)

View File

@ -123,8 +123,7 @@ class OrderPage extends Component {
getOrderDetails = (id) => { getOrderDetails = (id) => {
this.setState({ orderId: id }); this.setState({ orderId: id });
apiClient.get('/api/order/?order_id=' + id) apiClient.get('/api/order/?order_id=' + id).then(this.orderDetailsReceived);
.then(this.orderDetailsReceived);
}; };
orderDetailsReceived = (data) => { orderDetailsReceived = (data) => {
@ -185,10 +184,12 @@ class OrderPage extends Component {
}; };
sendWeblnInvoice = (invoice) => { sendWeblnInvoice = (invoice) => {
apiClient.post('/api/order/?order_id=' + this.state.orderId, { apiClient
action: 'update_invoice', .post('/api/order/?order_id=' + this.state.orderId, {
invoice, action: 'update_invoice',
}).then((data) => this.completeSetState(data)); invoice,
})
.then((data) => this.completeSetState(data));
}; };
// Countdown Renderer callback with condition // Countdown Renderer callback with condition
@ -422,10 +423,11 @@ class OrderPage extends Component {
takeOrder = () => { takeOrder = () => {
this.setState({ loading: true }); this.setState({ loading: true });
apiClient.post('/api/order/?order_id=' + this.state.orderId, { apiClient
action: 'take', .post('/api/order/?order_id=' + this.state.orderId, {
amount: this.state.takeAmount, action: 'take',
}) amount: this.state.takeAmount,
})
.then((data) => this.handleWebln(data) & this.completeSetState(data)); .then((data) => this.handleWebln(data) & this.completeSetState(data));
}; };
@ -441,9 +443,11 @@ class OrderPage extends Component {
handleClickConfirmCancelButton = () => { handleClickConfirmCancelButton = () => {
this.setState({ loading: true }); this.setState({ loading: true });
apiClient.post('/api/order/?order_id=' + this.state.orderId, { apiClient
action: 'cancel', .post('/api/order/?order_id=' + this.state.orderId, {
}).then(() => this.getOrderDetails(this.state.orderId) & this.setState({ status: 4 })); action: 'cancel',
})
.then(() => this.getOrderDetails(this.state.orderId) & this.setState({ status: 4 }));
this.handleClickCloseConfirmCancelDialog(); this.handleClickCloseConfirmCancelDialog();
}; };
@ -541,9 +545,11 @@ class OrderPage extends Component {
}; };
handleClickConfirmCollaborativeCancelButton = () => { handleClickConfirmCollaborativeCancelButton = () => {
apiClient.post('/api/order/?order_id=' + this.state.orderId, { apiClient
action: 'cancel', .post('/api/order/?order_id=' + this.state.orderId, {
}).then(() => this.getOrderDetails(this.state.orderId) & this.setState({ status: 4 })); action: 'cancel',
})
.then(() => this.getOrderDetails(this.state.orderId) & this.setState({ status: 4 }));
this.handleClickCloseCollaborativeCancelDialog(); this.handleClickCloseCollaborativeCancelDialog();
}; };

View File

@ -133,9 +133,11 @@ class TradeBox extends Component {
}; };
handleClickAgreeDisputeButton = () => { handleClickAgreeDisputeButton = () => {
apiClient.post('/api/order/?order_id=' + this.props.data.id, { apiClient
action: 'dispute', .post('/api/order/?order_id=' + this.props.data.id, {
}).then((data) => this.props.completeSetState(data)); action: 'dispute',
})
.then((data) => this.props.completeSetState(data));
this.handleClickCloseConfirmDispute(); this.handleClickCloseConfirmDispute();
}; };
@ -480,9 +482,11 @@ class TradeBox extends Component {
handleClickPauseOrder = () => { handleClickPauseOrder = () => {
this.props.completeSetState({ pauseLoading: true }); this.props.completeSetState({ pauseLoading: true });
apiClient.post('/api/order/?order_id=' + this.props.data.id, { apiClient
action: 'pause', .post('/api/order/?order_id=' + this.props.data.id, {
}).then((data) => this.props.getOrderDetails(data.id)); action: 'pause',
})
.then((data) => this.props.getOrderDetails(data.id));
}; };
showMakerWait = () => { showMakerWait = () => {
@ -626,10 +630,12 @@ class TradeBox extends Component {
handleClickSubmitInvoiceButton = () => { handleClickSubmitInvoiceButton = () => {
this.setState({ badInvoice: false }); this.setState({ badInvoice: false });
apiClient.post('/api/order/?order_id=' + this.props.data.id, { apiClient
action: 'update_invoice', .post('/api/order/?order_id=' + this.props.data.id, {
invoice: this.state.invoice, action: 'update_invoice',
}).then( invoice: this.state.invoice,
})
.then(
(data) => (data) =>
this.setState({ badInvoice: data.bad_invoice }) & this.props.completeSetState(data), this.setState({ badInvoice: data.bad_invoice }) & this.props.completeSetState(data),
); );
@ -656,11 +662,13 @@ class TradeBox extends Component {
handleClickSubmitAddressButton = () => { handleClickSubmitAddressButton = () => {
this.setState({ badInvoice: false }); this.setState({ badInvoice: false });
apiClient.post('/api/order/?order_id=' + this.props.data.id, { apiClient
action: 'update_address', .post('/api/order/?order_id=' + this.props.data.id, {
address: this.state.address, action: 'update_address',
mining_fee_rate: Math.max(1, this.state.miningFee), address: this.state.address,
}).then( mining_fee_rate: Math.max(1, this.state.miningFee),
})
.then(
(data) => (data) =>
this.setState({ badAddress: data.bad_address }) & this.props.completeSetState(data), this.setState({ badAddress: data.bad_address }) & this.props.completeSetState(data),
); );
@ -676,13 +684,15 @@ class TradeBox extends Component {
handleClickSubmitStatementButton = () => { handleClickSubmitStatementButton = () => {
this.setState({ badInvoice: false }); this.setState({ badInvoice: false });
apiClient.post('/api/order/?order_id=' + this.props.data.id, { apiClient
action: 'submit_statement', .post('/api/order/?order_id=' + this.props.data.id, {
statement: this.state.statement, action: 'submit_statement',
}).then( statement: this.state.statement,
(data) => })
this.setState({ badStatement: data.bad_statement }) & this.props.completeSetState(data), .then(
); (data) =>
this.setState({ badStatement: data.bad_statement }) & this.props.completeSetState(data),
);
}; };
handleScan = (data) => { handleScan = (data) => {
@ -1179,16 +1189,20 @@ class TradeBox extends Component {
} }
handleClickConfirmButton = () => { handleClickConfirmButton = () => {
apiClient.post('/api/order/?order_id=' + this.props.data.id, { apiClient
action: 'confirm', .post('/api/order/?order_id=' + this.props.data.id, {
}).then((data) => this.props.completeSetState(data)); action: 'confirm',
})
.then((data) => this.props.completeSetState(data));
}; };
handleRatingUserChange = (e) => { handleRatingUserChange = (e) => {
apiClient.post('/api/order/?order_id=' + this.props.data.id, { apiClient
action: 'rate_user', .post('/api/order/?order_id=' + this.props.data.id, {
rating: e.target.value, action: 'rate_user',
}).then((data) => this.props.completeSetState(data)); rating: e.target.value,
})
.then((data) => this.props.completeSetState(data));
}; };
handleRatingRobosatsChange = (e) => { handleRatingRobosatsChange = (e) => {
@ -1197,10 +1211,12 @@ class TradeBox extends Component {
} }
this.setState({ rating_platform: e.target.value }); this.setState({ rating_platform: e.target.value });
apiClient.post('/api/order/?order_id=' + this.props.data.id, { apiClient
action: 'rate_platform', .post('/api/order/?order_id=' + this.props.data.id, {
rating: e.target.value, action: 'rate_platform',
}).then((data) => this.props.completeSetState(data)); rating: e.target.value,
})
.then((data) => this.props.completeSetState(data));
}; };
showFiatSentButton() { showFiatSentButton() {
@ -1316,7 +1332,8 @@ class TradeBox extends Component {
bond_size: this.props.data.bond_size, bond_size: this.props.data.bond_size,
bondless_taker: this.props.data.bondless_taker, bondless_taker: this.props.data.bondless_taker,
}; };
apiClient.post('/api/make/', body) apiClient
.post('/api/make/', body)
.then( .then(
(data) => (data) =>
this.setState({ badRequest: data.bad_request }) & this.setState({ badRequest: data.bad_request }) &

View File

@ -77,51 +77,49 @@ class UserGenPage extends Component {
}); });
requestBody.then((body) => requestBody.then((body) =>
apiClient.post('/api/user/', body) apiClient.post('/api/user/', body).then((data) => {
.then((data) => { this.setState({
console.log(data) & nickname: data.nickname,
this.setState({ bit_entropy: data.token_bits_entropy,
nickname: data.nickname, avatarUrl: '/static/assets/avatars/' + data.nickname + '.png',
bit_entropy: data.token_bits_entropy, shannon_entropy: data.token_shannon_entropy,
avatarUrl: '/static/assets/avatars/' + data.nickname + '.png', bad_request: data.bad_request,
shannon_entropy: data.token_shannon_entropy, found: data.found,
bad_request: data.bad_request, loadingRobot: false,
found: data.found, stealthInvoices: data.wants_stealth,
loadingRobot: false, }) &
stealthInvoices: data.wants_stealth, // Add nick and token to App state (token only if not a bad request)
}) & (data.bad_request
// Add nick and token to App state (token only if not a bad request) ? this.props.setAppState({
(data.bad_request nickname: data.nickname,
? this.props.setAppState({ avatarLoaded: false,
nickname: data.nickname, activeOrderId: data.active_order_id ? data.active_order_id : null,
avatarLoaded: false, referralCode: data.referral_code,
activeOrderId: data.active_order_id ? data.active_order_id : null, earnedRewards: data.earned_rewards,
referralCode: data.referral_code, lastOrderId: data.last_order_id ? data.last_order_id : null,
earnedRewards: data.earned_rewards, stealthInvoices: data.wants_stealth,
lastOrderId: data.last_order_id ? data.last_order_id : null, })
stealthInvoices: data.wants_stealth, : this.props.setAppState({
}) nickname: data.nickname,
: this.props.setAppState({ token,
nickname: data.nickname, avatarLoaded: false,
token, activeOrderId: data.active_order_id ? data.active_order_id : null,
avatarLoaded: false, lastOrderId: data.last_order_id ? data.last_order_id : null,
activeOrderId: data.active_order_id ? data.active_order_id : null, referralCode: data.referral_code,
lastOrderId: data.last_order_id ? data.last_order_id : null, earnedRewards: data.earned_rewards,
referralCode: data.referral_code, stealthInvoices: data.wants_stealth,
earnedRewards: data.earned_rewards, }) &
stealthInvoices: data.wants_stealth, writeCookie('robot_token', token) &
}) & writeCookie('pub_key', data.public_key.split('\n').join('\\')) &
writeCookie('robot_token', token) & writeCookie('enc_priv_key', data.encrypted_private_key.split('\n').join('\\'))) &
writeCookie('pub_key', data.public_key.split('\n').join('\\')) & // If the robot has been found (recovered) we assume the token is backed up
writeCookie('enc_priv_key', data.encrypted_private_key.split('\n').join('\\'))) & (data.found ? this.props.setAppState({ copiedToken: true }) : null);
// If the robot has been found (recovered) we assume the token is backed up }),
(data.found ? this.props.setAppState({ copiedToken: true }) : null);
}),
); );
}; };
delGeneratedUser() { delGeneratedUser() {
apiClient.delete('/api/user') apiClient.delete('/api/user');
deleteCookie('sessionid'); deleteCookie('sessionid');
deleteCookie('robot_token'); deleteCookie('robot_token');

View File

@ -1,40 +1,40 @@
import { ApiClient } from "../api" import { ApiClient } from '../api';
import { getCookie } from '../../../utils/cookies'; import { getCookie } from '../../../utils/cookies';
class ApiWebClient implements ApiClient { class ApiWebClient implements ApiClient {
private getHeaders: () => HeadersInit = () => { private readonly getHeaders: () => HeadersInit = () => {
return { 'Content-Type': 'application/json', 'X-CSRFToken': getCookie('csrftoken') || "" } return { 'Content-Type': 'application/json', 'X-CSRFToken': getCookie('csrftoken') || '' };
} };
public post: (path: string, body: object) => Promise<object> = (path, body) => { public post: (path: string, body: object) => Promise<object> = async (path, body) => {
const requestOptions = { const requestOptions = {
method: 'POST', method: 'POST',
headers: this.getHeaders(), headers: this.getHeaders(),
body: JSON.stringify(body), body: JSON.stringify(body),
}; };
return fetch(path, requestOptions).then((response) => response.json()) return await fetch(path, requestOptions).then(async (response) => await response.json());
} };
public put: (path: string, body: object) => Promise<object> = (path, body) => { public put: (path: string, body: object) => Promise<object> = async (path, body) => {
const requestOptions = { const requestOptions = {
method: 'PUT', method: 'PUT',
headers: this.getHeaders(), headers: this.getHeaders(),
body: JSON.stringify(body), body: JSON.stringify(body),
}; };
return fetch(path, requestOptions).then((response) => response.json()) return await fetch(path, requestOptions).then(async (response) => await response.json());
} };
public delete: (path: string) => Promise<object> = (path) => { public delete: (path: string) => Promise<object> = async (path) => {
const requestOptions = { const requestOptions = {
method: 'DELETE', method: 'DELETE',
headers: this.getHeaders(), headers: this.getHeaders(),
}; };
return fetch(path, requestOptions).then((response) => response.json()) return await fetch(path, requestOptions).then(async (response) => await response.json());
} };
public get: (path: string) => Promise<object> = (path) => { public get: (path: string) => Promise<object> = async (path) => {
return fetch(path).then((response) => response.json()) return await fetch(path).then(async (response) => await response.json());
} };
} }
export default ApiWebClient export default ApiWebClient;

View File

@ -1,10 +1,10 @@
import ApiWebClient from './ApiWebClient' import ApiWebClient from './ApiWebClient';
export interface ApiClient { export interface ApiClient {
post: (path: string, body: object) => Promise<object> post: (path: string, body: object) => Promise<object>;
put: (path: string, body: object) => Promise<object> put: (path: string, body: object) => Promise<object>;
get: (path: string) => Promise<object> get: (path: string) => Promise<object>;
delete: (path: string) => Promise<object> delete: (path: string) => Promise<object>;
} }
export const apiClient: ApiClient = new ApiWebClient() export const apiClient: ApiClient = new ApiWebClient();