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

82.25% Statements 51/62
57.89% Branches 11/19
75% Functions 21/28
82.14% Lines 46/56

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                        5x   5x 5x 5x 5x   5x 5x 5x 5x 5x 5x   5x 5x 5x 5x 5x   5x     1x                       1x 1x 1x 1x     1x       1x       1x           1x 1x 1x             1x     1x   1x       1x 1x   1x                 1x         1x 1x             1x   2x         1x 1x               1x 1x 1x 1x                   2x                            
import { inject, Injectable, signal } from "@angular/core";
import { ProjectDetailsValidationService } from "./project.details.validation";
import { ProjectRequest } from "./project.interfaces";
import { HttpClient, HttpErrorResponse } from "@angular/common/http";
import { catchError, map, Observable, throwError } from "rxjs";
import { environment } from "../../../environments/environment";
import { ProjectTeamTableService } from "./project.team.table.service";
import { UserRole } from "../users/user.interfaces";
import { ProjectService } from "./project.service";
import { TaskService } from "../task/task.service";
 
@Injectable({ providedIn: 'root' })
export class ProjectDetailsService {
 
  readonly detailValidationService = inject(ProjectDetailsValidationService);
  private readonly teamTableService = inject(ProjectTeamTableService)
  private readonly projectService = inject(ProjectService)
  private readonly taskService = inject(TaskService)
 
  private readonly isDetailsPanelOpenSignal = signal(false);
  private readonly isLoadingSignal = signal(false);
  private readonly isEditModeSignal = signal(false);
  private readonly tagsInputSignal = signal('');
  private readonly isModalOpenSignal = signal(false);
  private readonly apiBase = environment.authApiBaseUrl;
 
  readonly tagsInput = this.tagsInputSignal.asReadonly();
  readonly isDetailsPanelOpen = this.isDetailsPanelOpenSignal.asReadonly();
  readonly isLoading = this.isLoadingSignal.asReadonly();
  readonly isEditMode = this.isEditModeSignal.asReadonly();
  readonly isModalOpen = this.isModalOpenSignal.asReadonly();
 
  constructor(private http: HttpClient) { }
 
  getNameCreator(id: string): string {
    return this.projectService.getNameMember(id)
  }
  setEditMode(editMode: boolean) {
    this.isEditModeSignal.set(editMode);
  }
  setLoading(loading: boolean) {
    this.isLoadingSignal.set(loading);
  }
  setIsModalOpen(isOpen: boolean) {
    this.isModalOpenSignal.set(isOpen);
  }
  openDetailsProjectPanel(projectId: string): void {
    this.getProjectById(projectId);
    this.isDetailsPanelOpenSignal.set(true);
    this.teamTableService.setIsEditMode(false)
    this.teamTableService.cleanInputMember();
  }
  closeDetailsProjectPanel(): void {
    this.isDetailsPanelOpenSignal.set(false);
  }
 
  tagsInputSet(tags: string) {
    this.tagsInputSignal.set(tags)
  }
 
  removeProject(projectId: string): Observable<String> {
    return this.http.delete(this.apiBase + '/api/v1/project/' + projectId, {
      withCredentials: true
    })
      .pipe(
        map((res) => {
          //Borrar aqui tareas del proyecto eliminado usando TaskService
          this.removeTaskOfProject(projectId)
          this.projectService.deletedProject(projectId)
          return "Project deleted successfully";
        }),
        catchError(this.handleError)
      );
  }
 
  updateProject(projectData: ProjectRequest, teamMembers: UserRole[]): Observable<String> {
    const newProject: ProjectRequest = {
      ...projectData,
      tags: this.splitCommaSeparatedValues(this.tagsInputSignal()),
      teamMembers: teamMembers.map(member => ({ userId: member.id, role: member.role.trim() }))
    };
    return this.updateProjectRequest(newProject);
  }
 
  private removeTaskOfProject(projectId: string) {
    const tasks: string[] = this.taskService.tasksForProject().find(p => p.projectId === projectId)?.tasks.map(t => t.id) || []
    this.taskService.removeSetTasks(tasks).subscribe({
      next: () => {
        this.taskService.deleteAllProjectTaskInSignal(projectId)
      },
      error: (err) => {
        console.error('Error fetching project details:', err);
      },
    })
  }
 
  private updateProjectRequest(projectData: ProjectRequest): Observable<String> {
    return this.http.put<ProjectRequest>(this.apiBase + '/api/v1/project/' + projectData.id, projectData, {
      withCredentials: true
    })
      .pipe(
        map((res) => {
          this.projectService.getProjectsFromApi();
          return "Project created successfully";
        }),
        catchError(this.handleError)
      );
  }
  
  private splitCommaSeparatedValues(value: string): string[] {
    return value
      .split(',')
      .map((entry) => entry.trim())
      .filter(Boolean);
  }
 
  private getProjectById(projectId: string): void {
    this.http.get<ProjectRequest>(this.apiBase + '/api/v1/project/' + projectId, {},).pipe(
      map(data => ({
        ...data,
        startDate: this.toInputDate(data.startDate),
        dueDate: this.toInputDate(data.dueDate)
      })),
      catchError(this.handleError)
    ).subscribe({
      next: (project) => {
        this.tagsInputSignal.set(project.tags.join(', '))
        this.detailValidationService.setProjectDetailsModel(project);
        this.detailValidationService.formDisable();
        this.teamTableService.loadTeamMembers(project.teamMembers)
      },
      error: (err) => {
        console.error('Error fetching project details:', err);
      },
    });
  }
 
  private toInputDate(value: string): string {
    // Si viene como ISO: "2024-03-15T00:00:00.000Z"
    return new Date(value).toISOString().split('T')[0];
  }
 
  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));
  }
}