crear tabla para visuaizar las actividades creadas

This commit is contained in:
Melina Gutierrez 2024-11-13 15:57:49 -04:00
parent 3c626e3c85
commit 090a4bb67a
11 changed files with 196 additions and 193 deletions

View File

@ -1,14 +0,0 @@
name: PR Builder
run-name: ${{ gitea.actor }} building PR
on: [pull_request]
jobs:
Build-PR:
runs-on: ubuntu-22.04
steps:
- run: echo "The job was automatically triggered by a ${{ gitea.event_name }} event on branch ${{ gitea.head_ref }} and ref is ${{ gitea.ref }} and your repository is ${{ gitea.repository }}."
- name: Build PR
if: gitea.base_ref == 'main'
run: |
git clone --single-branch --branch "${{ gitea.head_ref }}" https://git.primefactorsolutions.com/PFS/pfs-intra.git && cd pfs-intra && ./mvnw clean package -Pproduction
- run: echo "This job's status is ${{ job.status }}."

View File

@ -1,16 +0,0 @@
name: Builder
run-name: ${{ gitea.actor }} building
on:
push:
branches:
- main
jobs:
Build-Project:
runs-on: ubuntu-22.04
steps:
- run: echo "The job was automatically triggered by a ${{ gitea.event_name }} event on branch is ${{ gitea.ref }} and your repository is ${{ gitea.repository }}."
- name: Build package
run: |
git clone --single-branch --branch main https://git.primefactorsolutions.com/PFS/pfs-intra.git && cd pfs-intra && ./mvnw clean package -Pproduction && unlink /home/ubuntu/pfs-intra/app.jar && cp target/*.jar /home/ubuntu/pfs-intra/app.jar && sudo systemctl restart pfs-intra
- run: echo "This job's status is ${{ job.status }}."

View File

@ -1,118 +0,0 @@
/*
* Copyright 2007-present the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.*;
import java.net.*;
import java.nio.channels.*;
import java.util.Properties;
public class MavenWrapperDownloader {
private static final String WRAPPER_VERSION = "0.5.6";
/**
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is
* provided.
*/
private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/"
+ WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar";
/**
* Path to the maven-wrapper.properties file, which might contain a downloadUrl
* property to use instead of the default one.
*/
private static final String MAVEN_WRAPPER_PROPERTIES_PATH = ".mvn/wrapper/maven-wrapper.properties";
/**
* Path where the maven-wrapper.jar will be saved to.
*/
private static final String MAVEN_WRAPPER_JAR_PATH = ".mvn/wrapper/maven-wrapper.jar";
/**
* Name of the property which should be used to override the default download
* url for the wrapper.
*/
private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
public static void main(String args[]) {
System.out.println("- Downloader started");
File baseDirectory = new File(args[0]);
System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
// If the maven-wrapper.properties exists, read it and check if it contains a
// custom
// wrapperUrl parameter.
File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
String url = DEFAULT_DOWNLOAD_URL;
if (mavenWrapperPropertyFile.exists()) {
FileInputStream mavenWrapperPropertyFileInputStream = null;
try {
mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
Properties mavenWrapperProperties = new Properties();
mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
} catch (IOException e) {
System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
} finally {
try {
if (mavenWrapperPropertyFileInputStream != null) {
mavenWrapperPropertyFileInputStream.close();
}
} catch (IOException e) {
// Ignore ...
}
}
}
System.out.println("- Downloading from: " + url);
File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
if (!outputFile.getParentFile().exists()) {
if (!outputFile.getParentFile().mkdirs()) {
System.out.println(
"- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'");
}
}
System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
try {
downloadFileFromURL(url, outputFile);
System.out.println("Done");
System.exit(0);
} catch (Throwable e) {
System.out.println("- Error downloading");
e.printStackTrace();
System.exit(1);
}
}
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) {
String username = System.getenv("MVNW_USERNAME");
char[] password = System.getenv("MVNW_PASSWORD").toCharArray();
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
}
URL website = new URL(urlString);
ReadableByteChannel rbc;
rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(destination);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
}
}

Binary file not shown.

View File

@ -1,18 +0,0 @@
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.4/apache-maven-3.8.4-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar

View File

@ -0,0 +1,81 @@
package com.primefactorsolutions.model;
import jakarta.persistence.*;
import java.time.LocalDate;
import java.util.UUID;
@Entity
@Table(name = "Actividades_hours")
public class ActividadesHours {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private UUID id;
@ManyToOne
@JoinColumn(name = "employee_id", nullable = false)
private Employee employee;
@ManyToOne
@JoinColumn(name = "actividad_id", nullable = false)
private Actividad actividad;
@Column(nullable = false)
private double totalHours;
@Column(nullable = false)
private int weekNumber;
@Column(nullable = false)
private LocalDate fecha;
// Getters y Setters
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
public Actividad getActividad() {
return actividad;
}
public void setActividad(Actividad actividad) {
this.actividad = actividad;
}
public double getTotalHours() {
return totalHours;
}
public void setTotalHours(double totalHours) {
this.totalHours = totalHours;
}
public int getWeekNumber() {
return weekNumber;
}
public void setWeekNumber(int weekNumber) {
this.weekNumber = weekNumber;
}
public LocalDate getFecha() {
return fecha;
}
public void setFecha(LocalDate fecha) {
this.fecha = fecha;
}
}

View File

@ -5,8 +5,11 @@ import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType; import jakarta.persistence.GenerationType;
import jakarta.persistence.Id; import jakarta.persistence.Id;
import jakarta.persistence.ManyToOne; import jakarta.persistence.ManyToOne;
import jakarta.persistence.CascadeType;
import java.time.LocalDate; import java.time.LocalDate;
import java.time.temporal.WeekFields;
import java.util.Locale;
import java.util.UUID; import java.util.UUID;
@Entity @Entity
@ -18,25 +21,16 @@ public class HoursWorked extends BaseEntity {
@ManyToOne @ManyToOne
private Employee employee; private Employee employee;
@ManyToOne @ManyToOne(cascade = CascadeType.PERSIST) // Añadimos cascade para que persista la actividad automáticamente
private Actividad actividad; private Actividad actividad;
private int weekNumber; private int weekNumber;
private double totalHours; private double totalHours;
private LocalDate fecha; private LocalDate fecha;
public HoursWorked() {} public HoursWorked() {}
public Actividad getActividad() { // Getters y Setters
return this.actividad;
}
public void setActividad(Actividad actividad){
this.actividad = actividad;
}
public UUID getId() { public UUID getId() {
return id; return id;
} }
@ -49,8 +43,16 @@ public class HoursWorked extends BaseEntity {
return employee; return employee;
} }
public void setEmployee(final Employee value) { public void setEmployee(final Employee employee) {
this.employee = value; this.employee = employee;
}
public Actividad getActividad() {
return actividad;
}
public void setActividad(final Actividad actividad) {
this.actividad = actividad;
} }
public int getWeekNumber() { public int getWeekNumber() {
@ -61,8 +63,6 @@ public class HoursWorked extends BaseEntity {
this.weekNumber = weekNumber; this.weekNumber = weekNumber;
} }
public LocalDate getFecha() { return this.fecha;}
public double getTotalHours() { public double getTotalHours() {
return totalHours; return totalHours;
} }
@ -70,4 +70,34 @@ public class HoursWorked extends BaseEntity {
public void setTotalHours(final double totalHours) { public void setTotalHours(final double totalHours) {
this.totalHours = totalHours; this.totalHours = totalHours;
} }
public LocalDate getFecha() {
return fecha;
}
public void setFecha(final LocalDate fecha) {
this.fecha = fecha;
// Actualiza el número de semana automáticamente al establecer la fecha
if (fecha != null) {
this.weekNumber = calculateWeekNumber(fecha);
}
}
// Método adicional para calcular el número de semana basado en la fecha
private int calculateWeekNumber(LocalDate date) {
WeekFields weekFields = WeekFields.of(Locale.getDefault());
return date.get(weekFields.weekOfWeekBasedYear());
}
@Override
public String toString() {
return "HoursWorked{" +
"id=" + id +
", employee=" + (employee != null ? employee.getFirstName() : "N/A") +
", actividad=" + (actividad != null ? actividad.getNombre() : "N/A") +
", weekNumber=" + weekNumber +
", totalHours=" + totalHours +
", fecha=" + fecha +
'}';
}
} }

View File

@ -0,0 +1,6 @@
package com.primefactorsolutions.repositories;
import com.primefactorsolutions.model.ActividadesHours;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.UUID;
public interface ActividadesHoursRepository extends JpaRepository<ActividadesHours,UUID> {
}

View File

@ -11,7 +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> findByTeamId(UUID teamId); Optional<Employee> findByTeamIdAndLeadManagerTrue(UUID teamId);
List<Employee> findByTeamName(String teamName); List<Employee> findByTeamName(String teamName);
} }

View File

@ -50,7 +50,7 @@ public class EmployeeService {
public String getTeamLeadName(final UUID teamId) { public String getTeamLeadName(final UUID teamId) {
// Encuentra al empleado con el rol de lead_manager en el equipo especificado // Encuentra al empleado con el rol de lead_manager en el equipo especificado
Optional<Employee> leadManager = employeeRepository.findByTeamId(teamId); Optional<Employee> leadManager = employeeRepository.findByTeamIdAndLeadManagerTrue(teamId);
return leadManager.map(employee -> employee.getFirstName() + " " + employee.getLastName()) return leadManager.map(employee -> employee.getFirstName() + " " + employee.getLastName())
.orElse("No asignado"); .orElse("No asignado");

View File

@ -2,6 +2,7 @@ package com.primefactorsolutions.views;
import com.primefactorsolutions.model.Actividad; import com.primefactorsolutions.model.Actividad;
import com.primefactorsolutions.model.Employee; import com.primefactorsolutions.model.Employee;
import com.primefactorsolutions.model.HoursWorked; import com.primefactorsolutions.model.HoursWorked;
import com.primefactorsolutions.repositories.ActividadesHoursRepository;
import com.primefactorsolutions.service.EmployeeService; import com.primefactorsolutions.service.EmployeeService;
import com.primefactorsolutions.service.HoursWorkedService; import com.primefactorsolutions.service.HoursWorkedService;
import com.vaadin.flow.component.grid.Grid; import com.vaadin.flow.component.grid.Grid;
@ -58,6 +59,11 @@ public class HoursWorkedView extends VerticalLayout {
@Autowired @Autowired
private final HoursWorkedService hoursWorkedService; private final HoursWorkedService hoursWorkedService;
@Autowired
private ActividadesHoursRepository actividadesHoursRepository;
private final H2 equipoLabel = new H2("Tareas del Cliente/Equipo"); private final H2 equipoLabel = new H2("Tareas del Cliente/Equipo");
private final H2 empresaLabel = new H2("Tareas de la Empresa"); private final H2 empresaLabel = new H2("Tareas de la Empresa");
private final Label totalCompletadoLabel = new Label(); private final Label totalCompletadoLabel = new Label();
@ -186,6 +192,7 @@ public class HoursWorkedView extends VerticalLayout {
add(fechaPicker, filtersLayout, actividadFormLayout, add(fechaPicker, filtersLayout, actividadFormLayout,
equipoLabel, grid, empresaLabel, tareasEspecificasLayout, equipoLabel, grid, empresaLabel, tareasEspecificasLayout,
gridActividadesEspecificas, buttonsLayout, totalesLayout); gridActividadesEspecificas, buttonsLayout, totalesLayout);
} }
private void configurarGrid() { private void configurarGrid() {
@ -437,24 +444,69 @@ public class HoursWorkedView extends VerticalLayout {
return; return;
} }
// Verificar que hay actividades para guardar
if (actividades.isEmpty()) {
Notification.show("No hay actividades para guardar.");
return;
}
// Sumar el total de horas para la semana
double totalHorasSemana = actividades.stream() double totalHorasSemana = actividades.stream()
.mapToDouble(this::calcularTotalPorDia) .mapToDouble(this::calcularTotalPorDia)
.sum(); .sum();
HoursWorked hoursWorked = new HoursWorked(); // Crear un objeto HoursWorked por cada actividad
hoursWorked.setEmployee(selectedEmployee); List<HoursWorked> savedHoursWorked = new ArrayList<>(); // Para almacenar los objetos guardados
hoursWorked.setWeekNumber(weekNumber);
hoursWorked.setTotalHours(totalHorasSemana);
try { // Recorrer todas las actividades y guardar un registro para cada una
hoursWorkedService.saveHoursWorked(hoursWorked); // Usa saveHoursWorked directamente for (Actividad actividad : actividades) {
Notification.show("Actividades guardadas correctamente."); HoursWorked hoursWorked = new HoursWorked();
System.out.println(hoursWorked); hoursWorked.setEmployee(selectedEmployee);
} catch (Exception e) { hoursWorked.setWeekNumber(weekNumber);
Notification.show("Error al guardar actividades: " + e.getMessage()); hoursWorked.setTotalHours(totalHorasSemana);
// Asignar cada actividad individualmente
hoursWorked.setActividad(actividad);
hoursWorked.setFecha(LocalDate.now()); // Establecer la fecha actual o la seleccionada si es otra
// Mostrar información de la actividad para depuración
System.out.println("Guardando actividad: " + actividad.getNombre() + " con " + totalHorasSemana + " horas.");
try {
// Guardar en el servicio
hoursWorkedService.saveHoursWorked(hoursWorked);
savedHoursWorked.add(hoursWorked); // Agregar a la lista de registros guardados
Notification.show("Actividad guardada correctamente: " + actividad.getNombre());
} catch (Exception e) {
Notification.show("Error al guardar la actividad: " + actividad.getNombre() + " - " + e.getMessage());
}
} }
// Mostrar los registros guardados
savedHoursWorked.forEach(hw -> System.out.println("Horas trabajadas guardadas: " + hw));
// Crear el Grid
Grid<HoursWorked> grid = new Grid<>();
// Configurar columnas para mostrar la información deseada
grid.addColumn(hw -> hw.getEmployee().getFirstName()).setHeader("Empleado");
grid.addColumn(hw -> hw.getEmployee().getId()).setHeader("ID Empleado");
grid.addColumn(hw -> hw.getActividad().getNombre()).setHeader("Actividad");
grid.addColumn(hw -> hw.getTotalHours()).setHeader("Horas Trabajadas");
grid.addColumn(hw -> hw.getWeekNumber()).setHeader("Número de Semana");
grid.addColumn(hw -> hw.getFecha().toString()).setHeader("Fecha");
// Llenar el Grid con los datos de savedHoursWorked
grid.setItems(savedHoursWorked);
// Agregar el Grid a la vista
add(grid);
} }
private double calcularTotalHoras(final List<HoursWorked> listaDeHorasTrabajadas) { private double calcularTotalHoras(final List<HoursWorked> listaDeHorasTrabajadas) {
return listaDeHorasTrabajadas.stream() return listaDeHorasTrabajadas.stream()
.mapToDouble(HoursWorked::getTotalHours) .mapToDouble(HoursWorked::getTotalHours)