Skip to content
ExplanationForDeveloper⏱ About 12 min

Worked example: the SAWScore module ​

SAWScore scores buy-here-pay-here deals. It is a source module that BMA sells in the marketplace, and it uses most of what a module can do, so it is a good one to copy from. Everything below is in appcenter-next/modules/source/sawscore/. The scoring itself is driven by each organization's rulesets; this page is about the module's structure, not its scoring.

The folder ​

PathWhat it is
module.jsonthe manifest: id sawscore, kind: source, visibility: platform
api/routes.phpthe router file (api.entry) with the router function sawscore_module_route
api/routes_*.phpmore route files the router file requires: scoring, reports, documents, files, messages, share, webhooks, AI
api/Sawscore*.phpthe classes: SawscoreDb (database access), SawscoreStore, SawscoreEngine and the rest
migrations/001…004per-organization migrations for the sws_ tables
ui/src/index.tsthe UI bundle's entry: id, version, register(host)
ui/src/host.tslocal types for the host and the API helpers
ui/src/lib/helpers for tabs, shortcuts and messages that wrap the host calls

The manifest, in parts ​

json
"api": {
  "entry": "api/routes.php",
  "router": "sawscore_module_route",
  "prefixes": ["/sawscore"],
  "default_permission": "sawscore.use",
  "public_paths": ["/sawscore/share"]
}
  • Every /sawscore/… request has passed the entitlement gate before the router runs: the caller is signed in, the organization has SAWScore enabled, and the caller holds sawscore.use.
  • /sawscore/share/<token> is public (a shared read-only page). It skips sign-in and CSRF, so the router answers it first, before anything that needs a signed-in user, and checks the token itself.

Permissions are one key per capability: sawscore.use, .view, .score, .decide, .sales, .pii, .rulesets, .settings. Menu items each name the permission that shows them; the messages item also has a badge (host calls).

Data: "connection": "module", so the sws_ tables live on the organization's inventory connection. Each table is declared in data.tables with scope: tenant_column, and the four migrations are listed in data.migrations.

Two marketplace keys:

  • "x-entitlement": "marketplace": the organization's marketplace subscription switches SAWScore on and off. Organization administrators get 403 managed_by_marketplace if they try to install, enable, disable, upgrade or fork it; BMA staff keep every action.
  • "x-no-backfill": true: SAWScore is new in BMA 2.x, so the upgrade from classic installs never switches it on for an organization by itself.

The router ​

sawscore_module_route($method, $path, $body) in api/routes.php:

  1. Returns when the path is not /sawscore or under it, so the next router gets its turn.
  2. Answers the public share path, if it is one.
  3. Hands the rest to sawscore_module_dispatch, inside a try:
    • a SawscoreException becomes ApiResponse::error($message, $status, ['code' => …, 'details' => …]);
    • anything else becomes ApiResponse::fail('SAWScore could not complete the request', 500, $e, 'sawscore_error'): logged with a request id, never shown.
  4. Nothing matched: 404 not_found.

Each route then checks its own permission with sawscore_module_require('sawscore.score', …) (any one of the keys, else 403 forbidden).

Errors carry a code a screen can act on:

php
throw new SawscoreException('Choose a file to upload', 'no_file', 422);   // api/routes_files.php

Data bound to the organization ​

SawscoreDb (api/SawscoreDb.php) wraps the PDO connection and the organization id, made once per request:

php
$db = new SawscoreDb(ApiDb::inventory(), (int) Tenant::currentId());
$rows = $db->rows('SELECT * FROM sws_customers WHERE tenant_id = :tenant AND last_name = :n', array('n' => $name));
$id = $db->insert('sws_customers', array('first_name' => 'Avery', 'last_name' => 'Coleman'));
  • The constructor refuses an organization id of 0 or less.
  • rows(), one(), value() and exec() refuse SQL without the :tenant placeholder, and bind it themselves.
  • insert() and update() add the organization id; an update or delete of another organization's id touches nothing, and the route answers 404.

Why not InventoryQuery? InventoryQuery is for BMA's shared inventory tables: on an organization with a private database it turns its /*TENANT*/ token into 1=1 and leaves tenant_id out of inserts. SAWScore's own tables always carry tenant_id, so they bind it every time. Either way, the tenant scope lint is happy and the module's scope_verified is true.

Setting up on first use, not in a hook ​

sawscore_module_store() creates the store and calls ensureDefaults() (statuses, the default ruleset) on the first request of an organization. The comment there says why: install hooks run inside the registry's own transaction on the app database, and opening a second connection to write default rows would wait on that transaction.

So SAWScore's hooks class, SawscoreModuleHooks (in api/routes_talk.php), does only one thing: it keeps the module's cron job for mail notifications (sawscore-notify-mail-t<organization id>):

HookDoes
enableCronService::ensureModuleTaskJob(…)
upgradethe same, if the module is enabled
disable, uninstallCronService::removeModuleTaskJob(…)

The class also implements task($name, $ctx), which the cron runner calls only while SAWScore is enabled for that organization.

Settings with a secret ​

settings_schema has the decision sheet's options, the time zone, mail and AI settings. The AI key is "x-secret": true: it is sealed with the organization's key when saved, the settings form shows it as saved but never shows it again, and the screens never get it. The server reads it with ModuleRegistry::runtimeSettings($tenantId, 'sawscore').

The UI bundle ​

ui/src/index.ts exports id and version (filled in by the build) and register(host), which stores the host and returns no extra routes and twelve components, named by ui.routes[].component in the manifest. Every API call goes through host().api to /sawscore/…. The tab, badge and shortcut helpers in ui/src/lib/ check each host call before using it, so the bundle still works on an older shell.

Tests ​

SAWScore's tests are in tests/Modules/: SawscoreEngineTest.php (scoring, no sandbox), SawscoreHttpTest.php and the other Sawscore*Test.php files (routes, permissions and organization isolation against a sandbox), and MarketplaceSawscoreE2eTest.php (the marketplace switching it on and off). The pattern to copy is in Modules: sign, test, release and upgrade.