Skip to content

Commit

Permalink
Merge pull request #1407 from RoboSats/refactor-order-model
Browse files Browse the repository at this point in the history
Refactor Order/Slot models
  • Loading branch information
KoalaSat authored Sep 10, 2024
2 parents 17c9662 + 06fc2e8 commit a390254
Show file tree
Hide file tree
Showing 38 changed files with 788 additions and 956 deletions.
8 changes: 4 additions & 4 deletions frontend/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,17 +21,17 @@ const App = (): JSX.Element => {
<Suspense fallback='loading'>
<I18nextProvider i18n={i18n}>
<AppContextProvider>
<GarageContextProvider>
<FederationContextProvider>
<FederationContextProvider>
<GarageContextProvider>
<CssBaseline />
{window.NativeRobosats === undefined && window.RobosatsClient === undefined ? (
<HostAlert />
) : (
<TorConnectionBadge />
)}
<Main />
</FederationContextProvider>
</GarageContextProvider>
</GarageContextProvider>
</FederationContextProvider>
</AppContextProvider>
</I18nextProvider>
</Suspense>
Expand Down
7 changes: 0 additions & 7 deletions frontend/src/basic/BookPage/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,10 @@ import BookTable from '../../components/BookTable';
import { BarChart, FormatListBulleted, Map } from '@mui/icons-material';
import { AppContext, type UseAppStoreType } from '../../contexts/AppContext';
import MapChart from '../../components/Charts/MapChart';
import { FederationContext, type UseFederationStoreType } from '../../contexts/FederationContext';
import { GarageContext, type UseGarageStoreType } from '../../contexts/GarageContext';

const BookPage = (): JSX.Element => {
const { windowSize } = useContext<UseAppStoreType>(AppContext);
const { setDelay, setCurrentOrderId } = useContext<UseFederationStoreType>(FederationContext);
const { garage } = useContext<UseGarageStoreType>(GarageContext);
const { t } = useTranslation();
const navigate = useNavigate();
Expand All @@ -32,8 +30,6 @@ const BookPage = (): JSX.Element => {

const onOrderClicked = function (id: number, shortAlias: string): void {
if (garage.getSlot()?.hashId) {
setDelay(10000);
setCurrentOrderId({ id, shortAlias });
navigate(`/order/${shortAlias}/${id}`);
} else {
setOpenNoRobot(true);
Expand Down Expand Up @@ -102,9 +98,6 @@ const BookPage = (): JSX.Element => {
>
<Box sx={{ maxWidth: '18em', padding: '0.5em' }}>
<MakerForm
onOrderCreated={(id) => {
navigate(`/order/${id}`);
}}
onClickGenerateRobot={() => {
navigate('/robot');
}}
Expand Down
9 changes: 1 addition & 8 deletions frontend/src/basic/MakerPage/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,7 @@ import { GarageContext, type UseGarageStoreType } from '../../contexts/GarageCon

const MakerPage = (): JSX.Element => {
const { fav, windowSize, navbarHeight } = useContext<UseAppStoreType>(AppContext);
const { federation, setDelay, setCurrentOrderId } =
useContext<UseFederationStoreType>(FederationContext);
const { federation } = useContext<UseFederationStoreType>(FederationContext);
const { garage, maker } = useContext<UseGarageStoreType>(GarageContext);
const { t } = useTranslation();
const navigate = useNavigate();
Expand Down Expand Up @@ -54,8 +53,6 @@ const MakerPage = (): JSX.Element => {

const onOrderClicked = function (id: number, shortAlias: string): void {
if (garage.getSlot()?.hashId) {
setDelay(10000);
setCurrentOrderId({ id, shortAlias });
navigate(`/order/${shortAlias}/${id}`);
} else {
setOpenNoRobot(true);
Expand Down Expand Up @@ -105,10 +102,6 @@ const MakerPage = (): JSX.Element => {
}}
>
<MakerForm
onOrderCreated={(shortAlias, id) => {
setCurrentOrderId({ id, shortAlias });
navigate(`/order/${shortAlias}/${id}`);
}}
disableRequest={matches.length > 0 && !showMatches}
collapseAll={showMatches}
onSubmit={() => {
Expand Down
20 changes: 7 additions & 13 deletions frontend/src/basic/NavBar/NavBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,13 @@ import {
import RobotAvatar from '../../components/RobotAvatar';
import { AppContext, type UseAppStoreType, closeAll } from '../../contexts/AppContext';
import { GarageContext, type UseGarageStoreType } from '../../contexts/GarageContext';
import { FederationContext, type UseFederationStoreType } from '../../contexts/FederationContext';

const NavBar = (): JSX.Element => {
const theme = useTheme();
const { t } = useTranslation();
const { page, setPage, settings, setSlideDirection, open, setOpen, windowSize, navbarHeight } =
useContext<UseAppStoreType>(AppContext);
const { garage, robotUpdatedAt } = useContext<UseGarageStoreType>(GarageContext);
const { setCurrentOrderId } = useContext<UseFederationStoreType>(FederationContext);
const { garage, slotUpdatedAt } = useContext<UseGarageStoreType>(GarageContext);

const navigate = useNavigate();
const location = useLocation();
Expand All @@ -50,7 +48,7 @@ const NavBar = (): JSX.Element => {

useEffect(() => {
// re-render on orde rand robot updated at for latest orderId in tab
}, [robotUpdatedAt]);
}, [slotUpdatedAt]);

useEffect(() => {
// change tab (page) into the current route
Expand All @@ -77,14 +75,10 @@ const NavBar = (): JSX.Element => {
const slot = garage.getSlot();
handleSlideDirection(page, newPage);
setPage(newPage);
const shortAlias = String(slot?.activeShortAlias);
const activeOrderId = slot?.getRobot(slot?.activeShortAlias ?? '')?.activeOrderId;
const lastOrderId = slot?.getRobot(slot?.lastShortAlias ?? '')?.lastOrderId;
const param =
newPage === 'order' ? `${shortAlias}/${String(activeOrderId ?? lastOrderId)}` : '';
if (newPage === 'order') {
setCurrentOrderId({ id: activeOrderId ?? lastOrderId, shortAlias });
}

const shortAlias = slot?.activeOrder?.shortAlias;
const orderId = slot?.activeOrder?.id;
const param = newPage === 'order' ? `${String(shortAlias)}/${String(orderId)}` : '';
setTimeout(() => {
navigate(`/${newPage}/${param}`);
}, theme.transitions.duration.leavingScreen * 3);
Expand Down Expand Up @@ -162,7 +156,7 @@ const NavBar = (): JSX.Element => {
sx={tabSx}
label={smallBar ? undefined : t('Order')}
value='order'
disabled={!slot?.getRobot()?.activeOrderId}
disabled={!slot?.activeOrder}
icon={<Assignment />}
iconPosition='start'
/>
Expand Down
86 changes: 42 additions & 44 deletions frontend/src/basic/OrderPage/index.tsx
Original file line number Diff line number Diff line change
@@ -1,65 +1,64 @@
import React, { useContext, useEffect, useState } from 'react';
import React, { useContext, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Tab, Tabs, Paper, CircularProgress, Grid, Typography, Box } from '@mui/material';
import { useNavigate, useParams } from 'react-router-dom';

import TradeBox from '../../components/TradeBox';
import OrderDetails from '../../components/OrderDetails';

import { AppContext, closeAll, type UseAppStoreType } from '../../contexts/AppContext';
import { AppContext, type UseAppStoreType } from '../../contexts/AppContext';
import { FederationContext, type UseFederationStoreType } from '../../contexts/FederationContext';
import { GarageContext, type UseGarageStoreType } from '../../contexts/GarageContext';
import { WarningDialog } from '../../components/Dialogs';
import { Order, type Slot } from '../../models';
import { type UseGarageStoreType, GarageContext } from '../../contexts/GarageContext';

const OrderPage = (): JSX.Element => {
const {
windowSize,
open,
setOpen,
acknowledgedWarning,
setAcknowledgedWarning,
settings,
navbarHeight,
hostUrl,
origin,
} = useContext<UseAppStoreType>(AppContext);
const { federation, currentOrder, currentOrderId, setCurrentOrderId } =
useContext<UseFederationStoreType>(FederationContext);
const { badOrder } = useContext<UseGarageStoreType>(GarageContext);
const { windowSize, setOpen, acknowledgedWarning, setAcknowledgedWarning, navbarHeight } =
useContext<UseAppStoreType>(AppContext);
const { federation } = useContext<UseFederationStoreType>(FederationContext);
const { garage } = useContext<UseGarageStoreType>(GarageContext);
const { t } = useTranslation();
const navigate = useNavigate();
const params = useParams();
const paramsRef = useRef(params);

const doublePageWidth: number = 50;
const maxHeight: number = (windowSize?.height - navbarHeight) * 0.85 - 3;

const [tab, setTab] = useState<'order' | 'contract'>('contract');
const [baseUrl, setBaseUrl] = useState<string>(hostUrl);
const [currentOrder, setCurrentOrder] = useState<Order | null>(null);

useEffect(() => {
paramsRef.current = params;
const shortAlias = params.shortAlias;
const coordinator = federation.getCoordinator(shortAlias ?? '');
if (coordinator) {
const endpoint = coordinator?.getEndpoint(
settings.network,
origin,
settings.selfhostedClient,
hostUrl,
);
const orderId = Number(params.orderId);
const slot = garage.getSlot();
if (slot?.token) {
let order = new Order({ id: orderId, shortAlias });
if (slot.activeOrder?.id === orderId && slot.activeOrder?.shortAlias === shortAlias) {
order = slot.activeOrder;
} else if (slot.lastOrder?.id === orderId && slot.lastOrder?.shortAlias === shortAlias) {
order = slot.lastOrder;
}
void order.fecth(federation, slot).then((updatedOrder) => {
updateSlotFromOrder(updatedOrder, slot);
});
}

if (endpoint) setBaseUrl(`${endpoint?.url}${endpoint?.basePath}`);
return () => {
setCurrentOrder(null);
};
}, [params.orderId]);

const orderId = Number(params.orderId);
if (
orderId &&
currentOrderId.id !== orderId &&
currentOrderId.shortAlias !== shortAlias &&
shortAlias
)
setCurrentOrderId({ id: orderId, shortAlias });
if (!acknowledgedWarning) setOpen({ ...closeAll, warning: true });
const updateSlotFromOrder = (updatedOrder: Order, slot: Slot): void => {
if (
Number(paramsRef.current.orderId) === updatedOrder.id &&
paramsRef.current.shortAlias === updatedOrder.shortAlias
) {
setCurrentOrder(updatedOrder);
slot.updateSlotFromOrder(updatedOrder);
}
}, [params, currentOrderId]);
};

const onClickCoordinator = function (): void {
if (currentOrder?.shortAlias != null) {
Expand Down Expand Up @@ -87,28 +86,27 @@ const OrderPage = (): JSX.Element => {
);

const tradeBoxSpace = currentOrder ? (
<TradeBox baseUrl={baseUrl} onStartAgain={startAgain} />
<TradeBox onStartAgain={startAgain} currentOrder={currentOrder} />
) : (
<></>
);

return (
<Box>
<WarningDialog
open={open.warning}
open={!acknowledgedWarning && currentOrder?.status === 0}
onClose={() => {
setOpen(closeAll);
setAcknowledgedWarning(true);
}}
longAlias={federation.getCoordinator(params.shortAlias ?? '')?.longAlias}
/>
{currentOrder === null && badOrder === undefined && <CircularProgress />}
{badOrder !== undefined ? (
{!currentOrder?.maker_hash_id && <CircularProgress />}
{currentOrder?.bad_request && currentOrder.status !== 5 ? (
<Typography align='center' variant='subtitle2' color='secondary'>
{t(badOrder)}
{t(currentOrder.bad_request)}
</Typography>
) : null}
{currentOrder !== null && badOrder === undefined ? (
{currentOrder?.maker_hash_id && (!currentOrder.bad_request || currentOrder.status === 5) ? (
currentOrder.is_participant ? (
windowSize.width > doublePageWidth ? (
// DOUBLE PAPER VIEW
Expand Down
31 changes: 13 additions & 18 deletions frontend/src/basic/RobotPage/RobotProfile.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ import { AppContext, type UseAppStoreType } from '../../contexts/AppContext';
import { genBase62Token } from '../../utils';
import { LoadingButton } from '@mui/lab';
import { GarageContext, type UseGarageStoreType } from '../../contexts/GarageContext';
import { FederationContext, type UseFederationStoreType } from '../../contexts/FederationContext';

interface RobotProfileProps {
robot: Robot;
Expand All @@ -45,8 +44,7 @@ const RobotProfile = ({
width,
}: RobotProfileProps): JSX.Element => {
const { windowSize } = useContext<UseAppStoreType>(AppContext);
const { garage, robotUpdatedAt, orderUpdatedAt } = useContext<UseGarageStoreType>(GarageContext);
const { setCurrentOrderId } = useContext<UseFederationStoreType>(FederationContext);
const { garage, slotUpdatedAt } = useContext<UseGarageStoreType>(GarageContext);

const { t } = useTranslation();
const theme = useTheme();
Expand All @@ -59,7 +57,7 @@ const RobotProfile = ({
if (slot?.hashId) {
setLoading(false);
}
}, [orderUpdatedAt, robotUpdatedAt, loading]);
}, [slotUpdatedAt, loading]);

const handleAddRobot = (): void => {
getGenerateRobot(genBase62Token(36));
Expand Down Expand Up @@ -147,7 +145,7 @@ const RobotProfile = ({
tooltip={t('This is your trading avatar')}
tooltipPosition='top'
/>
{robot?.found && Boolean(slot?.lastShortAlias) ? (
{robot?.found && Boolean(slot?.lastOrder?.id) ? (
<Typography align='center' variant='h6'>
{t('Welcome back!')}
</Typography>
Expand All @@ -156,38 +154,38 @@ const RobotProfile = ({
)}
</Grid>

{loadingCoordinators > 0 && !robot?.activeOrderId ? (
{loadingCoordinators > 0 && !slot?.activeOrder?.id ? (
<Grid>
<b>{t('Looking for orders!')}</b>
<LinearProgress />
</Grid>
) : null}

{Boolean(robot?.activeOrderId) && Boolean(slot?.hashId) ? (
{slot?.activeOrder ? (
<Grid item>
<Button
onClick={() => {
setCurrentOrderId({ id: robot?.activeOrderId, shortAlias: slot?.activeShortAlias });
navigate(
`/order/${String(slot?.activeShortAlias)}/${String(robot?.activeOrderId)}`,
`/order/${String(slot?.activeOrder?.shortAlias)}/${String(slot?.activeOrder?.id)}`,
);
}}
>
{t('Active order #{{orderID}}', { orderID: robot?.activeOrderId })}
{t('Active order #{{orderID}}', { orderID: slot?.activeOrder?.id })}
</Button>
</Grid>
) : null}

{Boolean(robot?.lastOrderId) && Boolean(slot?.hashId) ? (
{!slot?.activeOrder?.id && Boolean(slot?.lastOrder?.id) ? (
<Grid item container direction='column' alignItems='center'>
<Grid item>
<Button
onClick={() => {
setCurrentOrderId({ id: robot?.lastOrderId, shortAlias: slot?.activeShortAlias });
navigate(`/order/${String(slot?.lastShortAlias)}/${String(robot?.lastOrderId)}`);
navigate(
`/order/${String(slot?.lastOrder?.shortAlias)}/${String(slot?.lastOrder?.id)}`,
);
}}
>
{t('Last order #{{orderID}}', { orderID: robot?.lastOrderId })}
{t('Last order #{{orderID}}', { orderID: slot?.lastOrder?.id })}
</Button>
</Grid>
<Grid item>
Expand All @@ -210,10 +208,7 @@ const RobotProfile = ({
</Grid>
) : null}

{!robot?.activeOrderId &&
slot?.hashId &&
!robot?.lastOrderId &&
loadingCoordinators === 0 ? (
{!slot?.activeOrder && !slot?.lastOrder && loadingCoordinators === 0 ? (
<Grid item>{t('No existing orders found')}</Grid>
) : null}

Expand Down
3 changes: 1 addition & 2 deletions frontend/src/basic/RobotPage/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,6 @@ const RobotPage = (): JSX.Element => {
if (token !== undefined && token !== null && page === 'robot') {
setInputToken(token);
if (window.NativeRobosats === undefined || torStatus === 'ON' || !settings.useProxy) {
getGenerateRobot(token);
setView('profile');
}
}
Expand All @@ -70,7 +69,7 @@ const RobotPage = (): JSX.Element => {
pubKey: key.publicKeyArmored,
encPrivKey: key.encryptedPrivateKeyArmored,
});
void federation.fetchRobot(garage, token);
void garage.fetchRobot(federation, token);
garage.setCurrentSlot(token);
})
.catch((error) => {
Expand Down
Loading

0 comments on commit a390254

Please sign in to comment.