Skip to content

Conversation

@RamRamez
Copy link
Member

@RamRamez RamRamez commented May 27, 2025

Summary by CodeRabbit

  • New Features

    • Added the ability to sort polls by participant count, with separate handling for active and ended polls.
  • Improvements

    • Enhanced sorting options for polls, now allowing sorting by creation date, end date, or participant count using a more robust selection method.
    • Improved poll data to indicate whether the user has voted, enhancing poll interaction visibility.

@coderabbitai
Copy link

coderabbitai bot commented May 27, 2025

Walkthrough

The changes introduce a new PollSortBy enum for poll sorting options and refactor the sorting logic in the getPolls method to use this enum. Specialized logic is added for sorting by participant count, separating active and ended polls, while maintaining existing behavior for other sorting criteria.

Changes

File(s) Change Summary
src/poll/Poll.dto.ts Added PollSortBy enum; updated GetPollsDto.sortBy to use the enum instead of string literals.
src/poll/poll.service.ts Refactored getPolls to use PollSortBy enum; added specialized multi-query sorting for participant count; added helper method to map vote status.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant PollService
    participant Database

    Client->>PollService: getPolls(query, worldID)
    alt sortBy == PARTICIPANT_COUNT
        PollService->>Database: Query active polls (order by participant count desc)
        PollService->>Database: Query ended polls (order by participant count desc)
        PollService->>PollService: Combine, paginate, map hasVoted, count total
    else sortBy == END_DATE or CREATION_DATE
        PollService->>Database: Query polls (order by sortBy and sortOrder)
        PollService->>PollService: Map hasVoted, count total
    end
    PollService->>Client: Return polls and total count
Loading

Possibly related PRs

  • fix: explore all polls order #111: Modifies getPolls in PollService for specialized multi-query sorting, similar to participant count sorting added here.
  • added getPolls api #12: Refines enum usage in GetPollsDto and extends getPolls with specialized participant count sorting, building on the same DTO and service method.
  • Add get poll details #20: Introduces initial GetPollsDto and generic sorting in getPolls; this PR builds directly on those changes with enum and specialized logic.

Suggested reviewers

  • Meriem-BM

Poem

In the meadow of enums, a new one appears,
Sorting polls by count, creation, or years.
Active and ended, now neatly apart,
The service hops smartly, a true work of art!
With every new query, the results are just right—
🐇 Cheers to clean code and logic in flight!


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 65e73b4 and 5d466b9.

📒 Files selected for processing (1)
  • src/poll/poll.service.ts (7 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/poll/poll.service.ts
✨ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

@RamRamez RamRamez requested a review from Meriem-BM May 27, 2025 23:05
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

🧹 Nitpick comments (1)
src/poll/poll.service.ts (1)

373-380: Extract duplicated poll mapping logic to reduce code duplication.

The logic for mapping polls with vote status is repeated four times throughout the method. Consider extracting it into a helper method.

Add this helper method to the class:

private mapPollsWithVoteStatus(polls: any[], userId: number) {
  return polls.map(poll => {
    const { votes, ...pollWithoutVotes } = poll;
    return {
      ...pollWithoutVotes,
      hasVoted: votes.length > 0,
    };
  });
}

Then replace all occurrences with:

-const pollsWithVoteStatus = paginatedPolls.map(poll => {
-  const { votes, ...pollWithoutVotes } = poll
-
-  return {
-    ...pollWithoutVotes,
-    hasVoted: votes.length > 0,
-  }
-})
+const pollsWithVoteStatus = this.mapPollsWithVoteStatus(paginatedPolls, userId);

Also applies to: 433-440, 470-477, 510-517

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between aa1cad4 and 65e73b4.

📒 Files selected for processing (2)
  • src/poll/Poll.dto.ts (2 hunks)
  • src/poll/poll.service.ts (4 hunks)
🔇 Additional comments (2)
src/poll/Poll.dto.ts (2)

16-20: Good use of enum for type safety!

The introduction of the PollSortBy enum improves type safety and maintainability by replacing string literals with strongly typed values.


124-125: Consistent use of enum for validation!

The update to use PollSortBy enum with @IsEnum decorator ensures type safety at both compile-time and runtime.

Comment on lines 388 to 445
if (sortBy === PollSortBy.PARTICIPANT_COUNT) {
// For participantCount: show active polls first (by highest voter count), then ended polls
const activeFilters = {
...filters,
startDate: { lte: now },
endDate: { gt: now },
}

const endedFilters = {
...filters,
endDate: { lte: now },
}

const [activePolls, endedPolls, total] =
await this.databaseService.$transaction([
this.databaseService.poll.findMany({
where: activeFilters,
include: {
author: true,
votes: {
where: { userId },
select: { voteID: true },
},
},
orderBy: { participantCount: 'desc' }, // Highest voter count first for active polls
take: Number(limit) + skip,
}),
this.databaseService.poll.findMany({
where: endedFilters,
include: {
author: true,
votes: {
where: { userId },
select: { voteID: true },
},
},
orderBy: { participantCount: 'desc' }, // Highest voter count first for ended polls too
take: Number(limit) + skip,
}),
this.databaseService.poll.count({ where: filters }),
])

const combinedPolls = [...activePolls, ...endedPolls]
const paginatedPolls = combinedPolls.slice(skip, skip + Number(limit))

const pollsWithVoteStatus = paginatedPolls.map(poll => {
const { votes, ...pollWithoutVotes } = poll

return {
...pollWithoutVotes,
hasVoted: votes.length > 0,
}
})

return {
polls: pollsWithVoteStatus,
total,
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

The participant count sorting has two issues to address.

  1. The sortOrder parameter is ignored - both active and ended polls are always sorted by 'desc' regardless of the user's preference.
  2. Future polls (where startDate > now) might be incorrectly included with ended polls.

Apply this diff to fix both issues:

 // For participantCount: show active polls first (by highest voter count), then ended polls
 const activeFilters = {
   ...filters,
   startDate: { lte: now },
   endDate: { gt: now },
 }

 const endedFilters = {
   ...filters,
   endDate: { lte: now },
+  startDate: { lte: now }, // Exclude future polls
 }

 const [activePolls, endedPolls, total] =
   await this.databaseService.$transaction([
     this.databaseService.poll.findMany({
       where: activeFilters,
       include: {
         author: true,
         votes: {
           where: { userId },
           select: { voteID: true },
         },
       },
-      orderBy: { participantCount: 'desc' }, // Highest voter count first for active polls
+      orderBy: { participantCount: sortOrder },
       take: Number(limit) + skip,
     }),
     this.databaseService.poll.findMany({
       where: endedFilters,
       include: {
         author: true,
         votes: {
           where: { userId },
           select: { voteID: true },
         },
       },
-      orderBy: { participantCount: 'desc' }, // Highest voter count first for ended polls too
+      orderBy: { participantCount: sortOrder },
       take: Number(limit) + skip,
     }),
     this.databaseService.poll.count({ where: filters }),
   ])
📝 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 (sortBy === PollSortBy.PARTICIPANT_COUNT) {
// For participantCount: show active polls first (by highest voter count), then ended polls
const activeFilters = {
...filters,
startDate: { lte: now },
endDate: { gt: now },
}
const endedFilters = {
...filters,
endDate: { lte: now },
}
const [activePolls, endedPolls, total] =
await this.databaseService.$transaction([
this.databaseService.poll.findMany({
where: activeFilters,
include: {
author: true,
votes: {
where: { userId },
select: { voteID: true },
},
},
orderBy: { participantCount: 'desc' }, // Highest voter count first for active polls
take: Number(limit) + skip,
}),
this.databaseService.poll.findMany({
where: endedFilters,
include: {
author: true,
votes: {
where: { userId },
select: { voteID: true },
},
},
orderBy: { participantCount: 'desc' }, // Highest voter count first for ended polls too
take: Number(limit) + skip,
}),
this.databaseService.poll.count({ where: filters }),
])
const combinedPolls = [...activePolls, ...endedPolls]
const paginatedPolls = combinedPolls.slice(skip, skip + Number(limit))
const pollsWithVoteStatus = paginatedPolls.map(poll => {
const { votes, ...pollWithoutVotes } = poll
return {
...pollWithoutVotes,
hasVoted: votes.length > 0,
}
})
return {
polls: pollsWithVoteStatus,
total,
}
if (sortBy === PollSortBy.PARTICIPANT_COUNT) {
// For participantCount: show active polls first (by highest voter count), then ended polls
const activeFilters = {
...filters,
startDate: { lte: now },
endDate: { gt: now },
}
const endedFilters = {
...filters,
endDate: { lte: now },
startDate: { lte: now }, // Exclude future polls
}
const [activePolls, endedPolls, total] =
await this.databaseService.$transaction([
this.databaseService.poll.findMany({
where: activeFilters,
include: {
author: true,
votes: {
where: { userId },
select: { voteID: true },
},
},
orderBy: { participantCount: sortOrder },
take: Number(limit) + skip,
}),
this.databaseService.poll.findMany({
where: endedFilters,
include: {
author: true,
votes: {
where: { userId },
select: { voteID: true },
},
},
orderBy: { participantCount: sortOrder },
take: Number(limit) + skip,
}),
this.databaseService.poll.count({ where: filters }),
])
const combinedPolls = [...activePolls, ...endedPolls]
const paginatedPolls = combinedPolls.slice(skip, skip + Number(limit))
const pollsWithVoteStatus = paginatedPolls.map(poll => {
const { votes, ...pollWithoutVotes } = poll
return {
...pollWithoutVotes,
hasVoted: votes.length > 0,
}
})
return {
polls: pollsWithVoteStatus,
total,
}
}
🤖 Prompt for AI Agents
In src/poll/poll.service.ts around lines 388 to 445, the participant count
sorting ignores the sortOrder parameter and always sorts descending, and future
polls are incorrectly included with ended polls. Fix this by using the provided
sortOrder value instead of hardcoding 'desc' in both active and ended polls
queries. Also, exclude future polls from the ended polls query by adding a
condition to ensure startDate is less than or equal to now, so only truly ended
polls are included.

Copy link
Member

@Meriem-BM Meriem-BM left a comment

Choose a reason for hiding this comment

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

LGTM

@RamRamez RamRamez merged commit ea5c1c0 into develop May 28, 2025
1 check passed
@RamRamez RamRamez deleted the trending-polls-should-show-active-polls-first branch May 28, 2025 09:34
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