76 lines
2.1 KiB
TypeScript
76 lines
2.1 KiB
TypeScript
"use client";
|
|
|
|
import { useEffect, useRef, useState } from "react";
|
|
import { useRouter } from "next/navigation";
|
|
|
|
import { usePaymentRouteFlow } from "@/app/_hooks/use-payment-route-flow";
|
|
import type { PayChannel } from "@/data/schemas/payment";
|
|
import { DEFAULT_CHARACTER_SLUG } from "@/data/constants/character";
|
|
import {
|
|
consumeSubscriptionExitUrl,
|
|
resolveSubscriptionSuccessExitUrl,
|
|
type SubscriptionReturnTo,
|
|
} from "@/lib/navigation/subscription_exit";
|
|
|
|
import type { SubscriptionType } from "./subscription-screen.helpers";
|
|
|
|
export interface UseSubscriptionPaymentFlowInput {
|
|
subscriptionType: SubscriptionType;
|
|
shouldResumePendingOrder: boolean;
|
|
returnTo: SubscriptionReturnTo;
|
|
initialPayChannel: PayChannel;
|
|
characterSlug?: string;
|
|
}
|
|
|
|
export function useSubscriptionPaymentFlow({
|
|
subscriptionType,
|
|
shouldResumePendingOrder,
|
|
returnTo,
|
|
initialPayChannel,
|
|
characterSlug = DEFAULT_CHARACTER_SLUG,
|
|
}: UseSubscriptionPaymentFlowInput) {
|
|
const router = useRouter();
|
|
const { payment, paymentDispatch } = usePaymentRouteFlow({
|
|
initialPayChannel,
|
|
paymentType: subscriptionType,
|
|
shouldResumePendingOrder,
|
|
});
|
|
const successDialogShownOrderRef = useRef<string | null>(null);
|
|
const [showPaymentSuccessDialog, setShowPaymentSuccessDialog] =
|
|
useState(false);
|
|
|
|
useEffect(() => {
|
|
if (!payment.isPaid || !payment.currentOrderId) return;
|
|
if (successDialogShownOrderRef.current === payment.currentOrderId) return;
|
|
|
|
successDialogShownOrderRef.current = payment.currentOrderId;
|
|
setShowPaymentSuccessDialog(true);
|
|
}, [payment.currentOrderId, payment.isPaid]);
|
|
|
|
const handleBackClick = () => {
|
|
void (async () => {
|
|
router.replace(
|
|
await consumeSubscriptionExitUrl(returnTo, characterSlug),
|
|
);
|
|
})();
|
|
};
|
|
|
|
const handlePaymentSuccessClose = () => {
|
|
setShowPaymentSuccessDialog(false);
|
|
paymentDispatch({ type: "PaymentReset" });
|
|
void (async () => {
|
|
router.replace(
|
|
await resolveSubscriptionSuccessExitUrl(returnTo, characterSlug),
|
|
);
|
|
})();
|
|
};
|
|
|
|
return {
|
|
payment,
|
|
paymentDispatch,
|
|
showPaymentSuccessDialog,
|
|
handleBackClick,
|
|
handlePaymentSuccessClose,
|
|
};
|
|
}
|