arreglar-funcionalidad #88

Merged
alex merged 5 commits from arreglar-funcionalidad into main 2024-11-28 13:59:32 +00:00
5 changed files with 172 additions and 14 deletions

View File

@ -2,6 +2,7 @@ package com.primefactorsolutions.service;
import com.openhtmltopdf.pdfboxout.PdfBoxRenderer;
import com.openhtmltopdf.pdfboxout.PdfRendererBuilder;
import com.primefactorsolutions.model.Employee;
import com.primefactorsolutions.repositories.HoursWorkedRepository;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
@ -174,4 +175,80 @@ public class ReportService {
return cfg;
}
public byte[] generateExcelReport(final Employee employee) {
try (Workbook workbook = new XSSFWorkbook()) {
Sheet sheet = workbook.createSheet("Empleado");
Row titleRow = sheet.createRow(0);
Cell titleCell = titleRow.createCell(0);
titleCell.setCellValue("Información General del Empleado");
CellStyle titleStyle = workbook.createCellStyle();
Font titleFont = workbook.createFont();
titleFont.setBold(true);
titleFont.setFontHeightInPoints((short) 16);
titleStyle.setFont(titleFont);
titleStyle.setAlignment(HorizontalAlignment.CENTER);
titleCell.setCellStyle(titleStyle);
sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 40));
Row header = sheet.createRow(2);
String[] headers = {
"Username", "Nombres", "Apellidos", "Estado", "Género", "Fecha de Nacimiento", "Edad",
"Ciudad y País de Nacimiento", "Dirección de Residencia", "Departamento y Provincia de Residencia",
"Estado Civil", "Número de Hijos", "CI", "Expedido en", "Teléfono", "E-mail Personal",
"Teléfono Laboral",
"E-mail Laboral", "Nombres y Apellidos de Contacto", "Dirección de Contacto",
"Teléfono de Contacto",
"Email de Contacto", "Código de Empleado", "Cargo", "Equipo", "Lead/Manager", "Fecha de Ingreso",
"Fecha de Retiro", "Tipo de Contrato", "Tipo de Contrato Personalizado", "Antigüedad",
"Salario Total",
"Salario Básico", "Bono de Antigüedad", "Bono Profesional", "Banco", "Número de Cuenta",
"Código Único de Asegurado (GPSS)", "Matrícula de Asegurado (SSS)", "Derechohabiente 1",
"Derechohabiente 2"
};
CellStyle headerStyle = workbook.createCellStyle();
Font headerFont = workbook.createFont();
headerFont.setBold(true);
headerStyle.setFont(headerFont);
headerStyle.setAlignment(HorizontalAlignment.CENTER);
headerStyle.setVerticalAlignment(VerticalAlignment.CENTER);
for (int i = 0; i < headers.length; i++) {
Cell cell = header.createCell(i);
cell.setCellValue(headers[i]);
cell.setCellStyle(headerStyle);
}
Row dataRow = sheet.createRow(3); // Fila 3
String[] employeeData = {
employee.getUsername(), employee.getFirstName(), employee.getLastName(),
employee.getStatus().toString(),
employee.getGender().toString(), employee.getBirthday().toString(),
String.valueOf(employee.getAge()),
employee.getBirthCity(), employee.getResidenceAddress(), employee.getLocalAddress(),
employee.getMaritalStatus().toString(), String.valueOf(employee.getNumberOfChildren()),
employee.getCi(),
employee.getIssuedIn(), employee.getPhoneNumber(), employee.getPersonalEmail(),
employee.getPhoneNumberProfesional(), employee.getProfesionalEmail(), employee.getEmergencyCName(),
employee.getEmergencyCAddress(), employee.getEmergencyCPhone(), employee.getEmergencyCEmail(),
employee.getCod(), employee.getPosition(), employee.getTeam().getName(), employee.getLeadManager(),
employee.getDateOfEntry().toString(), employee.getDateOfExit() != null ? employee.getDateOfExit()
.toString() : "",
employee.getContractType().toString(), employee.getCustomContractType(),
employee.getSeniority(), employee.getSalarytotal(), employee.getSalaryBasic(),
employee.getAntiguedad(), employee.getBonoProfesional(), employee.getBankName(),
employee.getAccountNumber(), employee.getGpss(), employee.getSss(),
employee.getBeneficiarie1(), employee.getBeneficiarie2()
};
for (int i = 0; i < employeeData.length; i++) {
dataRow.createCell(i).setCellValue(employeeData[i] != null ? employeeData[i] : "");
}
for (int i = 0; i < headers.length; i++) {
sheet.autoSizeColumn(i);
}
try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
workbook.write(outputStream);
return outputStream.toByteArray();
}
} catch (IOException e) {
throw new RuntimeException("Error al generar el reporte Excel", e);
}
}
}

View File

@ -0,0 +1,60 @@
package com.primefactorsolutions.views;
import com.primefactorsolutions.model.Employee;
import com.primefactorsolutions.service.EmployeeService;
import com.primefactorsolutions.service.ReportService;
import com.vaadin.flow.component.UI;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.html.Anchor;
import com.vaadin.flow.component.notification.Notification;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.router.*;
import com.vaadin.flow.server.StreamResource;
import jakarta.annotation.security.PermitAll;
import java.io.ByteArrayInputStream;
import java.util.UUID;
@PermitAll
@PageTitle("Reporte excel")
@Route("employee-report")
public class EmployeeReportView extends VerticalLayout implements HasUrlParameter<String> {
private final EmployeeService employeeService;
private final ReportService reportService;
public EmployeeReportView(final EmployeeService employeeService, final ReportService reportService) {
this.employeeService = employeeService;
this.reportService = reportService;
Button backButton = new Button("Volver al Reporte de Empleados", event ->
UI.getCurrent().navigate(EmployeesListView.class));
backButton.addClassName("back-button");
add(backButton);
}
@Override
public void setParameter(final BeforeEvent event, @OptionalParameter final String employeeId) {
if (employeeId != null) {
UUID id = UUID.fromString(employeeId);
Employee employee = employeeService.getEmployee(id);
if (employee != null) {
generateExcelReport(employee);
} else {
Notification.show("Empleado no encontrado", 3000, Notification.Position.MIDDLE);
}
}
}
private void generateExcelReport(final Employee employee) {
try {
byte[] excelContent = reportService.generateExcelReport(employee);
StreamResource resource = new StreamResource(
employee.getFirstName() + "_" + employee.getLastName() + "_report.xlsx",
() -> new ByteArrayInputStream(excelContent)
);
Anchor downloadLink = new Anchor(resource, "Descargar Reporte Excel");
downloadLink.getElement().setAttribute("download", true);
add(downloadLink);
} catch (Exception e) {
Notification.show("Error al generar el reporte Excel", 3000, Notification.Position.MIDDLE);
}
}
}

View File

@ -16,6 +16,7 @@ import com.vaadin.flow.component.button.ButtonVariant;
import com.vaadin.flow.component.combobox.ComboBox;
import com.vaadin.flow.component.dialog.Dialog;
import com.vaadin.flow.component.html.*;
import com.vaadin.flow.component.icon.VaadinIcon;
import com.vaadin.flow.component.notification.Notification;
import com.vaadin.flow.component.orderedlayout.FlexComponent;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
@ -126,6 +127,8 @@ public class EmployeeView extends BeanValidationForm<Employee> implements HasUrl
private final Button reportButton = new Button("Generar Ficha de Contratación");
private final Dialog dialog = new Dialog();
private final PdfViewer pdfViewer = new PdfViewer();
private final Button excelReportButton = new Button("Información General del Empleado Excel",
VaadinIcon.FILE_TABLE.create());
private final H2 infoPer = new H2("Información Personal");
private final H3 infoGenr = new H3("Información General");
private final H5 imagenSub = new H5("Insertar una imagen .jpg:");
@ -150,8 +153,14 @@ public class EmployeeView extends BeanValidationForm<Employee> implements HasUrl
this.requestService = requestService;
this.teamService = teamService;
saveButton.addThemeVariants(ButtonVariant.LUMO_PRIMARY);
excelReportButton.addThemeVariants(ButtonVariant.LUMO_PRIMARY);
configureComponents();
addClassName("main-layout");
excelReportButton.addClickListener(e ->
getUI().ifPresent(ui ->
ui.navigate(EmployeeReportView.class, getEntity().getId().toString())
)
);
}
private void makeUpperCase(final TextField textField) {
@ -514,6 +523,7 @@ public class EmployeeView extends BeanValidationForm<Employee> implements HasUrl
editButton.setVisible(false);
setFieldsEditable();
upload.setVisible(true);
profileImagePreview.setVisible(true);
salaryTotal.setValue(String.valueOf(0.0));
} else {
UUID employeeId = UUID.fromString(s);
@ -526,6 +536,7 @@ public class EmployeeView extends BeanValidationForm<Employee> implements HasUrl
setFieldsEditable();
upload.setVisible(true);
displayProfileImage(employee);
profileImagePreview.setVisible(true);
salaryTotal.setValue(employee.getSalarytotal());
} else if ("view".equals(action) && !s.isEmpty()) {
setFieldsReadOnly();
@ -533,7 +544,6 @@ public class EmployeeView extends BeanValidationForm<Employee> implements HasUrl
editButton.setVisible(true);
setFieldsReadOnly();
displayProfileImage(employee);
upload.setVisible(true);
salaryTotal.setValue(employee.getSalarytotal());
}
}
@ -573,7 +583,6 @@ public class EmployeeView extends BeanValidationForm<Employee> implements HasUrl
emergencyCAddress.setReadOnly(true);
emergencyCPhone.setReadOnly(true);
emergencyCEmail.setReadOnly(true);
upload.setVisible(true);
profileImagePreview.setVisible(true);
age.setReadOnly(true);
gender.setReadOnly(true);
@ -636,7 +645,6 @@ public class EmployeeView extends BeanValidationForm<Employee> implements HasUrl
emergencyCAddress.setReadOnly(false);
emergencyCPhone.setReadOnly(false);
emergencyCEmail.setReadOnly(false);
upload.setVisible(false);
profileImagePreview.setVisible(true);
age.setReadOnly(false);
gender.setReadOnly(false);
@ -704,7 +712,7 @@ public class EmployeeView extends BeanValidationForm<Employee> implements HasUrl
salaryBasic, bonoProfesional, antiguedad, salaryTotal,
datBanc, bankName, accountNumber,
datGest, gpss, sss, beneficiarie1, beneficiarie2,
saveButton, editButton, reportButton, dialog
saveButton, editButton, reportButton, excelReportButton, dialog
);
}
}

View File

@ -26,6 +26,7 @@ import java.time.temporal.IsoFields;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
@SpringComponent
@PermitAll
@ -142,14 +143,25 @@ public class HoursWorkedView extends BeanValidationForm<HoursWorked> implements
List<Team> teams = new ArrayList<>(teamService.findAllTeams());
teamField.setItems(teamService.findAllTeams());
teamField.setItemLabelGenerator(Team::getName);
teamField.setValue(teams.getFirst());
teamField.setValue(null);
teamField.addValueChangeListener(event -> {
if (teams != null) {
employeeField.getValue();
event.getValue();
}
}
);
Team selectedTeam = event.getValue();
updateEmployeeField(selectedTeam);
});
}
private void updateEmployeeField(final Team selectedTeam) {
if (selectedTeam != null) {
List<Employee> employeesInTeam = employeeService.findAllEmployees().stream()
.filter(employee -> employee.getTeam() != null && employee.getTeam().equals(selectedTeam))
.collect(Collectors.toList());
employeeField.setItems(employeesInTeam);
if (!employeesInTeam.isEmpty()) {
employeeField.setValue(employeesInTeam.get(0));
} else {
employeeField.clear();
}
}
}
private ComboBox<Employee> initializeEmployeeField() {
@ -157,7 +169,7 @@ public class HoursWorkedView extends BeanValidationForm<HoursWorked> implements
List<Employee> employees = new ArrayList<>(employeeService.findAllEmployees());
employeeField.setItems(employees);
employeeField.setItemLabelGenerator(this::getEmployeeFullName);
employeeField.setValue(employees.getFirst());
employeeField.setValue(null);
return employeeField;
}

View File

@ -47,8 +47,7 @@ INSERT INTO vacation (id, version, category, expiration, type) VALUES ('490e5fbe
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, date_of_entry) values ('cba3efb7-32bc-44be-9fdc-fc5e4f211254', 1, 'ben', 'Ben', 'Test', 'ACTIVE', '6d63bc15-3f8b-46f7-9cf1-7e9b0b9a2b28', 'MALE', '2016-10-23');
insert into employee (id, version, username, first_name, last_name, status, team_id, gender, birthday, date_of_entry,lead_manager) values ('5c6f11fe-c341-4be7-a9a6-bba0081ad7c6', 1, 'bob', 'Bob', 'Test', 'ACTIVE','b0e8f394-78c1-4d8a-9c57-dc6e8b36a5fa', 'MALE', '2024-02-20', '2013-10-22',1);insert into employee (id, version, username, first_name, last_name, status, team_id, gender, date_of_entry) values ('cba3efb7-32bc-44be-9fdc-fc5e4f211254', 1, 'ben', 'Ben', 'Test', 'ACTIVE', '6d63bc15-3f8b-46f7-9cf1-7e9b0b9a2b28', 'MALE', '2016-10-23');
insert into employee (id, version, username, first_name, last_name, status, team_id, gender, date_of_entry) values ('e99b7af5-7d3a-4c0f-b8bc-e8d0388d8fc4', 1, 'jperez', 'Juan', 'Perez Condori', 'INACTIVE', 'c3a8a7b1-f2d9-48c0-86ea-f215c2e6b3a3', 'MALE', '2022-10-22');
insert into employee (id, version, username, first_name, last_name, status, team_id, gender, date_of_entry) values ('f6ab3c6d-7078-45f6-9b22-4e37637bfec6', 1, 'agarcia', 'Ana', 'Garcia Rojas', 'ACTIVE', '8f6b61e7-efb2-4de7-b8ed-7438c9d8babe', 'FEMALE', '2024-10-24');
insert into employee (id, version, username, first_name, last_name, status, team_id, gender) values ('2e2293b1-3f9a-4f3d-abc8-32639b0a5e15', 1, 'clopez', 'Carlos', 'Lopez Mendoza', 'INACTIVE', 'b0e8f394-78c1-4d8a-9c57-dc6e8b36a5fa', 'MALE');
@ -90,3 +89,5 @@ insert into time_off_request (id, version, employee_id, category, state, availab
values ('12ec8b74-983d-4a17-b67e-134f45ae904c', 1, '5c1a7b82-832d-4f24-8377-54b77b91b6a8', 'AÑO_NUEVO', 'SOLICITADO', 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)
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);
insert into hours_worked (id, version, actividad, date, horaspendientes, hours, total_hours,week_number,employee_id,team_id) values ('389389ce-7b2e-4f39-aa06-2a251a2b35ea ',0,'meet','2024-11-27',0,4,0,48,'5c6f11fe-c341-4be7-a9a6-bba0081ad7c6','b0e8f394-78c1-4d8a-9c57-dc6e8b36a5fa');