Open-source personal finance manager. Self-hosted, privacy-first.
feat(pluggy): map COMPE bank codes to Pluggy icons for logo fallback
Tássio Noronha0e62d4326c96
diff --git a/backend/app/providers/pluggy.py b/backend/app/providers/pluggy.pyindex 2113e735..152fc2cd 100644--- a/backend/app/providers/pluggy.py+++ b/backend/app/providers/pluggy.py@@ -19,6 +19,7 @@ from app.providers.base import (RefreshOutcome,TransactionData,)+from app.providers.pluggy_constants import pluggy_icon_for_compelogger = logging.getLogger(__name__)@@ -51,6 +52,38 @@ _PLUGGY_REFRESH_USER_ACTION_CODES = {PLUGGY_API_BASE = "https://api.pluggy.ai"+def _compe_from_transfer_number(transfer_number) -> Optional[str]:+ """Extract the 3-digit COMPE bank code from a Pluggy ``transferNumber``.++ Format is ``"<compe>/<branch>/<account>"`` (e.g. ``"260/0001/06809695-5"``).+ Returns the zero-padded code, or None when absent/unparseable.+ """+ if not isinstance(transfer_number, str) or "/" not in transfer_number:+ return None+ code = transfer_number.split("/", 1)[0].strip()+ return code.zfill(3) if code.isdigit() else None+++def _resolve_connector_logo(connector: dict, accounts: list[dict]) -> Optional[str]:+ """Institution logo URL for a Pluggy connection, or None.++ Real connectors expose the bank logo directly in ``imageUrl`` (e.g.+ Nubank -> ``.../212.svg``). The demo "MeuPluggy" connector returns the+ generic ``sandbox.svg`` placeholder instead — in that case fall back to+ the real bank's icon resolved from an account's COMPE code. If neither is+ available, return None so the frontend shows the account-type icon.+ """+ image = connector.get("imageUrl")+ if image and not image.rstrip("/").endswith("/sandbox.svg"):+ return image+ for acc in accounts:+ compe = _compe_from_transfer_number((acc.get("bankData") or {}).get("transferNumber"))+ icon = pluggy_icon_for_compe(compe)+ if icon:+ return icon+ return None++def _parse_day(value) -> Optional[int]:"""Extract day-of-month from a Pluggy ISO date string (yyyy-mm-dd or datetime)."""if not value:@@ -302,8 +335,9 @@ class PluggyProvider(BankProvider):connector = item_data.get("connector", {})institution_name = connector.get("name", "Unknown Bank")+ raw_accounts = accounts_data.get("results", [])account_list = []- for acc in accounts_data.get("results", []):+ for acc in raw_accounts:account_list.append(_build_account_data(acc, self._map_account_type))return ConnectionData(@@ -311,7 +345,7 @@ class PluggyProvider(BankProvider):institution_name=institution_name,credentials={"item_id": item_id},accounts=account_list,- logo_url=connector.get("imageUrl"),+ logo_url=_resolve_connector_logo(connector, raw_accounts),)async def get_institution_logo(self, credentials: dict) -> Optional[str]:@@ -322,7 +356,16 @@ class PluggyProvider(BankProvider):f"{PLUGGY_API_BASE}/items/{item_id}", headers=headers)resp.raise_for_status()- return resp.json().get("connector", {}).get("imageUrl")+ connector = resp.json().get("connector", {})+ # The connector logo may be the demo placeholder; fetch accounts so+ # the COMPE-code fallback can recover the real bank icon.+ accts_resp = await client.get(+ f"{PLUGGY_API_BASE}/accounts", headers=headers,+ params={"itemId": item_id},+ )+ accts_resp.raise_for_status()+ raw_accounts = accts_resp.json().get("results", [])+ return _resolve_connector_logo(connector, raw_accounts)async def get_accounts(self, credentials: dict) -> list[AccountData]:item_id = credentials["item_id"]diff --git a/backend/app/providers/pluggy_constants.py b/backend/app/providers/pluggy_constants.pynew file mode 100644index 00000000..48ea607c--- /dev/null+++ b/backend/app/providers/pluggy_constants.py@@ -0,0 +1,72 @@+"""Static Pluggy lookup tables, kept out of the provider logic.++The COMPE map lets us recover a real bank logo when a Pluggy *connector*+doesn't expose one (notably the demo "MeuPluggy" connector). Pluggy still+embeds the real bank in each account's ``bankData.transferNumber`` — the+3-digit prefix is the Brazilian Central Bank COMPE code — so we map that code+to the bank's actual Pluggy CDN icon.++Icon filenames were harvested from Pluggy's own ``/connectors`` and do NOT+track the connector id (e.g. Nubank is connector 612 but its icon is+``212.svg``), which is why an explicit table is needed.+"""+from typing import Optional++# Public Pluggy CDN that hosts the per-bank connector icons.+PLUGGY_ICON_BASE = "https://cdn.pluggy.ai/assets/connector-icons"++# Brazilian COMPE (3-digit bank) code -> Pluggy connector-icon filename.+# Ordered by code; covers the popular retail/digital banks plus the larger+# regionals and cooperatives. Unknown codes fall back to the account-type icon.+COMPE_TO_PLUGGY_ICON = {+ "001": "211.svg", # Banco do Brasil+ "003": "679.svg", # Banco da Amazônia+ "004": "671.svg", # Banco do Nordeste do Brasil+ "021": "681.svg", # Banestes+ "033": "208.svg", # Santander+ "041": "659.svg", # Banrisul+ "047": "735.svg", # Banese+ "070": "682.svg", # BRB - Banco de Brasília+ "077": "215.svg", # Banco Inter+ "082": "734.svg", # Banco Topázio+ "085": "224.svg", # Ailos+ "104": "219.svg", # Caixa Econômica Federal+ "133": "684.svg", # Cresol+ "136": "663.svg", # Unicred+ "208": "214.svg", # BTG Pactual+ "212": "654.svg", # Banco Original+ "213": "738.svg", # Banco Arbi+ "218": "723.svg", # Banco BS2+ "237": "203.svg", # Bradesco+ "243": "680.svg", # Banco Master+ "260": "212.svg", # Nubank (Nu Pagamentos)+ "290": "692.svg", # PagBank (PagSeguro)+ "318": "652.svg", # Banco BMG+ "323": "206.svg", # Mercado Pago+ "330": "739.svg", # Banco Bari+ "335": "653.svg", # Banco Digio+ "336": "726.svg", # C6 Bank+ "341": "201.svg", # Itaú+ "348": "202.svg", # Banco XP+ "364": "686.svg", # Efí (Gerencianet)+ "376": "757.svg", # JP Morgan+ "380": "651.svg", # PicPay+ "389": "742.svg", # Banco Mercantil do Brasil+ "403": "250.svg", # Cora+ "422": "629.svg", # Safra+ "604": "731.svg", # Banco Industrial do Brasil+ "623": "657.svg", # Banco PAN+ "633": "769.svg", # Banco Rendimento+ "637": "714.svg", # Banco Sofisa+ "654": "740.svg", # Banco Digimais+ "707": "685.svg", # Banco Daycoval+ "735": "689.svg", # Banco Neon+ "748": "661.svg", # Sicredi+ "756": "228.svg", # Sicoob+}+++def pluggy_icon_for_compe(compe: Optional[str]) -> Optional[str]:+ """Full Pluggy CDN icon URL for a COMPE code, or None if unmapped."""+ icon = COMPE_TO_PLUGGY_ICON.get(compe) if compe else None+ return f"{PLUGGY_ICON_BASE}/{icon}" if icon else None