summaryrefslogtreecommitdiff
path: root/packages/frontend/src/InstanceRoutes.tsx
blob: 5c0427550511d89d5a38354a34684df39ec3180c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
/*
 This file is part of GNU Taler
 (C) 2021 Taler Systems S.A.

 GNU Taler is free software; you can redistribute it and/or modify it under the
 terms of the GNU General Public License as published by the Free Software
 Foundation; either version 3, or (at your option) any later version.

 GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY
 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 A PARTICULAR PURPOSE.  See the GNU General Public License for more details.

 You should have received a copy of the GNU General Public License along with
 GNU Taler; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
 */

/**
*
* @author Sebastian Javier Marchano (sebasjm)
*/

import { createHashHistory } from 'history';
import { Fragment, FunctionComponent, h, VNode } from 'preact';
import { Route, route, Router } from 'preact-router';
import { useCallback, useEffect, useMemo, useState } from "preact/hooks";
import { Loading } from './components/exception/loading';
import { NotificationCard } from './components/menu';
import { useBackendContext } from './context/backend';
import { InstanceContextProvider } from './context/instance';
import { useBackendDefaultToken, useBackendInstanceToken } from './hooks';
import { HttpError } from "./hooks/backend";
import { useTranslator } from './i18n';
import InstanceCreatePage from "./paths/admin/create";
import InstanceListPage from './paths/admin/list';
import OrderCreatePage from './paths/instance/orders/create';
import OrderDetailsPage from './paths/instance/orders/details';
import OrderListPage from './paths/instance/orders/list';
import ProductCreatePage from './paths/instance/products/create';
import ProductListPage from './paths/instance/products/list';
import ProductUpdatePage from './paths/instance/products/update';
import TransferListPage from './paths/instance/transfers/list';
import TransferCreatePage from './paths/instance/transfers/create';
import ReservesCreatePage from './paths/instance/reserves/create';
import ReservesDetailsPage from './paths/instance/reserves/details';
import ReservesListPage from './paths/instance/reserves/list';
import InstanceUpdatePage, { Props as InstanceUpdatePageProps } from "./paths/instance/update";
import LoginPage from './paths/login';
import NotFoundPage from './paths/notfound';
import { Notification } from './utils/types';

export enum InstancePaths {
  // details = '/',
  error = '/error',
  update = '/update',

  product_list = '/products',
  product_update = '/product/:pid/update',
  product_new = '/product/new',

  order_list = '/orders',
  order_new = '/order/new',
  order_details = '/order/:oid/details',

  reserves_list = '/reserves',
  reserves_details = '/reserves/:rid/details',
  reserves_new = '/reserves/new',

  transfers_list = '/transfers',
  transfers_new = '/transfer/new',
}

// eslint-disable-next-line @typescript-eslint/no-empty-function
const noop = () => { }

export enum AdminPaths {
  list_instances = '/instances',
  new_instance = '/instance/new',
  update_instance = '/instance/:id/update',
}

export interface Props {
  id: string;
  admin?: boolean;
}

export function InstanceRoutes({ id, admin }: Props): VNode {
  const [_, updateDefaultToken] = useBackendDefaultToken()
  const [token, updateToken] = useBackendInstanceToken(id);
  const { changeBackend, addTokenCleaner } = useBackendContext();
  const cleaner = useCallback(() => { updateToken(undefined); }, [id]);
  const i18n = useTranslator();
  const [globalNotification, setGlobalNotification] = useState<Notification & { to: string } | undefined>(undefined)

  useEffect(() => {
    addTokenCleaner(cleaner);
  }, [addTokenCleaner, cleaner]);

  const changeToken = (token?:string) => {
    if (admin) {
      updateToken(token);
    } else {
      updateDefaultToken(token)
    }
  }
  const updateLoginStatus = (url: string, token?: string) => {
    changeBackend(url);
    if (!token) return
    changeToken(token)
  };

  const value = useMemo(() => ({ id, token, admin, changeToken }), [id, token, admin])

  const ServerErrorRedirectTo = (to: InstancePaths | AdminPaths) => (error: HttpError) => {
    setGlobalNotification({
      message: i18n`The backend reported a problem: HTTP status #${error.status}`,
      description: i18n`Diagnostic from ${error.info?.url} is "${error.message}"`,
      type: 'ERROR',
      to
    })
    return <Redirect to={to} />
  }

  const LoginPageAccessDenied = () => <Fragment>
    <NotificationCard notification={{ message: i18n`Access denied`, description: i18n`The access token provided is invalid.`, type: 'ERROR', }} />
    <LoginPage onConfirm={updateLoginStatus} />
  </Fragment>

  function IfAdminCreateDefaultOr<T>(Next: FunctionComponent<any>) {
    return function IfAdminCreateDefaultOrImpl(props?: T) {
      if (admin && id === 'default') {
        return <Fragment>
          <NotificationCard notification={{
            message: i18n`No 'default' instance configured yet.`,
            description: i18n`Create a 'default' instance to begin using the merchant backoffice.`,
            type: 'INFO'
          }} />
          <InstanceCreatePage forceId="default" onConfirm={() => {
            route(AdminPaths.list_instances)
          }} />
        </Fragment>
      }
      if (props) {
        return <Next {...props} />
      }
      return <Next />

    }
  }

  return <InstanceContextProvider value={value}>

    <NotificationCard notification={globalNotification} />

    <Router  onChange={(e) => {
      const movingOutFromNotification = globalNotification && e.url !== globalNotification.to
      if (movingOutFromNotification) {
        setGlobalNotification(undefined)
      }
    }} >

      <Route path="/" component={Redirect} to={InstancePaths.order_list} />

      {/**
       * Admin pages
       */}
      {admin &&
        <Route path={AdminPaths.list_instances} component={InstanceListPage}
          onCreate={() => { route(AdminPaths.new_instance) }}
          onUpdate={(id: string): void => { route(`/instance/${id}/update`); }}
          onUnauthorized={LoginPageAccessDenied}
          onLoadError={ServerErrorRedirectTo(InstancePaths.error)}
        />
      }

      {admin &&
        <Route path={AdminPaths.new_instance} component={InstanceCreatePage}
          onBack={() => route(AdminPaths.list_instances)}
          onConfirm={() => { route(AdminPaths.list_instances); }}
        />
      }

      {admin &&
        <Route path={AdminPaths.update_instance} component={AdminInstanceUpdatePage}
          onBack={() => route(AdminPaths.list_instances)}
          onConfirm={() => { route(AdminPaths.list_instances); }}
          onUpdateError={ServerErrorRedirectTo(AdminPaths.list_instances)}
          onLoadError={ServerErrorRedirectTo(AdminPaths.list_instances)}
          onNotFound={NotFoundPage}
        />
      }

      {/**
       * Update instance page
       */}
      <Route path={InstancePaths.update} component={InstanceUpdatePage}
        onBack={() => { route(`/`); }}
        onConfirm={() => { route(`/`); }}
        onUpdateError={noop}
        onNotFound={IfAdminCreateDefaultOr(NotFoundPage)}
        onUnauthorized={LoginPageAccessDenied}
        onLoadError={ServerErrorRedirectTo(InstancePaths.error)}
      />

      {/**
       * Product pages
       */}
      <Route path={InstancePaths.product_list} component={ProductListPage}
        onUnauthorized={LoginPageAccessDenied}
        onLoadError={ServerErrorRedirectTo(InstancePaths.update)}
        onCreate={() => { route(InstancePaths.product_new) }}
        onSelect={(id: string) => { route(InstancePaths.product_update.replace(':pid', id)) }}
        onNotFound={IfAdminCreateDefaultOr(NotFoundPage)}
      />
      <Route path={InstancePaths.product_update} component={ProductUpdatePage}
        onUnauthorized={LoginPageAccessDenied}
        onLoadError={ServerErrorRedirectTo(InstancePaths.product_list)}
        onConfirm={() => { route(InstancePaths.product_list); }}
        onBack={() => { route(InstancePaths.product_list); }}
        onNotFound={IfAdminCreateDefaultOr(NotFoundPage)}
      />
      <Route path={InstancePaths.product_new}
        component={ProductCreatePage}
        onConfirm={() => { route(InstancePaths.product_list); }}
        onBack={() => { route(InstancePaths.product_list); }}
      />

      {/**
       * Order pages
       */}
      <Route path={InstancePaths.order_list} component={OrderListPage}
        onCreate={() => { route(InstancePaths.order_new) }}
        onSelect={(id: string) => { route(InstancePaths.order_details.replace(':oid', id)) }}
        onUnauthorized={LoginPageAccessDenied}
        onLoadError={ServerErrorRedirectTo(InstancePaths.update)}
        onNotFound={IfAdminCreateDefaultOr(NotFoundPage)}
      />
      <Route path={InstancePaths.order_details} component={OrderDetailsPage}
        onUnauthorized={LoginPageAccessDenied}
        onLoadError={ServerErrorRedirectTo(InstancePaths.order_list)}
        onNotFound={IfAdminCreateDefaultOr(NotFoundPage)}
        onBack={() => { route(InstancePaths.order_list) }}
      />
      <Route path={InstancePaths.order_new} component={OrderCreatePage}
        onConfirm={() => { route(InstancePaths.order_list) }}
        onBack={() => { route(InstancePaths.order_list) }}
      />

      {/**
       * Transfer pages
       */}
      <Route path={InstancePaths.transfers_list} component={TransferListPage}
        onUnauthorized={LoginPageAccessDenied}
        onNotFound={IfAdminCreateDefaultOr(NotFoundPage)}
        onLoadError={ServerErrorRedirectTo(InstancePaths.update)}
        onCreate={() => { route(InstancePaths.transfers_new) }}
      />

      <Route path={InstancePaths.transfers_new} component={TransferCreatePage}
        onConfirm={() => { route(InstancePaths.transfers_list) }}
        onBack={() => { route(InstancePaths.transfers_list) }}
      />

      {/**
       * reserves pages
       */}
      <Route path={InstancePaths.reserves_list} component={ReservesListPage}
        onUnauthorized={LoginPageAccessDenied}
        onNotFound={IfAdminCreateDefaultOr(NotFoundPage)}
        onLoadError={ServerErrorRedirectTo(InstancePaths.update)}
        onSelect={(id: string) => { route(InstancePaths.reserves_details.replace(':rid', id)) }}
        onCreate={() => { route(InstancePaths.reserves_new) }}
      />

      <Route path={InstancePaths.reserves_details} component={ReservesDetailsPage}
        onUnauthorized={LoginPageAccessDenied}
        onLoadError={ServerErrorRedirectTo(InstancePaths.reserves_list)}
        onNotFound={IfAdminCreateDefaultOr(NotFoundPage)}
        onBack={() => { route(InstancePaths.reserves_list) }}
      />

      <Route path={InstancePaths.reserves_new} component={ReservesCreatePage}
        onConfirm={() => { route(InstancePaths.reserves_list) }}
        onBack={() => { route(InstancePaths.reserves_list) }}
      />
      {/**
       * Example pages
       */}
      <Route path="/loading" component={Loading} />
      <Route default component={NotFoundPage} />
    </Router>
  </InstanceContextProvider>;

}

export function Redirect({ to }: { to: string }): null {
  useEffect(() => {
    route(to, true)
  })
  return null
}

function AdminInstanceUpdatePage({ id, ...rest }: { id: string } & InstanceUpdatePageProps) {
  const [token, changeToken] = useBackendInstanceToken(id);
  const { changeBackend } = useBackendContext();
  const updateLoginStatus = (url: string, token?: string) => {
    changeBackend(url);
    if (token)
    changeToken(token);
  };
  const value = useMemo(() => ({ id, token, admin: true, changeToken }), [id, token])
  const i18n = useTranslator();
  return <InstanceContextProvider value={value}>
    <InstanceUpdatePage {...rest}
      onLoadError={(error: HttpError) => {
        return <Fragment>
          <NotificationCard notification={{
            message: i18n`The backend reported a problem: HTTP status #${error.status}`,
            description: i18n`Diagnostic from ${error.info?.url} is "${error.message}"`,
            type: 'ERROR'
          }} />
          <LoginPage onConfirm={updateLoginStatus} />
        </Fragment>
      }}

      onUnauthorized={() => {
        return <Fragment>
          <NotificationCard notification={{
            message: i18n`Access denied`,
            description: i18n`The access token provided is invalid`,
            type: 'ERROR',
          }} />
          <LoginPage onConfirm={updateLoginStatus} />
        </Fragment>
      }}

    />
  </InstanceContextProvider>
}