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
    this.savedMessage = "";
127
    this.status = this.errorCodes.DONE;
128
    notification.notify = checked;
129
    this.prefsChanged[index] = true;
130
  }
131

    
132
  changeFrequency(value: number, index: number) {
133
    this.savedMessage = "";
134
    this.status = this.errorCodes.DONE;
135
    if(this.initialNotifications[index].frequency != value) {
136
      this.prefsChanged[index] = true;
137
    }
138
  }
139

    
140
  saveNotification(index: number) {
141
    if(this.notifications.length > 0 && this.initialNotifications.length > 0) {
142
      if(JSON.stringify(this.notifications[index]) != JSON.stringify(this.initialNotifications[index])) {
143
        if(!Session.isLoggedIn()){
144
          this.userValidMessage = "User session has expired. Please login again.";
145
          if(this.showSaveResetButtons) {
146
            this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this._router.url} });
147
          }
148
        }else{
149
          this.status = this.errorCodes.LOADING;
150
          this.savedMessage = "";
151
          console.info("Send notification to db: ", this.notifications[index]);
152

    
153
          this._mailPrefsService.saveUserEmailPreferences(this.notifications[index], this.properties.claimsAPIURL).subscribe(
154
            data => {
155
              console.info("Notification saved successfully");
156
              this.initialNotifications[index] = JSON.parse(JSON.stringify( this.notifications[index] ));
157

    
158
              this.status = this.errorCodes.DONE;
159

    
160
              /*UIkit.notification({
161
                  message : '<strong>Your email preferences for '+this.notifications[index].openaireName+' have been successfully changed<strong>',
162
                  status  : 'success',
163
                  timeout : 3000,
164
                  pos     : 'top-center'
165
              });*/
166
              this.savedMessage = "Notification settings for claims saved!";
167
            },
168
            err => {
169
              console.log(err);
170
              this.status = this.errorCodes.NOT_SAVED;
171
            }
172
          );
173
        }
174
      } else {
175
        console.info("Notification not changed: ", this.notifications[index]);
176
        /*UIkit.notification({
177
            message : '<strong>No changes selected for '+this.notifications[index].openaireName+' email preferences<strong>',
178
            status  : 'primary',
179
            timeout : 3000,
180
            pos     : 'top-center'
181
        });*/
182
        this.savedMessage = "Notification settings for claims saved!";
183
      }
184
    }
185
  }
186

    
187
  restoreNotification(index: number) {
188
    if(this.notifications.length > 0 && this.initialNotifications.length > 0) {
189
      this.status = this.errorCodes.LOADING;
190
      this.savedMessage = "";
191
      console.info("Restore Notification");
192
      console.info(this.notifications[index]);
193
      this.notifications[index] = JSON.parse(JSON.stringify( this.initialNotifications[index] ));
194
      console.info(this.initialNotifications[index]);
195
      this.status = this.errorCodes.DONE;
196
      this.prefsChanged[index] = false;
197
    }
198
  }
199
/*
200
  prefsChanged(index: number) : boolean {
201
    if(this.notifications.length > 0 && this.initialNotifications.length > 0) {
202
      if(JSON.stringify(this.notifications[index]) != JSON.stringify(this.initialNotifications[index])) {
203
        return true;
204
      }
205
    }
206
    return false;
207
  }
208
*/
209
  ngOnDestroy() {
210
    if(this.sub) {
211
      this.sub.unsubscribe();
212
    }
213
  }
214

    
215
  handleErrors(err){
216
    //this.showErrorMessage = true;
217
    //try{
218
      var code = "";
219
      if(!err.status) {
220
        var error =  err.json();
221
        code = error.code;
222
      } else {
223
        code = err.status;
224
      }
225
      console.info(code);
226
      if(code == "403") {
227
        this.status = this.errorCodes.FORBIDDEN;
228
      }
229
      else if(code == "204") {
230
        this.status = this.errorCodes.NONE;
231
      } else if(code == "404") {
232
        this.status = this.errorCodes.NOT_FOUND;
233
      } else if(code == "500") {
234
        this.status = this.errorCodes.ERROR;
235
      } else {
236
        this.status = this.errorCodes.NOT_AVAILABLE;
237
      }
238

    
239

    
240
    //}catch (e) {
241
      //console.log("Couldn't parse answer as json")
242
      //this.showErrorMessage = true;
243
    //}
244
  }
245
}
(2-2/4)