import { Injectable } from '@nestjs/common';
import { AuthService } from '@/auth/auth.service';
import { ApiClientService } from '@/shared/http/api-client.service';
import { CreateTimesheetEntryDto, FetchTimesheetEntriesDto } from './dto/create-timesheet.dto';
/**
* Service for timesheet operations
* Handles creating, fetching, and managing timesheet entries
*/
@Injectable()
export class TimesheetsService {
constructor(
private readonly authService: AuthService,
private readonly apiClient: ApiClientService,
) {}
/**
* Create a new timesheet entry
* @param params - Timesheet entry data
* @returns Created timesheet entry response
*/
async createTimesheetEntry(params: CreateTimesheetEntryDto) {
const user = this.authService.getCurrentUser();
const token = this.authService.getToken();
if (!user || !token) {
throw new Error('User not authenticated');
}
// Validate description length
if (params.description.length < 10) {
throw new Error('Description must be at least 10 characters long');
}
const payload = {
user_id: user.id,
project_id: params.project_id,
module_id: params.module_id,
activity_id: params.activity_id,
start_time: params.start_time,
end_time: params.end_time,
duration: params.duration,
description: params.description,
date: params.date,
managerId: user.managerId,
name: user.name,
};
try {
const response = await this.apiClient.createTimesheet(payload, token);
return response;
} catch (error) {
throw new Error(`Failed to create timesheet entry: ${error.message}`);
}
}
/**
* Fetch timesheet entries for current user with pagination
* @param params - Pagination parameters
* @returns Paginated timesheet entries
*/
async fetchTimesheetEntries(params: FetchTimesheetEntriesDto) {
const user = this.authService.getCurrentUser();
const token = this.authService.getToken();
if (!user || !token) {
throw new Error('User not authenticated');
}
// Ensure limit doesn't exceed 100
const limit = Math.min(params.limit || 10, 100);
const page = params.page || 1;
try {
const response = await this.apiClient.getTimesheets(user.id, page, limit, token);
return {
data: response,
pagination: {
page,
limit,
userId: user.id,
},
};
} catch (error) {
throw new Error(`Failed to fetch timesheet entries: ${error.message}`);
}
}
}