mulasharp 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
mulasharp/__init__.py ADDED
@@ -0,0 +1,36 @@
1
+ from .client import MulaSharpClient, SyncResult
2
+ from .errors import MulaSharpError, ConnectionExpired, NotFound, ProviderError, ValidationError
3
+ from .models import Account, Connection, Transaction
4
+ from .providers.base import Provider
5
+ from .providers.gocardless import GoCardlessProvider, NordigenProvider
6
+ from .providers.mock import MockProvider
7
+ from .providers.plaid import PlaidProvider
8
+ from .providers.tink import TinkProvider
9
+ from .providers.truelayer import TrueLayerProvider
10
+ from .providers import available_providers, get_provider
11
+ from .store import SyncStore
12
+
13
+ __all__ = [
14
+ "MulaSharpClient",
15
+ "SyncResult",
16
+ "MulaSharpError",
17
+ "ProviderError",
18
+ "ConnectionExpired",
19
+ "NotFound",
20
+ "ValidationError",
21
+ "Connection",
22
+ "Account",
23
+ "Transaction",
24
+ "Provider",
25
+ "MockProvider",
26
+ "GoCardlessProvider",
27
+ "NordigenProvider",
28
+ "PlaidProvider",
29
+ "TrueLayerProvider",
30
+ "TinkProvider",
31
+ "available_providers",
32
+ "get_provider",
33
+ "SyncStore",
34
+ ]
35
+
36
+ __version__ = "0.1.0"
mulasharp/client.py ADDED
@@ -0,0 +1,164 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from datetime import datetime, timezone
5
+ from typing import Any
6
+
7
+ from .models import Account, Connection, Transaction
8
+ from .providers.base import Provider
9
+ from .store import SyncStore
10
+ from .errors import NotFound
11
+
12
+
13
+ @dataclass
14
+ class SyncResult:
15
+ connection_id: str
16
+ accounts: int
17
+ transactions_seen: int
18
+ inserted: int
19
+ updated: int
20
+ cursor: str | None = None
21
+
22
+ def to_dict(self) -> dict[str, Any]:
23
+ return {
24
+ "connection_id": self.connection_id,
25
+ "accounts": self.accounts,
26
+ "transactions_seen": self.transactions_seen,
27
+ "inserted": self.inserted,
28
+ "updated": self.updated,
29
+ "cursor": self.cursor,
30
+ }
31
+
32
+
33
+ class MulaSharpClient:
34
+ """High-level client for connecting banks and syncing transactions."""
35
+
36
+ def __init__(self, provider: Provider, store: SyncStore):
37
+ self.provider = provider
38
+ self.store = store
39
+
40
+ def connect(self, user_id: str, **kwargs: Any) -> Connection:
41
+ """Create a connection via the provider and store it."""
42
+ conn = self.provider.create_connection(user_id, **kwargs)
43
+ self.store.save_connection(conn)
44
+ return conn
45
+
46
+ def refresh_connection(self, connection_id: str) -> Connection:
47
+ conn = self.provider.get_connection(connection_id)
48
+ self.store.save_connection(conn)
49
+ return conn
50
+
51
+ def list_connections(self, *, user_id: str | None = None) -> list[Connection]:
52
+ return self.store.list_connections(user_id=user_id)
53
+
54
+ def sync_accounts(self, connection_id: str) -> list[Account]:
55
+ conn = self._require_connection(connection_id)
56
+ accounts = self.provider.list_accounts(conn)
57
+ for account in accounts:
58
+ self.store.upsert_account(account)
59
+ return accounts
60
+
61
+ def sync_transactions(
62
+ self,
63
+ connection_id: str,
64
+ *,
65
+ account_id: str | None = None,
66
+ date_from: str | None = None,
67
+ date_to: str | None = None,
68
+ full_refresh: bool = False,
69
+ ) -> SyncResult:
70
+ """Sync transactions for a connection (or one account).
71
+
72
+ Uses a stored cursor per account unless full_refresh=True.
73
+ Deduplication is handled by the store using Transaction.uid.
74
+ """
75
+ conn = self._require_connection(connection_id)
76
+ accounts = self.store.list_accounts(connection_id)
77
+ if not accounts:
78
+ accounts = self.sync_accounts(connection_id)
79
+ if account_id:
80
+ accounts = [a for a in accounts if a.id == account_id]
81
+
82
+ total_seen = 0
83
+ total_inserted = 0
84
+ total_updated = 0
85
+ last_cursor: str | None = None
86
+
87
+ for account in accounts:
88
+ cursor_key = f"txn_cursor:{self.provider.name}:{account.id}"
89
+ cursor = None if full_refresh else self.store.get_cursor(cursor_key)
90
+ while True:
91
+ batch, next_cursor = self.provider.list_transactions(
92
+ conn,
93
+ account,
94
+ date_from=date_from,
95
+ date_to=date_to,
96
+ cursor=cursor,
97
+ )
98
+ if batch:
99
+ counts = self.store.upsert_transactions(batch)
100
+ total_seen += counts["total"]
101
+ total_inserted += counts["inserted"]
102
+ total_updated += counts["updated"]
103
+ if next_cursor:
104
+ self.store.set_cursor(cursor_key, next_cursor)
105
+ last_cursor = next_cursor
106
+ cursor = next_cursor
107
+ continue
108
+ # no next cursor: save a "synced" marker when we got a cursor-based page
109
+ if cursor is None:
110
+ self.store.set_cursor(cursor_key, "synced:" + datetime.now(timezone.utc).isoformat())
111
+ break
112
+
113
+ return SyncResult(
114
+ connection_id=connection_id,
115
+ accounts=len(accounts),
116
+ transactions_seen=total_seen,
117
+ inserted=total_inserted,
118
+ updated=total_updated,
119
+ cursor=last_cursor,
120
+ )
121
+
122
+ def list_accounts(self, connection_id: str) -> list[Account]:
123
+ return self.store.list_accounts(connection_id)
124
+
125
+ def list_transactions(self, account_id: str, **kwargs: Any) -> list[Transaction]:
126
+ return self.store.list_transactions(account_id, **kwargs)
127
+
128
+ def sync_all(self, *, user_id: str | None = None, **kwargs: Any) -> list[SyncResult]:
129
+ """Sync transactions for all stored connections (optionally for one user)."""
130
+ results: list[SyncResult] = []
131
+ for conn in self.store.list_connections(user_id=user_id):
132
+ if conn.needs_reconnect:
133
+ continue
134
+ results.append(self.sync_transactions(conn.id, **kwargs))
135
+ return results
136
+
137
+ def delete_connection(self, connection_id: str) -> bool:
138
+ return self.store.delete_connection(connection_id)
139
+
140
+ def _require_connection(self, connection_id: str) -> Connection:
141
+ conn = self.store.get_connection(connection_id)
142
+ if conn is None:
143
+ # try provider (useful when provider owns the record) and persist
144
+ try:
145
+ conn = self.provider.get_connection(connection_id)
146
+ except Exception as e:
147
+ raise NotFound(f"Connection not found: {connection_id}") from e
148
+ self.store.save_connection(conn)
149
+ # expire local status if past expires_at
150
+ if conn.expires_at and conn.status == "active":
151
+ now = datetime.now(timezone.utc)
152
+ exp = conn.expires_at if conn.expires_at.tzinfo else conn.expires_at.replace(tzinfo=timezone.utc)
153
+ if exp <= now:
154
+ conn = Connection(
155
+ id=conn.id,
156
+ provider=conn.provider,
157
+ user_id=conn.user_id,
158
+ status="expired",
159
+ created_at=conn.created_at,
160
+ expires_at=conn.expires_at,
161
+ provider_data=conn.provider_data,
162
+ )
163
+ self.store.save_connection(conn)
164
+ return conn
mulasharp/errors.py ADDED
@@ -0,0 +1,21 @@
1
+ """Errors for mulasharp."""
2
+
3
+
4
+ class MulaSharpError(Exception):
5
+ """Base error."""
6
+
7
+
8
+ class ProviderError(MulaSharpError):
9
+ """Raised when a provider API call fails."""
10
+
11
+
12
+ class ConnectionExpired(MulaSharpError):
13
+ """Raised when a connection/consent is expired and needs user action."""
14
+
15
+
16
+ class NotFound(MulaSharpError):
17
+ """Raised when a requested resource is not found."""
18
+
19
+
20
+ class ValidationError(MulaSharpError):
21
+ """Raised when input data is invalid."""
mulasharp/models.py ADDED
@@ -0,0 +1,116 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass, field
4
+ from datetime import date, datetime, timezone
5
+ from typing import Any, Optional
6
+
7
+
8
+ def _iso_date(value: date | datetime | None) -> str | None:
9
+ if value is None:
10
+ return None
11
+ if isinstance(value, datetime):
12
+ return value.date().isoformat()
13
+ return value.isoformat()
14
+
15
+
16
+ @dataclass(frozen=True)
17
+ class Connection:
18
+ """A user's connection to a bank/provider."""
19
+
20
+ id: str
21
+ provider: str
22
+ user_id: str
23
+ status: str = "active" # active | pending | expired | revoked | error
24
+ created_at: datetime | None = None
25
+ expires_at: datetime | None = None
26
+ provider_data: dict[str, Any] = field(default_factory=dict)
27
+
28
+ @property
29
+ def is_expired(self) -> bool:
30
+ if self.status == "expired":
31
+ return True
32
+ if self.expires_at is None:
33
+ return False
34
+ now = datetime.now(timezone.utc)
35
+ exp = self.expires_at if self.expires_at.tzinfo else self.expires_at.replace(tzinfo=timezone.utc)
36
+ return exp <= now
37
+
38
+ @property
39
+ def needs_reconnect(self) -> bool:
40
+ return self.status in {"expired", "revoked", "error"} or self.is_expired
41
+
42
+ def to_dict(self) -> dict[str, Any]:
43
+ return {
44
+ "id": self.id,
45
+ "provider": self.provider,
46
+ "user_id": self.user_id,
47
+ "status": self.status,
48
+ "created_at": self.created_at.isoformat() if self.created_at else None,
49
+ "expires_at": self.expires_at.isoformat() if self.expires_at else None,
50
+ "provider_data": dict(self.provider_data),
51
+ }
52
+
53
+
54
+ @dataclass(frozen=True)
55
+ class Account:
56
+ """Normalized bank account."""
57
+
58
+ id: str
59
+ connection_id: str
60
+ provider: str
61
+ name: str | None
62
+ currency: str | None
63
+ type: str | None = None
64
+ iban: str | None = None
65
+ account_number_masked: str | None = None
66
+ raw: dict[str, Any] = field(default_factory=dict)
67
+
68
+ def to_dict(self) -> dict[str, Any]:
69
+ return {
70
+ "id": self.id,
71
+ "connection_id": self.connection_id,
72
+ "provider": self.provider,
73
+ "name": self.name,
74
+ "currency": self.currency,
75
+ "type": self.type,
76
+ "iban": self.iban,
77
+ "account_number_masked": self.account_number_masked,
78
+ "raw": dict(self.raw),
79
+ }
80
+
81
+
82
+ @dataclass(frozen=True)
83
+ class Transaction:
84
+ """Normalized transaction.
85
+
86
+ Amount convention: positive = money in, negative = money out.
87
+ """
88
+
89
+ uid: str
90
+ account_id: str
91
+ provider: str
92
+ amount: str # decimal string to avoid float surprises
93
+ currency: str | None
94
+ date: date
95
+ description: str
96
+ pending: bool = False
97
+ counterparty: str | None = None
98
+ reference: str | None = None
99
+ category: str | None = None
100
+ raw: dict[str, Any] = field(default_factory=dict)
101
+
102
+ def to_dict(self) -> dict[str, Any]:
103
+ return {
104
+ "uid": self.uid,
105
+ "account_id": self.account_id,
106
+ "provider": self.provider,
107
+ "amount": self.amount,
108
+ "currency": self.currency,
109
+ "date": self.date.isoformat(),
110
+ "description": self.description,
111
+ "pending": self.pending,
112
+ "counterparty": self.counterparty,
113
+ "reference": self.reference,
114
+ "category": self.category,
115
+ "raw": dict(self.raw),
116
+ }
@@ -0,0 +1,41 @@
1
+ from .base import Provider
2
+ from .gocardless import GoCardlessProvider, NordigenProvider
3
+ from .mock import MockProvider
4
+ from .plaid import PlaidProvider
5
+ from .tink import TinkProvider
6
+ from .truelayer import TrueLayerProvider
7
+
8
+
9
+ _REGISTRY = {
10
+ "mock": MockProvider,
11
+ "gocardless": GoCardlessProvider,
12
+ "nordigen": NordigenProvider, # alias
13
+ "plaid": PlaidProvider,
14
+ "truelayer": TrueLayerProvider,
15
+ "tink": TinkProvider,
16
+ }
17
+
18
+
19
+ def available_providers() -> list[str]:
20
+ return sorted(_REGISTRY.keys())
21
+
22
+
23
+ def get_provider(name: str, **kwargs):
24
+ cls = _REGISTRY.get(name.lower())
25
+ if not cls:
26
+ known = ", ".join(available_providers())
27
+ raise KeyError(f"Unknown provider '{name}'. Available: {known}")
28
+ return cls(**kwargs)
29
+
30
+
31
+ __all__ = [
32
+ "Provider",
33
+ "MockProvider",
34
+ "GoCardlessProvider",
35
+ "NordigenProvider",
36
+ "PlaidProvider",
37
+ "TrueLayerProvider",
38
+ "TinkProvider",
39
+ "available_providers",
40
+ "get_provider",
41
+ ]
@@ -0,0 +1,43 @@
1
+ from __future__ import annotations
2
+
3
+ from abc import ABC, abstractmethod
4
+ from typing import Any, Iterable
5
+
6
+ from ..models import Account, Connection, Transaction
7
+
8
+
9
+ class Provider(ABC):
10
+ """Provider adapter interface.
11
+
12
+ Implement this to plug in a real open-banking aggregator.
13
+ """
14
+
15
+ name: str
16
+
17
+ @abstractmethod
18
+ def create_connection(self, user_id: str, **kwargs: Any) -> Connection:
19
+ """Create/initiate a bank connection. May return pending connection with auth link in provider_data."""
20
+
21
+ @abstractmethod
22
+ def get_connection(self, connection_id: str) -> Connection:
23
+ """Fetch latest connection status."""
24
+
25
+ @abstractmethod
26
+ def list_accounts(self, connection: Connection) -> list[Account]:
27
+ """List normalized accounts for a connection."""
28
+
29
+ @abstractmethod
30
+ def list_transactions(
31
+ self,
32
+ connection: Connection,
33
+ account: Account,
34
+ *,
35
+ date_from: str | None = None,
36
+ date_to: str | None = None,
37
+ cursor: str | None = None,
38
+ ) -> tuple[list[Transaction], str | None]:
39
+ """Return (transactions, next_cursor)."""
40
+
41
+ def exchange_connection(self, connection: Connection, **kwargs: Any) -> Connection:
42
+ """Optional step for providers that need token/code exchange."""
43
+ return connection