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
  private properties: EnvProperties = null;
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
      this.properties = data.envSpecific;
95
      this.errorMessage = "";
96
      this.missingCommunityId = "";
97
      this.status = this.errorCodes.LOADING;
98
      this.userManageService.getUserInfo(this.properties.userInfoUrl).subscribe(user => {
99
        this.user = user;
100
        this.route.queryParams.subscribe(
101
          communityId => {
102
            //if(!this.communityId && typeof document !== 'undefined'){
103
            this.communityId = ConnectHelper.getCommunityFromDomain(this.properties.domain);
104
            if (!this.communityId) {
105
              this.communityId = communityId['communityId'];
106
            }
107

    
108
            if (this.longView) {
109
              if (this.properties.enablePiwikTrack && (typeof document !== 'undefined')) {
110
                this.piwiksub = this._piwikService.trackView(this.properties, this.pageTitle, PiwikHelper.getSiteId(this.communityId, this.properties.environment)).subscribe();
111
              }
112
              this.url = this.properties.baseLink + this._router.url;
113
              this.seoService.createLinkForCanonicalURL(this.url);
114
              this.updateUrl(this.url);
115
              this.updateTitle(this.pageTitle);
116
              this.updateDescription("OpenAIRE - Connect, Community Gateway, research community, invite");
117
            }
118
            this.communityIdParam = (this.properties.environment != "development") ? {} : {communityId: this.communityId};
119
            if (this.communityId != null && this.communityId != '') {
120
              //this.getDivContents();
121
              this.getPageContents();
122
              this._communityService.getCommunity(this.properties, this.properties.communityAPI + this.communityId).subscribe(
123
                community => {
124
                  this.community = community;
125
                  this.fullname = this.user.fullname;
126
                  //console.log("Fullname from session " + Session.getUserFullName());
127

    
128
                  this.body = Composer.initializeInvitationsBody(this.communityId, this.community.title, this.fullname);
129
                  this.email = Composer.initializeInvitationsEmail(community.title);
130
                  this.recipients = "";
131

    
132
                  this.status = this.errorCodes.DONE;
133
                },
134
                error => {
135
                  //this.handleError(error)
136
                  this.handleError("Error getting community with id: " + this.communityId, error);
137
                  this.status = this.errorMessages.getErrorCode(error.status);
138
                }
139
              );
140
            } else {
141
              this.status = this.errorCodes.DONE;
142
              this.missingCommunityId = "There is no community selected!";
143
            }
144

    
145
          });
146

    
147
        HelperFunctions.scroll();
148
      });
149
    });
150
  }
151

    
152
  ngOnDestroy() {
153
    if (this.piwiksub) {
154
      this.piwiksub.unsubscribe();
155
    }
156
  }
157

    
158
  private getPageContents() {
159
    this.helper.getPageHelpContents(this._router.url, this.properties, this.communityId).subscribe(contents => {
160
      this.pageContents = contents;
161
    })
162
  }
163

    
164
  private getDivContents() {
165
    this.helper.getDivHelpContents(this._router.url, this.properties, this.communityId).subscribe(contents => {
166
      this.divContents = contents;
167
    })
168
  }
169

    
170

    
171
  public invite() {
172
    this.successfulSentMessage = "";
173
    this.failureSentMessage = "";
174
    this.inviteErrorMessage = "";
175
    this.status = this.errorCodes.LOADING;
176
    HelperFunctions.scroll();
177
    if (!this.isEmpty(this.recipients) && this.body.fromName != "") {
178
      if (this.validateEmails()) {
179
        this.composeEmail();
180

    
181
        this._emailService.sendEmail(this.properties.adminToolsAPIURL + "/sendMail/", this.email).subscribe(
182
          res => {
183
            this.status = this.errorCodes.DONE;
184
            //console.log("Emails Sent: ",res);
185
            /*if(res == 0) {
186

    
187
            } else if(res > 1) {
188
              this.successfulSentMessage = res + " emails sent successfully!";
189
            } else {
190
              this.successfulSentMessage = res + " email sent successfully!";
191
            }*/
192

    
193
            if (res['success']) {
194
              this.successfulSentMessage = "Email sent successfully to: ";
195
              this.successfulSentRecipients = res['success'];
196
            }
197
            if (res['failure']) {
198
              this.failureSentMessage = "There was an error sending email to: ";
199
              this.failureSentRecipients = res['failure'];
200
            }
201

    
202
            this.body = Composer.initializeInvitationsBody(this.communityId, this.community.title, this.fullname);
203
            this.email = Composer.initializeInvitationsEmail(this.community.title);
204
            this.recipients = "";
205
          },
206
          error => {
207
            //console.log(error);
208
            this.handleError("Error inviting emails: " + JSON.stringify(this.recipients) + " to community with id: " + this.communityId + " by: " + this.fullname, error);
209
            this.status = this.errorCodes.DONE;
210
            this.inviteErrorMessage = "There was an error sending emails. Please try again.";
211
          }
212
        );
213
      } else {
214
        this.email.recipients = [];
215
        this.status = this.errorCodes.DONE;
216
      }
217
    } else {
218
      this.showAddRecipientMessage = true;
219
      this.status = this.errorCodes.DONE;
220
    }
221
  }
222

    
223
  public isEmpty(data: string): boolean {
224
    if (data != undefined && !data.replace(/\s/g, '').length)
225
      return true;
226
    else
227
      return false;
228
  }
229

    
230
  public resetMessages() {
231
    this.errorMessage = "";
232
    this.successfulSentMessage = "";
233
    this.failureSentMessage = "";
234
    this.inviteErrorMessage = "";
235
  }
236

    
237
  public validateEmails(): boolean {
238
    if (this.parseEmails()) {
239
      if (Validator.hasValidEmails(this.email.recipients)) {
240
        return this.areValid;
241
      }
242
    }
243
    this.areValid = false;
244
    return this.areValid;
245
  }
246

    
247
  public parseEmails(): boolean {
248
    let email = new Array<string>();
249

    
250
    // remove spaces
251
    this.recipients = this.recipients.replace(/\s/g, '');
252

    
253
    // remove commas
254
    email = this.recipients.split(",");
255

    
256
    // remove empty fields
257
    for (let i = 0; i < email.length; i++) {
258
      if (!(email[i] == "")) {
259
        this.email.recipients.push(email[i]);
260
      }
261
    }
262
    return true;
263
  }
264

    
265
  public composeEmail() {
266
    this.email.body = Composer.formatEmailBodyForInvitation(this.body);
267
  }
268

    
269
  /*
270
    public handleError(error) {
271
      if(error.status == '401') {
272
        this.status = this.errorCodes.FORBIDDEN;
273
      } else if(error.status == '403') {
274
        this.status = this.errorCodes.FORBIDDEN;
275
      } else if(error.status == '404') {
276
        this.status = this.errorCodes.NOT_FOUND;
277
      } else if(error.status == '500') {
278
        this.status = this.errorCodes.ERROR;
279
      } else {
280
        this.status = this.errorCodes.NOT_AVAILABLE;
281
      }
282
        console.log('Server responded: ' + error);
283
    }
284
  */
285
  allowEdit() {
286
    if (!this.user) {
287
      return false;
288
    }
289
    var email = this.user.email;
290
    var index = -1;
291
    if (email && this.community != null && this.community.managers != null) {
292
      index = this.community.managers.indexOf(email);
293
    }
294
    return Session.isPortalAdministrator(this.user) || Session.isCommunityCurator(this.user) || index != -1;
295
  }
296

    
297
  private handleError(message: string, error) {
298
    console.error("Invite Page (or component): " + message, error);
299
  }
300

    
301
  private updateDescription(description: string) {
302
    this._meta.updateTag({content: description}, "name='description'");
303
    this._meta.updateTag({content: description}, "property='og:description'");
304
  }
305

    
306
  private updateTitle(title: string) {
307
    var _title = ((title.length > 50) ? title.substring(0, 50) : title);
308
    this._title.setTitle(_title);
309
    this._meta.updateTag({content: _title}, "property='og:title'");
310
  }
311

    
312
  private updateUrl(url: string) {
313
    this._meta.updateTag({content: url}, "property='og:url'");
314
  }
315
}
(3-3/4)