diff --git a/src/controllers/00-stats-controller.ts b/src/controllers/00-stats-controller.ts index 923696f..2059941 100644 --- a/src/controllers/00-stats-controller.ts +++ b/src/controllers/00-stats-controller.ts @@ -1,4 +1,11 @@ -import { QuotationStatus, RequestWorkStatus } from "@prisma/client"; +import { + Customer, + CustomerBranch, + ProductGroup, + QuotationStatus, + RequestWorkStatus, + User, +} from "@prisma/client"; import { Controller, Get, Query, Request, Route, Security } from "tsoa"; import prisma from "../db"; import { createPermCondition } from "../services/permission"; @@ -28,7 +35,6 @@ export class StatsController extends Controller { registeredBranch: { OR: permissionCondCompany(req.user) }, createdAt: { gte: startDate, lte: endDate }, }, - orderBy: { createdAt: 'desc' }, take: limit, }); @@ -65,7 +71,6 @@ export class StatsController extends Controller { }, createdAt: { gte: startDate, lte: endDate }, }, - orderBy: { createdAt: 'desc' }, take: limit, }); @@ -100,7 +105,9 @@ export class StatsController extends Controller { }, createdAt: { gte: startDate, lte: endDate }, }, - orderBy: { createdAt: 'desc' }, + orderBy: { + createdAt: 'desc' + } take: limit, }); @@ -211,5 +218,78 @@ export class StatsController extends Controller { @Query() limit?: number, @Query() startDate?: Date, @Query() endDate?: Date, - ) {} + ) { + const list = await prisma.quotationProductServiceList.findMany({ + include: { + quotation: { + include: { + createdBy: true, + customerBranch: { + include: { customer: true }, + }, + }, + }, + product: { + include: { + productGroup: true, + }, + }, + }, + where: { + quotation: { + isDebitNote: false, + registeredBranch: { OR: permissionCondCompany(req.user) }, + createdAt: { gte: startDate, lte: endDate }, + quotationStatus: { + in: [ + QuotationStatus.PaymentInProcess, + QuotationStatus.PaymentSuccess, + QuotationStatus.ProcessComplete, + ], + }, + }, + }, + take: limit, + }); + + return list.reduce<{ + byProductGroup: (ProductGroup & { _count: number })[]; + bySale: (User & { _count: number })[]; + byCustomer: ((CustomerBranch & { customer: Customer }) & { _count: number })[]; + }>( + (a, c) => { + { + const found = a.byProductGroup.find((v) => v.id === c.product.productGroupId); + if (found) { + found._count++; + } else { + a.byProductGroup.push({ ...c.product.productGroup, _count: 1 }); + } + } + + { + const found = a.bySale.find((v) => v.id === c.quotation.createdByUserId); + if (found) { + found._count++; + } else { + if (c.quotation.createdBy) { + a.bySale.push({ ...c.quotation.createdBy, _count: 1 }); + } + } + } + + { + const found = a.byCustomer.find((v) => v.id === c.quotation.customerBranchId); + if (found) { + found._count++; + } else { + a.byCustomer.push({ ...c.quotation.customerBranch, _count: 1 }); + } + } + + return a; + }, + { byProductGroup: [], bySale: [], byCustomer: [] }, + ); + } }