Sales Orders & Invoices
- Build a sales system with orders, line items, invoice generation, and payment tracking
Prerequisite
Complete the Get Started guide first.
A sales order and invoicing system is what any product or service business uses to manage the money side. Think freelancers, agencies, retailers, wholesalers, or any business that creates quotes, takes orders, sends invoices, and tracks payments.
By the end of this example you will have:
- Customers — full CRUD for the people and businesses you sell to
- Orders — sales orders with line items, totals, and status tracking
- Invoices — generated from orders with payment tracking and due dates
- Sales dashboard — real stats showing revenue, outstanding invoices, and order pipeline
- Realtime — all changes sync instantly across connected browsers
Database Schema and Permissions
Prompt
We are building a sales order and invoicing app on top of this template.
Create the database schema and add the permissions we need.
Database (via Supabase MCP):
Create five tables:
1. `customers` table — id (uuid, default gen_random_uuid(), primary key),
team_id (uuid, references teams(id) on delete cascade, not null),
name (text, not null), email (text, nullable), phone (text, nullable),
company (text, nullable), address (text, nullable),
billing_address (text, nullable),
tax_id (text, nullable),
notes (text, nullable),
created_by (uuid, references profiles(id), not null),
created_at (timestamptz, default now()),
updated_at (timestamptz, default now()).
2. `orders` table — id (uuid, default gen_random_uuid(), primary key),
team_id (uuid, references teams(id) on delete cascade, not null),
order_number (serial, not null),
customer_id (uuid, references customers(id) on delete cascade, not null),
status (text, check status in ('draft', 'confirmed', 'fulfilled',
'cancelled'), default 'draft', not null),
subtotal (numeric(12,2), default 0, not null),
tax_rate (numeric(5,2), default 0, not null),
tax_amount (numeric(12,2), default 0, not null),
total (numeric(12,2), default 0, not null),
notes (text, nullable),
order_date (date, default current_date, not null),
fulfilled_date (date, nullable),
created_by (uuid, references profiles(id), not null),
created_at (timestamptz, default now()),
updated_at (timestamptz, default now()).
Add a unique constraint on (team_id, order_number).
3. `order_items` table — id (uuid, default gen_random_uuid(), primary key),
order_id (uuid, references orders(id) on delete cascade, not null),
description (text, not null),
quantity (numeric(10,2), default 1, not null),
unit_price (numeric(12,2), not null),
amount (numeric(12,2), not null),
sort_order (integer, default 0, not null),
created_at (timestamptz, default now()).
4. `invoices` table — id (uuid, default gen_random_uuid(), primary key),
team_id (uuid, references teams(id) on delete cascade, not null),
invoice_number (serial, not null),
order_id (uuid, references orders(id) on delete set null, nullable),
customer_id (uuid, references customers(id) on delete cascade, not null),
status (text, check status in ('draft', 'sent', 'paid', 'overdue',
'cancelled', 'refunded'), default 'draft', not null),
subtotal (numeric(12,2), default 0, not null),
tax_rate (numeric(5,2), default 0, not null),
tax_amount (numeric(12,2), default 0, not null),
total (numeric(12,2), default 0, not null),
amount_paid (numeric(12,2), default 0, not null),
issue_date (date, default current_date, not null),
due_date (date, not null),
paid_date (date, nullable),
notes (text, nullable),
created_by (uuid, references profiles(id), not null),
created_at (timestamptz, default now()),
updated_at (timestamptz, default now()).
Add a unique constraint on (team_id, invoice_number).
5. `payments` table — id (uuid, default gen_random_uuid(), primary key),
invoice_id (uuid, references invoices(id) on delete cascade, not null),
amount (numeric(12,2), not null),
method (text, check method in ('cash', 'bank_transfer', 'credit_card',
'check', 'other'), default 'bank_transfer', not null),
reference (text, nullable),
payment_date (date, default current_date, not null),
notes (text, nullable),
created_by (uuid, references profiles(id), not null),
created_at (timestamptz, default now()).
Enable RLS on all five tables. Create policies that use the existing
`is_team_member()` function to scope access. For `customers`, `orders`,
and `invoices`, the policy should check that the row's `team_id` matches
a team the user belongs to. For `order_items`, join through the `orders`
table. For `payments`, join through the `invoices` table.
All policies should allow select, insert, update, and delete for team
members. We will handle finer-grained permission checks in the server
routes, not in RLS.
After creating the tables, add these permissions to `shared/permissions.ts`:
```
"customers.view": ["owner", "admin", "member"],
"customers.create": ["owner", "admin", "member"],
"customers.update": ["owner", "admin"],
"customers.delete": ["owner", "admin"],
"orders.view": ["owner", "admin", "member"],
"orders.create": ["owner", "admin", "member"],
"orders.update": ["owner", "admin"],
"orders.delete": ["owner", "admin"],
"invoices.view": ["owner", "admin", "member"],
"invoices.create": ["owner", "admin"],
"invoices.update": ["owner", "admin"],
"invoices.delete": ["owner", "admin"],
"payments.view": ["owner", "admin", "member"],
"payments.create": ["owner", "admin"],
```
Regenerate the TypeScript types via Supabase MCP and save them to
`shared/types/database.types.ts`.Adding plugins later?
If you plan to add API Keys & External API or AI Chat later, their pages will guide you through adding the required permissions. You don't need to add them now.
Customers
Prompt
Build the customer module — server routes and a full UI page.
Server routes (all use `authUser` with the appropriate permission):
- `GET /api/teams/[teamId]/customers` — uses
`authUser(event, "customers.view")`. Returns all customers for the team,
ordered by name asc. Include a count of orders and total revenue
(sum of paid invoice totals) per customer by joining.
- `POST /api/teams/[teamId]/customers` — uses
`authUser(event, "customers.create")`. Reads { name, email, phone,
company, address, billing_address, tax_id, notes } from the body.
Validates that name is required. Sets team_id from the auth context
and created_by from the authenticated user (user.sub).
- `PATCH /api/teams/[teamId]/customers/[customerId]` — uses
`authUser(event, "customers.update")`. Updates whichever fields are
provided in the body. Validates that the customer belongs to the team.
- `DELETE /api/teams/[teamId]/customers/[customerId]` — uses
`authUser(event, "customers.delete")`. Validates that the customer
belongs to the team before deleting.
UI:
Create `app/pages/customers/index.vue` — a customer list page as a
top-level route (not nested under `/dashboard`), wrapped in a
`UDashboardPanel`:
- `UDashboardNavbar` in the header: title "Customers",
`UDashboardSidebarCollapse` on the left. On the right, a "New Customer"
button wrapped in `CanAccess permission="customers.create"`.
- The body shows a table of customers with columns: name, company, email,
phone, order count, and total revenue (formatted as currency). Use
`USkeleton` for loading state on initial load. Show an empty state with
an icon and message when there are no customers.
- "New Customer" button opens a `UModal` with a form: name (required),
email, phone, company, address, billing address, tax ID, notes. Use Zod
for validation. Show loading on submit.
- Clicking a customer row opens a `USlideover` for editing. Show all fields
in a form. Below the form, show an "Orders" section: a read-only list of
orders for this customer (order number, date, status, total). Include a
delete button wrapped in `CanAccess permission="customers.delete"` with
a confirmation modal.
- After creating, editing, or deleting a customer, refresh the list.
Sidebar navigation:
Add a "Customers" link to the top navigation group in
`app/components/layout/sidebar/Links.vue`, between "Dashboard" and
"Settings". Use the icon `i-solar-users-group-two-rounded-bold-duotone`.Orders
Prompt
Build the order management module — this is the core sales feature.
Server routes (all use `authUser` with the appropriate permission):
- `GET /api/teams/[teamId]/orders` — uses `authUser(event, "orders.view")`.
Returns all orders for the team with customer name and item count joined
in. Order by order_date desc. Support optional query params: `?status=`
to filter by status, `?customer_id=` to filter by customer.
- `GET /api/teams/[teamId]/orders/[orderId]` — uses
`authUser(event, "orders.view")`. Returns the order with customer info,
all line items, and linked invoice info (if any). Validates that the order
belongs to the team.
- `POST /api/teams/[teamId]/orders` — uses
`authUser(event, "orders.create")`. Reads { customer_id, status, tax_rate,
notes, order_date, items } from the body where items is an array of
{ description, quantity, unit_price, sort_order }. Validates that
customer_id is required and items must have at least one entry. For each
item, calculate amount = quantity * unit_price. Calculate subtotal as sum
of all item amounts, tax_amount = subtotal * (tax_rate / 100), and
total = subtotal + tax_amount. Sets team_id from auth context and
created_by from the authenticated user. Insert order first, then items.
- `PATCH /api/teams/[teamId]/orders/[orderId]` — uses
`authUser(event, "orders.update")`. Updates order fields and/or replaces
line items. If items are provided, delete existing items and insert the
new ones. Recalculate subtotal, tax_amount, and total. If status is
changed to "fulfilled", set fulfilled_date to today. Validates that the
order belongs to the team.
- `DELETE /api/teams/[teamId]/orders/[orderId]` — uses
`authUser(event, "orders.delete")`. Validates that the order belongs to
the team. Return 400 if the order has a linked invoice.
- `POST /api/teams/[teamId]/orders/[orderId]/invoice` — uses
`authUser(event, "invoices.create")`. Generates an invoice from the
order. Reads { due_date, notes } from the body. Copies customer_id,
subtotal, tax_rate, tax_amount, and total from the order. Sets issue_date
to today. Returns 400 if an invoice already exists for this order.
UI:
Create `app/pages/orders/index.vue` — the main orders page as a top-level
route, wrapped in a `UDashboardPanel`:
- `UDashboardNavbar` in the header: title "Orders",
`UDashboardSidebarCollapse` on the left. On the right, a "New Order"
button wrapped in `CanAccess permission="orders.create"`.
- `UDashboardToolbar` below the navbar: on the left, show status counts
(e.g. "2 Draft, 5 Confirmed, 3 Fulfilled"). On the right, status
filter using `USelect`: All, Draft, Confirmed, Fulfilled, Cancelled.
- Order list as a table with columns: order number (formatted as #001),
customer name, order date, item count, status badge (color-coded —
draft = "neutral", confirmed = "info", fulfilled = "success",
cancelled = "error"), total (formatted as currency).
- Each row has an inline status dropdown using `UDropdownMenu`.
- "New Order" button opens a `UModal` (or full-width `USlideover` for
more space) with a form: customer (required — select from customers
fetched on mount), order date (use `UPopover` with `UCalendar`),
tax rate (numeric input, default 0), notes. Below, a "Line Items"
section: a dynamic list where each row has description (required),
quantity (default 1), unit price (required), and a calculated amount.
"Add Item" button to add rows, "Remove" button on each row. Show the
running subtotal, tax amount, and total at the bottom. Use Zod for
validation. Show loading on submit.
- Clicking an order row opens a `USlideover` for the order detail. Show
order metadata at the top (customer, status, dates). Below, show the
line items table (description, qty, unit price, amount) with
subtotal/tax/total summary. Show an "Invoice" section: if an invoice
exists, show its number, status, and a link; if not, show a "Generate
Invoice" button (wrapped in `CanAccess permission="invoices.create"`)
that prompts for a due date and creates the invoice. Include a delete
button wrapped in `CanAccess permission="orders.delete"` with confirmation.
- After creating, editing, or deleting an order, refresh the order list.
Sidebar navigation:
Add an "Orders" link to the top navigation group in
`app/components/layout/sidebar/Links.vue`, between "Customers" and
"Settings". Use the icon `i-solar-cart-large-2-bold-duotone`.Invoices & Payments
Prompt
Build the invoice and payment modules — billing and payment tracking.
Server routes (all use `authUser` with the appropriate permission):
- `GET /api/teams/[teamId]/invoices` — uses
`authUser(event, "invoices.view")`. Returns all invoices for the team
with customer name and payment count joined in. Order by issue_date desc.
Support optional query params: `?status=` to filter by status,
`?customer_id=` to filter by customer.
- `GET /api/teams/[teamId]/invoices/[invoiceId]` — uses
`authUser(event, "invoices.view")`. Returns the invoice with customer
info, linked order info (if any), and all payments. Validates team.
- `PATCH /api/teams/[teamId]/invoices/[invoiceId]` — uses
`authUser(event, "invoices.update")`. Updates whichever fields are
provided. If status is changed to "paid", set paid_date to today.
Validates that the invoice belongs to the team.
- `DELETE /api/teams/[teamId]/invoices/[invoiceId]` — uses
`authUser(event, "invoices.delete")`. Validates team. Return 400 if
the invoice has any payments recorded.
- `GET /api/teams/[teamId]/invoices/[invoiceId]/payments` — uses
`authUser(event, "payments.view")`. Returns all payments for the invoice
with the recorder's name joined in, ordered by payment_date desc.
- `POST /api/teams/[teamId]/invoices/[invoiceId]/payments` — uses
`authUser(event, "payments.create")`. Reads { amount, method, reference,
payment_date, notes } from the body. Validates that amount is required
and positive. After inserting, update the invoice's amount_paid (sum all
payments). If amount_paid >= total, automatically set status to "paid"
and paid_date to today. Sets created_by from the authenticated user.
UI:
Create `app/pages/invoices/index.vue` — the invoices page as a top-level
route, wrapped in a `UDashboardPanel`:
- `UDashboardNavbar` in the header: title "Invoices",
`UDashboardSidebarCollapse` on the left. On the right, a "New Invoice"
button wrapped in `CanAccess permission="invoices.create"` (for manual
invoices not linked to an order).
- `UDashboardToolbar` below the navbar: on the left, show summary
(e.g. "3 Outstanding, $12,450 Due"). On the right, status filter using
`USelect`: All, Draft, Sent, Paid, Overdue, Cancelled, Refunded.
- Invoice list as a table with columns: invoice number (formatted as
INV-001), customer name, issue date, due date, status badge (color-coded —
draft = "neutral", sent = "info", paid = "success", overdue = "error",
cancelled = "neutral", refunded = "warning"), total (formatted as
currency), amount paid, balance due (total - amount_paid).
- Overdue detection: if status is "sent" and due_date < today, show the
status badge as "Overdue" in red instead of "Sent".
- Each row has an inline status dropdown using `UDropdownMenu`.
- "New Invoice" button opens a `UModal` with a form: customer (required —
select from customers), issue date, due date (required), tax rate, notes.
Below, a "Line Items" section identical to the order form (description,
qty, unit price, amount). Calculate subtotal/tax/total. Use Zod. Show
loading on submit.
- Clicking an invoice row opens a `USlideover` with full invoice detail.
Show invoice metadata (customer, dates, status). Show line items from
the linked order (if any) or the invoice itself. Show a "Payments"
section: a list of recorded payments (date, amount, method, reference)
with a "Record Payment" button (wrapped in
`CanAccess permission="payments.create"`) that opens a small inline form
(amount, method select, reference, date, notes). Show balance remaining.
Include a delete button wrapped in
`CanAccess permission="invoices.delete"` with confirmation.
- After any change, refresh the invoice list.
Sidebar navigation:
Add an "Invoices" link to the top navigation group in
`app/components/layout/sidebar/Links.vue`, between "Orders" and
"Settings". Use the icon `i-solar-bill-list-bold-duotone`.Dashboard and Realtime
Prompt 1 — Dashboard
Replace the placeholder dashboard with real sales and billing stats.
Server route:
Create `GET /api/teams/[teamId]/stats` — uses `authUser(event, "team.view")`.
Returns a JSON object with:
- `customer_count` — total number of customers for the team
- `open_orders` — count of orders with status "draft" or "confirmed"
- `revenue_this_month` — sum of totals for invoices with status "paid" where
paid_date is in the current calendar month. Return 0 if none.
- `outstanding_amount` — sum of (total - amount_paid) for invoices with
status "sent" or "overdue". Return 0 if none.
- `overdue_invoices` — count of invoices where status is "sent" and
due_date < today
- `recent_orders` — the last 5 orders with customer name, status, total,
and order_date
- `recent_payments` — the last 5 payments with invoice number, customer
name, amount, method, and payment_date
- `revenue_by_month` — array of { month, total } for the last 6 months
of paid invoices, ordered chronologically
All queries are scoped to the team's team_id.
UI:
Update `app/pages/dashboard/index.vue` to show:
- A row of four stat cards at the top using a grid layout. Each card shows
an icon, a label, and the value. Cards: "Total Customers" (customer_count),
"Open Orders" (open_orders), "Revenue This Month" (revenue_this_month
formatted as currency), "Outstanding" (outstanding_amount formatted as
currency, with overdue_invoices count shown as a warning sub-label if > 0).
Use `USkeleton` placeholders while loading.
- Below the stats, a two-column layout:
- Left column: "Recent Orders" — a list of the last 5 orders. Each item
shows order number, customer name, status badge, total, and date.
Clicking an order navigates to the orders page. Show an empty state if
no orders.
- Right column: "Recent Payments" — a list of the last 5 payments. Each
item shows invoice number, customer name, amount (formatted as
currency), payment method badge, and date. Show an empty state if none.
Remove any placeholder/scaffolding content that was in the dashboard before.
Keep the `UDashboardPanel` wrapper with navbar and sidebar collapse.Prompt 2 — Realtime
Add Supabase Realtime sync for the new tables so changes appear instantly
across browser sessions.
Database migration (via Supabase MCP):
Enable realtime publication and full replica identity for the new tables:
```sql
ALTER PUBLICATION supabase_realtime ADD TABLE customers, orders, order_items, invoices, payments;
ALTER TABLE customers REPLICA IDENTITY FULL;
ALTER TABLE orders REPLICA IDENTITY FULL;
ALTER TABLE order_items REPLICA IDENTITY FULL;
ALTER TABLE invoices REPLICA IDENTITY FULL;
ALTER TABLE payments REPLICA IDENTITY FULL;
```
Composables:
1. Create `app/composables/useRealtimeOrders.ts` — takes a
`Ref<Order[]>` (or whatever the order array type is). Registers on
the `orders` table via the existing `useRealtime` composable's
`onTable` function. Handles INSERT (dedup against existing items by id),
UPDATE (replace the matching item), and DELETE (remove by id). Always
assign a new array to `.value` — do not mutate in place, or Vue will
not re-render.
2. Create `app/composables/useRealtimeInvoices.ts` — same pattern but for
the `invoices` table.
Update `app/composables/useRealtime.ts` to subscribe to `customers`,
`orders`, `order_items`, `invoices`, and `payments` tables in addition to
the existing subscriptions.
Integration:
- In `app/pages/orders/index.vue`, call
`useRealtimeOrders(orders)` where `orders` is the ref holding the
order list.
- In `app/pages/invoices/index.vue`, call `useRealtimeInvoices(invoices)`
where `invoices` is the ref holding the invoice list.
- The dashboard stats page should refetch stats when any realtime event
fires on orders, invoices, or payments. Use `onTable()` directly in
the dashboard page — no separate composable needed.What You Built
Starting from a template that handled auth, teams, roles, and permissions, you added:
- Customers — a customer database with contact info, billing details, and revenue tracking
- Orders — sales orders with dynamic line items, tax calculation, and status workflow
- Invoices — invoice generation from orders with payment tracking and overdue detection
- Payments — payment recording with automatic invoice status updates
- Dashboard — revenue metrics, outstanding amounts, and recent activity
- Realtime — all changes sync instantly across connected browsers
Every feature follows the same patterns: permission-gated server routes, team-scoped data, Nuxt UI components, and the conventions defined in CLAUDE.md.
What's Next
- API Keys & External API — let accounting software or payment gateways push payment records
- AI Chat — a chatbot that answers questions like "What's our outstanding balance?" or "Which invoices are overdue?"