Start learning free

LESSON 36 OF 58 · FULL-STACK: CART AND CHECKOUT

Project: A Discount Code

Practice

A discount code is a row in a table. The given db.js adds a coupons table, where WELCOME10 takes 10% off and SPRING20 takes 20% off. It also adds a cart_coupons table that holds one code per user. The server checks the code, not the page. An unknown code answers 404, and the given coupon box shows the server's message.

The percent comes off in cartOf, the function that builds every cart. That way the cart page, the payment and the receipt all see the same lower total. The payment provider takes whole dollars, so round the discount. For example, 15% off a $29 lamp:

Math.round(29 * 15 / 100)   // 4.35 rounds to 4: the lamp costs $25

A table whose primary key is user_id holds one row per user, and INSERT OR REPLACE swaps the old row for the new one: INSERT OR REPLACE INTO wishlists (user_id, name) VALUES (?, ?). The order keeps its items at full price and saves its discount, so its total is the items' sum minus the discount. After the payment, the code is deleted along with the cart.

The check logs in as Ana, adds the Mug and the Lamp, tries three codes and pays:

POST /api/cart/coupon {"code": "HELLO5"}     →  404  alert: Unknown discount code
POST /api/cart/coupon {"code": "WELCOME10"}  →  200  Discount (WELCOME10): -$4, Total: $37
POST /api/cart/coupon {"code": "SPRING20"}   →  200  Discount (SPRING20): -$8, Total: $33
click "Pay"    →  Order 8, Status: paid, Total: $33
GET /payments  →  200  [{"amount": 33, "id": "pay_1", "order_id": 8, "status": "succeeded"}]
open /cart     →  Your cart is empty, Total: $0
shop.db: order 8 | paid | discount 8 | items_total 41;   cart_coupons: (0 rows)

Your task: in server/app.js, save the cart's discount with the order and subtract it in the order's query. Finish POST /api/cart/coupon: look up the code, answer 404 for an unknown one, and save it in cart_coupons. In cartOf, take the code's percent off the total. Delete the user's code after the payment.


Assignment
Follow the Coding Tutorial to add a discount code that the server checks, that the cart, the payment and the order all agree on, and that is used for one cart only.


Hint
In cartOf, join cart_coupons with coupons to get the user's code and its percent. A cart without a code has no discount, so cart.discount || 0 saves 0.


STEP 1 OF 11
    Ctrl + Enter to check