commit ef3ab153e81b6ad021e8060ca92d1b0f3a98a74e Author: Aellis Tech Date: Fri Oct 23 15:29:08 2026 +0200 first commit diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..47c2760 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,6 @@ +.git +.env +.secrets +target +.idea +.tools diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..ef1277f --- /dev/null +++ b/.editorconfig @@ -0,0 +1,10 @@ +root = true +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true +indent_style = space +indent_size = 4 +[*.{yml,yaml,xml}] +indent_size = 2 diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..60b3835 --- /dev/null +++ b/.env.example @@ -0,0 +1,30 @@ +# La misma base que genesis_authv2. Este servicio NO crea ni modifica el esquema. +SERVER_PORT=8086 +DB_URL=jdbc:postgresql://localhost:5432/genesis_auth +DB_USER=genesis +DB_PASSWORD=replace-with-your-postgresql-password + +# Clave PUBLICA del auth Java. Nunca copies su clave privada a este servicio. +JWT_ALGORITHM=RS256 +JWT_PUBLIC_KEY=file:.secrets/public.pem +JWT_ISSUER=http://localhost:8080 +JWT_AUDIENCE=genesis-api +JWT_CHECK_SESSION=true +JWT_MAX_AGE=15m + +# Solo para transición con auth Node antiguo: JWT_ALGORITHM=HS256, TOKEN_SECRET y JWT_CHECK_SESSION=false. +TOKEN_SECRET= +CORS_ALLOWED_ORIGINS=http://localhost:3000 + +# Redis es opcional; sin URL se utiliza el límite local por IP. +REDIS_URL= +RATE_LIMIT_MAX=300 +RATE_LIMIT_WINDOW_MS=60000 +RATE_LIMIT_MEMORY_MAX_KEYS=10000 +RATE_LIMIT_REDIS_BACKOFF_MS=60000 +RATE_LIMIT_PREFIX=genesis-reporting:rate +REQUEST_LOG_ENABLED=true +REPORT_MAX_ROWS=100000 + +# Solo al usar Docker. localhost dentro del contenedor no es tu ordenador. +DOCKER_DB_URL=jdbc:postgresql://host.docker.internal:5432/genesis_auth diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..d66d0d2 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,6 @@ +* text=auto +mvnw text eol=lf +mvnw.cmd text eol=crlf +*.java text eol=lf +*.yml text eol=lf +*.sql text eol=lf diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..06db7a5 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,15 @@ +name: verify +on: [push, pull_request] +permissions: + contents: read +jobs: + verify: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '25' + cache: maven + - run: bash ./mvnw -B -ntp verify diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..21e929a --- /dev/null +++ b/.gitignore @@ -0,0 +1,8 @@ +/target/ +/.tools/ +/.secrets/ +/.env +/.idea/ +*.iml +*.log +.DS_Store diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..222cba3 --- /dev/null +++ b/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,4 @@ +wrapperVersion=3.3.4 +distributionType=only-script +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.11/apache-maven-3.9.11-bin.zip +distributionSha256Sum=0d7125e8c91097b36edb990ea5934e6c68b4440eef4ea96510a0f6815e7eeadb diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..736f6c3 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,13 @@ +FROM maven:3.9.11-eclipse-temurin-25 AS build +WORKDIR /build +COPY pom.xml . +COPY src src +RUN mvn -B -ntp -DskipTests package + +FROM eclipse-temurin:25-jre +WORKDIR /app +RUN groupadd --system app && useradd --system --gid app app +COPY --from=build --chown=app:app /build/target/genesis-reporting-0.0.1-SNAPSHOT.jar app.jar +USER app +EXPOSE 8086 +ENTRYPOINT ["java", "-XX:MaxRAMPercentage=75", "-jar", "/app/app.jar"] diff --git a/README.md b/README.md new file mode 100644 index 0000000..4aa5e1b --- /dev/null +++ b/README.md @@ -0,0 +1,100 @@ +# Genesis Reporting Service — Java 25 + +Migración de `genesis_reportingService` a Java 25 y Spring Boot. Incluye las 29 rutas, sus informes JSON y los ocho Excel originales, con consultas revisadas. + +## Arrancar + +Necesitas JDK 25 y la base PostgreSQL existente del Node y del auth. Desde `genesis_reportingv2`: + +```powershell +powershell -ExecutionPolicy Bypass -File .\scripts\run.ps1 +``` + +El script carga `.env` y arranca en **http://localhost:8086**. La primera ejecución necesita internet para descargar Maven y dependencias. Abre **http://localhost:8086/health** para comprobar que responde `{"ok":true}`. `/actuator/health` comprueba también PostgreSQL. Detén el proceso con `Ctrl+C`. + +El `.env` local se ha preparado con los valores compartidos del auth. Revisa el entorno de destino. Para otra instalación, copia `.env.example` como `.env` y completa la conexión. Si arrancas directamente desde el IDE o con `java -jar`, configura allí las variables de entorno: Spring no carga este `.env` por sí solo. + +No se necesitan columnas nuevas ni scripts de preparación. El servicio verifica las tablas existentes del dominio: `activities`, `cases`, `client`, `users`, `paytype`, `category`, `specialization`, `status`, `rol`, `documenttype` y la sesión del auth. Una base que solo tenga las tablas iniciales del auth no incluye todo el dominio; utiliza la base existente del Node. El esquema de `src/test/resources` es exclusivo para pruebas. + +Los informes son de solo lectura, con una instantánea consistente entre sus consultas. No se modifican importes, pagos ni tarifas históricas. No se ha modificado la base real. + +## Autenticación y permisos + +Inicia sesión en el auth Java y envía su access token: + +```http +Authorization: Bearer +``` + +La configuración predeterminada utiliza RS256 y solo la clave pública del auth en `.secrets/public.pem`; se ha copiado la actual. Nunca necesita su clave privada. Al rotar las claves, actualiza esta copia. La conexión, `JWT_ISSUER` y `JWT_AUDIENCE` deben coincidir con el entorno del auth. Se comprueban sesión `sid`, expiración, revocación, existencia del usuario y rol actual. El refresh token se utiliza solo con el auth. + +Se incluye el modo de transición HS256 de los otros servicios: selección explícita con `JWT_ALGORITHM=HS256`, `TOKEN_SECRET` de al menos 32 bytes y `JWT_CHECK_SESSION=false` si el emisor no genera `sid`. Exige issuer, audiencia, `id`, `rol`, `iat` y `exp`; pierde la validación de revocación por sesión. Las pruebas utilizan RS256. + +Todas las rutas son de admin excepto estas seis, que admiten también user: honorarios mensuales propios, horas propias por año/mes/día, Excel de mensajería propia y total de categorías propias. Para user se impone su ID aunque omita el filtro. Pedir el de otra persona devuelve 403. Los informes personales mantienen el historial de trabajo del propio usuario; no conceden acceso general a casos o clientes ni a los informes administrativos. + +## Rutas + +| Método | Ruta | +| --- | --- | +| GET | `/reporting/total/client`, `/total/case`, `/total/user`, `/total/activity` | +| GET | `/reporting/export/user`, `/export/client`, `/export/cases`, `/export/activity` | +| POST | `/reporting/calcfee/{id}`, `/fee/activity/{id}`, `/account/{id}` | +| POST | `/reporting/fee/user`, `/fee/month/user` | +| POST | `/reporting/hours/user/year/{id}`, `/hours/user/month/{id}` | +| GET | `/reporting/hours/user/day/{id}` | +| POST | `/reporting/activity/user/case`, `/bills/{id}`, `/other/bills/{id}`, `/activity/relation/{id}` | +| POST | `/reporting/export/activities`, `/hours/case/{id}` | +| POST | `/reporting/total/cases/day`, `/total/cases/month`, `/total/cases/year` | +| POST | `/reporting/total/activity/month`, `/total/activity/year` | +| POST | `/reporting/export/courier`, `/total/activity/category` | + +En la tabla, todas las rutas abreviadas de cada fila llevan también el prefijo `/reporting`. Los IDs de las rutas de horas por usuario son IDs de usuario; los demás IDs son IDs de caso. Se conservan los nombres de archivos y hojas originales. El método `exportPayments` del controller Node no estaba publicado en sus rutas; no se ha añadido un endpoint nuevo para él. + +Los informes JSON conservan `{ "data": { "data": ... }, "status": "success" }`, donde el resultado puede ser un número, objeto o lista. Los errores contienen `data.message` y `status: "error"`. Los Excel devuelven XLSX con su nombre en `Content-Disposition`, accesible mediante CORS. + +Los POST requieren un objeto JSON, aunque sea `{}`. Los filtros disponibles son `id_created`, `id_case`, `id_client`, `fecha_inicio`, `fecha_fin`, `day`, `month` y `year`, según el informe. Los desconocidos se ignoran para mantener compatibilidad. Los IDs de ruta prevalecen sobre el cuerpo. GET `/export/activity` acepta filtros por query, sin necesitar un cuerpo GET. + +Las fechas son días reales en formato `YYYY-MM-DD`, con intervalo ordenado e inclusivo. Se incluye todo el día final mediante un límite exclusivo al día siguiente. Se utiliza la zona horaria de la sesión PostgreSQL, igual que el Node: configura la misma zona entre entornos si necesitas resultados idénticos en los límites del día. Los años aceptados son 1 a 9998 y los meses 1 a 12. Los informes mensuales de honorarios y horas requieren mes y año; las horas anuales requieren año. + +## Criterios y correcciones + +Se ha unificado, por indicación del usuario, el reparto en **45% Aspen, 15% responsable de cuenta y 40% trabajo invertido**, tanto en JSON como en Excel. Los honorarios individuales suman el 40% del coste de cada actividad, incluidos los importes únicos, antes de agrupar por usuario/caso. + +El estado de cuenta calcula **cargos tipo 1 menos créditos tipo 2**. Los abonos tipo 4 no se descuentan ahí. El informe separado de gastos calcula tipo 3 menos tipo 2 y excluye los abonos. Estos libros no deben confundirse con el saldo usado por el servicio de actividades para asignar abonos a actividades pagadas. + +El coste usa `amount` cuando existe, incluso si vale cero; si falta, usa `hours × rate` con la tarifa guardada en la actividad. Nunca se sustituye por la tarifa actual del usuario. Si faltan datos, los totales monetarios afectados son NULL y los agregados exponen `pending_cost_count`; en Excel se muestra «Pendiente de revisar». No debe interpretarse como cero ni rellenarse con una tarifa actual sin evidencia histórica. + +También se han corregido la sintaxis de agregados de gastos, sus totales de Excel, los nombres de columnas duplicados, los registros omitidos por relaciones opcionales, el agrupamiento de honorarios por tarifas distintas y el control de acceso a informes personales. Consulta [query-review.md](docs/query-review.md) para los detalles y ejemplos. + +Se mantienen los criterios distintos de los contadores: los totales generales cuentan estados activos; las gráficas de casos cuentan creaciones históricas de todos los estados. El contador general de actividades y el conteo por usuario/caso incluyen todos los tipos activos; las gráficas de trabajo por mes/año y las horas usan solo tipo 1. Mensajería/categorías mantienen el criterio de categoría no nula. + +## Seguridad, límites y organización + +Se incluyen consultas parametrizadas, CORS con orígenes explícitos, cabeceras de seguridad, request ID, cuerpo máximo de 1 MiB y límite de peticiones por IP. Redis es opcional para compartir ese límite; si falla se usa memoria local. No se confía automáticamente en cabeceras de proxy. + +`REPORT_MAX_ROWS=100000` limita los detalles y exportaciones; superar el límite devuelve 422 para reducir filtros, sin entregar un informe truncado. Los totales agregan todas las filas que cumplan los filtros, no un subconjunto. Las consultas tienen timeout de 30 segundos y lectura por lotes. Los Excel se generan con [Apache POI 6.0.0](https://poi.apache.org/) y hojas con almacenamiento temporal; los textos se escriben como texto, no como fórmulas. Los números de Excel tienen sus límites habituales de precisión; los cálculos PostgreSQL utilizan decimales sobre las columnas existentes. + +`api/ReportingController.java` recibe las peticiones; `ReportingDtos.java` define rutas y valida filtros; `repository/ReportingRepository.java` contiene las consultas; `service/ReportingService.java` aplica permisos y prepara resultados; `ExcelExportService.java` genera los archivos. `config/` mantiene JWT, CORS y límites. No se han trasladado dependencias de correo, contraseñas o sockets que no utilizaban las rutas. + +## Verificación y Docker + +```powershell +powershell -ExecutionPolicy Bypass -File .\scripts\run.ps1 -Verify +``` + +Las pruebas necesitan Docker para levantar PostgreSQL 18 con Testcontainers. Como alternativa define `TEST_DB_URL`, `TEST_DB_USER` y `TEST_DB_PASSWORD` de una base de pruebas: se crea y elimina un esquema temporal exclusivo. No uses producción. + +Las 25 pruebas de integración ejecutan las 29 rutas, abren los ocho Excel y verifican importes, porcentajes, gastos, fechas, filtros, costes desconocidos, relaciones opcionales, permisos, JWT y límites. Se han ejecutado con Java 25 y PostgreSQL aislado. No se han utilizado datos reales ni probado un servidor Redis real. + +Se incluyen Maven Wrapper, CI, Dockerfile y Compose. Para Docker configura `DOCKER_DB_URL` accesible desde el contenedor y conserva la clave pública disponible: + +```powershell +docker compose up --build -d +``` + +No se levanta otra base ni se aplican migraciones. El contenedor usa un usuario sin privilegios. `.env`, `.secrets` y artefactos locales están excluidos del control de versiones y del contexto de construcción. + + +## Historial de negocio + +Las operaciones de escritura generan eventos transaccionales. La consulta de administradores se realiza en Reporting mediante `GET /reporting/audit`. Antes de desplegar, instala el esquema del historial desde Auth. Consulta [activacion, API y contrato](../genesis_authv2/docs/business-audit.md). diff --git a/compose.yml b/compose.yml new file mode 100644 index 0000000..d6682b2 --- /dev/null +++ b/compose.yml @@ -0,0 +1,34 @@ +services: + reporting: + build: . + ports: + - "127.0.0.1:${SERVER_PORT:-8086}:8086" + environment: + SERVER_PORT: 8086 + DB_URL: ${DOCKER_DB_URL:?Define DOCKER_DB_URL para PostgreSQL accesible desde Docker} + DB_USER: ${DB_USER:-genesis} + DB_PASSWORD: ${DB_PASSWORD:?Define DB_PASSWORD} + JWT_ALGORITHM: ${JWT_ALGORITHM:-RS256} + JWT_PUBLIC_KEY: file:/run/keys/public.pem + TOKEN_SECRET: ${TOKEN_SECRET:-} + JWT_ISSUER: ${JWT_ISSUER:-http://localhost:8080} + JWT_AUDIENCE: ${JWT_AUDIENCE:-genesis-api} + JWT_CHECK_SESSION: ${JWT_CHECK_SESSION:-true} + JWT_MAX_AGE: ${JWT_MAX_AGE:-15m} + CORS_ALLOWED_ORIGINS: ${CORS_ALLOWED_ORIGINS:-http://localhost:3000} + REDIS_URL: ${REDIS_URL:-} + RATE_LIMIT_MAX: ${RATE_LIMIT_MAX:-300} + RATE_LIMIT_WINDOW_MS: ${RATE_LIMIT_WINDOW_MS:-60000} + RATE_LIMIT_MEMORY_MAX_KEYS: ${RATE_LIMIT_MEMORY_MAX_KEYS:-10000} + RATE_LIMIT_REDIS_BACKOFF_MS: ${RATE_LIMIT_REDIS_BACKOFF_MS:-60000} + RATE_LIMIT_PREFIX: ${RATE_LIMIT_PREFIX:-genesis-reporting:rate} + REQUEST_LOG_ENABLED: ${REQUEST_LOG_ENABLED:-true} + REPORT_MAX_ROWS: ${REPORT_MAX_ROWS:-100000} + volumes: + - ./.secrets:/run/keys:ro + read_only: true + tmpfs: + - /tmp:size=64m + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + restart: unless-stopped diff --git a/docs/query-review.md b/docs/query-review.md new file mode 100644 index 0000000..420dc0c --- /dev/null +++ b/docs/query-review.md @@ -0,0 +1,52 @@ +# Revisión de las consultas de reporting + +Migración revisada el 23 de octubre de 2026. Se han ejecutado las consultas contra PostgreSQL aislado y se han abierto los archivos XLSX producidos. No se ha modificado el esquema ni los datos reales. + +## Errores corregidos + +| Área | Problema en Node | Resultado en Java | +| --- | --- | --- | +| Tarifas | `COALESCE(a.rate,u.rate)` reconstruía facturas con la tarifa actual. | Solo se usa el importe o la tarifa histórica de la actividad. | +| Costes incompletos | SUM omitía importes NULL y podía mostrar un total aparentemente completo. | El total afectado es NULL; los agregados indican `pending_cost_count` y el Excel marca revisión pendiente. | +| Honorarios | Se agrupaba por tarifa y se multiplicaban horas agregadas, generando varias filas por usuario y omitiendo importes únicos. | Se calcula el coste de cada fila y se suma antes de agrupar; el porcentaje individual es 40%. | +| Porcentajes | Excel de facturación 50/20/30 y resto 45/15/40; algunos subtotales usaban 30%. | Todos utilizan 45/15/40 por indicación expresa del usuario. | +| Gastos | `COALESCE(SUM(...) FILTER(...),0) OVER()` aplicaba OVER a una expresión que no es una función de ventana válida. | Se usa una CTE con las filas filtradas y otra con sus agregados. | +| Descripciones | Se seleccionaban dos columnas llamadas `description`; el objeto del driver podía sobrescribir una. | `case_description` identifica el caso y `description` la actividad. | +| Pie de gastos Excel | `debe`, `haber` y `total` se inicializaban a cero y nunca se acumulaban. | El pie usa los agregados reales de exactamente las filas filtradas. | +| Tipos en gastos | Se incluían todos los tipos distintos de 1, aunque los abonos no se colocaban en Debe/Haber. | El libro de gastos incluye tipo 3 y tipo 2; los abonos tipo 4 quedan fuera. | +| Usuarios exportados | INNER JOIN a especialización omitía usuarios con especialización opcional NULL. | LEFT JOIN conserva esos usuarios activos. | +| Clientes exportados | INNER JOIN al recomendador omitía clientes válidos sin recomendador. | LEFT JOIN conserva esos clientes activos. | +| Importes históricos | INNER JOIN al creador eliminaba movimientos con usuario ausente. | LEFT JOIN conserva el movimiento y su coste; no se pierde dinero por faltar metadatos. | +| Exportación de casos | Un cliente opcional ausente podía ocultar el caso. | Se conserva el caso, dejando el nombre de cliente vacío. | +| GET export/activity | Se accedía a `req.body` en un GET que normalmente no trae cuerpo. | Admite query y, por compatibilidad, cuerpo JSON opcional. | +| Seguridad | User podía omitir `id_created` o elegir otro usuario en informes personales. | Se impone el ID autenticado y se rechazan consultas ajenas con 403. | +| Filtros | Se aceptaba cualquier cuerpo sin validar fechas, años ni IDs. | Se validan días reales, orden del intervalo, períodos e IDs positivos. | +| Agregados | Contadores forzados a INTEGER podían desbordar antes que COUNT de PostgreSQL. | Se conserva el contador BIGINT. | +| Consistencia | Factura, reparto y honorarios se leían mediante consultas separadas sin snapshot común. | Una transacción de solo lectura REPEATABLE READ mantiene la misma instantánea. | + +## Criterios confirmados, no errores + +- El estado de cuenta resta **créditos tipo 2** de cargos tipo 1. No se ha cambiado a abonos tipo 4: el usuario confirmó que son libros distintos. +- Los porcentajes se han unificado a 45/15/40 por decisión del usuario; no se ha elegido un reparto por suposición. +- Los totales generales cuentan registros activos. Las gráficas de casos describen creaciones históricas de todos los estados. Se conservan ambos significados. +- El total general de actividades y el conteo por usuario/caso incluyen movimientos de todos los tipos activos. Las horas y gráficas de trabajo por usuario/mes/año se limitan al tipo 1. +- Los informes personales pertenecen al creador de la actividad. No requieren poder administrar el caso ni permiten consultar el trabajo de otras personas. +- Los informes no escriben en `payment` ni distribuyen abonos: esa operación corresponde a `genesis_activityv2`. + +## Ejemplos verificados + +1. Dos horas a 10, una hora a 20 y un importe único de 60 suman 100, aunque la tarifa actual del usuario sea 999 o cambie a 5000. El reparto es 45, 15 y 40; el honorario individual acumulado es 40, en una única fila por usuario/caso. +2. Cargos de 100, créditos tipo 2 de 10, gastos de 25 y abonos de 200 producen estado de cuenta 90. El informe separado de gastos produce Debe 25, Haber 10 y Total 15. No se mezclan ambos libros. +3. El Excel de gastos presenta 25/10/15 en su pie, no 0/0/0. El de facturación incluye 45/15/40 y honorarios 40. El reporte de actividades incluye el importe único en el subtotal del 40%. +4. Un registro a las 23:59:59.999999 del día final se incluye; uno a las 00:00 del día siguiente se excluye. Las pruebas fijan UTC para que esta comprobación sea reproducible; producción utiliza la zona de la sesión PostgreSQL. +5. Una actividad sin tarifa histórica ni importe no toma la tarifa actual del usuario. El resultado monetario afectado queda pendiente, tanto en JSON como en Excel. +6. User no puede obtener los honorarios, horas o mensajería de otra persona. Omitir el ID consulta solo sus propios datos, nunca todos los usuarios. +7. Las exportaciones conservan usuarios sin especialización y clientes sin recomendador, sin incluir contraseñas o reset tokens. +8. Un texto que empieza por `=` queda como una celda STRING, no como una fórmula ejecutable. +9. Si un detalle supera el límite configurado, se devuelve 422. Los agregados siguen contando todas las filas coincidentes y no se calculan sobre un detalle recortado. + +## Alcance + +Hay 25 pruebas de integración que cubren las 29 rutas y abren los ocho tipos de Excel. El controller Node también tenía una función de exportación de abonos sin ruta registrada; no se ha publicado una ruta nueva para ella. + +Se utilizan las tablas originales sin migraciones de esquema. Los importes existentes permanecen en sus columnas DOUBLE PRECISION; las operaciones SQL usan NUMERIC para sumar y repartir. Esto no recupera precisión ya perdida ni permite deducir tarifas históricas ausentes. Esos registros requieren su fuente original, como en el servicio de actividades. diff --git a/mvnw b/mvnw new file mode 100644 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..88d2758 --- /dev/null +++ b/pom.xml @@ -0,0 +1,28 @@ + + + 4.0.0 + org.springframework.bootspring-boot-starter-parent4.0.8 + com.aellisgenesis-reporting0.0.1-SNAPSHOT + Genesis Reporting Service + 25 + + org.apache.poipoi-ooxml6.0.0 + org.springframework.bootspring-boot-starter-webmvc + org.springframework.bootspring-boot-starter-security + org.springframework.bootspring-boot-starter-oauth2-resource-server + org.springframework.bootspring-boot-starter-jdbc + org.springframework.bootspring-boot-starter-validation + org.springframework.bootspring-boot-starter-data-redis + org.springframework.bootspring-boot-starter-actuator + org.postgresqlpostgresqlruntime + org.springframework.bootspring-boot-starter-testtest + org.springframework.securityspring-security-testtest + org.testcontainerstestcontainers-postgresqltest + org.testcontainerstestcontainers-junit-jupitertest + + + org.springframework.bootspring-boot-maven-plugin + org.apache.maven.pluginsmaven-failsafe-pluginintegration-testverify + org.apache.maven.pluginsmaven-enforcer-plugin3.6.2enforce[25,26) + + diff --git a/scripts/run.ps1 b/scripts/run.ps1 new file mode 100644 index 0000000..cda3342 --- /dev/null +++ b/scripts/run.ps1 @@ -0,0 +1,33 @@ +param([switch]$Verify) +$ErrorActionPreference = 'Stop' +$projectRoot = Split-Path -Parent $PSScriptRoot +Set-Location -LiteralPath $projectRoot + +if (Test-Path -LiteralPath '.env') { + foreach ($line in [System.IO.File]::ReadAllLines((Join-Path $projectRoot '.env'), [System.Text.Encoding]::UTF8)) { + if ($line -match '^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=(.*)$') { + $settingName = $Matches[1] + $settingValue = $Matches[2].Trim() + if ($settingValue.Length -ge 2) { + if (($settingValue.StartsWith('"') -and $settingValue.EndsWith('"')) -or + ($settingValue.StartsWith("'") -and $settingValue.EndsWith("'"))) { + $settingValue = $settingValue.Substring(1, $settingValue.Length - 2) + } + } + [Environment]::SetEnvironmentVariable($settingName, $settingValue, 'Process') + } + } +} else { + Write-Host 'No existe .env. Se usarán las variables del proceso; consulta .env.example.' +} + +if (!(Get-Command java -ErrorAction SilentlyContinue)) { + if ($env:JAVA_HOME -and (Test-Path -LiteralPath (Join-Path $env:JAVA_HOME 'bin/java.exe'))) { + $env:PATH = "$env:JAVA_HOME\bin;$env:PATH" + } else { + throw 'No se encuentra Java. Instala JDK 25 o configura JAVA_HOME.' + } +} +if ($Verify) { & (Join-Path $projectRoot 'mvnw.cmd') verify } +else { & (Join-Path $projectRoot 'mvnw.cmd') spring-boot:run } +exit $LASTEXITCODE diff --git a/src/main/java/com/aellis/reporting/ReportingApplication.java b/src/main/java/com/aellis/reporting/ReportingApplication.java new file mode 100644 index 0000000..fbafc28 --- /dev/null +++ b/src/main/java/com/aellis/reporting/ReportingApplication.java @@ -0,0 +1,22 @@ +package com.aellis.reporting; + +import org.springframework.boot.*; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.context.properties.ConfigurationPropertiesScan; +import org.springframework.context.annotation.Bean; +import org.springframework.jdbc.core.simple.JdbcClient; + +@SpringBootApplication +@ConfigurationPropertiesScan +public class ReportingApplication { + public static void main(String[] args) { SpringApplication.run(ReportingApplication.class,args); } + @Bean ApplicationRunner verifyDatabase(JdbcClient jdbc) { + return args -> { + jdbc.sql("SELECT id,description,hours,rate,amount,payment,created,id_created,id_status,id_paytype,id_case,id_category FROM activities WHERE FALSE").query().listOfRows(); + jdbc.sql("SELECT id,name,description,created,id_status,id_client FROM cases WHERE FALSE").query().listOfRows(); + jdbc.sql("SELECT id,identdocument,businessname,description,created,id_status,id_recomended,id_documenttype FROM client WHERE FALSE").query().listOfRows(); + jdbc.sql("SELECT id,name,lastname,email,acronym,rate,id_status,id_rol,id_specialization FROM users WHERE FALSE").query().listOfRows(); + for(String table:java.util.List.of("category","paytype","specialization","rol","status","documenttype")) jdbc.sql("SELECT id,name FROM "+table+" WHERE FALSE").query().listOfRows(); + }; + } +} diff --git a/src/main/java/com/aellis/reporting/api/ApiException.java b/src/main/java/com/aellis/reporting/api/ApiException.java new file mode 100644 index 0000000..aacecb3 --- /dev/null +++ b/src/main/java/com/aellis/reporting/api/ApiException.java @@ -0,0 +1,7 @@ +package com.aellis.reporting.api; + +public class ApiException extends RuntimeException { + private final int status; + public ApiException(int status, String message) { super(message); this.status = status; } + public int status() { return status; } +} diff --git a/src/main/java/com/aellis/reporting/api/ApiExceptionHandler.java b/src/main/java/com/aellis/reporting/api/ApiExceptionHandler.java new file mode 100644 index 0000000..dc3c1e1 --- /dev/null +++ b/src/main/java/com/aellis/reporting/api/ApiExceptionHandler.java @@ -0,0 +1,35 @@ +package com.aellis.reporting.api; + +import com.aellis.reporting.api.ReportingDtos.ApiResponse; +import org.slf4j.LoggerFactory; +import org.springframework.dao.*; +import org.springframework.http.ResponseEntity; +import org.springframework.http.converter.HttpMessageNotReadableException; +import org.springframework.web.bind.annotation.*; + +@RestControllerAdvice +public class ApiExceptionHandler { + @ExceptionHandler(ApiException.class) ResponseEntity application(ApiException error) { + return ResponseEntity.status(error.status()).body(ApiResponse.fail(error.getMessage())); + } + @ExceptionHandler(DuplicateKeyException.class) ResponseEntity duplicate() { return ResponseEntity.status(409).body(ApiResponse.fail("Conflict.")); } + @ExceptionHandler(DataIntegrityViolationException.class) ResponseEntity constraint(DataIntegrityViolationException error) { + for(Throwable cause=error;cause!=null;cause=cause.getCause()) { + if(cause instanceof java.sql.SQLException sql && sql.getSQLState()!=null && sql.getSQLState().startsWith("22")) + return ResponseEntity.badRequest().body(ApiResponse.fail("Invalid data.")); + } + return ResponseEntity.status(409).body(ApiResponse.fail("La operación entra en conflicto con datos relacionados.")); + } + @ExceptionHandler(HttpMessageNotReadableException.class) ResponseEntity invalid(HttpMessageNotReadableException error) { + for (Throwable cause = error; cause != null; cause = cause.getCause()) { + if (cause instanceof com.aellis.reporting.config.RequestFilter.BodyTooLargeException) return ResponseEntity.status(413).body(ApiResponse.fail("Request body too large.")); + } + return ResponseEntity.badRequest().body(ApiResponse.fail("Invalid request.")); + } + @ExceptionHandler(Exception.class) ResponseEntity unexpected(Exception error) { + if (error instanceof org.springframework.web.ErrorResponse response) return ResponseEntity.status(response.getStatusCode()) + .headers(response.getHeaders()).body(ApiResponse.fail("Invalid request.")); + LoggerFactory.getLogger(getClass()).error("reporting_service_error type={}", error.getClass().getSimpleName()); + return ResponseEntity.internalServerError().body(ApiResponse.fail("Internal server error.")); + } +} diff --git a/src/main/java/com/aellis/reporting/api/HealthController.java b/src/main/java/com/aellis/reporting/api/HealthController.java new file mode 100644 index 0000000..18ba11b --- /dev/null +++ b/src/main/java/com/aellis/reporting/api/HealthController.java @@ -0,0 +1,9 @@ +package com.aellis.reporting.api; + +import java.util.Map; +import org.springframework.web.bind.annotation.*; + +@RestController +public class HealthController { + @GetMapping("/health") public Map health() { return Map.of("ok", true); } +} diff --git a/src/main/java/com/aellis/reporting/api/ReportingController.java b/src/main/java/com/aellis/reporting/api/ReportingController.java new file mode 100644 index 0000000..45f8e56 --- /dev/null +++ b/src/main/java/com/aellis/reporting/api/ReportingController.java @@ -0,0 +1,32 @@ +package com.aellis.reporting.api; + +import com.aellis.reporting.api.ReportingDtos.*; +import com.aellis.reporting.service.ReportingService; +import com.aellis.reporting.service.ExcelExportService.Download; +import jakarta.servlet.http.HttpServletRequest; +import java.io.IOException; +import java.util.*; +import org.springframework.http.*; +import org.springframework.security.core.annotation.AuthenticationPrincipal; +import org.springframework.security.oauth2.jwt.Jwt; +import org.springframework.web.bind.annotation.*; + +@RestController +public class ReportingController { + private final ReportingService reports; + public ReportingController(ReportingService reports) { this.reports=reports; } + @RequestMapping(value="/reporting/**",method={RequestMethod.GET,RequestMethod.POST}) + public Object report(@AuthenticationPrincipal Jwt jwt,HttpServletRequest request,@RequestBody(required=false) Payload body,@RequestParam Map query) throws IOException { + var route=ReportingDtos.route(request.getMethod(),request.getServletPath().substring("/reporting".length())); + if(request.getMethod().equals("POST") && body==null) throw ReportingDtos.invalid(); + Map fields=new LinkedHashMap<>(); if(body!=null) fields.putAll(body); + if(request.getMethod().equals("GET")) fields.putAll(query); + var who=new Requester(Integer.parseInt(jwt.getClaimAsString("id")),jwt.getClaimAsString("rol")); + Object value=reports.execute(who,route,ReportingDtos.filters(fields)); + if(value instanceof Download download) return ResponseEntity.ok() + .contentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")) + .header(HttpHeaders.CONTENT_DISPOSITION,ContentDisposition.attachment().filename(download.filename()).build().toString()) + .body(download.content()); + return ApiResponse.ok(ReportingDtos.row("data",value)); + } +} diff --git a/src/main/java/com/aellis/reporting/api/ReportingDtos.java b/src/main/java/com/aellis/reporting/api/ReportingDtos.java new file mode 100644 index 0000000..447544a --- /dev/null +++ b/src/main/java/com/aellis/reporting/api/ReportingDtos.java @@ -0,0 +1,83 @@ +package com.aellis.reporting.api; + +import java.time.*; +import java.time.format.DateTimeParseException; +import java.util.*; + +public final class ReportingDtos { + private ReportingDtos() {} + public record ApiResponse(T data,String status) { + public static ApiResponse ok(T data) { return new ApiResponse<>(data,"success"); } + public static ApiResponse fail(String message) { return new ApiResponse<>(new Message(message),"error"); } + } + public record Message(String message) {} + public record Requester(int id,String role) { public boolean admin() { return "admin".equals(role); } } + public static class Payload extends LinkedHashMap { + @Override public String toString() { return "[report filters redacted]"; } + } + public record Filters(Integer user,Integer caseId,Integer client,LocalDate from,LocalDate to,Integer day,Integer month,Integer year) { + public Filters user(Integer id) { return new Filters(id,caseId,client,from,to,day,month,year); } + public Filters caseId(Integer id) { return new Filters(user,id,client,from,to,day,month,year); } + public void requirePeriod(boolean monthly) { if(year==null || (monthly && month==null)) throw invalid(); } + } + public enum Report { + TOTAL_CLIENT("GET","/total/client"),TOTAL_CASE("GET","/total/case"),TOTAL_USER("GET","/total/user"),TOTAL_ACTIVITY("GET","/total/activity"), + USERS("GET","/export/user"),CLIENTS("GET","/export/client"),CASES("GET","/export/cases"),ACTIVITIES("GET","/export/activity"), + FEES("POST","/calcfee/{id}"),FEE_ACTIVITY("POST","/fee/activity/{id}"),ACCOUNT("POST","/account/{id}"),USER_FEES("POST","/fee/user"), + MONTH_FEES("POST","/fee/month/user",true),HOURS_YEAR("POST","/hours/user/year/{id}",true),HOURS_MONTH("POST","/hours/user/month/{id}",true),HOURS_DAY("GET","/hours/user/day/{id}",true), + USER_CASE("POST","/activity/user/case"),BILLS("POST","/bills/{id}"),OTHER_BILLS("POST","/other/bills/{id}"),RELATIONS("POST","/activity/relation/{id}"), + REPORT_ACTIVITIES("POST","/export/activities"),HOURS_CASE("POST","/hours/case/{id}"), + CASES_DAY("POST","/total/cases/day"),CASES_MONTH("POST","/total/cases/month"),CASES_YEAR("POST","/total/cases/year"), + ACTIVITY_MONTH("POST","/total/activity/month"),ACTIVITY_YEAR("POST","/total/activity/year"), + COURIER("POST","/export/courier",true),CATEGORY_TOTAL("POST","/total/activity/category",true); + public final String method,path; public final boolean personal; + Report(String method,String path) { this(method,path,false); } + Report(String method,String path,boolean personal) { this.method=method; this.path=path; this.personal=personal; } + } + public record Route(Report report,Integer id) {} + public static Route route(String method,String path) { + for(var report:Report.values()) { + if(!report.method.equals(method)) continue; + if(report.path.equals(path)) return new Route(report,null); + if(report.path.endsWith("/{id}")) { + String prefix=report.path.substring(0,report.path.length()-4); + if(path.startsWith(prefix)) { + String raw=path.substring(prefix.length()); + if(!raw.isEmpty() && !raw.contains("/")) return new Route(report,positiveId(raw)); + } + } + } + throw new ApiException(404,"Not found."); + } + public static Filters filters(Map body) { + var from=date(body.get("fecha_inicio")); var to=date(body.get("fecha_fin")); + if(from!=null && to!=null && from.isAfter(to)) throw invalid(); + Integer day=optional(body,"day",31),month=optional(body,"month",12),year=optional(body,"year",9998); + try { + if(month!=null && day!=null) { + if(year==null) MonthDay.of(month,day); else LocalDate.of(year,month,day); + } + } catch(DateTimeException exception) { throw invalid(); } + return new Filters(optional(body,"id_created",Integer.MAX_VALUE),optional(body,"id_case",Integer.MAX_VALUE),optional(body,"id_client",Integer.MAX_VALUE),from,to,day,month,year); + } + private static Integer optional(Map body,String field,int max) { + Object value=body.get(field); if(value==null || "".equals(value)) return null; + int number=positiveId(value); if(number>max) throw invalid(); return number; + } + private static LocalDate date(Object raw) { + if(raw==null || "".equals(raw)) return null; + if(!(raw instanceof String value) || !value.matches("\\d{4}-\\d{2}-\\d{2}")) throw invalid(); + try { var date=LocalDate.parse(value); if(date.getYear()<1 || date.getYear()>9998) throw invalid(); return date; } + catch(DateTimeParseException exception) { throw invalid(); } + } + public static int positiveId(Object raw) { + try { + double n=raw instanceof Number number?number.doubleValue():raw instanceof String s?Double.parseDouble(s.strip()):Double.NaN; + if(!Double.isFinite(n) || n<=0 || n>Integer.MAX_VALUE || n!=Math.rint(n)) throw invalid(); return (int)n; + } catch(NumberFormatException exception) { throw invalid(); } + } + public static Map row(Object... pairs) { + var result=new LinkedHashMap(); for(int i=0;i list(@AuthenticationPrincipal Jwt jwt,@RequestParam Map query) { + if(!"admin".equals(jwt.getClaimAsString("rol"))) throw new ApiException(403,"Forbidden"); + var supported=Set.of("entityType","entityId","caseId","actorId","action","operationId","from","to","beforeId","limit"); + if(!supported.containsAll(query.keySet())) throw invalid(); + var parameters=new LinkedHashMap(); + StringBuilder sql=new StringBuilder("SELECT id,occurred_at,service,action,entity_type,entity_id,actor_id,actor_name,case_id,before_values::text,after_values::text,reason,operation_id,request_id,format_version FROM business_audit_events WHERE TRUE"); + for(var entry:Map.of("entityType","entity_type","entityId","entity_id","caseId","case_id","actorId","actor_id","action","action","operationId","operation_id","beforeId","id","from","occurred_at","to","occurred_at").entrySet()) { + String key=entry.getKey(); + if(!query.containsKey(key)) continue; + String value=query.get(key); Object parsed; + try { + parsed=switch(key) { + case "entityId","caseId","actorId","beforeId" -> positive(value); + case "operationId" -> { var uuid=UUID.fromString(value); if(!uuid.toString().equalsIgnoreCase(value)) throw invalid(); yield uuid; } + case "from","to" -> OffsetDateTime.parse(value).withOffsetSameInstant(ZoneOffset.UTC); + default -> { if(value.isBlank() || value.length()>80) throw invalid(); yield value; } + }; + } catch(IllegalArgumentException | java.time.format.DateTimeParseException e) { throw invalid(); } + parameters.put(key,parsed); + sql.append(" AND ").append(entry.getValue()).append(switch(key) { case "beforeId","to" -> "<"; case "from" -> ">="; default -> "="; }).append(":").append(key); + } + if(parameters.get("from") instanceof OffsetDateTime start && parameters.get("to") instanceof OffsetDateTime end && !start.isBefore(end)) throw invalid(); + long requested=query.containsKey("limit")?positive(query.get("limit")):50; + if(requested>100) throw invalid(); + int limit=(int)requested; + parameters.put("limit",limit+1); + var rows=jdbc.sql(sql+" ORDER BY id DESC LIMIT :limit").params(parameters).query((rs,row)-> { + var event=new LinkedHashMap(); + event.put("id",rs.getLong("id")); event.put("occurredAt",rs.getTimestamp("occurred_at").toInstant()); + event.put("service",rs.getString("service")); event.put("action",rs.getString("action")); + event.put("entityType",rs.getString("entity_type")); event.put("entityId",rs.getLong("entity_id")); + event.put("actorId",rs.getLong("actor_id")); event.put("actorName",rs.getString("actor_name")); + event.put("caseId",rs.getObject("case_id")); event.put("before",json.readTree(rs.getString("before_values"))); + event.put("after",json.readTree(rs.getString("after_values"))); event.put("reason",rs.getString("reason")); + event.put("operationId",rs.getObject("operation_id")); event.put("requestId",rs.getString("request_id")); + event.put("formatVersion",rs.getInt("format_version")); return event; + }).list(); + boolean more=rows.size()>limit; + var events=more?rows.subList(0,limit):rows; + var data=new LinkedHashMap(); + data.put("events",events); data.put("nextCursor",more?events.getLast().get("id"):null); + return ApiResponse.ok(data); + } + private static long positive(String value) { + try { + if(!value.matches("[1-9][0-9]*")) throw invalid(); + return Long.parseLong(value); + } catch(NumberFormatException e) { throw invalid(); } + } + private static ApiException invalid() { return new ApiException(400,"Invalid audit filters."); } +} diff --git a/src/main/java/com/aellis/reporting/audit/AuditReasonValidation.java b/src/main/java/com/aellis/reporting/audit/AuditReasonValidation.java new file mode 100644 index 0000000..e918e29 --- /dev/null +++ b/src/main/java/com/aellis/reporting/audit/AuditReasonValidation.java @@ -0,0 +1,23 @@ +package com.aellis.reporting.audit; + +import com.aellis.reporting.api.ApiException; +import jakarta.servlet.http.*; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.HandlerInterceptor; +import org.springframework.web.servlet.config.annotation.*; + +@Configuration +public class AuditReasonValidation implements WebMvcConfigurer { + @Override public void addInterceptors(InterceptorRegistry registry) { + registry.addInterceptor(new HandlerInterceptor() { + @Override public boolean preHandle(HttpServletRequest request,HttpServletResponse response,Object handler) { + var headers=request.getHeaders("X-Audit-Reason"); + if(!headers.hasMoreElements()) return true; + String reason=headers.nextElement(); + if(headers.hasMoreElements() || reason.length()>500 || reason.codePoints().anyMatch(Character::isISOControl)) + throw new ApiException(400,"X-Audit-Reason debe tener como maximo 500 caracteres y no contener caracteres de control."); + return true; + } + }); + } +} diff --git a/src/main/java/com/aellis/reporting/audit/BusinessAudit.java b/src/main/java/com/aellis/reporting/audit/BusinessAudit.java new file mode 100644 index 0000000..55e26e8 --- /dev/null +++ b/src/main/java/com/aellis/reporting/audit/BusinessAudit.java @@ -0,0 +1,112 @@ +package com.aellis.reporting.audit; + +import java.math.BigDecimal; +import java.util.*; +import jakarta.servlet.http.HttpServletRequest; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.jdbc.core.simple.JdbcClient; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.oauth2.jwt.Jwt; +import org.springframework.stereotype.Component; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.web.context.request.*; +import tools.jackson.databind.json.JsonMapper; + +/** Contract v1: allowlisted persisted values, atomic with the business transaction. */ +@Component +public class BusinessAudit implements ApplicationRunner { + public record Context(long actorId, String actorName, UUID operationId, String requestId, String reason) {} + private static final Map> FIELDS = Map.of( + "cases", List.of("name","description","id_client","id_status","id_created"), + "activities", List.of("description","hours","rate","amount","payment","id_case","id_category","id_paytype","id_status","id_created"), + "client", List.of("identdocument","businessname","description","id_recomended","id_documenttype","id_status"), + "users", List.of("name","lastname","email","rate","acronym","id_specialization","id_rol","id_status"), + "specialization", List.of("name")); + private final JdbcClient jdbc; + private final JsonMapper json; + public BusinessAudit(JdbcClient jdbc, JsonMapper json) { this.jdbc=jdbc; this.json=json; } + @Override public void run(ApplicationArguments args) { + try { + jdbc.sql("SELECT id,occurred_at,service,action,entity_type,entity_id,actor_id,actor_name,case_id,before_values,after_values,reason,operation_id,request_id,format_version FROM business_audit_events WHERE FALSE").query().listOfRows(); + } catch (RuntimeException e) { throw new IllegalStateException("Falta el esquema de historial de negocio. Aplica business-audit-schema.sql o la migracion de Auth antes de arrancar.", e); } + } + public Context context() { + var authentication=SecurityContextHolder.getContext().getAuthentication(); + if(authentication==null || !(authentication.getPrincipal() instanceof Jwt jwt)) + throw new IllegalStateException("Business audit requires an authenticated actor"); + return context(Long.parseLong(jwt.getClaimAsString("id"))); + } + public Context context(long actor) { + requireTransaction(); + String name=jdbc.sql("SELECT concat_ws(' ',to_jsonb(u)->>'name',to_jsonb(u)->>'lastname') FROM users u WHERE id=:id").param("id",actor).query(String.class).optional().orElse("Usuario "+actor); + if(name.isBlank()) name="Usuario "+actor; + String requestId=null, reason=null; + if(RequestContextHolder.getRequestAttributes() instanceof ServletRequestAttributes attributes) { + HttpServletRequest request=attributes.getRequest(); + requestId=attributes.getResponse()==null?null:attributes.getResponse().getHeader("X-Request-Id"); + reason=request.getHeader("X-Audit-Reason"); + } + return new Context(actor,name,UUID.randomUUID(),requestId,reason); + } + /** Preserve the caller's validated metadata for non-HTTP invocations too. */ + public Context context(long actor,String requestId) { + var context=context(actor); + String effective=context.requestId()!=null?context.requestId():requestId; + if(effective!=null && !effective.matches("[A-Za-z0-9._:-]{1,128}")) + throw new IllegalArgumentException("Invalid audit request identifier"); + return new Context(context.actorId(),context.actorName(),context.operationId(),effective,context.reason()); + } + @SuppressWarnings("unchecked") + public Map snapshot(String table,long id) { + requireTransaction(); + var fields=FIELDS.get(table); + if(fields==null) throw new IllegalArgumentException("Unknown audited table"); + String projection=String.join(",",fields.stream().map(field->"'"+field+"',to_jsonb(t)->'"+field+"'").toList()); + return jdbc.sql("SELECT jsonb_build_object("+projection+")::text FROM "+table+" t WHERE id=:id") + .param("id",id).query((rs,row)->(Map)json.readValue(rs.getString(1),Map.class)).optional() + .orElseThrow(()->new IllegalStateException("Missing audited entity")); + } + public void change(Context context,String action,String type,long id,Integer caseId,Map before,Map after) { + requireTransaction(); + List allowed=FIELDS.get(switch(type) { + case "case" -> "cases"; case "activity","payment" -> "activities"; case "client" -> "client"; + case "user" -> "users"; case "specialization" -> "specialization"; + case "assignment" -> ""; default -> throw new IllegalArgumentException("Unknown audited entity type"); + }); + if(type.equals("assignment")) allowed=List.of("id_user","id_case"); + if(allowed==null || !allowed.containsAll(before.keySet()) || !allowed.containsAll(after.keySet())) + throw new IllegalArgumentException("Disallowed audit fields"); + var oldValues=new LinkedHashMap(); + var newValues=new LinkedHashMap(); + var keys=new LinkedHashSet<>(before.keySet()); keys.addAll(after.keySet()); + for(String key:keys) { + if(before.containsKey(key)==after.containsKey(key) && equal(before.get(key),after.get(key))) continue; + if(before.containsKey(key)) oldValues.put(key,before.get(key)); + if(after.containsKey(key)) newValues.put(key,after.get(key)); + } + if(oldValues.isEmpty() && newValues.isEmpty()) return; + insert(context,action,type,id,caseId,oldValues,newValues); + } + public void passwordChanged(Context context,long id,String action) { + insert(context,action,"user",id,null,Map.of(),Map.of()); + } + private static boolean equal(Object first,Object second) { + if(first instanceof Number && second instanceof Number) + return new BigDecimal(first.toString()).compareTo(new BigDecimal(second.toString()))==0; + return Objects.equals(first,second); + } + private void insert(Context context,String action,String type,long id,Integer caseId,Map before,Map after) { + requireTransaction(); + jdbc.sql(""" + INSERT INTO business_audit_events(service,action,entity_type,entity_id,actor_id,actor_name,case_id,before_values,after_values,reason,operation_id,request_id) + VALUES(:service,:action,:type,:id,:actor,:name,:caseId,CAST(:before AS JSONB),CAST(:after AS JSONB),:reason,:operation,:request) + """).param("service","reporting").param("action",action).param("type",type).param("id",id) + .param("actor",context.actorId()).param("name",context.actorName()).param("caseId",caseId) + .param("before",json.writeValueAsString(before)).param("after",json.writeValueAsString(after)) + .param("reason",context.reason()).param("operation",context.operationId()).param("request",context.requestId()).update(); + } + private static void requireTransaction() { + if(!TransactionSynchronizationManager.isActualTransactionActive()) throw new IllegalStateException("Business audit requires an active transaction"); + } +} diff --git a/src/main/java/com/aellis/reporting/config/ReportingProperties.java b/src/main/java/com/aellis/reporting/config/ReportingProperties.java new file mode 100644 index 0000000..d6abbd6 --- /dev/null +++ b/src/main/java/com/aellis/reporting/config/ReportingProperties.java @@ -0,0 +1,22 @@ +package com.aellis.reporting.config; + +import java.time.Duration; +import java.util.List; +import jakarta.validation.constraints.*; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.core.io.Resource; +import org.springframework.validation.annotation.Validated; + +@Validated +@ConfigurationProperties("reporting") +public record ReportingProperties(@NotBlank String jwtAlgorithm, Resource publicKey, String tokenSecret, + @NotBlank String issuer, @NotBlank String audience, boolean checkSession, @NotNull Duration jwtMaxAge, + @NotEmpty List allowedOrigins, @Min(0) int rateLimitMax, @Min(1) long rateLimitWindowMs, + @Min(1) int rateLimitMemoryMaxKeys, @Min(1000) long rateLimitRedisBackoffMs, + @NotBlank String rateLimitPrefix, String redisUrl, boolean requestLogEnabled) { + public ReportingProperties { + if (!List.of("RS256", "HS256").contains(jwtAlgorithm)) throw new IllegalArgumentException("JWT_ALGORITHM debe ser RS256 o HS256"); + if (jwtMaxAge != null && (jwtMaxAge.isNegative() || jwtMaxAge.isZero())) throw new IllegalArgumentException("JWT_MAX_AGE debe ser positivo"); + if (allowedOrigins != null && allowedOrigins.contains("*")) throw new IllegalArgumentException("Configura origenes CORS explicitos"); + } +} diff --git a/src/main/java/com/aellis/reporting/config/RequestFilter.java b/src/main/java/com/aellis/reporting/config/RequestFilter.java new file mode 100644 index 0000000..b8bdb3a --- /dev/null +++ b/src/main/java/com/aellis/reporting/config/RequestFilter.java @@ -0,0 +1,120 @@ +package com.aellis.reporting.config; + +import jakarta.servlet.*; +import jakarta.servlet.http.*; +import java.io.*; +import java.time.Clock; +import java.util.*; +import org.slf4j.LoggerFactory; +import org.springframework.boot.web.servlet.FilterRegistrationBean; +import org.springframework.context.annotation.Bean; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.data.redis.core.script.DefaultRedisScript; +import org.springframework.stereotype.Component; +import org.springframework.web.filter.OncePerRequestFilter; + +@Component +public class RequestFilter extends OncePerRequestFilter { + private static final long MAX_BODY = 1024 * 1024; + private record Window(long count, long resetAt) {} + record Limit(long count, long resetAt, boolean allowed) {} + private static final DefaultRedisScript REDIS_SCRIPT = new DefaultRedisScript<>(""" + local count=redis.call('INCR',KEYS[1]) + local ttl=redis.call('PTTL',KEYS[1]) + if count==1 or ttl<0 then redis.call('PEXPIRE',KEYS[1],ARGV[1]); ttl=tonumber(ARGV[1]) end + return {count,ttl} + """, List.class); + private final Map memory = new LinkedHashMap<>(); + private final ReportingProperties properties; + private final Clock clock; + private final StringRedisTemplate redis; + private volatile long redisDisabledUntil; + public RequestFilter(ReportingProperties properties, Clock clock, StringRedisTemplate redis) { + this.properties = properties; this.clock = clock; this.redis = redis; + } + synchronized Limit memoryLimit(String key) { + long now = clock.millis(); + var window = memory.get(key); + if (window == null || window.resetAt() <= now) { + if (memory.size() >= properties.rateLimitMemoryMaxKeys()) { + memory.entrySet().removeIf(entry -> entry.getValue().resetAt() <= now); + if (memory.size() >= properties.rateLimitMemoryMaxKeys() && !memory.containsKey(key)) { + return new Limit(properties.rateLimitMax(), now + properties.rateLimitWindowMs(), false); + } + } + window = new Window(1, now + properties.rateLimitWindowMs()); + } else window = new Window(Math.min(window.count() + 1, properties.rateLimitMax() + 1L), window.resetAt()); + memory.put(key, window); + return new Limit(window.count(), window.resetAt(), window.count() <= properties.rateLimitMax()); + } + private Limit limit(String key) { + long now = clock.millis(); + if (properties.redisUrl() != null && !properties.redisUrl().isBlank() && now >= redisDisabledUntil) { + try { + List result = redis.execute(REDIS_SCRIPT, List.of(properties.rateLimitPrefix() + ":" + key), Long.toString(properties.rateLimitWindowMs())); + if (result != null && result.size() == 2) { + long count = ((Number) result.get(0)).longValue(); long ttl = ((Number) result.get(1)).longValue(); + return new Limit(count, now + Math.max(ttl, 0), count <= properties.rateLimitMax()); + } + } catch (RuntimeException exception) { + redisDisabledUntil = now + properties.rateLimitRedisBackoffMs(); + LoggerFactory.getLogger(getClass()).warn("redis_rate_limit_unavailable; using local limiter"); + } + } + return memoryLimit(key); + } + @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) + throws ServletException, IOException { + String supplied = request.getHeader("X-Request-Id"); + String requestId = supplied != null && supplied.matches("[A-Za-z0-9._:-]{1,128}") ? supplied : UUID.randomUUID().toString(); + response.setHeader("X-Request-Id", requestId); response.setHeader("Cache-Control", "no-store"); + response.setHeader("Permissions-Policy", "camera=(), microphone=(), geolocation=()"); + response.setHeader("X-DNS-Prefetch-Control", "off"); + if (properties.rateLimitMax() > 0) { + var limit = limit(request.getRemoteAddr()); + response.setHeader("X-RateLimit-Limit", Integer.toString(properties.rateLimitMax())); + response.setHeader("X-RateLimit-Remaining", Long.toString(Math.max(0, properties.rateLimitMax() - limit.count()))); + response.setHeader("X-RateLimit-Reset", Long.toString((limit.resetAt() + 999) / 1000)); + if (!limit.allowed()) { + response.setHeader("Retry-After", Long.toString(Math.max(1, (limit.resetAt() - clock.millis() + 999) / 1000))); + error(response, 429, "Too many requests."); return; + } + } + if (request.getContentLengthLong() > MAX_BODY) { error(response, 413, "Request body too large."); return; } + long start = clock.millis(); + try { chain.doFilter(new LimitedRequest(request), response); } + finally { + if (properties.requestLogEnabled()) LoggerFactory.getLogger(getClass()).info("request method={} path={} status={} durationMs={} requestId={}", + request.getMethod(), request.getServletPath(), response.getStatus(), clock.millis() - start, requestId); + } + } + public static void error(HttpServletResponse response, int status, String message) throws IOException { + response.setStatus(status); response.setCharacterEncoding("UTF-8"); response.setContentType("application/json"); + if (status == 401) response.setHeader("WWW-Authenticate", "Bearer"); + response.getWriter().write("{\"data\":{\"message\":\"" + message + "\"},\"status\":\"error\"}"); + } + @Bean FilterRegistrationBean disableDoubleRegistration() { + var registration = new FilterRegistrationBean<>(this); registration.setEnabled(false); return registration; + } + public static class BodyTooLargeException extends IOException {} + private static class LimitedRequest extends HttpServletRequestWrapper { + private ServletInputStream input; + LimitedRequest(HttpServletRequest request) { super(request); } + @Override public ServletInputStream getInputStream() throws IOException { + if (input == null) { + var original = super.getInputStream(); + input = new ServletInputStream() { + long count; + private void check(int read) throws IOException { if (read > 0 && (count += read) > MAX_BODY) throw new BodyTooLargeException(); } + @Override public int read() throws IOException { int value = original.read(); check(value < 0 ? 0 : 1); return value; } + @Override public int read(byte[] bytes, int offset, int length) throws IOException { int value = original.read(bytes, offset, length); check(value); return value; } + @Override public boolean isFinished() { return original.isFinished(); } + @Override public boolean isReady() { return original.isReady(); } + @Override public void setReadListener(ReadListener listener) { original.setReadListener(listener); } + }; + } + return input; + } + @Override public BufferedReader getReader() throws IOException { return new BufferedReader(new InputStreamReader(getInputStream(), java.nio.charset.StandardCharsets.UTF_8)); } + } +} diff --git a/src/main/java/com/aellis/reporting/config/SecurityConfig.java b/src/main/java/com/aellis/reporting/config/SecurityConfig.java new file mode 100644 index 0000000..a07f0bb --- /dev/null +++ b/src/main/java/com/aellis/reporting/config/SecurityConfig.java @@ -0,0 +1,106 @@ +package com.aellis.reporting.config; + +import java.nio.charset.StandardCharsets; +import java.security.KeyFactory; +import java.security.interfaces.RSAPublicKey; +import java.security.spec.X509EncodedKeySpec; +import java.time.*; +import java.util.*; +import javax.crypto.spec.SecretKeySpec; +import org.springframework.context.annotation.*; +import org.springframework.jdbc.core.simple.JdbcClient; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.oauth2.core.*; +import org.springframework.security.oauth2.jose.jws.MacAlgorithm; +import org.springframework.security.oauth2.jwt.*; +import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter; +import org.springframework.security.oauth2.server.resource.web.authentication.BearerTokenAuthenticationFilter; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.web.cors.*; + +@Configuration +public class SecurityConfig { + @Bean Clock clock() { return Clock.systemUTC(); } + + @Bean JwtDecoder jwtDecoder(ReportingProperties properties, JdbcClient jdbc, Clock clock) throws Exception { + NimbusJwtDecoder decoder; + if (properties.jwtAlgorithm().equals("HS256")) { + byte[] secret = properties.tokenSecret().getBytes(StandardCharsets.UTF_8); + if (secret.length < 32) throw new IllegalArgumentException("TOKEN_SECRET debe tener al menos 32 bytes para HS256"); + decoder = NimbusJwtDecoder.withSecretKey(new SecretKeySpec(secret, "HmacSHA256")).macAlgorithm(MacAlgorithm.HS256).build(); + } else { + byte[] encoded; + try (var input = properties.publicKey().getInputStream()) { + encoded = Base64.getDecoder().decode(new String(input.readAllBytes(), StandardCharsets.US_ASCII) + .replaceAll("-----[^-]+-----", "").replaceAll("\\s", "")); + } + var key = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(encoded)); + if (key.getModulus().bitLength() < 3072) throw new IllegalArgumentException("La clave RSA debe tener al menos 3072 bits"); + decoder = NimbusJwtDecoder.withPublicKey(key).build(); + } + OAuth2TokenValidator claims = jwt -> { + try { + long id = Long.parseLong(jwt.getClaimAsString("id")); + String role = jwt.getClaimAsString("rol"); + if (id <= 0 || id > Integer.MAX_VALUE || role == null || role.isBlank() + || jwt.getExpiresAt() == null || jwt.getIssuedAt() == null + || !jwt.getAudience().contains(properties.audience()) + || jwt.getIssuedAt().isAfter(clock.instant().plusSeconds(30)) + || jwt.getIssuedAt().plus(properties.jwtMaxAge()).isBefore(clock.instant().minusSeconds(30)) + || (jwt.getSubject() != null && !jwt.getSubject().equals(Long.toString(id))) + || ("RS256".equals(properties.jwtAlgorithm()) && !"access".equals(jwt.getClaimAsString("token_use"))) + || (jwt.hasClaim("token_use") && !"access".equals(jwt.getClaimAsString("token_use")))) return invalid(); + boolean active = jdbc.sql(""" + SELECT EXISTS(SELECT 1 FROM users u JOIN rol r ON r.id=u.id_rol + WHERE u.id=:id AND u.id_status<>2 AND lower(r.name)=:role) + """).param("id", id).param("role", role).query(Boolean.class).single(); + if (!active) return invalid(); + if (properties.checkSession()) { + UUID session = UUID.fromString(jwt.getClaimAsString("sid")); + boolean valid = jdbc.sql(""" + SELECT EXISTS(SELECT 1 FROM auth_session WHERE id=:session AND user_id=:id + AND NOT revoked AND expires_at>CURRENT_TIMESTAMP) + """).param("session", session).param("id", id).query(Boolean.class).single(); + if (!valid) return invalid(); + } + return OAuth2TokenValidatorResult.success(); + } catch (IllegalArgumentException | NullPointerException exception) { return invalid(); } + }; + decoder.setJwtValidator(new DelegatingOAuth2TokenValidator<>(JwtValidators.createDefaultWithIssuer(properties.issuer()), claims)); + return decoder; + } + private static OAuth2TokenValidatorResult invalid() { return OAuth2TokenValidatorResult.failure(new OAuth2Error("invalid_token")); } + + @Bean SecurityFilterChain security(HttpSecurity http, ReportingProperties properties, RequestFilter filter) throws Exception { + var converter = new JwtAuthenticationConverter(); + converter.setJwtGrantedAuthoritiesConverter(jwt -> List.of(new SimpleGrantedAuthority("ROLE_" + jwt.getClaimAsString("rol").toUpperCase(Locale.ROOT)))); + return http.cors(cors -> cors.configurationSource(cors(properties))) + .csrf(csrf -> csrf.disable()) + .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) + .requestCache(cache -> cache.disable()).formLogin(login -> login.disable()).httpBasic(basic -> basic.disable()).logout(logout -> logout.disable()) + .headers(headers -> headers.contentSecurityPolicy(csp -> csp.policyDirectives("default-src 'none'; frame-ancestors 'none'")) + .referrerPolicy(policy -> policy.policy(org.springframework.security.web.header.writers.ReferrerPolicyHeaderWriter.ReferrerPolicy.NO_REFERRER))) + .authorizeHttpRequests(auth -> auth + .requestMatchers(org.springframework.http.HttpMethod.GET, "/health", "/actuator/health").permitAll() + .requestMatchers(org.springframework.http.HttpMethod.GET, "/reporting/hours/user/day/*").hasAnyRole("ADMIN", "USER") + .requestMatchers(org.springframework.http.HttpMethod.POST, "/reporting/fee/month/user", "/reporting/hours/user/year/*", "/reporting/hours/user/month/*", "/reporting/export/courier", "/reporting/total/activity/category").hasAnyRole("ADMIN", "USER") + .requestMatchers("/reporting/**").hasRole("ADMIN") + .anyRequest().denyAll()) + .exceptionHandling(errors -> errors.authenticationEntryPoint((req, res, ex) -> RequestFilter.error(res, 401, "Unauthorized")) + .accessDeniedHandler((req, res, ex) -> RequestFilter.error(res, 403, "Forbidden"))) + .oauth2ResourceServer(resource -> resource.jwt(jwt -> jwt.jwtAuthenticationConverter(converter)) + .authenticationEntryPoint((req, res, ex) -> RequestFilter.error(res, 401, "Unauthorized"))) + .addFilterBefore(filter, BearerTokenAuthenticationFilter.class).build(); + } + private CorsConfigurationSource cors(ReportingProperties properties) { + var configuration = new CorsConfiguration(); + configuration.setAllowedOrigins(properties.allowedOrigins()); + configuration.setAllowedMethods(List.of("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS")); + configuration.setAllowedHeaders(List.of("X-Audit-Reason", "Content-Type", "Authorization", "X-Request-Id")); + configuration.setExposedHeaders(List.of("Content-Disposition", "X-Request-Id", "X-RateLimit-Limit", "X-RateLimit-Remaining", "X-RateLimit-Reset", "Retry-After")); + configuration.setAllowCredentials(false); + var source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", configuration); return source; + } +} diff --git a/src/main/java/com/aellis/reporting/repository/ReportingRepository.java b/src/main/java/com/aellis/reporting/repository/ReportingRepository.java new file mode 100644 index 0000000..776c063 --- /dev/null +++ b/src/main/java/com/aellis/reporting/repository/ReportingRepository.java @@ -0,0 +1,168 @@ +package com.aellis.reporting.repository; + +import com.aellis.reporting.api.*; +import com.aellis.reporting.api.ReportingDtos.*; +import java.time.*; +import java.util.*; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.jdbc.core.simple.JdbcClient; +import org.springframework.stereotype.Repository; + +@Repository +public class ReportingRepository { + static final String COST="COALESCE(a.amount::numeric,a.hours::numeric*a.rate::numeric)"; + private static final String BASE=""" + FROM activities a LEFT JOIN users u ON u.id=a.id_created LEFT JOIN cases ca ON ca.id=a.id_case + LEFT JOIN client cl ON cl.id=ca.id_client LEFT JOIN category cat ON cat.id=a.id_category + LEFT JOIN paytype p ON p.id=a.id_paytype + """; + private static final String ACTIVITY=""" + a.id AS id_activity,a.created,a.id_paytype,a.description,a.hours,a.rate,a.id_created AS id_user, + u.name,u.lastname,u.acronym,a.amount,%s AS total,a.id_case,ca.name AS "case",cl.businessname, + COALESCE(u.acronym,'Sin responsable') AS responsable,a.payment + """.formatted(COST); + private final JdbcClient jdbc; private final int maxRows; + public ReportingRepository(JdbcClient jdbc,@Value("${REPORT_MAX_ROWS:100000}") int maxRows) { + if(maxRows<1 || maxRows>1_000_000) throw new IllegalArgumentException("REPORT_MAX_ROWS debe estar entre 1 y 1000000"); + this.jdbc=jdbc; this.maxRows=maxRows; + } + private record Query(String where,Map params) {} + private Query activity(Filters f,Integer type) { + var params=new LinkedHashMap(); String sql=" WHERE a.id_status=5"+(type==null?"":" AND a.id_paytype="+type); + if(f.user()!=null) { sql+=" AND a.id_created=:user"; params.put("user",f.user()); } + if(f.caseId()!=null) { sql+=" AND a.id_case=:caseId"; params.put("caseId",f.caseId()); } + if(f.client()!=null) { sql+=" AND ca.id_client=:client"; params.put("client",f.client()); } + sql+=dates(f,"a",params); return new Query(sql,params); + } + private static String dates(Filters f,String alias,Map params) { + String sql=""; + if(f.from()!=null) { sql+=" AND "+alias+".created>=:fromDate"; params.put("fromDate",f.from()); } + if(f.to()!=null) { sql+=" AND "+alias+".created<:untilDate"; params.put("untilDate",f.to().plusDays(1)); } + return sql; + } + private static String period(Filters f,String alias,Map params) { + String sql=""; + if(f.year()!=null) { + LocalDate from=LocalDate.of(f.year(),f.month()==null?1:f.month(),1); + sql+=" AND "+alias+".created>=:periodFrom AND "+alias+".created<:periodUntil"; + params.put("periodFrom",from); params.put("periodUntil",f.month()==null?from.plusYears(1):from.plusMonths(1)); + } else if(f.month()!=null) { sql+=" AND EXTRACT(MONTH FROM "+alias+".created)=:month"; params.put("month",f.month()); } + if(f.day()!=null) { sql+=" AND EXTRACT(DAY FROM "+alias+".created)=:day"; params.put("day",f.day()); } + return sql; + } + private static String sum(String cost) { return "CASE WHEN COUNT(*) FILTER(WHERE ("+cost+") IS NULL)>0 THEN NULL ELSE COALESCE(SUM("+cost+"),0) END"; } + public long total(Report report) { + String sql=switch(report) { + case TOTAL_CLIENT -> "SELECT COUNT(*) FROM client WHERE id_status=3"; + case TOTAL_CASE -> "SELECT COUNT(*) FROM cases WHERE id_status=4"; + case TOTAL_USER -> "SELECT COUNT(*) FROM users WHERE id_status=1"; + case TOTAL_ACTIVITY -> "SELECT COUNT(*) FROM activities WHERE id_status=5"; + default -> throw new IllegalArgumentException("Not a total"); + }; return jdbc.sql(sql).query(Long.class).single(); + } + public List> users() { + return rows(""" + SELECT u.name,u.lastname,u.email,u.acronym,s.name AS specialization,u.rate,st.name AS status,r.name AS rol + FROM users u LEFT JOIN specialization s ON s.id=u.id_specialization LEFT JOIN status st ON st.id=u.id_status + LEFT JOIN rol r ON r.id=u.id_rol WHERE u.id_status=1 ORDER BY u.lastname,u.name,u.id + """,Map.of()); + } + public List> clients() { + return rows(""" + SELECT dt.name AS d_t,cl.identdocument,cl.businessname,cl.description,cl.created,u.name,u.lastname,u.acronym + FROM client cl LEFT JOIN documenttype dt ON dt.id=cl.id_documenttype LEFT JOIN users u ON u.id=cl.id_recomended + WHERE cl.id_status=3 ORDER BY cl.businessname,cl.id + """,Map.of()); + } + public List> cases() { + return rows("SELECT ca.name,ca.created,ca.description,cl.businessname FROM cases ca LEFT JOIN client cl ON cl.id=ca.id_client WHERE ca.id_status=4 ORDER BY ca.created DESC,ca.id DESC",Map.of()); + } + public List> activities(Filters f,boolean courier,boolean detailed) { + var query=activity(f,courier?null:1); + String select=courier?"a.id,cat.name AS category,a.description,a.amount,cl.businessname,ca.name AS \"case\",u.name AS username,u.lastname,u.acronym,a.created":ACTIVITY; + if(detailed) select=""" + a.id AS id_activities,a.description,a.hours,a.created,a.rate,ca.id AS id_case,ca.name AS "case",cl.id AS id_client, + cl.businessname,a.id_created AS id_user,u.acronym,u.name,u.lastname,u.acronym AS responsable,%s * 0.40 AS subtotal + """.formatted(COST); + return rows("SELECT "+select+" "+BASE+query.where()+(courier?" AND a.id_category IS NOT NULL":"")+" ORDER BY a.created,a.id",query.params()); + } + public List> allActivityExport(Filters f) { + var q=activity(f,null); + return rows("SELECT a.id AS id_activities,a.description,a.hours,a.created,u.acronym,ca.name AS \"case\",cl.businessname "+BASE+q.where()+" ORDER BY a.created DESC,a.id DESC",q.params()); + } + public List> fees(Filters f) { + var q=activity(f,1); + return rows("SELECT cl.id,cl.businessname AS cliente,ca.name AS caso,"+sum(COST)+" AS total,"+sum(COST)+" * 0.45 AS aspen," + +sum(COST)+" * 0.15 AS responsable_cuenta,"+sum(COST)+" * 0.40 AS trabajo_invertido,COUNT(*) FILTER(WHERE ("+COST+") IS NULL) AS pending_cost_count " + +BASE+q.where()+" GROUP BY cl.id,cl.businessname,ca.id,ca.name ORDER BY ca.name,ca.id",q.params()); + } + public List> userFees(Filters f,boolean monthly) { + var q=activity(f,1); String where=q.where(); if(monthly) where+=period(f,"a",q.params()); + return rows("SELECT "+(monthly?"":"a.id_case,")+"a.id_created AS id,u.name,u.lastname,u.acronym,SUM(COALESCE(a.hours::numeric,0)) AS horas_totales," + +sum(COST)+" * 0.40 AS honorarios,COUNT(*) FILTER(WHERE ("+COST+") IS NULL) AS pending_cost_count " + +BASE+where+" GROUP BY "+(monthly?"":"a.id_case,")+"a.id_created,u.name,u.lastname,u.acronym ORDER BY u.acronym,a.id_created"+(monthly?"":",a.id_case"),q.params()); + } + public Map account(Filters f) { + var q=activity(f,null); + String debit="CASE WHEN a.id_paytype=1 THEN "+COST+" ELSE 0 END",credit="CASE WHEN a.id_paytype=2 THEN "+COST+" ELSE 0 END"; + return rows("SELECT "+sum(debit)+" AS debito,"+sum(credit)+" AS credito,("+sum(debit)+")-("+sum(credit)+") AS total," + +"COUNT(*) FILTER(WHERE ("+COST+") IS NULL) AS pending_cost_count "+BASE+q.where()+" AND a.id_paytype IN(1,2)",q.params()).getFirst(); + } + public List> hours(Filters f,Report report) { + var q=activity(f,1); String where=q.where(); + if(report==Report.HOURS_DAY) where+=" AND a.created>=CURRENT_DATE AND a.created> countByUser(Filters f,Report report) { + boolean periodReport=report!=Report.USER_CASE; + var q=activity(f,periodReport?1:null); String where=q.where(); if(periodReport) where+=period(f,"a",q.params()); + if(!periodReport) return rows("SELECT COUNT(*) AS total,u.name,u.lastname,u.acronym "+BASE+where+" GROUP BY a.id_created,u.name,u.lastname,u.acronym ORDER BY u.acronym,a.id_created",q.params()); + boolean monthly=report==Report.ACTIVITY_MONTH; + return rows("SELECT CONCAT(u.name,' ',u.lastname,' (',u.acronym,')') AS responsable,COUNT(*) AS count,EXTRACT(YEAR FROM a.created)::int AS year" + +(monthly?",EXTRACT(MONTH FROM a.created)::int AS month":"")+" "+BASE+where + +" GROUP BY a.id_created,u.name,u.lastname,u.acronym,EXTRACT(YEAR FROM a.created)"+(monthly?",EXTRACT(MONTH FROM a.created)":"")+" ORDER BY year"+(monthly?",month":"")+",responsable",q.params()); + } + public List> caseCounts(Filters f,Report report) { + var params=new LinkedHashMap(); String where=" WHERE TRUE"+dates(f,"ca",params)+period(f,"ca",params); + boolean month=report!=Report.CASES_YEAR,day=report==Report.CASES_DAY; + return rows("SELECT COUNT(*) AS total,EXTRACT(YEAR FROM ca.created)::int AS year"+(month?",EXTRACT(MONTH FROM ca.created)::int AS month":"")+(day?",EXTRACT(DAY FROM ca.created)::int AS day":"") + +" FROM cases ca"+where+" GROUP BY EXTRACT(YEAR FROM ca.created)"+(month?",EXTRACT(MONTH FROM ca.created)":"")+(day?",EXTRACT(DAY FROM ca.created)":"") + +" ORDER BY year"+(month?",month":"")+(day?",day":""),params); + } + public Number totalHours(Filters f) { + var q=activity(f,1); return (Number)rows("SELECT COALESCE(SUM(a.hours::numeric),0) AS horas "+BASE+q.where(),q.params()).getFirst().get("horas"); + } + public Object categoryTotal(Filters f) { + var q=activity(f,null); return rows("SELECT "+sum("a.amount::numeric")+" AS total "+BASE+q.where()+" AND a.id_category IS NOT NULL",q.params()).getFirst().get("total"); + } + public List> relations(Filters f) { + var q=activity(f,null); + String debit=sum("CASE WHEN id_paytype=3 THEN cost ELSE 0 END"),credit=sum("CASE WHEN id_paytype=2 THEN cost ELSE 0 END"); + return rows(""" + WITH base AS (SELECT a.id,a.id_case,a.created,a.description,a.amount,a.id_created AS id_user,u.name,u.lastname,u.acronym, + a.id_paytype,p.name AS paytype,ca.name AS "case",ca.description AS case_description,cl.id AS id_client,cl.businessname,%s AS cost + %s %s AND a.id_paytype IN(2,3)), + totals AS (SELECT %s AS debe,%s AS haber,COUNT(*) FILTER(WHERE cost IS NULL) AS pending_cost_count FROM base) + SELECT b.*,t.debe,t.haber,t.debe-t.haber AS total,t.pending_cost_count FROM base b CROSS JOIN totals t ORDER BY b.created,b.id + """.formatted(COST,BASE,q.where(),debit,credit),q.params()); + } + private List> rows(String sql,Map params) { + try(var stream=jdbc.sql(sql).params(params).query((rs,row) -> { + Map result=new LinkedHashMap<>(); var metadata=rs.getMetaData(); + for(int i=1;i<=metadata.getColumnCount();i++) { + Object value=rs.getObject(i); + if(value instanceof java.sql.Timestamp timestamp) value=timestamp.toInstant(); + else if(value instanceof OffsetDateTime timestamp) value=timestamp.toInstant(); + result.put(metadata.getColumnLabel(i),value); + } + return result; + }).stream()) { + var rows=stream.limit(maxRows+1L).toList(); + if(rows.size()>maxRows) throw new ApiException(422,"El informe supera el limite de filas. Reduce el periodo o los filtros."); + return rows; + } + } +} diff --git a/src/main/java/com/aellis/reporting/service/ExcelExportService.java b/src/main/java/com/aellis/reporting/service/ExcelExportService.java new file mode 100644 index 0000000..5613bd6 --- /dev/null +++ b/src/main/java/com/aellis/reporting/service/ExcelExportService.java @@ -0,0 +1,53 @@ +package com.aellis.reporting.service; + +import com.aellis.reporting.api.ApiException; +import java.io.*; +import java.time.temporal.TemporalAccessor; +import java.util.*; +import org.apache.poi.ss.usermodel.*; +import org.apache.poi.xssf.streaming.SXSSFWorkbook; +import org.springframework.stereotype.Service; + +@Service +public class ExcelExportService { + public record Column(String header,String key) {} + public record Sheet(String name,List columns,List> rows) {} + public record Download(String filename,byte[] content) {} + public Download build(String filename,List sheets) throws IOException { + try(var workbook=new SXSSFWorkbook(100);var output=new ByteArrayOutputStream()) { + workbook.setCompressTempFiles(true); + var font=workbook.createFont(); font.setBold(true); + var header=workbook.createCellStyle(); header.setFont(font); + var number=workbook.createCellStyle(); number.setDataFormat(workbook.createDataFormat().getFormat("0.00")); + for(var spec:sheets) { + var sheet=workbook.createSheet(spec.name()); sheet.createFreezePane(0,1); + var first=sheet.createRow(0); + for(int i=0;i=1_048_576) throw new ApiException(422,"Demasiadas filas para una hoja Excel."); + var row=sheet.createRow(index++); + for(int i=0;i32767) throw new ApiException(422,"Un texto supera el limite de una celda Excel."); + // Strings explicitas: nunca se interpretan entradas de usuario como formulas. + cell.setCellValue(text); + } + } + } + } + workbook.write(output); return new Download(filename,output.toByteArray()); + } + } + public static List columns(String... pairs) { + var columns=new ArrayList(); for(int i=0;i reports.total(kind); + case FEES -> reports.fees(f); + case FEE_ACTIVITY -> reports.activities(f,false,false); + case ACCOUNT -> reports.account(f); + case USER_FEES -> reports.userFees(f,false); + case MONTH_FEES -> reports.userFees(f,true); + case HOURS_YEAR,HOURS_MONTH,HOURS_DAY -> reports.hours(f,kind); + case USER_CASE,ACTIVITY_MONTH,ACTIVITY_YEAR -> reports.countByUser(f,kind); + case RELATIONS -> reports.relations(f); + case HOURS_CASE -> reports.totalHours(f); + case CASES_DAY,CASES_MONTH,CASES_YEAR -> reports.caseCounts(f,kind); + case CATEGORY_TOTAL -> reports.categoryTotal(f); + case USERS -> single("Usuarios.xlsx","Usuarios",columns("Nombre","name","Apellido","lastname","Correo","email","Acrónimo","acronym","Especialización","specialization","Honorario","rate","Estado","status","Rol","rol"),reports.users()); + case CLIENTS -> single("clientes.xlsx","clientes",columns("Tipo de Documento","d_t","Documento de Identidad","identdocument","Nombre Comercial","businessname","Fecha de Creacion","created","Acrónimo","acronym"),reports.clients()); + case CASES -> single("casos.xlsx","casos",columns("Cliente","businessname","Caso","name","Descripción","description","Fecha de Creación","created"),reports.cases()); + case ACTIVITIES -> single("actividades.xlsx","actividades",columns("Cliente","businessname","Caso","case","Descripcion","description","Horas","hours","Fecha","created","Acrónimo","acronym"),reports.allActivityExport(f)); + case COURIER -> single("mensajeria.xlsx","mensajeria",columns("ID","id","Tipo","category","Descripción","description","Monto","amount","Cliente","businessname","Caso","case","Acrónimo","acronym","Fecha","created"),reports.activities(f,true,false)); + case BILLS -> bills(f); + case OTHER_BILLS -> otherBills(f); + case REPORT_ACTIVITIES -> reportActivities(f); + }; + } + private Download single(String file,String name,List columns,List> rows) throws IOException { + return excel.build(file,List.of(new Sheet(name,columns,rows))); + } + private Download bills(Filters f) throws IOException { + var activities=new ArrayList<>(reports.activities(f,false,false)); + for(var fee:reports.fees(f)) { + activities.add(row("amount","Total","total",display(fee.get("total")))); + activities.add(row("created","Aspen 45%","businessname",display(fee.get("aspen")),"case","Responsable de Cuenta 15%", + "responsable",display(fee.get("responsable_cuenta")),"description","Trabajo Invertido 40%","rate",display(fee.get("trabajo_invertido")))); + } + var fees=reports.userFees(f,false).stream().map(value -> { + var item=new LinkedHashMap<>(value); item.put("responsable",item.get("acronym")); item.put("honorarios",display(item.get("honorarios"))); return (Map)item; + }).toList(); + // El coste faltante se senala en cada linea y en los totales, nunca como cero. + var printable=activities.stream().map(value -> { + var item=new LinkedHashMap<>(value); if(item.containsKey("id_activity")) item.put("total",display(item.get("total"))); return (Map)item; + }).toList(); + return excel.build("clientes.xlsx",List.of( + new Sheet("Actividades",columns("ID","id_activity","Fecha de Creacion","created","Cliente","businessname","Asunto","case","Responsable","responsable","Actividad","description","Tarifa","rate","Horas Invertidas","hours","Monto Unico","amount","Total","total"),printable), + new Sheet("Honorarios",columns("Responsable","responsable","Horas","horas_totales","Honorarios","honorarios"),fees))); + } + private Download otherBills(Filters f) throws IOException { + var source=reports.relations(f); var rows=new ArrayList>(); + for(var value:source) { + int type=((Number)value.get("id_paytype")).intValue(); + rows.add(row("id",value.get("id"),"description",value.get("description"),"created",value.get("created"), + "amountDebe",type==3?display(value.get("cost")):null,"amountHaber",type==2?display(value.get("cost")):null)); + } + var total=source.isEmpty()?row("debe",BigDecimal.ZERO,"haber",BigDecimal.ZERO,"total",BigDecimal.ZERO):source.getFirst(); + rows.add(row("description","Total","amountDebe",display(total.get("debe")),"amountHaber",display(total.get("haber")),"total",display(total.get("total")))); + return single("Gastos.xlsx","Gastos",columns("ID","id","Descripcion","description","Fecha de Creacion","created","Debe","amountDebe","Haber","amountHaber","Total","total"),rows); + } + private Download reportActivities(Filters f) throws IOException { + var rows=new ArrayList<>(reports.activities(f,false,true)); BigDecimal total=BigDecimal.ZERO; boolean incomplete=false; + for(var item:rows) { + if(item.get("subtotal")==null) incomplete=true; + else total=total.add(new BigDecimal(item.get("subtotal").toString())); + } + var printable=new ArrayList>(); + for(var item:rows) { var copy=new LinkedHashMap<>(item); copy.put("subtotal",display(copy.get("subtotal"))); printable.add(copy); } + printable.add(row("description","Total","subtotal",incomplete?"Pendiente de revisar":total)); + return single("Actividades.xlsx","Actividades",columns("ID","id_activities","Cliente","businessname","Caso","case","Descripcion","description","Fecha de Creacion","created","Responsable","responsable","Horas Invertidas","hours","Valor Honorario","rate","Subtotal","subtotal"),printable); + } + private static Object display(Object value) { return value==null?"Pendiente de revisar":value; } +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml new file mode 100644 index 0000000..6fb37e8 --- /dev/null +++ b/src/main/resources/application.yml @@ -0,0 +1,57 @@ +spring: + jdbc: + template: + query-timeout: 30s + fetch-size: 500 + application: + name: genesis-reporting + datasource: + url: ${DB_URL:jdbc:postgresql://localhost:5432/genesis_auth} + username: ${DB_USER:genesis} + password: ${DB_PASSWORD} + hikari: + maximum-pool-size: 10 + connection-timeout: 5000 + data: + redis: + url: ${REDIS_URL:redis://localhost:6379} + connect-timeout: 500ms + timeout: 500ms + jackson: + deserialization: + fail-on-unknown-properties: true +server: + port: ${SERVER_PORT:8086} + shutdown: graceful + forward-headers-strategy: none + max-http-request-header-size: 16KB + error: + include-message: never + include-stacktrace: never +management: + endpoints: + web: + exposure: + include: health + endpoint: + health: + show-details: never + health: + redis: + enabled: false +reporting: + jwt-algorithm: ${JWT_ALGORITHM:RS256} + public-key: ${JWT_PUBLIC_KEY:file:.secrets/public.pem} + token-secret: ${TOKEN_SECRET:} + issuer: ${JWT_ISSUER:http://localhost:8080} + audience: ${JWT_AUDIENCE:genesis-api} + check-session: ${JWT_CHECK_SESSION:true} + jwt-max-age: ${JWT_MAX_AGE:15m} + allowed-origins: ${CORS_ALLOWED_ORIGINS:${FRONTEND_URL:http://localhost:3000}} + rate-limit-max: ${RATE_LIMIT_MAX:300} + rate-limit-window-ms: ${RATE_LIMIT_WINDOW_MS:60000} + rate-limit-memory-max-keys: ${RATE_LIMIT_MEMORY_MAX_KEYS:10000} + rate-limit-redis-backoff-ms: ${RATE_LIMIT_REDIS_BACKOFF_MS:60000} + rate-limit-prefix: ${RATE_LIMIT_PREFIX:genesis-reporting:rate} + redis-url: ${REDIS_URL:} + request-log-enabled: ${REQUEST_LOG_ENABLED:true} diff --git a/src/test/java/com/aellis/reporting/ReportingServiceIT.java b/src/test/java/com/aellis/reporting/ReportingServiceIT.java new file mode 100644 index 0000000..8dd1456 --- /dev/null +++ b/src/test/java/com/aellis/reporting/ReportingServiceIT.java @@ -0,0 +1,413 @@ +package com.aellis.reporting; + +import com.nimbusds.jose.jwk.*; +import com.nimbusds.jose.jwk.source.ImmutableJWKSet; +import java.net.URI; +import java.net.http.*; +import java.nio.file.*; +import java.security.*; +import java.security.interfaces.RSAPublicKey; +import java.security.interfaces.RSAPrivateKey; +import java.sql.*; +import java.time.*; +import java.util.*; +import org.junit.jupiter.api.*; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.core.env.Environment; +import org.springframework.core.io.ClassPathResource; +import org.springframework.jdbc.core.simple.JdbcClient; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.init.ScriptUtils; +import org.springframework.security.oauth2.jose.jws.SignatureAlgorithm; +import org.springframework.security.oauth2.jwt.*; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.*; +import org.testcontainers.postgresql.PostgreSQLContainer; +import tools.jackson.databind.json.JsonMapper; +import static org.assertj.core.api.Assertions.*; + +@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = { + "logging.level.root=WARN", "debug=false", "reporting.request-log-enabled=false", "reporting.rate-limit-max=10000", "reporting.redis-url=", "reporting.allowed-origins=http://localhost:3000", "spring.data.redis.port=1", "REPORT_MAX_ROWS=100", "spring.datasource.hikari.connection-init-sql=SET TIME ZONE 'UTC'"}) +class ReportingServiceIT { + static final PostgreSQLContainer DB = new PostgreSQLContainer("postgres:18"); + static String url, username, password, schema; + static Path keyDirectory; + static JwtEncoder signer; + @DynamicPropertySource static void database(DynamicPropertyRegistry registry) throws Exception { + url = System.getenv("TEST_DB_URL"); + if (url == null) { DB.start(); url = DB.getJdbcUrl(); username = DB.getUsername(); password = DB.getPassword(); } + else { username = System.getenv("TEST_DB_USER"); password = System.getenv("TEST_DB_PASSWORD"); } + schema = "reporting_test_" + UUID.randomUUID().toString().replace("-", ""); + try (var connection = DriverManager.getConnection(url, username, password); var statement = connection.createStatement()) { + statement.execute("CREATE SCHEMA " + schema); + } + String schemaUrl = url + (url.contains("?") ? "&" : "?") + "currentSchema=" + schema; + var source = new DriverManagerDataSource(schemaUrl, username, password); + try (var connection = source.getConnection()) { ScriptUtils.executeSqlScript(connection, new ClassPathResource("schema.sql")); } + var generator = KeyPairGenerator.getInstance("RSA"); generator.initialize(3072); var pair = generator.generateKeyPair(); + var key = new RSAKey.Builder((RSAPublicKey) pair.getPublic()).privateKey((RSAPrivateKey) pair.getPrivate()).keyID("test-auth").build(); + signer = new NimbusJwtEncoder(new ImmutableJWKSet<>(new JWKSet(key))); + keyDirectory = Files.createTempDirectory("genesis-reporting-public-key"); + Files.writeString(keyDirectory.resolve("public.pem"), "-----BEGIN PUBLIC KEY-----\n" + + Base64.getEncoder().encodeToString(pair.getPublic().getEncoded()) + "\n-----END PUBLIC KEY-----"); + registry.add("spring.datasource.url", () -> schemaUrl); + registry.add("spring.datasource.username", () -> username); + registry.add("spring.datasource.password", () -> password); + registry.add("reporting.public-key", () -> keyDirectory.resolve("public.pem").toUri().toString()); + registry.add("reporting.jwt-algorithm", () -> "RS256"); + registry.add("reporting.issuer", () -> "http://localhost:8080"); registry.add("reporting.audience", () -> "genesis-api"); + registry.add("reporting.check-session", () -> true); + } + @AfterAll static void cleanup() throws Exception { + try (var connection = DriverManager.getConnection(url, username, password); var statement = connection.createStatement()) { + statement.execute("DROP SCHEMA " + schema + " CASCADE"); + } + if (keyDirectory != null) { Files.deleteIfExists(keyDirectory.resolve("public.pem")); Files.deleteIfExists(keyDirectory); } + if (DB.isRunning()) DB.stop(); + } + @Autowired JdbcClient jdbc; + @Autowired javax.sql.DataSource dataSource; + @Autowired Environment environment; + final HttpClient http = HttpClient.newHttpClient(); + final JsonMapper json = JsonMapper.builder().build(); + + + + @BeforeEach void seed() { + jdbc.sql("TRUNCATE business_audit_events RESTART IDENTITY").update(); + jdbc.sql("TRUNCATE users,client,cases,activities RESTART IDENTITY CASCADE").update(); + jdbc.sql(""" + INSERT INTO users VALUES + (1,'Admin','Prueba','admin@example.com','AD',999,'test-secret-hash','test-reset',1,1,1), + (2,'Ana','Prueba','ana@example.com','AN',999,'test-secret-hash','test-reset',2,1,NULL), + (3,'Luis','Prueba','luis@example.com','LU',888,'test-secret-hash','test-reset',2,1,1), + (4,'Inactivo','Prueba','inactive@example.com','IN',10,'test-secret-hash','test-reset',2,2,1), + (5,'Supervisor','Prueba','supervisor@example.com','SU',10,'test-secret-hash','test-reset',3,1,1), + (6,'Libre','Prueba','free@example.com','LI',10,'test-secret-hash','test-reset',2,1,NULL) + """).update(); + jdbc.sql("INSERT INTO client VALUES(1,111,'Alpha',NULL,'2020-01-01',3,1,2),(2,222,'Beta',NULL,'2020-01-01',3,1,NULL),(3,333,'Inactivo',NULL,'2020-01-01',8,1,2)").update(); + jdbc.sql("INSERT INTO cases VALUES(1,'Caso uno','Descripcion del caso','2020-01-01',4,1),(2,'Caso dos',NULL,'2020-02-01',4,2),(3,'Caso antiguo',NULL,'2021-01-01',7,1),(4,'Sin cliente',NULL,'2020-01-02',4,NULL)").update(); + jdbc.sql(""" + INSERT INTO activities(id,description,hours,rate,amount,payment,created,id_created,id_status,id_paytype,id_case,id_category) VALUES + (1,'Horas antiguas',2,10,NULL,TRUE,'2020-01-31T23:59:59.999999Z',2,5,1,1,NULL), + (2,'Horas otra tarifa',1,20,NULL,FALSE,'2020-02-01T00:00:00Z',2,5,1,1,NULL), + (3,'Importe fijo',NULL,NULL,60,NULL,'2020-01-15T12:00:00Z',2,5,1,1,1), + (4,'Otro usuario',2,5,50,NULL,'2020-01-15T12:00:00Z',3,5,1,2,1), + (5,'Credito',NULL,NULL,10,NULL,'2020-01-16T12:00:00Z',1,5,2,1,NULL), + (6,'Gasto',NULL,NULL,25,NULL,'2020-01-17T12:00:00Z',1,5,3,1,NULL), + (7,'Abono',NULL,NULL,200,NULL,'2020-01-18T12:00:00Z',1,5,4,1,NULL), + (8,'Anulada',NULL,NULL,1000,TRUE,'2020-01-19T12:00:00Z',2,6,1,1,NULL), + (9,'Sin tarifa historica',2,NULL,NULL,FALSE,'2020-01-20T12:00:00Z',3,5,1,3,NULL), + (10,'Hoy',4,30,NULL,NULL,CURRENT_DATE+INTERVAL '12 hours',3,5,1,2,NULL) + """).update(); + jdbc.sql("SELECT setval(pg_get_serial_sequence('activities','id'),10,TRUE)").query(Long.class).single(); + } + tools.jackson.databind.JsonNode data(HttpResponse response) { return json.readTree(response.body()).get("data").get("data"); } + static final Set EXPORTS=EnumSet.of( + com.aellis.reporting.api.ReportingDtos.Report.USERS,com.aellis.reporting.api.ReportingDtos.Report.CLIENTS,com.aellis.reporting.api.ReportingDtos.Report.CASES, + com.aellis.reporting.api.ReportingDtos.Report.ACTIVITIES,com.aellis.reporting.api.ReportingDtos.Report.BILLS,com.aellis.reporting.api.ReportingDtos.Report.OTHER_BILLS, + com.aellis.reporting.api.ReportingDtos.Report.REPORT_ACTIVITIES,com.aellis.reporting.api.ReportingDtos.Report.COURIER); + @Test void allTwentyNineRoutesExecuteTheirQueriesAndExportsOpenAsRealXlsx() throws Exception { + String admin=token(1,"admin"); + for(var report:com.aellis.reporting.api.ReportingDtos.Report.values()) { + boolean userId=report==com.aellis.reporting.api.ReportingDtos.Report.HOURS_DAY || report==com.aellis.reporting.api.ReportingDtos.Report.HOURS_MONTH || report==com.aellis.reporting.api.ReportingDtos.Report.HOURS_YEAR; + String path="/reporting"+report.path.replace("{id}",userId?"2":"1"); + var response=bytes(report.method,path,report.method.equals("POST")?Map.of("year",2020,"month",1):null,admin); + assertThat(response.statusCode()).as(report.name()+": "+new String(response.body(),java.nio.charset.StandardCharsets.UTF_8)).isEqualTo(200); + if(EXPORTS.contains(report)) { + assertThat(response.headers().firstValue("Content-Type").orElse("")).contains("spreadsheetml.sheet"); + try(var workbook=workbook(response)) { assertThat(workbook.getNumberOfSheets()).isPositive(); assertThat((Object)workbook.getSheetAt(0).getRow(0)).isNotNull(); } + } else assertThat(json.readTree(response.body()).get("status").asString()).isEqualTo("success"); + } + } + @Test void healthIsPublicAndEveryReportRequiresAuthentication() throws Exception { + assertThat(request("GET","/health",null,null).body()).contains("\"ok\":true"); + assertThat(request("GET","/actuator/health",null,null).statusCode()).isEqualTo(200); + for(var report:com.aellis.reporting.api.ReportingDtos.Report.values()) + assertThat(request(report.method,"/reporting"+report.path.replace("{id}","1"),report.method.equals("POST")?Map.of():null,null).statusCode()).isEqualTo(401); + } + @Test void totalsUseActiveStatesAndCountAllActivityTypesAsInNode() throws Exception { + String admin=token(1,"admin"); + assertThat(data(request("GET","/reporting/total/client",null,admin)).asInt()).isEqualTo(2); + assertThat(data(request("GET","/reporting/total/case",null,admin)).asInt()).isEqualTo(3); + assertThat(data(request("GET","/reporting/total/user",null,admin)).asInt()).isEqualTo(5); + assertThat(data(request("GET","/reporting/total/activity",null,admin)).asInt()).isEqualTo(9); + } + @Test void feesUseHistoricalRatesAndFixedAmountsWithUnifiedSplit() throws Exception { + String admin=token(1,"admin"); + var item=data(request("POST","/reporting/calcfee/1",Map.of(),admin)).get(0); + assertThat(item.get("total").asDouble()).isEqualTo(100); + assertThat(item.get("aspen").asDouble()).isEqualTo(45); assertThat(item.get("responsable_cuenta").asDouble()).isEqualTo(15); + assertThat(item.get("trabajo_invertido").asDouble()).isEqualTo(40); + jdbc.sql("UPDATE users SET rate=5000 WHERE id=2").update(); + assertThat(data(request("POST","/reporting/calcfee/1",Map.of(),admin)).get(0).get("total").asDouble()).isEqualTo(100); + var lines=data(request("POST","/reporting/fee/activity/1",Map.of(),admin)); + assertThat(lines.size()).isEqualTo(3); + for(var line:lines) if(line.get("id_activity").asInt()==1) assertThat(line.get("rate").asDouble()).isEqualTo(10); + } + @Test void honorariosSumEachRateAndFixedAmountBeforeGrouping() throws Exception { + String admin=token(1,"admin"); + var result=data(request("POST","/reporting/fee/user",Map.of("id_created",2,"id_case",1),admin)); + assertThat(result.size()).isEqualTo(1); assertThat(result.get(0).get("horas_totales").asDouble()).isEqualTo(3); + assertThat(result.get(0).get("honorarios").asDouble()).isEqualTo(40); + var january=data(request("POST","/reporting/fee/month/user",Map.of("year",2020,"month",1,"id_created",2),admin)); + assertThat(january.size()).isEqualTo(1); assertThat(january.get(0).get("honorarios").asDouble()).isEqualTo(32); + } + @Test void accountUsesTypeTwoCreditsAndDoesNotSubtractTypeFourDeposits() throws Exception { + var account=data(request("POST","/reporting/account/1",Map.of(),token(1,"admin"))); + assertThat(account.get("debito").asDouble()).isEqualTo(100); assertThat(account.get("credito").asDouble()).isEqualTo(10); + assertThat(account.get("total").asDouble()).isEqualTo(90); + } + @Test void expenseRelationsHaveValidSqlDistinctDescriptionsAndCorrectTotals() throws Exception { + var rows=data(request("POST","/reporting/activity/relation/1",Map.of(),token(1,"admin"))); + assertThat(rows.size()).isEqualTo(2); + for(var item:rows) { + assertThat(item.get("id_paytype").asInt()).isIn(2,3); + assertThat(item.get("case_description").asString()).isEqualTo("Descripcion del caso"); + assertThat(item.get("description").asString()).isIn("Credito","Gasto"); + assertThat(item.get("debe").asDouble()).isEqualTo(25); assertThat(item.get("haber").asDouble()).isEqualTo(10); assertThat(item.get("total").asDouble()).isEqualTo(15); + } + } + @Test void expenseExcelFooterIsNotZeroAndMatchesRows() throws Exception { + try(var book=workbook(bytes("POST","/reporting/other/bills/1",Map.of(),token(1,"admin")))) { + var sheet=book.getSheet("Gastos"); assertThat(sheet.getLastRowNum()).isEqualTo(3); + var footer=sheet.getRow(sheet.getLastRowNum()); + assertThat(footer.getCell(3).getNumericCellValue()).isEqualTo(25); assertThat(footer.getCell(4).getNumericCellValue()).isEqualTo(10); assertThat(footer.getCell(5).getNumericCellValue()).isEqualTo(15); + } + } + @Test void billingExcelUsesSameFortyPercentHonorariosAndShowsResponsible() throws Exception { + try(var book=workbook(bytes("POST","/reporting/bills/1",Map.of(),token(1,"admin")))) { + assertThat(book.getNumberOfSheets()).isEqualTo(2); + var activities=book.getSheet("Actividades"); assertThat(activities.getLastRowNum()).isEqualTo(5); + assertThat(activities.getRow(1).getCell(4).getStringCellValue()).isEqualTo("AN"); + assertThat(activities.getRow(4).getCell(9).getNumericCellValue()).isEqualTo(100); + var split=activities.getRow(5); + assertThat(split.getCell(2).getNumericCellValue()).isEqualTo(45); assertThat(split.getCell(4).getNumericCellValue()).isEqualTo(15); assertThat(split.getCell(6).getNumericCellValue()).isEqualTo(40); + assertThat(book.getSheet("Honorarios").getRow(1).getCell(2).getNumericCellValue()).isEqualTo(40); + } + } + @Test void activityExcelUsesHistoricalRateAndFortyPercentIncludingFixedAmounts() throws Exception { + try(var book=workbook(bytes("POST","/reporting/export/activities",Map.of("id_case",1),token(1,"admin")))) { + var sheet=book.getSheetAt(0); assertThat(sheet.getLastRowNum()).isEqualTo(4); + assertThat(sheet.getRow(4).getCell(8).getNumericCellValue()).isEqualTo(40); + assertThat(sheet.getRow(2).getCell(7).getNumericCellValue()).isEqualTo(10); + } + } + @Test void inclusiveDateEndContainsLastMicrosecondAndExcludesNextMidnight() throws Exception { + var result=data(request("POST","/reporting/calcfee/1",Map.of("fecha_inicio","2020-01-31","fecha_fin","2020-01-31"),token(1,"admin"))); + assertThat(result.size()).isEqualTo(1); assertThat(result.get(0).get("total").asDouble()).isEqualTo(20); + var lines=data(request("POST","/reporting/fee/activity/1",Map.of("fecha_fin","2020-01-31"),token(1,"admin"))); + assertThat(lines.size()).isEqualTo(2); + } + @Test void unknownCostsPropagateAndAreNotReplacedWithCurrentRateOrZero() throws Exception { + String admin=token(1,"admin"); + var fee=data(request("POST","/reporting/calcfee/3",Map.of(),admin)).get(0); + assertThat(fee.get("total").isNull()).isTrue(); assertThat(fee.get("pending_cost_count").asInt()).isEqualTo(1); + var account=data(request("POST","/reporting/account/3",Map.of(),admin)); + assertThat(account.get("debito").isNull()).isTrue(); assertThat(account.get("total").isNull()).isTrue(); + try(var book=workbook(bytes("POST","/reporting/bills/3",Map.of(),admin))) { + assertThat(book.getSheet("Actividades").getRow(1).getCell(9).getStringCellValue()).isEqualTo("Pendiente de revisar"); + assertThat(book.getSheet("Honorarios").getRow(1).getCell(2).getStringCellValue()).isEqualTo("Pendiente de revisar"); + } + jdbc.sql("UPDATE activities SET id_category=1 WHERE id=9").update(); + assertThat(data(request("POST","/reporting/total/activity/category",Map.of("id_created",3),admin)).isNull()).isTrue(); + } + @Test void optionalSpecializationAndRecommenderDoNotHideExports() throws Exception { + String admin=token(1,"admin"); + try(var book=workbook(bytes("GET","/reporting/export/user",null,admin))) { + var sheet=book.getSheetAt(0); assertThat(sheet.getLastRowNum()).isEqualTo(5); + boolean found=false; + for(var row:sheet) if(row.getRowNum()>0 && row.getCell(0).getStringCellValue().equals("Ana")) { found=true; assertThat(row.getCell(4)).isNull(); } + assertThat(found).isTrue(); + } + try(var book=workbook(bytes("GET","/reporting/export/client",null,admin))) { assertThat(book.getSheetAt(0).getLastRowNum()).isEqualTo(2); } + try(var book=workbook(bytes("GET","/reporting/export/cases",null,admin))) { assertThat(book.getSheetAt(0).getLastRowNum()).isEqualTo(3); } + } + @Test void missingActivityCreatorDoesNotDropFinancialAmounts() throws Exception { + jdbc.sql("INSERT INTO activities(description,amount,id_created,id_case,id_status,id_paytype,created) VALUES('Sin responsable',40,NULL,1,5,1,'2020-01-01')").update(); + var fee=data(request("POST","/reporting/calcfee/1",Map.of(),token(1,"admin"))).get(0); + assertThat(fee.get("total").asDouble()).isEqualTo(140); + } + @Test void personalReportsNeverAllowAnotherUserOrOmittedFilterToExposeAllUsers() throws Exception { + String user=token(2,"user"); + var fees=data(request("POST","/reporting/fee/month/user",Map.of("year",2020,"month",1),user)); + assertThat(fees.size()).isEqualTo(1); assertThat(fees.get(0).get("id").asInt()).isEqualTo(2); + assertThat(fees.get(0).get("honorarios").asDouble()).isEqualTo(32); + assertThat(data(request("POST","/reporting/total/activity/category",Map.of(),user)).asDouble()).isEqualTo(60); + for(String route:List.of("/reporting/fee/month/user","/reporting/export/courier","/reporting/total/activity/category")) + assertThat(request("POST",route,Map.of("id_created",3,"year",2020,"month",1),user).statusCode()).isEqualTo(403); + for(String route:List.of("/reporting/hours/user/year/3","/reporting/hours/user/month/3")) + assertThat(request("POST",route,Map.of("year",2020,"month",1),user).statusCode()).isEqualTo(403); + assertThat(request("GET","/reporting/hours/user/day/3",null,user).statusCode()).isEqualTo(403); + try(var book=workbook(bytes("POST","/reporting/export/courier",Map.of(),user))) { + assertThat(book.getSheetAt(0).getLastRowNum()).isEqualTo(1); + assertThat(book.getSheetAt(0).getRow(1).getCell(6).getStringCellValue()).isEqualTo("AN"); + } + } + @Test void adminOnlyReportsAndUnknownRolesAreDenied() throws Exception { + String user=token(2,"user"); + for(var report:com.aellis.reporting.api.ReportingDtos.Report.values()) if(!report.personal) + assertThat(request(report.method,"/reporting"+report.path.replace("{id}","1"),report.method.equals("POST")?Map.of():null,user).statusCode()).isEqualTo(403); + assertThat(request("POST","/reporting/fee/month/user",Map.of("year",2020,"month",1),token(5,"supervisor")).statusCode()).isEqualTo(403); + } + @Test void hoursAndChartsGroupWithoutMultiplyingRowsOrRates() throws Exception { + String admin=token(1,"admin"),user=token(2,"user"); + assertThat(data(request("POST","/reporting/hours/user/year/2",Map.of("year",2020),user)).get(0).get("horas").asDouble()).isEqualTo(3); + assertThat(data(request("POST","/reporting/hours/user/month/2",Map.of("year",2020,"month",1),user)).get(0).get("horas").asDouble()).isEqualTo(2); + assertThat(data(request("GET","/reporting/hours/user/day/3",null,admin)).get(0).get("horas").asDouble()).isEqualTo(4); + assertThat(data(request("POST","/reporting/hours/case/1",Map.of(),admin)).asDouble()).isEqualTo(3); + var years=data(request("POST","/reporting/total/cases/year",Map.of("year",2020),admin)); + assertThat(years.size()).isEqualTo(1); assertThat(years.get(0).get("total").asInt()).isEqualTo(3); + var days=data(request("POST","/reporting/total/cases/day",Map.of("year",2020,"month",1,"day",1),admin)); + assertThat(days.get(0).get("total").asInt()).isEqualTo(1); + var counts=data(request("POST","/reporting/total/activity/month",Map.of("year",2020,"month",1,"id_created",2),admin)); + assertThat(counts.size()).isEqualTo(1); assertThat(counts.get(0).get("count").asInt()).isEqualTo(2); + } + @Test void invalidDatesIdsAndPeriodsFailBeforeRunningSql() throws Exception { + String admin=token(1,"admin"); + for(var body:List.of(Map.of("fecha_inicio","2020-02-30"),Map.of("fecha_inicio","2020-02-01","fecha_fin","2020-01-01"),Map.of("id_created","1 OR 1=1"),Map.of("id_client",0),Map.of("month",13),Map.of("day",0),Map.of("year",0),Map.of("day",30,"month",2,"year",2020))) + assertThat(request("POST","/reporting/calcfee/1",body,admin).statusCode()).isEqualTo(400); + assertThat(request("POST","/reporting/fee/month/user",Map.of(),admin).statusCode()).isEqualTo(400); + assertThat(request("POST","/reporting/hours/user/year/2",Map.of(),admin).statusCode()).isEqualTo(400); + assertThat(request("POST","/reporting/calcfee/0",Map.of(),admin).statusCode()).isEqualTo(400); + assertThat(request("POST","/reporting/calcfee/abc",Map.of(),admin).statusCode()).isEqualTo(400); + assertThat(request("POST","/reporting/calcfee/1",null,admin).statusCode()).isEqualTo(400); + } + @Test void getActivityExportAcceptsQueryFiltersInsteadOfRequiringGetBody() throws Exception { + try(var book=workbook(bytes("GET","/reporting/export/activity?id_case=1&id_created=2",null,token(1,"admin")))) { + assertThat(book.getSheetAt(0).getLastRowNum()).isEqualTo(3); + } + } + @Test void xlsxStringsAreNotExecutableFormulasAndNeverIncludeSecrets() throws Exception { + jdbc.sql("UPDATE client SET businessname=:name WHERE id=1").param("name","=1+1").update(); + try(var book=workbook(bytes("GET","/reporting/export/client",null,token(1,"admin")))) { + var cell=book.getSheetAt(0).getRow(1).getCell(2); + assertThat(cell.getCellType()).isEqualTo(org.apache.poi.ss.usermodel.CellType.STRING); + assertThat(cell.getStringCellValue()).isEqualTo("=1+1"); + } + try(var book=workbook(bytes("GET","/reporting/export/user",null,token(1,"admin")))) { + for(var row:book.getSheetAt(0)) for(var cell:row) if(cell.getCellType()==org.apache.poi.ss.usermodel.CellType.STRING) + assertThat(cell.getStringCellValue()).doesNotContain("test-secret-hash","test-reset","password"); + } + } + @Test void excessiveReportsAreRejectedWithoutReturningPartialTotalsOrFiles() throws Exception { + jdbc.sql("INSERT INTO activities(amount,id_created,id_case,id_status,id_paytype,created) SELECT 1,2,1,5,1,CURRENT_TIMESTAMP FROM generate_series(1,101)").update(); + String admin=token(1,"admin"); + assertThat(request("POST","/reporting/fee/activity/1",Map.of(),admin).statusCode()).isEqualTo(422); + assertThat(request("GET","/reporting/export/activity",null,admin).statusCode()).isEqualTo(422); + assertThat(data(request("POST","/reporting/calcfee/1",Map.of(),admin)).get(0).get("total").asDouble()).isEqualTo(201); + } + @Test void unknownCostsInExpenseLedgerPropagateToFooterInsteadOfZero() throws Exception { + jdbc.sql("UPDATE activities SET amount=NULL WHERE id=6").update(); + var rows=data(request("POST","/reporting/activity/relation/1",Map.of(),token(1,"admin"))); + assertThat(rows.get(0).get("debe").isNull()).isTrue(); assertThat(rows.get(0).get("total").isNull()).isTrue(); + try(var book=workbook(bytes("POST","/reporting/other/bills/1",Map.of(),token(1,"admin")))) { + assertThat(book.getSheetAt(0).getRow(3).getCell(5).getStringCellValue()).isEqualTo("Pendiente de revisar"); + } + } + @Test void emptyReportsHaveZeroTotalsAndValidExcelHeaders() throws Exception { + String admin=token(1,"admin"); + var account=data(request("POST","/reporting/account/999",Map.of(),admin)); + assertThat(account.get("total").asDouble()).isZero(); + assertThat(data(request("POST","/reporting/hours/case/999",Map.of(),admin)).asDouble()).isZero(); + try(var book=workbook(bytes("POST","/reporting/other/bills/999",Map.of(),admin))) { + assertThat(book.getSheetAt(0).getRow(1).getCell(5).getNumericCellValue()).isZero(); + } + } + @Test void revokedExpiredAndForgedTokensAreRejected() throws Exception { + String revoked=token(2,"user"); jdbc.sql("UPDATE auth_session SET revoked=TRUE").update(); + assertThat(request("GET","/reporting/hours/user/day/2",null,revoked).statusCode()).isEqualTo(401); + assertThat(request("GET","/reporting/total/user",null,token(4,"user")).statusCode()).isEqualTo(401); + assertThat(request("GET","/reporting/total/user",null,token(2,"admin")).statusCode()).isEqualTo(401); + for(String invalid:List.of("issuer","audience","expiry","age","type","session")) { + UUID sid=UUID.randomUUID(); if(!invalid.equals("session")) jdbc.sql("INSERT INTO auth_session(id,user_id,expires_at) VALUES(:id,2,CURRENT_TIMESTAMP+INTERVAL '1 day')").param("id",sid).update(); + String jwt=sign(2,"user",sid,invalid.equals("issuer")?"bad":"http://localhost:8080",invalid.equals("audience")?"bad":"genesis-api", + Instant.now().minusSeconds(invalid.equals("age")||invalid.equals("expiry")?3600:0),invalid.equals("expiry")?Instant.now().minusSeconds(120):Instant.now().plusSeconds(900),invalid.equals("type")?"refresh":"access"); + assertThat(request("GET","/reporting/hours/user/day/2",null,jwt).statusCode()).isEqualTo(401); + } + } + @Test void corsExposesDownloadFilenameAndBodyLimitIsEnforced() throws Exception { + var response=http.send(HttpRequest.newBuilder(URI.create(base()+"/reporting/export/user")).header("Origin","http://localhost:3000") + .header("Authorization","Bearer "+token(1,"admin")).GET().build(),HttpResponse.BodyHandlers.ofByteArray()); + assertThat(response.statusCode()).isEqualTo(200); + assertThat(response.headers().firstValue("Access-Control-Expose-Headers").orElse("")).contains("Content-Disposition"); + assertThat(response.headers().firstValue("Content-Disposition").orElse("")).contains("Usuarios.xlsx"); + assertThat(request("POST","/reporting/fee/user",Map.of("extra","x".repeat(1024*1024+1)),token(1,"admin")).statusCode()).isEqualTo(413); + } + HttpResponse bytes(String method,String path,Object body,String token) throws Exception { + var req=HttpRequest.newBuilder(URI.create(base()+path)).timeout(Duration.ofSeconds(30)).header("Content-Type","application/json"); + if(token!=null) req.header("Authorization","Bearer "+token); + return http.send(req.method(method,body==null?HttpRequest.BodyPublishers.noBody():HttpRequest.BodyPublishers.ofString(json.writeValueAsString(body))).build(),HttpResponse.BodyHandlers.ofByteArray()); + } + org.apache.poi.xssf.usermodel.XSSFWorkbook workbook(HttpResponse response) throws Exception { + assertThat(response.statusCode()).as(new String(response.body(),java.nio.charset.StandardCharsets.UTF_8)).isEqualTo(200); + return new org.apache.poi.xssf.usermodel.XSSFWorkbook(new java.io.ByteArrayInputStream(response.body())); + } + String token(long id, String role) { + UUID session = UUID.randomUUID(); + jdbc.sql("INSERT INTO auth_session(id,user_id,expires_at) VALUES(:session,:id,CURRENT_TIMESTAMP+INTERVAL '1 day')") + .param("session", session).param("id", id).update(); + return sign(id, role, session, "http://localhost:8080", "genesis-api", Instant.now(), Instant.now().plusSeconds(900), "access"); + } + String sign(long id, String role, UUID session, String issuer, String audience, Instant issued, Instant expires, String use) { + var claims = JwtClaimsSet.builder().issuer(issuer).subject(Long.toString(id)).audience(List.of(audience)) + .issuedAt(issued).expiresAt(expires).claim("id", id).claim("rol", role).claim("token_use", use) + .claim("sid", session.toString()).build(); + return signer.encode(JwtEncoderParameters.from(JwsHeader.with(SignatureAlgorithm.RS256).keyId("test-auth").build(), claims)).getTokenValue(); + } + String base() { return "http://localhost:" + environment.getProperty("local.server.port"); } + HttpResponse request(String method, String path, Object body, String token) throws Exception { + var request = HttpRequest.newBuilder(URI.create(base() + path)).header("Content-Type", "application/json").timeout(Duration.ofSeconds(30)); + if (token != null) request.header("Authorization", "Bearer " + token); + return http.send(request.method(method, body == null ? HttpRequest.BodyPublishers.noBody() + : HttpRequest.BodyPublishers.ofString(json.writeValueAsString(body))).build(), HttpResponse.BodyHandlers.ofString()); + } + + void auditFixture() { + for(int i=1;i<=5;i++) jdbc.sql(""" + INSERT INTO business_audit_events(service,action,entity_type,entity_id,actor_id,actor_name,case_id,before_values,after_values,reason,operation_id,request_id,occurred_at) + VALUES('cases','case.update','case',:entity,1,'Original Admin',1,'{"name":"Antes"}','{"name":"Despues"}','Correccion',:operation,'audit-request',:time) + """).param("entity",i==5?2:1).param("operation",UUID.fromString("00000000-0000-0000-0000-000000000001")) + .param("time",OffsetDateTime.parse("2026-01-01T00:00:00Z").plusSeconds(i)).update(); + } + @Test void auditEndpointIsAdminOnlyAndReadsHistoricalValues() throws Exception { + auditFixture(); + assertThat(request("GET","/reporting/audit",null,null).statusCode()).isEqualTo(401); + assertThat(request("GET","/reporting/audit",null,token(2,"user")).statusCode()).isEqualTo(403); + var response=request("GET","/reporting/audit",null,token(1,"admin")); + assertThat(response.statusCode()).isEqualTo(200); + var result=json.readTree(response.body()).get("data"); + assertThat(result.get("events").size()).isEqualTo(5); assertThat(result.get("nextCursor").isNull()).isTrue(); + var event=result.get("events").get(0); + assertThat(event.get("actorName").asString()).isEqualTo("Original Admin"); + assertThat(event.get("before").get("name").asString()).isEqualTo("Antes"); + assertThat(event.get("reason").asString()).isEqualTo("Correccion"); + assertThat(jdbc.sql("SELECT count(*) FROM business_audit_events").query(Integer.class).single()).isEqualTo(5); + } + @Test void auditFiltersCombineWithExclusiveEndAndStableCursor() throws Exception { + auditFixture(); String admin=token(1,"admin"); + String filters="?entityType=case&entityId=1&caseId=1&actorId=1&action=case.update&operationId=00000000-0000-0000-0000-000000000001&from=2026-01-01T00:00:01Z&to=2026-01-01T00:00:04Z&limit=2"; + var first=json.readTree(request("GET","/reporting/audit"+filters,null,admin).body()).get("data"); + assertThat(first.get("events").size()).isEqualTo(2); + long cursor=first.get("nextCursor").asLong(); + var last=json.readTree(request("GET","/reporting/audit"+filters+"&beforeId="+cursor,null,admin).body()).get("data"); + assertThat(last.get("events").size()).isEqualTo(1); assertThat(last.get("nextCursor").isNull()).isTrue(); + assertThat(last.get("events").get(0).get("id").asLong()).isLessThan(cursor); + } + @Test void auditRejectsInvalidFiltersAndHasNoMutationApi() throws Exception { + String admin=token(1,"admin"); + for(String query:List.of("limit=101","limit=0","entityId=-1","beforeId=abc","actorId=9223372036854775808","operationId=bad","from=2026-01-01","from=2026-01-02T00:00:00Z&to=2026-01-01T00:00:00Z","extra=x")) + assertThat(request("GET","/reporting/audit?"+query,null,admin).statusCode()).as(query).isEqualTo(400); + assertThat(request("POST","/reporting/audit",Map.of(),admin).statusCode()).isGreaterThanOrEqualTo(400); + assertThat(request("DELETE","/reporting/audit",null,admin).statusCode()).isGreaterThanOrEqualTo(400); + } + @Test void missingAuditSchemaGivesAnActionableStartupError() { + jdbc.sql("ALTER TABLE business_audit_events RENAME TO audit_backup").update(); + try { + var checker=new com.aellis.reporting.audit.BusinessAudit(jdbc,json); + assertThatThrownBy(()->checker.run(null)).isInstanceOf(IllegalStateException.class).hasMessageContaining("business-audit-schema.sql"); + } finally { jdbc.sql("ALTER TABLE audit_backup RENAME TO business_audit_events").update(); } + } +} diff --git a/src/test/resources/schema.sql b/src/test/resources/schema.sql new file mode 100644 index 0000000..583f976 --- /dev/null +++ b/src/test/resources/schema.sql @@ -0,0 +1,44 @@ +CREATE TABLE rol(id INTEGER PRIMARY KEY,name VARCHAR(255)); +INSERT INTO rol VALUES(1,'admin'),(2,'user'),(3,'supervisor'); +CREATE TABLE specialization(id INTEGER PRIMARY KEY,name VARCHAR(255)); +INSERT INTO specialization VALUES(1,'Legal'); +CREATE TABLE status(id INTEGER PRIMARY KEY,name VARCHAR(255)); +INSERT INTO status VALUES(1,'Activo'),(2,'Inactivo'),(3,'Cliente activo'),(4,'Caso activo'),(5,'Actividad activa'),(6,'Actividad anulada'),(7,'Caso inactivo'),(8,'Cliente inactivo'); +CREATE TABLE users(id INTEGER PRIMARY KEY,name VARCHAR(255),lastname VARCHAR(255),email VARCHAR(255),acronym VARCHAR(255),rate DOUBLE PRECISION, + password VARCHAR(255),reset_token_hash VARCHAR(255),id_rol INTEGER REFERENCES rol(id),id_status INTEGER REFERENCES status(id),id_specialization INTEGER REFERENCES specialization(id)); +CREATE TABLE auth_session(id UUID PRIMARY KEY,user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,expires_at TIMESTAMPTZ,revoked BOOLEAN NOT NULL DEFAULT FALSE); +CREATE TABLE documenttype(id INTEGER PRIMARY KEY,name VARCHAR(255)); +INSERT INTO documenttype VALUES(1,'DNI'); +CREATE TABLE client(id INTEGER PRIMARY KEY,identdocument INTEGER,businessname VARCHAR(255),description VARCHAR(1000),created TIMESTAMPTZ, + id_status INTEGER REFERENCES status(id),id_documenttype INTEGER REFERENCES documenttype(id),id_recomended INTEGER REFERENCES users(id)); +CREATE TABLE cases(id INTEGER PRIMARY KEY,name VARCHAR(255),description VARCHAR(255),created TIMESTAMPTZ,id_status INTEGER REFERENCES status(id),id_client INTEGER REFERENCES client(id)); +CREATE TABLE paytype(id INTEGER PRIMARY KEY,name VARCHAR(255)); +INSERT INTO paytype VALUES(1,'Horas'),(2,'Credito'),(3,'Gasto'),(4,'Abono'); +CREATE TABLE category(id INTEGER PRIMARY KEY,name VARCHAR(255)); +INSERT INTO category VALUES(1,'Mensajeria'); +CREATE TABLE activities(id SERIAL PRIMARY KEY,description VARCHAR(255),hours DOUBLE PRECISION,rate DOUBLE PRECISION,amount DOUBLE PRECISION,payment BOOLEAN, + created TIMESTAMPTZ,id_created INTEGER REFERENCES users(id) ON DELETE SET NULL,id_status INTEGER REFERENCES status(id),id_paytype INTEGER REFERENCES paytype(id), + id_case INTEGER REFERENCES cases(id),id_category INTEGER REFERENCES category(id)); + +CREATE TABLE business_audit_events ( + id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY, + occurred_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), + service VARCHAR(40) NOT NULL, + action VARCHAR(80) NOT NULL, + entity_type VARCHAR(40) NOT NULL, + entity_id BIGINT NOT NULL, + actor_id BIGINT NOT NULL, + actor_name VARCHAR(600) NOT NULL, + case_id BIGINT, + before_values JSONB NOT NULL, + after_values JSONB NOT NULL, + reason VARCHAR(500), + operation_id UUID NOT NULL, + request_id VARCHAR(128), + format_version INTEGER NOT NULL DEFAULT 1 CHECK (format_version=1) +); +CREATE INDEX business_audit_entity_idx ON business_audit_events(entity_type,entity_id,id DESC); +CREATE INDEX business_audit_case_idx ON business_audit_events(case_id,id DESC); +CREATE INDEX business_audit_actor_idx ON business_audit_events(actor_id,id DESC); +CREATE INDEX business_audit_date_idx ON business_audit_events(occurred_at,id DESC); +CREATE INDEX business_audit_operation_idx ON business_audit_events(operation_id,id);