Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 50 additions & 1 deletion controllers/progresses.js
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,8 @@ const getProgressRangeData = async (req, res) => {
* @property {string} date - The iso format date of the query.
*/



/**
* @typedef {Object} ProgressDocument
* @property {string} id - The id of the progress document.
Expand Down Expand Up @@ -267,4 +269,51 @@ const getProgressBydDateController = async (req, res) => {
}
};

module.exports = { createProgress, getProgress, getProgressRangeData, getProgressBydDateController };
/**
* 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,
});
}
};
Comment on lines +272 to +311
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.


module.exports = {
createProgress,
getProgress,
getProgressRangeData,
getProgressBydDateController,
createBulkProgress
};
Comment on lines +313 to +319
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.

79 changes: 78 additions & 1 deletion middlewares/validators/progresses.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
const joi = require("joi");
const { VALID_PROGRESS_TYPES, PROGRESS_VALID_SORT_FIELDS } = require("../../constants/progresses");

const validateCreateProgressRecords = async (req, res, next) => {
// Create a reusable progress record schema
const createProgressRecordSchema = () => {
const baseSchema = joi
.object()
.strict()
Expand Down Expand Up @@ -30,12 +31,19 @@ const validateCreateProgressRecords = async (req, res, next) => {
})
.messages({ "object.unknown": "Invalid field provided." });

return baseSchema;
};

const validateCreateProgressRecords = async (req, res, next) => {
const baseSchema = createProgressRecordSchema();

const taskSchema = joi.object().keys({
taskId: joi.string().trim().required().messages({
"any.required": "Required field 'taskId' is missing.",
"string.trim": "taskId must not have leading or trailing whitespace",
}),
});

const schema = req.body.type === "task" ? baseSchema.concat(taskSchema) : baseSchema;

try {
Expand Down Expand Up @@ -144,9 +152,78 @@ const validateGetDayProgressParams = async (req, res, next) => {
res.boom.badRequest(error.details[0].message);
}
};
/**
* Validates bulk creation of progress records
* Ensures the request contains an array of valid progress records
* with a minimum of 1 and maximum of 50 records
*/
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.",
}),
}),
Comment on lines +193 to +202
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.

})
)
.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." });
Comment on lines +160 to +212
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.


try {
await bulkSchema.validateAsync(req.body, { abortEarly: false });
next();
} catch (error) {
logger.error(`Error validating bulk payload: ${error}`);
res.boom.badRequest(error.details[0].message);
}
};

module.exports = {
validateCreateProgressRecords,
validateGetProgressRecordsQuery,
validateGetRangeProgressRecordsParams,
validateGetDayProgressParams,
validateBulkCreateProgressRecords,
};
84 changes: 84 additions & 0 deletions models/progresses.js
Original file line number Diff line number Diff line change
Expand Up @@ -146,11 +146,95 @@ const addUserDetailsToProgressDocs = async (progressDocs) => {
}
};

/**
* 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: []
};
Comment on lines +155 to +165
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.


// 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
};
}
})
);
Comment on lines +167 to +195
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.


// 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
};
Comment on lines +207 to +211
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.


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

result.successCount++;
result.successfulRecords.push({
id: docRef.id,
...progressDocumentData
});
Comment on lines +217 to +220
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.

}
});

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

return result;
};
Comment on lines +149 to +230
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.


module.exports = {
createProgressDocument,
getProgressDocument,
getPaginatedProgressDocument,
getRangeProgressData,
getProgressByDate,
addUserDetailsToProgressDocs,
createBulkProgressDocuments,
};
12 changes: 12 additions & 0 deletions routes/progresses.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,29 @@ import {
validateGetProgressRecordsQuery,
validateGetRangeProgressRecordsParams,
validateGetDayProgressParams,
validateBulkCreateProgressRecords,
} from "../middlewares/validators/progresses";
import {
createProgress,
getProgress,
getProgressRangeData,
getProgressBydDateController,
createBulkProgress,
} from "../controllers/progresses";
const router = express.Router();
// Create a single progress record
router.post("/", authenticate, validateCreateProgressRecords, createProgress);

// Create multiple progress records in bulk
router.post("/bulk", authenticate, validateBulkCreateProgressRecords, createBulkProgress);

// Get progress records with optional filtering
router.get("/", validateGetProgressRecordsQuery, getProgress);

// Get progress for a specific date
router.get("/:type/:typeId/date/:date", validateGetDayProgressParams, getProgressBydDateController);

// Get progress records for a date range
router.get("/range", validateGetRangeProgressRecordsParams, getProgressRangeData);

module.exports = router;