E-commerce Cart Checkout & Tax Engine

30:00

1. Studi Kasus

Buatlah logika checkout keranjang belanja untuk toko online. Endpoint menerima payload barang belanjaan, memvalidasi stok produk, menerapkan voucher diskon khusus kategori, menghitung PPN 11%, dan mengembalikan rincian tagihan.

POST /cart/checkout

2. Spesifikasi Input & Output

Request Body:

{
  "items": [
    { "productId": "P1", "quantity": 2 },
    { "productId": "P2", "quantity": 1 }
  ],
  "voucherCode": "TECH20"
}

Response Berhasil (HTTP 200):

{
  "subtotal": 2050,
  "discount": 150,
  "netSubtotal": 1900,
  "tax": 209,
  "total": 2109
}

3. Data Awal In-Memory

const products = [
  { id: "P1", name: "Laptop", price: 1000, category: "ELECTRONICS", stock: 3 },
  { id: "P2", name: "Mouse",  price: 50,   category: "ELECTRONICS", stock: 10 },
  { id: "P3", name: "Shirt",  price: 30,   category: "FASHION",     stock: 5 }
];

const vouchers = [
  { code: "TECH20", category: "ELECTRONICS", discountPercent: 20, maxDiscount: 150 }
];

4. Aturan Perhitungan & Requirement

  1. Validasi Payload: Jika items tidak ada atau array kosong → kembalikan HTTP 400 "Items array is required".
  2. Cek Stok: Jika quantity > product.stock → kembalikan HTTP 400 "Product X out of stock".
  3. Subtotal: Total harga (price × quantity) dari seluruh item.
  4. Diskon Voucher: 20% khusus item kategori ELECTRONICS, dengan batas diskon maksimal (maxDiscount) = 150.
  5. PPN 11%: tax = (subtotal - discount) × 0.11
  6. Pengurangan Stok: Kurangi stok produk (product.stock -= quantity) setelah transaksi berhasil.

5. Pertanyaan Bonus Konseptual 💡

Idempotency pada Payment Gateway Di komentar kode solusi Anda, jelaskan bagaimana cara menjamin Idempotency menggunakan header X-Idempotency-Key untuk mencegah penagihan ganda (double charge) saat koneksi jaringan terputus dan user melakukan retry.

solution.js
Loading...
Local Test Console