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.init();
101
      });
102
      this.init();
103
    });
104
  }
105

    
106
  ngOnDestroy() {
107
    if (this.piwiksub) {
108
      this.piwiksub.unsubscribe();
109
    }
110
  }
111

    
112
  private init() {
113
    this.route.queryParams.subscribe(
114
      communityId => {
115
        //if(!this.communityId && typeof document !== 'undefined'){
116
        this.communityId = ConnectHelper.getCommunityFromDomain(this.properties.domain);
117
        if (!this.communityId) {
118
          this.communityId = communityId['communityId'];
119
        }
120

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

    
141
              this.body = Composer.initializeInvitationsBody(this.communityId, this.community.title, this.fullname);
142
              this.email = Composer.initializeInvitationsEmail(community.title);
143
              this.recipients = "";
144

    
145
              this.status = this.errorCodes.DONE;
146
            },
147
            error => {
148
              //this.handleError(error)
149
              this.handleError("Error getting community with id: " + this.communityId, error);
150
              this.status = this.errorMessages.getErrorCode(error.status);
151
            }
152
          );
153
        } else {
154
          this.status = this.errorCodes.DONE;
155
          this.missingCommunityId = "There is no community selected!";
156
        }
157

    
158
      });
159
    HelperFunctions.scroll();
160
  }
161

    
162
  private getPageContents() {
163
    this.helper.getPageHelpContents(this._router.url, this.properties, this.communityId).subscribe(contents => {
164
      this.pageContents = contents;
165
    })
166
  }
167

    
168
  private getDivContents() {
169
    this.helper.getDivHelpContents(this._router.url, this.properties, this.communityId).subscribe(contents => {
170
      this.divContents = contents;
171
    })
172
  }
173

    
174

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

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

    
191
            } else if(res > 1) {
192
              this.successfulSentMessage = res + " emails sent successfully!";
193
            } else {
194
              this.successfulSentMessage = res + " email sent successfully!";
195
            }*/
196

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

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

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

    
234
  public resetMessages() {
235
    this.errorMessage = "";
236
    this.successfulSentMessage = "";
237
    this.failureSentMessage = "";
238
    this.inviteErrorMessage = "";
239
  }
240

    
241
  public validateEmails(): boolean {
242
    if (this.parseEmails()) {
243
      if (Validator.hasValidEmails(this.email.recipients)) {
244
        return this.areValid;
245
      }
246
    }
247
    this.areValid = false;
248
    return this.areValid;
249
  }
250

    
251
  public parseEmails(): boolean {
252
    let email = new Array<string>();
253

    
254
    // remove spaces
255
    this.recipients = this.recipients.replace(/\s/g, '');
256

    
257
    // remove commas
258
    email = this.recipients.split(",");
259

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

    
269
  public composeEmail() {
270
    this.email.body = Composer.formatEmailBodyForInvitation(this.body);
271
  }
272

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

    
301
  private handleError(message: string, error) {
302
    console.error("Invite Page (or component): " + message, error);
303
  }
304

    
305
  private updateDescription(description: string) {
306
    this._meta.updateTag({content: description}, "name='description'");
307
    this._meta.updateTag({content: description}, "property='og:description'");
308
  }
309

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

    
316
  private updateUrl(url: string) {
317
    this._meta.updateTag({content: url}, "property='og:url'");
318
  }
319
}
(3-3/4)