Skip to content
Merged
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
28 changes: 25 additions & 3 deletions guard_app/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions guard_app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,14 @@
"expo-dev-client": "~6.0.21",
"expo-device": "~8.0.10",
"expo-document-picker": "~14.0.8",
"expo-file-system": "~19.0.22",
"expo-image-picker": "~17.0.11",
"expo-localization": "~17.0.8",
"expo-location": "~19.0.8",
"expo-modules-autolinking": "~3.0.22",
"expo-notifications": "~0.32.17",
"expo-print": "~15.0.8",
"expo-sharing": "~14.0.8",
"expo-status-bar": "~3.0.9",
"i18next": "^26.0.6",
"react": "19.1.0",
Expand Down
222 changes: 109 additions & 113 deletions guard_app/src/api/payroll.ts
Original file line number Diff line number Diff line change
@@ -1,130 +1,126 @@
// src/api/payroll.ts
import http from '../lib/http';
import * as FileSystem from 'expo-file-system';
import * as Print from 'expo-print';
import * as Sharing from 'expo-sharing';
import { Platform } from 'react-native';

import http, { API_BASE_URL, API_PATH } from '../lib/http';
import { LocalStorage } from '../lib/localStorage';

export type PayrollPeriodType = 'daily' | 'weekly' | 'monthly';
export type PayrollStatus = 'PENDING' | 'APPROVED' | 'PROCESSED';
export type PayrollExportFormat = 'csv' | 'pdf';

export interface PayrollEntry {
shift: string;
attendance: string | null;
shiftDate: string;
scheduledHours: number;
actualHours: number;
regularHours: number;
overtimeHours: number;
payRate: number;
regularPay: number;
overtimePay: number;
totalPay: number;
hasAttendanceRecord: boolean;
attendanceStatus: 'present' | 'absent' | 'incomplete' | 'scheduled' | 'no_record';
}

export interface PayrollRecord {
_id: string;
guard: string;
period: {
type: PayrollPeriodType;
startDate: string;
endDate: string;
};
entries: PayrollEntry[];
totalScheduledHours: number;
totalWorkedHours: number;
totalRegularHours: number;
totalOvertimeHours: number;
grossPay: number;
status: PayrollStatus;
approvedBy?: any;
approvedAt?: string;
processedBy?: any;
processedAt?: string;
guardName: string;
guardEmail: string;
guardRole: string;
guardDepartment?: string;
createdAt: string;
updatedAt: string;
}
export type PayrollSummaryParams = {
startDate: string;
endDate: string;
periodType: PayrollPeriodType;
};

export interface PayrollSummary {
export type PayrollSummary = {
totalCompletedShifts: number;
totalAttendanceRecords: number;
totalGuards: number;
totalWorkedHours: number;
totalHours: number;
totalOvertimeHours: number;
totalGrossPay: number;
}
totalPendingApproval: number;
};

export interface PayrollResponse {
period: {
type: PayrollPeriodType;
startDate: string;
endDate: string;
};
export type PayrollResponse = {
message: string;
summary: PayrollSummary;
records: PayrollRecord[];
}

export interface ShiftAttendanceRecord {
_id: string;
shift: string;
guard: any;
clockIn: string | null;
clockOut: string | null;
scheduledStart: string;
scheduledEnd: string;
hoursWorked: number;
status: 'scheduled' | 'present' | 'incomplete' | 'absent';
notes?: string;
recordedBy?: any;
createdAt: string;
updatedAt: string;
}

export interface ShiftAttendanceListResponse {
shiftId: string;
count: number;
records: ShiftAttendanceRecord[];
}
guards: {
guardId: string | null;
guardName: string | null;
totalShifts: number;
totalHours: number;
overtimeHours: number;
underworkedShifts: number;
pendingApproval: number;
}[];
periods: {
periodLabel: string;
totalShifts: number;
totalHours: number;
overtimeHours: number;
underworkedShifts: number;
pendingApproval: number;
}[];
};

/**
* Retrieve (and generate / refresh) payroll summaries.
*/
export async function getPayroll(params: {
startDate: string;
endDate: string;
periodType: PayrollPeriodType;
guardId?: string;
department?: string;
}) {
export async function getPayrollSummary(params: PayrollSummaryParams) {
const { data } = await http.get<PayrollResponse>('/payroll', { params });
return data;
}

/**
* Export payroll data as CSV or PDF.
* Note: For mobile, you might want to handle the blob or return the URL.
*/
export async function exportPayroll(params: {
startDate: string;
endDate: string;
periodType: PayrollPeriodType;
format?: PayrollExportFormat;
guardId?: string;
department?: string;
status?: PayrollStatus;
}) {
const { data } = await http.get('/payroll/export', {
params,
responseType: 'blob',
export async function exportPayrollCsv(params: PayrollSummaryParams) {
const token = await LocalStorage.getToken();

const searchParams = new URLSearchParams({
startDate: params.startDate,
endDate: params.endDate,
periodType: params.periodType,
}).toString();

const url = `${API_BASE_URL}${API_PATH}/payroll/export?${searchParams}`;

const response = await fetch(url, {
method: 'GET',
headers: token
? {
Authorization: `Bearer ${token}`,
}
: undefined,
});

if (!response.ok) {
throw new Error('Failed to export payroll CSV');
}

if (Platform.OS === 'web') {
const blob = await response.blob();
const downloadUrl = window.URL.createObjectURL(blob);
const link = document.createElement('a');

link.href = downloadUrl;
link.download = `payroll-export-${params.startDate}-to-${params.endDate}.csv`;

document.body.appendChild(link);
link.click();
document.body.removeChild(link);

window.URL.revokeObjectURL(downloadUrl);
return;
}

const csvContent = await response.text();
const fileUri = `${FileSystem.Paths.cache.uri}payroll-export-${params.startDate}-to-${params.endDate}.csv`;

const file = new FileSystem.File(fileUri);
await file.write(csvContent);

const canShare = await Sharing.isAvailableAsync();

if (!canShare) {
throw new Error('Sharing is not available on this device.');
}

await Sharing.shareAsync(fileUri, {
mimeType: 'text/csv',
dialogTitle: 'Export Payroll CSV',
UTI: 'public.comma-separated-values-text',
});
return data;
}

/**
* Get attendance records for a specific shift.
*/
export async function getAttendanceForShift(shiftId: string) {
const { data } = await http.get<ShiftAttendanceListResponse>(`/payroll/attendance/${shiftId}`);
return data;
export async function exportPayrollPdf(html: string) {
const { uri } = await Print.printToFileAsync({ html });

const canShare = await Sharing.isAvailableAsync();

if (!canShare) {
throw new Error('Sharing is not available on this device.');
}

await Sharing.shareAsync(uri, {
mimeType: 'application/pdf',
dialogTitle: 'Export Payroll PDF',
UTI: 'com.adobe.pdf',
});
}
Loading
Loading