| ← All Docs Database

Database

Last updated Sep 2026 55+ tables · 30+ triggers · 1 view
No secrets, tokens, or credentials are documented here. All values shown are schema-level metadata only.

Core Tables

TablePurposeKey ColumnsRLS
dealers Dealer accounts id, shop_name, name, phone, email, plan, gst_billing_enabled, pin_hash, address, gstin, drug_license_no, language, onboarding_progress, branch_count, whatsapp_enabled Yes
branches Multi-branch support id, dealer_id, name, slug, is_main, is_active, color_theme Yes
farmers Customer records id, dealer_id, branch_id, name, phone, village, total_due, credit_limit, opening_balance, return_credit_balance, crop_status, stocking_date, estimated_harvest_date, notes, follow_up_date Yes
products Product catalog id, dealer_id, type (feed/medicine), company, name, variant, unit, hsn_code, gst_rate, default_price, is_active Yes
inventory Branch stock levels id, dealer_id, branch_id, product_id, quantity_in_stock, cost_price, selling_price, mrp, medicine_discount_percentage, min_stock_alert, track_expiry, expiry_date Yes
inventory_lots FIFO lot tracking id, inventory_id, stock_purchase_id, batch_number, expiry_date, quantity_received, remaining_quantity, cost_price, selling_price, mrp, received_at, is_expired Yes
inventory_movements Stock audit trail id, inventory_id, product_id, lot_id, reference_type, reference_id, quantity_change, notes, created_at Yes
bills Sale invoices id, bill_number, dealer_id, branch_id, farmer_id, subtotal, gst_amount, discount_amount, total, amount_paid, balance_due, payment_type, status, is_estimate, is_edited, bill_date, client_ref, whatsapp_status, created_at Yes
bill_items Line items id, bill_id, product_id, inventory_id, quantity, unit_price, gst_rate, gst_amount, total_price, discount_percentage Yes
bill_item_lot_allocations FIFO consumption id, bill_item_id, lot_id, allocated_quantity, cost_price Yes
payments Farmer payments id, dealer_id, farmer_id, bill_id, amount, method, payment_date, notes Yes
payment_allocations Payment-to-bill mapping id, payment_id, bill_id, allocated_amount, allocation_order Yes
suppliers Supplier directory id, dealer_id, name, company, phone, total_due Yes
stock_purchases Purchase records id, dealer_id, branch_id, supplier_id, product_id, inventory_id, quantity, cost_price_per_unit, total_amount, batch_number, expiry_date, invoice_number Yes
supplier_payments Supplier payment records id, dealer_id, supplier_id, amount, method, payment_date Yes
expenses Expense tracking id, dealer_id, branch_id, category, amount, description, paid_via, expense_date Yes
cash_book Cash ledger entries id, dealer_id, branch_id, entry_type, source, reference_id, amount, notes, entry_date Yes
cash_closings Daily cash reconciliation id, dealer_id, branch_id, closing_date, opening_balance, total_cash_in, total_cash_out, expected_closing, actual_closing, variance, notes Yes
bill_returns Sales returns id, dealer_id, bill_id, farmer_id, return_number, total_amount, notes, created_at Yes
bill_return_items Return line items id, return_id, bill_item_id, product_id, quantity, unit_price, total_price Yes
stock_transfers Branch-to-branch transfers id, dealer_id, from_branch_id, to_branch_id, total_quantity, notes, created_at Yes
stock_transfer_items Transfer line items id, transfer_id, product_id, quantity, lot_id, batch_number, expiry_date, cost_price Yes
transaction_events Undo/audit events id, dealer_id, event_type, reference_type, reference_id, metadata, undone_at, undo_deadline, created_at Yes
farmer_product_discounts Per-farmer pricing id, dealer_id, farmer_id, product_id, custom_price, discount_percentage Yes
farmer_return_credit_applications Return credit usage id, dealer_id, farmer_id No
staff_members Staff accounts id, dealer_id, name, phone, pin_hash, permissions (JSONB), branch_ids (UUID[]), is_active Yes
staff_sessions Active staff sessions id, staff_id, dealer_id, branch_id, token_hash, expires_at, created_at Yes
staff_login_attempts Login rate limiting id, staff_id, ip_address, success, created_at Yes
admin_users Platform admins id, email, name, password_hash, role (superadmin/admin/support) Yes
admin_sessions Admin sessions id, admin_id, token_hash, expires_at Yes
onboarding_progress Setup wizard tracking id, dealer_id, step, completed_at Yes
support_tickets Help desk id, dealer_id, subject, description, status, priority Yes
ticket_messages Ticket conversation id, ticket_id, sender_type, message, created_at Yes
whatsapp_addon_plans WhatsApp plan tiers id, name, messages_per_month, price Yes
whatsapp_message_usage Monthly message counts id, dealer_id, month_year, messages_sent, addon_plan_id Yes
bill_audit_logs Bill change history id, bill_id, dealer_id, action, changes (JSONB), created_at Yes
plan_definitions Subscription plans id, name, price, features (TEXT[]), limits (JSONB) Yes

Missing RLS: farmer_return_credit_applications

This table has no row-level security policy. Any authenticated user can read and write all rows. Add an RLS policy filtering on dealer_id = auth.uid() to match the pattern used by every other tenant-scoped table.

Key Triggers

TriggerTableEventPurpose
farmer_due_from_billbillsINSERT / UPDATE / DELETERecalculates farmers.total_due from bills
farmer_due_from_paymentpaymentsINSERT / UPDATE / DELETERecalculates farmers.total_due from payments
farmer_due_from_payment_allocationpayment_allocationsINSERT / UPDATE / DELETERecalculates farmers.total_due from payment allocations
trg_fanout_product_to_branchesproductsINSERTAuto-creates inventory row in every branch when product added
trg_fanout_branch_to_productsbranchesINSERTAuto-creates inventory rows for all products when branch added
transaction_event_billbillsINSERTLogs transaction event for bill creation
transaction_event_stock_purchasestock_purchasesINSERTLogs transaction event for stock purchase
transaction_event_farmer_paymentpaymentsINSERTLogs transaction event for payment
transaction_event_supplier_paymentsupplier_paymentsINSERTLogs transaction event for supplier payment
transaction_event_bill_returnbill_returnsINSERTLogs transaction event for return
transaction_event_stock_transferstock_transfersINSERTLogs transaction event for transfer
transaction_event_expenseexpensesINSERTLogs transaction event for expense
trg_bcrypt_dealer_pindealersINSERT / UPDATEHashes dealer PIN with bcrypt
trg_staff_hash_pinstaff_membersINSERT / UPDATEHashes staff PIN with bcrypt
trg_revoke_staff_sessionsstaff_membersUPDATEDeletes all sessions when staff deactivated (is_active = false)
trg_rate_limit_billsbillsINSERT / UPDATE / DELETERate-limits writes to 30 actions/minute per dealer
trg_rate_limit_paymentspaymentsINSERT / UPDATE / DELETERate-limits writes to 30 actions/minute per dealer
trg_rate_limit_farmersfarmersINSERT / UPDATE / DELETERate-limits writes to 30 actions/minute per dealer
trg_rate_limit_inventoryinventoryINSERT / UPDATE / DELETERate-limits writes to 30 actions/minute per dealer
trg_rate_limit_cash_bookcash_bookINSERT / UPDATE / DELETERate-limits writes to 30 actions/minute per dealer
trg_rate_limit_expensesexpensesINSERT / UPDATE / DELETERate-limits writes to 30 actions/minute per dealer

Views

archived_bills

Bills older than 2 years. Uses security_invoker (runs with the caller's RLS context, not the view owner). Purpose: archival queries without touching the hot bills table.

Key Indexes

Index ColumnsTablePurpose
(dealer_id, bill_date)billsDashboard queries
(dealer_id, farmer_id)billsFarmer ledger
(dealer_id, branch_id, status)billsBranch filtering
(dealer_id, phone)farmersUnique phone per dealer
(dealer_id, branch_id, product_id)inventoryStock lookups
(inventory_id, is_expired, remaining_quantity)inventory_lotsFIFO selection
(dealer_id, farmer_id)paymentsPayment history
(bill_id)bill_itemsBill detail joins
(dealer_id, branch_id, entry_date)cash_bookDaily book queries
(dealer_id, reference_type, reference_id)transaction_eventsUndo lookups