Skip to content

Conversation

@elhalj
Copy link
Owner

@elhalj elhalj commented Sep 9, 2025

Summary

Refactor task API endpoints to inline Fastify route handlers with direct Mongoose operations, comprehensive validation, transaction support, and real-time WebSocket notifications; clean up controller files; and update frontend profile and room context components for improved loading and error handling.

New Features:

  • Add real-time socket notifications for task creation, assignment, updates, views, and deletion.

Enhancements:

  • Replace TaskController methods with inline Fastify route handlers that enforce input validation, access control, and use Mongoose sessions for atomic CRUD operations.
  • Clean up user and room controllers by removing redundant logic and imports, and ensure consistent session usage in room transactions.

Chores:

  • Rename Profile component to Profiles and update ProfilePage to use custom Loader and Errors components instead of Skeleton and toasts.
  • Enhance RoomProvider error handling with detailed API error messages and TypeScript casting.

@elhalj elhalj added the good first issue Good for newcomers label Sep 9, 2025
@sourcery-ai
Copy link

sourcery-ai bot commented Sep 9, 2025

Reviewer's Guide

This PR refactors the task API by moving all CRUD logic inline into the Fastify route definitions, replacing the TaskController, and enriching operations with detailed validation, transaction-based persistence (Mongoose sessions), and socket.io real-time notifications. It also adjusts front-end profile components, improves error handling in the RoomProvider, and includes minor cleanups in user and room controllers.

Sequence diagram for task creation with validation, transaction, and notifications

sequenceDiagram
  actor User
  participant Fastify
  participant Task
  participant UserModel
  participant RoomModel
  participant SocketIO
  User->>Fastify: POST /add/tasks
  Fastify->>UserModel: Validate assignees
  Fastify->>RoomModel: Validate room access
  Fastify->>Task: Create new task (with validated data)
  Fastify->>UserModel: Update myTasks, increment tasksCreated
  Fastify->>UserModel: Update collaborators for assignees
  Fastify->>RoomModel: Add task to room (if roomId)
  Fastify->>SocketIO: emitTaskNotification("taskCreated")
  Fastify->>SocketIO: emitTaskNotification("taskAssigned") for each assignee
  Fastify-->>User: Return saved task
Loading

Sequence diagram for task update with validation and notifications

sequenceDiagram
  actor User
  participant Fastify
  participant Task
  participant UserModel
  participant SocketIO
  User->>Fastify: PUT /update/tasks/:id
  Fastify->>Task: Validate task ownership
  Fastify->>Task: Update task fields
  Fastify->>UserModel: Increment tasksCompleted (if status changed to done)
  Fastify->>SocketIO: emitTaskNotification("taskUpdated")
  Fastify->>SocketIO: io.to(`task_${id}`).emit("taskRoomUpdate")
  Fastify-->>User: Return updated task
Loading

Sequence diagram for task deletion with notifications

sequenceDiagram
  actor User
  participant Fastify
  participant Task
  participant UserModel
  participant SocketIO
  User->>Fastify: DELETE /delete/task/:id
  Fastify->>Task: Validate task ownership
  Fastify->>Task: Delete task
  Fastify->>UserModel: Remove task from myTasks
  Fastify->>SocketIO: emitTaskNotification("taskDeleted")
  Fastify->>SocketIO: io.to(`task_${id}`).emit("taskRoomDeleted")
  Fastify-->>User: Return success
Loading

Class diagram for removal of TaskController and inline route logic

classDiagram
  class TaskController {
    -emitTaskNotification()
    -getTask()
    -addTask()
    -updateTask()
    -getById()
    -delete()
  }
  %% TaskController is removed; logic now in Fastify route definitions
  class FastifyTaskRoutes {
    +emitTaskNotification()
    +getTask()
    +addTask()
    +updateTask()
    +getById()
    +delete()
  }
  FastifyTaskRoutes : uses Mongoose models
  FastifyTaskRoutes : uses socket.io for notifications
Loading

File-Level Changes

Change Details Files
Replace TaskController with inline async route handlers
  • Removed TaskController import and usage
  • Implemented get/add/update/getById/delete logic directly in task.route.js
  • Deleted redundant TaskController methods
src/routes/task.route.js
src/controllers/task.controller.js
Add socket.io notification utility
  • Introduced emitTaskNotification helper
  • Emit events for taskCreated, taskAssigned, taskUpdated, taskViewed, taskDeleted
  • Target notifications to individual users or broadcast
src/routes/task.route.js
Enhance task creation with validation and transactions
  • Validate assignees and room access
  • Ensure required fields and future dueDate
  • Use mongoose sessions to update task, author, assignees and room atomically
src/routes/task.route.js
Strengthen update and delete flows
  • Validate ObjectId and ownership
  • Detect status/priority changes and update user stats
  • Emit contextual notifications and room-specific socket events
src/routes/task.route.js
Refactor frontend profile components
  • Renamed Profile to Profiles
  • Replaced Skeleton UI with Loader component
  • Swapped toast-based errors for Errors component
frontend/src/pages/ProfilePage.tsx
frontend/src/ui/profile/Profile.tsx
Improve RoomProvider error handling
  • Handle ApiError to extract meaningful message
  • Avoid stale state update on room update path
frontend/src/context/RoomProvider.tsx
Clean up user and room controllers
  • Removed notification populate from user.getUser
  • Added mongoose import for session support in RoomController
src/controllers/user.controller.js
src/controllers/room.controller.js

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@netlify
Copy link

netlify bot commented Sep 9, 2025

Deploy Preview for colab-flow ready!

Name Link
🔨 Latest commit 21b01bc
🔍 Latest deploy log https://app.netlify.com/projects/colab-flow/deploys/68c0693aa0956f0007c0e78b
😎 Deploy Preview https://deploy-preview-34--colab-flow.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

@elhalj
Copy link
Owner Author

elhalj commented Sep 9, 2025

@sourcery-ai title

@sourcery-ai sourcery-ai bot changed the title reviw code Refactor Task API, Add Real-time Notifications, and Enhance Frontend Sep 9, 2025
Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey there - I've reviewed your changes - here's some feedback:

  • The task routes are very large and repetitive—consider extracting shared validation and notification logic into reusable helper functions or middleware to improve readability and maintainability.
  • It may be better to move the inlined controller logic back into dedicated controller/service classes (or at least separate modules) so that your route definitions stay concise and your business logic remains easily testable.
  • The front-end component rename (Profile → Profiles) is inconsistent—pick a single name and update imports/exports accordingly to avoid confusion.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- The task routes are very large and repetitive—consider extracting shared validation and notification logic into reusable helper functions or middleware to improve readability and maintainability.
- It may be better to move the inlined controller logic back into dedicated controller/service classes (or at least separate modules) so that your route definitions stay concise and your business logic remains easily testable.
- The front-end component rename (Profile → Profiles) is inconsistent—pick a single name and update imports/exports accordingly to avoid confusion.

## Individual Comments

### Comment 1
<location> `src/routes/task.route.js:156` </location>
<code_context>
-        }
-      }
-
-      if (!estimatedHours || typeof estimatedHours !== "number") {
-        return reply.code(400).send({
-          success: false,
</code_context>

<issue_to_address>
Estimated hours validation may reject valid zero values.

The validation treats 0 as invalid due to its falsy value. Use a type check or null/undefined check to permit zero.
</issue_to_address>

### Comment 2
<location> `src/routes/task.route.js:164` </location>
<code_context>
-      }
-
-      // Chercher les utilisateurs assignés existants (sans doublon)
-      const assigneesId = [...new Set(assignees)];
-      // Chercher les utilisateurs assignés existants (sans doublon)
-      const existingAssignees = await User.find({
-        $and: [{ _id: { $in: assigneesId } }, { _id: { $ne: userId } }],
-      }).select("_id");
</code_context>

<issue_to_address>
Duplicate assignee filtering may be redundant.

Using the original assignees array for updates and notifications may cause duplicate actions for users. Use the deduplicated list to avoid this issue.

Suggested implementation:

```javascript
          assignees: assigneesId,

```

If there are other places in this function or file where the original `assignees` array is used for notifications, updates, or other actions, you should replace those usages with `assigneesId` to ensure deduplication throughout the workflow.
</issue_to_address>

### Comment 3
<location> `src/routes/task.route.js:178` </location>
<code_context>
-        priority,
-        dueDate: dueDateObj,
-        estimatedHours: parseFloat(estimatedHours) || 0,
-        assignees: [...existingAssignees],
-        label,
-        author: request.user.userId,
</code_context>

<issue_to_address>
Assignees array may contain Mongoose documents instead of IDs.

If the schema requires ObjectIds, map `existingAssignees` to their `_id` properties before assigning.
</issue_to_address>

### Comment 4
<location> `src/routes/task.route.js:343` </location>
<code_context>
-      if (updateData.author) delete updateData.author;
-      if (updateData.room) delete updateData.room;
-
-      const updatedTask = await Task.findByIdAndUpdate(id, updateData, {
-        new: true,
-        runValidators: true,
</code_context>

<issue_to_address>
Update allows arbitrary fields to be set.

Whitelisting permitted fields for updates will help prevent unauthorized modifications to sensitive data.
</issue_to_address>

<suggested_fix>
<<<<<<< SEARCH
        // Mettre à jour la tâche
        const updateData = { ...request.body };
        // Ne pas permettre la modification de l'auteur
        if (updateData.author) delete updateData.author;
        if (updateData.room) delete updateData.room;

        const updatedTask = await Task.findByIdAndUpdate(id, updateData, {
          new: true,
          runValidators: true,
        }).populate("author", "userName email");
=======
        // Définir les champs autorisés à être mis à jour
        const allowedFields = [
          "title",
          "description",
          "status",
          "estimatedTime",
          "priority",
          "dueDate"
          // Ajoutez ici d'autres champs autorisés si nécessaire
        ];

        // Filtrer les données de mise à jour pour ne garder que les champs autorisés
        const updateData = {};
        for (const key of allowedFields) {
          if (request.body.hasOwnProperty(key)) {
            updateData[key] = request.body[key];
          }
        }

        const updatedTask = await Task.findByIdAndUpdate(id, updateData, {
          new: true,
          runValidators: true,
        }).populate("author", "userName email");
>>>>>>> REPLACE

</suggested_fix>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

}
}

if (!estimatedHours || typeof estimatedHours !== "number") {
Copy link

Choose a reason for hiding this comment

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

issue (bug_risk): Estimated hours validation may reject valid zero values.

The validation treats 0 as invalid due to its falsy value. Use a type check or null/undefined check to permit zero.

Comment on lines +164 to +166
// Chercher les utilisateurs assignés existants (sans doublon)
const existingAssignees = await User.find({
$and: [{ _id: { $in: assigneesId } }, { _id: { $ne: userId } }],
Copy link

Choose a reason for hiding this comment

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

suggestion (bug_risk): Duplicate assignee filtering may be redundant.

Using the original assignees array for updates and notifications may cause duplicate actions for users. Use the deduplicated list to avoid this issue.

Suggested implementation:

          assignees: assigneesId,

If there are other places in this function or file where the original assignees array is used for notifications, updates, or other actions, you should replace those usages with assigneesId to ensure deduplication throughout the workflow.

dueDate: dueDateObj,
estimatedHours: parseFloat(estimatedHours) || 0,
assignees: [...existingAssignees],
label,
Copy link

Choose a reason for hiding this comment

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

issue (bug_risk): Assignees array may contain Mongoose documents instead of IDs.

If the schema requires ObjectIds, map existingAssignees to their _id properties before assigning.

Comment on lines +337 to +346
const updateData = { ...request.body };
// Ne pas permettre la modification de l'auteur
if (updateData.author) delete updateData.author;
if (updateData.room) delete updateData.room;

const updatedTask = await Task.findByIdAndUpdate(id, updateData, {
new: true,
runValidators: true,
}).populate("author", "userName email");

Copy link

Choose a reason for hiding this comment

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

🚨 suggestion (security): Update allows arbitrary fields to be set.

Whitelisting permitted fields for updates will help prevent unauthorized modifications to sensitive data.

Suggested change
// Mettre à jour la tâche
const updateData = { ...request.body };
// Ne pas permettre la modification de l'auteur
if (updateData.author) delete updateData.author;
if (updateData.room) delete updateData.room;
const updatedTask = await Task.findByIdAndUpdate(id, updateData, {
new: true,
runValidators: true,
}).populate("author", "userName email");
// Définir les champs autorisés à être mis à jour
const allowedFields = [
"title",
"description",
"status",
"estimatedTime",
"priority",
"dueDate"
// Ajoutez ici d'autres champs autorisés si nécessaire
];
// Filtrer les données de mise à jour pour ne garder que les champs autorisés
const updateData = {};
for (const key of allowedFields) {
if (request.body.hasOwnProperty(key)) {
updateData[key] = request.body[key];
}
}
const updatedTask = await Task.findByIdAndUpdate(id, updateData, {
new: true,
runValidators: true,
}).populate("author", "userName email");

} = request.body;

const userId = request.user.userId;

Copy link

Choose a reason for hiding this comment

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

suggestion (code-quality): Prefer object destructuring when accessing and using properties. (use-object-destructuring)

Suggested change
const userId = request.user.userId;
const {userId} = request.user;


ExplanationObject destructuring can often remove an unnecessary temporary reference, as well as making your code more succinct.

From the Airbnb Javascript Style Guide

try {
const { id } = request.params;
const userId = request.user.userId;

Copy link

Choose a reason for hiding this comment

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

suggestion (code-quality): Prefer object destructuring when accessing and using properties. (use-object-destructuring)

Suggested change
const userId = request.user.userId;
const {userId} = request.user;


ExplanationObject destructuring can often remove an unnecessary temporary reference, as well as making your code more succinct.

From the Airbnb Javascript Style Guide

try {
const { id } = request.params;
const userId = request.user.userId;

Copy link

Choose a reason for hiding this comment

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

suggestion (code-quality): Prefer object destructuring when accessing and using properties. (use-object-destructuring)

Suggested change
const userId = request.user.userId;
const {userId} = request.user;


ExplanationObject destructuring can often remove an unnecessary temporary reference, as well as making your code more succinct.

From the Airbnb Javascript Style Guide

@elhalj elhalj merged commit 85a3607 into main Sep 9, 2025
8 of 10 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

good first issue Good for newcomers

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants