# Writing an extension

An extension is a Composer package of type `syncshop-extension`, found by Laravel's package discovery. It lives in
the shop's project (`extensions/<name>`, loaded through a `path` repository) or in its own repository when it is reused
across shops. It never edits `vendor/` and never alters core tables. Rules: `_docs/DISTRIBUTION.md` › Customisations.
The sample extension in `packages/core/tests/Fixtures/extensions/sample` uses every extension point below.

## composer.json

```json
{
    "name": "acme/syncshop-erp",
    "type": "syncshop-extension",
    "require": { "php": "^8.5", "syncshop/core": "^1.4" },
    "autoload": { "psr-4": { "Acme\\SyncShopErp\\": "src/" } },
    "extra": {
        "laravel": { "providers": ["Acme\\SyncShopErp\\ErpServiceProvider"] },
        "syncshop": { "name": "Acme ERP", "owner": "client" }
    }
}
```

`owner` is `client`, `agency` or `syncshop`. The `syncshop/core` constraint is what Settings → Extensions shows and
what stops an update the extension has not been checked against.

## The service provider

Add everything in `boot()`: the core's registries are bound by then, whatever order the providers load in. Every type
named below is `@api` ([Extension API](extension-api.md)).

| Extension point | Call | Notes |
| --- | --- | --- |
| Admin screens | `AdminRoutes::add(fn () => Route::get(...)->name('acme-erp.index'))` | Under `/admin`, names start `admin.`, behind sign-in, two-factor and the staff session |
| Sidebar entry | `AdminMenu::add(new MenuItem(...))` | Shown to staff holding any of its permissions |
| Settings card | `SettingsSections::add(new SettingsSection(...))` | A card under Settings linking to the extension's screen |
| Settings storage | `SettingsClasses::add(ErpSettings::class)` | A `spatie/laravel-settings` class; create its properties in a settings migration loaded with `loadMigrationsFrom()` |
| Permissions | `PermissionRegistry::add(new PermissionDefinition('acme-erp.sync.run', 'acme-erp::erp.permission', [SystemRole::ShopManager]))` | Named `<extension>.<action>`; `permissions:sync` writes them and removes those of an uninstalled extension |
| Recurring jobs | `ScheduledTaskRegistry::add(new ScheduledTaskDefinition(...))` | Never a `Schedule::` line; the owner can change or pause it |
| Dashboard cards | `DashboardWidgets::add(new DashboardWidget(...))` | The view renders the card body; `@inject` what it needs |
| Domain events | `Event::listen(OrderPlaced::class, PushOrder::class)` | Events are the modules' `Data\` classes |
| Markup on pages | `ViewSlots::add(ViewSlot::ProductAfterPrice, 'acme-erp::slots.price')` | The view gets only the slot's context (ids); slots are listed in [Extension API](extension-api.md) |
| Pricing rules | `TotalsStages::after(TotalsStages::PROMOTIONS, MemberDiscount::class)` | A `TotalsStage` before or after a named slot (`promotions`, `vouchers`, `loyalty`, `shipping`, `sgr`, `vat`); never after `vat` or around `gift_cards`, so VAT is always worked out on final prices. Discounts are `Adjustment`s with an amount per line |
| API endpoints | `ApiResources::add(StockSyncResource::class)` | An `ApiResource` with `path()` "acme-erp/stock-sync" (served at `/api/v1/acme-erp/stock-sync`), its own key for the scopes and texts under `acme-erp::erp.api.<key>`; it appears in the OpenAPI file and the Postman collection |

The domain events an extension can listen to, with their payload, are listed in [Extension API](extension-api.md).

Views, strings and migrations use the extension's own namespace: `loadViewsFrom(..., 'acme-erp')`,
`loadTranslationsFrom(..., 'acme-erp')` (labels are translation keys such as `acme-erp::erp.menu`), and its own tables.

Every shop's rows sit in the same tables, told apart by a `shop_id` column (on the SaaS host as well as on-premises,
where every row is shop 1's). Right after creating a table that holds a shop's data, call `ShopTables::scope()`
(`@api`): it adds `shop_id` and makes the table's natural keys unique per shop (a code, a slug, an e-mail), so two
shops may use the same one. Don't name `shop_id` in your queries; it is filled and checked for you. An `upsert()` on
such a key names it in the conflict: `->upsert($rows, ['shop_id', 'code'], [...])`.

```php
Schema::create('acme_erp_links', function (Blueprint $table): void {
    $table->id();
    $table->string('code')->unique();
    $table->timestampsTz();
});

resolve(ShopTables::class)->scope('acme_erp_links');
```

## On the SaaS host

The same extension runs on our SaaS host, installed once and switched on per shop (`saas:extension`). Everything
added through the extension points above, and the listeners registered in `boot()`, is used only for the shops it is
on for, so register through them rather than by hand (a route outside `AdminRoutes`, a `View::composer`, a
middleware pushed onto the core's groups would run for every shop). `ExtensionGate` (`@api`) answers whether an
extension is on for the shop being served. Keep per-request state out of static properties: one process serves many
shops.

## Keeping to the contract

The extension's tests check that it uses only `@api` core types:

```php
use SyncShop\Testing\ApiContract;

it('uses only the SyncSHOP API', function (): void {
    expect(ApiContract::violations(__DIR__.'/../src'))->toBe([]);
});
```
