diff options
Diffstat (limited to 'packages/aml-backoffice-ui/src/hooks/useCases.ts')
-rw-r--r-- | packages/aml-backoffice-ui/src/hooks/useCases.ts | 94 |
1 files changed, 94 insertions, 0 deletions
diff --git a/packages/aml-backoffice-ui/src/hooks/useCases.ts b/packages/aml-backoffice-ui/src/hooks/useCases.ts new file mode 100644 index 000000000..04b7c383b --- /dev/null +++ b/packages/aml-backoffice-ui/src/hooks/useCases.ts @@ -0,0 +1,94 @@ +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<AmlExchangeBackend.AmlRecords>, + RequestError<AmlExchangeBackend.AmlError> + >( + [ + `aml/${account}/decisions/${AmlExchangeBackend.AmlState[state]}`, + page, + PAGE_SIZE, + signature, + ], + paginatedFetcher, + ); + + const [lastAfter, setLastAfter] = useState< + HttpResponse<AmlExchangeBackend.AmlRecords, AmlExchangeBackend.AmlError> + >({ 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 }; +} |