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(chargify): sync coupons, reason codes, and credit notes (#102226)

Tom Owersc9d2c8283e06
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 c31b4e1fb9ae..69ebd29f6fb6 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
@@ -1339,17 +1339,18 @@ Note: Full endpoint list extracted from the single-page api-docs HTML. Only thre
## Chargify — gaps
-Today (8): `Components`, `Customers`, `Events`, `Invoices`, `ProductFamilies`, `Products`, `Subscriptions`, `Transactions`
+Today (11): `Components`, `Coupons`, `CreditNotes`, `Customers`, `Events`, `Invoices`, `ProductFamilies`, `Products`, `ReasonCodes`, `Subscriptions`, `Transactions`
Diffed against: <https://github.com/maxio-com/ab-python-sdk/tree/main/advancedbilling/controllers>
- [ ] `subscriptions/{id}/components (and site-wide list_subscription_components_for_site)` — per-subscription component price point and quantity - the line-item grain that makes Subscriptions joinable to Components (high)
- [ ] `subscriptions/{id}/components/{component_id}/usages` — metered usage records, the fact table for any usage-based billing analysis (high)
- [ ] `subscriptions/{id}/components/{component_id}/allocations` — quantity change history per component - seat expansion/contraction over time (high)
-- [ ] `coupons (and coupons/{id}/usage, coupon subcodes)` — lookup resolving the coupon ids already carried on subscriptions and invoices, plus discount attribution (high)
-- [ ] `reason_codes` — lookup that resolves the churn/cancellation reason codes referenced by subscription cancellations (high)
-- [ ] `invoices/credit_notes` — credits and write-offs that net against Invoices; revenue is wrong without them (high)
-- [ ] `insights/mrr_movements` — Maxio's headline metric - new/expansion/contraction/churn MRR movement breakdown (high)
+- [x] `coupons` — lookup resolving the coupon ids already carried on subscriptions and invoices, plus discount attribution (high)
+- [ ] `coupons/{id}/usage and coupon subcodes` — usage is a vendor-computed rollup per product with no record identity of its own and no pagination; subcodes return a bare array of code strings rather than objects, so both need a bespoke iterator outside this source's declarative endpoint catalog (medium)
+- [x] `reason_codes` — lookup that resolves the churn/cancellation reason codes referenced by subscription cancellations (high)
+- [x] `invoices/credit_notes` — credits and write-offs that net against Invoices; revenue is wrong without them (high)
+- [ ] `insights/mrr_movements` — deprecated by Maxio (as are `/mrr.json` and `/subscriptions_mrr.json`), and a movement carries no unique identifier to key a table on (high)
- [ ] `insights/mrr_per_subscription` — per-subscription MRR snapshot for cohorting and ARR rollups (medium)
- [ ] `components/{id}/price_points and products/{id}/price_points (list_all_component_price_points / list_all_product_price_points)` — pricing lookup resolving the price point ids on subscriptions and components (medium)
- [ ] `subscription_groups` — resolves multi-subscription billing groups so invoices can be attributed to the paying parent (medium)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/chargify/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/chargify/canonical_descriptions.py
index 2e9c5f4f6c39..327e8254c19f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/chargify/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/chargify/canonical_descriptions.py
@@ -163,4 +163,68 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
line_items="Line items itemizing the charges on the invoice.",
),
},
+ "CreditNotes": {
+ "description": "An inverse invoice that reduces what a customer owes, applied against one or more invoices.",
+ "docs_url": "https://developers.maxio.com/http/resources/credit-notes",
+ # Credit notes carry none of the shared id/created_at/updated_at fields.
+ "columns": {
+ "uid": 'Globally unique identifier for the credit note, prefixed with "cn_".',
+ "site_id": "Identifier of the site the credit note belongs to.",
+ "customer_id": "Identifier of the customer the credit note belongs to.",
+ "subscription_id": "Identifier of the subscription that generated the credit note.",
+ "number": "Short identifying number shown on the credit note to the customer.",
+ "sequence_number": "Monotonically increasing number assigned as credit notes are created, unique within the site.",
+ "issue_date": "Date the credit was made available for application (YYYY-MM-DD).",
+ "applied_date": "Date the credit note became fully applied to invoices; empty while only partially applied.",
+ "status": "Current status of the credit note (e.g. open, partial, applied, refunded).",
+ "currency": "Currency of the credit note amounts (ISO 4217 code).",
+ "memo": "Description of the reason for the credit, printed on the credit note.",
+ "subtotal_amount": "Sum of all line items before discounts or taxes, as a positive credit amount.",
+ "discount_amount": "Discount credited back to the customer, as a positive amount.",
+ "tax_amount": "Tax credited back to the customer, as a positive amount.",
+ "total_amount": "Credit note total, equal to subtotal_amount - discount_amount + tax_amount.",
+ "applied_amount": "Amount of the credit note already applied to invoices.",
+ "remaining_amount": "Amount of the credit note still available to apply, equal to total_amount - applied_amount.",
+ "origin_invoices": "The invoices the credit note originated from.",
+ },
+ },
+ "Coupons": {
+ "description": "A discount that can be applied to subscriptions, either site-wide or within a product family.",
+ "docs_url": "https://developers.maxio.com/http/resources/coupons",
+ "columns": _columns(
+ name="Name of the coupon shown in the Chargify interface.",
+ code="Code customers enter to redeem the coupon.",
+ description="Description of the coupon.",
+ amount="Flat discount amount, when the coupon discounts a fixed amount.",
+ amount_in_cents="Flat discount amount in cents.",
+ percentage="Percentage discount, when the coupon discounts a percentage.",
+ discount_type="Whether the coupon discounts an amount or a percentage.",
+ product_family_id="Identifier of the product family the coupon is restricted to, if any.",
+ product_family_name="Name of the product family the coupon is restricted to, if any.",
+ start_date="Timestamp for when the coupon becomes redeemable.",
+ end_date="Timestamp for when the coupon stops being redeemable.",
+ archived_at="Timestamp for when the coupon was archived, if applicable.",
+ recurring="Whether the discount applies to every billing period or only the first.",
+ recurring_scheme="How the recurring discount repeats (e.g. do_not_recur, noenddate, limited).",
+ duration_period_count="Number of billing periods a limited recurring discount applies for.",
+ conversion_limit="Maximum number of times the coupon can be redeemed.",
+ stackable="Whether the coupon can be combined with other coupons.",
+ compounding_strategy="How the discount compounds when stacked with other coupons.",
+ allow_negative_balance="Whether the discount may take the subscription balance below zero.",
+ exclude_mid_period_allocations="Whether mid-period allocation charges are excluded from the discount.",
+ apply_on_cancel_at_end_of_period="Whether the discount applies to the final invoice when cancelling at period end.",
+ use_site_exchange_rate="Whether the site exchange rate converts the discount for other currencies.",
+ coupon_restrictions="Products and components the coupon is restricted to.",
+ ),
+ },
+ "ReasonCodes": {
+ "description": "A churn code a merchant can pick from when cancelling a subscription.",
+ "docs_url": "https://developers.maxio.com/http/resources/reason-codes",
+ "columns": _columns(
+ site_id="Identifier of the site the reason code belongs to.",
+ code="Short code identifying the churn reason.",
+ description="Description of the churn reason shown when cancelling.",
+ position="Order the reason code appears in when picking a churn reason.",
+ ),
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/chargify/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/chargify/settings.py
index b321e5994aed..4da3841b7ad2 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/chargify/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/chargify/settings.py
@@ -95,6 +95,34 @@ CHARGIFY_ENDPOINTS: dict[str, ChargifyEndpoint] = {
partition_key="created_at",
params={"per_page": PER_PAGE, "direction": "asc"},
),
+ "CreditNotes": ChargifyEndpoint(
+ name="CreditNotes",
+ path="/credit_notes.json",
+ # Wrapped like Invoices rather than a bare array.
+ data_selector="credit_notes",
+ # Credit notes carry no numeric ``id`` — ``uid`` ("cn_" prefixed) is the identifier.
+ primary_key=["uid"],
+ # No creation timestamp is exposed: ``issue_date`` is a date, and ``applied_date`` only
+ # gets a value once the credit is fully applied, so neither is a stable partition key.
+ partition_key=None,
+ params={"per_page": PER_PAGE},
+ ),
+ "Coupons": ChargifyEndpoint(
+ name="Coupons",
+ path="/coupons.json",
+ data_selector="[*].coupon",
+ primary_key=["id"],
+ partition_key="created_at",
+ params={"per_page": PER_PAGE},
+ ),
+ "ReasonCodes": ChargifyEndpoint(
+ name="ReasonCodes",
+ path="/reason_codes.json",
+ data_selector="[*].reason_code",
+ primary_key=["id"],
+ partition_key="created_at",
+ params={"per_page": PER_PAGE},
+ ),
}
ENDPOINTS: tuple[str, ...] = tuple(CHARGIFY_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/chargify/tests/test_chargify.py b/products/warehouse_sources/backend/temporal/data_imports/sources/chargify/tests/test_chargify.py
index 91f7e8050e44..4a63f526eca3 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/chargify/tests/test_chargify.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/chargify/tests/test_chargify.py
@@ -121,10 +121,10 @@ class TestChargifySourceResumeBehavior:
def _drive(
self, endpoint: str, manager: MagicMock, responses: list[Response]
- ) -> tuple[MagicMock, list[dict[str, Any]]]:
+ ) -> tuple[MagicMock, list[dict[str, Any]], list[Any]]:
"""Drive ``chargify_source`` with a mocked HTTP session.
- Returns ``(mock_session, sent_params)`` where ``sent_params`` captures a shallow
+ Returns ``(mock_session, sent_params, rows)`` where ``sent_params`` captures a shallow
copy of ``request.params`` at send-time — the Request object is mutated in place
by the paginator between pages, so mock call history can't be trusted for it.
"""
@@ -153,10 +153,12 @@ class TestChargifySourceResumeBehavior:
db_incremental_field_last_value=None,
should_use_incremental_field=False,
)
- list(cast(Iterable[Any], resource))
- return mock_session, sent_params
+ rows = list(cast(Iterable[Any], resource))
+ return mock_session, sent_params, rows
- @pytest.mark.parametrize("endpoint", ["Customers", "Subscriptions", "Events", "Transactions"])
+ @pytest.mark.parametrize(
+ "endpoint", ["Customers", "Subscriptions", "Events", "Transactions", "Coupons", "ReasonCodes"]
+ )
def test_fresh_run_saves_page_after_each_non_terminal_page(self, endpoint: str) -> None:
manager = MagicMock(spec=ResumableSourceManager)
manager.can_resume.return_value = False
@@ -167,7 +169,7 @@ class TestChargifySourceResumeBehavior:
_make_http_response([{selector_key: {"id": 2}}]),
_make_http_response([]),
]
- _, sent_params = self._drive(endpoint, manager, responses)
+ _, sent_params, _ = self._drive(endpoint, manager, responses)
assert [p.get("page") for p in sent_params] == [1, 2, 3]
@@ -183,7 +185,7 @@ class TestChargifySourceResumeBehavior:
_make_http_response([{"customer": {"id": 1}}]),
_make_http_response([]),
]
- _, sent_params = self._drive("Customers", manager, responses)
+ _, sent_params, _ = self._drive("Customers", manager, responses)
assert [p.get("page") for p in sent_params] == [5, 6]
manager.load_state.assert_called_once()
@@ -207,6 +209,35 @@ class TestChargifySourceResumeBehavior:
manager.load_state.assert_not_called()
+ @pytest.mark.parametrize(
+ ("endpoint", "first_page", "empty_page", "expected_row"),
+ [
+ ("Coupons", [{"coupon": {"id": 1, "code": "FREE"}}], [], {"id": 1, "code": "FREE"}),
+ ("ReasonCodes", [{"reason_code": {"id": 2, "code": "LARGE"}}], [], {"id": 2, "code": "LARGE"}),
+ (
+ "CreditNotes",
+ {"credit_notes": [{"uid": "cn_1", "total_amount": "10.0"}]},
+ {"credit_notes": []},
+ {"uid": "cn_1", "total_amount": "10.0"},
+ ),
+ ],
+ )
+ def test_rows_are_unwrapped_and_pagination_terminates(
+ self, endpoint: str, first_page: Any, empty_page: Any, expected_row: dict[str, Any]
+ ) -> None:
+ # Chargify mixes bare arrays of single-key-wrapped objects with payloads nested under a
+ # plural key, so the selector has to strip the right wrapper and the paginator has to
+ # recognise an empty page in either shape.
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [_make_http_response(first_page), _make_http_response(empty_page)]
+ _, sent_params, rows = self._drive(endpoint, manager, responses)
+
+ # The resource yields one list per page.
+ assert rows == [[expected_row]]
+ assert [p.get("page") for p in sent_params] == [1, 2]
+
class TestValidateCredentials:
@pytest.mark.parametrize(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/chargify/tests/test_chargify_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/chargify/tests/test_chargify_source.py
index 1f79305d8bf6..ebf2c477f464 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/chargify/tests/test_chargify_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/chargify/tests/test_chargify_source.py
@@ -139,3 +139,18 @@ class TestChargifySource:
assert response.partition_mode == "datetime"
assert response.partition_format == "month"
assert response.partition_keys == ["created_at"]
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.chargify.source.chargify_source")
+ def test_source_for_pipeline_leaves_an_endpoint_without_a_timestamp_unpartitioned(
+ self, mock_source: mock.MagicMock
+ ) -> None:
+ # Credit notes expose no stable creation timestamp, so partitioning must stay off rather
+ # than point at a column the rows do not carry.
+ response = self.source.source_for_pipeline(
+ self.config, mock.MagicMock(spec=ResumableSourceManager), _make_inputs(schema_name="CreditNotes")
+ )
+
+ assert response.partition_mode is None
+ assert response.partition_format is None
+ assert response.partition_keys is None
+ assert response.primary_keys == ["uid"]