| ← All Docs Feature Specifications

Feature Specifications

Verified Against source code 7 core features documented Last updated: September 2026

Billing (Core)

Billing is the primary feature of AquaDealers. Every bill creates a cascade of data changes across multiple tables in a single atomic transaction.

Atomic Save: create_bill_v2 RPC

A single PostgreSQL function that performs all of the following in one transaction. If any step fails, the entire transaction is rolled back — no partial state.

#OperationTable
1Insert bill header (number, date, farmer, totals, branch)bills
2Insert line items with quantities, rates, discountsbill_items
3Deduct stock from oldest FIFO lots per iteminventory_lots
4Record inventory movements (type: 'sale')inventory_movements
5Insert payment record (if amount_paid > 0)payments
6Allocate payment to this billpayment_allocations
7Create cash book entry (if cash payment)cash_book
8Update farmer due balance (via trigger)farmers
9Record transaction event for undo capabilitytransaction_events

Offline Sync

When the device is offline, bills are saved locally and synced when connectivity returns. The sync mechanism uses create_bill_offline_sync RPC with client_ref idempotency.

Idempotency

Each offline bill gets a client_ref — a UUID generated on the client. There is a unique index on (dealer_id, client_ref) on the bills table. If the sync request is sent twice (e.g., network timeout followed by retry), the second attempt is safely rejected as a duplicate.

Draft Tabs

Up to 5 concurrent drafts stored in sessionStorage. Each draft preserves:

Drafts survive page refreshes within the same browser tab but not across tabs or after closing the browser.

Invoice Templates

5 invoice template designs available:

TemplateStyle
TemplateOneClean minimal — product, qty, rate, amount
TemplateTwoDetailed — includes HSN, MRP, discount columns
TemplateThreeGST-focused — full GST breakdown (CGST + SGST)
TemplateFourCompact — smaller font, more items per page
TemplateFiveModern — styled header, signature area prominent

Configurable Columns

Each template supports toggling these columns on/off via Settings:

Templates are branch-specific — different branches can use different templates.

PDF Generation

Bill Numbering

Format: AD-{YYYYMMDD}-{sequence}

The sequence is a branch-specific auto-incrementing counter. Example: AD-20260909-042 is the 42nd bill from this branch on September 9, 2026.

Estimates

Estimates (quotations) use the same billing flow but with no side effects.

How Estimates Differ from Bills

AspectBillEstimate
Database flagis_estimate = falseis_estimate = true
Stock impactDeducts from FIFO lotsNone
PaymentRecords payment, updates cash bookNone
Farmer dueIncreases outstanding balanceNo change
WhatsApp notificationSent (if configured)Not sent
Listed in/bill-history/estimates
ConversionCan be converted to a real bill

When an estimate is converted to a bill, the system creates a new bill using the estimate's items and runs the full create_bill_v2 transaction. The estimate record is updated with a reference to the new bill.

Returns

Returns handle the reversal of sold goods. The system restores stock to the original FIFO lots using LIFO (last-in-first-out) — the most recently consumed lot is refilled first.

Database Tables

Stock Restoration

Returns use LIFO for lot restoration. If a bill consumed 50 units from Lot A and 30 from Lot B (in that FIFO order), a return of 20 units restores to Lot B first (the last lot consumed), then Lot A if the return quantity exceeds what came from Lot B.

Excess Returns and Credit

If a return exceeds the remaining unpaid balance on the bill, the excess becomes return_credit_balance on the farmer record. This credit is automatically applied to the farmer's next bill.

Audit Trail

Every return creates inventory movement records with reference_type = 'bill_return' and reference_id pointing to the return. This ensures complete traceability of every unit in and out.

RPCs

RPCPurpose
preview_farmer_return_v1Preview what will happen — shows affected lots, amounts, credit calculation — before committing
create_farmer_return_v1Execute the return — restore stock, adjust farmer balance, create audit entries
replace_farmer_return_v1Replace (edit) an existing return — undoes the previous and applies the new

Stock Transfers

Transfer stock between branches while preserving FIFO lot data. Each transfer creates movement records at both ends.

How It Works

1
Select source branch and product — shows available lots at that branch
2
Select destination branch — must be a different branch owned by the same dealer
3
Enter quantity — cannot exceed available stock at source
4
Execute via create_stock_transfer RPC

What the RPC Does

FIFO Preservation: If transferring 100 units and the source has Lot A (80 units, Jan expiry) and Lot B (50 units, Mar expiry), the transfer creates two lots at the destination: 80 from Lot A and 20 from Lot B, preserving the original cost and expiry dates.

Bill Editing

RPC: edit_bill_v1

What Can Be Edited

Stock Adjustment Logic

Audit Trail

Every edit creates a record in bill_audit_logs with:

The bill record itself is flagged with is_edited = true so edited bills are visually distinguished in bill history.

Bill Cancellation

RPC: cancel_bill_v1

Constraints

ConstraintRuleReason
TimingSame-day onlyPrevents backdated financial manipulation
Paymentamount_paid must be 0Bills with payments must be handled via returns or editing
StatusMust not already be cancelledIdempotency — returns 'already_cancelled' without error

What Cancellation Does

  1. Sets bill status = 'cancelled'
  2. Restores all stock to original FIFO lots (LIFO restoration)
  3. Reduces farmer outstanding balance by the bill amount
  4. Creates inventory movements with reference_type = 'cancellation'
  5. Records transaction event for audit
Idempotent: Calling cancel_bill_v1 on an already-cancelled bill returns 'already_cancelled' status without error or side effects. Safe to retry.

Transaction Undo

A universal undo system that covers all financial transactions in the application.

Supported Transaction Types

TypeUndo Behavior
BillsCancels the bill, restores stock, reverses farmer due
PurchasesRemoves inventory lots, reverses supplier balance
Payments (farmer)Reverses payment allocation, restores farmer due
Supplier PaymentsReverses payment, restores supplier balance
ReturnsRe-deducts returned stock, reverses farmer credit
Stock TransfersReverses transfer at both branches
ExpensesRemoves expense record and cash book entry
Manual Cash EntriesRemoves the entry from cash book

How It Works

48-Hour Window: The undo window is enforced server-side in the RPC. The UI hides the undo button after 48 hours, but even if called directly, the RPC rejects undo attempts outside the window.