From 00143e477f753546db525d587285dded1ec91727 Mon Sep 17 00:00:00 2001 From: Ashelyn Dawn Date: Fri, 27 Nov 2020 20:00:15 -0700 Subject: [PATCH] Handle invalid coupon and display coupon errors --- api/orders.js | 3 +++ db/models/order.js | 8 +++++--- pages/store/checkout/index.js | 24 +++++++++++++++++++----- 3 files changed, 27 insertions(+), 8 deletions(-) diff --git a/api/orders.js b/api/orders.js index 147050e..4fb7152 100644 --- a/api/orders.js +++ b/api/orders.js @@ -63,6 +63,9 @@ router.post('/current/coupon', ensureCart, parseJSON, validate.coupon, validate. const coupon = await db.coupon.find(req.body.code) + if(!coupon) + throw new Error(`No such coupon: "${req.body.code}"`) + const currentTransaction = origOrder .transactions.find(transaction => ( transaction.payment_state === 'started' diff --git a/db/models/order.js b/db/models/order.js index c94645a..9193bff 100644 --- a/db/models/order.js +++ b/db/models/order.js @@ -151,12 +151,14 @@ order.addAddress = async function (transaction, address){ order.updateTax = async function(transaction_uuid){ const _order = await order.findForTransaction(transaction_uuid) - if(!_order.address) - throw new Error("Order has no address"); + if(!_order.address){ + debug("Skipping tax because order has no address yet") + return _order + } if(_order.address.state !== 'UT'){ debug("Skipping tax for state: " + _order.address.state); - return + return _order } const {item_total_price, coupon_effective_discount} = _order.transactions.find(t => t.uuid === transaction_uuid) diff --git a/pages/store/checkout/index.js b/pages/store/checkout/index.js index fc02177..f31700f 100644 --- a/pages/store/checkout/index.js +++ b/pages/store/checkout/index.js @@ -21,6 +21,7 @@ CheckoutSummary.getInitialProps = async function({ctx: {axios}}){ export default function CheckoutSummary({order: _order}){ const user = useUser(); const [order, updateOrder] = useState(_order) + const [couponError, setCouponError] = useState(null) const currentTransaction = order .transactions.find(transaction => ( @@ -45,9 +46,22 @@ export default function CheckoutSummary({order: _order}){ const onCouponSubmit = async ev => { if(ev) ev.preventDefault() + setCouponError(null) + const code = couponRef.current?.value - const {data: updatedOrder} = await axios.post(`/api/orders/current/coupon`, {code}) - updateOrder(updatedOrder) + + try { + const {data: updatedOrder} = await axios.post(`/api/orders/current/coupon`, {code}) + console.log(order, updatedOrder) + updateOrder(updatedOrder) + } catch (err) { + console.log(err.response.data.errors) + const message = err?.response?.data?.error?.message + || err.response?.data?.errors?.find(e => e.param === 'code')?.msg + || 'Unknown error applying coupon' + + setCouponError(message) + } } // For Stripe checkout @@ -127,9 +141,9 @@ export default function CheckoutSummary({order: _order}){ ) : (
- -
- + setCouponError(null)} error={couponError} /> +
+
)