Domdhi logoDOMDHI.OS
BACK_TO_COURSE

Save the History

A Collector You Can Trust

What the Code Has to Do

A collector is a small program on a schedule: ask for recent records, save them, stop. AI writes it in minutes. Your job is knowing the four things that make it trustworthy:

  1. It follows every page. (Module 2.)
  2. Running it twice does no harm. The same record is never saved twice.
  3. It overlaps. Each run re-reads the last few days, so a missed night or a late correction fixes itself.
  4. It records every run, even when it found nothing.

The second one comes down to a table that won't accept the same call twice:

create table calls (
  record_id    text primary key,
  call_id      text not null,
  started_at   timestamptz not null,
  direction    text not null,
  department   text,
  answered     boolean not null,
  wait_seconds integer not null,
  raw          jsonb not null
);

And a save that updates the row if it's already there (Postgres):

insert into calls
  (record_id, call_id, started_at, direction,
   department, answered, wait_seconds, raw)
values ($1, $2, $3, $4, $5, $6, $7, $8)
on conflict (record_id) do update set
  call_id      = excluded.call_id,
  started_at   = excluded.started_at,
  direction    = excluded.direction,
  department   = excluded.department,
  answered     = excluded.answered,
  wait_seconds = excluded.wait_seconds,
  raw          = excluded.raw;

You don't need to write that. You need to find two things in it: primary key and on conflict. If the AI's version has no equivalent, every overlap doubles your calls.

Notice there are two IDs. A system may write one record per phone that rang, all sharing a call ID. Key on the call ID and a later record can overwrite the one that answered. So the key is the record's own ID, and the call ID is there to group by later.

And raw is everything the system sent, which may include callers' phone numbers. Guard that table accordingly.

The paging is a loop that stops only when there's no next page:

async function pullCalls({ fetchPage, saveCalls, from, to }) {
  let cursor = null;
  let total = 0;
  do {
    const page = await fetchPage({ from, to, cursor });
    await saveCalls(page.calls);
    total += page.calls.length;
    cursor = page.nextCursor;
  } while (cursor);
  return total;
}

Your vendor's field names will differ, and some count page numbers instead of using a cursor. The shape stays the same.

Test It Like You Don't Believe It

Run it. Count the rows. Run it again over the same finished days. The count must not change. Then delete one day from a test copy, run it over that day, and check the day comes back.

Save each working version in Git before you let the AI change it again. Git 101 covers it.

QUIZ

You run the collector twice over the same finished day. What should happen to the row count?

Sign in to track lesson progress and earn a certificate.SIGN IN TO SAVE PROGRESS