Open-source personal finance manager. Self-hosted, privacy-first.
fix(pluggy): migrate to v2 cursor-based transactions endpoint (#277)
Tássio Noronha85d3cb0c153b
diff --git a/backend/app/providers/pluggy.py b/backend/app/providers/pluggy.pyindex 13dbb644..dc24c696 100644--- a/backend/app/providers/pluggy.py+++ b/backend/app/providers/pluggy.py@@ -4,6 +4,7 @@ import timefrom datetime import datefrom decimal import Decimal, InvalidOperationfrom typing import Optional+from urllib.parse import parse_qs, urlparseimport httpx@@ -335,27 +336,31 @@ class PluggyProvider(BankProvider):) -> list[TransactionData]:headers = await self._headers()all_transactions: list[TransactionData] = []- page = 1+ after: Optional[str] = Noneasync with httpx.AsyncClient(timeout=30.0) as client:while True:- params: dict = {- "accountId": account_external_id,- "pageSize": 500,- "page": page,- }+ # v2 cursor-based listing. Pluggy deprecated v1 GET+ # /transactions — it returns 410 ENDPOINT_DEPRECATED on newer+ # API keys (rolled out per key). /v2/transactions pages via an+ # opaque `after` cursor (returned in `next`) instead of+ # page/pageSize.+ params: dict = {"accountId": account_external_id}if since:# Filter by Pluggy ingestion time, NOT transaction date.- # `from`/`to` filter on `date` (when the txn happened),- # which silently drops transactions Pluggy ingests later- # but backdates — e.g. credit card bill payments dated- # to the bill close, or merchants that settle weeks late.- # `createdAtFrom` filters on Pluggy's row creation time,- # so any newly-ingested row is fetched regardless of date.+ # `dateFrom`/`dateTo` filter on `date` (when the txn+ # happened), which silently drops transactions Pluggy+ # ingests later but backdates — e.g. credit card bill+ # payments dated to the bill close, or merchants that+ # settle weeks late. `createdAtFrom` filters on Pluggy's+ # row creation time, so any newly-ingested row is fetched+ # regardless of date. v2 still supports it.params["createdAtFrom"] = since.isoformat()+ if after:+ params["after"] = afterresp = await client.get(- f"{PLUGGY_API_BASE}/transactions",+ f"{PLUGGY_API_BASE}/v2/transactions",headers=headers,params=params,)@@ -441,13 +446,27 @@ class PluggyProvider(BankProvider):))- total_pages = data.get("totalPages", 1)- if page >= total_pages:+ next_after = self._extract_after(data.get("next"))+ if not next_after or next_after == after:break- page += 1+ after = next_afterreturn all_transactions+ @staticmethod+ def _extract_after(next_value: Optional[str]) -> Optional[str]:+ """Pull the `after` cursor out of v2's `next` field.++ Pluggy returns `next` as a URL carrying the cursor+ (".../v2/transactions?accountId=...&after=<cursor>"), or null on the+ last page. Returns None when there's no further page so the caller+ stops — and never loops on a malformed value.+ """+ if not next_value:+ return None+ after_vals = parse_qs(urlparse(next_value).query).get("after")+ return after_vals[0] if after_vals else None+async def refresh_credentials(self, credentials: dict) -> dict:# Pluggy manages API keys at the provider level, not per-connectionreturn credentialsdiff --git a/backend/tests/test_providers_pluggy.py b/backend/tests/test_providers_pluggy.pyindex ca60e0ff..ec5ca96e 100644--- a/backend/tests/test_providers_pluggy.py+++ b/backend/tests/test_providers_pluggy.py@@ -284,3 +284,64 @@ async def test_parser_missing_purchase_date_only():assert tx.total_installments == 10assert tx.installment_total_amount == Decimal("250")assert tx.installment_purchase_date is None+++# ---------------------------------------------------------------------------+# v2 cursor pagination (GET /v2/transactions)+# ---------------------------------------------------------------------------+++ "next_value,expected",+ [+ (None, None),+ ("", None),+ (+ "https://api.pluggy.ai/v2/transactions?accountId=a&after=CURSOR123",+ "CURSOR123",+ ),+ ("/v2/transactions?after=abc%3D%3D&accountId=a", "abc=="),+ # No `after` in the URL → stop (don't loop on a malformed value).+ ("https://api.pluggy.ai/v2/transactions?accountId=a", None),+ ],+)+def test_extract_after(next_value, expected):+ assert PluggyProvider._extract_after(next_value) == expected+++def _txn(id_: str) -> dict:+ return {"id": id_, "description": "x", "amount": -1, "date": "2026-01-01", "type": "DEBIT"}+++async def test_get_transactions_follows_cursor_until_next_is_null():+ """Pages via the `after` cursor from `next` until it's null, hitting v2+ and forwarding createdAtFrom."""+ page1 = MagicMock(raise_for_status=MagicMock())+ page1.json = MagicMock(return_value={+ "results": [_txn("t1"), _txn("t2")],+ "next": "https://api.pluggy.ai/v2/transactions?accountId=a&after=CUR2",+ })+ page2 = MagicMock(raise_for_status=MagicMock())+ page2.json = MagicMock(return_value={"results": [_txn("t3")], "next": None})++ client = MagicMock()+ client.get = AsyncMock(side_effect=[page1, page2])+ client.__aenter__ = AsyncMock(return_value=client)+ client.__aexit__ = AsyncMock(return_value=None)++ provider = PluggyProvider()+ with patch.object(+ PluggyProvider, "_ensure_api_key", new=AsyncMock(return_value="k")+ ), patch("app.providers.pluggy.httpx.AsyncClient", return_value=client):+ txns = await provider.get_transactions(+ {"item_id": "i"}, "acc", since=date(2026, 1, 1)+ )++ assert [t.external_id for t in txns] == ["t1", "t2", "t3"]+ assert client.get.await_count == 2+ first = client.get.await_args_list[0]+ assert first.args[0].endswith("/v2/transactions")+ assert first.kwargs["params"]["createdAtFrom"] == "2026-01-01"+ assert "after" not in first.kwargs["params"]+ assert client.get.await_args_list[1].kwargs["params"]["after"] == "CUR2"