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.

9.4 KB
Raw Blame
from datetime import UTC, date, datetime, timedelta
from typing import Any

from requests import HTTPError

from products.warehouse_sources.sources.lodgify.settings import (
    AUTH_ERROR,
    BASE_URL,
    CALENDAR_WINDOW_DAYS,
    ENDPOINTS,
    PAGE_SIZE,
    PATHS,
    PERMISSION_ERROR,
    PRIMARY_KEYS,
)
from products.warehouse_sources.sources.sdk import (
    APIKeyAuth,
    Endpoint,
    EndpointResource,
    PageNumberPaginator,
    RESTAPIConfig,
    RESTClient,
    ResumableSourceManager,
    SinglePagePaginator,
    SourceResponse,
    frozen,
    parse_datetime_value,
    rename_parent_fields,
    rest_api_resource,
    rest_api_resources,
)


@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]:
    client = RESTClient(
        BASE_URL,
        auth=APIKeyAuth(api_key, name="X-ApiKey"),
        headers={"Accept": "application/json"},
        request_timeout=(10, 60),
    )
    try:
        next(
            client.paginate(
                path="properties",
                params={"page": 1, "size": 1},
                paginator=SinglePagePaginator(),
                data_selector="items",
                data_selector_required=True,
            )
        )
    except HTTPError as error:
        if error.response is not None and error.response.status_code in (401, 403):
            return False, AUTH_ERROR if error.response.status_code == 401 else PERMISSION_ERROR
        raise
    return True, None


def list_resource(endpoint: str, watermark: datetime | str | None = None) -> EndpointResource:
    params: dict[str, Any] = {"size": PAGE_SIZE}
    if endpoint == "bookings":
        params.update(stayFilter="All", trash="All", includeTransactions="true", includeQuoteDetails="true")
    if watermark is not None:
        parsed = parse_datetime_value(watermark)
        if parsed is None:
            raise ValueError("Invalid Lodgify sync timestamp. Reset the table and try again.")
        params["updatedSince"] = parsed.isoformat()
    endpoint_config: Endpoint = {
        "path": PATHS[endpoint],
        "params": params,
        "data_selector": "items",
        "data_selector_required": True,
        "paginator": PageNumberPaginator(base_page=1),
    }
    return {
        "name": endpoint,
        "endpoint": endpoint_config,
        "columns": {"created_at": {"data_type": "timestamp"}, "updated_at": {"data_type": "timestamp"}},
    }


@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,
    team_id: int,
    job_id: str,
    resumable_source_manager: ResumableSourceManager[LodgifyResumeConfig],
    should_use_incremental_field: bool = False,
    db_incremental_field_last_value: datetime | str | None = None,
) -> SourceResponse:
    if endpoint not in ENDPOINTS:
        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, window_start=start, window_end=end)
            )

    config: RESTAPIConfig = {
        "client": {
            "base_url": BASE_URL,
            "auth": {"type": "api_key", "name": "X-ApiKey", "api_key": api_key, "location": "header"},
            "headers": {"Accept": "application/json"},
            "request_timeout": (10, 60),
        },
        "resources": [],
    }
    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"),
            {
                "name": "rooms",
                "include_from_parent": ["id"],
                "endpoint": {
                    "path": PATHS["rooms"],
                    "params": {"id": {"type": "resolve", "resource": "properties", "field": "id"}},
                    "paginator": "single_page",
                    "data_selector": "$",
                    "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 == "rooms")
        resource.add_map(rename_parent_fields("properties", {"id": "property_id"}))
    else:
        watermark = db_incremental_field_last_value if should_use_incremental_field else None
        config["resources"] = [list_resource(endpoint, watermark)]
        resource = rest_api_resource(
            config, team_id, job_id, None, resume_hook=save_checkpoint, initial_paginator_state=initial_state
        )

    return SourceResponse(
        name=endpoint,
        items=lambda: resource,
        primary_keys=PRIMARY_KEYS[endpoint],
        column_hints=resource.column_hints,
        # The API does not guarantee ascending update order; save the watermark after the complete scan.
        sort_mode="desc",
    )