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} 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

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

    
30
export class InviteComponent implements OnInit {
31

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

    
36
  private properties: EnvProperties = null;
37

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

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

    
55
  public areValid: boolean = true;
56

    
57
  private ckeditorContent: string;
58

    
59
  // public defaultBody ='';
60

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

    
68
  public url: string = null;
69
  public pageTitle: string = "Invite";
70
  piwiksub: any;
71

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

    
84
    this.errorCodes = new ErrorCodes();
85
    this.errorMessages = new ErrorMessagesComponent();
86
    this.status = this.errorCodes.LOADING;
87
  }
88

    
89
  public ngOnInit() {
90
    this.route.data.subscribe((data: { envSpecific: EnvProperties }) => {
91
      this.properties = data.envSpecific;
92
      this.errorMessage = "";
93
      this.missingCommunityId = "";
94
      this.status = this.errorCodes.LOADING;
95
      this.route.queryParams.subscribe(
96
        communityId => {
97
          //if(!this.communityId && typeof document !== 'undefined'){
98
          this.communityId = ConnectHelper.getCommunityFromDomain(this.properties.domain);
99
          if (!this.communityId) {
100
            this.communityId = communityId['communityId'];
101
          }
102

    
103
          if (this.properties.enablePiwikTrack && (typeof document !== 'undefined')) {
104
            this.piwiksub = this._piwikService.trackView(this.properties, this.pageTitle, PiwikHelper.getSiteId(this.communityId,this.properties.environment)).subscribe();
105
          }
106
          this.url = this.properties.baseLink + this._router.url;
107
          this.seoService.createLinkForCanonicalURL(this.url);
108
          this.updateUrl(this.url);
109
          this.updateTitle(this.pageTitle);
110
          this.updateDescription("OpenAIRE - Connect, Community Gateway, research community, invite");
111

    
112
          this.communityIdParam = (this.properties.environment != "development") ? {} : {communityId: this.communityId};
113
          if (this.communityId != null && this.communityId != '') {
114
            //this.getDivContents();
115
            this.getPageContents();
116
            this._communityService.getCommunity(this.properties, this.properties.communityAPI + this.communityId).subscribe(
117
              community => {
118
                this.community = community;
119
                this.fullname = Session.getUserFullName();
120
                //console.log("Fullname from session " + Session.getUserFullName());
121

    
122
                this.body = Composer.initializeInvitationsBody(this.communityId, this.community.title, this.fullname);
123
                this.email = Composer.initializeInvitationsEmail(community.title);
124
                this.recipients = "";
125

    
126
                this.status = this.errorCodes.DONE;
127
              },
128
              error => {
129
                //this.handleError(error)
130
                this.handleError("Error getting community with id: " + this.communityId, error);
131
                this.status = this.errorMessages.getErrorCode(error.status);
132
              }
133
            );
134
          } else {
135
            this.status = this.errorCodes.DONE;
136
            this.missingCommunityId = "There is no community selected!";
137
          }
138

    
139
        });
140

    
141
      HelperFunctions.scroll();
142
    });
143
  }
144

    
145
  ngOnDestroy() {
146
    if(this.piwiksub) {
147
      this.piwiksub.unsubscribe();
148
    }
149
  }
150

    
151
  private getPageContents() {
152
    this.helper.getPageHelpContents(this._router.url, this.properties, this.communityId).subscribe(contents => {
153
      this.pageContents = contents;
154
    })
155
  }
156

    
157
  private getDivContents() {
158
    this.helper.getDivHelpContents(this._router.url, this.properties, this.communityId).subscribe(contents => {
159
      this.divContents = contents;
160
    })
161
  }
162

    
163

    
164
  public invite() {
165
    this.successfulSentMessage = "";
166
    this.failureSentMessage = "";
167
    this.inviteErrorMessage = "";
168
    this.status = this.errorCodes.LOADING;
169
    HelperFunctions.scroll();
170
    if (!this.isEmpty(this.recipients) && this.body.fromName != "") {
171
      if (this.validateEmails()) {
172
        this.composeEmail();
173

    
174
        this._emailService.sendEmail(this.properties.adminToolsAPIURL + "/sendMail/", this.email).subscribe(
175
          res => {
176
            this.status = this.errorCodes.DONE;
177
            //console.log("Emails Sent: ",res);
178
            /*if(res == 0) {
179

    
180
            } else if(res > 1) {
181
              this.successfulSentMessage = res + " emails sent successfully!";
182
            } else {
183
              this.successfulSentMessage = res + " email sent successfully!";
184
            }*/
185

    
186
            if (res['success']) {
187
              this.successfulSentMessage = "Email sent successfully to: ";
188
              this.successfulSentRecipients = res['success'];
189
            }
190
            if (res['failure']) {
191
              this.failureSentMessage = "There was an error sending email to: ";
192
              this.failureSentRecipients = res['failure'];
193
            }
194

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

    
216
  public isEmpty(data: string): boolean {
217
    if (data != undefined && !data.replace(/\s/g, '').length)
218
      return true;
219
    else
220
      return false;
221
  }
222

    
223
  public resetMessages() {
224
    this.errorMessage = "";
225
    this.successfulSentMessage = "";
226
    this.failureSentMessage = "";
227
    this.inviteErrorMessage = "";
228
  }
229

    
230
  public validateEmails(): boolean {
231
    if (this.parseEmails()) {
232
      if (Validator.hasValidEmails(this.email.recipients)) {
233
        return this.areValid;
234
      }
235
    }
236
    this.areValid = false;
237
    return this.areValid;
238
  }
239

    
240
  public parseEmails(): boolean {
241
    let email = new Array<string>();
242

    
243
    // remove spaces
244
    this.recipients = this.recipients.replace(/\s/g, '');
245

    
246
    // remove commas
247
    email = this.recipients.split(",");
248

    
249
    // remove empty fields
250
    for (let i = 0; i < email.length; i++) {
251
      if (!(email[i] == "")) {
252
        this.email.recipients.push(email[i]);
253
      }
254
    }
255
    return true;
256
  }
257

    
258
  public composeEmail() {
259
    this.email.body = Composer.formatEmailBodyForInvitation(this.body);
260
  }
261

    
262
  /*
263
    public handleError(error) {
264
      if(error.status == '401') {
265
        this.status = this.errorCodes.FORBIDDEN;
266
      } else if(error.status == '403') {
267
        this.status = this.errorCodes.FORBIDDEN;
268
      } else if(error.status == '404') {
269
        this.status = this.errorCodes.NOT_FOUND;
270
      } else if(error.status == '500') {
271
        this.status = this.errorCodes.ERROR;
272
      } else {
273
        this.status = this.errorCodes.NOT_AVAILABLE;
274
      }
275
        console.log('Server responded: ' + error);
276
    }
277
  */
278
  allowEdit() {
279
    var email = Session.getUserEmail();
280
    var index = -1;
281
    if (email && this.community != null && this.community.managers != null) {
282
      index = this.community.managers.indexOf(email);
283
    }
284

    
285
    return Session.isPortalAdministrator() || Session.isCommunityCurator() || index != -1;
286

    
287

    
288
  }
289

    
290
  private handleError(message: string, error) {
291
    console.error("Invite Page (or component): " + message, error);
292
  }
293

    
294
  private updateDescription(description: string) {
295
    this._meta.updateTag({content: description}, "name='description'");
296
    this._meta.updateTag({content: description}, "property='og:description'");
297
  }
298

    
299
  private updateTitle(title: string) {
300
    var _title = ((title.length > 50) ? title.substring(0, 50) : title);
301
    this._title.setTitle(_title);
302
    this._meta.updateTag({content: _title}, "property='og:title'");
303
  }
304

    
305
  private updateUrl(url: string) {
306
    this._meta.updateTag({content: url}, "property='og:url'");
307
  }
308
}
(3-3/4)