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

Feat/006 jan 19 create use project risks #496

Conversation

samuel-coutinho
Copy link
Contributor

@samuel-coutinho samuel-coutinho commented Jan 20, 2025

Describe your changes

  • Create useProjectRisks to fetch the project risks data and calculate the projectRisksSummary
  • Use useProjectRisks in Risks, ProjectView, Overview components.

Issue number

#392

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.

Screenshot

image

Summary by CodeRabbit

  • New Features

    • Introduced a new custom hook useProjectRisks to fetch and manage project risks data
    • Enhanced project view with dynamic risk data fetching and summary generation
  • Bug Fixes

    • Improved error handling and loading states for project risks retrieval
  • Refactor

    • Updated import paths and data structures for risk-related components
    • Modified project view component to use new risk data fetching mechanism

@samuel-coutinho samuel-coutinho added the frontend Frontend related tasks/issues label Jan 20, 2025
@samuel-coutinho samuel-coutinho added this to the 1.0 milestone Jan 20, 2025
@samuel-coutinho samuel-coutinho self-assigned this Jan 20, 2025
Copy link
Contributor

coderabbitai bot commented Jan 20, 2025

Walkthrough

This pull request introduces a new custom hook useProjectRisks for managing project risks data. The changes span multiple files in the project, focusing on enhancing risk data fetching, state management, and component rendering. The modifications include updating import paths, modifying component props, and implementing a new hook to dynamically fetch and categorize project risks based on project ID.

Changes

File Change Summary
Clients/src/application/hooks/useProjectRisks.tsx New custom hook added to fetch and manage project risks data with state management and risk level summarization
Clients/src/presentation/components/Risks/index.tsx Updated import path for RiskData type
Clients/src/presentation/pages/ProjectView/Overview/index.tsx Modified OverviewProps interface, updated component props and data sourcing
Clients/src/presentation/pages/ProjectView/RisksView/index.tsx Minor UI and formatting adjustments
Clients/src/presentation/pages/ProjectView/index.tsx Added useProjectRisks hook, updated project risk data fetching and rendering

Sequence Diagram

sequenceDiagram
    participant Component
    participant useProjectRisks
    participant API
    
    Component->>useProjectRisks: Initialize with projectId
    useProjectRisks->>API: Fetch project risks
    API-->>useProjectRisks: Return risks data
    useProjectRisks->>useProjectRisks: Categorize risks
    useProjectRisks-->>Component: Return risks data, loading state, error
Loading

Possibly related PRs

Suggested labels

backend

Suggested reviewers

  • MuhammadKhalilzadeh
  • gorkem-bwl

Poem

🐰 Risks, risks, hopping through the code,
A custom hook, a data load!
Fetching risks with bunny might,
Categorizing levels just right.
Project insights, clear and bright! 🚀


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

🧹 Nitpick comments (6)
Clients/src/application/hooks/useProjectRisks.tsx (2)

15-42: Consider using more specific types for certain fields.

The interface uses string type for fields that could benefit from more specific types:

  • Date fields like deadline and date_of_assessment could use Date
  • Boolean fields like risk_approval could use boolean
  • Numeric fields like project_id could use number
export interface ProjectRisk {
  id: number;
  project_id: number;
  risk_name: string;
  risk_owner: string;
  ai_lifecycle_phase: string;
  risk_description: string;
  risk_category: string;
  impact: string;
  assessment_mapping: string;
  controls_mapping: string;
  likelihood: string;
  severity: string;
  risk_level_autocalculated: string;
  review_notes: string;
  mitigation_status: string;
  current_risk_level: string;
-  deadline: string;
+  deadline: Date;
  mitigation_plan: string;
  implementation_strategy: string;
  mitigation_evidence_document: string;
  likelihood_mitigation: string;
  risk_severity: string;
  final_risk_level: string;
-  risk_approval: string;
+  risk_approval: boolean;
  approval_status: string;
-  date_of_assessment: string;
+  date_of_assessment: Date;
}

95-101: Add explicit return type for better type safety.

Define an interface for the hook's return type to ensure consistent usage across components.

+interface UseProjectRisksReturn {
+  projectRisks: ProjectRisk[];
+  loadingProjectRisks: boolean;
+  error: string | boolean;
+  projectRisksSummary: RiskData;
+}

-const useProjectRisks = ({ id }: { id?: number }) => {
+const useProjectRisks = ({ id }: { id?: number }): UseProjectRisksReturn => {
Clients/src/presentation/pages/ProjectView/index.tsx (2)

16-20: Consider using nullish coalescing for projectId.

The current implementation uses logical OR which could ignore valid project ID "0".

-const projectId = searchParams.get("projectId") || "1"
+const projectId = searchParams.get("projectId") ?? "1"

37-42: Improve loading and error states UI.

Consider using a proper loading spinner and error component for better user experience.

-return <Typography>Loading project risks...</Typography>;
+return <CircularProgress sx={{ m: 2 }} />;

-return <Typography>Error fetching project risks. {errorFetchingProjectRisks}</Typography>;
+return (
+  <Alert severity="error" sx={{ m: 2 }}>
+    Error fetching project risks: {errorFetchingProjectRisks}
+  </Alert>
+);
Clients/src/presentation/pages/ProjectView/Overview/index.tsx (2)

12-18: Consider moving RiskData type to a shared types file.

The RiskData type is used across multiple components and should be in a shared location.

Consider moving it to src/types/risk.types.ts.


30-30: Destructure only required props.

The component only uses projectRisksSummary but destructures vendorRisks as well.

-const Overview: FC<OverviewProps> = memo(({ projectRisksSummary }) => {
+const Overview: FC<OverviewProps> = memo(({ projectRisksSummary, vendorRisks }) => {

Also applies to: 147-147

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 95ac9f6 and 492aab5.

📒 Files selected for processing (5)
  • Clients/src/application/hooks/useProjectRisks.tsx (1 hunks)
  • Clients/src/presentation/components/Risks/index.tsx (1 hunks)
  • Clients/src/presentation/pages/ProjectView/Overview/index.tsx (4 hunks)
  • Clients/src/presentation/pages/ProjectView/RisksView/index.tsx (2 hunks)
  • Clients/src/presentation/pages/ProjectView/index.tsx (5 hunks)
🔇 Additional comments (3)
Clients/src/presentation/pages/ProjectView/RisksView/index.tsx (1)

96-98: LGTM!

The reformatting of handleOpenOrClose maintains the same functionality while improving code consistency.

Clients/src/presentation/pages/ProjectView/index.tsx (1)

63-65: Verify empty array for vendorRisks.

The Overview component receives an empty array for vendorRisks while the actual vendorRisks data is available in the project prop.

✅ Verification successful

Empty array for vendorRisks is correct

The Overview component expects an array of individual risks (RiskData[]), while the vendorRisks from project prop is a summary object containing aggregated statistics (veryHighRisks, highRisks, etc.). These serve different purposes in the UI, so passing an empty array is appropriate in this case.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if vendorRisks is used elsewhere in the codebase
rg -A 5 "vendorRisks" 

Length of output: 13941

Clients/src/presentation/components/Risks/index.tsx (1)

4-4: LGTM!

The import path update is correct and aligns with the new location of the RiskData type.

@@ -167,7 +167,7 @@ const RisksView: FC<RisksViewProps> = memo(
data={tableData}
table="risksTable"
paginated
label={`${title} risks`}
label={`${title} risk`}
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

Keep consistent pluralization in labels.

The label has been changed to singular form (${title} risk), but this creates inconsistency with:

  1. The title above the table which uses plural form ({title} risks)
  2. The table's content which displays multiple risks
-          label={`${title} risk`}
+          label={`${title} risks`}
📝 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
label={`${title} risk`}
label={`${title} risks`}

Comment on lines +81 to +93
const projectRisksSummary = projectRisks.reduce((acc, risk) => {
const riskLevel = risk.current_risk_level.charAt(0).toLowerCase() + risk.current_risk_level.slice(1);
const key = `${riskLevel.replace(/\s/g, '')}Risks` as keyof typeof acc;
acc[key] = acc[key] + 1;

return acc;
}, {
veryHighRisks: 0,
highRisks: 0,
mediumRisks: 0,
lowRisks: 0,
veryLowRisks: 0,
});
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

Add validation for risk levels and use an enum for type safety.

The current implementation assumes risk levels will always match expected values. Consider using an enum and validation to make this more robust.

+enum RiskLevel {
+  VeryHigh = 'Very High',
+  High = 'High',
+  Medium = 'Medium',
+  Low = 'Low',
+  VeryLow = 'Very Low'
+}

+const isValidRiskLevel = (level: string): level is RiskLevel => {
+  return Object.values(RiskLevel).includes(level as RiskLevel);
+}

 const projectRisksSummary = projectRisks.reduce((acc, risk) => {
-  const riskLevel = risk.current_risk_level.charAt(0).toLowerCase() + risk.current_risk_level.slice(1);
-  const key = `${riskLevel.replace(/\s/g, '')}Risks` as keyof typeof acc;
+  if (!isValidRiskLevel(risk.current_risk_level)) {
+    console.warn(`Invalid risk level: ${risk.current_risk_level}`);
+    return acc;
+  }
+  const key = `${risk.current_risk_level.replace(/\s/g, '').toLowerCase()}Risks` as keyof typeof acc;
   acc[key] = acc[key] + 1;
   return acc;
 }, {

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

Comment on lines +45 to +79
const useProjectRisks = ({ id }: { id?: number }) => {
const [projectRisks, setProjectRisks] = useState<ProjectRisk[]>([]);
const [loadingProjectRisks, setLoadingProjectRisks] = useState<boolean>(true);
const [error, setError] = useState<string | boolean>(false);

useEffect(() => {
const controller = new AbortController();
const signal = controller.signal;
const routeUrl = id ? `/projectRisks/${id}` : '/projectRisks'

const updateProjectRisks = async () => {
setLoadingProjectRisks(true);
try {
const response = await getEntityById({
routeUrl,
signal,
})
if(response.data) {
setProjectRisks(Array.isArray(response.data) ? response.data : [response.data])
}
} catch (err) {
if (err instanceof Error){
setError(`Request failed: ${err.message}`)
} else {
setError(`Request failed`)
}
} finally {
setLoadingProjectRisks(false)
}
}
updateProjectRisks();
return () => {
controller.abort();
};
}, [id])
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

Improve error handling and type safety.

Consider the following improvements:

  1. Add type validation for the API response
  2. Handle network errors specifically
  3. Add retry logic for transient failures
 const updateProjectRisks = async () => {
   setLoadingProjectRisks(true);
   try {
     const response = await getEntityById({
       routeUrl,
       signal,
     })
-    if(response.data) {
+    if (!response.data) {
+      throw new Error('No data received from API');
+    }
+    // Validate response type
+    if (!Array.isArray(response.data) && typeof response.data !== 'object') {
+      throw new Error('Invalid response format');
+    }
     setProjectRisks(Array.isArray(response.data) ? response.data : [response.data])
-    }
   } catch (err) {
+    // Handle network errors
+    if (err instanceof TypeError && err.message === 'Failed to fetch') {
+      setError('Network error: Please check your connection');
+      return;
+    }
     if (err instanceof Error){
       setError(`Request failed: ${err.message}`)
     } else {
       setError(`Request failed`)
     }
   } finally {
     setLoadingProjectRisks(false)
   }
 }
📝 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 useProjectRisks = ({ id }: { id?: number }) => {
const [projectRisks, setProjectRisks] = useState<ProjectRisk[]>([]);
const [loadingProjectRisks, setLoadingProjectRisks] = useState<boolean>(true);
const [error, setError] = useState<string | boolean>(false);
useEffect(() => {
const controller = new AbortController();
const signal = controller.signal;
const routeUrl = id ? `/projectRisks/${id}` : '/projectRisks'
const updateProjectRisks = async () => {
setLoadingProjectRisks(true);
try {
const response = await getEntityById({
routeUrl,
signal,
})
if(response.data) {
setProjectRisks(Array.isArray(response.data) ? response.data : [response.data])
}
} catch (err) {
if (err instanceof Error){
setError(`Request failed: ${err.message}`)
} else {
setError(`Request failed`)
}
} finally {
setLoadingProjectRisks(false)
}
}
updateProjectRisks();
return () => {
controller.abort();
};
}, [id])
const useProjectRisks = ({ id }: { id?: number }) => {
const [projectRisks, setProjectRisks] = useState<ProjectRisk[]>([]);
const [loadingProjectRisks, setLoadingProjectRisks] = useState<boolean>(true);
const [error, setError] = useState<string | boolean>(false);
useEffect(() => {
const controller = new AbortController();
const signal = controller.signal;
const routeUrl = id ? `/projectRisks/${id}` : '/projectRisks'
const updateProjectRisks = async () => {
setLoadingProjectRisks(true);
try {
const response = await getEntityById({
routeUrl,
signal,
})
if (!response.data) {
throw new Error('No data received from API');
}
// Validate response type
if (!Array.isArray(response.data) && typeof response.data !== 'object') {
throw new Error('Invalid response format');
}
setProjectRisks(Array.isArray(response.data) ? response.data : [response.data])
} catch (err) {
// Handle network errors
if (err instanceof TypeError && err.message === 'Failed to fetch') {
setError('Network error: Please check your connection');
return;
}
if (err instanceof Error){
setError(`Request failed: ${err.message}`)
} else {
setError(`Request failed`)
}
} finally {
setLoadingProjectRisks(false)
}
}
updateProjectRisks();
return () => {
controller.abort();
};
}, [id])

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
frontend Frontend related tasks/issues
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants