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

32 dec 08 data validation in compliance #334

Open
wants to merge 2 commits into
base: master
Choose a base branch
from

Conversation

melpsh
Copy link
Contributor

@melpsh melpsh commented Dec 11, 2024

Added Validation to compliance tracker inputs

image

Summary by CodeRabbit

  • New Features

    • Enhanced dropdown component with user data fetching and validation.
    • Added validation and error handling to select components.
    • Improved modal functionality for managing tab selections and dynamic content display.
  • Bug Fixes

    • Addressed error handling and user feedback in dropdown and select components.
  • Documentation

    • Updated interfaces to reflect new properties and methods in dropdown and select components.

Copy link

coderabbitai bot commented Dec 11, 2024

Walkthrough

The pull request introduces significant enhancements to several components, including the DropDowns, Select, and CustomModal. The DropDowns component now fetches user data from an API and incorporates validation for user selection, while the Select component has been updated to support new props for validation and error handling. The CustomModal component has undergone structural changes to simplify state management and maintain its interactive features. Overall, these changes improve type safety, user interaction, and validation across the components.

Changes

File Path Change Summary
Clients/src/presentation/components/Inputs/Dropdowns/index.tsx Added User and ValidationError interfaces; implemented user data fetching and validation logic; updated change handlers.
Clients/src/presentation/components/Inputs/Select/index.tsx Modified SelectProps to include new props (getOptionValue, required, helperText); updated error handling logic.
Clients/src/presentation/components/Modals/Controlpane/index.tsx Removed subControlNumber; retained commented-out handleSave; updated state management for active sections.

Possibly related PRs

  • Implemented ComplianceTracker Page- first section #19: The changes in the main PR regarding the DropDowns component's user data fetching and validation may relate to the ComplianceTracker page's implementation, as both involve user interaction and data management within forms.
  • 002 sep 20 vendor view design #20: The modifications in the Select component's props and validation logic could be relevant to the vendor management interface enhancements, as both involve dropdown selections and user input validation.
  • file upload component with Uppy #306: The introduction of the FileUploadComponent may relate to the main PR's focus on user interaction and validation, as both aim to enhance user experience through improved component functionality.

Suggested labels

enhancement, frontend

Suggested reviewers

  • MuhammadKhalilzadeh
  • popovaevgeniya

🐇 In the meadow where options bloom,
A dropdown dances, dispelling gloom.
With users fetched and errors checked,
Our forms now shine, all well-respected.
So hop along, let's validate,
In this code, we celebrate! 🎉


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

@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)
Clients/src/presentation/components/Inputs/Dropdowns/index.tsx (3)

52-52: Remove unnecessary console.log statement

The console.log on line 52 seems to be a leftover from debugging and should be removed to clean up the console output.

Apply this diff to remove it:

- console.log("🚀 ~ DropDowns ~ usersssssssssss:", users)

54-61: Rename handleChange to handleApproverChange for clarity

For consistency with other handler functions (handleOwnerChange, handleReviewerChange), consider renaming handleChange to handleApproverChange.

Apply this diff to rename the function:

- const handleChange = (e: SelectChangeEvent<string | number>) => {
+ const handleApproverChange = (e: SelectChangeEvent<string | number>) => {
    const selectedValue = e.target.value;
    console.log("Selected value:", selectedValue);
    const selectedUser = users.find(user => user.id === selectedValue);
    console.log("Selected user:", selectedUser);
    setApprover(selectedValue);
  };

  // Update the onChange prop in the Approver Select component
  <Select
    id="Approver"
    label="Approver:"
    value={approver || ""}
-   onChange={handleChange}
+   onChange={handleApproverChange}
    required
    items={users.map(user => ({ 
      _id: user.id,
      name: user.name 
    }))}
    sx={inputStyles}
  />

160-163: Refactor user mapping to avoid code duplication

The mapping of users to the items array is repeated for the Approver, Owner, and Reviewer selects. Consider extracting this mapping into a constant or function to adhere to the DRY (Don't Repeat Yourself) principle.

Apply this diff to create a reusable userItems array:

// After fetching and setting users
setUsers(response.data);
+ // Create a reusable array for user items
+ const userItems = users.map(user => ({
+   _id: user.id,
+   name: user.name,
+ }));

// In the Approver Select component
<Select
  id="Approver"
  label="Approver:"
  value={approver || ""}
  onChange={handleApproverChange}
  required
- items={users.map(user => ({ 
-   _id: user.id,
-   name: user.name 
- }))}
+ items={userItems}
  sx={inputStyles}
/>

// In the Owner Select component
<Select
  id="Owner"
  label="Owner:"
  value={owner || ""}
  onChange={handleOwnerChange}
  required
- items={users.map(user => ({ 
-   _id: user.id,
-   name: user.name 
- }))}
+ items={userItems}
  sx={inputStyles}
  error={ownerError.hasError}
  helperText={ownerError.message}
/>

// In the Reviewer Select component
<Select
  id="Reviewer"
  label="Reviewer:"
  value={reviewer || ""}
  onChange={handleReviewerChange}
  required
- items={users.map(user => ({ 
-   _id: user.id,
-   name: user.name 
- }))}
+ items={userItems}
  sx={inputStyles}
  error={reviewerError.hasError}
  helperText={reviewerError.message}
/>

Also applies to: 193-195, 205-207

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 11c4958 and a04ac67.

📒 Files selected for processing (3)
  • Clients/src/presentation/components/Inputs/Dropdowns/index.tsx (4 hunks)
  • Clients/src/presentation/components/Inputs/Select/index.tsx (8 hunks)
  • Clients/src/presentation/components/Modals/Controlpane/index.tsx (0 hunks)
💤 Files with no reviewable changes (1)
  • Clients/src/presentation/components/Modals/Controlpane/index.tsx

Comment on lines +45 to +51
useEffect(() => {
const fetchUsers = async () => {
const response = await getAllEntities({ routeUrl: "/users" });
setUsers(response.data);
};
fetchUsers();
}, []);
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add error handling for fetching user data

Currently, if the API call to fetch users fails, the component doesn't handle the error, which may lead to unexpected behavior or application crash. Consider adding error handling to manage API failures gracefully.

Apply this diff to handle errors:

const fetchUsers = async () => {
  try {
    const response = await getAllEntities({ routeUrl: "/users" });
    setUsers(response.data);
+ } catch (error) {
+   // Handle the error appropriately
+   console.error("Failed to fetch users:", error);
+   // Optionally, set an error state or display a message to the user
+ }
};

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +39 to +40
error?: boolean | string;
helperText?: string;
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Ensure error prop is consistently a boolean

The error prop is currently typed as boolean | string, which may lead to unexpected behavior since MuiSelect expects a boolean value for the error prop. Passing a string may cause the error prop to always evaluate to true. Consider changing the type of error to boolean and adjust the error handling logic accordingly.

Apply this diff to correct the error prop type and usage:

interface SelectProps {
  id: string;
  label?: string;
  placeholder?: string;
  isHidden?: boolean;
  value: string | number;
  items: { _id: string | number; name: string; email?: string }[];
  isRequired?: boolean;
- error?: boolean | string;
+ error?: boolean;
  helperText?: string;
  onChange: (
    event: SelectChangeEvent<string | number>,
    child: React.ReactNode
  ) => void;
  sx?: object;
  getOptionValue?: (item: any) => any;
  required?: boolean;
}

...

const Select: React.FC<SelectProps> = ({
  // ...other props
  error,
  // ...other props
}) => {
  // ...other code
- const isEmpty = required && (!value || value === "");
- const errorMessage = isEmpty ? "This field is required" : helperText;
+ const showError = error || (required && (!value || value === ""));
+ const errorMessage = showError ? helperText || "This field is required" : "";

  return (
    // ...other code
    <MuiSelect
      // ...other props
-     error={isEmpty || error}
+     error={showError}
      // ...other props
    >
    // ...other code
    </MuiSelect>
    {errorMessage && (
      <Typography
        component="span"
        className="input-error"
        color={theme.palette.status.error.text}
        mt={theme.spacing(2)}
        sx={{
          opacity: 0.8,
          fontSize: 11,
        }}
      >
        {errorMessage}
      </Typography>
    )}
  );
};

Also applies to: 73-75, 159-159

@gorkem-bwl
Copy link
Contributor

Looks good. !

@MuhammadKhalilzadeh
Copy link
Collaborator

Hello @melpsh

Thank you for the nice code 🙏🏻
You're pull request contains conflicts with the master branch.

After that, we will move to the code review

Regards

@melpsh melpsh self-assigned this Dec 12, 2024
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.

3 participants