Project

General

Profile

1
import {Component, ViewChild, Input} from '@angular/core';
2
import {Location} from '@angular/common';
3
import {Observable}       from 'rxjs/Observable';
4
import {ActivatedRoute, Router} from '@angular/router';
5
import {ModalLoading} from '../../utils/modal/loading.component';
6
import {AlertModal} from '../../utils/modal/alert';
7
import {Session} from '../../login/utils/helper.class';
8
import {EnvProperties} from '../../utils/properties/env-properties';
9
import {MailPrefsService} from './mailPrefs.service';
10
import {ConnectHelper} from '../connectHelper';
11
import {ErrorCodes} from '../../utils/properties/errorCodes';
12
import {LoginErrorCodes} from '../../login/utils/guardHelper.class';
13

    
14
declare var UIkit: any;
15

    
16
@Component({
17
  selector: 'mailPrefs',
18
  templateUrl: 'mailPrefs.component.html',
19
  providers:[MailPrefsService]
20

    
21
})
22
export class MailPrefsComponent {
23
  properties:EnvProperties;
24
  sub: any;
25
  public communityId: string;
26
  public preferencesFor: string = "community";
27
  public status: number;
28

    
29
  public notifications = [];
30
  public initialNotifications = [];
31
  public prefsChanged = {};
32

    
33
  //public showForbiddenMessage:boolean = false;
34
  public userValidMessage:string = "";
35
  public savedMessage: string = "";
36

    
37
  public fetchId:string;
38

    
39
  private errorCodes: ErrorCodes;
40

    
41
  @Input() showSaveResetButtons: boolean = true;
42

    
43
  constructor (private _mailPrefsService: MailPrefsService, private route: ActivatedRoute, private _router:Router, private location: Location) {
44
    this.errorCodes = new ErrorCodes();
45
    this.status = this.errorCodes.LOADING;
46
  }
47

    
48
  ngOnInit() {
49
    this.route.data
50
      .subscribe((data: { envSpecific: EnvProperties }) => {
51
        this.properties = data.envSpecific;
52
    });
53

    
54
    this.sub = this.route.queryParams.subscribe(params => {
55
      this.communityId = params['communityId'];
56

    
57
      if(!this.communityId){
58
        this.communityId  = ConnectHelper.getCommunityFromDomain(document.location.hostname);
59
      }
60

    
61
      this.fetchId = Session.getUserEmail();
62
      console.info("email: "+this.fetchId);
63
      console.info("communityId: " + this.communityId);
64

    
65
      this.getEmailPreferences();
66

    
67
    });
68
  }
69

    
70
  getEmailPreferences() {
71
    if(!Session.isLoggedIn()){
72
      //this.userValidMessage = "User session has expired. Please login again.";
73
      if(this.showSaveResetButtons) {
74
        this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this._router.url} });
75
      }
76
    } else {
77
      this.status = this.errorCodes.LOADING;
78
      this.savedMessage = "";
79

    
80
      if(this.communityId && this.communityId != "openaire") {
81
        this.preferencesFor = "community";
82
        this._mailPrefsService.getUserEmailPreferencesForCommunity(this.communityId, this.properties.claimsAPIURL).subscribe(
83
          data => {
84
            if(data.code == "204") {
85
              this.status = this.errorCodes.NONE;
86
            } else {
87
              this.initialNotifications = data.data;
88
              this.notifications = JSON.parse(JSON.stringify( this.initialNotifications ));
89

    
90
              this.status = this.errorCodes.DONE;
91
            }
92
          },
93
          err => {
94
            this.handleErrors(err);
95
          }
96
        );
97
      } else {
98
        this.preferencesFor = "project";
99
        this._mailPrefsService.getUserEmailPreferencesForOpenaire(this.properties.claimsAPIURL).subscribe(
100
          data => {
101
            console.info("email prefs returned");
102

    
103
            if(data.code == "204") {
104
              this.status = this.errorCodes.NONE;
105
            } else {
106
              console.info(data);
107

    
108
              this.initialNotifications = data.data;
109
              this.notifications = JSON.parse(JSON.stringify( this.initialNotifications ));
110
              //this.notifications = this.initialNotifications.map(x => Object.assign({}, x));
111
              //this.notifications = this.initialNotifications;
112

    
113
              this.status = this.errorCodes.DONE;
114
            }
115
          },
116
          err => {
117
            //console.info(err);
118
            this.handleErrors(err);
119
          }
120
        );
121
      }
122
    }
123
  }
124

    
125
  changeNotify(notification: any, checked: boolean, index: number) {
126
    if(!Session.isLoggedIn()){
127
      //this.userValidMessage = "User session has expired. Please login again.";
128
      if(this.showSaveResetButtons) {
129
        this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this._router.url} });
130
      }
131
    } else {
132
      this.savedMessage = "";
133
      this.status = this.errorCodes.DONE;
134
      notification.notify = checked;
135
      this.prefsChanged[index] = true;
136
    }
137
  }
138

    
139
  changeFrequency(value: number, index: number) {
140
    if(!Session.isLoggedIn()){
141
      //this.userValidMessage = "User session has expired. Please login again.";
142
      if(this.showSaveResetButtons) {
143
        this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this._router.url} });
144
      }
145
    } else {
146
      this.savedMessage = "";
147
      this.status = this.errorCodes.DONE;
148
      if(this.initialNotifications[index].frequency != value) {
149
        this.prefsChanged[index] = true;
150
      }
151
    }
152
  }
153

    
154
  saveNotification(index: number) {
155
    if(this.notifications.length > 0 && this.initialNotifications.length > 0) {
156
      if(!Session.isLoggedIn()){
157
          //this.userValidMessage = "User session has expired. Please login again.";
158
          if(this.showSaveResetButtons) {
159
            this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this._router.url} });
160
          }
161
      } else {
162
        if(JSON.stringify(this.notifications[index]) != JSON.stringify(this.initialNotifications[index])) {
163

    
164
          this.status = this.errorCodes.LOADING;
165
          this.savedMessage = "";
166
          console.info("Send notification to db: ", this.notifications[index]);
167

    
168
          this._mailPrefsService.saveUserEmailPreferences(this.notifications[index], this.properties.claimsAPIURL).subscribe(
169
            data => {
170
              console.info("Notification saved successfully");
171
              this.initialNotifications[index] = JSON.parse(JSON.stringify( this.notifications[index] ));
172

    
173
              this.status = this.errorCodes.DONE;
174

    
175
              /*UIkit.notification({
176
                  message : '<strong>Your email preferences for '+this.notifications[index].openaireName+' have been successfully changed<strong>',
177
                  status  : 'success',
178
                  timeout : 3000,
179
                  pos     : 'top-center'
180
              });*/
181
              this.savedMessage = "Notification settings for claims saved!";
182
            },
183
            err => {
184
              console.log(err);
185
              this.status = this.errorCodes.NOT_SAVED;
186
            }
187
          );
188
        }
189
        else {
190
          console.info("Notification not changed: ", this.notifications[index]);
191
          /*UIkit.notification({
192
              message : '<strong>No changes selected for '+this.notifications[index].openaireName+' email preferences<strong>',
193
              status  : 'primary',
194
              timeout : 3000,
195
              pos     : 'top-center'
196
          });*/
197
          this.savedMessage = "Notification settings for claims saved!";
198
        }
199
      }
200
    }
201
  }
202

    
203
  restoreNotification(index: number) {
204
    if(!Session.isLoggedIn()){
205
      //this.userValidMessage = "User session has expired. Please login again.";
206
      if(this.showSaveResetButtons) {
207
        this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this._router.url} });
208
      }
209
    } else {
210
      if(this.notifications.length > 0 && this.initialNotifications.length > 0) {
211
        this.status = this.errorCodes.LOADING;
212
        this.savedMessage = "";
213
        console.info("Restore Notification");
214
        console.info(this.notifications[index]);
215
        this.notifications[index] = JSON.parse(JSON.stringify( this.initialNotifications[index] ));
216
        console.info(this.initialNotifications[index]);
217
        this.status = this.errorCodes.DONE;
218
        this.prefsChanged[index] = false;
219
      }
220
    }
221
  }
222
/*
223
  prefsChanged(index: number) : boolean {
224
    if(this.notifications.length > 0 && this.initialNotifications.length > 0) {
225
      if(JSON.stringify(this.notifications[index]) != JSON.stringify(this.initialNotifications[index])) {
226
        return true;
227
      }
228
    }
229
    return false;
230
  }
231
*/
232
  ngOnDestroy() {
233
    if(this.sub) {
234
      this.sub.unsubscribe();
235
    }
236
  }
237

    
238
  handleErrors(err){
239
    //this.showErrorMessage = true;
240
    //try{
241
      var code = "";
242
      if(!err.status) {
243
        var error =  err.json();
244
        code = error.code;
245
      } else {
246
        code = err.status;
247
      }
248
      console.info(code);
249
      if(code == "403") {
250
        this.status = this.errorCodes.FORBIDDEN;
251
      }
252
      else if(code == "204") {
253
        this.status = this.errorCodes.NONE;
254
      } else if(code == "404") {
255
        this.status = this.errorCodes.NOT_FOUND;
256
      } else if(code == "500") {
257
        this.status = this.errorCodes.ERROR;
258
      } else {
259
        this.status = this.errorCodes.NOT_AVAILABLE;
260
      }
261

    
262

    
263
    //}catch (e) {
264
      //console.log("Couldn't parse answer as json")
265
      //this.showErrorMessage = true;
266
    //}
267
  }
268
}
(2-2/4)