: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(cloudbeds): add rate plan, reservation rate detail, and user tables (#102934)
Tom Owers7511e17bef1d
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 16d48917d3c9..5141436fe4b4 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@@ -1647,10 +1647,10 @@ Today (6): `guests`, `hotels`, `reservations`, `room_types`, `rooms`, `transactiDiffed against: <https://hotels.cloudbeds.com/api/docs/index.html>-- [ ] `getRatePlans` — Rate plan lookup resolving the rate IDs carried on every reservation - required for any ADR/rate-mix analysis (high)-- [ ] `getReservationsWithRateDetails (or getReservationRoomDetails)` — Per-room, per-night rate line items behind a reservation; reservations today are header-only (high)-- [ ] `getDashboard` — Cloudbeds' headline property metrics (occupancy, ADR, RevPAR) precomputed per date (high)-- [ ] `getUsers` — Staff lookup resolving the user IDs stamped on transactions and reservation changes (high)+- [x] `getRatePlans` — Rate plan lookup resolving the rate IDs carried on every reservation - required for any ADR/rate-mix analysis (high) — added as `rate_plans`. The method prices a stay rather than listing a catalog: `startDate`/`endDate` are required, so the request covers a rolling one-month forward window.+- [x] `getReservationsWithRateDetails (or getReservationRoomDetails)` — Per-room, per-night rate line items behind a reservation; reservations today are header-only (high) — added as `reservations_with_rate_details`. `getReservationRoomDetails` is a single-record lookup keyed by `subReservationID` and returns a subset of the `rooms` array the list method already carries, so it was not added.+- [ ] `getDashboard` — Cloudbeds' headline property metrics (occupancy, ADR, RevPAR) precomputed per date (high). Not added: the method returns a single unkeyed object of current-day counters (`roomsOccupied`, `percentageOccupied`, `arrivals`, `departures`, `inHouse`) with no ADR or RevPAR, and neither a date nor a property ID in the payload, so there is nothing to key a table on.+- [x] `getUsers` — Staff lookup resolving the user IDs stamped on transactions and reservation changes (high) — added as `users`. `data` is an object keyed by property ID, so rows are exploded out of the map with the property ID copied in.- [ ] `getSources` — Booking source / channel lookup that resolves the source ID on reservations - the key channel-mix dimension (medium)- [ ] `getItems and getItemCategories` — Sellable item catalog behind transaction line items, so ancillary revenue can be categorized (medium)- [ ] `getTaxesAndFees and getRoomsFeesAndTaxes` — Tax and fee definitions needed to split gross transaction amounts into net revenue vs tax (medium)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cloudbeds/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudbeds/canonical_descriptions.pyindex 5ae80bf17716..63b2138c0a90 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cloudbeds/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudbeds/canonical_descriptions.py@@ -87,4 +87,63 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"transactionDateTime": "When the transaction was posted.",},},+ "reservations_with_rate_details": {+ "description": "A booking at a property with the rates, source, and per-room details behind it, including the daily rate of each booked room.",+ "docs_url": "https://developers.cloudbeds.com",+ "columns": {+ "reservationID": "The unique ID of the reservation.",+ "propertyID": "The ID of the property the reservation belongs to.",+ "guestID": "The ID of the primary guest on the reservation.",+ "status": "The reservation status (e.g. confirmed, checked_in, checked_out, canceled, no_show).",+ "isDeleted": "Whether the reservation has been deleted.",+ "dateCreated": "When the reservation was created, in the property's time zone.",+ "dateCreatedUTC": "When the reservation was created, in UTC.",+ "dateModified": "When the reservation was last modified, in the property's time zone.",+ "dateModifiedUTC": "When the reservation was last modified, in UTC.",+ "dateCancelled": "When the reservation was cancelled, in the property's time zone.",+ "reservationCheckIn": "The check-in date of the reservation.",+ "reservationCheckOut": "The check-out date of the reservation.",+ "sourceName": "The booking source or channel the reservation came from.",+ "sourceReservationID": "The reservation ID assigned by the booking source.",+ "propertyCurrency": "The currency the property operates in.",+ "detailedRates": "The daily rates that make up the reservation.",+ "rooms": "The rooms booked on the reservation, each with its rate ID, rate name, and daily room rates.",+ "balanceDetailed": "The breakdown of the reservation total into sub total, additional items, taxes and fees, grand total, and paid amount.",+ "total": "The total value of the reservation.",+ "balance": "The outstanding balance on the reservation.",+ },+ },+ "rate_plans": {+ "description": "A rate a property sells, resolving the rate IDs carried on reservations to their rate plan and room type. Rate and availability columns cover a rolling one-month window from the sync date.",+ "docs_url": "https://developers.cloudbeds.com",+ "columns": {+ "rateID": "The unique ID of the rate.",+ "propertyID": "The ID of the property the rate belongs to.",+ "roomTypeID": "The ID of the room type the rate applies to.",+ "roomTypeName": "The name of the room type the rate applies to.",+ "ratePlanID": "The ID of the rate plan the rate belongs to, when the rate depends on a plan.",+ "ratePlanNamePublic": "The rate plan name shown to guests.",+ "ratePlanNamePrivate": "The rate plan name used internally at the property.",+ "promoCode": "The promotional code that unlocks the rate plan, when it has one.",+ "isDerived": "Whether the rate is derived from another rate.",+ "derivedType": "How a derived rate is calculated from its parent: fixed or percentage.",+ "derivedValue": "The amount a derived rate adds to or subtracts from its parent. Can be negative.",+ "parentRateID": "The ID of the rate this rate derives from. Empty when the rate is not derived.",+ "parentRatePlanID": "The ID of the rate plan this rate derives from.",+ "baseRate": "The base rate over the requested window.",+ "roomRate": "The room rate over the requested window.",+ "totalRate": "The room rate over the requested window plus the cost of extra guests.",+ "roomsAvailable": "The number of rooms available at this rate over the requested window.",+ "daysOfWeek": "The days of the week the rate applies to, when it does not apply to every day in the requested window.",+ "addOns": "The add-on items sold with the rate.",+ },+ },+ "users": {+ "description": "A staff user with access to a property, resolving the user IDs stamped on transactions and reservation changes. A user working at several properties in a group account has one row per property.",+ "docs_url": "https://developers.cloudbeds.com",+ "columns": {+ "userID": "The unique ID of the user.",+ "propertyID": "The ID of the property the user has access to.",+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cloudbeds/cloudbeds.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudbeds/cloudbeds.pyindex 7a967fb22509..080950760c76 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cloudbeds/cloudbeds.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudbeds/cloudbeds.py@@ -1,5 +1,6 @@import dataclassesfrom collections.abc import Callable+from datetime import UTC, datetime, timedeltafrom typing import Any, Optional, castfrom requests import Response@@ -96,6 +97,22 @@ def _flatten_map(config: CloudbedsEndpointConfig) -> Callable[[dict[str, Any]],return flatten+def _keyed_map(config: CloudbedsEndpointConfig) -> Callable[[dict[str, Any]], list[dict[str, Any]]]:+ """Explode a ``data`` object keyed by property ID (getUsers) into one row per nested item,+ copying the key into ``keyed_by_field``. This is the map-shaped counterpart of ``_flatten_map``."""+ key_field = cast("str", config.keyed_by_field)++ def explode(container: dict[str, Any]) -> list[dict[str, Any]]:+ rows: list[dict[str, Any]] = []+ for key, items in container.items():+ if not isinstance(items, list):+ continue+ rows.extend({**item, key_field: key} for item in items)+ return rows++ return explode++def cloudbeds_source(api_key: str,endpoint: str,@@ -108,11 +125,18 @@ def cloudbeds_source() -> SourceResponse:config = CLOUDBEDS_ENDPOINTS[endpoint]- # Group (multi-property) credentials require propertyID to scope reads; single-property+ # Group (multi-property) credentials require the property ID to scope reads; single-property# credentials can omit it. Sent on every request (the paginator only touches pageNumber).params: dict[str, Any] = {}if property_id:- params["propertyID"] = property_id+ params[config.property_param] = property_id++ if config.stay_window_days is not None:+ # The window is required, and it decides which rate plans the response covers: rates that do+ # not apply to any night in it are left out.+ today = datetime.now(UTC).date()+ params["startDate"] = today.isoformat()+ params["endDate"] = (today + timedelta(days=config.stay_window_days)).isoformat()paginator: BasePaginatorif config.paginated:@@ -135,6 +159,8 @@ def cloudbeds_source(}if config.flatten_field:endpoint_config["data_map"] = _flatten_map(config)+ elif config.keyed_by_field:+ endpoint_config["data_map"] = _keyed_map(config)rest_config: RESTAPIConfig = {"client": {diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cloudbeds/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudbeds/settings.pyindex 1580c6e3fe97..ba5aec49b337 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cloudbeds/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudbeds/settings.py@@ -3,7 +3,7 @@ from dataclasses import dataclass, fieldfrom products.warehouse_sources.backend.types import IncrementalField-@dataclass+@dataclass(frozen=True)class CloudbedsEndpointConfig:name: strpath: str@@ -18,13 +18,26 @@ class CloudbedsEndpointConfig:# the parent's fields from `flatten_parent_fields` copied in.flatten_field: str | None = Noneflatten_parent_fields: list[str] = field(default_factory=list)+ # Endpoints whose `data` is an object keyed by property ID, with that property's rows in a list+ # under the key (getUsers). Each nested row is emitted with the key copied into this field.+ keyed_by_field: str | None = None+ # Query parameter the configured property ID is sent under. Most methods take `propertyID`; a+ # few take a comma-separated list under their own spelling.+ property_param: str = "propertyID"+ # getRatePlans requires a stay window, so requests cover today through today plus this many+ # days. `None` leaves the endpoint unwindowed.+ stay_window_days: int | None = None+# getRatePlans prices a stay, so it needs a window. A rolling month forward covers the rate plans a+# property currently sells without making the request depend on how far ahead it takes bookings.+RATE_PLAN_WINDOW_DAYS = 30+# Cloudbeds PMS API list endpoints (identical method set across v1.2 and v1.3, which differ only-# by the `/api/<version>` URL segment). All are full refresh only for now: getReservations-# documents a server-side `modifiedSince` filter, but Cloudbeds notes some reservation+# by the `/api/<version>` URL segment). All are full refresh only for now: the reservation+# endpoints document server-side modification-date filters, but Cloudbeds notes some reservation# modifications are not reflected in the modified timestamp, and we have not been able to verify-# the filter's behavior against a live account - so we conservatively ship full refresh and dedupe+# the filters' behavior against a live account - so we conservatively ship full refresh and dedupe# on primary keys (see the implementing-warehouse-sources skill).CLOUDBEDS_ENDPOINTS: dict[str, CloudbedsEndpointConfig] = {"hotels": CloudbedsEndpointConfig(@@ -61,6 +74,32 @@ CLOUDBEDS_ENDPOINTS: dict[str, CloudbedsEndpointConfig] = {path="/getTransactions",primary_keys=["transactionID"],),+ "reservations_with_rate_details": CloudbedsEndpointConfig(+ name="reservations_with_rate_details",+ path="/getReservationsWithRateDetails",+ primary_keys=["reservationID"],+ ),+ # getRatePlans returns one row per rate, and a rate belongs to exactly one room type, so rateID+ # identifies the row. The rate and availability columns describe the requested window; the rate+ # plan identifiers and configuration are what resolves the rate IDs carried on reservations.+ "rate_plans": CloudbedsEndpointConfig(+ name="rate_plans",+ path="/getRatePlans",+ primary_keys=["rateID"],+ paginated=False,+ property_param="propertyIDs",+ stay_window_days=RATE_PLAN_WINDOW_DAYS,+ ),+ # A user can hold a role at more than one property in a group account, and the response lists+ # them once per property, so the property is part of the key.+ "users": CloudbedsEndpointConfig(+ name="users",+ path="/getUsers",+ primary_keys=["propertyID", "userID"],+ paginated=False,+ property_param="property_ids",+ keyed_by_field="propertyID",+ ),}ENDPOINTS = tuple(CLOUDBEDS_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cloudbeds/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudbeds/source.pyindex 0628432a9ae7..045be5039fec 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cloudbeds/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudbeds/source.py@@ -62,7 +62,7 @@ class CloudbedsSource(ResumableSource[CloudbedsSourceConfig, CloudbedsResumeConfcategory=DataWarehouseSourceCategory.PRODUCTIVITY,label="Cloudbeds",releaseStatus=ReleaseStatus.ALPHA,- caption="""Enter your Cloudbeds API key to pull your properties, reservations, guests, rooms, room types, and transactions into the PostHog Data warehouse.+ caption="""Enter your Cloudbeds API key to pull your properties, reservations and their rate details, guests, rooms, room types, transactions, rate plans, and staff users into the PostHog Data warehouse.You can create an API key under **Settings → API credentials** in [Cloudbeds](https://hotels.cloudbeds.com). Note that Cloudbeds API keys expire after 30 days of inactivity, so a key that has not been used recently may need to be regenerated.diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cloudbeds/tests/test_cloudbeds.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudbeds/tests/test_cloudbeds.pyindex a43127b487a7..3d7484a152aa 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cloudbeds/tests/test_cloudbeds.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudbeds/tests/test_cloudbeds.py@@ -1,4 +1,5 @@import json+from datetime import UTC, date, datetime, timedeltafrom typing import Anyimport pytest@@ -18,6 +19,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.cloudbeds.from products.warehouse_sources.backend.temporal.data_imports.sources.cloudbeds.settings import (CLOUDBEDS_ENDPOINTS,ENDPOINTS,+ RATE_PLAN_WINDOW_DAYS,)# RESTClient builds its session via make_tracked_session in the rest_client module.@@ -206,6 +208,68 @@ class TestPagination:{"roomID": "r2", "roomName": "102", "propertyID": "1"},]+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_users_are_exploded_out_of_the_per_property_map(self, MockSession: mock.MagicMock) -> None:+ session = MockSession.return_value+ # getUsers keys `data` by property ID instead of returning a list, so each property's users+ # arrive nested under the ID they belong to.+ _wire(+ session,+ [+ _response(+ None,+ body={+ "success": True,+ "data": {+ "1": [{"userID": "u1", "email": "[email protected]"}, {"userID": "u2"}],+ "2": [{"userID": "u1", "email": "[email protected]"}],+ },+ },+ )+ ],+ )++ rows = _rows(_source("users", manager=_make_manager()))++ # The same user at two properties must stay two rows, each carrying its own propertyID -+ # that is what makes the ["propertyID", "userID"] key unique.+ assert rows == [+ {"userID": "u1", "email": "[email protected]", "propertyID": "1"},+ {"userID": "u2", "propertyID": "1"},+ {"userID": "u1", "email": "[email protected]", "propertyID": "2"},+ ]++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_rate_plans_request_the_required_forward_stay_window(self, MockSession: mock.MagicMock) -> None:+ session = MockSession.return_value+ params = _wire(session, [_response([{"rateID": "r1"}])])++ before = datetime.now(UTC).date()+ _rows(_source("rate_plans", manager=_make_manager(), property_id="12345"))+ after = datetime.now(UTC).date()++ start = date.fromisoformat(params[0]["startDate"])+ end = date.fromisoformat(params[0]["endDate"])+ # getRatePlans rejects a request without a stay window, so the window has to be built for it,+ # and it has to start on the sync date rather than drift into the past.+ assert before <= start <= after+ assert end - start == timedelta(days=RATE_PLAN_WINDOW_DAYS)++ @parameterized.expand([("rate_plans", "propertyIDs"), ("users", "property_ids")])+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_property_is_scoped_under_the_param_the_endpoint_accepts(+ self, endpoint: str, param: str, MockSession: mock.MagicMock+ ) -> None:+ session = MockSession.return_value+ params = _wire(session, [_response(None, body={"success": True, "data": {}})])++ _rows(_source(endpoint, manager=_make_manager(), property_id="12345"))++ # These two methods spell the property filter their own way; sending `propertyID` instead+ # would leave a group credential reading every property it can see.+ assert params[0][param] == "12345"+ assert "propertyID" not in params[0]+class TestApiVersion:def _capture_urls(self, session: mock.MagicMock, responses: list[Response]) -> list[str]: