Skip to content

Inventory Management

  • Track products, warehouses, and stock movements with full audit history

Prerequisite

Complete the Get Started guide first.

An inventory management system is what any business with physical goods needs to keep track of stock levels across locations. Think retail, e-commerce, manufacturing, food service, or distribution. Any business that stores products somewhere and needs to know how much they have, where it is, and when it moves.

By the end of this example you will have:

  • Product catalog — full CRUD for products with SKUs, categories, and pricing
  • Warehouses — locations where stock is stored
  • Stock movements — inbound, outbound, and transfer records with full audit trail
  • Inventory dashboard — real stats showing stock levels, low-stock alerts, and recent movements
  • Realtime — all changes sync instantly across connected browsers

Database Schema and Permissions

Prompt

txt
We are building an inventory management app on top of this template. Create
the database schema and add the permissions we need.

Database (via Supabase MCP):

Create four tables:

1. `products` table — id (uuid, default gen_random_uuid(), primary key),
   team_id (uuid, references teams(id) on delete cascade, not null),
   name (text, not null), sku (text, not null),
   category (text, nullable), description (text, nullable),
   unit_price (numeric(10,2), nullable),
   unit (text, default 'each', not null),
   reorder_point (integer, default 0, not null),
   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, sku).

2. `warehouses` table — id (uuid, default gen_random_uuid(), primary key),
   team_id (uuid, references teams(id) on delete cascade, not null),
   name (text, not null), address (text, nullable),
   notes (text, nullable),
   created_by (uuid, references profiles(id), not null),
   created_at (timestamptz, default now()),
   updated_at (timestamptz, default now()).

3. `stock_levels` table — id (uuid, default gen_random_uuid(), primary key),
   team_id (uuid, references teams(id) on delete cascade, not null),
   product_id (uuid, references products(id) on delete cascade, not null),
   warehouse_id (uuid, references warehouses(id) on delete cascade, not null),
   quantity (integer, default 0, not null),
   updated_at (timestamptz, default now()).
   Add a unique constraint on (product_id, warehouse_id).

4. `stock_movements` table — id (uuid, default gen_random_uuid(), primary key),
   team_id (uuid, references teams(id) on delete cascade, not null),
   product_id (uuid, references products(id) on delete cascade, not null),
   warehouse_id (uuid, references warehouses(id) on delete cascade, not null),
   type (text, check type in ('inbound', 'outbound', 'transfer', 'adjustment'),
   not null),
   quantity (integer, not null),
   reference (text, nullable),
   notes (text, nullable),
   created_by (uuid, references profiles(id), not null),
   created_at (timestamptz, default now()).

Enable RLS on all four tables. Create policies that use the existing
`is_team_member()` function to scope access. For all tables, the policy
should check that the row's `team_id` matches a team the user belongs to.

All policies should allow select, insert, update, and delete for team
members. We will handle finer-grained permission checks (like admin-only
delete) in the server routes, not in RLS.

After creating the tables, add these permissions to `shared/permissions.ts`:

```
"products.view": ["owner", "admin", "member"],
"products.create": ["owner", "admin", "member"],
"products.update": ["owner", "admin"],
"products.delete": ["owner", "admin"],
"warehouses.view": ["owner", "admin", "member"],
"warehouses.create": ["owner", "admin"],
"warehouses.update": ["owner", "admin"],
"warehouses.delete": ["owner", "admin"],
"inventory.view": ["owner", "admin", "member"],
"inventory.manage": ["owner", "admin", "member"],
```

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.

Products

Prompt

txt
Build the product catalog module — server routes and a full UI page.

Server routes (all use `authUser` with the appropriate permission):

- `GET /api/teams/[teamId]/products` — uses `authUser(event, "products.view")`.
  Returns all products for the team, ordered by name asc. Include the total
  stock quantity across all warehouses by joining and summing from stock_levels.

- `POST /api/teams/[teamId]/products` — uses `authUser(event, "products.create")`.
  Reads { name, sku, category, description, unit_price, unit, reorder_point }
  from the body. Validates that name and sku are required. Sets team_id from
  the auth context and created_by from the authenticated user (user.sub).
  Return 409 if the SKU already exists for this team.

- `PATCH /api/teams/[teamId]/products/[productId]` — uses
  `authUser(event, "products.update")`. Updates whichever fields are provided
  in the body. Validates that the product belongs to the team before updating.
  If sku is being changed, check uniqueness within the team.

- `DELETE /api/teams/[teamId]/products/[productId]` — uses
  `authUser(event, "products.delete")`. Validates that the product belongs to
  the team before deleting.

UI:

Create `app/pages/products/index.vue` — a product list page as a top-level
route (not nested under `/dashboard`), wrapped in a `UDashboardPanel`:

- `UDashboardNavbar` in the header: title "Products",
  `UDashboardSidebarCollapse` on the left. On the right, a "New Product"
  button wrapped in `CanAccess permission="products.create"`.

- The body shows a table of products with columns: name, SKU, category,
  unit price (formatted as currency), total stock, and a low-stock indicator
  (show a warning badge when total stock <= reorder_point). Use `USkeleton`
  for loading state on initial load. Show an empty state with an icon and
  message when there are no products.

- "New Product" button opens a `UModal` with a form: name (required),
  SKU (required), category, description, unit price, unit (default "each"),
  reorder point (default 0). Use Zod for validation. Show loading state on
  the submit button. Show success toast on creation. Show error toast if
  SKU is a duplicate.

- Clicking a product row opens a `USlideover` for editing. Show all fields
  in a form. Below the form, show a "Stock by Warehouse" section: a read-only
  list showing each warehouse name and the quantity of this product in that
  warehouse. Include a delete button at the bottom wrapped in
  `CanAccess permission="products.delete"` — clicking it shows a confirmation
  modal before deleting. Show loading on the save button.

- After creating, editing, or deleting a product, refresh the product list.

Sidebar navigation:

Add a "Products" link to the top navigation group in
`app/components/layout/sidebar/Links.vue`, between "Dashboard" and
"Settings". Use the icon `i-solar-box-bold-duotone`.

The items array needs to become a `computed` (if it isn't already) so we
can conditionally include items based on permissions. Import `useUserRole`
and use `can()` to gate items that require specific permissions — though
for now, all roles can see the Products link.

Warehouses

Prompt

txt
Build the warehouse management module — server routes and a full UI page.

Server routes (all use `authUser` with the appropriate permission):

- `GET /api/teams/[teamId]/warehouses` — uses
  `authUser(event, "warehouses.view")`. Returns all warehouses for the team,
  ordered by name asc. Include a count of distinct products stored and total
  stock quantity by joining from stock_levels.

- `POST /api/teams/[teamId]/warehouses` — uses
  `authUser(event, "warehouses.create")`. Reads { name, address, notes }
  from the body. Validates that name is required. Sets team_id from auth
  context and created_by from the authenticated user (user.sub).

- `PATCH /api/teams/[teamId]/warehouses/[warehouseId]` — uses
  `authUser(event, "warehouses.update")`. Updates whichever fields are
  provided in the body. Validates that the warehouse belongs to the team.

- `DELETE /api/teams/[teamId]/warehouses/[warehouseId]` — uses
  `authUser(event, "warehouses.delete")`. Validates that the warehouse
  belongs to the team before deleting. Return 400 if the warehouse still
  has stock (stock_levels with quantity > 0).

UI:

Create `app/pages/warehouses/index.vue` — a warehouse list page as a
top-level route (not nested under `/dashboard`), wrapped in a
`UDashboardPanel`:

- `UDashboardNavbar` in the header: title "Warehouses",
  `UDashboardSidebarCollapse` on the left. On the right, a "New Warehouse"
  button wrapped in `CanAccess permission="warehouses.create"`.

- The body shows a table of warehouses with columns: name, address,
  product count, total stock quantity. Use `USkeleton` for loading state
  on initial load. Show an empty state when there are no warehouses.

- "New Warehouse" button opens a `UModal` with a form: name (required),
  address, notes. Use Zod for validation. Show loading on submit.

- Clicking a warehouse row opens a `USlideover` for editing. Show all
  fields in a form. Below the form, show an "Inventory" section: a
  read-only list of products in this warehouse with their quantities.
  Include a delete button wrapped in
  `CanAccess permission="warehouses.delete"` with a confirmation modal.

- After creating, editing, or deleting a warehouse, refresh the list.

Sidebar navigation:

Add a "Warehouses" link to the top navigation group in
`app/components/layout/sidebar/Links.vue`, between "Products" and
"Settings". Use the icon `i-solar-buildings-2-bold-duotone`.

Stock Movements

Prompt

txt
Build the stock movement module — the core inventory operation feature.

Server routes (all use `authUser` with the appropriate permission):

- `GET /api/teams/[teamId]/stock-movements` — uses
  `authUser(event, "inventory.view")`. Returns all stock movements for the
  team with product name and warehouse name joined in. Order by created_at
  desc. Support optional query params: `?type=` to filter by movement type,
  `?product_id=` to filter by product, `?warehouse_id=` to filter by
  warehouse.

- `POST /api/teams/[teamId]/stock-movements` — uses
  `authUser(event, "inventory.manage")`. Reads { product_id, warehouse_id,
  type, quantity, reference, notes } from the body. Validates that
  product_id, warehouse_id, type, and quantity are required. Quantity must
  be a positive integer.

  After inserting the movement, update the stock_levels table:
  - For "inbound" and "adjustment": upsert into stock_levels, adding the
    quantity (use ON CONFLICT on product_id, warehouse_id).
  - For "outbound": subtract the quantity. Return 400 if the resulting
    quantity would be negative.
  - For "transfer": this requires a second warehouse_id field
    (`to_warehouse_id`). Subtract from the source warehouse and add to
    the destination warehouse. Return 400 if the source would go negative.
    Create two stock_movement records — one outbound from source, one
    inbound to destination — linked by the same reference string.

  Sets team_id from auth context and created_by from the authenticated
  user (user.sub).

- `GET /api/teams/[teamId]/stock-levels` — uses
  `authUser(event, "inventory.view")`. Returns all stock levels for the
  team with product name, product SKU, and warehouse name joined in.
  Support optional query params: `?warehouse_id=` and `?low_stock=true`
  (filter to items where quantity <= product's reorder_point).

UI:

Create `app/pages/inventory/index.vue` — the main inventory page as a
top-level route, wrapped in a `UDashboardPanel`:

- `UDashboardNavbar` in the header: title "Inventory",
  `UDashboardSidebarCollapse` on the left. On the right, a "Record Movement"
  button wrapped in `CanAccess permission="inventory.manage"`.

- `UDashboardToolbar` below the navbar: on the left, a toggle between
  "Stock Levels" and "Movements" views using `UTabs` with `size="xs"`.
  On the right, a warehouse filter `USelect` (populated from the
  warehouses endpoint).

- **Stock Levels view** (default): a table with columns: product name,
  SKU, warehouse, quantity, reorder point, and status. Status shows a
  green "In Stock" badge when quantity > reorder_point, a yellow "Low Stock"
  badge when quantity <= reorder_point and quantity > 0, and a red
  "Out of Stock" badge when quantity is 0.

- **Movements view**: a table with columns: date (formatted nicely),
  type badge (color-coded — inbound = "success", outbound = "error",
  transfer = "info", adjustment = "warning"), product name, warehouse,
  quantity (with +/- prefix based on type), reference, and who recorded it.

- "Record Movement" button opens a `UModal` with a form: type (required —
  select from inbound/outbound/adjustment/transfer), product (required —
  select from products fetched on mount), warehouse (required — select
  from warehouses fetched on mount), quantity (required, positive integer),
  reference, notes. When type is "transfer", show a second warehouse
  select for the destination. Use Zod for validation. Show loading on
  submit. Show error toast if stock would go negative.

- After recording a movement, refresh both views.

Sidebar navigation:

Add an "Inventory" link to the top navigation group in
`app/components/layout/sidebar/Links.vue`, between "Warehouses" and
"Settings". Use the icon `i-solar-chart-square-bold-duotone`.

Dashboard and Realtime

Prompt 1 — Dashboard

txt
Replace the placeholder dashboard with real inventory data and stats.

Server route:

Create `GET /api/teams/[teamId]/stats` — uses `authUser(event, "team.view")`.
Returns a JSON object with:

- `product_count` — total number of products for the team
- `warehouse_count` — total number of warehouses for the team
- `total_stock_value` — sum of (stock_levels.quantity * products.unit_price)
  across all products and warehouses. Return 0 if no stock.
- `low_stock_count` — count of stock_level rows where quantity <=
  the product's reorder_point and quantity > 0
- `out_of_stock_count` — count of stock_level rows where quantity = 0
- `recent_movements` — the last 10 stock movements with product name,
  warehouse name, type, quantity, and created_at joined in
- `low_stock_items` — up to 10 products where any stock_level quantity <=
  reorder_point, with product name, SKU, warehouse name, quantity, and
  reorder_point

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 Products" (product_count),
  "Warehouses" (warehouse_count), "Stock Value" (total_stock_value formatted
  as currency), "Low Stock Alerts" (low_stock_count + out_of_stock_count).
  Use `USkeleton` placeholders while loading.

- Below the stats, a two-column layout:
  - Left column: "Low Stock Alerts" — a list of products with low or zero
    stock. Each item shows product name, SKU, warehouse, current quantity,
    and reorder point. Use red text for out-of-stock items and yellow for
    low-stock. Show an empty state if everything is well-stocked.
  - Right column: "Recent Movements" — a list of the last 10 stock
    movements. Each item shows movement type badge, product name, warehouse,
    quantity, and timestamp. 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

txt
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 products, warehouses, stock_levels, stock_movements;
ALTER TABLE products REPLICA IDENTITY FULL;
ALTER TABLE warehouses REPLICA IDENTITY FULL;
ALTER TABLE stock_levels REPLICA IDENTITY FULL;
ALTER TABLE stock_movements REPLICA IDENTITY FULL;
```

Composables:

1. Create `app/composables/useRealtimeProducts.ts` — takes a
   `Ref<Product[]>` (or whatever the product array type is). Registers on
   the `products` 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/useRealtimeStockLevels.ts` — same pattern but
   for the `stock_levels` table.

Update `app/composables/useRealtime.ts` to subscribe to `products`,
`warehouses`, `stock_levels`, and `stock_movements` tables in addition to
the existing subscriptions.

Integration:

- In `app/pages/products/index.vue`, call
  `useRealtimeProducts(products)` where `products` is the ref holding the
  product list.
- In `app/pages/inventory/index.vue`, refetch stock levels and movements
  when any realtime event fires on `stock_levels` or `stock_movements`.
  Use `onTable("stock_levels", refetch)` and
  `onTable("stock_movements", refetch)` directly — no separate composable
  needed.
- The dashboard stats page should refetch stats when any realtime event
  fires on products, stock_levels, or stock_movements. Use `onTable()`
  directly in the dashboard page.

What You Built

Starting from a template that handled auth, teams, roles, and permissions, you added:

  1. Products — a full catalog with SKUs, categories, pricing, and reorder points
  2. Warehouses — locations for storing stock with capacity tracking
  3. Stock Movements — inbound, outbound, transfer, and adjustment operations with audit trail
  4. Dashboard — real stats showing stock value, low-stock alerts, and recent activity
  5. 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 external services query stock levels and record movements programmatically
  • AI Chat — a chatbot that answers questions like "What's our lowest stock item?" or "How many units of X did we ship this week?"