import { useCallback } from "react"; import useSWR from "swr"; import { useClient } from "./AppConfig/AppConfig.tsx"; import { Failure, Success } from "./async-op.ts"; import { swrResponseToResult } from "./result/swr.ts"; import { useCurrentUser } from "./store/index.tsx"; import type { FailurePayload } from "./types.ts"; function useGetOwnedProduct(productCode: string) { const client = useClient(); const swr = useSWR( `getOwnedProduct:${productCode}`, useCallback(() => { return client.getOwnedProduct(productCode); }, [productCode]), ); return swrResponseToResult(swr); } export type ProductStatusSuccessPayload = /** * The user should authenticate before proceeding to checkout. */ | { type: "AUTHENTICATE" } /** * The user can proceed to checkout. */ | { type: "PURCHASE" } /** * The user already owns this product. The `downloadUrl` property should be * used to let the user download their files. */ | { type: "DOWNLOAD"; downloadUrl: string }; /** * Wraps ITC client's getOwnedProduct call and maps it's responses into * {@link ProductStatusSuccessPayload} which is more appropriate for product * purchase pages. */ export function useGetProductStatus(productCode: string) { const result = useGetOwnedProduct(productCode); const currentUser = useCurrentUser(); if (result.isPending) { return result; } if (result.isFailure) { const { failure } = result; if (failure.type === "API_ERROR") { // The no currentUser case is possible in case the user is logged into ITC // via a domain-wide cookie, but they have not yet logged in this app. if (failure.code === 401 || !currentUser) { return new Success({ type: "AUTHENTICATE", }); } if (failure.code === 403) { return new Success({ type: "PURCHASE", }); } } // Other errors should be handled by the default error handling return result; } // This shouldn't happen in practice, as this particular endpoint errors out // if a product link fails to generate. const { downloadUrl } = result.value; if (!downloadUrl) { return new Failure({ type: "UNKNOWN_ERROR", }); } return new Success({ type: "DOWNLOAD", downloadUrl, }); }