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(data-warehouse): add Workiz import source (#84471)

Tom Owersf672d798be8c
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/http/observer.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/http/observer.py
index a86f223da27d..540583aa6eec 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/http/observer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/http/observer.py
@@ -109,9 +109,10 @@ def record_request(
method = (request.method or "GET").upper()
raw_url = request.url or ""
scrubbed_url = scrub_url(raw_url)
+ template = url_template(raw_url)
if redact_values:
scrubbed_url = redact_literal_values(scrubbed_url, redact_values)
- template = url_template(raw_url)
+ template = redact_literal_values(template, redact_values)
host = host_of(raw_url)
status_code = response.status_code if response is not None else None
error_class = type(exception).__name__ if exception is not None else None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_http_observer.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_http_observer.py
index 04a9f0f37a26..13f5b52476de 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_http_observer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_http_observer.py
@@ -149,6 +149,21 @@ def test_log_redacts_credential_in_non_denylisted_query_param(captured_logs):
assert "page=2" in entry["url"]
+def test_log_redacts_credential_embedded_in_path_from_url_template(captured_logs):
+ # A path-based credential (e.g. Workiz's token-in-URL auth) isn't numeric,
+ # UUID, or hex, so `url_template`'s own ID-shaped heuristics won't mask it --
+ # it must be caught by value-based redaction like the full `url` field is.
+ request = _make_request(url="https://api.workiz.com/api/v1/not-hex-token-value/team/all/")
+ response = _make_response(status_code=200)
+
+ record_request(request, response, started_at_monotonic=time.monotonic(), redact_values=("not-hex-token-value",))
+
+ entry = _entries(captured_logs)[-1]
+ assert "not-hex-token-value" not in entry["url"]
+ assert "not-hex-token-value" not in entry["url_template"]
+ assert "REDACTED" in entry["url_template"]
+
+
def test_log_includes_job_context_fields(captured_logs, job_ctx):
request = _make_request()
response = _make_response(status_code=200)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/workiz.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/workiz.py
index 8b1da92e959d..5381518d9e82 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/workiz.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/workiz.py
@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class WorkizSourceConfig(config.Config):
- pass
+ api_token: str
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/workiz/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/workiz/canonical_descriptions.py
new file mode 100644
index 000000000000..89efe448e45e
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/workiz/canonical_descriptions.py
@@ -0,0 +1,103 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "Jobs": {
+ "description": "A scheduled job in Workiz, covering the client, address, pricing, and status of a piece of work.",
+ "docs_url": "https://developer.workiz.com/#tag/Jobs",
+ "columns": {
+ "UUID": "Unique identifier for the job.",
+ "SerialId": "Sequential job number shown in the Workiz UI.",
+ "JobDateTime": "Date and time the job is scheduled to start.",
+ "JobEndDateTime": "Date and time the job is scheduled to end.",
+ "CreatedDate": "Date and time the job was created.",
+ "JobTotalPrice": "Total price of the job.",
+ "JobAmountDue": "Amount still owed on the job.",
+ "SubTotal": "Job subtotal before adjustments.",
+ "item_cost": "Total cost of items used on the job.",
+ "tech_cost": "Total cost of technician labor on the job.",
+ "ClientId": "Identifier of the client the job is for.",
+ "Status": "Current job status, for example Submitted, In progress, Done, or Canceled.",
+ "SubStatus": "Additional status detail beneath the main job status.",
+ "PaymentDueDate": "Date payment for the job is due.",
+ "Phone": "Client's primary phone number.",
+ "SecondPhone": "Client's secondary phone number.",
+ "Email": "Client's email address.",
+ "Comments": "Free-text comments left on the job.",
+ "FirstName": "Client's first name.",
+ "LastName": "Client's last name.",
+ "Company": "Client's company name.",
+ "Address": "Job site street address.",
+ "City": "Job site city.",
+ "State": "Job site state or province.",
+ "PostalCode": "Job site postal code.",
+ "Country": "Job site country.",
+ "JobType": "Type of job, for example Repair or Installation.",
+ "ReferralCompany": "Company or platform that referred the job.",
+ "Timezone": "Timezone the job is scheduled in.",
+ "JobNotes": "Internal notes about the job.",
+ "JobSource": "Marketing source the job came from.",
+ "CreatedBy": "Name of the user who created the job.",
+ "ServiceArea": "Service area the job falls under.",
+ "LastStatusUpdate": "Date and time the job status last changed.",
+ "Team": "Team members assigned to the job.",
+ },
+ },
+ "Leads": {
+ "description": "A sales lead in Workiz, before it's converted into a job.",
+ "docs_url": "https://developer.workiz.com/#tag/Leads",
+ "columns": {
+ "UUID": "Unique identifier for the lead.",
+ "SerialId": "Sequential lead number shown in the Workiz UI.",
+ "LeadDateTime": "Date and time the lead is scheduled to start.",
+ "LeadEndDateTime": "Date and time the lead is scheduled to end.",
+ "CreatedDate": "Date and time the lead was created.",
+ "ClientId": "Identifier of the client the lead is for.",
+ "Status": "Current lead status, for example Submitted or Lost.",
+ "SubStatus": "Additional status detail beneath the main lead status.",
+ "Phone": "Client's primary phone number.",
+ "SecondPhone": "Client's secondary phone number.",
+ "Email": "Client's email address.",
+ "Comments": "Free-text comments left on the lead.",
+ "FirstName": "Client's first name.",
+ "LastName": "Client's last name.",
+ "Company": "Client's company name.",
+ "Address": "Lead site street address.",
+ "City": "Lead site city.",
+ "State": "Lead site state or province.",
+ "PostalCode": "Lead site postal code.",
+ "Country": "Lead site country.",
+ "JobType": "Type of work the lead is for.",
+ "ReferralCompany": "Company or platform that referred the lead.",
+ "Timezone": "Timezone the lead is scheduled in.",
+ "JobSource": "Marketing source the lead came from.",
+ "LeadNotes": "Internal notes about the lead.",
+ "Team": "Team members assigned to the lead.",
+ },
+ },
+ "Team": {
+ "description": "An active team member in the Workiz account.",
+ "docs_url": "https://developer.workiz.com/#tag/Team",
+ "columns": {
+ "id": "Unique identifier for the team member.",
+ "name": "Team member's full name.",
+ "created": "Date and time the team member was added to Workiz.",
+ "role": "Team member's role, for example tech or admin.",
+ "fieldTech": "Whether the team member is a field technician.",
+ "email": "Team member's email address.",
+ "serviceAreas": "Service areas the team member covers.",
+ "skills": "Skills tagged on the team member.",
+ "active": "Whether the team member's account is active.",
+ },
+ },
+ "TimeOff": {
+ "description": "A scheduled time-off window for a team member or the whole business.",
+ "docs_url": "https://developer.workiz.com/#tag/Time-Off",
+ "columns": {
+ "start": "Date and time the time off starts.",
+ "end": "Date and time the time off ends.",
+ "userName": "Name of the team member the time off applies to, or the business as a whole.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/workiz/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/workiz/settings.py
new file mode 100644
index 000000000000..3aad3738a736
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/workiz/settings.py
@@ -0,0 +1,54 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field
+from products.warehouse_sources.backend.types import IncrementalField
+
+ENDPOINTS = ("Jobs", "Leads", "Team", "TimeOff")
+
+# Only Jobs and Leads accept a `start_date` window; Team and TimeOff always return their
+# full (small) result set with no server-side filter.
+DATE_WINDOWED_ENDPOINTS = ("Jobs", "Leads")
+
+# Team and TimeOff return everything in one call; Jobs and Leads are offset-paginated.
+UNPAGINATED_ENDPOINTS = ("Team", "TimeOff")
+
+# `start_date` filters on the same field each endpoint is sorted by (JobDateTime / LeadDateTime),
+# not on when the record was last edited -- see the caveat on the source class.
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ "Jobs": [incremental_field("JobDateTime")],
+ "Leads": [incremental_field("LeadDateTime")],
+}
+
+DEFAULT_INCREMENTAL_FIELD: dict[str, str] = {
+ "Jobs": "JobDateTime",
+ "Leads": "LeadDateTime",
+}
+
+PRIMARY_KEYS: dict[str, list[str]] = {
+ "Jobs": ["UUID"],
+ "Leads": ["UUID"],
+ "Team": ["id"],
+ # TimeOff has no id field; a user + window start is the closest thing to unique.
+ "TimeOff": ["userName", "start"],
+}
+
+# CreatedDate never changes once a job/lead is created, unlike the schedulable
+# JobDateTime/LeadDateTime fields -- a partition key must be stable.
+PARTITION_KEYS: dict[str, str] = {
+ "Jobs": "CreatedDate",
+ "Leads": "CreatedDate",
+}
+
+TABLE_NAMES: dict[str, str] = {
+ "Jobs": "jobs",
+ "Leads": "leads",
+ "Team": "team",
+ "TimeOff": "time_off",
+}
+
+ENDPOINT_PATHS: dict[str, str] = {
+ "Jobs": "/job/all/",
+ "Leads": "/lead/all/",
+ "Team": "/team/all/",
+ "TimeOff": "/TimeOff/get/",
+}
+
+PAGE_SIZE = 100
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/workiz/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/workiz/source.py
index cd88936d5234..83e9f66c8af6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/workiz/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/workiz/source.py
@@ -1,30 +1,145 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (
+ SourceSchema,
+ build_endpoint_schemas,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.workiz import WorkizSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.workiz.settings import (
+ DATE_WINDOWED_ENDPOINTS,
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ PARTITION_KEYS,
+ PRIMARY_KEYS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.workiz.workiz import (
+ WorkizResumeConfig,
+ validate_credentials as validate_workiz_credentials,
+ workiz_source,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class WorkizSource(SimpleSource[WorkizSourceConfig]):
+class WorkizSource(ResumableSource[WorkizSourceConfig, WorkizResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog -- safe for public docs
+ api_docs_url = "https://developer.workiz.com/"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.WORKIZ
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error": "Workiz authentication failed. Please check your API token.",
+ "403 Client Error": "Workiz authentication failed. Please check your API token.",
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.workiz.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: WorkizSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ api_version: str | None = None,
+ ) -> list[SourceSchema]:
+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)
+
+ def validate_credentials(
+ self,
+ config: WorkizSourceConfig,
+ team_id: int,
+ schema_name: Optional[str] = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ return validate_workiz_credentials(config.api_token)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[WorkizResumeConfig]:
+ return ResumableSourceManager[WorkizResumeConfig](inputs, WorkizResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: WorkizSourceConfig,
+ resumable_source_manager: ResumableSourceManager[WorkizResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ resource = workiz_source(
+ api_token=config.api_token,
+ endpoint=inputs.schema_name,
+ team_id=inputs.team_id,
+ job_id=inputs.job_id,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
+ incremental_field=inputs.incremental_field,
+ )
+ partition_key = PARTITION_KEYS.get(inputs.schema_name)
+ return SourceResponse(
+ name=resource.name,
+ items=lambda: resource,
+ primary_keys=PRIMARY_KEYS.get(inputs.schema_name, ["id"]),
+ column_hints=resource.column_hints,
+ partition_count=1 if partition_key else None,
+ partition_size=1 if partition_key else None,
+ partition_mode="datetime" if partition_key else None,
+ partition_format="month" if partition_key else None,
+ partition_keys=[partition_key] if partition_key else None,
+ # Jobs/Leads are sorted newest-first with no way to request ascending order; Team/
+ # TimeOff return their full list in one shot so sort order there is moot.
+ sort_mode="desc" if inputs.schema_name in DATE_WINDOWED_ENDPOINTS else "asc",
+ )
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.WORKIZ,
category=DataWarehouseSourceCategory.CRM,
label="Workiz",
+ caption=(
+ "Sync jobs, leads, team members, and time off from Workiz. Requires the "
+ "Developer API add-on, enabled from Settings > Integrations > Developer in Workiz."
+ ),
+ docsUrl="https://posthog.com/docs/cdp/sources/workiz",
iconPath="/static/services/workiz.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ releaseStatus=ReleaseStatus.ALPHA,
+ keywords=["field service", "jobs", "leads"],
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_token",
+ label="API token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/workiz/tests/test_workiz.py b/products/warehouse_sources/backend/temporal/data_imports/sources/workiz/tests/test_workiz.py
new file mode 100644
index 000000000000..ef3148e7134c
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/workiz/tests/test_workiz.py
@@ -0,0 +1,313 @@
+import json
+from typing import Any, Optional
+
+import pytest
+from unittest import mock
+
+from parameterized import parameterized
+from requests import HTTPError, Response
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.workiz.settings import PAGE_SIZE
+from products.warehouse_sources.backend.temporal.data_imports.sources.workiz.workiz import (
+ WorkizResumeConfig,
+ get_resource,
+ validate_credentials,
+ workiz_source,
+)
+
+# RESTClient builds its session via make_tracked_session in the rest_client module.
+CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
+# validate_credentials builds its own tracked session in the workiz module.
+WORKIZ_SESSION_PATCH = (
+ "products.warehouse_sources.backend.temporal.data_imports.sources.workiz.workiz.make_tracked_session"
+)
+TENACITY_SLEEP_PATCH = "tenacity.nap.time.sleep"
+
+
+def _raw_response(body: Any, *, status: int = 200) -> Response:
+ resp = Response()
+ resp.status_code = status
+ resp.url = "https://api.workiz.com/api/v1/tok/job/all/"
+ resp._content = b"" if body is None else json.dumps(body).encode()
+ return resp
+
+
+def _job(uuid: str) -> dict[str, Any]:
+ return {"flag": True, "data": {"UUID": uuid, "Status": "Submitted"}}
+
+
+def _make_manager(resume_state: Optional[WorkizResumeConfig] = None) -> mock.MagicMock:
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = resume_state is not None
+ manager.load_state.return_value = resume_state
+ return manager
+
+
+def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str, Any]]:
+ """Wire a mock session and capture each request's params AT SEND TIME.
+
+ `request.params` is one dict mutated in place across pages, so inspecting it after the run
+ shows only the final state -- snapshot a copy when each request is prepared instead.
+ """
+ session.headers = {}
+ param_snapshots: list[dict[str, Any]] = []
+
+ def _prepare(request: Any) -> mock.MagicMock:
+ param_snapshots.append(dict(request.params or {}))
+ return mock.MagicMock()
+
+ session.prepare_request.side_effect = _prepare
+ session.send.side_effect = responses
+ return param_snapshots
+
+
+def _source(
+ manager: mock.MagicMock,
+ endpoint: str = "Leads",
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+ incremental_field: Optional[str] = None,
+) -> Any:
+ return workiz_source(
+ api_token="tok",
+ endpoint=endpoint,
+ team_id=1,
+ job_id="job-1",
+ resumable_source_manager=manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ incremental_field=incremental_field,
+ )
+
+
+def _rows(resource: Any) -> list[dict[str, Any]]:
+ return [row for page in resource for row in page]
+
+
+class TestPagination:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_paginates_and_progresses_offset(self, MockSession: mock.MagicMock) -> None:
+ session = MockSession.return_value
+ full_page = [{"UUID": str(i)} for i in range(PAGE_SIZE)]
+ params = _wire(
+ session,
+ [
+ _raw_response(full_page),
+ _raw_response([{"UUID": "last"}]),
+ ],
+ )
+
+ manager = _make_manager()
+ rows = _rows(_source(manager))
+
+ assert [r["UUID"] for r in rows] == [*(str(i) for i in range(PAGE_SIZE)), "last"]
+ assert params[0]["offset"] == 0
+ assert params[0]["records"] == PAGE_SIZE
+ assert params[1]["offset"] == PAGE_SIZE
+ manager.save_state.assert_called_once_with(WorkizResumeConfig(offset=PAGE_SIZE))
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_short_first_page_one_request_and_no_checkpoint(self, MockSession: mock.MagicMock) -> None:
+ session = MockSession.return_value
+ _wire(session, [_raw_response([{"UUID": "a"}, {"UUID": "b"}])])
+
+ manager = _make_manager()
+ rows = _rows(_source(manager))
+
+ assert [r["UUID"] for r in rows] == ["a", "b"]
+ assert session.send.call_count == 1
+ manager.save_state.assert_not_called()
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_resumes_from_saved_offset(self, MockSession: mock.MagicMock) -> None:
+ session = MockSession.return_value
+ params = _wire(session, [_raw_response([{"UUID": "x"}])])
+
+ manager = _make_manager(WorkizResumeConfig(offset=PAGE_SIZE))
+ _rows(_source(manager))
+
+ assert params[0]["offset"] == PAGE_SIZE
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_empty_first_page_yields_nothing(self, MockSession: mock.MagicMock) -> None:
+ session = MockSession.return_value
+ _wire(session, [_raw_response([])])
+
+ manager = _make_manager()
+ rows = _rows(_source(manager))
+
+ assert rows == []
+ assert session.send.call_count == 1
+ manager.save_state.assert_not_called()
+
+ @parameterized.expand([("Team",), ("TimeOff",)])
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_unpaginated_endpoints_send_one_request_with_no_offset(
+ self, endpoint: str, MockSession: mock.MagicMock
+ ) -> None:
+ session = MockSession.return_value
+ params = _wire(session, [_raw_response([{"id": "1"}])])
+
+ rows = _rows(_source(_make_manager(), endpoint=endpoint))
+
+ assert len(rows) == 1
+ assert session.send.call_count == 1
+ assert "offset" not in params[0]
+ assert "records" not in params[0]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_jobs_unwraps_flag_data_wrapper(self, MockSession: mock.MagicMock) -> None:
+ # Workiz's OpenAPI spec wraps each job/all item as {"flag": bool, "data": Job}.
+ session = MockSession.return_value
+ _wire(session, [_raw_response([_job("a"), _job("b")])])
+
+ rows = _rows(_source(_make_manager(), endpoint="Jobs"))
+
+ assert [r["UUID"] for r in rows] == ["a", "b"]
+ assert all("flag" not in r and "data" not in r for r in rows)
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_leads_are_not_wrapped(self, MockSession: mock.MagicMock) -> None:
+ session = MockSession.return_value
+ _wire(session, [_raw_response([{"UUID": "a"}])])
+
+ rows = _rows(_source(_make_manager(), endpoint="Leads"))
+
+ assert rows == [{"UUID": "a"}]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_client_session_excludes_responses_from_sample_capture(self, MockSession: mock.MagicMock) -> None:
+ # Jobs/Leads rows carry customer PII (contact details, addresses, job comments) the
+ # name-based sample scrubbers aren't built to catch, so the client must opt the sync
+ # session out of HTTP diagnostic sample capture entirely.
+ session = MockSession.return_value
+ _wire(session, [_raw_response([])])
+
+ _rows(_source(_make_manager()))
+
+ assert MockSession.call_args.kwargs["capture"] is False
+
+
+class TestIncrementalParams:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_first_incremental_sync_anchors_to_earliest_date(self, MockSession: mock.MagicMock) -> None:
+ session = MockSession.return_value
+ params = _wire(session, [_raw_response([])])
+
+ _rows(_source(_make_manager(), should_use_incremental_field=True, db_incremental_field_last_value=None))
+
+ assert params[0]["start_date"] == "2010-01-01"
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_full_refresh_also_anchors_to_earliest_date(self, MockSession: mock.MagicMock) -> None:
+ # Omitting start_date makes the vendor API default to the last 14 days -- a full-refresh
+ # sync must still pass an explicit far-past anchor to get the whole table.
+ session = MockSession.return_value
+ params = _wire(session, [_raw_response([])])
+
+ _rows(_source(_make_manager(), should_use_incremental_field=False))
+
+ assert params[0]["start_date"] == "2010-01-01"
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_incremental_sync_uses_last_synced_date(self, MockSession: mock.MagicMock) -> None:
+ import datetime
+
+ session = MockSession.return_value
+ params = _wire(session, [_raw_response([])])
+
+ _rows(
+ _source(
+ _make_manager(),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime.datetime(2024, 3, 15, 9, 0, 0),
+ )
+ )
+
+ assert params[0]["start_date"] == "2024-03-15"
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_only_open_and_records_are_always_sent(self, MockSession: mock.MagicMock) -> None:
+ session = MockSession.return_value
+ params = _wire(session, [_raw_response([])])
+
+ _rows(_source(_make_manager()))
+
+ assert params[0]["only_open"] == "false"
+ assert params[0]["records"] == PAGE_SIZE
+
+ @parameterized.expand([("Team",), ("TimeOff",)])
+ def test_unpaginated_endpoints_have_no_start_date_param(self, endpoint: str) -> None:
+ resource = get_resource(endpoint, should_use_incremental_field=False, incremental_field=None)
+ resource_endpoint = resource["endpoint"]
+ assert isinstance(resource_endpoint, dict)
+ assert resource_endpoint.get("params") is None
+
+
+class TestErrorHandling:
+ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])
+ @mock.patch(TENACITY_SLEEP_PATCH)
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_retryable_status_is_retried_then_succeeds(
+ self, _name: str, status: int, MockSession: mock.MagicMock, _sleep: mock.MagicMock
+ ) -> None:
+ session = MockSession.return_value
+ _wire(session, [_raw_response(None, status=status), _raw_response([{"UUID": "ok"}])])
+
+ rows = _rows(_source(_make_manager()))
+
+ assert [r["UUID"] for r in rows] == ["ok"]
+ assert session.send.call_count == 2
+
+ @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("not_found", 404)])
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_client_error_status_raises(self, _name: str, status: int, MockSession: mock.MagicMock) -> None:
+ session = MockSession.return_value
+ _wire(session, [_raw_response(None, status=status)])
+
+ with pytest.raises(HTTPError):
+ _rows(_source(_make_manager()))
+
+
+class TestValidateCredentials:
+ @parameterized.expand(
+ [
+ ("ok", 200, True, None),
+ (
+ "unauthorized",
+ 401,
+ False,
+ "Invalid API token. Check Settings > Integrations > Developer in Workiz and try again.",
+ ),
+ (
+ "forbidden",
+ 403,
+ False,
+ "Invalid API token. Check Settings > Integrations > Developer in Workiz and try again.",
+ ),
+ ("server_error", 500, False, "Workiz returned HTTP 500."),
+ ]
+ )
+ @mock.patch(WORKIZ_SESSION_PATCH)
+ def test_status_mapping(
+ self,
+ _name: str,
+ status: int,
+ expected_valid: bool,
+ expected_message: str | None,
+ mock_session: mock.MagicMock,
+ ) -> None:
+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=status)
+ assert validate_credentials("tok") == (expected_valid, expected_message)
+
+ @mock.patch(WORKIZ_SESSION_PATCH)
+ def test_probe_failure_is_not_validated(self, mock_session: mock.MagicMock) -> None:
+ mock_session.return_value.get.side_effect = Exception("boom")
+ assert validate_credentials("tok") == (False, "Could not reach Workiz to validate the API token.")
+
+ @mock.patch(WORKIZ_SESSION_PATCH)
+ def test_probe_session_excludes_response_from_sample_capture(self, mock_session: mock.MagicMock) -> None:
+ # The probe response is a team-member list -- same PII concern as the sync client.
+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=200)
+ validate_credentials("tok")
+ assert mock_session.call_args.kwargs["capture"] is False
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/workiz/tests/test_workiz_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/workiz/tests/test_workiz_source.py
new file mode 100644
index 000000000000..783342de26f1
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/workiz/tests/test_workiz_source.py
@@ -0,0 +1,199 @@
+import datetime
+
+from unittest import mock
+
+from parameterized import parameterized
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.workiz import WorkizSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.workiz.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.workiz.source import WorkizSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.workiz.workiz import WorkizResumeConfig
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestWorkizSource:
+ def setup_method(self) -> None:
+ self.source = WorkizSource()
+ self.team_id = 123
+ self.config = WorkizSourceConfig(api_token="tok")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.WORKIZ
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+ assert config.name.value == "Workiz"
+ assert config.label == "Workiz"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ # A finished source is visible -- it must not carry the scaffolding flag.
+ assert not config.unreleasedSource
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/workiz"
+
+ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]
+ assert field_names == ["api_token"]
+
+ def test_api_token_field_is_secret_password(self) -> None:
+ config = self.source.get_source_config
+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_token")
+ assert field.type == SourceFieldInputConfigType.PASSWORD
+ assert field.secret is True
+ assert field.required is True
+
+ def test_no_connection_host_fields(self) -> None:
+ # The only field is the secret API token; the base URL is hardcoded, so there is no
+ # non-secret field an editor could retarget to reuse a preserved token against another host.
+ assert self.source.connection_host_fields == []
+
+ def test_lists_tables_without_credentials(self) -> None:
+ assert self.source.lists_tables_without_credentials is True
+
+ def test_get_schemas_covers_all_endpoints(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+
+ @parameterized.expand([("Jobs",), ("Leads",)])
+ def test_get_schemas_marks_date_windowed_endpoints_incremental(self, name: str) -> None:
+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}
+ assert schemas[name].supports_incremental is True
+ assert schemas[name].incremental_fields != []
+
+ @parameterized.expand([("Team",), ("TimeOff",)])
+ def test_get_schemas_marks_full_list_endpoints_full_refresh(self, name: str) -> None:
+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}
+ assert schemas[name].supports_incremental is False
+ assert schemas[name].incremental_fields == []
+
+ def test_get_schemas_filtered_by_names(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["Team"])
+ assert [s.name for s in schemas] == ["Team"]
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self) -> None:
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ def test_documented_tables_render_for_public_docs(self) -> None:
+ tables = self.source.get_documented_tables()
+ assert {t["name"] for t in tables} == set(ENDPOINTS)
+
+ @parameterized.expand(
+ [
+ ("401 Client Error: Unauthorized for url: https://api.workiz.com/api/v1/tok/job/all/",),
+ ("403 Client Error: Forbidden for url: https://api.workiz.com/api/v1/tok/lead/all/",),
+ ]
+ )
+ def test_non_retryable_errors_match_auth_failures(self, observed_error: str) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable)
+
+ @parameterized.expand(
+ [
+ ("500 Server Error: Internal Server Error for url: https://api.workiz.com/api/v1/tok/job/all/",),
+ ("429 Client Error: Too Many Requests for url: https://api.workiz.com/api/v1/tok/lead/all/",),
+ ]
+ )
+ def test_non_retryable_errors_ignore_transient(self, unrelated_error: str) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert not any(key in unrelated_error for key in non_retryable)
+
+ @parameterized.expand(
+ [
+ (True, None),
+ (False, "Invalid API token. Check Settings > Integrations > Developer in Workiz and try again."),
+ ]
+ )
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.workiz.source.validate_workiz_credentials"
+ )
+ def test_validate_credentials_delegates(
+ self,
+ expected_valid: bool,
+ expected_message: str | None,
+ mock_validate: mock.MagicMock,
+ ) -> None:
+ mock_validate.return_value = (expected_valid, expected_message)
+ is_valid, returned = self.source.validate_credentials(self.config, self.team_id)
+ assert is_valid is expected_valid
+ assert returned == expected_message
+ mock_validate.assert_called_once_with("tok")
+
+ def test_get_resumable_source_manager_binds_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(mock.MagicMock())
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is WorkizResumeConfig
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.workiz.source.workiz_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:
+ mock_source.return_value.name = "Leads"
+ mock_source.return_value.column_hints = None
+ inputs = mock.MagicMock()
+ inputs.schema_name = "Leads"
+ inputs.team_id = 123
+ inputs.job_id = "job-1"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = datetime.datetime(2024, 1, 1)
+ inputs.incremental_field = "LeadDateTime"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_source.assert_called_once()
+ kwargs = mock_source.call_args.kwargs
+ assert kwargs["api_token"] == "tok"
+ assert kwargs["endpoint"] == "Leads"
+ assert kwargs["team_id"] == 123
+ assert kwargs["job_id"] == "job-1"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == datetime.datetime(2024, 1, 1)
+ assert kwargs["incremental_field"] == "LeadDateTime"
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.workiz.source.workiz_source")
+ def test_source_for_pipeline_full_refresh_drops_last_value(self, mock_source: mock.MagicMock) -> None:
+ # should_use_incremental_field=False means the schema is fully replaced each sync, so any
+ # stale last_value must not leak into the request.
+ mock_source.return_value.name = "Leads"
+ mock_source.return_value.column_hints = None
+ inputs = mock.MagicMock()
+ inputs.schema_name = "Leads"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = datetime.datetime(2024, 1, 1)
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ assert mock_source.call_args.kwargs["db_incremental_field_last_value"] is None
+
+ @parameterized.expand(
+ [
+ ("Jobs", ["UUID"], "desc"),
+ ("Leads", ["UUID"], "desc"),
+ ("Team", ["id"], "asc"),
+ ("TimeOff", ["userName", "start"], "asc"),
+ ]
+ )
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.workiz.source.workiz_source")
+ def test_source_for_pipeline_response_shape(
+ self,
+ schema_name: str,
+ expected_primary_keys: list[str],
+ expected_sort_mode: str,
+ mock_source: mock.MagicMock,
+ ) -> None:
+ mock_source.return_value.name = schema_name
+ mock_source.return_value.column_hints = None
+ inputs = mock.MagicMock()
+ inputs.schema_name = schema_name
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = None
+
+ response = self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ assert response.primary_keys == expected_primary_keys
+ assert response.sort_mode == expected_sort_mode
+ if schema_name in ("Jobs", "Leads"):
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == ["CreatedDate"]
+ else:
+ assert response.partition_mode is None
+ assert response.partition_keys is None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/workiz/workiz.py b/products/warehouse_sources/backend/temporal/data_imports/sources/workiz/workiz.py
new file mode 100644
index 000000000000..76a8dc12461b
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/workiz/workiz.py
@@ -0,0 +1,176 @@
+import datetime
+from typing import Any, Optional
+
+from requests import PreparedRequest
+
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (
+ RESTAPIConfig,
+ rest_api_resource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import AuthConfigBase
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ OffsetPaginator,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.resource import Resource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
+ Endpoint,
+ EndpointResource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe
+from products.warehouse_sources.backend.temporal.data_imports.sources.workiz.settings import (
+ DATE_WINDOWED_ENDPOINTS,
+ DEFAULT_INCREMENTAL_FIELD,
+ ENDPOINT_PATHS,
+ PAGE_SIZE,
+ TABLE_NAMES,
+ UNPAGINATED_ENDPOINTS,
+)
+
+API_BASE_URL = "https://api.workiz.com/api/v1"
+
+# Anchor for a full historical backfill. Omitting `start_date` entirely makes the API default to
+# the last 14 days (see only_open/start_date docs), so a from-scratch sync needs an explicit,
+# far-past date instead -- this predates Workiz itself.
+_EARLIEST_START_DATE = datetime.date(2010, 1, 1)
+
+
+class _PathTokenAuth(AuthConfigBase):
+ """No-op auth: the token already lives in the base URL, not a header.
+
+ Declaring it as an auth (rather than baking it into `base_url` alone) lets the shared client
+ redact it from raised exception messages and HTTP log samples, the same way every other
+ source's real auth class does.
+ """
+
+ def __init__(self, token: str) -> None:
+ self._token = token
+
+ def __call__(self, request: PreparedRequest) -> PreparedRequest:
+ return request
+
+ def secret_values(self) -> tuple[str, ...]:
+ return (self._token,)
+
+
+@frozen
+class WorkizResumeConfig:
+ offset: int
+
+
+def _to_workiz_date(value: Any) -> str:
+ """Format an incremental cursor value as the `yyyy-MM-dd` date Workiz's `start_date` expects."""
+ if isinstance(value, datetime.datetime):
+ return value.date().strftime("%Y-%m-%d")
+ if isinstance(value, datetime.date):
+ return value.strftime("%Y-%m-%d")
+ if value is None:
+ return _EARLIEST_START_DATE.strftime("%Y-%m-%d")
+ return str(value)
+
+
+def get_resource(name: str, should_use_incremental_field: bool, incremental_field: Optional[str]) -> EndpointResource:
+ write_disposition = {"disposition": "merge", "strategy": "upsert"} if should_use_incremental_field else "replace"
+
+ if name in DATE_WINDOWED_ENDPOINTS:
+ cursor_field = incremental_field or DEFAULT_INCREMENTAL_FIELD[name]
+ endpoint: Endpoint = {
+ "path": ENDPOINT_PATHS[name],
+ "params": {
+ "start_date": {
+ "type": "incremental",
+ "cursor_path": cursor_field,
+ "initial_value": _EARLIEST_START_DATE,
+ "convert": _to_workiz_date,
+ },
+ "records": PAGE_SIZE,
+ # Historical syncs need Done/Canceled records too; the API excludes them by default.
+ "only_open": "false",
+ },
+ "paginator": OffsetPaginator(
+ limit=PAGE_SIZE, offset_param="offset", limit_param="records", total_path=None
+ ),
+ }
+ if name == "Jobs":
+ # Workiz's published OpenAPI spec (developer.workiz.com/api.json) wraps each job/all
+ # item as {"flag": bool, "data": Job} -- unlike lead/all, which returns Lead objects
+ # directly. Not verified against a live account.
+ endpoint["data_selector"] = "[*].data"
+ else:
+ endpoint = {
+ "path": ENDPOINT_PATHS[name],
+ "paginator": "single_page",
+ }
+
+ resource: EndpointResource = {
+ "name": name,
+ "table_name": TABLE_NAMES[name],
+ "write_disposition": write_disposition,
+ "endpoint": endpoint,
+ "table_format": "delta",
+ }
+ return resource
+
+
+def workiz_source(
+ api_token: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[WorkizResumeConfig],
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Optional[Any],
+ incremental_field: Optional[str],
+) -> Resource:
+ config: RESTAPIConfig = {
+ "client": {
+ "base_url": f"{API_BASE_URL}/{api_token}",
+ "auth": _PathTokenAuth(api_token),
+ # `capture=False`: Jobs/Leads rows carry customer PII (contact details, addresses,
+ # job comments, internal notes) the name-based sample scrubbers aren't built to
+ # catch, so keep them out of HTTP diagnostic sample storage entirely, same as the
+ # other PII/free-text field-service sources (e.g. ServiceM8).
+ "capture": False,
+ },
+ "resources": [get_resource(endpoint, should_use_incremental_field, incremental_field)],
+ }
+
+ initial_paginator_state: Optional[dict[str, Any]] = None
+ if endpoint not in UNPAGINATED_ENDPOINTS and resumable_source_manager.can_resume():
+ resume_config = resumable_source_manager.load_state()
+ if resume_config is not None:
+ initial_paginator_state = {"offset": resume_config.offset}
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ offset = state.get("offset") if state else None
+ if offset is not None:
+ resumable_source_manager.save_state(WorkizResumeConfig(offset=int(offset)))
+
+ return rest_api_resource(
+ config,
+ team_id,
+ job_id,
+ db_incremental_field_last_value,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ )
+
+
+def validate_credentials(api_token: str) -> tuple[bool, str | None]:
+ # The token unlocks every read endpoint at once (no per-endpoint scopes), so one cheap probe
+ # against the smallest list endpoint validates it. `capture=False`: the probe response is a
+ # team-member list, same PII concern as the sync client above.
+ ok, status = validate_via_probe(
+ lambda: make_tracked_session(redact_values=(api_token,), capture=False),
+ f"{API_BASE_URL}/{api_token}/team/all/",
+ )
+ if ok:
+ return True, None
+ if status in (401, 403):
+ return False, "Invalid API token. Check Settings > Integrations > Developer in Workiz and try again."
+ if status is None:
+ return False, "Could not reach Workiz to validate the API token."
+ return False, f"Workiz returned HTTP {status}."