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

Implement syncing with parent item location. #275

Open
wants to merge 6 commits into
base: main
Choose a base branch
from

Conversation

slid1amo2n3e4
Copy link

@slid1amo2n3e4 slid1amo2n3e4 commented Oct 8, 2024

What type of PR is this?

  • feature

What this PR does / why we need it:

Implements ability to sync parent item's location to its children.

Which issue(s) this PR fixes:

Fixes #110

sht do I have to also include this?: close #110

Summary by CodeRabbit

  • New Features

    • Introduced a new toggle for managing item location synchronization.
    • Added functionality to synchronize child item locations with parent items.
  • Enhancements

    • Updated item management logic to conditionally synchronize child items during updates.
    • Enhanced control over parent-child relationships in item updates.
    • Improved user notifications regarding synchronization status when editing items.
  • Tests

    • Added test cases to verify the synchronization of child item locations with their parent.
  • Documentation

    • Enhanced API documentation to include new properties for item synchronization.
    • Updated Swagger documentation to reflect the new synchronization capabilities.

Copy link
Contributor

coderabbitai bot commented Oct 8, 2024

Walkthrough

The changes introduce a feature that allows the synchronization of child item locations with their parent item when the parent's location is updated. This is achieved by adding a boolean field, syncChildItemsLocations, to relevant data structures and updating various methods to manage this synchronization. The ItemOut and ItemUpdate structs are also updated to include this field for output and modification purposes. Additionally, the Swagger documentation is modified to reflect these changes, ensuring consistency across the API.

Changes

File Path Change Summary
backend/app/api/static/docs/docs.go Added syncChildItemsLocations field to Swagger docs for ItemOut and ItemUpdate.
backend/app/api/static/docs/swagger.json Updated Swagger documentation to include syncChildItemsLocations for ItemOut and ItemUpdate.
backend/app/api/static/docs/swagger.yaml Added syncChildItemsLocations to Swagger YAML definitions for ItemOut and ItemUpdate.
backend/internal/data/ent/item.go Introduced SyncChildItemsLocations field to Item struct and updated related methods.
backend/internal/data/ent/item/item.go Added FieldSyncChildItemsLocations constant and new query function for ordering by this field.
backend/internal/data/ent/item/where.go Introduced predicate functions for sync_child_items_locations.
backend/internal/data/ent/item_update.go Added methods for managing sync_child_items_locations in ItemUpdate builders.
frontend/lib/api/types/data-contracts.ts Added syncChildItemsLocations property to ItemOut and ItemUpdate interfaces.
frontend/pages/item/[id]/index/edit.vue Implemented functions for managing location synchronization with parent items.
frontend/lib/api/test/user/items.test.ts Added test case for verifying child items sync their location to their parent.

Assessment against linked issues

Objective Addressed Explanation
Ability to move all child items when the location of the parent item is changed (#[110])
Implement a toggle for linking parent and child item locations (#[110])
Ensure child items update their location based on the parent's location (#[110])

Security Recommendations

  • Ensure that the synchronization feature is properly secured, especially in the context of user permissions. Only authorized users should be able to change the synchronization settings for parent and child items.
  • Validate input data thoroughly when updating item locations to prevent unauthorized changes or data corruption.
  • Implement logging for changes made to item locations, especially when synchronization occurs, to maintain an audit trail for accountability.

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

@tankerkiller125
Copy link
Contributor

As a note, we're basically ignore the PR Testing CI, but I needed a PR to test it on to see what's broken so I can hopefully fix it. It has no effect on if we merge this or not. Although the Go Lint does have a valid thing that @coderabbitai missed. Notably:

Error: ST1003: should not use underscores in Go names; var child_location should be childLocation (stylecheck)

Copy link
Contributor

coderabbitai bot commented Oct 8, 2024

Tip

For best results, initiate chat on the files or code changes.

@tankerkiller125: Thank you for pointing out the variable naming issue. I apologize for missing this during the review. You're correct—Go naming conventions recommend using camelCase without underscores for variable names, as per Stylecheck ST1003. The variable child_location should be renamed to childLocation. I'll make sure to pay closer attention to this in future reviews.

Consistent adherence to coding standards improves code readability and maintainability, which helps prevent potential bugs and security vulnerabilities.


✏️ Learnings added
Learnt from: tankerkiller125
URL: https://github.com/sysadminsmedia/homebox/pull/275

Timestamp: 2024-10-08T20:00:55.236Z
Learning: In Go code, variable names should use camelCase without underscores, following Stylecheck ST1003.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

@katosdev
Copy link
Contributor

katosdev commented Oct 16, 2024

Thanks for updating to fix the underscores @slid1amo2n3e4 !

@katosdev
Copy link
Contributor

@coderabbitai full review

Copy link
Contributor

coderabbitai bot commented Oct 16, 2024

✅ Actions performed

Full review triggered.

Copy link
Contributor

coderabbitai bot commented Oct 16, 2024

@katosdev: Understood, and it's great to see that the underscores have been fixed. I will perform a full review of the pull request.

✅ Actions performed

Full review triggered.

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: 4

🧹 Outside diff range and nitpick comments (1)
frontend/lib/api/__test__/user/items.test.ts (1)

200-208: Use faker for consistent test data generation.

Consider using faker for generating test data to maintain consistency with other tests in the file.

-      name: "parent-item",
+      name: faker.commerce.productName(),
-      description: "test-description",
+      description: faker.lorem.sentence(),
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between f6d1f9c and ab80805.

📒 Files selected for processing (2)
  • frontend/lib/api/test/user/items.test.ts (1 hunks)
  • frontend/pages/item/[id]/index/edit.vue (3 hunks)
🔇 Additional comments (4)
frontend/lib/api/__test__/user/items.test.ts (3)

241-250: Verify syncChildItemsLocations flag in the response.

The test sets the sync flag but doesn't verify if it was properly set in the response data.

Add verification:

 expect(updateResponse.status).toBe(200);
+expect(updateData.syncChildItemsLocations).toBe(true);

251-261: Enhance test coverage with additional test cases.

While the test verifies the basic functionality, consider adding:

  1. Verification that other properties remained unchanged
  2. Negative test case when syncChildItemsLocations is false
  3. Error cases (e.g., invalid location IDs)

Example additions:

// Verify other properties remained unchanged
expect(child1FinalData.name).toBe(child1Item.name);
expect(child1FinalData.description).toBe(child1Item.description);

// Add negative test case
test("child items don't sync location when flag is false", async () => {
  // Similar setup but with syncChildItemsLocations: false
  // Verify locations remain unchanged
});

// Add error case
test("handles invalid location IDs gracefully", async () => {
  // Setup with invalid location ID
  // Verify appropriate error response
});

195-261: Add security-related test cases.

The test should verify that proper authorization checks are in place to prevent unauthorized users from modifying item locations.

Add security test cases:

test("prevents unauthorized users from syncing locations", async () => {
  const unauthorizedApi = await createUnauthorizedUserClient();
  // Attempt to update parent with sync flag
  const { response } = await unauthorizedApi.items.update(parent.id, {
    ...parent,
    syncChildItemsLocations: true
  });
  expect(response.status).toBe(403);
});

test("prevents syncing locations across different organizations", async () => {
  // Setup items in different organizations
  // Attempt to establish parent-child relationship
  // Verify it's prevented
});
frontend/pages/item/[id]/index/edit.vue (1)

478-478: ⚠️ Potential issue

Add a semicolon at the end of the assignment statement.

There's a missing semicolon at the end of the assignment on line 478. Adding it ensures consistency and prevents potential syntax issues.

Apply this diff to fix the issue:

-            item.value.location = data.location
+            item.value.location = data.location;

Likely invalid or redundant comment.

Comment on lines +209 to +240
const { response: child1Response, data: child1Item } = await api.items.create({
name: "child1-item",
labelIds: [],
description: "test-description",
locationId: childsLocation.id,
});
expect(child1Response.status).toBe(201);
const child1ItemUpdate = {
parentId: parent.id,
...child1Item,
locationId: child1Item.location?.id,
labelIds: []
};
const { response: child1UpdatedResponse, data: child1UpdatedData } = await api.items.update(child1Item.id, child1ItemUpdate as ItemUpdate);
expect(child1UpdatedResponse.status).toBe(200);

const { response: child2Response, data: child2Item } = await api.items.create({
name: "child2-item",
labelIds: [],
description: "test-description",
locationId: childsLocation.id,
});
expect(child2Response.status).toBe(201);
const child2ItemUpdate = {
parentId: parent.id,
...child2Item,
locationId: child2Item.location?.id,
labelIds: []
}
const { response: child2UpdatedResponse, data: child2UpdatedData } = await api.items.update(child2Item.id, child2ItemUpdate as ItemUpdate);
expect(child2UpdatedResponse.status).toBe(200);

Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Reduce code duplication by extracting child item creation logic.

The child item creation and parent association logic is duplicated. Consider extracting this into a helper function.

async function createChildItem(api: UserClient, parentId: string, locationId: string, name: string) {
  const { response, data: childItem } = await api.items.create({
    name,
    labelIds: [],
    description: faker.lorem.sentence(),
    locationId,
  });
  expect(response.status).toBe(201);
  
  const childItemUpdate = {
    parentId,
    ...childItem,
    locationId: childItem.location?.id,
    labelIds: []
  };
  
  const { response: updatedResponse, data: updatedData } = await api.items.update(
    childItem.id,
    childItemUpdate as ItemUpdate
  );
  expect(updatedResponse.status).toBe(200);
  
  return updatedData;
}

// Usage:
const child1 = await createChildItem(api, parent.id, childsLocation.id, "child1-item");
const child2 = await createChildItem(api, parent.id, childsLocation.id, "child2-item");

Comment on lines +195 to +199
test("child items sync their location to their parent", async () => {
const api = await sharedUserClient();
const [parentLocation, parentCleanup] = await useLocation(api);
const [childsLocation, childsCleanup] = await useLocation(api);

Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider enhancing test isolation with beforeEach/afterEach.

The test follows good practices by using the useLocation helper and handling cleanup. However, to improve test isolation and reduce boilerplate, consider moving the location setup into test hooks.

+ let parentLocation: LocationOut;
+ let childsLocation: LocationOut;
+ let cleanup: (() => Promise<void>)[];
+ 
+ beforeEach(async () => {
+   cleanup = [];
+   [parentLocation, const parentCleanup] = await useLocation(api);
+   [childsLocation, const childsCleanup] = await useLocation(api);
+   cleanup.push(parentCleanup, childsCleanup);
+ });
+ 
+ afterEach(async () => {
+   for (const cleanupFn of cleanup) {
+     await cleanupFn();
+   }
+ });

Committable suggestion was skipped due to low confidence.

@@ -533,8 +590,9 @@
<div class="mt-2 flex flex-wrap items-center justify-between gap-4"></div>
</template>
<div class="mb-6 grid gap-4 border-t px-5 pt-2 md:grid-cols-2">
<LocationSelector v-model="item.location" />
<LocationSelector v-model="item.location" @update:model-value="informAboutDesyncingLocationFromParent()" />
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Correct the event handler usage to prevent immediate function invocation.

In the template, when using event handlers like @update:model-value, you should pass the function reference without parentheses. Including () causes the function to execute immediately during render, instead of assigning it as an event handler.

Apply this diff to fix the issue:

-<LocationSelector v-model="item.location" @update:model-value="informAboutDesyncingLocationFromParent()" />
+<LocationSelector v-model="item.location" @update:model-value="informAboutDesyncingLocationFromParent" />

-<FormToggle v-model="item.syncChildItemsLocations" label="Sync child items' locations" inline @update:model-value="syncChildItemsLocations()" />
+<FormToggle v-model="item.syncChildItemsLocations" label="Sync child items' locations" inline @update:model-value="syncChildItemsLocations" />

-@update:model-value="maybeSyncWithParentLocation()"
+@update:model-value="maybeSyncWithParentLocation"

Also applies to: 595-595, 604-604

Comment on lines +488 to +490
if (error) {
toast.error("Something went wrong trying to load parent data");
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Prevent accessing undefined data after an error occurs.

After detecting an error when fetching the parent data, the function should return immediately to avoid accessing data when it might be undefined.

Apply this diff to fix the issue:

      if (error) {
        toast.error("Something went wrong trying to load parent data");
+       return;
      }

      if (data.syncChildItemsLocations) {
        toast.info("Changing location will de-sync it from the parent's location");
      }
📝 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
if (error) {
toast.error("Something went wrong trying to load parent data");
}
if (error) {
toast.error("Something went wrong trying to load parent data");
return;
}

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.

Feature Request: Ability to Move all Child Items when the Location of the Parent Item is Changed
3 participants