|
| 1 | +import { basketQueries } from "./queries" |
| 2 | +import { useMutation, useQueryClient } from "@tanstack/react-query" |
| 3 | +import { basketsApi } from "../../clients" |
| 4 | +import type { BasketWithProduct } from "@mitodl/mitxonline-api-axios/v2" |
| 5 | + |
| 6 | +/** |
| 7 | + * Hook to add a product to the user's basket. |
| 8 | + * Creates or updates the basket, adding the specified product. |
| 9 | + * On success, automatically redirects to the checkout page. |
| 10 | + */ |
| 11 | +const useAddToBasket = () => { |
| 12 | + const queryClient = useQueryClient() |
| 13 | + return useMutation({ |
| 14 | + mutationFn: async (productId: number): Promise<BasketWithProduct> => { |
| 15 | + const response = await basketsApi.basketsCreateFromProductCreate({ |
| 16 | + product_id: productId, |
| 17 | + }) |
| 18 | + return response.data |
| 19 | + }, |
| 20 | + onSuccess: async () => { |
| 21 | + // Invalidate checkout query to ensure fresh data |
| 22 | + queryClient.invalidateQueries({ |
| 23 | + queryKey: basketQueries.checkout().queryKey, |
| 24 | + }) |
| 25 | + |
| 26 | + // Get checkout data and submit form to CyberSource |
| 27 | + try { |
| 28 | + const checkoutResponse = await basketsApi.basketsCheckoutRetrieve() |
| 29 | + const { url, payload } = checkoutResponse.data |
| 30 | + |
| 31 | + if (url && payload) { |
| 32 | + // Create a form and submit it to CyberSource |
| 33 | + const form = document.createElement("form") |
| 34 | + form.method = "POST" |
| 35 | + form.action = url |
| 36 | + |
| 37 | + // Add all payload fields as hidden inputs |
| 38 | + Object.entries(payload).forEach(([key, value]) => { |
| 39 | + const input = document.createElement("input") |
| 40 | + input.type = "hidden" |
| 41 | + input.name = key |
| 42 | + input.value = String(value) |
| 43 | + form.appendChild(input) |
| 44 | + }) |
| 45 | + |
| 46 | + document.body.appendChild(form) |
| 47 | + form.submit() |
| 48 | + } |
| 49 | + } catch (error) { |
| 50 | + console.error("Failed to get checkout URL:", error) |
| 51 | + } |
| 52 | + }, |
| 53 | + }) |
| 54 | +} |
| 55 | + |
| 56 | +/** |
| 57 | + * Hook to clear the user's basket. |
| 58 | + */ |
| 59 | +const useClearBasket = () => { |
| 60 | + const queryClient = useQueryClient() |
| 61 | + return useMutation({ |
| 62 | + mutationFn: async (): Promise<void> => { |
| 63 | + await basketsApi.basketsClearDestroy() |
| 64 | + }, |
| 65 | + onSuccess: () => { |
| 66 | + queryClient.invalidateQueries({ |
| 67 | + queryKey: basketQueries.checkout().queryKey, |
| 68 | + }) |
| 69 | + }, |
| 70 | + }) |
| 71 | +} |
| 72 | + |
| 73 | +export { basketQueries, useAddToBasket, useClearBasket } |
0 commit comments