Project

General

Profile

1
import {Component, OnInit, Input, ElementRef}            from '@angular/core';
2
import {SimpleChanges, OnChanges}                        from '@angular/core';
3
import {FormGroup, FormArray, FormBuilder, Validators}   from "@angular/forms";
4
import {ActivatedRoute, Router}                          from '@angular/router';
5

    
6
import {ConnectHelper}                                   from '../../../openaireLibrary/connect/connectHelper';
7

    
8
import {Email}                                           from '../../../openaireLibrary/utils/email/email';
9
import {Body}                                            from '../../../openaireLibrary/utils/email/body';
10
import {Validator}                                       from '../../../openaireLibrary/utils/email/validator';
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 {Session} from '../../../openaireLibrary/login/utils/helper.class';
17

    
18
@Component({
19
    selector: 'invite',
20
    templateUrl: './invite.component.html',
21
})
22

    
23
export class InviteComponent implements OnInit {
24

    
25
  @Input() longView: boolean = true;
26
  @Input() communityId = null;
27

    
28
  private properties: EnvProperties = null;
29

    
30
  public community = null;
31
  //public showLoading: boolean = true;
32
  public errorMessage: string = '';
33
  public successfulSentMessage: string = '';
34
  public inviteErrorMessage: string = '';
35
  public missingCommunityId: string = '';
36
  public showAddRecipientMessage: boolean = false;
37
  public showAddNameMessage: boolean = false;
38

    
39
  public email: Email;
40
  public body: Body;
41
  public recipients: string;
42
  public fullname:string;
43

    
44
  public areValid: boolean = true;
45

    
46
  private ckeditorContent: string;
47

    
48
  // public defaultBody = '<p>OpenAIRE invites you to subscribe in <a href="https://beta.egi.openaire.eu">_Community_name_</a> dashboard. </p><p>The community dashboard is part of the <a href="https://beta.egi.openaire.eu">OpenAIRE-Connect</a> project.</p>';
49
  public defaultBody ='';
50

    
51
  public communityIdParam = {};
52
  public status: number = 1;
53
  public errorCodes: ErrorCodes;
54

    
55
  constructor (
56
      private element: ElementRef,
57
      private route: ActivatedRoute,
58
      private _router: Router,
59
      public _fb: FormBuilder,
60
      private _emailService: EmailService,
61
      private _communityService: CommunityService) {
62

    
63
        this.route.queryParams.subscribe(
64
          communityId => {
65
                this.communityId = communityId['communityId'];
66
                if(!this.communityId){
67
                  this.communityId  = ConnectHelper.getCommunityFromDomain(document.location.hostname);
68
                }
69
                this.communityIdParam = (ConnectHelper.isProduction(document.location.hostname))?{}:{communityId:this.communityId};
70
          });
71
          this.errorCodes = new ErrorCodes();
72
          this.status = this.errorCodes.LOADING;
73
      }
74

    
75

    
76
  public ngOnInit() {
77
      this.route.data.subscribe((data: { envSpecific: EnvProperties }) => {
78
          this.properties = data.envSpecific;
79
          this.errorMessage = "";
80
          this.missingCommunityId = "";
81
          this.status = this.errorCodes.LOADING;
82
          if (this.communityId != null && this.communityId != '') {
83
            this._communityService.getCommunity(this.properties, this.properties.communityAPI+this.communityId).subscribe (
84
              community => {
85
                this.community = community;
86
                this.fullname = Session.getUserFullName();
87
                console.log("Fullname from session " + Session.getUserFullName());
88
                this.defaultBody = '<p>You are invited to subscribe to <a href="https://beta.' + this.communityId + '.openaire.eu/">' + this.community.title + '</a> dashboard.'
89
                                   + '<br>The purpose of this dashboard  is to gather, link &amp; monitor the research results related to your community.</p><p>The community dashboard is part of the <a href="https://connect.openaire.eu/">OpenAIRE-Connect</a> project and currently is in BETA version.</p>';
90

    
91
                 // TODO move the initialisation
92
                 this.body = {fromMessage: ", on behalf of ", fromName: this.fullname, paragraphs: this.defaultBody, signature: "OpenAIRE team", note: ""};
93
                 this.email = {body: "", subject: "[OpenAIRE-Connect] " + community.title, recipients: []};
94
                 this.recipients = "";
95

    
96
                 this.status = this.errorCodes.DONE;
97
              },
98
              error => this.handleError(error)
99
            );
100
          } else {
101
            this.status = this.errorCodes.DONE;
102
            this.missingCommunityId = "There is no community selected!";
103
          }
104

    
105
          this.scroll();
106
      });
107
  }
108

    
109
  public scroll() {
110
    console.info("scroll into view");
111
    if (typeof document !== 'undefined') {
112
       this.element.nativeElement.scrollIntoView();
113
    }
114
  }
115

    
116
  public invite() {
117
      this.successfulSentMessage = "";
118
      this.inviteErrorMessage = "";
119
      this.status = this.errorCodes.LOADING;
120
      if (this.recipients != "" && this.body.fromName != "") {
121
        if (this.validateEmails()) {
122
          this.composeEmail();
123
          console.log(this.email.body);
124

    
125
          this._emailService.sendEmail(this.properties.adminToolsAPIURL + "/sendMail/", this.email).subscribe(
126
              res => {
127
                console.log("The email has been sent successfully!");
128
                this.status = this.errorCodes.DONE;
129
                console.log("Emails Sent: "+res);
130
                if(res > 1) {
131
                  this.successfulSentMessage = res + " emails sent successfully!";
132
                } else {
133
                  this.successfulSentMessage = res + " email sent successfully!";
134
                }
135

    
136
                this.body = {fromMessage: ", on behalf of ", fromName: this.fullname, paragraphs: this.defaultBody, signature: "OpenAIRE team", note: ""};
137
                this.email = {body: "", subject: "[OpenAIRE-Connect] " + this.community.title, recipients: []};
138
                this.recipients = "";
139
              },
140
              error => {
141
                console.log(error);
142
                this.status = this.errorCodes.DONE;
143
                this.inviteErrorMessage = "There was an error sending emails. Please try again.";
144
              }
145
          );
146
        } else {
147
          this.scroll();
148
          this.status = this.errorCodes.DONE;
149
        }
150
      } else {
151
        this.showAddRecipientMessage = true;
152
        this.scroll();
153
        this.status = this.errorCodes.DONE;
154
      }
155
  }
156

    
157
  public resetMessages() {
158
      this.errorMessage = "";
159
      this.successfulSentMessage = "";
160
      this.inviteErrorMessage = "";
161
  }
162

    
163
  public validateEmails(): boolean {
164
      if (this.parseEmails()) {
165
          if (Validator.hasValidEmails(this.email.recipients)) {
166
            return this.areValid;
167
          }
168
      }
169
      this.areValid = false;
170
      return this.areValid;
171
  }
172

    
173
  public parseEmails(): boolean {
174
      let email = new Array<string>();
175

    
176
      // remove spaces
177
      this.recipients = this.recipients.replace(/\s/g, '');
178

    
179
      // remove commas
180
      email = this.recipients.split(",");
181

    
182
      // remove empty fields
183
      for (let i = 0; i < email.length; i++) {
184
        if (!(email[i] == "")) {
185
          this.email.recipients.push(email[i]);
186
        }
187
      }
188
      console.log(this.email.recipients);
189
      return true;
190
  }
191

    
192
  public composeEmail() {
193
      // this.email.subject = "[OpenAIRE-Connect] Community_name";
194
      this.email.body = this.formatEmailBody();
195
  }
196

    
197
  public formatEmailBody(): string {
198
      let fromMessageAndName = "";
199

    
200
      if (this.body.fromName != "") {
201
        fromMessageAndName = "<span>" + this.body.fromMessage + this.body.fromName + "</span>";
202
      }
203

    
204
      let formattedEmail = "<div style='font-size:14px;'>"
205
                           + this.body.paragraphs
206
                           + "<p>" + this.body.signature + fromMessageAndName + "<br>"
207
                           + "<a href='https://www.openaire.eu'>www.openaire.eu</a>"
208
                           + "</p>"
209
                           + "</div>";
210

    
211
      return formattedEmail;
212
  }
213

    
214
  public handleError(error) {
215
    if(error.status == '401') {
216
      this.status = this.errorCodes.FORBIDDEN;
217
    } else if(error.status == '403') {
218
      this.status = this.errorCodes.FORBIDDEN;
219
    } else if(error.status == '404') {
220
      this.status = this.errorCodes.NOT_FOUND;
221
    } else if(error.status == '500') {
222
      this.status = this.errorCodes.ERROR;
223
    } else {
224
      this.status = this.errorCodes.NOT_AVAILABLE;
225
    }
226
      console.log('Server responded: ' + error);
227
  }
228
  allowEdit(){
229
    var email = Session.getUserEmail();
230
    var index =-1;
231
    if(email && this.community != null && this.community.managers != null){
232
        index = this.community.managers.indexOf(email);
233
    }
234

    
235
    return Session.isPortalAdministrator() || Session.isCommunityCurator()
236
  }
237
}
(3-3/4)