# Connect your other systems

This page shows how the pieces of the API fit together when TruTec runs next to other software: an estimating or field system that holds budgets and crew time, an accounting or ERP system that holds job cost and receivables, and a CRM that holds companies, contacts and deals. Each recipe links to the full reference for the endpoints it uses.

Every example uses the base URL `https://trutec.ai/api` and an API key in `X-API-Key` ([Authentication](authentication.md)). Build against a [sandbox](sandbox.md) first: it runs the same API on sample data, and nothing you do there can reach your real customers.

!!! note
    When an owner creates a key in **Settings › API keys**, they pick **Read only**, **Read and write** or **Read, write and delete**. Give each system its own key, and use **Read only** for any system that only pulls data. See [Permissions](authentication.md#permissions).

## Match records with external_ref

TruTec ids are integers that never change. Store them in your systems, and store your ids in TruTec: every record you sync has an `external_ref` field for your other system's id.

| Record | Create-or-match call | Look up with `?external_ref=` |
|---|---|---|
| Customer | `POST /v1/client-accounts` | `GET /v1/client-accounts` |
| Site | `POST /v1/locations` | `GET /v1/locations` |
| Job | `POST /v1/jobs` | `GET /v1/jobs` |
| Contact | `POST /v1/contacts` | `GET /v1/contacts` |
| Estimate | `POST /v1/estimates` | `GET /v1/estimates` |
| Invoice | `POST /v1/invoices` | `GET /v1/invoices`, `GET /v1/jobs/{id}/invoices` |
| Job cost | `POST /v1/jobs/{id}/costs` | `GET /v1/jobs/{id}/costs` |
| Time entry | `POST /v1/time-entries` | `GET /v1/time-entries` |
| Crew | `POST /v1/crews` | `GET /v1/crews` |
| Crew member | `POST /v1/crews/{id}/members` | `GET /v1/people` |
| Catalog service or cost item | `POST /v1/catalog/services`, `POST /v1/catalog/{item_type}` | `GET /v1/catalog/services`, `GET /v1/catalog/{item_type}` |

The rules are the same everywhere:

- `external_ref` is a string, up to 255 characters (customers and sites: 120). It is read back on every record, `null` when unset.
- It is **unique per workspace for each kind of record**. A crew member's ref is unique within its crew, so one employee id can sit on each of a person's crews. Catalog refs are unique within their item type.
- **A create call with a ref TruTec already holds is an upsert.** The matching record is updated with that record's `PATCH` rules, and you get `200` with `"created": false` instead of a twin. A new record returns `201`. Customers and sites also match by name or address when no ref matches ([Customers & sites](customers-and-sites.md)).
- `PATCH` sets, changes or clears it (`null` or `""`). A ref another record of the same kind already holds is a `409` naming the holder: `"code": "external_ref_conflict"` with `existing_id` (jobs: `existing_job_id`); customers and sites answer with `"field": "external_ref"`, `conflicting_id` and `conflicting_archived` instead.
- The `?external_ref=` filter is an exact match and returns 0 or 1 rows in `data`.
- A ref held by a cost or invoice on a different job is a `409`: costs and invoices never move between jobs. A time entry matched by ref can't change its person or work order (`409`).

Look up a job by your accounting system's job id:

```bash
curl "https://trutec.ai/api/v1/jobs?external_ref=erp-26-118" \
  -H "X-API-Key: $TRUTEC_API_KEY"
```

```json
{
  "data": [
    {
      "id": 70412,
      "name": "Northgate Plaza Mill and Pave",
      "external_ref": "erp-26-118",
      "job_number": 1015,
      "display_job_number": "J-1015",
      "accounting_job_number": "26-118",
      "status": "won",
      "...": "..."
    }
  ],
  "pagination": { "total": 1, "limit": 50, "offset": 0 }
}
```

!!! tip
    Pick one system as the owner of each ref. A common split: the CRM's ids on customers, contacts and jobs; the accounting system's ids on invoices; the field system's ids on time entries, job costs, crews and crew members. Write your ref the first time you create or see a record, and from then on every call is safe to repeat.

## Estimating & field systems (budgets, cost codes, time and quantities)

### Won estimate to a job budget

When a bid is won, your field or job-cost system needs the budget: one row per cost code with quantity, unit, cost by type and hours. Every estimate line item carries those.

1. Find out the bid was won. Subscribe to `estimate_approved` (an estimate is awarded) or `job_won` ([Keeping in sync](#keeping-in-sync)). The `estimate_approved` delivery has `data.estimate_id` and the whole estimate under `estimate`.
2. Or list won estimates for the job: `GET /v1/estimates?job_id=70412&status=won`.
3. Read the estimate with its line items: `GET /v1/estimates/{id}`.

```bash
curl "https://trutec.ai/api/v1/estimates/9840" \
  -H "X-API-Key: $TRUTEC_API_KEY"
```

Each area's `services` are the line items. One line, trimmed:

```json
{
  "id": 9840,
  "external_ref": "erp-est-5521",
  "status": "won",
  "job_id": 70412,
  "totals": { "price": 48500.0, "cost": 34852.1, "margin": 13647.9, "margin_pct": 0.2814 },
  "areas": [
    {
      "id": 22018,
      "name": "Front lot",
      "services": [
        {
          "id": 55120,
          "name": "2\" mill and overlay",
          "cost_code": "02-100",
          "quantity": 48250,
          "unit": "SF",
          "unit_cost": 0.6012,
          "cost": 29007.9,
          "price": 40125.0,
          "labor_hours": 96.0,
          "crew_hours": 16.0,
          "man_days": 12.0,
          "cost_by_type": {
            "labor": 6240.0,
            "equipment": 7120.5,
            "materials": 12880.0,
            "trucking": 2767.4,
            "subcontractors": 0.0,
            "overhead": 0.0,
            "misc": 0.0
          },
          "is_optional": false,
          "is_bundle_master": false,
          "bundle_parent_service_id": null
        }
      ]
    }
  ]
}
```

How the fields map to a budget:

| TruTec line field | Budget field |
|---|---|
| `cost_code` | Cost code. `null` when the estimator didn't set one; map by `name` or the catalog item (`assembly_id`) instead. |
| `quantity`, `unit` | Budget quantity and unit of measure. |
| `cost_by_type` | Cost by type: `labor`, `equipment`, `materials`, `trucking`, `subcontractors`, `overhead` and `misc` (dump fees and anything else). The buckets add up to the line's `cost`. |
| `labor_hours` | Man-hours (every crew member's hours added up). |
| `crew_hours` | How long the crew works the line (duration, not man-hours). |
| `man_days` | Man-days. |
| `id` | Keep it: it is the `estimate_service_id` that visits, time entries and job costs carry, so actuals line up with the budget. |

- `labor_hours`, `crew_hours`, `man_days` and `cost_by_type` are `null` until the estimate is priced.
- **Bundles:** a bundle line (`is_bundle_master: true`) already includes its sub-lines, and its `cost_by_type` does too. Send either the bundle line or its sub-lines (`bundle_child_service_ids`), not both.
- **Optional lines** (`is_optional: true`) are not in `totals.price`. Leave them out unless the customer took them.
- For resource-level detail (each crew, piece of equipment and material with its own quantity and unit cost), read `GET /v1/estimates/{id}/line-items/{line_item_id}` and use its `cost_lines` ([The cost line object](estimates-and-proposals.md#the-cost-line-object)).
- Store your system's id on the estimate: `PATCH /v1/estimates/{id}` with `{"external_ref": "erp-est-5521"}`.

### Cost codes

`GET /v1/cost-codes` lists the workspace's job cost codes. These are the `code` values on job costs and time entries. Use it to build or check your mapping table to your other systems' cost codes.

```bash
curl "https://trutec.ai/api/v1/cost-codes?active=true" \
  -H "X-API-Key: $TRUTEC_API_KEY"
```

```json
{
  "data": [
    {
      "id": 312,
      "firm_id": 958,
      "code": "02-100",
      "name": "Asphalt paving labor",
      "category": "labor",
      "description": "Crew time on paving",
      "is_active": true,
      "created_at": "2026-09-02T15:10:00Z",
      "updated_at": "2026-10-21T18:44:05Z"
    }
  ],
  "pagination": { "total": 1, "limit": 50, "offset": 0 }
}
```

Filters: `active`, `category`, `updated_after`, `limit` (max 200), `offset`. Listing never adds or changes codes. See [Cost codes](job-costing.md#list-cost-codes).

### Field time back into TruTec

Send crew time and field costs to TruTec so the job's budget-vs-actual, labor cost and month-end report stay current.

!!! note
    **Time entries need Operations.** Scheduling, crews and timesheets must be turned on for the workspace, or `POST /v1/time-entries` returns `403` `Operations not enabled`. **Cost writes need Job costing** turned on, or they return `403` with the reason. Both act as the person who created the API key: adding time needs the **Edit timesheets** permission in TruTec, and cost writes need someone who can see pricing.

Each timecard line becomes one time entry: one person, one visit (work order), one shift.

```bash
curl -X POST "https://trutec.ai/api/v1/time-entries" \
  -H "X-API-Key: $TRUTEC_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "user_id": 344,
    "work_order_id": 4120,
    "date": "2026-11-03",
    "clock_in": "07:00",
    "clock_out": "15:30",
    "category": "work",
    "reason": "Field system timecard",
    "external_ref": "field-tc-88213-1"
  }'
```

- `date`, `clock_in` and `clock_out` are local (`HH:MM`) in the workspace's time zone. `reason` is required and kept in the audit trail.
- `user_id` must be a TruTec login in the workspace, and `work_order_id` a visit on the job. Find visits with `GET /v1/work-orders?job_id=...`. Find people with `GET /v1/people`, which also returns the employee ids you stored as crew member `external_ref`.
- **Upsert:** send the same `external_ref` again and the entry is corrected, not duplicated (`200`, `"created": false`). Times that didn't change keep the approval.
- **Cost code:** a time entry's `cost_code`, `estimate_service_id` and `estimate_line_item_id` come from its visit's estimate line. You don't send them (unknown fields are a `400`).
- New entries land unapproved. Approve them in TruTec or with `POST /v1/time-entries/{id}/approve`.
- An employee with no TruTec login can't have a time entry. Send that labor as a `labor` cost instead (below).

Read time back with `GET /v1/time-entries?updated_after=...` (it also filters by `external_ref`). See [Timesheets](timesheets.md).

To hear about time as it happens, subscribe to `time_entry_created` and `time_entry_updated`. They fire for crew clock-ins and clock-outs, office corrections and API writes, and when an entry is approved, unapproved, voided or restored (`data.approved`, `data.voided`, `data.changed`). The payload carries the time entry with `external_ref` and `cost_code` ([Record events](webhooks-and-events.md#record-events)).

### Field costs back into TruTec

Equipment hours, materials, trucking tickets and subcontractor bills become job costs:

```bash
curl -X POST "https://trutec.ai/api/v1/jobs/70412/costs" \
  -H "X-API-Key: $TRUTEC_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "category": "equipment",
    "cost_code": "02-100",
    "description": "Milling machine, 8 hr",
    "qty": 8,
    "unit": "HR",
    "unit_cost": 310.0,
    "incurred_on": "2026-11-03",
    "work_order_id": 4120,
    "estimate_service_id": 55120,
    "external_ref": "field-eq-88213-4"
  }'
```

```json
{
  "data": {
    "id": 88311,
    "job_id": 70412,
    "work_order_id": 4120,
    "estimate_service_id": 55120,
    "category": "equipment",
    "cost_code": "02-100",
    "source": "manual",
    "description": "Milling machine, 8 hr",
    "qty": 8.0,
    "unit": "HR",
    "unit_cost": 310.0,
    "total_cost": 2480.0,
    "external_ref": "field-eq-88213-4",
    "...": "..."
  },
  "created": true
}
```

- `category` is `labor`, `material`, `equipment`, `trucking`, `subcontractor`, `overhead` or `other`. `cost_code` defaults to the workspace's code for the category.
- `estimate_service_id` (the line item `id` from the estimate) ties the cost to its budget line. `work_order_id` ties it to one visit. Either one from another job is a `400`.
- **Upsert:** the same `external_ref` on the same job updates the cost (`200`, `"created": false`). `unit` and `incurred_on` stay as first recorded.
- New costs are `pending` office review. Labor from TruTec's own crew clock (`source: "clock"`) is rebuilt from time entries; change the time entry, not the cost.
- Events: `job_cost_created` and `job_cost_updated` carry the cost with `external_ref`, `cost_code` and `review_status` (clock labor included), so you can post approved costs to your accounting system as they land.

See [Record costs](job-costing.md#record-costs).

## Accounting / ERP (jobs, customers, invoices, payments, job cost)

### Job setup

A won job carries what an accounting system needs to open the job:

| Need | Where it is |
|---|---|
| Job number | `display_job_number` (as TruTec prints it, for example `J-1015`) and `job_number` (digits only). |
| Accounting job number | `accounting_job_number`: the job's number in your accounting system. Set it with `PATCH /v1/jobs/{id}/details` (up to 80 characters) ([Job details](job-details-and-links.md)). |
| Your id | `external_ref`. |
| Customer | `client_account_id` and `client_account_external_ref`. Read the customer with `GET /v1/client-accounts/{id}`. |
| Site address | `address` on the job; the site is `location_id` and `location_external_ref` (`GET /v1/locations/{id}` for coordinates). |
| Dates | `start_date`, `end_date` (`YYYY-MM-DD`). |
| Contract value | The won estimate's `totals.price`. `estimated_value` on the job is the sales value. |
| Won reason | `close_reason`, `close_notes`. |

Write your accounting system's job number back so both systems print the same number:

```bash
curl -X PATCH "https://trutec.ai/api/v1/jobs/70412/details" \
  -H "X-API-Key: $TRUTEC_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"accounting_job_number": "26-118"}'
```

The job's scheduled visits (work orders, with crew and date) are in `GET /v1/work-orders?job_id=70412` ([Schedule & crews](schedule-and-crews.md)). A visit built from a won estimate carries the line's `estimate_service_id`.

### Job cost

Read everything recorded against a job with `GET /v1/jobs/{id}/costs` (cost entries and a summary), `GET /v1/jobs/{id}/labor` (crew time with `cost_code` and `labor_cost_at_wage_rate`) and `GET /v1/jobs/{id}/invoices`. Each cost entry carries `cost_code`, `category`, `estimate_service_id` and `external_ref`. See [Job costing](job-costing.md).

### Invoices and payments

TruTec drafts and sends customer invoices. Read them into your receivables and match payments.

```bash
curl "https://trutec.ai/api/v1/invoices?updated_after=2026-11-04T06:00:00Z" \
  -H "X-API-Key: $TRUTEC_API_KEY"
```

- Each invoice has `job_id`, `estimate_id`, `doc_number`, `status`, `line_items` (`{description, amount}`), `subtotal`, `discount`, `tax`, `amount`, `due_date`, `payment_terms`, `issued_at`, `paid_at` and `external_ref`. See [The invoice object](invoices-and-payments.md#the-invoice-object).
- Store your receivables invoice id on the TruTec invoice: `PATCH /v1/invoices/{id}` with only `{"external_ref": "acct-ar-10442"}`. A body with only `external_ref` works on any invoice and changes nothing else.
- Payments: `GET /v1/payments?paid_after=...` returns each payment recorded on an invoice (amount, `method`, check number in `reference`, `external_ref`) and each invoice paid in full with none recorded. Invoices carry `amount_paid`, `balance_due` and `payment_status` (`unpaid`, `partial`, `paid`).
- When your accounting system records a payment, part or whole, record it in TruTec: `POST /v1/invoices/{id}/payments` with `amount`, `paid_at`, `method`, `reference` and your `external_ref`. The one that pays the rest marks the invoice paid. See [Record a payment](invoices-and-payments.md#record-a-payment).
- When your accounting system records a check, mark the TruTec invoice paid: `POST /v1/invoices/{id}/mark-paid` (manual `check` invoices only; online invoices follow the payment processor).
- Events: `invoice_created` and `payment_received`. Each carries the whole invoice as `GET /v1/invoices/{id}` returns it (`invoice`: `external_ref`, `job_id`, amounts, `status`, `paid_at`, line items), next to `data` (`invoice_id`, `doc_number`, `amount_cents`).

- Payables: costs carry the vendor, the vendor's bill number and dates, and `ap_status`. Pull unpaid bills with `GET /v1/costs?ap_status=unpaid&updated_after=...`, and match vendors on their `external_ref`. See [Vendor bills and payables](job-costing.md#vendor-bills-and-payables).
- Retainage: read it from the job's pay applications (AIA G702): `GET /v1/jobs/{id}/retainage` for what's held now, `GET /v1/pay-applications?updated_after=...` for every application's figures. See [Retainage](invoices-and-payments.md#retainage).

## CRM (companies, contacts, deals)

| CRM object | TruTec | Endpoints |
|---|---|---|
| Company / account | Customer (client account) | `GET`/`POST /v1/client-accounts`, `PATCH /v1/client-accounts/{id}` |
| Contact | Contact | `GET`/`POST /v1/contacts`, `PATCH /v1/contacts/{id}` |
| Deal | Job | `GET`/`POST /v1/jobs`, `PATCH /v1/jobs/{id}` |
| Deal stage | Pipeline stage | `GET /v1/job-stages`, `POST /v1/jobs/{id}/move` |
| Quote | Estimate and proposal | `GET /v1/estimates`, `GET /v1/proposals` |

- **Deal fields:** a job has `status` (stage key), `status_label`, `estimated_value`, `probability`, `start_date`, `assigned_to_user_id`, `client_account_id` and `client_account_external_ref`.
- **Stages:** `GET /v1/job-stages` lists the workspace's stages with `stage_type` (`open`, `won`, `lost` or `excluded`). Map by `stage_type`, since workspaces rename stages.
- **Won and lost reasons:** read `close_reason` and `close_notes` on the job. To mark a deal lost from the CRM, `POST /v1/jobs/{id}/move` with `{"status": "lost", "reason": "Price", "competitor": "Acme Sealcoat"}`; lost stages list the `outcome_questions` they require.
- **Link a deal to its company by your id:** send `client_account_external_ref` instead of `client_account_id` on `POST` or `PATCH /v1/jobs`.
- **Quote activity:** webhooks `proposal_sent`, `proposal_viewed`, `proposal_accepted` and `proposal_declined`; business events `estimate_issued`, `estimate_revised`, `estimate_approved` and `estimate_declined`. Use the estimate's `revision_count` for a "times sent" count.
- **Order:** create the customer, then the site, then the job, then contacts. See [Customers & sites](customers-and-sites.md), [Contacts](contacts.md) and [Jobs](jobs.md#syncing-with-your-own-system).
- **Changes made in TruTec:** `customer_created` / `customer_updated`, `contact_created` / `contact_updated` and `site_created` / `site_updated` send the record (with `external_ref`) whenever someone adds or edits one, in the app or through the API. `data.changed` names the fields that changed.

## Keeping in sync

Use webhooks for speed and a pull for completeness.

**Webhooks.** `POST /v1/webhooks` with a `target_url`, an `event_type` and a `secret`. `event_type: "all"` sends every business event (`job_won`, `job_scheduled`, `work_order_completed`, `estimate_approved`, `change_order_approved`, `invoice_created`, `payment_received`, ...) and the record events for customers, contacts, sites, time entries and job costs (`customer_updated`, `time_entry_updated`, `job_cost_created`, ...). `"*"` sends the job and proposal events (`job_created`, `job_updated`, `job_status_changed`, `proposal_*`). They are separate, so create two subscriptions to get both. An `all` subscription made before November 5, 2026 gets the record events once you `PATCH` it with `{"include_record_events": true}`.

```bash
curl -X POST "https://trutec.ai/api/v1/webhooks" \
  -H "X-API-Key: $TRUTEC_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"event_type": "all", "target_url": "https://sync.example.com/trutec", "secret": "whsec_7f3a9c..."}'
```

- **Signing:** `X-TruTec-Signature: sha256=<hex>`, HMAC-SHA256 with your `secret` over `{X-TruTec-Timestamp}.{raw body}`. Verify against the raw bytes ([Verifying signatures](webhooks-and-events.md#verifying-signatures)).
- **Reply fast:** any `2xx` within 8 seconds, then do the work on a queue.
- **Retries:** 7 attempts with backoff (1 min, 5 min, 30 min, 2 h, 6 h, 24 h), about 33 hours in all.
- **Dedupe on `event_id`.** Delivery is at least once and can be out of order. `event_id` is the same in every retry, every replay and the feed; `X-TruTec-Delivery` changes on each attempt.
- **Replay:** `POST /v1/webhooks/replay` with `subscription_id` and `since` re-sends a time window ([Replay and redelivery](webhooks-and-events.md#replay-and-redelivery)).

**Event feed.** `GET /v1/events?after_id=<cursor>` returns business events oldest first. Save `next_after_id` and page while `has_more` is `true`. It does not hold `job_updated` or `proposal_*`.

**Nightly bulk export.** `GET /v1/exports/{dataset}.jsonl`, or `.csv` for CSV (add `.gz` to either for gzip), with `?updated_after=<watermark>` streams JSON Lines or CSV for `customers`, `properties`, `jobs`, `estimates`, `estimate_lines`, `change_orders`, `invoices`, `job_costs`, `work_orders`, `time_entries`, `allocations`, `saved_routes` and `events`. Save the `X-TruTec-Export-Watermark` response header and send it as `updated_after` next time. A full export now and then catches deletes. The CSV has the same records as the JSON Lines: objects with fixed keys become `parent.child` columns (`cost_by_type.labor`, `totals.price`) and arrays are JSON text in one cell, so a system that imports files instead of calling an API can load it as is ([CSV](bulk-export.md#csv)). See [Bulk data export](bulk-export.md).

### Recommended architecture

- **Map once, by ref.** Write your id into `external_ref` on every record you create or first see, and look records up with `?external_ref=` before creating. Every write is then an upsert you can retry.
- **Webhooks trigger, reads confirm.** On a webhook, store `event_id`, reply `2xx`, then read the current record by id (`GET /v1/estimates/{id}`, `GET /v1/jobs/{id}`) before writing to your other systems.
- **Follow the feed as the source of truth.** Every few minutes, page `GET /v1/events` from your saved cursor so nothing is lost while your receiver was down.
- **Reconcile nightly.** Pull each bulk export dataset with its watermark and upsert by `id`; weekly, run a full export to catch deletes.
- **One owner per field.** Decide which system owns each field (budgets and field time in the field system, receivables in accounting, deals in the CRM, estimates and the schedule in TruTec) and write in that direction only.

## Build against a sandbox first

Ask [support@trutec.ai](mailto:support@trutec.ai) for a sandbox workspace. It runs the same API with sample customers, sites, jobs, estimates, job costs and invoices, and its keys can't see your real records. Tell us you are building a field or accounting sync and we'll also load crews, scheduled visits and time entries (Operations turned on) so the time and cost recipes work. Point webhooks at a test endpoint, build every recipe above, then swap in a production key. IDs differ between sandbox and production, so match on `external_ref`, never on TruTec ids. See [Sandbox & testing](sandbox.md).
