Project

General

Profile

1
import {Component, Input} from '@angular/core';
2
import {Location} from '@angular/common';
3
import {ActivatedRoute, Router} from '@angular/router';
4
import {Session} from '../../login/utils/helper.class';
5
import {EnvProperties} from '../../utils/properties/env-properties';
6
import {MailPrefsService} from './mailPrefs.service';
7
import {ConnectHelper} from '../connectHelper';
8
import {ErrorCodes} from '../../utils/properties/errorCodes';
9
import {ErrorMessagesComponent}    from '../../utils/errorMessages.component';
10
import {LoginErrorCodes} from '../../login/utils/guardHelper.class';
11
import {properties} from "../../../../environments/environment";
12
import {Subscriber} from "rxjs";
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
  subscriptions = [];
25
  @Input()  communityId: string;
26
  public preferencesFor: string = "community";
27
  public status: number;
28

    
29
  public notifications = [];
30
  public initialNotifications = [];
31
  public prefsChanged = {};
32
  public hidden: boolean = true;
33

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

    
38
  private errorCodes: ErrorCodes;
39
  private errorMessages: ErrorMessagesComponent;
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.errorMessages = new ErrorMessagesComponent();
46
    this.status = this.errorCodes.LOADING;
47
  }
48

    
49
  ngOnInit() {
50
    this.properties = properties;
51
    this.subscriptions.push(this.route.params.subscribe(params => {
52
      this.hidden = true;
53
      console.debug(this.communityId);
54
      if(!this.communityId){
55
        this.communityId  = ConnectHelper.getCommunityFromDomain(this.properties.domain);
56
      }
57
      if(!this.communityId) {
58
        this.communityId = params['community'];
59
      }
60
      console.debug(this.communityId, params)
61
      this.getEmailPreferences();
62
    }));
63

    
64

    
65
  }
66

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

    
77
      if(this.communityId && this.communityId != "openaire") {
78
        this.preferencesFor = "community";
79
        this.subscriptions.push(this._mailPrefsService.getUserEmailPreferencesForCommunity(this.communityId, this.properties.claimsAPIURL).subscribe(
80
          data => {
81
            if(data.code == "204") {
82
              this.status = this.errorCodes.NONE;
83
              this.initialNotifications = [{notify: true, frequency:24, openaireId: this.communityId}];
84
            } else {
85
              this.initialNotifications = data.data;
86
            }
87
              this.notifications = JSON.parse(JSON.stringify( this.initialNotifications ));
88

    
89
              this.status = this.errorCodes.DONE;
90
              this.hidden = false;
91

    
92
          },
93
          err => {
94
            this.hidden = false;
95
            this.handleErrors(err);
96
            this.handleError("Error getting user email preferences for community with id: "+this.communityId, err);
97
          }
98
        ));
99
      } else {
100
        this.preferencesFor = "project";
101
        this.subscriptions.push(this._mailPrefsService.getUserEmailPreferencesForOpenaire(this.properties.claimsAPIURL).subscribe(
102
          data => {
103

    
104
            if(data.code == "204") {
105
              this.status = this.errorCodes.NONE;
106
            } else {
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
            this.handleError("Error getting user email preferences for openaire", err);
120
          }
121
        ));
122
      }
123
    }
124
  }
125

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

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

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

    
165
          this.status = this.errorCodes.LOADING;
166
          this.savedMessage = "";
167

    
168
          this.subscriptions.push(this._mailPrefsService.saveUserEmailPreferences(this.notifications[index], this.properties.claimsAPIURL).subscribe(
169
            data => {
170
              this.initialNotifications[index] = JSON.parse(JSON.stringify( this.notifications[index] ));
171

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

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

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

    
236

    
237
  handleErrors(err){
238
    //this.showErrorMessage = true;
239
    //try{
240
    var code = "";
241
    if(!err.status) {
242
      var error =  err.json();
243
      code = error.code;
244
    } else {
245
      code = err.status;
246
    }
247
    this.status = this.errorMessages.getErrorCode(code);
248
  }
249

    
250
  private handleError(message: string, error) {
251
    console.error("User mail notification preferences Page (for claims): "+message, error);
252
  }
253

    
254

    
255
  //}catch (e) {
256
  //console.log("Couldn't parse answer as json")
257
  //this.showErrorMessage = true;
258
  //}
259
}
(2-2/4)