diff --git a/.github/workflows/maven-publish.yml b/.github/workflows/maven-publish.yml index e71b2f9..7190c68 100644 --- a/.github/workflows/maven-publish.yml +++ b/.github/workflows/maven-publish.yml @@ -4,8 +4,11 @@ on: push: branches: [main] pull_request: - release: - types: [created] + workflow_dispatch: + +concurrency: + group: publish-${{ github.ref }} + cancel-in-progress: false jobs: build: @@ -23,23 +26,130 @@ jobs: run: ./gradlew build publish: - if: github.event_name == 'release' + if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main' needs: build runs-on: ubuntu-latest permissions: - contents: read + contents: write packages: write steps: - uses: actions/checkout@v4 + with: + fetch-depth: 0 + - name: Read version + id: version + run: | + VERSION=$(grep '^araraSdkVersion=' gradle.properties | cut -d= -f2 | tr -d '[:space:]') + GROUP=$(grep '^araraSdkGroup=' gradle.properties | cut -d= -f2 | tr -d '[:space:]') + ARTIFACT=$(sed -n "s/^rootProject.name *= *['\"]\([^'\"]*\)['\"].*/\1/p" settings.gradle) + if [ -z "$VERSION" ] || [ -z "$GROUP" ] || [ -z "$ARTIFACT" ]; then + echo "Could not read version, group or artifactId." >&2 + exit 1 + fi + echo "version=$VERSION" >> "$GITHUB_OUTPUT" + echo "group=$GROUP" >> "$GITHUB_OUTPUT" + echo "group_path=$(echo "$GROUP" | tr . /)" >> "$GITHUB_OUTPUT" + echo "artifact=$ARTIFACT" >> "$GITHUB_OUTPUT" + echo "tag=v$VERSION" >> "$GITHUB_OUTPUT" + - name: Check each destination + id: check + env: + GH_TOKEN: ${{ github.token }} + VERSION: ${{ steps.version.outputs.version }} + GROUP: ${{ steps.version.outputs.group }} + GROUP_PATH: ${{ steps.version.outputs.group_path }} + ARTIFACT: ${{ steps.version.outputs.artifact }} + TAG: ${{ steps.version.outputs.tag }} + run: | + CENTRAL_URL="https://repo1.maven.org/maven2/$GROUP_PATH/$ARTIFACT/$VERSION/$ARTIFACT-$VERSION.pom" + STATUS=$(curl -s -o /dev/null -w '%{http_code}' --max-time 20 "$CENTRAL_URL") + case "$STATUS" in + 200) echo "central=false" >> "$GITHUB_OUTPUT" ;; + 404) echo "central=true" >> "$GITHUB_OUTPUT" ;; + *) echo "Unexpected status $STATUS from Maven Central." >&2; exit 1 ;; + esac + + if VERSIONS=$(gh api "/orgs/ararahq/packages/maven/$GROUP.$ARTIFACT/versions" --paginate --jq '.[].name' 2>/tmp/gh-err); then + if echo "$VERSIONS" | grep -qx "$VERSION"; then + echo "packages=false" >> "$GITHUB_OUTPUT" + else + echo "packages=true" >> "$GITHUB_OUTPUT" + fi + elif grep -q "404" /tmp/gh-err; then + echo "packages=true" >> "$GITHUB_OUTPUT" + else + cat /tmp/gh-err >&2 + exit 1 + fi + + if git ls-remote --exit-code --tags origin "refs/tags/$TAG" >/dev/null; then + echo "tag=false" >> "$GITHUB_OUTPUT" + else + echo "tag=true" >> "$GITHUB_OUTPUT" + fi + + if gh release view "$TAG" >/dev/null 2>&1; then + echo "release=false" >> "$GITHUB_OUTPUT" + else + echo "release=true" >> "$GITHUB_OUTPUT" + fi + - name: Fail fast if publishing secrets are missing + if: steps.check.outputs.central == 'true' || steps.check.outputs.packages == 'true' + env: + MAVEN_CENTRAL_USERNAME: ${{ secrets.MAVEN_CENTRAL_USERNAME }} + MAVEN_CENTRAL_PASSWORD: ${{ secrets.MAVEN_CENTRAL_PASSWORD }} + GPG_PRIVATE_KEY: ${{ secrets.GPG_PRIVATE_KEY }} + GPG_PASSPHRASE: ${{ secrets.GPG_PASSPHRASE }} + run: | + MISSING="" + for NAME in MAVEN_CENTRAL_USERNAME MAVEN_CENTRAL_PASSWORD GPG_PRIVATE_KEY GPG_PASSPHRASE; do + if [ -z "${!NAME}" ]; then + MISSING="$MISSING $NAME" + fi + done + if [ -n "$MISSING" ]; then + echo "Missing publishing secrets:$MISSING" >&2 + exit 1 + fi - name: Set up JDK 17 + if: steps.check.outputs.central == 'true' || steps.check.outputs.packages == 'true' uses: actions/setup-java@v4 with: java-version: '17' distribution: 'temurin' - name: Setup Gradle + if: steps.check.outputs.central == 'true' || steps.check.outputs.packages == 'true' uses: gradle/actions/setup-gradle@v4 - - name: Publish to GitHub Packages - run: ./gradlew publishMavenJavaPublicationToGitHubPackagesRepository + - name: Publish signed artifacts in a single Gradle run + if: steps.check.outputs.central == 'true' || steps.check.outputs.packages == 'true' env: + PUBLISH_CENTRAL: ${{ steps.check.outputs.central }} + PUBLISH_PACKAGES: ${{ steps.check.outputs.packages }} + ORG_GRADLE_PROJECT_mavenCentralUsername: ${{ secrets.MAVEN_CENTRAL_USERNAME }} + ORG_GRADLE_PROJECT_mavenCentralPassword: ${{ secrets.MAVEN_CENTRAL_PASSWORD }} + ORG_GRADLE_PROJECT_signingInMemoryKey: ${{ secrets.GPG_PRIVATE_KEY }} + ORG_GRADLE_PROJECT_signingInMemoryKeyPassword: ${{ secrets.GPG_PASSPHRASE }} GITHUB_ACTOR: ${{ github.actor }} GITHUB_TOKEN: ${{ github.token }} + run: | + TASKS="" + if [ "$PUBLISH_CENTRAL" = "true" ]; then + TASKS="$TASKS publishAndReleaseToMavenCentral" + fi + if [ "$PUBLISH_PACKAGES" = "true" ]; then + TASKS="$TASKS publishMavenPublicationToGitHubPackagesRepository" + fi + ./gradlew $TASKS --no-configuration-cache + - name: Create tag + if: steps.check.outputs.tag == 'true' + env: + TAG: ${{ steps.version.outputs.tag }} + run: | + git tag "$TAG" + git push origin "$TAG" + - name: Create GitHub release + if: steps.check.outputs.release == 'true' + env: + GH_TOKEN: ${{ github.token }} + TAG: ${{ steps.version.outputs.tag }} + run: gh release create "$TAG" --title "$TAG" --generate-notes diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..d6b06cf --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,36 @@ +# Changelog + +## 2.0.0 (2026-09-24) + +Alinha o SDK com a API real por chave de API. Tem mudanças incompatíveis. + +### Incompatível +- Removido `getUsers()` (`/users/me` recusa chave de API). Use `getAuth().me()` → `GET /auth/me` (chave ADMIN). `UserResponse` agora tem `name`, `email`, `role`, `emailPending`. +- Removido `getApiKeys()`: a API recusa gerenciar chaves por chave (403 `RESOURCE_FORBIDDEN`). +- `getTemplates().list()` devolve `PaginatedResponse` (`data` + `pagination`) em vez de `List`; antes quebrava sempre na desserialização. +- `getSmartLinks().list()` devolve `PaginatedResponse`. +- 403 com código de negócio deixou de ser `AraraAuthException`: vira `AraraApiException` com `getCode()`, e `PLAN_FEATURE_LOCKED` vira `PlanFeatureLockedException` (`getFeature`, `getCurrentPlan`, `getUpgradeTo`). `AraraAuthException` agora estende `AraraApiException` e só cobre 401 e 403 sem código. +- POST e PATCH sem `Idempotency-Key` não são mais repetidos pelo retry automático. + +### Corrigido +- `getMessages().send` e `getCampaigns().create` sempre mandam `Idempotency-Key` (UUID v4 gerado ou o seu), reutilizado nos retries: timeout ou 5xx não vira envio duplicado e cobrado. +- `receiver` aceita `whatsapp:+55...`, `+55...` e só dígitos, com a regra da API (7 a 15 dígitos). +- Filtros de contatos e conversas e telefones no path são codificados na URL (`&`, `#`, `+` não corrompem mais a query). +- Erro do filtro de chave no formato padrão do Spring (`{timestamp,status,error,path}`) é lido como falha de autenticação, não como código de negócio. +- `getMessages().getById` com 403 de corpo vazio vira `AraraApiException` `NOT_FOUND` (mensagem de outra conta), não erro de chave. +- `Retry-After` acima de 30 s não segura a thread: a exceção sai com `getRetryAfter()`. +- Chave de idempotência em branco e api key em branco são recusadas; item nulo em lote ou campanha falha com o índice. +- `AraraApiException` expõe `getCode()`, `getDetails()` e `getRetryAfter()` (também em 503). + +### Novo +- `getMessages().sendBatch` (`POST /v1/messages/batch`, até 1000) e `getMessages().listByBatch`. +- `getCampaigns().list` (`CampaignPage`) e `getCampaigns().cancel`; `CampaignRequest.scheduledAt`. +- `getTemplates().list(name, status, page, size)` e `getTemplates().analytics(...)`; `CreateTemplateRequest.headerType`. +- `getOptOuts()` (`/v1/opt-outs`). +- `MessageResponse.reason`; `CampaignResponse.scheduledAt`; `CampaignListItem.scheduledAt/createdAt`. +- `getCampaigns().getById` devolve `CampaignDetail` (contadores de entrega, leitura, clique, conversão, bloqueio e estorno, `startedAt`, `finishedAt`). +- Publicação no Maven Central (assinada), além do GitHub Packages. + +## 1.8.1 (2026-07-14) + +- Última versão publicada só no GitHub Packages. diff --git a/README.md b/README.md index 9d06f2f..9627484 100644 --- a/README.md +++ b/README.md @@ -4,371 +4,154 @@ [![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) -SDK oficial em Java para integração com a **Plataforma WhatsApp Business Arara**. - -## Sobre - -O Arara Java SDK é uma biblioteca leve e type-safe para integração perfeita com os serviços de mensagens WhatsApp, gerenciamento de campanhas e usuários da Arara. Construa aplicações robustas de mensagens em Java com o mínimo de esforço. - -### Funcionalidades - -- 📱 **Serviço de Mensagens** - Envie mensagens WhatsApp (templates e texto livre) -- 📊 **Serviço de Campanhas** - Crie e gerencie campanhas de mensagens em massa -- 👤 **Serviço de Usuários** - Acesse e atualize informações do usuário autenticado -- 📝 **Serviço de Templates** - Crie, gerencie e consulte o status de templates WhatsApp -- ✅ **Validação Robusta** - Validação de requisições com mensagens de erro claras -- 🔐 **Autenticação Segura** - Gerenciamento automático de chave API via interceptadores -- 📦 **Type-Safe** - Segurança de tipos completa com padrão builder -- 🧪 **Bem Testado** - 66 testes unitários com 80% de cobertura -- 📖 **Documentação Completa** - Javadoc abrangente para todas as APIs públicas +SDK oficial em Java para a API de mensagens WhatsApp da **Arara**. ## Requisitos -- **Java**: 17 ou superior -- **Gradle**: 7.0 ou superior (ou use o wrapper incluído) -- **Chave de API**: Chave de API válida da Arara do seu painel de controle +- Java 17 ou superior +- Chave de API da Arara (painel → Configurações → Chaves de API) ## Instalação -O SDK é distribuído via **GitHub Packages** (não está publicado no Maven Central). O GitHub Packages exige autenticação mesmo para leitura: use seu usuário do GitHub e um personal access token com escopo `read:packages`. - -### Usando Gradle +A partir da 2.0.0 o SDK é publicado no **Maven Central**, sem repositório extra nem token. -Adicione o repositório e a dependência ao seu `build.gradle`: +Gradle: ```gradle -repositories { - mavenCentral() - maven { - name = "GitHubPackages" - url = uri("https://maven.pkg.github.com/ararahq/arara-java-sdk") - credentials { - username = System.getenv("GITHUB_ACTOR") ?: project.findProperty("gpr.user") - password = System.getenv("GITHUB_TOKEN") ?: project.findProperty("gpr.key") - } - } -} - dependencies { - implementation 'com.ararahq:arara-java-sdk:1.8.1' + implementation 'com.ararahq:arara-java-sdk:2.0.0' } ``` -Defina as credenciais em `~/.gradle/gradle.properties` (`gpr.user` e `gpr.key`) ou nas variáveis de ambiente `GITHUB_ACTOR` e `GITHUB_TOKEN`. - -### Usando Maven - -Adicione o repositório ao seu `pom.xml`: +Maven: ```xml - - - github - https://maven.pkg.github.com/ararahq/arara-java-sdk - - - com.ararahq arara-java-sdk - 1.8.1 + 2.0.0 ``` -E as credenciais no `~/.m2/settings.xml`: +Cada versão também sai no GitHub Packages (`https://maven.pkg.github.com/ararahq/arara-java-sdk`), que exige token com `read:packages` até para leitura. -```xml - - - github - SEU_USUARIO_GITHUB - SEU_TOKEN_COM_READ_PACKAGES - - -``` +## Permissões da chave -## Início Rápido +A API confere a permissão da chave em cada chamada. Envio, templates, campanhas e números funcionam com as permissões específicas (`MESSAGES_SEND`, `TEMPLATES_WRITE`, `CAMPAIGNS_SEND`, `READ`). -### 1. Inicializar o SDK +**Exigem chave ADMIN:** `getAuth().me()`, `contacts`, `conversations`, `wallet`, `optOuts` e `organizations` (perfil comercial e plano). Com chave sem ADMIN, essas chamadas lançam `AraraAuthException` (403). -```java -import com.ararahq.arara.sdk.Arara; +`getMessages().getById(id)` com 403 de corpo vazio significa mensagem de outra conta (ou inexistente para essa chave): o SDK lança `AraraApiException` com `getCode()` = `NOT_FOUND` e status 403, não erro de autenticação. -// Criar o cliente -Arara arara = Arara.builder() - .apiKey("sua-chave-api-aqui") - .baseUrl("https://api.ararahq.com") - .build(); -``` +Gerenciar chaves de API e o webhook da organização não é possível por chave: faça pelo painel. -Timeouts e retries são configuráveis no builder (valores abaixo são os defaults): +## Início rápido ```java Arara arara = Arara.builder() - .apiKey("sua-chave-api-aqui") - .connectTimeout(Duration.ofSeconds(10)) - .readTimeout(Duration.ofSeconds(30)) - .writeTimeout(Duration.ofSeconds(30)) - .callTimeout(Duration.ofMinutes(2)) - .maxRetries(3) - .build(); -``` - -Falhas de rede, respostas 5xx e 429 são reenviadas automaticamente com backoff exponencial até `maxRetries`, honrando o header `Retry-After` quando presente. + .apiKey(System.getenv("ARARA_API_KEY")) + .build(); -### 2. Enviar uma Mensagem - -```java -import com.ararahq.arara.sdk.models.SendMessageRequest; -import com.ararahq.arara.sdk.models.MessageResponse; - -// Enviar uma mensagem de texto livre -SendMessageRequest request = SendMessageRequest.builder() - .receiver("whatsapp:+5511999998888") - .body("Olá! Esta é uma mensagem de teste.") - .mediaUrl("https://ararahq.com/l/FtFmja") // Opcional: Imagem/PDF - .build(); - -MessageResponse response = arara.getMessages().send(request); -System.out.println("ID da Mensagem: " + response.getId()); -System.out.println("Status: " + response.getStatus()); -``` - -### 3. Enviar uma Mensagem com Template - -```java -SendMessageRequest request = SendMessageRequest.builder() - .receiver("whatsapp:+5511999998888") - .templateName("hello_world") - .templateVariables(Arrays.asList("João", "Silva")) - .scheduledAt(Instant.parse("2024-12-25T10:00:00Z")) // Opcional: Agendamento - .build(); - -MessageResponse response = arara.getMessages().send(request); +MessageResponse sent = arara.getMessages().send(SendMessageRequest.builder() + .receiver("+5511999998888") + .templateName("boas_vindas") + .templateVariables(List.of("Ana")) + .build()); ``` -### 4. Criar uma Campanha - -```java -import com.ararahq.arara.sdk.models.*; -import java.util.Arrays; - -List contacts = Arrays.asList( - CampaignContactRequest.builder() - .to("whatsapp:+5511999998888") - .variables(Arrays.asList("João")) - .build(), - CampaignContactRequest.builder() - .to("whatsapp:+5511988887777") - .variables(Arrays.asList("Maria")) - .build() -); - -CampaignRequest campaign = CampaignRequest.builder() - .name("Campanha de Boas-vindas") - .templateName("template_boas_vindas") - .sender("whatsapp:+551140001000") - .contacts(contacts) - .build(); - -CampaignResponse response = arara.getCampaigns().create(campaign); -System.out.println("ID da Campanha: " + response.getId()); -System.out.println("Total de Mensagens: " + response.getTotalMessages()); -``` +Uma chave de idempotência em branco é recusada com `AraraException`; espaços nas pontas são removidos. -### 5. Obter Informações do Usuário +O `receiver` aceita `whatsapp:+5511999998888`, `+5511999998888` ou só os dígitos (7 a 15 dígitos, mesma regra da API). -```java -UserResponse user = arara.getUsers().me(); -System.out.println("Usuário: " + user.getName()); -System.out.println("Email: " + user.getEmail()); -System.out.println("Papel: " + user.getRole()); - -// Atualizar informações do meu perfil -UpdateUserRequest updateRequest = UpdateUserRequest.builder() - .name("Novo Nome") - .phoneNumber("+5511999998888") - .build(); -UserResponse updatedUser = arara.getUsers().updateMe(updateRequest); -``` +### Idempotência e retry -### 6. Gerenciar Templates +`getMessages().send`, `getMessages().sendBatch` e `getCampaigns().create` **sempre** mandam o header `Idempotency-Key`. Sem chave sua, o SDK gera um UUID v4 por chamada e reutiliza a mesma chave em todos os retries dela, então um timeout nunca vira envio duplicado. Para retentar por conta própria (por exemplo, depois de reiniciar o processo), passe a sua chave: ```java -import com.ararahq.arara.sdk.models.CreateTemplateRequest; -import com.ararahq.arara.sdk.models.TemplateResponse; -import com.ararahq.arara.sdk.models.TemplateStatusResponse; - -// Criar um novo template -CreateTemplateRequest newTemplate = CreateTemplateRequest.builder() - .name("boas_vindas_v2") - .category("MARKETING") - .body("Olá {{1}}, bem-vindo à nossa plataforma!") - .build(); - -TemplateResponse template = arara.getTemplates().create(newTemplate); -System.out.println("ID: " + template.getId()); - -// Consultar status de aprovação na Meta -TemplateStatusResponse status = arara.getTemplates().getStatus(template.getId()); -System.out.println("Status: " + status.getStatus()); -``` - -## Estrutura do Projeto - +arara.getMessages().send(request, "pedido-4521-lembrete"); +arara.getCampaigns().create(campaign, "campanha-black-friday"); ``` -src/ -├── main/java/com/ararahq/arara/sdk/ -│ ├── Arara.java # Ponto de entrada principal do SDK -│ ├── config/ # Classes de configuração -│ ├── exceptions/ # Tipos de exceção personalizados -│ ├── http/ # Implementação do cliente HTTP -│ ├── interceptors/ # Interceptadores de requisição/resposta -│ ├── models/ # Modelos de requisição/resposta -│ ├── services/ # Serviços de lógica de negócio -│ │ ├── MessageService.java -│ │ ├── CampaignService.java -│ │ ├── UserService.java -│ │ └── TemplateService.java -│ └── utils/ # Funções utilitárias -└── test/java/com/ararahq/arara/sdk/ - ├── services/ # Testes unitários dos serviços (38 testes) - └── utils/ # Testes unitários de utilitários (28 testes) - -build.gradle # Configuração do Gradle -``` - -## Executando Testes -### Rodar todos os testes +O retry automático (padrão 3, `maxRetries`) cobre falha de rede, 5xx e 429, e honra `Retry-After` até 30 s; acima disso não espera e lança a exceção com `getRetryAfter()`. POST e PATCH sem `Idempotency-Key` **nunca** são repetidos; GET, PUT e DELETE sim. -```bash -./gradlew test -``` +## Recursos -### Gerar relatório de cobertura de testes +| Serviço | Métodos | Endpoint | +|---|---|---| +| `getMessages()` | `send`, `sendBatch` (até 1000), `getById`, `listByBatch` | `/v1/messages` | +| `getCampaigns()` | `create`, `list`, `getById`, `cancel` | `/v1/campaigns` | +| `getTemplates()` | `create`, `list`, `getById`, `getStatus`, `delete`, `analytics` | `/v1/templates` | +| `getSmartLinks()` | `create`, `update`, `list`, `stats` | `/v1/smart-links/whatsapp` | +| `getNumbers()` | `list`, `update`, `delete`, `request`, `listRequests`, `sync`, `warming` | `/v1/organizations/me/numbers` | +| `getAuth()` | `me` (ADMIN) | `/auth/me` | +| `getContacts()` | `list`, `importBatch`, `stats`, `reactivationCandidates`, `listTags`, `get`, `update`, `messages` (ADMIN) | `/v1/contacts` | +| `getConversations()` | `list`, `leadStats`, `messages`, `reply`, `updateStatus`, `windowStatus` (ADMIN) | `/v1/conversations` | +| `getWallet()` | `transactions`, `getAutoRecharge`, `updateAutoRecharge` (ADMIN) | `/v1/wallet` | +| `getOptOuts()` | `list`, `add`, `get`, `remove` (ADMIN) | `/v1/opt-outs` | +| `getOrganizations()` | `me`, `updateBusinessProfile`, `getPlan`, `changePlan` (ADMIN) | `/v1/organizations/me` | -```bash -./gradlew jacocoTestReport -``` +### Templates são por id -O relatório de cobertura estará disponível em `build/reports/jacoco/test/html/index.html` +`getById`, `getStatus`, `delete` e `analytics(id, period)` recebem o **id (UUID)** do template, nunca o nome. Para achar pelo nome, filtre a lista: -### Rodar uma classe de teste específica - -```bash -./gradlew test --tests MessageServiceTest +```java +PaginatedResponse page = arara.getTemplates().list("boas_vindas", "APPROVED", 0, 50); +UUID id = page.getData().get(0).getId(); ``` -## Referência da API - -### MessageService +### Paginação -- `send(SendMessageRequest)` - Enviar uma mensagem (template ou texto livre) -- `getById(String id)` - Recuperar detalhes da mensagem por ID +A API não usa um formato só, e o SDK segue cada endpoint: -### CampaignService +- `getTemplates().list` e `getSmartLinks().list` → `PaginatedResponse` com `getData()` e `getPagination()` (`page`, `size`, `totalElements`, `totalPages`). +- `getCampaigns().list` → `CampaignPage` e `getWallet().transactions` → `WalletTransactionPage`, ambos com `getContent()`, `getTotalPages()`, `getTotalElements()`. +- `getContacts().list` → `ContactsListResponse` (`contacts`, `total`, `page`, `size`, `totalPages`). -- `create(CampaignRequest)` - Criar e iniciar uma nova campanha -- `getById(UUID id)` - Recuperar detalhes da campanha por ID +## Erros -### UserService - -- `me()` - Obter informações do usuário autenticado atual -- `updateMe(UpdateUserRequest)` - Atualizar informações do perfil do usuário - -### TemplateService - -- `create(CreateTemplateRequest)` - Criar e submeter um novo template para o Meta -- `list()` - Listar todos os templates da conta -- `getById(UUID id)` - Recuperar detalhes de um template por ID -- `delete(UUID id)` - Remover um template -- `getStatus(UUID id)` - Consultar o status de aprovação atual do template - -## Tratamento de Erros - -O SDK fornece tipos de exceção específicos para melhor tratamento de erros: +Toda resposta de erro vira exceção; nada é engolido. ```java -import com.ararahq.arara.sdk.exceptions.*; - try { - MessageResponse response = arara.getMessages().send(request); + arara.getMessages().send(request); +} catch (PlanFeatureLockedException e) { + // 403 PLAN_FEATURE_LOCKED + log.info("Libere {} no plano {} (atual: {})", e.getFeature(), e.getUpgradeTo(), e.getCurrentPlan()); } catch (AraraAuthException e) { - // Tratar erros de autenticação (401, 403) - System.err.println("Autenticação falhou: " + e.getMessage()); + // 401, ou 403 sem código: chave inválida, expirada ou sem permissão } catch (AraraRateLimitException e) { - // Tratar rate limit (429) após esgotar os retries automáticos - System.err.println("Rate limit atingido. Aguarde: " + e.getRetryAfter()); + // 429 depois dos retries; e.getRetryAfter() } catch (AraraApiException e) { - // Tratar erros da API com código de status e detalhes - System.err.println("Erro da API " + e.getStatusCode() + ": " + e.getMessage()); + // e.getStatusCode(), e.getCode() (ex.: INVALID_RECIPIENT), e.getMessage(), e.getDetails(), e.getRetryAfter() } catch (AraraNetworkException e) { - // Tratar erros de rede/timeout - System.err.println("Erro de rede: " + e.getMessage()); -} catch (AraraException e) { - // Tratar erros gerais do SDK - System.err.println("Erro do SDK: " + e.getMessage()); + // timeout ou falha de conexão } ``` -## Contribuindo - -Agradecemos o interesse em contribuir para o Arara Java SDK! Por favor, siga estas diretrizes: - -### Fluxo de Trabalho +Um 403 com código de negócio (`NO_DEDICATED_NUMBER`, `PLAN_LIMIT_REACHED`, `RESOURCE_FORBIDDEN`...) é `AraraApiException` com o código, não erro de autenticação. -1. **Fork** este repositório -2. Crie uma **branch de feature**: `git checkout -b feat/sua-feature` -3. Faça suas alterações e **commit**: - - Escreva mensagens de commit claras e descritivas em português ou inglês - - Exemplo: `feat: adicionar suporte para agendamento de mensagens` -4. **Push** para seu fork: `git push origin feat/sua-feature` -5. Abra um **Pull Request** com uma descrição detalhada +## Configuração -### Padrões de Código - -- Siga as convenções Java (CamelCase para classes, camelCase para métodos) -- Todos os comentários e Javadoc em inglês -- Adicione testes unitários para novas funcionalidades (alvo 80% de cobertura) -- Execute os testes antes de enviar: `./gradlew test` -- Mantenha o código limpo sem comentários desnecessários - -### Requisitos de Testes - -- Cobertura mínima de 80% do código -- Todos os testes devem passar: `./gradlew build` -- Teste novas funcionalidades minuciosamente com cenários positivos e negativos - -## Solução de Problemas - -### Chave de API Inválida -``` -AraraAuthException: Unauthorized +```java +Arara arara = Arara.builder() + .apiKey(apiKey) + .baseUrl("https://api.ararahq.com") + .connectTimeout(Duration.ofSeconds(10)) + .readTimeout(Duration.ofSeconds(30)) + .callTimeout(Duration.ofMinutes(2)) + .maxRetries(3) + .build(); ``` -- Verifique se sua chave de API está correta -- Confira se sua chave de API não expirou -- Garanta que a chave tem as permissões apropriadas -### Formato de Número de Telefone Inválido -``` -AraraException: Invalid phone number. Must start with 'whatsapp:+' -``` -- Números de telefone devem estar no formato: `whatsapp:+[código_país][número]` -- Exemplo: `whatsapp:+5511999998888` (Brasil) +## Desenvolvimento -### Timeout de Rede -``` -AraraNetworkException: Communication failure with Arara API +```bash +./gradlew build # compila, roda os testes (contra servidor HTTP fake) e confere cobertura mínima de 80% +./gradlew jacocoTestReport ``` -- Verifique sua conexão com a internet -- Valide se o endpoint da API está acessível -- Aumente o timeout se necessário (ajuste na configuração) - -## Licença -Este projeto está licenciado sob a [Licença MIT](LICENSE). +A publicação é automática: todo push na `main` com versão nova em `gradle.properties` publica no Maven Central (assinado) e no GitHub Packages, e cria a tag `vX.Y.Z` com release. -## Suporte +## Licença -Para dúvidas, problemas ou solicitações de novas funcionalidades, abra uma issue no GitHub ou contate o time Arara em suporte@ararahq.com. +[MIT](LICENSE). Dúvidas: suporte@ararahq.com. diff --git a/build.gradle b/build.gradle index fcc9b27..5f07da1 100644 --- a/build.gradle +++ b/build.gradle @@ -1,6 +1,7 @@ plugins { id 'java-library' id 'maven-publish' + id 'com.vanniktech.maven.publish' version '0.34.0' id 'jacoco' id "io.freefair.lombok" version "8.6" } @@ -12,8 +13,6 @@ java { toolchain { languageVersion = JavaLanguageVersion.of(Integer.parseInt(project.javaVersion)) } - withSourcesJar() - withJavadocJar() } repositories { @@ -84,34 +83,46 @@ tasks.jacocoTestCoverageVerification { check.dependsOn jacocoTestCoverageVerification -// Maven publication configuration -publishing { - publications { - mavenJava(MavenPublication) { - from components.java - - pom { - name = 'Arara Java SDK' - description = 'Official SDK for integrating with the Arara platform' - url = 'https://github.com/ararahq/arara-java-sdk' - licenses { - license { - name = 'MIT License' - url = 'https://opensource.org/licenses/MIT' - } - } - developers { - developer { - id = 'ararahq' - name = 'Arara HQ' - email = 'suporte@ararahq.com' - } - } +// Maven Central (Sonatype Central Portal) + GitHub Packages. +// Central credentials: ORG_GRADLE_PROJECT_mavenCentralUsername / ORG_GRADLE_PROJECT_mavenCentralPassword. +// Signing: ORG_GRADLE_PROJECT_signingInMemoryKey / ORG_GRADLE_PROJECT_signingInMemoryKeyPassword. +mavenPublishing { + publishToMavenCentral() + if (project.findProperty('signingInMemoryKey')) { + signAllPublications() + } + coordinates(project.araraSdkGroup, rootProject.name, project.araraSdkVersion) + + pom { + name = 'Arara Java SDK' + description = 'Official Java SDK for the Arara WhatsApp messaging API' + inceptionYear = '2025' + url = 'https://github.com/ararahq/arara-java-sdk' + licenses { + license { + name = 'MIT License' + url = 'https://opensource.org/licenses/MIT' + distribution = 'repo' } } + developers { + developer { + id = 'ararahq' + name = 'Arara HQ' + email = 'suporte@ararahq.com' + url = 'https://ararahq.com' + } + } + scm { + url = 'https://github.com/ararahq/arara-java-sdk' + connection = 'scm:git:git://github.com/ararahq/arara-java-sdk.git' + developerConnection = 'scm:git:ssh://git@github.com/ararahq/arara-java-sdk.git' + } } +} + +publishing { repositories { - mavenLocal() maven { name = "GitHubPackages" url = uri("https://maven.pkg.github.com/ararahq/arara-java-sdk") @@ -131,3 +142,8 @@ test { exceptionFormat "full" } } + +tasks.withType(AbstractArchiveTask).configureEach { + preserveFileTimestamps = false + reproducibleFileOrder = true +} diff --git a/gradle.properties b/gradle.properties index 96adf3c..0081160 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,5 +1,5 @@ # SDK Versioning -araraSdkVersion=1.8.1 +araraSdkVersion=2.0.0 araraSdkGroup=com.ararahq # Dependency Versions diff --git a/src/main/java/com/ararahq/arara/sdk/Arara.java b/src/main/java/com/ararahq/arara/sdk/Arara.java index 8474112..a784be2 100644 --- a/src/main/java/com/ararahq/arara/sdk/Arara.java +++ b/src/main/java/com/ararahq/arara/sdk/Arara.java @@ -1,17 +1,18 @@ package com.ararahq.arara.sdk; import com.ararahq.arara.sdk.config.AraraConfig; +import com.ararahq.arara.sdk.exceptions.AraraException; import com.ararahq.arara.sdk.http.AraraHttpClient; -import com.ararahq.arara.sdk.services.ApiKeyService; +import com.ararahq.arara.sdk.services.AuthService; import com.ararahq.arara.sdk.services.CampaignService; import com.ararahq.arara.sdk.services.ContactService; import com.ararahq.arara.sdk.services.ConversationService; import com.ararahq.arara.sdk.services.MessageService; import com.ararahq.arara.sdk.services.NumberService; +import com.ararahq.arara.sdk.services.OptOutService; import com.ararahq.arara.sdk.services.OrganizationService; import com.ararahq.arara.sdk.services.SmartLinkService; import com.ararahq.arara.sdk.services.TemplateService; -import com.ararahq.arara.sdk.services.UserService; import com.ararahq.arara.sdk.services.WalletService; import lombok.Getter; @@ -24,7 +25,7 @@ @Getter public class Arara { private final MessageService messages; - private final UserService users; + private final AuthService auth; private final CampaignService campaigns; private final TemplateService templates; private final ContactService contacts; @@ -32,17 +33,17 @@ public class Arara { private final WalletService wallet; private final NumberService numbers; private final SmartLinkService smartLinks; - private final ApiKeyService apiKeys; + private final OptOutService optOuts; private final OrganizationService organizations; private Arara(AraraConfig config) { - if (config.getApiKey() == null || config.getApiKey().isEmpty()) { - throw new com.ararahq.arara.sdk.exceptions.AraraException( + if (config.getApiKey() == null || config.getApiKey().isBlank()) { + throw new AraraException( "API Key is required to initialize the SDK."); } AraraHttpClient httpClient = new AraraHttpClient(config); this.messages = new MessageService(httpClient); - this.users = new UserService(httpClient); + this.auth = new AuthService(httpClient); this.campaigns = new CampaignService(httpClient); this.templates = new TemplateService(httpClient); this.contacts = new ContactService(httpClient); @@ -50,7 +51,7 @@ private Arara(AraraConfig config) { this.wallet = new WalletService(httpClient); this.numbers = new NumberService(httpClient); this.smartLinks = new SmartLinkService(httpClient); - this.apiKeys = new ApiKeyService(httpClient); + this.optOuts = new OptOutService(httpClient); this.organizations = new OrganizationService(httpClient); } diff --git a/src/main/java/com/ararahq/arara/sdk/exceptions/AraraApiException.java b/src/main/java/com/ararahq/arara/sdk/exceptions/AraraApiException.java index f13eae4..3f64dce 100644 --- a/src/main/java/com/ararahq/arara/sdk/exceptions/AraraApiException.java +++ b/src/main/java/com/ararahq/arara/sdk/exceptions/AraraApiException.java @@ -3,18 +3,53 @@ import com.ararahq.arara.sdk.models.AraraError; import lombok.Getter; +import java.time.Duration; +import java.util.Collections; +import java.util.Map; + /** * Thrown when the API returns an error (4xx or 5xx). - * Contains structured error details returned by the server. + * Carries the envelope {@code {"error": {"code", "message", "details"}}} returned by the server, + * plus the {@code Retry-After} hint when the server sent one. */ @Getter public class AraraApiException extends AraraException { private final int statusCode; private final AraraError errorDetails; + private final Duration retryAfter; public AraraApiException(int statusCode, AraraError errorDetails) { - super(errorDetails != null ? errorDetails.getMessage() : "API Error " + statusCode); + this(statusCode, errorDetails, null); + } + + public AraraApiException(int statusCode, AraraError errorDetails, Duration retryAfter) { + super(resolveMessage(statusCode, errorDetails)); this.statusCode = statusCode; this.errorDetails = errorDetails; + this.retryAfter = retryAfter; + } + + /** + * @return The machine-readable error code (e.g. {@code INSUFFICIENT_FUNDS}), or null when absent. + */ + public String getCode() { + return errorDetails != null ? errorDetails.getCode() : null; + } + + /** + * @return The error details object, never null. + */ + public Map getDetails() { + if (errorDetails == null || errorDetails.getDetails() == null) { + return Collections.emptyMap(); + } + return errorDetails.getDetails(); + } + + private static String resolveMessage(int statusCode, AraraError errorDetails) { + if (errorDetails != null && errorDetails.getMessage() != null) { + return errorDetails.getMessage(); + } + return "API Error " + statusCode; } } diff --git a/src/main/java/com/ararahq/arara/sdk/exceptions/AraraAuthException.java b/src/main/java/com/ararahq/arara/sdk/exceptions/AraraAuthException.java index a16f805..8e40b0c 100644 --- a/src/main/java/com/ararahq/arara/sdk/exceptions/AraraAuthException.java +++ b/src/main/java/com/ararahq/arara/sdk/exceptions/AraraAuthException.java @@ -1,10 +1,14 @@ package com.ararahq.arara.sdk.exceptions; +import com.ararahq.arara.sdk.models.AraraError; + /** - * Thrown when there are authentication issues (401, 403). + * Thrown when the API key is missing, invalid, expired or lacks permission: + * any 401, or a 403 without an error code in the envelope. + * A 403 carrying a business code (e.g. {@code PLAN_FEATURE_LOCKED}) is not an auth failure. */ -public class AraraAuthException extends AraraException { - public AraraAuthException(String message) { - super(message); +public class AraraAuthException extends AraraApiException { + public AraraAuthException(int statusCode, AraraError errorDetails) { + super(statusCode, errorDetails); } } diff --git a/src/main/java/com/ararahq/arara/sdk/exceptions/AraraRateLimitException.java b/src/main/java/com/ararahq/arara/sdk/exceptions/AraraRateLimitException.java index 116ef03..2b44220 100644 --- a/src/main/java/com/ararahq/arara/sdk/exceptions/AraraRateLimitException.java +++ b/src/main/java/com/ararahq/arara/sdk/exceptions/AraraRateLimitException.java @@ -1,7 +1,6 @@ package com.ararahq.arara.sdk.exceptions; import com.ararahq.arara.sdk.models.AraraError; -import lombok.Getter; import java.time.Duration; @@ -9,14 +8,10 @@ * Thrown when the API returns 429 Too Many Requests. * Exposes the Retry-After hint returned by the server, when present. */ -@Getter public class AraraRateLimitException extends AraraApiException { private static final int HTTP_TOO_MANY_REQUESTS = 429; - private final Duration retryAfter; - public AraraRateLimitException(AraraError errorDetails, Duration retryAfter) { - super(HTTP_TOO_MANY_REQUESTS, errorDetails); - this.retryAfter = retryAfter; + super(HTTP_TOO_MANY_REQUESTS, errorDetails, retryAfter); } } diff --git a/src/main/java/com/ararahq/arara/sdk/exceptions/PlanFeatureLockedException.java b/src/main/java/com/ararahq/arara/sdk/exceptions/PlanFeatureLockedException.java new file mode 100644 index 0000000..252960d --- /dev/null +++ b/src/main/java/com/ararahq/arara/sdk/exceptions/PlanFeatureLockedException.java @@ -0,0 +1,41 @@ +package com.ararahq.arara.sdk.exceptions; + +import com.ararahq.arara.sdk.models.AraraError; + +/** + * Thrown on {@code 403 PLAN_FEATURE_LOCKED}: the feature requires a higher plan. + */ +public class PlanFeatureLockedException extends AraraApiException { + public static final String CODE = "PLAN_FEATURE_LOCKED"; + private static final int HTTP_FORBIDDEN = 403; + + public PlanFeatureLockedException(AraraError errorDetails) { + super(HTTP_FORBIDDEN, errorDetails); + } + + /** + * @return The locked feature key, from {@code details.feature}. + */ + public String getFeature() { + return detailAsString("feature"); + } + + /** + * @return The organization's current plan, from {@code details.currentPlan}. + */ + public String getCurrentPlan() { + return detailAsString("currentPlan"); + } + + /** + * @return The minimum plan that unlocks the feature, from {@code details.upgradeTo}. + */ + public String getUpgradeTo() { + return detailAsString("upgradeTo"); + } + + private String detailAsString(String key) { + Object value = getDetails().get(key); + return value instanceof String ? (String) value : null; + } +} diff --git a/src/main/java/com/ararahq/arara/sdk/http/AraraHttpClient.java b/src/main/java/com/ararahq/arara/sdk/http/AraraHttpClient.java index 3860822..45a596f 100644 --- a/src/main/java/com/ararahq/arara/sdk/http/AraraHttpClient.java +++ b/src/main/java/com/ararahq/arara/sdk/http/AraraHttpClient.java @@ -6,6 +6,7 @@ import com.ararahq.arara.sdk.exceptions.AraraException; import com.ararahq.arara.sdk.exceptions.AraraNetworkException; import com.ararahq.arara.sdk.exceptions.AraraRateLimitException; +import com.ararahq.arara.sdk.exceptions.PlanFeatureLockedException; import com.ararahq.arara.sdk.interceptors.AuthInterceptor; import com.ararahq.arara.sdk.interceptors.RetryInterceptor; import com.ararahq.arara.sdk.models.AraraError; @@ -13,6 +14,8 @@ import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import okhttp3.MediaType; import okhttp3.OkHttpClient; @@ -23,7 +26,9 @@ import org.slf4j.LoggerFactory; import java.io.IOException; +import java.util.Collections; import java.util.Map; +import java.util.regex.Pattern; /** * Internal HTTP client based on OkHttp for making calls to the Arara API. @@ -31,6 +36,14 @@ public class AraraHttpClient { private static final Logger log = LoggerFactory.getLogger(AraraHttpClient.class); private static final MediaType JSON = MediaType.get("application/json; charset=utf-8"); + private static final int HTTP_UNAUTHORIZED = 401; + private static final int HTTP_FORBIDDEN = 403; + private static final int HTTP_TOO_MANY_REQUESTS = 429; + private static final Pattern ERROR_CODE_PATTERN = Pattern.compile("^[A-Z][A-Z0-9_]+$"); + private static final String RETRY_AFTER_HEADER = "Retry-After"; + private static final TypeReference> DETAILS_TYPE = + new TypeReference>() { + }; private final OkHttpClient httpClient; private final ObjectMapper objectMapper; @@ -40,7 +53,9 @@ public AraraHttpClient(AraraConfig config) { this.baseUrl = config.getBaseUrl(); this.objectMapper = new ObjectMapper() .registerModule(new JavaTimeModule()) - .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) + .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false) + .setSerializationInclusion(JsonInclude.Include.NON_NULL); this.httpClient = new OkHttpClient.Builder() .connectTimeout(config.getConnectTimeout()) @@ -70,71 +85,95 @@ public T get(String path, TypeReference responseType) { * Performs a POST request with JSON body. */ public T post(String path, Object body, Class responseType) { - return execute(buildBody("POST", path, body), responseType); + return execute(buildBody("POST", path, body, Collections.emptyMap()), responseType); + } + + /** + * Performs a POST request with JSON body and extra headers (e.g. Idempotency-Key). + */ + public T post(String path, Object body, Map headers, Class responseType) { + return execute(buildBody("POST", path, body, headers), responseType); } /** * Performs a POST request with a generic response type. */ public T post(String path, Object body, TypeReference responseType) { - return execute(buildBody("POST", path, body), responseType); + return execute(buildBody("POST", path, body, Collections.emptyMap()), responseType); } /** * Performs a PUT request with JSON body. */ public T put(String path, Object body, Class responseType) { - return execute(buildBody("PUT", path, body), responseType); + return execute(buildBody("PUT", path, body, Collections.emptyMap()), responseType); } /** * Performs a PUT request with a generic response type. */ public T put(String path, Object body, TypeReference responseType) { - return execute(buildBody("PUT", path, body), responseType); + return execute(buildBody("PUT", path, body, Collections.emptyMap()), responseType); } /** * Performs a PATCH request with JSON body. */ public T patch(String path, Object body, Class responseType) { - return execute(buildBody("PATCH", path, body), responseType); + return execute(buildBody("PATCH", path, body, Collections.emptyMap()), responseType); } /** * Performs a PATCH request with a generic response type. */ public T patch(String path, Object body, TypeReference responseType) { - return execute(buildBody("PATCH", path, body), responseType); + return execute(buildBody("PATCH", path, body, Collections.emptyMap()), responseType); } /** - * Performs a DELETE request. + * Performs a DELETE request, discarding the response body. */ public void delete(String path) { - Request request = new Request.Builder() - .url(baseUrl + path) - .delete() - .build(); - execute(request, Void.class); + execute(buildDelete(path), Void.class); + } + + /** + * Performs a DELETE request with a generic response type. + */ + public T delete(String path, TypeReference responseType) { + return execute(buildDelete(path), responseType); + } + + private String url(String path) { + boolean baseEndsWithSlash = baseUrl.endsWith("/"); + boolean pathStartsWithSlash = path.startsWith("/"); + if (baseEndsWithSlash && pathStartsWithSlash) { + return baseUrl + path.substring(1); + } + if (!baseEndsWithSlash && !pathStartsWithSlash) { + return baseUrl + "/" + path; + } + return baseUrl + path; } private Request buildGet(String path) { - return new Request.Builder() - .url(baseUrl + path) - .get() - .build(); + return new Request.Builder().url(url(path)).get().build(); } - private Request buildBody(String method, String path, Object body) { + private Request buildDelete(String path) { + return new Request.Builder().url(url(path)).delete().build(); + } + + private Request buildBody(String method, String path, Object body, Map headers) { try { RequestBody requestBody = body == null ? RequestBody.create("", JSON) : RequestBody.create(objectMapper.writeValueAsString(body), JSON); - return new Request.Builder() - .url(baseUrl + path) - .method(method, requestBody) - .build(); + Request.Builder builder = new Request.Builder() + .url(url(path)) + .method(method, requestBody); + headers.forEach(builder::header); + return builder.build(); } catch (IOException e) { throw new AraraException("Error serializing object to JSON", e); } @@ -171,32 +210,36 @@ private T execute(Request request, TypeReference responseType) { private String call(Request request, boolean discardBody) { try (Response response = httpClient.newCall(request).execute()) { if (!response.isSuccessful()) { - handleErrorResponse(response); + throw toException(response); } if (discardBody || response.body() == null) { return null; } return response.body().string(); } catch (IOException e) { - log.error("Network error accessing Arara API: {}", request.url(), e); + log.error("Network error accessing Arara API. [url={}, reason={}]", request.url(), e.getMessage()); throw new AraraNetworkException("Communication failure with Arara API", e); } } - private void handleErrorResponse(Response response) throws IOException { + private AraraApiException toException(Response response) throws IOException { String body = response.body() != null ? response.body().string() : ""; AraraError errorDetails = parseError(body); + String code = errorDetails != null ? errorDetails.getCode() : null; + int status = response.code(); - int code = response.code(); - if (code == 401 || code == 403) { - throw new AraraAuthException(errorDetails != null ? errorDetails.getMessage() : "Unauthorized"); + if (status == HTTP_UNAUTHORIZED || (status == HTTP_FORBIDDEN && code == null)) { + return new AraraAuthException(status, errorDetails); } - if (code == 429) { - throw new AraraRateLimitException(errorDetails, - RetryInterceptor.parseRetryAfter(response.header("Retry-After"))); + if (status == HTTP_FORBIDDEN && PlanFeatureLockedException.CODE.equals(code)) { + return new PlanFeatureLockedException(errorDetails); } - - throw new AraraApiException(code, errorDetails); + if (status == HTTP_TOO_MANY_REQUESTS) { + return new AraraRateLimitException(errorDetails, + RetryInterceptor.parseRetryAfter(response.header(RETRY_AFTER_HEADER))); + } + return new AraraApiException(status, errorDetails, + RetryInterceptor.parseRetryAfter(response.header(RETRY_AFTER_HEADER))); } private AraraError parseError(String body) { @@ -208,22 +251,38 @@ private AraraError parseError(String body) { JsonNode error = root.path("error"); if (error.isObject()) { return AraraError.builder() - .code(error.path("code").asText(null)) - .message(error.path("message").asText(null)) + .code(textOrNull(error.path("code"))) + .message(textOrNull(error.path("message"))) .details(error.path("details").isObject() - ? objectMapper.convertValue(error.path("details"), - new TypeReference>() { - }) + ? objectMapper.convertValue(error.path("details"), DETAILS_TYPE) : null) .build(); } + if (isSpringDefaultError(root)) { + String message = textOrNull(root.path("message")); + return AraraError.builder() + .message(message != null ? message : textOrNull(error)) + .build(); + } + String flatCode = textOrNull(error); return AraraError.builder() - .code(error.isTextual() ? error.asText() : null) - .message(root.path("message").asText(null)) + .code(flatCode != null && ERROR_CODE_PATTERN.matcher(flatCode).matches() ? flatCode : null) + .message(textOrNull(root.path("message"))) .build(); - } catch (Exception e) { - log.warn("Could not parse API error: {}", body); + } catch (IOException | IllegalArgumentException e) { + log.warn("Could not parse API error body. [reason={}]", e.getMessage()); + return null; + } + } + + private static boolean isSpringDefaultError(JsonNode root) { + return root.has("timestamp") || root.has("path"); + } + + private static String textOrNull(JsonNode node) { + if (node == null || !node.isTextual() || node.asText().isBlank()) { return null; } + return node.asText(); } } diff --git a/src/main/java/com/ararahq/arara/sdk/interceptors/RetryInterceptor.java b/src/main/java/com/ararahq/arara/sdk/interceptors/RetryInterceptor.java index 4fd1373..6734911 100644 --- a/src/main/java/com/ararahq/arara/sdk/interceptors/RetryInterceptor.java +++ b/src/main/java/com/ararahq/arara/sdk/interceptors/RetryInterceptor.java @@ -14,18 +14,24 @@ import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; +import java.util.Set; /** * Interceptor that retries failed requests with exponential backoff. * Retries on network failures, 5xx responses and 429 responses, * honoring the Retry-After header when present. + * Non-idempotent methods (POST, PATCH) are retried only when the request carries + * an {@code Idempotency-Key} header, so a timeout never becomes a duplicated send. */ public class RetryInterceptor implements Interceptor { private static final Logger log = LoggerFactory.getLogger(RetryInterceptor.class); private static final long INITIAL_BACKOFF_MILLIS = 500L; private static final long MAX_BACKOFF_MILLIS = 8_000L; + private static final long MAX_RETRY_AFTER_MILLIS = 30_000L; private static final int HTTP_TOO_MANY_REQUESTS = 429; private static final int HTTP_INTERNAL_SERVER_ERROR = 500; + public static final String IDEMPOTENCY_KEY_HEADER = "Idempotency-Key"; + private static final Set IDEMPOTENT_METHODS = Set.of("GET", "HEAD", "OPTIONS", "PUT", "DELETE"); private final int maxRetries; @@ -37,6 +43,9 @@ public RetryInterceptor(int maxRetries) { @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); + if (!isRetrySafe(request)) { + return chain.proceed(request); + } for (int attempt = 0; ; attempt++) { Response response; @@ -57,6 +66,11 @@ public Response intercept(Chain chain) throws IOException { } long waitMillis = retryDelayMillis(response, attempt); + if (waitMillis > MAX_RETRY_AFTER_MILLIS) { + log.warn("Retry-After above limit, not retrying. [url={}, status={}, waitMillis={}]", + request.url(), response.code(), waitMillis); + return response; + } log.warn("Received retryable status, retrying. [url={}, status={}, attempt={}, waitMillis={}]", request.url(), response.code(), attempt + 1, waitMillis); response.close(); @@ -92,6 +106,17 @@ private static Duration parseHttpDate(String headerValue) { } } + /** + * @return true when repeating the request cannot create a duplicate side effect. + */ + public static boolean isRetrySafe(Request request) { + if (IDEMPOTENT_METHODS.contains(request.method())) { + return true; + } + String key = request.header(IDEMPOTENCY_KEY_HEADER); + return key != null && !key.isBlank(); + } + private boolean isRetryable(int statusCode) { return statusCode == HTTP_TOO_MANY_REQUESTS || statusCode >= HTTP_INTERNAL_SERVER_ERROR; } diff --git a/src/main/java/com/ararahq/arara/sdk/models/BatchMessageRequest.java b/src/main/java/com/ararahq/arara/sdk/models/BatchMessageRequest.java new file mode 100644 index 0000000..9945bec --- /dev/null +++ b/src/main/java/com/ararahq/arara/sdk/models/BatchMessageRequest.java @@ -0,0 +1,31 @@ +package com.ararahq.arara.sdk.models; + +import lombok.Builder; +import lombok.Value; +import lombok.extern.jackson.Jacksonized; + +import java.util.List; + +/** + * Payload for sending one template to up to 1000 recipients in a single call. + */ +@Value +@Builder +@Jacksonized +public class BatchMessageRequest { + String templateName; + List messages; + + /** + * One recipient of a batch send. + */ + @Value + @Builder + @Jacksonized + public static class BatchMessageItem { + String receiver; + List templateVariables; + String smartLinkParam; + String smartLinkUrl; + } +} diff --git a/src/main/java/com/ararahq/arara/sdk/models/BatchMessageResponse.java b/src/main/java/com/ararahq/arara/sdk/models/BatchMessageResponse.java new file mode 100644 index 0000000..1ff3467 --- /dev/null +++ b/src/main/java/com/ararahq/arara/sdk/models/BatchMessageResponse.java @@ -0,0 +1,36 @@ +package com.ararahq.arara.sdk.models; + +import lombok.Builder; +import lombok.Value; +import lombok.extern.jackson.Jacksonized; + +import java.math.BigDecimal; +import java.util.List; + +/** + * Result of a batch send. + */ +@Value +@Builder +@Jacksonized +public class BatchMessageResponse { + String batchId; + String templateName; + int total; + int accepted; + BigDecimal totalCost; + List messages; + + /** + * Per-recipient outcome of a batch send. + */ + @Value + @Builder + @Jacksonized + public static class Item { + String id; + String receiver; + String status; + BigDecimal cost; + } +} diff --git a/src/main/java/com/ararahq/arara/sdk/models/CampaignDetail.java b/src/main/java/com/ararahq/arara/sdk/models/CampaignDetail.java new file mode 100644 index 0000000..faf8a10 --- /dev/null +++ b/src/main/java/com/ararahq/arara/sdk/models/CampaignDetail.java @@ -0,0 +1,54 @@ +package com.ararahq.arara.sdk.models; + +import lombok.Builder; +import lombok.Value; +import lombok.extern.jackson.Jacksonized; + +import java.math.BigDecimal; +import java.time.Instant; +import java.util.List; +import java.util.UUID; + +/** + * Full campaign detail returned by {@code GET /v1/campaigns/{id}}. + */ +@Value +@Builder +@Jacksonized +public class CampaignDetail { + UUID id; + String name; + String status; + String templateName; + String templateBody; + int totalMessages; + int sentCount; + int deliveredCount; + int readCount; + int failedCount; + int clickedCount; + int convertedCount; + BigDecimal convertedValue; + int replyCount; + int holdoutCount; + int blockedCount; + List blockReasons; + int refundCount; + BigDecimal refundValue; + BigDecimal totalCost; + Instant scheduledAt; + Instant startedAt; + Instant finishedAt; + Instant createdAt; + + /** + * Why contacts were blocked, in customer language ({@code motivo}) with a count ({@code quantidade}). + */ + @Value + @Builder + @Jacksonized + public static class BlockReason { + String motivo; + long quantidade; + } +} diff --git a/src/main/java/com/ararahq/arara/sdk/models/CampaignListItem.java b/src/main/java/com/ararahq/arara/sdk/models/CampaignListItem.java new file mode 100644 index 0000000..489c161 --- /dev/null +++ b/src/main/java/com/ararahq/arara/sdk/models/CampaignListItem.java @@ -0,0 +1,30 @@ +package com.ararahq.arara.sdk.models; + +import lombok.Builder; +import lombok.Value; +import lombok.extern.jackson.Jacksonized; + +import java.math.BigDecimal; +import java.time.Instant; +import java.util.UUID; + +/** + * Campaign summary returned by the campaign list. + */ +@Value +@Builder +@Jacksonized +public class CampaignListItem { + UUID id; + String name; + String status; + String templateName; + int totalMessages; + int sentCount; + int deliveredCount; + int readCount; + int failedCount; + BigDecimal totalCost; + Instant scheduledAt; + Instant createdAt; +} diff --git a/src/main/java/com/ararahq/arara/sdk/models/CampaignPage.java b/src/main/java/com/ararahq/arara/sdk/models/CampaignPage.java new file mode 100644 index 0000000..d4cbc00 --- /dev/null +++ b/src/main/java/com/ararahq/arara/sdk/models/CampaignPage.java @@ -0,0 +1,19 @@ +package com.ararahq.arara.sdk.models; + +import lombok.Builder; +import lombok.Value; +import lombok.extern.jackson.Jacksonized; + +import java.util.List; + +/** + * Page of campaigns: {@code {"content": [...], "totalPages", "totalElements"}}. + */ +@Value +@Builder +@Jacksonized +public class CampaignPage { + List content; + int totalPages; + long totalElements; +} diff --git a/src/main/java/com/ararahq/arara/sdk/models/CampaignRequest.java b/src/main/java/com/ararahq/arara/sdk/models/CampaignRequest.java index 913a93f..bc5c4d8 100644 --- a/src/main/java/com/ararahq/arara/sdk/models/CampaignRequest.java +++ b/src/main/java/com/ararahq/arara/sdk/models/CampaignRequest.java @@ -3,6 +3,7 @@ import lombok.Builder; import lombok.Value; import lombok.extern.jackson.Jacksonized; +import java.time.Instant; import java.util.List; /** @@ -16,4 +17,6 @@ public class CampaignRequest { String templateName; String sender; List contacts; + /** Optional schedule; null sends immediately. */ + Instant scheduledAt; } diff --git a/src/main/java/com/ararahq/arara/sdk/models/CampaignResponse.java b/src/main/java/com/ararahq/arara/sdk/models/CampaignResponse.java index e84f6dd..160b035 100644 --- a/src/main/java/com/ararahq/arara/sdk/models/CampaignResponse.java +++ b/src/main/java/com/ararahq/arara/sdk/models/CampaignResponse.java @@ -4,6 +4,7 @@ import lombok.Value; import lombok.extern.jackson.Jacksonized; import java.math.BigDecimal; +import java.time.Instant; import java.util.UUID; /** @@ -18,4 +19,6 @@ public class CampaignResponse { String status; int totalMessages; BigDecimal totalCost; + /** Scheduled start; null when sent immediately. */ + Instant scheduledAt; } diff --git a/src/main/java/com/ararahq/arara/sdk/models/CreateTemplateRequest.java b/src/main/java/com/ararahq/arara/sdk/models/CreateTemplateRequest.java index 3395568..9442545 100644 --- a/src/main/java/com/ararahq/arara/sdk/models/CreateTemplateRequest.java +++ b/src/main/java/com/ararahq/arara/sdk/models/CreateTemplateRequest.java @@ -21,6 +21,8 @@ public class CreateTemplateRequest { String language = "pt_BR"; String header; + /** Header type: TEXT, IMAGE, VIDEO or DOCUMENT. Required for media headers. */ + String headerType; String footer; List buttons; Map samples; diff --git a/src/main/java/com/ararahq/arara/sdk/models/MessageResponse.java b/src/main/java/com/ararahq/arara/sdk/models/MessageResponse.java index 2d67e5a..0a8d295 100644 --- a/src/main/java/com/ararahq/arara/sdk/models/MessageResponse.java +++ b/src/main/java/com/ararahq/arara/sdk/models/MessageResponse.java @@ -18,5 +18,8 @@ public class MessageResponse { String sender; String receiver; String body; + /** Cost of the message; null when not billed yet. */ BigDecimal cost; + /** Rejection or failure reason, when present. */ + String reason; } diff --git a/src/main/java/com/ararahq/arara/sdk/models/PaginatedResponse.java b/src/main/java/com/ararahq/arara/sdk/models/PaginatedResponse.java new file mode 100644 index 0000000..7dbb4d3 --- /dev/null +++ b/src/main/java/com/ararahq/arara/sdk/models/PaginatedResponse.java @@ -0,0 +1,21 @@ +package com.ararahq.arara.sdk.models; + +import lombok.Builder; +import lombok.Value; +import lombok.extern.jackson.Jacksonized; + +import java.util.List; + +/** + * Page envelope used by templates, smart links, flows and charges: + * {@code {"data": [...], "pagination": {page, size, totalElements, totalPages}}}. + * + * @param Item type. + */ +@Value +@Builder +@Jacksonized +public class PaginatedResponse { + List data; + Pagination pagination; +} diff --git a/src/main/java/com/ararahq/arara/sdk/models/GeneratedApiKey.java b/src/main/java/com/ararahq/arara/sdk/models/Pagination.java similarity index 51% rename from src/main/java/com/ararahq/arara/sdk/models/GeneratedApiKey.java rename to src/main/java/com/ararahq/arara/sdk/models/Pagination.java index cc3bde1..2607fc8 100644 --- a/src/main/java/com/ararahq/arara/sdk/models/GeneratedApiKey.java +++ b/src/main/java/com/ararahq/arara/sdk/models/Pagination.java @@ -5,11 +5,14 @@ import lombok.extern.jackson.Jacksonized; /** - * A freshly generated API key, shown once in plaintext. + * Pagination metadata of a {@link PaginatedResponse}. */ @Value @Builder @Jacksonized -public class GeneratedApiKey { - String plainTextKey; +public class Pagination { + int page; + int size; + long totalElements; + int totalPages; } diff --git a/src/main/java/com/ararahq/arara/sdk/models/UpdateUserRequest.java b/src/main/java/com/ararahq/arara/sdk/models/UpdateUserRequest.java deleted file mode 100644 index 71178c4..0000000 --- a/src/main/java/com/ararahq/arara/sdk/models/UpdateUserRequest.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.ararahq.arara.sdk.models; - -import lombok.Builder; -import lombok.Value; -import lombok.extern.jackson.Jacksonized; - -/** - * Payload for updating user profile information. - */ -@Value -@Builder -@Jacksonized -public class UpdateUserRequest { - String name; - String phoneNumber; -} diff --git a/src/main/java/com/ararahq/arara/sdk/models/UserResponse.java b/src/main/java/com/ararahq/arara/sdk/models/UserResponse.java index 81e4b42..7e4b767 100644 --- a/src/main/java/com/ararahq/arara/sdk/models/UserResponse.java +++ b/src/main/java/com/ararahq/arara/sdk/models/UserResponse.java @@ -5,7 +5,7 @@ import lombok.extern.jackson.Jacksonized; /** - * Basic user information returned by the API. + * Owner of the API key, returned by {@code GET /auth/me}. */ @Value @Builder @@ -14,7 +14,5 @@ public class UserResponse { String name; String email; String role; - String phoneNumber; - String documentNumber; - boolean needsInitialOnboarding; + boolean emailPending; } diff --git a/src/main/java/com/ararahq/arara/sdk/services/ApiKeyService.java b/src/main/java/com/ararahq/arara/sdk/services/ApiKeyService.java deleted file mode 100644 index 3e3cb7e..0000000 --- a/src/main/java/com/ararahq/arara/sdk/services/ApiKeyService.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.ararahq.arara.sdk.services; - -import com.ararahq.arara.sdk.http.AraraHttpClient; -import com.ararahq.arara.sdk.models.GeneratedApiKey; -import com.fasterxml.jackson.core.type.TypeReference; - -import java.util.List; -import java.util.Map; - -/** - * Service for managing API keys. - */ -public class ApiKeyService { - private static final String BASE = "/v1/api-keys"; - - private final AraraHttpClient httpClient; - - public ApiKeyService(AraraHttpClient httpClient) { - this.httpClient = httpClient; - } - - /** - * Lists API keys. GET /v1/api-keys - */ - public List> list() { - return httpClient.get(BASE, new TypeReference>>() { - }); - } - - /** - * Creates an API key. POST /v1/api-keys?mode=LIVE - */ - public GeneratedApiKey create(String mode) { - return httpClient.post(BASE + "?mode=" + mode, null, GeneratedApiKey.class); - } - - /** - * Creates a LIVE API key. POST /v1/api-keys?mode=LIVE - */ - public GeneratedApiKey create() { - return create("LIVE"); - } -} diff --git a/src/main/java/com/ararahq/arara/sdk/services/AuthService.java b/src/main/java/com/ararahq/arara/sdk/services/AuthService.java new file mode 100644 index 0000000..4a58fa0 --- /dev/null +++ b/src/main/java/com/ararahq/arara/sdk/services/AuthService.java @@ -0,0 +1,22 @@ +package com.ararahq.arara.sdk.services; + +import com.ararahq.arara.sdk.http.AraraHttpClient; +import com.ararahq.arara.sdk.models.UserResponse; + +/** + * Identity of the API key owner. Requires an ADMIN key. + */ +public class AuthService { + private final AraraHttpClient httpClient; + + public AuthService(AraraHttpClient httpClient) { + this.httpClient = httpClient; + } + + /** + * Returns the user that owns the API key. GET /auth/me + */ + public UserResponse me() { + return httpClient.get("/auth/me", UserResponse.class); + } +} diff --git a/src/main/java/com/ararahq/arara/sdk/services/CampaignService.java b/src/main/java/com/ararahq/arara/sdk/services/CampaignService.java index e7fc1a9..0597ba6 100644 --- a/src/main/java/com/ararahq/arara/sdk/services/CampaignService.java +++ b/src/main/java/com/ararahq/arara/sdk/services/CampaignService.java @@ -1,8 +1,12 @@ package com.ararahq.arara.sdk.services; import com.ararahq.arara.sdk.http.AraraHttpClient; +import com.ararahq.arara.sdk.models.CampaignContactRequest; +import com.ararahq.arara.sdk.models.CampaignDetail; +import com.ararahq.arara.sdk.models.CampaignPage; import com.ararahq.arara.sdk.models.CampaignRequest; import com.ararahq.arara.sdk.models.CampaignResponse; +import com.ararahq.arara.sdk.utils.QueryString; import com.ararahq.arara.sdk.utils.ValidationUtils; import java.util.UUID; @@ -11,6 +15,8 @@ * Service for managing bulk message campaigns. */ public class CampaignService { + private static final String BASE = "/v1/campaigns"; + private final AraraHttpClient httpClient; public CampaignService(AraraHttpClient httpClient) { @@ -18,25 +24,59 @@ public CampaignService(AraraHttpClient httpClient) { } /** - * Creates and starts a new message campaign. - * - * @param request Campaign data and contact list. - * @return Summary of the created campaign. + * Creates a campaign with an auto-generated Idempotency-Key (UUID v4), reused across retries. */ public CampaignResponse create(CampaignRequest request) { + return create(request, null); + } + + /** + * Creates and starts a new message campaign. POST /v1/campaigns + * + * @param request Campaign data and contact list. + * @param idempotencyKey Caller key; when null a UUID v4 is generated. + */ + public CampaignResponse create(CampaignRequest request, String idempotencyKey) { ValidationUtils.checkNotNull(request, "request"); ValidationUtils.checkNotNull(request.getContacts(), "contacts"); - request.getContacts().forEach(contact -> ValidationUtils.validateWhatsAppNumber(contact.getTo())); - return httpClient.post("/v1/campaigns", request, CampaignResponse.class); + for (int i = 0; i < request.getContacts().size(); i++) { + CampaignContactRequest contact = request.getContacts().get(i); + ValidationUtils.checkNotNull(contact, "contacts[" + i + "]"); + ValidationUtils.validateWhatsAppNumber(contact.getTo()); + } + return httpClient.post(BASE, request, MessageService.idempotencyHeaders(idempotencyKey), + CampaignResponse.class); } /** - * Retrieves campaign details by ID. + * Lists campaigns. GET /v1/campaigns * - * @param id Campaign identifier. - * @return Campaign status and metrics. + * @param page Zero-based page. + * @param size Page size. + * @param status Optional status filter. + */ + public CampaignPage list(int page, int size, String status) { + String path = QueryString.create() + .add("page", page) + .add("size", size) + .add("status", status) + .appendTo(BASE); + return httpClient.get(path, CampaignPage.class); + } + + /** + * Retrieves campaign details by ID. GET /v1/campaigns/{id} + */ + public CampaignDetail getById(UUID id) { + ValidationUtils.checkNotNull(id, "id"); + return httpClient.get(BASE + "/" + id, CampaignDetail.class); + } + + /** + * Cancels a scheduled or running campaign. POST /v1/campaigns/{id}/cancel */ - public CampaignResponse getById(UUID id) { - return httpClient.get("/v1/campaigns/" + id.toString(), CampaignResponse.class); + public void cancel(UUID id) { + ValidationUtils.checkNotNull(id, "id"); + httpClient.post(BASE + "/" + id + "/cancel", null, Void.class); } } diff --git a/src/main/java/com/ararahq/arara/sdk/services/ContactService.java b/src/main/java/com/ararahq/arara/sdk/services/ContactService.java index ee11ecf..c407b9d 100644 --- a/src/main/java/com/ararahq/arara/sdk/services/ContactService.java +++ b/src/main/java/com/ararahq/arara/sdk/services/ContactService.java @@ -9,6 +9,7 @@ import com.ararahq.arara.sdk.models.ContactsListResponse; import com.ararahq.arara.sdk.models.ContactsReactivationResponse; import com.ararahq.arara.sdk.models.ContactsStatsResponse; +import com.ararahq.arara.sdk.utils.QueryString; import com.ararahq.arara.sdk.utils.ValidationUtils; import com.fasterxml.jackson.core.type.TypeReference; @@ -29,14 +30,13 @@ public ContactService(AraraHttpClient httpClient) { * Lists contacts. GET /v1/contacts */ public ContactsListResponse list(int page, int size, String query, String lifecycle) { - StringBuilder path = new StringBuilder("/v1/contacts?page=").append(page).append("&size=").append(size); - if (query != null) { - path.append("&q=").append(query); - } - if (lifecycle != null) { - path.append("&lifecycle=").append(lifecycle); - } - return httpClient.get(path.toString(), ContactsListResponse.class); + String path = QueryString.create() + .add("page", page) + .add("size", size) + .add("q", query) + .add("lifecycle", lifecycle) + .appendTo("/v1/contacts"); + return httpClient.get(path, ContactsListResponse.class); } /** @@ -73,7 +73,7 @@ public Map> listTags() { * Retrieves a contact by phone. GET /v1/contacts/{phone} */ public ContactResponse get(String phone) { - return httpClient.get("/v1/contacts/" + phone, ContactResponse.class); + return httpClient.get("/v1/contacts/" + QueryString.encodePathSegment(phone), ContactResponse.class); } /** @@ -81,13 +81,13 @@ public ContactResponse get(String phone) { */ public ContactResponse update(String phone, ContactPatchRequest request) { ValidationUtils.checkNotNull(request, "request"); - return httpClient.patch("/v1/contacts/" + phone, request, ContactResponse.class); + return httpClient.patch("/v1/contacts/" + QueryString.encodePathSegment(phone), request, ContactResponse.class); } /** * Lists recent messages for a contact. GET /v1/contacts/{phone}/messages */ public ContactMessagesResponse messages(String phone, int limit) { - return httpClient.get("/v1/contacts/" + phone + "/messages?limit=" + limit, ContactMessagesResponse.class); + return httpClient.get("/v1/contacts/" + QueryString.encodePathSegment(phone) + "/messages?limit=" + limit, ContactMessagesResponse.class); } } diff --git a/src/main/java/com/ararahq/arara/sdk/services/ConversationService.java b/src/main/java/com/ararahq/arara/sdk/services/ConversationService.java index a55578f..8bf4b45 100644 --- a/src/main/java/com/ararahq/arara/sdk/services/ConversationService.java +++ b/src/main/java/com/ararahq/arara/sdk/services/ConversationService.java @@ -2,6 +2,7 @@ import com.ararahq.arara.sdk.http.AraraHttpClient; import com.ararahq.arara.sdk.models.ConversationReplyRequest; +import com.ararahq.arara.sdk.utils.QueryString; import com.ararahq.arara.sdk.utils.ValidationUtils; import com.fasterxml.jackson.core.type.TypeReference; @@ -26,14 +27,13 @@ public ConversationService(AraraHttpClient httpClient) { * Lists conversations. GET /v1/conversations */ public Map list(String status, String leadStatus, int page, int size) { - StringBuilder path = new StringBuilder("/v1/conversations?page=").append(page).append("&size=").append(size); - if (status != null) { - path.append("&status=").append(status); - } - if (leadStatus != null) { - path.append("&leadStatus=").append(leadStatus); - } - return httpClient.get(path.toString(), MAP_TYPE); + String path = QueryString.create() + .add("page", page) + .add("size", size) + .add("status", status) + .add("leadStatus", leadStatus) + .appendTo("/v1/conversations"); + return httpClient.get(path, MAP_TYPE); } /** @@ -48,7 +48,9 @@ public Map leadStats() { */ public Map messages(String conversationId, int page, int size) { return httpClient.get( - "/v1/conversations/" + conversationId + "/messages?page=" + page + "&size=" + size, MAP_TYPE); + QueryString.create().add("page", page).add("size", size) + .appendTo("/v1/conversations/" + QueryString.encodePathSegment(conversationId) + "/messages"), + MAP_TYPE); } /** @@ -64,7 +66,7 @@ public Map reply(ConversationReplyRequest request) { */ public Map updateStatus(String conversationId, String status) { return httpClient.patch( - "/v1/conversations/" + conversationId + "/status", Map.of("status", status), MAP_TYPE); + "/v1/conversations/" + QueryString.encodePathSegment(conversationId) + "/status", Map.of("status", status), MAP_TYPE); } /** diff --git a/src/main/java/com/ararahq/arara/sdk/services/MessageService.java b/src/main/java/com/ararahq/arara/sdk/services/MessageService.java index 660ad91..ec3d236 100644 --- a/src/main/java/com/ararahq/arara/sdk/services/MessageService.java +++ b/src/main/java/com/ararahq/arara/sdk/services/MessageService.java @@ -1,14 +1,34 @@ package com.ararahq.arara.sdk.services; +import com.ararahq.arara.sdk.exceptions.AraraApiException; +import com.ararahq.arara.sdk.exceptions.AraraAuthException; +import com.ararahq.arara.sdk.exceptions.AraraException; import com.ararahq.arara.sdk.http.AraraHttpClient; +import com.ararahq.arara.sdk.interceptors.RetryInterceptor; +import com.ararahq.arara.sdk.models.AraraError; +import com.ararahq.arara.sdk.models.BatchMessageRequest; +import com.ararahq.arara.sdk.models.BatchMessageResponse; import com.ararahq.arara.sdk.models.MessageResponse; import com.ararahq.arara.sdk.models.SendMessageRequest; +import com.ararahq.arara.sdk.utils.QueryString; import com.ararahq.arara.sdk.utils.ValidationUtils; +import com.fasterxml.jackson.core.type.TypeReference; + +import java.util.List; +import java.util.Map; +import java.util.UUID; /** - * Service for managing WhatsApp messages. + * Service for sending and reading WhatsApp messages. */ public class MessageService { + private static final int MAX_BATCH_SIZE = 1000; + private static final int HTTP_FORBIDDEN = 403; + public static final String MESSAGE_NOT_FOUND_CODE = "NOT_FOUND"; + private static final TypeReference> MESSAGE_LIST_TYPE = + new TypeReference>() { + }; + private final AraraHttpClient httpClient; public MessageService(AraraHttpClient httpClient) { @@ -16,24 +36,91 @@ public MessageService(AraraHttpClient httpClient) { } /** - * Sends a message (template or free text). - * - * @param request The send payload following API rules. - * @return Details of the sent message, including ID and initial status. + * Sends a message with an auto-generated Idempotency-Key (UUID v4), reused across retries. */ public MessageResponse send(SendMessageRequest request) { + return send(request, null); + } + + /** + * Sends a message (template or free text). POST /v1/messages + * + * @param request The send payload. + * @param idempotencyKey Caller key; when null a UUID v4 is generated. Reuse it to retry safely. + * @return The accepted message (HTTP 202). + */ + public MessageResponse send(SendMessageRequest request, String idempotencyKey) { ValidationUtils.checkNotNull(request, "request"); ValidationUtils.validateWhatsAppNumber(request.getReceiver()); - return httpClient.post("/v1/messages", request, MessageResponse.class); + return httpClient.post("/v1/messages", request, idempotencyHeaders(idempotencyKey), MessageResponse.class); + } + + /** + * Sends one template to up to 1000 recipients, with an auto-generated Idempotency-Key. + */ + public BatchMessageResponse sendBatch(BatchMessageRequest request) { + return sendBatch(request, null); } /** - * Retrieves message details by ID. + * Sends one template to up to 1000 recipients. POST /v1/messages/batch * - * @param id The unique message identifier. - * @return Complete message details. + * @param request Template name and recipients. + * @param idempotencyKey Caller key; when null a UUID v4 is generated. + */ + public BatchMessageResponse sendBatch( + BatchMessageRequest request, String idempotencyKey) { + ValidationUtils.checkNotNull(request, "request"); + ValidationUtils.checkNotNull(request.getMessages(), "messages"); + if (request.getMessages().size() > MAX_BATCH_SIZE) { + throw new AraraException( + "Batch accepts at most " + MAX_BATCH_SIZE + " messages."); + } + for (int i = 0; i < request.getMessages().size(); i++) { + BatchMessageRequest.BatchMessageItem item = request.getMessages().get(i); + ValidationUtils.checkNotNull(item, "messages[" + i + "]"); + ValidationUtils.validateWhatsAppNumber(item.getReceiver()); + } + return httpClient.post("/v1/messages/batch", request, idempotencyHeaders(idempotencyKey), + BatchMessageResponse.class); + } + + /** + * Retrieves message details by ID. GET /v1/messages/{id} + * The API answers 403 with an empty body when the message belongs to another account, so an + * empty 403 here is raised as {@link AraraApiException} with code {@code NOT_FOUND} (status kept 403). */ public MessageResponse getById(String id) { - return httpClient.get("/v1/messages/" + id, MessageResponse.class); + ValidationUtils.checkNotNull(id, "id"); + try { + return httpClient.get("/v1/messages/" + QueryString.encodePathSegment(id), MessageResponse.class); + } catch (AraraAuthException e) { + if (e.getStatusCode() != HTTP_FORBIDDEN || e.getErrorDetails() != null) { + throw e; + } + throw new AraraApiException(HTTP_FORBIDDEN, AraraError.builder() + .code(MESSAGE_NOT_FOUND_CODE) + .message("Message " + id + " not found for this API key.") + .build()); + } + } + + /** + * Lists the messages of a batch. GET /v1/messages?batchId= + */ + public List listByBatch(String batchId) { + ValidationUtils.checkNotNull(batchId, "batchId"); + return httpClient.get(QueryString.create().add("batchId", batchId).appendTo("/v1/messages"), + MESSAGE_LIST_TYPE); + } + + static Map idempotencyHeaders(String idempotencyKey) { + if (idempotencyKey == null) { + return Map.of(RetryInterceptor.IDEMPOTENCY_KEY_HEADER, UUID.randomUUID().toString()); + } + if (idempotencyKey.isBlank()) { + throw new AraraException("Idempotency key cannot be blank. Pass null to let the SDK generate one."); + } + return Map.of(RetryInterceptor.IDEMPOTENCY_KEY_HEADER, idempotencyKey.trim()); } } diff --git a/src/main/java/com/ararahq/arara/sdk/services/OptOutService.java b/src/main/java/com/ararahq/arara/sdk/services/OptOutService.java new file mode 100644 index 0000000..66dd472 --- /dev/null +++ b/src/main/java/com/ararahq/arara/sdk/services/OptOutService.java @@ -0,0 +1,62 @@ +package com.ararahq.arara.sdk.services; + +import com.ararahq.arara.sdk.http.AraraHttpClient; +import com.ararahq.arara.sdk.utils.QueryString; +import com.ararahq.arara.sdk.utils.ValidationUtils; +import com.fasterxml.jackson.core.type.TypeReference; + +import java.util.HashMap; +import java.util.Map; + +/** + * Channel opt-outs (numbers that must not receive messages). Requires an ADMIN key. + */ +public class OptOutService { + private static final String BASE = "/v1/opt-outs"; + private static final TypeReference> MAP_TYPE = + new TypeReference>() { + }; + + private final AraraHttpClient httpClient; + + public OptOutService(AraraHttpClient httpClient) { + this.httpClient = httpClient; + } + + /** + * Lists opt-outs. GET /v1/opt-outs + */ + public Map list() { + return httpClient.get(BASE, MAP_TYPE); + } + + /** + * Registers an opt-out. POST /v1/opt-outs + * + * @param phone Phone number to block. + * @param reason Optional reason. + */ + public Map add(String phone, String reason) { + ValidationUtils.checkNotNull(phone, "phone"); + Map body = new HashMap<>(); + body.put("phone", phone); + body.put("reason", reason); + return httpClient.post(BASE, body, MAP_TYPE); + } + + /** + * Returns the opt-out state of a number. GET /v1/opt-outs/{phone} + */ + public Map get(String phone) { + ValidationUtils.checkNotNull(phone, "phone"); + return httpClient.get(BASE + "/" + QueryString.encodePathSegment(phone), MAP_TYPE); + } + + /** + * Removes an opt-out. DELETE /v1/opt-outs/{phone} + */ + public Map remove(String phone) { + ValidationUtils.checkNotNull(phone, "phone"); + return httpClient.delete(BASE + "/" + QueryString.encodePathSegment(phone), MAP_TYPE); + } +} diff --git a/src/main/java/com/ararahq/arara/sdk/services/SmartLinkService.java b/src/main/java/com/ararahq/arara/sdk/services/SmartLinkService.java index e58ff09..7f4e9b1 100644 --- a/src/main/java/com/ararahq/arara/sdk/services/SmartLinkService.java +++ b/src/main/java/com/ararahq/arara/sdk/services/SmartLinkService.java @@ -2,12 +2,13 @@ import com.ararahq.arara.sdk.http.AraraHttpClient; import com.ararahq.arara.sdk.models.CreateWhatsAppSmartLinkRequest; +import com.ararahq.arara.sdk.models.PaginatedResponse; import com.ararahq.arara.sdk.models.UpdateWhatsAppSmartLinkRequest; import com.ararahq.arara.sdk.models.WhatsAppSmartLinkResponse; +import com.ararahq.arara.sdk.utils.QueryString; import com.ararahq.arara.sdk.utils.ValidationUtils; import com.fasterxml.jackson.core.type.TypeReference; -import java.util.List; import java.util.Map; /** @@ -34,15 +35,27 @@ public WhatsAppSmartLinkResponse create(CreateWhatsAppSmartLinkRequest request) * Updates a smart link. PUT /v1/smart-links/whatsapp/{id} */ public WhatsAppSmartLinkResponse update(String id, UpdateWhatsAppSmartLinkRequest request) { + ValidationUtils.checkNotNull(id, "id"); ValidationUtils.checkNotNull(request, "request"); - return httpClient.put(BASE + "/" + id, request, WhatsAppSmartLinkResponse.class); + return httpClient.put(BASE + "/" + QueryString.encodePathSegment(id), request, WhatsAppSmartLinkResponse.class); } /** * Lists smart links. GET /v1/smart-links/whatsapp */ - public List list() { - return httpClient.get(BASE, new TypeReference>() { + public PaginatedResponse list() { + return list(null, null); + } + + /** + * Lists smart links with pagination. GET /v1/smart-links/whatsapp + * + * @param page Optional zero-based page. + * @param size Optional page size. + */ + public PaginatedResponse list(Integer page, Integer size) { + String path = QueryString.create().add("page", page).add("size", size).appendTo(BASE); + return httpClient.get(path, new TypeReference>() { }); } @@ -50,7 +63,8 @@ public List list() { * Returns click stats for a smart link. GET /v1/smart-links/whatsapp/{id}/stats */ public Map stats(String id) { - return httpClient.get(BASE + "/" + id + "/stats", new TypeReference>() { + ValidationUtils.checkNotNull(id, "id"); + return httpClient.get(BASE + "/" + QueryString.encodePathSegment(id) + "/stats", new TypeReference>() { }); } } diff --git a/src/main/java/com/ararahq/arara/sdk/services/TemplateService.java b/src/main/java/com/ararahq/arara/sdk/services/TemplateService.java index 9bb0040..7670568 100644 --- a/src/main/java/com/ararahq/arara/sdk/services/TemplateService.java +++ b/src/main/java/com/ararahq/arara/sdk/services/TemplateService.java @@ -2,18 +2,29 @@ import com.ararahq.arara.sdk.http.AraraHttpClient; import com.ararahq.arara.sdk.models.CreateTemplateRequest; +import com.ararahq.arara.sdk.models.PaginatedResponse; import com.ararahq.arara.sdk.models.TemplateResponse; import com.ararahq.arara.sdk.models.TemplateStatusResponse; +import com.ararahq.arara.sdk.utils.QueryString; import com.ararahq.arara.sdk.utils.ValidationUtils; +import com.fasterxml.jackson.core.type.TypeReference; -import java.util.Arrays; -import java.util.List; +import java.util.Map; import java.util.UUID; /** - * Service for managing WhatsApp templates. + * Service for managing WhatsApp templates. Single-template operations take the template id (UUID), + * never the name: to find by name, use {@link #list(String, String, Integer, Integer)} with the name filter. */ public class TemplateService { + private static final String BASE = "/v1/templates"; + private static final TypeReference> PAGE_TYPE = + new TypeReference>() { + }; + private static final TypeReference> MAP_TYPE = + new TypeReference>() { + }; + private final AraraHttpClient httpClient; public TemplateService(AraraHttpClient httpClient) { @@ -21,55 +32,77 @@ public TemplateService(AraraHttpClient httpClient) { } /** - * Creates and submits a new template to Meta. - * - * @param request The template definition. - * @return The created template details. + * Creates and submits a new template to Meta. POST /v1/templates */ public TemplateResponse create(CreateTemplateRequest request) { ValidationUtils.checkNotNull(request, "request"); - return httpClient.post("/v1/templates", request, TemplateResponse.class); + return httpClient.post(BASE, request, TemplateResponse.class); } /** - * Lists all templates for the authenticated account. - * - * @return A list of templates. + * Lists the first page of templates with the API defaults. GET /v1/templates */ - public List list() { - TemplateResponse[] templates = httpClient.get("/v1/templates", TemplateResponse[].class); - return templates != null ? Arrays.asList(templates) : List.of(); + public PaginatedResponse list() { + return list(null, null, null, null); } /** - * Retrieves a specific template by ID. + * Lists templates. GET /v1/templates * - * @param id The template UUID. - * @return Template details. + * @param name Optional name filter. + * @param status Optional status filter (e.g. APPROVED). + * @param page Optional zero-based page. + * @param size Optional page size. + */ + public PaginatedResponse list(String name, String status, Integer page, Integer size) { + String path = QueryString.create() + .add("name", name) + .add("status", status) + .add("page", page) + .add("size", size) + .appendTo(BASE); + return httpClient.get(path, PAGE_TYPE); + } + + /** + * Retrieves a template by id. GET /v1/templates/{id} */ public TemplateResponse getById(UUID id) { ValidationUtils.checkNotNull(id, "id"); - return httpClient.get("/v1/templates/" + id, TemplateResponse.class); + return httpClient.get(BASE + "/" + id, TemplateResponse.class); } /** - * Deletes a template. - * - * @param id The template UUID. + * Deletes a template by id. DELETE /v1/templates/{id} */ public void delete(UUID id) { ValidationUtils.checkNotNull(id, "id"); - httpClient.delete("/v1/templates/" + id); + httpClient.delete(BASE + "/" + id); } /** - * Checks and refreshes the approval status of a template. - * - * @param id The template UUID. - * @return Current approval status from provider. + * Refreshes and returns the approval status of a template. GET /v1/templates/{id}/status */ public TemplateStatusResponse getStatus(UUID id) { ValidationUtils.checkNotNull(id, "id"); - return httpClient.get("/v1/templates/" + id + "/status", TemplateStatusResponse.class); + return httpClient.get(BASE + "/" + id + "/status", TemplateStatusResponse.class); + } + + /** + * Aggregated analytics of all templates. GET /v1/templates/analytics + * + * @param period Optional window (e.g. 7d, 30d); API default is 30d. + */ + public Map analytics(String period) { + return httpClient.get(QueryString.create().add("period", period).appendTo(BASE + "/analytics"), MAP_TYPE); + } + + /** + * Analytics of one template. GET /v1/templates/{id}/analytics + */ + public Map analytics(UUID id, String period) { + ValidationUtils.checkNotNull(id, "id"); + return httpClient.get( + QueryString.create().add("period", period).appendTo(BASE + "/" + id + "/analytics"), MAP_TYPE); } } diff --git a/src/main/java/com/ararahq/arara/sdk/services/UserService.java b/src/main/java/com/ararahq/arara/sdk/services/UserService.java deleted file mode 100644 index daf8352..0000000 --- a/src/main/java/com/ararahq/arara/sdk/services/UserService.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.ararahq.arara.sdk.services; - -import com.ararahq.arara.sdk.http.AraraHttpClient; -import com.ararahq.arara.sdk.models.UpdateUserRequest; -import com.ararahq.arara.sdk.models.UserResponse; - -/** - * Service for managing users and profile information. - */ -public class UserService { - private final AraraHttpClient httpClient; - - public UserService(AraraHttpClient httpClient) { - this.httpClient = httpClient; - } - - /** - * Returns the currently authenticated user's data. - * - * @return Logged-in user's profile. - */ - public UserResponse me() { - return httpClient.get("/users/me", UserResponse.class); - } - - /** - * Updates the currently authenticated user's profile. - * - * @param request The update payload (name, phoneNumber). - * @return The updated user profile. - */ - public UserResponse updateMe(UpdateUserRequest request) { - return httpClient.patch("/users/me", request, UserResponse.class); - } -} diff --git a/src/main/java/com/ararahq/arara/sdk/utils/QueryString.java b/src/main/java/com/ararahq/arara/sdk/utils/QueryString.java new file mode 100644 index 0000000..d60dcc7 --- /dev/null +++ b/src/main/java/com/ararahq/arara/sdk/utils/QueryString.java @@ -0,0 +1,50 @@ +package com.ararahq.arara.sdk.utils; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; + +/** + * Builds a URL-encoded query string, skipping null values. + */ +public final class QueryString { + private final StringBuilder builder = new StringBuilder(); + + private QueryString() { + } + + public static QueryString create() { + return new QueryString(); + } + + /** + * Appends a parameter when the value is not null. + */ + public QueryString add(String name, Object value) { + if (value == null) { + return this; + } + builder.append(builder.length() == 0 ? '?' : '&') + .append(encode(name)) + .append('=') + .append(encode(String.valueOf(value))); + return this; + } + + /** + * @return The path with the encoded query string appended. + */ + public String appendTo(String path) { + return path + builder; + } + + /** + * Encodes a single path segment (e.g. a phone number with '+'). + */ + public static String encodePathSegment(String segment) { + return encode(segment).replace("+", "%20"); + } + + private static String encode(String value) { + return URLEncoder.encode(value, StandardCharsets.UTF_8); + } +} diff --git a/src/main/java/com/ararahq/arara/sdk/utils/ValidationUtils.java b/src/main/java/com/ararahq/arara/sdk/utils/ValidationUtils.java index a8b8c54..61c573b 100644 --- a/src/main/java/com/ararahq/arara/sdk/utils/ValidationUtils.java +++ b/src/main/java/com/ararahq/arara/sdk/utils/ValidationUtils.java @@ -5,21 +5,33 @@ /** * Utility methods for quick validations in the SDK. */ -public class ValidationUtils { +public final class ValidationUtils { + private static final String WHATSAPP_PREFIX = "whatsapp:"; + private static final int MIN_PHONE_DIGITS = 7; + private static final int MAX_PHONE_DIGITS = 15; private ValidationUtils() { - // Utility class should not be instantiated } /** - * Validates if the phone number follows the expected Arara/WhatsApp pattern. + * Validates a recipient number with the same rule as the API: accepts + * {@code whatsapp:+5511999998888}, {@code +5511999998888} or only digits. + * The {@code whatsapp:} prefix is dropped, non-digits are ignored and 7 to 15 digits must remain. * * @param phoneNumber The number to be validated. * @throws AraraException if the number is invalid. */ public static void validateWhatsAppNumber(String phoneNumber) { - if (phoneNumber == null || !phoneNumber.startsWith("whatsapp:+")) { - throw new AraraException("Invalid phone number. Must start with 'whatsapp:+'"); + if (phoneNumber == null || phoneNumber.isBlank()) { + throw new AraraException("Invalid phone number. Receiver is required."); + } + String withoutPrefix = phoneNumber.trim().startsWith(WHATSAPP_PREFIX) + ? phoneNumber.trim().substring(WHATSAPP_PREFIX.length()) + : phoneNumber; + long digits = withoutPrefix.chars().filter(Character::isDigit).count(); + if (digits < MIN_PHONE_DIGITS || digits > MAX_PHONE_DIGITS) { + throw new AraraException("Invalid phone number '" + phoneNumber + + "'. Use E.164 digits, e.g. +5511999998888, 5511999998888 or whatsapp:+5511999998888."); } } diff --git a/src/test/java/com/ararahq/arara/sdk/AraraTest.java b/src/test/java/com/ararahq/arara/sdk/AraraTest.java index e923bac..245dbf4 100644 --- a/src/test/java/com/ararahq/arara/sdk/AraraTest.java +++ b/src/test/java/com/ararahq/arara/sdk/AraraTest.java @@ -19,7 +19,8 @@ void shouldInitializeServices() { .build(); assertNotNull(arara.getMessages()); - assertNotNull(arara.getUsers()); + assertNotNull(arara.getAuth()); + assertNotNull(arara.getOptOuts()); assertNotNull(arara.getCampaigns()); assertNotNull(arara.getTemplates()); } @@ -46,4 +47,10 @@ void shouldBuildWithTimeoutsAndRetries() { assertNotNull(arara.getMessages()); assertNotNull(arara.getCampaigns()); } + + @Test + @DisplayName("should reject a blank API key") + void shouldRejectBlankApiKey() { + assertThrows(RuntimeException.class, () -> Arara.builder().apiKey(" ").build()); + } } diff --git a/src/test/java/com/ararahq/arara/sdk/http/AraraHttpClientTest.java b/src/test/java/com/ararahq/arara/sdk/http/AraraHttpClientTest.java index aba0231..e29101e 100644 --- a/src/test/java/com/ararahq/arara/sdk/http/AraraHttpClientTest.java +++ b/src/test/java/com/ararahq/arara/sdk/http/AraraHttpClientTest.java @@ -5,10 +5,12 @@ import com.ararahq.arara.sdk.exceptions.AraraAuthException; import com.ararahq.arara.sdk.exceptions.AraraNetworkException; import com.ararahq.arara.sdk.exceptions.AraraRateLimitException; +import com.ararahq.arara.sdk.exceptions.PlanFeatureLockedException; import com.fasterxml.jackson.core.type.TypeReference; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import okhttp3.mockwebserver.RecordedRequest; +import okhttp3.mockwebserver.SocketPolicy; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; @@ -20,6 +22,7 @@ import java.util.Map; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -81,6 +84,147 @@ void shouldHandle401() { assertThrows(AraraAuthException.class, () -> client.get("test", TestResponse.class)); } + @Test + @DisplayName("should map 403 without error code to auth exception") + void shouldMap403WithoutCodeToAuth() { + mockWebServer.enqueue(new MockResponse().setResponseCode(403)); + + AraraAuthException exception = assertThrows(AraraAuthException.class, + () -> client.get("test", TestResponse.class)); + + assertEquals(403, exception.getStatusCode()); + assertNull(exception.getCode()); + } + + @Test + @DisplayName("should map 403 PLAN_FEATURE_LOCKED to typed exception with details") + void shouldMapPlanFeatureLocked() { + mockWebServer.enqueue(new MockResponse() + .setResponseCode(403) + .setBody("{\"error\":{\"code\":\"PLAN_FEATURE_LOCKED\"," + + "\"message\":\"Essa feature está liberada a partir do plano VOO.\"," + + "\"details\":{\"feature\":\"canUseFlows\",\"currentPlan\":\"DECOLAGEM\"," + + "\"upgradeTo\":\"VOO\"}}}")); + + PlanFeatureLockedException exception = assertThrows(PlanFeatureLockedException.class, + () -> client.get("test", TestResponse.class)); + + assertEquals(403, exception.getStatusCode()); + assertEquals("PLAN_FEATURE_LOCKED", exception.getCode()); + assertEquals("canUseFlows", exception.getFeature()); + assertEquals("DECOLAGEM", exception.getCurrentPlan()); + assertEquals("VOO", exception.getUpgradeTo()); + } + + @Test + @DisplayName("should keep 403 with business code as API exception, not auth") + void shouldKeep403WithCodeAsApiException() { + mockWebServer.enqueue(new MockResponse() + .setResponseCode(403) + .setBody("{\"error\":{\"code\":\"NO_DEDICATED_NUMBER\",\"message\":\"x\",\"details\":{}}}")); + + AraraApiException exception = assertThrows(AraraApiException.class, + () -> client.get("test", TestResponse.class)); + + assertFalse(exception instanceof AraraAuthException); + assertFalse(exception instanceof PlanFeatureLockedException); + assertEquals("NO_DEDICATED_NUMBER", exception.getCode()); + assertTrue(exception.getDetails().isEmpty()); + } + + @Test + @DisplayName("should treat Spring default 403 body as auth failure") + void shouldTreatSpringDefault403AsAuth() { + mockWebServer.enqueue(new MockResponse() + .setResponseCode(403) + .setBody("{\"timestamp\":\"2026-09-24T00:00:00Z\",\"status\":403," + + "\"error\":\"Forbidden\",\"path\":\"/v1/wallet\"}")); + + AraraAuthException exception = assertThrows(AraraAuthException.class, + () -> client.get("test", TestResponse.class)); + + assertEquals("Forbidden", exception.getMessage()); + } + + @Test + @DisplayName("should expose Retry-After on 503") + void shouldExposeRetryAfterOn503() { + mockWebServer.enqueue(new MockResponse() + .setResponseCode(503) + .setHeader("Retry-After", "12") + .setBody("{\"error\":{\"code\":\"SEND_TEMPORARILY_UNAVAILABLE\",\"message\":\"x\"}}")); + + AraraApiException exception = assertThrows(AraraApiException.class, + () -> client.get("test", TestResponse.class)); + + assertEquals(Duration.ofSeconds(12), exception.getRetryAfter()); + assertEquals("SEND_TEMPORARILY_UNAVAILABLE", exception.getCode()); + } + + @Test + @DisplayName("should never retry POST without Idempotency-Key") + void shouldNotRetryPostWithoutIdempotencyKey() { + AraraHttpClient retryingClient = clientWithRetries(3); + mockWebServer.enqueue(new MockResponse().setResponseCode(500)); + + assertThrows(AraraApiException.class, + () -> retryingClient.post("test", Map.of("k", "v"), TestResponse.class)); + assertEquals(1, mockWebServer.getRequestCount()); + } + + @Test + @DisplayName("should never retry PATCH on network failure") + void shouldNotRetryPatchOnNetworkFailure() throws IOException { + AraraHttpClient retryingClient = clientWithRetries(3); + mockWebServer.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_AT_START)); + + assertThrows(AraraNetworkException.class, + () -> retryingClient.patch("test", Map.of("k", "v"), TestResponse.class)); + assertEquals(1, mockWebServer.getRequestCount()); + } + + @Test + @DisplayName("should retry POST with Idempotency-Key keeping the same key") + void shouldRetryPostWithIdempotencyKey() throws InterruptedException { + AraraHttpClient retryingClient = clientWithRetries(1); + mockWebServer.enqueue(new MockResponse().setResponseCode(502)); + mockWebServer.enqueue(new MockResponse().setResponseCode(200).setBody("{\"name\":\"Ok\"}")); + + TestResponse response = retryingClient.post("test", Map.of("k", "v"), + Map.of("Idempotency-Key", "abc"), TestResponse.class); + + assertEquals("Ok", response.name); + assertEquals("abc", mockWebServer.takeRequest().getHeader("Idempotency-Key")); + assertEquals("abc", mockWebServer.takeRequest().getHeader("Idempotency-Key")); + } + + @Test + @DisplayName("should join base URL without trailing slash and path") + void shouldJoinBaseUrlWithoutTrailingSlash() throws InterruptedException { + String base = mockWebServer.url("/").toString(); + AraraHttpClient noSlash = new AraraHttpClient(AraraConfig.builder() + .baseUrl(base.substring(0, base.length() - 1)).apiKey("k").maxRetries(0).build()); + mockWebServer.enqueue(new MockResponse().setResponseCode(200).setBody("{\"name\":\"a\"}")); + mockWebServer.enqueue(new MockResponse().setResponseCode(200).setBody("{\"name\":\"b\"}")); + + noSlash.get("/v1/x", TestResponse.class); + noSlash.get("v1/y", TestResponse.class); + + assertEquals("/v1/x", mockWebServer.takeRequest().getPath()); + assertEquals("/v1/y", mockWebServer.takeRequest().getPath()); + } + + @Test + @DisplayName("should DELETE with generic response type") + void shouldDeleteWithTypeReference() { + mockWebServer.enqueue(new MockResponse().setResponseCode(200).setBody("{\"removed\":true}")); + + Map response = client.delete("test", new TypeReference>() { + }); + + assertEquals(true, response.get("removed")); + } + @Test @DisplayName("should handle 400 Bad Request") void shouldHandle400() { @@ -355,6 +499,53 @@ void shouldPropagateDeleteError() { assertThrows(AraraApiException.class, () -> client.delete("test/1")); } + @Test + @DisplayName("should retry POST with Idempotency-Key after connection drop, same key and body") + void shouldRetryPostAfterDisconnectWithSameKeyAndBody() throws InterruptedException { + AraraHttpClient retryingClient = clientWithRetries(1); + mockWebServer.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_AFTER_REQUEST)); + mockWebServer.enqueue(new MockResponse().setResponseCode(200).setBody("{\"name\":\"Ok\"}")); + + TestResponse response = retryingClient.post("test", Map.of("k", "v"), + Map.of("Idempotency-Key", "key-1"), TestResponse.class); + + RecordedRequest first = mockWebServer.takeRequest(); + RecordedRequest second = mockWebServer.takeRequest(); + assertEquals("Ok", response.name); + assertEquals("key-1", first.getHeader("Idempotency-Key")); + assertEquals("key-1", second.getHeader("Idempotency-Key")); + assertEquals(first.getBody().readUtf8(), second.getBody().readUtf8()); + } + + @Test + @DisplayName("should not wait on Retry-After above the cap and surface it") + void shouldNotRetryWhenRetryAfterAboveCap() { + AraraHttpClient retryingClient = clientWithRetries(3); + mockWebServer.enqueue(new MockResponse().setResponseCode(429).setHeader("Retry-After", "3600")); + + long start = System.nanoTime(); + AraraRateLimitException exception = assertThrows(AraraRateLimitException.class, + () -> retryingClient.get("test", TestResponse.class)); + + assertTrue(Duration.ofNanos(System.nanoTime() - start).getSeconds() < 5); + assertEquals(1, mockWebServer.getRequestCount()); + assertEquals(Duration.ofSeconds(3600), exception.getRetryAfter()); + } + + @Test + @DisplayName("should not take a flat non-code error as code") + void shouldIgnoreFlatNonCodeError() { + mockWebServer.enqueue(new MockResponse() + .setResponseCode(403) + .setBody("{\"error\":\"Forbidden\",\"message\":\"Access Denied\"}")); + + AraraAuthException exception = assertThrows(AraraAuthException.class, + () -> client.get("test", TestResponse.class)); + + assertNull(exception.getCode()); + assertEquals("Access Denied", exception.getMessage()); + } + static class TestResponse { public String name; diff --git a/src/test/java/com/ararahq/arara/sdk/services/ApiKeyServiceTest.java b/src/test/java/com/ararahq/arara/sdk/services/ApiKeyServiceTest.java deleted file mode 100644 index dd0befc..0000000 --- a/src/test/java/com/ararahq/arara/sdk/services/ApiKeyServiceTest.java +++ /dev/null @@ -1,78 +0,0 @@ -package com.ararahq.arara.sdk.services; - -import com.ararahq.arara.sdk.http.AraraHttpClient; -import com.ararahq.arara.sdk.models.GeneratedApiKey; -import com.fasterxml.jackson.core.type.TypeReference; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; - -import java.util.Arrays; -import java.util.List; -import java.util.Map; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.ArgumentMatchers.isNull; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -@ExtendWith(MockitoExtension.class) -@DisplayName("ApiKeyService Tests") -class ApiKeyServiceTest { - - private static final String BASE = "/v1/api-keys"; - - @Mock - private AraraHttpClient httpClient; - - private ApiKeyService apiKeyService; - - @BeforeEach - void setUp() { - apiKeyService = new ApiKeyService(httpClient); - } - - @Test - @DisplayName("should list API keys") - void shouldListApiKeys() { - List> expected = Arrays.asList(Map.of("id", "key_1")); - when(httpClient.get(eq(BASE), any(TypeReference.class))).thenReturn(expected); - - List> result = apiKeyService.list(); - - assertEquals(1, result.size()); - verify(httpClient, times(1)).get(eq(BASE), any(TypeReference.class)); - } - - @Test - @DisplayName("should create an API key with an explicit mode") - void shouldCreateWithMode() { - GeneratedApiKey expected = GeneratedApiKey.builder().plainTextKey("ara_live_abc").build(); - when(httpClient.post(eq(BASE + "?mode=TEST"), isNull(), eq(GeneratedApiKey.class))) - .thenReturn(expected); - - GeneratedApiKey result = apiKeyService.create("TEST"); - - assertEquals("ara_live_abc", result.getPlainTextKey()); - verify(httpClient, times(1)).post(eq(BASE + "?mode=TEST"), isNull(), eq(GeneratedApiKey.class)); - } - - @Test - @DisplayName("should create a LIVE API key by default") - void shouldCreateLiveByDefault() { - GeneratedApiKey expected = GeneratedApiKey.builder().plainTextKey("ara_live_xyz").build(); - when(httpClient.post(eq(BASE + "?mode=LIVE"), isNull(), eq(GeneratedApiKey.class))) - .thenReturn(expected); - - GeneratedApiKey result = apiKeyService.create(); - - assertEquals("ara_live_xyz", result.getPlainTextKey()); - verify(httpClient, times(1)).post(eq(BASE + "?mode=LIVE"), isNull(), eq(GeneratedApiKey.class)); - } -} diff --git a/src/test/java/com/ararahq/arara/sdk/services/AuthServiceTest.java b/src/test/java/com/ararahq/arara/sdk/services/AuthServiceTest.java new file mode 100644 index 0000000..89ee13d --- /dev/null +++ b/src/test/java/com/ararahq/arara/sdk/services/AuthServiceTest.java @@ -0,0 +1,37 @@ +package com.ararahq.arara.sdk.services; + +import com.ararahq.arara.sdk.exceptions.AraraAuthException; +import com.ararahq.arara.sdk.models.UserResponse; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@DisplayName("AuthService against fake API") +class AuthServiceTest extends FakeApi { + + @Test + @DisplayName("should GET /auth/me without the /v1 prefix and parse the user") + void shouldGetMe() throws Exception { + respond(200, "{\"name\":\"Ana\",\"email\":\"ana@loja.com\",\"role\":\"ADMIN\",\"emailPending\":false}"); + + UserResponse me = arara.getAuth().me(); + + take("GET", "/auth/me"); + assertEquals("ana@loja.com", me.getEmail()); + assertEquals("ADMIN", me.getRole()); + } + + @Test + @DisplayName("should raise auth error when the key is not ADMIN (403 without envelope)") + void shouldRaiseAuthErrorForNonAdminKey() { + respond(403, "{\"timestamp\":\"2026-09-24T00:00:00Z\",\"status\":403,\"error\":\"Forbidden\"," + + "\"message\":\"API Key permission insufficient\",\"path\":\"/auth/me\"}"); + + AraraAuthException error = assertThrows(AraraAuthException.class, () -> arara.getAuth().me()); + + assertEquals(403, error.getStatusCode()); + assertEquals("API Key permission insufficient", error.getMessage()); + } +} diff --git a/src/test/java/com/ararahq/arara/sdk/services/CampaignServiceTest.java b/src/test/java/com/ararahq/arara/sdk/services/CampaignServiceTest.java index 0509d90..5dd7517 100644 --- a/src/test/java/com/ararahq/arara/sdk/services/CampaignServiceTest.java +++ b/src/test/java/com/ararahq/arara/sdk/services/CampaignServiceTest.java @@ -1,240 +1,160 @@ package com.ararahq.arara.sdk.services; +import com.ararahq.arara.sdk.Arara; +import com.ararahq.arara.sdk.exceptions.AraraApiException; import com.ararahq.arara.sdk.exceptions.AraraException; -import com.ararahq.arara.sdk.http.AraraHttpClient; import com.ararahq.arara.sdk.models.CampaignContactRequest; +import com.ararahq.arara.sdk.models.CampaignDetail; +import com.ararahq.arara.sdk.models.CampaignPage; import com.ararahq.arara.sdk.models.CampaignRequest; import com.ararahq.arara.sdk.models.CampaignResponse; -import org.junit.jupiter.api.BeforeEach; +import com.fasterxml.jackson.databind.JsonNode; +import okhttp3.mockwebserver.RecordedRequest; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; + import java.math.BigDecimal; +import java.time.Instant; import java.util.Arrays; +import java.util.List; import java.util.UUID; + import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoInteractions; -import static org.mockito.Mockito.when; - -/** - * Unit tests for CampaignService. - */ -@ExtendWith(MockitoExtension.class) -@DisplayName("CampaignService Tests") -class CampaignServiceTest { - @Mock - private AraraHttpClient httpClient; - private CampaignService campaignService; - - @BeforeEach - void setUp() { - campaignService = new CampaignService(httpClient); - } - - @Test - @DisplayName("should create campaign successfully") - void shouldCreateCampaignSuccessfully() { - // Arrange - CampaignContactRequest contact = CampaignContactRequest.builder() - .to("whatsapp:+5511999998888") - .build(); - CampaignRequest request = CampaignRequest.builder() - .name("Birthday Campaign") - .templateName("birthday_greeting") - .sender("whatsapp:+551140001000") - .contacts(Arrays.asList(contact)) - .build(); - UUID campaignId = UUID.randomUUID(); - CampaignResponse expectedResponse = CampaignResponse.builder() - .id(campaignId) - .name("Birthday Campaign") - .status("ACTIVE") - .totalMessages(1) - .totalCost(BigDecimal.valueOf(0.05)) - .build(); - when(httpClient.post("/v1/campaigns", request, CampaignResponse.class)) - .thenReturn(expectedResponse); - // Act - CampaignResponse result = campaignService.create(request); - // Assert - assertNotNull(result); - assertEquals(campaignId, result.getId()); - assertEquals("Birthday Campaign", result.getName()); - assertEquals("ACTIVE", result.getStatus()); - verify(httpClient, times(1)).post("/v1/campaigns", request, CampaignResponse.class); - } - - @Test - @DisplayName("should create campaign with multiple contacts") - void shouldCreateCampaignWithMultipleContacts() { - // Arrange - CampaignContactRequest contact1 = CampaignContactRequest.builder() - .to("whatsapp:+5511999998888") - .build(); - CampaignContactRequest contact2 = CampaignContactRequest.builder() - .to("whatsapp:+5511988887777") - .build(); - CampaignRequest request = CampaignRequest.builder() - .name("Newsletter Campaign") - .templateName("newsletter_template") - .sender("whatsapp:+551140001000") - .contacts(Arrays.asList(contact1, contact2)) - .build(); - UUID campaignId = UUID.randomUUID(); - CampaignResponse expectedResponse = CampaignResponse.builder() - .id(campaignId) - .name("Newsletter Campaign") - .status("ACTIVE") - .totalMessages(2) - .totalCost(BigDecimal.valueOf(0.10)) - .build(); - when(httpClient.post("/v1/campaigns", request, CampaignResponse.class)) - .thenReturn(expectedResponse); - // Act - CampaignResponse result = campaignService.create(request); - // Assert - assertNotNull(result); - assertEquals(2, result.getTotalMessages()); - assertEquals(BigDecimal.valueOf(0.10), result.getTotalCost()); - } - - @Test - @DisplayName("should retrieve campaign by ID successfully") - void shouldRetrieveCampaignByIdSuccessfully() { - // Arrange - UUID campaignId = UUID.randomUUID(); - CampaignResponse expectedResponse = CampaignResponse.builder() - .id(campaignId) - .name("Test Campaign") - .status("ACTIVE") - .totalMessages(100) - .totalCost(BigDecimal.valueOf(5.00)) - .build(); - when(httpClient.get("/v1/campaigns/" + campaignId.toString(), CampaignResponse.class)) - .thenReturn(expectedResponse); - // Act - CampaignResponse result = campaignService.getById(campaignId); - // Assert - assertNotNull(result); - assertEquals(campaignId, result.getId()); - assertEquals("Test Campaign", result.getName()); - assertEquals("ACTIVE", result.getStatus()); - verify(httpClient, times(1)).get("/v1/campaigns/" + campaignId.toString(), CampaignResponse.class); - } - - @Test - @DisplayName("should call correct endpoint with UUID") - void shouldCallCorrectEndpointWithUUID() { - // Arrange - UUID campaignId = UUID.randomUUID(); - CampaignResponse mockResponse = CampaignResponse.builder() - .id(campaignId) - .name("Test") - .status("ACTIVE") - .totalMessages(1) - .totalCost(BigDecimal.ZERO) - .build(); - when(httpClient.get("/v1/campaigns/" + campaignId.toString(), CampaignResponse.class)) - .thenReturn(mockResponse); - // Act - campaignService.getById(campaignId); - // Assert - verify(httpClient, times(1)).get("/v1/campaigns/" + campaignId.toString(), CampaignResponse.class); - } - - @Test - @DisplayName("should reject null campaign request") - void shouldRejectNullCampaignRequest() { - assertThrows(AraraException.class, () -> campaignService.create(null)); - verifyNoInteractions(httpClient); - } - - @Test - @DisplayName("should reject campaign without contacts") - void shouldRejectCampaignWithoutContacts() { - CampaignRequest request = CampaignRequest.builder() - .name("No Contacts Campaign") - .templateName("template") - .sender("whatsapp:+551140001000") - .build(); - - assertThrows(AraraException.class, () -> campaignService.create(request)); - verifyNoInteractions(httpClient); - } - - @Test - @DisplayName("should reject contact without whatsapp prefix") - void shouldRejectContactWithoutWhatsappPrefix() { - CampaignContactRequest invalidContact = CampaignContactRequest.builder() - .to("+5511999998888") - .build(); - CampaignRequest request = CampaignRequest.builder() - .name("Invalid Contact Campaign") - .templateName("template") - .sender("whatsapp:+551140001000") - .contacts(Arrays.asList(invalidContact)) - .build(); - - assertThrows(AraraException.class, () -> campaignService.create(request)); - verifyNoInteractions(httpClient); - } - - @Test - @DisplayName("should reject campaign when any contact is invalid") - void shouldRejectCampaignWhenAnyContactIsInvalid() { - CampaignContactRequest validContact = CampaignContactRequest.builder() - .to("whatsapp:+5511999998888") - .build(); - CampaignContactRequest invalidContact = CampaignContactRequest.builder() - .to("5511988887777") - .build(); - CampaignRequest request = CampaignRequest.builder() - .name("Mixed Contacts Campaign") - .templateName("template") - .sender("whatsapp:+551140001000") - .contacts(Arrays.asList(validContact, invalidContact)) - .build(); - - assertThrows(AraraException.class, () -> campaignService.create(request)); - verifyNoInteractions(httpClient); - } - - @Test - @DisplayName("should create then retrieve campaign") - void shouldCreateThenRetrieveCampaign() { - // Arrange - UUID campaignId = UUID.randomUUID(); - CampaignRequest createRequest = CampaignRequest.builder() - .name("Integration Campaign") - .templateName("template") - .sender("whatsapp:+551140001000") - .contacts(Arrays.asList( - CampaignContactRequest.builder() - .to("whatsapp:+5511999998888") - .build())) - .build(); - CampaignResponse createResponse = CampaignResponse.builder() - .id(campaignId) - .name("Integration Campaign") - .status("ACTIVE") - .totalMessages(1) - .totalCost(BigDecimal.valueOf(0.05)) - .build(); - when(httpClient.post("/v1/campaigns", createRequest, CampaignResponse.class)) - .thenReturn(createResponse); - when(httpClient.get("/v1/campaigns/" + campaignId.toString(), CampaignResponse.class)) - .thenReturn(createResponse); - // Act - CampaignResponse created = campaignService.create(createRequest); - CampaignResponse retrieved = campaignService.getById(created.getId()); - // Assert - assertEquals(campaignId, created.getId()); - assertEquals(created.getId(), retrieved.getId()); - } +import static org.junit.jupiter.api.Assertions.assertTrue; + +@DisplayName("CampaignService against fake API") +class CampaignServiceTest extends FakeApi { + private static final UUID ID = UUID.fromString("7f1c1c1e-0000-4000-8000-000000000001"); + private static final String CREATED = "{\"id\":\"" + ID + "\",\"name\":\"Black Friday\"," + + "\"status\":\"PROCESSING\",\"totalMessages\":1,\"totalCost\":0.05}"; + + private CampaignRequest request(String to) { + return CampaignRequest.builder() + .name("Black Friday") + .templateName("promo") + .contacts(List.of(CampaignContactRequest.builder().to(to).variables(List.of("Ana")).build())) + .build(); + } + + @Test + @DisplayName("should POST /v1/campaigns with contacts in 'to' and a generated Idempotency-Key") + void shouldCreateCampaign() throws Exception { + respond(200, CREATED); + + CampaignResponse response = arara.getCampaigns().create(request("5511999998888")); + + RecordedRequest recorded = take("POST", "/v1/campaigns"); + JsonNode body = json(recorded); + assertEquals("5511999998888", body.get("contacts").get(0).get("to").asText()); + assertNotNull(UUID.fromString(recorded.getHeader("Idempotency-Key"))); + assertEquals(ID, response.getId()); + } + + @Test + @DisplayName("should use caller key and reuse it on retry after 5xx") + void shouldReuseCallerKeyOnRetry() throws Exception { + Arara retrying = client(1); + respond(500, "{\"error\":{\"code\":\"INTERNAL_SERVER_ERROR\",\"message\":\"x\",\"details\":{}}}"); + respond(200, CREATED); + + retrying.getCampaigns().create(request("+5511999998888"), "camp-1"); + + assertEquals("camp-1", take("POST", "/v1/campaigns").getHeader("Idempotency-Key")); + assertEquals("camp-1", take("POST", "/v1/campaigns").getHeader("Idempotency-Key")); + } + + @Test + @DisplayName("should reject invalid contact phone locally") + void shouldRejectInvalidContact() { + assertThrows(AraraException.class, () -> arara.getCampaigns().create(request("12"))); + assertThrows(AraraException.class, () -> arara.getCampaigns().create(null)); + assertEquals(0, server.getRequestCount()); + } + + @Test + @DisplayName("should GET /v1/campaigns and parse {content,totalPages,totalElements}") + void shouldListCampaigns() throws Exception { + respond(200, "{\"content\":[{\"id\":\"" + ID + "\",\"name\":\"BF\",\"status\":\"DONE\"," + + "\"templateName\":\"promo\",\"totalMessages\":10,\"sentCount\":10," + + "\"scheduledAt\":\"2026-11-27T12:00:00Z\",\"createdAt\":\"2026-11-20T09:00:00Z\"}]," + + "\"totalPages\":3,\"totalElements\":21}"); + + CampaignPage page = arara.getCampaigns().list(0, 10, "DONE"); + + take("GET", "/v1/campaigns?page=0&size=10&status=DONE"); + assertEquals(21, page.getTotalElements()); + assertEquals("promo", page.getContent().get(0).getTemplateName()); + assertEquals(Instant.parse("2026-11-27T12:00:00Z"), page.getContent().get(0).getScheduledAt()); + assertEquals(Instant.parse("2026-11-20T09:00:00Z"), page.getContent().get(0).getCreatedAt()); + } + + @Test + @DisplayName("should GET /v1/campaigns/{id} and parse the full detail") + void shouldGetCampaignDetail() throws Exception { + respond(200, "{\"id\":\"" + ID + "\",\"name\":\"BF\",\"status\":\"DONE\",\"templateName\":\"promo\"," + + "\"totalMessages\":10,\"sentCount\":9,\"deliveredCount\":8,\"readCount\":5,\"failedCount\":1," + + "\"clickedCount\":3,\"convertedCount\":2,\"convertedValue\":199.90,\"blockedCount\":1," + + "\"blockReasons\":[{\"motivo\":\"Pediu para sair\",\"quantidade\":1}],\"refundCount\":1," + + "\"refundValue\":0.05,\"totalCost\":0.45,\"startedAt\":\"2026-11-27T12:00:00Z\"," + + "\"finishedAt\":\"2026-11-27T12:05:00Z\"}"); + + CampaignDetail detail = arara.getCampaigns().getById(ID); + + take("GET", "/v1/campaigns/" + ID); + assertEquals("promo", detail.getTemplateName()); + assertEquals(8, detail.getDeliveredCount()); + assertEquals(3, detail.getClickedCount()); + assertEquals(2, detail.getConvertedCount()); + assertEquals("Pediu para sair", detail.getBlockReasons().get(0).getMotivo()); + assertEquals(new BigDecimal("0.05"), detail.getRefundValue()); + assertEquals(Instant.parse("2026-11-27T12:05:00Z"), detail.getFinishedAt()); + } + + @Test + @DisplayName("should parse scheduledAt on create response") + void shouldParseScheduledAt() throws Exception { + respond(200, "{\"id\":\"" + ID + "\",\"status\":\"SCHEDULED\",\"scheduledAt\":\"2026-11-27T12:00:00Z\"}"); + + CampaignResponse response = arara.getCampaigns().create(request("5511999998888")); + + take("POST", "/v1/campaigns"); + assertEquals(Instant.parse("2026-11-27T12:00:00Z"), response.getScheduledAt()); + } + + @Test + @DisplayName("should reject a null contact with its index") + void shouldRejectNullContact() { + CampaignRequest request = CampaignRequest.builder().name("x").templateName("t") + .contacts(Arrays.asList(CampaignContactRequest.builder().to("5511999998888").build(), null)) + .build(); + + AraraException error = assertThrows(AraraException.class, () -> arara.getCampaigns().create(request)); + + assertTrue(error.getMessage().contains("contacts[1]")); + assertEquals(0, server.getRequestCount()); + } + + @Test + @DisplayName("should POST /v1/campaigns/{id}/cancel without retrying") + void shouldCancelCampaign() throws Exception { + Arara retrying = client(2); + respond(500, ""); + + assertThrows(AraraApiException.class, () -> retrying.getCampaigns().cancel(ID)); + + take("POST", "/v1/campaigns/" + ID + "/cancel"); + assertEquals(1, server.getRequestCount()); + } + + @Test + @DisplayName("should cancel successfully on 200") + void shouldCancelSuccessfully() throws Exception { + server.enqueue(new okhttp3.mockwebserver.MockResponse().setResponseCode(200)); + + arara.getCampaigns().cancel(ID); + + take("POST", "/v1/campaigns/" + ID + "/cancel"); + } } diff --git a/src/test/java/com/ararahq/arara/sdk/services/ContactServiceTest.java b/src/test/java/com/ararahq/arara/sdk/services/ContactServiceTest.java index 4f5c996..3a36d22 100644 --- a/src/test/java/com/ararahq/arara/sdk/services/ContactServiceTest.java +++ b/src/test/java/com/ararahq/arara/sdk/services/ContactServiceTest.java @@ -1,203 +1,74 @@ package com.ararahq.arara.sdk.services; -import com.ararahq.arara.sdk.exceptions.AraraException; -import com.ararahq.arara.sdk.http.AraraHttpClient; -import com.ararahq.arara.sdk.models.ContactMessagesResponse; import com.ararahq.arara.sdk.models.ContactPatchRequest; import com.ararahq.arara.sdk.models.ContactRequest; -import com.ararahq.arara.sdk.models.ContactResponse; -import com.ararahq.arara.sdk.models.ContactsBatchResponse; import com.ararahq.arara.sdk.models.ContactsListResponse; -import com.ararahq.arara.sdk.models.ContactsReactivationResponse; -import com.ararahq.arara.sdk.models.ContactsStatsResponse; -import com.fasterxml.jackson.core.type.TypeReference; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; -import java.util.Arrays; import java.util.List; import java.util.Map; -import java.util.UUID; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoInteractions; -import static org.mockito.Mockito.when; - -@ExtendWith(MockitoExtension.class) -@DisplayName("ContactService Tests") -class ContactServiceTest { - - @Mock - private AraraHttpClient httpClient; - - private ContactService contactService; - - @BeforeEach - void setUp() { - contactService = new ContactService(httpClient); - } - - @Test - @DisplayName("should list contacts with base pagination when filters are null") - void shouldListContactsWithoutFilters() { - ContactsListResponse expected = ContactsListResponse.builder() - .total(0) - .page(0) - .size(20) - .build(); - when(httpClient.get("/v1/contacts?page=0&size=20", ContactsListResponse.class)) - .thenReturn(expected); - - ContactsListResponse result = contactService.list(0, 20, null, null); - - assertNotNull(result); - verify(httpClient, times(1)).get("/v1/contacts?page=0&size=20", ContactsListResponse.class); - } - - @Test - @DisplayName("should append query and lifecycle filters to the path") - void shouldListContactsWithFilters() { - String path = "/v1/contacts?page=1&size=10&q=john&lifecycle=engaged"; - ContactsListResponse expected = ContactsListResponse.builder().total(5).build(); - when(httpClient.get(path, ContactsListResponse.class)).thenReturn(expected); - ContactsListResponse result = contactService.list(1, 10, "john", "engaged"); - - assertEquals(5, result.getTotal()); - verify(httpClient, times(1)).get(path, ContactsListResponse.class); - } +@DisplayName("ContactService against fake API") +class ContactServiceTest extends FakeApi { + private static final String CONTACT = "{\"name\":\"Ana\",\"phone\":\"+5511999998888\",\"lifecycle\":\"ENGAGED\"}"; @Test - @DisplayName("should import a batch of contacts") - void shouldImportBatch() { - List contacts = Arrays.asList( - ContactRequest.builder().name("Ana").phone("+5511999998888").build()); - ContactsBatchResponse expected = ContactsBatchResponse.builder() - .importId(UUID.randomUUID()) - .created(1) - .build(); - when(httpClient.post("/v1/contacts/batch", contacts, ContactsBatchResponse.class)) - .thenReturn(expected); - - ContactsBatchResponse result = contactService.importBatch(contacts); - - assertEquals(1, result.getCreated()); - verify(httpClient, times(1)).post("/v1/contacts/batch", contacts, ContactsBatchResponse.class); - } + @DisplayName("should URL-encode q and lifecycle on GET /v1/contacts") + void shouldEncodeQuery() throws Exception { + respond(200, "{\"contacts\":[" + CONTACT + "],\"total\":1,\"page\":0,\"size\":20,\"totalPages\":1}"); - @Test - @DisplayName("should reject null batch import") - void shouldRejectNullBatch() { - assertThrows(AraraException.class, () -> contactService.importBatch(null)); - verifyNoInteractions(httpClient); - } + ContactsListResponse page = arara.getContacts().list(0, 20, "a&b #1", "ENGAGED"); - @Test - @DisplayName("should return aggregate contact stats") - void shouldReturnStats() { - ContactsStatsResponse expected = ContactsStatsResponse.builder() - .total(100) - .engaged(40) - .build(); - when(httpClient.get("/v1/contacts/stats", ContactsStatsResponse.class)).thenReturn(expected); - - ContactsStatsResponse result = contactService.stats(); - - assertEquals(100, result.getTotal()); - verify(httpClient, times(1)).get("/v1/contacts/stats", ContactsStatsResponse.class); + take("GET", "/v1/contacts?page=0&size=20&q=a%26b+%231&lifecycle=ENGAGED"); + assertEquals("Ana", page.getContacts().get(0).getName()); } @Test - @DisplayName("should list reactivation candidates with limit") - void shouldListReactivationCandidates() { - ContactsReactivationResponse expected = ContactsReactivationResponse.builder().total(3).build(); - when(httpClient.get("/v1/contacts/reactivation?limit=25", ContactsReactivationResponse.class)) - .thenReturn(expected); + @DisplayName("should omit null filters") + void shouldOmitNullFilters() throws Exception { + respond(200, "{\"contacts\":[],\"total\":0}"); - ContactsReactivationResponse result = contactService.reactivationCandidates(25); + arara.getContacts().list(1, 5, null, null); - assertEquals(3, result.getTotal()); - verify(httpClient, times(1)) - .get("/v1/contacts/reactivation?limit=25", ContactsReactivationResponse.class); - } - - @Test - @DisplayName("should list distinct contact tags") - void shouldListTags() { - Map> expected = Map.of("tags", Arrays.asList("vip", "lead")); - when(httpClient.get(eq("/v1/contacts/tags"), any(TypeReference.class))).thenReturn(expected); - - Map> result = contactService.listTags(); - - assertEquals(Arrays.asList("vip", "lead"), result.get("tags")); - verify(httpClient, times(1)).get(eq("/v1/contacts/tags"), any(TypeReference.class)); - } - - @Test - @DisplayName("should retrieve a contact by phone") - void shouldGetContactByPhone() { - ContactResponse expected = ContactResponse.builder() - .id(UUID.randomUUID()) - .phone("+5511999998888") - .name("Ana") - .build(); - when(httpClient.get("/v1/contacts/+5511999998888", ContactResponse.class)).thenReturn(expected); - - ContactResponse result = contactService.get("+5511999998888"); - - assertEquals("Ana", result.getName()); - verify(httpClient, times(1)).get("/v1/contacts/+5511999998888", ContactResponse.class); - } - - @Test - @DisplayName("should patch a contact by phone") - void shouldUpdateContact() { - ContactPatchRequest request = ContactPatchRequest.builder() - .name("Ana Maria") - .tags(Arrays.asList("vip")) - .build(); - ContactResponse expected = ContactResponse.builder().name("Ana Maria").build(); - when(httpClient.patch("/v1/contacts/+5511999998888", request, ContactResponse.class)) - .thenReturn(expected); - - ContactResponse result = contactService.update("+5511999998888", request); - - assertEquals("Ana Maria", result.getName()); - verify(httpClient, times(1)) - .patch("/v1/contacts/+5511999998888", request, ContactResponse.class); + take("GET", "/v1/contacts?page=1&size=5"); } @Test - @DisplayName("should reject null patch request") - void shouldRejectNullUpdate() { - assertThrows(AraraException.class, () -> contactService.update("+5511999998888", null)); - verifyNoInteractions(httpClient); + @DisplayName("should encode the phone path segment on get, update and messages") + void shouldEncodePhonePath() throws Exception { + respond(200, CONTACT); + respond(200, CONTACT); + respond(200, "{\"phone\":\"+5511999998888\",\"total\":0,\"messages\":[]}"); + + arara.getContacts().get("+5511999998888"); + arara.getContacts().update("+5511999998888", ContactPatchRequest.builder().tags(List.of("vip")).build()); + arara.getContacts().messages("+5511999998888", 10); + + take("GET", "/v1/contacts/%2B5511999998888"); + assertEquals("vip", json(take("PATCH", "/v1/contacts/%2B5511999998888")).get("tags").get(0).asText()); + take("GET", "/v1/contacts/%2B5511999998888/messages?limit=10"); } @Test - @DisplayName("should list recent messages for a contact") - void shouldListContactMessages() { - ContactMessagesResponse expected = ContactMessagesResponse.builder() - .phone("+5511999998888") - .total(2) - .build(); - when(httpClient.get("/v1/contacts/+5511999998888/messages?limit=50", ContactMessagesResponse.class)) - .thenReturn(expected); - - ContactMessagesResponse result = contactService.messages("+5511999998888", 50); - - assertEquals(2, result.getTotal()); - verify(httpClient, times(1)) - .get("/v1/contacts/+5511999998888/messages?limit=50", ContactMessagesResponse.class); + @DisplayName("should import batch, read stats, reactivation and tags") + void shouldCoverAggregates() throws Exception { + respond(200, "{\"created\":1,\"updated\":0,\"skipped\":0,\"errors\":[]}"); + respond(200, "{\"total\":10,\"engaged\":4}"); + respond(200, "{\"total\":1,\"candidates\":[]}"); + respond(200, "{\"tags\":[\"vip\"]}"); + + assertEquals(1, arara.getContacts().importBatch(List.of(ContactRequest.builder() + .name("Ana").phone("5511999998888").attributes(Map.of()).build())).getCreated()); + assertEquals(4, arara.getContacts().stats().getEngaged()); + assertEquals(1, arara.getContacts().reactivationCandidates(50).getTotal()); + assertEquals(List.of("vip"), arara.getContacts().listTags().get("tags")); + + assertEquals("Ana", json(take("POST", "/v1/contacts/batch")).get(0).get("name").asText()); + take("GET", "/v1/contacts/stats"); + take("GET", "/v1/contacts/reactivation?limit=50"); + take("GET", "/v1/contacts/tags"); } } diff --git a/src/test/java/com/ararahq/arara/sdk/services/ConversationServiceTest.java b/src/test/java/com/ararahq/arara/sdk/services/ConversationServiceTest.java index cf8c616..00fcf22 100644 --- a/src/test/java/com/ararahq/arara/sdk/services/ConversationServiceTest.java +++ b/src/test/java/com/ararahq/arara/sdk/services/ConversationServiceTest.java @@ -1,157 +1,52 @@ package com.ararahq.arara.sdk.services; -import com.ararahq.arara.sdk.exceptions.AraraException; -import com.ararahq.arara.sdk.http.AraraHttpClient; import com.ararahq.arara.sdk.models.ConversationReplyRequest; -import com.fasterxml.jackson.core.type.TypeReference; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; -import java.util.Arrays; import java.util.List; -import java.util.Map; import java.util.UUID; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoInteractions; -import static org.mockito.Mockito.when; -@ExtendWith(MockitoExtension.class) -@DisplayName("ConversationService Tests") -class ConversationServiceTest { - - @Mock - private AraraHttpClient httpClient; - - private ConversationService conversationService; - - @BeforeEach - void setUp() { - conversationService = new ConversationService(httpClient); - } - - @Test - @DisplayName("should list conversations with base pagination when filters are null") - void shouldListWithoutFilters() { - Map expected = Map.of("data", Arrays.asList()); - when(httpClient.get(eq("/v1/conversations?page=0&size=20"), any(TypeReference.class))) - .thenReturn(expected); - - Map result = conversationService.list(null, null, 0, 20); - - assertNotNull(result); - verify(httpClient, times(1)).get(eq("/v1/conversations?page=0&size=20"), any(TypeReference.class)); - } +@DisplayName("ConversationService against fake API") +class ConversationServiceTest extends FakeApi { + private static final String CONV = "c0ffee00-3333-4000-8000-000000000004"; @Test - @DisplayName("should append status and leadStatus filters to the path") - void shouldListWithFilters() { - String path = "/v1/conversations?page=1&size=15&status=OPEN&leadStatus=HOT"; - Map expected = Map.of("total", 4); - when(httpClient.get(eq(path), any(TypeReference.class))).thenReturn(expected); + @DisplayName("should list with encoded filters and read lead stats") + void shouldListAndStats() throws Exception { + respond(200, "{\"content\":[],\"total\":0}"); + respond(200, "{\"HOT\":2}"); + respond(200, "{\"content\":[]}"); - Map result = conversationService.list("OPEN", "HOT", 1, 15); + arara.getConversations().list("OPEN", "HOT & WARM", 0, 20); + assertEquals(2, arara.getConversations().leadStats().get("HOT")); + arara.getConversations().list(null, null, 1, 5); - assertEquals(4, result.get("total")); - verify(httpClient, times(1)).get(eq(path), any(TypeReference.class)); + take("GET", "/v1/conversations?page=0&size=20&status=OPEN&leadStatus=HOT+%26+WARM"); + take("GET", "/v1/conversations/lead-stats"); + take("GET", "/v1/conversations?page=1&size=5"); } @Test - @DisplayName("should return lead counts by status") - void shouldReturnLeadStats() { - Map expected = Map.of("HOT", 2); - when(httpClient.get(eq("/v1/conversations/lead-stats"), any(TypeReference.class))) - .thenReturn(expected); + @DisplayName("should read messages, reply, update status and check window") + void shouldCoverConversationActions() throws Exception { + respond(200, "{\"messages\":[]}"); + respond(200, "{\"ok\":true}"); + respond(200, "{\"status\":\"CLOSED\"}"); + respond(200, "{\"5511999998888\":\"OPEN\"}"); - Map result = conversationService.leadStats(); - - assertEquals(2, result.get("HOT")); - verify(httpClient, times(1)).get(eq("/v1/conversations/lead-stats"), any(TypeReference.class)); - } - - @Test - @DisplayName("should list messages of a conversation") - void shouldListMessages() { - String path = "/v1/conversations/conv_1/messages?page=0&size=30"; - Map expected = Map.of("total", 12); - when(httpClient.get(eq(path), any(TypeReference.class))).thenReturn(expected); - - Map result = conversationService.messages("conv_1", 0, 30); - - assertEquals(12, result.get("total")); - verify(httpClient, times(1)).get(eq(path), any(TypeReference.class)); - } - - @Test - @DisplayName("should send a free-text reply") - void shouldReply() { - ConversationReplyRequest request = ConversationReplyRequest.builder() - .conversationId(UUID.randomUUID()) - .body("Hi there") - .build(); - Map expected = Map.of("status", "SENT"); - when(httpClient.post(eq("/v1/conversations/reply"), eq(request), any(TypeReference.class))) - .thenReturn(expected); + arara.getConversations().messages(CONV, 0, 50); + arara.getConversations().reply(ConversationReplyRequest.builder() + .conversationId(UUID.fromString(CONV)).body("Oi").build()); + arara.getConversations().updateStatus(CONV, "CLOSED"); + assertEquals("OPEN", arara.getConversations().windowStatus(List.of("5511999998888")).get("5511999998888")); - Map result = conversationService.reply(request); - - assertEquals("SENT", result.get("status")); - verify(httpClient, times(1)) - .post(eq("/v1/conversations/reply"), eq(request), any(TypeReference.class)); - } - - @Test - @DisplayName("should reject null reply request") - void shouldRejectNullReply() { - assertThrows(AraraException.class, () -> conversationService.reply(null)); - verifyNoInteractions(httpClient); - } - - @Test - @DisplayName("should update a conversation status") - void shouldUpdateStatus() { - Map expected = Map.of("status", "CLOSED"); - when(httpClient.patch( - eq("/v1/conversations/conv_9/status"), eq(Map.of("status", "CLOSED")), any(TypeReference.class))) - .thenReturn(expected); - - Map result = conversationService.updateStatus("conv_9", "CLOSED"); - - assertEquals("CLOSED", result.get("status")); - verify(httpClient, times(1)).patch( - eq("/v1/conversations/conv_9/status"), eq(Map.of("status", "CLOSED")), any(TypeReference.class)); - } - - @Test - @DisplayName("should check 24h window status for phones") - void shouldCheckWindowStatus() { - List phones = Arrays.asList("+5511999998888", "+5511988887777"); - Map expected = Map.of("open", 1); - when(httpClient.post( - eq("/v1/conversations/window-status"), eq(Map.of("phones", phones)), any(TypeReference.class))) - .thenReturn(expected); - - Map result = conversationService.windowStatus(phones); - - assertEquals(1, result.get("open")); - verify(httpClient, times(1)).post( - eq("/v1/conversations/window-status"), eq(Map.of("phones", phones)), any(TypeReference.class)); - } - - @Test - @DisplayName("should reject null phones list for window status") - void shouldRejectNullPhones() { - assertThrows(AraraException.class, () -> conversationService.windowStatus(null)); - verifyNoInteractions(httpClient); + take("GET", "/v1/conversations/" + CONV + "/messages?page=0&size=50"); + assertEquals("Oi", json(take("POST", "/v1/conversations/reply")).get("body").asText()); + assertEquals("CLOSED", json(take("PATCH", "/v1/conversations/" + CONV + "/status")).get("status").asText()); + assertEquals("5511999998888", + json(take("POST", "/v1/conversations/window-status")).get("phones").get(0).asText()); } } diff --git a/src/test/java/com/ararahq/arara/sdk/services/FakeApi.java b/src/test/java/com/ararahq/arara/sdk/services/FakeApi.java new file mode 100644 index 0000000..e464678 --- /dev/null +++ b/src/test/java/com/ararahq/arara/sdk/services/FakeApi.java @@ -0,0 +1,68 @@ +package com.ararahq.arara.sdk.services; + +import com.ararahq.arara.sdk.Arara; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import okhttp3.mockwebserver.MockResponse; +import okhttp3.mockwebserver.MockWebServer; +import okhttp3.mockwebserver.RecordedRequest; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; + +import java.io.IOException; +import java.util.concurrent.TimeUnit; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +/** + * Base for service tests: runs the real SDK against a fake HTTP server. + */ +abstract class FakeApi { + static final String API_KEY = "ara_live_test"; + private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final long TAKE_TIMEOUT_SECONDS = 2; + + MockWebServer server; + Arara arara; + + @BeforeEach + void startServer() throws IOException { + server = new MockWebServer(); + server.start(); + arara = client(0); + } + + @AfterEach + void stopServer() throws IOException { + server.shutdown(); + } + + Arara client(int maxRetries) { + return Arara.builder() + .apiKey(API_KEY) + .baseUrl(server.url("/").toString()) + .maxRetries(maxRetries) + .build(); + } + + void respond(int status, String body) { + server.enqueue(new MockResponse() + .setResponseCode(status) + .setHeader("Content-Type", "application/json") + .setBody(body)); + } + + RecordedRequest take(String method, String path) throws InterruptedException { + RecordedRequest request = server.takeRequest(TAKE_TIMEOUT_SECONDS, TimeUnit.SECONDS); + assertNotNull(request, "expected a request to " + method + " " + path); + assertEquals(method, request.getMethod()); + assertEquals(path, request.getPath()); + assertEquals("Bearer " + API_KEY, request.getHeader("Authorization")); + return request; + } + + static JsonNode json(RecordedRequest request) throws IOException { + return MAPPER.readTree(request.getBody().readUtf8()); + } +} diff --git a/src/test/java/com/ararahq/arara/sdk/services/MessageServiceTest.java b/src/test/java/com/ararahq/arara/sdk/services/MessageServiceTest.java index 4fa93c1..171ab00 100644 --- a/src/test/java/com/ararahq/arara/sdk/services/MessageServiceTest.java +++ b/src/test/java/com/ararahq/arara/sdk/services/MessageServiceTest.java @@ -1,384 +1,244 @@ package com.ararahq.arara.sdk.services; +import com.ararahq.arara.sdk.Arara; +import com.ararahq.arara.sdk.exceptions.AraraApiException; import com.ararahq.arara.sdk.exceptions.AraraException; -import com.ararahq.arara.sdk.http.AraraHttpClient; +import com.ararahq.arara.sdk.models.BatchMessageRequest; +import com.ararahq.arara.sdk.models.BatchMessageResponse; import com.ararahq.arara.sdk.models.MessageResponse; import com.ararahq.arara.sdk.models.SendMessageRequest; -import org.junit.jupiter.api.BeforeEach; +import com.fasterxml.jackson.databind.JsonNode; +import okhttp3.mockwebserver.RecordedRequest; import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + import java.math.BigDecimal; -import java.util.Arrays; +import java.util.List; +import java.util.UUID; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -/** - * Unit tests for MessageService. - */ -@ExtendWith(MockitoExtension.class) -@DisplayName("MessageService Tests") -class MessageServiceTest { - - @Mock - private AraraHttpClient httpClient; - - private MessageService messageService; - - @BeforeEach - void setUp() { - messageService = new MessageService(httpClient); - } - - @Nested - @DisplayName("send() method") - class SendMessageTests { - - @Test - @DisplayName("should send message successfully with template") - void shouldSendMessageWithTemplate() { - // Arrange - SendMessageRequest request = SendMessageRequest.builder() - .receiver("whatsapp:+5511999998888") - .templateName("hello_world") - .templateVariables(Arrays.asList("John", "Doe")) - .build(); - - MessageResponse expectedResponse = MessageResponse.builder() - .id("msg_123abc") - .status("SENT") - .mode("LIVE") - .sender("whatsapp:+551140001000") - .receiver("whatsapp:+5511999998888") - .body("Hello John Doe") - .cost(BigDecimal.valueOf(0.05)) - .build(); - - when(httpClient.post("/v1/messages", request, MessageResponse.class)) - .thenReturn(expectedResponse); - - // Act - MessageResponse result = messageService.send(request); - - // Assert - assertNotNull(result); - assertEquals("msg_123abc", result.getId()); - assertEquals("SENT", result.getStatus()); - assertEquals("whatsapp:+5511999998888", result.getReceiver()); - assertEquals(BigDecimal.valueOf(0.05), result.getCost()); - verify(httpClient, times(1)).post("/v1/messages", request, MessageResponse.class); - } - - @Test - @DisplayName("should send message successfully with free text") - void shouldSendMessageWithFreeText() { - // Arrange - SendMessageRequest request = SendMessageRequest.builder() - .receiver("whatsapp:+5511999998888") - .body("Hello, this is a free text message!") - .build(); - - MessageResponse expectedResponse = MessageResponse.builder() - .id("msg_456def") - .status("SENT") - .mode("LIVE") - .receiver("whatsapp:+5511999998888") - .body("Hello, this is a free text message!") - .cost(BigDecimal.valueOf(0.02)) - .build(); - - when(httpClient.post("/v1/messages", request, MessageResponse.class)) - .thenReturn(expectedResponse); - - // Act - MessageResponse result = messageService.send(request); - - // Assert - assertNotNull(result); - assertEquals("msg_456def", result.getId()); - assertEquals("Hello, this is a free text message!", result.getBody()); - assertEquals(BigDecimal.valueOf(0.02), result.getCost()); - } - - @Test - @DisplayName("should throw exception when request is null") - void shouldThrowExceptionWhenRequestIsNull() { - // Act & Assert - assertThrows(AraraException.class, () -> messageService.send(null), - "Should throw AraraException when request is null"); - } - - @Test - @DisplayName("should throw exception when receiver is null") - void shouldThrowExceptionWhenReceiverIsNull() { - // Arrange - SendMessageRequest request = SendMessageRequest.builder() - .receiver(null) - .body("Test message") - .build(); - - // Act & Assert - assertThrows(AraraException.class, () -> messageService.send(request), - "Should throw AraraException when receiver is null"); - } - - @Test - @DisplayName("should throw exception when receiver format is invalid") - void shouldThrowExceptionWhenReceiverFormatIsInvalid() { - // Arrange - SendMessageRequest request = SendMessageRequest.builder() - .receiver("invalid-format") - .body("Test message") - .build(); - - // Act & Assert - AraraException exception = assertThrows(AraraException.class, - () -> messageService.send(request), - "Should throw AraraException when receiver format is invalid"); - assertTrue(exception.getMessage().contains("whatsapp:+")); - } - - @Test - @DisplayName("should throw exception when receiver doesn't start with whatsapp:") - void shouldThrowExceptionWhenReceiverDoesntStartWithWhatsappPrefix() { - // Arrange - SendMessageRequest request = SendMessageRequest.builder() - .receiver("+5511999998888") - .body("Test message") - .build(); - - // Act & Assert - assertThrows(AraraException.class, () -> messageService.send(request), - "Should throw AraraException when receiver doesn't start with 'whatsapp:'"); - } - - @Test - @DisplayName("should send message with all optional fields populated") - void shouldSendMessageWithAllOptionalFields() { - // Arrange - SendMessageRequest request = SendMessageRequest.builder() - .receiver("whatsapp:+5511999998888") - .sender("whatsapp:+551140001000") - .templateName("template_1") - .templateVariables(Arrays.asList("var1", "var2")) - .mode("TEST") - .smartLinkParam("campaign_id") - .smartLinkUrl("https://example.com/campaign") - .build(); - - MessageResponse expectedResponse = MessageResponse.builder() - .id("msg_full") - .status("SENT") - .receiver("whatsapp:+5511999998888") - .build(); - - when(httpClient.post("/v1/messages", request, MessageResponse.class)) - .thenReturn(expectedResponse); - - // Act - MessageResponse result = messageService.send(request); - - // Assert - assertNotNull(result); - assertEquals("msg_full", result.getId()); - verify(httpClient, times(1)).post(eq("/v1/messages"), eq(request), eq(MessageResponse.class)); - } - } - - @Nested - @DisplayName("getById() method") - class GetByIdTests { - - @Test - @DisplayName("should retrieve message by ID successfully") - void shouldRetrieveMessageByIdSuccessfully() { - // Arrange - String messageId = "msg_123abc"; - MessageResponse expectedResponse = MessageResponse.builder() - .id(messageId) - .status("DELIVERED") - .receiver("whatsapp:+5511999998888") - .body("Test message") - .build(); - - when(httpClient.get("/v1/messages/" + messageId, MessageResponse.class)) - .thenReturn(expectedResponse); - - // Act - MessageResponse result = messageService.getById(messageId); - - // Assert - assertNotNull(result); - assertEquals(messageId, result.getId()); - assertEquals("DELIVERED", result.getStatus()); - verify(httpClient, times(1)).get("/v1/messages/" + messageId, MessageResponse.class); - } - - @Test - @DisplayName("should call correct endpoint with message ID") - void shouldCallCorrectEndpointWithMessageId() { - // Arrange - String messageId = "msg_xyz789"; - MessageResponse mockResponse = MessageResponse.builder() - .id(messageId) - .status("READ") - .build(); - - when(httpClient.get("/v1/messages/" + messageId, MessageResponse.class)) - .thenReturn(mockResponse); - - // Act - messageService.getById(messageId); - - // Assert - verify(httpClient, times(1)).get("/v1/messages/" + messageId, MessageResponse.class); - } - - @Test - @DisplayName("should handle message with various statuses") - void shouldHandleMessageWithVariousStatuses() { - // Test with different statuses - String[] statuses = { "SENT", "DELIVERED", "READ", "FAILED", "PENDING" }; - - for (String status : statuses) { - // Arrange - String messageId = "msg_" + status; - MessageResponse mockResponse = MessageResponse.builder() - .id(messageId) - .status(status) - .receiver("whatsapp:+5511999998888") - .build(); - - when(httpClient.get("/v1/messages/" + messageId, MessageResponse.class)) - .thenReturn(mockResponse); - - // Act - MessageResponse result = messageService.getById(messageId); - - // Assert - assertNotNull(result); - assertEquals(status, result.getStatus()); - assertEquals(messageId, result.getId()); - } - } - - @Test - @DisplayName("should retrieve message with cost information") - void shouldRetrieveMessageWithCostInformation() { - // Arrange - String messageId = "msg_cost_test"; - BigDecimal expectedCost = BigDecimal.valueOf(0.15); - MessageResponse expectedResponse = MessageResponse.builder() - .id(messageId) - .status("DELIVERED") - .cost(expectedCost) - .build(); - - when(httpClient.get("/v1/messages/" + messageId, MessageResponse.class)) - .thenReturn(expectedResponse); - - // Act - MessageResponse result = messageService.getById(messageId); - - // Assert - assertNotNull(result); - assertEquals(expectedCost, result.getCost()); - } - } - - @Nested - @DisplayName("Integration scenarios") - class IntegrationScenarios { - - @Test - @DisplayName("should send then retrieve the same message") - void shouldSendThenRetrieveSameMessage() { - // Arrange - String messageId = "msg_integration"; - SendMessageRequest sendRequest = SendMessageRequest.builder() - .receiver("whatsapp:+5511999998888") - .body("Integration test message") - .build(); - - MessageResponse sentResponse = MessageResponse.builder() - .id(messageId) - .status("SENT") - .receiver("whatsapp:+5511999998888") - .body("Integration test message") - .cost(BigDecimal.valueOf(0.05)) - .build(); - - MessageResponse retrievedResponse = MessageResponse.builder() - .id(messageId) - .status("DELIVERED") - .receiver("whatsapp:+5511999998888") - .body("Integration test message") - .cost(BigDecimal.valueOf(0.05)) - .build(); - - when(httpClient.post("/v1/messages", sendRequest, MessageResponse.class)) - .thenReturn(sentResponse); - when(httpClient.get("/v1/messages/" + messageId, MessageResponse.class)) - .thenReturn(retrievedResponse); - - // Act - MessageResponse sent = messageService.send(sendRequest); - MessageResponse retrieved = messageService.getById(sent.getId()); - - // Assert - assertEquals(messageId, sent.getId()); - assertEquals("SENT", sent.getStatus()); - assertEquals("DELIVERED", retrieved.getStatus()); - assertEquals(sent.getId(), retrieved.getId()); - assertEquals(sent.getCost(), retrieved.getCost()); - } - - @Test - @DisplayName("should send multiple messages") - void shouldSendMultipleMessages() { - // Arrange - String[] receivers = { "whatsapp:+5511999998888", "whatsapp:+5511988887777", - "whatsapp:+5511977776666" }; - MessageResponse[] responses = new MessageResponse[3]; - - for (int i = 0; i < receivers.length; i++) { - SendMessageRequest request = SendMessageRequest.builder() - .receiver(receivers[i]) - .body("Test message " + i) - .build(); - - responses[i] = MessageResponse.builder() - .id("msg_" + i) - .status("SENT") - .receiver(receivers[i]) - .build(); - - when(httpClient.post("/v1/messages", request, MessageResponse.class)) - .thenReturn(responses[i]); - } - - // Act - for (int i = 0; i < receivers.length; i++) { - SendMessageRequest request = SendMessageRequest.builder() - .receiver(receivers[i]) - .body("Test message " + i) - .build(); - messageService.send(request); - } - - // Assert - verify(httpClient, times(3)).post(eq("/v1/messages"), any(SendMessageRequest.class), - eq(MessageResponse.class)); - } - } + +@DisplayName("MessageService against fake API") +class MessageServiceTest extends FakeApi { + private static final String ACCEPTED = "{\"id\":\"msg_1\",\"status\":\"QUEUED\",\"mode\":\"LIVE\"," + + "\"receiver\":\"5511999998888\",\"cost\":0.05}"; + + private SendMessageRequest template(String receiver) { + return SendMessageRequest.builder() + .receiver(receiver) + .templateName("hello_world") + .templateVariables(List.of("Ana")) + .build(); + } + + @Test + @DisplayName("should POST /v1/messages with body and parse the 202 response") + void shouldPostMessageAndParseResponse() throws Exception { + respond(202, ACCEPTED); + + MessageResponse response = arara.getMessages().send(template("whatsapp:+5511999998888")); + + RecordedRequest request = take("POST", "/v1/messages"); + JsonNode body = json(request); + assertEquals("whatsapp:+5511999998888", body.get("receiver").asText()); + assertEquals("hello_world", body.get("templateName").asText()); + assertEquals("Ana", body.get("templateVariables").get(0).asText()); + assertEquals("msg_1", response.getId()); + assertEquals(new BigDecimal("0.05"), response.getCost()); + } + + @Test + @DisplayName("should accept a response without cost") + void shouldAcceptResponseWithoutCost() throws Exception { + respond(202, "{\"id\":\"msg_2\",\"status\":\"SCHEDULED\"}"); + + MessageResponse response = arara.getMessages().send(template("5511999998888")); + + take("POST", "/v1/messages"); + assertNull(response.getCost()); + } + + @Test + @DisplayName("should always send a UUID v4 Idempotency-Key when caller gives none") + void shouldGenerateIdempotencyKey() throws Exception { + respond(202, ACCEPTED); + + arara.getMessages().send(template("+5511999998888")); + + String key = take("POST", "/v1/messages").getHeader("Idempotency-Key"); + assertNotNull(key); + assertEquals(4, UUID.fromString(key).version()); + } + + @Test + @DisplayName("should use the caller Idempotency-Key when given") + void shouldUseCallerIdempotencyKey() throws Exception { + respond(202, ACCEPTED); + + arara.getMessages().send(template("+5511999998888"), "order-42"); + + assertEquals("order-42", take("POST", "/v1/messages").getHeader("Idempotency-Key")); + } + + @Test + @DisplayName("should retry after 5xx reusing the same Idempotency-Key") + void shouldRetryWithSameKey() throws Exception { + Arara retrying = client(2); + respond(503, "{\"error\":{\"code\":\"SEND_TEMPORARILY_UNAVAILABLE\",\"message\":\"x\",\"details\":{}}}"); + respond(202, ACCEPTED); + + MessageResponse response = retrying.getMessages().send(template("+5511999998888")); + + String first = take("POST", "/v1/messages").getHeader("Idempotency-Key"); + String second = take("POST", "/v1/messages").getHeader("Idempotency-Key"); + assertEquals(first, second); + assertEquals("msg_1", response.getId()); + } + + @ParameterizedTest + @ValueSource(strings = {"whatsapp:+5511999998888", "+5511999998888", "5511999998888"}) + @DisplayName("should accept every receiver format the API accepts") + void shouldAcceptFlexibleReceiver(String receiver) throws Exception { + respond(202, ACCEPTED); + + assertDoesNotThrow(() -> arara.getMessages().send(template(receiver))); + + assertEquals(receiver, json(take("POST", "/v1/messages")).get("receiver").asText()); + } + + @Test + @DisplayName("should reject null request and invalid receiver without calling the API") + void shouldRejectInvalidInputLocally() { + assertThrows(AraraException.class, () -> arara.getMessages().send(null)); + assertThrows(AraraException.class, () -> arara.getMessages().send(template("abc"))); + assertEquals(0, server.getRequestCount()); + } + + @Test + @DisplayName("should surface 422 INVALID_RECIPIENT with code") + void shouldSurfaceInvalidRecipient() { + respond(422, "{\"error\":{\"code\":\"INVALID_RECIPIENT\",\"message\":\"Numero invalido\",\"details\":{}}}"); + + AraraApiException error = assertThrows(AraraApiException.class, + () -> arara.getMessages().send(template("5511999998888"))); + + assertEquals(422, error.getStatusCode()); + assertEquals("INVALID_RECIPIENT", error.getCode()); + } + + @Test + @DisplayName("should GET /v1/messages/{id}") + void shouldGetById() throws Exception { + respond(200, ACCEPTED); + + MessageResponse response = arara.getMessages().getById("msg_1"); + + take("GET", "/v1/messages/msg_1"); + assertEquals("QUEUED", response.getStatus()); + } + + @Test + @DisplayName("should GET /v1/messages?batchId= as a raw list") + void shouldListByBatch() throws Exception { + respond(200, "[" + ACCEPTED + "]"); + + List messages = arara.getMessages().listByBatch("b 1"); + + take("GET", "/v1/messages?batchId=b+1"); + assertEquals(1, messages.size()); + } + + @Test + @DisplayName("should POST /v1/messages/batch with Idempotency-Key and parse result") + void shouldSendBatch() throws Exception { + respond(202, "{\"batchId\":\"b1\",\"templateName\":\"hello\",\"total\":1,\"accepted\":1," + + "\"totalCost\":0.05,\"messages\":[{\"id\":\"m1\",\"receiver\":\"5511999998888\"," + + "\"status\":\"QUEUED\",\"cost\":0.05}]}"); + BatchMessageRequest request = BatchMessageRequest.builder() + .templateName("hello") + .messages(List.of(BatchMessageRequest.BatchMessageItem.builder() + .receiver("5511999998888") + .templateVariables(List.of("Ana")) + .build())) + .build(); + + BatchMessageResponse response = arara.getMessages().sendBatch(request); + + RecordedRequest recorded = take("POST", "/v1/messages/batch"); + assertNotNull(recorded.getHeader("Idempotency-Key")); + assertEquals("hello", json(recorded).get("templateName").asText()); + assertEquals("b1", response.getBatchId()); + assertEquals("m1", response.getMessages().get(0).getId()); + } + + @Test + @DisplayName("should reject a batch above 1000 items locally") + void shouldRejectOversizedBatch() { + List items = IntStream.range(0, 1001) + .mapToObj(i -> BatchMessageRequest.BatchMessageItem.builder().receiver("5511999998888").build()) + .collect(Collectors.toList()); + BatchMessageRequest request = BatchMessageRequest.builder().templateName("t").messages(items).build(); + + assertThrows(AraraException.class, () -> arara.getMessages().sendBatch(request, "k")); + assertEquals(0, server.getRequestCount()); + } + + @Test + @DisplayName("should trim the caller key and reject a blank one") + void shouldTrimAndRejectBlankKey() throws Exception { + respond(202, ACCEPTED); + + arara.getMessages().send(template("5511999998888"), " order-7 "); + + assertEquals("order-7", take("POST", "/v1/messages").getHeader("Idempotency-Key")); + assertThrows(AraraException.class, () -> arara.getMessages().send(template("5511999998888"), " ")); + assertEquals(1, server.getRequestCount()); + } + + @Test + @DisplayName("should raise NOT_FOUND on empty 403 from GET /v1/messages/{id}") + void shouldMapEmpty403ToNotFound() throws Exception { + server.enqueue(new okhttp3.mockwebserver.MockResponse().setResponseCode(403)); + + AraraApiException error = assertThrows(AraraApiException.class, + () -> arara.getMessages().getById("msg_other")); + + take("GET", "/v1/messages/msg_other"); + assertFalse(error instanceof com.ararahq.arara.sdk.exceptions.AraraAuthException); + assertEquals("NOT_FOUND", error.getCode()); + assertEquals(403, error.getStatusCode()); + } + + @Test + @DisplayName("should keep 401 on GET /v1/messages/{id} as auth error") + void shouldKeep401AsAuth() { + server.enqueue(new okhttp3.mockwebserver.MockResponse().setResponseCode(401)); + + assertThrows(com.ararahq.arara.sdk.exceptions.AraraAuthException.class, + () -> arara.getMessages().getById("msg_1")); + } + + @Test + @DisplayName("should reject a null batch item with its index") + void shouldRejectNullBatchItem() { + BatchMessageRequest request = BatchMessageRequest.builder().templateName("t") + .messages(java.util.Arrays.asList( + BatchMessageRequest.BatchMessageItem.builder().receiver("5511999998888").build(), null)) + .build(); + + AraraException error = assertThrows(AraraException.class, () -> arara.getMessages().sendBatch(request)); + + assertTrue(error.getMessage().contains("messages[1]")); + assertEquals(0, server.getRequestCount()); + } } diff --git a/src/test/java/com/ararahq/arara/sdk/services/NumberServiceTest.java b/src/test/java/com/ararahq/arara/sdk/services/NumberServiceTest.java index 006a6eb..16c6975 100644 --- a/src/test/java/com/ararahq/arara/sdk/services/NumberServiceTest.java +++ b/src/test/java/com/ararahq/arara/sdk/services/NumberServiceTest.java @@ -1,156 +1,42 @@ package com.ararahq.arara.sdk.services; -import com.ararahq.arara.sdk.exceptions.AraraException; -import com.ararahq.arara.sdk.http.AraraHttpClient; -import com.ararahq.arara.sdk.models.NumberCard; -import com.ararahq.arara.sdk.models.NumbersResponse; -import com.ararahq.arara.sdk.models.NumbersSlot; import com.ararahq.arara.sdk.models.RequestNumberRequest; import com.ararahq.arara.sdk.models.UpdateNumberRequest; -import com.fasterxml.jackson.core.type.TypeReference; -import org.junit.jupiter.api.BeforeEach; +import okhttp3.mockwebserver.MockResponse; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; - -import java.util.Arrays; -import java.util.List; -import java.util.Map; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.ArgumentMatchers.isNull; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoInteractions; -import static org.mockito.Mockito.when; - -@ExtendWith(MockitoExtension.class) -@DisplayName("NumberService Tests") -class NumberServiceTest { +@DisplayName("NumberService against fake API") +class NumberServiceTest extends FakeApi { private static final String BASE = "/v1/organizations/me/numbers"; - @Mock - private AraraHttpClient httpClient; - - private NumberService numberService; - - @BeforeEach - void setUp() { - numberService = new NumberService(httpClient); - } - - @Test - @DisplayName("should list numbers and slot info") - void shouldListNumbers() { - NumbersResponse expected = NumbersResponse.builder() - .numbers(Arrays.asList(NumberCard.builder().id("num_1").phoneNumber("+551140001000").build())) - .slot(NumbersSlot.builder().used(1).max(3).build()) - .build(); - when(httpClient.get(BASE, NumbersResponse.class)).thenReturn(expected); - - NumbersResponse result = numberService.list(); - - assertEquals(1, result.getNumbers().size()); - assertEquals(3, result.getSlot().getMax()); - verify(httpClient, times(1)).get(BASE, NumbersResponse.class); - } - @Test - @DisplayName("should update a number") - void shouldUpdateNumber() { - UpdateNumberRequest request = UpdateNumberRequest.builder().alias("Support").isDefault(true).build(); - Map expected = Map.of("id", "num_1"); - when(httpClient.patch(eq(BASE + "/num_1"), eq(request), any(TypeReference.class))) - .thenReturn(expected); - - Map result = numberService.update("num_1", request); - - assertEquals("num_1", result.get("id")); - verify(httpClient, times(1)).patch(eq(BASE + "/num_1"), eq(request), any(TypeReference.class)); - } - - @Test - @DisplayName("should reject null update request") - void shouldRejectNullUpdate() { - assertThrows(AraraException.class, () -> numberService.update("num_1", null)); - verifyNoInteractions(httpClient); - } - - @Test - @DisplayName("should soft-delete a number") - void shouldDeleteNumber() { - numberService.delete("num_1"); - - verify(httpClient, times(1)).delete(BASE + "/num_1"); - } - - @Test - @DisplayName("should request a new dedicated number") - void shouldRequestNumber() { - RequestNumberRequest request = RequestNumberRequest.builder() - .reason("scale") - .expectedVolume("1000") - .areaCode("11") - .build(); - Map expected = Map.of("status", "PENDING"); - when(httpClient.post(eq(BASE + "/request"), eq(request), any(TypeReference.class))) - .thenReturn(expected); - - Map result = numberService.request(request); - - assertEquals("PENDING", result.get("status")); - verify(httpClient, times(1)).post(eq(BASE + "/request"), eq(request), any(TypeReference.class)); - } - - @Test - @DisplayName("should reject null request-number payload") - void shouldRejectNullRequest() { - assertThrows(AraraException.class, () -> numberService.request(null)); - verifyNoInteractions(httpClient); - } - - @Test - @DisplayName("should list pending and resolved number requests") - void shouldListRequests() { - List> expected = Arrays.asList(Map.of("id", "req_1")); - when(httpClient.get(eq(BASE + "/requests"), any(TypeReference.class))).thenReturn(expected); - - List> result = numberService.listRequests(); - - assertEquals(1, result.size()); - verify(httpClient, times(1)).get(eq(BASE + "/requests"), any(TypeReference.class)); - } - - @Test - @DisplayName("should trigger a provider sync with null body") - void shouldSyncNumber() { - Map expected = Map.of("synced", true); - when(httpClient.post(eq(BASE + "/num_1/sync"), isNull(), any(TypeReference.class))) - .thenReturn(expected); - - Map result = numberService.sync("num_1"); - - assertEquals(true, result.get("synced")); - verify(httpClient, times(1)).post(eq(BASE + "/num_1/sync"), isNull(), any(TypeReference.class)); - } - - @Test - @DisplayName("should return warming recommendations") - void shouldReturnWarming() { - Map expected = Map.of("recommendedDailyCap", 50); - when(httpClient.get(eq(BASE + "/num_1/warming"), any(TypeReference.class))).thenReturn(expected); - - Map result = numberService.warming("num_1"); - - assertNotNull(result); - assertEquals(50, result.get("recommendedDailyCap")); - verify(httpClient, times(1)).get(eq(BASE + "/num_1/warming"), any(TypeReference.class)); + @DisplayName("should hit every numbers endpoint with the right method and path") + void shouldCoverNumbers() throws Exception { + respond(200, "{\"numbers\":[],\"slot\":null}"); + respond(200, "{\"ok\":true}"); + server.enqueue(new MockResponse().setResponseCode(204)); + respond(200, "{\"requested\":true}"); + respond(200, "[{\"id\":\"r1\"}]"); + respond(200, "{\"synced\":true}"); + respond(200, "{\"dailyLimit\":250}"); + + arara.getNumbers().list(); + arara.getNumbers().update("n1", UpdateNumberRequest.builder().alias("Vendas").build()); + arara.getNumbers().delete("n1"); + arara.getNumbers().request(RequestNumberRequest.builder().areaCode("11").build()); + assertEquals("r1", arara.getNumbers().listRequests().get(0).get("id")); + arara.getNumbers().sync("n1"); + assertEquals(250, arara.getNumbers().warming("n1").get("dailyLimit")); + + take("GET", BASE); + assertEquals("Vendas", json(take("PATCH", BASE + "/n1")).get("alias").asText()); + take("DELETE", BASE + "/n1"); + assertEquals("11", json(take("POST", BASE + "/request")).get("areaCode").asText()); + take("GET", BASE + "/requests"); + take("POST", BASE + "/n1/sync"); + take("GET", BASE + "/n1/warming"); } } diff --git a/src/test/java/com/ararahq/arara/sdk/services/OptOutServiceTest.java b/src/test/java/com/ararahq/arara/sdk/services/OptOutServiceTest.java new file mode 100644 index 0000000..a10fc85 --- /dev/null +++ b/src/test/java/com/ararahq/arara/sdk/services/OptOutServiceTest.java @@ -0,0 +1,42 @@ +package com.ararahq.arara.sdk.services; + +import com.fasterxml.jackson.databind.JsonNode; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@DisplayName("OptOutService against fake API") +class OptOutServiceTest extends FakeApi { + + @Test + @DisplayName("should list, add, get and remove opt-outs") + void shouldCoverOptOuts() throws Exception { + respond(200, "{\"items\":[],\"total\":0}"); + respond(201, "{\"phone\":\"+5511999998888\"}"); + respond(200, "{\"optedOut\":true}"); + respond(200, "{\"removed\":true}"); + + assertEquals(0, arara.getOptOuts().list().get("total")); + arara.getOptOuts().add("+5511999998888", "pediu"); + assertEquals(true, arara.getOptOuts().get("+5511999998888").get("optedOut")); + assertEquals(true, arara.getOptOuts().remove("+5511999998888").get("removed")); + + take("GET", "/v1/opt-outs"); + JsonNode body = json(take("POST", "/v1/opt-outs")); + assertEquals("+5511999998888", body.get("phone").asText()); + assertEquals("pediu", body.get("reason").asText()); + take("GET", "/v1/opt-outs/%2B5511999998888"); + take("DELETE", "/v1/opt-outs/%2B5511999998888"); + } + + @Test + @DisplayName("should reject null phone locally") + void shouldRejectNullPhone() { + assertThrows(RuntimeException.class, () -> arara.getOptOuts().add(null, null)); + assertThrows(RuntimeException.class, () -> arara.getOptOuts().get(null)); + assertThrows(RuntimeException.class, () -> arara.getOptOuts().remove(null)); + assertEquals(0, server.getRequestCount()); + } +} diff --git a/src/test/java/com/ararahq/arara/sdk/services/OrganizationServiceTest.java b/src/test/java/com/ararahq/arara/sdk/services/OrganizationServiceTest.java index d5e20e0..b6468ab 100644 --- a/src/test/java/com/ararahq/arara/sdk/services/OrganizationServiceTest.java +++ b/src/test/java/com/ararahq/arara/sdk/services/OrganizationServiceTest.java @@ -1,115 +1,31 @@ package com.ararahq.arara.sdk.services; -import com.ararahq.arara.sdk.exceptions.AraraException; -import com.ararahq.arara.sdk.http.AraraHttpClient; import com.ararahq.arara.sdk.models.BusinessProfilePatch; -import com.ararahq.arara.sdk.models.BusinessProfileResponse; -import com.ararahq.arara.sdk.models.OrganizationPlanResponse; -import com.fasterxml.jackson.core.type.TypeReference; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; - -import java.util.Map; -import java.util.UUID; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoInteractions; -import static org.mockito.Mockito.when; - -@ExtendWith(MockitoExtension.class) -@DisplayName("OrganizationService Tests") -class OrganizationServiceTest { - @Mock - private AraraHttpClient httpClient; - - private OrganizationService organizationService; - - @BeforeEach - void setUp() { - organizationService = new OrganizationService(httpClient); - } +@DisplayName("OrganizationService against fake API") +class OrganizationServiceTest extends FakeApi { + private static final String PROFILE = "/v1/organizations/me/business-profile"; @Test - @DisplayName("should return the organization business profile") - void shouldReturnBusinessProfile() { - BusinessProfileResponse expected = BusinessProfileResponse.builder() - .id(UUID.randomUUID()) - .displayName("Arara") - .build(); - when(httpClient.get("/v1/organizations/me/business-profile", BusinessProfileResponse.class)) - .thenReturn(expected); - - BusinessProfileResponse result = organizationService.me(); - - assertEquals("Arara", result.getDisplayName()); - verify(httpClient, times(1)) - .get("/v1/organizations/me/business-profile", BusinessProfileResponse.class); - } - - @Test - @DisplayName("should patch the organization business profile") - void shouldUpdateBusinessProfile() { - BusinessProfilePatch request = BusinessProfilePatch.builder() - .displayName("Arara HQ") - .vertical("TECH") - .build(); - BusinessProfileResponse expected = BusinessProfileResponse.builder().displayName("Arara HQ").build(); - when(httpClient.patch("/v1/organizations/me/business-profile", request, BusinessProfileResponse.class)) - .thenReturn(expected); - - BusinessProfileResponse result = organizationService.updateBusinessProfile(request); - - assertEquals("Arara HQ", result.getDisplayName()); - verify(httpClient, times(1)) - .patch("/v1/organizations/me/business-profile", request, BusinessProfileResponse.class); - } - - @Test - @DisplayName("should reject null business profile patch") - void shouldRejectNullPatch() { - assertThrows(AraraException.class, () -> organizationService.updateBusinessProfile(null)); - verifyNoInteractions(httpClient); - } - - @Test - @DisplayName("should return the organization current plan") - void shouldReturnPlan() { - OrganizationPlanResponse expected = OrganizationPlanResponse.builder() - .current("VOO") - .monthlyPriceCents(34900) - .build(); - when(httpClient.get("/v1/organizations/me/plan", OrganizationPlanResponse.class)).thenReturn(expected); - - OrganizationPlanResponse result = organizationService.getPlan(); - - assertEquals("VOO", result.getCurrent()); - verify(httpClient, times(1)).get("/v1/organizations/me/plan", OrganizationPlanResponse.class); - } - - @Test - @DisplayName("should change the organization plan") - void shouldChangePlan() { - Map expected = Map.of("current", "DECOLAGEM"); - when(httpClient.patch( - eq("/v1/organizations/me/plan"), eq(Map.of("plan", "DECOLAGEM")), any(TypeReference.class))) - .thenReturn(expected); - - Map result = organizationService.changePlan("DECOLAGEM"); - - assertNotNull(result); - assertEquals("DECOLAGEM", result.get("current")); - verify(httpClient, times(1)).patch( - eq("/v1/organizations/me/plan"), eq(Map.of("plan", "DECOLAGEM")), any(TypeReference.class)); + @DisplayName("should read and patch the business profile and read and change the plan") + void shouldCoverOrganization() throws Exception { + respond(200, "{\"displayName\":\"Loja\"}"); + respond(200, "{\"displayName\":\"Loja 2\"}"); + respond(200, "{\"current\":\"VOO\",\"monthlyPriceCents\":99700}"); + respond(200, "{\"plan\":\"DECOLAGEM\"}"); + + assertEquals("Loja", arara.getOrganizations().me().getDisplayName()); + arara.getOrganizations().updateBusinessProfile(BusinessProfilePatch.builder().displayName("Loja 2").build()); + assertEquals("VOO", arara.getOrganizations().getPlan().getCurrent()); + assertEquals("DECOLAGEM", arara.getOrganizations().changePlan("DECOLAGEM").get("plan")); + + take("GET", PROFILE); + assertEquals("Loja 2", json(take("PATCH", PROFILE)).get("displayName").asText()); + take("GET", "/v1/organizations/me/plan"); + assertEquals("DECOLAGEM", json(take("PATCH", "/v1/organizations/me/plan")).get("plan").asText()); } } diff --git a/src/test/java/com/ararahq/arara/sdk/services/SmartLinkServiceTest.java b/src/test/java/com/ararahq/arara/sdk/services/SmartLinkServiceTest.java index 54fa5d4..8b0665a 100644 --- a/src/test/java/com/ararahq/arara/sdk/services/SmartLinkServiceTest.java +++ b/src/test/java/com/ararahq/arara/sdk/services/SmartLinkServiceTest.java @@ -1,123 +1,74 @@ package com.ararahq.arara.sdk.services; -import com.ararahq.arara.sdk.exceptions.AraraException; -import com.ararahq.arara.sdk.http.AraraHttpClient; import com.ararahq.arara.sdk.models.CreateWhatsAppSmartLinkRequest; +import com.ararahq.arara.sdk.models.PaginatedResponse; import com.ararahq.arara.sdk.models.UpdateWhatsAppSmartLinkRequest; import com.ararahq.arara.sdk.models.WhatsAppSmartLinkResponse; -import com.fasterxml.jackson.core.type.TypeReference; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; - -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.UUID; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoInteractions; -import static org.mockito.Mockito.when; - -@ExtendWith(MockitoExtension.class) -@DisplayName("SmartLinkService Tests") -class SmartLinkServiceTest { - - private static final String BASE = "/v1/smart-links/whatsapp"; - - @Mock - private AraraHttpClient httpClient; - private SmartLinkService smartLinkService; - - @BeforeEach - void setUp() { - smartLinkService = new SmartLinkService(httpClient); - } +@DisplayName("SmartLinkService against fake API") +class SmartLinkServiceTest extends FakeApi { + private static final String ID = "5d0f6c7a-2222-4000-8000-000000000003"; + private static final String LINK = "{\"id\":\"" + ID + "\",\"name\":\"Loja\",\"code\":\"abc\",\"clicks\":7}"; @Test - @DisplayName("should create a smart link") - void shouldCreateSmartLink() { - CreateWhatsAppSmartLinkRequest request = CreateWhatsAppSmartLinkRequest.builder() - .name("Promo") - .phoneNumber("+551140001000") - .defaultText("Hi") - .build(); - WhatsAppSmartLinkResponse expected = WhatsAppSmartLinkResponse.builder() - .id(UUID.randomUUID()) - .name("Promo") - .code("abc123") - .build(); - when(httpClient.post(BASE, request, WhatsAppSmartLinkResponse.class)).thenReturn(expected); + @DisplayName("should parse the {data, pagination} envelope of GET /v1/smart-links/whatsapp") + void shouldListPaginated() throws Exception { + respond(200, "{\"data\":[" + LINK + "],\"pagination\":{\"page\":0,\"size\":50," + + "\"totalElements\":1,\"totalPages\":1}}"); - WhatsAppSmartLinkResponse result = smartLinkService.create(request); - - assertEquals("Promo", result.getName()); - verify(httpClient, times(1)).post(BASE, request, WhatsAppSmartLinkResponse.class); - } + PaginatedResponse page = arara.getSmartLinks().list(); - @Test - @DisplayName("should reject null create request") - void shouldRejectNullCreate() { - assertThrows(AraraException.class, () -> smartLinkService.create(null)); - verifyNoInteractions(httpClient); + take("GET", "/v1/smart-links/whatsapp"); + assertEquals(7, page.getData().get(0).getClicks()); + assertEquals(1, page.getPagination().getTotalPages()); } @Test - @DisplayName("should update a smart link via PUT") - void shouldUpdateSmartLink() { - UpdateWhatsAppSmartLinkRequest request = UpdateWhatsAppSmartLinkRequest.builder() - .name("Promo v2") - .defaultText("Hello") - .build(); - WhatsAppSmartLinkResponse expected = WhatsAppSmartLinkResponse.builder().name("Promo v2").build(); - when(httpClient.put(BASE + "/link_1", request, WhatsAppSmartLinkResponse.class)).thenReturn(expected); - - WhatsAppSmartLinkResponse result = smartLinkService.update("link_1", request); + @DisplayName("should send page and size") + void shouldListWithPage() throws Exception { + respond(200, "{\"data\":[],\"pagination\":{\"page\":2,\"size\":5,\"totalElements\":0,\"totalPages\":0}}"); - assertEquals("Promo v2", result.getName()); - verify(httpClient, times(1)).put(BASE + "/link_1", request, WhatsAppSmartLinkResponse.class); - } + arara.getSmartLinks().list(2, 5); - @Test - @DisplayName("should reject null update request") - void shouldRejectNullUpdate() { - assertThrows(AraraException.class, () -> smartLinkService.update("link_1", null)); - verifyNoInteractions(httpClient); + take("GET", "/v1/smart-links/whatsapp?page=2&size=5"); } @Test - @DisplayName("should list smart links") - void shouldListSmartLinks() { - List expected = Arrays.asList( - WhatsAppSmartLinkResponse.builder().name("Promo").build()); - when(httpClient.get(eq(BASE), any(TypeReference.class))).thenReturn(expected); - - List result = smartLinkService.list(); - - assertEquals(1, result.size()); - verify(httpClient, times(1)).get(eq(BASE), any(TypeReference.class)); + @DisplayName("should create, update and read stats") + void shouldCreateUpdateAndStats() throws Exception { + respond(200, LINK); + respond(200, LINK); + respond(200, "{\"clicks\":7}"); + + arara.getSmartLinks().create(CreateWhatsAppSmartLinkRequest.builder() + .name("Loja").phoneNumber("5511999998888").build()); + arara.getSmartLinks().update(ID, UpdateWhatsAppSmartLinkRequest.builder().name("Loja 2").build()); + assertEquals(7, arara.getSmartLinks().stats(ID).get("clicks")); + + assertEquals("5511999998888", json(take("POST", "/v1/smart-links/whatsapp")).get("phoneNumber").asText()); + assertEquals("Loja 2", json(take("PUT", "/v1/smart-links/whatsapp/" + ID)).get("name").asText()); + take("GET", "/v1/smart-links/whatsapp/" + ID + "/stats"); } @Test - @DisplayName("should return click stats for a smart link") - void shouldReturnStats() { - Map expected = Map.of("clicks", 42); - when(httpClient.get(eq(BASE + "/link_1/stats"), any(TypeReference.class))).thenReturn(expected); - - Map result = smartLinkService.stats("link_1"); - - assertNotNull(result); - assertEquals(42, result.get("clicks")); - verify(httpClient, times(1)).get(eq(BASE + "/link_1/stats"), any(TypeReference.class)); + @DisplayName("should encode id in update and stats paths and reject null id") + void shouldEncodeIdAndRejectNull() throws Exception { + respond(200, LINK); + respond(200, "{}"); + + arara.getSmartLinks().update("a b/c", UpdateWhatsAppSmartLinkRequest.builder().name("x").build()); + arara.getSmartLinks().stats("a b/c"); + + take("PUT", "/v1/smart-links/whatsapp/a%20b%2Fc"); + take("GET", "/v1/smart-links/whatsapp/a%20b%2Fc/stats"); + assertThrows(RuntimeException.class, + () -> arara.getSmartLinks().update(null, UpdateWhatsAppSmartLinkRequest.builder().build())); + assertThrows(RuntimeException.class, () -> arara.getSmartLinks().stats(null)); + assertEquals(2, server.getRequestCount()); } } diff --git a/src/test/java/com/ararahq/arara/sdk/services/TemplateServiceTest.java b/src/test/java/com/ararahq/arara/sdk/services/TemplateServiceTest.java index 1b802b4..f06de2e 100644 --- a/src/test/java/com/ararahq/arara/sdk/services/TemplateServiceTest.java +++ b/src/test/java/com/ararahq/arara/sdk/services/TemplateServiceTest.java @@ -1,90 +1,114 @@ package com.ararahq.arara.sdk.services; -import com.ararahq.arara.sdk.http.AraraHttpClient; +import com.ararahq.arara.sdk.exceptions.AraraApiException; import com.ararahq.arara.sdk.models.CreateTemplateRequest; +import com.ararahq.arara.sdk.models.PaginatedResponse; import com.ararahq.arara.sdk.models.TemplateResponse; -import com.ararahq.arara.sdk.models.TemplateStatusResponse; -import org.junit.jupiter.api.BeforeEach; +import com.fasterxml.jackson.databind.JsonNode; +import okhttp3.mockwebserver.MockResponse; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; -import java.util.List; +import java.util.Map; import java.util.UUID; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; +import static org.junit.jupiter.api.Assertions.assertThrows; -@ExtendWith(MockitoExtension.class) -@DisplayName("TemplateService Tests") -class TemplateServiceTest { +@DisplayName("TemplateService against fake API") +class TemplateServiceTest extends FakeApi { + private static final UUID ID = UUID.fromString("0b7e3a8e-1111-4000-8000-000000000002"); + private static final String TEMPLATE = "{\"id\":\"" + ID + "\",\"name\":\"boas_vindas\",\"category\":\"UTILITY\"}"; - @Mock - private AraraHttpClient httpClient; + @Test + @DisplayName("should parse the {data, pagination} envelope of GET /v1/templates") + void shouldListPaginated() throws Exception { + respond(200, "{\"data\":[" + TEMPLATE + "],\"pagination\":{\"page\":0,\"size\":50," + + "\"totalElements\":1,\"totalPages\":1}}"); - private TemplateService templateService; + PaginatedResponse page = arara.getTemplates().list(); - @BeforeEach - void setUp() { - templateService = new TemplateService(httpClient); + take("GET", "/v1/templates"); + assertEquals(ID, page.getData().get(0).getId()); + assertEquals(1, page.getPagination().getTotalElements()); + assertEquals(50, page.getPagination().getSize()); } @Test - @DisplayName("should create template") - void shouldCreateTemplate() { - CreateTemplateRequest request = CreateTemplateRequest.builder() - .name("test_template") - .body("Hello") - .category("MARKETING") - .build(); - - TemplateResponse expected = TemplateResponse.builder().id(UUID.randomUUID()).build(); - when(httpClient.post("/v1/templates", request, TemplateResponse.class)).thenReturn(expected); - - TemplateResponse result = templateService.create(request); - assertEquals(expected, result); + @DisplayName("should send name, status, page and size filters encoded") + void shouldListWithFilters() throws Exception { + respond(200, "{\"data\":[],\"pagination\":{\"page\":1,\"size\":10,\"totalElements\":0,\"totalPages\":0}}"); + + arara.getTemplates().list("boas vindas", "APPROVED", 1, 10); + + take("GET", "/v1/templates?name=boas+vindas&status=APPROVED&page=1&size=10"); } @Test - @DisplayName("should list templates") - void shouldListTemplates() { - TemplateResponse[] templates = { TemplateResponse.builder().id(UUID.randomUUID()).build() }; - when(httpClient.get("/v1/templates", TemplateResponse[].class)).thenReturn(templates); + @DisplayName("should GET, status and DELETE by template id (UUID), never by name") + void shouldUseIdInPath() throws Exception { + respond(200, TEMPLATE); + respond(200, "{\"status\":\"APPROVED\",\"category\":\"UTILITY\"}"); + server.enqueue(new MockResponse().setResponseCode(200).setBody("{\"deleted\":true}")); + + assertEquals("boas_vindas", arara.getTemplates().getById(ID).getName()); + assertEquals("APPROVED", arara.getTemplates().getStatus(ID).getStatus()); + arara.getTemplates().delete(ID); + + take("GET", "/v1/templates/" + ID); + take("GET", "/v1/templates/" + ID + "/status"); + take("DELETE", "/v1/templates/" + ID); + } - List result = templateService.list(); - assertEquals(1, result.size()); + @Test + @DisplayName("should reject null id locally") + void shouldRejectNullId() { + assertThrows(RuntimeException.class, () -> arara.getTemplates().getById(null)); + assertThrows(RuntimeException.class, () -> arara.getTemplates().getStatus(null)); + assertThrows(RuntimeException.class, () -> arara.getTemplates().delete(null)); + assertThrows(RuntimeException.class, () -> arara.getTemplates().analytics(null, "7d")); + assertEquals(0, server.getRequestCount()); } @Test - @DisplayName("should get template by ID") - void shouldGetTemplateById() { - UUID id = UUID.randomUUID(); - TemplateResponse expected = TemplateResponse.builder().id(id).build(); - when(httpClient.get("/v1/templates/" + id, TemplateResponse.class)).thenReturn(expected); - - TemplateResponse result = templateService.getById(id); - assertEquals(expected, result); + @DisplayName("should POST /v1/templates with body, language and headerType") + void shouldCreateTemplate() throws Exception { + respond(201, TEMPLATE); + + arara.getTemplates().create(CreateTemplateRequest.builder() + .name("boas_vindas") + .category("UTILITY") + .body("Oi {{1}}") + .headerType("IMAGE") + .samples(Map.of("1", "Ana")) + .build()); + + JsonNode body = json(take("POST", "/v1/templates")); + assertEquals("Oi {{1}}", body.get("body").asText()); + assertEquals("pt_BR", body.get("language").asText()); + assertEquals("IMAGE", body.get("headerType").asText()); } @Test - @DisplayName("should delete template") - void shouldDeleteTemplate() { - UUID id = UUID.randomUUID(); - templateService.delete(id); - verify(httpClient).delete("/v1/templates/" + id); + @DisplayName("should GET analytics globally and per template") + void shouldGetAnalytics() throws Exception { + respond(200, "{\"sent\":10}"); + respond(200, "{\"sent\":3}"); + + assertEquals(10, arara.getTemplates().analytics("7d").get("sent")); + assertEquals(3, arara.getTemplates().analytics(ID, null).get("sent")); + + take("GET", "/v1/templates/analytics?period=7d"); + take("GET", "/v1/templates/" + ID + "/analytics"); } @Test - @DisplayName("should get template status") - void shouldGetTemplateStatus() { - UUID id = UUID.randomUUID(); - TemplateStatusResponse expected = TemplateStatusResponse.builder().status("APPROVED").build(); - when(httpClient.get("/v1/templates/" + id + "/status", TemplateStatusResponse.class)).thenReturn(expected); - - TemplateStatusResponse result = templateService.getStatus(id); - assertEquals(expected, result); + @DisplayName("should surface 400 INVALID_PATH_PARAM as typed error") + void shouldSurfaceInvalidPathParam() { + respond(400, "{\"error\":{\"code\":\"INVALID_PATH_PARAM\",\"message\":\"id\",\"details\":{}}}"); + + AraraApiException error = assertThrows(AraraApiException.class, () -> arara.getTemplates().getById(ID)); + + assertEquals("INVALID_PATH_PARAM", error.getCode()); } } diff --git a/src/test/java/com/ararahq/arara/sdk/services/UserServiceTest.java b/src/test/java/com/ararahq/arara/sdk/services/UserServiceTest.java deleted file mode 100644 index b5d1630..0000000 --- a/src/test/java/com/ararahq/arara/sdk/services/UserServiceTest.java +++ /dev/null @@ -1,311 +0,0 @@ -package com.ararahq.arara.sdk.services; - -import com.ararahq.arara.sdk.http.AraraHttpClient; -import com.ararahq.arara.sdk.models.UpdateUserRequest; -import com.ararahq.arara.sdk.models.UserResponse; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Nested; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -/** - * Unit tests for UserService. - */ -@ExtendWith(MockitoExtension.class) -@DisplayName("UserService Tests") -class UserServiceTest { - - @Mock - private AraraHttpClient httpClient; - - private UserService userService; - - @BeforeEach - void setUp() { - userService = new UserService(httpClient); - } - - @Nested - @DisplayName("me() method") - class MeMethodTests { - - @Test - @DisplayName("should retrieve current user information successfully") - void shouldRetrieveCurrentUserInformationSuccessfully() { - // Arrange - UserResponse expectedUser = UserResponse.builder() - .name("John Doe") - .email("john.doe@example.com") - .role("ADMIN") - .build(); - - when(httpClient.get("/users/me", UserResponse.class)) - .thenReturn(expectedUser); - - // Act - UserResponse result = userService.me(); - - // Assert - assertNotNull(result); - assertEquals("John Doe", result.getName()); - assertEquals("john.doe@example.com", result.getEmail()); - assertEquals("ADMIN", result.getRole()); - verify(httpClient, times(1)).get("/users/me", UserResponse.class); - } - - @Test - @DisplayName("should call correct endpoint") - void shouldCallCorrectEndpoint() { - // Arrange - UserResponse mockResponse = UserResponse.builder() - .name("Test User") - .email("test@example.com") - .role("USER") - .build(); - - when(httpClient.get("/users/me", UserResponse.class)) - .thenReturn(mockResponse); - - // Act - userService.me(); - - // Assert - verify(httpClient, times(1)).get("/users/me", UserResponse.class); - } - - @Test - @DisplayName("should retrieve user with various roles") - void shouldRetrieveUserWithVariousRoles() { - // Test with different roles - String[] roles = { "ADMIN", "USER", "VIEWER", "EDITOR", "GUEST" }; - - for (String role : roles) { - // Arrange - UserResponse mockResponse = UserResponse.builder() - .name("User with " + role) - .email("user." + role.toLowerCase() + "@example.com") - .role(role) - .build(); - - when(httpClient.get("/users/me", UserResponse.class)) - .thenReturn(mockResponse); - - // Act - UserResponse result = userService.me(); - - // Assert - assertNotNull(result); - assertEquals(role, result.getRole()); - assertTrue(result.getEmail().contains(role.toLowerCase())); - } - } - - @Test - @DisplayName("should retrieve user with all fields populated") - void shouldRetrieveUserWithAllFieldsPopulated() { - // Arrange - UserResponse expectedUser = UserResponse.builder() - .name("Jane Smith") - .email("jane.smith@ararahq.com") - .role("ADMIN") - .build(); - - when(httpClient.get("/users/me", UserResponse.class)) - .thenReturn(expectedUser); - - // Act - UserResponse result = userService.me(); - - // Assert - assertNotNull(result); - assertNotNull(result.getName()); - assertNotNull(result.getEmail()); - assertNotNull(result.getRole()); - assertEquals("Jane Smith", result.getName()); - assertEquals("jane.smith@ararahq.com", result.getEmail()); - assertEquals("ADMIN", result.getRole()); - } - - @Test - @DisplayName("should return user response with email verification") - void shouldReturnUserResponseWithEmailVerification() { - // Arrange - String expectedEmail = "verified@example.com"; - UserResponse mockResponse = UserResponse.builder() - .name("Verified User") - .email(expectedEmail) - .role("USER") - .build(); - - when(httpClient.get("/users/me", UserResponse.class)) - .thenReturn(mockResponse); - - // Act - UserResponse result = userService.me(); - - // Assert - assertNotNull(result); - assertEquals(expectedEmail, result.getEmail()); - assertTrue(result.getEmail().contains("@example.com")); - } - - @Test - @DisplayName("should retrieve multiple times independently") - void shouldRetrieveMultipleTimesIndependently() { - // Arrange - UserResponse mockResponse = UserResponse.builder() - .name("Test User") - .email("test@example.com") - .role("USER") - .build(); - - when(httpClient.get("/users/me", UserResponse.class)) - .thenReturn(mockResponse); - - // Act - UserResponse first = userService.me(); - UserResponse second = userService.me(); - UserResponse third = userService.me(); - - // Assert - assertEquals(first.getName(), second.getName()); - assertEquals(second.getEmail(), third.getEmail()); - verify(httpClient, times(3)).get("/users/me", UserResponse.class); - } - - @Test - @DisplayName("should handle user with special characters in name") - void shouldHandleUserWithSpecialCharactersInName() { - // Arrange - UserResponse mockResponse = UserResponse.builder() - .name("José da Silva") - .email("jose.silva@example.com") - .role("USER") - .build(); - - when(httpClient.get("/users/me", UserResponse.class)) - .thenReturn(mockResponse); - - // Act - UserResponse result = userService.me(); - - // Assert - assertNotNull(result); - assertEquals("José da Silva", result.getName()); - assertTrue(result.getName().contains("José")); - } - - @Test - @DisplayName("should handle user with minimal information") - void shouldHandleUserWithMinimalInformation() { - // Arrange - UserResponse mockResponse = UserResponse.builder() - .name("User") - .email("user@example.com") - .role("GUEST") - .build(); - - when(httpClient.get("/users/me", UserResponse.class)) - .thenReturn(mockResponse); - - // Act - UserResponse result = userService.me(); - - // Assert - assertNotNull(result); - assertNotNull(result.getName()); - assertNotNull(result.getEmail()); - assertNotNull(result.getRole()); - } - } - - @Nested - @DisplayName("User authentication context") - class AuthenticationContextTests { - - @Test - @DisplayName("should represent authenticated user") - void shouldRepresentAuthenticatedUser() { - // Arrange - UserResponse authenticatedUser = UserResponse.builder() - .name("Authenticated User") - .email("auth@example.com") - .role("ADMIN") - .build(); - - when(httpClient.get("/users/me", UserResponse.class)) - .thenReturn(authenticatedUser); - - // Act - UserResponse result = userService.me(); - - // Assert - assertNotNull(result); - assertTrue(result.getRole().equals("ADMIN") || result.getRole().equals("USER")); - } - - @Test - @DisplayName("should always return same endpoint regardless of multiple calls") - void shouldAlwaysReturnSameEndpointRegardlessOfMultipleCalls() { - // Arrange - UserResponse mockResponse = UserResponse.builder() - .name("Consistent User") - .email("consistent@example.com") - .role("USER") - .build(); - - when(httpClient.get("/users/me", UserResponse.class)) - .thenReturn(mockResponse); - - // Act & Assert - for (int i = 0; i < 5; i++) { - UserResponse result = userService.me(); - assertEquals("consistent@example.com", result.getEmail()); - } - - verify(httpClient, times(5)).get("/users/me", UserResponse.class); - } - } - - @Nested - @DisplayName("updateMe() method") - class UpdateMeMethodTests { - - @Test - @DisplayName("should update user information successfully") - void shouldUpdateUserInformationSuccessfully() { - // Arrange - UpdateUserRequest request = UpdateUserRequest.builder() - .name("New Name") - .phoneNumber("+5511999998888") - .build(); - - UserResponse expectedResponse = UserResponse.builder() - .name("New Name") - .email("john.doe@example.com") - .phoneNumber("+5511999998888") - .build(); - - when(httpClient.patch("/users/me", request, UserResponse.class)) - .thenReturn(expectedResponse); - - // Act - UserResponse result = userService.updateMe(request); - - // Assert - assertNotNull(result); - assertEquals("New Name", result.getName()); - assertEquals("+5511999998888", result.getPhoneNumber()); - verify(httpClient, times(1)).patch("/users/me", request, UserResponse.class); - } - } -} diff --git a/src/test/java/com/ararahq/arara/sdk/services/WalletServiceTest.java b/src/test/java/com/ararahq/arara/sdk/services/WalletServiceTest.java index 388dc27..8be3c3b 100644 --- a/src/test/java/com/ararahq/arara/sdk/services/WalletServiceTest.java +++ b/src/test/java/com/ararahq/arara/sdk/services/WalletServiceTest.java @@ -1,104 +1,42 @@ package com.ararahq.arara.sdk.services; -import com.ararahq.arara.sdk.exceptions.AraraException; -import com.ararahq.arara.sdk.http.AraraHttpClient; -import com.ararahq.arara.sdk.models.AutoRechargeSettings; import com.ararahq.arara.sdk.models.UpdateAutoRechargeRequest; import com.ararahq.arara.sdk.models.WalletTransactionPage; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; import java.math.BigDecimal; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoInteractions; -import static org.mockito.Mockito.when; -@ExtendWith(MockitoExtension.class) -@DisplayName("WalletService Tests") -class WalletServiceTest { - - @Mock - private AraraHttpClient httpClient; - - private WalletService walletService; - - @BeforeEach - void setUp() { - walletService = new WalletService(httpClient); - } - - @Test - @DisplayName("should list wallet transactions with pagination") - void shouldListTransactions() { - WalletTransactionPage expected = WalletTransactionPage.builder() - .page(0) - .size(20) - .totalElements(3) - .build(); - when(httpClient.get("/v1/wallet/transactions?page=0&size=20", WalletTransactionPage.class)) - .thenReturn(expected); - - WalletTransactionPage result = walletService.transactions(0, 20); - - assertEquals(3, result.getTotalElements()); - verify(httpClient, times(1)) - .get("/v1/wallet/transactions?page=0&size=20", WalletTransactionPage.class); - } +@DisplayName("WalletService against fake API") +class WalletServiceTest extends FakeApi { @Test - @DisplayName("should return auto-recharge settings") - void shouldGetAutoRecharge() { - AutoRechargeSettings expected = AutoRechargeSettings.builder() - .enabled(true) - .threshold(BigDecimal.valueOf(10)) - .amount(BigDecimal.valueOf(50)) - .build(); - when(httpClient.get("/v1/wallet/auto-recharge", AutoRechargeSettings.class)).thenReturn(expected); + @DisplayName("should parse wallet transactions as {content,totalPages,totalElements}") + void shouldListTransactions() throws Exception { + respond(200, "{\"content\":[{\"id\":\"t1\",\"amount\":50.00,\"type\":\"CREDIT\"}]," + + "\"totalPages\":1,\"totalElements\":1}"); - AutoRechargeSettings result = walletService.getAutoRecharge(); + WalletTransactionPage page = arara.getWallet().transactions(0, 20); - assertTrue(result.isEnabled()); - assertEquals(BigDecimal.valueOf(50), result.getAmount()); - verify(httpClient, times(1)).get("/v1/wallet/auto-recharge", AutoRechargeSettings.class); + take("GET", "/v1/wallet/transactions?page=0&size=20"); + assertEquals("t1", page.getContent().get(0).getId()); + assertEquals(1, page.getTotalElements()); } @Test - @DisplayName("should update auto-recharge settings") - void shouldUpdateAutoRecharge() { - UpdateAutoRechargeRequest request = UpdateAutoRechargeRequest.builder() - .enabled(true) - .threshold(BigDecimal.valueOf(15)) - .amount(BigDecimal.valueOf(100)) - .build(); - AutoRechargeSettings expected = AutoRechargeSettings.builder() - .enabled(true) - .amount(BigDecimal.valueOf(100)) - .build(); - when(httpClient.patch("/v1/wallet/auto-recharge", request, AutoRechargeSettings.class)) - .thenReturn(expected); + @DisplayName("should read and patch auto-recharge") + void shouldCoverAutoRecharge() throws Exception { + respond(200, "{\"enabled\":true,\"threshold\":100,\"amount\":500}"); + respond(200, "{\"enabled\":false}"); - AutoRechargeSettings result = walletService.updateAutoRecharge(request); + assertTrue(arara.getWallet().getAutoRecharge().isEnabled()); + arara.getWallet().updateAutoRecharge(UpdateAutoRechargeRequest.builder() + .enabled(false).threshold(new BigDecimal("100")).build()); - assertNotNull(result); - assertEquals(BigDecimal.valueOf(100), result.getAmount()); - verify(httpClient, times(1)) - .patch("/v1/wallet/auto-recharge", request, AutoRechargeSettings.class); - } - - @Test - @DisplayName("should reject null auto-recharge update request") - void shouldRejectNullUpdate() { - assertThrows(AraraException.class, () -> walletService.updateAutoRecharge(null)); - verifyNoInteractions(httpClient); + take("GET", "/v1/wallet/auto-recharge"); + assertEquals(false, json(take("PATCH", "/v1/wallet/auto-recharge")).get("enabled").asBoolean()); } } diff --git a/src/test/java/com/ararahq/arara/sdk/utils/ValidationUtilsTest.java b/src/test/java/com/ararahq/arara/sdk/utils/ValidationUtilsTest.java index e36e875..8e10533 100644 --- a/src/test/java/com/ararahq/arara/sdk/utils/ValidationUtilsTest.java +++ b/src/test/java/com/ararahq/arara/sdk/utils/ValidationUtilsTest.java @@ -2,275 +2,60 @@ import com.ararahq.arara.sdk.exceptions.AraraException; import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.NullAndEmptySource; +import org.junit.jupiter.params.provider.ValueSource; + import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; -/** - * Unit tests for ValidationUtils. - */ -@DisplayName("ValidationUtils Tests") +@DisplayName("ValidationUtils and QueryString") class ValidationUtilsTest { - @Nested - @DisplayName("validateWhatsAppNumber() method") - class ValidateWhatsAppNumberTests { - @Test - @DisplayName("should accept valid WhatsApp number") - void shouldAcceptValidWhatsAppNumber() { - // Act & Assert - No exception should be thrown - assertDoesNotThrow(() -> ValidationUtils.validateWhatsAppNumber("whatsapp:+5511999998888")); - } - - @Test - @DisplayName("should accept valid WhatsApp number with different country code") - void shouldAcceptValidWhatsAppNumberWithDifferentCountryCode() { - // Act & Assert - assertDoesNotThrow(() -> ValidationUtils.validateWhatsAppNumber("whatsapp:+15551234567")); - assertDoesNotThrow(() -> ValidationUtils.validateWhatsAppNumber("whatsapp:+447700900123")); - } - - @Test - @DisplayName("should reject null number") - void shouldRejectNullNumber() { - // Act & Assert - AraraException exception = assertThrows(AraraException.class, - () -> ValidationUtils.validateWhatsAppNumber(null)); - assertTrue(exception.getMessage().contains("whatsapp:+")); - } - - @Test - @DisplayName("should reject number without whatsapp prefix") - void shouldRejectNumberWithoutWhatsappPrefix() { - // Act & Assert - assertThrows(AraraException.class, - () -> ValidationUtils.validateWhatsAppNumber("+5511999998888")); - } - - @Test - @DisplayName("should reject number with invalid prefix") - void shouldRejectNumberWithInvalidPrefix() { - // Act & Assert - assertThrows(AraraException.class, - () -> ValidationUtils.validateWhatsAppNumber("telegram:+5511999998888")); - } - - @Test - @DisplayName("should reject empty string") - void shouldRejectEmptyString() { - // Act & Assert - assertThrows(AraraException.class, - () -> ValidationUtils.validateWhatsAppNumber("")); - } - - @Test - @DisplayName("should reject number without plus sign") - void shouldRejectNumberWithoutPlusSign() { - // Act & Assert - assertThrows(AraraException.class, - () -> ValidationUtils.validateWhatsAppNumber("whatsapp:5511999998888")); - } - - @Test - @DisplayName("should reject incomplete format") - void shouldRejectIncompleteFormat() { - // Act & Assert - assertThrows(AraraException.class, - () -> ValidationUtils.validateWhatsAppNumber("whatsapp:")); - } - - @Test - @DisplayName("should accept valid Brazilian number") - void shouldAcceptValidBrazilianNumber() { - // Act & Assert - assertDoesNotThrow(() -> ValidationUtils.validateWhatsAppNumber("whatsapp:+5511999998888")); - assertDoesNotThrow(() -> ValidationUtils.validateWhatsAppNumber("whatsapp:+5521987654321")); - } - - @Test - @DisplayName("should accept valid US number") - void shouldAcceptValidUSNumber() { - // Act & Assert - assertDoesNotThrow(() -> ValidationUtils.validateWhatsAppNumber("whatsapp:+12015550123")); - } - - @Test - @DisplayName("should validate multiple numbers") - void shouldValidateMultipleNumbers() { - // Arrange - String[] validNumbers = { - "whatsapp:+5511999998888", - "whatsapp:+5521987654321", - "whatsapp:+15551234567", - "whatsapp:+447700900123" - }; - // Act & Assert - for (String number : validNumbers) { - assertDoesNotThrow(() -> ValidationUtils.validateWhatsAppNumber(number)); - } - } - @Test - @DisplayName("should reject various invalid formats") - void shouldRejectVariousInvalidFormats() { - // Arrange - String[] invalidNumbers = { - "+5511999998888", // Missing prefix - "whatsapp5511999998888", // Missing + and : - "whatsapp:5511999998888", // Missing + - "5511999998888", // No prefix or + - "tel:+5511999998888", // Wrong prefix - null // Null value - }; - // Act & Assert - for (String number : invalidNumbers) { - assertThrows(AraraException.class, - () -> ValidationUtils.validateWhatsAppNumber(number), - "Should reject: " + number); - } - } + @ParameterizedTest + @ValueSource(strings = { + "whatsapp:+5511999998888", "+5511999998888", "5511999998888", + "+1 (201) 555-0123", "whatsapp:+447700900123", "1234567", "123456789012345" + }) + @DisplayName("should accept every receiver format the API accepts") + void shouldAcceptApiFormats(String phone) { + assertDoesNotThrow(() -> ValidationUtils.validateWhatsAppNumber(phone)); } - @Nested - @DisplayName("checkNotNull() method") - class CheckNotNullTests { - @Test - @DisplayName("should accept non-null object") - void shouldAcceptNonNullObject() { - // Act & Assert - assertDoesNotThrow(() -> ValidationUtils.checkNotNull("test", "param")); - assertDoesNotThrow(() -> ValidationUtils.checkNotNull(new Object(), "param")); - assertDoesNotThrow(() -> ValidationUtils.checkNotNull(123, "param")); - } - - @Test - @DisplayName("should reject null object") - void shouldRejectNullObject() { - // Act & Assert - assertThrows(AraraException.class, - () -> ValidationUtils.checkNotNull(null, "testParam")); - } - - @Test - @DisplayName("should include parameter name in error message") - void shouldIncludeParameterNameInErrorMessage() { - // Act - AraraException exception = assertThrows(AraraException.class, - () -> ValidationUtils.checkNotNull(null, "myParameter")); - // Assert - assertTrue(exception.getMessage().contains("myParameter")); - } - - @Test - @DisplayName("should handle various parameter names") - void shouldHandleVariousParameterNames() { - // Arrange - String[] paramNames = { "request", "id", "name", "email", "config" }; - // Act & Assert - for (String paramName : paramNames) { - AraraException exception = assertThrows(AraraException.class, - () -> ValidationUtils.checkNotNull(null, paramName)); - assertTrue(exception.getMessage().contains(paramName)); - } - } - - @Test - @DisplayName("should accept zero value") - void shouldAcceptZeroValue() { - // Act & Assert - assertDoesNotThrow(() -> ValidationUtils.checkNotNull(0, "zeroValue")); - } - - @Test - @DisplayName("should accept false value") - void shouldAcceptFalseValue() { - // Act & Assert - assertDoesNotThrow(() -> ValidationUtils.checkNotNull(false, "falseValue")); - } - - @Test - @DisplayName("should accept empty string") - void shouldAcceptEmptyString() { - // Act & Assert - assertDoesNotThrow(() -> ValidationUtils.checkNotNull("", "emptyString")); - } - - @Test - @DisplayName("should accept empty collection") - void shouldAcceptEmptyCollection() { - // Act & Assert - assertDoesNotThrow(() -> ValidationUtils.checkNotNull(java.util.Collections.emptyList(), "emptyList")); - } - - @Test - @DisplayName("should validate multiple objects") - void shouldValidateMultipleObjects() { - // Arrange - Object obj1 = new Object(); - Object obj2 = "test"; - Object obj3 = 123; - // Act & Assert - assertDoesNotThrow(() -> ValidationUtils.checkNotNull(obj1, "obj1")); - assertDoesNotThrow(() -> ValidationUtils.checkNotNull(obj2, "obj2")); - assertDoesNotThrow(() -> ValidationUtils.checkNotNull(obj3, "obj3")); - } + @ParameterizedTest + @NullAndEmptySource + @ValueSource(strings = {" ", "abc", "123456", "1234567890123456", "whatsapp:+", "tel:"}) + @DisplayName("should reject what the API rejects (fewer than 7 or more than 15 digits)") + void shouldRejectInvalid(String phone) { + AraraException error = assertThrows(AraraException.class, + () -> ValidationUtils.validateWhatsAppNumber(phone)); + assertTrue(error.getMessage().startsWith("Invalid phone number")); } - @Nested - @DisplayName("Combined validation scenarios") - class CombinedValidationScenarios { - @Test - @DisplayName("should validate request object and phone number together") - void shouldValidateRequestObjectAndPhoneNumberTogether() { - // Arrange - Object request = new Object(); - String phoneNumber = "whatsapp:+5511999998888"; - // Act & Assert - assertDoesNotThrow(() -> { - ValidationUtils.checkNotNull(request, "request"); - ValidationUtils.validateWhatsAppNumber(phoneNumber); - }); - } - - @Test - @DisplayName("should fail fast on null request") - void shouldFailFastOnNullRequest() { - // Arrange - String phoneNumber = "whatsapp:+5511999998888"; - // Act & Assert - assertThrows(AraraException.class, () -> { - ValidationUtils.checkNotNull(null, "request"); - ValidationUtils.validateWhatsAppNumber(phoneNumber); - }); - } + @Test + @DisplayName("should include the parameter name when null") + void shouldIncludeParameterName() { + AraraException error = assertThrows(AraraException.class, + () -> ValidationUtils.checkNotNull(null, "myParameter")); + assertTrue(error.getMessage().contains("myParameter")); + assertDoesNotThrow(() -> ValidationUtils.checkNotNull(0, "zero")); + } - @Test - @DisplayName("should fail on invalid phone number even with valid request") - void shouldFailOnInvalidPhoneNumberEvenWithValidRequest() { - // Arrange - Object request = new Object(); - String phoneNumber = "+5511999998888"; // Missing prefix - // Act & Assert - assertThrows(AraraException.class, () -> { - ValidationUtils.checkNotNull(request, "request"); - ValidationUtils.validateWhatsAppNumber(phoneNumber); - }); - } + @Test + @DisplayName("should encode query values and skip nulls") + void shouldBuildQueryString() { + assertEquals("/p?a=1&q=a%26b+c", + QueryString.create().add("a", 1).add("skip", null).add("q", "a&b c").appendTo("/p")); + assertEquals("/p", QueryString.create().add("x", null).appendTo("/p")); + } - @Test - @DisplayName("should validate multiple phone numbers in sequence") - void shouldValidateMultiplePhoneNumbersInSequence() { - // Arrange - String[] phones = { - "whatsapp:+5511999998888", - "whatsapp:+5521987654321", - "whatsapp:+15551234567" - }; - // Act & Assert - for (String phone : phones) { - assertDoesNotThrow(() -> ValidationUtils.validateWhatsAppNumber(phone)); - } - } + @Test + @DisplayName("should encode path segments with plus and spaces") + void shouldEncodePathSegment() { + assertEquals("%2B5511999998888", QueryString.encodePathSegment("+5511999998888")); + assertEquals("a%20b%2Fc", QueryString.encodePathSegment("a b/c")); } }