: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 4 missing tables to the Buildium (RealPage) source (#118748)
Tom Owers7b1d8f8e3ffc
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.mdindex f9477c45a6a1..bbdf3ea668e2 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md@@ -1976,10 +1976,10 @@ Today (10): `applicants`, `bills`, `general_ledger_accounts`, `leases`, `rental_Diffed against: <https://developer.buildium.com/>-- [ ] `Bank accounts (GET /v1/bankaccounts)` — resolve OperatingBankAccountId in rental properties and identify accounts used for property finances (high)-- [ ] `General ledger entries and transactions (GET /v1/generalledger; GET /v1/generalledger/transactions)` — analyze account activity and transaction details to report property income, expenses, and cash flow (high)-- [ ] `Lease transactions (GET /v1/leases/{leaseId}/transactions)` — analyze tenant charges, payments, credits, and collection timing (high)-- [ ] `Lease outstanding balances (GET /v1/leases/outstandingbalances)` — measure delinquency and unpaid rent across properties and leases (high)+- [x] `Bank accounts (GET /v1/bankaccounts)` — resolve OperatingBankAccountId in rental properties and identify accounts used for property finances (high)+- [x] `General ledger entries and transactions (GET /v1/generalledger; GET /v1/generalledger/transactions)` — analyze account activity and transaction details to report property income, expenses, and cash flow (high)+- [x] `Lease transactions (GET /v1/leases/{leaseId}/transactions)` — analyze tenant charges, payments, credits, and collection timing (high)+- [x] `Lease outstanding balances (GET /v1/leases/outstandingbalances)` — measure delinquency and unpaid rent across properties and leases (high)- [ ] `Rent schedules (GET /v1/leases/rent)` — build rent roll reports and track scheduled rent changes over time (high)- [ ] `Bill payments (GET /v1/bills/{billId}/payments)` — analyze vendor payments and reconcile billed costs with cash paid (high)- [ ] `Tasks (GET /v1/tasks)` — resolve task IDs in work orders and include resident, owner, contact, and maintenance requests (high)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/buildium/buildium.py b/products/warehouse_sources/backend/temporal/data_imports/sources/buildium/buildium.pyindex d599dfdb0b96..03e756755305 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/buildium/buildium.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/buildium/buildium.py@@ -1,3 +1,4 @@+from collections.abc import Callable, Iteratorfrom datetime import UTC, datetimefrom typing import Any@@ -5,9 +6,18 @@ from posthog.dataclasses import frozenfrom products.warehouse_sources.backend.temporal.data_imports.sources.buildium.settings import (BASE_URL,+ CREDENTIAL_PROBE_PATHS,ENDPOINTS,+ EXCLUDED_COLUMNS,+ GL_ACCOUNT_BATCH_SIZE,+ GL_ACCOUNTS_PATH,+ GL_TRANSACTIONS_END_DATE,+ GL_TRANSACTIONS_START_DATE,INCREMENTAL_FIELDS,+ LEASE_TRANSACTIONS_PARENT,+ ORDER_BY,PAGE_SIZE,+ PRIMARY_KEYS,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_sessionfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (@@ -15,8 +25,14 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resEndpointResource,RESTAPIConfig,rest_api_resource,+ rest_api_resources,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import APIKeyAuth+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.resource import (+ Resource,+ ResumeHook,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import ClientConfigfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import schema_for_resourcefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse@@ -29,10 +45,11 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_class BuildiumResumeConfig:offset: intupdated_from: str | None = None+ gl_account_batch: int = 0def validate_credentials(config: BuildiumSourceConfig, endpoint: str, api_version: str) -> None:- path = schema_for_resource(ENDPOINTS, endpoint)+ path = CREDENTIAL_PROBE_PATHS.get(endpoint) or schema_for_resource(ENDPOINTS, endpoint)with make_tracked_session(redact_values=(config.client_secret,)) as session:response = session.get(f"{BASE_URL}/{api_version}/{path}",@@ -44,6 +61,137 @@ def validate_credentials(config: BuildiumSourceConfig, endpoint: str, api_versioresponse.raise_for_status()+def _client_config(config: BuildiumSourceConfig, api_version: str) -> ClientConfig:+ return {+ "base_url": f"{BASE_URL}/{api_version}/",+ "request_timeout": (10, 30),+ "headers": {"x-buildium-client-id": config.client_id},+ "auth": {"type": "api_key", "name": "x-buildium-client-secret", "api_key": config.client_secret},+ "paginator": {"type": "offset", "limit": PAGE_SIZE, "total_path": None, "total_header": "X-Total-Count"},+ }+++def _format_watermark(value: datetime | str) -> str:+ watermark = datetime.fromisoformat(value.replace("Z", "+00:00")) if isinstance(value, str) else value+ if watermark.tzinfo is None:+ watermark = watermark.replace(tzinfo=UTC)+ return watermark.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")+++def _list_resource(+ client: ClientConfig,+ endpoint: str,+ path: str,+ params: dict[str, Any],+ team_id: int,+ job_id: str,+ resume_hook: ResumeHook | None = None,+ initial_offset: int | None = None,+) -> Resource:+ endpoint_config: Endpoint = {"path": path, "data_selector": "$", "params": params}+ resource_config: EndpointResource = {+ "name": endpoint,+ "endpoint": endpoint_config,+ "columns": {"LastUpdatedDateTime": {"data_type": "timestamp"}} if endpoint in INCREMENTAL_FIELDS else {},+ }+ rest_config: RESTAPIConfig = {"client": client, "resources": [resource_config]}+ return rest_api_resource(+ rest_config,+ team_id,+ job_id,+ None,+ resume_hook=resume_hook,+ initial_paginator_state={"offset": initial_offset} if initial_offset is not None else None,+ )+++def _drop_columns(columns: tuple[str, ...]) -> Callable[[dict[str, Any]], dict[str, Any]]:+ def drop(row: dict[str, Any]) -> dict[str, Any]:+ for column in columns:+ row.pop(column, None)+ return row++ return drop+++def _lease_transactions_resource(client: ClientConfig, team_id: int, job_id: str) -> Resource:+ rest_config: RESTAPIConfig = {+ "client": client,+ "resources": [+ {+ "name": LEASE_TRANSACTIONS_PARENT,+ "endpoint": {+ "path": ENDPOINTS[LEASE_TRANSACTIONS_PARENT],+ "data_selector": "$",+ "params": {"orderby": "Id asc"},+ },+ },+ {+ "name": "lease_transactions",+ "include_from_parent": ["Id"],+ "endpoint": {+ "path": ENDPOINTS["lease_transactions"],+ "data_selector": "$",+ "params": {+ "leaseId": {"type": "resolve", "resource": LEASE_TRANSACTIONS_PARENT, "field": "Id"},+ "orderby": "Id asc",+ },+ # A lease deleted after the lease listing has no transactions left to read.+ "response_actions": [{"status_code": 404, "action": "ignore"}],+ },+ },+ ],+ }+ resources = rest_api_resources(rest_config, team_id, job_id, None)+ return next(resource for resource in resources if resource.name == "lease_transactions")+++def _gl_account_ids(client: ClientConfig, team_id: int, job_id: str) -> list[int]:+ accounts = _list_resource(+ client, "general_ledger_accounts", GL_ACCOUNTS_PATH, {"orderby": "Id asc"}, team_id, job_id+ )+ ids: set[int] = set()+ for page in accounts:+ for account in page:+ for item in [account, *(account.get("SubAccounts") or [])]:+ if item.get("Id") is not None:+ ids.add(item["Id"])+ return sorted(ids)+++def _owned_by_batch(batch_index: int, batch_of_account: dict[int, int]) -> Callable[[dict[str, Any]], bool]:+ # A transaction with lines in several account batches comes back once per batch. Only the batch+ # of its lowest known account keeps it, so each transaction lands once without a seen-id set.+ def keep(row: dict[str, Any]) -> bool:+ lines = (row.get("Journal") or {}).get("Lines") or []+ batches = [+ batch_of_account[account_id]+ for line in lines+ if (account_id := (line.get("GLAccount") or {}).get("Id")) in batch_of_account+ ]+ return not batches or min(batches) == batch_index++ return keep+++def _iter_gl_transactions(+ client: ClientConfig,+ team_id: int,+ job_id: str,+ build_batch: Callable[[list[int], int, bool, int | None], Resource],+ start_batch: int,+ start_offset: int | None,+) -> Iterator[list[dict[str, Any]]]:+ account_ids = _gl_account_ids(client, team_id, job_id)+ batches = [account_ids[i : i + GL_ACCOUNT_BATCH_SIZE] for i in range(0, len(account_ids), GL_ACCOUNT_BATCH_SIZE)]+ batch_of_account = {account_id: index for index, batch in enumerate(batches) for account_id in batch}+ for index in range(start_batch, len(batches)):+ resource = build_batch(+ batches[index], index, index + 1 < len(batches), start_offset if index == start_batch else None+ )+ yield from resource.add_filter(_owned_by_batch(index, batch_of_account))++def buildium_source(config: BuildiumSourceConfig,endpoint: str,@@ -55,15 +203,11 @@ def buildium_source(db_incremental_field_last_value: datetime | str | None,) -> SourceResponse:path = schema_for_resource(ENDPOINTS, endpoint)+ client = _client_config(config, api_version)incremental = should_use_incremental_field and endpoint in INCREMENTAL_FIELDSupdated_from = Noneif incremental and db_incremental_field_last_value is not None:- watermark = db_incremental_field_last_value- if isinstance(watermark, str):- watermark = datetime.fromisoformat(watermark.replace("Z", "+00:00"))- if watermark.tzinfo is None:- watermark = watermark.replace(tzinfo=UTC)- updated_from = watermark.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")+ updated_from = _format_watermark(db_incremental_field_last_value)resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else Noneif resume is not None:@@ -72,45 +216,80 @@ def buildium_source(# Keep offset pagination stable when an object is updated during extraction. Ordering by the# mutable update timestamp can move an already-read object to a later page and skip another one.- params: dict[str, Any] = {"orderby": "Id asc"}+ params: dict[str, Any] = {"orderby": ORDER_BY.get(endpoint, "Id asc")}if updated_from is not None:params["lastupdatedfrom"] = updated_from- endpoint_config: Endpoint = {"path": path, "data_selector": "$", "params": params}- resource_config: EndpointResource = {- "name": endpoint,- "endpoint": endpoint_config,- "columns": {"LastUpdatedDateTime": {"data_type": "timestamp"}} if endpoint in INCREMENTAL_FIELDS else {},- }- rest_config: RESTAPIConfig = {- "client": {- "base_url": f"{BASE_URL}/{api_version}/",- "request_timeout": (10, 30),- "headers": {"x-buildium-client-id": config.client_id},- "auth": {"type": "api_key", "name": "x-buildium-client-secret", "api_key": config.client_secret},- "paginator": {"type": "offset", "limit": PAGE_SIZE, "total_path": None, "total_header": "X-Total-Count"},- },- "resources": [resource_config],- }-def save_checkpoint(state: dict[str, Any] | None) -> None:if state is not None:resumable_source_manager.save_state(BuildiumResumeConfig(offset=int(state["offset"]), updated_from=updated_from))- resource = rest_api_resource(- rest_config,- team_id,- job_id,- None,- resume_hook=save_checkpoint,- initial_paginator_state={"offset": resume.offset} if resume else None,- )+ resource: Resource+ if endpoint == "lease_transactions":+ # Fan-out resources cannot resume, so this table restarts from the first lease after a hand-off.+ resource = _lease_transactions_resource(client, team_id, job_id)+ elif endpoint == "general_ledger_transactions":+ params.update({"startdate": GL_TRANSACTIONS_START_DATE, "enddate": GL_TRANSACTIONS_END_DATE})++ def build_batch(account_ids: list[int], index: int, has_next_batch: bool, offset: int | None) -> Resource:+ def save_batch_checkpoint(state: dict[str, Any] | None) -> None:+ if state is not None:+ resumable_source_manager.save_state(+ BuildiumResumeConfig(+ offset=int(state["offset"]), updated_from=updated_from, gl_account_batch=index+ )+ )+ elif has_next_batch:+ resumable_source_manager.save_state(+ BuildiumResumeConfig(offset=0, updated_from=updated_from, gl_account_batch=index + 1)+ )++ return _list_resource(+ client,+ endpoint,+ path,+ {**params, "glaccountids": account_ids},+ team_id,+ job_id,+ resume_hook=save_batch_checkpoint,+ initial_offset=offset,+ )++ template = build_batch([], 0, False, None)+ # Wrapping the batches in a `Resource` keeps the framework's safe points and page checkpoints.+ resource = Resource(+ _iter_gl_transactions,+ name=endpoint,+ hints=template._hints,+ args=(+ client,+ team_id,+ job_id,+ build_batch,+ resume.gl_account_batch if resume else 0,+ resume.offset if resume else None,+ ),+ )+ else:+ resource = _list_resource(+ client,+ endpoint,+ path,+ params,+ team_id,+ job_id,+ resume_hook=save_checkpoint,+ initial_offset=resume.offset if resume else None,+ )+ if endpoint in EXCLUDED_COLUMNS:+ resource.add_map(_drop_columns(EXCLUDED_COLUMNS[endpoint]))+return SourceResponse(name=endpoint,items=lambda: resource,- primary_keys=["Id"],+ primary_keys=PRIMARY_KEYS.get(endpoint, ["Id"]),column_hints=resource.column_hints,# Incremental rows are ID-ordered rather than timestamp-ordered, so only advance the# timestamp watermark after a complete extraction.diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/buildium/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/buildium/canonical_descriptions.pyindex 43d81e4121b4..4c95b8f99cd9 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/buildium/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/buildium/canonical_descriptions.py@@ -77,4 +77,50 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"LastUpdatedDateTime": "Time of the most recent applicant update.",},},+ "bank_accounts": {+ "description": "Bank accounts that hold property, company, and association funds.",+ "docs_url": "https://developer.buildium.com/#operation/ExternalApiBankAccounts_GetAllBankAccounts",+ "columns": {+ "Id": "Identifier for this bank account.",+ "GLAccount": "General ledger account linked to the bank account.",+ "BankAccountType": "Type of bank account, such as Checking or Savings.",+ "Balance": "Current bank account balance.",+ "IsActive": "Whether the bank account is active.",+ },+ },+ "general_ledger_transactions": {+ "description": "Financial transactions recorded in the general ledger, with their journal lines.",+ "docs_url": "https://developer.buildium.com/#operation/ExternalApiGeneralLedgerTransactions_GetAllTransactions",+ "columns": {+ "Id": "Identifier for this transaction.",+ "Date": "Date of the transaction.",+ "TransactionType": "Type of transaction that occurred.",+ "TotalAmount": "Sum of all journal line amounts in the transaction.",+ "Journal": "Journal lines that record the transaction against general ledger accounts.",+ "LastUpdatedDateTime": "Time of the most recent transaction update.",+ },+ },+ "lease_transactions": {+ "description": "Charges, payments, credits, and other transactions on each lease ledger.",+ "docs_url": "https://developer.buildium.com/#operation/ExternalApiLeaseLedgerTransactions_GetLeaseLedgers",+ "columns": {+ "_leases_Id": "Lease whose ledger was read to return the transaction.",+ "Id": "Identifier for this transaction.",+ "Date": "Date of the transaction.",+ "TransactionType": "Type of transaction that occurred.",+ "TotalAmount": "Sum of all journal line amounts in the transaction.",+ "PayeeTenantId": "Tenant associated with the transaction, where applicable.",+ },+ },+ "lease_outstanding_balances": {+ "description": "Leases that have an outstanding balance, split by how long the amount has been due.",+ "docs_url": "https://developer.buildium.com/#operation/ExternalApiLeaseOutstandingBalances_GetLeaseOutstandingBalances",+ "columns": {+ "LeaseId": "Lease that has the outstanding balance.",+ "PropertyId": "Property covered by the lease.",+ "UnitId": "Unit covered by the lease.",+ "TotalBalance": "Total outstanding balance due.",+ "BalanceOver90Days": "Outstanding balance due from over 90 days ago.",+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/buildium/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/buildium/settings.pyindex 2ae9082731a8..850d87195a8a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/buildium/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/buildium/settings.py@@ -13,8 +13,33 @@ ENDPOINTS = {"general_ledger_accounts": "glaccounts","work_orders": "workorders","applicants": "applicants",+ "bank_accounts": "bankaccounts",+ "general_ledger_transactions": "generalledger/transactions",+ "lease_transactions": "leases/{leaseId}/transactions",+ "lease_outstanding_balances": "leases/outstandingbalances",}# Other list responses omit update timestamps, even when their endpoints accept update filters.-INCREMENTAL_FIELDS = {name: [incremental_field("LastUpdatedDateTime")] for name in ("leases", "applicants")}+INCREMENTAL_FIELDS = {+ name: [incremental_field("LastUpdatedDateTime")] for name in ("leases", "applicants", "general_ledger_transactions")+}+PRIMARY_KEYS = {+ "lease_transactions": ["_leases_Id", "Id"],+ "lease_outstanding_balances": ["LeaseId"],+}+ORDER_BY = {"lease_outstanding_balances": "LeaseId asc"}+# The full account number is not needed for analysis, and the masked AccountNumber column stays.+EXCLUDED_COLUMNS = {"bank_accounts": ("AccountNumberUnmasked",)}+# Endpoints that need a parent id or required filters are probed through the list they depend on.+CREDENTIAL_PROBE_PATHS = {"lease_transactions": "leases", "general_ledger_transactions": "glaccounts"}++LEASE_TRANSACTIONS_PARENT = "leases"+GL_ACCOUNTS_PATH = "glaccounts"+# Buildium rejects query strings over 4096 characters, and each repeated glaccountids value takes+# up to 24 characters, so larger charts of accounts are requested in batches.+GL_ACCOUNT_BATCH_SIZE = 150+# The transactions endpoint requires a date range. These bounds cover every transaction date.+GL_TRANSACTIONS_START_DATE = "1900-01-01"+GL_TRANSACTIONS_END_DATE = "2099-12-31"+AUTH_ERROR = "Buildium authentication failed. Check your API client ID and secret."PERMISSION_ERROR = "Buildium denied access. Enable Open API and grant your API key View access to the selected data."diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/buildium/tests/test_buildium.py b/products/warehouse_sources/backend/temporal/data_imports/sources/buildium/tests/test_buildium.pyindex eb453b49e3b4..0ab3ab2dffcb 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/buildium/tests/test_buildium.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/buildium/tests/test_buildium.py@@ -13,8 +13,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.buildium.s)from products.warehouse_sources.backend.temporal.data_imports.sources.buildium.source import BuildiumSourcefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (+ RecordedRequest,ScriptedResponse,SourceDriver,+ route,)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.buildium import (BuildiumSourceConfig,@@ -114,3 +116,145 @@ def test_sync_error_mapping(status: int, message: str) -> None:assert isinstance(result.raised, HTTPError)errors = BuildiumSource().get_non_retryable_errors()assert next(value for key, value in errors.items() if key in str(result.raised)) == message+++def _gl_transaction(transaction_id: int, *account_ids: int) -> dict[str, Any]:+ return {+ "Id": transaction_id,+ "Journal": {"Lines": [{"GLAccount": {"Id": account_id}} for account_id in account_ids]},+ }+++GL_TRANSACTION_PAGES: dict[tuple[tuple[str, ...], str], list[dict[str, Any]]] = {+ (("10", "30"), "0"): [_gl_transaction(1, 10), _gl_transaction(2, 30, 31)],+ (("10", "30"), "2"): [_gl_transaction(3, 31, 10)],+ # Transactions 2 and 3 also have a line in this batch, but the first batch already returned them.+ (("31",), "0"): [_gl_transaction(2, 30, 31), _gl_transaction(3, 31, 10)],+ (("31",), "2"): [_gl_transaction(4, 31), {"Id": 5, "Journal": None}],+}+++ ("accounts", "resume_state", "watermark", "expected_batches", "expected_ids", "expected_saved"),+ [+ (+ [{"Id": 30, "SubAccounts": [{"Id": 31}]}, {"Id": 10, "SubAccounts": None}],+ None,+ None,+ [(("10", "30"), "0"), (("10", "30"), "2"), (("31",), "0"), (("31",), "2")],+ [1, 2, 3, 4, 5],+ [+ BuildiumResumeConfig(offset=2, gl_account_batch=0),+ BuildiumResumeConfig(offset=0, gl_account_batch=1),+ BuildiumResumeConfig(offset=2, gl_account_batch=1),+ ],+ ),+ (+ [{"Id": 30, "SubAccounts": [{"Id": 31}]}, {"Id": 10}],+ BuildiumResumeConfig(offset=2, updated_from="2026-01-01T00:00:00Z", gl_account_batch=1),+ "2026-02-01T00:00:00Z",+ [(("31",), "2")],+ [4, 5],+ [],+ ),+ (+ [{"Id": 10}, {"Id": 30}],+ None,+ "2026-02-01T00:00:00Z",+ [(("10", "30"), "0"), (("10", "30"), "2")],+ [1, 2, 3],+ [BuildiumResumeConfig(offset=2, updated_from="2026-02-01T00:00:00Z", gl_account_batch=0)],+ ),+ ([], None, None, [], [], []),+ ],+)+def test_general_ledger_transactions_batches_accounts(+ accounts: list[dict[str, Any]],+ resume_state: BuildiumResumeConfig | None,+ watermark: str | None,+ expected_batches: list[tuple[tuple[str, ...], str]],+ expected_ids: list[int],+ expected_saved: list[BuildiumResumeConfig],+) -> None:+ def respond(request: RecordedRequest) -> ScriptedResponse:+ if request.path == "/v1/glaccounts":+ return ScriptedResponse(json=accounts, headers={"X-Total-Count": str(len(accounts))})+ batch = request.query["glaccountids"]+ total = 3 if batch == ("10", "30") else 4+ page = GL_TRANSACTION_PAGES[(batch, request.param("offset") or "0")]+ return ScriptedResponse(json=page, headers={"X-Total-Count": str(total)})++ module = "products.warehouse_sources.backend.temporal.data_imports.sources.buildium.buildium"+ with patch(f"{module}.PAGE_SIZE", 2), patch(f"{module}.GL_ACCOUNT_BATCH_SIZE", 2):+ result = driver().run(+ "general_ledger_transactions",+ respond,+ resume_state=resume_state,+ should_use_incremental_field=watermark is not None,+ db_incremental_field_last_value=watermark,+ )++ assert result.raised is None+ assert [row["Id"] for row in result.rows] == expected_ids+ assert result.saved_states == expected_saved+ assert result.paths[0] == "/v1/glaccounts"+ transaction_requests = result.requests[1:]+ assert [(request.query["glaccountids"], request.param("offset")) for request in transaction_requests] == (+ expected_batches+ )+ expected_filter = resume_state.updated_from if resume_state else watermark+ for request in transaction_requests:+ assert request.path == "/v1/generalledger/transactions"+ assert request.param("startdate") == "1900-01-01"+ assert request.param("enddate") == "2099-12-31"+ assert request.param("orderby") == "Id asc"+ assert request.param("lastupdatedfrom") == (None if watermark is None else expected_filter)+++def test_lease_transactions_fan_out_over_leases() -> None:+ script = route(+ {+ "/v1/leases": [ScriptedResponse(json=[{"Id": 7}, {"Id": 8}], headers={"X-Total-Count": "2"})],+ "/v1/leases/7/transactions": [+ ScriptedResponse(+ json=[{"Id": 100, "LeaseId": 7, "TotalAmount": 1250.5}], headers={"X-Total-Count": "1"}+ )+ ],+ "/v1/leases/8/transactions": [+ ScriptedResponse(status=404, json={"UserMessage": "The lease could not be found.", "Errors": []})+ ],+ }+ )+ result = driver().run("lease_transactions", script)++ assert result.raised is None+ assert result.rows == [{"Id": 100, "LeaseId": 7, "TotalAmount": 1250.5, "_leases_Id": 7}]+ assert result.paths == ["/v1/leases", "/v1/leases/7/transactions", "/v1/leases/8/transactions"]+ assert result.params("orderby") == ["Id asc"] * 3+++ ("endpoint", "row", "expected_row", "expected_orderby"),+ [+ (+ "bank_accounts",+ {"Id": 3, "AccountNumber": "XXXX1234", "AccountNumberUnmasked": "000011111234", "Balance": 10.0},+ {"Id": 3, "AccountNumber": "XXXX1234", "Balance": 10.0},+ "Id asc",+ ),+ (+ "lease_outstanding_balances",+ {"LeaseId": 7, "TotalBalance": 300.0, "Balances": [{"GLAccountId": 10, "TotalBalance": 300.0}]},+ {"LeaseId": 7, "TotalBalance": 300.0, "Balances": [{"GLAccountId": 10, "TotalBalance": 300.0}]},+ "LeaseId asc",+ ),+ ],+)+def test_top_level_row_shaping_and_order(+ endpoint: str, row: dict[str, Any], expected_row: dict[str, Any], expected_orderby: str+) -> None:+ result = driver().run(endpoint, [ScriptedResponse(json=[row], headers={"X-Total-Count": "1"})])++ assert result.raised is None+ assert result.rows == [expected_row]+ assert result.params("orderby") == [expected_orderby]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/buildium/tests/test_buildium_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/buildium/tests/test_buildium_source.pyindex 04383f78ecdc..c1c9801053e3 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/buildium/tests/test_buildium_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/buildium/tests/test_buildium_source.py@@ -17,12 +17,22 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_)[email protected]("schema_name", [None, "bills"])+ ("schema_name", "expected_path"),+ [+ (None, "/v1/rentals"),+ ("bills", "/v1/bills"),+ ("lease_transactions", "/v1/leases"),+ ("general_ledger_transactions", "/v1/glaccounts"),+ ],+)@pytest.mark.parametrize(("status", "expected"),[(200, (True, None)), (401, (False, AUTH_ERROR)), (403, (False, PERMISSION_ERROR)), (500, None)],)-def test_validate_credentials(schema_name: str | None, status: int, expected: tuple[bool, str | None] | None) -> None:+def test_validate_credentials(+ schema_name: str | None, expected_path: str, status: int, expected: tuple[bool, str | None] | None+) -> None:config = BuildiumSourceConfig(client_id="example-client", client_secret="example-secret")answer = ScriptedResponse(status=status)script = always(answer) if status == 500 else [answer]@@ -37,7 +47,7 @@ def test_validate_credentials(schema_name: str | None, status: int, expected: tuif status != 500:assert len(network.requests_log) == 1for request in network.requests_log:- assert request.path == ("/v1/bills" if schema_name else "/v1/rentals")+ assert request.path == expected_pathassert request.param("limit") == "1"assert request.headers["x-buildium-client-id"] == config.client_idassert request.headers["x-buildium-client-secret"] == config.client_secret