wallet-core/packages/demobank-ui/src/hooks/circuit.ts

349 lines
10 KiB
TypeScript
Raw Normal View History

2023-02-08 21:41:19 +01:00
/*
This file is part of GNU Taler
(C) 2022 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/>
*/
import {
HttpResponse,
HttpResponseOk,
HttpResponsePaginated,
2023-02-10 13:51:37 +01:00
RequestError,
useApiContext,
2023-02-08 21:41:19 +01:00
} from "@gnu-taler/web-util/lib/index.browser";
import { useEffect, useMemo, useState } from "preact/hooks";
import { useBackendContext } from "../context/backend.js";
import { MAX_RESULT_SIZE, PAGE_SIZE } from "../utils.js";
2023-02-10 13:51:37 +01:00
import { useAuthenticatedBackend, useMatchMutate } from "./backend.js";
2023-02-08 21:41:19 +01:00
2023-02-16 16:14:24 +01:00
// FIX default import https://github.com/microsoft/TypeScript/issues/49189
import _useSWR, { SWRHook } from 'swr';
const useSWR = _useSWR as unknown as SWRHook
2023-02-08 21:41:19 +01:00
export function useAdminAccountAPI(): AdminAccountAPI {
const { request } = useAuthenticatedBackend();
2023-02-10 13:51:37 +01:00
const mutateAll = useMatchMutate();
const { state } = useBackendContext();
2023-02-08 21:41:19 +01:00
if (state.status === "loggedOut") {
2023-02-10 13:51:37 +01:00
throw Error("access-api can't be used when the user is not logged In");
2023-02-08 21:41:19 +01:00
}
const createAccount = async (
data: SandboxBackend.Circuit.CircuitAccountRequest,
): Promise<HttpResponseOk<void>> => {
const res = await request<void>(`circuit-api/accounts`, {
method: "POST",
data,
2023-02-10 13:51:37 +01:00
contentType: "json",
2023-02-08 21:41:19 +01:00
});
2023-02-10 13:51:37 +01:00
await mutateAll(/.*circuit-api\/accounts.*/);
2023-02-08 21:41:19 +01:00
return res;
};
const updateAccount = async (
account: string,
data: SandboxBackend.Circuit.CircuitAccountReconfiguration,
): Promise<HttpResponseOk<void>> => {
const res = await request<void>(`circuit-api/accounts/${account}`, {
method: "PATCH",
data,
2023-02-10 13:51:37 +01:00
contentType: "json",
2023-02-08 21:41:19 +01:00
});
2023-02-10 13:51:37 +01:00
await mutateAll(/.*circuit-api\/accounts.*/);
2023-02-08 21:41:19 +01:00
return res;
};
const deleteAccount = async (
account: string,
): Promise<HttpResponseOk<void>> => {
const res = await request<void>(`circuit-api/accounts/${account}`, {
method: "DELETE",
2023-02-10 13:51:37 +01:00
contentType: "json",
2023-02-08 21:41:19 +01:00
});
2023-02-10 13:51:37 +01:00
await mutateAll(/.*circuit-api\/accounts.*/);
2023-02-08 21:41:19 +01:00
return res;
};
const changePassword = async (
account: string,
data: SandboxBackend.Circuit.AccountPasswordChange,
): Promise<HttpResponseOk<void>> => {
const res = await request<void>(`circuit-api/accounts/${account}/auth`, {
method: "PATCH",
data,
2023-02-10 13:51:37 +01:00
contentType: "json",
2023-02-08 21:41:19 +01:00
});
return res;
};
return { createAccount, deleteAccount, updateAccount, changePassword };
}
export function useCircuitAccountAPI(): CircuitAccountAPI {
const { request } = useAuthenticatedBackend();
2023-02-10 13:51:37 +01:00
const mutateAll = useMatchMutate();
const { state } = useBackendContext();
2023-02-08 21:41:19 +01:00
if (state.status === "loggedOut") {
2023-02-10 13:51:37 +01:00
throw Error("access-api can't be used when the user is not logged In");
2023-02-08 21:41:19 +01:00
}
const account = state.username;
const updateAccount = async (
data: SandboxBackend.Circuit.CircuitAccountReconfiguration,
): Promise<HttpResponseOk<void>> => {
const res = await request<void>(`circuit-api/accounts/${account}`, {
method: "PATCH",
data,
2023-02-10 13:51:37 +01:00
contentType: "json",
2023-02-08 21:41:19 +01:00
});
2023-02-10 13:51:37 +01:00
await mutateAll(/.*circuit-api\/accounts.*/);
2023-02-08 21:41:19 +01:00
return res;
};
const changePassword = async (
data: SandboxBackend.Circuit.AccountPasswordChange,
): Promise<HttpResponseOk<void>> => {
const res = await request<void>(`circuit-api/accounts/${account}/auth`, {
method: "PATCH",
data,
2023-02-10 13:51:37 +01:00
contentType: "json",
2023-02-08 21:41:19 +01:00
});
return res;
};
return { updateAccount, changePassword };
}
export interface AdminAccountAPI {
createAccount: (
data: SandboxBackend.Circuit.CircuitAccountRequest,
) => Promise<HttpResponseOk<void>>;
deleteAccount: (account: string) => Promise<HttpResponseOk<void>>;
updateAccount: (
account: string,
2023-02-10 13:51:37 +01:00
data: SandboxBackend.Circuit.CircuitAccountReconfiguration,
2023-02-08 21:41:19 +01:00
) => Promise<HttpResponseOk<void>>;
changePassword: (
account: string,
2023-02-10 13:51:37 +01:00
data: SandboxBackend.Circuit.AccountPasswordChange,
2023-02-08 21:41:19 +01:00
) => Promise<HttpResponseOk<void>>;
}
export interface CircuitAccountAPI {
updateAccount: (
2023-02-10 13:51:37 +01:00
data: SandboxBackend.Circuit.CircuitAccountReconfiguration,
2023-02-08 21:41:19 +01:00
) => Promise<HttpResponseOk<void>>;
changePassword: (
2023-02-10 13:51:37 +01:00
data: SandboxBackend.Circuit.AccountPasswordChange,
2023-02-08 21:41:19 +01:00
) => Promise<HttpResponseOk<void>>;
}
export interface InstanceTemplateFilter {
//FIXME: add filter to the template list
position?: string;
}
2023-02-10 13:51:37 +01:00
async function getBusinessStatus(
request: ReturnType<typeof useApiContext>["request"],
url: string,
basicAuth: { username: string; password: string },
): Promise<boolean> {
try {
const result = await request<
HttpResponseOk<SandboxBackend.Circuit.CircuitAccountData>
>(url, `circuit-api/accounts/${basicAuth.username}`, { basicAuth });
return result.ok;
} catch (error) {
return false;
2023-02-08 21:41:19 +01:00
}
2023-02-10 13:51:37 +01:00
}
export function useBusinessAccountFlag(): boolean | undefined {
const [isBusiness, setIsBusiness] = useState<boolean | undefined>();
const { state } = useBackendContext();
const { request } = useApiContext();
const creds =
state.status === "loggedOut"
? undefined
: { username: state.username, password: state.password };
useEffect(() => {
if (!creds) return;
getBusinessStatus(request, state.url, creds)
.then((result) => {
setIsBusiness(result);
})
.catch((error) => {
setIsBusiness(false);
});
2023-02-08 21:41:19 +01:00
});
2023-02-10 13:51:37 +01:00
return isBusiness;
2023-02-08 21:41:19 +01:00
}
2023-02-10 13:51:37 +01:00
export function useBusinessAccountDetails(
account: string,
): HttpResponse<
SandboxBackend.Circuit.CircuitAccountData,
SandboxBackend.SandboxError
> {
2023-02-08 21:41:19 +01:00
const { fetcher } = useAuthenticatedBackend();
2023-02-16 16:14:24 +01:00
const { data, error } = useSWR<
2023-02-08 21:41:19 +01:00
HttpResponseOk<SandboxBackend.Circuit.CircuitAccountData>,
RequestError<SandboxBackend.SandboxError>
>([`circuit-api/accounts/${account}`], 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.info;
return { loading: true };
}
interface PaginationFilter {
2023-02-10 13:51:37 +01:00
account?: string;
page?: number;
2023-02-08 21:41:19 +01:00
}
2023-02-10 13:51:37 +01:00
export function useBusinessAccounts(
2023-02-08 21:41:19 +01:00
args?: PaginationFilter,
2023-02-10 13:51:37 +01:00
): HttpResponsePaginated<
SandboxBackend.Circuit.CircuitAccounts,
SandboxBackend.SandboxError
> {
2023-02-08 21:41:19 +01:00
const { sandboxAccountsFetcher } = useAuthenticatedBackend();
const [page, setPage] = useState(0);
const {
data: afterData,
error: afterError,
// isValidating: loadingAfter,
2023-02-16 16:14:24 +01:00
} = useSWR<
2023-02-08 21:41:19 +01:00
HttpResponseOk<SandboxBackend.Circuit.CircuitAccounts>,
RequestError<SandboxBackend.SandboxError>
2023-02-10 13:51:37 +01:00
>(
[`circuit-api/accounts`, args?.page, PAGE_SIZE, args?.account],
sandboxAccountsFetcher,
{
refreshInterval: 0,
refreshWhenHidden: false,
revalidateOnFocus: false,
revalidateOnReconnect: false,
refreshWhenOffline: false,
errorRetryCount: 0,
errorRetryInterval: 1,
shouldRetryOnError: false,
keepPreviousData: true,
},
);
2023-02-08 21:41:19 +01:00
// const [lastAfter, setLastAfter] = useState<
// HttpResponse<SandboxBackend.Circuit.CircuitAccounts, SandboxBackend.SandboxError>
// >({ loading: true });
// useEffect(() => {
// if (afterData) setLastAfter(afterData);
// }, [afterData]);
// if the query returns less that we ask, then we have reach the end or beginning
const isReachingEnd =
afterData && afterData.data?.customers?.length < PAGE_SIZE;
const isReachingStart = false;
const pagination = {
isReachingEnd,
isReachingStart,
loadMore: () => {
if (!afterData || isReachingEnd) return;
if (afterData.data?.customers?.length < MAX_RESULT_SIZE) {
setPage(page + 1);
}
},
loadMorePrev: () => {
2023-02-10 13:51:37 +01:00
null;
2023-02-08 21:41:19 +01:00
},
};
const result = useMemo(() => {
2023-02-10 13:51:37 +01:00
const customers = !afterData ? [] : afterData?.data?.customers ?? [];
return { ok: true as const, data: { customers }, ...pagination };
}, [afterData?.data]);
2023-02-08 21:41:19 +01:00
if (afterError) return afterError.info;
if (afterData) {
2023-02-10 13:51:37 +01:00
return result;
2023-02-08 21:41:19 +01:00
}
// if (loadingAfter)
// return { loading: true, data: { customers } };
// if (afterData) {
// return { ok: true, data: { customers }, ...pagination };
// }
return { loading: true };
}
export function useCashouts(): HttpResponse<
(SandboxBackend.Circuit.CashoutStatusResponse & WithId)[],
SandboxBackend.SandboxError
> {
const { fetcher, multiFetcher } = useAuthenticatedBackend();
2023-02-16 16:14:24 +01:00
const { data: list, error: listError } = useSWR<
2023-02-08 21:41:19 +01:00
HttpResponseOk<SandboxBackend.Circuit.Cashouts>,
RequestError<SandboxBackend.SandboxError>
>([`circuit-api/cashouts`], fetcher, {
refreshInterval: 0,
refreshWhenHidden: false,
revalidateOnFocus: false,
revalidateOnReconnect: false,
refreshWhenOffline: false,
});
const paths = (list?.data.cashouts || []).map(
(cashoutId) => `circuit-api/cashouts/${cashoutId}`,
);
2023-02-16 16:14:24 +01:00
const { data: cashouts, error: productError } = useSWR<
2023-02-08 21:41:19 +01:00
HttpResponseOk<SandboxBackend.Circuit.CashoutStatusResponse>[],
RequestError<SandboxBackend.SandboxError>
>([paths], multiFetcher, {
refreshInterval: 0,
refreshWhenHidden: false,
revalidateOnFocus: false,
revalidateOnReconnect: false,
refreshWhenOffline: false,
});
if (listError) return listError.info;
if (productError) return productError.info;
if (cashouts) {
const dataWithId = cashouts.map((d) => {
//take the id from the queried url
return {
...d.data,
id: d.info?.url.replace(/.*\/cashouts\//, "") || "",
};
});
return { ok: true, data: dataWithId };
}
return { loading: true };
}