# Instant sheet sync — Google Apps Script → portal webhook

The portal polls every connected sheet once a minute (`sheets:sync` on the
scheduler). Drive's modified-time check makes an unchanged sheet a no-op, so the
poll is cheap — but it still means up to sixty seconds between an edit and the wall.

For instant updates the sheet itself tells the portal when it changes. A tiny Apps
Script trigger on the spreadsheet calls this endpoint on every change:

```
POST https://<your-api-host>/api/sheets/webhook/<connection id>?token=<SHEET_WEBHOOK_TOKEN>
```

The endpoint answers `202 {"queued":true}` immediately and runs
`php artisan sheets:sync <id> --force` in the background. Syncs are serialised per
connection: a burst of edits becomes one sync plus one follow-up pass, never a pile.

## Requirements

- The API must be reachable from Google: a public HTTPS hostname. `localhost`
  cannot receive the call — for local work use a tunnel (e.g. `ngrok http 8120`) and
  put the tunnel hostname in the script.
- `SHEET_WEBHOOK_TOKEN` set in `server/.env` (a long random string). The same value
  goes in the script below.
- The connection id from Portal → Data Connections (East/South today: `2`).

## The script (Extensions → Apps Script, in the connected spreadsheet)

```javascript
// Change these two lines.
const WEBHOOK = "https://api-lagos-eccc-election-manager.bravoelections.com/api/sheets/webhook/2";
const TOKEN = "PASTE-SHEET_WEBHOOK_TOKEN-HERE";

// Called by an INSTALLABLE trigger (simple onEdit cannot make network calls).
function bravoSheetChanged(e) {
  try {
    UrlFetchApp.fetch(WEBHOOK + "?token=" + encodeURIComponent(TOKEN), {
      method: "post",
      muteHttpExceptions: true,
      // a few edits in quick succession are fine: the portal serialises the syncs
    });
  } catch (err) {
    console.error("bravo webhook failed: " + err);
  }
}
```

Install the trigger: Apps Script editor → **Triggers** (clock icon) → **Add trigger**
→ function `bravoSheetChanged` → event source **From spreadsheet** → event type
**On change** (fires on edits, pastes, row deletes and imports). Add a second trigger
with **On edit** if you also want single-cell typing to fire it. Authorise the script
when asked (it needs the "connect to an external service" scope).

## What the portal does on each call

1. Checks the token (401 if wrong) and that the connection is active (410 if not).
2. Starts the sync in the background and returns 202.
3. The sync pulls the tab, re-imports results, turnout and sheet incidents, and
   broadcasts `sheet-synced` on Pusher — every open war room, incident map and
   insights wall refetches without a refresh, and the bell shows the update.
4. If the tab has been **emptied** (headers only), the sync clears this state's
   sheet-sourced results, turnout and incidents, hides the stories built on them,
   and broadcasts `cleared: true`. Hand-filed field reports and the polling-unit
   register are never removed. A **failed** read (deleted spreadsheet, missing tab,
   network error) does not clear anything — the connection shows the error and the
   last known data stays.

## Checking it works

```
curl -X POST "https://<host>/api/sheets/webhook/2?token=<token>"
# → {"queued":true,"connection":2,"at":"…"}
```

Then watch Portal → Data Connections: `last synced` moves within a few seconds,
and any open war room updates on its own.
