Kadai: A Simple PoS for "3 for 10 kr" Pricing

Published on

A friend of mine in Denmark put up a small food stall at a Christmas market this year - Indian tea, vadai, unniyappam, cutlets and cakes.

The stall at the Christmas market

Their pricing is more dynamic than a usual shop, which is good for sales: 1 vadai is 5 kr, but 3 vadai are only 10 kr.

Menu with single and bulk prices

It looks simple on paper. In the rush, it isn’t. A customer asks for 4 vadai, 2 unniyappam and a masala tea, and you have to work out “one set of 3, plus 1 single, plus 2 singles that don’t make a set” in your head while the queue grows and your hands are busy with hot food.

Busy counter

I looked for a PoS app that handles this. Most of them support discounts, coupons or “buy X get Y free”, but not a plain N for a fixed price rule per product - or they hide it behind a paid plan built for a full restaurant. So I built my own: Kadai (கடை - Tamil for “shop”).

Try it: kadai.mkumaran.net

What it needs to do

I kept the scope small on purpose:

  • Products with a price, and an optional bulk rule: bulkQty items for bulkPrice.
  • A PoS screen: tap a product, adjust quantity, see the total, complete the sale.
  • A list of past sales, and the ability to fix a wrong bill.
  • Multiple shops per user.
  • Works on a phone, because that’s what is on the counter.

No inventory, no tax, no printer, no payment integration - payment is MobilePay via a QR code on the counter, outside the app.

Stack

LayerChoice
APIGo, Echo
DatabasePostgres, pgx + sqlx, sql-migrate
WebReact, Vite, TanStack Router + Query, shadcn/ui, Tailwind
AuthCasdoor (self-hosted OIDC)
DeployOne Docker image (distroless), Dokploy on a VPS

I started with Bun ORM and later replaced it with plain SQL through sqlx. For a schema this small, an ORM was more indirection than help - the queries are short, and I’d rather read the SQL than guess what the ORM generates.

The pricing rule

This is the core of the app, so it’s worth getting exactly right. The rule: every full set of bulkQty costs bulkPrice, the rest are charged at the single price.

// Bulk pricing: every full set of bulkQty costs bulkPrice, the rest price.
export function lineSplit(line: CartLine) {
	if (line.bulkQty === null || line.bulkPrice === null || line.bulkQty < 1) {
		return { sets: 0, singles: line.qty };
	}
	return {
		sets: Math.floor(line.qty / line.bulkQty),
		singles: line.qty % line.bulkQty
	};
}

export function lineTotal(line: CartLine): number {
	const { sets, singles } = lineSplit(line);
	return roundMoney(sets * (line.bulkPrice ?? 0) + singles * line.price);
}

So with vadai at 5 kr / 3 for 10 kr:

QtySetsSinglesTotal
20210 kr
31010 kr
41115 kr
72125 kr

Note that 2 vadai cost the same as 3. The app does not silently upgrade the customer to 3 - that’s a decision for the person at the counter. Instead it shows a hint: “+2 more → 3 for 10 kr, save 5 kr”.

// How many more to complete the next deal, and what that saves against
// buying those items one by one.
export function nextDeal(line: CartLine) {
	const { singles } = lineSplit(line);
	if (line.bulkQty === null || line.bulkPrice === null || singles === 0) {
		return null;
	}
	const saving = roundMoney(line.bulkQty * line.price - line.bulkPrice);
	return saving > 0 ? { more: line.bulkQty - singles, saving } : null;
}

All cart logic lives in one file of pure functions (cart.ts): addProduct, changeQty, lineTotal, cartTotal, toSaleBill. No React in it. That makes it trivial to unit test with Vitest, and the components only render what these functions return.

Money and floats

JavaScript numbers are floats, and 0.1 + 0.2 is 0.30000000000000004. Every total goes through one helper:

export const roundMoney = (amount: number) => Math.round(amount * 100) / 100;

Prices at a market stall are whole kroner, so this is enough. In the database, all amounts are NUMERIC(6, 2), so storage is exact.

The PoS screen

On desktop it’s a product grid on the left and the current sale on the right. Each line shows the breakdown once a deal applies - 3 for 10 kr × 1, 5 kr each × 1 - so the customer can see why 4 vadai cost 15 kr and not 20.

PoS on desktop

On a phone, the cart panel collapses into a bottom bar with the item count and total, and the quantity steppers move into the product tiles. The person at the counter never has to leave the grid.

PoS on mobile

Data model

Four main tables: shop, product, sale, sale_item (plus user and user_shop).

CREATE TABLE "product" (
  "id" uuid PRIMARY KEY,
  "shop_id" uuid NOT NULL REFERENCES "shop"(id),
  "name" varchar(100) NOT NULL,
  "price" NUMERIC(6, 2) NOT NULL,
  "bulk_qty" INTEGER NULL,
  "bulk_price" NUMERIC(6, 2) NULL,
  ...
);

CREATE TABLE "sale_item" (
  "id" uuid PRIMARY KEY,
  "sale_id" uuid NOT NULL REFERENCES "sale"(id),
  "sr_no" INTEGER NOT NULL,
  "product_id" uuid NOT NULL REFERENCES "product"(id),
  "product_price" NUMERIC(6, 2) NOT NULL,
  "product_bulk_qty" INTEGER NULL,
  "product_bulk_price" NUMERIC(6, 2) NULL,
  "buy_qty" INTEGER NOT NULL,
  "total" NUMERIC(6, 2) NOT NULL
);

The important decision: sale_item copies the price and the bulk rule at the time of sale. If they change the vadai price on day 3, the bills from day 1 still show what the customer actually paid. Editing an old bill also uses the stored prices, not the current ones. It’s a small amount of duplication that saves a whole class of “why did yesterday’s total change?” bugs.

Products and sales are soft-deleted (deleted_at, deleted_by), since a sale item still references the product.

Saving a bill is one transaction: check the items, insert the sale, insert the sale_item rows. Updating a bill replaces its items inside a transaction too.

err := util.WithTx(ctx, s.db, func(tx *sqlx.Tx) error {
    if err := checkItems(ctx, tx, shopId, input.Items); err != nil {
        return err
    }
    _, err := tx.ExecContext(ctx, `
        INSERT INTO sale (id, shop_id, total, created_by, created_at)
        VALUES ($1, $2, $3, $4, $5)`,
        saleId, shopId, input.Total, loggedInUserId, time.Now())
    if err != nil {
        return fmt.Errorf("unable to create new sale. Err: %w", err)
    }
    return insertItems(ctx, tx, saleId, input.Items)
})

checkItems rejects an empty bill, zero quantities, and - more importantly - any product that doesn’t belong to the current shop, with a single COUNT(*) ... WHERE id = ANY($1) AND shop_id = $2.

Multi-shop

Each shop also has a free-text currency_symbol (kr., $, ₹), so there’s no currency library and no locale logic. The shop owner types what they want to see.

Auth

Auth is delegated to a self-hosted Casdoor - the same setup I use for my other apps.

  1. The web app redirects to Casdoor, which returns to /callback with a code.
  2. The web app posts the code to POST /api/auth/signin (rate limited per IP). The API exchanges it with the client secret, which never leaves the server.
  3. The browser sends the access token as Authorization: Bearer on every call.
  4. AuthMiddleware verifies the token locally against the Casdoor certificate - no round trip to Casdoor per request - and checks the issuer and client id. On first sign-in it creates the user, or links an existing one by email.

One binary, one image

The React app is built into api/internal/webui/dist and embedded into the Go binary with //go:embed, behind a build tag:

//go:build embedui

//go:embed all:dist
var dist embed.FS

With the tag (the Docker build) you get one binary that serves both the API and the web app. Without it (go run during development), nothing is embedded and Vite serves the app with a proxy to the API. I wrote about this pattern in detail in Shipping a React + Go App as a Single Binary.

A few details in the SPA handler that are easy to get wrong:

  • Files under assets/ are content-hashed by Vite, so they get Cache-Control: immutable for a year. index.html gets no-cache, so a new deploy is picked up on the next load.
  • A missing assets/... file returns 404 instead of falling back to index.html. Otherwise a stale tab after a deploy would cache HTML as JavaScript.
  • An unknown /api/... path returns a JSON 404, not the app shell.

The web bundle has no build-time environment variables. index.html loads /config.js, which the API generates from its own environment:

window.__KADAI_CONFIG__ = { casdoorEndpoint: '...', casdoorClientId: '...', version: '...' };

So the same image runs in every environment, configured only through the API’s env vars.

The Dockerfile is a three-stage build: Node builds the web app, Go compiles a static binary (CGO_ENABLED=0) with the dist copied in, and the final image is distroless/static:nonroot - no shell, no package manager, runs as an unprivileged user. The binary has its own healthcheck subcommand, so the image’s HEALTHCHECK doesn’t need curl. CI pushes the image to GHCR and triggers a Dokploy webhook on main.

Trade-offs I’m aware of

  • The client computes the totals. The server checks that products belong to the shop and quantities are valid, but it stores the totals the client sends. For a stall where the only users are the owners, that’s fine. If this ever had untrusted cashiers, the server should recompute each line from product_price, product_bulk_qty and buy_qty - the logic is ten lines.
  • One bulk rule per product. “3 for 10, 6 for 18” tiers aren’t supported. Nobody asked for it yet.
  • Online only. The app needs a connection to save a sale. An offline queue would be the first thing to add if the market network turns out to be unreliable.

Wrap up

Kadai is a small app: a handful of services, and one file of pure pricing logic that matters more than everything else. Most of the effort went into keeping it boring - plain SQL, a single binary, one rule for bulk pricing done right, and a screen that works on the phone sitting on the counter.

It is live at kadai.mkumaran.net - sign in, create a shop, add a few products with a bulk price and try the PoS screen.