You can't keep gulab jamun in stock: modelling made-to-order products in an online store

Building an online store for a 1960s sweets shop meant rethinking stock, order flow and alerts. Here's the model, with the code.

Ahmad Hassan (Open-Source)4 min read1 kali dilihat
You can't keep gulab jamun in stock: modelling made-to-order products in an online store

Most e-commerce tutorials assume a warehouse. You have 40 units, you sell 40 units, you show "Out of stock".

I built the online store for Marhaba Sweets & Bakers, a family sweets shop at Railbazar Chowk, Jhang, Pakistan, making mithai since 1960. Almost nothing there fits the warehouse model:

  • Most sweets are made fresh each morning, and the kitchen can only make so many.
  • Gift boxes spike around Eid and weddings.
  • Many customers still pay cash when the box arrives.
  • Staff aren't watching a dashboard. They need to hear about orders.

Here's how the store handles each of these. It's a Next.js app with Prisma and PostgreSQL.

Two kinds of product

Every product is one of two kinds:

  1. Counted stock: a number that goes down with each order (packaged rusk, for example).
  2. Made to order: no stock count at all, optionally capped by a daily limit the kitchen can manage.

A product's real limit is whichever is lower:

export async function limitsFor(db, product) {
  const stockLeft = product.madeToOrder ? Infinity : product.stockQty
  const dailyLeft = product.dailyLimit == null
    ? Infinity
    : Math.max(0, product.dailyLimit - (await orderedToday(db, product.id)))
  return { stockLeft, dailyLeft, left: Math.min(stockLeft, dailyLeft) }
}

Infinity turns out to be a lovely way to say "no limit of this kind": Math.min just works.

"Today" is a time-zone bug waiting to happen

A daily limit needs to know when the day starts. The server runs in UTC; the shop runs in Pakistan time (UTC+5, no daylight saving). If you use the server's midnight, the shop's day resets at 5 a.m.

const PK_OFFSET_MS = 5 * 60 * 60 * 1000

export function startOfShopDay(now = new Date()) {
  const pk = new Date(now.getTime() + PK_OFFSET_MS)
  pk.setUTCHours(0, 0, 0, 0)
  return new Date(pk.getTime() - PK_OFFSET_MS)
}

Shift into shop time, truncate to midnight, shift back. Then count today's units, ignoring cancelled orders so a cancellation gives the allowance back:

export async function orderedToday(db, productId) {
  const res = await db.orderItem.aggregate({
    _sum: { quantity: true },
    where: {
      productId,
      order: { createdAt: { gte: startOfShopDay() }, status: { not: 'CANCELLED' } },
    },
  })
  return res._sum.quantity ?? 0
}

Tell customers why

"Out of stock" isn't helpful for something that will exist again tomorrow. The check returns a reason the customer understands:

  • "Gulab Jaman" is sold out for today. Please order again tomorrow.
  • Only 3 more "Sohn Halwa" can be ordered today.
  • Only 2 "Cake Rusk" left in stock.

A human in the loop, on purpose

The daily-limit check isn't a single atomic statement, so two orders placed in the same instant could both squeeze in under the limit. For a warehouse that would be a bug to fix with locking. For a kitchen there's a better answer: orders wait as PENDING until the shop confirms them. The person who knows whether the kitchen can make one more box decides.

The order then moves through a strict set of steps:

const VALID_TRANSITIONS = {
  PENDING: ['CONFIRMED', 'CANCELLED', 'AWAITING_PAYMENT'],
  AWAITING_PAYMENT: ['CONFIRMED', 'CANCELLED'],
  CONFIRMED: ['PREPARING', 'CANCELLED'],
  PREPARING: ['OUT_FOR_DELIVERY', 'CANCELLED'],
  OUT_FOR_DELIVERY: ['DELIVERED', 'CANCELLED'],
  DELIVERED: [],
  CANCELLED: [],
}

Anything else is rejected, so an order can't skip from pending to delivered by accident. Customers can cancel only before the kitchen starts (PENDING or CONFIRMED); after that, the shop handles it.

The price you see is the price you pay

Free delivery from Rs 3,000 is decided in one shared module used by the cart, the checkout page and the order API. No copy of the rule lives in the UI to drift out of date.

Make sure the shop actually sees the order

A small shop doesn't need more dashboards; it needs alerts it can't miss. Each new order sends an email, shows an alert in the admin panel and can send a WhatsApp message. There's even a "Send test order email" button, so the owner can check alerts work before a busy Eid weekend.

Takeaways

  • Model the business, not a generic store. "Made to order with a daily limit" mattered more than any theme.
  • Time zones belong in your domain logic, not just your date formatting.
  • Sometimes the right fix for a race is a human confirmation step.
  • Keep pricing rules in one place.

The full case study, including the checkout security work (HTTP-only cookie auth, database coupons, idempotent orders), is here: Marhaba Sweets case study.

I'm Ahmad, a full-stack developer building stores and web apps in Next.js and Node.js. Get in touch if your business doesn't fit a template either.


Sumber artikel open-source oleh Ahmad Hassan di DEV Community — Baca artikel asli. Topik: #nextjs #ecommerce #javascript #webdev

Sukai & bagikan artikel ini

Komentar