: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): add Harvest source (#77080)
Tom Owersa79dc5045203
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex fc4e0531c1a6..35c88f6cd127 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -296,6 +296,7 @@ the row lists both.| guardian | HTTP | requests | ✅ || guru | HTTP | requests | ✅ || gusto | HTTP | requests | ✅ |+| harvest | HTTP | requests + `rest_source.RESTClient` | ✅ || harvey | HTTP | requests | ✅ || hatchet | HTTP | requests | ✅ || healthchecks | HTTP | requests | ✅ |@@ -1021,7 +1022,6 @@ doesn't conflict with concurrent PRs.- harness- harness_ccm- harness_sei-- harvest- harvey- healthie- heapdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/harvest.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/harvest.pyindex 435ea22caa15..9e00f0fbfe64 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/harvest.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/harvest.py@@ -6,4 +6,5 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass HarvestSourceConfig(config.Config):- pass+ account_id: str+ access_token: strdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/harvest/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/harvest/canonical_descriptions.pynew file mode 100644index 000000000000..fcc92024ab99--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/harvest/canonical_descriptions.py@@ -0,0 +1,284 @@+"""Canonical, documentation-sourced descriptions for Harvest endpoints and columns.++Sourced from the official Harvest API v2 reference (https://help.getharvest.com/api-v2/).+Keyed by the schema names in `settings.py` `ENDPOINTS`, which match the `ExternalDataSchema.name`+of a synced Harvest table. Columns absent here fall back to LLM enrichment.+"""++from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Every Harvest object carries these, so they're merged into each entry rather than repeated.+_COMMON_COLUMNS = {+ "id": "Unique identifier for the object.",+ "created_at": "Date and time the object was created.",+ "updated_at": "Date and time the object was last updated.",+}+++def _columns(**overrides: str) -> dict[str, str]:+ return {**_COMMON_COLUMNS, **overrides}+++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "clients": {+ "description": "A client you track time and bill against.",+ "docs_url": "https://help.getharvest.com/api-v2/clients-api/clients/clients/",+ "columns": _columns(+ name="Name of the client.",+ is_active="Whether the client is active, or archived.",+ address="Physical address of the client.",+ statement_key="Used to build the client's invoice dashboard URL.",+ currency="Currency code associated with the client.",+ ),+ },+ "contacts": {+ "description": "A contact person belonging to a client.",+ "docs_url": "https://help.getharvest.com/api-v2/clients-api/clients/contacts/",+ "columns": _columns(+ client="The client the contact belongs to.",+ title="Job title of the contact.",+ first_name="First name of the contact.",+ last_name="Last name of the contact.",+ email="Email address of the contact.",+ phone_office="Office phone number of the contact.",+ phone_mobile="Mobile phone number of the contact.",+ fax="Fax number of the contact.",+ invoice_recipient_status="Role the contact takes on invoices: none, recipient, cc, or bcc.",+ ),+ },+ "estimate_item_categories": {+ "description": "A category that estimate line items can be filed under.",+ "docs_url": "https://help.getharvest.com/api-v2/estimates-api/estimates/estimate-item-categories/",+ "columns": _columns(name="Name of the estimate item category."),+ },+ "estimates": {+ "description": "An estimate sent to a client, including its line items.",+ "docs_url": "https://help.getharvest.com/api-v2/estimates-api/estimates/estimates/",+ "columns": _columns(+ client="The client the estimate belongs to.",+ line_items="Line items on the estimate.",+ creator="The user who created the estimate.",+ client_key="Used to build the client's estimate URL.",+ number="Estimate number, generated automatically when not set.",+ purchase_order="Purchase order number on the estimate.",+ amount="Total amount of the estimate, including discounts and taxes.",+ tax="First tax percentage applied to the estimate.",+ tax_amount="Amount calculated from the first tax percentage.",+ tax2="Second tax percentage applied to the estimate.",+ tax2_amount="Amount calculated from the second tax percentage.",+ discount="Discount percentage applied to the estimate.",+ discount_amount="Amount calculated from the discount percentage.",+ subject="Subject line of the estimate.",+ notes="Notes shown on the estimate.",+ currency="Currency code of the estimate.",+ state="Current state of the estimate: draft, sent, accepted, or declined.",+ issue_date="Date the estimate was issued.",+ sent_at="Date and time the estimate was sent.",+ accepted_at="Date and time the estimate was accepted.",+ declined_at="Date and time the estimate was declined.",+ ),+ },+ "expense_categories": {+ "description": "A category that expenses can be filed under.",+ "docs_url": "https://help.getharvest.com/api-v2/expenses-api/expenses/expense-categories/",+ "columns": _columns(+ name="Name of the expense category.",+ unit_name="Unit name used when the category is billed by unit.",+ unit_price="Unit price used when the category is billed by unit.",+ is_active="Whether the expense category is active, or archived.",+ ),+ },+ "expenses": {+ "description": "An expense logged against a project.",+ "docs_url": "https://help.getharvest.com/api-v2/expenses-api/expenses/expenses/",+ "columns": _columns(+ client="The client the expense belongs to.",+ project="The project the expense belongs to.",+ expense_category="The category the expense is filed under.",+ user="The user who recorded the expense.",+ user_assignment="The user assignment linking that user to the project.",+ receipt="Receipt file attached to the expense.",+ invoice="The invoice the expense was billed on, if any.",+ notes="Notes on the expense.",+ units="Quantity of units, when the category is billed by unit.",+ total_cost="Total cost of the expense.",+ billable="Whether the expense can be billed to the client.",+ is_closed="Whether the expense is locked because its project or invoice is closed.",+ is_locked="Whether the expense can no longer be edited.",+ is_billed="Whether the expense has been added to an invoice.",+ locked_reason="Why the expense is locked, when it is.",+ approval_status="Approval state of the expense: unsubmitted, submitted, or approved.",+ spent_date="Date the expense was incurred.",+ ),+ },+ "invoice_item_categories": {+ "description": "A category that invoice line items can be filed under.",+ "docs_url": "https://help.getharvest.com/api-v2/invoices-api/invoices/invoice-item-categories/",+ "columns": _columns(+ name="Name of the invoice item category.",+ use_as_service="Whether the category is used for billable hours when generating an invoice.",+ use_as_expense="Whether the category is used for expenses when generating an invoice.",+ ),+ },+ "invoices": {+ "description": "An invoice issued to a client, including its line items.",+ "docs_url": "https://help.getharvest.com/api-v2/invoices-api/invoices/invoices/",+ "columns": _columns(+ client="The client the invoice belongs to.",+ line_items="Line items on the invoice.",+ estimate="The estimate the invoice was generated from, if any.",+ retainer="The retainer associated with the invoice, if any.",+ creator="The user who created the invoice.",+ client_key="Used to build the client's invoice URL.",+ number="Invoice number, generated automatically when not set.",+ purchase_order="Purchase order number on the invoice.",+ amount="Total amount of the invoice, including discounts and taxes.",+ due_amount="Amount still outstanding on the invoice.",+ tax="First tax percentage applied to the invoice.",+ tax_amount="Amount calculated from the first tax percentage.",+ tax2="Second tax percentage applied to the invoice.",+ tax2_amount="Amount calculated from the second tax percentage.",+ discount="Discount percentage applied to the invoice.",+ discount_amount="Amount calculated from the discount percentage.",+ subject="Subject line of the invoice.",+ notes="Notes shown on the invoice.",+ currency="Currency code of the invoice.",+ state="Current state of the invoice: draft, open, paid, or closed.",+ period_start="Start of the time period the invoice covers.",+ period_end="End of the time period the invoice covers.",+ issue_date="Date the invoice was issued.",+ due_date="Date payment is due.",+ payment_term="Payment term of the invoice.",+ payment_options="Payment methods the client can use to pay the invoice.",+ sent_at="Date and time the invoice was sent.",+ paid_at="Date and time the invoice was paid.",+ paid_date="Date the invoice was paid.",+ closed_at="Date and time the invoice was closed.",+ ),+ },+ "projects": {+ "description": "A project that time and expenses are tracked against.",+ "docs_url": "https://help.getharvest.com/api-v2/projects-api/projects/projects/",+ "columns": _columns(+ client="The client the project belongs to.",+ name="Name of the project.",+ code="Short code for the project.",+ is_active="Whether the project is active, or archived.",+ is_billable="Whether the project is billable.",+ is_fixed_fee="Whether the project is a fixed-fee project.",+ bill_by="How the project is invoiced: Project, Tasks, People, or none.",+ hourly_rate="Rate for projects billed by project hourly rate.",+ budget="Budget in hours or currency, depending on budget_by.",+ budget_by="What the budget is measured against: project, project_cost, task, task_fees, person, or none.",+ budget_is_monthly="Whether the budget resets every month.",+ notify_when_over_budget="Whether managers are notified when the project goes over budget.",+ over_budget_notification_percentage="Percentage of the budget that triggers the notification.",+ over_budget_notification_date="Date the last over-budget notification was sent.",+ show_budget_to_all="Whether the budget is visible to everyone assigned to the project.",+ cost_budget="Monetary budget for the project.",+ cost_budget_include_expenses="Whether expenses count toward the cost budget.",+ fee="Fee charged for a fixed-fee project.",+ notes="Notes on the project.",+ starts_on="Date the project starts.",+ ends_on="Date the project ends.",+ ),+ },+ "roles": {+ "description": "A role and the users assigned to it.",+ "docs_url": "https://help.getharvest.com/api-v2/roles-api/roles/roles/",+ "columns": _columns(+ name="Name of the role.",+ user_ids="Identifiers of the users assigned to the role.",+ ),+ },+ "task_assignments": {+ "description": "A task assigned to a project, with its billable rate and budget.",+ "docs_url": "https://help.getharvest.com/api-v2/projects-api/projects/task-assignments/",+ "columns": _columns(+ project="The project the task is assigned to.",+ task="The assigned task.",+ is_active="Whether the task assignment is active, or archived.",+ billable="Whether the task is billable on this project.",+ hourly_rate="Rate used when the project is billed by task hourly rate.",+ budget="Budget in hours or currency for this task on the project.",+ ),+ },+ "tasks": {+ "description": "A task that can be assigned to projects.",+ "docs_url": "https://help.getharvest.com/api-v2/tasks-api/tasks/tasks/",+ "columns": _columns(+ name="Name of the task.",+ billable_by_default="Whether the task is billable by default when added to a project.",+ default_hourly_rate="Rate used by default when the task is added to a project.",+ is_default="Whether the task is added to new projects automatically.",+ is_active="Whether the task is active, or archived.",+ ),+ },+ "time_entries": {+ "description": "A tracked block of time, one row per entry.",+ "docs_url": "https://help.getharvest.com/api-v2/timesheets-api/timesheets/time-entries/",+ "columns": _columns(+ user="The user the time entry belongs to.",+ user_assignment="The user assignment linking that user to the project.",+ client="The client the time entry belongs to.",+ project="The project the time entry belongs to.",+ task="The task the time was tracked against.",+ task_assignment="The task assignment linking that task to the project.",+ external_reference="Reference to an object in an external system, when the entry was imported.",+ invoice="The invoice the time entry was billed on, if any.",+ spent_date="Date the time was spent.",+ hours="Number of hours tracked, including any running timer.",+ hours_without_timer="Number of hours tracked, excluding any running timer.",+ rounded_hours="Hours tracked, rounded according to the account's rounding settings.",+ notes="Notes on the time entry.",+ is_locked="Whether the time entry can no longer be edited.",+ locked_reason="Why the time entry is locked, when it is.",+ is_closed="Whether the time entry is locked because its project or invoice is closed.",+ is_billed="Whether the time entry has been added to an invoice.",+ timer_started_at="Date and time a running timer was started.",+ started_time="Time the entry was started, when the account tracks start and end times.",+ ended_time="Time the entry was ended, when the account tracks start and end times.",+ is_running="Whether a timer is currently running for the entry.",+ billable="Whether the time entry can be billed to the client.",+ budgeted="Whether the time entry counts toward the project budget.",+ billable_rate="Rate the time entry is billed at.",+ cost_rate="Cost rate of the user at the time the entry was recorded.",+ approval_status="Approval state of the entry: unsubmitted, submitted, or approved.",+ ),+ },+ "user_assignments": {+ "description": "A user assigned to a project, with their rate and budget.",+ "docs_url": "https://help.getharvest.com/api-v2/projects-api/projects/user-assignments/",+ "columns": _columns(+ project="The project the user is assigned to.",+ user="The assigned user.",+ is_active="Whether the user assignment is active, or archived.",+ is_project_manager="Whether the user manages the project.",+ use_default_rates="Whether the assignment uses the user's default rates.",+ hourly_rate="Rate used when the project is billed by person hourly rate.",+ budget="Budget in hours or currency for this user on the project.",+ ),+ },+ "users": {+ "description": "A person in the Harvest account.",+ "docs_url": "https://help.getharvest.com/api-v2/users-api/users/users/",+ "columns": _columns(+ first_name="First name of the user.",+ last_name="Last name of the user.",+ email="Email address of the user.",+ telephone="Telephone number of the user.",+ timezone="Timezone the user works in.",+ has_access_to_all_future_projects="Whether the user is assigned to every future project.",+ is_contractor="Whether the user is a contractor rather than an employee.",+ is_active="Whether the user is active, or archived.",+ weekly_capacity="Number of seconds the user is expected to work per week.",+ default_hourly_rate="Default billable rate for the user.",+ cost_rate="Cost rate of the user.",+ roles="Names of the roles assigned to the user.",+ access_roles="Access roles that determine what the user can do in Harvest.",+ avatar_url="URL of the user's avatar image.",+ ),+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/harvest/harvest.py b/products/warehouse_sources/backend/temporal/data_imports/sources/harvest/harvest.pynew file mode 100644index 000000000000..79f941dc370e--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/harvest/harvest.py@@ -0,0 +1,174 @@+import datetime+import dataclasses+from typing import Any, Optional++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.paginators import (+ JSONResponsePaginator,+)+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.common.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.harvest.settings import HARVEST_ENDPOINTS++# Harvest serves every account from one global host - there are no regional or per-tenant+# subdomains, so the account is identified by the Harvest-Account-Id header instead.+HARVEST_API_HOST = "api.harvestapp.com"+HARVEST_BASE_URL = f"https://{HARVEST_API_HOST}"++# Harvest rejects requests without a descriptive User-Agent with a 400.+HARVEST_USER_AGENT = "PostHog (https://posthog.com)"++# Connect/read timeout per request, so a stalled response can't hold an import worker forever.+REQUEST_TIMEOUT = (10.0, 60.0)+++class HarvestResumeConfig:+ # Absolute URL of the next page, taken from the response's `links.next`. Harvest's own+ # docs tell integrators to follow that link rather than rebuild page/cursor params, since+ # it picks whichever pagination style is cheapest for the endpoint.+ next_url: str+++def _to_iso8601(value: Any) -> Optional[str]:+ """Render an incremental watermark as the ISO 8601 string `updated_since` expects.++ The pipeline hands back whatever the Delta table stored for the cursor column, which for a+ DateTime incremental field is a `datetime` but may arrive as an already-formatted string.+ `None` (a first sync) stays `None` so `requests` drops the param entirely.+ """+ if value is None:+ return None+ if isinstance(value, datetime.datetime):+ # A naive watermark can't be shifted with astimezone(); treat it as UTC, like the+ # other sources do, so incremental sync never crashes on a tz-less stored cursor.+ utc = value.replace(tzinfo=datetime.UTC) if value.tzinfo is None else value.astimezone(datetime.UTC)+ return utc.strftime("%Y-%m-%dT%H:%M:%SZ")+ if isinstance(value, datetime.date):+ return value.isoformat()+ return str(value)+++def _build_headers(account_id: str) -> dict[str, str]:+ # The access token rides the framework's bearer auth so its value is redacted from logs;+ # only the non-secret identification headers are set here. A token can reach several+ # Harvest accounts, so the account id header is mandatory on every request.+ return {+ "Harvest-Account-Id": account_id,+ "User-Agent": HARVEST_USER_AGENT,+ "Accept": "application/json",+ }+++def _build_params(endpoint: str, should_use_incremental_field: bool) -> dict[str, Any]:+ config = HARVEST_ENDPOINTS[endpoint]+ params: dict[str, Any] = {"per_page": config.page_size}+ if should_use_incremental_field and config.supports_updated_since:+ params["updated_since"] = {+ "type": "incremental",+ "cursor_path": "updated_at",+ "convert": _to_iso8601,+ }+ return params+++def harvest_source(+ account_id: str,+ access_token: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[HarvestResumeConfig],+ api_version: str,+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = HARVEST_ENDPOINTS[endpoint]+ use_incremental = should_use_incremental_field and config.supports_updated_since++ rest_config: RESTAPIConfig = {+ "client": {+ "base_url": f"{HARVEST_BASE_URL}/{api_version}",+ "headers": _build_headers(account_id),+ "auth": {"type": "bearer", "token": access_token},+ # Harvest returns a self-contained absolute next-page URL, which already carries+ # `per_page` and `updated_since`, so the filter survives every page.+ "paginator": JSONResponsePaginator(next_url_path="links.next"),+ # Pagination and resume follow URLs supplied by the response body, so pin them to+ # the API host and refuse redirects - a tampered link must not carry the bearer+ # token somewhere else.+ "allowed_hosts": [HARVEST_API_HOST],+ "allow_redirects": False,+ "request_timeout": REQUEST_TIMEOUT,+ },+ "resources": [+ {+ "name": endpoint,+ "endpoint": {+ "path": config.path,+ "data_selector": config.data_key,+ # A missing envelope key means the response shape changed; fail loud+ # rather than silently syncing zero rows.+ "data_selector_required": True,+ "params": _build_params(endpoint, should_use_incremental_field),+ },+ }+ ],+ }++ initial_paginator_state: Optional[dict[str, Any]] = None+ if resumable_source_manager.can_resume():+ resume = resumable_source_manager.load_state()+ if resume is not None:+ initial_paginator_state = {"next_url": resume.next_url}++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ # Persist only while a next page remains; saved AFTER a page is yielded so a crash+ # re-yields the last page (merge dedupes on the primary key) rather than skipping it.+ if state and state.get("next_url"):+ resumable_source_manager.save_state(HarvestResumeConfig(next_url=str(state["next_url"])))++ resource = rest_api_resource(+ rest_config,+ team_id,+ job_id,+ db_incremental_field_last_value if use_incremental else None,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )++ return SourceResponse(+ name=endpoint,+ items=lambda: resource,+ primary_keys=config.primary_keys,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="month" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ # Harvest orders list responses by a domain date (spent_date, creation date), newest+ # first, and offers no sort parameter - so rows never arrive ordered by `updated_at`.+ # "desc" keeps the pipeline from checkpointing the watermark mid-sync, which would+ # skip rows an interrupted run had not reached yet.+ sort_mode="desc",+ )+++def validate_credentials(account_id: str, access_token: str, api_version: str) -> tuple[bool, Optional[int]]:+ """Probe the authenticated-user endpoint to confirm the token and account id are genuine.++ `/users/me` is readable by every Harvest role, so it validates the credential without+ also requiring the admin access that listing users needs.+ """+ return validate_via_probe(+ lambda: make_tracked_session(redact_values=(access_token,)),+ f"{HARVEST_BASE_URL}/{api_version}/users/me",+ headers={"Authorization": f"Bearer {access_token}", **_build_headers(account_id)},+ timeout=REQUEST_TIMEOUT[0],+ allow_redirects=False,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/harvest/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/harvest/settings.pynew file mode 100644index 000000000000..476604772b24--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/harvest/settings.py@@ -0,0 +1,146 @@+from dataclasses import dataclass, field+from typing import Optional++from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field+from products.warehouse_sources.backend.types import IncrementalField++# Harvest exposes exactly one generally-available API version, addressed by the `/v2` path+# segment on a single global host. The base URL below is what the transport actually calls.+HARVEST_API_VERSION = "v2"+HARVEST_SUPPORTED_VERSIONS = (HARVEST_API_VERSION,)+++@dataclass(frozen=True)+class HarvestEndpointConfig:+ name: str # schema name shown to the user (matches the warehouse table)+ path: str # API path relative to the versioned base URL, e.g. "clients"+ data_key: str # key in the JSON response body holding the list of rows+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ # Rows per page. Harvest caps `per_page` at 2000 and rejects anything larger with a 422.+ # Endpoints whose rows embed a `line_items` array use a smaller page so one page stays a+ # reasonable size in memory.+ page_size: int = 1000+ # `updated_since` is Harvest's server-side "modified after" filter. The handful of+ # endpoints that don't accept it are full refresh only.+ supports_updated_since: bool = True+ # Stable creation-time field used for datetime partitioning. Never `updated_at`, which+ # would rewrite partitions on every sync. Left None for small lookup tables where+ # partitioning only adds overhead.+ partition_key: Optional[str] = None+ description: Optional[str] = None+++HARVEST_ENDPOINTS: dict[str, HarvestEndpointConfig] = {+ "clients": HarvestEndpointConfig(+ name="clients",+ path="clients",+ data_key="clients",+ description="Clients you track time and bill against.",+ ),+ "contacts": HarvestEndpointConfig(+ name="contacts",+ path="contacts",+ data_key="contacts",+ description="Contact people belonging to a client.",+ ),+ "estimate_item_categories": HarvestEndpointConfig(+ name="estimate_item_categories",+ path="estimate_item_categories",+ data_key="estimate_item_categories",+ description="Categories available for estimate line items.",+ ),+ "estimates": HarvestEndpointConfig(+ name="estimates",+ path="estimates",+ data_key="estimates",+ page_size=100,+ partition_key="created_at",+ description="Estimates sent to clients, including their line items.",+ ),+ "expense_categories": HarvestEndpointConfig(+ name="expense_categories",+ path="expense_categories",+ data_key="expense_categories",+ description="Categories expenses can be filed under.",+ ),+ "expenses": HarvestEndpointConfig(+ name="expenses",+ path="expenses",+ data_key="expenses",+ partition_key="created_at",+ description="Expenses logged against projects.",+ ),+ "invoice_item_categories": HarvestEndpointConfig(+ name="invoice_item_categories",+ path="invoice_item_categories",+ data_key="invoice_item_categories",+ description="Categories available for invoice line items.",+ ),+ "invoices": HarvestEndpointConfig(+ name="invoices",+ path="invoices",+ data_key="invoices",+ page_size=100,+ partition_key="created_at",+ description="Invoices issued to clients, including their line items.",+ ),+ "projects": HarvestEndpointConfig(+ name="projects",+ path="projects",+ data_key="projects",+ description="Projects time and expenses are tracked against.",+ ),+ "roles": HarvestEndpointConfig(+ name="roles",+ path="roles",+ data_key="roles",+ supports_updated_since=False,+ description="Roles and the users assigned to them. Full refresh only - the roles "+ "endpoint has no server-side modified-since filter.",+ ),+ "task_assignments": HarvestEndpointConfig(+ name="task_assignments",+ path="task_assignments",+ data_key="task_assignments",+ description="Tasks assigned to projects, with their billable rate and budget.",+ ),+ "tasks": HarvestEndpointConfig(+ name="tasks",+ path="tasks",+ data_key="tasks",+ description="Tasks that can be assigned to projects.",+ ),+ "time_entries": HarvestEndpointConfig(+ name="time_entries",+ path="time_entries",+ data_key="time_entries",+ partition_key="created_at",+ description="Tracked time, one row per entry.",+ ),+ "user_assignments": HarvestEndpointConfig(+ name="user_assignments",+ path="user_assignments",+ data_key="user_assignments",+ description="Users assigned to projects, with their rate and budget.",+ ),+ "users": HarvestEndpointConfig(+ name="users",+ path="users",+ data_key="users",+ description="People in the Harvest account.",+ ),+}++ENDPOINTS = tuple(HARVEST_ENDPOINTS.keys())++# Every Harvest object carries `updated_at`, and the list endpoints filter on it server-side+# via `updated_since`. Endpoints without that filter advertise no incremental field, so+# `build_endpoint_schemas` marks them full refresh only.+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: [incremental_field("updated_at")] if config.supports_updated_since else []+ for name, config in HARVEST_ENDPOINTS.items()+}++DESCRIPTIONS: dict[str, str] = {+ name: config.description for name, config in HARVEST_ENDPOINTS.items() if config.description is not None+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/harvest/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/harvest/source.pyindex 3a59ce39b75c..031324a85d9c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/harvest/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/harvest/source.py@@ -1,32 +1,152 @@-from typing import cast+from typing import Optional, castfrom 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, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.harvest import (HarvestSourceConfig,)+from products.warehouse_sources.backend.temporal.data_imports.sources.harvest.harvest import (+ HarvestResumeConfig,+ harvest_source,+ validate_credentials as validate_harvest_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.harvest.settings import (+ DESCRIPTIONS,+ ENDPOINTS,+ HARVEST_API_VERSION,+ HARVEST_SUPPORTED_VERSIONS,+ INCREMENTAL_FIELDS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class HarvestSource(SimpleSource[HarvestSourceConfig]):+class HarvestSource(ResumableSource[HarvestSourceConfig, HarvestResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+ supported_versions = HARVEST_SUPPORTED_VERSIONS+ default_version = HARVEST_API_VERSION+ api_docs_url = "https://help.getharvest.com/api-v2/"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.HARVEST+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url: https://api.harvestapp.com": "Your Harvest access token or account ID is invalid. Create a new personal access token in Harvest, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.harvestapp.com": "Your Harvest user does not have permission to read this data. Some tables need an administrator or manager role, so check the user's permissions and reconnect.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.harvest.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: HarvestSourceConfig,+ 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, descriptions=DESCRIPTIONS)++ def validate_credentials(+ self,+ config: HarvestSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ ok, status = validate_harvest_credentials(+ config.account_id, config.access_token, self.resolve_api_version(api_version)+ )+ if ok:+ return True, None+ if status is None:+ return False, "Could not reach Harvest to validate the credentials. Check your connection and try again."+ if status == 403:+ return (+ False,+ "This Harvest user does not have permission to read this data. Check the user's role and reconnect.",+ )+ return False, "Invalid Harvest account ID or access token"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[HarvestResumeConfig]:+ return ResumableSourceManager[HarvestResumeConfig](inputs, HarvestResumeConfig)++ def source_for_pipeline(+ self,+ config: HarvestSourceConfig,+ resumable_source_manager: ResumableSourceManager[HarvestResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return harvest_source(+ account_id=config.account_id,+ access_token=config.access_token,+ endpoint=inputs.schema_name,+ team_id=inputs.team_id,+ job_id=inputs.job_id,+ resumable_source_manager=resumable_source_manager,+ api_version=self.resolve_api_version(inputs.api_version),+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value,+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.HARVEST,category=DataWarehouseSourceCategory.FINANCE___ACCOUNTING,label="Harvest",+ releaseStatus=ReleaseStatus.ALPHA,+ keywords=["time tracking", "timesheets", "invoicing"],+ caption="""Enter your Harvest account ID and a personal access token to sync your time tracking and invoicing data into the PostHog Data warehouse.++Create a token at [id.getharvest.com/developers](https://id.getharvest.com/developers), which shows the account ID alongside it. The token inherits the permissions of the user who created it, so connect a user who can see the data you want to sync. Listing users and roles needs an administrator.""",iconPath="/static/services/harvest.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/harvest",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="account_id",+ label="Account ID",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="1234567",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="access_token",+ label="Personal access token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/harvest/tests/test_harvest.py b/products/warehouse_sources/backend/temporal/data_imports/sources/harvest/tests/test_harvest.pynew file mode 100644index 000000000000..ea409a756f4a--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/harvest/tests/test_harvest.py@@ -0,0 +1,299 @@+import json+import datetime+from collections.abc import Iterable+from typing import Any, cast++import pytest+from unittest import mock++from parameterized import parameterized+from requests import Response++from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import BearerTokenAuth+from products.warehouse_sources.backend.temporal.data_imports.sources.harvest.harvest import (+ HARVEST_API_HOST,+ HARVEST_USER_AGENT,+ HarvestResumeConfig,+ _to_iso8601,+ harvest_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.harvest.settings import (+ ENDPOINTS,+ HARVEST_ENDPOINTS,+)++# 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 harvest module.+HARVEST_SESSION_PATCH = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.harvest.harvest.make_tracked_session"+)+++def _page(+ rows: list[dict[str, Any]] | None,+ *,+ data_key: str = "time_entries",+ next_url: str | None = None,+ drop_key: bool = False,+) -> Response:+ body: dict[str, Any] = {"links": {"next": next_url}}+ if not drop_key:+ body[data_key] = rows or []+ response = Response()+ response.status_code = 200+ response._content = json.dumps(body).encode()+ return response+++def _make_manager(resume_state: HarvestResumeConfig | None = 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]) -> tuple[list[dict[str, Any]], list[str], list[Any]]:+ """Wire a mock session, snapshotting params/url/auth AT SEND TIME.++ ``request.params`` is one dict mutated in place across pages, so reading it after the run+ only shows the final state.+ """+ session.headers = {}+ params: list[dict[str, Any]] = []+ urls: list[str] = []+ auths: list[Any] = []++ def _prepare(request: Any) -> mock.MagicMock:+ params.append(dict(request.params or {}))+ urls.append(request.url)+ auths.append(request.auth)+ # The client host-pins on the prepared URL, so it has to be a real string.+ prepared = mock.MagicMock()+ prepared.url = request.url+ return prepared++ session.prepare_request.side_effect = _prepare+ session.send.side_effect = responses+ return params, urls, auths+++def _rows(source_response: Any) -> list[dict[str, Any]]:+ return [row for page in cast("Iterable[Any]", source_response.items()) for row in page]+++def _source(+ endpoint: str = "time_entries",+ manager: mock.MagicMock | None = None,+ *,+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Any:+ return harvest_source(+ account_id="123456",+ access_token="pat-secret",+ endpoint=endpoint,+ team_id=1,+ job_id="job-1",+ resumable_source_manager=manager if manager is not None else _make_manager(),+ api_version="v2",+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ )+++class TestHarvestTransport:+ @parameterized.expand(+ [+ ("none", None, None),+ ("aware_datetime", datetime.datetime(2026, 5, 4, 9, 30, tzinfo=datetime.UTC), "2026-05-04T09:30:00Z"),+ ("naive_datetime", datetime.datetime(2026, 5, 4, 9, 30), "2026-05-04T09:30:00Z"),+ (+ "offset_datetime",+ datetime.datetime(2026, 5, 4, 9, 30, tzinfo=datetime.timezone(datetime.timedelta(hours=2))),+ "2026-05-04T07:30:00Z",+ ),+ ("date", datetime.date(2026, 5, 4), "2026-05-04"),+ ("string_passthrough", "2026-05-04T09:30:00Z", "2026-05-04T09:30:00Z"),+ ]+ )+ def test_to_iso8601(self, _name: str, value: Any, expected: str | None) -> None:+ # `updated_since` only filters when it receives ISO 8601; a naive repr would be ignored+ # or rejected, silently turning an incremental sync into a full one.+ assert _to_iso8601(value) == expected++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_account_and_user_agent_headers_and_bearer_auth(self, MockSession: mock.MagicMock) -> None:+ session = MockSession.return_value+ _params, _urls, auths = _wire(session, [_page([{"id": 1}])])++ _rows(_source())++ # A token can reach several accounts, so Harvest 401s without the account header, and+ # 400s without a descriptive User-Agent.+ assert session.headers["Harvest-Account-Id"] == "123456"+ assert session.headers["User-Agent"] == HARVEST_USER_AGENT+ auth = auths[0]+ assert isinstance(auth, BearerTokenAuth)+ assert auth.token == "pat-secret"++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_follows_links_next_across_pages(self, MockSession: mock.MagicMock) -> None:+ session = MockSession.return_value+ next_url = f"https://{HARVEST_API_HOST}/v2/time_entries?cursor=abc&per_page=1000"+ params, urls, _auths = _wire(+ session,+ [+ _page([{"id": 1}], next_url=next_url),+ _page([{"id": 2}]),+ ],+ )++ rows = _rows(_source())++ assert [r["id"] for r in rows] == [1, 2]+ # The next link is self-contained, so the original params must not be re-appended.+ assert urls[1] == next_url+ assert params[1] == {}++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_saves_resume_state_only_while_a_next_page_remains(self, MockSession: mock.MagicMock) -> None:+ session = MockSession.return_value+ next_url = f"https://{HARVEST_API_HOST}/v2/time_entries?cursor=abc"+ _wire(session, [_page([{"id": 1}], next_url=next_url), _page([{"id": 2}])])++ manager = _make_manager()+ _rows(_source(manager=manager))++ manager.save_state.assert_called_once_with(HarvestResumeConfig(next_url=next_url))++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_resumes_from_saved_next_url(self, MockSession: mock.MagicMock) -> None:+ session = MockSession.return_value+ saved = f"https://{HARVEST_API_HOST}/v2/time_entries?cursor=xyz"+ _params, urls, _auths = _wire(session, [_page([{"id": 3}])])++ rows = _rows(_source(manager=_make_manager(HarvestResumeConfig(next_url=saved))))++ # Picks up at the saved page rather than restarting at the first one.+ assert urls[0] == saved+ assert [r["id"] for r in rows] == [3]++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_off_host_next_link_is_rejected(self, MockSession: mock.MagicMock) -> None:+ session = MockSession.return_value+ _wire(session, [_page([{"id": 1}], next_url="https://evil.example.com/v2/time_entries")])++ # Following a spoofed next link would replay the bearer token off-host.+ with pytest.raises(ValueError, match="disallowed host"):+ _rows(_source())++ @parameterized.expand(+ [+ ("first_sync", True, None, None),+ ("with_watermark", True, datetime.datetime(2026, 5, 4, 9, 30, tzinfo=datetime.UTC), "2026-05-04T09:30:00Z"),+ ("full_refresh", False, datetime.datetime(2026, 5, 4, 9, 30, tzinfo=datetime.UTC), None),+ ]+ )+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_updated_since_is_sent_only_for_incremental_syncs(+ self, _name: str, incremental: bool, last_value: Any, expected: str | None, MockSession: mock.MagicMock+ ) -> None:+ session = MockSession.return_value+ params, _urls, _auths = _wire(session, [_page([{"id": 1}])])++ _rows(+ _source(+ should_use_incremental_field=incremental,+ db_incremental_field_last_value=last_value,+ )+ )++ assert params[0].get("updated_since") == expected+ assert params[0]["per_page"] == HARVEST_ENDPOINTS["time_entries"].page_size++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_endpoint_without_updated_since_never_sends_the_filter(self, MockSession: mock.MagicMock) -> None:+ session = MockSession.return_value+ params, _urls, _auths = _wire(session, [_page([{"id": 1}], data_key="roles")])++ # Roles has no server-side modified-since filter; sending one would be ignored at best.+ _rows(+ _source(+ "roles",+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime.datetime(2026, 5, 4, tzinfo=datetime.UTC),+ )+ )++ assert "updated_since" not in params[0]++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_missing_envelope_key_fails_loud(self, MockSession: mock.MagicMock) -> None:+ session = MockSession.return_value+ _wire(session, [_page(None, drop_key=True)])++ # A changed response shape must fail rather than silently sync zero rows.+ with pytest.raises(Exception, match="time_entries"):+ _rows(_source())++ @parameterized.expand(ENDPOINTS)+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_every_endpoint_reads_its_own_envelope_and_path(self, endpoint: str, MockSession: mock.MagicMock) -> None:+ config = HARVEST_ENDPOINTS[endpoint]+ session = MockSession.return_value+ _params, urls, _auths = _wire(session, [_page([{"id": 1}], data_key=config.data_key)])++ response = _source(endpoint)+ rows = _rows(response)++ # A wrong path 404s; a wrong envelope key yields zero rows.+ assert urls[0].startswith(f"https://{HARVEST_API_HOST}/v2/{config.path}")+ assert [r["id"] for r in rows] == [1]+ assert response.name == endpoint+ assert response.primary_keys == config.primary_keys++ @parameterized.expand([("time_entries", "created_at"), ("invoices", "created_at"), ("roles", None)])+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_partitioning_matches_the_endpoint_config(+ self, endpoint: str, partition_key: str | None, MockSession: mock.MagicMock+ ) -> None:+ response = _source(endpoint)+ assert response.partition_keys == ([partition_key] if partition_key else None)+ assert response.partition_mode == ("datetime" if partition_key else None)++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_sort_mode_is_desc(self, MockSession: mock.MagicMock) -> None:+ # Harvest lists newest-first by a domain date and exposes no sort param, so rows never+ # arrive ordered by updated_at. "asc" would checkpoint the watermark mid-sync and skip+ # rows an interrupted run had not reached.+ assert _source().sort_mode == "desc"+++class TestValidateCredentials:+ @parameterized.expand([("ok", 200, True), ("unauthorized", 401, False), ("forbidden", 403, False)])+ @mock.patch(HARVEST_SESSION_PATCH)+ def test_status_mapping(self, _name: str, status: int, expected_ok: bool, mock_session: mock.MagicMock) -> None:+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=status)+ ok, reported = validate_credentials("123456", "pat-secret", "v2")+ assert ok is expected_ok+ assert reported == status++ @mock.patch(HARVEST_SESSION_PATCH)+ def test_transport_errors_do_not_raise(self, mock_session: mock.MagicMock) -> None:+ mock_session.return_value.get.side_effect = Exception("boom")+ assert validate_credentials("123456", "pat-secret", "v2") == (False, None)++ @mock.patch(HARVEST_SESSION_PATCH)+ def test_probe_targets_users_me_with_both_credentials(self, mock_session: mock.MagicMock) -> None:+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=200)+ validate_credentials("123456", "pat-secret", "v2")++ args, kwargs = mock_session.return_value.get.call_args+ # /users/me is readable by every role, unlike listing users, which needs an admin.+ assert args[0] == f"https://{HARVEST_API_HOST}/v2/users/me"+ assert kwargs["headers"]["Authorization"] == "Bearer pat-secret"+ assert kwargs["headers"]["Harvest-Account-Id"] == "123456"+ # Custom credential headers are not stripped by requests on a cross-origin redirect.+ assert kwargs["allow_redirects"] is Falsediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/harvest/tests/test_harvest_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/harvest/tests/test_harvest_source.pynew file mode 100644index 000000000000..e6cffaa0a1d7--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/harvest/tests/test_harvest_source.py@@ -0,0 +1,149 @@+from unittest.mock import MagicMock, patch++from parameterized import parameterized++from posthog.schema import DataWarehouseSourceCategory, ReleaseStatus, SourceFieldInputConfig++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.harvest import (+ HarvestSourceConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.harvest.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.harvest.harvest import HarvestResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.harvest.settings import (+ ENDPOINTS,+ HARVEST_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.harvest.source import HarvestSource+from products.warehouse_sources.backend.types import ExternalDataSourceType++VALIDATE_PATCH = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.harvest.source.validate_harvest_credentials"+)+SOURCE_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.harvest.source.harvest_source"+++def _config() -> HarvestSourceConfig:+ return HarvestSourceConfig(account_id="123456", access_token="pat-secret")+++class TestHarvestSource:+ def test_source_type(self) -> None:+ assert HarvestSource().source_type == ExternalDataSourceType.HARVEST++ def test_source_config_shape(self) -> None:+ config = HarvestSource().get_source_config+ assert config.category == DataWarehouseSourceCategory.FINANCE___ACCOUNTING+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/harvest"+ assert {f.name for f in config.fields} == {"account_id", "access_token"}++ @parameterized.expand([("account_id", False), ("access_token", True)])+ def test_only_the_token_field_is_secret(self, field_name: str, expected_secret: bool) -> None:+ # A non-secret token field would be echoed back to the frontend in plain text.+ field = next(f for f in HarvestSource().get_source_config.fields if f.name == field_name)+ assert isinstance(field, SourceFieldInputConfig)+ assert field.secret is expected_secret+ assert field.required is True++ def test_api_version_pins_the_path_the_code_calls(self) -> None:+ assert HarvestSource.supported_versions == ("v2",)+ assert HarvestSource.default_version == "v2"++ def test_get_schemas_lists_every_endpoint(self) -> None:+ schemas = HarvestSource().get_schemas(_config(), team_id=1)+ assert {s.name for s in schemas} == set(ENDPOINTS)++ @parameterized.expand([("time_entries", True), ("invoices", True), ("roles", False)])+ def test_incremental_support_tracks_the_updated_since_filter(self, name: str, expected: bool) -> None:+ # Only endpoints with a server-side `updated_since` filter may advertise incremental+ # sync; roles has none, so it must stay full refresh.+ schema = next(s for s in HarvestSource().get_schemas(_config(), team_id=1) if s.name == name)+ assert schema.supports_incremental is expected+ assert [f["field"] for f in schema.incremental_fields] == (["updated_at"] if expected else [])++ def test_get_schemas_filters_by_names(self) -> None:+ schemas = HarvestSource().get_schemas(_config(), team_id=1, names=["time_entries"])+ assert [s.name for s in schemas] == ["time_entries"]++ def test_documented_tables_render_without_credentials(self) -> None:+ # Static catalog -> the public docs Supported tables section renders with no connection.+ assert HarvestSource.lists_tables_without_credentials is True+ tables = HarvestSource().get_documented_tables()+ assert {t["name"] for t in tables} == set(ENDPOINTS)+ assert all(t["description"] for t in tables)++ def test_canonical_descriptions_cover_every_endpoint(self) -> None:+ # Entries keyed off a stale endpoint name silently fall back to LLM enrichment.+ assert set(CANONICAL_DESCRIPTIONS) == set(ENDPOINTS)++ @parameterized.expand(+ [+ ("valid", True, None, True, None),+ ("invalid", False, 401, False, "Invalid Harvest account ID"),+ ("no_scope", False, 403, False, "does not have permission"),+ ("unreachable", False, None, False, "Could not reach Harvest"),+ ]+ )+ def test_validate_credentials(+ self, _name: str, probe_ok: bool, status: int | None, expected_ok: bool, expected_error: str | None+ ) -> None:+ # Distinct messages keep a 403 (missing permission) and an unreachable probe from both+ # reading as "bad credentials", which would send the user chasing the wrong fix.+ with patch(VALIDATE_PATCH, return_value=(probe_ok, status)):+ ok, error = HarvestSource().validate_credentials(_config(), team_id=1)+ assert ok is expected_ok+ if expected_error is None:+ assert error is None+ else:+ assert error is not None and expected_error in error++ def test_non_retryable_errors_cover_auth_and_permissions(self) -> None:+ errors = HarvestSource().get_non_retryable_errors()+ assert any("401" in key for key in errors)+ assert any("403" in key for key in errors)++ def test_get_resumable_source_manager_binds_resume_config(self) -> None:+ inputs = MagicMock()+ inputs.logger = MagicMock()+ manager = HarvestSource().get_resumable_source_manager(inputs)+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is HarvestResumeConfig++ @parameterized.expand([("unpinned", None, "v2"), ("pinned", "v2", "v2")])+ def test_source_for_pipeline_plumbs_config_and_version(self, _name: str, pin: str | None, expected: str) -> None:+ inputs = MagicMock()+ inputs.schema_name = "time_entries"+ inputs.team_id = 7+ inputs.job_id = "job-1"+ inputs.api_version = pin+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"+ manager = MagicMock()++ with patch(SOURCE_PATCH) as mock_source:+ HarvestSource().source_for_pipeline(_config(), manager, inputs)++ kwargs = mock_source.call_args.kwargs+ assert kwargs["account_id"] == "123456"+ assert kwargs["access_token"] == "pat-secret"+ assert kwargs["endpoint"] == "time_entries"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["api_version"] == expected+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00Z"++ def test_partition_keys_are_creation_time_only(self) -> None:+ # An `updated_at` partition key would rewrite every partition on each sync.+ partition_keys = {c.partition_key for c in HARVEST_ENDPOINTS.values() if c.partition_key}+ assert partition_keys == {"created_at"}++ def test_page_size_stays_within_the_api_cap(self) -> None:+ # Harvest rejects per_page above 2000 with a 422.+ assert all(0 < c.page_size <= 2000 for c in HARVEST_ENDPOINTS.values())++ def test_source_config_is_visible_to_users(self) -> None:+ # A truthy unreleasedSource filters the connector out of the frontend entirely.+ assert not HarvestSource().get_source_config.unreleasedSource