Skip to content

POS Billing Rules

The business rules, limits and edge cases behind POS billing - tenders and splits, per-item payment methods, round-off, drafts, void, refunds, owner edits, self-billing and billing alerts.

18 min read

Overview

This page lists the rules enforced when a bill is made, changed, voided or refunded. It does not repeat the checkout walkthrough (see Checkout & POS) or the cash drawer (see Cash Register). Money is stored in minor units (paise); the app is built for INR with a 2-decimal assumption.

Kagami point-of-sale billing engine enforcing pricing tiers, staff splits, and GST tax calculation

Almost every rule lives in one server action, createInvoiceAction (web/src/lib/billing/actions.ts). The checkout screen applies the same rules for display, but the server is the authority: a stale or forged request is rejected there. A bill is written as status = paid in one pass; there is no "unpaid draft invoice" in this flow (browser drafts are separate, see below).

Who can do what

Action Rule Default roles
Make / finalise a bill billing.create permission org_owner, brand_manager, location_manager. Not front_desk or stylist unless an owner turns it on
Make a bill for your own appointment Solo-own-appointment rule (below), no permission needed stylist (and any role) on their own in-progress appointment
Void a bill billing.void permission org_owner, brand_manager, location_manager
Void your own just-made bill billing.create + you created it + under 10 minutes old anyone holding billing.create
Edit a bill Hard-coded owner check (org_owner, super_admin) owners only; not configurable
Online (Razorpay) refund Hard-coded manager check (MANAGER_ROLES) super_admin, org_owner, brand_manager, location_manager
Change per-item allowed payment methods Hard-coded manager check managers (MANAGER_ROLES)
Back-date a walk-in's start time Owners only; any other role gets "now" org_owner, super_admin
  • billing.create and billing.void are toggles in Settings -> Roles and Permissions, stored per org in role_permissions. With no override the defaults above apply. super_admin always passes; a role of null never does.
  • Stylist or front desk without the permission see a disabled Collect button and the text "Your role isn't allowed to make bills. Ask an owner or manager, or have them enable it in Settings -> Roles and Permissions." The server returns the same message.
  • Voiding without permission returns "Your role isn't allowed to void bills. Ask an owner or manager."

Tenders and splits

A bill can be paid with one tender or a split. Valid tender methods on the server: cash, card, upi, wallet, loyalty_points, complimentary, package, membership, gift_card, other, cashback.

Rule Detail
Splits must equal the total Sum of positive split amounts must be within 1 paisa of the (rounded) invoice total. Otherwise: Split payments (₹X) must equal the invoice total (₹Y) (both amounts shown with 2 decimals)
Round-off slack If the splits miss the total by up to ₹1.00, the gap is added to the largest cash-equivalent split (cash, card, upi, other only) so the books balance. A gap above ₹1 is rejected. Balance-capped tenders (wallet, cashback, loyalty, gift card) and entitlements never absorb it. The carrying split is never reduced to zero or below
Duplicate methods merge Two cash rows are stored as one payment_splits row
Primary method invoices.payment_method holds the method with the largest amount
One row per method, always Even single-tender bills get one payment_splits row for the full total. A zero-total (fully complimentary) bill gets no rows because amount_minor > 0 is a table check
Gift card Must be found, active, unexpired, and its balance must cover the whole total, else Gift card balance (₹X) is less than invoice total (₹Y) (whole rupees). When a gift card pays, the split-sum check is skipped
Membership or package redemption cannot be combined with wallet Error: "A membership or package redemption cannot be combined with a wallet payment on the same invoice."
Client required for stored value Wallet, cashback or loyalty points with no client selected: "Select a client to pay with wallet, cashback or loyalty points."
Loyalty points 1 point = ₹1; amount is rounded to a whole number of points. Paying with points earns no new points and no raffle entry
Complimentary Full-bill comp needs a second confirmation tap in the UI: the first tap shows "This comps the entire ₹X bill — the customer pays nothing", and the button then reads "Confirm — comp full ₹X bill" (X is the payable total). No receipt email, no referral qualification, no raffle entry, no Meta Purchase event
Tip Tip (tipMinor + tipStaffId) is stored in staff_tips and is not part of the invoice total

Fixed tender matrix (not configurable)

Stored-value and promo tenders depend on what is being sold (tender-eligibility.ts):

Tender Service bill Product Membership sale Package sale Combo sale
cashback, loyalty_points, complimentary, gift_card Yes No No Yes No
redeem_package, redeem_membership, redeem_combo Yes No No No No

This matrix is applied in the checkout UI. The server only enforces the configurable tenders (below), the wallet rules and the gift-card and balance checks.

Mixed service + product bills

When a bill has both service and product lines, the screen collects two sub-payments: Products due (cash, card, UPI, other, narrowed by each product's allowed tenders; falls back to cash if the products disagree) and Services due (any service tender). Products get the payable total pro-rata to the pre-tax product share; services get the remainder, so the round-off lands on services and the two always add up. A bill that is all services or all products uses a single grid. The sub-payment split is a screen convenience; the server still checks the total and the per-tender ceilings.

Per-item allowed payment methods

Membership plans, session packages, service combos and retail products each have allowed_tenders text[] (migration 0167). NULL means "use the built-in default".

Item Default allowed tenders
Membership plan cash, card, upi
Package cash, card, upi, other
Combo cash, card, upi, other
Product cash, card, upi, wallet, other
Service No restriction
  • Configurable keys: cash, card, upi, wallet, other (shown as "Online" in the picker). Anything else is rejected with "Unknown payment method". Selecting none is rejected: "Select at least one payment method, or reset to default."
  • An empty array or NULL falls back to the default. A non-empty array with no valid keys falls back to the entity default restricted to cash, card and upi (fail-safe, logged to the console).
  • Where owners set it: the catalogue panels (per-row picker and a bulk "Set payment methods" bar, up to 500 items per call). Only managers can change it, scoped to their own org and brand.
  • Ceiling rule (server, createInvoiceAction): for each tender, the most it may cover is payable x (share of subtotal made of lines that accept it), rounded to paise. A split above its ceiling by more than ₹0.50 is rejected: {Tender} can cover at most ₹N of this bill — some items on it don't accept that payment method. ({Tender} is the payment method's display name; N is shown in whole rupees.) Only product lines carry restrictions on this path; service lines accept everything.
  • If a bill's payable total is 0 every ceiling is 0. If there are no priceable line totals, a tender restricted on any line gets a ceiling of 0.
  • The invoice server check inspects the product allowed tenders. Membership, package and combo defaults are enforced by the checkout screen, which caps the tender inputs.

Wallet cap

The wallet auto-seed (walletFirstSplit) puts as much of the bill as the client's balance allows on the wallet, capped at the wallet ceiling above, and leaves the remainder unassigned - staff must pick the tender for the rest (SALO-2452; it no longer defaults the remainder to cash). The wallet is not seeded for exclusive tenders (package, membership, combo, gift card) or after staff start typing amounts.

Net effect today:

  • Membership, package and combo sales cannot be paid from the wallet (not in their defaults).
  • A mixed service + product bill: wallet is seeded against the services share, and the product sub-payment grid has no wallet.
  • A product-only bill: wallet is allowed by default, because the product default includes wallet. An owner can remove it per product.
  • Wallet debit happens before the invoice is considered done; if it fails: Wallet error: followed by the reason, and the whole invoice is rolled back.

Round-off

  • The payable total (after discounts and, for tax-exclusive pricing, GST) is rounded to the nearest whole rupee, half up (50 paise rounds up). The delta is stored in invoices.round_off_minor and shown on the bill.
  • The same maths is used by the checkout screen (roundOffMajor) and the server (roundOffTotal), by edit-invoice, and everything downstream (gift-card check, splits, payment rows) uses the rounded total.
  • A negative or non-finite total fails loudly: "Could not calculate the invoice total. Please refresh and try again."
  • Tax: GST is computed on the post-discount amount. With inclusive pricing (the default) the total stays as the post-discount amount and tax is extracted for reporting. With exclusive pricing, GST is added on top. A brand with no default tax rate gets 18% seeded at checkout (resolveDefaultTaxRate with seedIfMissing); if the rate cannot be read: "Failed to resolve the tax rate for this bill. Please try again."

Discounts on a bill

  • Manual invoice discount + discount code + spin-wheel prize are summed and capped at the subtotal. Line discounts are separate and also floored at zero per line.
  • A code that is not a discount code falls back to Marketing -> Offers (weekday and service scoped). A referral reward does not combine with a manual discount or a spin prize: "A referral reward can't be combined with another discount on the same bill".
  • Spin prize must belong to the same client and be unredeemed, else "This spin prize is no longer available to redeem". Only discount_pct and free_addon prizes are applicable.
  • The total of all discounts on a bill can never exceed the bill subtotal.

Bill drafts (browser only)

Drafts exist so a half-built bill survives a closed tab. They are not invoices and never touch the server.

Property Value
Storage Browser localStorage, key salonos:pos-drafts:v1. Not shared across devices, terminals or staff
Autosave Debounced 2 seconds after any change, once the bill has content; also flushed on tab close and on leaving the page
Cap 50 drafts. Saving a 51st evicts the oldest by last-saved time and shows "Older saved drafts were removed to make room for this one." (once per session)
Save failure Storage full or blocked: "Couldn't save this bill as a draft on this device (browser storage is full or blocked)." (once per session)
Restore ?draftId= on the checkout URL. Missing draft: "That draft is no longer available - it may have been cleared." Success: "Draft restored". Per-product allowed tenders are re-read from the live catalogue because older drafts lack them
Lifetime Removed when its bill is paid or when deleted from the Billing drafts list
Corrupt store Unreadable JSON is treated as empty, but the first corrupt value is copied to salonos:pos-drafts:v1:corrupt-backup so it can be recovered
Race Two tabs saving at the same instant: last write wins

Draft entries record location, saved time, a client label (or "Walk-in"), item count and total. Drafts are filtered by location in the list.

Voiding a bill

voidInvoiceAction is an atomic reversal plus a few follow-up steps.

  1. Permission: billing.void, or (billing.create and the bill was created by the caller and is less than 10 minutes old). The 10-minute path exists for the POS flow rolling back the bill it just made when a follow-up step (membership or package sale) fails. The Void button on the invoice page appears only for roles with billing.void and only on paid bills.
  2. One database transaction (void_invoice_reversals, migration 0196, extended in 0277):
    • locks the invoice row (a concurrent or repeated void is a no-op),
    • sets status = void, voided_at = now(), voided_by (the sale date paid_at is kept),
    • gives gift-card balances back and reactivates the card,
    • gives package sessions back (floored at 0) and reactivates the package,
    • gives one membership service back per redemption (floored at 0),
    • credits wallet debits back (per-wallet advisory lock) and deletes the wallet debit and reconciliation rows,
    • deletes the redemption rows. Any failure rolls everything back and the bill can be voided again; the error shown is the real database cause.
  3. After the transaction (not atomic with it): an audit-log entry; loyalty points redeemed on the bill are re-credited (matched by the exact note Redeemed for invoice followed by the invoice number); the linked appointment goes back from completed to in_progress so it can be billed again; staff tips for that appointment are deleted.
  4. Reports count only status = paid, so a void never counts as a sale. Bills voided before migration 0277 have no void date and do not appear in voided figures.

What a void reverses: gift cards, packages, memberships, wallet debits and redeemed loyalty points. It does not automatically adjust cashback (store credit) spent on the bill, combo session redemptions, spin-wheel prize redemption, discount-code usage counters, loyalty points earned on the bill, or stock for product and back-bar lines; correct those separately if needed.

Refunds ledger

Refunds are recorded one row at a time in invoice_refunds (migration 0276) so reports can net refunds per payment mode on the day they were paid out.

Column Meaning
amount_minor Positive only (> 0)
method cash, upi, card, online, other
source online (Razorpay), return (product return), manual (backfilled/imported only)
invoice_id / return_item_id Link to the bill or the return; either can be null
provider_refund_id Razorpay refund id; unique where present, so webhook retries cannot double count
refunded_at, refunded_by, reason, location_id When, who, why, which store

recordRefund returns false (not an error) when the same Razorpay refund id or the same return was already recorded. Any other failure throws "Could not record the refund: ...". A non-positive or non-integer amount throws "Refund amount must be a positive number."

Three ways money goes back

  1. Online (Razorpay) refund from the invoice - managers only; the bill must have a Razorpay payment, else "No Razorpay payment found for this invoice". Error for non-managers: "You don't have permission to issue refunds". The action always refunds the full payment and marks the invoice void with voided_at. The wallet, gift-card and package reversal above belongs to the Void action and is not part of this refund.
  2. Razorpay refund.processed webhook - records an online refund row (idempotent on the refund id), adds to invoices.refunded_minor with a compare-and-set (retries up to 3 times, then throws "refunded_minor CAS lost 3 times"), and marks the bill void only when total refunded reaches the invoice total. A partial refund keeps the bill paid.
  3. Product return paid out at the counter - return_items go pending -> approved/rejected/refunded. Refunding requires choosing cash or upi ("Choose whether the refund was paid in cash or UPI."), a positive refund amount ("This return has no refund amount to pay out."), and a store ("This return has no store recorded, so its refund can't be reported. Log it again from the store it was handled in."). A finished return cannot be resolved again ("This return is already refunded/rejected."). Logging a return needs an active store selected: "Select a store in the sidebar before logging a return." The refund row has source = return and is not linked to an invoice.

Credit notes (credit_notes, reasons refund, correction, goodwill, service_redo, overcharge, other) are a separate adjustment: applying one adds the amount to the linked invoice's discount_minor and reduces total_minor (reversed again if an applied note is voided; migration 0178). The amount must be at least 1 and tax cannot exceed the amount: "Tax cannot exceed the credit amount".

Owner bill edit

Owners can edit a bill from the invoice page (editInvoiceAction, SALO-2427). Non-owners get "Only an owner can edit an invoice."; a void bill cannot be edited.

  • Editable: location, client, date, notes, line items (staff, quantity, price, discount), invoice discount and the cash/card/upi/other/complimentary tenders. GST and round-off are recomputed with the same maths as checkout.
  • Date: the chosen date becomes both created_at and paid_at.
  • Payments must equal the new total (same split rules and ₹1 round-off slack): "Payments (₹X) must equal the invoice total (₹Y)."
  • Locked tenders: wallet, cashback, loyalty points, gift card, package and membership cannot be added, removed or changed ("... can't be added or changed here. Void and re-bill instead."). A bill that used one of them, or was paid online, cannot change its total, and (for locked tenders) its client ("This invoice was paid with a balance tender or online payment, so its total and client can't change. Void and re-bill instead.").
  • Stock: the difference between old and new product quantities is posted as a stock adjustment; failures come back as a warning to adjust inventory manually.
  • Safety: new lines and splits are inserted before the old ones are deleted; a failed insert restores the old header. If the old rows cannot be removed: "The edit was saved but old rows could not be removed - please contact support before editing again." Every edit writes an audit-log entry with old and new values.

Staff self-billing (SALO-2496)

A stylist without billing.create may still bill an appointment when all of these hold (solo-own-appointment.ts):

  • the appointment status is in_progress,
  • the appointment's staff member is the caller's active staff record,
  • every service on it is unassigned or assigned to the caller (they are the only staff),
  • the appointment is not part of a group booking.

The rule is checked in createInvoiceAction and mirrored on the appointment checkout page, so the Collect button is enabled. It fails closed: any database error means "not allowed" and is logged (billing.solo_own_appointment). Without it, a stylist on the checkout page is redirected to /my. All other bill rules (tenders, day-open gate) still apply.

Billing gates and failures

Gate Behaviour
Day not opened If the brand requires an open day (default required), billing needs an open salon day and an open cash drawer shift for that location: "Open the salon and cash register for today before billing (Open / Close Salon)." Reads that fail open (billing allowed) and are logged
Already billed A second non-void invoice for the same appointment is rejected by a unique index: "This appointment has already been billed. Refresh to see the invoice."
Cross-tenant ids Location, brand and client ids are verified against the caller's org before any write
Walk-in without a stylist "A manager or staff member must be selected for POS checkout"
Walk-in checkout type Walk-in vs guest walk-in must be chosen
Failed follow-up step Gift-card, wallet, cashback, loyalty, payment-split, package, membership or combo redemption failures roll back the invoice and return a specific message (Wallet error: ..., Package redemption failed: ..., Payment recording failed - please retry)
Partial rollback Reported to monitoring (billing.rollback_partial) so a reversed-but-not-fully-refunded invoice is visible
Non-fatal problems Stock or appointment-status or walk-in-queue sync failures do not undo the bill; they come back as warnings for the operator to fix manually

Fast and slow bill alerts

When a bill is paid for an appointment that has a start time (in_progress_at), the elapsed minutes are compared with the expected service time and written to service_time_logs (one row per service line, with alert_triggered and alert_kind).

Rule Default Owner setting
Fast: billed sooner than this many minutes after start 5 minutes fast_minutes (0-120)
Fast / slow tolerance around expected time 10% tolerance_pct (0-100)
Expected time Per stylist: sum of (duration x quantity) over their services; stylists run in parallel, so the longest stylist wins. If any service has no duration there is no expected time (no false alerts) -

Examples at the defaults: a 30-minute service alerts as fast before 27 minutes and as slow after 33 minutes. Anything under 5 minutes is always fast, even with no expected time.

  • Where owners configure it: the "Billing time alert" entry under Bookings and billing in the alert settings. A per-store row overrides the org row; missing params use the defaults.
  • Who is told: managers by default (bell). Delivery channels (bell, push, WhatsApp, email) and recipients are configurable. A read failure of the settings falls back to the defaults. Title is "Fast billing" or "Slow billing" plus staff and store, linking to the invoice.
  • Left-open exception: a bill closed after more than 3x the expected time is treated as an appointment left "in progress" (e.g. billed at closing). It is still logged as slow but no alert is sent.
  • The alert runs in the background after the bill is saved (fire-and-forget); a failure goes to monitoring and never blocks or undoes the bill.

Card split settlement (online payments)

For Razorpay payments on an invoice, checkout-time splits record the tender chosen before payment. Once Razorpay captures the money:

  • If the captured amount equals the invoice total, settle_invoice_card_split (migration 0275) locks the invoice row, deletes its splits and inserts one card split for the full total. The browser confirmation and the payment.captured webhook race on this, so the function is idempotent: any number of calls leave exactly one card row.
  • If the captured amount differs (part paid by wallet or cash) or is not a number, the existing splits are kept and the mismatch is reported to monitoring (payments.settle-splits-mismatch).
  • A failure to rewrite splits never fails the payment itself (the invoice is already paid); it is reported and repaired by the webhook or a browser retry.
  • Capture is bound to the order created for that invoice and to an unpaid, non-void invoice; otherwise "This payment does not match an open invoice." A bad signature gives "Invalid payment signature". An invoice that is already paid or void cannot start a new online payment.

Data model

Table / column Purpose
invoices status (paid / void), subtotal_minor, discount_minor, tax columns, round_off_minor, total_minor, payment_method (primary), refunded_minor, voided_at, voided_by, created_by, razorpay_* ids
invoice_lines Service or product line, qty, price, discount_minor, total_minor, tax_rate_pct, hsn_sac, staff_id
payment_splits One row per method per invoice; amount_minor > 0
invoice_refunds Refund ledger (above)
return_items Product returns with status, refund_minor, location_id
credit_notes Adjustments applied against an invoice
membership_plans, session_packages, service_combos, products allowed_tenders text[] (NULL = default)
service_time_logs Per-service timing and fast/slow alert result
role_permissions Per-org toggles for billing.create and billing.void
alert_settings Per-org / per-store billing_time_alert thresholds and recipients

Source

  • web/src/lib/billing/actions.ts - checkout, void, walk-in POS checkout
  • web/src/lib/billing/tender-eligibility.ts, tender-split.ts, splits.ts, round-off.ts, wallet-auto-apply.ts
  • web/src/lib/billing/tender-admin-actions.ts - set per-item allowed tenders
  • web/src/lib/billing/draft-storage.ts and web/src/app/(tenant)/dashboard/billing/checkout/pos-flow.tsx - drafts and tender UI
  • web/src/lib/billing/rollback.ts - checkout rollback
  • web/src/lib/billing/edit-invoice-actions.ts, edit-invoice-calc.ts - owner edit
  • web/src/lib/billing/solo-own-appointment.ts, web/src/lib/auth/can-create-bill.ts, can-void-bill.ts, permissions.ts
  • web/src/lib/billing/bill-time-alert.ts, web/src/lib/alerts/registry.ts
  • web/src/lib/refunds/index.ts, web/src/lib/return-items/, web/src/lib/credit-notes/
  • web/src/lib/payments/index.ts, web/src/app/api/webhooks/razorpay/route.ts
  • Migrations: 0087_payment_splits, 0162_invoice_round_off, 0167_item_allowed_tenders, 0196_void_invoice_reversals_rpc, 0178_credit_note_apply_void_rpc, 0275_settle_invoice_card_split, 0276_invoice_refunds, 0277_invoice_void_date