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
import {Breadcrumb} from "../../../openaireLibrary/utils/breadcrumbs/breadcrumbs.component";
26

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

    
32
export class InviteComponent implements OnInit {
33

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

    
38
  @Input() properties: EnvProperties;
39

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

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

    
57
  public areValid: boolean = true;
58

    
59
  private ckeditorContent: string;
60

    
61
  // public defaultBody ='';
62

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

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

    
75
  public breadcrumbs: Breadcrumb[] = [{name: 'home', route: '/'}, {name: 'invite'}];
76

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

    
90
    this.errorCodes = new ErrorCodes();
91
    this.errorMessages = new ErrorMessagesComponent();
92
    this.status = this.errorCodes.LOADING;
93
  }
94

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

    
118
  ngOnDestroy() {
119
    if (this.piwiksub) {
120
      this.piwiksub.unsubscribe();
121
    }
122
  }
123

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

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

    
153
              this.body = Composer.initializeInvitationsBody(this.communityId, this.community.title, this.fullname);
154
              this.email = Composer.initializeInvitationsEmail(community.title);
155
              this.recipients = "";
156

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

    
170
      });
171
    HelperFunctions.scroll();
172
  }
173

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

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

    
186

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

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

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

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

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

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

    
246
  public resetMessages() {
247
    this.errorMessage = "";
248
    this.successfulSentMessage = "";
249
    this.failureSentMessage = "";
250
    this.inviteErrorMessage = "";
251
  }
252

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

    
263
  public parseEmails(): boolean {
264
    let email = new Array<string>();
265

    
266
    // remove spaces
267
    this.recipients = this.recipients.replace(/\s/g, '');
268

    
269
    // remove commas
270
    email = this.recipients.split(",");
271

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

    
281
  public composeEmail() {
282
    this.email.body = Composer.formatEmailBodyForInvitation(this.body);
283
  }
284

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

    
313
  private handleError(message: string, error) {
314
    console.error("Invite Page (or component): " + message, error);
315
  }
316

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

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

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