Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(bulk): correct batch terminal status on cancel and stop-on-error

rmyndharis7f4b858a1c53
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ffcb7a747..ddf6c6776 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,18 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+## [Unreleased]
+
+### Fixed
+
+- **Bulk-message batch status is now correct on cancel and stop-on-error.** A cancelled batch could be
+ silently reverted to `PROCESSING` (the final save overwrote the `CANCELLED` status with the stale
+ in-memory one), and a `stopOnError` abort was reported as `COMPLETED` whenever at least one message had
+ already been sent. The terminal status is now re-derived (cancelled → `CANCELLED` with reconciled
+ counters; stop-on-error → `FAILED`; otherwise `COMPLETED`/`FAILED`).
+- Bulk-message item `type` is now validated against the allowed set (`text`/`image`/`video`/`audio`/`document`)
+ with `@IsIn`, so an invalid type is rejected up front instead of failing mid-send.
+
## [0.2.8] - 2026-06-17
The engine-pluggability release: the whatsapp-web.js delivery-ack, message-type, and JID specifics are
diff --git a/src/modules/message/bulk-message.service.spec.ts b/src/modules/message/bulk-message.service.spec.ts
index 1633ba4e5..ce579afb0 100644
--- a/src/modules/message/bulk-message.service.spec.ts
+++ b/src/modules/message/bulk-message.service.spec.ts
@@ -1,9 +1,33 @@
import { Test, TestingModule } from '@nestjs/testing';
import { getRepositoryToken } from '@nestjs/typeorm';
-import { BulkMessageService } from './bulk-message.service';
+import { BulkMessageService, resolveFinalBatchStatus } from './bulk-message.service';
import { MessageBatch, BatchStatus } from './entities/message-batch.entity';
import { SessionService } from '../session/session.service';
+/** Regression lock for the terminal-status decision (cancel-clobber + stopOnError overwrite bugs). */
+describe('resolveFinalBatchStatus', () => {
+ it('CANCELLED wins even when messages were sent/failed (no clobber back to PROCESSING/COMPLETED)', () => {
+ expect(resolveFinalBatchStatus(true, false, { sent: 3, failed: 1 })).toBe(BatchStatus.CANCELLED);
+ });
+
+ it('cancellation takes precedence over stop-on-error', () => {
+ expect(resolveFinalBatchStatus(true, true, { sent: 0, failed: 1 })).toBe(BatchStatus.CANCELLED);
+ });
+
+ it('stopOnError → FAILED even when some messages already sent (not COMPLETED)', () => {
+ expect(resolveFinalBatchStatus(false, true, { sent: 5, failed: 1 })).toBe(BatchStatus.FAILED);
+ });
+
+ it('all attempts failed → FAILED', () => {
+ expect(resolveFinalBatchStatus(false, false, { sent: 0, failed: 4 })).toBe(BatchStatus.FAILED);
+ });
+
+ it('some sent (with or without failures) → COMPLETED', () => {
+ expect(resolveFinalBatchStatus(false, false, { sent: 4, failed: 0 })).toBe(BatchStatus.COMPLETED);
+ expect(resolveFinalBatchStatus(false, false, { sent: 3, failed: 1 })).toBe(BatchStatus.COMPLETED);
+ });
+});
+
/** Regression lock: orphaned (restart-interrupted) PROCESSING batches are transitioned. */
describe('BulkMessageService.onApplicationBootstrap', () => {
let service: BulkMessageService;
diff --git a/src/modules/message/bulk-message.service.ts b/src/modules/message/bulk-message.service.ts
index 29e80bd32..103cf11b9 100644
--- a/src/modules/message/bulk-message.service.ts
+++ b/src/modules/message/bulk-message.service.ts
@@ -23,6 +23,23 @@ interface BulkMessageContent {
document?: { url?: string; base64?: string; mimetype?: string; filename?: string };
}
+/**
+ * Resolve a batch's terminal status, in precedence order:
+ * - cancelled (cancelBatch flipped the flag) → CANCELLED. Must win over the in-memory PROCESSING
+ * status set at the start of processBatch, which would otherwise be saved back over the cancellation.
+ * - stopped on the first error (stopOnError) → FAILED, even if some messages were already sent.
+ * - otherwise → COMPLETED, or FAILED only when every attempt failed.
+ */
+export function resolveFinalBatchStatus(
+ cancelled: boolean,
+ stoppedOnError: boolean,
+ progress: Pick<BatchProgress, 'sent' | 'failed'>,
+): BatchStatus {
+ if (cancelled) return BatchStatus.CANCELLED;
+ if (stoppedOnError) return BatchStatus.FAILED;
+ return progress.failed > 0 && progress.sent === 0 ? BatchStatus.FAILED : BatchStatus.COMPLETED;
+}
+
@Injectable()
export class BulkMessageService implements OnApplicationBootstrap {
private readonly logger = new Logger(BulkMessageService.name);
@@ -164,6 +181,7 @@ export class BulkMessageService implements OnApplicationBootstrap {
}
const results: BatchMessageResult[] = batch.results || [];
+ let stoppedOnError = false;
for (let i = batch.currentIndex; i < batch.messages.length; i++) {
// Check for cancellation
@@ -205,6 +223,7 @@ export class BulkMessageService implements OnApplicationBootstrap {
if (batch.options.stopOnError) {
batch.status = BatchStatus.FAILED;
+ stoppedOnError = true;
results.push(result);
break;
}
@@ -226,10 +245,14 @@ export class BulkMessageService implements OnApplicationBootstrap {
}
}
- // Final update
- if (this.processingBatches.get(batch.id)) {
- batch.status =
- batch.progress.failed > 0 && batch.progress.sent === 0 ? BatchStatus.FAILED : BatchStatus.COMPLETED;
+ // Final update. NOTE: `batch` still holds the in-memory PROCESSING status from the start, so a
+ // cancellation persisted by cancelBatch would be overwritten if we saved without re-deriving it.
+ const cancelled = !this.processingBatches.get(batch.id);
+ batch.status = resolveFinalBatchStatus(cancelled, stoppedOnError, batch.progress);
+ if (cancelled) {
+ // Reconcile the counters the same way cancelBatch does, so the persisted state is consistent.
+ batch.progress.cancelled = batch.progress.pending;
+ batch.progress.pending = 0;
}
batch.completedAt = new Date();
batch.results = results;
diff --git a/src/modules/message/dto/bulk-message.dto.ts b/src/modules/message/dto/bulk-message.dto.ts
index 1fe8f68cc..76a062cc8 100644
--- a/src/modules/message/dto/bulk-message.dto.ts
+++ b/src/modules/message/dto/bulk-message.dto.ts
@@ -1,6 +1,7 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import {
IsString,
+ IsIn,
IsArray,
IsOptional,
IsNumber,
@@ -46,7 +47,7 @@ class BulkMessageItemDto {
chatId: string;
@ApiProperty({ description: 'Message type', enum: ['text', 'image', 'video', 'audio', 'document'] })
- @IsString()
+ @IsIn(['text', 'image', 'video', 'audio', 'document'])
type: 'text' | 'image' | 'video' | 'audio' | 'document';
@ApiProperty({ description: 'Message content based on type' })