Compare commits

..

1 Commits

Author SHA1 Message Date
Nicolas Arenas 8305542fed Test job
testing/ogGui-multibranch/pipeline/head There was a failure building this commit Details
2024-10-29 13:32:47 +01:00
410 changed files with 9070 additions and 20951 deletions

8
.gitignore vendored
View File

@ -1,9 +1 @@
ogWebconsole/.env
ogWebconsole/test-results/ogGui-junit-report.xml
node_modules/
### Debian packaging
debian/oggui
debian/*.substvars
debian/*.log
debian/.debhelper/
debian/files

View File

@ -1,119 +0,0 @@
# Changelog
## [0.11.2] - 2025-4-16
### Fixed
- Se ha corregido un error en la actualizacion del estado de los pcs en la vista tarjetas.
---
## [0.11.1] - 2025-4-16
### Improved
- Nuevos campos en la tabla de clientes. Tipo de firmware y mac.
## Fixed
- Se ha corregido error al crear OUs, que no refrescaba la web.
- Se ha corregido error en el formulario de creacion de imagenes. Si se seleccionaba una imagen para un versionado, no dejaba deseleccionar.
- Se ha corregido un bug en el particionador que impedia ejecutar, cuando eliminabamos una particion.
---
## [0.11.0] - 2025-4-11
### Added
- Se ha diseñado el nuevo formulario para poder ejecutar script. Sistema mejorado con variables etiquetadas.
- Se puede añadir descripcion a una imagen.
- Se han añadido al formulario de crear/editar repositorio, la posibilidad de añadir usuario y puerto ssh.
- Nuevo estado en pc => desconectado.
- Se ha añadido nueva accion para renombrar imagen monolitica.
### Improved
- Se ha mejorado la interfaz de usuario tanto para el despliegue de imagenes, como el particionado.
- Se ha mejorado la responsividad de la vista de grupos.
- Cambios en el comportamiento general de muchos componentes modales. Se han añadido spinners de carga mas intuitivos.
---
## [0.10.1] - 2025-3-27
### Improved
- Mejoras en el comportamiento del arbol de grupos.
- Nueva regexp para controlar las "macs" en la creacion de clientes.
---
## [0.10.0] - 2025-3-25
### Added
- Nuevo componenten de estado global.
- Servicio para que el ogGui obtenga de forma dinamica las variables de entorno.
- Nueva funcionalidad para convertir imagen en imagen virtual.
- Nueva funcionalidad para importar imágenes externas al sistema.
- Despliegue de imangenes sin cache. Cambios en el formulario de "despliegue".
### Improved
- Mejoras en la internacionalización.
- Nueva UX ogRepository. Ahora se gestionan las imagenes de forma mas sencilla.
- Cambios en ogLive. Mejora en la sincronizacion y obtención de datos en la API
### Fixed
- Cambios en la expresion regular para la validacion de documentos DHCP en la carga masiva de pc.
---
## [0.9.2] - 2025-03-19
### Changed
- Jenkinsfile to pubilsh packages in repo in case og release
---
## [0.9.1] - 2025-03-12
### Changed
- Se ha modificado el acceso a Mercure añadiendo nueva variable de entorno.
---
## [0.9.0] - 2025-3-4
### Added
- Integracion con Mercure. Subscriber tanto en "Trazas" con en "Clientes".
- Nueva funcionalidad para checkear la integridad de una imagen. Boton en apartado "imagenes" dentro del repositorio.
- Centralizacion de estilos.
- Nueva funcionalidad para realizar backup de imágenes.
- Botón para cancelar despliegues de imagenes. Aparece en "trazas" tan solo para los comendos "deploy" y para el estado "en progreso".
### Changed
- Nueva interfaz en "Grupos". Se ha aprovechado mejor el espacio y acortado el tamaño de las filas, para poder tener mas elementos por pantalla.
- Cambios en filtros de "Grupos". Ahora se pueden filtrar por "Centro" y "Unidad Organizativa" y estado. Ahora se busca en base de datos, y no en una lista de clientes dados.
- Refactorizados compontentes de crear/editar clientes en uno solo.
- Cambios en DHCP. Nueva UX en "ver clientes". Ahora tenemos un buscador detallado.
- Para gestionar/añadir clientes a subredes ahora tenemos un botón para "añadir todos" y tan solo nos aparecn los equipos que no estén previamente asignados en una subred.
---
## [0.7.0] - 2024-12-10
### Refactored
- Refactored the group screen, removing the separate tabs for clients, advanced search, and organizational units.
- Added support for partitioning functionality in the client detail view.
---
## [0.6.1] - 2024-11-19
### Improved
- Introduced a new automatic sync mode for the ogdhcp and ogBoot components.
- Improve test coverage.
- New view for clients inside the classroom on the main page.
---
## [0.6.0] - 2024-11-19
### Added
- Added functionality to execute actions from the menu in the general groups screen.
- Displayed the selected center on the general screen for better context.
- Implemented the option to collapse the sidebar for improved usability.
- Introduced a dropdown menu to select boot files (BootfileNames).
- Simplified the process of adding multiple clients in the subnets section.
- Enabled ogBoot to manage storage units more intuitively.
- Added preloading of template models in ogBoot for faster setup.
- Created a contextual help tour to guide users through various components and features.
### Improved
- Renamed the field "Reserved Room" to "Available RemotePC" for better clarity.
- Added view sizes for visual cards.
- Refactored the task stepper to improve efficiency and readability.
- Replaced red "X" icons with more consistent and user-friendly visuals.
- Allowed logical names for IP addresses in the subnets section.
- Enabled reordering of commands when creating a command group.
- Made predefined commands read-only to prevent accidental modifications.
- Simplified the task creation modal to enhance user experience.
- Adjusted the translation system to cover new elements and improve consistency (work in progress).
- New element view from clients on groups main view.
### Fixed
- Resolved an issue that prevented editing software profiles correctly.
- Fixed a bug where newly created commands failed to execute in the commands section.

View File

@ -1,107 +0,0 @@
@Library('jenkins-shared-library') _
pipeline {
agent {
label 'jenkins-slave'
}
environment {
DEBIAN_FRONTEND = 'noninteractive'
DEFAULT_DEV_NAME = 'Opengnsys Team'
DEFAULT_DEV_EMAIL = 'opengnsys@qindel.com'
}
options {
skipDefaultCheckout()
}
parameters {
string(name: 'DEV_NAME', defaultValue: '', description: 'Nombre del desarrollador')
string(name: 'DEV_EMAIL', defaultValue: '', description: 'Email del desarrollador')
}
stages {
stage('Prepare Workspace') {
steps {
script {
env.BUILD_DIR = "${WORKSPACE}/oggui"
sh "mkdir -p ${env.BUILD_DIR}"
}
}
}
stage('Checkout') {
steps {
dir("${env.BUILD_DIR}") {
checkout scm
}
}
}
stage('Generate Changelog') {
when {
expression {
return env.TAG_NAME != null
}
}
steps {
script {
def devName = params.DEV_NAME ? params.DEV_NAME : env.DEFAULT_DEV_NAME
def devEmail = params.DEV_EMAIL ? params.DEV_EMAIL : env.DEFAULT_DEV_EMAIL
generateDebianChangelog(env.BUILD_DIR, devName, devEmail)
}
}
}
stage('Generate Changelog (Nightly)'){
when {
branch 'main'
}
steps {
script {
def devName = params.DEV_NAME ? params.DEV_NAME : env.DEFAULT_DEV_NAME
def devEmail = params.DEV_EMAIL ? params.DEV_EMAIL : env.DEFAULT_DEV_EMAIL
generateDebianChangelog(env.BUILD_DIR, devName, devEmail,"nightly")
}
}
}
stage('Build') {
steps {
script {
construirPaquete(env.BUILD_DIR, "../artifacts", "172.17.8.68", "/var/tmp/opengnsys/debian-repo/oggui")
}
}
}
stage ('Publish to Debian Repository') {
when {
expression {
return env.TAG_NAME != null
}
}
agent { label 'debian-repo' }
steps {
script {
// Construir el patrón de versión esperado en el nombre del paquete
def versionPattern = "${env.TAG_NAME}-${env.BUILD_NUMBER}"
publicarEnAptly('/var/tmp/opengnsys/debian-repo/oggui', 'opengnsys-devel', versionPattern)
}
}
}
stage ('Publish to Debian Repository (Nightly)') {
when {
branch 'main'
}
agent { label 'debian-repo' }
steps {
script {
// Construir el patrón de versión esperado en el nombre del paquete
def versionPattern = "-${env.BUILD_NUMBER}~nightly"
publicarEnAptly('/var/tmp/opengnsys/debian-repo/oggui', 'nightly', versionPattern)
}
}
}
}
post {
always {
notifyBuildStatus('narenas@qindel.com')
}
}
}

View File

@ -1,34 +0,0 @@
#!/bin/bash
set -e
CONFIG_FILE="/opt/opengnsys/oggui/src/.env"
HASH_FILE="/opt/opengnsys/oggui/var/lib/oggui/oggui.config.hash"
APP_DIR="/opt/opengnsys/oggui/browser"
SRC_DIR="/opt/opengnsys/oggui/src"
COMPILED_DIR=$SRC_DIR/dist
NGINX_SERVICE="nginx"
# Verificar si el archivo de configuración cambió
if [ -f "$CONFIG_FILE" ] && [ -f "$HASH_FILE" ]; then
OLD_HASH=$(cat "$HASH_FILE")
NEW_HASH=$(md5sum "$CONFIG_FILE")
if [ "$OLD_HASH" != "$NEW_HASH" ]; then
echo "🔄 Cambios detectados en $CONFIG_FILE, recompilando Angular..."
cd "$SRC_DIR"
npm install -g @angular/cli
npm install
/usr/local/bin/ng build --base-href=/ --output-path=dist/oggui --optimization=true --configuration=production --localize=false
md5sum "$CONFIG_FILE" > "$HASH_FILE"
exit 0
else
echo "No hay cambios en $CONFIG_FILE, no es necesario recompilar."
exit 0
fi
else
echo "Archivo de configuración no encontrado o sin hash previo. No se recompilará."
exit 1
fi
# Iniciar Nginx
systemctl restart "$NGINX_SERVICE"

14
debian/changelog vendored
View File

@ -1,14 +0,0 @@
oggui (0.0.1-1) unstable; urgency=medium
* Add debian files
* Update .gitignore
* refs #1637 refactor: remove unused client edit and create components; add manage client component
* refs #1619. Style: enhance cards view layout and paginator integration in groups component
* refactor: update paginator settings and improve page change handling in groups component
* Merge branch 'develop' of ssh://ognproject.evlt.uma.es:21987/opengnsys/oggui into develop
* style: clean up and optimize CSS for groups component; enhance HTML structure and improve responsiveness
* Updated groups paginator
* Merge branch 'develop' of ssh://ognproject.evlt.uma.es:21987/opengnsys/oggui into develop
* refs #1567. New subnet field: 'dns'
-- Tu Nombre <tuemail@example.com> Mon, 10 Mar 2025 14:48:36 +0000

1
debian/compat vendored
View File

@ -1 +0,0 @@
12

13
debian/control vendored
View File

@ -1,13 +0,0 @@
Source: oggui
Section: web
Priority: optional
Maintainer: Nicolas Arenas <nicolas.arenas@qindel.com>
Build-Depends: debhelper (>= 12), nodejs, npm
Standards-Version: 4.5.0
Package: oggui
Architecture: any
Maintainer: Nicolas Arenas <nicolas.arenas@qindel.com>
Depends: ${shlibs:Depends}, ${misc:Depends}, nginx
Description: OpenGnsys GUI created for the Opengnsys Team
Opengnsys Graphical Intercface

View File

@ -1 +0,0 @@
oggui

2
debian/files vendored
View File

@ -1,2 +0,0 @@
oggui_1.0.1+deb-pkg20250310-1_amd64.buildinfo web optional
oggui_1.0.1+deb-pkg20250310-1_amd64.deb web optional

10
debian/oggui.config vendored
View File

@ -1,10 +0,0 @@
#!/bin/sh
set -e
. /usr/share/debconf/confmodule
db_input high opengnsys/oggui_ogcoreUrl || true
db_input high opengnsys/oggui_ogmercureUrl || true
db_go

View File

@ -1,4 +0,0 @@
ogWebconsole/dist/oggui/browser /opt/opengnsys/oggui/
etc /opt/opengnsys/oggui/
ogWebconsole/ssl/* /opt/opengnsys/oggui/etc/nginx/certs/

61
debian/oggui.postinst vendored
View File

@ -1,61 +0,0 @@
#!/bin/bash
set -e
. /usr/share/debconf/confmodule
db_get opengnsys/oggui_ogcoreUrl
OGCORE_URL="$RET"
db_get opengnsys/oggui_ogmercureUrl
OGMERCURE_URL="$RET"
# Asegurarse de que el usuario exista
USER="opengnsys"
CONFIG_FILE="/opt/opengnsys/oggui/browser/assets/config.json"
restore_config_if_modified() {
local new="$1"
local backup="$1.bak"
if [ -f "$backup" ]; then
if ! cmp -s "$new" "$backup"; then
echo ">>> Archivo modificado por el usuario detectado en $new"
echo " - Guardando archivo nuevo como ${new}.new"
mv -f "$new" "${new}.new"
echo " - Restaurando archivo anterior desde backup"
mv -f "$backup" "$new"
else
echo ">>> El archivo $new no ha cambiado desde la última versión, eliminando backup"
rm -f "$backup"
fi
fi
}
# Detectar si es una instalación nueva o una actualización
if [ "$1" = "configure" ] && [ -z "$2" ]; then
if [ ! -f "$CONFIG_FILE" ]; then
jq --arg apiUrl "$OGCORE_URL" --arg mercureUrl "$OGMERCURE_URL" \
'.apiUrl = $apiUrl | .mercureUrl = $mercureUrl' "$CONFIG_FILE" > "${CONFIG_FILE}.tmp" && mv "${CONFIG_FILE}.tmp" "$CONFIG_FILE"
fi
ln -s /opt/opengnsys/oggui/etc/nginx/oggui.conf /etc/nginx/sites-enabled/oggui.conf
ln -s $CONFIG_FILE /opt/opengnsys/oggui/etc/config.json
mkdir -p /etc/nginx/certs/
cp -p /opt/opengnsys/oggui/etc/nginx/certs/* /etc/nginx/certs/
chown -R www-data:www-data /etc/nginx/certs
systemctl daemon-reload
systemctl restart nginx
elif [ "$1" = "configure" ] && [ -n "$2" ]; then
cd /opt/opengnsys/oggui
echo "Actualización desde la versión $2"
# Si upgrade recupero los archivos de configuracion
echo ">>> Backup de archivos de configuración reales en /opt/opengnsys"
restore_config_if_modified "/opt/opengnsys/oggui/etc/nginx/oggui.conf"
restore_config_if_modified "$CONFIG_FILE"
fi
# Cambiar la propiedad de los archivos al usuario especificado
chown opengnsys:www-data /opt/opengnsys/
chown -R opengnsys:www-data /opt/opengnsys/oggui
exit 0

32
debian/oggui.postrm vendored
View File

@ -1,32 +0,0 @@
#!/bin/sh
set -e
NGINX_FILE="/etc/nginx/sites-enabled/oggui.conf"
UNIT_FILE="/etc/systemd/system/oggui.service"
case "$1" in
remove)
echo "El paquete se está desinstalando..."
# Aquí puedes hacer limpieza de archivos o servicios
if [ -L "$NGINX_FILE" ]; then
rm -f "$NGINX_FILE"
systemctl restart nginx
fi
if [ -L "$UNIT_FILE" ]; then
rm -f "$UNIT_FILE"
systemctl daemon-reload
fi
;;
purge)
echo "Eliminando configuración residual..."
;;
upgrade)
echo "Actualizando paquete..."
;;
esac
exit 0

View File

@ -1,6 +0,0 @@
# Automatically added by dh_installdebconf/13.14.1ubuntu5
if [ "$1" = purge ] && [ -e /usr/share/debconf/confmodule ]; then
. /usr/share/debconf/confmodule
db_purge
fi
# End automatically added section

32
debian/oggui.preinst vendored
View File

@ -1,32 +0,0 @@
#!/bin/bash
set -e
backup_file_if_exists() {
local original="$1"
local backup="$1.bak"
if [ -e "$original" ]; then
echo " - Guardando backup de $original en $backup"
cp -a "$original" "$backup"
fi
}
CONFIG_FILE="/opt/opengnsys/oggui/browser/assets/config.json"
# Asegurarse de que el usuario exista
USER="opengnsys"
HOME_DIR="/opt/opengnsys"
if id "$USER" &>/dev/null; then
echo "El usuario $USER ya existe."
else
echo "Creando el usuario $USER con home en $HOME_DIR."
useradd -m -d "$HOME_DIR" -s /bin/bash "$USER"
fi
# Si upgrade hago backup del archivo de configuración
if [ "$1" = "upgrade" ]; then
echo ">>> Backup de archivos de configuración reales en /opt/opengnsys"
backup_file_if_exists "/opt/opengnsys/oggui/etc/nginx/sites-available/oggui.conf"
backup_file_if_exists "$CONFIG_FILE"
fi
exit 0

13
debian/oggui.prerm vendored
View File

@ -1,13 +0,0 @@
#!/bin/bash
set -e
set -x
# Solo eliminar archivos de configuración si se está eliminando el paquete
if [ "$1" = "remove" ] || [ "$1" = "purge" ]; then
rm -f /etc/nginx/sites-enabled/oggui.conf
systemctl daemon-reload
systemctl restart nginx
fi
exit 0

View File

@ -1,9 +0,0 @@
Template: opengnsys/oggui_ogcoreUrl
Type: string
Default: https://127.0.0.1:8443
Description: Introduzca la URL delAPI de OgCore
Template: opengnsys/oggui_ogmercureUrl
Type: string
Default: https://127.0.0.1:3000/.well-known/mercure
Description: Introduzca el endpoint de mercure

11
debian/rules vendored
View File

@ -1,11 +0,0 @@
#!/usr/bin/make -f
%:
dh $@
override_dh_auto_build:
cd ogWebconsole && npm install
cd ogWebconsole && npx ng build --base-href=/ --output-path=dist/oggui --optimization=true --configuration=production
override_dh_auto_install:
dh_auto_install

View File

@ -1,20 +0,0 @@
server {
listen 4200 ssl;
server_name localhost;
root /opt/opengnsys/oggui/browser;
index index.html;
location / {
try_files $uri $uri/ /index.html;
}
# Manejo de archivos estáticos
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
try_files $uri =404;
}
ssl_certificate /opt/opengnsys/oggui/etc/nginx/certs/oggui.uds-test.net.crt.pem;
ssl_certificate_key /opt/opengnsys/oggui/etc/nginx/certs/oggui.uds-test.net.key.pem;
# Configuración para evitar problemas con rutas de Angular
error_page 404 /index.html;
}

View File

@ -1,2 +1 @@
# NG_APP_BASE_API_URL=https://127.0.0.1:8443
# NG_APP_OGCORE_MERCURE_BASE_URL=http://localhost:3000/.well-known/mercure
NG_APP_BASE_API_URL=https://127.0.0.1:8443

View File

@ -1,2 +0,0 @@
NG_APP_BASE_API_URL=https://localhost:8443
NG_APP_OGCORE_MERCURE_BASE_URL=http://localhost:3000/.well-known/mercure

View File

@ -41,5 +41,3 @@ testem.log
.DS_Store
Thumbs.db
test-results/

View File

@ -1,4 +1,4 @@
FROM node:22.10-alpine
FROM node:22.1.0
WORKDIR /app

View File

@ -1,15 +0,0 @@
FROM node:22.10
WORKDIR /app
RUN apt -y update && apt -y install chromium
RUN npm install -g npm@latest
RUN npm install -g @angular/cli@^12.0.0
COPY . /app
RUN npm install
EXPOSE 4200
CMD ["ng", "serve", "--host", "0.0.0.0", "--disable-host-check"]

View File

@ -3,7 +3,9 @@ pipeline {
environment {
DOCKER_REPO = "opengnsys"
DOCKER_CREDENTIALS = credentials('docker-hub-credentials')
DOCKER_TAG = "${env.BUILD_NUMBER}"
DOCKER_IMAGE_NAME = "oggui"
BRANCH_NAME = "${GIT_BRANCH.split("/")[1]}"
}
stages {
stage ('Checkout') {
@ -11,53 +13,12 @@ pipeline {
checkout scm
}
}
stage('Build Testing Image') {
steps {
sh "printenv"
echo 'Building....'
script {
def DOCKER_TAG = "${env.BUILD_NUMBER}"
dir('ogWebconsole') {
IMAGE_ID = "${DOCKER_REPO}/${DOCKER_IMAGE_NAME}:${BRANCH_NAME}-${DOCKER_TAG}"
IMAGE_ID_TESTING = "${DOCKER_REPO}/${DOCKER_IMAGE_NAME}:${BRANCH_NAME}-${DOCKER_TAG}-testing"
if (BRANCH_NAME == 'main') {
LATEST_ID = "${DOCKER_REPO}/${DOCKER_IMAGE_NAME}:latest"
} else {
LATEST_ID = "${DOCKER_REPO}/${DOCKER_IMAGE_NAME}:${BRANCH_NAME}-latest"
}
env.IMAGE_ID_TESTING = IMAGE_ID_TESTING
env.IMAGE_ID = IMAGE_ID
env.LATEST_ID = LATEST_ID
docker.build("${IMAGE_ID_TESTING}", "-f Dockerfile-testing .")
if (env.TAG_NAME) {
TAG_ID = "${DOCKER_REPO}/${DOCKER_IMAGE_NAME}:${env.TAG_NAME}"
}
}
}
}
}
stage('Testing') {
steps {
echo 'Running Tests....'
sh '''
cd ogWebconsole
docker run -p 4200:4200 --name oggui-testing -e CHROME_BIN=/usr/bin/chromium -v $(pwd)/karma.conf.js:/app/karma.conf.js -v $(pwd)/.env:/app/.env -d $IMAGE_ID_TESTING
docker exec oggui-testing ng test --watch=false --source-map=false --karma-config=karma.conf.js
'''
}
}
stage('Build') {
steps {
echo 'Building....'
script {
dir('ogWebconsole') {
docker.build("${IMAGE_ID}", "-f Dockerfile .")
docker.build("${LATEST_ID}", "-f Dockerfile .")
if (env.TAG_NAME) {
docker.build("${TAG_ID}", "-f Dockerfile .")
}
docker.build("${DOCKER_REPO}/${DOCKER_IMAGE_NAME}:${BRANCH_NAME}-${DOCKER_TAG}", "-f Dockerfile .")
}
}
}
@ -66,46 +27,13 @@ pipeline {
steps {
echo 'Pushing....'
script {
docker.withRegistry('https://index.docker.io/v1/', 'docker-hub-credentials') {
docker.image("${IMAGE_ID}").push()
docker.image("${LATEST_ID}").push()
if (env.TAG_NAME) {
docker.image("${TAG_ID}").push()
docker.withRegistry('https://index.docker.io/v1/', 'docker-hub-credentials' ) {
dir('ogWebconsole') {
docker.image("${DOCKER_REPO}/${DOCKER_IMAGE_NAME}:${BRANCH_NAME}-${DOCKER_TAG}").push()
}
}
}
}
}
}
post {
always {
echo 'Get test results....'
sh "mkdir -p test-results"
sh "docker cp oggui-testing:/app/test-results/ogGui-junit-report.xml ./test-results/ogGui-junit-report.xml"
junit '**/test-results/*.xml'
echo 'Cleaning up....'
sh "docker stop oggui-testing"
sh "docker rm oggui-testing"
sh "docker rmi ${IMAGE_ID} || true"
sh "docker rmi ${LATEST_ID} || true"
sh "docker rmi ${IMAGE_ID_TESTING} || true"
script {
def committerEmail = sh (
script: "git show -s --pretty=%ae",
returnStdout: true
).trim()
def buildResult = currentBuild.currentResult
mail to: committerEmail,
subject: "Opengnsys CI Build ${env.JOB_NAME} - ${env.BRANCH_NAME} - ${buildResult}",
body: """
<h1>Opengnsys CI Build ${JOB_NAME} - ${BRANCH_NAME} - ${buildResult}</h1>
<p>Build Number: ${BUILD_NUMBER}</p>
<p>Build URL: ${BUILD_URL}</p>º
Saludos cordiales,
Opengnsys CI
"""
}
}
}
}

View File

@ -4,6 +4,12 @@
"newProjectRoot": "projects",
"projects": {
"ogWebconsole": {
"i18n": {
"sourceLocale": "es",
"locales": {
"en-US": "src/locale/messages.en.json"
}
},
"projectType": "application",
"schematics": {
"@schematics/angular:component": {
@ -24,7 +30,7 @@
"builder": "@ngx-env/builder:application",
"options": {
"baseHref": "/oggui/",
"localize": false,
"localize": true,
"aot": true,
"outputPath": "dist/og-webconsole",
"index": "src/index.html",
@ -36,22 +42,14 @@
"tsConfig": "tsconfig.app.json",
"assets": [
"src/favicon.ico",
"src/assets",
{
"glob": "**/*",
"input": "src/locale",
"output": "/locale"
}
"src/assets"
],
"styles": [
"src/custom-theme.scss",
"src/styles.css",
"node_modules/ngx-toastr/toastr.css"
],
"scripts": [],
"allowedCommonJsDependencies": [
"rfdc"
]
"scripts": []
},
"configurations": {
"production": {
@ -63,8 +61,8 @@
},
{
"type": "anyComponentStyle",
"maximumWarning": "7kb",
"maximumError": "10kb"
"maximumWarning": "2kb",
"maximumError": "4kb"
}
],
"outputHashing": "all"
@ -73,6 +71,16 @@
"optimization": false,
"extractLicenses": false,
"sourceMap": false
},
"es": {
"localize": [
"es-ES"
]
},
"en": {
"localize": [
"en-US"
]
}
},
"defaultConfiguration": "production"
@ -91,16 +99,29 @@
},
"development": {
"buildTarget": "ogWebconsole:build:development"
},
"es": {
"buildTarget": "ogWebconsole:build:es"
},
"en": {
"buildTarget": "ogWebconsole:build:en"
}
},
"defaultConfiguration": "development"
},
"extract-i18n": {
"builder": "@ngx-env/builder:extract-i18n",
"options": {
"buildTarget": "ogWebconsole:build"
}
},
"test": {
"builder": "@ngx-env/builder:karma",
"options": {
"polyfills": [
"zone.js",
"zone.js/testing"
"zone.js/testing",
"@angular/localize/init"
],
"tsConfig": "tsconfig.spec.json",
"assets": [
@ -108,8 +129,7 @@
"src/assets"
],
"styles": [
"src/styles.css",
"src/custom-theme.scss"
"src/styles.css"
],
"scripts": []
}
@ -120,4 +140,4 @@
"cli": {
"analytics": "95fac95c-8936-41a8-8c9c-1fae82fe6912"
}
}
}

View File

@ -1,40 +0,0 @@
module.exports = function(config) {
config.set({
frameworks: ['jasmine', '@angular-devkit/build-angular'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage'),
require('karma-junit-reporter'),
require('@angular-devkit/build-angular/plugins/karma')
],
client: {
clearContext: false
},
reporters: ['progress', 'kjhtml', 'junit'],
junitReporter: {
outputDir: 'test-results',
outputFile: 'ogGui-junit-report.xml',
useBrowserName: false,
},
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['ChromeHeadlessNoSandbox'],
customLaunchers: {
ChromeHeadlessNoSandbox: {
base: 'ChromeHeadless',
flags: ['--no-sandbox','--disable-setuid-sandbox']
}
},
singleRun: false,
restartOnFileChange: true
});
};

View File

@ -1,12 +1,12 @@
{
"name": "og-webconsole",
"version": "0.5.0",
"version": "0.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "og-webconsole",
"version": "0.5.0",
"version": "0.0.0",
"dependencies": {
"@angular/animations": "^18.0.0",
"@angular/cdk": "~18.0.0",
@ -18,13 +18,9 @@
"@angular/platform-browser": "^18.0.0",
"@angular/platform-browser-dynamic": "^18.0.0",
"@angular/router": "^18.0.0",
"@ngx-translate/core": "^16.0.3",
"@ngx-translate/http-loader": "^16.0.0",
"@swimlane/ngx-charts": "^20.5.0",
"jwt-decode": "^4.0.0",
"ngx-joyride": "^2.5.0",
"ngx-toastr": "^19.0.0",
"papaparse": "^5.4.1",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "^0.14.6"
@ -36,14 +32,12 @@
"@angular/localize": "^18.1.0",
"@ngx-env/builder": "^18.0.1",
"@types/jasmine": "~5.1.0",
"@types/papaparse": "^5.3.15",
"jasmine-core": "~5.1.0",
"karma": "~6.4.0",
"karma-chrome-launcher": "~3.2.0",
"karma-coverage": "~2.2.0",
"karma-jasmine": "~5.1.0",
"karma-jasmine-html-reporter": "~2.1.0",
"karma-junit-reporter": "^2.0.1",
"typescript": "~5.4.5"
}
},
@ -4980,30 +4974,6 @@
"url": "https://github.com/sponsors/isaacs"
}
},
"node_modules/@ngx-translate/core": {
"version": "16.0.3",
"resolved": "https://registry.npmjs.org/@ngx-translate/core/-/core-16.0.3.tgz",
"integrity": "sha512-UPse66z9tRUmIpeorYodXBQY6O4foUmj9jy9cCuuja7lqdOwRBWPzCWqc+qYIXv5L2QoqZdxgHtqoUz+Q9weSA==",
"dependencies": {
"tslib": "^2.3.0"
},
"peerDependencies": {
"@angular/common": ">=16",
"@angular/core": ">=16"
}
},
"node_modules/@ngx-translate/http-loader": {
"version": "16.0.0",
"resolved": "https://registry.npmjs.org/@ngx-translate/http-loader/-/http-loader-16.0.0.tgz",
"integrity": "sha512-l3okOHGVxZ1Bm55OpakSfXvI2yYmVmhYqgwGU4aIQIRUqpkBCrSDZnmrHTcZfsGJzXKB5E2D2rko9i28gBijmA==",
"dependencies": {
"tslib": "^2.3.0"
},
"peerDependencies": {
"@angular/common": ">=16",
"@angular/core": ">=16"
}
},
"node_modules/@nodelib/fs.scandir": {
"version": "2.1.5",
"resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz",
@ -5904,15 +5874,6 @@
"@types/node": "*"
}
},
"node_modules/@types/papaparse": {
"version": "5.3.15",
"resolved": "https://registry.npmjs.org/@types/papaparse/-/papaparse-5.3.15.tgz",
"integrity": "sha512-JHe6vF6x/8Z85nCX4yFdDslN11d+1pr12E526X8WAfhadOeaOTx5AuIkvDKIBopfvlzpzkdMx4YyvSKCM9oqtw==",
"dev": true,
"dependencies": {
"@types/node": "*"
}
},
"node_modules/@types/qs": {
"version": "6.9.15",
"resolved": "https://registry.npmjs.org/@types/qs/-/qs-6.9.15.tgz",
@ -6571,9 +6532,9 @@
}
},
"node_modules/body-parser": {
"version": "1.20.3",
"resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.3.tgz",
"integrity": "sha512-7rAxByjUMqQ3/bHJy7D6OGXvx/MMc4IqBn/X0fcM1QUcAItpZrBEYhWGem+tzXH90c+G01ypMcYJBO9Y30203g==",
"version": "1.20.2",
"resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.2.tgz",
"integrity": "sha512-ml9pReCu3M61kGlqoTm2umSXTlRTuGTx0bfYj+uIUKKYycG5NtSbeetV3faSU6R7ajOPw0g/J1PvK4qNy7s5bA==",
"dev": true,
"dependencies": {
"bytes": "3.1.2",
@ -6584,7 +6545,7 @@
"http-errors": "2.0.0",
"iconv-lite": "0.4.24",
"on-finished": "2.4.1",
"qs": "6.13.0",
"qs": "6.11.0",
"raw-body": "2.5.2",
"type-is": "~1.6.18",
"unpipe": "1.0.0"
@ -7259,9 +7220,9 @@
"dev": true
},
"node_modules/cookie": {
"version": "0.7.2",
"resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz",
"integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==",
"version": "0.4.2",
"resolved": "https://registry.npmjs.org/cookie/-/cookie-0.4.2.tgz",
"integrity": "sha512-aSWTXFzaKWkvHO1Ny/s+ePFpvKsPnjc551iI41v3ny/ow6tBG5Vd+FuqGNhh1LxOmVzOlGUriIlOaokOvhaStA==",
"dev": true,
"engines": {
"node": ">= 0.6"
@ -8119,9 +8080,9 @@
}
},
"node_modules/engine.io": {
"version": "6.6.2",
"resolved": "https://registry.npmjs.org/engine.io/-/engine.io-6.6.2.tgz",
"integrity": "sha512-gmNvsYi9C8iErnZdVcJnvCpSKbWTt1E8+JZo8b+daLninywUWi5NQ5STSHZ9rFjFO7imNcvb8Pc5pe/wMR5xEw==",
"version": "6.5.5",
"resolved": "https://registry.npmjs.org/engine.io/-/engine.io-6.5.5.tgz",
"integrity": "sha512-C5Pn8Wk+1vKBoHghJODM63yk8MvrO9EWZUfkAt5HAqIgPE4/8FF0PEGHXtEd40l223+cE5ABWuPzm38PHFXfMA==",
"dev": true,
"dependencies": {
"@types/cookie": "^0.4.1",
@ -8129,7 +8090,7 @@
"@types/node": ">=10.0.0",
"accepts": "~1.3.4",
"base64id": "2.0.0",
"cookie": "~0.7.2",
"cookie": "~0.4.1",
"cors": "~2.8.5",
"debug": "~4.3.1",
"engine.io-parser": "~5.2.1",
@ -8435,37 +8396,37 @@
"dev": true
},
"node_modules/express": {
"version": "4.21.1",
"resolved": "https://registry.npmjs.org/express/-/express-4.21.1.tgz",
"integrity": "sha512-YSFlK1Ee0/GC8QaO91tHcDxJiE/X4FbpAyQWkxAvG6AXCuR65YzK8ua6D9hvi/TzUfZMpc+BwuM1IPw8fmQBiQ==",
"version": "4.19.2",
"resolved": "https://registry.npmjs.org/express/-/express-4.19.2.tgz",
"integrity": "sha512-5T6nhjsT+EOMzuck8JjBHARTHfMht0POzlA60WV2pMD3gyXw2LZnZ+ueGdNxG+0calOJcWKbpFcuzLZ91YWq9Q==",
"dev": true,
"dependencies": {
"accepts": "~1.3.8",
"array-flatten": "1.1.1",
"body-parser": "1.20.3",
"body-parser": "1.20.2",
"content-disposition": "0.5.4",
"content-type": "~1.0.4",
"cookie": "0.7.1",
"cookie": "0.6.0",
"cookie-signature": "1.0.6",
"debug": "2.6.9",
"depd": "2.0.0",
"encodeurl": "~2.0.0",
"encodeurl": "~1.0.2",
"escape-html": "~1.0.3",
"etag": "~1.8.1",
"finalhandler": "1.3.1",
"finalhandler": "1.2.0",
"fresh": "0.5.2",
"http-errors": "2.0.0",
"merge-descriptors": "1.0.3",
"merge-descriptors": "1.0.1",
"methods": "~1.1.2",
"on-finished": "2.4.1",
"parseurl": "~1.3.3",
"path-to-regexp": "0.1.10",
"path-to-regexp": "0.1.7",
"proxy-addr": "~2.0.7",
"qs": "6.13.0",
"qs": "6.11.0",
"range-parser": "~1.2.1",
"safe-buffer": "5.2.1",
"send": "0.19.0",
"serve-static": "1.16.2",
"send": "0.18.0",
"serve-static": "1.15.0",
"setprototypeof": "1.2.0",
"statuses": "2.0.1",
"type-is": "~1.6.18",
@ -8477,9 +8438,9 @@
}
},
"node_modules/express/node_modules/cookie": {
"version": "0.7.1",
"resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.1.tgz",
"integrity": "sha512-6DnInpx7SJ2AK3+CTUE/ZM0vWTUboZCegxhC2xiIydHR9jNuTAASBrfEpHhiGOZw/nX51bHt6YQl8jsGo4y/0w==",
"version": "0.6.0",
"resolved": "https://registry.npmjs.org/cookie/-/cookie-0.6.0.tgz",
"integrity": "sha512-U71cyTamuh1CRNCfpGY6to28lxvNwPG4Guz/EVjgf3Jmzv0vlDp1atT9eS5dDjMYHucpHbWns6Lwf3BKz6svdw==",
"dev": true,
"engines": {
"node": ">= 0.6"
@ -8494,23 +8455,14 @@
"ms": "2.0.0"
}
},
"node_modules/express/node_modules/encodeurl": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz",
"integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==",
"dev": true,
"engines": {
"node": ">= 0.8"
}
},
"node_modules/express/node_modules/finalhandler": {
"version": "1.3.1",
"resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.3.1.tgz",
"integrity": "sha512-6BN9trH7bp3qvnrRyzsBz+g3lZxTNZTbVO2EV1CS0WIcDbawYVdYvGflME/9QP0h0pYlCDBCTjYa9nZzMDpyxQ==",
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.2.0.tgz",
"integrity": "sha512-5uXcUVftlQMFnWC9qu/svkWv3GTd2PfUhK/3PLkYNAe7FbqJMt3515HaxE6eRL74GdsriiwujiawdaB1BpEISg==",
"dev": true,
"dependencies": {
"debug": "2.6.9",
"encodeurl": "~2.0.0",
"encodeurl": "~1.0.2",
"escape-html": "~1.0.3",
"on-finished": "2.4.1",
"parseurl": "~1.3.3",
@ -10075,22 +10027,6 @@
"integrity": "sha512-VYz/BjjmC3klLJlLwA4Kw8ytk0zDSmbbDLNs794VnWmkcCB7I9aAL/D48VNQtmITyPvea2C3jdUMfc3kAoy0PQ==",
"dev": true
},
"node_modules/karma-junit-reporter": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/karma-junit-reporter/-/karma-junit-reporter-2.0.1.tgz",
"integrity": "sha512-VtcGfE0JE4OE1wn0LK8xxDKaTP7slN8DO3I+4xg6gAi1IoAHAXOJ1V9G/y45Xg6sxdxPOR3THCFtDlAfBo9Afw==",
"dev": true,
"dependencies": {
"path-is-absolute": "^1.0.0",
"xmlbuilder": "12.0.0"
},
"engines": {
"node": ">= 8"
},
"peerDependencies": {
"karma": ">=0.9"
}
},
"node_modules/karma-source-map-support": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/karma-source-map-support/-/karma-source-map-support-1.4.0.tgz",
@ -10830,13 +10766,10 @@
}
},
"node_modules/merge-descriptors": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.3.tgz",
"integrity": "sha512-gaNvAS7TZ897/rVaZ0nMtAyxNyi/pdbjbAwUpFQpN70GqnVfOiXpeUUMKRBmzXaSQ8DdTX4/0ms62r2K+hE6mQ==",
"dev": true,
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.1.tgz",
"integrity": "sha512-cCi6g3/Zr1iqQi6ySbseM1Xvooa98N0w31jzUYrXPX2xqObmFGHJ0tQ5u74H3mVh7wLouTseZyYIq39g8cNp1w==",
"dev": true
},
"node_modules/merge-stream": {
"version": "2.0.0",
@ -10863,9 +10796,9 @@
}
},
"node_modules/micromatch": {
"version": "4.0.8",
"resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz",
"integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==",
"version": "4.0.7",
"resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.7.tgz",
"integrity": "sha512-LPP/3KorzCwBxfeUuZmaR6bG2kdeHSbe0P2tY3FLRU4vYrjYz5hI4QZwV0njUx3jeuKe67YukQ1LSPZBKDqO/Q==",
"dev": true,
"dependencies": {
"braces": "^3.0.3",
@ -11278,18 +11211,6 @@
"integrity": "sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw==",
"dev": true
},
"node_modules/ngx-joyride": {
"version": "2.5.0",
"resolved": "https://registry.npmjs.org/ngx-joyride/-/ngx-joyride-2.5.0.tgz",
"integrity": "sha512-C/J8C4uWZjKl9aMmRBt9egVjuIpwWFplJgBZDl1EfqNVTJkdEC51nt9DpAOuDwOgkbArhJ9sZIk3bZT4vkud/w==",
"dependencies": {
"tslib": "^2.0.0"
},
"peerDependencies": {
"@angular/common": ">=8.2.14",
"@angular/core": ">=8.2.14"
}
},
"node_modules/ngx-toastr": {
"version": "19.0.0",
"resolved": "https://registry.npmjs.org/ngx-toastr/-/ngx-toastr-19.0.0.tgz",
@ -11639,9 +11560,9 @@
}
},
"node_modules/object-inspect": {
"version": "1.13.3",
"resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.3.tgz",
"integrity": "sha512-kDCGIbxkDSXE3euJZZXzc6to7fCrKHNI/hSRQnRuQ+BWjFNzZwiFF8fj/6o2t2G9/jTj8PSIYTfCLelLZEeRpA==",
"version": "1.13.2",
"resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.2.tgz",
"integrity": "sha512-IRZSRuzJiynemAXPYtPe5BoI/RESNYR7TYm50MC5Mqbd3Jmw5y790sErYw3V6SryFJD64b74qQQs9wn5Bg/k3g==",
"dev": true,
"engines": {
"node": ">= 0.4"
@ -11966,11 +11887,6 @@
"node": "^16.14.0 || >=18.0.0"
}
},
"node_modules/papaparse": {
"version": "5.4.1",
"resolved": "https://registry.npmjs.org/papaparse/-/papaparse-5.4.1.tgz",
"integrity": "sha512-HipMsgJkZu8br23pW15uvo6sib6wne/4woLZPlFf3rpDyMe9ywEXUsuD7+6K9PRkJlVT51j/sCOYDKGGS3ZJrw=="
},
"node_modules/parent-module": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz",
@ -12119,9 +12035,9 @@
"dev": true
},
"node_modules/path-to-regexp": {
"version": "0.1.10",
"resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.10.tgz",
"integrity": "sha512-7lf7qcQidTku0Gu3YDPc8DJ1q7OOucfa/BSsIwjuh56VU7katFvuM8hULfkwB3Fns/rsVF7PwPKVw1sl5KQS9w==",
"version": "0.1.7",
"resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.7.tgz",
"integrity": "sha512-5DFkuoqlv1uYQKxy8omFBeJPQcdoE07Kv2sferDCrAq1ohOU+MSDswDIbnx3YAM60qIOnYa53wBhXW0EbMonrQ==",
"dev": true
},
"node_modules/path-type": {
@ -12410,12 +12326,12 @@
}
},
"node_modules/qs": {
"version": "6.13.0",
"resolved": "https://registry.npmjs.org/qs/-/qs-6.13.0.tgz",
"integrity": "sha512-+38qI9SOr8tfZ4QmJNplMUxqjbe7LKvvZgWdExBOmd+egZTtjLB67Gu0HRX3u/XOq7UU2Nx6nsjvS16Z9uwfpg==",
"version": "6.11.0",
"resolved": "https://registry.npmjs.org/qs/-/qs-6.11.0.tgz",
"integrity": "sha512-MvjoMCJwEarSbUYk5O+nmoSzSutSsTwF85zcHPQ9OrlFoZOYIjaqBAJIqIXjptyD5vThxGq52Xu/MaJzRkIk4Q==",
"dev": true,
"dependencies": {
"side-channel": "^1.0.6"
"side-channel": "^1.0.4"
},
"engines": {
"node": ">=0.6"
@ -12990,9 +12906,9 @@
}
},
"node_modules/send": {
"version": "0.19.0",
"resolved": "https://registry.npmjs.org/send/-/send-0.19.0.tgz",
"integrity": "sha512-dW41u5VfLXu8SJh5bwRmyYUbAoSB3c9uQh6L8h/KtsFREPWpbX1lrljJo186Jc4nmci/sGUZ9a0a0J2zgfq2hw==",
"version": "0.18.0",
"resolved": "https://registry.npmjs.org/send/-/send-0.18.0.tgz",
"integrity": "sha512-qqWzuOjSFOuqPjFe4NOsMLafToQQwBSOEpS+FwEt3A2V3vKubTquT3vmLTQpFgMXp8AlFWFuP1qKaJZOtPpVXg==",
"dev": true,
"dependencies": {
"debug": "2.6.9",
@ -13134,29 +13050,20 @@
"dev": true
},
"node_modules/serve-static": {
"version": "1.16.2",
"resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.16.2.tgz",
"integrity": "sha512-VqpjJZKadQB/PEbEwvFdO43Ax5dFBZ2UECszz8bQ7pi7wt//PWe1P6MN7eCnjsatYtBT6EuiClbjSWP2WrIoTw==",
"version": "1.15.0",
"resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.15.0.tgz",
"integrity": "sha512-XGuRDNjXUijsUL0vl6nSD7cwURuzEgglbOaFuZM9g3kwDXOWVTck0jLzjPzGD+TazWbboZYu52/9/XPdUgne9g==",
"dev": true,
"dependencies": {
"encodeurl": "~2.0.0",
"encodeurl": "~1.0.2",
"escape-html": "~1.0.3",
"parseurl": "~1.3.3",
"send": "0.19.0"
"send": "0.18.0"
},
"engines": {
"node": ">= 0.8.0"
}
},
"node_modules/serve-static/node_modules/encodeurl": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz",
"integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==",
"dev": true,
"engines": {
"node": ">= 0.8"
}
},
"node_modules/set-function-length": {
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.2.tgz",
@ -13320,16 +13227,16 @@
}
},
"node_modules/socket.io": {
"version": "4.8.1",
"resolved": "https://registry.npmjs.org/socket.io/-/socket.io-4.8.1.tgz",
"integrity": "sha512-oZ7iUCxph8WYRHHcjBEc9unw3adt5CmSNlppj/5Q4k2RIrhl8Z5yY2Xr4j9zj0+wzVZ0bxmYoGSzKJnRl6A4yg==",
"version": "4.7.5",
"resolved": "https://registry.npmjs.org/socket.io/-/socket.io-4.7.5.tgz",
"integrity": "sha512-DmeAkF6cwM9jSfmp6Dr/5/mfMwb5Z5qRrSXLpo3Fq5SqyU8CMF15jIN4ZhfSwu35ksM1qmHZDQ/DK5XTccSTvA==",
"dev": true,
"dependencies": {
"accepts": "~1.3.4",
"base64id": "~2.0.0",
"cors": "~2.8.5",
"debug": "~4.3.2",
"engine.io": "~6.6.0",
"engine.io": "~6.5.2",
"socket.io-adapter": "~2.5.2",
"socket.io-parser": "~4.2.4"
},
@ -14545,9 +14452,9 @@
}
},
"node_modules/webpack-dev-server/node_modules/http-proxy-middleware": {
"version": "2.0.7",
"resolved": "https://registry.npmjs.org/http-proxy-middleware/-/http-proxy-middleware-2.0.7.tgz",
"integrity": "sha512-fgVY8AV7qU7z/MmXJ/rxwbrtQH4jBQ9m7kp3llF0liB7glmFeVZFBepQb32T3y8n8k2+AEYuMPCpinYW+/CuRA==",
"version": "2.0.6",
"resolved": "https://registry.npmjs.org/http-proxy-middleware/-/http-proxy-middleware-2.0.6.tgz",
"integrity": "sha512-ya/UeJ6HVBYxrgYotAZo1KvPWlgB48kUJLDePFeneHsVujFaW5WNj2NgWCAE//B1Dl02BIfYlpNgBy8Kf8Rjmw==",
"dev": true,
"dependencies": {
"@types/http-proxy": "^1.17.8",
@ -14924,15 +14831,6 @@
}
}
},
"node_modules/xmlbuilder": {
"version": "12.0.0",
"resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-12.0.0.tgz",
"integrity": "sha512-lMo8DJ8u6JRWp0/Y4XLa/atVDr75H9litKlb2E5j3V3MesoL50EBgZDWoLT3F/LztVnG67GjPXLZpqcky/UMnQ==",
"dev": true,
"engines": {
"node": ">=6.0"
}
},
"node_modules/y18n": {
"version": "5.0.8",
"resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz",

View File

@ -1,6 +1,6 @@
{
"name": "og-webconsole",
"version": "0.5.0",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve",
@ -20,13 +20,9 @@
"@angular/platform-browser": "^18.0.0",
"@angular/platform-browser-dynamic": "^18.0.0",
"@angular/router": "^18.0.0",
"@ngx-translate/core": "^16.0.3",
"@ngx-translate/http-loader": "^16.0.0",
"@swimlane/ngx-charts": "^20.5.0",
"jwt-decode": "^4.0.0",
"ngx-joyride": "^2.5.0",
"ngx-toastr": "^19.0.0",
"papaparse": "^5.4.1",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "^0.14.6"
@ -38,14 +34,12 @@
"@angular/localize": "^18.1.0",
"@ngx-env/builder": "^18.0.1",
"@types/jasmine": "~5.1.0",
"@types/papaparse": "^5.3.15",
"jasmine-core": "~5.1.0",
"karma": "~6.4.0",
"karma-chrome-launcher": "~3.2.0",
"karma-coverage": "~2.2.0",
"karma-jasmine": "~5.1.0",
"karma-jasmine-html-reporter": "~2.1.0",
"karma-junit-reporter": "^2.0.1",
"typescript": "~5.4.5"
}
}

View File

@ -13,78 +13,59 @@ import { PXEimagesComponent } from './components/ogboot/pxe-images/pxe-images.co
import { PxeComponent } from './components/ogboot/pxe/pxe.component';
import { PxeBootFilesComponent } from './components/ogboot/pxe-boot-files/pxe-boot-files.component';
import {OgbootStatusComponent} from "./components/ogboot/ogboot-status/ogboot-status.component";
import { OgdhcpComponent } from './components/ogdhcp/ogdhcp.component';
import { OgDhcpSubnetsComponent } from './components/ogdhcp/og-dhcp-subnets/og-dhcp-subnets.component';
import { CalendarComponent } from "./components/calendar/calendar.component";
import { CommandsComponent } from './components/commands/main-commands/commands.component';
import { CommandsGroupsComponent } from './components/commands/commands-groups/commands-groups.component';
import { CommandsTaskComponent } from './components/commands/commands-task/commands-task.component';
import { TaskLogsComponent } from './components/commands/commands-task/task-logs/task-logs.component';
import { StatusComponent } from "./components/ogdhcp/og-dhcp-subnets/status/status.component";
import { ClientMainViewComponent } from './components/groups/components/client-main-view/client-main-view.component';
import { ImagesComponent } from './components/images/images.component';
import { RestoreImageComponent } from './components/groups/components/client-main-view/restore-image/restore-image.component';
import {SoftwareComponent} from "./components/software/software.component";
import {SoftwareProfileComponent} from "./components/software-profile/software-profile.component";
import {OperativeSystemComponent} from "./components/operative-system/operative-system.component";
import {
PartitionAssistantComponent
} from "./components/groups/components/client-main-view/partition-assistant/partition-assistant.component";
import {RepositoriesComponent} from "./components/repositories/repositories.component";
import {
CreateClientImageComponent
} from "./components/groups/components/client-main-view/create-image/create-image.component";
import {
DeployImageComponent
} from "./components/groups/components/client-main-view/deploy-image/deploy-image.component";
import {
MainRepositoryViewComponent
} from "./components/repositories/main-repository-view/main-repository-view.component";
import {EnvVarsComponent} from "./components/admin/env-vars/env-vars.component";
import {MenusComponent} from "./components/menus/menus.component";
import {OgDhcpSubnetsComponent} from "./components/ogdhcp/og-dhcp-subnets.component";
import {StatusComponent} from "./components/ogdhcp/status/status.component";
import {
RunScriptAssistantComponent
} from "./components/groups/components/client-main-view/run-script-assistant/run-script-assistant.component";
const routes: Routes = [
{ path: '', redirectTo: 'auth/login', pathMatch: 'full' },
{ path: '', component: MainLayoutComponent,
children: [
{ path: 'dashboard', component: DashboardComponent },
{ path: 'admin', component: AdminComponent },
{ path: 'users', component: UsersComponent },
{ path: 'env-vars', component: EnvVarsComponent },
{ path: 'user-groups', component: RolesComponent },
{ path: 'groups', component: GroupsComponent },
{ path: 'pxe-images', component: PXEimagesComponent },
{ path: 'pxe', component: PxeComponent },
{ path: 'pxe-boot-file', component: PxeBootFilesComponent },
{ path: 'ogboot-status', component: OgbootStatusComponent },
{ path: 'subnets', component: OgDhcpSubnetsComponent },
{ path: 'ogdhcp-status', component: StatusComponent },
{ path: 'commands', component: CommandsComponent },
{ path: 'commands-groups', component: CommandsGroupsComponent },
{ path: 'commands-task', component: CommandsTaskComponent },
{ path: 'commands-logs', component: TaskLogsComponent },
{ path: 'calendars', component: CalendarComponent },
{ path: 'clients/deploy-image', component: DeployImageComponent },
{ path: 'clients/partition-assistant', component: PartitionAssistantComponent },
{ path: 'clients/run-script', component: RunScriptAssistantComponent },
{ path: 'clients/:id', component: ClientMainViewComponent },
{ path: 'clients/:id/create-image', component: CreateClientImageComponent },
{ path: 'repositories', component: RepositoriesComponent },
{ path: 'repository/:id', component: MainRepositoryViewComponent },
{ path: 'software', component: SoftwareComponent },
{ path: 'software-profiles', component: SoftwareProfileComponent },
{ path: 'operative-systems', component: OperativeSystemComponent },
{ path: 'menus', component: MenusComponent },
],
},
{
path: 'auth',
component: AuthLayoutComponent,
children: [
{ path: 'login', component: LoginComponent },
],
},
{ path: '**', component: PageNotFoundComponent },
{
path: '',
component: MainLayoutComponent,
children: [
{ path: 'dashboard', component: DashboardComponent },
{ path: 'admin', component: AdminComponent },
{ path: 'users', component: UsersComponent },
{ path: 'user-groups', component: RolesComponent },
{ path: 'groups', component: GroupsComponent },
{ path: 'pxe-images', component: PXEimagesComponent },
{ path: 'pxe', component: PxeComponent },
{ path: 'pxe-boot-file', component: PxeBootFilesComponent },
{ path: 'ogboot-status', component: OgbootStatusComponent },
{ path: 'dhcp', component: OgdhcpComponent },
{ path: 'subnets', component: OgDhcpSubnetsComponent },
{ path: 'ogdhcp-status', component: StatusComponent },
{ path: 'commands', component: CommandsComponent },
{ path: 'commands-groups', component: CommandsGroupsComponent },
{ path: 'commands-task', component: CommandsTaskComponent },
{ path: 'commands-logs', component: TaskLogsComponent },
{ path: 'calendars', component: CalendarComponent },
{ path: 'client/:id', component: ClientMainViewComponent },
{ path: 'images', component: ImagesComponent },
{ path: 'restore-image', component: RestoreImageComponent},
{ path: 'software', component: SoftwareComponent },
{ path: 'software-profiles', component: SoftwareProfileComponent },
{ path: 'operative-systems', component: OperativeSystemComponent },
],
},
{
path: 'auth',
component: AuthLayoutComponent,
children: [
{ path: 'login', component: LoginComponent },
],
},
{ path: '**', component: PageNotFoundComponent },
];
@NgModule({

View File

@ -1,23 +1,17 @@
import { TestBed } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { TranslateModule, TranslateService } from '@ngx-translate/core';
import { RouterTestingModule } from '@angular/router/testing'; // Asegúrate de que está importado
import { AppComponent } from './app.component';
describe('AppComponent', () => {
let translateService: TranslateService;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [
RouterTestingModule,
TranslateModule.forRoot()
RouterTestingModule
],
declarations: [
AppComponent
],
}).compileComponents();
translateService = TestBed.inject(TranslateService);
});
it('should create the app', () => {
@ -26,41 +20,4 @@ describe('AppComponent', () => {
expect(app).toBeTruthy();
});
it(`should have as title 'ogWebconsole'`, () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app.title).toEqual('ogWebconsole');
});
it('should set the language from localStorage on creation', () => {
spyOn(localStorage, 'getItem').and.returnValue('en'); // Simula que el idioma guardado es "en"
spyOn(translateService, 'use');
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
expect(localStorage.getItem).toHaveBeenCalledWith('language');
expect(translateService.use).toHaveBeenCalledWith('en');
});
it('should default to Spanish if no language is saved in localStorage', () => {
spyOn(localStorage, 'getItem').and.returnValue(null); // Simula que no hay idioma guardado
spyOn(translateService, 'use');
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
expect(localStorage.getItem).toHaveBeenCalledWith('language');
expect(translateService.use).toHaveBeenCalledWith('es');
});
it('should set language to Spanish in sessionStorage on ngOnInit', () => {
spyOn(sessionStorage, 'setItem');
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
app.ngOnInit();
expect(sessionStorage.setItem).toHaveBeenCalledWith('language', 'es');
});
});

View File

@ -1,5 +1,4 @@
import { Component } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
@Component({
selector: 'app-root',
@ -8,11 +7,4 @@ import { TranslateService } from '@ngx-translate/core';
})
export class AppComponent {
title = 'ogWebconsole';
constructor(private translateService: TranslateService) {
const savedLanguage = localStorage.getItem('language') || 'es';
this.translateService.use(savedLanguage);
}
ngOnInit() {
sessionStorage.setItem('language', 'es');
}
}

View File

@ -1,5 +1,4 @@
import { NgModule, CUSTOM_ELEMENTS_SCHEMA, LOCALE_ID, APP_INITIALIZER } from '@angular/core';
import { ConfigService } from './services/config.service';
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
@ -9,7 +8,7 @@ import { HeaderComponent } from './layout/header/header.component';
import { SidebarComponent } from './layout/sidebar/sidebar.component';
import { LoginComponent } from './components/login/login.component';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { HTTP_INTERCEPTORS, HttpClient, provideHttpClient, withInterceptorsFromDi } from '@angular/common/http';
import { HTTP_INTERCEPTORS, provideHttpClient, withInterceptorsFromDi } from '@angular/common/http';
import { CustomInterceptor } from './core/services/custom.interceptor';
import { provideAnimationsAsync } from '@angular/platform-browser/animations/async';
import { MatToolbarModule } from '@angular/material/toolbar';
@ -26,7 +25,6 @@ import { MatListModule } from '@angular/material/list';
import { UsersComponent } from './components/admin/users/users/users.component';
import { RolesComponent } from './components/admin/roles/roles/roles.component';
import { MatTableModule } from '@angular/material/table';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { MatDialogModule } from '@angular/material/dialog';
import { AddUserModalComponent } from './components/admin/users/users/add-user-modal/add-user-modal.component';
import { MatSelectModule } from '@angular/material/select';
@ -34,14 +32,17 @@ import { AddRoleModalComponent } from './components/admin/roles/roles/add-role-m
import { ChangePasswordModalComponent } from './components/admin/users/users/change-password-modal/change-password-modal.component';
import { GroupsComponent } from './components/groups/groups.component';
import { MatDividerModule } from '@angular/material/divider';
import { CreateOrganizationalUnitComponent } from './components/groups/shared/organizational-units/create-organizational-unit/create-organizational-unit.component';
import { MatStepperModule } from '@angular/material/stepper';
import { MatSlideToggleModule } from '@angular/material/slide-toggle';
import { CreateClientComponent } from './components/groups/shared/clients/create-client/create-client.component';
import { DeleteModalComponent } from './shared/delete_modal/delete-modal/delete-modal.component';
import { EditOrganizationalUnitComponent } from './components/groups/shared/organizational-units/edit-organizational-unit/edit-organizational-unit.component';
import { EditClientComponent } from './components/groups/shared/clients/edit-client/edit-client.component';
import { ClassroomViewComponent } from './components/groups/shared/classroom-view/classroom-view.component';
import { MatProgressSpinner } from "@angular/material/progress-spinner";
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { MatMenu, MatMenuItem, MatMenuTrigger } from "@angular/material/menu";
import { MatAutocomplete, MatAutocompleteTrigger } from "@angular/material/autocomplete";
import {MatAutocomplete, MatAutocompleteTrigger} from "@angular/material/autocomplete";
import { MatChip, MatChipListbox, MatChipOption, MatChipSet, MatChipsModule } from "@angular/material/chips";
import { ClientViewComponent } from './components/groups/shared/client-view/client-view.component';
import { MatTab, MatTabGroup } from "@angular/material/tabs";
@ -51,6 +52,7 @@ import { DragDropModule } from '@angular/cdk/drag-drop';
import { ToastrModule } from 'ngx-toastr';
import { ShowOrganizationalUnitComponent } from './components/groups/shared/organizational-units/show-organizational-unit/show-organizational-unit.component';
import { MatGridList, MatGridTile } from "@angular/material/grid-list";
import { TreeViewComponent } from './components/groups/shared/tree-view/tree-view.component';
import {
MatNestedTreeNode,
MatTree,
@ -63,6 +65,7 @@ import { LegendComponent } from './components/groups/shared/legend/legend.compon
import { ClassroomViewDialogComponent } from './components/groups/shared/classroom-view/classroom-view-modal';
import { MatPaginator } from "@angular/material/paginator";
import { SaveFiltersDialogComponent } from './components/groups/shared/save-filters-dialog/save-filters-dialog.component';
import { AcctionsModalComponent } from './components/groups/shared/acctions-modal/acctions-modal.component';
import { PXEimagesComponent } from './components/ogboot/pxe-images/pxe-images.component';
import { CreatePXEImageComponent } from './components/ogboot/pxe-images/create-image/create-image/create-image.component';
import { InfoImageComponent } from './components/ogboot/pxe-images/info-image/info-image/info-image.component';
@ -71,7 +74,12 @@ import { CreatePxeTemplateComponent } from './components/ogboot/pxe/create-pxeTe
import { PxeBootFilesComponent } from './components/ogboot/pxe-boot-files/pxe-boot-files.component';
import { MatExpansionPanel, MatExpansionPanelDescription, MatExpansionPanelTitle } from "@angular/material/expansion";
import { OgbootStatusComponent } from './components/ogboot/ogboot-status/ogboot-status.component';
import { CreatePxeBootFileComponent } from './components/ogboot/pxe-boot-files/create-pxeBootFile/create-pxe-boot-file/create-pxe-boot-file.component';
import { NgxChartsModule } from '@swimlane/ngx-charts';
import { OgdhcpComponent } from './components/ogdhcp/ogdhcp.component';
import { OgDhcpSubnetsComponent } from './components/ogdhcp/og-dhcp-subnets/og-dhcp-subnets.component';
import { CreateSubnetComponent } from './components/ogdhcp/og-dhcp-subnets/create-subnet/create-subnet.component';
import { AddClientsToSubnetComponent } from './components/ogdhcp/og-dhcp-subnets/add-clients-to-subnet/add-clients-to-subnet.component';
import { CommandsComponent } from './components/commands/main-commands/commands.component';
import { CommandDetailComponent } from './components/commands/main-commands/detail-command/command-detail.component';
import { CreateCommandComponent } from './components/commands/main-commands/create-command/create-command.component';
@ -79,7 +87,7 @@ import { MatDatepickerModule } from '@angular/material/datepicker';
import { MatNativeDateModule } from '@angular/material/core';
import { CalendarComponent } from './components/calendar/calendar.component';
import { CreateCalendarComponent } from './components/calendar/create-calendar/create-calendar.component';
import { MatRadioButton, MatRadioGroup } from "@angular/material/radio";
import {MatRadioButton, MatRadioGroup} from "@angular/material/radio";
import { CreateCalendarRuleComponent } from './components/calendar/create-calendar-rule/create-calendar-rule.component';
import { CommandsGroupsComponent } from './components/commands/commands-groups/commands-groups.component';
import { CommandsTaskComponent } from './components/commands/commands-task/commands-task.component';
@ -87,13 +95,18 @@ import { CreateCommandGroupComponent } from './components/commands/commands-grou
import { DetailCommandGroupComponent } from './components/commands/commands-groups/detail-command-group/detail-command-group.component';
import { CreateTaskComponent } from './components/commands/commands-task/create-task/create-task.component';
import { DetailTaskComponent } from './components/commands/commands-task/detail-task/detail-task.component';
import { ClientTabViewComponent } from './components/groups/components/client-tab-view/client-tab-view.component';
import { AdvancedSearchComponent } from './components/groups/components/advanced-search/advanced-search.component';
import { TaskLogsComponent } from './components/commands/commands-task/task-logs/task-logs.component';
import { MatSliderModule } from '@angular/material/slider';
import { OrganizationalUnitTabViewComponent } from './components/groups/components/organizational-unit-tab-view/organizational-unit-tab-view.component';
import { ServerInfoDialogComponent } from './components/ogdhcp/og-dhcp-subnets/server-info-dialog/server-info-dialog.component';
import { StatusComponent } from './components/ogdhcp/og-dhcp-subnets/status/status.component';
import {MatSliderModule} from '@angular/material/slider';
import { ClientMainViewComponent } from './components/groups/components/client-main-view/client-main-view.component';
import { ImagesComponent } from './components/images/images.component';
import { CreateImageComponent } from './components/images/create-image/create-image.component';
import { CreateClientImageComponent } from './components/groups/components/client-main-view/create-image/create-image.component';
import { PartitionAssistantComponent } from './components/groups/components/client-main-view/partition-assistant/partition-assistant.component';
import { RestoreImageComponent } from './components/groups/components/client-main-view/restore-image/restore-image.component';
import { SoftwareComponent } from './components/software/software.component';
import { CreateSoftwareComponent } from './components/software/create-software/create-software.component';
import { SoftwareProfileComponent } from './components/software-profile/software-profile.component';
@ -101,59 +114,8 @@ import { CreateSoftwareProfileComponent } from './components/software-profile/cr
import { OperativeSystemComponent } from './components/operative-system/operative-system.component';
import { CreateOperativeSystemComponent } from './components/operative-system/create-operative-system/create-operative-system.component';
import { ShowTemplateContentComponent } from './components/ogboot/pxe/show-template-content/show-template-content.component';
import { RepositoriesComponent } from './components/repositories/repositories.component';
import { ManageRepositoryComponent } from './components/repositories/manage-repository/manage-repository.component';
import { ExecuteCommandComponent } from './components/commands/main-commands/execute-command/execute-command.component';
import { DeployImageComponent } from './components/groups/components/client-main-view/deploy-image/deploy-image.component';
import { MainRepositoryViewComponent } from './components/repositories/main-repository-view/main-repository-view.component';
import { ExecuteCommandOuComponent } from './components/groups/shared/execute-command-ou/execute-command-ou.component';
import { JoyrideModule } from 'ngx-joyride';
import { TranslateModule, TranslateLoader } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
import { EnvVarsComponent } from './components/admin/env-vars/env-vars.component';
import { MatSortModule } from '@angular/material/sort';
import { MenusComponent } from './components/menus/menus.component';
import { CreateMenuComponent } from './components/menus/create-menu/create-menu.component';
import { CreateMultipleClientComponent } from './components/groups/shared/clients/create-multiple-client/create-multiple-client.component';
import { ExportImageComponent } from './components/images/export-image/export-image.component';
import { ImportImageComponent } from "./components/repositories/import-image/import-image.component";
import { LoadingComponent } from './shared/loading/loading.component';
import { InputDialogComponent } from './components/commands/commands-task/task-logs/input-dialog/input-dialog.component';
import { ManageOrganizationalUnitComponent } from './components/groups/shared/organizational-units/manage-organizational-unit/manage-organizational-unit.component';
import { BackupImageComponent } from './components/repositories/backup-image/backup-image.component';
import { ServerInfoDialogComponent } from "./components/ogdhcp/server-info-dialog/server-info-dialog.component";
import { StatusComponent } from "./components/ogdhcp/status/status.component";
import { OgDhcpSubnetsComponent } from "./components/ogdhcp/og-dhcp-subnets.component";
import { CreateSubnetComponent } from "./components/ogdhcp/create-subnet/create-subnet.component";
import { AddClientsToSubnetComponent } from "./components/ogdhcp/add-clients-to-subnet/add-clients-to-subnet.component";
import { ShowClientsComponent } from './components/ogdhcp/show-clients/show-clients.component';
import { OperationResultDialogComponent } from './components/ogdhcp/operation-result-dialog/operation-result-dialog.component';
import { ManageClientComponent } from './components/groups/shared/clients/manage-client/manage-client.component';
import { ConvertImageComponent } from './components/repositories/convert-image/convert-image.component';
import { registerLocaleData } from '@angular/common';
import localeEs from '@angular/common/locales/es';
import { GlobalStatusComponent } from './components/global-status/global-status.component';
import { ShowMonoliticImagesComponent } from './components/repositories/show-monolitic-images/show-monolitic-images.component';
import { StatusTabComponent } from './components/global-status/status-tab/status-tab.component';
import { ConvertImageToVirtualComponent } from './components/repositories/convert-image-to-virtual/convert-image-to-virtual.component';
import { RunScriptAssistantComponent } from './components/groups/components/client-main-view/run-script-assistant/run-script-assistant.component';
import {
SaveScriptComponent
} from "./components/groups/components/client-main-view/run-script-assistant/save-script/save-script.component";
import { EditImageComponent } from './components/repositories/edit-image/edit-image.component';
import { ShowGitImagesComponent } from './components/repositories/show-git-images/show-git-images.component';
import { RenameImageComponent } from './components/repositories/rename-image/rename-image.component';
export function HttpLoaderFactory(http: HttpClient) {
return new TranslateHttpLoader(http, './locale/', '.json');
}
export function initializeApp(configService: ConfigService) {
return () => configService.loadConfig();
}
registerLocaleData(localeEs, 'es-ES');
import { AddClientsToPxeComponent } from './components/ogboot/pxe/add-clients-to-pxe/add-clients-to-pxe.component';
import { ClientsComponent } from './components/ogboot/pxe/clients/clients.component';
@NgModule({
declarations: [
AppComponent,
@ -170,14 +132,19 @@ registerLocaleData(localeEs, 'es-ES');
AddRoleModalComponent,
ChangePasswordModalComponent,
GroupsComponent,
ManageClientComponent,
CreateOrganizationalUnitComponent,
CreateClientComponent,
DeleteModalComponent,
EditOrganizationalUnitComponent,
EditClientComponent,
ClassroomViewComponent,
ClientViewComponent,
ShowOrganizationalUnitComponent,
TreeViewComponent,
LegendComponent,
ClassroomViewDialogComponent,
SaveFiltersDialogComponent,
AcctionsModalComponent,
PXEimagesComponent,
CreatePXEImageComponent,
InfoImageComponent,
@ -185,6 +152,8 @@ registerLocaleData(localeEs, 'es-ES');
CreatePxeTemplateComponent,
PxeBootFilesComponent,
OgbootStatusComponent,
CreatePxeBootFileComponent,
OgdhcpComponent,
OgDhcpSubnetsComponent,
CreateSubnetComponent,
AddClientsToSubnetComponent,
@ -193,7 +162,6 @@ registerLocaleData(localeEs, 'es-ES');
CreateCommandComponent,
CalendarComponent,
CreateCalendarComponent,
CreateClientImageComponent,
CreateCalendarRuleComponent,
CommandsGroupsComponent,
CommandsTaskComponent,
@ -201,13 +169,17 @@ registerLocaleData(localeEs, 'es-ES');
DetailCommandGroupComponent,
CreateTaskComponent,
DetailTaskComponent,
ClientTabViewComponent,
AdvancedSearchComponent,
TaskLogsComponent,
OrganizationalUnitTabViewComponent,
ServerInfoDialogComponent,
StatusComponent,
ClientMainViewComponent,
ImagesComponent,
CreateImageComponent,
PartitionAssistantComponent,
RestoreImageComponent,
SoftwareComponent,
CreateSoftwareComponent,
SoftwareProfileComponent,
@ -215,85 +187,47 @@ registerLocaleData(localeEs, 'es-ES');
OperativeSystemComponent,
CreateOperativeSystemComponent,
ShowTemplateContentComponent,
RepositoriesComponent,
ManageRepositoryComponent,
ExecuteCommandComponent,
ExecuteCommandOuComponent,
DeployImageComponent,
MainRepositoryViewComponent,
ExecuteCommandOuComponent,
EnvVarsComponent,
MenusComponent,
CreateMenuComponent,
CreateMultipleClientComponent,
ExportImageComponent,
ImportImageComponent,
LoadingComponent,
InputDialogComponent,
ManageOrganizationalUnitComponent,
BackupImageComponent,
ShowClientsComponent,
OperationResultDialogComponent,
ConvertImageComponent,
GlobalStatusComponent,
ShowMonoliticImagesComponent,
StatusTabComponent,
ConvertImageToVirtualComponent,
RunScriptAssistantComponent,
SaveScriptComponent,
EditImageComponent,
ShowGitImagesComponent,
RenameImageComponent
AddClientsToPxeComponent,
ClientsComponent,
],
bootstrap: [AppComponent],
imports: [BrowserModule,
AppRoutingModule,
FormsModule,
ReactiveFormsModule,
MatToolbarModule,
MatIconModule,
MatButtonToggleModule,
MatButtonModule,
MatSidenavModule,
NoopAnimationsModule,
MatCardModule,
MatCheckboxModule,
MatFormFieldModule,
MatInputModule,
MatListModule,
MatTableModule,
MatDialogModule,
MatSelectModule,
MatDividerModule,
MatProgressBarModule,
MatStepperModule,
DragDropModule,
MatSlideToggleModule, MatMenu, MatMenuTrigger, MatMenuItem, MatAutocomplete, MatChipListbox, MatChipOption, MatChipSet, MatChipsModule, MatChip, MatProgressSpinner, MatTabGroup, MatTab, MatTooltip,
MatExpansionModule,
NgxChartsModule,
MatDatepickerModule,
MatNativeDateModule,
MatSliderModule,
MatSortModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: HttpLoaderFactory,
deps: [HttpClient]
}
}),
JoyrideModule.forRoot(),
ToastrModule.forRoot(
{
timeOut: 5000,
positionClass: 'toast-bottom-right',
preventDuplicates: true,
progressBar: true,
progressAnimation: 'increasing',
closeButton: true
}
), MatGridList, MatTree, MatTreeNode, MatNestedTreeNode, MatTreeNodeToggle, MatTreeNodeDef, MatTreeNodePadding, MatTreeNodeOutlet, MatPaginator, MatGridTile, MatExpansionPanel, MatExpansionPanelTitle, MatExpansionPanelDescription, MatRadioGroup, MatRadioButton, MatAutocompleteTrigger
],
imports: [BrowserModule,
AppRoutingModule,
FormsModule,
ReactiveFormsModule,
MatToolbarModule,
MatIconModule,
MatButtonModule,
MatSidenavModule,
NoopAnimationsModule,
MatCardModule,
MatCheckboxModule,
MatFormFieldModule,
MatInputModule,
MatListModule,
MatTableModule,
MatDialogModule,
MatSelectModule,
MatDividerModule,
MatStepperModule,
DragDropModule,
MatSlideToggleModule, MatMenu, MatMenuTrigger, MatMenuItem, MatAutocomplete, MatChipListbox, MatChipOption, MatChipSet, MatChipsModule, MatChip, MatProgressSpinner, MatTabGroup, MatTab, MatTooltip,
MatExpansionModule,
NgxChartsModule,
MatDatepickerModule,
MatNativeDateModule,
MatSliderModule,
ToastrModule.forRoot(
{
timeOut: 5000,
positionClass: 'toast-bottom-right',
preventDuplicates: true,
progressBar: true,
progressAnimation: 'increasing',
closeButton: true
}
), MatGridList, MatTree, MatTreeNode, MatNestedTreeNode, MatTreeNodeToggle, MatTreeNodeDef, MatTreeNodePadding, MatTreeNodeOutlet, MatPaginator, MatGridTile, MatExpansionPanel, MatExpansionPanelTitle, MatExpansionPanelDescription, MatRadioGroup, MatRadioButton, MatAutocompleteTrigger
],
schemas: [
CUSTOM_ELEMENTS_SCHEMA,
],
@ -303,16 +237,8 @@ registerLocaleData(localeEs, 'es-ES');
useClass: CustomInterceptor,
multi: true
},
{ provide: LOCALE_ID, useValue: 'es-ES' },
provideAnimationsAsync(),
provideHttpClient(withInterceptorsFromDi()),
ConfigService,
{
provide: APP_INITIALIZER,
useFactory: initializeApp,
deps: [ConfigService],
multi: true
}
provideHttpClient(withInterceptorsFromDi())
],
})
export class AppModule { }

View File

@ -14,6 +14,16 @@
margin: 0 10px;
}
/* Estilos de los botones */
button {
height: 150px;
width: 150px;
margin: 5px;
padding: 5px;
cursor: pointer;
transition: all 0.3s;
}
/* Estilos del texto debajo de los botones */
span{
margin: 0;

View File

@ -1,10 +1,10 @@
<div class="container">
<button class="action-button" routerLink="/users">
<button mat-fab color="primary" class="fab-button" routerLink="/users">
<mat-icon>group</mat-icon>
<span>{{ 'labelUsers' | translate }}</span>
<span i18n="@@labelUsers">Usuarios</span>
</button>
<button class="action-button" routerLink="/user-groups">
<button mat-fab color="primary" class="fab-button" routerLink="/user-groups">
<mat-icon>admin_panel_settings</mat-icon>
<span>{{ 'labelRoles' | translate }}</span>
<span i18n="@@labelRoles">Roles</span>
</button>
</div>

View File

@ -3,46 +3,55 @@ import { RouterTestingModule } from '@angular/router/testing';
import { AdminComponent } from './admin.component';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { TranslateModule } from '@ngx-translate/core';
import { Router } from '@angular/router';
import { By } from '@angular/platform-browser';
describe('AdminComponent', () => {
let component: AdminComponent;
let fixture: ComponentFixture<AdminComponent>;
let router: Router;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [AdminComponent],
imports: [
RouterTestingModule,
MatButtonModule,
MatIconModule,
TranslateModule.forRoot()
RouterTestingModule, // Importa RouterTestingModule para manejar routerLink
MatButtonModule, // Importa MatButtonModule para botones
MatIconModule // Importa MatIconModule para iconos
]
}).compileComponents();
router = TestBed.inject(Router);
});
beforeEach(() => {
fixture = TestBed.createComponent(AdminComponent);
component = fixture.componentInstance;
fixture.detectChanges();
fixture.detectChanges(); // Detecta cambios para renderizar el componente
});
it('debería crear el componente', () => {
expect(component).toBeTruthy();
});
it('debería renderizar dos botones', () => {
const buttons = fixture.nativeElement.querySelectorAll('button');
expect(buttons.length).toBe(2);
it('debería contener dos botones', () => {
const buttons = fixture.debugElement.queryAll(By.css('button'));
expect(buttons.length).toBe(2); // Verifica que hay dos botones
});
it('debería tener un botón con routerLink a "/users"', () => {
const button = fixture.nativeElement.querySelector('button[routerLink="/users"]');
expect(button).toBeTruthy();
expect(button.querySelector('mat-icon').textContent.trim()).toBe('group');
it('el primer botón debería tener el texto "Usuarios"', () => {
const firstButton = fixture.debugElement.query(By.css('.fab-button:first-child'));
expect(firstButton.nativeElement.textContent).toContain('Usuarios'); // Verifica que el texto sea "Usuarios"
});
it('el segundo botón debería tener el texto "Roles"', () => {
const secondButton = fixture.debugElement.query(By.css('.fab-button:last-child'));
expect(secondButton.nativeElement.textContent).toContain('Roles'); // Verifica que el texto sea "Roles"
});
it('el primer botón debería tener el routerLink correcto', () => {
const firstButton = fixture.debugElement.query(By.css('.fab-button:first-child'));
expect(firstButton.nativeElement.getAttribute('ng-reflect-router-link')).toBe('/users'); // Verifica el routerLink
});
it('el segundo botón debería tener el routerLink correcto', () => {
const secondButton = fixture.debugElement.query(By.css('.fab-button:last-child'));
expect(secondButton.nativeElement.getAttribute('ng-reflect-router-link')).toBe('/user-groups'); // Verifica el routerLink
});
});

View File

@ -1,30 +0,0 @@
.env-settings {
padding: 0rem 1rem 0rem 1rem;
.mat-table {
margin-bottom: 16px;
width: 100%;
}
.value-input {
width: 100%;
}
.actions {
display: flex;
gap: 16px;
justify-content: flex-end;
margin-top: 16px;
}
}
.header-container {
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px;
}
.mat-elevation-z8 {
box-shadow: 0px 0px 0px rgba(0,0,0,0.2);
}

View File

@ -1,33 +0,0 @@
<div class="env-settings">
<div class="header-container">
<div class="header-container-title">
<h2>Editar Variables de Entorno</h2>
</div>
</div>
<mat-table [dataSource]="envVars" class="mat-elevation-z8">
<!-- Nombre de la variable -->
<ng-container matColumnDef="name">
<mat-header-cell *matHeaderCellDef> Variable </mat-header-cell>
<mat-cell *matCellDef="let variable">{{ variable.name }}</mat-cell>
</ng-container>
<!-- Valor de la variable -->
<ng-container matColumnDef="value">
<mat-header-cell *matHeaderCellDef> Valor </mat-header-cell>
<mat-cell *matCellDef="let variable">
<mat-form-field class="value-input">
<input matInput [(ngModel)]="variable.value" />
</mat-form-field>
</mat-cell>
</ng-container>
<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
</mat-table>
<div class="actions">
<button class="action-button" (click)="loadEnvVars()">Recargar</button>
<button class="submit-button" (click)="saveEnvVars()">Guardar Cambios</button>
</div>
</div>

View File

@ -1,71 +0,0 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { EnvVarsComponent } from './env-vars.component';
import { provideHttpClient } from '@angular/common/http';
import { provideHttpClientTesting } from '@angular/common/http/testing';
import { ReactiveFormsModule, FormsModule, FormBuilder } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatDialogModule, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { TranslateModule } from '@ngx-translate/core';
import { ToastrModule, ToastrService } from 'ngx-toastr';
import { DataService } from '../users/users/data.service';
import { MatTableModule } from '@angular/material/table';
import { ConfigService } from '@services/config.service';
describe('EnvVarsComponent', () => {
let component: EnvVarsComponent;
let fixture: ComponentFixture<EnvVarsComponent>;
beforeEach(async () => {
const mockConfigService = {
apiUrl: 'http://mock-api-url'
};
await TestBed.configureTestingModule({
declarations: [EnvVarsComponent],
imports: [
ReactiveFormsModule,
FormsModule,
MatDialogModule,
MatFormFieldModule,
MatInputModule,
MatCheckboxModule,
MatButtonModule,
BrowserAnimationsModule,
MatTableModule,
ToastrModule.forRoot(),
TranslateModule.forRoot()
],
providers: [
FormBuilder,
ToastrService,
DataService,
provideHttpClient(),
provideHttpClientTesting(),
{
provide: MatDialogRef,
useValue: {}
},
{
provide: MAT_DIALOG_DATA,
useValue: {}
},
{
provide: ConfigService,
useValue: mockConfigService
}
]
}).compileComponents();
fixture = TestBed.createComponent(EnvVarsComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@ -1,56 +0,0 @@
import { Component } from '@angular/core';
import { HttpClient } from "@angular/common/http";
import { ToastrService } from "ngx-toastr";
import { ConfigService } from '@services/config.service';
@Component({
selector: 'app-env-vars',
templateUrl: './env-vars.component.html',
styleUrl: './env-vars.component.css'
})
export class EnvVarsComponent {
envVars: { name: string; value: string }[] = [];
displayedColumns: string[] = ['name', 'value'];
private apiUrl: string;
constructor(
private http: HttpClient,
private toastService: ToastrService,
private configService: ConfigService
) {
this.apiUrl = `${this.configService.apiUrl}/env-vars`;
}
ngOnInit(): void {
this.loadEnvVars();
}
loadEnvVars(): void {
this.http.get<{ vars: Record<string, string> }>(this.apiUrl).subscribe({
next: (response) => {
this.envVars = Object.entries(response.vars).map(([name, value]) => ({ name, value }));
},
error: (err) => {
console.error('Error al cargar las variables de entorno:', err);
this.toastService.error('No se pudieron cargar las variables de entorno.');
}
});
}
saveEnvVars(): void {
const vars = this.envVars.reduce((acc, variable) => {
acc[variable.name] = variable.value;
return acc;
}, {} as Record<string, string>);
this.http.post(this.apiUrl, { vars }).subscribe({
next: () => {
this.toastService.success('Variables de entorno guardadas correctamente.');
},
error: (err) => {
console.error('Error al guardar las variables de entorno:', err);
this.toastService.error('No se pudieron cargar las variables de entorno.');
}
});
}
}

View File

@ -1,9 +1,7 @@
.full-width {
width: 100%;
}
.form-container {
margin-top: 2em;
padding: 40px;
}
@ -17,24 +15,16 @@
margin-bottom: 16px;
}
.checkbox-group {
.checkbox-group {
margin: 15px 0;
align-items: flex-start;
}
.time-fields {
display: flex;
gap: 15px;
/* Espacio entre los campos */
gap: 15px; /* Espacio entre los campos */
}
.time-field {
flex: 1;
}
.action-container {
display: flex;
justify-content: flex-end;
gap: 1em;
padding: 1.5em;
}

View File

@ -1,22 +1,22 @@
<h1 mat-dialog-title>{{ 'dialogTitleAddRole' | translate }}</h1>
<h1 mat-dialog-title i18n="@@dialogTitleAddRole">Añadir Rol</h1>
<mat-dialog-content class="form-container">
<form [formGroup]="roleForm" class="role-form">
<mat-form-field appearance="fill" class="full-width">
<mat-label>{{ 'labelRoleName' | translate }}</mat-label>
<mat-label i18n="@@labelRoleName">Nombre</mat-label>
<input matInput formControlName="name" required>
</mat-form-field>
<section class="example-section">
<h4>{{ 'sectionTitlePermissions' | translate }}</h4>
<p><mat-checkbox formControlName="superAdmin">{{ 'checkboxSuperAdmin' | translate }}</mat-checkbox></p>
<p><mat-checkbox formControlName="orgAdmin">{{ 'checkboxOrgAdmin' | translate }}</mat-checkbox></p>
<p><mat-checkbox formControlName="orgOperator">{{ 'checkboxOrgOperator' | translate }}</mat-checkbox></p>
<p><mat-checkbox formControlName="orgMinimal">{{ 'checkboxOrgMinimal' | translate }}</mat-checkbox></p>
<p><mat-checkbox formControlName="userRole">{{ 'checkboxUserRole' | translate }}</mat-checkbox></p>
<h4 i18n="@@sectionTitlePermissions">Permisos:</h4>
<p><mat-checkbox formControlName="superAdmin" i18n="@@checkboxSuperAdmin">Super Admin</mat-checkbox></p>
<p><mat-checkbox formControlName="orgAdmin" i18n="@@checkboxOrgAdmin">Admin de Unidad Organizativa</mat-checkbox></p>
<p><mat-checkbox formControlName="orgOperator" i18n="@@checkboxOrgOperator">Operador de Unidad Organizativa</mat-checkbox></p>
<p><mat-checkbox formControlName="orgMinimal" i18n="@@checkboxOrgMinimal">Unidad Organizativa Mínima</mat-checkbox></p>
<p><mat-checkbox formControlName="userRole" i18n="@@checkboxUserRole">Usuario</mat-checkbox></p>
</section>
</form>
</mat-dialog-content>
<mat-dialog-actions class="action-container">
<button class="ordinary-button" (click)="onNoClick()">{{ 'buttonCancel' | translate }}</button>
<button class="submit-button" (click)="onSubmit()">{{ 'buttonAdd' | translate }}</button>
<mat-dialog-actions align="end">
<button mat-button (click)="onNoClick()" i18n="@@buttonCancel">Cancelar</button>
<button mat-button (click)="onSubmit()" i18n="@@buttonAdd">Añadir</button>
</mat-dialog-actions>

View File

@ -4,7 +4,6 @@ import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {DataService} from "../data.service";
import {ToastrService} from "ngx-toastr";
import { ConfigService } from '@services/config.service';
@Component({
selector: 'app-add-role-modal',
@ -12,9 +11,9 @@ import { ConfigService } from '@services/config.service';
styleUrls: ['./add-role-modal.component.css']
})
export class AddRoleModalComponent {
baseUrl: string = import.meta.env.NG_APP_BASE_API_URL;
roleForm: FormGroup<any>;
roleId: string | null = null;
baseUrl: string;
constructor(
public dialogRef: MatDialogRef<AddRoleModalComponent>,
@ -22,10 +21,8 @@ export class AddRoleModalComponent {
private http: HttpClient,
private fb: FormBuilder,
private dataService: DataService,
private toastService: ToastrService,
private configService: ConfigService
private toastService: ToastrService
) {
this.baseUrl = this.configService.apiUrl;
this.roleForm = this.fb.group({
name: ['', Validators.required],
superAdmin: [false],

View File

@ -2,19 +2,15 @@ import { Injectable } from '@angular/core';
import {HttpClient, HttpParams} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
import { ConfigService } from '@services/config.service';
@Injectable({
providedIn: 'root'
})
export class DataService {
baseUrl: string;
private apiUrl: string;
baseUrl: string = import.meta.env.NG_APP_BASE_API_URL;
private apiUrl = `${this.baseUrl}/user-groups?page=1&itemsPerPage=1000`;
constructor(private http: HttpClient, private configService: ConfigService) {
this.baseUrl = this.configService.apiUrl;
this.apiUrl = `${this.baseUrl}/user-groups?page=1&itemsPerPage=1000`;
}
constructor(private http: HttpClient) {}
getUserGroups(filters: { [key: string]: string }): Observable<{ totalItems: any; data: any }> {
const params = new HttpParams({ fromObject: filters });

View File

@ -1,30 +1,21 @@
.header-container {
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px 10px;
border-bottom: 1px solid #ddd;
}
.header-container-title {
flex-grow: 1;
text-align: left;
margin-left: 1em;
}
table {
width: 100%;
margin-top: 50px;
}
.search-container {
.search-container {
display: flex;
justify-content: space-between;
align-items: center;
width: 100%;
margin: 1.5rem 0rem 1.5rem 0rem;
padding: 0 5px;
box-sizing: border-box;
}
.divider {
margin: 20px 0;
}
.search-string {
flex: 2;
padding: 5px;
@ -35,12 +26,20 @@ table {
padding: 5px;
}
.header-container {
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px;
}
.mat-elevation-z8 {
box-shadow: 0px 0px 0px rgba(0, 0, 0, 0.2);
box-shadow: 0px 0px 0px rgba(0,0,0,0.2);
}
.paginator-container {
display: flex;
justify-content: end;
margin-bottom: 30px;
}
}

View File

@ -1,52 +1,39 @@
<div class="header-container">
<div class="header-container-title">
<h2>{{ 'adminRolesTitle' | translate }}</h2>
</div>
<h2 class="title" i18n="@@adminImagesTitle">Administrar Roles</h2>
<div class="images-button-row">
<button class="action-button" (click)="addUser()">
{{ 'addRole' | translate }}
</button>
<button mat-flat-button color="primary" (click)="addUser()">Añadir rol</button>
</div>
</div>
<mat-divider class="divider"></mat-divider>
<div class="search-container">
<mat-form-field appearance="fill" class="search-string">
<mat-label>{{ 'searchRoleLabel' | translate }}</mat-label>
<input matInput placeholder="{{ 'searchPlaceholder' | translate }}" [(ngModel)]="filters['name']"
(keyup.enter)="search()">
<mat-label i18n="@@searchLabel">Buscar nombre de rol</mat-label>
<input matInput placeholder="Búsqueda" [(ngModel)]="filters['name']" (keyup.enter)="search()" i18n-placeholder="@@searchPlaceholder">
<mat-icon matSuffix>search</mat-icon>
<mat-hint>{{ 'searchHint' | translate }}</mat-hint>
<mat-hint i18n="@@searchHint">Pulsar 'enter' para buscar</mat-hint>
</mat-form-field>
</div>
<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
<ng-container *ngFor="let column of columns" [matColumnDef]="column.columnDef">
<th mat-header-cell *matHeaderCellDef> {{ column.header }} </th>
<td mat-cell *matCellDef="let role"> {{ column.cell(role) }} </td>
</ng-container>
<app-loading [isLoading]="loading"></app-loading>
<div *ngIf="!loading">
<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
<ng-container *ngFor="let column of columns" [matColumnDef]="column.columnDef">
<th mat-header-cell *matHeaderCellDef> {{ column.header }} </th>
<td mat-cell *matCellDef="let role"> {{ column.cell(role) }} </td>
</ng-container>
<ng-container matColumnDef="actions">
<th mat-header-cell *matHeaderCellDef style="text-align: center;">{{ 'columnActions' | translate }}</th>
<td mat-cell *matCellDef="let role" style="text-align: center;">
<button mat-icon-button color="primary" (click)="editRole(role)">
<mat-icon>edit</mat-icon>
</button>
<button mat-icon-button color="warn" (click)="deleteRole(role)"
[disabled]="role.permissions.includes('ROLE_SUPER_ADMIN')">
<mat-icon>delete</mat-icon>
</button>
</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
</div>
<ng-container matColumnDef="actions">
<th mat-header-cell *matHeaderCellDef i18n="@@columnActions" style="text-align: center;">Acciones</th>
<td mat-cell *matCellDef="let role" style="text-align: center;">
<button mat-icon-button color="primary" (click)="editRole(role)" i18n="@@editImage"> <mat-icon>edit</mat-icon></button>
<button mat-icon-button color="warn" (click)="deleteRole(role)" i18n="@@buttonDelete" [disabled]="role.permissions.includes('ROLE_SUPER_ADMIN')"><mat-icon>delete</mat-icon></button>
</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
<div class="paginator-container">
<mat-paginator [length]="length" [pageSize]="itemsPerPage" [pageIndex]="page" [pageSizeOptions]="pageSizeOptions"
(page)="onPageChange($event)">
<mat-paginator [length]="length"
[pageSize]="itemsPerPage"
[pageIndex]="page"
[pageSizeOptions]="pageSizeOptions"
(page)="onPageChange($event)">
</mat-paginator>
</div>
</div>

View File

@ -4,15 +4,13 @@ import { MatDialog } from '@angular/material/dialog';
import { HttpClient } from '@angular/common/http';
import { ToastrService } from 'ngx-toastr';
import { DataService } from './data.service';
import { ConfigService } from '@services/config.service';
import { of } from 'rxjs';
import { MatDivider } from '@angular/material/divider';
import { MatFormField } from '@angular/material/form-field';
import { MatLabel } from '@angular/material/form-field';
import { MatIcon } from '@angular/material/icon';
import { MatHint } from '@angular/material/form-field';
import { MatPaginator } from '@angular/material/paginator';
import { TranslateModule } from '@ngx-translate/core';
import { LoadingComponent } from '../../../../shared/loading/loading.component';
describe('RolesComponent', () => {
let component: RolesComponent;
let fixture: ComponentFixture<RolesComponent>;
@ -20,25 +18,21 @@ describe('RolesComponent', () => {
let mockHttpClient: jasmine.SpyObj<HttpClient>;
let mockToastrService: jasmine.SpyObj<ToastrService>;
let mockDataService: jasmine.SpyObj<DataService>;
let mockConfigService: jasmine.SpyObj<ConfigService>;
beforeEach(async () => {
const matDialogSpy = jasmine.createSpyObj('MatDialog', ['open']);
const httpClientSpy = jasmine.createSpyObj('HttpClient', ['get', 'post', 'put', 'delete']);
const toastrServiceSpy = jasmine.createSpyObj('ToastrService', ['success', 'error']);
const dataServiceSpy = jasmine.createSpyObj('DataService', ['getRoles']);
const configServiceSpy = jasmine.createSpyObj('ConfigService', [], { apiUrl: 'http://mock-api-url' });
await TestBed.configureTestingModule({
declarations: [RolesComponent, LoadingComponent],
imports: [MatDivider, MatFormField, MatLabel, MatIcon, MatHint, MatPaginator,
TranslateModule.forRoot()],
declarations: [RolesComponent],
imports: [MatDivider, MatFormField, MatLabel, MatIcon, MatHint, MatPaginator],
providers: [
{ provide: MatDialog, useValue: matDialogSpy },
{ provide: HttpClient, useValue: httpClientSpy },
{ provide: ToastrService, useValue: toastrServiceSpy },
{ provide: DataService, useValue: dataServiceSpy },
{ provide: ConfigService, useValue: configServiceSpy }
{ provide: DataService, useValue: dataServiceSpy }
]
}).compileComponents();
});
@ -50,24 +44,9 @@ describe('RolesComponent', () => {
mockHttpClient = TestBed.inject(HttpClient) as jasmine.SpyObj<HttpClient>;
mockToastrService = TestBed.inject(ToastrService) as jasmine.SpyObj<ToastrService>;
mockDataService = TestBed.inject(DataService) as jasmine.SpyObj<DataService>;
mockConfigService = TestBed.inject(ConfigService) as jasmine.SpyObj<ConfigService>;
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should have a default itemsPerPage value', () => {
expect(component.itemsPerPage).toBeDefined();
});
it('should initialize the dataSource', () => {
expect(component.dataSource).toBeDefined();
});
it('should have a defined columns array', () => {
expect(component.columns).toBeDefined();
expect(component.columns.length).toBeGreaterThan(0);
});
});

View File

@ -1,13 +1,13 @@
import { Component, OnInit } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { MatDialog } from '@angular/material/dialog';
import { AddRoleModalComponent } from './add-role-modal/add-role-modal.component';
import { DeleteModalComponent } from '../../../../shared/delete_modal/delete-modal/delete-modal.component';
import { HttpClient } from '@angular/common/http';
import { ToastrService } from 'ngx-toastr';
import { DataService } from "./data.service";
import { PageEvent } from "@angular/material/paginator";
import { DeleteModalComponent } from '../../../../shared/delete_modal/delete-modal/delete-modal.component';
import { AddRoleModalComponent } from './add-role-modal/add-role-modal.component';
import { ConfigService } from '@services/config.service';
import {DataService} from "./data.service";
import {CreateCalendarComponent} from "../../../calendar/create-calendar/create-calendar.component";
import {PageEvent} from "@angular/material/paginator";
@Component({
selector: 'app-roles',
@ -15,10 +15,10 @@ import { ConfigService } from '@services/config.service';
styleUrls: ['./roles.component.css']
})
export class RolesComponent implements OnInit {
baseUrl: string = this.configService.apiUrl;
baseUrl: string = import.meta.env.NG_APP_BASE_API_URL;
dataSource = new MatTableDataSource<any>();
filters: { [key: string]: string } = {};
loading: boolean = false;
loading:boolean = false;
length: number = 0;
itemsPerPage: number = 10;
page: number = 0;
@ -49,8 +49,7 @@ export class RolesComponent implements OnInit {
public dialog: MatDialog,
private http: HttpClient,
private dataService: DataService,
private toastService: ToastrService,
private configService: ConfigService
private toastService: ToastrService
) {}
ngOnInit() {
@ -58,16 +57,13 @@ export class RolesComponent implements OnInit {
}
search() {
this.loading = true;
this.http.get<any>(`${this.apiUrl}?&page=${this.page + 1}&itemsPerPage=${this.itemsPerPage}`, { params: this.filters }).subscribe(
(data) => {
this.dataSource.data = data['hydra:member'];
this.length = data['hydra:totalItems'];
this.loading = false;
},
(error) => {
console.error('Error fetching roles', error);
this.loading = false;
console.error('Error fetching commands', error);
}
);
}
@ -118,7 +114,7 @@ export class RolesComponent implements OnInit {
});
}
onPageChange(event: PageEvent): void {
onPageChange(event: any): void {
this.page = event.pageIndex;
this.itemsPerPage = event.pageSize;
this.length = event.length;

View File

@ -1,12 +1,30 @@
.user-form {
display: flex;
flex-direction: column;
margin-top: 2rem;
.full-width {
width: 100%;
}
.form-container {
padding: 40px;
}
.action-container {
.form-group {
margin-top: 20px;
margin-bottom: 26px;
}
.full-width {
width: 100%;
margin-bottom: 16px;
}
.checkbox-group {
margin: 15px 0;
align-items: flex-start;
}
.time-fields {
display: flex;
justify-content: flex-end;
gap: 1em;
padding: 1.5em;
}
gap: 15px; /* Espacio entre los campos */
}
.time-field {
flex: 1;
}

View File

@ -1,19 +1,17 @@
<app-loading [isLoading]="loading"></app-loading>
<h1 mat-dialog-title>{{ isEditMode ? ('dialogTitleEditUser' | translate) : ('dialogTitleAddUser' | translate) }}</h1>
<h1 mat-dialog-title i18n="@@dialogTitleAddRole">Añadir Usuario</h1>
<mat-dialog-content class="form-container">
<form [formGroup]="userForm" class="user-form">
<mat-form-field appearance="fill" class="full-width">
<mat-label>{{ 'addUserlabelUsername' | translate }}</mat-label>
<mat-label i18n="@@addUserlabelUsername">Nombre de usuario</mat-label>
<input matInput formControlName="username" required>
</mat-form-field>
<mat-form-field appearance="fill" class="full-width">
<mat-label>{{ 'addUserlabelPassword' | translate }}</mat-label>
<mat-label i18n="@@addUserlabelPassword">Contraseña</mat-label>
<input matInput formControlName="password" type="password" required>
</mat-form-field>
<mat-form-field appearance="fill" class="full-width">
<mat-label>{{ 'labelRole' | translate }}</mat-label>
<mat-label i18n="@@labelRole">Rol</mat-label>
<mat-select formControlName="role" required>
<mat-option *ngFor="let group of userGroups" [value]="group['@id']">
{{ group.name }}
@ -22,25 +20,16 @@
</mat-form-field>
<mat-form-field appearance="fill" class="full-width">
<mat-label>{{ 'labelOrganizationalUnit' | translate }}</mat-label>
<mat-label i18n="@@labelOrganizationalUnit">Unidad organiativa</mat-label>
<mat-select multiple formControlName="organizationalUnits">
<mat-option *ngFor="let unit of organizationalUnits" [value]="unit['@id']">
{{ unit.name }}
</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field appearance="fill" class="full-width">
<mat-label>Vista tarjetas</mat-label>
<mat-select formControlName="groupsView" required>
<mat-option *ngFor="let option of views" [value]="option.value">
{{ option.name }}
{{unit.name}}
</mat-option>
</mat-select>
</mat-form-field>
</form>
</mat-dialog-content>
<mat-dialog-actions class="action-container">
<button class="ordinary-button" (click)="onNoClick()">{{ 'buttonCancel' | translate }}</button>
<button class="submit-button" (click)="onSubmit()" [disabled]="userForm.invalid">{{ isEditMode ? ('buttonEdit' | translate) : ('buttonAdd' | translate) }}</button>
</mat-dialog-actions>
<mat-dialog-actions align="end">
<button mat-button (click)="onNoClick()" i18n="@@buttonCancel">Cancelar</button>
<button mat-button (click)="onSubmit()" i18n="@@buttonAdd">Añadir</button>
</mat-dialog-actions>

View File

@ -1,10 +1,9 @@
import { Component, EventEmitter, Inject, OnInit, Output } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { ToastrService } from "ngx-toastr";
import { HttpClient } from "@angular/common/http";
import { DataService } from "../data.service";
import { ConfigService } from '@services/config.service';
import {ToastrService} from "ngx-toastr";
import {HttpClient} from "@angular/common/http";
import {DataService} from "../data.service";
interface UserGroup {
'@id': string;
@ -18,20 +17,12 @@ interface UserGroup {
styleUrls: ['./add-user-modal.component.css']
})
export class AddUserModalComponent implements OnInit {
baseUrl: string;
baseUrl: string = import.meta.env.NG_APP_BASE_API_URL;
@Output() userAdded = new EventEmitter<void>();
@Output() userEdited = new EventEmitter<void>();
userForm: FormGroup<any>;
userGroups: UserGroup[] = [];
organizationalUnits: any[] = [];
userId: string | null = null;
loading: boolean = false;
isEditMode: boolean = false;
protected views = [
{ value: 'card', name: 'Tarjetas' },
{ value: 'list', name: 'Listado' },
];
constructor(
public dialogRef: MatDialogRef<AddUserModalComponent>,
@ -39,60 +30,46 @@ export class AddUserModalComponent implements OnInit {
private http: HttpClient,
private fb: FormBuilder,
private dataService: DataService,
private toastService: ToastrService,
private configService: ConfigService
private toastService: ToastrService
) {
this.baseUrl = this.configService.apiUrl;
this.userForm = this.fb.group({
username: ['', Validators.required],
password: ['', Validators.required],
role: ['', Validators.required],
groupsView: ['card', Validators.required],
organizationalUnits: [[]]
});
if (data) {
this.isEditMode = true;
}
}
ngOnInit(): void {
this.dataService.getUserGroups().subscribe((data) => {
this.userGroups = data['hydra:member'];
});
this.dataService.getOrganizationalUnits().subscribe((data) => {
this.organizationalUnits = data['hydra:member'].filter((item: any) => item.type === 'organizational-unit');
});
if (this.data) {
this.load();
} else {
this.userForm.get('password')?.setValidators([Validators.required]);
this.load()
}
}
load(): void {
this.loading = true;
this.dataService.getUser(this.data).subscribe({
next: (response) => {
console.log(response);
const organizationalUnitIds = response.allowedOrganizationalUnits.map((unit: any) => unit['@id']);
// Patch the values to the form
this.userForm.patchValue({
username: response.username,
role: response.userGroups.length > 0 ? response.userGroups[0]['@id'] : null,
organizationalUnits: organizationalUnitIds,
groupsView: response.groupsView
role: response.userGroups[0]['@id'],
organizationalUnits: organizationalUnitIds
});
this.userId = response['@id'];
this.userForm.get('password')?.clearValidators();
this.userForm.get('password')?.updateValueAndValidity();
this.loading = false;
},
error: (err) => {
this.loading = false;
console.error('Error fetching user:', err);
console.error('Error fetching remote calendar:', err);
}
});
}
@ -103,49 +80,37 @@ export class AddUserModalComponent implements OnInit {
onSubmit(): void {
if (this.userForm.valid) {
const payload: any = {
const payload = {
username: this.userForm.value.username,
allowedOrganizationalUnits: this.userForm.value.organizationalUnits,
allowedOrganizationalUnits: this.userForm.value.organizationalUnit,
password: this.userForm.value.password,
enabled: true,
userGroups: [this.userForm.value.role],
groupsView: this.userForm.value.groupsView
userGroups: [this.userForm.value.role ]
};
if (!this.userId && this.userForm.value.password) {
payload.password = this.userForm.value.password;
} else if (this.userId && this.userForm.value.password.trim() !== '') {
payload.password = this.userForm.value.password;
}
this.loading = true;
if (this.userId) {
this.http.put(`${this.baseUrl}${this.userId}`, payload).subscribe(
(response) => {
this.toastService.success('Usuario editado correctamente');
this.userEdited.emit();
this.dialogRef.close();
this.loading = false;
},
(error) => {
this.toastService.error(error['error']['hydra:description']);
this.loading = false;
console.error('Error al editar el rol', error);
}
);
} else {
this.http.post(`${this.baseUrl}/users`, payload).subscribe(
(response) => {
this.toastService.success('Usuario añadido correctamente');
this.userAdded.emit();
this.dialogRef.close();
this.loading = false;
},
(error) => {
this.toastService.error(error['error']['hydra:description']);
this.loading = false;
console.error('Error al añadir añadido', error);
}
);
}
}
}
}
}

View File

@ -1,5 +1,6 @@
.user-form .form-field {
display: block;
display: block;
margin-bottom: 10px;
}
.checkbox-group label {
@ -16,14 +17,3 @@ mat-spinner {
margin: 0 auto;
align-self: center;
}
.action-container {
display: flex;
justify-content: flex-end;
gap: 1em;
padding: 1.5em;
}
.form-container {
margin-top: 2em;
}

View File

@ -1,29 +1,29 @@
<h1 mat-dialog-title>{{ 'dialogTitleChangePassword' | translate }}</h1>
<h1 mat-dialog-title i18n="@@dialogTitleEditUser">Editar Usuario</h1>
<mat-dialog-content class="form-container">
<form [formGroup]="userForm" class="user-form">
<mat-form-field class="form-field">
<mat-label>{{ 'labelCurrentPassword' | translate }}</mat-label>
<mat-label i18n="@@labelCurrentPassword">Contraseña actual</mat-label>
<input matInput formControlName="currentPassword" type="password">
</mat-form-field>
<mat-form-field class="form-field">
<mat-label>{{ 'labelNewPassword' | translate }}</mat-label>
<mat-label i18n="@@labelNewPassword">Nueva contraseña</mat-label>
<input matInput formControlName="newPassword" type="password">
</mat-form-field>
<mat-form-field class="form-field">
<mat-label>{{ 'labelRepeatPassword' | translate }}</mat-label>
<mat-label i18n="@@labelRepeatPassword">Repite la contraseña</mat-label>
<input matInput formControlName="repeatNewPassword" type="password">
</mat-form-field>
<div class="error-message" *ngIf="passwordMismatch">
{{ 'errorPasswordMismatch' | translate }}
<div class="error-message" *ngIf="passwordMismatch" i18n="@@errorPasswordMismatch">
Las contraseñas no coinciden
</div>
<div class="error-message" *ngIf="updateError">
<div class="error-message" *ngIf="updateError" i18n="@@errorUpdate">
{{ resetPasswordError }}
</div>
</form>
</mat-dialog-content>
<mat-dialog-actions class="action-container">
<button class="ordinary-button" (click)="onNoClick()">{{ 'buttonCancel' | translate }}</button>
<button class="submit-button" (click)="onSubmit()" [disabled]="loading">{{ 'buttonEdit' | translate }}</button>
</mat-dialog-actions>
<mat-dialog-actions align="end">
<button mat-button (click)="onNoClick()" i18n="@@buttonCancel">Cancelar</button>
<button mat-button (click)="onSubmit()" [disabled]="loading" i18n="@@buttonEdit">Editar</button>
</mat-dialog-actions>

View File

@ -3,19 +3,15 @@ import { Injectable } from '@angular/core';
import {HttpClient, HttpParams} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
import { ConfigService } from '@services/config.service';
@Injectable({
providedIn: 'root'
})
export class DataService {
baseUrl: string;
private apiUrl: string;
baseUrl: string = import.meta.env.NG_APP_BASE_API_URL;
private apiUrl = `${this.baseUrl}/users?page=1&itemsPerPage=1000`;
constructor(private http: HttpClient, private configService: ConfigService) {
this.baseUrl = this.configService.apiUrl;
this.apiUrl = `${this.baseUrl}/users?page=1&itemsPerPage=1000`;
}
constructor(private http: HttpClient) {}
getUsers(filters: { [key: string]: string }): Observable<{ totalItems: any; data: any }> {
const params = new HttpParams({ fromObject: filters });

View File

@ -1,19 +1,6 @@
.header-container {
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px 10px;
border-bottom: 1px solid #ddd;
}
.header-container-title {
flex-grow: 1;
text-align: left;
margin-left: 1em;
}
table {
width: 100%;
margin-top: 50px;
}
.search-container {
@ -21,10 +8,14 @@ table {
justify-content: space-between;
align-items: center;
width: 100%;
margin: 1.5rem 0rem 1.5rem 0rem;
padding: 0 5px;
box-sizing: border-box;
}
.divider {
margin: 20px 0;
}
.search-string {
flex: 2;
padding: 5px;
@ -35,6 +26,13 @@ table {
padding: 5px;
}
.header-container {
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px;
}
.mat-elevation-z8 {
box-shadow: 0px 0px 0px rgba(0,0,0,0.2);
}

View File

@ -1,60 +1,40 @@
<div class="header-container">
<div class="header-container-title">
<h2>{{ 'adminUsersTitle' | translate }}</h2>
</div>
<h2 class="title" i18n="@@adminImagesTitle">Administrar usuarios</h2>
<div class="images-button-row">
<button class="action-button" (click)="addUser()">
{{ 'addUser' | translate }}
</button>
<button mat-flat-button color="primary" (click)="addUser()">Añadir usuarios</button>
</div>
</div>
<mat-divider class="divider"></mat-divider>
<div class="search-container">
<mat-form-field appearance="fill" class="search-string">
<mat-label>{{ 'searchLabel' | translate }}</mat-label>
<input matInput placeholder="{{ 'searchPlaceholder' | translate }}" [(ngModel)]="filters['name']"
(keyup.enter)="search()">
<mat-label i18n="@@searchLabel">Buscar nombre de usuario</mat-label>
<input matInput placeholder="Búsqueda" [(ngModel)]="filters['name']" (keyup.enter)="search()" i18n-placeholder="@@searchPlaceholder">
<mat-icon matSuffix>search</mat-icon>
<mat-hint>{{ 'searchHint' | translate }}</mat-hint>
<mat-hint i18n="@@searchHint">Pulsar 'enter' para buscar</mat-hint>
</mat-form-field>
</div>
<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
<app-loading [isLoading]="loading"></app-loading>
<div *ngIf="!loading">
<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
<ng-container *ngFor="let column of columns" [matColumnDef]="column.columnDef">
<th mat-header-cell *matHeaderCellDef> {{ column.header }} </th>
<td mat-cell *matCellDef="let user">
<ng-container *ngIf="column.columnDef === 'groupsView'">
<mat-chip>
{{ user[column.columnDef] === 'card' ? 'Vista tarjetas' : 'Listado' }}
</mat-chip>
</ng-container>
<ng-container *ngIf="column.columnDef !== 'groupsView'">
{{ column.cell(user) }}
</ng-container>
</td>
</ng-container>
<ng-container matColumnDef="actions">
<th mat-header-cell *matHeaderCellDef style="text-align: center;">{{ 'columnActions' | translate }}</th>
<td mat-cell *matCellDef="let user" style="text-align: center;">
<button mat-icon-button color="primary" (click)="editUser(user)">
<mat-icon>edit</mat-icon>
</button>
<button mat-icon-button color="warn" (click)="deleteUser(user)">
<mat-icon>delete</mat-icon>
</button>
</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
</div>
<ng-container *ngFor="let column of columns" [matColumnDef]="column.columnDef">
<th mat-header-cell *matHeaderCellDef> {{ column.header }} </th>
<td mat-cell *matCellDef="let user"> {{ column.cell(user) }} </td>
</ng-container>
<ng-container matColumnDef="actions">
<th mat-header-cell *matHeaderCellDef i18n="@@columnActions" style="text-align: center;">Acciones</th>
<td mat-cell *matCellDef="let user" style="text-align: center;">
<button mat-icon-button color="primary" (click)="editUser(user)" i18n="@@editImage"> <mat-icon>edit</mat-icon></button>
<button mat-icon-button color="warn" (click)="deleteUser(user)" i18n="@@buttonDelete"><mat-icon>delete</mat-icon></button>
</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
<div class="paginator-container">
<mat-paginator [length]="length" [pageSize]="itemsPerPage" [pageIndex]="page" [pageSizeOptions]="pageSizeOptions"
(page)="onPageChange($event)">
<mat-paginator [length]="length"
[pageSize]="itemsPerPage"
[pageIndex]="page"
[pageSizeOptions]="pageSizeOptions"
(page)="onPageChange($event)">
</mat-paginator>
</div>
</div>

View File

@ -6,12 +6,16 @@ import { HttpClientTestingModule } from '@angular/common/http/testing';
import { ToastrService } from 'ngx-toastr';
import { of } from 'rxjs';
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { TranslateModule } from '@ngx-translate/core';
import { ConfigService } from '@services/config.service';
class MockToastrService {
success() {}
error() {}
class MockUserService {
getUsers() {
return of({
'hydra:member': [
{ id: 1, username: 'user1', allowedOrganizationalUnits: [], roles: ['admin'] },
{ id: 2, username: 'user2', allowedOrganizationalUnits: [], roles: ['user'] }
]
});
}
}
describe('UsersComponent', () => {
@ -19,25 +23,20 @@ describe('UsersComponent', () => {
let fixture: ComponentFixture<UsersComponent>;
beforeEach(async () => {
const mockConfigService = {
apiUrl: 'http://mock-api-url',
mercureUrl: 'http://mock-mercure-url'
};
await TestBed.configureTestingModule({
declarations: [UsersComponent],
imports: [
MatTableModule,
MatDialogModule,
HttpClientTestingModule,
TranslateModule.forRoot(),
],
providers: [
{ provide: ToastrService, useClass: MockToastrService },
{ provide: ConfigService, useValue: mockConfigService }
{ useClass: MockUserService },
{ provide: ToastrService, useValue: { success: () => {} } },
],
schemas: [NO_ERRORS_SCHEMA], // Ignorar elementos desconocidos
}).compileComponents();
schemas: [NO_ERRORS_SCHEMA],
})
.compileComponents();
fixture = TestBed.createComponent(UsersComponent);
component = fixture.componentInstance;
@ -48,27 +47,4 @@ describe('UsersComponent', () => {
expect(component).toBeTruthy();
});
it('should have default values for pagination', () => {
expect(component.itemsPerPage).toBe(10);
expect(component.page).toBe(0);
expect(component.pageSizeOptions).toEqual([5, 10, 20, 40, 100]);
});
it('should call search on init', () => {
spyOn(component, 'search');
component.ngOnInit();
expect(component.search).toHaveBeenCalled();
});
it('should initialize the dataSource', () => {
expect(component.dataSource).toBeDefined();
});
it('should define displayedColumns', () => {
expect(component.displayedColumns).toBeDefined();
expect(component.displayedColumns).toContain('id');
expect(component.displayedColumns).toContain('username');
expect(component.displayedColumns).toContain('roles');
expect(component.displayedColumns).toContain('actions');
});
});

View File

@ -5,19 +5,20 @@ import { AddUserModalComponent } from './add-user-modal/add-user-modal.component
import { DeleteModalComponent } from '../../../../shared/delete_modal/delete-modal/delete-modal.component';
import { HttpClient } from '@angular/common/http';
import { ToastrService } from 'ngx-toastr';
import { ConfigService } from '@services/config.service';
import {DataService} from "./data.service";
import {AddRoleModalComponent} from "../../roles/roles/add-role-modal/add-role-modal.component";
@Component({
selector: 'app-users',
templateUrl: './users.component.html',
styleUrls: ['./users.component.css']
})
export class UsersComponent implements OnInit {
baseUrl: string;
private apiUrl: string;
baseUrl: string = import.meta.env.NG_APP_BASE_API_URL;
dataSource = new MatTableDataSource<any>();
filters: { [key: string]: string } = {};
loading: boolean = false;
loading:boolean = false;
length: number = 0;
itemsPerPage: number = 10;
page: number = 0;
@ -33,11 +34,6 @@ export class UsersComponent implements OnInit {
header: 'Nombre de Usuario',
cell: (user: any) => `${user.username}`
},
{
columnDef: 'groupsView',
header: 'Vista de Grupos',
cell: (user: any) => `${user.groupsView}`
},
{
columnDef: 'allowedOrganizationalUnits',
header: 'Unidades Organizacionales Permitidas',
@ -51,31 +47,27 @@ export class UsersComponent implements OnInit {
];
displayedColumns = [...this.columns.map(column => column.columnDef), 'actions'];
private apiUrl = `${this.baseUrl}/users`;
constructor(
public dialog: MatDialog,
private configService: ConfigService,
private http: HttpClient,
private dataService: DataService,
private toastService: ToastrService
) {
this.baseUrl = this.configService.apiUrl;
this.apiUrl = `${this.baseUrl}/users`;
}
) {}
ngOnInit() {
this.search();
}
search() {
this.loading = true;
this.http.get<any>(`${this.apiUrl}?&page=${this.page + 1}&itemsPerPage=${this.itemsPerPage}`, { params: this.filters }).subscribe(
(data) => {
this.dataSource.data = data['hydra:member'];
this.length = data['hydra:totalItems'];
this.loading = false;
},
(error) => {
console.error('Error fetching users', error);
this.loading = false;
console.error('Error fetching commands', error);
}
);
}
@ -86,6 +78,7 @@ export class UsersComponent implements OnInit {
dialogRef.componentInstance.userAdded.subscribe(() => {
this.search();
});
}
editUser(user: any): void {
@ -94,10 +87,6 @@ export class UsersComponent implements OnInit {
data: user['@id']
});
dialogRef.componentInstance.userEdited.subscribe(() => {
this.search();
});
dialogRef.afterClosed().subscribe(result => {
if (result) {
this.search();
@ -125,6 +114,8 @@ export class UsersComponent implements OnInit {
console.error('Error deleting user:', error);
}
});
} else {
console.log('User deletion cancelled');
}
});
}
@ -135,4 +126,5 @@ export class UsersComponent implements OnInit {
this.length = event.length;
this.search();
}
}
}

View File

@ -1,20 +1,15 @@
.header-container {
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px 10px;
border-bottom: 1px solid #ddd;
}
.header-container-title {
flex-grow: 1;
text-align: left;
margin-left: 1em;
.title {
font-size: 24px;
}
.calendar-button-row {
display: flex;
gap: 15px;
justify-content: flex-start;
margin-top: 16px;
}
.divider {
margin: 20px 0;
}
.lists-container {
@ -28,14 +23,15 @@
table {
width: 100%;
margin-top: 50px;
}
.search-container {
.search-container {
display: flex;
justify-content: space-between;
align-items: center;
width: 100%;
margin: 1.5rem 0rem 1.5rem 0rem;
padding: 0 5px;
box-sizing: border-box;
}
@ -49,12 +45,19 @@ table {
padding: 5px;
}
.header-container {
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px;
}
.mat-elevation-z8 {
box-shadow: 0px 0px 0px rgba(0, 0, 0, 0.2);
box-shadow: 0px 0px 0px rgba(0,0,0,0.2);
}
.paginator-container {
display: flex;
justify-content: end;
margin-bottom: 30px;
}
}

View File

@ -1,74 +1,52 @@
<div class="header-container">
<button mat-icon-button color="primary" (click)="iniciarTour()">
<mat-icon>help</mat-icon>
</button>
<div class="header-container-title">
<h2 joyrideStep="titleStep" text="{{ 'titleStepText' | translate }}">{{ 'adminCalendarsTitle' | translate }}</h2>
</div>
<h2 class="title" i18n="@@adminImagesTitle">Administrar calendarios</h2>
<div class="calendar-button-row">
<button joyrideStep="addButtonStep" text="{{ 'addButtonStepText' | translate }}" class="action-button"
(click)="addCalendar()">
{{ 'addCalendar' | translate }}
</button>
<button mat-flat-button color="primary" (click)="addImage()">Añadir calendario</button>
</div>
</div>
<mat-divider class="divider"></mat-divider>
<div class="search-container">
<mat-form-field joyrideStep="searchStep" text="{{ 'searchStepText' | translate }}" appearance="fill"
class="search-string">
<mat-label>{{ 'searchCalendarLabel' | translate }}</mat-label>
<input matInput placeholder="{{ 'searchPlaceholder' | translate }}" [(ngModel)]="filters['name']"
(keyup.enter)="search()">
<mat-form-field appearance="fill" class="search-string">
<mat-label i18n="@@searchLabel">Buscar nombre de calendario</mat-label>
<input matInput placeholder="Búsqueda" [(ngModel)]="filters['name']" (keyup.enter)="search()" i18n-placeholder="@@searchPlaceholder">
<mat-icon matSuffix>search</mat-icon>
<mat-hint>{{ 'searchHint' | translate }}</mat-hint>
<mat-hint i18n="@@searchHint">Pulsar 'enter' para buscar</mat-hint>
</mat-form-field>
</div>
<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
<ng-container *ngFor="let column of columns" [matColumnDef]="column.columnDef">
<th mat-header-cell *matHeaderCellDef> {{ column.header }} </th>
<td mat-cell *matCellDef="let image" >
<ng-container *ngIf="column.columnDef === 'isDefault' || column.columnDef === 'installed'">
<mat-icon [color]="image[column.columnDef] ? 'primary' : 'warn'">
{{ image[column.columnDef] ? 'check_circle' : 'cancel' }}
</mat-icon>
</ng-container>
<app-loading [isLoading]="loading"></app-loading>
<ng-container *ngIf="column.columnDef !== 'isDefault' && column.columnDef !== 'installed' && column.columnDef !== 'downloadUrl'">
{{ column.cell(image) }}
</ng-container>
</td>
</ng-container>
<div *ngIf="!loading">
<table mat-table [dataSource]="dataSource" class="mat-elevation-z8" joyrideStep="tableStep"
text="{{ 'tableStepText' | translate }}">
<ng-container *ngFor="let column of columns" [matColumnDef]="column.columnDef">
<th mat-header-cell *matHeaderCellDef> {{ column.header }} </th>
<td mat-cell *matCellDef="let image">
<ng-container *ngIf="column.columnDef === 'isDefault' || column.columnDef === 'installed'">
<mat-icon [color]="image[column.columnDef] ? 'primary' : 'warn'">
{{ image[column.columnDef] ? 'check_circle' : 'cancel' }}
</mat-icon>
</ng-container>
<ng-container
*ngIf="column.columnDef !== 'isDefault' && column.columnDef !== 'installed' && column.columnDef !== 'downloadUrl'">
{{ column.cell(image) }}
</ng-container>
</td>
</ng-container>
<ng-container matColumnDef="actions" joyrideStep="actionsStep" text="{{ 'actionsStepText' | translate }}">
<th mat-header-cell *matHeaderCellDef style="text-align: center;">{{ 'columnActions' | translate }}</th>
<td mat-cell *matCellDef="let calendar" style="text-align: center;">
<button mat-icon-button color="primary" (click)="editCalendar(calendar)">
<mat-icon>edit</mat-icon>
</button>
<button *ngIf="!syncUds" mat-icon-button color="primary" (click)="sync(calendar)">
<mat-icon>sync</mat-icon>
</button>
<button *ngIf="syncUds" mat-icon-button color="primary">
<app-loading [isLoading]="syncUds"></app-loading>
</button>
<button mat-icon-button color="warn" (click)="deleteCalendar(calendar)">
<mat-icon>delete</mat-icon>
</button>
</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
</div>
<ng-container matColumnDef="actions">
<th mat-header-cell *matHeaderCellDef i18n="@@columnActions" style="text-align: center;">Acciones</th>
<td mat-cell *matCellDef="let calendar" style="text-align: center;">
<button mat-icon-button color="primary" (click)="editCalendar(calendar)" i18n="@@editImage"> <mat-icon>edit</mat-icon></button>
<button *ngIf="!syncUds" mat-icon-button color="primary" (click)="sync(calendar)"><mat-icon>sync</mat-icon></button>
<button *ngIf="syncUds" mat-icon-button color="primary"><mat-spinner diameter="24"></mat-spinner></button>
<button mat-icon-button color="warn" (click)="deleteCalendar(calendar)" i18n="@@buttonDelete"><mat-icon>delete</mat-icon></button>
</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
<div class="paginator-container">
<mat-paginator [length]="length" [pageSize]="itemsPerPage" [pageIndex]="page" [pageSizeOptions]="pageSizeOptions"
(page)="onPageChange($event)">
<mat-paginator [length]="length"
[pageSize]="itemsPerPage"
[pageIndex]="page"
[pageSizeOptions]="pageSizeOptions"
(page)="onPageChange($event)">
</mat-paginator>
</div>
</div>

View File

@ -10,26 +10,16 @@ import { MatButtonModule } from '@angular/material/button';
import { MatTableModule } from '@angular/material/table';
import { MatPaginatorModule } from '@angular/material/paginator';
import { MatTooltipModule } from '@angular/material/tooltip';
import { FormsModule } from '@angular/forms';
import { FormsModule } from '@angular/forms'; // Importa FormsModule para ngModel
import { CalendarComponent } from './calendar.component';
import { MatProgressSpinner } from '@angular/material/progress-spinner';
import { JoyrideModule, JoyrideService } from 'ngx-joyride';
import { TranslateModule } from '@ngx-translate/core';
import { LoadingComponent } from '../../shared/loading/loading.component';
import { ConfigService } from '@services/config.service';
describe('CalendarComponent', () => {
let component: CalendarComponent;
let fixture: ComponentFixture<CalendarComponent>;
beforeEach(async () => {
const mockConfigService = {
apiUrl: 'http://mock-api-url',
mercureUrl: 'http://mock-mercure-url'
};
await TestBed.configureTestingModule({
declarations: [CalendarComponent, LoadingComponent],
declarations: [CalendarComponent],
imports: [
HttpClientTestingModule,
ToastrModule.forRoot(),
@ -42,13 +32,7 @@ describe('CalendarComponent', () => {
MatTableModule,
MatPaginatorModule,
MatTooltipModule,
FormsModule,
MatProgressSpinner,
JoyrideModule.forRoot(),
TranslateModule.forRoot(),
],
providers: [
{ provide: ConfigService, useValue: mockConfigService }
FormsModule // Añade FormsModule aquí para que ngModel funcione
]
})
.compileComponents();

View File

@ -1,15 +1,13 @@
import { Component, OnInit, signal } from '@angular/core';
import { MatTableDataSource } from "@angular/material/table";
import { DatePipe } from "@angular/common";
import { MatDialog } from "@angular/material/dialog";
import { HttpClient } from "@angular/common/http";
import { DataService } from "./data.service";
import { ToastrService } from "ngx-toastr";
import { PageEvent } from "@angular/material/paginator";
import { CreateCalendarComponent } from "./create-calendar/create-calendar.component";
import { DeleteModalComponent } from "../../shared/delete_modal/delete-modal/delete-modal.component";
import { JoyrideService } from 'ngx-joyride';
import { ConfigService } from '@services/config.service';
import {Component, OnInit, signal} from '@angular/core';
import {MatTableDataSource} from "@angular/material/table";
import {DatePipe} from "@angular/common";
import {MatDialog} from "@angular/material/dialog";
import {HttpClient} from "@angular/common/http";
import {DataService} from "./data.service";
import {ToastrService} from "ngx-toastr";
import {PageEvent} from "@angular/material/paginator";
import {CreateCalendarComponent} from "./create-calendar/create-calendar.component";
import {DeleteModalComponent} from "../../shared/delete_modal/delete-modal/delete-modal.component";
@Component({
selector: 'app-calendar',
@ -17,15 +15,14 @@ import { ConfigService } from '@services/config.service';
styleUrl: './calendar.component.css'
})
export class CalendarComponent implements OnInit {
baseUrl: string;
private apiUrl: string;
baseUrl: string = import.meta.env.NG_APP_BASE_API_URL;
images: { downloadUrl: string; name: string; uuid: string }[] = [];
dataSource = new MatTableDataSource<any>();
length: number = 0;
itemsPerPage: number = 10;
page: number = 1;
pageSizeOptions: number[] = [5, 10, 20, 40, 100];
loading: boolean = false;
loading:boolean = false;
filters: { [key: string]: string } = {};
alertMessage: string | null = null;
readonly panelOpenState = signal(false);
@ -55,28 +52,26 @@ export class CalendarComponent implements OnInit {
];
displayedColumns = [...this.columns.map(column => column.columnDef), 'actions'];
private apiUrl = `${this.baseUrl}/remote-calendars`;
constructor(
public dialog: MatDialog,
private http: HttpClient,
private dataService: DataService,
private toastService: ToastrService,
private configService: ConfigService,
private joyrideService: JoyrideService
) {
this.baseUrl = this.configService.apiUrl;
this.apiUrl = `${this.baseUrl}/remote-calendars`;
}
private toastService: ToastrService
) {}
ngOnInit(): void {
this.search();
}
addCalendar(): void {
addImage(): void {
const dialogRef = this.dialog.open(CreateCalendarComponent, {
width: '400px'
});
dialogRef.afterClosed().subscribe(result => {
console.log('The dialog was closed');
this.search();
});
}
@ -89,21 +84,24 @@ export class CalendarComponent implements OnInit {
this.loading = false;
},
error => {
console.error('Error fetching calendars', error);
console.error('Error fetching og lives', error);
this.loading = false;
}
);
}
sync(calendar: any): void {
console.log('Syncing calendars');
this.syncUds = true;
this.http.post(`${this.apiUrl}/${calendar.uuid}/sync-uds`, {}).subscribe({
next: () => {
console.log('Calendars synced successfully');
this.toastService.success('Calendarios sincronizados correctamente');
this.search();
this.syncUds = false;
},
error: (error) => {
console.error('Error al sincronizar los calendarios:', error);
this.toastService.error(error.error['hydra:description']);
this.syncUds = false;
}
@ -135,27 +133,28 @@ export class CalendarComponent implements OnInit {
this.http.delete(apiUrl).subscribe({
next: () => {
console.log('Calendar deleted successfully');
this.search();
this.toastService.success('Calendar deleted successfully');
},
error: () => {
error: (error) => {
this.toastService.error('Error deleting calendar');
}
});
} else {
console.log('calendar deletion cancelled');
}
});
}
applyFilter() {
this.loading = true;
this.http.get<any>(`${this.apiUrl}?page=${this.page}&itemsPerPage=${this.itemsPerPage}`).subscribe({
next: (response) => {
this.dataSource.data = response['hydra:member'];
this.length = response['hydra:totalItems'];
this.loading = false;
},
error: () => {
this.loading = false;
error: (error) => {
console.error('Error al cargar las imágenes:', error);
}
});
}
@ -165,12 +164,4 @@ export class CalendarComponent implements OnInit {
this.itemsPerPage = event.pageSize;
this.applyFilter();
}
iniciarTour(): void {
this.joyrideService.startTour({
steps: ['titleStep', 'addButtonStep', 'searchStep', 'tableStep', 'actionsStep'],
showPrevButton: true,
themeColor: '#3f51b5'
});
}
}

View File

@ -28,10 +28,3 @@
.time-field {
flex: 1;
}
.action-container {
display: flex;
justify-content: flex-end;
gap: 1em;
padding: 1.5em;
}

View File

@ -1,19 +1,17 @@
<h2 mat-dialog-title>{{ isEditMode ? ('editCalendar' | translate) : ('addCalendar' | translate) }}</h2>
<h2 mat-dialog-title>{{ isEditMode ? 'Editar' : 'Añadir' }} calendario</h2>
<mat-dialog-content class="form-container">
<mat-slide-toggle [(ngModel)]="isRemoteAvailable" class="example-margin">
{{ 'remoteAvailability' | translate }}
</mat-slide-toggle>
<mat-slide-toggle [(ngModel)]="isRemoteAvailable" class="example-margin">¿Disponibilidad remoto?</mat-slide-toggle>
<div *ngIf="!isRemoteAvailable" class="form-group">
<mat-label>{{ 'selectWeekDays' | translate }}</mat-label>
<mat-label>Selecciona los días de la semana</mat-label>
<div class="row">
<div class="col-md-6 checkbox-group">
<mat-checkbox *ngFor="let day of weekDays.slice(0, (weekDays.length / 2) + 1)" [(ngModel)]="busyWeekDays[day]">
{{ day }}
</mat-checkbox>
</div>
<div class="col-md-6 checkbox-group">
<mat-checkbox *ngFor="let day of weekDays.slice(weekDays.length / 2 + 1)" [(ngModel)]="busyWeekDays[day]">
<div class="col-md-6 checkbox-group ">
<mat-checkbox *ngFor="let day of weekDays.slice(weekDays.length / 2 + 1 )" [(ngModel)]="busyWeekDays[day]">
{{ day }}
</mat-checkbox>
</div>
@ -21,32 +19,32 @@
<div class="time-fields">
<mat-form-field appearance="fill" class="time-field">
<mat-label>{{ 'startTime' | translate }}</mat-label>
<input matInput [(ngModel)]="busyFromHour" type="time" placeholder="{{ 'startTimePlaceholder' | translate }}" [required]="!isRemoteAvailable">
<mat-label>Hora de inicio</mat-label>
<input matInput [(ngModel)]="busyFromHour" type="time" placeholder="Selecciona la hora de inicio" [required]="!isRemoteAvailable">
</mat-form-field>
<mat-form-field appearance="fill" class="time-field">
<mat-label>{{ 'endTime' | translate }}</mat-label>
<input matInput [(ngModel)]="busyToHour" type="time" placeholder="{{ 'endTimePlaceholder' | translate }}" [required]="!isRemoteAvailable">
<mat-label>Hora de fin</mat-label>
<input matInput [(ngModel)]="busyToHour" type="time" placeholder="Selecciona la hora de fin" [required]="!isRemoteAvailable">
</mat-form-field>
</div>
</div>
<div *ngIf="isRemoteAvailable" class="form-group">
<mat-form-field appearance="fill" class="full-width">
<mat-label>{{ 'reasonLabel' | translate }}</mat-label>
<input matInput [(ngModel)]="availableReason" placeholder="{{ 'reasonPlaceholder' | translate }}" [required]="isRemoteAvailable">
<mat-label>Razón</mat-label>
<input matInput [(ngModel)]="availableReason" placeholder="Razon para la excepción" [required]="isRemoteAvailable">
</mat-form-field>
<div class="time-fields">
<mat-form-field appearance="fill" class="full-width">
<mat-label>{{ 'startDate' | translate }}</mat-label>
<mat-label>Fecha de inicio</mat-label>
<input matInput [matDatepicker]="picker1" [(ngModel)]="availableFromDate" [required]="isRemoteAvailable">
<mat-hint>MM/DD/YYYY</mat-hint>
<mat-datepicker-toggle matIconSuffix [for]="picker1"></mat-datepicker-toggle>
<mat-datepicker #picker1></mat-datepicker>
</mat-form-field>
<mat-form-field appearance="fill" class="full-width">
<mat-label>{{ 'endDate' | translate }}</mat-label>
<mat-label>Fecha de fin</mat-label>
<input matInput [matDatepicker]="picker2" [(ngModel)]="availableToDate" [required]="isRemoteAvailable">
<mat-hint>MM/DD/YYYY</mat-hint>
<mat-datepicker-toggle matIconSuffix [for]="picker2"></mat-datepicker-toggle>
@ -56,13 +54,13 @@
</div>
</mat-dialog-content>
<mat-dialog-actions class="action-container">
<button class="ordinary-button" (click)="onNoClick()">{{ 'buttonCancel' | translate }}</button>
<mat-dialog-actions align="end">
<button mat-button (click)="onNoClick()">Cancelar</button>
<button
class="submit-button"
mat-button
(click)="submitRule()"
cdkFocusInitial
[disabled]="(!isRemoteAvailable && (!busyFromHour || !busyToHour)) || (isRemoteAvailable && (!availableReason || !availableFromDate || !availableToDate))">
{{ isEditMode ? ('buttonSave' | translate) : ('buttonAdd' | translate) }}
{{ isEditMode ? 'Guardar' : 'Añadir' }}
</button>
</mat-dialog-actions>

View File

@ -1,8 +1,7 @@
import { Component, Inject } from '@angular/core';
import { ToastrService } from "ngx-toastr";
import { HttpClient } from "@angular/common/http";
import { MAT_DIALOG_DATA, MatDialogRef } from "@angular/material/dialog";
import { ConfigService } from '@services/config.service';
import {Component, Inject} from '@angular/core';
import {ToastrService} from "ngx-toastr";
import {HttpClient} from "@angular/common/http";
import {MAT_DIALOG_DATA, MatDialogRef} from "@angular/material/dialog";
@Component({
selector: 'app-create-calendar-rule',
@ -10,7 +9,7 @@ import { ConfigService } from '@services/config.service';
styleUrl: './create-calendar-rule.component.css'
})
export class CreateCalendarRuleComponent {
baseUrl: string;
baseUrl: string = import.meta.env.NG_APP_BASE_API_URL;
name: string = '';
remoteCalendarRules: any[] = [];
weekDays: string[] = ['Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado', 'Domingo'];
@ -30,23 +29,20 @@ export class CreateCalendarRuleComponent {
constructor(
private toastService: ToastrService,
private http: HttpClient,
private configService: ConfigService,
public dialogRef: MatDialogRef<CreateCalendarRuleComponent>,
@Inject(MAT_DIALOG_DATA) public data: any,
) {
this.baseUrl = this.configService.apiUrl;
}
) { }
ngOnInit(): void {
this.calendarId = this.data.calendar
if (this.data) {
this.isEditMode = true;
this.availableFromDate = this.data.rule ? this.data.rule.availableFromDate : null;
this.availableToDate = this.data.rule ? this.data.rule.availableToDate : null;
this.isRemoteAvailable = this.data.rule ? this.data.rule.isRemoteAvailable : false;
this.availableReason = this.data.rule ? this.data.rule.availableReason : null;
this.busyFromHour = this.data.rule ? this.data.rule.busyFromHour : null;
this.busyToHour = this.data.rule ? this.data.rule.busyToHour : null;
this.availableFromDate = this.data.rule? this.data.rule.availableFromDate : null;
this.availableToDate = this.data.rule? this.data.rule.availableToDate : null;
this.isRemoteAvailable = this.data.rule? this.data.rule.isRemoteAvailable : false;
this.availableReason = this.data.rule? this.data.rule.availableReason : null;
this.busyFromHour = this.data.rule? this.data.rule.busyFromHour : null;
this.busyToHour = this.data.rule? this.data.rule.busyToHour : null;
if (this.data.rule && this.data.rule.busyWeekDays) {
this.busyWeekDays = this.data.rule.busyWeekDays.reduce((acc: {
[x: string]: boolean;

View File

@ -1,3 +1,6 @@
.full-width {
width: 100%;
}
.form-container {
padding: 40px;
}
@ -9,7 +12,7 @@
.full-width {
width: 100%;
margin-top: 16px;
margin-bottom: 16px;
}
.additional-form {
@ -55,9 +58,3 @@
cursor: pointer;
}
.action-container {
display: flex;
justify-content: flex-end;
gap: 1em;
padding: 1.5em;
}

View File

@ -1,16 +1,15 @@
<h2 mat-dialog-title>{{ isEditMode ? ('editCalendar' | translate) : ('addCalendar' | translate) }}</h2>
<h2 mat-dialog-title>{{ isEditMode ? 'Editar' : 'Añadir' }} calendario</h2>
<mat-dialog-content class="form-container">
<!-- Campo para el nombre -->
<mat-form-field appearance="fill" class="full-width">
<mat-label>{{ 'labelName' | translate }}</mat-label>
<mat-label>Nombre</mat-label>
<input matInput [(ngModel)]="name" required>
<mat-icon *ngIf="isEditMode" matSuffix (click)="submitForm()">mode_edit</mat-icon>
</mat-form-field>
<div style="display: flex; justify-content: space-between; align-items: center;">
<div *ngIf="isEditMode" mat-subheader>{{ 'rulesHeader' | translate }}</div>
<button class="action-button" *ngIf="isEditMode" (click)="createRule()" style="padding: 10px;">
{{ 'addRule' | translate }}
<div *ngIf="isEditMode" mat-subheader>Reglas</div>
<button mat-flat-button color="primary" *ngIf="isEditMode" (click)="createRule()" style="padding: 10px;">
Añadir regla
</button>
</div>
@ -22,16 +21,16 @@
<div class="list-item-content">
<mat-icon matListItemIcon>event_available</mat-icon>
<div class="text-content">
<div matListItemTitle>{{ rule.isRemoteAvailable ? ('statusAvailable' | translate) : ('statusUnavailable' | translate) }}</div>
<div matListItemTitle>{{ rule.isRemoteAvailable ? 'Disponible' : 'No disponible ( periodo presencial )' }}</div>
<div matListItemLine *ngIf="!rule.isRemoteAvailable">{{ rule.busyFromHour }} - {{ rule.busyToHour }}</div>
<div matListItemLine *ngIf="!rule.isRemoteAvailable">{{ rule.busyWeekDaysMap }}</div>
<div matListItemLine *ngIf="rule.isRemoteAvailable">{{ rule.availableReason }} | {{ rule.availableFromDate | date }} - {{ rule.availableToDate | date }}</div>
</div>
<div class="icon-container">
<button mat-icon-button color="primary" class="right-icon" (click)="createRule(rule)">
<button mat-icon-button color="primary" class="right-icon" (click)="createRule(rule)" i18n="@@editImage">
<mat-icon>edit</mat-icon>
</button>
<button mat-icon-button color="warn" class="right-icon" (click)="deleteCalendarRule(rule)">
<button mat-icon-button color="warn" class="right-icon" (click)="deleteCalendarRule(rule)" >
<mat-icon>delete</mat-icon>
</button>
</div>
@ -41,9 +40,7 @@
</mat-list>
</mat-dialog-content>
<mat-dialog-actions class="action-container">
<button class="ordinary-button" (click)="onNoClick()">{{ 'buttonCancel' | translate }}</button>
<button class="submit-button" (click)="submitForm()" [disabled]="!name || name === ''" cdkFocusInitial>
{{ 'buttonSave' | translate }}
</button>
<mat-dialog-actions align="end">
<button mat-button (click)="onNoClick()">Cancelar</button>
<button mat-button (click)="submitForm()" [disabled]="!name || name === ''" cdkFocusInitial> Guardar </button>
</mat-dialog-actions>

View File

@ -1,11 +1,10 @@
import { Component, Inject, OnInit } from '@angular/core';
import { ToastrService } from "ngx-toastr";
import { HttpClient } from "@angular/common/http";
import { MAT_DIALOG_DATA, MatDialog, MatDialogRef } from "@angular/material/dialog";
import { CreateCalendarRuleComponent } from "../create-calendar-rule/create-calendar-rule.component";
import { DataService } from "../data.service";
import { DeleteModalComponent } from "../../../shared/delete_modal/delete-modal/delete-modal.component";
import { ConfigService } from '@services/config.service';
import {Component, Inject, OnInit} from '@angular/core';
import {ToastrService} from "ngx-toastr";
import {HttpClient} from "@angular/common/http";
import {MAT_DIALOG_DATA, MatDialog, MatDialogRef} from "@angular/material/dialog";
import {CreateCalendarRuleComponent} from "../create-calendar-rule/create-calendar-rule.component";
import {DataService} from "../data.service";
import {DeleteModalComponent} from "../../../shared/delete_modal/delete-modal/delete-modal.component";
@Component({
selector: 'app-create-calendar',
@ -13,7 +12,7 @@ import { ConfigService } from '@services/config.service';
styleUrl: './create-calendar.component.css'
})
export class CreateCalendarComponent implements OnInit {
baseUrl: string;
baseUrl: string = import.meta.env.NG_APP_BASE_API_URL;
name: string = '';
remoteCalendarRules: any[] = [];
isEditMode: boolean = false;
@ -23,14 +22,11 @@ export class CreateCalendarComponent implements OnInit {
constructor(
private toastService: ToastrService,
private http: HttpClient,
private configService: ConfigService,
public dialogRef: MatDialogRef<CreateCalendarComponent>,
@Inject(MAT_DIALOG_DATA) public data: any,
public dialog: MatDialog,
private dataService: DataService,
) {
this.baseUrl = this.configService.apiUrl;
}
) { }
ngOnInit(): void {
if (this.data) {

View File

@ -1,20 +1,16 @@
import { Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import {HttpClient, HttpParams} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
import { ConfigService } from '@services/config.service';
@Injectable({
providedIn: 'root'
})
export class DataService {
baseUrl: string;
private apiUrl: string;
baseUrl: string = import.meta.env.NG_APP_BASE_API_URL;
private apiUrl = `${this.baseUrl}/remote-calendars?page=1&itemsPerPage=1000`;
constructor(private http: HttpClient, private configService: ConfigService) {
this.baseUrl = this.configService.apiUrl;
this.apiUrl = `${this.baseUrl}/remote-calendars?page=1&itemsPerPage=1000`;
}
constructor(private http: HttpClient) {}
getRemoteCalendars(filters: { [key: string]: string }): Observable<any[]> {
const params = new HttpParams({ fromObject: filters });

View File

@ -1,12 +1,11 @@
.header-container-title {
flex-grow: 1;
text-align: left;
margin-left: 1em;
.title {
font-size: 24px;
}
.command-groups-button-row {
.calendar-button-row {
display: flex;
gap: 15px;
justify-content: flex-start;
margin-top: 16px;
}
.divider {
@ -28,15 +27,16 @@
table {
width: 100%;
margin-top: 50px;
}
.search-container {
.search-container {
display: flex;
justify-content: space-between;
align-items: center;
width: 100%;
padding: 0 5px;
box-sizing: border-box;
margin: 1.5rem 0rem 1.5rem 0rem;
}
.search-string {
@ -53,12 +53,11 @@ table {
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px 10px;
border-bottom: 1px solid #ddd;
padding: 10px;
}
.mat-elevation-z8 {
box-shadow: 0px 0px 0px rgba(0, 0, 0, 0.2);
box-shadow: 0px 0px 0px rgba(0,0,0,0.2);
}
.paginator-container {
@ -75,4 +74,5 @@ table {
.mat-chip-readonly-false {
background-color: #F44336 !important;
color: white !important;
}
}

View File

@ -1,75 +1,57 @@
<div class="header-container">
<button mat-icon-button color="primary" (click)="iniciarTour()">
<mat-icon>help</mat-icon>
</button>
<div class="header-container-title">
<h2 joyrideStep="titleStep" text="{{ 'titleStepText' | translate }}">{{ 'adminCommandGroupsTitle' | translate }}</h2>
<h2 class="title" i18n="@@adminCommandGroupsTitle">Administrar Grupos de Comandos</h2>
<div class="command-groups-button-row">
<button mat-flat-button color="primary" (click)="openCreateCommandGroupModal()">Añadir Grupo de Comandos</button>
</div>
</div>
<div class="command-groups-button-row">
<button class="action-button" (click)="openCreateCommandGroupModal()" joyrideStep="addCommandGroupStep" text="{{ 'addCommandGroupStepText' | translate }}">
{{ 'addCommandGroup' | translate }}
</button>
<mat-divider class="divider"></mat-divider>
<div class="search-container">
<mat-form-field appearance="fill" class="search-string">
<mat-label i18n="@@searchLabel">Buscar nombre de grupo</mat-label>
<input matInput placeholder="Búsqueda" [(ngModel)]="filters['name']" (keyup.enter)="search()" i18n-placeholder="@@searchPlaceholder">
<mat-icon matSuffix>search</mat-icon>
<mat-hint i18n="@@searchHint">Pulsar 'enter' para buscar</mat-hint>
</mat-form-field>
</div>
</div>
<div class="search-container" joyrideStep="searchStep" text="{{ 'searchStepText' | translate }}">
<mat-form-field appearance="fill" class="search-string">
<mat-label>{{ 'searchGroupNameLabel' | translate }}</mat-label>
<input matInput placeholder="{{ 'searchPlaceholder' | translate }}" [(ngModel)]="filters['name']" (keyup.enter)="search()">
<mat-icon matSuffix>search</mat-icon>
<mat-hint>{{ 'searchHint' | translate }}</mat-hint>
</mat-form-field>
</div>
<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
<ng-container *ngFor="let column of columns" [matColumnDef]="column.columnDef">
<th mat-header-cell *matHeaderCellDef> {{ column.header }} </th>
<td mat-cell *matCellDef="let commandGroup">
<ng-container *ngIf="column.columnDef !== 'commands'">
{{ column.cell(commandGroup) }}
</ng-container>
<div *ngIf="loading" class="loading-container" joyrideStep="loadingStep" text="{{ 'loadingStepText' | translate }}">
<app-loading [isLoading]="loading"></app-loading>
</div>
<ng-container *ngIf="column.columnDef === 'commands'">
<button mat-button [matMenuTriggerFor]="menu">Ver comandos</button>
<mat-menu #menu="matMenu">
<button mat-menu-item *ngFor="let command of commandGroup.commands">
{{ command.name }}
</button>
</mat-menu>
</ng-container>
</td>
</ng-container>
<ng-container matColumnDef="actions">
<th mat-header-cell *matHeaderCellDef i18n="@@columnActions" style="text-align: center;">Acciones</th>
<td mat-cell *matCellDef="let client" style="text-align: center;">
<button mat-icon-button color="info" (click)="viewGroupDetails(client)"><mat-icon i18n="@@deleteElementTooltip">visibility</mat-icon></button>
<button mat-icon-button color="primary" (click)="editCommandGroup(client)" i18n="@@editImage"> <mat-icon>edit</mat-icon></button>
<button mat-icon-button color="warn" (click)="deleteCommandGroup(client)">
<mat-icon i18n="@@deleteElementTooltip">delete</mat-icon>
</button>
</td>
</ng-container>
<div *ngIf="!loading">
<table mat-table [dataSource]="dataSource" class="mat-elevation-z8" joyrideStep="tableStep" text="{{ 'tableStepText' | translate }}">
<ng-container *ngFor="let column of columns" [matColumnDef]="column.columnDef">
<th mat-header-cell *matHeaderCellDef> {{ column.header }} </th>
<td mat-cell *matCellDef="let commandGroup">
<ng-container *ngIf="column.columnDef !== 'commands'">
{{ column.cell(commandGroup) }}
</ng-container>
<ng-container *ngIf="column.columnDef === 'commands'" joyrideStep="viewCommandsStep" text="{{ 'viewCommandsStepText' | translate }}">
<button class="action-button" [matMenuTriggerFor]="menu">{{ 'viewCommands' | translate }}</button>
<mat-menu #menu="matMenu">
<button mat-menu-item *ngFor="let command of commandGroup.commands">
{{ command.name }}
</button>
</mat-menu>
</ng-container>
</td>
</ng-container>
<ng-container matColumnDef="actions">
<th mat-header-cell *matHeaderCellDef style="text-align: center;">{{ 'columnActions' | translate }}</th>
<td mat-cell *matCellDef="let client" style="text-align: center;" joyrideStep="actionsStep" text="{{ 'actionsStepText' | translate }}">
<button mat-icon-button color="info" (click)="viewGroupDetails(client)">
<mat-icon>visibility</mat-icon>
</button>
<button mat-icon-button color="primary" (click)="editCommandGroup(client)">
<mat-icon>edit</mat-icon>
</button>
<button mat-icon-button color="warn" (click)="deleteCommandGroup(client)">
<mat-icon>delete</mat-icon>
</button>
</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
</div>
<div class="paginator-container" joyrideStep="paginationStep" text="{{ 'paginationStepText' | translate }}">
<mat-paginator [length]="length"
[pageSize]="itemsPerPage"
[pageIndex]="page"
[pageSizeOptions]="pageSizeOptions"
(page)="onPageChange($event)">
</mat-paginator>
</div>
<div class="paginator-container">
<mat-paginator [length]="length"
[pageSize]="itemsPerPage"
[pageIndex]="page"
[pageSizeOptions]="pageSizeOptions"
(page)="onPageChange($event)">
</mat-paginator>
</div>

View File

@ -2,13 +2,11 @@ import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { MatDialog } from '@angular/material/dialog';
import { ToastrService } from 'ngx-toastr';
import { CreateCommandGroupComponent } from './create-command-group/create-command-group.component';
import { CreateCommandGroupComponent } from './create-command-group/create-command-group.component'
import { DetailCommandGroupComponent } from './detail-command-group/detail-command-group.component';
import { DeleteModalComponent } from '../../../shared/delete_modal/delete-modal/delete-modal.component';
import { MatTableDataSource } from "@angular/material/table";
import { DatePipe } from "@angular/common";
import { JoyrideService } from 'ngx-joyride';
import { ConfigService } from '@services/config.service';
import {MatTableDataSource} from "@angular/material/table";
import {DatePipe} from "@angular/common";
@Component({
selector: 'app-commands-groups',
@ -16,8 +14,7 @@ import { ConfigService } from '@services/config.service';
styleUrls: ['./commands-groups.component.css']
})
export class CommandsGroupsComponent implements OnInit {
baseUrl: string;
private apiUrl: string;
baseUrl: string = import.meta.env.NG_APP_BASE_API_URL;
dataSource = new MatTableDataSource<any>();
filters: { [key: string]: string | boolean } = {};
length: number = 0;
@ -25,7 +22,6 @@ export class CommandsGroupsComponent implements OnInit {
page: number = 0;
pageSizeOptions: number[] = [10, 20, 40, 100];
datePipe: DatePipe = new DatePipe('es-ES');
loading: boolean = false;
columns = [
{
columnDef: 'id',
@ -49,28 +45,22 @@ export class CommandsGroupsComponent implements OnInit {
}
];
displayedColumns = [...this.columns.map(column => column.columnDef), 'actions'];
private apiUrl = `${this.baseUrl}/command-groups`;
constructor(private http: HttpClient, private dialog: MatDialog, private toastService: ToastrService,
private configService: ConfigService, private joyrideService: JoyrideService) {
this.baseUrl = this.configService.apiUrl;
this.apiUrl = `${this.baseUrl}/command-groups`;
}
constructor(private http: HttpClient, private dialog: MatDialog, private toastService: ToastrService) {}
ngOnInit(): void {
this.search();
}
search(): void {
this.loading = true;
this.http.get<any>(`${this.apiUrl}?page=${this.page + 1}&itemsPerPage=${this.itemsPerPage}`, { params: this.filters }).subscribe(
(data) => {
this.dataSource.data = data['hydra:member'];
this.length = data['hydra:totalItems'];
this.loading = false;
},
(error) => {
console.error('Error fetching command groups', error);
this.loading = false;
}
);
}
@ -120,21 +110,4 @@ export class CommandsGroupsComponent implements OnInit {
this.length = event.length;
this.search();
}
iniciarTour(): void {
this.joyrideService.startTour({
steps: [
'titleStep',
'addCommandGroupStep',
'searchStep',
'tableStep',
'viewCommandsStep',
'actionsStep',
'paginationStep'
],
showPrevButton: true,
themeColor: '#3f51b5'
});
}
}

View File

@ -1,8 +1,8 @@
.create-command-group-container {
padding: 20px;
max-width: 800px;
margin: auto;
background-color: #fff;
max-width: 800px; /* Ancho máximo del contenedor */
margin: auto; /* Centra el contenedor en la pantalla */
background-color: #fff; /* Fondo blanco para el contenedor */
}
.form-container {
@ -24,14 +24,14 @@
width: 48%;
display: flex;
flex-direction: column;
max-height: 200px;
max-height: 200px; /* Limita la altura máxima para evitar desbordamiento */
}
.table-wrapper {
flex: 1;
overflow-y: auto;
border: 1px solid #ccc;
border-radius: 4px;
overflow-y: auto; /* Scroll para la tabla si hay demasiados comandos */
border: 1px solid #ccc; /* Borde para la tabla */
border-radius: 4px; /* Bordes redondeados */
}
.selected-commands-list {
@ -40,7 +40,7 @@
padding: 10px;
background-color: #f9f9f9;
flex: 1;
overflow-y: auto;
overflow-y: auto; /* Scroll para los comandos seleccionados */
}
.commands-container {
@ -60,7 +60,7 @@
.remove-icon {
cursor: pointer;
color: #f44336;
color: #f44336; /* Rojo para eliminar */
}
.chevron-icon {
@ -74,34 +74,29 @@
justify-content: space-between;
}
.available-commands, .selected-commands {
width: 48%;
display: flex;
flex-direction: column;
max-height: 500px;
max-height: 500px; /* Limita la altura máxima para evitar desbordamiento */
}
.table-wrapper {
flex: 1;
overflow-y: auto;
border: 1px solid #ccc;
border-radius: 4px;
max-height: 400px;
overflow-y: auto; /* Scroll para la tabla si hay demasiados comandos */
border: 1px solid #ccc; /* Borde para la tabla */
border-radius: 4px; /* Bordes redondeados */
max-height: 400px; /* Establece la altura máxima */
}
/* Para asegurar que el componente sea responsivo en pantallas pequeñas */
@media (max-width: 600px) {
.command-selection {
flex-direction: column;
flex-direction: column; /* Cambia a columna en pantallas pequeñas */
}
.available-commands, .selected-commands {
width: 100%;
margin-bottom: 20px;
width: 100%; /* Ocupa el ancho completo */
margin-bottom: 20px; /* Espacio entre elementos */
}
}
.action-container {
display: flex;
justify-content: flex-end;
gap: 1em;
padding: 1.5em;
}

View File

@ -1,27 +1,25 @@
<h2 mat-dialog-title>{{ editing ? ('editCommandGroup' | translate) : ('createCommandGroup' | translate) }}</h2>
<h2 mat-dialog-title>{{ editing ? 'Editar' : 'Crear' }} grupo de comando</h2>
<mat-dialog-content class="form-container">
<app-loading [isLoading]="loading"></app-loading>
<form *ngIf="!loading" class="command-group-form" (ngSubmit)="onSubmit()">
<form class="command-group-form" (ngSubmit)="onSubmit()">
<mat-form-field>
<mat-label>{{ 'groupNameLabel' | translate }}</mat-label>
<mat-label>Nombre del Grupo</mat-label>
<input matInput [(ngModel)]="groupName" name="groupName" required />
</mat-form-field>
<mat-slide-toggle [(ngModel)]="enabled" name="enabled">{{ 'enabledToggle' | translate }}</mat-slide-toggle>
<mat-slide-toggle [(ngModel)]="enabled" name="enabled">Habilitado</mat-slide-toggle>
<div class="command-selection">
<div class="available-commands">
<h3>{{ 'availableCommandsTitle' | translate }}</h3>
<div class="table-wrapper">
<h3>Comandos Disponibles</h3>
<div class="table-wrapper"> <!-- Agregar este contenedor -->
<table mat-table [dataSource]="availableCommands" class="mat-elevation-z8">
<ng-container matColumnDef="name">
<th mat-header-cell *matHeaderCellDef> {{ 'nameColumn' | translate }} </th>
<th mat-header-cell *matHeaderCellDef> Nombre </th>
<td mat-cell *matCellDef="let command"> {{ command.name }} </td>
</ng-container>
<ng-container matColumnDef="actions">
<th mat-header-cell *matHeaderCellDef> {{ 'actionsColumn' | translate }} </th>
<th mat-header-cell *matHeaderCellDef> Acciones </th>
<td mat-cell *matCellDef="let command">
<button mat-icon-button type="button" (click)="addCommand(command)">
<mat-icon>add</mat-icon>
@ -36,16 +34,18 @@
</div>
<div class="selected-commands">
<h3>{{ 'selectedCommandsTitle' | translate }}</h3>
<div class="selected-commands-list" cdkDropList (cdkDropListDropped)="drop($event)">
<h3>Comandos Seleccionados</h3>
<div class="selected-commands-list">
<div class="commands-container">
<div *ngFor="let command of selectedCommands" cdkDrag>
<ng-container *ngFor="let command of selectedCommands; let last = last">
<div class="command-item">
<mat-icon class="drag-handle" cdkDragHandle>drag_indicator</mat-icon>
{{ command.name }}
<mat-icon class="remove-icon" (click)="removeCommand(command)">close</mat-icon>
</div>
</div>
<ng-container *ngIf="!last">
<mat-icon class="chevron-icon">chevron_right</mat-icon>
</ng-container>
</ng-container>
</div>
</div>
</div>
@ -53,7 +53,8 @@
</form>
</mat-dialog-content>
<mat-dialog-actions class="action-container">
<button class="ordinary-button" (click)="close()">{{ 'buttonCancel' | translate }}</button>
<button class="submit-button" (click)="onSubmit()" cdkFocusInitial>{{ 'buttonSave' | translate }}</button>
</mat-dialog-actions>
<mat-dialog-actions align="end">
<button mat-button (click)="close()">Cancelar</button>
<button mat-button (click)="onSubmit()" cdkFocusInitial> Guardar </button>
</mat-dialog-actions>

View File

@ -2,8 +2,6 @@ import { Component, OnInit, Inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { ToastrService } from 'ngx-toastr';
import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop';
import { ConfigService } from '@services/config.service';
@Component({
selector: 'app-create-command-group',
@ -11,25 +9,20 @@ import { ConfigService } from '@services/config.service';
styleUrls: ['./create-command-group.component.css']
})
export class CreateCommandGroupComponent implements OnInit {
baseUrl: string;
baseUrl: string = import.meta.env.NG_APP_BASE_API_URL;
availableCommands: any[] = [];
selectedCommands: any[] = [];
groupName: string = '';
enabled: boolean = true;
editing: boolean = false;
loading: boolean = false;
private apiUrl: string;
private apiUrl = `${this.baseUrl}/commands`;
constructor(
private http: HttpClient,
private dialogRef: MatDialogRef<CreateCommandGroupComponent>,
private toastService: ToastrService,
private configService: ConfigService,
@Inject(MAT_DIALOG_DATA) public data: any
) {
this.baseUrl = this.configService.apiUrl;
this.apiUrl = `${this.baseUrl}/commands`;
}
) {}
ngOnInit(): void {
this.loadAvailableCommands();
@ -41,15 +34,12 @@ export class CreateCommandGroupComponent implements OnInit {
}
loadAvailableCommands(): void {
this.loading = true;
this.http.get<any>(this.apiUrl).subscribe(
(data) => {
this.availableCommands = data['hydra:member'];
this.loading = false;
},
(error) => {
console.error('Error fetching available commands', error);
this.loading = false;
}
);
}
@ -61,9 +51,7 @@ export class CreateCommandGroupComponent implements OnInit {
}
addCommand(command: any): void {
if (!this.selectedCommands.includes(command)) {
this.selectedCommands.push(command);
}
this.selectedCommands.push(command);
}
removeCommand(command: any): void {
@ -73,10 +61,6 @@ export class CreateCommandGroupComponent implements OnInit {
}
}
drop(event: CdkDragDrop<any[]>): void {
moveItemInArray(this.selectedCommands, event.previousIndex, event.currentIndex);
}
onSubmit(): void {
const payload = {
name: this.groupName,
@ -93,7 +77,6 @@ export class CreateCommandGroupComponent implements OnInit {
},
error: (error) => {
console.error('Error actualizando el grupo de comandos', error);
this.toastService.error('Error al actualizar el grupo de comandos');
}
});
} else {
@ -104,7 +87,6 @@ export class CreateCommandGroupComponent implements OnInit {
},
error: (error) => {
console.error('Error creando el grupo de comandos', error);
this.toastService.error('Error al crear el grupo de comandos');
}
});
}

View File

@ -58,6 +58,19 @@
padding: 10px 20px;
}
button {
background-color: #3f51b5; /* Color primario */
color: white;
padding: 10px 15px;
border: none;
border-radius: 4px;
cursor: pointer;
}
button:hover {
background-color: #2c387e; /* Color primario oscuro */
}
@media (max-width: 600px) {
.mat-card {
margin: 10px 0;
@ -73,6 +86,15 @@
}
}
.cancel-button {
background-color: #dc3545;
color: white;
border-radius: 5px;
}
.cancel-button:hover {
opacity: 0.9;
}
.create-command-group-container {
padding: 20px;
}
@ -124,9 +146,8 @@
color: #666;
}
.action-container {
.command-group-actions {
margin-top: 20px;
display: flex;
justify-content: flex-end;
gap: 1em;
padding: 1.5em;
justify-content: space-between;
}

View File

@ -1,22 +1,20 @@
<div class="detail-command-group-container">
<h2>{{ 'commandGroupDetailsTitle' | translate }}</h2>
<app-loading [isLoading]="loading"></app-loading>
<mat-card *ngIf="!loading">
<h2>Detalles del Grupo de Comandos</h2>
<mat-card>
<mat-card-header>
<mat-card-title>{{ data.name }}</mat-card-title>
<mat-card-subtitle>{{ 'createdBy' | translate }}: {{ data.createdBy }}</mat-card-subtitle>
<mat-card-subtitle>Creado por: {{ data.createdBy }}</mat-card-subtitle>
</mat-card-header>
<mat-card-content>
<p><strong>{{ 'groupId' | translate }}:</strong> {{ data.uuid }}</p>
<p><strong>{{ 'creationDate' | translate }}:</strong> {{ data.createdAt | date:'short' }}</p>
<h3>{{ 'includedCommands' | translate }}</h3>
<p><strong>ID del Grupo:</strong> {{ data.uuid }}</p>
<p><strong>Fecha de Creación:</strong> {{ data.createdAt | date:'short' }}</p>
<h3>Comandos Incluidos:</h3>
<table mat-table [dataSource]="data.commands" class="mat-elevation-z8">
<ng-container matColumnDef="name">
<th mat-header-cell *matHeaderCellDef> {{ 'nameColumn' | translate }} </th>
<th mat-header-cell *matHeaderCellDef> Nombre </th>
<td mat-cell *matCellDef="let command"> {{ command.name }} </td>
</ng-container>
@ -29,30 +27,31 @@
<tr mat-row *matRowDef="let row; columns: ['name', 'uuid'];"></tr>
</table>
</mat-card-content>
</mat-card>
<!-- Sección para seleccionar clientes -->
<div class="additional-section" *ngIf="showClientSelect && !loading">
<div class="additional-section" *ngIf="showClientSelect">
<form [formGroup]="form">
<h4>{{ 'selectClients' | translate }}</h4>
<h4>Selecciona los clientes:</h4>
<mat-form-field appearance="fill">
<mat-label>{{ 'clientsLabel' | translate }}</mat-label>
<mat-label>Clientes</mat-label>
<mat-select formControlName="selectedClients" multiple (selectionChange)="onClientSelectionChange($event)">
<mat-option *ngFor="let client of clients" [value]="client.uuid">
{{ client.name }}
</mat-option>
</mat-select>
<mat-error *ngIf="form.get('selectedClients')?.invalid && form.get('selectedClients')?.touched">
{{ 'selectAtLeastOneClient' | translate }}
Debes seleccionar al menos un cliente.
</mat-error>
</mat-form-field>
</form>
</div>
<div class="action-container" *ngIf="!loading">
<button class="ordinary-button" (click)="close()">{{ 'buttonCancel' | translate }}</button>
<button [ngClass]="showClientSelect ? 'submit-button' : 'action-button'" (click)="toggleClientSelect()">
{{ showClientSelect ? ('execute' | translate) : ('scheduleExecution' | translate) }}
<div class="command-group-actions">
<button mat-flat-button color="primary" (click)="toggleClientSelect()">
{{ showClientSelect ? 'Ejecutar' : 'Programar Ejecución' }}
</button>
<button mat-flat-button color="warn" (click)="close()">Cancelar</button>
</div>
</div>
</div>

View File

@ -3,7 +3,6 @@ import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { HttpClient } from '@angular/common/http';
import { ToastrService } from 'ngx-toastr';
import { ConfigService } from '@services/config.service';
@Component({
selector: 'app-detail-command-group',
@ -11,51 +10,36 @@ import { ConfigService } from '@services/config.service';
styleUrls: ['./detail-command-group.component.css']
})
export class DetailCommandGroupComponent implements OnInit {
baseUrl: string;
baseUrl: string = import.meta.env.NG_APP_BASE_API_URL;
form!: FormGroup;
clients: any[] = [];
showClientSelect = false;
showClientSelect = false; // Ocultar selección de clientes inicialmente
canExecute = false;
loading: boolean = false;
constructor(
@Inject(MAT_DIALOG_DATA) public data: any,
private dialogRef: MatDialogRef<DetailCommandGroupComponent>,
private fb: FormBuilder,
private configService: ConfigService,
private http: HttpClient,
private toastService: ToastrService
) {
this.baseUrl = this.configService.apiUrl;
}
) { }
ngOnInit(): void {
this.form = this.fb.group({
selectedClients: [[], Validators.required],
});
this.loadClients();
}
loadClients(): void {
this.loading = true;
this.http.get<any>(`${this.baseUrl}/clients?page=1&itemsPerPage=30`).subscribe({
next: (response) => {
this.clients = response['hydra:member'];
this.loading = false;
},
error: (error) => {
console.error('Error fetching clients:', error);
this.loading = false;
}
// Obtener la lista de clientes
this.http.get<any>(`${this.baseUrl}/clients?page=1&itemsPerPage=30`).subscribe(response => {
this.clients = response['hydra:member'];
});
}
toggleClientSelect(): void {
if (!this.showClientSelect) {
this.showClientSelect = true;
this.showClientSelect = true; // Mostrar selección de clientes
} else {
this.execute();
this.execute(); // Ejecutar si ya está visible
}
}
@ -66,16 +50,13 @@ export class DetailCommandGroupComponent implements OnInit {
};
const apiUrl = `${this.baseUrl}/command-groups/${this.data.uuid}/execute`;
this.loading = true;
this.http.post(apiUrl, payload).subscribe({
next: () => {
this.dialogRef.close();
this.toastService.success('Grupo de comandos ejecutado exitosamente');
this.loading = false;
},
error: (error) => {
console.error('Error ejecutando grupo de comandos:', error);
this.loading = false;
}
});
} else {

View File

@ -1,12 +1,11 @@
.header-container-title {
flex-grow: 1;
text-align: left;
margin-left: 1em;
.title {
font-size: 24px;
}
.task-button-row {
.calendar-button-row {
display: flex;
gap: 15px;
justify-content: flex-start;
margin-top: 16px;
}
.divider {
@ -28,6 +27,7 @@
table {
width: 100%;
margin-top: 50px;
}
.search-container {
@ -35,7 +35,7 @@ table {
justify-content: space-between;
align-items: center;
width: 100%;
margin: 1.5rem 0rem 1.5rem 0rem;
padding: 0 5px;
box-sizing: border-box;
}
@ -53,8 +53,7 @@ table {
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px 10px;
border-bottom: 1px solid #ddd;
padding: 10px;
}
.mat-elevation-z8 {

View File

@ -1,75 +1,63 @@
<div class="header-container">
<button mat-icon-button color="primary" (click)="iniciarTour()">
<mat-icon>help</mat-icon>
</button>
<div class="header-container-title">
<h2 class="title" joyrideStep="titleStep" text="{{ 'titleStepText' | translate }}">{{ 'manageTasksTitle' | translate }}</h2>
</div>
<h2 class="title">Administrar Tareas</h2>
<div class="task-button-row">
<button class="action-button" (click)="openCreateTaskModal()" joyrideStep="addTaskStep" text="{{ 'addTaskStepText' | translate }}">
{{ 'addTask' | translate }}
</button>
<button mat-flat-button color="primary" (click)="openCreateTaskModal()">Añadir Tarea</button>
</div>
</div>
<div class="search-container" joyrideStep="searchStep" text="{{ 'searchStepText' | translate }}">
<mat-divider class="divider"></mat-divider>
<div class="search-container">
<mat-form-field appearance="fill" class="search-string">
<mat-label>{{ 'searchTaskLabel' | translate }}</mat-label>
<input matInput placeholder="{{ 'searchPlaceholder' | translate }}" [(ngModel)]="filters['name']" (keyup.enter)="search()" />
<mat-label>Buscar tarea</mat-label>
<input matInput placeholder="Búsqueda" [(ngModel)]="filters['name']" (keyup.enter)="search()" />
<mat-icon matSuffix>search</mat-icon>
<mat-hint>{{ 'searchHint' | translate }}</mat-hint>
<mat-hint>Pulsar 'enter' para buscar</mat-hint>
</mat-form-field>
</div>
<div *ngIf="!loading">
<table mat-table [dataSource]="tasks" class="mat-elevation-z8" joyrideStep="tableStep" text="{{ 'tableStepText' | translate }}">
<ng-container matColumnDef="taskid">
<th mat-header-cell *matHeaderCellDef> {{ 'idColumn' | translate }} </th>
<td mat-cell *matCellDef="let task"> {{ task.id }} </td>
</ng-container>
<table mat-table [dataSource]="tasks" class="mat-elevation-z8">
<ng-container matColumnDef="taskid">
<th mat-header-cell *matHeaderCellDef> Id</th>
<td mat-cell *matCellDef="let task"> {{ task.id }} </td>
</ng-container>
<ng-container matColumnDef="notes">
<th mat-header-cell *matHeaderCellDef> {{ 'infoColumn' | translate }} </th>
<td mat-cell *matCellDef="let task"> {{ task.notes }} </td>
</ng-container>
<ng-container matColumnDef="notes">
<th mat-header-cell *matHeaderCellDef> Info</th>
<td mat-cell *matCellDef="let task"> {{ task.notes }} </td>
</ng-container>
<ng-container matColumnDef="name">
<th mat-header-cell *matHeaderCellDef> {{ 'createdByColumn' | translate }} </th>
<td mat-cell *matCellDef="let task"> {{ task.createdBy }} </td>
</ng-container>
<ng-container matColumnDef="name">
<th mat-header-cell *matHeaderCellDef> Creado por </th>
<td mat-cell *matCellDef="let task"> {{ task.createdBy }} </td>
</ng-container>
<ng-container matColumnDef="scheduledDate">
<th mat-header-cell *matHeaderCellDef> {{ 'executionDateColumn' | translate }} </th>
<td mat-cell *matCellDef="let task"> {{ task.dateTime | date:'short' }} </td>
</ng-container>
<ng-container matColumnDef="scheduledDate">
<th mat-header-cell *matHeaderCellDef> Fecha de Ejecución </th>
<td mat-cell *matCellDef="let task"> {{ task.dateTime | date:'short' }} </td>
</ng-container>
<ng-container matColumnDef="enabled">
<th mat-header-cell *matHeaderCellDef> {{ 'statusColumn' | translate }} </th>
<td mat-cell *matCellDef="let task"> {{ task.enabled ? ('enabled' | translate) : ('disabled' | translate) }} </td>
</ng-container>
<ng-container matColumnDef="enabled">
<th mat-header-cell *matHeaderCellDef> Estado </th>
<td mat-cell *matCellDef="let task"> {{ task.enabled ? 'Habilitado' : 'Deshabilitado' }} </td>
</ng-container>
<ng-container matColumnDef="actions">
<th mat-header-cell *matHeaderCellDef style="text-align: center;">{{ 'columnActions' | translate }}</th>
<td mat-cell *matCellDef="let task" style="text-align: center;" joyrideStep="actionsStep" text="{{ 'actionsStepText' | translate }}">
<button mat-icon-button color="info" (click)="viewTaskDetails(task)">
<mat-icon>visibility</mat-icon>
</button>
<button mat-icon-button color="primary" (click)="editTask(task)">
<mat-icon>edit</mat-icon>
</button>
<button mat-icon-button color="warn" (click)="deleteTask(task)">
<mat-icon>delete</mat-icon>
</button>
</td>
</ng-container>
<ng-container matColumnDef="actions">
<th mat-header-cell *matHeaderCellDef i18n="@@columnActions" style="text-align: center;">Acciones</th>
<td mat-cell *matCellDef="let task" style="text-align: center;">
<button mat-icon-button color="info" (click)="viewTaskDetails(task)"><mat-icon i18n="@@deleteElementTooltip">visibility</mat-icon></button>
<button mat-icon-button color="primary" (click)="editTask(task)" i18n="@@editImage"> <mat-icon>edit</mat-icon></button>
<button mat-icon-button color="warn" (click)="deleteTask(task)">
<mat-icon i18n="@@deleteElementTooltip">delete</mat-icon>
</button>
</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
</div>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
<mat-paginator joyrideStep="paginationStep" text="{{ 'paginationStepText' | translate }}"
[length]="length"
<mat-paginator [length]="length"
[pageSize]="itemsPerPage"
[pageSizeOptions]="pageSizeOptions"
(page)="onPageChange($event)">

View File

@ -7,22 +7,14 @@ import { MatDividerModule } from '@angular/material/divider';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatPaginatorModule } from '@angular/material/paginator';
import { FormsModule } from '@angular/forms';
import { MatInputModule } from '@angular/material/input';
import { MatInputModule } from '@angular/material/input';
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { TranslateModule } from '@ngx-translate/core';
import { LoadingComponent } from '../../../shared/loading/loading.component';
import { JoyrideModule, JoyrideService, JoyrideStepService } from 'ngx-joyride';
import { ConfigService } from '@services/config.service';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
describe('CommandsTaskComponent', () => {
let component: CommandsTaskComponent;
let fixture: ComponentFixture<CommandsTaskComponent>;
let mockConfigService: jasmine.SpyObj<ConfigService>;
beforeEach(async () => {
const configServiceSpy = jasmine.createSpyObj('ConfigService', [], { apiUrl: 'http://mock-api-url' });
await TestBed.configureTestingModule({
imports: [
HttpClientTestingModule,
@ -33,18 +25,11 @@ describe('CommandsTaskComponent', () => {
MatPaginatorModule,
FormsModule,
MatInputModule,
BrowserAnimationsModule,
TranslateModule.forRoot(),
JoyrideModule.forRoot(),
],
declarations: [CommandsTaskComponent, LoadingComponent],
providers: [
{ provide: ConfigService, useValue: configServiceSpy }
BrowserAnimationsModule
],
declarations: [CommandsTaskComponent],
schemas: [NO_ERRORS_SCHEMA]
}).compileComponents();
mockConfigService = TestBed.inject(ConfigService) as jasmine.SpyObj<ConfigService>;
});
beforeEach(() => {

View File

@ -5,8 +5,6 @@ import { ToastrService } from 'ngx-toastr';
import { CreateTaskComponent } from './create-task/create-task.component';
import { DetailTaskComponent } from './detail-task/detail-task.component';
import { DeleteModalComponent } from '../../../shared/delete_modal/delete-modal/delete-modal.component';
import { JoyrideService } from 'ngx-joyride';
import { ConfigService } from '@services/config.service';
@Component({
selector: 'app-commands-task',
@ -14,23 +12,17 @@ import { ConfigService } from '@services/config.service';
styleUrls: ['./commands-task.component.css']
})
export class CommandsTaskComponent implements OnInit {
baseUrl: string;
baseUrl: string = import.meta.env.NG_APP_BASE_API_URL;
tasks: any[] = [];
filters: { [key: string]: string | boolean } = {};
length: number = 0;
itemsPerPage: number = 10;
page: number = 1;
pageSizeOptions: number[] = [5, 10, 20, 40, 100];
displayedColumns: string[] = ['taskid', 'notes', 'name', 'scheduledDate', 'enabled', 'actions'];
loading: boolean = false;
private apiUrl: string;
displayedColumns: string[] = ['taskid','notes','name', 'scheduledDate', 'enabled', 'actions'];
private apiUrl = `${this.baseUrl}/command-tasks`;
constructor(private http: HttpClient, private dialog: MatDialog, private toastService: ToastrService,
private configService: ConfigService,
private joyrideService: JoyrideService) {
this.baseUrl = this.configService.apiUrl;
this.apiUrl = `${this.baseUrl}/command-tasks`;
}
constructor(private http: HttpClient, private dialog: MatDialog, private toastService: ToastrService) {}
ngOnInit(): void {
this.loadTasks();
@ -42,16 +34,13 @@ export class CommandsTaskComponent implements OnInit {
}
loadTasks(): void {
this.loading = true;
this.http.get<any>(`${this.apiUrl}?page=${this.page}&itemsPerPage=${this.itemsPerPage}`, { params: this.filters }).subscribe(
(data) => {
this.tasks = data['hydra:member'];
this.length = data['hydra:totalItems'];
this.loading = false;
},
(error) => {
console.error('Error fetching tasks', error);
this.loading = false;
}
);
}
@ -59,7 +48,7 @@ export class CommandsTaskComponent implements OnInit {
viewTaskDetails(task: any): void {
this.dialog.open(DetailTaskComponent, {
width: '800px',
data: { task },
data: {task},
}).afterClosed().subscribe(() => this.loadTasks());
}
@ -100,20 +89,4 @@ export class CommandsTaskComponent implements OnInit {
this.itemsPerPage = event.pageSize;
this.loadTasks();
}
iniciarTour(): void {
this.joyrideService.startTour({
steps: [
'titleStep',
'addTaskStep',
'searchStep',
'tableStep',
'actionsStep',
'paginationStep'
],
showPrevButton: true,
themeColor: '#3f51b5'
});
}
}

View File

@ -12,17 +12,10 @@
.button-container {
display: flex;
justify-content: flex-end;
justify-content: space-between;
margin-top: 20px;
padding: 1.5rem;
}
mat-form-field {
margin-bottom: 16px;
}
.section-title {
margin-top: 24px;
margin-bottom: 8px;
font-weight: 500;
margin-bottom: 16px; /* Espaciado entre campos */
}

View File

@ -1,106 +1,108 @@
<h2 mat-dialog-title class="dialog-title">{{ editing ? ('editTask' | translate) : ('createTask' | translate) }}</h2>
<h2 mat-dialog-title class="dialog-title">{{ editing ? 'Editar Tarea' : 'Crear Tarea' }}</h2>
<form [formGroup]="taskForm" class="task-form">
<mat-dialog-content>
<mat-horizontal-stepper linear>
<!-- Paso 1: Información y Selecciona Comandos -->
<mat-step label="Información y Selecciona Comandos">
<mat-form-field appearance="fill" class="full-width">
<mat-label>Información</mat-label>
<textarea matInput formControlName="notes" placeholder="Ingresa tus notas aquí"></textarea>
</mat-form-field>
<h3 class="section-title">Información</h3>
<mat-divider></mat-divider>
<mat-form-field appearance="fill" class="full-width">
<mat-label>Información</mat-label>
<textarea matInput formControlName="notes" placeholder="Ingresa tus notas aquí"></textarea>
</mat-form-field>
<mat-form-field appearance="fill" class="full-width">
<mat-label>Selecciona Comandos</mat-label>
<mat-select formControlName="commandGroup" (selectionChange)="onCommandGroupChange()">
<mat-option *ngFor="let group of availableCommandGroups" [value]="group.uuid">
{{ group.name }}
</mat-option>
</mat-select>
<mat-error *ngIf="taskForm.get('commandGroup')?.invalid">Este campo es obligatorio</mat-error>
</mat-form-field>
<h3 class="section-title">{{ 'informationSectionTitle' | translate }}</h3>
<mat-divider></mat-divider>
<mat-form-field appearance="fill" class="full-width">
<mat-label>{{ 'informationLabel' | translate }}</mat-label>
<textarea matInput formControlName="notes" placeholder="{{ 'notesPlaceholder' | translate }}"></textarea>
</mat-form-field>
<div class="button-container">
<button mat-raised-button color="primary" matStepperNext [disabled]="taskForm.get('commandGroup')?.invalid">Continuar</button>
</div>
</mat-step>
<h3 class="section-title">{{ 'commandSelectionSectionTitle' | translate }}</h3>
<mat-divider></mat-divider>
<mat-form-field appearance="fill" class="full-width">
<mat-label>{{ 'selectCommandsLabel' | translate }}</mat-label>
<mat-select formControlName="commandGroup" (selectionChange)="onCommandGroupChange()">
<mat-option *ngFor="let group of availableCommandGroups" [value]="group.uuid">
{{ group.name }}
</mat-option>
</mat-select>
<mat-error *ngIf="taskForm.get('commandGroup')?.invalid">{{ 'requiredFieldError' | translate }}</mat-error>
</mat-form-field>
<!-- Paso 2: Selecciona Comandos Individuales -->
<mat-step label="Selecciona Comandos Individuales">
<mat-form-field appearance="fill" class="full-width">
<mat-label>Selecciona Comandos Individuales (Opcional)</mat-label>
<mat-select formControlName="extraCommands" multiple>
<mat-option *ngFor="let command of availableIndividualCommands" [value]="command.uuid">
{{ command.name }}
</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field appearance="fill" class="full-width">
<mat-label>{{ 'selectIndividualCommandsLabel' | translate }}</mat-label>
<mat-select formControlName="extraCommands" multiple>
<mat-option *ngFor="let command of availableIndividualCommands" [value]="command.uuid">
{{ command.name }}
</mat-option>
</mat-select>
</mat-form-field>
<div class="button-container">
<button mat-button matStepperPrevious>Atrás</button>
<button mat-raised-button color="primary" matStepperNext>Continuar</button>
</div>
</mat-step>
<h3 class="section-title">{{ 'executionDateTimeSectionTitle' | translate }}</h3>
<mat-divider></mat-divider>
<mat-form-field appearance="fill" class="full-width">
<mat-label>{{ 'executionDateLabel' | translate }}</mat-label>
<input matInput [matDatepicker]="picker" formControlName="date" placeholder="{{ 'selectDatePlaceholder' | translate }}">
<mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
<mat-datepicker #picker></mat-datepicker>
<mat-error *ngIf="taskForm.get('date')?.invalid">{{ 'requiredFieldError' | translate }}</mat-error>
</mat-form-field>
<!-- Paso 3: Fecha de Ejecución y Hora -->
<mat-step label="Fecha de Ejecución y Hora">
<mat-form-field appearance="fill" class="full-width">
<mat-label>Fecha de Ejecución</mat-label>
<input matInput [matDatepicker]="picker" formControlName="date" placeholder="Selecciona una fecha">
<mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
<mat-datepicker #picker></mat-datepicker>
<mat-error *ngIf="taskForm.get('date')?.invalid">Este campo es obligatorio</mat-error>
</mat-form-field>
<mat-form-field appearance="fill" class="full-width">
<mat-label>{{ 'executionTimeLabel' | translate }}</mat-label>
<input matInput type="time" formControlName="time" placeholder="{{ 'selectTimePlaceholder' | translate }}">
<mat-error *ngIf="taskForm.get('time')?.invalid">{{ 'requiredFieldError' | translate }}</mat-error>
</mat-form-field>
<mat-form-field appearance="fill" class="full-width">
<mat-label>Hora de Ejecución</mat-label>
<input matInput type="time" formControlName="time" placeholder="Selecciona una hora">
<mat-error *ngIf="taskForm.get('time')?.invalid">Este campo es obligatorio</mat-error>
</mat-form-field>
<h3 class="section-title">{{ 'destinationSelectionSectionTitle' | translate }}</h3>
<mat-divider></mat-divider>
<mat-form-field appearance="fill" class="full-width">
<mat-label>{{ 'selectOrganizationalUnitLabel' | translate }}</mat-label>
<mat-select formControlName="organizationalUnit" (selectionChange)="onOrganizationalUnitChange()">
<mat-option *ngFor="let unit of availableOrganizationalUnits" [value]="unit['@id']">
{{ unit.name }}
</mat-option>
</mat-select>
<mat-error *ngIf="taskForm.get('organizationalUnit')?.invalid">{{ 'requiredFieldError' | translate }}</mat-error>
</mat-form-field>
<div class="button-container">
<button mat-button matStepperPrevious>Atrás</button>
<button mat-raised-button color="primary" matStepperNext>Continuar</button>
</div>
</mat-step>
<mat-form-field appearance="fill" class="full-width">
<mat-label>{{ 'selectClassroomLabel' | translate }}</mat-label>
<mat-select formControlName="selectedChild" (selectionChange)="onChildChange()">
<mat-option *ngFor="let child of selectedUnitChildren" [value]="child['@id']">
{{ child.name }}
</mat-option>
</mat-select>
</mat-form-field>
<!-- Paso 4: Selecciona Unidad Organizacional, Aula y Clientes -->
<mat-step label="Selecciona Unidad Organizacional, Aula y Clientes">
<mat-form-field appearance="fill" class="full-width">
<mat-label>Selecciona Unidad Organizacional</mat-label>
<mat-select formControlName="organizationalUnit" (selectionChange)="onOrganizationalUnitChange()">
<mat-option *ngFor="let unit of availableOrganizationalUnits" [value]="unit['@id']">
{{ unit.name }}
</mat-option>
</mat-select>
<mat-error *ngIf="taskForm.get('organizationalUnit')?.invalid">Este campo es obligatorio</mat-error>
</mat-form-field>
<mat-form-field appearance="fill" class="full-width">
<mat-label>{{ 'selectClientsLabel' | translate }}</mat-label>
<mat-select formControlName="selectedClients" multiple>
<mat-option (click)="toggleSelectAll()" [selected]="areAllSelected()">
{{ 'selectAllClients' | translate }}
</mat-option>
<mat-option *ngFor="let client of selectedClients" [value]="client.uuid">
{{ client.name }} ({{ client.ip }})
</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field appearance="fill" class="full-width">
<mat-label>Selecciona aula</mat-label>
<mat-select formControlName="selectedChild" (selectionChange)="onChildChange()">
<mat-option *ngFor="let child of selectedUnitChildren" [value]="child['@id']">
{{ child.name }}
</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field appearance="fill" class="full-width">
<mat-label>Selecciona Clientes</mat-label>
<mat-select formControlName="selectedClients" multiple>
<mat-option (click)="toggleSelectAll()" [selected]="areAllSelected()">
Seleccionar todos
</mat-option>
<mat-option *ngFor="let client of selectedClients" [value]="client.uuid">
{{ client.name }} ({{ client.ip }})
</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field appearance="fill" class="full-width">
<mat-label>Selecciona Clientes</mat-label>
<mat-select formControlName="selectedClients" multiple>
<mat-option (click)="toggleSelectAll()" [selected]="areAllSelected()">
Seleccionar todos
</mat-option>
<mat-option *ngFor="let client of selectedClients" [value]="client.uuid">
{{ client.name }} ({{ client.ip }})
</mat-option>
</mat-select>
</mat-form-field>
<div class="button-container">
<button mat-button matStepperPrevious>Atrás</button>
<button mat-raised-button color="primary" (click)="saveTask()">Guardar</button>
</div>
</mat-step>
</mat-horizontal-stepper>
</mat-dialog-content>
</form>
<div class="button-container">
<button class="submit-button" (click)="saveTask()">{{ 'buttonSave' | translate }}</button>
</div>

View File

@ -3,7 +3,6 @@ import { HttpClient } from '@angular/common/http';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { ToastrService } from 'ngx-toastr';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ConfigService } from '@services/config.service';
@Component({
selector: 'app-create-task',
@ -11,12 +10,12 @@ import { ConfigService } from '@services/config.service';
styleUrls: ['./create-task.component.css']
})
export class CreateTaskComponent implements OnInit {
baseUrl: string;
baseUrl: string = import.meta.env.NG_APP_BASE_API_URL;
taskForm: FormGroup;
availableCommandGroups: any[] = [];
selectedGroupCommands: any[] = [];
availableIndividualCommands: any[] = [];
apiUrl: string;
apiUrl = `${this.baseUrl}/command-tasks`;
editing: boolean = false;
availableOrganizationalUnits: any[] = [];
selectedUnitChildren: any[] = [];
@ -26,13 +25,10 @@ export class CreateTaskComponent implements OnInit {
constructor(
private fb: FormBuilder,
private http: HttpClient,
private configService: ConfigService,
private toastr: ToastrService,
public dialogRef: MatDialogRef<CreateTaskComponent>,
@Inject(MAT_DIALOG_DATA) public data: any
) {
this.baseUrl = this.configService.apiUrl;
this.apiUrl = `${this.baseUrl}/command-tasks`;
this.taskForm = this.fb.group({
commandGroup: ['', Validators.required],
extraCommands: [[]],
@ -53,6 +49,8 @@ export class CreateTaskComponent implements OnInit {
this.editing = true;
this.loadTaskData(this.data.task);
}
console.log(this.data);
}
loadCommandGroups(): void {
@ -103,76 +101,6 @@ export class CreateTaskComponent implements OnInit {
}
}
private collectClassrooms(unit: any): any[] {
let classrooms = [];
if (unit.type === 'classroom') {
classrooms.push(unit);
}
if (unit.children && unit.children.length > 0) {
for (let child of unit.children) {
classrooms = classrooms.concat(this.collectClassrooms(child));
}
}
return classrooms;
}
onOrganizationalUnitChange(): void {
const selectedUnitId = this.taskForm.get('organizationalUnit')?.value;
const selectedUnit = this.availableOrganizationalUnits.find(unit => unit['@id'] === selectedUnitId);
if (selectedUnit) {
this.selectedUnitChildren = this.collectClassrooms(selectedUnit);
} else {
this.selectedUnitChildren = [];
}
this.taskForm.patchValue({ selectedChild: '', selectedClients: [] });
this.selectedClients = [];
this.selectedClientIds.clear();
}
onChildChange(): void {
const selectedChildId = this.taskForm.get('selectedChild')?.value;
if (!selectedChildId) {
this.selectedClients = [];
return;
}
const url = `${this.baseUrl}${selectedChildId}`.replace(/([^:]\/)\/+/g, '$1');
this.http.get<any>(url).subscribe(
(data) => {
if (Array.isArray(data.clients) && data.clients.length > 0) {
this.selectedClients = data.clients;
} else {
this.selectedClients = [];
this.toastr.warning('El aula seleccionada no tiene clientes.');
}
this.taskForm.patchValue({ selectedClients: [] });
this.selectedClientIds.clear();
},
(error) => {
this.toastr.error('Error al cargar los detalles del aula seleccionada');
}
);
}
toggleSelectAll() {
const allSelected = this.areAllSelected();
if (allSelected) {
this.selectedClientIds.clear();
} else {
this.selectedClients.forEach(client => this.selectedClientIds.add(client.uuid));
}
this.taskForm.get('selectedClients')!.setValue(Array.from(this.selectedClientIds));
}
areAllSelected(): boolean {
return this.selectedClients.length > 0 && this.selectedClients.every(client => this.selectedClientIds.has(client.uuid));
}
onCommandGroupChange(): void {
const selectedGroupId = this.taskForm.get('commandGroup')?.value;
this.http.get<any>(`${this.baseUrl}/command-groups/${selectedGroupId}`).subscribe(
@ -185,6 +113,40 @@ export class CreateTaskComponent implements OnInit {
);
}
onOrganizationalUnitChange(): void {
const selectedUnitId = this.taskForm.get('organizationalUnit')?.value;
const selectedUnit = this.availableOrganizationalUnits.find(unit => unit['@id'] === selectedUnitId);
this.selectedUnitChildren = selectedUnit ? selectedUnit.children : [];
}
onChildChange(): void {
const selectedChildId = this.taskForm.get('selectedChild')?.value;
this.http.get<any>(`${this.baseUrl}${selectedChildId}`).subscribe(
(data) => {
this.selectedClients = data.clients;
this.taskForm.patchValue({ selectedClients: [] });
this.selectedClientIds.clear();
},
(error) => {
this.toastr.error('Error al cargar los detalles del aula seleccionada');
}
);
}
toggleSelectAll() {
const allSelected = this.areAllSelected();
if (allSelected) {
this.selectedClientIds.clear();
} else {
this.selectedClients.forEach(client => this.selectedClientIds.add(client.uuid));
}
this.taskForm.get('selectedClients')!.setValue(Array.from(this.selectedClientIds));
}
areAllSelected(): boolean {
return this.selectedClients.length > 0 && this.selectedClients.every(client => this.selectedClientIds.has(client.uuid));
}
saveTask(): void {
if (this.taskForm.invalid) {
this.toastr.error('Por favor, rellene todos los campos obligatorios');
@ -194,14 +156,14 @@ export class CreateTaskComponent implements OnInit {
const formData = this.taskForm.value;
const dateTime = this.combineDateAndTime(formData.date, formData.time);
const selectedCommands = formData.extraCommands && formData.extraCommands.length > 0
? formData.extraCommands.map((id: any) => `/commands/${id}`)
: null;
? formData.extraCommands.map((id: any) => `/commands/${id}`)
: null;
const payload: any = {
commandGroups: formData.commandGroup ? [`/command-groups/${formData.commandGroup}`] : null,
dateTime: dateTime,
notes: formData.notes || '',
clients: Array.from(this.selectedClientIds).map((uuid: string) => `/clients/${uuid}`),
clients: Array.from(this.selectedClientIds).map((uuid: string) => `/clients/${uuid}`),
};
if (selectedCommands) {

View File

@ -57,4 +57,26 @@
justify-content: flex-end;
padding: 10px 20px;
}
button {
background-color: #3f51b5;
color: white;
padding: 10px 15px;
border: none;
border-radius: 4px;
cursor: pointer;
}
button:hover {
background-color: #2c387e;
}
.cancel-button {
background-color: #dc3545;
color: white;
}
.cancel-button:hover {
opacity: 0.9;
}

View File

@ -1,55 +1,56 @@
<div class="detail-task-container">
<h2>{{ 'taskDetailsTitle' | translate }}</h2>
<mat-card>
<mat-card-header>
<mat-card-subtitle>{{ 'createdBy' | translate }}: {{ task.createdBy }}</mat-card-subtitle>
</mat-card-header>
<mat-card-content>
<p><strong>{{ 'taskId' | translate }}:</strong> {{ task.uuid }}</p>
<p><strong>{{ 'status' | translate }}:</strong> {{ task.status }}</p>
<p><strong>{{ 'creationDate' | translate }}:</strong> {{ task.createdAt | date: 'short' }}</p>
<p><strong>{{ 'notes' | translate }}:</strong> {{ task.notes }}</p>
<h3>{{ 'includedCommandGroups' | translate }}</h3>
<table mat-table [dataSource]="task.commandGroups" class="mat-elevation-z8">
<ng-container matColumnDef="name">
<th mat-header-cell *matHeaderCellDef> {{ 'commandGroupColumn' | translate }} </th>
<td mat-cell *matCellDef="let group"> {{ group.name }} </td>
</ng-container>
<ng-container matColumnDef="uuid">
<th mat-header-cell *matHeaderCellDef> UUID </th>
<td mat-cell *matCellDef="let group"> {{ group.uuid }} </td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="['name', 'uuid']"></tr>
<tr mat-row *matRowDef="let row; columns: ['name', 'uuid'];"></tr>
</table>
<h3>{{ 'commandsToExecute' | translate }}</h3>
<div *ngFor="let group of task.commandGroups">
<p><strong>{{ 'group' | translate }}: </strong>{{ group.name }}</p>
<table mat-table [dataSource]="group.commands" class="mat-elevation-z8">
<ng-container matColumnDef="commandName">
<th mat-header-cell *matHeaderCellDef> {{ 'commandColumn' | translate }} </th>
<td mat-cell *matCellDef="let command"> {{ command.name }} </td>
<h2>Detalles de la Tarea</h2>
<mat-card>
<mat-card-header>
<mat-card-subtitle>Creado por: {{ task.createdBy }}</mat-card-subtitle>
</mat-card-header>
<mat-card-content>
<p><strong>ID de la Tarea:</strong> {{ task.uuid }}</p>
<p><strong>Estado:</strong> {{ task.status }}</p>
<p><strong>Fecha de Creación:</strong> {{ task.createdAt | date: 'short' }}</p>
<p><strong>Notas:</strong> {{ task.notes }}</p>
<h3>Grupos de Comandos Incluidos:</h3>
<table mat-table [dataSource]="task.commandGroups" class="mat-elevation-z8">
<ng-container matColumnDef="name">
<th mat-header-cell *matHeaderCellDef> Grupo de Comandos </th>
<td mat-cell *matCellDef="let group"> {{ group.name }} </td>
</ng-container>
<ng-container matColumnDef="commandUuid">
<ng-container matColumnDef="uuid">
<th mat-header-cell *matHeaderCellDef> UUID </th>
<td mat-cell *matCellDef="let command"> {{ command.uuid }} </td>
<td mat-cell *matCellDef="let group"> {{ group.uuid }} </td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="['commandName', 'commandUuid']"></tr>
<tr mat-row *matRowDef="let row; columns: ['commandName', 'commandUuid'];"></tr>
<tr mat-header-row *matHeaderRowDef="['name', 'uuid']"></tr>
<tr mat-row *matRowDef="let row; columns: ['name', 'uuid'];"></tr>
</table>
</div>
</mat-card-content>
</mat-card>
<div class="task-actions">
<button class="ordinary-button" (click)="closeDialog()">Cancel</button>
<h3>Comandos a ejecutar:</h3>
<div *ngFor="let group of task.commandGroups">
<p><strong>Grupo: </strong>{{ group.name }}</p>
<table mat-table [dataSource]="group.commands" class="mat-elevation-z8">
<ng-container matColumnDef="commandName">
<th mat-header-cell *matHeaderCellDef> Comando </th>
<td mat-cell *matCellDef="let command"> {{ command.name }} </td>
</ng-container>
<ng-container matColumnDef="commandUuid">
<th mat-header-cell *matHeaderCellDef> UUID </th>
<td mat-cell *matCellDef="let command"> {{ command.uuid }} </td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="['commandName', 'commandUuid']"></tr>
<tr mat-row *matRowDef="let row; columns: ['commandName', 'commandUuid'];"></tr>
</table>
</div>
</mat-card-content>
</mat-card>
<div class="task-actions">
<button mat-flat-button class="cancel-button" (click)="closeDialog()">Cerrar</button>
</div>
</div>
</div>

View File

@ -13,9 +13,11 @@ export class DetailTaskComponent {
public dialogRef: MatDialogRef<DetailTaskComponent>,
@Inject(MAT_DIALOG_DATA) public data: any
) {
this.task = data.task;
this.task = data.task; // Asignamos la tarea que viene en el modal
console.log('tasaas',this.task);
}
// Método opcional para cerrar el modal
closeDialog(): void {
this.dialogRef.close();
}

View File

@ -1,7 +0,0 @@
<h1 mat-dialog-title>{{ 'inputDetails' | translate }}</h1>
<div mat-dialog-content>
<pre>{{ data.input | json }}</pre>
</div>
<div mat-dialog-actions align="end">
<button class="ordinary-button" (click)="close()">{{ 'closeButton' | translate }}</button>
</div>

View File

@ -1,47 +0,0 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { InputDialogComponent } from './input-dialog.component';
import {MAT_DIALOG_DATA, MatDialogModule, MatDialogRef} from "@angular/material/dialog";
import {FormBuilder} from "@angular/forms";
import {ToastrService} from "ngx-toastr";
import {provideHttpClient} from "@angular/common/http";
import {provideHttpClientTesting} from "@angular/common/http/testing";
import {TranslateModule} from "@ngx-translate/core";
describe('InputDialogComponent', () => {
let component: InputDialogComponent;
let fixture: ComponentFixture<InputDialogComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [InputDialogComponent],
imports: [
MatDialogModule,
TranslateModule.forRoot(),
],
providers: [
FormBuilder,
ToastrService,
provideHttpClient(),
provideHttpClientTesting(),
{
provide: MatDialogRef,
useValue: {}
},
{
provide: MAT_DIALOG_DATA,
useValue: {}
}
]
})
.compileComponents();
fixture = TestBed.createComponent(InputDialogComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@ -1,18 +0,0 @@
import { Component, Inject } from '@angular/core';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
@Component({
selector: 'app-input-dialog',
templateUrl: './input-dialog.component.html',
styleUrl: './input-dialog.component.css'
})
export class InputDialogComponent {
constructor(
public dialogRef: MatDialogRef<InputDialogComponent>,
@Inject(MAT_DIALOG_DATA) public data: { input: any }
) {}
close(): void {
this.dialogRef.close();
}
}

View File

@ -1,20 +1,15 @@
.header-container {
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px 10px;
border-bottom: 1px solid #ddd;
}
.header-container-title {
flex-grow: 1;
text-align: left;
margin-left: 1em;
.title {
font-size: 24px;
}
.calendar-button-row {
display: flex;
gap: 15px;
justify-content: flex-start;
margin-top: 16px;
}
.divider {
margin: 20px 0;
}
.lists-container {
@ -32,13 +27,14 @@
table {
width: 100%;
margin-top: 50px;
}
.search-container {
.search-container {
display: flex;
justify-content: space-between;
align-items: center;
margin: 1.5rem 0rem 1.5rem 0rem;
padding: 0 5px;
box-sizing: border-box;
}
@ -57,14 +53,15 @@ table {
padding: 5px;
}
.mat-elevation-z8 {
box-shadow: 0px 0px 0px rgba(0, 0, 0, 0.2);
.header-container {
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px;
}
.progress-container {
display: flex;
align-items: center;
gap: 10px;
.mat-elevation-z8 {
box-shadow: 0px 0px 0px rgba(0,0,0,0.2);
}
.paginator-container {
@ -73,46 +70,13 @@ table {
margin-bottom: 30px;
}
.chip-failed {
background-color: #e87979 !important;
color: white;
.mat-chip-readonly-true {
background-color: #4CAF50 !important;
color: white !important;
}
.chip-success {
background-color: #46c446 !important;
color: white;
.mat-chip-readonly-false {
background-color: #F44336 !important;
color: white !important;
}
.chip-pending {
background-color: #bebdbd !important;
color: black;
}
.chip-in-progress {
background-color: #f5a623 !important;
color: white;
}
.status-progress-flex {
display: flex;
align-items: center;
gap: 8px;
}
button.cancel-button {
display: flex;
align-items: center;
justify-content: center;
padding: 5px;
}
.cancel-button {
color: red;
background-color: transparent;
border: none;
padding: 0;
}
.cancel-button mat-icon {
color: red;
}

View File

@ -1,128 +1,50 @@
<div class="header-container">
<button mat-icon-button color="primary" (click)="iniciarTour()">
<mat-icon>help</mat-icon>
</button>
<div class="header-container-title">
<h2 joyrideStep="titleStep" text="{{ 'titleStepText' | translate }}">{{ 'adminCommandsTitle' |
translate }}</h2>
</div>
<h2 class="title" i18n="@@adminCommandsTitle">Trazas de comandos y procedimientos</h2>
<div class="images-button-row">
<button class="action-button" (click)="resetFilters()" joyrideStep="resetFiltersStep"
text="{{ 'resetFiltersStepText' | translate }}">
{{ 'resetFilters' | translate }}
</button>
<button mat-flat-button color="primary" (click)="resetFilters()">Reiniciar filtros</button>
</div>
</div>
<mat-divider class="divider"></mat-divider>
<div class="search-container">
<mat-form-field appearance="fill" class="search-select" joyrideStep="clientSelectStep"
text="{{ 'clientSelectStepText' | translate }}">
<input type="text" matInput [formControl]="clientControl" [matAutocomplete]="clientAuto"
placeholder="{{ 'filterClientPlaceholder' | translate }}">
<mat-autocomplete #clientAuto="matAutocomplete" [displayWith]="displayFnClient"
(optionSelected)="onOptionClientSelected($event.option.value)">
<mat-form-field appearance="fill" class="search-select">
<input type="text" matInput [formControl]="clientControl" [matAutocomplete]="clientAuto" placeholder="Seleccione un cliente">
<mat-autocomplete #clientAuto="matAutocomplete" [displayWith]="displayFnClient" (optionSelected)="onOptionClientSelected($event.option.value)">
<mat-option *ngFor="let client of filteredClients | async" [value]="client">
{{ client.name }}
</mat-option>
</mat-autocomplete>
</mat-form-field>
<mat-form-field appearance="fill" class="search-select" joyrideStep="commandSelectStep"
text="{{ 'commandSelectStepText' | translate }}">
<input type="text" matInput [formControl]="commandControl" [matAutocomplete]="commandAuto"
placeholder="{{ 'filterCommandPlaceholder' | translate }}">
<mat-autocomplete #commandAuto="matAutocomplete" [displayWith]="displayFnCommand"
(optionSelected)="onOptionCommandSelected($event.option.value)">
<!-- Autocomplete para seleccionar un comando -->
<mat-form-field appearance="fill" class="search-select">
<input type="text" matInput [formControl]="commandControl" [matAutocomplete]="commandAuto" placeholder="Seleccione un comando">
<mat-autocomplete #commandAuto="matAutocomplete" [displayWith]="displayFnCommand" (optionSelected)="onOptionCommandSelected($event.option.value)">
<mat-option *ngFor="let command of filteredCommands | async" [value]="command">
{{ command.name }}
</mat-option>
</mat-autocomplete>
</mat-form-field>
<mat-form-field appearance="fill" class="search-boolean">
<mat-label i18n="@@searchLabel">Estado</mat-label>
<mat-select [(ngModel)]="filters['status']" (selectionChange)="loadTraces()" placeholder="Seleccionar opción">
<mat-option [value]="undefined">Todos</mat-option>
<mat-option [value]="'failed'">Fallido</mat-option>
<mat-option [value]="'pending'">Pendiente de ejecutar</mat-option>
<mat-option [value]="'in-progress'">Ejecutando</mat-option>
<mat-option [value]="'success'">Completado con éxito</mat-option>
<mat-option [value]="'cancelled'">Cancelado</mat-option>
</mat-select>
</mat-form-field>
</div>
<app-loading [isLoading]="loading"></app-loading>
<table mat-table [dataSource]="traces" class="mat-elevation-z8">
<ng-container *ngFor="let column of columns" [matColumnDef]="column.columnDef">
<th mat-header-cell *matHeaderCellDef> {{ column.header }} </th>
<td mat-cell *matCellDef="let trace" >
<ng-container >
{{ column.cell(trace) }}
</ng-container>
</td>
</ng-container>
<div *ngIf="!loading">
<table mat-table [dataSource]="traces" class="mat-elevation-z8" joyrideStep="tableStep"
text="{{ 'tableStepText' | translate }}">
<ng-container *ngFor="let column of columns" [matColumnDef]="column.columnDef">
<th mat-header-cell *matHeaderCellDef> {{ column.header }} </th>
<td mat-cell *matCellDef="let trace">
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
<ng-container [ngSwitch]="column.columnDef">
<ng-container *ngSwitchCase="'status'">
<ng-container *ngIf="trace.status === 'in-progress' && trace.progress; else statusChip">
<div class="progress-container">
<mat-progress-bar class="example-margin" [mode]="mode" [value]="trace.progress" [bufferValue]="bufferValue">
</mat-progress-bar>
<span>{{trace.progress}}%</span>
</div>
</ng-container>
<ng-template #statusChip>
<div class="status-progress-flex">
<mat-chip [ngClass]="{
'chip-failed': trace.status === 'failed',
'chip-success': trace.status === 'success',
'chip-pending': trace.status === 'pending',
'chip-in-progress': trace.status === 'in-progress',
'chip-cancelled': trace.status === 'cancelled'
}">
{{
trace.status === 'failed' ? 'Fallido' :
trace.status === 'in-progress' ? 'En ejecución' :
trace.status === 'success' ? 'Finalizado con éxito' :
trace.status === 'pending' ? 'Pendiente de ejecutar' :
trace.status === 'cancelled' ? 'Cancelado' :
trace.status
}}
</mat-chip>
<button *ngIf="trace.status === 'in-progress' && trace.command === 'deploy-image'"
mat-icon-button
(click)="cancelTrace(trace)"
class="cancel-button"
matTooltip="Cancelar transmisión de imagen">
<mat-icon>cancel</mat-icon>
</button>
</div>
</ng-template>
</ng-container>
<ng-container *ngSwitchCase="'input'">
<button mat-icon-button (click)="openInputModal(trace.input)">
<mat-icon>info</mat-icon>
</button>
</ng-container>
<ng-container *ngSwitchDefault>
{{ column.cell(trace) }}
</ng-container>
</ng-container>
</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
</div>
<div class="paginator-container" joyrideStep="paginationStep" text="{{ 'paginationStepText' | translate }}">
<mat-paginator [length]="length" [pageSize]="itemsPerPage" [pageIndex]="page" [pageSizeOptions]="pageSizeOptions"
(page)="onPageChange($event)">
<div class="paginator-container">
<mat-paginator [length]="length"
[pageSize]="itemsPerPage"
[pageIndex]="page"
[pageSizeOptions]="pageSizeOptions"
(page)="onPageChange($event)">
</mat-paginator>
</div>

View File

@ -1,16 +1,9 @@
import { ChangeDetectorRef, Component, OnInit } from '@angular/core';
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, forkJoin } from 'rxjs';
import { FormControl } from '@angular/forms';
import { map, startWith } from 'rxjs/operators';
import { DatePipe } from '@angular/common';
import { JoyrideService } from 'ngx-joyride';
import { MatDialog } from "@angular/material/dialog";
import { InputDialogComponent } from "./input-dialog/input-dialog.component";
import { ProgressBarMode } from '@angular/material/progress-bar';
import { DeleteModalComponent } from "../../../../shared/delete_modal/delete-modal/delete-modal.component";
import { ToastrService } from "ngx-toastr";
import { ConfigService } from '@services/config.service';
import {Observable, startWith} from 'rxjs';
import {FormControl} from "@angular/forms";
import {map} from "rxjs/operators";
import {DatePipe} from "@angular/common";
@Component({
selector: 'app-task-logs',
@ -18,8 +11,7 @@ import { ConfigService } from '@services/config.service';
styleUrls: ['./task-logs.component.css']
})
export class TaskLogsComponent implements OnInit {
baseUrl: string;
mercureUrl: string;
baseUrl: string = import.meta.env.NG_APP_BASE_API_URL;
traces: any[] = [];
groupedTraces: any[] = [];
commands: any[] = [];
@ -30,9 +22,6 @@ export class TaskLogsComponent implements OnInit {
loading: boolean = true;
pageSizeOptions: number[] = [10, 20, 30, 50];
datePipe: DatePipe = new DatePipe('es-ES');
mode: ProgressBarMode = 'buffer';
progress = 0;
bufferValue = 0;
columns = [
{
@ -43,7 +32,7 @@ export class TaskLogsComponent implements OnInit {
{
columnDef: 'command',
header: 'Comando',
cell: (trace: any) => `${trace.command}`
cell: (trace: any) => `${trace.command?.name}`
},
{
columnDef: 'client',
@ -55,31 +44,16 @@ export class TaskLogsComponent implements OnInit {
header: 'Estado',
cell: (trace: any) => `${trace.status}`
},
{
columnDef: 'jobId',
header: 'Hilo de trabajo',
cell: (trace: any) => `${trace.jobId}`
},
{
columnDef: 'input',
header: 'Input',
cell: (trace: any) => `${trace.input}`
},
{
columnDef: 'output',
header: 'Logs',
cell: (trace: any) => `${trace.output}`
},
{
columnDef: 'executedAt',
header: 'Programación de ejecución',
header: 'Programacion de ejecución',
cell: (trace: any) => `${this.datePipe.transform(trace.executedAt, 'dd/MM/yyyy hh:mm:ss')}`,
},
{
columnDef: 'finishedAt',
header: 'Finalización',
cell: (trace: any) => `${this.datePipe.transform(trace.finishedAt, 'dd/MM/yyyy hh:mm:ss')}`,
},
columnDef: 'createdAt',
header: 'Fecha de creación',
cell: (trace: any) => `${this.datePipe.transform(trace.createdAt, 'dd/MM/yyyy hh:mm:ss')}`,
}
];
displayedColumns = [...this.columns.map(column => column.columnDef)];
@ -89,21 +63,12 @@ export class TaskLogsComponent implements OnInit {
filteredCommands!: Observable<any[]>;
commandControl = new FormControl();
constructor(private http: HttpClient,
private joyrideService: JoyrideService,
private dialog: MatDialog,
private cdr: ChangeDetectorRef,
private configService: ConfigService,
private toastService: ToastrService
) {
this.baseUrl = this.configService.apiUrl;
this.mercureUrl = this.configService.mercureUrl;
}
constructor(private http: HttpClient) {}
ngOnInit(): void {
this.loadTraces();
this.loadCommands();
//this.loadClients();
this.loadClients();
this.filteredCommands = this.commandControl.valueChanges.pipe(
startWith(''),
map(value => (typeof value === 'string' ? value : value?.name)),
@ -114,39 +79,8 @@ export class TaskLogsComponent implements OnInit {
map(value => (typeof value === 'string' ? value : value?.name)),
map(name => (name ? this._filterClients(name) : this.clients.slice()))
);
const eventSource = new EventSource(`${this.mercureUrl}?topic=`
+ encodeURIComponent(`traces`));
eventSource.onmessage = (event) => {
const data = JSON.parse(event.data);
if (data && data['@id']) {
this.updateTracesStatus(data['@id'], data.status, data.progress);
}
}
}
private updateTracesStatus(clientUuid: string, newStatus: string, progress: Number): void {
const traceIndex = this.traces.findIndex(trace => trace['@id'] === clientUuid);
if (traceIndex !== -1) {
const updatedTraces = [...this.traces];
updatedTraces[traceIndex] = {
...updatedTraces[traceIndex],
status: newStatus,
progress: progress
};
this.traces = updatedTraces;
this.cdr.detectChanges();
console.log(`Estado actualizado para la traza ${clientUuid}: ${newStatus}`);
} else {
console.warn(`Traza con UUID ${clientUuid} no encontrado en la lista.`);
}
}
private _filterClients(name: string): any[] {
const filterValue = name.toLowerCase();
return this.clients.filter(client => client.name.toLowerCase().includes(filterValue));
@ -175,87 +109,41 @@ export class TaskLogsComponent implements OnInit {
this.loadTraces();
}
openInputModal(inputData: any): void {
this.dialog.open(InputDialogComponent, {
width: '700px',
data: { input: inputData }
});
}
cancelTrace(trace: any): void {
this.dialog.open(DeleteModalComponent, {
width: '300px',
data: { name: trace.jobId },
}).afterClosed().subscribe((result) => {
if (result) {
this.http.post(`${this.baseUrl}/traces/server/${trace.uuid}/cancel`, {}).subscribe({
next: () => {
this.toastService.success('Transmision de imagen cancelada');
this.loadTraces();
},
error: (error) => {
this.toastService.error(error.error['hydra:description']);
console.error(error.error['hydra:description']);
}
});
}
});
}
loadTraces(): void {
this.loading = true;
const url = `${this.baseUrl}/traces?page=${this.page + 1}&itemsPerPage=${this.itemsPerPage}`;
const params = { ...this.filters };
if (params['status'] === undefined) {
delete params['status'];
}
this.http.get<any>(url, { params }).subscribe(
this.http.get<any>(url, { params: this.filters }).subscribe(
(data) => {
this.traces = data['hydra:member'];
this.length = data['hydra:totalItems'];
this.groupedTraces = this.groupByCommandId(this.traces);
this.loading = false;
},
(error) => {
console.error('Error fetching traces', error);
this.loading = false;
}
);
}
loadCommands() {
this.loading = true;
this.http.get<any>(`${this.baseUrl}/commands?&page=1&itemsPerPage=10000`).subscribe(
this.http.get<any>( `${this.baseUrl}/commands?&page=1&itemsPerPage=10000`).subscribe(
response => {
this.commands = response['hydra:member'];
this.loading = false;
},
error => {
console.error('Error fetching commands:', error);
console.error('Error fetching parent units:', error);
this.loading = false;
}
);
}
loadClients() {
this.loading = true;
this.http.get<any>(`${this.baseUrl}/clients?&page=1&itemsPerPage=10000`).subscribe(
this.http.get<any>( `${this.baseUrl}/clients?&page=1&itemsPerPage=10000`).subscribe(
response => {
const clientIds = response['hydra:member'].map((client: any) => client['@id']);
const clientDetailsRequests: Observable<any>[] = clientIds.map((id: string) => this.http.get<any>(`${this.baseUrl}${id}`));
forkJoin(clientDetailsRequests).subscribe(
(clients: any[]) => {
this.clients = clients;
this.loading = false;
},
(error: any) => {
console.error('Error fetching client details:', error);
this.loading = false;
}
);
this.clients = response['hydra:member'];
this.loading = false;
},
(error: any) => {
console.error('Error fetching clients:', error);
error => {
console.error('Error fetching parent units:', error);
this.loading = false;
}
);
@ -290,20 +178,4 @@ export class TaskLogsComponent implements OnInit {
this.length = event.length;
this.loadTraces();
}
iniciarTour(): void {
this.joyrideService.startTour({
steps: [
'titleStep',
'resetFiltersStep',
'clientSelectStep',
'commandSelectStep',
'tableStep',
'paginationStep'
],
showPrevButton: true,
themeColor: '#3f51b5'
});
}
}

View File

@ -1,12 +1,11 @@
.header-container-title {
flex-grow: 1;
text-align: left;
margin-left: 1em;
.title {
font-size: 24px;
}
.command-button-row {
.calendar-button-row {
display: flex;
gap: 15px;
justify-content: flex-start;
margin-top: 16px;
}
.divider {
@ -28,6 +27,7 @@
table {
width: 100%;
margin-top: 50px;
}
.search-container {
@ -35,8 +35,8 @@ table {
justify-content: space-between;
align-items: center;
width: 100%;
padding: 0 5px;
box-sizing: border-box;
margin: 1.5rem 0rem 1.5rem 0rem;
}
.search-string {
@ -53,8 +53,7 @@ table {
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px 10px;
border-bottom: 1px solid #ddd;
padding: 10px;
}
.mat-elevation-z8 {

View File

@ -1,60 +1,49 @@
<div class="header-container">
<button mat-icon-button color="primary" (click)="iniciarTour()">
<mat-icon>help</mat-icon>
</button>
<div class="header-container-title">
<h2 joyrideStep="titleStep" text="{{ 'titleStepText' | translate }}">{{ 'CommandsTitle' | translate }}</h2>
</div>
<div class="command-button-row" joyrideStep="addCommandStep" text="{{ 'addCommandStepText' | translate }}">
<button class="action-button" (click)="openCreateCommandModal()">{{ 'addCommand' | translate }}</button>
<h2 class="title" i18n="@@adminCommandsTitle">Administrar Comandos</h2>
<div class="command-button-row">
<button mat-flat-button color="primary" (click)="openCreateCommandModal()">Añadir Comando</button>
</div>
</div>
<div class="search-container" joyrideStep="searchStep" text="{{ 'searchStepText' | translate }}">
<mat-divider class="divider"></mat-divider>
<div class="search-container">
<mat-form-field appearance="fill" class="search-string">
<mat-label>{{ 'searchCommandLabel' | translate }}</mat-label>
<input matInput placeholder="{{ 'searchPlaceholder' | translate }}" [(ngModel)]="filters['name']" (keyup.enter)="search()" />
<mat-label i18n="@@searchLabel">Buscar nombre de comando</mat-label>
<input matInput placeholder="Búsqueda" [(ngModel)]="filters['name']" (keyup.enter)="search()" i18n-placeholder="@@searchPlaceholder">
<mat-icon matSuffix>search</mat-icon>
<mat-hint>{{ 'searchHint' | translate }}</mat-hint>
<mat-hint i18n="@@searchHint">Pulsar 'enter' para buscar</mat-hint>
</mat-form-field>
</div>
<div *ngIf="loading" class="loading-container" joyrideStep="loadingStep" text="{{ 'loadingStepText' | translate }}">
<app-loading [isLoading]="loading"></app-loading>
</div>
<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
<ng-container *ngFor="let column of columns" [matColumnDef]="column.columnDef">
<th mat-header-cell *matHeaderCellDef> {{ column.header }} </th>
<td mat-cell *matCellDef="let command" >
<ng-container *ngIf="column.columnDef !== 'readOnly'">
{{ column.cell(command) }}
</ng-container>
<ng-container *ngIf="column.columnDef === 'readOnly'" >
<mat-chip *ngIf="command.readOnly" class="mat-chip-readonly-true"><mat-icon style="color:white;">check</mat-icon></mat-chip>
<mat-chip *ngIf="!command.readOnly" class="mat-chip-readonly-false"> <mat-icon style="color:white;">close</mat-icon></mat-chip>
</ng-container>
</td>
</ng-container>
<div *ngIf="!loading">
<table mat-table [dataSource]="dataSource" class="mat-elevation-z8" joyrideStep="tableStep" text="{{ 'tableStepText' | translate }}">
<ng-container *ngFor="let column of columns" [matColumnDef]="column.columnDef">
<th mat-header-cell *matHeaderCellDef> {{ column.header }} </th>
<td mat-cell *matCellDef="let command">
<ng-container *ngIf="column.columnDef !== 'readOnly'">
{{ column.cell(command) }}
</ng-container>
<ng-container matColumnDef="actions">
<th mat-header-cell *matHeaderCellDef i18n="@@columnActions" style="text-align: center;">Acciones</th>
<td mat-cell *matCellDef="let client" style="text-align: center;">
<button mat-icon-button color="info" (click)="viewDetails($event, client)"><mat-icon i18n="@@deleteElementTooltip">visibility</mat-icon></button>
<button mat-icon-button color="primary" (click)="editCommand($event, client)" i18n="@@editImage"> <mat-icon>edit</mat-icon></button>
<button mat-icon-button color="warn" (click)="deleteCommand($event, client)">
<mat-icon i18n="@@deleteElementTooltip">delete</mat-icon>
</button>
</td>
</ng-container>
<ng-container *ngIf="column.columnDef === 'readOnly'">
<mat-icon [color]="command[column.columnDef] ? 'primary' : 'warn'">
{{ command[column.columnDef] ? 'check_circle' : 'cancel' }}
</mat-icon>
</ng-container>
</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
<ng-container matColumnDef="actions">
<th mat-header-cell *matHeaderCellDef style="text-align: center;">{{ 'columnActions' | translate }}</th>
<td mat-cell *matCellDef="let command" style="text-align: center;" joyrideStep="actionsStep" text="{{ 'actionsStepText' | translate }}">
<button mat-icon-button color="info" (click)="viewDetails($event, command)"><mat-icon>visibility</mat-icon></button>
<button mat-icon-button color="primary" [disabled]="command.readOnly" (click)="editCommand($event, command)"><mat-icon>edit</mat-icon></button>
<button mat-icon-button color="warn" [disabled]="command.readOnly" (click)="deleteCommand($event, command)"><mat-icon>delete</mat-icon></button>
</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
</div>
<div class="paginator-container" joyrideStep="paginationStep" text="{{ 'paginationStepText' | translate }}">
<div class="paginator-container">
<mat-paginator [length]="length"
[pageSize]="itemsPerPage"
[pageIndex]="page"

View File

@ -1,73 +1,33 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { MAT_DIALOG_DATA, MatDialogModule, MatDialogRef } from '@angular/material/dialog';
import { ToastrModule } from 'ngx-toastr';
import { MatTableModule } from '@angular/material/table';
import { DatePipe } from '@angular/common';
import { CommandsComponent } from './commands.component';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatDividerModule } from '@angular/material/divider';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { MatPaginatorModule } from '@angular/material/paginator';
import { MatProgressSpinner, MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatSelectModule } from '@angular/material/select';
import { MatTooltipModule } from '@angular/material/tooltip';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { NgxChartsModule } from '@swimlane/ngx-charts';
import { TranslateModule } from '@ngx-translate/core';
import { JoyrideModule } from 'ngx-joyride';
import { LoadingComponent } from '../../../shared/loading/loading.component';
import { ConfigService } from '@services/config.service';
import { provideHttpClient, withInterceptorsFromDi } from '@angular/common/http';
import { TreeViewComponent } from '../../groups/shared/tree-view/tree-view.component';
import { MatDialogModule } from '@angular/material/dialog'; // <-- Import MatDialogModule
import { MatFormFieldModule } from '@angular/material/form-field'; // Import for mat-form-field
import { MatInputModule } from '@angular/material/input'; // Import for matInput
import { MatDividerModule } from '@angular/material/divider'; // Import for mat-divider
import { ToastrModule } from 'ngx-toastr'; // Import for Toastr
describe('CommandsComponent', () => {
let component: CommandsComponent;
let fixture: ComponentFixture<CommandsComponent>;
describe('TreeViewComponent', () => {
let component: TreeViewComponent;
let fixture: ComponentFixture<TreeViewComponent>;
beforeEach(async () => {
const mockConfigService = {
apiUrl: 'http://mock-api-url',
mercureUrl: 'http://mock-mercure-url'
};
await TestBed.configureTestingModule({
declarations: [CommandsComponent, LoadingComponent],
declarations: [TreeViewComponent],
imports: [
HttpClientTestingModule,
ToastrModule.forRoot(),
BrowserAnimationsModule,
MatDividerModule,
MatFormFieldModule,
MatInputModule,
MatIconModule,
MatButtonModule,
MatTableModule,
MatPaginatorModule,
MatTooltipModule,
FormsModule,
MatProgressSpinner,
MatProgressSpinnerModule,
MatDialogModule,
ReactiveFormsModule,
MatSelectModule,
NgxChartsModule,
DatePipe,
TranslateModule.forRoot(),
JoyrideModule.forRoot(),
MatDialogModule, // <-- Add MatDialogModule here
MatFormFieldModule, // <-- For mat-form-field
MatInputModule, // <-- For matInput
MatDividerModule, // <-- For mat-divider
ToastrModule.forRoot() // <-- For ToastrService
],
providers: [
{ provide: MatDialogRef, useValue: {} },
{ provide: MAT_DIALOG_DATA, useValue: {} },
{ provide: ConfigService, useValue: mockConfigService }
provideHttpClient(withInterceptorsFromDi())
]
}).compileComponents();
});
})
.compileComponents();
beforeEach(() => {
fixture = TestBed.createComponent(CommandsComponent);
fixture = TestBed.createComponent(TreeViewComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
@ -75,5 +35,4 @@ describe('CommandsComponent', () => {
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@ -5,10 +5,8 @@ import { ToastrService } from 'ngx-toastr';
import { CommandDetailComponent } from './detail-command/command-detail.component';
import { CreateCommandComponent } from './create-command/create-command.component';
import { DeleteModalComponent } from '../../../shared/delete_modal/delete-modal/delete-modal.component';
import { MatTableDataSource } from '@angular/material/table';
import { DatePipe } from '@angular/common';
import { ConfigService } from '@services/config.service';
import { JoyrideService } from 'ngx-joyride';
import {MatTableDataSource} from "@angular/material/table";
import {DatePipe} from "@angular/common";
@Component({
selector: 'app-commands',
@ -16,8 +14,7 @@ import { JoyrideService } from 'ngx-joyride';
styleUrls: ['./commands.component.css']
})
export class CommandsComponent implements OnInit {
baseUrl: string;
private apiUrl: string;
baseUrl: string = import.meta.env.NG_APP_BASE_API_URL;
dataSource = new MatTableDataSource<any>();
filters: { [key: string]: string | boolean } = {};
length: number = 0;
@ -25,7 +22,6 @@ export class CommandsComponent implements OnInit {
page: number = 0;
pageSizeOptions: number[] = [10, 20, 40, 100];
datePipe: DatePipe = new DatePipe('es-ES');
loading: boolean = false;
columns = [
{
columnDef: 'id',
@ -49,28 +45,22 @@ export class CommandsComponent implements OnInit {
}
];
displayedColumns = [...this.columns.map(column => column.columnDef), 'actions'];
private apiUrl = `${this.baseUrl}/commands`;
constructor(private http: HttpClient, private dialog: MatDialog, private toastService: ToastrService,
private joyrideService: JoyrideService, private configService: ConfigService) {
this.baseUrl = this.configService.apiUrl;
this.apiUrl = `${this.baseUrl}/commands`;
}
constructor(private http: HttpClient, private dialog: MatDialog, private toastService: ToastrService) {}
ngOnInit(): void {
this.search();
}
search(): void {
this.loading = true;
this.http.get<any>(`${this.apiUrl}?page=${this.page + 1}&itemsPerPage=${this.itemsPerPage}`, { params: this.filters }).subscribe(
this.http.get<any>(`${this.apiUrl}?page=${this.page +1 }&itemsPerPage=${this.itemsPerPage}`, { params: this.filters }).subscribe(
(data) => {
this.dataSource.data = data['hydra:member'];
this.length = data['hydra:totalItems'];
this.loading = false;
},
(error) => {
console.error('Error fetching commands', error);
this.loading = false;
}
);
}
@ -80,24 +70,24 @@ export class CommandsComponent implements OnInit {
this.dialog.open(CommandDetailComponent, {
width: '800px',
data: command,
});
}).afterClosed().subscribe(() => this.search());
}
openCreateCommandModal(): void {
this.dialog.open(CreateCommandComponent, {
width: '800px',
width: '600px',
}).afterClosed().subscribe(() => this.search());
}
editCommand(event: MouseEvent, command: any): void {
event.stopPropagation();
this.dialog.open(CreateCommandComponent, {
width: '800px',
width: '600px',
data: command['@id']
}).afterClosed().subscribe(() => this.search());
}
deleteCommand(event: MouseEvent, command: any): void {
deleteCommand(event: MouseEvent,command: any): void {
event.stopPropagation();
this.dialog.open(DeleteModalComponent, {
width: '300px',
@ -123,19 +113,4 @@ export class CommandsComponent implements OnInit {
this.length = event.length;
this.search();
}
iniciarTour(): void {
this.joyrideService.startTour({
steps: [
'titleStep',
'addCommandStep',
'searchStep',
'tableStep',
'actionsStep'
],
showPrevButton: true,
themeColor: '#3f51b5'
});
}
}

Some files were not shown because too many files have changed in this diff Show More