From 60791142172468964678940043ee89b207f2c77f Mon Sep 17 00:00:00 2001 From: Thomas Heartman Date: Fri, 24 Jan 2025 14:42:27 +0100 Subject: [PATCH] chore(1-3293): add new method for monthly aggregate of traffic data --- .../traffic-data-usage-store.ts | 21 ++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/src/lib/features/traffic-data-usage/traffic-data-usage-store.ts b/src/lib/features/traffic-data-usage/traffic-data-usage-store.ts index bcdde3bf84..7b1bb8ac10 100644 --- a/src/lib/features/traffic-data-usage/traffic-data-usage-store.ts +++ b/src/lib/features/traffic-data-usage/traffic-data-usage-store.ts @@ -1,4 +1,4 @@ -import { endOfMonth, startOfMonth } from 'date-fns'; +import { endOfMonth, startOfMonth, subMonths } from 'date-fns'; import type { Db } from '../../db/db'; import type { Logger, LogProvider } from '../../logger'; import type { @@ -112,8 +112,9 @@ export class TrafficDataUsageStore implements ITrafficDataUsageStore { ); } - async getTrafficDataForMonthRange( - monthsBack: number, + async getMonthlyTrafficDataUsageForPeriod( + from: Date, + to: Date, ): Promise { const rows = await this.db(TABLE) .select( @@ -122,10 +123,8 @@ export class TrafficDataUsageStore implements ITrafficDataUsageStore { this.db.raw(`to_char(day, 'YYYY-MM') AS month`), this.db.raw(`SUM(count) AS count`), ) - .whereRaw( - `day >= date_trunc('month', CURRENT_DATE) - make_interval(months := ?)`, - [monthsBack], - ) + .where('day', '>=', from) + .andWhere('day', '<=', to) .groupBy([ 'traffic_group', this.db.raw(`to_char(day, 'YYYY-MM')`), @@ -144,4 +143,12 @@ export class TrafficDataUsageStore implements ITrafficDataUsageStore { }), ); } + + async getTrafficDataForMonthRange( + monthsBack: number, + ): Promise { + const to = endOfMonth(new Date()); + const from = startOfMonth(subMonths(to, monthsBack)); + return this.getMonthlyTrafficDataUsageForPeriod(from, to); + } }