diff --git a/src/app/portfolio/[slug]/utils.ts b/src/app/portfolio/[slug]/utils.ts index f5019c8d..adbf53a6 100644 --- a/src/app/portfolio/[slug]/utils.ts +++ b/src/app/portfolio/[slug]/utils.ts @@ -61,6 +61,41 @@ export async function getProperties( return data; } +interface Recommendation { + quantity: number; + quantityUnit: string; + estimatedCost: number; + materialType: string; +} + +function aggregateRecommendations(data: Recommendation[]): Recommendation[] { + const grouped: { [key: string]: Recommendation } = {}; + + data.forEach((item) => { + // Use the combination of quantityUnit and materialType as a unique key + const key = `${item.quantityUnit}_${item.materialType}`; + + if (!grouped[key]) { + grouped[key] = { + ...item, + }; + } else { + grouped[key].quantity += item.quantity; + grouped[key].estimatedCost += item.estimatedCost; + } + }); + + // Round the results to 2 decimal places + for (const key in grouped) { + grouped[key].quantity = parseFloat(grouped[key].quantity.toFixed(2)); + grouped[key].estimatedCost = parseFloat( + grouped[key].estimatedCost.toFixed(2) + ); + } + + return Object.values(grouped); +} + export async function getPortfolioPlan(portfolioId: string) { // To do this we need to do the following: // 1. For the portfolioId, get all of the default plans. This can be done from the plan table @@ -126,5 +161,8 @@ export async function getPortfolioPlan(portfolioId: string) { [] ); - return unnestedRecommendations; + const aggregated = aggregateRecommendations(unnestedRecommendations); + console.log(aggregated); + + return aggregated; }