# Daily history sync

A nightly job that copies every finished tracking item of an organization into your own storage - for
reporting, billing reconciliation or archiving. History keeps finished tracking items for a limited
time only, so sync what you need regularly.

## How the window works

`GET /get-all-tracking-items?type=history` returns tracking items with status `done` (or `doneEld` for
[ELD and Hybrid](/eld-tracking)) whose **expiration date** is inside `fromDate < expDate <= toDate`,
oldest first, in pages of up to 500.
Pending installation tracking items the driver never accepted are billed but never appear in history.

A tracking stopped early with `stop-tracking` keeps its original `expDate`, which can be days in the
future. To catch those too, do not set `toDate` - and upsert by `trackingId`, so a tracking seen twice
is simply overwritten.

## The job

1. Read the watermark the previous run saved (start with 7 days ago).
2. Request pages with `fromDate` = watermark and no `toDate`, following `pagination.nextCursor` until
   it is `null`.
3. Upsert every item by `trackingId`.
4. Save the new watermark as the start of this run minus a safety overlap (for example 3 days), so
   tracking items that finished late are picked up again.

```js
const BASE = 'https://api.load-market.com/v1';
const HEADERS = {
  'x-api-key': process.env.LOADMARKET_API_KEY,
  'x-api-client-key': process.env.LOADMARKET_CLIENT_KEY,
};
const OVERLAP_MS = 3 * 24 * 60 * 60 * 1000;

export async function syncHistory(store) {
  const runStartedAt = Date.now();
  const fromDate = (await store.getWatermark()) ?? runStartedAt - 7 * 24 * 60 * 60 * 1000;

  let cursor = null;
  let total = 0;

  do {
    const params = new URLSearchParams({ type: 'history', fromDate: String(fromDate), limit: '500' });
    if (cursor) params.set('cursor', cursor);

    const res = await fetch(`${BASE}/get-all-tracking-items?${params}`, { headers: HEADERS });
    if (!res.ok) {
      const error = await res.json().catch(() => ({}));
      throw new Error(`History sync failed: ${res.status} ${error.code} (requestId ${error.requestId})`);
    }

    const page = await res.json();
    for (const item of page.data) {
      await store.upsertTracking(item.trackingId, item);
    }

    total += page.data.length;
    cursor = page.pagination.nextCursor;
  } while (cursor);

  await store.setWatermark(runStartedAt - OVERLAP_MS);

  return total;
}
```

## Getting more detail

List items are slim, and history items have `driverCoords: null` (a position is published only while
a tracking is live). For each new tracking you need in full (email settings, driver files), call
`GET /get-tracking` - pace these calls (for example 5 per second) rather than firing them all at once.
A location sample about every 15 minutes while the driver moved is available with `GET /get-reports`.

## Notes

- Keep the same `fromDate` / `toDate` for every page of one run. The cursor is only valid for the window
  it was issued for.
- Retry a failed page with the same cursor - it is safe.
- Test keys return a single page of at most `limit` items (default 100), and `nextCursor` is always `null`.
- History keeps finished tracking items for a limited time only - run the sync regularly and do not
  pause it for long.
