import { Injectable, Logger } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Repository } from 'typeorm'; import { BotTask, BotPlatform, BotTaskType, BotTaskStatus } from './entities/bot-task.entity'; @Injectable() export class BotService { private readonly logger = new Logger(BotService.name); constructor( @InjectRepository(BotTask) private readonly taskRepo: Repository, ) {} async createTask(data: Partial): Promise { const task = this.taskRepo.create(data); return this.taskRepo.save(task); } async findAll(tenantId: string): Promise { return this.taskRepo.find({ where: { tenant_id: tenantId }, order: { created_at: 'DESC' }, take: 100, }); } async findOne(id: string): Promise { return this.taskRepo.findOne({ where: { id } }); } async updateStatus(id: string, status: BotTaskStatus, result?: Record): Promise { const update: any = { status }; if (status === 'running') update.started_at = new Date(); if (status === 'completed' || status === 'failed') update.completed_at = new Date(); if (result) update.result = result; await this.taskRepo.update(id, update); return this.taskRepo.findOneOrFail({ where: { id } }); } async getStats(tenantId: string): Promise<{ total: number; by_status: Record; by_platform: Record; }> { const tasks = await this.taskRepo.find({ where: { tenant_id: tenantId } }); const by_status: any = { pending: 0, running: 0, completed: 0, failed: 0, cancelled: 0 }; const by_platform: any = { facebook: 0, instagram: 0, telegram: 0, whatsapp: 0 }; for (const task of tasks) { by_status[task.status]++; by_platform[task.platform]++; } return { total: tasks.length, by_status, by_platform }; } async getDueTasks(): Promise { return this.taskRepo.find({ where: { status: 'pending' }, order: { created_at: 'ASC' }, take: 50, }); } async cancelTask(id: string): Promise { return this.updateStatus(id, 'cancelled'); } }