import { Injectable, HttpException, HttpStatus } from '@nestjs/common'; import { Repository } from 'typeorm'; import { InjectRepository } from '@nestjs/typeorm'; import { TaskEntity } from './task.entity'; import { CreateTaskDTO, EditTaskDTO } from './task.dto'; import { FactionEntity } from '../faction/faction.entity'; import { Game_PersonEntity } from '../game/game.entity'; import { NotificationGateway } from '../notifications/notifications.gateway'; @Injectable() export class TaskService { constructor( @InjectRepository(TaskEntity) private taskRepository: Repository<TaskEntity>, @InjectRepository(FactionEntity) private factionRepository: Repository<FactionEntity>, @InjectRepository(Game_PersonEntity) private gamePersonRepository: Repository<Game_PersonEntity>, private notificationGateway: NotificationGateway, ) {} async newTask(task: CreateTaskDTO) { // check if is not null, check that the faction exists in the game if ( task.faction != null && !(await this.factionRepository.findOne({ factionId: task.faction.toString(), game: task.taskGame, })) ) { throw new HttpException('Faction not found', HttpStatus.BAD_REQUEST); } const createdTask = await this.taskRepository.create(task); await this.taskRepository.insert(createdTask); // notify subscribers about a new task // if faction was set it notifies only faction members, else everyone this.notificationGateway.server.emit( task.faction != null ? task.faction.toString() : 'global', 'new task', ); return { message: 'Task added', }; } async editTask(data: EditTaskDTO) { const task = await this.taskRepository.findOne(data.taskId); // checks if task is already closed if (!task.taskIsActive) { throw new HttpException('Task is not active', HttpStatus.BAD_REQUEST); } // checks if faction is valid if ( !(await this.factionRepository.findOne({ factionId: data.taskWinner.toString(), game: data.taskGame, })) ) { throw new HttpException('Faction not found', HttpStatus.BAD_REQUEST); } task.taskWinner = data.taskWinner; task.taskIsActive = false; await this.taskRepository.save(task); return { message: 'Task updated and closed', }; } async fetchTasks(user, taskGame) { const gamePerson = await this.gamePersonRepository.findOne({ where: { person: user, game: taskGame, }, relations: ['faction'], }); if (gamePerson.role == 'admin') { return await this.taskRepository.find({ where: { taskGame: taskGame }, relations: ['faction'], }); } else { return await this.taskRepository.find({ relations: ['faction'], where: [ { taskGame: taskGame, faction: gamePerson.faction.factionId, taskIsActive: true, }, { taskGame: taskGame, faction: null, taskIsActive: true, }, ], }); } } }