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

81 lines
2.2 KiB
TypeScript
Raw Normal View History

2022-07-31 01:55:41 +02: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 { Amounts } from "@gnu-taler/taler-util";
2022-10-25 17:23:08 +02:00
import { WalletApiOperation } from "@gnu-taler/taler-wallet-core";
2022-07-31 01:55:41 +02:00
import { useAsyncAsHook } from "../../hooks/useAsyncAsHook.js";
2022-10-25 17:23:08 +02:00
import { wxApi } from "../../wxApi.js";
2022-07-31 01:55:41 +02:00
import { Props, State } from "./index.js";
export function useComponentState(
2022-09-16 21:03:58 +02:00
{ talerTipUri, onCancel, onSuccess }: Props,
2022-07-31 01:55:41 +02:00
api: typeof wxApi,
): State {
const tipInfo = useAsyncAsHook(async () => {
if (!talerTipUri) throw Error("ERROR_NO-URI-FOR-TIP");
2022-10-25 17:23:08 +02:00
const tip = await api.wallet.call(WalletApiOperation.PrepareTip, { talerTipUri });
2022-07-31 01:55:41 +02:00
return { tip };
});
if (!tipInfo) {
return {
status: "loading",
error: undefined,
2022-09-16 19:29:35 +02:00
};
2022-07-31 01:55:41 +02:00
}
if (tipInfo.hasError) {
return {
status: "loading-uri",
error: tipInfo,
};
}
const { tip } = tipInfo.response;
const doAccept = async (): Promise<void> => {
2022-10-25 17:23:08 +02:00
const res = await api.wallet.call(WalletApiOperation.AcceptTip, { walletTipId: tip.walletTipId });
2022-09-16 21:03:58 +02:00
//FIX: this may not be seen since we are moving to the success also
2022-07-31 01:55:41 +02:00
tipInfo.retry();
2022-09-16 21:04:41 +02:00
onSuccess(res.transactionId);
2022-07-31 01:55:41 +02:00
};
const baseInfo = {
merchantBaseUrl: tip.merchantBaseUrl,
exchangeBaseUrl: tip.exchangeBaseUrl,
amount: Amounts.parseOrThrow(tip.tipAmountEffective),
error: undefined,
2022-08-31 16:46:39 +02:00
cancel: {
2022-09-16 19:29:35 +02:00
onClick: onCancel,
},
};
2022-07-31 01:55:41 +02:00
if (tip.accepted) {
return {
status: "accepted",
...baseInfo,
};
}
return {
status: "ready",
...baseInfo,
accept: {
onClick: doAccept,
},
};
}