Skip to content

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

feat(ezofficeinventory): add teams, work orders and checkout history tables (#107283)

Tom Owersdaf5b487a31b
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index 0c7441d4b9ad..73216806f5a4 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
@@ -2975,10 +2975,10 @@ Today (12): `asset_stocks`, `assets`, `checked_out_assets`, `custom_fields`, `gr
Diffed against: <https://ezo.io/ezofficeinventory/developers/>
-- [ ] `GET /assets/{id}/history.api and /members/{id}/checkin_checkout_history.api (+ checkin_checkout_history_for_stock.api)` — check-in/check-out transition history - the utilization fact table; the source only has the point-in-time checked_out_assets snapshot (high)
-- [ ] `GET /tasks.api (work orders) and /tasks/filter` — work orders with state, assignee and duration - a core analytical object with no coverage at all (high)
-- [ ] `GET /services.api` — service/maintenance records per asset, the basis for downtime and maintenance-cost reporting (high)
-- [ ] `GET /teams.api` — team lookup resolving the team IDs carried on members and assignments (high)
+- [x] `GET /assets/{id}/history.api and /members/{id}/checkin_checkout_history.api (+ checkin_checkout_history_for_stock.api)` — check-in/check-out transition history - the utilization fact table; the source only has the point-in-time checked_out_assets snapshot (high) — added as `asset_checkout_history` (fan-out over assets) and `member_stock_histories`. `members/{id}/checkin_checkout_history.api` returns the same transition records as the asset history, keyed by member instead of asset, so it was not added as a third table.
+- [x] `GET /tasks.api (work orders) and /tasks/filter` — work orders with state, assignee and duration - a core analytical object with no coverage at all (high) — added as `work_orders`. `/tasks/filter` does not exist; the list endpoint takes a `filter` query param, and the table syncs the unfiltered list.
+- [ ] `GET /services.api` — service/maintenance records per asset, the basis for downtime and maintenance-cost reporting (high). Not readable: `assets/{id}/services.api` is POST/PUT only and v2 has no services resource, so there is no list endpoint to sync. The closest GET returns assets being serviced, not service records.
+- [x] `GET /teams.api` — team lookup resolving the team IDs carried on members and assignments (high) — added as `teams`
- [ ] `GET /custom_roles.api` — role lookup resolving the role reference on every member row already synced (medium)
- [ ] `GET /task_types.api` — work order type lookup, the primary breakdown dimension for work orders (medium)
- [ ] `GET /reservation_requests.api and /checkout_requests/filter.api` — reservations and booking requests - forward-looking demand against the asset pool (medium)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ezofficeinventory/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ezofficeinventory/canonical_descriptions.py
index 06c900f8a5c6..2168ebb00ac0 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/ezofficeinventory/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ezofficeinventory/canonical_descriptions.py
@@ -3,6 +3,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.can
)
_DOCS_URL = "https://ezo.io/ezofficeinventory/developers/"
+# Work orders and the history sub-resources are documented on the v2 reference only.
+_DOCS_URL_V2 = "https://ezo.io/ezofficeinventory/api-v2/"
CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"assets": {
@@ -112,6 +114,99 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"name": "Display name of the custom field.",
},
},
+ "teams": {
+ "description": "Teams that members are grouped into. Resolves the team ids carried on member records.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "id": "Unique identifier for the team.",
+ "name": "Display name of the team.",
+ "description": "Free-text description of the team.",
+ "parent_id": "Identifier of the parent team, for teams nested under another team.",
+ "identification_number": "Identification number assigned to the team.",
+ },
+ },
+ "work_orders": {
+ "description": "Work orders (maintenance, repair and service tasks) raised against assets or locations.",
+ "docs_url": _DOCS_URL_V2,
+ "columns": {
+ "id": "Unique identifier for the work order.",
+ "title": "Summary of the work to be done.",
+ "state": "Current state of the work order (e.g. open, in progress, review pending, completed).",
+ "priority": "Priority of the work order (high, medium or low).",
+ "task_type": "Work order type, the primary breakdown dimension for work orders.",
+ "task_type_id": "Identifier of the work order type.",
+ "assigned_to_id": "Identifier of the member or team the work order is assigned to.",
+ "assigned_to_type": "Whether the work order is assigned to a member or a team.",
+ "reviewer_id": "Identifier of the member who reviews the completed work order.",
+ "location_id": "Identifier of the location the work order applies to.",
+ "project_id": "Identifier of the project the work order is linked to.",
+ "expected_start_date": "Date the work was expected to start.",
+ "due_date": "Date the work order is due for completion.",
+ "started_on": "Timestamp when work on the work order started.",
+ "completed_on": "Timestamp when the work order was completed.",
+ "time_spent": "Total time logged against the work order, in hours.",
+ "base_cost": "Labour or base cost recorded on the work order.",
+ "inventory_cost": "Cost of inventory consumed by the work order.",
+ "total_cost": "Total cost of the work order, including inventory and work logs.",
+ "created_at": "Timestamp when the work order was created.",
+ "updated_at": "Timestamp when the work order was last updated.",
+ },
+ },
+ "asset_checkout_history": {
+ "description": (
+ "Check-in and check-out transitions per fixed asset — the utilization history behind "
+ "how long each asset was held and by whom."
+ ),
+ "docs_url": _DOCS_URL_V2,
+ "columns": {
+ "asset_id": "Identifier of the asset this history entry belongs to, taken from the parent asset record.",
+ "id": "Identifier of the history entry within its asset.",
+ "is_checkout": "Whether the entry records a check-out rather than a check-in.",
+ "assigned_to_id": "Identifier of the member, team or location the asset was assigned to.",
+ "assigned_to_type": "What kind of entity the asset was assigned to.",
+ "assigned_to_name": "Display name of the entity the asset was assigned to.",
+ "checkout_on": "Timestamp when the asset was checked out.",
+ "checkin_due_on": "Timestamp the asset was due back.",
+ "checkin_on": "Timestamp the asset was expected to be checked in.",
+ "actual_checkin_on": "Timestamp the asset was actually checked in.",
+ "checked_out_duration_in_seconds": "How long the asset stayed checked out, in seconds.",
+ "location_id": "Identifier of the location involved in the transition.",
+ "project_id": "Identifier of the project the checkout was linked to.",
+ "is_transfer": "Whether the entry records a transfer rather than a plain check-in or check-out.",
+ "action_source": "Where the transition was made from (e.g. Web App).",
+ "created_at": "Timestamp when the history entry was created.",
+ "updated_at": "Timestamp when the history entry was last updated.",
+ },
+ },
+ "member_stock_histories": {
+ "description": (
+ "Stock transactions attributed to a member — checkouts, check-ins, transfers and stock "
+ "adjustments against quantity-tracked items."
+ ),
+ "docs_url": _DOCS_URL_V2,
+ "columns": {
+ "member_id": "Identifier of the member this entry belongs to, taken from the parent member record.",
+ "id": "Identifier of the stock history entry within its member.",
+ "order_type": "Kind of stock transaction (e.g. Add Stock, checkin, New Sale).",
+ "asset_name": "Display name of the item the transaction applies to.",
+ "quantity": "Quantity moved by the transaction.",
+ "quantity_after_transaction": "Quantity remaining on the item after the transaction.",
+ "price": "Unit price recorded on the transaction.",
+ "cost_price": "Total cost recorded on the transaction.",
+ "unit_cost_price": "Cost per unit recorded on the transaction.",
+ "checkout_on": "Timestamp the stock was checked out.",
+ "checkin_due_on": "Timestamp the stock was due back.",
+ "checkin_on": "Timestamp the stock was checked in.",
+ "checked_out_to_location_id": "Identifier of the location the stock was checked out to.",
+ "checked_in_from_location_id": "Identifier of the location the stock was checked in from.",
+ "purchase_order_id": "Identifier of the purchase order the stock came in on.",
+ "vendor_id": "Identifier of the vendor the stock was bought from.",
+ "project_id": "Identifier of the project the transaction was linked to.",
+ "task_id": "Identifier of the work order that consumed the stock.",
+ "created_at": "Timestamp when the transaction was recorded.",
+ "updated_at": "Timestamp when the transaction was last updated.",
+ },
+ },
"purchase_orders": {
"description": "Purchase orders raised for procuring assets and inventory.",
"docs_url": _DOCS_URL,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ezofficeinventory/ezofficeinventory.com.mdx b/products/warehouse_sources/backend/temporal/data_imports/sources/ezofficeinventory/ezofficeinventory.com.mdx
index a8853b6505ff..50f3076ddfc9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/ezofficeinventory/ezofficeinventory.com.mdx
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ezofficeinventory/ezofficeinventory.com.mdx
@@ -22,8 +22,8 @@ import AlphaRelease from '../_snippets/alpha-release.mdx'
[EZOfficeInventory](https://ezo.io/ezofficeinventory/) (now branded EZO) is a cloud asset and
inventory management platform. Linking it as a source syncs your assets, inventory, members,
-locations, and related records into PostHog so you can join asset and inventory data with the rest of
-your warehouse.
+locations, work orders, and related records into PostHog so you can join asset and inventory data with
+the rest of your warehouse.
## Prerequisites
@@ -61,6 +61,11 @@ limit (~60 requests/minute) and backs off automatically on rate-limit responses.
<SourceTables />
+`asset_checkout_history` and `member_stock_histories` are turned off by default. EZOfficeInventory
+serves check-in and check-out history one item at a time, so these two tables need a request per asset
+or per member and are slow to sync on large accounts. Turn them on if you want to report on
+utilization or stock movement over time.
+
## Troubleshooting
- **Invalid credentials on connect**: confirm API access is enabled in **Settings → Integrations → API
@@ -68,6 +73,7 @@ limit (~60 requests/minute) and backs off automatically on rate-limit responses.
`https://` prefix or `.ezofficeinventory.com` suffix).
- **Syncs are slow on large accounts**: EZOfficeInventory enforces a fair-use limit of roughly 60
requests per minute (lower on trial accounts). The connector throttles to stay within it, so large
- asset or inventory tables can take a while on the first sync.
+ asset or inventory tables can take a while on the first sync. The two history tables are the slowest,
+ because the API only serves history one item at a time.
<TroubleshootingLink />
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ezofficeinventory/ezofficeinventory.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ezofficeinventory/ezofficeinventory.py
index 8a7cf1f4ed45..6950a56aaa88 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/ezofficeinventory/ezofficeinventory.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ezofficeinventory/ezofficeinventory.py
@@ -1,7 +1,7 @@
import re
import dataclasses
-from collections.abc import Callable
-from typing import Any, Optional
+from collections.abc import Callable, Iterable
+from typing import Any, Optional, cast
from urllib3.util.retry import Retry
@@ -12,6 +12,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
RESTAPIConfig,
rest_api_resource,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ build_dependent_resource,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
BasePaginator,
JSONResponsePaginator,
@@ -21,6 +24,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
ApiKeyAuthConfig,
AuthConfig,
BearerTokenAuthConfig,
+ ClientConfig,
)
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
@@ -80,6 +84,21 @@ def _make_unwrap_map(unwrap_key: str) -> Callable[[dict[str, Any]], dict[str, An
return _unwrap
+def _client_config(subdomain: str, api_key: str, api_version: str) -> ClientConfig:
+ return {
+ "base_url": base_url(subdomain),
+ # Only the non-secret Accept header is set here; the token goes through the auth config.
+ "headers": {"Accept": "application/json"},
+ "auth": _auth_config(api_version, api_key),
+ # Pin every request (including paginator/resume URLs) to the subdomain host and reject
+ # cross-host redirects — the user-supplied token must not be replayable off-host
+ # (SSRF / credential-exfiltration defense-in-depth). `allowed_hosts=[]` means
+ # "same host as base_url only".
+ "allowed_hosts": [],
+ "allow_redirects": False,
+ }
+
+
def _rest_config(
subdomain: str, api_key: str, config: EZOfficeInventoryEndpointConfig, api_version: str
) -> RESTAPIConfig:
@@ -94,22 +113,59 @@ def _rest_config(
resource["data_map"] = _make_unwrap_map(config.unwrap_key)
return {
- "client": {
- "base_url": base_url(subdomain),
- # Only the non-secret Accept header is set here; the token goes through the auth config.
- "headers": {"Accept": "application/json"},
- "auth": _auth_config(api_version, api_key),
- # Pin every request (including paginator/resume URLs) to the subdomain host and reject
- # cross-host redirects — the user-supplied token must not be replayable off-host
- # (SSRF / credential-exfiltration defense-in-depth). `allowed_hosts=[]` means
- # "same host as base_url only".
- "allowed_hosts": [],
- "allow_redirects": False,
- },
+ "client": _client_config(subdomain, api_key, api_version),
"resources": [resource],
}
+def _fanout_source(
+ api_key: str,
+ subdomain: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ api_version: str,
+) -> SourceResponse:
+ """Fan a per-item history sub-resource out over the list endpoint it hangs off.
+
+ The parent list is re-walked each sync because neither the parent nor the child takes a
+ server-side time filter, so this path is always full refresh and carries no resume state.
+ """
+ endpoint_configs = endpoints_for_version(api_version)
+ config = endpoint_configs[endpoint]
+ assert config.fanout is not None
+ parent_config = endpoint_configs[config.fanout.parent_name]
+
+ dependent_resource = cast(
+ Iterable[Any],
+ build_dependent_resource(
+ endpoint_configs=endpoint_configs,
+ child_endpoint=endpoint,
+ fanout=config.fanout,
+ client_config=_client_config(subdomain, api_key, api_version),
+ path_format_values={},
+ team_id=team_id,
+ job_id=job_id,
+ db_incremental_field_last_value=None,
+ should_use_incremental_field=False,
+ # The history sub-resources document no page-size param; only the parent listing
+ # takes one, so it is sent through the fan-out's parent_params instead.
+ page_size_param=None,
+ parent_endpoint_extra={"paginator": _paginator(api_version), "data_selector": parent_config.data_selector},
+ child_endpoint_extra={"paginator": _paginator(api_version), "data_selector": config.data_selector},
+ ),
+ )
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: dependent_resource,
+ primary_keys=config.primary_keys,
+ 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,
+ )
+
+
def ezofficeinventory_source(
api_key: str,
subdomain: str,
@@ -122,6 +178,9 @@ def ezofficeinventory_source(
) -> SourceResponse:
config = endpoints_for_version(api_version)[endpoint]
+ if config.fanout is not None:
+ return _fanout_source(api_key, subdomain, endpoint, team_id, job_id, api_version)
+
initial_paginator_state: Optional[dict[str, Any]] = None
if resumable_source_manager.can_resume():
resume = resumable_source_manager.load_state()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ezofficeinventory/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ezofficeinventory/settings.py
index 0c752da3fa45..65fa3b5356ea 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/ezofficeinventory/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ezofficeinventory/settings.py
@@ -1,15 +1,25 @@
from dataclasses import dataclass, field
from typing import Optional
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ DependentEndpointConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import ResponseAction
from products.warehouse_sources.backend.types import IncrementalField
+# v2 list endpoints cap page size at 100. Only the fan-out parents send it, to keep the number of
+# requests down against the account's ~60 req/min fair-use limit.
+PAGE_SIZE = 100
+
# Vendor API version labels. v1 is the legacy `*.api` interface (token header, page-number
# pagination); v2 is the GA `/api/v2/` REST interface (bearer token, next-URL pagination).
EZOFFICEINVENTORY_API_VERSION_V1 = "v1"
EZOFFICEINVENTORY_API_VERSION_V2 = "v2"
-@dataclass
+# frozen=False: the shared FanoutEndpointLike protocol is satisfied either way, but the config
+# stays mutable to match the other endpoint-catalog dataclasses in this tree.
+@dataclass(frozen=False)
class EZOfficeInventoryEndpointConfig:
name: str
# Path relative to https://<subdomain>.ezofficeinventory.com (no leading slash).
@@ -26,6 +36,43 @@ class EZOfficeInventoryEndpointConfig:
# Extra static query params (e.g. the `status=checked_out` filter on /assets/filter.api).
extra_params: dict[str, str] = field(default_factory=dict)
should_sync_default: bool = True
+ # When set, the endpoint is a per-parent sub-resource fetched once per row of another
+ # endpoint rather than a flat list.
+ fanout: Optional[DependentEndpointConfig] = None
+ # The three below exist so the config satisfies the shared FanoutEndpointLike protocol.
+ # Nothing on this source reads them: page sizes are set per fan-out through
+ # `parent_params`, and every EZOfficeInventory table is full refresh.
+ page_size: int = PAGE_SIZE
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ default_incremental_field: Optional[str] = None
+
+
+# A parent row retired or deleted between the parent listing and its child fetch answers 404.
+# Ignoring it keeps the fan-out going instead of failing the whole table.
+_PARENT_GONE: list[ResponseAction] = [{"status_code": 404, "action": "ignore"}]
+
+# The history sub-resources are keyed on the record id (`id`), not the user-facing identification
+# number, so the parent id is what binds the child path. It is also injected onto every child row,
+# because a history row carries no reference back to the item or member it belongs to.
+_ASSET_HISTORY_FANOUT = DependentEndpointConfig(
+ parent_name="assets",
+ resolve_param="asset_id",
+ resolve_field="id",
+ include_from_parent=["id"],
+ parent_field_renames={"id": "asset_id"},
+ parent_params={"per_page": PAGE_SIZE},
+ child_response_actions=_PARENT_GONE,
+)
+
+_MEMBER_STOCK_HISTORY_FANOUT = DependentEndpointConfig(
+ parent_name="members",
+ resolve_param="member_id",
+ resolve_field="id",
+ include_from_parent=["id"],
+ parent_field_renames={"id": "member_id"},
+ parent_params={"per_page": PAGE_SIZE},
+ child_response_actions=_PARENT_GONE,
+)
# EZOfficeInventory exposes no general server-side `updated_after`/`created_after` cursor on its
@@ -69,6 +116,12 @@ EZOFFICEINVENTORY_ENDPOINTS: dict[str, EZOfficeInventoryEndpointConfig] = {
primary_keys=["id"],
partition_key="created_at",
),
+ "teams": EZOfficeInventoryEndpointConfig(
+ name="teams",
+ path="teams.api",
+ data_selector="teams",
+ primary_keys=["id"],
+ ),
"locations": EZOfficeInventoryEndpointConfig(
name="locations",
path="locations/get_line_item_locations.api",
@@ -128,6 +181,12 @@ ENDPOINTS = tuple(EZOFFICEINVENTORY_ENDPOINTS.keys())
# `created_at`, so that table can't be datetime-partitioned under v2. The v1-only endpoints
# (`checked_out_assets`, `subgroups`, `labels`, `custom_fields`) have no flat v2 list equivalent
# and stay v1-only — pinned v1 sources keep serving them.
+#
+# Work orders and the two history tables are v2-only. v1 reaches the same records through
+# `tasks.api`, `assets/<id>/history_paginate.api` and `members/<id>/checkin_checkout_history*.api`,
+# but the v1 docs give no response envelope for any of them, and a guessed `data_selector` yields
+# an empty table rather than an error. The v2 OpenAPI spec names all three, so they are wired
+# there only.
EZOFFICEINVENTORY_V2_ENDPOINTS: dict[str, EZOfficeInventoryEndpointConfig] = {
"assets": EZOfficeInventoryEndpointConfig(
name="assets",
@@ -157,6 +216,41 @@ EZOFFICEINVENTORY_V2_ENDPOINTS: dict[str, EZOfficeInventoryEndpointConfig] = {
primary_keys=["id"],
partition_key="created_at",
),
+ "teams": EZOfficeInventoryEndpointConfig(
+ name="teams",
+ path="api/v2/teams",
+ data_selector="teams",
+ primary_keys=["id"],
+ ),
+ "work_orders": EZOfficeInventoryEndpointConfig(
+ name="work_orders",
+ path="api/v2/work_orders",
+ data_selector="work_orders",
+ primary_keys=["id"],
+ partition_key="created_at",
+ ),
+ "asset_checkout_history": EZOfficeInventoryEndpointConfig(
+ name="asset_checkout_history",
+ path="api/v2/assets/{asset_id}/history",
+ data_selector="histories",
+ # The history id is only documented as unique within its asset, so the parent id is part
+ # of the key. It stays correct if the id turns out to be unique account-wide.
+ primary_keys=["asset_id", "id"],
+ partition_key="created_at",
+ fanout=_ASSET_HISTORY_FANOUT,
+ # One request per asset, so it is opt-in rather than on by default.
+ should_sync_default=False,
+ ),
+ "member_stock_histories": EZOfficeInventoryEndpointConfig(
+ name="member_stock_histories",
+ path="api/v2/members/{member_id}/stock_histories",
+ data_selector="stock_histories",
+ primary_keys=["member_id", "id"],
+ partition_key="created_at",
+ fanout=_MEMBER_STOCK_HISTORY_FANOUT,
+ # One request per member, so it is opt-in rather than on by default.
+ should_sync_default=False,
+ ),
"locations": EZOfficeInventoryEndpointConfig(
name="locations",
path="api/v2/locations",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ezofficeinventory/tests/test_ezofficeinventory.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ezofficeinventory/tests/test_ezofficeinventory.py
index 5ef1620c7304..eca46259c170 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/ezofficeinventory/tests/test_ezofficeinventory.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ezofficeinventory/tests/test_ezofficeinventory.py
@@ -72,6 +72,26 @@ def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str,
return param_snapshots
+def _wire_urls(session: mock.MagicMock, responses: list[Response]) -> list[str]:
+ """Wire a mock session and capture each request's URL at send time.
+
+ Fan-out binds the parent id into the child path, so the URL — not the params — is what
+ proves the right parent was requested.
+ """
+ session.headers = {}
+ urls: list[str] = []
+
+ def _prepare(request: Any) -> mock.MagicMock:
+ urls.append(request.url)
+ prepared = mock.MagicMock()
+ prepared.url = request.url
+ return prepared
+
+ session.prepare_request.side_effect = _prepare
+ session.send.side_effect = responses
+ return urls
+
+
def _rows(source_response) -> list[dict[str, Any]]:
return [row for page in source_response.items() for row in page]
@@ -379,11 +399,114 @@ class TestV2Pagination:
manager.save_state.assert_not_called()
@mock.patch(CLIENT_SESSION_PATCH)
- def test_uses_renamed_v2_selector(self, MockSession) -> None:
- # v2 renamed the inventory list key from `volatile_assets` to `inventory`; a wrong selector
- # would silently yield zero rows.
+ @pytest.mark.parametrize(
+ ("endpoint", "body_key", "row"),
+ [
+ # v2 renamed the inventory list key from `volatile_assets` to `inventory`.
+ ("inventories", "inventory", {"identifier": 7}),
+ # The v2 path is `tasks`-free: work orders list under `work_orders`.
+ ("work_orders", "work_orders", {"id": 3}),
+ ("teams", "teams", {"id": 4}),
+ ],
+ )
+ def test_uses_v2_selector(self, MockSession, endpoint: str, body_key: str, row: dict) -> None:
+ # A selector that does not match the response envelope silently yields zero rows.
session = MockSession.return_value
- _wire(session, [_response({"inventory": [{"identifier": 7}], "metadata": {"next_page": None}})])
+ _wire(session, [_response({body_key: [row], "metadata": {"next_page": None}})])
- rows = _rows(_source("inventories", _make_manager(), api_version=EZOFFICEINVENTORY_API_VERSION_V2))
- assert rows == [{"identifier": 7}]
+ rows = _rows(_source(endpoint, _make_manager(), api_version=EZOFFICEINVENTORY_API_VERSION_V2))
+ assert rows == [row]
+
+
+class TestHistoryFanout:
+ """The history tables are per-item sub-resources fanned out over their list endpoint."""
+
+ @staticmethod
+ def _fanout_source(endpoint: str, manager: mock.MagicMock):
+ return _source(endpoint, manager, api_version=EZOFFICEINVENTORY_API_VERSION_V2)
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_fetches_each_parent_and_injects_parent_id(self, MockSession) -> None:
+ session = MockSession.return_value
+ urls = _wire_urls(
+ session,
+ [
+ _response(
+ {"assets": [{"id": 1, "identifier": "A1"}, {"id": 2, "identifier": "A2"}], "metadata": {}},
+ ),
+ _response({"histories": [{"id": 10}], "metadata": {}}),
+ _response({"histories": [{"id": 20}], "metadata": {}}),
+ ],
+ )
+
+ rows = _rows(self._fanout_source("asset_checkout_history", _make_manager()))
+
+ # The child path binds the parent's record id, not its identification number.
+ assert urls[1:] == [
+ "https://acme.ezofficeinventory.com/api/v2/assets/1/history",
+ "https://acme.ezofficeinventory.com/api/v2/assets/2/history",
+ ]
+ # A history row carries no back-reference to its asset, so the parent id is injected —
+ # without it the composite primary key would collapse every asset's history together.
+ assert rows == [{"id": 10, "asset_id": 1}, {"id": 20, "asset_id": 2}]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_member_fanout_binds_member_id(self, MockSession) -> None:
+ session = MockSession.return_value
+ urls = _wire_urls(
+ session,
+ [
+ _response({"members": [{"id": 8}], "metadata": {}}),
+ _response({"stock_histories": [{"id": 99}], "metadata": {}}),
+ ],
+ )
+
+ rows = _rows(self._fanout_source("member_stock_histories", _make_manager()))
+
+ assert urls[1] == "https://acme.ezofficeinventory.com/api/v2/members/8/stock_histories"
+ assert rows == [{"id": 99, "member_id": 8}]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_parent_deleted_mid_sync_does_not_fail_the_table(self, MockSession) -> None:
+ # An asset retired or deleted between the parent listing and its history fetch answers
+ # 404. Failing there would lose every other asset's history for the whole sync.
+ session = MockSession.return_value
+ _wire(
+ session,
+ [
+ _response({"assets": [{"id": 1}, {"id": 2}], "metadata": {}}),
+ _response({"messages": {"errors": ["Resource not found"]}}, status_code=404),
+ _response({"histories": [{"id": 20}], "metadata": {}}),
+ ],
+ )
+
+ rows = _rows(self._fanout_source("asset_checkout_history", _make_manager()))
+ assert rows == [{"id": 20, "asset_id": 2}]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_child_pages_are_followed_per_parent(self, MockSession) -> None:
+ session = MockSession.return_value
+ next_url = "https://acme.ezofficeinventory.com/api/v2/assets/1/history?page=2"
+ manager = _make_manager()
+ _wire(
+ session,
+ [
+ _response({"assets": [{"id": 1}], "metadata": {}}),
+ _response({"histories": [{"id": 10}], "metadata": {"next_page": next_url}}),
+ _response({"histories": [{"id": 11}], "metadata": {"next_page": None}}),
+ ],
+ )
+
+ rows = _rows(self._fanout_source("asset_checkout_history", manager))
+
+ assert rows == [{"id": 10, "asset_id": 1}, {"id": 11, "asset_id": 1}]
+ # A fan-out run is full refresh with no resumable cursor: a mid-run checkpoint would
+ # point at a child page without recording which parents were already walked.
+ manager.save_state.assert_not_called()
+
+ def test_source_response_keys_on_parent_and_row_id(self) -> None:
+ response = self._fanout_source("asset_checkout_history", _make_manager())
+ assert response.name == "asset_checkout_history"
+ assert response.primary_keys == ["asset_id", "id"]
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == ["created_at"]