Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(stats): portable date-bucket SQL so analytics work on a Postgres data DB (#322)
Yudhi Armyndharisb22f80fc6208
diff --git a/src/modules/stats/stats.service.spec.ts b/src/modules/stats/stats.service.spec.tsnew file mode 100644index 000000000..400548f20--- /dev/null+++ b/src/modules/stats/stats.service.spec.ts@@ -0,0 +1,98 @@+import { DataSource } from 'typeorm';+import { StatsService, timeSeriesTimestampSql, hourBucketSql } from './stats.service';+import { Session, SessionStatus } from '../session/entities/session.entity';+import { Message, MessageDirection, MessageStatus } from '../message/entities/message.entity';++// F-06 — these two analytics queries used SQLite-only strftime(), which 500s on a Postgres+// data DB. The dialect-correct SQL is generated by these pure helpers; the Postgres branch is+// unit-tested here (a live Postgres isn't available in CI), and the SQLite path is exercised+// end-to-end below so the fix can't regress the working backend.+describe('stats SQL dialect helpers (F-06)', () => {+ it('uses strftime on sqlite (hour + day buckets)', () => {+ expect(timeSeriesTimestampSql('sqlite', 'hour')).toBe(`strftime('%Y-%m-%d %H:00:00', m.createdAt)`);+ expect(timeSeriesTimestampSql('sqlite', 'day')).toBe(`strftime('%Y-%m-%d', m.createdAt)`);+ expect(hourBucketSql('sqlite')).toBe(`CAST(strftime('%H', m.createdAt) AS INTEGER)`);+ });++ it('uses to_char/extract with a quoted createdAt on postgres', () => {+ expect(timeSeriesTimestampSql('postgres', 'hour')).toBe(`to_char(m."createdAt", 'YYYY-MM-DD HH24:00:00')`);+ expect(timeSeriesTimestampSql('postgres', 'day')).toBe(`to_char(m."createdAt", 'YYYY-MM-DD')`);+ expect(hourBucketSql('postgres')).toBe(`CAST(EXTRACT(HOUR FROM m."createdAt") AS INTEGER)`);+ });+});++describe('StatsService time-series + hourly activity on SQLite (end-to-end regression)', () => {+ let ds: DataSource;+ let service: StatsService;++ beforeEach(async () => {+ ds = new DataSource({+ type: 'sqlite',+ database: ':memory:',+ entities: [Session, Message],+ synchronize: true,+ });+ await ds.initialize();+ const cache = { setSessionsStats: jest.fn() };+ service = new StatsService(ds.getRepository(Session), ds.getRepository(Message), cache as never);+ });++ afterEach(async () => {+ await ds.destroy();+ });++ const seedMessage = (over: Partial<Message>) =>+ ds.getRepository(Message).save(+ ds.getRepository(Message).create({+ sessionId: 's1',+ chatId: 'c1',+ from: 'a',+ to: 'b',+ type: 'text',+ direction: MessageDirection.OUTGOING,+ status: MessageStatus.SENT,+ ...over,+ }),+ );++ it('getMessageStats returns a populated time series without throwing', async () => {+ await ds+ .getRepository(Session)+ .save(ds.getRepository(Session).create({ id: 's1', name: 'n', status: SessionStatus.READY, config: {} }));+ await seedMessage({ direction: MessageDirection.OUTGOING });+ await seedMessage({ direction: MessageDirection.INCOMING });++ const stats = await service.getMessageStats('24h');+ expect(Array.isArray(stats.timeSeries)).toBe(true);+ expect(stats.timeSeries.length).toBeGreaterThanOrEqual(1);+ const totals = stats.timeSeries.reduce(+ (acc, p) => ({ sent: acc.sent + p.sent, received: acc.received + p.received }),+ {+ sent: 0,+ received: 0,+ },+ );+ expect(totals.sent).toBe(1);+ expect(totals.received).toBe(1);+ // The hour bucket must be the zero-padded chronological label strftime produces.+ expect(stats.timeSeries[0].timestamp).toMatch(/^\d{4}-\d{2}-\d{2} \d{2}:00:00$/);+ });++ it('getSessionStats returns 24 hourly buckets with the right counts', async () => {+ await ds+ .getRepository(Session)+ .save(ds.getRepository(Session).create({ id: 's1', name: 'n', status: SessionStatus.READY, config: {} }));+ await seedMessage({ direction: MessageDirection.OUTGOING });+ await seedMessage({ direction: MessageDirection.OUTGOING });+ await seedMessage({ direction: MessageDirection.INCOMING });++ const stats = await service.getSessionStats('s1');+ expect(stats.hourlyActivity).toHaveLength(24);+ const totals = stats.hourlyActivity.reduce(+ (acc, h) => ({ sent: acc.sent + h.sent, received: acc.received + h.received }),+ { sent: 0, received: 0 },+ );+ expect(totals.sent).toBe(2);+ expect(totals.received).toBe(1);+ });+});diff --git a/src/modules/stats/stats.service.ts b/src/modules/stats/stats.service.tsindex 4c12de6fb..a575865bc 100644--- a/src/modules/stats/stats.service.ts+++ b/src/modules/stats/stats.service.ts@@ -5,6 +5,29 @@ import { Session, SessionStatus } from '../session/entities/session.entity';import { Message, MessageStatus } from '../message/entities/message.entity';import { CacheService } from '../../common/cache';+/**+ * SQL for the time-series timestamp bucket, per DB dialect. SQLite has strftime(); Postgres has+ * neither strftime nor a case-insensitive bare `m.createdAt` (unquoted it folds to lowercase and+ * misses the quoted "createdAt" column) — so it needs to_char() with a quoted column. The hour+ * format yields an identical zero-padded, chronologically-sortable label on both engines, so the+ * GROUP BY/ORDER BY on the alias and the downstream map() are unchanged.+ */+export function timeSeriesTimestampSql(dbType: string, interval: 'hour' | 'day'): string {+ if (dbType === 'postgres') {+ const fmt = interval === 'hour' ? 'YYYY-MM-DD HH24:00:00' : 'YYYY-MM-DD';+ return `to_char(m."createdAt", '${fmt}')`;+ }+ const fmt = interval === 'hour' ? '%Y-%m-%d %H:00:00' : '%Y-%m-%d';+ return `strftime('${fmt}', m.createdAt)`;+}++/** SQL for the integer hour-of-day (0-23) bucket, per DB dialect. */+export function hourBucketSql(dbType: string): string {+ return dbType === 'postgres'+ ? `CAST(EXTRACT(HOUR FROM m."createdAt") AS INTEGER)`+ : `CAST(strftime('%H', m.createdAt) AS INTEGER)`;+}+export interface OverviewStats {sessions: {active: number;@@ -49,6 +72,11 @@ export class StatsService {private readonly cacheService: CacheService,) {}+ /** The data-connection dialect ('sqlite' | 'postgres'), used to pick portable date SQL. */+ private get dataDbType(): string {+ return this.messageRepo.manager.connection.options.type;+ }+async getOverview(): Promise<OverviewStats> {// Get session statsconst sessions = await this.sessionRepo.find();@@ -256,12 +284,9 @@ export class StatsService {}private async getTimeSeries(since: Date, interval: 'hour' | 'day'): Promise<TimeSeriesPoint[]> {- // SQLite-compatible time series query- const formatStr = interval === 'hour' ? '%Y-%m-%d %H:00:00' : '%Y-%m-%d';-const raw = await this.messageRepo.createQueryBuilder('m')- .select(`strftime('${formatStr}', m.createdAt)`, 'timestamp')+ .select(timeSeriesTimestampSql(this.dataDbType, interval), 'timestamp').addSelect(`SUM(CASE WHEN m.direction = 'outgoing' THEN 1 ELSE 0 END)`, 'sent').addSelect(`SUM(CASE WHEN m.direction = 'incoming' THEN 1 ELSE 0 END)`, 'received').where('m.createdAt >= :since', { since })@@ -281,7 +306,7 @@ export class StatsService {const raw = await this.messageRepo.createQueryBuilder('m')- .select(`CAST(strftime('%H', m.createdAt) AS INTEGER)`, 'hour')+ .select(hourBucketSql(this.dataDbType), 'hour').addSelect(`SUM(CASE WHEN m.direction = 'outgoing' THEN 1 ELSE 0 END)`, 'sent').addSelect(`SUM(CASE WHEN m.direction = 'incoming' THEN 1 ELSE 0 END)`, 'received').where('m.sessionId = :sessionId', { sessionId })