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

[Netmanager] Added serial number field to create device and soft create device, fix network bug #2435

Merged
merged 1 commit into from
Feb 4, 2025

Conversation

Codebmk
Copy link
Member

@Codebmk Codebmk commented Feb 4, 2025

This pull request introduces several changes to the CreateDevice and SoftCreateDevice components in the netmanager project to include a new "serial number" field and improve the handling of device data. Additionally, it modifies the Main layout to handle the active network more robustly. The most important changes are detailed below:

Enhancements to Device Creation Forms:

  • Added a new serial_number field to the newDeviceInitState and initialErrors objects in both CreateDevice and SoftCreateDevice components. (netmanager/src/views/components/DataDisplay/Devices.js) [1] [2]
  • Updated the handleDeviceDataChange function to include validation for the serial_number field. (netmanager/src/views/components/DataDisplay/Devices.js) [1] [2]
  • Modified the form reset logic to include the serial_number field. (netmanager/src/views/components/DataDisplay/Devices.js) [1] [2]
  • Enhanced the form validation logic to check for non-empty serial_number. (netmanager/src/views/components/DataDisplay/Devices.js) [1] [2]
  • Added the serial_number field to the form UI in both CreateDevice and SoftCreateDevice components. (netmanager/src/views/components/DataDisplay/Devices.js) [1] [2]

Improvements to Device Data Handling:

  • Created a copy of newDevice and removed fields with empty values before sending the data to the server in both CreateDevice and SoftCreateDevice components. (netmanager/src/views/components/DataDisplay/Devices.js) [1] [2]
  • Updated the network handling logic to use network.net_name instead of network. (netmanager/src/views/components/DataDisplay/Devices.js) [1] [2]

Enhancements to Active Network Handling:

  • Modified the Main layout to retrieve the active network from local storage if it is not already set, ensuring the user's role is correctly assigned. (netmanager/src/views/layouts/Main.js)

image
image

Summary by CodeRabbit

  • New Features

    • Introduced a required "Serial Number" field on device registration forms, complete with validation and error feedback to ensure proper input.
  • Refactor

    • Enhanced the application's initialization flow to correctly manage active network settings and user roles, improving overall configuration accuracy.

@Codebmk Codebmk requested a review from Baalmart February 4, 2025 05:34
@Codebmk Codebmk self-assigned this Feb 4, 2025
Copy link

coderabbitai bot commented Feb 4, 2025

📝 Walkthrough

Walkthrough

This pull request introduces a new required field, serial_number, to the device registration forms in the Devices component. The new field is added in the initial device state, validated during data changes, and cleared on dialog close. Additionally, the device submission process now omits empty fields before making an API call. In parallel, the Main layout file updates the control flow in a useEffect hook to check if the activeNetwork is empty, and accordingly retrieves data from local storage or dispatches a current user role action.

Changes

File(s) Change Summary
netmanager/src/views/components/DataDisplay/Devices.js - Added serial_number to initial device state in CreateDevice and SoftCreateDevice components.
- Implemented validation and error handling for serial_number in form submission.
- Updated API call logic to remove empty fields before sending data.
- Modified network mapping to use network.net_name.
netmanager/src/views/layouts/Main.js - Inverted the logic in the second useEffect hook to check if activeNetwork is empty.
- Retrieves activeNetwork from local storage when empty and dispatches addActiveNetwork.
- Dispatches addCurrentUserRole and updates local storage when activeNetwork is not empty.

Sequence Diagram(s)

sequenceDiagram
    participant U as User
    participant D as Devices Component
    participant API as Server API

    U->>D: Open device registration form
    D->>D: Initialize new device state (including serial_number)
    U->>D: Enter device details (with serial_number)
    D->>D: Validate serial_number and other data
    alt Valid Form
        U->>D: Submit form
        D->>D: Copy and clean device data (remove empty fields)
        D->>API: API call to register device
        API-->>D: Return registration response
    else Invalid Form
        D->>U: Display error for missing serial_number
    end
Loading
sequenceDiagram
    participant M as Main Component
    participant LS as Local Storage
    participant Dispatcher as Store Actions

    M->>M: Check activeNetwork value
    alt activeNetwork is empty
        M->>LS: Retrieve activeNetwork data
        LS-->>M: Return activeNetwork
        M->>Dispatcher: Dispatch addActiveNetwork with parsed data
    else activeNetwork is present
        M->>Dispatcher: Dispatch addCurrentUserRole
        M->>LS: Update localStorage with current user role
    end
Loading

Suggested reviewers

  • OchiengPaul442
  • Baalmart

Poem

In the realm of code so keen,
A new serial joins the scene.
Forms now check with careful grace,
Leaving errors no longer a race.
Networks set, roles anew,
Our changes shine, crisp and true.
Cheers to progress in every queue!

Tip

🌐 Web search-backed reviews and chat
  • We have enabled web search-based reviews and chat for all users. This feature allows CodeRabbit to access the latest documentation and information on the web.
  • You can disable this feature by setting web_search: false in the knowledge_base settings.
  • Please share any feedback in the Discord discussion.
✨ 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 or @coderabbitai title 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

@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 (2)
netmanager/src/views/layouts/Main.js (1)

138-148: Consider potential race conditions in useEffect dependencies.

The useEffect hook's dependency array is missing dispatch, which could lead to stale closures. Additionally, the localStorage operations could be moved outside the effect to optimize performance.

Consider this refactoring:

+ const activeNetworkStorage = localStorage.getItem('activeNetwork');
+ const parsedActiveNetwork = activeNetworkStorage ? JSON.parse(activeNetworkStorage) : null;

  useEffect(() => {
    if (isEmpty(activeNetwork)) {
-     const activeNetworkStorage = localStorage.getItem('activeNetwork');
-     if (activeNetworkStorage) {
-       dispatch(addActiveNetwork(JSON.parse(activeNetworkStorage)));
+     if (parsedActiveNetwork) {
+       dispatch(addActiveNetwork(parsedActiveNetwork));
      }
    } else {
      dispatch(addCurrentUserRole(activeNetwork.role));
      localStorage.setItem('currentUserRole', JSON.stringify(activeNetwork.role));
    }
- }, [activeNetwork]);
+ }, [activeNetwork, dispatch, parsedActiveNetwork]);
netmanager/src/views/components/DataDisplay/Devices.js (1)

341-347: Consider enhancing serial number validation.

While the basic validation is in place, consider adding format validation for the serial number to ensure it matches your expected pattern.

 const isFormValid = () => {
+  const isValidSerialFormat = /^[A-Za-z0-9-]+$/.test(newDevice.serial_number.trim());
   return (
     newDevice.long_name.trim() !== '' &&
     newDevice.category !== '' &&
-    newDevice.serial_number.trim() !== ''
+    newDevice.serial_number.trim() !== '' &&
+    isValidSerialFormat
   );
 };

Also applies to: 616-622

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 35ca1d0 and c0c8b8c.

📒 Files selected for processing (2)
  • netmanager/src/views/components/DataDisplay/Devices.js (14 hunks)
  • netmanager/src/views/layouts/Main.js (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: netmanager code tests
  • GitHub Check: build-push-deploy-netmanager-preview
🔇 Additional comments (5)
netmanager/src/views/layouts/Main.js (2)

150-164: LGTM! Good use of loading states.

The loading state handling is well-implemented, showing a centered loader while essential data (activeNetwork, currentRole) is being initialized.


118-130: LGTM! Comprehensive error handling.

Good implementation of error handling with appropriate user feedback through MainAlert. The distinction between server errors (status >= 500) and other errors provides clear messaging.

netmanager/src/views/components/DataDisplay/Devices.js (3)

280-280: LGTM! Network reference update is consistent.

The change from network to network.net_name is applied consistently across both device creation components.

Also applies to: 534-535, 597-598, 662-663


467-477: LGTM! Serial number field implementation is complete.

The serial number field is properly implemented with:

  • Required field validation
  • Error handling
  • Consistent placement in both device creation forms

Also applies to: 739-749


367-375: LGTM! Clean implementation of empty field removal.

The implementation efficiently removes empty fields before API calls, reducing payload size and maintaining data cleanliness.

Also applies to: 644-649

Copy link
Contributor

github-actions bot commented Feb 4, 2025

New netmanager changes available for preview here

Copy link
Collaborator

@Baalmart Baalmart left a comment

Choose a reason for hiding this comment

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

Thanks @Codebmk !

@Baalmart Baalmart merged commit a4656ec into staging Feb 4, 2025
31 checks passed
@Baalmart Baalmart deleted the hotifx-device-reg branch February 4, 2025 05:58
@Baalmart Baalmart mentioned this pull request Feb 4, 2025
1 task
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants