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(warehouse_sources): add lightspeed retail inventory and lookup tables (#114503)

Tom Owers779d9a5985e0
diff --git a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
index ad870bff2d97..85fc4a231986 100644
--- a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
+++ b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
@@ -761,8 +761,6 @@
1 products/warehouse_sources/backend/temporal/data_imports/sources/lever/settings.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/lightdash/settings.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/lightfield/settings.py
-1 products/warehouse_sources/backend/temporal/data_imports/sources/lightspeed_retail/lightspeed_retail.py
-1 products/warehouse_sources/backend/temporal/data_imports/sources/lightspeed_retail/settings.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/linear/linear.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/linear/settings.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/linearb/linearb.py
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 a279d144df98..91b139f7d3c0 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
@@ -5170,10 +5170,10 @@ Today (8): `customers`, `inventory`, `outlets`, `products`, `registers`, `sales`
Diffed against: <https://x-series-api.lightspeedhq.com/reference/listcustomers>
-- [ ] `consignments (GET /api/2.0/consignments)` — stock orders, transfers and stocktakes - the entire inbound inventory movement side is missing (high)
-- [ ] `consignment_products (GET /api/2.0/consignments/{id}/products)` — line items of each stock order, needed for received-vs-ordered and cost analysis (high)
-- [ ] `suppliers (GET /api/2.0/suppliers)` — lookup resolving the supplier_id carried on products and consignments (high)
-- [ ] `payment_types (GET /api/2.0/payment_types)` — lookup resolving payment type IDs on the sale payments we already sync (high)
+- [x] `consignments (GET /api/2.0/consignments)` — stock orders, transfers and stocktakes - the entire inbound inventory movement side is missing (high)
+- [x] `consignment_products (GET /api/2.0/consignments/{id}/products)` — line items of each stock order, needed for received-vs-ordered and cost analysis (high)
+- [x] `suppliers (GET /api/2.0/suppliers)` — lookup resolving the supplier_id carried on products and consignments (high)
+- [x] `payment_types (GET /api/2.0/payment_types)` — lookup resolving payment type IDs on the sale payments we already sync (high)
- [ ] `product_categories (GET /api/2.0/product_categories)` — lookup for category IDs on products - required for any category-level sales breakdown (high)
- [ ] `brands (GET /api/2.0/brands)` — lookup resolving brand_id on products (medium)
- [ ] `customer_groups (+ /customer_groups/{id}/customers)` — customer segment membership table for cohort and loyalty analysis (medium)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/lightspeed_retail/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lightspeed_retail/canonical_descriptions.py
index c34932a20a56..52862de22dfe 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/lightspeed_retail/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lightspeed_retail/canonical_descriptions.py
@@ -135,4 +135,73 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
is_default="Whether this is the default tax applied to sales.",
),
},
+ "consignments": {
+ "description": "An inventory movement in Lightspeed Retail: a supplier order, outlet transfer, stocktake or supplier return.",
+ "docs_url": "https://x-series-api.lightspeedhq.com/reference/getconsignments",
+ "columns": _columns(
+ type="Consignment type: SUPPLIER, OUTLET, STOCKTAKE or RETURN.",
+ status="Workflow status of the consignment (e.g. OPEN, SENT, DISPATCHED, RECEIVED, CANCELLED, STOCKTAKE_COMPLETE).",
+ name="Consignment name. For orders, this is the note shown in the UI.",
+ reference="Order number.",
+ outlet_id="ID of the outlet where the stock is received.",
+ source_outlet_id="ID of the outlet the stock comes from. Set for stock transfers only.",
+ supplier_id="ID of the supplier the stock is ordered from.",
+ supplier_invoice="Supplier invoice number.",
+ consignment_date="Date the consignment was created.",
+ due_at="Date the consignment is due.",
+ received_at="Date the consignment was received.",
+ total_count_gain="Number of items over the expected level.",
+ total_count_loss="Number of items below the expected level.",
+ total_cost_gain="Cost of items over the expected level.",
+ total_cost_loss="Cost of items below the expected level.",
+ created_at="Time at which the consignment was created.",
+ updated_at="Time at which the consignment was last updated.",
+ ),
+ },
+ "consignment_products": {
+ "description": "A product line item on a Lightspeed Retail consignment, with the expected and received counts.",
+ "docs_url": "https://x-series-api.lightspeedhq.com/reference/listproductsbyconsignmentid",
+ "columns": {
+ "consignment_id": "ID of the consignment the line item belongs to.",
+ "product_id": "ID of the product.",
+ "product_sku": "SKU of the product.",
+ "count": "Expected item count.",
+ "received": "Observed (received) item count.",
+ "cost": "Cost of the item.",
+ "status": "Status of the item: PENDING or SUCCESS.",
+ "is_included": "Whether the item was included via a filter. Always true for a full count with no filters.",
+ "version": _COMMON_COLUMNS["version"],
+ "created_at": "Time at which the line item was created.",
+ "updated_at": "Time at which the line item was last updated.",
+ "deleted_at": _COMMON_COLUMNS["deleted_at"],
+ },
+ },
+ "suppliers": {
+ "description": "A supplier that products are ordered from in Lightspeed Retail.",
+ "docs_url": "https://x-series-api.lightspeedhq.com/reference/listsuppliers",
+ "columns": _columns(
+ name="The supplier's name.",
+ description="The supplier's description.",
+ source="Origin of the supplier record (e.g. USER, SHOPIFY).",
+ default_markup="Default markup for the supplier. Used for record keeping only; it does not affect products.",
+ contact="Contact information for the supplier.",
+ ),
+ },
+ "payment_types": {
+ "description": "A payment type (e.g. cash, card, gift card) configured in Lightspeed Retail.",
+ "docs_url": "https://x-series-api.lightspeedhq.com/reference/listpaymenttypes",
+ "columns": _columns(
+ name="The payment type's name.",
+ type_id="ID of the global payment type. Several payment types can share the same type_id.",
+ payment_type="The global payment type this payment type is based on.",
+ config="Payment type configuration. The shape varies by payment type.",
+ outlet_ids="IDs of the outlets this payment type is associated with.",
+ disabled="Whether the payment type is disabled.",
+ gateway="Whether the payment type is a payment gateway type.",
+ internal="Whether the payment type is for internal use only.",
+ is_editable="Whether the payment type can be edited.",
+ name_changed_by_user="Whether the retailer customized the name.",
+ created_at="Time at which the payment type was created.",
+ ),
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/lightspeed_retail/lightspeed_retail.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lightspeed_retail/lightspeed_retail.py
index c387cdd3be00..47865b29d26f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/lightspeed_retail/lightspeed_retail.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lightspeed_retail/lightspeed_retail.py
@@ -1,5 +1,6 @@
import re
import dataclasses
+from collections.abc import Callable, Iterable
from typing import Any, Optional
from requests import Request, Response
@@ -9,24 +10,29 @@ 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
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import 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
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.lightspeed_retail.settings import (
LIGHTSPEED_RETAIL_ENDPOINTS,
+ PAGE_SIZE,
)
-# X-Series v2.0 list pages cap at 200 items.
-PAGE_SIZE = 200
-
[email protected](frozen=True)
class LightspeedRetailResumeConfig:
# X-Series keyset pagination: `after=<version>` where version is the max
# record version of the previous page — one integer fully describes where
# to pick back up.
- after: int
+ after: Optional[int] = None
+ # Fan-out endpoints checkpoint the `build_dependent_resource` shape instead: which parent
+ # consignments finished and where the current one stopped.
+ fanout_state: Optional[dict[str, Any]] = None
def _clean_domain_prefix(domain_prefix: str) -> str:
@@ -123,13 +129,40 @@ def lightspeed_retail_source(
) -> SourceResponse:
config = LIGHTSPEED_RETAIL_ENDPOINTS[endpoint]
+ client_config: ClientConfig = {
+ "base_url": _base_url(domain_prefix, api_version),
+ # Bearer auth via the framework so the token is redacted from logs and errors.
+ "auth": {"type": "bearer", "token": api_token},
+ "paginator": LightspeedRetailPaginator(),
+ }
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+
+ if config.fanout is not None:
+
+ def save_fanout_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ if state:
+ resumable_source_manager.save_state(LightspeedRetailResumeConfig(fanout_state=state))
+
+ child = build_dependent_resource(
+ endpoint_configs=LIGHTSPEED_RETAIL_ENDPOINTS,
+ child_endpoint=endpoint,
+ fanout=config.fanout,
+ client_config=client_config,
+ parent_endpoint_extra={"data_selector": "data"},
+ child_endpoint_extra={"data_selector": "data"},
+ page_size_param="page_size",
+ path_format_values={},
+ team_id=team_id,
+ job_id=job_id,
+ db_incremental_field_last_value=None,
+ resume_hook=save_fanout_checkpoint,
+ initial_paginator_state=resume.fanout_state if resume else None,
+ )
+ return _source_response(endpoint, lambda: child)
+
rest_config: RESTAPIConfig = {
- "client": {
- "base_url": _base_url(domain_prefix, api_version),
- # Bearer auth via the framework so the token is redacted from logs and errors.
- "auth": {"type": "bearer", "token": api_token},
- "paginator": LightspeedRetailPaginator(),
- },
+ "client": client_config,
"resource_defaults": {},
"resources": [
{
@@ -147,10 +180,8 @@ def lightspeed_retail_source(
# The version cursor doubles as the incremental watermark: on a resumed run seed
# from saved state, otherwise (incremental) seed from the stored watermark.
initial_after: Optional[int] = None
- if resumable_source_manager.can_resume():
- resume = resumable_source_manager.load_state()
- if resume is not None:
- initial_after = resume.after
+ if resume is not None:
+ initial_after = resume.after
elif should_use_incremental_field:
initial_after = _to_version(db_incremental_field_last_value)
@@ -171,10 +202,17 @@ def lightspeed_retail_source(
initial_paginator_state=initial_paginator_state,
)
+ return _source_response(endpoint, lambda: resource, resource.column_hints)
+
+
+def _source_response(
+ endpoint: str, items: Callable[[], Iterable[Any]], column_hints: Optional[dict[str, Any]] = None
+) -> SourceResponse:
+ config = LIGHTSPEED_RETAIL_ENDPOINTS[endpoint]
return SourceResponse(
name=endpoint,
- items=lambda: resource,
- primary_keys=[config.primary_key],
+ items=items,
+ primary_keys=config.primary_key,
partition_count=1,
partition_size=1,
partition_mode="datetime" if config.partition_key else None,
@@ -182,7 +220,7 @@ def lightspeed_retail_source(
partition_keys=[config.partition_key] if config.partition_key else None,
# Keyset pagination on the monotonic version yields ascending version order.
sort_mode="asc",
- column_hints=resource.column_hints,
+ column_hints=column_hints,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/lightspeed_retail/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lightspeed_retail/settings.py
index fd265d7783b6..23d419764b6b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/lightspeed_retail/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lightspeed_retail/settings.py
@@ -1,8 +1,14 @@
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.types import IncrementalField, IncrementalFieldType
+# X-Series v2.0 list pages cap at 200 items.
+PAGE_SIZE = 200
+
# Every X-Series v2.0 record carries a monotonically increasing integer
# `version`; the same `after=<version>` param used for keyset pagination doubles
# as a lossless incremental cursor, so the menu is shared across endpoints.
@@ -16,15 +22,18 @@ _VERSION_INCREMENTAL_FIELDS: list[IncrementalField] = [
]
-@dataclass
+@dataclass(frozen=True)
class LightspeedRetailEndpointConfig:
name: str
path: str
- primary_key: str = "id"
+ primary_key: list[str] = field(default_factory=lambda: ["id"])
incremental_fields: list[IncrementalField] = field(default_factory=lambda: list(_VERSION_INCREMENTAL_FIELDS))
# Stable creation-time field used for datetime partitioning. Never a
# version/updated-style field, which would rewrite partitions on every sync.
partition_key: Optional[str] = None
+ fanout: Optional[DependentEndpointConfig] = None
+ page_size: int = PAGE_SIZE
+ default_incremental_field: Optional[str] = None
LIGHTSPEED_RETAIL_ENDPOINTS: dict[str, LightspeedRetailEndpointConfig] = {
@@ -63,6 +72,36 @@ LIGHTSPEED_RETAIL_ENDPOINTS: dict[str, LightspeedRetailEndpointConfig] = {
name="taxes",
path="/taxes",
),
+ "consignments": LightspeedRetailEndpointConfig(
+ name="consignments",
+ path="/consignments",
+ partition_key="created_at",
+ ),
+ "consignment_products": LightspeedRetailEndpointConfig(
+ name="consignment_products",
+ path="/consignments/{consignment_id}/products",
+ # Line items carry no id of their own; a product appears once per consignment.
+ primary_key=["consignment_id", "product_id"],
+ # Child versions only ascend within one consignment, so a fan-out run is not in
+ # global version order and can't drive a watermark.
+ incremental_fields=[],
+ partition_key="created_at",
+ fanout=DependentEndpointConfig(
+ parent_name="consignments",
+ resolve_param="consignment_id",
+ resolve_field="id",
+ include_from_parent=["id"],
+ parent_field_renames={"id": "consignment_id"},
+ ),
+ ),
+ "suppliers": LightspeedRetailEndpointConfig(
+ name="suppliers",
+ path="/suppliers",
+ ),
+ "payment_types": LightspeedRetailEndpointConfig(
+ name="payment_types",
+ path="/payment_types",
+ ),
}
ENDPOINTS = tuple(LIGHTSPEED_RETAIL_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/lightspeed_retail/tests/test_lightspeed_retail.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lightspeed_retail/tests/test_lightspeed_retail.py
index bc29fb4747c8..23bc4ba0dc58 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/lightspeed_retail/tests/test_lightspeed_retail.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lightspeed_retail/tests/test_lightspeed_retail.py
@@ -175,3 +175,55 @@ class TestGetRows:
assert [item["id"] for batch in batches for item in batch] == ["1"]
assert session.send.call_count == 2
assert params[1]["after"] == 0
+
+ @pytest.mark.parametrize(
+ "resume_state, expected_paths, expected_rows",
+ [
+ (
+ None,
+ [
+ "/consignments",
+ "/consignments/c1/products",
+ "/consignments/c1/products",
+ "/consignments/c2/products",
+ "/consignments/c2/products",
+ "/consignments",
+ ],
+ [("c1", "p1"), ("c2", "p1")],
+ ),
+ (
+ LightspeedRetailResumeConfig(fanout_state={"completed": ["/consignments/c1/products"]}),
+ [
+ "/consignments",
+ "/consignments/c2/products",
+ "/consignments/c2/products",
+ "/consignments",
+ ],
+ [("c2", "p1")],
+ ),
+ ],
+ )
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_consignment_products_fan_out_over_consignments(
+ self, mock_session, resume_state, expected_paths, expected_rows
+ ):
+ session = mock_session.return_value
+ child_pages = {
+ "c1": [_response([{"product_id": "p1", "version": 5}]), _response([])],
+ "c2": [_response([{"product_id": "p1", "version": 6}]), _response([])],
+ }
+ responses = [_response([{"id": "c1", "version": 1}, {"id": "c2", "version": 2}], max_version=2)]
+ for consignment_id in ("c1", "c2"):
+ if expected_paths.count(f"/consignments/{consignment_id}/products"):
+ responses.extend(child_pages[consignment_id])
+ responses.append(_response([]))
+ _wire(session, responses)
+
+ manager = _make_manager(resume_state)
+ batches = _run(manager, endpoint="consignment_products")
+
+ requested = [call.args[0].url for call in session.prepare_request.call_args_list]
+ assert [url.split("/api/2026-01")[1] for url in requested] == expected_paths
+ rows = [item for batch in batches for item in batch]
+ assert [(row["consignment_id"], row["product_id"]) for row in rows] == expected_rows
+ assert all("_consignments_id" not in row for row in rows)