Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[PWA-240] [feature]: Cart Price Summary #2092

Merged
merged 21 commits into from
Jan 15, 2020
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@
"execa": "~1.0.0",
"figures": "~2.0.0",
"first-run": "~2.0.0",
"fraql": "~1.2.1",
"graphql-tag": "~2.10.1",
"husky": "~1.3.1",
"identity-obj-proxy": "~3.0.0",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { useCallback, useEffect } from 'react';
import { useQuery } from '@apollo/react-hooks';
import { useCartContext } from '@magento/peregrine/lib/context/cart';

export const usePriceSummary = props => {
const [{ cartId }] = useCartContext();
const { error, loading, data } = useQuery(props.query, {
variables: {
cartId
},
fetchPolicy: 'no-cache'
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should verify that actions that modify the price summary values such as shipping method or adding a shipping address elsewhere also update the price summary even if no-cache is used here.

});

const handleProceedToCheckout = useCallback(() => {
// TODO: Navigate to checkout view
console.log('Going to checkout!');
}, []);

useEffect(() => {
if (error) {
console.error('GraphQL Error:', error);
}
}, [error]);

return {
handleProceedToCheckout,
hasError: !!error,
hasItems: data && !!data.cart.items.length,
isLoading: !!loading,
data
};
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import React from 'react';
import gql from 'fraql';
import { Price } from '@magento/peregrine';

const DEFAULT_AMOUNT = {
currency: 'USD',
value: 0
};

/**
* Reduces discounts array into a single amount.
*
* @param {Array} discounts
*/
const getDiscount = (discounts = []) => {
// discounts from data can be null
if (!discounts || !discounts.length) {
return DEFAULT_AMOUNT;
} else {
return {
currency: discounts[0].amount.currency,
value: discounts.reduce(
(acc, discount) => acc + discount.amount.value,
0
)
};
}
};

/**
* A component that renders the discount summary line item.
*
* @param {Object} props.classes
* @param {Object} props.data fragment response data
*/
const DiscountSummary = props => {
const { classes } = props;
const discount = getDiscount(props.data);

return discount.value ? (
<>
<span className={classes.lineItemLabel}>{'Discounts applied'}</span>
<span className={classes.price}>
{'(-'}
<Price
value={discount.value}
currencyCode={discount.currency}
/>
{')'}
</span>
</>
) : null;
};

DiscountSummary.fragments = {
discounts: gql`
fragment _ on CartPrices {
discounts {
Copy link
Contributor Author

@sirugh sirugh Jan 10, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In 2.3.3 we have discount, which is a "deprecated but functional" field in 2.3.4
In 2.3.4 we have discounts, which 2.3.3 does not have.

If we want to support both versions we will need to provide some way (build or runtime?) to determine which field is valid for the current backend.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am going to proceed with the assumption that we don't need to support 2.3.3, so discounts is valid.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am going to proceed with the assumption that we don't need to support 2.3.3, so discounts is valid.

We do need to support 2.3.3.

amount {
currency
value
}
label
}
}
`
};

export default DiscountSummary;
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import React from 'react';
import gql from 'fraql';
import { Price } from '@magento/peregrine';

/**
* Gift cards are an EE feature and we need some way to conditionally include
* this code and query in bundled assets. For now, this constant will be the
* toggle, but we may eventually need to do something like a build tool that can
* check schema for existence of "applied_gift_cards" and include this component
* if present.
*
* Right now, if `IS_EE == false`, this component returns a no-op, null function
* as well as an "empty" fragment so as to not break the GQL query of a parent.
*
* TODO: Solve this problem. This local toggle should not be long-lived, at least not past PWA-78.
*/
const IS_EE = false;

const DEFAULT_AMOUNT = {
currency: 'USD', // TODO: better default
value: 0
};

/**
* Reduces applied gift card amounts into a single amount.
*
* @param {Array} cards
*/
const getGiftCards = (cards = []) => {
if (!cards.length) {
return DEFAULT_AMOUNT;
} else {
return {
currency: 'USD',
value: cards.reduce(
(acc, card) => acc + card.applied_balance.value,
0
)
};
}
};

/**
* A component that renders the gift card summary line item.
*
* @param {Object} props.classes
* @param {Object} props.data fragment response data
*/
const GiftCardSummary = IS_EE
? props => {
const { classes } = props;

const cards = getGiftCards(props.data);

return cards.value ? (
<>
<span className={classes.lineItemLabel}>
{'Gift Card(s) applied'}
</span>
<span className={classes.price}>
{'(-'}
<Price
value={cards.value}
currencyCode={cards.currency}
/>
{')'}
</span>
</>
) : null;
}
: () => null;

GiftCardSummary.fragments = {
applied_gift_cards: IS_EE
? gql`
fragment _ on Cart {
applied_gift_cards {
applied_balance {
value
currency
}
}
}
`
: gql`
fragment _ on Cart {
__typename
}
`
};

export default GiftCardSummary;
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { default } from './priceSummary';
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
.root {
padding: 0 1rem 1rem 1rem;
}

.lineItems {
display: grid;
grid-row-gap: 0.75rem;
grid-template-columns: 50% 50%;
padding-bottom: 1rem;
line-height: 1.5rem;
}

.lineItemLabel {
justify-self: start;
}

.price {
justify-self: end;
}

.totalLabel {
composes: lineItemLabel;
font-weight: bold;
}

.totalPrice {
composes: price;
font-weight: bold;
}

.checkoutButton_container {
text-align: center;
}
136 changes: 136 additions & 0 deletions packages/venia-ui/lib/components/CartPage/PriceSummary/priceSummary.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
import React from 'react';
import gql from 'fraql';
import { Price } from '@magento/peregrine';
import { usePriceSummary } from '@magento/peregrine/lib/talons/CartPage/PriceSummary/usePriceSummary';
import Button from '../../Button';
import { mergeClasses } from '../../../classify';
import defaultClasses from './priceSummary.css';

import DiscountSummary from './discountSummary';
import GiftCardSummary from './giftCardSummary';
import ShippingSummary from './shippingSummary';
import TaxSummary from './taxSummary';

/**
* A component that fetches and renders cart data including:
* - subtotal
* - coupons applied
sirugh marked this conversation as resolved.
Show resolved Hide resolved
* - gift cards applied
* - estimated tax
* - estimated shipping
* - estimated total
*/
const PriceSummary = props => {
const classes = mergeClasses(defaultClasses, props.classes);
const talonProps = usePriceSummary({
query: PriceSummary.GET_PRICE_SUMMARY
sirugh marked this conversation as resolved.
Show resolved Hide resolved
});

const {
handleProceedToCheckout,
hasError,
hasItems,
isLoading,
data
} = talonProps;

if (hasError) {
return (
<div className={classes.root}>
An error occurred. Please refresh the page.
</div>
);
} else if (!hasItems || isLoading) {
return null;
}

const subtotal = data.cart.prices.subtotal_excluding_tax;
const discountData = data.cart.prices.discounts;
const giftCardData = data.cart.applied_gift_cards;
const taxData = data.cart.prices.applied_taxes;
const shippingData = data.cart.shipping_addresses;
const total = data.cart.prices.grand_total;

return (
<div className={classes.root}>
<div className={classes.lineItems}>
<span className={classes.lineItemLabel}>{'Subtotal'}</span>
<span className={classes.price}>
<Price
value={subtotal.value}
currencyCode={subtotal.currency}
/>
</span>
<DiscountSummary
classes={{
lineItemLabel: classes.lineItemLabel,
price: classes.price
}}
data={discountData}
/>
<GiftCardSummary
classes={{
lineItemLabel: classes.lineItemLabel,
price: classes.price
}}
data={giftCardData}
/>
<TaxSummary
classes={{
lineItemLabel: classes.lineItemLabel,
price: classes.price
}}
data={taxData}
/>
<ShippingSummary
classes={{
lineItemLabel: classes.lineItemLabel,
price: classes.price
}}
data={shippingData}
/>
<span className={classes.totalLabel}>{'Estimated Total'}</span>
<span className={classes.totalPrice}>
<Price value={total.value} currencyCode={total.currency} />
</span>
</div>
<div className={classes.checkoutButton_container}>
<Button priority={'high'} onClick={handleProceedToCheckout}>
{'PROCEED TO CHECKOUT'}
</Button>
</div>
</div>
);
};

// queries exported as static member to be used by refetchQueries.
PriceSummary.queries = {
GET_PRICE_SUMMARY: gql`
query getPriceSummary($cartId: String!) {
cart(cart_id: $cartId) {
id
items {
quantity
}
# Use fraql to compose inline, unnamed fragments...
# https://github.com/apollographql/graphql-tag/issues/237
${ShippingSummary.fragments.shipping_addresses}
prices {
${TaxSummary.fragments.applied_taxes}
${DiscountSummary.fragments.discounts}
grand_total {
currency
value
}
subtotal_excluding_tax {
currency
value
}
}
${GiftCardSummary.fragments.applied_gift_cards}
}
}
`
};

export default PriceSummary;
Loading