aiocospend 0.2.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.
aiocospend/__init__.py ADDED
@@ -0,0 +1,74 @@
1
+ """Client asynchrone pour l'API OCS de Nextcloud Cospend."""
2
+
3
+ from .client import CospendClient
4
+ from .const import MIN_COSPEND_VERSION
5
+ from .exceptions import (
6
+ CospendAuthenticationError,
7
+ CospendBadRequestError,
8
+ CospendConnectionError,
9
+ CospendError,
10
+ CospendForbiddenError,
11
+ CospendMaintenanceError,
12
+ CospendNotFoundError,
13
+ CospendResponseError,
14
+ CospendServerError,
15
+ CospendSSLError,
16
+ CospendVersionError,
17
+ )
18
+ from .models import (
19
+ Bill,
20
+ BillsPage,
21
+ Category,
22
+ Currency,
23
+ Member,
24
+ MemberStats,
25
+ Ower,
26
+ PaymentMode,
27
+ Project,
28
+ ProjectStatistics,
29
+ ServerInfo,
30
+ Settlement,
31
+ Share,
32
+ Transaction,
33
+ )
34
+ from .sync import BillChanges, ProjectBills
35
+ from .utils import compare_versions, format_amount, normalize_url, parse_version
36
+
37
+ __version__ = "0.2.0"
38
+
39
+ __all__ = [
40
+ "MIN_COSPEND_VERSION",
41
+ "Bill",
42
+ "BillChanges",
43
+ "BillsPage",
44
+ "Category",
45
+ "CospendAuthenticationError",
46
+ "CospendBadRequestError",
47
+ "CospendClient",
48
+ "CospendConnectionError",
49
+ "CospendError",
50
+ "CospendForbiddenError",
51
+ "CospendMaintenanceError",
52
+ "CospendNotFoundError",
53
+ "CospendResponseError",
54
+ "CospendSSLError",
55
+ "CospendServerError",
56
+ "CospendVersionError",
57
+ "Currency",
58
+ "Member",
59
+ "MemberStats",
60
+ "Ower",
61
+ "PaymentMode",
62
+ "Project",
63
+ "ProjectBills",
64
+ "ProjectStatistics",
65
+ "ServerInfo",
66
+ "Settlement",
67
+ "Share",
68
+ "Transaction",
69
+ "__version__",
70
+ "compare_versions",
71
+ "format_amount",
72
+ "normalize_url",
73
+ "parse_version",
74
+ ]
aiocospend/client.py ADDED
@@ -0,0 +1,429 @@
1
+ """Client asynchrone pour l'API OCS de Nextcloud Cospend.
2
+
3
+ Comportements relevés sur un serveur Cospend 4.3.0 (voir les jeux d'essai) :
4
+
5
+ * les écritures sont envoyées en **formulaire** (``application/x-www-form-urlencoded``) ;
6
+ * la création envoie **tous** les champs, comme l'application Cowspent ;
7
+ * une modification partielle ne touche que les champs envoyés ;
8
+ * une suppression envoie la dépense en corbeille ; **supprimer une dépense déjà en corbeille la
9
+ supprime définitivement**. Ce client ne rejoue jamais une suppression de lui-même : l'appelant
10
+ doit relire l'état de la dépense avant de réessayer.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import base64
16
+ import json
17
+ from collections.abc import AsyncIterator, Mapping, Sequence
18
+ from decimal import Decimal
19
+ from typing import Any
20
+ from urllib.parse import quote
21
+
22
+ import aiohttp
23
+
24
+ from .const import API_VERSION, CAPABILITIES_PATH, MIN_COSPEND_VERSION, OCS_BASE_PATH
25
+ from .exceptions import (
26
+ CospendAuthenticationError,
27
+ CospendBadRequestError,
28
+ CospendConnectionError,
29
+ CospendError,
30
+ CospendForbiddenError,
31
+ CospendMaintenanceError,
32
+ CospendNotFoundError,
33
+ CospendResponseError,
34
+ CospendServerError,
35
+ CospendSSLError,
36
+ CospendVersionError,
37
+ )
38
+ from .models import (
39
+ Bill,
40
+ BillsPage,
41
+ Project,
42
+ ProjectStatistics,
43
+ ServerInfo,
44
+ Settlement,
45
+ )
46
+ from .utils import compare_versions, format_amount, normalize_url
47
+
48
+ DEFAULT_TIMEOUT = 30.0
49
+ DEFAULT_PAGE_SIZE = 50
50
+
51
+ type Amount = int | float | Decimal | str
52
+
53
+
54
+ def _query_value(value: Any) -> str:
55
+ if isinstance(value, bool):
56
+ return "true" if value else "false"
57
+ return str(value)
58
+
59
+
60
+ def basic_auth_header(username: str, password: str) -> str:
61
+ """En-tête ``Authorization`` Basic (sans dépendre de l'API d'authentification d'aiohttp)."""
62
+ token = base64.b64encode(f"{username}:{password}".encode()).decode("ascii")
63
+ return f"Basic {token}"
64
+
65
+
66
+ def _clean(params: Mapping[str, Any]) -> dict[str, str]:
67
+ """Retire les valeurs ``None`` et convertit tout en texte."""
68
+ return {key: _query_value(value) for key, value in params.items() if value is not None}
69
+
70
+
71
+ class CospendClient:
72
+ """Client de l'API Cospend d'un serveur Nextcloud.
73
+
74
+ ``session`` est fournie par l'appelant (celle de Home Assistant en production). Les
75
+ identifiants ne sont pas attachés à la session : ils sont envoyés à chaque requête.
76
+ """
77
+
78
+ def __init__(
79
+ self,
80
+ session: aiohttp.ClientSession,
81
+ base_url: str,
82
+ username: str,
83
+ password: str,
84
+ *,
85
+ timeout: float = DEFAULT_TIMEOUT,
86
+ ) -> None:
87
+ self._session = session
88
+ self._base_url = normalize_url(base_url)
89
+ self._authorization = basic_auth_header(username, password)
90
+ self._timeout = aiohttp.ClientTimeout(total=timeout)
91
+
92
+ @property
93
+ def base_url(self) -> str:
94
+ return self._base_url
95
+
96
+ # ------------------------------------------------------------------ requêtes
97
+
98
+ def _api(self, path: str = "") -> str:
99
+ return f"{OCS_BASE_PATH}/{API_VERSION}{path}"
100
+
101
+ async def _request(
102
+ self,
103
+ method: str,
104
+ path: str,
105
+ *,
106
+ params: Mapping[str, Any] | None = None,
107
+ form: Mapping[str, Any] | None = None,
108
+ ) -> Any:
109
+ """Envoie une requête OCS et renvoie le contenu de ``ocs.data``."""
110
+ try:
111
+ async with self._session.request(
112
+ method,
113
+ f"{self._base_url}{path}",
114
+ params=_clean(params) if params else None,
115
+ data=_clean(form) if form is not None else None,
116
+ headers={
117
+ "OCS-APIRequest": "true",
118
+ "Accept": "application/json",
119
+ "Authorization": self._authorization,
120
+ },
121
+ timeout=self._timeout,
122
+ ) as response:
123
+ status = response.status
124
+ text = await response.text()
125
+ except aiohttp.ClientSSLError as err:
126
+ raise CospendSSLError(f"Certificat refusé : {err}") from err
127
+ except TimeoutError as err:
128
+ raise CospendConnectionError("Délai dépassé") from err
129
+ except aiohttp.ClientError as err:
130
+ raise CospendConnectionError(f"Connexion impossible : {err}") from err
131
+
132
+ if status >= 400:
133
+ raise self._error_for(status, text)
134
+ try:
135
+ payload = json.loads(text)
136
+ return payload["ocs"]["data"]
137
+ except (ValueError, KeyError, TypeError) as err:
138
+ raise CospendResponseError(
139
+ "Réponse inattendue (adresse du serveur incorrecte ?)", status=status
140
+ ) from err
141
+
142
+ @staticmethod
143
+ def _error_for(status: int, text: str) -> CospendError:
144
+ detail = f"HTTP {status}"
145
+ if status == 401:
146
+ return CospendAuthenticationError(f"{detail} : identifiants refusés", status=status)
147
+ if status == 403:
148
+ return CospendForbiddenError(f"{detail} : accès refusé", status=status)
149
+ if status == 404:
150
+ return CospendNotFoundError(f"{detail} : introuvable", status=status)
151
+ if status == 400:
152
+ return CospendBadRequestError(f"{detail} : requête refusée", status=status)
153
+ if status == 503:
154
+ return CospendMaintenanceError(f"{detail} : serveur en maintenance", status=status)
155
+ if status >= 500:
156
+ return CospendServerError(f"{detail} : erreur du serveur", status=status)
157
+ return CospendError(f"{detail} : {text[:200]}", status=status)
158
+
159
+ # ------------------------------------------------------------------ connexion
160
+
161
+ async def get_server_info(self) -> ServerInfo:
162
+ """Version de Cospend et état de la fédération (``capabilities``)."""
163
+ data = await self._request("GET", CAPABILITIES_PATH)
164
+ try:
165
+ cospend = data["capabilities"]["cospend"]
166
+ return ServerInfo(
167
+ version=str(cospend["version"]),
168
+ federation_enabled=bool(cospend.get("federation", {}).get("enabled", False)),
169
+ )
170
+ except (KeyError, TypeError) as err:
171
+ raise CospendVersionError("L'application Cospend est absente ou désactivée") from err
172
+
173
+ async def ping(self) -> None:
174
+ """Vérifie que l'API Cospend répond avec ces identifiants."""
175
+ await self._request("GET", self._api("/ping"))
176
+
177
+ async def check_connection(self) -> ServerInfo:
178
+ """Valide l'adresse, les identifiants et la version minimale de Cospend."""
179
+ info = await self.get_server_info()
180
+ try:
181
+ too_old = compare_versions(info.version, MIN_COSPEND_VERSION) < 0
182
+ except ValueError as err:
183
+ raise CospendResponseError(f"Version illisible : {info.version!r}") from err
184
+ if too_old:
185
+ raise CospendVersionError(
186
+ f"Cospend {info.version} est trop ancienne (minimum {MIN_COSPEND_VERSION})"
187
+ )
188
+ await self.ping()
189
+ return info
190
+
191
+ # ------------------------------------------------------------------ projets
192
+
193
+ async def get_projects(self) -> list[Project]:
194
+ """Projets du compte, avec membres, catégories, modes de paiement et soldes."""
195
+ data = await self._request("GET", self._api("/projects"))
196
+ if not isinstance(data, list):
197
+ raise CospendResponseError("La liste des projets n'est pas une liste")
198
+ return [Project.from_api(item) for item in data]
199
+
200
+ async def get_project(self, project_id: str) -> Project:
201
+ data = await self._request("GET", self._api(f"/projects/{quote(project_id, safe='')}"))
202
+ return Project.from_api(data)
203
+
204
+ # ------------------------------------------------------------------ dépenses
205
+
206
+ def _bills_path(self, project_id: str, bill_id: int | None = None) -> str:
207
+ path = self._api(f"/projects/{quote(project_id, safe='')}/bills")
208
+ return path if bill_id is None else f"{path}/{bill_id}"
209
+
210
+ async def get_bills(
211
+ self,
212
+ project_id: str,
213
+ *,
214
+ offset: int | None = None,
215
+ limit: int | None = None,
216
+ reverse: bool | None = None,
217
+ payer_id: int | None = None,
218
+ category_id: int | None = None,
219
+ payment_mode_id: int | None = None,
220
+ search_term: str | None = None,
221
+ deleted: bool = False,
222
+ last_changed: int | None = None,
223
+ ) -> BillsPage:
224
+ """Liste des dépenses.
225
+
226
+ Avec ``last_changed``, seules les dépenses visibles modifiées depuis ce curseur sont
227
+ renvoyées ; une dépense mise en corbeille n'est détectable que par son absence de
228
+ ``all_bill_ids``. Avec ``deleted=True``, on obtient la corbeille.
229
+ """
230
+ data = await self._request(
231
+ "GET",
232
+ self._bills_path(project_id),
233
+ params={
234
+ "offset": offset,
235
+ "limit": limit,
236
+ "reverse": reverse,
237
+ "payerId": payer_id,
238
+ "categoryId": category_id,
239
+ "paymentModeId": payment_mode_id,
240
+ "searchTerm": search_term,
241
+ "deleted": 1 if deleted else None,
242
+ "lastChanged": last_changed,
243
+ },
244
+ )
245
+ return BillsPage.from_api(data)
246
+
247
+ async def iter_bills(
248
+ self,
249
+ project_id: str,
250
+ *,
251
+ page_size: int = DEFAULT_PAGE_SIZE,
252
+ reverse: bool = True,
253
+ **filters: Any,
254
+ ) -> AsyncIterator[Bill]:
255
+ """Parcourt toutes les dépenses, page par page (de la plus récente à la plus ancienne)."""
256
+ offset = 0
257
+ while True:
258
+ page = await self.get_bills(
259
+ project_id, offset=offset, limit=page_size, reverse=reverse, **filters
260
+ )
261
+ for bill in page.bills:
262
+ yield bill
263
+ offset += len(page.bills)
264
+ if len(page.bills) < page_size:
265
+ return
266
+
267
+ async def get_bill(self, project_id: str, bill_id: int) -> Bill:
268
+ data = await self._request("GET", self._bills_path(project_id, bill_id))
269
+ return Bill.from_api(data)
270
+
271
+ async def create_bill(
272
+ self,
273
+ project_id: str,
274
+ *,
275
+ what: str,
276
+ amount: Amount,
277
+ payer_id: int,
278
+ payed_for: Sequence[int],
279
+ timestamp: int,
280
+ date: str,
281
+ comment: str = "",
282
+ category_id: int = 0,
283
+ payment_mode_id: int = 0,
284
+ payment_mode: str = "n",
285
+ repeat: str = "n",
286
+ repeat_freq: int | None = None,
287
+ repeat_until: str | None = None,
288
+ repeat_all_active: int | None = None,
289
+ ) -> int:
290
+ """Crée une dépense et renvoie son identifiant.
291
+
292
+ Tous les champs sont envoyés, comme le fait Cowspent. ``date`` (AAAA-MM-JJ) et
293
+ ``timestamp`` doivent être cohérents : l'appelant les calcule dans le même fuseau.
294
+ """
295
+ if not payed_for:
296
+ raise ValueError("au moins un participant est requis")
297
+ data = await self._request(
298
+ "POST",
299
+ self._bills_path(project_id),
300
+ form={
301
+ "date": date,
302
+ "what": what,
303
+ "payer": payer_id,
304
+ "amount": format_amount(amount),
305
+ "comment": comment,
306
+ "timestamp": timestamp,
307
+ "repeat": repeat,
308
+ "payedFor": ",".join(str(i) for i in payed_for),
309
+ "paymentMode": payment_mode,
310
+ "categoryId": category_id,
311
+ "paymentModeId": payment_mode_id,
312
+ "repeatFreq": repeat_freq,
313
+ "repeatUntil": repeat_until,
314
+ "repeatAllActive": repeat_all_active,
315
+ },
316
+ )
317
+ return self._bill_id(data)
318
+
319
+ async def update_bill(
320
+ self,
321
+ project_id: str,
322
+ bill_id: int,
323
+ *,
324
+ what: str | None = None,
325
+ amount: Amount | None = None,
326
+ payer_id: int | None = None,
327
+ payed_for: Sequence[int] | None = None,
328
+ timestamp: int | None = None,
329
+ date: str | None = None,
330
+ comment: str | None = None,
331
+ category_id: int | None = None,
332
+ payment_mode_id: int | None = None,
333
+ payment_mode: str | None = None,
334
+ repeat: str | None = None,
335
+ repeat_freq: int | None = None,
336
+ repeat_until: str | None = None,
337
+ repeat_all_active: int | None = None,
338
+ ) -> int:
339
+ """Modifie une dépense : seuls les champs fournis sont envoyés (testé sur Cospend 4.3.0)."""
340
+ form = {
341
+ "what": what,
342
+ "amount": format_amount(amount) if amount is not None else None,
343
+ "payer": payer_id,
344
+ "payedFor": ",".join(str(i) for i in payed_for) if payed_for is not None else None,
345
+ "timestamp": timestamp,
346
+ "date": date,
347
+ "comment": comment,
348
+ "categoryId": category_id,
349
+ "paymentModeId": payment_mode_id,
350
+ "paymentMode": payment_mode,
351
+ "repeat": repeat,
352
+ "repeatFreq": repeat_freq,
353
+ "repeatUntil": repeat_until,
354
+ "repeatAllActive": repeat_all_active,
355
+ }
356
+ if payed_for is not None and not payed_for:
357
+ raise ValueError("au moins un participant est requis")
358
+ if all(value is None for value in form.values()):
359
+ raise ValueError("aucun champ à modifier")
360
+ data = await self._request("PUT", self._bills_path(project_id, bill_id), form=form)
361
+ return self._bill_id(data)
362
+
363
+ async def delete_bill(
364
+ self, project_id: str, bill_id: int, *, move_to_trash: bool = True
365
+ ) -> None:
366
+ """Supprime une dépense : corbeille par défaut, définitivement si déjà en corbeille.
367
+
368
+ Ne jamais rejouer cet appel à l'aveugle (voir l'en-tête du module).
369
+ """
370
+ await self._request(
371
+ "DELETE",
372
+ self._bills_path(project_id, bill_id),
373
+ params=None if move_to_trash else {"moveToTrash": False},
374
+ )
375
+
376
+ @staticmethod
377
+ def _bill_id(data: Any) -> int:
378
+ try:
379
+ return int(data)
380
+ except (TypeError, ValueError) as err:
381
+ raise CospendResponseError(f"Identifiant de dépense attendu, reçu : {data!r}") from err
382
+
383
+ # ------------------------------------------------------------------ analyse
384
+
385
+ async def get_statistics(
386
+ self,
387
+ project_id: str,
388
+ *,
389
+ ts_min: int | None = None,
390
+ ts_max: int | None = None,
391
+ category_id: int | None = None,
392
+ payment_mode_id: int | None = None,
393
+ payer_id: int | None = None,
394
+ amount_min: float | None = None,
395
+ amount_max: float | None = None,
396
+ currency_id: int | None = None,
397
+ show_disabled: bool | None = None,
398
+ ) -> ProjectStatistics:
399
+ data = await self._request(
400
+ "GET",
401
+ self._api(f"/projects/{quote(project_id, safe='')}/statistics"),
402
+ params={
403
+ "tsMin": ts_min,
404
+ "tsMax": ts_max,
405
+ "categoryId": category_id,
406
+ "paymentModeId": payment_mode_id,
407
+ "payerId": payer_id,
408
+ "amountMin": amount_min,
409
+ "amountMax": amount_max,
410
+ "currencyId": currency_id,
411
+ "showDisabled": show_disabled,
412
+ },
413
+ )
414
+ return ProjectStatistics.from_api(data)
415
+
416
+ async def get_settlement(
417
+ self,
418
+ project_id: str,
419
+ *,
420
+ centered_on: int | None = None,
421
+ max_timestamp: int | None = None,
422
+ ) -> Settlement:
423
+ """Plan de remboursement du serveur (lecture seule)."""
424
+ data = await self._request(
425
+ "GET",
426
+ self._api(f"/projects/{quote(project_id, safe='')}/settlement"),
427
+ params={"centeredOn": centered_on, "maxTimestamp": max_timestamp},
428
+ )
429
+ return Settlement.from_api(data)
aiocospend/const.py ADDED
@@ -0,0 +1,25 @@
1
+ """Constantes de l'API Cospend, issues des tests sur un serveur réel (Cospend 4.3.0)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Final
6
+
7
+ # Version minimale de l'application Cospend (API OCS v1, paramètres en camelCase).
8
+ MIN_COSPEND_VERSION: Final = "1.6.1"
9
+
10
+ API_VERSION: Final = "v1"
11
+ OCS_BASE_PATH: Final = "/ocs/v2.php/apps/cospend/api"
12
+ CAPABILITIES_PATH: Final = "/ocs/v2.php/cloud/capabilities"
13
+
14
+ # Catégorie native attribuée par Cospend aux dépenses de remboursement.
15
+ REIMBURSEMENT_CATEGORY_ID: Final = -11
16
+ # Aucun mode de paiement / aucune catégorie.
17
+ NO_PAYMENT_MODE_ID: Final = 0
18
+ NO_CATEGORY_ID: Final = 0
19
+
20
+ # Codes de répétition d'une dépense ("n" = aucune).
21
+ REPEAT_NONE: Final = "n"
22
+ REPEAT_CODES: Final = ("n", "d", "w", "b", "s", "m", "y")
23
+
24
+ # Niveaux d'accès à un projet (4 = propriétaire, constaté sur le serveur de test).
25
+ ACCESS_LEVEL_OWNER: Final = 4
@@ -0,0 +1,52 @@
1
+ """Exceptions du client Cospend."""
2
+
3
+ from __future__ import annotations
4
+
5
+
6
+ class CospendError(Exception):
7
+ """Erreur de base du client Cospend."""
8
+
9
+ def __init__(self, message: str = "", *, status: int | None = None) -> None:
10
+ super().__init__(message)
11
+ self.message = message
12
+ self.status = status
13
+
14
+
15
+ class CospendConnectionError(CospendError):
16
+ """Serveur injoignable : réseau, délai dépassé, DNS."""
17
+
18
+
19
+ class CospendSSLError(CospendConnectionError):
20
+ """Échec de la vérification du certificat TLS."""
21
+
22
+
23
+ class CospendAuthenticationError(CospendError):
24
+ """Identifiants refusés (HTTP 401) : mot de passe d'application à renouveler."""
25
+
26
+
27
+ class CospendForbiddenError(CospendError):
28
+ """Accès refusé à la ressource (HTTP 403), par exemple droits insuffisants."""
29
+
30
+
31
+ class CospendNotFoundError(CospendError):
32
+ """Ressource introuvable (HTTP 404)."""
33
+
34
+
35
+ class CospendBadRequestError(CospendError):
36
+ """Requête refusée par le serveur (HTTP 400). Le message du serveur est souvent vide."""
37
+
38
+
39
+ class CospendMaintenanceError(CospendError):
40
+ """Serveur en maintenance (HTTP 503) : nouvel essai possible plus tard."""
41
+
42
+
43
+ class CospendServerError(CospendError):
44
+ """Erreur interne du serveur (HTTP 5xx hors 503)."""
45
+
46
+
47
+ class CospendResponseError(CospendError):
48
+ """Réponse inattendue : pas du JSON, enveloppe OCS absente, champ obligatoire manquant."""
49
+
50
+
51
+ class CospendVersionError(CospendError):
52
+ """Version de Cospend trop ancienne ou application Cospend absente."""
aiocospend/models.py ADDED
@@ -0,0 +1,452 @@
1
+ """Modèles de données de l'API Cospend.
2
+
3
+ Les formats viennent de réponses réelles de Cospend 4.3.0 ; voir ``tests/fixtures``.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import re
9
+ from collections.abc import Mapping
10
+ from dataclasses import dataclass, field
11
+ from typing import Any
12
+
13
+ from .exceptions import CospendResponseError
14
+
15
+ _MONTH = re.compile(r"^\d{4}-\d{2}$")
16
+
17
+ # Niveaux d'accès supposés d'après le code de Cospend (4 = propriétaire est confirmé) :
18
+ # à valider par les tests de contrat avant de s'appuyer dessus.
19
+ ACCESS_LEVEL_PARTICIPANT = 2
20
+
21
+
22
+ def _as_dict(value: Any) -> dict[Any, Any]:
23
+ """Normalise une table indexée par identifiant.
24
+
25
+ Le serveur est en PHP : un tableau dont les clés sont 0, 1, 2… est sérialisé en **liste**
26
+ JSON au lieu d'un objet. Cas réel : des dépenses sans catégorie donnent
27
+ ``categoryStats == [600]`` au lieu de ``{"0": 600}``. Une liste est donc lue comme
28
+ ``{0: v0, 1: v1, …}``.
29
+ """
30
+ if isinstance(value, Mapping):
31
+ return dict(value)
32
+ if isinstance(value, (list, tuple)):
33
+ return dict(enumerate(value))
34
+ return {}
35
+
36
+
37
+ def _invalid(kind: str, err: Exception) -> CospendResponseError:
38
+ return CospendResponseError(f"{kind} invalide dans la réponse du serveur : {err!r}")
39
+
40
+
41
+ @dataclass(frozen=True, slots=True)
42
+ class Ower:
43
+ """Participant à une dépense."""
44
+
45
+ id: int
46
+ weight: float
47
+ name: str
48
+ activated: bool
49
+
50
+ @classmethod
51
+ def from_api(cls, data: Mapping[str, Any]) -> Ower:
52
+ try:
53
+ return cls(
54
+ id=int(data["id"]),
55
+ weight=float(data.get("weight", 1)),
56
+ name=str(data.get("name") or ""),
57
+ activated=bool(data.get("activated", True)),
58
+ )
59
+ except (KeyError, TypeError, ValueError) as err:
60
+ raise _invalid("Participant", err) from err
61
+
62
+
63
+ @dataclass(frozen=True, slots=True)
64
+ class Bill:
65
+ """Dépense. Les montants sont ceux du serveur (flottants, non arrondis)."""
66
+
67
+ id: int
68
+ what: str
69
+ amount: float
70
+ comment: str
71
+ timestamp: int
72
+ date: str
73
+ payer_id: int
74
+ owers: tuple[Ower, ...]
75
+ repeat: str
76
+ repeat_freq: int
77
+ repeat_until: str | None
78
+ repeat_all_active: int
79
+ payment_mode: str
80
+ payment_mode_id: int
81
+ category_id: int
82
+ deleted: bool
83
+ last_changed: int
84
+ project_id: str | None = field(default=None, compare=False)
85
+
86
+ @property
87
+ def ower_ids(self) -> tuple[int, ...]:
88
+ return tuple(ower.id for ower in self.owers)
89
+
90
+ @classmethod
91
+ def from_api(cls, data: Mapping[str, Any]) -> Bill:
92
+ try:
93
+ return cls(
94
+ id=int(data["id"]),
95
+ what=str(data.get("what") or ""),
96
+ amount=float(data["amount"]),
97
+ comment=str(data.get("comment") or ""),
98
+ timestamp=int(data["timestamp"]),
99
+ date=str(data.get("date") or ""),
100
+ payer_id=int(data["payer_id"]),
101
+ owers=tuple(Ower.from_api(o) for o in data.get("owers") or ()),
102
+ repeat=str(data.get("repeat") or "n"),
103
+ repeat_freq=int(data.get("repeatfreq") or 1),
104
+ repeat_until=data.get("repeatuntil"),
105
+ repeat_all_active=int(data.get("repeatallactive") or 0),
106
+ payment_mode=str(data.get("paymentmode") or "n"),
107
+ payment_mode_id=int(data.get("paymentmodeid") or 0),
108
+ category_id=int(data.get("categoryid") or 0),
109
+ deleted=bool(data.get("deleted", 0)),
110
+ last_changed=int(data.get("lastchanged") or 0),
111
+ project_id=data.get("projectid"),
112
+ )
113
+ except (KeyError, TypeError, ValueError) as err:
114
+ raise _invalid("Dépense", err) from err
115
+
116
+
117
+ @dataclass(frozen=True, slots=True)
118
+ class BillsPage:
119
+ """Réponse de la liste des dépenses.
120
+
121
+ ``nb_bills`` est le total des dépenses du projet pour l'état demandé (visibles ou en
122
+ corbeille), pas le nombre de dépenses renvoyées. ``all_bill_ids`` liste les identifiants
123
+ de cet état : une dépense mise en corbeille en disparaît. ``timestamp`` est l'heure du
124
+ serveur, à réutiliser comme curseur ``last_changed`` du cycle suivant.
125
+ """
126
+
127
+ nb_bills: int
128
+ bills: tuple[Bill, ...]
129
+ all_bill_ids: tuple[int, ...]
130
+ timestamp: int
131
+
132
+ @classmethod
133
+ def from_api(cls, data: Mapping[str, Any]) -> BillsPage:
134
+ try:
135
+ return cls(
136
+ nb_bills=int(data["nb_bills"]),
137
+ bills=tuple(Bill.from_api(b) for b in data.get("bills") or ()),
138
+ all_bill_ids=tuple(int(i) for i in data.get("allBillIds") or ()),
139
+ timestamp=int(data["timestamp"]),
140
+ )
141
+ except (KeyError, TypeError, ValueError) as err:
142
+ raise _invalid("Liste de dépenses", err) from err
143
+
144
+
145
+ @dataclass(frozen=True, slots=True)
146
+ class Member:
147
+ id: int
148
+ name: str
149
+ weight: float
150
+ activated: bool
151
+ last_changed: int
152
+ user_id: str | None
153
+ color: tuple[int, int, int] | None
154
+
155
+ @classmethod
156
+ def from_api(cls, data: Mapping[str, Any]) -> Member:
157
+ try:
158
+ color = data.get("color")
159
+ return cls(
160
+ id=int(data["id"]),
161
+ name=str(data.get("name") or ""),
162
+ weight=float(data.get("weight", 1)),
163
+ activated=bool(data.get("activated", True)),
164
+ last_changed=int(data.get("lastchanged") or 0),
165
+ user_id=data.get("userid"),
166
+ color=(int(color["r"]), int(color["g"]), int(color["b"])) if color else None,
167
+ )
168
+ except (KeyError, TypeError, ValueError) as err:
169
+ raise _invalid("Membre", err) from err
170
+
171
+
172
+ @dataclass(frozen=True, slots=True)
173
+ class Category:
174
+ id: int
175
+ name: str
176
+ color: str
177
+ icon: str
178
+ order: int
179
+
180
+ @classmethod
181
+ def from_api(cls, data: Mapping[str, Any]) -> Category:
182
+ try:
183
+ return cls(
184
+ id=int(data["id"]),
185
+ name=str(data.get("name") or ""),
186
+ color=str(data.get("color") or ""),
187
+ icon=str(data.get("icon") or ""),
188
+ order=int(data.get("order") or 0),
189
+ )
190
+ except (KeyError, TypeError, ValueError) as err:
191
+ raise _invalid("Catégorie", err) from err
192
+
193
+
194
+ @dataclass(frozen=True, slots=True)
195
+ class PaymentMode:
196
+ id: int
197
+ name: str
198
+ color: str
199
+ icon: str
200
+ order: int
201
+ old_id: str | None
202
+
203
+ @classmethod
204
+ def from_api(cls, data: Mapping[str, Any]) -> PaymentMode:
205
+ try:
206
+ return cls(
207
+ id=int(data["id"]),
208
+ name=str(data.get("name") or ""),
209
+ color=str(data.get("color") or ""),
210
+ icon=str(data.get("icon") or ""),
211
+ order=int(data.get("order") or 0),
212
+ old_id=data.get("old_id"),
213
+ )
214
+ except (KeyError, TypeError, ValueError) as err:
215
+ raise _invalid("Mode de paiement", err) from err
216
+
217
+
218
+ @dataclass(frozen=True, slots=True)
219
+ class Currency:
220
+ id: int
221
+ name: str
222
+ exchange_rate: float
223
+
224
+ @classmethod
225
+ def from_api(cls, data: Mapping[str, Any]) -> Currency:
226
+ try:
227
+ return cls(
228
+ id=int(data["id"]),
229
+ name=str(data.get("name") or ""),
230
+ exchange_rate=float(data["exchange_rate"]),
231
+ )
232
+ except (KeyError, TypeError, ValueError) as err:
233
+ raise _invalid("Devise", err) from err
234
+
235
+
236
+ @dataclass(frozen=True, slots=True)
237
+ class Share:
238
+ """Partage d'un projet (type ``u`` utilisateur, ``l`` lien, etc.)."""
239
+
240
+ id: int
241
+ type: str
242
+ access_level: int
243
+ user_id: str | None
244
+ name: str | None
245
+
246
+ @classmethod
247
+ def from_api(cls, data: Mapping[str, Any]) -> Share:
248
+ try:
249
+ return cls(
250
+ id=int(data["id"]),
251
+ type=str(data.get("type") or ""),
252
+ access_level=int(data.get("accesslevel") or 0),
253
+ user_id=data.get("userid"),
254
+ name=data.get("name"),
255
+ )
256
+ except (KeyError, TypeError, ValueError) as err:
257
+ raise _invalid("Partage", err) from err
258
+
259
+
260
+ @dataclass(frozen=True, slots=True)
261
+ class Project:
262
+ """Projet Cospend avec sa structure (la liste des projets renvoie déjà tout cela)."""
263
+
264
+ id: str
265
+ name: str
266
+ owner_id: str | None
267
+ currency_name: str | None
268
+ archived_ts: int | None
269
+ access_level: int
270
+ last_changed: int
271
+ nb_bills: int
272
+ nb_trashbin_bills: int
273
+ total_spent: float
274
+ balance: Mapping[int, float]
275
+ members: tuple[Member, ...]
276
+ categories: tuple[Category, ...]
277
+ payment_modes: tuple[PaymentMode, ...]
278
+ currencies: tuple[Currency, ...]
279
+ shares: tuple[Share, ...]
280
+ deletion_disabled: bool = False
281
+
282
+ @property
283
+ def is_archived(self) -> bool:
284
+ return self.archived_ts is not None
285
+
286
+ @property
287
+ def can_write(self) -> bool:
288
+ """Écriture supposée possible (niveau ≥ 2). À valider par les tests de contrat."""
289
+ return self.access_level >= ACCESS_LEVEL_PARTICIPANT
290
+
291
+ def member(self, member_id: int) -> Member | None:
292
+ return next((m for m in self.members if m.id == member_id), None)
293
+
294
+ @classmethod
295
+ def from_api(cls, data: Mapping[str, Any]) -> Project:
296
+ try:
297
+ categories = sorted(
298
+ (Category.from_api(c) for c in _as_dict(data.get("categories")).values()),
299
+ key=lambda c: (c.order, c.id),
300
+ )
301
+ payment_modes = sorted(
302
+ (PaymentMode.from_api(p) for p in _as_dict(data.get("paymentmodes")).values()),
303
+ key=lambda p: (p.order, p.id),
304
+ )
305
+ archived = data.get("archived_ts")
306
+ return cls(
307
+ id=str(data["id"]),
308
+ name=str(data.get("name") or data["id"]),
309
+ owner_id=data.get("userid"),
310
+ currency_name=data.get("currencyname"),
311
+ archived_ts=int(archived) if archived is not None else None,
312
+ access_level=int(data.get("myaccesslevel") or 0),
313
+ last_changed=int(data.get("lastchanged") or 0),
314
+ nb_bills=int(data.get("nb_bills") or 0),
315
+ nb_trashbin_bills=int(data.get("nb_trashbin_bills") or 0),
316
+ total_spent=float(data.get("total_spent") or 0),
317
+ balance={int(k): float(v) for k, v in _as_dict(data.get("balance")).items()},
318
+ members=tuple(Member.from_api(m) for m in data.get("members") or ()),
319
+ categories=tuple(categories),
320
+ payment_modes=tuple(payment_modes),
321
+ currencies=tuple(Currency.from_api(c) for c in data.get("currencies") or ()),
322
+ shares=tuple(Share.from_api(s) for s in data.get("shares") or ()),
323
+ deletion_disabled=bool(data.get("deletiondisabled", False)),
324
+ )
325
+ except (KeyError, TypeError, ValueError, AttributeError) as err:
326
+ raise _invalid("Projet", err) from err
327
+
328
+
329
+ @dataclass(frozen=True, slots=True)
330
+ class MemberStats:
331
+ balance: float
332
+ filtered_balance: float
333
+ paid: float
334
+ spent: float
335
+ member: Member
336
+
337
+
338
+ def _monthly_by_member(data: Mapping[str, Any] | None) -> dict[str, dict[int, float]]:
339
+ """``{"2026-11": {"12": 1250, "0": 1850}}`` → ``{"2026-11": {12: 1250.0, 0: 1850.0}}``.
340
+
341
+ Seules les clés au format AAAA-MM sont conservées : le serveur ajoute une entrée de
342
+ moyenne dont le libellé est traduit (« Moyenne par mois ») et ne doit jamais servir de clé.
343
+ """
344
+ return {
345
+ month: {int(k): float(v) for k, v in _as_dict(values).items()}
346
+ for month, values in _as_dict(data).items()
347
+ if _MONTH.match(str(month))
348
+ }
349
+
350
+
351
+ def _monthly_by_key(data: Mapping[str, Any] | None) -> dict[int, dict[str, float]]:
352
+ """``{"36": {"2026-11": 1250, "Moyenne par mois": 1250}}`` → ``{36: {"2026-11": 1250.0}}``."""
353
+ return {
354
+ int(key): {m: float(v) for m, v in _as_dict(values).items() if _MONTH.match(str(m))}
355
+ for key, values in _as_dict(data).items()
356
+ }
357
+
358
+
359
+ @dataclass(frozen=True, slots=True)
360
+ class ProjectStatistics:
361
+ """Statistiques d'un projet. ``raw`` conserve la réponse complète du serveur."""
362
+
363
+ stats: tuple[MemberStats, ...]
364
+ months: tuple[str, ...]
365
+ member_ids: tuple[int, ...]
366
+ monthly_paid: Mapping[str, Mapping[int, float]]
367
+ monthly_spent: Mapping[str, Mapping[int, float]]
368
+ category_stats: Mapping[int, float]
369
+ category_monthly: Mapping[int, Mapping[str, float]]
370
+ category_member: Mapping[int, Mapping[int, float]]
371
+ payment_mode_stats: Mapping[int, float]
372
+ raw: Mapping[str, Any] = field(repr=False, default_factory=dict)
373
+
374
+ def paid_in(self, month: str, member_id: int = 0) -> float:
375
+ """Montant payé sur un mois ``AAAA-MM`` (``member_id`` 0 = total du projet)."""
376
+ return float(self.monthly_paid.get(month, {}).get(member_id, 0.0))
377
+
378
+ def spent_in(self, month: str, member_id: int = 0) -> float:
379
+ """Montant dépensé (part consommée) sur un mois ``AAAA-MM`` (0 = total)."""
380
+ return float(self.monthly_spent.get(month, {}).get(member_id, 0.0))
381
+
382
+ @classmethod
383
+ def from_api(cls, data: Mapping[str, Any]) -> ProjectStatistics:
384
+ try:
385
+ return cls(
386
+ stats=tuple(
387
+ MemberStats(
388
+ balance=float(s["balance"]),
389
+ filtered_balance=float(s.get("filtered_balance", s["balance"])),
390
+ paid=float(s["paid"]),
391
+ spent=float(s["spent"]),
392
+ member=Member.from_api(s["member"]),
393
+ )
394
+ for s in data.get("stats") or ()
395
+ ),
396
+ months=tuple(str(m) for m in data.get("realMonths") or ()),
397
+ member_ids=tuple(int(i) for i in data.get("memberIds") or ()),
398
+ monthly_paid=_monthly_by_member(data.get("memberMonthlyPaidStats")),
399
+ monthly_spent=_monthly_by_member(data.get("memberMonthlySpentStats")),
400
+ category_stats={
401
+ int(k): float(v) for k, v in _as_dict(data.get("categoryStats")).items()
402
+ },
403
+ category_monthly=_monthly_by_key(data.get("categoryMonthlyStats")),
404
+ category_member={
405
+ int(cat): {int(m): float(v) for m, v in _as_dict(per).items()}
406
+ for cat, per in _as_dict(data.get("categoryMemberStats")).items()
407
+ },
408
+ payment_mode_stats={
409
+ int(k): float(v) for k, v in _as_dict(data.get("paymentModeStats")).items()
410
+ },
411
+ raw=data,
412
+ )
413
+ except (KeyError, TypeError, ValueError, AttributeError) as err:
414
+ raise _invalid("Statistiques", err) from err
415
+
416
+
417
+ @dataclass(frozen=True, slots=True)
418
+ class Transaction:
419
+ """Remboursement proposé : ``from_member`` doit ``amount`` à ``to_member``."""
420
+
421
+ from_member: int
422
+ to_member: int
423
+ amount: float
424
+
425
+
426
+ @dataclass(frozen=True, slots=True)
427
+ class Settlement:
428
+ """Plan de remboursement du serveur. Montants non arrondis (flottants)."""
429
+
430
+ transactions: tuple[Transaction, ...]
431
+ balances: Mapping[int, float]
432
+
433
+ @classmethod
434
+ def from_api(cls, data: Mapping[str, Any]) -> Settlement:
435
+ try:
436
+ return cls(
437
+ transactions=tuple(
438
+ Transaction(int(t["from"]), int(t["to"]), float(t["amount"]))
439
+ for t in data.get("transactions") or ()
440
+ ),
441
+ balances={int(k): float(v) for k, v in _as_dict(data.get("balances")).items()},
442
+ )
443
+ except (KeyError, TypeError, ValueError, AttributeError) as err:
444
+ raise _invalid("Plan de remboursement", err) from err
445
+
446
+
447
+ @dataclass(frozen=True, slots=True)
448
+ class ServerInfo:
449
+ """Informations sur le serveur Cospend."""
450
+
451
+ version: str
452
+ federation_enabled: bool = False
aiocospend/py.typed ADDED
File without changes
aiocospend/sync.py ADDED
@@ -0,0 +1,146 @@
1
+ """Cache des dépenses d'un projet et synchronisation incrémentale.
2
+
3
+ Principe, validé sur Cospend 4.3.0 :
4
+
5
+ * la première lecture (ou une resynchronisation complète) parcourt toutes les dépenses par pages ;
6
+ * ensuite, ``last_changed`` ne renvoie que les dépenses modifiées depuis le curseur ;
7
+ * une dépense mise en corbeille n'est pas renvoyée : on la détecte par son absence de
8
+ ``all_bill_ids``, à comparer au cache ;
9
+ * le curseur est l'heure du serveur renvoyée par la lecture, avec un recouvrement de quelques
10
+ secondes (la limite exacte de ``last_changed`` n'est pas connue). La fusion est idempotente :
11
+ une dépense relue à l'identique ne produit aucun changement.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import time
17
+ from dataclasses import dataclass
18
+
19
+ from .client import CospendClient
20
+ from .models import Bill
21
+
22
+ DEFAULT_OVERLAP = 2
23
+ DEFAULT_PAGE_SIZE = 200
24
+
25
+
26
+ @dataclass(frozen=True, slots=True)
27
+ class BillChanges:
28
+ """Différences constatées par une synchronisation.
29
+
30
+ ``is_initial`` vaut ``True`` pour la toute première lecture : tout y est « ajouté », ce qui
31
+ ne doit pas déclencher d'événements.
32
+ """
33
+
34
+ added: tuple[Bill, ...] = ()
35
+ updated: tuple[Bill, ...] = ()
36
+ deleted: tuple[Bill, ...] = ()
37
+ is_initial: bool = False
38
+ full: bool = False
39
+
40
+ @property
41
+ def any(self) -> bool:
42
+ return bool(self.added or self.updated or self.deleted)
43
+
44
+
45
+ class ProjectBills:
46
+ """Dépenses d'un projet gardées en mémoire, tenues à jour de façon incrémentale."""
47
+
48
+ def __init__(
49
+ self,
50
+ project_id: str,
51
+ *,
52
+ overlap: int = DEFAULT_OVERLAP,
53
+ page_size: int = DEFAULT_PAGE_SIZE,
54
+ ) -> None:
55
+ self.project_id = project_id
56
+ self.bills: dict[int, Bill] = {}
57
+ self.cursor: int | None = None
58
+ self.last_full_sync: float | None = None
59
+ self._overlap = overlap
60
+ self._page_size = page_size
61
+
62
+ @property
63
+ def synced(self) -> bool:
64
+ return self.cursor is not None
65
+
66
+ def full_sync_due(self, max_age: float, *, now: float | None = None) -> bool:
67
+ """Vrai si aucune lecture complète n'a eu lieu ou si elle date de plus de ``max_age`` s."""
68
+ if self.last_full_sync is None:
69
+ return True
70
+ current = time.monotonic() if now is None else now
71
+ return current - self.last_full_sync >= max_age
72
+
73
+ async def sync(
74
+ self, client: CospendClient, *, full_sync_max_age: float | None = None
75
+ ) -> BillChanges:
76
+ """Lecture complète si nécessaire, incrémentale sinon."""
77
+ if not self.synced or (
78
+ full_sync_max_age is not None and self.full_sync_due(full_sync_max_age)
79
+ ):
80
+ return await self.full_sync(client)
81
+ return await self.incremental_sync(client)
82
+
83
+ async def full_sync(self, client: CospendClient) -> BillChanges:
84
+ """Relit toutes les dépenses, page par page."""
85
+ first = await client.get_bills(
86
+ self.project_id, offset=0, limit=self._page_size, reverse=True
87
+ )
88
+ fetched = {bill.id: bill for bill in first.bills}
89
+ offset = len(first.bills)
90
+ while first.bills and offset < first.nb_bills:
91
+ page = await client.get_bills(
92
+ self.project_id, offset=offset, limit=self._page_size, reverse=True
93
+ )
94
+ if not page.bills:
95
+ break
96
+ fetched.update({bill.id: bill for bill in page.bills})
97
+ offset += len(page.bills)
98
+ initial = not self.synced
99
+ changes = self._apply(fetched, set(fetched), initial=initial, full=True)
100
+ self.cursor = first.timestamp
101
+ self.last_full_sync = time.monotonic()
102
+ return changes
103
+
104
+ async def incremental_sync(self, client: CospendClient) -> BillChanges:
105
+ """Ne lit que les dépenses modifiées depuis le curseur."""
106
+ if self.cursor is None:
107
+ raise RuntimeError("synchronisation complète requise avant la lecture incrémentale")
108
+ page = await client.get_bills(
109
+ self.project_id, last_changed=max(self.cursor - self._overlap, 0)
110
+ )
111
+ changes = self._apply(
112
+ {bill.id: bill for bill in page.bills},
113
+ set(page.all_bill_ids),
114
+ initial=False,
115
+ full=False,
116
+ )
117
+ self.cursor = page.timestamp
118
+ return changes
119
+
120
+ def _apply(
121
+ self,
122
+ changed: dict[int, Bill],
123
+ alive_ids: set[int],
124
+ *,
125
+ initial: bool,
126
+ full: bool,
127
+ ) -> BillChanges:
128
+ added: list[Bill] = []
129
+ updated: list[Bill] = []
130
+ for bill in changed.values():
131
+ known = self.bills.get(bill.id)
132
+ if known is None:
133
+ added.append(bill)
134
+ elif known != bill:
135
+ updated.append(bill)
136
+ self.bills[bill.id] = bill
137
+ deleted = [
138
+ self.bills.pop(bill_id) for bill_id in [i for i in self.bills if i not in alive_ids]
139
+ ]
140
+ return BillChanges(
141
+ added=tuple(sorted(added, key=lambda b: b.id)),
142
+ updated=tuple(sorted(updated, key=lambda b: b.id)),
143
+ deleted=tuple(sorted(deleted, key=lambda b: b.id)),
144
+ is_initial=initial,
145
+ full=full,
146
+ )
aiocospend/utils.py ADDED
@@ -0,0 +1,66 @@
1
+ """Utilitaires : adresse du serveur, versions, formatage des montants."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from decimal import Decimal, InvalidOperation
7
+ from urllib.parse import urlsplit
8
+
9
+ # Segments qu'un utilisateur colle souvent à la fin de l'adresse de son Nextcloud.
10
+ _CUT_MARKERS = ("/index.php", "/apps/", "/ocs/", "/status.php", "/login", "/remote.php")
11
+
12
+
13
+ def normalize_url(url: str) -> str:
14
+ """Normalise l'adresse d'un Nextcloud.
15
+
16
+ Ajoute ``https://`` si aucun schéma n'est donné, retire la requête, le fragment, le slash
17
+ final et tout ce qui suit ``/index.php``, ``/apps/``, ``/ocs/``, etc. Conserve un
18
+ éventuel sous-dossier (``https://exemple.org/nextcloud``).
19
+ """
20
+ raw = url.strip()
21
+ if not raw:
22
+ raise ValueError("adresse vide")
23
+ if "://" not in raw:
24
+ raw = f"https://{raw}"
25
+ parts = urlsplit(raw)
26
+ if parts.scheme not in ("http", "https") or not parts.hostname:
27
+ raise ValueError(f"adresse invalide : {url!r}")
28
+ path = parts.path
29
+ for marker in _CUT_MARKERS:
30
+ index = path.find(marker if marker.endswith("/") else marker)
31
+ if index != -1:
32
+ path = path[:index]
33
+ path = path.rstrip("/")
34
+ return f"{parts.scheme}://{parts.netloc}{path}"
35
+
36
+
37
+ def parse_version(version: str) -> tuple[int, ...]:
38
+ """Convertit ``"4.3.0"`` (ou ``"4.3.0-beta.1"``) en ``(4, 3, 0)``."""
39
+ numbers = re.match(r"^\s*(\d+(?:\.\d+)*)", version)
40
+ if not numbers:
41
+ raise ValueError(f"version illisible : {version!r}")
42
+ return tuple(int(part) for part in numbers.group(1).split("."))
43
+
44
+
45
+ def compare_versions(left: str, right: str) -> int:
46
+ """Renvoie -1, 0 ou 1 selon que ``left`` est inférieure, égale ou supérieure à ``right``."""
47
+ a, b = parse_version(left), parse_version(right)
48
+ size = max(len(a), len(b))
49
+ a += (0,) * (size - len(a))
50
+ b += (0,) * (size - len(b))
51
+ return (a > b) - (a < b)
52
+
53
+
54
+ def format_amount(value: int | float | Decimal | str) -> str:
55
+ """Formate un montant pour l'API (point décimal, sans exposant ni zéros inutiles).
56
+
57
+ Les flottants passent par leur représentation la plus courte (``0.1`` donne ``"0.1"``).
58
+ """
59
+ try:
60
+ number = value if isinstance(value, Decimal) else Decimal(str(value).strip())
61
+ except InvalidOperation as err:
62
+ raise ValueError(f"montant invalide : {value!r}") from err
63
+ if not number.is_finite():
64
+ raise ValueError(f"montant invalide : {value!r}")
65
+ text = format(number.normalize(), "f")
66
+ return "0" if text in ("-0", "") else text
@@ -0,0 +1,83 @@
1
+ Metadata-Version: 2.5
2
+ Name: aiocospend
3
+ Version: 0.2.0
4
+ Summary: Client asynchrone pour l'API OCS de Nextcloud Cospend
5
+ Project-URL: Homepage, https://github.com/SpaRtzZii/cospend-ha
6
+ Project-URL: Issues, https://github.com/SpaRtzZii/cospend-ha/issues
7
+ License-Expression: GPL-3.0-only
8
+ Requires-Python: >=3.13
9
+ Requires-Dist: aiohttp>=3.9
10
+ Provides-Extra: test
11
+ Requires-Dist: pytest; extra == 'test'
12
+ Requires-Dist: pytest-asyncio; extra == 'test'
13
+ Description-Content-Type: text/markdown
14
+
15
+ # aiocospend
16
+
17
+ Client asynchrone (aiohttp) pour l'API OCS de [Nextcloud Cospend](https://github.com/julien-nc/cospend-nc).
18
+ Fait partie du dépôt [cospend-ha](https://github.com/SpaRtzZii/cospend-ha). Version 0.2.0.
19
+
20
+ ```python
21
+ import time
22
+
23
+ import aiohttp
24
+ from aiocospend import CospendClient
25
+
26
+ async with aiohttp.ClientSession() as session:
27
+ client = CospendClient(
28
+ session, "https://cloud.exemple.org", "utilisateur", "mot-de-passe-d-application"
29
+ )
30
+ await client.check_connection() # adresse, identifiants, version de Cospend (>= 1.6.1)
31
+
32
+ project = (await client.get_projects())[0] # membres, catégories, soldes inclus
33
+ page = await client.get_bills(project.id) # page.timestamp = curseur du prochain last_changed
34
+ delta = await client.get_bills(project.id, last_changed=page.timestamp)
35
+
36
+ bill_id = await client.create_bill(
37
+ project.id,
38
+ what="Courses",
39
+ amount=42.5,
40
+ payer_id=project.members[0].id,
41
+ payed_for=[m.id for m in project.members],
42
+ timestamp=int(time.time()),
43
+ date=time.strftime("%Y-%m-%d"),
44
+ )
45
+ await client.update_bill(project.id, bill_id, amount=45) # modification partielle
46
+ await client.delete_bill(project.id, bill_id) # corbeille
47
+ ```
48
+
49
+ ## Synchronisation incrémentale
50
+
51
+ ```python
52
+ from aiocospend import ProjectBills
53
+
54
+ store = ProjectBills(project.id)
55
+ changes = await store.sync(
56
+ client, full_sync_max_age=24 * 3600
57
+ ) # complète au besoin, sinon incrémentale
58
+ for bill in changes.added:
59
+ ... # changes.updated, changes.deleted ; changes.is_initial = première lecture
60
+ ```
61
+
62
+ ## À savoir (relevé sur Cospend 4.3.0)
63
+
64
+ - Les écritures sont envoyées en formulaire, avec tous les champs à la création (comme Cowspent).
65
+ - **Supprimer une dépense déjà en corbeille la supprime définitivement.** Le client ne rejoue jamais
66
+ une suppression : relisez l'état de la dépense avant de réessayer.
67
+ - La lecture incrémentale (`last_changed`) ne renvoie pas les dépenses mises en corbeille ; on les
68
+ repère par leur absence de `all_bill_ids`.
69
+ - Les montants renvoyés par le serveur (statistiques, remboursements) ne sont pas arrondis.
70
+
71
+ ## Tests
72
+
73
+ ```bash
74
+ pip install -e ".[test]"
75
+ pytest tests # faux serveur Cospend local, sans réseau externe
76
+ ```
77
+
78
+ ## Publication sur PyPI (mainteneur)
79
+
80
+ Le paquet est publié par le workflow manuel `publish-aiocospend.yml`, sans mot de passe, par
81
+ « Trusted Publisher » : sur pypi.org, ajouter un *pending publisher* (propriétaire `SpaRtzZii`,
82
+ dépôt `cospend-ha`, workflow `publish-aiocospend.yml`, environnement `pypi`), créer l'environnement
83
+ `pypi` dans les réglages du dépôt GitHub, puis lancer le workflow depuis l'onglet Actions.
@@ -0,0 +1,11 @@
1
+ aiocospend/__init__.py,sha256=TPDLSF1MczunKfhiL8RTdmSUcIU4AUDqBsopEwvpz2s,1571
2
+ aiocospend/client.py,sha256=99Un0f7KkukX4Cz2sy-5-2GQvlnkB9BkqGJjw5KOTmE,15913
3
+ aiocospend/const.py,sha256=K9d1Wxxtm7bbFYzHm3XjoIWz4DRZBIL3AexuqjPZjBA,889
4
+ aiocospend/exceptions.py,sha256=883ARpKixxR6SwlXVochJua0uj8X_hYxGPYQuI6acUo,1520
5
+ aiocospend/models.py,sha256=aOWHKL5U9QYWUQi91nYhD_8en1PawqlneLcQuDOIRig,15984
6
+ aiocospend/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ aiocospend/sync.py,sha256=bBLUVHbVGVmxNuepGzVUZe2wBddE6tiQlFePXOMzkh8,5252
8
+ aiocospend/utils.py,sha256=PJihw2XqdSblHjV0rpqThhq2bMSRrVpEnFcjpueCxkE,2554
9
+ aiocospend-0.2.0.dist-info/METADATA,sha256=eQytDxmNfi8vEps5woYTn22uZi064nKwMFar1dzFoqw,3190
10
+ aiocospend-0.2.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
11
+ aiocospend-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any