# Save scheduler changes to a server

> Persist every scheduler edit from historyChange, batch requests, roll back changes the server rejects, and apply updates from other users without echoing them back.

The scheduler applies a user's change to its own copy of the data and then tells you about it. Saving is up to you. This recipe sends each change to a REST API in small batches, undoes changes the server refuses, and applies changes pushed by other dispatchers without sending them back.

## Choose the events to listen to

| Approach | Listen to | Use it when |
| --- | --- | --- |
| Per action | `eventDrop`, `eventResize`, `eventRemove`, plus `historyChange` for undo and redo | Your API has one endpoint per action, such as "reschedule job". |
| Per change | `historyChange` only | Your API stores events. One listener covers moves, resizes, removals, API edits, undo, redo and recurring series. |

This recipe uses the second approach. The first is shown in [Keeping a server in sync](https://docs.birchui.com/scheduler/resources-and-events.md#keeping-a-server-in-sync).

## Steps

1. Collect `{ id, after }` pairs from `historyChange` into a pending map, so several edits to one job become one request.
2. Flush the map after a short pause.
3. When the server rejects the batch, call `undo()` and tell the user.
4. Apply changes from other users with a flag set, so the listener skips them.

## Save in batches

```ts title="schedule-sync.ts"
import type { SchedulerApi } from '@birchui/scheduler';

type JobPatch = { id: string; job: WorkOrder | null };

export function syncToServer(scheduler: SchedulerApi<WorkOrder, Technician>, notify: (message: string) => void) {
  const pending = new Map<string, WorkOrder | null>();
  let timer: ReturnType<typeof setTimeout> | undefined;
  let applyingRemote = false;

  async function flush() {
    const batch: JobPatch[] = [...pending].map(([id, job]) => ({ id, job }));
    pending.clear();
    if (batch.length === 0) return;
    const response = await fetch('/api/dispatch/jobs', {
      method: 'PATCH',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(batch),
    });
    if (response.ok) return;
    const { message } = (await response.json().catch(() => ({ message: 'The change could not be saved.' }))) as {
      message: string;
    };
    applyingRemote = true;
    scheduler.undo();
    applyingRemote = false;
    notify(message);
  }

  const off = scheduler.on('historyChange', ({ action, changes }) => {
    if (action === 'clear' || applyingRemote) return;
    for (const { id, after } of changes) pending.set(id, after);
    clearTimeout(timer);
    timer = setTimeout(() => void flush(), 400);
  });

  function applyRemote(update: JobPatch) {
    applyingRemote = true;
    try {
      if (!update.job) scheduler.removeEvent(update.id);
      else if (scheduler.getEventById(update.id)) scheduler.updateEvent(update.id, update.job);
      else scheduler.addEvent(update.job);
    } finally {
      applyingRemote = false;
    }
  }

  return { applyRemote, stop: off };
}
```

Wire it to a WebSocket or server-sent events stream:

```ts title="dispatch-board.ts"
const sync = syncToServer(scheduler, showToast);

const stream = new EventSource('/api/dispatch/stream');
stream.addEventListener('job', (message) => sync.applyRemote(JSON.parse(message.data)));
```

## The server side

The server receives the full event for each id, or `null` for a removal. Validate it there too: client-side rules can be bypassed.

```ts title="server/dispatch-jobs.ts"
app.patch('/api/dispatch/jobs', async (request, response) => {
  const batch = request.body as { id: string; job: WorkOrder | null }[];
  for (const { id, job } of batch) {
    if (job && (await jobs.overlapsForTechnician(job.resourceId, job.start, job.end, id))) {
      return response.status(409).json({ message: `${job.title} overlaps another job for this technician.` });
    }
  }
  await db.transaction(async (tx) => {
    for (const { id, job } of batch) {
      if (job) await tx.jobs.upsert({ ...job, id });
      else await tx.jobs.delete(id);
    }
  });
  broadcast(batch);
  response.status(204).end();
});
```

## How it works

- `historyChange` fires once per recorded step with every event it touched. `after` is the event as it is now, or `null` when it was removed, so one upsert-or-delete loop handles all kinds of edits.
- Moving one occurrence of a recurring series yields two changes: the master with a new `exdates` entry, and the detached occurrence. Both are saved by the same loop. See [Schedule recurring maintenance jobs](https://docs.birchui.com/recipes/scheduler-recurring-jobs.md).
- Because `undo()` reverses the last step, the rejected change disappears from the screen and from the history, and `historyChange` fires with `action: 'undo'`. The `applyingRemote` flag stops that undo from being sent back to the server.
- Remote updates applied with `addEvent`, `updateEvent` and `removeEvent` are recorded in the history as well. Skipping them in the listener keeps the server from receiving its own data.

## Pitfalls

- **History must be on.** `historyChange` does not fire with `undoRedo: false`. Keep the default or set a `limit`.
- **Undo after several batches.** `undo()` reverses only the latest step. If the user made another change before the server answered, that change is undone instead. For busy boards, save each change on its own and roll back with `updateEvent(id, before)` from the `historyChange` payload.
- **Remote updates join the user's undo stack.** A dispatcher pressing <kbd>Ctrl</kbd> + <kbd>Z</kbd> can undo a colleague's change. If that matters, call `setEvents()` with fresh data for large remote updates, which starts a new history.
- **Dates on the wire.** `after.start` and `after.end` are `Date` objects after a drag. `JSON.stringify` writes them as UTC ISO strings.

## Related

- [Validate scheduler drag and drop](https://docs.birchui.com/recipes/scheduler-drag-validation.md) to block invalid changes before they happen.
- [Undo and redo in the scheduler](https://docs.birchui.com/recipes/scheduler-undo-redo.md).
- [Updating data](https://docs.birchui.com/scheduler/resources-and-events.md#updating-data).
