# Synchron Permits → HeavyHaul Agent state updates

HHA implementation is prepared locally. Supabase migration 0055 is applied and its live atomic publication was verified on 2026-10-12. Deploy the updated backend callback and both permanent workers before the production acceptance test. SP's Laravel source and installed version have not been provided; the attached job is an integration example for its developer, not an installed SP change.

## Callback contract

After a new state or a state edit is committed, SP sends:

```http
POST https://<existing-HHA-backend-domain>/api/update-state
Authorization: Bearer <HHA-INTERNAL_API_TOKEN>
Content-Type: application/json
Accept: application/json
```

```json
{"stateid": 1}
```

Use the numeric SP state primary key. Send the same payload for state information, pricing, weight/dimensions, travel rules and provision PDF changes. Dispatch after all related records and uploaded PDF references have been saved. The callback reads current data, so repeated delivery is safe. No full state object or credentials belong in the JSON body. State deletion is outside this callback contract.

The destination is the Flask backend, not the HHA Next.js workspace domain. Confirm the actual backend hostname with its deployment administrator; it is intentionally not invented here.

Successful response example:

```json
{
  "success": true,
  "message": "State synchronized from Synchron",
  "details": {"state_id": 1, "changed": true, "provision_queued": true}
}
```

HTTP 200 with `success: true` confirms Mongo metadata was applied (or already current). PDF extraction and the Supabase mirror complete asynchronously. Optional `details` keys vary; Laravel should check only HTTP 200 and `success === true`.

HTTP 400 means invalid JSON/state ID; 401/403 means missing/incorrect callback authentication; 500 means HHA could not apply the update or is misconfigured. Retrying temporary failures is safe. Alert the operator on exhausted retries; authentication/configuration errors need correction rather than silent dismissal.

## Credentials and configuration

Two server credentials have different purposes:

| Direction | Configured credential |
| --- | --- |
| SP → HHA callback | SP `HHA_CALLBACK_TOKEN` must match backend `INTERNAL_API_TOKEN` |
| HHA → SP read APIs | Backend `SYNCHRON_API_TOKEN`, accepted by SP |

Use the established HHA internal token (at least 32 characters), provisioned through the existing secret channel. Changing it must account for other authenticated HHA endpoints. Do not assume it equals the SP read token. Keep both out of browser code, Git and logs.

SP environment values:

```dotenv
HHA_BACKEND_URL=https://<existing-HHA-backend-domain>
HHA_CALLBACK_TOKEN=<existing-HHA-INTERNAL_API_TOKEN>
```

Add to SP's existing `config/services.php` array:

```php
'heavyhaul' => [
    'base_url' => env('HHA_BACKEND_URL'),
    'callback_token' => env('HHA_CALLBACK_TOKEN'),
],
```

## Laravel save hook

Copy [the example job](laravel/NotifyHeavyHaulState.php) into SP `app/Jobs/NotifyHeavyHaulState.php`. Verify compatibility with its installed Laravel/PHP version. At the common save path, after saving all state fields and PDF references, dispatch:

```php
use App\Jobs\NotifyHeavyHaulState;

NotifyHeavyHaulState::dispatch((int) $state->id)
    ->onQueue('hha-state-sync')
    ->afterCommit();
```

`$state` represents the actual SP state model; use the real variable in its controller/service. Include state creation and every admin tab's save path. Existing bulk/raw SQL updates may bypass model observers, so inspect those paths if implementing an observer. Verify whether an existing SP callback already covers these paths before adding duplicate notifications.

Use an asynchronous database/Redis queue, with a supervised worker consuming `hha-state-sync`. The worker's `retry_after` must exceed the job's 75-second timeout (for example 120 seconds). Use the project's existing queue setup and retain failed jobs for operator retry. Reload config cache and restart queue workers through the existing deployment procedure after updating configuration. HHA's five-minute source poll recovers missed deliveries once its source worker is enabled.

The example uses Laravel's documented [dispatch after commit](https://laravel.com/docs/12.x/queues#jobs-and-database-transactions) and [HTTP client](https://laravel.com/docs/12.x/http-client) features. It sends one request per queue attempt, with bounded timeouts and six queue attempts.

## Existing SP read APIs

HHA fetches one complete state with:

```http
GET https://permits.synchrontms.com/ai/v1/getseperatestate?stateid=1
Authorization: Bearer <SYNCHRON_API_TOKEN>
```

Expected existing structure: `status: true`, `data.getAllState` contains the state object; `data.getPermit` contains its counter. The returned state ID must equal the requested ID. Existing approved fields include identity, contacts/time zone, pricing and its flags, dimensions/limits, travel restrictions, escorts, signs/lights, superloads, miscellaneous information and `provision` PDF URLs. Every relevant saved public admin field must be present in this response; updating the portal alone is insufficient if its API omits that field. Update `updated_at` for state/PDF changes, including replacement of PDF contents at the same URL.

HHA's recovery worker fetches all pages of:

```http
GET https://permits.synchrontms.com/ai/v1/getstates?page=1&perPage=20
Authorization: Bearer <SYNCHRON_API_TOKEN>
```

Expected structure: `status: true`, `data` is an array, ending with an empty array. Keep public state fields consistent with the single-state API. These APIs already exist; no new SP read endpoint is needed. Account credentials and activation scripts are intentionally excluded from the HHA state catalog.

## Joint acceptance test

1. In staging or using an authorized real state edit, update a travel rule and pricing field, then save. Verify both SP APIs return the committed values.
2. Verify the Laravel queued callback returns HTTP 200 and `success: true`.
3. Verify the corresponding Mongo `all_states` record has the new values, then verify Supabase `all_states` and the open HHA viewer. The viewer refreshes every 30 seconds while visible; this is not an instantaneous end-to-end guarantee.
4. Change a provision PDF reference and verify its Mongo job is queued, the current PDF link appears, and extracted evidence becomes ready. Scanned PDFs require the configured OCR service.
5. Verify state creation, repeated callback delivery, and recovery after a temporary HHA outage. Use isolated/staging records for failure tests; no fake production state is needed.

The deployment administrator enables the HHA web update, source/PDF worker and Mongo→Supabase worker according to [README.md](README.md). Laravel's job must not be considered fully connected until this end-to-end test passes.
