Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,33 @@ jobs:
- name: Pruebas unitarias con cobertura
run: npm run test:coverage

- name: Configurar Node.js para el frontend
uses: actions/setup-node@v4
with:
node-version: 22
cache: npm
cache-dependency-path: frontend/package-lock.json

- name: Instalar dependencias del frontend
working-directory: frontend
run: npm ci

- name: Validar tipos del frontend
working-directory: frontend
run: npm run typecheck

- name: Revisar estilo del frontend
working-directory: frontend
run: npm run lint

- name: Compilar el frontend
working-directory: frontend
run: npm run build

- name: Pruebas unitarias del frontend
working-directory: frontend
run: npm test

- name: Análisis con SonarCloud
uses: SonarSource/sonarqube-scan-action@v6
env:
Expand Down
55 changes: 55 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,58 @@
# Documentación del proyecto final

[![CI](https://github.com/Juanma-cardona/Proyecto_final/actions/workflows/ci.yml/badge.svg)](https://github.com/Juanma-cardona/Proyecto_final/actions/workflows/ci.yml)
[![Quality Gate](https://sonarcloud.io/api/project_badges/measure?project=Juanma-cardona_Proyecto_final&metric=alert_status)](https://sonarcloud.io/summary/overall?id=Juanma-cardona_Proyecto_final)

## Enlaces

| Recurso | Enlace / estado |
|---|---|
| Repositorio GitHub | [Juanma-cardona/Proyecto_final](https://github.com/Juanma-cardona/Proyecto_final) |
| Aplicación web | [Abrir BodegasApp](https://proyecto-final-two-beige.vercel.app/) |
| Análisis SonarCloud | [Resumen del proyecto](https://sonarcloud.io/summary/overall?id=Juanma-cardona_Proyecto_final) |
| Pipeline CI | [GitHub Actions](https://github.com/Juanma-cardona/Proyecto_final/actions/workflows/ci.yml) |

## Estado actual de SonarCloud

La captura más reciente muestra **2 condiciones fallidas en New Code**. La imagen resume esas métricas; el [panel de SonarCloud](https://sonarcloud.io/summary/overall?id=Juanma-cardona_Proyecto_final) refleja el análisis publicado más reciente.

| Métrica | Resultado de la captura |
|---|---:|
| Condición | Resultado | Requisito |
|---|---:|---:|
| Cobertura de código nuevo | 55.77% (368 líneas) | ≥ 80.0% |
| Líneas duplicadas nuevas | 8.96% (3k líneas) | ≤ 3.0% |
| Issues nuevos / aceptados | 0 / 0 | — |
| Security hotspots | 0 | — |

Estos valores provienen de la captura más reciente compartida y pueden cambiar después del siguiente análisis.

## Componentes del proyecto

- **API** (`src/`): servicio REST con Express y TypeScript para productos, existencias, ajustes y transferencias entre las bodegas BOG, MED y CAL.
- **Interfaz web** (`frontend/`): aplicación React y Vite para consultar existencias y gestionar productos y movimientos.
- **Pruebas de API** (`automation/`): pruebas de integración con Playwright. Requieren una API accesible y una base de datos configurada.
- **Base de datos** (`database/`): scripts y configuración de persistencia.

## Pipeline de integración continua

El workflow [`.github/workflows/ci.yml`](.github/workflows/ci.yml) se ejecuta en pushes a `main` o `master` y en Pull Requests. Compila la API, ejecuta sus pruebas con cobertura, valida los tipos y el estilo del frontend, compila la interfaz y corre sus pruebas unitarias. También envía el análisis a SonarCloud mediante el secreto `SONAR_TOKEN` del repositorio.

Las pruebas Playwright de `automation/` no se ejecutan en CI porque requieren una API y una base de datos de integración. Sus instrucciones están en [`automation/README.md`](automation/README.md).

## Ejecución local

Instala las dependencias de la API y del frontend:

```bash
npm ci
cd frontend
npm ci
npm run dev
```

En otra terminal, desde la raíz del repositorio, ejecuta `npm run dev` para iniciar la API. La interfaz queda en `http://localhost:5173` y la API en `http://localhost:3000`. Revisa [`.env.example`](.env.example) y [`frontend/.env.example`](frontend/.env.example) para los valores locales; no publiques credenciales.

# API de Gestión de Bodegas (3 bodegas)

API REST para controlar el inventario de una distribuidora con **tres bodegas físicas** (propuesta 2 del curso de Pruebas de Software). Permite crear productos, consultar el stock por bodega, hacer ajustes manuales con justificación y transferir mercancía entre bodegas, garantizando que **el stock nunca quede negativo** y dejando registro de cada movimiento.
Expand Down
53 changes: 53 additions & 0 deletions src/repositories/cache/warehouse-count.cache.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
interface CachedCount {
total: number;
expiresAt: number;
version: number;
}

interface PendingCount {
version: number;
promise: Promise<number>;
}

/** Shares short-lived warehouse row counts and coalesces concurrent reads. */
export class WarehouseCountCache {
private readonly values = new Map<string, CachedCount>();
private readonly pending = new Map<string, PendingCount>();
private readonly versions = new Map<string, number>();

constructor(private readonly ttlMs = 2000, private readonly now: () => number = Date.now) {}

invalidate(warehouseId: string): void {
this.values.delete(warehouseId);
this.versions.set(warehouseId, (this.versions.get(warehouseId) ?? 0) + 1);
this.pending.delete(warehouseId);
}

invalidateMany(warehouseIds: string[]): void {
for (const warehouseId of warehouseIds) this.invalidate(warehouseId);
}

get(warehouseId: string, load: () => Promise<number>): Promise<number> {
const version = this.versions.get(warehouseId) ?? 0;
const cached = this.values.get(warehouseId);
if (cached && cached.expiresAt > this.now() && cached.version === version) {
return Promise.resolve(cached.total);
}

const existing = this.pending.get(warehouseId);
if (existing?.version === version) return existing.promise;

const promise = load()
.then((total) => {
if ((this.versions.get(warehouseId) ?? 0) === version) {
this.values.set(warehouseId, { total, expiresAt: this.now() + this.ttlMs, version });
}
return total;
})
.finally(() => {
if (this.pending.get(warehouseId)?.promise === promise) this.pending.delete(warehouseId);
});
this.pending.set(warehouseId, { version, promise });
return promise;
}
}
32 changes: 2 additions & 30 deletions src/repositories/postgres/product.repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,25 +3,9 @@ import { AppError } from "../../exceptions/errors/app.error";
import { fail } from "../../exceptions/fail";
import { ISqlExecutor } from "../interfaces/database.interface";
import { IProductRepository } from "../interfaces/repositories.interface";

interface ProductRow {
id: string;
code: string;
name: string;
description: string | null;
active: boolean;
created_at: Date;
}
import { findProductsByIds, ProductRow, toProduct } from "../shared/product.mapping";

const SELECT_PRODUCT = "SELECT id, code, name, description, active, created_at FROM products";
const toProduct = (row: ProductRow): Product => ({
id: row.id,
code: row.code,
name: row.name,
description: row.description,
active: row.active,
createdAt: row.created_at,
});

export class PostgresProductRepository implements IProductRepository {
constructor(private readonly sqlExecutor: ISqlExecutor) {}
Expand Down Expand Up @@ -67,19 +51,7 @@ export class PostgresProductRepository implements IProductRepository {
}

async findByIds(ids: string[]): Promise<Product[]> {
const uniqueIds = [...new Set(ids)];
if (uniqueIds.length === 0) return [];

const params: Record<string, string> = {};
const placeholders = uniqueIds.map((id, index) => {
params[`id${index}`] = id;
return `@id${index}`;
});
const rows = await this.sqlExecutor.query<ProductRow>(
`${SELECT_PRODUCT} WHERE id IN (${placeholders.join(", ")})`,
params
);
return rows.map(toProduct);
return findProductsByIds(this.sqlExecutor, "products", ids);
}

async findByCode(code: string): Promise<Product | null> {
Expand Down
80 changes: 12 additions & 68 deletions src/repositories/postgres/stock.repository.ts
Original file line number Diff line number Diff line change
@@ -1,64 +1,26 @@
import { StockListItem } from "../../entities/warehouse.entities";
import { WarehouseCountCache } from "../cache/warehouse-count.cache";
import { ISqlExecutor } from "../interfaces/database.interface";
import { IStockRepository, StockBalance } from "../interfaces/repositories.interface";

interface StockPageRow {
product_id: string;
product_code: string;
product_name: string;
quantity: number;
}
import { buildStockBalanceValues, buildWarehouseQuery, StockPageRow, toStockListItems } from "../shared/stock.mapping";

export class PostgresStockRepository implements IStockRepository {
private static readonly COUNT_CACHE_TTL_MS = 2000;
private readonly warehouseCounts = new Map<string, { total: number; expiresAt: number; version: number }>();
private readonly pendingCounts = new Map<string, { version: number; promise: Promise<number> }>();
private readonly countVersions = new Map<string, number>();
private readonly warehouseCounts = new WarehouseCountCache();

constructor(private readonly sqlExecutor: ISqlExecutor) {}

private invalidateWarehouseCount(warehouseId: string): void {
this.warehouseCounts.delete(warehouseId);
this.countVersions.set(warehouseId, (this.countVersions.get(warehouseId) ?? 0) + 1);
this.pendingCounts.delete(warehouseId);
}

invalidateWarehouseCounts(warehouseIds: string[]): void {
for (const warehouseId of warehouseIds) this.invalidateWarehouseCount(warehouseId);
this.warehouseCounts.invalidateMany(warehouseIds);
}

private getWarehouseCount(warehouseId: string): Promise<number> {
const version = this.countVersions.get(warehouseId) ?? 0;
const cached = this.warehouseCounts.get(warehouseId);
if (cached && cached.expiresAt > Date.now() && cached.version === version) {
return Promise.resolve(cached.total);
}
const pending = this.pendingCounts.get(warehouseId);
if (pending?.version === version) return pending.promise;

const promise = this.sqlExecutor
.query<{ total: number }>(
return this.warehouseCounts.get(warehouseId, async () => {
const rows = await this.sqlExecutor.query<{ total: number }>(
"SELECT COUNT(*)::integer AS total FROM stock WHERE warehouse_id = @warehouseId",
{ warehouseId }
)
.then((rows) => {
const total = rows[0]?.total ?? 0;
if ((this.countVersions.get(warehouseId) ?? 0) === version) {
this.warehouseCounts.set(warehouseId, {
total,
expiresAt: Date.now() + PostgresStockRepository.COUNT_CACHE_TTL_MS,
version,
});
}
return total;
})
.finally(() => {
if (this.pendingCounts.get(warehouseId)?.promise === promise) {
this.pendingCounts.delete(warehouseId);
}
});
this.pendingCounts.set(warehouseId, { version, promise });
return promise;
);
return rows[0]?.total ?? 0;
});
}

async getQuantity(warehouseId: string, productId: string): Promise<number> {
Expand All @@ -82,14 +44,8 @@ export class PostgresStockRepository implements IStockRepository {
}

async getQuantities(productId: string, warehouseIds: string[]): Promise<Map<string, number>> {
const balances = new Map<string, number>(warehouseIds.map((id) => [id, 0]));
const { balances, params, placeholders } = buildWarehouseQuery(productId, warehouseIds);
if (warehouseIds.length === 0) return balances;

const params: Record<string, string> = { productId };
const placeholders = warehouseIds.map((id, index) => {
params[`warehouseId${index}`] = id;
return `@warehouseId${index}`;
});
const rows = await this.sqlExecutor.query<{ warehouse_id: string; quantity: number }>(
`SELECT warehouse_id, quantity FROM stock
WHERE product_id = @productId AND warehouse_id IN (${placeholders.join(", ")})
Expand All @@ -102,13 +58,7 @@ export class PostgresStockRepository implements IStockRepository {

async setQuantities(productId: string, balances: StockBalance[]): Promise<void> {
if (balances.length === 0) return;

const params: Record<string, string | number> = { productId };
const values = balances.map((balance, index) => {
params[`warehouseId${index}`] = balance.warehouseId;
params[`quantity${index}`] = balance.quantity;
return `(@warehouseId${index}, @productId, @quantity${index})`;
});
const { params, values } = buildStockBalanceValues(productId, balances);
await this.sqlExecutor.query(
`INSERT INTO stock (warehouse_id, product_id, quantity)
VALUES ${values.join(", ")}
Expand Down Expand Up @@ -136,13 +86,7 @@ export class PostgresStockRepository implements IStockRepository {
this.getWarehouseCount(warehouseId),
]);
return {
items: rows.map((row) => ({
warehouseId,
productId: row.product_id,
productCode: row.product_code,
productName: row.product_name,
quantity: row.quantity,
})),
items: toStockListItems(warehouseId, rows),
total,
};
}
Expand Down
40 changes: 40 additions & 0 deletions src/repositories/shared/product.mapping.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { Product } from "../../entities/warehouse.entities";
import { ISqlExecutor } from "../interfaces/database.interface";

export interface ProductRow {
id: string;
code: string;
name: string;
description: string | null;
active: boolean;
created_at: Date;
}

export const toProduct = (row: ProductRow): Product => ({
id: row.id,
code: row.code,
name: row.name,
description: row.description,
active: row.active,
createdAt: row.created_at,
});

export const findProductsByIds = async (
sqlExecutor: ISqlExecutor,
table: "products" | "dbo.products",
ids: string[]
): Promise<Product[]> => {
const uniqueIds = [...new Set(ids)];
if (uniqueIds.length === 0) return [];

const params: Record<string, string> = {};
const placeholders = uniqueIds.map((id, index) => {
params[`id${index}`] = id;
return `@id${index}`;
});
const rows = await sqlExecutor.query<ProductRow>(
`SELECT id, code, name, description, active, created_at FROM ${table} WHERE id IN (${placeholders.join(", ")})`,
params
);
return rows.map(toProduct);
};
38 changes: 38 additions & 0 deletions src/repositories/shared/stock.mapping.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { StockListItem } from "../../entities/warehouse.entities";
import { StockBalance } from "../interfaces/repositories.interface";

export interface StockPageRow {
product_id: string;
product_code: string;
product_name: string;
quantity: number;
}

export const toStockListItems = (warehouseId: string, rows: StockPageRow[]): StockListItem[] =>
rows.map((row) => ({
warehouseId,
productId: row.product_id,
productCode: row.product_code,
productName: row.product_name,
quantity: row.quantity,
}));

export const buildWarehouseQuery = (productId: string, warehouseIds: string[]) => {
const balances = new Map<string, number>(warehouseIds.map((id) => [id, 0]));
const params: Record<string, string> = { productId };
const placeholders = warehouseIds.map((id, index) => {
params[`warehouseId${index}`] = id;
return `@warehouseId${index}`;
});
return { balances, params, placeholders };
};

export const buildStockBalanceValues = (productId: string, balances: StockBalance[]) => {
const params: Record<string, string | number> = { productId };
const values = balances.map((balance, index) => {
params[`warehouseId${index}`] = balance.warehouseId;
params[`quantity${index}`] = balance.quantity;
return `(@warehouseId${index}, @productId, @quantity${index})`;
});
return { params, values };
};
Loading
Loading