Files
crosscode-platform/apps/events/frontend/src/lib/onlinePayments.ts
T

52 lines
2.1 KiB
TypeScript

"use client";
import { useEffect, useState } from "react";
import { apiV2Data } from "@/lib/apiV2";
type ProvidersResponse = { providers: { id: string; label: string }[]; minimumAmount: number };
export type OnlinePayments = {
/** The answer has arrived (until then, nothing offers online payment). */
ready: boolean;
/** At least one payment provider is switched on and set up. */
available: boolean;
/** Online payments must be at least this much (R15). */
minimum: number;
/** Whether `amount` can be paid online now. */
canPay: (amount: number) => boolean;
/** Why `amount` can't be paid online, for showing instead of the button; null when it can. */
reason: (amount: number) => string | null;
};
// One request per page load, shared by every component that asks.
let pending: Promise<ProvidersResponse | null> | null = null;
function load() {
if (!pending) pending = (apiV2Data("get", "/payments/providers") as Promise<ProvidersResponse>).catch(() => null);
return pending;
}
/**
* Whether people can pay online: only when a payment provider is enabled (Site settings →
* Payments) and the amount is at least the online minimum. "Pay online" buttons use this to
* stay hidden otherwise.
*/
export function useOnlinePayments(): OnlinePayments {
const [state, setState] = useState<{ ready: boolean; available: boolean; minimum: number }>({ ready: false, available: false, minimum: 15 });
useEffect(() => {
let cancelled = false;
load().then(res => {
if (!cancelled) setState({ ready: true, available: !!res && res.providers.length > 0, minimum: res?.minimumAmount ?? 15 });
});
return () => { cancelled = true; };
}, []);
const canPay = (amount: number) => state.ready && state.available && amount >= state.minimum;
const reason = (amount: number) => {
if (!state.ready || canPay(amount)) return null;
if (!state.available) return "Online payment isn't available at the moment. You can pay at the event, or contact the organiser.";
return `Online payments must be at least R${state.minimum}. You can pay this at the event.`;
};
return { ...state, canPay, reason };
}