Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(stats): stop naming a group after one of its members
Yudhi Armyndharis898202b153c3
diff --git a/docs/05-database-design.md b/docs/05-database-design.mdindex 49a8eb14d..9b239b974 100644--- a/docs/05-database-design.md+++ b/docs/05-database-design.md@@ -488,7 +488,7 @@ CREATE TABLE messages ("sessionId" UUID NOT NULL,"waMessageId" VARCHAR, -- nullable; transient outgoing rows have none yet"chatId" VARCHAR NOT NULL,- "chatName" VARCHAR, -- nullable; contact pushName / group name when known+ "chatName" VARCHAR, -- nullable; inbound sender pushName (the member, in a group)author VARCHAR, -- nullable; participant JID for a group message ("from" is the group)"from" VARCHAR NOT NULL,"to" VARCHAR NOT NULL,diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 50332cbd0..9ea9c31e0 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -5150,7 +5150,7 @@ Get message statistics over a period: time series, counts by type, by session, a}```-Notes: raw handler return. `timeSeries.timestamp` is a DB-formatted bucket string — hourly `YYYY-MM-DD HH:00:00` for `24h`, daily `YYYY-MM-DD` for `7d`/`30d` — sorted ascending. `byType` keys are message-type strings (a null type becomes `unknown`). `bySession.name` is `Unknown` when the session is not found. `topChats` is the top 10 by `messageCount` DESC. All counts are numbers.+Notes: raw handler return. `timeSeries.timestamp` is a DB-formatted bucket string — hourly `YYYY-MM-DD HH:00:00` for `24h`, daily `YYYY-MM-DD` for `7d`/`30d` — sorted ascending. `byType` keys are message-type strings (a null type becomes `unknown`). `bySession.name` is `Unknown` when the session is not found. `topChats` is the top 10 by `messageCount` DESC; each `chatName` is the contact's push name for a 1:1 chat, taken from its incoming messages, and `null` for a group or when none is known. All counts are numbers.**Errors:** `400` — `period` not in the enum, or any non-whitelisted query field (strict `whitelist` + `forbidNonWhitelisted`) · `401` — missing/invalid API key · `403` — role below `ADMIN`, or the key is session-restricted.@@ -5180,7 +5180,7 @@ Get statistics for a single session: identity, message counts, top chats, and 24}```-Notes: raw handler return. `session.status` is the `SessionStatus` enum value. `messages.sent`/`received` are all-time outgoing/incoming COUNTs; `today` is the total message count since local midnight; `failed` is the `FAILED`-status count. `topChats` is the top 10 by count DESC, with `lastActive` = `MAX(createdAt)` as a DB-native datetime string. `hourlyActivity` always has 24 entries (hour `0..23`), missing hours zero-filled, computed over the last 24 h.+Notes: raw handler return. `session.status` is the `SessionStatus` enum value. `messages.sent`/`received` are all-time outgoing/incoming COUNTs; `today` is the total message count since local midnight; `failed` is the `FAILED`-status count. `topChats` is the top 10 by count DESC, with `lastActive` = `MAX(createdAt)` as a DB-native datetime string and `chatName` as in `GET /api/stats/messages`. `hourlyActivity` always has 24 entries (hour `0..23`), missing hours zero-filled, computed over the last 24 h.**Errors:** `401` — missing/invalid API key, or the key is not scoped to this session · `404` — session not found (`Session not found`).diff --git a/openapi.json b/openapi.jsonindex 038338e97..e5106dca9 100644--- a/openapi.json+++ b/openapi.json@@ -15917,7 +15917,7 @@"chatName": {"type": "string","nullable": true,- "description": "Null when no name is known for the chat."+ "description": "The contact's push name for a 1:1 chat, taken from its incoming messages. Null for a group chat, or when no name is known."},"messageCount": {"type": "number",@@ -16030,7 +16030,7 @@"chatName": {"type": "string","nullable": true,- "description": "Null when no name is known for the chat."+ "description": "The contact's push name for a 1:1 chat, taken from its incoming messages. Null for a group chat, or when no name is known."},"count": {"type": "number",diff --git a/src/modules/message/entities/message.entity.ts b/src/modules/message/entities/message.entity.tsindex f34c2338f..1f2773b29 100644--- a/src/modules/message/entities/message.entity.ts+++ b/src/modules/message/entities/message.entity.ts@@ -52,7 +52,8 @@ 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. */+ /** The sender's contact name (pushName) as the engine reported it: in a group that is the member, not+ * the group. Null on legacy rows and on rows that carried no contact. */@Column({ nullable: true })chatName?: string;diff --git a/src/modules/stats/dto/stats-response.dto.ts b/src/modules/stats/dto/stats-response.dto.tsindex 29452047b..2f1f55439 100644--- a/src/modules/stats/dto/stats-response.dto.ts+++ b/src/modules/stats/dto/stats-response.dto.ts@@ -63,11 +63,15 @@ export class StatsBySessionDto {@ApiProperty({ example: 34 }) received!: number;}+const CHAT_NAME_DESCRIPTION =+ "The contact's push name for a 1:1 chat, taken from its incoming messages. Null for a group chat, " ++ 'or when no name is known.';+export class StatsTopChatDto {@ApiProperty({ example: '[email protected]' })chatId!: string;- @ApiProperty({ type: String, nullable: true, description: 'Null when no name is known for the chat.' })+ @ApiProperty({ type: String, nullable: true, description: CHAT_NAME_DESCRIPTION })chatName!: string | null;@ApiProperty({ example: 42 }) messageCount!: number;@@ -108,7 +112,7 @@ export class SessionStatsTopChatDto {@ApiProperty({ example: '[email protected]' })chatId!: string;- @ApiProperty({ type: String, nullable: true, description: 'Null when no name is known for the chat.' })+ @ApiProperty({ type: String, nullable: true, description: CHAT_NAME_DESCRIPTION })chatName!: string | null;@ApiProperty({ example: 42 }) count!: number;diff --git a/src/modules/stats/stats.service.spec.ts b/src/modules/stats/stats.service.spec.tsindex 48c94d9c7..c5693518a 100644--- a/src/modules/stats/stats.service.spec.ts+++ b/src/modules/stats/stats.service.spec.ts@@ -101,6 +101,26 @@ describe('StatsService time-series + hourly activity on SQLite (end-to-end regreexpect(chat?.chatName).toBe('Alice');});+ // chatName holds the SENDER's push name, so a group's MAX over it named the group after whichever member+ // sorts last, and an outgoing row would carry the operator's own name. Only a 1:1 chat's inbound rows name it.+ it('topChats names a 1:1 chat from its inbound rows only and leaves a group unnamed, in both queries', async () => {+ await ds+ .getRepository(Session)+ .save(ds.getRepository(Session).create({ id: 's1', name: 'n', status: SessionStatus.READY, config: {} }));+ await seedMessage({ chatId: '[email protected]', chatName: 'Andi', direction: MessageDirection.INCOMING });+ await seedMessage({ chatId: '[email protected]', chatName: 'Zul', direction: MessageDirection.INCOMING });+ await seedMessage({ chatId: '[email protected]', chatName: 'Bob', direction: MessageDirection.INCOMING });+ await seedMessage({ chatId: '[email protected]', chatName: 'Zz Operator', direction: MessageDirection.OUTGOING });++ const overall = await service.getMessageStats('24h');+ expect(overall.topChats.find(c => c.chatId === '[email protected]')?.chatName).toBeNull();+ expect(overall.topChats.find(c => c.chatId === '[email protected]')?.chatName).toBe('Bob');++ const perSession = await service.getSessionStats('s1');+ expect(perSession.topChats.find(c => c.chatId === '[email protected]')?.chatName).toBeNull();+ expect(perSession.topChats.find(c => c.chatId === '[email protected]')?.chatName).toBe('Bob');+ });+it('getMessageStats byType excludes content-less system/event rows (no body AND no metadata)', async () => {await ds.getRepository(Session)diff --git a/src/modules/stats/stats.service.ts b/src/modules/stats/stats.service.tsindex 31e8a4906..996d1e9a8 100644--- a/src/modules/stats/stats.service.ts+++ b/src/modules/stats/stats.service.ts@@ -3,7 +3,7 @@ import { InjectRepository } from '@nestjs/typeorm';import { ConfigService } from '@nestjs/config';import { Repository } from 'typeorm';import { Session, SessionStatus } from '../session/entities/session.entity';-import { Message, MessageStatus } from '../message/entities/message.entity';+import { Message, MessageDirection, MessageStatus } from '../message/entities/message.entity';import { CacheService } from '../../common/cache';/**@@ -42,6 +42,13 @@ export function maxCreatedAtSql(dbType: string): string {: `strftime('%Y-%m-%d %H:%M:%S', MAX(m.createdAt))`;}+/**+ * SQL for a top chat's label. `chatName` holds the SENDER's push name, not the chat's: MAX over a group's+ * rows named the group after whichever member sorts last. Only a 1:1 chat's inbound rows carry the name+ * of the chat itself, so groups get null and the dashboard falls back to the chat id.+ */+const CHAT_LABEL_SQL = `MAX(CASE WHEN m.direction = '${MessageDirection.INCOMING}' AND m.chatId NOT LIKE '%@g.us' THEN m.chatName END)`;+export interface OverviewStats {sessions: {active: number;@@ -251,7 +258,7 @@ export class StatsService {.createQueryBuilder('m').select('m.chatId', 'chatId').addSelect('COUNT(*)', 'messageCount')- .addSelect('MAX(m.chatName)', 'chatName')+ .addSelect(CHAT_LABEL_SQL, 'chatName').where('m.createdAt >= :since', { since }).groupBy('m.chatId')// Order by the aggregate expression, not the "messageCount" alias: Postgres folds an unquoted@@ -323,7 +330,7 @@ export class StatsService {.select('m.chatId', 'chatId').addSelect('COUNT(*)', 'count').addSelect(maxCreatedAtSql(this.dataDbType), 'lastActive')- .addSelect('MAX(m.chatName)', 'chatName')+ .addSelect(CHAT_LABEL_SQL, 'chatName').where('m.sessionId = :sessionId', { sessionId }).groupBy('m.chatId').orderBy('count', 'DESC')