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

Attachment refactor #98

Merged
merged 4 commits into from
Jun 25, 2024
Merged

Attachment refactor #98

merged 4 commits into from
Jun 25, 2024

Conversation

SchrodingersGat
Copy link
Collaborator

@SchrodingersGat SchrodingersGat commented Jun 24, 2024

This PR adds support for the "modern" attachments table in InvenTree, which uses a single database table to store all attachments.

Ref: inventree/InvenTree#7420

Without this PR, the plugin breaks on any installation running off the 0.16.x dev branch.

Summary by CodeRabbit

  • New Features
    • Enhanced attachment handling for parts, supporting both 'modern' and 'legacy' attachment tables.
    • Improved datasheet fetching with case-insensitive comment matching for streamlined attachment filtering.

Copy link

coderabbitai bot commented Jun 24, 2024

Walkthrough

The recent changes enhance the import_meta_data functionality within the KiCad Library Plugin by introducing a dedicated add_attachment method to manage attachments for parts. This method now accommodates both modern and legacy attachment tables. Additionally, the get_datasheet method in serializers.py has been optimized to filter datasheets efficiently using case-insensitive matching, improving overall data handling.

Changes

Files/Paths Change Summaries
inventree_kicad/KiCadLibraryPlugin.py Refactored import_meta_data to use a new add_attachment method. Supported handling for both modern and legacy attachment tables. Removed import of PartAttachment.
inventree_kicad/serializers.py Updated get_datasheet to use case-insensitive filtering for datasheet comments, optimizing the logic.

Sequence Diagram(s)

sequenceDiagram
  participant User
  participant KiCadLibraryPlugin
  participant Part
  participant PartAttachment (Modern)
  participant PartAttachment (Legacy)

  User ->> KiCadLibraryPlugin: import_meta_data(part)
  KiCadLibraryPlugin ->>+ Part: Retrieve part details
  KiCadLibraryPlugin ->>+ add_attachment: Handle attachments
  add_attachment ->> PartAttachment (Modern): Add to modern table (if applicable)
  add_attachment ->> PartAttachment (Legacy): Add to legacy table (if applicable)
  PartAttachment (Modern) -->> KiCadLibraryPlugin: Attachment added
  PartAttachment (Legacy) -->> KiCadLibraryPlugin: Attachment added

  Note over KiCadLibraryPlugin,User: Attachment process complete
Loading
sequenceDiagram
  participant User
  participant serializers.py
  participant Attachment

  User ->> serializers.py: get_datasheet(part)
  serializers.py ->>+ Attachment: Filter attachments by case-insensitive "datasheet"
  Attachment -->> serializers.py: Return filtered datasheet
  serializers.py -->> User: Returned datasheet
Loading

Poem

🐰 In code, we find a new delight,
As attachments now are handled right.
Modern or legacy, all in flow,
Improved, the datasheets now show.
With changes swift and filters keen,
Our library's efficiency clearly seen.
📚✨


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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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 resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration 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

@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

Commits

Files that changed from the base of the PR and between ab386e9 and ad3e585.

Files selected for processing (2)
  • inventree_kicad/KiCadLibraryPlugin.py (2 hunks)
  • inventree_kicad/serializers.py (1 hunks)
Additional context used
Ruff
inventree_kicad/serializers.py

234-236: Use a single if statement instead of nested if statements (SIM102)


262-263: Use a single if statement instead of nested if statements (SIM102)

Additional comments not posted (2)
inventree_kicad/serializers.py (1)

206-206: Optimized attachment filtering logic.

The new implementation using filter(comment__iexact='datasheet') directly in the database query is a significant improvement over iterating over all attachments. This change enhances both performance and clarity by leveraging the database's capabilities to filter data.

inventree_kicad/KiCadLibraryPlugin.py (1)

18-18: Updated import statement.

The import statement has been simplified by removing PartAttachment. This change aligns with the new handling of attachments using a unified approach as described in the PR linked at inventree/InvenTree#7420.

Comment on lines +366 to +415
def add_attachment(self, part_id, link):
"""Add an external link as an attachment for the part.

Note: We support the 'legacy' and 'modern' attachment tables.

Ref: https://github.com/inventree/InvenTree/pull/7420
"""

# First, try the 'modern' attachment table
try:
from common.models import Attachment

# Check if there is an existing attachment
attachment = Attachment.objects.filter(
model_type='part',
model_id=part_id,
comment__iexact='datasheet'
)

if not attachment.exists():
Attachment.objects.create(
model_type='part',
model_id=part_id,
link=link,
comment='Datasheet'
)

return
except Exception:
pass

# Second, try the 'legacy' attachment table
try:
from part.models import PartAttachment

# Check if there is an existing attachment
attachment = PartAttachment.objects.filter(
part=part_id,
comment__iexact='datasheet'
)

if not attachment.exists():
PartAttachment.objects.create(
part=part_id,
link=link,
comment='Datasheet'
)

except Exception:
pass
Copy link

Choose a reason for hiding this comment

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

Refactor suggestion for the add_attachment method.

The method handles both 'modern' and 'legacy' attachment tables, which is good for compatibility. However, the method contains duplicate logic for checking and creating attachments in two different models. Consider refactoring to reduce duplication and improve maintainability.

- # First, try the 'modern' attachment table
- try:
-     from common.models import Attachment
-     # Check if there is an existing attachment
-     attachment = Attachment.objects.filter(
-         model_type='part',
-         model_id=part_id,
-         comment__iexact='datasheet'
-     )
-     if not attachment.exists():
-         Attachment.objects.create(
-             model_type='part',
-             model_id=part_id,
-             link=link,
-             comment='Datasheet'
-         )
-     return
- except Exception:
-     pass
- # Second, try the 'legacy' attachment table
- try:
-     from part.models import PartAttachment
-     # Check if there is an existing attachment
-     attachment = PartAttachment.objects.filter(
-         part=part_id,
-         comment__iexact='datasheet'
-     )
-     if not attachment.exists():
-         PartAttachment.objects.create(
-             part=part_id,
-             link=link,
-             comment='Datasheet'
-         )
- except Exception:
-     pass

+ def try_add_attachment(model, **kwargs):
+     """Utility function to attempt adding an attachment if it does not exist."""
+     attachment = model.objects.filter(**kwargs)
+     if not attachment.exists():
+         model.objects.create(**kwargs)
+
+ from common.models import Attachment
+ from part.models import PartAttachment
+
+ # Try adding to the 'modern' attachment table
+ try_add_attachment(Attachment, model_type='part', model_id=part_id, link=link, comment='Datasheet')
+
+ # Fallback to the 'legacy' attachment table
+ try_add_attachment(PartAttachment, part=part_id, link=link, comment='Datasheet')
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.

Suggested change
def add_attachment(self, part_id, link):
"""Add an external link as an attachment for the part.
Note: We support the 'legacy' and 'modern' attachment tables.
Ref: https://github.com/inventree/InvenTree/pull/7420
"""
# First, try the 'modern' attachment table
try:
from common.models import Attachment
# Check if there is an existing attachment
attachment = Attachment.objects.filter(
model_type='part',
model_id=part_id,
comment__iexact='datasheet'
)
if not attachment.exists():
Attachment.objects.create(
model_type='part',
model_id=part_id,
link=link,
comment='Datasheet'
)
return
except Exception:
pass
# Second, try the 'legacy' attachment table
try:
from part.models import PartAttachment
# Check if there is an existing attachment
attachment = PartAttachment.objects.filter(
part=part_id,
comment__iexact='datasheet'
)
if not attachment.exists():
PartAttachment.objects.create(
part=part_id,
link=link,
comment='Datasheet'
)
except Exception:
pass
def add_attachment(self, part_id, link):
"""Add an external link as an attachment for the part.
Note: We support the 'legacy' and 'modern' attachment tables.
Ref: https://github.com/inventree/InvenTree/pull/7420
"""
def try_add_attachment(model, **kwargs):
"""Utility function to attempt adding an attachment if it does not exist."""
attachment = model.objects.filter(**kwargs)
if not attachment.exists():
model.objects.create(**kwargs)
from common.models import Attachment
from part.models import PartAttachment
# Try adding to the 'modern' attachment table
try_add_attachment(Attachment, model_type='part', model_id=part_id, link=link, comment='Datasheet')
# Fallback to the 'legacy' attachment table
try_add_attachment(PartAttachment, part=part_id, link=link, comment='Datasheet')

@SchrodingersGat SchrodingersGat merged commit 250ccb5 into main Jun 25, 2024
2 checks passed
@SchrodingersGat SchrodingersGat deleted the attachment-refactor branch June 25, 2024 00:07
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.

1 participant