Skip to content
MSO CloudDocumentation

Plugin development

On this page

An optional feature or connector is a plugin: a declarative manifest plus the code it describes, gating a page, a menu item and a data route.

The plugin contract#

Identity, tenancy, RLS, roles, warehouse, i18n and audit are always on; everything optional is a plugin in one compiled catalog, never loaded dynamically.

Artifact Lives in
Manifest packages/plugin-host/src/registry.ts
tRPC router apps/web/src/server/routers/<feature>.ts
Pages apps/web/src/app/(dashboard)/<feature>/
API routes apps/web/src/app/api/<feature>/
Tables and RLS packages/schema/src/tables/
Copy packages/i18n/src/messages/{vi,en}.ts
Pure logic, shared UI a workspace package (optional)

Manifest fields

The schema in packages/plugin-host/src/manifest.ts is strict and parsed at module load, so an unknown key fails the build.

Field Required Meaning
id yes Stable kebab-case id, also the persisted installation key; never renamed
version yes Manifest version, written on each installation row
nameKey, descriptionKey yes Catalog card copy; must resolve in Vietnamese and English
category yes ai_decision, analytics, growth, operations, market_intelligence or data_source (connectors)
navItemIds yes Menu ids the plugin owns, hidden while it is off; [] when headless
replacesNavItemIds no Generic menu ids hidden while this plugin is on; hides from the menu only
providesPillars features only Metric pillars it owns; one owner per pillar, asserted at load; ecom has none
providesCapabilities connectors only Organization capabilities an active credential of this connector is evidence for
defaultEnabled yes On where the shape runs a home domain; true without one fails the build
legacyOrgFlag yes null for every new plugin
prerequisite yes ai_config (the organization needs a saved AI key) or none
dependsOn no Plugins that must be on first, transitively; the graph must be acyclic
kind no (default feature) feature, connector or satellite
connectorFamily connectors only marketplace, marketing, dataset, market_intel or content_intel; the family is the data plane
transport connectors only api, file or both
vertical, servesDomains connectors only The catalog heading and every domain one credential can serve
thirdPartyData connectors only The data describes the market rather than the organization; renders the third-party badge
providerId connectors only The worker connector registry id or parser id that implements it
clientId satellites only The OIDC client id the app is registered under in the issuer
launchUrl satellites only An https URL on the app's own origin; the launcher opens it. An environment variable named after the client id (<CLIENTID>_URL) overrides it
scopes satellites only Platform API scopes the app may request, platform:<plane>.<verb>
planIds satellites only Plan ids an installation may carry

Gate API

From @yng/plugin-host, inside the caller's tenant scope; the caller owns the super-admin bypass and role checks.

Function Returns
isPluginEnabledForOrg(orgId, id) Whether one plugin is on for one organization
getEnabledPluginIdsForOrg(orgId) The whole enabled set, one query
getDisabledNavItemsForOrg(orgId) Menu ids to hide because their plugin is off
getReplacedNavItemsForOrg(orgId) Generic menu ids hidden by an active tailored pack
orgHasConnectorFamily(orgId, family) Whether the org has a live credential in a family

The installation row decides (no row means off); a plugin is also off while anything in dependsOn is off. A reconcile derives each organization's rows from its shape on blueprint apply, domain activation and every deploy, never overriding a super admin's manual row.

Where entitlement is enforced

OnOff, or no rowDependency offSuper admin, plugin offPage (requirePlugin)rendersnot-found in shellnot-found in shellrendersMenu (layout)item shownitem hiddenitem hiddenhidden; reach by URLData (dedicated procedure)answersFORBIDDENFORBIDDENanswersOff: the installation row is disabled or inactive, or there is no row (a missing row is not an entitlement).Dependency off: a plugin in dependsOn is off, transitively; the gate derives this at read time and writes nothing.Super admin: the guard and the procedure return before reading the row; the caller owns that bypass, never the gate.
What each layer does per state. Hiding a menu item is never the gate: the page guard and the dedicated procedure are, and both let a super admin through.

A dedicated page, deep links included, calls requirePlugin('<id>') first; a console page uses requireAdminTenantPlugin. A new plugin gets its own router on a dedicated procedure, like chatProcedure. Routers core pages also read stay on orgProcedure, so a plugin turned off cannot break a core surface.

How to#

Add a plugin

  1. Print the snippets: pnpm tsx scripts/scaffold-plugin.ts <id> <category> [navItemId ...]. It writes nothing and covers feature plugins; write a connector manifest by hand.
  2. Paste the manifest into MANIFESTS in packages/plugin-host/src/registry.ts. Use defaultEnabled: true only with a home domain; otherwise list it in the blueprints that want it.
  3. Add plugins.<camelId>.name and .description to packages/i18n/src/messages/vi.ts and en.ts.
  4. Check every navItemId exists in ORG_MENU_ITEMS (apps/web/src/lib/rbac.ts); add it to MENU_ITEM_LABEL_KEYS to make it renamable.
  5. Call await requirePlugin('<id>') first in each dedicated page's server component.
  6. Declare the page's report-surface manifest beside it and run pnpm surfaces:generate.
  7. Deploy. The reconcile writes each organization's installation row; no backfill is needed.

Add an export to a page

Exports go through @yng/exports, <ExportMenu> and useExportMenu. PDF renders server-side from the page's own URL. Reader view: Exports: CSV, Excel, PDF.

  1. Tabular export (CSV and Excel): build items from typed rows, headers from t().

    const { items } = useExportMenu<OrderRow>({
      locale,
      filename: 'orders',
      excludePdf: true, // operations lists are tabular only
      table: {
        sheet: {
          name: t('orders.export.sheet'),
          columns: [
            { header: t('orders.col.id'), value: (r) => r.id },
            { header: t('orders.col.amount'), value: (r) => r.amountVnd }, // integer VND
            { header: t('orders.col.placedAt'), value: (r) => r.placedAt }, // Date to ISO
          ],
          rows,
        },
      },
    });
    return <ExportMenu label={t('common.export')} items={items} />;
    
  2. PDF of a server page: wrap the body in <PdfExportPage filename="…" pdfTitle="…"> from @/lib/page-export-wrapper; its header prop places the action in the page header.

  3. PDF plus tabular: pass pdfRef and pdfTitle with table. A multi-tab deck passes pdfWholeDeck for one whole-deck PDF.

  4. File names go through safeFilename(): no diacritics, at most 64 characters, an ISO date suffix.

Wire period comparison into a report

Comparison state lives in the URL; @yng/ui/compare-period is the one period implementation for filter bar and server. Reader view: Explore and period comparison.

  1. Parse the URL with parseReportFilters() (apps/web/src/app/(dashboard)/reports/_lib/report-filters.ts): compare=1 plus comparePreset (previous, year-ago, custom) yields filters.compare.

  2. Fetch the primary and comparison windows in parallel:

    const filters = parseReportFilters(await searchParams, 45);
    const compareFilters = filters.compare
      ? { ...filters, from: filters.compare.from, to: filters.compare.to }
      : null;
    const [report, compareReport] = await Promise.all([
      caller.reports.settlement(filters),
      compareFilters ? caller.reports.settlement(compareFilters) : Promise.resolve(null),
    ]);
    
  3. Render each KPI delta through the shared delta formatter: a dash for a zero or non-finite baseline.

  4. On an Explore-style page, pass compareFrom and compareTo to explore.query; the response carries summary.previousValue and previousTimeSeries.

Verify#

pnpm tsx scripts/audit/plugin-manifest-validity.ts
pnpm run typecheck && pnpm run lint
pnpm run audit:all
pnpm --filter @yng/web build

A cached typecheck can pass on stale output, so run the build. Then toggle the plugin for a test organization at /admin/orgs/<slug>/plugins and confirm the menu item and the not-found page follow.

Troubleshoot#

Symptom Cause Fix
Build fails at module load with a manifest parse error An unknown key, or a field on the wrong kind Check the cross-field rules above
The plugin is on in the catalog but its menu item never shows The organization's hidden-menu list hides it, or a dependency is off Un-hide the item, or enable the dependency
A gate read returns off for every organization in a script The script did not open a tenant scope Pin each organization before reading installation rows
A toggle is blocked in the admin catalog The plugin needs a saved AI key, or a dependsOn plugin is off Enable the dependency first; enabling never cascades
A year-ago comparison shows zeros The organization has less than a year of data Expected; sample data covers a few months
  • Never rename a plugin id; add a new plugin and bump version for changes.
  • org_plugin_installations.config is reserved; a plugin's settings belong in its own tables or settings page.