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): add moengage flows, segments and subscription categories tables (#123050)

Tom Owersc2c79ac56d6e
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 a7ea3ce7e27a..213e66acc862 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
@@ -8125,19 +8125,21 @@ Note: Compared the official SDK protobuf service and its documented read methods
## MoEngage — **thin**
-Today (3): `campaign_report`, `campaigns`, `daily_campaign_report`
+Today (6): `campaign_report`, `campaigns`, `daily_campaign_report`, `flows`, `segments`, `subscription_categories`
Diffed against: <https://moengage.com/docs/llms-full.txt>
-- [ ] `Search Flows (POST /v5/flows/search; GET /v5/flows/{flow_id})` — resolve flow_id on synced child campaigns and analyze journey stages, versions, and lifecycle states (high)
-- [ ] `List Segments (GET /v3/custom-segments)` — resolve custom segment references in campaign audience filters and compare targeting definitions (high)
-- [ ] `Get Subscription Categories (GET /v5/subscription-categories)` — resolve subscription_category values on email campaigns to display names, groups, and descriptions (high)
+- [x] `Search Flows (POST /v5/flows/search; GET /v5/flows/{flow_id})` — resolve flow_id on synced child campaigns and analyze journey stages, versions, and lifecycle states (high)
+- [x] `List Segments (GET /v3/custom-segments)` — resolve custom segment references in campaign audience filters and compare targeting definitions (high)
+- [x] `Get Subscription Categories (GET /v5/subscription-categories)` — resolve subscription_category values on email campaigns to display names, groups, and descriptions (high)
- [ ] `Get Query Results (GET /v5/analytics/query/{request_id}/results)` — import retention, funnel conversion, behavior, and acquisition results that campaign statistics cannot provide (high)
- [ ] `Dashboard charts and chart data (GET /v5/analytics/dashboards; GET /v5/analytics/dashboards/{dashboard_id}/charts; GET /v5/analytics/dashboards/{dashboard_id}/charts/{chart_id})` — reproduce existing dashboard metrics and compare campaign performance with the underlying customer behavior (medium)
- [ ] `Fetch All Coupon Lists (GET /v1/coupon-list)` — track available and issued coupon counts, expiry dates, and campaign incentive availability (medium)
Note: Compared operations in the full official reference and parsed the corresponding OpenAPI files. Campaign search already includes child and archived campaigns, so execution listings are duplicate coverage. Chart imports need dashboard enumeration; analytics queries need registration, polling, and result schemas selected by users. Flow endpoints have early access restrictions; excluded write operations, template configuration, and streaming ingestion.
+Note: `Get Query Results` is left unticked on purpose. It only returns rows for a query registered first through a behavior, funnels, retention, session source, or user analysis POST, so each result set depends on a query definition the user chooses, not a fixed catalog the source can sync. `flows` syncs the Search Flows listing only; the per-flow detail call is not fanned out.
+
## Mollie — gaps
Today (7): `chargebacks`, `customers`, `payment_links`, `payments`, `refunds`, `settlements`, `subscriptions`
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/moengage.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/moengage.py
index f2991b5f1d4a..38bb138df8e8 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/moengage.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/moengage.py
@@ -12,3 +12,5 @@ class MoEngageSourceConfig(config.Config):
api_key: str
data_center: Literal["01", "02", "03", "04", "05", "06", "101"] = config.value(default="01")
start_date: str | None = None
+ project_code: str | None = None
+ flow_teams: str | None = None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/moengage/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/moengage/canonical_descriptions.py
index 3bc1d414721d..66576d626a4a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/moengage/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/moengage/canonical_descriptions.py
@@ -56,4 +56,44 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"date": "Day the stats cover, in the workspace timezone.",
},
},
+ "flows": {
+ "description": "Flows (multi-step customer journeys) in the MoEngage workspace, including archived flows, with the status of their active version.",
+ "docs_url": "https://moengage.com/docs/api/flows/search-flows",
+ "columns": {
+ "flow_id": "Unique identifier of the flow. Child campaigns that flow stages send carry it as flow_id.",
+ "name": "Display name of the flow.",
+ "status": "Lifecycle status of the flow's active version (for example ACTIVE, PAUSED, STOPPED, RETIRED).",
+ "archived": "Whether the flow is archived. Independent of status.",
+ "delivery_type": "How users enter the flow: ONE_TIME, PERIODIC, ON_FLOW_EXIT, EVENT_TRIGGERED, or BUSINESS_EVENT_TRIGGERED.",
+ "active_version_name": "Display name of the active version, such as Version 3.",
+ "tags": "Tag names attached to the flow.",
+ "created_at": "Time the flow was created, in UTC.",
+ "updated_at": "Time the active version was last updated, in UTC.",
+ "published_at": "Time the active version was published, in UTC. Null if it was never published.",
+ "created_by": "Email of the user who created the flow.",
+ },
+ },
+ "segments": {
+ "description": "Custom segments saved in the MoEngage workspace, which campaigns and flows can target by name.",
+ "docs_url": "https://moengage.com/docs/api/filter-segments/list-segments",
+ "columns": {
+ "id": "Unique identifier of the segment.",
+ "name": "Name of the segment.",
+ "created_time": "Time the segment was created.",
+ "type": "Type of the segment, used for internal classification.",
+ "source": "How the segment was created.",
+ },
+ },
+ "subscription_categories": {
+ "description": "Active subscription categories that users can opt in to or out of, such as promotional or newsletter email.",
+ "docs_url": "https://moengage.com/docs/api/subscription-categories/get-subscription-categories-v5",
+ "columns": {
+ "name": "Unique name of the category. Email campaigns reference the category by this value.",
+ "display_name": "Human-readable name of the category.",
+ "description": "Description of the category.",
+ "channel": "Channel the category applies to. Only email is supported today.",
+ "group": "Group the category belongs to.",
+ "status": "Status of the category. The API returns only active categories.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/moengage/moengage.py b/products/warehouse_sources/backend/temporal/data_imports/sources/moengage/moengage.py
index 66f777fcffcd..e060cdd472df 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/moengage/moengage.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/moengage/moengage.py
@@ -14,7 +14,10 @@ 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.paginators import BasePaginator
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ BasePaginator,
+ JSONResponseCursorPaginator,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
ClientConfig,
EndpointResource,
@@ -24,6 +27,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.typ
from products.warehouse_sources.backend.temporal.data_imports.sources.moengage.settings import (
ATTRIBUTION_TYPE,
DEFAULT_BACKFILL_DAYS,
+ FLOWS_PAGE_SIZE,
+ FLOWS_UNSUPPORTED_DATA_CENTERS,
MAX_BACKFILL_DAYS,
MAX_RETRY_ATTEMPTS,
METRIC_TYPE,
@@ -39,11 +44,17 @@ START_DATE_TOO_OLD_ERROR = (
f"Start date can't be more than {MAX_BACKFILL_DAYS // 365} years ago. Pick a more recent date."
)
+FLOWS_UNSUPPORTED_DATA_CENTER_ERROR = (
+ "MoEngage doesn't offer the Flows API on this data center, so the flows table can't sync. Disable the flows table."
+)
+
@frozen
class MoEngageResumeConfig:
# Campaign search checkpoint: {"page": <next 1-indexed page>}.
search_state: dict | None = None
+ # Flow search checkpoint: {"cursor": <next_cursor of the last yielded page>}.
+ flows_state: dict | None = None
# Daily report checkpoint: {"start": "YYYY-MM-DD"}, the first day not yet fully yielded. The
# within-day stats offset is deliberately not saved: replaying a whole day costs at most a few
# request sets and merge dedupes the overlap on the synthesized `id`.
@@ -226,6 +237,10 @@ def _stats_body(start_date: date, end_date: date) -> dict[str, Any]:
}
+def parse_flow_teams(value: Optional[str]) -> list[str]:
+ return [team.strip() for team in (value or "").split(",") if team.strip()]
+
+
def parse_iso_date(value: str) -> date:
# Accept a bare date or a full timestamp; only the calendar day matters for the fan-out.
return date.fromisoformat(value.strip()[:10])
@@ -363,6 +378,8 @@ def moengage_source(
configured_start_date: Optional[str] = None,
last_synced_at: Optional[datetime] = None,
db_incremental_field_last_value_before_lookback: Optional[Any] = None,
+ project_code: Optional[str] = None,
+ flow_teams: Optional[str] = None,
) -> SourceResponse:
endpoint_config = MOENGAGE_ENDPOINTS.get(endpoint)
if endpoint_config is None:
@@ -412,6 +429,77 @@ def moengage_source(
resume_hook=save_search_checkpoint,
initial_paginator_state=resume.search_state if resume is not None else None,
)
+ elif endpoint == "flows":
+ if data_center in FLOWS_UNSUPPORTED_DATA_CENTERS:
+ raise ValueError(FLOWS_UNSUPPORTED_DATA_CENTER_ERROR)
+ flows_body: dict[str, Any] = {"include_archived": True, "limit": FLOWS_PAGE_SIZE}
+ teams = parse_flow_teams(flow_teams)
+ # Workspaces with the Flows-teams feature reject a search without team names, and the
+ # others reject a search with them, so the list is sent only when configured.
+ if teams:
+ flows_body["teams"] = teams
+ flows_resource: EndpointResource = {
+ "name": endpoint,
+ "write_disposition": "replace",
+ "table_format": "delta",
+ "endpoint": {
+ "path": endpoint_config.path,
+ "method": "POST",
+ "json": flows_body,
+ "data_selector": "data.flows",
+ "paginator": JSONResponseCursorPaginator(
+ cursor_path="data.next_cursor",
+ cursor_param="cursor",
+ param_location="json",
+ raise_on_repeated_cursor=True,
+ ),
+ },
+ }
+ flows_config: RESTAPIConfig = {
+ "client": client_config,
+ "resource_defaults": None,
+ "resources": [flows_resource],
+ }
+
+ def save_flows_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ if state and state.get("cursor"):
+ resumable_source_manager.save_state(MoEngageResumeConfig(flows_state=state))
+ else:
+ resumable_source_manager.clear_state()
+
+ resource = rest_api_resource(
+ flows_config,
+ team_id,
+ job_id,
+ db_incremental_field_last_value,
+ resume_hook=save_flows_checkpoint,
+ initial_paginator_state=resume.flows_state if resume is not None else None,
+ )
+ elif endpoint in ("segments", "subscription_categories"):
+ # Both endpoints return the whole catalog in one unpaginated response.
+ if endpoint == "subscription_categories" and project_code and project_code.strip():
+ # Required by subscription categories on workspaces with the Portfolio feature enabled.
+ client_config["headers"] = {
+ **(client_config.get("headers") or {}),
+ "MOE-PROJECT-CODE": project_code.strip(),
+ }
+ catalog_resource: EndpointResource = {
+ "name": endpoint,
+ "write_disposition": "replace",
+ "table_format": "delta",
+ "endpoint": {
+ "path": endpoint_config.path,
+ "method": "GET",
+ "data_selector": "data",
+ "paginator": "single_page",
+ },
+ }
+ catalog_config: RESTAPIConfig = {
+ "client": client_config,
+ "resource_defaults": None,
+ "resources": [catalog_resource],
+ }
+ resource = rest_api_resource(catalog_config, team_id, job_id, db_incremental_field_last_value)
elif endpoint == "campaign_report":
# A per-campaign snapshot of the trailing window the stats API allows in one call. The
# whole table restates each sync, so it is full-refresh only and not resumed: the window is
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/moengage/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/moengage/settings.py
index 923bffafbd56..dea1c17ad84d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/moengage/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/moengage/settings.py
@@ -10,9 +10,13 @@ from products.warehouse_sources.backend.types import IncrementalField, Increment
MOENGAGE_DATA_CENTERS = ("01", "02", "03", "04", "05", "06", "101")
# Documented page maximums: campaign search serves up to 15 campaigns per page, campaign-stats up
-# to 10 campaigns per page.
+# to 10 campaigns per page, flow search up to 100 flows per page.
SEARCH_PAGE_SIZE = 15
STATS_PAGE_SIZE = 10
+FLOWS_PAGE_SIZE = 100
+
+# The Flows API is not served from this data center.
+FLOWS_UNSUPPORTED_DATA_CENTERS = ("101",)
# Without this, the underlying rest_source client never times out a stalled connection.
REQUEST_TIMEOUT_SECONDS = 60
@@ -83,6 +87,22 @@ MOENGAGE_ENDPOINTS: dict[str, MoEngageEndpointConfig] = {
path="/core-services/v1/campaign-stats",
primary_keys=["id"],
),
+ "flows": MoEngageEndpointConfig(
+ name="flows",
+ path="/v5/flows/search",
+ primary_keys=["flow_id"],
+ ),
+ "segments": MoEngageEndpointConfig(
+ name="segments",
+ path="/v3/custom-segments",
+ primary_keys=["id"],
+ ),
+ # The response has no id; `name` is the category identifier that campaigns reference.
+ "subscription_categories": MoEngageEndpointConfig(
+ name="subscription_categories",
+ path="/v5/subscription-categories",
+ primary_keys=["name"],
+ ),
"daily_campaign_report": MoEngageEndpointConfig(
name="daily_campaign_report",
path="/core-services/v1/campaign-stats",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/moengage/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/moengage/source.py
index a2efa439855d..3839d56733ff 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/moengage/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/moengage/source.py
@@ -22,6 +22,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_
MoEngageSourceConfig,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.moengage.moengage import (
+ FLOWS_UNSUPPORTED_DATA_CENTER_ERROR,
MoEngageResumeConfig,
moengage_source,
parse_iso_date,
@@ -29,6 +30,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.moengage.m
validate_credentials as validate_moengage_credentials,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.moengage.settings import (
+ FLOWS_UNSUPPORTED_DATA_CENTERS,
INCREMENTAL_FIELDS,
MOENGAGE_DATA_CENTERS,
MOENGAGE_ENDPOINTS,
@@ -124,11 +126,12 @@ class MoEngageSource(ResumableSource[MoEngageSourceConfig, MoEngageResumeConfig]
message = (
"MoEngage authentication failed. Check that the Workspace ID and the Campaign report API key "
"(Settings > Account > APIs in your MoEngage dashboard) are correct and match your data center, "
- "then reconnect the source."
+ "and that the key has access to Segmentation APIs if you sync segments. Then reconnect the source."
)
return {
"401 Client Error: Unauthorized for url": message,
"403 Client Error: Forbidden for url": message,
+ FLOWS_UNSUPPORTED_DATA_CENTER_ERROR: FLOWS_UNSUPPORTED_DATA_CENTER_ERROR,
}
def get_canonical_descriptions(self) -> CanonicalDescriptions:
@@ -158,6 +161,7 @@ class MoEngageSource(ResumableSource[MoEngageSourceConfig, MoEngageResumeConfig]
default_incremental_lookback_seconds=endpoint_config.default_incremental_lookback_seconds,
)
for endpoint_config in MOENGAGE_ENDPOINTS.values()
+ if not (endpoint_config.name == "flows" and config.data_center in FLOWS_UNSUPPORTED_DATA_CENTERS)
]
if names is not None:
names_set = set(names)
@@ -207,6 +211,8 @@ class MoEngageSource(ResumableSource[MoEngageSourceConfig, MoEngageResumeConfig]
configured_start_date=config.start_date,
last_synced_at=inputs.last_synced_at,
db_incremental_field_last_value_before_lookback=inputs.db_incremental_field_last_value_before_lookback,
+ project_code=config.project_code,
+ flow_teams=config.flow_teams,
)
@property
@@ -216,9 +222,9 @@ class MoEngageSource(ResumableSource[MoEngageSourceConfig, MoEngageResumeConfig]
category=DataWarehouseSourceCategory.MARKETING___EMAIL,
label="MoEngage",
releaseStatus=ReleaseStatus.BETA,
- caption="""Sync your MoEngage campaigns and their performance reports into the PostHog Data warehouse.
+ caption="""Sync your MoEngage campaigns, flows, segments, subscription categories, and campaign performance reports into the PostHog Data warehouse.
-Find your Workspace ID and the **Campaign report** API key in your MoEngage dashboard under **Settings** > **Account** > **APIs**. Pick the data center your dashboard URL shows (for example, `dashboard-01.moengage.com` is DC-01).
+Find your Workspace ID and the **Campaign report** API key in your MoEngage dashboard under **Settings** > **Account** > **APIs**. Pick the data center your dashboard URL shows (for example, `dashboard-01.moengage.com` is DC-01). To sync the `segments` table, give the key access to **Segmentation APIs** too.
The `daily_campaign_report` table backfills the last 90 days by default. Set a daily report start date to backfill further. The `campaign_report` table always covers the last 30 days.""",
docsUrl="https://posthog.com/docs/cdp/sources/moengage",
@@ -261,6 +267,24 @@ The `daily_campaign_report` table backfills the last 90 days by default. Set a d
placeholder="2025-01-01",
secret=False,
),
+ SourceFieldInputConfig(
+ name="project_code",
+ label="Project ID (optional)",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder="",
+ secret=False,
+ caption="Required for the `subscription_categories` table if your workspace uses Portfolio. Find it under **Settings** > **Account** > **Portfolio**.",
+ ),
+ SourceFieldInputConfig(
+ name="flow_teams",
+ label="Flow team names (optional)",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder="Marketing, Growth",
+ secret=False,
+ caption="Required for the `flows` table if your workspace has teams turned on for Flows. Enter team names separated by commas. Leave it empty otherwise.",
+ ),
],
),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/moengage/tests/test_moengage.py b/products/warehouse_sources/backend/temporal/data_imports/sources/moengage/tests/test_moengage.py
index 1631b9b845c3..6b073bef0bc4 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/moengage/tests/test_moengage.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/moengage/tests/test_moengage.py
@@ -29,6 +29,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.moengage.m
validate_credentials,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.moengage.settings import (
+ FLOWS_PAGE_SIZE,
MAX_BACKFILL_DAYS,
REPORT_WINDOW_DAYS,
SEARCH_PAGE_SIZE,
@@ -146,9 +147,18 @@ def _drive(
return sent_bodies, sent_headers, rows, manager
-def _driver(start_date: str | None = None) -> SourceDriver:
+def _driver(
+ start_date: str | None = None, project_code: str | None = None, flow_teams: str | None = None
+) -> SourceDriver:
return SourceDriver(
- MoEngageSource(), MoEngageSourceConfig(workspace_id="ws-1", api_key="test-key", start_date=start_date)
+ MoEngageSource(),
+ MoEngageSourceConfig(
+ workspace_id="ws-1",
+ api_key="test-key",
+ start_date=start_date,
+ project_code=project_code,
+ flow_teams=flow_teams,
+ ),
)
@@ -257,6 +267,96 @@ class TestMoEngageSourceCampaigns:
assert [request.json()["page"] for request in result.requests] == [5]
+def _flows_page(flow_ids: list[str], next_cursor: str | None) -> dict[str, Any]:
+ return {
+ "response_id": "r1",
+ "type": "flow",
+ "data": {
+ "flows": [{"flow_id": flow_id, "name": f"Flow {flow_id}"} for flow_id in flow_ids],
+ "has_more": next_cursor is not None,
+ "next_cursor": next_cursor,
+ },
+ }
+
+
+class TestMoEngageSourceFlows:
+ def test_walks_the_body_cursor_until_it_is_null_and_checkpoints(self) -> None:
+ result = _driver().run(
+ "flows",
+ [
+ ScriptedResponse(json=_flows_page(["f1", "f2"], "cur-2")),
+ ScriptedResponse(json=_flows_page(["f3"], "cur-3")),
+ ScriptedResponse(json=_flows_page(["f4"], None)),
+ ],
+ )
+
+ assert result.raised is None
+ assert {(request.method, request.path) for request in result.requests} == {("POST", "/v5/flows/search")}
+ bodies = [request.json() for request in result.requests]
+ assert [body.get("cursor") for body in bodies] == [None, "cur-2", "cur-3"]
+ assert all(body["include_archived"] is True and body["limit"] == FLOWS_PAGE_SIZE for body in bodies)
+ assert [row["flow_id"] for row in result.rows] == ["f1", "f2", "f3", "f4"]
+ assert result.saved_states == [
+ MoEngageResumeConfig(flows_state={"cursor": "cur-2"}),
+ MoEngageResumeConfig(flows_state={"cursor": "cur-3"}),
+ ]
+ assert result.final_state is None
+
+ def test_resumes_flow_search_at_the_saved_cursor(self) -> None:
+ result = _driver().run(
+ "flows",
+ [ScriptedResponse(json=_flows_page(["f9"], None))],
+ resume_state=MoEngageResumeConfig(flows_state={"cursor": "cur-9"}),
+ )
+
+ assert result.raised is None
+ assert [request.json().get("cursor") for request in result.requests] == ["cur-9"]
+
+ @pytest.mark.parametrize(
+ ("flow_teams", "expected_teams"),
+ [(None, None), (" , ", None), ("Marketing, Growth ,", ["Marketing", "Growth"])],
+ )
+ def test_sends_team_names_only_when_configured(
+ self, flow_teams: str | None, expected_teams: list[str] | None
+ ) -> None:
+ result = _driver(flow_teams=flow_teams).run("flows", [ScriptedResponse(json=_flows_page(["f1"], None))])
+
+ assert result.raised is None
+ assert result.requests[0].json().get("teams") == expected_teams
+
+
+class TestMoEngageSourceCatalogs:
+ @pytest.mark.parametrize(
+ ("endpoint", "path", "rows"),
+ [
+ ("segments", "/v3/custom-segments", [{"id": "s1", "name": "Buyers"}, {"id": "s2", "name": "Churned"}]),
+ (
+ "subscription_categories",
+ "/v5/subscription-categories",
+ [{"name": "promotional", "display_name": "Promotional", "channel": "email"}],
+ ),
+ ],
+ )
+ def test_reads_the_whole_catalog_from_one_get(self, endpoint: str, path: str, rows: list[dict[str, Any]]) -> None:
+ result = _driver().run(endpoint, [ScriptedResponse(json={"response_id": "r1", "type": "x", "data": rows})])
+
+ assert result.raised is None
+ assert [(request.method, request.path) for request in result.requests] == [("GET", path)]
+ assert result.requests[0].headers["moe-appkey"] == "ws-1"
+ assert result.rows == rows
+
+ @pytest.mark.parametrize(("project_code", "expected_header"), [(None, None), (" p-1 ", "p-1")])
+ def test_subscription_categories_forward_the_portfolio_project_code(
+ self, project_code: str | None, expected_header: str | None
+ ) -> None:
+ result = _driver(project_code=project_code).run(
+ "subscription_categories", [ScriptedResponse(json={"data": []})]
+ )
+
+ assert result.raised is None
+ assert result.requests[0].headers.get("moe-project-code") == expected_header
+
+
class TestMoEngageSourceDailyReport:
def test_resume_skips_days_already_yielded(self) -> None:
today = datetime.now(UTC).date()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/moengage/tests/test_moengage_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/moengage/tests/test_moengage_source.py
index 366efa8a281a..979cd51c8743 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/moengage/tests/test_moengage_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/moengage/tests/test_moengage_source.py
@@ -65,3 +65,14 @@ class TestMoEngageValidateCredentials:
assert request.path == "/v5/campaigns/search"
assert request.headers["moe-appkey"] == "ws-1"
assert request.json() == {"limit": 1, "page": 1}
+
+
+class TestMoEngageGetSchemas:
+ @pytest.mark.parametrize(("data_center", "offers_flows"), [("01", True), ("101", False)])
+ def test_flows_table_is_offered_only_where_the_flows_api_is_served(
+ self, data_center: str, offers_flows: bool
+ ) -> None:
+ names = {schema.name for schema in MoEngageSource().get_schemas(_config(data_center), team_id=1)}
+
+ assert ("flows" in names) is offers_flows
+ assert {"segments", "subscription_categories"} <= names