Skip to content

Postal code#376

Merged
rogelioLpz merged 14 commits intomainfrom
postal-code
Jul 10, 2025
Merged

Postal code#376
rogelioLpz merged 14 commits intomainfrom
postal-code

Conversation

@gmorales96
Copy link
Copy Markdown
Contributor

@gmorales96 gmorales96 commented Jun 25, 2025

Summary by CodeRabbit

  • New Features

    • Introduced a new query parameter for postal code searches.
  • Bug Fixes

    • Simplified address input by replacing multiple fields with a single postal code identifier.
    • Updated legal representative address format to use the new address request model.
  • Chores

    • Updated version to 2.1.8.
    • Adjusted tests to reflect the updated address format.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Jun 25, 2025

Walkthrough

The changes add a new PostalCodeQuery class with a postal_code field validated to be exactly five digits, and this class is included in the module's public exports. The AddressRequest model is modified by removing the fields colonia, postal_code, state, country, and city, replacing them with a single required postal_code_id field. Corresponding test cases are updated to use the new address structure. Imports related to address types are adjusted in the morals module, and the type annotation for the address field in LegalRepresentative is updated accordingly. Additionally, the version number is updated from 2.1.7 to 2.1.8. No other functional or logical changes were made.


📜 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 0cdc080 and 4bebd25.

📒 Files selected for processing (2)
  • cuenca_validations/types/queries.py (2 hunks)
  • cuenca_validations/version.py (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • cuenca_validations/types/queries.py
  • cuenca_validations/version.py
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: Analyze (python)
  • GitHub Check: Analyze (actions)
✨ Finishing Touches
  • 📝 Generate Docstrings

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

@codecov
Copy link
Copy Markdown

codecov Bot commented Jun 25, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 100.00%. Comparing base (fa26d3a) to head (4bebd25).
Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff            @@
##              main      #376   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           16        16           
  Lines         1305      1304    -1     
=========================================
- Hits          1305      1304    -1     
Flag Coverage Δ
unittests 100.00% <100.00%> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
cuenca_validations/types/__init__.py 100.00% <ø> (ø)
cuenca_validations/types/identities.py 100.00% <100.00%> (ø)
cuenca_validations/types/morals.py 100.00% <100.00%> (ø)
cuenca_validations/types/queries.py 100.00% <100.00%> (ø)
cuenca_validations/version.py 100.00% <100.00%> (ø)

Continue to review full report in Codecov by Sentry.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update fa26d3a...4bebd25. Read the comment docs.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Copy link
Copy Markdown
Contributor

@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.

Actionable comments posted: 1

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b9cb39c and c028d2a.

📒 Files selected for processing (5)
  • cuenca_validations/types/__init__.py (2 hunks)
  • cuenca_validations/types/identities.py (2 hunks)
  • cuenca_validations/types/queries.py (1 hunks)
  • cuenca_validations/version.py (1 hunks)
  • tests/test_types.py (1 hunks)
🧰 Additional context used
📓 Path-based instructions (5)
`**/*.py`: Enforce Relative Imports for Internal Modules

Ensure that any import...

**/*.py: Enforce Relative Imports for Internal Modules

Ensure that any imports referencing internal modules use relative paths. However, if modules reside in the main module directories (for example /src or /library_or_app_name) —and relative imports are not feasible—absolute imports are acceptable. Additionally, if a module is located outside the main module structure (for example, in /tests or /scripts at a similar level), absolute imports are also valid.

Examples and Guidelines:

  1. If a module is in the same folder or a subfolder of the current file, use relative imports. For instance: from .some_module import SomeClass
  2. If the module is located under /src or /library_or_app_name and cannot be imported relatively, absolute imports are allowed (e.g., from library_or_app_name.utilities import helper_method).
  3. If a module is outside the main module directories (for example, in /tests, /scripts, or any similarly placed directory), absolute imports are valid.
  4. External (third-party) libraries should be imported absolutely (e.g., import requests).

⚙️ Source: CodeRabbit Configuration File

List of files the instruction was applied to:

  • cuenca_validations/types/queries.py
  • cuenca_validations/version.py
  • cuenca_validations/types/__init__.py
  • tests/test_types.py
  • cuenca_validations/types/identities.py
`**/*.py`: Rule: Enforce Snake Case in Python Backend
  1. New or Modified Code:...

**/*.py:
Rule: Enforce Snake Case in Python Backend

  1. New or Modified Code: Use snake_case for all variables, functions, methods, and class attributes.
  2. Exceptions (Pydantic models for API responses):
    • Primary fields must be snake_case.
    • If older clients expect camelCase, create a computed or alias field that references the snake_case field.
    • Mark any camelCase fields as deprecated or transitional.

Examples

Invalid:

class CardConfiguration(BaseModel):
    title: str
    subTitle: str  # ❌ Modified or new field in camelCase

Valid:

class CardConfiguration(BaseModel):
    title: str
    subtitle: str  # ✅ snake_case for new/modified field

    @computed_field
    def subTitle(self) -> str:  # camelCase allowed only for compatibility
        return self.subtitle

Any direct use of camelCase in new or updated code outside of these exceptions should be flagged.

⚙️ Source: CodeRabbit Configuration File

List of files the instruction was applied to:

  • cuenca_validations/types/queries.py
  • cuenca_validations/version.py
  • cuenca_validations/types/__init__.py
  • tests/test_types.py
  • cuenca_validations/types/identities.py
`**/*.py`: Use try/except for concise error handling when accessing nested dicti...

**/*.py: Use try/except for concise error handling when accessing nested dictionary keys:

try:
    can_ignore_error = data['error']['code'] in ignore_error_codes
except KeyError:
    can_ignore_error = False

❌ Avoid Verbose Chained Conditionals:

can_ignore_error = (
    'code' in data['error']
    and data['error']['code'] in ignore_error_codes
)

Explanation:
The try/except approach:

Reduces code complexity and nesting
Improves readability by focusing on the "happy path" logic
Follows Python's "easier to ask forgiveness than permission" (EAFP) idiom

Severity: Important (Not a Nitpick)
This pattern significantly improves code maintainability and readability, especially as dictionary access patterns become more complex.

⚙️ Source: CodeRabbit Configuration File

List of files the instruction was applied to:

  • cuenca_validations/types/queries.py
  • cuenca_validations/version.py
  • cuenca_validations/types/__init__.py
  • tests/test_types.py
  • cuenca_validations/types/identities.py
`**/*.py`: Context Agave is our internal Python library for processing SQS messa...

**/*.py: Context
Agave is our internal Python library for processing SQS messages. The @task decorator can automatically convert JSON to Pydantic models.

Rule
Always annotate @task parameters with Pydantic models instead of manually converting dictionaries.

Correct Pattern

from pydantic import BaseModel
from agave.tasks.sqs_tasks import task

class User(BaseModel):
    name: str
    age: int
    
@task(queue_url=QUEUE_URL, region_name='us-east-1')
async def task_validator(message: User) -> None:
    # The message is already a User instance - no conversion needed
    print(message.name)  # Direct attribute access

Incorrect Pattern

from pydantic import BaseModel
from agave.tasks.sqs_tasks import task

class User(BaseModel):
    name: str
    age: int
    
@task(queue_url=QUEUE_URL, region_name='us-east-1')
async def task_validator(message_data: dict) -> None:  # or unannotated parameter
    # Unnecessary conversion
    message = User(**message_data)
    print(message.name)

Explanation
The Agave @task decorator automatically:

  • Reads JSON messages from SQS queues
  • Converts them to Pydantic model instances when the handler parameter is annotated
  • Performs validation based on the Pydantic model

⚙️ Source: CodeRabbit Configuration File

List of files the instruction was applied to:

  • cuenca_validations/types/queries.py
  • cuenca_validations/version.py
  • cuenca_validations/types/__init__.py
  • tests/test_types.py
  • cuenca_validations/types/identities.py
`**/*.py`: ## MANDATORY: Use built-in Pydantic validators

Description

Avoid...

**/*.py: ## MANDATORY: Use built-in Pydantic validators

Description

Avoid creating custom validators that duplicate functionality already provided by Pydantic's built-in validators, pydantic_extra_types package, or third-party Pydantic validator libraries. This improves code maintainability and reduces unnecessary unit tests.

Bad Practice

from pydantic import BaseModel, field_validator

class MyValidator(BaseModel):
    location: str
    
    @field_validator('location')
    def validate_location(cls, value: str) -> str:
        values = value.split(',')
        if len(values) != 3:
            raise ValueError('Must provide exactly 3 values for location')
        # Custom validation logic that duplicates functionality
        return value

Good Practice

from pydantic import BaseModel
from pydantic_extra_types.coordinate import Coordinate

class MyValidator(BaseModel):
    location: Coordinate

Unit Test Guidelines

Do not write unit tests specifically for validating the behavior of Pydantic's built-in validators. These are already well-tested by the Pydantic library itself.

Tests to Remove

def test_invalid_location():
    pytest.raises(ValidationError):
        MyValidator(location='foo,bar')

Rule Enforcement

This is a mandatory rule, not a refactoring suggestion. Changes must be implemented when:

  1. A custom validator replicates functionality already available in Pydantic's ecosystem
  2. There is a suitable built-in, pydantic_extra_types, or third-party Pydantic validator available

Actions required:

  1. Replace custom validators with appropriate existing validators
  2. Remove unnecessary unit tests that only validate built-in Pydantic validation behavior
  3. Block PRs that introduce new custom validators when alternatives exist

⚙️ Source: CodeRabbit Configuration File

List of files the instruction was applied to:

  • cuenca_validations/types/queries.py
  • cuenca_validations/version.py
  • cuenca_validations/types/__init__.py
  • tests/test_types.py
  • cuenca_validations/types/identities.py
🧬 Code Graph Analysis (3)
cuenca_validations/types/__init__.py (1)
cuenca_validations/types/queries.py (1)
  • PostalCodeQuery (184-185)
tests/test_types.py (1)
cuenca_validations/types/enums.py (1)
  • State (264-297)
cuenca_validations/types/identities.py (1)
cuenca_validations/types/enums.py (2)
  • Country (303-553)
  • State (264-297)
🪛 Pylint (3.3.7)
cuenca_validations/types/queries.py

[refactor] 184-184: Too few public methods (1/2)

(R0903)

🔇 Additional comments (4)
cuenca_validations/types/queries.py (1)

184-185: LGTM! Simple and well-designed query class.

The PostalCodeQuery implementation correctly follows the established pattern in this module. The Pylint warning about too few public methods is a false positive for Pydantic models, which are primarily data containers.

cuenca_validations/version.py (1)

1-1: Version update appropriate for development iteration.

The version bump to '2.1.8.dev2' correctly reflects this is a development version.

cuenca_validations/types/__init__.py (1)

10-10: Properly exposes PostalCodeQuery in public API.

The addition of PostalCodeQuery to both the __all__ list and the imports correctly makes the new class publicly available from the types module.

Also applies to: 187-187

tests/test_types.py (1)

320-320: Correctly updated to use enum member directly.

The change from State.DF.value to State.DF properly aligns with the updated Address model where the state field now expects the enum member directly rather than its string value.

Comment thread cuenca_validations/types/identities.py Outdated
Comment thread tests/test_types.py Outdated
Copy link
Copy Markdown
Contributor

@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.

Actionable comments posted: 2

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c028d2a and 8b0bb4d.

📒 Files selected for processing (4)
  • cuenca_validations/types/identities.py (2 hunks)
  • cuenca_validations/types/requests.py (1 hunks)
  • cuenca_validations/version.py (1 hunks)
  • tests/test_types.py (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • cuenca_validations/version.py
🧰 Additional context used
📓 Path-based instructions (5)
`**/*.py`: Enforce Relative Imports for Internal Modules

Ensure that any import...

**/*.py: Enforce Relative Imports for Internal Modules

Ensure that any imports referencing internal modules use relative paths. However, if modules reside in the main module directories (for example /src or /library_or_app_name) —and relative imports are not feasible—absolute imports are acceptable. Additionally, if a module is located outside the main module structure (for example, in /tests or /scripts at a similar level), absolute imports are also valid.

Examples and Guidelines:

  1. If a module is in the same folder or a subfolder of the current file, use relative imports. For instance: from .some_module import SomeClass
  2. If the module is located under /src or /library_or_app_name and cannot be imported relatively, absolute imports are allowed (e.g., from library_or_app_name.utilities import helper_method).
  3. If a module is outside the main module directories (for example, in /tests, /scripts, or any similarly placed directory), absolute imports are valid.
  4. External (third-party) libraries should be imported absolutely (e.g., import requests).

⚙️ Source: CodeRabbit Configuration File

List of files the instruction was applied to:

  • cuenca_validations/types/requests.py
  • tests/test_types.py
  • cuenca_validations/types/identities.py
`**/*.py`: Rule: Enforce Snake Case in Python Backend
  1. New or Modified Code:...

**/*.py:
Rule: Enforce Snake Case in Python Backend

  1. New or Modified Code: Use snake_case for all variables, functions, methods, and class attributes.
  2. Exceptions (Pydantic models for API responses):
    • Primary fields must be snake_case.
    • If older clients expect camelCase, create a computed or alias field that references the snake_case field.
    • Mark any camelCase fields as deprecated or transitional.

Examples

Invalid:

class CardConfiguration(BaseModel):
    title: str
    subTitle: str  # ❌ Modified or new field in camelCase

Valid:

class CardConfiguration(BaseModel):
    title: str
    subtitle: str  # ✅ snake_case for new/modified field

    @computed_field
    def subTitle(self) -> str:  # camelCase allowed only for compatibility
        return self.subtitle

Any direct use of camelCase in new or updated code outside of these exceptions should be flagged.

⚙️ Source: CodeRabbit Configuration File

List of files the instruction was applied to:

  • cuenca_validations/types/requests.py
  • tests/test_types.py
  • cuenca_validations/types/identities.py
`**/*.py`: Use try/except for concise error handling when accessing nested dicti...

**/*.py: Use try/except for concise error handling when accessing nested dictionary keys:

try:
    can_ignore_error = data['error']['code'] in ignore_error_codes
except KeyError:
    can_ignore_error = False

❌ Avoid Verbose Chained Conditionals:

can_ignore_error = (
    'code' in data['error']
    and data['error']['code'] in ignore_error_codes
)

Explanation:
The try/except approach:

Reduces code complexity and nesting
Improves readability by focusing on the "happy path" logic
Follows Python's "easier to ask forgiveness than permission" (EAFP) idiom

Severity: Important (Not a Nitpick)
This pattern significantly improves code maintainability and readability, especially as dictionary access patterns become more complex.

⚙️ Source: CodeRabbit Configuration File

List of files the instruction was applied to:

  • cuenca_validations/types/requests.py
  • tests/test_types.py
  • cuenca_validations/types/identities.py
`**/*.py`: Context Agave is our internal Python library for processing SQS messa...

**/*.py: Context
Agave is our internal Python library for processing SQS messages. The @task decorator can automatically convert JSON to Pydantic models.

Rule
Always annotate @task parameters with Pydantic models instead of manually converting dictionaries.

Correct Pattern

from pydantic import BaseModel
from agave.tasks.sqs_tasks import task

class User(BaseModel):
    name: str
    age: int
    
@task(queue_url=QUEUE_URL, region_name='us-east-1')
async def task_validator(message: User) -> None:
    # The message is already a User instance - no conversion needed
    print(message.name)  # Direct attribute access

Incorrect Pattern

from pydantic import BaseModel
from agave.tasks.sqs_tasks import task

class User(BaseModel):
    name: str
    age: int
    
@task(queue_url=QUEUE_URL, region_name='us-east-1')
async def task_validator(message_data: dict) -> None:  # or unannotated parameter
    # Unnecessary conversion
    message = User(**message_data)
    print(message.name)

Explanation
The Agave @task decorator automatically:

  • Reads JSON messages from SQS queues
  • Converts them to Pydantic model instances when the handler parameter is annotated
  • Performs validation based on the Pydantic model

⚙️ Source: CodeRabbit Configuration File

List of files the instruction was applied to:

  • cuenca_validations/types/requests.py
  • tests/test_types.py
  • cuenca_validations/types/identities.py
`**/*.py`: ## MANDATORY: Use built-in Pydantic validators

Description

Avoid...

**/*.py: ## MANDATORY: Use built-in Pydantic validators

Description

Avoid creating custom validators that duplicate functionality already provided by Pydantic's built-in validators, pydantic_extra_types package, or third-party Pydantic validator libraries. This improves code maintainability and reduces unnecessary unit tests.

Bad Practice

from pydantic import BaseModel, field_validator

class MyValidator(BaseModel):
    location: str
    
    @field_validator('location')
    def validate_location(cls, value: str) -> str:
        values = value.split(',')
        if len(values) != 3:
            raise ValueError('Must provide exactly 3 values for location')
        # Custom validation logic that duplicates functionality
        return value

Good Practice

from pydantic import BaseModel
from pydantic_extra_types.coordinate import Coordinate

class MyValidator(BaseModel):
    location: Coordinate

Unit Test Guidelines

Do not write unit tests specifically for validating the behavior of Pydantic's built-in validators. These are already well-tested by the Pydantic library itself.

Tests to Remove

def test_invalid_location():
    pytest.raises(ValidationError):
        MyValidator(location='foo,bar')

Rule Enforcement

This is a mandatory rule, not a refactoring suggestion. Changes must be implemented when:

  1. A custom validator replicates functionality already available in Pydantic's ecosystem
  2. There is a suitable built-in, pydantic_extra_types, or third-party Pydantic validator available

Actions required:

  1. Replace custom validators with appropriate existing validators
  2. Remove unnecessary unit tests that only validate built-in Pydantic validation behavior
  3. Block PRs that introduce new custom validators when alternatives exist

⚙️ Source: CodeRabbit Configuration File

List of files the instruction was applied to:

  • cuenca_validations/types/requests.py
  • tests/test_types.py
  • cuenca_validations/types/identities.py
🧬 Code Graph Analysis (2)
cuenca_validations/types/requests.py (1)
cuenca_validations/types/identities.py (1)
  • Address (40-55)
cuenca_validations/types/identities.py (1)
cuenca_validations/types/enums.py (2)
  • KYCFileType (241-251)
  • VerificationStatus (556-563)
🔇 Additional comments (3)
tests/test_types.py (1)

317-317: LGTM! Test updated correctly for new Address model

The addition of postal_code_id to the address dictionary correctly reflects the new required field in the Address model. The test data is consistent with the updated model structure shown in cuenca_validations/types/identities.py.

cuenca_validations/types/identities.py (2)

2-2: LGTM! Import updates support new Address model structure

The import changes correctly support the updated Address model by adding Optional and NonEmptyStr while removing unused imports.

Also applies to: 4-4, 7-8


52-52: LGTM! Example updated to match new Address structure

The JSON schema example correctly reflects the new Address model structure with the required postal_code_id field.

Comment thread cuenca_validations/types/requests.py Outdated
Comment thread cuenca_validations/types/identities.py
Comment thread cuenca_validations/types/queries.py Outdated
Comment thread cuenca_validations/version.py Outdated
…o use optional fields and postal_code_id. Adjust tests accordingly.
Copy link
Copy Markdown
Contributor

@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.

Actionable comments posted: 1

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between bef86e9 and 9c5c4ac.

📒 Files selected for processing (3)
  • cuenca_validations/types/identities.py (1 hunks)
  • cuenca_validations/version.py (1 hunks)
  • tests/test_types.py (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • cuenca_validations/version.py
  • tests/test_types.py
🧰 Additional context used
📓 Path-based instructions (5)
`**/*.py`: Enforce Relative Imports for Internal Modules

Ensure that any import...

**/*.py: Enforce Relative Imports for Internal Modules

Ensure that any imports referencing internal modules use relative paths. However, if modules reside in the main module directories (for example /src or /library_or_app_name) —and relative imports are not feasible—absolute imports are acceptable. Additionally, if a module is located outside the main module structure (for example, in /tests or /scripts at a similar level), absolute imports are also valid.

Examples and Guidelines:

  1. If a module is in the same folder or a subfolder of the current file, use relative imports. For instance: from .some_module import SomeClass
  2. If the module is located under /src or /library_or_app_name and cannot be imported relatively, absolute imports are allowed (e.g., from library_or_app_name.utilities import helper_method).
  3. If a module is outside the main module directories (for example, in /tests, /scripts, or any similarly placed directory), absolute imports are valid.
  4. External (third-party) libraries should be imported absolutely (e.g., import requests).

⚙️ Source: CodeRabbit Configuration File

List of files the instruction was applied to:

  • cuenca_validations/types/identities.py
`**/*.py`: Rule: Enforce Snake Case in Python Backend
  1. New or Modified Code:...

**/*.py:
Rule: Enforce Snake Case in Python Backend

  1. New or Modified Code: Use snake_case for all variables, functions, methods, and class attributes.
  2. Exceptions (Pydantic models for API responses):
    • Primary fields must be snake_case.
    • If older clients expect camelCase, create a computed or alias field that references the snake_case field.
    • Mark any camelCase fields as deprecated or transitional.

Examples

Invalid:

class CardConfiguration(BaseModel):
    title: str
    subTitle: str  # ❌ Modified or new field in camelCase

Valid:

class CardConfiguration(BaseModel):
    title: str
    subtitle: str  # ✅ snake_case for new/modified field

    @computed_field
    def subTitle(self) -> str:  # camelCase allowed only for compatibility
        return self.subtitle

Any direct use of camelCase in new or updated code outside of these exceptions should be flagged.

⚙️ Source: CodeRabbit Configuration File

List of files the instruction was applied to:

  • cuenca_validations/types/identities.py
`**/*.py`: Use try/except for concise error handling when accessing nested dicti...

**/*.py: Use try/except for concise error handling when accessing nested dictionary keys:

try:
    can_ignore_error = data['error']['code'] in ignore_error_codes
except KeyError:
    can_ignore_error = False

❌ Avoid Verbose Chained Conditionals:

can_ignore_error = (
    'code' in data['error']
    and data['error']['code'] in ignore_error_codes
)

Explanation:
The try/except approach:

Reduces code complexity and nesting
Improves readability by focusing on the "happy path" logic
Follows Python's "easier to ask forgiveness than permission" (EAFP) idiom

Severity: Important (Not a Nitpick)
This pattern significantly improves code maintainability and readability, especially as dictionary access patterns become more complex.

⚙️ Source: CodeRabbit Configuration File

List of files the instruction was applied to:

  • cuenca_validations/types/identities.py
`**/*.py`: Context Agave is our internal Python library for processing SQS messa...

**/*.py: Context
Agave is our internal Python library for processing SQS messages. The @task decorator can automatically convert JSON to Pydantic models.

Rule
Always annotate @task parameters with Pydantic models instead of manually converting dictionaries.

Correct Pattern

from pydantic import BaseModel
from agave.tasks.sqs_tasks import task

class User(BaseModel):
    name: str
    age: int
    
@task(queue_url=QUEUE_URL, region_name='us-east-1')
async def task_validator(message: User) -> None:
    # The message is already a User instance - no conversion needed
    print(message.name)  # Direct attribute access

Incorrect Pattern

from pydantic import BaseModel
from agave.tasks.sqs_tasks import task

class User(BaseModel):
    name: str
    age: int
    
@task(queue_url=QUEUE_URL, region_name='us-east-1')
async def task_validator(message_data: dict) -> None:  # or unannotated parameter
    # Unnecessary conversion
    message = User(**message_data)
    print(message.name)

Explanation
The Agave @task decorator automatically:

  • Reads JSON messages from SQS queues
  • Converts them to Pydantic model instances when the handler parameter is annotated
  • Performs validation based on the Pydantic model

⚙️ Source: CodeRabbit Configuration File

List of files the instruction was applied to:

  • cuenca_validations/types/identities.py
`**/*.py`: ## MANDATORY: Use built-in Pydantic validators

Description

Avoid...

**/*.py: ## MANDATORY: Use built-in Pydantic validators

Description

Avoid creating custom validators that duplicate functionality already provided by Pydantic's built-in validators, pydantic_extra_types package, or third-party Pydantic validator libraries. This improves code maintainability and reduces unnecessary unit tests.

Bad Practice

from pydantic import BaseModel, field_validator

class MyValidator(BaseModel):
    location: str
    
    @field_validator('location')
    def validate_location(cls, value: str) -> str:
        values = value.split(',')
        if len(values) != 3:
            raise ValueError('Must provide exactly 3 values for location')
        # Custom validation logic that duplicates functionality
        return value

Good Practice

from pydantic import BaseModel
from pydantic_extra_types.coordinate import Coordinate

class MyValidator(BaseModel):
    location: Coordinate

Unit Test Guidelines

Do not write unit tests specifically for validating the behavior of Pydantic's built-in validators. These are already well-tested by the Pydantic library itself.

Tests to Remove

def test_invalid_location():
    pytest.raises(ValidationError):
        MyValidator(location='foo,bar')

Rule Enforcement

This is a mandatory rule, not a refactoring suggestion. Changes must be implemented when:

  1. A custom validator replicates functionality already available in Pydantic's ecosystem
  2. There is a suitable built-in, pydantic_extra_types, or third-party Pydantic validator available

Actions required:

  1. Replace custom validators with appropriate existing validators
  2. Remove unnecessary unit tests that only validate built-in Pydantic validation behavior
  3. Block PRs that introduce new custom validators when alternatives exist

⚙️ Source: CodeRabbit Configuration File

List of files the instruction was applied to:

  • cuenca_validations/types/identities.py
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: Analyze (actions)
  • GitHub Check: Analyze (python)
🔇 Additional comments (1)
cuenca_validations/types/identities.py (1)

78-78: Good approach using postal_code_id to simplify address validation.

The addition of postal_code_id as a required NonEmptyStr field aligns well with the refactoring strategy to centralize address identification. This approach reduces complexity compared to validating multiple discrete address fields.

Comment thread cuenca_validations/types/identities.py
Comment thread cuenca_validations/types/queries.py Outdated
@rogelioLpz rogelioLpz merged commit 37ee0b7 into main Jul 10, 2025
21 checks passed
@rogelioLpz rogelioLpz deleted the postal-code branch July 10, 2025 00:29
@coderabbitai coderabbitai Bot mentioned this pull request Jul 28, 2025
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.

2 participants