Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(everhour): sync invoices, expenses, timecards and assignments (#107278)

Tom Owers735f1a95581b
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index 062943c1978c..e1aac09af266 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -2938,14 +2938,14 @@ Note: The Redoc page embeds the full OpenAPI document. Its entire GET surface is
## Everhour — gaps
-Today (5): `clients`, `projects`, `tasks`, `time_records`, `users`
+Today (9): `assignments`, `clients`, `expenses`, `invoices`, `projects`, `tasks`, `time_records`, `timecards`, `users`
Diffed against: <https://everhour.docs.apiary.io/api-description-document>
-- [ ] `GET /invoices, GET /invoices/{id}` — client billing documents and line items; the revenue side of tracked time (high)
-- [ ] `GET /expenses` — project cost records that pair with time_records for margin analysis (high)
-- [ ] `GET /timecards, GET /users/{user_id}/timecards` — clock-in/clock-out attendance records, distinct from time_records (high)
-- [ ] `GET /resource-planner/assignments` — scheduled/planned work per user, project and task - planned vs actual (high)
+- [x] `GET /invoices, GET /invoices/{id}` — client billing documents and line items; the revenue side of tracked time (high)
+- [x] `GET /expenses` — project cost records that pair with time_records for margin analysis (high)
+- [x] `GET /timecards, GET /users/{user_id}/timecards` — clock-in/clock-out attendance records, distinct from time_records (high)
+- [x] `GET /resource-planner/assignments` — scheduled/planned work per user, project and task - planned vs actual (high)
- [ ] `GET /expenses/categories` — lookup table resolving the category id carried on every expense (high)
- [ ] `GET /timesheets, GET /users/{user_id}/timesheets` — weekly timesheet approval state and transitions (medium)
- [ ] `GET /resource-planner/time-off-types` — lookup resolving time-off type ids on assignments/allocations (medium)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/everhour/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/everhour/canonical_descriptions.py
index 5452be8e5056..6977aead83b9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/everhour/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/everhour/canonical_descriptions.py
@@ -81,4 +81,73 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"createdAt": "When the time record was created.",
},
},
+ "invoices": {
+ "description": "A client invoice, including its line items, totals and billing period.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "id": "Unique identifier for the invoice.",
+ "client": "The client the invoice was raised for (nested client object).",
+ "createdBy": "The user who created the invoice (nested user object).",
+ "createdAt": "When the invoice was created.",
+ "issueDate": "Date the invoice was issued.",
+ "dueDate": "Date payment is due.",
+ "dateFrom": "Start of the period the invoice covers.",
+ "dateTill": "End of the period the invoice covers.",
+ "invoiceItems": "Line items on the invoice, each with a name, billed time and amounts.",
+ "publicId": "Human-facing invoice number shown to the client.",
+ "status": "Invoice status: 'draft', 'sent' or 'paid'.",
+ "projects": "Project ids the invoice draws its time and expenses from.",
+ "includeTime": "Whether tracked time is billed on this invoice.",
+ "includeExpenses": "Whether expenses are billed on this invoice.",
+ "discount": "Discount applied to the invoice (rate and amount in cents).",
+ "tax": "Tax applied to the invoice (rate and amount in cents).",
+ "listAmount": "Amount in cents before discount and taxes.",
+ "netAmount": "Amount in cents with the discount applied but before taxes.",
+ "totalAmount": "Amount in cents with both discount and taxes applied.",
+ "totalTime": "Total time billed on the invoice, in seconds.",
+ },
+ },
+ "expenses": {
+ "description": "A cost recorded against a project, used alongside time records for margin and billing.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "id": "Unique identifier for the expense.",
+ "date": "Calendar date the expense was incurred (YYYY-MM-DD).",
+ "amount": "Expense amount, in cents.",
+ "category": "Identifier of the expense category.",
+ "project": "Identifier of the project the expense belongs to.",
+ "user": "Identifier of the user who recorded the expense.",
+ "billable": "Whether the expense can be billed to the client.",
+ "quantity": "Number of units, for unit-based categories such as mileage.",
+ "details": "Free-text notes on the expense.",
+ "attachments": "Receipts and other files attached to the expense.",
+ },
+ },
+ "timecards": {
+ "description": "Clock-in and clock-out attendance per user per day. Separate from time records, which log time against tasks.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "user": "Identifier of the user the timecard belongs to.",
+ "date": "Calendar date the timecard covers (YYYY-MM-DD).",
+ "clockIn": "Clock-in time, in the user's timezone.",
+ "clockOut": "Clock-out time, in the user's timezone.",
+ "breakTime": "Total break duration, in seconds.",
+ "workTime": "Working time in seconds: clock-out minus clock-in minus breaks.",
+ "history": "Ordered record of every clock-in, clock-out and break change on the day.",
+ },
+ },
+ "assignments": {
+ "description": "Planned work and time off from the resource planner, giving the scheduled counterpart to logged time records.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "id": "Unique identifier for the assignment.",
+ "user": "Identifier of the user the work is scheduled for.",
+ "project": "Identifier of the project the work is scheduled against.",
+ "type": "Whether the entry is scheduled project work or time off.",
+ "startDate": "First day of the scheduled period.",
+ "endDate": "Last day of the scheduled period.",
+ "days": "Number of workdays the assignment spans.",
+ "time": "Scheduled time across the period, in seconds.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/everhour/everhour.com-doc.md b/products/warehouse_sources/backend/temporal/data_imports/sources/everhour/everhour.com-doc.md
index 36be3f4463cc..2d9e1a4d5d4f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/everhour/everhour.com-doc.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/everhour/everhour.com-doc.md
@@ -29,7 +29,7 @@ import AlphaRelease from "../\_snippets/alpha-release.mdx"
<AlphaRelease />
-[Everhour](https://everhour.com) is a time-tracking, budgeting, and resource-planning tool for teams. This source syncs your Everhour clients, projects, tasks, team members, and time records into the PostHog data warehouse so you can join time-tracking data with your product and revenue data.
+[Everhour](https://everhour.com) is a time-tracking, budgeting, and resource-planning tool for teams. This source syncs your Everhour clients, projects, tasks, team members, time records, invoices, expenses, timecards, and resource planner assignments into the PostHog data warehouse so you can join time-tracking data with your product and revenue data.
## Prerequisites
@@ -51,7 +51,9 @@ Paste the key into the API key field when connecting the source in PostHog. The
<SyncModes />
-Most Everhour reference tables (clients, projects, users, tasks) have no server-side change timestamp, so they sync as **full refresh**. **Time records** support incremental sync: PostHog uses Everhour's server-side `from`/`to` date window to pull only entries on or after the last synced date.
+**Time records** support incremental sync: PostHog uses Everhour's server-side `from`/`to` date window to pull only entries on or after the last synced date.
+
+Every other table syncs as **full refresh**. Clients, projects, users, tasks, invoices, and expenses have no server-side change timestamp to filter on. Timecards and assignments do accept a date filter, but it selects rows by the day they cover rather than the day they changed, so it cannot tell PostHog what is new since the last sync.
## Configuration
@@ -66,6 +68,9 @@ A few notes:
- **Time values are in seconds.** The `time` field on time records and tasks is a duration in seconds (e.g. `3600` is one hour).
- **Tasks are fanned out per project.** Each task row carries the parent `project_id` it was fetched under, and the primary key is `(project_id, id)` because a task can belong to more than one project.
- **Integration IDs are prefixed.** Projects and tasks imported from integrations use a prefixed id (e.g. `as:` for Asana, `jira:` for Jira, `tr:` for Trello).
+- **Timecards and time records are different things.** A time record is time logged against a task. A timecard is a clock-in and clock-out for one person on one day. Timecards carry no id of their own, so the table is keyed on `(user, date)`.
+- **Invoice line items are nested.** Each invoice row carries its line items in the `invoiceItems` column rather than in a separate table.
+- **Assignments cover planned work and time off.** The `type` column tells the two apart, and the rows reach into the future because they describe scheduled work.
## Troubleshooting
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/everhour/everhour.py b/products/warehouse_sources/backend/temporal/data_imports/sources/everhour/everhour.py
index f3fe2719e91a..a88da0614de3 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/everhour/everhour.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/everhour/everhour.py
@@ -1,7 +1,7 @@
import re
import dataclasses
from collections.abc import Iterator
-from datetime import UTC, date, datetime
+from datetime import UTC, date, datetime, timedelta
from typing import Any, Optional
from urllib.parse import urlencode
@@ -23,9 +23,9 @@ MAX_RETRIES = 5
# Defensive cap so a buggy/ignored offset param can't loop forever. 50k pages * 50 rows is far more
# than any real account holds; reaching it is logged as a warning.
MAX_PAGES_PER_URL = 50_000
-# First sync lower bound for the /time-records date window. Everhour launched in 2015, so this
+# First sync lower bound for every date-windowed endpoint. Everhour launched in 2015, so this
# captures effectively all history while still giving the API a concrete `from` (it otherwise
-# defaults to returning only today's records).
+# defaults to a narrow recent window).
EARLIEST_FROM_DATE = "2015-01-01"
# Matches the parent project id in a fan-out tasks URL: /projects/{project_id}/tasks
@@ -84,11 +84,12 @@ def _format_date(value: Any) -> str:
return str(value)
-def _time_records_window(
+def _date_window(
+ config: EverhourEndpointConfig,
should_use_incremental_field: bool,
db_incremental_field_last_value: Any,
) -> dict[str, str]:
- """Build the from/to date window for /time-records.
+ """Build the from/to date window for an endpoint that accepts one.
On the first sync (or full refresh) we span all history; on an incremental sync we floor `from`
to the watermark's day. Re-querying the whole watermark day each sync is intentional — the boundary
@@ -98,7 +99,12 @@ def _time_records_window(
from_date = _format_date(db_incremental_field_last_value)
else:
from_date = EARLIEST_FROM_DATE
- return {"from": from_date, "to": datetime.now(UTC).date().isoformat()}
+ to_date = datetime.now(UTC).date() + timedelta(days=config.window_days_ahead)
+ return {"from": from_date, "to": to_date.isoformat()}
+
+
+def _row_key(item: dict[str, Any], dedupe_keys: list[str]) -> tuple[Any, ...]:
+ return tuple(item.get(key) for key in dedupe_keys)
@retry(
@@ -205,7 +211,7 @@ def get_rows(
session = _make_session(api_key)
window = (
- _time_records_window(should_use_incremental_field, db_incremental_field_last_value)
+ _date_window(config, should_use_incremental_field, db_incremental_field_last_value)
if config.supports_date_window
else None
)
@@ -221,17 +227,17 @@ def get_rows(
current = remaining.pop(0) if remaining else None
offset = 0
- # The same id only repeats within a base URL when the API ignores `offset`; tracking ids per
- # URL lets us stop instead of looping forever on the first page.
- seen_ids: set[Any] = set()
+ # The same row only repeats within a base URL when the API ignores `offset`; tracking the keys
+ # seen per URL lets us stop instead of looping forever on the first page.
+ seen_keys: set[tuple[Any, ...]] = set()
pages_on_current = 0
while current is not None:
items = _fetch_page(_with_query(current, {"offset": offset}), headers, logger, session)
pages_on_current += 1
- new_items = [item for item in items if item["id"] not in seen_ids]
- seen_ids.update(item["id"] for item in new_items)
+ new_items = [item for item in items if _row_key(item, config.dedupe_keys) not in seen_keys]
+ seen_keys.update(_row_key(item, config.dedupe_keys) for item in new_items)
if config.include_parent_id_as:
parent_id = _parent_project_id(current)
@@ -239,7 +245,7 @@ def get_rows(
item[config.include_parent_id_as] = parent_id
# A full page of genuinely new rows means there may be more; a short page (or one that
- # surfaced no new ids, i.e. offset was ignored) ends this URL.
+ # surfaced no new rows, i.e. offset was ignored) ends this URL.
would_continue = len(items) >= config.page_size and len(new_items) > 0
if would_continue and pages_on_current >= MAX_PAGES_PER_URL:
logger.warning(f"Everhour: hit max page cap while paginating {current}")
@@ -259,7 +265,7 @@ def get_rows(
new_offset = 0
if new_current != current:
- seen_ids = set()
+ seen_keys = set()
pages_on_current = 0
if new_items:
@@ -303,7 +309,7 @@ def everhour_source(
partition_mode="datetime" if config.partition_key else None,
partition_format=config.partition_format if config.partition_key else None,
partition_keys=[config.partition_key] if config.partition_key else None,
- # /time-records is returned in ascending date order; the reference endpoints are full refresh
+ # /time-records is returned in ascending date order; every other endpoint is full refresh
# so ordering is immaterial for them.
sort_mode="asc",
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/everhour/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/everhour/settings.py
index 127ad3d3764d..4f0a1b71fd72 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/everhour/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/everhour/settings.py
@@ -1,15 +1,20 @@
-from dataclasses import dataclass, field
+from dataclasses import field
from typing import Literal, Optional
+from posthog.dataclasses import frozen
+
from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+# No real planning horizon reaches this far, and Everhour drops assignments ending after ``to``.
+ASSIGNMENTS_DAYS_AHEAD = 5 * 365
+
# How an endpoint's request URLs are derived:
# "none" -> a single top-level list endpoint (no parent fan-out)
# "project" -> one request per project (fan out over /projects)
FanOut = Literal["none", "project"]
-@dataclass
+@frozen
class EverhourEndpointConfig:
name: str
fan_out: FanOut
@@ -20,6 +25,10 @@ class EverhourEndpointConfig:
# /time-records is capped at 50 per page; the reference endpoints comfortably take 100.
page_size: int = 100
primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ # Fields identifying a row while paginating, used to spot a page the API re-served because it
+ # ignored ``offset``. Kept separate from ``primary_keys`` because an injected parent id is only
+ # added to a row after the check, and because not every endpoint returns an ``id``.
+ dedupe_keys: list[str] = field(default_factory=lambda: ["id"])
# Stable creation/work-date field used for datetime partitioning. Never an "updated_at"-style
# field — partitions would rewrite on every sync.
partition_key: Optional[str] = None
@@ -27,6 +36,9 @@ class EverhourEndpointConfig:
# When set, the endpoint accepts ``from``/``to`` (YYYY-MM-DD) date-range filters, enabling
# server-side date-windowed incremental sync.
supports_date_window: bool = False
+ # How far past today the window's ``to`` bound reaches. Endpoints holding scheduled future work
+ # need this; leaving it at 0 would drop every planned row.
+ window_days_ahead: int = 0
incremental_fields: list[IncrementalField] = field(default_factory=list)
# For fan-out endpoints: inject the parent project id into each row under this key, so the
# composite primary key stays unique table-wide (a task can belong to multiple projects).
@@ -74,6 +86,41 @@ EVERHOUR_ENDPOINTS: dict[str, EverhourEndpointConfig] = {
},
],
),
+ "invoices": EverhourEndpointConfig(
+ name="invoices",
+ fan_out="none",
+ path_template="/invoices",
+ # Line items come back nested under `invoiceItems`, and GET /invoices/{id} returns the same
+ # object the list does, so there is nothing further to fan out for.
+ partition_key="createdAt",
+ ),
+ "expenses": EverhourEndpointConfig(
+ name="expenses",
+ fan_out="none",
+ path_template="/expenses",
+ partition_key="date",
+ ),
+ "timecards": EverhourEndpointConfig(
+ name="timecards",
+ fan_out="none",
+ path_template="/timecards",
+ # A timecard carries no id of its own; a user holds at most one card per calendar date.
+ primary_keys=["user", "date"],
+ dedupe_keys=["user", "date"],
+ partition_key="date",
+ # /timecards defaults to the last two weeks, so the window has to be passed explicitly to
+ # reach any history at all.
+ supports_date_window=True,
+ ),
+ "assignments": EverhourEndpointConfig(
+ name="assignments",
+ fan_out="none",
+ path_template="/resource-planner/assignments",
+ # An assignment carries no creation timestamp, and its startDate moves whenever the work is
+ # replanned, so there is no stable partition key to use.
+ supports_date_window=True,
+ window_days_ahead=ASSIGNMENTS_DAYS_AHEAD,
+ ),
}
ENDPOINTS = tuple(EVERHOUR_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/everhour/tests/test_everhour.py b/products/warehouse_sources/backend/temporal/data_imports/sources/everhour/tests/test_everhour.py
index 6729b5f38ab4..c494ff404bff 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/everhour/tests/test_everhour.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/everhour/tests/test_everhour.py
@@ -10,9 +10,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.everhour.e
EVERHOUR_BASE_URL,
EverhourResumeConfig,
_build_initial_urls,
+ _date_window,
_format_date,
_parent_project_id,
- _time_records_window,
_with_query,
everhour_source,
get_rows,
@@ -67,24 +67,39 @@ class TestFormatDate:
assert _format_date(value) == expected
-class TestTimeRecordsWindow:
+class TestDateWindow:
@time_machine.travel("2026-06-15T12:00:00Z", tick=False)
def test_first_sync_spans_all_history(self) -> None:
- window = _time_records_window(should_use_incremental_field=True, db_incremental_field_last_value=None)
+ window = _date_window(
+ EVERHOUR_ENDPOINTS["time_records"], should_use_incremental_field=True, db_incremental_field_last_value=None
+ )
assert window == {"from": EARLIEST_FROM_DATE, "to": "2026-06-15"}
@time_machine.travel("2026-06-15T12:00:00Z", tick=False)
def test_full_refresh_spans_all_history(self) -> None:
- window = _time_records_window(should_use_incremental_field=False, db_incremental_field_last_value=None)
+ window = _date_window(
+ EVERHOUR_ENDPOINTS["time_records"], should_use_incremental_field=False, db_incremental_field_last_value=None
+ )
assert window == {"from": EARLIEST_FROM_DATE, "to": "2026-06-15"}
@time_machine.travel("2026-06-15T12:00:00Z", tick=False)
def test_incremental_floors_from_to_watermark_day(self) -> None:
- window = _time_records_window(
- should_use_incremental_field=True, db_incremental_field_last_value=date(2026, 5, 1)
+ window = _date_window(
+ EVERHOUR_ENDPOINTS["time_records"],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=date(2026, 5, 1),
)
assert window == {"from": "2026-05-01", "to": "2026-06-15"}
+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)
+ def test_assignments_window_reaches_into_the_future(self) -> None:
+ # Resource-planner rows are scheduled ahead of today; a `to` of today would drop all of them.
+ window = _date_window(
+ EVERHOUR_ENDPOINTS["assignments"], should_use_incremental_field=False, db_incremental_field_last_value=None
+ )
+ assert window["from"] == EARLIEST_FROM_DATE
+ assert window["to"] > "2030-01-01"
+
class TestParentProjectId:
def test_extracts_project_id(self) -> None:
@@ -126,7 +141,9 @@ class TestBuildInitialUrls:
@time_machine.travel("2026-06-15T12:00:00Z", tick=False)
def test_time_records_bakes_in_date_window(self) -> None:
- window = _time_records_window(should_use_incremental_field=True, db_incremental_field_last_value=None)
+ window = _date_window(
+ EVERHOUR_ENDPOINTS["time_records"], should_use_incremental_field=True, db_incremental_field_last_value=None
+ )
urls = _build_initial_urls(EVERHOUR_ENDPOINTS["time_records"], window, {}, mock.MagicMock(), mock.MagicMock())
assert len(urls) == 1
assert "limit=50" in urls[0]
@@ -251,6 +268,23 @@ class TestGetRows:
assert batches == []
manager.save_state.assert_not_called()
+ @mock.patch(f"{EVERHOUR_MODULE}.make_tracked_session")
+ @mock.patch(f"{EVERHOUR_MODULE}._build_initial_urls")
+ @mock.patch(f"{EVERHOUR_MODULE}._fetch_page")
+ def test_rows_without_an_id_paginate_on_their_own_key(
+ self, mock_fetch: mock.MagicMock, mock_build_urls: mock.MagicMock, _mock_session: mock.MagicMock
+ ) -> None:
+ # Timecards carry no `id`, so the pagination guard has to key on (user, date) instead.
+ mock_build_urls.return_value = [f"{EVERHOUR_BASE_URL}/timecards?limit=100"]
+ first_page = [{"user": u, "date": "2026-06-01", "workTime": 3600} for u in range(100)]
+ mock_fetch.side_effect = [first_page, [{"user": 0, "date": "2026-06-02", "workTime": 3600}]]
+
+ manager = _make_manager()
+ rows = [row for batch in get_rows("key", "timecards", mock.MagicMock(), manager) for row in batch]
+
+ assert len(rows) == 101
+ assert "offset=100" in mock_fetch.call_args_list[1].args[0]
+
@mock.patch(f"{EVERHOUR_MODULE}.make_tracked_session")
@mock.patch(f"{EVERHOUR_MODULE}._build_initial_urls")
def test_no_urls_yields_nothing(self, mock_build_urls: mock.MagicMock, _mock_session: mock.MagicMock) -> None:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/everhour/tests/test_everhour_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/everhour/tests/test_everhour_source.py
index 17e719567885..13bedad01949 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/everhour/tests/test_everhour_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/everhour/tests/test_everhour_source.py
@@ -50,7 +50,7 @@ class TestEverhourSource:
assert schemas["time_records"].supports_append is True
assert [f["field"] for f in schemas["time_records"].incremental_fields] == ["date"]
- for name in ("clients", "projects", "users", "tasks"):
+ for name in set(ENDPOINTS) - {"time_records"}:
assert schemas[name].supports_incremental is False
assert schemas[name].supports_append is False
assert schemas[name].incremental_fields == []