';
+ const emailAddresses = normalizeEmailAddresses(to)
+
+ const message = {
+ from: sender,
+ to: emailAddresses,
+ subject,
+ text,
+ html,
+ attachments
+ };
+
+ if (mailtrapTestClient !== null) {
+ // Assuming mailtrapTestClient is correctly set up to send emails
+ await mailtrapTestClient
+ .send(message)
+ .then(console.log)
+ .catch(console.error);
+
+ } else {
+
+ let result = await transporter
+ .sendMail(message)
+ .then(console.log)
+ .catch(console.error);
+ return result;
+ }
+
+};
+
+exports.SendEmailHandlebars = async function (to, templateName, model, attachments = []) {
+ try {
+ // Ensure the sender and mailtrapTestClient are correctly defined or imported
+
+ // Load and compile the main template
+ const mainTemplateSource = fs.readFileSync(path.join(process.cwd(), 'src', 'templates', 'emails', 'main.hbs'), 'utf8');
+ const mainTemplate = Handlebars.compile(mainTemplateSource);
+
+ // Dynamically load and compile the specified template
+ const templateSource = fs.readFileSync(path.join(process.cwd(), 'src', 'templates', 'emails', `${templateName}.hbs`), 'utf8');
+
+ // Extract subject and optional text version from the template source
+ const subjectMatch = templateSource.match(/{{!--\s*Subject:\s*(.*?)\s*--}}/);
+ const textMatch = templateSource.match(/{{!--\s*Text:\s*([\s\S]*?)\s*--}}/);
+
+ let subject = subjectMatch ? subjectMatch[1].trim() : 'ССС: Известие';
+ let textVersion = textMatch ? textMatch[1].trim() : null;
+
+ // Remove the subject and text annotations from the template source
+ const cleanTemplateSource = templateSource.replace(/{{!-- Subject: .* --}}/, '').replace(/{{!-- Text: [\s\S]*? --}}/, '');
+ // const cleanTemplateSource = templateSource
+ // .replace(/{{!--\s*Subject:.*?--}}\s*/, '')
+ // .replace(/{{!--\s*Text:.*?--}}\s*/, '');
+ // Compile the cleaned template
+ const template = Handlebars.compile(cleanTemplateSource);
+
+ // Render the specified template with the provided model
+ const templateHtml = template(model);
+
+ // Render the main template, inserting the specific template HTML
+ const html = mainTemplate({ body: templateHtml });
+
+ // Generate a plain text version if not explicitly provided
+ let text = textVersion || html.replace(/<[^>]*>?/gm, ''); // Simple regex to strip HTML tags. Might need refinement.
+ subject = Handlebars.compile(subject)(model);
+ text = Handlebars.compile(text)(model);
+
+ let results = this.SendEmail(to, subject, text, html, attachments);
+ return results;
+
+ } catch (error) {
+ console.error(error);
+ return new Error('Error sending email');
+ }
+};
+
+
+exports.SendEmail_NewShifts = async function (publisher, shifts) {
+ if (shifts.length === 0) return;
+
+ var date = new Date(shifts[0].startTime);
+
+ // Generate ICS calendar links for all shifts
+ const icsLink = CAL.GenerateICS(shifts);
+
+ // Prepare the shifts string
+ const shiftStr = shifts.map((s) => {
+ return `${CON.weekdaysBG[s.startTime.getDay()]} ${CON.GetDateFormat(s.startTime)} at ${s.cartEvent.location.name} from ${CON.GetTimeFormat(s.startTime)} to ${CON.GetTimeFormat(s.endTime)}`;
+ }).join(" ");
+
+ // Define the model for the Handlebars template
+ const model = {
+ publisherFirstName: publisher.firstName,
+ publisherLastName: publisher.lastName,
+ month: CON.monthNamesBG[date.getMonth()],
+ shifts: shiftStr,
+ sentDate: new Date().toLocaleDateString() // Assuming you want to include the sent date in the email
+ };
+
+ await exports.SendEmailHandlebars(publisher.email, "newShifts", model,
+ [{
+ filename: "calendar.ics",
+ content: icsLink,
+ contentType: 'text/calendar' // Ensure this is correctly set for the ICS file
+ }]
+ ).then(console.log).catch(console.error);
+};
+
+
+
+
+//----------------------- OLD -----------------------------
+
+// exports.SendEmail_NewShifts = async function (publisher, shifts) {
+// if (shifts.length == 0) return;
+
+// var date = new Date(shifts[0].startTime);
+
+// //generate ICS calendar links for all shifts
+// const icsLink = CAL.GenerateICS(shifts);
+
+// const shftStr = shifts
+// .map((s) => {
+// return ` ${CON.weekdaysBG[s.startTime.getDay()]
+// } ${CON.GetDateFormat(s.startTime)} ${s.cartEvent.location.name
+// } ${CON.GetTimeFormat(s.startTime)} - ${CON.GetTimeFormat(
+// s.endTime
+// )}`;
+// })
+// .join("\n");
+
+// await client.send({
+// from: sender,
+// to: [
+// {
+// email: "dobromir.popov@gmail.com",//publisher.email,
+// name: publisher.firstName + " " + publisher.lastName,
+// },
+// ],
+// subject: "[CCC]: вашите смени през " + CON.monthNamesBG[date.getMonth()],
+// text:
+// "Здравейте, " + publisher.firstName + " " + publisher.lastName + "!\n\n" +
+// "Ти регистриран да получавате известия за нови смени на количка.\n" +
+// `За месец ${CON.monthNamesBG[date.getMonth()]} имате следните смени:\n` +
+// ` ${shftStr} \n\n\n` +
+// "Поздрави,\n" +
+// "Специално Свидетелстване София",
+// attachments: [
+// {
+// filename: "calendar.ics",
+// content_id: "calendar.ics",
+// disposition: "inline",
+// content: icsLink,
+// },
+// ],
+// })
+// .then(console.log, console.error, setResult);
+// };
+
+
// https://mailtrap.io/blog/sending-emails-with-nodemailer/
-exports.SendTestEmail = async function (to) {
- // await client
- // .send({
- // from: sender,
- // to: [{ email: RECIPIENT_EMAIL }],
- // subject: "Hello from Mailtrap!",
- // text: "Welcome to Mailtrap Sending!",Shift Info"
- // })
- // .then(console.log, console.error, setResult);
-
- // return lastResult;
-
+exports.SendEmail_Example = async function (to) {
const welcomeImage = fs.readFileSync(
path.join(CON.contentPath, "welcome.png")
);
@@ -113,50 +293,3 @@ exports.SendTestEmail = async function (to) {
})
.then(console.log, console.error, setResult);
};
-
-
-exports.SendEmail_NewShifts = async function (publisher, shifts) {
- if (shifts.length == 0) return;
-
- var date = new Date(shifts[0].startTime);
-
- //generate ICS calendar links for all shifts
- const icsLink = CAL.GenerateICS(shifts);
-
- const shftStr = shifts
- .map((s) => {
- return ` ${CON.weekdaysBG[s.startTime.getDay()]
- } ${CON.GetDateFormat(s.startTime)} ${s.cartEvent.location.name
- } ${CON.GetTimeFormat(s.startTime)} - ${CON.GetTimeFormat(
- s.endTime
- )}`;
- })
- .join("\n");
-
- await client.send({
- from: sender,
- to: [
- {
- email: "dobromir.popov@gmail.com",//publisher.email,
- name: publisher.firstName + " " + publisher.lastName,
- },
- ],
- subject: "[CCC]: вашите смени през " + CON.monthNamesBG[date.getMonth()],
- text:
- "Здравейте, " + publisher.firstName + " " + publisher.lastName + "!\n\n" +
- "Ти регистриран да получавате известия за нови смени на количка.\n" +
- `За месец ${CON.monthNamesBG[date.getMonth()]} имате следните смени:\n` +
- ` ${shftStr} \n\n\n` +
- "Поздрави,\n" +
- "Специално Свидетелстване София",
- attachments: [
- {
- filename: "calendar.ics",
- content_id: "calendar.ics",
- disposition: "inline",
- content: icsLink,
- },
- ],
- })
- .then(console.log, console.error, setResult);
-};
diff --git a/src/templates/emails/coverMe.hbs b/src/templates/emails/coverMe.hbs
new file mode 100644
index 0000000..2855a11
--- /dev/null
+++ b/src/templates/emails/coverMe.hbs
@@ -0,0 +1,26 @@
+{{!--Subject: ССС: Нужен е заместник --}}
+
+
+ Търси се зместник:
+ {{!-- за смяна на {{placeName}} за {{dateStr}}! --}}
+
+ Здравей {{firstName}},
+ {{prefix}} {{user.firstName}} {{user.lastName}} търси заместник.
+ {{!-- Shift Details:
--}}
+ Дата: {{dateStr}} Час: {{time}} Място: {{placeName}}
+ С натискането на бутона по-долу можеш да премеш да го заместваш.
+ {{!-- Ти, той/тя и останалите участници в смяната ще
+ получат имейл за промяната. Твоята помощ е много ценна. --}}
+
+
+ Ще
+ поема смяната
+
+ {{!-- Thank you very much for considering my request.
+ Best regards, {{name}}
--}}
+
+
\ No newline at end of file
diff --git a/src/templates/emails/coverMeAccepted.hbs b/src/templates/emails/coverMeAccepted.hbs
new file mode 100644
index 0000000..16bb198
--- /dev/null
+++ b/src/templates/emails/coverMeAccepted.hbs
@@ -0,0 +1,19 @@
+{{!-- Subject: ССС: Промени в твоята смяна --}}
+
+
+ Промяна твоята смяна на {{placeName}} {{dateStr}}
+ Здравейте {{firstName}},
+ {{firstName}} {{lastName}} ще замести {{oldPubName}} на смяната ви в {{dateStr}} от {{time}}
+ Новаия списък с участници за тази смяна е:
+
+ {{#each newPubs}}
+ {{this.name}} - {{this.phone}}
+ {{/each}}
+
+
+
+
+
+{{!-- --}}
\ No newline at end of file
diff --git a/src/templates/emails/example.hbs b/src/templates/emails/example.hbs
new file mode 100644
index 0000000..e300167
--- /dev/null
+++ b/src/templates/emails/example.hbs
@@ -0,0 +1,24 @@
+{{!-- Subject: ССС: Нужен е заместник--}}
+{{!-- Text: Plain text version of your email. If not provided, HTML tags will be stripped from the HTML version for the
+text version. --}}
+
+
+ Търси се зместник за смяна на {{placeName}} за {{dateStr}}!
+ Здравейте,
+ {{prefix}} {{firstName}} {{lastName}} търси заместник.
+ {{!-- Shift Details:
--}}
+ Дата: {{dateStr}} Час: {{time}} Място: {{placeName}}
+ С натискането на бутона по-долу можете да премете да го замествате. Вие, той/тя и останалите участници в смяната
+ ще бъдат уведумени чрез имейл за промяната. Вашата помощ е много ценна.
+
+ Ще
+ поема смяната
+
+ {{!-- Thank you very much for considering my request.
+ Best regards, {{name}}
--}}
+
+
\ No newline at end of file
diff --git a/src/templates/emails/main.hbs b/src/templates/emails/main.hbs
new file mode 100644
index 0000000..1669557
--- /dev/null
+++ b/src/templates/emails/main.hbs
@@ -0,0 +1,25 @@
+
+
+
+
+
+
+ ССС известия
+
+
+
+
+ Cпециално Свидетелстване София
+
+
+
+ {{{body}}}
+
+
+
+ © 2024 ССС. All rights reserved.
+
+
+
+
\ No newline at end of file
diff --git a/src/templates/emails/newShifts.hbs b/src/templates/emails/newShifts.hbs
new file mode 100644
index 0000000..5f52bc8
--- /dev/null
+++ b/src/templates/emails/newShifts.hbs
@@ -0,0 +1,14 @@
+{{!-- Subject: ССС: Нови назначени смени--}}
+
+
+ Здравейте, {{publisherFirstName}} {{publisherLastName}}!
+ Ти регистриран да получавате известия за нови смени на количка.
+ За месец {{month}} имате следните смени:
+
+ {{{shifts}}}
+
+
+
+
\ No newline at end of file