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

    
11
import {EnvProperties}                                   from '../../../openaireLibrary/utils/properties/env-properties';
12
import {EmailService}                                    from '../../../openaireLibrary/utils/email/email.service';
13
import {CommunityService}                                from "../../../openaireLibrary/connect/community/community.service";
14
import {ErrorCodes}                                      from '../../../openaireLibrary/utils/properties/errorCodes';
15

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

    
21
export class InviteComponent implements OnInit {
22

    
23
  @Input() longView: boolean = true;
24
  @Input() communityId = null;
25

    
26
  private properties: EnvProperties = null;
27

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

    
36
  public email: Email;
37
  public body: Body;
38
  public recipients: string;
39

    
40
  public areValid: boolean = true;
41

    
42
  private ckeditorContent: string;
43

    
44
  // 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>';
45
  public defaultBody ='';
46

    
47
  public communityIdParam = {};
48
  public status: number = 1;
49
  public errorCodes: ErrorCodes;
50

    
51
  constructor (
52
      private element: ElementRef,
53
      private route: ActivatedRoute,
54
      private _router: Router,
55
      public _fb: FormBuilder,
56
      private _emailService: EmailService,
57
      private _communityService: CommunityService) {
58

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

    
71

    
72
  public ngOnInit() {
73
      this.route.data.subscribe((data: { envSpecific: EnvProperties }) => {
74
          this.properties = data.envSpecific;
75
          this.errorMessage = "";
76
          this.missingCommunityId = "";
77
          this.status = this.errorCodes.LOADING;
78
          if (this.communityId != null && this.communityId != '') {
79
            this._communityService.getCommunity(this.properties, this.properties.communityAPI+this.communityId).subscribe (
80
              community => {
81
                this.community = community;
82

    
83
                this.defaultBody = '<p>You are invited to subscribe to <a href="https://beta.' + this.communityId + '.openaire.eu/">' + this.community.title + '</a> dashboard.'
84
                                   + '<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>';
85

    
86
                 // TODO move the initialisation
87
                 this.body = {/*salutation: "Dear Sir/Madame,",*/ fromMessage: ", on behalf of ", fromName: "", paragraphs: this.defaultBody, /*closing: "Kind regards,",*/ signature: "OpenAIRE team", ps: ""};
88
                 this.email = {body: "", subject: "[OpenAIRE-Connect] " + community.title, recipients: []};
89
                 this.recipients = "";
90

    
91
                 this.status = this.errorCodes.DONE;
92
              },
93
              error => this.handleError(error)
94
            );
95

    
96
          } else {
97
            this.status = this.errorCodes.DONE;
98
            this.missingCommunityId = "There is no community selected!";
99
          }
100

    
101
          this.scroll();
102
      });
103
  }
104

    
105
  public scroll() {
106
    console.info("scroll into view");
107
    if (typeof document !== 'undefined') {
108
       this.element.nativeElement.scrollIntoView();
109
    }
110
  }
111

    
112
  public invite() {
113
      this.successfulSentMessage = "";
114
      this.inviteErrorMessage = "";
115
      this.status = this.errorCodes.LOADING;
116
      if (this.recipients != "") {
117
        if (this.validateEmails()) {
118
          this.composeEmail();
119
          console.log(this.email.body);
120

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

    
132
                this.body = {/*salutation: "Dear Sir/Madame,",*/ fromMessage: ", on behalf of ", fromName: "", paragraphs: this.defaultBody, /*closing: "Kind regards,",*/ signature: "OpenAIRE team", ps: ""};
133
                this.email = {body: "", subject: "[OpenAIRE-Connect] " + this.community.title, recipients: []};
134
                this.recipients = "";
135
              },
136
              error => {
137
                console.log(error);
138
                this.status = this.errorCodes.DONE;
139
                this.inviteErrorMessage = "There was an error sending emails. Please try again.";
140
              }
141
          );
142
        } else {
143
          this.scroll();
144
          this.status = this.errorCodes.DONE;
145
        }
146
      } else {
147
        this.showAddRecipientMessage = true;
148
        this.scroll();
149
        this.status = this.errorCodes.DONE;
150
      }
151
  }
152

    
153
  public resetMessages() {
154
      this.errorMessage = "";
155
      this.successfulSentMessage = "";
156
      this.inviteErrorMessage = "";
157
  }
158

    
159
  public validateEmails(): boolean {
160
      if (this.parseEmails()) {
161
          if (this.hasValidEmails()) {
162
            return this.areValid;
163
          }
164
      }
165
      this.areValid = false;
166
      return this.areValid;
167
  }
168

    
169
  public parseEmails(): boolean {
170
      let email = new Array<string>();
171

    
172
      // remove spaces
173
      this.recipients = this.recipients.replace(/\s/g, '');
174

    
175
      // remove commas
176
      email = this.recipients.split(",");
177

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

    
188
  private hasValidEmails(): boolean {
189
      let length = this.email.recipients.length;
190

    
191
      for(let i = 0; i < length; i++) {
192
          if (!this.emailValidator(this.email.recipients[i])){
193
              // TODO remove console message after final testing
194
              console.log("INVALID EMAIL");
195
              return false;
196
          }
197
      }
198
      // TODO remove console message after final testing
199
      console.log("ALL EMAILS ARE VALID");
200
      return true;
201
    }
202

    
203
  private emailValidator(email : any): boolean {
204
      if (email.match("^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$"))
205
          return true;
206
      else
207
          return false;
208
  }
209

    
210
  public composeEmail() {
211
      // this.email.subject = "[OpenAIRE-Connect] Community_name";
212
      this.email.body = this.formatEmailBody();
213
  }
214

    
215
  public formatEmailBody(): string {
216
      let fromMessageAndName = "";
217

    
218
      if (this.body.fromName != "") {
219
        fromMessageAndName = "<span>" + this.body.fromMessage + this.body.fromName + "</span>";
220
      }
221

    
222
      let formattedEmail = "<div style='font-size:14px;'>" + /*+ this.body.salutation + "<br><br>" +*/
223
       this.body.paragraphs +
224
      "<p>" /*+ this.body.closing + "<br>"*/ + this.body.signature + fromMessageAndName + "<br>" +
225
      "<a href='https://www.openaire.eu'>www.openaire.eu</a>" + "</p></div>";
226

    
227

    
228
      return formattedEmail;
229
  }
230

    
231
  public handleError(error) {
232
    if(error.status == '401') {
233
      this.status = this.errorCodes.FORBIDDEN;
234
    } else if(error.status == '403') {
235
      this.status = this.errorCodes.FORBIDDEN;
236
    } else if(error.status == '404') {
237
      this.status = this.errorCodes.NOT_FOUND;
238
    } else if(error.status == '500') {
239
      this.status = this.errorCodes.ERROR;
240
    } else {
241
      this.status = this.errorCodes.NOT_AVAILABLE;
242
    }
243
      console.log('Server responded: ' + error);
244
  }
245
}
(3-3/4)