infoalloggi-monorepo/apps/infoalloggi/src/pages/servizio/pagamento/[ordineId].tsx

118 lines
2.9 KiB
TypeScript

import { loadStripe } from "@stripe/stripe-js";
import type { GetServerSideProps } from "next";
import { AcquistoProcessing } from "~/components/acquisto_processing";
import { AreaRiservataLayout } from "~/components/Layout";
import { LoadingPage } from "~/components/loading";
import { Status500 } from "~/components/status-page";
import { env } from "~/env.mjs";
import type { NextPageWithLayout } from "~/pages/_app";
import { useTranslation } from "~/providers/I18nProvider";
import type { OrdiniOrdineId } from "~/schemas/public/Ordini";
import { TrpcAuthedFetchingIstance } from "~/server/utils/ssgHelper";
import { zOrdineId } from "~/server/utils/zod_types";
import { api } from "~/utils/api";
type ServizioPurchaseProps = {
ordineId: OrdiniOrdineId;
};
const ServicePurchasePage: NextPageWithLayout<ServizioPurchaseProps> = ({
ordineId,
}: ServizioPurchaseProps) => {
const { data, isLoading } = api.servizio.getServizioPaymentData.useQuery({
ordineId,
});
const { t } = useTranslation();
const stripePromise = loadStripe(env.NEXT_PUBLIC_STRIPE_PUBLIC_KEY);
if (isLoading) {
return <LoadingPage />;
}
if (!data) {
return <Status500 />;
}
return (
<div className="mx-auto w-full max-w-6xl grow space-y-4 p-2 sm:px-8 sm:py-4">
<div className="flex justify-between">
<h3 className="text-primary text-3xl font-bold">
{t.acquisto.pagamento}
</h3>
</div>
<AcquistoProcessing
paymentId={data.payment.id}
stripePromise={stripePromise}
packId={data.ordine.packid}
/>
</div>
);
};
ServicePurchasePage.getLayout = function getLayout(page) {
return (
<AreaRiservataLayout noSidebar noFooter>
{page}
</AreaRiservataLayout>
);
};
export default ServicePurchasePage;
export const getServerSideProps = (async (context) => {
const id = context.params?.ordineId;
if (typeof id !== "string") {
console.error("Error: ordineId is not a string");
return {
redirect: {
destination: "/500",
permanent: false,
},
};
}
const parsed = zOrdineId.safeParse(id);
if (!parsed.success) {
console.error("Error parsing ordineId", parsed.error);
return {
redirect: {
destination: "/500",
permanent: false,
},
};
}
const access_token = context.req.cookies.access_token;
const helper = await TrpcAuthedFetchingIstance({ access_token });
if (helper) {
const isAwaitingPayment =
await helper.trpc.servizio.isOrdineAwaitingPayment.fetch({
ordineId: parsed.data,
});
if (!isAwaitingPayment) {
return {
redirect: {
destination: "/area-riservata/dashboard",
permanent: false,
},
};
}
await helper.trpc.servizio.getServizioPaymentData.prefetch({
ordineId: parsed.data,
});
return {
props: {
trpcState: helper.trpc.dehydrate(),
ordineId: parsed.data,
},
};
}
return {
redirect: {
destination: "/500",
permanent: false,
},
};
}) satisfies GetServerSideProps<ServizioPurchaseProps>;