Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(stats): add chat names to top chats and stats endpoints (#572)
Yudhi Armyndharisdd02e51c8e92
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 500497d80..def771191 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Added++- **Stats endpoint now returns chat names in top chats.** The `GET /stats/messages` and `GET /sessions/:id/stats` endpoints include a `chatName` field on each top-chat entry, populated from the contact's pushName or saved name at message time. The dashboard uses it to show readable names instead of raw JIDs. Existing rows start as `NULL` until a new message sets the name. (#558) Thanks @buluma.+### Fixed- **Incoming WhatsApp Business interactive messages no longer arrive with an empty body on the Baileys engine.** Messages sent as interactive/button/template shapes — which businesses use for one-time codes and verification prompts — were saved with `type: "unknown"` and a blank body, dropping the text (e.g. an OTP) entirely. The engine now extracts the display text from `interactiveMessage`, `buttonsMessage`, `templateMessage`, and `interactiveResponseMessage` into the message body and classifies them as `text`, so the content is retrievable over the standard messages API and rendered in the dashboard. (#562)diff --git a/dashboard/src/components/DashboardCharts.tsx b/dashboard/src/components/DashboardCharts.tsxindex 5b4119c66..0f90cf1fc 100644--- a/dashboard/src/components/DashboardCharts.tsx+++ b/dashboard/src/components/DashboardCharts.tsx@@ -73,7 +73,7 @@ export function DashboardCharts() {const byType = Object.entries(data?.byType ?? {}).map(([name, value]) => ({ name, value })).sort((a, b) => b.value - a.value);- const topChats = (data?.topChats ?? []).slice(0, 8).map(c => ({ name: shortChat(c.chatId), count: c.messageCount }));+ const topChats = (data?.topChats ?? []).slice(0, 8).map(c => ({ name: c.chatName || shortChat(c.chatId), count: c.messageCount }));const hasData = timeSeries.length > 0 || byType.length > 0 || topChats.length > 0;return (diff --git a/dashboard/src/services/api.ts b/dashboard/src/services/api.tsindex b4a355033..86bab07a4 100644--- a/dashboard/src/services/api.ts+++ b/dashboard/src/services/api.ts@@ -817,7 +817,7 @@ export interface MessageStats {timeSeries: MessageTimeSeriesPoint[];byType: Record<string, number>;bySession: Array<{ sessionId: string; name: string; sent: number; received: number }>;- topChats: Array<{ chatId: string; messageCount: number }>;+ topChats: Array<{ chatId: string; chatName?: string | null; messageCount: number }>;}export const statsApi = {diff --git a/src/database/migrations/1782000000000-AddMessageChatName.ts b/src/database/migrations/1782000000000-AddMessageChatName.tsnew file mode 100644index 000000000..c321507d0--- /dev/null+++ b/src/database/migrations/1782000000000-AddMessageChatName.ts@@ -0,0 +1,28 @@+import { MigrationInterface, QueryRunner } from 'typeorm';++/**+ * Adds `chatName` column to the `messages` table. This stores the human-readable name for the+ * chat (contact pushName, group name, etc) at the time the message was received/sent, enabling+ * stats endpoints to display readable names instead of raw JIDs.+ *+ * Hand-authored because `synchronize` is off for the `data` connection on PostgreSQL (and optional+ * on SQLite via DATABASE_SYNCHRONIZE=false). Idempotent: checks for column existence first.+ */+export class AddMessageChatName1782000000000 implements MigrationInterface {+ name = 'AddMessageChatName1782000000000';++ public async up(queryRunner: QueryRunner): Promise<void> {+ const table = await queryRunner.getTable('messages');+ const col = table?.findColumnByName('chatName');+ if (col) return; // already added by synchronize or a previous run++ await queryRunner.query(`ALTER TABLE "messages" ADD COLUMN "chatName" varchar NULL`);+ }++ public async down(queryRunner: QueryRunner): Promise<void> {+ const table = await queryRunner.getTable('messages');+ const col = table?.findColumnByName('chatName');+ if (!col) return;+ await queryRunner.query(`ALTER TABLE "messages" DROP COLUMN "chatName"`);+ }+}diff --git a/src/modules/message/entities/message.entity.ts b/src/modules/message/entities/message.entity.tsindex 073a6ffb5..df3425b42 100644--- a/src/modules/message/entities/message.entity.ts+++ b/src/modules/message/entities/message.entity.ts@@ -52,6 +52,10 @@ export class Message {@Column()chatId: string;+ /** Human-readable name for the chat (contact pushName, group name, etc). Populated on save when available — null for legacy rows. */+ @Column({ nullable: true })+ chatName?: string;+@Column()from: string;diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.tsindex 6705cf371..f93aef55a 100644--- a/src/modules/session/session.service.ts+++ b/src/modules/session/session.service.ts@@ -691,10 +691,13 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatmetadata.call = incoming.call;}+ const chatName = incoming.contact?.pushName ?? incoming.contact?.name ?? undefined;+const dbMessage = this.messageRepository.create({sessionId: id,waMessageId: incoming.id,chatId: incoming.chatId,+ chatName,from: incoming.from,to: incoming.to,body: incoming.body,diff --git a/src/modules/stats/stats.service.spec.ts b/src/modules/stats/stats.service.spec.tsindex 5347b1d02..53700982d 100644--- a/src/modules/stats/stats.service.spec.ts+++ b/src/modules/stats/stats.service.spec.ts@@ -86,6 +86,19 @@ describe('StatsService time-series + hourly activity on SQLite (end-to-end regreexpect(stats.timeSeries[0].timestamp).toMatch(/^\d{4}-\d{2}-\d{2} \d{2}:00:00$/);});+ it('getMessageStats topChats surfaces chatName via the MAX aggregate (ignoring null rows)', async () => {+ await ds+ .getRepository(Session)+ .save(ds.getRepository(Session).create({ id: 's1', name: 'n', status: SessionStatus.READY, config: {} }));+ await seedMessage({ chatId: '[email protected]', chatName: 'Alice', direction: MessageDirection.INCOMING });+ await seedMessage({ chatId: '[email protected]', chatName: undefined, direction: MessageDirection.INCOMING });++ const stats = await service.getMessageStats('24h');+ const chat = stats.topChats.find(c => c.chatId === '[email protected]');+ // MAX(m.chatName) across the group returns the non-null name, so a legacy null row can't blank it.+ expect(chat?.chatName).toBe('Alice');+ });+it('time-series query never groups by the bare reserved word `timestamp` (Postgres-safe)', async () => {await ds.getRepository(Session)diff --git a/src/modules/stats/stats.service.ts b/src/modules/stats/stats.service.tsindex ea7f12e42..7dd64639e 100644--- a/src/modules/stats/stats.service.ts+++ b/src/modules/stats/stats.service.ts@@ -65,13 +65,13 @@ export interface MessageStats {timeSeries: TimeSeriesPoint[];byType: Record<string, number>;bySession: Array<{ sessionId: string; name: string; sent: number; received: number }>;- topChats: Array<{ chatId: string; messageCount: number }>;+ topChats: Array<{ chatId: string; chatName: string | null; messageCount: number }>;}export interface SessionStats {session: { id: string; name: string; status: string };messages: { sent: number; received: number; today: number; failed: number };- topChats: Array<{ chatId: string; count: number; lastActive: string }>;+ topChats: Array<{ chatId: string; chatName: string | null; count: number; lastActive: string }>;hourlyActivity: Array<{ hour: number; sent: number; received: number }>;}@@ -208,13 +208,14 @@ export class StatsService {.createQueryBuilder('m').select('m.chatId', 'chatId').addSelect('COUNT(*)', 'messageCount')+ .addSelect('MAX(m.chatName)', 'chatName').where('m.createdAt >= :since', { since }).groupBy('m.chatId')// Order by the aggregate expression, not the "messageCount" alias: Postgres folds an unquoted// ORDER BY messageCount to lowercase and 42703s against the quoted alias (SQLite tolerated it)..orderBy('COUNT(*)', 'DESC').limit(10)- .getRawMany<{ chatId: string; messageCount: string }>();+ .getRawMany<{ chatId: string; messageCount: string; chatName: string | null }>();return {timeSeries,@@ -222,6 +223,7 @@ export class StatsService {bySession,topChats: topChats.map(c => ({chatId: c.chatId,+ chatName: c.chatName ?? null,messageCount: parseInt(c.messageCount),})),};@@ -265,11 +267,12 @@ export class StatsService {.select('m.chatId', 'chatId').addSelect('COUNT(*)', 'count').addSelect(maxCreatedAtSql(this.dataDbType), 'lastActive')+ .addSelect('MAX(m.chatName)', 'chatName').where('m.sessionId = :sessionId', { sessionId }).groupBy('m.chatId').orderBy('count', 'DESC').limit(10)- .getRawMany<{ chatId: string; count: string; lastActive: string }>();+ .getRawMany<{ chatId: string; count: string; lastActive: string; chatName: string | null }>();// Hourly activity (last 24h)const hourlyActivity = await this.getHourlyActivity(sessionId);@@ -279,6 +282,7 @@ export class StatsService {messages: { sent, received, today: todayCount, failed },topChats: topChats.map(c => ({chatId: c.chatId,+ chatName: c.chatName ?? null,count: parseInt(c.count),lastActive: c.lastActive,})),