diff --git a/app/(protected)/productos/page.tsx b/app/(protected)/productos/page.tsx index 7e3af43..40ea5d4 100644 --- a/app/(protected)/productos/page.tsx +++ b/app/(protected)/productos/page.tsx @@ -33,9 +33,17 @@ export default async function ProductosPage() { currentStock: Number(ri.supply.currentStock), minStock: Number(ri.supply.minStock), purchasePrice: Number(ri.supply.purchasePrice) - } : null + } : null })) || [] + const recipeCost = recipeItems.reduce((acc: number, ri: any) => { + return acc + (Number(ri.quantityRequired) || 0) * (Number(ri.supply?.purchasePrice) || 0) + }, 0) + const unitCost = yieldAmount > 0 ? recipeCost / yieldAmount : 0 + const computedMargin = salePrice > 0 && unitCost > 0 + ? ((salePrice - unitCost) / salePrice) * 100 + : profitMargin + let maxBatches = Infinity if (recipeItems.length === 0) { maxBatches = 0 @@ -64,9 +72,12 @@ export default async function ProductosPage() { companyId: p.companyId, isPublic: p.isPublic ?? false, preparation: p.preparation, + computedMargin, } }) + products.sort((a: any, b: any) => b.computedMargin - a.computedMargin) + const supplies = suppliesRaw.map((s: any) => ({ id: s.id, name: s.name, diff --git a/app/api/products/route.ts b/app/api/products/route.ts index 00b9ac2..199ae2e 100644 --- a/app/api/products/route.ts +++ b/app/api/products/route.ts @@ -39,6 +39,14 @@ export async function GET() { } : null })) || [] + const recipeCost = recipeItems.reduce((acc: number, ri: any) => { + return acc + (Number(ri.quantityRequired) || 0) * (Number(ri.supply?.purchasePrice) || 0) + }, 0) + const unitCost = yieldAmount > 0 ? recipeCost / yieldAmount : 0 + const computedMargin = salePrice > 0 && unitCost > 0 + ? ((salePrice - unitCost) / salePrice) * 100 + : profitMargin + let maxBatches = Infinity if (recipeItems.length === 0) { maxBatches = 0 @@ -66,9 +74,12 @@ export async function GET() { maxPossibleBatches: maxBatches === Infinity ? 0 : maxBatches, isPublic: p.isPublic ?? false, preparation: p.preparation, + computedMargin, } }) + mapped.sort((a: any, b: any) => b.computedMargin - a.computedMargin) + return NextResponse.json(mapped) } catch (error) { console.error('Error fetching products:', error) diff --git a/app/tienda/[slug]/producto/[productId]/producto-detalle-client.tsx b/app/tienda/[slug]/producto/[productId]/producto-detalle-client.tsx index 274a7e3..4be285c 100644 --- a/app/tienda/[slug]/producto/[productId]/producto-detalle-client.tsx +++ b/app/tienda/[slug]/producto/[productId]/producto-detalle-client.tsx @@ -177,7 +177,7 @@ export function ProductoDetalleClient({ product, company }: { product: Product; {product.ingredients.map((ig, i) => (