/** * Alışveriş sepeti. Fiyatlar kuruş (tam sayı) olarak tutulur. */ class Cart { constructor() { this.items = new Map(); // sku -> { name, unitPrice, qty } this.coupon = null; } add(sku, name, unitPrice, qty = 1) { if (!Number.isInteger(unitPrice) || unitPrice < 0) throw new TypeError('unitPrice negatif olmayan tam sayı olmalı'); if (!Number.isInteger(qty) || qty < 1) throw new RangeError('qty en az 1 olmalı'); const cur = this.items.get(sku); if (cur) cur.qty += qty; else this.items.set(sku, { name, unitPrice, qty }); return this; } remove(sku, qty = Infinity) { const cur = this.items.get(sku); if (!cur) return false; if (qty >= cur.qty) this.items.delete(sku); else cur.qty -= qty; return true; } subtotal() { let sum = 0; for (const { unitPrice, qty } of this.items.values()) sum += unitPrice * qty; return sum; } applyCoupon(code) { const coupons = { YUZDE10: { type: 'percent', value: 10 }, INDIRIM50: { type: 'fixed', value: 5000 } }; const c = coupons[String(code).toUpperCase()]; if (!c) throw new Error('Geçersiz kupon'); this.coupon = c; } discount() { const sub = this.subtotal(); if (!this.coupon) return 0; if (this.coupon.type === 'percent') return Math.round((sub * this.coupon.value) / 100); return Math.min(this.coupon.value, sub); } shipping() { const afterDiscount = this.subtotal() - this.discount(); if (this.items.size === 0) return 0; return afterDiscount >= 50000 ? 0 : 2999; } total() { return this.subtotal() - this.discount() + this.shipping(); } } module.exports = { Cart };