import { Injectable } from '@angular/core' ; import { BehaviorSubject , Observable } from 'rxjs' ; import { IOrganizationSprint , IGetSprintsOptions , ITask } from '@gauzy/contracts' ; import { SprintService } from './../../@core/services/organization-sprint.service' ; import { tap , take , map , switchMap } from 'rxjs/operators' ; import { UntilDestroy , untilDestroyed } from '@ngneat/until-destroy' ; @ UntilDestroy ( ) @ Injectable ( { providedIn : 'root' } ) export class SprintStoreService { private _sprints$ : BehaviorSubject < IOrganizationSprint [ ] > = new BehaviorSubject ( [ ] ) ; sprints$ : Observable < IOrganizationSprint [ ] > = this . _sprints$ . asObservable ( ) ; private get sprints ( ) : IOrganizationSprint [ ] { return this . _sprints$ . getValue ( ) ; } constructor ( private sprintService ) { } fetchSprints ( findInput = { } ) { this . sprintService . getAllSprints ( findInput ) . pipe ( tap ( ( { items } ) => this . loadAllSprints ( items ) ) , untilDestroyed ( this ) ) . subscribe ( ) ; } loadAllSprints ( sprints ) { this . _sprints$ . next ( sprints ) ; } createSprint ( newSprint ) { return this . sprintService . createSprint ( newSprint ) . pipe ( tap ( ( createdSprint ) => { const sprints = [ ... this . sprints , createdSprint ] ; this . _sprints$ . next ( sprints as IOrganizationSprint [ ] ) ; } ) , take ( 1 ) ) ; } updateSprint ( editedSprint ) { return this . sprintService . editSprint ( editedSprint . id , editedSprint ) . pipe ( tap ( ( ) => { const sprints = [ ... this . sprints ] ; const newState = sprints . map ( ( t ) => t . id === editedSprint . id ? editedSprint : t ) ; this . _sprints$ . next ( newState ) ; } ) , take ( 1 ) ) ; } deleteSprint ( id ) { return this . sprintService . deleteSprint ( id ) . pipe ( tap ( ( ) => { const newState = this . sprints . filter ( ( sprint ) => sprint . id !== id ) ; this . _sprints$ . next ( newState ) ; } ) , take ( 1 ) ) ; } moveTaskToSprint ( sprintId , task ) { return this . sprints$ . pipe ( map ( ( sprints ) => sprints . find ( ( sprint ) => sprint . id === sprintId ) ) , switchMap ( ( { tasks } ) => this . sprintService . editSprint ( sprintId , { tasks : [ ... tasks , task ] } ) ) , tap ( ( updatedSprint ) => { } ) , take ( 1 ) ) ; } }