Skip to content

refactor: validation error for plan add-on assignment - #2842

Merged
chrisgacsal merged 3 commits into
mainfrom
refactor/productcatalog
May 19, 2025
Merged

chrisgacsal merged 3 commits into
mainfrom
refactor/productcatalog

Conversation

@chrisgacsal

@chrisgacsal chrisgacsal commented May 19, 2025 •

Copy link
Copy Markdown
Collaborator

Overview

Adopt ValidationIssue for describing validation errors for plan add-on assignments.

Summary by CodeRabbit

  • New Features

    • Validation errors now provide explicit machine-readable error codes, human-readable messages, and optional attributes, with field paths indicating the error location.
  • Bug Fixes

    • Improved consistency and clarity in validation error reporting across the product catalog.
  • Refactor

    • Simplified and unified validation error structures and handling, removing nested resource context and custom error types.
    • Streamlined error mapping and reporting in plan add-on and rate card validation.
  • Tests

    • Added comprehensive tests for plan add-on validation errors.
    • Updated and removed outdated tests to align with the new validation error format.

@chrisgacsal chrisgacsal self-assigned this May 19, 2025
@chrisgacsal
chrisgacsal requested a review from a team as a code owner May 19, 2025 09:33
@chrisgacsal chrisgacsal added the release-note/ignore Ignore this change when generating release notes label May 19, 2025
@coderabbitai

coderabbitai Bot commented May 19, 2025 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This change refactors validation error handling across the codebase by removing the ValidationResource type and restructuring the ValidationError model. The new model introduces code, message, and optional attributes fields, and clarifies the field property as a path. Related error creation, mapping, and validation logic are updated accordingly, and obsolete tests and resource utilities are removed.

Changes

Files/Paths Change Summary
api/client/go/client.gen.go, api/client/javascript/src/client/schemas.ts, api/openapi.cloud.yaml, api/openapi.yaml, api/spec/src/productcatalog/errors.tsp Refactored ValidationError schema: removed ValidationResource, replaced detail and resource with code, message, and attributes; updated field to be a path.
openmeter/productcatalog/errors.go Removed InvalidResourceError and related utilities; added declarative error variables using models.ValidationIssue for plan addon and rate card validation.
openmeter/productcatalog/errors_test.go, openmeter/productcatalog/resource.go, openmeter/productcatalog/resource_test.go Deleted test and implementation files for InvalidResourceError and Resource types.
openmeter/productcatalog/planaddon.go Refactored validation methods to use new error model and structured field paths; updated method signatures.
openmeter/productcatalog/planaddon/httpdriver/mapping.go Updated error mapping functions to use new error types and fields; removed references to old error/resource types.
openmeter/productcatalog/planaddon_test.go Added comprehensive tests for new ValidationErrors logic on PlanAddon.
openmeter/productcatalog/ratecard.go Refactored internal validation logic to use new error construction and field path conventions.
openmeter/productcatalog/ratecard_test.go Updated test data to include Key in RateCardMeta for all scenarios.
openmeter/subscription/addon/extend_test.go Updated error message assertions to match new singular phrasing in validation errors.

Possibly related PRs

  • openmeterio/openmeter#2838: Introduces foundational types and utilities for structured validation errors, directly supporting the refactoring of validation error handling in this PR.
  • openmeterio/openmeter#2820: Adds the now-removed ValidationResource and original ValidationError structure; this PR directly modifies and reverses those changes.

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 golangci-lint (1.64.8)

Error: you are using a configuration file for golangci-lint v2 with golangci-lint v1: please use golangci-lint v2
Failed executing command with error: you are using a configuration file for golangci-lint v2 with golangci-lint v1: please use golangci-lint v2


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a13ebc3 and b31a1d2.

📒 Files selected for processing (15)
  • api/client/go/client.gen.go (2 hunks)
  • api/client/javascript/src/client/schemas.ts (1 hunks)
  • api/openapi.cloud.yaml (1 hunks)
  • api/openapi.yaml (1 hunks)
  • api/spec/src/productcatalog/errors.tsp (1 hunks)
  • openmeter/productcatalog/errors.go (1 hunks)
  • openmeter/productcatalog/errors_test.go (0 hunks)
  • openmeter/productcatalog/planaddon.go (4 hunks)
  • openmeter/productcatalog/planaddon/httpdriver/mapping.go (2 hunks)
  • openmeter/productcatalog/planaddon_test.go (1 hunks)
  • openmeter/productcatalog/ratecard.go (9 hunks)
  • openmeter/productcatalog/ratecard_test.go (14 hunks)
  • openmeter/productcatalog/resource.go (0 hunks)
  • openmeter/productcatalog/resource_test.go (0 hunks)
  • openmeter/subscription/addon/extend_test.go (4 hunks)
💤 Files with no reviewable changes (3)
  • openmeter/productcatalog/resource.go
  • openmeter/productcatalog/resource_test.go
  • openmeter/productcatalog/errors_test.go
🚧 Files skipped from review as they are similar to previous changes (10)
  • openmeter/subscription/addon/extend_test.go
  • openmeter/productcatalog/ratecard_test.go
  • api/openapi.yaml
  • api/openapi.cloud.yaml
  • openmeter/productcatalog/planaddon/httpdriver/mapping.go
  • openmeter/productcatalog/planaddon.go
  • api/spec/src/productcatalog/errors.tsp
  • openmeter/productcatalog/ratecard.go
  • api/client/javascript/src/client/schemas.ts
  • api/client/go/client.gen.go
🧰 Additional context used
🧬 Code Graph Analysis (1)
openmeter/productcatalog/errors.go (1)
pkg/models/validationissue.go (3)
  • NewValidationIssue (92-103)
  • WithPath (71-75)
  • WithCriticalSeverity (83-85)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: E2E
  • GitHub Check: CI
  • GitHub Check: Analyze (go)
🔇 Additional comments (2)
openmeter/productcatalog/errors.go (1)

1-120: Well-structured approach to validation error standardization

The refactoring from custom error types to using models.ValidationIssue is an excellent improvement that standardizes error handling. The new approach provides:

  1. Machine-readable error codes for programmatic handling
  2. Human-readable messages for users
  3. Specific field paths that pinpoint exactly where issues occur
  4. Severity levels that indicate the importance of each issue

This approach aligns with modern API design practices and will likely improve error handling throughout the application.

I noticed that some RateCard errors (lines 103-119) don't include the WithCriticalSeverity() option while most others do. This appears to be intentional based on error severity, which is a good practice for distinguishing between different types of validation issues.

openmeter/productcatalog/planaddon_test.go (1)

17-581: Comprehensive test coverage for validation scenarios

The test implementation is thorough and well-structured, covering multiple validation scenarios:

  1. The "valid" case verifies the happy path with properly configured plan add-ons
  2. The "invalid" case tests basic validation rules like currency matching and phase key existence
  3. The "incompatible" case tests deeper compatibility issues between plan and add-on components

The test assertions are precise, checking not only for the presence of validation issues but also validating their exact codes, messages, paths, and severities. This approach ensures that the validation error format is consistently applied throughout the codebase.

The detailed test fixtures also serve as valuable documentation for how plan add-ons should be properly configured.

✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@chrisgacsal
chrisgacsal force-pushed the refactor/productcatalog branch from 2e308dd to a13ebc3 Compare May 19, 2025 09:38
@chrisgacsal
chrisgacsal force-pushed the refactor/productcatalog branch from a13ebc3 to b31a1d2 Compare May 19, 2025 09:44

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Caution

Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments. If you are seeing this consistently it is likely a permissions issue. Please check "Moderation" -> "Code review limits" under your organization settings.

Actionable comments posted: 5

🧹 Nitpick comments (16)
api/client/go/client.gen.go (4)

6399-6401: Consider using map[string]any directly or exposing a read-only accessor to avoid accidental mutation

Attributes is a pointer to Annotations, which is map[string]interface{}.
Because maps are reference types, callers can still mutate the contents even when the pointer itself is non-nil.
If the intention is to expose arbitrary, read-only annotations, think about:

  1. Returning a copy in a getter (GetAttributes() map[string]any) and omitting the field from the public struct, or
  2. Documenting that the caller must treat the map as immutable.

Both patterns guard against data races when the same instance is shared across goroutines – a common scenario for generated client models transported through channels.


6402-6404: Expose error-code enumerations for stronger compile-time guarantees

Code string \json:"code"`` leaves the caller with a free-form string.
To prevent typos and improve autocompletion it helps to provide a generated const block, e.g.:

const (
    ValidationCodeUnknown              = "unknown"
    ValidationCodeIncompatibleAddOn    = "incompatible_addon"
    // …
)

That way SDK consumers can reference the symbolic name instead of hard-coding literals.


6408-6409: Internationalisation (i18n) hint – separate message localisation from the transport model

Embedding the final human-readable Message in the wire format hard-codes one language (English) into the API.
If multi-language support is on the roadmap, consider transporting a language-agnostic key plus arguments and letting clients/locales render the final string.

For now, at least document the language guarantees (e.g., always English).


39348-39355: Huge base64-encoded swagger blob hurts diff readability & binary size

The embedded swagger string has grown again (>3 MB diff). Re-generating the client always touches this constant, which:

  • Bloats the git history/diffs.
  • Slows go vet/go test due to large string literal compilation.
  • Makes IDE navigation cumbersome.

The Go tool-chain now supports //go:embed (Go 1.16+).
Storing the spec as a compressed JSON/YAML file and embedding it like:

//go:embed swagger.json.gz
var swaggerSpec []byte

would keep diffs tight and compilation fast.

api/openapi.cloud.yaml (1)

21689-21703: Enhance error detail schema and optional annotations

  • The code and message properties correctly split machine-readable vs. human-readable information.
  • Consider tightening code with a pattern or enumerated list of known error codes to prevent typos and improve client validation.
  • For attributes, adding an example or marking it explicitly as nullable: true could help clarify that it’s optional and may be omitted when no extra metadata is present.
api/openapi.yaml (2)

22334-22338: Refine machine-readable error description
Consider hyphenating “machine-readable” and tightening the description for consistency. For example:

-def description: The machine readable description of the error.
+description: The machine-readable identifier for this error.

22339-22343: Refine human-readable error message
Similarly, hyphenate “human-readable” and adjust the wording to emphasize clarity. For example:

-def description: The human readable description of the error.
+description: A human-readable explanation of the validation failure.
openmeter/productcatalog/planaddon.go (1)

146-148: Consider propagating structured validation issues instead of plain fmt.Errorf

Wrapping rate-card validation failures with fmt.Errorf(... %w) preserves the error chain, but the added text adds an extra, non-machine-readable layer around the underlying models.ValidationIssues.
Down-stream tooling that maps issues to JSON may end up with duplicated or harder-to-parse messages.

A lighter alternative is to delegate prefixing directly and avoid the textual decoration, e.g.:

if err := NewRateCardWithOverlay(phaseRateCard, addonRateCard).Validate(); err != nil {
    errs = append(errs,
        models.ErrorWithFieldPrefix(
            models.FieldPathFromParts(planPrefix, "phases", phase.Key, "ratecards", phaseRateCard.Key()),
            err,
        ),
    )
}

This keeps the structured issue intact while still attaching the correct field path.

api/spec/src/productcatalog/errors.tsp (1)

14-19: Property name may confuse consumers (path vs. field)

The comment says “The path to the field”, but the property is still called field.
Renaming the property to path (or fieldPath) would make its semantics explicit and eliminate ambiguity with single-field names.

If the rename is not feasible, consider updating the description to “The affected field (path notation)”.

api/client/javascript/src/client/schemas.ts (1)

9899-9919: Consider documenting the error code patterns.

The overall ValidationError schema looks solid. One suggestion would be to document any patterns or constraints for error codes to ensure consistency across the API.

Consider adding TypeScript documentation that describes error code patterns:

    /**
     * @description The machine readable description of the error.
     * @example invalid_feature_key
+    * @pattern ^[a-z]+(_[a-z]+)*$
     */
    readonly code: string
openmeter/productcatalog/planaddon_test.go (2)

352-384: Leverage the predefined error constants to build expectedIssues

The literals duplicate messages / codes that already live in productcatalog/errors.go. If the source messages change, the test will silently diverge.
Prefer constructing expectations with the shared constants and models.ErrorWithPathPrefix (or an equivalent helper) e.g.:

expectedIssues := models.ValidationIssues{
    models.ErrorWithPathPrefix("/plans/pro/versions/2", ErrPlanAddonIncompatibleStatus),
    models.ErrorWithPathPrefix("/addons/storage/versions/1", ErrPlanAddonIncompatibleStatus),
    // …
}

This keeps tests DRY and future-proof.

Also applies to: 540-570


1-581: High duplication inflates maintenance cost

The three scenarios embed ~550 lines of almost-identical JSON-like structs differing only in a handful of fields. Subsequent spec tweaks will require triple edits and invite divergence bugs.

Consider extracting minimal helpers/builders:

func makePlan(version int, currency currency.Code, effectiveFrom *time.Time, price any /* … */) Plan { … }
func makeAddon(instanceType AddonInstanceType, cur currency.Code, …) Addon { … }

Then each case only specifies the deltas. This shrinks the test, highlights what differs, and accelerates future edits.

openmeter/productcatalog/errors.go (4)

15-20: Minor grammar polish for clarity

"maximum quantity must be set to positive number …" → missing article.

- "maximum quantity must be set to positive number for add-on with multiple instance type",
+ "maximum quantity must be set to a positive number for add-on with multiple instance type",

22-27: Message phrasing

"maximum quantity must not be set for add-on with single instance type" → consider inserting the article:

- "maximum quantity must not be set for add-on with single instance type",
+ "maximum quantity must not be set for an add-on with single instance type",

75-80: Typo in error message

"feature identifiers id must match" – the double noun reads oddly.

- "feature identifiers id must match",
+ "feature identifier id must match",

1-120: Consider grouping error vars by functional domain

The flat list is getting long; grouping into nested structs or prefixing with domain comments (e.g. // PlanAddon, // RateCard/Price, // RateCard/Entitlement) will aid discoverability and reduce merge conflicts when multiple contributors append new issues simultaneously.

🛑 Comments failed to post (5)
api/client/go/client.gen.go (1)

6405-6406: 🛠️ Refactor suggestion

Make Field optional to reflect root-level errors

Some validation errors apply to the whole resource rather than a specific field.
Using a non-pointer string forces the empty string ("") in such cases, which is ambiguous in JSON and loses the “unset vs. set-to-empty” distinction.

- Field string `json:"field"`
+ Field *string `json:"field,omitempty"`

Downstream, helpers such as GetField() can safely dereference while preserving backward compatibility.

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In api/client/go/client.gen.go around lines 6405 to 6406, the Field property
should be changed from a non-pointer string to a pointer to string to make it
optional. This change allows distinguishing between an unset Field (nil) and an
empty string, which is important for representing root-level errors accurately.
Update the Field declaration to use *string instead of string, ensuring that
downstream code can safely handle the pointer while maintaining backward
compatibility.
openmeter/productcatalog/planaddon.go (2)

121-124: 🛠️ Refactor suggestion

Incorrect field-path root for unknown plan-phase error

ErrPlanAddonUnknownPlanPhaseKey relates to a plan attribute (FromPlanPhase), yet the error is associated with addonPrefix:

models.FieldPathFromParts(addonPrefix)

Using the add-on prefix misleads API clients and UI tooling that rely on the field path to highlight the problematic plan configuration.

-errs = append(errs, models.ErrorWithFieldPrefix(models.FieldPathFromParts(addonPrefix),
+errs = append(errs, models.ErrorWithFieldPrefix(models.FieldPathFromParts(planPrefix),
     ErrPlanAddonUnknownPlanPhaseKey,
 ))

Switching to planPrefix (or a more specific plans/.../fromPlanPhase) keeps the path consistent with the actual data location.

🤖 Prompt for AI Agents
In openmeter/productcatalog/planaddon.go around lines 121 to 124, the error for
ErrPlanAddonUnknownPlanPhaseKey is incorrectly associated with addonPrefix,
which misleads clients about the error location. Change the field path prefix
from addonPrefix to planPrefix or a more specific path pointing to the plan's
FromPlanPhase attribute to correctly reflect the error's data location.

89-97: ⚠️ Potential issue

MaxQuantity for MULTIPLE instance type is not enforced when omitted

The current check only fails when MaxQuantity is present and <= 0.
Given the error constant is named ErrPlanAddonMaxQuantityMustBeSet, the intent seems to be that the field is mandatory for AddonInstanceTypeMultiple.
As written, nil (omitted) values silently pass validation, which contradicts the wording and may hide configuration errors.

case AddonInstanceTypeMultiple:
-    if c.MaxQuantity != nil && *c.MaxQuantity <= 0 {
+    if c.MaxQuantity == nil || *c.MaxQuantity <= 0 {
         errs = append(errs, models.ErrorWithFieldPrefix(addonPrefix,
             ErrPlanAddonMaxQuantityMustBeSet,
         ))
     }

This guarantees the value is provided and strictly positive.
Please verify the desired business rule and adjust tests accordingly.

🤖 Prompt for AI Agents
In openmeter/productcatalog/planaddon.go around lines 89 to 97, the validation
for AddonInstanceTypeMultiple does not enforce that MaxQuantity is set; it only
checks if MaxQuantity is present and <= 0. To fix this, update the validation to
also check if MaxQuantity is nil and append an error if it is, ensuring
MaxQuantity is both provided and strictly positive for the MULTIPLE instance
type. Adjust related tests to cover the case where MaxQuantity is omitted.
openmeter/productcatalog/planaddon_test.go (1)

574-579: 🛠️ Refactor suggestion

Avoid capturing the loop variable directly in sub-test closures

test is reused for every loop iteration. Although t.Run executes the closure synchronously today, relying on this behaviour is brittle and can bite when the test body is later parallelised (t.Parallel()) or refactored.
Create a copy per iteration:

-for _, test := range tests {
-    t.Run(test.name, func(t *testing.T) {
+for _, tc := range tests {
+    tc := tc // capture
+    t.Run(tc.name, func(t *testing.T) {
+        // use tc instead of test

This guarantees each sub-test sees the correct data regardless of execution order.

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In openmeter/productcatalog/planaddon_test.go around lines 574 to 579, the loop
variable 'test' is captured directly in the sub-test closure, which can cause
issues if the test is parallelized or refactored. To fix this, create a new
local variable inside the loop that copies the current 'test' value, and use
this local copy within the t.Run closure to ensure each sub-test has the correct
data independent of execution order.
openmeter/productcatalog/errors.go (1)

96-120: 💡 Verification agent

🧩 Analysis chain

Severity missing on several RateCard issues

ErrRateCardStaticEntitlementTemplateNotAllowed, ErrRateCardMeteredEntitlementTemplateUsagePeriodMismatch, and ErrRateCardPercentageDiscountNotAllowed omit models.WithCriticalSeverity(), whereas all previous RateCard issues are critical.
If these should also block saving a catalog entry, add the severity flag for consistency; if not, add a comment explaining why their severity differs.

- models.NewValidationIssue(
+ models.NewValidationIssue(
    …,
    models.WithCriticalSeverity(),
 )

I’ll verify how ErrRateCard* issues are defined and the default severity in NewValidationIssue.


🏁 Script executed:

#!/bin/bash
# List all RateCard error definitions with context
rg -n "ErrRateCard" -A3 openmeter/productcatalog/errors.go

# Find the signature and default options for NewValidationIssue
rg -n "func NewValidationIssue" -C5 .

Length of output: 3053


I’ll inspect the severity defaults and see which RateCard errors already use critical severity:


🏁 Script executed:

#!/bin/bash
# Show the full NewValidationIssue implementation
rg -n "func NewValidationIssue" -C20 pkg/models/validationissue.go

# Show the ValidationIssue struct
rg -n "type ValidationIssue" -C5 pkg/models/validationissue.go

# List all severity-related constants and options
rg -n "ErrorSeverity" -C5 pkg/models/validationissue.go
rg -n "WithCriticalSeverity" -C5 pkg/models/validationissue.go

# Check which RateCard errors include CriticalSeverity
rg -n "WithCriticalSeverity" -n openmeter/productcatalog/errors.go

Length of output: 5558


Enforce consistent critical severity on RateCard validation issues

All existing ErrRateCard* validations include models.WithCriticalSeverity(), but the following three do not, leaving their severity at the default (no severity set):

  • openmeter/productcatalog/errors.go:
    • Line 103 – ErrRateCardStaticEntitlementTemplateNotAllowed
    • Line 109 – ErrRateCardMeteredEntitlementTemplateUsagePeriodMismatch
    • Line 115 – ErrRateCardPercentageDiscountNotAllowed

If these conditions should block saving a catalog entry like the others, add models.WithCriticalSeverity():

 models.NewValidationIssue(
   "rate_card_static_entitlement_template_not_allowed",
   "static entitlement template is not allowed",
   models.WithPath("entitlementTemplate", "type"),
+  models.WithCriticalSeverity(),
 )

Otherwise, explicitly document the intended severity—either by using models.WithWarningSeverity() or by adding a code comment explaining why they differ from the critical-severity defaults.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

ErrRateCardEntitlementTemplateTypeMismatch = models.NewValidationIssue(
    "rate_card_entitlement_template_type_mismatch",
    "entitlement template type must match",
    models.WithPath("entitlementTemplate", "type"),
    models.WithCriticalSeverity(),
)

ErrRateCardStaticEntitlementTemplateNotAllowed = models.NewValidationIssue(
    "rate_card_static_entitlement_template_not_allowed",
    "static entitlement template is not allowed",
    models.WithPath("entitlementTemplate", "type"),
    models.WithCriticalSeverity(),
)

ErrRateCardMeteredEntitlementTemplateUsagePeriodMismatch = models.NewValidationIssue(
    "rate_card_metered_entitlement_template_usage_period_mismatch",
    "usage period for metered entitlement template must match",
    models.WithPath("entitlementTemplate", "usagePeriod"),
    models.WithCriticalSeverity(),
)

ErrRateCardPercentageDiscountNotAllowed = models.NewValidationIssue(
    "rate_card_percentage_discount_not_allowed",
    "percentage discount is not allowed",
    models.WithPath("discounts", "percentage"),
    models.WithCriticalSeverity(),
)
🤖 Prompt for AI Agents
In openmeter/productcatalog/errors.go around lines 96 to 120, the RateCard
validation errors ErrRateCardStaticEntitlementTemplateNotAllowed,
ErrRateCardMeteredEntitlementTemplateUsagePeriodMismatch, and
ErrRateCardPercentageDiscountNotAllowed lack the models.WithCriticalSeverity()
option present in other RateCard errors. To fix this, add
models.WithCriticalSeverity() to these three error definitions if they should
block saving a catalog entry for consistency. If not critical, add a comment
explaining why their severity differs or set an explicit severity like
models.WithWarningSeverity().

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

Labels

release-note/ignore Ignore this change when generating release notes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants