Project

General

Profile

1
import {Component, Input, OnInit} from '@angular/core';
2
import {FormBuilder} from "@angular/forms";
3
import {ActivatedRoute, Router} from '@angular/router';
4

    
5
import {ConnectHelper} from '../../../openaireLibrary/connect/connectHelper';
6

    
7
import {Email} from '../../../openaireLibrary/utils/email/email';
8
import {Body} from '../../../openaireLibrary/utils/email/body';
9
import {Validator} from '../../../openaireLibrary/utils/email/validator';
10
import {Composer} from '../../../openaireLibrary/utils/email/composer';
11

    
12
import {EnvProperties} from '../../../openaireLibrary/utils/properties/env-properties';
13
import {EmailService} from '../../../openaireLibrary/utils/email/email.service';
14
import {CommunityService} from "../../../openaireLibrary/connect/community/community.service";
15
import {ErrorCodes} from '../../../openaireLibrary/utils/properties/errorCodes';
16
import {ErrorMessagesComponent} from '../../../openaireLibrary/utils/errorMessages.component';
17
import {Session, User} from '../../../openaireLibrary/login/utils/helper.class';
18
import {HelperFunctions} from "../../../openaireLibrary/utils/HelperFunctions.class";
19
import {HelperService} from "../../../openaireLibrary/utils/helper/helper.service";
20
import {Meta, Title} from "@angular/platform-browser";
21
import {SEOService} from "../../../openaireLibrary/sharedComponents/SEO/SEO.service";
22
import {PiwikService} from "../../../openaireLibrary/utils/piwik/piwik.service";
23
import {PiwikHelper} from "../../piwikHelper";
24
import {UserManagementService} from "../../../openaireLibrary/services/user-management.service";
25

    
26
@Component({
27
  selector: 'invite',
28
  templateUrl: './invite.component.html',
29
})
30

    
31
export class InviteComponent implements OnInit {
32

    
33
  @Input() longView: boolean = true;
34
  @Input() communityId = null;
35
  @Input() buttonSizeSmall = true;
36

    
37
  @Input() properties: EnvProperties;
38

    
39
  public community = null;
40
  //public showLoading: boolean = true;
41
  public errorMessage: string = '';
42
  public successfulSentMessage: string = '';
43
  public successfulSentRecipients: string[] = [];
44
  public failureSentMessage: string = '';
45
  public failureSentRecipients: string[] = [];
46
  public inviteErrorMessage: string = '';
47
  public missingCommunityId: string = '';
48
  public showAddRecipientMessage: boolean = false;
49
  public showAddNameMessage: boolean = false;
50

    
51
  public email: Email;
52
  public body: Body;
53
  public recipients: string;
54
  public fullname: string;
55

    
56
  public areValid: boolean = true;
57

    
58
  private ckeditorContent: string;
59

    
60
  // public defaultBody ='';
61

    
62
  public communityIdParam = {};
63
  public status: number = 1;
64
  public errorCodes: ErrorCodes;
65
  private errorMessages: ErrorMessagesComponent;
66
  public pageContents = null;
67
  public divContents = null;
68

    
69
  public url: string = null;
70
  public pageTitle: string = "Invite";
71
  piwiksub: any;
72
  private user: User;
73

    
74
  constructor(
75
    private route: ActivatedRoute,
76
    private _router: Router,
77
    public _fb: FormBuilder,
78
    private _emailService: EmailService,
79
    private _communityService: CommunityService,
80
    private helper: HelperService,
81
    private _meta: Meta,
82
    private _title: Title,
83
    private seoService: SEOService,
84
    private _piwikService: PiwikService,
85
    private userManageService: UserManagementService) {
86

    
87
    this.errorCodes = new ErrorCodes();
88
    this.errorMessages = new ErrorMessagesComponent();
89
    this.status = this.errorCodes.LOADING;
90
  }
91

    
92
  public ngOnInit() {
93
    this.route.data.subscribe((data: { envSpecific: EnvProperties }) => {
94
      if(!this.properties) {
95
        this.properties = data.envSpecific;
96
      }
97
      if(this.properties) {
98
        this.errorMessage = "";
99
        this.missingCommunityId = "";
100
        this.status = this.errorCodes.LOADING;
101
        this.userManageService.getUserInfo().subscribe(
102
          user => {
103
            this.user = user;
104
            this.init();
105
          },
106
          error => {
107
            this.init();
108
          }
109
        );
110
        //this.init();
111
      }
112
    });
113
  }
114

    
115
  ngOnDestroy() {
116
    if (this.piwiksub) {
117
      this.piwiksub.unsubscribe();
118
    }
119
  }
120

    
121
  private init() {
122
    this.route.queryParams.subscribe(
123
      communityId => {
124
        //if(!this.communityId && typeof document !== 'undefined'){
125
        this.communityId = ConnectHelper.getCommunityFromDomain(this.properties.domain);
126
        if (!this.communityId) {
127
          this.communityId = communityId['communityId'];
128
        }
129

    
130
        if (this.longView) {
131
          if (this.properties.enablePiwikTrack && (typeof document !== 'undefined')) {
132
            this.piwiksub = this._piwikService.trackView(this.properties, this.pageTitle, PiwikHelper.getSiteId(this.communityId, this.properties.environment)).subscribe();
133
          }
134
          this.url = this.properties.baseLink + this._router.url;
135
          this.seoService.createLinkForCanonicalURL(this.url);
136
          this.updateUrl(this.url);
137
          this.updateTitle(this.pageTitle);
138
          this.updateDescription("OpenAIRE - Connect, Community Gateway, research community, invite");
139
        }
140
        this.communityIdParam = (this.properties.environment != "development") ? {} : {communityId: this.communityId};
141
        if (this.communityId != null && this.communityId != '') {
142
          //this.getDivContents();
143
          this.getPageContents();
144
          this._communityService.getCommunity(this.properties, this.properties.communityAPI + this.communityId).subscribe(
145
            community => {
146
              this.community = community;
147
              this.fullname = (this.user) ? this.user.fullname : null;
148
              //console.log("Fullname from session " + Session.getUserFullName());
149

    
150
              this.body = Composer.initializeInvitationsBody(this.communityId, this.community.title, this.fullname);
151
              this.email = Composer.initializeInvitationsEmail(community.title);
152
              this.recipients = "";
153

    
154
              this.status = this.errorCodes.DONE;
155
            },
156
            error => {
157
              //this.handleError(error)
158
              this.handleError("Error getting community with id: " + this.communityId, error);
159
              this.status = this.errorMessages.getErrorCode(error.status);
160
            }
161
          );
162
        } else {
163
          this.status = this.errorCodes.DONE;
164
          this.missingCommunityId = "There is no community selected!";
165
        }
166

    
167
      });
168
    HelperFunctions.scroll();
169
  }
170

    
171
  private getPageContents() {
172
    this.helper.getPageHelpContents(this.properties, this.communityId, this._router.url).subscribe(contents => {
173
      this.pageContents = contents;
174
    })
175
  }
176

    
177
  private getDivContents() {
178
    this.helper.getDivHelpContents(this.properties, this.communityId, this._router.url).subscribe(contents => {
179
      this.divContents = contents;
180
    })
181
  }
182

    
183

    
184
  public invite() {
185
    this.successfulSentMessage = "";
186
    this.failureSentMessage = "";
187
    this.inviteErrorMessage = "";
188
    this.status = this.errorCodes.LOADING;
189
    HelperFunctions.scroll();
190
    if (!this.isEmpty(this.recipients) && this.body.fromName != "") {
191
      if (this.validateEmails()) {
192
        this.composeEmail();
193

    
194
        this._emailService.sendEmail(this.properties, this.email).subscribe(
195
          res => {
196
            this.status = this.errorCodes.DONE;
197
            //console.log("Emails Sent: ",res);
198
            /*if(res == 0) {
199

    
200
            } else if(res > 1) {
201
              this.successfulSentMessage = res + " emails sent successfully!";
202
            } else {
203
              this.successfulSentMessage = res + " email sent successfully!";
204
            }*/
205

    
206
            if (res['success']) {
207
              this.successfulSentMessage = "Email sent successfully to: ";
208
              this.successfulSentRecipients = res['success'];
209
            }
210
            if (res['failure']) {
211
              this.failureSentMessage = "There was an error sending email to: ";
212
              this.failureSentRecipients = res['failure'];
213
            }
214

    
215
            this.body = Composer.initializeInvitationsBody(this.communityId, this.community.title, this.fullname);
216
            this.email = Composer.initializeInvitationsEmail(this.community.title);
217
            this.recipients = "";
218
          },
219
          error => {
220
            //console.log(error);
221
            this.handleError("Error inviting emails: " + JSON.stringify(this.recipients) + " to community with id: " + this.communityId + " by: " + this.fullname, error);
222
            this.status = this.errorCodes.DONE;
223
            this.inviteErrorMessage = "There was an error sending emails. Please try again.";
224
          }
225
        );
226
      } else {
227
        this.email.recipients = [];
228
        this.status = this.errorCodes.DONE;
229
      }
230
    } else {
231
      this.showAddRecipientMessage = true;
232
      this.status = this.errorCodes.DONE;
233
    }
234
  }
235

    
236
  public isEmpty(data: string): boolean {
237
    if (data != undefined && !data.replace(/\s/g, '').length)
238
      return true;
239
    else
240
      return false;
241
  }
242

    
243
  public resetMessages() {
244
    this.errorMessage = "";
245
    this.successfulSentMessage = "";
246
    this.failureSentMessage = "";
247
    this.inviteErrorMessage = "";
248
  }
249

    
250
  public validateEmails(): boolean {
251
    if (this.parseEmails()) {
252
      if (Validator.hasValidEmails(this.email.recipients)) {
253
        return this.areValid;
254
      }
255
    }
256
    this.areValid = false;
257
    return this.areValid;
258
  }
259

    
260
  public parseEmails(): boolean {
261
    let email = new Array<string>();
262

    
263
    // remove spaces
264
    this.recipients = this.recipients.replace(/\s/g, '');
265

    
266
    // remove commas
267
    email = this.recipients.split(",");
268

    
269
    // remove empty fields
270
    for (let i = 0; i < email.length; i++) {
271
      if (!(email[i] == "")) {
272
        this.email.recipients.push(email[i]);
273
      }
274
    }
275
    return true;
276
  }
277

    
278
  public composeEmail() {
279
    this.email.body = Composer.formatEmailBodyForInvitation(this.body);
280
  }
281

    
282
  /*
283
    public handleError(error) {
284
      if(error.status == '401') {
285
        this.status = this.errorCodes.FORBIDDEN;
286
      } else if(error.status == '403') {
287
        this.status = this.errorCodes.FORBIDDEN;
288
      } else if(error.status == '404') {
289
        this.status = this.errorCodes.NOT_FOUND;
290
      } else if(error.status == '500') {
291
        this.status = this.errorCodes.ERROR;
292
      } else {
293
        this.status = this.errorCodes.NOT_AVAILABLE;
294
      }
295
        console.log('Server responded: ' + error);
296
    }
297
  */
298
  allowEdit() {
299
    if (!this.user) {
300
      return false;
301
    }
302
    var email = this.user.email;
303
    var index = -1;
304
    if (email && this.community != null && this.community.managers != null) {
305
      index = this.community.managers.indexOf(email);
306
    }
307
    return Session.isPortalAdministrator(this.user) || Session.isCommunityCurator(this.user) || index != -1;
308
  }
309

    
310
  private handleError(message: string, error) {
311
    console.error("Invite Page (or component): " + message, error);
312
  }
313

    
314
  private updateDescription(description: string) {
315
    this._meta.updateTag({content: description}, "name='description'");
316
    this._meta.updateTag({content: description}, "property='og:description'");
317
  }
318

    
319
  private updateTitle(title: string) {
320
    var _title = ((title.length > 50) ? title.substring(0, 50) : title);
321
    this._title.setTitle(_title);
322
    this._meta.updateTag({content: _title}, "property='og:title'");
323
  }
324

    
325
  private updateUrl(url: string) {
326
    this._meta.updateTag({content: url}, "property='og:url'");
327
  }
328
}
(3-3/5)