import { JsonPipe } from '@angular/common'; import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { ResourceFields } from '@syncfusion/ej2-angular-gantt'; import { LanguageService } from './language.service'; @Injectable({ providedIn: 'root' }) /** *The DataService manages the communication between Frontend and Backend, fetches Data from the Backend and maps it to the Frontend Data Structure. Additionally it updates data on the Backend. * */ export class DataService { private states: any []; //Array of statuses and possible statuses, which is queried once at the beginning by backend and stored in dataservice private supportGroups: any []; private contracts: any []; private paketTypes: any []; private totalSize: number = null; public userSupportGroup: string; //public selectedLanguage: string = 'DE'; /** * This constructor builds the dataService and fetches the states from the backend * @param http */ constructor(public languageService: LanguageService, private http: HttpClient) { this.fetchStates().then((res: any [])=>{ this.states = res; }); this.fetchSupportGroups().then((res: any [])=>{ this.supportGroups = res; }); this.fetchContracts().then((res: any [])=>{ this.contracts = res; }); this.fetchPaketTypes().then((res: any [])=>{ this.paketTypes = res; // console.log(res); }); this.fetchUserSupportGroup().then((res: any)=>{ this.userSupportGroup = res.name; console.log(this.userSupportGroup); }); } /** * * @returns an array of states and possible states per state */ public getStates():any[]{ return this.states; } public getSupportGroups():any[]{ return this.supportGroups; } public getContracts():any[]{ return this.contracts; } public getPaketTypes():any[]{ return this.paketTypes; } public getTotalSize():number{ return this.totalSize; } public getUserSupportGroup():string{ return this.userSupportGroup; } /** * The function fetchStates fetches an array from the possible statuses per state * @returns promise for the fetched Status Array */ public async fetchStates(){ const promise = new Promise(resolve=>{ let res : any[] = []; this.http.get('http://localhost:8080/api/getStates') .subscribe((response: any)=>{ response.forEach(state => { res.push(state) }); resolve(res); }) }) return promise; } public async fetchSupportGroups(){ const promise = new Promise(resolve=>{ let res : any[] = []; this.http.get('http://localhost:8080/api/getSupportGroups') .subscribe((response: any)=>{ response.forEach(supportGroup => { res.push(supportGroup) }); resolve(res); }) }) return promise; } public async fetchContracts(){ const promise = new Promise(resolve=>{ let res : any[] = []; this.http.get('http://localhost:8080/api/getContracts') .subscribe((response: any)=>{ response.forEach(contract => { res.push(contract) }); resolve(res); }) }) return promise; } public async fetchPaketTypes(){ const promise = new Promise(resolve=>{ let res : any[] = []; this.http.get('http://localhost:8080/api/getPackageTypes') .subscribe((response: any)=>{ response.forEach(paketType => { res.push(paketType) }); resolve(res); }) }) return promise; } public async fetchUserSupportGroup(){ const promise = new Promise(resolve=>{ let res : any = {}; this.http.get('http://localhost:8080/api/getUserSupportGroup') .subscribe((response: any)=>{ this.userSupportGroup = res.name; res = response; resolve(res); }) }) return promise; } /** * The function updateDatePerChange sends the new date to the backend if the date was moved * @param change the Change (the Resource) from which the date should be changed */ public async updateDatePerChange(change: any){ // //console.log(change); // let serializableResource = { resourceId: change.resourceId, d2: change.tasks[1].StartDate, changeNr: change.changeNr, state: change.state}; // let strigifiedResource = JSON.stringify(serializableResource); // let resJson = JSON.parse(strigifiedResource) as typeof strigifiedResource; // // console.log(resJson); // this.http.post('http://localhost:8080/api/updateChange', resJson).toPromise().then((value)=>{ // console.log(value); // }); const promise = new Promise(resolve=>{ let serializableResource = { resourceId: change.resourceId, d2: change.tasks[1].StartDate, changeNr: change.changeNr, state: change.state}; let strigifiedResource = JSON.stringify(serializableResource); let resJson = JSON.parse(strigifiedResource) as typeof strigifiedResource; // console.log(dataJson); this.http.post('http://localhost:8080/api/updateChange', resJson).subscribe((response:any)=>{ resolve(response); },(error:any)=>{ resolve(error); }); }); return promise; } /** * The function updateStatePerChange performs a status transition on the backend * @param change The Change for which the status transition is to be performed * @returns a Promise */ public async updateStatePerChange(change: any){ const promise = new Promise(resolve=>{ let obj = {changeNr : change.changeNr, currentState : change.currentState, nextState : change.nextState}; let stringyfiedData = JSON.stringify(obj); let dataJson = JSON.parse(stringyfiedData) as typeof stringyfiedData; // console.log(dataJson); this.http.post('http://localhost:8080/api/updateState', dataJson).subscribe((response:any)=>{ resolve(response); },(error:any)=>{ resolve(error); }); }); return promise; } public async updateImplementerPerChange(change: any){ const promise = new Promise(resolve=>{ // console.log(change); let obj = {pkgId : change.resourceId, loginId : change.loginId}; let stringyfiedData = JSON.stringify(obj); let dataJson = JSON.parse(stringyfiedData) as typeof stringyfiedData; // console.log(dataJson); this.http.post('http://localhost:8080/api/updateImplementer', dataJson).subscribe((response:any)=>{ resolve(response); },(error:any)=>{ console.log(error); resolve(error); }); }) return promise; } public async fetchPlanTimes(filters: any, renderStartDate: Date, renderEndtDate: Date){ const promise = new Promise(resolve=>{ let obj = {filter : filters.filter, renderStartDate : renderStartDate, renderEndDate: renderEndtDate }; let stringyfiedData = JSON.stringify(obj); let dataJson = JSON.parse(stringyfiedData) as typeof stringyfiedData; console.log(dataJson); let res : any[] = []; this.http.post('http://localhost:8080/api/fetchPlanTimes', dataJson) .subscribe((response: any[])=>{ response.forEach(week => { res.push(week); }); resolve(res); }) }) return promise; } public async fetchImplementers(change: any){ const promise = new Promise(resolve=>{ let obj = {entryId : change.resourceId, supportGroup : change.supportGroupId}; let stringyfiedData = JSON.stringify(obj); let dataJson = JSON.parse(stringyfiedData) as typeof stringyfiedData; // console.log(dataJson); let res : any[] = []; this.http.post('http://localhost:8080/api/getImplementer', dataJson) .subscribe((response: any)=>{ response.members.forEach(implementer => { res.push(implementer) }); resolve(res); }) }) return promise; } public async updateApproval(change: any, approvalAction){ const promise = new Promise(resolve=>{ let obj = {changeNr : change.changeNr, approvalAction: approvalAction}; let stringyfiedData = JSON.stringify(obj); let dataJson = JSON.parse(stringyfiedData) as typeof stringyfiedData; console.log(dataJson); this.http.post('http://localhost:8080/api/updateApproval', dataJson).subscribe((response:any)=>{ resolve(response); },(error:any)=>{ resolve(error); }); }).catch((error)=>{ throw(error); }) return promise; } /** * The function fetchChanges fetches the changes from backend and maps them to a structure that the Gannt component can interpret * @returns promise for the fetched Changes Array */ public async fetchChanges(reqestParams: any = null){ // let filter = {'filterElement': [reqestParams]}; let stringyfiedData = JSON.stringify(reqestParams); let dataJson = JSON.parse(stringyfiedData) as typeof stringyfiedData; const promise = new Promise(resolve=>{ let first : boolean = true; let res : any[] = []; console.log(dataJson); this.http.post('http://localhost:8080/api/getChanges', dataJson) .subscribe((response:any)=>{ console.log(response); this.totalSize = response.totalSize; response.changes.forEach(resp=>{ //console.log(resp.resourceId+" "+resp.approvalStatus) //console.log(resp); let tasks : any[] = []; if(resp.d1!=null){ tasks.push( { TaskID: resp.resourceId+"D1", TaskName: "Requested Start Date", StartDate: new Date(resp.d1), Duration: 0, isFixed: true, resources: [{resourceId: resp.resourceId},], Progress: 0, work: 0, isRes: false } ); } if(resp.d2!=null){ let isFixed = true; if(resp.state == 0 || resp.state == 3){ isFixed = false; } tasks.push( { TaskID: resp.resourceId+"D2", TaskName: "Sheduled Start Date", StartDate: new Date(resp.d2), Duration: 0, isFixed: isFixed, resources: [{resourceId: resp.resourceId},], Progress: 0, work: 0, isRes: false } ); } if(resp.d3!=null && resp.state>1){ tasks.push( { TaskID: resp.resourceId+"D3", TaskName: "Approved Start Date", StartDate: new Date(resp.d3), Duration: 0, isFixed: true, resources: [{resourceId: resp.resourceId},], Progress: 0, work: 0, isRes: false } ); } if(resp.d4!=null && resp.state == 10){ tasks.push( { TaskID: resp.resourceId+"D4", TaskName: "Actual End Date", StartDate: new Date(resp.d4), Duration: 0, isFixed: true, resources: [{resourceId: resp.resourceId},], Progress: 0, work: 0, isRes: false } ); } let approval = this.validateApproval(resp.approvalStatus); res.push({ resourceId: resp.resourceId, approvalStatus: this.validateApproval(resp.approvalStatus), statusReason: resp.statusReason, changeNr: resp.changeNr, resourceName: resp.resourceName, vertrag: resp.contract, vertragName: this.getContractName(resp.contract), isExpand: false, isRes: true, state: resp.state, stateName: this.getStateNameById(resp.state), supportGroup: resp.supportGroup, tasks: tasks, supportGroupId: resp.supportGroupId, implementerEdit: this.validateImplementerEdit(resp.state), flagApproval: approval, flagReject: approval, flagCancel: this.validateCancel(resp.state), flagPermit: this.validatePermit(resp.state), changeImplementerLogin: resp.changeImplementerLogin, packageName: resp.packageName, coordinatorSg: resp.coordinatorSg, plantime: resp.planTime, calenderWeek: this.getWeekNumber(new Date(resp.d2)) }); }) console.log(res); resolve(res); }) }) return promise; } getWeekNumber(d) { // Copy date so don't modify original d = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate())); // Set to nearest Thursday: current date + 4 - current day number // Make Sunday's day number 7 d.setUTCDate(d.getUTCDate() + 4 - (d.getUTCDay()||7)); // Get first day of year let yearStart : any; yearStart = new Date(Date.UTC(d.getUTCFullYear(),0,1)); // Calculate full weeks to nearest Thursday let weekNo = Math.ceil(( ( (d - yearStart) / 86400000) + 1)/7); // Return array of year and week number return '' + d.getUTCFullYear() + weekNo; } validateImplementerEdit(state):boolean{ if(state == 1 || state == 3 || state == 6){ return true }else{ return true } } validateCancel(state):boolean{ if(state == 1){ return true }else{ return false } } validatePermit(state): boolean{ if(state == 0){ return true }else{ return false } } validateApproval(approval):boolean{ if(approval!=""){ return true; }else{ return false; } } getStateNameById(stateNr): String { if(this.languageService.language == 'EN'){ for (let state of this.states) { if(stateNr == state.actualState){ return state.stateNameEN; } } } if(this.languageService.language == 'DE'){ for (let state of this.states) { if(stateNr == state.actualState){ return state.stateNameDE; } } } return ""; } getStateIdByName(stateName: string): number { for (let state of this.states) { if(stateName == state.stateNameEN){ return state.id; } } return -1; } getContractName(contractId: string): string{ return this.contracts.find((contract)=> {return contract.id == contractId;}).name; } }