12vo Commit

This commit is contained in:
DillusDev001 2026-10-28 13:03:45 -04:00
parent ee88c8e963
commit cf671a683e
10 changed files with 401 additions and 7 deletions

Binary file not shown.

View file

@ -58,7 +58,7 @@
height: auto;
margin: 0 auto 22px;
border-radius: 16px;
filter: drop-shadow(0 14px 26px rgba(14, 27, 44, 0.28));
filter: drop-shadow(0 5px 3px rgba(14, 27, 44, 0.28));
}
h1 {
@ -92,6 +92,63 @@
padding: 6px 12px;
}
/* Versión web (alternativa sin instalación) */
.web {
display: flex;
align-items: center;
gap: 12px;
width: 100%;
margin-top: 28px;
padding: 13px 16px;
background: var(--surface);
border: 1.5px solid #dbe4ee;
color: var(--ink);
text-decoration: none;
border-radius: 16px;
text-align: left;
transition: border-color 0.15s ease, background 0.15s ease,
transform 0.15s ease;
}
.web:hover {
border-color: var(--brand);
background: rgba(31, 95, 150, 0.06);
transform: translateY(-1px);
}
.web .ico {
color: var(--brand);
flex: none;
display: flex;
}
.web .txt {
display: flex;
flex-direction: column;
line-height: 1.3;
min-width: 0;
}
.web .fuerte {
font-size: 15.5px;
font-weight: 700;
letter-spacing: -0.01em;
}
.web .chico {
font-size: 12.5px;
color: var(--muted);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.web .flecha {
margin-left: auto;
color: var(--muted);
flex: none;
}
/* Botón principal: descarga APK */
.descarga {
display: flex;
@ -99,7 +156,7 @@
justify-content: center;
gap: 10px;
width: 100%;
margin-top: 28px;
margin-top: 12px;
padding: 16px 20px;
background: var(--brand);
color: #fff;
@ -224,14 +281,39 @@
<span class="chip">Multi-equipo</span>
</div>
<!-- Descarga directa del APK -->
<a class="descarga" href="/descargas/app-ser-101.apk" download="app-ser-101.apk">
<!-- Versión web: corre en el navegador, sin instalar nada -->
<a
class="web"
href="https://min-ser-app.alphaxdev.cc/"
target="_blank"
rel="noopener noreferrer"
>
<span class="ico" aria-hidden="true">
<svg width="22" height="22" viewBox="0 0 24 24" fill="none">
<circle cx="12" cy="12" r="9" stroke="currentColor" stroke-width="2"/>
<path d="M3 12h18M12 3c2.5 2.6 3.75 5.6 3.75 9S14.5 18.4 12 21c-2.5-2.6-3.75-5.6-3.75-9S9.5 5.6 12 3z" stroke="currentColor" stroke-width="2"/>
</svg>
</span>
<span class="txt">
<span class="fuerte">Usar la versión web</span>
<span class="chico">Sin instalación · min-ser-app.alphaxdev.cc</span>
</span>
<span class="flecha" aria-hidden="true">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none">
<path d="M7 17L17 7M9 7h8v8" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
</svg>
</span>
</a>
<!-- Descarga directa del APK (el href fijo es el fallback; el JS lo
reemplaza por el último que reporta el backend) -->
<a class="descarga" id="apk-btn" href="/uploads/apks/app-ser-101.apk" download="app-ser-101.apk">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" aria-hidden="true">
<path d="M12 3v11m0 0l-4.5-4.5M12 14l4.5-4.5" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M4 17v2a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2" stroke="currentColor" stroke-width="2.2" stroke-linecap="round"/>
</svg>
<span>Descargar APK</span>
<span class="meta">· 77 MB</span>
<span class="meta" id="apk-meta">· 77 MB</span>
</a>
<div class="divider">o consíguela en</div>
@ -283,6 +365,22 @@
clearTimeout(temporizador);
temporizador = setTimeout(() => toast.classList.remove('visible'), 2600);
}
// Apunta al APK más nuevo que reporta el backend; si el endpoint no
// responde, queda el href fijo del HTML como fallback.
fetch('/v1/descargas/apk')
.then((r) => (r.ok ? r.json() : null))
.then((j) => {
const apk = j && j.boolean && j.data && j.data[0];
if (!apk) return;
const btn = document.getElementById('apk-btn');
btn.href = apk.url;
btn.setAttribute('download', apk.archivo);
const mb = Math.round(apk.bytes / 1048576);
document.getElementById('apk-meta').textContent =
(apk.version ? '· v' + apk.version + ' · ' : '· ') + mb + ' MB';
})
.catch(() => {});
</script>
</body>
</html>

View file

@ -1,5 +1,7 @@
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service.js';
import { Public } from './common/decorators/public.decorator.js';
import type { ApiResult } from './common/interfaces/api.result.js';
@Controller()
export class AppController {
@ -9,4 +11,16 @@ export class AppController {
getHello(): string {
return this.appService.getHello();
}
/**
* Página de descargas (pública, sin JWT): APK más nuevo — la última
* subida desde la app (fila en la BD con su ruta) o, si no hay, el
* archivo de `uploads/apks/`. El HTML lo usa para apuntar el botón sin
* tener que editar el href a mano en cada versión.
*/
@Public()
@Get('descargas/apk')
async ultimoApk(): Promise<ApiResult> {
return this.appService.ultimoApk();
}
}

View file

@ -1,8 +1,91 @@
import { Injectable } from '@nestjs/common';
import { existsSync, readdirSync, statSync } from 'node:fs';
import { join } from 'node:path';
import { ApiResult, defaultApiResult } from './common/interfaces/api.result.js';
import { ApkService } from './modules/mantenimiento/apk.service.js';
@Injectable()
export class AppService {
constructor(private readonly apks: ApkService) {}
getHello(): string {
return 'Hello World!';
}
/**
* APK más nuevo para la página de descargas: la **última fila** subida
* desde la app (`POST /v1/mantenimiento/apk`), con fallback al escaneo
* de `uploads/apks/` por si el archivo está en disco sin fila (p. ej.
* al migrar un deploy). El HTML hace `GET /v1/descargas/apk` y
* actualiza el href del botón de descarga.
*/
async ultimoApk(): Promise<ApiResult> {
const resultado = defaultApiResult(
'Último APK',
'[GET].../v1/descargas/apk',
);
const fila = await this.apks.ultimo();
if (fila) {
resultado.status = 'correct';
resultado.code = 200;
resultado.message = `APK más nuevo: ${fila.nombreArchivo}.`;
resultado.boolean = true;
resultado.rows = 1;
resultado.data = [
{
archivo: fila.nombreArchivo,
url: fila.ruta,
version: fila.version,
bytes: fila.bytes,
subidoEn: fila.subidoEn,
},
];
return resultado;
}
// Fallback: archivos en `uploads/apks/` sin fila en la BD.
const dir = join(process.cwd(), 'uploads', 'apks');
const apks = existsSync(dir)
? readdirSync(dir)
.filter((nombre) => nombre.toLowerCase().endsWith('.apk'))
.map((archivo) => ({
archivo,
version: /(\d+)(?!.*\d)/.exec(archivo)?.[1] ?? null,
bytes: statSync(join(dir, archivo)).size,
mtime: statSync(join(dir, archivo)).mtimeMs,
}))
: [];
if (apks.length === 0) {
// Vacío ≠ error: la página queda con el href de fallback y la app
// muestra “sin APK publicado”.
resultado.status = 'correct';
resultado.code = 200;
resultado.message = 'No hay APK publicados todavía.';
return resultado;
}
apks.sort((a, b) =>
a.version && b.version
? Number(b.version) - Number(a.version)
: b.mtime - a.mtime,
);
const mejor = apks[0];
resultado.status = 'correct';
resultado.code = 200;
resultado.message = `APK más nuevo: ${mejor.archivo}.`;
resultado.boolean = true;
resultado.rows = 1;
resultado.data = [
{
archivo: mejor.archivo,
url: `/uploads/apks/${mejor.archivo}`,
version: mejor.version,
bytes: mejor.bytes,
},
];
return resultado;
}
}

View file

@ -0,0 +1,66 @@
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import {
defaultServiceResult,
ServiceResult,
} from '../../common/interfaces/service.result.js';
import { Apk } from './entities/apk.entity.js';
/** Versión numérica del nombre (`app-ser-102.apk` → `102`). */
export function versionDeNombre(nombre: string): string | null {
return /(\d+)(?!.*\d)/.exec(nombre)?.[1] ?? null;
}
/**
* Publicación del APK de la app (solo Developer, vía `POST
* /v1/mantenimiento/apk`). El archivo ya quedó en disco en
* `uploads/apks/` (multer); acá se guarda la **ruta** en la BD,
* reemplazando la fila si se vuelve a subir el mismo nombre.
*/
@Injectable()
export class ApkService {
constructor(
@InjectRepository(Apk) private readonly repo: Repository<Apk>,
) {}
async subir(file: Express.Multer.File, idPersona: string): Promise<ServiceResult> {
const resultado = defaultServiceResult();
const nombre = file.filename;
const ruta = `/uploads/apks/${nombre}`;
await this.repo.delete({ nombreArchivo: nombre });
const fila = await this.repo.save(
this.repo.create({
nombreArchivo: nombre,
ruta,
version: versionDeNombre(nombre),
bytes: file.size,
subidoPor: idPersona,
}),
);
resultado.boolean = true;
resultado.number = 1;
resultado.message = `APK ${nombre} publicado. La página de descargas ya lo ofrece.`;
resultado.object = {
nombreArchivo: fila.nombreArchivo,
ruta: fila.ruta,
version: fila.version,
bytes: fila.bytes,
subidoEn: fila.subidoEn,
};
return resultado;
}
/** Fila del APK más recientemente subido (`null` si nunca subieron). */
async ultimo(): Promise<Apk | null> {
// TypeORM 1.x: `findOne` exige condiciones de selección; `find` con
// `take` + orden devuelve lo mismo sin `where`.
const filas = await this.repo.find({
order: { subidoEn: 'DESC' },
take: 1,
});
return filas[0] ?? null;
}
}

View file

@ -0,0 +1,42 @@
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';
/**
* Metadato del APK de la app publicado en `uploads/apks/` (fuera de
* `public/`; el volumen `uploads` lo persiste entre deploys).
*
* El HTML de descargas hace `GET /v1/descargas/apk` y el backend devuelve
* la fila más reciente → el botón queda apuntado a `ruta`.
*/
@Entity('apk')
export class Apk {
@PrimaryGeneratedColumn('uuid')
idApk: string;
/** Nombre del archivo bajo `uploads/apks/` (p. ej. `app-ser-102.apk`). */
@Column({ type: 'varchar' })
nombreArchivo: string;
/** Ruta pública que consume el HTML (`/uploads/apks/…`). */
@Column({ type: 'varchar' })
ruta: string;
/** Versión numérica del nombre (`app-ser-102.apk` → `102`), si la hay. */
@Column({ type: 'varchar', nullable: true })
version?: string | null;
/** Tamaño en bytes del archivo. */
@Column({
type: 'bigint',
transformer: {
to: (v: number) => v,
from: (v: string | number) => Number(v),
},
})
bytes: number;
@Column({ type: 'uuid' })
subidoPor: string;
@Column({ type: 'timestamptz', default: () => 'now()' })
subidoEn: Date;
}

View file

@ -33,6 +33,7 @@ import {
} from './dto/backup.dto.js';
import { MantenimientoService } from './mantenimiento.service.js';
import { BackupService } from './backup.service.js';
import { ApkService } from './apk.service.js';
import { routeMantenimiento } from './mantenimiento.router.js';
function dirBackups(): string {
@ -48,6 +49,7 @@ export class MantenimientoController {
constructor(
private readonly mantenimientoService: MantenimientoService,
private readonly backupService: BackupService,
private readonly apkService: ApkService,
) {}
/// Borrado físico total por categoría: dryRun cuenta; ejecutar exige
@ -437,4 +439,84 @@ export class MantenimientoController {
}
return apiResult;
}
/**
* Sube el APK de la app (multipart campo `archivo`) a `uploads/apks/` y
* guarda la ruta en la BD. El HTML de descargas lo toma vía
* `GET /v1/descargas/apk`.
*/
@Post('apk')
@Autorizacion(AutorizacionEnum.Developer)
@UseInterceptors(
FileInterceptor('archivo', {
storage: diskStorage({
destination: (_req, _file, callback) => {
const dir = join(process.cwd(), 'uploads', 'apks');
if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
callback(null, dir);
},
filename: (_req, file, callback) => {
const ext = extname(file.originalname).toLowerCase() || '.apk';
const base = basename(
file.originalname,
extname(file.originalname),
).replace(/[^\w.-]+/g, '_');
callback(null, `${base}${ext}`);
},
}),
limits: { fileSize: 512 * 1024 * 1024 },
fileFilter: (_req, file, callback) => {
if (!file.originalname.toLowerCase().endsWith('.apk')) {
callback(new Error('El archivo debe tener extensión .apk.'), false);
return;
}
callback(null, true);
},
}),
)
async subirApk(
@Req() req: AuthRequest,
@UploadedFile() file?: Express.Multer.File,
): Promise<ApiResult> {
const apiResult = defaultApiResult(
routeMantenimiento.apkSubir.title,
routeMantenimiento.apkSubir.route,
);
try {
const user = getAuthUser(req);
if (!user) {
apiResult.code = HttpStatus.UNAUTHORIZED;
apiResult.message = 'Token inválido.';
return apiResult;
}
if (!file?.path || !file.filename) {
apiResult.code = HttpStatus.BAD_REQUEST;
apiResult.message = 'No se recibió el APK (campo "archivo").';
return apiResult;
}
const result = await this.apkService.subir(file, user.idPersona);
if (result.boolean) {
apiResult.status = 'correct';
apiResult.code = HttpStatus.OK;
apiResult.message = result.message;
apiResult.boolean = true;
apiResult.rows = result.number;
apiResult.data = [result.object];
} else {
apiResult.code = HttpStatus.BAD_REQUEST;
apiResult.message = result.message;
const { unlink } = await import('fs/promises');
await unlink(file.path).catch(() => undefined);
}
} catch (error) {
apiResult.code = error.status ?? HttpStatus.INTERNAL_SERVER_ERROR;
apiResult.message = error.message;
if (file?.path) {
const { unlink } = await import('fs/promises');
await unlink(file.path).catch(() => undefined);
}
}
return apiResult;
}
}

View file

@ -13,9 +13,11 @@ import { Servicio } from '../servicio/entities/servicio.entity.js';
import { SolicitudApoyo } from '../solicitud-apoyo/entities/solicitud-apoyo.entity.js';
import { Turno } from '../turno/entities/turno.entity.js';
import { Backup } from './entities/backup.entity.js';
import { Apk } from './entities/apk.entity.js';
import { MantenimientoController } from './mantenimiento.controller.js';
import { MantenimientoService } from './mantenimiento.service.js';
import { BackupService } from './backup.service.js';
import { ApkService } from './apk.service.js';
@Module({
imports: [
@ -33,9 +35,12 @@ import { BackupService } from './backup.service.js';
Turno,
Persona,
Backup,
Apk,
]),
],
controllers: [MantenimientoController],
providers: [MantenimientoService, BackupService],
providers: [MantenimientoService, BackupService, ApkService],
// ApkService lo consume AppService (GET público /v1/descargas/apk).
exports: [ApkService],
})
export class MantenimientoModule {}

View file

@ -27,6 +27,10 @@ export const routeMantenimiento = {
route: '[DELETE].../v1/mantenimiento/backup/:idBackup',
title: 'Eliminar respaldo .sql (Developer)',
},
apkSubir: {
route: '[POST].../v1/mantenimiento/apk',
title: 'Subir APK de la app (Developer)',
},
contarInhabilitadas: {
route: '[GET].../v1/mantenimiento/personas-inhabilitadas',
title: 'Contar personas inhabilitadas (Developer)',

File diff suppressed because one or more lines are too long