From fff5928102ed2f751d60191c3ab26c076e52e20f Mon Sep 17 00:00:00 2001 From: Daniel Ramos Date: Sun, 12 Apr 2026 23:14:18 -0400 Subject: [PATCH] desafio tecnico empleados - Daniel Ramos - Tecnova --- .gitignore | 54 +- Dockerfile | 18 + Empleados.postman_collection.json | 80 +++ HELP.md | 27 + README.md | 326 ++++++++++-- docker-compose.yml | 19 + mvnw | 295 +++++++++++ mvnw.cmd | 189 +++++++ pom.xml | 74 +++ .../danielr/desafio/DesafioApplication.java | 15 + .../controller/EmployeeController.java | 143 ++++++ .../desafio/dto/EmployeeRequestDTO.java | 30 ++ .../desafio/dto/EmployeeResponseDTO.java | 37 ++ .../desafio/exception/BusinessException.java | 22 + .../com/danielr/desafio/model/Employee.java | 123 +++++ .../repository/EmployeeRepository.java | 149 ++++++ .../desafio/service/IEmployeeService.java | 15 + .../service/impl/EmployeeServiceImpl.java | 153 ++++++ src/main/resources/application.properties | 25 + src/main/resources/schema.sql | 15 + src/main/resources/static/index.html | 471 ++++++++++++++++++ .../desafio/DesafioApplicationTests.java | 13 + .../repository/EmployeeRepositoryTest.java | 225 +++++++++ .../service/EmployeeServiceImplTest.java | 323 ++++++++++++ start.sh | 48 ++ 25 files changed, 2817 insertions(+), 72 deletions(-) create mode 100644 Dockerfile create mode 100644 Empleados.postman_collection.json create mode 100644 HELP.md create mode 100644 docker-compose.yml create mode 100755 mvnw create mode 100644 mvnw.cmd create mode 100644 pom.xml create mode 100644 src/main/java/com/danielr/desafio/DesafioApplication.java create mode 100644 src/main/java/com/danielr/desafio/controller/EmployeeController.java create mode 100644 src/main/java/com/danielr/desafio/dto/EmployeeRequestDTO.java create mode 100644 src/main/java/com/danielr/desafio/dto/EmployeeResponseDTO.java create mode 100644 src/main/java/com/danielr/desafio/exception/BusinessException.java create mode 100644 src/main/java/com/danielr/desafio/model/Employee.java create mode 100644 src/main/java/com/danielr/desafio/repository/EmployeeRepository.java create mode 100644 src/main/java/com/danielr/desafio/service/IEmployeeService.java create mode 100644 src/main/java/com/danielr/desafio/service/impl/EmployeeServiceImpl.java create mode 100644 src/main/resources/application.properties create mode 100644 src/main/resources/schema.sql create mode 100644 src/main/resources/static/index.html create mode 100644 src/test/java/com/danielr/desafio/DesafioApplicationTests.java create mode 100644 src/test/java/com/danielr/desafio/repository/EmployeeRepositoryTest.java create mode 100644 src/test/java/com/danielr/desafio/service/EmployeeServiceImplTest.java create mode 100755 start.sh diff --git a/.gitignore b/.gitignore index 524f096..9232c63 100644 --- a/.gitignore +++ b/.gitignore @@ -1,24 +1,40 @@ -# Compiled class file -*.class +# Maven +target/ +*.jar +*.war +*.ear +pom.xml.tag +pom.xml.releaseBackup +pom.xml.versionsBackup +pom.xml.next +release.properties -# Log file -*.log +# IntelliJ IDEA +.idea/ +*.iws +*.iml +*.ipr -# BlueJ files -*.ctxt +# VS Code +.vscode/ -# Mobile Tools for Java (J2ME) -.mtj.tmp/ +# Eclipse +.classpath +.project +.settings/ +bin/ -# Package Files # -*.jar -*.war -*.nar -*.ear -*.zip -*.tar.gz -*.rar +# Mac +.DS_Store +.AppleDouble +.LSOverride + +# Logs +*.log +logs/ + +# Docker +.dockerignore -# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml -hs_err_pid* -replay_pid* +# Spring Boot +spring-shell.log \ No newline at end of file diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..8709ebc --- /dev/null +++ b/Dockerfile @@ -0,0 +1,18 @@ +FROM eclipse-temurin:17-jdk AS builder + +WORKDIR /app + +COPY pom.xml . +COPY src ./src + +RUN apt-get update && apt-get install -y maven && mvn clean package -DskipTests + +FROM eclipse-temurin:17-jre + +WORKDIR /app + +COPY --from=builder /app/target/*.jar app.jar + +EXPOSE 8040 + +ENTRYPOINT ["java", "-jar", "app.jar"] \ No newline at end of file diff --git a/Empleados.postman_collection.json b/Empleados.postman_collection.json new file mode 100644 index 0000000..69ad09b --- /dev/null +++ b/Empleados.postman_collection.json @@ -0,0 +1,80 @@ +{ + "info": { + "_postman_id": "935f6379-1ad6-4aa5-a5ce-d36a400f1a11", + "name": "Employee", + "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json", + "_exporter_id": "52888531", + "_collection_link": "https://go.postman.co/collection/52888531-935f6379-1ad6-4aa5-a5ce-d36a400f1a11?source=collection_link" + }, + "item": [ + { + "name": "Create", + "request": { + "method": "POST", + "header": [], + "body": { + "mode": "raw", + "raw": "{\n \"nombre\": \"Juan\",\n \"apellido\": \"Pérez\",\n \"rut\": \"11111111-1\",\n \"cargo\": \"Desarrollador\",\n \"salario\": 500000,\n \"bono\": 30000,\n \"descuentos\":400000\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "localhost:8040/api/empleados/", + "host": [ + "localhost" + ], + "port": "8040", + "path": [ + "api", + "empleados", + "" + ] + } + }, + "response": [] + }, + { + "name": "List", + "request": { + "method": "GET", + "header": [], + "url": { + "raw": "localhost:8040/api/empleados/", + "host": [ + "localhost" + ], + "port": "8040", + "path": [ + "api", + "empleados", + "" + ] + } + }, + "response": [] + }, + { + "name": "delete", + "request": { + "method": "DELETE", + "header": [], + "url": { + "raw": "localhost:8040/api/empleados/1", + "host": [ + "localhost" + ], + "port": "8040", + "path": [ + "api", + "empleados", + "1" + ] + } + }, + "response": [] + } + ] +} \ No newline at end of file diff --git a/HELP.md b/HELP.md new file mode 100644 index 0000000..e3488aa --- /dev/null +++ b/HELP.md @@ -0,0 +1,27 @@ +# Getting Started + +### Reference Documentation +For further reference, please consider the following sections: + +* [Official Apache Maven documentation](https://maven.apache.org/guides/index.html) +* [Spring Boot Maven Plugin Reference Guide](https://docs.spring.io/spring-boot/3.5.13/maven-plugin) +* [Create an OCI image](https://docs.spring.io/spring-boot/3.5.13/maven-plugin/build-image.html) +* [Spring Web](https://docs.spring.io/spring-boot/3.5.13/reference/web/servlet.html) +* [JDBC API](https://docs.spring.io/spring-boot/3.5.13/reference/data/sql.html) + +### Guides +The following guides illustrate how to use some features concretely: + +* [Building a RESTful Web Service](https://spring.io/guides/gs/rest-service/) +* [Serving Web Content with Spring MVC](https://spring.io/guides/gs/serving-web-content/) +* [Building REST services with Spring](https://spring.io/guides/tutorials/rest/) +* [Accessing Relational Data using JDBC with Spring](https://spring.io/guides/gs/relational-data-access/) +* [Managing Transactions](https://spring.io/guides/gs/managing-transactions/) + +### Maven Parent overrides + +Due to Maven's design, elements are inherited from the parent POM to the project POM. +While most of the inheritance is fine, it also inherits unwanted elements like `` and `` from the parent. +To prevent this, the project POM contains empty overrides for these elements. +If you manually switch to a different parent and actually want the inheritance, you need to remove those overrides. + diff --git a/README.md b/README.md index dbe2b5d..84257a0 100644 --- a/README.md +++ b/README.md @@ -1,72 +1,292 @@ -# Desafío Técnico: Servlets y AJAX +# Desafío Técnico — Gestión de Empleados -## Objetivo: -Demostrar el conocimiento sobre Java (mínimo versión 8), manejo de servlets y peticiones AJAX nativas. +**Nombre:** Daniel Ivan Ramos Truitrui +**Empresa reclutadora:** Tecnova +**Correo:** dan.ramostr@gmail.com +**Cargo:** Desarrollador Java -## Requisitos Técnicos: -### Java: -- Utiliza Java 8 o superior para la implementación. -- Utiliza las características de Java como lambdas y streams, cuando sea apropiado. -- Utilizar Maven como gestor de dependencias. -- Utilizar Spring Boot como Runtime para la ejecución del desafío en conjunto con Apache Tomcat como contenedor web. +--- -## Parte 1: Implementación de un Servicio Web con Servlets y AJAX +## Descripción + +Aplicación web para la gestión de empleados implementada con Java 17, Spring Boot 3.5, Servlets y JDBC con base de datos H2 en memoria. Permite listar, agregar y eliminar empleados mediante una interfaz web con AJAX. + +--- + +## Tecnologías + +- Java 17 +- Spring Boot 3.5.13 +- Apache Tomcat (embebido) +- Servlets (`@WebServlet`) +- JdbcTemplate (JDBC puro, sin JPA/Hibernate) +- H2 Database (en memoria) +- JUnit 5 + Mockito +- HTML + CSS + Fetch API (AJAX) + +--- + +## Arquitectura + +El proyecto sigue una arquitectura de 3 capas: + +``` +Controller → Servlet puro (@WebServlet) +Service → Lógica de negocio y validaciones +Repository → Acceso a datos con JdbcTemplate +``` + +### Estructura de paquetes + +``` +src/ +├── main/ +│ ├── java/com/danielr/desafio/ +│ │ ├── DesafioApplication.java +│ │ ├── controller/ +│ │ │ └── EmployeeController.java +│ │ ├── dto/ +│ │ │ ├── EmployeeRequestDTO.java +│ │ │ └── EmployeeResponseDTO.java +│ │ ├── exception/ +│ │ │ └── BusinessException.java +│ │ ├── model/ +│ │ │ └── Employee.java +│ │ ├── repository/ +│ │ │ └── EmployeeRepository.java +│ │ └── service/ +│ │ ├── IEmployeeService.java +│ │ └── impl/ +│ │ └── EmployeeServiceImpl.java +│ └── resources/ +│ ├── static/ +│ │ └── index.html +│ ├── application.properties +│ ├── schema.sql +│ └── data.sql +└── test/ + ├── java/com/danielr/desafio/ + │ ├── repository/ + │ │ └── EmployeeRepositoryTest.java + │ └── service/ + │ └── EmployeeServiceImplTest.java + └── resources/ + └── application-test.properties +``` + +--- + +## Requisitos previos + +- Java 17 o superior +- Maven 3.8 o superior + +Verificar versiones instaladas: + +```bash +java -version +mvn -version +``` + +--- + +## Cómo ejecutar + +### 1. Clonar el repositorio + +```bash +git clone https://github.com/previred/desafio-legacy.git +cd desafio-legacy +``` + +### 2. Compilar el proyecto + +```bash +mvn clean install +``` + +### 3. Ejecutar la aplicación + +```bash +mvn spring-boot:run +``` + +La aplicación estará disponible en: + +``` +http://localhost:8084 +``` + +--- + +## Endpoints disponibles + +| Método | Endpoint | Descripción | +|---|---|---| +| GET | `/api/empleados` | Listar todos los empleados | +| POST | `/api/empleados` | Crear un nuevo empleado | +| DELETE | `/api/empleados/{id}` | Eliminar un empleado por ID | + +### Ejemplo POST + +```bash +curl -X POST http://localhost:8040/api/empleados \ + -H "Content-Type: application/json" \ + -d '{ + "nombre": "Juan", + "apellido": "Pérez", + "rut": "12345678-9", + "cargo": "Desarrollador", + "salario": 800000, + "bono": 100000, + "descuentos": 50000 + }' ``` - Crear una aplicación web en Java 8 con Servlets y manejo de AJAX, con las siguientes características: - Endpoint: /api/empleados - GET: Retorna una lista de empleados en formato JSON. - POST: Permite agregar un nuevo empleado enviando datos en formato JSON. - DELETE: Elimina un empleado por su ID. +### Ejemplo DELETE - Datos esperados del empleado: +```bash +curl -X DELETE http://localhost:8040/api/empleados/1 +``` + +--- + +## Códigos de respuesta HTTP + +| Código | Descripción | +|---|---| +| 200 | OK — GET exitoso | +| 201 | Created — POST exitoso | +| 204 | No Content — DELETE exitoso | +| 400 | Bad Request — error de validación | +| 500 | Internal Server Error — error inesperado | + +### Respuesta de error (HTTP 400) + +```json +{ + "errores": [ + "El salario base no puede ser menor a $400.000", + "El bono no puede superar el 50% del salario base" + ] +} +``` + +--- + +## Reglas de negocio + +- El salario base no puede ser menor a **$400.000** +- El bono no puede superar el **50% del salario base** +- Los descuentos no pueden superar el **salario base** +- No se permiten empleados con **RUT duplicado** +- El borrado de empleados es **lógico** (campo `deleted_at`) + +--- + +## Consola H2 + +Durante el desarrollo se puede acceder a la consola web de H2 para inspeccionar los datos: + +``` +URL: http://localhost:8040/h2-console +JDBC URL: jdbc:h2:mem:desafiodb +Usuario: sa +Password: (vacío) +``` + +--- + +## Ejecutar tests + +```bash +mvn test +``` - ID (autogenerado), Nombre, Apellido, RUT/DNI, Cargo, Salario. +Los tests cubren las capas de **Service** (con Mockito) y **Repository** (con H2 real): - Interfaz con AJAX: - Crear una página web simple en HTML + JavaScript (sin frameworks como React o Angular). - Usar AJAX (Fetch API o XMLHttpRequest) para: - - Cargar la lista de empleados sin recargar la página. - - Agregar nuevos empleados mediante un formulario sin recargar la página. - - Eliminar empleados con un botón sin recargar la página. +``` +EmployeeServiceImplTest → 14 tests — validaciones de negocio +EmployeeRepositoryTest → 14 tests — queries SQL con H2 +``` + +--- + +## Interfaz web + +La interfaz está disponible en `http://localhost:8040` e incluye: + +- Formulario para agregar empleados con validaciones en tiempo real +- Formato automático del RUT mientras se escribe +- Tabla de empleados con botón de eliminación por fila +- Mensajes de error y éxito dinámicos sin recargar la página +- Comunicación con el backend mediante Fetch API (AJAX) + +--- + +## Coleccion Postman + +En la raiz del proyecto se encuentra el archivo `empleados.postman_collection.json` con los 3 endpoints listos para importar y probar en Postman. + +Para importarlo: +1. Abre Postman +2. Clic en **Import** +3. Selecciona el archivo `empleados.postman_collection.json` +4. Los endpoints quedaran listos para usar - Requerimientos técnicos: - - No usar frameworks externos, solo Servlets y JDBC para conexión con una BD en memoria como H2. - - Manejo adecuado de excepciones y logging. - - Validación de datos en los endpoints. +--- + +## Docker + +### Requisitos + +- Docker instalado y corriendo +- Docker Compose instalado + +Verificar: + +```bash +docker -v +docker-compose -v ``` -## Parte 2: Validaciones de Reglas de Negocio con AJAX +### Opcion 1: Script automatico (recomendado) +La forma mas simple de levantar la aplicacion es usando el script incluido: + +```bash +chmod +x start.sh +./start.sh ``` - Implementar validaciones en la carga de empleados y nóminas: - 1. En el backend (Java 8): - - Rechazar empleados con RUT/DNI duplicado. - - No permitir salarios base menores a $400,000. - - Bonos no pueden superar el 50% del salario base. - - El total de descuentos no puede ser mayor al salario base. - - Si alguna regla se incumple, se debe retornar una respuesta HTTP 400 con un JSON indicando los registros con error. - 2. En el frontend (JavaScript + AJAX): - - Implementar validaciones antes de enviar el formulario: - - Verificar que todos los campos estén completos. - - Validar formato del RUT/DNI. - - Validar que el salario base no sea menor a $400,000. - - Mostrar errores de validación de forma dinámica en la página (sin alertas de JavaScript). +El script verifica que Docker este instalado y corriendo, construye la imagen y levanta el contenedor automaticamente. La aplicacion quedara disponible en `http://localhost:8040`. + +### Opcion 2: Docker Compose manualmente + +```bash +# Construir y levantar +docker-compose up --build -d + +# Ver logs +docker-compose logs -f + +# Detener +docker-compose down ``` -## Entregables: -### Repositorio de GitHub: -- Realiza un Pull request a este repositorio indicando tu nombre, empresa reclutadora, correo y cargo al que postulas. -- Todos los PR serán rechazados, no es un indicador de la prueba. +### Opcion 3: Docker manualmente -### Documentación: -- Incluye instrucciones claras en un README en formato markdown, sobre cómo ejecutar y probar la aplicación. +```bash +# Construir la imagen +docker build -t desafio-empleados . + +# Correr el contenedor +docker run -p 8040:8040 desafio-empleados +``` -## Evaluación: -Se evaluará la solución en función de los siguientes criterios: +### URLs con Docker -- Correcta implementación de las funcionalidades solicitadas. -- Aplicación de buenas prácticas de desarrollo, patrones de diseño y principios SOLID. -- Uso adecuado de Java y Javascript. -- Claridad y completitud de la documentación. +``` +App: http://localhost:8040 +H2: http://localhost:8040/h2-console +``` \ No newline at end of file diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..704ce0e --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,19 @@ +services: + desafio: + build: + context: . + dockerfile: Dockerfile + container_name: desafio-empleados + ports: + - "8040:8040" + environment: + - SPRING_PROFILES_ACTIVE=default + - SPRING_DATASOURCE_URL=jdbc:h2:mem:desafiodb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE + - SPRING_H2_CONSOLE_ENABLED=true + - SPRING_H2_CONSOLE_SETTINGS_WEB_ALLOW_OTHERS=true + healthcheck: + test: ["CMD", "wget", "--spider", "-q", "http://localhost:8040/h2-console"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 40s \ No newline at end of file diff --git a/mvnw b/mvnw new file mode 100755 index 0000000..bd8896b --- /dev/null +++ b/mvnw @@ -0,0 +1,295 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# 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. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Apache Maven Wrapper startup batch script, version 3.3.4 +# +# Optional ENV vars +# ----------------- +# JAVA_HOME - location of a JDK home dir, required when download maven via java source +# MVNW_REPOURL - repo url base for downloading maven distribution +# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output +# ---------------------------------------------------------------------------- + +set -euf +[ "${MVNW_VERBOSE-}" != debug ] || set -x + +# OS specific support. +native_path() { printf %s\\n "$1"; } +case "$(uname)" in +CYGWIN* | MINGW*) + [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" + native_path() { cygpath --path --windows "$1"; } + ;; +esac + +# set JAVACMD and JAVACCMD +set_java_home() { + # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched + if [ -n "${JAVA_HOME-}" ]; then + if [ -x "$JAVA_HOME/jre/sh/java" ]; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACCMD="$JAVA_HOME/jre/sh/javac" + else + JAVACMD="$JAVA_HOME/bin/java" + JAVACCMD="$JAVA_HOME/bin/javac" + + if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then + echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 + echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 + return 1 + fi + fi + else + JAVACMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v java + )" || : + JAVACCMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v javac + )" || : + + if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then + echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 + return 1 + fi + fi +} + +# hash string like Java String::hashCode +hash_string() { + str="${1:-}" h=0 + while [ -n "$str" ]; do + char="${str%"${str#?}"}" + h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) + str="${str#?}" + done + printf %x\\n $h +} + +verbose() { :; } +[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } + +die() { + printf %s\\n "$1" >&2 + exit 1 +} + +trim() { + # MWRAPPER-139: + # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. + # Needed for removing poorly interpreted newline sequences when running in more + # exotic environments such as mingw bash on Windows. + printf "%s" "${1}" | tr -d '[:space:]' +} + +scriptDir="$(dirname "$0")" +scriptName="$(basename "$0")" + +# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties +while IFS="=" read -r key value; do + case "${key-}" in + distributionUrl) distributionUrl=$(trim "${value-}") ;; + distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; + esac +done <"$scriptDir/.mvn/wrapper/maven-wrapper.properties" +[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" + +case "${distributionUrl##*/}" in +maven-mvnd-*bin.*) + MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ + case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in + *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; + :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; + :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; + :Linux*x86_64*) distributionPlatform=linux-amd64 ;; + *) + echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 + distributionPlatform=linux-amd64 + ;; + esac + distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" + ;; +maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; +*) MVN_CMD="mvn${scriptName#mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; +esac + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" +distributionUrlName="${distributionUrl##*/}" +distributionUrlNameMain="${distributionUrlName%.*}" +distributionUrlNameMain="${distributionUrlNameMain%-bin}" +MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" +MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" + +exec_maven() { + unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : + exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" +} + +if [ -d "$MAVEN_HOME" ]; then + verbose "found existing MAVEN_HOME at $MAVEN_HOME" + exec_maven "$@" +fi + +case "${distributionUrl-}" in +*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; +*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; +esac + +# prepare tmp dir +if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then + clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } + trap clean HUP INT TERM EXIT +else + die "cannot create temp dir" +fi + +mkdir -p -- "${MAVEN_HOME%/*}" + +# Download and Install Apache Maven +verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +verbose "Downloading from: $distributionUrl" +verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +# select .zip or .tar.gz +if ! command -v unzip >/dev/null; then + distributionUrl="${distributionUrl%.zip}.tar.gz" + distributionUrlName="${distributionUrl##*/}" +fi + +# verbose opt +__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' +[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v + +# normalize http auth +case "${MVNW_PASSWORD:+has-password}" in +'') MVNW_USERNAME='' MVNW_PASSWORD='' ;; +has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; +esac + +if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then + verbose "Found wget ... using wget" + wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" +elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then + verbose "Found curl ... using curl" + curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" +elif set_java_home; then + verbose "Falling back to use Java to download" + javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" + targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" + cat >"$javaSource" <<-END + public class Downloader extends java.net.Authenticator + { + protected java.net.PasswordAuthentication getPasswordAuthentication() + { + return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); + } + public static void main( String[] args ) throws Exception + { + setDefault( new Downloader() ); + java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); + } + } + END + # For Cygwin/MinGW, switch paths to Windows format before running javac and java + verbose " - Compiling Downloader.java ..." + "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" + verbose " - Running Downloader.java ..." + "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" +fi + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +if [ -n "${distributionSha256Sum-}" ]; then + distributionSha256Result=false + if [ "$MVN_CMD" = mvnd.sh ]; then + echo "Checksum validation is not supported for maven-mvnd." >&2 + echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + elif command -v sha256sum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c - >/dev/null 2>&1; then + distributionSha256Result=true + fi + elif command -v shasum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 + echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + fi + if [ $distributionSha256Result = false ]; then + echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 + echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 + exit 1 + fi +fi + +# unzip and move +if command -v unzip >/dev/null; then + unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" +else + tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" +fi + +# Find the actual extracted directory name (handles snapshots where filename != directory name) +actualDistributionDir="" + +# First try the expected directory name (for regular distributions) +if [ -d "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" ]; then + if [ -f "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/bin/$MVN_CMD" ]; then + actualDistributionDir="$distributionUrlNameMain" + fi +fi + +# If not found, search for any directory with the Maven executable (for snapshots) +if [ -z "$actualDistributionDir" ]; then + # enable globbing to iterate over items + set +f + for dir in "$TMP_DOWNLOAD_DIR"/*; do + if [ -d "$dir" ]; then + if [ -f "$dir/bin/$MVN_CMD" ]; then + actualDistributionDir="$(basename "$dir")" + break + fi + fi + done + set -f +fi + +if [ -z "$actualDistributionDir" ]; then + verbose "Contents of $TMP_DOWNLOAD_DIR:" + verbose "$(ls -la "$TMP_DOWNLOAD_DIR")" + die "Could not find Maven distribution directory in extracted archive" +fi + +verbose "Found extracted Maven distribution directory: $actualDistributionDir" +printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$actualDistributionDir/mvnw.url" +mv -- "$TMP_DOWNLOAD_DIR/$actualDistributionDir" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" + +clean || : +exec_maven "$@" diff --git a/mvnw.cmd b/mvnw.cmd new file mode 100644 index 0000000..92450f9 --- /dev/null +++ b/mvnw.cmd @@ -0,0 +1,189 @@ +<# : batch portion +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Apache Maven Wrapper startup batch script, version 3.3.4 +@REM +@REM Optional ENV vars +@REM MVNW_REPOURL - repo url base for downloading maven distribution +@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output +@REM ---------------------------------------------------------------------------- + +@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) +@SET __MVNW_CMD__= +@SET __MVNW_ERROR__= +@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% +@SET PSModulePath= +@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( + IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) +) +@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% +@SET __MVNW_PSMODULEP_SAVE= +@SET __MVNW_ARG0_NAME__= +@SET MVNW_USERNAME= +@SET MVNW_PASSWORD= +@IF NOT "%__MVNW_CMD__%"=="" ("%__MVNW_CMD__%" %*) +@echo Cannot start maven from wrapper >&2 && exit /b 1 +@GOTO :EOF +: end batch / begin powershell #> + +$ErrorActionPreference = "Stop" +if ($env:MVNW_VERBOSE -eq "true") { + $VerbosePreference = "Continue" +} + +# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties +$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl +if (!$distributionUrl) { + Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" +} + +switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { + "maven-mvnd-*" { + $USE_MVND = $true + $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" + $MVN_CMD = "mvnd.cmd" + break + } + default { + $USE_MVND = $false + $MVN_CMD = $script -replace '^mvnw','mvn' + break + } +} + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +if ($env:MVNW_REPOURL) { + $MVNW_REPO_PATTERN = if ($USE_MVND -eq $False) { "/org/apache/maven/" } else { "/maven/mvnd/" } + $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace "^.*$MVNW_REPO_PATTERN",'')" +} +$distributionUrlName = $distributionUrl -replace '^.*/','' +$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' + +$MAVEN_M2_PATH = "$HOME/.m2" +if ($env:MAVEN_USER_HOME) { + $MAVEN_M2_PATH = "$env:MAVEN_USER_HOME" +} + +if (-not (Test-Path -Path $MAVEN_M2_PATH)) { + New-Item -Path $MAVEN_M2_PATH -ItemType Directory | Out-Null +} + +$MAVEN_WRAPPER_DISTS = $null +if ((Get-Item $MAVEN_M2_PATH).Target[0] -eq $null) { + $MAVEN_WRAPPER_DISTS = "$MAVEN_M2_PATH/wrapper/dists" +} else { + $MAVEN_WRAPPER_DISTS = (Get-Item $MAVEN_M2_PATH).Target[0] + "/wrapper/dists" +} + +$MAVEN_HOME_PARENT = "$MAVEN_WRAPPER_DISTS/$distributionUrlNameMain" +$MAVEN_HOME_NAME = ([System.Security.Cryptography.SHA256]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' +$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" + +if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { + Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" + Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" + exit $? +} + +if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { + Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" +} + +# prepare tmp dir +$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile +$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" +$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null +trap { + if ($TMP_DOWNLOAD_DIR.Exists) { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } + } +} + +New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null + +# Download and Install Apache Maven +Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +Write-Verbose "Downloading from: $distributionUrl" +Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +$webclient = New-Object System.Net.WebClient +if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { + $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) +} +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum +if ($distributionSha256Sum) { + if ($USE_MVND) { + Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." + } + Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash + if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { + Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." + } +} + +# unzip and move +Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null + +# Find the actual extracted directory name (handles snapshots where filename != directory name) +$actualDistributionDir = "" + +# First try the expected directory name (for regular distributions) +$expectedPath = Join-Path "$TMP_DOWNLOAD_DIR" "$distributionUrlNameMain" +$expectedMvnPath = Join-Path "$expectedPath" "bin/$MVN_CMD" +if ((Test-Path -Path $expectedPath -PathType Container) -and (Test-Path -Path $expectedMvnPath -PathType Leaf)) { + $actualDistributionDir = $distributionUrlNameMain +} + +# If not found, search for any directory with the Maven executable (for snapshots) +if (!$actualDistributionDir) { + Get-ChildItem -Path "$TMP_DOWNLOAD_DIR" -Directory | ForEach-Object { + $testPath = Join-Path $_.FullName "bin/$MVN_CMD" + if (Test-Path -Path $testPath -PathType Leaf) { + $actualDistributionDir = $_.Name + } + } +} + +if (!$actualDistributionDir) { + Write-Error "Could not find Maven distribution directory in extracted archive" +} + +Write-Verbose "Found extracted Maven distribution directory: $actualDistributionDir" +Rename-Item -Path "$TMP_DOWNLOAD_DIR/$actualDistributionDir" -NewName $MAVEN_HOME_NAME | Out-Null +try { + Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null +} catch { + if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { + Write-Error "fail to move MAVEN_HOME" + } +} finally { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } +} + +Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..f6033db --- /dev/null +++ b/pom.xml @@ -0,0 +1,74 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.5.13 + + + com.danielr + desafio + 0.0.1-SNAPSHOT + + + + + + + + + + + + + + + + + 17 + UTF-8 + UTF-8 + + + + org.springframework.boot + spring-boot-starter-jdbc + + + org.springframework.boot + spring-boot-starter-web + + + + com.h2database + h2 + runtime + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + src/main/resources + false + + + + + + diff --git a/src/main/java/com/danielr/desafio/DesafioApplication.java b/src/main/java/com/danielr/desafio/DesafioApplication.java new file mode 100644 index 0000000..58ebcb8 --- /dev/null +++ b/src/main/java/com/danielr/desafio/DesafioApplication.java @@ -0,0 +1,15 @@ +package com.danielr.desafio; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.web.servlet.ServletComponentScan; + +@SpringBootApplication +@ServletComponentScan +public class DesafioApplication { + + public static void main(String[] args) { + SpringApplication.run(DesafioApplication.class, args); + } + +} diff --git a/src/main/java/com/danielr/desafio/controller/EmployeeController.java b/src/main/java/com/danielr/desafio/controller/EmployeeController.java new file mode 100644 index 0000000..cebeb11 --- /dev/null +++ b/src/main/java/com/danielr/desafio/controller/EmployeeController.java @@ -0,0 +1,143 @@ +package com.danielr.desafio.controller; + +import com.danielr.desafio.dto.EmployeeRequestDTO; +import com.danielr.desafio.dto.EmployeeResponseDTO; +import com.danielr.desafio.exception.BusinessException; +import com.danielr.desafio.service.IEmployeeService; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import jakarta.servlet.ServletException; +import jakarta.servlet.annotation.WebServlet; +import jakarta.servlet.http.HttpServlet; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.springframework.context.ApplicationContext; +import org.springframework.web.context.support.WebApplicationContextUtils; + +import java.io.IOException; +import java.util.List; +import java.util.Map; + +@WebServlet("/api/empleados/*") +public class EmployeeController extends HttpServlet { + + private IEmployeeService employeeService; + private ObjectMapper objectMapper; + + @Override + public void init() throws ServletException { + ApplicationContext ctx = WebApplicationContextUtils + .getRequiredWebApplicationContext(getServletContext()); + this.employeeService = ctx.getBean(IEmployeeService.class); + this.objectMapper = new ObjectMapper(); + + // para LocalDateTime + this.objectMapper.registerModule(new JavaTimeModule()); + } + + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) + throws IOException { + + setJsonResponse(resp); + + try { + List empleados = employeeService.findAll(); + resp.setStatus(HttpServletResponse.SC_OK); // 200 + resp.getWriter().write(objectMapper.writeValueAsString(empleados)); + } catch (Exception e) { + sendError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error al obtener empleados"); + } + + } + + @Override + protected void doPost(HttpServletRequest req, HttpServletResponse resp) + throws IOException { + + setJsonResponse(resp); + + try { + EmployeeRequestDTO dto = objectMapper.readValue(req.getReader(), EmployeeRequestDTO.class); + EmployeeResponseDTO created = employeeService.save(dto); + resp.setStatus(HttpServletResponse.SC_CREATED); // 201 + resp.getWriter().write(objectMapper.writeValueAsString(created)); + } catch (BusinessException e) { + sendErrors(resp, HttpServletResponse.SC_BAD_REQUEST, e.getErrors()); // 400 + } catch (Exception e) { + sendError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error al crear empleado"); // 500 + } + + } + + @Override + protected void doDelete(HttpServletRequest req, HttpServletResponse resp) + throws IOException { + + setJsonResponse(resp); + + try { + Long id = extractId(req); + if (id == null) { + sendError(resp, HttpServletResponse.SC_BAD_REQUEST, "Se requiere ID"); // 400 + return; + } + + if (employeeService.delete(id)) { + resp.setStatus(HttpServletResponse.SC_NO_CONTENT); // 204 + } else { + sendError(resp, HttpServletResponse.SC_BAD_REQUEST, "Empleado no encontrado"); + } + + } catch (BusinessException e) { + sendErrors(resp, HttpServletResponse.SC_BAD_REQUEST, e.getErrors()); // 400 + } catch (Exception e) { + sendError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error al eliminar empleado"); // 500 + } + + } + + /** + * extrae id de la ruta + */ + private Long extractId(HttpServletRequest req) { + String pathInfo = req.getPathInfo(); + if (pathInfo == null || pathInfo.equals("/")) return null; + try { + return Long.parseLong(pathInfo.substring(1)); + } catch (NumberFormatException e) { + return null; + } + } + + /** + * Set Json y encoding + */ + private void setJsonResponse(HttpServletResponse resp) { + resp.setContentType("application/json"); + resp.setCharacterEncoding("UTF-8"); + } + + /** + * Error simple con un mensaje + */ + private void sendError(HttpServletResponse resp, int status, String message) + throws IOException { + resp.setStatus(status); + resp.getWriter().write( + objectMapper.writeValueAsString(Map.of("mensaje", message)) + ); + } + + /** + * Error con lista de mensajes (validaciones) + */ + private void sendErrors(HttpServletResponse resp, int status, List errors) + throws IOException { + resp.setStatus(status); + resp.getWriter().write( + objectMapper.writeValueAsString(Map.of("errores", errors)) + ); + } + +} diff --git a/src/main/java/com/danielr/desafio/dto/EmployeeRequestDTO.java b/src/main/java/com/danielr/desafio/dto/EmployeeRequestDTO.java new file mode 100644 index 0000000..c4a918b --- /dev/null +++ b/src/main/java/com/danielr/desafio/dto/EmployeeRequestDTO.java @@ -0,0 +1,30 @@ +package com.danielr.desafio.dto; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.math.BigDecimal; + +public record EmployeeRequestDTO( + + @JsonProperty("nombre") + String name, + + @JsonProperty("apellido") + String lastname, + + @JsonProperty("rut") + String dni, + + @JsonProperty("cargo") + String position, + + @JsonProperty("salario") + BigDecimal salary, + + @JsonProperty("bono") + BigDecimal bonus, + + @JsonProperty("descuentos") + BigDecimal deductions + +) {} diff --git a/src/main/java/com/danielr/desafio/dto/EmployeeResponseDTO.java b/src/main/java/com/danielr/desafio/dto/EmployeeResponseDTO.java new file mode 100644 index 0000000..1333792 --- /dev/null +++ b/src/main/java/com/danielr/desafio/dto/EmployeeResponseDTO.java @@ -0,0 +1,37 @@ +package com.danielr.desafio.dto; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.math.BigDecimal; + +public record EmployeeResponseDTO( + + @JsonProperty("id") + Long id, + + @JsonProperty("nombre") + String name, + + @JsonProperty("apellido") + String lastname, + + @JsonProperty("rut") + String dni, + + @JsonProperty("cargo") + String position, + + @JsonProperty("salario") + BigDecimal salary, + + @JsonProperty("bono") + BigDecimal bonus, + + @JsonProperty("descuentos") + BigDecimal deductions, + + @JsonProperty("fecha_creacion") + String created + +) { +} diff --git a/src/main/java/com/danielr/desafio/exception/BusinessException.java b/src/main/java/com/danielr/desafio/exception/BusinessException.java new file mode 100644 index 0000000..d685eda --- /dev/null +++ b/src/main/java/com/danielr/desafio/exception/BusinessException.java @@ -0,0 +1,22 @@ +package com.danielr.desafio.exception; + +import java.util.List; + +public class BusinessException extends RuntimeException { + + private final List errors; + + public BusinessException(String message) { + super(message); + this.errors = List.of(message); + } + + public BusinessException(List errors) { + super(String.join(", ", errors)); + this.errors = errors; + } + + public List getErrors() { + return errors; + } +} diff --git a/src/main/java/com/danielr/desafio/model/Employee.java b/src/main/java/com/danielr/desafio/model/Employee.java new file mode 100644 index 0000000..6c8ea5e --- /dev/null +++ b/src/main/java/com/danielr/desafio/model/Employee.java @@ -0,0 +1,123 @@ +package com.danielr.desafio.model; + +import java.math.BigDecimal; +import java.time.LocalDateTime; + +public class Employee { + + private Long id; + private String firstName; + private String lastName; + private String taxId; + private String position; + private BigDecimal baseSalary; + private BigDecimal bonus; + private BigDecimal deductions; + private LocalDateTime createdAt; + private LocalDateTime updatedAt; + private LocalDateTime deletedAt; + + public Employee() {} + + public Employee(Long id, String firstName, String lastName, String taxId, String position, BigDecimal baseSalary, BigDecimal bonus, BigDecimal deductions, LocalDateTime createdAt, LocalDateTime updatedAt, LocalDateTime deletedAt) { + this.id = id; + this.firstName = firstName; + this.lastName = lastName; + this.taxId = taxId; + this.position = position; + this.baseSalary = baseSalary; + this.bonus = bonus; + this.deductions = deductions; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + this.deletedAt = deletedAt; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getTaxId() { + return taxId; + } + + public void setTaxId(String taxId) { + this.taxId = taxId; + } + + public String getPosition() { + return position; + } + + public void setPosition(String position) { + this.position = position; + } + + public BigDecimal getBaseSalary() { + return baseSalary; + } + + public void setBaseSalary(BigDecimal baseSalary) { + this.baseSalary = baseSalary; + } + + public BigDecimal getBonus() { + return bonus; + } + + public void setBonus(BigDecimal bonus) { + this.bonus = bonus; + } + + public BigDecimal getDeductions() { + return deductions; + } + + public void setDeductions(BigDecimal deductions) { + this.deductions = deductions; + } + + public LocalDateTime getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(LocalDateTime createdAt) { + this.createdAt = createdAt; + } + + public LocalDateTime getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(LocalDateTime updatedAt) { + this.updatedAt = updatedAt; + } + + public LocalDateTime getDeletedAt() { + return deletedAt; + } + + public void setDeletedAt(LocalDateTime deletedAt) { + this.deletedAt = deletedAt; + } +} diff --git a/src/main/java/com/danielr/desafio/repository/EmployeeRepository.java b/src/main/java/com/danielr/desafio/repository/EmployeeRepository.java new file mode 100644 index 0000000..216beb4 --- /dev/null +++ b/src/main/java/com/danielr/desafio/repository/EmployeeRepository.java @@ -0,0 +1,149 @@ +package com.danielr.desafio.repository; + +import com.danielr.desafio.exception.BusinessException; +import com.danielr.desafio.model.Employee; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.RowMapper; +import org.springframework.jdbc.support.GeneratedKeyHolder; +import org.springframework.jdbc.support.KeyHolder; +import org.springframework.stereotype.Repository; + +import java.math.BigDecimal; +import java.sql.PreparedStatement; +import java.sql.Statement; +import java.sql.Timestamp; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +@Repository +public class EmployeeRepository { + + private static final Logger logger = LoggerFactory.getLogger(EmployeeRepository.class); + private final JdbcTemplate jdbcTemplate; + + public EmployeeRepository(JdbcTemplate jdbcTemplate) { + this.jdbcTemplate = jdbcTemplate; + } + + // RowMapper reutilizable: convierte una fila SQL → objeto Employee + private final RowMapper rowMapper = (rs, rowNum) -> { + Employee e = new Employee(); + e.setId(rs.getLong("id")); + e.setFirstName(rs.getString("first_name")); + e.setLastName(rs.getString("last_name")); + e.setTaxId(rs.getString("tax_id")); + e.setPosition(rs.getString("position")); + e.setBaseSalary(rs.getBigDecimal("base_salary")); + e.setBonus(rs.getBigDecimal("bonus")); + e.setDeductions(rs.getBigDecimal("deductions")); + e.setCreatedAt(rs.getTimestamp("created_at").toLocalDateTime()); + e.setUpdatedAt(rs.getTimestamp("updated_at").toLocalDateTime()); + + Timestamp deletedAt = rs.getTimestamp("deleted_at"); + e.setDeletedAt(deletedAt != null ? deletedAt.toLocalDateTime() : null); + + return e; + }; + + /** + * Se filtra por registros que no esten eliminados + */ + public List findAll() { + logger.debug("Ejecutando Lista de empleados filtrada por eliminados"); + String sql = "SELECT * FROM employees WHERE deleted_at IS NULL"; + List query = jdbcTemplate.query(sql, rowMapper); + return query; + } + + public Optional findById(Long id) { + logger.debug("Ejecutando findById: {}", id); + String sql = "SELECT * FROM employees WHERE id = ? AND deleted_at IS NULL"; + List result = jdbcTemplate.query(sql, rowMapper, id); + return result.stream().findFirst(); + } + + /** + * Find by Rut/Dni + */ + public boolean existsByDni(String taxId) { + logger.debug("Verificando DNI duplicado: {}", taxId); + String sql = "SELECT COUNT(*) FROM employees WHERE tax_id = ? AND deleted_at IS NULL"; + Integer count = jdbcTemplate.queryForObject(sql, Integer.class, taxId); + return count != null && count > 0; + } + + /** + * Create Method + */ + public Employee save(Employee employee) { + + logger.debug("Ejecutando creacion de empleado........"); + + String sql = "INSERT INTO employees (first_name, last_name, tax_id, position, base_salary, bonus, deductions) " + + "VALUES (?, ?, ?, ?, ?, ?, ?)"; + + + KeyHolder keyHolder = new GeneratedKeyHolder(); + + try { + + int rows = jdbcTemplate.update(connection -> { + PreparedStatement ps = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); + ps.setString(1, employee.getFirstName()); + ps.setString(2, employee.getLastName()); + ps.setString(3, employee.getTaxId()); + ps.setString(4, employee.getPosition()); + ps.setBigDecimal(5, employee.getBaseSalary()); + ps.setBigDecimal(6, employee.getBonus() != null ? employee.getBonus() : BigDecimal.ZERO); + ps.setBigDecimal(7, employee.getDeductions() != null ? employee.getDeductions() : BigDecimal.ZERO); + + return ps; + }, keyHolder); + + if (rows == 0) { + logger.error("No se pudo crear el empleado con DNI: {}", employee.getTaxId()); + throw new BusinessException("No se pudo crear el empleado"); + } + + Map keys = keyHolder.getKeys(); + if (keys != null) { + employee.setId(((Number) keys.get("ID")).longValue()); + employee.setCreatedAt(((Timestamp) keys.get("CREATED_AT")).toLocalDateTime()); + employee.setUpdatedAt(((Timestamp) keys.get("UPDATED_AT")).toLocalDateTime()); + } + + return employee; + } catch (BusinessException e) { + logger.error(e.getMessage()); + throw e; + } catch (DataIntegrityViolationException e) { + logger.error("Violacion de constraint al crear empleado con DNI: {}", employee.getTaxId()); + throw new BusinessException("Ya existe un empleado con el RUT: " + employee.getTaxId()); + } catch (RuntimeException e) { + logger.error("Error de BD al crear empleado con DNI: {} - {}", employee.getTaxId(), e.getMessage()); + logger.error("Linea..... {}", e.getStackTrace()); + throw new BusinessException("Error al crear el empleado en la base de datos"); + } + + } + + /** + * Debido a buenas practicas no se elimina el registro + * y se procede a asignar fecha de eliminacion + */ + public boolean deleteById(Long id) { + logger.debug("Eliminando empleado con id: {} .....", id); + String sql = "UPDATE employees " + + "SET deleted_at = CURRENT_TIMESTAMP, " + + "updated_at = CURRENT_TIMESTAMP, " + + "tax_id = CONCAT(tax_id, '_deleted_', id) " + + "WHERE id = ?"; + int rows = jdbcTemplate.update(sql, id); + return rows > 0; + } + +} diff --git a/src/main/java/com/danielr/desafio/service/IEmployeeService.java b/src/main/java/com/danielr/desafio/service/IEmployeeService.java new file mode 100644 index 0000000..8cab4c9 --- /dev/null +++ b/src/main/java/com/danielr/desafio/service/IEmployeeService.java @@ -0,0 +1,15 @@ +package com.danielr.desafio.service; + +import com.danielr.desafio.dto.EmployeeRequestDTO; +import com.danielr.desafio.dto.EmployeeResponseDTO; +import com.danielr.desafio.model.Employee; + +import java.util.List; + +public interface IEmployeeService { + + List findAll(); + EmployeeResponseDTO save(EmployeeRequestDTO dto); + boolean delete(Long id); + +} diff --git a/src/main/java/com/danielr/desafio/service/impl/EmployeeServiceImpl.java b/src/main/java/com/danielr/desafio/service/impl/EmployeeServiceImpl.java new file mode 100644 index 0000000..5193891 --- /dev/null +++ b/src/main/java/com/danielr/desafio/service/impl/EmployeeServiceImpl.java @@ -0,0 +1,153 @@ +package com.danielr.desafio.service.impl; + +import com.danielr.desafio.dto.EmployeeRequestDTO; +import com.danielr.desafio.dto.EmployeeResponseDTO; +import com.danielr.desafio.exception.BusinessException; +import com.danielr.desafio.model.Employee; +import com.danielr.desafio.repository.EmployeeRepository; +import com.danielr.desafio.service.IEmployeeService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.stereotype.Service; + +import java.math.BigDecimal; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +@Service +public class EmployeeServiceImpl implements IEmployeeService { + + private static final Logger logger = LoggerFactory.getLogger(EmployeeServiceImpl.class); + private static final BigDecimal MIN_SALARY = new BigDecimal("400000"); + private static final BigDecimal MAX_BONUS = new BigDecimal("0.50"); + + private final EmployeeRepository employeeRepository; + + public EmployeeServiceImpl(EmployeeRepository employeeRepository) { + this.employeeRepository = employeeRepository; + } + + @Override + public List findAll() { + logger.debug("Obteniendo lista de empleados........"); + return employeeRepository.findAll() + .stream() + .map(this::toResponseDTO) + .collect(Collectors.toList()); + } + + @Override + public EmployeeResponseDTO save(EmployeeRequestDTO dto) { + + logger.debug("Guardando empleado: {} - {}", dto.name() + " " + dto.lastname(), dto.dni()); + + List errors = new ArrayList<>(); + + // validamos - No permitir salarios base menores a $400,000. + if (hasInvalidMinSalary(dto.salary())) { + errors.add("El salario debe ser mayor a $400.000"); + } + + // validamos - Bonos no pueden superar el 50% del salario base. + if (hasInvalidMaxBonus(dto.salary(), dto.bonus())) { + errors.add("El bono no debe ser superior al 50% del salario base"); + } + + if (hasInvalidDeductions(dto.salary(), dto.deductions())) { + errors.add("Los descuentos no pueden superar el salario base"); + } + + if (employeeRepository.existsByDni(dto.dni())) { + errors.add("Ya existe un empleado con el RUT: " + dto.dni()); + } + + if (!errors.isEmpty()) { + logger.warn("Validaciones fallidas para RUT {}: {}", dto.dni(), errors); + throw new BusinessException(errors); + } + + try { + + Employee savedEmployee = employeeRepository.save(toEntity(dto)); + logger.debug("Empleado creado exitosamente con nombre: {}", + savedEmployee.getFirstName() + " " + savedEmployee.getLastName()); + return toResponseDTO(savedEmployee); + } catch (BusinessException e) { + throw e; + } catch (DataIntegrityViolationException e) { + logger.error("Violacion de constraint al crear empleado con DNI: {}", dto.dni()); + throw new BusinessException("Ya existe un empleado con el RUT: " + dto.dni()); + } catch (RuntimeException e) { + logger.error("Error inesperado al guardar empleado con RUT: {} - {}", dto.dni(), e.getMessage()); + throw new BusinessException("Error inesperado al guardar el empleado"); + } + } + + @Override + public boolean delete(Long id) { + logger.debug("Eliminando empleado con id: {}", id); + + boolean deleted = employeeRepository.deleteById(id); + + if (!deleted) { + logger.warn("Empleado no encontrado con id: {}", id); + throw new BusinessException("Empleado no encontrado con id: " + id); + } + + logger.debug("Empleado eliminado correctamente con id: {}", id); + return deleted; + } + + private EmployeeResponseDTO toResponseDTO(Employee e) { + + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm"); + String dateCreate = e.getCreatedAt().format(formatter); + + return new EmployeeResponseDTO( + e.getId(), + e.getFirstName(), + e.getLastName(), + e.getTaxId(), + e.getPosition(), + e.getBaseSalary(), + e.getBonus(), + e.getDeductions(), + dateCreate + ); + } + + private Employee toEntity(EmployeeRequestDTO dto) { + Employee e = new Employee(); + e.setFirstName(dto.name()); + e.setLastName(dto.lastname()); + e.setTaxId(dto.dni()); + e.setPosition(dto.position()); + e.setBaseSalary(dto.salary()); + e.setBonus(dto.bonus() != null ? dto.bonus() : BigDecimal.ZERO); + e.setDeductions(dto.deductions() != null ? dto.deductions() : BigDecimal.ZERO); + return e; + } + + private boolean hasInvalidMinSalary(BigDecimal salary) { + return salary.compareTo(MIN_SALARY) < 0; + } + + private boolean hasInvalidMaxBonus(BigDecimal salary, BigDecimal bonus) { + if (bonus!=null && bonus.compareTo(BigDecimal.ZERO) > 0) { + BigDecimal limit = salary.multiply(MAX_BONUS); + return bonus.compareTo(limit) > 0; + } + return false; + } + + private boolean hasInvalidDeductions(BigDecimal salary, BigDecimal deductions) { + if (deductions!=null && deductions.compareTo(BigDecimal.ZERO) > 0) { + return deductions.compareTo(salary) > 0; + } + return false; + } + +} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties new file mode 100644 index 0000000..383afc0 --- /dev/null +++ b/src/main/resources/application.properties @@ -0,0 +1,25 @@ +spring.application.name=desafio + +# Servidor +server.port=8040 + +# H2 en memoria +spring.datasource.url=jdbc:h2:mem:desafiodb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE;INIT=RUNSCRIPT FROM 'classpath:schema.sql' +spring.datasource.driver-class-name=org.h2.Driver +spring.datasource.username=sa +spring.datasource.password= + +# Consola H2 (útil para ver los datos mientras desarrollas) +spring.h2.console.enabled=true +spring.h2.console.path=/h2-console +spring.h2.console.settings.web-allow-others=true + +# Inicialización SQL +spring.sql.init.mode=always + +# JSON con fechas legibles +spring.jackson.serialization.write-dates-as-timestamps=false + +# Logs +logging.level.org.springframework=INFO +logging.level.com.danielr.desafio=DEBUG \ No newline at end of file diff --git a/src/main/resources/schema.sql b/src/main/resources/schema.sql new file mode 100644 index 0000000..f16ef6e --- /dev/null +++ b/src/main/resources/schema.sql @@ -0,0 +1,15 @@ +DROP TABLE IF EXISTS employees; + +CREATE TABLE employees ( + id BIGINT AUTO_INCREMENT PRIMARY KEY, + first_name VARCHAR(100) NOT NULL, + last_name VARCHAR(100) NOT NULL, + tax_id VARCHAR(20) NOT NULL UNIQUE, + position VARCHAR(100) NOT NULL, + base_salary DECIMAL(15,2) NOT NULL, + bonus DECIMAL(15,2) DEFAULT 0, + deductions DECIMAL(15,2) DEFAULT 0, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + deleted_at TIMESTAMP DEFAULT NULL +); \ No newline at end of file diff --git a/src/main/resources/static/index.html b/src/main/resources/static/index.html new file mode 100644 index 0000000..4d8c069 --- /dev/null +++ b/src/main/resources/static/index.html @@ -0,0 +1,471 @@ + + + + + + Gestión de Empleados + + + + +
+ +
+

Gestión de empleados

+

Administración de personal — Desafío Técnico Previred

+
+ +
+

Agregar empleado

+ +
+ +
+
+ + + Campo requerido +
+
+ + + Campo requerido +
+
+ + + Formato inválido (ej: 12345678-9) +
+
+ + + Campo requerido +
+
+ + + El salario mínimo es $400.000 +
+
+ + + El bono no puede superar el 50% del salario +
+
+ + + Los descuentos no pueden superar el salario base +
+
+ + +
+ +
+

Lista de empleados

+
+
+ + + + + + + + + + + + + + + +
IDEmpleadoRUT / DNICargoSalarioFecha Ingreso
Cargando empleados...
+
+
+ +
+ + + + + \ No newline at end of file diff --git a/src/test/java/com/danielr/desafio/DesafioApplicationTests.java b/src/test/java/com/danielr/desafio/DesafioApplicationTests.java new file mode 100644 index 0000000..c789c4a --- /dev/null +++ b/src/test/java/com/danielr/desafio/DesafioApplicationTests.java @@ -0,0 +1,13 @@ +package com.danielr.desafio; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class DesafioApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/src/test/java/com/danielr/desafio/repository/EmployeeRepositoryTest.java b/src/test/java/com/danielr/desafio/repository/EmployeeRepositoryTest.java new file mode 100644 index 0000000..18a04ff --- /dev/null +++ b/src/test/java/com/danielr/desafio/repository/EmployeeRepositoryTest.java @@ -0,0 +1,225 @@ +package com.danielr.desafio.repository; + +import com.danielr.desafio.model.Employee; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.jdbc.JdbcTest; +import org.springframework.context.annotation.Import; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.jdbc.Sql; + +import java.math.BigDecimal; +import java.util.List; +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; + +@JdbcTest +@Import(EmployeeRepository.class) +@ActiveProfiles("test") +@Sql(scripts = "/schema.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD) +public class EmployeeRepositoryTest { + + @Autowired + private EmployeeRepository employeeRepository; + + private Employee validEmployee; + + @BeforeEach + void setUp() { + validEmployee = new Employee(); + validEmployee.setFirstName("Juan"); + validEmployee.setLastName("Pérez"); + validEmployee.setTaxId("12345678-9"); + validEmployee.setPosition("Desarrollador"); + validEmployee.setBaseSalary(new BigDecimal("800000")); + validEmployee.setBonus(new BigDecimal("100000")); + validEmployee.setDeductions(new BigDecimal("50000")); + } + + // ───────────────────────────────────────────────────────────── + // findAll + // ───────────────────────────────────────────────────────────── + + @Nested + @DisplayName("findAll") + class FindAll { + + @Test + @DisplayName("retorna lista con empleados no eliminados") + void returnsActiveEmployees() { + employeeRepository.save(validEmployee); + + List result = employeeRepository.findAll(); + + assertThat(result).hasSize(1); + assertThat(result.get(0).getFirstName()).isEqualTo("Juan"); + } + + @Test + @DisplayName("no retorna empleados eliminados logicamente") + void doesNotReturnDeletedEmployees() { + Employee saved = employeeRepository.save(validEmployee); + employeeRepository.deleteById(saved.getId()); + + List result = employeeRepository.findAll(); + + assertThat(result).isEmpty(); + } + + @Test + @DisplayName("retorna lista vacia cuando no hay empleados") + void returnsEmptyList() { + List result = employeeRepository.findAll(); + + assertThat(result).isEmpty(); + } + } + + // ───────────────────────────────────────────────────────────── + // findById + // ───────────────────────────────────────────────────────────── + + @Nested + @DisplayName("findById") + class FindById { + + @Test + @DisplayName("retorna el empleado cuando existe") + void returnsEmployeeWhenExists() { + Employee saved = employeeRepository.save(validEmployee); + + Optional result = employeeRepository.findById(saved.getId()); + + assertThat(result).isPresent(); + assertThat(result.get().getTaxId()).isEqualTo("12345678-9"); + } + + @Test + @DisplayName("retorna Optional vacio cuando no existe") + void returnsEmptyWhenNotExists() { + Optional result = employeeRepository.findById(999L); + + assertThat(result).isEmpty(); + } + + @Test + @DisplayName("no retorna empleado eliminado logicamente") + void doesNotReturnDeletedEmployee() { + Employee saved = employeeRepository.save(validEmployee); + employeeRepository.deleteById(saved.getId()); + Optional result = employeeRepository.findById(saved.getId()); + assertThat(result).isEmpty(); + } + } + + // ───────────────────────────────────────────────────────────── + // existsByDni + // ───────────────────────────────────────────────────────────── + + @Nested + @DisplayName("existsByDni") + class ExistsByDni { + + @Test + @DisplayName("retorna true cuando el RUT existe") + void returnsTrueWhenExists() { + employeeRepository.save(validEmployee); + + boolean result = employeeRepository.existsByDni("12345678-9"); + + assertThat(result).isTrue(); + } + + @Test + @DisplayName("retorna false cuando el RUT no existe") + void returnsFalseWhenNotExists() { + boolean result = employeeRepository.existsByDni("99999999-9"); + + assertThat(result).isFalse(); + } + + @Test + @DisplayName("retorna false cuando el empleado fue eliminado logicamente") + void returnsFalseWhenDeleted() { + Employee saved = employeeRepository.save(validEmployee); + employeeRepository.deleteById(saved.getId()); + + boolean result = employeeRepository.existsByDni("12345678-9"); + + assertThat(result).isFalse(); + } + } + + // ───────────────────────────────────────────────────────────── + // save + // ───────────────────────────────────────────────────────────── + + @Nested + @DisplayName("save") + class Save { + + @Test + @DisplayName("guarda el empleado y retorna con ID generado") + void savesEmployeeWithGeneratedId() { + Employee saved = employeeRepository.save(validEmployee); + + assertThat(saved.getId()).isNotNull(); + assertThat(saved.getId()).isGreaterThan(0L); + assertThat(saved.getFirstName()).isEqualTo("Juan"); + assertThat(saved.getTaxId()).isEqualTo("12345678-9"); + } + + @Test + @DisplayName("retorna con createdAt y updatedAt poblados") + void savesEmployeeWithTimestamps() { + Employee saved = employeeRepository.save(validEmployee); + + assertThat(saved.getCreatedAt()).isNotNull(); + assertThat(saved.getUpdatedAt()).isNotNull(); + } + } + + // ───────────────────────────────────────────────────────────── + // deleteById + // ───────────────────────────────────────────────────────────── + + @Nested + @DisplayName("deleteById") + class DeleteById { + + @Test + @DisplayName("retorna true cuando el empleado existe") + void returnsTrueWhenExists() { + Employee saved = employeeRepository.save(validEmployee); + + boolean result = employeeRepository.deleteById(saved.getId()); + + assertThat(result).isTrue(); + } + + @Test + @DisplayName("retorna false cuando el ID no existe") + void returnsFalseWhenNotExists() { + boolean result = employeeRepository.deleteById(999L); + + assertThat(result).isFalse(); + } + + @Test + @DisplayName("el empleado eliminado no aparece en findAll") + void deletedEmployeeNotInFindAll() { + Employee saved = employeeRepository.save(validEmployee); + employeeRepository.deleteById(saved.getId()); + + List result = employeeRepository.findAll(); + + assertThat(result).isEmpty(); + } + } + + +} diff --git a/src/test/java/com/danielr/desafio/service/EmployeeServiceImplTest.java b/src/test/java/com/danielr/desafio/service/EmployeeServiceImplTest.java new file mode 100644 index 0000000..5ec68a2 --- /dev/null +++ b/src/test/java/com/danielr/desafio/service/EmployeeServiceImplTest.java @@ -0,0 +1,323 @@ +package com.danielr.desafio.service; + +import com.danielr.desafio.dto.EmployeeRequestDTO; +import com.danielr.desafio.dto.EmployeeResponseDTO; +import com.danielr.desafio.exception.BusinessException; +import com.danielr.desafio.model.Employee; +import com.danielr.desafio.repository.EmployeeRepository; +import com.danielr.desafio.service.impl.EmployeeServiceImpl; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; +import org.springframework.test.context.TestPropertySource; + +import java.math.BigDecimal; +import java.time.LocalDateTime; +import java.util.List; + +import static org.assertj.core.api.Assertions.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +@TestPropertySource(locations = "classpath:application-test.properties") +public class EmployeeServiceImplTest { + + @Mock + private EmployeeRepository employeeRepository; + @InjectMocks + private EmployeeServiceImpl employeeService; + + private Employee employeeSave; + + private EmployeeRequestDTO dto; + + @BeforeEach + public void setUp() { + dto = new EmployeeRequestDTO( + "Juan", + "Pérez", + "12345678-9", + "Desarrollador", + new BigDecimal("800000"), + new BigDecimal("100000"), + new BigDecimal("50000") + ); + + employeeSave = new Employee(); + employeeSave.setId(1L); + employeeSave.setFirstName("Juan"); + employeeSave.setLastName("Pérez"); + employeeSave.setTaxId("12345678-9"); + employeeSave.setPosition("Desarrollador"); + employeeSave.setBaseSalary(new BigDecimal("800000")); + employeeSave.setBonus(new BigDecimal("100000")); + employeeSave.setDeductions(new BigDecimal("50000")); + employeeSave.setCreatedAt(LocalDateTime.now()); + employeeSave.setUpdatedAt(LocalDateTime.now()); + } + + /** + * findAll + */ + @Nested + @DisplayName("findAll") + class FindAll { + + @Test + @DisplayName("Retorna lista empleados correctamente") + void returnsEmpList() { + when(employeeRepository.findAll()).thenReturn(List.of(employeeSave)); + + List result = employeeService.findAll(); + + assertThat(result).hasSize(1); + assertThat(result.get(0).name()).isEqualTo("Juan"); + assertThat(result.get(0).lastname()).isEqualTo("Pérez"); + verify(employeeRepository, times(1)).findAll(); + } + + @Test + @DisplayName("retorna lista vacía sin errores") + void returnsEmptyList() { + when(employeeRepository.findAll()).thenReturn(List.of()); + + List result = employeeService.findAll(); + + assertThat(result).isEmpty(); + verify(employeeRepository, times(1)).findAll(); + } + + } + + /** + * Save + */ + @Nested + @DisplayName("save") + class Save { + + @Test + @DisplayName("empleado válido se crea correctamente") + void validEmployee_returnsDTO() { + when(employeeRepository.existsByDni(any())).thenReturn(false); + when(employeeRepository.save(any())).thenReturn(employeeSave); + + EmployeeResponseDTO result = employeeService.save(dto); + + assertThat(result).isNotNull(); + assertThat(result.name()).isEqualTo("Juan"); + assertThat(result.lastname()).isEqualTo("Pérez"); + assertThat(result.dni()).isEqualTo("12345678-9"); + verify(employeeRepository, times(1)).save(any()); + } + + @Test + @DisplayName("salario menor a $400.000 lanza BusinessException") + void lowSalary_throwsBusinessException() { + EmployeeRequestDTO request = new EmployeeRequestDTO( + "Juan", "Pérez", "12345678-9", "Desarrollador", + new BigDecimal("300000"), null, null + ); + + assertThatThrownBy(() -> employeeService.save(request)) + .isInstanceOf(BusinessException.class) + .satisfies(ex -> { + BusinessException be = (BusinessException) ex; + assertThat(be.getErrors()) + .anyMatch(e -> e.contains("400.000")); + }); + + verify(employeeRepository, never()).save(any()); + } + + @Test + @DisplayName("bono exactamente 50% del salario es válido") + void bonusExactly50Percent_isValid() { + EmployeeRequestDTO request = new EmployeeRequestDTO( + "Juan", "Pérez", "12345678-9", "Desarrollador", + new BigDecimal("800000"), + new BigDecimal("400000"), // exactamente 50% + null + ); + + when(employeeRepository.existsByDni(any())).thenReturn(false); + when(employeeRepository.save(any())).thenReturn(employeeSave); + + assertThatCode(() -> employeeService.save(request)) + .doesNotThrowAnyException(); + + verify(employeeRepository, times(1)).save(any()); + } + + @Test + @DisplayName("bono mayor al 50% del salario lanza BusinessException") + void bonusOver50Percent_throwsBusinessException() { + EmployeeRequestDTO request = new EmployeeRequestDTO( + "Juan", "Pérez", "12345678-9", "Desarrollador", + new BigDecimal("800000"), + new BigDecimal("500000"), // 500.000 > 50% de 800.000 + new BigDecimal("0") + ); + + assertThatThrownBy(() -> employeeService.save(request)) + .isInstanceOf(BusinessException.class) + .satisfies(ex -> { + BusinessException be = (BusinessException) ex; + assertThat(be.getErrors()) + .anyMatch(e -> e.contains("bono")); + }); + + verify(employeeRepository, never()).save(any()); + } + + @Test + @DisplayName("bono en cero es válido") + void zeroBonus_isValid() { + EmployeeRequestDTO request = new EmployeeRequestDTO( + "Juan", "Pérez", "12345678-9", "Desarrollador", + new BigDecimal("800000"), + BigDecimal.ZERO, + null + ); + + when(employeeRepository.existsByDni(any())).thenReturn(false); + when(employeeRepository.save(any())).thenReturn(employeeSave); + + assertThatCode(() -> employeeService.save(request)) + .doesNotThrowAnyException(); + } + + @Test + @DisplayName("descuentos igual al salario es válido") + void deductionsEqualSalary_isValid() { + EmployeeRequestDTO request = new EmployeeRequestDTO( + "Juan", "Pérez", "12345678-9", "Desarrollador", + new BigDecimal("800000"), + null, + new BigDecimal("800000") // igual al salario + ); + + when(employeeRepository.existsByDni(any())).thenReturn(false); + when(employeeRepository.save(any())).thenReturn(employeeSave); + + assertThatCode(() -> employeeService.save(request)) + .doesNotThrowAnyException(); + + verify(employeeRepository, times(1)).save(any()); + } + + @Test + @DisplayName("descuentos mayores al salario lanzan BusinessException") + void deductionsOverSalary_throwsBusinessException() { + EmployeeRequestDTO request = new EmployeeRequestDTO( + "Juan", "Pérez", "12345678-9", "Desarrollador", + new BigDecimal("800000"), + null, + new BigDecimal("900000") // 900.000 > 800.000 + ); + + assertThatThrownBy(() -> employeeService.save(request)) + .isInstanceOf(BusinessException.class) + .satisfies(ex -> { + BusinessException be = (BusinessException) ex; + assertThat(be.getErrors()) + .anyMatch(e -> e.contains("descuentos")); + }); + + verify(employeeRepository, never()).save(any()); + } + + @Test + @DisplayName("descuentos en cero son válidos") + void zeroDeductions_isValid() { + EmployeeRequestDTO request = new EmployeeRequestDTO( + "Juan", "Pérez", "12345678-9", "Desarrollador", + new BigDecimal("800000"), + null, + BigDecimal.ZERO + ); + + when(employeeRepository.existsByDni(any())).thenReturn(false); + when(employeeRepository.save(any())).thenReturn(employeeSave); + + assertThatCode(() -> employeeService.save(request)) + .doesNotThrowAnyException(); + } + + @Test + @DisplayName("RUT duplicado lanza BusinessException") + void duplicateDni_throwsBusinessException() { + when(employeeRepository.existsByDni("12345678-9")).thenReturn(true); + + assertThatThrownBy(() -> employeeService.save(dto)) + .isInstanceOf(BusinessException.class) + .satisfies(ex -> { + BusinessException be = (BusinessException) ex; + assertThat(be.getErrors()) + .anyMatch(e -> e.contains("12345678-9")); + }); + + verify(employeeRepository, never()).save(any()); + } + + @Test + @DisplayName("múltiples errores se acumulan en una sola excepción") + void multipleErrors_accumulatesAllErrors() { + EmployeeRequestDTO request = new EmployeeRequestDTO( + "Juan", "Pérez", "12.345.678-9", "Desarrollador", + new BigDecimal("300000"), // salario inválido + new BigDecimal("200000"), // bono inválido + new BigDecimal("400000") // descuentos inválidos + ); + + assertThatThrownBy(() -> employeeService.save(request)) + .isInstanceOf(BusinessException.class) + .satisfies(ex -> { + BusinessException be = (BusinessException) ex; + assertThat(be.getErrors()).hasSizeGreaterThan(1); + }); + + verify(employeeRepository, never()).save(any()); + } + } + + @Nested + @DisplayName("delete") + class Delete { + + @Test + @DisplayName("elimina empleado existente y retorna true") + void existingEmployee_returnsTrue() { + when(employeeRepository.deleteById(1L)).thenReturn(true); + + boolean result = employeeService.delete(1L); + + assertThat(result).isTrue(); + verify(employeeRepository, times(1)).deleteById(1L); + } + + @Test + @DisplayName("ID inexistente lanza BusinessException") + void nonExistingEmployee_throwsBusinessException() { + when(employeeRepository.deleteById(99L)).thenReturn(false); + + assertThatThrownBy(() -> employeeService.delete(99L)) + .isInstanceOf(BusinessException.class) + .satisfies(ex -> { + BusinessException be = (BusinessException) ex; + assertThat(be.getErrors()) + .anyMatch(e -> e.contains("99")); + }); + } + } + +} diff --git a/start.sh b/start.sh new file mode 100755 index 0000000..b4e99b3 --- /dev/null +++ b/start.sh @@ -0,0 +1,48 @@ +#!/bin/bash + +docker-compose down +echo "========================================" +echo " Desafio Tecnico - Gestion Empleados " +echo " Daniel Ivan Ramos Truitrui " +echo " Empresa " +echo "========================================" + +# Verificar que Docker esta instalado +if ! command -v docker &> /dev/null; then + echo "ERROR: Docker no esta instalado." + echo "Instala Docker desde https://www.docker.com/get-started" + exit 1 +fi + +# Verificar que Docker Compose esta instalado +if ! command -v docker-compose &> /dev/null; then + echo "ERROR: Docker Compose no esta instalado." + exit 1 +fi + +# Verificar que Docker esta corriendo +if ! docker info &> /dev/null; then + echo "ERROR: Docker no esta corriendo. Inicia Docker Desktop e intenta de nuevo." + exit 1 +fi + +echo "" +echo "Construyendo y levantando la aplicacion..." +echo "" + +docker-compose up --build -d + +echo "" +echo "Esperando que la aplicacion levante..." +sleep 10 + +echo "" +echo "========================================" +echo " Aplicacion lista!" +echo " App: http://localhost:8040" +echo " H2: http://localhost:8040/h2-console" +echo "========================================" +echo "" +echo "Para ver los logs: docker-compose logs -f" +echo "Para detener: docker-compose down" +echo "" \ No newline at end of file