Admin Table
elements man recipes/admin-tableA searchable, paginated table of orders with inline actions ("ship", "refund")
per row. Admin-only: the route and each RPC function call isUserAdminOrThrow
from the shared admin helpers before doing anything else. Search and status filter run
server-side via an @rpc that returns a page of results plus the total count.
The recipe composes three patterns already shown elsewhere: admin role gating
(app/shared/services/admin.ts from elements man recipes admin-roles),
debounced server-driven search (from elements man recipes search-filter), and
offset-based pagination with page numbers. Each inline action calls an @rpc
function that updates one row and returns the refreshed page, so the table
re-renders.
Migration
Terminalelements create migration 'add orders' -tables=orders
app/migrations/<timestamp>-add-orders.migration.sql-- add orders -- Auto-update updatedAt on row changes. create or replace function touchUpdatedAt() returns trigger language plpgsql as $$ begin new.updatedAt = now(); return new; end; $$; create type orderStatus as enum ('pending', 'shipped', 'refunded'); create table orders ( id uuid primary key default uuidGenerateV7(), createdAt timestamptz not null default now(), updatedAt timestamptz not null default now(), customerName text not null, status orderStatus not null default 'pending', amountCents integer not null ); create index ordersStatusIdx on orders (status); create index ordersCreatedAtIdx on orders (createdAt desc); create trigger ordersTouchUpdatedAt before update on orders for each row execute function touchUpdatedAt();
orderStatus is a Postgres enum that constrains the status column to the three
valid values. The query uses the index on status for the status filter and the
index on createdAt desc for the newest-first sort.
Page setup
Terminalelements create page admin-orders
The Order interface, the OrderQuery interface, the search RPC, and the
status-update RPC are used only by this page, so they are declared in the page's
own services.ts.
The admin gate comes from app/shared/services/admin.ts (see
elements man recipes admin-roles for that file). The query types and the two
RPC functions are long enough to crowd the markup, so they go in a services.ts
sibling rather than in template.ehtml. The route runs the initial search and
passes the first page to the template; the template debounces filter changes and
refreshes via the same rpc.
app/pages/admin-orders/services.tsimport { sql } from "@elements/app"; import { isUserAdminOrThrow } from "#app/shared/services/admin"; export type OrderStatus = "pending" | "shipped" | "refunded"; export interface Order { id: string; createdAt: Date; customerName: string; status: OrderStatus; amountCents: number; } export interface OrderQuery { text: string; status: OrderStatus | "all"; page: number; } export interface OrderPage { orders: Order[]; total: number; page: number; pageCount: number; } const PAGE_SIZE = 25; /** @rpc */ export function searchOrders(query: OrderQuery): OrderPage { isUserAdminOrThrow(); let pattern = `%${query.text.trim()}%`; let page = Math.max(1, query.page); let offset = (page - 1) * PAGE_SIZE; let total: number; let rows: Order[]; if (query.status === "all") { total = sql<{ count: number }>(` select count(*)::int as count from orders where customerName ilike ${pattern} `).firstOrThrow().count; rows = sql<Order>(` select id, createdAt, customerName, status, amountCents from orders where customerName ilike ${pattern} order by createdAt desc limit ${PAGE_SIZE} offset ${offset} `).all(); } else { total = sql<{ count: number }>(` select count(*)::int as count from orders where customerName ilike ${pattern} and status = ${query.status} `).firstOrThrow().count; rows = sql<Order>(` select id, createdAt, customerName, status, amountCents from orders where customerName ilike ${pattern} and status = ${query.status} order by createdAt desc limit ${PAGE_SIZE} offset ${offset} `).all(); } let pageCount = Math.max(1, Math.ceil(total / PAGE_SIZE)); return { orders: rows, total, page, pageCount, }; } /** @rpc */ export function setOrderStatus(orderId: string, status: OrderStatus, query: OrderQuery): OrderPage { isUserAdminOrThrow(); sql(` update orders set status = ${status} where id = ${orderId} `); return searchOrders(query); }
searchOrders runs one pair of queries when the status filter is "all" and
another pair when it is a specific status. Only the second pair has
status = ... in its where clause, so only those queries use the status
index. Both
branches return the page rows plus the total count so the template can render
page numbers.
setOrderStatus updates one row and re-runs the search with the current query,
returning the refreshed page. The template assigns the returned page to
results.value, so the table re-renders with the new status. The admin check at the
top blocks a non-admin who knows the RPC name from calling it directly over the
network; the route guard below blocks page rendering for non-admins.
app/pages/admin-orders/index.tsimport { Request, Response } from "@elements/app"; import adminOrders from "./template"; import { isUserAdminOrThrow } from "#app/shared/services/admin"; import { searchOrders, OrderQuery } from "./services"; export default function route(req: Request, res: Response) { isUserAdminOrThrow(); let initialQuery: OrderQuery = { text: "", status: "all", page: 1, }; let initial = searchOrders(initialQuery); return new adminOrders({ initial }); }
The route gates on admin status, runs an initial search with the default query,
and passes the first page into the template. The server renders the first page of orders into the
HTML, so the browser shows them without calling searchOrders after the page
loads.
app/pages/admin-orders/template.ehtmlimport "./style.css"; import { Badge } from "@elements/ui/badge"; import { Button } from "@elements/ui/button"; import { Input } from "@elements/ui/input"; import { NativeSelect } from "@elements/ui/native-select"; import { Pagination } from "@elements/ui/pagination"; import { Table, TableHead, TableCell } from "@elements/ui/table"; import { Order, OrderQuery, OrderStatus, OrderPage, searchOrders, setOrderStatus, } from "./services"; let debounceTimer: ReturnType<typeof setTimeout> | null = null; function refresh(query: OrderQuery, results: { value: OrderPage }) { results.value = searchOrders({ text: query.text, status: query.status, page: query.page, }); } function onChange(query: OrderQuery, results: { value: OrderPage }) { if (debounceTimer !== null) { clearTimeout(debounceTimer); } debounceTimer = setTimeout(() => { query.page = 1; refresh(query, results); }, 300); } function onGoToPage(target: number, query: OrderQuery, results: { value: OrderPage }) { if (target < 1) { return; } if (target > results.value.pageCount) { return; } query.page = target; refresh(query, results); } function onAction(orderId: string, status: OrderStatus, query: OrderQuery, results: { value: OrderPage }) { results.value = setOrderStatus(orderId, status, { text: query.text, status: query.status, page: query.page, }); } function statusVariant(status: OrderStatus): "warning" | "success" | "secondary" { switch (status) { case "pending": return "warning"; case "shipped": return "success"; case "refunded": return "secondary"; } } <html class="page-admin-orders" ( initial: OrderPage, private query: OrderQuery = { text: "", status: "all", page: 1, }, private results: { value: OrderPage } = { value: initial }, )> <main class="page-shell"> <h1>orders</h1> <form class="row"> <Input value={query.text} placeholder="search by customer" attrs={{ "aria-label": "search by customer" }} oninput={() => onChange(query, results)} /> <NativeSelect value={query.status} attrs={{ "aria-label": "status" }} onchange={() => onChange(query, results)}> <option value="all">all statuses</option> <option value="pending">pending</option> <option value="shipped">shipped</option> <option value="refunded">refunded</option> </NativeSelect> </form> <Table label="orders"> <table> <thead> <tr> <TableHead>customer</TableHead> <TableHead>status</TableHead> <TableHead align="end">amount</TableHead> <TableHead>placed</TableHead> <TableHead align="end">actions</TableHead> </tr> </thead> <tbody> <tr e:for={o of results.value.orders}> <TableCell>{o.customerName}</TableCell> <TableCell><Badge variant={statusVariant(o.status)}>{o.status}</Badge></TableCell> <TableCell align="end">${(o.amountCents / 100).toFixed(2)}</TableCell> <TableCell>{o.createdAt.toLocaleDateString()}</TableCell> <TableCell align="end"> <Button e:if={o.status === "pending"} size="sm" onclick={() => onAction(o.id, "shipped", query, results)}> ship </Button> <Button e:if={o.status === "shipped" || o.status === "pending"} size="sm" onclick={() => onAction(o.id, "refunded", query, results)}> refund </Button> </TableCell> </tr> <tr e:if={results.value.orders.length === 0}> <TableCell colspan={5}>no orders match.</TableCell> </tr> </tbody> </table> </Table> <Pagination page={results.value.page} total={results.value.pageCount} onPageChange={(target) => onGoToPage(target, query, results)} /> <p class="hint">{results.value.total} orders</p> </main> </html>
The filters, the table, the status pill, the row actions and the pager are
@elements/ui templates: Input (opens in a new tab) and
NativeSelect (opens in a new tab) bind query.text and
query.status two-way, Table (opens in a new tab) styles the native
<table> inside it, with align="end" on the number columns, a
Badge (opens in a new tab) carries the status, a small
Button (opens in a new tab) runs each action, and
Pagination (opens in a new tab) draws the page numbers from
pageCount. statusVariant maps the three statuses to a badge variant, so
the badge's color is set by its variant attribute and the page writes no CSS
class for it.
The Input and the NativeSelect both call onChange, which debounces a
single refresh across them. Every search resets query.page = 1 because the
previous page number may not exist after filters narrow the result set.
Pagination is bound two-way to results.value.page: a press writes the new
page and calls onPageChange with it, which runs onGoToPage. onGoToPage
returns without searching when the page is below 1 or above pageCount, and
otherwise re-runs the search. The page number is stored in
query.page, so refresh sends it with the text and the status in every
searchOrders call.
onAction calls the per-row mutation RPC with the current query attached, so
the RPC can return the refreshed page in one round-trip. The template binds the
returned page directly to results.value.
Routes
Register the page in index.ts:
index.tsimport adminOrders from "#app/pages/admin-orders"; // ... app.route("/admin/orders", adminOrders);
Notes
- Offset vs cursor pagination. Page numbers (offset/limit) match admin UX
expectations: jump to page N, see total page count, navigate freely. For
high-churn streams, where inserts between pages shift the offsets, use the
keyset window shown in
elements man recipes infinite-scroll-feed. - Single RPC returns the refreshed page.
setOrderStatusre-runs the search and returns the new page. The alternative is two RPC per action (mutate + re-search); the single RPC keeps the round-trip count down and avoids a second loading state in the UI. - Status type: union instead of
const enum. The TS side is a union ("pending" | "shipped" | "refunded") rather than aconst enum. The Postgres enum already declares the value list, so a TS-side enum would declare it a second time. The values are sent between the server and the browser as plain strings, so a union matches what's actually transmitted (status: "shipped"in JSON,status === "shipped"in code) without anOrderStatus.Shippedindirection. Type narrowing on a union is the same as on aconst enumat the call sites; exhaustiveswitchchecks both ways. Neither form adds a runtime object to the browser bundle. Adding"cancelled"is the same two-line change either way:alter type orderStatus add value 'cancelled'plus extending the value list. If you'd rather centralize the values for autocomplete via dot-access (OrderStatus.Shipped), swap toexport const enum OrderStatus { Pending = "pending", ... }; both forms send the same JSON strings between the server and the browser. - Sorting. Add a
sort: "newest" | "oldest" | "highest" | "lowest"field toOrderQueryand switch theorder byclause inside the rpc. The header cells become clickable; clicking callsonChangewith the new sort. - Bulk actions. Add a
selected: string[]to template state and a "selected" column with checkboxes (group={selected} value={o.id}). A toolbar button calls a bulk RPC that takes the id list and the new status.