mirror of
https://github.com/eitchtee/WYGIWYH.git
synced 2026-11-29 03:42:51 +01:00
feat(bank-sync): add Pluggy provider
Brazilian banks through Open Finance. Users give their Pluggy client credentials and the ids of their connections (items), from Meu Pluggy. - Uses the cursor-paginated /v2/transactions; /transactions is removed after 2026-12-31. Our own filters are sent again with each cursor. - The direction comes from `type`, not the amount's sign: credit cards keep the card's sign, purchases are positive. Checked against a real Meu Pluggy card and checking account; the sandbox data doesn't match production here. - Pending transactions keep their id once they post (a card's open bill stays pending until it closes), so they're imported unpaid and settled later. Future-dated ones (installments, scheduled payments) wait for their date. Installments already come dated in their own month. - Foreign purchases use the account's amount, with the original amount in the notes. - Connections that need the user to log in again show as an error.
This commit is contained in:
1 parent
2a4202118b
commit
cc4c58b676
5 files changed
+257
-1
No files matched your search
@@ -21,7 +21,7 @@ class Migration(migrations.Migration):
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('name', models.CharField(max_length=255, verbose_name='Name')),
|
||||
('service_type', models.CharField(choices=[('lunchflow', 'Lunch Flow'), ('simplefin', 'SimpleFIN')], max_length=255, verbose_name='Service Type')),
|
||||
('service_type', models.CharField(choices=[('lunchflow', 'Lunch Flow'), ('simplefin', 'SimpleFIN'), ('pluggy', 'Pluggy')], max_length=255, verbose_name='Service Type')),
|
||||
('is_active', models.BooleanField(default=True, verbose_name='Active')),
|
||||
('settings', models.JSONField(blank=True, default=dict, verbose_name='Settings')),
|
||||
('sync_interval', models.PositiveIntegerField(default=24, help_text='Most banks only update once a day.', validators=[django.core.validators.MinValueValidator(1), django.core.validators.MaxValueValidator(168)], verbose_name='Sync every X hours')),
|
||||
|
||||
@@ -9,6 +9,7 @@ class BankSyncService(OwnedObject):
|
||||
class ServiceType(models.TextChoices):
|
||||
LUNCHFLOW = "lunchflow", "Lunch Flow"
|
||||
SIMPLEFIN = "simplefin", "SimpleFIN"
|
||||
PLUGGY = "pluggy", "Pluggy"
|
||||
|
||||
name = models.CharField(max_length=255, verbose_name=_("Name"))
|
||||
service_type = models.CharField(
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
from apps.bank_sync.providers.lunchflow import LunchFlowProvider
|
||||
from apps.bank_sync.providers.pluggy import PluggyProvider
|
||||
from apps.bank_sync.providers.simplefin import SimpleFINProvider
|
||||
|
||||
# Keys must match BankSyncService.ServiceType
|
||||
PROVIDER_MAPPING = {
|
||||
"lunchflow": LunchFlowProvider,
|
||||
"simplefin": SimpleFINProvider,
|
||||
"pluggy": PluggyProvider,
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
import re
|
||||
from datetime import date
|
||||
from decimal import Decimal
|
||||
from urllib.parse import parse_qs, urlsplit
|
||||
|
||||
import requests
|
||||
from django import forms
|
||||
from django.utils import timezone
|
||||
from django.utils.translation import gettext as _
|
||||
from django.utils.translation import gettext_lazy
|
||||
|
||||
from apps.bank_sync.providers.base import (
|
||||
BankSyncProvider,
|
||||
RemoteAccount,
|
||||
RemoteTransaction,
|
||||
)
|
||||
|
||||
BASE_URL = "https://api.pluggy.ai"
|
||||
# Item statuses that need the user to reconnect on Pluggy
|
||||
NEEDS_ACTION = {"LOGIN_ERROR", "WAITING_USER_INPUT"}
|
||||
|
||||
|
||||
class PluggyProvider(BankSyncProvider):
|
||||
"""https://docs.pluggy.ai"""
|
||||
|
||||
settings_fields = {
|
||||
"client_id": forms.CharField(
|
||||
label=gettext_lazy("Client ID"),
|
||||
widget=forms.TextInput(attrs={"autocomplete": "off"}),
|
||||
),
|
||||
"client_secret": forms.CharField(
|
||||
label=gettext_lazy("Client Secret"),
|
||||
# Not a PasswordInput: browsers autofill those with saved logins
|
||||
widget=forms.TextInput(attrs={"autocomplete": "off"}),
|
||||
),
|
||||
"item_ids": forms.CharField(
|
||||
label=gettext_lazy("Item IDs"),
|
||||
widget=forms.TextInput(attrs={"autocomplete": "off"}),
|
||||
help_text=gettext_lazy(
|
||||
"The IDs of your Pluggy connections (items), separated by commas. "
|
||||
"Meu Pluggy shows them for each connected institution."
|
||||
),
|
||||
),
|
||||
}
|
||||
|
||||
def __init__(self, settings: dict):
|
||||
super().__init__(settings)
|
||||
self.session = requests.Session()
|
||||
self.item_ids = [
|
||||
item_id
|
||||
for item_id in re.split(r"[\s,]+", self.settings.get("item_ids", ""))
|
||||
if item_id
|
||||
]
|
||||
|
||||
def _get(self, path: str, **params) -> dict:
|
||||
if "X-API-KEY" not in self.session.headers:
|
||||
# Lasts 2 hours, longer than any sync
|
||||
response = self.session.post(
|
||||
f"{BASE_URL}/auth",
|
||||
json={
|
||||
"clientId": self.settings.get("client_id", ""),
|
||||
"clientSecret": self.settings.get("client_secret", ""),
|
||||
},
|
||||
timeout=30,
|
||||
)
|
||||
response.raise_for_status()
|
||||
self.session.headers["X-API-KEY"] = response.json()["apiKey"]
|
||||
response = self.session.get(f"{BASE_URL}{path}", params=params, timeout=30)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
def list_accounts(self) -> list[RemoteAccount]:
|
||||
accounts = []
|
||||
for item_id in self.item_ids:
|
||||
item = self._get(f"/items/{item_id}")
|
||||
institution = (item.get("connector") or {}).get("name")
|
||||
status = item.get("status") or ""
|
||||
error = (
|
||||
_(
|
||||
"Pluggy reports this connection as %(status)s, reconnect it "
|
||||
"on Pluggy."
|
||||
)
|
||||
% {"status": status}
|
||||
if status in NEEDS_ACTION
|
||||
else ""
|
||||
)
|
||||
for account in self._get("/accounts", itemId=item_id)["results"]:
|
||||
currency = account.get("currencyCode") or ""
|
||||
accounts.append(
|
||||
RemoteAccount(
|
||||
id=str(account["id"]),
|
||||
name=" - ".join(
|
||||
filter(
|
||||
None,
|
||||
[
|
||||
institution,
|
||||
account.get("marketingName") or account["name"],
|
||||
account.get("number"),
|
||||
],
|
||||
)
|
||||
),
|
||||
currencies=(currency.upper(),) if currency else (),
|
||||
error=error,
|
||||
)
|
||||
)
|
||||
return accounts
|
||||
|
||||
def get_transactions(
|
||||
self, account_id: str, start_date: date
|
||||
) -> list[RemoteTransaction]:
|
||||
params = {"accountId": account_id, "dateFrom": start_date.isoformat()}
|
||||
transactions = []
|
||||
while True:
|
||||
data = self._get("/v2/transactions", **params)
|
||||
for tx in data["results"]:
|
||||
day = date.fromisoformat(tx["date"][:10])
|
||||
# Pending keeps its id once it posts (a card's open bill). Future
|
||||
# ones (installments, scheduled payments) wait for their date
|
||||
pending = tx.get("status") == "PENDING"
|
||||
if pending and day > timezone.localdate():
|
||||
continue
|
||||
converted = tx.get("amountInAccountCurrency")
|
||||
amount = abs(Decimal(str(tx["amount"] if converted is None else converted)))
|
||||
notes = ""
|
||||
if converted is not None:
|
||||
# Foreign purchase: keep the account's amount, note the original
|
||||
notes = f"{tx.get('currencyCode', '')} {abs(Decimal(str(tx['amount'])))}"
|
||||
transactions.append(
|
||||
RemoteTransaction(
|
||||
id=str(tx["id"]),
|
||||
# Installments already come dated in their own month
|
||||
date=day,
|
||||
# Not the amount's sign: cards keep theirs, purchases are
|
||||
# positive. `type` is normalized for every account
|
||||
amount=amount if tx.get("type") == "CREDIT" else -amount,
|
||||
description=(tx.get("description") or "").strip(),
|
||||
notes=notes,
|
||||
currency=""
|
||||
if converted is not None
|
||||
else (tx.get("currencyCode") or "").upper(),
|
||||
pending=pending,
|
||||
)
|
||||
)
|
||||
if not data.get("next"):
|
||||
return transactions
|
||||
# Send our own filters again with the cursor, `next` may drop them
|
||||
params["after"] = parse_qs(urlsplit(data["next"]).query)["after"][0]
|
||||
@@ -18,6 +18,7 @@ from apps.bank_sync.forms import BankSyncAccountForm, BankSyncServiceForm
|
||||
from apps.bank_sync.models import BankSyncAccount, BankSyncService
|
||||
from apps.bank_sync.providers.base import RemoteAccount, RemoteTransaction
|
||||
from apps.bank_sync.providers.lunchflow import LunchFlowProvider
|
||||
from apps.bank_sync.providers.pluggy import PluggyProvider
|
||||
from apps.bank_sync.providers.simplefin import SimpleFINProvider
|
||||
from apps.bank_sync.providers.simplefin import _timestamp as _ts
|
||||
from apps.bank_sync.sync import is_due, refresh_remote_accounts, sync_service
|
||||
@@ -209,6 +210,111 @@ class SimpleFINProviderTests(TestCase):
|
||||
)
|
||||
|
||||
|
||||
class PluggyProviderTests(TestCase):
|
||||
def setUp(self):
|
||||
self.provider = PluggyProvider(
|
||||
{"client_id": "id", "client_secret": "secret", "item_ids": "i1, i2\n"}
|
||||
)
|
||||
auth = _response({"apiKey": "key"})
|
||||
self.post = self.enterContext(
|
||||
patch.object(self.provider.session, "post", return_value=auth)
|
||||
)
|
||||
|
||||
def test_list_accounts(self):
|
||||
def get(url, params, timeout):
|
||||
self.assertEqual(self.provider.session.headers["X-API-KEY"], "key")
|
||||
if url.endswith("/items/i1"):
|
||||
return _response({"status": "UPDATED", "connector": {"name": "Nubank"}})
|
||||
if url.endswith("/items/i2"):
|
||||
return _response({"status": "LOGIN_ERROR", "connector": {"name": "Itaú"}})
|
||||
return _response(
|
||||
{
|
||||
"results": [
|
||||
{"id": f"{params['itemId']}-a", "name": "Conta", "marketingName": None, "number": "0001", "currencyCode": "BRL"}
|
||||
]
|
||||
}
|
||||
)
|
||||
|
||||
with patch.object(self.provider.session, "get", side_effect=get):
|
||||
accounts = self.provider.list_accounts()
|
||||
|
||||
self.post.assert_called_once_with(
|
||||
"https://api.pluggy.ai/auth",
|
||||
json={"clientId": "id", "clientSecret": "secret"},
|
||||
timeout=30,
|
||||
)
|
||||
self.assertEqual(accounts[0], RemoteAccount("i1-a", "Nubank - Conta - 0001", ("BRL",), ""))
|
||||
self.assertEqual(accounts[1].id, "i2-a")
|
||||
self.assertIn("LOGIN_ERROR", accounts[1].error)
|
||||
|
||||
def _get_transactions(self, pages):
|
||||
responses = [_response(p) for p in pages]
|
||||
with patch.object(self.provider.session, "get", side_effect=responses) as get:
|
||||
transactions = self.provider.get_transactions("a", date(2026, 10, 1))
|
||||
return transactions, get.call_args_list
|
||||
|
||||
def test_bank_account_follows_cursor_with_own_filters(self):
|
||||
pages = [
|
||||
{
|
||||
"results": [
|
||||
{"id": "t1", "date": "2026-10-01T03:00:00.000Z", "amount": -12.5, "type": "DEBIT", "status": "POSTED", "description": "Padaria", "currencyCode": "BRL"},
|
||||
{"id": "t2", "date": "2026-10-02T03:00:00.000Z", "amount": -1, "type": "DEBIT", "status": "PENDING", "description": "Pending"},
|
||||
],
|
||||
"next": "?accountId=a&after=MjAy%3D",
|
||||
},
|
||||
{
|
||||
"results": [
|
||||
{"id": "t3", "date": "2026-10-04T03:00:00.000Z", "amount": 100, "type": "CREDIT", "status": "POSTED", "description": "Pix", "currencyCode": "BRL"},
|
||||
],
|
||||
"next": None,
|
||||
},
|
||||
]
|
||||
transactions, calls = self._get_transactions(pages)
|
||||
|
||||
self.assertEqual(
|
||||
[c.kwargs["params"] for c in calls],
|
||||
[
|
||||
{"accountId": "a", "dateFrom": "2026-10-01"},
|
||||
{"accountId": "a", "dateFrom": "2026-10-01", "after": "MjAy="},
|
||||
],
|
||||
)
|
||||
self.assertEqual(
|
||||
transactions,
|
||||
[
|
||||
RemoteTransaction("t1", date(2026, 10, 1), Decimal("-12.5"), "Padaria", "", "BRL"),
|
||||
RemoteTransaction("t2", date(2026, 10, 2), Decimal("-1"), "Pending", "", "", pending=True),
|
||||
RemoteTransaction("t3", date(2026, 10, 4), Decimal("100"), "Pix", "", "BRL"),
|
||||
],
|
||||
)
|
||||
|
||||
def test_credit_card_follows_type_not_sign(self):
|
||||
# Shapes from a real Meu Pluggy card: purchases are positive DEBITs,
|
||||
# the bill payment a negative CREDIT
|
||||
pages = [
|
||||
{
|
||||
"results": [
|
||||
{"id": "t1", "date": "2026-10-03T03:00:00.000Z", "amount": 10, "amountInAccountCurrency": 55.3, "type": "DEBIT", "status": "POSTED", "description": "Steam", "currencyCode": "USD"},
|
||||
{"id": "t2", "date": "2026-10-05T03:00:00.000Z", "amount": -500, "type": "CREDIT", "status": "POSTED", "description": "Pagamento recebido", "currencyCode": "BRL"},
|
||||
{"id": "t3", "date": "2026-10-13T03:00:00.000Z", "amount": 18.72, "type": "DEBIT", "status": "POSTED", "description": "Loja 2/10", "currencyCode": "BRL",
|
||||
"creditCardMetadata": {"installmentNumber": 2, "totalInstallments": 10, "purchaseDate": "2026-09-12T03:00:00.000Z"}},
|
||||
# Future installment, waits for its date
|
||||
{"id": "t4", "date": "2027-07-13T03:00:00.000Z", "amount": 18.72, "type": "DEBIT", "status": "PENDING", "description": "Loja 10/10", "currencyCode": "BRL"},
|
||||
],
|
||||
"next": None,
|
||||
},
|
||||
]
|
||||
transactions, _ = self._get_transactions(pages)
|
||||
|
||||
self.assertEqual(
|
||||
transactions,
|
||||
[
|
||||
RemoteTransaction("t1", date(2026, 10, 3), Decimal("-55.3"), "Steam", "USD 10", ""),
|
||||
RemoteTransaction("t2", date(2026, 10, 5), Decimal("500"), "Pagamento recebido", "", "BRL"),
|
||||
RemoteTransaction("t3", date(2026, 10, 13), Decimal("-18.72"), "Loja 2/10", "", "BRL"),
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
class FakeProvider:
|
||||
def __init__(self, transactions=(), accounts=()):
|
||||
self.transactions = list(transactions)
|
||||
|
||||
Reference in new issue
Block a user