: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 Propertyware import source (#84431)
Tom Owers114b18421711
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/propertyware.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/propertyware.pyindex 81babccbab18..fe2ae0c0dfc6 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/propertyware.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/propertyware.py@@ -6,4 +6,6 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass PropertywareSourceConfig(config.Config):- pass+ client_id: str+ client_secret: str+ system_id: strdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/propertyware/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/propertyware/canonical_descriptions.pynew file mode 100644index 000000000000..283b8d7b5aeb--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/propertyware/canonical_descriptions.py@@ -0,0 +1,264 @@+"""Canonical, documentation-sourced descriptions for Propertyware endpoints and columns.++Sourced from the official Propertyware OpenAPI 3.0 spec. Keyed by the resource names in+`settings.py` `ENDPOINT_PATHS`, which match the `ExternalDataSchema.name` of a synced+Propertyware table. Columns absent here fall back to LLM enrichment.+"""++from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++_API_DOCS_URL = "https://app.propertyware.com/apidocs/index.html"++# Audit fields shared by every Propertyware object.+_COMMON_COLUMNS = {+ "id": "Unique identifier.",+ "createdBy": "User who created the record.",+ "createdDateTime": "Date and time the record was created (UTC).",+ "lastModifiedBy": "User who last modified the record.",+ "lastModifiedDateTime": "Date and time the record was last modified (UTC).",+}+++def _columns(**overrides: str) -> dict[str, str]:+ return {**_COMMON_COLUMNS, **overrides}+++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "Portfolios": {+ "description": "A group of properties (buildings) managed together, typically for one owner.",+ "docs_url": _API_DOCS_URL,+ "columns": _columns(+ name="Portfolio name.",+ abbreviation="Abbreviated name assigned to the portfolio.",+ active="Whether the portfolio is active or inactive.",+ cashAccrual="Cash or accrual accounting basis.",+ closingDate="Date when the accounting period for the portfolio will close.",+ defaultBankAccountID="ID of the portfolio's default bank account.",+ targetOperatingReserve="Minimum balance to be maintained within the portfolio at all times.",+ ),+ },+ "Buildings": {+ "description": "A physical property (single-family home or multi-unit building) within a portfolio.",+ "docs_url": _API_DOCS_URL,+ "columns": _columns(+ name="Name of the property.",+ portfolioID="ID of the portfolio associated with this property.",+ active="Whether the property is active or inactive.",+ status="Property status (occupied/vacant).",+ propertyType="Type of property.",+ multiUnit="Whether the building is multi-family or single-family.",+ numberOfBedrooms="Number of bedrooms in the property.",+ numberOfBathrooms="Number of bathrooms in the property.",+ totalArea="Property total area.",+ targetRent="Property target rent.",+ yearBuilt="Property built year.",+ rentable="Whether the property is available for rent.",+ ),+ },+ "Units": {+ "description": "An individually leasable unit within a building.",+ "docs_url": _API_DOCS_URL,+ "columns": _columns(+ name="Name of the unit.",+ buildingID="ID of the building associated with this unit.",+ portfolioID="ID of the portfolio associated with this property.",+ leaseID="Related lease ID.",+ status="Property status (occupied/vacant).",+ targetRent="Property target rent.",+ numberOfBedrooms="Number of bedrooms in the property.",+ numberOfBathrooms="Number of bathrooms in the property.",+ rentable="Whether the property is available for rent.",+ ),+ },+ "Leases": {+ "description": "A lease agreement between one or more tenants and a portfolio owner for a unit or building.",+ "docs_url": _API_DOCS_URL,+ "columns": _columns(+ leaseName="Lease name.",+ portfolioID="ID of the portfolio associated with this lease.",+ buildingID="ID of the building associated with this lease.",+ unitID="ID of the unit associated with this lease.",+ status="Lease's current status.",+ active="Whether the lease is active.",+ startDate="Start date of the lease term.",+ endDate="End date of the lease term.",+ moveInDate="Day that the tenant(s) moved into the property.",+ moveOutDate="Day that the tenant(s) vacated the property.",+ baseRent="Property base rent.",+ leaseBalance="Lease balance.",+ arBalance="Lease accounts receivable balance.",+ ),+ },+ "LeaseCharges": {+ "description": "A charge posted to a lease (rent, fees, or other billed amounts).",+ "docs_url": _API_DOCS_URL,+ "columns": _columns(+ leaseID="ID of the lease associated with this charge.",+ portfolioID="ID of the portfolio associated with this charge.",+ glAccountID="ID of the general ledger account associated with this charge.",+ amount="Charge amount.",+ amountDue="The amount due for the charge.",+ amountPaid="The amount paid for the charge.",+ date="Post date.",+ refNo="Reference number.",+ ),+ },+ "LeasePayments": {+ "description": "A payment applied against lease charges.",+ "docs_url": _API_DOCS_URL,+ "columns": _columns(+ leaseID="ID of the lease associated with this payment.",+ portfolioID="ID of the portfolio associated with this transaction.",+ contactID="ID of the contact associated with this payment.",+ glAccountID="General ledger account ID.",+ amount="Payment amount.",+ date="Post date.",+ depositDate="Date the payment was deposited.",+ paymentType="Payment type.",+ isDeposited="Whether the payment has been deposited.",+ refNo="Reference number.",+ ),+ },+ "LeaseAdjustments": {+ "description": "A manual adjustment posted to a lease's balance.",+ "docs_url": _API_DOCS_URL,+ "columns": _columns(+ leaseID="ID of the lease associated with this adjustment.",+ portfolioID="ID of the portfolio associated with this adjustment.",+ glAccountID="ID of the general ledger account associated with this adjustment.",+ amount="Adjustment amount.",+ date="Post date.",+ refNo="Reference number.",+ ),+ },+ "LeaseRefunds": {+ "description": "A refund issued from a lease's balance back to a tenant.",+ "docs_url": _API_DOCS_URL,+ "columns": _columns(+ leaseID="ID of the lease associated with the refund.",+ portfolioID="ID of the portfolio associated with the refund.",+ glAccountID="ID of the general ledger account associated with the refund.",+ destinationAccountID="ID of the bank account to send the refund from.",+ amount="Refund amount.",+ date="Post date.",+ payeePayer="Name of the payee.",+ refNo="Reference number.",+ ),+ },+ "Contacts": {+ "description": "A person record — tenant, owner, or other contact — in the account.",+ "docs_url": _API_DOCS_URL,+ "columns": _columns(+ firstName="First name.",+ lastName="Last name.",+ email="Email address.",+ company="Company where the contact is employed.",+ type="Contact type.",+ category="Contact category.",+ mobilePhone="Mobile phone.",+ namedOnLease="Whether the contact is named on a lease.",+ ),+ },+ "Prospects": {+ "description": "A prospective tenant who has expressed interest in leasing a property.",+ "docs_url": _API_DOCS_URL,+ "columns": _columns(+ portfolioID="ID of the portfolio associated with the prospect.",+ buildingID="ID of the building associated with the prospect.",+ unitID="ID of the unit associated with the prospect.",+ status="Prospect status.",+ type="Prospect type.",+ source="Prospect source.",+ moveInDate="Desired move-in date.",+ rent="Confirmed lease rent.",+ applicationFeePaid="Whether the application fee has been paid by the prospect.",+ ),+ },+ "Vendors": {+ "description": "A vendor or service provider paid for work performed on managed properties.",+ "docs_url": _API_DOCS_URL,+ "columns": _columns(+ name="Vendor name.",+ companyName="Name of the vendor's company.",+ type="The type of vendor.",+ active="Whether the vendor is active.",+ email="Email address.",+ phone="Phone number.",+ taxId="Tax identification number.",+ eligible1099="Whether the vendor is eligible for a 1099 form.",+ ),+ },+ "Bills": {+ "description": "A bill owed to a vendor, optionally tied to a work order.",+ "docs_url": _API_DOCS_URL,+ "columns": _columns(+ vendorID="The ID of the vendor related to the bill.",+ workOrderID="The ID of the work order associated with the bill.",+ markupGLAccountID="The ID of the markup/discount general ledger account associated with the bill.",+ amount="Bill amount.",+ billDate="Entry date.",+ dueDate="Due date.",+ paymentDate="Date the bill was paid.",+ credit="Whether the bill is a vendor credit.",+ refNo="Reference number.",+ ),+ },+ "BillPayments": {+ "description": "A payment made to a vendor against one or more bills.",+ "docs_url": _API_DOCS_URL,+ "columns": _columns(+ vendorID="ID of the vendor associated with this payment.",+ paymentAccountID="ID of the payment general ledger account.",+ amount="Payment amount.",+ paymentDate="Payment date.",+ paymentMethod="Payment method.",+ checkNumber="Payment check number.",+ ),+ },+ "WorkOrders": {+ "description": "A maintenance work order for a building or unit.",+ "docs_url": _API_DOCS_URL,+ "columns": _columns(+ portfolioID="ID of the portfolio associated with this work order.",+ buildingID="ID of the building associated with this work order.",+ unitID="ID of the unit associated with this work order.",+ status="Current status of the work order.",+ priority="Priority of the work order: low, medium, or high.",+ type="Classifies the work order (general, service request, turnover, inspection, estimate, etc).",+ category="Classifies the work order into a category.",+ description="Detailed description of the problem.",+ completedDate="Date on which the work was completed.",+ costEstimate="Estimated, actual, and invoiced cost of the work order.",+ ),+ },+ "Inspections": {+ "description": "A property inspection scheduled or completed for a lease or building.",+ "docs_url": _API_DOCS_URL,+ "columns": _columns(+ portfolioID="ID of the portfolio associated with this inspection.",+ buildingID="ID of the building associated with this inspection.",+ leaseID="ID of the lease associated with this inspection.",+ inspectorID="ID of the inspector.",+ status="Inspection status.",+ type="Inspection type.",+ scheduledDateAndTime="Date and time the inspection is/was scheduled to occur.",+ inspectedDateAndTime="Date and time the inspection occurred.",+ ),+ },+ "GLAccounts": {+ "description": "A general ledger account used for accounting entries across the account.",+ "docs_url": _API_DOCS_URL,+ "columns": _columns(+ name="Account name.",+ accountNumber="Account number.",+ accountCode="Account code.",+ accountType="Account type.",+ active="Whether the account is active.",+ description="Description of the account.",+ parentGLAccountId="Parent account ID.",+ rentAccount="Whether the account is a rent account.",+ ),+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/propertyware/propertyware.py b/products/warehouse_sources/backend/temporal/data_imports/sources/propertyware/propertyware.pynew file mode 100644index 000000000000..b527c154a10e--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/propertyware/propertyware.py@@ -0,0 +1,180 @@+from datetime import UTC, date, datetime+from typing import Any, Optional+from urllib.parse import urlencode++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.typing import Endpoint+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.propertyware.settings import (+ ENDPOINT_PATHS,+ INCREMENTAL_FIELD,+ PARTITION_KEY,+ PRIMARY_KEY,+)++BASE_URL = "https://api.propertyware.com/pw/api/rest/v1"+# Docs: default 100, max 500; a limit above 500 is clamped to 500 server-side, so requesting the+# max up front minimizes the number of pages.+PAGE_SIZE = 500+TOTAL_COUNT_HEADER = "X-Total-Count"+++@frozen+class PropertywareResumeConfig:+ offset: int+++class PropertywareAuth(AuthConfigBase):+ """Propertyware authenticates with three separate headers, not one.++ `x-propertyware-client-id` / `x-propertyware-client-secret` identify the API key pair and+ `x-propertyware-system-id` scopes it to one organization. The generic `api_key` auth type+ carries a single header, so all three are set here and reported for redaction — the tracked+ session's generic header-name scrubber doesn't know these connector-specific header names.+ """++ def __init__(self, client_id: str, client_secret: str, system_id: str) -> None:+ self.client_id = client_id+ self.client_secret = client_secret+ self.system_id = system_id++ def __call__(self, request: PreparedRequest) -> PreparedRequest:+ request.headers["x-propertyware-client-id"] = self.client_id+ request.headers["x-propertyware-client-secret"] = self.client_secret+ request.headers["x-propertyware-system-id"] = self.system_id+ return request++ def secret_values(self) -> tuple[str, ...]:+ return tuple(value for value in (self.client_id, self.client_secret, self.system_id) if value)+++def _format_pw_datetime(value: Any) -> str:+ """Format the incremental cursor as Propertyware's dateAndTime format.++ Docs specify `YYYY-MM-ddTHH:mm:ssXXX` (e.g. `2022-06-28T08:47:13Z`), always UTC.+ """+ if isinstance(value, datetime):+ dt = value if value.tzinfo is not None else value.replace(tzinfo=UTC)+ return dt.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")+ if isinstance(value, date):+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC).strftime("%Y-%m-%dT%H:%M:%SZ")+ return str(value)+++def propertyware_source(+ client_id: str,+ client_secret: str,+ system_id: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[PropertywareResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ endpoint_config: Endpoint = {+ "path": ENDPOINT_PATHS[endpoint],+ "paginator": OffsetPaginator(limit=PAGE_SIZE, total_header=TOTAL_COUNT_HEADER, total_path=None),+ # Propertyware list endpoints return a bare JSON array. A non-list 200 body (an error+ # envelope, an HTML gateway page) must fail loud instead of silently syncing 0 rows.+ "data_selector_required": True,+ "params": {"orderby": f"{INCREMENTAL_FIELD} asc"},+ }++ use_incremental = bool(should_use_incremental_field and db_incremental_field_last_value)+ if use_incremental:+ endpoint_config["incremental"] = {+ "start_param": "lastModifiedDateTimeStart",+ "convert": _format_pw_datetime,+ }++ rest_config: RESTAPIConfig = {+ "client": {+ "base_url": BASE_URL,+ "headers": {"Accept": "application/json"},+ "auth": PropertywareAuth(client_id=client_id, client_secret=client_secret, system_id=system_id),+ # Credentials travel in custom headers, not `Authorization` — `requests` won't strip+ # those on a cross-origin redirect, so pin every sync request to the Propertyware host+ # and refuse to follow a 3xx (mirrors the same guard on the validation probe below).+ "allowed_hosts": [],+ "allow_redirects": False,+ },+ "resources": [+ {+ "name": endpoint,+ "endpoint": endpoint_config,+ }+ ],+ }++ 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 = {"offset": resume.offset}++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ # Only persist when there's a next page to resume to; the Redis TTL handles cleanup on+ # completion. 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("offset") is not None:+ resumable_source_manager.save_state(PropertywareResumeConfig(offset=int(state["offset"])))++ 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=[PRIMARY_KEY],+ # We always request `orderby={INCREMENTAL_FIELD} asc`, so rows arrive in ascending order.+ sort_mode="asc",+ partition_count=1,+ partition_size=1,+ partition_mode="datetime",+ partition_format="week",+ partition_keys=[PARTITION_KEY],+ )+++def validate_credentials(client_id: str, client_secret: str, system_id: str, path: str = "/health") -> Optional[int]:+ """Return the status code of a cheap authenticated probe, or `None` on transport error.++ `/health` requires the same three headers as every other endpoint, so a genuine key set+ returns 200, a bad one 401, and one without access to the whole account 403.+ """+ url = f"{BASE_URL}{path}"+ _ok, status = validate_via_probe(+ lambda: make_tracked_session(redact_values=(client_id, client_secret, system_id)),+ url,+ auth=PropertywareAuth(client_id=client_id, client_secret=client_secret, system_id=system_id),+ # Credentials travel in custom headers, not `Authorization` — `requests` won't strip+ # those on a cross-origin redirect, so don't follow one.+ allow_redirects=False,+ )+ return status+++def endpoint_probe_path(endpoint: str) -> str:+ """Path (with query string) for a cheap single-row probe of one endpoint's access."""+ return f"{ENDPOINT_PATHS[endpoint]}?{urlencode({'limit': 1})}"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/propertyware/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/propertyware/settings.pynew file mode 100644index 000000000000..05eae3f9e4af--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/propertyware/settings.py@@ -0,0 +1,35 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field+from products.warehouse_sources.backend.types import IncrementalField++# Every Propertyware object carries a global `id` and a `lastModifiedDateTime` audit field+# (verified against the published OpenAPI schema), so pagination, incremental sync, and+# partitioning are uniform across every endpoint below.+PRIMARY_KEY = "id"+INCREMENTAL_FIELD = "lastModifiedDateTime"+# Stable creation timestamp for partitioning; unlike lastModifiedDateTime it never changes once set.+PARTITION_KEY = "createdDateTime"++ENDPOINT_PATHS: dict[str, str] = {+ "Portfolios": "/portfolios",+ "Buildings": "/buildings",+ "Units": "/units",+ "Leases": "/leases",+ "LeaseCharges": "/leases/charges",+ "LeasePayments": "/leases/payments",+ "LeaseAdjustments": "/leases/adjustments",+ "LeaseRefunds": "/leases/refunds",+ "Contacts": "/contacts",+ "Prospects": "/prospects",+ "Vendors": "/vendors",+ "Bills": "/bills",+ "BillPayments": "/bills/payments",+ "WorkOrders": "/workorders",+ "Inspections": "/inspections",+ "GLAccounts": "/accounting/glaccounts",+}++ENDPOINTS: tuple[str, ...] = tuple(ENDPOINT_PATHS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: [incremental_field(INCREMENTAL_FIELD)] for name in ENDPOINTS+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/propertyware/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/propertyware/source.pyindex ee8eb6b62569..8f2adb9b165b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/propertyware/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/propertyware/source.py@@ -1,21 +1,50 @@-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.propertyware import (PropertywareSourceConfig,)+from products.warehouse_sources.backend.temporal.data_imports.sources.propertyware.propertyware import (+ PropertywareResumeConfig,+ endpoint_probe_path,+ propertyware_source,+ validate_credentials as validate_propertyware_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.propertyware.settings import (+ ENDPOINT_PATHS,+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ PRIMARY_KEY,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class PropertywareSource(SimpleSource[PropertywareSourceConfig]):+class PropertywareSource(ResumableSource[PropertywareSourceConfig, PropertywareResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+ # Propertyware uses a single major version with no version token in the URL or headers+ # (docs: "Propertyware uses only a major version nomenclature to manage changes").+ api_docs_url = "https://app.propertyware.com/apidocs/index.html"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.PROPERTYWARE@@ -26,7 +55,112 @@ class PropertywareSource(SimpleSource[PropertywareSourceConfig]):name=SchemaExternalDataSourceType.PROPERTYWARE,category=DataWarehouseSourceCategory.FINANCE___ACCOUNTING,label="Propertyware (RealPage)",+ releaseStatus=ReleaseStatus.ALPHA,+ keywords=["property management", "rentals", "realpage"],+ caption="""Enter your Propertyware API credentials to sync property, lease, and accounting data into the PostHog Data warehouse.++Find your **client ID**, **client secret**, and **organization ID** in Propertyware under **Administration Setup > API Keys** (you'll need an administrator role to access this page). The client secret is shown only once when the key is created, so store it somewhere safe before closing the dialog.""",+ docsUrl="https://posthog.com/docs/cdp/sources/propertyware",iconPath="/static/services/propertyware.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="client_id",+ label="Client ID",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="client_secret",+ label="Client secret",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="system_id",+ label="Organization ID",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="",+ secret=False,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.propertyware.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": "Propertyware authentication failed. Check your client ID, client secret, and organization ID.",+ "403 Client Error": "This Propertyware API key doesn't have permission to access this data. Check the key's access in Administration Setup > API Keys.",+ }++ def get_schemas(+ self,+ config: PropertywareSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ schemas = build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)+ for schema in schemas:+ schema.detected_primary_keys = [PRIMARY_KEY]+ return schemas++ def validate_credentials(+ self,+ config: PropertywareSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ # A key may legitimately be restricted to specific Propertyware entities, so validating a+ # chosen schema probes that endpoint directly rather than the account-wide `/health` check.+ path = endpoint_probe_path(schema_name) if schema_name in ENDPOINT_PATHS else "/health"+ status = validate_propertyware_credentials(config.client_id, config.client_secret, config.system_id, path)++ if status is not None and 200 <= status < 300:+ return True, None+ # Accept 403 at source-create (schema_name is None) — users may only grant a key access+ # to some entities — and only reject it when validating a specific schema.+ if status == 403 and schema_name is None:+ return True, None+ if status in (401, 403):+ return False, "Invalid Propertyware credentials, or this API key doesn't have access to this data."+ return False, "Could not validate Propertyware credentials."++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[PropertywareResumeConfig]:+ return ResumableSourceManager[PropertywareResumeConfig](inputs, PropertywareResumeConfig)++ def source_for_pipeline(+ self,+ config: PropertywareSourceConfig,+ resumable_source_manager: ResumableSourceManager[PropertywareResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return propertyware_source(+ client_id=config.client_id,+ client_secret=config.client_secret,+ system_id=config.system_id,+ 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,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/propertyware/tests/test_propertyware.py b/products/warehouse_sources/backend/temporal/data_imports/sources/propertyware/tests/test_propertyware.pynew file mode 100644index 000000000000..7a3a0bf152c7--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/propertyware/tests/test_propertyware.py@@ -0,0 +1,266 @@+import json+from datetime import UTC, date, datetime+from typing import Any, Optional++import pytest+from unittest import mock++from requests import PreparedRequest, Response+from requests.structures import CaseInsensitiveDict++from products.warehouse_sources.backend.temporal.data_imports.sources.propertyware.propertyware import (+ PAGE_SIZE,+ PropertywareAuth,+ PropertywareResumeConfig,+ _format_pw_datetime,+ endpoint_probe_path,+ propertyware_source,+ validate_credentials,+)++# 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 propertyware module.+PROPERTYWARE_SESSION_PATCH = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.propertyware.propertyware.make_tracked_session"+)++_PINNED_URL = "https://api.propertyware.com/pw/api/rest/v1/portfolios"+++def _response(items: list[dict[str, Any]] | None, *, status: int = 200, raw: Optional[bytes] = None) -> Response:+ resp = Response()+ resp.status_code = status+ resp.url = _PINNED_URL+ resp.reason = "OK" if status < 400 else "Unauthorized"+ resp._content = raw if raw is not None else json.dumps(items or []).encode()+ return resp+++def _make_manager(resume_state: PropertywareResumeConfig | 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]) -> list[dict[str, Any]]:+ """Wire a mock session and return a list capturing each request's params AT SEND TIME."""+ session.headers = {}+ param_snapshots: list[dict[str, Any]] = []++ def _prepare(request: Any) -> mock.MagicMock:+ param_snapshots.append(dict(request.params or {}))+ return mock.MagicMock(url=_PINNED_URL)++ session.prepare_request.side_effect = _prepare+ session.send.side_effect = responses+ return param_snapshots+++def _rows(source_response) -> list[dict[str, Any]]:+ return [row for page in source_response.items() for row in page]+++def _source(manager: mock.MagicMock, **kwargs: Any):+ return propertyware_source(+ kwargs.pop("client_id", "cid"),+ kwargs.pop("client_secret", "secret"),+ kwargs.pop("system_id", "org-1"),+ kwargs.pop("endpoint", "Portfolios"),+ team_id=1,+ job_id="j",+ resumable_source_manager=manager,+ **kwargs,+ )+++class TestPropertywareAuth:+ def test_sets_all_three_headers(self) -> None:+ auth = PropertywareAuth(client_id="cid", client_secret="csecret", system_id="org-1")+ request = PreparedRequest()+ request.headers = CaseInsensitiveDict()+ auth(request)+ assert request.headers["x-propertyware-client-id"] == "cid"+ assert request.headers["x-propertyware-client-secret"] == "csecret"+ assert request.headers["x-propertyware-system-id"] == "org-1"++ def test_secret_values_redacts_all_three(self) -> None:+ auth = PropertywareAuth(client_id="cid", client_secret="csecret", system_id="org-1")+ assert set(auth.secret_values()) == {"cid", "csecret", "org-1"}++ def test_secret_values_omits_blank_fields(self) -> None:+ auth = PropertywareAuth(client_id="cid", client_secret="", system_id="")+ assert auth.secret_values() == ("cid",)+++class TestFormatPwDatetime:+ def test_formats_aware_datetime(self) -> None:+ assert _format_pw_datetime(datetime(2022, 6, 28, 8, 47, 13, tzinfo=UTC)) == "2022-06-28T08:47:13Z"++ def test_naive_datetime_treated_as_utc(self) -> None:+ assert _format_pw_datetime(datetime(2020, 1, 2, 3, 4, 5)) == "2020-01-02T03:04:05Z"++ def test_date_formats_at_midnight(self) -> None:+ assert _format_pw_datetime(date(2021, 6, 7)) == "2021-06-07T00:00:00Z"++ def test_string_passes_through(self) -> None:+ assert _format_pw_datetime("2022-03-04T05:06:07Z") == "2022-03-04T05:06:07Z"+++class TestEndpointProbePath:+ def test_builds_limit_one_query(self) -> None:+ assert endpoint_probe_path("Portfolios") == "/portfolios?limit=1"+ assert endpoint_probe_path("LeaseCharges") == "/leases/charges?limit=1"+++class TestPagination:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_paginates_offset_and_saves_state_after_full_page(self, MockSession) -> None:+ session = MockSession.return_value+ full_page = [{"id": i} for i in range(PAGE_SIZE)]+ params = _wire(session, [_response(full_page), _response([{"id": 9999}])])++ manager = _make_manager()+ rows = _rows(_source(manager))++ assert rows[-1] == {"id": 9999}+ assert len(rows) == PAGE_SIZE + 1+ assert params[0]["offset"] == 0+ assert params[0]["limit"] == PAGE_SIZE+ assert params[1]["offset"] == PAGE_SIZE+ manager.save_state.assert_called_once_with(PropertywareResumeConfig(offset=PAGE_SIZE))++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_sync_requests_pin_host_and_refuse_redirects(self, MockSession) -> None:+ # Credentials ride in custom headers, not `Authorization` — `requests` won't strip those+ # on a cross-origin redirect, so every sync request (not just the validation probe) must+ # refuse to follow one and stay pinned to the Propertyware host.+ session = MockSession.return_value+ _wire(session, [_response([{"id": 1}])])++ _rows(_source(_make_manager()))++ assert session.send.call_args.kwargs["allow_redirects"] is False++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_single_short_page_makes_one_request_and_no_checkpoint(self, MockSession) -> None:+ session = MockSession.return_value+ _wire(session, [_response([{"id": 1}, {"id": 2}])])++ manager = _make_manager()+ rows = _rows(_source(manager))++ assert rows == [{"id": 1}, {"id": 2}]+ 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) -> None:+ session = MockSession.return_value+ params = _wire(session, [_response([{"id": 7}])])++ rows = _rows(_source(_make_manager(PropertywareResumeConfig(offset=1000))))++ assert rows == [{"id": 7}]+ assert params[0]["offset"] == 1000++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_orderby_is_always_sent(self, MockSession) -> None:+ session = MockSession.return_value+ params = _wire(session, [_response([{"id": 1}])])++ _rows(_source(_make_manager()))+ assert params[0]["orderby"] == "lastModifiedDateTime asc"++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_incremental_filter_applied_on_every_page(self, MockSession) -> None:+ session = MockSession.return_value+ full_page = [{"id": i} for i in range(PAGE_SIZE)]+ params = _wire(session, [_response(full_page), _response([])])++ _rows(+ _source(+ _make_manager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2020, 1, 1, tzinfo=UTC),+ )+ )+ assert all(p.get("lastModifiedDateTimeStart") == "2020-01-01T00:00:00Z" for p in params)+ assert len(params) == 2++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_no_incremental_filter_without_value(self, MockSession) -> None:+ session = MockSession.return_value+ params = _wire(session, [_response([{"id": 1}])])++ _rows(_source(_make_manager(), should_use_incremental_field=True, db_incremental_field_last_value=None))+ assert "lastModifiedDateTimeStart" not in params[0]++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_no_incremental_filter_when_not_requested(self, MockSession) -> None:+ session = MockSession.return_value+ params = _wire(session, [_response([{"id": 1}])])++ _rows(+ _source(+ _make_manager(),+ should_use_incremental_field=False,+ db_incremental_field_last_value=datetime(2020, 1, 1, tzinfo=UTC),+ )+ )+ assert "lastModifiedDateTimeStart" not in params[0]++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_raises_on_non_retryable_error(self, MockSession) -> None:+ session = MockSession.return_value+ _wire(session, [_response([], status=401)])++ with pytest.raises(Exception, match="401 Client Error"):+ _rows(_source(_make_manager()))++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_raises_on_non_list_response(self, MockSession) -> None:+ session = MockSession.return_value+ # A 200 with an unexpected (non-array) body must fail loudly, not sync zero rows silently.+ _wire(session, [_response(None, raw=json.dumps({"error": "boom"}).encode())])++ with pytest.raises(ValueError, match="list response body"):+ _rows(_source(_make_manager()))+++class TestValidateCredentials:+ @pytest.mark.parametrize("status_code", [200, 401, 403, 500])+ @mock.patch(PROPERTYWARE_SESSION_PATCH)+ def test_returns_status_code(self, mock_session: mock.MagicMock, status_code: int) -> None:+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=status_code)+ assert validate_credentials("cid", "secret", "org-1") == status_code+ called_url = mock_session.return_value.get.call_args.args[0]+ assert called_url == "https://api.propertyware.com/pw/api/rest/v1/health"+ # allow_redirects is False because credentials ride in custom headers, not Authorization.+ assert mock_session.return_value.get.call_args.kwargs["allow_redirects"] is False+ assert set(mock_session.call_args.kwargs["redact_values"]) == {"cid", "secret", "org-1"}++ @mock.patch(PROPERTYWARE_SESSION_PATCH)+ def test_probes_a_specific_endpoint_path(self, mock_session: mock.MagicMock) -> None:+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=200)+ validate_credentials("cid", "secret", "org-1", path="/leases?limit=1")+ called_url = mock_session.return_value.get.call_args.args[0]+ assert called_url == "https://api.propertyware.com/pw/api/rest/v1/leases?limit=1"++ @mock.patch(PROPERTYWARE_SESSION_PATCH)+ def test_returns_none_on_transport_error(self, mock_session: mock.MagicMock) -> None:+ mock_session.return_value.get.side_effect = Exception("boom")+ assert validate_credentials("cid", "secret", "org-1") is None+++class TestPropertywareSourceResponse:+ @pytest.mark.parametrize("endpoint", ["Portfolios", "Leases", "LeaseCharges", "Bills", "GLAccounts"])+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_source_response_shape(self, MockSession, endpoint: str) -> None:+ response = _source(_make_manager(), endpoint=endpoint)+ assert response.name == endpoint+ assert response.primary_keys == ["id"]+ assert response.partition_keys == ["createdDateTime"]+ assert response.partition_mode == "datetime"+ assert response.sort_mode == "asc"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/propertyware/tests/test_propertyware_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/propertyware/tests/test_propertyware_source.pynew file mode 100644index 000000000000..fa6f8905db4a--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/propertyware/tests/test_propertyware_source.py@@ -0,0 +1,172 @@+import pytest+from unittest import mock++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.propertyware import (+ PropertywareSourceConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.propertyware.propertyware import (+ PropertywareResumeConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.propertyware.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.propertyware.source import PropertywareSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestPropertywareSource:+ def setup_method(self) -> None:+ self.source = PropertywareSource()+ self.team_id = 123+ self.config = PropertywareSourceConfig(client_id="cid", client_secret="secret", system_id="org-1")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.PROPERTYWARE++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config+ assert config.name.value == "Propertyware"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/propertyware"++ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert field_names == ["client_id", "client_secret", "system_id"]++ def test_client_secret_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 == "client_secret")+ assert field.type == SourceFieldInputConfigType.PASSWORD+ assert field.secret is True+ assert field.required is True++ @pytest.mark.parametrize("name", ["client_id", "system_id"])+ def test_non_secret_identifier_fields_are_plain_text(self, name: str) -> None:+ config = self.source.get_source_config+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == name)+ assert field.type == SourceFieldInputConfigType.TEXT+ assert field.secret is False+ assert field.required is True++ @pytest.mark.parametrize(+ "observed_error",+ [+ "401 Client Error: Unauthorized for url: https://api.propertyware.com/pw/api/rest/v1/portfolios",+ "403 Client Error: Forbidden for url: https://api.propertyware.com/pw/api/rest/v1/bills",+ ],+ )+ def test_non_retryable_errors_match_auth_failures(self, observed_error: str) -> None:+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable_errors)++ @pytest.mark.parametrize(+ "other_error",+ [+ "429 Client Error: Too Many Requests for url: https://api.propertyware.com/pw/api/rest/v1/portfolios",+ "500 Server Error for url: https://api.propertyware.com/pw/api/rest/v1/leases",+ ],+ )+ def test_transient_errors_are_not_marked_non_retryable(self, other_error: str) -> None:+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert not any(key in other_error for key in non_retryable_errors)++ def test_get_schemas_lists_every_endpoint(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)++ def test_get_schemas_names_filter(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["Portfolios"])+ assert [s.name for s in schemas] == ["Portfolios"]++ @pytest.mark.parametrize("endpoint", sorted(ENDPOINTS))+ def test_every_endpoint_is_incremental_on_last_modified(self, endpoint: str) -> None:+ schema = next(s for s in self.source.get_schemas(self.config, self.team_id, names=[endpoint]))+ assert schema.supports_incremental is True+ assert [f["field"] for f in schema.incremental_fields] == ["lastModifiedDateTime"]+ assert schema.detected_primary_keys == ["id"]++ def test_lists_tables_without_credentials(self) -> None:+ # Static endpoint catalog with no I/O — safe for public docs.+ assert self.source.lists_tables_without_credentials is True+ tables = self.source.get_documented_tables()+ assert {t["name"] for t in tables} == set(ENDPOINTS)++ @pytest.mark.parametrize(+ "status, schema_name, expected_ok",+ [+ (200, None, True),+ (200, "Portfolios", True),+ (403, None, True), # a key scoped to fewer entities is tolerated at source-create+ (403, "Bills", False), # but rejected when validating a schema it can't reach+ (401, None, False),+ (500, None, False),+ (None, None, False),+ ],+ )+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.propertyware.source.validate_propertyware_credentials"+ )+ def test_validate_credentials(+ self,+ mock_validate: mock.MagicMock,+ status: int | None,+ schema_name: str | None,+ expected_ok: bool,+ ) -> None:+ mock_validate.return_value = status+ ok, _ = self.source.validate_credentials(self.config, self.team_id, schema_name)+ assert ok is expected_ok++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.propertyware.source.validate_propertyware_credentials"+ )+ def test_validate_credentials_probes_health_at_create(self, mock_validate: mock.MagicMock) -> None:+ mock_validate.return_value = 200+ self.source.validate_credentials(self.config, self.team_id, None)+ assert mock_validate.call_args.args[3] == "/health"++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.propertyware.source.validate_propertyware_credentials"+ )+ def test_validate_credentials_probes_specific_endpoint(self, mock_validate: mock.MagicMock) -> None:+ mock_validate.return_value = 200+ self.source.validate_credentials(self.config, self.team_id, "LeaseCharges")+ assert mock_validate.call_args.args[3] == "/leases/charges?limit=1"++ def test_get_resumable_source_manager_binds_resume_config(self) -> None:+ inputs = mock.MagicMock()+ manager = self.source.get_resumable_source_manager(inputs)+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is PropertywareResumeConfig++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.propertyware.source.propertyware_source"+ )+ def test_source_for_pipeline_passes_credentials_and_cursor(self, mock_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "Portfolios"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2020-01-01T00:00:00Z"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ kwargs = mock_source.call_args.kwargs+ assert kwargs["client_id"] == "cid"+ assert kwargs["client_secret"] == "secret"+ assert kwargs["system_id"] == "org-1"+ assert kwargs["endpoint"] == "Portfolios"+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2020-01-01T00:00:00Z"++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.propertyware.source.propertyware_source"+ )+ def test_source_for_pipeline_omits_cursor_when_not_incremental(self, mock_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "Portfolios"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2020-01-01T00:00:00Z"++ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)+ assert mock_source.call_args.kwargs["db_incremental_field_last_value"] is None