Skip to content

Shop (inventory and orders)

This tutorial builds examples/shop: a small shop admin with products, stock, suppliers, customers, orders, and order items. The shop starter writes the schema, resources, policies, actions, and seed; this guide explains every piece and shows the running app.

It is written for someone comfortable with JavaScript or TypeScript who is new to Dashild. Every step explains what the command or file does, not just what to paste.

What you will learn:

  • How a Prisma model becomes a Dashild resource.
  • How Decimal, money formatting, relation selects, and filters work.
  • How declared actions, confirmation, and action handlers fit together.
  • How relation managers are derived from the schema.
  • How Stripe links and CSV import/export are wired without API keys.

The finished app is in the repository if you want to compare.

Terminal window
pnpm create dashild@latest my-shop --template shop --database sqlite --yes
cd my-shop

The scaffolder creates a Next.js app, installs Dashild, and applies the shop starter. The starter adds:

  • Six models: Category, Supplier, Product, Customer, Order, and OrderItem.
  • One resource file per model under src/dashild/resources/.
  • src/dashild/policies.ts, src/dashild/actions/index.ts, and the panel registration in src/dashild/panel.ts.
  • A seed with demo products, customers, and orders.
  • The Stripe and CSV glue, already wired into the route.

--database sqlite keeps the example self-contained: the database is a file (prisma/dev.db), so you do not need a server.

The shop starter is staff-only: it writes ALLOW_SIGNUP="false", REQUIRE_EMAIL_VERIFICATION="true", and a DASHILD_STAFF_EMAILS allowlist with the seeded staff. Update that list when you add staff; an account outside it cannot read or write the shop even if signup is enabled later.

BETTER_AUTH_URL must match the URL you open in the browser. The scaffold sets http://localhost:3000. If you change the port, set it before pnpm dev:

Terminal window
BETTER_AUTH_URL=http://localhost:3001 pnpm dev

The starter is a folder template: a short template.json plus real files under packages/create-dashild/templates/shop. List what is available with:

Terminal window
pnpm create dashild@latest --list-templates

Sign in to the shop panel

The seeded demo account signs in at /login; the panel lives at /admin.

prisma/schema.prisma describes the tables. Prisma generates a typed client; Dashild reads the metadata to know which fields each model has.

The shop models are a small catalog plus orders:

prisma/schema.prisma
enum OrderStatus {
PENDING
PAID
SHIPPED
CANCELLED
}
model Product {
id String @id @default(uuid())
name String
sku String @unique
description String?
price Decimal
stock Int @default(0)
categoryId String?
category Category? @relation(fields: [categoryId], references: [id], onDelete: SetNull)
supplierId String?
supplier Supplier? @relation(fields: [supplierId], references: [id], onDelete: SetNull)
orderItems OrderItem[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
model Order {
id String @id @default(uuid())
number String @unique
customerId String
customer Customer @relation(fields: [customerId], references: [id], onDelete: Restrict)
status OrderStatus @default(PENDING)
total Decimal @default(0)
items OrderItem[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}

A few details matter for the admin:

  • Decimal is money. Prisma sends and receives it as a string; Dashild keeps it as a string on the wire and only converts it for display.
  • @unique on sku and Order.number becomes a server validation error, not a client-side guess.
  • Optional relations (categoryId, supplierId) can be cleared. Required relations (Order.customer, OrderItem.order) cannot.
  • @@unique([orderId, productId]) on OrderItem stops the same product from appearing twice in one order.
Terminal window
pnpm prisma migrate dev --name init
pnpm prisma generate
pnpm db:seed
  • migrate dev writes and applies the migration.
  • prisma generate regenerates the Prisma client and the Dashild metadata. On Prisma 7, migrate dev does not run this step for the metadata; skipping it leaves make:resource and the panel looking at the old models.
  • db:seed creates the demo users through Better Auth and inserts products, customers, orders, and items.

The account is:

Email Password
ana@shop.test dashild123
bruno@shop.test dashild123

pnpm db:seed is re-runnable: it deletes the demo rows in dependency order and creates them again.

4. The panel, its resources, and its widgets

Section titled “4. The panel, its resources, and its widgets”

src/dashild/panel.ts is the only place that decides what appears in the panel:

src/dashild/panel.ts
export const panel = definePanel({
title: "Admin",
path: "/admin",
locale: "en",
resources: [
categoryResource,
customerResource,
orderItemResource,
orderResource,
productResource,
supplierResource,
],
auth: { getCurrentUser, signOut },
});

A resource is data, not a page. The catch-all route src/app/admin/[[...dashild]]/page.tsx resolves every list, form, detail, and relation manager from this array. There is no generated page per model.

The shop dashboard with widgets

The dashboard combines stats, a chart, a table and the resource cards. Each widget is one file; the cards still open the same catch-all route with a different slug.

The example registers three widgets in the same panel:

src/dashild/panel.ts
widgets: [
revenueOverviewWidget,
ordersChartWidget,
latestOrdersWidget,
],
  • revenue-overview.ts returns four stats (revenue, orders, customers, low stock).
  • orders-chart.ts returns a doughnut chart with orders per status.
  • latest-orders.ts returns a table with the five newest orders.

All three receive the scoped Prisma client, so their numbers follow the same policies as the tables. The widgets guide explains the API, the chart types, and how to write your own.

The starter groups them in the sidebar:

  • Catalog: Categories, Products, Suppliers.
  • Sales: Customers, Order items, Orders.

The group comes from navigation.group in each resource file.

5. Products: money, stock, filters, and relations

Section titled “5. Products: money, stock, filters, and relations”

Open src/dashild/resources/product.ts. The column list is the table; the field list is the form:

src/dashild/resources/product.ts
export const productResource = defineResource({
model: "Product",
navigation: {
label: "Products",
slug: "products",
group: "Catalog",
icon: "package",
},
table: {
searchable: ["name", "sku"],
pageSize: 25,
columns: [
{ field: "name", sortable: true },
{ field: "sku", sortable: true },
{ field: "price", format: "currency", currency: "EUR", sortable: true },
{ field: "stock", format: "number", sortable: true },
{ field: "category", display: "name", sortable: true },
{ field: "supplier", display: "name" },
],
filters: [
{ field: "category", type: "relation", label: "Category", display: "name" },
{ field: "supplier", type: "relation", label: "Supplier", display: "name" },
],
},
form: {
fields: [
{ field: "name", type: "text", rules: { required: true } },
{ field: "sku", type: "text", rules: { required: true } },
{ field: "description", type: "textarea" },
{ field: "price", type: "number", rules: { required: true } },
{ field: "stock", type: "number", default: 0 },
{ field: "category", type: "relation", relation: "category", display: "name" },
{ field: "supplier", type: "relation", relation: "supplier", display: "name" },
],
},
policy: { scope: "public" },
});

The products table

price is rendered as EUR, stock as a number, and the relation columns show the display field instead of a raw id.

Creating a product

The create form uses the same field list with empty values.

Editing a product

The same field definitions build the create and edit forms. Decimal values arrive as strings; format: "currency" handles the display.

Two rules avoid surprises:

  • format: "currency" is presentation only. Validation and storage still use the Prisma Decimal; do not do arithmetic on the formatted value.
  • The policy.scope string is a marker, not a rule. "public" selects nothing; the real predicate lives in policies.ts (step 9).

Filters are server-side. The options for a relation filter are loaded with the active user’s policy scope, so a filter cannot reveal rows the user cannot read. Combining filters is a normal GET form, which means the URL is shareable and the back button works.

Products filtered by category

Filtering by Category is a GET request: the URL, pagination, and sorting stay in sync.

Declaring table.actions replaces the built-in create/view/edit/delete list, so the resource lists them explicitly and then adds its own:

src/dashild/resources/product.ts
actions: [
{ name: "create", placement: "header" },
{ name: "view", placement: "row" },
{ name: "edit", placement: "row" },
{ name: "delete", placement: "row" },
{
name: "restock",
label: "Restock +10",
placement: "row",
requires: "restock",
variant: "secondary",
data: { amount: 10 },
},
],

requires is the policy predicate that decides whether the action is visible and allowed. data is passed to the handler; confirm: true asks before running.

Product row actions

The row menu contains the declared actions. “Restock +10” sends { amount: 10 } to the handler.

The handler lives in src/dashild/actions/index.ts and runs on the server:

src/dashild/actions/index.ts
Product: {
restock: async (context) => {
if (!context.id) return { ok: false, message: "Missing product id." };
const db = dbFrom(context);
if (!db) return { ok: false, message: "Database client unavailable." };
const amount = Number(context.data?.amount ?? 10);
await db.product.update({
where: { id: context.id },
data: { stock: { increment: Number.isFinite(amount) ? amount : 10 } },
});
return { ok: true, message: `Stock increased by ${amount}.` };
},
},

context.db is Prisma extended with the policy scope. It is typed unknown and can be undefined, so the example narrows it with dbFrom. An update on a row outside the scope fails even with a guessed id. context.id is optional: always check it before a row action.

Orders use the same pattern to change status:

src/dashild/resources/order.ts
actions: [
// create, view, edit, delete...
{ name: "markPaid", label: "Mark paid", placement: "row", requires: "markPaid", variant: "secondary" },
{ name: "ship", label: "Ship", placement: "row", requires: "ship", variant: "secondary" },
{ name: "cancelOrder", label: "Cancel", placement: "row", requires: "cancelOrder", confirm: true },
],

Do not name a custom action cancel: it is a built-in form action and the panel would ignore yours. The example uses cancelOrder.

The orders table

Status is a badge with a tone per enum value; the actions change it without a page reload.

Open an order from Orders → row menu → View. The detail page shows the record and, below it, every one-to-many or many-to-many relation that has a registered child resource.

An order with its items

The order detail includes the Order items relation manager automatically.

The relation manager close up

Rows can be edited or deleted, and “Create related” opens the child form with the parent id already set.

Creating an order

A normal resource form: the customer relation is a select, and the status is an enum. The order items are managed from the detail page.

The manager is derived, not hand-written:

  1. Dashild reads the metadata and finds list fields on Order (items).
  2. It looks for a resource whose model matches the child (OrderItem).
  3. It checks the child policy allows list.
  4. It loads the rows with the child’s scope and the parent id applied.

The child’s foreign key decides what is possible. OrderItem.orderId is required, so an item cannot be dissociated from its order; it can only be edited or deleted. If the foreign key is optional, the manager also offers “associate” and “dissociate”. Many-to-many relations (the blog’s tags) use attach/detach.

The Order items resource also exists as a top-level list, so you can inspect all items and filter them by order or product:

Order items table

Relations are visible from both sides: the parent detail and the child list.

Customers store the id the app already synced from Stripe:

model Customer {
id String @id @default(uuid())
name String
email String?
phone String?
stripeCustomerId String?
orders Order[]
}

The customers table

The customer list stores the Stripe id on the record; the action below reads it when you open the dashboard.

The resource declares an action with no custom handler:

src/dashild/resources/customer.ts
actions: [
// create, view, edit, delete...
{
name: "openInStripe",
label: "Open in Stripe",
placement: "row",
variant: "outline",
},
],

The handler is the shared stripeActionHandler:

src/dashild/actions/index.ts
Customer: {
openInStripe: stripeActionHandler({
type: "customer",
field: "stripeCustomerId",
mode: "test",
}),
},

Customer row actions with the Stripe link

“Open in Stripe” reads the id through the scoped client and returns a dashboard URL.

What this does not do: call the Stripe API, read an API key, or receive webhooks. It builds https://dashboard.stripe.com/test/customers/<id> and opens it. Use mode: "live" for live ids. The same helper supports subscriptions, invoices, payments, products, and prices.

src/dashild/policies.ts is the authority. The shop is staff-only: public signup is closed and DASHILD_STAFF_EMAILS is an allowlist. A signed-in account outside the list sees nothing:

src/dashild/policies.ts
const staff = (ctx: { user: { email?: string } }) => {
const allowed = (process.env.DASHILD_STAFF_EMAILS ?? "")
.split(",")
.map((email) => email.trim().toLowerCase())
.filter(Boolean);
const email = ctx.user.email?.toLowerCase();
return Boolean(email && allowed.includes(email));
};
const scope = (ctx: { user: { email?: string } }) =>
staff(ctx) ? {} : null;
Product: {
scope,
can: {
create: staff,
update: staff,
delete: staff,
restock: staff,
},
},

scope returns a Prisma where. {} means “all rows”; null denies the resource. can decides permissions and declared actions are deny-by-default: if restock is missing from the predicates, the action is hidden and the server refuses it.

The seed enables signup only inside its own process so Better Auth can create the demo staff; the running app keeps ALLOW_SIGNUP="false". When you add staff, update DASHILD_STAFF_EMAILS. If you need roles instead of an allowlist, read User.role in the session and replace staff with hasRole(ctx, "ADMIN"); the multi-tenancy guide shows the same pattern with organizations.

Every list has Export and Import buttons. Export uses the current view: search, filters, sort, and page size. It writes the visible columns except Bytes fields, and relations become ids.

CSV import result

Import reports how many rows succeeded and how many failed. It creates rows; it does not update existing ones.

The imported product

The new row is a normal product: policy, validation, and the table refresh all apply.

Rules worth knowing:

  • Export cap: 5,000 rows. The response reports truncated when the view is larger.
  • Import cap: 1,000 rows and 2 MB.
  • Headers must match form.fields (name, sku, price, …). Unknown columns are ignored.
  • Relations use the form field name (category), with the id as the value, not the display name.
  • Types: Int/Float are coerced, booleans accept true/1, and Decimal/BigInt stay strings.
  • Create only: the import calls the same server save path as the form, so validation, uniqueness, and policies apply. It is not an upsert.

Advanced import mapping, updates, and background jobs are reserved for Dashild Pro; the open CSV path is deliberately small.

Terminal window
pnpm dev

Open http://localhost:3000/admin and sign in as ana@shop.test / dashild123.

What to check:

  1. Products: filter by category, sort by price, and open a product. Change the stock and save; the table refreshes.
  2. Restock +10: run it from a row menu and watch stock increase.
  3. Orders: filter by status, then open one. Add an item with Create related, edit its quantity, and delete it.
  4. Order actions: “Mark paid”, “Ship”, and “Cancel”. Cancel asks for confirmation.
  5. Customers: open “Open in Stripe” (test mode) with a seeded stripeCustomerId.
  6. CSV: export products, change a price in the file, and import it as a new row with a new sku.
  7. dark mode: the theme toggle is in the header.

Finally, verify the app the same way CI does:

Terminal window
pnpm dashild doctor
pnpm build

The dashboard is built from widgets, and each widget is one file. Create one with the command and a type:

Terminal window
pnpm dashild make:widget LowStock --stats
pnpm dashild make:widget RevenueChart --chart bar
pnpm dashild make:widget LatestCustomers --table

make:widget writes src/dashild/widgets/<name>.ts and registers the export in panel.ts. The file is write-once. A stats widget returns cards:

src/dashild/widgets/low-stock.ts
export const lowStockWidget = defineWidget({
type: "stats",
title: "Low stock",
width: "full",
async data({ db }) {
const client = db as ScopedClient;
const count = await client.product.count({ where: { stock: { lt: 10 } } });
return [
{
label: "Products",
value: count,
description: "Under 10 units",
color: count > 0 ? "warning" : "success",
},
];
},
});

A chart returns labels and datasets, and a table returns columns plus rows. The full contract, including width, sort, canView and the chart types, is in the widgets guide.

The starter is a normal Dashild app. To add a model:

Terminal window
pnpm prisma migrate dev --name add_reviews
pnpm prisma generate
pnpm dashild make:resource Review

make:resource writes src/dashild/resources/review.ts, registers it in panel.ts, and adds a fail-closed policy entry. Edit the columns, fields, and predicates, then run pnpm dashild doctor and pnpm build.

To add an action:

Terminal window
pnpm dashild make:action Review approve

That appends a handler stub without touching the resource. Declare it in table.actions or form.actions, add the predicate to policies.ts, and implement it with the scoped client.

For a deeper walkthrough of generating each resource by hand, read the vet clinic tutorial. It covers make:resource, custom cells, tenancy, and role-aware actions from an empty app.

  • make:resource says the model does not exist: the metadata is stale. Run pnpm prisma generate after migrate dev.
  • Empty relation options: the child resource is missing from panel.ts, or its policy denies list.
  • “No Stripe id”: the customer has no stripeCustomerId; the helper does not look the customer up in Stripe.
  • CSV import skips a column: the header must match a form field exactly. Relations need ids, not names.
  • A custom action does not appear: the name collides with a built-in (cancel, delete, save…) or the policy predicate is missing.