diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2a15eb1..ecf9e6a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -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: diff --git a/README.md b/README.md index 4ca6e73..3a38843 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/src/repositories/cache/warehouse-count.cache.ts b/src/repositories/cache/warehouse-count.cache.ts new file mode 100644 index 0000000..1970a5d --- /dev/null +++ b/src/repositories/cache/warehouse-count.cache.ts @@ -0,0 +1,53 @@ +interface CachedCount { + total: number; + expiresAt: number; + version: number; +} + +interface PendingCount { + version: number; + promise: Promise; +} + +/** Shares short-lived warehouse row counts and coalesces concurrent reads. */ +export class WarehouseCountCache { + private readonly values = new Map(); + private readonly pending = new Map(); + private readonly versions = new Map(); + + 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): Promise { + 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; + } +} diff --git a/src/repositories/postgres/product.repository.ts b/src/repositories/postgres/product.repository.ts index ead7a16..d17aafe 100644 --- a/src/repositories/postgres/product.repository.ts +++ b/src/repositories/postgres/product.repository.ts @@ -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) {} @@ -67,19 +51,7 @@ export class PostgresProductRepository implements IProductRepository { } async findByIds(ids: string[]): Promise { - const uniqueIds = [...new Set(ids)]; - if (uniqueIds.length === 0) return []; - - const params: Record = {}; - const placeholders = uniqueIds.map((id, index) => { - params[`id${index}`] = id; - return `@id${index}`; - }); - const rows = await this.sqlExecutor.query( - `${SELECT_PRODUCT} WHERE id IN (${placeholders.join(", ")})`, - params - ); - return rows.map(toProduct); + return findProductsByIds(this.sqlExecutor, "products", ids); } async findByCode(code: string): Promise { diff --git a/src/repositories/postgres/stock.repository.ts b/src/repositories/postgres/stock.repository.ts index bde59b5..bae319d 100644 --- a/src/repositories/postgres/stock.repository.ts +++ b/src/repositories/postgres/stock.repository.ts @@ -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(); - private readonly pendingCounts = new Map }>(); - private readonly countVersions = new Map(); + 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 { - 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 { @@ -82,14 +44,8 @@ export class PostgresStockRepository implements IStockRepository { } async getQuantities(productId: string, warehouseIds: string[]): Promise> { - const balances = new Map(warehouseIds.map((id) => [id, 0])); + const { balances, params, placeholders } = buildWarehouseQuery(productId, warehouseIds); if (warehouseIds.length === 0) return balances; - - const params: Record = { 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(", ")}) @@ -102,13 +58,7 @@ export class PostgresStockRepository implements IStockRepository { async setQuantities(productId: string, balances: StockBalance[]): Promise { if (balances.length === 0) return; - - const params: Record = { 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(", ")} @@ -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, }; } diff --git a/src/repositories/shared/product.mapping.ts b/src/repositories/shared/product.mapping.ts new file mode 100644 index 0000000..999a61c --- /dev/null +++ b/src/repositories/shared/product.mapping.ts @@ -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 => { + const uniqueIds = [...new Set(ids)]; + if (uniqueIds.length === 0) return []; + + const params: Record = {}; + const placeholders = uniqueIds.map((id, index) => { + params[`id${index}`] = id; + return `@id${index}`; + }); + const rows = await sqlExecutor.query( + `SELECT id, code, name, description, active, created_at FROM ${table} WHERE id IN (${placeholders.join(", ")})`, + params + ); + return rows.map(toProduct); +}; diff --git a/src/repositories/shared/stock.mapping.ts b/src/repositories/shared/stock.mapping.ts new file mode 100644 index 0000000..493df7a --- /dev/null +++ b/src/repositories/shared/stock.mapping.ts @@ -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(warehouseIds.map((id) => [id, 0])); + const params: Record = { 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 = { 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 }; +}; diff --git a/src/repositories/sqlserver/product.repository.ts b/src/repositories/sqlserver/product.repository.ts index e11637e..299be19 100644 --- a/src/repositories/sqlserver/product.repository.ts +++ b/src/repositories/sqlserver/product.repository.ts @@ -3,30 +3,13 @@ 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"; // Números de error de SQL Server para "llave duplicada" (índice único / restricción UNIQUE). const UNIQUE_VIOLATION_NUMBERS = [2601, 2627]; const SELECT_PRODUCT = "SELECT id, code, name, description, active, created_at FROM dbo.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 SqlServerProductRepository implements IProductRepository { constructor(private readonly sqlExecutor: ISqlExecutor) {} @@ -80,24 +63,7 @@ export class SqlServerProductRepository implements IProductRepository { } async findByIds(ids: string[]): Promise { - const uniqueIds = [...new Set(ids)]; - if (uniqueIds.length === 0) { - return []; - } - - // Una sola consulta con IN (@id0, @id1, ...). SQL Server admite hasta 2100 parámetros por consulta - // y una página de stock trae como máximo 100 productos. - const params: Record = {}; - const placeholders = uniqueIds.map((id, index) => { - params[`id${index}`] = id; - return `@id${index}`; - }); - - const rows = await this.sqlExecutor.query( - `${SELECT_PRODUCT} WHERE id IN (${placeholders.join(", ")})`, - params - ); - return rows.map(toProduct); + return findProductsByIds(this.sqlExecutor, "dbo.products", ids); } async findByCode(code: string): Promise { diff --git a/src/repositories/sqlserver/stock.repository.ts b/src/repositories/sqlserver/stock.repository.ts index 19c2a1d..478b9cc 100644 --- a/src/repositories/sqlserver/stock.repository.ts +++ b/src/repositories/sqlserver/stock.repository.ts @@ -1,66 +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 SqlServerStockRepository implements IStockRepository { - private static readonly COUNT_CACHE_TTL_MS = 2000; - private readonly warehouseCounts = new Map(); - private readonly pendingCounts = new Map }>(); - private readonly countVersions = new Map(); + 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 { - 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(*) AS total FROM dbo.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() + SqlServerStockRepository.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 { @@ -88,7 +48,7 @@ export class SqlServerStockRepository implements IStockRepository { } async getQuantities(productId: string, warehouseIds: string[]): Promise> { - const balances = new Map(warehouseIds.map((id) => [id, 0])); + const { balances, params, placeholders } = buildWarehouseQuery(productId, warehouseIds); if (warehouseIds.length === 0) { return balances; } @@ -96,12 +56,6 @@ export class SqlServerStockRepository implements IStockRepository { // Una sola consulta con IN (@warehouseId0, @warehouseId1, ...) en lugar de una por bodega. // SQL Server recorre la llave (warehouse_id, product_id) en orden, así que las filas se bloquean // siempre en el mismo orden y dos transferencias en sentidos opuestos no se bloquean entre sí. - const params: Record = { 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 dbo.stock WITH (UPDLOCK, HOLDLOCK) WHERE product_id = @productId AND warehouse_id IN (${placeholders.join(", ")})`, @@ -119,12 +73,7 @@ export class SqlServerStockRepository implements IStockRepository { } // Un solo MERGE con todas las filas (actualiza las que existen e inserta las que no). - const params: Record = { 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( `MERGE dbo.stock WITH (HOLDLOCK) AS target @@ -159,15 +108,7 @@ export class SqlServerStockRepository implements IStockRepository { this.getWarehouseCount(warehouseId), ]); - const items = rows.map((row) => ({ - warehouseId, - productId: row.product_id, - productCode: row.product_code, - productName: row.product_name, - quantity: row.quantity, - })); - - return { items, total }; + return { items: toStockListItems(warehouseId, rows), total }; } } diff --git a/test/repositories/postgres.repositories.spec.ts b/test/repositories/postgres.repositories.spec.ts new file mode 100644 index 0000000..b56a52b --- /dev/null +++ b/test/repositories/postgres.repositories.spec.ts @@ -0,0 +1,342 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { AppError } from "../../src/exceptions/errors/app.error"; +import { ISqlExecutor } from "../../src/repositories/interfaces/database.interface"; +import { PostgresMovementRepository } from "../../src/repositories/postgres/movement.repository"; +import { PostgresProductRepository } from "../../src/repositories/postgres/product.repository"; +import { PostgresStockMutationPersistence } from "../../src/repositories/postgres/stock-mutation.persistence"; +import { PostgresStockRepository } from "../../src/repositories/postgres/stock.repository"; +import { PostgresWarehouseRepository } from "../../src/repositories/postgres/warehouse.repository"; +import { + createMovementRepositoryMock, + createStockRepositoryMock, + createTransactionManagerMock, + makeProduct, +} from "../helpers/mocks"; + +const makeExecutor = () => { + const query = vi.fn(async (_sql: string, _params?: Record) => [] as unknown[]); + return { executor: { query } as unknown as ISqlExecutor, query }; +}; + +const productRow = (overrides: Record = {}) => ({ + id: "p-1", + code: "TOR-001", + name: "Tornillo", + description: null, + active: true, + created_at: new Date("2026-01-01T00:00:00.000Z"), + ...overrides, +}); + +describe("PostgresProductRepository", () => { + let query: ReturnType["query"]; + let repository: PostgresProductRepository; + + beforeEach(() => { + const setup = makeExecutor(); + query = setup.query; + repository = new PostgresProductRepository(setup.executor); + }); + + it("inserts or updates a product and returns a copy", async () => { + const product = makeProduct({ description: "Acero" }); + + await expect(repository.save(product)).resolves.toEqual(product); + expect(query).toHaveBeenCalledWith(expect.stringMatching(/ON CONFLICT \(id\) DO UPDATE/), { + id: product.id, + code: product.code, + name: product.name, + description: "Acero", + active: true, + createdAt: product.createdAt, + }); + const saved = await repository.save(product); + expect(saved).not.toBe(product); + }); + + it("maps a duplicate code to the application error and rethrows other database errors", async () => { + query.mockRejectedValueOnce(Object.assign(new Error("duplicate"), { code: "23505" })); + await expect(repository.save(makeProduct())).rejects.toMatchObject({ code: AppError.PRODUCT_CODE_DUPLICATED.code }); + + const databaseError = new Error("connection lost"); + query.mockRejectedValueOnce(databaseError); + await expect(repository.save(makeProduct())).rejects.toBe(databaseError); + }); + + it("maps rows when finding by id and returns null when absent", async () => { + query.mockResolvedValueOnce([productRow()]); + await expect(repository.findById("p-1")).resolves.toEqual(makeProduct({ id: "p-1", name: "Tornillo" })); + expect(query).toHaveBeenLastCalledWith(expect.stringMatching(/WHERE id = @id/), { id: "p-1" }); + await expect(repository.findById("missing")).resolves.toBeNull(); + }); + + it("updates status and maps the returned row, or returns null for a missing product", async () => { + query.mockResolvedValueOnce([productRow({ active: false })]); + await expect(repository.updateStatus("p-1", false)).resolves.toMatchObject({ id: "p-1", active: false }); + expect(query).toHaveBeenLastCalledWith(expect.stringMatching(/UPDATE products[\s\S]*RETURNING/), { id: "p-1", active: false }); + await expect(repository.updateStatus("missing", true)).resolves.toBeNull(); + }); + + it("finds unique ids with parameterized SQL and skips an empty list", async () => { + query.mockResolvedValueOnce([productRow(), productRow({ id: "p-2", code: "B-2" })]); + await expect(repository.findByIds(["p-1", "p-1", "p-2"])).resolves.toHaveLength(2); + expect(query).toHaveBeenLastCalledWith(expect.stringMatching(/IN \(@id0, @id1\)/), { id0: "p-1", id1: "p-2" }); + const calls = query.mock.calls.length; + await expect(repository.findByIds([])).resolves.toEqual([]); + expect(query).toHaveBeenCalledTimes(calls); + }); + + it("finds a product by code and returns null when absent", async () => { + query.mockResolvedValueOnce([productRow()]); + await expect(repository.findByCode("TOR-001")).resolves.toMatchObject({ code: "TOR-001" }); + expect(query).toHaveBeenLastCalledWith(expect.stringMatching(/WHERE code = @code/), { code: "TOR-001" }); + await expect(repository.findByCode("missing")).resolves.toBeNull(); + }); +}); + +describe("PostgresWarehouseRepository", () => { + it("returns a warehouse copy or null when it does not exist", async () => { + const { executor, query } = makeExecutor(); + const repository = new PostgresWarehouseRepository(executor); + const warehouse = { id: "BOG", name: "Bodega Bogotá", city: "Bogotá" }; + query.mockResolvedValueOnce([warehouse]); + const found = await repository.findById("BOG"); + expect(found).toEqual(warehouse); + expect(found).not.toBe(warehouse); + expect(query).toHaveBeenLastCalledWith(expect.stringMatching(/FROM warehouses WHERE id = @id/), { id: "BOG" }); + await expect(repository.findById("missing")).resolves.toBeNull(); + }); +}); + +describe("PostgresMovementRepository", () => { + it("saves one movement through saveMany and returns a copy", async () => { + const { executor, query } = makeExecutor(); + const repository = new PostgresMovementRepository(executor); + const movement = { + id: "m-1", type: "ADJUSTMENT_IN" as const, warehouseId: "BOG", productId: "p-1", quantity: 3, + balanceAfter: 3, reason: "Conteo", transferId: null, responsibleId: "u-1", createdAt: new Date(), + }; + const result = await repository.save(movement); + expect(result).toEqual(movement); + expect(result).not.toBe(movement); + expect(query).toHaveBeenCalledWith(expect.stringMatching(/INSERT INTO movements/), expect.objectContaining({ + id0: "m-1", type0: "ADJUSTMENT_IN", warehouseId0: "BOG", productId0: "p-1", quantity0: 3, + })); + }); + + it("saves multiple movements in one insert and does nothing for an empty list", async () => { + const { executor, query } = makeExecutor(); + const repository = new PostgresMovementRepository(executor); + const base = { + type: "TRANSFER_OUT" as const, warehouseId: "BOG", productId: "p-1", quantity: 2, + balanceAfter: 1, reason: null, transferId: "t-1", responsibleId: "u-1", createdAt: new Date(), + }; + const movements = [ + { ...base, id: "out" }, + { ...base, id: "in", type: "TRANSFER_IN" as const, warehouseId: "MED", balanceAfter: 2 }, + ]; + const result = await repository.saveMany(movements); + expect(result).toEqual(movements); + expect(result[0]).not.toBe(movements[0]); + expect(query).toHaveBeenCalledTimes(1); + expect(query).toHaveBeenCalledWith(expect.stringMatching(/\(@id0[\s\S]*\(@id1/), expect.objectContaining({ + id0: "out", id1: "in", type1: "TRANSFER_IN", warehouseId1: "MED", + })); + await expect(repository.saveMany([])).resolves.toEqual([]); + expect(query).toHaveBeenCalledTimes(1); + }); +}); + +describe("PostgresStockRepository", () => { + let query: ReturnType["query"]; + let executor: ISqlExecutor; + let repository: PostgresStockRepository; + + beforeEach(() => { + vi.restoreAllMocks(); + const setup = makeExecutor(); + query = setup.query; + executor = setup.executor; + repository = new PostgresStockRepository(executor); + }); + + it("reads a locked quantity and defaults a missing balance to zero", async () => { + query.mockResolvedValueOnce([{ quantity: 7 }]); + await expect(repository.getQuantity("BOG", "p-1")).resolves.toBe(7); + expect(query).toHaveBeenLastCalledWith(expect.stringMatching(/FOR UPDATE/), { warehouseId: "BOG", productId: "p-1" }); + await expect(repository.getQuantity("BOG", "missing")).resolves.toBe(0); + }); + + it("upserts one quantity and invalidates its count cache", async () => { + const invalidate = vi.spyOn(repository, "invalidateWarehouseCounts"); + await repository.setQuantity("BOG", "p-1", 8); + expect(query).toHaveBeenCalledWith(expect.stringMatching(/ON CONFLICT \(warehouse_id, product_id\)/), { + warehouseId: "BOG", productId: "p-1", quantity: 8, + }); + expect(invalidate).toHaveBeenCalledWith(["BOG"]); + }); + + it("returns zero balances for unrequested rows and avoids a query for no warehouses", async () => { + query.mockResolvedValueOnce([{ warehouse_id: "BOG", quantity: 9 }]); + await expect(repository.getQuantities("p-1", ["BOG", "MED"])).resolves.toEqual(new Map([ + ["BOG", 9], ["MED", 0], + ])); + expect(query).toHaveBeenLastCalledWith(expect.stringMatching(/ORDER BY warehouse_id FOR UPDATE/), { + productId: "p-1", warehouseId0: "BOG", warehouseId1: "MED", + }); + const calls = query.mock.calls.length; + await expect(repository.getQuantities("p-1", [])).resolves.toEqual(new Map()); + expect(query).toHaveBeenCalledTimes(calls); + }); + + it("upserts several balances at once and skips an empty update", async () => { + const invalidate = vi.spyOn(repository, "invalidateWarehouseCounts"); + const balances = [{ warehouseId: "BOG", quantity: 4 }, { warehouseId: "MED", quantity: 6 }]; + await repository.setQuantities("p-1", balances); + expect(query).toHaveBeenCalledWith(expect.stringMatching(/VALUES \(@warehouseId0, @productId, @quantity0\), \(@warehouseId1/), { + productId: "p-1", warehouseId0: "BOG", quantity0: 4, warehouseId1: "MED", quantity1: 6, + }); + expect(invalidate).toHaveBeenCalledWith(["BOG", "MED"]); + await repository.setQuantities("p-1", []); + expect(query).toHaveBeenCalledTimes(1); + }); + + it("lists a page, maps rows, and caches the count query", async () => { + query.mockResolvedValueOnce([{ product_id: "p-1", product_code: "A-1", product_name: "Alfa", quantity: 5 }]) + .mockResolvedValueOnce([{ total: 2 }]); + await expect(repository.listByWarehouse("BOG", 10, 1)).resolves.toEqual({ + items: [{ warehouseId: "BOG", productId: "p-1", productCode: "A-1", productName: "Alfa", quantity: 5 }], + total: 2, + }); + expect(query).toHaveBeenCalledTimes(2); + expect(query).toHaveBeenCalledWith(expect.stringMatching(/INNER JOIN products/), { warehouseId: "BOG", offset: 10, limit: 1 }); + query.mockResolvedValueOnce([]); + await repository.listByWarehouse("BOG", 0, 10); + expect(query).toHaveBeenCalledTimes(3); + }); + + it("coalesces count requests and does not cache a result invalidated while pending", async () => { + let resolveCount!: (rows: { total: number }[]) => void; + query.mockResolvedValueOnce([]); + query.mockImplementationOnce(() => new Promise((resolve) => { resolveCount = resolve; })); + query.mockResolvedValueOnce([]); + const first = repository.listByWarehouse("BOG", 0, 10); + const second = repository.listByWarehouse("BOG", 10, 10); + await Promise.resolve(); + expect(query).toHaveBeenCalledTimes(3); + repository.invalidateWarehouseCounts(["BOG"]); + resolveCount([{ total: 3 }]); + await Promise.all([first, second]); + + query.mockResolvedValueOnce([]).mockResolvedValueOnce([{ total: 4 }]); + await repository.listByWarehouse("BOG", 0, 10); + expect(query).toHaveBeenCalledTimes(5); + }); + + it("refreshes an expired count and defaults to zero when the count row is absent", async () => { + let now = 100; + vi.spyOn(Date, "now").mockImplementation(() => now); + repository = new PostgresStockRepository(executor); + query.mockResolvedValueOnce([]).mockResolvedValueOnce([{ total: 2 }]); + await repository.listByWarehouse("MED", 0, 10); + now += 2500; + query.mockResolvedValueOnce([]).mockResolvedValueOnce([]); + await expect(repository.listByWarehouse("MED", 0, 10)).resolves.toMatchObject({ total: 0 }); + expect(query).toHaveBeenCalledTimes(4); + }); +}); + +describe("PostgresStockMutationPersistence", () => { + const adjustment = { + warehouseId: "BOG", productId: "p-1", quantity: 3, reason: "Conteo inicial", responsibleId: "u-1", + movementId: "m-1", createdAt: new Date("2026-01-01T00:00:00.000Z"), + }; + const transfer = { + productId: "p-1", originWarehouseId: "BOG", destinationWarehouseId: "MED", quantity: 2, + responsibleId: "u-1", transferId: "t-1", outMovementId: "m-out", inMovementId: "m-in", + createdAt: new Date("2026-01-01T00:00:00.000Z"), + }; + + it("adjusts stock atomically, writes the matching movement, and invalidates counts", async () => { + const { executor, query } = makeExecutor(); + query.mockResolvedValueOnce([{ active: true }]); + const transactions = createTransactionManagerMock(); + const stock = createStockRepositoryMock(); + stock.getQuantity.mockResolvedValue(5); + const movements = createMovementRepositoryMock(); + const persistence = new PostgresStockMutationPersistence(executor, transactions, stock, movements); + + await expect(persistence.adjustStock(adjustment)).resolves.toEqual({ previousBalance: 5, newBalance: 8 }); + expect(transactions.run).toHaveBeenCalledTimes(1); + expect(query).toHaveBeenCalledWith(expect.stringMatching(/FOR UPDATE/), { productId: "p-1" }); + expect(stock.setQuantity).toHaveBeenCalledWith("BOG", "p-1", 8); + expect(movements.save).toHaveBeenCalledWith(expect.objectContaining({ + type: "ADJUSTMENT_IN", quantity: 3, balanceAfter: 8, transferId: null, + })); + expect(stock.invalidateWarehouseCounts).toHaveBeenCalledWith(["BOG"]); + }); + + it("records outgoing adjustments as positive movement amounts", async () => { + const { executor, query } = makeExecutor(); + query.mockResolvedValueOnce([{ active: true }]); + const stock = createStockRepositoryMock(); + stock.getQuantity.mockResolvedValue(7); + const movements = createMovementRepositoryMock(); + const persistence = new PostgresStockMutationPersistence(executor, createTransactionManagerMock(), stock, movements); + + await expect(persistence.adjustStock({ ...adjustment, quantity: -2 })).resolves.toEqual({ previousBalance: 7, newBalance: 5 }); + expect(movements.save).toHaveBeenCalledWith(expect.objectContaining({ type: "ADJUSTMENT_OUT", quantity: 2, balanceAfter: 5 })); + }); + + it("rejects missing or inactive products and prevents negative stock", async () => { + const { executor, query } = makeExecutor(); + const stock = createStockRepositoryMock(); + const movements = createMovementRepositoryMock(); + const persistence = new PostgresStockMutationPersistence(executor, createTransactionManagerMock(), stock, movements); + + await expect(persistence.adjustStock(adjustment)).rejects.toMatchObject({ code: AppError.PRODUCT_NOT_FOUND.code }); + query.mockResolvedValueOnce([{ active: false }]); + await expect(persistence.adjustStock(adjustment)).rejects.toMatchObject({ code: AppError.PRODUCT_INACTIVE.code }); + query.mockResolvedValueOnce([{ active: true }]); + stock.getQuantity.mockResolvedValue(1); + await expect(persistence.adjustStock({ ...adjustment, quantity: -2 })).rejects.toMatchObject({ code: AppError.INSUFFICIENT_STOCK.code }); + expect(stock.setQuantity).not.toHaveBeenCalled(); + expect(movements.save).not.toHaveBeenCalled(); + }); + + it("transfers both balances in one transaction and writes paired movements", async () => { + const { executor, query } = makeExecutor(); + query.mockResolvedValueOnce([{ active: true }]); + const transactions = createTransactionManagerMock(); + const stock = createStockRepositoryMock(); + stock.getQuantities.mockResolvedValue(new Map([["BOG", 8], ["MED", 1]])); + const movements = createMovementRepositoryMock(); + const persistence = new PostgresStockMutationPersistence(executor, transactions, stock, movements); + + await expect(persistence.transfer(transfer)).resolves.toEqual({ originBalance: 6, destinationBalance: 3 }); + expect(transactions.run).toHaveBeenCalledTimes(1); + expect(stock.setQuantities).toHaveBeenCalledWith("p-1", [ + { warehouseId: "BOG", quantity: 6 }, { warehouseId: "MED", quantity: 3 }, + ]); + expect(movements.saveMany).toHaveBeenCalledWith([ + expect.objectContaining({ id: "m-out", type: "TRANSFER_OUT", warehouseId: "BOG", balanceAfter: 6 }), + expect.objectContaining({ id: "m-in", type: "TRANSFER_IN", warehouseId: "MED", balanceAfter: 3 }), + ]); + expect(stock.invalidateWarehouseCounts).toHaveBeenCalledWith(["BOG", "MED"]); + }); + + it("rejects transfers of inactive products or insufficient stock", async () => { + const { executor, query } = makeExecutor(); + const stock = createStockRepositoryMock(); + const movements = createMovementRepositoryMock(); + const persistence = new PostgresStockMutationPersistence(executor, createTransactionManagerMock(), stock, movements); + + query.mockResolvedValueOnce([{ active: false }]); + await expect(persistence.transfer(transfer)).rejects.toMatchObject({ code: AppError.PRODUCT_INACTIVE.code }); + query.mockResolvedValueOnce([{ active: true }]); + stock.getQuantities.mockResolvedValue(new Map([["BOG", 1], ["MED", 4]])); + await expect(persistence.transfer(transfer)).rejects.toMatchObject({ code: AppError.INSUFFICIENT_STOCK.code }); + expect(stock.setQuantities).not.toHaveBeenCalled(); + expect(movements.saveMany).not.toHaveBeenCalled(); + }); +});