I have a triggered email associated with an overnight job, It checks to see if a report has been emailed out then looks for contacts who have signed up for the report and then sends the report to each of the contacts. It is an intermittent issue in that some days the test group gets 1 email other days 2 recieved at the same time anyone have any insight as to why this could be happening?
export async function sendEmailToContact() {
let contactId = [];
let options;
const triggeredEmailTemplate = '*******';
//Has email been sent if not then send email
const emailinfo = await wixData.query("emailreports").eq("title", 'principal_Changes').limit(100).find();
if (emailinfo.items[0].emailsent === "false") {
// Get Contacts
const queryResults = await contacts.queryContacts()
.eq('info.extendedFields.custom.principlereport', "Yes")
.find();
const contactsWithEmail = queryResults.items;
if (contactsWithEmail.length === 1) {
console.log('Found 1 contact');
contactId[0] = contactsWithEmail[0]._id;
} else if (contactsWithEmail.length > 1) {
// Handle when more than one contact is found
console.log('Found more than 1 contact');
for (let i = 0; i < contactsWithEmail.length; i++) {
contactId[i] = contactsWithEmail[i]._id;
}
} else {
console.log('No contacts found');
// Handle when no contacts are found
}
// Get variables to post to email template
const principleresults = await wixData.query("principles").gt('amount_change', 0).limit(100).descending('amount_change').ascending('frn').find();
if (principleresults.items.length > 0) {
let item = principleresults.items;
let totalCount = principleresults.length;
}
let resultsdate = (principleresults.items[0]._updatedDate).toLocaleDateString()
let represults = await wixData.aggregate("principles")
.sum("amount_change")
.run()
options = {
variables: {
NoPrinciples: principleresults.totalCount,
NoReps: represults.items[0].amount_changeSum,
Principle1: principleresults.items[0].organisationName,
Principle1Ars: principleresults.items[0].amount_change,
Querydate: resultsdate
}
}
console.log('Send email')
// Flag sent email table
let toUpdate = {
"_id": emailinfo.items[0]._id,
"emailsent": "true",
"title": "principal_Changes"
};
try {
let results = await wixData.update("emailreports", toUpdate)
console.log(results); //see item below
} catch (err) {
console.log(err);
}
// Send report to all who have it as Yes
for (let j = 0; j < contactId.length; j++) {
try {
await triggeredEmails.emailContact(triggeredEmailTemplate, contactId[j], options);
console.log('Email sent to contact ' + contactId[j]);
} catch (error) {
console.error(error);
// Handle the error
}
}
} else { console.log('Email Already sent') }
}
Worked out why this is happening and the code above is fine. The issue is with the scheduled jobs, it appears to be running twice within 0.5s
the jobs.config is using cron expressions all set out to run at diffrent minutes past the hour so not the reason for the above. Any suggestions welcome.