diff --git a/jam-ui/src/components/jamtracks/JKJamTrackPurchaseButton.js b/jam-ui/src/components/jamtracks/JKJamTrackPurchaseButton.js index 0b7acc889..be948a394 100644 --- a/jam-ui/src/components/jamtracks/JKJamTrackPurchaseButton.js +++ b/jam-ui/src/components/jamtracks/JKJamTrackPurchaseButton.js @@ -8,34 +8,60 @@ import { useShoppingCart } from '../../hooks/useShoppingCart'; import { Link } from 'react-router-dom'; import { useTranslation } from 'react-i18next'; import JKTooltip from '../common/JKTooltip'; +import { placeOrder, updateUser } from '../../helpers/rest'; const JKJamTrackPurchaseButton = ({ jamTrack }) => { const history = useHistory(); const { currentUser } = useAuth(); - const { addCartItem } = useShoppingCart(); + const { addCartItem, getCartItems, hasOnlyFreeItemsInShoppingCart } = useShoppingCart(); const { t } = useTranslation('jamtracks'); - const addToCart = async () => { + if (!currentUser) { + return; + } const options = { id: jamTrack.id, variant: 'full' }; - if (await addCartItem(options)) { - toast.success(t('search.list.add_success_alert')); - history.push('/shopping-cart'); - } else { - console.log('Add to Cart Error'); + + try { + const resp = await addCartItem(options); + console.log('resp1', resp); + if(resp.fast_reedem){ //if this is a free jamtrack + //get shopping cart items and see if all are free + if(!hasOnlyFreeItemsInShoppingCart()){ + history.push('/jamtracks'); + }else{ + const purchadeResp = await placeOrder(); + console.log('resp2', purchadeResp); + if(purchadeResp.ok){ + const userResp = await updateUser(currentUser.id); + console.log('resp3', userResp); + if(userResp.ok){ + history.push('/checkout/success?free=yes&jamtrackId=' + jamTrack.id); + } + } + } + + }else{ //if this is a paid jamtrack + toast.success(t('search.list.add_success_alert')); + history.push('/shopping-cart'); + } + } catch (error) { + console.log(error); toast.error(t('search.list.add_error_alert')); + } + }; return ( <> - {jamTrack.purchaed ? ( - + {jamTrack.purchased ? ( + + {t('search.list.purchased')} + ) : jamTrack.allow_free && currentUser && currentUser.show_free_jamtrack ? ( <>