# The SaaS edition

SyncSHOP is sold on-premises and as SaaS hosted by us (`_docs/DISTRIBUTION.md`). The SaaS host is one more install of
the same packages plus `syncshop/saas` (`packages/saas`), which is never shipped to on-premises shops. It is one app
with **one database for every shop**, as ELVPro is, on [stancl/tenancy](https://tenancyforlaravel.com/docs/v3) 3.10
in single-database mode.

## Switching it on

`SYNCSHOP_EDITION=saas` in the host's `.env` (the default is `onprem`). Without it the package does nothing, so it can
sit in the development install. `SyncShop\Enums\Edition::current()` tells code which edition runs; the SaaS edition
hides Settings → Updates and its daily check, refuses `syncshop:update` and switches shell scheduled tasks off.

| Setting | Meaning |
| --- | --- |
| `SAAS_PLATFORM_DOMAIN` | syncshop.ro: the website, and our admin under `/admin` ([The project website](website.md)) |
| `SAAS_REPOSITORY_DOMAIN` | repo.syncshop.ro: the package server installed shops ask |
| `SAAS_CENTRAL_DOMAINS` | More hosts that are no shop's (comma-separated); the two above and `www.` are always ours |
| `SAAS_SHOP_DOMAIN` | A new shop's address is `<shop>.<this>` (`syncshop.ro`) until it brings its own domain |
| `SAAS_SCHEDULE_CONCURRENCY` | How many shops' schedulers `saas:schedule` runs at once (8) |

`DB_DATABASE` holds everything: the shops (`tenants`, each with a `number`), their hostnames (`domains`), our staff,
and every shop's rows, told apart by `shop_id` (= the shop's `number`). PostgreSQL shows a shop only its own rows:
after each `migrate`, every table with `shop_id` gets row-level security (enabled and forced, the policy
`syncshop_shop_rows`) and a `shop_id` default of the shop being served, which the app sets on the connection
(`syncshop.shop`, `ShopRows`) when it starts serving a shop and clears after. That covers Eloquent, the query builder
and raw SQL alike; serving no shop, reads find nothing and writes are refused. The host refuses to migrate or serve a shop over a database role that is a superuser or has BYPASSRLS, which row-level security never holds back. A table with neither `shop_id`
(`ShopTables::scope()`) nor a place on the shared list stops the migrate. Creating a shop adds a row, as an ELVPro
yard, and runs its data migrations (below); deleting it deletes its rows.

## Which shop is being served

- **Web:** the request's host, before cookies are decrypted or the session starts (`IdentifyShop`, the first global
  middleware). A host that belongs to no shop gets a 404.
- **Command line:** `php artisan <command> --shop=<id>`, or `SYNCSHOP_SHOP=<id>` in the environment (the commands a
  shop's scheduler starts inherit it). The shop is served from the boot on, so its schedule is read from its own
  rows. From code: `$shop->run(fn () => Artisan::call(…))`.
- **Queue:** a job carries the shop that queued it and runs for it (stancl's queue bootstrapper); Horizon itself runs
  for no shop. The `redis` connection uses the `saas-redis` driver (`ShopFairQueue`): a shop's jobs wait in its own
  list under the queue (`default@alfa`), and workers on `default` take from the host's list and each shop's in turn,
  so a shop that queues thousands of jobs delays the others by one job per turn. Horizon's settings stay as they are;
  its dashboard shows the shops' lists by name, and its balancing counts them with the queue.

`php artisan migrate` migrates the schema once, for every shop, then each shop's **data migrations**: spatie settings
migrations and any migration that implements `ShopDataMigration` (`@api`: the euro, the VAT classes, the first
location), recorded per shop in `shop_migrations`. A new shop runs them all when it is created. On-premises it is the
same, for shop 1. A migration that changes existing rows is a data migration too: the schema migration runs serving no
shop and sees none.

## What changes with the shop

| | |
| --- | --- |
| Rows | `syncshop.shop` on the connection: the database shows and fills only the shop's rows |
| Cache | the prefix gains `shop_<id>:`, set on the stores in place (locks and unique jobs included) |
| Files | `storage/shop_<id>/` for the `local` and `private` disks; the `public` and `media` disks under `storage/app/public/shops/<id>/`, served at `/storage/shops/<id>/` by the usual `storage:link` (no link per shop, nothing lost at a deploy) |
| Key | the shop's own `APP_KEY`, kept with the shop's row in `tenants`, encrypted with the host's: its stored secrets, signed links and HMACs open with nothing else |
| Address | `app.url` and the URL root (links built in jobs and commands) |
| Storage settings | the shop's Settings → Storage (S3 disks) |
| Broadcasts | `syncshop.broadcast.shop` = the shop id (`chat.inbox.<id>`) |
| Logs | every line carries `shop` |
| Services | scoped instances (settings classes, locations, B2B companies), the permission registrar and the password broker are reset |

## Our admin

`https://<SAAS_PLATFORM_DOMAIN>/admin` (`syncshop.ro/admin`) is where our staff manage the shops, next to the
licences, releases, legal data and the site's settings ([The project website](website.md)); shop hosts
never reach it, and it never reaches a shop's own admin. Only the **first** account is made on the host: `php artisan
saas:admin <email> --name=…` asks for a password (12 characters at least); after that, colleagues are invited from
**Echipa** (an e-mailed link, valid 24 hours, to choose a password), where an account can also be sent its invitation
again, made to set up two-factor again, or deleted (never one's own). "Ai uitat parola?" on the sign-in screen mails a
reset link; two-factor stays. `saas:admin --reset-two-factor` remains for someone locked out with nobody else to reset
them. Signing in takes the password, then a code from an authenticator app: the first time the screen shows the QR
code to set it up and, once confirmed, eight recovery codes shown once. The accounts are in their own table
(`central_admins`, shared by no shop), with their own guard (`central`) and their own middleware group (`saas.central`: cookies, session,
CSRF; no shop, no installer).

| Screen | Does |
| --- | --- |
| Magazine | Every shop with its address, licence, extensions and theme; search by name, code or address |
| Magazin nou | `CreateShop` from a form: code (the subdomain), name, licence, owner's name and e-mail |
| Echipa | Our staff: invite, send the invitation again, reset two-factor, delete |
| A shop | Its addresses (the first own domain becomes the main one; the SyncSHOP subdomain stays), extensions on/off (`SetShopExtensions`, permissions follow), child theme, licence key |

A shop's own domain is set up on the web server from the admin, as ELVPro does for a yard's domain: adding it
queues `ProvisionShopDomain`, which waits (5, 15, 30, then 60 minutes, for about a day) until the domain's A record
points at `SAAS_SERVER_IP`, then runs the one command the worker may sudo, `provision-domain-wrapper.sh <domain>`.
That adds the Hestia web domain, the host's nginx includes and a Let's Encrypt certificate, and forces HTTPS. The
domain shows *Așteaptă DNS*, *Se configurează*, *Activ* or *Nereușit* with the reason, and *Încearcă din nou* starts
over. The server side (`packages/saas/server`: the wrapper, the script, the sudoers entry, the Hestia template and
the runbook) is installed once, by hand, when the host is set up.

## An unpaid subscription

Liviu's timeline (open question 11): marked unpaid (by hand for now; from the billing later), the shop's owners get an
e-mail and every admin page shows the dates; after **7 days** the store closes to customers (a plain page in the
shop's name; payment and courier webhooks still arrive) and the admin turns read-only (any change answers 423); **30
days** later the admin closes too; **60 days** after that the shop is deleted, an export taken first. `saas:schedule`
moves shops along each minute (`ShopLifecycle::advance`, never backwards). On the shop's page in our admin
every step can be taken by hand at any time (mark unpaid, mark paid and reopen, close the store, close the admin),
and *Exportă acum* writes one tar.gz to `storage/app/private/saas-exports`: `data/<table>.ndjson` with the shop's rows
of every table it owns (a JSON object a line) and its files,
downloadable there. *Șterge magazinul* asks for the shop's code and deletes it after a final export. The days are in
`config/saas.php` (`lifecycle`); the owners write to `SAAS_BILLING_EMAIL`.

## Extensions and child themes per shop

An extension is installed once on the host (after our review) and **switched on per shop**: `saas:extension <shop>
<package>` (`--off` to switch it off). The core's registries note which extension added each menu item, settings card,
dashboard card, view slot, totals stage, scheduled task, permission, admin route and API resource (the extension
whose file called the registry), and the `ExtensionGate` (`@api`) lets them through only for shops where it is on; its
event listeners are wrapped the same way once the app has booted. Its tables call `ShopTables::scope()`; its data migrations run for every shop. Its
permissions follow: switching runs `permissions:sync` in the shop, which removes those of an extension that is off,
as for an uninstalled one. Settings → Extensions lists only the ones on for the shop. On-premises the gate lets
everything through and works nothing out.

A **child theme** is a folder `themes/<name>/resources/views` on the host (`SAAS_THEMES_PATH` to keep them elsewhere):
`saas:theme <shop> <name>` puts its views in front of the app's and `syncshop/theme-default`'s while that shop is
served (`--none` goes back to the default). It overrides only the views it contains.

## Commands

| Command | Does |
| --- | --- |
| `saas:shop:create <id> --owner=<email> [--name= --owner-name= --licence=]` | Creates a shop ready for its owner (`CreateShop`, the action our admin's "create shop" calls): its row and number, its key and `<id>.<SAAS_SHOP_DOMAIN>`; inside it its data migrations, the permissions, the owner (Owner role, invited by e-mail to set a password, as new staff are), the shop's name, a search collection of its own (`shop_<id>_products`) and the install marked done. Ids are 3–40 lowercase letters, digits and single hyphens, not reserved (`www`, `demo`, `repo`, `admin`, `api`, `app`, `mail`, `docs`, `status`, `static`, `cdn`) |
| `saas:extension <shop> <package> [--off]` | Switches an installed extension on or off for one shop |
| `saas:theme <shop> <name> [--none]` | Gives a shop a child theme, or takes it away |
| `saas:schedule` | The host's only cron line, every minute: each shop's `schedule:run --shop=<id>` in its own process |
| `tenants:run`, `tenants:list` | stancl's, for every shop or `--tenants=<id>` |

## Licence

A SaaS shop runs under a **hosted** licence (Licensing: a licence product with *Licență găzduită* on): the right to a
shop on our host while it is valid, never versions to download, so it has no update entitlement and the licence API
answers `"hosted": true`. `--licence=` keeps its key with the shop's row.

## Deploying the host

The host is a SyncSHOP project like an on-premises shop (the skeleton) with `syncshop/saas` required and
`SYNCSHOP_EDITION=saas`. Its `deploy.php` is the skeleton's with `require 'vendor/syncshop/saas/deploy/recipe.php';`
at the end: a pg_dump of the database before migrating by a backup role that reads past row-level security
(`DB_BACKUP_USERNAME` / `DB_BACKUP_PASSWORD`; the app's own role sees no shop's rows outside a shop; the last ten dumps
kept), `migrate` as on-premises, `permissions:sync` in every shop (`tenants:run`) and `addresses:sync` once. This repository's own `deploy.php` does the same for a host with `edition: saas` in `deploy/hosts.yml` (syncshop.ro). The host's cron runs `php artisan saas:schedule` every minute instead
of `schedule:run`; Horizon runs once for all shops.

## Writing code that works in both editions

Nothing in the core may know about the SaaS edition (an arch test checks it), so new code keeps to the rules in
DISTRIBUTION.md › How SaaS is built: no state in static properties or singletons, files only through disks, cache
keys through the cache, `config('app.key')` read at call time, no `Schedule::` lines, broadcast channel names built
with the shop (`ChatChanged::channel()`), and settings read when used, not copied into config at boot (the storage
settings are the one exception, re-applied for each shop).

## Tests

`composer test:saas` (part of `composer check`) runs `tests/Saas` with `phpunit.saas.xml`: one test database
with two shops, `alfa` and `beta`, created once per run (`tests/SaasTestCase.php`), with Redis as the
cache. Nothing is rolled back between tests, so each test writes values of its own.
