Compare commits

...

34 Commits

Author SHA1 Message Date
Melina Gutierrez
b58a833444 Merge remote-tracking branch 'origin/hoursworked' into hoursworked
Some checks failed
PR Builder / Build-PR (pull_request) Failing after 21s
# Conflicts:
#	src/main/java/com/primefactorsolutions/model/Actividad.java
#	src/main/java/com/primefactorsolutions/service/HoursWorkedService.java
#	src/main/java/com/primefactorsolutions/views/EmployeeView.java
#	src/main/java/com/primefactorsolutions/views/HoursWorkedView.java
#	src/main/java/com/primefactorsolutions/views/ReporteView.java
2024-11-09 12:58:42 -04:00
Melina Gutierrez
ca2cd583a0 #45-Registro Semanal de Horas Trabajadas mas Reporte Excel 2024-11-09 12:43:31 -04:00
Melina Gutierrez
36287611b8 hoursworked sin reporte vista 2024-11-09 11:43:42 -04:00
Melina Gutierrez
5a0aa27382 primer commit 2024-11-09 11:42:54 -04:00
1ab10e286e Merge pull request 'En-desarrollo' (#65) from En-desarrollo into main
All checks were successful
Builder / Build-Project (push) Successful in 2m37s
Reviewed-on: #65
2024-11-09 12:15:26 +00:00
3922220439 Resolver errores de checkstyle
All checks were successful
PR Builder / Build-PR (pull_request) Successful in 2m33s
2024-11-07 18:53:47 -04:00
6024b3fdd0 Resolved merge conflict in RequestsListView.java
Some checks failed
PR Builder / Build-PR (pull_request) Failing after 17s
2024-11-07 18:45:01 -04:00
5e37cbbcd0 Perfil de Personal Administrativo - Listado Vacaciones de empleado (Calcular automadicamente dias de las vacaciones gestion actual y anterior) 2024-11-07 18:40:34 -04:00
f7e7dea7cb #37 Perfil de Personal Administrativo - Listado General de Vacaciones (Calcular automadicamente dias de las vacaciones gestion actual y anterior)
Some checks failed
PR Builder / Build-PR (pull_request) Failing after 21s
2024-11-07 18:31:05 -04:00
cb34868b9c Descarte funcionalidad generar automaticamente solicitud vacacion
All checks were successful
PR Builder / Build-PR (pull_request) Successful in 2m42s
2024-11-07 15:42:42 -04:00
d3fdb128b7 Merge branch 'En-desarrollo' of https://git.primefactorsolutions.com/PFS/pfs-intra into En-desarrollo
All checks were successful
PR Builder / Build-PR (pull_request) Successful in 2m37s
2024-11-07 02:18:18 -04:00
91aad85146 #5, #6 Perfil de Empleado - GUARDAR y EDITAR Información de Empleados (Refactorizacion generar solicitudes vacaciones) 2024-11-07 02:17:27 -04:00
9a29f91994 Merge pull request '#5, #6 Perfil de Empleado - GUARDAR y EDITAR Información de Empleados (Asignar o actualizar vacaciones)' (#68) from Vacaciones into En-desarrollo
Some checks failed
PR Builder / Build-PR (pull_request) Failing after 19s
Reviewed-on: #68
2024-11-06 18:56:16 +00:00
ed88936683 Resolviendo conflictos y finalizando fusión entre ramas Vacaciones y En-desarrollo
All checks were successful
PR Builder / Build-PR (pull_request) Successful in 0s
2024-11-06 14:55:53 -04:00
a0bd00fba4 #5, #6 Perfil de Empleado - GUARDAR y EDITAR Información de Empleados (Asignar o actualizar vacaciones)
All checks were successful
PR Builder / Build-PR (pull_request) Successful in 0s
2024-11-06 14:49:02 -04:00
81acc686e6 Merge pull request 'Correccion registro solicitud vacaciones actual y anterior' (#67) from Vacaciones into En-desarrollo
Some checks failed
PR Builder / Build-PR (pull_request) Failing after 19s
Reviewed-on: #67
2024-11-05 18:59:37 +00:00
9fdf1c08b5 Correccion registro solicitud vacaciones actual y anterior
All checks were successful
PR Builder / Build-PR (pull_request) Successful in 0s
2024-11-05 14:58:28 -04:00
4f128fd02e Merge pull request 'Vacaciones' (#66) from Vacaciones into En-desarrollo
Some checks failed
PR Builder / Build-PR (pull_request) Failing after 22s
Reviewed-on: #66
2024-11-05 18:32:42 +00:00
88e80a7dcc traducir a español y cambiar uso de grid a paging grid de RequestEmploye
All checks were successful
PR Builder / Build-PR (pull_request) Successful in 1s
2024-11-05 13:33:00 -04:00
7e415ae837 cambiar team string a un team class 2024-11-05 10:47:16 -04:00
2b6400fe24 Merge branch 'En-desarrollo' of https://git.primefactorsolutions.com/PFS/pfs-intra into En-desarrollo
All checks were successful
PR Builder / Build-PR (pull_request) Successful in 2m35s
2024-11-04 00:49:43 -04:00
4615febec3 Actualizar BD - Actualizar el estado de los registros de solicitudes de vacaciones 2024-11-04 00:48:59 -04:00
9d87493f7d Merge pull request 'Vacaciones' (#64) from Vacaciones into En-desarrollo
All checks were successful
PR Builder / Build-PR (pull_request) Successful in 2m27s
Reviewed-on: #64
2024-11-04 04:25:22 +00:00
eb6183df19 Correcciones
All checks were successful
PR Builder / Build-PR (pull_request) Successful in 0s
2024-11-04 00:24:34 -04:00
45bf76c3d8 Actualizar BD - Actualizar el estado de los registros de solicitudes de vacaciones 2024-11-04 00:19:12 -04:00
cfd5599d32 #55 Perfil de Personal Administrativo - Añadir Vacaciones del Empleado (No aceptar fechas pasadas) 2024-11-03 23:40:13 -04:00
4421c6fe45 #55 Perfil de Personal Administrativo - Añadir Vacaciones del Empleado (correcciones) 2024-11-03 23:22:09 -04:00
71cb2d67c9 Perfil de Personal Administrativo - Listado solicitudes pendientes de Vacaciones 2024-11-02 00:51:21 -04:00
3efa8c73d5 Traducir a epañol las sentencias de incercion de datos 2024-11-01 13:42:23 -04:00
c0cc1e86de Categoria vacaciones - traducirlo al español 2024-10-31 01:42:33 -04:00
a02499d53f Estado de la solicitud - traducirlo al español 2024-10-31 01:34:18 -04:00
ca630ef5c6 #37 Perfil de Personal Administrativo - Listado General de Vacaciones (Tracducir a español) 2024-10-31 01:29:59 -04:00
f7ab9f8421 #37 Perfil de Personal Administrativo - Listado General de Vacaciones (Modificar calcular total general) 2024-10-31 01:16:48 -04:00
94e7432551 #37 Perfil de Personal Administrativo - Listado General de Vacaciones (Modificar estado del empleado) 2024-10-30 15:10:05 -04:00
20 changed files with 1170 additions and 422 deletions

View File

@ -1,8 +1,5 @@
package com.primefactorsolutions.model; package com.primefactorsolutions.model;
import java.util.ArrayList;
import java.util.List;
public final class Actividad { public final class Actividad {
private String nombre; private String nombre;
private double lunes; private double lunes;
@ -12,11 +9,9 @@ public final class Actividad {
private double viernes; private double viernes;
private double sabado; private double sabado;
private double domingo; private double domingo;
private String nombreActivEsp; private String tarea;
private double horas; private double horas;
private static final List<Actividad> actividadesExistentes = new ArrayList<>();
public Actividad(final Builder builder) { public Actividad(final Builder builder) {
this.nombre = builder.nombre; this.nombre = builder.nombre;
this.lunes = builder.lunes; this.lunes = builder.lunes;
@ -26,7 +21,7 @@ public final class Actividad {
this.viernes = builder.viernes; this.viernes = builder.viernes;
this.sabado = builder.sabado; this.sabado = builder.sabado;
this.domingo = builder.domingo; this.domingo = builder.domingo;
this.nombreActivEsp = builder.nombreActivEsp; // Cambié aquí también this.tarea = builder.tarea;
this.horas = builder.horas; this.horas = builder.horas;
} }
@ -62,8 +57,8 @@ public final class Actividad {
return domingo; return domingo;
} }
public String getNombreActivEsp() { // Cambié aquí también public String getTarea() { // Cambié aquí también
return nombreActivEsp; return tarea;
} }
public double getHoras() { public double getHoras() {
@ -80,17 +75,17 @@ public final class Actividad {
private double viernes; private double viernes;
private double sabado; private double sabado;
private double domingo; private double domingo;
private String nombreActivEsp; // Cambié 'tarea' por 'descripcion' private String tarea; // Cambié 'tarea' por 'descripcion'
private double horas; private double horas;
public Builder nombreActivEsp(final String nombreActivEsp, final double horas) { public Builder tarea(final String tarea, final double horas) {
this.nombreActivEsp = nombreActivEsp; this.tarea = tarea;
this.horas = horas; this.horas = horas;
return this; return this;
} }
public Builder nombreActivEsp(final String nombreActivEsp) { public Builder tarea(final String tarea) {
this.nombreActivEsp = nombreActivEsp; this.tarea = tarea;
return this; return this;
} }

View File

@ -1,15 +1,15 @@
package com.primefactorsolutions.model; package com.primefactorsolutions.model;
public enum TimeOffRequestStatus { public enum TimeOffRequestStatus {
ALL, TODOS,
TAKEN, TOMADO,
REQUESTED, SOLICITADO,
APPROVED, APROBADO,
IN_USE, EN_USO,
UNDER_REVIEW, EN_REVISION,
PENDING, PENDIENTE,
REJECTED, RECHAZADO,
COMPLETED, COMPLETADO,
CANCELLED, CANCELADO,
EXPIRED VENCIDO
} }

View File

@ -1,29 +1,31 @@
package com.primefactorsolutions.model; package com.primefactorsolutions.model;
public enum TimeOffRequestType { public enum TimeOffRequestType {
ALL, TODOS,
NEW_YEAR, AÑO_NUEVO,
MONDAY_CARNIVAL, LUNES_CARNAVAL,
TUESDAY_CARNIVAL, MARTES_CARNAVAL,
GOOD_FRIDAY, VIERNES_SANTO,
LABOR_DAY, DIA_DEL_TRABAJADOR,
INDEPENDENCE_DAY, DIA_DE_LA_INDEPENDENCIA,
CHRISTMAS, NAVIDAD,
PRURINATIONAL_STATE_DAY, DIA_DEL_ESTADO_PLURINACIONAL,
CORPUS_CHRISTI, CORPUS_CHRISTI,
ANDEAN_NEW_YEAR, AÑO_NUEVO_ANDINO,
DEPARTMENTAL_ANNIVERSARY, ANIVERSARIO_DEPARTAMENTAL,
ALL_SOULS_DAY, DIA_DE_TODOS_LOS_DIFUNTOS,
BIRTHDAY, CUMPLEAÑOS,
MATERNITY, MATERNIDAD,
PATERNITY, PATERNIDAD,
MARRIAGE, MATRIMONIO,
FATHERS_DAY, DUELO_1ER_GRADO,
MOTHERS_DAY, DUELO_2ER_GRADO,
INTERNATIONAL_WOMENS_DAY, DIA_DEL_PADRE,
NATIONAL_WOMENS_DAY, DIA_DE_LA_MADRE,
HEALTH_PERMIT, DIA_DE_LA_MUJER_INTERNACIONAL,
VACATION_CURRENT_MANAGEMENT, DIA_DE_LA_MUJER_NACIONAL,
VACATION_PREVIOUS_MANAGEMENT, PERMISOS_DE_SALUD,
VACACION_GESTION_ACTUAL,
VACACION_GESTION_ANTERIOR,
} }

View File

@ -3,6 +3,7 @@ package com.primefactorsolutions.repositories;
import com.primefactorsolutions.model.Employee; import com.primefactorsolutions.model.Employee;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
import java.util.Optional; import java.util.Optional;
import java.util.UUID; import java.util.UUID;
@ -10,4 +11,7 @@ public interface EmployeeRepository extends JpaRepository<Employee, UUID> {
Optional<Employee> findByUsername(String username); Optional<Employee> findByUsername(String username);
Optional<Employee> findByPersonalEmail(String personalEmail); Optional<Employee> findByPersonalEmail(String personalEmail);
Optional<Employee> findByTeamIdAndLeadManagerTrue(UUID teamId);
List<Employee> findByTeamName(String teamName);
} }

View File

@ -13,4 +13,5 @@ public interface TimeOffRequestRepository extends JpaRepository<TimeOffRequest,
List<TimeOffRequest> findByEmployeeId(UUID idEmployee); List<TimeOffRequest> findByEmployeeId(UUID idEmployee);
Optional<TimeOffRequest> findByEmployeeIdAndState(UUID employeeId, TimeOffRequestStatus state); Optional<TimeOffRequest> findByEmployeeIdAndState(UUID employeeId, TimeOffRequestStatus state);
List<TimeOffRequest> findByEmployeeIdAndCategory(UUID employeeId, TimeOffRequestType category); List<TimeOffRequest> findByEmployeeIdAndCategory(UUID employeeId, TimeOffRequestType category);
List<TimeOffRequest> findByState(TimeOffRequestStatus state);
} }

View File

@ -48,6 +48,13 @@ public class EmployeeService {
return null; return null;
} }
public String getTeamLeadName(final UUID teamId) {
// Encuentra al empleado con el rol de lead_manager en el equipo especificado
Optional<Employee> leadManager = employeeRepository.findByTeamIdAndLeadManagerTrue(teamId);
return leadManager.map(employee -> employee.getFirstName() + " " + employee.getLastName())
.orElse("No asignado");
}
public List<Employee> findEmployees( public List<Employee> findEmployees(
final int start, final int pageSize, final String sortProperty, final boolean asc) { final int start, final int pageSize, final String sortProperty, final boolean asc) {
List<Employee> employees = employeeRepository.findAll(); List<Employee> employees = employeeRepository.findAll();
@ -115,4 +122,10 @@ public class EmployeeService {
public List<Employee> findAllEmployees() { public List<Employee> findAllEmployees() {
return employeeRepository.findAll(); return employeeRepository.findAll();
} }
public List<Employee> findEmployeesByTeam(final String teamName) {
return employeeRepository.findByTeamName(teamName);
}
} }

View File

@ -32,7 +32,7 @@ public class HoursWorkedService {
hoursWorkedRepository.deleteById(id); hoursWorkedRepository.deleteById(id);
} }
public List<HoursWorked> findByWeekNumber(int weekNumber) { public List<HoursWorked> findByWeekNumber(final int weekNumber) {
return hoursWorkedRepository.findByWeekNumber(weekNumber); return hoursWorkedRepository.findByWeekNumber(weekNumber);
} }

View File

@ -11,6 +11,7 @@ import lombok.SneakyThrows;
import org.apache.pdfbox.io.MemoryUsageSetting; import org.apache.pdfbox.io.MemoryUsageSetting;
import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.poi.ss.usermodel.*; import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@ -31,20 +32,59 @@ public class ReportService {
// Este método ahora solo crea el archivo Excel a partir de los datos que recibe. // Este método ahora solo crea el archivo Excel a partir de los datos que recibe.
public byte[] writeAsExcel(final String reportName, final List<String> headers, public byte[] writeAsExcel(final String reportName, final List<String> headers,
final List<Map<String, Object>> data) final List<Map<String, Object>> data, final String selectedTeam,
final int weekNumber, final int currentYear)
throws IOException { throws IOException {
return createExcelFile(reportName, headers, data); return createExcelFile(reportName, headers, data, selectedTeam, weekNumber, currentYear);
} }
private byte[] createExcelFile(final String reportName, final List<String> headers, private byte[] createExcelFile(final String reportName, final List<String> headers,
final List<Map<String, Object>> data) final List<Map<String, Object>> data, final String selectedTeam,
final int weekNumber, final int currentYear)
throws IOException { throws IOException {
try (Workbook workbook = new XSSFWorkbook(); try (Workbook workbook = new XSSFWorkbook();
ByteArrayOutputStream os = new ByteArrayOutputStream()) { ByteArrayOutputStream os = new ByteArrayOutputStream()) {
Sheet sheet = workbook.createSheet(reportName); Sheet sheet = workbook.createSheet(reportName);
// Crear encabezados // Crear encabezados
Row headerRow = sheet.createRow(0); // Crear una fila para el rótulo "Reporte por equipo"
Row titleRow = sheet.createRow(0); // Fila 0 para el rótulo
Cell titleCell = titleRow.createCell(0);
// Concatenar el nombre del equipo al rótulo
String titleText = "Informe: " + weekNumber + "/" + currentYear;
titleCell.setCellValue(titleText);
// Estilo del rótulo
CellStyle titleStyle = workbook.createCellStyle();
Font titleFont = workbook.createFont();
titleFont.setBold(true);
titleFont.setFontHeightInPoints((short) 14); // Tamaño de la fuente
titleStyle.setFont(titleFont);
titleCell.setCellStyle(titleStyle);
// Fusionar celdas para el rótulo
sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, headers.size() - 1)); // Ajusta el rango de celdas
// Crear filas adicionales con la información solicitada
Row asuntoRow = sheet.createRow(1); // Fila 1: Asunto
asuntoRow.createCell(0).setCellValue("Asunto: Informe semanal de horas trabajadas");
sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, headers.size() - 1));
Row semanaRow = sheet.createRow(2); // Fila 2: Semana
semanaRow.createCell(0).setCellValue("Semana: " + weekNumber); // Puedes insertar una fecha real aquí
sheet.addMergedRegion(new CellRangeAddress(2, 2, 0, headers.size() - 1));
Row horasCumplirRow = sheet.createRow(3); // Fila 3: Horas a cumplir
horasCumplirRow.createCell(0).setCellValue("Horas a cumplir: 40 horas"); // Puedes agregar las horas reales
sheet.addMergedRegion(new CellRangeAddress(3, 3, 0, headers.size() - 1));
Row teamLeadRow = sheet.createRow(4); // Fila 4: Team Lead
teamLeadRow.createCell(0).setCellValue("Team Lead: "); // Solo texto
sheet.addMergedRegion(new CellRangeAddress(4, 4, 0, headers.size() - 1));
// Crear encabezados (fila 5)
Row headerRow = sheet.createRow(5); // Los encabezados empiezan en la fila 5
CellStyle headerStyle = workbook.createCellStyle(); CellStyle headerStyle = workbook.createCellStyle();
Font headerFont = workbook.createFont(); Font headerFont = workbook.createFont();
headerFont.setBold(true); headerFont.setBold(true);
@ -56,20 +96,22 @@ public class ReportService {
cell.setCellStyle(headerStyle); cell.setCellStyle(headerStyle);
} }
// Crear filas de datos // Crear filas de datos (a partir de la fila 6)
for (int i = 0; i < data.size(); i++) { for (int i = 0; i < data.size(); i++) {
Row dataRow = sheet.createRow(i + 1); Row dataRow = sheet.createRow(i + 6); // Los datos empiezan después de la fila de encabezados
Map<String, Object> rowData = data.get(i); Map<String, Object> rowData = data.get(i);
int cellIndex = 0; int cellIndex = 0;
for (String key : headers) { for (String key : headers) {
Cell cell = dataRow.createCell(cellIndex++); Cell cell = dataRow.createCell(cellIndex++);
Object value = rowData.get(key); Object value = rowData.get(key);
switch (value) { if (value != null) {
case String s -> cell.setCellValue(s); if (value instanceof String) {
case Number number -> cell.setCellValue(number.doubleValue()); cell.setCellValue((String) value);
case null -> cell.setCellValue(""); // Manejo de valores nulos } else if (value instanceof Number) {
default -> { cell.setCellValue(((Number) value).doubleValue());
} }
} else {
cell.setCellValue(""); // Manejo de valores nulos
} }
} }
} }

View File

@ -18,6 +18,10 @@ public class TimeOffRequestService {
timeOffRequestRepository.save(newTimeOffRequest); timeOffRequestRepository.save(newTimeOffRequest);
} }
public void saveAll(final List<TimeOffRequest> requests) {
timeOffRequestRepository.saveAll(requests);
}
public void deleteTimeOffRequest(final UUID id) { public void deleteTimeOffRequest(final UUID id) {
timeOffRequestRepository.deleteById(id); timeOffRequestRepository.deleteById(id);
} }
@ -31,6 +35,10 @@ public class TimeOffRequestService {
return timeOffRequest.orElse(null); return timeOffRequest.orElse(null);
} }
public List<TimeOffRequest> findRequestsByState(final TimeOffRequestStatus state) {
return timeOffRequestRepository.findByState(state);
}
public List<TimeOffRequest> findRequestsByEmployeeId(final UUID idEmployee) { public List<TimeOffRequest> findRequestsByEmployeeId(final UUID idEmployee) {
return timeOffRequestRepository.findByEmployeeId(idEmployee); return timeOffRequestRepository.findByEmployeeId(idEmployee);
} }

View File

@ -2,8 +2,11 @@ package com.primefactorsolutions.views;
import com.primefactorsolutions.model.Employee; import com.primefactorsolutions.model.Employee;
import com.primefactorsolutions.model.Team; import com.primefactorsolutions.model.Team;
import com.primefactorsolutions.model.*;
import com.primefactorsolutions.service.EmployeeService; import com.primefactorsolutions.service.EmployeeService;
import com.primefactorsolutions.service.ReportService; import com.primefactorsolutions.service.ReportService;
import com.primefactorsolutions.service.TeamService;
import com.primefactorsolutions.service.TimeOffRequestService;
import com.vaadin.componentfactory.pdfviewer.PdfViewer; import com.vaadin.componentfactory.pdfviewer.PdfViewer;
import com.vaadin.flow.component.ClickEvent; import com.vaadin.flow.component.ClickEvent;
import com.vaadin.flow.component.Component; import com.vaadin.flow.component.Component;
@ -23,9 +26,6 @@ import com.vaadin.flow.component.textfield.EmailField;
import com.vaadin.flow.component.textfield.TextField; import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.component.upload.Upload; import com.vaadin.flow.component.upload.Upload;
import com.vaadin.flow.component.upload.receivers.MemoryBuffer; import com.vaadin.flow.component.upload.receivers.MemoryBuffer;
import com.vaadin.flow.data.binder.Result;
import com.vaadin.flow.data.binder.ValueContext;
import com.vaadin.flow.data.converter.Converter;
import com.vaadin.flow.data.value.ValueChangeMode; import com.vaadin.flow.data.value.ValueChangeMode;
import com.vaadin.flow.router.*; import com.vaadin.flow.router.*;
import com.vaadin.flow.server.StreamResource; import com.vaadin.flow.server.StreamResource;
@ -38,6 +38,8 @@ import org.vaadin.firitin.form.BeanValidationForm;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.IOException; import java.io.IOException;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.Base64; import java.util.Base64;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
@ -51,6 +53,9 @@ public class EmployeeView extends BeanValidationForm<Employee> implements HasUrl
private final EmployeeService employeeService; private final EmployeeService employeeService;
private final ReportService reportService; private final ReportService reportService;
private final TimeOffRequestService requestService;
private final TeamService teamService;
// TODO: campo usado para registrar al empleado en LDAP. Este campo podria estar en otro form eventualmente. // TODO: campo usado para registrar al empleado en LDAP. Este campo podria estar en otro form eventualmente.
private final TextField username = createTextField("Username: ", 30, true); private final TextField username = createTextField("Username: ", 30, true);
@ -71,7 +76,7 @@ public class EmployeeView extends BeanValidationForm<Employee> implements HasUrl
private final EmailField personalEmail = createEmailField("E-mail"); private final EmailField personalEmail = createEmailField("E-mail");
private final TextField cod = createTextField("Codigo de Empleado", 30, false); private final TextField cod = createTextField("Codigo de Empleado", 30, false);
private final TextField position = createTextField("Cargo", 30, false); private final TextField position = createTextField("Cargo", 30, false);
private final TextField team = createTextField("Equipo", 30, false); private final ComboBox<Team> team = new ComboBox<>("Equipo");
private final TextField leadManager = createTextField("Lead/Manager", 30, false); private final TextField leadManager = createTextField("Lead/Manager", 30, false);
private final TextField project = createTextField("Proyecto", 30, false); private final TextField project = createTextField("Proyecto", 30, false);
private final TextField emergencyCName = createTextField("Nombres y Apellidos de Contacto", 50, false); private final TextField emergencyCName = createTextField("Nombres y Apellidos de Contacto", 50, false);
@ -139,26 +144,19 @@ public class EmployeeView extends BeanValidationForm<Employee> implements HasUrl
private final H3 datBanc = new H3("Datos Bancados"); private final H3 datBanc = new H3("Datos Bancados");
private final H3 datGest = new H3("Datos Gestora Pública y Seguro Social"); private final H3 datGest = new H3("Datos Gestora Pública y Seguro Social");
public EmployeeView(final EmployeeService employeeService, final ReportService reportService) { public EmployeeView(final EmployeeService employeeService,
final ReportService reportService,
final TeamService teamService,
final TimeOffRequestService requestService) {
super(Employee.class); super(Employee.class);
this.employeeService = employeeService; this.employeeService = employeeService;
this.reportService = reportService; this.reportService = reportService;
this.requestService = requestService;
this.teamService = teamService;
saveButton.addThemeVariants(ButtonVariant.LUMO_PRIMARY); saveButton.addThemeVariants(ButtonVariant.LUMO_PRIMARY);
configureComponents(); configureComponents();
addClassName("main-layout"); addClassName("main-layout");
getBinder().setConverter("team", new Converter<Object, Object>() {
@Override
public Result<Object> convertToModel(final Object o, final ValueContext valueContext) {
return Result.ok(new Team((String) o));
}
@Override
public Object convertToPresentation(final Object o, final ValueContext valueContext) {
return ((Team) o).getName();
}
});
} }
private void configureComponents() { private void configureComponents() {
@ -171,6 +169,7 @@ public class EmployeeView extends BeanValidationForm<Employee> implements HasUrl
firstName.addValueChangeListener(e -> validateNameField(firstName, e.getValue())); firstName.addValueChangeListener(e -> validateNameField(firstName, e.getValue()));
lastName.setValueChangeMode(ValueChangeMode.EAGER); lastName.setValueChangeMode(ValueChangeMode.EAGER);
lastName.addValueChangeListener(e -> validateNameField(lastName, e.getValue())); lastName.addValueChangeListener(e -> validateNameField(lastName, e.getValue()));
createTeamComboBox();
configureUpload(); configureUpload();
saveButton.setVisible(true); saveButton.setVisible(true);
@ -293,6 +292,13 @@ public class EmployeeView extends BeanValidationForm<Employee> implements HasUrl
return emailField; return emailField;
} }
private void createTeamComboBox() {
List<Team> teams = teamService.findAllTeams();
team.setItems(teams);
team.setItemLabelGenerator(Team::getName);
team.setWidthFull();
}
private <T> ComboBox<T> createComboBox(final String label, final T[] items) { private <T> ComboBox<T> createComboBox(final String label, final T[] items) {
ComboBox<T> comboBox = new ComboBox<>(label); ComboBox<T> comboBox = new ComboBox<>(label);
comboBox.setItems(items); comboBox.setItems(items);
@ -313,6 +319,26 @@ public class EmployeeView extends BeanValidationForm<Employee> implements HasUrl
return !firstName.isEmpty() && !lastName.isEmpty() && status.getValue() != null; return !firstName.isEmpty() && !lastName.isEmpty() && status.getValue() != null;
} }
private void setVacationDuration(
final Employee employee,
final TimeOffRequest request,
final LocalDate referenceDate) {
double yearsOfService = ChronoUnit.YEARS.between(employee.getDateOfEntry(), referenceDate);
request.setAvailableDays(calculateAvailableDays(yearsOfService));
}
private double calculateAvailableDays(final double yearsOfService) {
if (yearsOfService > 10) {
return 30.0;
} else if (yearsOfService > 5) {
return 20.0;
} else if (yearsOfService > 1) {
return 15.0;
} else {
return 0.0;
}
}
private void saveEmployee() { private void saveEmployee() {
if (validateForm()) { if (validateForm()) {
Employee employee = getEntity(); Employee employee = getEntity();
@ -333,7 +359,6 @@ public class EmployeeView extends BeanValidationForm<Employee> implements HasUrl
editButton.setVisible(false); editButton.setVisible(false);
} }
@Override @Override
public void setParameter(final BeforeEvent beforeEvent, final String action) { public void setParameter(final BeforeEvent beforeEvent, final String action) {
final RouteParameters params = beforeEvent.getRouteParameters(); final RouteParameters params = beforeEvent.getRouteParameters();
@ -514,5 +539,4 @@ public class EmployeeView extends BeanValidationForm<Employee> implements HasUrl
saveButton, editButton, reportButton, dialog saveButton, editButton, reportButton, dialog
); );
} }
} }

View File

@ -17,8 +17,11 @@ import com.vaadin.flow.router.Route;
import com.vaadin.flow.spring.annotation.SpringComponent; import com.vaadin.flow.spring.annotation.SpringComponent;
import jakarta.annotation.security.PermitAll; import jakarta.annotation.security.PermitAll;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope; import org.springframework.context.annotation.Scope;
import com.vaadin.flow.component.html.Label; import com.vaadin.flow.component.html.Label;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import java.time.DayOfWeek; import java.time.DayOfWeek;
@ -62,6 +65,11 @@ public class HoursWorkedView extends VerticalLayout {
private final Label numeroSemanaLabel = new Label("Número de la Semana: "); private final Label numeroSemanaLabel = new Label("Número de la Semana: ");
private DatePicker fechaPicker = new DatePicker("Selecciona una fecha"); private DatePicker fechaPicker = new DatePicker("Selecciona una fecha");
@Autowired
private InternalResourceViewResolver defaultViewResolver;
@Qualifier("defaultServletHandlerMapping")
@Autowired
private HandlerMapping defaultServletHandlerMapping;
public HoursWorkedView(final EmployeeService employeeService, final HoursWorkedService hoursWorkedService) { public HoursWorkedView(final EmployeeService employeeService, final HoursWorkedService hoursWorkedService) {
@ -75,7 +83,8 @@ public class HoursWorkedView extends VerticalLayout {
} }
private void configurarTareasEspecificas() { private void configurarTareasEspecificas() {
tareasEspecificasDropdown.setItems("Entrevistas", "Reuniones", "Colaboraciones", "Aprendizajes", "Proyectos PFS", "Otros"); tareasEspecificasDropdown.setItems("Entrevistas", "Reuniones", "Colaboraciones",
"Aprendizajes", "Proyectos PFS", "Otros");
tareasEspecificasDropdown.setPlaceholder("Selecciona una tarea..."); tareasEspecificasDropdown.setPlaceholder("Selecciona una tarea...");
tareasEspecificasDropdown.addValueChangeListener(event -> { tareasEspecificasDropdown.addValueChangeListener(event -> {
@ -141,8 +150,18 @@ public class HoursWorkedView extends VerticalLayout {
getUI().ifPresent(ui -> ui.navigate(HoursWorkedMonthView.class)); getUI().ifPresent(ui -> ui.navigate(HoursWorkedMonthView.class));
}); });
equipoDropdown.setItems("Equipo 1", "Equipo 2", "Equipo 3"); equipoDropdown.setItems("ABC", "DEF", "XYZ");
equipoDropdown.setWidth("250px"); equipoDropdown.setWidth("250px");
equipoDropdown.addValueChangeListener(event -> {
String selectedEquipo = event.getValue();
if (selectedEquipo != null) {
// Filtra la lista de empleados según el equipo seleccionado
List<Employee> filteredEmployees = employeeService.findEmployeesByTeam(selectedEquipo);
employeeComboBox.setItems(filteredEmployees);
}
});
setEmployeeComboBoxProperties(); setEmployeeComboBoxProperties();
HorizontalLayout filtersLayout = new HorizontalLayout(equipoDropdown, employeeComboBox); HorizontalLayout filtersLayout = new HorizontalLayout(equipoDropdown, employeeComboBox);
@ -163,7 +182,8 @@ public class HoursWorkedView extends VerticalLayout {
totalesLayout.setSpacing(true); totalesLayout.setSpacing(true);
totalesLayout.setPadding(true); totalesLayout.setPadding(true);
add(fechaPicker, fechasLabel, numeroSemanaLabel, filtersLayout, actividadFormLayout, tareasEspecificasLayout, grid,gridActividadesEspecificas, buttonsLayout, totalesLayout); add(fechaPicker, fechasLabel, numeroSemanaLabel, filtersLayout, actividadFormLayout,
tareasEspecificasLayout, grid, gridActividadesEspecificas, buttonsLayout, totalesLayout);
} }
private void configurarGrid() { private void configurarGrid() {
@ -183,7 +203,7 @@ public class HoursWorkedView extends VerticalLayout {
private void configurarGridActividadesEspecificas() { private void configurarGridActividadesEspecificas() {
gridActividadesEspecificas.removeAllColumns(); gridActividadesEspecificas.removeAllColumns();
gridActividadesEspecificas.setItems(actividadesEspecificas); gridActividadesEspecificas.setItems(actividadesEspecificas);
gridActividadesEspecificas.addColumn(Actividad::getNombreActivEsp).setHeader("Actividad"); gridActividadesEspecificas.addColumn(Actividad::getTarea).setHeader("Actividad");
gridActividadesEspecificas.addColumn(Actividad::getLunes).setHeader("Lunes"); gridActividadesEspecificas.addColumn(Actividad::getLunes).setHeader("Lunes");
gridActividadesEspecificas.addColumn(Actividad::getMartes).setHeader("Martes"); gridActividadesEspecificas.addColumn(Actividad::getMartes).setHeader("Martes");
gridActividadesEspecificas.addColumn(Actividad::getMiercoles).setHeader("Miércoles"); gridActividadesEspecificas.addColumn(Actividad::getMiercoles).setHeader("Miércoles");
@ -191,7 +211,8 @@ public class HoursWorkedView extends VerticalLayout {
gridActividadesEspecificas.addColumn(Actividad::getViernes).setHeader("Viernes"); gridActividadesEspecificas.addColumn(Actividad::getViernes).setHeader("Viernes");
gridActividadesEspecificas.addColumn(Actividad::getSabado).setHeader("Sábado"); gridActividadesEspecificas.addColumn(Actividad::getSabado).setHeader("Sábado");
gridActividadesEspecificas.addColumn(Actividad::getDomingo).setHeader("Domingo"); gridActividadesEspecificas.addColumn(Actividad::getDomingo).setHeader("Domingo");
gridActividadesEspecificas.addColumn(this::calcularTotalPorDia).setHeader("Total Día Específico").setKey("totalDiaEspecifico"); gridActividadesEspecificas.addColumn(this::calcularTotalPorDia).setHeader("Total Día Específico")
.setKey("totalDiaEspecifico");
} }
private HorizontalLayout configurarFormularioActividades() { private HorizontalLayout configurarFormularioActividades() {
@ -221,13 +242,14 @@ public class HoursWorkedView extends VerticalLayout {
case FRIDAY -> actividadBuilder.viernes(horas); case FRIDAY -> actividadBuilder.viernes(horas);
case SATURDAY -> actividadBuilder.sabado(horas); case SATURDAY -> actividadBuilder.sabado(horas);
case SUNDAY -> actividadBuilder.domingo(horas); case SUNDAY -> actividadBuilder.domingo(horas);
default -> throw new IllegalArgumentException("Día seleccionado no válido: " + selectedDay);
} }
String tareaSeleccionada = tareasEspecificasDropdown.getValue(); String tareaSeleccionada = tareasEspecificasDropdown.getValue();
double horasTarea = parseHoras(horasTareaInput.getValue()); double horasTarea = parseHoras(horasTareaInput.getValue());
if (tareaSeleccionada != null && !tareaSeleccionada.isEmpty()) { if (tareaSeleccionada != null && !tareaSeleccionada.isEmpty()) {
actividadBuilder.nombreActivEsp(tareaSeleccionada).lunes(horasTarea); actividadBuilder.tarea(tareaSeleccionada).lunes(horasTarea);
Actividad nuevaActividadEspecifica = actividadBuilder.build(); Actividad nuevaActividadEspecifica = actividadBuilder.build();
actividadesEspecificas.add(nuevaActividadEspecifica); actividadesEspecificas.add(nuevaActividadEspecifica);
gridActividadesEspecificas.setItems(actividadesEspecificas); gridActividadesEspecificas.setItems(actividadesEspecificas);
@ -255,7 +277,9 @@ public class HoursWorkedView extends VerticalLayout {
Button agregarTareaButton = new Button("Agregar Tarea PFS", e -> { Button agregarTareaButton = new Button("Agregar Tarea PFS", e -> {
try { try {
String tareaSeleccionada = tareasEspecificasDropdown.getValue(); String tareaSeleccionada = tareasEspecificasDropdown.getValue();
String tareaNombre = "Otros".equals(tareaSeleccionada) ? tareaEspecificaInput.getValue() : tareaSeleccionada; String tareaNombre = "Otros"
.equals(tareaSeleccionada) ? tareaEspecificaInput
.getValue() : tareaSeleccionada;
if (tareaNombre == null || tareaNombre.isEmpty()) { if (tareaNombre == null || tareaNombre.isEmpty()) {
Notification.show("Por favor, especifica la tarea."); Notification.show("Por favor, especifica la tarea.");
@ -276,7 +300,7 @@ public class HoursWorkedView extends VerticalLayout {
} }
DayOfWeek selectedDay = selectedDate.getDayOfWeek(); DayOfWeek selectedDay = selectedDate.getDayOfWeek();
Actividad.Builder actividadBuilder = new Actividad.Builder().nombreActivEsp(tareaNombre); Actividad.Builder actividadBuilder = new Actividad.Builder().tarea(tareaNombre);
switch (selectedDay) { switch (selectedDay) {
case MONDAY -> actividadBuilder.lunes(horasTarea); case MONDAY -> actividadBuilder.lunes(horasTarea);
@ -286,6 +310,7 @@ public class HoursWorkedView extends VerticalLayout {
case FRIDAY -> actividadBuilder.viernes(horasTarea); case FRIDAY -> actividadBuilder.viernes(horasTarea);
case SATURDAY -> actividadBuilder.sabado(horasTarea); case SATURDAY -> actividadBuilder.sabado(horasTarea);
case SUNDAY -> actividadBuilder.domingo(horasTarea); case SUNDAY -> actividadBuilder.domingo(horasTarea);
default -> throw new IllegalArgumentException("Día seleccionado no válido: " + selectedDay);
} }
Actividad nuevaActividadEspecifica = actividadBuilder.build(); Actividad nuevaActividadEspecifica = actividadBuilder.build();
@ -307,7 +332,8 @@ public class HoursWorkedView extends VerticalLayout {
} }
}); });
HorizontalLayout layout= new HorizontalLayout(tareasEspecificasDropdown, tareaEspecificaInput, horasTareaInput, agregarTareaButton); HorizontalLayout layout = new HorizontalLayout(tareasEspecificasDropdown,
tareaEspecificaInput, horasTareaInput, agregarTareaButton);
layout.setSpacing(true); layout.setSpacing(true);
return layout; return layout;
} }
@ -354,7 +380,6 @@ public class HoursWorkedView extends VerticalLayout {
Employee selectedEmployee = employeeComboBox.getValue(); Employee selectedEmployee = employeeComboBox.getValue();
String selectedEquipo = equipoDropdown.getValue(); String selectedEquipo = equipoDropdown.getValue();
if (selectedEmployee == null || selectedEquipo == null) { if (selectedEmployee == null || selectedEquipo == null) {
Notification.show("Por favor selecciona un equipo y un empleado."); Notification.show("Por favor selecciona un equipo y un empleado.");
return; return;
@ -372,6 +397,7 @@ public class HoursWorkedView extends VerticalLayout {
try { try {
hoursWorkedService.saveHoursWorked(hoursWorked); // Usa saveHoursWorked directamente hoursWorkedService.saveHoursWorked(hoursWorked); // Usa saveHoursWorked directamente
Notification.show("Actividades guardadas correctamente."); Notification.show("Actividades guardadas correctamente.");
System.out.println(hoursWorked);
} catch (Exception e) { } catch (Exception e) {
Notification.show("Error al guardar actividades: " + e.getMessage()); Notification.show("Error al guardar actividades: " + e.getMessage());
} }

View File

@ -143,9 +143,11 @@ public class MainLayout extends AppLayout {
SideNavItem timeOff = new SideNavItem("My Time-off", TimeoffView.class, SideNavItem timeOff = new SideNavItem("My Time-off", TimeoffView.class,
LineAwesomeIcon.PLANE_DEPARTURE_SOLID.create()); LineAwesomeIcon.PLANE_DEPARTURE_SOLID.create());
timeOff.addItem(new SideNavItem("Vacations", RequestsListView.class, timeOff.addItem(new SideNavItem("Vacations", RequestsListView.class,
LineAwesomeIcon.SUN.create())); LineAwesomeIcon.UMBRELLA_BEACH_SOLID.create()));
timeOff.addItem(new SideNavItem("Add Vacation", RequestRegisterView.class, timeOff.addItem(new SideNavItem("Add Vacation", RequestRegisterView.class,
LineAwesomeIcon.SUN.create())); LineAwesomeIcon.CALENDAR_PLUS.create()));
timeOff.addItem(new SideNavItem("Pending Requests", PendingRequestsListView.class,
LineAwesomeIcon.LIST_ALT.create()));
SideNavItem timesheet = new SideNavItem("My Timesheet", TimesheetView.class, SideNavItem timesheet = new SideNavItem("My Timesheet", TimesheetView.class,
LineAwesomeIcon.HOURGLASS_START_SOLID.create()); LineAwesomeIcon.HOURGLASS_START_SOLID.create());
timesheet.addItem(new SideNavItem("Horas Trabajadas", HoursWorkedView.class, timesheet.addItem(new SideNavItem("Horas Trabajadas", HoursWorkedView.class,

View File

@ -1,16 +1,50 @@
package com.primefactorsolutions.views; package com.primefactorsolutions.views;
import com.primefactorsolutions.model.TimeOffRequest;
import com.primefactorsolutions.model.TimeOffRequestStatus;
import com.primefactorsolutions.service.TimeOffRequestService;
import com.vaadin.flow.component.Text; import com.vaadin.flow.component.Text;
import com.vaadin.flow.component.html.Main; import com.vaadin.flow.component.html.Main;
import com.vaadin.flow.router.PageTitle; import com.vaadin.flow.router.PageTitle;
import com.vaadin.flow.router.Route; import com.vaadin.flow.router.Route;
import jakarta.annotation.security.PermitAll; import jakarta.annotation.security.PermitAll;
import java.time.LocalDate;
import java.util.List;
@PageTitle("Home") @PageTitle("Home")
@Route(value = "", layout = MainLayout.class) @Route(value = "", layout = MainLayout.class)
@PermitAll @PermitAll
public class MainView extends Main { public class MainView extends Main {
public MainView() {
add(new Text("Welcome to PFS Intra.")); private final TimeOffRequestService requestService;
public MainView(final TimeOffRequestService requestService) {
this.requestService = requestService;
add(new Text("Welcome"));
updateRequestStatuses();
}
private void updateRequestStatuses() {
List<TimeOffRequest> requests = requestService.findAllTimeOffRequests();
LocalDate now = LocalDate.now();
for (TimeOffRequest request : requests) {
if (request.getState() == TimeOffRequestStatus.APROBADO) {
LocalDate expirationDate = request.getExpiration();
LocalDate startDate = request.getStartDate();
LocalDate endDate = request.getEndDate();
if (now.isAfter(expirationDate)) {
request.setState(TimeOffRequestStatus.VENCIDO);
} else if (now.isAfter(endDate) && now.isBefore(expirationDate)) {
request.setState(TimeOffRequestStatus.TOMADO);
} else if (now.isEqual(startDate) || now.isAfter(startDate) && now.isBefore(endDate)) {
request.setState(TimeOffRequestStatus.EN_USO);
}
}
}
requestService.saveAll(requests);
} }
} }

View File

@ -0,0 +1,227 @@
package com.primefactorsolutions.views;
import com.primefactorsolutions.model.*;
import com.primefactorsolutions.service.EmployeeService;
import com.primefactorsolutions.service.TeamService;
import com.primefactorsolutions.service.TimeOffRequestService;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.combobox.ComboBox;
import com.vaadin.flow.component.html.Main;
import com.vaadin.flow.component.notification.Notification;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.router.PageTitle;
import com.vaadin.flow.router.Route;
import com.vaadin.flow.spring.annotation.SpringComponent;
import jakarta.annotation.security.PermitAll;
import org.springframework.context.annotation.Scope;
import org.vaadin.firitin.components.grid.PagingGrid;
import java.util.*;
import java.util.stream.Collectors;
@SpringComponent
@Scope("prototype")
@PageTitle("PendingRequests")
@Route(value = "/pending-requests", layout = MainLayout.class)
@PermitAll
public class PendingRequestsListView extends Main {
private final TimeOffRequestService requestService;
private final EmployeeService employeeService;
private final TeamService teamService;
private final PagingGrid<TimeOffRequest> pendingRequestsGrid = new PagingGrid<>();
private List<Employee> employees = Collections.emptyList();
private ComboBox<Employee> employeeFilter;
private ComboBox<Team> teamFilter;
private ComboBox<TimeOffRequestType> categoryFilter;
private UUID selectedRequestId;
public PendingRequestsListView(final TimeOffRequestService requestService,
final EmployeeService employeeService,
final TeamService teamService) {
this.requestService = requestService;
this.employeeService = employeeService;
this.teamService = teamService;
this.employees = employeeService.findAllEmployees();
initializeView();
refreshGeneralPendingRequestsGrid(null, null, null);
}
private void initializeView() {
setupFilters();
setupPendingRequestsGrid();
add(pendingRequestsGrid);
add(createActionButtons());
}
private void setupFilters() {
add(createEmployeeFilter());
add(createTeamFilter());
add(createCategoryFilter());
}
private void setupPendingRequestsGrid() {
pendingRequestsGrid.addColumn(this::getEmployeeFullName).setHeader("Empleado");
pendingRequestsGrid.addColumn(this::getTeamName).setHeader("Equipo");
pendingRequestsGrid.addColumn(this::getCategory).setHeader("Categoría");
pendingRequestsGrid.setPaginationBarMode(PagingGrid.PaginationBarMode.BOTTOM);
pendingRequestsGrid.setPageSize(5);
pendingRequestsGrid.asSingleSelect().addValueChangeListener(event -> {
TimeOffRequest selectedRequest = event.getValue();
if (selectedRequest != null) {
selectedRequestId = selectedRequest.getId();
}
});
}
private HorizontalLayout createActionButtons() {
Button approveButton = createActionButton("Aprobar", TimeOffRequestStatus.APROBADO);
Button rejectButton = createActionButton("Rechazar", TimeOffRequestStatus.RECHAZADO);
Button closeButton = new Button("Salir", event -> navigateToMainView());
return new HorizontalLayout(approveButton, rejectButton, closeButton);
}
private Button createActionButton(final String caption, final TimeOffRequestStatus status) {
return new Button(caption, event -> {
if (selectedRequestId != null) {
TimeOffRequest request = requestService.findTimeOffRequest(selectedRequestId);
request.setState(status);
requestService.saveTimeOffRequest(request);
refreshGeneralPendingRequestsGrid(null, null, null);
} else {
Notification.show("Seleccione una solicitud.", 3000, Notification.Position.MIDDLE);
}
});
}
private void refreshGeneralPendingRequestsGrid(final Employee employee,
final Team team,
final TimeOffRequestType category) {
pendingRequestsGrid.setPagingDataProvider((page, pageSize) -> {
int start = (int) (page * pendingRequestsGrid.getPageSize());
return fetchFilteredPendingRequests(start, pageSize, employee, team, category);
});
pendingRequestsGrid.getDataProvider().refreshAll();
}
private List<TimeOffRequest> fetchFilteredPendingRequests(final int start,
final int pageSize,
final Employee employee,
final Team team,
final TimeOffRequestType category) {
List<TimeOffRequest> filteredPendingRequests
= requestService.findRequestsByState(TimeOffRequestStatus.PENDIENTE);
if (employee != null && !"TODOS".equals(employee.getFirstName())) {
filteredPendingRequests = filteredPendingRequests.stream()
.filter(emp -> emp.getEmployee().getId().equals(employee.getId()))
.collect(Collectors.toList());
}
if (team != null && !"TODOS".equals(team.getName())) {
filteredPendingRequests = filteredPendingRequests.stream()
.filter(emp -> emp.getEmployee().getTeam() != null
&& emp.getEmployee().getTeam().getId().equals(team.getId()))
.collect(Collectors.toList());
}
if (category != null && category != TimeOffRequestType.TODOS) {
filteredPendingRequests = filteredPendingRequests.stream()
.filter(emp -> emp.getCategory().equals(category))
.collect(Collectors.toList());
}
int end = Math.min(start + pageSize, filteredPendingRequests.size());
return filteredPendingRequests.subList(start, end);
}
private String getEmployeeFullName(final TimeOffRequest request) {
Employee employee = request.getEmployee();
return getEmployeeFullNameLabel(employee);
}
private String getEmployeeFullNameLabel(final Employee employee) {
return "TODOS".equals(employee.getFirstName())
? "TODOS" : employee.getFirstName() + " " + employee.getLastName();
}
private String getTeamName(final TimeOffRequest request) {
Team team = request.getEmployee().getTeam();
return team != null ? team.getName() : "Sin asignar";
}
private String getTeamLabel(final Team team) {
return "TODOS".equals(team.getName()) ? "TODOS" : team.getName();
}
private String getCategory(final TimeOffRequest request) {
return String.valueOf(request.getCategory());
}
private ComboBox<Employee> createEmployeeFilter() {
employeeFilter = new ComboBox<>("Empleado");
List<Employee> employees = new ArrayList<>(employeeService.findAllEmployees());
employees.addFirst(createAllEmployeesOption());
employeeFilter.setItems(employees);
employeeFilter.setItemLabelGenerator(this::getEmployeeFullNameLabel);
employeeFilter.setValue(employees.getFirst());
employeeFilter.addValueChangeListener(event ->
refreshGeneralPendingRequestsGrid(
event.getValue(),
teamFilter.getValue(),
categoryFilter.getValue()
)
);
return employeeFilter;
}
private ComboBox<Team> createTeamFilter() {
teamFilter = new ComboBox<>("Equipo");
List<Team> teams = new ArrayList<>(teamService.findAllTeams());
teams.addFirst(createAllTeamsOption());
teamFilter.setItems(teams);
teamFilter.setItemLabelGenerator(this::getTeamLabel);
teamFilter.setValue(teams.getFirst());
teamFilter.addValueChangeListener(event ->
refreshGeneralPendingRequestsGrid(
employeeFilter.getValue(),
event.getValue(),
categoryFilter.getValue()
)
);
return teamFilter;
}
private ComboBox<TimeOffRequestType> createCategoryFilter() {
categoryFilter = new ComboBox<>("Categoría");
categoryFilter.setItems(TimeOffRequestType.values());
categoryFilter.setValue(TimeOffRequestType.values()[0]);
categoryFilter.addValueChangeListener(event ->
refreshGeneralPendingRequestsGrid(
employeeFilter.getValue(),
teamFilter.getValue(),
event.getValue()
)
);
return categoryFilter;
}
private Employee createAllEmployeesOption() {
Employee allEmployeesOption = new Employee();
allEmployeesOption.setFirstName("TODOS");
return allEmployeesOption;
}
private Team createAllTeamsOption() {
Team allTeamsOption = new Team();
allTeamsOption.setName("TODOS");
return allTeamsOption;
}
private void navigateToMainView() {
getUI().ifPresent(ui -> ui.navigate(MainView.class));
}
}

View File

@ -1,13 +1,17 @@
package com.primefactorsolutions.views; package com.primefactorsolutions.views;
import com.primefactorsolutions.model.HoursWorked; import com.primefactorsolutions.model.HoursWorked;
import com.primefactorsolutions.model.Team;
import com.primefactorsolutions.service.HoursWorkedService; import com.primefactorsolutions.service.HoursWorkedService;
import com.primefactorsolutions.service.ReportService; import com.primefactorsolutions.service.ReportService;
import com.primefactorsolutions.service.TeamService;
import com.vaadin.flow.component.button.Button; import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.combobox.ComboBox; import com.vaadin.flow.component.combobox.ComboBox;
import com.vaadin.flow.component.datepicker.DatePicker; import com.vaadin.flow.component.grid.Grid;
import com.vaadin.flow.component.html.Anchor; import com.vaadin.flow.component.html.Anchor;
import com.vaadin.flow.component.html.H2; import com.vaadin.flow.component.html.H2;
import com.vaadin.flow.component.html.Span;
import com.vaadin.flow.component.notification.Notification;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout; import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.orderedlayout.VerticalLayout; import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.router.PageTitle; import com.vaadin.flow.router.PageTitle;
@ -15,10 +19,12 @@ import com.vaadin.flow.router.Route;
import com.vaadin.flow.server.StreamResource; import com.vaadin.flow.server.StreamResource;
import jakarta.annotation.security.PermitAll; import jakarta.annotation.security.PermitAll;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import com.vaadin.flow.component.notification.Notification; import com.primefactorsolutions.service.EmployeeService;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.time.DayOfWeek;
import java.time.LocalDate; import java.time.LocalDate;
import java.time.format.TextStyle;
import java.time.temporal.WeekFields; import java.time.temporal.WeekFields;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
@ -31,90 +37,217 @@ import java.util.stream.Collectors;
@PageTitle("Reporte de Horas Trabajadas") @PageTitle("Reporte de Horas Trabajadas")
public class ReporteView extends VerticalLayout { public class ReporteView extends VerticalLayout {
private final EmployeeService employeeService;
private final HoursWorkedService hoursWorkedService; private final HoursWorkedService hoursWorkedService;
private final ReportService reportService; private final ReportService reportService;
private final TeamService teamService;
private final ComboBox<String> equipoComboBox = new ComboBox<>("Seleccionar Equipo"); private final ComboBox<Team> equipoComboBox = new ComboBox<>("Seleccionar Equipo");
private final DatePicker semanaPicker = new DatePicker("Seleccionar Semana"); private final ComboBox<String> semanaComboBox = new ComboBox<>("Seleccionar Semana");
private final Grid<Map<String, Object>> grid = new Grid<>();
private final VerticalLayout headerLayout = new VerticalLayout();
private Anchor downloadLink; private Anchor downloadLink;
private final Span semanaInfoSpan = new Span();
// Obtener el año actual
private int currentYear = LocalDate.now().getYear();
@Autowired @Autowired
public ReporteView(final HoursWorkedService hoursWorkedService, final ReportService reportService) { public ReporteView(final HoursWorkedService hoursWorkedService,
final ReportService reportService, final TeamService teamService,
final EmployeeService employeeService) {
this.hoursWorkedService = hoursWorkedService; this.hoursWorkedService = hoursWorkedService;
this.reportService = reportService; this.reportService = reportService;
this.teamService = teamService;
this.employeeService = employeeService;
H2 title = new H2("Reporte de Horas Trabajadas"); H2 title = new H2("Reporte de Horas Trabajadas");
add(title); add(title);
equipoComboBox.setItems("Equipo 1", "Equipo 2", "Equipo 3"); // Opciones de equipo List<Team> teams = teamService.findAllTeams();
semanaPicker.setPlaceholder("Seleccione una fecha dentro de la semana deseada"); equipoComboBox.setItems(teams);
equipoComboBox.setItemLabelGenerator(Team::getName);
Button reportButton = new Button("Generar Reporte de Horas Trabajadas", event -> generateHoursWorkedReport()); // Configurar el ComboBox de semanas
HorizontalLayout filtersLayout = new HorizontalLayout(equipoComboBox, semanaPicker, reportButton); initializeSemanaComboBox();
// Listener para actualizar `semanaInfoSpan` con la selección del usuario en `semanaComboBox`
semanaComboBox.addValueChangeListener(event -> {
String selectedWeek = event.getValue();
semanaInfoSpan.setText(selectedWeek != null
? selectedWeek : "Selecciona una semana");
});
Button reportButton = new Button("Generar Reporte de Horas Trabajadas",
event -> generateHoursWorkedReport());
HorizontalLayout filtersLayout = new HorizontalLayout(equipoComboBox,
semanaComboBox, reportButton);
add(filtersLayout); add(filtersLayout);
// Añadir `headerLayout` al diseño principal para el encabezado dinámico
add(headerLayout);
updateHeaderLayout(null, null);
grid.addColumn(map -> map.get("ID")).setHeader("ID")
.getElement().getStyle().set("font-weight", "bold");
grid.addColumn(map -> map.get("Employee ID")).setHeader("Employee ID");
grid.addColumn(map -> map.get("Empleado")).setHeader("Empleado");
grid.addColumn(map -> map.get("Horas Trabajadas")).setHeader("Horas Trabajadas");
grid.addColumn(map -> map.get("Horas Pendientes")).setHeader("Horas Pendientes");
grid.addColumn(map -> map.get("Observaciones")).setHeader("Observaciones");
add(grid);
}
private void initializeSemanaComboBox() {
int year = LocalDate.now().getYear();
LocalDate startOfYear = LocalDate.of(year, 1, 5); // Suponemos que la semana comienza el 5 de enero.
List<String> semanas = startOfYear.datesUntil(LocalDate
.of(year + 1, 1, 1),
java.time.Period.ofWeeks(1))
.map(date -> {
int weekNumber = date.get(WeekFields.of(DayOfWeek.MONDAY, 1)
.weekOfWeekBasedYear());
LocalDate startOfWeek = date;
LocalDate endOfWeek = startOfWeek.plusDays(6);
return String.format("Semana %d: %s - %s",
weekNumber,
startOfWeek.getDayOfMonth() + " de " + startOfWeek.getMonth()
.getDisplayName(TextStyle.FULL, Locale.getDefault()),
endOfWeek.getDayOfMonth() + " de " + endOfWeek.getMonth()
.getDisplayName(TextStyle.FULL, Locale.getDefault())
);
})
.collect(Collectors.toList());
semanaComboBox.setItems(semanas);
semanaComboBox.setPlaceholder("Seleccione una semana");
} }
private void generateHoursWorkedReport() { private void generateHoursWorkedReport() {
String selectedEquipo = equipoComboBox.getValue(); Team selectedEquipo = equipoComboBox.getValue();
LocalDate selectedDate = semanaPicker.getValue(); String selectedWeek = semanaComboBox.getValue();
if (selectedEquipo == null || selectedDate == null) { if (selectedEquipo == null || selectedWeek == null) {
Notification.show("Por favor, selecciona un equipo y una semana para generar el reporte.", 3000, Notification.Position.MIDDLE); Notification.show("Por favor, selecciona un equipo y una semana para generar el reporte.",
3000,
Notification.Position.MIDDLE);
return; return;
} }
int weekNumber = getWeekOfYear(selectedDate); int weekNumber = Integer.parseInt(selectedWeek.split(" ")[1]
.replace(":", ""));
LocalDate selectedDate = LocalDate.now()
.with(WeekFields.of(DayOfWeek.FRIDAY, 1)
.weekOfWeekBasedYear(), weekNumber);
updateHeaderLayout(selectedEquipo, selectedDate);
List<HoursWorked> hoursWorkedList = hoursWorkedService.findAll().stream() List<HoursWorked> hoursWorkedList = hoursWorkedService.findAll().stream()
.filter(hw -> hw.getEmployee().getTeam().equals(selectedEquipo) && hw.getWeekNumber() == weekNumber) .filter(hw -> hw.getEmployee().getTeam().getId()
.equals(selectedEquipo.getId()) && hw.getWeekNumber() == weekNumber)
.collect(Collectors.toList()); .collect(Collectors.toList());
if (hoursWorkedList.isEmpty()) { if (hoursWorkedList.isEmpty()) {
Notification.show("No hay horas trabajadas disponibles para generar el reporte.", Notification.show("No hay horas trabajadas disponibles para generar el reporte.",
3000, Notification.Position.MIDDLE); 3000,
Notification.Position.MIDDLE);
return; return;
} }
List<Map<String, Object>> data = hoursWorkedList.stream()
.map(hoursWorked -> {
Map<String, Object> map = new HashMap<>();
map.put("ID", hoursWorked.getId().toString());
map.put("Employee ID", hoursWorked.getEmployee().getId().toString());
map.put("Empleado", hoursWorked.getEmployee().getFirstName() + " "
+ hoursWorked.getEmployee().getLastName());
map.put("Horas Trabajadas", hoursWorked.getTotalHours());
map.put("Horas Pendientes", 40 - hoursWorked.getTotalHours());
map.put("Observaciones", "");
return map;
})
.collect(Collectors.toList());
grid.setItems(data);
generateExcelDownloadLink(data, weekNumber);
}
private void updateHeaderLayout(final Team team, final LocalDate dateInWeek) {
headerLayout.removeAll();
if (team != null && dateInWeek != null) {
LocalDate startOfWeek = dateInWeek.with(DayOfWeek.FRIDAY);
LocalDate endOfWeek = dateInWeek.with(DayOfWeek.THURSDAY);
int weekNumber = getWeekOfYear(dateInWeek);
String formattedStartDate = startOfWeek.getDayOfMonth() + " de "
+ startOfWeek.getMonth().getDisplayName(TextStyle.FULL, Locale.getDefault());
String formattedEndDate = endOfWeek.getDayOfMonth() + " de "
+ endOfWeek.getMonth().getDisplayName(TextStyle.FULL, Locale.getDefault());
headerLayout.add(new Span("Informe " + String.format("%03d", weekNumber)
+ "/" + currentYear) {{
getStyle().set("font-size", "24px");
getStyle().set("font-weight", "bold");
}});
String teamLeadName = employeeService.getTeamLeadName(team.getId());
headerLayout.add(
new Span("Asunto: Informe Semanal de Horas Trabajadas") {{
getStyle().set("font-size", "18px");
}},
semanaInfoSpan,
new Span("Horas a cumplir: 40 horas") {{
getStyle().set("font-size", "18px");
}},
new Span("Equipo: " + team.getName()) {{
getStyle().set("font-size", "18px");
}},
new Span("Team Lead: " + teamLeadName) {{
getStyle().set("font-size", "18px");
}}
);
}
}
private void generateExcelDownloadLink(final List<Map<String, Object>> data,
final int weekNumber) {
try { try {
List<String> headers = List.of("ID", "Employee ID", "Empleado", "Week Number", "Total Hours"); List<String> headers = List.of("ID", "Employee ID", "Empleado",
"Horas Trabajadas", "Horas Pendientes", "Observaciones");
List<Map<String, Object>> data = hoursWorkedList.stream() String selectedTeam = equipoComboBox.getValue().getName();
.map(hoursWorked -> { byte[] excelBytes = reportService.writeAsExcel("hours_worked_report",
Map<String, Object> map = new HashMap<>(); headers, data, selectedTeam, weekNumber, currentYear);
map.put("ID", hoursWorked.getId().toString());
map.put("Employee ID", hoursWorked.getEmployee().getId().toString());
map.put("Empleado", hoursWorked.getEmployee().getFirstName() + " " + hoursWorked.getEmployee().getLastName());
map.put("Week Number", hoursWorked.getWeekNumber());
map.put("Total Hours", hoursWorked.getTotalHours());
return map;
})
.collect(Collectors.toList());
byte[] excelBytes = reportService.writeAsExcel("hours_worked_report", headers, data);
StreamResource excelResource = new StreamResource("hours_worked_report.xlsx", StreamResource excelResource = new StreamResource("hours_worked_report.xlsx",
() -> new ByteArrayInputStream(excelBytes)); () -> new ByteArrayInputStream(excelBytes));
excelResource.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); if (downloadLink == null) {
excelResource.setCacheTime(0); downloadLink = new Anchor(excelResource, "Descargar Reporte en Excel");
downloadLink.getElement().setAttribute("download", true);
if (downloadLink != null) { add(downloadLink);
remove(downloadLink); } else {
downloadLink.setHref(excelResource);
} }
downloadLink = new Anchor(excelResource, "Descargar Reporte de Horas Trabajadas");
downloadLink.getElement().setAttribute("download", true);
add(downloadLink);
Notification.show("Reporte de horas trabajadas generado exitosamente.",
3000, Notification.Position.MIDDLE);
} catch (Exception e) { } catch (Exception e) {
Notification.show("Error al generar el reporte de horas trabajadas. Inténtalo de nuevo.", Notification.show("Error al generar el reporte de horas trabajadas en Excel.",
3000, Notification.Position.MIDDLE); 3000, Notification.Position.MIDDLE);
e.printStackTrace();
} }
} }
private int getWeekOfYear(final LocalDate date) { private int getWeekOfYear(final LocalDate date) {
return date.get(WeekFields.of(Locale.getDefault()).weekOfWeekBasedYear()); return date.get(WeekFields.of(Locale.getDefault()).weekOfWeekBasedYear());
} }
public int getCurrentYear() {
return currentYear;
}
// Opcional: Si deseas permitir cambiar el año actual manualmente, agrega un setter
public void setCurrentYear(final int currentYear) {
this.currentYear = currentYear;
}
} }

View File

@ -6,7 +6,6 @@ import com.primefactorsolutions.service.TimeOffRequestService;
import com.primefactorsolutions.service.VacationService; import com.primefactorsolutions.service.VacationService;
import com.vaadin.flow.component.button.Button; import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.combobox.ComboBox; import com.vaadin.flow.component.combobox.ComboBox;
import com.vaadin.flow.component.grid.Grid;
import com.vaadin.flow.component.html.Div; import com.vaadin.flow.component.html.Div;
import com.vaadin.flow.component.html.H3; import com.vaadin.flow.component.html.H3;
import com.vaadin.flow.component.html.Span; import com.vaadin.flow.component.html.Span;
@ -20,8 +19,10 @@ import com.vaadin.flow.router.Route;
import com.vaadin.flow.spring.annotation.SpringComponent; import com.vaadin.flow.spring.annotation.SpringComponent;
import jakarta.annotation.security.PermitAll; import jakarta.annotation.security.PermitAll;
import org.springframework.context.annotation.Scope; import org.springframework.context.annotation.Scope;
import org.vaadin.firitin.components.grid.PagingGrid;
import java.time.LocalDate; import java.time.LocalDate;
import java.time.Period;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
@ -37,7 +38,7 @@ public class RequestEmployeeView extends Div implements HasUrlParameter<String>
private final TimeOffRequestService requestService; private final TimeOffRequestService requestService;
private final EmployeeService employeeService; private final EmployeeService employeeService;
private final VacationService vacationService; private final VacationService vacationService;
private final Grid<TimeOffRequest> requestGrid = new Grid<>(TimeOffRequest.class); private final PagingGrid<TimeOffRequest> requestGrid = new PagingGrid<>(TimeOffRequest.class);
private List<TimeOffRequest> requests = Collections.emptyList(); private List<TimeOffRequest> requests = Collections.emptyList();
private ComboBox<TimeOffRequestType> categoryFilter; private ComboBox<TimeOffRequestType> categoryFilter;
private ComboBox<TimeOffRequestStatus> stateFilter; private ComboBox<TimeOffRequestStatus> stateFilter;
@ -66,7 +67,7 @@ public class RequestEmployeeView extends Div implements HasUrlParameter<String>
} }
private ComboBox<TimeOffRequestType> createCategoryFilter() { private ComboBox<TimeOffRequestType> createCategoryFilter() {
categoryFilter = new ComboBox<>("Category"); categoryFilter = new ComboBox<>("Categoría");
categoryFilter.setItems(TimeOffRequestType.values()); categoryFilter.setItems(TimeOffRequestType.values());
categoryFilter.setValue(TimeOffRequestType.values()[0]); categoryFilter.setValue(TimeOffRequestType.values()[0]);
categoryFilter.addValueChangeListener(event -> refreshRequestGrid(event.getValue(), stateFilter.getValue())); categoryFilter.addValueChangeListener(event -> refreshRequestGrid(event.getValue(), stateFilter.getValue()));
@ -74,7 +75,7 @@ public class RequestEmployeeView extends Div implements HasUrlParameter<String>
} }
private ComboBox<TimeOffRequestStatus> createStateFilter() { private ComboBox<TimeOffRequestStatus> createStateFilter() {
stateFilter = new ComboBox<>("State"); stateFilter = new ComboBox<>("Estado de la solicitud");
stateFilter.setItems(TimeOffRequestStatus.values()); stateFilter.setItems(TimeOffRequestStatus.values());
stateFilter.setValue(TimeOffRequestStatus.values()[0]); stateFilter.setValue(TimeOffRequestStatus.values()[0]);
stateFilter.addValueChangeListener(event -> refreshRequestGrid(categoryFilter.getValue(), event.getValue())); stateFilter.addValueChangeListener(event -> refreshRequestGrid(categoryFilter.getValue(), event.getValue()));
@ -87,10 +88,16 @@ public class RequestEmployeeView extends Div implements HasUrlParameter<String>
"state", "state",
"startDate", "startDate",
"endDate", "endDate",
"daysToBeTake", "daysToBeTake");
"daysBalance"
); requestGrid.getColumnByKey("category").setHeader("Categoría");
requestGrid.setAllRowsVisible(true); requestGrid.getColumnByKey("state").setHeader("Estado");
requestGrid.getColumnByKey("startDate").setHeader("Fecha de Inicio");
requestGrid.getColumnByKey("endDate").setHeader("Fecha de Fin");
requestGrid.getColumnByKey("daysToBeTake").setHeader("Días a Tomar");
requestGrid.setPaginationBarMode(PagingGrid.PaginationBarMode.BOTTOM);
requestGrid.setPageSize(5);
requestGrid.asSingleSelect().addValueChangeListener(event -> { requestGrid.asSingleSelect().addValueChangeListener(event -> {
TimeOffRequest selectedRequest = event.getValue(); TimeOffRequest selectedRequest = event.getValue();
if (selectedRequest != null) { if (selectedRequest != null) {
@ -104,48 +111,103 @@ public class RequestEmployeeView extends Div implements HasUrlParameter<String>
.filter(this::verificationIsHoliday) .filter(this::verificationIsHoliday)
.mapToDouble(TimeOffRequest::getAvailableDays) .mapToDouble(TimeOffRequest::getAvailableDays)
.sum(); .sum();
double totalVacations = requests.stream() double totalVacations = calculateVacationDays(employeeService.getEmployee(employeeId));
.filter(req -> req.getCategory().toString().startsWith("VACATION"))
.mapToDouble(TimeOffRequest::getAvailableDays)
.sum();
double totalPersonalDays = requests.stream() double totalPersonalDays = requests.stream()
.filter(req -> !verificationIsHoliday(req)) // Solo los de tipo OTHER .filter(req -> !verificationIsHoliday(req))
.filter(req -> !req.getCategory().name().startsWith("VACACION"))
.mapToDouble(TimeOffRequest::getAvailableDays) .mapToDouble(TimeOffRequest::getAvailableDays)
.sum(); .sum();
double totalAvailableDays = totalHoliday + totalVacations + totalPersonalDays; double totalAvailableDays = totalHoliday + totalVacations + totalPersonalDays;
return new VerticalLayout( return new VerticalLayout(
new Span("TOTAL HOLIDAYS: " + totalHoliday), new Span("Total feriados: " + totalHoliday),
new Span("TOTAL VACATIONS: " + totalVacations), new Span("Total vacaciones: " + totalVacations),
new Span("TOTAL PERSONAL DAYS: " + totalPersonalDays), new Span("Total días personales: " + totalPersonalDays),
new Span("TOTAL GENERAL: " + totalAvailableDays) new Span("Total general: " + totalAvailableDays)
); );
} }
private double calculateVacationDays(final Employee employee) {
if (employee.getDateOfEntry() != null) {
LocalDate entryDate = employee.getDateOfEntry();
LocalDate today = LocalDate.now();
boolean hasAnniversaryPassed = entryDate.getMonthValue() < today.getMonthValue()
|| (entryDate.getMonthValue() == today.getMonthValue() && entryDate.getDayOfMonth()
<= today.getDayOfMonth());
LocalDate previousVacationYearDate;
LocalDate currentVacationYearDate;
if (hasAnniversaryPassed) {
previousVacationYearDate = LocalDate.of(
today.getYear() - 1,
entryDate.getMonth(),
entryDate.getDayOfMonth()
);
currentVacationYearDate = LocalDate.of(
today.getYear(),
entryDate.getMonth(),
entryDate.getDayOfMonth()
);
} else {
previousVacationYearDate = LocalDate.of(
today.getYear() - 2,
entryDate.getMonth(),
entryDate.getDayOfMonth()
);
currentVacationYearDate = LocalDate.of(
today.getYear() - 1,
entryDate.getMonth(),
entryDate.getDayOfMonth()
);
}
return calculateVacationDaysSinceEntry(entryDate, previousVacationYearDate)
+ calculateVacationDaysSinceEntry(entryDate, currentVacationYearDate);
} else {
return 0.0;
}
}
private double calculateVacationDaysSinceEntry(final LocalDate dateOfEntry, final LocalDate date) {
int yearsOfService = dateOfEntry != null ? Period.between(dateOfEntry, date).getYears() : 0;
if (yearsOfService > 10) {
return 30;
}
if (yearsOfService > 5) {
return 20;
}
if (yearsOfService > 1) {
return 15;
}
return 0;
}
private Boolean verificationIsHoliday(final TimeOffRequest request) { private Boolean verificationIsHoliday(final TimeOffRequest request) {
Vacation vacation = vacationService.findVacationByCategory(request.getCategory()); Vacation vacation = vacationService.findVacationByCategory(request.getCategory());
return vacation.getType() != Vacation.Type.OTHER; return vacation.getType() != Vacation.Type.OTHER;
} }
private HorizontalLayout createActionButtons() { private HorizontalLayout createActionButtons() {
Button viewButton = new Button("View", event -> { Button viewButton = createButton("Ver", () -> navigateToViewRequest(request));
if (request != null) { Button editButton = createButton("Editar", () -> navigateToEditRequest(request));
navigateToViewRequest(request); Button closeButton = new Button("Salir", event -> navigateToRequestsListView());
} else {
Notification.show("Please select a request to view.", 3000, Notification.Position.MIDDLE);
}
});
Button editButton = new Button("Edit", event -> {
if (request != null) {
navigateToEditRequest(request);
} else {
Notification.show("Please select a request to view.", 3000, Notification.Position.MIDDLE);
}
});
Button closeButton = new Button("Close", event -> navigateToRequestsListView());
return new HorizontalLayout(viewButton, editButton, closeButton); return new HorizontalLayout(viewButton, editButton, closeButton);
} }
private Button createButton(final String caption, final Runnable action) {
return new Button(caption, event -> {
if (request != null) {
action.run();
} else {
Notification.show("Seleccione una solicitud.", 3000, Notification.Position.MIDDLE);
}
});
}
private void navigateToRequestsListView() { private void navigateToRequestsListView() {
getUI().ifPresent(ui -> ui.navigate(RequestsListView.class)); getUI().ifPresent(ui -> ui.navigate(RequestsListView.class));
} }
@ -163,38 +225,30 @@ public class RequestEmployeeView extends Div implements HasUrlParameter<String>
} }
private void refreshRequestGrid(final TimeOffRequestType category, final TimeOffRequestStatus state) { private void refreshRequestGrid(final TimeOffRequestType category, final TimeOffRequestStatus state) {
List<TimeOffRequest> filteredRequests = allFiltersAreNull(category, state) requestGrid.setPagingDataProvider((page, pageSize) -> {
? requestService.findRequestsByEmployeeId(employeeId) int start = (int) (page * requestGrid.getPageSize());
: fetchFilteredTimeOffRequests(category, state); return fetchFilteredTimeOffRequests(start, pageSize, category, state);
for (TimeOffRequest request : filteredRequests) { });
if (request.getExpiration().isBefore(LocalDate.now())) { requestGrid.getDataProvider().refreshAll();
request.setState(TimeOffRequestStatus.EXPIRED);
}
}
for (TimeOffRequest request : filteredRequests) {
requestService.saveTimeOffRequest(request);
}
requestGrid.setItems(filteredRequests);
} }
private boolean allFiltersAreNull(final TimeOffRequestType category, final TimeOffRequestStatus state) { private List<TimeOffRequest> fetchFilteredTimeOffRequests(final int start,
return category == null && state == null; final int pageSize,
} final TimeOffRequestType category,
private List<TimeOffRequest> fetchFilteredTimeOffRequests(final TimeOffRequestType category,
final TimeOffRequestStatus state) { final TimeOffRequestStatus state) {
requests = requestService.findRequestsByEmployeeId(employeeId); requests = requestService.findRequestsByEmployeeId(employeeId);
if (category != null && !"ALL".equals(category.name())) { if (category != null && !"TODOS".equals(category.name())) {
requests = requests.stream() requests = requests.stream()
.filter(req -> req.getCategory().equals(category)) .filter(req -> req.getCategory().equals(category))
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
if (state != null && !"ALL".equals(state.name())) { if (state != null && !"TODOS".equals(state.name())) {
requests = requests.stream() requests = requests.stream()
.filter(req -> req.getState().equals(state)) .filter(req -> req.getState().equals(state))
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
return requests; int end = Math.min(start + pageSize, requests.size());
return requests.subList(start, end);
} }
@Override @Override
@ -208,7 +262,7 @@ public class RequestEmployeeView extends Div implements HasUrlParameter<String>
} }
private void setViewTitle(final String employeeName, final String employeeTeam) { private void setViewTitle(final String employeeName, final String employeeTeam) {
addComponentAsFirst(new H3("Name: " + employeeName)); addComponentAsFirst(new H3("Nombre del empleado: " + employeeName));
addComponentAtIndex(1, new H3("Team: " + employeeTeam)); addComponentAtIndex(1, new H3("Equipo: " + employeeTeam));
} }
} }

View File

@ -32,13 +32,13 @@ import java.util.UUID;
@Route(value = "/requests/new", layout = MainLayout.class) @Route(value = "/requests/new", layout = MainLayout.class)
public class RequestRegisterView extends VerticalLayout { public class RequestRegisterView extends VerticalLayout {
private final ComboBox<Employee> employeeComboBox = new ComboBox<>("Employee"); private final ComboBox<Employee> employeeComboBox = new ComboBox<>("Empleado");
private final ComboBox<TimeOffRequestType> categoryComboBox = new ComboBox<>("Category"); private final ComboBox<TimeOffRequestType> categoryComboBox = new ComboBox<>("Categoría");
private final NumberField availableDaysField = new NumberField("Available Days"); private final NumberField availableDaysField = new NumberField("Días disponibles");
private final DatePicker startDatePicker = new DatePicker("Start Date"); private final DatePicker startDatePicker = new DatePicker("Fecha de inicio");
private final DatePicker endDatePicker = new DatePicker("End Date"); private final DatePicker endDatePicker = new DatePicker("Fecha final");
private final NumberField daysToBeTakenField = new NumberField("Days To Be Taken"); private final NumberField daysToBeTakenField = new NumberField("Días a tomar");
private final NumberField balanceDaysField = new NumberField("Balance Days"); private final NumberField balanceDaysField = new NumberField("Días de saldo");
private final TimeOffRequestService requestService; private final TimeOffRequestService requestService;
private final EmployeeService employeeService; private final EmployeeService employeeService;
@ -59,11 +59,24 @@ public class RequestRegisterView extends VerticalLayout {
this.employeeService = employeeService; this.employeeService = employeeService;
this.vacationService = vacationService; this.vacationService = vacationService;
this.binder = new Binder<>(TimeOffRequest.class); this.binder = new Binder<>(TimeOffRequest.class);
initializeView();
}
private void initializeView() {
configureFormFields(); configureFormFields();
configureButtons(); configureButtons();
configureBinder(); configureBinder();
setupFormLayout(); setupFormLayout();
configureInitialFieldStates();
}
private void configureInitialFieldStates() {
categoryComboBox.setEnabled(false);
startDatePicker.setEnabled(false);
endDatePicker.setEnabled(false);
availableDaysField.setReadOnly(true);
daysToBeTakenField.setReadOnly(true);
balanceDaysField.setReadOnly(true);
} }
private void configureFormFields() { private void configureFormFields() {
@ -71,66 +84,75 @@ public class RequestRegisterView extends VerticalLayout {
employeeComboBox.setItemLabelGenerator(emp -> emp.getFirstName() + " " + emp.getLastName()); employeeComboBox.setItemLabelGenerator(emp -> emp.getFirstName() + " " + emp.getLastName());
employeeComboBox.addValueChangeListener(event -> { employeeComboBox.addValueChangeListener(event -> {
employee = event.getValue(); employee = event.getValue();
handleEmployeeSelection(employee); System.out.println("Clearing form..." + employee);
handleEmployeeSelection(event.getValue());
});
categoryComboBox.addValueChangeListener(event -> {
onCategoryChange(event.getValue());
handleCategorySelection(event.getValue());
}); });
categoryComboBox.setEnabled(false);
startDatePicker.setEnabled(false);
endDatePicker.setEnabled(false);
categoryComboBox.addValueChangeListener(event -> handleCategorySelection(event.getValue()));
startDatePicker.addValueChangeListener(event -> updateDatePickerMinValues()); startDatePicker.addValueChangeListener(event -> updateDatePickerMinValues());
endDatePicker.addValueChangeListener(event -> calculateDays()); endDatePicker.addValueChangeListener(event -> calculateDays());
availableDaysField.setReadOnly(true);
daysToBeTakenField.setReadOnly(true);
balanceDaysField.setReadOnly(true);
} }
private void configureBinder() { private void configureBinder() {
binder.forField(employeeComboBox) binder.forField(employeeComboBox)
.asRequired("Employee is required")
.bind(TimeOffRequest::getEmployee, TimeOffRequest::setEmployee); .bind(TimeOffRequest::getEmployee, TimeOffRequest::setEmployee);
binder.forField(categoryComboBox) binder.forField(categoryComboBox)
.asRequired("Category is required")
.bind(TimeOffRequest::getCategory, TimeOffRequest::setCategory); .bind(TimeOffRequest::getCategory, TimeOffRequest::setCategory);
binder.forField(availableDaysField) binder.forField(availableDaysField)
.bind(TimeOffRequest::getAvailableDays, TimeOffRequest::setAvailableDays); .bind(TimeOffRequest::getAvailableDays, TimeOffRequest::setAvailableDays);
binder.forField(startDatePicker) binder.forField(startDatePicker)
.asRequired("Start date is required")
.bind(TimeOffRequest::getStartDate, TimeOffRequest::setStartDate); .bind(TimeOffRequest::getStartDate, TimeOffRequest::setStartDate);
binder.forField(endDatePicker) binder.forField(endDatePicker)
.asRequired("End date is required")
.bind(TimeOffRequest::getEndDate, TimeOffRequest::setEndDate); .bind(TimeOffRequest::getEndDate, TimeOffRequest::setEndDate);
binder.forField(daysToBeTakenField) binder.forField(daysToBeTakenField)
.bind(TimeOffRequest::getDaysToBeTake, TimeOffRequest::setDaysToBeTake); .bind(TimeOffRequest::getDaysToBeTake, TimeOffRequest::setDaysToBeTake);
binder.forField(balanceDaysField) binder.forField(balanceDaysField)
.bind(TimeOffRequest::getDaysBalance, TimeOffRequest::setDaysBalance); .bind(TimeOffRequest::getDaysBalance, TimeOffRequest::setDaysBalance);
binder.setBean(new TimeOffRequest()); binder.setBean(new TimeOffRequest());
} }
private void handleEmployeeSelection(final Employee selectedEmployee) { private void handleEmployeeSelection(final Employee selectedEmployee) {
clearForm();
if (selectedEmployee != null) { if (selectedEmployee != null) {
categoryComboBox.clear();
availableDaysField.clear();
startDatePicker.clear();
endDatePicker.clear();
daysToBeTakenField.clear();
balanceDaysField.clear();
categoryComboBox.setEnabled(true); categoryComboBox.setEnabled(true);
startDatePicker.setEnabled(false);
endDatePicker.setEnabled(false);
filterCategories(selectedEmployee); filterCategories(selectedEmployee);
} }
} }
private void filterCategories(final Employee employee) { private void filterCategories(final Employee employee) {
categoryComboBox.clear();
List<TimeOffRequest> employeeRequests = requestService.findRequestsByEmployeeId(employee.getId()); List<TimeOffRequest> employeeRequests = requestService.findRequestsByEmployeeId(employee.getId());
List<TimeOffRequestType> allCategories = Arrays.asList(TimeOffRequestType.values()); List<TimeOffRequestType> allCategories = Arrays.asList(TimeOffRequestType.values());
List<TimeOffRequestType> availableCategories = allCategories.stream() List<TimeOffRequestType> availableCategories = allCategories.stream()
.filter(category -> isCategoryAvailable(employeeRequests, category)) .filter(category -> isCategoryAvailable(employeeRequests, category))
.filter(category -> isCategoryAllowedByGender(category, employee.getGender())) .filter(category -> isCategoryAllowedByGender(category, employee.getGender()))
.filter(category -> category != TimeOffRequestType.VACACION_GESTION_ANTERIOR
&& category != TimeOffRequestType.TODOS)
.toList(); .toList();
categoryComboBox.setItems(availableCategories); categoryComboBox.setItems(availableCategories);
} }
private void onCategoryChange(final TimeOffRequestType selectedCategory) {
if (selectedCategory == TimeOffRequestType.VACACION_GESTION_ACTUAL) {
startDatePicker.setEnabled(true);
endDatePicker.setEnabled(true);
} else {
startDatePicker.setEnabled(true);
endDatePicker.setEnabled(false);
}
}
private boolean isCategoryAvailable(final List<TimeOffRequest> employeeRequests, private boolean isCategoryAvailable(final List<TimeOffRequest> employeeRequests,
final TimeOffRequestType category) { final TimeOffRequestType category) {
List<TimeOffRequest> requestsByCategory = employeeRequests.stream() List<TimeOffRequest> requestsByCategory = employeeRequests.stream()
@ -145,32 +167,31 @@ public class RequestRegisterView extends VerticalLayout {
.max(Comparator.comparing(TimeOffRequest::getStartDate)) .max(Comparator.comparing(TimeOffRequest::getStartDate))
.orElse(null); .orElse(null);
if (category == TimeOffRequestType.HEALTH_PERMIT if (category == TimeOffRequestType.PERMISOS_DE_SALUD
|| category == TimeOffRequestType.VACATION_CURRENT_MANAGEMENT || category == TimeOffRequestType.VACACION_GESTION_ACTUAL
|| category == TimeOffRequestType.VACATION_PREVIOUS_MANAGEMENT) { || category == TimeOffRequestType.VACACION_GESTION_ANTERIOR) {
return latestRequest.getState() == TimeOffRequestStatus.EXPIRED return latestRequest.getState() == TimeOffRequestStatus.VENCIDO
|| (latestRequest.getState() == TimeOffRequestStatus.TAKEN && latestRequest.getDaysBalance() > 0); || (latestRequest.getState() == TimeOffRequestStatus.TOMADO && latestRequest.getDaysBalance() > 0);
} else { } else {
return latestRequest.getState() == TimeOffRequestStatus.EXPIRED; return latestRequest.getState() == TimeOffRequestStatus.VENCIDO;
} }
} }
private boolean isCategoryAllowedByGender(final TimeOffRequestType category, final Employee.Gender gender) { private boolean isCategoryAllowedByGender(final TimeOffRequestType category, final Employee.Gender gender) {
if (gender == Employee.Gender.MALE) { if (gender == Employee.Gender.MALE) {
return category != TimeOffRequestType.MATERNITY return category != TimeOffRequestType.MATERNIDAD
&& category != TimeOffRequestType.MOTHERS_DAY && category != TimeOffRequestType.DIA_DE_LA_MADRE
&& category != TimeOffRequestType.INTERNATIONAL_WOMENS_DAY && category != TimeOffRequestType.DIA_DE_LA_MUJER_INTERNACIONAL
&& category != TimeOffRequestType.NATIONAL_WOMENS_DAY; && category != TimeOffRequestType.DIA_DE_LA_MUJER_NACIONAL;
} else { } else {
return category != TimeOffRequestType.FATHERS_DAY return category != TimeOffRequestType.DIA_DEL_PADRE
&& category != TimeOffRequestType.PATERNITY; && category != TimeOffRequestType.PATERNIDAD;
} }
} }
private void handleCategorySelection(final TimeOffRequestType selectedCategory) { private void handleCategorySelection(final TimeOffRequestType selectedCategory) {
if (selectedCategory != null) { if (selectedCategory != null) {
updateAvailableDays(selectedCategory); updateAvailableDays(selectedCategory);
startDatePicker.setEnabled(true);
} }
} }
@ -181,16 +202,16 @@ public class RequestRegisterView extends VerticalLayout {
if (vacation != null) { if (vacation != null) {
TimeOffRequest requestWithBalance = requests.stream() TimeOffRequest requestWithBalance = requests.stream()
.filter(request -> request.getDaysBalance() > 0 .filter(request -> request.getDaysBalance() > 0
&& request.getState() != TimeOffRequestStatus.EXPIRED) && request.getState() != TimeOffRequestStatus.VENCIDO)
.max(Comparator.comparing(TimeOffRequest::getStartDate)) .max(Comparator.comparing(TimeOffRequest::getStartDate))
.orElse(null); .orElse(null);
if (requestWithBalance != null) { if (requestWithBalance != null) {
if (requestWithBalance.getState() == TimeOffRequestStatus.TAKEN) { if (requestWithBalance.getState() == TimeOffRequestStatus.TOMADO) {
availableDaysField.setValue(requestWithBalance.getDaysBalance()); availableDaysField.setValue(requestWithBalance.getDaysBalance());
} else if (requestWithBalance.getState() == TimeOffRequestStatus.EXPIRED) { } else if (requestWithBalance.getState() == TimeOffRequestStatus.VENCIDO) {
availableDaysField.setValue(vacation.getDuration()); availableDaysField.setValue(vacation.getDuration());
} }
} else if (vacation.getCategory() == TimeOffRequestType.VACATION_CURRENT_MANAGEMENT) { } else if (vacation.getCategory() == TimeOffRequestType.VACACION_GESTION_ACTUAL) {
LocalDate dateOfEntry = employeeComboBox.getValue().getDateOfEntry(); LocalDate dateOfEntry = employeeComboBox.getValue().getDateOfEntry();
LocalDate currentDate = LocalDate.now(); LocalDate currentDate = LocalDate.now();
long yearsOfService = ChronoUnit.YEARS.between(dateOfEntry, currentDate); long yearsOfService = ChronoUnit.YEARS.between(dateOfEntry, currentDate);
@ -218,70 +239,83 @@ public class RequestRegisterView extends VerticalLayout {
List<TimeOffRequest> previousRequests List<TimeOffRequest> previousRequests
= requestService.findByEmployeeAndCategory(employeeId, vacation.getCategory()); = requestService.findByEmployeeAndCategory(employeeId, vacation.getCategory());
int startYear; int startYear = calculateStartYear(previousRequests);
if (previousRequests.isEmpty()) {
startYear = LocalDate.now().getYear();
} else {
int lastRequestYear = previousRequests.stream()
.max(Comparator.comparing(TimeOffRequest::getStartDate))
.map(request -> request.getStartDate().getYear())
.orElse(LocalDate.now().getYear());
int proposedYear = lastRequestYear + 1; startDate = determineStartDate(vacation, startYear);
int currentYear = LocalDate.now().getYear();
if (proposedYear < currentYear) { if (startDate.isBefore(LocalDate.now())) {
startYear = currentYear; startDate = determineStartDate(vacation, startYear + 1);
} else {
startYear = proposedYear;
}
} }
if (vacation.getMonthOfYear() != null && vacation.getDayOfMonth() != null) { if (startDate != null) {
startDate = LocalDate.of(
startYear,
vacation.getMonthOfYear().intValue(),
vacation.getDayOfMonth().intValue());
endDate = startDate.plusDays(vacation.getExpiration().intValue() - 1); endDate = startDate.plusDays(vacation.getExpiration().intValue() - 1);
} else { } else {
if (vacation.getCategory() == TimeOffRequestType.BIRTHDAY && employee.getBirthday() != null) { startDate = LocalDate.now();
startDate = LocalDate.of(
startYear,
employee.getBirthday().getMonth(),
employee.getBirthday().getDayOfMonth());
endDate = startDate.plusDays(vacation.getExpiration().intValue() - 1);
} else if (vacation.getCategory() == TimeOffRequestType.HEALTH_PERMIT) {
startDate = LocalDate.now();
endDate = LocalDate.of(startYear, 12, 31);
} else {
startDate = LocalDate.now();
}
} }
setPickerValues(vacation, startDate);
setPickerLimits(startDate, endDate);
}
private int calculateStartYear(final List<TimeOffRequest> previousRequests) {
if (previousRequests.isEmpty()) {
return LocalDate.now().getYear();
}
int lastRequestYear = previousRequests.stream()
.max(Comparator.comparing(TimeOffRequest::getStartDate))
.map(request -> request.getStartDate().getYear())
.orElse(LocalDate.now().getYear());
int currentYear = LocalDate.now().getYear();
return Math.max(lastRequestYear + 1, currentYear);
}
private LocalDate determineStartDate(final Vacation vacation, final int startYear) {
if (vacation.getMonthOfYear() != null && vacation.getDayOfMonth() != null) {
return LocalDate.of(startYear, vacation.getMonthOfYear().intValue(), vacation.getDayOfMonth().intValue());
}
if (vacation.getCategory() == TimeOffRequestType.CUMPLEAÑOS && employee.getBirthday() != null) {
return LocalDate.of(startYear, employee.getBirthday().getMonth(), employee.getBirthday().getDayOfMonth());
}
if (vacation.getCategory() == TimeOffRequestType.PERMISOS_DE_SALUD) {
return LocalDate.now();
}
return LocalDate.now();
}
private void setPickerValues(final Vacation vacation, final LocalDate startDate) {
startDatePicker.setValue(startDate); startDatePicker.setValue(startDate);
if ((vacation.getDuration() != null && vacation.getDuration() == 0.5) if ((vacation.getDuration() != null && vacation.getDuration() == 0.5)
|| vacation.getCategory() == TimeOffRequestType.HEALTH_PERMIT) { || vacation.getCategory() == TimeOffRequestType.PERMISOS_DE_SALUD) {
endDatePicker.setValue(startDate); endDatePicker.setValue(startDate);
} else { } else {
int durationDays = (vacation.getDuration() != null ? vacation.getDuration().intValue() - 1 : 0); int durationDays = (vacation.getDuration() != null ? vacation.getDuration().intValue() - 1 : 0);
endDatePicker.setValue(startDate.plusDays(durationDays)); endDatePicker.setValue(startDate.plusDays(durationDays));
} }
}
private void setPickerLimits(final LocalDate startDate, final LocalDate endDate) {
startDatePicker.setMin(startDate); startDatePicker.setMin(startDate);
startDatePicker.setMax(endDate); startDatePicker.setMax(endDate);
endDatePicker.setMin(startDate); endDatePicker.setMin(startDate);
endDatePicker.setMax(endDate); endDatePicker.setMax(endDate);
} }
private void updateDatePickerMinValues() { private void updateDatePickerMinValues() {
LocalDate startDate = startDatePicker.getValue(); LocalDate startDate = startDatePicker.getValue();
if (vacation.getDuration() == 0.5) { if (availableDaysField.getValue() != null) {
endDatePicker.setValue(startDate.plusDays(0)); if (availableDaysField.getValue() == 0.5) {
} else { endDatePicker.setValue(startDate.plusDays(0));
endDatePicker.setValue(startDate.plusDays(vacation.getDuration().intValue() - 1)); } else {
endDatePicker.setValue(startDate.plusDays(availableDaysField.getValue().intValue() - 1));
}
calculateDays();
} }
calculateDays();
} }
private void calculateDays() { private void calculateDays() {
@ -289,26 +323,53 @@ public class RequestRegisterView extends VerticalLayout {
LocalDate endDate = endDatePicker.getValue(); LocalDate endDate = endDatePicker.getValue();
Double availableDays = availableDaysField.getValue(); Double availableDays = availableDaysField.getValue();
if (startDate != null && endDate != null) { if (areDatesValid(startDate, endDate)) {
double daysToBeTaken = java.time.temporal.ChronoUnit.DAYS.between(startDate, endDate) + 1; double daysToBeTaken = calculateDaysBetween(startDate, endDate);
if (vacation.getCategory() == TimeOffRequestType.HEALTH_PERMIT || vacation.getDuration() == 0.5) { setDaysToBeTakenField(daysToBeTaken);
daysToBeTakenField.setValue(0.5);
} else { double balanceDays = calculateBalanceDays(availableDays, daysToBeTakenField.getValue());
daysToBeTakenField.setValue(daysToBeTaken);
}
double balanceDays = availableDays - daysToBeTakenField.getValue();
balanceDaysField.setValue(balanceDays); balanceDaysField.setValue(balanceDays);
if (balanceDays < 0) {
clearFields();
}
} }
} }
private boolean areDatesValid(final LocalDate startDate, final LocalDate endDate) {
return startDate != null && endDate != null;
}
private double calculateDaysBetween(final LocalDate startDate, final LocalDate endDate) {
return java.time.temporal.ChronoUnit.DAYS.between(startDate, endDate) + 1;
}
private void setDaysToBeTakenField(final double daysToBeTaken) {
if (vacation.getCategory() == TimeOffRequestType.PERMISOS_DE_SALUD) {
daysToBeTakenField.setValue(0.5);
} else {
daysToBeTakenField.setValue(daysToBeTaken);
}
}
private double calculateBalanceDays(final double availableDays, final double daysToBeTaken) {
return availableDays - daysToBeTaken;
}
private void clearFields() {
daysToBeTakenField.clear();
balanceDaysField.clear();
endDatePicker.clear();
}
private void configureButtons() { private void configureButtons() {
saveButton = new Button("Save", event -> saveRequest()); saveButton = new Button("Guardar", event -> saveRequest());
closeButton = new Button("Close", event -> closeForm()); closeButton = new Button("Salir", event -> closeForm());
} }
private void setupFormLayout() { private void setupFormLayout() {
add( add(
new H3("Add Vacation Request"), new H3("Añadir solicitud de vacaciones"),
employeeComboBox, employeeComboBox,
categoryComboBox, categoryComboBox,
availableDaysField, availableDaysField,
@ -321,59 +382,71 @@ public class RequestRegisterView extends VerticalLayout {
} }
private void saveRequest() { private void saveRequest() {
if (binder.validate().isOk()) { if (!binder.validate().isOk()) {
TimeOffRequest request = binder.getBean(); Notification.show("Rellene correctamente todos los campos obligatorios.");
request.setStartDate(startDatePicker.getValue()); return;
request.setAvailableDays(availableDaysField.getValue()); }
if (endDate == null) {
request.setExpiration(endDatePicker.getValue());
} else {
request.setExpiration(endDate);
}
request.setState(TimeOffRequestStatus.REQUESTED);
List<TimeOffRequest> existingRequests = if (!validateForm()) {
requestService.findByEmployeeAndCategory(employee.getId(), request.getCategory()); Notification.show("Por favor, complete los campos antes de guardar");
return;
}
int maxRequests = request.getCategory() == TimeOffRequestType.HEALTH_PERMIT ? 4 : 2; TimeOffRequest request = prepareRequest();
if (existingRequests.size() >= maxRequests) { if (request.getCategory() == TimeOffRequestType.VACACION_GESTION_ACTUAL) {
existingRequests.stream() handleVacationRequest(request);
.min(Comparator.comparing(TimeOffRequest::getStartDate))
.ifPresent(oldestRequest -> requestService.deleteTimeOffRequest(oldestRequest.getId()));
}
requestService.saveTimeOffRequest(request);
Notification.show("Request saved successfully.");
closeForm();
} else { } else {
Notification.show("Please fill all required fields correctly."); handleExistingRequests(request);
}
requestService.saveTimeOffRequest(request);
Notification.show("Solicitud guardada correctamente.");
closeForm();
}
private TimeOffRequest prepareRequest() {
TimeOffRequest request = binder.getBean();
request.setStartDate(startDatePicker.getValue());
request.setAvailableDays(availableDaysField.getValue());
request.setExpiration(endDate != null ? endDate : endDatePicker.getValue());
request.setState(TimeOffRequestStatus.PENDIENTE);
return request;
}
private void handleExistingRequests(final TimeOffRequest request) {
List<TimeOffRequest> existingRequests =
requestService.findByEmployeeAndCategory(employee.getId(), request.getCategory());
int maxRequests = request.getCategory() == TimeOffRequestType.PERMISOS_DE_SALUD ? 4 : 2;
if (existingRequests.size() >= maxRequests) {
existingRequests.stream()
.min(Comparator.comparing(TimeOffRequest::getStartDate))
.ifPresent(oldestRequest -> requestService.deleteTimeOffRequest(oldestRequest.getId()));
} }
} }
private void updateBalanceForCategory(final TimeOffRequest newRequest) { private void handleVacationRequest(final TimeOffRequest request) {
List<TimeOffRequest> requests = requestService.findByEmployeeAndCategory( List<TimeOffRequest> existingRequests = requestService.findByEmployeeAndCategory(
newRequest.getEmployee().getId(), newRequest.getCategory()); employee.getId(),
TimeOffRequestType.VACACION_GESTION_ACTUAL
if (vacation.getCategory() == TimeOffRequestType.HEALTH_PERMIT );
&& vacation.getCategory() == TimeOffRequestType.VACATION_CURRENT_MANAGEMENT) { if (!existingRequests.isEmpty()) {
for (TimeOffRequest request : requests) { TimeOffRequest existingRequest = existingRequests.getFirst();
double newBalance = request.getDaysBalance() - newRequest.getDaysToBeTake(); existingRequest.setCategory(TimeOffRequestType.VACACION_GESTION_ANTERIOR);
request.setDaysBalance(newBalance); requestService.saveTimeOffRequest(existingRequest);
requestService.saveTimeOffRequest(request);
}
} }
} }
private boolean validateForm() {
return employeeComboBox.getValue() != null
&& categoryComboBox.getValue() != null
&& startDatePicker.getValue() != null
&& endDatePicker.getValue() != null;
}
private void closeForm() { private void closeForm() {
getUI().ifPresent(ui -> ui.navigate(RequestsListView.class)); getUI().ifPresent(ui -> ui.navigate(RequestsListView.class));
} }
private void clearForm() {
availableDaysField.clear();
startDatePicker.clear();
endDatePicker.clear();
daysToBeTakenField.clear();
balanceDaysField.clear();
}
} }

View File

@ -27,12 +27,12 @@ import java.util.UUID;
@Route(value = "/requests/:requestId?/:action?", layout = MainLayout.class) @Route(value = "/requests/:requestId?/:action?", layout = MainLayout.class)
public class RequestView extends BeanValidationForm<TimeOffRequest> implements HasUrlParameter<String> { public class RequestView extends BeanValidationForm<TimeOffRequest> implements HasUrlParameter<String> {
private final ComboBox<TimeOffRequestStatus> state = new ComboBox<>("State"); private final ComboBox<TimeOffRequestStatus> state = new ComboBox<>("Estado de la solicitud");
private final DatePicker expiration = new DatePicker("Expiration"); private final DatePicker expiration = new DatePicker("Vencimiento");
private final DatePicker startDate = new DatePicker("Start Date"); private final DatePicker startDate = new DatePicker("Fecha de inicio");
private final DatePicker endDate = new DatePicker("End Date"); private final DatePicker endDate = new DatePicker("Fecha de fin");
private final NumberField availableDays = new NumberField("Available Days"); private final NumberField availableDays = new NumberField("Días disponibles");
private final NumberField daysToBeTake = new NumberField("Days To Be Take"); private final NumberField daysToBeTake = new NumberField("Días a tomar");
private final TimeOffRequestService requestService; private final TimeOffRequestService requestService;
private final EmployeeService employeeService; private final EmployeeService employeeService;
@ -85,13 +85,13 @@ public class RequestView extends BeanValidationForm<TimeOffRequest> implements H
} }
protected Button createSaveButton() { protected Button createSaveButton() {
saveButton = new Button("Save"); saveButton = new Button("Guardar");
saveButton.addClickListener(event -> saveRequest()); saveButton.addClickListener(event -> saveRequest());
return saveButton; return saveButton;
} }
protected Button createCloseButton() { protected Button createCloseButton() {
Button closeButton = new Button("Close"); Button closeButton = new Button("Salir");
closeButton.addClickListener(event -> closeForm()); closeButton.addClickListener(event -> closeForm());
return closeButton; return closeButton;
} }
@ -110,7 +110,7 @@ public class RequestView extends BeanValidationForm<TimeOffRequest> implements H
TimeOffRequest request = getEntity(); TimeOffRequest request = getEntity();
setRequestFieldValues(request); setRequestFieldValues(request);
requestService.saveTimeOffRequest(request); requestService.saveTimeOffRequest(request);
Notification.show("Request saved successfully."); Notification.show("Solicitud guardada correctamente.");
closeForm(); closeForm();
} }
} }
@ -147,14 +147,14 @@ public class RequestView extends BeanValidationForm<TimeOffRequest> implements H
} }
private H3 createEmployeeHeader() { private H3 createEmployeeHeader() {
return new H3("Employee: " + employee.getFirstName() + " " + employee.getLastName()); return new H3("Empleado: " + employee.getFirstName() + " " + employee.getLastName());
} }
private H3 createTeamHeader() { private H3 createTeamHeader() {
return new H3("Team: " + employee.getTeam().getName()); return new H3("Equipo: " + employee.getTeam().getName());
} }
private H3 createCategoryHeader() { private H3 createCategoryHeader() {
return new H3("Category: " + request.getCategory()); return new H3("Categoría: " + request.getCategory());
} }
} }

View File

@ -17,6 +17,8 @@ import jakarta.annotation.security.PermitAll;
import org.springframework.context.annotation.Scope; import org.springframework.context.annotation.Scope;
import org.vaadin.firitin.components.grid.PagingGrid; import org.vaadin.firitin.components.grid.PagingGrid;
import java.time.LocalDate;
import java.time.Period;
import java.util.*; import java.util.*;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@ -68,10 +70,10 @@ public class RequestsListView extends Main {
} }
private void setupRequestGrid() { private void setupRequestGrid() {
requestGrid.addColumn(this::getEmployeeFullName).setHeader("Employee"); requestGrid.addColumn(this::getEmployeeFullName).setHeader("Empleado");
requestGrid.addColumn(this::getTeamName).setHeader("Team"); requestGrid.addColumn(this::getTeamName).setHeader("Equipo");
requestGrid.addColumn(this::getEmployeeStatus).setHeader("Employee State"); requestGrid.addColumn(this::getEmployeeStatus).setHeader("Estado del empleado");
requestGrid.addColumn(this::getGeneralTotal).setHeader("General Total"); requestGrid.addColumn(this::getGeneralTotal).setHeader("Total general");
requestGrid.setPaginationBarMode(PagingGrid.PaginationBarMode.BOTTOM); requestGrid.setPaginationBarMode(PagingGrid.PaginationBarMode.BOTTOM);
requestGrid.setPageSize(5); requestGrid.setPageSize(5);
@ -84,14 +86,14 @@ public class RequestsListView extends Main {
} }
private HorizontalLayout createActionButtons() { private HorizontalLayout createActionButtons() {
Button viewButton = new Button("View", event -> { Button viewButton = new Button("Ver", event -> {
if (selectedEmployeeId != null) { if (selectedEmployeeId != null) {
navigateToTimeOffRequestView(selectedEmployeeId); navigateToTimeOffRequestView(selectedEmployeeId);
} else { } else {
Notification.show("Please select a request to view.", 3000, Notification.Position.MIDDLE); Notification.show("Seleccione una solicitud.", 3000, Notification.Position.MIDDLE);
} }
}); });
Button closeButton = new Button("Close", event -> navigateToMainView()); Button closeButton = new Button("Salir", event -> navigateToMainView());
return new HorizontalLayout(viewButton, closeButton); return new HorizontalLayout(viewButton, closeButton);
} }
@ -112,24 +114,24 @@ public class RequestsListView extends Main {
final Status state) { final Status state) {
List<Employee> filteredEmployees = employeeService.findAllEmployees(); List<Employee> filteredEmployees = employeeService.findAllEmployees();
if (employee != null && !"ALL".equals(employee.getFirstName())) { if (employee != null && !"TODOS".equals(employee.getFirstName())) {
filteredEmployees = filteredEmployees.stream() filteredEmployees = filteredEmployees.stream()
.filter(emp -> emp.getId().equals(employee.getId())) .filter(emp -> emp.getId().equals(employee.getId()))
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
if (team != null && !"ALL".equals(team.getName())) { if (team != null && !"TODOS".equals(team.getName())) {
filteredEmployees = filteredEmployees.stream() filteredEmployees = filteredEmployees.stream()
.filter(emp -> emp.getTeam() != null && emp.getTeam().getId().equals(team.getId())) .filter(emp -> emp.getTeam() != null && emp.getTeam().getId().equals(team.getId()))
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
if (state != null && state != Status.ALL) { if (state != null && state != Status.TODOS) {
filteredEmployees = filteredEmployees.stream() filteredEmployees = filteredEmployees.stream()
.filter(emp -> { .filter(emp -> {
Optional<TimeOffRequest> request = requestService Optional<TimeOffRequest> request = requestService
.findByEmployeeAndState(emp.getId(), TimeOffRequestStatus.TAKEN); .findByEmployeeAndState(emp.getId(), TimeOffRequestStatus.EN_USO);
return state == Status.IDLE ? request.isPresent() : request.isEmpty(); return state == Status.EN_DESCANSO ? request.isPresent() : request.isEmpty();
}) })
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
@ -139,54 +141,160 @@ public class RequestsListView extends Main {
} }
private String getEmployeeFullName(final Employee employee) { private String getEmployeeFullName(final Employee employee) {
return "ALL".equals(employee.getFirstName()) ? "ALL" : employee.getFirstName() + " " + employee.getLastName(); return "TODOS".equals(employee.getFirstName())
? "TODOS" : employee.getFirstName() + " " + employee.getLastName();
} }
private String getTeamName(final Employee employee) { private String getTeamName(final Employee employee) {
Team team = employee.getTeam(); Team team = employee.getTeam();
return team != null ? team.getName() : "Unassigned"; return team != null ? team.getName() : "Sin asignar";
} }
private String getTeamLabel(final Team team) { private String getTeamLabel(final Team team) {
return "ALL".equals(team.getName()) ? "ALL" : team.getName(); return "TODOS".equals(team.getName()) ? "TODOS" : team.getName();
} }
private String getEmployeeStatus(final Employee employee) { private String getEmployeeStatus(final Employee employee) {
Optional<TimeOffRequest> activeRequest = requestService Optional<TimeOffRequest> activeRequest = requestService
.findByEmployeeAndState(employee.getId(), TimeOffRequestStatus.TAKEN); .findByEmployeeAndState(employee.getId(), TimeOffRequestStatus.EN_USO);
return activeRequest.isPresent() ? "IDLE" : "ACTIVE"; return activeRequest.isPresent() ? "EN_DESCANSO" : "ACTIVO";
} }
private String getGeneralTotal(final Employee employee) { private String getGeneralTotal(final Employee employee) {
List<TimeOffRequest> employeeRequests = requestService.findRequestsByEmployeeId(employee.getId()); List<TimeOffRequest> employeeRequests = requestService.findRequestsByEmployeeId(employee.getId());
List<Vacation> vacations = vacationService.findVacations(); List<Vacation> vacations = vacationService.findVacations();
double totalUtilized = employeeRequests.stream() double totalUtilized = calculateTotalUtilized(employeeRequests);
.filter(Objects::nonNull) double totalVacations = calculateVacationDays(employee);
.mapToDouble(request -> { double totalAvailable = calculateTotalAvailable(vacations, employeeRequests, employee);
Double daysBalance = request.getAvailableDays();
return daysBalance != null ? daysBalance : 0.0; double generalTotal = totalAvailable + totalVacations - totalUtilized;
})
.sum();
double totalUnused = employeeRequests.stream()
.filter(Objects::nonNull)
.mapToDouble(request -> {
Double daysBalance = request.getDaysBalance();
return daysBalance != null ? daysBalance : 0.0;
})
.sum();
double totalAvailable = vacations.stream()
.filter(Objects::nonNull)
.mapToDouble(request -> {
Double daysBalance = request.getDuration();
return daysBalance != null ? daysBalance : 0.0;
})
.sum();
double generalTotal = (totalAvailable - totalUtilized) + totalUnused;
return String.valueOf(generalTotal); return String.valueOf(generalTotal);
} }
private Set<TimeOffRequestType> getExcludedCategories() {
return Set.of(
TimeOffRequestType.MATERNIDAD,
TimeOffRequestType.PATERNIDAD,
TimeOffRequestType.MATRIMONIO,
TimeOffRequestType.DUELO_1ER_GRADO,
TimeOffRequestType.DUELO_2ER_GRADO,
TimeOffRequestType.DIA_DEL_PADRE,
TimeOffRequestType.DIA_DE_LA_MADRE
);
}
private Set<TimeOffRequestType> getGenderSpecificExclusions() {
return Set.of(
TimeOffRequestType.DIA_DE_LA_MUJER_INTERNACIONAL,
TimeOffRequestType.DIA_DE_LA_MUJER_NACIONAL
);
}
private double calculateTotalUtilized(final List<TimeOffRequest> employeeRequests) {
return employeeRequests.stream()
.filter(Objects::nonNull)
.mapToDouble(request -> request.getDaysToBeTake() != null ? request.getDaysToBeTake() : 0.0)
.sum();
}
private double calculateVacationDays(final Employee employee) {
if (employee.getDateOfEntry() != null) {
LocalDate entryDate = employee.getDateOfEntry();
LocalDate today = LocalDate.now();
boolean hasAnniversaryPassed = entryDate.getMonthValue() < today.getMonthValue()
|| (entryDate.getMonthValue() == today.getMonthValue() && entryDate.getDayOfMonth()
<= today.getDayOfMonth());
LocalDate previousVacationYearDate;
LocalDate currentVacationYearDate;
if (hasAnniversaryPassed) {
previousVacationYearDate = LocalDate.of(
today.getYear() - 1,
entryDate.getMonth(),
entryDate.getDayOfMonth()
);
currentVacationYearDate = LocalDate.of(
today.getYear(),
entryDate.getMonth(),
entryDate.getDayOfMonth()
);
} else {
previousVacationYearDate = LocalDate.of(
today.getYear() - 2,
entryDate.getMonth(),
entryDate.getDayOfMonth()
);
currentVacationYearDate = LocalDate.of(
today.getYear() - 1,
entryDate.getMonth(),
entryDate.getDayOfMonth()
);
}
return calculateVacationDaysSinceEntry(entryDate, previousVacationYearDate)
+ calculateVacationDaysSinceEntry(entryDate, currentVacationYearDate);
} else {
return 0.0;
}
}
private double calculateTotalAvailable(final List<Vacation> vacations, final List<TimeOffRequest> employeeRequests,
final Employee employee) {
Set<TimeOffRequestType> excludedCategories = getExcludedCategories();
Set<TimeOffRequestType> genderSpecificExclusions = getGenderSpecificExclusions();
Set<TimeOffRequestType> employeeRequestCategories = employeeRequests.stream()
.map(TimeOffRequest::getCategory)
.collect(Collectors.toSet());
return vacations.stream()
.filter(Objects::nonNull)
.filter(vacation -> shouldIncludeVacation(
vacation,
excludedCategories,
genderSpecificExclusions,
employee, employeeRequestCategories
))
.mapToDouble(vacation -> vacation.getDuration() != null ? vacation.getDuration() : 0.0)
.sum();
}
private double calculateVacationDaysSinceEntry(final LocalDate dateOfEntry, final LocalDate date) {
int yearsOfService = dateOfEntry != null ? Period.between(dateOfEntry, date).getYears() : 0;
if (yearsOfService > 10) {
return 30;
}
if (yearsOfService > 5) {
return 20;
}
if (yearsOfService > 1) {
return 15;
}
return 0;
}
private boolean shouldIncludeVacation(final Vacation vacation,
final Set<TimeOffRequestType> excludedCategories,
final Set<TimeOffRequestType> genderSpecificExclusions,
final Employee employee,
final Set<TimeOffRequestType> employeeRequestCategories) {
if (excludedCategories.contains(vacation.getCategory())
&& !employeeRequestCategories.contains(vacation.getCategory())) {
return false;
}
if (!isFemale(employee) && genderSpecificExclusions.contains(vacation.getCategory())) {
return false;
}
return true;
}
private boolean isFemale(final Employee employee) {
return employee.getGender() == Employee.Gender.FEMALE;
}
private ComboBox<Employee> createEmployeeFilter() { private ComboBox<Employee> createEmployeeFilter() {
employeeFilter = new ComboBox<>("Employee"); employeeFilter = new ComboBox<>("Empleado");
List<Employee> employees = new ArrayList<>(employeeService.findAllEmployees()); List<Employee> employees = new ArrayList<>(employeeService.findAllEmployees());
employees.addFirst(createAllEmployeesOption()); employees.addFirst(createAllEmployeesOption());
employeeFilter.setItems(employees); employeeFilter.setItems(employees);
@ -203,7 +311,7 @@ public class RequestsListView extends Main {
} }
private ComboBox<Team> createTeamFilter() { private ComboBox<Team> createTeamFilter() {
teamFilter = new ComboBox<>("Team"); teamFilter = new ComboBox<>("Equipo");
List<Team> teams = new ArrayList<>(teamService.findAllTeams()); List<Team> teams = new ArrayList<>(teamService.findAllTeams());
teams.addFirst(createAllTeamsOption()); teams.addFirst(createAllTeamsOption());
teamFilter.setItems(teams); teamFilter.setItems(teams);
@ -220,7 +328,7 @@ public class RequestsListView extends Main {
} }
private ComboBox<Status> createStateFilter() { private ComboBox<Status> createStateFilter() {
stateFilter = new ComboBox<>("Employee State"); stateFilter = new ComboBox<>("Estado del empleado");
stateFilter.setItems(Status.values()); stateFilter.setItems(Status.values());
stateFilter.setValue(Status.values()[0]); stateFilter.setValue(Status.values()[0]);
stateFilter.addValueChangeListener(event -> stateFilter.addValueChangeListener(event ->
@ -234,20 +342,20 @@ public class RequestsListView extends Main {
} }
private enum Status { private enum Status {
ALL, TODOS,
IDLE, EN_DESCANSO,
ACTIVE ACTIVO
} }
private Employee createAllEmployeesOption() { private Employee createAllEmployeesOption() {
Employee allEmployeesOption = new Employee(); Employee allEmployeesOption = new Employee();
allEmployeesOption.setFirstName("ALL"); allEmployeesOption.setFirstName("TODOS");
return allEmployeesOption; return allEmployeesOption;
} }
private Team createAllTeamsOption() { private Team createAllTeamsOption() {
Team allTeamsOption = new Team(); Team allTeamsOption = new Team();
allTeamsOption.setName("ALL"); allTeamsOption.setName("TODOS");
return allTeamsOption; return allTeamsOption;
} }

View File

@ -16,33 +16,35 @@ INSERT INTO team (id, version, name) VALUES ('c3a8a7b1-f2d9-48c0-86ea-f215c2e6b3
INSERT INTO team (id, version, name) VALUES ('8f6b61e7-efb2-4de7-b8ed-7438c9d8babe', 1, 'GHI'); INSERT INTO team (id, version, name) VALUES ('8f6b61e7-efb2-4de7-b8ed-7438c9d8babe', 1, 'GHI');
INSERT INTO vacation (id, version, category, month_of_year, day_of_month, duration, expiration, type) VALUES ('123e4567-e89b-12d3-a456-426614174000', 1, 'NEW_YEAR', 1, 1, 1, 1, 'FIXED'); INSERT INTO vacation (id, version, category, month_of_year, day_of_month, duration, expiration, type) VALUES ('123e4567-e89b-12d3-a456-426614174000', 1, 'AÑO_NUEVO', 1, 1, 1, 1, 'FIXED');
INSERT INTO vacation (id, version, category, month_of_year, day_of_month, duration, expiration, type) VALUES ('223e4567-e89b-12d3-a456-426614174001', 1, 'MONDAY_CARNIVAL', 2, 12, 1, 1, 'FIXED'); INSERT INTO vacation (id, version, category, month_of_year, day_of_month, duration, expiration, type) VALUES ('223e4567-e89b-12d3-a456-426614174001', 1, 'LUNES_CARNAVAL', 2, 12, 1, 1, 'FIXED');
INSERT INTO vacation (id, version, category, month_of_year, day_of_month, duration, expiration, type) VALUES ('323e4567-e89b-12d3-a456-426614174002', 1, 'TUESDAY_CARNIVAL', 2, 13, 1, 1, 'FIXED'); INSERT INTO vacation (id, version, category, month_of_year, day_of_month, duration, expiration, type) VALUES ('323e4567-e89b-12d3-a456-426614174002', 1, 'MARTES_CARNAVAL', 2, 13, 1, 1, 'FIXED');
INSERT INTO vacation (id, version, category, month_of_year, day_of_month, duration, expiration, type) VALUES ('423e4567-e89b-12d3-a456-426614174003', 1, 'GOOD_FRIDAY', 3, 29, 1, 1, 'FIXED'); INSERT INTO vacation (id, version, category, month_of_year, day_of_month, duration, expiration, type) VALUES ('423e4567-e89b-12d3-a456-426614174003', 1, 'VIERNES_SANTO', 3, 29, 1, 1, 'FIXED');
INSERT INTO vacation (id, version, category, month_of_year, day_of_month, duration, expiration, type) VALUES ('523e4567-e89b-12d3-a456-426614174004', 1, 'LABOR_DAY', 5, 1, 1, 1, 'FIXED'); INSERT INTO vacation (id, version, category, month_of_year, day_of_month, duration, expiration, type) VALUES ('523e4567-e89b-12d3-a456-426614174004', 1, 'DIA_DEL_TRABAJADOR', 5, 1, 1, 1, 'FIXED');
INSERT INTO vacation (id, version, category, month_of_year, day_of_month, duration, expiration, type) VALUES ('623e4567-e89b-12d3-a456-426614174005', 1, 'INDEPENDENCE_DAY', 8, 6, 1, 1, 'FIXED'); INSERT INTO vacation (id, version, category, month_of_year, day_of_month, duration, expiration, type) VALUES ('623e4567-e89b-12d3-a456-426614174005', 1, 'DIA_DE_LA_INDEPENDENCIA', 8, 6, 1, 1, 'FIXED');
INSERT INTO vacation (id, version, category, month_of_year, day_of_month, duration, expiration, type) VALUES ('723e4567-e89b-12d3-a456-426614174006', 1, 'CHRISTMAS', 12, 25, 1, 1, 'FIXED'); INSERT INTO vacation (id, version, category, month_of_year, day_of_month, duration, expiration, type) VALUES ('723e4567-e89b-12d3-a456-426614174006', 1, 'NAVIDAD', 12, 25, 1, 1, 'FIXED');
INSERT INTO vacation (id, version, category, month_of_year, day_of_month, duration, expiration, type) VALUES ('823e4567-e89b-12d3-a456-426614174007', 1, 'PRURINATIONAL_STATE_DAY', 1, 21, 1, 30, 'MOVABLE'); INSERT INTO vacation (id, version, category, month_of_year, day_of_month, duration, expiration, type) VALUES ('823e4567-e89b-12d3-a456-426614174007', 1, 'DIA_DEL_ESTADO_PLURINACIONAL', 1, 21, 1, 30, 'MOVABLE');
INSERT INTO vacation (id, version, category, month_of_year, day_of_month, duration, expiration, type) VALUES ('923e4567-e89b-12d3-a456-426614174008', 1, 'CORPUS_CHRISTI', 5, 30, 1, 30, 'MOVABLE'); INSERT INTO vacation (id, version, category, month_of_year, day_of_month, duration, expiration, type) VALUES ('923e4567-e89b-12d3-a456-426614174008', 1, 'CORPUS_CHRISTI', 5, 30, 1, 30, 'MOVABLE');
INSERT INTO vacation (id, version, category, month_of_year, day_of_month, duration, expiration, type) VALUES ('a23e4567-e89b-12d3-a456-426614174009', 1, 'ANDEAN_NEW_YEAR', 6, 21, 1, 30, 'MOVABLE'); INSERT INTO vacation (id, version, category, month_of_year, day_of_month, duration, expiration, type) VALUES ('a23e4567-e89b-12d3-a456-426614174009', 1, 'AÑO_NUEVO_ANDINO', 6, 21, 1, 30, 'MOVABLE');
INSERT INTO vacation (id, version, category, month_of_year, day_of_month, duration, expiration, type) VALUES ('b23e4567-e89b-12d3-a456-42661417400a', 1, 'DEPARTMENTAL_ANNIVERSARY', 9, 14, 1, 30, 'MOVABLE'); INSERT INTO vacation (id, version, category, month_of_year, day_of_month, duration, expiration, type) VALUES ('b23e4567-e89b-12d3-a456-42661417400a', 1, 'ANIVERSARIO_DEPARTAMENTAL', 9, 14, 1, 30, 'MOVABLE');
INSERT INTO vacation (id, version, category, month_of_year, day_of_month, duration, expiration, type) VALUES ('c23e4567-e89b-12d3-a456-42661417400b', 1, 'ALL_SOULS_DAY', 11, 2, 1, 30, 'MOVABLE'); INSERT INTO vacation (id, version, category, month_of_year, day_of_month, duration, expiration, type) VALUES ('c23e4567-e89b-12d3-a456-42661417400b', 1, 'DIA_DE_TODOS_LOS_DIFUNTOS', 11, 2, 1, 30, 'MOVABLE');
INSERT INTO vacation (id, version, category, duration, expiration, type) VALUES ('c23e4567-e89b-12d3-a456-42661417400c', 1, 'BIRTHDAY', 0.5, 365, 'OTHER'); INSERT INTO vacation (id, version, category, duration, expiration, type) VALUES ('c23e4567-e89b-12d3-a456-42661417400c', 1, 'CUMPLEAÑOS', 0.5, 365, 'OTHER');
INSERT INTO vacation (id, version, category, duration, expiration, type) VALUES ('c23e4567-e89b-12d3-a456-42661417400d', 1, 'MATERNITY', 90, 90, 'OTHER'); INSERT INTO vacation (id, version, category, duration, expiration, type) VALUES ('c23e4567-e89b-12d3-a456-42661417400d', 1, 'MATERNIDAD', 90, 90, 'OTHER');
INSERT INTO vacation (id, version, category, duration, expiration, type) VALUES ('c23e4567-e89b-12d3-a456-42661417400e', 1, 'PATERNITY', 3, 3, 'OTHER'); INSERT INTO vacation (id, version, category, duration, expiration, type) VALUES ('c23e4567-e89b-12d3-a456-42661417400e', 1, 'PATERNIDAD', 3, 3, 'OTHER');
INSERT INTO vacation (id, version, category, duration, expiration, type) VALUES ('c23e4567-e89b-12d3-a456-42661417400f', 1, 'MARRIAGE', 3, 3, 'OTHER'); INSERT INTO vacation (id, version, category, duration, expiration, type) VALUES ('c23e4567-e89b-12d3-a456-42661417400f', 1, 'MATRIMONIO', 3, 3, 'OTHER');
INSERT INTO vacation (id, version, category, month_of_year, day_of_month, duration, expiration, type) VALUES ('c23e4567-e89b-12d3-a456-42661417401a', 1, 'FATHERS_DAY', 3, 19, 0.5, 30, 'OTHER'); INSERT INTO vacation (id, version, category, duration, expiration, type) VALUES ('550e8400-e29b-41d4-a716-446655440000', 1, 'DUELO_1ER_GRADO', 3, 3, 'OTHER');
INSERT INTO vacation (id, version, category, month_of_year, day_of_month, duration, expiration, type) VALUES ('c23e4567-e89b-12d3-a456-42661417401b', 1, 'MOTHERS_DAY', 5, 27, 0.5, 30, 'OTHER'); INSERT INTO vacation (id, version, category, duration, expiration, type) VALUES ('c23e4567-e89b-12d3-a456-42661417400a', 1, 'DUELO_2ER_GRADO', 2, 2, 'OTHER');
INSERT INTO vacation (id, version, category, month_of_year, day_of_month, duration, expiration, type) VALUES ('c23e4567-e89b-12d3-a456-42661417401c', 1, 'INTERNATIONAL_WOMENS_DAY', 3, 8, 0.5, 30, 'OTHER'); INSERT INTO vacation (id, version, category, month_of_year, day_of_month, duration, expiration, type) VALUES ('c23e4567-e89b-12d3-a456-42661417401a', 1, 'DIA_DEL_PADRE', 3, 19, 0.5, 30, 'OTHER');
INSERT INTO vacation (id, version, category, month_of_year, day_of_month, duration, expiration, type) VALUES ('c23e4567-e89b-12d3-a456-42661417401d', 1, 'NATIONAL_WOMENS_DAY', 10, 11, 0.5, 30, 'OTHER'); INSERT INTO vacation (id, version, category, month_of_year, day_of_month, duration, expiration, type) VALUES ('c23e4567-e89b-12d3-a456-42661417401b', 1, 'DIA_DE_LA_MADRE', 5, 27, 0.5, 30, 'OTHER');
INSERT INTO vacation (id, version, category, duration, type) VALUES ('c23e4567-e89b-12d3-a456-42661417401e', 1, 'HEALTH_PERMIT', 2, 'OTHER'); INSERT INTO vacation (id, version, category, month_of_year, day_of_month, duration, expiration, type) VALUES ('c23e4567-e89b-12d3-a456-42661417401c', 1, 'DIA_DE_LA_MUJER_INTERNACIONAL', 3, 8, 0.5, 30, 'OTHER');
INSERT INTO vacation (id, version, category, expiration, type) VALUES ('490e5fbe-895b-42f8-b914-95437f7b39c0', 1, 'VACATION_CURRENT_MANAGEMENT', 730, 'OTHER'); INSERT INTO vacation (id, version, category, month_of_year, day_of_month, duration, expiration, type) VALUES ('c23e4567-e89b-12d3-a456-42661417401d', 1, 'DIA_DE_LA_MUJER_NACIONAL', 10, 11, 0.5, 30, 'OTHER');
INSERT INTO vacation (id, version, category, expiration, type) VALUES ('c23e4567-e89b-12d3-a456-4266141740ff', 1, 'VACATION_PREVIOUS_MANAGEMENT', 730, 'OTHER'); INSERT INTO vacation (id, version, category, duration, type) VALUES ('c23e4567-e89b-12d3-a456-42661417401e', 1, 'PERMISOS_DE_SALUD', 2, 'OTHER');
INSERT INTO vacation (id, version, category, expiration, type) VALUES ('490e5fbe-895b-42f8-b914-95437f7b39c0', 1, 'VACACION_GESTION_ACTUAL', 360, 'OTHER');
INSERT INTO vacation (id, version, category, expiration, type) VALUES ('c23e4567-e89b-12d3-a456-4266141740ff', 1, 'VACACION_GESTION_ANTERIOR', 360, 'OTHER');
insert into employee (id, version, username, first_name, last_name, status, team_id, gender, birthday, date_of_entry) values ('5c6f11fe-c341-4be7-a9a6-bba0081ad7c6', 1, 'bob', 'Bob', 'Test', 'ACTIVE','b0e8f394-78c1-4d8a-9c57-dc6e8b36a5fa', 'MALE', '2024-02-20', '2013-10-22'); insert into employee (id, version, username, first_name, last_name, status, team_id, gender, birthday, date_of_entry) values ('5c6f11fe-c341-4be7-a9a6-bba0081ad7c6', 1, 'bob', 'Bob', 'Test', 'ACTIVE','b0e8f394-78c1-4d8a-9c57-dc6e8b36a5fa', 'MALE', '2024-02-20', '2013-10-22');
@ -66,25 +68,25 @@ insert into employee (id, version, username, first_name, last_name, status, team
insert into time_off_request (id, version, employee_id, category, state, available_days, expiration, start_date, end_date, days_to_be_take, days_balance) insert into time_off_request (id, version, employee_id, category, state, available_days, expiration, start_date, end_date, days_to_be_take, days_balance)
values ('9d6f12ba-e341-4e7a-b8a6-cab0982bd8c1', 1, '5c6f11fe-c341-4be7-a9a6-bba0081ad7c6', 'PATERNITY', 'TAKEN', 3, '2024-10-03', '2024-10-01', '2024-10-03', 3, 0); values ('9d6f12ba-e341-4e7a-b8a6-cab0982bd8c1', 1, '5c6f11fe-c341-4be7-a9a6-bba0081ad7c6', 'PATERNIDAD', 'VENCIDO', 3, '2024-10-03', '2024-10-01', '2024-10-03', 3, 0);
insert into time_off_request (id, version, employee_id, category, state, available_days, expiration, start_date, end_date, days_to_be_take, days_balance) insert into time_off_request (id, version, employee_id, category, state, available_days, expiration, start_date, end_date, days_to_be_take, days_balance)
values ('9a6f12ba-e111-4e7a-b8a6-caa0982bd8a1', 1, '5c6f11fe-c341-4be7-a9a6-bba0081ad7c6', 'NEW_YEAR', 'EXPIRED', 1, '2024-01-01', '2024-01-01', '2024-01-01', 1, 0); values ('9a6f12ba-e111-4e7a-b8a6-caa0982bd8a1', 1, '5c6f11fe-c341-4be7-a9a6-bba0081ad7c6', 'AÑO_NUEVO', 'VENCIDO', 1, '2024-01-01', '2024-01-01', '2024-01-01', 1, 0);
insert into time_off_request (id, version, employee_id, category, state, available_days, expiration, start_date, end_date, days_to_be_take, days_balance) insert into time_off_request (id, version, employee_id, category, state, available_days, expiration, start_date, end_date, days_to_be_take, days_balance)
values ('9b6f12ba-e222-4e7a-b8a6-caa0982bd8b2', 1, '5c6f11fe-c341-4be7-a9a6-bba0081ad7c6', 'MONDAY_CARNIVAL', 'APPROVED', 1, '2025-02-12', '2025-02-12', '2025-02-12', 1, 0); values ('9b6f12ba-e222-4e7a-b8a6-caa0982bd8b2', 1, '5c6f11fe-c341-4be7-a9a6-bba0081ad7c6', 'LUNES_CARNAVAL', 'APROBADO', 1, '2025-02-12', '2025-02-12', '2025-02-12', 1, 0);
insert into time_off_request (id, version, employee_id, category, state, available_days, expiration, start_date, end_date, days_to_be_take, days_balance) insert into time_off_request (id, version, employee_id, category, state, available_days, expiration, start_date, end_date, days_to_be_take, days_balance)
values ('9c6f12ba-e333-4e7a-b8a6-caa0982bd8c3', 1, '5c6f11fe-c341-4be7-a9a6-bba0081ad7c6', 'TUESDAY_CARNIVAL', 'UNDER_REVIEW', 1, '2025-02-13', '2025-02-13', '2025-02-13', 1, 0); values ('9c6f12ba-e333-4e7a-b8a6-caa0982bd8c3', 1, '5c6f11fe-c341-4be7-a9a6-bba0081ad7c6', 'MARTES_CARNAVAL', 'EN_REVISION', 1, '2025-02-13', '2025-02-13', '2025-02-13', 1, 0);
insert into time_off_request (id, version, employee_id, category, state, available_days, expiration, start_date, end_date, days_to_be_take, days_balance) insert into time_off_request (id, version, employee_id, category, state, available_days, expiration, start_date, end_date, days_to_be_take, days_balance)
values ('9d6f12ba-e444-4e7a-b8a6-caa0982bd8d4', 1, '5c6f11fe-c341-4be7-a9a6-bba0081ad7c6', 'GOOD_FRIDAY', 'COMPLETED', 1, '2024-03-29', '2024-03-29', '2024-03-29', 1, 0); values ('9d6f12ba-e444-4e7a-b8a6-caa0982bd8d4', 1, '5c6f11fe-c341-4be7-a9a6-bba0081ad7c6', 'VIERNES_SANTO', 'APROBADO', 1, '2024-03-29', '2024-03-29', '2024-03-29', 1, 0);
insert into time_off_request (id, version, employee_id, category, state, available_days, expiration, start_date, end_date, days_to_be_take, days_balance) insert into time_off_request (id, version, employee_id, category, state, available_days, expiration, start_date, end_date, days_to_be_take, days_balance)
values ('9e6f12ba-e555-4e7a-b8a6-caa0982bd8e5', 1, '5c6f11fe-c341-4be7-a9a6-bba0081ad7c6', 'VACATION_CURRENT_MANAGEMENT', 'APPROVED', 30, '2026-11-01', '2024-11-01', '2024-11-30', 30, 0); values ('9e6f12ba-e555-4e7a-b8a6-caa0982bd8e5', 1, '5c6f11fe-c341-4be7-a9a6-bba0081ad7c6', 'VACACION_GESTION_ACTUAL', 'APROBADO', 30, '2024-11-01', '2022-11-01', '2022-11-30', 30, 0);
insert into time_off_request (id, version, employee_id, category, state, available_days, expiration, start_date, end_date, days_to_be_take, days_balance) insert into time_off_request (id, version, employee_id, category, state, available_days, expiration, start_date, end_date, days_to_be_take, days_balance)
values ('8c653f2a-f9a3-4d67-b3b6-12ad98fe0983', 1, 'f6ab3c6d-7078-45f6-9b22-4e37637bfec6', 'LABOR_DAY', 'REQUESTED', 1, '2025-05-01', '2024-05-01', '2024-05-01', 1, 0); values ('8c653f2a-f9a3-4d67-b3b6-12ad98fe0983', 1, 'f6ab3c6d-7078-45f6-9b22-4e37637bfec6', 'DIA_DEL_TRABAJADOR', 'APROBADO', 1, '2024-05-01', '2024-05-01', '2024-05-01', 1, 0);
insert into time_off_request (id, version, employee_id, category, state, available_days, expiration, start_date, end_date, days_to_be_take, days_balance) insert into time_off_request (id, version, employee_id, category, state, available_days, expiration, start_date, end_date, days_to_be_take, days_balance)
values ('fb9d9d75-b2ab-4ea4-b8b3-0a8f89e5c123', 1, '2e2293b1-3f9a-4f3d-abc8-32639b0a5e15', 'INDEPENDENCE_DAY', 'IN_USE', 1, '2025-08-06', '2024-08-06', '2024-08-06', 1, 0); values ('fb9d9d75-b2ab-4ea4-b8b3-0a8f89e5c123', 1, '2e2293b1-3f9a-4f3d-abc8-32639b0a5e15', 'DIA_DE_LA_INDEPENDENCIA', 'APROBADO', 1, '2024-08-06', '2024-08-06', '2024-08-06', 1, 0);
insert into time_off_request (id, version, employee_id, category, state, available_days, expiration, start_date, end_date, days_to_be_take, days_balance) insert into time_off_request (id, version, employee_id, category, state, available_days, expiration, start_date, end_date, days_to_be_take, days_balance)
values ('6fdc47a8-127b-41c4-8d12-7fc12098ab12', 1, 'b2436b82-7b9f-4f0d-9463-f2c3173a45c3', 'ALL_SOULS_DAY', 'PENDING', 1, '2025-12-01', '2025-11-02', '2025-11-02', 1, 0); values ('6fdc47a8-127b-41c4-8d12-7fc12098ab12', 1, 'b2436b82-7b9f-4f0d-9463-f2c3173a45c3', 'DIA_DE_TODOS_LOS_DIFUNTOS', 'PENDIENTE', 1, '2025-12-01', '2025-11-02', '2025-11-02', 1, 0);
insert into time_off_request (id, version, employee_id, category, state, available_days, expiration, start_date, end_date, days_to_be_take, days_balance) insert into time_off_request (id, version, employee_id, category, state, available_days, expiration, start_date, end_date, days_to_be_take, days_balance)
values ('12ec8b74-983d-4a17-b67e-134f45ae904c', 1, '5c1a7b82-832d-4f24-8377-54b77b91b6a8', 'NEW_YEAR', 'PENDING', 1, '2025-01-01', '2025-01-01', '2025-01-01', 1, 0); values ('12ec8b74-983d-4a17-b67e-134f45ae904c', 1, '5c1a7b82-832d-4f24-8377-54b77b91b6a8', 'AÑO_NUEVO', 'PENDIENTE', 1, '2025-01-01', '2025-01-01', '2025-01-01', 1, 0);
insert into time_off_request (id, version, employee_id, category, state, available_days, expiration, start_date, end_date, days_to_be_take, days_balance) insert into time_off_request (id, version, employee_id, category, state, available_days, expiration, start_date, end_date, days_to_be_take, days_balance)
values ('89bc4b2a-943f-487c-a9f3-bacf78145e67', 1, 'cba3efb7-32bc-44be-9fdc-fc5e4f211254', 'MONDAY_CARNIVAL', 'APPROVED', 1, '2025-02-12', '2024-02-12', '2024-02-12', 1, 0); values ('89bc4b2a-943f-487c-a9f3-bacf78145e67', 1, 'cba3efb7-32bc-44be-9fdc-fc5e4f211254', 'LUNES_CARNAVAL', 'APROBADO', 1, '2024-02-12', '2024-02-12', '2024-02-12', 1, 0);