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

88% Statements 88/100
66.66% Branches 32/48
87.75% Functions 43/49
86.9% Lines 73/84

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 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233                      16x   16x 16x 16x 16x 16x 16x 16x   16x 16x 16x 16x   16x     5x       2x 2x 1x   1x 5x       2x 2x       1x       1x     16x 1x 1x                                               16x 1x 1x   1x     1x       1x                 16x 3x 3x   3x 3x 3x   3x 3x 3x 3x     3x   3x                   1x 1x   2x         1x 2x       1x         3x 1x   2x               2x   1x   1x             2x   1x   1x             1x   5x           1x   1x 1x 1x 1x 1x 1x             1x 1x       1x       1x                 1x                              
import { computed, inject, Injectable, signal } from '@angular/core';
import { ProjectCard, ProjectHealth, ProjectPriority } from './project.interfaces';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { environment } from '../../../environments/environment';
import { AuthService } from '../auth/auth.service';
import { catchError, throwError } from 'rxjs';
import { UserSearchEmailResult } from '../users/user.interfaces';
import { TaskService } from '../task/task.service';
import { TaskCard } from '../task/task.interfaces';
 
@Injectable({ providedIn: 'root' })
export class ProjectService {
 
  private readonly authService = inject(AuthService);
  private readonly taskService = inject(TaskService);
  private readonly projectsSignal = signal<ProjectCard[]>([]);
  private readonly membersSignal = signal<UserSearchEmailResult[]>([]);
  private readonly currentProjectIdSignal = signal<string>('');
  private readonly loadProjectsFromApi = signal(false);
  private readonly apiBase = environment.authApiBaseUrl;
 
  readonly currentProjectId = this.currentProjectIdSignal.asReadonly();
  readonly projects = this.projectsSignal.asReadonly();
  readonly loadProjects = this.loadProjectsFromApi.asReadonly();
  readonly members = this.membersSignal.asReadonly()
 
  constructor(private http: HttpClient) {}
 
  setCurrentProjectId(id: string) {
    this.currentProjectIdSignal.set(id);
  }
 
  getMembersOfCurrentProject() {
    const currentProject = this.projectsSignal().find(project => project.id === this.currentProjectIdSignal());
    if (!currentProject) {
      return [];
    }
    const memberIds = Array.from(new Set(currentProject.teamMembers.concat(currentProject.creator)));
    return memberIds.map(memberId => this.membersSignal().find(member => member.id === memberId)).filter(Boolean) as UserSearchEmailResult[];
  }
 
  getNameCurrentProject() {
    const currentProject = this.projectsSignal().find(project => project.id === this.currentProjectIdSignal());
    return currentProject ? currentProject.name : '';
  }
 
  inProgressTasks(): TaskCard[] {
    return this.taskService.getAllTask().filter((task) => task.status === 'En curso')
  }
 
  blockedTasks(): TaskCard[] {
    return this.taskService.getAllTask().filter((task) => task.blocked)
  }
 
  readonly overviewCards = computed(() => {
    const summary = this.portfolioSummary();
    return [
      {
        label: 'Proyectos activos',
        value: `${summary.activeProjects}`,
        helper: 'Iniciativas con seguimiento visible desde esta vista.',
      },
      {
        label: 'Avance promedio',
        value: `${summary.avgProgress}%`,
        helper: 'Progreso acumulado entre todos los frentes activos.',
      },
      {
        label: 'Colaboradores',
        value: `${summary.totalCollaborators}`,
        helper: 'Personas distintas participando en el portafolio.',
      },
      {
        label: 'Proxima entrega',
        value: this.formatDate(summary.nextDeadline, true),
        helper: 'Fecha mas cercana comprometida por el equipo.',
      },
    ];
  });
 
  readonly projectSignals = computed(() => {
    const projects = this.projects();
    const summary = this.portfolioSummary();
 
    return [
      {
        label: 'Alta prioridad',
        value: `${projects.filter((project) => project.priority === 'Alta').length}`,
      },
      {
        label: 'En foco',
        value: `${projects.filter((project) => project.health === 'En foco').length}`,
      },
      {
        label: 'Bloqueos',
        value: `${summary.blockedTasks}`,
      },
    ];
  });
 
  readonly portfolioSummary = computed(() => {
    const projects = this.projectsSignal();
    const tasks = this.taskService.getAllTask();
 
    const activeProjects = projects.length;
    const avgProgress = activeProjects
      ? Math.round(projects.reduce((sum, project) => sum + this.taskService.getAdvance(project.id), 0) / activeProjects)
      : 0;
    const totalCollaborators = new Set(projects.flatMap((project) => project.teamMembers)).size;
    const nextDeadline = tasks
      .filter((task) => task.status !== 'Completada')
      .map((task) => task.dueDate)
      .filter(Boolean)
      .sort((a, b) => new Date(a).getTime() - new Date(b).getTime())[0] ?? null;
    const blockedTasks = tasks.filter((task) => task.blocked).length;
 
    return {
      activeProjects,
      avgProgress,
      totalCollaborators,
      nextDeadline,
      blockedTasks,
    };
  });
 
  getInitialsMember(id: string): string {
    return this.membersSignal()
      .find(member => member.id === id)?.name
      .split(' ')
      .map(n => n[0])
      .join('') || '';
  }
  
  getNameMember(id:string): string {
    return this.membersSignal()
      .find(member => member.id === id)?.name || '';
  }
 
  getNameProject(id:string): string {
    return this.projectsSignal()
      .find(p => p.id === id)?.name || "";
  }
 
  formatDate(value: string | null, longFormat = false): string {
    if (!value) {
      return 'Sin fecha';
    }
    return new Intl.DateTimeFormat('es-ES', {
      day: '2-digit',
      month: 'short',
      ...(longFormat ? { year: 'numeric' } : {}),
    }).format(new Date(value));
  }
 
  getHealthClasses(health: ProjectHealth): string {
    switch (health) {
      case 'En foco':
        return 'bg-emerald-100 text-emerald-700 ring-1 ring-emerald-200';
      case 'En riesgo':
        return 'bg-amber-100 text-amber-700 ring-1 ring-amber-200';
      default:
        return 'bg-sky-100 text-sky-700 ring-1 ring-sky-200';
    }
  }
  
  getPriorityClasses(priority: ProjectPriority): 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';
    }
  }
 
  previewCommaSeparatedValues(value: string): string[] {
    return value
      .split(',')
      .map((entry) => entry.trim())
      .filter(Boolean)
      .slice(0, 4);
  }
 
  getProjectsFromApi(): void {
    this.http.get<ProjectCard[]>(this.apiBase + '/api/v1/project/ofTheUser/' + this.getUserId()).subscribe({
      next: (projects) => {
        this.projectsSignal.set(projects);
        const teamMenbersIds = Array.from(new Set(projects.flatMap(p => p.teamMembers).concat(projects.map(p => p.creator))));
        const projectsIds = projects.map(p => p.id);
        this.getMembersByIds(teamMenbersIds);
        this.taskService.getTaskByProjectsIds(projectsIds);
        this.loadProjectsFromApi.set(true)
      },
      error: (err) => console.error('Error fetching projects:', err),
    });
  }
 
  deletedProject(projectId: string) {
    const updatedProjects = this.projectsSignal().filter(p => p.id !== projectId)
    this.projectsSignal.set(updatedProjects)
  }
  
  private getMembersByIds(ids: string[]): void {
    this.http.post<UserSearchEmailResult[]>(this.apiBase + '/api/v1/user/search/team', ids).pipe(
      catchError(this.handleError)
    ).subscribe({
      next: (members) => {
        this.membersSignal.set(members);
      },
      error: (err) => {
        console.error('Error fetching members:', err)
      },
    });
  }
 
  private getUserId(): string {
    return this.authService.authUser()?.id ?? '';
  }
 
  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));
  }
}