Home / API

Keep your system in sync

Most teams keep their own copy of each takeoff: in their estimating database, their front end, or their ERP. This guide shows the pattern that stays right as jobs are re-read and repriced: react to the webhook, fetch, and replace by version.

The pattern

  1. A webhook arrives

    takeoff.completed with the job's id. Answer 2xx at once, and queue the work.

  2. Fetch the takeoff

    GET /v1/jobs/{id}/takeoff, with your key, from your worker.

  3. Replace by version

    If takeoff_version is new to you, replace the job's items in one transaction. If you already have it, do nothing.

Item ids belong to one takeoff version, so a new version replaces the old one rather than merging with it. Keying on the version also makes the sync safe to run twice: a retried webhook, or a webhook and a poll that both fire, change nothing the second time.

The sync, in full

This keeps each job's takeoff in a SQLite database; swap in your own. Call it from your webhook worker, from a poll, or by hand. It is safe to call any number of times.

import json
import os
import sqlite3

import requests

BASE = "https://insulengine.com"
auth = {"Authorization": f"Bearer {os.environ['INSULENGINE_API_KEY']}"}
db = sqlite3.connect("takeoffs.db")
db.executescript("""
create table if not exists jobs (job_id text primary key, takeoff_version integer);
create table if not exists items (job_id text, takeoff_version integer, item_id text, sheet text,
    page integer, service text, size text, quantity real, unit text, state text, points text);
""")


def sync_job(job_id):
    """Copy a job's takeoff into the database if it is a version we don't have. True when it changed."""
    response = requests.get(f"{BASE}/v1/jobs/{job_id}/takeoff", headers=auth)
    if response.status_code == 409:                   # still analyzing: the webhook will come
        return False
    response.raise_for_status()
    takeoff = response.json()
    version = takeoff["takeoff_version"]
    have = db.execute("select takeoff_version from jobs where job_id = ?", (job_id,)).fetchone()
    if have and have[0] == version:
        return False
    rows = [(page["sheet_number"], page["page"], item) for page in takeoff["pages"] for item in page["items"]]
    rows += [(None, None, item) for item in takeoff["allowances"]]
    with db:                                          # one transaction: the old version or the new, never half
        db.execute("delete from items where job_id = ?", (job_id,))
        db.executemany("insert into items values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", [
            (job_id, version, item["id"], sheet, page, item["service"], item["size"], item["quantity"],
             item["unit"], item["state"], json.dumps(item.get("points"))) for sheet, page, item in rows])
        db.execute("insert or replace into jobs values (?, ?)", (job_id, version))
    return True

From the webhook

Verify the signature, answer at once, and run the sync after answering. InsulEngine waits 10 seconds for an answer, and reading a large takeoff can take longer than that. The Webhooks page has the verifier and a complete receiver in Python and Node.js.

if event["type"] in ("takeoff.completed", "estimate.priced"):
    queue.enqueue(sync_job, event["data"]["job_id"])     # your job queue: Celery, RQ, a thread…
return "", 204

Polling, as a fallback

A webhook can be missed, for example while your server is down for longer than the retries last. A sweep every hour or so catches up, because sync_job does nothing for a version you already have:

for job in requests.get(f"{BASE}/v1/jobs", headers=auth, params={"limit": 200}).json()["jobs"]:
    sync_job(job["id"])

To sync only what changed, ask each job's status first (GET /v1/jobs/{id}) and sync the ones whose takeoff_version differs from yours.

Sending jobs safely

When your system creates jobs, send a request_id with each upload: your own id for the bid works. If the upload times out and you send it again with the same request_id, the job is not started twice. See Jobs.

Your own review

Many teams have an estimator check every takeoff, and some have a second estimator check it again. InsulEngine's own checks run before a takeoff is shown (see How it works). Your team's checks belong in your system, and fit the pattern above: