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
32 changes: 29 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ It focuses on the parts that usually go wrong in real shops:
`UPDATE … WHERE stock >= ?`. Two customers racing for the last item: one gets the order, the other a `409`.
- **Safe retries.** `POST /orders` accepts an `Idempotency-Key` header. A double-clicked "Pay" button creates one order.
- **Correct money.** Prices are integer kuruş, VAT-inclusive, with per-product Turkish VAT (KDV) rates of 0, 1, 10 or 20 %.
- **Discount coupons.** Percent or fixed-amount codes with minimum cart value, usage limit and
expiry. Usage is counted inside the checkout transaction and given back if the order is cancelled.
- **Order workflow.** `pending → paid → shipped → delivered`, or `cancelled`, which puts the stock back.
- **Secure auth.** scrypt password hashes, HS256 JWTs verified in constant time, no user enumeration on login.

Expand All @@ -26,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 # 27 tests: unit + full HTTP flows
npm test # 40 tests: unit + full HTTP flows
```

With Docker:
Expand Down Expand Up @@ -54,11 +56,16 @@ All routes are under `/api/v1`. Send `Authorization: Bearer <token>` for protect
| `GET` | `/cart` | user | Cart lines, availability and totals |
| `PUT` | `/cart/items/:productId` | user | Set quantity (`0` removes) |
| `DELETE` | `/cart` | user | Empty the cart |
| `PUT` | `/cart/coupon` | user | Apply a coupon code (`{ "code": "HOSGELDIN10" }`) |
| `DELETE` | `/cart/coupon` | user | Remove the coupon |
| `POST` | `/orders` | user | Checkout. Supports `Idempotency-Key` |
| `GET` | `/orders` | user | My orders (`?all=true` for admins) |
| `GET` | `/orders/:id` | user | Order detail (owner or admin) |
| `POST` | `/orders/:id/cancel` | user | Cancel a pending order |
| `PATCH` | `/orders/:id/status` | admin | Move an order through the workflow |
| `GET` | `/coupons` | admin | List coupons with usage counts |
| `POST` | `/coupons` | admin | Create a coupon |
| `DELETE` | `/coupons/:code` | admin | Deactivate a coupon |

**Product query parameters:** `q`, `category` (slug), `minPrice`, `maxPrice` (kuruş),
`inStock=true`, `sort` (`newest`, `price_asc`, `price_desc`, `name`), `page`, `limit` (max 100).
Expand Down Expand Up @@ -89,6 +96,24 @@ curl -X POST localhost:3000/api/v1/orders -H "Authorization: Bearer $TOKEN" \
}
```

### Example: coupon

```bash
# admin: 10% off orders of 500 TL or more, 1000 uses, valid until the end of the year
curl -X POST localhost:3000/api/v1/coupons -H "Authorization: Bearer $ADMIN_TOKEN" \
-H 'Content-Type: application/json' \
-d '{"code":"HOSGELDIN10","type":"percent","value":10,"minSubtotal":50000,"maxUses":1000,"expiresAt":"2026-12-31T23:59:59+03:00"}'

# customer
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`. 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 All @@ -113,8 +138,9 @@ src/
auth.ts scrypt passwords, JWT, role guards
validate.ts tiny schema validator (422 with per-field errors)
db.ts schema migrations (PRAGMA user_version), transactions, seed data
pricing.ts VAT, shipping and totals in integer kuruş
routes/ auth, catalog, cart, orders
pricing.ts VAT, coupon discounts, shipping and totals in integer kuruş
coupons.ts coupon lookup and validity checks (expiry, usage limit)
routes/ auth, catalog, cart, orders, coupons
app.ts wiring, CORS, error handling
test/ node:test unit tests and end-to-end HTTP tests
```
Expand Down
2 changes: 2 additions & 0 deletions src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { authRoutes } from './routes/auth.ts';
import { catalogRoutes } from './routes/catalog.ts';
import { cartRoutes } from './routes/cart.ts';
import { orderRoutes } from './routes/orders.ts';
import { couponRoutes } from './routes/coupons.ts';

export interface Config {
jwtSecret: string;
Expand All @@ -26,6 +27,7 @@ export function createApp(deps: AppDeps) {
catalogRoutes(router, deps);
cartRoutes(router, deps);
orderRoutes(router, deps);
couponRoutes(router, deps);

return async function handler(req: IncomingMessage, res: ServerResponse): Promise<void> {
const started = performance.now();
Expand Down
52 changes: 52 additions & 0 deletions src/coupons.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { HttpError } from './http.ts';
import type { Db } from './db.ts';
import type { CouponRule } from './pricing.ts';

export interface Coupon extends CouponRule {
code: string;
maxUses: number | null;
usedCount: number;
expiresAt: string | null;
isActive: number;
}

const COLUMNS = `code, type, value, min_subtotal AS minSubtotal, max_uses AS maxUses,
used_count AS usedCount, expires_at AS expiresAt, is_active AS isActive`;

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);
if (!coupon || !coupon.isActive) throw new HttpError(404, 'Coupon not found');
if (coupon.expiresAt && new Date(coupon.expiresAt) <= now) throw new HttpError(409, 'Coupon has expired');
if (coupon.maxUses !== null && coupon.usedCount >= coupon.maxUses) throw new HttpError(409, 'Coupon usage limit reached');
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 coupon = cartCoupon(db, userId);
return coupon && coupon.isActive ? coupon : null;
}

export function listCoupons(db: Db): Coupon[] {
return db.prepare(`SELECT ${COLUMNS} FROM coupons ORDER BY code`).all() as unknown as Coupon[];
}
18 changes: 18 additions & 0 deletions src/db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,24 @@ const MIGRATIONS: string[] = [
quantity INTEGER NOT NULL,
PRIMARY KEY (order_id, product_id)
);`,
// 2: discount coupons
`CREATE TABLE coupons (
code TEXT PRIMARY KEY COLLATE NOCASE,
type TEXT NOT NULL CHECK (type IN ('percent', 'fixed')),
value INTEGER NOT NULL CHECK (value > 0),
min_subtotal INTEGER NOT NULL DEFAULT 0,
max_uses INTEGER,
used_count INTEGER NOT NULL DEFAULT 0,
expires_at TEXT,
is_active INTEGER NOT NULL DEFAULT 1,
CHECK (type = 'fixed' OR value <= 100)
);
CREATE TABLE cart_coupons (
user_id INTEGER PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,
code TEXT NOT NULL REFERENCES coupons(code) ON DELETE CASCADE
);
ALTER TABLE orders ADD COLUMN discount INTEGER NOT NULL DEFAULT 0;
ALTER TABLE orders ADD COLUMN coupon_code TEXT;`,
];

export function openDb(path = ':memory:'): Db {
Expand Down
56 changes: 47 additions & 9 deletions src/pricing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ export interface PricedLine {

export interface Totals {
subtotal: number;
/** Coupon discount, already subtracted from `total`. */
discount: number;
vatTotal: number;
shipping: number;
total: number;
Expand All @@ -28,16 +30,52 @@ export function vatIncluded(grossAmount: number, vatRate: number): number {
return Math.round((grossAmount * vatRate) / (100 + vatRate));
}

export function calculateTotals(lines: PricedLine[], shipping: ShippingRule): Totals {
let subtotal = 0;
let vatTotal = 0;
for (const line of lines) {
const gross = line.unitPrice * line.quantity;
subtotal += gross;
vatTotal += vatIncluded(gross, line.vatRate);
export interface CouponRule {
type: 'percent' | 'fixed';
/** Percent (1–100) or a fixed amount in kuruş. */
value: number;
/** Minimum cart subtotal in kuruş for the coupon to apply. */
minSubtotal: number;
}

/** Discount a coupon gives on a subtotal; never more than the subtotal itself. */
export function couponDiscount(coupon: CouponRule, subtotal: number): number {
if (subtotal < coupon.minSubtotal) return 0;
const amount = coupon.type === 'percent' ? Math.round((subtotal * coupon.value) / 100) : coupon.value;
return Math.min(amount, subtotal);
}

/**
* 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--;
}
const shippingFee = subtotal === 0 || subtotal >= shipping.freeOver ? 0 : shipping.fee;
return { subtotal, vatTotal, shipping: shippingFee, total: subtotal + shippingFee };
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;
// 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 };
}

/** 249900 → "2.499,00 ₺" */
Expand Down
34 changes: 33 additions & 1 deletion src/routes/cart.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { HttpError } from '../http.ts';
import { requireUser } from '../auth.ts';
import { validate } from '../validate.ts';
import { calculateTotals } from '../pricing.ts';
import { cartCoupon, checkCoupon, couponProblem } from '../coupons.ts';
import type { AppDeps } from '../app.ts';

export interface CartLine {
Expand All @@ -28,13 +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 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,
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),
totals: calculateTotals(lines, config.shipping, coupon && !problem ? coupon : null),
};
};

Expand Down Expand Up @@ -66,6 +77,27 @@ export function cartRoutes(r: Router, { db, config }: AppDeps): void {
r.delete('/cart', (ctx) => {
const { id } = requireUser(ctx);
db.prepare('DELETE FROM cart_items WHERE user_id = ?').run(id);
db.prepare('DELETE FROM cart_coupons WHERE user_id = ?').run(id);
return view(id);
});

/** Applies a coupon code to the cart. Only one coupon per cart; a new one replaces the old. */
r.put('/cart/coupon', (ctx) => {
const { id: userId } = requireUser(ctx);
const { code } = validate<{ code: string }>(ctx.body, { code: { type: 'string', min: 3, max: 32 } });
const coupon = checkCoupon(db, code);
const subtotal = loadCart(db, userId).reduce((sum, l) => sum + l.unitPrice * l.quantity, 0);
if (subtotal < coupon.minSubtotal) {
throw new HttpError(409, `Coupon needs a cart subtotal of at least ${coupon.minSubtotal} kuruş`);
}
db.prepare(`INSERT INTO cart_coupons (user_id, code) VALUES (?, ?)
ON CONFLICT (user_id) DO UPDATE SET code = excluded.code`).run(userId, coupon.code);
return view(userId);
});

r.delete('/cart/coupon', (ctx) => {
const { id } = requireUser(ctx);
db.prepare('DELETE FROM cart_coupons WHERE user_id = ?').run(id);
return view(id);
});
}
54 changes: 54 additions & 0 deletions src/routes/coupons.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import type { Router } from '../http.ts';
import { HttpError, withStatus } from '../http.ts';
import { requireAdmin } from '../auth.ts';
import { validate } from '../validate.ts';
import { findCoupon, listCoupons } from '../coupons.ts';
import type { AppDeps } from '../app.ts';

interface CouponInput {
code: string;
type: 'percent' | 'fixed';
value: number;
minSubtotal?: number;
maxUses?: number;
expiresAt?: string;
isActive?: boolean;
}

export function couponRoutes(r: Router, { db }: AppDeps): void {
r.get('/coupons', (ctx) => {
requireAdmin(ctx);
return listCoupons(db);
});

r.post('/coupons', (ctx) => {
requireAdmin(ctx);
const c = validate<CouponInput>(ctx.body, {
code: { type: 'string', min: 3, max: 32, pattern: /^[A-Za-z0-9_-]+$/ },
type: { type: 'enum', values: ['percent', 'fixed'] },
value: { type: 'int', min: 1, max: 100_000_000 },
minSubtotal: { type: 'int', min: 0, max: 100_000_000, optional: true },
maxUses: { type: 'int', min: 1, max: 1_000_000, optional: true },
expiresAt: { type: 'string', max: 40, optional: true },
isActive: { type: 'boolean', optional: true },
});
if (c.type === 'percent' && c.value > 100) throw new HttpError(422, 'Validation failed', { value: 'must be <= 100 for percent coupons' });
if (c.expiresAt && Number.isNaN(Date.parse(c.expiresAt))) throw new HttpError(422, 'Validation failed', { expiresAt: 'must be an ISO date' });
const code = c.code.toUpperCase();
if (findCoupon(db, code)) throw new HttpError(409, 'Coupon code already exists');

db.prepare(`INSERT INTO coupons (code, type, value, min_subtotal, max_uses, expires_at, is_active)
VALUES (?, ?, ?, ?, ?, ?, ?)`)
.run(code, c.type, c.value, c.minSubtotal ?? 0, c.maxUses ?? null,
c.expiresAt ? new Date(c.expiresAt).toISOString() : null, c.isActive === false ? 0 : 1);
return withStatus(201, findCoupon(db, code));
});

/** Deactivates a coupon. Past orders keep their coupon code and discount. */
r.delete('/coupons/:code', (ctx) => {
requireAdmin(ctx);
const { changes } = db.prepare('UPDATE coupons SET is_active = 0 WHERE code = ?').run(ctx.params.code);
if (!changes) throw new HttpError(404, 'Coupon not found');
return withStatus(204, null);
});
}
Loading
Loading