fix: GetByCategoryIdAsync incluye productos de categorías ancestras (CTE recursivo)

This commit is contained in:
2026-02-21 20:19:21 -03:00
parent a9ad545fbb
commit da99fd5843

View File

@@ -46,12 +46,26 @@ public class ProductRepository : IProductRepository
public async Task<IEnumerable<Product>> 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<Product>(sql, new { CategoryId = categoryId });
}