Skip to content

Fix stats grouped commands: response types and query param#2

Open
solovey23 wants to merge 2 commits intomailtrap:mainfrom
solovey23:main
Open

Fix stats grouped commands: response types and query param#2
solovey23 wants to merge 2 commits intomailtrap:mainfrom
solovey23:main

Conversation

@solovey23
Copy link
Copy Markdown

@solovey23 solovey23 commented Apr 16, 2026

Summary

  • Fix stats by-domain, by-category, by-esp, by-date commands that returned empty/zero values due to wrong response types — the API wraps stats under a nested "stats" key, but the CLI was deserializing into flat structs
  • Add proper wrapper types (DomainStats, CategoryStats, ESPStats, DateStats) with grouping-key columns (domain ID, category, ESP, date) in the output
  • Fix query parameter name from streams[] to sending_streams[] per API spec

Test plan

  • All 120 existing tests pass (go test ./...)
  • Manually verify mailtrap stats by-domain --start-date 2024-01-01 --end-date 2024-12-31 returns rows with domain IDs and stats
  • Manually verify mailtrap stats by-category, by-esp, by-date similarly show grouping keys
  • Verify --streams flag filters correctly (now sends sending_streams[] to API)

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added --merge-tag flag for contact field creation to specify merge tag templates.
    • Introduced --data-type flag for contact fields with supported values: text, integer, float, boolean, date.
  • Bug Fixes

    • Fixed stats commands to properly filter by sending streams.
    • Corrected tokens create request structure.
  • Documentation

    • Updated CLI flag documentation for contact fields and tokens commands.

Mariya Solovey and others added 2 commits April 8, 2026 16:30
…fields

- tokens/create.go: remove erroneous 'api_token' wrapper from POST body;
  API expects flat {"name": ..., "resources": [...]} at the top level
- contact_fields/create.go: add required --merge-tag flag (merge_tag is
  required by the Mailtrap API but was not exposed in the CLI)
- Update tests for both commands to reflect corrected behaviour; add
  TestContactFieldsCreateMissingMergeTag coverage
- Update README, TEST_PLAN, and skill reference docs to match

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Add proper nested response types (DomainStats, CategoryStats, ESPStats,
  DateStats) that match the API's wrapped format where stats are under a
  "stats" key alongside the grouping field
- Fix query parameter name from "streams[]" to "sending_streams[]" per API spec
- Add grouping-key columns (domain ID, category, ESP, date) to output
- Update test mock responses to use the correct nested API format

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Apr 16, 2026

📝 Walkthrough

Walkthrough

The changes update three main CLI command areas: contact fields now require a --merge-tag flag; token creation payload structure is flattened and gains a --permissions flag; stats commands consistently rename the stream query parameter to sending_streams[] and introduce grouped response types with custom JSON marshaling.

Changes

Cohort / File(s) Summary
Contact Fields Enhancement
README.md, internal/commands/contact_fields/create.go, internal/commands/contact_fields/contact_fields_test.go, skills/mailtrap-cli/references/contacts.md
Added required --merge-tag flag to the contact fields create command; updated command examples and documentation; added test coverage for the new flag including a negative test case for when it is omitted.
Tokens Create Refactoring
internal/commands/tokens/create.go, internal/commands/tokens/tokens_test.go, skills/mailtrap-cli/references/accounts.md
Flattened token creation request payload by removing the api_token wrapper object; added required --permissions flag for resource access specification; updated corresponding test assertions and documentation.
Stats Command Updates
internal/commands/stats/by_category.go, internal/commands/stats/by_date.go, internal/commands/stats/by_domain.go, internal/commands/stats/by_esp.go
Consistently renamed query parameter from streams[] to sending_streams[] across all four grouped stats commands; updated response types to use category-, date-, domain-, and ESP-specific stat types; switched output column definitions to match new response structures.
Stats Type and Test Infrastructure
internal/commands/stats/get.go, internal/commands/stats/stats_test.go
Introduced four new public types (DomainStats, CategoryStats, ESPStats, DateStats) with nested Stats objects and custom MarshalJSON() methods to flatten JSON output; defined corresponding column configurations for each type; updated mock API responses and test assertions to validate grouped stat structures.
Test Plan and Documentation
docs/TEST_PLAN.md
Updated integration test expectations for contact-fields and tokens commands; documented two fixed issues related to --merge-tag flag support and token request payload structure.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 A CLI grows with grace and care,
Merge tags dance in contact air,
Stats grouped by domain, date, and more,
Token payloads streamlined to the core!
Permissions flow, validation tight—
Each command now shines just right!

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title accurately reflects the main change: fixing stats grouped commands' response types and query parameters, which represents the primary focus across multiple files in the changeset.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
internal/commands/stats/get.go (1)

221-223: ⚠️ Potential issue | 🟡 Minor

Update streams[] parameter to sending_streams[] for consistency with grouped stats endpoints.

All grouped stats commands (by-domain, by-category, by-esp, by-date) consistently use sending_streams[] as the parameter name. The base stats get command still uses the outdated streams[] parameter, creating an inconsistency. This should be corrected to match the grouped stats endpoints.

Proposed fix
 			for _, s := range opts.Streams {
-				params.Add("streams[]", s)
+				params.Add("sending_streams[]", s)
 			}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/commands/stats/get.go` around lines 221 - 223, The loop adding
stream params uses the wrong parameter name; in internal/commands/stats/get.go
locate the loop that iterates over opts.Streams and change the params.Add call
from "streams[]" to "sending_streams[]" so the base stats get command matches
grouped endpoints (update the params.Add("streams[]", s) invocation referenced
in that loop to params.Add("sending_streams[]", s)).
🧹 Nitpick comments (3)
skills/mailtrap-cli/references/contacts.md (1)

193-193: Consider listing allowed --data-type values in update docs too.

Line 193 currently says “New data type” only; mirroring the enum from create improves consistency and reduces guesswork.

Suggested doc refinement
-| `--data-type` | string | No | New data type |
+| `--data-type` | string | No | New data type: `text`, `integer`, `float`, `boolean`, `date` |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@skills/mailtrap-cli/references/contacts.md` at line 193, The docs for the
update endpoint currently list `--data-type` as "New data type" only; update the
contacts update docs to enumerate the allowed `--data-type` values (the same
enum used in the create docs) so users see valid options. Find the `--data-type`
entry in the update reference and replace the vague "New data type" with the
explicit list of allowed values (matching the create/contacts create enum),
keeping the same formatting as the create docs for consistency.
internal/commands/contact_fields/create.go (1)

62-62: Align --merge-tag help text with update command for consistency.

Line 62 can include the same constraint wording used elsewhere (e.g., max length) to keep CLI UX consistent.

Suggested docs/help-text tweak
-cmd.Flags().StringVar(&mergeTag, "merge-tag", "", "Merge tag for the field (required)")
+cmd.Flags().StringVar(&mergeTag, "merge-tag", "", "Merge tag for the field (max 80 chars) (required)")
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/commands/contact_fields/create.go` at line 62, Update the help
string for the --merge-tag flag in create command to match the update command's
wording (include the same constraint wording such as max length); edit the call
that registers the flag (StringVar(&mergeTag, "merge-tag", "", "...")) so the
third argument description mirrors the update command's help text exactly,
referencing the same constraints used there to keep CLI UX consistent.
internal/commands/tokens/tokens_test.go (1)

179-188: Strengthen payload contract assertions for resources entries.

You already verify array presence/size; adding field-level checks (resource_type, resource_id, access_level) would better protect against silent shape regressions.

Suggested assertion expansion
 		if len(resources) != 1 {
 			t.Errorf("expected 1 resource, got %d", len(resources))
 		}
+		resource, ok := resources[0].(map[string]interface{})
+		if !ok {
+			t.Fatal("expected first resource to be an object")
+		}
+		if resource["resource_type"] != "account" {
+			t.Errorf("expected resource_type 'account', got %v", resource["resource_type"])
+		}
+		if resource["resource_id"] != float64(123) {
+			t.Errorf("expected resource_id 123, got %v", resource["resource_id"])
+		}
+		if resource["access_level"] != float64(100) {
+			t.Errorf("expected access_level 100, got %v", resource["access_level"])
+		}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/commands/tokens/tokens_test.go` around lines 179 - 188, Extend the
test's assertions after converting payload["resources"] to resources to validate
each resource object's shape: cast resources[0] to map[string]interface{} (or
iterate over resources), assert the presence and types of the keys
"resource_type", "resource_id", and "access_level" (e.g., non-empty strings or
expected enum values), and fail the test if any key is missing or has an
unexpected type/value; update the test around the payload/resources checks in
tokens_test.go to perform these field-level assertions so regressions in
resource shape are caught.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Outside diff comments:
In `@internal/commands/stats/get.go`:
- Around line 221-223: The loop adding stream params uses the wrong parameter
name; in internal/commands/stats/get.go locate the loop that iterates over
opts.Streams and change the params.Add call from "streams[]" to
"sending_streams[]" so the base stats get command matches grouped endpoints
(update the params.Add("streams[]", s) invocation referenced in that loop to
params.Add("sending_streams[]", s)).

---

Nitpick comments:
In `@internal/commands/contact_fields/create.go`:
- Line 62: Update the help string for the --merge-tag flag in create command to
match the update command's wording (include the same constraint wording such as
max length); edit the call that registers the flag (StringVar(&mergeTag,
"merge-tag", "", "...")) so the third argument description mirrors the update
command's help text exactly, referencing the same constraints used there to keep
CLI UX consistent.

In `@internal/commands/tokens/tokens_test.go`:
- Around line 179-188: Extend the test's assertions after converting
payload["resources"] to resources to validate each resource object's shape: cast
resources[0] to map[string]interface{} (or iterate over resources), assert the
presence and types of the keys "resource_type", "resource_id", and
"access_level" (e.g., non-empty strings or expected enum values), and fail the
test if any key is missing or has an unexpected type/value; update the test
around the payload/resources checks in tokens_test.go to perform these
field-level assertions so regressions in resource shape are caught.

In `@skills/mailtrap-cli/references/contacts.md`:
- Line 193: The docs for the update endpoint currently list `--data-type` as
"New data type" only; update the contacts update docs to enumerate the allowed
`--data-type` values (the same enum used in the create docs) so users see valid
options. Find the `--data-type` entry in the update reference and replace the
vague "New data type" with the explicit list of allowed values (matching the
create/contacts create enum), keeping the same formatting as the create docs for
consistency.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 47ba3dec-9361-4751-97db-9d416b556eee

📥 Commits

Reviewing files that changed from the base of the PR and between 2b52f7e and 71845f2.

📒 Files selected for processing (14)
  • README.md
  • docs/TEST_PLAN.md
  • internal/commands/contact_fields/contact_fields_test.go
  • internal/commands/contact_fields/create.go
  • internal/commands/stats/by_category.go
  • internal/commands/stats/by_date.go
  • internal/commands/stats/by_domain.go
  • internal/commands/stats/by_esp.go
  • internal/commands/stats/get.go
  • internal/commands/stats/stats_test.go
  • internal/commands/tokens/create.go
  • internal/commands/tokens/tokens_test.go
  • skills/mailtrap-cli/references/accounts.md
  • skills/mailtrap-cli/references/contacts.md

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants