SIGNALS Docs
Reader View

Documents & Templates

Per-warehouse document templates, PDF rendering, numbering sequences, public sharing, and the template editor.

Overview

The Document Engine renders PDFs and HTML from per-warehouse Blade templates — invoices, credit notes, quotes, purchase orders, receipts, and other document types. Templates compile through a sandboxed Blade compiler with an allowlisted tag set; DomPDF drives PDF output with repeating headers and footers on every page.

Generated documents are first-class records with status, versioning, audit trail, and webhook events (document.created, document.finalised, document.voided, document.pdf_generated). Equipment-test certificates additionally record generic issued_at and issued_by metadata and emit equipment_test_certificate.issued.

Template editor

Routes:

Route Purpose
/admin/document-templates List templates by warehouse and type
/admin/document-templates/{template}/edit Three-panel editor

The editor provides:

  • Field browser — insert fields from the field registry
  • CodeMirror 6 source editor — sandboxed Blade source
  • Live preview — rendered output against sample data
  • Version history — diff, restore, export/import
  • Set default / restore default — for system templates

Allowed template expressions

Body, header and footer expressions are validated on save, import, preview and generation. You can read provided data ($rental->title, $lines[0]->name, $branding['logo_url'], $loop->iteration), use literal strings, numbers, arrays, true, false and null, and combine them with arithmetic, comparisons, logical operators, concatenation, ternaries and ??. isset, empty and nullsafe property access are supported. Use @foreach or @forelse with simple key/value variables for iteration; references and @for are not supported.

The only callable helpers are abs, count, date, e, implode, join, max, min, nl2br, number_format, round, strtolower, strtoupper, trim and ucfirst. Call them directly, for example {{ number_format($total, 2) }}. Method and static calls, dynamic calls (including string literals and array elements), closures, construction, PHP tags, shell commands, includes, eval, assignments, variable variables, dynamic properties, global state and renderer internals are refused.

An existing stored template that fails these rules cannot be previewed or used to generate a new document. The editor or API returns the refusal reason, and the application records a Document template render blocked warning with the template/version/section identifier. Correct the template before retrying; unsafe content is never silently removed. Already issued documents remain unchanged and continue to use their stored output.

Template CSS for PDFs

When a CSS variable supplies a background, use background-color: var(--primary-colour) rather than the background shorthand; DomPDF does not reliably paint variable shorthand backgrounds on table cells. Use the contrast-corrected --primary-ink, --secondary-ink, --accent-ink, and --tertiary-ink variables for text. Reserve --on-primary, --on-secondary, --on-accent, and --on-tertiary for text placed on the matching filled colour.

Communication templates (billing emails) use a parallel editor at /admin/settings/communication-templates/{template}/edit — see Notifications & Comms.

Generating documents

From the UI, generate documents on rentals (Documents tab at /rentals/{rental}/documents), invoices, credit notes, and other documentables.

Via API:

  • POST /api/v1/documents/generate — single document (sync or async)
  • POST /api/v1/documents/batch_generate — batch generation job. Poll the returned status_url. The payload has status (processing, retrying, completed or failed), total, completed and document_ids. A failed payload also has error (the first refusal message) and, for a coded refusal, code (for example rental_document_precision_missing). A coded, guard, authorization or missing-source refusal fails the batch at once and keeps the documents already generated. Any other failure is retried. A retry, or a second copy of the job, reuses the document already generated for each batch item, so no item gets a second document, and completes a document that a prior attempt stopped before finishing. A retry uses no new document number, with one exception: when two copies insert the same item at the same moment, the losing copy has already taken a number, so that one number is not used.
  • POST /api/v1/documents/{id}/finalise — lock rendered output
  • POST /api/v1/documents/{id}/void — void a document
  • POST /api/v1/equipment_test_results/{result}/certificate/issue — issue the result's one final compliance certificate

output_format accepts preview, pdf or html_download; html is not supported. Batch generation rejects output_format: null. Invalid documentable types, output formats, or missing required template/type inputs return synchronous 422 before dispatch. A template or source record that no longer exists returns 404. Use the public documentable_type aliases shown by the API schema.

Single generation accepts a flat custom_fields object for the created document. Final documents protect their immutable fields. See Documents API.

Captured money precision

Invoice, credit-note and receipt money fields remain decimal strings. They use the invoice's captured version 1 money_unit_facts (original currency and decimal places), including historical precision that differs from today's currency metadata. Receipt amounts inherit the invoice's units; credit-note amounts retain their positive credit presentation, while invoice adjustments and refunds retain their signs. These fields do not use base-currency precision or recalculate captured minor amounts.

Missing, malformed, unsupported-version or mismatched original units refuse new rendering. The generation action returns Unable to resolve document data. without creating a document, output snapshot or audit entry. It does not infer precision from ISO defaults or company settings. This is historical display support, independent of new-posting currency admission.

The billing issue path reuses an existing issued PDF and its stored data before resolving live source data, including invoices without captured units. Existing PDFs, snapshots and history are preserved. This repair does not enable prospective rollout or rerender historical documents.

Frozen regeneration

Finalised documents regenerate from rendered_data snapshots — the template at generation time is preserved even if the live template changes later.

Equipment-test certificates use the final status as Issued in their result UI. They can only reach that state through the certificate issue action, which rechecks that the test is certifying and passed; generic document finalisation refuses this document type. There is one certificate per result: it is issued once, remains final, and cannot be revoked or re-issued. If an amended result needs certification, create a new equipment-test result and issue its certificate. Delivery is download and handover.

Rental phase variables

Rental document resolvers expose the ordered rental.phases collection and direct access through rental.phases_by_key.<key>, for example rental.phases_by_key.delivery.starts_at_formatted. Each entry includes key, label, sequence, UTC starts_at and ends_at, warehouse-local starts_at_formatted and ends_at_formatted, timezone, colour, blocks_availability and operational_role.

Attached hidden and archived definitions remain available, including partial endpoints; an unset endpoint remains null. The template editor's field picker reflects current definition labels and keys. Use the collection for an ordered schedule or the key lookup for a specific definition. Commercial and warehouse system templates include phase schedules.

Issued documents retain their rendered-data snapshot, including phase dates and definition presentation. Later edits to dates, labels, colours, blocking or roles do not rewrite that snapshot. Quote versions and alternatives share rental phases, while issued output keeps its captured schedule. See Rentals.

Numbering sequences

Route: /admin/settings/numbering

Per-entity numbering schemes (rentals, invoices, credit notes, accounts, payments, purchase orders, etc.) are backed by document_sequences with warehouse scoping and collision guards. The admin page shows a live preview of the next number for each scheme.

Rental numbering converges on the same sequence infrastructure as invoices and documents.

API: GET /api/v1/document_sequences lists schemes; PUT /api/v1/document_sequences/{documentSequence} updates one scheme. See Document Sequences API.

Public sharing

Share finalised documents via tokenised public links:

Feature Description
Token URL {app-url}/d/{token} (prefix configurable via documents.public_route_prefix)
PIN protection Optional PIN verified at POST /d/{token}/pin
Expiry Configurable link expiry
QR code QR on shared links for mobile access

Manage links via API: POST, PUT, and DELETE /api/v1/documents/{id}/public_link.

Sharing a document for approval turns the same link into the branded customer portal — question thread, approve/decline, and invoice payments. See Document Portal.

Public HTML responses are hardened against stored XSS; preview rendering enforces authorisation to prevent IDOR.

Downloads

Authenticated downloads use signed temporary URLs. Every download path sets a human-readable filename derived from the document number and type.

Document branding

Document rendering resolves branding at render time rather than baking one company palette into a template. The four colours follow these precedence chains:

Colour Resolution order
Primary Template branding_config.primary_colour → warehouse brand_primary_colour → branding.primary_colour → documents.defaults.branding.primary_colour (#1f2937)
Secondary Template branding_config.secondary_colour → warehouse brand_secondary_colour → branding.secondary_colour → documents.defaults.branding.secondary_colour (#6b7280)
Accent Template branding_config.accent_colour → branding.accent_colour → documents.defaults.branding.accent_colour (#374151)
Tertiary Template branding_config.tertiary_colour → branding.tertiary_colour → documents.defaults.branding.tertiary_colour (#9ca3af)

The company logo uses the same most-specific-first principle: template branding_config.logo_path, then the warehouse brand_logo_path, then company-wide branding.logo_path. For PDF safety the selected raster image (GIF, JPEG, PNG, or WebP) is validated, capped at a 512 KB data URI, and embedded directly as a data: URI; a missing, unreadable, unsupported, or oversized image is logged and omitted instead of breaking document generation. branding.logo_has_transparency supplies transparency metadata when the company-wide logo is selected.

The canonical system templates put that logo above the organisation name on the eleven external-facing types: Quote, Invoice, Pro Forma, Deposit, Credit Note, Statement, Receipt, Delivery Note, Delivery Note (with prices), Purchase Order, and Equipment Test Certificate. Internal operational templates keep their existing compact headers.

New warehouses receive the canonical branding-aware content from SystemDocumentTemplates when their system templates are seeded. User-created templates are untouched.

Using it in the app

Document administration lives under Admin → Preferences (sidebar group preferences).

Screen Route Permission
Numbering /admin/settings/numbering numbering.view / numbering.edit
Document templates index /admin/document-templates document_templates.view
Template editor /admin/document-templates/{template}/edit document_templates.view; save needs document_templates.edit
Rental Documents tab /rentals/{rental}/documents Tab: documents.view; generate: documents.create

Communication templates (billing emails) use a separate editor at /admin/settings/communication-templates/{template}/edit — see Notifications & Comms.

Document templates index

The index is a full data table with live filters, column toggles, and export.

Columns: Name, Document Type, Warehouse, Status badges (Default / System / Active / Inactive), Version, Last Edited, Actions

Toolbar: New template (when document_templates.edit) opens a modal with three starting points:

Starting point Use when
Base on existing Clone a template
Blank for document type System starter for a type
Completely empty From scratch

Row actions (edit permission + warehouse scope): Edit, Duplicate, Set default, Restore default (system templates), Delete (non-system)

Three-panel template editor

Full-screen editor at /admin/document-templates/{id}/edit.

Area Contents
Field browser Searchable snippet list from the field registry — click to insert at cursor
CodeMirror tabs Body, Header, Footer, Styles — sandboxed Blade source
Live preview Rendered output; toggle Sample vs Real entity data; optional record picker; zoom control
Version sidebar Version history with diff viewer and Restore
Top bar Page, branding & numbering modal; Refresh preview; Save

Page setup modal covers margins, page size, logo upload, and per-template document sequence (prefix, suffix, year/month toggles, next number, padding) with live next-number preview.

Open preview in a new window via the preview panel controls when you need a detached render.

Numbering admin

Route: /admin/settings/numbering

Two sections:

  1. Per-warehouse table — Standard Invoice, Deposit Invoice, Pro Forma Invoice, Credit Note, Purchase Order, Virtual Stock Intake, Rental — each row shows a live next number preview and an edit pencil (when numbering.edit)
  2. Global — Account and Payment numbers shared across warehouses

The edit modal exposes prefix, suffix, next number, digit padding, and include year/month switches with a live preview string. reset_frequency (never, yearly or monthly, default never) restarts the counter at 1 when the year or month rolls over. It is set on the sequence through PUT /api/v1/document_sequences/{id} and is not shown in the edit modal. yearly requires include year, and monthly requires include year and month; a rollover is refused if the format does not carry the period.

Rental and invoice documents

On a rental, the Documents tab (badge = document count) shows:

Generate document card — pick Template, Output (PDF or HTML), click Generate.

Document table — Number, Type, Status, Created, First viewed, and a row ⋯ actions menu holding:

Action Permission
Download Signed URL when file exists
Share documents.share — opens public link modal
Copy link / QR When link already exists
Configure Update expiry / PIN on existing link
Revoke Remove public link

The same ⋯ menu carries the document actions on the Account, Credit note and Payment Documents tabs.

Share modal: optional expiry datetime, optional PIN (min 4 chars), QR code for the public URL, copy-to-clipboard. Public URLs use /d/{token} (configurable prefix).

After saving a link the modal does not leave you parked in a dialog: it returns you to the Documents tab for the record you were on (rental, account, credit note or payment) with ?shared={id}. That page flags the document's row and prints the portal link with its QR and a Copy link button, so the thing to hand the customer is the obvious next click. Where the modal was opened from a surface that names no area — the print menu, a conversation panel — the document's own parent record decides where you land.

Finalise and void document actions exist on the API but are not exposed as buttons on the rental Documents tab — generated documents move through statuses via backend rules and API calls.

Invoice PDFs from invoice detail use the billing document type for that invoice's warehouse; see Invoicing.

Permissions summary

Permission UI effect
document_templates.view Templates index and editor (read)
document_templates.edit Save template, row mutations, new template
numbering.view Numbering admin page
numbering.edit Edit sequence modal
documents.view Rental Documents tab
documents.create Generate document card
documents.share Share / configure / revoke public links
documents.record-response Record a customer decision received by staff; Admin and Operations Manager by default

Attachment files and downloads

Record attachments use the parent record’s policy and warehouse scope on every surface, including API-backed MCP calls and search results. Reading or downloading requires parent view; upload, rename and delete require parent update. Invoice and credit-note additions use a dedicated attachment ability backed by invoices.edit and parent visibility, including issued or locked invoices. Issued invoice and credit-note attachments cannot be deleted; locked invoice attachments cannot be deleted either. Adding a file changes no financial fields. The uploader does not bypass this check. The file list omits parents the viewer cannot read, including missing parents.

Attachments and export files are private. Attachment links expire within five minutes and require authentication plus a fresh parent-access check when opened. Downloads use attachment disposition and nosniff. Public document links remain separate: their token, expiry, final status, privacy restrictions and optional PIN protect generated document bytes and grant no access to record attachments. See Storage for file access controls.

Rental templates receive their line collection as $lines; use @foreach ($lines as $line) to render names, quantities and the fields shown in the field browser. This collection is shared by quote, delivery-note and pick-list templates and their preview data.

Document-template creation accepts a public resource alias in model_type, such as rental; omit it or send null to use the document type’s registered source. Portable template imports require that source alias to match the registered document type. Pass the object returned in data by GET /api/v1/document_templates/{documentTemplate}/export as payload to POST /api/v1/document_templates/import, together with the destination warehouse_id. The portable definition requires export_format: "signals.document_template", export_version: 1, and non-empty name, document_type, model_type, and body_html strings. Optional HTML, CSS and description fields accept strings or null; page_config and branding_config accept objects or null; is_active accepts a boolean. Empty configuration objects serialize as {}.

Portable exports require nonblank template content, including body_html. Incomplete drafts remain editable, and exporting them returns HTTP 422 with field validation errors until the required content is supplied.

page_config accepts only page_size, page_orientation, page_width_mm, page_height_mm, display_unit, margins, header_height_mm, and footer_height_mm. Margins accept only top, right, bottom, and left. Unknown keys are rejected by API commands, portable imports, and the template editor.

When a workflow resolves rental document data, account identity, contact details and tax number follow the workflow service principal’s corresponding account permissions. Fields it cannot read resolve to null.