From b01a40a1fd71dd0abfcb8c784670fc38c20c8d63 Mon Sep 17 00:00:00 2001 From: Ryan Mwangi Date: Mon, 30 Dec 2024 03:00:35 +0300 Subject: [PATCH] fix(campaign): fix Listmonk campaign handling logic --- src/formHandler.js | 91 ++++++++++++++++++++++++++++++++-------------- 1 file changed, 64 insertions(+), 27 deletions(-) diff --git a/src/formHandler.js b/src/formHandler.js index 1b154be..1481118 100644 --- a/src/formHandler.js +++ b/src/formHandler.js @@ -4,18 +4,16 @@ import fetch from 'node-fetch'; export async function submitToListmonk(req, res) { const { name, email, message } = req.body; - 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 listmonkBaseUrl = process.env.LISTMONK_BASE_URL; + const listId = parseInt(process.env.LIST_ID, 10); + // Encode username and password as base64 const auth = Buffer.from(`${listmonkUsername}:${listmonkPassword}`).toString('base64'); - const listId = parseInt(process.env.LIST_ID, 10); - console.log(`Sending request to Listmonk with URL: ${listmonkUrl}`); const payload = { @@ -28,41 +26,80 @@ export async function submitToListmonk(req, res) { console.log('Sending request to Listmonk with payload:', payload); try { - // Add subscriber + // Add subscriber const response = await fetch(listmonkUrl, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - 'Authorization': `Basic ${auth}` - }, - body: JSON.stringify(payload) - }) - - if (!response.ok) { - const errorBody = await response.text(); // Get the response body as text - throw new Error(`Listmonk API error: ${response.statusText}. Response body: ${errorBody}`); - } - - // Send the welcome campaign - const campaignSendUrl = `${listmonkBaseUrl}/campaigns/${campaignId}/send`; - console.log('Sending campaign using URL:', campaignSendUrl); - const campaignResponse = await fetch(campaignSendUrl, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Basic ${auth}` - } + }, + body: JSON.stringify(payload), }); + + if (!response.ok) { + const errorBody = await response.text(); + throw new Error(`Listmonk API error: ${response.statusText}. Response body: ${errorBody}`); + } + + 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, + }; + + console.log('Updating campaign status using URL:', campaignStatusUrl); + console.log('Campaign status payload:', statusPayload); + + try { + const statusResponse = await fetch(campaignStatusUrl, { + method: 'PUT', + headers: { + 'Content-Type': 'application/json', + 'Authorization': `Basic ${auth}`, + }, + body: JSON.stringify(statusPayload), + }); + 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}`); + } + + const statusResult = await statusResponse.json(); + console.log('Campaign status updated successfully:', statusResult); + } catch (error) { + console.error('Error updating campaign status:', error); + } + + const statusResult = await statusResponse.json(); + console.log('Campaign status updated successfully:', statusResult); + + // Send the campaign + const campaignSendUrl = `${listmonkBaseUrl}/campaigns/${campaignId}/send`; + console.log('Sending campaign using URL:', campaignSendUrl); + + const campaignResponse = await fetch(campaignSendUrl, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'Authorization': `Basic ${auth}`, + }, + }); + if (!campaignResponse.ok) { const errorBody = await campaignResponse.text(); throw new Error(`Listmonk API error (Send Campaign): ${campaignResponse.statusText}. Response body: ${errorBody}`); } - + const campaignResult = await campaignResponse.json(); console.log('Campaign sent successfully:', campaignResult); - - const result = await response.json(); + res.status(200).json({ message: 'Subscription successful!', result }); } catch (error) { console.error('Error submitting to Listmonk:', error);