# Tenant migrations (production)

## Deploy after git pull (recommended)

After pulling new code on the server, run the deploy script to run central migrations, tenant migrations, and tenant seeders for all tenants:

```bash
./scripts/deploy.sh
```

Or from project root: `bash scripts/deploy.sh`

The script runs (in order):

1. `php artisan migrate --force` — central database
2. `php artisan tenants:migrate-all --skip-missing` — all tenant databases
3. `php artisan tenants:seed-all --skip-missing` — DatabaseSeeder for each tenant

---

## Update database on production (manual)

Run these on the **production server** (e.g. via SSH) from the project root. Use `--force` so the command does not ask for confirmation.

**1. Central database (app/tenants table, etc.):**
```bash
php artisan migrate --force
```

**2. All tenant databases:**
```bash
php artisan tenants:migrate-all --skip-missing
```

**3. All tenant seeders (optional, also run by deploy.sh):**
```bash
php artisan tenants:seed-all --skip-missing
```

Use `--skip-missing` so that if a tenant has no database yet, the command skips it and continues with the rest.

---

## Run migrations on all tenants

**Production (all tenants, skip missing DBs):**
```bash
php artisan tenants:migrate-all --skip-missing
```

**Production (all tenants, fail on first missing DB):**
```bash
php artisan tenants:migrate
```

**Specific tenant(s):**
```bash
# One tenant
php artisan tenants:migrate --tenants=17eb61d8-f9be-4fe8-ad76-937f9b79144e

# Multiple tenants (custom command)
php artisan tenants:migrate-all --tenants=id1,id2,id3 --skip-missing
```

Use `--skip-missing` when some tenants have no database (e.g. stale tenant records) so the command continues and migrates the rest.

---

## New tenants

New tenants **already get all tenant migrations** when they are created. The pipeline is:

1. `TenantCreated` → `CreateDatabase` → **`MigrateDatabase`**
2. `MigrateDatabase` runs `tenants:migrate` for that tenant.
3. That runs every migration in `database/migrations/` (including `stock_adjustment_previews`).

So **no seed or config change is required** for new tenants; the `stock_adjustment_previews` table is created by the existing migration when the tenant database is first migrated.
