Skip to content

Commit

Permalink
[Feat]: Add Delete Task Timesheet function (#3338)
Browse files Browse the repository at this point in the history
* Add deleteTaskTimesheet function to handle timesheet deletion

* fix: coderabbitai

* fix: build

* feat: make AlertDialogConfirmation fully controllable via external props

* fix: coderabbitai

* fix: coderabbitai
  • Loading branch information
Innocent-Akim authored Nov 17, 2024
1 parent aace163 commit 5c1cada
Show file tree
Hide file tree
Showing 15 changed files with 484 additions and 69 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -24,23 +24,25 @@ export const TimesheetButton = ({ className, icon, onClick, title }: ITimesheetB


export type StatusType = "Pending" | "Approved" | "Rejected";
export type StatusAction = "Deleted" | "Approved" | "Rejected";


// eslint-disable-next-line @typescript-eslint/no-empty-function
export const getTimesheetButtons = (status: StatusType, t: TranslationHooks, onClick: (action: StatusType) => void) => {
export const getTimesheetButtons = (status: StatusType, t: TranslationHooks, onClick: (action: StatusAction) => void) => {

const buttonsConfig: Record<StatusType, { icon: JSX.Element; title: string; action: StatusType }[]> = {
const buttonsConfig: Record<StatusType, { icon: JSX.Element; title: string; action: StatusAction }[]> = {
Pending: [
{ icon: <FaClipboardCheck className="!text-[#2932417c] dark:!text-gray-400 rounded" />, title: t('pages.timesheet.TIMESHEET_ACTION_APPROVE_SELECTED'), action: "Approved" },
{ icon: <IoClose className="!bg-[#2932417c] dark:!bg-gray-400 rounded" />, title: t('pages.timesheet.TIMESHEET_ACTION_REJECT_SELECTED'), action: "Rejected" },
{ icon: <RiDeleteBin6Fill className="!text-[#2932417c] dark:!text-gray-400 rounded" />, title: t('pages.timesheet.TIMESHEET_ACTION_DELETE_SELECTED'), action: "Pending" }
{ icon: <RiDeleteBin6Fill className="!text-[#2932417c] dark:!text-gray-400 rounded" />, title: t('pages.timesheet.TIMESHEET_ACTION_DELETE_SELECTED'), action: "Deleted" }
],
Approved: [
{ icon: <IoClose className="!bg-[#2932417c] dark:!bg-gray-400 rounded" />, title: t('pages.timesheet.TIMESHEET_ACTION_REJECT_SELECTED'), action: "Rejected" },
{ icon: <RiDeleteBin6Fill className="!text-[#2932417c] dark:!text-gray-400 rounded" />, title: t('pages.timesheet.TIMESHEET_ACTION_DELETE_SELECTED'), action: "Pending" }
{ icon: <RiDeleteBin6Fill className="!text-[#2932417c] dark:!text-gray-400 rounded" />, title: t('pages.timesheet.TIMESHEET_ACTION_DELETE_SELECTED'), action: "Deleted" }
],
Rejected: [
{ icon: <FaClipboardCheck className="!text-[#2932417c] dark:!text-gray-400 rounded" />, title: t('pages.timesheet.TIMESHEET_ACTION_APPROVE_SELECTED'), action: "Approved" },
{ icon: <RiDeleteBin6Fill className="!text-[#2932417c] dark:!text-gray-400 rounded" />, title: t('pages.timesheet.TIMESHEET_ACTION_DELETE_SELECTED'), action: "Pending" }
{ icon: <RiDeleteBin6Fill className="!text-[#2932417c] dark:!text-gray-400 rounded" />, title: t('pages.timesheet.TIMESHEET_ACTION_DELETE_SELECTED'), action: "Deleted" }
]
};

Expand Down
42 changes: 42 additions & 0 deletions apps/web/app/api/timer/timesheet/bulk-delete/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { deleteTaskTimesheetRequest } from '@/app/services/server/requests';
import { authenticatedGuard } from '@app/services/server/guards/authenticated-guard-app';
import { NextResponse } from "next/server";

export async function DELETE(req: Request) {
const res = new NextResponse();
const body = await req.json();
const { logIds = [] } = body;

if (!Array.isArray(logIds) || logIds.length === 0) {
return NextResponse.json(
{ error: 'logIds must be a non-empty array' },
{ status: 400 }
);
}

const { $res, user, tenantId, organizationId, access_token, } = await authenticatedGuard(req, res);
if (!user) return $res('Unauthorized');
try {
const { data } = await deleteTaskTimesheetRequest({
tenantId,
organizationId,
logIds,
}, access_token);

if (!data) {
return NextResponse.json(
{ error: 'No data found' },
{ status: 404 }
);
}

return NextResponse.json(data);
} catch (error) {
console.error('Error delete timesheet:', error);
return NextResponse.json(
{ error: 'Failed to delete timesheet data' },
{ status: 500 }
);
}

}
15 changes: 13 additions & 2 deletions apps/web/app/hooks/features/useTimelogFilterOptions.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,24 @@
import { timesheetFilterEmployeeState, timesheetFilterProjectState, timesheetFilterStatusState, timesheetFilterTaskState } from '@/app/stores';
import { timesheetDeleteState, timesheetFilterEmployeeState, timesheetFilterProjectState, timesheetFilterStatusState, timesheetFilterTaskState } from '@/app/stores';
import { useAtom } from 'jotai';
import React from 'react';

export function useTimelogFilterOptions() {
const [employeeState, setEmployeeState] = useAtom(timesheetFilterEmployeeState);
const [projectState, setProjectState] = useAtom(timesheetFilterProjectState);
const [statusState, setStatusState] = useAtom(timesheetFilterStatusState);
const [taskState, setTaskState] = useAtom(timesheetFilterTaskState);
const [selectTimesheet, setSelectTimesheet] = useAtom(timesheetDeleteState);

const employee = employeeState;
const project = projectState;
const task = taskState

const handleSelectRowTimesheet = (items: string) => {
setSelectTimesheet((prev) => prev.includes(items) ? prev.filter((filter) => filter !== items) : [...prev, items])
}
React.useEffect(() => {
return () => setSelectTimesheet([]);
}, []);

return {
statusState,
Expand All @@ -20,6 +28,9 @@ export function useTimelogFilterOptions() {
setEmployeeState,
setProjectState,
setTaskState,
setStatusState
setStatusState,
handleSelectRowTimesheet,
selectTimesheet,
setSelectTimesheet
};
}
47 changes: 44 additions & 3 deletions apps/web/app/hooks/features/useTimesheet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { useAtom } from 'jotai';
import { timesheetRapportState } from '@/app/stores/time-logs';
import { useQuery } from '../useQuery';
import { useCallback, useEffect } from 'react';
import { getTaskTimesheetLogsApi } from '@/app/services/client/api/timer/timer-log';
import { deleteTaskTimesheetLogsApi, getTaskTimesheetLogsApi } from '@/app/services/client/api/timer/timer-log';
import moment from 'moment';
import { ITimeSheet } from '@/app/interfaces';
import { useTimelogFilterOptions } from './useTimelogFilterOptions';
Expand All @@ -17,7 +17,11 @@ export interface GroupedTimesheet {
date: string;
tasks: ITimeSheet[];
}

interface DeleteTimesheetParams {
organizationId: string;
tenantId: string;
logIds: string[];
}

const groupByDate = (items: ITimeSheet[]): GroupedTimesheet[] => {
if (!items?.length) return [];
Expand Down Expand Up @@ -46,8 +50,10 @@ export function useTimesheet({
}: TimesheetParams) {
const { user } = useAuthenticateUser();
const [timesheet, setTimesheet] = useAtom(timesheetRapportState);
const { employee, project } = useTimelogFilterOptions();
const { employee, project, selectTimesheet: logIds } = useTimelogFilterOptions();
const { loading: loadingTimesheet, queryCall: queryTimesheet } = useQuery(getTaskTimesheetLogsApi);
const { loading: loadingDeleteTimesheet, queryCall: queryDeleteTimesheet } = useQuery(deleteTaskTimesheetLogsApi)


const getTaskTimesheet = useCallback(
({ startDate, endDate }: TimesheetParams) => {
Expand Down Expand Up @@ -76,6 +82,39 @@ export function useTimesheet({
project
]
);



const handleDeleteTimesheet = async (params: DeleteTimesheetParams) => {
try {
return await queryDeleteTimesheet(params);
} catch (error) {
console.error('Error deleting timesheet:', error);
throw error;
}
};

const deleteTaskTimesheet = useCallback(async () => {
if (!user) {
throw new Error('User not authenticated');
}
if (!logIds.length) {
throw new Error('No timesheet IDs provided for deletion');
}
try {
await handleDeleteTimesheet({
organizationId: user.employee.organizationId,
tenantId: user.tenantId ?? "",
logIds
});
} catch (error) {
console.error('Failed to delete timesheets:', error);
throw error;
}
},
[user, queryDeleteTimesheet, logIds, handleDeleteTimesheet] // deepscan-disable-line
);

useEffect(() => {
getTaskTimesheet({ startDate, endDate });
}, [getTaskTimesheet, startDate, endDate]);
Expand All @@ -86,5 +125,7 @@ export function useTimesheet({
loadingTimesheet,
timesheet: groupByDate(timesheet),
getTaskTimesheet,
loadingDeleteTimesheet,
deleteTaskTimesheet
};
}
41 changes: 40 additions & 1 deletion apps/web/app/services/client/api/timer/timer-log.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { ITimeSheet, ITimerStatus } from '@app/interfaces';
import { get } from '../../axios';
import { get, deleteApi } from '../../axios';

export async function getTimerLogs(
tenantId: string,
Expand Down Expand Up @@ -66,3 +66,42 @@ export async function getTaskTimesheetLogsApi({
const endpoint = `/timesheet/time-log?${params.toString()}`;
return get<ITimeSheet[]>(endpoint, { tenantId });
}


export async function deleteTaskTimesheetLogsApi({
logIds,
organizationId,
tenantId
}: {
organizationId: string,
tenantId: string,
logIds: string[]
}) {
// Validate required parameters
if (!organizationId || !tenantId || !logIds?.length) {
throw new Error('Required parameters missing: organizationId, tenantId, and logIds are required');
}

// Limit bulk deletion size for safety
if (logIds.length > 100) {
throw new Error('Maximum 100 logs can be deleted at once');
}

const params = new URLSearchParams({
organizationId,
tenantId
});
logIds.forEach((id, index) => {
if (!id) {
throw new Error(`Invalid logId at index ${index}`);
}
params.append(`logIds[${index}]`, id);
});

const endPoint = `/timesheet/time-log?${params.toString()}`;
try {
return await deleteApi<{ success: boolean; message: string }>(endPoint, { tenantId });
} catch (error) {
throw new Error(`Failed to delete timesheet logs`);
}
}
16 changes: 16 additions & 0 deletions apps/web/app/services/server/requests/timesheet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,3 +79,19 @@ export function getTaskTimesheetRequest(params: ITimesheetProps, bearer_token: s
tenantId: params.tenantId
})
}

type IDeleteTimesheetProps = {
organizationId: string;
tenantId: string;
logIds?: string[]
}

export function deleteTaskTimesheetRequest(params: IDeleteTimesheetProps, bearer_token: string) {
const { logIds = [] } = params;
return serverFetch<ITimeSheet[]>({
path: `/timesheet/time-log/${logIds.join(',')}`,
method: 'DELETE',
bearer_token,
tenantId: params.tenantId
});
}
1 change: 1 addition & 0 deletions apps/web/app/stores/time-logs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,4 @@ export const timesheetFilterProjectState = atom<IProject[]>([]);
export const timesheetFilterTaskState = atom<ITeamTask[]>([]);

export const timesheetFilterStatusState = atom<IFilterOption | IFilterOption[] | null>([]);
export const timesheetDeleteState = atom<string[]>([])
Loading

0 comments on commit 5c1cada

Please sign in to comment.