targo-frontend/src/modules/employee-list/composables/use-employee-api.ts

86 lines
3.3 KiB
TypeScript

import { useEmployeeStore } from "src/stores/employee-store";
import { useSchedulePresetsStore } from "src/stores/schedule-presets.store";
import { SchedulePreset } from "../models/schedule-presets.models";
import { isShiftOverlap } from "src/modules/timesheets/utils/shift.util";
export const useEmployeeListApi = () => {
const employee_store = useEmployeeStore();
const schedule_preset_store = useSchedulePresetsStore();
const getEmployeeList = async (): Promise<void> => {
employee_store.is_loading = true;
const success = await employee_store.getEmployeeList();
if (success) await schedule_preset_store.findSchedulePresetList();
employee_store.is_loading = false;
};
const getEmployeeDetails = async (email: string): Promise<void> => {
const success = await employee_store.getEmployeeDetails(email);
if (success && employee_store.employee.preset_id !== null) {
schedule_preset_store.setCurrentSchedulePreset(employee_store.employee.preset_id ?? -1);
}
}
const setSchedulePreset = (preset_id: number) => {
schedule_preset_store.setCurrentSchedulePreset(preset_id);
employee_store.employee.preset_id = preset_id < 0 ? null : preset_id;
}
const saveSchedulePreset = async () => {
// Get the currently edited schedule preset from the store (frontend model)
const preset = schedule_preset_store.current_schedule_preset;
// Check if there's any overlap between shifts. If there is, is_error property
// will be toggled to true and save process will stop
for (const weekday of preset.weekdays) {
weekday.is_error = isShiftOverlap(weekday.shifts);
}
if (preset.weekdays.some(weekday => weekday.is_error)) {
return;
}
// Flatten all weekday shifts into a single array
const preset_shifts = preset.weekdays.flatMap(weekday => weekday.shifts);
// Build a backend-compatible SchedulePreset instance
const backend_preset = new SchedulePreset(
preset.id,
preset.name,
preset_shifts
);
// Track whether the create/update operation succeeds
let success = false;
// Create a new preset if it has no backend ID, otherwise update the existing one
if (preset.id === -1)
success = await schedule_preset_store.createSchedulePreset(backend_preset);
else
success = await schedule_preset_store.updateSchedulePreset(backend_preset);
// On success, refresh the preset list and close the preset manager UI
if (success) {
await schedule_preset_store.findSchedulePresetList();
schedule_preset_store.is_manager_open = false;
}
}
const deleteSchedulePreset = async (preset_id: number) => {
const success = await schedule_preset_store.deleteSchedulePreset(preset_id);
if (success) {
await schedule_preset_store.findSchedulePresetList();
schedule_preset_store.is_manager_open = false;
}
}
return {
getEmployeeList,
getEmployeeDetails,
setSchedulePreset,
saveSchedulePreset,
deleteSchedulePreset,
};
};