connect/src/app/utils/subscribe/invite/invite.component.ts

335 lines
11 KiB
TypeScript

import {Component, Input, OnInit} from '@angular/core';
import {FormBuilder} from "@angular/forms";
import {ActivatedRoute, Router} from '@angular/router';
import {ConnectHelper} from '../../../openaireLibrary/connect/connectHelper';
import {Email} from '../../../openaireLibrary/utils/email/email';
import {Body} from '../../../openaireLibrary/utils/email/body';
import {Validator} from '../../../openaireLibrary/utils/email/validator';
import {Composer} from '../../../openaireLibrary/utils/email/composer';
import {EnvProperties} from '../../../openaireLibrary/utils/properties/env-properties';
import {EmailService} from '../../../openaireLibrary/utils/email/email.service';
import {CommunityService} from "../../../openaireLibrary/connect/community/community.service";
import {ErrorCodes} from '../../../openaireLibrary/utils/properties/errorCodes';
import {ErrorMessagesComponent} from '../../../openaireLibrary/utils/errorMessages.component';
import {Session, User} from '../../../openaireLibrary/login/utils/helper.class';
import {HelperFunctions} from "../../../openaireLibrary/utils/HelperFunctions.class";
import {HelperService} from "../../../openaireLibrary/utils/helper/helper.service";
import {Meta, Title} from "@angular/platform-browser";
import {SEOService} from "../../../openaireLibrary/sharedComponents/SEO/SEO.service";
import {PiwikService} from "../../../openaireLibrary/utils/piwik/piwik.service";
import {PiwikHelper} from "../../piwikHelper";
import {UserManagementService} from "../../../openaireLibrary/services/user-management.service";
import {Breadcrumb} from "../../../openaireLibrary/utils/breadcrumbs/breadcrumbs.component";
import {Subscriber, Subscription} from "rxjs";
import {properties} from "../../../../environments/environment";
@Component({
selector: 'invite',
templateUrl: './invite.component.html',
})
export class InviteComponent implements OnInit {
@Input() longView: boolean = true;
@Input() communityId = null;
@Input() buttonSizeSmall = true;
@Input() properties: EnvProperties;
public community = null;
//public showLoading: boolean = true;
public errorMessage: string = '';
public successfulSentMessage: string = '';
public successfulSentRecipients: string[] = [];
public failureSentMessage: string = '';
public failureSentRecipients: string[] = [];
public inviteErrorMessage: string = '';
public missingCommunityId: string = '';
public showAddRecipientMessage: boolean = false;
public showAddNameMessage: boolean = false;
public email: Email;
public body: Body;
public recipients: string;
public fullname: string;
public areValid: boolean = true;
private ckeditorContent: string;
// public defaultBody ='';
public communityIdParam = {};
public status: number = 1;
public errorCodes: ErrorCodes;
private errorMessages: ErrorMessagesComponent;
public pageContents = null;
public divContents = null;
public url: string = null;
public pageTitle: string = "Invite";
private user: User;
public breadcrumbs: Breadcrumb[] = [{name: 'home', route: '/'}, {name: 'invite'}];
subs: Subscription[] = [];
constructor(
private route: ActivatedRoute,
private _router: Router,
public _fb: FormBuilder,
private _emailService: EmailService,
private _communityService: CommunityService,
private helper: HelperService,
private _meta: Meta,
private _title: Title,
private seoService: SEOService,
private _piwikService: PiwikService,
private userManageService: UserManagementService) {
this.errorCodes = new ErrorCodes();
this.errorMessages = new ErrorMessagesComponent();
this.status = this.errorCodes.LOADING;
}
public ngOnInit() {
if(!this.properties) {
this.properties = properties;
}
if(this.properties) {
this.errorMessage = "";
this.missingCommunityId = "";
this.status = this.errorCodes.LOADING;
this.subs.push(this.userManageService.getUserInfo().subscribe(
user => {
this.user = user;
this.init();
},
error => {
this.init();
}
));
//this.init();
}
}
ngOnDestroy() {
for (let sub of this.subs) {
if (sub instanceof Subscriber) {
sub.unsubscribe();
}
}
}
private init() {
this.subs.push(this.route.queryParams.subscribe(
communityId => {
//if(!this.communityId && typeof document !== 'undefined'){
this.communityId = ConnectHelper.getCommunityFromDomain(this.properties.domain);
if (!this.communityId) {
this.communityId = communityId['communityId'];
}
if (this.longView) {
if (this.properties.enablePiwikTrack && (typeof document !== 'undefined')) {
this.subs.push(this._piwikService.trackView(this.properties, this.pageTitle, PiwikHelper.getSiteId(this.communityId, this.properties.environment)).subscribe());
}
this.url = this.properties.domain + this._router.url;
this.seoService.createLinkForCanonicalURL(this.url);
this.updateUrl(this.url);
this.updateTitle(this.pageTitle);
this.updateDescription("OpenAIRE - Connect, Community Gateway, research community, invite");
}
this.communityIdParam = (this.properties.environment != "development") ? {} : {communityId: this.communityId};
if (this.communityId != null && this.communityId != '') {
//this.getDivContents();
this.getPageContents();
this.subs.push(this._communityService.getCommunityAsObservable().subscribe(
community => {
this.community = community;
this.fullname = (this.user) ? this.user.fullname : null;
//console.log("Fullname from session " + Session.getUserFullName());
this.body = Composer.initializeInvitationsBody(this.communityId, this.community.title, this.fullname);
this.email = Composer.initializeInvitationsEmail(community.title);
this.recipients = "";
this.status = this.errorCodes.DONE;
},
error => {
//this.handleError(error)
this.handleError("Error getting community with id: " + this.communityId, error);
this.status = this.errorMessages.getErrorCode(error.status);
}
));
} else {
this.status = this.errorCodes.DONE;
this.missingCommunityId = "There is no community selected!";
}
}));
HelperFunctions.scroll();
}
private getPageContents() {
this.subs.push(this.helper.getPageHelpContents(this.properties, this.communityId, this._router.url).subscribe(contents => {
this.pageContents = contents;
}));
}
private getDivContents() {
this.subs.push(this.helper.getDivHelpContents(this.properties, this.communityId, this._router.url).subscribe(contents => {
this.divContents = contents;
}));
}
public invite() {
this.successfulSentMessage = "";
this.failureSentMessage = "";
this.inviteErrorMessage = "";
this.status = this.errorCodes.LOADING;
HelperFunctions.scroll();
if (!this.isEmpty(this.recipients) && this.body.fromName != "") {
if (this.validateEmails()) {
this.composeEmail();
this.subs.push(this._emailService.sendEmail(this.properties, this.email).subscribe(
res => {
this.status = this.errorCodes.DONE;
//console.log("Emails Sent: ",res);
/*if(res == 0) {
} else if(res > 1) {
this.successfulSentMessage = res + " emails sent successfully!";
} else {
this.successfulSentMessage = res + " email sent successfully!";
}*/
if (res['success']) {
this.successfulSentMessage = "Email sent successfully to: ";
this.successfulSentRecipients = res['success'];
}
if (res['failure']) {
this.failureSentMessage = "There was an error sending email to: ";
this.failureSentRecipients = res['failure'];
}
this.body = Composer.initializeInvitationsBody(this.communityId, this.community.title, this.fullname);
this.email = Composer.initializeInvitationsEmail(this.community.title);
this.recipients = "";
},
error => {
//console.log(error);
this.handleError("Error inviting emails: " + JSON.stringify(this.recipients) + " to community with id: " + this.communityId + " by: " + this.fullname, error);
this.status = this.errorCodes.DONE;
this.inviteErrorMessage = "There was an error sending emails. Please try again.";
}
));
} else {
this.email.recipients = [];
this.status = this.errorCodes.DONE;
}
} else {
this.showAddRecipientMessage = true;
this.status = this.errorCodes.DONE;
}
}
public isEmpty(data: string): boolean {
if (data != undefined && !data.replace(/\s/g, '').length)
return true;
else
return false;
}
public resetMessages() {
this.errorMessage = "";
this.successfulSentMessage = "";
this.failureSentMessage = "";
this.inviteErrorMessage = "";
}
public validateEmails(): boolean {
if (this.parseEmails()) {
if (Validator.hasValidEmails(this.email.recipients)) {
return this.areValid;
}
}
this.areValid = false;
return this.areValid;
}
public parseEmails(): boolean {
let email = new Array<string>();
// remove spaces
this.recipients = this.recipients.replace(/\s/g, '');
// remove commas
email = this.recipients.split(",");
// remove empty fields
for (let i = 0; i < email.length; i++) {
if (!(email[i] == "")) {
this.email.recipients.push(email[i]);
}
}
return true;
}
public composeEmail() {
this.email.body = Composer.formatEmailBodyForInvitation(this.body);
}
/*
public handleError(error) {
if(error.status == '401') {
this.status = this.errorCodes.FORBIDDEN;
} else if(error.status == '403') {
this.status = this.errorCodes.FORBIDDEN;
} else if(error.status == '404') {
this.status = this.errorCodes.NOT_FOUND;
} else if(error.status == '500') {
this.status = this.errorCodes.ERROR;
} else {
this.status = this.errorCodes.NOT_AVAILABLE;
}
console.log('Server responded: ' + error);
}
*/
allowEdit() {
if (!this.user) {
return false;
}
var email = this.user.email;
var index = -1;
if (email && this.community != null && this.community.managers != null) {
index = this.community.managers.indexOf(email);
}
return Session.isPortalAdministrator(this.user) || Session.isCommunityCurator(this.user) || index != -1;
}
private handleError(message: string, error) {
console.error("Invite Page (or component): " + message, error);
}
private updateDescription(description: string) {
this._meta.updateTag({content: description}, "name='description'");
this._meta.updateTag({content: description}, "property='og:description'");
}
private updateTitle(title: string) {
var _title = ((title.length > 50) ? title.substring(0, 50) : title);
this._title.setTitle(_title);
this._meta.updateTag({content: _title}, "property='og:title'");
}
private updateUrl(url: string) {
this._meta.updateTag({content: url}, "property='og:url'");
}
}