Skip to content

Writing a Tradehall module

A module is a Go package that plugs into Tradehall. It can add pages, database tables, permissions, sidebar entries, client tabs, and client portal pages, and it can reuse core’s clients, users, permissions, and billing. modules/timesheets is the smallest complete example. Read it first. modules/projects is a fuller one that also listens for another module’s events.

Laravel for Go compiles every package into the application binary; nothing loads at runtime. A module therefore ships as a Go package, and an installation chooses its modules at build time by listing them in bootstrap/modules.go:

func modules() []laravel.Package {
return core.Install(
invoicing.New(),
support.New(),
timesheets.New(),
)
}

A module in another repository is a Go module the app requires in go.mod, imported the same way.

Out-of-process apps (a REST API, webhooks, embedded panels) are planned for third parties who can’t or shouldn’t compile into the binary. They will use the same permission keys and entity IDs.

Export a type, usually built by New(), that implements core.Module:

  • Register(app *laravel.Registrar) error, from laravel.Package, adds what the module runs: routes (app.Web, or app.Bare for webhooks and public endpoints that take no session or CSRF token), migrations, listeners, jobs, commands, schedules, views, and its own settings read with app.Env(). Store settings on the module and call app.Services(m), then read them anywhere with laravel.ServicesOf[*Module](ctx). See the Laravel for Go package guide.
  • The other methods tell Tradehall how to present the module: its manifest, the permission keys it checks, staff sidebar entries, client portal entries, client tabs, invoice actions, dashboard widgets, search, AI tools, signals, and settings pages. Embed core.Defaults and write only the ones you need.
type Timesheets struct {
core.Defaults
rate numeric.Decimal
}
func (*Timesheets) Manifest() core.Manifest { /* ID, Name, Version, Description */ }
func (*Timesheets) Permissions() []core.Permission {
return []core.Permission{{Key: "timesheets.time.log", Label: "Log time"}}
}
func (*Timesheets) ClientTabs() []core.ClientTab {
return []core.ClientTab{{Label: "Time", Path: "/clients/{client}/time", Permission: "timesheets.time.log"}}
}
  • Permissions. Name keys <module>.<thing>.<verb>, such as invoicing.invoices.manage. Check them in every staff handler with access.Authorize(r, models.CurrentUser(r), "..."). A role holding * passes every check.
  • Client portal. Portal users are models.Users with a ClientID. Check ownership with user.BelongsToClient(record.ClientID) and answer 404, not 403, so a contact can’t probe for other clients’ records.
  • Routes. Wrap them in route.Middleware(auth.Authenticate{}).Group(...). Put portal routes under /portal/ and client tabs under /clients/{client}/. Go’s net/http patterns refuse two routes that overlap where neither is more specific, such as /agents/runs/{run} and /agents/{agent}/edit, so the app fails to start; pick paths that don’t overlap.
  • Tables. Register migrations in Register with app.Migrations(db.Migration{Name: ..., Run: ...}), written with the schema builder. Name them with a timestamp after core’s 2026_12_02_000000 so they run after the tables they reference. A model’s field whose name has an initialism other than ID, such as RedirectURIs, needs an explicit db:"redirect_uris" tag.
  • Billing. Never write to invoicing’s tables. Hand billable work to billing.Record from tradehall/core/billing, and invoicing will pick it up. The Source you pass shows on the client’s Invoices tab.
  • Sidebar. A NavItem may set Check, which runs on each page to hide the entry, such as for a feature the owner turned off, and to give it a badge count. Chat uses it for unread threads. Keep it to one quick query.
  • Activity. Record what happened to a client with activity.Record. Staff see every entry on the client page; set VisibleToClient for entries the client should see on their portal home.
  • Files. Store uploads with files.Uploads(ctx) from tradehall/core/files, under a folder named for your module, and keep the path in your table. It writes to the storage volume or the bucket, whichever the owner chose, and finds files from before a switch. Serve them through a handler that checks access, with disk.Download. modules/support/attachments.go is the example.
  • Config. Read environment variables in Register with app.Env().String, .Int, or .Bool, and return an error there for a bad value so the app fails at start.

Navigation() returns the module’s staff sidebar entries and PortalNavigation() its client portal entries. Give each staff entry:

  • a Group: core.NavWork (clients and the work done for them), core.NavSales (proposals, quotes, contracts, invoices), core.NavAutomation (agents and automations), or core.NavAdmin (running the installation). A group of your own, such as core.NavGroup("Inventory"), shows after Automation and before Admin. Leave Group empty in PortalNavigation, which has no headings.
  • an Icon, named from the list in resources/js/lib/icons.ts (Lucide names such as life-buoy). Add the icon there if your module needs another; an unknown name draws a dot.
  • an Order within the group, lower first. Core and the bundled modules use multiples of 10, so a new entry can sit between them.
func (*Support) Navigation() []core.NavItem {
return []core.NavItem{{Label: "Tickets", Href: "/tickets", Group: core.NavWork, Icon: "life-buoy", Order: 20, Permission: viewTickets}}
}

Each person can pin sidebar pages. Pins show at the top of the sidebar, and on phones the bottom tab bar holds the first three after Dashboard or Home. A pin only stores the entry’s Href, so keep hrefs stable once released.

Staff open the command palette with Ctrl+K or ⌘K, or the search button in the sidebar and on phones. It lists sidebar pages and, as they type, records from every module’s Search(). Return a search.Source from tradehall/core/search with the Permission needed to see results and a Find function that matches the query, with search.Pattern(query) for a case-insensitive WhereLike, and returns at most search.Limit results. Each search.Result has a Kind (“Ticket”), which groups results, a Title, a short Detail such as the client’s name, and the Href to open. Keep Find to one indexed query: it runs on every keystroke after a short pause. modules/support/search.go is the example.

A module whose work runs in the background, such as automation or agent runs, offers it to the monitoring page with Runs(), returning a runs.Source from tradehall/core/runs. List and Counts read the module’s own table; Retry and Cancel change it through the module’s own functions, and each run says whether it CanRetry (only when running it again can’t repeat something it already did) and CanCancel. List the queue jobs that carry the runs in JobNames, so the queue page sends people to the run instead of deleting its job. Queued jobs and scheduled tasks show on the page without any of this.

A module adds pages under Settings with Settings(). Put the user’s own preferences in the account group and business-wide controls in the business group, guarded by a permission. Account sections without a permission show to client contacts too, unless you set StaffOnly. MCP’s AI connections page is the example.

Register the routes yourself under /settings/<module>, and render the page with @/layouts/SettingsLayout, which draws the settings menu beside the page on wide screens and a link back to it on phones. To store values an admin changes at runtime, use settings.Get, settings.Put, and settings.Forget from tradehall/core/settings with keys named <module>.<thing>, rather than a table of your own. Keep secrets such as API keys in environment variables.

Anything a client sees should read the business’s name, logo, colour, and support contacts from branding.Current(ctx), not from APP_NAME, so installations can white-label Tradehall. Pages get it as the shared brand prop. Emails that render mail::layout pick up the logo, name, primary colour, and footer on their own.

The owner styles every page in Settings > Theme, which sets the shadcn/ui theme tokens for light and dark mode. So style pages only with token classes (bg-background, bg-card, text-foreground, text-muted-foreground, border-border, bg-primary, text-primary, text-destructive, bg-success/15, bg-warning/10, bg-info/10, bg-sidebar), never palette classes like text-stone-500 or bg-white, which ignore the theme and break dark mode. node bin/theme-tokens.mjs <files> rewrites the old palette classes in a page for you.

Settings > Custom code (permission branding.code) adds the owner’s CSS and scripts to the head and end of body of portal and login pages, and markup slots above and below portal pages and under the login form. TRADEHALL_SAFE_MODE=true turns all of it off.

A payment provider is a module that adds InvoiceActions, buttons on an unpaid invoice in the client portal. Each button posts to the provider’s own route, with {invoice} replaced by the invoice’s ID. When the money arrives, the provider calls invoicing.MarkPaid, which fires InvoicePaid and does nothing if the invoice is already paid, so call it from both a return page and a webhook. modules/stripe is the example.

A provider that also sends invoices, such as Stripe Invoicing, implements invoicing.Courier so invoicing skips its own invoice and receipt emails, and stores the PDF and any tax it calculated with invoicing.AttachDocument. The invoice pages then link to the provider’s PDF and show tax and amount due. Finance on Stripe describes the split.

A module offers actions to AI through Tools(). The same list backs the MCP server (modules/mcp), where Claude or another MCP client works as a signed-in staff member, and the agents module (modules/agents), where each agent works as its own staff account. Write each tool once and both get it.

func (*Timesheets) Tools() []tools.Tool {
return []tools.Tool{{
Name: "timesheets_log_time", // prefixed with the module ID, snake_case, 64 characters at most
Module: "timesheets",
Title: "Log time",
Description: "Log hours worked for a client...", // written for the model that calls it
Schema: map[string]any{"type": "object", "properties": map[string]any{ /* ... */ }},
Permission: "timesheets.time.log",
Effect: tools.Write, // Read, or Write for anything that changes data
Run: logTool,
}}
}
  • Run gets a context and an Invocation with the calling User and the JSON arguments. Read them with tools.Input[T](call).
  • Return a value that encodes as JSON, or an error from tools.InvalidInput, tools.NotFound, or tools.Denied. The error reaches the model as a tool error it can read and correct, so write messages for it: “due_on can’t be in the past.”
  • The registry checks Permission before Run, and only staff ever get tools. Check record-level rules inside Run, as a handler would.
  • Call the module’s own domain functions so events, activity, and email happen as they do from the UI.
  • Mark a tool tools.Write if it changes anything. Agents can be set to hold write tools for a person’s approval.

The staff dashboard is built from Dashboard(). Return one or more dashboard.Sources, each with an Order (core’s unbilled-work stat is 25; support 10, invoicing 20, projects 30, timesheets 40, agents 50), the Permission a user needs to see it, and a Load function that gets the signed-in user and returns widgets:

  • dashboard.Count, dashboard.MoneyStat, or dashboard.HoursStat for a headline number, with .WithDetail(..) for one line under it, .WithHref(..) to link the card, and .AttentionIf(..) when someone should act on it.
  • dashboard.NewList(title, emptyText, items) for up to five records to act on, each a dashboard.NewItem(title, detail, href) with an optional .WithBadge(..). Add .WithHref(..) for “View all”.

Keep loads quick: they run on every dashboard visit. Show only what a person can act on from the dashboard or one click away. A source that fails is logged and left out, so it can’t take the dashboard down. modules/support/dashboard.go is a short example.

The event catalog (tradehall/core/catalog) is how anything outside a module learns that something happened: automations today, and outgoing webhooks and the REST API later. Unlike signals, catalog events cover every change, including ones staff, agents, and automations make.

  • List the events a module publishes in Events(), each a catalog.Kind with a Key of <module>.<thing>_<past tense verb> (such as invoicing.invoice_paid), a Label, a Description, and an Example payload. Keys never change once released, since owners’ scripts depend on them. The example is what the script editor shows, what dry runs replay when nothing real has happened yet, and what the drafting agent reads.
  • Publish with catalog.Publish(ctx, key, clientID, data), from a listener of your module’s own typed event so every path fires it. Put JSON-ready records in data named by kind ({"invoice": invoice}). Automations add key, occurred_at, and client before a script sees it.
  • Pass the ctx you were given. A context from an automation run carries the automation’s account, which keeps an automation from triggering itself and stops chains between automations.

modules/invoicing/catalog.go is the example.

The owner adds custom fields to record types in Settings > Custom fields (Custom fields). Core stores the definitions and values, so a module adds no columns. To let the owner add fields to a module’s records, return fields.Entitys from CustomFields() (from tradehall/core/fields):

func (*Support) CustomFields() []fields.Entity {
return []fields.Entity{{
Key: "ticket", Label: "Tickets", Module: "support", Table: "tickets",
ViewPermission: viewTickets, EditPermission: manageTickets, Portal: true,
Find: fields.FindModel(func(ticket Ticket) *int64 { return &ticket.ClientID }),
}}
}

Make Key the record’s name in your catalog payloads ({"ticket": ticket}), so automations see its custom_fields. Then:

  • Record page. Pass fields.PanelFor(r, user, "ticket", ticket.ID) as the custom_fields prop and render <CustomFieldsPanel panel={custom_fields} /> from @/components/CustomFields. It saves through core’s PUT /custom-fields/{entity}/{record}, which checks EditPermission and fires core.custom_fields_changed.
  • List. Read fields.ListFrom(r.URL.Query()), narrow the query with fields.Apply before your own OrderBy, and pass fields.ListPageFor as custom_fields. Render <CustomFieldFilters list={custom_fields} /> above the table and spread listColumns(custom_fields) into its headers and rows.
  • Portal page. Pass fields.PortalPanelFor(r, "ticket", ticket.ID) and render <PortalCustomFields panel={custom_fields} />. It holds only the fields marked for clients.
  • Deleting a record. Call fields.Forget(ctx, "ticket", id).

The custom_fields_* tools already cover every registered record type, so a module writes no field tools of its own.

A signal is a moment agents can act on, such as support.ticket_opened. List the ones a module sends in Signals() so the agent form offers them, and send them with signals.Send(ctx, key, clientID, summary, data), usually from a listener of the module’s own event. The summary becomes the agent’s task, so write it in plain language with the client’s own words, and put record IDs in data. Don’t signal for actions staff or agents took, or an agent can trigger itself.

Modules talk to each other through events, never through each other’s tables. A module exports its event types and dispatches them with event.Dispatch from its domain functions, not its handlers, so every path that changes the data fires them:

Module Events
Invoicing invoicing.InvoiceIssued, invoicing.InvoicePaid, invoicing.InvoiceVoided, invoicing.QuoteSent, invoicing.QuoteAccepted, invoicing.QuoteDeclined
Support support.TicketOpened, support.TicketReplied (not fired for internal notes)
Contracts contracts.ContractSent, contracts.ContractSigned, contracts.ContractDeclined
Agents agents.RunFinished, agents.ActionsRequested (a chat run paused for approval), agents.ActionDecided
Proposals proposals.ProposalSent, proposals.ProposalAccepted (with the signed contract and the issued invoice), proposals.ProposalDeclined

To react to another module’s event, import its package and register a listener in Register. Projects does this to mark milestones paid when their invoice is paid:

app.Listeners(laravel.Listen(markMilestonesPaid))
func markMilestonesPaid(ctx context.Context, e invoicing.InvoicePaid) error {
return MarkPaid(ctx, e.Invoice.Number)
}

Importing another module makes that module required, so only do it when your module has no reason to exist without it.

Events dispatched inside a database transaction run their listeners after it commits. Queue slow or fallible work such as email (mail.To(..).Queue(..)) rather than sending it inline.

  • Email. Write a mailable whose view lives in your package’s resources/views/mail/. Embed the views with //go:embed resources/views, register them with app.Views("<id>", ...), and name the view <id>::mail.<name>. Mail views are html/template files that start with {{template "mail::layout" .}} and fill {{define "content"}}. models.Recipients(ctx, clientID) gives the addresses for a client: its portal contacts, or the client’s own email when it has none.
  • Standalone pages. For something that isn’t an Inertia page, such as invoicing’s print view, return web.View("<id>::<name>", data).
  • Schedules. Write a console command, register it with app.Commands, and schedule it with app.Schedule, such as invoicing’s daily invoicing:recur at 06:00. Keep the work in a plain exported function so tests call it directly, as invoicing.IssueDue does.

Pages are React components rendered through Inertia. Put them in modules/<id>/resources/js/pages/<Name>/, and render them by that path, such as inertia.Render("Timesheets/ClientTab", ...). The app’s Vite build finds module pages on its own.

Import the shared building blocks with the @/ alias:

  • @/layouts/AppLayout for a normal page, or @/layouts/ClientLayout for a client tab (it draws the client header and every module’s tabs).
  • @/components/ui for panels, tables, buttons, fields, and badges. These are shadcn/ui components (Button, Input, Select, Textarea, Card, Badge, table parts) plus PageHeader, Panel, Field, Table, and Cell.
  • @/lib/format for money and dates.

Known gap: Laravel for Go’s AssertInertia checks that the page file exists in resources/js/pages, so tests check module pages with tests.Page(res, "Component"), which compares the component name only. A module published in its own repository will also need a step that copies its pages into the app’s build. Both are fine for modules that live in this repository.

Feature tests live in tests/feature, because they need the whole application. tests has helpers: tests.New(t), tests.Owner(c), tests.StaffWith(c, "perm"), tests.Client(c), and tests.ContactOf(c, client). Fake the Claude API, Stripe, and GitHub with httpclienttest.New(c). Cover the unauthenticated, forbidden, invalid, and happy paths for each route.