Skip to content

Fix undefined subcontrols #1321

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

Open
wants to merge 4 commits into
base: develop
Choose a base branch
from
Open

Conversation

HarshP4585
Copy link
Collaborator

@HarshP4585 HarshP4585 commented May 8, 2025

Describe your changes

  • Fix undefined sub-controls due to API changes
image

Write your issue number after "Fixes "

Fixes #1320

Please ensure all items are checked off before requesting a review:

  • I deployed the code locally.
  • I have performed a self-review of my code.
  • I have included the issue # in the PR.
  • I have labelled the PR correctly.
  • The issue I am working on is assigned to me.
  • I didn't use any hardcoded values (otherwise it will not scale, and will make it difficult to maintain consistency across the application).
  • I made sure font sizes, color choices etc are all referenced from the theme.
  • My PR is granular and targeted to one specific feature.
  • I took a screenshot or a video and attached to this PR if there is a UI change.

Summary by CodeRabbit

  • New Features

    • Controls in the Compliance Tracker now display detailed subcontrol information, including counts of total and completed subcontrols.
  • Bug Fixes

    • Progress metrics in project assessment and compliance responses are now consistently returned as integers.
  • Refactor

    • Improved the way control data is managed and displayed in modals for a more streamlined user experience.
    • Enhanced update functions to avoid unnecessary database queries when no changes are provided.

@HarshP4585 HarshP4585 self-assigned this May 8, 2025
@HarshP4585 HarshP4585 added bug Something isn't working frontend Frontend related tasks/issues backend Backend related tasks/issues labels May 8, 2025
Copy link
Contributor

coderabbitai bot commented May 8, 2025

Walkthrough

The changes refactor the NewControlPane component to remove internal data fetching and state management, instead relying on enriched control data passed as props. The controls table page now fetches detailed control data including subcontrol counts before rendering the modal. Server-side, helper functions and return types are updated to provide subcontrol aggregation and type consistency, and API endpoints are adjusted to accept project framework filtering.

Changes

File(s) Change Summary
Clients/src/presentation/components/Modals/Controlpane/NewControlPane.tsx Refactored to remove internal state and async data fetching; expects fully populated data prop; prop renamed from _data to data; removed projectFrameworkId prop.
Clients/src/presentation/pages/ComplianceTracker/1.0ComplianceTracker/ControlsTable.tsx Added selectedControl state; changed handleRowClick to async to fetch detailed control data by ID and project framework ID; passes fetched control as data prop to NewControlPane; removed projectFrameworkId prop.
Servers/controllers/eu.ctrl.ts Updated getControlsByControlCategoryId to accept projectFrameworkId and use new query function; added explicit parseInt() conversions for numeric fields in progress endpoints.
Servers/utils/eu.utils.ts Added getSubControlsCalculations helper; updated control queries to include subcontrol counts; added new query for project-specific control structs; improved update functions to handle empty updates and adjusted return types.

Sequence Diagram(s)

sequenceDiagram
    participant UI as ControlsTable
    participant API as API Server
    participant DB as Database

    UI->>API: Fetch controls by category ID and projectFrameworkId
    API->>DB: Query controls list with projectFrameworkId filter
    DB-->>API: Return controls
    UI->>API: On control row click, fetch detailed control by ID and projectFrameworkId
    API->>DB: Query detailed control with subcontrol counts
    DB-->>API: Return detailed control data
    API-->>UI: Return detailed control data
    UI->>UI: Pass detailed control as `data` prop to NewControlPane modal
    UI->>UI: Render modal with control details
Loading

Assessment against linked issues

Objective (Issue #) Addressed Explanation
Ensure subcontrol counts/details are defined and available for controls (#1320)

Poem

A hop and a leap through code anew,
Subcontrols now counted, their numbers in view.
No more undefined, the data flows right,
From backend to frontend, all clear in sight.
With carrots and queries, the tracker’s refined—
A rabbit’s delight in the progress we find! 🥕

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

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

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this 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.

@HarshP4585 HarshP4585 mentioned this pull request May 8, 2025
@charurajput16
Copy link
Contributor

@HarshP4585 - Thank you Harsh! This is working now.

Comment on lines 130 to 137
let _response = []
for (let control of response) {
const subControlsResponse = await getEntityById({
routeUrl: `eu-ai-act/controlById?controlId=${control.id}&projectFrameworkId=${projectFrameworkId}`,
});
_response.push({...subControlsResponse.data, ...control});
}
setControls(_response);
Copy link
Contributor

Choose a reason for hiding this comment

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

We have a few issues to address here. First, we are making multiple asynchronous requests inside a for loop, which results in sequential execution. This means that the next fetch will not start until the previous one has completed, significantly slowing down performance.

To improve this, we should create a specific endpoint that retrieves all the data from the controls and subcontrols in a single call.

Additionally, it would be beneficial to move the logic for calling the API to a dedicated hook, which we can name useControls.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

@samuel-coutinho Updated the route to get the controls by control category id and changes the UI code to only fetch the subControls if the modal is open.

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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8ce7b23 and e2f62d4.

📒 Files selected for processing (3)
  • Clients/src/presentation/pages/ComplianceTracker/1.0ComplianceTracker/ControlsTable.tsx (4 hunks)
  • Servers/controllers/eu.ctrl.ts (4 hunks)
  • Servers/utils/eu.utils.ts (6 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • Clients/src/presentation/pages/ComplianceTracker/1.0ComplianceTracker/ControlsTable.tsx
🧰 Additional context used
🧬 Code Graph Analysis (1)
Servers/utils/eu.utils.ts (3)
Servers/database/db.ts (1)
  • sequelize (82-82)
Servers/models/EU/controlEU.model.ts (1)
  • ControlEU (14-29)
Servers/models/EU/subControlEU.model.ts (1)
  • SubcontrolEU (11-27)
🔇 Additional comments (9)
Servers/controllers/eu.ctrl.ts (3)

9-9: Import statement updated to include new utility function.

The import now includes getControlStructByControlCategoryIdForAProjectQuery, which is used in the updated getControlsByControlCategoryId function. This aligns with the project-specific control querying functionality being added.


295-296: Improved type consistency with explicit integer parsing.

Converting string numbers to integers using parseInt() ensures consistent numeric types in the API response, which prevents potential type-related issues on the frontend.


316-317: Improved type consistency with explicit integer parsing.

Similar to the assessment progress endpoint, explicitly parsing string numbers to integers ensures data type consistency in the API response.

Servers/utils/eu.utils.ts (6)

125-139: Added helper function for subcontrol calculations.

This new utility function retrieves the count of total subcontrols and completed subcontrols for a given control. It properly encapsulates database query logic that's reused in multiple functions.


158-160: Enhanced control data with subcontrol counts.

The getControlByIdForProjectQuery function now augments the control data with parsed integer properties for subcontrol counts. This provides important metadata that helps the frontend display accurate progress information.


273-292: Added new function to get controls filtered by project framework.

This function retrieves controls for a specific control category and project framework, and enriches each control with subcontrol counts. The implementation correctly joins the control structure with actual control data and includes ownership information.


614-616: Improved update function to avoid empty update queries.

Adding an early return when there are no fields to update avoids running an unnecessary database query with an empty SET clause.


639-639: Updated function return type for consistency.

Changed the return type from Promise<SubcontrolEU | null> to Promise<SubcontrolEU> to match the actual behavior where the function never returns null (it returns the input object when there's nothing to update).


695-695: Fixed early return to maintain type consistency.

Changed the early return from null to subcontrol as SubcontrolEU to ensure the function always returns a SubcontrolEU object, which is consistent with the updated return type on line 639.

Comment on lines 414 to 417
const controlCategoryId = parseInt(req.params.id);
const controls = await getControlStructByControlCategoryIdQuery(controlCategoryId);
const projectFrameworkId = parseInt(req.query.projectFrameworkId as string);
const controls = await getControlStructByControlCategoryIdForAProjectQuery(controlCategoryId, projectFrameworkId);
return res.status(200).json(controls);
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

Added project framework filtering to control retrieval.

The function now accepts a projectFrameworkId query parameter and uses it to filter controls by both category and project framework. This resolves the issue where sub-controls were undefined due to missing project context.

You should add validation for the projectFrameworkId parameter to handle cases where it might be missing or invalid:

  try {
    const controlCategoryId = parseInt(req.params.id);
    const projectFrameworkId = parseInt(req.query.projectFrameworkId as string);
+   if (isNaN(projectFrameworkId)) {
+     return res.status(400).json(STATUS_CODE[400]("Invalid projectFrameworkId"));
+   }
    const controls = await getControlStructByControlCategoryIdForAProjectQuery(controlCategoryId, projectFrameworkId);
    return res.status(200).json(controls);
  } catch (error) {
📝 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
const controlCategoryId = parseInt(req.params.id);
const controls = await getControlStructByControlCategoryIdQuery(controlCategoryId);
const projectFrameworkId = parseInt(req.query.projectFrameworkId as string);
const controls = await getControlStructByControlCategoryIdForAProjectQuery(controlCategoryId, projectFrameworkId);
return res.status(200).json(controls);
try {
const controlCategoryId = parseInt(req.params.id);
const projectFrameworkId = parseInt(req.query.projectFrameworkId as string);
if (isNaN(projectFrameworkId)) {
return res.status(400).json(STATUS_CODE[400]("Invalid projectFrameworkId"));
}
const controls = await getControlStructByControlCategoryIdForAProjectQuery(
controlCategoryId,
projectFrameworkId
);
return res.status(200).json(controls);
} catch (error) {
next(error);
}

Copy link
Contributor

@samuel-coutinho samuel-coutinho left a comment

Choose a reason for hiding this comment

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

We are still making multiple calls to get the data, which is not efficient. But we will address this problem in the future.
Additionally, there seems to be a bug with the completion bar, as it does not update every time. Could you please check this?
image

@@ -125,16 +130,9 @@ const ControlsTable: React.FC<ControlsTableProps> = ({
setLoading(true);
try {
const response = await getEntityById({
routeUrl: `/eu-ai-act/controls/byControlCategoryId/${controlCategoryId}`,
routeUrl: `/eu-ai-act/controls/byControlCategoryId/${controlCategoryId}?projectFrameworkId=${projectFrameworkId}`,
Copy link
Contributor

Choose a reason for hiding this comment

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

Good work. Now we could move the logic inside this useEffect to its hook, useControls, and call it here to obtain controls.

@HarshP4585
Copy link
Collaborator Author

We are still making multiple calls to get the data, which is not efficient. But we will address this problem in the future. Additionally, there seems to be a bug with the completion bar, as it does not update every time. Could you please check this? image

Screen.Recording.2025-05-10.at.12.07.06.AM.mov

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
backend Backend related tasks/issues bug Something isn't working frontend Frontend related tasks/issues
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Undefined Subcontrols
3 participants