//campaignEmailSender.
js
import { LightningElement, wire, track, api } from 'lwc';
import getEmailTemplates from
'@salesforce/apex/CampaignEmailSenderController.getEmailTemplates';
import getEmailTemplateDetails from
'@salesforce/apex/CampaignEmailSenderController.getEmailTemplateDetails';
import sendEmails from '@salesforce/apex/CampaignEmailSenderController.sendEmails';
import sendPreviewEmails from
'@salesforce/apex/CampaignEmailSenderController.sendPreviewEmails';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import { CloseActionScreenEvent } from 'lightning/actions';
export default class CampaignEmailSender extends LightningElement {
@api recordId; // Campaign Id passed to the component
@track templateOptions = [];
selectedTemplate = '';
emailSubject = '';
emailBody = '';
@wire(getEmailTemplates)
templates({ error, data }) {
if (data) {
this.templateOptions = data.map(template => ({
label: template.Name,
value: template.Id
}));
} else if (error) {
console.error(error);
}
}
handleTemplateChange(event) {
this.selectedTemplate = event.detail.value;
// Fetch template details (subject and body) when a template is selected
getEmailTemplateDetails({ templateId: this.selectedTemplate, campaignId:
this.recordId })
.then((result) => {
console.log(result);
this.emailSubject = result.Subject;
this.emailBody = result.body;
})
.catch(error => {
console.error(error);
this.showToast('Error', 'Failed to load template details',
'error');
});
}
handleSubjectChange(event) {
this.emailSubject = event.target.value;
}
handleBodyChange(event) {
this.emailBody = event.target.value;
}
sendEmails() {
sendEmails({
campaignId: this.recordId,
templateId: this.selectedTemplate,
subject: this.emailSubject,
body: this.emailBody
})
.then(() => {
this.showToast('Success', 'Emails sent successfully', 'success');
this.dispatchEvent(new CloseActionScreenEvent());
})
.catch(error => {
console.error(error);
this.showToast('Error', 'Failed to send emails', 'error');
this.dispatchEvent(new CloseActionScreenEvent());
});
}
showToast(title, message, variant) {
const evt = new ShowToastEvent({
title,
message,
variant
});
this.dispatchEvent(evt);
}
sendPreviewEmails() {
sendPreviewEmails({
campaignId: this.recordId,
templateId: this.selectedTemplate,
subject: this.emailSubject,
body: this.emailBody
})
.then(() => {
this.showToast('Success', 'Preview emails sent successfully',
'success');
})
.catch(error => {
console.error(error);
this.showToast('Error', 'Failed to send preview emails', 'error');
});
}
}