Skip to content

Conversation

sam22kalvium
Copy link

Date:

Developer Name:


Issue Ticket Number

Description

Documentation Updated?

  • Yes
  • No

Under Feature Flag

  • Yes
  • No

Database Changes

  • Yes
  • No

Breaking Changes

  • Yes
  • No

Development Tested?

  • Yes
  • No

Screenshots

Screenshot 1

Test Coverage

Screenshot 1

Additional Notes

Copy link

coderabbitai bot commented May 18, 2025

Summary by CodeRabbit

  • New Features
    • Added the ability to create multiple progress records in a single request via a new bulk creation endpoint.
  • Bug Fixes
    • Improved validation and error handling for progress record creation, including detailed feedback for bulk operations.
  • Documentation
    • Enhanced route documentation with comments for better clarity.

Walkthrough

A bulk creation feature for progress records was introduced. This includes a new controller, model method, validation middleware, and a dedicated POST route for handling multiple progress records in a single request. The implementation ensures validation, error handling, and batch database operations, while also updating exports and route definitions as needed.

Changes

File(s) Change Summary
controllers/progresses.js Added createBulkProgress controller for bulk creation; updated exports to include the new function.
middlewares/validators/progresses.js Refactored validation logic; added createProgressRecordSchema and validateBulkCreateProgressRecords middleware.
models/progresses.js Added createBulkProgressDocuments for batch creation with validation and error handling; updated exports.
routes/progresses.ts Added POST /bulk endpoint with authentication and bulk validation middleware; updated comments for clarity.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Router
    participant AuthMiddleware
    participant BulkValidation
    participant ProgressController
    participant ProgressModel
    participant Firestore

    Client->>Router: POST /progresses/bulk (records[])
    Router->>AuthMiddleware: Authenticate user
    AuthMiddleware->>BulkValidation: Validate records array
    BulkValidation->>ProgressController: Pass validated request
    ProgressController->>ProgressModel: createBulkProgressDocuments(records)
    ProgressModel->>Firestore: Batch write (valid records)
    ProgressModel-->>ProgressController: {successes, failures}
    ProgressController-->>Client: Response with summary
Loading

Poem

In the warren where data hops in a batch,
Rabbits now bulk their progress—what a catch!
With schemas that check, and controllers that care,
Records leap in, fifty at a hare.
If errors arise, don’t fret or frown—
The log will note, but the code won’t drown!
🐇✨

Note

⚡️ AI Code Reviews for VS Code, Cursor, Windsurf

CodeRabbit now has a plugin for VS Code, Cursor and Windsurf. This brings AI code reviews directly in the code editor. Each commit is reviewed immediately, finding bugs before the PR is raised. Seamless context handoff to your AI code agent ensures that you can easily incorporate review feedback.
Learn more here.


Note

⚡️ Faster reviews with caching

CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.
Enjoy the performance boost—your workflow just got faster.

✨ 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.

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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 72d59ef and 1c7b762.

📒 Files selected for processing (4)
  • controllers/progresses.js (2 hunks)
  • middlewares/validators/progresses.js (3 hunks)
  • models/progresses.js (1 hunks)
  • routes/progresses.ts (1 hunks)
🧰 Additional context used
🪛 ESLint
models/progresses.js

[error] 159-159: Trailing spaces not allowed.

(no-trailing-spaces)


[error] 159-159: Delete ··

(prettier/prettier)


[error] 164-164: Insert ,

(prettier/prettier)


[error] 166-166: Trailing spaces not allowed.

(no-trailing-spaces)


[error] 166-166: Delete ··

(prettier/prettier)


[error] 171-171: 'userId' is assigned a value but never used.

(no-unused-vars)


[error] 172-172: Trailing spaces not allowed.

(no-trailing-spaces)


[error] 172-172: Delete ········

(prettier/prettier)


[error] 177-177: Trailing spaces not allowed.

(no-trailing-spaces)


[error] 177-177: Delete ········

(prettier/prettier)


[error] 181-181: Trailing spaces not allowed.

(no-trailing-spaces)


[error] 181-181: Delete ········

(prettier/prettier)


[error] 185-185: Replace ·?·null·:·${type.charAt(0).toUpperCase()·+·type.slice(1)}·${PROGRESS_ALREADY_CREATED}`` with ⏎············?·null⏎············:·${type.charAt(0).toUpperCase()·+·type.slice(1)}·${PROGRESS_ALREADY_CREATED}`,`

(prettier/prettier)


[error] 191-191: Insert ,

(prettier/prettier)


[error] 196-196: Trailing spaces not allowed.

(no-trailing-spaces)


[error] 196-196: Delete ··

(prettier/prettier)


[error] 203-203: Insert ,

(prettier/prettier)


[error] 207-207: Trailing spaces not allowed.

(no-trailing-spaces)


[error] 207-207: Delete ·

(prettier/prettier)


[error] 208-208: Trailing spaces not allowed.

(no-trailing-spaces)


[error] 208-208: Delete ·

(prettier/prettier)


[error] 209-209: Trailing spaces not allowed.

(no-trailing-spaces)


[error] 209-209: Delete ·

(prettier/prettier)


[error] 210-210: Trailing spaces not allowed.

(no-trailing-spaces)


[error] 210-210: Replace · with ,

(prettier/prettier)


[error] 212-212: Trailing spaces not allowed.

(no-trailing-spaces)


[error] 212-212: Delete ······

(prettier/prettier)


[error] 215-215: Trailing spaces not allowed.

(no-trailing-spaces)


[error] 215-215: Delete ······

(prettier/prettier)


[error] 219-219: Insert ,

(prettier/prettier)


[error] 223-223: Trailing spaces not allowed.

(no-trailing-spaces)


[error] 223-223: Delete ··

(prettier/prettier)


[error] 228-228: Trailing spaces not allowed.

(no-trailing-spaces)


[error] 228-228: Delete ··

(prettier/prettier)

controllers/progresses.js

[error] 223-225: Delete ⏎⏎

(prettier/prettier)


[error] 286-286: Trailing spaces not allowed.

(no-trailing-spaces)


[error] 286-286: Delete ··

(prettier/prettier)


[error] 289-289: Replace record with (record)

(prettier/prettier)


[error] 291-291: Insert ,

(prettier/prettier)


[error] 293-293: Trailing spaces not allowed.

(no-trailing-spaces)


[error] 293-293: Delete ····

(prettier/prettier)


[error] 295-295: Trailing spaces not allowed.

(no-trailing-spaces)


[error] 295-295: Delete ····

(prettier/prettier)


[error] 302-302: Insert ,

(prettier/prettier)


[error] 303-303: Insert ,

(prettier/prettier)


[error] 313-313: Trailing spaces not allowed.

(no-trailing-spaces)


[error] 313-313: Delete ·

(prettier/prettier)


[error] 314-314: Trailing spaces not allowed.

(no-trailing-spaces)


[error] 314-314: Delete ·

(prettier/prettier)


[error] 315-315: Trailing spaces not allowed.

(no-trailing-spaces)


[error] 315-315: Delete ·

(prettier/prettier)


[error] 316-316: Trailing spaces not allowed.

(no-trailing-spaces)


[error] 316-316: Delete ·

(prettier/prettier)


[error] 318-318: Insert ,

(prettier/prettier)

middlewares/validators/progresses.js

[error] 39-39: Trailing spaces not allowed.

(no-trailing-spaces)


[error] 39-39: Delete ··

(prettier/prettier)


[error] 46-46: Trailing spaces not allowed.

(no-trailing-spaces)


[error] 46-46: Delete ··

(prettier/prettier)


[error] 161-161: 'baseProgressSchema' is assigned a value but never used.

(no-unused-vars)


[error] 162-162: Trailing spaces not allowed.

(no-trailing-spaces)


[error] 162-162: Delete ··

(prettier/prettier)


[error] 193-193: Replace .string().trim() with ⏎··············.string()⏎··············.trim()⏎··············

(prettier/prettier)


[error] 194-194: Insert ··

(prettier/prettier)


[error] 195-195: Replace ·············· with ················

(prettier/prettier)


[error] 196-196: Insert ··

(prettier/prettier)


[error] 197-197: Replace ················ with ··················

(prettier/prettier)


[error] 198-198: Insert ··

(prettier/prettier)


[error] 199-199: Replace ·············· with ················

(prettier/prettier)


[error] 200-200: Insert ··

(prettier/prettier)


[error] 201-201: Insert ··

(prettier/prettier)


[error] 202-202: Insert ··

(prettier/prettier)

🪛 Biome (1.9.4)
middlewares/validators/progresses.js

[error] 195-195: Do not add then to an object.

(lint/suspicious/noThenProperty)

🔇 Additional comments (2)
routes/progresses.ts (1)

21-22: Well-structured new route for bulk creation.

The implementation of a dedicated route for bulk progress creation follows best practices by reusing authentication and adding specific validation middleware. The clear comment above the route improves maintainability.

middlewares/validators/progresses.js (1)

4-35: Great refactoring to create a reusable schema.

Extracting the common validation logic into a reusable function improves code maintainability and reduces duplication. This is a good pattern.

Comment on lines +272 to +311
/**
* Creates multiple progress documents in bulk.
* @param {Object} req - The HTTP request object.
* @param {Object} req.body - The request body containing an array of progress records.
* @param {Array<ProgressRequestBody>} req.body.records - Array of progress records to create.
* @param {Object} res - The HTTP response object.
* @returns {Promise<void>} A Promise that resolves when the response is sent.
*/
const createBulkProgress = async (req, res) => {
if (req.userData.roles.archived) {
return res.boom.forbidden(UNAUTHORIZED_WRITE);
}

const { records } = req.body;

try {
// Add userId to each record
const recordsWithUserId = records.map(record => ({
...record,
userId: req.userData.id
}));

const result = await progressesModel.createBulkProgressDocuments(recordsWithUserId);

return res.status(201).json({
message: `Successfully created ${result.successCount} progress records`,
data: {
successCount: result.successCount,
failureCount: result.failureCount,
successfulRecords: result.successfulRecords,
failedRecords: result.failedRecords
}
});
} catch (error) {
logger.error(`Error in bulk progress creation: ${error.message}`);
return res.status(500).json({
message: INTERNAL_SERVER_ERROR_MESSAGE,
});
}
};
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Fix formatting issues and enhance error handling.

The bulk progress creation controller logic is well-implemented, but has formatting issues and limited error handling.

Apply these formatting fixes:

const createBulkProgress = async (req, res) => {
  if (req.userData.roles.archived) {
    return res.boom.forbidden(UNAUTHORIZED_WRITE);
  }

  const { records } = req.body;
- 
+ 
  try {
    // Add userId to each record
-   const recordsWithUserId = records.map(record => ({
+   const recordsWithUserId = records.map((record) => ({
      ...record,
-     userId: req.userData.id
+     userId: req.userData.id,
    }));
-   
+    
    const result = await progressesModel.createBulkProgressDocuments(recordsWithUserId);
-   
+    
    return res.status(201).json({
      message: `Successfully created ${result.successCount} progress records`,
      data: {
        successCount: result.successCount,
        failureCount: result.failureCount,
        successfulRecords: result.successfulRecords,
-       failedRecords: result.failedRecords
+       failedRecords: result.failedRecords,
      }
    });
  } catch (error) {
    logger.error(`Error in bulk progress creation: ${error.message}`);
    return res.status(500).json({
      message: INTERNAL_SERVER_ERROR_MESSAGE,
    });
  }
};

Consider enhancing error handling to differentiate between server errors and client errors (like validation failures that passed middleware but failed at model level).

📝 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
/**
* Creates multiple progress documents in bulk.
* @param {Object} req - The HTTP request object.
* @param {Object} req.body - The request body containing an array of progress records.
* @param {Array<ProgressRequestBody>} req.body.records - Array of progress records to create.
* @param {Object} res - The HTTP response object.
* @returns {Promise<void>} A Promise that resolves when the response is sent.
*/
const createBulkProgress = async (req, res) => {
if (req.userData.roles.archived) {
return res.boom.forbidden(UNAUTHORIZED_WRITE);
}
const { records } = req.body;
try {
// Add userId to each record
const recordsWithUserId = records.map(record => ({
...record,
userId: req.userData.id
}));
const result = await progressesModel.createBulkProgressDocuments(recordsWithUserId);
return res.status(201).json({
message: `Successfully created ${result.successCount} progress records`,
data: {
successCount: result.successCount,
failureCount: result.failureCount,
successfulRecords: result.successfulRecords,
failedRecords: result.failedRecords
}
});
} catch (error) {
logger.error(`Error in bulk progress creation: ${error.message}`);
return res.status(500).json({
message: INTERNAL_SERVER_ERROR_MESSAGE,
});
}
};
const createBulkProgress = async (req, res) => {
if (req.userData.roles.archived) {
return res.boom.forbidden(UNAUTHORIZED_WRITE);
}
const { records } = req.body;
try {
// Add userId to each record
const recordsWithUserId = records.map((record) => ({
...record,
userId: req.userData.id,
}));
const result = await progressesModel.createBulkProgressDocuments(recordsWithUserId);
return res.status(201).json({
message: `Successfully created ${result.successCount} progress records`,
data: {
successCount: result.successCount,
failureCount: result.failureCount,
successfulRecords: result.successfulRecords,
failedRecords: result.failedRecords,
},
});
} catch (error) {
logger.error(`Error in bulk progress creation: ${error.message}`);
return res.status(500).json({
message: INTERNAL_SERVER_ERROR_MESSAGE,
});
}
};
🧰 Tools
🪛 ESLint

[error] 286-286: Trailing spaces not allowed.

(no-trailing-spaces)


[error] 286-286: Delete ··

(prettier/prettier)


[error] 289-289: Replace record with (record)

(prettier/prettier)


[error] 291-291: Insert ,

(prettier/prettier)


[error] 293-293: Trailing spaces not allowed.

(no-trailing-spaces)


[error] 293-293: Delete ····

(prettier/prettier)


[error] 295-295: Trailing spaces not allowed.

(no-trailing-spaces)


[error] 295-295: Delete ····

(prettier/prettier)


[error] 302-302: Insert ,

(prettier/prettier)


[error] 303-303: Insert ,

(prettier/prettier)

🤖 Prompt for AI Agents
In controllers/progresses.js around lines 272 to 311, fix inconsistent
indentation and spacing to improve code readability. Enhance error handling by
checking if the caught error is a validation or client error and respond with a
400 status and detailed message; otherwise, respond with a 500 status for server
errors. Ensure the error logging captures full error details for debugging.

Comment on lines +313 to +319
module.exports = {
createProgress,
getProgress,
getProgressRangeData,
getProgressBydDateController,
createBulkProgress
};
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Fix trailing whitespace in module exports.

The module exports have trailing whitespace issues.

Apply this fix:

-module.exports = { 
-  createProgress, 
-  getProgress, 
-  getProgressRangeData, 
+module.exports = {
+  createProgress,
+  getProgress,
+  getProgressRangeData,
  getProgressBydDateController,
-  createBulkProgress
+  createBulkProgress,
};
📝 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
module.exports = {
createProgress,
getProgress,
getProgressRangeData,
getProgressBydDateController,
createBulkProgress
};
module.exports = {
createProgress,
getProgress,
getProgressRangeData,
getProgressBydDateController,
createBulkProgress,
};
🧰 Tools
🪛 ESLint

[error] 313-313: Trailing spaces not allowed.

(no-trailing-spaces)


[error] 313-313: Delete ·

(prettier/prettier)


[error] 314-314: Trailing spaces not allowed.

(no-trailing-spaces)


[error] 314-314: Delete ·

(prettier/prettier)


[error] 315-315: Trailing spaces not allowed.

(no-trailing-spaces)


[error] 315-315: Delete ·

(prettier/prettier)


[error] 316-316: Trailing spaces not allowed.

(no-trailing-spaces)


[error] 316-316: Delete ·

(prettier/prettier)


[error] 318-318: Insert ,

(prettier/prettier)

🤖 Prompt for AI Agents
In controllers/progresses.js around lines 313 to 319, remove any trailing
whitespace characters from the module.exports object to ensure clean and
consistent code formatting. Check each line within the export block and delete
spaces or tabs after the last character on the line.

Comment on lines +149 to +230
/**
* Creates multiple progress documents in a batch operation.
* @param {Array<Object>} progressDataArray - Array of progress data objects to create.
* @returns {Promise<Object>} A Promise that resolves with the result of the batch operation,
* including counts of successful and failed operations and details of each.
*/
const createBulkProgressDocuments = async (progressDataArray) => {
const batch = fireStore.batch();
const createdAtTimestamp = new Date().getTime();
const progressDateTimestamp = getProgressDateTimestamp();

const result = {
successCount: 0,
failureCount: 0,
successfulRecords: [],
failedRecords: []
};

// First, check for existing progress documents for the current day
const existingProgressChecks = await Promise.all(
progressDataArray.map(async (progressData) => {
try {
const { type, taskId, userId } = progressData;

// Validate task exists if taskId is provided
if (taskId) {
await assertTaskExists(taskId);
}

// Check if progress already exists for today
const query = buildQueryForPostingProgress(progressData);
const existingDocumentSnapshot = await query.where("date", "==", progressDateTimestamp).get();

return {
progressData,
exists: !existingDocumentSnapshot.empty,
error: existingDocumentSnapshot.empty ? null : `${type.charAt(0).toUpperCase() + type.slice(1)} ${PROGRESS_ALREADY_CREATED}`
};
} catch (error) {
return {
progressData,
exists: false,
error: error.message
};
}
})
);

// Process records that don't have existing progress for today
existingProgressChecks.forEach((check) => {
if (check.error) {
result.failureCount++;
result.failedRecords.push({
record: check.progressData,
error: check.error
});
} else {
// Add to batch
const progressDocumentData = {
...check.progressData,
createdAt: createdAtTimestamp,
date: progressDateTimestamp
};

const docRef = progressesCollection.doc();
batch.set(docRef, progressDocumentData);

result.successCount++;
result.successfulRecords.push({
id: docRef.id,
...progressDocumentData
});
}
});

// Commit the batch if there are any successful records
if (result.successCount > 0) {
await batch.commit();
}

return result;
};
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Consider breaking down the lengthy function.

The createBulkProgressDocuments function is quite long and handles multiple concerns. Consider breaking it down into smaller helper functions for better readability and maintainability.

You could extract the validation logic and batch creation into separate helper functions:

/**
 * Validates a single progress record
 * @param {Object} progressData - Progress data to validate
 * @returns {Promise<Object>} - Validation result with error if any
 */
const validateProgressRecord = async (progressData) => {
  try {
    const { type, taskId } = progressData;
    
    // Validate task exists if taskId is provided
    if (taskId) {
      await assertTaskExists(taskId);
    }
    
    // Check if progress already exists for today
    const query = buildQueryForPostingProgress(progressData);
    const progressDateTimestamp = getProgressDateTimestamp();
    const existingDocumentSnapshot = await query.where("date", "==", progressDateTimestamp).get();
    
    return {
      progressData,
      exists: !existingDocumentSnapshot.empty,
      error: existingDocumentSnapshot.empty ? null : `${type.charAt(0).toUpperCase() + type.slice(1)} ${PROGRESS_ALREADY_CREATED}`
    };
  } catch (error) {
    return {
      progressData,
      exists: false,
      error: error.message
    };
  }
};

/**
 * Creates multiple progress documents in a batch operation.
 * @param {Array<Object>} progressDataArray - Array of progress data objects to create.
 * @returns {Promise<Object>} A Promise that resolves with the result of the batch operation.
 */
const createBulkProgressDocuments = async (progressDataArray) => {
  // ... Rest of the function with calls to the helper methods
}
🧰 Tools
🪛 ESLint

[error] 159-159: Trailing spaces not allowed.

(no-trailing-spaces)


[error] 159-159: Delete ··

(prettier/prettier)


[error] 164-164: Insert ,

(prettier/prettier)


[error] 166-166: Trailing spaces not allowed.

(no-trailing-spaces)


[error] 166-166: Delete ··

(prettier/prettier)


[error] 171-171: 'userId' is assigned a value but never used.

(no-unused-vars)


[error] 172-172: Trailing spaces not allowed.

(no-trailing-spaces)


[error] 172-172: Delete ········

(prettier/prettier)


[error] 177-177: Trailing spaces not allowed.

(no-trailing-spaces)


[error] 177-177: Delete ········

(prettier/prettier)


[error] 181-181: Trailing spaces not allowed.

(no-trailing-spaces)


[error] 181-181: Delete ········

(prettier/prettier)


[error] 185-185: Replace ·?·null·:·${type.charAt(0).toUpperCase()·+·type.slice(1)}·${PROGRESS_ALREADY_CREATED}`` with ⏎············?·null⏎············:·${type.charAt(0).toUpperCase()·+·type.slice(1)}·${PROGRESS_ALREADY_CREATED}`,`

(prettier/prettier)


[error] 191-191: Insert ,

(prettier/prettier)


[error] 196-196: Trailing spaces not allowed.

(no-trailing-spaces)


[error] 196-196: Delete ··

(prettier/prettier)


[error] 203-203: Insert ,

(prettier/prettier)


[error] 207-207: Trailing spaces not allowed.

(no-trailing-spaces)


[error] 207-207: Delete ·

(prettier/prettier)


[error] 208-208: Trailing spaces not allowed.

(no-trailing-spaces)


[error] 208-208: Delete ·

(prettier/prettier)


[error] 209-209: Trailing spaces not allowed.

(no-trailing-spaces)


[error] 209-209: Delete ·

(prettier/prettier)


[error] 210-210: Trailing spaces not allowed.

(no-trailing-spaces)


[error] 210-210: Replace · with ,

(prettier/prettier)


[error] 212-212: Trailing spaces not allowed.

(no-trailing-spaces)


[error] 212-212: Delete ······

(prettier/prettier)


[error] 215-215: Trailing spaces not allowed.

(no-trailing-spaces)


[error] 215-215: Delete ······

(prettier/prettier)


[error] 219-219: Insert ,

(prettier/prettier)


[error] 223-223: Trailing spaces not allowed.

(no-trailing-spaces)


[error] 223-223: Delete ··

(prettier/prettier)


[error] 228-228: Trailing spaces not allowed.

(no-trailing-spaces)


[error] 228-228: Delete ··

(prettier/prettier)

🤖 Prompt for AI Agents
In models/progresses.js from lines 149 to 230, the createBulkProgressDocuments
function is too long and mixes validation and batch creation logic. Refactor by
extracting the validation logic into a separate async helper function, e.g.,
validateProgressRecord, which checks task existence and existing progress for
the day, returning validation results with errors if any. Then simplify
createBulkProgressDocuments to call this helper for each record, handle results,
and perform batch writes accordingly. This will improve readability and
maintainability.

Comment on lines +167 to +195
// First, check for existing progress documents for the current day
const existingProgressChecks = await Promise.all(
progressDataArray.map(async (progressData) => {
try {
const { type, taskId, userId } = progressData;

// Validate task exists if taskId is provided
if (taskId) {
await assertTaskExists(taskId);
}

// Check if progress already exists for today
const query = buildQueryForPostingProgress(progressData);
const existingDocumentSnapshot = await query.where("date", "==", progressDateTimestamp).get();

return {
progressData,
exists: !existingDocumentSnapshot.empty,
error: existingDocumentSnapshot.empty ? null : `${type.charAt(0).toUpperCase() + type.slice(1)} ${PROGRESS_ALREADY_CREATED}`
};
} catch (error) {
return {
progressData,
exists: false,
error: error.message
};
}
})
);
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Consider transaction for atomicity.

The current implementation checks for existing progress documents and validates tasks serially, which is good but could lead to race conditions if multiple requests try to create progress for the same user/task on the same day.

Consider using Firestore transactions instead of just batches to ensure atomicity and prevent race conditions. Transactions would allow you to check for existing documents and create new ones in a single atomic operation.

🧰 Tools
🪛 ESLint

[error] 171-171: 'userId' is assigned a value but never used.

(no-unused-vars)


[error] 172-172: Trailing spaces not allowed.

(no-trailing-spaces)


[error] 172-172: Delete ········

(prettier/prettier)


[error] 177-177: Trailing spaces not allowed.

(no-trailing-spaces)


[error] 177-177: Delete ········

(prettier/prettier)


[error] 181-181: Trailing spaces not allowed.

(no-trailing-spaces)


[error] 181-181: Delete ········

(prettier/prettier)


[error] 185-185: Replace ·?·null·:·${type.charAt(0).toUpperCase()·+·type.slice(1)}·${PROGRESS_ALREADY_CREATED}`` with ⏎············?·null⏎············:·${type.charAt(0).toUpperCase()·+·type.slice(1)}·${PROGRESS_ALREADY_CREATED}`,`

(prettier/prettier)


[error] 191-191: Insert ,

(prettier/prettier)

🤖 Prompt for AI Agents
In models/progresses.js around lines 167 to 195, the current code checks for
existing progress documents and validates tasks outside of a transaction, which
can cause race conditions. Refactor this logic to use Firestore transactions
that atomically check for existing progress and create new documents within the
same transaction. This ensures that the existence check and creation happen as a
single atomic operation, preventing concurrent requests from creating duplicate
progress entries.

Comment on lines +217 to +220
result.successfulRecords.push({
id: docRef.id,
...progressDocumentData
});
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Fix object formatting in successfulRecords.

The object being pushed to successfulRecords is missing a trailing comma.

Apply this fix:

      result.successfulRecords.push({
        id: docRef.id,
-       ...progressDocumentData
+       ...progressDocumentData,
      });
📝 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
result.successfulRecords.push({
id: docRef.id,
...progressDocumentData
});
result.successfulRecords.push({
id: docRef.id,
...progressDocumentData,
});
🧰 Tools
🪛 ESLint

[error] 219-219: Insert ,

(prettier/prettier)

🤖 Prompt for AI Agents
In models/progresses.js around lines 217 to 220, the object pushed to
successfulRecords is missing a trailing comma after the last property. Add a
trailing comma after the spread operator line to fix the object formatting.

Comment on lines +155 to +165
const createBulkProgressDocuments = async (progressDataArray) => {
const batch = fireStore.batch();
const createdAtTimestamp = new Date().getTime();
const progressDateTimestamp = getProgressDateTimestamp();

const result = {
successCount: 0,
failureCount: 0,
successfulRecords: [],
failedRecords: []
};
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Fix result object formatting.

The result object is missing a trailing comma after successfulRecords.

Apply this fix:

  const result = {
    successCount: 0,
    failureCount: 0,
-   successfulRecords: [],
+   successfulRecords: [],
    failedRecords: []
  };

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

🧰 Tools
🪛 ESLint

[error] 159-159: Trailing spaces not allowed.

(no-trailing-spaces)


[error] 159-159: Delete ··

(prettier/prettier)


[error] 164-164: Insert ,

(prettier/prettier)

🤖 Prompt for AI Agents
In models/progresses.js around lines 155 to 165, the result object declaration
is missing a trailing comma after the successfulRecords property. Add a comma
after successfulRecords to properly format the object and avoid syntax errors.

Comment on lines +207 to +211
const progressDocumentData = {
...check.progressData,
createdAt: createdAtTimestamp,
date: progressDateTimestamp
};
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Fix formatting in document data object.

The progress document data object has formatting issues.

Apply this fix:

-      const progressDocumentData = { 
-        ...check.progressData, 
-        createdAt: createdAtTimestamp, 
-        date: progressDateTimestamp 
+      const progressDocumentData = {
+        ...check.progressData,
+        createdAt: createdAtTimestamp,
+        date: progressDateTimestamp,
      };
📝 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 progressDocumentData = {
...check.progressData,
createdAt: createdAtTimestamp,
date: progressDateTimestamp
};
const progressDocumentData = {
...check.progressData,
createdAt: createdAtTimestamp,
date: progressDateTimestamp,
};
🧰 Tools
🪛 ESLint

[error] 207-207: Trailing spaces not allowed.

(no-trailing-spaces)


[error] 207-207: Delete ·

(prettier/prettier)


[error] 208-208: Trailing spaces not allowed.

(no-trailing-spaces)


[error] 208-208: Delete ·

(prettier/prettier)


[error] 209-209: Trailing spaces not allowed.

(no-trailing-spaces)


[error] 209-209: Delete ·

(prettier/prettier)


[error] 210-210: Trailing spaces not allowed.

(no-trailing-spaces)


[error] 210-210: Replace · with ,

(prettier/prettier)

🤖 Prompt for AI Agents
In models/progresses.js around lines 207 to 211, the progressDocumentData object
has inconsistent or unclear formatting. Reformat the object to have each
key-value pair on its own line with proper indentation and consistent spacing,
improving readability and maintaining code style standards.

Comment on lines +160 to +212
const validateBulkCreateProgressRecords = async (req, res, next) => {
const baseProgressSchema = createProgressRecordSchema();

const bulkSchema = joi
.object()
.keys({
records: joi
.array()
.min(1)
.max(50)
.items(
joi.object().keys({
type: joi
.string()
.trim()
.valid(...VALID_PROGRESS_TYPES)
.required()
.messages({
"any.required": "Required field 'type' is missing.",
"any.only": "Type field is restricted to either 'user' or 'task'.",
}),
completed: joi.string().trim().required().messages({
"any.required": "Required field 'completed' is missing.",
"string.trim": "completed must not have leading or trailing whitespace",
}),
planned: joi.string().trim().required().messages({
"any.required": "Required field 'planned' is missing.",
"string.trim": "planned must not have leading or trailing whitespace",
}),
blockers: joi.string().trim().allow("").required().messages({
"any.required": "Required field 'blockers' is missing.",
"string.trim": "blockers must not have leading or trailing whitespace",
}),
taskId: joi.string().trim().when("type", {
is: "task",
then: joi.required().messages({
"any.required": "Required field 'taskId' is missing for task type.",
"string.trim": "taskId must not have leading or trailing whitespace",
}),
otherwise: joi.forbidden().messages({
"any.unknown": "taskId should not be provided for user type.",
}),
}),
})
)
.required()
.messages({
"array.min": "At least one progress record is required.",
"array.max": "Maximum of 50 progress records can be created at once.",
"any.required": "Progress records array is required.",
}),
})
.messages({ "object.unknown": "Invalid field provided." });
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider reusing baseProgressSchema in bulk validation.

The baseProgressSchema is created but not used, and instead the validation rules are duplicated.

The validator creates baseProgressSchema but doesn't use it, instead duplicating the validation rules in the bulk schema. Consider reusing the schema to avoid duplication:

const validateBulkCreateProgressRecords = async (req, res, next) => {
  const baseProgressSchema = createProgressRecordSchema();
  
  const bulkSchema = joi
    .object()
    .keys({
      records: joi
        .array()
        .min(1)
        .max(50)
        .items(
          joi.object().keys({
-           type: joi
-             .string()
-             .trim()
-             .valid(...VALID_PROGRESS_TYPES)
-             .required()
-             .messages({
-               "any.required": "Required field 'type' is missing.",
-               "any.only": "Type field is restricted to either 'user' or 'task'.",
-             }),
-           completed: joi.string().trim().required().messages({
-             "any.required": "Required field 'completed' is missing.",
-             "string.trim": "completed must not have leading or trailing whitespace",
-           }),
-           planned: joi.string().trim().required().messages({
-             "any.required": "Required field 'planned' is missing.",
-             "string.trim": "planned must not have leading or trailing whitespace",
-           }),
-           blockers: joi.string().trim().allow("").required().messages({
-             "any.required": "Required field 'blockers' is missing.",
-             "string.trim": "blockers must not have leading or trailing whitespace",
-           }),
+           ...baseProgressSchema.extract(),
            taskId: joi.string().trim().when("type", {
              is: "task",
              then: joi.required().messages({
                "any.required": "Required field 'taskId' is missing for task type.",
                "string.trim": "taskId must not have leading or trailing whitespace",
              }),
              otherwise: joi.forbidden().messages({
                "any.unknown": "taskId should not be provided for user type.",
              }),
            }),
          })
        )
        .required()
        .messages({
          "array.min": "At least one progress record is required.",
          "array.max": "Maximum of 50 progress records can be created at once.",
          "any.required": "Progress records array is required.",
        }),
    })
    .messages({ "object.unknown": "Invalid field provided." });

Note: If Joi's .extract() method isn't available in your version, you might need to use another approach to reuse the schema keys.

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

🧰 Tools
🪛 Biome (1.9.4)

[error] 195-195: Do not add then to an object.

(lint/suspicious/noThenProperty)

🪛 ESLint

[error] 161-161: 'baseProgressSchema' is assigned a value but never used.

(no-unused-vars)


[error] 162-162: Trailing spaces not allowed.

(no-trailing-spaces)


[error] 162-162: Delete ··

(prettier/prettier)


[error] 193-193: Replace .string().trim() with ⏎··············.string()⏎··············.trim()⏎··············

(prettier/prettier)


[error] 194-194: Insert ··

(prettier/prettier)


[error] 195-195: Replace ·············· with ················

(prettier/prettier)


[error] 196-196: Insert ··

(prettier/prettier)


[error] 197-197: Replace ················ with ··················

(prettier/prettier)


[error] 198-198: Insert ··

(prettier/prettier)


[error] 199-199: Replace ·············· with ················

(prettier/prettier)


[error] 200-200: Insert ··

(prettier/prettier)


[error] 201-201: Insert ··

(prettier/prettier)


[error] 202-202: Insert ··

(prettier/prettier)

🤖 Prompt for AI Agents
In middlewares/validators/progresses.js between lines 160 and 212, the
baseProgressSchema is defined but not used in the bulk validation schema,
leading to duplicated validation rules. Refactor the bulkSchema to reuse
baseProgressSchema by referencing its keys or structure within the records array
items, avoiding duplication. If Joi's .extract() method is unavailable, manually
incorporate the keys from baseProgressSchema into the bulkSchema's records items
to maintain consistency and reduce redundancy.

Comment on lines +193 to +202
taskId: joi.string().trim().when("type", {
is: "task",
then: joi.required().messages({
"any.required": "Required field 'taskId' is missing for task type.",
"string.trim": "taskId must not have leading or trailing whitespace",
}),
otherwise: joi.forbidden().messages({
"any.unknown": "taskId should not be provided for user type.",
}),
}),
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Fix Biome warning about 'then' property.

The static analysis tool Biome is warning about using 'then' as a property name, which could be confused with Promise's then method.

Consider renaming or refactoring the conditional validation to avoid the Biome warning. You could use Joi's when with a callback function instead:

-            taskId: joi.string().trim().when("type", {
-              is: "task",
-              then: joi.required().messages({
-                "any.required": "Required field 'taskId' is missing for task type.",
-                "string.trim": "taskId must not have leading or trailing whitespace",
-              }),
-              otherwise: joi.forbidden().messages({
-                "any.unknown": "taskId should not be provided for user type.",
-              }),
-            }),
+            taskId: joi.string().trim().when("type", (value, helpers) => {
+              return value === "task"
+                ? joi.required().messages({
+                    "any.required": "Required field 'taskId' is missing for task type.",
+                    "string.trim": "taskId must not have leading or trailing whitespace",
+                  })
+                : joi.forbidden().messages({
+                    "any.unknown": "taskId should not be provided for user type.",
+                  });
+            }),

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

🧰 Tools
🪛 Biome (1.9.4)

[error] 195-195: Do not add then to an object.

(lint/suspicious/noThenProperty)

🪛 ESLint

[error] 193-193: Replace .string().trim() with ⏎··············.string()⏎··············.trim()⏎··············

(prettier/prettier)


[error] 194-194: Insert ··

(prettier/prettier)


[error] 195-195: Replace ·············· with ················

(prettier/prettier)


[error] 196-196: Insert ··

(prettier/prettier)


[error] 197-197: Replace ················ with ··················

(prettier/prettier)


[error] 198-198: Insert ··

(prettier/prettier)


[error] 199-199: Replace ·············· with ················

(prettier/prettier)


[error] 200-200: Insert ··

(prettier/prettier)


[error] 201-201: Insert ··

(prettier/prettier)


[error] 202-202: Insert ··

(prettier/prettier)

🤖 Prompt for AI Agents
In middlewares/validators/progresses.js around lines 193 to 202, the use of
'then' as a property in the Joi conditional validation triggers a Biome warning
due to potential confusion with Promise's then method. Refactor the Joi.when
condition to use a callback function instead of the object with 'is' and 'then'
properties. Inside the callback, return the appropriate Joi schema for the
'taskId' field based on the 'type' value, ensuring the validation logic and
custom messages remain the same while avoiding the 'then' property usage.

@JC-Coder
Copy link

@sam22kalvium provide detailed description and link to the issue this solves

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.

2 participants