Skip to content

API created for Leave#11

Merged
harshGupta090722 merged 1 commit into
mainfrom
Development
Apr 30, 2026
Merged

API created for Leave#11
harshGupta090722 merged 1 commit into
mainfrom
Development

Conversation

@harshGupta090722

@harshGupta090722 harshGupta090722 commented Apr 30, 2026

Copy link
Copy Markdown
Owner

Summary by CodeRabbit

Release Notes

  • New Features

    • Leave management system: employees can submit leave requests and admins can review and update status.
  • Bug Fixes

    • Fixed employee creation and update data processing.
    • Corrected attendance clock in/out record lookup.
    • Fixed admin access control authorization checks.
    • Restored user role default value assignment.
  • Chores

    • Updated middleware import paths.
    • Added encryption dependency.

@coderabbitai

coderabbitai Bot commented Apr 30, 2026

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

The pull request introduces a leave management system with new LeaveApplication model and controller, fixes several bugs across controllers and middleware (typos, incorrect imports, query logic), corrects model field definitions, and adds the bcryptjs dependency to the project manifest.

Changes

Cohort / File(s) Summary
Dependency Management
package.json
Adds bcryptjs ^3.0.3 as a project dependency.
Leave Management System
server/models/LeaveApplication.js, server/controllers/leaveController.js
Introduces new LeaveApplication model with status/type validation and date fields; new controller exports createLeave, getLeaves (role-aware filtering), and updateLeaveStatus handlers.
Import and Path Corrections
server/controllers/authController.js, server/routes/AttendanceRoutes.js
Corrects User model import to explicit .js extension; updates middleware import path from ../middlewares/auth.js to ../middleware/auth.js.
Controller Query and Parsing Fixes
server/controllers/attendanceController.js, server/controllers/employeeController.js
Fixes attendanceController to query Attendance model directly instead of invalid getAttendance reference; corrects employeeController to read from req.body instead of misspelled req.bod.
Model Field Corrections
server/models/Employee.js, server/models/User.js
Corrects Employee.userId field from mongoose.Schema.types.ObjectId to mongoose.Schema.Types.ObjectId (case-sensitive); fixes User role field default from misspelled dafault to default.
Middleware Authorization Logic
server/middleware/auth.js
Corrects jwt import to default import; fixes adminProtect authorization check from invalid expression !req?.session?.role !== "ADMIN" to direct inequality req?.session?.role !== "ADMIN".

Sequence Diagram

sequenceDiagram
    actor Client
    participant LeaveController
    participant Employee Model
    participant LeaveApplication Model
    participant Database

    Client->>LeaveController: POST /leaves (createLeave)
    LeaveController->>Employee Model: Resolve employee from session
    Employee Model->>Database: Query employee by ID
    Database-->>Employee Model: Return employee record
    LeaveController->>LeaveApplication Model: Validate dates & create document
    LeaveApplication Model->>Database: Insert new leave with PENDING status
    Database-->>LeaveApplication Model: Return created leave
    LeaveApplication Model-->>Client: Return leave record

    Client->>LeaveController: GET /leaves (getLeaves)
    alt Admin Role
        LeaveController->>LeaveApplication Model: Query with optional status filter
    else Employee Role
        LeaveController->>LeaveApplication Model: Query only own leaves
    end
    LeaveApplication Model->>Database: Fetch leave records & populate employee
    Database-->>LeaveApplication Model: Return populated records
    LeaveApplication Model-->>Client: Return normalized leaves

    Client->>LeaveController: PATCH /leaves/:id (updateLeaveStatus)
    LeaveController->>LeaveApplication Model: Update status by ID
    LeaveApplication Model->>Database: Modify leave document
    Database-->>LeaveApplication Model: Return updated leave
    LeaveApplication Model-->>Client: Return updated record
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • api created for employees,authentication and attendance. #10: Addresses similar code-level fixes and adaptations across the same controllers, models, middleware, and routes (attendanceController, authController, employeeController, auth middleware, Employee/User/Attendance models, and AttendanceRoutes).

Poem

🐰 A leave system springs to life,
With bugs now squashed and paths set right,
bcryptjs joins the warren's stride,
Models fixed with mongoose pride!
Attendance flows, permissions clear—
The EMS hops into a better year!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Title check ⚠️ Warning The PR title 'API created for Leave' focuses on the leave API functionality, but the changeset includes multiple unrelated fixes and improvements across authentication, employee, and attendance controllers, plus dependency additions and schema corrections. Revise the title to reflect the full scope of changes, such as 'Add Leave API and fix various controller/schema issues' or split into multiple focused PRs.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch Development

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
Review rate limit: 0/1 reviews remaining, refill in 60 minutes.

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 5

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
server/controllers/employeeController.js (1)

91-110: ⚠️ Potential issue | 🔴 Critical

Add missing joinDate to destructuring in updateEmployee.

Line 91 is missing joinDate from the destructuring statement, but line 110 references it, causing a runtime ReferenceError when the update endpoint is called.

Proposed fix
-        const { firstName, lastName, email, phone, position, department, basicSalary, allowances, deductions, password, role, bio, employmentStatus } = req.body;
+        const { firstName, lastName, email, phone, position, department, basicSalary, allowances, deductions, joinDate, password, role, bio, employmentStatus } = req.body;
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@server/controllers/employeeController.js` around lines 91 - 110, The
updateEmployee handler destructures req.body but omits joinDate while later
using joinDate in Employee.findByIdAndUpdate; add joinDate to the destructuring
list in updateEmployee (alongside firstName, lastName, email, etc.) so joinDate
is defined, and ensure the existing call to new Date(joinDate) remains valid
when passed to Employee.findByIdAndUpdate.
🧹 Nitpick comments (1)
package.json (1)

1-5: 💤 Low value

Consider adding package metadata and scripts.

Standard package.json files typically include:

  • name, version, description for package identification
  • author and license for attribution and compliance
  • scripts section for common tasks (start, dev, test, etc.)
  • engines to specify Node.js version requirements

While not blocking, these fields improve maintainability and documentation.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@package.json` around lines 1 - 5, package.json currently only lists
dependencies; add standard package metadata fields (name, version, description),
attribution fields (author, license), a scripts object with at least start, dev,
and test entries, and an engines field specifying supported Node.js versions;
update the existing package.json by inserting these keys at the top level so
tools and contributors can identify and run the package (refer to the
package.json top-level object and the "dependencies" key when locating where to
add the new fields).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@server/controllers/leaveController.js`:
- Around line 113-114: The validation array for the status check in
leaveController.js contains a typo ("AP[ROVED") causing valid "APPROVED"
statuses to be rejected; update the string list used in the includes check (the
array literal used where status is tested) to ["APPROVED", "REJECTED",
"PENDING"] so that the variable status is correctly validated against the proper
values (adjust the includes(...) call in the status validation block).
- Around line 117-122: After calling
LeaveApplication.findByIdAndUpdate(req.params.id, { status }, { returnDocument:
'after' }) in the leaveController, add a null check for the returned leave and
if it's null send a 404 response (e.g., res.status(404).json({ success: false,
error: 'Leave application not found' })) instead of returning success: true with
data: null; keep the existing successful res.json({ success: true, data: leave
}) path for non-null results.
- Around line 26-30: The date validation contains a duplicated condition and
doesn't check that endDate is after startDate; update the second check in
leaveController.js to compare parsed Dates (new Date(endDate) < new
Date(startDate)) and return the "end date must be greater than start date"
response, leaving the first check that ensures neither startDate nor endDate is
in the past (new Date(startDate) < today || new Date(endDate) < today) intact;
use the startDate and endDate symbols to locate and replace the duplicate
condition with the proper comparison.

In `@server/models/LeaveApplication.js`:
- Around line 16-23: The model allows endDate earlier than startDate; add a
validation on the LeaveApplication schema to reject such records: either add a
custom validator for the endDate field that checks (this.startDate && value >=
this.startDate) and returns a validation error message, or add a
schema.pre('validate', ...) hook on the LeaveApplication schema that
throws/invalidates when endDate < startDate; ensure the validation runs on
updates (use runValidators for update operations) so invalid ranges cannot be
persisted.
- Around line 6-8: The schema field employeeId in LeaveApplication.js uses the
misspelled mongoose.Schhema.Types.ObjectId which breaks model initialization;
change the reference to mongoose.Schema.Types.ObjectId (update the employeeId
definition) so the schema uses the correct ObjectId type.

---

Outside diff comments:
In `@server/controllers/employeeController.js`:
- Around line 91-110: The updateEmployee handler destructures req.body but omits
joinDate while later using joinDate in Employee.findByIdAndUpdate; add joinDate
to the destructuring list in updateEmployee (alongside firstName, lastName,
email, etc.) so joinDate is defined, and ensure the existing call to new
Date(joinDate) remains valid when passed to Employee.findByIdAndUpdate.

---

Nitpick comments:
In `@package.json`:
- Around line 1-5: package.json currently only lists dependencies; add standard
package metadata fields (name, version, description), attribution fields
(author, license), a scripts object with at least start, dev, and test entries,
and an engines field specifying supported Node.js versions; update the existing
package.json by inserting these keys at the top level so tools and contributors
can identify and run the package (refer to the package.json top-level object and
the "dependencies" key when locating where to add the new fields).
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 086cd9dd-f744-46de-bf52-a9ffb7b9db2c

📥 Commits

Reviewing files that changed from the base of the PR and between a4541cb and 2e5d412.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (10)
  • package.json
  • server/controllers/attendanceController.js
  • server/controllers/authController.js
  • server/controllers/employeeController.js
  • server/controllers/leaveController.js
  • server/middleware/auth.js
  • server/models/Employee.js
  • server/models/LeaveApplication.js
  • server/models/User.js
  • server/routes/AttendanceRoutes.js

Comment on lines +26 to +30
if (new Date(startDate) < today || new Date(endDate) < today)
return res.status(400).json({ message: "Please provide valid dates" });

if (new Date(endDate) < today || new Date(startDate) < today)
return res.status(400).json({ message: "end date must be greater than start date" });

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Critical bug: Date validation logic is incorrect and duplicated.

Lines 29-30 have the same condition as lines 26-27, making the second check unreachable and failing to validate that endDate >= startDate. Users can submit a leave where endDate is before startDate.

🐛 Proposed fix
         if (new Date(startDate) < today || new Date(endDate) < today)
             return res.status(400).json({ message: "Please provide valid dates" });

-        if (new Date(endDate) < today || new Date(startDate) < today)
+        if (new Date(endDate) < new Date(startDate))
             return res.status(400).json({ message: "end date must be greater than start date" });
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@server/controllers/leaveController.js` around lines 26 - 30, The date
validation contains a duplicated condition and doesn't check that endDate is
after startDate; update the second check in leaveController.js to compare parsed
Dates (new Date(endDate) < new Date(startDate)) and return the "end date must be
greater than start date" response, leaving the first check that ensures neither
startDate nor endDate is in the past (new Date(startDate) < today || new
Date(endDate) < today) intact; use the startDate and endDate symbols to locate
and replace the duplicate condition with the proper comparison.

Comment on lines +113 to +114
if (!["AP[ROVED", "REJECTED", "PENDING"].includes(status))
return res.status(400).json({ error: "invalid status" });

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Critical typo: "AP[ROVED" should be "APPROVED".

This typo causes all legitimate "APPROVED" status updates to be rejected with "invalid status" error.

🐛 Proposed fix
-        if (!["AP[ROVED", "REJECTED", "PENDING"].includes(status))
+        if (!["APPROVED", "REJECTED", "PENDING"].includes(status))
             return res.status(400).json({ error: "invalid status" });
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (!["AP[ROVED", "REJECTED", "PENDING"].includes(status))
return res.status(400).json({ error: "invalid status" });
if (!["APPROVED", "REJECTED", "PENDING"].includes(status))
return res.status(400).json({ error: "invalid status" });
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@server/controllers/leaveController.js` around lines 113 - 114, The validation
array for the status check in leaveController.js contains a typo ("AP[ROVED")
causing valid "APPROVED" statuses to be rejected; update the string list used in
the includes check (the array literal used where status is tested) to
["APPROVED", "REJECTED", "PENDING"] so that the variable status is correctly
validated against the proper values (adjust the includes(...) call in the status
validation block).

Comment on lines +117 to +122
const leave = await LeaveApplication.findByIdAndUpdate(req.params.id, { status }, { returnDocument: 'after' });

return res.json({
success: true,
data: leave
})

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Missing null check when leave is not found.

If req.params.id doesn't match any document, findByIdAndUpdate returns null and the response will indicate success with data: null. This should return a 404 error instead.

🐛 Proposed fix
         const leave = await LeaveApplication.findByIdAndUpdate(req.params.id, { status }, { returnDocument: 'after' });

+        if (!leave)
+            return res.status(404).json({ error: "Leave application not found" });
+
         return res.json({
             success: true,
             data: leave
         })
📝 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 leave = await LeaveApplication.findByIdAndUpdate(req.params.id, { status }, { returnDocument: 'after' });
return res.json({
success: true,
data: leave
})
const leave = await LeaveApplication.findByIdAndUpdate(req.params.id, { status }, { returnDocument: 'after' });
if (!leave)
return res.status(404).json({ error: "Leave application not found" });
return res.json({
success: true,
data: leave
})
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@server/controllers/leaveController.js` around lines 117 - 122, After calling
LeaveApplication.findByIdAndUpdate(req.params.id, { status }, { returnDocument:
'after' }) in the leaveController, add a null check for the returned leave and
if it's null send a 404 response (e.g., res.status(404).json({ success: false,
error: 'Leave application not found' })) instead of returning success: true with
data: null; keep the existing successful res.json({ success: true, data: leave
}) path for non-null results.

Comment on lines +6 to +8
employeeId: {
type: mongoose.Schhema.Types.ObjectId,
ref: "Employee",

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Verify the typo and expected Schema API usage
rg -n 'Schhema|Schema\.Types\.ObjectId' server/models/LeaveApplication.js

Repository: harshGupta090722/EMS

Length of output: 113


Fix typo in ObjectId type definition—Schhema is invalid and will break schema initialization at runtime.

Line 7 uses mongoose.Schhema.Types.ObjectId where Schhema is misspelled. The correct property is mongoose.Schema.Types.ObjectId. This typo will cause the model to fail when loaded.

Proposed fix
-        type: mongoose.Schhema.Types.ObjectId,
+        type: mongoose.Schema.Types.ObjectId,
📝 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
employeeId: {
type: mongoose.Schhema.Types.ObjectId,
ref: "Employee",
employeeId: {
type: mongoose.Schema.Types.ObjectId,
ref: "Employee",
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@server/models/LeaveApplication.js` around lines 6 - 8, The schema field
employeeId in LeaveApplication.js uses the misspelled
mongoose.Schhema.Types.ObjectId which breaks model initialization; change the
reference to mongoose.Schema.Types.ObjectId (update the employeeId definition)
so the schema uses the correct ObjectId type.

Comment on lines +16 to +23
startDate: {
type: Date,
required: true
},
endDate: {
type: Date,
required: true
},

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Add date-order validation for leave periods.

endDate can currently be earlier than startDate, which allows invalid leave applications to be persisted.

Proposed fix
     endDate: {
         type: Date,
-        required: true
+        required: true,
+        validate: {
+            validator: function (value) {
+                return !this.startDate || value >= this.startDate;
+            },
+            message: "endDate must be greater than or equal to startDate"
+        }
     },
📝 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
startDate: {
type: Date,
required: true
},
endDate: {
type: Date,
required: true
},
startDate: {
type: Date,
required: true
},
endDate: {
type: Date,
required: true,
validate: {
validator: function (value) {
return !this.startDate || value >= this.startDate;
},
message: "endDate must be greater than or equal to startDate"
}
},
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@server/models/LeaveApplication.js` around lines 16 - 23, The model allows
endDate earlier than startDate; add a validation on the LeaveApplication schema
to reject such records: either add a custom validator for the endDate field that
checks (this.startDate && value >= this.startDate) and returns a validation
error message, or add a schema.pre('validate', ...) hook on the LeaveApplication
schema that throws/invalidates when endDate < startDate; ensure the validation
runs on updates (use runValidators for update operations) so invalid ranges
cannot be persisted.

@harshGupta090722
harshGupta090722 merged commit 63292f4 into main Apr 30, 2026
1 check passed
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.

1 participant