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(data-warehouse): add 3 missing tables to the Lodgify source (#118906)

Tom Owers0374aece69bb
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 687b48ccd348..e4f3b16ad00b 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
@@ -7378,9 +7378,9 @@ Today (3): `bookings`, `properties`, `rooms`
Diffed against: <https://docs.lodgify.com/llms.txt>
-- [ ] `Availability calendar for all properties (Lodgify Public API v2)` — measure available nights and blocked capacity to calculate occupancy accurately (high)
-- [ ] `Nightly rates (Lodgify Public API v2)` — compare offered nightly prices with booked revenue and seasonal demand (medium)
-- [ ] `External bookings by Booking id (Lodgify Public API v2)` — link reservations to external channel bookings for reconciliation and channel analysis (medium)
+- [x] `Availability calendar for all properties (Lodgify Public API v2)` — measure available nights and blocked capacity to calculate occupancy accurately (high)
+- [x] `Nightly rates (Lodgify Public API v2)` — compare offered nightly prices with booked revenue and seasonal demand (medium)
+- [x] `External bookings by Booking id (Lodgify Public API v2)` — link reservations to external channel bookings for reconciliation and channel analysis (medium)
Note: Fetched the official llms.txt and compared its complete v2 operation list with the source routes. Reference pages and Swagger probes returned access blocks, so unverified paths are omitted. Bookings already request transactions and quote details; excluded payment links, webhooks, write operations, and rate settings. Calendar imports need date ranges, while external bookings need booking fan-out.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/lodgify/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lodgify/canonical_descriptions.py
index 505faa667b10..b7dd5c2800c1 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/lodgify/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lodgify/canonical_descriptions.py
@@ -40,4 +40,40 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"units": "Number of units with this room type.",
},
},
+ "availability": {
+ "description": "Availability calendar periods for each property room type, for one year from the sync date.",
+ "docs_url": "https://docs.lodgify.com/reference/getcalendarbyuser",
+ "columns": {
+ "user_id": "Identifier of the Lodgify account that owns the property.",
+ "property_id": "Property identifier.",
+ "room_type_id": "Room type identifier.",
+ "start": "First day of the period.",
+ "end": "Last day of the period.",
+ "available": "Number of units available in the period.",
+ "closed_period": "Closed period that blocks the dates, if any.",
+ "bookings": "Bookings that occupy the period, with their status.",
+ "channel_calendars": "External channel calendars that block the period.",
+ },
+ },
+ "rates_calendar": {
+ "description": "Nightly rates for each property room type, for one year from the sync date.",
+ "docs_url": "https://docs.lodgify.com/reference/ratescalendar-v2",
+ "columns": {
+ "property_id": "Property identifier.",
+ "room_type_id": "Room type identifier.",
+ "date": "Day that the rates apply to.",
+ "is_default": "Whether the day uses the default rate.",
+ "prices": "Prices for the day, with minimum stay, maximum stay, and price per extra guest.",
+ },
+ },
+ "external_bookings": {
+ "description": "External channel bookings that belong to each booking.",
+ "docs_url": "https://docs.lodgify.com/reference/getexternalbookingsasync",
+ "columns": {
+ "booking_id": "Identifier of the Lodgify booking.",
+ "booking_updated_at": "Time of the latest update to the Lodgify booking.",
+ "created_at": "Time when the external booking was created.",
+ "content": "Contents of the external booking.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/lodgify/lodgify.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lodgify/lodgify.py
index dc99e9b970e0..07cf58437e7a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/lodgify/lodgify.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lodgify/lodgify.py
@@ -1,4 +1,4 @@
-from datetime import datetime
+from datetime import UTC, date, datetime, timedelta
from typing import Any
from requests import HTTPError
@@ -29,6 +29,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.typ
from products.warehouse_sources.backend.temporal.data_imports.sources.lodgify.settings import (
AUTH_ERROR,
BASE_URL,
+ CALENDAR_WINDOW_DAYS,
ENDPOINTS,
PAGE_SIZE,
PATHS,
@@ -40,6 +41,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.lodgify.se
@frozen
class LodgifyResumeConfig:
paginator_state: dict[str, Any]
+ # Calendar tables only. Kept so a resumed sync reuses the window it started with.
+ window_start: str | None = None
+ window_end: str | None = None
def validate_credentials(api_key: str) -> tuple[bool, str | None]:
@@ -89,6 +93,34 @@ def list_resource(endpoint: str, watermark: datetime | str | None = None) -> End
}
+@frozen
+class CalendarWindow:
+ start: str
+ end: str
+
+
+def calendar_window(today: date) -> CalendarWindow:
+ return CalendarWindow(start=today.isoformat(), end=(today + timedelta(days=CALENDAR_WINDOW_DAYS)).isoformat())
+
+
+def availability_resource(start: str, end: str) -> EndpointResource:
+ return {
+ "name": "availability",
+ "endpoint": {
+ "path": PATHS["availability"],
+ "params": {"start": start, "end": end, "includeDetails": "true"},
+ "paginator": "single_page",
+ "data_selector": "$",
+ "data_selector_required": True,
+ },
+ }
+
+
+def flatten_availability_periods(calendar: dict[str, Any]) -> list[dict[str, Any]]:
+ keys = {key: calendar.get(key) for key in ("user_id", "property_id", "room_type_id")}
+ return [{**keys, **period} for period in calendar.get("periods") or []]
+
+
def lodgify_source(
api_key: str,
endpoint: str,
@@ -102,14 +134,22 @@ def lodgify_source(
raise ValueError(f"Unsupported Lodgify table: {endpoint}")
initial_state = None
+ window: CalendarWindow | None = None
if resumable_source_manager.can_resume():
saved = resumable_source_manager.load_state()
if saved is not None:
initial_state = saved.paginator_state
+ if saved.window_start and saved.window_end:
+ window = CalendarWindow(start=saved.window_start, end=saved.window_end)
+ if window is None:
+ window = calendar_window(datetime.now(UTC).date())
+ start, end = window.start, window.end
def save_checkpoint(state: dict[str, Any] | None) -> None:
if state is not None:
- resumable_source_manager.save_state(LodgifyResumeConfig(paginator_state=state))
+ resumable_source_manager.save_state(
+ LodgifyResumeConfig(paginator_state=state, window_start=start, window_end=end)
+ )
config: RESTAPIConfig = {
"client": {
@@ -120,7 +160,65 @@ def lodgify_source(
},
"resources": [],
}
- if endpoint == "rooms":
+ if endpoint == "availability":
+ config["resources"] = [availability_resource(start, end)]
+ resource = rest_api_resource(
+ config, team_id, job_id, None, resume_hook=save_checkpoint, initial_paginator_state=initial_state
+ )
+ resource.add_map(flatten_availability_periods)
+ elif endpoint == "rates_calendar":
+ # The availability calendar lists every property and room type pair in one request.
+ config["resources"] = [
+ availability_resource(start, end),
+ {
+ "name": "rates_calendar",
+ "include_from_parent": ["property_id", "room_type_id"],
+ "endpoint": {
+ "path": PATHS["rates_calendar"],
+ "params": {
+ "HouseId": {"type": "resolve", "resource": "availability", "field": "property_id"},
+ "RoomTypeId": {"type": "resolve", "resource": "availability", "field": "room_type_id"},
+ "StartDate": start,
+ "EndDate": end,
+ },
+ "paginator": "single_page",
+ "data_selector": "calendar_items",
+ "data_selector_required": True,
+ },
+ },
+ ]
+ resources = rest_api_resources(
+ config, team_id, job_id, None, resume_hook=save_checkpoint, initial_paginator_state=initial_state
+ )
+ resource = next(resource for resource in resources if resource.name == "rates_calendar")
+ resource.add_map(
+ rename_parent_fields("availability", {"property_id": "property_id", "room_type_id": "room_type_id"})
+ )
+ # The primary key needs a day, and the API marks the date as nullable.
+ resource.add_filter(lambda row: row.get("date") is not None)
+ elif endpoint == "external_bookings":
+ watermark = db_incremental_field_last_value if should_use_incremental_field else None
+ config["resources"] = [
+ list_resource("bookings", watermark),
+ {
+ "name": "external_bookings",
+ "include_from_parent": ["id", "updated_at"],
+ "endpoint": {
+ "path": PATHS["external_bookings"],
+ "params": {"id": {"type": "resolve", "resource": "bookings", "field": "id"}},
+ "paginator": "single_page",
+ "data_selector": "external_bookings",
+ "data_selector_required": True,
+ },
+ "columns": {"created_at": {"data_type": "timestamp"}, "booking_updated_at": {"data_type": "timestamp"}},
+ },
+ ]
+ resources = rest_api_resources(
+ config, team_id, job_id, None, resume_hook=save_checkpoint, initial_paginator_state=initial_state
+ )
+ resource = next(resource for resource in resources if resource.name == "external_bookings")
+ resource.add_map(rename_parent_fields("bookings", {"id": "booking_id", "updated_at": "booking_updated_at"}))
+ elif endpoint == "rooms":
config["resources"] = [
list_resource("properties"),
{
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/lodgify/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lodgify/settings.py
index ae384029f4a4..3521af80e3a7 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/lodgify/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lodgify/settings.py
@@ -2,19 +2,42 @@ from products.warehouse_sources.backend.types import IncrementalField, Increment
BASE_URL = "https://api.lodgify.com/v2/"
PAGE_SIZE = 50
-ENDPOINTS = ("properties", "bookings", "rooms")
-PATHS = {"properties": "properties", "bookings": "reservations/bookings", "rooms": "properties/{id}/rooms"}
-PRIMARY_KEYS = {"properties": ["id"], "bookings": ["id"], "rooms": ["property_id", "id"]}
-INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
- name: [
+# The availability and rates calendars need a date range; sync a rolling year from today.
+CALENDAR_WINDOW_DAYS = 365
+ENDPOINTS = ("properties", "bookings", "rooms", "availability", "rates_calendar", "external_bookings")
+PATHS = {
+ "properties": "properties",
+ "bookings": "reservations/bookings",
+ "rooms": "properties/{id}/rooms",
+ "availability": "availability",
+ "rates_calendar": "rates/calendar?HouseId={HouseId}&RoomTypeId={RoomTypeId}",
+ "external_bookings": "reservations/bookings/{id}/externalBookings",
+}
+PRIMARY_KEYS = {
+ "properties": ["id"],
+ "bookings": ["id"],
+ "rooms": ["property_id", "id"],
+ "availability": ["property_id", "room_type_id", "start"],
+ "rates_calendar": ["property_id", "room_type_id", "date"],
+ "external_bookings": ["booking_id", "created_at"],
+}
+
+
+def _incremental_field(field: str) -> list[IncrementalField]:
+ return [
{
- "field": "updated_at",
+ "field": field,
"type": IncrementalFieldType.DateTime,
"field_type": IncrementalFieldType.DateTime,
- "label": "updated_at",
+ "label": field,
}
]
- for name in ("properties", "bookings")
+
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ "properties": _incremental_field("updated_at"),
+ "bookings": _incremental_field("updated_at"),
+ "external_bookings": _incremental_field("booking_updated_at"),
}
AUTH_ERROR = "Lodgify rejected the API key. Copy your key from Settings > Public API and reconnect."
PERMISSION_ERROR = "Lodgify denied access. Check your account's API access and reconnect."
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/lodgify/tests/test_lodgify.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lodgify/tests/test_lodgify.py
index ff805968f7b1..19f0a8cc6eab 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/lodgify/tests/test_lodgify.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lodgify/tests/test_lodgify.py
@@ -1,6 +1,7 @@
from datetime import UTC, datetime
import pytest
+import time_machine
from requests import HTTPError
@@ -105,6 +106,190 @@ def test_room_fanout(resume: bool) -> None:
]
+ "calendars,expected_rows",
+ [
+ ([], []),
+ ([{"user_id": 5, "property_id": 10, "room_type_id": 11, "periods": None}], []),
+ (
+ [
+ {
+ "user_id": 5,
+ "property_id": 10,
+ "room_type_id": 11,
+ "periods": [
+ {"start": "2026-03-01", "end": "2026-03-04", "available": 1, "bookings": []},
+ {"start": "2026-03-05", "end": "2026-03-07", "available": 0, "bookings": [{"id": 7}]},
+ ],
+ },
+ {"user_id": 5, "property_id": 20, "room_type_id": 21, "periods": []},
+ ],
+ [
+ {
+ "user_id": 5,
+ "property_id": 10,
+ "room_type_id": 11,
+ "start": "2026-03-01",
+ "end": "2026-03-04",
+ "available": 1,
+ "bookings": [],
+ },
+ {
+ "user_id": 5,
+ "property_id": 10,
+ "room_type_id": 11,
+ "start": "2026-03-05",
+ "end": "2026-03-07",
+ "available": 0,
+ "bookings": [{"id": 7}],
+ },
+ ],
+ ),
+ ],
+)
+@time_machine.travel(datetime(2026, 3, 1, 23, 30, tzinfo=UTC), tick=False)
+def test_availability_rows(calendars: list[dict], expected_rows: list[dict]) -> None:
+ result = driver().run(
+ "availability",
+ [ScriptedResponse(json=calendars)],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2026-01-01T00:00:00Z",
+ )
+
+ assert result.raised is None
+ assert result.rows == expected_rows
+ assert result.paths == ["/v2/availability"]
+ assert result.queries == [
+ {"start": ("2026-03-01",), "end": ("2027-03-01",), "includeDetails": ("true",)},
+ ]
+
+
[email protected]("resume", [False, True])
+@time_machine.travel(datetime(2026, 3, 1, tzinfo=UTC), tick=False)
+def test_rates_calendar_fanout(resume: bool) -> None:
+ state = LodgifyResumeConfig(
+ paginator_state={
+ "completed": ["rates/calendar?HouseId=10&RoomTypeId=11"],
+ "current": None,
+ "child_state": None,
+ },
+ window_start="2026-02-27",
+ window_end="2027-02-27",
+ )
+ result = driver().run(
+ "rates_calendar",
+ [
+ ScriptedResponse(
+ json=[
+ {"property_id": 10, "room_type_id": 11, "periods": []},
+ {"property_id": 20, "room_type_id": 21, "periods": None},
+ {"property_id": 30, "room_type_id": 31, "periods": []},
+ ]
+ ),
+ *(
+ []
+ if resume
+ else [ScriptedResponse(json={"calendar_items": [{"date": "2026-03-01", "is_default": True}]})]
+ ),
+ ScriptedResponse(
+ json={
+ "calendar_items": [
+ {"date": None, "is_default": True, "prices": []},
+ {"date": "2026-03-02", "is_default": False, "prices": [{"min_stay": 2}]},
+ ],
+ "rate_settings": {"currency_code": "EUR"},
+ }
+ ),
+ ScriptedResponse(json={"calendar_items": None}),
+ ],
+ resume_state=state if resume else None,
+ )
+
+ assert result.raised is None
+ assert result.rows == [
+ *([] if resume else [{"date": "2026-03-01", "is_default": True, "property_id": 10, "room_type_id": 11}]),
+ {"date": "2026-03-02", "is_default": False, "prices": [{"min_stay": 2}], "property_id": 20, "room_type_id": 21},
+ ]
+ assert result.response is not None
+ assert result.response.primary_keys == ["property_id", "room_type_id", "date"]
+ assert result.paths == ["/v2/availability"] + ["/v2/rates/calendar"] * (2 if resume else 3)
+ assert result.params("HouseId") == [None, *([] if resume else ["10"]), "20", "30"]
+ assert result.params("RoomTypeId") == [None, *([] if resume else ["11"]), "21", "31"]
+ # A resumed sync keeps the window it started with, even after the date has moved on.
+ assert set(result.params("StartDate")[1:]) == ({"2026-02-27"} if resume else {"2026-03-01"})
+ assert set(result.params("EndDate")[1:]) == ({"2027-02-27"} if resume else {"2027-03-01"})
+ assert result.saved_states[-1].window_start == ("2026-02-27" if resume else "2026-03-01")
+ assert result.saved_states[-1].paginator_state["completed"] == [
+ "rates/calendar?HouseId=10&RoomTypeId=11",
+ "rates/calendar?HouseId=20&RoomTypeId=21",
+ "rates/calendar?HouseId=30&RoomTypeId=31",
+ ]
+
+
+ "incremental,watermark,expected",
+ [
+ (False, "2026-01-01T00:00:00Z", None),
+ (True, None, None),
+ (True, "2026-01-01T00:00:00Z", "2026-01-01T00:00:00+00:00"),
+ ],
+)
+def test_external_bookings_fanout(incremental: bool, watermark: str | None, expected: str | None) -> None:
+ result = driver().run(
+ "external_bookings",
+ [
+ ScriptedResponse(
+ json={
+ "items": [
+ {"id": 100, "updated_at": "2026-02-01T10:00:00Z"},
+ {"id": 200, "updated_at": "2026-02-02T10:00:00Z"},
+ ]
+ }
+ ),
+ ScriptedResponse(
+ json={
+ "external_bookings": [
+ {"created_at": "2026-01-30T08:00:00Z", "content": "channel booking A"},
+ {"created_at": "2026-01-31T08:00:00Z", "content": "channel booking B"},
+ ]
+ }
+ ),
+ ScriptedResponse(json={"external_bookings": []}),
+ ScriptedResponse(json={"items": [{"id": 300, "updated_at": "2026-02-03T10:00:00Z"}]}),
+ ScriptedResponse(json={"external_bookings": None}),
+ ScriptedResponse(json={"items": []}),
+ ],
+ should_use_incremental_field=incremental,
+ db_incremental_field_last_value=watermark,
+ )
+
+ assert result.raised is None
+ assert result.rows == [
+ {
+ "created_at": datetime(2026, 1, 30, 8, tzinfo=UTC),
+ "content": "channel booking A",
+ "booking_id": 100,
+ "booking_updated_at": datetime(2026, 2, 1, 10, tzinfo=UTC),
+ },
+ {
+ "created_at": datetime(2026, 1, 31, 8, tzinfo=UTC),
+ "content": "channel booking B",
+ "booking_id": 100,
+ "booking_updated_at": datetime(2026, 2, 1, 10, tzinfo=UTC),
+ },
+ ]
+ assert result.paths == [
+ "/v2/reservations/bookings",
+ "/v2/reservations/bookings/100/externalBookings",
+ "/v2/reservations/bookings/200/externalBookings",
+ "/v2/reservations/bookings",
+ "/v2/reservations/bookings/300/externalBookings",
+ "/v2/reservations/bookings",
+ ]
+ assert result.params("updatedSince") == [expected, None, None, expected, None, expected]
+ assert result.params("page") == ["1", None, None, "2", None, "3"]
+
+
@pytest.mark.parametrize(
"status,expected", [(200, (True, None)), (401, (False, AUTH_ERROR)), (403, (False, PERMISSION_ERROR))]
)