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
import {Subscriber, Subscription} from "rxjs";
27
import {properties} from "../../../../environments/environment";
28

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

    
34
export class InviteComponent implements OnInit {
35

    
36
  @Input() longView: boolean = true;
37
  @Input() communityId = null;
38
  @Input() buttonSizeSmall = true;
39

    
40
  @Input() properties: EnvProperties;
41

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

    
54
  public email: Email;
55
  public body: Body;
56
  public recipients: string;
57
  public fullname: string;
58

    
59
  public areValid: boolean = true;
60

    
61
  private ckeditorContent: string;
62

    
63
  // public defaultBody ='';
64

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

    
72
  public url: string = null;
73
  public pageTitle: string = "Invite";
74
  private user: User;
75

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

    
78
  subs: Subscription[] = [];
79

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

    
93
    this.errorCodes = new ErrorCodes();
94
    this.errorMessages = new ErrorMessagesComponent();
95
    this.status = this.errorCodes.LOADING;
96
  }
97

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

    
119
  ngOnDestroy() {
120
    for (let sub of this.subs) {
121
      if (sub instanceof Subscriber) {
122
        sub.unsubscribe();
123
      }
124
    }
125
  }
126

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

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

    
156
              this.body = Composer.initializeInvitationsBody(this.communityId, this.community.title, this.fullname);
157
              this.email = Composer.initializeInvitationsEmail(community.title);
158
              this.recipients = "";
159

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

    
173
      }));
174
  }
175

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

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

    
188

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

    
199
        this.subs.push(this._emailService.sendEmail(this.properties, this.email).subscribe(
200
          res => {
201
            this.status = this.errorCodes.DONE;
202
            if (res['success']) {
203
              this.successfulSentMessage = "Email sent successfully to: ";
204
              this.successfulSentRecipients = res['success'];
205
            }
206
            if (res['failure']) {
207
              this.failureSentMessage = "There was an error sending email to: ";
208
              this.failureSentRecipients = res['failure'];
209
            }
210

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

    
232
  public isEmpty(data: string): boolean {
233
    return data != undefined && !data.replace(/\s/g, '').length;
234
  }
235

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

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

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

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

    
259
    // remove commas
260
    email = this.recipients.split(",");
261

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

    
271
  public composeEmail() {
272
    this.email.body = Composer.formatEmailBodyForInvitation(this.body);
273
  }
274
  
275
  allowEdit() {
276
    if (!this.user) {
277
      return false;
278
    }
279
    var email = this.user.email;
280
    var index = -1;
281
    if (email && this.community != null && this.community.managers != null) {
282
      index = this.community.managers.indexOf(email);
283
    }
284
    return Session.isPortalAdministrator(this.user) || Session.isCommunityCurator(this.user) || index != -1;
285
  }
286

    
287
  private handleError(message: string, error) {
288
    console.error("Invite Page (or component): " + message, error);
289
  }
290

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

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

    
302
  private updateUrl(url: string) {
303
    this._meta.updateTag({content: url}, "property='og:url'");
304
  }
305
}
(3-3/5)