import { useEffect, useState } from "preact/hooks"; import { AmlExchangeBackend } from "../types.js"; import { HttpResponse, HttpResponseOk, HttpResponsePaginated, RequestError, } from "@gnu-taler/web-util/browser"; // FIX default import https://github.com/microsoft/TypeScript/issues/49189 import _useSWR, { SWRHook } from "swr"; import { usePublicBackend } from "./useBackend.js"; import { AccountId, buildQuerySignature } from "../account.js"; import { useOfficer } from "./useOfficer.js"; const useSWR = _useSWR as unknown as SWRHook; const PAGE_SIZE = 10; const MAX_RESULT_SIZE = PAGE_SIZE * 2 - 1; /** * FIXME: mutate result when balance change (transaction ) * @param account * @param args * @returns */ export function useCases( account: AccountId, state: AmlExchangeBackend.AmlState, signature: string | undefined, ): HttpResponsePaginated< AmlExchangeBackend.AmlRecords, AmlExchangeBackend.AmlError > { const { paginatedFetcher } = usePublicBackend(); const [page, setPage] = useState(1); const { data: afterData, error: afterError, isValidating: loadingAfter, } = useSWR< HttpResponseOk, RequestError >( [ `aml/${account}/decisions/${AmlExchangeBackend.AmlState[state]}`, page, PAGE_SIZE, signature, ], paginatedFetcher, ); const [lastAfter, setLastAfter] = useState< HttpResponse >({ loading: true }); useEffect(() => { if (afterData) setLastAfter(afterData); }, [afterData]); if (afterError) { return afterError.cause; } // if the query returns less that we ask, then we have reach the end or beginning const isReachingEnd = afterData && afterData.data && afterData.data.records.length < PAGE_SIZE; const isReachingStart = false; const pagination = { isReachingEnd, isReachingStart, loadMore: () => { if (!afterData || isReachingEnd) return; if (afterData.data && afterData.data.records.length < MAX_RESULT_SIZE) { setPage(page + 1); } }, loadMorePrev: () => { null; }, }; const records = !afterData ? [] : ((afterData ?? lastAfter).data ?? { records: [] }).records; console.log("afterdata", afterData, lastAfter, records) if (loadingAfter) return { loading: true, data: { records } }; if (afterData) { return { ok: true, data: { records }, ...pagination }; } return { loading: true }; } const example1: AmlExchangeBackend.AmlRecords = { records: [ { current_state: 0, h_payto: "QWEQWEQWEQWEWQE", rowid: 1, threshold: "USD 100", }, { current_state: 1, h_payto: "ASDASDASD", rowid: 1, threshold: "USD 100", }, { current_state: 2, h_payto: "ZXCZXCZXCXZC", rowid: 1, threshold: "USD 1000", }, { current_state: 0, h_payto: "QWEQWEQWEQWEWQE", rowid: 1, threshold: "USD 100", }, { current_state: 1, h_payto: "ASDASDASD", rowid: 1, threshold: "USD 100", }, { current_state: 2, h_payto: "ZXCZXCZXCXZC", rowid: 1, threshold: "USD 1000", }, ].map((e, idx) => { e.rowid = idx; e.threshold = `${e.threshold}${idx}`; return e; }), }; export const exampleResponse: HttpResponsePaginated = { ok: true, data: example1, loadMore: () => {}, loadMorePrev: () => {}, }