All files / src/app/core/services job.service.ts

55% Statements 66/120
48.38% Branches 15/31
55.81% Functions 24/43
92.42% Lines 61/66

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 20618x 18x   18x                 18x   18x         18x   24x   24x     24x   24x   25x                   6x   11x 11x   5x 5x 5x 5x 5x 5x 2x   3x 2x     5x         5x   5x 5x       6x                   1x               1x   1x 1x                   2x   2x           9x 9x 9x 4x 4x 4x 2x 2x     2x         9x 5x                   2x   2x 2x                       2x   2x 2x             1x   1x 1x                             1x   1x 1x                           1x   1x 1x           1x    
import { Injectable } from '@angular/core';
import { DataService } from './data.service';
import { Job } from '@core/model/job.interface';
import { BehaviorSubject, map, Observable, of, switchMap, tap } from 'rxjs';
import { Page } from '@core/model/page.interface';
import { CreateJobRequest } from '@core/model/create-job-request.interface';
import { UpdateJobFieldRequest, UpdateJobRequest } from '@core/model/update-job-request.interface';
import { CreateJobAttachmentsRequest } from '@core/model/create-job-attachments-request.interface';
import { CreateJobAttachmentRequest } from '@core/model/create-job-attachment-request.interface';
import { CreateJobActivitiesRequest } from '@core/model/create-job-activities-request.interface';
import { UpdateJobRatingRequest } from '@core/model/update-job-rating-request.interface';
import { JobMetadata } from '@core/model/job-metadata.interface';
import { SessionService } from './session.service';
import { ProtectedFile } from '../model/protected-file.interface';
import { JobsListOptions } from '../model/jobs-list-options';
 
@Injectable({
  providedIn: 'root'
})
export class JobService {
 
  private jobsSubject: BehaviorSubject<Page<Job> | null> = new BehaviorSubject<Page<Job> | null> (null);
  
  private currentOptions: JobsListOptions = new JobsListOptions();
 
 
  constructor(private dataService: DataService, private sessionService: SessionService) {
    
    this.sessionService.$isLogged().subscribe(l => {
        // reset subject when user logged in status changes
        this.jobsSubject.next(null);
      });
   }
 
   /**
   * Retrieves the sorted jobs loaded from the backend 
   * trying to avoid unncessary data service requests
   * @returns the jobs
   */
  public getAllJobs(jobsListOptions: JobsListOptions): Observable<Page<Job>> {
    return this.jobsSubject.pipe(
      switchMap((jobsPage: Page<Job> | null) => {
        console.log('JobService.getAllJobs called with options:', jobsListOptions);
        if(jobsPage === null || jobsListOptions.getMustReload() || !this.currentOptions.equals(jobsListOptions)) {
          // create a new instance to store current options, otherwise the current instance would be the same as the one in the service
          this.currentOptions = jobsListOptions;
          this.currentOptions.forceReload(null);
          const status = this.currentOptions.getStatus();
          const statusMeta = this.currentOptions.getStatusMeta();
          let statusOrFilterParam = '';
          if(status !== null) {
            statusOrFilterParam += `status=${status}`;
          }
          else if (statusMeta !== null) {
            statusOrFilterParam += `statusMeta=${statusMeta}`;
          }
          
          const url = `jobs?page=${this.currentOptions.getCurrentPage()}&itemsPerPage=${this.currentOptions.getItemsPerPage()}`
            +(statusOrFilterParam ? `&${statusOrFilterParam}` : '')
            +`&sort=${this.currentOptions.getSort()}`
            +`&query=${encodeURIComponent(this.currentOptions.getQuery() as string)}`
 
          return this.dataService.get<Page<Job>>(url).pipe(
            switchMap((fetchedJobs: Page<Job>) => {
              this.jobsSubject.next(fetchedJobs);
              return of(fetchedJobs);
            })
          )
        }
        return of(jobsPage);
      })
    );
  }
 
  /**
   * Retrieves a job by its id
   * @returns the job
   */
  public getJobById(jobId: string): Observable<Job> {
    return this.dataService.get<Job>(`jobs/${jobId}`);
  }
 
   /**
   * Creates a job
   * @returns the job
   */
   public createJob(request: CreateJobRequest): Observable<Job> {
    return this.dataService.post<Job>(`jobs`, request).pipe(
      map((j: Job) => {
        this.jobsSubject.next(null);
        return j;
      })
    );
  }
 
  /**
   * Retrieves a job by its id
   * @returns the job
   */
  public deleteJob(jobId: string): Observable<void> {
    return this.dataService.delete<void>(`jobs/${jobId}`).pipe(
      tap(() => {
        this.reloadIfNecessary({id: jobId} as Job, true);
      })
    );
  }
  
  private reloadIfNecessary(j: Job, remove: boolean = false) :void {
    const page: Page<Job> | null = this.jobsSubject.value;
    let existingJobIndex = -1
    if(page !== null) {
      existingJobIndex = page.content.findIndex((job: Job) => j.id == job.id);
      if(existingJobIndex !== -1) {
        if(remove) {
          page.content.splice(existingJobIndex, 1);
          page.totalElementsCount--;
        }
        else {
          page.content[existingJobIndex] = j;
        }
      }
    }
 
    if(existingJobIndex === -1) {
      this.jobsSubject.next(null);
    }
  }
 
  /**
   * Updates a job rating
   * @returns the job
   */
  public updateJobRating(jobId: string, request: UpdateJobRatingRequest): Observable<Job> {
    // using patch because only some fields are edited
    return this.dataService.patch<Job>(`jobs/${jobId}`, request).pipe(
      map((j: Job) => {
        this.reloadIfNecessary(j);
        return j;
      })
    );
  }
 
  
   /**
   * Updates a job
   * @returns the job
   */
   public updateJob(jobId: string, request: UpdateJobRequest): Observable<Job> {
    // using patch because only some fields are edited
    return this.dataService.patch<Job>(`jobs/${jobId}`, request).pipe(
      map((j: Job) => {
        this.reloadIfNecessary(j);
        return j;
      })
    );
  }
 
  public updateJobField(jobId: string, request: UpdateJobFieldRequest): Observable<Job> {
    // using patch because only some fields are edited
    return this.dataService.patch<Job>(`jobs/${jobId}`, request).pipe(
      map((j: Job) => {
        this.reloadIfNecessary(j);
        return j;
      })
    );
  }
 
  public createAttachment(jobId: string, request: CreateJobAttachmentRequest): Observable<Job> {
    return this.dataService.post<Job>(`jobs/${jobId}/attachments`, request).pipe(
      map((j: Job) => {
        this.reloadIfNecessary(j);
        return j;
      })
    );
  }
 
  public createAttachments(jobId: string, request: CreateJobAttachmentsRequest): Observable<Job> {
    return this.dataService.post<Job>(`jobs/${jobId}/attachments`, request.attachments).pipe(
      map((j: Job) => {
        this.reloadIfNecessary(j);
        return j;
      })
    );
  }
 
  public deleteAttachment(jobId: string, attachmentId: string): Observable<void> {
    return this.dataService.delete<void>(`jobs/${jobId}/attachments/${attachmentId}`);
  }
 
  public getProtectedFile(jobId: string, attachmentId: string): Observable<ProtectedFile> {
    return this.dataService.get<ProtectedFile>(`jobs/${jobId}/attachments/${attachmentId}/file/info`);
  }
 
  public createActivities(jobId: string, request: CreateJobActivitiesRequest): Observable<Job> {
    return this.dataService.post<Job>(`jobs/${jobId}/activities`, request.activities).pipe(
      map((j: Job) => {
        this.reloadIfNecessary(j);
        return j;
      })
    );
  }
 
  public getJobMetadata(url: string) :Observable<JobMetadata> {
    return this.dataService.get<JobMetadata>(`jobs/metadata?url=${url}`)
  } 
}