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.
1. Create the app
Section titled “1. Create the app”pnpm create dashild@latest my-shop --template shop --database sqlite --yescd my-shopThe scaffolder creates a Next.js app, installs Dashild, and applies the shop
starter. The starter adds:
- Six models:
Category,Supplier,Product,Customer,Order, andOrderItem. - One resource file per model under
src/dashild/resources/. src/dashild/policies.ts,src/dashild/actions/index.ts, and the panel registration insrc/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:
BETTER_AUTH_URL=http://localhost:3001 pnpm devThe starter is a folder template: a short template.json plus real files
under packages/create-dashild/templates/shop. List what is available with:
pnpm create dashild@latest --list-templates
The seeded demo account signs in at /login; the panel lives at /admin.
2. The data model
Section titled “2. The data model”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:
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:
Decimalis money. Prisma sends and receives it as a string; Dashild keeps it as a string on the wire and only converts it for display.@uniqueonskuandOrder.numberbecomes 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])onOrderItemstops the same product from appearing twice in one order.
3. Create the database and seed it
Section titled “3. Create the database and seed it”pnpm prisma migrate dev --name initpnpm prisma generatepnpm db:seedmigrate devwrites and applies the migration.prisma generateregenerates the Prisma client and the Dashild metadata. On Prisma 7,migrate devdoes not run this step for the metadata; skipping it leavesmake:resourceand the panel looking at the old models.db:seedcreates the demo users through Better Auth and inserts products, customers, orders, and items.
The account is:
| 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:
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 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:
widgets: [ revenueOverviewWidget, ordersChartWidget, latestOrdersWidget,],revenue-overview.tsreturns four stats (revenue, orders, customers, low stock).orders-chart.tsreturns a doughnut chart with orders per status.latest-orders.tsreturns 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:
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" },});
price is rendered as EUR, stock as a number, and the relation columns show
the display field instead of a raw id.

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

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 PrismaDecimal; do not do arithmetic on the formatted value.- The
policy.scopestring is a marker, not a rule."public"selects nothing; the real predicate lives inpolicies.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.

Filtering by Category is a GET request: the URL, pagination, and sorting stay in sync.
6. Actions: restock and order status
Section titled “6. Actions: restock and order status”Declaring table.actions replaces the built-in create/view/edit/delete list, so
the resource lists them explicitly and then adds its own:
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.

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:
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:
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.

Status is a badge with a tone per enum value; the actions change it without a page reload.
7. Orders and the relation manager
Section titled “7. Orders and the relation manager”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.

The order detail includes the Order items relation manager automatically.

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

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:
- Dashild reads the metadata and finds list fields on
Order(items). - It looks for a resource whose
modelmatches the child (OrderItem). - It checks the child policy allows
list. - 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:

Relations are visible from both sides: the parent detail and the child list.
8. Customers and Stripe links
Section titled “8. Customers and Stripe links”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 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:
actions: [ // create, view, edit, delete... { name: "openInStripe", label: "Open in Stripe", placement: "row", variant: "outline", },],The handler is the shared stripeActionHandler:
Customer: { openInStripe: stripeActionHandler({ type: "customer", field: "stripeCustomerId", mode: "test", }),},
“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.
9. Policies
Section titled “9. Policies”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:
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.
10. CSV import and export
Section titled “10. CSV import and export”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.

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

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
truncatedwhen 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/Floatare coerced, booleans accepttrue/1, andDecimal/BigIntstay 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.
11. Run it and try
Section titled “11. Run it and try”pnpm devOpen http://localhost:3000/admin and sign in as
ana@shop.test / dashild123.
What to check:
- Products: filter by category, sort by price, and open a product. Change the stock and save; the table refreshes.
- Restock +10: run it from a row menu and watch stock increase.
- Orders: filter by status, then open one. Add an item with Create related, edit its quantity, and delete it.
- Order actions: “Mark paid”, “Ship”, and “Cancel”. Cancel asks for confirmation.
- Customers: open “Open in Stripe” (test mode) with a seeded
stripeCustomerId. - CSV: export products, change a price in the file, and import it as a new
row with a new
sku. - dark mode: the theme toggle is in the header.
Finally, verify the app the same way CI does:
pnpm dashild doctorpnpm build12. Add a dashboard widget
Section titled “12. Add a dashboard widget”The dashboard is built from widgets, and each widget is one file. Create one with the command and a type:
pnpm dashild make:widget LowStock --statspnpm dashild make:widget RevenueChart --chart barpnpm dashild make:widget LatestCustomers --tablemake:widget writes src/dashild/widgets/<name>.ts and registers the export in
panel.ts. The file is write-once. A stats widget returns cards:
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.
13. Extend it
Section titled “13. Extend it”The starter is a normal Dashild app. To add a model:
pnpm prisma migrate dev --name add_reviewspnpm prisma generatepnpm dashild make:resource Reviewmake: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:
pnpm dashild make:action Review approveThat 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.
Troubleshooting
Section titled “Troubleshooting”make:resourcesays the model does not exist: the metadata is stale. Runpnpm prisma generateaftermigrate dev.- Empty relation options: the child resource is missing from
panel.ts, or its policy denieslist. - “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.