# Deploying charity-analytics to cPanel + MariaDB shared hosting

Step-by-step guide for installing the app on a shared host with cPanel, phpMyAdmin, MariaDB, and SSH access (no Docker).

---

## 0. Pre-flight — check before you start

In cPanel:

- **MultiPHP Manager** → confirm PHP **8.3+** is available (Laravel 13 + your `composer.json` require `^8.3`; PHP 8.4 if MultiPHP offers it). If only 8.2, ask the host to enable 8.3.
- **`pdftotext`** (poppler-utils) — optional but recommended: the AI website
  appraisal reads charity annual reports and audited accounts locally with it,
  which is what lets the report quote a PDF and have that quote checked. Run
  `which pdftotext`; if the host has it elsewhere, set `AI_PDFTOTEXT_BIN` to the
  full path. Without it the feature still runs, and says PDF text was
  unavailable.
- **MultiPHP INI Editor** → bump these for your domain:
    ```ini
    memory_limit=512M
    max_execution_time=600
    upload_max_filesize=256M
    post_max_size=256M
    ```
    Filament admin needs the headroom.
- **PHP Selector → Extensions** → enable: `pdo_mysql, mbstring, xml, bcmath, gd, zip, intl, opcache, fileinfo, openssl, ctype, json, tokenizer, curl`.
- **MySQL/MariaDB quota** — check your plan's max DB size. The full `irs990.sql` is **1.6 GB / 2.88M rows**. Most shared plans cap at 1–5 GB. If you're under-quota, you'll need to filter the dataset before upload (e.g. only `is_featured=1` rows or only one country).
- **SSH access** with composer pre-installed (`composer --version` should work). If not, install user-local:
    ```bash
    curl -sS https://getcomposer.org/installer | php
    ```
- **Softaculous** is for one-click WordPress/Joomla installs — **not useful** for a custom Laravel app. Skip it.

---

## 1. Build assets locally (before upload)

Shared hosts usually lack Node.js. Build on your laptop:

```bash
cd /Users/noahvanboven/Downloads/2026_TEOS_XML_01A/charity-analytics
composer install --no-dev --optimize-autoloader --no-scripts
npm ci
npm run build
```

Confirm `public/build/manifest.json` exists.

---

## 2. Create a MariaDB database in cPanel

cPanel → **MySQL® Databases**:

1. Create database, e.g. `youruser_charity` (cPanel prefixes your username).
2. Create user, e.g. `youruser_app`, strong password.
3. **Add User to Database**, grant ALL PRIVILEGES.
4. Note the host (usually `localhost`).

---

## 3. Upload files

Easiest: cPanel **File Manager** → upload the project as a zip → extract. Or use SSH/SFTP:

```bash
# Local: package everything except .git, node_modules, and the huge SQL dump
cd /Users/noahvanboven/Downloads/2026_TEOS_XML_01A
tar --exclude='charity-analytics/.git' \
    --exclude='charity-analytics/node_modules' \
    --exclude='charity-analytics/docker/mysql/irs990.sql' \
    -czf charity-app.tar.gz charity-analytics

scp charity-app.tar.gz youruser@yourhost:~/
```

On the server via SSH:

```bash
cd ~
tar -xzf charity-app.tar.gz
mv charity-analytics charity-app   # rename if you want
cd charity-app
```

---

## 4. Import the database

Don't try phpMyAdmin for a 1.6 GB dump — it'll time out. SCP the dump separately and use the MariaDB CLI:

```bash
# Local
scp /Users/noahvanboven/Downloads/2026_TEOS_XML_01A/charity-analytics/docker/mysql/irs990.sql \
    youruser@yourhost:~/

# Server
mysql -u youruser_app -p youruser_charity < ~/irs990.sql
# Type password when prompted. Takes 20–60 min on shared disk.
rm ~/irs990.sql   # clean up
```

### Slim the dump if your quota can't fit 1.6 GB

```bash
# Example: only featured + large US charities
mysqldump irs990 \
  --where="is_featured=1 OR (country_code='US' AND total_revenue>1000000)" \
  charities > slim.sql

# Add the other tables (users, cache, sessions, etc.) too:
mysqldump irs990 \
  --ignore-table=irs990.charities \
  >> slim.sql
```

Then also append `docker/mysql/z_laravel_framework.sql` so the `migrations` tracking table is pre-populated:

```bash
cat docker/mysql/z_laravel_framework.sql | \
    mysql -u youruser_app -p youruser_charity
```

---

## 5. Configure `.env`

```bash
cd ~/charity-app
cp .env.example .env
nano .env
```

Set at minimum:

```ini
APP_NAME="Charity Analytics"
APP_ENV=production
APP_DEBUG=false
APP_URL=https://yourdomain.tld
APP_KEY=                         # leave blank — generated next

DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=youruser_charity
DB_USERNAME=youruser_app
DB_PASSWORD=the-password-from-step-2

# Shared hosting: keep the cache and sessions off the database.
# Both default to `database`, and on this app that is ~17 MySQL round trips on
# every single page load and every Livewire click — the app caches (colours,
# columns, lenses, text zones), the rate limiter behind `throttle:60,1`, and the
# session read/write. On one machine with a local disk, files are far cheaper.
# (Leave these as `database` only if you ever run the app on more than one
# server, where a file cache would not be shared.)
CACHE_STORE=file
SESSION_DRIVER=file

ADMIN_NAME="Your Name"
ADMIN_EMAIL=you@yourdomain.tld
# Must be strong and unique — the seeder refuses passwords under 8 chars or
# known-weak defaults, and silently skips creating the account if unset.
ADMIN_PASSWORD=set-a-strong-one

LOG_CHANNEL=stack
SESSION_DRIVER=database
CACHE_STORE=database
QUEUE_CONNECTION=database

# IRS_* vars only matter if running Python loaders on the server (unlikely on shared host).
RESCORE_ON_BOOT=false
```

Generate the app key:

```bash
php artisan key:generate
```

---

## 6. Install vendor deps on the server (if you skipped step 1)

If you uploaded without `vendor/`:

```bash
composer install --no-dev --optimize-autoloader --no-interaction
```

---

## 7. Run migrations + seed admin user

```bash
php artisan migrate --force
php artisan db:seed --class=AdminUserSeeder --force
php artisan db:seed --class=ColumnTooltipSeeder --force
```

If the dump from step 4 already included `z_laravel_framework.sql`, the migrations table is pre-populated and `migrate` will be a near no-op (only the Round 2 columns get added if missing).

---

## 8. Point your domain to `public/`

Laravel's web root is `public/`, not the project root. cPanel default is `~/public_html/`. Two options:

### Option A (recommended): edit the domain's document root

cPanel → **Domains** → click your domain → **Document Root** → set to `/home/youruser/charity-app/public`. Save.

### Option B: move `public/` contents to `public_html/`

If cPanel won't let you change docroot:

```bash
mv ~/public_html ~/public_html.bak
cp -r ~/charity-app/public ~/public_html
nano ~/public_html/index.php
```

Change these two lines:

```php
require __DIR__.'/../vendor/autoload.php';
$app = require_once __DIR__.'/../bootstrap/app.php';
```

to:

```php
require __DIR__.'/../charity-app/vendor/autoload.php';
$app = require_once __DIR__.'/../charity-app/bootstrap/app.php';
```

---

## 9. Permissions

```bash
cd ~/charity-app
chmod -R 755 storage bootstrap/cache
# If web server runs as a different user (rare on cPanel), use 775 + group write:
# chmod -R 775 storage bootstrap/cache
```

Storage symlink (for uploaded charity logos):

```bash
php artisan storage:link
```

If `storage:link` fails because `public/storage` already exists, delete it first.

---

## 10. Warm caches

```bash
php artisan config:cache
php artisan route:cache
php artisan view:cache
php artisan event:cache
php artisan filament:optimize   # caches Filament's component discovery + icons
```

> ⚠️ **Edit `.env` later?** Re-run `php artisan config:clear && php artisan config:cache`.
> Once config is cached, `env()` calls outside of `config/*.php` return `null`.
> The seeders here use `config()` so they survive caching, but only if `.env`
> was finalized _before_ `config:cache` ran.

---

## 11. Cron for Laravel scheduler + queue worker

cPanel → **Cron Jobs**. Many shared cPanel plans cap cron frequency at every 5 minutes minimum (no `* * * * *`). The schedules below are sized for 5-min cadence — if your plan allows every-minute crons, you can change `*/5` to `*` for faster queue pickup.

```cron
# Laravel scheduler — every 5 min (app currently defines no sub-5-min scheduled tasks)
*/5 * * * * cd /home/youruser/charity-app && /usr/local/bin/php artisan schedule:run >> /dev/null 2>&1

# Queue worker — sized to your host's per-process time limit.
# 1800s (30 min) handles most CRA / large IRS imports. Bump higher if your host
# allows it (premium cPanel plans usually do; basic plans cap at 60–300s).
# --timeout=0 + ProcessImportBatch.timeout=0 = no Laravel-side timeout.
# flock prevents the next cron firing from starting a second worker on top of
# a still-running one (extra safety; --stop-when-empty already handles this).
*/5 * * * * /usr/bin/flock -n /tmp/charity-queue.lock -c 'cd /home/youruser/charity-app && /usr/local/bin/php artisan queue:work --stop-when-empty --max-time=1800 --timeout=0 >> storage/logs/queue.log 2>&1'

# Watchdog — mark long-stuck import batches as failed.
# --minutes MUST exceed --max-time (1800s = 30 min) plus the worker pickup gap
# (5 min) so it doesn't false-positive a job that's still legitimately running.
*/15 * * * * cd /home/youruser/charity-app && /usr/local/bin/php artisan imports:recover --minutes=45 >> /dev/null 2>&1
```

Adjust `/usr/local/bin/php` if your host uses a different path:

```bash
which php
which flock     # usually /usr/bin/flock on cPanel; drop the flock wrapper if missing
```

### What 5-min cadence means for users

- **Logo uploads, small jobs** — appear in the admin UI as "Queued", processed within ~5 min of submission.
- **CCEW / CRA imports** — submit from the UI, then wait up to 5 min for the worker to pick up the job, then it runs for its full duration uninterrupted (single worker, lock held until done).
- **Failed batches** — appear with status "failed" up to 15 min after the underlying process dies (watchdog cadence). Refresh the admin to see updated status.

If you need faster pickup for interactive jobs, kick the worker manually via SSH right after submitting:

```bash
ssh youruser@yourhost
cd ~/charity-app && php artisan queue:work --once --timeout=0
```

### Picking the right `--max-time`

| Your host's process killer                            | Use `--max-time=`                         |
| ----------------------------------------------------- | ----------------------------------------- |
| Unlimited (premium VPS-style cPanel, your own server) | `3600` (1h) or higher                     |
| ~30 min (most premium shared plans)                   | `1700` (under the limit)                  |
| ~5 min (basic shared plans)                           | `280`                                     |
| ~60s (kiddie shared plans)                            | `50` and use the SSH/`screen` route below |

To find your limit: `time php -r 'sleep(900); echo "OK\n";'` from SSH. If it returns "OK" after 15 min, your shared plan has at least that headroom.

### Fallback for hosts with hard 60s limits

If your plan kills any process at 60s (test above failed) you can't run long imports through cron. Use SSH inside `screen`:

```bash
screen -S import
cd ~/charity-app
pip3 install --user -r requirements.txt   # first run only — pinned loader deps
# Password via env, not --password: argv is visible to other users in `ps`
# for the whole multi-hour import.
CHARITY_DB_PASSWORD='xxx' python3 bulk_load.py --source CCEW \
  --host localhost --user youruser_app --database youruser_charity
# Ctrl+A then D to detach; screen -r import to reattach
```

Or kick off a Filament import batch from the admin UI, then immediately run
`php artisan queue:work --once --timeout=0` in SSH to process that single job uninterrupted.

---

## 12. First login

Browse to `https://yourdomain.tld/admin` → log in with the `ADMIN_EMAIL` / `ADMIN_PASSWORD` from `.env`.

---

## 13. Rescore charities (if scores look wrong)

After data import or any calculator change:

```bash
cd ~/charity-app
php artisan charities:rescore
```

~14 minutes on the full 2.88M rows; less on a filtered dataset. Run in a `screen` or `tmux` session so a dropped SSH connection doesn't kill it:

```bash
screen -S rescore
php artisan charities:rescore
# Ctrl+A then D to detach. Reattach with: screen -r rescore
```

---

## 14. Updating later (after pulling new code)

```bash
cd ~/charity-app
git pull               # or re-upload via SFTP
composer install --no-dev --optimize-autoloader --classmap-authoritative
php artisan migrate --force

php artisan config:clear && php artisan config:cache
php artisan route:cache
php artisan view:cache
php artisan event:cache
php artisan filament:optimize    # re-run this, or new admin pages stay invisible
php artisan cache:clear          # see the note below — do not skip this
# If calculator changed:
php artisan charities:rescore
```

> ⚠️ **`public/build/` is part of the upload.** The server has no Node, so the
> compiled CSS/JS is committed to the repo. `git pull` brings it along; an SFTP
> upload that skips it leaves the old bundle in place and the change simply does
> not appear.

> ⚠️ **`cache:clear` is not optional here.** Site colours, homepage columns
> (including compiled formulas), column lenses and text zones are cached
> *forever* under `CACHE_STORE=database`. They are normally invalidated by model
> events — which a migration's `DB::table()->update()` does not fire. Skipping
> this step leaves the site serving definitions from before the deploy: the most
> visible symptom is a charity list full of `N/A`.

> ⚠️ **`filament:optimize` caches which admin components exist.** Without it the
> panel scans `app/Filament/{Resources,Pages,Widgets}` and the Blade icon sets on
> *every* request — including public homepage requests, because the panel
> provider boots regardless of the route. It measured as a third of the total
> request time on a fast local disk, and directory scanning costs more on shared storage,
> not less. The flip side: add a Filament resource or page and forget to
> re-run it, and the new one simply will not appear. `filament:optimize-clear`
> undoes it.

> `--classmap-authoritative` builds a closed class map, so the autoloader
> resolves every class from an array instead of probing the filesystem. It
> matters most when OPcache is *not* retaining anything between requests, which
> is the usual shape of a slow shared host — see the OPcache section above.
> Drop it if a package generates classes at runtime and starts failing to load;
> nothing in this project does.

> Blade templates are the other easy one to miss. `view:cache` clears before it
> recompiles, so the command above is enough — but deploying a `.blade.php`
> change *without* re-running it keeps serving the previously compiled file, and
> the fix looks like it never landed.

---

### Splitting a slow request into bootstrap and application

`app:profile-homepage` renders in an already-warm process, so it can only
report the application half. The framework bootstrap a real request pays —
composer's autoloader, every service provider — is invisible to it, and on a
slow host that is usually the larger half. To see both, set `SERVER_TIMING=true`
in `.env`, re-run `php artisan config:cache`, load a page, and read the
`Server-Timing` header in the browser's network panel:

```
boot;dur=171.0, app;dur=147.2, total;dur=318.2     # cold worker
boot;dur=3.3,   app;dur=25.5,  total;dur=28.8      # warm worker
```

Those two lines are consecutive requests on the same machine. The difference is
entirely OPcache: **bootstrap is ~50x cheaper once the framework is cached**.

- **`boot` high, `app` low** — the framework is being recompiled or re-read.
  Either OPcache is not retaining it (see below), or the workers are recycled
  often enough that most requests hit a cold one. A site with no traffic yet
  sees this constantly and real users would not.
- **`app` high** — the render itself, which is CPU and query work. Compare
  against `php artisan app:profile-homepage`, which measures exactly that half.

Turn it off again when you are done — `SERVER_TIMING` is unset or `false`, then
`php artisan config:cache`. It tells anyone watching how long your code spends
on what.

---

### Checking OPcache from the web SAPI

`php -i` and `php artisan` report the **CLI**, where `opcache.enable_cli` is 0
by default — they will say "disabled" on a perfectly configured host. To see
what actually serves your requests:

```bash
cat > public/_oc.php <<'EOF'
<?php $s = opcache_get_status(false) ?: [];
echo json_encode([
    'sapi'           => PHP_SAPI,
    'pid'            => getmypid(),
    'enabled'        => $s['opcache_enabled'] ?? false,
    'cached_scripts' => $s['opcache_statistics']['num_cached_scripts'] ?? null,
    'max_keys'       => $s['opcache_statistics']['max_cached_keys'] ?? null,
    'free_mb'        => round(($s['memory_usage']['free_memory'] ?? 0) / 1048576, 1),
    'hit_rate'       => round($s['opcache_statistics']['opcache_hit_rate'] ?? 0, 1),
    'oom_restarts'   => $s['opcache_statistics']['oom_restarts'] ?? null,
    'hash_restarts'  => $s['opcache_statistics']['hash_restarts'] ?? null,
], JSON_PRETTY_PRINT);
EOF
# open https://yourdomain.tld/_oc.php , then:
rm public/_oc.php
```

**Load it twice in a row**, then compare. A healthy result has `hit_rate` above
95, both restart counters at 0, and `cached_scripts` in the thousands — the
whole framework, still there from the previous request.

`cached_scripts: 1` and `hit_rate: 0` mean OPcache is enabled but keeping
nothing: the PHP process does not survive the request, so its shared memory is
built and thrown away every time and the framework is recompiled on every
click. Reload and look at `pid`:

- **`pid` changes and `cached_scripts` stays 1** — PHP is running as CGI/suPHP,
  a fresh process per request. Ask the host to move the domain to the LiteSpeed
  API handler (`lsapi`) or PHP-FPM; on cPanel this is **MultiPHP Manager →
  PHP handler**. This is the single biggest thing you can change.
- **`pid` is stable and `cached_scripts` climbs** — the cache does persist, and
  a cold reading only means the worker had been idle long enough to be reaped.
  Normal on a site with no traffic yet; it warms up under real use.

---

## Known risks on shared hosting

| Risk                              | What to check / do                                                                                                                                                                                                                                                                   |
| --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| **MariaDB JSON columns**          | Laravel writes JSON via the `json` column type; MariaDB 10.2+ supports it as a `LONGTEXT` alias. If your host runs MariaDB 10.1 or older the `categories` / `sch3_band_counts` migrations will fail. Check with `SELECT VERSION();` in phpMyAdmin.                                   |
| **FULLTEXT on charities.name**    | Requires MariaDB 10.0.5+. Should be fine; verify version anyway.                                                                                                                                                                                                                     |
| **Long-running artisan commands** | Shared hosts often kill processes after 60s from cron or 600s from SSH. Use `screen`/`tmux` for the rescore. The migration adding 4 columns on 2.88M rows takes ~13 min — if SSH times out, the ALTER continues on the server side; reconnect and verify with `DESCRIBE charities;`. |
| **Slow disk I/O**                 | Rescore writes ~2.88M UPDATEs in bulk CASE batches; shared disks are slow. Expect 20–40 min instead of the ~14 min you saw locally.                                                                                                                                                  |
| **`exec`/`passthru` disabled**    | Some shared hosts disable PHP shell functions. Laravel queue/scheduler don't need them, but check with `php -i \| grep disable_functions`.                                                                                                                                           |
| **Disk quota**                    | 1.6 GB dump + vendor (~200 MB) + storage logs. Confirm your plan has 3 GB+ of disk free.                                                                                                                                                                                             |
| **Responses not compressed**       | `curl -sI -H 'Accept-Encoding: gzip' https://yourdomain.tld/ \| grep -i content-encoding` must print `gzip`. The app compresses its own responses (`App\Support\ResponseCompressor`, hooked to `RequestHandled` — *not* middleware, because Livewire injects its scripts after the pipeline unwinds), so this should hold on any host — it exists because `public/.htaccess`'s `mod_deflate` block is Apache-only, LiteSpeed ignores it *and* cPanel's *Optimize Website* (which writes the same directives), and CloudLinux's PHP Selector does not expose `zlib.output_compression`. If the server or `zlib.output_compression` does compress, the middleware stands down rather than double-encoding. |
| **Slow sorting / lens switching** | Work through these in order. **1.** `CACHE_STORE` and `SESSION_DRIVER` must be `file`, not `database` — see step 5. **2.** Confirm the query is indexed: `EXPLAIN SELECT id FROM charities WHERE is_featured=1 AND is_latest=1;` should show `key: idx_featured_latest` and `rows` in the tens. If it shows `NULL` or millions of rows, run `ANALYZE TABLE charities;` — a dump restore leaves the index statistics stale, and MariaDB then reports `Cardinality 1` for `is_featured` and scans the table instead. **3.** Check OPcache is on **for the web SAPI** — `php -i` and `php artisan` report the *CLI*, where `opcache.enable_cli` is 0 by default, so they will say "disabled" even on a correctly configured host. Check the real one with a throwaway file: `echo '<?php var_dump(opcache_get_status(false)["opcache_enabled"] ?? false);' > public/_oc.php`, open `https://yourdomain.tld/_oc.php`, then `rm public/_oc.php`. Without OPcache, PHP recompiles the whole framework on every request. **4.** In the browser's Network tab, look at a `livewire/update` request and compare *Waiting (TTFB)* with *Content Download* — that tells you whether the time is the server or the payload. **5.** `php artisan app:profile-homepage` splits the server side into PHP time and database time. **6.** Run `php artisan filament:optimize` and `php artisan event:cache` — without them the admin panel re-discovers its components on every request, public pages included (53 ms -> 34 ms locally). **7.** Set `SERVER_TIMING=true` and read the `Server-Timing` header to see whether the time is bootstrap or render — see the section above. **8.** If OPcache *is* on for the web and TTFB is still high, check it is not thrashing — this project is ~13,000 PHP files and `opcache.max_accelerated_files` defaults to 10,000, so it can run out of slots and recompile on every request. Dump the counters with the throwaway file below; `oom_restarts` or `hash_restarts` above zero, or `cached_scripts` pinned at `max_keys`, means it is. Both that setting and `opcache.memory_consumption` are `PHP_INI_SYSTEM` — they cannot be set from `.user.ini` or the PHP Selector, so this is a support ticket: ask for `opcache.max_accelerated_files=20000` and `opcache.memory_consumption=256`. |

---

## Quick reference — final directory layout

```
/home/youruser/
├── charity-app/                    # The Laravel project
│   ├── app/
│   ├── bootstrap/
│   ├── config/
│   ├── database/
│   ├── public/                     # Web root (point domain here, Option A)
│   ├── resources/
│   ├── routes/
│   ├── storage/
│   ├── vendor/
│   ├── .env
│   └── artisan
└── public_html/                    # Default cPanel docroot (use Option B if you can't move docroot)
```
