Skip to content

AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents

feat(campaign-monitor): manage lists, subscribers, campaign reports and smart transactional emails (#16771)

Odai Ahmad612231a67f3f
diff --git a/bun.lock b/bun.lock
index 57f808b57e5..9fa81bc8e2e 100644
--- a/bun.lock
+++ b/bun.lock
@@ -1558,7 +1558,7 @@
},
"packages/pieces/community/campaign-monitor": {
"name": "@activepieces/piece-campaign-monitor",
- "version": "0.1.9",
+ "version": "0.2.0",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
@@ -1567,6 +1567,7 @@
},
"devDependencies": {
"tslib": "2.6.2",
+ "vitest": "3.2.6",
},
},
"packages/pieces/community/canny": {
diff --git a/docs/install/reference/breaking-changes-unreleased.mdx b/docs/install/reference/breaking-changes-unreleased.mdx
index ba725293390..ba0a139be92 100644
--- a/docs/install/reference/breaking-changes-unreleased.mdx
+++ b/docs/install/reference/breaking-changes-unreleased.mdx
@@ -8,6 +8,16 @@ Entries here move to [Breaking Changes](/install/reference/breaking-changes) aut
## What has changed?
+#### Campaign Monitor 0.2.0: Add Subscriber and Update Subscriber are builder-only
+
+Add Subscriber and Update Subscriber are no longer offered to AI agents. They keep working in flows, but an agent that used them as tools loses them after the upgrade.
+
+Find Subscriber now fails with an error when Campaign Monitor returns a real error, such as an invalid API key or an outage. It used to return `found: false` in those cases; it still returns `found: false` when the subscriber does not exist.
+
+#### What you need to do
+
+Agents that used these actions switch to their twins: Add Subscriber (JSON fields) and Update Subscriber (JSON fields). Flows that read `found: false` from Find Subscriber to mean "not found" keep working; a run that hits a bad key or an outage now fails instead of taking the not-found branch. Flow steps keep running on the version they were built with until you upgrade them.
+
#### Bannerbear 0.6.0: Create Image is builder-only, returns the normalized image, and Custom API Call is asynchronous
From Bannerbear 0.6.0, **Create Image** is no longer offered as a tool to AI agents; it still works as a normal flow step. Agents use the new **Create Image from JSON** action instead. Create Image now returns the same normalized image as the other Bannerbear actions: the template ID is in `template_uid` instead of `template`, and `modifications`, `width` and `height` are no longer returned. **Custom API Call** no longer goes through `sync.api.bannerbear.com`; it now uses `api.bannerbear.com`, so a `POST /images` call returns the image while it is still `pending` instead of waiting for it to finish rendering.
diff --git a/packages/pieces/community/campaign-monitor/package.json b/packages/pieces/community/campaign-monitor/package.json
index 43275f0123f..4eb92d1b91c 100644
--- a/packages/pieces/community/campaign-monitor/package.json
+++ b/packages/pieces/community/campaign-monitor/package.json
@@ -1,12 +1,13 @@
{
"name": "@activepieces/piece-campaign-monitor",
- "version": "0.1.9",
+ "version": "0.2.0",
"main": "./dist/src/index.js",
"types": "./dist/src/index.d.ts",
"scripts": {
"build": "tsc -p tsconfig.lib.json && cp package.json dist/",
"bundle": "node ../../../../dist/packages/cli/src/index.js pieces bundle",
- "lint": "eslint 'src/**/*.ts'"
+ "lint": "eslint 'src/**/*.ts'",
+ "test": "vitest run"
},
"dependencies": {
"@activepieces/pieces-common": "workspace:*",
@@ -15,6 +16,7 @@
"@activepieces/core-utils": "workspace:*"
},
"devDependencies": {
- "tslib": "2.6.2"
+ "tslib": "2.6.2",
+ "vitest": "3.2.6"
}
}
diff --git a/packages/pieces/community/campaign-monitor/src/i18n/de.json b/packages/pieces/community/campaign-monitor/src/i18n/de.json
index 17ffa5fe46f..7239492b9c5 100644
--- a/packages/pieces/community/campaign-monitor/src/i18n/de.json
+++ b/packages/pieces/community/campaign-monitor/src/i18n/de.json
@@ -32,4 +32,4 @@
"Triggered when a new subscriber is added to a list.": "Wird ausgelöst, wenn ein neuer Abonnent zu einer Liste hinzugefügt wird.",
"Triggered when a subscriber unsubscribes from a list": "Ausgelöst, wenn ein Abonnent sich von einer Liste abmeldet",
"Triggered when a new client is added to Campaign Monitor.": "Wird ausgelöst, wenn ein neuer Client zum Kampagnen-Monitor hinzugefügt wird."
-}
\ No newline at end of file
+}
diff --git a/packages/pieces/community/campaign-monitor/src/i18n/es.json b/packages/pieces/community/campaign-monitor/src/i18n/es.json
index d9f55d65d06..4eff3162851 100644
--- a/packages/pieces/community/campaign-monitor/src/i18n/es.json
+++ b/packages/pieces/community/campaign-monitor/src/i18n/es.json
@@ -32,4 +32,4 @@
"Triggered when a new subscriber is added to a list.": "Se activa cuando se añade un nuevo suscriptor a una lista.",
"Triggered when a subscriber unsubscribes from a list": "Se activó cuando un suscriptor se daba de baja de una lista",
"Triggered when a new client is added to Campaign Monitor.": "Se ha activado cuando se añade un nuevo cliente al Monitor de Campaña."
-}
\ No newline at end of file
+}
diff --git a/packages/pieces/community/campaign-monitor/src/i18n/fr.json b/packages/pieces/community/campaign-monitor/src/i18n/fr.json
index 4cfc0dd3aa9..3496b889a3d 100644
--- a/packages/pieces/community/campaign-monitor/src/i18n/fr.json
+++ b/packages/pieces/community/campaign-monitor/src/i18n/fr.json
@@ -32,4 +32,4 @@
"Triggered when a new subscriber is added to a list.": "Déclenché lorsqu'un nouvel abonné est ajouté à une liste.",
"Triggered when a subscriber unsubscribes from a list": "Déclenché lorsqu'un abonné se désabonne d'une liste",
"Triggered when a new client is added to Campaign Monitor.": "Déclenché lorsqu'un nouveau client est ajouté au moniteur de campagne."
-}
\ No newline at end of file
+}
diff --git a/packages/pieces/community/campaign-monitor/src/i18n/ja.json b/packages/pieces/community/campaign-monitor/src/i18n/ja.json
index 6daed478210..fc252d0b274 100644
--- a/packages/pieces/community/campaign-monitor/src/i18n/ja.json
+++ b/packages/pieces/community/campaign-monitor/src/i18n/ja.json
@@ -32,4 +32,4 @@
"Triggered when a new subscriber is added to a list.": "新しい購読者がリストに追加されたときにトリガーされます。",
"Triggered when a subscriber unsubscribes from a list": "購読者が一覧から購読を解除したときにトリガーされます",
"Triggered when a new client is added to Campaign Monitor.": "新規クライアントがCampaign Monitorに追加されたときにトリガーされます。"
-}
\ No newline at end of file
+}
diff --git a/packages/pieces/community/campaign-monitor/src/i18n/nl.json b/packages/pieces/community/campaign-monitor/src/i18n/nl.json
index 1d146a71733..e3e4c123369 100644
--- a/packages/pieces/community/campaign-monitor/src/i18n/nl.json
+++ b/packages/pieces/community/campaign-monitor/src/i18n/nl.json
@@ -32,4 +32,4 @@
"Triggered when a new subscriber is added to a list.": "Uitgelokt wanneer een nieuwe ontvanger aan een lijst wordt toegevoegd.",
"Triggered when a subscriber unsubscribes from a list": "Uitgelokt wanneer een abonnee zich afmeldt van een lijst",
"Triggered when a new client is added to Campaign Monitor.": "Uitgelokt wanneer een nieuwe klant is toegevoegd aan Campaign Monitor."
-}
\ No newline at end of file
+}
diff --git a/packages/pieces/community/campaign-monitor/src/i18n/pt.json b/packages/pieces/community/campaign-monitor/src/i18n/pt.json
index c33e247991d..e791b0aede5 100644
--- a/packages/pieces/community/campaign-monitor/src/i18n/pt.json
+++ b/packages/pieces/community/campaign-monitor/src/i18n/pt.json
@@ -32,4 +32,4 @@
"Triggered when a new subscriber is added to a list.": "Acionada quando um novo assinante é adicionado a uma lista.",
"Triggered when a subscriber unsubscribes from a list": "Acionada quando um assinante desinscrever-se de uma lista",
"Triggered when a new client is added to Campaign Monitor.": "Acionada quando um novo cliente é adicionado ao Monitor da Campanha."
-}
\ No newline at end of file
+}
diff --git a/packages/pieces/community/campaign-monitor/src/i18n/ru.json b/packages/pieces/community/campaign-monitor/src/i18n/ru.json
index 174d4caf15e..79fbab6a600 100644
--- a/packages/pieces/community/campaign-monitor/src/i18n/ru.json
+++ b/packages/pieces/community/campaign-monitor/src/i18n/ru.json
@@ -33,4 +33,4 @@
"Triggered when a new subscriber is added to a list.": "Срабатывает при добавлении в список нового абонента.",
"Triggered when a subscriber unsubscribes from a list": "Срабатывает при отказе от подписки подписчика из списка",
"Triggered when a new client is added to Campaign Monitor.": "Срабатывает при добавлении нового клиента в Монитор Кампании."
-}
\ No newline at end of file
+}
diff --git a/packages/pieces/community/campaign-monitor/src/i18n/translation.json b/packages/pieces/community/campaign-monitor/src/i18n/translation.json
index 678247ddd70..61edb58c154 100644
--- a/packages/pieces/community/campaign-monitor/src/i18n/translation.json
+++ b/packages/pieces/community/campaign-monitor/src/i18n/translation.json
@@ -5,10 +5,48 @@
"Update Subscriber": "Update Subscriber",
"Unsubscribe Subscriber": "Unsubscribe Subscriber",
"Find Subscriber": "Find Subscriber",
+ "Delete Subscriber": "Delete Subscriber",
+ "Get List Subscribers": "Get List Subscribers",
+ "List Clients": "List Clients",
+ "List Lists": "List Lists",
+ "List Smart Emails": "List Smart Emails",
+ "Create List": "Create List",
+ "List Sent Campaigns": "List Sent Campaigns",
+ "Get Campaign Summary": "Get Campaign Summary",
+ "Send Smart Transactional Email": "Send Smart Transactional Email",
+ "Add Subscriber (JSON fields)": "Add Subscriber (JSON fields)",
+ "Update Subscriber (JSON fields)": "Update Subscriber (JSON fields)",
+ "Create Draft Campaign": "Create Draft Campaign",
+ "Send Campaign": "Send Campaign",
+ "Delete Draft Campaign": "Delete Draft Campaign",
+ "Get Campaign Activity": "Get Campaign Activity",
+ "Get List Stats": "Get List Stats",
+ "Add Emails to Suppression List": "Add Emails to Suppression List",
+ "Remove Email from Suppression List": "Remove Email from Suppression List",
+ "Create Custom Field": "Create Custom Field",
"Adds a new subscriber to a list.": "Adds a new subscriber to a list.",
"Update an existing subscriber in a list.": "Update an existing subscriber in a list.",
"Remove a subscriber from a list.": "Remove a subscriber from a list.",
"Find a subscriber by email in a specific list.": "Find a subscriber by email in a specific list.",
+ "Moves a subscriber to the Deleted state of a list.": "Moves a subscriber to the Deleted state of a list.",
+ "Returns one page of subscribers in a list, filtered by state.": "Returns one page of subscribers in a list, filtered by state.",
+ "Returns all clients in your Campaign Monitor account.": "Returns all clients in your Campaign Monitor account.",
+ "Returns all subscriber lists of a client.": "Returns all subscriber lists of a client.",
+ "Returns the smart transactional emails of a client.": "Returns the smart transactional emails of a client.",
+ "Creates a new subscriber list for a client.": "Creates a new subscriber list for a client.",
+ "Returns one page of campaigns a client has sent.": "Returns one page of campaigns a client has sent.",
+ "Returns the reporting summary of a sent campaign.": "Returns the reporting summary of a sent campaign.",
+ "Sends a smart transactional email to one or more recipients.": "Sends a smart transactional email to one or more recipients.",
+ "Adds a subscriber to a list, with custom fields as JSON.": "Adds a subscriber to a list, with custom fields as JSON.",
+ "Updates a subscriber in a list, with custom fields as JSON.": "Updates a subscriber in a list, with custom fields as JSON.",
+ "Creates a draft campaign from hosted HTML content.": "Creates a draft campaign from hosted HTML content.",
+ "Sends or schedules a draft campaign.": "Sends or schedules a draft campaign.",
+ "Permanently deletes a draft campaign.": "Permanently deletes a draft campaign.",
+ "Returns one page of recipients, opens, clicks or bounces.": "Returns one page of recipients, opens, clicks or bounces.",
+ "Returns subscriber growth and totals for a list.": "Returns subscriber growth and totals for a list.",
+ "Stops a client from sending to the given email addresses.": "Stops a client from sending to the given email addresses.",
+ "Lets a client send to a suppressed email address again.": "Lets a client send to a suppressed email address again.",
+ "Adds a custom field to a list.": "Adds a custom field to a list.",
"Client Account": "Client Account",
"List ID": "List ID",
"Email Address": "Email Address",
@@ -18,18 +56,126 @@
"Consent to Send SMS": "Consent to Send SMS",
"Resubscribe": "Resubscribe",
"Custom Fields": "Custom Fields",
+ "New Email Address": "New Email Address",
+ "State": "State",
+ "Page": "Page",
+ "Page Size": "Page Size",
+ "Order By": "Order By",
+ "Order Direction": "Order Direction",
+ "Status": "Status",
+ "Title": "Title",
+ "Unsubscribe Setting": "Unsubscribe Setting",
+ "Confirmed Opt-In": "Confirmed Opt-In",
+ "Unsubscribe Page URL": "Unsubscribe Page URL",
+ "Confirmation Success Page URL": "Confirmation Success Page URL",
+ "Sent From Date": "Sent From Date",
+ "Sent To Date": "Sent To Date",
+ "Tags": "Tags",
+ "Campaign": "Campaign",
+ "Smart Email": "Smart Email",
+ "To": "To",
+ "CC": "CC",
+ "BCC": "BCC",
+ "Data": "Data",
+ "Add Recipients to List": "Add Recipients to List",
+ "Campaign Name": "Campaign Name",
+ "Subject": "Subject",
+ "From Name": "From Name",
+ "From Email": "From Email",
+ "Reply-To Email": "Reply-To Email",
+ "HTML Content URL": "HTML Content URL",
+ "Text Content URL": "Text Content URL",
+ "Lists": "Lists",
+ "Segments": "Segments",
+ "Draft Campaign": "Draft Campaign",
+ "Confirmation Email": "Confirmation Email",
+ "Send Date": "Send Date",
+ "Activity Type": "Activity Type",
+ "Since Date": "Since Date",
+ "Email Addresses": "Email Addresses",
+ "Field Name": "Field Name",
+ "Data Type": "Data Type",
+ "Options": "Options",
+ "Visible in Preference Center": "Visible in Preference Center",
"Whether the subscriber has consented to tracking.": "Whether the subscriber has consented to tracking.",
"Whether the subscriber has consented to send SMS.": "Whether the subscriber has consented to send SMS.",
"If true, the subscriber will be resubscribed if they previously unsubscribed.": "If true, the subscriber will be resubscribed if they previously unsubscribed.",
+ "The current email address of the subscriber.": "The current email address of the subscriber.",
+ "New email for the subscriber. Leave empty to keep the current one.": "New email for the subscriber. Leave empty to keep the current one.",
"The email address of the subscriber to unsubscribe.": "The email address of the subscriber to unsubscribe.",
"The email address of the subscriber to find": "The email address of the subscriber to find",
+ "The email address of the subscriber to delete.": "The email address of the subscriber to delete.",
+ "Page number to return, starting at 1.": "Page number to return, starting at 1.",
+ "Subscribers per page, between 10 and 1000.": "Subscribers per page, between 10 and 1000.",
+ "Whether an unsubscribe here also applies to all client lists.": "Whether an unsubscribe here also applies to all client lists.",
+ "Require new subscribers to confirm by email (double opt-in).": "Require new subscribers to confirm by email (double opt-in).",
+ "Page shown after unsubscribing. Leave empty for the default page.": "Page shown after unsubscribing. Leave empty for the default page.",
+ "Page shown after a subscriber confirms (Confirmed Opt-In only).": "Page shown after a subscriber confirms (Confirmed Opt-In only).",
+ "Only campaigns sent on or after this date.": "Only campaigns sent on or after this date.",
+ "Only campaigns sent before this date (the date itself is excluded).": "Only campaigns sent before this date (the date itself is excluded).",
+ "Only campaigns with these tags, as a comma-separated list.": "Only campaigns with these tags, as a comma-separated list.",
+ "Campaigns per page, between 10 and 1000.": "Campaigns per page, between 10 and 1000.",
+ "A sent campaign of the selected client, newest first.": "A sent campaign of the selected client, newest first.",
+ "An active smart transactional email of the selected client.": "An active smart transactional email of the selected client.",
+ "Recipients, as an email address or \"Name <[email protected]>\".": "Recipients, as an email address or \"Name <[email protected]>\".",
+ "Values for the smart email variables, as a JSON object.": "Values for the smart email variables, as a JSON object.",
+ "Add the recipients to the list configured on the smart email.": "Add the recipients to the list configured on the smart email.",
+ "Whether the recipients have consented to tracking.": "Whether the recipients have consented to tracking.",
+ "ID of the list to add the subscriber to.": "ID of the list to add the subscriber to.",
+ "Resubscribe the contact if they previously unsubscribed.": "Resubscribe the contact if they previously unsubscribed.",
+ "JSON object of field name to value, e.g. {\"Company\":\"Acme\"}.": "JSON object of field name to value, e.g. {\"Company\":\"Acme\"}.",
+ "ID of the list the subscriber belongs to.": "ID of the list the subscriber belongs to.",
+ "New email for the subscriber. Leave empty to keep it.": "New email for the subscriber. Leave empty to keep it.",
+ "Internal name; must be unique among the client campaigns.": "Internal name; must be unique among the client campaigns.",
+ "Sender address; must be verified in Campaign Monitor.": "Sender address; must be verified in Campaign Monitor.",
+ "Public URL of the HTML content to import.": "Public URL of the HTML content to import.",
+ "Public URL of the plain-text version. Optional.": "Public URL of the plain-text version. Optional.",
+ "Lists the campaign is sent to.": "Lists the campaign is sent to.",
+ "Segments the campaign is sent to.": "Segments the campaign is sent to.",
+ "A draft campaign of the selected client.": "A draft campaign of the selected client.",
+ "Up to 5 comma-separated addresses notified when sent.": "Up to 5 comma-separated addresses notified when sent.",
+ "\"Immediately\" or YYYY-MM-DD HH:MM in the client time zone.": "\"Immediately\" or YYYY-MM-DD HH:MM in the client time zone.",
+ "Only activity on or after this day. Ignored for recipients.": "Only activity on or after this day. Ignored for recipients.",
+ "Records per page, between 10 and 1000.": "Records per page, between 10 and 1000.",
+ "Addresses to add to the suppression list.": "Addresses to add to the suppression list.",
+ "Address to remove from the suppression list.": "Address to remove from the suppression list.",
+ "Choices for the multi-select data types.": "Choices for the multi-select data types.",
+ "Let subscribers see and edit this field.": "Let subscribers see and edit this field.",
"Yes": "Yes",
"No": "No",
"Unchanged": "Unchanged",
+ "Active": "Active",
+ "Unsubscribed": "Unsubscribed",
+ "Bounced": "Bounced",
+ "Deleted": "Deleted",
+ "Unconfirmed": "Unconfirmed",
+ "Date": "Date",
+ "Email": "Email",
+ "Ascending": "Ascending",
+ "Descending": "Descending",
+ "Draft": "Draft",
+ "All": "All",
+ "All client lists": "All client lists",
+ "Only this list": "Only this list",
+ "Newest first": "Newest first",
+ "Oldest first": "Oldest first",
+ "Recipients": "Recipients",
+ "Opens": "Opens",
+ "Clicks": "Clicks",
+ "Bounces": "Bounces",
+ "Unsubscribes": "Unsubscribes",
+ "Text": "Text",
+ "Number": "Number",
+ "Select one option": "Select one option",
+ "Select many options": "Select many options",
+ "Country": "Country",
+ "US State": "US State",
"New Subscriber Added": "New Subscriber Added",
"Subscriber Unsubscribed": "Subscriber Unsubscribed",
"New Client": "New Client",
+ "New Campaign Sent": "New Campaign Sent",
"Triggered when a new subscriber is added to a list.": "Triggered when a new subscriber is added to a list.",
"Triggered when a subscriber unsubscribes from a list": "Triggered when a subscriber unsubscribes from a list",
- "Triggered when a new client is added to Campaign Monitor.": "Triggered when a new client is added to Campaign Monitor."
-}
\ No newline at end of file
+ "Triggered when a new client is added to Campaign Monitor.": "Triggered when a new client is added to Campaign Monitor.",
+ "Triggers when a client sends a new campaign.": "Triggers when a client sends a new campaign."
+}
diff --git a/packages/pieces/community/campaign-monitor/src/i18n/vi.json b/packages/pieces/community/campaign-monitor/src/i18n/vi.json
index e019f24ed8d..e73aefdd09b 100644
--- a/packages/pieces/community/campaign-monitor/src/i18n/vi.json
+++ b/packages/pieces/community/campaign-monitor/src/i18n/vi.json
@@ -33,4 +33,4 @@
"Triggered when a new subscriber is added to a list.": "Triggered when a new subscriber is added to a list.",
"Triggered when a subscriber unsubscribes from a list": "Triggered when a subscriber unsubscribes from a list",
"Triggered when a new client is added to Campaign Monitor.": "Triggered when a new client is added to Campaign Monitor."
-}
\ No newline at end of file
+}
diff --git a/packages/pieces/community/campaign-monitor/src/i18n/zh.json b/packages/pieces/community/campaign-monitor/src/i18n/zh.json
index 5853152917e..30665d23a70 100644
--- a/packages/pieces/community/campaign-monitor/src/i18n/zh.json
+++ b/packages/pieces/community/campaign-monitor/src/i18n/zh.json
@@ -32,4 +32,4 @@
"Triggered when a new subscriber is added to a list.": "Triggered when a new subscriber is added to a list.",
"Triggered when a subscriber unsubscribes from a list": "Triggered when a subscriber unsubscribes from a list",
"Triggered when a new client is added to Campaign Monitor.": "Triggered when a new client is added to Campaign Monitor."
-}
\ No newline at end of file
+}
diff --git a/packages/pieces/community/campaign-monitor/src/index.ts b/packages/pieces/community/campaign-monitor/src/index.ts
index 9763c19b8cc..af1d7ff310d 100644
--- a/packages/pieces/community/campaign-monitor/src/index.ts
+++ b/packages/pieces/community/campaign-monitor/src/index.ts
@@ -1,38 +1,72 @@
-import { createPiece, PieceAuth } from '@activepieces/pieces-framework';
+import { createPiece } from '@activepieces/pieces-framework';
import { PieceCategory } from '@activepieces/pieces-framework';
import { addSubscriberToListAction } from './lib/actions/add-subscriber-to-list';
import { updateSubscriberDetailsAction } from './lib/actions/update-subscriber-details';
import { unsubscribeSubscriberAction } from './lib/actions/unsubscribe-subscriber';
import { findSubscriberAction } from './lib/actions/find-subscriber';
+import { deleteSubscriberAction } from './lib/actions/delete-subscriber';
+import { getListSubscribersAction } from './lib/actions/get-list-subscribers';
+import { listListsAction } from './lib/actions/list-lists';
+import { listClientsAction } from './lib/actions/list-clients';
+import { listSmartEmailsAction } from './lib/actions/list-smart-emails';
+import { createListAction } from './lib/actions/create-list';
+import { listSentCampaignsAction } from './lib/actions/list-sent-campaigns';
+import { getCampaignSummaryAction } from './lib/actions/get-campaign-summary';
+import { sendSmartEmailAction } from './lib/actions/send-smart-email';
+import { addSubscriberJsonAction } from './lib/actions/add-subscriber-json';
+import { updateSubscriberJsonAction } from './lib/actions/update-subscriber-json';
+import { createDraftCampaignAction } from './lib/actions/create-draft-campaign';
+import { sendCampaignAction } from './lib/actions/send-campaign';
+import { deleteDraftCampaignAction } from './lib/actions/delete-draft-campaign';
+import { getCampaignActivityAction } from './lib/actions/get-campaign-activity';
+import { getListStatsAction } from './lib/actions/get-list-stats';
+import { suppressEmailsAction } from './lib/actions/suppress-emails';
+import { unsuppressEmailAction } from './lib/actions/unsuppress-email';
+import { createCustomFieldAction } from './lib/actions/create-custom-field';
+import { newCampaignSentTrigger } from './lib/triggers/new-campaign-sent';
import { newSubscriberAddedTrigger } from './lib/triggers/new-subscriber-added';
import { subscriberUnsubscribedTrigger } from './lib/triggers/subscriber-unsubscribed';
import { newClientTrigger } from './lib/triggers/new-client';
import { campaignMonitorAuth } from './lib/auth';
-const markdownDescription = `
-To use Campaign Monitor, you need to get an API key:
-1. Login to your account at https://www.campaignmonitor.com.
-2. Navigate to Account Settings.
-3. Click on API Keys.
-4. Create a new API key or use an existing one.
-`;
-
export const campaignMonitor = createPiece({
- displayName: 'Campaign Monitor',
- description: 'Email marketing platform for delivering exceptional email campaigns.',
- logoUrl: 'https://cdn.activepieces.com/pieces/campaign-monitor.png',
- authors: ['AnkitSharmaOnGithub','kishanprmr'],
- auth: campaignMonitorAuth,
- actions: [
- addSubscriberToListAction,
- updateSubscriberDetailsAction,
- unsubscribeSubscriberAction,
- findSubscriberAction
- ],
- triggers: [
- newSubscriberAddedTrigger,
- subscriberUnsubscribedTrigger,
- newClientTrigger
- ],
- categories: [PieceCategory.MARKETING],
+ displayName: 'Campaign Monitor',
+ description:
+ 'Email marketing platform for delivering exceptional email campaigns.',
+ logoUrl: 'https://cdn.activepieces.com/pieces/campaign-monitor.png',
+ authors: ['AnkitSharmaOnGithub', 'kishanprmr', 'OdaiAhmed99'],
+ minimumSupportedRelease: '0.88.2',
+ auth: campaignMonitorAuth,
+ actions: [
+ addSubscriberToListAction,
+ updateSubscriberDetailsAction,
+ unsubscribeSubscriberAction,
+ findSubscriberAction,
+ deleteSubscriberAction,
+ getListSubscribersAction,
+ listClientsAction,
+ listListsAction,
+ listSmartEmailsAction,
+ createListAction,
+ listSentCampaignsAction,
+ getCampaignSummaryAction,
+ sendSmartEmailAction,
+ addSubscriberJsonAction,
+ updateSubscriberJsonAction,
+ createDraftCampaignAction,
+ sendCampaignAction,
+ deleteDraftCampaignAction,
+ getCampaignActivityAction,
+ getListStatsAction,
+ suppressEmailsAction,
+ unsuppressEmailAction,
+ createCustomFieldAction,
+ ],
+ triggers: [
+ newSubscriberAddedTrigger,
+ subscriberUnsubscribedTrigger,
+ newClientTrigger,
+ newCampaignSentTrigger,
+ ],
+ categories: [PieceCategory.MARKETING],
});
diff --git a/packages/pieces/community/campaign-monitor/src/lib/actions/add-subscriber-json.ts b/packages/pieces/community/campaign-monitor/src/lib/actions/add-subscriber-json.ts
new file mode 100644
index 00000000000..196e5ddcdd3
--- /dev/null
+++ b/packages/pieces/community/campaign-monitor/src/lib/actions/add-subscriber-json.ts
@@ -0,0 +1,112 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import {
+ buildCustomFieldsPayload,
+ fetchDateFieldKeys,
+ jsonCustomFieldsToRecord,
+ makeRequest,
+} from '../common/client';
+import { subscriptionResultOutputSchema } from '../output-schemas';
+import { campaignMonitorAuth } from '../auth';
+
+export const addSubscriberJsonAction = createAction({
+ auth: campaignMonitorAuth,
+ name: 'add_subscriber_json',
+ classification: 'WRITE',
+ displayName: 'Add Subscriber (JSON fields)',
+ description: 'Adds a subscriber to a list, with custom fields as JSON.',
+ outputSchema: subscriptionResultOutputSchema,
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Adds a subscriber (by email) to a Campaign Monitor list given its list ID, optionally setting name, phone, tracking/SMS consent and custom fields passed as a JSON object keyed by field name (spaces are ignored, so "Favorite Color" maps to [FavoriteColor]), e.g. {"Company":"Acme","Age":30}; use an array value for multi-select fields and YYYY-MM-DD for dates. Empty values are skipped. Use List Lists to find the list ID. Enable Resubscribe to re-add someone who previously unsubscribed. Not idempotent: each call posts a new subscription and may overwrite or re-add the contact.',
+ idempotent: false,
+ },
+ props: {
+ listId: Property.ShortText({
+ displayName: 'List ID',
+ description: 'ID of the list to add the subscriber to.',
+ required: true,
+ }),
+ email: Property.ShortText({
+ displayName: 'Email Address',
+ required: true,
+ }),
+ name: Property.ShortText({
+ displayName: 'Name',
+ required: false,
+ }),
+ phone: Property.ShortText({
+ displayName: 'Phone',
+ required: false,
+ }),
+ consentToTrack: Property.StaticDropdown({
+ displayName: 'Consent to Track',
+ description: 'Whether the subscriber has consented to tracking.',
+ required: true,
+ defaultValue: 'Unchanged',
+ options: {
+ options: [
+ { label: 'Yes', value: 'Yes' },
+ { label: 'No', value: 'No' },
+ { label: 'Unchanged', value: 'Unchanged' },
+ ],
+ },
+ }),
+ consentToSendSms: Property.StaticDropdown({
+ displayName: 'Consent to Send SMS',
+ description: 'Whether the subscriber has consented to send SMS.',
+ required: false,
+ defaultValue: 'Unchanged',
+ options: {
+ options: [
+ { label: 'Yes', value: 'Yes' },
+ { label: 'No', value: 'No' },
+ { label: 'Unchanged', value: 'Unchanged' },
+ ],
+ },
+ }),
+ resubscribe: Property.Checkbox({
+ displayName: 'Resubscribe',
+ description: 'Resubscribe the contact if they previously unsubscribed.',
+ required: false,
+ defaultValue: false,
+ }),
+ customFields: Property.Json({
+ displayName: 'Custom Fields',
+ description:
+ 'JSON object of field name to value, e.g. {"Company":"Acme"}.',
+ required: false,
+ }),
+ },
+ async run({ propsValue, auth }) {
+ const listId = propsValue.listId.trim();
+ const email = propsValue.email.trim();
+ const dateKeys = await fetchDateFieldKeys({
+ auth: { apiKey: auth.secret_text },
+ listId,
+ });
+ const response = await makeRequest({
+ auth: { apiKey: auth.secret_text },
+ method: HttpMethod.POST,
+ path: `/subscribers/${encodeURIComponent(listId)}.json`,
+ body: {
+ EmailAddress: email,
+ Name: propsValue.name ?? '',
+ MobileNumber: propsValue.phone,
+ ConsentToTrack: propsValue.consentToTrack ?? 'Unchanged',
+ ConsentToSendSms: propsValue.consentToSendSms ?? 'Unchanged',
+ Resubscribe: propsValue.resubscribe ?? false,
+ CustomFields: buildCustomFieldsPayload({
+ fields: jsonCustomFieldsToRecord(propsValue.customFields),
+ dateKeys,
+ }),
+ },
+ });
+ return {
+ success: true,
+ emailAddress: typeof response.body === 'string' ? response.body : email,
+ listId,
+ };
+ },
+});
diff --git a/packages/pieces/community/campaign-monitor/src/lib/actions/add-subscriber-to-list.ts b/packages/pieces/community/campaign-monitor/src/lib/actions/add-subscriber-to-list.ts
index 6c00b3d3af3..a15553ffefc 100644
--- a/packages/pieces/community/campaign-monitor/src/lib/actions/add-subscriber-to-list.ts
+++ b/packages/pieces/community/campaign-monitor/src/lib/actions/add-subscriber-to-list.ts
@@ -1,6 +1,11 @@
import { createAction, Property } from '@activepieces/pieces-framework';
import { HttpMethod } from '@activepieces/pieces-common';
-import { makeRequest } from '../common/client';
+import {
+ buildCustomFieldsPayload,
+ fetchDateFieldKeys,
+ makeRequest,
+} from '../common/client';
+import { subscriptionResultOutputSchema } from '../output-schemas';
import { campaignMonitorAuth } from '../auth';
import { clientId, customFields, listId } from '../common/props';
@@ -10,10 +15,11 @@ export const addSubscriberToListAction = createAction({
classification: 'WRITE',
displayName: 'Add Subscriber',
description: 'Adds a new subscriber to a list.',
- audience: 'both',
+ outputSchema: subscriptionResultOutputSchema,
+ audience: 'human',
aiMetadata: {
description:
- 'Adds a subscriber (by email) to a specific Campaign Monitor list under a client, optionally setting name, phone, custom fields, and tracking/SMS consent. Choose this to enroll a new contact into an email list; enable Resubscribe to re-add someone who previously unsubscribed. Not idempotent: each call posts a new subscription and may overwrite or re-add the contact, so guard against duplicate runs.',
+ 'Builder form with a custom field per list field; agents use the JSON fields variant. Adds a subscriber (by email) to a specific Campaign Monitor list under a client, optionally setting name, phone, custom fields, and tracking/SMS consent. Choose this to enroll a new contact into an email list; enable Resubscribe to re-add someone who previously unsubscribed. Not idempotent: each call posts a new subscription and may overwrite or re-add the contact, so guard against duplicate runs.',
idempotent: false,
},
props: {
@@ -64,7 +70,7 @@ export const addSubscriberToListAction = createAction({
required: false,
defaultValue: false,
}),
- fields:customFields,
+ fields: customFields,
},
async run({ propsValue, auth }) {
const {
@@ -75,38 +81,35 @@ export const addSubscriberToListAction = createAction({
consentToSendSms,
consentToTrack,
resubscribe,
- fields
+ fields,
} = propsValue;
+ const dateKeys = await fetchDateFieldKeys({
+ auth: { apiKey: auth.secret_text },
+ listId,
+ });
+
const payload = {
EmailAddress: email,
Name: name || '',
- ConsentToTrack: consentToTrack,
- ConsentToSendSms: consentToSendSms,
- Resubscribe: resubscribe ?? true,
+ ConsentToTrack: consentToTrack ?? 'Unchanged',
+ ConsentToSendSms: consentToSendSms ?? 'Unchanged',
+ Resubscribe: resubscribe ?? false,
MobileNumber: phone,
- CustomFields: Object.entries(fields).flatMap(([key, value]) =>
- Array.isArray(value)
- ? value.map((v) => ({ Key: key, Value: v }))
- : [{ Key: key, Value: value }]
- ),
+ CustomFields: buildCustomFieldsPayload({ fields, dateKeys }),
};
- const response = await makeRequest(
- { apiKey: auth.secret_text },
- HttpMethod.POST,
- `/subscribers/${listId}.json`,
- payload
- );
+ const response = await makeRequest({
+ auth: { apiKey: auth.secret_text },
+ method: HttpMethod.POST,
+ path: `/subscribers/${listId}.json`,
+ body: payload,
+ });
- if (response.status === 201) {
- return {
- success: true,
- };
- }
return {
- success: false,
- error: response.body,
+ success: true,
+ emailAddress: typeof response.body === 'string' ? response.body : email,
+ listId,
};
},
});
diff --git a/packages/pieces/community/campaign-monitor/src/lib/actions/create-custom-field.ts b/packages/pieces/community/campaign-monitor/src/lib/actions/create-custom-field.ts
new file mode 100644
index 00000000000..ed575c13a36
--- /dev/null
+++ b/packages/pieces/community/campaign-monitor/src/lib/actions/create-custom-field.ts
@@ -0,0 +1,84 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { makeRequest } from '../common/client';
+import { campaignMonitorAuth } from '../auth';
+import { clientId, listId } from '../common/props';
+import { createCustomFieldOutputSchema } from '../output-schemas';
+
+export const createCustomFieldAction = createAction({
+ auth: campaignMonitorAuth,
+ name: 'create_custom_field',
+ classification: 'WRITE',
+ displayName: 'Create Custom Field',
+ description: 'Adds a custom field to a list.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Creates a custom field on a Campaign Monitor list and returns its key (the field name in square brackets) for use when adding or updating subscribers. Data Type is Text, Number, Date, MultiSelectOne, MultiSelectMany, Country or USState; Options are required for the two multi-select types. Not idempotent: a second call with the same name fails because the field already exists.',
+ idempotent: false,
+ },
+ outputSchema: createCustomFieldOutputSchema,
+ props: {
+ clientId: clientId,
+ listId: listId,
+ fieldName: Property.ShortText({
+ displayName: 'Field Name',
+ required: true,
+ }),
+ dataType: Property.StaticDropdown({
+ displayName: 'Data Type',
+ required: true,
+ defaultValue: 'Text',
+ options: {
+ options: [
+ { label: 'Text', value: 'Text' },
+ { label: 'Number', value: 'Number' },
+ { label: 'Date', value: 'Date' },
+ { label: 'Select one option', value: 'MultiSelectOne' },
+ { label: 'Select many options', value: 'MultiSelectMany' },
+ { label: 'Country', value: 'Country' },
+ { label: 'US State', value: 'USState' },
+ ],
+ },
+ }),
+ options: Property.Array({
+ displayName: 'Options',
+ description: 'Choices for the multi-select data types.',
+ required: false,
+ }),
+ visibleInPreferenceCenter: Property.Checkbox({
+ displayName: 'Visible in Preference Center',
+ description: 'Let subscribers see and edit this field.',
+ required: false,
+ defaultValue: true,
+ }),
+ },
+ async run({ propsValue, auth }) {
+ const options = (propsValue.options ?? [])
+ .map((option) => String(option).trim())
+ .filter((option) => option.length > 0);
+ const isOptionType = OPTION_TYPES.includes(propsValue.dataType);
+ if (isOptionType && options.length === 0) {
+ throw new Error('Options are required for multi-select data types.');
+ }
+ const response = await makeRequest<string>({
+ auth: { apiKey: auth.secret_text },
+ method: HttpMethod.POST,
+ path: `/lists/${propsValue.listId}/customfields.json`,
+ body: {
+ FieldName: propsValue.fieldName.trim(),
+ DataType: propsValue.dataType,
+ Options: isOptionType ? options : [],
+ VisibleInPreferenceCenter: propsValue.visibleInPreferenceCenter ?? true,
+ },
+ });
+ return {
+ key: String(response.body),
+ fieldName: propsValue.fieldName.trim(),
+ dataType: propsValue.dataType,
+ listId: propsValue.listId,
+ };
+ },
+});
+
+const OPTION_TYPES = ['MultiSelectOne', 'MultiSelectMany'];
diff --git a/packages/pieces/community/campaign-monitor/src/lib/actions/create-draft-campaign.ts b/packages/pieces/community/campaign-monitor/src/lib/actions/create-draft-campaign.ts
new file mode 100644
index 00000000000..1206d030b71
--- /dev/null
+++ b/packages/pieces/community/campaign-monitor/src/lib/actions/create-draft-campaign.ts
@@ -0,0 +1,86 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { makeRequest } from '../common/client';
+import { campaignMonitorAuth } from '../auth';
+import { clientId, listIds, segmentIds } from '../common/props';
+import { createDraftCampaignOutputSchema } from '../output-schemas';
+
+export const createDraftCampaignAction = createAction({
+ auth: campaignMonitorAuth,
+ name: 'create_draft_campaign',
+ classification: 'WRITE',
+ displayName: 'Create Draft Campaign',
+ description: 'Creates a draft campaign from hosted HTML content.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Creates a draft email campaign for a Campaign Monitor client, importing its HTML (and optional text) content from public URLs, addressed to the given lists and/or segments, and returns the new campaign ID. The draft is not sent: use Send Campaign afterwards. At least one list or segment is required. Not idempotent: every call creates another draft.',
+ idempotent: false,
+ },
+ outputSchema: createDraftCampaignOutputSchema,
+ props: {
+ clientId: clientId,
+ name: Property.ShortText({
+ displayName: 'Campaign Name',
+ description: 'Internal name; must be unique among the client campaigns.',
+ required: true,
+ }),
+ subject: Property.ShortText({
+ displayName: 'Subject',
+ required: true,
+ }),
+ fromName: Property.ShortText({
+ displayName: 'From Name',
+ required: true,
+ }),
+ fromEmail: Property.ShortText({
+ displayName: 'From Email',
+ description: 'Sender address; must be verified in Campaign Monitor.',
+ required: true,
+ }),
+ replyTo: Property.ShortText({
+ displayName: 'Reply-To Email',
+ required: true,
+ }),
+ htmlUrl: Property.ShortText({
+ displayName: 'HTML Content URL',
+ description: 'Public URL of the HTML content to import.',
+ required: true,
+ }),
+ textUrl: Property.ShortText({
+ displayName: 'Text Content URL',
+ description: 'Public URL of the plain-text version. Optional.',
+ required: false,
+ }),
+ listIds: listIds,
+ segmentIds: segmentIds,
+ },
+ async run({ propsValue, auth }) {
+ const lists = propsValue.listIds ?? [];
+ const segments = propsValue.segmentIds ?? [];
+ if (lists.length === 0 && segments.length === 0) {
+ throw new Error('Select at least one list or segment.');
+ }
+ const textUrl = propsValue.textUrl?.trim();
+ const response = await makeRequest<string>({
+ auth: { apiKey: auth.secret_text },
+ method: HttpMethod.POST,
+ path: `/campaigns/${propsValue.clientId}.json`,
+ body: {
+ Name: propsValue.name,
+ Subject: propsValue.subject,
+ FromName: propsValue.fromName,
+ FromEmail: propsValue.fromEmail.trim(),
+ ReplyTo: propsValue.replyTo.trim(),
+ HtmlUrl: propsValue.htmlUrl.trim(),
+ TextUrl: textUrl ? textUrl : undefined,
+ ListIDs: lists,
+ SegmentIDs: segments,
+ },
+ });
+ return {
+ campaignId: String(response.body),
+ name: propsValue.name,
+ };
+ },
+});
diff --git a/packages/pieces/community/campaign-monitor/src/lib/actions/create-list.ts b/packages/pieces/community/campaign-monitor/src/lib/actions/create-list.ts
new file mode 100644
index 00000000000..88fc18071e5
--- /dev/null
+++ b/packages/pieces/community/campaign-monitor/src/lib/actions/create-list.ts
@@ -0,0 +1,78 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { makeRequest } from '../common/client';
+import { campaignMonitorAuth } from '../auth';
+import { clientId } from '../common/props';
+import { createListOutputSchema } from '../output-schemas';
+
+export const createListAction = createAction({
+ auth: campaignMonitorAuth,
+ name: 'create_list',
+ classification: 'WRITE',
+ displayName: 'Create List',
+ description: 'Creates a new subscriber list for a client.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Creates a new subscriber list under a Campaign Monitor client and returns its list ID. Choose this to set up a fresh audience before adding subscribers. Not idempotent: every call creates another list, even with the same title.',
+ idempotent: false,
+ },
+ outputSchema: createListOutputSchema,
+ props: {
+ clientId: clientId,
+ title: Property.ShortText({
+ displayName: 'Title',
+ required: true,
+ }),
+ unsubscribeSetting: Property.StaticDropdown({
+ displayName: 'Unsubscribe Setting',
+ description:
+ 'Whether an unsubscribe here also applies to all client lists.',
+ required: true,
+ defaultValue: 'AllClientLists',
+ options: {
+ options: [
+ { label: 'All client lists', value: 'AllClientLists' },
+ { label: 'Only this list', value: 'OnlyThisList' },
+ ],
+ },
+ }),
+ confirmedOptIn: Property.Checkbox({
+ displayName: 'Confirmed Opt-In',
+ description:
+ 'Require new subscribers to confirm by email (double opt-in).',
+ required: false,
+ defaultValue: false,
+ }),
+ unsubscribePage: Property.ShortText({
+ displayName: 'Unsubscribe Page URL',
+ description:
+ 'Page shown after unsubscribing. Leave empty for the default page.',
+ required: false,
+ }),
+ confirmationSuccessPage: Property.ShortText({
+ displayName: 'Confirmation Success Page URL',
+ description:
+ 'Page shown after a subscriber confirms (Confirmed Opt-In only).',
+ required: false,
+ }),
+ },
+ async run({ propsValue, auth }) {
+ const response = await makeRequest({
+ auth: { apiKey: auth.secret_text },
+ method: HttpMethod.POST,
+ path: `/lists/${propsValue.clientId}.json`,
+ body: {
+ Title: propsValue.title,
+ UnsubscribePage: propsValue.unsubscribePage ?? '',
+ UnsubscribeSetting: propsValue.unsubscribeSetting,
+ ConfirmedOptIn: propsValue.confirmedOptIn ?? false,
+ ConfirmationSuccessPage: propsValue.confirmationSuccessPage ?? '',
+ },
+ });
+ return {
+ listId: String(response.body),
+ title: propsValue.title,
+ };
+ },
+});
diff --git a/packages/pieces/community/campaign-monitor/src/lib/actions/delete-draft-campaign.ts b/packages/pieces/community/campaign-monitor/src/lib/actions/delete-draft-campaign.ts
new file mode 100644
index 00000000000..a7f6a952c05
--- /dev/null
+++ b/packages/pieces/community/campaign-monitor/src/lib/actions/delete-draft-campaign.ts
@@ -0,0 +1,36 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { makeRequest } from '../common/client';
+import { campaignMonitorAuth } from '../auth';
+import { clientId, draftCampaignId } from '../common/props';
+import { deleteDraftCampaignOutputSchema } from '../output-schemas';
+
+export const deleteDraftCampaignAction = createAction({
+ auth: campaignMonitorAuth,
+ name: 'delete_draft_campaign',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Delete Draft Campaign',
+ description: 'Permanently deletes a draft campaign.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Permanently deletes a Campaign Monitor draft campaign and its content; it cannot be restored. Sent campaigns are not affected. Not idempotent: deleting the same campaign again fails because it no longer exists.',
+ idempotent: false,
+ },
+ outputSchema: deleteDraftCampaignOutputSchema,
+ props: {
+ clientId: clientId,
+ campaignId: draftCampaignId,
+ },
+ async run({ propsValue, auth }) {
+ await makeRequest({
+ auth: { apiKey: auth.secret_text },
+ method: HttpMethod.DELETE,
+ path: `/campaigns/${propsValue.campaignId}.json`,
+ });
+ return {
+ success: true,
+ campaignId: propsValue.campaignId,
+ };
+ },
+});
diff --git a/packages/pieces/community/campaign-monitor/src/lib/actions/delete-subscriber.ts b/packages/pieces/community/campaign-monitor/src/lib/actions/delete-subscriber.ts
new file mode 100644
index 00000000000..fa68c400faa
--- /dev/null
+++ b/packages/pieces/community/campaign-monitor/src/lib/actions/delete-subscriber.ts
@@ -0,0 +1,43 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { makeRequest } from '../common/client';
+import { campaignMonitorAuth } from '../auth';
+import { clientId, listId } from '../common/props';
+import { subscriptionResultOutputSchema } from '../output-schemas';
+
+export const deleteSubscriberAction = createAction({
+ auth: campaignMonitorAuth,
+ name: 'delete_subscriber',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Delete Subscriber',
+ description: 'Moves a subscriber to the Deleted state of a list.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Deletes a subscriber, identified by email, from a Campaign Monitor list: they move to the Deleted state and will not receive any further sends to that list, but can be added again later. Choose Unsubscribe Subscriber instead to record an opt-out. Idempotent: deleting an email that was already deleted succeeds again with no change.',
+ idempotent: true,
+ },
+ outputSchema: subscriptionResultOutputSchema,
+ props: {
+ clientId: clientId,
+ listId: listId,
+ email: Property.ShortText({
+ displayName: 'Email Address',
+ description: 'The email address of the subscriber to delete.',
+ required: true,
+ }),
+ },
+ async run({ propsValue, auth }) {
+ const { listId, email } = propsValue;
+ await makeRequest({
+ auth: { apiKey: auth.secret_text },
+ method: HttpMethod.DELETE,
+ path: `/subscribers/${listId}.json?email=${encodeURIComponent(email)}`,
+ });
+ return {
+ success: true,
+ emailAddress: email,
+ listId,
+ };
+ },
+});
diff --git a/packages/pieces/community/campaign-monitor/src/lib/actions/find-subscriber.ts b/packages/pieces/community/campaign-monitor/src/lib/actions/find-subscriber.ts
index 7b670cc6aff..4ac8a21b995 100644
--- a/packages/pieces/community/campaign-monitor/src/lib/actions/find-subscriber.ts
+++ b/packages/pieces/community/campaign-monitor/src/lib/actions/find-subscriber.ts
@@ -1,6 +1,11 @@
import { createAction, Property } from '@activepieces/pieces-framework';
import { HttpMethod } from '@activepieces/pieces-common';
-import { makeRequest, transformCustomFields } from '../common/client';
+import {
+ isSubscriberNotFoundError,
+ makeRequest,
+ transformCustomFields,
+} from '../common/client';
+import { findSubscriberOutputSchema } from '../output-schemas';
import { campaignMonitorAuth } from '../auth';
import { clientId, listId } from '../common/props';
@@ -10,6 +15,7 @@ export const findSubscriberAction = createAction({
classification: 'READ',
displayName: 'Find Subscriber',
description: 'Find a subscriber by email in a specific list.',
+ outputSchema: findSubscriberOutputSchema,
audience: 'both',
aiMetadata: {
description:
@@ -29,27 +35,33 @@ export const findSubscriberAction = createAction({
const { listId, email } = propsValue;
try {
- const response = await makeRequest(
- { apiKey: auth.secret_text },
- HttpMethod.GET,
- `/subscribers/${listId}.json?email=${encodeURIComponent(
+ const response = await makeRequest<
+ Record<string, unknown> & {
+ CustomFields?: Array<{ Key: string; Value: string }>;
+ }
+ >({
+ auth: { apiKey: auth.secret_text },
+ method: HttpMethod.GET,
+ path: `/subscribers/${listId}.json?email=${encodeURIComponent(
email
- )}&includetrackingpreference=true`
- );
+ )}&includetrackingpreference=true`,
+ });
return {
found: true,
result: {
- ...response.body,
- CustomFields:transformCustomFields(response.body['CustomFields'])
+ ...response.body,
+ CustomFields: transformCustomFields(response.body.CustomFields),
},
};
} catch (error) {
- // If subscriber is not found, API returns a 404
- return {
- found: false,
- result: null,
- };
+ if (isSubscriberNotFoundError(error)) {
+ return {
+ found: false,
+ result: null,
+ };
+ }
+ throw error;
}
},
});
diff --git a/packages/pieces/community/campaign-monitor/src/lib/actions/get-campaign-activity.ts b/packages/pieces/community/campaign-monitor/src/lib/actions/get-campaign-activity.ts
new file mode 100644
index 00000000000..2432a410442
--- /dev/null
+++ b/packages/pieces/community/campaign-monitor/src/lib/actions/get-campaign-activity.ts
@@ -0,0 +1,111 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { clampPage, clampPageSize, makeRequest } from '../common/client';
+import { campaignMonitorAuth } from '../auth';
+import { clientId, sentCampaignId } from '../common/props';
+import { campaignActivityOutputSchema } from '../output-schemas';
+
+export const getCampaignActivityAction = createAction({
+ auth: campaignMonitorAuth,
+ name: 'get_campaign_activity',
+ classification: 'SEARCH',
+ displayName: 'Get Campaign Activity',
+ description: 'Returns one page of recipients, opens, clicks or bounces.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Returns one page of per-subscriber activity for a sent Campaign Monitor campaign. Activity Type picks the report: recipients (who it was sent to), opens, clicks (with the clicked URL), bounces (with bounce type and reason) or unsubscribes. Since Date limits opens, clicks, bounces and unsubscribes to events on or after that day and is ignored for recipients. The output includes PageNumber, NumberOfPages and TotalNumberOfRecords; request the next Page to read further. Page size is clamped to 10-1000. Read-only and idempotent.',
+ idempotent: true,
+ },
+ outputSchema: campaignActivityOutputSchema,
+ props: {
+ clientId: clientId,
+ campaignId: sentCampaignId,
+ activityType: Property.StaticDropdown({
+ displayName: 'Activity Type',
+ required: true,
+ defaultValue: 'opens',
+ options: {
+ options: [
+ { label: 'Recipients', value: 'recipients' },
+ { label: 'Opens', value: 'opens' },
+ { label: 'Clicks', value: 'clicks' },
+ { label: 'Bounces', value: 'bounces' },
+ { label: 'Unsubscribes', value: 'unsubscribes' },
+ ],
+ },
+ }),
+ sinceDate: Property.DateTime({
+ displayName: 'Since Date',
+ description:
+ 'Only activity on or after this day. Ignored for recipients.',
+ required: false,
+ }),
+ page: Property.Number({
+ displayName: 'Page',
+ description: 'Page number to return, starting at 1.',
+ required: false,
+ defaultValue: 1,
+ }),
+ pageSize: Property.Number({
+ displayName: 'Page Size',
+ description: 'Records per page, between 10 and 1000.',
+ required: false,
+ defaultValue: 100,
+ }),
+ orderDirection: Property.StaticDropdown({
+ displayName: 'Order Direction',
+ required: false,
+ defaultValue: 'desc',
+ options: {
+ options: [
+ { label: 'Newest first', value: 'desc' },
+ { label: 'Oldest first', value: 'asc' },
+ ],
+ },
+ }),
+ },
+ async run({ propsValue, auth }) {
+ const activityType = propsValue.activityType;
+ if (!ACTIVITY_TYPES.includes(activityType)) {
+ throw new Error(`Unsupported activity type: ${activityType}`);
+ }
+ const query = new URLSearchParams({
+ page: String(clampPage(propsValue.page)),
+ pagesize: String(clampPageSize(propsValue.pageSize)),
+ orderdirection: propsValue.orderDirection ?? 'desc',
+ });
+ if (activityType === 'recipients') {
+ query.set('orderfield', 'email');
+ } else {
+ query.set('orderfield', 'date');
+ if (propsValue.sinceDate) {
+ query.set('date', toApiDate(propsValue.sinceDate));
+ }
+ }
+ const response = await makeRequest({
+ auth: { apiKey: auth.secret_text },
+ method: HttpMethod.GET,
+ path: `/campaigns/${
+ propsValue.campaignId
+ }/${activityType}.json?${query.toString()}`,
+ });
+ return response.body;
+ },
+});
+
+const ACTIVITY_TYPES = [
+ 'recipients',
+ 'opens',
+ 'clicks',
+ 'bounces',
+ 'unsubscribes',
+];
+
+function toApiDate(value: string) {
+ const date = new Date(value);
+ if (Number.isNaN(date.getTime())) {
+ throw new Error(`Invalid date: ${value}`);
+ }
+ return date.toISOString().slice(0, 10);
+}
diff --git a/packages/pieces/community/campaign-monitor/src/lib/actions/get-campaign-summary.ts b/packages/pieces/community/campaign-monitor/src/lib/actions/get-campaign-summary.ts
new file mode 100644
index 00000000000..46ac141a505
--- /dev/null
+++ b/packages/pieces/community/campaign-monitor/src/lib/actions/get-campaign-summary.ts
@@ -0,0 +1,33 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { makeRequest } from '../common/client';
+import { campaignMonitorAuth } from '../auth';
+import { clientId, sentCampaignId } from '../common/props';
+import { campaignSummaryOutputSchema } from '../output-schemas';
+
+export const getCampaignSummaryAction = createAction({
+ auth: campaignMonitorAuth,
+ name: 'get_campaign_summary',
+ classification: 'READ',
+ displayName: 'Get Campaign Summary',
+ description: 'Returns the reporting summary of a sent campaign.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Returns the reporting totals of one sent Campaign Monitor campaign: recipients, total and unique opens, clicks, unsubscribes, bounces, spam complaints, forwards, likes, mentions and the web version and Worldview links. Read-only and idempotent.',
+ idempotent: true,
+ },
+ outputSchema: campaignSummaryOutputSchema,
+ props: {
+ clientId: clientId,
+ campaignId: sentCampaignId,
+ },
+ async run({ propsValue, auth }) {
+ const response = await makeRequest({
+ auth: { apiKey: auth.secret_text },
+ method: HttpMethod.GET,
+ path: `/campaigns/${propsValue.campaignId}/summary.json`,
+ });
+ return response.body;
+ },
+});
diff --git a/packages/pieces/community/campaign-monitor/src/lib/actions/get-list-stats.ts b/packages/pieces/community/campaign-monitor/src/lib/actions/get-list-stats.ts
new file mode 100644
index 00000000000..c0a38aa5a51
--- /dev/null
+++ b/packages/pieces/community/campaign-monitor/src/lib/actions/get-list-stats.ts
@@ -0,0 +1,33 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { makeRequest } from '../common/client';
+import { campaignMonitorAuth } from '../auth';
+import { clientId, listId } from '../common/props';
+import { listStatsOutputSchema } from '../output-schemas';
+
+export const getListStatsAction = createAction({
+ auth: campaignMonitorAuth,
+ name: 'get_list_stats',
+ classification: 'READ',
+ displayName: 'Get List Stats',
+ description: 'Returns subscriber growth and totals for a list.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Returns statistics for a Campaign Monitor list: total active, unsubscribed, deleted and bounced subscribers, plus new subscribers, unsubscribes, deletes and bounces today, yesterday, this week, this month and this year. Read-only and idempotent.',
+ idempotent: true,
+ },
+ outputSchema: listStatsOutputSchema,
+ props: {
+ clientId: clientId,
+ listId: listId,
+ },
+ async run({ propsValue, auth }) {
+ const response = await makeRequest({
+ auth: { apiKey: auth.secret_text },
+ method: HttpMethod.GET,
+ path: `/lists/${propsValue.listId}/stats.json`,
+ });
+ return response.body;
+ },
+});
diff --git a/packages/pieces/community/campaign-monitor/src/lib/actions/get-list-subscribers.ts b/packages/pieces/community/campaign-monitor/src/lib/actions/get-list-subscribers.ts
new file mode 100644
index 00000000000..76bed9c45bc
--- /dev/null
+++ b/packages/pieces/community/campaign-monitor/src/lib/actions/get-list-subscribers.ts
@@ -0,0 +1,119 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import {
+ clampPage,
+ clampPageSize,
+ makeRequest,
+ transformCustomFields,
+} from '../common/client';
+import { campaignMonitorAuth } from '../auth';
+import { clientId, listId } from '../common/props';
+import { listSubscribersOutputSchema } from '../output-schemas';
+
+export const getListSubscribersAction = createAction({
+ auth: campaignMonitorAuth,
+ name: 'get_list_subscribers',
+ classification: 'SEARCH',
+ displayName: 'Get List Subscribers',
+ description: 'Returns one page of subscribers in a list, filtered by state.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Returns one page of subscribers from a Campaign Monitor list, filtered by state (active, unsubscribed, bounced, deleted or unconfirmed), with custom fields flattened into a key/value object. The output includes PageNumber, NumberOfPages and TotalNumberOfRecords; request the next Page to read further. Page size is clamped to 10-1000. Read-only and idempotent.',
+ idempotent: true,
+ },
+ outputSchema: listSubscribersOutputSchema,
+ props: {
+ clientId: clientId,
+ listId: listId,
+ state: Property.StaticDropdown({
+ displayName: 'State',
+ required: true,
+ defaultValue: 'active',
+ options: {
+ options: [
+ { label: 'Active', value: 'active' },
+ { label: 'Unsubscribed', value: 'unsubscribed' },
+ { label: 'Bounced', value: 'bounced' },
+ { label: 'Deleted', value: 'deleted' },
+ { label: 'Unconfirmed', value: 'unconfirmed' },
+ ],
+ },
+ }),
+ page: Property.Number({
+ displayName: 'Page',
+ description: 'Page number to return, starting at 1.',
+ required: false,
+ defaultValue: 1,
+ }),
+ pageSize: Property.Number({
+ displayName: 'Page Size',
+ description: 'Subscribers per page, between 10 and 1000.',
+ required: false,
+ defaultValue: 100,
+ }),
+ orderField: Property.StaticDropdown({
+ displayName: 'Order By',
+ required: false,
+ defaultValue: 'date',
+ options: {
+ options: [
+ { label: 'Date', value: 'date' },
+ { label: 'Email', value: 'email' },
+ { label: 'Name', value: 'name' },
+ ],
+ },
+ }),
+ orderDirection: Property.StaticDropdown({
+ displayName: 'Order Direction',
+ required: false,
+ defaultValue: 'asc',
+ options: {
+ options: [
+ { label: 'Ascending', value: 'asc' },
+ { label: 'Descending', value: 'desc' },
+ ],
+ },
+ }),
+ },
+ async run({ propsValue, auth }) {
+ const query = new URLSearchParams({
+ page: String(clampPage(propsValue.page)),
+ pagesize: String(clampPageSize(propsValue.pageSize)),
+ orderfield: propsValue.orderField ?? 'date',
+ orderdirection: propsValue.orderDirection ?? 'asc',
+ includetrackingpreference: 'true',
+ includesmspreference: 'true',
+ });
+ const response = await makeRequest<{
+ Results: Array<
+ Record<string, unknown> & {
+ CustomFields?: Array<{ Key: string; Value: string }>;
+ }
+ >;
+ PageNumber: number;
+ PageSize: number;
+ RecordsOnThisPage: number;
+ TotalNumberOfRecords: number;
+ NumberOfPages: number;
+ }>({
+ auth: { apiKey: auth.secret_text },
+ method: HttpMethod.GET,
+ path: `/lists/${propsValue.listId}/${
+ propsValue.state
+ }.json?${query.toString()}`,
+ });
+ const body = response.body;
+ return {
+ Results: (body.Results ?? []).map((subscriber) => ({
+ ...subscriber,
+ CustomFields: transformCustomFields(subscriber.CustomFields),
+ })),
+ PageNumber: body.PageNumber,
+ PageSize: body.PageSize,
+ RecordsOnThisPage: body.RecordsOnThisPage,
+ TotalNumberOfRecords: body.TotalNumberOfRecords,
+ NumberOfPages: body.NumberOfPages,
+ };
+ },
+});
diff --git a/packages/pieces/community/campaign-monitor/src/lib/actions/list-clients.ts b/packages/pieces/community/campaign-monitor/src/lib/actions/list-clients.ts
new file mode 100644
index 00000000000..84e932eca1e
--- /dev/null
+++ b/packages/pieces/community/campaign-monitor/src/lib/actions/list-clients.ts
@@ -0,0 +1,29 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { makeRequest } from '../common/client';
+import { campaignMonitorAuth } from '../auth';
+import { listClientsOutputSchema } from '../output-schemas';
+
+export const listClientsAction = createAction({
+ auth: campaignMonitorAuth,
+ name: 'list_clients',
+ classification: 'SEARCH',
+ displayName: 'List Clients',
+ description: 'Returns all clients in your Campaign Monitor account.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Returns every client (ID and name) in the connected Campaign Monitor account. Choose this first to discover the client ID that List Lists, List Sent Campaigns, Send Smart Transactional Email and the subscriber actions need. Read-only and idempotent.',
+ idempotent: true,
+ },
+ outputSchema: listClientsOutputSchema,
+ props: {},
+ async run({ auth }) {
+ const response = await makeRequest<{ ClientID: string; Name: string }[]>({
+ auth: { apiKey: auth.secret_text },
+ method: HttpMethod.GET,
+ path: '/clients.json',
+ });
+ return response.body;
+ },
+});
diff --git a/packages/pieces/community/campaign-monitor/src/lib/actions/list-lists.ts b/packages/pieces/community/campaign-monitor/src/lib/actions/list-lists.ts
new file mode 100644
index 00000000000..e1d21918dec
--- /dev/null
+++ b/packages/pieces/community/campaign-monitor/src/lib/actions/list-lists.ts
@@ -0,0 +1,32 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { makeRequest } from '../common/client';
+import { campaignMonitorAuth } from '../auth';
+import { clientId } from '../common/props';
+import { listListsOutputSchema } from '../output-schemas';
+
+export const listListsAction = createAction({
+ auth: campaignMonitorAuth,
+ name: 'list_lists',
+ classification: 'SEARCH',
+ displayName: 'List Lists',
+ description: 'Returns all subscriber lists of a client.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Returns every subscriber list (ID and name) that belongs to one Campaign Monitor client. Choose this to discover list IDs before adding, finding or listing subscribers. Read-only and idempotent.',
+ idempotent: true,
+ },
+ outputSchema: listListsOutputSchema,
+ props: {
+ clientId: clientId,
+ },
+ async run({ propsValue, auth }) {
+ const response = await makeRequest<{ ListID: string; Name: string }[]>({
+ auth: { apiKey: auth.secret_text },
+ method: HttpMethod.GET,
+ path: `/clients/${propsValue.clientId}/lists.json`,
+ });
+ return response.body;
+ },
+});
diff --git a/packages/pieces/community/campaign-monitor/src/lib/actions/list-sent-campaigns.ts b/packages/pieces/community/campaign-monitor/src/lib/actions/list-sent-campaigns.ts
new file mode 100644
index 00000000000..ab4cb488fd5
--- /dev/null
+++ b/packages/pieces/community/campaign-monitor/src/lib/actions/list-sent-campaigns.ts
@@ -0,0 +1,99 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { clampPage, clampPageSize, makeRequest } from '../common/client';
+import { campaignMonitorAuth } from '../auth';
+import { clientId } from '../common/props';
+import { listCampaignsOutputSchema } from '../output-schemas';
+
+export const listSentCampaignsAction = createAction({
+ auth: campaignMonitorAuth,
+ name: 'list_sent_campaigns',
+ classification: 'SEARCH',
+ displayName: 'List Sent Campaigns',
+ description: 'Returns one page of campaigns a client has sent.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Returns one page of sent campaigns for a Campaign Monitor client (ID, name, subject, sender, sent date, recipient count, web version links), optionally limited to a sent-date range (To date exclusive) and to campaigns with given tags. The output includes PageNumber, NumberOfPages and TotalNumberOfRecords; request the next Page to read further. Page size is clamped to 10-1000. Read-only and idempotent.',
+ idempotent: true,
+ },
+ outputSchema: listCampaignsOutputSchema,
+ props: {
+ clientId: clientId,
+ sentFromDate: Property.DateTime({
+ displayName: 'Sent From Date',
+ description: 'Only campaigns sent on or after this date.',
+ required: false,
+ }),
+ sentToDate: Property.DateTime({
+ displayName: 'Sent To Date',
+ description:
+ 'Only campaigns sent before this date (the date itself is excluded).',
+ required: false,
+ }),
+ tags: Property.ShortText({
+ displayName: 'Tags',
+ description: 'Only campaigns with these tags, as a comma-separated list.',
+ required: false,
+ }),
+ page: Property.Number({
+ displayName: 'Page',
+ description: 'Page number to return, starting at 1.',
+ required: false,
+ defaultValue: 1,
+ }),
+ pageSize: Property.Number({
+ displayName: 'Page Size',
+ description: 'Campaigns per page, between 10 and 1000.',
+ required: false,
+ defaultValue: 100,
+ }),
+ orderDirection: Property.StaticDropdown({
+ displayName: 'Order Direction',
+ required: false,
+ defaultValue: 'desc',
+ options: {
+ options: [
+ { label: 'Newest first', value: 'desc' },
+ { label: 'Oldest first', value: 'asc' },
+ ],
+ },
+ }),
+ },
+ async run({ propsValue, auth }) {
+ const query = new URLSearchParams({
+ page: String(clampPage(propsValue.page)),
+ pagesize: String(clampPageSize(propsValue.pageSize)),
+ orderdirection: propsValue.orderDirection ?? 'desc',
+ });
+ if (propsValue.sentFromDate) {
+ query.set('sentfromdate', toApiDate(propsValue.sentFromDate));
+ }
+ if (propsValue.sentToDate) {
+ query.set('senttodate', toApiDate(propsValue.sentToDate));
+ }
+ const tags = propsValue.tags
+ ?.split(',')
+ .map((tag) => tag.trim())
+ .filter((tag) => tag.length > 0);
+ if (tags && tags.length > 0) {
+ query.set('tags', tags.join(','));
+ }
+ const response = await makeRequest({
+ auth: { apiKey: auth.secret_text },
+ method: HttpMethod.GET,
+ path: `/clients/${
+ propsValue.clientId
+ }/campaigns.json?${query.toString()}`,
+ });
+ return response.body;
+ },
+});
+
+function toApiDate(value: string) {
+ const date = new Date(value);
+ if (Number.isNaN(date.getTime())) {
+ throw new Error(`Invalid date: ${value}`);
+ }
+ return date.toISOString().slice(0, 10);
+}
diff --git a/packages/pieces/community/campaign-monitor/src/lib/actions/list-smart-emails.ts b/packages/pieces/community/campaign-monitor/src/lib/actions/list-smart-emails.ts
new file mode 100644
index 00000000000..a8326fe2756
--- /dev/null
+++ b/packages/pieces/community/campaign-monitor/src/lib/actions/list-smart-emails.ts
@@ -0,0 +1,54 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { makeRequest } from '../common/client';
+import { campaignMonitorAuth } from '../auth';
+import { clientId } from '../common/props';
+import { listSmartEmailsOutputSchema } from '../output-schemas';
+
+export const listSmartEmailsAction = createAction({
+ auth: campaignMonitorAuth,
+ name: 'list_smart_emails',
+ classification: 'SEARCH',
+ displayName: 'List Smart Emails',
+ description: 'Returns the smart transactional emails of a client.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Returns the smart transactional emails (ID, name, status, creation date) of one Campaign Monitor client, filtered by status. Choose this to discover the smart email ID that Send Smart Transactional Email needs. Read-only and idempotent.',
+ idempotent: true,
+ },
+ outputSchema: listSmartEmailsOutputSchema,
+ props: {
+ clientId: clientId,
+ status: Property.StaticDropdown({
+ displayName: 'Status',
+ required: false,
+ defaultValue: 'active',
+ options: {
+ options: [
+ { label: 'Active', value: 'active' },
+ { label: 'Draft', value: 'draft' },
+ { label: 'All', value: 'all' },
+ ],
+ },
+ }),
+ },
+ async run({ propsValue, auth }) {
+ const status = propsValue.status ?? 'active';
+ const response = await makeRequest<
+ {
+ ID: string;
+ Name: string;
+ CreatedAt: string;
+ Status: string;
+ }[]
+ >({
+ auth: { apiKey: auth.secret_text },
+ method: HttpMethod.GET,
+ path: `/transactional/smartEmail?status=${status}&clientID=${encodeURIComponent(
+ propsValue.clientId
+ )}`,
+ });
+ return response.body;
+ },
+});
diff --git a/packages/pieces/community/campaign-monitor/src/lib/actions/send-campaign.ts b/packages/pieces/community/campaign-monitor/src/lib/actions/send-campaign.ts
new file mode 100644
index 00000000000..2633f0d0ce6
--- /dev/null
+++ b/packages/pieces/community/campaign-monitor/src/lib/actions/send-campaign.ts
@@ -0,0 +1,69 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { makeRequest } from '../common/client';
+import { campaignMonitorAuth } from '../auth';
+import { clientId, draftCampaignId } from '../common/props';
+import { sendCampaignOutputSchema } from '../output-schemas';
+
+export const sendCampaignAction = createAction({
+ auth: campaignMonitorAuth,
+ name: 'send_campaign',
+ classification: 'WRITE',
+ displayName: 'Send Campaign',
+ description: 'Sends or schedules a draft campaign.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Sends a Campaign Monitor draft campaign to its lists and segments, either immediately or at a scheduled time (YYYY-MM-DD HH:MM in the client time zone), and emails a confirmation to the given addresses. Once sent, emails cannot be recalled. Not idempotent: a draft can only be sent once, so a retry after success fails.',
+ idempotent: false,
+ },
+ outputSchema: sendCampaignOutputSchema,
+ props: {
+ clientId: clientId,
+ campaignId: draftCampaignId,
+ confirmationEmail: Property.ShortText({
+ displayName: 'Confirmation Email',
+ description: 'Up to 5 comma-separated addresses notified when sent.',
+ required: true,
+ }),
+ sendDate: Property.ShortText({
+ displayName: 'Send Date',
+ description: '"Immediately" or YYYY-MM-DD HH:MM in the client time zone.',
+ required: true,
+ defaultValue: 'Immediately',
+ }),
+ },
+ async run({ propsValue, auth }) {
+ const sendDate = propsValue.sendDate.trim();
+ if (
+ sendDate.toLowerCase() !== 'immediately' &&
+ !SEND_DATE_FORMAT.test(sendDate)
+ ) {
+ throw new Error(
+ 'Send Date must be "Immediately" or in the format YYYY-MM-DD HH:MM.'
+ );
+ }
+ const normalizedSendDate =
+ sendDate.toLowerCase() === 'immediately' ? 'Immediately' : sendDate;
+ await makeRequest({
+ auth: { apiKey: auth.secret_text },
+ method: HttpMethod.POST,
+ path: `/campaigns/${propsValue.campaignId}/send.json`,
+ body: {
+ ConfirmationEmail: propsValue.confirmationEmail
+ .split(',')
+ .map((address) => address.trim())
+ .filter((address) => address.length > 0)
+ .join(','),
+ SendDate: normalizedSendDate,
+ },
+ });
+ return {
+ success: true,
+ campaignId: propsValue.campaignId,
+ sendDate: normalizedSendDate,
+ };
+ },
+});
+
+const SEND_DATE_FORMAT = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}$/;
diff --git a/packages/pieces/community/campaign-monitor/src/lib/actions/send-smart-email.ts b/packages/pieces/community/campaign-monitor/src/lib/actions/send-smart-email.ts
new file mode 100644
index 00000000000..c22fc9070a1
--- /dev/null
+++ b/packages/pieces/community/campaign-monitor/src/lib/actions/send-smart-email.ts
@@ -0,0 +1,99 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { makeRequest } from '../common/client';
+import { campaignMonitorAuth } from '../auth';
+import { clientId, smartEmailId } from '../common/props';
+import { sendSmartEmailOutputSchema } from '../output-schemas';
+
+export const sendSmartEmailAction = createAction({
+ auth: campaignMonitorAuth,
+ name: 'send_smart_email',
+ classification: 'WRITE',
+ displayName: 'Send Smart Transactional Email',
+ description: 'Sends a smart transactional email to one or more recipients.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Sends an existing Campaign Monitor smart transactional email template to the given recipients, filling its variables from Data, and returns one message ID per recipient. Choose this for one-off transactional sends such as receipts or password resets. Not idempotent: each call sends the email again.',
+ idempotent: false,
+ },
+ outputSchema: sendSmartEmailOutputSchema,
+ props: {
+ clientId: clientId,
+ smartEmailId: smartEmailId,
+ to: Property.Array({
+ displayName: 'To',
+ description:
+ 'Recipients, as an email address or "Name <[email protected]>".',
+ required: true,
+ }),
+ cc: Property.Array({
+ displayName: 'CC',
+ required: false,
+ }),
+ bcc: Property.Array({
+ displayName: 'BCC',
+ required: false,
+ }),
+ data: Property.Json({
+ displayName: 'Data',
+ description: 'Values for the smart email variables, as a JSON object.',
+ required: false,
+ defaultValue: {},
+ }),
+ addRecipientsToList: Property.Checkbox({
+ displayName: 'Add Recipients to List',
+ description:
+ 'Add the recipients to the list configured on the smart email.',
+ required: false,
+ defaultValue: false,
+ }),
+ consentToTrack: Property.StaticDropdown({
+ displayName: 'Consent to Track',
+ description: 'Whether the recipients have consented to tracking.',
+ required: true,
+ defaultValue: 'Unchanged',
+ options: {
+ options: [
+ { label: 'Yes', value: 'Yes' },
+ { label: 'No', value: 'No' },
+ { label: 'Unchanged', value: 'Unchanged' },
+ ],
+ },
+ }),
+ },
+ async run({ propsValue, auth }) {
+ const to = toAddressList(propsValue.to);
+ if (to.length === 0) {
+ throw new Error('Add at least one recipient in To.');
+ }
+ const cc = toAddressList(propsValue.cc);
+ const bcc = toAddressList(propsValue.bcc);
+ const response = await makeRequest<
+ {
+ MessageID: string;
+ Recipient: string;
+ Status: string;
+ }[]
+ >({
+ auth: { apiKey: auth.secret_text },
+ method: HttpMethod.POST,
+ path: `/transactional/smartEmail/${propsValue.smartEmailId}/send`,
+ body: {
+ To: to,
+ CC: cc.length > 0 ? cc : undefined,
+ BCC: bcc.length > 0 ? bcc : undefined,
+ Data: propsValue.data ?? {},
+ AddRecipientsToList: propsValue.addRecipientsToList ?? false,
+ ConsentToTrack: propsValue.consentToTrack,
+ },
+ });
+ return response.body;
+ },
+});
+
+function toAddressList(value: unknown[] | undefined) {
+ return (value ?? [])
+ .map((item) => String(item ?? '').trim())
+ .filter((item) => item.length > 0);
+}
diff --git a/packages/pieces/community/campaign-monitor/src/lib/actions/suppress-emails.ts b/packages/pieces/community/campaign-monitor/src/lib/actions/suppress-emails.ts
new file mode 100644
index 00000000000..fa6cdbb7f37
--- /dev/null
+++ b/packages/pieces/community/campaign-monitor/src/lib/actions/suppress-emails.ts
@@ -0,0 +1,47 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { makeRequest } from '../common/client';
+import { campaignMonitorAuth } from '../auth';
+import { clientId } from '../common/props';
+import { suppressEmailsOutputSchema } from '../output-schemas';
+
+export const suppressEmailsAction = createAction({
+ auth: campaignMonitorAuth,
+ name: 'suppress_emails',
+ classification: 'WRITE',
+ displayName: 'Add Emails to Suppression List',
+ description: 'Stops a client from sending to the given email addresses.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Adds one or more email addresses to a Campaign Monitor client suppression list, so no campaign from that client is sent to them; their subscriber records stay in place. Reverse with Remove Email from Suppression List. Idempotent: suppressing an address that is already suppressed changes nothing.',
+ idempotent: true,
+ },
+ outputSchema: suppressEmailsOutputSchema,
+ props: {
+ clientId: clientId,
+ emails: Property.Array({
+ displayName: 'Email Addresses',
+ description: 'Addresses to add to the suppression list.',
+ required: true,
+ }),
+ },
+ async run({ propsValue, auth }) {
+ const emails = propsValue.emails
+ .map((email) => String(email).trim())
+ .filter((email) => email.length > 0);
+ if (emails.length === 0) {
+ throw new Error('Provide at least one email address.');
+ }
+ await makeRequest({
+ auth: { apiKey: auth.secret_text },
+ method: HttpMethod.POST,
+ path: `/clients/${propsValue.clientId}/suppress.json`,
+ body: { EmailAddresses: emails },
+ });
+ return {
+ success: true,
+ emailAddresses: emails,
+ };
+ },
+});
diff --git a/packages/pieces/community/campaign-monitor/src/lib/actions/unsubscribe-subscriber.ts b/packages/pieces/community/campaign-monitor/src/lib/actions/unsubscribe-subscriber.ts
index 399e4d9e5cd..2f2704b5174 100644
--- a/packages/pieces/community/campaign-monitor/src/lib/actions/unsubscribe-subscriber.ts
+++ b/packages/pieces/community/campaign-monitor/src/lib/actions/unsubscribe-subscriber.ts
@@ -1,6 +1,7 @@
import { createAction, Property } from '@activepieces/pieces-framework';
import { HttpMethod } from '@activepieces/pieces-common';
import { makeRequest } from '../common/client';
+import { subscriptionResultOutputSchema } from '../output-schemas';
import { campaignMonitorAuth } from '../auth';
import { clientId, listId } from '../common/props';
@@ -10,11 +11,12 @@ export const unsubscribeSubscriberAction = createAction({
classification: 'DESTRUCTIVE',
displayName: 'Unsubscribe Subscriber',
description: 'Remove a subscriber from a list.',
+ outputSchema: subscriptionResultOutputSchema,
audience: 'both',
aiMetadata: {
description:
- 'Unsubscribes a subscriber, identified by email, from a specific Campaign Monitor list under a client, marking them as opted out. Choose this to suppress a contact from further sends on that list. Idempotent: repeating the call leaves the subscriber in the same unsubscribed state.',
- idempotent: true,
+ 'Unsubscribes a subscriber, identified by email, from a specific Campaign Monitor list under a client, marking them as opted out. Choose this to record an opt-out and suppress further sends on that list; use Delete Subscriber instead to remove the contact without recording an opt-out. Not idempotent: calling it again for an email that is already unsubscribed, or not on the list, fails with Campaign Monitor error 203.',
+ idempotent: false,
},
props: {
clientId: clientId,
@@ -32,21 +34,17 @@ export const unsubscribeSubscriberAction = createAction({
EmailAddress: email,
};
- const response = await makeRequest(
- { apiKey: auth.secret_text },
- HttpMethod.POST,
- `/subscribers/${listId}/unsubscribe.json`,
- payload
- );
+ await makeRequest({
+ auth: { apiKey: auth.secret_text },
+ method: HttpMethod.POST,
+ path: `/subscribers/${listId}/unsubscribe.json`,
+ body: payload,
+ });
- if (response.status === 200) {
- return {
- success: true,
- };
- }
return {
- success: false,
- error: response.body,
+ success: true,
+ emailAddress: email,
+ listId,
};
},
});
diff --git a/packages/pieces/community/campaign-monitor/src/lib/actions/unsuppress-email.ts b/packages/pieces/community/campaign-monitor/src/lib/actions/unsuppress-email.ts
new file mode 100644
index 00000000000..b2eba59c0e9
--- /dev/null
+++ b/packages/pieces/community/campaign-monitor/src/lib/actions/unsuppress-email.ts
@@ -0,0 +1,57 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { getApiErrorCode, makeRequest } from '../common/client';
+import { campaignMonitorAuth } from '../auth';
+import { clientId } from '../common/props';
+import { unsuppressEmailOutputSchema } from '../output-schemas';
+
+export const unsuppressEmailAction = createAction({
+ auth: campaignMonitorAuth,
+ name: 'unsuppress_email',
+ classification: 'WRITE',
+ displayName: 'Remove Email from Suppression List',
+ description: 'Lets a client send to a suppressed email address again.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Removes an email address from a Campaign Monitor client suppression list so campaigns from that client can reach it again. It does not resubscribe the contact to any list. Idempotent: removing an address that is not suppressed succeeds with no change and wasSuppressed false.',
+ idempotent: true,
+ },
+ outputSchema: unsuppressEmailOutputSchema,
+ props: {
+ clientId: clientId,
+ email: Property.ShortText({
+ displayName: 'Email Address',
+ description: 'Address to remove from the suppression list.',
+ required: true,
+ }),
+ },
+ async run({ propsValue, auth }) {
+ const email = propsValue.email.trim();
+ try {
+ await makeRequest({
+ auth: { apiKey: auth.secret_text },
+ method: HttpMethod.PUT,
+ path: `/clients/${
+ propsValue.clientId
+ }/unsuppress.json?email=${encodeURIComponent(email)}`,
+ });
+ } catch (error) {
+ if (getApiErrorCode(error) !== NOT_SUPPRESSED_CODE) {
+ throw error;
+ }
+ return {
+ success: true,
+ emailAddress: email,
+ wasSuppressed: false,
+ };
+ }
+ return {
+ success: true,
+ emailAddress: email,
+ wasSuppressed: true,
+ };
+ },
+});
+
+const NOT_SUPPRESSED_CODE = 176;
diff --git a/packages/pieces/community/campaign-monitor/src/lib/actions/update-subscriber-details.ts b/packages/pieces/community/campaign-monitor/src/lib/actions/update-subscriber-details.ts
index c4e1eafa7ed..22977980e2c 100644
--- a/packages/pieces/community/campaign-monitor/src/lib/actions/update-subscriber-details.ts
+++ b/packages/pieces/community/campaign-monitor/src/lib/actions/update-subscriber-details.ts
@@ -1,6 +1,11 @@
import { createAction, Property } from '@activepieces/pieces-framework';
import { HttpMethod } from '@activepieces/pieces-common';
-import { makeRequest } from '../common/client';
+import {
+ buildCustomFieldsPayload,
+ fetchDateFieldKeys,
+ makeRequest,
+} from '../common/client';
+import { subscriptionResultOutputSchema } from '../output-schemas';
import { campaignMonitorAuth } from '../auth';
import { clientId, customFields, listId } from '../common/props';
@@ -10,10 +15,11 @@ export const updateSubscriberDetailsAction = createAction({
classification: 'WRITE',
displayName: 'Update Subscriber',
description: 'Update an existing subscriber in a list.',
- audience: 'both',
+ outputSchema: subscriptionResultOutputSchema,
+ audience: 'human',
aiMetadata: {
description:
- 'Updates an existing subscriber, identified by their current email address, in a specific Campaign Monitor list under a client — changing name, phone, custom fields, and tracking/SMS consent. Choose this to modify a contact already on a list rather than to add one. Idempotent: it keys on the email and overwrites the same record, so repeating with identical input leaves the subscriber in the same state.',
+ 'Builder form with a custom field per list field; agents use the JSON fields variant. Updates an existing subscriber, identified by their current email address, in a specific Campaign Monitor list under a client — changing email address (via New Email Address), name, phone, custom fields, and tracking/SMS consent. The output emailAddress is the address the subscriber has after the update. Choose this to modify a contact already on a list rather than to add one. Idempotent when the email is not changed: it keys on the email and overwrites the same record, so repeating with identical input leaves the subscriber in the same state. Custom fields left blank are not sent, so their stored values are kept.',
idempotent: true,
},
props: {
@@ -21,8 +27,15 @@ export const updateSubscriberDetailsAction = createAction({
listId: listId,
email: Property.ShortText({
displayName: 'Email Address',
+ description: 'The current email address of the subscriber.',
required: true,
}),
+ newEmail: Property.ShortText({
+ displayName: 'New Email Address',
+ description:
+ 'New email for the subscriber. Leave empty to keep the current one.',
+ required: false,
+ }),
name: Property.ShortText({
displayName: 'Name',
required: false,
@@ -35,7 +48,7 @@ export const updateSubscriberDetailsAction = createAction({
displayName: 'Consent to Track',
description: 'Whether the subscriber has consented to tracking.',
required: false,
- defaultValue: 'Yes',
+ defaultValue: 'Unchanged',
options: {
options: [
{ label: 'Yes', value: 'Yes' },
@@ -64,48 +77,48 @@ export const updateSubscriberDetailsAction = createAction({
required: false,
defaultValue: false,
}),
- fields:customFields,
+ fields: customFields,
},
async run({ propsValue, auth }) {
const {
listId,
email,
+ newEmail,
name,
consentToSendSms,
phone,
resubscribe,
consentToTrack,
- fields
+ fields,
} = propsValue;
+ const dateKeys = await fetchDateFieldKeys({
+ auth: { apiKey: auth.secret_text },
+ listId,
+ });
+
+ const targetEmail = newEmail?.trim() || email;
const payload = {
+ EmailAddress: targetEmail,
MobileNumber: phone,
Name: name,
- ConsentToTrack: consentToTrack,
- ConsentToSendSms: consentToSendSms,
- Resubscribe: resubscribe ?? true,
- CustomFields: Object.entries(fields).flatMap(([key, value]) =>
- Array.isArray(value)
- ? value.map((v) => ({ Key: key, Value: v }))
- : [{ Key: key, Value: value }]
- ),
+ ConsentToTrack: consentToTrack ?? 'Unchanged',
+ ConsentToSendSms: consentToSendSms ?? 'Unchanged',
+ Resubscribe: resubscribe ?? false,
+ CustomFields: buildCustomFieldsPayload({ fields, dateKeys }),
};
- const response = await makeRequest(
- { apiKey: auth.secret_text },
- HttpMethod.PUT,
- `/subscribers/${listId}.json?email=${encodeURIComponent(email)}`,
- payload
- );
+ await makeRequest({
+ auth: { apiKey: auth.secret_text },
+ method: HttpMethod.PUT,
+ path: `/subscribers/${listId}.json?email=${encodeURIComponent(email)}`,
+ body: payload,
+ });
- if (response.status === 200) {
- return {
- success: true,
- };
- }
return {
- success: false,
- error: response.body,
+ success: true,
+ emailAddress: targetEmail,
+ listId,
};
},
});
diff --git a/packages/pieces/community/campaign-monitor/src/lib/actions/update-subscriber-json.ts b/packages/pieces/community/campaign-monitor/src/lib/actions/update-subscriber-json.ts
new file mode 100644
index 00000000000..7c56aceb4ae
--- /dev/null
+++ b/packages/pieces/community/campaign-monitor/src/lib/actions/update-subscriber-json.ts
@@ -0,0 +1,121 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import {
+ buildCustomFieldsPayload,
+ fetchDateFieldKeys,
+ jsonCustomFieldsToRecord,
+ makeRequest,
+} from '../common/client';
+import { subscriptionResultOutputSchema } from '../output-schemas';
+import { campaignMonitorAuth } from '../auth';
+
+export const updateSubscriberJsonAction = createAction({
+ auth: campaignMonitorAuth,
+ name: 'update_subscriber_json',
+ classification: 'WRITE',
+ displayName: 'Update Subscriber (JSON fields)',
+ description: 'Updates a subscriber in a list, with custom fields as JSON.',
+ outputSchema: subscriptionResultOutputSchema,
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Updates an existing subscriber, identified by their current email, in a Campaign Monitor list given its list ID: change email (New Email Address), name, phone, tracking/SMS consent and custom fields passed as a JSON object keyed by field name (spaces are ignored, so "Favorite Color" maps to [FavoriteColor]), e.g. {"Company":"Acme","Age":30}; use an array value for multi-select fields and YYYY-MM-DD for dates. Fields left out or empty keep their stored values. The output emailAddress is the address after the update. Idempotent when the email is not changed: repeating with identical input leaves the subscriber in the same state.',
+ idempotent: true,
+ },
+ props: {
+ listId: Property.ShortText({
+ displayName: 'List ID',
+ description: 'ID of the list the subscriber belongs to.',
+ required: true,
+ }),
+ email: Property.ShortText({
+ displayName: 'Email Address',
+ description: 'The current email address of the subscriber.',
+ required: true,
+ }),
+ newEmail: Property.ShortText({
+ displayName: 'New Email Address',
+ description: 'New email for the subscriber. Leave empty to keep it.',
+ required: false,
+ }),
+ name: Property.ShortText({
+ displayName: 'Name',
+ required: false,
+ }),
+ phone: Property.ShortText({
+ displayName: 'Phone',
+ required: false,
+ }),
+ consentToTrack: Property.StaticDropdown({
+ displayName: 'Consent to Track',
+ description: 'Whether the subscriber has consented to tracking.',
+ required: false,
+ defaultValue: 'Unchanged',
+ options: {
+ options: [
+ { label: 'Yes', value: 'Yes' },
+ { label: 'No', value: 'No' },
+ { label: 'Unchanged', value: 'Unchanged' },
+ ],
+ },
+ }),
+ consentToSendSms: Property.StaticDropdown({
+ displayName: 'Consent to Send SMS',
+ description: 'Whether the subscriber has consented to send SMS.',
+ required: false,
+ defaultValue: 'Unchanged',
+ options: {
+ options: [
+ { label: 'Yes', value: 'Yes' },
+ { label: 'No', value: 'No' },
+ { label: 'Unchanged', value: 'Unchanged' },
+ ],
+ },
+ }),
+ resubscribe: Property.Checkbox({
+ displayName: 'Resubscribe',
+ description: 'Resubscribe the contact if they previously unsubscribed.',
+ required: false,
+ defaultValue: false,
+ }),
+ customFields: Property.Json({
+ displayName: 'Custom Fields',
+ description:
+ 'JSON object of field name to value, e.g. {"Company":"Acme"}.',
+ required: false,
+ }),
+ },
+ async run({ propsValue, auth }) {
+ const listId = propsValue.listId.trim();
+ const email = propsValue.email.trim();
+ const dateKeys = await fetchDateFieldKeys({
+ auth: { apiKey: auth.secret_text },
+ listId,
+ });
+ const targetEmail = propsValue.newEmail?.trim() || email;
+ await makeRequest({
+ auth: { apiKey: auth.secret_text },
+ method: HttpMethod.PUT,
+ path: `/subscribers/${encodeURIComponent(
+ listId
+ )}.json?email=${encodeURIComponent(email)}`,
+ body: {
+ EmailAddress: targetEmail,
+ Name: propsValue.name,
+ MobileNumber: propsValue.phone,
+ ConsentToTrack: propsValue.consentToTrack ?? 'Unchanged',
+ ConsentToSendSms: propsValue.consentToSendSms ?? 'Unchanged',
+ Resubscribe: propsValue.resubscribe ?? false,
+ CustomFields: buildCustomFieldsPayload({
+ fields: jsonCustomFieldsToRecord(propsValue.customFields),
+ dateKeys,
+ }),
+ },
+ });
+ return {
+ success: true,
+ emailAddress: targetEmail,
+ listId,
+ };
+ },
+});
diff --git a/packages/pieces/community/campaign-monitor/src/lib/auth.ts b/packages/pieces/community/campaign-monitor/src/lib/auth.ts
index 86d55ada533..198e3291a32 100644
--- a/packages/pieces/community/campaign-monitor/src/lib/auth.ts
+++ b/packages/pieces/community/campaign-monitor/src/lib/auth.ts
@@ -1,4 +1,6 @@
import { PieceAuth } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { makeRequest } from './common/client';
const markdownDescription = `
To use Campaign Monitor, you need to get an API key:
@@ -9,7 +11,23 @@ To use Campaign Monitor, you need to get an API key:
`;
export const campaignMonitorAuth = PieceAuth.SecretText({
- displayName: 'API Key',
- description: markdownDescription,
- required: true,
+ displayName: 'API Key',
+ description: markdownDescription,
+ required: true,
+ validate: async ({ auth }) => {
+ try {
+ await makeRequest({
+ auth: { apiKey: auth },
+ method: HttpMethod.GET,
+ path: '/systemdate.json',
+ });
+ return { valid: true };
+ } catch {
+ return {
+ valid: false,
+ error:
+ 'Invalid API key. Copy it from Account Settings → API keys in Campaign Monitor.',
+ };
+ }
+ },
});
diff --git a/packages/pieces/community/campaign-monitor/src/lib/common/client.ts b/packages/pieces/community/campaign-monitor/src/lib/common/client.ts
index 460e7d7af98..02a0b8fbeb1 100644
--- a/packages/pieces/community/campaign-monitor/src/lib/common/client.ts
+++ b/packages/pieces/community/campaign-monitor/src/lib/common/client.ts
@@ -6,17 +6,18 @@ import {
export const BASE_URL = 'https://api.createsend.com/api/v3.3';
-export interface CampaignMonitorAuth {
- apiKey: string;
-}
-
-export async function makeRequest(
- auth: CampaignMonitorAuth,
- method: HttpMethod,
- path: string,
- body?: unknown
-) {
- const response = await httpClient.sendRequest({
+export async function makeRequest<T>({
+ auth,
+ method,
+ path,
+ body,
+}: {
+ auth: CampaignMonitorAuth;
+ method: HttpMethod;
+ path: string;
+ body?: unknown;
+}) {
+ const response = await httpClient.sendRequest<T>({
method,
url: `${BASE_URL}${path}`,
headers: {
@@ -33,20 +34,211 @@ export async function makeRequest(
}
export function transformCustomFields(
- inputFields: Array<{ Key: string; Value: string }>
+ inputFields: Array<{ Key: string; Value: string }> | undefined
) {
- const fields: Record<string, any> = {};
-
- for (const { Key, Value } of inputFields) {
- if (fields[Key]) {
- if (Array.isArray(fields[Key])) {
- fields[Key].push(Value);
- } else {
- fields[Key] = [fields[Key], Value];
- }
+ const fields: Record<string, string | string[]> = {};
+
+ for (const { Key, Value } of inputFields ?? []) {
+ const key = Key.replace(/^\[(.*)\]$/, '$1');
+ const existing = fields[key];
+ if (existing === undefined) {
+ fields[key] = Value;
+ } else if (Array.isArray(existing)) {
+ existing.push(Value);
} else {
- fields[Key] = Value;
+ fields[key] = [existing, Value];
+ }
+ }
+ return fields;
+}
+
+export async function fetchDateFieldKeys({
+ auth,
+ listId,
+}: {
+ auth: CampaignMonitorAuth;
+ listId: string;
+}) {
+ const response = await makeRequest<
+ Array<{ Key: string; DataType: string }>
+ >({
+ auth,
+ method: HttpMethod.GET,
+ path: `/lists/${encodeURIComponent(listId)}/customfields.json`,
+ });
+ return new Set(
+ (response.body ?? [])
+ .filter((field) => field.DataType === 'Date')
+ .map((field) => field.Key)
+ );
+}
+
+export function buildCustomFieldsPayload({
+ fields,
+ dateKeys,
+}: {
+ fields: Record<string, unknown> | undefined;
+ dateKeys: Set<string>;
+}) {
+ return Object.entries(fields ?? {}).flatMap(([key, value]) => {
+ if (Array.isArray(value)) {
+ return value
+ .filter((v) => !isBlank(v))
+ .map((v) => ({ Key: key, Value: v }));
+ }
+ if (isBlank(value)) {
+ return [];
+ }
+ return [
+ {
+ Key: key,
+ Value: dateKeys.has(key) ? toDateFieldValue(value) : value,
+ },
+ ];
+ });
+}
+
+export function isSubscriberNotFoundError(error: unknown): boolean {
+ if (typeof error !== 'object' || error === null || !('response' in error)) {
+ return false;
+ }
+ const response = error.response;
+ if (typeof response !== 'object' || response === null) {
+ return false;
+ }
+ const status = 'status' in response ? response.status : undefined;
+ if (status === 404) {
+ return true;
+ }
+ const body = 'body' in response ? response.body : undefined;
+ return (
+ status === 400 &&
+ typeof body === 'object' &&
+ body !== null &&
+ 'Code' in body &&
+ Number(body.Code) === 203
+ );
+}
+
+export function getApiErrorCode(error: unknown) {
+ if (typeof error !== 'object' || error === null || !('response' in error)) {
+ return undefined;
+ }
+ const response = error.response;
+ if (
+ typeof response !== 'object' ||
+ response === null ||
+ !('body' in response)
+ ) {
+ return undefined;
+ }
+ const body = response.body;
+ if (typeof body !== 'object' || body === null || !('Code' in body)) {
+ return undefined;
+ }
+ return Number(body.Code);
+}
+
+export function clampPageSize(value: number | undefined) {
+ const size = Number(value ?? 100);
+ if (!Number.isFinite(size)) {
+ return 100;
+ }
+ return Math.min(1000, Math.max(10, Math.floor(size)));
+}
+
+export function clampPage(value: number | undefined) {
+ const page = Number(value ?? 1);
+ if (!Number.isFinite(page) || page < 1) {
+ return 1;
+ }
+ return Math.floor(page);
+}
+
+export async function fetchSubscriberOrEventData({
+ apiKey,
+ listId,
+ event,
+}: {
+ apiKey: string;
+ listId: string;
+ event: CampaignMonitorWebhookEvent;
+}) {
+ try {
+ const response = await makeRequest<
+ Record<string, unknown> & {
+ CustomFields?: Array<{ Key: string; Value: string }>;
+ }
+ >({
+ auth: { apiKey },
+ method: HttpMethod.GET,
+ path: `/subscribers/${listId}.json?email=${encodeURIComponent(
+ event.EmailAddress
+ )}&includetrackingpreference=true`,
+ });
+ return {
+ ...response.body,
+ State: event.State ?? response.body['State'],
+ CustomFields: transformCustomFields(response.body.CustomFields),
+ };
+ } catch (error) {
+ if (!isSubscriberNotFoundError(error)) {
+ throw error;
+ }
+ return {
+ EmailAddress: event.EmailAddress,
+ Name: event.Name ?? null,
+ Date: event.Date ?? null,
+ State: event.State ?? null,
+ CustomFields: transformCustomFields(event.CustomFields),
+ };
+ }
+}
+
+export function jsonCustomFieldsToRecord(value: unknown) {
+ if (value === undefined || value === null || value === '') {
+ return {};
+ }
+ const parsed: unknown = typeof value === 'string' ? JSON.parse(value) : value;
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
+ throw new Error(
+ 'Custom Fields must be a JSON object, e.g. {"Company":"Acme","Age":30}.'
+ );
+ }
+ const fields: Record<string, unknown> = {};
+ for (const [key, fieldValue] of Object.entries(parsed)) {
+ const name = key.replace(/^\s*\[(.*)\]\s*$/, '$1').replace(/\s+/g, '');
+ if (name.length === 0) {
+ continue;
}
+ fields[`[${name}]`] = fieldValue;
}
return fields;
}
+
+const ISO_DATE_TIME = /^(\d{4})-(\d{2})-(\d{2})T\d{2}:\d{2}/;
+
+function toDateFieldValue(value: unknown) {
+ if (typeof value !== 'string') {
+ return value;
+ }
+ const match = ISO_DATE_TIME.exec(value);
+ return match ? `${match[1]}/${match[2]}/${match[3]}` : value;
+}
+
+function isBlank(value: unknown) {
+ return value === undefined || value === null || value === '';
+}
+
+export interface CampaignMonitorAuth {
+ apiKey: string;
+}
+
+export interface CampaignMonitorWebhookEvent {
+ Type: string;
+ EmailAddress: string;
+ Name?: string;
+ Date?: string;
+ State?: string;
+ CustomFields?: Array<{ Key: string; Value: string }>;
+}
diff --git a/packages/pieces/community/campaign-monitor/src/lib/common/props.ts b/packages/pieces/community/campaign-monitor/src/lib/common/props.ts
index 57b8167320f..ccf448c8cb4 100644
--- a/packages/pieces/community/campaign-monitor/src/lib/common/props.ts
+++ b/packages/pieces/community/campaign-monitor/src/lib/common/props.ts
@@ -17,12 +17,12 @@ export const clientId = Property.Dropdown({
};
}
- const response = await makeRequest(
- { apiKey: auth.secret_text },
- HttpMethod.GET,
- '/clients.json'
- );
- const clients = response.body as { ClientID: string; Name: string }[];
+ const response = await makeRequest<{ ClientID: string; Name: string }[]>({
+ auth: { apiKey: auth.secret_text },
+ method: HttpMethod.GET,
+ path: '/clients.json',
+ });
+ const clients = response.body;
return {
disabled: false,
@@ -50,12 +50,12 @@ export const listId = Property.Dropdown({
};
}
- const response = await makeRequest(
- { apiKey: auth.secret_text },
- HttpMethod.GET,
- `/clients/${clientId}/lists.json`
- );
- const lists = response.body as { ListID: string; Name: string }[];
+ const response = await makeRequest<{ ListID: string; Name: string }[]>({
+ auth: { apiKey: auth.secret_text },
+ method: HttpMethod.GET,
+ path: `/clients/${clientId}/lists.json`,
+ });
+ const lists = response.body;
return {
disabled: false,
@@ -79,20 +79,22 @@ export const customFields = Property.DynamicProperties({
const fields: DynamicPropsValue = {};
- const response = await makeRequest(
- {
- apiKey: auth.secret_text,
+ const response = await makeRequest<
+ Array<{
+ FieldName: string;
+ Key: string;
+ DataType: string;
+ FieldOptions: string[];
+ }>
+ >({
+ auth: {
+ apiKey: auth.secret_text,
},
- HttpMethod.GET,
- `/lists/${listId}/customfields.json`
- );
+ method: HttpMethod.GET,
+ path: `/lists/${listId}/customfields.json`,
+ });
- const listFields = response.body as Array<{
- FieldName: string;
- Key: string;
- DataType: string;
- FieldOptions: string[];
- }>;
+ const listFields = response.body;
for (const field of listFields) {
switch (field.DataType) {
@@ -145,3 +147,174 @@ export const customFields = Property.DynamicProperties({
return fields;
},
});
+
+export const sentCampaignId = Property.Dropdown({
+ auth: campaignMonitorAuth,
+ displayName: 'Campaign',
+ description: 'A sent campaign of the selected client, newest first.',
+ refreshers: ['clientId'],
+ required: true,
+ options: async ({ auth, clientId }) => {
+ if (!auth || !clientId) {
+ return {
+ disabled: true,
+ placeholder: 'Please connect your account and select a client.',
+ options: [],
+ };
+ }
+ const options: { label: string; value: string }[] = [];
+ let page = 1;
+ let numberOfPages = 1;
+ do {
+ const response = await makeRequest<{
+ Results: { CampaignID: string; Name: string; SentDate: string }[];
+ NumberOfPages: number;
+ }>({
+ auth: { apiKey: auth.secret_text },
+ method: HttpMethod.GET,
+ path: `/clients/${clientId}/campaigns.json?page=${page}&pagesize=1000&orderdirection=desc`,
+ });
+ const body = response.body;
+ for (const campaign of body.Results ?? []) {
+ options.push({
+ label: `${campaign.Name} (${campaign.SentDate})`,
+ value: campaign.CampaignID,
+ });
+ }
+ numberOfPages = body.NumberOfPages ?? 1;
+ page++;
+ } while (page <= numberOfPages && page <= 10);
+
+ return {
+ disabled: false,
+ placeholder:
+ options.length === 0 ? 'No sent campaigns found.' : undefined,
+ options,
+ };
+ },
+});
+
+export const smartEmailId = Property.Dropdown({
+ auth: campaignMonitorAuth,
+ displayName: 'Smart Email',
+ description: 'An active smart transactional email of the selected client.',
+ refreshers: ['clientId'],
+ required: true,
+ options: async ({ auth, clientId }) => {
+ if (!auth || !clientId) {
+ return {
+ disabled: true,
+ placeholder: 'Please connect your account and select a client.',
+ options: [],
+ };
+ }
+ const response = await makeRequest<{ ID: string; Name: string }[]>({
+ auth: { apiKey: auth.secret_text },
+ method: HttpMethod.GET,
+ path: `/transactional/smartEmail?status=active&clientID=${encodeURIComponent(
+ String(clientId)
+ )}`,
+ });
+ const emails = response.body;
+ return {
+ disabled: false,
+ placeholder:
+ emails.length === 0 ? 'No active smart emails found.' : undefined,
+ options: emails.map((email) => ({ label: email.Name, value: email.ID })),
+ };
+ },
+});
+
+export const draftCampaignId = Property.Dropdown({
+ auth: campaignMonitorAuth,
+ displayName: 'Draft Campaign',
+ description: 'A draft campaign of the selected client.',
+ refreshers: ['clientId'],
+ required: true,
+ options: async ({ auth, clientId }) => {
+ if (!auth || !clientId) {
+ return {
+ disabled: true,
+ placeholder: 'Please connect your account and select a client.',
+ options: [],
+ };
+ }
+ const response = await makeRequest<
+ { CampaignID: string; Name: string; Subject: string }[]
+ >({
+ auth: { apiKey: auth.secret_text },
+ method: HttpMethod.GET,
+ path: `/clients/${clientId}/drafts.json`,
+ });
+ const drafts = response.body;
+ return {
+ disabled: false,
+ placeholder:
+ drafts.length === 0 ? 'No draft campaigns found.' : undefined,
+ options: drafts.map((draft) => ({
+ label: `${draft.Name} (${draft.Subject})`,
+ value: draft.CampaignID,
+ })),
+ };
+ },
+});
+
+export const listIds = Property.MultiSelectDropdown({
+ auth: campaignMonitorAuth,
+ displayName: 'Lists',
+ description: 'Lists the campaign is sent to.',
+ refreshers: ['clientId'],
+ required: false,
+ options: async ({ auth, clientId }) => {
+ if (!auth || !clientId) {
+ return {
+ disabled: true,
+ placeholder: 'Please connect your account and select a client.',
+ options: [],
+ };
+ }
+ const response = await makeRequest<{ ListID: string; Name: string }[]>({
+ auth: { apiKey: auth.secret_text },
+ method: HttpMethod.GET,
+ path: `/clients/${clientId}/lists.json`,
+ });
+ return {
+ disabled: false,
+ options: response.body.map((list) => ({
+ label: list.Name,
+ value: list.ListID,
+ })),
+ };
+ },
+});
+
+export const segmentIds = Property.MultiSelectDropdown({
+ auth: campaignMonitorAuth,
+ displayName: 'Segments',
+ description: 'Segments the campaign is sent to.',
+ refreshers: ['clientId'],
+ required: false,
+ options: async ({ auth, clientId }) => {
+ if (!auth || !clientId) {
+ return {
+ disabled: true,
+ placeholder: 'Please connect your account and select a client.',
+ options: [],
+ };
+ }
+ const response = await makeRequest<{ SegmentID: string; Title: string }[]>({
+ auth: { apiKey: auth.secret_text },
+ method: HttpMethod.GET,
+ path: `/clients/${clientId}/segments.json`,
+ });
+ return {
+ disabled: false,
+ placeholder:
+ response.body.length === 0 ? 'No segments found.' : undefined,
+ options: response.body.map((segment) => ({
+ label: segment.Title,
+ value: segment.SegmentID,
+ })),
+ };
+ },
+});
diff --git a/packages/pieces/community/campaign-monitor/src/lib/output-schemas.ts b/packages/pieces/community/campaign-monitor/src/lib/output-schemas.ts
new file mode 100644
index 00000000000..8afd03c081d
--- /dev/null
+++ b/packages/pieces/community/campaign-monitor/src/lib/output-schemas.ts
@@ -0,0 +1,337 @@
+import {
+ OutputSchema,
+ OutputSchemaField,
+} from '@activepieces/pieces-framework';
+
+export const subscriberFields: OutputSchemaField[] = [
+ { key: 'EmailAddress', label: 'Email Address', format: 'email' },
+ { key: 'Name', label: 'Name' },
+ { key: 'Date', label: 'Date', format: 'datetime' },
+ { key: 'ListJoinedDate', label: 'List Joined Date', format: 'datetime' },
+ { key: 'State', label: 'State' },
+ { key: 'CustomFields', label: 'Custom Fields' },
+ { key: 'ReadsEmailWith', label: 'Reads Email With' },
+ { key: 'ConsentToTrack', label: 'Consent to Track' },
+ { key: 'ConsentToSendSms', label: 'Consent to Send SMS' },
+ { key: 'MobileNumber', label: 'Mobile Number' },
+];
+
+export const paginationFields: OutputSchemaField[] = [
+ { key: 'PageNumber', label: 'Page Number', format: 'number' },
+ { key: 'PageSize', label: 'Page Size', format: 'number' },
+ { key: 'RecordsOnThisPage', label: 'Records on This Page', format: 'number' },
+ {
+ key: 'TotalNumberOfRecords',
+ label: 'Total Number of Records',
+ format: 'number',
+ },
+ { key: 'NumberOfPages', label: 'Number of Pages', format: 'number' },
+];
+
+export const subscriptionResultFields: OutputSchemaField[] = [
+ { key: 'success', label: 'Success', format: 'boolean' },
+ { key: 'emailAddress', label: 'Email Address', format: 'email' },
+ { key: 'listId', label: 'List ID' },
+];
+
+export const subscriptionResultOutputSchema: OutputSchema = {
+ fields: subscriptionResultFields,
+};
+
+export const findSubscriberOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'found', label: 'Found', format: 'boolean' },
+ { key: 'result', label: 'Subscriber', children: subscriberFields },
+ ],
+};
+
+export const subscriberOutputSchema: OutputSchema = {
+ fields: subscriberFields,
+};
+
+export const clientOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'ClientID', label: 'Client ID' },
+ { key: 'Name', label: 'Name' },
+ ],
+};
+
+export const listClientsOutputSchema: OutputSchema = {
+ itemLabel: '{Name}',
+ fields: [
+ {
+ key: 'clients',
+ label: 'Clients',
+ value: '',
+ labelKey: 'Name',
+ listItems: [
+ { key: 'ClientID', label: 'Client ID' },
+ { key: 'Name', label: 'Name' },
+ ],
+ },
+ ],
+};
+
+export const listSmartEmailsOutputSchema: OutputSchema = {
+ itemLabel: '{Name}',
+ fields: [
+ {
+ key: 'smartEmails',
+ label: 'Smart Emails',
+ value: '',
+ labelKey: 'Name',
+ listItems: [
+ { key: 'ID', label: 'Smart Email ID' },
+ { key: 'Name', label: 'Name' },
+ { key: 'Status', label: 'Status' },
+ { key: 'CreatedAt', label: 'Created At' },
+ ],
+ },
+ ],
+};
+
+export const listListsOutputSchema: OutputSchema = {
+ itemLabel: '{Name}',
+ fields: [
+ {
+ key: 'lists',
+ label: 'Lists',
+ value: '',
+ labelKey: 'Name',
+ listItems: [
+ { key: 'ListID', label: 'List ID' },
+ { key: 'Name', label: 'Name' },
+ ],
+ },
+ ],
+};
+
+export const listSubscribersOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'Results',
+ label: 'Subscribers',
+ labelKey: 'EmailAddress',
+ listItems: subscriberFields,
+ },
+ ...paginationFields,
+ ],
+};
+
+export const createListOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'listId', label: 'List ID' },
+ { key: 'title', label: 'Title' },
+ ],
+};
+
+export const sentCampaignFields: OutputSchemaField[] = [
+ { key: 'CampaignID', label: 'Campaign ID' },
+ { key: 'Name', label: 'Name' },
+ { key: 'Subject', label: 'Subject' },
+ { key: 'FromName', label: 'From Name' },
+ { key: 'FromEmail', label: 'From Email', format: 'email' },
+ { key: 'ReplyTo', label: 'Reply To', format: 'email' },
+ { key: 'SentDate', label: 'Sent Date', format: 'datetime' },
+ { key: 'TotalRecipients', label: 'Total Recipients', format: 'number' },
+ { key: 'WebVersionURL', label: 'Web Version URL', format: 'url' },
+ { key: 'WebVersionTextURL', label: 'Web Version Text URL', format: 'url' },
+ { key: 'Tags', label: 'Tags' },
+];
+
+export const sentCampaignOutputSchema: OutputSchema = {
+ fields: sentCampaignFields,
+};
+
+export const listCampaignsOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'Results',
+ label: 'Campaigns',
+ labelKey: 'Name',
+ listItems: sentCampaignFields,
+ },
+ { key: 'ResultsOrderedBy', label: 'Results Ordered By' },
+ { key: 'OrderDirection', label: 'Order Direction' },
+ ...paginationFields,
+ ],
+};
+
+export const campaignSummaryOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'Name', label: 'Name' },
+ { key: 'Recipients', label: 'Recipients', format: 'number' },
+ { key: 'TotalOpened', label: 'Total Opened', format: 'number' },
+ { key: 'UniqueOpened', label: 'Unique Opened', format: 'number' },
+ { key: 'Clicks', label: 'Clicks', format: 'number' },
+ { key: 'Unsubscribed', label: 'Unsubscribed', format: 'number' },
+ { key: 'Bounced', label: 'Bounced', format: 'number' },
+ { key: 'SpamComplaints', label: 'Spam Complaints', format: 'number' },
+ { key: 'Forwards', label: 'Forwards', format: 'number' },
+ { key: 'Likes', label: 'Likes', format: 'number' },
+ { key: 'Mentions', label: 'Mentions', format: 'number' },
+ { key: 'WebVersionURL', label: 'Web Version URL', format: 'url' },
+ { key: 'WebVersionTextURL', label: 'Web Version Text URL', format: 'url' },
+ { key: 'WorldviewURL', label: 'Worldview URL', format: 'url' },
+ ],
+};
+
+export const sendSmartEmailOutputSchema: OutputSchema = {
+ itemLabel: '{Recipient}',
+ fields: [
+ {
+ key: 'messages',
+ label: 'Messages',
+ value: '',
+ labelKey: 'Recipient',
+ listItems: [
+ { key: 'MessageID', label: 'Message ID' },
+ { key: 'Recipient', label: 'Recipient' },
+ { key: 'Status', label: 'Status' },
+ ],
+ },
+ ],
+};
+
+export const createDraftCampaignOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'campaignId', label: 'Campaign ID' },
+ { key: 'name', label: 'Name' },
+ ],
+};
+
+export const sendCampaignOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'success', label: 'Success', format: 'boolean' },
+ { key: 'campaignId', label: 'Campaign ID' },
+ { key: 'sendDate', label: 'Send Date' },
+ ],
+};
+
+export const deleteDraftCampaignOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'success', label: 'Success', format: 'boolean' },
+ { key: 'campaignId', label: 'Campaign ID' },
+ ],
+};
+
+export const campaignActivityOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'Results',
+ label: 'Activity',
+ labelKey: 'EmailAddress',
+ listItems: [
+ { key: 'EmailAddress', label: 'Email Address', format: 'email' },
+ { key: 'ListID', label: 'List ID' },
+ { key: 'Date', label: 'Date', format: 'datetime' },
+ { key: 'IPAddress', label: 'IP Address' },
+ { key: 'URL', label: 'Clicked URL', format: 'url' },
+ { key: 'BounceType', label: 'Bounce Type' },
+ { key: 'Reason', label: 'Bounce Reason' },
+ { key: 'Latitude', label: 'Latitude', format: 'number' },
+ { key: 'Longitude', label: 'Longitude', format: 'number' },
+ { key: 'City', label: 'City' },
+ { key: 'Region', label: 'Region' },
+ { key: 'CountryCode', label: 'Country Code' },
+ { key: 'CountryName', label: 'Country Name' },
+ ],
+ },
+ { key: 'ResultsOrderedBy', label: 'Results Ordered By' },
+ { key: 'OrderDirection', label: 'Order Direction' },
+ ...paginationFields,
+ ],
+};
+
+export const listStatsOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'TotalActiveSubscribers',
+ label: 'Total Active Subscribers',
+ format: 'number',
+ },
+ {
+ key: 'NewActiveSubscribersToday',
+ label: 'New Active Subscribers Today',
+ format: 'number',
+ },
+ {
+ key: 'NewActiveSubscribersYesterday',
+ label: 'New Active Subscribers Yesterday',
+ format: 'number',
+ },
+ {
+ key: 'NewActiveSubscribersThisWeek',
+ label: 'New Active Subscribers This Week',
+ format: 'number',
+ },
+ {
+ key: 'NewActiveSubscribersThisMonth',
+ label: 'New Active Subscribers This Month',
+ format: 'number',
+ },
+ {
+ key: 'NewActiveSubscribersThisYear',
+ label: 'New Active Subscribers This Year',
+ format: 'number',
+ },
+ { key: 'TotalUnsubscribes', label: 'Total Unsubscribes', format: 'number' },
+ { key: 'UnsubscribesToday', label: 'Unsubscribes Today', format: 'number' },
+ {
+ key: 'UnsubscribesYesterday',
+ label: 'Unsubscribes Yesterday',
+ format: 'number',
+ },
+ {
+ key: 'UnsubscribesThisWeek',
+ label: 'Unsubscribes This Week',
+ format: 'number',
+ },
+ {
+ key: 'UnsubscribesThisMonth',
+ label: 'Unsubscribes This Month',
+ format: 'number',
+ },
+ {
+ key: 'UnsubscribesThisYear',
+ label: 'Unsubscribes This Year',
+ format: 'number',
+ },
+ { key: 'TotalDeleted', label: 'Total Deleted', format: 'number' },
+ { key: 'DeletedToday', label: 'Deleted Today', format: 'number' },
+ { key: 'DeletedYesterday', label: 'Deleted Yesterday', format: 'number' },
+ { key: 'DeletedThisWeek', label: 'Deleted This Week', format: 'number' },
+ { key: 'DeletedThisMonth', label: 'Deleted This Month', format: 'number' },
+ { key: 'DeletedThisYear', label: 'Deleted This Year', format: 'number' },
+ { key: 'TotalBounces', label: 'Total Bounces', format: 'number' },
+ { key: 'BouncesToday', label: 'Bounces Today', format: 'number' },
+ { key: 'BouncesYesterday', label: 'Bounces Yesterday', format: 'number' },
+ { key: 'BouncesThisWeek', label: 'Bounces This Week', format: 'number' },
+ { key: 'BouncesThisMonth', label: 'Bounces This Month', format: 'number' },
+ { key: 'BouncesThisYear', label: 'Bounces This Year', format: 'number' },
+ ],
+};
+
+export const suppressEmailsOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'success', label: 'Success', format: 'boolean' },
+ { key: 'emailAddresses', label: 'Email Addresses' },
+ ],
+};
+
+export const unsuppressEmailOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'success', label: 'Success', format: 'boolean' },
+ { key: 'emailAddress', label: 'Email Address', format: 'email' },
+ { key: 'wasSuppressed', label: 'Was Suppressed', format: 'boolean' },
+ ],
+};
+
+export const createCustomFieldOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'key', label: 'Field Key' },
+ { key: 'fieldName', label: 'Field Name' },
+ { key: 'dataType', label: 'Data Type' },
+ { key: 'listId', label: 'List ID' },
+ ],
+};
diff --git a/packages/pieces/community/campaign-monitor/src/lib/triggers/new-campaign-sent.ts b/packages/pieces/community/campaign-monitor/src/lib/triggers/new-campaign-sent.ts
new file mode 100644
index 00000000000..bb3d1766309
--- /dev/null
+++ b/packages/pieces/community/campaign-monitor/src/lib/triggers/new-campaign-sent.ts
@@ -0,0 +1,124 @@
+import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { makeRequest } from '../common/client';
+import { campaignMonitorAuth } from '../auth';
+import { clientId } from '../common/props';
+import { sentCampaignOutputSchema } from '../output-schemas';
+
+export const newCampaignSentTrigger = createTrigger({
+ auth: campaignMonitorAuth,
+ name: 'new_campaign_sent',
+ classification: 'READ',
+ displayName: 'New Campaign Sent',
+ description: 'Triggers when a client sends a new campaign.',
+ aiMetadata: {
+ description:
+ 'Fires once for each campaign that a Campaign Monitor client sends, detected by polling the client sent campaigns (newest first) for campaign IDs not seen before, and returns the campaign name, subject, sender, sent date, recipient count and web version links.',
+ },
+ props: {
+ clientId: clientId,
+ },
+ type: TriggerStrategy.POLLING,
+ outputSchema: sentCampaignOutputSchema,
+ sampleData: {
+ CampaignID: 'a4ba8e44cd0d82e5a9a703affc2572c2',
+ Name: 'October Newsletter',
+ Subject: 'Our October news',
+ FromName: 'Acme',
+ FromEmail: '[email protected]',
+ ReplyTo: '[email protected]',
+ SentDate: '2026-10-20 09:30:00',
+ TotalRecipients: 1250,
+ WebVersionURL: 'https://example.createsend1.com/t/ViewEmail/r/ABC/',
+ WebVersionTextURL: 'https://example.createsend1.com/t/ViewEmail/r/ABC/t',
+ Tags: [],
+ },
+ async onEnable(context) {
+ if (context.isRepublish && (await context.store.get(STORE_KEY))) {
+ return;
+ }
+ const campaigns = await fetchRecentCampaigns({
+ apiKey: context.auth.secret_text,
+ clientId: context.propsValue.clientId,
+ seen: new Set<string>(),
+ maxPages: 1,
+ });
+ await context.store.put<string[]>(
+ STORE_KEY,
+ campaigns.map((campaign) => campaign.CampaignID)
+ );
+ },
+ async onDisable() {
+ return;
+ },
+ async test(context) {
+ const campaigns = await fetchRecentCampaigns({
+ apiKey: context.auth.secret_text,
+ clientId: context.propsValue.clientId,
+ seen: new Set<string>(),
+ maxPages: 1,
+ });
+ return campaigns.slice(0, 5);
+ },
+ async run(context) {
+ const stored = (await context.store.get<string[]>(STORE_KEY)) ?? [];
+ const seen = new Set(stored);
+ const campaigns = await fetchRecentCampaigns({
+ apiKey: context.auth.secret_text,
+ clientId: context.propsValue.clientId,
+ seen,
+ });
+ const newCampaigns = campaigns.filter(
+ (campaign) => !seen.has(campaign.CampaignID)
+ );
+ const updated = [
+ ...newCampaigns.map((campaign) => campaign.CampaignID),
+ ...stored,
+ ].slice(0, MAX_STORED_IDS);
+ await context.store.put<string[]>(STORE_KEY, updated);
+ return newCampaigns.reverse();
+ },
+});
+
+const STORE_KEY = 'seen_sent_campaigns';
+const PAGE_SIZE = 100;
+const MAX_STORED_IDS = 1000;
+
+async function fetchRecentCampaigns({
+ apiKey,
+ clientId,
+ seen,
+ maxPages,
+}: {
+ apiKey: string;
+ clientId: string;
+ seen: Set<string>;
+ maxPages?: number;
+}) {
+ const campaigns: SentCampaign[] = [];
+ for (let page = 1; maxPages === undefined || page <= maxPages; page++) {
+ const response = await makeRequest<{
+ Results?: SentCampaign[];
+ NumberOfPages?: number;
+ }>({
+ auth: { apiKey },
+ method: HttpMethod.GET,
+ path: `/clients/${clientId}/campaigns.json?page=${page}&pagesize=${PAGE_SIZE}&orderdirection=desc`,
+ });
+ const results = response.body.Results ?? [];
+ campaigns.push(...results);
+ const reachedSeen = results.some((campaign) =>
+ seen.has(campaign.CampaignID)
+ );
+ if (reachedSeen || page >= (response.body.NumberOfPages ?? 1)) {
+ break;
+ }
+ }
+ return campaigns;
+}
+
+type SentCampaign = {
+ CampaignID: string;
+ Name: string;
+ SentDate: string;
+};
diff --git a/packages/pieces/community/campaign-monitor/src/lib/triggers/new-client.ts b/packages/pieces/community/campaign-monitor/src/lib/triggers/new-client.ts
index 14561af2897..9413ffe74c2 100644
--- a/packages/pieces/community/campaign-monitor/src/lib/triggers/new-client.ts
+++ b/packages/pieces/community/campaign-monitor/src/lib/triggers/new-client.ts
@@ -2,6 +2,7 @@ import { createTrigger, isNil, TriggerStrategy } from '@activepieces/pieces-fram
import { HttpMethod } from '@activepieces/pieces-common';
import { makeRequest } from '../common/client';
import { campaignMonitorAuth } from '../auth';
+import { clientOutputSchema } from '../output-schemas';
export const newClientTrigger = createTrigger({
auth: campaignMonitorAuth,
@@ -15,22 +16,27 @@ export const newClientTrigger = createTrigger({
},
props: {},
type: TriggerStrategy.POLLING,
+ outputSchema: clientOutputSchema,
sampleData: {
ClientID: 'xyz',
Name: 'New Client',
},
async onEnable(context) {
- if (context.isRepublish && !isNil(await context.store.get('existing_clients'))) {
+ if (
+ context.isRepublish &&
+ !isNil(await context.store.get('existing_clients'))
+ ) {
return;
}
- // Store the list of existing clients
- const response = await makeRequest(
- { apiKey: context.auth.secret_text },
- HttpMethod.GET,
- '/clients.json'
- );
+ const response = await makeRequest<
+ Array<{ ClientID: string; Name: string }>
+ >({
+ auth: { apiKey: context.auth.secret_text },
+ method: HttpMethod.GET,
+ path: '/clients.json',
+ });
- const clients = response.body as Array<{ ClientID: string; Name: string }>;
+ const clients = response.body;
await context.store.put('existing_clients', {
clients: clients.map((c) => c.ClientID),
@@ -40,51 +46,45 @@ export const newClientTrigger = createTrigger({
if (context.isRepublish) {
return;
}
- // No cleanup needed for polling trigger
await context.store.delete('existing_clients');
},
async test(context) {
- const response = await makeRequest(
- { apiKey: context.auth.secret_text },
- HttpMethod.GET,
- '/clients.json'
- );
+ const response = await makeRequest<
+ Array<{ ClientID: string; Name: string }>
+ >({
+ auth: { apiKey: context.auth.secret_text },
+ method: HttpMethod.GET,
+ path: '/clients.json',
+ });
return response.body;
},
async run(context) {
- // Get stored list of clients
const storedClients = await context.store.get<{ clients: string[] }>(
'existing_clients'
);
const existingClientIds = storedClients?.clients || [];
+ const response = await makeRequest<
+ Array<{
+ ClientID: string;
+ Name: string;
+ }>
+ >({
+ auth: { apiKey: context.auth.secret_text },
+ method: HttpMethod.GET,
+ path: '/clients.json',
+ });
- // Get all clients
- const response = await makeRequest(
- { apiKey: context.auth.secret_text },
- HttpMethod.GET,
- '/clients.json'
- );
-
- const allClients = response.body as Array<{
- ClientID: string;
- Name: string;
- }>;
-
- // Find new clients
+ const allClients = response.body;
const newClients = allClients.filter(
(client) => !existingClientIds.includes(client.ClientID)
);
-
- // Update stored client list
const updatedClientIds = Array.from(
new Set([...existingClientIds, ...allClients.map((c) => c.ClientID)])
);
await context.store.put('existing_clients', {
clients: updatedClientIds,
});
-
- // Return new clients
return newClients;
},
});
diff --git a/packages/pieces/community/campaign-monitor/src/lib/triggers/new-subscriber-added.ts b/packages/pieces/community/campaign-monitor/src/lib/triggers/new-subscriber-added.ts
index 6c6a1556bb5..2c49b1fe21a 100644
--- a/packages/pieces/community/campaign-monitor/src/lib/triggers/new-subscriber-added.ts
+++ b/packages/pieces/community/campaign-monitor/src/lib/triggers/new-subscriber-added.ts
@@ -1,9 +1,14 @@
import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';
import { HttpMethod } from '@activepieces/pieces-common';
-import { makeRequest, transformCustomFields } from '../common/client';
+import {
+ CampaignMonitorWebhookEvent,
+ fetchSubscriberOrEventData,
+ makeRequest,
+} from '../common/client';
import { isNil } from '@activepieces/pieces-framework';
import { campaignMonitorAuth } from '../auth';
import { clientId, listId } from '../common/props';
+import { subscriberOutputSchema } from '../output-schemas';
export const newSubscriberAddedTrigger = createTrigger({
auth: campaignMonitorAuth,
@@ -20,32 +25,36 @@ export const newSubscriberAddedTrigger = createTrigger({
listId: listId,
},
type: TriggerStrategy.WEBHOOK,
+ outputSchema: subscriberOutputSchema,
sampleData: {
EmailAddress: '[email protected]',
Name: 'New Subscriber',
- Date: '2023-07-15T15:30:00Z',
- ListID: 'xyz',
+ Date: '2023-07-15 15:30:00',
+ ListJoinedDate: '2023-07-15 15:30:00',
+ State: 'Active',
CustomFields: {
website: 'https://example.com',
},
- State: 'Active',
+ ReadsEmailWith: '',
ConsentToTrack: 'Yes',
+ ConsentToSendSms: 'Unchanged',
+ MobileNumber: '',
},
async onEnable(context) {
const { listId } = context.propsValue;
- const response = await makeRequest(
- { apiKey: context.auth.secret_text },
- HttpMethod.POST,
- `/lists/${listId}/webhooks.json`,
- {
+ const response = await makeRequest<string>({
+ auth: { apiKey: context.auth.secret_text },
+ method: HttpMethod.POST,
+ path: `/lists/${listId}/webhooks.json`,
+ body: {
Events: ['Subscribe'],
Url: context.webhookUrl,
PayloadFormat: 'json',
- }
- );
+ },
+ });
- const webhook = response.body as string;
+ const webhook = response.body;
await context.store.put('new_subscriber_added_webhook', webhook);
},
@@ -55,19 +64,18 @@ export const newSubscriberAddedTrigger = createTrigger({
'new_subscriber_added_webhook'
);
-
if (!isNil(storedData)) {
- await makeRequest(
- { apiKey: context.auth.secret_text },
- HttpMethod.DELETE,
- `/lists/${listId}/webhooks/${storedData}.json`
- );
+ await makeRequest({
+ auth: { apiKey: context.auth.secret_text },
+ method: HttpMethod.DELETE,
+ path: `/lists/${listId}/webhooks/${storedData}.json`,
+ });
}
},
async run(context) {
const payload = context.payload.body as {
ListID: string;
- Events: { Type: string; EmailAddress: string }[];
+ Events: CampaignMonitorWebhookEvent[];
};
if (payload.ListID !== context.propsValue.listId) {
@@ -78,18 +86,13 @@ export const newSubscriberAddedTrigger = createTrigger({
for (const event of payload.Events) {
if (event.Type === 'Subscribe') {
- const response = await makeRequest(
- { apiKey: context.auth.secret_text },
- HttpMethod.GET,
- `/subscribers/${context.propsValue.listId}.json?email=${encodeURIComponent(
- event.EmailAddress
- )}`,
- payload
+ result.push(
+ await fetchSubscriberOrEventData({
+ apiKey: context.auth.secret_text,
+ listId: context.propsValue.listId,
+ event,
+ })
);
- result.push({
- ...response.body,
- CustomFields: transformCustomFields(response.body['CustomFields']),
- });
}
}
diff --git a/packages/pieces/community/campaign-monitor/src/lib/triggers/subscriber-unsubscribed.ts b/packages/pieces/community/campaign-monitor/src/lib/triggers/subscriber-unsubscribed.ts
index 0ef09e15b73..b61a3c2a896 100644
--- a/packages/pieces/community/campaign-monitor/src/lib/triggers/subscriber-unsubscribed.ts
+++ b/packages/pieces/community/campaign-monitor/src/lib/triggers/subscriber-unsubscribed.ts
@@ -1,13 +1,14 @@
-import {
- createTrigger,
- Property,
- TriggerStrategy,
-} from '@activepieces/pieces-framework';
+import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';
import { HttpMethod } from '@activepieces/pieces-common';
-import { makeRequest, transformCustomFields } from '../common/client';
+import {
+ CampaignMonitorWebhookEvent,
+ fetchSubscriberOrEventData,
+ makeRequest,
+} from '../common/client';
import { isNil } from '@activepieces/pieces-framework';
import { campaignMonitorAuth } from '../auth';
import { clientId, listId } from '../common/props';
+import { subscriberOutputSchema } from '../output-schemas';
export const subscriberUnsubscribedTrigger = createTrigger({
auth: campaignMonitorAuth,
@@ -24,48 +25,56 @@ export const subscriberUnsubscribedTrigger = createTrigger({
listId: listId,
},
type: TriggerStrategy.WEBHOOK,
+ outputSchema: subscriberOutputSchema,
sampleData: {
EmailAddress: '[email protected]',
Name: 'Former Subscriber',
- Date: '2023-07-15T15:30:00Z',
- ListID: 'xyz',
+ Date: '2023-07-15 15:30:00',
+ ListJoinedDate: '2023-07-01 10:00:00',
State: 'Unsubscribed',
+ CustomFields: {
+ website: 'https://example.com',
+ },
+ ReadsEmailWith: 'Gmail',
+ ConsentToTrack: 'Yes',
+ ConsentToSendSms: 'Unchanged',
+ MobileNumber: '',
},
async onEnable(context) {
const { listId } = context.propsValue;
- const response = await makeRequest(
- { apiKey: context.auth.secret_text },
- HttpMethod.POST,
- `/lists/${listId}/webhooks.json`,
- {
+ const response = await makeRequest<string>({
+ auth: { apiKey: context.auth.secret_text },
+ method: HttpMethod.POST,
+ path: `/lists/${listId}/webhooks.json`,
+ body: {
Events: ['Deactivate'],
Url: context.webhookUrl,
- ListID: listId,
PayloadFormat: 'json',
- }
- );
- const webhook = response.body as string;
+ },
+ });
+ const webhook = response.body;
await context.store.put('subscriber_unsubscribed_webhook', webhook);
},
async onDisable(context) {
+ const { listId } = context.propsValue;
const storedData = await context.store.get<string>(
'subscriber_unsubscribed_webhook'
);
if (!isNil(storedData)) {
- await makeRequest(
- { apiKey: context.auth.secret_text },
- HttpMethod.DELETE,
- `/lists/${listId}/webhooks/${storedData}.json`
- );
+ await makeRequest({
+ auth: { apiKey: context.auth.secret_text },
+ method: HttpMethod.DELETE,
+ path: `/lists/${listId}/webhooks/${storedData}.json`,
+ });
}
},
async run(context) {
const payload = context.payload.body as {
ListID: string;
- Events: { Type: string; EmailAddress: string,State:string }[];
+ Events: CampaignMonitorWebhookEvent[];
};
if (payload.ListID !== context.propsValue.listId) {
@@ -75,19 +84,14 @@ export const subscriberUnsubscribedTrigger = createTrigger({
const result = [];
for (const event of payload.Events) {
- if (event.Type === 'Deactivate' && event.State==='Unsubscribed') {
- const response = await makeRequest(
- { apiKey: context.auth.secret_text },
- HttpMethod.GET,
- `/subscribers/${context.propsValue.listId}.json?email=${encodeURIComponent(
- event.EmailAddress
- )}`,
- payload
+ if (event.Type === 'Deactivate' && event.State === 'Unsubscribed') {
+ result.push(
+ await fetchSubscriberOrEventData({
+ apiKey: context.auth.secret_text,
+ listId: context.propsValue.listId,
+ event,
+ })
);
- result.push({
- ...response.body,
- CustomFields: transformCustomFields(response.body['CustomFields']),
- });
}
}
diff --git a/packages/pieces/community/campaign-monitor/test/campaign-monitor.test.ts b/packages/pieces/community/campaign-monitor/test/campaign-monitor.test.ts
new file mode 100644
index 00000000000..8bb00ae3e9a
--- /dev/null
+++ b/packages/pieces/community/campaign-monitor/test/campaign-monitor.test.ts
@@ -0,0 +1,185 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { httpClient } from '@activepieces/pieces-common';
+import {
+ buildCustomFieldsPayload,
+ isSubscriberNotFoundError,
+ jsonCustomFieldsToRecord,
+} from '../src/lib/common/client';
+import { newCampaignSentTrigger } from '../src/lib/triggers/new-campaign-sent';
+
+const STORE_KEY = 'seen_sent_campaigns';
+
+describe('buildCustomFieldsPayload', () => {
+ it('drops blanks, expands arrays and formats date fields', () => {
+ const payload = buildCustomFieldsPayload({
+ fields: {
+ '[Company]': 'Acme',
+ '[Empty]': '',
+ '[Missing]': null,
+ '[Tags]': ['a', '', 'b'],
+ '[Birthday]': '2026-10-20T09:30:00Z',
+ '[Note]': '2026-10-20T09:30:00Z',
+ '[Age]': 30,
+ },
+ dateKeys: new Set(['[Birthday]']),
+ });
+ expect(payload).toEqual([
+ { Key: '[Company]', Value: 'Acme' },
+ { Key: '[Tags]', Value: 'a' },
+ { Key: '[Tags]', Value: 'b' },
+ { Key: '[Birthday]', Value: '2026/10/20' },
+ { Key: '[Note]', Value: '2026-10-20T09:30:00Z' },
+ { Key: '[Age]', Value: 30 },
+ ]);
+ });
+
+ it('returns an empty list for undefined fields', () => {
+ expect(buildCustomFieldsPayload({ fields: undefined, dateKeys: new Set() })).toEqual([]);
+ });
+});
+
+describe('jsonCustomFieldsToRecord', () => {
+ it('returns an empty record for empty input', () => {
+ expect(jsonCustomFieldsToRecord(undefined)).toEqual({});
+ expect(jsonCustomFieldsToRecord(null)).toEqual({});
+ expect(jsonCustomFieldsToRecord('')).toEqual({});
+ });
+
+ it('parses a JSON string and normalises keys to the bracket form', () => {
+ expect(
+ jsonCustomFieldsToRecord('{"Company":"Acme","[Age]":30," Favourite Colour ":"red","":1}')
+ ).toEqual({ '[Company]': 'Acme', '[Age]': 30, '[FavouriteColour]': 'red' });
+ });
+
+ it('accepts an object directly', () => {
+ expect(jsonCustomFieldsToRecord({ Company: 'Acme' })).toEqual({ '[Company]': 'Acme' });
+ });
+
+ it('rejects arrays and scalars', () => {
+ expect(() => jsonCustomFieldsToRecord('[1,2]')).toThrow('Custom Fields must be a JSON object');
+ expect(() => jsonCustomFieldsToRecord('5')).toThrow('Custom Fields must be a JSON object');
+ });
+});
+
+describe('isSubscriberNotFoundError', () => {
+ it('matches 404 and the 400 code 203 response', () => {
+ expect(isSubscriberNotFoundError({ response: { status: 404, body: {} } })).toBe(true);
+ expect(isSubscriberNotFoundError({ response: { status: 400, body: { Code: 203 } } })).toBe(true);
+ expect(isSubscriberNotFoundError({ response: { status: 400, body: { Code: '203' } } })).toBe(true);
+ });
+
+ it('does not match real failures', () => {
+ expect(isSubscriberNotFoundError({ response: { status: 401, body: { Code: 50 } } })).toBe(false);
+ expect(isSubscriberNotFoundError({ response: { status: 400, body: { Code: 1 } } })).toBe(false);
+ expect(isSubscriberNotFoundError({ response: { status: 500 } })).toBe(false);
+ expect(isSubscriberNotFoundError(new Error('network down'))).toBe(false);
+ expect(isSubscriberNotFoundError(null)).toBe(false);
+ expect(isSubscriberNotFoundError({ response: null })).toBe(false);
+ });
+});
+
+describe('New Campaign Sent trigger', () => {
+ let campaigns: Array<{ CampaignID: string; Name: string; SentDate: string }>;
+ let requestedPages: number[];
+
+ beforeEach(() => {
+ campaigns = makeCampaigns({ from: 1, to: 3 });
+ requestedPages = [];
+ vi.spyOn(httpClient, 'sendRequest').mockImplementation(async ({ url }) => {
+ const page = Number(new URL(url).searchParams.get('page'));
+ const pageSize = Number(new URL(url).searchParams.get('pagesize'));
+ requestedPages.push(page);
+ const newestFirst = [...campaigns].reverse();
+ return {
+ status: 200,
+ headers: {},
+ body: {
+ Results: newestFirst.slice((page - 1) * pageSize, page * pageSize),
+ NumberOfPages: Math.max(1, Math.ceil(newestFirst.length / pageSize)),
+ },
+ };
+ });
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('emits nothing for campaigns that existed when the flow was enabled', async () => {
+ const context = createContext();
+ await newCampaignSentTrigger.onEnable(context);
+ expect(await newCampaignSentTrigger.run(context)).toEqual([]);
+ });
+
+ it('emits each new campaign once, oldest first', async () => {
+ const context = createContext();
+ await newCampaignSentTrigger.onEnable(context);
+ campaigns.push(...makeCampaigns({ from: 4, to: 5 }));
+
+ const first = await newCampaignSentTrigger.run(context);
+ const second = await newCampaignSentTrigger.run(context);
+
+ expect(first.map((campaign) => campaign.CampaignID)).toEqual(['c4', 'c5']);
+ expect(second).toEqual([]);
+ });
+
+ it('reads past the first page until it reaches a seen campaign', async () => {
+ const context = createContext();
+ await newCampaignSentTrigger.onEnable(context);
+ campaigns.push(...makeCampaigns({ from: 4, to: 153 }));
+ requestedPages = [];
+
+ const emitted = await newCampaignSentTrigger.run(context);
+
+ expect(emitted.length).toBe(150);
+ expect(new Set(emitted.map((campaign) => campaign.CampaignID)).size).toBe(150);
+ expect(requestedPages).toEqual([1, 2]);
+ });
+
+ it('keeps the seen list on republish so campaigns sent meanwhile still fire', async () => {
+ const context = createContext();
+ await newCampaignSentTrigger.onEnable(context);
+ campaigns.push(...makeCampaigns({ from: 4, to: 4 }));
+
+ await newCampaignSentTrigger.onDisable(context);
+ await newCampaignSentTrigger.onEnable({ ...context, isRepublish: true });
+ const emitted = await newCampaignSentTrigger.run(context);
+
+ expect(emitted.map((campaign) => campaign.CampaignID)).toEqual(['c4']);
+ });
+
+ it('re-seeds on republish when nothing is stored yet', async () => {
+ const context = createContext();
+ await newCampaignSentTrigger.onEnable({ ...context, isRepublish: true });
+ expect(await context.store.get(STORE_KEY)).toEqual(['c3', 'c2', 'c1']);
+ });
+});
+
+function makeCampaigns({ from, to }: { from: number; to: number }) {
+ const result = [];
+ for (let id = from; id <= to; id++) {
+ result.push({ CampaignID: `c${id}`, Name: `Campaign ${id}`, SentDate: '2026-10-20 09:30:00' });
+ }
+ return result;
+}
+
+function createContext() {
+ const data = new Map<string, unknown>();
+ return {
+ auth: { secret_text: 'key', type: 'SECRET_TEXT' },
+ propsValue: { clientId: 'client-1' },
+ isRepublish: false,
+ store: {
+ async get(key: string) {
+ return data.get(key) ?? null;
+ },
+ async put(key: string, value: unknown) {
+ data.set(key, value);
+ return value;
+ },
+ async delete(key: string) {
+ data.delete(key);
+ },
+ },
+ };
+}
diff --git a/packages/pieces/community/campaign-monitor/vitest.config.ts b/packages/pieces/community/campaign-monitor/vitest.config.ts
new file mode 100644
index 00000000000..1bd3d1e5fe7
--- /dev/null
+++ b/packages/pieces/community/campaign-monitor/vitest.config.ts
@@ -0,0 +1,19 @@
+import path from 'path'
+import { defineConfig } from 'vitest/config'
+
+const repoRoot = path.resolve(__dirname, '../../../..')
+
+export default defineConfig({
+ test: {
+ globals: true,
+ environment: 'node',
+ },
+ resolve: {
+ alias: {
+ '@activepieces/pieces-framework': path.resolve(repoRoot, 'packages/pieces/framework/src/index.ts'),
+ '@activepieces/pieces-common': path.resolve(repoRoot, 'packages/pieces/common/src/index.ts'),
+ '@activepieces/core-piece-types': path.resolve(repoRoot, 'packages/core/piece-types/src/index.ts'),
+ '@activepieces/core-utils': path.resolve(repoRoot, 'packages/core/utils/src/index.ts'),
+ },
+ },
+})