campai-api 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.
@@ -0,0 +1,294 @@
1
+ # SPDX-FileCopyrightText: 2026 2026 Stephan Lukasczyk <stephan@dante.de>
2
+ #
3
+ # SPDX-License-Identifier: EUPL-1.2
4
+
5
+ """Campai API exception hierarchy."""
6
+
7
+ from __future__ import annotations
8
+
9
+ import datetime as dt
10
+ import email.utils
11
+ from typing import TYPE_CHECKING, Any, override
12
+
13
+ if TYPE_CHECKING:
14
+ from collections.abc import Mapping
15
+
16
+
17
+ class CampaiError(Exception):
18
+ """Base exception for all Campai SDK errors."""
19
+
20
+ def __init__(self, message: str) -> None:
21
+ """Initialize CampaiError with an error message.
22
+
23
+ Args:
24
+ message: Explanation of the error.
25
+ """
26
+ super().__init__(message)
27
+ self.message = message
28
+
29
+ @override
30
+ def __str__(self) -> str:
31
+ return self.message
32
+
33
+ @override
34
+ def __repr__(self) -> str:
35
+ return f"{self.__class__.__name__}({self.message!r})"
36
+
37
+
38
+ class CampaiNetworkError(CampaiError):
39
+ """Raised when a network or transport-level communication failure occurs."""
40
+
41
+ def __init__(self, message: str, *, original_error: Exception | None = None) -> None:
42
+ """Initialize CampaiNetworkError.
43
+
44
+ Args:
45
+ message: Explanation of the error.
46
+ original_error: The underlying network exception, if available.
47
+ """
48
+ super().__init__(message)
49
+ self.original_error = original_error
50
+
51
+
52
+ class CampaiSerializationError(CampaiError):
53
+ """Raised when data serialization or deserialization fails."""
54
+
55
+ def __init__(self, message: str, *, original_error: Exception | None = None) -> None:
56
+ """Initialize CampaiSerializationError.
57
+
58
+ Args:
59
+ message: Explanation of the error.
60
+ original_error: The underlying serialization exception, if available.
61
+ """
62
+ super().__init__(message)
63
+ self.original_error = original_error
64
+
65
+
66
+ class CampaiJSONDecodeError(CampaiSerializationError):
67
+ """Raised when the API returns an invalid or malformed JSON payload."""
68
+
69
+ def __init__(
70
+ self,
71
+ message: str,
72
+ *,
73
+ raw_body: str | bytes | None = None,
74
+ original_error: Exception | None = None,
75
+ ) -> None:
76
+ """Initialize CampaiJSONDecodeError.
77
+
78
+ Args:
79
+ message: Explanation of the error.
80
+ raw_body: The unparsed response body.
81
+ original_error: The underlying decode exception, if available.
82
+ """
83
+ super().__init__(message, original_error=original_error)
84
+ self.raw_body = raw_body
85
+
86
+
87
+ class CampaiAPIError(CampaiError):
88
+ """Base exception for HTTP errors returned by the Campai REST API."""
89
+
90
+ def __init__(
91
+ self,
92
+ message: str,
93
+ *,
94
+ status_code: int,
95
+ body: Any = None,
96
+ headers: Mapping[str, str] | None = None,
97
+ request_id: str | None = None,
98
+ ) -> None:
99
+ """Initialize CampaiAPIError.
100
+
101
+ Args:
102
+ message: Explanation of the error.
103
+ status_code: HTTP status code returned by the server.
104
+ body: Parsed response body payload.
105
+ headers: Response headers dictionary.
106
+ request_id: Unique request / correlation identifier.
107
+ """
108
+ self.status_code = status_code
109
+ self.body = body
110
+ self.headers = dict(headers) if headers is not None else {}
111
+ self.request_id = request_id or self._extract_request_id(self.headers, body)
112
+ super().__init__(message)
113
+
114
+ @staticmethod
115
+ def _extract_request_id(headers: Mapping[str, str], body: Any) -> str | None:
116
+ # Check standard headers (case-insensitive search)
117
+ lower_headers = {k.lower(): v for k, v in headers.items()}
118
+ for header_key in ("x-request-id", "request-id", "x-correlation-id"):
119
+ if header_key in lower_headers:
120
+ return lower_headers[header_key]
121
+
122
+ # Check body if dict
123
+ if isinstance(body, dict):
124
+ for key in (
125
+ "requestId",
126
+ "request_id",
127
+ "x-request-id",
128
+ "correlationId",
129
+ "correlation_id",
130
+ ):
131
+ val = body.get(key)
132
+ if isinstance(val, str) and val:
133
+ return val
134
+ return None
135
+
136
+ @override
137
+ def __repr__(self) -> str:
138
+ return (
139
+ f"{self.__class__.__name__}("
140
+ f"status_code={self.status_code}, "
141
+ f"message={self.message!r}, "
142
+ f"request_id={self.request_id!r})"
143
+ )
144
+
145
+
146
+ class BadRequestError(CampaiAPIError):
147
+ """HTTP 400 Bad Request."""
148
+
149
+
150
+ class AuthenticationError(CampaiAPIError):
151
+ """HTTP 401 Unauthorized - invalid or missing API key."""
152
+
153
+
154
+ class ForbiddenError(CampaiAPIError):
155
+ """HTTP 403 Forbidden - insufficient permissions."""
156
+
157
+
158
+ class NotFoundError(CampaiAPIError):
159
+ """HTTP 404 Not Found - requested resource does not exist."""
160
+
161
+
162
+ class ConflictError(CampaiAPIError):
163
+ """HTTP 409 Conflict."""
164
+
165
+
166
+ class UnprocessableEntityError(CampaiAPIError):
167
+ """HTTP 422 Unprocessable Entity - validation error."""
168
+
169
+
170
+ class RateLimitError(CampaiAPIError):
171
+ """HTTP 429 Too Many Requests."""
172
+
173
+ def __init__(
174
+ self,
175
+ message: str,
176
+ *,
177
+ status_code: int = 429,
178
+ body: Any = None,
179
+ headers: Mapping[str, str] | None = None,
180
+ request_id: str | None = None,
181
+ retry_after: float | None = None,
182
+ ) -> None:
183
+ """Initialize RateLimitError.
184
+
185
+ Args:
186
+ message: Explanation of the error.
187
+ status_code: HTTP status code (defaults to 429).
188
+ body: Parsed response body payload.
189
+ headers: Response headers dictionary.
190
+ request_id: Unique request / correlation identifier.
191
+ retry_after: Retry-after duration in seconds.
192
+ """
193
+ self.retry_after = (
194
+ retry_after if retry_after is not None else self._parse_retry_after(headers, body)
195
+ )
196
+ super().__init__(
197
+ message,
198
+ status_code=status_code,
199
+ body=body,
200
+ headers=headers,
201
+ request_id=request_id,
202
+ )
203
+
204
+ @staticmethod
205
+ def _parse_retry_after(headers: Mapping[str, str] | None, body: Any) -> float | None:
206
+ if headers is not None:
207
+ lower_headers = {k.lower(): v for k, v in headers.items()}
208
+ retry_val = lower_headers.get("retry-after")
209
+ if bool(retry_val):
210
+ # Can be seconds as integer/float
211
+ try:
212
+ return max(0.0, float(retry_val))
213
+ except ValueError:
214
+ pass
215
+
216
+ # Can be HTTP-date
217
+ try:
218
+ parsed_date = email.utils.parsedate_to_datetime(retry_val)
219
+ if parsed_date.tzinfo is None:
220
+ parsed_date = parsed_date.replace(tzinfo=dt.UTC)
221
+ now = dt.datetime.now(dt.UTC)
222
+ delta = (parsed_date - now).total_seconds()
223
+ return max(0.0, delta)
224
+ except (TypeError, ValueError, OverflowError, IndexError):
225
+ pass
226
+
227
+ if isinstance(body, dict):
228
+ retry_val = body.get("retry_after") or body.get("retryAfter")
229
+ if isinstance(retry_val, (int, float)):
230
+ return max(0.0, float(retry_val))
231
+ if isinstance(retry_val, str) and retry_val:
232
+ try:
233
+ return max(0.0, float(retry_val))
234
+ except ValueError:
235
+ pass
236
+
237
+ return None
238
+
239
+
240
+ class ServerError(CampaiAPIError):
241
+ """Base class for HTTP 5xx Server Errors."""
242
+
243
+
244
+ class InternalServerError(ServerError):
245
+ """HTTP 500 Internal Server Error."""
246
+
247
+
248
+ class BadGatewayError(ServerError):
249
+ """HTTP 502 Bad Gateway."""
250
+
251
+
252
+ class ServiceUnavailableError(ServerError):
253
+ """HTTP 503 Service Unavailable."""
254
+
255
+
256
+ class GatewayTimeoutError(ServerError):
257
+ """HTTP 504 Gateway Timeout."""
258
+
259
+
260
+ _STATUS_CODE_TO_EXCEPTION: dict[int, type[CampaiAPIError]] = {
261
+ 400: BadRequestError,
262
+ 401: AuthenticationError,
263
+ 403: ForbiddenError,
264
+ 404: NotFoundError,
265
+ 409: ConflictError,
266
+ 422: UnprocessableEntityError,
267
+ 429: RateLimitError,
268
+ 500: InternalServerError,
269
+ 502: BadGatewayError,
270
+ 503: ServiceUnavailableError,
271
+ 504: GatewayTimeoutError,
272
+ }
273
+
274
+
275
+ def create_api_error(
276
+ *,
277
+ status_code: int,
278
+ message: str,
279
+ body: Any = None,
280
+ headers: Mapping[str, str] | None = None,
281
+ request_id: str | None = None,
282
+ ) -> CampaiAPIError:
283
+ """Create an appropriate CampaiAPIError subclass instance for a given HTTP status code."""
284
+ exception_cls = _STATUS_CODE_TO_EXCEPTION.get(status_code)
285
+ if exception_cls is None:
286
+ exception_cls = ServerError if 500 <= status_code <= 599 else CampaiAPIError
287
+
288
+ return exception_cls(
289
+ message=message,
290
+ status_code=status_code,
291
+ body=body,
292
+ headers=headers,
293
+ request_id=request_id,
294
+ )
@@ -0,0 +1,95 @@
1
+ # SPDX-FileCopyrightText: 2026 2026 Stephan Lukasczyk <stephan@dante.de>
2
+ #
3
+ # SPDX-License-Identifier: EUPL-1.2
4
+
5
+ """Campai API slotted dataclass models."""
6
+
7
+ from __future__ import annotations
8
+
9
+ from campai_api.models.auth import (
10
+ ApiKeyInfo,
11
+ CostCenter,
12
+ Mandate,
13
+ MandatesListResponse,
14
+ Organization,
15
+ OrganizationAddress,
16
+ PermissionActions,
17
+ )
18
+ from campai_api.models.finance import (
19
+ FinanceDatevSettings,
20
+ FinanceSettings,
21
+ FinanceSettingsUpdateRequest,
22
+ InvoiceCreateRequest,
23
+ InvoiceCreateResult,
24
+ InvoicePositionRequest,
25
+ InvoiceUpdateRequest,
26
+ Receipt,
27
+ ReceiptPosition,
28
+ ReceiptsListResponse,
29
+ )
30
+ from campai_api.models.members import (
31
+ Address,
32
+ Communication,
33
+ CommunicationCreateInput,
34
+ CommunicationUpdateInput,
35
+ Contact,
36
+ ContactCreateRequest,
37
+ ContactCreateResult,
38
+ ContactDepartment,
39
+ ContactDepartmentAssignment,
40
+ ContactsListResponse,
41
+ ContactUpdateRequest,
42
+ Institution,
43
+ MailingUnsubscriptionInput,
44
+ MemberCreateInput,
45
+ MemberData,
46
+ MemberUpdateInput,
47
+ Person,
48
+ PersonCreateInput,
49
+ PersonUpdateInput,
50
+ )
51
+ from campai_api.models.webhooks import (
52
+ WebhookTriggerEvent,
53
+ WebhookTriggerRequest,
54
+ )
55
+
56
+ __all__ = [
57
+ "Address",
58
+ "ApiKeyInfo",
59
+ "Communication",
60
+ "CommunicationCreateInput",
61
+ "CommunicationUpdateInput",
62
+ "Contact",
63
+ "ContactCreateRequest",
64
+ "ContactCreateResult",
65
+ "ContactDepartment",
66
+ "ContactDepartmentAssignment",
67
+ "ContactUpdateRequest",
68
+ "ContactsListResponse",
69
+ "CostCenter",
70
+ "FinanceDatevSettings",
71
+ "FinanceSettings",
72
+ "FinanceSettingsUpdateRequest",
73
+ "Institution",
74
+ "InvoiceCreateRequest",
75
+ "InvoiceCreateResult",
76
+ "InvoicePositionRequest",
77
+ "InvoiceUpdateRequest",
78
+ "MailingUnsubscriptionInput",
79
+ "Mandate",
80
+ "MandatesListResponse",
81
+ "MemberCreateInput",
82
+ "MemberData",
83
+ "MemberUpdateInput",
84
+ "Organization",
85
+ "OrganizationAddress",
86
+ "PermissionActions",
87
+ "Person",
88
+ "PersonCreateInput",
89
+ "PersonUpdateInput",
90
+ "Receipt",
91
+ "ReceiptPosition",
92
+ "ReceiptsListResponse",
93
+ "WebhookTriggerEvent",
94
+ "WebhookTriggerRequest",
95
+ ]
@@ -0,0 +1,91 @@
1
+ # SPDX-FileCopyrightText: 2026 2026 Stephan Lukasczyk <stephan@dante.de>
2
+ #
3
+ # SPDX-License-Identifier: EUPL-1.2
4
+
5
+ """Data models for authentication, organizations, and mandates."""
6
+
7
+ from __future__ import annotations
8
+
9
+ from dataclasses import dataclass, field
10
+ from typing import Any
11
+
12
+
13
+ @dataclass(slots=True, kw_only=True)
14
+ class PermissionActions:
15
+ """Individual CRUD capability permissions for an API key resource."""
16
+
17
+ read: bool = False
18
+ insert: bool = False
19
+ edit: bool = False
20
+ remove: bool = False
21
+
22
+
23
+ @dataclass(slots=True, kw_only=True)
24
+ class ApiKeyInfo:
25
+ """API key information and capability permissions mapping."""
26
+
27
+ organization: str
28
+ permissions: dict[str, PermissionActions] = field(default_factory=dict)
29
+
30
+
31
+ @dataclass(slots=True, kw_only=True)
32
+ class OrganizationAddress:
33
+ """Address details for an organization."""
34
+
35
+ country: str | None = None
36
+ state: str | None = None
37
+ zip: str | None = None
38
+ city: str | None = None
39
+ address_line: str | None = None
40
+ details1: str | None = None
41
+ details2: str | None = None
42
+
43
+
44
+ @dataclass(slots=True, kw_only=True)
45
+ class Organization:
46
+ """Campai organization details."""
47
+
48
+ id: str = field(metadata={"alias": "_id"})
49
+ name: str
50
+ short_id: str | None = None
51
+ website: str | None = None
52
+ founding_year: int | None = None
53
+ address: OrganizationAddress | dict[str, Any] | None = None
54
+ member_count: int | None = None
55
+ user_count: int | None = None
56
+ language: str | None = None
57
+ slug: str | None = None
58
+ online_letter_sending: bool | None = None
59
+ has_eventim: bool | None = None
60
+ has_portal: bool | None = None
61
+ billing: dict[str, Any] | None = None
62
+ created_at: str | None = None
63
+
64
+
65
+ @dataclass(slots=True, kw_only=True)
66
+ class CostCenter:
67
+ """Cost center configuration."""
68
+
69
+ number: float | int
70
+ label: str
71
+ bookable: bool = True
72
+
73
+
74
+ @dataclass(slots=True, kw_only=True)
75
+ class Mandate:
76
+ """Campai mandate configuration."""
77
+
78
+ id: str = field(metadata={"alias": "_id"})
79
+ name: str
80
+ description: str | None = None
81
+ datev_mandate_number: str | None = None
82
+ is_default: bool = False
83
+ cost_centers: list[CostCenter] = field(default_factory=list)
84
+
85
+
86
+ @dataclass(slots=True, kw_only=True)
87
+ class MandatesListResponse:
88
+ """Response containing a list of mandates and total count."""
89
+
90
+ mandates: list[Mandate] = field(default_factory=list)
91
+ count: int = 0