Skip to content

Complete mail rule reorder IDs - #2167

Open
yangr-happy wants to merge 3 commits into
larksuite:mainfrom
yangr-happy:feat/de08ac7
Open

Complete mail rule reorder IDs#2167
yangr-happy wants to merge 3 commits into
larksuite:mainfrom
yangr-happy:feat/de08ac7

Conversation

@yangr-happy

@yangr-happy yangr-happy commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator

Fetch the current mail rule order before submitting reorder requests.

  • Complete partial reorder input with the remaining rule IDs in their current order.
  • Reject duplicate or unknown rule IDs before sending the write request.
  • Avoid calling reorder when listing rules fails or returns no rules.
  • Add focused tests for completion, validation, and call ordering.

Summary by CodeRabbit

  • New Features

    • Added mail rule reordering with validation for empty, duplicate, invalid, and unknown rule IDs.
    • Supports partial reorder requests while keeping unspecified existing rules afterward.
    • Preserves the requested order when all rule IDs are supplied.
  • Bug Fixes

    • Prevents invalid reorder requests from being submitted.
    • Handles unavailable or empty mail rule lists without attempting a reorder.

Fetch the current mail rule order before submitting reorder requests so partial input can be completed locally and invalid IDs fail before the write call.

Co-authored-by: TRAE CLI <noreply@bytedance.com>
@coderabbitai

coderabbitai Bot commented Aug 3, 2026

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 1eb34ba0-a19e-457c-8626-5e6327c47361

📥 Commits

Reviewing files that changed from the base of the PR and between f27eabc and d6bf387.

📒 Files selected for processing (2)
  • cmd/service/mail_rules_reorder.go
  • cmd/service/service_test.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • cmd/service/mail_rules_reorder.go
  • cmd/service/service_test.go

📝 Walkthrough

Walkthrough

The service now completes mail rule reorder requests before execution. It validates rule IDs, fetches current rules for partial orders, preserves requested order, and propagates validation or list API errors.

Changes

Mail rules reorder

Layer / File(s) Summary
Reorder request contract
cmd/service/mail_rules_reorder.go
Matches mail rules reorder POST requests. Validates non-empty string IDs and rejects duplicates.
Rule list completion
cmd/service/mail_rules_reorder.go
Fetches current rule IDs, validates list responses, rejects unknown IDs, and appends unspecified rules after the requested IDs.
Service wiring and validation
cmd/service/service.go, cmd/service/service_test.go
Runs request completion before response handling. Tests cover complete and partial orders, pagination, invalid IDs, list failures, and empty lists.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Service
  participant MailRulesReorder
  participant MailRulesAPI
  Service->>MailRulesReorder: Match and validate reorder request
  MailRulesReorder->>MailRulesAPI: GET current mail rules
  MailRulesAPI-->>MailRulesReorder: Return rule IDs
  MailRulesReorder->>MailRulesReorder: Complete rule_ids order
  MailRulesReorder-->>Service: Return updated request
Loading

Possibly related PRs

  • larksuite/cli#2166: Both changes update mail-rule reorder handling, validation, and service tests.
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly describes the main change: completing mail rule reorder IDs before submission.
Description check ✅ Passed The description clearly covers the purpose, key changes, and focused tests, although it does not use the repository template headings.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ 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.

@github-actions github-actions Bot added the size/L Large or sensitive change across domains or core paths label Aug 3, 2026
@github-actions

github-actions Bot commented Aug 3, 2026

Copy link
Copy Markdown

🚀 PR Preview Install Guide

🧰 CLI update

npm i -g https://pkg.pr.new/larksuite/cli/@larksuite/cli@d6bf3875f6a6590787da31dcdcec9c8126272bb9

🧩 Skill update

npx skills add yangr-happy/cli#feat/de08ac7 -y -g

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 2

Caution

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

⚠️ Outside diff range comments (1)
cmd/service/service.go (1)

404-425: 🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift

--dry-run bypasses reorder completion and validation.

completeMailRulesReorder runs at Line 422, after the --dry-run early return at Lines 404-409. For a mail rules reorder command, --dry-run therefore prints the raw, unfinished rule_ids instead of the request that would actually be submitted, and skips duplicate/unknown-ID validation entirely.

Move the API client creation and completeMailRulesReorder call before the DryRun check so the preview reflects the completed and validated request.

🐛 Proposed fix to run completion before the DryRun preview
 	request, fileMeta, err := buildServiceRequest(opts)
 	if err != nil {
 		return err
 	}
 
-	if opts.DryRun {
-		if fileMeta != nil {
-			return cmdutil.PrintDryRunWithFile(f.IOStreams.Out, request, config, opts.Format, fileMeta.FieldName, fileMeta.FilePath, fileMeta.FormFields)
-		}
-		return serviceDryRun(f, request, config, opts.Format)
-	}
-
-	if opts.Method.Risk == cmdutil.RiskHighRiskWrite {
-		if yes, _ := opts.Cmd.Flags().GetBool("yes"); !yes {
-			return cmdutil.RequireConfirmation(opts.SchemaPath)
-		}
-	}
-
 	ac, err := f.NewAPIClientWithConfig(config)
 	if err != nil {
 		return err
 	}
 
 	if err := completeMailRulesReorder(opts.Ctx, ac, &request, opts.SchemaPath, opts.As); err != nil {
 		return err
 	}
 
+	if opts.DryRun {
+		if fileMeta != nil {
+			return cmdutil.PrintDryRunWithFile(f.IOStreams.Out, request, config, opts.Format, fileMeta.FieldName, fileMeta.FilePath, fileMeta.FormFields)
+		}
+		return serviceDryRun(f, request, config, opts.Format)
+	}
+
+	if opts.Method.Risk == cmdutil.RiskHighRiskWrite {
+		if yes, _ := opts.Cmd.Flags().GetBool("yes"); !yes {
+			return cmdutil.RequireConfirmation(opts.SchemaPath)
+		}
+	}
+
 	out := f.IOStreams.Out
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@cmd/service/service.go` around lines 404 - 425, Move the API client creation
and completeMailRulesReorder call in the command flow before the opts.DryRun
early return, while preserving the existing high-risk confirmation and preview
behavior. Ensure dry-run mail rules reorder requests use the completed,
validated request so duplicate and unknown rule IDs are rejected and the preview
reflects the submitted request.
🧹 Nitpick comments (1)
cmd/service/service_test.go (1)

583-625: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add tests for the remaining rule_ids validation branches.

Tests cover duplicate and unknown rule IDs, but not two other new validation branches in mail_rules_reorder.go:

  • --data payload that is not a JSON object (Lines 24-27 of mail_rules_reorder.go).
  • rule_ids that is not an array, or contains a non-string/empty element (Lines 138-146 of mail_rules_reorder.go).

Add test cases for these branches to lock in the typed-error contract for each.

As per coding guidelines, "Every behavior change must have an accompanying test, and contract tests must assert the changed field or behavior directly so reverting the implementation causes failure."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@cmd/service/service_test.go` around lines 583 - 625, Extend the service
reorder tests around TestServiceMethod_MailRulesReorderRejectsDuplicateIDs to
cover a non-object --data payload and invalid rule_ids values: a non-array, a
non-string element, and an empty string element. Execute each through
mailRulesReorderMethod and assert the typed validation error contract directly
with requireProblem, preserving the existing duplicate and unknown-ID coverage.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@cmd/service/mail_rules_reorder.go`:
- Around line 126-147: Update stringSliceField so the []string branch validates
every element as a non-empty string, matching the existing []any validation and
returning the same indexed validation error for empty values; preserve copying
valid slices and the existing handling for missing or invalid fields.
- Around line 82-124: Update listMailRuleIDs to retrieve every mail rule through
the list endpoint’s pagination mechanism, carrying page_size/page_token until no
next-page token remains before building the ID list. Preserve response
validation for each page and ensure IDs retain server-provided order; if
pagination metadata or ordering semantics are unavailable, return a clear
invalid-response error rather than submitting a partial reorder.

---

Outside diff comments:
In `@cmd/service/service.go`:
- Around line 404-425: Move the API client creation and completeMailRulesReorder
call in the command flow before the opts.DryRun early return, while preserving
the existing high-risk confirmation and preview behavior. Ensure dry-run mail
rules reorder requests use the completed, validated request so duplicate and
unknown rule IDs are rejected and the preview reflects the submitted request.

---

Nitpick comments:
In `@cmd/service/service_test.go`:
- Around line 583-625: Extend the service reorder tests around
TestServiceMethod_MailRulesReorderRejectsDuplicateIDs to cover a non-object
--data payload and invalid rule_ids values: a non-array, a non-string element,
and an empty string element. Execute each through mailRulesReorderMethod and
assert the typed validation error contract directly with requireProblem,
preserving the existing duplicate and unknown-ID coverage.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: dcec4fcc-f280-4d81-850f-928c9782c608

📥 Commits

Reviewing files that changed from the base of the PR and between f4cf768 and 1fac2d7.

📒 Files selected for processing (3)
  • cmd/service/mail_rules_reorder.go
  • cmd/service/service.go
  • cmd/service/service_test.go

Comment thread cmd/service/mail_rules_reorder.go
Comment thread cmd/service/mail_rules_reorder.go
Fetch every mail rule page before completing partial reorder inputs, and validate empty rule IDs consistently.

Change-Type: ci-fix

Co-authored-by: TRAE CLI <noreply@bytedance.com>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

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 (3)
cmd/service/mail_rules_reorder.go (1)

101-112: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

Read has_more from the object that contains items.

Line 110 reads only top-level has_more. The normal response shape in cmd/service/service_test.go Lines 559-566 stores it in data.has_more. This guard can therefore accept an incomplete nested list response and submit a reorder that omits rules.

Proposed fix
-	items, ok := data["items"].([]any)
+	items, ok := data["items"].([]any)
+	pagination := data
 	if !ok {
 		if nested, hasData := data["data"].(map[string]any); hasData {
 			items, ok = nested["items"].([]any)
+			pagination = nested
 		}
 	}
@@
-	if hasMore, _ := data["has_more"].(bool); hasMore {
+	if hasMore, _ := pagination["has_more"].(bool); hasMore {
 		return nil, errs.NewInternalError(errs.SubtypeInvalidResponse, "mail rules list pagination did not return all pages")
 	}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@cmd/service/mail_rules_reorder.go` around lines 101 - 112, Update the mail
rules response parsing around the items extraction to track whether items came
from the top-level data object or the nested data object, then read has_more
from that same containing object. Keep rejecting responses where has_more is
true, including nested responses, before returning the parsed items.
cmd/service/service_test.go (2)

699-731: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Assert that the reorder request was not sent.

These tests only assert that cmd.Execute returns an error. A faulty implementation can attempt the POST and still pass because the mock has no matching reorder stub. Register a reorder stub that records matches, then assert that it was not called after both list failure and an empty list.

As per coding guidelines, contract tests must assert the changed behavior directly.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@cmd/service/service_test.go` around lines 699 - 731, Update both MailRules
reorder tests, TestServiceMethod_MailRulesReorderListFailureSkipsReorder and
TestServiceMethod_MailRulesReorderEmptyListSkipsReorder, to register a reorder
POST stub that records whether it matches. After cmd.Execute, retain the
existing error assertions and additionally assert that the reorder stub was not
called in either failure path.

Source: Coding guidelines


639-697: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Test the []string validation path and assert Param.

cmd.Execute decodes JSON arrays as []any. These tests do not exercise the new []string branch in stringSliceField. Add a direct test with []string{""}. Also assert ValidationError.Param == "rule_ids" through errors.As.

As per coding guidelines, error-path tests must assert typed metadata. Based on learnings, use errors.As for Param because errs.ProblemOf does not expose it.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@cmd/service/service_test.go` around lines 639 - 697, Extend the mail-rules
validation tests to directly exercise the []string branch in stringSliceField by
adding a case that passes []string{""} and assert the resulting ValidationError
via errors.As, including Param == "rule_ids". Update the existing error-path
assertions as needed to verify this typed metadata while preserving the current
problem category, subtype, and message checks.

Sources: Coding guidelines, Learnings

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@cmd/service/mail_rules_reorder.go`:
- Around line 101-112: Update the mail rules response parsing around the items
extraction to track whether items came from the top-level data object or the
nested data object, then read has_more from that same containing object. Keep
rejecting responses where has_more is true, including nested responses, before
returning the parsed items.

In `@cmd/service/service_test.go`:
- Around line 699-731: Update both MailRules reorder tests,
TestServiceMethod_MailRulesReorderListFailureSkipsReorder and
TestServiceMethod_MailRulesReorderEmptyListSkipsReorder, to register a reorder
POST stub that records whether it matches. After cmd.Execute, retain the
existing error assertions and additionally assert that the reorder stub was not
called in either failure path.
- Around line 639-697: Extend the mail-rules validation tests to directly
exercise the []string branch in stringSliceField by adding a case that passes
[]string{""} and assert the resulting ValidationError via errors.As, including
Param == "rule_ids". Update the existing error-path assertions as needed to
verify this typed metadata while preserving the current problem category,
subtype, and message checks.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: d4a919a1-b6b4-45ac-b402-d73c281291dc

📥 Commits

Reviewing files that changed from the base of the PR and between 1fac2d7 and f27eabc.

📒 Files selected for processing (2)
  • cmd/service/mail_rules_reorder.go
  • cmd/service/service_test.go

Use the rule list response id field when completing reorder requests so partial input can be expanded before calling the reorder endpoint.

Co-authored-by: TRAE CLI <noreply@bytedance.com>
@yangr-happy

Copy link
Copy Markdown
Collaborator Author

🤖 AI Review | CR 汇总 | 有风险(0 个新增评论,2 个已由既有评论覆盖)

增量审查:已读取既有评论并按同位置同问题去重。本轮确认 cmd/service/service.go 的 dry-run 绕过补齐/校验、cmd/service/mail_rules_reorder.go 单页 nested has_more 未检查这两个问题仍有风险,但均已由既有 CodeRabbit 评论覆盖,未重复发表行级评论。

验证:go test ./cmd/service 通过。

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

Labels

size/L Large or sensitive change across domains or core paths

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant