Project

General

Profile

1
/**
2
 * Created by stefania on 7/13/17.
3
 */
4
import { Component, ViewChild, OnInit, ElementRef } from '@angular/core';
5
import { ActivatedRoute, Router } from "@angular/router";
6
import { HelpContentService } from "../../services/help-content.service";
7
import { FormGroup } from "@angular/forms";
8
import { ModalFormComponent } from "../modal-form.component";
9
import { DeleteConfirmationDialogComponent } from "../delete-confirmation-dialog.component";
10
import { PageFormComponent } from "./page-form.component";
11
import { CheckPage, Page } from "../../domain/page";
12
import { Community } from "../../domain/community";
13
import { Entity } from "../../domain/entity";
14
import { EnvProperties } from '../../openaireLibrary/utils/properties/env-properties';
15
import {Session} from '../../openaireLibrary/login/utils/helper.class';
16
import {LoginErrorCodes} from '../../openaireLibrary/login/utils/guardHelper.class';
17

    
18
@Component({
19
    selector: 'pages',
20
    templateUrl: './pages.component.html',
21
})
22

    
23
export class PagesComponent implements OnInit {
24

    
25
    // @ViewChild(ModalFormComponent)
26
    @ViewChild('saveModal')
27
    public modal:ModalFormComponent;
28
    //
29
    // @ViewChild('updateModal')
30
    // public updateModal:ModalFormComponent;
31

    
32
    // @ViewChild('deleteConfirmationModal')
33
    // public deleteConfirmationModal : DeleteConfirmationDialogComponent;
34
    @ViewChild('AlertModalSavePage') alertModalSavePage;
35
    @ViewChild('AlertModalUpdatePage') alertModalUpdatePage;
36
    @ViewChild('AlertModalDeletePages') alertModalDeletePages;
37
    private selectedPages: string[] = [];
38

    
39
    @ViewChild(PageFormComponent)
40
    public formComponent : PageFormComponent;
41

    
42
    public checkboxes : CheckPage[] = [];
43

    
44
    public pages : Page[] = [];
45
    public pageWithDivIds: string[] = [];
46

    
47
    //public errorMessage: string;
48

    
49
    public formGroup : FormGroup;
50

    
51
    private searchText : RegExp = new RegExp('');
52
    public  keyword: string = "";
53

    
54
    public communities: Community[] = [];
55

    
56
    public selectedCommunityPid: string;
57

    
58
    public pagesType: string;
59
    public properties:EnvProperties = null;
60

    
61
    public showLoading: boolean = true;
62
    public errorMessage: string = '';
63
    public updateErrorMessage: string = '';
64
    public modalErrorMessage: string = '';
65
    public isPortalAdministrator = null;
66

    
67
    ngOnInit() {
68
        this.formGroup = this.formComponent.form;
69
        this.route.data
70
          .subscribe((data: { envSpecific: EnvProperties }) => {
71
             this.properties = data.envSpecific;
72

    
73
             this.route.queryParams.subscribe(params => {
74
               this.scroll();
75

    
76
               this.pagesType = "";
77
               if(params['type']) {
78
                 this.pagesType = params['type'];
79
               }
80

    
81
               this.keyword = "";
82

    
83
               this.selectedCommunityPid = params['communityId'];
84
               this.applyCommunityFilter(this.selectedCommunityPid);
85
               this.isPortalAdministrator = Session.isPortalAdministrator();
86

    
87
               //this.getCommunities();
88
             });
89
        });
90
    }
91

    
92
    constructor(private element: ElementRef, private route: ActivatedRoute, private _router: Router, private _helpContentService: HelpContentService) {}
93

    
94
    getPages(community_pid: string) {
95
      if(!Session.isLoggedIn()){
96
        console.info(this._router.url);
97
        this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this._router.url} });
98
      } else {
99
        this.showLoading = true;
100
        this.updateErrorMessage = "";
101
        this.errorMessage = "";
102

    
103
        this.pageWithDivIds = [];
104

    
105
        let parameters = "";
106
        if(this.pagesType) {
107
          parameters = "?page_type="+this.pagesType;
108
        }
109
        this._helpContentService.getCommunityPages(community_pid, parameters, this.properties.adminToolsAPIURL).subscribe(
110
            pages => {
111
              this.pagesReturned(pages);
112
              if(!this.pagesType || this.pagesType == "link") {
113
                this.getPagesWithDivIds(community_pid);
114
              } else {
115
                this.showLoading = false;
116
              }
117
            },
118
            error => this.handleError('System error retrieving pages', error)
119
        );
120
      }
121
    }
122

    
123
    getPagesWithDivIds(community_pid: string) {
124
      if(!Session.isLoggedIn()){
125
        console.info(this._router.url);
126
        this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this._router.url} });
127
      } else {
128
        this._helpContentService.getPagesWithDivIds(community_pid, this.properties.adminToolsAPIURL).subscribe(
129
            pages => {
130
              this.pageWithDivIds = pages;
131
              this.showLoading = false;
132
            },
133
            error => this.handleError('System error retrieving information about pages\' classes', error));
134
      }
135
    }
136

    
137
    pagesReturned(pages: Page[]) {
138
      this.pages = pages;
139
      this.checkboxes = [];
140

    
141
      if(pages) {
142
        pages.forEach(_ => {
143
          this.checkboxes.push(<CheckPage>{page : _, checked : false});
144
        });
145
      }
146
    }
147
/*
148
    getCommunities() {
149
        this._helpContentService.getCommunities(this.properties.adminToolsAPIURL).subscribe(
150
            communities => {
151
                this.communities = communities;
152
                this.selectedCommunityPid = this.communities[0].pid;
153
                this.getPages(this.selectedCommunityPid);
154
                this.getPagesWithDivIds(this.selectedCommunityPid);
155
        },
156
        error => this.handleError('System error retrieving communities', error));
157
    }
158
*/
159
    public showModal():void {
160
        this.modal.showModal();
161
    }
162

    
163
    public toggleCheckBoxes(event) {
164
        this.checkboxes.forEach(_ => _.checked = event.target.checked);
165
    }
166

    
167
    public applyCheck(flag : boolean) {
168
      console.info("applyCheck "+flag);
169
        this.checkboxes.forEach(_ => _.checked = flag);
170
    }
171

    
172
    public getSelectedPages() : string[] {
173
        return this.checkboxes.filter(page => page.checked == true).map(checkedPage => checkedPage.page).map(res => res._id);
174
    }
175

    
176
    private deletePagesFromArray(ids : string[]) : void {
177
        for(let id of ids) {
178
            let i = this.checkboxes.findIndex(_ => _.page._id == id);
179
            this.checkboxes.splice(i, 1);
180
        }
181
    }
182

    
183
    public confirmDeletePage(id : string) {
184
        //this.deleteConfirmationModal.ids = [id];
185
        //this.deleteConfirmationModal.showModal();
186
        this.selectedPages = [id];
187
        this.confirmModalOpen();
188
    }
189

    
190
    public confirmDeleteSelectedPages() {
191
        //this.deleteConfirmationModal.ids = this.getSelectedPages();
192
        //this.deleteConfirmationModal.showModal();
193
        this.selectedPages = this.getSelectedPages();
194
        this.confirmModalOpen();
195
    }
196

    
197
    private confirmModalOpen() {
198
      if(!Session.isLoggedIn()){
199
        console.info(this._router.url);
200
        this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this._router.url} });
201
      } else {
202
        this.alertModalDeletePages.cancelButton = true;
203
        this.alertModalDeletePages.okButton = true;
204
        this.alertModalDeletePages.alertTitle = "Delete Confirmation";
205
        this.alertModalDeletePages.message = "Are you sure you want to delete the selected page(s)?";
206
        this.alertModalDeletePages.okButtonText = "Yes";
207
        this.alertModalDeletePages.open();
208
      }
209
    }
210

    
211
    public confirmedDeletePages(data: any) {
212
      if(!Session.isLoggedIn()){
213
        console.info(this._router.url);
214
        this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this._router.url} });
215
      } else {
216
        this.showLoading = true;
217
        this.updateErrorMessage = "";
218

    
219
        this._helpContentService.deletePages(this.selectedPages, this.properties.adminToolsAPIURL).subscribe(
220
            _ => {
221
              this.deletePagesFromArray(this.selectedPages);
222
              this.showLoading = false;
223
            },
224
            error => this.handleUpdateError('System error deleting the selected pages', error)
225
        );
226
      }
227
    }
228

    
229
    public editPage(i : number) {
230
        let page : Page = this.checkboxes[i].page;
231
        this.formGroup.patchValue(page);
232
        this.formComponent.setEntities(page.entities as Entity[]);
233

    
234
        console.info(this.formGroup.value);
235
        //this.updateModal.showModal();
236
        this.modalErrorMessage = "";
237
        this.pagesModalOpen(this.alertModalUpdatePage, "Update", "Update Page");
238
    }
239

    
240
    public newPage() {
241
        this.formComponent.reset();
242
        this.modalErrorMessage = "";
243
        this.pagesModalOpen(this.alertModalSavePage, "Save", "Add a new Page");
244
    }
245

    
246
    private pagesModalOpen(modal: any, title: string, yesBtn: string) {
247
      if(!Session.isLoggedIn()){
248
        console.info(this._router.url);
249
        this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this._router.url} });
250
      } else {
251
        modal.cancelButton = true;
252
        modal.okButton = true;
253
        modal.alertTitle = title;
254
        modal.okButtonText = yesBtn;
255
        modal.open();
256
      }
257
    }
258

    
259
    public pageSaveConfirmed(data: any) {
260
      if(!Session.isLoggedIn()){
261
        console.info(this._router.url);
262
        this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this._router.url} });
263
      } else {
264
        if(!this.formGroup.valid) {
265
          this.pagesModalOpen(this.alertModalSavePage, "Save", "Add a new Page");
266
          this.modalErrorMessage = "Please fill in all required fields marked with *";
267
        } else {
268
          this.modalErrorMessage = "";
269
          this._helpContentService.savePage(<Page> this.formGroup.value, this.properties.adminToolsAPIURL).subscribe(
270
              page => {
271
                this.pageSavedSuccessfully(page);
272
              },
273
              error => this.handleUpdateError("System error creating page", error)
274
          );
275
        }
276
      }
277
    }
278

    
279
    public pageUpdateConfirmed(data: any) {
280
      if(!Session.isLoggedIn()){
281
        console.info(this._router.url);
282
        this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this._router.url} });
283
      } else {
284
        if(!this.formGroup.valid) {
285
          this.pagesModalOpen(this.alertModalUpdatePage, "Update", "Update Page");
286
          this.modalErrorMessage = "Please fill in all required fields marked with *";
287
        } else {
288
          this._helpContentService.updatePage(<Page> this.formGroup.value, this.properties.adminToolsAPIURL).subscribe(
289
              page => {
290
                this.pageUpdatedSuccessfully(page);
291
              },
292
              error => this.handleUpdateError("System error updating page", error)
293
          );
294
        }
295
      }
296
    }
297

    
298
    public pageSavedSuccessfully(page: Page) {
299
        this.checkboxes.push(<CheckPage>{page : page, checked : false});
300
        console.info("checkboxes length: "+this.checkboxes.length);
301
        this.applyCheck(false);
302
    }
303

    
304
    public pageUpdatedSuccessfully(page : Page) {
305
      console.info(page._id);
306
      console.info(this.checkboxes.find(checkItem => (checkItem.page._id == page._id)));
307
      console.info(page.entities);
308
        this.checkboxes.find(checkItem => checkItem.page._id==page._id).page = page;
309
        this.applyCheck(false);
310
    }
311

    
312
    public filterBySearch(text : string) {
313
        this.searchText = new RegExp(text,'i');
314
        this.applyFilter();
315
    }
316

    
317
    public applyFilter() {
318
        this.checkboxes = [];
319
        this.pages.filter(item => this.filterPages(item)).forEach(
320
            _ => this.checkboxes.push(<CheckPage>{page: _, checked: false})
321
        );
322
    }
323

    
324
    public filterPages(page : Page) : boolean {
325
        let textFlag = this.searchText.toString() == '' || (page.route + ' ' +page.name).match(this.searchText) != null;
326
        return textFlag;
327
    }
328

    
329
    handleError(message: string, error) {
330
        // if(error == null) {
331
        //     this.formComponent.reset();
332
        // } else {
333
          this.errorMessage = message;// + ' (Server responded: ' + error + ')';
334
          console.log('Server responded: ' +error);
335
        //}
336

    
337
        this.showLoading = false;
338
    }
339

    
340
    handleUpdateError(message: string, error) {
341
        if(error == null) {
342
            this.formComponent.reset();
343
        } else {
344
          this.updateErrorMessage = message;// + ' (Server responded: ' + error + ')';
345
          console.log('Server responded: ' +error);
346
        }
347

    
348
        this.showLoading = false;
349
    }
350

    
351
    // public filterByCommunity(event: any) {
352
    //     this.selectedCommunityPid = event.target.value;
353
    //     this.applyCommunityFilter(this.selectedCommunityPid);
354
    // }
355

    
356
    public applyCommunityFilter(community_pid: string) {
357
        this.getPages(community_pid);
358
    }
359

    
360
    public togglePages(status : boolean, ids : string[]) {
361
      if(!Session.isLoggedIn()){
362
        console.info(this._router.url);
363
        this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this._router.url} });
364
      } else {
365
        this.showLoading = true;
366
        this.updateErrorMessage = "";
367

    
368
        this._helpContentService.togglePages(this.selectedCommunityPid,ids,status, this.properties.adminToolsAPIURL).subscribe(
369
            () => {
370
                for(let id of ids) {
371
                  let i = this.checkboxes.findIndex(_ => _.page._id == id);
372
                  this.checkboxes[i].page.isEnabled=status;
373
                }
374
                this.applyCheck(false);
375
                this.showLoading = false;
376
            },
377
            error => this.handleUpdateError('System error changing the status of the selected page(s)', error)
378
        );
379
      }
380
    }
381

    
382
    public capitalizeFirstLetter(str: string) {
383
        return str.charAt(0).toUpperCase() + str.slice(1);
384
    }
385

    
386
    public scroll() {
387
      console.info("scroll into view");
388
      if (typeof document !== 'undefined') {
389
         this.element.nativeElement.scrollIntoView();
390
      }
391
    }
392
}
(4-4/4)