Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add ref id to assets #1509

Merged
merged 6 commits into from
Feb 18, 2025
Merged

feat: add ref id to assets #1509

merged 6 commits into from
Feb 18, 2025

Conversation

Axxiar
Copy link
Contributor

@Axxiar Axxiar commented Feb 17, 2025

Summary by CodeRabbit

  • New Features
    • Enhanced asset forms now include a dedicated Reference ID field that accepts longer values (up to 100 characters).
    • Asset listings have been updated to display the Reference ID, offering improved record identification.

Copy link
Contributor

coderabbitai bot commented Feb 17, 2025

Walkthrough

The changes update how the ref_id field is handled across both backend and frontend components. In the backend, the ref_id field in the Asset and RiskScenario models is expanded from 8 to 100 characters, with a corresponding migration applied. In the frontend, a new text input for ref_id is added to the Asset form, and the validation schemas and table view configurations are updated to reflect the increased length. Overall functionality remains consistent while allowing longer reference identifiers.

Changes

File(s) Change Summary
backend/core/models.py
backend/.../0053_asset_ref_id_alter_riskscenario_ref_id.py
Expanded ref_id field: Increased max length from 8 to 100 in the RiskScenario model and added it to the Asset model. A migration script updates the database schema accordingly.
frontend/.../AssetForm.svelte
frontend/.../schemas.ts
frontend/.../table.ts
Frontend updates: Added a new <TextField> component for ref_id in the Asset form, updated schemas to allow a 100-character ref_id, and modified the asset table view to include the new field.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant AssetForm
    participant SchemaValidator
    participant API
    participant Database

    User->>AssetForm: Enter ref_id value
    AssetForm->>SchemaValidator: Validate ref_id (max 100 chars)
    SchemaValidator-->>AssetForm: Return validation result
    AssetForm->>API: Submit asset data with ref_id
    API->>Database: Save asset record (including ref_id)
    Database-->>API: Confirm data persistence
    API-->>User: Return creation/update confirmation
Loading

Poem

(_/)
( •.•) Hopped into code with glee,
I stretched my ref_id wide as can be.
From eight to a hundred, like carrots in a row,
Each change makes our project happily grow!
Bye-bye limits—let the longer IDs show!

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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. (Beta)
  • @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.

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

🔭 Outside diff range comments (1)
backend/core/models.py (1)

2664-2664: 🛠️ Refactor suggestion

Align field validation with the default reference ID format.

The get_default_ref_id method generates IDs in the format "R.{number}", but the field lacks validation to ensure manually entered IDs follow this format.

-    ref_id = models.CharField(max_length=8, blank=True, verbose_name=_("Reference ID"))
+    ref_id = models.CharField(
+        max_length=8,
+        blank=True,
+        validators=[
+            RegexValidator(
+                regex=r'^R\.\d+$',
+                message='Reference ID must be in format R.{number}',
+                code='invalid_risk_ref_id'
+            )
+        ],
+        verbose_name=_("Reference ID")
+    )
🧹 Nitpick comments (1)
backend/core/models.py (1)

1575-1575: Consider adding constraints and validation for the reference ID field.

While the field definition is correct, consider the following improvements:

  1. Add a unique constraint if reference IDs should be unique across assets
  2. Add a validator to enforce a specific format (e.g., alphanumeric)
-    ref_id = models.CharField(max_length=8, blank=True, verbose_name=_("Reference ID"))
+    ref_id = models.CharField(
+        max_length=8,
+        blank=True,
+        unique=True,  # If ref_ids should be unique
+        validators=[
+            RegexValidator(
+                regex=r'^[A-Za-z0-9-_.]+$',
+                message='Reference ID must be alphanumeric',
+                code='invalid_ref_id'
+            )
+        ],
+        verbose_name=_("Reference 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 aee03c7 and dd46cf0.

📒 Files selected for processing (5)
  • backend/core/migrations/0053_asset_ref_id.py (1 hunks)
  • backend/core/models.py (1 hunks)
  • frontend/src/lib/components/Forms/ModelForm/AssetForm.svelte (1 hunks)
  • frontend/src/lib/utils/schemas.ts (1 hunks)
  • frontend/src/lib/utils/table.ts (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (11)
  • GitHub Check: startup-functional-test (3.12)
  • GitHub Check: startup-docker-compose-test
  • GitHub Check: functional-tests (3.12, chromium)
  • GitHub Check: enterprise-startup-functional-test (3.12)
  • GitHub Check: build (3.12)
  • GitHub Check: ruff (3.12)
  • GitHub Check: enterprise-startup-docker-compose-test
  • GitHub Check: enterprise-functional-tests (3.12, chromium)
  • GitHub Check: test (3.12)
  • GitHub Check: Analyze (python)
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (4)
backend/core/migrations/0053_asset_ref_id.py (1)

1-19: LGTM! Migration looks good.

The migration correctly adds the ref_id field to the asset model with appropriate constraints.

frontend/src/lib/components/Forms/ModelForm/AssetForm.svelte (1)

73-79: LGTM! Form field implementation looks good.

The TextField component for ref_id is properly implemented with all necessary props and data binding.

frontend/src/lib/utils/schemas.ts (1)

222-223: LGTM! Schema definition looks good.

The ref_id field is properly defined in the AssetSchema with matching constraints (optional, max length 8).

frontend/src/lib/utils/table.ts (1)

571-571: LGTM! Table configuration looks good.

The ref_id field is properly added to both the header and body configurations of the assets table.

Also applies to: 582-582

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 (1)
backend/core/migrations/0054_alter_asset_ref_id_alter_riskscenario_ref_id.py (1)

5-5: Fix formatting issue.

Remove the extra newline at line 5 to adhere to the formatting standards.

from django.db import migrations, models
-
class Migration(migrations.Migration):
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 934d226 and 0437f34.

📒 Files selected for processing (1)
  • backend/core/migrations/0054_alter_asset_ref_id_alter_riskscenario_ref_id.py (1 hunks)
🧰 Additional context used
🪛 GitHub Actions: Backend Linters
backend/core/migrations/0054_alter_asset_ref_id_alter_riskscenario_ref_id.py

[warning] 1-1: File would be reformatted. Please adhere to the formatting standards.

⏰ Context from checks skipped due to timeout of 90000ms (10)
  • GitHub Check: startup-functional-test (3.12)
  • GitHub Check: startup-docker-compose-test
  • GitHub Check: enterprise-functional-tests (3.12, chromium)
  • GitHub Check: enterprise-startup-docker-compose-test
  • GitHub Check: functional-tests (3.12, chromium)
  • GitHub Check: test (3.12)
  • GitHub Check: enterprise-startup-functional-test (3.12)
  • GitHub Check: build (3.12)
  • GitHub Check: Analyze (python)
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (3)
backend/core/migrations/0054_alter_asset_ref_id_alter_riskscenario_ref_id.py (3)

13-17: LGTM! Field modification for Asset model looks good.

The field attributes are well-defined and the change from max_length=8 to max_length=100 is non-breaking.


18-22:

✅ Verification successful

LGTM! Field modification for RiskScenario model looks good.

The field attributes are consistent with the Asset model and well-defined.

Let's verify if there's any existing data that needs attention:


🏁 Script executed:

#!/bin/bash
# Description: Check for existing ref_id values in both models
# that might be affected by the field modification

# Search for model definitions to understand the table names
rg -A 5 "class Asset\(" 
rg -A 5 "class RiskScenario\("

# Note: In a real environment, you would need to check the database
# for records where ref_id length > 8 characters

Length of output: 712


Field Modification Approved for RiskScenario Model

The migration altering the ref_id field in the RiskScenario model (using CharField(blank=True, max_length=100)) is consistent with the Asset model’s configuration. The executed script confirmed that both models are defined as expected.

Please ensure that, in your production environment, any existing records with ref_id values that might exceed prior length constraints are reviewed and handled appropriately.


1-1:

❓ Verification inconclusive

Verify Django version compatibility.

The migration is generated using Django 5.1.5. Let's verify if this version is stable and compatible with the project's requirements.


🌐 Web query:

What is the latest stable version of Django?

💡 Result:

The latest stable version of Django is 5.1.6, released on February 5, 2025[1][4][7]. This version supports Python 3.10, 3.11, 3.12, and Python 3.13 (added in Django 5.1.3)[1].

Key details:

  • Security support for Django 5.1 will continue until December 31, 2025[2]
  • Installation command:
    python -m pip install Django==5.1.6 (Linux/macOS)
    py -m pip install Django==5.1.6 (Windows)[4]
  • The previous LTS version remains 4.2.x (supported until April 2026)[2]

For production environments, using the latest stable release (currently v5.x) is recommended to benefit from security updates and new features[4].

Citations:


Django Version Compatibility Verification

The migration header shows it was generated with Django 5.1.5, but the latest stable release is now Django 5.1.6. Please verify that your project’s environment is intentionally using 5.1.5. If not, consider upgrading to Django 5.1.6 to benefit from the latest security updates and fixes.

  • Confirm that the Django version in your virtual environment or requirements is set as expected.
  • If an upgrade is planned, update the migration header accordingly.
🧰 Tools
🪛 GitHub Actions: Backend Linters

[warning] 1-1: File would be reformatted. Please adhere to the formatting standards.

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 (1)
backend/core/migrations/0053_asset_ref_id_alter_riskscenario_ref_id.py (1)

1-27: Consider performance impact on large tables.

For large tables, altering column definitions could potentially lock the table during the migration.

Consider:

  1. Running this migration during off-peak hours
  2. If the tables are large, use Django's database constraints to add the field without locking:
    migrations.SeparateDatabaseAndState(
        state_operations=[...],  # Your current operations
        database_operations=[...] # Custom SQL with ALTER TABLE LOCK=NONE
    )
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0437f34 and 26773d1.

📒 Files selected for processing (1)
  • backend/core/migrations/0053_asset_ref_id_alter_riskscenario_ref_id.py (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (10)
  • GitHub Check: startup-functional-test (3.12)
  • GitHub Check: enterprise-startup-docker-compose-test
  • GitHub Check: functional-tests (3.12, chromium)
  • GitHub Check: build (3.12)
  • GitHub Check: enterprise-startup-functional-test (3.12)
  • GitHub Check: enterprise-functional-tests (3.12, chromium)
  • GitHub Check: test (3.12)
  • GitHub Check: startup-docker-compose-test
  • GitHub Check: Analyze (python)
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (2)
backend/core/migrations/0053_asset_ref_id_alter_riskscenario_ref_id.py (2)

11-18: LGTM! Adding ref_id to Asset model.

The field definition is consistent and well-structured with appropriate attributes.

Before applying this migration in production, verify that no unique constraints are needed on the ref_id field. If reference IDs should be unique per asset, consider adding a unique constraint:

 field=models.CharField(
-    blank=True, max_length=100, verbose_name="Reference ID"
+    blank=True, max_length=100, verbose_name="Reference ID", unique=True
 ),

19-25:

❓ Verification inconclusive

Verify data safety for RiskScenario ref_id modification.

The field modification looks good, but since we're altering an existing field from 8 to 100 characters, ensure data safety.

Run this script to check for any existing data that might be affected:


🏁 Script executed:

#!/bin/bash
# Description: Check for RiskScenario ref_ids that might be affected by the migration

# Use Django's shell to inspect existing data
python manage.py shell << EOF
from core.models import RiskScenario
scenarios = RiskScenario.objects.exclude(ref_id='').values_list('ref_id', flat=True)
print("Current ref_ids:", list(scenarios))
print("Max length found:", max((len(id) for id in scenarios), default=0))
EOF

Length of output: 116


Attention: Verify RiskScenario ref_id Data Safety Before Migration

  • The migration modifying RiskScenario.ref_id appears correctly implemented.

  • The initial verification script failed because manage.py was not found in the expected path. It’s likely that the Django project’s entry point is located elsewhere (e.g., within the backend directory).

  • Action Required: Please re-run the verification script from the correct project directory. For example:

    # Run from the repository root
    cd backend
    python manage.py shell << EOF
    from core.models import RiskScenario
    scenarios = RiskScenario.objects.exclude(ref_id='').values_list('ref_id', flat=True)
    print("Current ref_ids:", list(scenarios))
    print("Max length found:", max((len(id) for id in scenarios), default=0))
    EOF
  • Once you confirm that existing ref_id values are within safe limits, the migration can be considered safe.

@Mohamed-Hacene Mohamed-Hacene self-requested a review February 18, 2025 14:12
Copy link
Collaborator

@Mohamed-Hacene Mohamed-Hacene left a comment

Choose a reason for hiding this comment

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

0k

@Mohamed-Hacene Mohamed-Hacene merged commit 9494729 into main Feb 18, 2025
20 checks passed
@Mohamed-Hacene Mohamed-Hacene deleted the CA-829-add-ref-id-to-assets branch February 18, 2025 14:12
@github-actions github-actions bot locked and limited conversation to collaborators Feb 18, 2025
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants