Skip to content

Conversation

@rogelioLpz
Copy link
Member

@rogelioLpz rogelioLpz commented Nov 25, 2025

No permite actualizar el documentos de Identidad si no se incluye el frente y reverso para la INE y otros tipos

Summary by CodeRabbit

  • New Features

    • Enhanced validation for government ID uploads: certain document types now require a back-side image; attempts to submit without it produce a clear validation error.
  • Tests

    • Added test coverage ensuring government ID back-side requirement and associated error handling behave as expected.

✏️ Tip: You can customize this high-level summary in your review settings.

@rogelioLpz rogelioLpz self-assigned this Nov 25, 2025
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 25, 2025

Walkthrough

Adds a top-level constant DOCS_WITH_BACK listing KYC document types that require a back-side image (ine, dni, residency, matricula_consular). Introduces a validate_govt_id field validator for govt_id (including on UserUpdateRequest) that raises ValueError("uri_back must be provided for type {type}") when a govt_id of those types lacks uri_back. Bumps __version__ from 2.1.22 to 2.1.23. Adds a test asserting the validator raises when uri_back is missing for type ine.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

  • Review validator conditional logic and exact error message formatting.
  • Confirm DOCS_WITH_BACK contains the intended document type identifiers.
  • Verify decorator placement on UserUpdateRequest and that validation triggers as expected in tests.

Files/areas to inspect:

  • cuenca_validations/types/requests.py
  • tests/test_requests.py
  • cuenca_validations/version.py

Pre-merge checks and finishing touches

❌ 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%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Validate uri_back exists' directly describes the main change: adding validation to ensure uri_back is provided for specific government ID document types.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch validate-uri-back

📜 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 4da62cf and aa08e76.

📒 Files selected for processing (1)
  • tests/test_requests.py (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/test_requests.py

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

@codecov
Copy link

codecov bot commented Nov 25, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (95f8482) to head (aa08e76).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff            @@
##              main      #394   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           16        16           
  Lines         1409      1417    +8     
=========================================
+ Hits          1409      1417    +8     
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/requests.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 95f8482...aa08e76. 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
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: 0

🧹 Nitpick comments (3)
tests/test_requests.py (1)

49-52: Test correctly asserts missing uri_back; consider covering all doc types requiring back.

This test covers the ine case well, but DOCS_WITH_BACK also includes dni, residency, and matricula_consular. Parametrizing over those types would better lock in the contract.

- def test_update_user_update_govt():
-    with pytest.raises(ValueError) as ex:
-        UserUpdateRequest(govt_id={'type': 'ine', 'uri_front': 'files/123'})
-    assert 'uri_back must be provided for type ine' in str(ex.value)
+@pytest.mark.parametrize(
+    'doc_type', ['ine', 'dni', 'residency', 'matricula_consular']
+)
+def test_update_user_govt_requires_uri_back(doc_type: str) -> None:
+    with pytest.raises(ValueError) as ex:
+        UserUpdateRequest(govt_id={'type': doc_type, 'uri_front': 'files/123'})
+    assert (
+        f'uri_back must be provided for type {doc_type}' in str(ex.value)
+    )
cuenca_validations/types/requests.py (2)

97-102: DOCS_WITH_BACK definition is clear; consider typing and immutability.

The constant accurately captures document types needing a back image; you could make it more explicit and immutable by adding a type annotation and switching to a tuple.

-DOCS_WITH_BACK = [
-    KYCFileType.ine,
-    KYCFileType.dni,
-    KYCFileType.residency,
-    KYCFileType.matricula_consular,
-]
+DOCS_WITH_BACK: tuple[KYCFileType, ...] = (
+    KYCFileType.ine,
+    KYCFileType.dni,
+    KYCFileType.residency,
+    KYCFileType.matricula_consular,
+)

555-561: govt_id validator enforces uri_back correctly; minor typing tweak possible.

The logic matches the requirement (back image required for the listed types) and error messaging aligns with the test; you can tighten typing and avoid relying on truthiness for a slightly clearer validator.

-    @field_validator('govt_id')
-    @classmethod
-    def validate_govt_id(cls, govt_id: KYCFile):
-        if govt_id and govt_id.type in DOCS_WITH_BACK and not govt_id.uri_back:
-            error = f'uri_back must be provided for type {govt_id.type.value}'
-            raise ValueError(error)
-        return govt_id
+    @field_validator('govt_id')
+    @classmethod
+    def validate_govt_id(
+        cls, govt_id: Optional[KYCFile]
+    ) -> Optional[KYCFile]:
+        if (
+            govt_id is not None
+            and govt_id.type in DOCS_WITH_BACK
+            and not govt_id.uri_back
+        ):
+            error = f'uri_back must be provided for type {govt_id.type.value}'
+            raise ValueError(error)
+        return govt_id
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 95f8482 and 312ced8.

📒 Files selected for processing (3)
  • cuenca_validations/types/requests.py (2 hunks)
  • cuenca_validations/version.py (1 hunks)
  • tests/test_requests.py (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.py

⚙️ CodeRabbit configuration file

**/*.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).

**/*.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.

`*...

Files:

  • tests/test_requests.py
  • cuenca_validations/types/requests.py
  • cuenca_validations/version.py
🧬 Code graph analysis (2)
tests/test_requests.py (1)
cuenca_validations/types/requests.py (1)
  • UserUpdateRequest (509-561)
cuenca_validations/types/requests.py (2)
cuenca_validations/types/enums.py (1)
  • KYCFileType (241-251)
cuenca_validations/types/identities.py (1)
  • KYCFile (138-175)
🔇 Additional comments (1)
cuenca_validations/version.py (1)

1-1: Version bump is consistent with the new validation; confirm intended impact level.

Stricter validation on govt_id.uri_back can cause previously accepted requests to fail, so treating this as a patch (2.1.222.1.23) is fine only if this is considered a bugfix rather than a behavior change for clients—please confirm and ensure any changelog/release notes call this out.

Copy link
Contributor

@gmorales96 gmorales96 left a comment

Choose a reason for hiding this comment

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

Solo un par de type hints

Copy link
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

🧹 Nitpick comments (2)
cuenca_validations/types/requests.py (1)

97-102: Use frozenset for more efficient membership checks.

Since DOCS_WITH_BACK is used for membership checks (line 558), using a frozenset provides O(1) lookup instead of O(n) for lists, and conveys immutability.

Apply this diff:

-DOCS_WITH_BACK = [
+DOCS_WITH_BACK = frozenset([
     KYCFileType.ine,
     KYCFileType.dni,
     KYCFileType.residency,
     KYCFileType.matricula_consular,
-]
+])
tests/test_requests.py (1)

49-52: Expand test coverage for all document types requiring uri_back.

The test only validates the INE type. Consider using @pytest.mark.parametrize to test all document types in DOCS_WITH_BACK (INE, DNI, residency, matricula_consular), and add a positive test case where providing uri_back allows the request to succeed.

Example enhancement:

@pytest.mark.parametrize(
    'doc_type',
    ['ine', 'dni', 'residency', 'matricula_consular']
)
def test_update_user_govt_id_requires_uri_back(doc_type: str) -> None:
    with pytest.raises(ValueError) as ex:
        UserUpdateRequest(
            govt_id=KYCFile(type=doc_type, uri_front='files/123')
        )
    assert f'uri_back must be provided for type {doc_type}' in str(ex.value)


@pytest.mark.parametrize(
    'doc_type',
    ['ine', 'dni', 'residency', 'matricula_consular']
)
def test_update_user_govt_id_with_uri_back_succeeds(doc_type: str) -> None:
    # Should not raise
    request = UserUpdateRequest(
        govt_id=KYCFile(
            type=doc_type,
            uri_front='files/123',
            uri_back='files/456'
        )
    )
    assert request.govt_id is not None
    assert request.govt_id.uri_back == 'files/456'
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 312ced8 and 4da62cf.

📒 Files selected for processing (2)
  • cuenca_validations/types/requests.py (2 hunks)
  • tests/test_requests.py (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.py

⚙️ CodeRabbit configuration file

**/*.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).

**/*.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.

`*...

Files:

  • tests/test_requests.py
  • cuenca_validations/types/requests.py
🧠 Learnings (1)
📚 Learning: 2025-07-09T00:29:18.195Z
Learnt from: gmorales96
Repo: cuenca-mx/cuenca-validations PR: 376
File: cuenca_validations/types/identities.py:86-86
Timestamp: 2025-07-09T00:29:18.195Z
Learning: The `postal_code_id` field in `AddressRequest` model in `cuenca_validations/types/identities.py` refers to a database record ID that references a postal code record, not the actual postal code value itself. Therefore, it should use standard database ID validation (like `NonEmptyStr`) rather than postal code format validation.

Applied to files:

  • cuenca_validations/types/requests.py
🧬 Code graph analysis (1)
cuenca_validations/types/requests.py (2)
cuenca_validations/types/enums.py (1)
  • KYCFileType (241-251)
cuenca_validations/types/identities.py (1)
  • KYCFile (138-175)
🪛 GitHub Actions: test
tests/test_requests.py

[error] 51-51: mypy: Argument "govt_id" to "UserUpdateRequest" has incompatible type "dict[str, str]"; expected "KYCFile | None" [arg-type]

🔇 Additional comments (1)
cuenca_validations/types/requests.py (1)

555-561: LGTM! Validator logic is correct.

The validator correctly enforces that government ID documents requiring a back side (INE, DNI, residency, matricula consular) must have uri_back provided. The error message is clear and specific.

felipao-mx
felipao-mx previously approved these changes Nov 25, 2025
@rogelioLpz rogelioLpz merged commit 45ab309 into main Nov 25, 2025
21 checks passed
@rogelioLpz rogelioLpz deleted the validate-uri-back branch November 25, 2025 18:25
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.

4 participants