Skip to content

leader component refactor #1448

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

Draft
wants to merge 6 commits into
base: main
Choose a base branch
from

Conversation

yashgoyal0110
Copy link
Contributor

@yashgoyal0110 yashgoyal0110 commented Apr 30, 2025

fixes: #1431

Copy link
Contributor

coderabbitai bot commented Apr 30, 2025

Summary by CodeRabbit

  • New Features
    • Introduced project leaders functionality, allowing multiple users to be associated as leaders of a project.
    • Added a new component to display project leaders with detailed user information in the UI.
  • Improvements
    • Consolidated leader display logic for a more streamlined and maintainable user experience.
  • Bug Fixes
    • Improved handling of leader data fetching and display, reducing redundant queries and potential errors.
      """

Summary by CodeRabbit

  • New Features

    • Introduced a new ProjectLeaders component to display project leaders with detailed user information in a visually organized card format.
  • Refactor

    • Simplified the leaders section on the About page by replacing multiple individual leader components with the new ProjectLeaders component.
    • Updated card detail pages to extract and display leader information using the ProjectLeaders component.
  • Bug Fixes

    • Improved handling of leader data by restructuring how leader information is fetched and displayed.
  • Chores

    • Enhanced GraphQL queries to retrieve more detailed leader data.

Walkthrough

This update introduces a new ProjectLeaders component to centralize and streamline the display of project leader information. The previous approach, which involved rendering multiple LeaderData components and related logic directly within the about page, has been replaced by this new component. The ProjectLeaders component is now used in both the about page and the CardDetailsPage component, with leader data passed as props. Supporting changes include the removal of now-unnecessary imports and components, as well as an update to a GraphQL query to fetch leader login information as an object. Additionally, a debugging useEffect was added to the project page to log project state changes.

Changes

Files/Paths Change Summary
frontend/src/app/about/page.tsx Removed the LeaderData component and related imports. Replaced the previous leaders section with a single ProjectLeaders component, passing the leaders object as a prop.
frontend/src/components/CardDetailsPage.tsx Imported and integrated the ProjectLeaders component. Added logic to extract and process leader information from the details prop, and render ProjectLeaders when leader data is present.
frontend/src/components/ProjectLeaders.tsx Introduced a new ProjectLeaders component that displays a list of leaders using user data fetched via GraphQL. Includes internal LeaderData component, TypeScript interfaces, and logic for rendering user cards and handling loading/error states.
frontend/src/server/queries/projectQueries.ts Modified the GET_PROJECT_DATA GraphQL query to request the leaders field as an object with the login property for each leader, instead of a scalar or unspecified type.
frontend/src/app/projects/[projectKey]/page.tsx Added a useEffect hook to log the current project state to the console whenever it changes. No changes to exported entities or rendering logic.
backend/apps/owasp/graphql/nodes/project.py Added a new GraphQL field leaders to the ProjectNode class, typed as a list of UserNode objects. Included a commented-out resolver stub for leaders.
backend/apps/owasp/migrations/0032_project_leaders.py Added a migration to create a new ManyToManyField leaders on the project model linking to the user model, allowing multiple leaders per project.
backend/apps/owasp/models/project.py Added a new ManyToManyField leaders to the Project model referencing the User model, with related name led_projects and allowing blank values.

Assessment against linked issues

Objective Addressed Explanation
Extract leader display code into a reusable component and use it on the About page (Issue #1431)
Add a Leaders block on chapters/projects detail pages above Top Contributors (Issue #1431)
Maintain the existing layout and presentation style of leaders on the About page (Issue #1431)

Suggested labels

backend, frontend

Suggested reviewers

  • kasya
  • arkid15r
    """

📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a2acb3f and d10116f.

📒 Files selected for processing (1)
  • backend/apps/owasp/models/project.py (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • backend/apps/owasp/models/project.py
✨ 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.

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.

@yashgoyal0110 yashgoyal0110 marked this pull request as draft April 30, 2025 17:43
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: 2

🔭 Outside diff range comments (1)
frontend/src/app/projects/[projectKey]/page.tsx (1)

59-59: 💡 Verification agent

🧩 Analysis chain

Potential inconsistency with leaders data format

Line 59 is treating project.leaders as an array with a .join() method, but the GraphQL query in projectQueries.ts now returns leaders as objects with a login property. This might cause runtime errors.

- { label: 'Leaders', value: project.leaders.join(', ') },
+ { label: 'Leaders', value: project.leaders.map(leader => leader.login).join(', ') },

Let's verify this with a script:


🏁 Script executed:

#!/bin/bash
# Check how leaders are used in the codebase
rg "project\.leaders" --type ts --type tsx

Length of output: 72


Let's search more broadly without relying on file-type filters and inspect both the page and the GraphQL query definition:


🏁 Script executed:

#!/bin/bash
# 1. Check for any direct usage of project.leaders
echo "##### Searching for project.leaders usage #####"
rg "project\.leaders" -n .

# 2. Inspect the NextJS page component for a leaders field
echo
echo "##### Inspecting page.tsx for 'leaders' #####"
rg "leaders" -n -g "frontend/src/app/projects/*/page.tsx"

# 3. Locate projectQueries.ts and show its 'leaders' selection
echo
echo "##### Locating projectQueries.ts #####"
file=$(fd projectQueries.ts)
echo "Found: $file"
echo
echo "##### Showing GraphQL selection for 'leaders' #####"
grep -R "leaders" -n "$file"

Length of output: 1219


Let’s inspect the GraphQL selection to confirm the shape of leaders:


🏁 Script executed:

#!/bin/bash
# Show surrounding lines for the 'leaders' block in the query
grep -R -n -C3 "leaders {" frontend/src/server/queries/projectQueries.ts

Length of output: 183


Update mapping for leaders before joining

The leaders field now returns an array of objects ({ login: string }), so calling .join() directly on project.leaders will throw at runtime.

• File: frontend/src/app/projects/[projectKey]/page.tsx (line 59)

- { label: 'Leaders', value: project.leaders.join(', ') },
+ { label: 'Leaders', value: project.leaders.map(leader => leader.login).join(', ') },

• You may also need to update other usages—for example in frontend/src/app/page.tsx (around lines 269–272) replace

<LeadersList leaders={String(project.leaders)} />

with

<LeadersList leaders={project.leaders.map(l => l.login)} />
🧹 Nitpick comments (6)
frontend/src/components/ProjectLeaders.tsx (1)

18-23: Remove console.log statement before deployment

The console.log on line 22 should be removed before deploying to production.

- console.log('LeaderData:', data)
frontend/src/app/projects/[projectKey]/page.tsx (1)

29-31: Remove debugging useEffect

This useEffect appears to be added for debugging purposes. It should be removed before merging to production.

-  useEffect(() => {
-   console.log(`project`, project)
-    },[project])
frontend/src/components/CardDetailsPage.tsx (4)

49-54: Remove debug console.log statement

The console.log on line 53 appears to be added for debugging purposes and should be removed before production deployment.

  const isLeaderData = details?.some((detail) => detail?.label === 'Leaders')
  const leaders = details.find((detail) => detail.label === 'Leaders')?.value || ''
  const leadersArray = leaders.split(',').map((leader) => leader.trim());

- console.log('Leaders:', leadersArray)

159-170: Fix indentation in ProjectLeaders component

The indentation in the ProjectLeaders component is inconsistent with the rest of the file. The props should be aligned with the component name.

  {
    isLeaderData && (
      <ProjectLeaders
-     leaders={
-       leadersArray.reduce((acc, leader) => {
-         acc[leader] = leader
-         return acc
-       }, {} as Record<string, string>)
-     }
+       leaders={
+         leadersArray.reduce((acc, leader) => {
+           acc[leader] = leader
+           return acc
+         }, {} as Record<string, string>)
+       }
      />
    )
  }

159-170: Consider simplifying the leaders object creation

The current approach of using reduce to create an object where keys equal values could be simplified using Object.fromEntries or a more declarative approach.

  {
    isLeaderData && (
      <ProjectLeaders
        leaders={
-         leadersArray.reduce((acc, leader) => {
-           acc[leader] = leader
-           return acc
-         }, {} as Record<string, string>)
+         Object.fromEntries(leadersArray.map(leader => [leader, leader]))
        }
      />
    )
  }

159-172: Remove extra blank lines

There are excessive blank lines following the ProjectLeaders component that should be removed to maintain consistent spacing in the file.

    }
  }

-

  {topContributors && (
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2c99e2d and 66c4157.

📒 Files selected for processing (5)
  • frontend/src/app/about/page.tsx (2 hunks)
  • frontend/src/app/projects/[projectKey]/page.tsx (1 hunks)
  • frontend/src/components/CardDetailsPage.tsx (3 hunks)
  • frontend/src/components/ProjectLeaders.tsx (1 hunks)
  • frontend/src/server/queries/projectQueries.ts (1 hunks)
🔇 Additional comments (9)
frontend/src/server/queries/projectQueries.ts (1)

12-14: Structured leader data retrieval looks good

The GraphQL query now explicitly requests the login field from leaders, which aligns well with the new ProjectLeaders component structure. This change ensures that leader objects have the necessary data fields for proper display.

frontend/src/components/ProjectLeaders.tsx (4)

1-7: Clean imports

The imports are well-organized and include all necessary dependencies for the component.


8-16: Well-defined TypeScript interfaces

The interfaces are clear and properly define the component props, including optional properties.


24-31: Loading and error states handled properly

The component properly handles loading and error states, providing appropriate feedback to users.


50-62: Clean and well-structured component implementation

The ProjectLeaders component is well-organized with good use of props and conditional rendering.

frontend/src/app/about/page.tsx (2)

22-22: Clean import for the new component

The import for the ProjectLeaders component is properly added.


85-85: Simplified leader display with reusable component

Replacing the previous leader display implementation with the new ProjectLeaders component improves code reusability and maintainability.

frontend/src/components/CardDetailsPage.tsx (2)

26-26: New import added for ProjectLeaders component

The import for the new ProjectLeaders component follows the existing import pattern in the file. This aligns with the refactoring to centralize leader display logic.


49-170: Consider potential duplication with existing LeadersList component

The file now contains two different ways to display leader information - the existing approach using LeadersList (line 92) and the new approach using ProjectLeaders. If this is intended as a transition, consider adding a comment explaining this or complete the migration by removing the old implementation.

Is the plan to eventually replace all instances of LeadersList with ProjectLeaders? If so, you may want to consider updating line 92 to use the new component for consistency.

Comment on lines +33 to +48
return (
<UserCard
avatar={user.avatarUrl}
button={{
icon: <FontAwesomeIconWrapper icon="fa-solid fa-right-to-bracket" />,
label: 'View Profile',
onclick: () => window.open(`/members/${username}`, '_blank', 'noopener,noreferrer'),
}}
className="h-64 w-40 bg-inherit"
company={user.company}
description='description'
location={user.location}
name={user.name || username}
/>
)
}
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

Fix hardcoded description value

The component uses a hardcoded 'description' value instead of the description prop that's passed to the component.

- description='description'
+ description={description}

Also, note that you're passing the description prop in the function parameters, but not using it in the component:

- const LeaderData = ({ username }: { username: string; description: string }) => {
+ const LeaderData = ({ username, description }: { username: string; description: string }) => {
📝 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
return (
<UserCard
avatar={user.avatarUrl}
button={{
icon: <FontAwesomeIconWrapper icon="fa-solid fa-right-to-bracket" />,
label: 'View Profile',
onclick: () => window.open(`/members/${username}`, '_blank', 'noopener,noreferrer'),
}}
className="h-64 w-40 bg-inherit"
company={user.company}
description='description'
location={user.location}
name={user.name || username}
/>
)
}
const LeaderData = ({ username, description }: { username: string; description: string }) => {
return (
<UserCard
avatar={user.avatarUrl}
button={{
icon: <FontAwesomeIconWrapper icon="fa-solid fa-right-to-bracket" />,
label: 'View Profile',
onclick: () => window.open(`/members/${username}`, '_blank', 'noopener,noreferrer'),
}}
className="h-64 w-40 bg-inherit"
company={user.company}
description={description}
location={user.location}
name={user.name || username}
/>
)
}
🤖 Prompt for AI Agents (early access)
In frontend/src/components/ProjectLeaders.tsx around lines 33 to 48, the UserCard component is using a hardcoded string 'description' instead of the description prop passed to the component. Replace the hardcoded 'description' value with the description prop variable to correctly display the passed description.

Comment on lines +49 to +51
const isLeaderData = details?.some((detail) => detail?.label === 'Leaders')
const leaders = details.find((detail) => detail.label === 'Leaders')?.value || ''
const leadersArray = leaders.split(',').map((leader) => leader.trim());
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 null check for details in find method

While you've added optional chaining for the some() method, you should also add it for the find() method to prevent potential TypeErrors if details is undefined.

  const isLeaderData = details?.some((detail) => detail?.label === 'Leaders')
- const leaders = details.find((detail) => detail.label === 'Leaders')?.value || ''
+ const leaders = details?.find((detail) => detail?.label === 'Leaders')?.value || ''
  const leadersArray = leaders.split(',').map((leader) => leader.trim());
📝 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 isLeaderData = details?.some((detail) => detail?.label === 'Leaders')
const leaders = details.find((detail) => detail.label === 'Leaders')?.value || ''
const leadersArray = leaders.split(',').map((leader) => leader.trim());
const isLeaderData = details?.some((detail) => detail?.label === 'Leaders')
const leaders = details?.find((detail) => detail?.label === 'Leaders')?.value || ''
const leadersArray = leaders.split(',').map((leader) => leader.trim());
🤖 Prompt for AI Agents (early access)
In frontend/src/components/CardDetailsPage.tsx around lines 49 to 51, the find method is called on details without optional chaining, which can cause a TypeError if details is undefined. Add optional chaining to the find call by changing details.find to details?.find to safely handle cases when details is undefined.

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

🧹 Nitpick comments (1)
backend/apps/owasp/graphql/nodes/project.py (1)

78-79: Why is the resolver method commented out?

The commented-out resolver method seems unnecessary as GraphQL will use the default resolver to return self.leaders.all(). However, having it commented out rather than removed or implemented is confusing and inconsistent with the rest of the codebase where explicit resolvers are used for other fields.

Either remove the commented code entirely or uncomment and use it for consistency with other resolvers in this file:

-# def resolve_leaders(self, info):
-#     return self.leaders.all()
+def resolve_leaders(self, info):
+    """Resolve leaders."""
+    return self.leaders.all()
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 65d15bc and a2acb3f.

📒 Files selected for processing (4)
  • backend/apps/owasp/graphql/nodes/project.py (3 hunks)
  • backend/apps/owasp/migrations/0032_project_leaders.py (1 hunks)
  • backend/apps/owasp/models/project.py (2 hunks)
  • frontend/src/server/queries/projectQueries.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • frontend/src/server/queries/projectQueries.ts
🧰 Additional context used
🧬 Code Graph Analysis (1)
backend/apps/owasp/graphql/nodes/project.py (1)
backend/apps/github/graphql/nodes/user.py (1)
  • UserNode (16-60)
🔇 Additional comments (5)
backend/apps/owasp/graphql/nodes/project.py (2)

8-8: Good addition of the UserNode import.

The import is correctly added to support the new leaders field in the ProjectNode class.


22-22: Properly defined GraphQL field for project leaders.

The leaders field is correctly defined as a list of UserNode objects, which will expose project leaders through the GraphQL API.

backend/apps/owasp/models/project.py (2)

13-13: Good addition of the User model import.

The import is correctly added to support the new leaders field in the Project model.


81-85: Well-defined ManyToMany relationship for project leaders.

The leaders field is properly defined as a ManyToManyField with appropriate parameters:

  • The relationship targets the User model
  • Uses a descriptive related_name for reverse lookups
  • Has blank=True to make it optional

This implementation allows for multiple users to be associated as leaders of a project and for users to lead multiple projects.

backend/apps/owasp/migrations/0032_project_leaders.py (1)

1-23: Migration properly created for adding the leaders field.

This migration correctly:

  1. Adds the leaders ManyToManyField to the Project model
  2. References all necessary dependencies
  3. Uses the same field attributes (blank=True, related_name="led_projects") as defined in the model

The migration will set up the necessary database tables to support the many-to-many relationship between projects and users.

@arkid15r
Copy link
Collaborator

arkid15r commented May 4, 2025

@yashgoyal0110 when this one is going to be ready for review?

@yashgoyal0110
Copy link
Contributor Author

@yashgoyal0110 when this one is going to be ready for review?
Working on it, most probably today
Thanks!

Copy link

sonarqubecloud bot commented May 5, 2025

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.

Impove chapter/project leaders presentation
2 participants