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
46 changes: 45 additions & 1 deletion app-backend/src/controllers/payroll.controller.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { buildPayrollSummary } from "../services/payroll.service.js";
import { buildPayrollCsv, buildPayrollSummary } from "../services/payroll.service.js";

export const getPayrollSummary = async (req, res) => {
try {
Expand Down Expand Up @@ -38,4 +38,48 @@ export const getPayrollSummary = async (req, res) => {
error: error.message,
});
}
};

export const exportPayrollCsv = async (req, res) => {
try {
const csv = await buildPayrollCsv(req.query, req.user);

res.setHeader("Content-Type", "text/csv");
res.setHeader("Content-Disposition", 'attachment; filename="payroll-export.csv"');

return res.status(200).send(csv);
} catch (error) {
if (
error.message.includes("required") ||
error.message.includes("periodType") ||
error.message.includes("ISO") ||
error.message.includes("Invalid startDate") ||
error.message.includes("after")
) {
return res.status(400).json({
message: error.message,
});
}

if (
error.message.includes("Forbidden") ||
error.message.includes("only access their own") ||
error.message.includes("unsupported role")
) {
return res.status(403).json({
message: error.message,
});
}

if (error.message.includes("Unauthorised")) {
return res.status(401).json({
message: error.message,
});
}

return res.status(500).json({
message: "Failed to export payroll CSV",
error: error.message,
});
}
};
87 changes: 85 additions & 2 deletions app-backend/src/routes/payroll.routes.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import express from "express";
import auth from "../middleware/auth.js";
import { getPayrollSummary } from "../controllers/payroll.controller.js";
import { exportPayrollCsv, getPayrollSummary } from "../controllers/payroll.controller.js";

const router = express.Router();

Expand Down Expand Up @@ -78,6 +78,89 @@ const authorizeRole = (...allowedRoles) => (req, res, next) => {
* 500:
* description: Server error
*/
router.get("/", auth, authorizeRole("admin", "employer", "guard"), getPayrollSummary);
router.get(
"/",
auth,
authorizeRole("admin", "employer", "guard"),
getPayrollSummary,
);

/**
* @swagger
* /api/v1/payroll/export:
* get:
* summary: Export payroll summary as CSV
* description: |
* Exports generated payroll data as a CSV file.
*
* Role access:
* - Admin: can export payroll summaries for all guards, optionally filtered
* - Employer: can export payroll summaries only for completed shifts they created
* - Guard: can export only their own payroll summary
* tags: [Payroll]
* security:
* - bearerAuth: []
* parameters:
* - in: query
* name: startDate
* required: true
* schema:
* type: string
* format: date
* description: Start date in ISO format YYYY-MM-DD
* - in: query
* name: endDate
* required: true
* schema:
* type: string
* format: date
* description: End date in ISO format YYYY-MM-DD
* - in: query
* name: periodType
* required: true
* schema:
* type: string
* enum: [daily, weekly, monthly]
* description: Aggregation type for payroll summaries
* - in: query
* name: guardId
* required: false
* schema:
* type: string
* description: Optional filter for a specific guard
* - in: query
* name: site
* required: false
* schema:
* type: string
* description: Optional filter for a specific site
* - in: query
* name: department
* required: false
* schema:
* type: string
* description: Optional filter for a specific department
* responses:
* 200:
* description: Payroll CSV exported successfully
* content:
* text/csv:
* schema:
* type: string
* 400:
* description: Invalid request parameters
* 401:
* description: Unauthorised
* 403:
* description: Forbidden
* 500:
* description: Server error
*/
router.get(
"/export",
auth,
authorizeRole("admin", "employer", "guard"),
exportPayrollCsv,
);

export default router;
50 changes: 47 additions & 3 deletions app-backend/src/services/payroll.service.js
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,20 @@ const calculateScheduledHours = (shift) => {
return (scheduledEnd - scheduledStart) / (1000 * 60 * 60);
};

const escapeCsvValue = (value) => {
if (value === null || value === undefined) {
return "";
}

const stringValue = String(value);

if (stringValue.includes(",") || stringValue.includes('"') || stringValue.includes("\n")) {
return `"${stringValue.replaceAll('"', '""')}"`;
}

return stringValue;
};

export const buildPayrollSummary = async (query, user) => {
const { startDate, endDate, periodType, guardId, site, department } = query;

Expand Down Expand Up @@ -111,13 +125,11 @@ export const buildPayrollSummary = async (query, user) => {
},
};

// Role-based access rules
if (user.role === "admin") {
if (guardId) {
shiftQuery.acceptedBy = guardId;
}
} else if (user.role === "employer") {
// current scoping uses shift ownership
shiftQuery.createdBy = user._id;

if (guardId) {
Expand All @@ -137,7 +149,6 @@ export const buildPayrollSummary = async (query, user) => {
shiftQuery.location = site;
}

// depends on current Shift model support
if (department) {
shiftQuery.field = department;
}
Expand Down Expand Up @@ -276,4 +287,37 @@ export const buildPayrollSummary = async (query, user) => {
periods,
payrollDetails,
};
};

export const buildPayrollCsv = async (query, user) => {
const payrollData = await buildPayrollSummary(query, user);

const headers = [
"shiftId",
"guardId",
"guardName",
"employerId",
"location",
"department",
"date",
"scheduledHours",
"totalHours",
"overtimeHours",
"underworkedShift",
"pendingApproval",
"attendanceStatus",
];

const rows = payrollData.payrollDetails.map((item) =>
headers
.map((header) => {
const value =
header === "date" && item[header] ? new Date(item[header]).toISOString() : item[header];

return escapeCsvValue(value);
})
.join(","),
);

return [headers.join(","), ...rows].join("\n");
};
2 changes: 1 addition & 1 deletion guard_app/app.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,6 @@
}
},
"owner": "secureshift-guardapp",
"plugins": ["@react-native-community/datetimepicker"]
"plugins": []
}
}
Loading
Loading