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 { PageFormComponent } from "./page-form.component";
9
import { CheckPage, Page } from "../../domain/page";
10
import { Community } from "../../domain/community";
11
import { Entity } from "../../domain/entity";
12
import { EnvProperties } from '../../openaireLibrary/utils/properties/env-properties';
13
import {Session} from '../../openaireLibrary/login/utils/helper.class';
14
import {LoginErrorCodes} from '../../openaireLibrary/login/utils/guardHelper.class';
15
import {HelperFunctions} from "../../openaireLibrary/utils/HelperFunctions.class";
16

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

    
22
export class PagesComponent implements OnInit {
23

    
24
    @ViewChild('AlertModalSavePage') alertModalSavePage;
25
    @ViewChild('AlertModalUpdatePage') alertModalUpdatePage;
26
    @ViewChild('AlertModalDeletePages') alertModalDeletePages;
27
    private selectedPages: string[] = [];
28

    
29
    @ViewChild(PageFormComponent)
30
    public formComponent : PageFormComponent;
31

    
32
    public checkboxes : CheckPage[] = [];
33

    
34
    public pages : Page[] = [];
35
    public pageWithDivIds: string[] = [];
36

    
37
    //public errorMessage: string;
38

    
39
    public formGroup : FormGroup;
40

    
41
    private searchText : RegExp = new RegExp('');
42
    public  keyword: string = "";
43

    
44
    public communities: Community[] = [];
45

    
46
    public selectedCommunityPid: string;
47

    
48
    public pagesType: string;
49
    public properties:EnvProperties = null;
50

    
51
    public showLoading: boolean = true;
52
    public errorMessage: string = '';
53
    public updateErrorMessage: string = '';
54
    public modalErrorMessage: string = '';
55
    public isPortalAdministrator = null;
56

    
57
    ngOnInit() {
58
        this.formGroup = this.formComponent.form;
59
        this.route.data
60
          .subscribe((data: { envSpecific: EnvProperties }) => {
61
             this.properties = data.envSpecific;
62

    
63
             this.route.queryParams.subscribe(params => {
64
               HelperFunctions.scroll();
65

    
66
               this.pagesType = "";
67
               if(params['type']) {
68
                 this.pagesType = params['type'];
69
               }
70

    
71
               this.keyword = "";
72

    
73
               this.selectedCommunityPid = params['communityId'];
74
               this.applyCommunityFilter(this.selectedCommunityPid);
75
               this.isPortalAdministrator = Session.isPortalAdministrator() && !this.selectedCommunityPid;
76

    
77
               //this.getCommunities();
78
             });
79
        });
80
    }
81

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

    
84
    getPages(community_pid: string) {
85
      if(!Session.isLoggedIn()){
86
        this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this._router.url} });
87
      } else {
88
        this.showLoading = true;
89
        this.updateErrorMessage = "";
90
        this.errorMessage = "";
91

    
92
        this.pageWithDivIds = [];
93

    
94
        let parameters = "";
95
        if(this.pagesType) {
96
          parameters = "?page_type="+this.pagesType;
97
        }
98
        if(community_pid) {
99
          this._helpContentService.getCommunityPages(community_pid, parameters, this.properties.adminToolsAPIURL).subscribe(
100
            pages => {
101
              this.pagesReturned(pages);
102
              //if(!this.pagesType || this.pagesType == "link") {
103
              this.getPagesWithDivIds(community_pid);
104
              //} else {
105
              //this.showLoading = false;
106
              //}
107
            },
108
            error => this.handleError('System error retrieving pages', error)
109
          );
110
        } else {
111
          this._helpContentService.getPagesFull(this.properties.adminToolsAPIURL, null).subscribe(
112
            pages => {
113
              this.pagesReturned(pages);
114
              this.showLoading = false;
115
            },
116
            error => this.handleError('System error retrieving pages', error)
117
          );
118
        }
119
      }
120
    }
121

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

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

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

    
158
    public toggleCheckBoxes(event) {
159
        this.checkboxes.forEach(_ => _.checked = event.target.checked);
160
    }
161

    
162
    public applyCheck(flag : boolean) {
163
        this.checkboxes.forEach(_ => _.checked = flag);
164
    }
165

    
166
    public getSelectedPages() : string[] {
167
        return this.checkboxes.filter(page => page.checked == true).map(checkedPage => checkedPage.page).map(res => res._id);
168
    }
169

    
170
    private deletePagesFromArray(ids : string[]) : void {
171
        for(let id of ids) {
172
            let i = this.checkboxes.findIndex(_ => _.page._id == id);
173
            this.checkboxes.splice(i, 1);
174
        }
175
    }
176

    
177
    public confirmDeletePage(id : string) {
178
        //this.deleteConfirmationModal.ids = [id];
179
        //this.deleteConfirmationModal.showModal();
180
        this.selectedPages = [id];
181
        this.confirmModalOpen();
182
    }
183

    
184
    public confirmDeleteSelectedPages() {
185
        //this.deleteConfirmationModal.ids = this.getSelectedPages();
186
        //this.deleteConfirmationModal.showModal();
187
        this.selectedPages = this.getSelectedPages();
188
        this.confirmModalOpen();
189
    }
190

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

    
204
    public confirmedDeletePages(data: any) {
205
      if(!Session.isLoggedIn()){
206
        this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this._router.url} });
207
      } else {
208
        this.showLoading = true;
209
        this.updateErrorMessage = "";
210

    
211
        this._helpContentService.deletePages(this.selectedPages, this.properties.adminToolsAPIURL).subscribe(
212
            _ => {
213
              this.deletePagesFromArray(this.selectedPages);
214
              this.showLoading = false;
215
            },
216
            error => this.handleUpdateError('System error deleting the selected pages', error)
217
        );
218
      }
219
    }
220

    
221
    public editPage(i : number) {
222
        let page : Page = this.checkboxes[i].page;
223
        this.formGroup.patchValue(page);
224
        this.formComponent.setEntities(page.entities as Entity[]);
225

    
226
        //console.info(this.formGroup.value);
227
        //this.updateModal.showModal();
228
        this.modalErrorMessage = "";
229
        this.pagesModalOpen(this.alertModalUpdatePage, "Update", "Update Page");
230
    }
231

    
232
    public newPage() {
233
        this.formComponent.reset();
234
        this.modalErrorMessage = "";
235
        this.pagesModalOpen(this.alertModalSavePage, "Save", "Add a new Page");
236
    }
237

    
238
    private pagesModalOpen(modal: any, title: string, yesBtn: string) {
239
      if(!Session.isLoggedIn()){
240
        this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this._router.url} });
241
      } else {
242
        modal.cancelButton = true;
243
        modal.okButton = true;
244
        modal.alertTitle = title;
245
        modal.okButtonText = yesBtn;
246
        modal.open();
247
      }
248
    }
249

    
250
    public pageSaveConfirmed(data: any) {
251
      if(!Session.isLoggedIn()){
252
        this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this._router.url} });
253
      } else {
254
        if(!this.formGroup.valid) {
255
          this.pagesModalOpen(this.alertModalSavePage, "Save", "Add a new Page");
256
          this.modalErrorMessage = "Please fill in all required fields marked with *";
257
        } else {
258
          this.modalErrorMessage = "";
259
          this._helpContentService.savePage(<Page> this.formGroup.value, this.properties.adminToolsAPIURL).subscribe(
260
              page => {
261
                this.pageSavedSuccessfully(page);
262
              },
263
              error => this.handleUpdateError("System error creating page", error)
264
          );
265
        }
266
      }
267
    }
268

    
269
    public pageUpdateConfirmed(data: any) {
270
      if(!Session.isLoggedIn()){
271
        this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this._router.url} });
272
      } else {
273
        if(!this.formGroup.valid) {
274
          this.pagesModalOpen(this.alertModalUpdatePage, "Update", "Update Page");
275
          this.modalErrorMessage = "Please fill in all required fields marked with *";
276
        } else {
277
          this._helpContentService.updatePage(<Page> this.formGroup.value, this.properties.adminToolsAPIURL).subscribe(
278
              page => {
279
                this.pageUpdatedSuccessfully(page);
280
              },
281
              error => this.handleUpdateError("System error updating page", error)
282
          );
283
        }
284
      }
285
    }
286

    
287
    public pageSavedSuccessfully(page: Page) {
288
        this.checkboxes.push(<CheckPage>{page : page, checked : false});
289
        this.applyCheck(false);
290
    }
291

    
292
    public pageUpdatedSuccessfully(page : Page) {
293
        this.checkboxes.find(checkItem => checkItem.page._id==page._id).page = page;
294
        this.applyCheck(false);
295
    }
296

    
297
    public filterBySearch(text : string) {
298
        this.searchText = new RegExp(text,'i');
299
        this.applyFilter();
300
    }
301

    
302
    public applyFilter() {
303
        this.checkboxes = [];
304
        this.pages.filter(item => this.filterPages(item)).forEach(
305
            _ => this.checkboxes.push(<CheckPage>{page: _, checked: false})
306
        );
307
    }
308

    
309
    public filterPages(page : Page) : boolean {
310
        let textFlag = this.searchText.toString() == '' || (page.route + ' ' +page.name).match(this.searchText) != null;
311
        return textFlag;
312
    }
313

    
314
    handleError(message: string, error) {
315
        // if(error == null) {
316
        //     this.formComponent.reset();
317
        // } else {
318
          this.errorMessage = message;// + ' (Server responded: ' + error + ')';
319
          console.log('Server responded: ' +error);
320
        //}
321

    
322
        this.showLoading = false;
323
    }
324

    
325
    handleUpdateError(message: string, error) {
326
        if(error == null) {
327
            this.formComponent.reset();
328
        } else {
329
          this.updateErrorMessage = message;// + ' (Server responded: ' + error + ')';
330
          console.log('Server responded: ' +error);
331
        }
332

    
333
        this.showLoading = false;
334
    }
335

    
336
    // public filterByCommunity(event: any) {
337
    //     this.selectedCommunityPid = event.target.value;
338
    //     this.applyCommunityFilter(this.selectedCommunityPid);
339
    // }
340

    
341
    public applyCommunityFilter(community_pid: string) {
342
        this.getPages(community_pid);
343
    }
344

    
345
    public togglePages(status : boolean, ids : string[]) {
346
      if(!Session.isLoggedIn()){
347
        this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this._router.url} });
348
      } else {
349
        this.updateErrorMessage = "";
350

    
351
        this._helpContentService.togglePages(this.selectedCommunityPid,ids,status, this.properties.adminToolsAPIURL).subscribe(
352
            () => {
353
                for(let id of ids) {
354
                  let i = this.checkboxes.findIndex(_ => _.page._id == id);
355
                  this.checkboxes[i].page.isEnabled=status;
356
                }
357
                this.applyCheck(false);
358
            },
359
            error => this.handleUpdateError('System error changing the status of the selected page(s)', error)
360
        );
361
      }
362
    }
363

    
364
    public capitalizeFirstLetter(str: string) {
365
        return str.charAt(0).toUpperCase() + str.slice(1);
366
    }
367
}
(5-5/6)