From da99fd584312613be00d31e7c3c9edcb7d8ac1be Mon Sep 17 00:00:00 2001 From: dmolinari Date: Sat, 21 Feb 2026 20:19:21 -0300 Subject: [PATCH] =?UTF-8?q?fix:=20GetByCategoryIdAsync=20incluye=20product?= =?UTF-8?q?os=20de=20categor=C3=ADas=20ancestras=20(CTE=20recursivo)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Repositories/ProductRepository.cs | 20 ++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/src/SIGCM.Infrastructure/Repositories/ProductRepository.cs b/src/SIGCM.Infrastructure/Repositories/ProductRepository.cs index 4cd5055..e2a4c77 100644 --- a/src/SIGCM.Infrastructure/Repositories/ProductRepository.cs +++ b/src/SIGCM.Infrastructure/Repositories/ProductRepository.cs @@ -46,12 +46,26 @@ public class ProductRepository : IProductRepository public async Task> GetByCategoryIdAsync(int categoryId) { using var conn = _db.CreateConnection(); + // CTE recursivo: sube por la jerarquía de categorías para incluir + // productos asignados al rubro solicitado O a cualquiera de sus ancestros. + // Ejemplo: consultando "Autos" devuelve productos de "Autos" Y de "Vehículos". var sql = @" - SELECT p.*, c.Name as CompanyName, pt.Code as TypeCode + WITH CategoryAncestors AS ( + -- Nodo raíz: la categoría pedida + SELECT Id, ParentId FROM Categories WHERE Id = @CategoryId + UNION ALL + -- Subir un nivel: el padre de cada nodo ya en el CTE + SELECT c.Id, c.ParentId + FROM Categories c + INNER JOIN CategoryAncestors ca ON c.Id = ca.ParentId + ) + SELECT p.*, comp.Name as CompanyName, pt.Code as TypeCode FROM Products p - JOIN Companies c ON p.CompanyId = c.Id + JOIN Companies comp ON p.CompanyId = comp.Id JOIN ProductTypes pt ON p.ProductTypeId = pt.Id - WHERE p.CategoryId = @CategoryId AND p.IsActive = 1"; + WHERE p.CategoryId IN (SELECT Id FROM CategoryAncestors) + AND p.IsActive = 1 + OPTION (MAXRECURSION 20)"; return await conn.QueryAsync(sql, new { CategoryId = categoryId }); }