From a83c2e2c72aecec6c254bcd74af635a28b504185 Mon Sep 17 00:00:00 2001 From: Micael Marques Date: Thu, 24 Sep 2026 16:01:25 -0300 Subject: [PATCH 01/13] feat(http): type 403/422 errors and retry POST only with idempotency key --- arara_api_sdk/__init__.py | 12 +++- arara_api_sdk/exceptions.py | 59 ++++++++++++----- arara_api_sdk/http/client.py | 110 +++++++++++++++++++++---------- tests/unit/test_http_client.py | 115 ++++++++++++++++++++++++++++++++- 4 files changed, 241 insertions(+), 55 deletions(-) diff --git a/arara_api_sdk/__init__.py b/arara_api_sdk/__init__.py index 5e7db47..c335952 100644 --- a/arara_api_sdk/__init__.py +++ b/arara_api_sdk/__init__.py @@ -1,20 +1,26 @@ from arara_api_sdk.client import AraraClient from arara_api_sdk.exceptions import ( - AraraError, AraraAuthError, - AraraValidationError, + AraraConnectionError, + AraraError, + AraraForbiddenError, + AraraPlanFeatureLockedError, AraraRateLimitError, AraraResourceNotFoundError, AraraServerError, - AraraConnectionError, AraraTimeoutError, + AraraUnprocessableError, + AraraValidationError, ) __all__ = [ "AraraClient", "AraraError", "AraraAuthError", + "AraraForbiddenError", + "AraraPlanFeatureLockedError", "AraraValidationError", + "AraraUnprocessableError", "AraraRateLimitError", "AraraResourceNotFoundError", "AraraServerError", diff --git a/arara_api_sdk/exceptions.py b/arara_api_sdk/exceptions.py index 603fe9f..d0baded 100644 --- a/arara_api_sdk/exceptions.py +++ b/arara_api_sdk/exceptions.py @@ -2,7 +2,12 @@ class AraraError(Exception): - """Base exception for Arara SDK.""" + """Base exception for Arara SDK. + + Carries the API error envelope ``{"error": {"code", "message", "details"}}`` + unwrapped into ``code``, ``message`` and ``details``, plus the HTTP status + and the ``Retry-After`` hint (seconds) when the server sent one. + """ def __init__( self, @@ -11,6 +16,7 @@ def __init__( response_body: Optional[Dict[str, Any]] = None, code: Optional[str] = None, details: Optional[Dict[str, Any]] = None, + retry_after: Optional[int] = None, ): """Store the message and, when the API sent them, the code and details.""" super().__init__(message) @@ -19,49 +25,70 @@ def __init__( self.response_body = response_body self.code = code self.details = details or {} + self.retry_after = retry_after + class AraraAuthError(AraraError): - """Raised when authentication fails.""" + """Raised when the API key is missing, invalid, expired or not allowed. - pass + The backend answers key failures with 401 or with 403 without an error + code (the filter rejects the request before the envelope is built). + """ -class AraraValidationError(AraraError): - """Raised when request validation fails (400).""" - pass +class AraraForbiddenError(AraraError): + """Raised on a business 403 that carries an error code.""" -class AraraRateLimitError(AraraError): - """Raised when rate limit is exceeded (429).""" + +class AraraPlanFeatureLockedError(AraraForbiddenError): + """Raised on 403 ``PLAN_FEATURE_LOCKED``: the plan does not include the feature.""" def __init__( self, message: str, status_code: Optional[int] = None, response_body: Optional[Dict[str, Any]] = None, - retry_after: Optional[int] = None, code: Optional[str] = None, details: Optional[Dict[str, Any]] = None, + retry_after: Optional[int] = None, ): - """Store the error plus the Retry-After hint, in seconds.""" - super().__init__(message, status_code, response_body, code, details) - self.retry_after = retry_after + """Expose ``feature``, ``current_plan`` and ``upgrade_to`` from details.""" + super().__init__( + message, status_code, response_body, code, details, retry_after + ) + self.feature = _str_or_none(self.details.get("feature")) + self.current_plan = _str_or_none(self.details.get("currentPlan")) + self.upgrade_to = _str_or_none(self.details.get("upgradeTo")) + + +class AraraValidationError(AraraError): + """Raised when request validation fails (400).""" + + +class AraraUnprocessableError(AraraError): + """Raised on 422, e.g. send pre-flight (``INVALID_RECIPIENT``).""" + + +class AraraRateLimitError(AraraError): + """Raised when rate limit is exceeded (429).""" + class AraraResourceNotFoundError(AraraError): """Raised when a resource is not found (404).""" - pass class AraraServerError(AraraError): """Raised when the server returns a 5xx error.""" - pass class AraraConnectionError(AraraError): """Raised when a connection error occurs.""" - pass class AraraTimeoutError(AraraError): """Raised when a request times out.""" - pass + +def _str_or_none(value: Any) -> Optional[str]: + """Return the value when it is a string, otherwise None.""" + return value if isinstance(value, str) else None diff --git a/arara_api_sdk/http/client.py b/arara_api_sdk/http/client.py index 610ca52..e8e6526 100644 --- a/arara_api_sdk/http/client.py +++ b/arara_api_sdk/http/client.py @@ -1,5 +1,5 @@ import logging -from typing import Any, Dict, Optional, Tuple, Type, TypeVar, Union +from typing import Any, Callable, Dict, Mapping, Optional, Tuple, Type, TypeVar, Union import httpx from pydantic import BaseModel @@ -17,10 +17,13 @@ AraraAuthError, AraraConnectionError, AraraError, + AraraForbiddenError, + AraraPlanFeatureLockedError, AraraRateLimitError, AraraResourceNotFoundError, AraraServerError, AraraTimeoutError, + AraraUnprocessableError, AraraValidationError, ) @@ -36,6 +39,17 @@ ) MAX_RETRY_AFTER_SECONDS = 60 +IDEMPOTENCY_HEADER = "Idempotency-Key" +PLAN_FEATURE_LOCKED = "PLAN_FEATURE_LOCKED" +RETRY_SAFE_METHODS = frozenset({"GET", "HEAD", "OPTIONS", "PUT", "DELETE"}) + +_STATUS_ERRORS: Dict[int, Type[AraraError]] = { + 400: AraraValidationError, + 401: AraraAuthError, + 404: AraraResourceNotFoundError, + 422: AraraUnprocessableError, + 429: AraraRateLimitError, +} UNKNOWN_ERROR_MESSAGE = "Unknown error" _EXPONENTIAL_BACKOFF = wait_exponential(multiplier=1, min=2, max=10) @@ -65,6 +79,40 @@ def _should_retry(retry_state: RetryCallState) -> bool: return isinstance(exception, RETRYABLE_EXCEPTIONS) +def _never_retry(retry_state: RetryCallState) -> bool: + """Retry policy for non-idempotent calls: a second attempt could duplicate.""" + return False + + +def _retry_policy( + method: str, headers: Optional[Mapping[str, str]] +) -> Callable[[RetryCallState], bool]: + """Pick the retry policy for a call. + + GET and other idempotent methods retry freely. A POST/PATCH only retries + when it carries an ``Idempotency-Key``: the same key travels on every + attempt, so the API collapses duplicates instead of sending twice. + """ + if method.upper() in RETRY_SAFE_METHODS: + return _should_retry + if headers and headers.get(IDEMPOTENCY_HEADER): + return _should_retry + return _never_retry + + +def _error_class(status_code: int, code: Optional[str]) -> Type[AraraError]: + """Map status and envelope code to the exception type.""" + if status_code == 403: + if code is None: + return AraraAuthError + if code == PLAN_FEATURE_LOCKED: + return AraraPlanFeatureLockedError + return AraraForbiddenError + if 500 <= status_code < 600: + return AraraServerError + return _STATUS_ERRORS.get(status_code, AraraError) + + def _wait_strategy(retry_state: RetryCallState) -> float: """Honor Retry-After on 429, fall back to exponential backoff.""" exception = _exception_from(retry_state) @@ -155,30 +203,17 @@ def _handle_response(self, response: httpx.Response) -> httpx.Response: error_data = {"error": response.text} code, message, details = self._parse_error_envelope(error_data) - - if status_code == 401: - raise AraraAuthError(message, status_code, error_data, code, details) - elif status_code == 400: - raise AraraValidationError(message, status_code, error_data, code, details) - elif status_code == 404: - raise AraraResourceNotFoundError( - message, status_code, error_data, code, details - ) - elif status_code == 429: - raise AraraRateLimitError( - message, - status_code, - error_data, - retry_after=self._parse_retry_after(response), - code=code, - details=details, - ) - elif 500 <= status_code < 600: - raise AraraServerError(message, status_code, error_data, code, details) - else: - raise AraraError( - f"HTTP {status_code}: {message}", status_code, error_data, code, details - ) + error_class = _error_class(status_code, code) + if error_class is AraraError: + message = f"HTTP {status_code}: {message}" + raise error_class( + message, + status_code, + error_data, + code=code, + details=details, + retry_after=self._parse_retry_after(response), + ) def _parse_body( self, @@ -186,12 +221,18 @@ def _parse_body( response_model: Optional[Type[T]], ) -> Union[T, Dict[str, Any], None]: """Deserialize the response body into the requested model or dict.""" - if response.status_code == 204: + if response.status_code == 204 or not response.content: return None if response_model: return response_model.model_validate(response.json()) return response.json() + def _config_for(self, method: str, kwargs: Dict[str, Any]) -> Dict[str, Any]: + """Build the tenacity config for one call, gating retry by method.""" + config = dict(self._retry_config) + config["retry"] = _retry_policy(method, kwargs.get("headers")) + return config + def _send(self, method: str, path: str, **kwargs: Any) -> httpx.Response: """Send a synchronous request and raise for error statuses.""" response = self.sync_client.request(method, path, **kwargs) @@ -207,11 +248,14 @@ def request( method: str, path: str, response_model: Optional[Type[T]] = None, - **kwargs, + **kwargs: Any, ) -> Union[T, Dict[str, Any], None]: - """Send a request, retrying timeouts, connection errors, 5xx and 429.""" + """Send a request, retrying timeouts, connection errors, 5xx and 429. + + POST/PATCH are retried only when they carry an Idempotency-Key. + """ try: - response = Retrying(**self._retry_config)( + response = Retrying(**self._config_for(method, kwargs))( self._send, method, path, **kwargs ) except httpx.TimeoutException as e: @@ -225,11 +269,11 @@ async def arequest( method: str, path: str, response_model: Optional[Type[T]] = None, - **kwargs, + **kwargs: Any, ) -> Union[T, Dict[str, Any], None]: """Send an async request, retrying timeouts, connection errors, 5xx and 429.""" try: - response = await AsyncRetrying(**self._retry_config)( + response = await AsyncRetrying(**self._config_for(method, kwargs))( self._asend, method, path, **kwargs ) except httpx.TimeoutException as e: @@ -238,10 +282,10 @@ async def arequest( raise AraraConnectionError(f"Connection error: {str(e)}") from e return self._parse_body(response, response_model) - def close(self): + def close(self) -> None: """Close the synchronous client.""" self.sync_client.close() - async def aclose(self): + async def aclose(self) -> None: """Close the asynchronous client.""" await self.async_client.aclose() diff --git a/tests/unit/test_http_client.py b/tests/unit/test_http_client.py index d6fd976..ce371cb 100644 --- a/tests/unit/test_http_client.py +++ b/tests/unit/test_http_client.py @@ -4,6 +4,9 @@ from arara_api_sdk.exceptions import ( AraraAuthError, AraraError, + AraraForbiddenError, + AraraPlanFeatureLockedError, + AraraUnprocessableError, AraraRateLimitError, AraraResourceNotFoundError, AraraValidationError, @@ -195,10 +198,10 @@ def test_http_client_extracts_code_message_and_details_from_envelope( ) # Act & Assert - with pytest.raises(AraraError) as exc: + with pytest.raises(AraraForbiddenError) as exc: http_client.request("GET", "/envelope") - assert str(exc.value) == "HTTP 403: Limite do plano atingido em 'numbers': 1/1." - assert exc.value.message == "HTTP 403: Limite do plano atingido em 'numbers': 1/1." + assert str(exc.value) == "Limite do plano atingido em 'numbers': 1/1." + assert exc.value.message == "Limite do plano atingido em 'numbers': 1/1." assert exc.value.code == "PLAN_LIMIT_REACHED" assert exc.value.details == {"feature": "numbers", "current": 1, "max": 1} @@ -246,3 +249,109 @@ def test_http_client_retry_logic_on_server_error(http_client, respx_mock): # Assert assert response == {"status": "ok-after-retry"} assert route.call_count == 3 + + +def test_http_client_raises_plan_feature_locked_with_upgrade_details( + http_client, respx_mock +): + """Test that 403 PLAN_FEATURE_LOCKED becomes a typed error, not an auth error.""" + body = { + "error": { + "code": "PLAN_FEATURE_LOCKED", + "message": "Essa feature esta liberada a partir do plano Voo.", + "details": { + "feature": "campaigns", + "currentPlan": "DECOLAGEM", + "upgradeTo": "VOO", + }, + } + } + respx_mock.get("https://api.arara.test/locked").mock( + return_value=httpx.Response(403, json=body) + ) + + with pytest.raises(AraraPlanFeatureLockedError) as exc: + http_client.request("GET", "/locked") + assert exc.value.status_code == 403 + assert exc.value.feature == "campaigns" + assert exc.value.current_plan == "DECOLAGEM" + assert exc.value.upgrade_to == "VOO" + assert not isinstance(exc.value, AraraAuthError) + + +def test_http_client_treats_403_without_code_as_auth_error(http_client, respx_mock): + """Test that a bare 403 (key rejected by the filter) is an auth error.""" + respx_mock.get("https://api.arara.test/bare-403").mock( + return_value=httpx.Response(403) + ) + + with pytest.raises(AraraAuthError) as exc: + http_client.request("GET", "/bare-403") + assert exc.value.status_code == 403 + assert exc.value.code is None + + +def test_http_client_raises_unprocessable_on_422_preflight(http_client, respx_mock): + """Test that a 422 send pre-flight rejection keeps its code.""" + body = {"error": {"code": "INVALID_RECIPIENT", "message": "Numero invalido"}} + respx_mock.get("https://api.arara.test/422").mock( + return_value=httpx.Response(422, json=body) + ) + + with pytest.raises(AraraUnprocessableError) as exc: + http_client.request("GET", "/422") + assert exc.value.code == "INVALID_RECIPIENT" + + +def test_http_client_keeps_generic_error_for_unmapped_status(http_client, respx_mock): + """Test that an unmapped status still raises AraraError with the status.""" + respx_mock.get("https://api.arara.test/402").mock( + return_value=httpx.Response( + 402, json={"error": {"code": "INSUFFICIENT_FUNDS", "message": "Sem saldo"}} + ) + ) + + with pytest.raises(AraraError) as exc: + http_client.request("GET", "/402") + assert str(exc.value) == "HTTP 402: Sem saldo" + assert exc.value.code == "INSUFFICIENT_FUNDS" + + +def test_http_client_does_not_retry_post_without_idempotency_key( + http_client, respx_mock, recorded_sleeps +): + """Test that a POST without Idempotency-Key is never retried.""" + route = respx_mock.post("https://api.arara.test/post").mock( + return_value=httpx.Response(500) + ) + + with pytest.raises(AraraError): + http_client.request("POST", "/post", json={}) + assert route.call_count == 1 + + +def test_http_client_retries_post_with_idempotency_key_reusing_it( + http_client, respx_mock, recorded_sleeps +): + """Test that a POST with Idempotency-Key retries and sends the same key.""" + route = respx_mock.post("https://api.arara.test/post-key").mock( + side_effect=[httpx.Response(503), httpx.Response(200, json={"ok": True})] + ) + + response = http_client.request( + "POST", "/post-key", json={}, headers={"Idempotency-Key": "k-1"} + ) + + assert response == {"ok": True} + assert route.call_count == 2 + keys = [call.request.headers["Idempotency-Key"] for call in route.calls] + assert keys == ["k-1", "k-1"] + + +def test_http_client_returns_none_for_empty_success_body(http_client, respx_mock): + """Test that a 200 with an empty body (Void endpoints) yields None.""" + respx_mock.post("https://api.arara.test/void").mock( + return_value=httpx.Response(200) + ) + + assert http_client.request("POST", "/void") is None From 07f0b20d16c5724729fb2a64e0e8c127a53ad8b9 Mon Sep 17 00:00:00 2001 From: Micael Marques Date: Thu, 24 Sep 2026 16:01:25 -0300 Subject: [PATCH 02/13] refactor(models): replace deprecated pydantic config and settings env --- arara_api_sdk/config.py | 26 +++++++++-------- arara_api_sdk/models/contact.py | 43 ++++++++++++++++------------ arara_api_sdk/models/conversation.py | 8 +++--- arara_api_sdk/models/number.py | 27 ++++++++--------- arara_api_sdk/models/wallet.py | 21 +++++++------- tests/unit/test_config.py | 11 +++++++ 6 files changed, 78 insertions(+), 58 deletions(-) diff --git a/arara_api_sdk/config.py b/arara_api_sdk/config.py index 2a487dc..46fac8c 100644 --- a/arara_api_sdk/config.py +++ b/arara_api_sdk/config.py @@ -1,14 +1,16 @@ -from typing import Optional -from pydantic_settings import BaseSettings -from pydantic import Field +from pydantic_settings import BaseSettings, SettingsConfigDict + +DEFAULT_BASE_URL = "https://api.ararahq.com" +DEFAULT_TIMEOUT_SECONDS = 30.0 +DEFAULT_MAX_RETRIES = 3 + class SDKConfig(BaseSettings): - """SDK Configuration settings.""" - api_key: str = Field(..., env="ARARA_API_KEY") - base_url: str = Field("https://api.ararahq.com", env="ARARA_BASE_URL") - timeout: float = Field(30.0, env="ARARA_TIMEOUT") - max_retries: int = Field(3, env="ARARA_MAX_RETRIES") - - class Config: - env_prefix = "ARARA_" - case_sensitive = False + """SDK configuration, read from arguments or ``ARARA_*`` env vars.""" + + model_config = SettingsConfigDict(env_prefix="ARARA_", case_sensitive=False) + + api_key: str + base_url: str = DEFAULT_BASE_URL + timeout: float = DEFAULT_TIMEOUT_SECONDS + max_retries: int = DEFAULT_MAX_RETRIES diff --git a/arara_api_sdk/models/contact.py b/arara_api_sdk/models/contact.py index 47ce3fb..bcfc536 100644 --- a/arara_api_sdk/models/contact.py +++ b/arara_api_sdk/models/contact.py @@ -1,11 +1,12 @@ from typing import Any, Dict, List, Optional from uuid import UUID -from pydantic import BaseModel, Field +from pydantic import BaseModel, ConfigDict, Field class ContactRequest(BaseModel): """Request model for importing a contact.""" + name: str phone: str email: Optional[str] = None @@ -14,6 +15,7 @@ class ContactRequest(BaseModel): class ContactPatchRequest(BaseModel): """Request model for updating a contact.""" + name: Optional[str] = None email: Optional[str] = None tags: Optional[List[str]] = None @@ -21,6 +23,9 @@ class ContactPatchRequest(BaseModel): class ContactResponse(BaseModel): """Response model for a single contact.""" + + model_config = ConfigDict(populate_by_name=True) + id: UUID name: str phone: str @@ -39,24 +44,22 @@ class ContactResponse(BaseModel): opt_out_at: Optional[str] = Field(None, alias="optOutAt") last_template_name: Optional[str] = Field(None, alias="lastTemplateName") - class Config: - populate_by_name = True - class ContactsListResponse(BaseModel): """Paginated list of contacts.""" + + model_config = ConfigDict(populate_by_name=True) + contacts: List[ContactResponse] total: int page: int size: int total_pages: int = Field(..., alias="totalPages") - class Config: - populate_by_name = True - class ContactsBatchError(BaseModel): """A single failed row in a batch import.""" + index: int phone: Optional[str] = None reason: str @@ -64,18 +67,21 @@ class ContactsBatchError(BaseModel): class ContactsBatchResponse(BaseModel): """Result of a batch contact import.""" + + model_config = ConfigDict(populate_by_name=True) + import_id: UUID = Field(..., alias="importId") created: int updated: int skipped: int errors: List[ContactsBatchError] = [] - class Config: - populate_by_name = True - class ContactsStatsResponse(BaseModel): """Aggregate lifecycle counts for the organization's contacts.""" + + model_config = ConfigDict(populate_by_name=True) + total: int new_count: int = Field(..., alias="newCount") engaged: int @@ -83,29 +89,30 @@ class ContactsStatsResponse(BaseModel): dormant: int opted_out: int = Field(..., alias="optedOut") - class Config: - populate_by_name = True - class ContactsReactivationCandidate(BaseModel): """A dormant contact eligible for reactivation.""" + + model_config = ConfigDict(populate_by_name=True) + phone: str name: str last_message_at: Optional[str] = Field(None, alias="lastMessageAt") last_template_name: Optional[str] = Field(None, alias="lastTemplateName") - class Config: - populate_by_name = True - class ContactsReactivationResponse(BaseModel): """List of reactivation candidates.""" + total: int candidates: List[ContactsReactivationCandidate] class ContactMessageItem(BaseModel): """A single message in a contact's history.""" + + model_config = ConfigDict(populate_by_name=True) + id: UUID direction: str status: str @@ -113,12 +120,10 @@ class ContactMessageItem(BaseModel): body: Optional[str] = None created_at: str = Field(..., alias="createdAt") - class Config: - populate_by_name = True - class ContactMessagesResponse(BaseModel): """Message history for a contact.""" + phone: str total: int messages: List[ContactMessageItem] diff --git a/arara_api_sdk/models/conversation.py b/arara_api_sdk/models/conversation.py index 435ec71..ff96e3b 100644 --- a/arara_api_sdk/models/conversation.py +++ b/arara_api_sdk/models/conversation.py @@ -1,12 +1,12 @@ from uuid import UUID -from pydantic import BaseModel, Field +from pydantic import BaseModel, ConfigDict, Field class ConversationReplyRequest(BaseModel): """Request model for replying inside an open conversation window.""" + + model_config = ConfigDict(populate_by_name=True) + conversation_id: UUID = Field(..., alias="conversationId") body: str - - class Config: - populate_by_name = True diff --git a/arara_api_sdk/models/number.py b/arara_api_sdk/models/number.py index ef49328..b7acaca 100644 --- a/arara_api_sdk/models/number.py +++ b/arara_api_sdk/models/number.py @@ -1,11 +1,14 @@ from datetime import datetime from typing import List, Optional -from pydantic import BaseModel, Field +from pydantic import BaseModel, ConfigDict, Field class NumberCardDTO(BaseModel): """Detailed card for a single phone number, including health metrics.""" + + model_config = ConfigDict(populate_by_name=True) + id: str name: str alias: Optional[str] = None @@ -23,12 +26,12 @@ class NumberCardDTO(BaseModel): messages_last_7d: int = Field(..., alias="messagesLast7d") messages_last_30d: int = Field(..., alias="messagesLast30d") - class Config: - populate_by_name = True - class NumbersSlotDTO(BaseModel): """Plan slot info for dedicated numbers.""" + + model_config = ConfigDict(populate_by_name=True) + used: int max: int plan_label: str = Field(..., alias="planLabel") @@ -37,34 +40,32 @@ class NumbersSlotDTO(BaseModel): monthly_price_cents: int = Field(..., alias="monthlyPriceCents") monthly_total_cents: int = Field(..., alias="monthlyTotalCents") - class Config: - populate_by_name = True - class NumbersResponseDTO(BaseModel): """Numbers list with plan slot info.""" + numbers: List[NumberCardDTO] slot: NumbersSlotDTO class RequestNumberRequest(BaseModel): """Request a new dedicated number.""" + + model_config = ConfigDict(populate_by_name=True) + reason: Optional[str] = None expected_volume: Optional[str] = Field(None, alias="expectedVolume") area_code: Optional[str] = Field(None, alias="areaCode") display_name: Optional[str] = Field(None, alias="displayName") profile_picture_url: Optional[str] = Field(None, alias="profilePictureUrl") - class Config: - populate_by_name = True - class UpdateNumberRequest(BaseModel): """Update a phone number's editable fields.""" + + model_config = ConfigDict(populate_by_name=True) + alias: Optional[str] = None is_default: Optional[bool] = Field(None, alias="isDefault") name: Optional[str] = None description: Optional[str] = None - - class Config: - populate_by_name = True diff --git a/arara_api_sdk/models/wallet.py b/arara_api_sdk/models/wallet.py index a3217f7..50df03c 100644 --- a/arara_api_sdk/models/wallet.py +++ b/arara_api_sdk/models/wallet.py @@ -2,11 +2,14 @@ from decimal import Decimal from typing import List, Optional -from pydantic import BaseModel, Field +from pydantic import BaseModel, ConfigDict, Field class WalletTransactionDTO(BaseModel): """A single wallet ledger entry.""" + + model_config = ConfigDict(populate_by_name=True) + id: str amount: Decimal type: str @@ -15,36 +18,34 @@ class WalletTransactionDTO(BaseModel): mode: str created_at: Optional[datetime] = Field(None, alias="createdAt") - class Config: - populate_by_name = True - class WalletTransactionPageDTO(BaseModel): """Paginated wallet transactions.""" + + model_config = ConfigDict(populate_by_name=True) + content: List[WalletTransactionDTO] page: int size: int total_elements: int = Field(..., alias="totalElements") total_pages: int = Field(..., alias="totalPages") - class Config: - populate_by_name = True - class AutoRechargeSettingsDTO(BaseModel): """Auto-recharge configuration for the organization's wallet.""" + + model_config = ConfigDict(populate_by_name=True) + enabled: bool threshold: Decimal amount: Decimal last_attempt_at: Optional[datetime] = Field(None, alias="lastAttemptAt") last_failure_reason: Optional[str] = Field(None, alias="lastFailureReason") - class Config: - populate_by_name = True - class UpdateAutoRechargeRequest(BaseModel): """Request to update auto-recharge settings.""" + enabled: Optional[bool] = None threshold: Optional[Decimal] = None amount: Optional[Decimal] = None diff --git a/tests/unit/test_config.py b/tests/unit/test_config.py index 1f39d26..a3704d5 100644 --- a/tests/unit/test_config.py +++ b/tests/unit/test_config.py @@ -29,3 +29,14 @@ def test_config_default_values(): assert config.base_url == "https://api.ararahq.com" assert config.timeout == 30.0 assert config.max_retries == 3 + + +def test_config_reads_arara_prefixed_env_vars(monkeypatch): + """Test that ARARA_* env vars fill the config without deprecated Field(env=).""" + monkeypatch.setenv("ARARA_API_KEY", "env_key") + monkeypatch.setenv("ARARA_MAX_RETRIES", "5") + + config = SDKConfig() + + assert config.api_key == "env_key" + assert config.max_retries == 5 From 28139072ded3de5be1a2ef6a2ef6c126df62546d Mon Sep 17 00:00:00 2001 From: Micael Marques Date: Thu, 24 Sep 2026 16:01:25 -0300 Subject: [PATCH 03/13] feat(client): replace key-unreachable resources with auth.me and opt-outs --- arara_api_sdk/client.py | 84 ++++---- arara_api_sdk/models/api_key.py | 34 --- arara_api_sdk/models/auth.py | 21 +- arara_api_sdk/models/brain.py | 28 --- arara_api_sdk/models/organization.py | 61 ------ arara_api_sdk/models/payment.py | 37 ---- arara_api_sdk/models/user.py | 22 -- arara_api_sdk/resources/api_key.py | 36 ---- arara_api_sdk/resources/auth.py | 18 ++ arara_api_sdk/resources/brain.py | 35 ---- arara_api_sdk/resources/opt_out.py | 59 ++++++ arara_api_sdk/resources/organization.py | 198 ------------------ arara_api_sdk/resources/payment.py | 69 ------ arara_api_sdk/resources/user.py | 44 ---- tests/unit/resources/test_auth_and_opt_out.py | 79 +++++++ 15 files changed, 212 insertions(+), 613 deletions(-) delete mode 100644 arara_api_sdk/models/api_key.py delete mode 100644 arara_api_sdk/models/brain.py delete mode 100644 arara_api_sdk/models/organization.py delete mode 100644 arara_api_sdk/models/payment.py delete mode 100644 arara_api_sdk/models/user.py delete mode 100644 arara_api_sdk/resources/api_key.py create mode 100644 arara_api_sdk/resources/auth.py delete mode 100644 arara_api_sdk/resources/brain.py create mode 100644 arara_api_sdk/resources/opt_out.py delete mode 100644 arara_api_sdk/resources/organization.py delete mode 100644 arara_api_sdk/resources/payment.py delete mode 100644 arara_api_sdk/resources/user.py create mode 100644 tests/unit/resources/test_auth_and_opt_out.py diff --git a/arara_api_sdk/client.py b/arara_api_sdk/client.py index aea26a5..cf4e7cf 100644 --- a/arara_api_sdk/client.py +++ b/arara_api_sdk/client.py @@ -1,90 +1,86 @@ -from typing import Any, Optional +from typing import Any, Dict, Optional + from arara_api_sdk.config import SDKConfig from arara_api_sdk.http.client import HttpClient -from arara_api_sdk.resources.message import MessageResource -from arara_api_sdk.resources.template import TemplateResource -from arara_api_sdk.resources.organization import OrganizationResource -from arara_api_sdk.resources.user import UserResource -from arara_api_sdk.resources.brain import BrainResource +from arara_api_sdk.resources.auth import AuthResource from arara_api_sdk.resources.campaign import CampaignResource -from arara_api_sdk.resources.payment import PaymentResource from arara_api_sdk.resources.contact import ContactResource from arara_api_sdk.resources.conversation import ConversationResource -from arara_api_sdk.resources.wallet import WalletResource +from arara_api_sdk.resources.message import MessageResource from arara_api_sdk.resources.number import NumberResource +from arara_api_sdk.resources.opt_out import OptOutResource from arara_api_sdk.resources.smart_link import SmartLinkResource -from arara_api_sdk.resources.api_key import ApiKeyResource +from arara_api_sdk.resources.template import TemplateResource +from arara_api_sdk.resources.wallet import WalletResource + class AraraClient: - """ - Official Arara Python SDK Client. - - Provides access to messages, templates, organizations, users, and AI brain features. - Supports both synchronous and asynchronous operations. + """Official Arara Python SDK client, sync and async. + + Covers what an API key can reach: messages, templates, campaigns, + contacts, conversations, numbers, opt-outs, smart links, wallet and + ``auth.me()``. Contacts, conversations, wallet and ``auth.me`` require an + ADMIN key. """ def __init__( - self, - api_key: Optional[str] = None, + self, + api_key: Optional[str] = None, base_url: Optional[str] = None, timeout: Optional[float] = None, - max_retries: Optional[int] = None + max_retries: Optional[int] = None, ) -> None: - """Initializes the Arara SDK Client. + """Initialize the client. Args: - api_key: The Arara API Key. If not provided, will look for the - ARARA_API_KEY environment variable. - base_url: The base URL for the Arara API. Defaults to - https://api.ararahq.com. + api_key: The Arara API key. Falls back to ``ARARA_API_KEY``. + base_url: API base URL. Defaults to https://api.ararahq.com. timeout: Request timeout in seconds. Defaults to 30.0. - max_retries: Maximum number of request retries. Defaults to 3. + max_retries: Retries for transient failures. Defaults to 3. + """ - # Allow passing config directly or via env/defaults - config_kwargs = {} - if api_key: config_kwargs["api_key"] = api_key - if base_url: config_kwargs["base_url"] = base_url - if timeout: config_kwargs["timeout"] = timeout - if max_retries: config_kwargs["max_retries"] = max_retries - - self.config = SDKConfig(**config_kwargs) + overrides: Dict[str, Any] = { + "api_key": api_key, + "base_url": base_url, + "timeout": timeout, + "max_retries": max_retries, + } + self.config = SDKConfig( + **{key: value for key, value in overrides.items() if value is not None} + ) self._http = HttpClient(self.config) - - # Initialize resources + + self.auth = AuthResource(self._http) self.messages = MessageResource(self._http) self.templates = TemplateResource(self._http) - self.organizations = OrganizationResource(self._http) - self.users = UserResource(self._http) - self.brain = BrainResource(self._http) self.campaigns = CampaignResource(self._http) - self.payments = PaymentResource(self._http) self.contacts = ContactResource(self._http) self.conversations = ConversationResource(self._http) self.wallet = WalletResource(self._http) self.numbers = NumberResource(self._http) + self.opt_outs = OptOutResource(self._http) self.smart_links = SmartLinkResource(self._http) - self.api_keys = ApiKeyResource(self._http) def close(self) -> None: - """Closes the internal synchronous HTTP client.""" + """Close the internal synchronous HTTP client.""" self._http.close() async def aclose(self) -> None: - """Closes the internal asynchronous HTTP client.""" + """Close the internal asynchronous HTTP client.""" await self._http.aclose() def __enter__(self) -> "AraraClient": - """Context manager entry point for synchronous use.""" + """Enter the synchronous context manager.""" return self def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None: - """Context manager exit point for synchronous use.""" + """Exit the synchronous context manager.""" self.close() async def __aenter__(self) -> "AraraClient": - """Context manager entry point for asynchronous use.""" + """Enter the asynchronous context manager.""" return self async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None: - """Context manager exit point for asynchronous use.""" + """Exit the asynchronous context manager.""" await self.aclose() diff --git a/arara_api_sdk/models/api_key.py b/arara_api_sdk/models/api_key.py deleted file mode 100644 index 40ac907..0000000 --- a/arara_api_sdk/models/api_key.py +++ /dev/null @@ -1,34 +0,0 @@ -from typing import Optional - -from pydantic import BaseModel, Field - - -class ApiKey(BaseModel): - """Metadata for an existing API key (never exposes the secret).""" - id: str - name: Optional[str] = None - prefix: str - last_four: Optional[str] = Field(None, alias="lastFour") - mode: str - scope: Optional[str] = None - created_at: Optional[str] = Field(None, alias="createdAt") - last_used_at: Optional[str] = Field(None, alias="lastUsedAt") - expires_at: Optional[str] = Field(None, alias="expiresAt") - expired: Optional[bool] = None - ip_allowlist: Optional[str] = Field(None, alias="ipAllowlist") - rotated_from_id: Optional[str] = Field(None, alias="rotatedFromId") - - class Config: - populate_by_name = True - - -class GeneratedApiKey(BaseModel): - """A freshly created API key, including the one-time plaintext secret.""" - plain_text_key: str = Field(..., alias="plainTextKey") - prefix: Optional[str] = None - last_four_chars: Optional[str] = Field(None, alias="lastFourChars") - mode: Optional[str] = None - created_at: Optional[str] = Field(None, alias="createdAt") - - class Config: - populate_by_name = True diff --git a/arara_api_sdk/models/auth.py b/arara_api_sdk/models/auth.py index 7947dbd..33def88 100644 --- a/arara_api_sdk/models/auth.py +++ b/arara_api_sdk/models/auth.py @@ -1,8 +1,19 @@ from typing import Optional -from pydantic import BaseModel, EmailStr -class UserResponseDTO(BaseModel): - """Data Transfer Object for User response.""" - name: str - email: EmailStr +from pydantic import BaseModel, ConfigDict, Field + + +class CurrentUserResponse(BaseModel): + """``GET /auth/me``: the user that owns the API key. + + Only the stable fields are typed; anything else the API returns is kept + as extra attributes. + """ + + model_config = ConfigDict(populate_by_name=True, extra="allow") + + id: Optional[str] = None + name: Optional[str] = None + email: Optional[str] = None role: Optional[str] = None + organization_id: Optional[str] = Field(None, alias="organizationId") diff --git a/arara_api_sdk/models/brain.py b/arara_api_sdk/models/brain.py deleted file mode 100644 index 01751cc..0000000 --- a/arara_api_sdk/models/brain.py +++ /dev/null @@ -1,28 +0,0 @@ -from typing import Optional, Dict, Any -from pydantic import BaseModel, Field - -class BrainRequest(BaseModel): - """Request to interact with the AI Brain.""" - prompt: str - context_type: Optional[str] = Field("HYBRID", alias="contextType") - - class Config: - populate_by_name = True - -class BrainAction(BaseModel): - """Action suggested by the AI Brain.""" - type: str # CREATE_TEMPLATE, SCHEDULE_CAMPAIGN, etc. - payload: Dict[str, Any] - requires_approval: bool = Field(True, alias="requiresApproval") - description: str - - class Config: - populate_by_name = True - -class BrainResponse(BaseModel): - """Response from the AI Brain.""" - text: str - suggested_action: Optional[BrainAction] = Field(None, alias="suggestedAction") - - class Config: - populate_by_name = True diff --git a/arara_api_sdk/models/organization.py b/arara_api_sdk/models/organization.py deleted file mode 100644 index af8df56..0000000 --- a/arara_api_sdk/models/organization.py +++ /dev/null @@ -1,61 +0,0 @@ -from typing import Optional, List, Any, Dict -from pydantic import BaseModel, Field -from uuid import UUID - -class OrganizationBrainConfig(BaseModel): - """Configuration for Organization's AI Brain.""" - can_use_ai: bool = Field(..., alias="canUseAi") - is_ai_agent_enabled: bool = Field(..., alias="isAiAgentEnabled") - - class Config: - populate_by_name = True - -class UpdateBrainConfigRequest(BaseModel): - """Request to update UI Brain configuration.""" - is_ai_agent_enabled: Optional[bool] = Field(None, alias="isAiAgentEnabled") - - class Config: - populate_by_name = True - -class WebhookConfig(BaseModel): - """Webhook configuration for an organization.""" - url: str - secret: str - is_shared_number: bool = Field(..., alias="isSharedNumber") - - class Config: - populate_by_name = True - -class UpdateWebhookRequest(BaseModel): - """Request to update webhook configuration.""" - url: Optional[str] = None - secret: Optional[str] = None - -class InviteUserRequest(BaseModel): - """Request to invite a new user to the organization.""" - email: str - -class InvitationResponse(BaseModel): - """Response after inviting a user.""" - message: str - token: str - -class OrganizationNumber(BaseModel): - """Model for an organization's phone number.""" - id: str - name: str - phone_number: str = Field(..., alias="phoneNumber") - type: str - is_default: bool = Field(..., alias="isDefault") - alias: str - - class Config: - populate_by_name = True - -class UpdateNumberRequest(BaseModel): - """Request to update a phone number's details.""" - alias: Optional[str] = None - is_default: Optional[bool] = Field(None, alias="isDefault") - - class Config: - populate_by_name = True diff --git a/arara_api_sdk/models/payment.py b/arara_api_sdk/models/payment.py deleted file mode 100644 index 57e47fc..0000000 --- a/arara_api_sdk/models/payment.py +++ /dev/null @@ -1,37 +0,0 @@ -from typing import Optional, Dict, Any -from pydantic import BaseModel, Field - -class AbacatePayCustomerRequest(BaseModel): - name: str - cellphone: str - email: str - tax_id: str = Field(..., alias="taxId") - -class AbacatePayPixRequest(BaseModel): - amount: int # Cents - expires_in: Optional[int] = Field(3600, alias="expiresIn") - description: Optional[str] = "Recarga de Créditos - Arara" - customer: Optional[AbacatePayCustomerRequest] = None - metadata: Optional[Dict[str, str]] = None - - class Config: - populate_by_name = True - -class AbacatePayPixData(BaseModel): - id: str - amount: int - status: str - br_code: str = Field(..., alias="brCode") - br_code_base64: str = Field(..., alias="brCodeBase64") - expires_at: str = Field(..., alias="expiresAt") - - class Config: - populate_by_name = True - -class AbacatePayPixResponse(BaseModel): - data: AbacatePayPixData - error: Optional[str] = None - -class CreatePaymentRequest(BaseModel): - amount: int - method: str = "PIX" diff --git a/arara_api_sdk/models/user.py b/arara_api_sdk/models/user.py deleted file mode 100644 index fbcb864..0000000 --- a/arara_api_sdk/models/user.py +++ /dev/null @@ -1,22 +0,0 @@ -from typing import Optional -from pydantic import BaseModel, Field - -class UserUpdate(BaseModel): - """Request model for updating user information.""" - name: Optional[str] = None - phone_number: Optional[str] = Field(None, alias="phoneNumber") - - class Config: - populate_by_name = True - -class UserProfileResponse(BaseModel): - """Response model for the current user profile.""" - name: str - email: str - phone_number: str = Field(..., alias="phoneNumber") - document_number: str = Field(..., alias="documentNumber") - role: str - needs_initial_onboarding: bool = Field(..., alias="needsInitialOnboarding") - - class Config: - populate_by_name = True diff --git a/arara_api_sdk/resources/api_key.py b/arara_api_sdk/resources/api_key.py deleted file mode 100644 index 1c5a213..0000000 --- a/arara_api_sdk/resources/api_key.py +++ /dev/null @@ -1,36 +0,0 @@ -from typing import List - -from arara_api_sdk.resources import BaseResource -from arara_api_sdk.models.api_key import ApiKey, GeneratedApiKey - -_BASE = "/v1/api-keys" - - -class ApiKeyResource(BaseResource): - """Resource for managing API keys. - - Read keys only GET; send keys GET plus POST on /messages and /campaigns; - everything else needs an admin-scoped key. - """ - - def list(self) -> List[ApiKey]: - """GET /v1/api-keys — lists API keys synchronously.""" - response = self._http.request("GET", _BASE) - return [ApiKey.model_validate(item) for item in response] - - async def list_async(self) -> List[ApiKey]: - """GET /v1/api-keys — lists API keys asynchronously.""" - response = await self._http.arequest("GET", _BASE) - return [ApiKey.model_validate(item) for item in response] - - def create(self, mode: str = "LIVE") -> GeneratedApiKey: - """POST /v1/api-keys — creates an API key synchronously.""" - return self._http.request( - "POST", _BASE, response_model=GeneratedApiKey, params={"mode": mode} - ) - - async def create_async(self, mode: str = "LIVE") -> GeneratedApiKey: - """POST /v1/api-keys — creates an API key asynchronously.""" - return await self._http.arequest( - "POST", _BASE, response_model=GeneratedApiKey, params={"mode": mode} - ) diff --git a/arara_api_sdk/resources/auth.py b/arara_api_sdk/resources/auth.py new file mode 100644 index 0000000..8b8b465 --- /dev/null +++ b/arara_api_sdk/resources/auth.py @@ -0,0 +1,18 @@ +from arara_api_sdk.models.auth import CurrentUserResponse +from arara_api_sdk.resources import BaseResource + +_ME = "/auth/me" + + +class AuthResource(BaseResource): + """Identity of the API key. Requires an ADMIN key.""" + + def me(self) -> CurrentUserResponse: + """GET /auth/me — the user that owns the API key.""" + return self._http.request("GET", _ME, response_model=CurrentUserResponse) + + async def me_async(self) -> CurrentUserResponse: + """GET /auth/me — asynchronously.""" + return await self._http.arequest( + "GET", _ME, response_model=CurrentUserResponse + ) diff --git a/arara_api_sdk/resources/brain.py b/arara_api_sdk/resources/brain.py deleted file mode 100644 index 2065254..0000000 --- a/arara_api_sdk/resources/brain.py +++ /dev/null @@ -1,35 +0,0 @@ -from arara_api_sdk.resources import BaseResource -from arara_api_sdk.models.brain import BrainRequest, BrainResponse - -class BrainResource(BaseResource): - """Resource for interacting with the AI Brain.""" - - def prompt(self, request: BrainRequest) -> BrainResponse: - """Sends a prompt/question to the AI Brain synchronously. - - Args: - request: The prompt data and optional context. - - Returns: - The AI response and any identified actions. - """ - return self._http.request( - "POST", "/v1/brain", - response_model=BrainResponse, - json=request.model_dump(by_alias=True) - ) - - async def prompt_async(self, request: BrainRequest) -> BrainResponse: - """Sends a prompt/question to the AI Brain asynchronously. - - Args: - request: The prompt data and optional context. - - Returns: - The AI response and any identified actions. - """ - return await self._http.arequest( - "POST", "/v1/brain", - response_model=BrainResponse, - json=request.model_dump(by_alias=True) - ) diff --git a/arara_api_sdk/resources/opt_out.py b/arara_api_sdk/resources/opt_out.py new file mode 100644 index 0000000..fe143e6 --- /dev/null +++ b/arara_api_sdk/resources/opt_out.py @@ -0,0 +1,59 @@ +from typing import Any, Dict, Optional +from urllib.parse import quote + +from arara_api_sdk.resources import BaseResource + +_OPT_OUTS = "/v1/opt-outs" + + +def _phone_path(phone: str) -> str: + """Build ``/v1/opt-outs/{phone}`` with the phone URL-encoded (``+`` included).""" + return f"{_OPT_OUTS}/{quote(phone, safe='')}" + + +def _create_body(phone: str, reason: Optional[str]) -> Dict[str, Any]: + """Build the body of ``POST /v1/opt-outs``.""" + body: Dict[str, Any] = {"phone": phone} + if reason: + body["reason"] = reason + return body + + +class OptOutResource(BaseResource): + """Numbers that asked not to receive messages (blocked at send time).""" + + def list(self) -> Dict[str, Any]: + """GET /v1/opt-outs — the organization's opt-out list.""" + return self._http.request("GET", _OPT_OUTS) + + async def list_async(self) -> Dict[str, Any]: + """GET /v1/opt-outs — asynchronously.""" + return await self._http.arequest("GET", _OPT_OUTS) + + def create(self, phone: str, reason: Optional[str] = None) -> Dict[str, Any]: + """POST /v1/opt-outs — blocks a number.""" + return self._http.request("POST", _OPT_OUTS, json=_create_body(phone, reason)) + + async def create_async( + self, phone: str, reason: Optional[str] = None + ) -> Dict[str, Any]: + """POST /v1/opt-outs — asynchronously.""" + return await self._http.arequest( + "POST", _OPT_OUTS, json=_create_body(phone, reason) + ) + + def get(self, phone: str) -> Dict[str, Any]: + """GET /v1/opt-outs/{phone} — opt-out status of one number.""" + return self._http.request("GET", _phone_path(phone)) + + async def get_async(self, phone: str) -> Dict[str, Any]: + """GET /v1/opt-outs/{phone} — asynchronously.""" + return await self._http.arequest("GET", _phone_path(phone)) + + def delete(self, phone: str) -> None: + """DELETE /v1/opt-outs/{phone} — lifts the block.""" + self._http.request("DELETE", _phone_path(phone)) + + async def delete_async(self, phone: str) -> None: + """DELETE /v1/opt-outs/{phone} — asynchronously.""" + await self._http.arequest("DELETE", _phone_path(phone)) diff --git a/arara_api_sdk/resources/organization.py b/arara_api_sdk/resources/organization.py deleted file mode 100644 index 8f0d3dc..0000000 --- a/arara_api_sdk/resources/organization.py +++ /dev/null @@ -1,198 +0,0 @@ -from typing import List, Dict, Any, Optional -from arara_api_sdk.resources import BaseResource -from arara_api_sdk.models.organization import ( - OrganizationBrainConfig, - UpdateBrainConfigRequest, - WebhookConfig, - UpdateWebhookRequest, - InviteUserRequest, - InvitationResponse, - OrganizationNumber, - UpdateNumberRequest -) -from arara_api_sdk.models.auth import UserResponseDTO - -class OrganizationResource(BaseResource): - """Resource for managing organization settings and members.""" - - def get_webhook(self) -> WebhookConfig: - """Retrieves current webhook configuration synchronously. - - Returns: - The webhook configuration including URL and secret. - """ - return self._http.request("GET", "/organizations/me/webhook", response_model=WebhookConfig) - - async def get_webhook_async(self) -> WebhookConfig: - """Retrieves current webhook configuration asynchronously. - - Returns: - The webhook configuration including URL and secret. - """ - return await self._http.arequest("GET", "/organizations/me/webhook", response_model=WebhookConfig) - - def update_webhook(self, request: UpdateWebhookRequest) -> Dict[str, Any]: - """Updates webhook configuration synchronously. - - Args: - request: The new webhook URL and/or secret. - - Returns: - The API response confirmation. - """ - return self._http.request("PATCH", "/organizations/me/webhook", json=request.model_dump(exclude_none=True)) - - async def update_webhook_async(self, request: UpdateWebhookRequest) -> Dict[str, Any]: - """Updates webhook configuration asynchronously. - - Args: - request: The new webhook URL and/or secret. - - Returns: - The API response confirmation. - """ - return await self._http.arequest("PATCH", "/organizations/me/webhook", json=request.model_dump(exclude_none=True)) - - def get_brain_config(self) -> OrganizationBrainConfig: - """Retrieves AI Brain configuration for the organization synchronously. - - Returns: - The current Brain configuration. - """ - return self._http.request("GET", "/organizations/me/brain-config", response_model=OrganizationBrainConfig) - - async def get_brain_config_async(self) -> OrganizationBrainConfig: - """Retrieves AI Brain configuration for the organization asynchronously. - - Returns: - The current Brain configuration. - """ - return await self._http.arequest("GET", "/organizations/me/brain-config", response_model=OrganizationBrainConfig) - - def update_brain_config(self, request: UpdateBrainConfigRequest) -> OrganizationBrainConfig: - """Updates AI Brain configuration synchronously. - - Args: - request: The new configuration parameters. - - Returns: - The updated Brain configuration. - """ - return self._http.request( - "PATCH", "/organizations/me/brain-config", - response_model=OrganizationBrainConfig, - json=request.model_dump(exclude_none=True) - ) - - async def update_brain_config_async(self, request: UpdateBrainConfigRequest) -> OrganizationBrainConfig: - """Updates AI Brain configuration asynchronously. - - Args: - request: The new configuration parameters. - - Returns: - The updated Brain configuration. - """ - return await self._http.arequest( - "PATCH", "/organizations/me/brain-config", - response_model=OrganizationBrainConfig, - json=request.model_dump(exclude_none=True) - ) - - def invite_user(self, request: InviteUserRequest) -> InvitationResponse: - """Invites a new user to the organization synchronously. - - Args: - request: Invitation details including email and role. - - Returns: - The invitation response. - """ - return self._http.request( - "POST", "/organizations/me/invitations", - response_model=InvitationResponse, - json=request.model_dump() - ) - - async def invite_user_async(self, request: InviteUserRequest) -> InvitationResponse: - """Invites a new user to the organization asynchronously. - - Args: - request: Invitation details including email and role. - - Returns: - The invitation response. - """ - return await self._http.arequest( - "POST", "/organizations/me/invitations", - response_model=InvitationResponse, - json=request.model_dump() - ) - - def list_members(self) -> List[UserResponseDTO]: - """Lists all organization members synchronously. - - Returns: - A list of organization members. - """ - response = self._http.request("GET", "/organizations/me/members") - return [UserResponseDTO.model_validate(item) for item in response] - - async def list_members_async(self) -> List[UserResponseDTO]: - """Lists all organization members asynchronously. - - Returns: - A list of organization members. - """ - response = await self._http.arequest("GET", "/organizations/me/members") - return [UserResponseDTO.model_validate(item) for item in response] - - def list_numbers(self) -> List[OrganizationNumber]: - """Lists all phone numbers owned by the organization synchronously. - - Returns: - A list of phone numbers. - """ - response = self._http.request("GET", "/organizations/me/numbers") - return [OrganizationNumber.model_validate(item) for item in response] - - async def list_numbers_async(self) -> List[OrganizationNumber]: - """Lists all phone numbers owned by the organization asynchronously. - - Returns: - A list of phone numbers. - """ - response = await self._http.arequest("GET", "/organizations/me/numbers") - return [OrganizationNumber.model_validate(item) for item in response] - - def update_number(self, number_id: str, request: UpdateNumberRequest) -> OrganizationNumber: - """Updates configuration for a specific phone number synchronously. - - Args: - number_id: The ID of the number to update. - request: The updated configuration. - - Returns: - The updated phone number details. - """ - return self._http.request( - "PATCH", f"/organizations/me/numbers/{number_id}", - response_model=OrganizationNumber, - json=request.model_dump(exclude_none=True) - ) - - async def update_number_async(self, number_id: str, request: UpdateNumberRequest) -> OrganizationNumber: - """Updates configuration for a specific phone number asynchronously. - - Args: - number_id: The ID of the number to update. - request: The updated configuration. - - Returns: - The updated phone number details. - """ - return await self._http.arequest( - "PATCH", f"/organizations/me/numbers/{number_id}", - response_model=OrganizationNumber, - json=request.model_dump(exclude_none=True) - ) diff --git a/arara_api_sdk/resources/payment.py b/arara_api_sdk/resources/payment.py deleted file mode 100644 index 03c9061..0000000 --- a/arara_api_sdk/resources/payment.py +++ /dev/null @@ -1,69 +0,0 @@ -from typing import Optional, Dict, Any -from pydantic import BaseModel, Field -from arara_api_sdk.resources import BaseResource -from arara_api_sdk.models.payment import ( - AbacatePayPixRequest, - AbacatePayPixResponse, - CreatePaymentRequest -) - -class PaymentResource(BaseResource): - """Resource for managing payments and credits.""" - - def create_pix(self, request: AbacatePayPixRequest) -> AbacatePayPixResponse: - """Creates a Pix payment via AbacatePay synchronously. - - Args: - request: The payment details. - - Returns: - The created Pix payment response including QR code/Copy-Paste. - """ - return self._http.request( - "POST", "/payments/pix", - response_model=AbacatePayPixResponse, - json=request.model_dump(by_alias=True, exclude_none=True) - ) - - async def create_pix_async(self, request: AbacatePayPixRequest) -> AbacatePayPixResponse: - """Creates a Pix payment via AbacatePay asynchronously. - - Args: - request: The payment details. - - Returns: - The created Pix payment response including QR code/Copy-Paste. - """ - return await self._http.arequest( - "POST", "/payments/pix", - response_model=AbacatePayPixResponse, - json=request.model_dump(by_alias=True, exclude_none=True) - ) - - def checkout(self, request: CreatePaymentRequest) -> Any: - """Creates a checkout session for credits synchronously. - - Args: - request: Checkout session parameters. - - Returns: - The checkout session response. - """ - return self._http.request( - "POST", "/payments/checkout", - json=request.model_dump(exclude_none=True) - ) - - async def checkout_async(self, request: CreatePaymentRequest) -> Any: - """Creates a checkout session for credits asynchronously. - - Args: - request: Checkout session parameters. - - Returns: - The checkout session response. - """ - return await self._http.arequest( - "POST", "/payments/checkout", - json=request.model_dump(exclude_none=True) - ) diff --git a/arara_api_sdk/resources/user.py b/arara_api_sdk/resources/user.py deleted file mode 100644 index 7ffd05d..0000000 --- a/arara_api_sdk/resources/user.py +++ /dev/null @@ -1,44 +0,0 @@ -from typing import Dict, Any -from arara_api_sdk.resources import BaseResource -from arara_api_sdk.models.user import UserProfileResponse, UserUpdate - -class UserResource(BaseResource): - """Resource for managing user profile.""" - - def me(self) -> UserProfileResponse: - """Retrieves the current user's profile information synchronously. - - Returns: - The profile details of the authenticated user. - """ - return self._http.request("GET", "/users/me", response_model=UserProfileResponse) - - async def me_async(self) -> UserProfileResponse: - """Retrieves the current user's profile information asynchronously. - - Returns: - The profile details of the authenticated user. - """ - return await self._http.arequest("GET", "/users/me", response_model=UserProfileResponse) - - def update(self, request: UserUpdate) -> Dict[str, Any]: - """Updates the current user's profile synchronously. - - Args: - request: The updated profile information. - - Returns: - The API confirmation response. - """ - return self._http.request("PATCH", "/users/me", json=request.model_dump(exclude_none=True)) - - async def update_async(self, request: UserUpdate) -> Dict[str, Any]: - """Updates the current user's profile asynchronously. - - Args: - request: The updated profile information. - - Returns: - The API confirmation response. - """ - return await self._http.arequest("PATCH", "/users/me", json=request.model_dump(exclude_none=True)) diff --git a/tests/unit/resources/test_auth_and_opt_out.py b/tests/unit/resources/test_auth_and_opt_out.py new file mode 100644 index 0000000..8f00bf2 --- /dev/null +++ b/tests/unit/resources/test_auth_and_opt_out.py @@ -0,0 +1,79 @@ +import json + +import httpx +import pytest + +OPT_OUTS = "https://api.arara.test/v1/opt-outs" + + +def test_auth_me_calls_auth_me_without_v1(arara_client, respx_mock): + """Test that auth.me() hits GET /auth/me and keeps unknown fields.""" + route = respx_mock.get("https://api.arara.test/auth/me").mock( + return_value=httpx.Response( + 200, + json={"name": "Ana", "email": "ana@x.com", "role": "ADMIN", "emailPending": False}, + ) + ) + + me = arara_client.auth.me() + + assert route.call_count == 1 + assert me.name == "Ana" + assert me.role == "ADMIN" + + +@pytest.mark.asyncio +async def test_auth_me_async(arara_client, respx_mock): + """Test the async auth.me path.""" + respx_mock.get("https://api.arara.test/auth/me").mock( + return_value=httpx.Response(200, json={"name": "Ana", "email": "a@x.com"}) + ) + + assert (await arara_client.auth.me_async()).email == "a@x.com" + + +def test_removed_resources_are_gone(arara_client): + """Test that resources unreachable by API key are no longer exposed.""" + for name in ("payments", "brain", "organizations", "users", "api_keys"): + assert not hasattr(arara_client, name) + + +def test_opt_outs_sync_paths(arara_client, respx_mock): + """Test list, create, get and delete with the phone URL-encoded.""" + respx_mock.get(OPT_OUTS).mock(return_value=httpx.Response(200, json={"items": []})) + create = respx_mock.post(OPT_OUTS).mock( + return_value=httpx.Response(201, json={"phone": "+5511987654321"}) + ) + one = respx_mock.get(f"{OPT_OUTS}/%2B5511987654321").mock( + return_value=httpx.Response(200, json={"optedOut": True}) + ) + delete = respx_mock.delete(f"{OPT_OUTS}/%2B5511987654321").mock( + return_value=httpx.Response(204) + ) + + assert arara_client.opt_outs.list() == {"items": []} + arara_client.opt_outs.create("+5511987654321", reason="pediu") + assert arara_client.opt_outs.get("+5511987654321") == {"optedOut": True} + assert arara_client.opt_outs.delete("+5511987654321") is None + + assert json.loads(create.calls[0].request.content) == { + "phone": "+5511987654321", + "reason": "pediu", + } + assert one.call_count == 1 + assert delete.call_count == 1 + + +@pytest.mark.asyncio +async def test_opt_outs_async_paths(arara_client, respx_mock): + """Test the async opt-out paths; reason is omitted when absent.""" + respx_mock.get(OPT_OUTS).mock(return_value=httpx.Response(200, json={})) + create = respx_mock.post(OPT_OUTS).mock(return_value=httpx.Response(201, json={})) + respx_mock.get(f"{OPT_OUTS}/5511").mock(return_value=httpx.Response(200, json={})) + respx_mock.delete(f"{OPT_OUTS}/5511").mock(return_value=httpx.Response(204)) + + assert await arara_client.opt_outs.list_async() == {} + await arara_client.opt_outs.create_async("5511") + assert await arara_client.opt_outs.get_async("5511") == {} + assert await arara_client.opt_outs.delete_async("5511") is None + assert json.loads(create.calls[0].request.content) == {"phone": "5511"} From 67b1d0a9c8d030a5f800cb901ab266db9b8beead Mon Sep 17 00:00:00 2001 From: Micael Marques Date: Thu, 24 Sep 2026 16:01:25 -0300 Subject: [PATCH 04/13] fix(templates): send body on create and paginate template and smart link lists --- arara_api_sdk/models/common.py | 23 +++ arara_api_sdk/models/smart_link.py | 20 +-- arara_api_sdk/models/template.py | 70 ++++++-- arara_api_sdk/resources/smart_link.py | 36 ++-- arara_api_sdk/resources/template.py | 197 +++++++++++----------- tests/unit/resources/test_smart_link.py | 61 +++++++ tests/unit/resources/test_template.py | 214 +++++++++++++++++------- 7 files changed, 426 insertions(+), 195 deletions(-) create mode 100644 arara_api_sdk/models/common.py create mode 100644 tests/unit/resources/test_smart_link.py diff --git a/arara_api_sdk/models/common.py b/arara_api_sdk/models/common.py new file mode 100644 index 0000000..5543312 --- /dev/null +++ b/arara_api_sdk/models/common.py @@ -0,0 +1,23 @@ +from typing import Generic, List, TypeVar + +from pydantic import BaseModel, ConfigDict, Field + +ItemT = TypeVar("ItemT") + + +class PaginationInfo(BaseModel): + """Pagination block of ``{data, pagination}`` responses.""" + + model_config = ConfigDict(populate_by_name=True) + + page: int + size: int + total_elements: int = Field(..., alias="totalElements") + total_pages: int = Field(..., alias="totalPages") + + +class Page(BaseModel, Generic[ItemT]): + """Paginated response ``{data: [...], pagination: {...}}``.""" + + data: List[ItemT] + pagination: PaginationInfo diff --git a/arara_api_sdk/models/smart_link.py b/arara_api_sdk/models/smart_link.py index 1b2bcc2..14fd2c7 100644 --- a/arara_api_sdk/models/smart_link.py +++ b/arara_api_sdk/models/smart_link.py @@ -2,32 +2,35 @@ from typing import Optional from uuid import UUID -from pydantic import BaseModel, Field +from pydantic import BaseModel, ConfigDict, Field class CreateWhatsAppSmartLinkRequest(BaseModel): """Request to create a WhatsApp smart link.""" + + model_config = ConfigDict(populate_by_name=True) + name: str phone_number: str = Field(..., alias="phoneNumber") default_text: Optional[str] = Field(None, alias="defaultText") qr_code_color: Optional[str] = Field("BLACK", alias="qrCodeColor") - class Config: - populate_by_name = True - class UpdateWhatsAppSmartLinkRequest(BaseModel): """Request to update a WhatsApp smart link.""" + + model_config = ConfigDict(populate_by_name=True) + name: Optional[str] = None default_text: Optional[str] = Field(None, alias="defaultText") qr_code_color: Optional[str] = Field(None, alias="qrCodeColor") - class Config: - populate_by_name = True - class WhatsAppSmartLinkResponse(BaseModel): """Response model for a WhatsApp smart link.""" + + model_config = ConfigDict(populate_by_name=True) + id: UUID name: str phone_number: str = Field(..., alias="phoneNumber") @@ -37,6 +40,3 @@ class WhatsAppSmartLinkResponse(BaseModel): short_url: str = Field(..., alias="shortUrl") created_at: Optional[datetime] = Field(None, alias="createdAt") clicks: int = 0 - - class Config: - populate_by_name = True diff --git a/arara_api_sdk/models/template.py b/arara_api_sdk/models/template.py index f45909c..c507950 100644 --- a/arara_api_sdk/models/template.py +++ b/arara_api_sdk/models/template.py @@ -1,10 +1,17 @@ -from typing import Optional, Dict, Any -from pydantic import BaseModel, Field from datetime import datetime +from typing import Any, Dict, List, Optional from uuid import UUID +from pydantic import BaseModel, ConfigDict, Field + +DEFAULT_TEMPLATE_LANGUAGE = "pt_BR" + + class TemplateResponse(BaseModel): """Response model for a Template.""" + + model_config = ConfigDict(populate_by_name=True) + id: UUID name: str formatted_name: str = Field(..., alias="formattedName") @@ -15,31 +22,66 @@ class TemplateResponse(BaseModel): provider_template_id: str = Field(..., alias="providerTemplateId") provider_status: str = Field(..., alias="providerStatus") rejection_reason: Optional[str] = Field(None, alias="rejectionReason") + available_for_sending: bool = Field(True, alias="availableForSending") + unavailable_reason: Optional[str] = Field(None, alias="unavailableReason") body_preview: Optional[str] = Field(None, alias="bodyPreview") - structure_json: Dict[str, Any] = Field(..., alias="structureJson") + structure_json: Any = Field(None, alias="structureJson") usage_guide: Optional[Dict[str, Any]] = Field(None, alias="usageGuide") variables_schema: Optional[Dict[str, str]] = Field(None, alias="variablesSchema") created_at: datetime = Field(..., alias="createdAt") updated_at: Optional[datetime] = Field(None, alias="updatedAt") - class Config: - populate_by_name = True + +class TemplateButton(BaseModel): + """A template button (``QUICK_REPLY``, ``URL``, ``PHONE_NUMBER``, ...).""" + + model_config = ConfigDict(populate_by_name=True) + + type: str + text: str + url: Optional[str] = None + phone: Optional[str] = None + extra_config: Optional[Dict[str, Any]] = Field(None, alias="extraConfig") + flow_id: Optional[UUID] = Field(None, alias="flowId") + + +class CarouselCard(BaseModel): + """A carousel card: media, body and up to two buttons.""" + + model_config = ConfigDict(populate_by_name=True) + + media_url: str = Field(..., alias="mediaUrl") + body: str + buttons: Optional[List[TemplateButton]] = None + class CreateTemplateRequest(BaseModel): - """Request model for creating a new Template.""" + """Request model for ``POST /v1/templates``. + + ``body`` is required; ``samples`` maps each body variable (``"1"``, + ``"2"``...) to an example value for Meta review. + """ + + model_config = ConfigDict(populate_by_name=True) + name: str category: str - language: str - structure_json: Dict[str, Any] = Field(..., alias="structureJson") + body: str + language: str = DEFAULT_TEMPLATE_LANGUAGE + header: Optional[str] = None + header_type: Optional[str] = Field(None, alias="headerType") + footer: Optional[str] = None + buttons: Optional[List[TemplateButton]] = None + samples: Optional[Dict[str, str]] = None + variable_examples: Optional[List[str]] = Field(None, alias="variableExamples") + carousel_cards: Optional[List[CarouselCard]] = Field(None, alias="carouselCards") - class Config: - populate_by_name = True class TemplateStatusResponse(BaseModel): """Response for template status checking.""" + + model_config = ConfigDict(populate_by_name=True, extra="allow") + status: str rejection_reason: Optional[str] = Field(None, alias="rejectionReason") - category: str - - class Config: - populate_by_name = True + category: Optional[str] = None diff --git a/arara_api_sdk/resources/smart_link.py b/arara_api_sdk/resources/smart_link.py index 926ea8a..2d430e3 100644 --- a/arara_api_sdk/resources/smart_link.py +++ b/arara_api_sdk/resources/smart_link.py @@ -1,13 +1,17 @@ -from typing import Any, Dict, List +from typing import Any, Dict -from arara_api_sdk.resources import BaseResource +from arara_api_sdk.models.common import Page from arara_api_sdk.models.smart_link import ( CreateWhatsAppSmartLinkRequest, UpdateWhatsAppSmartLinkRequest, WhatsAppSmartLinkResponse, ) +from arara_api_sdk.resources import BaseResource _BASE = "/v1/smart-links/whatsapp" +DEFAULT_SMART_LINK_PAGE_SIZE = 50 + +SmartLinkPage = Page[WhatsAppSmartLinkResponse] class SmartLinkResource(BaseResource): @@ -53,15 +57,27 @@ async def update_async( json=request.model_dump(by_alias=True, exclude_none=True), ) - def list(self) -> List[WhatsAppSmartLinkResponse]: - """GET /v1/smart-links/whatsapp — lists smart links synchronously.""" - response = self._http.request("GET", _BASE) - return [WhatsAppSmartLinkResponse.model_validate(item) for item in response] + def list( + self, page: int = 0, size: int = DEFAULT_SMART_LINK_PAGE_SIZE + ) -> SmartLinkPage: + """GET /v1/smart-links/whatsapp — one page ``{data, pagination}``.""" + return self._http.request( + "GET", + _BASE, + response_model=SmartLinkPage, + params={"page": page, "size": size}, + ) - async def list_async(self) -> List[WhatsAppSmartLinkResponse]: - """GET /v1/smart-links/whatsapp — lists smart links asynchronously.""" - response = await self._http.arequest("GET", _BASE) - return [WhatsAppSmartLinkResponse.model_validate(item) for item in response] + async def list_async( + self, page: int = 0, size: int = DEFAULT_SMART_LINK_PAGE_SIZE + ) -> SmartLinkPage: + """GET /v1/smart-links/whatsapp — one page, asynchronously.""" + return await self._http.arequest( + "GET", + _BASE, + response_model=SmartLinkPage, + params={"page": page, "size": size}, + ) def stats(self, link_id: str) -> Dict[str, Any]: """GET /v1/smart-links/whatsapp/{id}/stats — click stats synchronously.""" diff --git a/arara_api_sdk/resources/template.py b/arara_api_sdk/resources/template.py index b38fa8c..298fb3d 100644 --- a/arara_api_sdk/resources/template.py +++ b/arara_api_sdk/resources/template.py @@ -1,139 +1,136 @@ -from typing import List, Optional +from typing import Any, Dict, Optional from uuid import UUID -from arara_api_sdk.resources import BaseResource + +from arara_api_sdk.models.common import Page from arara_api_sdk.models.template import ( - TemplateResponse, - CreateTemplateRequest, - TemplateStatusResponse + CreateTemplateRequest, + TemplateResponse, + TemplateStatusResponse, ) +from arara_api_sdk.resources import BaseResource -class TemplateResource(BaseResource): - """Resource for managing templates.""" +_TEMPLATES = "/v1/templates" +DEFAULT_TEMPLATE_PAGE_SIZE = 50 +DEFAULT_ANALYTICS_PERIOD = "30d" - def create(self, request: CreateTemplateRequest) -> TemplateResponse: - """Creates a new message template synchronously. +TemplatePage = Page[TemplateResponse] - Args: - request: The template creation data. - Returns: - The created template details. - """ +def _list_params( + name: Optional[str], status: Optional[str], page: int, size: int +) -> Dict[str, Any]: + """Build the query string of ``GET /v1/templates``.""" + params: Dict[str, Any] = {"page": page, "size": size} + if name: + params["name"] = name + if status: + params["status"] = status + return params + + +class TemplateResource(BaseResource): + """Resource for message templates. + + ``get``, ``get_status``, ``delete`` and ``analytics`` take the template + ``id`` (UUID). To find a template by name, use ``list(name=...)``. + """ + + def create(self, request: CreateTemplateRequest) -> TemplateResponse: + """POST /v1/templates — creates and submits a template for approval.""" return self._http.request( - "POST", "/v1/templates", + "POST", + _TEMPLATES, response_model=TemplateResponse, - json=request.model_dump(by_alias=True) + json=request.model_dump(mode="json", by_alias=True, exclude_none=True), ) async def create_async(self, request: CreateTemplateRequest) -> TemplateResponse: - """Creates a new message template asynchronously. - - Args: - request: The template creation data. - - Returns: - The created template details. - """ + """POST /v1/templates — asynchronous create.""" return await self._http.arequest( - "POST", "/v1/templates", + "POST", + _TEMPLATES, response_model=TemplateResponse, - json=request.model_dump(by_alias=True) + json=request.model_dump(mode="json", by_alias=True, exclude_none=True), ) - def list(self, name: Optional[str] = None) -> List[TemplateResponse]: - """Lists available message templates synchronously. - - Args: - name: Optional filter by template name. - - Returns: - A list of templates. - """ - params = {"name": name} if name else None - response = self._http.request("GET", "/v1/templates", params=params) - return [TemplateResponse.model_validate(item) for item in response] - - async def list_async(self, name: Optional[str] = None) -> List[TemplateResponse]: - """Lists available message templates asynchronously. - - Args: - name: Optional filter by template name. + def list( + self, + name: Optional[str] = None, + status: Optional[str] = None, + page: int = 0, + size: int = DEFAULT_TEMPLATE_PAGE_SIZE, + ) -> TemplatePage: + """GET /v1/templates — one page ``{data, pagination}`` of templates.""" + return self._http.request( + "GET", + _TEMPLATES, + response_model=TemplatePage, + params=_list_params(name, status, page, size), + ) - Returns: - A list of templates. - """ - params = {"name": name} if name else None - response = await self._http.arequest("GET", "/v1/templates", params=params) - return [TemplateResponse.model_validate(item) for item in response] + async def list_async( + self, + name: Optional[str] = None, + status: Optional[str] = None, + page: int = 0, + size: int = DEFAULT_TEMPLATE_PAGE_SIZE, + ) -> TemplatePage: + """GET /v1/templates — one page of templates, asynchronously.""" + return await self._http.arequest( + "GET", + _TEMPLATES, + response_model=TemplatePage, + params=_list_params(name, status, page, size), + ) def get(self, template_id: UUID) -> TemplateResponse: - """Retrieves details of a specific template synchronously. - - Args: - template_id: The unique ID of the template. - - Returns: - The template details. - """ + """GET /v1/templates/{id} — template details.""" return self._http.request( - "GET", f"/v1/templates/{template_id}", - response_model=TemplateResponse + "GET", f"{_TEMPLATES}/{template_id}", response_model=TemplateResponse ) async def get_async(self, template_id: UUID) -> TemplateResponse: - """Retrieves details of a specific template asynchronously. - - Args: - template_id: The unique ID of the template. - - Returns: - The template details. - """ + """GET /v1/templates/{id} — template details, asynchronously.""" return await self._http.arequest( - "GET", f"/v1/templates/{template_id}", - response_model=TemplateResponse + "GET", f"{_TEMPLATES}/{template_id}", response_model=TemplateResponse ) def delete(self, template_id: UUID) -> None: - """Deletes a message template synchronously. - - Args: - template_id: The unique ID of the template to delete. - """ - self._http.request("DELETE", f"/v1/templates/{template_id}") + """DELETE /v1/templates/{id} — deletes on Meta and locally.""" + self._http.request("DELETE", f"{_TEMPLATES}/{template_id}") async def delete_async(self, template_id: UUID) -> None: - """Deletes a message template asynchronously. - - Args: - template_id: The unique ID of the template to delete. - """ - await self._http.arequest("DELETE", f"/v1/templates/{template_id}") + """DELETE /v1/templates/{id} — asynchronous delete.""" + await self._http.arequest("DELETE", f"{_TEMPLATES}/{template_id}") def get_status(self, template_id: UUID) -> TemplateStatusResponse: - """Checks the status of a template synchronously. - - Args: - template_id: The unique ID of the template. - - Returns: - The current approval status of the template. - """ + """GET /v1/templates/{id}/status — approval status.""" return self._http.request( - "GET", f"/v1/templates/{template_id}/status", - response_model=TemplateStatusResponse + "GET", + f"{_TEMPLATES}/{template_id}/status", + response_model=TemplateStatusResponse, ) async def get_status_async(self, template_id: UUID) -> TemplateStatusResponse: - """Checks the status of a template asynchronously. + """GET /v1/templates/{id}/status — approval status, asynchronously.""" + return await self._http.arequest( + "GET", + f"{_TEMPLATES}/{template_id}/status", + response_model=TemplateStatusResponse, + ) - Args: - template_id: The unique ID of the template. + def analytics( + self, template_id: UUID, period: str = DEFAULT_ANALYTICS_PERIOD + ) -> Dict[str, Any]: + """GET /v1/templates/{id}/analytics — delivery and read stats.""" + return self._http.request( + "GET", f"{_TEMPLATES}/{template_id}/analytics", params={"period": period} + ) - Returns: - The current approval status of the template. - """ + async def analytics_async( + self, template_id: UUID, period: str = DEFAULT_ANALYTICS_PERIOD + ) -> Dict[str, Any]: + """GET /v1/templates/{id}/analytics — stats, asynchronously.""" return await self._http.arequest( - "GET", f"/v1/templates/{template_id}/status", - response_model=TemplateStatusResponse + "GET", f"{_TEMPLATES}/{template_id}/analytics", params={"period": period} ) diff --git a/tests/unit/resources/test_smart_link.py b/tests/unit/resources/test_smart_link.py new file mode 100644 index 0000000..9737b6a --- /dev/null +++ b/tests/unit/resources/test_smart_link.py @@ -0,0 +1,61 @@ +from uuid import uuid4 + +import httpx +import pytest + +BASE = "https://api.arara.test/v1/smart-links/whatsapp" + + +def link(): + """Build a WhatsAppSmartLinkResponse body.""" + return { + "id": str(uuid4()), + "name": "Loja", + "phoneNumber": "5511987654321", + "qrCodeColor": "BLACK", + "code": "abc", + "shortUrl": "https://ararahq.com/l/abc", + } + + +def test_list_smart_links_returns_paginated_page(arara_client, respx_mock): + """Test that list() parses {data, pagination}.""" + route = respx_mock.get(BASE).mock( + return_value=httpx.Response( + 200, + json={ + "data": [link()], + "pagination": { + "page": 0, + "size": 50, + "totalElements": 1, + "totalPages": 1, + }, + }, + ) + ) + + page = arara_client.smart_links.list() + + assert page.data[0].code == "abc" + assert page.pagination.total_pages == 1 + assert route.calls[0].request.url.params["size"] == "50" + + +@pytest.mark.asyncio +async def test_list_smart_links_async(arara_client, respx_mock): + """Test the async list path.""" + respx_mock.get(BASE).mock( + return_value=httpx.Response( + 200, + json={ + "data": [], + "pagination": {"page": 3, "size": 1, "totalElements": 0, "totalPages": 0}, + }, + ) + ) + + page = await arara_client.smart_links.list_async(page=3, size=1) + + assert page.data == [] + assert page.pagination.page == 3 diff --git a/tests/unit/resources/test_template.py b/tests/unit/resources/test_template.py index 2f6d21a..2c053fb 100644 --- a/tests/unit/resources/test_template.py +++ b/tests/unit/resources/test_template.py @@ -1,66 +1,158 @@ -import pytest -import respx -import httpx +import json from uuid import uuid4 + +import httpx +import pytest + from arara_api_sdk.models.template import CreateTemplateRequest, TemplateResponse -def test_list_templates_success(arara_client, respx_mock): - """Test successful template listing.""" - # Arrange - response_data = [ - { - "id": str(uuid4()), - "name": "welcome_msg", - "formattedName": "welcome_msg", - "category": "UTILITY", - "language": "pt_BR", - "providerName": "TWILIO", - "providerTemplateId": "HX...", - "providerStatus": "APPROVED", - "structureJson": {"body": "Welcome!"}, - "createdAt": "2023-10-27T10:00:00Z" - } - ] - respx_mock.get("https://api.arara.test/v1/templates").mock(return_value=httpx.Response(200, json=response_data)) - - # Act - templates = arara_client.templates.list() - - # Assert - assert len(templates) == 1 - assert templates[0].name == "welcome_msg" - assert isinstance(templates[0], TemplateResponse) - -def test_create_template_payload_mapping(arara_client, respx_mock): - """Test that CreateTemplateRequest maps correctly to the request body.""" - # Arrange - request = CreateTemplateRequest( - name="test_template", - category="MARKETING", - language="pt_BR", - structure_json={"body": "Hello {{1}}"} - ) - respx_mock.post("https://api.arara.test/v1/templates").mock(return_value=httpx.Response(201, json={ +BASE = "https://api.arara.test/v1/templates" + + +def template_payload(name="welcome_msg", status="APPROVED"): + """Build a TemplateResponse body as the API returns it.""" + return { "id": str(uuid4()), - "name": "test_template", - "formattedName": "test_template", - "category": "MARKETING", + "name": name, + "formattedName": name, + "category": "UTILITY", "language": "pt_BR", - "providerName": "TWILIO", - "providerTemplateId": "HX...", - "providerStatus": "PENDING", - "structureJson": {"body": "Hello {{1}}"}, - "createdAt": "2023-10-27T10:00:00Z" - })) - - # Act - arara_client.templates.create(request) - - # Assert - last_request = respx_mock.calls[0].request - assert last_request.method == "POST" - # Testing camelCase mapping in the body - import json - body = json.loads(last_request.content) - assert "structureJson" in body - assert body["structureJson"] == {"body": "Hello {{1}}"} + "providerName": "GUPSHUP", + "providerTemplateId": "gs-1", + "providerStatus": status, + "availableForSending": True, + "structureJson": {"body": "Welcome!"}, + "createdAt": "2026-09-24T10:00:00Z", + } + + +def page_of(items, page=0, size=50): + """Wrap items in the {data, pagination} envelope.""" + return { + "data": items, + "pagination": { + "page": page, + "size": size, + "totalElements": len(items), + "totalPages": 1, + }, + } + + +def test_list_templates_returns_paginated_page(arara_client, respx_mock): + """Test that list() parses {data, pagination} instead of iterating the dict.""" + route = respx_mock.get(BASE).mock( + return_value=httpx.Response(200, json=page_of([template_payload()])) + ) + + page = arara_client.templates.list(name="welcome_msg", status="APPROVED") + + assert len(page.data) == 1 + assert isinstance(page.data[0], TemplateResponse) + assert page.data[0].name == "welcome_msg" + assert page.pagination.total_elements == 1 + params = route.calls[0].request.url.params + assert params["name"] == "welcome_msg" + assert params["status"] == "APPROVED" + assert params["page"] == "0" + assert params["size"] == "50" + + +@pytest.mark.asyncio +async def test_list_templates_async_returns_paginated_page(arara_client, respx_mock): + """Test the async list path with default params.""" + route = respx_mock.get(BASE).mock( + return_value=httpx.Response(200, json=page_of([], page=2, size=10)) + ) + + page = await arara_client.templates.list_async(page=2, size=10) + + assert page.data == [] + assert page.pagination.page == 2 + assert "name" not in route.calls[0].request.url.params + + +def test_create_template_sends_body_not_structure_json(arara_client, respx_mock): + """Test that create() sends the fields the API validates (body is required).""" + route = respx_mock.post(BASE).mock( + return_value=httpx.Response(201, json=template_payload("pedido")) + ) + request = CreateTemplateRequest( + name="pedido", + category="UTILITY", + body="Ola {{1}}, seu pedido saiu.", + footer="Arara", + samples={"1": "Ana"}, + buttons=[{"type": "URL", "text": "Rastrear", "url": "https://x.y/{{1}}"}], + ) + + created = arara_client.templates.create(request) + + body = json.loads(route.calls[0].request.content) + assert body["body"] == "Ola {{1}}, seu pedido saiu." + assert body["language"] == "pt_BR" + assert body["samples"] == {"1": "Ana"} + assert body["buttons"][0]["type"] == "URL" + assert "structureJson" not in body + assert "headerType" not in body + assert created.name == "pedido" + + +@pytest.mark.asyncio +async def test_create_template_async(arara_client, respx_mock): + """Test the async create path.""" + respx_mock.post(BASE).mock( + return_value=httpx.Response(201, json=template_payload("x")) + ) + + created = await arara_client.templates.create_async( + CreateTemplateRequest(name="x", category="UTILITY", body="Oi") + ) + + assert created.name == "x" + + +def test_template_get_status_delete_and_analytics_use_id(arara_client, respx_mock): + """Test that get/get_status/delete/analytics address the template by UUID.""" + template_id = uuid4() + respx_mock.get(f"{BASE}/{template_id}").mock( + return_value=httpx.Response(200, json=template_payload()) + ) + respx_mock.get(f"{BASE}/{template_id}/status").mock( + return_value=httpx.Response(200, json={"status": "APPROVED"}) + ) + delete_route = respx_mock.delete(f"{BASE}/{template_id}").mock( + return_value=httpx.Response(204) + ) + analytics_route = respx_mock.get(f"{BASE}/{template_id}/analytics").mock( + return_value=httpx.Response(200, json={"sent": 10}) + ) + + assert arara_client.templates.get(template_id).name == "welcome_msg" + assert arara_client.templates.get_status(template_id).status == "APPROVED" + assert arara_client.templates.delete(template_id) is None + assert arara_client.templates.analytics(template_id, period="7d") == {"sent": 10} + assert delete_route.call_count == 1 + assert analytics_route.calls[0].request.url.params["period"] == "7d" + + +@pytest.mark.asyncio +async def test_template_async_by_id_paths(arara_client, respx_mock): + """Test the async get/get_status/delete/analytics paths.""" + template_id = uuid4() + respx_mock.get(f"{BASE}/{template_id}").mock( + return_value=httpx.Response(200, json=template_payload()) + ) + respx_mock.get(f"{BASE}/{template_id}/status").mock( + return_value=httpx.Response(200, json={"status": "PENDING"}) + ) + respx_mock.delete(f"{BASE}/{template_id}").mock(return_value=httpx.Response(204)) + respx_mock.get(f"{BASE}/{template_id}/analytics").mock( + return_value=httpx.Response(200, json={"read": 3}) + ) + + assert (await arara_client.templates.get_async(template_id)).name == "welcome_msg" + status = await arara_client.templates.get_status_async(template_id) + assert status.status == "PENDING" + assert await arara_client.templates.delete_async(template_id) is None + assert await arara_client.templates.analytics_async(template_id) == {"read": 3} From 664e702a2739e8fd373824d7dd86dc89117f0ab1 Mon Sep 17 00:00:00 2001 From: Micael Marques Date: Thu, 24 Sep 2026 16:01:26 -0300 Subject: [PATCH 05/13] feat(messages): send idempotency key always, add batch and campaign list/get/cancel --- arara_api_sdk/models/campaign.py | 80 ++++++- arara_api_sdk/models/message.py | 100 +++++++-- arara_api_sdk/resources/__init__.py | 19 +- arara_api_sdk/resources/campaign.py | 108 +++++++-- arara_api_sdk/resources/contact.py | 2 +- arara_api_sdk/resources/conversation.py | 2 +- arara_api_sdk/resources/message.py | 117 ++++++---- arara_api_sdk/resources/number.py | 2 +- arara_api_sdk/resources/wallet.py | 2 +- tests/unit/resources/test_campaign.py | 158 +++++++++++++ tests/unit/resources/test_message.py | 285 ++++++++++++++++++++---- 11 files changed, 726 insertions(+), 149 deletions(-) create mode 100644 tests/unit/resources/test_campaign.py diff --git a/arara_api_sdk/models/campaign.py b/arara_api_sdk/models/campaign.py index 665710c..88f69e6 100644 --- a/arara_api_sdk/models/campaign.py +++ b/arara_api_sdk/models/campaign.py @@ -1,30 +1,92 @@ -from typing import List, Optional -from pydantic import BaseModel, Field -from uuid import UUID +from datetime import datetime from decimal import Decimal +from typing import Any, Dict, List, Optional +from uuid import UUID + +from pydantic import BaseModel, ConfigDict, Field + class CampaignContactRequest(BaseModel): - """Request model for a contact in a campaign.""" + """A campaign recipient (``to`` accepts the same formats as ``receiver``).""" + to: str variables: List[str] = [] + class CampaignRequest(BaseModel): """Request model for creating a campaign.""" + + model_config = ConfigDict(populate_by_name=True) + name: str template_name: str = Field(..., alias="templateName") sender: Optional[str] = None contacts: List[CampaignContactRequest] + scheduled_at: Optional[datetime] = Field(None, alias="scheduledAt") + ab_test: Optional[Dict[str, Any]] = Field(None, alias="abTest") - class Config: - populate_by_name = True class CampaignResponse(BaseModel): - """Response model for a campaign.""" + """Response model for a created campaign.""" + + model_config = ConfigDict(populate_by_name=True) + id: UUID name: str status: str total_messages: int = Field(..., alias="totalMessages") total_cost: Decimal = Field(..., alias="totalCost") + scheduled_at: Optional[datetime] = Field(None, alias="scheduledAt") + + +class CampaignListItem(BaseModel): + """A campaign row in ``GET /v1/campaigns``.""" + + model_config = ConfigDict(populate_by_name=True) + + id: UUID + name: str + status: str + template_name: str = Field(..., alias="templateName") + total_messages: int = Field(..., alias="totalMessages") + sent_count: int = Field(0, alias="sentCount") + delivered_count: int = Field(0, alias="deliveredCount") + read_count: int = Field(0, alias="readCount") + failed_count: int = Field(0, alias="failedCount") + total_cost: Decimal = Field(..., alias="totalCost") + scheduled_at: Optional[datetime] = Field(None, alias="scheduledAt") + created_at: Optional[datetime] = Field(None, alias="createdAt") + + +class CampaignBlockReason(BaseModel): + """Why part of the audience was blocked, and how many contacts.""" + + motivo: str + quantidade: int + + +class CampaignDetailResponse(CampaignListItem): + """``GET /v1/campaigns/{id}``: counters, refunds and timeline.""" + + template_body: Optional[str] = Field(None, alias="templateBody") + clicked_count: int = Field(0, alias="clickedCount") + converted_count: int = Field(0, alias="convertedCount") + converted_value: Decimal = Field(Decimal(0), alias="convertedValue") + reply_count: int = Field(0, alias="replyCount") + holdout_count: int = Field(0, alias="holdoutCount") + blocked_count: int = Field(0, alias="blockedCount") + block_reasons: List[CampaignBlockReason] = Field([], alias="blockReasons") + refund_count: int = Field(0, alias="refundCount") + refund_value: Decimal = Field(Decimal(0), alias="refundValue") + started_at: Optional[datetime] = Field(None, alias="startedAt") + finished_at: Optional[datetime] = Field(None, alias="finishedAt") + + +class CampaignListResponse(BaseModel): + """``GET /v1/campaigns``: ``{content, totalPages, totalElements}``.""" + + model_config = ConfigDict(populate_by_name=True) - class Config: - populate_by_name = True + content: List[CampaignListItem] + total_pages: int = Field(..., alias="totalPages") + total_elements: int = Field(..., alias="totalElements") diff --git a/arara_api_sdk/models/message.py b/arara_api_sdk/models/message.py index 1c6b3c3..46f446c 100644 --- a/arara_api_sdk/models/message.py +++ b/arara_api_sdk/models/message.py @@ -1,10 +1,33 @@ -from typing import Optional, List -from pydantic import BaseModel, Field, field_validator from datetime import datetime from decimal import Decimal +from typing import List, Optional + +from pydantic import BaseModel, ConfigDict, Field, field_validator + +MAX_BATCH_SIZE = 1000 +FORBIDDEN_VARIABLE_CHARS = ("\n", "\r", "\t") + + +def _check_variables(values: Optional[List[str]]) -> Optional[List[str]]: + """Reject variables with newlines or tabs, which WhatsApp refuses.""" + if not values: + return values + for item in values: + if any(char in item for char in FORBIDDEN_VARIABLE_CHARS): + raise ValueError("Variables cannot contain newlines or tabs") + return values + class SendMessageRequest(BaseModel): - """Request model for sending a message.""" + """Request model for sending a message. + + ``receiver`` accepts ``whatsapp:+55...``, ``+55...`` or digits only; the + API normalizes and validates it. ``media_url`` is deprecated (the API drops + it on 2027-01-01); send header media as ``variables[0]``. + """ + + model_config = ConfigDict(populate_by_name=True) + receiver: str sender: Optional[str] = None template_name: Optional[str] = Field(None, alias="templateName") @@ -12,31 +35,72 @@ class SendMessageRequest(BaseModel): smart_link_param: Optional[str] = Field(None, alias="smartLinkParam") smart_link_url: Optional[str] = Field(None, alias="smartLinkUrl") body: Optional[str] = None - media_url: Optional[str] = Field(None, alias="media_url") # Deprecated: use variables[0] for header media + reply_to: Optional[str] = Field(None, alias="replyTo") + media_url: Optional[str] = Field(None, alias="media_url") scheduled_at: Optional[datetime] = Field(None, alias="scheduled_at") - mode: Optional[str] = None # LIVE or TEST - - class Config: - populate_by_name = True + mode: Optional[str] = None @field_validator("template_variables") @classmethod - def validate_variables(cls, v): - if v: - for item in v: - if any(c in item for c in ["\n", "\r", "\t"]): - raise ValueError("Variables cannot contain newlines or tabs") - return v + def validate_variables(cls, value: Optional[List[str]]) -> Optional[List[str]]: + """Reject variables with newlines or tabs.""" + return _check_variables(value) + class MessageResponse(BaseModel): - """Response model for a sent message.""" + """A message as returned by ``POST /v1/messages`` and ``GET /v1/messages/{id}``. + + ``cost`` is null in TEST mode, for scheduled messages and when pricing + could not be computed up front. + """ + + model_config = ConfigDict(populate_by_name=True) + id: str status: str mode: str sender: Optional[str] = None receiver: str body: Optional[str] = None - cost: Decimal + cost: Optional[Decimal] = None + reason: Optional[str] = None + + +class BatchMessageItem(BaseModel): + """One recipient of a batch send.""" - class Config: - populate_by_name = True + model_config = ConfigDict(populate_by_name=True) + + receiver: str + variables: Optional[List[str]] = None + sender: Optional[str] = None + + @field_validator("variables") + @classmethod + def validate_variables(cls, value: Optional[List[str]]) -> Optional[List[str]]: + """Reject variables with newlines or tabs.""" + return _check_variables(value) + + +class BatchMessageRequest(BaseModel): + """``POST /v1/messages/batch``: same template to up to 1000 recipients.""" + + model_config = ConfigDict(populate_by_name=True) + + template_name: str = Field(..., alias="templateName") + messages: List[BatchMessageItem] = Field( + ..., min_length=1, max_length=MAX_BATCH_SIZE + ) + + +class BatchMessageResponse(BaseModel): + """Result of a batch send.""" + + model_config = ConfigDict(populate_by_name=True) + + batch_id: str = Field(..., alias="batchId") + template_name: Optional[str] = Field(None, alias="templateName") + total: int + accepted: int + total_cost: Optional[Decimal] = Field(None, alias="totalCost") + messages: List[MessageResponse] = [] diff --git a/arara_api_sdk/resources/__init__.py b/arara_api_sdk/resources/__init__.py index d585221..0ab633a 100644 --- a/arara_api_sdk/resources/__init__.py +++ b/arara_api_sdk/resources/__init__.py @@ -1,7 +1,22 @@ -from typing import Optional -from arara_api_sdk.http.client import HttpClient +from typing import Dict, Optional +from uuid import uuid4 + +from arara_api_sdk.http.client import IDEMPOTENCY_HEADER, HttpClient + class BaseResource: """Base class for all API resources.""" + def __init__(self, http_client: HttpClient): + """Keep the shared HTTP client.""" self._http = http_client + + +def idempotency_headers(idempotency_key: Optional[str]) -> Dict[str, str]: + """Return the Idempotency-Key header, generating a UUID v4 when absent. + + The key is created once per SDK call and travels unchanged on every retry + of that call, so a timeout after the API accepted the request does not + send (and bill) the message twice. + """ + return {IDEMPOTENCY_HEADER: idempotency_key or str(uuid4())} diff --git a/arara_api_sdk/resources/campaign.py b/arara_api_sdk/resources/campaign.py index d1e53cb..d09323a 100644 --- a/arara_api_sdk/resources/campaign.py +++ b/arara_api_sdk/resources/campaign.py @@ -1,35 +1,97 @@ -from arara_api_sdk.resources import BaseResource -from arara_api_sdk.models.campaign import CampaignRequest, CampaignResponse +from typing import Any, Dict, Optional +from uuid import UUID + +from arara_api_sdk.models.campaign import ( + CampaignDetailResponse, + CampaignListResponse, + CampaignRequest, + CampaignResponse, +) +from arara_api_sdk.resources import BaseResource, idempotency_headers + +_CAMPAIGNS = "/v1/campaigns" +DEFAULT_CAMPAIGN_PAGE_SIZE = 20 -class CampaignResource(BaseResource): - """Resource for managing marketing campaigns.""" - def create(self, request: CampaignRequest) -> CampaignResponse: - """Starts a new marketing campaign synchronously. +def _list_params(page: int, size: int, status: Optional[str]) -> Dict[str, Any]: + """Build the query string of ``GET /v1/campaigns``.""" + params: Dict[str, Any] = {"page": page, "size": size} + if status: + params["status"] = status + return params - Args: - request: The campaign details and recipients. - Returns: - The created campaign summary. - """ +class CampaignResource(BaseResource): + """Resource for campaigns (template sent to a contact list).""" + + def create( + self, request: CampaignRequest, idempotency_key: Optional[str] = None + ) -> CampaignResponse: + """POST /v1/campaigns — creates a campaign, always with an Idempotency-Key.""" return self._http.request( - "POST", "/v1/campaigns", + "POST", + _CAMPAIGNS, response_model=CampaignResponse, - json=request.model_dump(by_alias=True) + json=request.model_dump(mode="json", by_alias=True, exclude_none=True), + headers=idempotency_headers(idempotency_key), ) - async def create_async(self, request: CampaignRequest) -> CampaignResponse: - """Starts a new marketing campaign asynchronously. + async def create_async( + self, request: CampaignRequest, idempotency_key: Optional[str] = None + ) -> CampaignResponse: + """POST /v1/campaigns — asynchronous create.""" + return await self._http.arequest( + "POST", + _CAMPAIGNS, + response_model=CampaignResponse, + json=request.model_dump(mode="json", by_alias=True, exclude_none=True), + headers=idempotency_headers(idempotency_key), + ) - Args: - request: The campaign details and recipients. + def list( + self, + page: int = 0, + size: int = DEFAULT_CAMPAIGN_PAGE_SIZE, + status: Optional[str] = None, + ) -> CampaignListResponse: + """GET /v1/campaigns — one page of campaigns.""" + return self._http.request( + "GET", + _CAMPAIGNS, + response_model=CampaignListResponse, + params=_list_params(page, size, status), + ) - Returns: - The created campaign summary. - """ + async def list_async( + self, + page: int = 0, + size: int = DEFAULT_CAMPAIGN_PAGE_SIZE, + status: Optional[str] = None, + ) -> CampaignListResponse: + """GET /v1/campaigns — one page of campaigns, asynchronously.""" return await self._http.arequest( - "POST", "/v1/campaigns", - response_model=CampaignResponse, - json=request.model_dump(by_alias=True) + "GET", + _CAMPAIGNS, + response_model=CampaignListResponse, + params=_list_params(page, size, status), ) + + def get(self, campaign_id: UUID) -> CampaignDetailResponse: + """GET /v1/campaigns/{id} — campaign detail.""" + return self._http.request( + "GET", f"{_CAMPAIGNS}/{campaign_id}", response_model=CampaignDetailResponse + ) + + async def get_async(self, campaign_id: UUID) -> CampaignDetailResponse: + """GET /v1/campaigns/{id} — campaign detail, asynchronously.""" + return await self._http.arequest( + "GET", f"{_CAMPAIGNS}/{campaign_id}", response_model=CampaignDetailResponse + ) + + def cancel(self, campaign_id: UUID) -> None: + """POST /v1/campaigns/{id}/cancel — stops a scheduled or running campaign.""" + self._http.request("POST", f"{_CAMPAIGNS}/{campaign_id}/cancel") + + async def cancel_async(self, campaign_id: UUID) -> None: + """POST /v1/campaigns/{id}/cancel — asynchronous cancel.""" + await self._http.arequest("POST", f"{_CAMPAIGNS}/{campaign_id}/cancel") diff --git a/arara_api_sdk/resources/contact.py b/arara_api_sdk/resources/contact.py index db4d64e..ff6c156 100644 --- a/arara_api_sdk/resources/contact.py +++ b/arara_api_sdk/resources/contact.py @@ -1,6 +1,5 @@ from typing import Any, Dict, List, Optional -from arara_api_sdk.resources import BaseResource from arara_api_sdk.models.contact import ( ContactMessagesResponse, ContactPatchRequest, @@ -11,6 +10,7 @@ ContactsReactivationResponse, ContactsStatsResponse, ) +from arara_api_sdk.resources import BaseResource _BASE = "/v1/contacts" diff --git a/arara_api_sdk/resources/conversation.py b/arara_api_sdk/resources/conversation.py index 09f8e74..4d6caa8 100644 --- a/arara_api_sdk/resources/conversation.py +++ b/arara_api_sdk/resources/conversation.py @@ -1,7 +1,7 @@ from typing import Any, Dict, List, Optional -from arara_api_sdk.resources import BaseResource from arara_api_sdk.models.conversation import ConversationReplyRequest +from arara_api_sdk.resources import BaseResource _BASE = "/v1/conversations" diff --git a/arara_api_sdk/resources/message.py b/arara_api_sdk/resources/message.py index 42358a4..4592844 100644 --- a/arara_api_sdk/resources/message.py +++ b/arara_api_sdk/resources/message.py @@ -1,64 +1,93 @@ -from typing import Optional -from arara_api_sdk.resources import BaseResource -from arara_api_sdk.models.message import SendMessageRequest, MessageResponse +from typing import List, Optional -class MessageResource(BaseResource): - """Resource for managing messages.""" +from arara_api_sdk.models.message import ( + BatchMessageRequest, + BatchMessageResponse, + MessageResponse, + SendMessageRequest, +) +from arara_api_sdk.resources import BaseResource, idempotency_headers + +_MESSAGES = "/v1/messages" +_BATCH = "/v1/messages/batch" - def send(self, request: SendMessageRequest) -> MessageResponse: - """Sends a message synchronously. - Args: - request: The message data including receiver and body/template. +class MessageResource(BaseResource): + """Resource for sending and reading messages. + + Every send carries an ``Idempotency-Key``. Pass your own to dedupe across + processes (e.g. your order id); otherwise the SDK generates one per call + and reuses it on retries. + """ - Returns: - The API response containing message status and ID. - """ + def send( + self, request: SendMessageRequest, idempotency_key: Optional[str] = None + ) -> MessageResponse: + """POST /v1/messages — sends a message synchronously.""" return self._http.request( - "POST", "/v1/messages", - response_model=MessageResponse, - json=request.model_dump(by_alias=True, exclude_none=True) + "POST", + _MESSAGES, + response_model=MessageResponse, + json=request.model_dump(mode="json", by_alias=True, exclude_none=True), + headers=idempotency_headers(idempotency_key), ) - async def send_async(self, request: SendMessageRequest) -> MessageResponse: - """Sends a message asynchronously. + async def send_async( + self, request: SendMessageRequest, idempotency_key: Optional[str] = None + ) -> MessageResponse: + """POST /v1/messages — sends a message asynchronously.""" + return await self._http.arequest( + "POST", + _MESSAGES, + response_model=MessageResponse, + json=request.model_dump(mode="json", by_alias=True, exclude_none=True), + headers=idempotency_headers(idempotency_key), + ) - Args: - request: The message data including receiver and body/template. + def send_batch( + self, request: BatchMessageRequest, idempotency_key: Optional[str] = None + ) -> BatchMessageResponse: + """POST /v1/messages/batch — one template to up to 1000 recipients.""" + return self._http.request( + "POST", + _BATCH, + response_model=BatchMessageResponse, + json=request.model_dump(mode="json", by_alias=True, exclude_none=True), + headers=idempotency_headers(idempotency_key), + ) - Returns: - The API response containing message status and ID. - """ + async def send_batch_async( + self, request: BatchMessageRequest, idempotency_key: Optional[str] = None + ) -> BatchMessageResponse: + """POST /v1/messages/batch — asynchronous batch send.""" return await self._http.arequest( - "POST", "/v1/messages", - response_model=MessageResponse, - json=request.model_dump(by_alias=True, exclude_none=True) + "POST", + _BATCH, + response_model=BatchMessageResponse, + json=request.model_dump(mode="json", by_alias=True, exclude_none=True), + headers=idempotency_headers(idempotency_key), ) def get(self, internal_id: str) -> MessageResponse: - """Retrieves message details synchronously. - - Args: - internal_id: The Arara internal ID of the message. - - Returns: - The message details. - """ + """GET /v1/messages/{id} — message details synchronously.""" return self._http.request( - "GET", f"/v1/messages/{internal_id}", - response_model=MessageResponse + "GET", f"{_MESSAGES}/{internal_id}", response_model=MessageResponse ) async def get_async(self, internal_id: str) -> MessageResponse: - """Retrieves message details asynchronously. + """GET /v1/messages/{id} — message details asynchronously.""" + return await self._http.arequest( + "GET", f"{_MESSAGES}/{internal_id}", response_model=MessageResponse + ) - Args: - internal_id: The Arara internal ID of the message. + def list_by_batch(self, batch_id: str) -> List[MessageResponse]: + """GET /v1/messages?batchId= — every message of a batch.""" + response = self._http.request("GET", _MESSAGES, params={"batchId": batch_id}) + return [MessageResponse.model_validate(item) for item in response] - Returns: - The message details. - """ - return await self._http.arequest( - "GET", f"/v1/messages/{internal_id}", - response_model=MessageResponse + async def list_by_batch_async(self, batch_id: str) -> List[MessageResponse]: + """GET /v1/messages?batchId= — every message of a batch, asynchronously.""" + response = await self._http.arequest( + "GET", _MESSAGES, params={"batchId": batch_id} ) + return [MessageResponse.model_validate(item) for item in response] diff --git a/arara_api_sdk/resources/number.py b/arara_api_sdk/resources/number.py index 37a37bc..90b36d2 100644 --- a/arara_api_sdk/resources/number.py +++ b/arara_api_sdk/resources/number.py @@ -1,11 +1,11 @@ from typing import Any, Dict, List -from arara_api_sdk.resources import BaseResource from arara_api_sdk.models.number import ( NumbersResponseDTO, RequestNumberRequest, UpdateNumberRequest, ) +from arara_api_sdk.resources import BaseResource _BASE = "/v1/organizations/me/numbers" diff --git a/arara_api_sdk/resources/wallet.py b/arara_api_sdk/resources/wallet.py index 8308525..4a94bba 100644 --- a/arara_api_sdk/resources/wallet.py +++ b/arara_api_sdk/resources/wallet.py @@ -1,9 +1,9 @@ -from arara_api_sdk.resources import BaseResource from arara_api_sdk.models.wallet import ( AutoRechargeSettingsDTO, UpdateAutoRechargeRequest, WalletTransactionPageDTO, ) +from arara_api_sdk.resources import BaseResource class WalletResource(BaseResource): diff --git a/tests/unit/resources/test_campaign.py b/tests/unit/resources/test_campaign.py new file mode 100644 index 0000000..97201b2 --- /dev/null +++ b/tests/unit/resources/test_campaign.py @@ -0,0 +1,158 @@ +import json +from uuid import uuid4 + +import httpx +import pytest + +from arara_api_sdk.models.campaign import CampaignContactRequest, CampaignRequest + +CAMPAIGNS = "https://api.arara.test/v1/campaigns" +CAMPAIGN_ID = uuid4() + + +def created(): + """Build a CampaignResponse body.""" + return { + "id": str(CAMPAIGN_ID), + "name": "Black Friday", + "status": "PROCESSING", + "totalMessages": 2, + "totalCost": "0.10", + } + + +def list_item(): + """Build a CampaignListItem body.""" + return { + **created(), + "templateName": "promo", + "sentCount": 2, + "deliveredCount": 1, + "readCount": 0, + "failedCount": 0, + "scheduledAt": None, + "createdAt": "2026-09-24T10:00:00Z", + } + + +def request(): + """Build a campaign request.""" + return CampaignRequest( + name="Black Friday", + template_name="promo", + contacts=[CampaignContactRequest(to="+5511987654321", variables=["Ana"])], + ) + + +def test_create_campaign_sends_generated_key_and_reuses_it_on_retry( + arara_client, respx_mock +): + """Test that create always sends a key and a retry after 5xx keeps it.""" + arara_client._http._retry_config["sleep"] = lambda seconds: None + route = respx_mock.post(CAMPAIGNS).mock( + side_effect=[httpx.Response(502), httpx.Response(200, json=created())] + ) + + campaign = arara_client.campaigns.create(request()) + + keys = [call.request.headers["Idempotency-Key"] for call in route.calls] + assert len(keys) == 2 + assert keys[0] == keys[1] + assert campaign.id == CAMPAIGN_ID + body = json.loads(route.calls[0].request.content) + assert body["templateName"] == "promo" + assert body["contacts"] == [{"to": "+5511987654321", "variables": ["Ana"]}] + assert "scheduledAt" not in body + + +@pytest.mark.asyncio +async def test_create_campaign_async_uses_caller_key_and_schedule( + arara_client, respx_mock +): + """Test that the caller key and scheduledAt are sent.""" + route = respx_mock.post(CAMPAIGNS).mock( + return_value=httpx.Response(200, json=created()) + ) + scheduled = CampaignRequest( + name="Agendada", + template_name="promo", + contacts=[CampaignContactRequest(to="11987654321")], + scheduled_at="2026-12-01T12:00:00Z", + ) + + await arara_client.campaigns.create_async(scheduled, idempotency_key="camp-1") + + assert route.calls[0].request.headers["Idempotency-Key"] == "camp-1" + body = json.loads(route.calls[0].request.content) + assert body["scheduledAt"].startswith("2026-12-01T12:00:00") + + +def test_list_campaigns_parses_content_page(arara_client, respx_mock): + """Test that list() parses {content, totalPages, totalElements}.""" + route = respx_mock.get(CAMPAIGNS).mock( + return_value=httpx.Response( + 200, json={"content": [list_item()], "totalPages": 1, "totalElements": 1} + ) + ) + + page = arara_client.campaigns.list(status="COMPLETED") + + assert page.total_elements == 1 + assert page.content[0].template_name == "promo" + assert route.calls[0].request.url.params["status"] == "COMPLETED" + + +@pytest.mark.asyncio +async def test_list_campaigns_async_without_status(arara_client, respx_mock): + """Test the async list omits status when not given.""" + route = respx_mock.get(CAMPAIGNS).mock( + return_value=httpx.Response( + 200, json={"content": [], "totalPages": 0, "totalElements": 0} + ) + ) + + page = await arara_client.campaigns.list_async(page=1, size=5) + + assert page.content == [] + params = route.calls[0].request.url.params + assert "status" not in params + assert params["size"] == "5" + + +def test_get_and_cancel_campaign(arara_client, respx_mock): + """Test detail parsing and cancel with an empty 200 body.""" + detail = { + **list_item(), + "clickedCount": 0, + "convertedCount": 0, + "convertedValue": "0", + "blockReasons": [{"motivo": "Opt-out", "quantidade": 1}], + "startedAt": None, + "finishedAt": None, + } + respx_mock.get(f"{CAMPAIGNS}/{CAMPAIGN_ID}").mock( + return_value=httpx.Response(200, json=detail) + ) + cancel = respx_mock.post(f"{CAMPAIGNS}/{CAMPAIGN_ID}/cancel").mock( + return_value=httpx.Response(200) + ) + + campaign = arara_client.campaigns.get(CAMPAIGN_ID) + + assert campaign.block_reasons[0].quantidade == 1 + assert arara_client.campaigns.cancel(CAMPAIGN_ID) is None + assert cancel.call_count == 1 + + +@pytest.mark.asyncio +async def test_get_and_cancel_campaign_async(arara_client, respx_mock): + """Test the async get and cancel paths.""" + respx_mock.get(f"{CAMPAIGNS}/{CAMPAIGN_ID}").mock( + return_value=httpx.Response(200, json=list_item()) + ) + respx_mock.post(f"{CAMPAIGNS}/{CAMPAIGN_ID}/cancel").mock( + return_value=httpx.Response(200) + ) + + assert (await arara_client.campaigns.get_async(CAMPAIGN_ID)).name == "Black Friday" + assert await arara_client.campaigns.cancel_async(CAMPAIGN_ID) is None diff --git a/tests/unit/resources/test_message.py b/tests/unit/resources/test_message.py index e9fd617..428ec18 100644 --- a/tests/unit/resources/test_message.py +++ b/tests/unit/resources/test_message.py @@ -1,61 +1,248 @@ -import pytest -import respx -import httpx +import json from decimal import Decimal -from arara_api_sdk.models.message import SendMessageRequest, MessageResponse -from arara_api_sdk.exceptions import AraraResourceNotFoundError -def test_send_message_success(arara_client, respx_mock): - """Test successful message sending.""" - # Arrange - request = SendMessageRequest(receiver="whatsapp:+5511987654321", body="Hello") - response_data = { +import httpx +import pytest +from pydantic import ValidationError + +from arara_api_sdk.exceptions import AraraResourceNotFoundError, AraraServerError +from arara_api_sdk.models.message import ( + BatchMessageItem, + BatchMessageRequest, + MessageResponse, + SendMessageRequest, +) + +MESSAGES = "https://api.arara.test/v1/messages" +BATCH = "https://api.arara.test/v1/messages/batch" + + +def accepted(cost="0.05", **extra): + """Build a MessageResponse body.""" + body = { "id": "msg_123", - "status": "SENT", + "status": "QUEUED", "mode": "LIVE", - "receiver": "whatsapp:+5511987654321", - "body": "Hello", - "cost": "0.05" + "receiver": "5511987654321", + "cost": cost, } - respx_mock.post("https://api.arara.test/v1/messages").mock(return_value=httpx.Response(201, json=response_data)) - - # Act - response = arara_client.messages.send(request) - - # Assert + body.update(extra) + return body + + +@pytest.fixture +def no_sleep(arara_client): + """Skip real backoff sleeps in retry tests.""" + arara_client._http._retry_config["sleep"] = lambda seconds: None + + +def test_send_message_success(arara_client, respx_mock): + """Test successful message sending.""" + respx_mock.post(MESSAGES).mock(return_value=httpx.Response(202, json=accepted())) + + response = arara_client.messages.send( + SendMessageRequest(receiver="+5511987654321", body="Hello") + ) + assert isinstance(response, MessageResponse) - assert response.id == "msg_123" - assert response.status == "SENT" assert response.cost == Decimal("0.05") + +def test_send_message_accepts_null_cost_and_reason(arara_client, respx_mock): + """Test that a null cost (TEST mode, scheduled) does not raise after acceptance.""" + respx_mock.post(MESSAGES).mock( + return_value=httpx.Response( + 202, json=accepted(cost=None, mode="TEST", reason="scheduled") + ) + ) + + response = arara_client.messages.send( + SendMessageRequest(receiver="11987654321", body="Hi", mode="TEST") + ) + + assert response.cost is None + assert response.reason == "scheduled" + + +def test_send_message_always_sends_generated_idempotency_key(arara_client, respx_mock): + """Test that each send without a caller key gets its own UUID v4 key.""" + route = respx_mock.post(MESSAGES).mock( + return_value=httpx.Response(202, json=accepted()) + ) + request = SendMessageRequest(receiver="+5511987654321", body="Hi") + + arara_client.messages.send(request) + arara_client.messages.send(request) + + keys = [call.request.headers["Idempotency-Key"] for call in route.calls] + assert len(keys[0]) == 36 + assert keys[0] != keys[1] + + +def test_send_message_retry_after_5xx_reuses_same_key( + arara_client, respx_mock, no_sleep +): + """Test that a retry after a 5xx sends the same Idempotency-Key.""" + route = respx_mock.post(MESSAGES).mock( + side_effect=[httpx.Response(503), httpx.Response(202, json=accepted())] + ) + + arara_client.messages.send(SendMessageRequest(receiver="+5511987654321", body="Hi")) + + keys = [call.request.headers["Idempotency-Key"] for call in route.calls] + assert route.call_count == 2 + assert keys[0] == keys[1] + + +def test_send_message_uses_caller_idempotency_key(arara_client, respx_mock): + """Test that a caller-supplied key is sent as is.""" + route = respx_mock.post(MESSAGES).mock( + return_value=httpx.Response(202, json=accepted()) + ) + + arara_client.messages.send( + SendMessageRequest(receiver="+5511987654321", body="Hi"), + idempotency_key="order-42", + ) + + assert route.calls[0].request.headers["Idempotency-Key"] == "order-42" + + +@pytest.mark.asyncio +async def test_send_message_async_retry_reuses_caller_key(arara_client, respx_mock): + """Test the async send: retries keep the caller key.""" + + async def no_async_sleep(seconds): + return None + + arara_client._http._retry_config["sleep"] = no_async_sleep + route = respx_mock.post(MESSAGES).mock( + side_effect=[httpx.Response(500), httpx.Response(202, json=accepted())] + ) + + response = await arara_client.messages.send_async( + SendMessageRequest(receiver="+5511987654321", body="Hi"), + idempotency_key="k-async", + ) + + assert response.id == "msg_123" + keys = [call.request.headers["Idempotency-Key"] for call in route.calls] + assert keys == ["k-async", "k-async"] + + +def test_send_message_raises_after_retries_exhausted( + arara_client, respx_mock, no_sleep +): + """Test that persistent 5xx surfaces a server error.""" + respx_mock.post(MESSAGES).mock(return_value=httpx.Response(500)) + + with pytest.raises(AraraServerError): + arara_client.messages.send(SendMessageRequest(receiver="1", body="x")) + + +def test_send_message_serializes_scheduled_at(arara_client, respx_mock): + """Test that scheduled_at is sent as ISO-8601 under the snake_case key.""" + route = respx_mock.post(MESSAGES).mock( + return_value=httpx.Response(202, json=accepted(cost=None)) + ) + + arara_client.messages.send( + SendMessageRequest( + receiver="1", + template_name="t", + template_variables=["a"], + scheduled_at="2026-12-25T10:00:00Z", + ) + ) + + body = json.loads(route.calls[0].request.content) + assert body["scheduled_at"].startswith("2026-12-25T10:00:00") + assert body["variables"] == ["a"] + assert body["templateName"] == "t" + + +def test_variables_reject_newlines(): + """Test that variables with newlines are rejected locally.""" + with pytest.raises(ValidationError): + SendMessageRequest(receiver="1", template_variables=["a\nb"]) + with pytest.raises(ValidationError): + BatchMessageItem(receiver="1", variables=["a\tb"]) + + +def test_batch_rejects_more_than_1000_messages(): + """Test that the batch limit is enforced before the request.""" + items = [BatchMessageItem(receiver=str(i)) for i in range(1001)] + with pytest.raises(ValidationError): + BatchMessageRequest(template_name="t", messages=items) + + +def test_send_batch_posts_items_with_idempotency_key(arara_client, respx_mock): + """Test that send_batch posts the template and items with a key.""" + route = respx_mock.post(BATCH).mock( + return_value=httpx.Response( + 202, + json={ + "batchId": "b-1", + "templateName": "t", + "total": 1, + "accepted": 1, + "totalCost": "0.05", + "messages": [accepted()], + }, + ) + ) + + result = arara_client.messages.send_batch( + BatchMessageRequest( + template_name="t", + messages=[BatchMessageItem(receiver="1", variables=["Ana"])], + ) + ) + + body = json.loads(route.calls[0].request.content) + assert body == {"templateName": "t", "messages": [{"receiver": "1", "variables": ["Ana"]}]} + assert route.calls[0].request.headers["Idempotency-Key"] + assert result.batch_id == "b-1" + assert result.messages[0].id == "msg_123" + + +@pytest.mark.asyncio +async def test_send_batch_async_and_list_by_batch(arara_client, respx_mock): + """Test async batch send and the batch listing paths.""" + respx_mock.post(BATCH).mock( + return_value=httpx.Response( + 202, json={"batchId": "b-2", "total": 1, "accepted": 0, "messages": []} + ) + ) + list_route = respx_mock.get(MESSAGES).mock( + return_value=httpx.Response(200, json=[accepted()]) + ) + request = BatchMessageRequest( + template_name="t", messages=[BatchMessageItem(receiver="1")] + ) + + result = await arara_client.messages.send_batch_async(request, "k-b") + listed_sync = arara_client.messages.list_by_batch("b-2") + listed_async = await arara_client.messages.list_by_batch_async("b-2") + + assert result.batch_id == "b-2" + assert listed_sync[0].id == listed_async[0].id == "msg_123" + assert list_route.calls[0].request.url.params["batchId"] == "b-2" + + def test_get_message_not_found_raises_exception(arara_client, respx_mock): - """Test that getting a non-existent message raises AraraResourceNotFoundError.""" - # Arrange - internal_id = "non_existent" - respx_mock.get(f"https://api.arara.test/v1/messages/{internal_id}").mock(return_value=httpx.Response(404, json={"error": "Not Found"})) - - # Act & Assert + """Test that a 404 with empty body raises AraraResourceNotFoundError.""" + respx_mock.get(f"{MESSAGES}/missing").mock(return_value=httpx.Response(404)) + with pytest.raises(AraraResourceNotFoundError): - arara_client.messages.get(internal_id) + arara_client.messages.get("missing") + @pytest.mark.asyncio -async def test_send_message_async_success(arara_client, respx_mock): - """Test successful asynchronous message sending.""" - # Arrange - request = SendMessageRequest(receiver="whatsapp:+5511987654321", body="Hello Async") - response_data = { - "id": "msg_async_123", - "status": "QUEUED", - "mode": "LIVE", - "receiver": "whatsapp:+5511987654321", - "body": "Hello Async", - "cost": "0.00" - } - respx_mock.post("https://api.arara.test/v1/messages").mock(return_value=httpx.Response(201, json=response_data)) - - # Act - response = await arara_client.messages.send_async(request) - - # Assert - assert response.id == "msg_async_123" - assert response.mode == "LIVE" +async def test_get_message_async(arara_client, respx_mock): + """Test the async get path.""" + respx_mock.get(f"{MESSAGES}/msg_123").mock( + return_value=httpx.Response(200, json=accepted()) + ) + + assert (await arara_client.messages.get_async("msg_123")).id == "msg_123" From ecb342857e38ef5be71e25ee6c5ea1d4d61852c1 Mon Sep 17 00:00:00 2001 From: Micael Marques Date: Thu, 24 Sep 2026 16:06:14 -0300 Subject: [PATCH 06/13] chore(ci): publish to pypi on push to main via trusted publishing --- .github/workflows/ci.yml | 24 +++++++++++ .github/workflows/pypi-publish.yml | 64 +++++++++++++++++++++++++++--- 2 files changed, 83 insertions(+), 5 deletions(-) create mode 100644 .github/workflows/ci.yml diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..ce0a1ae --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,24 @@ +name: CI + +on: + pull_request: + branches: [main] + +permissions: + contents: read + +jobs: + check: + runs-on: ubuntu-latest + strategy: + matrix: + python-version: ['3.9', '3.12'] + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python-version }} + - run: python -m pip install -e '.[test]' ruff build + - run: ruff check arara_api_sdk + - run: python -m pytest + - run: python -m build diff --git a/.github/workflows/pypi-publish.yml b/.github/workflows/pypi-publish.yml index df42794..c7aad0d 100644 --- a/.github/workflows/pypi-publish.yml +++ b/.github/workflows/pypi-publish.yml @@ -1,20 +1,74 @@ name: Publish to PyPI on: - release: - types: [published] + push: + branches: [main] workflow_dispatch: +concurrency: + group: pypi-publish + cancel-in-progress: false + jobs: + build: + runs-on: ubuntu-latest + permissions: + contents: read + outputs: + publish: ${{ steps.version.outputs.publish }} + version: ${{ steps.version.outputs.version }} + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - run: python -m pip install -e '.[test]' ruff build + - run: ruff check arara_api_sdk + - run: python -m pytest + - run: python -m build + + - name: Resolve version + id: version + run: | + NAME=$(python -c "import tomllib; print(tomllib.load(open('pyproject.toml','rb'))['project']['name'])") + LOCAL=$(python -c "import tomllib; print(tomllib.load(open('pyproject.toml','rb'))['project']['version'])") + STATUS=$(curl -s -o /dev/null -w '%{http_code}' "https://pypi.org/pypi/$NAME/$LOCAL/json") + if [ "$STATUS" = "200" ]; then + echo "publish=false" >> "$GITHUB_OUTPUT" + echo "::notice::$NAME $LOCAL ja existe no PyPI, nada a publicar" + else + echo "publish=true" >> "$GITHUB_OUTPUT" + fi + echo "version=$LOCAL" >> "$GITHUB_OUTPUT" + + - uses: actions/upload-artifact@v4 + if: steps.version.outputs.publish == 'true' + with: + name: dist + path: dist/ + publish: + needs: build + if: needs.build.outputs.publish == 'true' runs-on: ubuntu-latest environment: pypi permissions: + contents: write id-token: write steps: - uses: actions/checkout@v4 - - uses: actions/setup-python@v5 + - uses: actions/download-artifact@v4 with: - python-version: '3.12' - - run: python -m pip install build && python -m build + name: dist + path: dist/ + - uses: pypa/gh-action-pypi-publish@release/v1 + + - name: Tag and release + env: + GH_TOKEN: ${{ github.token }} + TAG: v${{ needs.build.outputs.version }} + run: | + git tag "$TAG" + git push origin "$TAG" + gh release create "$TAG" dist/* --title "$TAG" --generate-notes From 04ddcf5c2bea5cf9225385aa12a5e58c4166a9f8 Mon Sep 17 00:00:00 2001 From: Micael Marques Date: Thu, 24 Sep 2026 16:06:14 -0300 Subject: [PATCH 07/13] chore(release): bump to 2.0.0 with changelog --- .gitignore | 1 + CHANGELOG.md | 29 +++++++ README.md | 206 ++++++++++++++++++++++--------------------------- pyproject.toml | 18 +---- 4 files changed, 125 insertions(+), 129 deletions(-) create mode 100644 CHANGELOG.md diff --git a/.gitignore b/.gitignore index 5a5899f..d1af6e4 100644 --- a/.gitignore +++ b/.gitignore @@ -144,3 +144,4 @@ cython_debug/ # PyCharm .idea/ +.DS_Store diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..4754113 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,29 @@ +# Changelog + +## 2.0.0 - 2026-09-24 + +Alinha o SDK ao contrato real da API por chave. Versão major porque remove recursos e muda retornos. + +### Quebras +- Removidos `payments`, `brain`, `organizations`, `users` e `api_keys`: nenhum deles é alcançável por API key (403 ou rota inexistente). +- `templates.list()` e `smart_links.list()` devolvem `Page` (`data` + `pagination`) em vez de lista; aceitam `page`/`size` (e `name`/`status` em templates). +- `CreateTemplateRequest` manda `body` (obrigatório), `header`, `headerType`, `footer`, `buttons`, `samples`, `variableExamples` e `carouselCards`. `structure_json` saiu (a API ignorava e respondia 400). +- 403 com código de negócio levanta `AraraForbiddenError` (ou `AraraPlanFeatureLockedError` para `PLAN_FEATURE_LOCKED`, com `feature`, `current_plan`, `upgrade_to`); 403 sem código e 401 levantam `AraraAuthError`; 422 levanta `AraraUnprocessableError`. +- POST/PATCH sem `Idempotency-Key` não são mais repetidos em timeout, erro de conexão, 5xx ou 429. + +### Novo +- `auth.me()` (`GET /auth/me`, exige chave ADMIN). +- `messages.send` e `campaigns.create` sempre enviam `Idempotency-Key`: a do caller (`idempotency_key=`) ou um UUID v4 gerado por chamada e reaproveitado em todos os retries. +- `messages.send_batch` (até 1000 destinatários) e `messages.list_by_batch`. +- `campaigns.list`, `campaigns.get`, `campaigns.cancel`; `CampaignRequest` aceita `scheduled_at` e `ab_test`. +- `templates.analytics(id, period)`. +- `opt_outs` (`list`, `create`, `get`, `delete`). +- Todo erro expõe `status_code`, `code`, `message`, `details` e `retry_after`. + +### Correções +- `MessageResponse.cost` é opcional (nulo em TEST, agendada ou sem pré-cálculo) e ganhou `reason`. Antes o SDK lançava depois de a API já ter aceitado o envio. +- Resposta 200 sem corpo (ex.: cancelar campanha) devolve `None` em vez de quebrar no parse. +- Configuração e modelos sem APIs obsoletas do pydantic (`class Config`, `Field(env=...)`). + +### Publicação +- Publica no PyPI a cada push na `main` via Trusted Publishing quando a versão do `pyproject.toml` ainda não existe, e cria a tag `vX.Y.Z` com release no GitHub. diff --git a/README.md b/README.md index 5c67c47..825b740 100644 --- a/README.md +++ b/README.md @@ -5,177 +5,157 @@ [![License](https://img.shields.io/badge/License-MIT-green)](LICENSE) [![Docs](https://img.shields.io/badge/Docs-docs.ararahq.com-orange)](https://docs.ararahq.com) -O SDK oficial da [AraraHQ](https://ararahq.com) para Python. Esta biblioteca permite integrar facilmente as funcionalidades de mensageria (WhatsApp), gestão de templates, inteligência artificial (Brain), campanhas e pagamentos diretamente no seu aplicativo ou servidor. +SDK oficial da [AraraHQ](https://ararahq.com) para Python: envio de WhatsApp, templates, campanhas, contatos, conversas, números, opt-outs, smart links e carteira, com chamadas síncronas e assíncronas. ---- - -## 🚀 Destaques (Features) - -- **Suporte Nativo a Async/Sync**: Escolha entre operações bloqueantes ou assíncronas (`httpx` baseado). -- **Type Safety**: Utiliza **Pydantic V2** para validação rigorosa de dados e suporte total a autocompletar em IDEs. -- **Resiliência**: Lógica de **Retries** automática com backoff exponencial integrada. -- **Tratamento de Erros Profissional**: Hierarquia de exceções clara para cada status HTTP relevante. -- **Arquitetura Modular**: Recursos organizados por domínio (Messages, Templates, Brain, etc). - ---- - -## 📦 Instalação +## Instalação ```bash pip install ararahq-sdk ``` -> **Nota:** Requer Python 3.8 ou superior. - ---- +Requer Python 3.8 ou superior. -## 🔑 Autenticação +## Autenticação -A autenticação é feita via **Bearer API Key**. Você pode obter sua chave no painel da Arara. - -O SDK busca automaticamente a variável de ambiente `ARARA_API_KEY` caso nenhuma chave seja passada no construtor. +Autenticação por API key (`Bearer ara_live_...`), criada no painel da Arara. Sem chave no construtor, o SDK lê `ARARA_API_KEY`. ```bash export ARARA_API_KEY="ara_live_..." ``` ---- - -## 🛠️ Uso Rápido (Quick Start) +Algumas áreas exigem chave com permissão **ADMIN**: `contacts`, `conversations`, `wallet` e `auth.me()`. Com chave sem essa permissão a API responde 403 e o SDK levanta `AraraAuthError`. -### Modo Síncrono (Standard) -Ideal para scripts simples ou servidores que não utilizam async/await. +## Uso rápido ```python from arara_api_sdk import AraraClient from arara_api_sdk.models.message import SendMessageRequest -# O uso de Context Manager garante que os recursos sejam fechados corretamente -with AraraClient(api_key="your_api_key") as client: - request = SendMessageRequest( - receiver="whatsapp:+5511987654321", - body="Hello World from Arara SDK!", - media_url="https://ararahq.com/l/FtFmja" # Opcional: Anexo +with AraraClient() as client: + response = client.messages.send( + SendMessageRequest( + receiver="+5511987654321", + template_name="pedido_enviado", + template_variables=["Ana"], + ), + idempotency_key="pedido-4521", ) - response = client.messages.send(request) - print(f"Message ID: {response.id} | Status: {response.status}") + print(response.id, response.status, response.cost) ``` -### Modo Assíncrono (High Performance) -Recomendado para aplicações FastAPI, aiohttp ou volumes massivos de dados. +`receiver` aceita `whatsapp:+5511...`, `+5511...` ou só dígitos. `cost` pode vir `None` (modo TEST, mensagem agendada). + +Assíncrono: ```python import asyncio from arara_api_sdk import AraraClient from arara_api_sdk.models.message import SendMessageRequest -async def send_bulk(): +async def main(): async with AraraClient() as client: - request = SendMessageRequest( - receiver="whatsapp:+5511987654321", - template_name="welcome_message", - template_variables=["Amos"], - scheduled_at="2024-12-25T10:00:00Z" # Opcional: Agendamento ISO8601 + response = await client.messages.send_async( + SendMessageRequest(receiver="+5511987654321", body="Oi!") ) - response = await client.messages.send_async(request) - print(f"Async Sent: {response.id}") + print(response.id) -asyncio.run(send_bulk()) +asyncio.run(main()) ``` ---- +## Idempotência e retries -## 📂 Visão Geral dos Módulos +`messages.send`, `messages.send_batch` e `campaigns.create` sempre mandam `Idempotency-Key`. Se você não passar `idempotency_key`, o SDK gera um UUID v4 por chamada e usa a mesma chave em todas as tentativas daquela chamada: um timeout depois de a API aceitar não vira envio duplicado. -### 💬 Mensagens (Messages) -Envio de mensagens de texto simples ou baseadas em templates aprovados. -```python -client.messages.send(request) -client.messages.get(message_id) -``` +Timeout, erro de conexão, 5xx e 429 são repetidos até `max_retries` (backoff exponencial, ou o `Retry-After` do 429). GET, PUT e DELETE repetem livremente; POST e PATCH só repetem quando levam `Idempotency-Key`. -### 📝 Templates -Gestão completa do ciclo de vida de modelos de mensagem do WhatsApp. -```python -client.templates.list() -client.templates.create(create_request) -client.templates.get_status(template_id) -``` +## Recursos -### 🧠 AI Brain -Interface direta com o motor de Inteligência Artificial da Arara. ```python -response = client.brain.prompt(BrainRequest(prompt="Como configurar meu webhook?")) -print(response.text) -``` +client.auth.me() # GET /auth/me (ADMIN) -### 🏢 Organizações & Webhooks -Gestão de membros, números de telefone e configuração de webhooks de recebimento. -```python -webhook = client.organizations.get_webhook() -members = client.organizations.list_members() -``` +client.messages.send(request, idempotency_key=None) +client.messages.send_batch(batch_request) # até 1000 destinatários +client.messages.get(message_id) +client.messages.list_by_batch(batch_id) ---- +page = client.templates.list(name=None, status=None, page=0, size=50) +page.data, page.pagination.total_pages +client.templates.create(CreateTemplateRequest(name=..., category="UTILITY", body="Olá {{1}}", samples={"1": "Ana"})) +client.templates.get(template_id) # sempre pelo id (UUID) +client.templates.get_status(template_id) +client.templates.analytics(template_id, period="30d") +client.templates.delete(template_id) -## ⚙️ Configuração Avançada +client.campaigns.create(campaign_request, idempotency_key=None) +client.campaigns.list(page=0, size=20, status=None) # content, total_pages, total_elements +client.campaigns.get(campaign_id) +client.campaigns.cancel(campaign_id) -Você pode customizar o comportamento do HttpClient no momento da inicialização: +client.opt_outs.list() +client.opt_outs.create("+5511987654321", reason="pediu para sair") +client.opt_outs.get("+5511987654321") +client.opt_outs.delete("+5511987654321") -```python -client = AraraClient( - api_key="...", - timeout=60.0, # Custom timeout in seconds - max_retries=5, # Exponential backoff retries - base_url="https://..." # Custom API endpoint -) +client.smart_links.list(page=0, size=50) # Page com data e pagination +client.contacts, client.conversations, client.numbers, client.wallet ``` ---- +Para achar um template pelo nome, use `client.templates.list(name="...")` e pegue o `id` do resultado. + +Todo método tem a versão `_async` (`send_async`, `list_async`, ...). + +## Erros -## ⚠️ Tratamento de Erros (Error Handling) +Todo erro herda de `AraraError` e traz `status_code`, `code`, `message`, `details` e `retry_after`, lidos do envelope `{"error": {"code", "message", "details"}}`. -O SDK mapeia erros da API para exceções Python específicas: +| Situação | Exceção | +|---|---| +| 401, ou 403 sem código (chave inválida, expirada ou sem permissão) | `AraraAuthError` | +| 403 `PLAN_FEATURE_LOCKED` | `AraraPlanFeatureLockedError` (`feature`, `current_plan`, `upgrade_to`) | +| outro 403 com código (`PLAN_LIMIT_REACHED`, `ACCOUNT_NOT_ACTIVATED`...) | `AraraForbiddenError` | +| 400 | `AraraValidationError` | +| 404 | `AraraResourceNotFoundError` | +| 422 (`INVALID_RECIPIENT`, `RECIPIENT_OPTED_OUT`, `TEMPLATE_PAUSED`...) | `AraraUnprocessableError` | +| 429 | `AraraRateLimitError` | +| 5xx | `AraraServerError` | +| timeout / conexão | `AraraTimeoutError` / `AraraConnectionError` | ```python -from arara_api_sdk.exceptions import ( - AraraAuthError, - AraraValidationError, - AraraResourceNotFoundError -) +from arara_api_sdk import AraraPlanFeatureLockedError, AraraUnprocessableError try: - client.messages.send(request) -except AraraAuthError: - # Error 401 - pass -except AraraResourceNotFoundError: - # Error 404 - pass -except AraraValidationError as e: - # Error 400 - o envelope { "error": { "code", "message", "details" } } - # vem desempacotado em e.code, str(e) e e.details + client.campaigns.create(request) +except AraraPlanFeatureLockedError as e: + print(f"Disponível a partir do plano {e.upgrade_to}") +except AraraUnprocessableError as e: print(e.code, e.details) ``` -Erros 429 sao repetidos automaticamente respeitando o header `Retry-After` -(ou backoff exponencial, quando ausente), ate `max_retries`. Se o servidor -pedir uma espera maior que 60s, o SDK levanta `AraraRateLimitError` na hora -com `e.retry_after` preenchido, em vez de bloquear a chamada. +## Configuração ---- +```python +client = AraraClient( + api_key="...", + timeout=30.0, + max_retries=3, + base_url="https://api.ararahq.com", +) +``` -## 👩‍💻 Desenvolvimento e Testes +Também por variáveis de ambiente: `ARARA_API_KEY`, `ARARA_BASE_URL`, `ARARA_TIMEOUT`, `ARARA_MAX_RETRIES`. -Se você deseja contribuir ou rodar os testes localmente: +## Desenvolvimento -1. Crie um ambiente virtual: `python -m venv .venv` -2. Ative: `source .venv/bin/activate` -3. Instale as dependências: `pip install -e ".[test]"` -4. Rode os testes: `pytest tests/` +```bash +python -m venv .venv && source .venv/bin/activate +pip install -e ".[test]" ruff build +ruff check arara_api_sdk +python -m pytest +python -m build +``` ---- +Publicação: cada push na `main` publica no PyPI (Trusted Publishing) se a versão do `pyproject.toml` ainda não existir lá, e cria a tag e o release no GitHub. Ver `CHANGELOG.md`. -## 📄 Licença +## Licença -Distribuído sob a licença MIT. Veja `LICENSE` para mais informações. +MIT. Ver `LICENSE`. diff --git a/pyproject.toml b/pyproject.toml index ebd4738..dcda4f9 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "ararahq-sdk" -version = "1.8.1" +version = "2.0.0" description = "Official Python SDK for the Arara API" readme = "README.md" requires-python = ">=3.8" @@ -49,7 +49,7 @@ lint = [ ] [tool.hatch.build.targets.sdist] -exclude = ["/tests", "/.github", "/.gemini"] +exclude = ["/tests", "/.github", "/.gemini", "/.venv", "/htmlcov"] [tool.hatch.build.targets.wheel] packages = ["arara_api_sdk"] @@ -97,17 +97,3 @@ ignore_missing_imports = true "Homepage" = "https://github.com/ararahq/arara-python-sdk" "Bug Tracker" = "https://github.com/ararahq/arara-python-sdk/issues" -# Scripts para publicação (Comentados): -# -# 1. Instalar dependências de build: -# pip install hatch -# -# 2. Gerar arquivos de distribuição: -# hatch build -# -# 3. Publicar no PyPI: -# hatch publish -# -# 4. Publicar no GitHub Packages: -# (Requer configuração de autenticação no ~/.pypirc ou enviando tokens via ENV) -# hatch publish -r https://pypi.pkg.github.com/ararahq/arara-python-sdk From 7f8b860d401ccb10d0b9e39f5aedec194c2f56ed Mon Sep 17 00:00:00 2001 From: Micael Marques Date: Thu, 24 Sep 2026 17:40:23 -0300 Subject: [PATCH 08/13] fix(http): treat blank idempotency key as absent and split 403 into forbidden and api errors --- README.md | 9 +++--- arara_api_sdk/__init__.py | 2 ++ arara_api_sdk/exceptions.py | 18 ++++++++---- arara_api_sdk/http/client.py | 8 ++++-- tests/unit/test_http_client.py | 50 ++++++++++++++++++++++++++++++---- 5 files changed, 69 insertions(+), 18 deletions(-) diff --git a/README.md b/README.md index 825b740..eef11b3 100644 --- a/README.md +++ b/README.md @@ -23,7 +23,7 @@ Autenticação por API key (`Bearer ara_live_...`), criada no painel da Arara. S export ARARA_API_KEY="ara_live_..." ``` -Algumas áreas exigem chave com permissão **ADMIN**: `contacts`, `conversations`, `wallet` e `auth.me()`. Com chave sem essa permissão a API responde 403 e o SDK levanta `AraraAuthError`. +Algumas áreas exigem chave com permissão **ADMIN**: `contacts`, `conversations`, `wallet` e `auth.me()`. Com chave sem essa permissão a API responde 403 sem envelope e o SDK levanta `AraraForbiddenError` (a chave é válida, só não tem permissão). ## Uso rápido @@ -66,7 +66,7 @@ asyncio.run(main()) `messages.send`, `messages.send_batch` e `campaigns.create` sempre mandam `Idempotency-Key`. Se você não passar `idempotency_key`, o SDK gera um UUID v4 por chamada e usa a mesma chave em todas as tentativas daquela chamada: um timeout depois de a API aceitar não vira envio duplicado. -Timeout, erro de conexão, 5xx e 429 são repetidos até `max_retries` (backoff exponencial, ou o `Retry-After` do 429). GET, PUT e DELETE repetem livremente; POST e PATCH só repetem quando levam `Idempotency-Key`. +Timeout, erro de conexão, 5xx e 429 são repetidos até `max_retries` (backoff exponencial, ou o `Retry-After` do 429). GET, PUT e DELETE repetem livremente; POST e PATCH só repetem quando levam `Idempotency-Key` não vazia (chave só com espaços conta como ausente; nos métodos do SDK ela é trocada por um UUID gerado). ## Recursos @@ -110,9 +110,10 @@ Todo erro herda de `AraraError` e traz `status_code`, `code`, `message`, `detail | Situação | Exceção | |---|---| -| 401, ou 403 sem código (chave inválida, expirada ou sem permissão) | `AraraAuthError` | +| 401 | `AraraAuthError` | +| 403 sem envelope (corpo do Spring `{timestamp, status, error, path}` ou vazio): chave inválida, sem permissão (ex.: não ADMIN) ou rota fora da allowlist | `AraraForbiddenError` (mensagem = campo `error` do corpo) | | 403 `PLAN_FEATURE_LOCKED` | `AraraPlanFeatureLockedError` (`feature`, `current_plan`, `upgrade_to`) | -| outro 403 com código (`PLAN_LIMIT_REACHED`, `ACCOUNT_NOT_ACTIVATED`...) | `AraraForbiddenError` | +| 403 com outro código (`PLAN_LIMIT_REACHED`, `ACCOUNT_NOT_ACTIVATED`...) | `AraraApiError` (com `code`) | | 400 | `AraraValidationError` | | 404 | `AraraResourceNotFoundError` | | 422 (`INVALID_RECIPIENT`, `RECIPIENT_OPTED_OUT`, `TEMPLATE_PAUSED`...) | `AraraUnprocessableError` | diff --git a/arara_api_sdk/__init__.py b/arara_api_sdk/__init__.py index c335952..3f7bca8 100644 --- a/arara_api_sdk/__init__.py +++ b/arara_api_sdk/__init__.py @@ -1,5 +1,6 @@ from arara_api_sdk.client import AraraClient from arara_api_sdk.exceptions import ( + AraraApiError, AraraAuthError, AraraConnectionError, AraraError, @@ -17,6 +18,7 @@ "AraraClient", "AraraError", "AraraAuthError", + "AraraApiError", "AraraForbiddenError", "AraraPlanFeatureLockedError", "AraraValidationError", diff --git a/arara_api_sdk/exceptions.py b/arara_api_sdk/exceptions.py index d0baded..3d24b6c 100644 --- a/arara_api_sdk/exceptions.py +++ b/arara_api_sdk/exceptions.py @@ -29,18 +29,24 @@ def __init__( class AraraAuthError(AraraError): - """Raised when the API key is missing, invalid, expired or not allowed. + """Raised on 401: the API key is missing or invalid.""" - The backend answers key failures with 401 or with 403 without an error - code (the filter rejects the request before the envelope is built). + +class AraraForbiddenError(AraraError): + """Raised on 403 without an error envelope. + + The key filter rejects with the plain Spring body + ``{timestamp, status, error, path}`` (or empty) for an invalid key, a key + without the needed permission (e.g. not ADMIN) or a path outside the + allowlist. The body's ``error`` text becomes the message. """ -class AraraForbiddenError(AraraError): - """Raised on a business 403 that carries an error code.""" +class AraraApiError(AraraError): + """Raised on a business error with an envelope code, e.g. 403 PLAN_LIMIT_REACHED.""" -class AraraPlanFeatureLockedError(AraraForbiddenError): +class AraraPlanFeatureLockedError(AraraApiError): """Raised on 403 ``PLAN_FEATURE_LOCKED``: the plan does not include the feature.""" def __init__( diff --git a/arara_api_sdk/http/client.py b/arara_api_sdk/http/client.py index e8e6526..82f73ae 100644 --- a/arara_api_sdk/http/client.py +++ b/arara_api_sdk/http/client.py @@ -14,6 +14,7 @@ from arara_api_sdk._version import __version__ from arara_api_sdk.config import SDKConfig from arara_api_sdk.exceptions import ( + AraraApiError, AraraAuthError, AraraConnectionError, AraraError, @@ -95,7 +96,8 @@ def _retry_policy( """ if method.upper() in RETRY_SAFE_METHODS: return _should_retry - if headers and headers.get(IDEMPOTENCY_HEADER): + key = headers.get(IDEMPOTENCY_HEADER) if headers else None + if isinstance(key, str) and key.strip(): return _should_retry return _never_retry @@ -104,10 +106,10 @@ def _error_class(status_code: int, code: Optional[str]) -> Type[AraraError]: """Map status and envelope code to the exception type.""" if status_code == 403: if code is None: - return AraraAuthError + return AraraForbiddenError if code == PLAN_FEATURE_LOCKED: return AraraPlanFeatureLockedError - return AraraForbiddenError + return AraraApiError if 500 <= status_code < 600: return AraraServerError return _STATUS_ERRORS.get(status_code, AraraError) diff --git a/tests/unit/test_http_client.py b/tests/unit/test_http_client.py index ce371cb..7ef1f76 100644 --- a/tests/unit/test_http_client.py +++ b/tests/unit/test_http_client.py @@ -2,6 +2,7 @@ import pytest from arara_api_sdk.exceptions import ( + AraraApiError, AraraAuthError, AraraError, AraraForbiddenError, @@ -198,8 +199,9 @@ def test_http_client_extracts_code_message_and_details_from_envelope( ) # Act & Assert - with pytest.raises(AraraForbiddenError) as exc: + with pytest.raises(AraraApiError) as exc: http_client.request("GET", "/envelope") + assert not isinstance(exc.value, AraraForbiddenError) assert str(exc.value) == "Limite do plano atingido em 'numbers': 1/1." assert exc.value.message == "Limite do plano atingido em 'numbers': 1/1." assert exc.value.code == "PLAN_LIMIT_REACHED" @@ -277,17 +279,39 @@ def test_http_client_raises_plan_feature_locked_with_upgrade_details( assert exc.value.current_plan == "DECOLAGEM" assert exc.value.upgrade_to == "VOO" assert not isinstance(exc.value, AraraAuthError) + assert isinstance(exc.value, AraraApiError) + +def test_http_client_maps_spring_403_body_to_forbidden_not_auth( + http_client, respx_mock +): + """Test that the key filter's Spring 403 body is a forbidden error, not auth.""" + body = { + "timestamp": "2026-09-24T12:00:00.000+00:00", + "status": 403, + "error": "Forbidden", + "path": "/v1/contacts", + } + respx_mock.get("https://api.arara.test/v1/contacts").mock( + return_value=httpx.Response(403, json=body) + ) + + with pytest.raises(AraraForbiddenError) as exc: + http_client.request("GET", "/v1/contacts") + assert not isinstance(exc.value, AraraAuthError) + assert exc.value.status_code == 403 + assert exc.value.code is None + assert str(exc.value) == "Forbidden" -def test_http_client_treats_403_without_code_as_auth_error(http_client, respx_mock): - """Test that a bare 403 (key rejected by the filter) is an auth error.""" + +def test_http_client_maps_empty_403_to_forbidden(http_client, respx_mock): + """Test that a 403 with empty body (path outside allowlist) is forbidden.""" respx_mock.get("https://api.arara.test/bare-403").mock( return_value=httpx.Response(403) ) - with pytest.raises(AraraAuthError) as exc: + with pytest.raises(AraraForbiddenError) as exc: http_client.request("GET", "/bare-403") - assert exc.value.status_code == 403 assert exc.value.code is None @@ -355,3 +379,19 @@ def test_http_client_returns_none_for_empty_success_body(http_client, respx_mock ) assert http_client.request("POST", "/void") is None + + +@pytest.mark.parametrize("blank", ["", " ", "\t", " \n"]) +def test_http_client_does_not_retry_post_with_blank_idempotency_key( + http_client, respx_mock, recorded_sleeps, blank +): + """Test that a whitespace-only Idempotency-Key does not unlock POST retries.""" + route = respx_mock.post("https://api.arara.test/post-blank").mock( + return_value=httpx.Response(503) + ) + + with pytest.raises(AraraError): + http_client.request( + "POST", "/post-blank", json={}, headers={"Idempotency-Key": blank} + ) + assert route.call_count == 1 From 3e5894caa18ca651aa1d3ab2fc067327394b2114 Mon Sep 17 00:00:00 2001 From: Micael Marques Date: Thu, 24 Sep 2026 17:40:23 -0300 Subject: [PATCH 09/13] fix(messages): type batch items with nullable id and cost and regenerate blank keys --- arara_api_sdk/models/message.py | 11 +++++- arara_api_sdk/resources/__init__.py | 5 +-- tests/unit/resources/test_message.py | 50 ++++++++++++++++++++++++++-- 3 files changed, 61 insertions(+), 5 deletions(-) diff --git a/arara_api_sdk/models/message.py b/arara_api_sdk/models/message.py index 46f446c..59bfdee 100644 --- a/arara_api_sdk/models/message.py +++ b/arara_api_sdk/models/message.py @@ -93,6 +93,15 @@ class BatchMessageRequest(BaseModel): ) +class BatchMessageItemResponse(BaseModel): + """Per-recipient result of a batch; ``id`` and ``cost`` are null on failure.""" + + id: Optional[str] = None + receiver: str + status: str + cost: Optional[Decimal] = None + + class BatchMessageResponse(BaseModel): """Result of a batch send.""" @@ -103,4 +112,4 @@ class BatchMessageResponse(BaseModel): total: int accepted: int total_cost: Optional[Decimal] = Field(None, alias="totalCost") - messages: List[MessageResponse] = [] + messages: List[BatchMessageItemResponse] = [] diff --git a/arara_api_sdk/resources/__init__.py b/arara_api_sdk/resources/__init__.py index 0ab633a..0d30e6e 100644 --- a/arara_api_sdk/resources/__init__.py +++ b/arara_api_sdk/resources/__init__.py @@ -13,10 +13,11 @@ def __init__(self, http_client: HttpClient): def idempotency_headers(idempotency_key: Optional[str]) -> Dict[str, str]: - """Return the Idempotency-Key header, generating a UUID v4 when absent. + """Return the Idempotency-Key header, generating a UUID v4 when absent or blank. The key is created once per SDK call and travels unchanged on every retry of that call, so a timeout after the API accepted the request does not send (and bill) the message twice. """ - return {IDEMPOTENCY_HEADER: idempotency_key or str(uuid4())} + key = (idempotency_key or "").strip() or str(uuid4()) + return {IDEMPOTENCY_HEADER: key} diff --git a/tests/unit/resources/test_message.py b/tests/unit/resources/test_message.py index 428ec18..c2dc0fa 100644 --- a/tests/unit/resources/test_message.py +++ b/tests/unit/resources/test_message.py @@ -94,6 +94,35 @@ def test_send_message_retry_after_5xx_reuses_same_key( assert keys[0] == keys[1] +@pytest.mark.parametrize("blank", ["", " ", "\t"]) +def test_send_message_generates_key_when_caller_key_is_blank( + arara_client, respx_mock, blank +): + """Test that a blank caller key is replaced by a generated UUID v4.""" + route = respx_mock.post(MESSAGES).mock( + return_value=httpx.Response(202, json=accepted()) + ) + + arara_client.messages.send( + SendMessageRequest(receiver="1", body="Hi"), idempotency_key=blank + ) + + assert len(route.calls[0].request.headers["Idempotency-Key"]) == 36 + + +def test_send_message_strips_caller_key(arara_client, respx_mock): + """Test that surrounding whitespace is stripped from the caller key.""" + route = respx_mock.post(MESSAGES).mock( + return_value=httpx.Response(202, json=accepted()) + ) + + arara_client.messages.send( + SendMessageRequest(receiver="1", body="Hi"), idempotency_key=" order-7 " + ) + + assert route.calls[0].request.headers["Idempotency-Key"] == "order-7" + + def test_send_message_uses_caller_idempotency_key(arara_client, respx_mock): """Test that a caller-supplied key is sent as is.""" route = respx_mock.post(MESSAGES).mock( @@ -187,7 +216,10 @@ def test_send_batch_posts_items_with_idempotency_key(arara_client, respx_mock): "total": 1, "accepted": 1, "totalCost": "0.05", - "messages": [accepted()], + "messages": [ + {"id": "msg_123", "receiver": "1", "status": "QUEUED", "cost": "0.05"}, + {"id": None, "receiver": "2", "status": "FAILED", "cost": None}, + ], }, ) ) @@ -204,6 +236,9 @@ def test_send_batch_posts_items_with_idempotency_key(arara_client, respx_mock): assert route.calls[0].request.headers["Idempotency-Key"] assert result.batch_id == "b-1" assert result.messages[0].id == "msg_123" + assert result.messages[1].id is None + assert result.messages[1].status == "FAILED" + assert result.messages[1].cost is None @pytest.mark.asyncio @@ -211,7 +246,17 @@ async def test_send_batch_async_and_list_by_batch(arara_client, respx_mock): """Test async batch send and the batch listing paths.""" respx_mock.post(BATCH).mock( return_value=httpx.Response( - 202, json={"batchId": "b-2", "total": 1, "accepted": 0, "messages": []} + 202, + json={ + "batchId": "b-2", + "templateName": "t", + "total": 1, + "accepted": 0, + "totalCost": "0", + "messages": [ + {"id": None, "receiver": "1", "status": "FAILED", "cost": None} + ], + }, ) ) list_route = respx_mock.get(MESSAGES).mock( @@ -226,6 +271,7 @@ async def test_send_batch_async_and_list_by_batch(arara_client, respx_mock): listed_async = await arara_client.messages.list_by_batch_async("b-2") assert result.batch_id == "b-2" + assert result.messages[0].id is None assert listed_sync[0].id == listed_async[0].id == "msg_123" assert list_route.calls[0].request.url.params["batchId"] == "b-2" From 9c28a0a0069783c3ab2d7fba578860a29fa0c765 Mon Sep 17 00:00:00 2001 From: Micael Marques Date: Thu, 24 Sep 2026 17:40:23 -0300 Subject: [PATCH 10/13] fix(auth): mirror auth me response with email pending --- arara_api_sdk/models/auth.py | 11 +++++------ tests/unit/resources/test_auth_and_opt_out.py | 7 +++++-- 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/arara_api_sdk/models/auth.py b/arara_api_sdk/models/auth.py index 33def88..e15f9ac 100644 --- a/arara_api_sdk/models/auth.py +++ b/arara_api_sdk/models/auth.py @@ -6,14 +6,13 @@ class CurrentUserResponse(BaseModel): """``GET /auth/me``: the user that owns the API key. - Only the stable fields are typed; anything else the API returns is kept - as extra attributes. + Mirrors ``UserResponseDTO {name, email, role, emailPending}``; unknown + fields the API may add later are kept as extra attributes. """ model_config = ConfigDict(populate_by_name=True, extra="allow") - id: Optional[str] = None - name: Optional[str] = None - email: Optional[str] = None + name: str + email: str role: Optional[str] = None - organization_id: Optional[str] = Field(None, alias="organizationId") + email_pending: bool = Field(False, alias="emailPending") diff --git a/tests/unit/resources/test_auth_and_opt_out.py b/tests/unit/resources/test_auth_and_opt_out.py index 8f00bf2..0fa09ea 100644 --- a/tests/unit/resources/test_auth_and_opt_out.py +++ b/tests/unit/resources/test_auth_and_opt_out.py @@ -20,16 +20,19 @@ def test_auth_me_calls_auth_me_without_v1(arara_client, respx_mock): assert route.call_count == 1 assert me.name == "Ana" assert me.role == "ADMIN" + assert me.email_pending is False @pytest.mark.asyncio async def test_auth_me_async(arara_client, respx_mock): """Test the async auth.me path.""" respx_mock.get("https://api.arara.test/auth/me").mock( - return_value=httpx.Response(200, json={"name": "Ana", "email": "a@x.com"}) + return_value=httpx.Response(200, json={"name": "Ana", "email": "a@x.com", "role": None, "emailPending": True}) ) - assert (await arara_client.auth.me_async()).email == "a@x.com" + me = await arara_client.auth.me_async() + assert me.email == "a@x.com" + assert me.email_pending is True def test_removed_resources_are_gone(arara_client): From 2a966ddd6e7e4675471adcb8cbcda32edf3c3a32 Mon Sep 17 00:00:00 2001 From: Micael Marques Date: Thu, 24 Sep 2026 17:40:23 -0300 Subject: [PATCH 11/13] test(wallet): cover transactions page with the real dto body --- tests/unit/resources/test_wallet.py | 44 +++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 tests/unit/resources/test_wallet.py diff --git a/tests/unit/resources/test_wallet.py b/tests/unit/resources/test_wallet.py new file mode 100644 index 0000000..718b5a3 --- /dev/null +++ b/tests/unit/resources/test_wallet.py @@ -0,0 +1,44 @@ +import httpx +import pytest + +TX = "https://api.arara.test/v1/wallet/transactions" + +REAL_PAGE = { + "content": [ + { + "id": "tx-1", + "amount": "-0.05", + "type": "DEBIT", + "description": "Mensagem", + "referenceId": "msg_1", + "mode": "LIVE", + "createdAt": "2026-09-24T10:00:00Z", + } + ], + "page": 0, + "size": 20, + "totalElements": 1, + "totalPages": 1, +} + + +def test_wallet_transactions_parses_real_page_dto(arara_client, respx_mock): + """Test the WalletTransactionPageDTO body (content, page, size, totals).""" + route = respx_mock.get(TX).mock(return_value=httpx.Response(200, json=REAL_PAGE)) + + page = arara_client.wallet.transactions(page=0, size=20) + + assert page.content[0].reference_id == "msg_1" + assert page.total_elements == 1 + assert page.page == 0 + assert route.calls[0].request.url.params["size"] == "20" + + +@pytest.mark.asyncio +async def test_wallet_transactions_async(arara_client, respx_mock): + """Test the async transactions path.""" + respx_mock.get(TX).mock(return_value=httpx.Response(200, json=REAL_PAGE)) + + page = await arara_client.wallet.transactions_async() + + assert page.total_pages == 1 From d49736adfacbfaa3ab6f81dc62758a26c33ba3a7 Mon Sep 17 00:00:00 2001 From: Micael Marques Date: Thu, 24 Sep 2026 17:40:23 -0300 Subject: [PATCH 12/13] chore(ci): fail pypi gate on unexpected status and isolate oidc publish from release --- .github/workflows/pypi-publish.yml | 36 ++++++++++++++++++++++-------- 1 file changed, 27 insertions(+), 9 deletions(-) diff --git a/.github/workflows/pypi-publish.yml b/.github/workflows/pypi-publish.yml index c7aad0d..ca78eab 100644 --- a/.github/workflows/pypi-publish.yml +++ b/.github/workflows/pypi-publish.yml @@ -32,13 +32,20 @@ jobs: run: | NAME=$(python -c "import tomllib; print(tomllib.load(open('pyproject.toml','rb'))['project']['name'])") LOCAL=$(python -c "import tomllib; print(tomllib.load(open('pyproject.toml','rb'))['project']['version'])") - STATUS=$(curl -s -o /dev/null -w '%{http_code}' "https://pypi.org/pypi/$NAME/$LOCAL/json") - if [ "$STATUS" = "200" ]; then - echo "publish=false" >> "$GITHUB_OUTPUT" - echo "::notice::$NAME $LOCAL ja existe no PyPI, nada a publicar" - else - echo "publish=true" >> "$GITHUB_OUTPUT" - fi + STATUS=$(curl -s -o /dev/null -w '%{http_code}' --max-time 30 "https://pypi.org/pypi/$NAME/$LOCAL/json" || true) + case "$STATUS" in + 200) + echo "publish=false" >> "$GITHUB_OUTPUT" + echo "::notice::$NAME $LOCAL ja existe no PyPI, nada a publicar" + ;; + 404) + echo "publish=true" >> "$GITHUB_OUTPUT" + ;; + *) + echo "::error::PyPI respondeu HTTP $STATUS ao checar $NAME $LOCAL; abortando sem publicar" + exit 1 + ;; + esac echo "version=$LOCAL" >> "$GITHUB_OUTPUT" - uses: actions/upload-artifact@v4 @@ -53,10 +60,9 @@ jobs: runs-on: ubuntu-latest environment: pypi permissions: - contents: write + contents: read id-token: write steps: - - uses: actions/checkout@v4 - uses: actions/download-artifact@v4 with: name: dist @@ -64,6 +70,18 @@ jobs: - uses: pypa/gh-action-pypi-publish@release/v1 + release: + needs: [build, publish] + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - uses: actions/checkout@v4 + - uses: actions/download-artifact@v4 + with: + name: dist + path: dist/ + - name: Tag and release env: GH_TOKEN: ${{ github.token }} From 4af3d40457f93ccdad8d071aa7e9a6953b5ce4b2 Mon Sep 17 00:00:00 2001 From: Micael Marques Date: Thu, 24 Sep 2026 17:40:23 -0300 Subject: [PATCH 13/13] docs(changelog): describe error split, batch items and auth me fields --- CHANGELOG.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4754113..0b52278 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,13 +8,13 @@ Alinha o SDK ao contrato real da API por chave. Versão major porque remove recu - Removidos `payments`, `brain`, `organizations`, `users` e `api_keys`: nenhum deles é alcançável por API key (403 ou rota inexistente). - `templates.list()` e `smart_links.list()` devolvem `Page` (`data` + `pagination`) em vez de lista; aceitam `page`/`size` (e `name`/`status` em templates). - `CreateTemplateRequest` manda `body` (obrigatório), `header`, `headerType`, `footer`, `buttons`, `samples`, `variableExamples` e `carouselCards`. `structure_json` saiu (a API ignorava e respondia 400). -- 403 com código de negócio levanta `AraraForbiddenError` (ou `AraraPlanFeatureLockedError` para `PLAN_FEATURE_LOCKED`, com `feature`, `current_plan`, `upgrade_to`); 403 sem código e 401 levantam `AraraAuthError`; 422 levanta `AraraUnprocessableError`. +- 401 levanta `AraraAuthError`; 403 sem envelope (chave sem permissão, rota fora da allowlist) levanta `AraraForbiddenError`; 403 com código levanta `AraraApiError` (ou `AraraPlanFeatureLockedError` para `PLAN_FEATURE_LOCKED`, com `feature`, `current_plan`, `upgrade_to`); 422 levanta `AraraUnprocessableError`. - POST/PATCH sem `Idempotency-Key` não são mais repetidos em timeout, erro de conexão, 5xx ou 429. ### Novo -- `auth.me()` (`GET /auth/me`, exige chave ADMIN). +- `auth.me()` (`GET /auth/me`, exige chave ADMIN): `name`, `email`, `role`, `email_pending`. - `messages.send` e `campaigns.create` sempre enviam `Idempotency-Key`: a do caller (`idempotency_key=`) ou um UUID v4 gerado por chamada e reaproveitado em todos os retries. -- `messages.send_batch` (até 1000 destinatários) e `messages.list_by_batch`. +- `messages.send_batch` (até 1000 destinatários, resultado por item em `BatchMessageItemResponse`) e `messages.list_by_batch`. - `campaigns.list`, `campaigns.get`, `campaigns.cancel`; `CampaignRequest` aceita `scheduled_at` e `ab_test`. - `templates.analytics(id, period)`. - `opt_outs` (`list`, `create`, `get`, `delete`).