wallet-core/packages/taler-wallet-webextension/src/cta/InvoicePay/state.ts

85 lines
2.4 KiB
TypeScript
Raw Normal View History

/*
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/>
*/
2022-08-31 16:46:39 +02:00
import { AbsoluteTime, Amounts, TalerErrorDetail, TalerProtocolTimestamp } from "@gnu-taler/taler-util";
2022-08-31 05:20:35 +02:00
import { TalerError } from "@gnu-taler/taler-wallet-core";
import { useState } from "preact/hooks";
import { useAsyncAsHook } from "../../hooks/useAsyncAsHook.js";
import * as wxApi from "../../wxApi.js";
import { Props, State } from "./index.js";
export function useComponentState(
2022-08-31 16:46:39 +02:00
{ talerPayPullUri, onClose }: Props,
api: typeof wxApi,
): State {
2022-08-31 05:20:35 +02:00
const hook = useAsyncAsHook(async () => {
return await api.checkPeerPullPayment({
talerUri: talerPayPullUri
})
}, [])
const [operationError, setOperationError] = useState<TalerErrorDetail | undefined>(undefined)
if (!hook) {
return {
status: "loading",
error: undefined,
}
}
if (hook.hasError) {
return {
status: "loading-uri",
error: hook,
};
}
2022-08-31 16:46:39 +02:00
const { amount: purseAmount, contractTerms, peerPullPaymentIncomingId } = hook.response
const amount: string = contractTerms?.amount
const summary: string | undefined = contractTerms?.summary
const expiration: TalerProtocolTimestamp | undefined = contractTerms?.purse_expiration
2022-08-31 05:20:35 +02:00
async function accept(): Promise<void> {
try {
const resp = await api.acceptPeerPullPayment({
peerPullPaymentIncomingId
})
2022-08-31 16:46:39 +02:00
await onClose()
2022-08-31 05:20:35 +02:00
} catch (e) {
if (e instanceof TalerError) {
setOperationError(e.errorDetail)
}
console.error(e)
throw Error("error trying to accept")
}
}
return {
status: "ready",
2022-08-31 05:20:35 +02:00
amount: Amounts.parseOrThrow(amount),
error: undefined,
2022-08-31 05:20:35 +02:00
accept: {
onClick: accept
},
2022-08-31 16:46:39 +02:00
summary,
expiration: expiration ? AbsoluteTime.fromTimestamp(expiration) : undefined,
cancel: {
onClick: onClose
},
2022-08-31 05:20:35 +02:00
operationError
}
}