aboutsummaryrefslogtreecommitdiff
path: root/packages/demobank-ui/src/hooks/circuit.ts
diff options
context:
space:
mode:
authorSebastian <sebasjm@gmail.com>2024-01-23 18:00:42 -0300
committerSebastian <sebasjm@gmail.com>2024-01-24 17:14:02 -0300
commit236d4347f5884bb1d9ca1d3bb4ad0ba776577fd2 (patch)
treea38823a73006c38bd54cb438da81f13bb513dce5 /packages/demobank-ui/src/hooks/circuit.ts
parent579128ce40c7e56f390cadaf2fc2fd4cc6290d68 (diff)
downloadwallet-core-236d4347f5884bb1d9ca1d3bb4ad0ba776577fd2.tar.xz
many changes
activate eslint update file headers removed history and preact-router remove eslint errors and more applied prettier
Diffstat (limited to 'packages/demobank-ui/src/hooks/circuit.ts')
-rw-r--r--packages/demobank-ui/src/hooks/circuit.ts310
1 files changed, 194 insertions, 116 deletions
diff --git a/packages/demobank-ui/src/hooks/circuit.ts b/packages/demobank-ui/src/hooks/circuit.ts
index c012fe4c1..0c306259b 100644
--- a/packages/demobank-ui/src/hooks/circuit.ts
+++ b/packages/demobank-ui/src/hooks/circuit.ts
@@ -14,15 +14,24 @@
GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
*/
-import { useState } from "preact/hooks";
import { MAX_RESULT_SIZE, PAGE_SIZE } from "../utils.js";
import { useBackendState } from "./backend.js";
-import { AccessToken, AmountJson, AmountString, Amounts, OperationOk, TalerBankConversionResultByMethod, TalerCoreBankErrorsByMethod, TalerCoreBankResultByMethod, TalerCorebankApi, TalerError, TalerHttpError, opFixedSuccess } from "@gnu-taler/taler-util";
+import {
+ AccessToken,
+ AmountJson,
+ Amounts,
+ OperationOk,
+ TalerBankConversionResultByMethod,
+ TalerCoreBankErrorsByMethod,
+ TalerCoreBankResultByMethod,
+ TalerCorebankApi,
+ TalerError,
+ TalerHttpError,
+ opFixedSuccess,
+} from "@gnu-taler/taler-util";
import _useSWR, { SWRHook, mutate } from "swr";
import { useBankCoreApiContext } from "../context/config.js";
-import { assertUnreachable } from "../pages/WithdrawalOperationPage.js";
-import { format, getDate, getDay, getHours, getMonth, getYear, set, sub } from "date-fns";
// FIX default import https://github.com/microsoft/TypeScript/issues/49189
const useSWR = _useSWR as unknown as SWRHook;
@@ -43,16 +52,21 @@ type CashoutEstimators = {
};
export function revalidateConversionInfo() {
- mutate(key => Array.isArray(key) && key[key.length - 1] === "getConversionInfoAPI")
+ mutate(
+ (key) =>
+ Array.isArray(key) && key[key.length - 1] === "getConversionInfoAPI",
+ );
}
export function useConversionInfo() {
- const { api, config } = useBankCoreApiContext()
+ const { api, config } = useBankCoreApiContext();
async function fetcher() {
- return await api.getConversionInfoAPI().getConfig()
+ return await api.getConversionInfoAPI().getConfig();
}
- const { data, error } = useSWR<TalerBankConversionResultByMethod<"getConfig">, TalerHttpError>(
- !config.allow_conversion ? undefined : ["getConversionInfoAPI"], fetcher, {
+ const { data, error } = useSWR<
+ TalerBankConversionResultByMethod<"getConfig">,
+ TalerHttpError
+ >(!config.allow_conversion ? undefined : ["getConversionInfoAPI"], fetcher, {
refreshInterval: 0,
refreshWhenHidden: false,
revalidateOnFocus: false,
@@ -64,25 +78,23 @@ export function useConversionInfo() {
keepPreviousData: true,
});
- if (data) return data
+ if (data) return data;
if (error) return error;
return undefined;
-
}
export function useEstimator(): CashoutEstimators {
- const { state } = useBackendState();
const { api } = useBankCoreApiContext();
return {
estimateByCredit: async (fiatAmount, fee) => {
const resp = await api.getConversionInfoAPI().getCashoutRate({
- credit: fiatAmount
+ credit: fiatAmount,
});
if (resp.type === "fail") {
// can't happen
// not-supported: it should not be able to call this function
// wrong-calculation: we are using just one parameter
- throw TalerError.fromDetail(resp.detail.code, {}, resp.detail.hint)
+ throw TalerError.fromDetail(resp.detail.code, {}, resp.detail.hint);
}
const credit = Amounts.parseOrThrow(resp.body.amount_credit);
const debit = Amounts.parseOrThrow(resp.body.amount_debit);
@@ -96,13 +108,13 @@ export function useEstimator(): CashoutEstimators {
},
estimateByDebit: async (regionalAmount, fee) => {
const resp = await api.getConversionInfoAPI().getCashoutRate({
- debit: regionalAmount
+ debit: regionalAmount,
});
if (resp.type === "fail") {
// can't happen
// not-supported: it should not be able to call this function
// wrong-calculation: we are using just one parameter
- throw TalerError.fromDetail(resp.detail.code, {}, resp.detail.hint)
+ throw TalerError.fromDetail(resp.detail.code, {}, resp.detail.hint);
}
const credit = Amounts.parseOrThrow(resp.body.amount_credit);
const debit = Amounts.parseOrThrow(resp.body.amount_debit);
@@ -118,26 +130,34 @@ export function useEstimator(): CashoutEstimators {
}
export function revalidateBusinessAccounts() {
- mutate(key => Array.isArray(key) && key[key.length - 1] === "getAccounts")
+ mutate((key) => Array.isArray(key) && key[key.length - 1] === "getAccounts");
}
export function useBusinessAccounts() {
const { state: credentials } = useBackendState();
- const token = credentials.status !== "loggedIn" ? undefined : credentials.token
+ const token =
+ credentials.status !== "loggedIn" ? undefined : credentials.token;
const { api } = useBankCoreApiContext();
- const [offset, setOffset] = useState<string | undefined>();
+ // const [offset, setOffset] = useState<string | undefined>();
+ const offset = undefined;
function fetcher([token, offset]: [AccessToken, string]) {
- //FIXME: add account name filter
- return api.getAccounts(token, {}, {
- limit: MAX_RESULT_SIZE,
- offset,
- order: "asc"
- })
+ // FIXME: add account name filter
+ return api.getAccounts(
+ token,
+ {},
+ {
+ limit: MAX_RESULT_SIZE,
+ offset,
+ order: "asc",
+ },
+ );
}
- const { data, error } = useSWR<TalerCoreBankResultByMethod<"getAccounts">, TalerHttpError>(
- [token, offset, "getAccounts"], fetcher, {
+ const { data, error } = useSWR<
+ TalerCoreBankResultByMethod<"getAccounts">,
+ TalerHttpError
+ >([token, offset, "getAccounts"], fetcher, {
refreshInterval: 0,
refreshWhenHidden: false,
revalidateOnFocus: false,
@@ -147,8 +167,7 @@ export function useBusinessAccounts() {
errorRetryInterval: 1,
shouldRetryOnError: false,
keepPreviousData: true,
- },
- );
+ });
const isLastPage =
data && data.type === "ok" && data.body.accounts.length < PAGE_SIZE;
@@ -159,10 +178,9 @@ export function useBusinessAccounts() {
isFirstPage,
loadMore: () => {
if (isLastPage || data?.type !== "ok") return;
- const list = data.body.accounts
+ const list = data.body.accounts;
if (list.length < MAX_RESULT_SIZE) {
- //FIXME: define pagination
-
+ // FIXME: define pagination
// setOffset(list[list.length - 1].row_id);
}
},
@@ -176,44 +194,66 @@ export function useBusinessAccounts() {
return undefined;
}
-type CashoutWithId = TalerCorebankApi.CashoutStatusResponse & { id: number }
+type CashoutWithId = TalerCorebankApi.CashoutStatusResponse & { id: number };
function notUndefined(c: CashoutWithId | undefined): c is CashoutWithId {
- return c !== undefined
+ return c !== undefined;
}
export function revalidateOnePendingCashouts() {
- mutate(key => Array.isArray(key) && key[key.length - 1] === "useOnePendingCashouts")
+ mutate(
+ (key) =>
+ Array.isArray(key) && key[key.length - 1] === "useOnePendingCashouts",
+ );
}
export function useOnePendingCashouts(account: string) {
const { state: credentials } = useBackendState();
const { api, config } = useBankCoreApiContext();
- const token = credentials.status !== "loggedIn" ? undefined : credentials.token
+ const token =
+ credentials.status !== "loggedIn" ? undefined : credentials.token;
async function fetcher([username, token]: [string, AccessToken]) {
- const list = await api.getAccountCashouts({ username, token })
+ const list = await api.getAccountCashouts({ username, token });
if (list.type !== "ok") {
return list;
}
- const pendingCashout = list.body.cashouts.find(c => c.status === "pending")
- if (!pendingCashout) return opFixedSuccess(undefined)
- const cashoutInfo = await api.getCashoutById({ username, token }, pendingCashout?.cashout_id)
+ const pendingCashout = list.body.cashouts.find(
+ (c) => c.status === "pending",
+ );
+ if (!pendingCashout) return opFixedSuccess(undefined);
+ const cashoutInfo = await api.getCashoutById(
+ { username, token },
+ pendingCashout?.cashout_id,
+ );
if (cashoutInfo.type !== "ok") {
return cashoutInfo;
}
- return opFixedSuccess({ ...cashoutInfo.body, id: pendingCashout.cashout_id })
+ return opFixedSuccess({
+ ...cashoutInfo.body,
+ id: pendingCashout.cashout_id,
+ });
}
- const { data, error } = useSWR<OperationOk<CashoutWithId | undefined> | TalerCoreBankErrorsByMethod<"getAccountCashouts"> | TalerCoreBankErrorsByMethod<"getCashoutById">, TalerHttpError>(
- !config.allow_conversion ? undefined : [account, token, "useOnePendingCashouts"], fetcher, {
- refreshInterval: 0,
- refreshWhenHidden: false,
- revalidateOnFocus: false,
- revalidateOnReconnect: false,
- refreshWhenOffline: false,
- errorRetryCount: 0,
- errorRetryInterval: 1,
- shouldRetryOnError: false,
- keepPreviousData: true,
- });
+ const { data, error } = useSWR<
+ | OperationOk<CashoutWithId | undefined>
+ | TalerCoreBankErrorsByMethod<"getAccountCashouts">
+ | TalerCoreBankErrorsByMethod<"getCashoutById">,
+ TalerHttpError
+ >(
+ !config.allow_conversion
+ ? undefined
+ : [account, token, "useOnePendingCashouts"],
+ fetcher,
+ {
+ refreshInterval: 0,
+ refreshWhenHidden: false,
+ revalidateOnFocus: false,
+ revalidateOnReconnect: false,
+ refreshWhenOffline: false,
+ errorRetryCount: 0,
+ errorRetryInterval: 1,
+ shouldRetryOnError: false,
+ keepPreviousData: true,
+ },
+ );
if (data) return data;
if (error) return error;
@@ -221,42 +261,54 @@ export function useOnePendingCashouts(account: string) {
}
export function revalidateCashouts() {
- mutate(key => Array.isArray(key) && key[key.length - 1] === "useCashouts")
+ mutate((key) => Array.isArray(key) && key[key.length - 1] === "useCashouts");
}
export function useCashouts(account: string) {
const { state: credentials } = useBackendState();
const { api, config } = useBankCoreApiContext();
- const token = credentials.status !== "loggedIn" ? undefined : credentials.token
+ const token =
+ credentials.status !== "loggedIn" ? undefined : credentials.token;
async function fetcher([username, token]: [string, AccessToken]) {
- const list = await api.getAccountCashouts({ username, token })
+ const list = await api.getAccountCashouts({ username, token });
if (list.type !== "ok") {
return list;
}
- const all: Array<CashoutWithId | undefined> = await Promise.all(list.body.cashouts.map(c => {
- return api.getCashoutById({ username, token }, c.cashout_id).then(r => {
- if (r.type === "fail") {
- return undefined
- }
- return { ...r.body, id: c.cashout_id }
- })
- }))
- const cashouts = all.filter(notUndefined)
- return { type: "ok" as const, body: { cashouts } }
+ const all: Array<CashoutWithId | undefined> = await Promise.all(
+ list.body.cashouts.map((c) => {
+ return api
+ .getCashoutById({ username, token }, c.cashout_id)
+ .then((r) => {
+ if (r.type === "fail") {
+ return undefined;
+ }
+ return { ...r.body, id: c.cashout_id };
+ });
+ }),
+ );
+ const cashouts = all.filter(notUndefined);
+ return { type: "ok" as const, body: { cashouts } };
}
- const { data, error } = useSWR<OperationOk<{ cashouts: CashoutWithId[] }> | TalerCoreBankErrorsByMethod<"getAccountCashouts">, TalerHttpError>(
- !config.allow_conversion ? undefined : [account, token, "useCashouts"], fetcher, {
- refreshInterval: 0,
- refreshWhenHidden: false,
- revalidateOnFocus: false,
- revalidateOnReconnect: false,
- refreshWhenOffline: false,
- errorRetryCount: 0,
- errorRetryInterval: 1,
- shouldRetryOnError: false,
- keepPreviousData: true,
- });
+ const { data, error } = useSWR<
+ | OperationOk<{ cashouts: CashoutWithId[] }>
+ | TalerCoreBankErrorsByMethod<"getAccountCashouts">,
+ TalerHttpError
+ >(
+ !config.allow_conversion ? undefined : [account, token, "useCashouts"],
+ fetcher,
+ {
+ refreshInterval: 0,
+ refreshWhenHidden: false,
+ revalidateOnFocus: false,
+ revalidateOnReconnect: false,
+ refreshWhenOffline: false,
+ errorRetryCount: 0,
+ errorRetryInterval: 1,
+ shouldRetryOnError: false,
+ keepPreviousData: true,
+ },
+ );
if (data) return data;
if (error) return error;
@@ -264,72 +316,98 @@ export function useCashouts(account: string) {
}
export function revalidateCashoutDetails() {
- mutate(key => Array.isArray(key) && key[key.length - 1] === "getCashoutById")
+ mutate(
+ (key) => Array.isArray(key) && key[key.length - 1] === "getCashoutById",
+ );
}
export function useCashoutDetails(cashoutId: number | undefined) {
const { state: credentials } = useBackendState();
- const creds = credentials.status !== "loggedIn" ? undefined : credentials
+ const creds = credentials.status !== "loggedIn" ? undefined : credentials;
const { api } = useBankCoreApiContext();
async function fetcher([username, token, id]: [string, AccessToken, number]) {
- return api.getCashoutById({ username, token }, id)
+ return api.getCashoutById({ username, token }, id);
}
- const { data, error } = useSWR<TalerCoreBankResultByMethod<"getCashoutById">, TalerHttpError>(
- cashoutId === undefined ? undefined : [creds?.username, creds?.token, cashoutId, "getCashoutById"], fetcher, {
- refreshInterval: 0,
- refreshWhenHidden: false,
- revalidateOnFocus: false,
- revalidateOnReconnect: false,
- refreshWhenOffline: false,
- errorRetryCount: 0,
- errorRetryInterval: 1,
- shouldRetryOnError: false,
- keepPreviousData: true,
- });
+ const { data, error } = useSWR<
+ TalerCoreBankResultByMethod<"getCashoutById">,
+ TalerHttpError
+ >(
+ cashoutId === undefined
+ ? undefined
+ : [creds?.username, creds?.token, cashoutId, "getCashoutById"],
+ fetcher,
+ {
+ refreshInterval: 0,
+ refreshWhenHidden: false,
+ revalidateOnFocus: false,
+ revalidateOnReconnect: false,
+ refreshWhenOffline: false,
+ errorRetryCount: 0,
+ errorRetryInterval: 1,
+ shouldRetryOnError: false,
+ keepPreviousData: true,
+ },
+ );
if (data) return data;
if (error) return error;
return undefined;
}
export type MonitorMetrics = {
- lastHour: TalerCoreBankResultByMethod<"getMonitor">,
- lastDay: TalerCoreBankResultByMethod<"getMonitor">,
- lastMonth: TalerCoreBankResultByMethod<"getMonitor">,
-}
+ lastHour: TalerCoreBankResultByMethod<"getMonitor">;
+ lastDay: TalerCoreBankResultByMethod<"getMonitor">;
+ lastMonth: TalerCoreBankResultByMethod<"getMonitor">;
+};
-export type LastMonitor = { current: TalerCoreBankResultByMethod<"getMonitor">, previous: TalerCoreBankResultByMethod<"getMonitor"> }
+export type LastMonitor = {
+ current: TalerCoreBankResultByMethod<"getMonitor">;
+ previous: TalerCoreBankResultByMethod<"getMonitor">;
+};
export function revalidateLastMonitorInfo() {
- mutate(key => Array.isArray(key) && key[key.length - 1] === "useLastMonitorInfo")
+ mutate(
+ (key) => Array.isArray(key) && key[key.length - 1] === "useLastMonitorInfo",
+ );
}
-export function useLastMonitorInfo(currentMoment: number, previousMoment: number, timeframe: TalerCorebankApi.MonitorTimeframeParam) {
- const { api, config } = useBankCoreApiContext();
+export function useLastMonitorInfo(
+ currentMoment: number,
+ previousMoment: number,
+ timeframe: TalerCorebankApi.MonitorTimeframeParam,
+) {
+ const { api } = useBankCoreApiContext();
const { state: credentials } = useBackendState();
- const token = credentials.status !== "loggedIn" ? undefined : credentials.token
+ const token =
+ credentials.status !== "loggedIn" ? undefined : credentials.token;
- async function fetcher([token, timeframe]: [AccessToken, TalerCorebankApi.MonitorTimeframeParam]) {
+ async function fetcher([token, timeframe]: [
+ AccessToken,
+ TalerCorebankApi.MonitorTimeframeParam,
+ ]) {
const [current, previous] = await Promise.all([
api.getMonitor(token, { timeframe, which: currentMoment }),
api.getMonitor(token, { timeframe, which: previousMoment }),
- ])
+ ]);
return {
current,
previous,
- }
+ };
}
const { data, error } = useSWR<LastMonitor, TalerHttpError>(
- !token ? undefined : [token, timeframe, "useLastMonitorInfo"], fetcher, {
- refreshInterval: 0,
- refreshWhenHidden: false,
- revalidateOnFocus: false,
- revalidateOnReconnect: false,
- refreshWhenOffline: false,
- errorRetryCount: 0,
- errorRetryInterval: 1,
- shouldRetryOnError: false,
- keepPreviousData: true,
- });
+ !token ? undefined : [token, timeframe, "useLastMonitorInfo"],
+ fetcher,
+ {
+ refreshInterval: 0,
+ refreshWhenHidden: false,
+ revalidateOnFocus: false,
+ revalidateOnReconnect: false,
+ refreshWhenOffline: false,
+ errorRetryCount: 0,
+ errorRetryInterval: 1,
+ shouldRetryOnError: false,
+ keepPreviousData: true,
+ },
+ );
if (data) return data;
if (error) return error;