diff --git a/src/controllers/00-stats-controller.ts b/src/controllers/00-stats-controller.ts index e739d44..03a9ba2 100644 --- a/src/controllers/00-stats-controller.ts +++ b/src/controllers/00-stats-controller.ts @@ -322,6 +322,13 @@ export class StatsController extends Controller { ) { const record = await prisma.quotationProductServiceList.findMany({ include: { + work: { + include: { + productOnWork: { + select: { stepCount: true, productId: true }, + }, + }, + }, product: { select: { agentPrice: true, @@ -335,9 +342,16 @@ export class StatsController extends Controller { vatIncluded: true, }, }, + requestWork: { + include: { + stepStatus: true, + creditNote: true, + }, + }, quotation: { select: { agentPrice: true, + creditNote: true, }, }, }, @@ -358,26 +372,44 @@ export class StatsController extends Controller { take: limit, }); - let income = 0; - let expenses = 0; - let netProfit = 0; - - record.forEach((v) => { + const data = record.map((v) => { const originalPrice = v.product.serviceCharge; const productExpenses = precisionRound( originalPrice + (v.product.serviceChargeVatIncluded ? 0 : originalPrice * VAT_DEFAULT), ); const finalPrice = v.pricePerUnit * v.amount * (1 + config.vat); - income += finalPrice; - expenses += productExpenses; - netProfit += finalPrice - productExpenses; + return v.requestWork.map((w) => { + const creditNote = w.creditNote; + const roundCount = v.work?.productOnWork.find((p) => p.productId)?.stepCount || 1; + const successCount = w.stepStatus.filter( + (s) => s.workStatus !== RequestWorkStatus.Canceled, + ).length; + + const income = creditNote + ? precisionRound(productExpenses * successCount) + : precisionRound(finalPrice); + const expenses = creditNote + ? precisionRound(productExpenses * successCount) + : precisionRound(productExpenses * roundCount); + const netProfit = creditNote ? 0 : precisionRound(finalPrice - expenses); + + return { + income, + expenses, + netProfit, + }; + }); }); - return { - income: precisionRound(income), - expenses: precisionRound(expenses), - netProfit: precisionRound(netProfit), - }; + return data.flat().reduce( + (a, c) => { + a.income += c.income; + a.expenses += c.expenses; + a.netProfit += c.netProfit; + return a; + }, + { income: 0, expenses: 0, netProfit: 0 }, + ); } }