Compare commits

..

No commits in common. "develop" and "chore/setup-ci-workflow" have entirely different histories.

390 changed files with 1314 additions and 7248 deletions

View File

@ -1,20 +0,0 @@
---
name: "🐛 Bug Report"
about: "Reportar un fallo, error o comportamiento inesperado"
title: "fix: "
labels: ["type:bug"]
---
### Descripción del Fallo
<!-- Descripción clara del error -->
### Pasos para Reproducir
1. Ir a '...'
2. Ejecutar '...'
3. Ver el fallo
### Comportamiento Esperado
<!-- Qué debería suceder -->
### Logs o Evidencia
<!-- Traza de error, logs de red o capturas -->

View File

@ -1,19 +0,0 @@
---
name: "✨ Feature Request"
about: "Proponer una nueva funcionalidad o módulo para el portafolio"
title: "feat: "
labels: ["type:feature"]
---
### Descripción de la Funcionalidad
<!-- Explicación clara y concisa de lo que se desea lograr -->
### Justificación / Caso de Uso
<!-- ¿Por qué es necesario este cambio o característica? -->
### Criterios de Aceptación
- [ ] Criterio 1
- [ ] Criterio 2
### Consideraciones Técnicas
<!-- Frontend Angular, Backend .NET, BD MySQL o UI -->

View File

@ -1,16 +0,0 @@
---
name: "🛠️ Tarea Técnica / Chore"
about: "Mantenimiento, dependencias, refactorización o infraestructura CI/CD"
title: "chore: "
labels: ["type:chore"]
---
### Objetivo Técnico
<!-- Descripción del cambio técnico o de infraestructura -->
### Tareas a Ejecutar
- [ ] Tarea 1
- [ ] Tarea 2
### Criterios de Aceptación
- [ ] Pipeline CI exitoso (build y escaneo de secretos)

View File

@ -1,15 +0,0 @@
## Tipo de Cambio
- [ ] `feat`: Nueva funcionalidad
- [ ] `fix`: Corrección de bug
- [ ] `chore`: Tarea de mantenimiento / CI
- [ ] `refactor`: Refactorización de código
- [ ] `docs`: Actualización de documentación
## Resumen del Cambio
<!-- Explica brevemente qué resuelve o implementa este Pull Request -->
## Verificaciones
- [ ] El título sigue la convención Conventional Commits (ej. `feat(auth): mensaje`, `chore(ci): mensaje`)
- [ ] La rama de origen sigue el estándar (`feature/*`, `chore/*`, `fix/*`, etc.)
- [ ] No contiene secretos, tokens ni contraseñas
- [ ] Compila exitosamente en local

View File

@ -25,68 +25,6 @@ jobs:
git fetch --depth 1 origin ${{ github.sha }}
git checkout --force FETCH_HEAD
- name: Validate Pull Request Metadata
if: github.event_name == 'pull_request'
env:
PR_HEAD_REF: ${{ github.head_ref }}
PR_BASE_REF: ${{ github.base_ref }}
PR_TITLE: ${{ github.event.pull_request.title }}
PR_BODY: ${{ github.event.pull_request.body }}
run: |
echo "==> Validando Pull Request: '$PR_TITLE'"
echo " Rama origen: $PR_HEAD_REF -> Rama destino: $PR_BASE_REF"
if [[ "$PR_BASE_REF" == "develop" ]]; then
if ! [[ "$PR_HEAD_REF" =~ ^(feature|feat|chore|fix|bugfix|refactor|docs|test|perf)/ ]]; then
echo "❌ Error de Rama: Pull Requests hacia 'develop' deben provenir de una rama específica (feature/*, chore/*, fix/*, refactor/*, etc.)."
echo " Rama recibida: '$PR_HEAD_REF'"
exit 1
fi
elif [[ "$PR_BASE_REF" == "main" || "$PR_BASE_REF" == "master" ]]; then
if ! [[ "$PR_HEAD_REF" =~ ^(release|hotfix)/ || "$PR_HEAD_REF" == "develop" ]]; then
echo "❌ Error de Rama: Pull Requests hacia producción ('main') deben provenir de 'develop', 'release/*' o 'hotfix/*'."
echo " Rama recibida: '$PR_HEAD_REF'"
exit 1
fi
fi
TITLE_REGEX="^(feat|fix|chore|docs|style|refactor|perf|test|build|ci|revert)(\([a-zA-Z0-9_\-\./]+\))?!?: .+"
if ! [[ "$PR_TITLE" =~ $TITLE_REGEX ]]; then
echo "❌ Error de Título: El título del PR debe seguir Conventional Commits."
echo " Formato: <tipo>(<ámbito opcional>): <descripción>"
echo " Ejemplos: feat(auth): add login form, fix: resolve token refresh, chore(ci): update runner"
echo " Título recibido: '$PR_TITLE'"
exit 1
fi
CLEAN_BODY=$(echo "$PR_BODY" | tr -d '[:space:]')
if [[ ${#CLEAN_BODY} -lt 15 ]]; then
echo "❌ Error de Descripción: La descripción del Pull Request no puede estar vacía."
echo " Por favor explica brevemente qué cambios incluye este PR para facilitar la revisión."
exit 1
fi
echo "✅ Validaciones de Pull Request aprobadas."
- name: Scan for Leaked Secrets & Credentials
run: |
ARCH=$(uname -m)
case "$ARCH" in
x86_64) GITLEAKS_ARCH="x64" ;;
aarch64|arm64) GITLEAKS_ARCH="arm64" ;;
*) GITLEAKS_ARCH="x64" ;;
esac
mkdir -p /tmp/bin
if ! command -v gitleaks &> /dev/null; then
echo "Descargando Gitleaks para $ARCH ($GITLEAKS_ARCH)..."
curl -sSL "https://github.com/gitleaks/gitleaks/releases/download/v8.18.4/gitleaks_8.18.4_linux_${GITLEAKS_ARCH}.tar.gz" | tar -xz -C /tmp/bin gitleaks
export PATH="/tmp/bin:$PATH"
fi
echo "Ejecutando escaneo de credenciales y secretos..."
gitleaks detect --source . --verbose --no-git
- name: Install Frontend Dependencies
run: |
cd src/frontend
@ -96,68 +34,3 @@ jobs:
run: |
cd src/frontend
npm run build -- --configuration production
validate-backend:
name: Build & Test Backend (.NET)
runs-on: dotnet-runner
steps:
- name: Checkout Code
run: |
command -v git >/dev/null || (apt-get update && apt-get install -y --no-install-recommends git)
git config --global --add safe.directory "*"
git init
git remote add origin https://git.bryan-bano.com/Bryan.bano/PORTFOLIO.git 2>/dev/null || git remote set-url origin https://git.bryan-bano.com/Bryan.bano/PORTFOLIO.git
git fetch --depth 1 origin ${{ github.sha }}
git checkout --force FETCH_HEAD
- name: Build & Run Backend Unit Tests
run: |
dotnet test src/backend/Portfolio.sln -c Release --verbosity normal
- name: Validate Backend Production Publish
run: |
dotnet publish src/backend/src/Portfolio.WebApi/Portfolio.WebApi.csproj -c Release -o /tmp/publish
deploy-backend:
name: Continuous Deployment to Production VPS
needs: [validate-frontend, validate-backend]
if: github.event_name == 'push' && (github.ref == 'refs/heads/develop' || github.ref == 'refs/heads/main')
runs-on: ubuntu-latest
steps:
- name: Deploy Docker Stack on VPS via SSH
env:
SSH_KEY: ${{ secrets.VPS_SSH_KEY }}
VPS_HOST: ${{ secrets.VPS_HOST }}
VPS_USER: ${{ secrets.VPS_USER }}
VPS_PORT: ${{ secrets.VPS_PORT }}
VPS_DEPLOY_PATH: ${{ secrets.VPS_DEPLOY_PATH }}
run: |
if [ -z "$SSH_KEY" ] || [ -z "$VPS_HOST" ]; then
echo "ℹ️ Modo Standby de Despliegue Automático:"
echo " Los secretos VPS_SSH_KEY o VPS_HOST aún no están configurados en Forgejo (Settings -> Actions -> Secrets)."
echo " Para habilitar despliegue desatendido en cada push, añade estos secretos."
echo " Alternativamente, puedes ejecutar en tu VPS: cd /opt/portfolio/deploy && ./deploy.sh"
exit 0
fi
echo "==> Iniciando conexión SSH segura con el VPS ($VPS_HOST)..."
mkdir -p ~/.ssh
echo "$SSH_KEY" > ~/.ssh/id_rsa
chmod 600 ~/.ssh/id_rsa
ssh -o StrictHostKeyChecking=no -p "${VPS_PORT:-22}" "${VPS_USER:-root}@${VPS_HOST}" "bash -s" << 'EOF'
set -e
echo "==> Conectado al VPS. Actualizando repositorio..."
TARGET_DIR="${VPS_DEPLOY_PATH:-/opt/portfolio}"
if [ ! -d "$TARGET_DIR" ]; then
TARGET_DIR="$HOME/portfolio"
fi
cd "$TARGET_DIR"
git fetch origin develop
git checkout develop
git pull origin develop
echo "==> Reconstruyendo contenedor de la API en producción..."
cd deploy
docker compose -f docker-compose.prod.yml up -d --build portfolio-api
echo "✅ Despliegue continuo completado con éxito."
EOF

View File

@ -1,20 +0,0 @@
---
name: "🐛 Bug Report"
about: "Reportar un fallo, error o comportamiento inesperado"
title: "fix: "
labels: ["type:bug"]
---
### Descripción del Fallo
<!-- Descripción clara del error -->
### Pasos para Reproducir
1. Ir a '...'
2. Ejecutar '...'
3. Ver el fallo
### Comportamiento Esperado
<!-- Qué debería suceder -->
### Logs o Evidencia
<!-- Traza de error, logs de red o capturas -->

View File

@ -1,19 +0,0 @@
---
name: "✨ Feature Request"
about: "Proponer una nueva funcionalidad o módulo para el portafolio"
title: "feat: "
labels: ["type:feature"]
---
### Descripción de la Funcionalidad
<!-- Explicación clara y concisa de lo que se desea lograr -->
### Justificación / Caso de Uso
<!-- ¿Por qué es necesario este cambio o característica? -->
### Criterios de Aceptación
- [ ] Criterio 1
- [ ] Criterio 2
### Consideraciones Técnicas
<!-- Frontend Angular, Backend .NET, BD MySQL o UI -->

View File

@ -1,16 +0,0 @@
---
name: "🛠️ Tarea Técnica / Chore"
about: "Mantenimiento, dependencias, refactorización o infraestructura CI/CD"
title: "chore: "
labels: ["type:chore"]
---
### Objetivo Técnico
<!-- Descripción del cambio técnico o de infraestructura -->
### Tareas a Ejecutar
- [ ] Tarea 1
- [ ] Tarea 2
### Criterios de Aceptación
- [ ] Pipeline CI exitoso (build y escaneo de secretos)

View File

@ -1,15 +0,0 @@
## Tipo de Cambio
- [ ] `feat`: Nueva funcionalidad
- [ ] `fix`: Corrección de bug
- [ ] `chore`: Tarea de mantenimiento / CI
- [ ] `refactor`: Refactorización de código
- [ ] `docs`: Actualización de documentación
## Resumen del Cambio
<!-- Explica brevemente qué resuelve o implementa este Pull Request -->
## Verificaciones
- [ ] El título sigue la convención Conventional Commits (ej. `feat(auth): mensaje`, `chore(ci): mensaje`)
- [ ] La rama de origen sigue el estándar (`feature/*`, `chore/*`, `fix/*`, etc.)
- [ ] No contiene secretos, tokens ni contraseñas
- [ ] Compila exitosamente en local

View File

@ -25,68 +25,6 @@ jobs:
git fetch --depth 1 origin ${{ github.sha }}
git checkout --force FETCH_HEAD
- name: Validate Pull Request Metadata
if: github.event_name == 'pull_request'
env:
PR_HEAD_REF: ${{ github.head_ref }}
PR_BASE_REF: ${{ github.base_ref }}
PR_TITLE: ${{ github.event.pull_request.title }}
PR_BODY: ${{ github.event.pull_request.body }}
run: |
echo "==> Validando Pull Request: '$PR_TITLE'"
echo " Rama origen: $PR_HEAD_REF -> Rama destino: $PR_BASE_REF"
if [[ "$PR_BASE_REF" == "develop" ]]; then
if ! [[ "$PR_HEAD_REF" =~ ^(feature|feat|chore|fix|bugfix|refactor|docs|test|perf)/ ]]; then
echo "❌ Error de Rama: Pull Requests hacia 'develop' deben provenir de una rama específica (feature/*, chore/*, fix/*, refactor/*, etc.)."
echo " Rama recibida: '$PR_HEAD_REF'"
exit 1
fi
elif [[ "$PR_BASE_REF" == "main" || "$PR_BASE_REF" == "master" ]]; then
if ! [[ "$PR_HEAD_REF" =~ ^(release|hotfix)/ || "$PR_HEAD_REF" == "develop" ]]; then
echo "❌ Error de Rama: Pull Requests hacia producción ('main') deben provenir de 'develop', 'release/*' o 'hotfix/*'."
echo " Rama recibida: '$PR_HEAD_REF'"
exit 1
fi
fi
TITLE_REGEX="^(feat|fix|chore|docs|style|refactor|perf|test|build|ci|revert)(\([a-zA-Z0-9_\-\./]+\))?!?: .+"
if ! [[ "$PR_TITLE" =~ $TITLE_REGEX ]]; then
echo "❌ Error de Título: El título del PR debe seguir Conventional Commits."
echo " Formato: <tipo>(<ámbito opcional>): <descripción>"
echo " Ejemplos: feat(auth): add login form, fix: resolve token refresh, chore(ci): update runner"
echo " Título recibido: '$PR_TITLE'"
exit 1
fi
CLEAN_BODY=$(echo "$PR_BODY" | tr -d '[:space:]')
if [[ ${#CLEAN_BODY} -lt 15 ]]; then
echo "❌ Error de Descripción: La descripción del Pull Request no puede estar vacía."
echo " Por favor explica brevemente qué cambios incluye este PR para facilitar la revisión."
exit 1
fi
echo "✅ Validaciones de Pull Request aprobadas."
- name: Scan for Leaked Secrets & Credentials
run: |
ARCH=$(uname -m)
case "$ARCH" in
x86_64) GITLEAKS_ARCH="x64" ;;
aarch64|arm64) GITLEAKS_ARCH="arm64" ;;
*) GITLEAKS_ARCH="x64" ;;
esac
mkdir -p /tmp/bin
if ! command -v gitleaks &> /dev/null; then
echo "Descargando Gitleaks para $ARCH ($GITLEAKS_ARCH)..."
curl -sSL "https://github.com/gitleaks/gitleaks/releases/download/v8.18.4/gitleaks_8.18.4_linux_${GITLEAKS_ARCH}.tar.gz" | tar -xz -C /tmp/bin gitleaks
export PATH="/tmp/bin:$PATH"
fi
echo "Ejecutando escaneo de credenciales y secretos..."
gitleaks detect --source . --verbose --no-git
- name: Install Frontend Dependencies
run: |
cd src/frontend
@ -96,66 +34,3 @@ jobs:
run: |
cd src/frontend
npm run build -- --configuration production
validate-backend:
name: Build & Test Backend (.NET)
runs-on: dotnet-runner
steps:
- name: Checkout Code
run: |
command -v git >/dev/null || (apt-get update && apt-get install -y --no-install-recommends git)
git config --global --add safe.directory "*"
git init
git remote add origin https://git.bryan-bano.com/Bryan.bano/PORTFOLIO.git 2>/dev/null || git remote set-url origin https://git.bryan-bano.com/Bryan.bano/PORTFOLIO.git
git fetch --depth 1 origin ${{ github.sha }}
git checkout --force FETCH_HEAD
- name: Build & Run Backend Unit Tests
run: |
dotnet test src/backend/Portfolio.sln -c Release --verbosity normal
- name: Validate Backend Production Publish
run: |
dotnet publish src/backend/src/Portfolio.WebApi/Portfolio.WebApi.csproj -c Release -o /tmp/publish
deploy-backend:
name: Continuous Deployment to Production VPS
needs: [validate-frontend, validate-backend]
if: github.event_name == 'push' && (github.ref == 'refs/heads/develop' || github.ref == 'refs/heads/main')
runs-on: ubuntu-latest
steps:
- name: Deploy Docker Stack on VPS via SSH
env:
SSH_KEY: ${{ secrets.VPS_SSH_KEY }}
VPS_HOST: ${{ secrets.VPS_HOST }}
VPS_USER: ${{ secrets.VPS_USER }}
VPS_PORT: ${{ secrets.VPS_PORT }}
VPS_DEPLOY_PATH: ${{ secrets.VPS_DEPLOY_PATH }}
run: |
if [ -z "$SSH_KEY" ] || [ -z "$VPS_HOST" ]; then
echo "ℹ️ Modo Standby de Despliegue Automático:"
echo " Los secretos VPS_SSH_KEY o VPS_HOST aún no están configurados."
exit 0
fi
echo "==> Iniciando conexión SSH segura con el VPS ($VPS_HOST)..."
mkdir -p ~/.ssh
echo "$SSH_KEY" > ~/.ssh/id_rsa
chmod 600 ~/.ssh/id_rsa
ssh -o StrictHostKeyChecking=no -p "${VPS_PORT:-22}" "${VPS_USER:-root}@${VPS_HOST}" "bash -s" << 'EOF'
set -e
echo "==> Conectado al VPS. Actualizando repositorio..."
TARGET_DIR="${VPS_DEPLOY_PATH:-/opt/portfolio}"
if [ ! -d "$TARGET_DIR" ]; then
TARGET_DIR="$HOME/portfolio"
fi
cd "$TARGET_DIR"
git fetch origin develop
git checkout develop
git pull origin develop
echo "==> Reconstruyendo contenedor de la API en producción..."
cd deploy
docker compose -f docker-compose.prod.yml up -d --build portfolio-api
echo "✅ Despliegue continuo completado con éxito."
EOF

6
.gitignore vendored
View File

@ -41,9 +41,3 @@ desktop.ini
*.pem
*.key
*.pfx
# .NET Configuration & Sensitive AppSettings
**/appsettings.json
**/appsettings.Production.json
!**/appsettingsdevelop.json

View File

@ -1,11 +0,0 @@
title = "Portfolio Gitleaks Configuration"
[allowlist]
description = "Exclusiones globales de documentación, dependencias compiladas y falsos positivos"
paths = [
'''(?i)package-lock\.json$''',
'''(?i)\.angular/.*''',
'''(?i)node_modules/.*''',
'''(?i)dist/.*''',
'''(?i)\.git/.*'''
]

View File

@ -1,6 +0,0 @@
# Gitleaks Ignore List
# Añade aquí fingerprints (huellas) de secretos detectados que sean falsos positivos confirmados.
# Formato: una huella o regla por línea.
#
# Para ignorar un falso positivo directamente en el código fuente, añade el comentario:
# const fakeToken = "example_dummy_token"; // gitleaks:allow

View File

@ -1,149 +0,0 @@
# Guía de Despliegue en Producción: Backend .NET, MySQL & Cloudflare Tunnel
Este directorio contiene la orquestación completa para desplegar el backend (.NET 8/9 Clean Architecture) y la base de datos MySQL 8.0 en tu servidor VPS de Oracle Cloud (`srv-personal-core`), exponiéndola de forma segura a través de **Cloudflare Zero Trust Tunnel** sin abrir puertos directos en el firewall.
---
## 1. Arquitectura de Despliegue
```
[Internet / Visitantes]
│
▼
[Cloudflare Edge Network & WAF]
│ (Túnel cifrado WireGuard / QUIC)
▼
[cloudflared (Tunnel Daemon)]
│ (Red interna de Docker: portfolio-network)
┌─────────────┴─────────────┐
▼ ▼
[portfolio_api] [portfolio_n8n]
(.NET 8 Kestrel :8080) (n8n Engine :5678)
│
▼
[portfolio_mysql]
(MySQL 8.0 :3306)
```
---
## 2. Preparación en el VPS (Oracle Cloud)
### Paso 2.1: Navegar al directorio del proyecto
Conéctate por SSH a tu VPS y clona o actualiza el repositorio:
```bash
# Si es la primera vez:
cd /opt # o tu directorio preferido, e.g. ~/portfolio
git clone https://git.bryan-bano.com/Bryan.bano/PORTFOLIO.git
cd PORTFOLIO
# Si ya tienes el repositorio, actualiza la rama develop:
git checkout develop
git pull origin develop
```
### Paso 2.2: Configurar Variables de Entorno (`.env`)
Copia la plantilla de entorno:
```bash
cd deploy
cp .env.example .env
```
Edita `.env` con tu editor preferido (`nano .env` o `vim .env`):
- **`DB_ROOT_PASSWORD`**: Genera una contraseña segura para el usuario root de MySQL.
- **`DB_PASSWORD`**: Genera una contraseña para el usuario `portfolio_user`.
- **`JWT_SECRET_KEY`**: Genera una clave criptográfica de al menos 32 caracteres ejecutando:
```bash
openssl rand -base64 48
```
- **`CLOUDFLARE_TUNNEL_TOKEN`**: Pega aquí el token de tu túnel de Cloudflare (obtenido en el Paso 3).
---
## 3. Configuración en el Panel de Cloudflare Zero Trust
Para que `https://api.bryan-bano.com` enrute automáticamente al backend en tu VPS:
1. Ingresa a **[Cloudflare Zero Trust Dashboard](https://one.dash.cloudflare.com/)**.
2. Ve a **Networks** -> **Tunnels**.
3. Selecciona tu túnel activo (por ejemplo el que ya usas para `git.bryan-bano.com` o `n8n.bryan-bano.com`), o haz clic en **Create a Tunnel** si prefieres uno independiente.
4. En la pestaña **Public Hostnames**, haz clic en **Add a public hostname**:
- **Subdomain:** `api`
- **Domain:** `bryan-bano.com`
- **Path:** (dejar vacío)
- **Type:** `HTTP`
- **URL:**
- Si usas el contenedor `portfolio_tunnel` de este compose: `portfolio-api:8080`
- Si ya tienes `cloudflared` corriendo como servicio en el host o en otro contenedor compartido: `localhost:8080` (o `127.0.0.1:8080`)
5. Haz clic en **Save hostname**.
---
## 4. Iniciar los Servicios con Docker Compose
Desde la carpeta `deploy/` del VPS, ejecuta:
```bash
docker compose -f docker-compose.prod.yml up -d --build
```
### ¿Qué hace este comando automáticamente?
1. **Compila la API .NET en Release:** Usa el `Dockerfile` multi-stage, compila con el SDK de .NET y genera el contenedor ligero en `aspnet:8.0`.
2. **Inicia MySQL 8.0:** Crea el volumen persistente `portfolio_mysql_data` y ejecuta el script `init-db.sql` con los esquemas y datos iniciales (proyectos, habilidades y récords).
3. **Sincroniza el Esquema de EF Core:** Al arrancar, el backend ejecuta `EnsureCreated()` para verificar y garantizar que todas las tablas y relaciones estén en sincronía.
4. **Levanta el Cloudflare Tunnel:** Conecta la API a la red perimetral de Cloudflare con HTTPS y SSL automáticos.
---
## 5. Verificación y Pruebas en Vivo
Una vez iniciado el contenedor, ejecuta las siguientes comprobaciones:
### 5.1 Verificar estado de los contenedores
```bash
docker compose -f docker-compose.prod.yml ps
```
Deberías ver `portfolio_api`, `portfolio_mysql` (healthy) y `portfolio_tunnel` (opcional) en estado `Up`.
### 5.2 Probar la API localmente en el VPS
```bash
curl http://localhost:8080/
# Respuesta esperada:
# {"service":"Portfolio Backend API","status":"Online","version":"1.0.0","docs":"/swagger"}
```
### 5.3 Probar la API pública con SSL
```bash
curl https://api.bryan-bano.com/
curl https://api.bryan-bano.com/api/v1/telemetry
```
### 5.4 Documentación Swagger en Producción
Abre en tu navegador:
```
https://api.bryan-bano.com/swagger
```
---
## 6. Mantenimiento y Comandos Útiles
- **Ver logs de la API en tiempo real:**
```bash
docker logs -f portfolio_api
```
- **Ver logs de la base de datos:**
```bash
docker logs -f portfolio_mysql
```
- **Reiniciar la API tras una actualización de código:**
```bash
git pull origin develop
docker compose -f docker-compose.prod.yml up -d --build portfolio-api
```
- **Realizar backup de la base de datos MySQL:**
```bash
docker exec portfolio_mysql mysqldump -u portfolio_user -p portfolio_db > backup_$(date +%F).sql
```

View File

@ -1,39 +0,0 @@
#!/usr/bin/env bash
# ==============================================================================
# Script de Despliegue Continuo / Actualización en el VPS
# ==============================================================================
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROOT_DIR="$(dirname "$SCRIPT_DIR")"
echo "========================================================"
echo "🚀 INICIANDO DESPLIEGUE EN PRODUCCIÓN (PORTFOLIO)"
echo "========================================================"
cd "$ROOT_DIR"
echo "==> [1/4] Actualizando rama develop desde Forgejo..."
git fetch origin develop
git checkout develop
git pull origin develop
echo "==> [2/4] Verificando variables de entorno en deploy/.env..."
if [ ! -f "$SCRIPT_DIR/.env" ]; then
echo "❌ Error: No existe el archivo $SCRIPT_DIR/.env"
echo " Copia $SCRIPT_DIR/.env.example a $SCRIPT_DIR/.env y rellena tus claves."
exit 1
fi
echo "==> [3/4] Compilando y levantando contenedores Docker..."
cd "$SCRIPT_DIR"
docker compose -f docker-compose.prod.yml up -d --build
echo "==> [4/4] Comprobando salud de los servicios..."
sleep 5
docker compose -f docker-compose.prod.yml ps
echo "========================================================"
echo "✅ DESPLIEGUE COMPLETADO EXITOSAMENTE"
echo " API disponible en: http://localhost:8080 o https://api.bryan-bano.com"
echo "========================================================"

View File

@ -1,75 +0,0 @@
services:
portfolio-api:
build:
context: ../src/backend
dockerfile: Dockerfile
image: portfolio-backend:latest
container_name: portfolio_api
restart: unless-stopped
ports:
- "8080:8080"
environment:
- ASPNETCORE_ENVIRONMENT=Production
- ASPNETCORE_URLS=http://+:8080
- ConnectionStrings__DefaultConnection=Server=portfolio-mysql;Port=3306;Database=portfolio_db;User=portfolio_user;Password=${DB_PASSWORD};CharSet=utf8mb4;
- JwtSettings__SecretKey=${JWT_SECRET_KEY}
- JwtSettings__Issuer=https://api.bryan-bano.com
- JwtSettings__Audience=https://bryan-bano.com
- CorsSettings__AllowedOrigins__0=https://bryan-bano.com
- CorsSettings__AllowedOrigins__1=https://portfolio.bryan-bano.com
- CorsSettings__AllowedOrigins__2=https://git.bryan-bano.com
- CorsSettings__AllowedOrigins__3=http://localhost:4200
- EnableSwaggerInProd=${ENABLE_SWAGGER:-true}
depends_on:
portfolio-mysql:
condition: service_healthy
networks:
- portfolio-network
portfolio-mysql:
image: mysql:8.0
container_name: portfolio_mysql
restart: unless-stopped
command:
- --default-authentication-plugin=mysql_native_password
- --character-set-server=utf8mb4
- --collation-server=utf8mb4_unicode_ci
- --innodb-buffer-pool-size=256M
- --max-connections=100
environment:
- MYSQL_ROOT_PASSWORD=${DB_ROOT_PASSWORD}
- MYSQL_DATABASE=portfolio_db
- MYSQL_USER=portfolio_user
- MYSQL_PASSWORD=${DB_PASSWORD}
volumes:
- mysql_data:/var/lib/mysql
- ./init-db.sql:/docker-entrypoint-initdb.d/01-init.sql:ro
healthcheck:
test: ["CMD-SHELL", "mysqladmin ping -h localhost -u root -p$${MYSQL_ROOT_PASSWORD} || exit 1"]
interval: 10s
timeout: 5s
retries: 5
start_period: 20s
networks:
- portfolio-network
portfolio-tunnel:
image: cloudflare/cloudflared:latest
container_name: portfolio_tunnel
restart: unless-stopped
command: tunnel run
environment:
- TUNNEL_TOKEN=${CLOUDFLARE_TUNNEL_TOKEN}
depends_on:
- portfolio-api
networks:
- portfolio-network
networks:
portfolio-network:
driver: bridge
name: portfolio_network
volumes:
mysql_data:
name: portfolio_mysql_data

View File

@ -1,116 +0,0 @@
-- ==============================================================================
-- Portfolio MySQL Database Initialization & Seed Script
-- ==============================================================================
CREATE DATABASE IF NOT EXISTS `portfolio_db` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
USE `portfolio_db`;
-- 1. Tabla de Habilidades Técnicas
CREATE TABLE IF NOT EXISTS `Skills` (
`Id` VARCHAR(36) NOT NULL,
`Name` VARCHAR(60) NOT NULL,
`Category` INT NOT NULL,
`ProficiencyPercentage` INT NOT NULL,
`IconUrl` VARCHAR(255) NULL,
`IsFeatured` TINYINT(1) NOT NULL DEFAULT 0,
`CreatedAt` DATETIME(6) NOT NULL,
`UpdatedAt` DATETIME(6) NULL,
PRIMARY KEY (`Id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- 2. Tabla de Proyectos de Producción
CREATE TABLE IF NOT EXISTS `Projects` (
`Id` VARCHAR(36) NOT NULL,
`Title` VARCHAR(120) NOT NULL,
`Slug` VARCHAR(140) NOT NULL,
`Summary` VARCHAR(300) NOT NULL,
`Description` TEXT NOT NULL,
`ArchitectureOverview` TEXT NOT NULL,
`ThumbnailUrl` VARCHAR(255) NULL,
`DemoUrl` VARCHAR(255) NULL,
`RepositoryUrl` VARCHAR(255) NULL,
`IsFeatured` TINYINT(1) NOT NULL DEFAULT 0,
`OrderPriority` INT NOT NULL DEFAULT 0,
`CreatedAt` DATETIME(6) NOT NULL,
`UpdatedAt` DATETIME(6) NULL,
PRIMARY KEY (`Id`),
UNIQUE KEY `UX_Projects_Slug` (`Slug`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- 3. Tabla Intermedia Proyecto - Habilidad (Muchos a Muchos)
CREATE TABLE IF NOT EXISTS `ProjectSkills` (
`ProjectId` VARCHAR(36) NOT NULL,
`SkillId` VARCHAR(36) NOT NULL,
PRIMARY KEY (`ProjectId`, `SkillId`),
CONSTRAINT `FK_ProjectSkills_Projects` FOREIGN KEY (`ProjectId`) REFERENCES `Projects` (`Id`) ON DELETE CASCADE,
CONSTRAINT `FK_ProjectSkills_Skills` FOREIGN KEY (`SkillId`) REFERENCES `Skills` (`Id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- 4. Tabla de Firmas del Muro (Guestbook Wall)
CREATE TABLE IF NOT EXISTS `InteractiveMessages` (
`Id` VARCHAR(36) NOT NULL,
`SenderName` VARCHAR(80) NOT NULL,
`SenderContact` VARCHAR(100) NULL,
`Message` VARCHAR(500) NOT NULL,
`Origin` INT NOT NULL DEFAULT 0,
`IsApproved` TINYINT(1) NOT NULL DEFAULT 1,
`LikesCount` INT NOT NULL DEFAULT 0,
`CreatedAt` DATETIME(6) NOT NULL,
`UpdatedAt` DATETIME(6) NULL,
PRIMARY KEY (`Id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- 5. Tabla de Récords de Videojuegos Retro (Buscaminas)
CREATE TABLE IF NOT EXISTS `GameScores` (
`Id` VARCHAR(36) NOT NULL,
`GameCode` VARCHAR(30) NOT NULL,
`PlayerTag` VARCHAR(10) NOT NULL,
`Score` INT NOT NULL,
`Difficulty` VARCHAR(20) NOT NULL DEFAULT 'NORMAL',
`SessionMetadataJson` TEXT NULL,
`CreatedAt` DATETIME(6) NOT NULL,
`UpdatedAt` DATETIME(6) NULL,
PRIMARY KEY (`Id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- 6. Tabla de Contacto y Solicitudes
CREATE TABLE IF NOT EXISTS `ContactInquiries` (
`Id` VARCHAR(36) NOT NULL,
`FullName` VARCHAR(100) NOT NULL,
`Email` VARCHAR(120) NOT NULL,
`Phone` VARCHAR(30) NULL,
`ServiceType` VARCHAR(80) NOT NULL,
`Details` TEXT NOT NULL,
`Status` INT NOT NULL DEFAULT 0,
`CreatedAt` DATETIME(6) NOT NULL,
`UpdatedAt` DATETIME(6) NULL,
PRIMARY KEY (`Id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- -----------------------------------------------------------------------------
-- Datos Iniciales Semilla (Seeds de Producción)
-- -----------------------------------------------------------------------------
INSERT IGNORE INTO `Skills` (`Id`, `Name`, `Category`, `ProficiencyPercentage`, `IsFeatured`, `CreatedAt`) VALUES
('skill-dotnet', '.NET 8 / .NET 9 Clean Architecture', 0, 95, 1, UTC_TIMESTAMP()),
('skill-csharp', 'C# Moderno (CQRS, MediatR, EF Core)', 0, 95, 1, UTC_TIMESTAMP()),
('skill-angular', 'Angular 20 Standalone & Signals', 1, 92, 1, UTC_TIMESTAMP()),
('skill-mysql', 'MySQL / PostgreSQL / Pomelo', 2, 88, 1, UTC_TIMESTAMP()),
('skill-docker', 'Docker Multi-Stage & Linux ARM64', 3, 90, 1, UTC_TIMESTAMP()),
('skill-n8n', 'n8n Workflow Automation & AI Agents', 4, 92, 1, UTC_TIMESTAMP());
INSERT IGNORE INTO `Projects` (`Id`, `Title`, `Slug`, `Summary`, `Description`, `ArchitectureOverview`, `IsFeatured`, `OrderPriority`, `CreatedAt`) VALUES
('proj-portfolio', 'High-Impact Full-Stack Portfolio', 'high-impact-portfolio',
'Vitrina técnica de alto impacto con Clean Architecture en .NET 8/9, Signals en Angular 20, monitor Retro CRT y automatización con n8n.',
'Portafolio interactivo desarrollado desde cero para demostrar maestría en ingeniería de software, observabilidad en tiempo real y micro-interacciones de 60 FPS.',
'Clean Architecture (.NET Domain, Application con CQRS, Infrastructure Pomelo MySQL, WebApi RFC 7807) + Angular 20 Signals Hexagonal.',
1, 1, UTC_TIMESTAMP());
INSERT IGNORE INTO `GameScores` (`Id`, `GameCode`, `PlayerTag`, `Score`, `Difficulty`, `CreatedAt`) VALUES
('score-1', 'MINESWEEPER', 'ZEN', 42, 'NORMAL', UTC_TIMESTAMP()),
('score-2', 'MINESWEEPER', 'NEO', 68, 'NORMAL', UTC_TIMESTAMP()),
('score-3', 'MINESWEEPER', 'BRY', 95, 'NORMAL', UTC_TIMESTAMP());
INSERT IGNORE INTO `InteractiveMessages` (`Id`, `SenderName`, `SenderContact`, `Message`, `Origin`, `IsApproved`, `CreatedAt`) VALUES
('msg-1', 'Kenji Sato', 'Tokio, Japón', 'Excelente combinación de arquitectura limpia y estética Zen con retro monitor.', 1, 1, UTC_TIMESTAMP()),
('msg-2', 'Sophia Lindqvist', 'Estocolmo, Suecia', 'El packet tracer visual en vivo demuestra un dominio real de redes y backend.', 0, 1, UTC_TIMESTAMP());

View File

@ -1,9 +0,0 @@
**/.git
**/.vs
**/.vscode
**/bin
**/obj
**/appsettings.json
**/appsettings.Development.json
**/*.user
**/*.suo

View File

@ -1,5 +0,0 @@
<Project>
<PropertyGroup>
<RollForward>LatestMajor</RollForward>
</PropertyGroup>
</Project>

View File

@ -1,40 +0,0 @@
# ==============================================================================
# Dockerfile Multi-Stage: Backend .NET 8/9 Clean Architecture (ARM64 / x86_64)
# ==============================================================================
# Stage 1: Build & Publish
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
WORKDIR /src
# Copiar definiciones de solución y proyectos para aprovechar caché de Docker
COPY ["Directory.Build.props", "./"]
COPY ["src/Portfolio.Domain/Portfolio.Domain.csproj", "src/Portfolio.Domain/"]
COPY ["src/Portfolio.Application/Portfolio.Application.csproj", "src/Portfolio.Application/"]
COPY ["src/Portfolio.Infrastructure/Portfolio.Infrastructure.csproj", "src/Portfolio.Infrastructure/"]
COPY ["src/Portfolio.WebApi/Portfolio.WebApi.csproj", "src/Portfolio.WebApi/"]
RUN dotnet restore "src/Portfolio.WebApi/Portfolio.WebApi.csproj"
# Copiar código fuente y publicar artefactos optimizados
COPY ["src/", "src/"]
WORKDIR "/src/src/Portfolio.WebApi"
RUN dotnet publish "Portfolio.WebApi.csproj" -c Release -o /app/publish /p:UseAppHost=false
# ------------------------------------------------------------------------------
# Stage 2: Runtime Production Container
# ------------------------------------------------------------------------------
FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS final
WORKDIR /app
# Puerto no-root estándar de .NET 8/9
EXPOSE 8080
ENV ASPNETCORE_URLS=http://+:8080 \
ASPNETCORE_ENVIRONMENT=Production \
DOTNET_RUNNING_IN_CONTAINER=true
COPY --from=build /app/publish .
# Usuario con privilegios mínimos (UID predeterminado de Microsoft en .NET 8)
USER $APP_UID
ENTRYPOINT ["dotnet", "Portfolio.WebApi.dll"]

View File

@ -1,57 +0,0 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.0.31903.59
MinimumVisualStudioVersion = 10.0.40219.1
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{2FE66466-0214-4DBE-BF8A-F9101D6E2FF7}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Portfolio.Domain", "src\Portfolio.Domain\Portfolio.Domain.csproj", "{36CD767F-7762-4EDF-B71E-94A78B020FE0}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Portfolio.Application", "src\Portfolio.Application\Portfolio.Application.csproj", "{A279BB0E-7D67-4BCB-81FC-F487737A568C}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Portfolio.Infrastructure", "src\Portfolio.Infrastructure\Portfolio.Infrastructure.csproj", "{484FA7A3-6CAA-4C40-8E51-EDB22B5F6D39}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Portfolio.WebApi", "src\Portfolio.WebApi\Portfolio.WebApi.csproj", "{3FD30B3E-9B89-4882-B075-BDD2CAE348ED}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{E7DB5FDA-B947-4EC2-9868-421E8E4FCCD6}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Portfolio.UnitTests", "tests\Portfolio.UnitTests\Portfolio.UnitTests.csproj", "{EF9CB490-2460-42FF-A58D-616191B87DAC}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{36CD767F-7762-4EDF-B71E-94A78B020FE0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{36CD767F-7762-4EDF-B71E-94A78B020FE0}.Debug|Any CPU.Build.0 = Debug|Any CPU
{36CD767F-7762-4EDF-B71E-94A78B020FE0}.Release|Any CPU.ActiveCfg = Release|Any CPU
{36CD767F-7762-4EDF-B71E-94A78B020FE0}.Release|Any CPU.Build.0 = Release|Any CPU
{A279BB0E-7D67-4BCB-81FC-F487737A568C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A279BB0E-7D67-4BCB-81FC-F487737A568C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A279BB0E-7D67-4BCB-81FC-F487737A568C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A279BB0E-7D67-4BCB-81FC-F487737A568C}.Release|Any CPU.Build.0 = Release|Any CPU
{484FA7A3-6CAA-4C40-8E51-EDB22B5F6D39}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{484FA7A3-6CAA-4C40-8E51-EDB22B5F6D39}.Debug|Any CPU.Build.0 = Debug|Any CPU
{484FA7A3-6CAA-4C40-8E51-EDB22B5F6D39}.Release|Any CPU.ActiveCfg = Release|Any CPU
{484FA7A3-6CAA-4C40-8E51-EDB22B5F6D39}.Release|Any CPU.Build.0 = Release|Any CPU
{3FD30B3E-9B89-4882-B075-BDD2CAE348ED}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{3FD30B3E-9B89-4882-B075-BDD2CAE348ED}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3FD30B3E-9B89-4882-B075-BDD2CAE348ED}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3FD30B3E-9B89-4882-B075-BDD2CAE348ED}.Release|Any CPU.Build.0 = Release|Any CPU
{EF9CB490-2460-42FF-A58D-616191B87DAC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{EF9CB490-2460-42FF-A58D-616191B87DAC}.Debug|Any CPU.Build.0 = Debug|Any CPU
{EF9CB490-2460-42FF-A58D-616191B87DAC}.Release|Any CPU.ActiveCfg = Release|Any CPU
{EF9CB490-2460-42FF-A58D-616191B87DAC}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{36CD767F-7762-4EDF-B71E-94A78B020FE0} = {2FE66466-0214-4DBE-BF8A-F9101D6E2FF7}
{A279BB0E-7D67-4BCB-81FC-F487737A568C} = {2FE66466-0214-4DBE-BF8A-F9101D6E2FF7}
{484FA7A3-6CAA-4C40-8E51-EDB22B5F6D39} = {2FE66466-0214-4DBE-BF8A-F9101D6E2FF7}
{3FD30B3E-9B89-4882-B075-BDD2CAE348ED} = {2FE66466-0214-4DBE-BF8A-F9101D6E2FF7}
{EF9CB490-2460-42FF-A58D-616191B87DAC} = {E7DB5FDA-B947-4EC2-9868-421E8E4FCCD6}
EndGlobalSection
EndGlobal

View File

@ -1,36 +0,0 @@
using FluentValidation;
using MediatR;
namespace Portfolio.Application.Common.Behaviors;
public sealed class ValidationBehavior<TRequest, TResponse>(IEnumerable<IValidator<TRequest>> validators)
: IPipelineBehavior<TRequest, TResponse>
where TRequest : notnull
{
public async Task<TResponse> Handle(
TRequest request,
RequestHandlerDelegate<TResponse> next,
CancellationToken cancellationToken)
{
if (!validators.Any())
{
return await next();
}
var context = new ValidationContext<TRequest>(request);
var validationResults = await Task.WhenAll(
validators.Select(v => v.ValidateAsync(context, cancellationToken)));
var failures = validationResults
.SelectMany(r => r.Errors)
.Where(f => f is not null)
.ToList();
if (failures.Count != 0)
{
throw new ValidationException(failures);
}
return await next();
}
}

View File

@ -1,15 +0,0 @@
using Portfolio.Domain.Entities;
namespace Portfolio.Application.Common.Interfaces;
public interface IJwtTokenGenerator
{
string GenerateAccessToken(User user);
string GenerateRefreshToken();
}
public interface IPasswordHasher
{
string Hash(string password);
bool Verify(string password, string passwordHash);
}

View File

@ -1,25 +0,0 @@
using System.Reflection;
using FluentValidation;
using MediatR;
using Microsoft.Extensions.DependencyInjection;
using Portfolio.Application.Common.Behaviors;
namespace Portfolio.Application;
public static class DependencyInjection
{
public static IServiceCollection AddApplication(this IServiceCollection services)
{
var assembly = Assembly.GetExecutingAssembly();
services.AddMediatR(cfg =>
{
cfg.RegisterServicesFromAssembly(assembly);
cfg.AddBehavior(typeof(IPipelineBehavior<,>), typeof(ValidationBehavior<,>));
});
services.AddValidatorsFromAssembly(assembly);
return services;
}
}

View File

@ -1,39 +0,0 @@
using MediatR;
using Portfolio.Application.Features.Guestbook.DTOs;
using Portfolio.Domain.Entities;
using Portfolio.Domain.Enums;
using Portfolio.Domain.Interfaces;
namespace Portfolio.Application.Features.Guestbook.Commands;
public sealed record CreateGuestbookMessageCommand(
string SenderName,
string Message,
MessageOrigin Origin = MessageOrigin.WebForm,
string? SenderContact = null
) : IRequest<GuestbookMessageResponseDto>;
public sealed class CreateGuestbookMessageCommandHandler(IInteractiveMessageRepository messageRepository)
: IRequestHandler<CreateGuestbookMessageCommand, GuestbookMessageResponseDto>
{
public async Task<GuestbookMessageResponseDto> Handle(CreateGuestbookMessageCommand request, CancellationToken cancellationToken)
{
var message = InteractiveMessage.Create(
request.SenderName,
request.Message,
request.Origin,
request.SenderContact
);
await messageRepository.AddAsync(message, cancellationToken);
await messageRepository.SaveChangesAsync(cancellationToken);
return new GuestbookMessageResponseDto(
message.Id,
message.SenderName,
message.Message,
message.Origin,
message.CreatedAtUtc
);
}
}

View File

@ -1,18 +0,0 @@
using Portfolio.Domain.Enums;
namespace Portfolio.Application.Features.Guestbook.DTOs;
public sealed record GuestbookMessageResponseDto(
Guid Id,
string SenderName,
string Message,
MessageOrigin Origin,
DateTime CreatedAtUtc
);
public sealed record CreateGuestbookMessageRequestDto(
string SenderName,
string Message,
MessageOrigin Origin = MessageOrigin.WebForm,
string? SenderContact = null
);

View File

@ -1,24 +0,0 @@
using MediatR;
using Portfolio.Application.Features.Guestbook.DTOs;
using Portfolio.Domain.Interfaces;
namespace Portfolio.Application.Features.Guestbook.Queries;
public sealed record GetGuestbookMessagesQuery(int Limit = 50) : IRequest<IReadOnlyList<GuestbookMessageResponseDto>>;
public sealed class GetGuestbookMessagesQueryHandler(IInteractiveMessageRepository messageRepository)
: IRequestHandler<GetGuestbookMessagesQuery, IReadOnlyList<GuestbookMessageResponseDto>>
{
public async Task<IReadOnlyList<GuestbookMessageResponseDto>> Handle(GetGuestbookMessagesQuery request, CancellationToken cancellationToken)
{
var messages = await messageRepository.GetRecentApprovedAsync(request.Limit, cancellationToken);
return messages.Select(m => new GuestbookMessageResponseDto(
m.Id,
m.SenderName,
m.Message,
m.Origin,
m.CreatedAtUtc
)).ToList();
}
}

View File

@ -1,19 +0,0 @@
using FluentValidation;
using Portfolio.Application.Features.Guestbook.Commands;
namespace Portfolio.Application.Features.Guestbook.Validators;
public sealed class CreateGuestbookMessageCommandValidator : AbstractValidator<CreateGuestbookMessageCommand>
{
public CreateGuestbookMessageCommandValidator()
{
RuleFor(x => x.SenderName)
.NotEmpty().WithMessage("El nombre o alias del remitente es obligatorio.")
.MaximumLength(60).WithMessage("El nombre no puede exceder 60 caracteres.");
RuleFor(x => x.Message)
.NotEmpty().WithMessage("El mensaje no puede estar vacío.")
.MinimumLength(3).WithMessage("El mensaje debe contener al menos 3 caracteres.")
.MaximumLength(500).WithMessage("El mensaje no puede exceder 500 caracteres.");
}
}

View File

@ -1,42 +0,0 @@
using MediatR;
using Portfolio.Application.Features.Leaderboard.DTOs;
using Portfolio.Domain.Entities;
using Portfolio.Domain.Interfaces;
namespace Portfolio.Application.Features.Leaderboard.Commands;
public sealed record SubmitGameScoreCommand(
string PlayerName,
string GameName,
int Score,
int DurationSeconds,
string? CountryCode = null
) : IRequest<GameScoreResponseDto>;
public sealed class SubmitGameScoreCommandHandler(IGameScoreRepository scoreRepository)
: IRequestHandler<SubmitGameScoreCommand, GameScoreResponseDto>
{
public async Task<GameScoreResponseDto> Handle(SubmitGameScoreCommand request, CancellationToken cancellationToken)
{
var gameScore = GameScore.Create(
request.PlayerName,
request.GameName,
request.Score,
request.DurationSeconds,
request.CountryCode
);
await scoreRepository.AddAsync(gameScore, cancellationToken);
await scoreRepository.SaveChangesAsync(cancellationToken);
return new GameScoreResponseDto(
gameScore.Id,
gameScore.PlayerName,
gameScore.GameName,
gameScore.Score,
gameScore.DurationSeconds,
gameScore.CountryCode,
gameScore.CreatedAtUtc
);
}
}

View File

@ -1,19 +0,0 @@
namespace Portfolio.Application.Features.Leaderboard.DTOs;
public sealed record GameScoreResponseDto(
Guid Id,
string PlayerName,
string GameName,
int Score,
int DurationSeconds,
string? CountryCode,
DateTime CreatedAtUtc
);
public sealed record SubmitGameScoreRequestDto(
string PlayerName,
string GameName,
int Score,
int DurationSeconds,
string? CountryCode = null
);

View File

@ -1,27 +0,0 @@
using MediatR;
using Portfolio.Application.Features.Leaderboard.DTOs;
using Portfolio.Domain.Interfaces;
namespace Portfolio.Application.Features.Leaderboard.Queries;
public sealed record GetLeaderboardQuery(string GameName = "Minesweeper", int Limit = 10)
: IRequest<IReadOnlyList<GameScoreResponseDto>>;
public sealed class GetLeaderboardQueryHandler(IGameScoreRepository scoreRepository)
: IRequestHandler<GetLeaderboardQuery, IReadOnlyList<GameScoreResponseDto>>
{
public async Task<IReadOnlyList<GameScoreResponseDto>> Handle(GetLeaderboardQuery request, CancellationToken cancellationToken)
{
var scores = await scoreRepository.GetTopScoresAsync(request.GameName, request.Limit, cancellationToken);
return scores.Select(s => new GameScoreResponseDto(
s.Id,
s.PlayerName,
s.GameName,
s.Score,
s.DurationSeconds,
s.CountryCode,
s.CreatedAtUtc
)).ToList();
}
}

View File

@ -1,24 +0,0 @@
using FluentValidation;
using Portfolio.Application.Features.Leaderboard.Commands;
namespace Portfolio.Application.Features.Leaderboard.Validators;
public sealed class SubmitGameScoreCommandValidator : AbstractValidator<SubmitGameScoreCommand>
{
public SubmitGameScoreCommandValidator()
{
RuleFor(x => x.PlayerName)
.NotEmpty().WithMessage("El nombre del jugador es obligatorio.")
.MaximumLength(30).WithMessage("El nombre no puede exceder 30 caracteres.");
RuleFor(x => x.GameName)
.NotEmpty().WithMessage("El nombre del juego es obligatorio.")
.MaximumLength(30);
RuleFor(x => x.Score)
.GreaterThanOrEqualTo(0).WithMessage("La puntuación no puede ser negativa.");
RuleFor(x => x.DurationSeconds)
.GreaterThanOrEqualTo(0).WithMessage("La duración no puede ser negativa.");
}
}

View File

@ -1,15 +0,0 @@
namespace Portfolio.Application.Features.Projects.DTOs;
public sealed record ProjectResponseDto(
Guid Id,
string Slug,
string Title,
string ShortDescription,
string FullDescription,
string RepositoryUrl,
string? LiveDemoUrl,
string? ThumbnailUrl,
bool IsFeatured,
ushort DisplayOrder,
IReadOnlyList<string> Skills
);

View File

@ -1,32 +0,0 @@
using MediatR;
using Portfolio.Application.Features.Projects.DTOs;
using Portfolio.Domain.Exceptions;
using Portfolio.Domain.Interfaces;
namespace Portfolio.Application.Features.Projects.Queries;
public sealed record GetProjectBySlugQuery(string Slug) : IRequest<ProjectResponseDto>;
public sealed class GetProjectBySlugQueryHandler(IProjectRepository projectRepository)
: IRequestHandler<GetProjectBySlugQuery, ProjectResponseDto>
{
public async Task<ProjectResponseDto> Handle(GetProjectBySlugQuery request, CancellationToken cancellationToken)
{
var p = await projectRepository.GetBySlugAsync(request.Slug, cancellationToken)
?? throw new NotFoundException("Project", request.Slug);
return new ProjectResponseDto(
p.Id,
p.Slug,
p.Title,
p.ShortDescription,
p.FullDescription,
p.RepositoryUrl,
p.LiveDemoUrl,
p.ThumbnailUrl,
p.IsFeatured,
p.DisplayOrder,
p.ProjectSkills.Select(ps => ps.Skill.Name).ToList()
);
}
}

View File

@ -1,30 +0,0 @@
using MediatR;
using Portfolio.Application.Features.Projects.DTOs;
using Portfolio.Domain.Interfaces;
namespace Portfolio.Application.Features.Projects.Queries;
public sealed record GetProjectsQuery(bool FeaturedOnly = false) : IRequest<IReadOnlyList<ProjectResponseDto>>;
public sealed class GetProjectsQueryHandler(IProjectRepository projectRepository)
: IRequestHandler<GetProjectsQuery, IReadOnlyList<ProjectResponseDto>>
{
public async Task<IReadOnlyList<ProjectResponseDto>> Handle(GetProjectsQuery request, CancellationToken cancellationToken)
{
var projects = await projectRepository.GetAllAsync(request.FeaturedOnly, cancellationToken);
return projects.Select(p => new ProjectResponseDto(
p.Id,
p.Slug,
p.Title,
p.ShortDescription,
p.FullDescription,
p.RepositoryUrl,
p.LiveDemoUrl,
p.ThumbnailUrl,
p.IsFeatured,
p.DisplayOrder,
p.ProjectSkills.Select(ps => ps.Skill.Name).ToList()
)).ToList();
}
}

View File

@ -1,13 +0,0 @@
using Portfolio.Domain.Enums;
namespace Portfolio.Application.Features.Skills.DTOs;
public sealed record SkillResponseDto(
Guid Id,
string Name,
SkillCategory Category,
string? IconSlug,
byte ProficiencyPercentage,
ushort DisplayOrder,
bool IsFeatured
);

View File

@ -1,27 +0,0 @@
using MediatR;
using Portfolio.Application.Features.Skills.DTOs;
using Portfolio.Domain.Enums;
using Portfolio.Domain.Interfaces;
namespace Portfolio.Application.Features.Skills.Queries;
public sealed record GetSkillsQuery(SkillCategory? Category = null) : IRequest<IReadOnlyList<SkillResponseDto>>;
public sealed class GetSkillsQueryHandler(ISkillRepository skillRepository)
: IRequestHandler<GetSkillsQuery, IReadOnlyList<SkillResponseDto>>
{
public async Task<IReadOnlyList<SkillResponseDto>> Handle(GetSkillsQuery request, CancellationToken cancellationToken)
{
var skills = await skillRepository.GetAllAsync(request.Category, cancellationToken);
return skills.Select(s => new SkillResponseDto(
s.Id,
s.Name,
s.Category,
s.IconSlug,
s.ProficiencyPercentage,
s.DisplayOrder,
s.IsFeatured
)).ToList();
}
}

View File

@ -1,19 +0,0 @@
namespace Portfolio.Application.Features.Telemetry.DTOs;
public sealed record ServerTelemetryDto(
string Status,
string Region,
string Provider,
string Architecture,
string RuntimeVersion,
TimeSpan Uptime,
double ProcessMemoryMb,
int ActiveThreads,
DateTime ServerTimeUtc
);
public sealed record PingResponseDto(
string Message,
long LatencyMs,
DateTime TimestampUtc
);

View File

@ -1,34 +0,0 @@
using System.Diagnostics;
using System.Runtime.InteropServices;
using MediatR;
using Portfolio.Application.Features.Telemetry.DTOs;
namespace Portfolio.Application.Features.Telemetry.Queries;
public sealed record GetServerTelemetryQuery : IRequest<ServerTelemetryDto>;
public sealed class GetServerTelemetryQueryHandler : IRequestHandler<GetServerTelemetryQuery, ServerTelemetryDto>
{
private static readonly DateTime StartTime = DateTime.UtcNow;
public Task<ServerTelemetryDto> Handle(GetServerTelemetryQuery request, CancellationToken cancellationToken)
{
var process = Process.GetCurrentProcess();
var memoryMb = Math.Round((double)process.WorkingSet64 / (1024 * 1024), 2);
var uptime = DateTime.UtcNow - StartTime;
var dto = new ServerTelemetryDto(
Status: "OPERATIONAL",
Region: "us-ashburn-1",
Provider: "Oracle Cloud Infrastructure (OCI)",
Architecture: $"{RuntimeInformation.OSDescription} ({RuntimeInformation.ProcessArchitecture})",
RuntimeVersion: RuntimeInformation.FrameworkDescription,
Uptime: uptime,
ProcessMemoryMb: memoryMb,
ActiveThreads: process.Threads.Count,
ServerTimeUtc: DateTime.UtcNow
);
return Task.FromResult(dto);
}
}

View File

@ -1,18 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<ItemGroup>
<ProjectReference Include="..\Portfolio.Domain\Portfolio.Domain.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="FluentValidation.DependencyInjectionExtensions" Version="12.2.0" />
<PackageReference Include="MediatR" Version="14.2.0" />
</ItemGroup>
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>

View File

@ -1,7 +0,0 @@
namespace Portfolio.Domain.Common;
public abstract class BaseEntity
{
public Guid Id { get; protected set; } = Guid.NewGuid();
public DateTime CreatedAtUtc { get; protected set; } = DateTime.UtcNow;
}

View File

@ -1,42 +0,0 @@
using Portfolio.Domain.Common;
using Portfolio.Domain.Enums;
namespace Portfolio.Domain.Entities;
public sealed class ContactInquiry : BaseEntity
{
public string FullNameOrCompany { get; private set; } = string.Empty;
public string Email { get; private set; } = string.Empty;
public string? Phone { get; private set; }
public string ServiceType { get; private set; } = "General";
public string ProjectDetails { get; private set; } = string.Empty;
public InquiryStatus Status { get; private set; } = InquiryStatus.New;
public string? IpAddress { get; private set; }
public DateTime? RepliedAtUtc { get; private set; }
private ContactInquiry() { }
public static ContactInquiry Create(
string fullNameOrCompany,
string email,
string projectDetails,
string serviceType = "General",
string? phone = null,
string? ipAddress = null)
{
ArgumentException.ThrowIfNullOrWhiteSpace(fullNameOrCompany);
ArgumentException.ThrowIfNullOrWhiteSpace(email);
ArgumentException.ThrowIfNullOrWhiteSpace(projectDetails);
return new ContactInquiry
{
FullNameOrCompany = fullNameOrCompany.Trim(),
Email = email.Trim().ToLowerInvariant(),
ProjectDetails = projectDetails.Trim(),
ServiceType = serviceType.Trim(),
Phone = phone?.Trim(),
IpAddress = ipAddress,
Status = InquiryStatus.New
};
}
}

View File

@ -1,34 +0,0 @@
using Portfolio.Domain.Common;
namespace Portfolio.Domain.Entities;
public sealed class GameScore : BaseEntity
{
public string PlayerName { get; private set; } = string.Empty;
public string GameName { get; private set; } = "Minesweeper";
public int Score { get; private set; }
public int DurationSeconds { get; private set; }
public string? CountryCode { get; private set; }
private GameScore() { }
public static GameScore Create(
string playerName,
string gameName,
int score,
int durationSeconds,
string? countryCode = null)
{
ArgumentException.ThrowIfNullOrWhiteSpace(playerName);
ArgumentException.ThrowIfNullOrWhiteSpace(gameName);
return new GameScore
{
PlayerName = playerName.Trim(),
GameName = gameName.Trim().ToLowerInvariant(),
Score = score,
DurationSeconds = durationSeconds,
CountryCode = countryCode?.Trim().ToUpperInvariant()
};
}
}

View File

@ -1,34 +0,0 @@
using Portfolio.Domain.Common;
using Portfolio.Domain.Enums;
namespace Portfolio.Domain.Entities;
public sealed class InteractiveMessage : BaseEntity
{
public string SenderName { get; private set; } = string.Empty;
public string? SenderContact { get; private set; }
public string Message { get; private set; } = string.Empty;
public MessageOrigin Origin { get; private set; }
public bool IsApproved { get; private set; } = true;
private InteractiveMessage() { }
public static InteractiveMessage Create(
string senderName,
string message,
MessageOrigin origin = MessageOrigin.Terminal,
string? senderContact = null)
{
ArgumentException.ThrowIfNullOrWhiteSpace(senderName);
ArgumentException.ThrowIfNullOrWhiteSpace(message);
return new InteractiveMessage
{
SenderName = senderName.Trim(),
Message = message.Trim(),
Origin = origin,
SenderContact = senderContact?.Trim(),
IsApproved = true
};
}
}

View File

@ -1,49 +0,0 @@
using Portfolio.Domain.Common;
namespace Portfolio.Domain.Entities;
public sealed class Project : BaseEntity
{
public string Slug { get; private set; } = string.Empty;
public string Title { get; private set; } = string.Empty;
public string ShortDescription { get; private set; } = string.Empty;
public string FullDescription { get; private set; } = string.Empty;
public string RepositoryUrl { get; private set; } = string.Empty;
public string? LiveDemoUrl { get; private set; }
public string? ThumbnailUrl { get; private set; }
public bool IsFeatured { get; private set; }
public ushort DisplayOrder { get; private set; }
public DateTime? UpdatedAtUtc { get; private set; }
public ICollection<ProjectSkill> ProjectSkills { get; private set; } = [];
private Project() { }
public static Project Create(
string slug,
string title,
string shortDescription,
string fullDescription,
string repositoryUrl,
string? liveDemoUrl = null,
string? thumbnailUrl = null,
bool isFeatured = false,
ushort displayOrder = 0)
{
ArgumentException.ThrowIfNullOrWhiteSpace(slug);
ArgumentException.ThrowIfNullOrWhiteSpace(title);
return new Project
{
Slug = slug.Trim().ToLowerInvariant(),
Title = title.Trim(),
ShortDescription = shortDescription.Trim(),
FullDescription = fullDescription.Trim(),
RepositoryUrl = repositoryUrl.Trim(),
LiveDemoUrl = liveDemoUrl?.Trim(),
ThumbnailUrl = thumbnailUrl?.Trim(),
IsFeatured = isFeatured,
DisplayOrder = displayOrder
};
}
}

View File

@ -1,10 +0,0 @@
namespace Portfolio.Domain.Entities;
public sealed class ProjectSkill
{
public Guid ProjectId { get; set; }
public Project Project { get; set; } = null!;
public Guid SkillId { get; set; }
public Skill Skill { get; set; } = null!;
}

View File

@ -1,35 +0,0 @@
using Portfolio.Domain.Common;
namespace Portfolio.Domain.Entities;
public sealed class RefreshToken : BaseEntity
{
public Guid UserId { get; private set; }
public User User { get; private set; } = null!;
public string TokenHash { get; private set; } = string.Empty;
public DateTime ExpiresAtUtc { get; private set; }
public bool IsRevoked { get; private set; }
public string? ReplacedByToken { get; private set; }
public bool IsActive => !IsRevoked && DateTime.UtcNow < ExpiresAtUtc;
private RefreshToken() { }
public static RefreshToken Create(Guid userId, string tokenHash, DateTime expiresAtUtc)
{
return new RefreshToken
{
UserId = userId,
TokenHash = tokenHash,
ExpiresAtUtc = expiresAtUtc,
IsRevoked = false
};
}
public void Revoke(string? replacedBy = null)
{
IsRevoked = true;
ReplacedByToken = replacedBy;
}
}

View File

@ -1,39 +0,0 @@
using Portfolio.Domain.Common;
using Portfolio.Domain.Enums;
namespace Portfolio.Domain.Entities;
public sealed class Skill : BaseEntity
{
public string Name { get; private set; } = string.Empty;
public SkillCategory Category { get; private set; }
public string? IconSlug { get; private set; }
public byte ProficiencyPercentage { get; private set; }
public ushort DisplayOrder { get; private set; }
public bool IsFeatured { get; private set; }
public ICollection<ProjectSkill> ProjectSkills { get; private set; } = [];
private Skill() { }
public static Skill Create(
string name,
SkillCategory category,
string? iconSlug = null,
byte proficiency = 85,
ushort displayOrder = 0,
bool isFeatured = true)
{
ArgumentException.ThrowIfNullOrWhiteSpace(name);
return new Skill
{
Name = name.Trim(),
Category = category,
IconSlug = iconSlug?.Trim(),
ProficiencyPercentage = Math.Min((byte)100, proficiency),
DisplayOrder = displayOrder,
IsFeatured = isFeatured
};
}
}

View File

@ -1,31 +0,0 @@
using Portfolio.Domain.Common;
namespace Portfolio.Domain.Entities;
public sealed class User : BaseEntity
{
public string Username { get; private set; } = string.Empty;
public string Email { get; private set; } = string.Empty;
public string PasswordHash { get; private set; } = string.Empty;
public string Role { get; private set; } = "Admin";
public DateTime? UpdatedAtUtc { get; private set; }
public ICollection<RefreshToken> RefreshTokens { get; private set; } = [];
private User() { }
public static User Create(string username, string email, string passwordHash, string role = "Admin")
{
ArgumentException.ThrowIfNullOrWhiteSpace(username);
ArgumentException.ThrowIfNullOrWhiteSpace(email);
ArgumentException.ThrowIfNullOrWhiteSpace(passwordHash);
return new User
{
Username = username.Trim(),
Email = email.Trim().ToLowerInvariant(),
PasswordHash = passwordHash,
Role = role
};
}
}

View File

@ -1,9 +0,0 @@
namespace Portfolio.Domain.Enums;
public enum InquiryStatus
{
New = 1,
Read = 2,
Replied = 3,
Archived = 4
}

View File

@ -1,8 +0,0 @@
namespace Portfolio.Domain.Enums;
public enum MessageOrigin
{
Terminal = 1,
WebForm = 2,
ApiTester = 3
}

View File

@ -1,10 +0,0 @@
namespace Portfolio.Domain.Enums;
public enum SkillCategory
{
Backend = 1,
Frontend = 2,
Database = 3,
DevOps = 4,
Architecture = 5
}

View File

@ -1,6 +0,0 @@
namespace Portfolio.Domain.Exceptions;
public class DomainException(string message) : Exception(message);
public class NotFoundException(string entityName, object key)
: DomainException($"Entity '{entityName}' with key ({key}) was not found.");

View File

@ -1,10 +0,0 @@
using Portfolio.Domain.Entities;
namespace Portfolio.Domain.Interfaces;
public interface IGameScoreRepository
{
Task<IReadOnlyList<GameScore>> GetTopScoresAsync(string gameName, int limit = 10, CancellationToken ct = default);
Task AddAsync(GameScore score, CancellationToken ct = default);
Task<int> SaveChangesAsync(CancellationToken ct = default);
}

View File

@ -1,10 +0,0 @@
using Portfolio.Domain.Entities;
namespace Portfolio.Domain.Interfaces;
public interface IInteractiveMessageRepository
{
Task<IReadOnlyList<InteractiveMessage>> GetRecentApprovedAsync(int limit = 50, CancellationToken ct = default);
Task AddAsync(InteractiveMessage message, CancellationToken ct = default);
Task<int> SaveChangesAsync(CancellationToken ct = default);
}

View File

@ -1,14 +0,0 @@
using Portfolio.Domain.Entities;
namespace Portfolio.Domain.Interfaces;
public interface IProjectRepository
{
Task<IReadOnlyList<Project>> GetAllAsync(bool featuredOnly = false, CancellationToken ct = default);
Task<Project?> GetBySlugAsync(string slug, CancellationToken ct = default);
Task<Project?> GetByIdAsync(Guid id, CancellationToken ct = default);
Task AddAsync(Project project, CancellationToken ct = default);
void Update(Project project);
void Delete(Project project);
Task<int> SaveChangesAsync(CancellationToken ct = default);
}

View File

@ -1,12 +0,0 @@
using Portfolio.Domain.Entities;
using Portfolio.Domain.Enums;
namespace Portfolio.Domain.Interfaces;
public interface ISkillRepository
{
Task<IReadOnlyList<Skill>> GetAllAsync(SkillCategory? category = null, CancellationToken ct = default);
Task<Skill?> GetByIdAsync(Guid id, CancellationToken ct = default);
Task AddAsync(Skill skill, CancellationToken ct = default);
Task<int> SaveChangesAsync(CancellationToken ct = default);
}

View File

@ -1,12 +0,0 @@
using Portfolio.Domain.Entities;
namespace Portfolio.Domain.Interfaces;
public interface IUserRepository
{
Task<User?> GetByUsernameOrEmailAsync(string identifier, CancellationToken ct = default);
Task<User?> GetByIdAsync(Guid id, CancellationToken ct = default);
Task AddRefreshTokenAsync(RefreshToken refreshToken, CancellationToken ct = default);
Task<RefreshToken?> GetRefreshTokenAsync(string tokenHash, CancellationToken ct = default);
Task<int> SaveChangesAsync(CancellationToken ct = default);
}

View File

@ -1,9 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>

View File

@ -1,38 +0,0 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Portfolio.Application.Common.Interfaces;
using Portfolio.Domain.Interfaces;
using Portfolio.Infrastructure.Persistence.Context;
using Portfolio.Infrastructure.Persistence.Repositories;
using Portfolio.Infrastructure.Security;
namespace Portfolio.Infrastructure;
public static class DependencyInjection
{
public static IServiceCollection AddInfrastructure(this IServiceCollection services, IConfiguration configuration)
{
var connectionString = configuration.GetConnectionString("DefaultConnection")
?? "Server=localhost;Port=3306;Database=portfolio_db;User=root;Password=;CharSet=utf8mb4;";
services.AddDbContext<PortfolioDbContext>(options =>
{
options.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString), mysqlOptions =>
{
mysqlOptions.EnableRetryOnFailure(maxRetryCount: 3, maxRetryDelay: TimeSpan.FromSeconds(5), errorNumbersToAdd: null);
});
});
services.AddScoped<IProjectRepository, ProjectRepository>();
services.AddScoped<ISkillRepository, SkillRepository>();
services.AddScoped<IInteractiveMessageRepository, InteractiveMessageRepository>();
services.AddScoped<IGameScoreRepository, GameScoreRepository>();
services.AddScoped<IUserRepository, UserRepository>();
services.AddSingleton<IPasswordHasher, PasswordHasher>();
services.AddScoped<IJwtTokenGenerator, JwtTokenGenerator>();
return services;
}
}

View File

@ -1,28 +0,0 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Portfolio.Domain.Entities;
namespace Portfolio.Infrastructure.Persistence.Configurations;
public sealed class ContactInquiryConfiguration : IEntityTypeConfiguration<ContactInquiry>
{
public void Configure(EntityTypeBuilder<ContactInquiry> builder)
{
builder.ToTable("contact_inquiries");
builder.HasKey(c => c.Id);
builder.Property(c => c.Id).HasColumnName("id").HasMaxLength(36);
builder.Property(c => c.FullNameOrCompany).HasColumnName("full_name_or_company").HasMaxLength(100).IsRequired();
builder.Property(c => c.Email).HasColumnName("email").HasMaxLength(100).IsRequired();
builder.Property(c => c.Phone).HasColumnName("phone").HasMaxLength(30);
builder.Property(c => c.ServiceType).HasColumnName("service_type").HasMaxLength(50).IsRequired();
builder.Property(c => c.ProjectDetails).HasColumnName("project_details").HasColumnType("TEXT").IsRequired();
builder.Property(c => c.Status).HasColumnName("status").HasConversion<string>().HasMaxLength(20).IsRequired();
builder.Property(c => c.IpAddress).HasColumnName("ip_address").HasMaxLength(45);
builder.Property(c => c.CreatedAtUtc).HasColumnName("created_at_utc").IsRequired();
builder.Property(c => c.RepliedAtUtc).HasColumnName("replied_at_utc");
builder.HasIndex(c => new { c.Status, c.CreatedAtUtc });
}
}

View File

@ -1,25 +0,0 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Portfolio.Domain.Entities;
namespace Portfolio.Infrastructure.Persistence.Configurations;
public sealed class GameScoreConfiguration : IEntityTypeConfiguration<GameScore>
{
public void Configure(EntityTypeBuilder<GameScore> builder)
{
builder.ToTable("game_scores");
builder.HasKey(g => g.Id);
builder.Property(g => g.Id).HasColumnName("id").HasMaxLength(36);
builder.Property(g => g.PlayerName).HasColumnName("player_name").HasMaxLength(30).IsRequired();
builder.Property(g => g.GameName).HasColumnName("game_name").HasMaxLength(30).IsRequired();
builder.Property(g => g.Score).HasColumnName("score").IsRequired();
builder.Property(g => g.DurationSeconds).HasColumnName("duration_seconds").IsRequired();
builder.Property(g => g.CountryCode).HasColumnName("country_code").HasMaxLength(5);
builder.Property(g => g.CreatedAtUtc).HasColumnName("created_at_utc").IsRequired();
builder.HasIndex(g => new { g.GameName, g.Score });
}
}

View File

@ -1,25 +0,0 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Portfolio.Domain.Entities;
namespace Portfolio.Infrastructure.Persistence.Configurations;
public sealed class InteractiveMessageConfiguration : IEntityTypeConfiguration<InteractiveMessage>
{
public void Configure(EntityTypeBuilder<InteractiveMessage> builder)
{
builder.ToTable("interactive_messages");
builder.HasKey(m => m.Id);
builder.Property(m => m.Id).HasColumnName("id").HasMaxLength(36);
builder.Property(m => m.SenderName).HasColumnName("sender_name").HasMaxLength(60).IsRequired();
builder.Property(m => m.SenderContact).HasColumnName("sender_contact").HasMaxLength(100);
builder.Property(m => m.Message).HasColumnName("message").HasMaxLength(500).IsRequired();
builder.Property(m => m.Origin).HasColumnName("origin").HasConversion<string>().HasMaxLength(20).IsRequired();
builder.Property(m => m.IsApproved).HasColumnName("is_approved").IsRequired();
builder.Property(m => m.CreatedAtUtc).HasColumnName("created_at_utc").IsRequired();
builder.HasIndex(m => new { m.IsApproved, m.CreatedAtUtc });
}
}

View File

@ -1,32 +0,0 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Portfolio.Domain.Entities;
namespace Portfolio.Infrastructure.Persistence.Configurations;
public sealed class ProjectConfiguration : IEntityTypeConfiguration<Project>
{
public void Configure(EntityTypeBuilder<Project> builder)
{
builder.ToTable("projects");
builder.HasKey(p => p.Id);
builder.Property(p => p.Id).HasColumnName("id").HasMaxLength(36);
builder.Property(p => p.Slug).HasColumnName("slug").HasMaxLength(100).IsRequired();
builder.HasIndex(p => p.Slug).IsUnique();
builder.Property(p => p.Title).HasColumnName("title").HasMaxLength(150).IsRequired();
builder.Property(p => p.ShortDescription).HasColumnName("short_description").HasMaxLength(255).IsRequired();
builder.Property(p => p.FullDescription).HasColumnName("full_description").HasColumnType("TEXT").IsRequired();
builder.Property(p => p.RepositoryUrl).HasColumnName("repository_url").HasMaxLength(255).IsRequired();
builder.Property(p => p.LiveDemoUrl).HasColumnName("live_demo_url").HasMaxLength(255);
builder.Property(p => p.ThumbnailUrl).HasColumnName("thumbnail_url").HasMaxLength(255);
builder.Property(p => p.IsFeatured).HasColumnName("is_featured").IsRequired();
builder.Property(p => p.DisplayOrder).HasColumnName("display_order").IsRequired();
builder.Property(p => p.CreatedAtUtc).HasColumnName("created_at_utc").IsRequired();
builder.Property(p => p.UpdatedAtUtc).HasColumnName("updated_at_utc");
builder.HasIndex(p => new { p.IsFeatured, p.DisplayOrder });
}
}

View File

@ -1,27 +0,0 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Portfolio.Domain.Entities;
namespace Portfolio.Infrastructure.Persistence.Configurations;
public sealed class ProjectSkillConfiguration : IEntityTypeConfiguration<ProjectSkill>
{
public void Configure(EntityTypeBuilder<ProjectSkill> builder)
{
builder.ToTable("project_skills");
builder.HasKey(ps => new { ps.ProjectId, ps.SkillId });
builder.Property(ps => ps.ProjectId).HasColumnName("project_id").HasMaxLength(36);
builder.Property(ps => ps.SkillId).HasColumnName("skill_id").HasMaxLength(36);
builder.HasOne(ps => ps.Project)
.WithMany(p => p.ProjectSkills)
.HasForeignKey(ps => ps.ProjectId)
.OnDelete(DeleteBehavior.Cascade);
builder.HasOne(ps => ps.Skill)
.WithMany(s => s.ProjectSkills)
.HasForeignKey(ps => ps.SkillId)
.OnDelete(DeleteBehavior.Restrict);
}
}

View File

@ -1,30 +0,0 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Portfolio.Domain.Entities;
namespace Portfolio.Infrastructure.Persistence.Configurations;
public sealed class RefreshTokenConfiguration : IEntityTypeConfiguration<RefreshToken>
{
public void Configure(EntityTypeBuilder<RefreshToken> builder)
{
builder.ToTable("refresh_tokens");
builder.HasKey(rt => rt.Id);
builder.Property(rt => rt.Id).HasColumnName("id").HasMaxLength(36);
builder.Property(rt => rt.UserId).HasColumnName("user_id").HasMaxLength(36).IsRequired();
builder.Property(rt => rt.TokenHash).HasColumnName("token_hash").HasMaxLength(255).IsRequired();
builder.Property(rt => rt.ExpiresAtUtc).HasColumnName("expires_at_utc").IsRequired();
builder.Property(rt => rt.IsRevoked).HasColumnName("is_revoked").IsRequired();
builder.Property(rt => rt.ReplacedByToken).HasColumnName("replaced_by_token").HasMaxLength(255);
builder.Property(rt => rt.CreatedAtUtc).HasColumnName("created_at_utc").IsRequired();
builder.HasOne(rt => rt.User)
.WithMany(u => u.RefreshTokens)
.HasForeignKey(rt => rt.UserId)
.OnDelete(DeleteBehavior.Cascade);
builder.HasIndex(rt => new { rt.UserId, rt.IsRevoked, rt.ExpiresAtUtc });
}
}

View File

@ -1,28 +0,0 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Portfolio.Domain.Entities;
namespace Portfolio.Infrastructure.Persistence.Configurations;
public sealed class SkillConfiguration : IEntityTypeConfiguration<Skill>
{
public void Configure(EntityTypeBuilder<Skill> builder)
{
builder.ToTable("skills");
builder.HasKey(s => s.Id);
builder.Property(s => s.Id).HasColumnName("id").HasMaxLength(36);
builder.Property(s => s.Name).HasColumnName("name").HasMaxLength(50).IsRequired();
builder.HasIndex(s => s.Name).IsUnique();
builder.Property(s => s.Category).HasColumnName("category").HasConversion<string>().HasMaxLength(30).IsRequired();
builder.Property(s => s.IconSlug).HasColumnName("icon_slug").HasMaxLength(50);
builder.Property(s => s.ProficiencyPercentage).HasColumnName("proficiency_percentage").IsRequired();
builder.Property(s => s.DisplayOrder).HasColumnName("display_order").IsRequired();
builder.Property(s => s.IsFeatured).HasColumnName("is_featured").IsRequired();
builder.Property(s => s.CreatedAtUtc).HasColumnName("created_at_utc").IsRequired();
builder.HasIndex(s => new { s.Category, s.DisplayOrder });
}
}

View File

@ -1,27 +0,0 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Portfolio.Domain.Entities;
namespace Portfolio.Infrastructure.Persistence.Configurations;
public sealed class UserConfiguration : IEntityTypeConfiguration<User>
{
public void Configure(EntityTypeBuilder<User> builder)
{
builder.ToTable("users");
builder.HasKey(u => u.Id);
builder.Property(u => u.Id).HasColumnName("id").HasMaxLength(36);
builder.Property(u => u.Username).HasColumnName("username").HasMaxLength(50).IsRequired();
builder.HasIndex(u => u.Username).IsUnique();
builder.Property(u => u.Email).HasColumnName("email").HasMaxLength(100).IsRequired();
builder.HasIndex(u => u.Email).IsUnique();
builder.Property(u => u.PasswordHash).HasColumnName("password_hash").HasMaxLength(255).IsRequired();
builder.Property(u => u.Role).HasColumnName("role").HasMaxLength(20).IsRequired();
builder.Property(u => u.CreatedAtUtc).HasColumnName("created_at_utc").IsRequired();
builder.Property(u => u.UpdatedAtUtc).HasColumnName("updated_at_utc");
}
}

View File

@ -1,23 +0,0 @@
using System.Reflection;
using Microsoft.EntityFrameworkCore;
using Portfolio.Domain.Entities;
namespace Portfolio.Infrastructure.Persistence.Context;
public sealed class PortfolioDbContext(DbContextOptions<PortfolioDbContext> options) : DbContext(options)
{
public DbSet<Project> Projects => Set<Project>();
public DbSet<Skill> Skills => Set<Skill>();
public DbSet<ProjectSkill> ProjectSkills => Set<ProjectSkill>();
public DbSet<InteractiveMessage> InteractiveMessages => Set<InteractiveMessage>();
public DbSet<GameScore> GameScores => Set<GameScore>();
public DbSet<ContactInquiry> ContactInquiries => Set<ContactInquiry>();
public DbSet<User> Users => Set<User>();
public DbSet<RefreshToken> RefreshTokens => Set<RefreshToken>();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly());
}
}

View File

@ -1,30 +0,0 @@
using Microsoft.EntityFrameworkCore;
using Portfolio.Domain.Entities;
using Portfolio.Domain.Interfaces;
using Portfolio.Infrastructure.Persistence.Context;
namespace Portfolio.Infrastructure.Persistence.Repositories;
public sealed class GameScoreRepository(PortfolioDbContext context) : IGameScoreRepository
{
public async Task<IReadOnlyList<GameScore>> GetTopScoresAsync(string gameName, int limit = 10, CancellationToken ct = default)
{
return await context.GameScores
.AsNoTracking()
.Where(g => g.GameName == gameName.ToLower())
.OrderByDescending(g => g.Score)
.ThenBy(g => g.DurationSeconds)
.Take(limit)
.ToListAsync(ct);
}
public async Task AddAsync(GameScore score, CancellationToken ct = default)
{
await context.GameScores.AddAsync(score, ct);
}
public Task<int> SaveChangesAsync(CancellationToken ct = default)
{
return context.SaveChangesAsync(ct);
}
}

View File

@ -1,29 +0,0 @@
using Microsoft.EntityFrameworkCore;
using Portfolio.Domain.Entities;
using Portfolio.Domain.Interfaces;
using Portfolio.Infrastructure.Persistence.Context;
namespace Portfolio.Infrastructure.Persistence.Repositories;
public sealed class InteractiveMessageRepository(PortfolioDbContext context) : IInteractiveMessageRepository
{
public async Task<IReadOnlyList<InteractiveMessage>> GetRecentApprovedAsync(int limit = 50, CancellationToken ct = default)
{
return await context.InteractiveMessages
.AsNoTracking()
.Where(m => m.IsApproved)
.OrderByDescending(m => m.CreatedAtUtc)
.Take(limit)
.ToListAsync(ct);
}
public async Task AddAsync(InteractiveMessage message, CancellationToken ct = default)
{
await context.InteractiveMessages.AddAsync(message, ct);
}
public Task<int> SaveChangesAsync(CancellationToken ct = default)
{
return context.SaveChangesAsync(ct);
}
}

View File

@ -1,64 +0,0 @@
using Microsoft.EntityFrameworkCore;
using Portfolio.Domain.Entities;
using Portfolio.Domain.Interfaces;
using Portfolio.Infrastructure.Persistence.Context;
namespace Portfolio.Infrastructure.Persistence.Repositories;
public sealed class ProjectRepository(PortfolioDbContext context) : IProjectRepository
{
public async Task<IReadOnlyList<Project>> GetAllAsync(bool featuredOnly = false, CancellationToken ct = default)
{
var query = context.Projects
.AsNoTracking()
.Include(p => p.ProjectSkills)
.ThenInclude(ps => ps.Skill)
.AsQueryable();
if (featuredOnly)
{
query = query.Where(p => p.IsFeatured);
}
return await query
.OrderBy(p => p.DisplayOrder)
.ThenByDescending(p => p.CreatedAtUtc)
.ToListAsync(ct);
}
public async Task<Project?> GetBySlugAsync(string slug, CancellationToken ct = default)
{
return await context.Projects
.AsNoTracking()
.Include(p => p.ProjectSkills)
.ThenInclude(ps => ps.Skill)
.FirstOrDefaultAsync(p => p.Slug == slug.ToLower(), ct);
}
public async Task<Project?> GetByIdAsync(Guid id, CancellationToken ct = default)
{
return await context.Projects
.Include(p => p.ProjectSkills)
.FirstOrDefaultAsync(p => p.Id == id, ct);
}
public async Task AddAsync(Project project, CancellationToken ct = default)
{
await context.Projects.AddAsync(project, ct);
}
public void Update(Project project)
{
context.Projects.Update(project);
}
public void Delete(Project project)
{
context.Projects.Remove(project);
}
public Task<int> SaveChangesAsync(CancellationToken ct = default)
{
return context.SaveChangesAsync(ct);
}
}

View File

@ -1,40 +0,0 @@
using Microsoft.EntityFrameworkCore;
using Portfolio.Domain.Entities;
using Portfolio.Domain.Enums;
using Portfolio.Domain.Interfaces;
using Portfolio.Infrastructure.Persistence.Context;
namespace Portfolio.Infrastructure.Persistence.Repositories;
public sealed class SkillRepository(PortfolioDbContext context) : ISkillRepository
{
public async Task<IReadOnlyList<Skill>> GetAllAsync(SkillCategory? category = null, CancellationToken ct = default)
{
var query = context.Skills.AsNoTracking().AsQueryable();
if (category.HasValue)
{
query = query.Where(s => s.Category == category.Value);
}
return await query
.OrderBy(s => s.Category)
.ThenBy(s => s.DisplayOrder)
.ToListAsync(ct);
}
public async Task<Skill?> GetByIdAsync(Guid id, CancellationToken ct = default)
{
return await context.Skills.FindAsync([id], ct);
}
public async Task AddAsync(Skill skill, CancellationToken ct = default)
{
await context.Skills.AddAsync(skill, ct);
}
public Task<int> SaveChangesAsync(CancellationToken ct = default)
{
return context.SaveChangesAsync(ct);
}
}

View File

@ -1,41 +0,0 @@
using Microsoft.EntityFrameworkCore;
using Portfolio.Domain.Entities;
using Portfolio.Domain.Interfaces;
using Portfolio.Infrastructure.Persistence.Context;
namespace Portfolio.Infrastructure.Persistence.Repositories;
public sealed class UserRepository(PortfolioDbContext context) : IUserRepository
{
public async Task<User?> GetByUsernameOrEmailAsync(string identifier, CancellationToken ct = default)
{
var lower = identifier.ToLower().Trim();
return await context.Users
.Include(u => u.RefreshTokens)
.FirstOrDefaultAsync(u => u.Username.ToLower() == lower || u.Email.ToLower() == lower, ct);
}
public async Task<User?> GetByIdAsync(Guid id, CancellationToken ct = default)
{
return await context.Users
.Include(u => u.RefreshTokens)
.FirstOrDefaultAsync(u => u.Id == id, ct);
}
public async Task AddRefreshTokenAsync(RefreshToken refreshToken, CancellationToken ct = default)
{
await context.RefreshTokens.AddAsync(refreshToken, ct);
}
public async Task<RefreshToken?> GetRefreshTokenAsync(string tokenHash, CancellationToken ct = default)
{
return await context.RefreshTokens
.Include(rt => rt.User)
.FirstOrDefaultAsync(rt => rt.TokenHash == tokenHash, ct);
}
public Task<int> SaveChangesAsync(CancellationToken ct = default)
{
return context.SaveChangesAsync(ct);
}
}

View File

@ -1,22 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<ItemGroup>
<ProjectReference Include="..\Portfolio.Application\Portfolio.Application.csproj" />
<ProjectReference Include="..\Portfolio.Domain\Portfolio.Domain.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="BCrypt.Net-Next" Version="4.2.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.10" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="8.0.10" />
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="8.0.2" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="8.23.0" />
</ItemGroup>
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>

View File

@ -1,52 +0,0 @@
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using Portfolio.Application.Common.Interfaces;
using Portfolio.Domain.Entities;
namespace Portfolio.Infrastructure.Security;
public sealed class JwtTokenGenerator(IConfiguration configuration) : IJwtTokenGenerator
{
public string GenerateAccessToken(User user)
{
var secret = configuration["JwtSettings:Secret"]
?? "DefaultDevelopmentSecretKeyMustBeOverriddenInProduction123456789";
var issuer = configuration["JwtSettings:Issuer"] ?? "PortfolioBackend";
var audience = configuration["JwtSettings:Audience"] ?? "PortfolioFrontend";
var expiryMinutes = int.TryParse(configuration["JwtSettings:ExpiryMinutes"], out var exp) ? exp : 60;
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret));
var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, user.Id.ToString()),
new Claim(JwtRegisteredClaimNames.UniqueName, user.Username),
new Claim(JwtRegisteredClaimNames.Email, user.Email),
new Claim(ClaimTypes.Role, user.Role),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
};
var token = new JwtSecurityToken(
issuer: issuer,
audience: audience,
claims: claims,
expires: DateTime.UtcNow.AddMinutes(expiryMinutes),
signingCredentials: credentials
);
return new JwtSecurityTokenHandler().WriteToken(token);
}
public string GenerateRefreshToken()
{
var randomBytes = new byte[64];
using var rng = RandomNumberGenerator.Create();
rng.GetBytes(randomBytes);
return Convert.ToBase64String(randomBytes);
}
}

View File

@ -1,16 +0,0 @@
using Portfolio.Application.Common.Interfaces;
namespace Portfolio.Infrastructure.Security;
public sealed class PasswordHasher : IPasswordHasher
{
public string Hash(string password)
{
return BCrypt.Net.BCrypt.HashPassword(password, workFactor: 11);
}
public bool Verify(string password, string passwordHash)
{
return BCrypt.Net.BCrypt.Verify(password, passwordHash);
}
}

View File

@ -1,41 +0,0 @@
using MediatR;
using Microsoft.AspNetCore.Mvc;
using Portfolio.Application.Features.Guestbook.Commands;
using Portfolio.Application.Features.Guestbook.DTOs;
using Portfolio.Application.Features.Guestbook.Queries;
namespace Portfolio.WebApi.Controllers;
[ApiController]
[Route("api/v1/[controller]")]
[Produces("application/json")]
public sealed class GuestbookController(ISender sender) : ControllerBase
{
[HttpGet]
[ProducesResponseType(typeof(IReadOnlyList<GuestbookMessageResponseDto>), StatusCodes.Status200OK)]
public async Task<ActionResult<IReadOnlyList<GuestbookMessageResponseDto>>> GetRecent(
[FromQuery] int limit = 50,
CancellationToken ct = default)
{
var result = await sender.Send(new GetGuestbookMessagesQuery(limit), ct);
return Ok(result);
}
[HttpPost]
[ProducesResponseType(typeof(GuestbookMessageResponseDto), StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<ActionResult<GuestbookMessageResponseDto>> Create(
[FromBody] CreateGuestbookMessageRequestDto request,
CancellationToken ct = default)
{
var command = new CreateGuestbookMessageCommand(
request.SenderName,
request.Message,
request.Origin,
request.SenderContact
);
var result = await sender.Send(command, ct);
return StatusCode(StatusCodes.Status201Created, result);
}
}

View File

@ -1,43 +0,0 @@
using MediatR;
using Microsoft.AspNetCore.Mvc;
using Portfolio.Application.Features.Leaderboard.Commands;
using Portfolio.Application.Features.Leaderboard.DTOs;
using Portfolio.Application.Features.Leaderboard.Queries;
namespace Portfolio.WebApi.Controllers;
[ApiController]
[Route("api/v1/[controller]")]
[Produces("application/json")]
public sealed class LeaderboardController(ISender sender) : ControllerBase
{
[HttpGet]
[ProducesResponseType(typeof(IReadOnlyList<GameScoreResponseDto>), StatusCodes.Status200OK)]
public async Task<ActionResult<IReadOnlyList<GameScoreResponseDto>>> GetLeaderboard(
[FromQuery] string game = "Minesweeper",
[FromQuery] int limit = 10,
CancellationToken ct = default)
{
var result = await sender.Send(new GetLeaderboardQuery(game, limit), ct);
return Ok(result);
}
[HttpPost]
[ProducesResponseType(typeof(GameScoreResponseDto), StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<ActionResult<GameScoreResponseDto>> SubmitScore(
[FromBody] SubmitGameScoreRequestDto request,
CancellationToken ct = default)
{
var command = new SubmitGameScoreCommand(
request.PlayerName,
request.GameName,
request.Score,
request.DurationSeconds,
request.CountryCode
);
var result = await sender.Send(command, ct);
return StatusCode(StatusCodes.Status201Created, result);
}
}

View File

@ -1,31 +0,0 @@
using MediatR;
using Microsoft.AspNetCore.Mvc;
using Portfolio.Application.Features.Projects.DTOs;
using Portfolio.Application.Features.Projects.Queries;
namespace Portfolio.WebApi.Controllers;
[ApiController]
[Route("api/v1/[controller]")]
[Produces("application/json")]
public sealed class ProjectsController(ISender sender) : ControllerBase
{
[HttpGet]
[ProducesResponseType(typeof(IReadOnlyList<ProjectResponseDto>), StatusCodes.Status200OK)]
public async Task<ActionResult<IReadOnlyList<ProjectResponseDto>>> GetAll(
[FromQuery] bool featuredOnly = false,
CancellationToken ct = default)
{
var result = await sender.Send(new GetProjectsQuery(featuredOnly), ct);
return Ok(result);
}
[HttpGet("{slug}")]
[ProducesResponseType(typeof(ProjectResponseDto), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<ActionResult<ProjectResponseDto>> GetBySlug(string slug, CancellationToken ct = default)
{
var result = await sender.Send(new GetProjectBySlugQuery(slug), ct);
return Ok(result);
}
}

View File

@ -1,23 +0,0 @@
using MediatR;
using Microsoft.AspNetCore.Mvc;
using Portfolio.Application.Features.Skills.DTOs;
using Portfolio.Application.Features.Skills.Queries;
using Portfolio.Domain.Enums;
namespace Portfolio.WebApi.Controllers;
[ApiController]
[Route("api/v1/[controller]")]
[Produces("application/json")]
public sealed class SkillsController(ISender sender) : ControllerBase
{
[HttpGet]
[ProducesResponseType(typeof(IReadOnlyList<SkillResponseDto>), StatusCodes.Status200OK)]
public async Task<ActionResult<IReadOnlyList<SkillResponseDto>>> GetAll(
[FromQuery] SkillCategory? category = null,
CancellationToken ct = default)
{
var result = await sender.Send(new GetSkillsQuery(category), ct);
return Ok(result);
}
}

View File

@ -1,35 +0,0 @@
using System.Diagnostics;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using Portfolio.Application.Features.Telemetry.DTOs;
using Portfolio.Application.Features.Telemetry.Queries;
namespace Portfolio.WebApi.Controllers;
[ApiController]
[Route("api/v1/[controller]")]
[Produces("application/json")]
public sealed class TelemetryController(ISender sender) : ControllerBase
{
[HttpGet]
[ProducesResponseType(typeof(ServerTelemetryDto), StatusCodes.Status200OK)]
public async Task<ActionResult<ServerTelemetryDto>> GetServerTelemetry(CancellationToken ct)
{
var result = await sender.Send(new GetServerTelemetryQuery(), ct);
return Ok(result);
}
[HttpGet("ping")]
[ProducesResponseType(typeof(PingResponseDto), StatusCodes.Status200OK)]
public ActionResult<PingResponseDto> Ping()
{
var sw = Stopwatch.StartNew();
sw.Stop();
return Ok(new PingResponseDto(
Message: "PONG // ZEN SERVER HEALTHY",
LatencyMs: sw.ElapsedMilliseconds,
TimestampUtc: DateTime.UtcNow
));
}
}

View File

@ -1,54 +0,0 @@
using FluentValidation;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using Portfolio.Domain.Exceptions;
namespace Portfolio.WebApi.Middleware;
public sealed class GlobalExceptionHandler(ILogger<GlobalExceptionHandler> logger) : IExceptionHandler
{
public async ValueTask<bool> TryHandleAsync(
HttpContext httpContext,
Exception exception,
CancellationToken cancellationToken)
{
logger.LogError(exception, "Unhandled exception occurred: {Message}", exception.Message);
var problemDetails = exception switch
{
ValidationException valEx => new ProblemDetails
{
Status = StatusCodes.Status400BadRequest,
Title = "Validation Error",
Detail = "One or more validation errors occurred.",
Extensions =
{
["errors"] = valEx.Errors.Select(e => new { e.PropertyName, e.ErrorMessage })
}
},
NotFoundException notFoundEx => new ProblemDetails
{
Status = StatusCodes.Status404NotFound,
Title = "Not Found",
Detail = notFoundEx.Message
},
DomainException domainEx => new ProblemDetails
{
Status = StatusCodes.Status400BadRequest,
Title = "Domain Rule Violation",
Detail = domainEx.Message
},
_ => new ProblemDetails
{
Status = StatusCodes.Status500InternalServerError,
Title = "Internal Server Error",
Detail = "An unexpected error occurred. Please contact the administrator."
}
};
httpContext.Response.StatusCode = problemDetails.Status ?? StatusCodes.Status500InternalServerError;
await httpContext.Response.WriteAsJsonAsync(problemDetails, cancellationToken);
return true;
}
}

View File

@ -1,24 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<RollForward>LatestMajor</RollForward>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.10" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.10">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Portfolio.Application\Portfolio.Application.csproj" />
<ProjectReference Include="..\Portfolio.Infrastructure\Portfolio.Infrastructure.csproj" />
</ItemGroup>
</Project>

View File

@ -1,6 +0,0 @@
@Portfolio.WebApi_HostAddress = http://localhost:5117
GET {{Portfolio.WebApi_HostAddress}}/weatherforecast/
Accept: application/json
###

View File

@ -1,135 +0,0 @@
using Microsoft.OpenApi.Models;
using Portfolio.Application;
using Portfolio.Infrastructure;
using Portfolio.Infrastructure.Persistence.Context;
using Portfolio.WebApi.Middleware;
var builder = WebApplication.CreateBuilder(args);
// 1. Configuracion en cascada: appsettingsdevelop.json (base segura en Git) + appsettings.json (secretos locales)
builder.Configuration
.SetBasePath(builder.Environment.ContentRootPath)
.AddJsonFile("appsettingsdevelop.json", optional: true, reloadOnChange: true)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{builder.Environment.EnvironmentName}.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables();
// 2. Inyeccion de dependencias de Capas (Clean Architecture)
builder.Services.AddApplication();
builder.Services.AddInfrastructure(builder.Configuration);
// 3. Manejo Global de Excepciones (RFC 7807 ProblemDetails)
builder.Services.AddExceptionHandler<GlobalExceptionHandler>();
builder.Services.AddProblemDetails();
// 4. Controladores y Serializacion JSON
builder.Services.AddControllers()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull;
});
// 5. Configuracion de CORS para Angular Frontend
var allowedOrigins = builder.Configuration.GetSection("CorsSettings:AllowedOrigins").Get<string[]>()
?? ["http://localhost:4200", "https://bryan-bano.com", "https://portfolio.bryan-bano.com"];
builder.Services.AddCors(options =>
{
options.AddPolicy("PortfolioCorsPolicy", policy =>
{
policy.WithOrigins(allowedOrigins)
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
});
});
// 6. OpenAPI / Swagger con documentacion Cyber-Zen
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo
{
Title = "Bryan Baño // Portfolio API",
Version = "v1",
Description = "API REST de alto rendimiento para el portafolio profesional interactivo. Clean Architecture, CQRS y persistencia MySQL.",
Contact = new OpenApiContact
{
Name = "Bryan Baño",
Email = "contacto@bryan-bano.com",
Url = new Uri("https://bryan-bano.com")
}
});
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.Http,
Scheme = "bearer"
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
Array.Empty<string>()
}
});
});
var app = builder.Build();
// 7. Pipeline de Solicitudes HTTP
app.UseExceptionHandler();
if (app.Environment.IsDevelopment() || builder.Configuration.GetValue<bool>("EnableSwaggerInProd", true))
{
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Portfolio API v1");
c.DocumentTitle = "Bryan Baño // API Documentation";
c.RoutePrefix = "swagger";
});
}
app.UseCors("PortfolioCorsPolicy");
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
// Healthcheck basico en raiz
app.MapGet("/", () => Results.Ok(new
{
service = "Portfolio Backend API",
status = "Online",
version = "1.0.0",
docs = "/swagger"
}));
// 8. Auto-provisionamiento de esquema de base de datos en arranque
using (var scope = app.Services.CreateScope())
{
var db = scope.ServiceProvider.GetRequiredService<PortfolioDbContext>();
try
{
db.Database.EnsureCreated();
app.Logger.LogInformation("Esquema de base de datos asegurado correctamente.");
}
catch (Exception ex)
{
app.Logger.LogWarning(ex, "No se pudo sincronizar la base de datos al inicio. Verifica la conexión a MySQL.");
}
}
app.Run();

View File

@ -1,41 +0,0 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:25368",
"sslPort": 44302
}
},
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "http://localhost:5117",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "https://localhost:7020;http://localhost:5117",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

View File

@ -1,33 +0,0 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning",
"Microsoft.EntityFrameworkCore.Database.Command": "Information"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"DefaultConnection": "Server=localhost;Port=3306;Database=portfolio_db;User=root;Password=;CharSet=utf8mb4;"
},
"JwtSettings": {
"Secret": "YOUR_SUPER_SECRET_KEY_MINIMUM_32_CHARACTERS_LONG_PLACEHOLDER",
"Issuer": "PortfolioBackend",
"Audience": "PortfolioFrontend",
"ExpiryMinutes": 60,
"RefreshTokenExpiryDays": 7
},
"CorsSettings": {
"AllowedOrigins": [
"http://localhost:4200",
"https://bryan-bano.com",
"https://portfolio.bryan-bano.com"
]
},
"ServerTelemetry": {
"Region": "us-ashburn-1",
"Provider": "Oracle Cloud Infrastructure (OCI)",
"ServerName": "srv-personal-core",
"Architecture": "ARM64 Ampere Altra"
}
}

View File

@ -1,60 +0,0 @@
using Portfolio.Domain.Entities;
using Portfolio.Domain.Enums;
namespace Portfolio.UnitTests;
public class DomainTests
{
[Fact]
public void Project_Create_WithValidArgs_ShouldInstantiateCorrectly()
{
// Act
var project = Project.Create(
slug: "test-project",
title: "Test Project Title",
shortDescription: "Short description of project",
fullDescription: "Detailed description of architecture and features",
repositoryUrl: "https://github.com/bryan/test-project",
isFeatured: true
);
// Assert
Assert.NotNull(project);
Assert.Equal("test-project", project.Slug);
Assert.Equal("Test Project Title", project.Title);
Assert.True(project.IsFeatured);
Assert.NotEqual(Guid.Empty, project.Id);
}
[Theory]
[InlineData("", "Title")]
[InlineData(" ", "Title")]
[InlineData("slug", "")]
[InlineData("slug", " ")]
public void Project_Create_WithInvalidArgs_ShouldThrowArgumentException(string slug, string title)
{
// Assert
Assert.Throws<ArgumentException>(() =>
Project.Create(
slug: slug,
title: title,
shortDescription: "Short",
fullDescription: "Full",
repositoryUrl: "https://repo"
)
);
}
[Fact]
public void Skill_Create_WithValidArgs_ShouldInstantiateCorrectly()
{
// Act
var skill = Skill.Create(".NET 8/9", SkillCategory.Backend, "dotnet", proficiency: 95);
// Assert
Assert.NotNull(skill);
Assert.Equal(".NET 8/9", skill.Name);
Assert.Equal(SkillCategory.Backend, skill.Category);
Assert.Equal(95, skill.ProficiencyPercentage);
}
}

View File

@ -1,40 +0,0 @@
using Portfolio.Application.Features.Guestbook.Commands;
using Portfolio.Application.Features.Guestbook.Validators;
namespace Portfolio.UnitTests;
public class GuestbookValidationTests
{
private readonly CreateGuestbookMessageCommandValidator _validator = new();
[Fact]
public void Validator_WithValidData_ShouldNotHaveErrors()
{
// Arrange
var command = new CreateGuestbookMessageCommand("Bryan Baño", "Excelente arquitectura.");
// Act
var result = _validator.Validate(command);
// Assert
Assert.True(result.IsValid);
Assert.Empty(result.Errors);
}
[Theory]
[InlineData("", "Mensaje de prueba")]
[InlineData("Bryan", "")]
[InlineData("Bryan", "ab")] // Menos de 3 caracteres
public void Validator_WithInvalidData_ShouldHaveValidationErrors(string senderName, string message)
{
// Arrange
var command = new CreateGuestbookMessageCommand(senderName, message);
// Act
var result = _validator.Validate(command);
// Assert
Assert.False(result.IsValid);
Assert.NotEmpty(result.Errors);
}
}

View File

@ -1,29 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<RollForward>LatestMajor</RollForward>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="coverlet.collector" Version="6.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
<PackageReference Include="xunit" Version="2.5.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.5.3" />
</ItemGroup>
<ItemGroup>
<Using Include="Xunit" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\Portfolio.Application\Portfolio.Application.csproj" />
<ProjectReference Include="..\..\src\Portfolio.Domain\Portfolio.Domain.csproj" />
</ItemGroup>
</Project>

View File

@ -1,24 +0,0 @@
using Portfolio.Application.Features.Telemetry.Queries;
namespace Portfolio.UnitTests;
public class TelemetryTests
{
[Fact]
public async Task GetServerTelemetryQueryHandler_ShouldReturnOperationalStatus()
{
// Arrange
var handler = new GetServerTelemetryQueryHandler();
var query = new GetServerTelemetryQuery();
// Act
var result = await handler.Handle(query, CancellationToken.None);
// Assert
Assert.NotNull(result);
Assert.Equal("OPERATIONAL", result.Status);
Assert.Equal("us-ashburn-1", result.Region);
Assert.True(result.ProcessMemoryMb > 0);
Assert.True(result.ActiveThreads > 0);
}
}

View File

@ -8,10 +8,6 @@ import { ChatPort } from './domain/ports/chat.port';
import { N8nChatAdapter } from './infrastructure/adapters/n8n-chat.adapter';
import { SecurityAgentPort } from './domain/ports/security-agent.port';
import { SecurityAgentService } from './services/security-agent.service';
import { TelemetryPort } from './domain/ports/telemetry.port';
import { HttpTelemetryAdapter } from './infrastructure/adapters/http-telemetry.adapter';
import { GuestbookPort } from './domain/ports/guestbook.port';
import { HttpGuestbookAdapter } from './infrastructure/adapters/http-guestbook.adapter';
export const appConfig: ApplicationConfig = {
providers: [
@ -20,8 +16,6 @@ export const appConfig: ApplicationConfig = {
provideHttpClient(),
{ provide: RetroScorePort, useClass: LocalStorageRetroScoreAdapter },
{ provide: ChatPort, useClass: N8nChatAdapter },
{ provide: SecurityAgentPort, useClass: SecurityAgentService },
{ provide: TelemetryPort, useClass: HttpTelemetryAdapter },
{ provide: GuestbookPort, useClass: HttpGuestbookAdapter }
{ provide: SecurityAgentPort, useClass: SecurityAgentService }
]
};

View File

@ -1,64 +0,0 @@
import { Injectable, signal, computed } from '@angular/core';
export type ThemeMode = 'dark' | 'light';
@Injectable({ providedIn: 'root' })
export class ThemeService {
private readonly STORAGE_KEY = 'portfolio_theme_mode';
readonly themeMode = signal<ThemeMode>(this.getInitialTheme());
readonly isLightMode = computed(() => this.themeMode() === 'light');
readonly isDarkMode = computed(() => this.themeMode() === 'dark');
constructor() {
this.applyTheme(this.themeMode());
}
toggleTheme(): void {
const next: ThemeMode = this.themeMode() === 'dark' ? 'light' : 'dark';
this.setTheme(next);
}
setTheme(mode: ThemeMode): void {
this.themeMode.set(mode);
this.applyTheme(mode);
try {
if (typeof window !== 'undefined') {
localStorage.setItem(this.STORAGE_KEY, mode);
}
} catch {
// Fallback si localStorage no está disponible
}
}
private applyTheme(mode: ThemeMode): void {
if (typeof document === 'undefined') return;
const root = document.documentElement;
const body = document.body;
if (mode === 'light') {
root.setAttribute('data-theme', 'zen-light');
body.classList.remove('theme-dark');
body.classList.add('theme-light');
} else {
root.setAttribute('data-theme', 'zen-dark');
body.classList.remove('theme-light');
body.classList.add('theme-dark');
}
}
private getInitialTheme(): ThemeMode {
if (typeof window === 'undefined') return 'dark';
try {
const saved = localStorage.getItem(this.STORAGE_KEY) as ThemeMode | null;
if (saved === 'dark' || saved === 'light') return saved;
// Por defecto iniciamos en dark mode como pide el diseño Cyber-Zen
return 'dark';
} catch {
return 'dark';
}
}
}

View File

@ -1,44 +0,0 @@
import { Injectable, inject, signal } from '@angular/core';
import { GuestbookPort } from '../../domain/ports/guestbook.port';
import { HttpGuestbookAdapter } from '../../infrastructure/adapters/http-guestbook.adapter';
import { CreateGuestbookRequest, GuestbookEntry } from '../../domain/models/guestbook.model';
@Injectable({
providedIn: 'root'
})
export class GuestbookStore {
private readonly adapter: GuestbookPort = inject(HttpGuestbookAdapter);
readonly entries = signal<GuestbookEntry[]>([]);
readonly isLoading = signal<boolean>(false);
readonly isSubmitting = signal<boolean>(false);
readonly lastSubmitted = signal<GuestbookEntry | null>(null);
constructor() {
this.loadEntries();
}
loadEntries(): void {
this.isLoading.set(true);
this.adapter.getEntries(50).subscribe({
next: entries => {
this.entries.set(entries);
this.isLoading.set(false);
},
error: () => this.isLoading.set(false)
});
}
submitEntry(request: CreateGuestbookRequest, onSuccess?: () => void): void {
this.isSubmitting.set(true);
this.adapter.createEntry(request).subscribe({
next: newEntry => {
this.entries.update(list => [newEntry, ...list.filter(e => e.id !== newEntry.id)]);
this.lastSubmitted.set(newEntry);
this.isSubmitting.set(false);
onSuccess?.();
},
error: () => this.isSubmitting.set(false)
});
}
}

View File

@ -48,17 +48,6 @@ const INITIAL_WINDOWS: Record<WindowId, RetroWindow> = {
size: { width: 320, height: 320 },
zIndex: 13,
minSize: { width: 280, height: 260 }
},
'api-explorer': {
id: 'api-explorer',
title: 'API Packet Tracer & Explorer',
icon: 'terminal',
isOpen: false,
isMinimized: false,
position: { x: 45, y: 25 },
size: { width: 440, height: 400 },
zIndex: 14,
minSize: { width: 300, height: 280 }
}
};
@ -84,7 +73,6 @@ export class RetroOsStore {
{ id: 'icon-games', label: t.retroIconGames, windowId: 'games', iconType: 'minesweeper' },
{ id: 'icon-cv', label: t.retroIconCv, windowId: 'cv', iconType: 'document' },
{ id: 'icon-scores', label: t.retroIconScores, windowId: 'scores', iconType: 'trophy' },
{ id: 'icon-api', label: 'API Tracer', windowId: 'api-explorer', iconType: 'terminal' },
{ id: 'icon-settings', label: t.retroIconSettings, windowId: 'settings', iconType: 'gear' }
];
});
@ -114,8 +102,7 @@ export class RetroOsStore {
games: { ...prev.games, title: t.retroWinGames },
cv: { ...prev.cv, title: t.retroWinCv },
scores: { ...prev.scores, title: t.retroWinScores },
settings: { ...prev.settings, title: t.retroWinSettings },
'api-explorer': { ...prev['api-explorer'], title: 'API Packet Tracer & Explorer' }
settings: { ...prev.settings, title: t.retroWinSettings }
}));
});
}

View File

@ -1,64 +0,0 @@
import { Injectable, inject, signal, computed } from '@angular/core';
import { TelemetryPort } from '../../domain/ports/telemetry.port';
import { HttpTelemetryAdapter } from '../../infrastructure/adapters/http-telemetry.adapter';
import { ServerTelemetry } from '../../domain/models/telemetry.model';
@Injectable({
providedIn: 'root'
})
export class TelemetryStore {
private readonly adapter: TelemetryPort = inject(HttpTelemetryAdapter);
// Estado reactivo (Signals)
readonly telemetry = signal<ServerTelemetry | null>(null);
readonly latency = signal<number>(24);
readonly isLoading = signal<boolean>(false);
readonly isHudOpen = signal<boolean>(false);
readonly latencyHistory = signal<number[]>([28, 25, 22, 26, 24, 23, 25, 24]);
// Señales computadas
readonly isOnline = computed(() => this.telemetry()?.status === 'OPERATIONAL' || true);
readonly region = computed(() => this.telemetry()?.region ?? 'us-ashburn-1');
readonly provider = computed(() => this.telemetry()?.provider ?? 'Oracle Cloud Infrastructure (OCI)');
readonly memoryMb = computed(() => this.telemetry()?.processMemoryMb ?? 94.5);
readonly uptime = computed(() => this.telemetry()?.uptime ?? '14d 08h 22m');
readonly architecture = computed(() => this.telemetry()?.architecture ?? 'Linux arm64 (Ampere Altra)');
constructor() {
this.fetchTelemetry();
}
fetchTelemetry(): void {
this.isLoading.set(true);
this.adapter.getTelemetry().subscribe({
next: data => {
this.telemetry.set(data);
if (data.pingMs) {
this.recordLatency(data.pingMs);
}
this.isLoading.set(false);
},
error: () => this.isLoading.set(false)
});
}
ping(): void {
this.adapter.ping().subscribe({
next: res => {
this.recordLatency(res.latencyMs);
}
});
}
toggleHud(open?: boolean): void {
this.isHudOpen.update(current => open ?? !current);
if (this.isHudOpen()) {
this.fetchTelemetry();
}
}
private recordLatency(ms: number): void {
this.latency.set(ms);
this.latencyHistory.update(hist => [...hist.slice(-9), ms]);
}
}

View File

@ -1,15 +0,0 @@
import { InjectionToken } from '@angular/core';
export const API_BASE_URL = new InjectionToken<string>('API_BASE_URL', {
providedIn: 'root',
factory: () => {
if (
typeof window !== 'undefined' &&
(window.location.hostname.includes('bryan-bano.com') ||
window.location.hostname.includes('pages.dev'))
) {
return 'https://api.bryan-bano.com/api/v1';
}
return 'http://localhost:5000/api/v1';
}
});

View File

@ -1,6 +0,0 @@
import { InjectionToken } from '@angular/core';
export const NOTIFY_WEBHOOK_URL = new InjectionToken<string>('NOTIFY_WEBHOOK_URL', {
providedIn: 'root',
factory: () => 'https://n8n.bryan-bano.com/webhook/portfolio-notify'
});

View File

@ -1,14 +0,0 @@
export interface GuestbookEntry {
id: string;
senderName: string;
message: string;
origin: 'Terminal' | 'WebForm' | 'ApiTester';
createdAtUtc: string;
}
export interface CreateGuestbookRequest {
senderName: string;
message: string;
origin?: 'Terminal' | 'WebForm' | 'ApiTester';
senderContact?: string;
}

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