All files / app/core/task task.service.ts

85.54% Statements 71/83
59.09% Branches 26/44
87.8% Functions 36/41
84.28% Lines 59/70

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178                18x   18x 18x 18x 18x 18x   18x 18x 18x   18x     4x       1x 1x   1x       1x       1x   1x   1x                 1x       2x       2x 2x 1x   1x                   2x         2x 2x 2x 2x     2x           2x 2x 2x 2x                 6x       2x       1x   1x         3x       1x   1x   1x         1x 2x 1x 2x 1x 1x       2x 1x       3x       1x 2x   1x       2x 1x       3x 3x   3x                            
import { inject, Injectable, signal } from "@angular/core";
import { environment } from "../../../environments/environment";
import { TaskCard, TaskForProject, TaskPriority, TaskStatus } from "./task.interfaces";
import { HttpClient, HttpErrorResponse } from "@angular/common/http";
import { catchError, map, Observable, throwError } from "rxjs";
import { ToastService } from "../toast/toast.service";
 
@Injectable({ providedIn: 'root' })
export class TaskService {
 
  private readonly toastService = inject(ToastService);
  private readonly apiBaseUrl = environment.authApiBaseUrl;
  private readonly tasksForProjectSiganl = signal<TaskForProject[]>([]);
  private readonly taskToBlockSignal = signal<TaskCard>({} as TaskCard);
  private readonly showBlockTaskModalSignal = signal<boolean>(false);
 
  readonly tasksForProject = this.tasksForProjectSiganl.asReadonly();
  readonly showBlockTaskModal = this.showBlockTaskModalSignal.asReadonly();
  readonly taskToBlock = this.taskToBlockSignal.asReadonly();
 
  constructor(private http: HttpClient) { }
 
  setShowBlockTaskModal(show: boolean): void {
    this.showBlockTaskModalSignal.set(show);
  }
 
  addTask(projectId: string, newTask: TaskCard): void {
    const updateTask: TaskForProject[] = this.tasksForProjectSiganl().map(p => {
      return p.projectId === projectId ? {...p, tasks: [...p.tasks, newTask]} : p
    })
    this.tasksForProjectSiganl.set(updateTask)
  }
 
  getTaskByProjectsIds(ids: string[]): void {
    this.http.post<TaskCard[]>(this.apiBaseUrl + '/api/v1/task/byprojects', ids).pipe(
      catchError(this.handleError)
    ).subscribe({
      next: (tasks) => {
        const tasksByProject: TaskForProject[] = ids.map(projectId => ({
          projectId,
          tasks: tasks.filter(task => task.projectId === projectId)
        }));
        this.tasksForProjectSiganl.set(tasksByProject);
      },
      error: (err) => {
        console.error('Error fetching tasks:', err)
      },
    });
  }
 
  setTaskToBlock(task: TaskCard): void {
    this.taskToBlockSignal.set(task);
  }
 
  updateTaskStatus(projectId: string, taskId: string, newState: string): void {
    this.http.put<TaskCard>(this.apiBaseUrl + `/api/v1/task/${taskId}/status/${newState}`, {}).pipe(
      catchError(this.handleError)
    ).subscribe({
      next: (respose) => {
        this.updateTaskInSignal(projectId, respose)
        if (newState === 'Completada') {
          this.toastService.success('Tarea marcada como completada');
        } else {
          this.toastService.info(`Tarea actualizada a estado: ${newState}`);
        }
      },
      error: (err) => {
        console.error('Error updating task status:', err);
      },
    });
  }
 
  updateTaskBlockUnblock(projectId: string, taskId: string, blocked: boolean): void {
    this.http.put(this.apiBaseUrl + `/api/v1/task/${taskId}/blocked/${!blocked}`, {}).pipe(
      catchError(this.handleError)
    ).subscribe({
      next: () => {
        //update task in signal
        const currentTasksForProject = this.tasksForProjectSiganl();
        const updatedTasksForProject = currentTasksForProject.map(taskForProject => {
          Eif (taskForProject.projectId === projectId) {
            return {
              ...taskForProject,
              tasks: taskForProject.tasks.map(task =>
                task.id === taskId ? { ...task, blocked: !blocked } : task
              )
            };
          }
          return taskForProject;
        });
        this.tasksForProjectSiganl.set(updatedTasksForProject);
        this.setShowBlockTaskModal(false);
        const action = blocked ? 'desbloqueada' : 'bloqueada';
        this.toastService.show('info', `Tarea ${action} exitosamente`);
      },
      error: (err) => {
        console.error('Error updating task blocked status:', err);
      },
    });
  }
 
  getTasksForCurrentProject(projectId: string) {
    return this.tasksForProject().find(taskForProject => taskForProject.projectId === projectId)?.tasks || [];
  }
 
  getPriorityClasses(priority: TaskPriority): string {
    switch (priority) {
      case 'Alta':
        return 'bg-rose-100 text-rose-700 ring-1 ring-rose-200';
      case 'Media':
        return 'bg-amber-100 text-amber-700 ring-1 ring-amber-200';
      default:
        return 'bg-slate-100 text-slate-700 ring-1 ring-slate-200';
    }
  }
 
  getTaskStatusClasses(status: TaskStatus): string {
    switch (status) {
      case 'En curso':
        return 'bg-primary-100 text-primary-700 ring-1 ring-primary-200';
      case 'Creada':
        return 'bg-slate-100 text-slate-700 ring-1 ring-slate-200';
      case 'En revision':
        return 'bg-violet-100 text-violet-700 ring-1 ring-violet-200';
      default:
        return 'bg-emerald-100 text-emerald-700 ring-1 ring-emerald-200';
    }
  }
 
  getAdvance(projectId: string): number{
    const completedPoints =this.tasksForProject()
      .find(p => p.projectId === projectId)?.tasks.filter(t => t.status === "Completada").reduce((acc, task) => acc + task.effortPoints, 0) || 0
    const totalPoints = this.tasksForProject()
      .find(p => p.projectId === projectId)?.tasks.reduce((acc, task) => acc + task.effortPoints, 0) || 0
    const advance = completedPoints !== 0 ? Math.round((completedPoints / totalPoints) * 100) : 0
    return advance 
  }
 
  getAllTask(): TaskCard[] {
    const AllTask = this.tasksForProject().flatMap(p => p.tasks);
    return AllTask
  }
 
  removeSetTasks( ids: string[]): Observable<Object>{
    return this.http.delete(this.apiBaseUrl + "/api/v1/task/set", { body:ids })
  }
 
  deleteTasksInSignal(projectId: string, tasksIds: string[]) {
    const updateTasks: TaskForProject[] = this.tasksForProjectSiganl().map(p => {
      return p.projectId === projectId ? {...p, tasks: p.tasks.filter(t => !tasksIds.includes(t.id))} : p
    })
    this.tasksForProjectSiganl.set(updateTasks)
  }
 
  deleteAllProjectTaskInSignal(projectId: string) {
    const updateTasks: TaskForProject[] = this.tasksForProjectSiganl().filter(p => p.projectId !== projectId)
    this.tasksForProjectSiganl.set(updateTasks)
  }
 
  updateTaskInSignal(projectId: string, task: TaskCard) {
    const updateTask: TaskForProject[] = this.tasksForProjectSiganl().map(p => {
      return p.projectId === projectId ? {...p, tasks: p.tasks.map(t => t.id === task.id ? task : t)} : p
    })
    this.tasksForProjectSiganl.set(updateTask)
  }
 
  private handleError(error: HttpErrorResponse) {
    let errorMessage = 'Error desconocido';
    if (error.error instanceof ErrorEvent) {
      // Error del lado del cliente
      errorMessage = `Error: ${error.error.message}`;
    } else {
      // Error del lado del servidor
      errorMessage = `Código: ${error.status} - Mensaje: ${error.message}`;
    }
    return throwError(() => new Error(errorMessage));
  }
}