//Imoprting the libraries
import { Component, OnInit } from '@angular/core';
import { DialogService, DynamicDialogConfig } from 'primeng/api';
import dayGridPlugin from '@fullcalendar/daygrid';
import timeGridPlugin from '@fullcalendar/timegrid';
import interactionPlugin from '@fullcalendar/interaction';
import { CookieService } from 'ngx-cookie-service';
import { debug } from 'util';
import { ActivatedRoute } from '@angular/router';
import { ThrowStmt } from '@angular/compiler';
//Importing the components
import { ContactLoadTemplateComponent } from '../contact-load-template/contact-load-template.component';
import { ContactSaveTemplateComponent } from '../contact-save-template/contact-save-template.component';
import { ContactCreateEmailSignatureComponent } from '../contact-create-email-signature/contact-create-email-signature.component';
//Importing the core classes
import { IEmailAttachments } from '../../../shared/core/IEmailAttachments';
import { EmailDetails } from '../../../shared/core/emailDetails';
import { IStaffs } from '../../../shared/core/IStaffs';
import { IEmailBodyDetails } from '../../../shared/core/IEmailBodyDetails';
import { IEmailAddress } from '../../../shared/core/IEmailAddress';
import { IInternelEmailType } from '../../../shared/core/IInternelEmailType';
import { IEmailSignature } from '../../../shared/core/IEmailSignature';
import { IAssociateRecords } from '../../../shared/core/IAssociateRecords ';
//Importing the service classes
import { EmailsService } from '../../../shared/service/emails.service';
import { AutomationService } from '../../../shared/service/automation.service';
import { IAutomation } from '../../../shared/core/automation/IAutomation';
@Component({
selector: 'app-contact-create-email',
templateUrl: './contact-create-email.component.html',
styleUrls: ['./contact-create-email.component.scss'],
providers: [EmailsService]
})
export class ContactCreateEmailComponent implements OnInit {
public editor;
public editorContent = `
I am Example content
`;
public editorOptions = {
placeholder: "insert content..."
};
events: any = [];
options: any;
startDate = "2016-01-01";
//Display cc state
displayCCFields: boolean = false;
displayBCCFields: boolean = false;
//Variables to hold the attachments
attachmentFiles: string[] = [];
attachmentImageNames: string[] = [];
attachmentList: IEmailAttachments[] = [];
sampleIdValue: number = 0;
//Varibales for the auto complete
filteredEmailsMultiple: any[];
//To email list
toEmailsList: IEmailAddress[] = [];
ccEmailsList: IEmailAddress[] = [];
bccEmailsList: IEmailAddress[] = [];
//Email send button status
disableSendNowButton: boolean = true;
//Variables to get the email data
emailSubject: string = "";
//Variables to hold the create task and automation checkboxes
emailCreateTask: string[] = [];
emailAutomation: string[] = [];
staffId: number;
IStaffs: IStaffs[];
//Variable to hold the from email
fromEmail: IStaffs;
//Get all the signatures
IEmailSignature: IEmailSignature[];
selectedSignature: IEmailSignature;
sendLaterDateState: boolean = false;
sendEmailLaterDate: string;
companyContactId: number;
// Associate records
IAssociateRecords: IAssociateRecords[];
// contactId
contactId: number;
// Associate Variables
ContactSelectedValues: string;
CompanySelectedValues: string;
// Bussiness Dates
bussinessDates: number;
//Variable to hold the reply mail id
replyId: number = 0;
defualtUserEMail: string = '';
defualtUserName: string = '';
displayInputNumber: boolean = false;
userEnteredValue: number = 0;
businessdayDropdown:any = '1';
customSelected:boolean = false;
showAutomationList:boolean;
automationList: IAutomation[] = [];
constructor(public dialogService: DialogService, private emailsService: EmailsService, private cookieService: CookieService, private route: ActivatedRoute, public config: DynamicDialogConfig
,private automationService:AutomationService) { }
ngOnInit() {
/** get parameter contactId */
this.route.paramMap.subscribe(params => {
this.contactId = +params.get("contactId")
})
if (this.config.data['companyContactId']) {
this.companyContactId = this.config.data['companyContactId'];
}
if (this.config.data['replyEmailId']) {
this.replyId = +this.config.data['replyEmailId'];
}
if (this.config.data['defualtUserEMail']) {
this.defualtUserEMail = this.config.data['defualtUserEMail'];
}
if (this.config.data['defualtUserName']) {
this.defualtUserName = this.config.data['defualtUserName'];
}
if (this.defualtUserEMail !== '' && this.defualtUserName !== '') {
this.toEmailsList.push({
Address: this.defualtUserEMail,
Name: this.defualtUserName
});
}
// get automations
this.getAutomations(1,'CRM$TYPE',0,0);
this.staffId = +this.cookieService.get('LoggedUserId');
// Get Signatures by staff id
this.emailsService.GetAllSignaturesByStaffId(this.staffId).subscribe(
data => {
this.IEmailSignature = data;
if (this.IEmailSignature.length > 0) {
this.selectedSignature = this.IEmailSignature[0];
}
}
);
// Get Logged user details
this.emailsService.GetLoggedUserEmailDetails(this.staffId).subscribe(
data => {
this.IStaffs = data;
// console.log('Logged User Data :');
// console.log(this.IStaffs);
}
);
// setTimeout(() => {
// this.editorContent = 'content changed!
';
// console.log('you can use the quill instance object to do something', this.editor);
// // this.editor.disable();
// }, 2800);
this.events = [
{
"title": "All Day Event",
"start": "2017-08-15"
},
{
"title": "Long Event",
"start": "2016-01-07",
"end": "2016-01-10"
},
{
"title": "Repeating Event",
"start": "2016-01-09T16:00:00"
},
{
"title": "Repeating Event",
"start": "2016-01-16T16:00:00"
},
{
"title": "Conference",
"start": "2016-01-11",
"end": "2016-01-13"
}
];
//options needed for calnedar
this.options = {
themeSystem: 'bootstrap',
plugins: [dayGridPlugin, timeGridPlugin, interactionPlugin],
defaultDate: this.startDate,
header: { left: 'prev,next', center: 'title', right: 'month,week,day,today' },
titleFormat: { year: 'numeric', month: 'long', day: 'numeric' },
buttonText: {
today: 'Today',
month: 'Month',
week: 'Week',
}
};
//Getting all the available email details
// Get Associata Records
this.emailsService.GetAssociateRecords(this.contactId).subscribe(
result => {
if (result != null) {
this.IAssociateRecords = result;
// console.log('Associate Records In Email');
// console.log(this.IAssociateRecords);
}
else {
//console.log(" Error: GetAllNotesTypes ");
}
}
);
//set client name as default
let iEmailAddress: IEmailAddress;
this.emailsService.getAllAvailableEmailDetails().subscribe(
data => {
console.log(data);
}
);
}
onEditorBlured(quill) {
//console.log('editor blur!', quill);
}
onEditorFocused(quill) {
//console.log('editor focus!', quill);
}
onEditorCreated(quill) {
this.editor = quill;
//console.log('quill is ready! this is current quill instance object', quill);
}
onContentChanged({ quill, html, text }) {
//console.log('quill content is changed!', quill, html, text);
this.validateFields();
}
showLoadTemplate() {
const ref = this.dialogService.open(ContactLoadTemplateComponent, {
header: 'Load from template',
width: '50%'
});
ref.onClose.subscribe(() => {
this.emailSubject = this.dialogService.dialogComponentRef.instance.componentRef.instance.emailSubject;
this.editorContent = this.dialogService.dialogComponentRef.instance.componentRef.instance.emailContent;
});
}
saveTemplate() {
const ref = this.dialogService.open(ContactSaveTemplateComponent, {
data: {
emailSubject: this.emailSubject,
emailContent: this.editorContent
},
header: 'Save as template',
width: '50%'
});
}
//CC on click function
ccOnClickEvent() {
this.displayCCFields = !this.displayCCFields;
}
//BCC on click function
bccOnClickEvent() {
this.displayBCCFields = !this.displayBCCFields;
}
//Uploading attachments
uploadAttachment(files) {
if (files.length === 0)
return;
for (var i = 0; i < files.target.files.length; i++) {
this.attachmentFiles.push(files.target.files[i]);
this.attachmentImageNames.push(files.target.files[i]['name']);
//Adding to the list
this.attachmentList.push({
Id: this.sampleIdValue,
FileType: this.identifyFileType(files.target.files[i]['name']),
Path: "",
Title: files.target.files[i]['name']
});
//Incrementing the ID
this.sampleIdValue--;
}
//-------------- End of Adding the file to the list ---------------
}
//On click function of remove icon
removeAttachment(selectedAttachment: IEmailAttachments) {
for (let i = 0; i < this.attachmentList.length; i++) {
if (this.attachmentList[i].Id == selectedAttachment.Id) {
this.attachmentList.splice(i, 1);
this.attachmentFiles.splice(i, 1);
this.attachmentImageNames.splice(i, 1);
}
}
}
//Identify the file type
identifyFileType(fileName: string) {
let fileType = "";
let lastIndexOf = fileName.lastIndexOf(".");
let ext = fileName.substring(lastIndexOf + 1);
switch (ext.toUpperCase()) {
case "ZIP":
case "RAR":
fileType = "COMPRESSED";
break;
case "PNG":
case "JPEG":
case "JPG":
case "TIF":
case "TIFF":
fileType = "IMAGE";
break;
case "PPT":
case "PPTX":
fileType = "POWERPOINT";
break;
case "XLSX":
case "XLS":
case "XLR":
fileType = "EXCEL";
break;
case "DOC":
case "DOCX":
fileType = "WORD";
break;
case "TXT":
fileType = "TEXT";
break;
default:
fileType = "UNKNOWN";
break;
}
return fileType;
}
//Auto complete to email section
filterEmailsMultiple(event) {
let query = event.query;
this.emailsService.getAllAvailableEmailDetails().subscribe(
data => {
this.filteredEmailsMultiple = this.filterEmailDetails(query, data);
}
);
}
//Auto complete CC email section
filteredCCEmailsMultiple(event) {
let query = event.query;
this.emailsService.getAllAvailableEmailDetails().subscribe(
data => {
this.filteredEmailsMultiple = this.filterEmailDetails(query, data);
}
);
}
//Auto complete BCC email section
filteredBCCEmailsMultiple(event) {
let query = event.query;
this.emailsService.getAllAvailableEmailDetails().subscribe(
data => {
this.filteredEmailsMultiple = this.filterEmailDetails(query, data);
}
);
}
//Filter emails
filterEmailDetails(query: string, emailList: IEmailAddress[]): any[] {
//in a real application, make a request to a remote url with the query and return filtered results, for demo we filter at client side
let filtered: IEmailAddress[] = [];
for (let i = 0; i < emailList.length; i++) {
let email = emailList[i];
//Check if the last charater is empty
let val = query.charAt(query.length - 1);
if (query.charAt(query.length - 1) == " ") {
filtered.push({
Address: query,
Name: ""
});
break;
} else if (email.Address.toLowerCase().indexOf(query.toLowerCase()) == 0) {
filtered.push(email);
}
}
this.validateFields();
return filtered;
}
// Show Email Signature
showEmailSignature() {
const ref = this.dialogService.open(ContactCreateEmailSignatureComponent, {
header: 'Email Signature',
width: '30%',
data: { signatureStateType: "CREATE" }
});
ref.onClose.subscribe(() => {
// Get Signatures by staff id
this.emailsService.GetAllSignaturesByStaffId(this.staffId).subscribe(
data => {
this.IEmailSignature = [];
this.IEmailSignature = data;
if (this.IEmailSignature.length > 0) {
this.selectedSignature = this.IEmailSignature[0];
}
}
);
});
}
//Send now on click function
sendNowButton() {
//appenidng both the contactid and the company ids of the associate
let associateRecords = this.ContactSelectedValues + "$" + this.CompanySelectedValues;
//Check if the task create is checked
let isTaskCreate = false;
let isAutomation = false;
if (this.emailCreateTask.length > 0) {
isTaskCreate = true;
}
if (this.emailAutomation.length > 0) {
isAutomation = true;
}
//Setting the email object to be sent
const emailObject: IEmailBodyDetails = {
ToAddressList: this.toEmailsList,
BCCAddressList: this.bccEmailsList,
CCAddressList: this.ccEmailsList,
Content: this.editorContent + "
" + this.selectedSignature.SignatureContent,
FromAddress: {
Address: this.fromEmail.FullName,
Name: this.fromEmail.FirstName + " " + this.fromEmail.LastName
},
Subject: this.emailSubject,
AttachmentPath: [],
AssociateRecords: associateRecords,
}
//Calling the service to send the mail
let internelEmailObject: IInternelEmailType = {
EmailBodyDetails: emailObject,
ApplyAutomation: isAutomation,
CreateTask: isTaskCreate,
SendDate: new Date(),
SignatureId: this.selectedSignature.EmailSignatureId,
AttachmentNameList: this.attachmentImageNames,
BusinessDays: this.bussinessDates,
StaffId: this.staffId,
CompanyContactId: this.companyContactId,
ContactId: this.contactId,
ReplyToID: this.replyId
}
let attachmentPathList = [];
if (this.attachmentFiles.length > 0) {
//Iterating through the attachments
for (let i = 0; i < this.attachmentFiles.length; i++) {
//Setting the form data
const frmDataObj = new FormData();
frmDataObj.append("fileUpload", this.attachmentFiles[i]);
//Uploading the attachments and getting the uploaded path
this.emailsService.UploadAttachment(frmDataObj).subscribe(
data => {
//Pussing the uploaded path to the list
attachmentPathList.push(data);
//Checking whether its the last index
if (i == this.attachmentFiles.length - 1) {
emailObject.AttachmentPath = attachmentPathList;
emailObject.ToAddressList[0].Name = "SAmple";
internelEmailObject.EmailBodyDetails = emailObject;
//Sending the new email
this.emailsService.SendNewEmail(internelEmailObject).subscribe(
data => {
//console.log("New mail sent");
//console.log(data);
//Clearing the fields
this.clearAllThefields();
this.dialogService.dialogComponentRef.instance.close();
}
);
}
}
);
}
} else {
//Sending the new email
this.emailsService.SendNewEmail(internelEmailObject).subscribe(
data => {
//console.log("New mail sent");
//console.log(data);
//Clearing the fields
this.clearAllThefields();
this.dialogService.dialogComponentRef.instance.close();
}
);
}
}
//Validating the fields
validateFields() {
//console.log(this.toEmailsList.length);
//console.log(this.editorContent);
if (this.emailSubject != null && this.emailSubject != ""
&& this.editorContent != null && this.editorContent != "" && this.editorContent != "
"
&& this.toEmailsList.length > 0 && this.fromEmail && this.fromEmail.FullName != "") {
this.disableSendNowButton = false;
} else {
this.disableSendNowButton = true;
}
}
//Clear fields
clearAllThefields() {
this.emailSubject = "";
this.editorContent = "";
this.toEmailsList = [];
this.bccEmailsList = [];
this.ccEmailsList = [];
this.attachmentList = [];
}
// Edit Signature
editEmailSignature() {
const ref = this.dialogService.open(ContactCreateEmailSignatureComponent, {
header: 'Email Signature',
width: '30%',
data: { signatureStateType: "EDIT", selectedSignature: this.selectedSignature }
});
// Get Signatures by staff id
this.emailsService.GetAllSignaturesByStaffId(this.staffId).subscribe(
data => {
this.IEmailSignature = [];
this.IEmailSignature = data;
if (this.IEmailSignature.length > 0) {
this.selectedSignature = this.IEmailSignature[0];
}
}
);
}
//Send later on click function
sendlaterOnClickButton() {
if (this.sendLaterDateState == false) {
this.sendLaterDateState = true;
} else {
//Check if the task create is checked
let isTaskCreate = false;
let isAutomation = false;
if (this.emailAutomation.length > 0) {
isTaskCreate = true;
}
// debugger;
if (this.emailCreateTask.length > 0) {
isAutomation = true;
}
//Setting the email object to be sent
const emailObject: IEmailBodyDetails = {
ToAddressList: this.toEmailsList,
BCCAddressList: this.bccEmailsList,
CCAddressList: this.ccEmailsList,
Content: this.editorContent + "
" + this.selectedSignature.SignatureContent,
FromAddress: {
Address: this.fromEmail.FullName,
Name: this.fromEmail.FirstName + " " + this.fromEmail.LastName
},
Subject: this.emailSubject,
AttachmentPath: []
}
//Calling the service to send the mail
let internelEmailObject: IInternelEmailType = {
EmailBodyDetails: emailObject,
ApplyAutomation: isAutomation,
CreateTask: isTaskCreate,
SendDate: new Date(this.sendEmailLaterDate),
SignatureId: this.selectedSignature.EmailSignatureId,
AttachmentNameList: this.attachmentImageNames,
ReplyToID: this.replyId
}
let attachmentPathList = [];
if (this.attachmentFiles.length > 0) {
//Iterating through the attachments
for (let i = 0; i < this.attachmentFiles.length; i++) {
//Setting the form data
const frmDataObj = new FormData();
frmDataObj.append("fileUpload", this.attachmentFiles[i]);
//Uploading the attachments and getting the uploaded path
this.emailsService.UploadAttachment(frmDataObj).subscribe(
data => {
//Pussing the uploaded path to the list
attachmentPathList.push(data);
//Checking whether its the last index
if (i == this.attachmentFiles.length - 1) {
emailObject.AttachmentPath = attachmentPathList;
emailObject.ToAddressList[0].Name = "SAmple";
internelEmailObject.EmailBodyDetails = emailObject;
//Sending the new email
this.emailsService.SendNewEmail(internelEmailObject).subscribe(
data => {
//console.log("New mail sent");
//console.log(data);
//Clearing the fields
this.clearAllThefields();
this.dialogService.dialogComponentRef.instance.close();
}
);
}
}
);
}
} else {
//Sending the new email
this.emailsService.SendNewEmail(internelEmailObject).subscribe(
data => {
//console.log("New mail sent");
//console.log(data);
//Clearing the fields
this.clearAllThefields();
this.dialogService.dialogComponentRef.instance.close();
}
);
}
}
}
// Business Days
onChangeBusinessDays(event) {
this.bussinessDates = event.target.value;
// console.log(this.bussinessDates);
if (event.target.value == -1) {
// Enable input box
this.customSelected = true;
this.displayInputNumber = true;
this.businessdayDropdown = '1';
} else {
// Hide input box
this.displayInputNumber = false;
this.customSelected = false;
}
}
inputCustomValues() {
if (this.displayInputNumber == true) {
this.bussinessDates = this.userEnteredValue;
}
}
// Get automation list
getAutomations(companyId:number, siteType:string,automationId:number, automationType:number){
this.automationService.GetAutomations(companyId,siteType,automationId,automationType).subscribe(list=>{
// bind automation list
this.automationList = list;
})
}
}