diff --git a/go.mod b/go.mod index b531610..7c4c7aa 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/ararahq/cli -go 1.26.3 +go 1.26.5 require ( github.com/charmbracelet/bubbles v1.0.0 diff --git a/internal/api/errors.go b/internal/api/errors.go index 9279594..b8ccdc4 100644 --- a/internal/api/errors.go +++ b/internal/api/errors.go @@ -5,12 +5,16 @@ import ( "errors" "fmt" "net/http" + "strings" "time" ) const ( errorCodeWindowClosed = "ararahq-63016" - errorCodeInvalidNumber = "ararahq-63024" + errorCodeReengagement = "ararahq-reengagement" + errorCodeInvalidNumber = "ararahq-invalid-number" + errorCodeTemplateError = "ararahq-63024" + errorCodeTemplateNotFound = "ararahq-template-not-found" errorCodeInsufficientFunds = "ararahq-insufficient-funds" errorCodeRateLimit = "ararahq-rate-limit" errorCodeTemplateMismatch = "ararahq-template-mismatch" @@ -19,7 +23,10 @@ const ( var friendlyMessages = map[string]string{ errorCodeWindowClosed: "Janela de 24h fechada. Envie um template primeiro.", + errorCodeReengagement: "Janela de 24h fechada. Envie um template primeiro.", errorCodeInvalidNumber: "Numero invalido. Use formato: +5511999999999", + errorCodeTemplateError: "Template rejeitado ou pausado pela Meta. Confira o status no dashboard.", + errorCodeTemplateNotFound: "Template nao existe ou nao esta aprovado nesta conta.", errorCodeInsufficientFunds: "Saldo insuficiente. Recarregue em ararahq.com/dashboard", errorCodeRateLimit: "Rate limit atingido. Aguarde ou use campaigns para envio em massa.", errorCodeTemplateMismatch: "Variaveis nao batem com o template.", @@ -30,13 +37,34 @@ type APIError struct { StatusCode int Code string `json:"code"` Message string `json:"message"` - RawBody string - RetryAfter time.Duration + // DiagnosticCode carries the real business code ("ararahq-63016") that the + // backend buries in error.details.diagnostic.code. GlobalExceptionHandler + // flattens every BusinessException to code "UNPROCESSABLE_ENTITY", so Code + // alone never identifies what went wrong. + DiagnosticCode string + // DiagnosticHint is the backend-authored explanation (whatHappened + + // howToAct) used when the code has no entry in friendlyMessages. The + // backend emits a diagnostic for every provider code, including ones the + // CLI does not know about. + DiagnosticHint string + RawBody string + RetryAfter time.Duration +} + +// BusinessCode returns the code that identifies the failure for the user, +// preferring the diagnostic over the generic envelope code. +func (apiError *APIError) BusinessCode() string { + if apiError.DiagnosticCode != "" { + return apiError.DiagnosticCode + } + + return apiError.Code } func (apiError *APIError) Error() string { - if apiError.Code != "" { - return fmt.Sprintf("[%d] %s: %s", apiError.StatusCode, apiError.Code, apiError.Message) + businessCode := apiError.BusinessCode() + if businessCode != "" { + return fmt.Sprintf("[%d] %s: %s", apiError.StatusCode, businessCode, apiError.Message) } if apiError.Message != "" { @@ -47,11 +75,15 @@ func (apiError *APIError) Error() string { } func (apiError *APIError) FriendlyMessage() string { - friendlyMessage, exists := friendlyMessages[apiError.Code] + friendlyMessage, exists := friendlyMessages[apiError.BusinessCode()] if exists { return friendlyMessage } + if apiError.DiagnosticHint != "" { + return apiError.DiagnosticHint + } + if apiError.Message != "" { return apiError.Message } @@ -84,6 +116,45 @@ type apiErrorEnvelope struct { type apiErrorPayload struct { Code string `json:"code"` Message string `json:"message"` + // Details is free-form per exception type: some handlers put a diagnostic + // object in it, others put plan metadata or a list. Decoding it lazily + // keeps an unexpected shape from failing the whole envelope and losing the + // error code. + Details json.RawMessage `json:"details"` +} + +type apiErrorDetails struct { + Diagnostic apiErrorDiagnostic `json:"diagnostic"` +} + +type apiErrorDiagnostic struct { + Code string `json:"code"` + WhatHappened string `json:"whatHappened"` + HowToAct string `json:"howToAct"` +} + +func (diagnostic apiErrorDiagnostic) hint() string { + parts := make([]string, 0, 2) + for _, part := range []string{diagnostic.WhatHappened, diagnostic.HowToAct} { + if trimmed := strings.TrimSpace(part); trimmed != "" { + parts = append(parts, trimmed) + } + } + + return strings.Join(parts, " ") +} + +func extractDiagnostic(rawDetails json.RawMessage) apiErrorDiagnostic { + if len(rawDetails) == 0 { + return apiErrorDiagnostic{} + } + + var details apiErrorDetails + if unmarshalError := json.Unmarshal(rawDetails, &details); unmarshalError != nil { + return apiErrorDiagnostic{} + } + + return details.Diagnostic } func ParseErrorResponse(statusCode int, body []byte) *APIError { @@ -91,11 +162,14 @@ func ParseErrorResponse(statusCode int, body []byte) *APIError { var envelope apiErrorEnvelope if unmarshalError := json.Unmarshal(body, &envelope); unmarshalError == nil && envelope.Error.Code != "" { + diagnostic := extractDiagnostic(envelope.Error.Details) return &APIError{ - StatusCode: statusCode, - Code: envelope.Error.Code, - Message: envelope.Error.Message, - RawBody: rawBody, + StatusCode: statusCode, + Code: envelope.Error.Code, + Message: envelope.Error.Message, + DiagnosticCode: strings.TrimSpace(diagnostic.Code), + DiagnosticHint: diagnostic.hint(), + RawBody: rawBody, } } diff --git a/internal/api/errors_test.go b/internal/api/errors_test.go index 9d5a137..b8c835b 100644 --- a/internal/api/errors_test.go +++ b/internal/api/errors_test.go @@ -86,6 +86,69 @@ func TestAPIError_FriendlyMessage(t *testing.T) { } } +func TestParseErrorResponse_ReadsDiagnosticCode(t *testing.T) { + body := []byte(`{"error":{"code":"UNPROCESSABLE_ENTITY","message":"Janela de 24h fechada.",` + + `"details":{"diagnostic":{"code":"ararahq-63016","whatHappened":"Janela fechada.",` + + `"howToAct":"Envie um template."}}}}`) + got := ParseErrorResponse(http.StatusUnprocessableEntity, body) + + if got.Code != "UNPROCESSABLE_ENTITY" { + t.Errorf("envelope code should be preserved, got %q", got.Code) + } + if got.DiagnosticCode != errorCodeWindowClosed { + t.Errorf("diagnostic code: want %q, got %q", errorCodeWindowClosed, got.DiagnosticCode) + } + if got.BusinessCode() != errorCodeWindowClosed { + t.Errorf("business code should prefer the diagnostic, got %q", got.BusinessCode()) + } + if !strings.Contains(got.FriendlyMessage(), "Janela de 24h fechada. Envie um template primeiro.") { + t.Errorf("friendly message should be reachable, got %q", got.FriendlyMessage()) + } +} + +func TestParseErrorResponse_UnknownDiagnosticFallsBackToHint(t *testing.T) { + body := []byte(`{"error":{"code":"UNPROCESSABLE_ENTITY","message":"[131037]",` + + `"details":{"diagnostic":{"code":"ararahq-display-name",` + + `"whatHappened":"Nome de exibicao nao aprovado.","howToAct":"Peca a aprovacao."}}}}`) + got := ParseErrorResponse(http.StatusUnprocessableEntity, body) + + if got.BusinessCode() != "ararahq-display-name" { + t.Errorf("business code: got %q", got.BusinessCode()) + } + want := "Nome de exibicao nao aprovado. Peca a aprovacao." + if got.FriendlyMessage() != want { + t.Errorf("friendly message: want %q, got %q", want, got.FriendlyMessage()) + } +} + +func TestParseErrorResponse_DetailsWithoutDiagnostic(t *testing.T) { + body := []byte(`{"error":{"code":"PLAN_FEATURE_LOCKED","message":"Faca upgrade.",` + + `"details":{"feature":"campaigns","currentPlan":"FREE","upgradeTo":"VOO"}}}`) + got := ParseErrorResponse(http.StatusForbidden, body) + + if got.BusinessCode() != "PLAN_FEATURE_LOCKED" { + t.Errorf("business code should fall back to the envelope code, got %q", got.BusinessCode()) + } + if got.DiagnosticCode != "" { + t.Errorf("no diagnostic expected, got %q", got.DiagnosticCode) + } + if got.FriendlyMessage() != "Faca upgrade." { + t.Errorf("friendly message: got %q", got.FriendlyMessage()) + } +} + +func TestParseErrorResponse_NonObjectDetailsKeepsCode(t *testing.T) { + body := []byte(`{"error":{"code":"VALIDATION_ERROR","message":"invalido","details":["campo"]}}`) + got := ParseErrorResponse(http.StatusBadRequest, body) + + if got.Code != "VALIDATION_ERROR" { + t.Errorf("unexpected details shape must not lose the code, got %q", got.Code) + } + if got.DiagnosticCode != "" { + t.Errorf("no diagnostic expected, got %q", got.DiagnosticCode) + } +} + func TestIsAuthError(t *testing.T) { if !IsAuthError(&APIError{StatusCode: http.StatusUnauthorized}) { t.Error("401 should be auth error") diff --git a/internal/api/messages.go b/internal/api/messages.go index f4b10da..222c6ac 100644 --- a/internal/api/messages.go +++ b/internal/api/messages.go @@ -12,12 +12,17 @@ const ( messagesBasePath = "/v1/messages" ) +// SendMessageRequest mirrors the Kotlin SendMessageRequest DTO. Every field is +// camelCase except scheduledAt, which the backend binds with +// @JsonProperty("scheduled_at") and no @JsonAlias. Sending "scheduledAt" is +// dropped silently (FAIL_ON_UNKNOWN_PROPERTIES is off), so the message goes out +// immediately and the caller never sees an error. type SendMessageRequest struct { Receiver string `json:"receiver"` TemplateName string `json:"templateName,omitempty"` TemplateVariables []string `json:"variables,omitempty"` Body string `json:"body,omitempty"` - ScheduledAt string `json:"scheduledAt,omitempty"` + ScheduledAt string `json:"scheduled_at,omitempty"` } type DryRunPreview struct { diff --git a/internal/api/messages_test.go b/internal/api/messages_test.go index 7a8f1e6..9d2c939 100644 --- a/internal/api/messages_test.go +++ b/internal/api/messages_test.go @@ -30,6 +30,45 @@ func TestEnsurePhonePrefix(t *testing.T) { } } +func TestSendMessageRequest_SerializesScheduledAtAsSnakeCase(t *testing.T) { + encoded, marshalErr := json.Marshal(SendMessageRequest{ + Receiver: "whatsapp:+5511999999999", + TemplateName: "hello", + ScheduledAt: "2026-01-01T00:00:00Z", + }) + if marshalErr != nil { + t.Fatalf("marshal: %v", marshalErr) + } + + var wire map[string]any + if err := json.Unmarshal(encoded, &wire); err != nil { + t.Fatalf("unmarshal: %v", err) + } + + if wire["scheduled_at"] != "2026-01-01T00:00:00Z" { + t.Errorf("backend binds scheduled_at, got payload %s", encoded) + } + if _, hasCamelCase := wire["scheduledAt"]; hasCamelCase { + t.Errorf("scheduledAt is dropped silently by the backend, got payload %s", encoded) + } +} + +func TestSendMessageRequest_OmitsScheduledAtWhenEmpty(t *testing.T) { + encoded, marshalErr := json.Marshal(SendMessageRequest{Receiver: "whatsapp:+5511", Body: "hi"}) + if marshalErr != nil { + t.Fatalf("marshal: %v", marshalErr) + } + + var wire map[string]any + if err := json.Unmarshal(encoded, &wire); err != nil { + t.Fatalf("unmarshal: %v", err) + } + + if _, present := wire["scheduled_at"]; present { + t.Errorf("empty schedule must not be sent, got payload %s", encoded) + } +} + func TestMessageResponse_UnmarshalNullIDAsEmpty(t *testing.T) { body := `{"id":null,"status":"queued","receiver":"+5511","mode":"test"}` var response MessageResponse diff --git a/internal/api/webhook_listener.go b/internal/api/webhook_listener.go index 7191bfc..6e1ad59 100644 --- a/internal/api/webhook_listener.go +++ b/internal/api/webhook_listener.go @@ -4,6 +4,7 @@ import ( "errors" "fmt" "net/http" + "strings" ) const ( @@ -97,7 +98,11 @@ func classifyCaptureError(err error) error { return ErrCaptureNotSupported } - if apiError.StatusCode == http.StatusConflict && apiError.Code == "capture_listener_active" { + // EqualFold porque o backend emite CAPTURE_LISTENER_ACTIVE em maiusculo + // (GlobalExceptionHandler.kt) e a comparacao exata em minusculo nunca casava: o usuario via + // um conflito generico em vez de quem esta com o listener e ate quando. + if apiError.StatusCode == http.StatusConflict && + strings.EqualFold(apiError.Code, "CAPTURE_LISTENER_ACTIVE") { return &CaptureConflictError{ ListenerID: stringFromDetails(apiError, "listenerId"), Owner: stringFromDetails(apiError, "owner"), diff --git a/internal/api/webhook_listener_test.go b/internal/api/webhook_listener_test.go index e498ed3..a3b906b 100644 --- a/internal/api/webhook_listener_test.go +++ b/internal/api/webhook_listener_test.go @@ -61,7 +61,7 @@ func TestCreateWebhookListener_409ReturnsTypedConflict(t *testing.T) { w.WriteHeader(http.StatusConflict) _, _ = w.Write([]byte(`{ "error":{ - "code":"capture_listener_active", + "code":"CAPTURE_LISTENER_ACTIVE", "message":"another CLI session is already capturing for this org", "details":{ "listenerId":"lst_existing", diff --git a/internal/cmd/listen_test.go b/internal/cmd/listen_test.go index 4181166..f0ef94f 100644 --- a/internal/cmd/listen_test.go +++ b/internal/cmd/listen_test.go @@ -432,7 +432,7 @@ func TestRunListenCapture_PropagatesConflict(t *testing.T) { if r.URL.Path == "/v1/cli/webhook-listeners" && r.Method == http.MethodPost { w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusConflict) - _, _ = w.Write([]byte(`{"error":{"code":"capture_listener_active","message":"taken","details":{"listenerId":"lst_other","owner":"laptop@there","expiresAt":"2026-12-01T00:00:00Z"}}}`)) + _, _ = w.Write([]byte(`{"error":{"code":"CAPTURE_LISTENER_ACTIVE","message":"taken","details":{"listenerId":"lst_other","owner":"laptop@there","expiresAt":"2026-12-01T00:00:00Z"}}}`)) return } w.WriteHeader(http.StatusNotFound) diff --git a/internal/mcp/errors.go b/internal/mcp/errors.go index 9e5ce30..5a1db4a 100644 --- a/internal/mcp/errors.go +++ b/internal/mcp/errors.go @@ -64,7 +64,7 @@ func classifyError(err error) toolErrorBody { var apiError *api.APIError if errors.As(err, &apiError) { body := toolErrorBody{ - Code: apiError.Code, + Code: apiError.BusinessCode(), Message: apiError.FriendlyMessage(), } if apiError.StatusCode == httpTooManyRequests || apiError.StatusCode >= 500 {