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] Append user_id to deploy, recall, CRU maintenance logs activities api request body #2180

Merged
merged 2 commits into from
Oct 5, 2024

Conversation

Codebmk
Copy link
Member

@Codebmk Codebmk commented Oct 5, 2024

Summary of Changes (What does this PR do?)

  • Updated device deployment, recall, maintenance log operations by including user_id.

Status of maturity (all need to be checked before merging):

  • I've tested this locally
  • I consider this code done
  • This change ready to hit production in its current state

How should this be manually tested?

  • Please include the steps to be done inorder to setup and test this PR.

What are the relevant tickets?

Screenshots (optional)

image
image

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Introduced a new environment variable for map preview functionality.
    • Enhanced device deployment and recall operations by including user identification.
    • Improved maintenance log operations with user ID tracking.
  • Bug Fixes

    • Added error handling for missing user data in local storage to prevent application crashes.
  • Style

    • Improved JSX formatting for better readability and consistency across components.

@Codebmk Codebmk requested a review from Baalmart October 5, 2024 09:15
@Codebmk Codebmk self-assigned this Oct 5, 2024
Copy link

coderabbitai bot commented Oct 5, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

The pull request includes modifications to the .env.sample file and several components within the DeviceView directory. The .env.sample file has had the REACT_APP_GOOGLE_ANALYTICS_TOKEN variable's value removed and a new variable REACT_APP_MAP_PREVIEW added. Changes in the DeviceDeployStatus.js and DeviceLogs.js components focus on incorporating a user_id field into various data objects for device deployment and maintenance log operations, enhancing user identification. Minor formatting adjustments for code readability are also present across the components.

Changes

File Path Change Summary
netmanager/.env.sample - Removed value for REACT_APP_GOOGLE_ANALYTICS_TOKEN.
- Added REACT_APP_MAP_PREVIEW.
netmanager/src/views/components/DataDisplay/DeviceView/DeviceDeployStatus.js - Added user_id field to deployData and responseData.
- Updated handleDeploySubmit and handleRecallSubmit to include user_id.
- Adjusted JSX formatting for consistency.
netmanager/src/views/components/DataDisplay/DeviceView/DeviceLogs.js - Added user_id to logData in EditLog and AddLogForm components.
- Included error handling for missing user data in local storage.
- Minor formatting adjustments for JSX elements.

Possibly related PRs

Suggested reviewers

  • Baalmart
  • OchiengPaul442

🌟 In the land of code where changes flow,
A token removed, a new one to show.
With user IDs added, logs now align,
Device deployments and formats, all refined.
In this realm of tech, clarity reigns,
As we build and enhance, embracing the gains! 🌟


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

🧹 Outside diff range and nitpick comments (5)
netmanager/.env.sample (1)

20-20: Consider providing guidance for Google Analytics setup.

The Google Analytics token has been removed from the sample environment file. This change improves security by not exposing a potentially sensitive token in version control.

However, it might be helpful to add a comment explaining how users should obtain and configure their own Google Analytics token, if it's still required for the application.

netmanager/src/views/components/DataDisplay/DeviceView/DeviceLogs.js (1)

272-273: Approved: User ID inclusion with a minor suggestion

The addition of user_id to the log data in the AddLogForm component is consistent with the PR objective and the changes made in the EditLog component. This ensures that user identification is included when creating new logs.

For consistency with the EditLog component, consider adding a similar error check:

+if (!parsedData || !parsedData._id) {
+  console.error('User ID not found. User might not be logged in.');
+  // Handle this case, perhaps by showing an error message to the user
+  return;
+}

This addition would provide better error handling and maintain consistency across components.

netmanager/src/views/components/DataDisplay/DeviceView/DeviceDeployStatus.js (3)

330-331: Approve RecallButton changes with a suggestion for user feedback.

The updates to the RecallButton component are well-implemented. The addition of a recall type selection improves the specificity of the recall process, and the dropdown implementation is space-efficient. Good job!

A minor suggestion for improvement:

Consider adding a visual indicator or tooltip to inform the user that they need to select a recall type after clicking the button. This could enhance the user experience by providing clear guidance on the next required action.

You could add a tooltip to the button like this:

 <Button
   variant="contained"
   color="primary"
   disabled={!deviceData.isActive || recallLoading}
   onClick={handleRecallClick}
+  title={selectVisible ? "Please select a recall type" : "Click to recall device"}
 >
   {recallLoading ? 'Recalling' : 'Recall Device'}
 </Button>

Also applies to: 357-358


477-478: Approve addition of user_id with suggestion for error handling.

The addition of the user_id to the deployData object is a good improvement. It allows for better tracking of who initiated the deployment. Nice work!

However, there are a couple of points to consider for robustness:

  1. The code assumes that the user data is always present in local storage. It's good practice to handle cases where it might not be.
  2. There's no specific error handling if the _id field is not found in the parsed data.

Consider adding some error checking:

const parsedData = JSON.parse(storedData);
if (!parsedData || !parsedData._id) {
  console.error('Error: Invalid user data in local storage');
  // Handle the error appropriately, maybe set a default value or show an error message
  return;
}

530-531: Consistent addition of user_id, consider error handling.

The addition of the user_id to the responseData object in the handleRecallSubmit function is consistent with the changes made in the deploy function. This consistency is good for maintaining a uniform approach to user tracking across different operations.

However, the same considerations apply here as in the deploy function:

  1. Error handling for cases where user data might not be in local storage.
  2. Checking for the presence of the _id field in the parsed data.

Consider adding similar error checking as suggested for the deploy function:

const parsedData = JSON.parse(storedData);
if (!parsedData || !parsedData._id) {
  console.error('Error: Invalid user data in local storage');
  // Handle the error appropriately, maybe set a default value or show an error message
  return;
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 5dcffaf and 0dea0c3.

📒 Files selected for processing (3)
  • netmanager/.env.sample (1 hunks)
  • netmanager/src/views/components/DataDisplay/DeviceView/DeviceDeployStatus.js (19 hunks)
  • netmanager/src/views/components/DataDisplay/DeviceView/DeviceLogs.js (6 hunks)
🔇 Additional comments (8)
netmanager/.env.sample (2)

21-21: Clarify the purpose of the new map preview variable.

A new environment variable REACT_APP_MAP_PREVIEW has been added. This suggests the introduction of a new feature or configuration option related to map previews.

Could you provide more context about this new variable? What does it control, and how should it be configured? Consider adding a brief comment in the file to explain its purpose and expected value format.


20-21: Verify alignment with PR objectives.

The changes in this file, while potentially valuable, don't seem to directly relate to the stated PR objective of appending user_id to certain API request bodies.

Can you clarify how these environment variable changes contribute to the PR's goal of modifying API requests? If they're unrelated, consider separating these changes into a different PR to maintain focus and traceability.

netmanager/src/views/components/DataDisplay/DeviceView/DeviceLogs.js (4)

218-219: Approved: Improved button spacing

The addition of left margin to the "Save Changes" button enhances the visual spacing between buttons, resulting in a more polished user interface. This is a good attention to detail.


553-554: Approved: Enhanced vertical spacing

The addition of bottom margin to the button container improves the visual separation between the buttons and the content below. This small UI adjustment contributes to a more balanced and aesthetically pleasing layout.


560-561: Approved: Improved code formatting

The onClick handlers for the buttons have been moved to separate lines, enhancing code readability without altering functionality. This change aligns with best practices for maintaining clean and easily scannable code.

Also applies to: 571-572


Line range hint 1-654: Summary: PR objectives achieved with room for minor enhancements

The changes in this file successfully implement the main objective of appending user_id to the log data for both editing and adding logs. Additionally, some UI improvements have been made to enhance the visual appeal and readability of the code.

Key points:

  1. User ID is now included in log data for both EditLog and AddLogForm components.
  2. Minor UI adjustments improve button spacing and overall layout.
  3. Code readability has been enhanced through better formatting.

Suggestions for further improvement:

  1. Implement consistent error handling for cases where user data is not available.
  2. Consider using a more secure method for storing and retrieving user data, if applicable to the broader application architecture.

Overall, the changes are positive and align well with the PR objectives. The suggested improvements are minor and could be addressed in this PR or as follow-up tasks.

🧰 Tools
🪛 Biome

[error] 93-93: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

netmanager/src/views/components/DataDisplay/DeviceView/DeviceDeployStatus.js (2)

577-578: Approve style prop changes to object syntax.

The updates to the style prop for Button components, changing from string to object syntax, are a positive improvement. This change adheres to React best practices and offers several benefits:

  1. It allows for easier addition of multiple style properties.
  2. It provides better type checking and IDE support.
  3. It's more consistent with how inline styles are typically handled in React.

The consistent application of this change across multiple Button components in the file is commendable. It improves code readability and maintainability.

Also applies to: 584-585, 592-593, 602-603, 610-611, 625-626, 646-647, 690-691, 719-720, 787-788, 799-800, 819-820, 842-843, 850-851


148-148: Verify the range for BatteryVoltage and consider adding units.

The addition of the BatteryVoltage field is a good improvement for monitoring device power status. However, the current range (0 to 100) might be misleading if it's not representing a percentage. Consider the following:

  1. Verify if the range accurately represents all possible battery voltage values.
  2. Add a unit of measurement (e.g., Volts) to the label for clarity.
  3. If it is indeed a percentage, update the label to reflect this (e.g., "Battery Voltage Percentage").

To confirm the expected range and unit for battery voltage, you can run the following command to search for any documentation or comments related to battery voltage in the codebase:

Comment on lines 94 to 105
let currentUser = JSON.parse(localStorage.getItem('currentUser'));
let userId = '';
if (currentUser) {
userId = currentUser._id;
}
const logData = {
deviceName,
locationName: deviceLocation,
date: selectedDate.toISOString(),
tags: extracted_tags,
description: description
description: description,
user_id: userId
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider enhancing user data retrieval and error handling

The addition of user_id to the log data aligns well with the PR objective. However, a few points to consider:

  1. While using localStorage for user data is common, it's not the most secure method. Consider using a more secure state management solution or server-side sessions if possible.

  2. There's no error handling if the user data is not found in localStorage. It might be beneficial to add a check and handle the case where currentUser is null or undefined.

Here's a suggestion to improve error handling:

 let currentUser = JSON.parse(localStorage.getItem('currentUser'));
-let userId = '';
-if (currentUser) {
-  userId = currentUser._id;
-}
+let userId = currentUser && currentUser._id ? currentUser._id : null;
+if (!userId) {
+  console.error('User ID not found. User might not be logged in.');
+  // Handle this case, perhaps by showing an error message to the user
+}

This change will provide better error handling and logging, which could be helpful for debugging and user experience.

📝 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
let currentUser = JSON.parse(localStorage.getItem('currentUser'));
let userId = '';
if (currentUser) {
userId = currentUser._id;
}
const logData = {
deviceName,
locationName: deviceLocation,
date: selectedDate.toISOString(),
tags: extracted_tags,
description: description
description: description,
user_id: userId
let currentUser = JSON.parse(localStorage.getItem('currentUser'));
let userId = currentUser && currentUser._id ? currentUser._id : null;
if (!userId) {
console.error('User ID not found. User might not be logged in.');
// Handle this case, perhaps by showing an error message to the user
}
const logData = {
deviceName,
locationName: deviceLocation,
date: selectedDate.toISOString(),
tags: extracted_tags,
description: description,
user_id: userId

Copy link
Contributor

github-actions bot commented Oct 5, 2024

New netmanager changes available for preview here

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

🧹 Outside diff range and nitpick comments (3)
netmanager/src/views/components/DataDisplay/DeviceView/DeviceDeployStatus.js (2)

480-484: Good addition of user_id to deployData

The inclusion of user_id in the deployData object aligns with the PR objectives. The check for the existence of parsedData._id before adding it is a good practice.

Consider adding error logging if parsedData._id is missing, as this might indicate an unexpected state:

 if (parsedData._id) {
   deployData.user_id = parsedData._id;
+} else {
+  console.warn('User ID is missing from parsed data');
 }

This will help with debugging if issues arise related to missing user IDs.


537-541: Consistent addition of user_id to responseData

The inclusion of user_id in the responseData object for the recall functionality is consistent with the changes made in the deploy functionality and aligns with the PR objectives.

As suggested for the deploy functionality, consider adding error logging here as well:

 if (parsedData._id) {
   responseData.user_id = parsedData._id;
+} else {
+  console.warn('User ID is missing from parsed data for recall operation');
 }

This will help maintain consistency in error handling across both deploy and recall operations.

netmanager/src/views/components/DataDisplay/DeviceView/DeviceLogs.js (1)

Line range hint 94-107: Consider extracting user data retrieval into a helper function

I noticed that both EditLog and AddLogForm components repeat the logic for fetching user data from local storage. To make your code more maintainable and reduce redundancy, it might be a good idea to extract this logic into a shared helper function.

Here's how you could do it:

// In a utilities file, e.g., userUtils.js
export const getUserId = () => {
  const storedData = localStorage.getItem('currentUser');
  if (!storedData) {
    console.error('Error: No user data found in local storage');
    return null;
  }
  const parsedData = JSON.parse(storedData);
  return parsedData._id || null;
};

Then, in your components:

import { getUserId } from 'path/to/userUtils';

// ...

const userId = getUserId();
if (userId) {
  logData.user_id = userId;
}
🧰 Tools
🪛 Biome

[error] 104-104: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 0dea0c3 and 348122d.

📒 Files selected for processing (2)
  • netmanager/src/views/components/DataDisplay/DeviceView/DeviceDeployStatus.js (19 hunks)
  • netmanager/src/views/components/DataDisplay/DeviceView/DeviceLogs.js (7 hunks)
🧰 Additional context used
🪛 Biome
netmanager/src/views/components/DataDisplay/DeviceView/DeviceLogs.js

[error] 104-104: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (3)
netmanager/src/views/components/DataDisplay/DeviceView/DeviceDeployStatus.js (3)

148-148: Nice addition of BatteryVoltage to sensorFeedNameMapper!

The new entry for BatteryVoltage is consistent with the existing structure and provides a reasonable range for battery voltage monitoring.


167-168: Styling improvement for EmptyDeviceTest component

The style changes to the Button component enhance consistency and maintain the component's functionality. Good attention to detail!


205-206: Consistent styling in DeviceRecentFeedView component

The style adjustments in the DeviceRecentFeedView component enhance code readability and maintain consistent styling throughout the component. These changes are purely cosmetic and don't affect functionality.

Also applies to: 212-213, 236-237, 277-278

@@ -265,6 +272,11 @@ const AddLogForm = ({ deviceName, deviceLocation, toggleShow, loading, setLoadin
lastName: parsedData.lastName
};

// Add user_id only if it exists
if (parsedData._id) {
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Simplify condition with optional chaining

Similarly, you can simplify if (parsedData._id) to enhance readability:

Apply this diff:

-if (parsedData._id) {
+if (parsedData?._id) {
📝 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 (parsedData._id) {
if (parsedData?._id) {

@@ -99,6 +100,11 @@
description: description
};

// Add user_id only if it exists
if (currentUser && currentUser._id) {
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Simplify condition with optional chaining

You can streamline the condition if (currentUser && currentUser._id) by using optional chaining. It makes the code cleaner and more readable.

Apply this diff:

-if (currentUser && currentUser._id) {
+if (currentUser?._id) {
📝 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 (currentUser && currentUser._id) {
if (currentUser?._id) {
🧰 Tools
🪛 Biome

[error] 104-104: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

Copy link
Contributor

github-actions bot commented Oct 5, 2024

New netmanager changes available for preview here

@Baalmart Baalmart merged commit d7da525 into staging Oct 5, 2024
29 checks passed
@Baalmart Baalmart deleted the ft-append-userid-device-activities branch October 5, 2024 09:56
@Baalmart Baalmart mentioned this pull request Oct 5, 2024
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