Lesson 39 โข Advanced
E-Commerce Logic ๐
Model shopping carts with coupons, build order processing pipelines with inventory checks, and generate professional invoices.
What You'll Learn in This Lesson
- โข Build a shopping cart with add, remove, and quantity updates
- โข Apply coupon codes with percentage discounts
- โข Calculate subtotals, tax, and grand totals
- โข Process orders through a status lifecycle
- โข Generate formatted invoices and track order timelines
Shopping Cart System
A cart needs to handle adding items (merging duplicates), updating quantities, removing items, and applying discount coupons. Store prices in cents (integers) to avoid floating-point rounding errors โ $29.99 becomes 2999. Calculate tax only on the discounted subtotal.
Try It: Shopping Cart
Build a cart with items, coupons, tax calculation, and totals
// Shopping Cart System in PHP
console.log("=== Building a Shopping Cart ===");
console.log();
class ShoppingCart {
constructor(userId) {
this.userId = userId;
this.items = [];
this.coupon = null;
}
addItem(product, quantity) {
let existing = this.items.find(i => i.product.id === product.id);
if (existing) {
existing.quantity += quantity;
console.log(" ๐ฆ Updated: " + product.name + " ร " + existing.quantity);
} else {
this.items.push({ product,
...Orders & Invoices
Orders have a lifecycle: pending โ paid โ processing โ shipped โ delivered. Each status change creates a timeline entry for customer tracking. Inventory checks prevent overselling, and invoices provide a permanent record of the transaction for accounting and tax purposes.
Try It: Order Processing
Check inventory, process orders through lifecycle, and generate invoices
// Order Processing & Invoice Generation
console.log("=== Order Lifecycle ===");
console.log();
class Order {
constructor(cart, customer, shippingAddress) {
this.id = "ORD-" + Date.now().toString(36).toUpperCase();
this.items = cart.items.map(i => ({
productId: i.product.id,
name: i.product.name,
price: i.product.price,
quantity: i.quantity,
lineTotal: i.product.price * i.quantity,
}));
this.customer = customer;
this.shipping = shippingAddress
...โ ๏ธ Common Mistakes
0.1 + 0.2 !== 0.3 in JavaScript and PHP. Store prices as integers (cents) and divide by 100 only for display.SELECT ... FOR UPDATE to prevent race conditions.๐ Quick Reference โ E-Commerce
| Concept | Description |
|---|---|
| Cart | Temporary collection of items before checkout |
| Order | Confirmed purchase with payment and shipping |
| SKU | Stock Keeping Unit โ unique product identifier |
| Idempotent Payment | Ensure charge happens exactly once |
| Cents (integers) | Store money as integers to avoid float errors |
๐ Lesson Complete!
You can now build e-commerce systems! Next, learn server-side rendering with template engines like Twig.
Sign up for free to track which lessons you've completed and get learning reminders.