71 lines
2.2 KiB
TypeScript
71 lines
2.2 KiB
TypeScript
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<BotTask>,
|
|
) {}
|
|
|
|
async createTask(data: Partial<BotTask>): Promise<BotTask> {
|
|
const task = this.taskRepo.create(data);
|
|
return this.taskRepo.save(task);
|
|
}
|
|
|
|
async findAll(tenantId: string): Promise<BotTask[]> {
|
|
return this.taskRepo.find({
|
|
where: { tenant_id: tenantId },
|
|
order: { created_at: 'DESC' },
|
|
take: 100,
|
|
});
|
|
}
|
|
|
|
async findOne(id: string): Promise<BotTask | null> {
|
|
return this.taskRepo.findOne({ where: { id } });
|
|
}
|
|
|
|
async updateStatus(id: string, status: BotTaskStatus, result?: Record<string, any>): Promise<BotTask> {
|
|
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<BotTaskStatus, number>;
|
|
by_platform: Record<BotPlatform, number>;
|
|
}> {
|
|
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<BotTask[]> {
|
|
return this.taskRepo.find({
|
|
where: { status: 'pending' },
|
|
order: { created_at: 'ASC' },
|
|
take: 50,
|
|
});
|
|
}
|
|
|
|
async cancelTask(id: string): Promise<BotTask> {
|
|
return this.updateStatus(id, 'cancelled');
|
|
}
|
|
}
|