Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ It focuses on the parts that usually go wrong in real shops:
git clone https://github.com/bahriy-dev/ecommerce-api.git
cd ecommerce-api
npm start # http://localhost:3000/api/v1 (seeds an admin and 3 demo products)
npm test # 36 tests: unit + full HTTP flows
npm test # 40 tests: unit + full HTTP flows
```

With Docker:
Expand Down Expand Up @@ -109,8 +109,10 @@ curl -X PUT localhost:3000/api/v1/cart/coupon -H "Authorization: Bearer $TOKEN"
-H 'Content-Type: application/json' -d '{"code":"hosgeldin10"}'
```

The cart and the order then show `discount` and `couponCode`. VAT is recalculated on the
discounted amount, and the free-shipping threshold is checked after the discount.
The cart and the order then show `discount` and `couponCode`. The discount is spread over the
cart lines and VAT is recalculated per line on the discounted amount; the free-shipping threshold
is checked after the discount. If an applied coupon expires, runs out or no longer meets the
minimum, the cart keeps showing it with `usable: false` and a `reason`, and stops applying it.

Errors always look like `{ "error": "…", "details": { … } }`. Validation errors return `422`
with one message per field.
Expand Down
19 changes: 16 additions & 3 deletions src/coupons.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,15 @@ export function findCoupon(db: Db, code: string): Coupon | undefined {
return db.prepare(`SELECT ${COLUMNS} FROM coupons WHERE code = ?`).get(code.trim()) as unknown as Coupon | undefined;
}

/** Why a coupon cannot be used right now for this subtotal, or null when it can. */
export function couponProblem(coupon: Coupon, subtotal: number, now = new Date()): string | null {
if (!coupon.isActive) return 'Coupon is no longer active';
if (coupon.expiresAt && new Date(coupon.expiresAt) <= now) return 'Coupon has expired';
if (coupon.maxUses !== null && coupon.usedCount >= coupon.maxUses) return 'Coupon usage limit reached';
if (subtotal < coupon.minSubtotal) return `Cart subtotal must be at least ${coupon.minSubtotal} kuruş`;
return null;
}

/** Returns the coupon if it can be used right now, otherwise throws a 4xx explaining why. */
export function checkCoupon(db: Db, code: string, now = new Date()): Coupon {
const coupon = findCoupon(db, code);
Expand All @@ -26,11 +35,15 @@ export function checkCoupon(db: Db, code: string, now = new Date()): Coupon {
return coupon;
}

/** The coupon a customer applied to their cart, whatever its current state. */
export function cartCoupon(db: Db, userId: number): Coupon | null {
const row = db.prepare('SELECT code FROM cart_coupons WHERE user_id = ?').get(userId) as { code: string } | undefined;
return row ? findCoupon(db, row.code) ?? null : null;
}

/** The coupon a customer applied to their cart, if it still exists and is active. */
export function appliedCoupon(db: Db, userId: number): Coupon | null {
const row = db.prepare('SELECT code FROM cart_coupons WHERE user_id = ?').get(userId) as { code: string } | undefined;
if (!row) return null;
const coupon = findCoupon(db, row.code);
const coupon = cartCoupon(db, userId);
return coupon && coupon.isActive ? coupon : null;
}

Expand Down
34 changes: 25 additions & 9 deletions src/pricing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,18 +45,34 @@ export function couponDiscount(coupon: CouponRule, subtotal: number): number {
return Math.min(amount, subtotal);
}

export function calculateTotals(lines: PricedLine[], shipping: ShippingRule, coupon: CouponRule | null = null): Totals {
let subtotal = 0;
let grossVat = 0;
for (const line of lines) {
const gross = line.unitPrice * line.quantity;
subtotal += gross;
grossVat += vatIncluded(gross, line.vatRate);
/**
* Splits `amount` across `weights` proportionally, in whole kuruş, so the parts always add up
* to exactly `amount` (largest-remainder method).
*/
export function allocate(amount: number, weights: number[]): number[] {
const total = weights.reduce((a, b) => a + b, 0);
if (amount === 0 || total === 0) return weights.map(() => 0);
const exact = weights.map((w) => (amount * w) / total);
const parts = exact.map(Math.floor);
let rest = amount - parts.reduce((a, b) => a + b, 0);
const order = exact.map((x, i) => [x - Math.floor(x), i] as const).sort((a, b) => b[0] - a[0]);
for (const [, i] of order) {
if (rest === 0) break;
parts[i]++;
rest--;
}
return parts;
}

export function calculateTotals(lines: PricedLine[], shipping: ShippingRule, coupon: CouponRule | null = null): Totals {
const grosses = lines.map((line) => line.unitPrice * line.quantity);
const subtotal = grosses.reduce((a, b) => a + b, 0);
const discount = coupon ? couponDiscount(coupon, subtotal) : 0;
const net = subtotal - discount;
// A discount lowers the taxable amount, so the VAT inside it shrinks proportionally.
const vatTotal = subtotal === 0 ? 0 : Math.round((grossVat * net) / subtotal);
// The discount lowers each line's taxable amount, so VAT is recalculated per line on the
// discounted amount and rounded once (rounding the original VAT first would round twice).
const shares = allocate(discount, grosses);
const vatTotal = lines.reduce((sum, line, i) => sum + vatIncluded(grosses[i] - shares[i], line.vatRate), 0);
// Free-shipping threshold is checked against what the customer actually pays for goods.
const shippingFee = subtotal === 0 || net >= shipping.freeOver ? 0 : shipping.fee;
return { subtotal, discount, vatTotal, shipping: shippingFee, total: net + shippingFee };
Expand Down
16 changes: 12 additions & 4 deletions src/routes/cart.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { HttpError } from '../http.ts';
import { requireUser } from '../auth.ts';
import { validate } from '../validate.ts';
import { calculateTotals } from '../pricing.ts';
import { appliedCoupon, checkCoupon } from '../coupons.ts';
import { cartCoupon, checkCoupon, couponProblem } from '../coupons.ts';
import type { AppDeps } from '../app.ts';

export interface CartLine {
Expand All @@ -29,15 +29,23 @@ export function loadCart(db: AppDeps['db'], userId: number): CartLine[] {
export function cartRoutes(r: Router, { db, config }: AppDeps): void {
const view = (userId: number) => {
const lines = loadCart(db, userId);
const coupon = appliedCoupon(db, userId);
const subtotal = lines.reduce((sum, l) => sum + l.unitPrice * l.quantity, 0);
const coupon = cartCoupon(db, userId);
// Only a coupon that checkout would accept may change the totals; otherwise say why it is ignored.
const problem = coupon ? couponProblem(coupon, subtotal) : null;
return {
coupon: coupon ? { code: coupon.code, type: coupon.type, value: coupon.value, minSubtotal: coupon.minSubtotal } : null,
coupon: coupon
? {
code: coupon.code, type: coupon.type, value: coupon.value, minSubtotal: coupon.minSubtotal,
usable: problem === null, ...(problem ? { reason: problem } : {}),
}
: null,
items: lines.map(({ stock, isActive, ...line }) => ({
...line,
lineTotal: line.unitPrice * line.quantity,
available: Boolean(isActive) && stock >= line.quantity,
})),
totals: calculateTotals(lines, config.shipping, coupon),
totals: calculateTotals(lines, config.shipping, coupon && !problem ? coupon : null),
};
};

Expand Down
40 changes: 38 additions & 2 deletions test/coupons.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { describe, it, before, after } from 'node:test';
import assert from 'node:assert/strict';
import { startApp, registerCustomer, loginAdmin, type TestApp } from './helpers.ts';
import { couponDiscount, calculateTotals } from '../src/pricing.ts';
import { couponDiscount, calculateTotals, allocate } from '../src/pricing.ts';

describe('couponDiscount', () => {
it('applies percent and fixed coupons', () => {
Expand All @@ -21,6 +21,24 @@ describe('couponDiscount', () => {
});
});

describe('discount VAT', () => {
it('splits a discount across lines so the parts add up exactly', () => {
assert.deepEqual(allocate(100, [1, 1, 1]), [34, 33, 33]);
assert.deepEqual(allocate(0, [5, 5]), [0, 0]);
assert.equal(allocate(997, [12000, 3200, 5]).reduce((a, b) => a + b, 0), 997);
});
it('recalculates VAT on the discounted amount instead of rounding twice', () => {
const t = calculateTotals([{ unitPrice: 3, vatRate: 20, quantity: 1 }], { fee: 0, freeOver: 0 }, { type: 'fixed', value: 1, minSubtotal: 0 });
assert.equal(t.vatTotal, 0); // VAT inside 2 kuruş at 20% rounds to 0
});
it('applies each line its own VAT rate after the discount', () => {
const lines = [{ unitPrice: 12000, vatRate: 20, quantity: 1 }, { unitPrice: 11000, vatRate: 10, quantity: 1 }, { unitPrice: 5000, vatRate: 0, quantity: 1 }];
const t = calculateTotals(lines, { fee: 0, freeOver: 0 }, { type: 'fixed', value: 2800, minSubtotal: 0 });
// shares of 2800 over 12000/11000/5000 = 1200/1100/500 → VAT inside 10800 at 20% + 9900 at 10%
assert.equal(t.vatTotal, 1800 + 900);
});
});

describe('coupons API', () => {
let app: TestApp;
let admin: string;
Expand Down Expand Up @@ -91,12 +109,30 @@ describe('coupons API', () => {
assert.match(below.body.error, /at least/);
});

it('shows an expired or used-up coupon in the cart without applying it', async () => {
await createCoupon({ code: 'BITECEK', type: 'fixed', value: 1000, maxUses: 1 });
const [a, b] = [await registerCustomer(app), await registerCustomer(app)];
for (const token of [a, b]) {
await app.request('PUT', `/cart/items/${productId('KTP-003')}`, { token, body: { quantity: 1 } });
await app.request('PUT', '/cart/coupon', { token, body: { code: 'BITECEK' } });
}
assert.equal((await app.request('POST', '/orders', { token: a, body: { shippingAddress: 'Çankaya, Ankara 06420' } })).status, 201);

const cart = await app.request('GET', '/cart', { token: b });
assert.equal(cart.body.coupon.usable, false);
assert.match(cart.body.coupon.reason, /usage limit/);
assert.equal(cart.body.totals.discount, 0);
assert.equal(cart.body.totals.total, 32000 + 4990);
});

it('stops working once an admin deactivates it', async () => {
await createCoupon({ code: 'KAPAT', type: 'fixed', value: 500 });
const token = await registerCustomer(app);
await app.request('PUT', `/cart/items/${productId('KTP-003')}`, { token, body: { quantity: 1 } });
await app.request('PUT', '/cart/coupon', { token, body: { code: 'KAPAT' } });
assert.equal((await app.request('DELETE', '/coupons/KAPAT', { token: admin })).status, 204);
assert.equal((await app.request('GET', '/cart', { token })).body.totals.discount, 0);
const cart = await app.request('GET', '/cart', { token });
assert.equal(cart.body.totals.discount, 0);
assert.equal(cart.body.coupon.usable, false);
});
});
Loading