import React, { useEffect } from 'react'; import { useAppDispatch } from '@akinon/next/redux/hooks'; import { useForm } from 'react-hook-form'; import { yupResolver } from '@hookform/resolvers/yup'; import * as yup from 'yup'; import { basketApi, useApplyVoucherCodeMutation, useRemoveVoucherCodeMutation } from '@akinon/next/data/client/basket'; import { Basket, Error } from '@akinon/next/types'; import { Button, Input, Price } from '@theme/components'; import { pushBeginCheckout } from '@theme/utils/gtm'; import { ROUTES } from '@theme/routes'; import { useLocalization, useRouter } from '@akinon/next/hooks'; import PluginModule, { Component } from '@akinon/next/components/plugin-module'; import clsx from 'clsx'; interface Props { basket: Basket; } const voucherCodeFormSchema = (t) => yup.object().shape({ voucherCode: yup.string().required(t('basket.summary.form.error.required')) }); export const Summary = (props: Props) => { const { t } = useLocalization(); const { basket } = props; const router = useRouter(); const { register, handleSubmit, setError, reset, formState: { errors } } = useForm<{ voucherCode: string; }>({ resolver: yupResolver(voucherCodeFormSchema(t)) }); const dispatch = useAppDispatch(); const [applyVoucherCodeMutation] = useApplyVoucherCodeMutation(); const [removeVoucherCodeMutation] = useRemoveVoucherCodeMutation(); useEffect(() => { if (basket.voucher_code) { reset({ voucherCode: basket.voucher_code }); } }, [basket, reset]); const removeVoucherCode = () => { removeVoucherCodeMutation() .unwrap() .then((basket) => dispatch( basketApi.util.updateQueryData( 'getBasket', undefined, (draftBasket) => { Object.assign(draftBasket, basket); } ) ) ) .catch((error: Error) => { setError('voucherCode', { message: error.data.non_field_errors }); }); }; const onSubmit = (data) => { applyVoucherCodeMutation({ voucher_code: data.voucherCode }) .unwrap() .then((basket) => dispatch( basketApi.util.updateQueryData( 'getBasket', undefined, (draftBasket) => { Object.assign(draftBasket, basket); } ) ) ) .catch((error: Error) => { setError('voucherCode', { message: error.data.non_field_errors }); }); }; const checkoutProviderProps = { className: clsx([ 'py-2.5', 'bg-black', 'relative', 'hover:bg-black', 'before:content-[""]', 'before:w-6', 'before:h-6', 'before:bg-white', 'before:absolute', 'before:rounded-r-[18px]', 'before:left-0', 'after:content-[""]', 'after:absolute', 'after:w-3', 'after:h-3', 'after:bg-[#d02c2f]', 'after:rounded-xl', 'after:left-1' ]) }; useEffect(() => { const products = basket.basketitem_set.map((basketItem) => ({ ...basketItem.product })); pushBeginCheckout(products); }, [basket]); return (
{t('basket.summary.subtotal')} ( {basket.basketitem_set .map((x) => x.quantity) .reduce((a, b) => a + b)}{' '} {t('basket.summary.items')})
{discount.description}
{t('basket.summary.discounts_total')}
{t('basket.summary.form.title')}