diff --git a/src/formHandler.js b/src/formHandler.js index ea5c110..f97f594 100644 --- a/src/formHandler.js +++ b/src/formHandler.js @@ -7,7 +7,6 @@ export async function submitToListmonk(req, res) { const listmonkUrl = process.env.LISTMONK_URL; const listmonkUsername = process.env.LISTMONK_USERNAME; const listmonkPassword = process.env.LISTMONK_PASSWORD; - const campaignId = process.env.PRESET_CAMPAIGN_ID; const listmonkBaseUrl = process.env.LISTMONK_BASE_URL; const listId = parseInt(process.env.LIST_ID, 10); @@ -20,6 +19,7 @@ export async function submitToListmonk(req, res) { email, name, lists: [listId], + status: "enabled", fields: { message } }; @@ -49,7 +49,7 @@ export async function submitToListmonk(req, res) { 'Authorization': `Basic ${auth}` }, body: JSON.stringify(payload), - },3); + },12); if (!response.ok) { const errorBody = await response.text(); @@ -59,63 +59,98 @@ export async function submitToListmonk(req, res) { const result = await response.json(); console.log('Subscriber added successfully:', result); - // Update campaign status to "scheduled" - const campaignStatusUrl = `${listmonkBaseUrl}/campaigns/${campaignId}/status`; - const scheduleTime = new Date(Date.now() + 5 * 60 * 1000).toISOString(); // Schedule 5 minutes from now - const statusPayload = { - status: 'scheduled', - schedule: scheduleTime, - }; + // Create a new campaign for the subscriber + const createCampaign = async (subject, body) => { + const createCampaignUrl = `${listmonkBaseUrl}/campaigns`; + const campaignPayload = { + name: `Welcome email for ${email}`, + subject: subject, + from_email: "Janek ", + body: body, + type: "regular", + to_emails: [email], + lists: [listId], + content_type: "richtext", + status: "scheduled", + schedule: new Date().toISOString() + }; - console.log('Updating campaign status using URL:', campaignStatusUrl); - console.log('Campaign status payload:', statusPayload); - - try { - const statusResponse = await fetch(campaignStatusUrl, { - method: 'PUT', + const response = await fetch(createCampaignUrl, { + method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Basic ${auth}`, }, - body: JSON.stringify(statusPayload), + body: JSON.stringify(campaignPayload), }); - if (!statusResponse.ok) { - const errorBody = await statusResponse.text(); - console.error('Response from Listmonk:', errorBody); - throw new Error(`Listmonk API error (Update Campaign Status): ${statusResponse.statusText}. Response body: ${errorBody}`); + if (!response.ok) { + const errorBody = await response.text(); + throw new Error(`Listmonk API error (Create Campaign): ${response.statusText}. Response body: ${errorBody}`); } - const statusResult = await statusResponse.json(); - console.log('Campaign status updated successfully:', statusResult); - } catch (error) { - console.error('Error updating campaign status:', error); - } + const result = await response.json(); + return result.data.id; + }; - const statusResult = await statusResponse.json(); - console.log('Campaign status updated successfully:', statusResult); + // Campaign subject and body content + const subject = "👋 Welcome to the Progodyssey Family!"; + const body = ` +

👋 Welcome to the Progodyssey Family, {{ .Subscriber.Name }}!

- // Send the campaign - const campaignSendUrl = `${listmonkBaseUrl}/campaigns/${campaignId}/send`; - console.log('Sending campaign using URL:', campaignSendUrl); +

We’re thrilled to have you as part of the Progodyssey Traineeship journey! 🎉 + This program is designed to equip you with the skills, experience, and network to thrive in the tech world and beyond.

- const campaignResponse = await fetch(campaignSendUrl, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - 'Authorization': `Basic ${auth}`, - }, +

Here’s what you can expect in the coming weeks:

+ + +

To kick things off, go through the Progodyssey handbook, pick a course and submit your reflection essay to reflection@progodyssey.com.

+

Janek’s Blog could also have some insight for you.

+ +

Encouragement:
+ "Success is the sum of small efforts repeated day in and day out."Robert Collier

+ +

Let’s take the first step together!
+ If you have any questions or need assistance, feel free to reply to this email or contact us at hello@progodyssey.com

+ +

Looking forward to seeing you thrive,
+ The Progodyssey Team

+ `; + + // 1. Create campaign + const newCampaignId = await createCampaign(subject, body); + console.log(`Created new campaign with ID: ${newCampaignId}`); + + // 2. Dispatch campaign + const dispatchUrl = `${listmonkBaseUrl}/campaigns/${newCampaignId}/status`; + const dispatchPayload = { + status: 'running' + }; + + const dispatchResponse = await fetch(dispatchUrl, { + method: 'PUT', + headers: { + 'Content-Type': 'application/json', + 'Authorization': `Basic ${auth}`, + }, + body: JSON.stringify(dispatchPayload), }); - if (!campaignResponse.ok) { - const errorBody = await campaignResponse.text(); - throw new Error(`Listmonk API error (Send Campaign): ${campaignResponse.statusText}. Response body: ${errorBody}`); + if (!dispatchResponse.ok) { + const errorBody = await dispatchResponse.text(); + console.error('Response from Listmonk (Dispatch):', errorBody); + throw new Error(`Listmonk API error (Dispatch Campaign): ${dispatchResponse.statusText}. Response body: ${errorBody}`); } - const campaignResult = await campaignResponse.json(); - console.log('Campaign sent successfully:', campaignResult); + const dispatchResult = await dispatchResponse.json(); + console.log('Campaign dispatched successfully:', dispatchResult); + + res.status(200).json({ message: 'Subscription and welcome email sent successfully!', result }); - res.status(200).json({ message: 'Subscription successful!', result }); } catch (error) { console.error('Error submitting to Listmonk:', error); res.status(500).json({ message: 'Failed to submit to Listmonk', error: error.message });