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(systeme-io): manage courses, communities and subscriptions; react to opt-ins and canceled sales (#15979)

Odai Ahmad4443d4fe0263
diff --git a/bun.lock b/bun.lock
index 01f160364f7..d25adaf9530 100644
--- a/bun.lock
+++ b/bun.lock
@@ -8862,7 +8862,7 @@
},
"packages/pieces/community/systeme-io": {
"name": "@activepieces/piece-systeme-io",
- "version": "0.1.9",
+ "version": "0.2.0",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
@@ -8871,6 +8871,7 @@
},
"devDependencies": {
"tslib": "^2.3.0",
+ "vitest": "3.2.6",
},
},
"packages/pieces/community/tableau": {
diff --git a/packages/pieces/community/systeme-io/package.json b/packages/pieces/community/systeme-io/package.json
index a8baad746c9..51f6a1aa6dd 100644
--- a/packages/pieces/community/systeme-io/package.json
+++ b/packages/pieces/community/systeme-io/package.json
@@ -1,6 +1,6 @@
{
"name": "@activepieces/piece-systeme-io",
- "version": "0.1.9",
+ "version": "0.2.0",
"type": "commonjs",
"main": "./dist/src/index.js",
"types": "./dist/src/index.d.ts",
@@ -11,11 +11,13 @@
"@activepieces/core-utils": "workspace:*"
},
"devDependencies": {
- "tslib": "^2.3.0"
+ "tslib": "^2.3.0",
+ "vitest": "3.2.6"
},
"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"
}
}
diff --git a/packages/pieces/community/systeme-io/src/i18n/translation.json b/packages/pieces/community/systeme-io/src/i18n/translation.json
index c8514527044..9023f1da802 100644
--- a/packages/pieces/community/systeme-io/src/i18n/translation.json
+++ b/packages/pieces/community/systeme-io/src/i18n/translation.json
@@ -1,16 +1,60 @@
{
"Systeme.io is a CRM platform that allows you to manage your contacts, sales, and marketing campaigns.": "Systeme.io is a CRM platform that allows you to manage your contacts, sales, and marketing campaigns.",
- "Your Systeme.io API key. You can find this in your Systeme.io dashboard under Profile Settings > Public API Keys.": "Your Systeme.io API key. You can find this in your Systeme.io dashboard under Profile Settings > Public API Keys.",
+ "Your Systeme.io API key. In your Systeme.io dashboard open Profile > **MCP & API keys** (systeme.io/dashboard/profile/public-api-settings), create a key and paste it here.": "Your Systeme.io API key. In your Systeme.io dashboard open Profile > **MCP & API keys** (systeme.io/dashboard/profile/public-api-settings), create a key and paste it here.",
"Create Contact": "Create Contact",
"Add Tag to Contact": "Add Tag to Contact",
"Remove Tag from Contact": "Remove Tag from Contact",
"Find Contact by Email": "Find Contact by Email",
"Update Contact": "Update Contact",
+ "Find Contacts": "Find Contacts",
+ "Get Contact": "Get Contact",
+ "Delete Contact": "Delete Contact",
+ "Create Tag": "Create Tag",
+ "Delete Tag": "Delete Tag",
+ "Enroll Contact in Course": "Enroll Contact in Course",
+ "Remove Course Access": "Remove Course Access",
+ "Add Contact to Community": "Add Contact to Community",
+ "Remove Contact from Community": "Remove Contact from Community",
+ "Cancel Subscription": "Cancel Subscription",
+ "Create Contact (AI)": "Create Contact (AI)",
+ "Update Contact (AI)": "Update Contact (AI)",
+ "Add Tag to Contact (AI)": "Add Tag to Contact (AI)",
+ "List Tags": "List Tags",
+ "Get Tag": "Get Tag",
+ "Rename Tag": "Rename Tag",
+ "List Contact Fields": "List Contact Fields",
+ "List Courses": "List Courses",
+ "List Course Enrollments": "List Course Enrollments",
+ "List Communities": "List Communities",
+ "List Community Memberships": "List Community Memberships",
+ "List Subscriptions": "List Subscriptions",
"Create a new contact with email and contact fields from your Systeme.io account, with optional tags": "Create a new contact with email and contact fields from your Systeme.io account, with optional tags",
"Assign a tag to an existing contact - select an existing tag or create a new one": "Assign a tag to an existing contact - select an existing tag or create a new one",
"Remove a tag that is currently assigned to an existing contact": "Remove a tag that is currently assigned to an existing contact",
"Locate an existing contact by email address": "Locate an existing contact by email address",
"Update fields (name, phone, custom fields) of an existing contact using fields from your Systeme.io account": "Update fields (name, phone, custom fields) of an existing contact using fields from your Systeme.io account",
+ "Search contacts by email, tags, sign-up date or status": "Search contacts by email, tags, sign-up date or status",
+ "Get a contact with its fields and tags": "Get a contact with its fields and tags",
+ "Permanently delete a contact. This cannot be undone.": "Permanently delete a contact. This cannot be undone.",
+ "Create a tag, or return the existing tag with the same name": "Create a tag, or return the existing tag with the same name",
+ "Permanently delete a tag. It is removed from every contact that has it.": "Permanently delete a tag. It is removed from every contact that has it.",
+ "Give a contact access to a course (full, partial, or drip-fed)": "Give a contact access to a course (full, partial, or drip-fed)",
+ "Remove a contact's enrollment in a course": "Remove a contact's enrollment in a course",
+ "Give a contact membership of a community": "Give a contact membership of a community",
+ "Remove a contact's membership of a community": "Remove a contact's membership of a community",
+ "Cancel one of a contact's subscriptions, now or at the end of the billing period": "Cancel one of a contact's subscriptions, now or at the end of the billing period",
+ "Create a contact with fields and existing tag ids": "Create a contact with fields and existing tag ids",
+ "Change a contact's field values or locale": "Change a contact's field values or locale",
+ "Assign an existing tag to a contact by id": "Assign an existing tag to a contact by id",
+ "List tags, optionally filtered by a search text": "List tags, optionally filtered by a search text",
+ "Get a tag by id": "Get a tag by id",
+ "Change the name of a tag": "Change the name of a tag",
+ "List the contact fields defined in the account": "List the contact fields defined in the account",
+ "List courses, optionally filtered by name or active state": "List courses, optionally filtered by name or active state",
+ "List course enrollments, filtered by course and/or contact": "List course enrollments, filtered by course and/or contact",
+ "List communities, optionally filtered by name": "List communities, optionally filtered by name",
+ "List community memberships, filtered by community and/or contact": "List community memberships, filtered by community and/or contact",
+ "List a contact's subscriptions": "List a contact's subscriptions",
"Email": "Email",
"Language": "Language",
"Contact Fields": "Contact Fields",
@@ -23,6 +67,33 @@
"New Tag Name": "New Tag Name",
"Tag to Remove": "Tag to Remove",
"Custom Fields (Manual Entry)": "Custom Fields (Manual Entry)",
+ "Has All Tags": "Has All Tags",
+ "Registered After": "Registered After",
+ "Registered Before": "Registered Before",
+ "Unsubscribed": "Unsubscribed",
+ "Bounced": "Bounced",
+ "Needs Confirmation": "Needs Confirmation",
+ "Max Results": "Max Results",
+ "Continue After (cursor)": "Continue After (cursor)",
+ "Contact": "Contact",
+ "Tag Name": "Tag Name",
+ "Tag": "Tag",
+ "Course": "Course",
+ "Access Type": "Access Type",
+ "Modules": "Modules",
+ "Community": "Community",
+ "Subscription": "Subscription",
+ "When": "When",
+ "Locale": "Locale",
+ "Fields": "Fields",
+ "Tag IDs": "Tag IDs",
+ "Tag ID": "Tag ID",
+ "Search": "Search",
+ "Starting After": "Starting After",
+ "New Name": "New Name",
+ "Active Filter": "Active Filter",
+ "Course ID": "Course ID",
+ "Community ID": "Community ID",
"Contact email address": "Contact email address",
"Contact preferred language": "Contact preferred language",
"Set contact fields from your Systeme.io account": "Set contact fields from your Systeme.io account",
@@ -30,7 +101,7 @@
"Choose how to handle tags for this contact": "Choose how to handle tags for this contact",
"Select existing tags to assign": "Select existing tags to assign",
"Enter names for new tags to create and assign (only used when \"Create New Tags\" is selected)": "Enter names for new tags to create and assign (only used when \"Create New Tags\" is selected)",
- "Select a contact by ID": "Select a contact by ID",
+ "Select a contact. Type a name (searches the newest 100), a full email address or a contact id.": "Select a contact. Type a name (searches the newest 100), a full email address or a contact id.",
"Choose whether to use an existing tag or create a new one": "Choose whether to use an existing tag or create a new one",
"Select an existing tag": "Select an existing tag",
"Enter the name for the new tag (only used when \"Create New Tag\" is selected)": "Enter the name for the new tag (only used when \"Create New Tag\" is selected)",
@@ -38,6 +109,46 @@
"The email address to search for": "The email address to search for",
"Select which contact fields to update": "Select which contact fields to update",
"Add or update custom fields with manual slug entry (use empty value to clear field)": "Add or update custom fields with manual slug entry (use empty value to clear field)",
+ "Optional. Change the contact's preferred language. Leave empty to keep the current language.": "Optional. Change the contact's preferred language. Leave empty to keep the current language.",
+ "Optional email address, matched exactly but ignoring case, e.g. \"[email protected]\".": "Optional email address, matched exactly but ignoring case, e.g. \"[email protected]\".",
+ "Optional. Only contacts that have every selected tag. Agents can pass numeric tag ids.": "Optional. Only contacts that have every selected tag. Agents can pass numeric tag ids.",
+ "Optional ISO 8601 date-time, e.g. \"2026-01-01T00:00:00Z\".": "Optional ISO 8601 date-time, e.g. \"2026-01-01T00:00:00Z\".",
+ "Optional ISO 8601 date-time, e.g. \"2026-02-01T00:00:00Z\".": "Optional ISO 8601 date-time, e.g. \"2026-02-01T00:00:00Z\".",
+ "Optional. Yes: only contacts unsubscribed from emails. No: only contacts still subscribed to emails. Leave empty for both.": "Optional. Yes: only contacts unsubscribed from emails. No: only contacts still subscribed to emails. Leave empty for both.",
+ "Optional. Yes: only contacts whose emails bounced. No: only contacts whose emails did not bounce. Leave empty for both.": "Optional. Yes: only contacts whose emails bounced. No: only contacts whose emails did not bounce. Leave empty for both.",
+ "Optional. Yes: only contacts who still have to confirm their opt-in. No: only contacts who do not need to confirm their opt-in. Leave empty for both.": "Optional. Yes: only contacts who still have to confirm their opt-in. No: only contacts who do not need to confirm their opt-in. Leave empty for both.",
+ "How many contacts to return at most (1-1000). Default 100.": "How many contacts to return at most (1-1000). Default 100.",
+ "Optional. The Next Cursor value from a previous run, to fetch the following contacts.": "Optional. The Next Cursor value from a previous run, to fetch the following contacts.",
+ "Pick a contact: type a name (searches the newest 100), a full email address or a contact id, or map a contact id. Agents can pass the numeric contact id directly.": "Pick a contact: type a name (searches the newest 100), a full email address or a contact id, or map a contact id. Agents can pass the numeric contact id directly.",
+ "The tag name, up to 64 characters, e.g. \"Webinar 2026 attendee\".": "The tag name, up to 64 characters, e.g. \"Webinar 2026 attendee\".",
+ "Pick a tag (type to search), or map a tag id. Agents can pass the numeric tag id directly.": "Pick a tag (type to search), or map a tag id. Agents can pass the numeric tag id directly.",
+ "Pick a course (type to search), or map a course id. Agents can pass the numeric course id directly.": "Pick a course (type to search), or map a course id. Agents can pass the numeric course id directly.",
+ "What the contact can open. 'full_access' = the whole course; 'partial_access' = only the selected modules; 'dripping_content' = lectures unlock on the course's drip schedule; 'partial_dripping_access' = selected modules on the drip schedule.": "What the contact can open. 'full_access' = the whole course; 'partial_access' = only the selected modules; 'dripping_content' = lectures unlock on the course's drip schedule; 'partial_dripping_access' = selected modules on the drip schedule.",
+ "Required for \"Partial access\" and \"Partial dripping access\": the modules the contact can open. Ignored for full access and dripping content. Agents can pass module ids.": "Required for \"Partial access\" and \"Partial dripping access\": the modules the contact can open. Ignored for full access and dripping content. Agents can pass module ids.",
+ "Pick a community (type to search), or map a community id. Agents can pass the numeric community id directly.": "Pick a community (type to search), or map a community id. Agents can pass the numeric community id directly.",
+ "Pick one of the contact's subscriptions, or map a subscription id. Agents can pass the numeric subscription id directly.": "Pick one of the contact's subscriptions, or map a subscription id. Agents can pass the numeric subscription id directly.",
+ "'WhenBillingPeriodEnds' (default) keeps access until the paid period ends; 'Now' cancels immediately.": "'WhenBillingPeriodEnds' (default) keeps access until the paid period ends; 'Now' cancels immediately.",
+ "The contact email address, e.g. \"[email protected]\".": "The contact email address, e.g. \"[email protected]\".",
+ "Optional two-letter language code: en, fr, es, it, pt, de, nl, ru, jp, tr, ar, zh, sv, ro, cs, hu, sk, dk, id, pl, el, sr, hi, no, th, sq, sl or ua.": "Optional two-letter language code: en, fr, es, it, pt, de, nl, ru, jp, tr, ar, zh, sv, ro, cs, hu, sk, dk, id, pl, el, sr, hi, no, th, sq, sl or ua.",
+ "Optional field values, e.g. [{\"slug\":\"first_name\",\"value\":\"Jane\"},{\"slug\":\"country\",\"value\":\"US\"}]. Country takes a 2-letter ISO code.": "Optional field values, e.g. [{\"slug\":\"first_name\",\"value\":\"Jane\"},{\"slug\":\"country\",\"value\":\"US\"}]. Country takes a 2-letter ISO code.",
+ "Optional numeric ids of existing tags to assign, e.g. [\"123\",\"456\"].": "Optional numeric ids of existing tags to assign, e.g. [\"123\",\"456\"].",
+ "Numeric contact id, e.g. \"12345\".": "Numeric contact id, e.g. \"12345\".",
+ "Field values to set, e.g. [{\"slug\":\"phone_number\",\"value\":\"+15551234\"}]. Use {\"slug\":\"phone_number\",\"value\":null} to clear a field. Slugs you leave out are not touched.": "Field values to set, e.g. [{\"slug\":\"phone_number\",\"value\":\"+15551234\"}]. Use {\"slug\":\"phone_number\",\"value\":null} to clear a field. Slugs you leave out are not touched.",
+ "Optional new two-letter language code (en, fr, es, de, jp, dk, ua, ...). Omit to keep the current one.": "Optional new two-letter language code (en, fr, es, de, jp, dk, ua, ...). Omit to keep the current one.",
+ "Numeric tag id, e.g. \"678\" (from systeme_list_tags).": "Numeric tag id, e.g. \"678\" (from systeme_list_tags).",
+ "Optional text to search tag names for, e.g. \"webinar\".": "Optional text to search tag names for, e.g. \"webinar\".",
+ "Maximum rows to return, 1-1000 (default 100). The action pages automatically.": "Maximum rows to return, 1-1000 (default 100). The action pages automatically.",
+ "Optional cursor: the next_cursor value from a previous call, to continue listing.": "Optional cursor: the next_cursor value from a previous call, to continue listing.",
+ "Numeric tag id, e.g. \"123456\" (from systeme_list_tags).": "Numeric tag id, e.g. \"123456\" (from systeme_list_tags).",
+ "The new tag name, up to 64 characters.": "The new tag name, up to 64 characters.",
+ "Optional text matched against course, module or lecture names.": "Optional text matched against course, module or lecture names.",
+ "Optional. \"true\" lists active courses only, \"false\" inactive only; leave empty for all.": "Optional. \"true\" lists active courses only, \"false\" inactive only; leave empty for all.",
+ "Optional numeric course id (from systeme_list_courses).": "Optional numeric course id (from systeme_list_courses).",
+ "Optional numeric contact id (from find_contacts or a trigger).": "Optional numeric contact id (from find_contacts or a trigger).",
+ "Optional text to search community names for.": "Optional text to search community names for.",
+ "Optional numeric community id (from systeme_list_communities).": "Optional numeric community id (from systeme_list_communities).",
+ "Optional numeric contact id.": "Optional numeric contact id.",
+ "Numeric contact id, e.g. \"12345\" (from find_contacts, findContactByEmail or a sale trigger's customer.contactId).": "Numeric contact id, e.g. \"12345\" (from find_contacts, findContactByEmail or a sale trigger's customer.contactId).",
"English": "English",
"French": "French",
"Spanish": "Spanish",
@@ -71,10 +182,27 @@
"Create New Tags": "Create New Tags",
"Use Existing Tag": "Use Existing Tag",
"Create New Tag": "Create New Tag",
+ "Yes": "Yes",
+ "No": "No",
+ "Full access": "Full access",
+ "Partial access (selected modules)": "Partial access (selected modules)",
+ "Dripping content": "Dripping content",
+ "Partial dripping access (selected modules)": "Partial dripping access (selected modules)",
+ "At the end of the billing period": "At the end of the billing period",
+ "Immediately": "Immediately",
"New Contact": "New Contact",
"New Sale": "New Sale",
"New Tag Added to Contact": "New Tag Added to Contact",
+ "Tag Removed from Contact": "Tag Removed from Contact",
+ "New Opt-in": "New Opt-in",
+ "Sale Canceled": "Sale Canceled",
"Fires when a new contact is created": "Fires when a new contact is created",
"Fires when a new purchase is made within a funnel": "Fires when a new purchase is made within a funnel",
- "Fires when a specific tag is assigned to a contact": "Fires when a specific tag is assigned to a contact"
+ "Fires when a tag is assigned to a contact (optionally only a chosen tag)": "Fires when a tag is assigned to a contact (optionally only a chosen tag)",
+ "Fires when a tag is removed from a contact (optionally only a chosen tag)": "Fires when a tag is removed from a contact (optionally only a chosen tag)",
+ "Fires when a contact submits an opt-in form, including contacts that already exist": "Fires when a contact submits an opt-in form, including contacts that already exist",
+ "Fires when a sale is canceled (a subscription is canceled or a one-off payment is refunded)": "Fires when a sale is canceled (a subscription is canceled or a one-off payment is refunded)",
+ "Only for Tag": "Only for Tag",
+ "Optional. Pick a tag to run the flow only when that tag is added. Leave empty to run for every tag.": "Optional. Pick a tag to run the flow only when that tag is added. Leave empty to run for every tag.",
+ "Optional. Pick a tag to run the flow only when that tag is removed. Leave empty to run for every tag.": "Optional. Pick a tag to run the flow only when that tag is removed. Leave empty to run for every tag."
}
\ No newline at end of file
diff --git a/packages/pieces/community/systeme-io/src/index.ts b/packages/pieces/community/systeme-io/src/index.ts
index 596d5966654..5a41eff27ca 100644
--- a/packages/pieces/community/systeme-io/src/index.ts
+++ b/packages/pieces/community/systeme-io/src/index.ts
@@ -4,18 +4,32 @@ import { systemeIoAuth } from "./lib/common/auth"
import { newContact } from "./lib/triggers/new-contact";
import { newSale } from "./lib/triggers/new-sale";
import { newTagAddedToContact } from "./lib/triggers/new-tag-added-to-contact"
+import { contactTagRemoved } from "./lib/triggers/contact-tag-removed";
+import { newOptIn } from "./lib/triggers/new-opt-in";
+import { saleCanceled } from "./lib/triggers/sale-canceled";
import { createContact } from "./lib/actions/create-contact";
import { addTagToContact } from "./lib/actions/add-tag-to-contact";
import { removeTagFromContact } from "./lib/actions/remove-tag-from-contact";
import { findContactByEmail } from "./lib/actions/find-contact-by-email";
import { updateContact } from "./lib/actions/update-contact"
+import { findContacts } from "./lib/actions/find-contacts";
+import { getContact } from "./lib/actions/get-contact";
+import { deleteContact } from "./lib/actions/delete-contact";
+import { createTag } from "./lib/actions/create-tag";
+import { deleteTag } from "./lib/actions/delete-tag";
+import { enrollContactInCourse } from "./lib/actions/enroll-contact-in-course";
+import { removeCourseEnrollment } from "./lib/actions/remove-course-enrollment";
+import { addContactToCommunity } from "./lib/actions/add-contact-to-community";
+import { removeContactFromCommunity } from "./lib/actions/remove-contact-from-community";
+import { cancelSubscription } from "./lib/actions/cancel-subscription";
+import { systemeAiActions } from "./lib/actions/ai";
import { PieceCategory } from '@activepieces/pieces-framework';
export const systemeIo = createPiece({
displayName: "Systeme.io",
auth: systemeIoAuth,
- minimumSupportedRelease: '0.36.1',
+ minimumSupportedRelease: '0.88.2',
categories: [PieceCategory.MARKETING],
description: "Systeme.io is a CRM platform that allows you to manage your contacts, sales, and marketing campaigns.",
logoUrl: "https://cdn.activepieces.com/pieces/systeme-io.png",
@@ -26,10 +40,24 @@ export const systemeIo = createPiece({
removeTagFromContact,
findContactByEmail,
updateContact,
+ findContacts,
+ getContact,
+ deleteContact,
+ createTag,
+ deleteTag,
+ enrollContactInCourse,
+ removeCourseEnrollment,
+ addContactToCommunity,
+ removeContactFromCommunity,
+ cancelSubscription,
+ ...systemeAiActions,
],
triggers: [
newContact,
newSale,
newTagAddedToContact,
+ contactTagRemoved,
+ newOptIn,
+ saleCanceled,
],
});
diff --git a/packages/pieces/community/systeme-io/src/lib/actions/add-contact-to-community.ts b/packages/pieces/community/systeme-io/src/lib/actions/add-contact-to-community.ts
new file mode 100644
index 00000000000..565b7164acf
--- /dev/null
+++ b/packages/pieces/community/systeme-io/src/lib/actions/add-contact-to-community.ts
@@ -0,0 +1,36 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { systemeIoAuth } from '../common/auth';
+import { systemeIoCommon, systemeIoInput } from '../common/client';
+import { communityDropdown, contactPicker } from '../common/dropdowns';
+import { addToCommunityOutputSchema } from '../output-schemas';
+
+export const addContactToCommunity = createAction({
+ auth: systemeIoAuth,
+ name: 'add_contact_to_community',
+ classification: 'WRITE',
+ displayName: 'Add Contact to Community',
+ description: 'Give a contact membership of a community',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Requests membership of a Systeme.io community for a contact. Systeme.io queues the request (HTTP 202), so the membership may take a moment to appear in the community member list. Use to grant community access after a purchase or signup. Not idempotent: repeat behaviour is undocumented.',
+ idempotent: false,
+ },
+ props: {
+ community_id: communityDropdown,
+ contact_id: contactPicker({ required: true }),
+ },
+ outputSchema: addToCommunityOutputSchema,
+ async run(context) {
+ const communityId = systemeIoInput.requireId({ value: context.propsValue.community_id, name: 'Community' });
+ const contactId = systemeIoInput.requireId({ value: context.propsValue.contact_id, name: 'Contact' });
+ await systemeIoCommon.apiCall({
+ method: HttpMethod.POST,
+ url: `/community/communities/${communityId}/memberships`,
+ auth: context.auth.secret_text,
+ body: { contactId },
+ });
+ return { queued: true, community_id: communityId, contact_id: contactId };
+ },
+});
diff --git a/packages/pieces/community/systeme-io/src/lib/actions/add-tag-to-contact.ts b/packages/pieces/community/systeme-io/src/lib/actions/add-tag-to-contact.ts
index 13a313469b8..fa1dd8ce856 100644
--- a/packages/pieces/community/systeme-io/src/lib/actions/add-tag-to-contact.ts
+++ b/packages/pieces/community/systeme-io/src/lib/actions/add-tag-to-contact.ts
@@ -1,8 +1,9 @@
import { createAction, Property } from '@activepieces/pieces-framework';
import { HttpMethod } from '@activepieces/pieces-common';
import { systemeIoAuth } from '../common/auth';
-import { systemeIoCommon } from '../common/client';
+import { systemeIoCommon, systemeIoInput } from '../common/client';
import { systemeIoProps } from '../common/props';
+import { systemeIoAuthTagOptions } from '../common/dropdowns';
import { addTagToContactActionOutputSchema } from '../output-schemas';
export const addTagToContact = createAction({
@@ -11,7 +12,7 @@ export const addTagToContact = createAction({
classification: 'WRITE',
displayName: 'Add Tag to Contact',
description: 'Assign a tag to an existing contact - select an existing tag or create a new one',
- audience: 'both',
+ audience: 'human',
aiMetadata: { description: 'Assigns a tag to an existing Systeme.io contact, identified by contact id. Operates in two modes: reference an existing tag by id, or create a brand-new tag by name and then assign it. Use to label or segment a known contact; assigning an existing tag is effectively idempotent, but the create-new-tag mode creates a fresh tag on each call, so this is not idempotent overall.', idempotent: false },
props: {
contactId: systemeIoProps.contactIdDropdown,
@@ -34,7 +35,8 @@ export const addTagToContact = createAction({
description: 'Select an existing tag',
required: false,
refreshers: ['tagSource'],
- options: async ({ auth, tagSource }) => {
+ refreshOnSearch: true,
+ options: async ({ auth, tagSource }, ctx) => {
if (!auth || tagSource !== 'existing') {
return {
disabled: true,
@@ -43,44 +45,7 @@ export const addTagToContact = createAction({
};
}
- try {
- const response = await systemeIoCommon.getTags({
- auth: auth.secret_text,
- });
-
- let tags: any[] = [];
- if (Array.isArray(response)) {
- tags = response;
- } else if (response && typeof response === 'object' && response !== null) {
- const responseAny = response as any;
- if (responseAny.items && Array.isArray(responseAny.items)) {
- tags = responseAny.items;
- }
- }
-
- if (tags.length > 0) {
- return {
- disabled: false,
- options: tags.map((tag: any) => ({
- label: tag.name,
- value: tag.id,
- })),
- };
- }
-
- return {
- disabled: true,
- placeholder: 'No tags found',
- options: [],
- };
- } catch (error) {
- console.error('Error fetching tags:', error);
- return {
- disabled: true,
- placeholder: 'Error loading tags',
- options: [],
- };
- }
+ return systemeIoAuthTagOptions({ apiKey: auth.secret_text, searchValue: ctx?.searchValue });
},
}),
newTagName: Property.ShortText({
@@ -92,6 +57,7 @@ export const addTagToContact = createAction({
outputSchema: addTagToContactActionOutputSchema,
async run(context) {
const { contactId, tagSource, existingTagId, newTagName } = context.propsValue;
+ const contact = systemeIoInput.requireId({ value: contactId, name: 'Contact ID' });
let tagId: string | number;
let tagCreated = false;
@@ -125,7 +91,7 @@ export const addTagToContact = createAction({
const response = await systemeIoCommon.apiCall({
method: HttpMethod.POST,
- url: `/contacts/${contactId}/tags`,
+ url: `/contacts/${contact}/tags`,
body: {
tagId: tagId,
},
diff --git a/packages/pieces/community/systeme-io/src/lib/actions/ai/add-tag-to-contact.ts b/packages/pieces/community/systeme-io/src/lib/actions/ai/add-tag-to-contact.ts
new file mode 100644
index 00000000000..5e66056dcb1
--- /dev/null
+++ b/packages/pieces/community/systeme-io/src/lib/actions/ai/add-tag-to-contact.ts
@@ -0,0 +1,53 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { systemeIoAuth } from '../../common/auth';
+import { apiErrorStatus, systemeIoCommon, systemeIoInput } from '../../common/client';
+import { systemeOps } from '../../common/operations';
+import { aiAddTagOutputSchema } from '../../output-schemas-ai';
+
+export const systemeAddTagToContact = createAction({
+ auth: systemeIoAuth,
+ name: 'systeme_add_tag_to_contact',
+ classification: 'WRITE',
+ displayName: 'Add Tag to Contact (AI)',
+ description: 'Assign an existing tag to a contact by id',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Assigns an existing Systeme.io tag to a contact, both given by numeric id; tagging often starts automations in systeme.io. Get the tag id from systeme_list_tags or create_tag (which also creates a missing tag). Idempotent: assigning a tag the contact already has succeeds again and changes nothing.',
+ idempotent: true,
+ },
+ props: {
+ contact_id: Property.ShortText({
+ displayName: 'Contact ID',
+ description: 'Numeric contact id, e.g. "12345".',
+ required: true,
+ }),
+ tag_id: Property.ShortText({
+ displayName: 'Tag ID',
+ description: 'Numeric tag id, e.g. "678" (from systeme_list_tags).',
+ required: true,
+ }),
+ },
+ outputSchema: aiAddTagOutputSchema,
+ async run(context) {
+ const apiKey = context.auth.secret_text;
+ const contactId = systemeIoInput.requireId({ value: context.propsValue.contact_id, name: 'contact_id' });
+ const tagId = systemeIoInput.requireId({ value: context.propsValue.tag_id, name: 'tag_id' });
+ try {
+ await systemeIoCommon.apiCall({
+ method: HttpMethod.POST,
+ url: `/contacts/${contactId}/tags`,
+ auth: apiKey,
+ body: { tagId },
+ });
+ return { assigned: true, already_assigned: false, contact_id: contactId, tag_id: tagId };
+ } catch (error) {
+ const onContact = apiErrorStatus(error) === 422 && (await systemeOps.tagIsOnContact({ apiKey, contactId, tagId }).catch(() => false));
+ if (onContact) {
+ return { assigned: true, already_assigned: true, contact_id: contactId, tag_id: tagId };
+ }
+ throw error;
+ }
+ },
+});
diff --git a/packages/pieces/community/systeme-io/src/lib/actions/ai/common.ts b/packages/pieces/community/systeme-io/src/lib/actions/ai/common.ts
new file mode 100644
index 00000000000..6ea0cdfa969
--- /dev/null
+++ b/packages/pieces/community/systeme-io/src/lib/actions/ai/common.ts
@@ -0,0 +1,72 @@
+import { Property } from '@activepieces/pieces-framework';
+import { systemeIoCommon, systemeIoInput } from '../../common/client';
+
+async function list<T extends { id?: unknown }, R>({
+ apiKey,
+ url,
+ query,
+ maxResults,
+ startingAfter,
+ map,
+}: {
+ apiKey: string;
+ url: string;
+ query?: Record<string, string | number | boolean | undefined>;
+ maxResults: unknown;
+ startingAfter: unknown;
+ map: (row: T) => R;
+}) {
+ const page = await systemeIoCommon.paginate<T>({
+ auth: apiKey,
+ url,
+ query,
+ maxItems: systemeIoInput.clampInt({ value: maxResults, name: 'max_results', min: 1, max: 1000, fallback: 100 }),
+ startingAfter: systemeIoInput.optionalId({ value: startingAfter, name: 'starting_after' }),
+ });
+ return {
+ items: page.items.map(map),
+ count: page.items.length,
+ has_more: page.hasMore,
+ next_cursor: page.nextCursor,
+ };
+}
+
+function optionalBoolean({ value, name }: { value: unknown; name: string }): boolean | undefined {
+ if (value === undefined || value === null || value === '') return undefined;
+ if (value === true || value === 'true') return true;
+ if (value === false || value === 'false') return false;
+ throw new Error(`${name} must be true or false.`);
+}
+
+function fieldsInput({ value }: { value: unknown }): { slug: string; value: string | null }[] {
+ if (value === undefined || value === null || value === '') return [];
+ if (!Array.isArray(value)) {
+ throw new Error('fields must be a list of {"slug": "...", "value": "..."} objects.');
+ }
+ return value.map((item: unknown, index: number) => {
+ if (typeof item !== 'object' || item === null) {
+ throw new Error(`fields[${index}] must be an object with a slug and a value.`);
+ }
+ const slug: unknown = Reflect.get(item, 'slug');
+ const raw: unknown = Reflect.get(item, 'value');
+ if (typeof slug !== 'string' || slug.trim() === '') {
+ throw new Error(`fields[${index}].slug is required (get slugs from systeme_list_contact_fields).`);
+ }
+ const fieldValue = raw === undefined || raw === null || raw === '' ? null : String(raw);
+ return { slug: slug.trim(), value: fieldValue };
+ });
+}
+
+const maxResultsProp = Property.Number({
+ displayName: 'Max Results',
+ description: 'Maximum rows to return, 1-1000 (default 100). The action pages automatically.',
+ required: false,
+});
+
+const startingAfterProp = Property.ShortText({
+ displayName: 'Starting After',
+ description: 'Optional cursor: the next_cursor value from a previous call, to continue listing.',
+ required: false,
+});
+
+export const aiCommon = { list, optionalBoolean, fieldsInput, maxResultsProp, startingAfterProp };
diff --git a/packages/pieces/community/systeme-io/src/lib/actions/ai/create-contact.ts b/packages/pieces/community/systeme-io/src/lib/actions/ai/create-contact.ts
new file mode 100644
index 00000000000..0cd982d3121
--- /dev/null
+++ b/packages/pieces/community/systeme-io/src/lib/actions/ai/create-contact.ts
@@ -0,0 +1,99 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { systemeIoAuth } from '../../common/auth';
+import { SystemeContact, systemeIoCommon, systemeIoInput } from '../../common/client';
+import { optionalLocale } from '../../common/dropdowns';
+import { aiCreateContactOutputSchema } from '../../output-schemas-ai';
+import { aiCommon } from './common';
+
+export const systemeCreateContact = createAction({
+ auth: systemeIoAuth,
+ name: 'systeme_create_contact',
+ classification: 'WRITE',
+ displayName: 'Create Contact (AI)',
+ description: 'Create a contact with fields and existing tag ids',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Creates a new Systeme.io contact from an email, with optional locale, contact field values (slugs from systeme_list_contact_fields) and existing tag ids (from systeme_list_tags or create_tag). Use to add a new lead; check first with find_contacts when the email may already exist, since a duplicate email fails with a validation error. Not idempotent: each successful call creates a contact. Tag failures are reported per tag instead of failing the call.',
+ idempotent: false,
+ },
+ props: {
+ email: Property.ShortText({
+ displayName: 'Email',
+ description: 'The contact email address, e.g. "[email protected]".',
+ required: true,
+ }),
+ locale: Property.ShortText({
+ displayName: 'Locale',
+ description: "Optional two-letter language code: en, fr, es, it, pt, de, nl, ru, jp, tr, ar, zh, sv, ro, cs, hu, sk, dk, id, pl, el, sr, hi, no, th, sq, sl or ua.",
+ required: false,
+ }),
+ fields: Property.Array({
+ displayName: 'Fields',
+ description: 'Optional field values, e.g. [{"slug":"first_name","value":"Jane"},{"slug":"country","value":"US"}]. Country takes a 2-letter ISO code.',
+ required: false,
+ properties: {
+ slug: Property.ShortText({ displayName: 'Slug', required: true }),
+ value: Property.ShortText({ displayName: 'Value', required: false }),
+ },
+ }),
+ tag_ids: Property.Array({
+ displayName: 'Tag IDs',
+ description: 'Optional numeric ids of existing tags to assign, e.g. ["123","456"].',
+ required: false,
+ }),
+ },
+ outputSchema: aiCreateContactOutputSchema,
+ async run(context) {
+ const p = context.propsValue;
+ const apiKey = context.auth.secret_text;
+ const email = p.email.trim();
+ if (email === '') {
+ throw new Error('email is required.');
+ }
+ const locale = optionalLocale(p.locale);
+ const fields = aiCommon.fieldsInput({ value: p.fields }).filter((field) => field.value !== null);
+ const tagIds = systemeIoInput.idList({ value: p.tag_ids, name: 'tag_ids' });
+
+ const contact = await systemeIoCommon.apiCall<SystemeContact>({
+ method: HttpMethod.POST,
+ url: '/contacts',
+ auth: apiKey,
+ body: {
+ email,
+ ...(locale !== undefined ? { locale } : {}),
+ ...(fields.length > 0 ? { fields } : {}),
+ },
+ });
+
+ const tagResults = [];
+ for (const tagId of tagIds) {
+ try {
+ await systemeIoCommon.apiCall({
+ method: HttpMethod.POST,
+ url: `/contacts/${contact.id}/tags`,
+ auth: apiKey,
+ body: { tagId },
+ });
+ tagResults.push({ tag_id: tagId, assigned: true, error: null });
+ } catch (error) {
+ tagResults.push({ tag_id: tagId, assigned: false, error: error instanceof Error ? error.message : String(error) });
+ }
+ }
+
+ const assigned = tagResults.some((r) => r.assigned);
+ const refreshed = assigned
+ ? await systemeIoCommon.getContact({ contactId: contact.id, auth: apiKey }).catch(() => undefined)
+ : undefined;
+
+ return {
+ contact_id: contact.id,
+ email: contact.email,
+ contact: refreshed ?? contact,
+ tag_results: tagResults,
+ tags_assigned: tagResults.filter((r) => r.assigned).length,
+ tags_failed: tagResults.filter((r) => !r.assigned).length,
+ };
+ },
+});
diff --git a/packages/pieces/community/systeme-io/src/lib/actions/ai/get-tag.ts b/packages/pieces/community/systeme-io/src/lib/actions/ai/get-tag.ts
new file mode 100644
index 00000000000..96411561164
--- /dev/null
+++ b/packages/pieces/community/systeme-io/src/lib/actions/ai/get-tag.ts
@@ -0,0 +1,33 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { systemeIoAuth } from '../../common/auth';
+import { systemeIoCommon, systemeIoInput } from '../../common/client';
+import { tagRow } from '../../common/mappers';
+import { aiTagOutputSchema } from '../../output-schemas-ai';
+
+export const systemeGetTag = createAction({
+ auth: systemeIoAuth,
+ name: 'systeme_get_tag',
+ classification: 'READ',
+ displayName: 'Get Tag',
+ description: 'Get a tag by id',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Retrieves one Systeme.io tag (id, name, created date) by its numeric id. Use to confirm a tag id still exists or read its name; use systeme_list_tags to find a tag by name. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ tag_id: Property.ShortText({
+ displayName: 'Tag ID',
+ description: 'Numeric tag id, e.g. "123456" (from systeme_list_tags).',
+ required: true,
+ }),
+ },
+ outputSchema: aiTagOutputSchema,
+ async run(context) {
+ const id = systemeIoInput.requireId({ value: context.propsValue.tag_id, name: 'tag_id' });
+ const tag = await systemeIoCommon.apiCall<unknown>({ method: HttpMethod.GET, url: `/tags/${id}`, auth: context.auth.secret_text });
+ return tagRow(tag);
+ },
+});
diff --git a/packages/pieces/community/systeme-io/src/lib/actions/ai/index.ts b/packages/pieces/community/systeme-io/src/lib/actions/ai/index.ts
new file mode 100644
index 00000000000..702f3c574fc
--- /dev/null
+++ b/packages/pieces/community/systeme-io/src/lib/actions/ai/index.ts
@@ -0,0 +1,27 @@
+import { systemeAddTagToContact } from './add-tag-to-contact';
+import { systemeCreateContact } from './create-contact';
+import { systemeGetTag } from './get-tag';
+import { systemeListCommunities } from './list-communities';
+import { systemeListCommunityMemberships } from './list-community-memberships';
+import { systemeListContactFields } from './list-contact-fields';
+import { systemeListCourses } from './list-courses';
+import { systemeListEnrollments } from './list-enrollments';
+import { systemeListSubscriptions } from './list-subscriptions';
+import { systemeListTags } from './list-tags';
+import { systemeRenameTag } from './rename-tag';
+import { systemeUpdateContact } from './update-contact';
+
+export const systemeAiActions = [
+ systemeCreateContact,
+ systemeUpdateContact,
+ systemeAddTagToContact,
+ systemeListTags,
+ systemeGetTag,
+ systemeRenameTag,
+ systemeListContactFields,
+ systemeListCourses,
+ systemeListEnrollments,
+ systemeListCommunities,
+ systemeListCommunityMemberships,
+ systemeListSubscriptions,
+];
diff --git a/packages/pieces/community/systeme-io/src/lib/actions/ai/list-communities.ts b/packages/pieces/community/systeme-io/src/lib/actions/ai/list-communities.ts
new file mode 100644
index 00000000000..159247fc182
--- /dev/null
+++ b/packages/pieces/community/systeme-io/src/lib/actions/ai/list-communities.ts
@@ -0,0 +1,41 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { systemeIoAuth } from '../../common/auth';
+import { communityRow } from '../../common/mappers';
+import { aiListCommunitiesOutputSchema } from '../../output-schemas-ai';
+import { aiCommon } from './common';
+
+export const systemeListCommunities = createAction({
+ auth: systemeIoAuth,
+ name: 'systeme_list_communities',
+ classification: 'SEARCH',
+ displayName: 'List Communities',
+ description: 'List communities, optionally filtered by name',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists Systeme.io communities (id, name, path, domain). Use to find the community_id needed by add_contact_to_community and remove_contact_from_community. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ query: Property.ShortText({
+ displayName: 'Search',
+ description: 'Optional text to search community names for.',
+ required: false,
+ }),
+ max_results: aiCommon.maxResultsProp,
+ starting_after: aiCommon.startingAfterProp,
+ },
+ outputSchema: aiListCommunitiesOutputSchema,
+ async run(context) {
+ const p = context.propsValue;
+ const result = await aiCommon.list({
+ apiKey: context.auth.secret_text,
+ url: '/community/communities',
+ query: { query: p.query?.trim() || undefined },
+ maxResults: p.max_results,
+ startingAfter: p.starting_after,
+ map: communityRow,
+ });
+ return { communities: result.items, count: result.count, has_more: result.has_more, next_cursor: result.next_cursor };
+ },
+});
diff --git a/packages/pieces/community/systeme-io/src/lib/actions/ai/list-community-memberships.ts b/packages/pieces/community/systeme-io/src/lib/actions/ai/list-community-memberships.ts
new file mode 100644
index 00000000000..052bd534601
--- /dev/null
+++ b/packages/pieces/community/systeme-io/src/lib/actions/ai/list-community-memberships.ts
@@ -0,0 +1,49 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { systemeIoAuth } from '../../common/auth';
+import { systemeIoInput } from '../../common/client';
+import { membershipRow } from '../../common/mappers';
+import { aiListMembershipsOutputSchema } from '../../output-schemas-ai';
+import { aiCommon } from './common';
+
+export const systemeListCommunityMemberships = createAction({
+ auth: systemeIoAuth,
+ name: 'systeme_list_community_memberships',
+ classification: 'SEARCH',
+ displayName: 'List Community Memberships',
+ description: 'List community memberships, filtered by community and/or contact',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists Systeme.io community memberships (membership id, community and contact id), optionally filtered by community_id and/or contact_id. Use to check whether a contact is already a member; a membership added with add_contact_to_community can take a moment to appear. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ community_id: Property.ShortText({
+ displayName: 'Community ID',
+ description: 'Optional numeric community id (from systeme_list_communities).',
+ required: false,
+ }),
+ contact_id: Property.ShortText({
+ displayName: 'Contact ID',
+ description: 'Optional numeric contact id.',
+ required: false,
+ }),
+ max_results: aiCommon.maxResultsProp,
+ starting_after: aiCommon.startingAfterProp,
+ },
+ outputSchema: aiListMembershipsOutputSchema,
+ async run(context) {
+ const p = context.propsValue;
+ const community = systemeIoInput.optionalId({ value: p.community_id, name: 'community_id' });
+ const contact = systemeIoInput.optionalId({ value: p.contact_id, name: 'contact_id' });
+ const result = await aiCommon.list({
+ apiKey: context.auth.secret_text,
+ url: '/community/memberships',
+ query: { community, contact },
+ maxResults: p.max_results,
+ startingAfter: p.starting_after,
+ map: membershipRow,
+ });
+ return { memberships: result.items, count: result.count, has_more: result.has_more, next_cursor: result.next_cursor };
+ },
+});
diff --git a/packages/pieces/community/systeme-io/src/lib/actions/ai/list-contact-fields.ts b/packages/pieces/community/systeme-io/src/lib/actions/ai/list-contact-fields.ts
new file mode 100644
index 00000000000..2722b638176
--- /dev/null
+++ b/packages/pieces/community/systeme-io/src/lib/actions/ai/list-contact-fields.ts
@@ -0,0 +1,30 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { systemeIoAuth } from '../../common/auth';
+import { systemeIoCommon } from '../../common/client';
+import { aiListContactFieldsOutputSchema } from '../../output-schemas-ai';
+
+export const systemeListContactFields = createAction({
+ auth: systemeIoAuth,
+ name: 'systeme_list_contact_fields',
+ classification: 'SEARCH',
+ displayName: 'List Contact Fields',
+ description: 'List the contact fields defined in the account',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ "Lists the contact fields defined in the Systeme.io account (slug and display name), such as first_name, surname, phone_number, country and custom fields. Use before systeme_create_contact or systeme_update_contact to get the exact slugs. Returns every field in one response (this list has no paging). Read-only and idempotent.",
+ idempotent: true,
+ },
+ props: {},
+ outputSchema: aiListContactFieldsOutputSchema,
+ async run(context) {
+ const response = await systemeIoCommon.apiCall<{ items?: { slug?: string; fieldName?: string }[]; hasMore?: boolean }>({
+ method: HttpMethod.GET,
+ url: '/contact_fields',
+ auth: context.auth.secret_text,
+ });
+ const fields = (response?.items ?? []).map((field) => ({ slug: field.slug ?? null, field_name: field.fieldName ?? null }));
+ return { fields, count: fields.length, has_more: response?.hasMore === true };
+ },
+});
diff --git a/packages/pieces/community/systeme-io/src/lib/actions/ai/list-courses.ts b/packages/pieces/community/systeme-io/src/lib/actions/ai/list-courses.ts
new file mode 100644
index 00000000000..be1273505a6
--- /dev/null
+++ b/packages/pieces/community/systeme-io/src/lib/actions/ai/list-courses.ts
@@ -0,0 +1,46 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { systemeIoAuth } from '../../common/auth';
+import { courseRow } from '../../common/mappers';
+import { aiListCoursesOutputSchema } from '../../output-schemas-ai';
+import { aiCommon } from './common';
+
+export const systemeListCourses = createAction({
+ auth: systemeIoAuth,
+ name: 'systeme_list_courses',
+ classification: 'SEARCH',
+ displayName: 'List Courses',
+ description: 'List courses, optionally filtered by name or active state',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists Systeme.io courses with their id, name, active state and modules (id and name). Use to find the course_id and module ids needed by enroll_contact_in_course and remove_course_enrollment; the search text also matches module and lecture names. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ query: Property.ShortText({
+ displayName: 'Search',
+ description: 'Optional text matched against course, module or lecture names.',
+ required: false,
+ }),
+ active: Property.ShortText({
+ displayName: 'Active Filter',
+ description: 'Optional. "true" lists active courses only, "false" inactive only; leave empty for all.',
+ required: false,
+ }),
+ max_results: aiCommon.maxResultsProp,
+ starting_after: aiCommon.startingAfterProp,
+ },
+ outputSchema: aiListCoursesOutputSchema,
+ async run(context) {
+ const p = context.propsValue;
+ const result = await aiCommon.list({
+ apiKey: context.auth.secret_text,
+ url: '/school/courses',
+ query: { query: p.query?.trim() || undefined, active: aiCommon.optionalBoolean({ value: p.active, name: 'active' }) },
+ maxResults: p.max_results,
+ startingAfter: p.starting_after,
+ map: courseRow,
+ });
+ return { courses: result.items, count: result.count, has_more: result.has_more, next_cursor: result.next_cursor };
+ },
+});
diff --git a/packages/pieces/community/systeme-io/src/lib/actions/ai/list-enrollments.ts b/packages/pieces/community/systeme-io/src/lib/actions/ai/list-enrollments.ts
new file mode 100644
index 00000000000..6ea2d9a0988
--- /dev/null
+++ b/packages/pieces/community/systeme-io/src/lib/actions/ai/list-enrollments.ts
@@ -0,0 +1,52 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { systemeIoAuth } from '../../common/auth';
+import { systemeIoInput } from '../../common/client';
+import { enrollmentRow } from '../../common/mappers';
+import { aiListEnrollmentsOutputSchema } from '../../output-schemas-ai';
+import { aiCommon } from './common';
+
+export const systemeListEnrollments = createAction({
+ auth: systemeIoAuth,
+ name: 'systeme_list_enrollments',
+ classification: 'SEARCH',
+ displayName: 'List Course Enrollments',
+ description: 'List course enrollments, filtered by course and/or contact',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists Systeme.io course enrollments (enrollment id, access type, course and contact), optionally filtered by course_id and/or contact_id. Use to check whether a contact already has access to a course before enrolling or removing them. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ course_id: Property.ShortText({
+ displayName: 'Course ID',
+ description: 'Optional numeric course id (from systeme_list_courses).',
+ required: false,
+ }),
+ contact_id: Property.ShortText({
+ displayName: 'Contact ID',
+ description: 'Optional numeric contact id (from find_contacts or a trigger).',
+ required: false,
+ }),
+ max_results: aiCommon.maxResultsProp,
+ starting_after: aiCommon.startingAfterProp,
+ },
+ outputSchema: aiListEnrollmentsOutputSchema,
+ async run(context) {
+ const p = context.propsValue;
+ const course = systemeIoInput.optionalId({ value: p.course_id, name: 'course_id' });
+ const contact = systemeIoInput.optionalId({ value: p.contact_id, name: 'contact_id' });
+ const result = await aiCommon.list({
+ apiKey: context.auth.secret_text,
+ url: '/school/enrollments',
+ query: { course, contact },
+ maxResults: p.max_results,
+ startingAfter: p.starting_after,
+ map: enrollmentRow,
+ });
+ const enrollments = result.items.filter(
+ (row) => (course === undefined || Number(row.course_id) === course) && (contact === undefined || Number(row.contact_id) === contact),
+ );
+ return { enrollments, count: enrollments.length, has_more: result.has_more, next_cursor: result.next_cursor };
+ },
+});
diff --git a/packages/pieces/community/systeme-io/src/lib/actions/ai/list-subscriptions.ts b/packages/pieces/community/systeme-io/src/lib/actions/ai/list-subscriptions.ts
new file mode 100644
index 00000000000..af3ee331d8e
--- /dev/null
+++ b/packages/pieces/community/systeme-io/src/lib/actions/ai/list-subscriptions.ts
@@ -0,0 +1,43 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { systemeIoAuth } from '../../common/auth';
+import { systemeIoInput } from '../../common/client';
+import { subscriptionRow } from '../../common/mappers';
+import { aiListSubscriptionsOutputSchema } from '../../output-schemas-ai';
+import { aiCommon } from './common';
+
+export const systemeListSubscriptions = createAction({
+ auth: systemeIoAuth,
+ name: 'systeme_list_subscriptions',
+ classification: 'SEARCH',
+ displayName: 'List Subscriptions',
+ description: "List a contact's subscriptions",
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ "Lists one Systeme.io contact's subscriptions with status (active, cancelled, completed, in_charge, incomplete, incomplete_expired), dates and price plan. Use to find the subscription_id for cancel_subscription or to check whether a contact still pays. A contact_id is required. Read-only and idempotent.",
+ idempotent: true,
+ },
+ props: {
+ contact_id: Property.ShortText({
+ displayName: 'Contact ID',
+ description: 'Numeric contact id, e.g. "12345" (from find_contacts, findContactByEmail or a sale trigger\'s customer.contactId).',
+ required: true,
+ }),
+ max_results: aiCommon.maxResultsProp,
+ starting_after: aiCommon.startingAfterProp,
+ },
+ outputSchema: aiListSubscriptionsOutputSchema,
+ async run(context) {
+ const p = context.propsValue;
+ const contact = systemeIoInput.requireId({ value: p.contact_id, name: 'contact_id' });
+ const result = await aiCommon.list({
+ apiKey: context.auth.secret_text,
+ url: '/payment/subscriptions',
+ query: { contact },
+ maxResults: p.max_results,
+ startingAfter: p.starting_after,
+ map: subscriptionRow,
+ });
+ return { subscriptions: result.items, count: result.count, has_more: result.has_more, next_cursor: result.next_cursor };
+ },
+});
diff --git a/packages/pieces/community/systeme-io/src/lib/actions/ai/list-tags.ts b/packages/pieces/community/systeme-io/src/lib/actions/ai/list-tags.ts
new file mode 100644
index 00000000000..1704d0752f2
--- /dev/null
+++ b/packages/pieces/community/systeme-io/src/lib/actions/ai/list-tags.ts
@@ -0,0 +1,41 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { systemeIoAuth } from '../../common/auth';
+import { tagRow } from '../../common/mappers';
+import { aiListTagsOutputSchema } from '../../output-schemas-ai';
+import { aiCommon } from './common';
+
+export const systemeListTags = createAction({
+ auth: systemeIoAuth,
+ name: 'systeme_list_tags',
+ classification: 'SEARCH',
+ displayName: 'List Tags',
+ description: 'List tags, optionally filtered by a search text',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists Systeme.io tags (id, name, created date), newest first, optionally filtered by a search text. Use to resolve a tag name to the tag_id that the tagging, contact-search and delete actions need; use create_tag to get-or-create a tag by exact name. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ query: Property.ShortText({
+ displayName: 'Search',
+ description: 'Optional text to search tag names for, e.g. "webinar".',
+ required: false,
+ }),
+ max_results: aiCommon.maxResultsProp,
+ starting_after: aiCommon.startingAfterProp,
+ },
+ outputSchema: aiListTagsOutputSchema,
+ async run(context) {
+ const p = context.propsValue;
+ const result = await aiCommon.list({
+ apiKey: context.auth.secret_text,
+ url: '/tags',
+ query: { query: p.query?.trim() || undefined },
+ maxResults: p.max_results,
+ startingAfter: p.starting_after,
+ map: tagRow,
+ });
+ return { tags: result.items, count: result.count, has_more: result.has_more, next_cursor: result.next_cursor };
+ },
+});
diff --git a/packages/pieces/community/systeme-io/src/lib/actions/ai/rename-tag.ts b/packages/pieces/community/systeme-io/src/lib/actions/ai/rename-tag.ts
new file mode 100644
index 00000000000..b0884ca8043
--- /dev/null
+++ b/packages/pieces/community/systeme-io/src/lib/actions/ai/rename-tag.ts
@@ -0,0 +1,45 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { systemeIoAuth } from '../../common/auth';
+import { systemeIoCommon, systemeIoInput } from '../../common/client';
+import { tagRow } from '../../common/mappers';
+import { systemeOps } from '../../common/operations';
+import { aiTagOutputSchema } from '../../output-schemas-ai';
+
+export const systemeRenameTag = createAction({
+ auth: systemeIoAuth,
+ name: 'systeme_rename_tag',
+ classification: 'WRITE',
+ displayName: 'Rename Tag',
+ description: 'Change the name of a tag',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Renames an existing Systeme.io tag; the tag keeps its id and stays on every contact that has it. Use when a tag should be relabelled rather than replaced. Names are at most 64 characters. Idempotent: renaming to the same name again changes nothing.',
+ idempotent: true,
+ },
+ props: {
+ tag_id: Property.ShortText({
+ displayName: 'Tag ID',
+ description: 'Numeric tag id, e.g. "123456" (from systeme_list_tags).',
+ required: true,
+ }),
+ name: Property.ShortText({
+ displayName: 'New Name',
+ description: 'The new tag name, up to 64 characters.',
+ required: true,
+ }),
+ },
+ outputSchema: aiTagOutputSchema,
+ async run(context) {
+ const id = systemeIoInput.requireId({ value: context.propsValue.tag_id, name: 'tag_id' });
+ const name = systemeOps.validTagName(context.propsValue.name);
+ const tag = await systemeIoCommon.apiCall<unknown>({
+ method: HttpMethod.PUT,
+ url: `/tags/${id}`,
+ auth: context.auth.secret_text,
+ body: { name },
+ });
+ return tagRow(tag);
+ },
+});
diff --git a/packages/pieces/community/systeme-io/src/lib/actions/ai/update-contact.ts b/packages/pieces/community/systeme-io/src/lib/actions/ai/update-contact.ts
new file mode 100644
index 00000000000..b531ac45abc
--- /dev/null
+++ b/packages/pieces/community/systeme-io/src/lib/actions/ai/update-contact.ts
@@ -0,0 +1,69 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { systemeIoAuth } from '../../common/auth';
+import { SystemeContact, systemeIoCommon, systemeIoInput } from '../../common/client';
+import { optionalLocale } from '../../common/dropdowns';
+import { aiUpdateContactOutputSchema } from '../../output-schemas-ai';
+import { aiCommon } from './common';
+
+export const systemeUpdateContact = createAction({
+ auth: systemeIoAuth,
+ name: 'systeme_update_contact',
+ classification: 'WRITE',
+ displayName: 'Update Contact (AI)',
+ description: "Change a contact's field values or locale",
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ "Partially updates a Systeme.io contact: only the field slugs you pass change, every other field is left as it is, and a field with an empty or null value is cleared. Optionally changes the locale. Use to correct or enrich a known contact (slugs from systeme_list_contact_fields); the email cannot be changed. Idempotent: sending the same values again converges on the same contact.",
+ idempotent: true,
+ },
+ props: {
+ contact_id: Property.ShortText({
+ displayName: 'Contact ID',
+ description: 'Numeric contact id, e.g. "12345".',
+ required: true,
+ }),
+ fields: Property.Array({
+ displayName: 'Fields',
+ description: 'Field values to set, e.g. [{"slug":"phone_number","value":"+15551234"}]. Use {"slug":"phone_number","value":null} to clear a field. Slugs you leave out are not touched.',
+ required: false,
+ properties: {
+ slug: Property.ShortText({ displayName: 'Slug', required: true }),
+ value: Property.ShortText({ displayName: 'Value', required: false }),
+ },
+ }),
+ locale: Property.ShortText({
+ displayName: 'Locale',
+ description: 'Optional new two-letter language code (en, fr, es, de, jp, dk, ua, ...). Omit to keep the current one.',
+ required: false,
+ }),
+ },
+ outputSchema: aiUpdateContactOutputSchema,
+ async run(context) {
+ const p = context.propsValue;
+ const contactId = systemeIoInput.requireId({ value: p.contact_id, name: 'contact_id' });
+ const fields = aiCommon.fieldsInput({ value: p.fields });
+ const locale = optionalLocale(p.locale);
+ if (fields.length === 0 && locale === undefined) {
+ throw new Error('Nothing to update: pass at least one field or a locale.');
+ }
+ const contact = await systemeIoCommon.apiCall<SystemeContact>({
+ method: HttpMethod.PATCH,
+ url: `/contacts/${contactId}`,
+ auth: context.auth.secret_text,
+ headers: { 'Content-Type': 'application/merge-patch+json' },
+ body: {
+ ...(fields.length > 0 ? { fields } : {}),
+ ...(locale !== undefined ? { locale } : {}),
+ },
+ });
+ return {
+ contact_id: contactId,
+ updated_slugs: fields.filter((f) => f.value !== null).map((f) => f.slug),
+ cleared_slugs: fields.filter((f) => f.value === null).map((f) => f.slug),
+ locale_changed: locale !== undefined,
+ contact,
+ };
+ },
+});
diff --git a/packages/pieces/community/systeme-io/src/lib/actions/cancel-subscription.ts b/packages/pieces/community/systeme-io/src/lib/actions/cancel-subscription.ts
new file mode 100644
index 00000000000..ec6ea595976
--- /dev/null
+++ b/packages/pieces/community/systeme-io/src/lib/actions/cancel-subscription.ts
@@ -0,0 +1,123 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { systemeIoAuth } from '../common/auth';
+import { apiErrorStatus, systemeIoCommon, systemeIoInput } from '../common/client';
+import { contactPicker, subscriptionDropdown } from '../common/dropdowns';
+import { cancelSubscriptionOutputSchema } from '../output-schemas';
+
+export const cancelSubscription = createAction({
+ auth: systemeIoAuth,
+ name: 'cancel_subscription',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Cancel Subscription',
+ description: "Cancel one of a contact's subscriptions, now or at the end of the billing period",
+ audience: 'both',
+ aiMetadata: {
+ description:
+ "Cancels a Systeme.io subscription, either immediately or when the current billing period ends (the default and safer choice). Needs the contact id and the subscription id; it first checks that the subscription belongs to that contact and cancels nothing otherwise. With the end-of-period option the subscription stays active until the period ends. Idempotent: a subscription that is already cancelled is reported with already_cancelled=true and not cancelled again; if Systeme.io refuses a repeat end-of-period cancel, the action converges when the subscription is already set to end.",
+ idempotent: true,
+ },
+ props: {
+ contact_id: contactPicker({ required: true }),
+ subscription_id: subscriptionDropdown,
+ cancel: Property.StaticDropdown({
+ displayName: 'When',
+ description: "'WhenBillingPeriodEnds' (default) keeps access until the paid period ends; 'Now' cancels immediately.",
+ required: true,
+ defaultValue: 'WhenBillingPeriodEnds',
+ options: {
+ disabled: false,
+ options: [
+ { label: 'At the end of the billing period', value: 'WhenBillingPeriodEnds' },
+ { label: 'Immediately', value: 'Now' },
+ ],
+ },
+ }),
+ },
+ outputSchema: cancelSubscriptionOutputSchema,
+ async run(context) {
+ const p = context.propsValue;
+ return cancel({
+ apiKey: context.auth.secret_text,
+ contactId: p.contact_id,
+ subscriptionId: p.subscription_id,
+ when: p.cancel,
+ });
+ },
+});
+
+async function cancel({
+ apiKey,
+ contactId,
+ subscriptionId,
+ when,
+}: {
+ apiKey: string;
+ contactId: unknown;
+ subscriptionId: unknown;
+ when: unknown;
+}) {
+ const contact = systemeIoInput.requireId({ value: contactId, name: 'Contact' });
+ const subscription = systemeIoInput.requireId({ value: subscriptionId, name: 'Subscription' });
+ if (when !== undefined && when !== null && when !== '' && when !== 'Now' && when !== 'WhenBillingPeriodEnds') {
+ throw new Error("When must be 'Now' or 'WhenBillingPeriodEnds'.");
+ }
+ const cancelType = when === 'Now' ? 'Now' : 'WhenBillingPeriodEnds';
+ const result = ({ already }: { already: boolean }) => ({
+ cancelled: true,
+ already_cancelled: already,
+ subscription_id: subscription,
+ contact_id: contact,
+ cancel_type: cancelType,
+ });
+ const current = await findSubscription({ apiKey, contact, subscription });
+ if (current.status === 'cancelled') {
+ return result({ already: true });
+ }
+ try {
+ await systemeIoCommon.apiCall({
+ method: HttpMethod.POST,
+ url: `/payment/subscriptions/${subscription}/cancel`,
+ auth: apiKey,
+ body: { cancel: cancelType },
+ });
+ return result({ already: false });
+ } catch (error) {
+ if (apiErrorStatus(error) !== 422) {
+ throw error;
+ }
+ const after = await findSubscription({ apiKey, contact, subscription }).catch(() => undefined);
+ if (after && isAlreadyCancelled({ row: after, cancelType })) {
+ return result({ already: true });
+ }
+ throw error;
+ }
+}
+
+async function findSubscription({ apiKey, contact, subscription }: { apiKey: string; contact: number; subscription: number }) {
+ const { items, hasMore } = await systemeIoCommon.paginate<Subscription>({
+ auth: apiKey,
+ url: '/payment/subscriptions',
+ query: { contact },
+ maxItems: 1000,
+ });
+ const row = items.find((item) => Number(item.id) === subscription);
+ if (row) {
+ return row;
+ }
+ throw new Error(
+ hasMore
+ ? `Subscription ${subscription} is not among the first 1,000 subscriptions of contact ${contact}, so it was not cancelled.`
+ : `Subscription ${subscription} does not belong to contact ${contact}, so nothing was cancelled. Pick one of the contact's subscriptions.`,
+ );
+}
+
+function isAlreadyCancelled({ row, cancelType }: { row: Subscription; cancelType: string }): boolean {
+ if (row.status === 'cancelled') {
+ return true;
+ }
+ const scheduled = row.status === 'active' && typeof row.cancelledAt === 'string' && row.cancelledAt !== '';
+ return scheduled && cancelType === 'WhenBillingPeriodEnds';
+}
+
+type Subscription = { id?: unknown; status?: string; cancelledAt?: string | null };
diff --git a/packages/pieces/community/systeme-io/src/lib/actions/create-contact.ts b/packages/pieces/community/systeme-io/src/lib/actions/create-contact.ts
index 0f317a10750..50955aa05f4 100644
--- a/packages/pieces/community/systeme-io/src/lib/actions/create-contact.ts
+++ b/packages/pieces/community/systeme-io/src/lib/actions/create-contact.ts
@@ -3,6 +3,7 @@ import { HttpMethod } from '@activepieces/pieces-common';
import { systemeIoAuth } from '../common/auth';
import { systemeIoCommon } from '../common/client';
import { systemeIoProps } from '../common/props';
+import { systemeIoAuthTagOptions } from '../common/dropdowns';
import { createContactActionOutputSchema } from '../output-schemas';
interface ContactField {
@@ -20,7 +21,7 @@ export const createContact = createAction({
classification: 'WRITE',
displayName: 'Create Contact',
description: 'Create a new contact with email and contact fields from your Systeme.io account, with optional tags',
- audience: 'both',
+ audience: 'human',
aiMetadata: { description: 'Creates a new contact in Systeme.io from an email plus optional locale and contact/custom fields, and can optionally tag it. Tags are controlled by a tag-source mode: none, assign existing tags by id, or create-and-assign new tags by name. Use to add someone to the CRM; each call creates a new contact and is not idempotent (repeating may produce duplicates or re-create tags). Requires an email.', idempotent: false },
props: {
email: Property.ShortText({
@@ -131,7 +132,8 @@ export const createContact = createAction({
description: 'Select existing tags to assign',
required: false,
refreshers: ['tagSource'],
- options: async ({ auth, tagSource }) => {
+ refreshOnSearch: true,
+ options: async ({ auth, tagSource }, ctx) => {
if (!auth || tagSource !== 'existing') {
return {
disabled: true,
@@ -142,44 +144,7 @@ export const createContact = createAction({
};
}
- try {
- const response = await systemeIoCommon.getTags({
- auth: auth.secret_text,
- });
-
- let tags: any[] = [];
- if (Array.isArray(response)) {
- tags = response;
- } else if (response && typeof response === 'object' && response !== null) {
- const responseAny = response as any;
- if (responseAny.items && Array.isArray(responseAny.items)) {
- tags = responseAny.items;
- }
- }
-
- if (tags.length > 0) {
- return {
- disabled: false,
- options: tags.map((tag: any) => ({
- label: tag.name || tag.id,
- value: tag.id,
- })),
- };
- }
-
- return {
- disabled: true,
- placeholder: 'No tags found',
- options: [],
- };
- } catch (error) {
- console.error('Error fetching tags:', error);
- return {
- disabled: true,
- placeholder: 'Error loading tags',
- options: [],
- };
- }
+ return systemeIoAuthTagOptions({ apiKey: auth.secret_text, searchValue: ctx?.searchValue });
},
}),
newTagNames: Property.Array({
diff --git a/packages/pieces/community/systeme-io/src/lib/actions/create-tag.ts b/packages/pieces/community/systeme-io/src/lib/actions/create-tag.ts
new file mode 100644
index 00000000000..1f2dd0ce3ae
--- /dev/null
+++ b/packages/pieces/community/systeme-io/src/lib/actions/create-tag.ts
@@ -0,0 +1,29 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { systemeIoAuth } from '../common/auth';
+import { systemeOps } from '../common/operations';
+import { createTagActionOutputSchema } from '../output-schemas';
+
+export const createTag = createAction({
+ auth: systemeIoAuth,
+ name: 'create_tag',
+ classification: 'WRITE',
+ displayName: 'Create Tag',
+ description: 'Create a tag, or return the existing tag with the same name',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Returns the Systeme.io tag with the given name, creating it only if no tag has that name (matched case-insensitively). Use to get a tag id before tagging contacts, without creating duplicates. Idempotent when calls run one after another: a repeat returns the same tag with created=false. Two calls at the same moment can both find no tag and both create one. Names are at most 64 characters.',
+ idempotent: true,
+ },
+ props: {
+ name: Property.ShortText({
+ displayName: 'Tag Name',
+ description: 'The tag name, up to 64 characters, e.g. "Webinar 2026 attendee".',
+ required: true,
+ }),
+ },
+ outputSchema: createTagActionOutputSchema,
+ async run(context) {
+ return systemeOps.getOrCreateTag({ apiKey: context.auth.secret_text, name: context.propsValue.name });
+ },
+});
diff --git a/packages/pieces/community/systeme-io/src/lib/actions/delete-contact.ts b/packages/pieces/community/systeme-io/src/lib/actions/delete-contact.ts
new file mode 100644
index 00000000000..5d96538034e
--- /dev/null
+++ b/packages/pieces/community/systeme-io/src/lib/actions/delete-contact.ts
@@ -0,0 +1,28 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { systemeIoAuth } from '../common/auth';
+import { systemeIoInput } from '../common/client';
+import { systemeOps } from '../common/operations';
+import { contactPicker } from '../common/dropdowns';
+import { deleteResultOutputSchema } from '../output-schemas';
+
+export const deleteContact = createAction({
+ auth: systemeIoAuth,
+ name: 'delete_contact',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Delete Contact',
+ description: 'Permanently delete a contact. This cannot be undone.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Permanently deletes a Systeme.io contact by id, including its tags, course enrollments and history; there is no trash or undo. Use only when the user explicitly asks to delete the contact; to stop emailing someone, remove a tag instead. Idempotent: deleting an already-deleted id returns not_found instead of failing.',
+ idempotent: true,
+ },
+ props: {
+ contact_id: contactPicker({ required: true }),
+ },
+ outputSchema: deleteResultOutputSchema,
+ async run(context) {
+ const id = systemeIoInput.requireId({ value: context.propsValue.contact_id, name: 'Contact' });
+ return systemeOps.deleteById({ apiKey: context.auth.secret_text, url: `/contacts/${id}`, id });
+ },
+});
diff --git a/packages/pieces/community/systeme-io/src/lib/actions/delete-tag.ts b/packages/pieces/community/systeme-io/src/lib/actions/delete-tag.ts
new file mode 100644
index 00000000000..d714e9a18fb
--- /dev/null
+++ b/packages/pieces/community/systeme-io/src/lib/actions/delete-tag.ts
@@ -0,0 +1,28 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { systemeIoAuth } from '../common/auth';
+import { systemeIoInput } from '../common/client';
+import { tagPicker } from '../common/dropdowns';
+import { deleteResultOutputSchema } from '../output-schemas';
+import { systemeOps } from '../common/operations';
+
+export const deleteTag = createAction({
+ auth: systemeIoAuth,
+ name: 'delete_tag',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Delete Tag',
+ description: 'Permanently delete a tag. It is removed from every contact that has it.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Permanently deletes a Systeme.io tag by id, which also removes it from every contact that has it and can break automations that use the tag. Use only when the tag itself should no longer exist; to untag one contact use Remove Tag from Contact. Idempotent: an already-deleted id returns not_found instead of failing.',
+ idempotent: true,
+ },
+ props: {
+ tag_id: tagPicker({ required: true }),
+ },
+ outputSchema: deleteResultOutputSchema,
+ async run(context) {
+ const id = systemeIoInput.requireId({ value: context.propsValue.tag_id, name: 'Tag' });
+ return systemeOps.deleteById({ apiKey: context.auth.secret_text, url: `/tags/${id}`, id });
+ },
+});
diff --git a/packages/pieces/community/systeme-io/src/lib/actions/enroll-contact-in-course.ts b/packages/pieces/community/systeme-io/src/lib/actions/enroll-contact-in-course.ts
new file mode 100644
index 00000000000..af64c95bedd
--- /dev/null
+++ b/packages/pieces/community/systeme-io/src/lib/actions/enroll-contact-in-course.ts
@@ -0,0 +1,77 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { systemeIoAuth } from '../common/auth';
+import { systemeIoCommon, systemeIoInput } from '../common/client';
+import { accessTypeDropdown, contactPicker, courseDropdown, courseModulesDropdown } from '../common/dropdowns';
+import { enrollmentRow } from '../common/mappers';
+import { enrollmentOutputSchema } from '../output-schemas';
+
+export const enrollContactInCourse = createAction({
+ auth: systemeIoAuth,
+ name: 'enroll_contact_in_course',
+ classification: 'WRITE',
+ displayName: 'Enroll Contact in Course',
+ description: 'Give a contact access to a course (full, partial, or drip-fed)',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ "Enrolls a Systeme.io contact in a course, giving full access, access to selected modules only, or drip-fed access. Use after a purchase or signup to grant course access; partial_access and partial_dripping_access require module ids from the course. Not idempotent: behaviour on a repeat enrollment is undocumented, so check the contact's enrollments first if unsure.",
+ idempotent: false,
+ },
+ props: {
+ course_id: courseDropdown,
+ contact_id: contactPicker({ required: true }),
+ access_type: accessTypeDropdown,
+ modules: courseModulesDropdown,
+ },
+ outputSchema: enrollmentOutputSchema,
+ async run(context) {
+ const p = context.propsValue;
+ return enroll({
+ apiKey: context.auth.secret_text,
+ courseId: p.course_id,
+ contactId: p.contact_id,
+ accessType: p.access_type,
+ modules: p.modules,
+ });
+ },
+});
+
+async function enroll({
+ apiKey,
+ courseId,
+ contactId,
+ accessType,
+ modules,
+}: {
+ apiKey: string;
+ courseId: unknown;
+ contactId: unknown;
+ accessType: unknown;
+ modules: unknown;
+}) {
+ const course = systemeIoInput.requireId({ value: courseId, name: 'Course' });
+ const contact = systemeIoInput.requireId({ value: contactId, name: 'Contact' });
+ const access = String(accessType ?? 'full_access');
+ if (!ACCESS_TYPES.includes(access)) {
+ throw new Error(`Access type must be one of: ${ACCESS_TYPES.join(', ')}.`);
+ }
+ const partial = access === 'partial_access' || access === 'partial_dripping_access';
+ const moduleIds = partial ? systemeIoInput.idList({ value: modules, name: 'Module' }) : [];
+ if (partial && moduleIds.length === 0) {
+ throw new Error(`Access type "${access}" needs at least one module.`);
+ }
+ const enrollment = await systemeIoCommon.apiCall<unknown>({
+ method: HttpMethod.POST,
+ url: `/school/courses/${course}/enrollments`,
+ auth: apiKey,
+ body: {
+ contactId: contact,
+ accessType: access,
+ ...(partial ? { modules: moduleIds } : {}),
+ },
+ });
+ return enrollmentRow(enrollment);
+}
+
+const ACCESS_TYPES = ['full_access', 'partial_access', 'dripping_content', 'partial_dripping_access'];
diff --git a/packages/pieces/community/systeme-io/src/lib/actions/find-contact-by-email.ts b/packages/pieces/community/systeme-io/src/lib/actions/find-contact-by-email.ts
index 44a5e43f02a..272fb18db9a 100644
--- a/packages/pieces/community/systeme-io/src/lib/actions/find-contact-by-email.ts
+++ b/packages/pieces/community/systeme-io/src/lib/actions/find-contact-by-email.ts
@@ -10,7 +10,7 @@ export const findContactByEmail = createAction({
displayName: 'Find Contact by Email',
description: 'Locate an existing contact by email address',
audience: 'both',
- aiMetadata: { description: 'Looks up a single Systeme.io contact by exact email address by paging through all contacts and matching case-insensitively. Use to resolve an email to a contact record (e.g. to get its id before tagging or updating). Read-only and idempotent; returns a not-found result if no contact matches.', idempotent: true },
+ aiMetadata: { description: 'Looks up a single Systeme.io contact by exact email address (case-insensitive) using the API email filter. Use to resolve an email to a contact record (e.g. to get its id before tagging or updating). Read-only and idempotent; returns a not-found result if no contact matches.', idempotent: true },
props: {
email: Property.ShortText({
displayName: 'Email',
@@ -21,45 +21,14 @@ export const findContactByEmail = createAction({
outputSchema: findContactByEmailActionOutputSchema,
async run(context) {
const { email } = context.propsValue;
- const searchEmail = email.toLowerCase().trim();
-
- const allContacts: any[] = [];
- let hasMore = true;
- let startingAfter: string | undefined;
-
- while (hasMore) {
- const response = await systemeIoCommon.getContacts({
- auth: context.auth.secret_text,
- limit: 100,
- startingAfter,
- });
-
- let contacts: any[] = [];
- let nextHasMore = false;
-
- if (Array.isArray(response)) {
- contacts = response;
- } else if (response && typeof response === 'object' && response !== null) {
- const responseAny = response as any;
- if (responseAny.items && Array.isArray(responseAny.items)) {
- contacts = responseAny.items;
- }
- nextHasMore = responseAny.hasMore || false;
- }
-
- allContacts.push(...contacts);
-
- if (nextHasMore && contacts.length > 0) {
- startingAfter = contacts[contacts.length - 1].id?.toString();
- } else {
- hasMore = false;
- }
- }
-
- const foundContact = allContacts.find(contact =>
- contact.email && contact.email.toLowerCase().trim() === searchEmail
- );
-
+ const trimmed = email.trim();
+ const searchEmail = trimmed.toLowerCase();
+ const auth = context.auth.secret_text;
+ const matches = (contact: { email?: string }) =>
+ typeof contact.email === 'string' && contact.email.toLowerCase().trim() === searchEmail;
+
+ const foundContact = (await systemeIoCommon.findContactsByEmail({ auth, email: trimmed })).find(matches);
+
if (foundContact) {
return {
success: true,
diff --git a/packages/pieces/community/systeme-io/src/lib/actions/find-contacts.ts b/packages/pieces/community/systeme-io/src/lib/actions/find-contacts.ts
new file mode 100644
index 00000000000..f9d37fe75fa
--- /dev/null
+++ b/packages/pieces/community/systeme-io/src/lib/actions/find-contacts.ts
@@ -0,0 +1,120 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { systemeIoAuth } from '../common/auth';
+import { SystemeContact, systemeIoCommon, systemeIoInput } from '../common/client';
+import { systemeIoAuthTagOptions } from '../common/dropdowns';
+import { findContactsActionOutputSchema } from '../output-schemas';
+
+export const findContacts = createAction({
+ auth: systemeIoAuth,
+ name: 'find_contacts',
+ classification: 'SEARCH',
+ displayName: 'Find Contacts',
+ description: 'Search contacts by email, tags, sign-up date or status',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Lists Systeme.io contacts matching optional filters: email (exact, case-insensitive), tag ids (contacts must have all of them), a registration date range, and unsubscribed/bounced/needs-confirmation status; with no filters it lists every contact, newest first (Systeme.io ignores any other order). Use to build a segment or check who matches before tagging or enrolling; use Find Contact by Email for a single lookup. Pages automatically up to Max Results and returns a cursor to continue. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ email: Property.ShortText({
+ displayName: 'Email',
+ description: 'Optional email address, matched exactly but ignoring case, e.g. "[email protected]".',
+ required: false,
+ }),
+ tag_ids: Property.MultiSelectDropdown({
+ auth: systemeIoAuth,
+ displayName: 'Has All Tags',
+ description: 'Optional. Only contacts that have every selected tag. Agents can pass numeric tag ids.',
+ required: false,
+ refreshers: [],
+ refreshOnSearch: true,
+ options: async ({ auth }, ctx) => systemeIoAuthTagOptions({ apiKey: auth?.secret_text, searchValue: ctx?.searchValue }),
+ }),
+ registered_after: Property.DateTime({
+ displayName: 'Registered After',
+ description: 'Optional ISO 8601 date-time, e.g. "2026-01-01T00:00:00Z".',
+ required: false,
+ }),
+ registered_before: Property.DateTime({
+ displayName: 'Registered Before',
+ description: 'Optional ISO 8601 date-time, e.g. "2026-02-01T00:00:00Z".',
+ required: false,
+ }),
+ unsubscribed: statusFilter({ displayName: 'Unsubscribed', yes: 'unsubscribed from emails', no: 'still subscribed to emails' }),
+ bounced: statusFilter({ displayName: 'Bounced', yes: 'whose emails bounced', no: 'whose emails did not bounce' }),
+ needs_confirmation: statusFilter({
+ displayName: 'Needs Confirmation',
+ yes: 'who still have to confirm their opt-in',
+ no: 'who do not need to confirm their opt-in',
+ }),
+ max_results: Property.Number({
+ displayName: 'Max Results',
+ description: 'How many contacts to return at most (1-1000). Default 100.',
+ required: false,
+ defaultValue: 100,
+ }),
+ starting_after: Property.ShortText({
+ displayName: 'Continue After (cursor)',
+ description: 'Optional. The Next Cursor value from a previous run, to fetch the following contacts.',
+ required: false,
+ }),
+ },
+ outputSchema: findContactsActionOutputSchema,
+ async run(context) {
+ const p = context.propsValue;
+ const maxResults = systemeIoInput.clampInt({ value: p.max_results, name: 'Max Results', min: 1, max: 1000, fallback: 100 });
+ const tagIds = systemeIoInput.idList({ value: p.tag_ids, name: 'Tag ID' });
+ const page = await systemeIoCommon.paginate<SystemeContact>({
+ auth: context.auth.secret_text,
+ url: '/contacts',
+ maxItems: maxResults,
+ startingAfter: systemeIoInput.optionalId({ value: p.starting_after, name: 'Continue After' }),
+ query: {
+ email: p.email?.trim() || undefined,
+ tags: tagIds.length > 0 ? tagIds.join(',') : undefined,
+ registeredAfter: isoOrUndefined({ value: p.registered_after, name: 'Registered After' }),
+ registeredBefore: isoOrUndefined({ value: p.registered_before, name: 'Registered Before' }),
+ unsubscribed: triState(p.unsubscribed),
+ bounced: triState(p.bounced),
+ needsConfirmation: triState(p.needs_confirmation),
+ },
+ });
+ return {
+ contacts: page.items,
+ count: page.items.length,
+ has_more: page.hasMore,
+ next_cursor: page.nextCursor,
+ };
+ },
+});
+
+function statusFilter({ displayName, yes, no }: { displayName: string; yes: string; no: string }) {
+ return Property.StaticDropdown({
+ displayName,
+ description: `Optional. Yes: only contacts ${yes}. No: only contacts ${no}. Leave empty for both.`,
+ required: false,
+ options: {
+ disabled: false,
+ options: [
+ { label: 'Yes', value: 'yes' },
+ { label: 'No', value: 'no' },
+ ],
+ },
+ });
+}
+
+function triState(value: unknown): string | undefined {
+ if (value === 'yes' || value === true || value === 'true') return 'true';
+ if (value === 'no' || value === false || value === 'false') return 'false';
+ return undefined;
+}
+
+function isoOrUndefined({ value, name }: { value: unknown; name: string }): string | undefined {
+ if (value === undefined || value === null || value === '') return undefined;
+ const date = new Date(String(value));
+ if (Number.isNaN(date.getTime())) {
+ throw new Error(`${name} must be an ISO 8601 date-time, e.g. "2026-01-01T00:00:00Z".`);
+ }
+ return date.toISOString();
+}
diff --git a/packages/pieces/community/systeme-io/src/lib/actions/get-contact.ts b/packages/pieces/community/systeme-io/src/lib/actions/get-contact.ts
new file mode 100644
index 00000000000..1530e1621b3
--- /dev/null
+++ b/packages/pieces/community/systeme-io/src/lib/actions/get-contact.ts
@@ -0,0 +1,32 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { systemeIoAuth } from '../common/auth';
+import { SystemeContact, systemeIoCommon, systemeIoInput } from '../common/client';
+import { contactPicker } from '../common/dropdowns';
+import { getContactActionOutputSchema } from '../output-schemas';
+
+export const getContact = createAction({
+ auth: systemeIoAuth,
+ name: 'get_contact',
+ classification: 'READ',
+ displayName: 'Get Contact',
+ description: 'Get a contact with its fields and tags',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Retrieves one Systeme.io contact by its numeric id, including all contact field values and assigned tags. Use when you already have the contact id (from a trigger or a search); use Find Contact by Email when you only have the email. Read-only and idempotent; fails with a not-found error for an unknown id.',
+ idempotent: true,
+ },
+ props: {
+ contact_id: contactPicker({ required: true }),
+ },
+ outputSchema: getContactActionOutputSchema,
+ async run(context) {
+ const contactId = systemeIoInput.requireId({ value: context.propsValue.contact_id, name: 'Contact' });
+ return systemeIoCommon.apiCall<SystemeContact>({
+ method: HttpMethod.GET,
+ url: `/contacts/${contactId}`,
+ auth: context.auth.secret_text,
+ });
+ },
+});
diff --git a/packages/pieces/community/systeme-io/src/lib/actions/remove-contact-from-community.ts b/packages/pieces/community/systeme-io/src/lib/actions/remove-contact-from-community.ts
new file mode 100644
index 00000000000..1a90b852d36
--- /dev/null
+++ b/packages/pieces/community/systeme-io/src/lib/actions/remove-contact-from-community.ts
@@ -0,0 +1,38 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { systemeIoAuth } from '../common/auth';
+import { systemeIoInput } from '../common/client';
+import { communityDropdown, contactPicker } from '../common/dropdowns';
+import { systemeOps } from '../common/operations';
+import { removalResultOutputSchema } from '../output-schemas';
+
+export const removeContactFromCommunity = createAction({
+ auth: systemeIoAuth,
+ name: 'remove_contact_from_community',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Remove Contact from Community',
+ description: "Remove a contact's membership of a community",
+ audience: 'both',
+ aiMetadata: {
+ description:
+ "Removes a Systeme.io contact from a community by deleting their membership; the contact and community stay. Use to revoke community access after a refund or cancellation. Idempotent: if the contact is not a member it returns not_found=true and changes nothing.",
+ idempotent: true,
+ },
+ props: {
+ community_id: communityDropdown,
+ contact_id: contactPicker({ required: true }),
+ },
+ outputSchema: removalResultOutputSchema,
+ async run(context) {
+ const communityId = systemeIoInput.requireId({ value: context.propsValue.community_id, name: 'Community' });
+ const contactId = systemeIoInput.requireId({ value: context.propsValue.contact_id, name: 'Contact' });
+ return systemeOps.removeMatching<Membership>({
+ apiKey: context.auth.secret_text,
+ listUrl: '/community/memberships',
+ query: { community: communityId, contact: contactId },
+ matches: (row) => Number(row.community?.id) === communityId && Number(row.contact?.id) === contactId,
+ deleteUrl: (id) => `/community/memberships/${id}`,
+ });
+ },
+});
+
+type Membership = { id?: unknown; community?: { id?: unknown }; contact?: { id?: unknown } };
diff --git a/packages/pieces/community/systeme-io/src/lib/actions/remove-course-enrollment.ts b/packages/pieces/community/systeme-io/src/lib/actions/remove-course-enrollment.ts
new file mode 100644
index 00000000000..021c83b130b
--- /dev/null
+++ b/packages/pieces/community/systeme-io/src/lib/actions/remove-course-enrollment.ts
@@ -0,0 +1,38 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { systemeIoAuth } from '../common/auth';
+import { systemeIoInput } from '../common/client';
+import { contactPicker, courseDropdown } from '../common/dropdowns';
+import { systemeOps } from '../common/operations';
+import { removalResultOutputSchema } from '../output-schemas';
+
+export const removeCourseEnrollment = createAction({
+ auth: systemeIoAuth,
+ name: 'remove_course_enrollment',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Remove Course Access',
+ description: "Remove a contact's enrollment in a course",
+ audience: 'both',
+ aiMetadata: {
+ description:
+ "Removes a Systeme.io contact's access to a course by deleting their enrollment(s) in it; the contact and course stay. Use to revoke access after a refund or cancellation. Idempotent: if the contact is not enrolled it returns not_found=true and changes nothing.",
+ idempotent: true,
+ },
+ props: {
+ course_id: courseDropdown,
+ contact_id: contactPicker({ required: true }),
+ },
+ outputSchema: removalResultOutputSchema,
+ async run(context) {
+ const courseId = systemeIoInput.requireId({ value: context.propsValue.course_id, name: 'Course' });
+ const contactId = systemeIoInput.requireId({ value: context.propsValue.contact_id, name: 'Contact' });
+ return systemeOps.removeMatching<Enrollment>({
+ apiKey: context.auth.secret_text,
+ listUrl: '/school/enrollments',
+ query: { course: courseId, contact: contactId },
+ matches: (row) => Number(row.course?.id) === courseId && Number(row.contact?.id) === contactId,
+ deleteUrl: (id) => `/school/enrollments/${id}`,
+ });
+ },
+});
+
+type Enrollment = { id?: unknown; course?: { id?: unknown }; contact?: { id?: unknown } };
diff --git a/packages/pieces/community/systeme-io/src/lib/actions/remove-tag-from-contact.ts b/packages/pieces/community/systeme-io/src/lib/actions/remove-tag-from-contact.ts
index 669e843ff9a..5da6589015f 100644
--- a/packages/pieces/community/systeme-io/src/lib/actions/remove-tag-from-contact.ts
+++ b/packages/pieces/community/systeme-io/src/lib/actions/remove-tag-from-contact.ts
@@ -1,7 +1,7 @@
import { createAction, Property } from '@activepieces/pieces-framework';
import { HttpMethod } from '@activepieces/pieces-common';
import { systemeIoAuth } from '../common/auth';
-import { systemeIoCommon } from '../common/client';
+import { systemeIoCommon, systemeIoInput } from '../common/client';
import { systemeIoProps } from '../common/props';
import { removeTagFromContactActionOutputSchema } from '../output-schemas';
@@ -78,11 +78,13 @@ export const removeTagFromContact = createAction({
outputSchema: removeTagFromContactActionOutputSchema,
async run(context) {
const { contactId, tagId } = context.propsValue;
+ const contact = systemeIoInput.requireId({ value: contactId, name: 'Contact ID' });
+ const tag = systemeIoInput.requireId({ value: tagId, name: 'Tag ID' });
let tagName = 'Unknown Tag';
try {
const contact = await systemeIoCommon.getContact({
- contactId: contactId as string,
+ contactId,
auth: context.auth.secret_text,
});
@@ -99,7 +101,7 @@ export const removeTagFromContact = createAction({
const response = await systemeIoCommon.apiCall({
method: HttpMethod.DELETE,
- url: `/contacts/${contactId}/tags/${tagId}`,
+ url: `/contacts/${contact}/tags/${tag}`,
auth: context.auth.secret_text,
});
diff --git a/packages/pieces/community/systeme-io/src/lib/actions/update-contact.ts b/packages/pieces/community/systeme-io/src/lib/actions/update-contact.ts
index b6338717e47..1472b72675c 100644
--- a/packages/pieces/community/systeme-io/src/lib/actions/update-contact.ts
+++ b/packages/pieces/community/systeme-io/src/lib/actions/update-contact.ts
@@ -1,14 +1,10 @@
-import { createAction, Property } from '@activepieces/pieces-framework';
+import { createAction, InputPropertyMap, Property } from '@activepieces/pieces-framework';
import { HttpMethod } from '@activepieces/pieces-common';
import { systemeIoAuth } from '../common/auth';
-import { systemeIoCommon } from '../common/client';
+import { systemeIoCommon, systemeIoInput } from '../common/client';
import { systemeIoProps } from '../common/props';
import { updateContactActionOutputSchema } from '../output-schemas';
-
-interface ContactFieldUpdate {
- field: string;
- value: string;
-}
+import { contactLocaleOptions, optionalLocale } from '../common/dropdowns';
export const updateContact = createAction({
auth: systemeIoAuth,
@@ -16,8 +12,8 @@ export const updateContact = createAction({
classification: 'WRITE',
displayName: 'Update Contact',
description: 'Update fields (name, phone, custom fields) of an existing contact using fields from your Systeme.io account',
- audience: 'both',
- aiMetadata: { description: 'Updates fields of an existing Systeme.io contact, identified by contact id, via a partial merge-patch of standard, account-defined, and manually-keyed custom fields (an empty value clears a field). Use to change a known contact\'s data such as name, phone, or custom attributes. Idempotent: applying the same field values yields the same result; only the provided fields are touched, and a call with no fields makes no change.', idempotent: true },
+ audience: 'human',
+ aiMetadata: { description: 'Updates fields of an existing Systeme.io contact, identified by contact id, via a partial merge-patch of standard, account-defined, and manually-keyed custom fields (an empty value clears a field), plus an optional language change. Use to change a known contact\'s data such as name, phone, or custom attributes. Idempotent: applying the same field values yields the same result; only the provided fields are touched, and a call with no fields makes no change.', idempotent: true },
props: {
contactId: systemeIoProps.contactIdDropdown,
dynamicContactFields: Property.DynamicProperties({
@@ -36,19 +32,9 @@ export const updateContact = createAction({
auth: auth.secret_text,
});
- let fields: any[] = [];
- if (Array.isArray(response)) {
- fields = response;
- } else if (response && typeof response === 'object' && response !== null) {
- const responseAny = response as any;
- if (responseAny.items && Array.isArray(responseAny.items)) {
- fields = responseAny.items;
- }
- }
-
- const dynamicProps: any = {};
+ const dynamicProps: InputPropertyMap = {};
- for (const field of fields) {
+ for (const field of contactFieldsOf(response)) {
dynamicProps[field.slug] = Property.ShortText({
displayName: field.fieldName || field.slug,
description: `Update ${field.fieldName || field.slug} (leave empty to keep current value)`,
@@ -80,19 +66,29 @@ export const updateContact = createAction({
}),
},
}),
+ locale: Property.StaticDropdown({
+ displayName: 'Language',
+ description: 'Optional. Change the contact\'s preferred language. Leave empty to keep the current language.',
+ required: false,
+ options: {
+ disabled: false,
+ options: contactLocaleOptions,
+ },
+ }),
},
outputSchema: updateContactActionOutputSchema,
async run(context) {
const {
contactId,
dynamicContactFields,
- customFields
+ customFields,
+ locale,
} = context.propsValue;
- const fields: any[] = [];
+ const fields: { slug: string; value: string | null }[] = [];
if (dynamicContactFields && typeof dynamicContactFields === 'object') {
- const fieldsObj = dynamicContactFields as Record<string, any>;
+ const fieldsObj: Record<string, unknown> = dynamicContactFields;
for (const key in fieldsObj) {
if (Object.prototype.hasOwnProperty.call(fieldsObj, key)) {
const value = fieldsObj[key];
@@ -107,18 +103,23 @@ export const updateContact = createAction({
}
if (customFields && Array.isArray(customFields)) {
- for (const customField of customFields as any[]) {
- if (customField.fieldSlug) {
+ for (const customField of customFields) {
+ const slug: unknown = isRecord(customField) ? customField['fieldSlug'] : undefined;
+ const fieldValue: unknown = isRecord(customField) ? customField['fieldValue'] : undefined;
+ if (typeof slug === 'string' && slug !== '') {
fields.push({
- slug: customField.fieldSlug,
- value: customField.fieldValue || null
+ slug,
+ value: fieldValue ? String(fieldValue) : null
});
}
}
}
- const updateData: any = {};
- if (fields.length > 0) updateData.fields = fields;
+ const localeValue = optionalLocale(locale);
+ const updateData = {
+ ...(fields.length > 0 ? { fields } : {}),
+ ...(localeValue !== undefined ? { locale: localeValue } : {}),
+ };
if (Object.keys(updateData).length === 0) {
return {
@@ -130,7 +131,7 @@ export const updateContact = createAction({
const response = await systemeIoCommon.apiCall({
method: HttpMethod.PATCH,
- url: `/contacts/${contactId}`,
+ url: `/contacts/${systemeIoInput.requireId({ value: contactId, name: 'Contact ID' })}`,
body: updateData,
auth: context.auth.secret_text,
headers: {
@@ -152,3 +153,21 @@ export const updateContact = createAction({
};
},
});
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
+}
+
+function contactFieldsOf(response: unknown): { slug: string; fieldName?: string }[] {
+ const items: unknown = Array.isArray(response) ? response : isRecord(response) ? response['items'] : undefined;
+ if (!Array.isArray(items)) {
+ return [];
+ }
+ return items.flatMap((item: unknown) => {
+ if (!isRecord(item) || typeof item['slug'] !== 'string') {
+ return [];
+ }
+ const fieldName = item['fieldName'];
+ return [{ slug: item['slug'], fieldName: typeof fieldName === 'string' ? fieldName : undefined }];
+ });
+}
diff --git a/packages/pieces/community/systeme-io/src/lib/common/auth.ts b/packages/pieces/community/systeme-io/src/lib/common/auth.ts
index ffabc2710c3..1b0585d178f 100644
--- a/packages/pieces/community/systeme-io/src/lib/common/auth.ts
+++ b/packages/pieces/community/systeme-io/src/lib/common/auth.ts
@@ -1,10 +1,11 @@
import { PieceAuth } from '@activepieces/pieces-framework';
import { HttpMethod } from '@activepieces/pieces-common';
-import { systemeIoCommon } from './client';
+import { apiErrorStatus, systemeIoCommon } from './client';
export const systemeIoAuth = PieceAuth.SecretText({
displayName: 'API Key',
- description: 'Your Systeme.io API key. You can find this in your Systeme.io dashboard under Profile Settings > Public API Keys.',
+ description:
+ 'Your Systeme.io API key. In your Systeme.io dashboard open Profile > **MCP & API keys** (systeme.io/dashboard/profile/public-api-settings), create a key and paste it here.',
required: true,
validate: async ({ auth }) => {
try {
@@ -18,17 +19,19 @@ export const systemeIoAuth = PieceAuth.SecretText({
valid: true,
message: 'API key validated successfully. Connected to Systeme.io.'
};
- } catch (error: any) {
- if (error.message.includes('401') || error.message.includes('403')) {
+ } catch (error: unknown) {
+ const status = apiErrorStatus(error);
+ if (status === 401 || status === 403) {
return {
valid: false,
error: 'Invalid API key. Please check your API key and try again.',
};
}
+ const message = error instanceof Error ? error.message : String(error);
return {
valid: false,
- error: `Authentication failed: ${error.message}. Please verify your API key is correct.`,
+ error: `Authentication failed: ${message.replace(/[.!?]+\s*$/, '')}. Please verify your API key is correct.`,
};
}
},
diff --git a/packages/pieces/community/systeme-io/src/lib/common/client.ts b/packages/pieces/community/systeme-io/src/lib/common/client.ts
index 855565bb8ae..d16f1966918 100644
--- a/packages/pieces/community/systeme-io/src/lib/common/client.ts
+++ b/packages/pieces/community/systeme-io/src/lib/common/client.ts
@@ -1,61 +1,371 @@
import { httpClient, HttpMethod } from '@activepieces/pieces-common';
import crypto from 'crypto';
+type SystemeAuth = string | { apiKey: string };
+
+type QueryValue = string | number | boolean | undefined | null;
+
+class SystemeIoApiError extends Error {
+ readonly status: number | undefined;
+ readonly responseBody: unknown;
+
+ constructor({ message, status, body }: { message: string; status?: number; body?: unknown }) {
+ super(message);
+ this.name = 'SystemeIoApiError';
+ this.status = status;
+ this.responseBody = body;
+ }
+}
+
+function responseOf(error: unknown): { status?: number; body?: unknown } | undefined {
+ if (typeof error !== 'object' || error === null) {
+ return undefined;
+ }
+ const response: unknown = Reflect.get(error, 'response');
+ if (typeof response !== 'object' || response === null) {
+ return undefined;
+ }
+ const status: unknown = Reflect.get(response, 'status');
+ return {
+ status: typeof status === 'number' ? status : undefined,
+ body: Reflect.get(response, 'body'),
+ };
+}
+
+function vendorDetail(body: unknown): string | undefined {
+ let parsed: unknown = body;
+ if (typeof body === 'string') {
+ try {
+ parsed = JSON.parse(body);
+ } catch {
+ return body.trim() === '' ? undefined : body.slice(0, 500);
+ }
+ }
+ if (typeof parsed !== 'object' || parsed === null) {
+ return undefined;
+ }
+ const violations: unknown = Reflect.get(parsed, 'violations');
+ if (Array.isArray(violations) && violations.length > 0) {
+ const parts = violations
+ .map((v: unknown) => {
+ if (typeof v !== 'object' || v === null) return undefined;
+ const path: unknown = Reflect.get(v, 'propertyPath');
+ const message: unknown = Reflect.get(v, 'message');
+ if (typeof message !== 'string') return undefined;
+ return typeof path === 'string' && path !== '' ? `${path}: ${message}` : message;
+ })
+ .filter((p): p is string => typeof p === 'string');
+ if (parts.length > 0) {
+ return parts.join('; ');
+ }
+ }
+ const detail: unknown = Reflect.get(parsed, 'detail');
+ if (typeof detail === 'string' && detail !== '') {
+ return detail;
+ }
+ const message: unknown = Reflect.get(parsed, 'message');
+ if (typeof message === 'string' && message !== '') {
+ return message;
+ }
+ const title: unknown = Reflect.get(parsed, 'title');
+ return typeof title === 'string' && title !== '' ? title : undefined;
+}
+
+function toApiError(error: unknown): Error {
+ const response = responseOf(error);
+ if (!response || response.status === undefined) {
+ return error instanceof Error ? error : new Error(String(error));
+ }
+ const status = response.status;
+ const detail = vendorDetail(response.body);
+ let hint = '';
+ if (status === 401) {
+ hint = ' Check that the API key is valid (Dashboard > Profile > MCP & API keys).';
+ } else if (status === 403) {
+ hint = ' This API key may not access this record or feature; check the id and your Systeme.io plan.';
+ } else if (status === 404) {
+ hint = ' The record was not found; check the id.';
+ } else if (status === 429) {
+ hint = ' Rate limited by Systeme.io (the quota is shared across all API keys); retry later.';
+ }
+ const text = `Systeme.io API error ${status}${detail ? `: ${detail}` : ''}`;
+ return new SystemeIoApiError({
+ message: `${/[.!?]$/.test(text) ? text : `${text}.`}${hint}`,
+ status,
+ body: response.body,
+ });
+}
+
+export function apiErrorStatus(error: unknown): number | undefined {
+ if (error instanceof SystemeIoApiError) {
+ return error.status;
+ }
+ if (typeof error === 'object' && error !== null) {
+ const status: unknown = Reflect.get(error, 'status');
+ if (typeof status === 'number') {
+ return status;
+ }
+ }
+ return responseOf(error)?.status;
+}
+
+function requireId({ value, name }: { value: unknown; name: string }): number {
+ const raw = typeof value === 'number' ? String(value) : typeof value === 'string' ? value.trim() : '';
+ const id = /^[1-9]\d*$/.test(raw) ? Number(raw) : NaN;
+ if (!Number.isSafeInteger(id)) {
+ throw new Error(`${name} must be a positive whole number (a Systeme.io id), got "${String(value ?? '')}".`);
+ }
+ return id;
+}
+
+function optionalId({ value, name }: { value: unknown; name: string }): number | undefined {
+ if (value === undefined || value === null || value === '') {
+ return undefined;
+ }
+ return requireId({ value, name });
+}
+
+function idList({ value, name }: { value: unknown; name: string }): number[] {
+ if (value === undefined || value === null || value === '') {
+ return [];
+ }
+ if (!Array.isArray(value)) {
+ throw new Error(`${name} must be a list of ids.`);
+ }
+ return value.map((item: unknown) => requireId({ value: item, name }));
+}
+
+function clampInt({ value, name, min, max, fallback }: { value: unknown; name: string; min: number; max: number; fallback: number }): number {
+ if (value === undefined || value === null || value === '') {
+ return fallback;
+ }
+ const parsed = typeof value === 'number' ? value : Number(value);
+ if (!Number.isInteger(parsed) || parsed < min || parsed > max) {
+ throw new Error(`${name} must be a whole number between ${min} and ${max}.`);
+ }
+ return parsed;
+}
+
+function phpJsonEncode(value: unknown): string {
+ const json = JSON.stringify(value);
+ let out = '';
+ for (let i = 0; i < json.length; i++) {
+ const ch = json[i];
+ const code = json.charCodeAt(i);
+ if (ch === '/') {
+ out += '\\/';
+ } else if (code > 0x7f) {
+ out += '\\u' + code.toString(16).padStart(4, '0');
+ } else {
+ out += ch;
+ }
+ }
+ return out;
+}
+
+function signatureCandidates(rawBody: unknown): string[] {
+ const candidates: string[] = [];
+ let text: string | undefined;
+ if (typeof rawBody === 'string') {
+ text = rawBody;
+ } else if (Buffer.isBuffer(rawBody)) {
+ text = rawBody.toString('utf8');
+ }
+ if (text !== undefined && text !== '') {
+ candidates.push(text);
+ try {
+ const normalized = phpJsonEncode(JSON.parse(text));
+ if (normalized !== text) {
+ candidates.push(normalized);
+ }
+ } catch {
+ return candidates;
+ }
+ } else if (typeof rawBody === 'object' && rawBody !== null) {
+ candidates.push(phpJsonEncode(rawBody));
+ }
+ return candidates;
+}
+
+function hmacMatches({ secret, input, signature }: { secret: string; input: string; signature: string }): boolean {
+ const expected = crypto.createHmac('sha256', secret).update(input, 'utf8').digest('hex');
+ const given = signature.trim().toLowerCase();
+ if (!/^[0-9a-f]+$/.test(given) || given.length !== expected.length) {
+ return false;
+ }
+ return crypto.timingSafeEqual(Buffer.from(given, 'hex'), Buffer.from(expected, 'hex'));
+}
+
+function webhookOwner({ webhookUrl }: { webhookUrl: string }): string {
+ let parts: string[] = [];
+ try {
+ parts = new URL(webhookUrl).pathname.split('/').filter((part) => part !== '');
+ } catch {
+ parts = [];
+ }
+ const at = parts.lastIndexOf('webhooks');
+ const owner = (at >= 0 ? parts.slice(at + 1) : []).join('-');
+ if (/^[A-Za-z0-9_-]{1,80}$/.test(owner)) {
+ return owner;
+ }
+ return crypto.createHash('sha256').update(webhookUrl, 'utf8').digest('hex').slice(0, 16);
+}
+
+function webhookName({ eventType, webhookUrl }: { eventType: string; webhookUrl: string }): string {
+ return `Activepieces Webhook - ${eventType} - ${webhookOwner({ webhookUrl })}`;
+}
+
+const PAGE_SIZE_FALLBACKS = [50, 20, 10];
+
+const WEBHOOK_SCHEMA_VERSIONS: Record<string, number> = {
+ CONTACT_CREATED: 1,
+ CONTACT_TAG_ADDED: 1,
+ CONTACT_TAG_REMOVED: 1,
+ CONTACT_OPT_IN: 1,
+ SALE_NEW: 2,
+ SALE_CANCELED: 2,
+};
+
+function webhookSchemaVersion({ eventType }: { eventType: string }): number {
+ const version = WEBHOOK_SCHEMA_VERSIONS[eventType];
+ if (version === undefined) {
+ throw new Error(`Unknown Systeme.io webhook event ${eventType}.`);
+ }
+ return version;
+}
+
+function isPageLimitRejection(error: unknown): boolean {
+ if (apiErrorStatus(error) !== 422) {
+ return false;
+ }
+ const body = error instanceof SystemeIoApiError ? error.responseBody : responseOf(error)?.body;
+ const text = typeof body === 'string' ? body : JSON.stringify(body ?? '');
+ return text.includes('pagination.limit');
+}
+
export const systemeIoCommon = {
baseUrl: 'https://api.systeme.io/api',
+ webhookName,
+
async apiCall<T>({
method,
url,
body,
auth,
headers,
+ queryParams,
}: {
method: HttpMethod;
url: string;
- body?: any;
- auth: string | { apiKey: string };
+ body?: unknown;
+ auth: SystemeAuth;
headers?: Record<string, string>;
+ queryParams?: Record<string, QueryValue>;
}): Promise<T> {
const apiKey = typeof auth === 'string' ? auth : auth.apiKey;
-
- const response = await httpClient.sendRequest<T>({
- method,
- url: `${this.baseUrl}${url}`,
- headers: {
- 'X-API-Key': apiKey,
- 'Content-Type': 'application/json',
- ...headers,
- },
- body,
- });
- if (response.status >= 400) {
- throw new Error(`Systeme.io API error: ${response.status}`);
+ const query: Record<string, string> = {};
+ for (const [key, value] of Object.entries(queryParams ?? {})) {
+ if (value !== undefined && value !== null && value !== '') {
+ query[key] = String(value);
+ }
+ }
+
+ try {
+ const response = await httpClient.sendRequest<T>({
+ method,
+ url: `${this.baseUrl}${url}`,
+ headers: {
+ 'X-API-Key': apiKey,
+ 'Content-Type': 'application/json',
+ ...headers,
+ },
+ queryParams: Object.keys(query).length > 0 ? query : undefined,
+ body,
+ });
+ return response.body;
+ } catch (error) {
+ throw toApiError(error);
}
+ },
- return response.body;
+ async paginate<T extends { id?: unknown }>({
+ auth,
+ url,
+ query,
+ maxItems,
+ pageSize = 100,
+ startingAfter,
+ }: {
+ auth: SystemeAuth;
+ url: string;
+ query?: Record<string, QueryValue>;
+ maxItems: number;
+ pageSize?: number;
+ startingAfter?: number;
+ }): Promise<{ items: T[]; hasMore: boolean; nextCursor: number | null }> {
+ const items: T[] = [];
+ let cursor = startingAfter;
+ let vendorHasMore = true;
+ let limit = Math.max(10, Math.min(100, pageSize));
+ while (items.length < maxItems && vendorHasMore) {
+ let page: { items?: T[]; hasMore?: boolean };
+ try {
+ page = await this.apiCall<{ items?: T[]; hasMore?: boolean }>({
+ method: HttpMethod.GET,
+ url,
+ auth,
+ queryParams: { ...query, limit, startingAfter: cursor },
+ });
+ } catch (error) {
+ const smaller = PAGE_SIZE_FALLBACKS.find((size) => size < limit);
+ if (smaller === undefined || !isPageLimitRejection(error)) {
+ throw error;
+ }
+ limit = smaller;
+ continue;
+ }
+ const pageItems = Array.isArray(page?.items) ? page.items : [];
+ vendorHasMore = page?.hasMore === true && pageItems.length > 0;
+ const room = maxItems - items.length;
+ const taken = pageItems.slice(0, room);
+ items.push(...taken);
+ if (taken.length < pageItems.length) {
+ vendorHasMore = true;
+ break;
+ }
+ const lastId = Number(pageItems[pageItems.length - 1]?.id);
+ if (!Number.isInteger(lastId) || lastId <= 0) {
+ break;
+ }
+ cursor = lastId;
+ }
+ const lastReturned = Number(items[items.length - 1]?.id);
+ const hasMore = vendorHasMore;
+ return {
+ items,
+ hasMore,
+ nextCursor: hasMore && Number.isInteger(lastReturned) && lastReturned > 0 ? lastReturned : null,
+ };
},
- verifyWebhookSignature: (
- webhookSecret?: string,
- webhookSignatureHeader?: string,
- webhookRawBody?: any,
- ): boolean => {
- if (!webhookSecret || !webhookSignatureHeader || !webhookRawBody) {
+ verifyWebhookSignature: ({
+ secret,
+ signatureHeader,
+ rawBody,
+ }: {
+ secret?: string;
+ signatureHeader?: string | string[];
+ rawBody?: unknown;
+ }): boolean => {
+ const signature = Array.isArray(signatureHeader) ? signatureHeader[0] : signatureHeader;
+ if (!secret || !signature || rawBody === undefined || rawBody === null) {
return false;
}
-
try {
- const hmac = crypto.createHmac('sha256', webhookSecret);
- hmac.update(webhookRawBody);
- const expectedSignature = hmac.digest('hex');
-
- return crypto.timingSafeEqual(
- Buffer.from(webhookSignatureHeader, 'hex'),
- Buffer.from(expectedSignature, 'hex'),
- );
- } catch (error) {
+ return signatureCandidates(rawBody).some((candidate) => hmacMatches({ secret, input: candidate, signature }));
+ } catch {
return false;
}
},
@@ -68,32 +378,41 @@ export const systemeIoCommon = {
}: {
eventType: string;
webhookUrl: string;
- auth: string | { apiKey: string };
+ auth: SystemeAuth;
secret: string;
}) {
return this.apiCall<{ id: string }>({
method: HttpMethod.POST,
url: '/webhooks',
body: {
- name: `Activepieces Webhook - ${eventType}`,
+ name: webhookName({ eventType, webhookUrl }),
url: webhookUrl,
- subscriptions: [eventType],
+ subscriptions: [{ event: eventType, schemaVersion: webhookSchemaVersion({ eventType }) }],
secret: secret,
},
auth,
});
},
+ async listWebhooks({ auth }: { auth: SystemeAuth }): Promise<Array<{ id: string; url?: string; name?: string }>> {
+ const page = await this.apiCall<{ items?: Array<{ id: string; url?: string; name?: string }> }>({
+ method: HttpMethod.GET,
+ url: '/webhooks',
+ auth,
+ });
+ return Array.isArray(page?.items) ? page.items : [];
+ },
+
async deleteWebhook({
webhookId,
auth,
}: {
webhookId: string;
- auth: string | { apiKey: string };
+ auth: SystemeAuth;
}) {
return this.apiCall({
method: HttpMethod.DELETE,
- url: `/webhooks/${webhookId}`,
+ url: `/webhooks/${encodeURIComponent(webhookId)}`,
auth,
});
},
@@ -118,30 +437,46 @@ export const systemeIoCommon = {
});
},
+ async findContactsByEmail({ auth, email }: { auth: SystemeAuth; email: string }) {
+ const page = await this.apiCall<{ items?: SystemeContact[] }>({
+ method: HttpMethod.GET,
+ url: '/contacts',
+ auth,
+ queryParams: { email, limit: 10 },
+ });
+ return Array.isArray(page?.items) ? page.items : [];
+ },
+
async getContact({
contactId,
auth,
}: {
- contactId: string;
- auth: string | { apiKey: string };
+ contactId: string | number;
+ auth: SystemeAuth;
}) {
- return this.apiCall({
+ return this.apiCall<SystemeContact>({
method: HttpMethod.GET,
- url: `/contacts/${contactId}`,
+ url: `/contacts/${requireId({ value: contactId, name: 'Contact ID' })}`,
auth,
});
},
async getTags({
auth,
+ query,
+ maxItems = 1000,
}: {
- auth: string | { apiKey: string };
+ auth: SystemeAuth;
+ query?: string;
+ maxItems?: number;
}) {
- return this.apiCall({
- method: HttpMethod.GET,
- url: '/tags',
+ const result = await this.paginate<SystemeTag>({
auth,
+ url: '/tags',
+ query: { query },
+ maxItems,
});
+ return { items: result.items, hasMore: result.hasMore };
},
async getContactFields({
@@ -156,3 +491,20 @@ export const systemeIoCommon = {
});
},
};
+
+export const systemeIoInput = { requireId, optionalId, idList, clampInt, phpJsonEncode };
+
+export type SystemeContact = {
+ id: number;
+ email: string;
+ registeredAt?: string;
+ locale?: string;
+ sourceURL?: string | null;
+ unsubscribed?: boolean;
+ bounced?: boolean;
+ needsConfirmation?: boolean;
+ fields?: { fieldName?: string; slug: string; value: string | null }[];
+ tags?: { id: number; name: string }[];
+};
+
+export type SystemeTag = { id: number; name: string; createdAt?: string };
diff --git a/packages/pieces/community/systeme-io/src/lib/common/dropdowns.ts b/packages/pieces/community/systeme-io/src/lib/common/dropdowns.ts
new file mode 100644
index 00000000000..57c4caa65b1
--- /dev/null
+++ b/packages/pieces/community/systeme-io/src/lib/common/dropdowns.ts
@@ -0,0 +1,431 @@
+import { Property } from '@activepieces/pieces-framework';
+import { systemeIoAuth } from './auth';
+import { apiErrorStatus, SystemeContact, systemeIoCommon } from './client';
+
+type Option<T> = { label: string; value: T };
+type OptionsState<T> = { disabled: boolean; placeholder?: string; options: Option<T>[] };
+
+const CONNECT_FIRST = 'Please connect your account first';
+
+function errorPlaceholder({ what, error }: { what: string; error: unknown }): string {
+ const message = error instanceof Error ? error.message : String(error);
+ return `Could not load ${what}: ${message.slice(0, 120)}`;
+}
+
+function fieldValue({ contact, slug }: { contact: SystemeContact; slug: string }): string | undefined {
+ const field = contact.fields?.find((f) => f.slug === slug);
+ return typeof field?.value === 'string' && field.value.trim() !== '' ? field.value.trim() : undefined;
+}
+
+export function contactLabel(contact: SystemeContact): string {
+ const name = [fieldValue({ contact, slug: 'first_name' }), fieldValue({ contact, slug: 'surname' }) ?? fieldValue({ contact, slug: 'last_name' })]
+ .filter((p) => p !== undefined)
+ .join(' ');
+ return name ? `${name} (${contact.email})` : contact.email;
+}
+
+export async function contactDropdownOptions({
+ apiKey,
+ searchValue,
+ label = contactLabel,
+}: {
+ apiKey: string;
+ searchValue?: string;
+ label?: (contact: SystemeContact) => string;
+}): Promise<OptionsState<number>> {
+ try {
+ const search = searchValue?.trim() ?? '';
+ const found = await searchContacts({ apiKey, search, label });
+ if (found.contacts.length === 0) {
+ return {
+ disabled: false,
+ placeholder: noMatchHint({ search, nameSearch: found.nameSearch }),
+ options: [],
+ };
+ }
+ return {
+ disabled: false,
+ placeholder: found.hint,
+ options: found.contacts.map((contact) => ({ label: label(contact), value: contact.id })),
+ };
+ } catch (error) {
+ return { disabled: true, placeholder: errorPlaceholder({ what: 'contacts', error }), options: [] };
+ }
+}
+
+async function searchContacts({
+ apiKey,
+ search,
+ label,
+}: {
+ apiKey: string;
+ search: string;
+ label: (contact: SystemeContact) => string;
+}): Promise<{ contacts: SystemeContact[]; hint?: string; nameSearch?: boolean }> {
+ if (FULL_EMAIL.test(search)) {
+ const contacts = await systemeIoCommon.findContactsByEmail({ auth: apiKey, email: search }).catch((error: unknown) => {
+ if (apiErrorStatus(error) === 422) {
+ return [];
+ }
+ throw error;
+ });
+ return { contacts };
+ }
+ if (/^\d+$/.test(search)) {
+ const id = Number(search);
+ if (!Number.isSafeInteger(id) || id <= 0) {
+ return { contacts: [] };
+ }
+ const contacts = await systemeIoCommon.getContact({ auth: apiKey, contactId: id }).then(
+ (contact) => [contact],
+ (error: unknown) => {
+ if (apiErrorStatus(error) === 404) {
+ return [];
+ }
+ throw error;
+ },
+ );
+ return { contacts };
+ }
+ const page = await systemeIoCommon.paginate<SystemeContact>({ auth: apiKey, url: '/contacts', maxItems: 100 });
+ if (search === '') {
+ return {
+ contacts: page.items,
+ hint: page.hasMore ? 'Showing the newest 100 contacts. Type a full email address or a contact id to find others.' : undefined,
+ };
+ }
+ const needle = search.toLowerCase();
+ const contacts = page.items.filter(
+ (contact) => label(contact).toLowerCase().includes(needle) || (contact.email ?? '').toLowerCase().includes(needle),
+ );
+ return {
+ contacts,
+ nameSearch: true,
+ hint: page.hasMore && contacts.length > 0 ? 'Name search covers the newest 100 contacts. Type a full email address or a contact id to find others.' : undefined,
+ };
+}
+
+function noMatchHint({ search, nameSearch }: { search: string; nameSearch?: boolean }): string {
+ if (search === '') {
+ return 'No contacts found';
+ }
+ if (nameSearch) {
+ return `No match for "${search}" among the newest 100 contacts. Type the full email address or a contact id.`;
+ }
+ return `No contact matches "${search}". Type the full email address or a contact id.`;
+}
+
+const FULL_EMAIL = /^[^@\s]+@[^@\s]+\.[^@\s]+$/;
+
+async function tagDropdownOptions({ apiKey, searchValue }: { apiKey: string; searchValue?: string }): Promise<OptionsState<number>> {
+ try {
+ const search = searchValue?.trim() || undefined;
+ const { items, hasMore } = await systemeIoCommon.getTags({ auth: apiKey, query: search, maxItems: search ? SEARCH_PAGE : 1000 });
+ return {
+ disabled: false,
+ placeholder: items.length === 0 ? 'No tags found' : truncatedHint({ hasMore, what: 'tags', searched: search !== undefined }),
+ options: items.map((tag) => ({ label: tag.name, value: tag.id })),
+ };
+ } catch (error) {
+ return { disabled: true, placeholder: errorPlaceholder({ what: 'tags', error }), options: [] };
+ }
+}
+
+const CONTACT_DESCRIPTION =
+ 'Pick a contact: type a name (searches the newest 100), a full email address or a contact id, or map a contact id. Agents can pass the numeric contact id directly.';
+
+export function contactPicker<R extends boolean>({
+ required,
+ displayName = 'Contact',
+ description = CONTACT_DESCRIPTION,
+}: {
+ required: R;
+ displayName?: string;
+ description?: string;
+}) {
+ return Property.Dropdown({
+ auth: systemeIoAuth,
+ displayName,
+ description,
+ required,
+ refreshers: [],
+ refreshOnSearch: true,
+ options: async ({ auth }, ctx) => {
+ if (!auth) {
+ return { disabled: true, placeholder: CONNECT_FIRST, options: [] };
+ }
+ return contactDropdownOptions({ apiKey: auth.secret_text, searchValue: ctx?.searchValue });
+ },
+ });
+}
+
+export function tagPicker<R extends boolean>({
+ required,
+ displayName = 'Tag',
+ description = 'Pick a tag (type to search), or map a tag id. Agents can pass the numeric tag id directly.',
+}: {
+ required: R;
+ displayName?: string;
+ description?: string;
+}) {
+ return Property.Dropdown({
+ auth: systemeIoAuth,
+ displayName,
+ description,
+ required,
+ refreshers: [],
+ refreshOnSearch: true,
+ options: async ({ auth }, ctx) => {
+ if (!auth) {
+ return { disabled: true, placeholder: CONNECT_FIRST, options: [] };
+ }
+ return tagDropdownOptions({ apiKey: auth.secret_text, searchValue: ctx?.searchValue });
+ },
+ });
+}
+
+type Course = { id: number; name: string; active?: boolean };
+
+export const courseDropdown = Property.Dropdown({
+ auth: systemeIoAuth,
+ displayName: 'Course',
+ description: 'Pick a course (type to search), or map a course id. Agents can pass the numeric course id directly.',
+ required: true,
+ refreshers: [],
+ refreshOnSearch: true,
+ options: async ({ auth }, ctx) => {
+ if (!auth) {
+ return { disabled: true, placeholder: CONNECT_FIRST, options: [] };
+ }
+ try {
+ const search = ctx?.searchValue?.trim() || undefined;
+ const { items, hasMore } = await systemeIoCommon.paginate<Course>({
+ auth: auth.secret_text,
+ url: '/school/courses',
+ query: { query: search },
+ maxItems: search ? SEARCH_PAGE : 1000,
+ });
+ return {
+ disabled: false,
+ placeholder: items.length === 0 ? 'No courses found' : truncatedHint({ hasMore, what: 'courses', searched: search !== undefined }),
+ options: items.map((course) => ({
+ label: course.active === false ? `${course.name} (inactive)` : course.name,
+ value: course.id,
+ })),
+ };
+ } catch (error) {
+ return { disabled: true, placeholder: errorPlaceholder({ what: 'courses', error }), options: [] };
+ }
+ },
+});
+
+type Community = { id: number; name: string };
+
+export const communityDropdown = Property.Dropdown({
+ auth: systemeIoAuth,
+ displayName: 'Community',
+ description: 'Pick a community (type to search), or map a community id. Agents can pass the numeric community id directly.',
+ required: true,
+ refreshers: [],
+ refreshOnSearch: true,
+ options: async ({ auth }, ctx) => {
+ if (!auth) {
+ return { disabled: true, placeholder: CONNECT_FIRST, options: [] };
+ }
+ try {
+ const search = ctx?.searchValue?.trim() || undefined;
+ const { items, hasMore } = await systemeIoCommon.paginate<Community>({
+ auth: auth.secret_text,
+ url: '/community/communities',
+ query: { query: search },
+ maxItems: search ? SEARCH_PAGE : 1000,
+ });
+ return {
+ disabled: false,
+ placeholder: items.length === 0 ? 'No communities found' : truncatedHint({ hasMore, what: 'communities', searched: search !== undefined }),
+ options: items.map((community) => ({ label: community.name, value: community.id })),
+ };
+ } catch (error) {
+ return { disabled: true, placeholder: errorPlaceholder({ what: 'communities', error }), options: [] };
+ }
+ },
+});
+
+type CourseModule = { id: number; name: string; position?: number };
+
+export const courseModulesDropdown = Property.MultiSelectDropdown({
+ auth: systemeIoAuth,
+ displayName: 'Modules',
+ description:
+ 'Required for "Partial access" and "Partial dripping access": the modules the contact can open. Ignored for full access and dripping content. Agents can pass module ids.',
+ required: false,
+ refreshers: ['course_id', 'access_type'],
+ options: async ({ auth, course_id, access_type }) => {
+ if (!auth) {
+ return { disabled: true, placeholder: CONNECT_FIRST, options: [] };
+ }
+ if (access_type !== 'partial_access' && access_type !== 'partial_dripping_access') {
+ return { disabled: true, placeholder: 'Only needed for partial access', options: [] };
+ }
+ const courseId = Number(course_id);
+ if (!Number.isInteger(courseId) || courseId <= 0) {
+ return { disabled: true, placeholder: 'Please select a course first', options: [] };
+ }
+ try {
+ const { items, hasMore } = await systemeIoCommon.paginate<CourseModule>({
+ auth: auth.secret_text,
+ url: '/school/course-modules',
+ query: { courseId },
+ maxItems: 1000,
+ });
+ return {
+ disabled: false,
+ placeholder: items.length === 0 ? 'This course has no modules' : truncatedHint({ hasMore, what: 'modules', searchable: false }),
+ options: items.map((module) => ({ label: module.name, value: module.id })),
+ };
+ } catch (error) {
+ return { disabled: true, placeholder: errorPlaceholder({ what: 'modules', error }), options: [] };
+ }
+ },
+});
+
+type Subscription = {
+ id: number;
+ status: string;
+ pricePlan?: { name?: string; amount?: number; currency?: string } | null;
+};
+
+export const subscriptionDropdown = Property.Dropdown({
+ auth: systemeIoAuth,
+ displayName: 'Subscription',
+ description: 'Pick one of the contact\'s subscriptions, or map a subscription id. Agents can pass the numeric subscription id directly.',
+ required: true,
+ refreshers: ['contact_id'],
+ options: async ({ auth, contact_id }) => {
+ if (!auth) {
+ return { disabled: true, placeholder: CONNECT_FIRST, options: [] };
+ }
+ const contactId = Number(contact_id);
+ if (!Number.isInteger(contactId) || contactId <= 0) {
+ return { disabled: true, placeholder: 'Please select a contact first', options: [] };
+ }
+ try {
+ const { items, hasMore } = await systemeIoCommon.paginate<Subscription>({
+ auth: auth.secret_text,
+ url: '/payment/subscriptions',
+ query: { contact: contactId },
+ maxItems: 1000,
+ });
+ return {
+ disabled: false,
+ placeholder: items.length === 0 ? 'This contact has no subscriptions' : truncatedHint({ hasMore, what: 'subscriptions', searchable: false }),
+ options: items.map((sub) => ({
+ label: `${sub.pricePlan?.name ?? `Subscription ${sub.id}`} (${sub.status})`,
+ value: sub.id,
+ })),
+ };
+ } catch (error) {
+ return { disabled: true, placeholder: errorPlaceholder({ what: 'subscriptions', error }), options: [] };
+ }
+ },
+});
+
+export const accessTypeDropdown = Property.StaticDropdown({
+ displayName: 'Access Type',
+ description:
+ "What the contact can open. 'full_access' = the whole course; 'partial_access' = only the selected modules; 'dripping_content' = lectures unlock on the course's drip schedule; 'partial_dripping_access' = selected modules on the drip schedule.",
+ required: true,
+ defaultValue: 'full_access',
+ options: {
+ disabled: false,
+ options: [
+ { label: 'Full access', value: 'full_access' },
+ { label: 'Partial access (selected modules)', value: 'partial_access' },
+ { label: 'Dripping content', value: 'dripping_content' },
+ { label: 'Partial dripping access (selected modules)', value: 'partial_dripping_access' },
+ ],
+ },
+});
+
+const CONTACT_LOCALES = [
+ 'en', 'fr', 'es', 'it', 'pt', 'de', 'nl', 'ru', 'jp', 'tr', 'ar', 'zh', 'sv', 'ro',
+ 'cs', 'hu', 'sk', 'dk', 'id', 'pl', 'el', 'sr', 'hi', 'no', 'th', 'sq', 'sl', 'ua',
+];
+
+export const contactLocaleOptions = [
+ { label: 'English', value: 'en' },
+ { label: 'French', value: 'fr' },
+ { label: 'Spanish', value: 'es' },
+ { label: 'Italian', value: 'it' },
+ { label: 'Portuguese', value: 'pt' },
+ { label: 'German', value: 'de' },
+ { label: 'Dutch', value: 'nl' },
+ { label: 'Russian', value: 'ru' },
+ { label: 'Japanese', value: 'jp' },
+ { label: 'Turkish', value: 'tr' },
+ { label: 'Arabic', value: 'ar' },
+ { label: 'Chinese', value: 'zh' },
+ { label: 'Swedish', value: 'sv' },
+ { label: 'Romanian', value: 'ro' },
+ { label: 'Czech', value: 'cs' },
+ { label: 'Hungarian', value: 'hu' },
+ { label: 'Slovak', value: 'sk' },
+ { label: 'Danish', value: 'dk' },
+ { label: 'Indonesian', value: 'id' },
+ { label: 'Polish', value: 'pl' },
+ { label: 'Greek', value: 'el' },
+ { label: 'Serbian', value: 'sr' },
+ { label: 'Hindi', value: 'hi' },
+ { label: 'Norwegian', value: 'no' },
+ { label: 'Thai', value: 'th' },
+ { label: 'Albanian', value: 'sq' },
+ { label: 'Slovenian', value: 'sl' },
+ { label: 'Ukrainian', value: 'ua' },
+];
+
+export function optionalLocale(value: unknown): string | undefined {
+ if (value === undefined || value === null || value === '') {
+ return undefined;
+ }
+ const locale = String(value).trim();
+ if (!CONTACT_LOCALES.includes(locale)) {
+ throw new Error(`Locale must be one of: ${CONTACT_LOCALES.join(', ')}. Note Systeme.io uses 'jp' (Japanese), 'dk' (Danish) and 'ua' (Ukrainian).`);
+ }
+ return locale;
+}
+
+
+export async function systemeIoAuthTagOptions({
+ apiKey,
+ searchValue,
+}: {
+ apiKey: string | undefined;
+ searchValue?: string;
+}): Promise<OptionsState<number>> {
+ if (!apiKey) {
+ return { disabled: true, placeholder: CONNECT_FIRST, options: [] };
+ }
+ return tagDropdownOptions({ apiKey, searchValue });
+}
+
+function truncatedHint({
+ hasMore,
+ what,
+ searchable = true,
+ searched = false,
+}: {
+ hasMore: boolean;
+ what: string;
+ searchable?: boolean;
+ searched?: boolean;
+}): string | undefined {
+ if (!hasMore) {
+ return undefined;
+ }
+ if (searched) {
+ return `Showing the first ${SEARCH_PAGE} matching ${what}. Type more to narrow the search.`;
+ }
+ return `Showing the first 1,000 ${what}. ${searchable ? 'Type to search, or map an id.' : 'Map an id for the others.'}`;
+}
+
+const SEARCH_PAGE = 100;
diff --git a/packages/pieces/community/systeme-io/src/lib/common/mappers.ts b/packages/pieces/community/systeme-io/src/lib/common/mappers.ts
new file mode 100644
index 00000000000..f32deb326e6
--- /dev/null
+++ b/packages/pieces/community/systeme-io/src/lib/common/mappers.ts
@@ -0,0 +1,104 @@
+type Obj = Record<string, unknown>;
+
+function isRecord(value: unknown): value is Obj {
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
+}
+
+function obj(value: unknown): Obj {
+ return isRecord(value) ? value : {};
+}
+
+function orNull<T>(value: T | undefined): T | null {
+ return value === undefined ? null : value;
+}
+
+type EnrollmentRow = {
+ id: unknown;
+ access_type: unknown;
+ active: unknown;
+ course_id: unknown;
+ course_name: unknown;
+ contact_id: unknown;
+ contact_email: unknown;
+};
+
+export function enrollmentRow(raw: unknown): EnrollmentRow {
+ const e = obj(raw);
+ const course = obj(e['course']);
+ const contact = obj(e['contact']);
+ return {
+ id: orNull(e['id']),
+ access_type: orNull(e['accessType']),
+ active: orNull(e['active']),
+ course_id: orNull(course['id']),
+ course_name: orNull(course['name']),
+ contact_id: orNull(contact['id']),
+ contact_email: orNull(contact['email']),
+ };
+}
+
+export function membershipRow(raw: unknown) {
+ const m = obj(raw);
+ const community = obj(m['community']);
+ const contact = obj(m['contact']);
+ return {
+ id: orNull(m['id']),
+ community_id: orNull(community['id']),
+ community_name: orNull(community['name']),
+ contact_id: orNull(contact['id']),
+ };
+}
+
+export function subscriptionRow(raw: unknown) {
+ const s = obj(raw);
+ const plan = obj(s['pricePlan']);
+ const recurring = obj(plan['recurringOptions']);
+ return {
+ id: orNull(s['id']),
+ status: orNull(s['status']),
+ created_at: orNull(s['createdAt']),
+ cancelled_at: orNull(s['cancelledAt']),
+ completed_at: orNull(s['completedAt']),
+ price_plan_id: orNull(plan['id']),
+ price_plan_name: orNull(plan['name']),
+ price_plan_type: orNull(plan['type']),
+ amount: orNull(plan['amount']),
+ currency: orNull(plan['currency']),
+ interval: orNull(recurring['interval']),
+ interval_count: orNull(recurring['intervalCount']),
+ };
+}
+
+export function courseRow(raw: unknown) {
+ const c = obj(raw);
+ const modules = Array.isArray(c['modules']) ? c['modules'] : [];
+ return {
+ id: orNull(c['id']),
+ name: orNull(c['name']),
+ active: orNull(c['active']),
+ description: orNull(c['description']),
+ path: orNull(c['path']),
+ domain_name: orNull(c['domainName']),
+ locale: orNull(c['locale']),
+ modules: modules.map((m) => ({ id: orNull(obj(m)['id']), name: orNull(obj(m)['name']) })),
+ };
+}
+
+export function communityRow(raw: unknown) {
+ const c = obj(raw);
+ return {
+ id: orNull(c['id']),
+ name: orNull(c['name']),
+ path: orNull(c['path']),
+ domain_name: orNull(c['domainName']),
+ };
+}
+
+export function tagRow(raw: unknown) {
+ const t = obj(raw);
+ return {
+ id: orNull(t['id']),
+ name: orNull(t['name']),
+ created_at: orNull(t['createdAt']),
+ };
+}
diff --git a/packages/pieces/community/systeme-io/src/lib/common/operations.ts b/packages/pieces/community/systeme-io/src/lib/common/operations.ts
new file mode 100644
index 00000000000..efacde35e21
--- /dev/null
+++ b/packages/pieces/community/systeme-io/src/lib/common/operations.ts
@@ -0,0 +1,107 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { apiErrorStatus, SystemeContact, SystemeTag, systemeIoCommon, systemeIoInput } from './client';
+import { tagRow } from './mappers';
+
+const TAG_NAME_MAX = 64;
+
+async function deleteById({ apiKey, url, id }: { apiKey: string; url: string; id: number }) {
+ try {
+ await systemeIoCommon.apiCall({ method: HttpMethod.DELETE, url, auth: apiKey });
+ return { deleted: true, not_found: false, id };
+ } catch (error) {
+ if (apiErrorStatus(error) === 404) {
+ return { deleted: false, not_found: true, id };
+ }
+ throw error;
+ }
+}
+
+function validTagName(name: unknown): string {
+ const trimmed = typeof name === 'string' ? name.trim() : '';
+ if (trimmed === '') {
+ throw new Error('Tag name is required.');
+ }
+ if (trimmed.length > TAG_NAME_MAX) {
+ throw new Error(`Tag name must be at most ${TAG_NAME_MAX} characters (got ${trimmed.length}).`);
+ }
+ return trimmed;
+}
+
+async function findTagByName({ apiKey, name }: { apiKey: string; name: string }): Promise<SystemeTag | undefined> {
+ const wanted = name.toLowerCase();
+ const { items, hasMore } = await systemeIoCommon.getTags({ auth: apiKey, query: name });
+ const match = items.find((tag) => typeof tag.name === 'string' && tag.name.trim().toLowerCase() === wanted);
+ if (!match && hasMore) {
+ throw new Error(`More than 1,000 tags contain "${name}", so an existing tag with that exact name could not be ruled out. No tag was created.`);
+ }
+ return match;
+}
+
+async function getOrCreateTag({ apiKey, name }: { apiKey: string; name: unknown }) {
+ const tagName = validTagName(name);
+ const existing = await findTagByName({ apiKey, name: tagName });
+ if (existing) {
+ return { ...tagRow(existing), created: false };
+ }
+ const created = await systemeIoCommon.apiCall<SystemeTag>({
+ method: HttpMethod.POST,
+ url: '/tags',
+ body: { name: tagName },
+ auth: apiKey,
+ });
+ return { ...tagRow(created), created: true };
+}
+
+async function removeMatching<T extends { id?: unknown }>({
+ apiKey,
+ listUrl,
+ query,
+ matches,
+ deleteUrl,
+}: {
+ apiKey: string;
+ listUrl: string;
+ query: Record<string, string | number>;
+ matches: (row: T) => boolean;
+ deleteUrl: (id: number) => string;
+}) {
+ const { items, hasMore } = await systemeIoCommon.paginate<T>({ auth: apiKey, url: listUrl, query, maxItems: 1000 });
+ if (hasMore) {
+ throw new Error('Systeme.io returned more than 1,000 matching rows, so the removal could not be checked completely. Nothing was removed.');
+ }
+ const ids = items
+ .filter(matches)
+ .map((row) => Number(row.id))
+ .filter((id) => Number.isInteger(id) && id > 0);
+ const results = [];
+ for (const id of ids) {
+ try {
+ results.push(await deleteById({ apiKey, url: deleteUrl(id), id }));
+ } catch (error) {
+ const done = results.filter((r) => r.deleted).map((r) => r.id);
+ if (done.length === 0) {
+ throw error;
+ }
+ const reason = error instanceof Error ? error.message : String(error);
+ throw new Error(`Removed ${done.join(', ')}, then removing ${id} failed: ${reason}`);
+ }
+ }
+ const removedIds = results.filter((r) => r.deleted).map((r) => r.id);
+ return {
+ removed: removedIds.length > 0,
+ removed_count: removedIds.length,
+ removed_ids: removedIds,
+ not_found: removedIds.length === 0,
+ };
+}
+
+async function tagIsOnContact({ apiKey, contactId, tagId }: { apiKey: string; contactId: number; tagId: number }): Promise<boolean> {
+ const contact = await systemeIoCommon.apiCall<SystemeContact>({
+ method: HttpMethod.GET,
+ url: `/contacts/${systemeIoInput.requireId({ value: contactId, name: 'Contact ID' })}`,
+ auth: apiKey,
+ });
+ return (contact.tags ?? []).some((tag) => Number(tag.id) === tagId);
+}
+
+export const systemeOps = { deleteById, getOrCreateTag, validTagName, removeMatching, tagIsOnContact };
diff --git a/packages/pieces/community/systeme-io/src/lib/common/props.ts b/packages/pieces/community/systeme-io/src/lib/common/props.ts
index edbfdb09057..13f6f259683 100644
--- a/packages/pieces/community/systeme-io/src/lib/common/props.ts
+++ b/packages/pieces/community/systeme-io/src/lib/common/props.ts
@@ -1,6 +1,7 @@
import { Property } from '@activepieces/pieces-framework';
import { systemeIoCommon } from './client';
import { systemeIoAuth } from './auth';
+import { contactDropdownOptions, contactLabel } from './dropdowns';
export const systemeIoProps = {
contactDropdown: Property.Dropdown({
@@ -175,10 +176,11 @@ export const systemeIoProps = {
contactIdDropdown: Property.Dropdown({
auth: systemeIoAuth,
displayName: 'Contact ID',
- description: 'Select a contact by ID',
+ description: 'Select a contact. Type a name (searches the newest 100), a full email address or a contact id.',
required: true,
refreshers: [],
- options: async ({ auth }) => {
+ refreshOnSearch: true,
+ options: async ({ auth }, ctx) => {
if (!auth) {
return {
disabled: true,
@@ -186,46 +188,11 @@ export const systemeIoProps = {
options: [],
};
}
-
- try {
- const response = await systemeIoCommon.getContacts({
- auth: auth.secret_text,
- limit: 100,
- });
-
- let contacts: any[] = [];
- if (Array.isArray(response)) {
- contacts = response;
- } else if (response && typeof response === 'object' && response !== null) {
- const responseAny = response as any;
- if (responseAny.items && Array.isArray(responseAny.items)) {
- contacts = responseAny.items;
- }
- }
-
- if (contacts.length > 0) {
- return {
- disabled: false,
- options: contacts.map((contact: any) => ({
- label: `ID: ${contact.id} - ${contact.first_name || ''} ${contact.last_name || ''} (${contact.email})`.trim(),
- value: contact.id,
- })),
- };
- }
-
- return {
- disabled: true,
- placeholder: 'No contacts found',
- options: [],
- };
- } catch (error) {
- console.error('Error fetching contacts:', error);
- return {
- disabled: true,
- placeholder: 'Error loading contacts',
- options: [],
- };
- }
+ return contactDropdownOptions({
+ apiKey: auth.secret_text,
+ searchValue: ctx?.searchValue,
+ label: (contact) => `ID: ${contact.id} - ${contactLabel(contact)}`,
+ });
},
}),
diff --git a/packages/pieces/community/systeme-io/src/lib/common/samples.ts b/packages/pieces/community/systeme-io/src/lib/common/samples.ts
new file mode 100644
index 00000000000..6f7d003c8c6
--- /dev/null
+++ b/packages/pieces/community/systeme-io/src/lib/common/samples.ts
@@ -0,0 +1,84 @@
+export const contactSample = {
+ id: 12345,
+ email: '[email protected]',
+ registeredAt: '2024-01-01T00:00:00+00:00',
+ locale: 'en',
+ sourceURL: null,
+ unsubscribed: false,
+ bounced: false,
+ needsConfirmation: false,
+ fields: [
+ { fieldName: 'First name', slug: 'first_name', value: 'John' },
+ { fieldName: 'Last name', slug: 'surname', value: 'Doe' },
+ ],
+ tags: [
+ { id: 1, name: 'some_tag' },
+ { id: 2, name: 'another_tag' },
+ ],
+};
+
+export const saleSample = {
+ customer: {
+ id: 12345,
+ clientIp: 'dbad:0dad:6d09:3123:548f:712b:96dc:62e5',
+ contactId: 12345,
+ email: '[email protected]',
+ fields: {
+ company_name: 'Super company',
+ postcode: '12345',
+ phone_number: '1234567890',
+ surname: 'Doe',
+ country: 'US',
+ first_name: 'John',
+ },
+ paymentProcessor: 'stripe',
+ sourceUrl: 'https://example.com/some-page',
+ },
+ coupon: {
+ innerName: 'Coupon 123',
+ code: 'C123',
+ discountAmount: 1234,
+ discountType: 'fixed',
+ expirationDate: '2025-02-07T12:34:56+00:00',
+ limitOfUse: 12,
+ },
+ funnelStep: {
+ id: 12345,
+ name: 'Beautiful funnel step',
+ type: 'offer-form',
+ funnel: { id: 12345, name: 'Beautiful funnel' },
+ },
+ order: {
+ id: 12345,
+ createdAt: '2025-02-06T12:34:56+00:00',
+ discountAmount: null,
+ discountType: null,
+ shippingFee: null,
+ totalPrice: null,
+ vat: null,
+ },
+ orderItem: {
+ createdAt: '2025-02-06T12:34:56+00:00',
+ id: 12345,
+ resources: [
+ {
+ course: null,
+ courseBundle: null,
+ enrollmentAccessType: null,
+ enrollmentDrippingAccessCourse: null,
+ physicalProduct: { id: 12345, name: 'Marketeur Booster', options: [] },
+ tag: null,
+ },
+ ],
+ },
+ pricePlan: {
+ id: 94283,
+ name: 'Custom price plan',
+ type: 'one_shot',
+ amount: 1234,
+ currency: 'eur',
+ innerName: 'PP1',
+ recurringOptions: null,
+ statementDescriptor: '',
+ },
+};
diff --git a/packages/pieces/community/systeme-io/src/lib/common/webhook.ts b/packages/pieces/community/systeme-io/src/lib/common/webhook.ts
new file mode 100644
index 00000000000..dbebc036656
--- /dev/null
+++ b/packages/pieces/community/systeme-io/src/lib/common/webhook.ts
@@ -0,0 +1,205 @@
+import { Store } from '@activepieces/pieces-framework';
+import { randomBytes } from 'crypto';
+import { apiErrorStatus, systemeIoCommon } from './client';
+
+async function enable({
+ auth,
+ webhookUrl,
+ store,
+ event,
+ prefix,
+}: {
+ auth: { secret_text: string };
+ webhookUrl: string;
+ store: Store;
+ event: SystemeWebhookEvent;
+ prefix: string;
+}) {
+ const k = storeKeys({ prefix });
+ const apiKey = auth.secret_text;
+ const secret = randomBytes(32).toString('hex');
+ const response = await createWebhook({ apiKey, webhookUrl, event, secret });
+ try {
+ await store.put(k.id, response.id);
+ await store.put(k.secret, secret);
+ } catch (error) {
+ await systemeIoCommon.deleteWebhook({ webhookId: response.id, auth: apiKey }).catch(() => undefined);
+ await store.delete(k.id).catch(() => undefined);
+ await store.delete(k.secret).catch(() => undefined);
+ throw error;
+ }
+}
+
+async function disable({ auth, store, prefix }: { auth: { secret_text: string }; store: Store; prefix: string }) {
+ const k = storeKeys({ prefix });
+ const webhookId = await store.get<string>(k.id);
+ if (!webhookId) {
+ return;
+ }
+ try {
+ await systemeIoCommon.deleteWebhook({ webhookId, auth: auth.secret_text });
+ } catch (error) {
+ if (apiErrorStatus(error) !== 404) {
+ throw error;
+ }
+ }
+ await store.put(k.id, null);
+ await store.put(k.secret, null);
+ await store.put(k.seen, null);
+}
+
+async function accept({
+ store,
+ payload,
+ prefix,
+}: {
+ store: Store;
+ payload: WebhookPayload;
+ prefix: string;
+}): Promise<boolean> {
+ const k = storeKeys({ prefix });
+ const secret = await store.get<string>(k.secret);
+ const signature = header({ headers: payload.headers, name: 'x-webhook-signature' });
+ const messageId = header({ headers: payload.headers, name: 'x-webhook-message-id' });
+ const verified = systemeIoCommon.verifyWebhookSignature({
+ secret: secret ?? undefined,
+ signatureHeader: signature,
+ rawBody: payload.rawBody,
+ });
+ if (!verified) {
+ const reason = !secret
+ ? 'no webhook secret is stored for this trigger (re-publish the flow to recreate the webhook)'
+ : !signature
+ ? 'the X-Webhook-Signature header is missing'
+ : payload.rawBody === undefined || payload.rawBody === null
+ ? 'the raw request body is not available'
+ : 'the HMAC-SHA256 signature does not match';
+ throw new Error(
+ `Systeme.io webhook rejected: ${reason}${messageId ? ` (message id ${messageId})` : ''}. The event was not processed.`,
+ );
+ }
+ if (!messageId) {
+ return true;
+ }
+ const seen = (await store.get<string[]>(k.seen)) ?? [];
+ if (seen.includes(messageId)) {
+ return false;
+ }
+ await store.put(k.seen, [...seen, messageId].slice(-SEEN_LIMIT));
+ return true;
+}
+
+function normalizeTagPayload(body: unknown): unknown {
+ const payload = objectOrUndefined(body);
+ if (!payload) {
+ return body;
+ }
+ const outer = objectOrUndefined(payload['contact']);
+ const inner = outer ? objectOrUndefined(outer['contact']) : undefined;
+ return { ...payload, contact: inner ?? outer ?? null, tag: payload['tag'] ?? null };
+}
+
+function tagIdOf(body: unknown): number | undefined {
+ const tag = objectOrUndefined(objectOrUndefined(body)?.['tag']);
+ const id = Number(tag?.['id']);
+ return Number.isInteger(id) ? id : undefined;
+}
+
+function tagEvent({ body, tagFilter }: { body: unknown; tagFilter: unknown }): unknown[] {
+ const filtered = tagFilter !== undefined && tagFilter !== null && String(tagFilter) !== '';
+ if (filtered && tagIdOf(body) !== Number(tagFilter)) {
+ return [];
+ }
+ return [normalizeTagPayload(body)];
+}
+
+function unwrap({ body, key }: { body: unknown; key: string }): unknown {
+ const inner = isRecord(body) ? body[key] : undefined;
+ return inner ? inner : body;
+}
+
+export const systemeWebhook = { enable, disable, accept, tagEvent, unwrap };
+
+const SEEN_LIMIT = 200;
+
+function storeKeys({ prefix }: { prefix: string }) {
+ return {
+ id: `${prefix}_webhook_id`,
+ secret: `${prefix}_webhook_secret`,
+ seen: `${prefix}_seen_message_ids`,
+ };
+}
+
+function header({ headers, name }: { headers: WebhookPayload['headers']; name: string }): string | undefined {
+ const value = headers[name] ?? headers[name.toLowerCase()];
+ if (Array.isArray(value)) {
+ return value[0];
+ }
+ return typeof value === 'string' && value !== '' ? value : undefined;
+}
+
+function isAlreadyUsed(error: unknown): boolean {
+ return (
+ apiErrorStatus(error) === 422 &&
+ error instanceof Error &&
+ /\b(name|url): This value is already used/.test(error.message)
+ );
+}
+
+async function createWebhook({
+ apiKey,
+ webhookUrl,
+ event,
+ secret,
+}: {
+ apiKey: string;
+ webhookUrl: string;
+ event: SystemeWebhookEvent;
+ secret: string;
+}) {
+ const create = () => systemeIoCommon.createWebhook({ eventType: event, webhookUrl, auth: apiKey, secret });
+ try {
+ return await create();
+ } catch (error) {
+ if (!isAlreadyUsed(error)) {
+ throw error;
+ }
+ const name = systemeIoCommon.webhookName({ eventType: event, webhookUrl });
+ const stale = (await systemeIoCommon.listWebhooks({ auth: apiKey })).filter(
+ (webhook) => webhook.url === webhookUrl || webhook.name === name,
+ );
+ if (stale.length === 0) {
+ throw error;
+ }
+ for (const webhook of stale) {
+ await systemeIoCommon.deleteWebhook({ webhookId: webhook.id, auth: apiKey }).catch((deleteError: unknown) => {
+ if (apiErrorStatus(deleteError) !== 404) {
+ throw deleteError;
+ }
+ });
+ }
+ return create();
+ }
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
+}
+
+function objectOrUndefined(value: unknown): Record<string, unknown> | undefined {
+ return isRecord(value) ? value : undefined;
+}
+
+type SystemeWebhookEvent =
+ | 'CONTACT_CREATED'
+ | 'CONTACT_TAG_ADDED'
+ | 'CONTACT_TAG_REMOVED'
+ | 'CONTACT_OPT_IN'
+ | 'SALE_NEW'
+ | 'SALE_CANCELED';
+
+type WebhookPayload = {
+ headers: Record<string, string | string[] | undefined>;
+ body: unknown;
+ rawBody?: unknown;
+};
diff --git a/packages/pieces/community/systeme-io/src/lib/output-schemas-ai.ts b/packages/pieces/community/systeme-io/src/lib/output-schemas-ai.ts
new file mode 100644
index 00000000000..1c58e4d8e28
--- /dev/null
+++ b/packages/pieces/community/systeme-io/src/lib/output-schemas-ai.ts
@@ -0,0 +1,193 @@
+import { OutputSchema, OutputSchemaField } from '@activepieces/pieces-framework';
+import { contactOutputFields, enrollmentOutputFields, tagOutputFields } from './output-schemas';
+
+const listMeta: OutputSchemaField[] = [
+ { key: 'count', label: 'Returned', format: 'number' },
+ { key: 'has_more', label: 'More Available', format: 'boolean' },
+ {
+ key: 'next_cursor',
+ label: 'Next Cursor',
+ description: 'Pass as starting_after to continue. Empty when there are no more rows.',
+ },
+];
+
+const contactField: OutputSchemaField = {
+ key: 'contact',
+ label: 'Contact',
+ children: contactOutputFields,
+};
+
+export const aiListTagsOutputSchema: OutputSchema = {
+ fields: [{ key: 'tags', label: 'Tags', labelKey: 'name', listItems: tagOutputFields }, ...listMeta],
+};
+
+export const aiTagOutputSchema: OutputSchema = { fields: tagOutputFields };
+
+export const aiListContactFieldsOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'fields',
+ label: 'Contact Fields',
+ labelKey: 'field_name',
+ listItems: [
+ { key: 'slug', label: 'Slug', description: 'Use this as the slug in create and update calls.' },
+ { key: 'field_name', label: 'Field Name' },
+ ],
+ },
+ { key: 'count', label: 'Count', format: 'number' },
+ {
+ key: 'has_more',
+ label: 'More Available',
+ format: 'boolean',
+ description: 'Systeme.io returns every contact field in one response and has no paging for this list, so this is false unless that response was cut off.',
+ },
+ ],
+};
+
+export const aiListCoursesOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'courses',
+ label: 'Courses',
+ labelKey: 'name',
+ listItems: [
+ { key: 'id', label: 'Course ID' },
+ { key: 'name', label: 'Name' },
+ { key: 'active', label: 'Active', format: 'boolean' },
+ { key: 'description', label: 'Description' },
+ { key: 'path', label: 'Path' },
+ { key: 'domain_name', label: 'Domain' },
+ { key: 'locale', label: 'Locale' },
+ {
+ key: 'modules',
+ label: 'Modules',
+ labelKey: 'name',
+ listItems: [
+ { key: 'id', label: 'Module ID' },
+ { key: 'name', label: 'Name' },
+ ],
+ },
+ ],
+ },
+ ...listMeta,
+ ],
+};
+
+export const aiListEnrollmentsOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'enrollments', label: 'Enrollments', labelKey: 'course_name', listItems: enrollmentOutputFields },
+ ...listMeta,
+ ],
+};
+
+export const aiListCommunitiesOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'communities',
+ label: 'Communities',
+ labelKey: 'name',
+ listItems: [
+ { key: 'id', label: 'Community ID' },
+ { key: 'name', label: 'Name' },
+ { key: 'path', label: 'Path' },
+ { key: 'domain_name', label: 'Domain' },
+ ],
+ },
+ ...listMeta,
+ ],
+};
+
+export const aiListMembershipsOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'memberships',
+ label: 'Memberships',
+ labelKey: 'community_name',
+ listItems: [
+ { key: 'id', label: 'Membership ID' },
+ { key: 'community_id', label: 'Community ID' },
+ { key: 'community_name', label: 'Community Name' },
+ { key: 'contact_id', label: 'Contact ID' },
+ ],
+ },
+ ...listMeta,
+ ],
+};
+
+export const aiListSubscriptionsOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'subscriptions',
+ label: 'Subscriptions',
+ labelKey: 'price_plan_name',
+ listItems: [
+ { key: 'id', label: 'Subscription ID' },
+ { key: 'status', label: 'Status' },
+ { key: 'created_at', label: 'Created At', format: 'datetime' },
+ { key: 'cancelled_at', label: 'Cancelled At', format: 'datetime' },
+ { key: 'completed_at', label: 'Completed At', format: 'datetime' },
+ { key: 'price_plan_id', label: 'Price Plan ID' },
+ { key: 'price_plan_name', label: 'Price Plan' },
+ { key: 'price_plan_type', label: 'Price Plan Type' },
+ {
+ key: 'amount',
+ label: 'Amount',
+ format: 'number',
+ description: 'Unverified: most likely in the smallest currency unit (cents).',
+ },
+ { key: 'currency', label: 'Currency' },
+ { key: 'interval', label: 'Billing Interval' },
+ { key: 'interval_count', label: 'Interval Count', format: 'number' },
+ ],
+ },
+ ...listMeta,
+ ],
+};
+
+export const aiCreateContactOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'contact_id', label: 'Contact ID' },
+ { key: 'email', label: 'Email', format: 'email' },
+ { key: 'tags_assigned', label: 'Tags Assigned', format: 'number' },
+ { key: 'tags_failed', label: 'Tags Failed', format: 'number' },
+ {
+ key: 'tag_results',
+ label: 'Tag Results',
+ labelKey: 'tag_id',
+ listItems: [
+ { key: 'tag_id', label: 'Tag ID' },
+ { key: 'assigned', label: 'Assigned', format: 'boolean' },
+ { key: 'error', label: 'Error' },
+ ],
+ },
+ {
+ ...contactField,
+ description: 'The contact after its tags were assigned. If that re-read fails, the contact as created, without the new tags.',
+ },
+ ],
+};
+
+export const aiUpdateContactOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'contact_id', label: 'Contact ID' },
+ { key: 'updated_slugs', label: 'Updated Fields' },
+ { key: 'cleared_slugs', label: 'Cleared Fields' },
+ { key: 'locale_changed', label: 'Locale Changed', format: 'boolean' },
+ { ...contactField, description: 'The contact after the update.' },
+ ],
+};
+
+export const aiAddTagOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'assigned', label: 'Assigned', format: 'boolean' },
+ {
+ key: 'already_assigned',
+ label: 'Already Had Tag',
+ format: 'boolean',
+ description:
+ 'True only when Systeme.io rejected the call and the tag was confirmed on the contact. A normal repeat succeeds with this false.',
+ },
+ { key: 'contact_id', label: 'Contact ID' },
+ { key: 'tag_id', label: 'Tag ID' },
+ ],
+};
diff --git a/packages/pieces/community/systeme-io/src/lib/output-schemas.ts b/packages/pieces/community/systeme-io/src/lib/output-schemas.ts
index 6c64a874790..07a0255a8a4 100644
--- a/packages/pieces/community/systeme-io/src/lib/output-schemas.ts
+++ b/packages/pieces/community/systeme-io/src/lib/output-schemas.ts
@@ -216,7 +216,7 @@ export const removeTagFromContactActionOutputSchema: OutputSchema = {
],
};
-export const newContactTriggerOutputSchema: OutputSchema = { fields: contactFields };
+export const newContactTriggerOutputSchema: OutputSchema = { fields: contactFieldsWithTags };
export const newTagAddedToContactTriggerOutputSchema: OutputSchema = {
fields: [
@@ -237,3 +237,266 @@ export const newTagAddedToContactTriggerOutputSchema: OutputSchema = {
},
],
};
+
+const tagFields: OutputSchemaField[] = [
+ { key: 'id', label: 'Tag ID', description: 'Use this to tag or untag contacts in a later step.' },
+ { key: 'name', label: 'Name' },
+ { key: 'created_at', label: 'Created At', format: 'datetime' },
+];
+
+export const findContactsActionOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'contacts',
+ label: 'Contacts',
+ labelKey: 'email',
+ listItems: contactFieldsWithTags,
+ },
+ { key: 'count', label: 'Returned', format: 'number' },
+ {
+ key: 'has_more',
+ label: 'More Available',
+ format: 'boolean',
+ description: 'True when more contacts match than were returned.',
+ },
+ {
+ key: 'next_cursor',
+ label: 'Next Cursor',
+ description: 'Pass this as "Continue After" to fetch the next contacts. Empty when there are no more.',
+ },
+ ],
+};
+
+export const getContactActionOutputSchema: OutputSchema = { fields: contactFieldsWithTags };
+
+export const deleteResultOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'deleted', label: 'Deleted', format: 'boolean' },
+ {
+ key: 'not_found',
+ label: 'Already Gone',
+ format: 'boolean',
+ description: 'True when the record did not exist (already deleted), so nothing changed.',
+ },
+ { key: 'id', label: 'ID' },
+ ],
+};
+
+export const createTagActionOutputSchema: OutputSchema = {
+ fields: [
+ ...tagFields,
+ {
+ key: 'created',
+ label: 'Was Created',
+ format: 'boolean',
+ description: 'False when a tag with this name already existed and was returned instead.',
+ },
+ ],
+};
+
+const enrollmentFields: OutputSchemaField[] = [
+ { key: 'id', label: 'Enrollment ID' },
+ {
+ key: 'access_type',
+ label: 'Access Type',
+ description: 'full_access, partial_access, dripping_content or partial_dripping_access.',
+ },
+ { key: 'active', label: 'Active', format: 'boolean' },
+ { key: 'course_id', label: 'Course ID' },
+ { key: 'course_name', label: 'Course Name' },
+ { key: 'contact_id', label: 'Contact ID' },
+ { key: 'contact_email', label: 'Contact Email', format: 'email' },
+];
+
+export const enrollmentOutputSchema: OutputSchema = { fields: enrollmentFields };
+
+export const removalResultOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'removed', label: 'Removed', format: 'boolean' },
+ { key: 'removed_count', label: 'Removed Count', format: 'number' },
+ {
+ key: 'removed_ids',
+ label: 'Removed IDs',
+ description: 'The enrollment or membership ids that were deleted.',
+ },
+ {
+ key: 'not_found',
+ label: 'Nothing to Remove',
+ format: 'boolean',
+ description: 'True when the contact had no matching enrollment or membership, so nothing changed.',
+ },
+ ],
+};
+
+export const addToCommunityOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'queued',
+ label: 'Queued',
+ format: 'boolean',
+ description: 'Systeme.io accepted the request and adds the member in the background.',
+ },
+ { key: 'community_id', label: 'Community ID' },
+ { key: 'contact_id', label: 'Contact ID' },
+ ],
+};
+
+export const cancelSubscriptionOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'cancelled',
+ label: 'Cancelled',
+ format: 'boolean',
+ description: 'True when Systeme.io accepted the cancellation. With "At the end of the billing period" the subscription stays active until the period ends.',
+ },
+ {
+ key: 'already_cancelled',
+ label: 'Was Already Cancelled',
+ format: 'boolean',
+ description: 'True when the subscription was already cancelled, or already set to end with the period, so nothing changed.',
+ },
+ { key: 'subscription_id', label: 'Subscription ID' },
+ { key: 'contact_id', label: 'Contact ID' },
+ { key: 'cancel_type', label: 'When', description: 'Now or WhenBillingPeriodEnds.' },
+ ],
+};
+
+const pricePlanFields: OutputSchemaField[] = [
+ { key: 'id', label: 'Price Plan ID' },
+ { key: 'name', label: 'Name' },
+ { key: 'innerName', label: 'Internal Name' },
+ { key: 'type', label: 'Type', description: 'For example one_shot or subscription.' },
+ {
+ key: 'amount',
+ label: 'Amount',
+ format: 'number',
+ description: 'Unverified: most likely in the smallest currency unit (cents).',
+ },
+ { key: 'currency', label: 'Currency' },
+ {
+ key: 'recurringOptions',
+ label: 'Recurring Options',
+ description: 'Empty for one-off prices.',
+ children: [
+ { key: 'interval', label: 'Interval' },
+ { key: 'intervalCount', label: 'Interval Count', format: 'number' },
+ { key: 'trialPeriod', label: 'Trial Period', format: 'number' },
+ { key: 'trialInterval', label: 'Trial Interval' },
+ { key: 'limitOfPayments', label: 'Limit of Payments', format: 'number' },
+ ],
+ },
+];
+
+export const saleTriggerOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'customer',
+ label: 'Customer',
+ children: [
+ { key: 'contactId', label: 'Contact ID', description: 'Use this with the contact actions.' },
+ { key: 'email', label: 'Email', format: 'email' },
+ { key: 'id', label: 'Customer ID' },
+ {
+ key: 'fields',
+ label: 'Form Fields',
+ dynamicKey: true,
+ description: 'Values the buyer entered, keyed by field slug (e.g. first_name, surname, country).',
+ },
+ { key: 'paymentProcessor', label: 'Payment Processor' },
+ { key: 'sourceUrl', label: 'Source URL', format: 'url' },
+ { key: 'clientIp', label: 'IP Address' },
+ ],
+ },
+ {
+ key: 'order',
+ label: 'Order',
+ children: [
+ { key: 'id', label: 'Order ID' },
+ { key: 'createdAt', label: 'Created At', format: 'datetime' },
+ { key: 'totalPrice', label: 'Total Price', format: 'number' },
+ { key: 'vat', label: 'VAT', format: 'number' },
+ { key: 'shippingFee', label: 'Shipping Fee', format: 'number' },
+ { key: 'discountAmount', label: 'Discount Amount', format: 'number' },
+ { key: 'discountType', label: 'Discount Type' },
+ ],
+ },
+ {
+ key: 'orderItem',
+ label: 'Order Item',
+ children: [
+ { key: 'id', label: 'Order Item ID' },
+ { key: 'createdAt', label: 'Created At', format: 'datetime' },
+ {
+ key: 'resources',
+ label: 'Resources',
+ description: 'What the purchase grants: a course, course bundle, physical product or tag.',
+ listItems: [
+ { key: 'course', label: 'Course', children: [{ key: 'id', label: 'Course ID' }, { key: 'name', label: 'Name' }] },
+ {
+ key: 'courseBundle',
+ label: 'Course Bundle',
+ children: [{ key: 'id', label: 'Bundle ID' }, { key: 'name', label: 'Name' }],
+ },
+ { key: 'enrollmentAccessType', label: 'Enrollment Access Type' },
+ {
+ key: 'physicalProduct',
+ label: 'Physical Product',
+ children: [{ key: 'id', label: 'Product ID' }, { key: 'name', label: 'Name' }],
+ },
+ { key: 'tag', label: 'Tag', children: [{ key: 'id', label: 'Tag ID' }, { key: 'name', label: 'Name' }] },
+ ],
+ },
+ ],
+ },
+ { key: 'pricePlan', label: 'Price Plan', children: pricePlanFields },
+ {
+ key: 'funnelStep',
+ label: 'Funnel Step',
+ children: [
+ { key: 'id', label: 'Funnel Step ID' },
+ { key: 'name', label: 'Name' },
+ { key: 'type', label: 'Type' },
+ { key: 'funnel', label: 'Funnel', children: [{ key: 'id', label: 'Funnel ID' }, { key: 'name', label: 'Name' }] },
+ ],
+ },
+ {
+ key: 'coupon',
+ label: 'Coupon',
+ description: 'Empty when no coupon was used.',
+ children: [
+ { key: 'code', label: 'Code' },
+ { key: 'innerName', label: 'Internal Name' },
+ { key: 'discountAmount', label: 'Discount Amount', format: 'number' },
+ { key: 'discountType', label: 'Discount Type' },
+ { key: 'expirationDate', label: 'Expires At', format: 'datetime' },
+ { key: 'limitOfUse', label: 'Limit of Use', format: 'number' },
+ ],
+ },
+ ],
+};
+
+export const newOptInTriggerOutputSchema: OutputSchema = { fields: contactFieldsWithTags };
+
+export const contactTagRemovedTriggerOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'tag',
+ label: 'Tag',
+ description: 'The tag that was just removed.',
+ children: [
+ { key: 'id', label: 'Tag ID' },
+ { key: 'name', label: 'Name' },
+ ],
+ },
+ {
+ key: 'contact',
+ label: 'Contact',
+ description: 'The contact it was removed from, with its remaining tags.',
+ children: contactFieldsWithTags,
+ },
+ ],
+};
+
+export const tagOutputFields = tagFields;
+export const enrollmentOutputFields = enrollmentFields;
+export const contactOutputFields = contactFieldsWithTags;
diff --git a/packages/pieces/community/systeme-io/src/lib/triggers/contact-tag-removed.ts b/packages/pieces/community/systeme-io/src/lib/triggers/contact-tag-removed.ts
new file mode 100644
index 00000000000..a0cc836bb3c
--- /dev/null
+++ b/packages/pieces/community/systeme-io/src/lib/triggers/contact-tag-removed.ts
@@ -0,0 +1,51 @@
+import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';
+import { systemeIoAuth } from '../common/auth';
+import { systemeWebhook } from '../common/webhook';
+import { contactSample } from '../common/samples';
+import { tagPicker } from '../common/dropdowns';
+import { contactTagRemovedTriggerOutputSchema } from '../output-schemas';
+
+const PREFIX = 'contact_tag_removed';
+
+export const contactTagRemoved = createTrigger({
+ auth: systemeIoAuth,
+ name: 'contact_tag_removed',
+ classification: 'READ',
+ displayName: 'Tag Removed from Contact',
+ description: 'Fires when a tag is removed from a contact (optionally only a chosen tag)',
+ aiMetadata: {
+ description:
+ 'Fires when a tag is removed from a Systeme.io contact, once per removal, delivering the contact (with its remaining tags) and the removed tag. Fires for every tag unless the optional tag filter is set. Use to react to a contact leaving a tag-based segment.',
+ },
+ props: {
+ tag: tagPicker({
+ required: false,
+ displayName: 'Only for Tag',
+ description: 'Optional. Pick a tag to run the flow only when that tag is removed. Leave empty to run for every tag.',
+ }),
+ },
+ sampleData: {
+ contact: { ...contactSample, tags: [{ id: 1, name: 'some_tag' }] },
+ tag: { id: 2, name: 'another_tag' },
+ },
+ outputSchema: contactTagRemovedTriggerOutputSchema,
+ type: TriggerStrategy.WEBHOOK,
+ async onEnable(context) {
+ await systemeWebhook.enable({
+ auth: context.auth,
+ webhookUrl: context.webhookUrl,
+ store: context.store,
+ event: 'CONTACT_TAG_REMOVED',
+ prefix: PREFIX,
+ });
+ },
+ async onDisable(context) {
+ await systemeWebhook.disable({ auth: context.auth, store: context.store, prefix: PREFIX });
+ },
+ async run(context) {
+ if (!(await systemeWebhook.accept({ store: context.store, payload: context.payload, prefix: PREFIX }))) {
+ return [];
+ }
+ return systemeWebhook.tagEvent({ body: context.payload.body, tagFilter: context.propsValue.tag });
+ },
+});
diff --git a/packages/pieces/community/systeme-io/src/lib/triggers/new-contact.ts b/packages/pieces/community/systeme-io/src/lib/triggers/new-contact.ts
index 70a0faca224..94736fbe089 100644
--- a/packages/pieces/community/systeme-io/src/lib/triggers/new-contact.ts
+++ b/packages/pieces/community/systeme-io/src/lib/triggers/new-contact.ts
@@ -1,7 +1,7 @@
import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';
import { systemeIoAuth } from '../common/auth';
-import { systemeIoCommon } from '../common/client';
-import { randomBytes } from 'crypto';
+import { systemeWebhook } from '../common/webhook';
+import { contactSample } from '../common/samples';
import { newContactTriggerOutputSchema } from '../output-schemas';
export const newContact = createTrigger({
@@ -14,81 +14,26 @@ export const newContact = createTrigger({
description: 'Fires when a new contact is created in the Systeme.io account, delivering the new contact record (email, fields, tags). Use to react to newly captured leads or subscribers.',
},
props: {},
- sampleData: {
- contact: {
- id: 12345,
- email: "[email protected]",
- registeredAt: "2024-01-01T00:00:00+00:00",
- locale: "en",
- sourceURL: null,
- unsubscribed: false,
- bounced: false,
- needsConfirmation: false,
- fields: [
- {
- fieldName: "first_name",
- slug: "first_name",
- value: "John"
- },
- {
- fieldName: "last_name",
- slug: "last_name",
- value: "Doe"
- },
- {
- fieldName: "phone_number",
- slug: "phone_number",
- value: "+1234567890"
- }
- ],
- tags: [
- {
- id: 1,
- name: "new_customer"
- },
- {
- id: 2,
- name: "email_subscriber"
- }
- ]
- }
- },
+ sampleData: contactSample,
outputSchema: newContactTriggerOutputSchema,
type: TriggerStrategy.WEBHOOK,
async onEnable(context) {
- const secret = randomBytes(32).toString('hex');
- const response = await systemeIoCommon.createWebhook({
- eventType: 'CONTACT_CREATED',
+ await systemeWebhook.enable({
+ auth: context.auth,
webhookUrl: context.webhookUrl,
- auth: context.auth.secret_text,
- secret: secret,
+ store: context.store,
+ event: 'CONTACT_CREATED',
+ prefix: 'new_contact',
});
-
- await context.store.put('new_contact_webhook_id', response.id);
- await context.store.put('new_contact_webhook_secret', secret);
},
async onDisable(context) {
- const webhookId = await context.store.get<string>('new_contact_webhook_id');
- if (webhookId) {
- await systemeIoCommon.deleteWebhook({
- webhookId,
- auth: context.auth.secret_text,
- });
- await context.store.put('new_contact_webhook_id', null);
- await context.store.put('new_contact_webhook_secret', null);
- }
+ await systemeWebhook.disable({ auth: context.auth, store: context.store, prefix: 'new_contact' });
},
async run(context) {
- const webhookSecret = await context.store.get<string>('new_contact_webhook_secret');
- const webhookSignatureHeader = context.payload.headers['x-webhook-signature'];
- const rawBody = context.payload.rawBody;
-
- if (!systemeIoCommon.verifyWebhookSignature(webhookSecret || undefined, webhookSignatureHeader, rawBody)) {
- console.warn('Systeme.io webhook signature verification failed');
+ if (!(await systemeWebhook.accept({ store: context.store, payload: context.payload, prefix: 'new_contact' }))) {
return [];
}
- const payload = context.payload.body as any;
- return [payload.contact || payload];
+ return [systemeWebhook.unwrap({ body: context.payload.body, key: 'contact' })];
}
});
diff --git a/packages/pieces/community/systeme-io/src/lib/triggers/new-opt-in.ts b/packages/pieces/community/systeme-io/src/lib/triggers/new-opt-in.ts
new file mode 100644
index 00000000000..f25e840136b
--- /dev/null
+++ b/packages/pieces/community/systeme-io/src/lib/triggers/new-opt-in.ts
@@ -0,0 +1,41 @@
+import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';
+import { systemeIoAuth } from '../common/auth';
+import { systemeWebhook } from '../common/webhook';
+import { contactSample } from '../common/samples';
+import { newOptInTriggerOutputSchema } from '../output-schemas';
+
+const PREFIX = 'new_opt_in';
+
+export const newOptIn = createTrigger({
+ auth: systemeIoAuth,
+ name: 'new_opt_in',
+ classification: 'READ',
+ displayName: 'New Opt-in',
+ description: 'Fires when a contact submits an opt-in form, including contacts that already exist',
+ aiMetadata: {
+ description:
+ 'Fires each time a contact opts in through a Systeme.io form, delivering the contact with its fields, tags and the source URL of the form. Unlike New Contact it can also fire for contacts that already existed, so use it to react to every form submission.',
+ },
+ props: {},
+ sampleData: { ...contactSample, sourceURL: 'https://webhook-optin.systeme.io/123456aa?utm_source=123' },
+ outputSchema: newOptInTriggerOutputSchema,
+ type: TriggerStrategy.WEBHOOK,
+ async onEnable(context) {
+ await systemeWebhook.enable({
+ auth: context.auth,
+ webhookUrl: context.webhookUrl,
+ store: context.store,
+ event: 'CONTACT_OPT_IN',
+ prefix: PREFIX,
+ });
+ },
+ async onDisable(context) {
+ await systemeWebhook.disable({ auth: context.auth, store: context.store, prefix: PREFIX });
+ },
+ async run(context) {
+ if (!(await systemeWebhook.accept({ store: context.store, payload: context.payload, prefix: PREFIX }))) {
+ return [];
+ }
+ return [systemeWebhook.unwrap({ body: context.payload.body, key: 'contact' })];
+ },
+});
diff --git a/packages/pieces/community/systeme-io/src/lib/triggers/new-sale.ts b/packages/pieces/community/systeme-io/src/lib/triggers/new-sale.ts
index 4013eddc1b3..99347115ddd 100644
--- a/packages/pieces/community/systeme-io/src/lib/triggers/new-sale.ts
+++ b/packages/pieces/community/systeme-io/src/lib/triggers/new-sale.ts
@@ -1,7 +1,8 @@
import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';
import { systemeIoAuth } from '../common/auth';
-import { systemeIoCommon } from '../common/client';
-import { randomBytes } from 'crypto';
+import { systemeWebhook } from '../common/webhook';
+import { saleSample } from '../common/samples';
+import { saleTriggerOutputSchema } from '../output-schemas';
export const newSale = createTrigger({
auth: systemeIoAuth,
@@ -10,79 +11,29 @@ export const newSale = createTrigger({
displayName: 'New Sale',
description: 'Fires when a new purchase is made within a funnel',
aiMetadata: {
- description: 'Fires when a new sale (purchase) is completed within a Systeme.io funnel, delivering the sale record including amount, product, funnel, contact, and payment details. Use to react to new orders or revenue events.',
+ description: 'Fires when a new sale (purchase) is completed within a Systeme.io funnel, delivering the customer (email, contact id, form fields), order, order item resources, price plan, funnel step and any coupon. Use to react to new orders or revenue events; use Sale Canceled for refunds and subscription cancellations.',
},
props: {},
- sampleData: {
- sale: {
- id: 67890,
- amount: 99.99,
- currency: "USD",
- status: "completed",
- createdAt: "2024-01-01T00:00:00+00:00",
- updatedAt: "2024-01-01T00:00:00+00:00",
- product: {
- id: 123,
- name: "Premium Course",
- type: "digital_product"
- },
- funnel: {
- id: 456,
- name: "Sales Funnel",
- step: "checkout"
- },
- contact: {
- id: 12345,
- email: "[email protected]",
- firstName: "John",
- lastName: "Doe"
- },
- payment: {
- method: "stripe",
- transactionId: "txn_1234567890",
- gateway: "stripe"
- },
- affiliate: {
- id: null,
- commission: null
- }
- }
- },
+ sampleData: saleSample,
+ outputSchema: saleTriggerOutputSchema,
type: TriggerStrategy.WEBHOOK,
async onEnable(context) {
- const secret = randomBytes(32).toString('hex');
- const response = await systemeIoCommon.createWebhook({
- eventType: 'SALE_NEW',
+ await systemeWebhook.enable({
+ auth: context.auth,
webhookUrl: context.webhookUrl,
- auth: context.auth.secret_text,
- secret: secret,
+ store: context.store,
+ event: 'SALE_NEW',
+ prefix: 'new_sale',
});
-
- await context.store.put('new_sale_webhook_id', response.id);
- await context.store.put('new_sale_webhook_secret', secret);
},
async onDisable(context) {
- const webhookId = await context.store.get<string>('new_sale_webhook_id');
- if (webhookId) {
- await systemeIoCommon.deleteWebhook({
- webhookId,
- auth: context.auth.secret_text,
- });
- await context.store.put('new_sale_webhook_id', null);
- await context.store.put('new_sale_webhook_secret', null);
- }
+ await systemeWebhook.disable({ auth: context.auth, store: context.store, prefix: 'new_sale' });
},
async run(context) {
- const webhookSecret = await context.store.get<string>('new_sale_webhook_secret');
- const webhookSignatureHeader = context.payload.headers['x-webhook-signature'];
- const rawBody = context.payload.rawBody;
-
- if (!systemeIoCommon.verifyWebhookSignature(webhookSecret || undefined, webhookSignatureHeader, rawBody)) {
- console.warn('Systeme.io webhook signature verification failed');
+ if (!(await systemeWebhook.accept({ store: context.store, payload: context.payload, prefix: 'new_sale' }))) {
return [];
}
- const payload = context.payload.body as any;
- return [payload.sale || payload];
+ return [systemeWebhook.unwrap({ body: context.payload.body, key: 'sale' })];
}
});
diff --git a/packages/pieces/community/systeme-io/src/lib/triggers/new-tag-added-to-contact.ts b/packages/pieces/community/systeme-io/src/lib/triggers/new-tag-added-to-contact.ts
index 518fb9cc21c..b2bd9b2d2c5 100644
--- a/packages/pieces/community/systeme-io/src/lib/triggers/new-tag-added-to-contact.ts
+++ b/packages/pieces/community/systeme-io/src/lib/triggers/new-tag-added-to-contact.ts
@@ -1,99 +1,48 @@
import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';
import { systemeIoAuth } from '../common/auth';
-import { systemeIoCommon } from '../common/client';
-import { randomBytes } from 'crypto';
+import { systemeWebhook } from '../common/webhook';
+import { contactSample } from '../common/samples';
import { newTagAddedToContactTriggerOutputSchema } from '../output-schemas';
+import { tagPicker } from '../common/dropdowns';
export const newTagAddedToContact = createTrigger({
auth: systemeIoAuth,
name: 'newTagAddedToContact',
classification: 'READ',
displayName: 'New Tag Added to Contact',
- description: 'Fires when a specific tag is assigned to a contact',
+ description: 'Fires when a tag is assigned to a contact (optionally only a chosen tag)',
aiMetadata: {
- description: 'Fires when a tag is added to a contact in Systeme.io, delivering the affected contact, the tag that was added, and when it was added. Use to react to a contact being labeled or entering a tag-based segment.',
+ description: 'Fires when a tag is added to a contact in Systeme.io, delivering the affected contact and the tag that was added. Fires for every tag unless the optional tag filter is set. Use to react to a contact being labeled or entering a tag-based segment.',
+ },
+ props: {
+ tag: tagPicker({
+ required: false,
+ displayName: 'Only for Tag',
+ description: 'Optional. Pick a tag to run the flow only when that tag is added. Leave empty to run for every tag.',
+ }),
},
- props: {},
sampleData: {
- contact: {
- id: 12345,
- email: "[email protected]",
- registeredAt: "2024-01-01T00:00:00+00:00",
- locale: "en",
- sourceURL: null,
- unsubscribed: false,
- bounced: false,
- needsConfirmation: false,
- fields: [
- {
- fieldName: "first_name",
- slug: "first_name",
- value: "John"
- },
- {
- fieldName: "last_name",
- slug: "last_name",
- value: "Doe"
- },
- {
- fieldName: "phone_number",
- slug: "phone_number",
- value: "+1234567890"
- }
- ],
- tags: [
- {
- id: 1,
- name: "existing_customer"
- },
- {
- id: 2,
- name: "VIP Customer"
- }
- ]
- },
- tag: {
- id: 2,
- name: "VIP Customer"
- },
- addedAt: "2024-01-01T10:30:00+00:00"
+ contact: contactSample,
+ tag: { id: 2, name: 'another_tag' },
},
outputSchema: newTagAddedToContactTriggerOutputSchema,
type: TriggerStrategy.WEBHOOK,
async onEnable(context) {
- const secret = randomBytes(32).toString('hex');
- const response = await systemeIoCommon.createWebhook({
- eventType: 'CONTACT_TAG_ADDED',
+ await systemeWebhook.enable({
+ auth: context.auth,
webhookUrl: context.webhookUrl,
- auth: context.auth.secret_text ,
- secret: secret,
+ store: context.store,
+ event: 'CONTACT_TAG_ADDED',
+ prefix: 'new_tag_added',
});
-
- await context.store.put('new_tag_added_webhook_id', response.id);
- await context.store.put('new_tag_added_webhook_secret', secret);
},
async onDisable(context) {
- const webhookId = await context.store.get<string>('new_tag_added_webhook_id');
- if (webhookId) {
- await systemeIoCommon.deleteWebhook({
- webhookId,
- auth: context.auth.secret_text,
- });
- await context.store.put('new_tag_added_webhook_id', null);
- await context.store.put('new_tag_added_webhook_secret', null);
- }
+ await systemeWebhook.disable({ auth: context.auth, store: context.store, prefix: 'new_tag_added' });
},
async run(context) {
- const webhookSecret = await context.store.get<string>('new_tag_added_webhook_secret');
- const webhookSignatureHeader = context.payload.headers['x-webhook-signature'];
- const rawBody = context.payload.rawBody;
-
- if (!systemeIoCommon.verifyWebhookSignature(webhookSecret || undefined, webhookSignatureHeader, rawBody)) {
- console.warn('Systeme.io webhook signature verification failed');
+ if (!(await systemeWebhook.accept({ store: context.store, payload: context.payload, prefix: 'new_tag_added' }))) {
return [];
}
-
- const payload = context.payload.body as any;
- return [payload];
+ return systemeWebhook.tagEvent({ body: context.payload.body, tagFilter: context.propsValue.tag });
}
});
diff --git a/packages/pieces/community/systeme-io/src/lib/triggers/sale-canceled.ts b/packages/pieces/community/systeme-io/src/lib/triggers/sale-canceled.ts
new file mode 100644
index 00000000000..a24ac9eae4b
--- /dev/null
+++ b/packages/pieces/community/systeme-io/src/lib/triggers/sale-canceled.ts
@@ -0,0 +1,41 @@
+import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';
+import { systemeIoAuth } from '../common/auth';
+import { systemeWebhook } from '../common/webhook';
+import { saleSample } from '../common/samples';
+import { saleTriggerOutputSchema } from '../output-schemas';
+
+const PREFIX = 'sale_canceled';
+
+export const saleCanceled = createTrigger({
+ auth: systemeIoAuth,
+ name: 'sale_canceled',
+ classification: 'READ',
+ displayName: 'Sale Canceled',
+ description: 'Fires when a sale is canceled (a subscription is canceled or a one-off payment is refunded)',
+ aiMetadata: {
+ description:
+ 'Fires when a Systeme.io sale is canceled, such as a subscription cancellation or a refund, delivering the same customer, order, order item, price plan, funnel step and coupon data as New Sale. Use to revoke access or update records when a purchase is reversed.',
+ },
+ props: {},
+ sampleData: saleSample,
+ outputSchema: saleTriggerOutputSchema,
+ type: TriggerStrategy.WEBHOOK,
+ async onEnable(context) {
+ await systemeWebhook.enable({
+ auth: context.auth,
+ webhookUrl: context.webhookUrl,
+ store: context.store,
+ event: 'SALE_CANCELED',
+ prefix: PREFIX,
+ });
+ },
+ async onDisable(context) {
+ await systemeWebhook.disable({ auth: context.auth, store: context.store, prefix: PREFIX });
+ },
+ async run(context) {
+ if (!(await systemeWebhook.accept({ store: context.store, payload: context.payload, prefix: PREFIX }))) {
+ return [];
+ }
+ return [systemeWebhook.unwrap({ body: context.payload.body, key: 'sale' })];
+ },
+});
diff --git a/packages/pieces/community/systeme-io/test/ai.test.ts b/packages/pieces/community/systeme-io/test/ai.test.ts
new file mode 100644
index 00000000000..eb2200a3942
--- /dev/null
+++ b/packages/pieces/community/systeme-io/test/ai.test.ts
@@ -0,0 +1,190 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { BASE, fail, ok, request, runAction, sendRequest } from './helpers';
+import { systemeIo } from '../src/index';
+import { systemeUpdateContact } from '../src/lib/actions/ai/update-contact';
+import { systemeAddTagToContact } from '../src/lib/actions/ai/add-tag-to-contact';
+import { systemeCreateContact } from '../src/lib/actions/ai/create-contact';
+import { systemeListTags } from '../src/lib/actions/ai/list-tags';
+import { systemeListSubscriptions } from '../src/lib/actions/ai/list-subscriptions';
+import { systemeRenameTag } from '../src/lib/actions/ai/rename-tag';
+
+vi.mock('@activepieces/pieces-common', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@activepieces/pieces-common')>();
+ return {
+ ...actual,
+ httpClient: { sendRequest: (...args: unknown[]) => sendRequest(...args) },
+ };
+});
+
+beforeEach(() => {
+ sendRequest.mockReset();
+});
+
+describe('piece metadata', () => {
+ const actions = Object.values(systemeIo.actions());
+
+ it('every action declares audience, classification and aiMetadata', () => {
+ for (const action of actions) {
+ expect(action.audience, action.name).toBeDefined();
+ expect(action.classification, action.name).toBeDefined();
+ expect(action.aiMetadata?.description, action.name).toBeTruthy();
+ expect(typeof action.aiMetadata?.idempotent, action.name).toBe('boolean');
+ }
+ });
+
+ it('ships 12 ai atomics and demotes the 3 twinned originals', () => {
+ expect(actions.filter((a) => a.audience === 'ai')).toHaveLength(12);
+ const audience = Object.fromEntries(actions.map((a) => [a.name, a.audience]));
+ expect(audience['createContact']).toBe('human');
+ expect(audience['updateContact']).toBe('human');
+ expect(audience['addTagToContact']).toBe('human');
+ expect(audience['findContactByEmail']).toBe('both');
+ expect(audience['removeTagFromContact']).toBe('both');
+ });
+
+ it('keeps every original action and trigger name', () => {
+ const names = actions.map((a) => a.name);
+ for (const name of ['createContact', 'addTagToContact', 'removeTagFromContact', 'findContactByEmail', 'updateContact']) {
+ expect(names).toContain(name);
+ }
+ expect(Object.keys(systemeIo.triggers())).toEqual(
+ expect.arrayContaining(['newContact', 'newSale', 'newTagAddedToContact', 'contact_tag_removed', 'new_opt_in', 'sale_canceled']),
+ );
+ });
+
+ it('every ai atomic takes ids as text, never as a dropdown', () => {
+ for (const action of actions.filter((a) => a.audience === 'ai')) {
+ for (const [key, prop] of Object.entries(action.props)) {
+ expect(String(prop.type), `${action.name}.${key}`).not.toMatch(/DROPDOWN/);
+ }
+ }
+ });
+});
+
+describe('systeme_update_contact (partial update, template section 6)', () => {
+ it('sends only the slugs given, turns empty/null into a clear, and omits locale when unset', async () => {
+ ok({ body: { id: 5, email: '[email protected]' } });
+ const result = await runAction({ action: systemeUpdateContact, props: {
+ contact_id: '5',
+ fields: [
+ { slug: 'phone_number', value: '+1555' },
+ { slug: 'country', value: '' },
+ { slug: 'company', value: null },
+ ],
+ } });
+ expect(request(0).method).toBe('PATCH');
+ expect(request(0).url).toBe(`${BASE}/contacts/5`);
+ expect(request(0).headers['Content-Type']).toBe('application/merge-patch+json');
+ expect(request(0).body).toEqual({
+ fields: [
+ { slug: 'phone_number', value: '+1555' },
+ { slug: 'country', value: null },
+ { slug: 'company', value: null },
+ ],
+ });
+ expect(result).toMatchObject({ updated_slugs: ['phone_number'], cleared_slugs: ['country', 'company'], locale_changed: false });
+ });
+
+ it('refuses an empty update before any request, and validates locale', async () => {
+ await expect(runAction({ action: systemeUpdateContact, props: { contact_id: '5' } })).rejects.toThrow(/Nothing to update/);
+ await expect(runAction({ action: systemeUpdateContact, props: { contact_id: '5', locale: 'ja' } })).rejects.toThrow(/jp/);
+ expect(sendRequest).not.toHaveBeenCalled();
+ });
+});
+
+describe('systeme_add_tag_to_contact', () => {
+ it('converges when the tag is already on the contact (422 + re-read)', async () => {
+ fail({ status: 422, body: { detail: 'Tag already assigned' } });
+ ok({ body: { id: 5, email: '[email protected]', tags: [{ id: 9, name: 'vip' }] } });
+ expect(await runAction({ action: systemeAddTagToContact, props: { contact_id: '5', tag_id: '9' } })).toEqual({
+ assigned: true,
+ already_assigned: true,
+ contact_id: 5,
+ tag_id: 9,
+ });
+ });
+
+ it('rethrows a 422 when the tag is not on the contact', async () => {
+ fail({ status: 422, body: { detail: 'Invalid tag' } });
+ ok({ body: { id: 5, email: '[email protected]', tags: [] } });
+ await expect(runAction({ action: systemeAddTagToContact, props: { contact_id: '5', tag_id: '9' } })).rejects.toThrow(/Invalid tag/);
+ });
+});
+
+describe('systeme_create_contact', () => {
+ it('creates, then reports tag failures per tag instead of failing', async () => {
+ ok({ body: { id: 42, email: '[email protected]', tags: [] }, status: 201 });
+ ok({ body: undefined, status: 204 });
+ fail({ status: 422, body: { detail: 'Tag not found' } });
+ const result = await runAction({ action: systemeCreateContact, props: {
+ email: ' [email protected] ',
+ locale: 'fr',
+ fields: [{ slug: 'first_name', value: 'Zoë' }, { slug: 'surname', value: '' }],
+ tag_ids: ['1', '2'],
+ } });
+ expect(request(0).body).toEqual({ email: '[email protected]', locale: 'fr', fields: [{ slug: 'first_name', value: 'Zoë' }] });
+ expect(request(1).url).toBe(`${BASE}/contacts/42/tags`);
+ expect(result).toMatchObject({
+ contact_id: 42,
+ tags_assigned: 1,
+ tags_failed: 1,
+ tag_results: [
+ { tag_id: 1, assigned: true, error: null },
+ { tag_id: 2, assigned: false },
+ ],
+ });
+ });
+});
+
+describe('list inputs', () => {
+ it('systeme_update_contact refuses fields that are not a list, before any request', async () => {
+ await expect(runAction({ action: systemeUpdateContact, props: { contact_id: '5', fields: 'phone_number=1' } })).rejects.toThrow(/fields must be a list/);
+ expect(sendRequest).not.toHaveBeenCalled();
+ });
+});
+
+describe('list atomics', () => {
+ it('systeme_list_tags flattens rows and returns a cursor', async () => {
+ ok({ body: { items: [{ id: 3, name: 'a', createdAt: '2026-01-01T00:00:00+00:00' }], hasMore: true } });
+ const result = await runAction({ action: systemeListTags, props: { query: 'a', max_results: 1 } });
+ expect(request(0).queryParams).toEqual({ query: 'a', limit: '100' });
+ expect(result).toEqual({
+ tags: [{ id: 3, name: 'a', created_at: '2026-01-01T00:00:00+00:00' }],
+ count: 1,
+ has_more: true,
+ next_cursor: 3,
+ });
+ });
+
+ it('systeme_list_subscriptions requires a contact and flattens the price plan', async () => {
+ await expect(runAction({ action: systemeListSubscriptions, props: { contact_id: '' } })).rejects.toThrow(/contact_id/);
+ ok({ body: {
+ items: [
+ {
+ id: 8,
+ status: 'active',
+ createdAt: 'c',
+ cancelledAt: null,
+ completedAt: null,
+ pricePlan: { id: 1, name: 'Monthly', type: 'subscription', amount: 1900, currency: 'eur', recurringOptions: { interval: 'month', intervalCount: 1 } },
+ },
+ ],
+ hasMore: false,
+ } });
+ const result = await runAction({ action: systemeListSubscriptions, props: { contact_id: '12' } });
+ expect(request(0).queryParams).toEqual({ contact: '12', limit: '100' });
+ expect(result).toMatchObject({
+ subscriptions: [{ id: 8, status: 'active', price_plan_name: 'Monthly', amount: 1900, currency: 'eur', interval: 'month', interval_count: 1 }],
+ count: 1,
+ has_more: false,
+ next_cursor: null,
+ });
+ });
+
+ it('systeme_rename_tag uses PUT with only the name', async () => {
+ ok({ body: { id: 3, name: 'b', createdAt: 'x' } });
+ await runAction({ action: systemeRenameTag, props: { tag_id: '3', name: ' b ' } });
+ expect(request(0).method).toBe('PUT');
+ expect(request(0).body).toEqual({ name: 'b' });
+ });
+});
diff --git a/packages/pieces/community/systeme-io/test/helpers.ts b/packages/pieces/community/systeme-io/test/helpers.ts
new file mode 100644
index 00000000000..00c0501d917
--- /dev/null
+++ b/packages/pieces/community/systeme-io/test/helpers.ts
@@ -0,0 +1,75 @@
+import crypto from 'crypto';
+import { vi } from 'vitest';
+
+export const API_KEY = 'systeme_test_key';
+export const AUTH = { type: 'SECRET_TEXT', secret_text: API_KEY };
+export const BASE = 'https://api.systeme.io/api';
+
+export const sendRequest = vi.fn();
+
+export function ok({ body, status = 200 }: { body: unknown; status?: number }) {
+ sendRequest.mockResolvedValueOnce({ status, headers: {}, body });
+}
+
+export function fail({ status, body = {} }: { status: number; body?: unknown }) {
+ sendRequest.mockRejectedValueOnce(new FakeHttpError({ status, body }));
+}
+
+export function request(index: number) {
+ return sendRequest.mock.calls[index][0];
+}
+
+export function memoryStore(initial: Record<string, unknown> = {}) {
+ const data = new Map<string, unknown>(Object.entries(initial));
+ return {
+ data,
+ store: {
+ put: async <T>(key: string, value: T) => {
+ data.set(key, value);
+ return value;
+ },
+ get: async <T>(key: string): Promise<T | null> => {
+ const value: unknown = data.get(key);
+ return value === undefined ? null : JSON.parse(JSON.stringify(value));
+ },
+ delete: async (key: string) => {
+ data.delete(key);
+ },
+ },
+ };
+}
+
+export function sign({ secret, body }: { secret: string; body: string }) {
+ return crypto.createHmac('sha256', secret).update(body, 'utf8').digest('hex');
+}
+
+export function runAction({ action, props }: { action: { run: unknown }; props: Record<string, unknown> }): Promise<unknown> {
+ return Promise.resolve(Reflect.apply(asFunction(action.run), action, [{ auth: AUTH, propsValue: props, store: memoryStore().store }]));
+}
+
+export function runHook({
+ trigger,
+ hook,
+ context,
+}: {
+ trigger: Record<string, unknown>;
+ hook: 'run' | 'onEnable' | 'onDisable';
+ context: Record<string, unknown>;
+}): Promise<unknown> {
+ return Promise.resolve(Reflect.apply(asFunction(trigger[hook]), trigger, [{ auth: AUTH, webhookUrl: 'https://ap.example.com/v1/webhooks/abc', propsValue: {}, ...context }]));
+}
+
+function asFunction(value: unknown): (...args: unknown[]) => unknown {
+ if (typeof value !== 'function') {
+ throw new Error('not a function');
+ }
+ return (...args: unknown[]) => Reflect.apply(value, undefined, args);
+}
+
+class FakeHttpError extends Error {
+ readonly response: { status: number; body: unknown };
+ constructor({ status, body }: { status: number; body: unknown }) {
+ super(JSON.stringify({ response: { status, body } }));
+ this.response = { status, body };
+ }
+}
diff --git a/packages/pieces/community/systeme-io/test/requests.test.ts b/packages/pieces/community/systeme-io/test/requests.test.ts
new file mode 100644
index 00000000000..5014efd6d71
--- /dev/null
+++ b/packages/pieces/community/systeme-io/test/requests.test.ts
@@ -0,0 +1,507 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { API_KEY, AUTH, BASE, fail, memoryStore, ok, request, runAction, runHook, sendRequest, sign } from './helpers';
+import { systemeIoAuth } from '../src/lib/common/auth';
+import { systemeIoInput } from '../src/lib/common/client';
+import { contactDropdownOptions, courseDropdown, courseModulesDropdown, tagPicker } from '../src/lib/common/dropdowns';
+import { getContact } from '../src/lib/actions/get-contact';
+import { deleteTag } from '../src/lib/actions/delete-tag';
+import { removeContactFromCommunity } from '../src/lib/actions/remove-contact-from-community';
+import { createContact } from '../src/lib/actions/create-contact';
+import { addTagToContact } from '../src/lib/actions/add-tag-to-contact';
+import { removeTagFromContact } from '../src/lib/actions/remove-tag-from-contact';
+import { findContacts } from '../src/lib/actions/find-contacts';
+import { updateContact } from '../src/lib/actions/update-contact';
+import { createTag } from '../src/lib/actions/create-tag';
+import { removeCourseEnrollment } from '../src/lib/actions/remove-course-enrollment';
+import { systemeGetTag } from '../src/lib/actions/ai/get-tag';
+import { systemeListCommunities } from '../src/lib/actions/ai/list-communities';
+import { systemeListCommunityMemberships } from '../src/lib/actions/ai/list-community-memberships';
+import { systemeListContactFields } from '../src/lib/actions/ai/list-contact-fields';
+import { systemeListCourses } from '../src/lib/actions/ai/list-courses';
+import { systemeListEnrollments } from '../src/lib/actions/ai/list-enrollments';
+import { systemeAddTagToContact } from '../src/lib/actions/ai/add-tag-to-contact';
+import { systemeCreateContact } from '../src/lib/actions/ai/create-contact';
+import { newContact } from '../src/lib/triggers/new-contact';
+import { newSale } from '../src/lib/triggers/new-sale';
+import { saleCanceled } from '../src/lib/triggers/sale-canceled';
+import { newOptIn } from '../src/lib/triggers/new-opt-in';
+import { newTagAddedToContact } from '../src/lib/triggers/new-tag-added-to-contact';
+import { contactTagRemoved } from '../src/lib/triggers/contact-tag-removed';
+
+vi.mock('@activepieces/pieces-common', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@activepieces/pieces-common')>();
+ return {
+ ...actual,
+ httpClient: { sendRequest: (...args: unknown[]) => sendRequest(...args) },
+ };
+});
+
+const CONTACT = { id: 5, email: '[email protected]', fields: [], tags: [{ id: 7, name: 'vip' }] };
+const SECRET = 'whsec';
+
+beforeEach(() => {
+ sendRequest.mockReset();
+});
+
+function options({ prop, input = {}, searchValue }: { prop: unknown; input?: Record<string, unknown>; searchValue?: string }): Promise<unknown> {
+ const fn: unknown = typeof prop === 'object' && prop !== null ? Reflect.get(prop, 'options') : undefined;
+ if (typeof fn !== 'function') {
+ throw new Error('not a dropdown');
+ }
+ return Promise.resolve(Reflect.apply(fn, prop, [{ auth: AUTH, ...input }, { searchValue }]));
+}
+
+function signed({ body, messageId }: { body: unknown; messageId: string }) {
+ const raw = JSON.stringify(body);
+ return { headers: { 'x-webhook-signature': sign({ secret: SECRET, body: raw }), 'x-webhook-message-id': messageId }, body, rawBody: raw };
+}
+
+describe('request shape of each action without one elsewhere', () => {
+ it('get_contact reads /contacts/{id}', async () => {
+ ok({ body: CONTACT });
+ expect(await runAction({ action: getContact, props: { contact_id: '5' } })).toEqual(CONTACT);
+ expect(sendRequest).toHaveBeenCalledTimes(1);
+ expect(request(0).method).toBe('GET');
+ expect(request(0).url).toBe(`${BASE}/contacts/5`);
+ expect(request(0).headers['X-API-Key']).toBe(API_KEY);
+ });
+
+ it('delete_tag deletes /tags/{id}', async () => {
+ ok({ body: undefined, status: 204 });
+ expect(await runAction({ action: deleteTag, props: { tag_id: 9 } })).toEqual({ deleted: true, not_found: false, id: 9 });
+ expect(sendRequest).toHaveBeenCalledTimes(1);
+ expect(request(0).method).toBe('DELETE');
+ expect(request(0).url).toBe(`${BASE}/tags/9`);
+ });
+
+ it('remove_contact_from_community lists by community and contact, then deletes only the matching membership', async () => {
+ ok({
+ body: {
+ items: [
+ { id: 77, community: { id: 3 }, contact: { id: 5 } },
+ { id: 78, community: { id: 3 }, contact: { id: 6 } },
+ ],
+ hasMore: false,
+ },
+ });
+ ok({ body: undefined, status: 204 });
+ expect(await runAction({ action: removeContactFromCommunity, props: { community_id: 3, contact_id: 5 } })).toEqual({
+ removed: true,
+ removed_count: 1,
+ removed_ids: [77],
+ not_found: false,
+ });
+ expect(sendRequest).toHaveBeenCalledTimes(2);
+ expect(request(0).url).toBe(`${BASE}/community/memberships`);
+ expect(request(0).queryParams).toEqual({ community: '3', contact: '5', limit: '100' });
+ expect(request(1).method).toBe('DELETE');
+ expect(request(1).url).toBe(`${BASE}/community/memberships/77`);
+ });
+
+ it('createContact (human) posts the contact, then assigns each existing tag', async () => {
+ ok({ body: { id: 42, email: '[email protected]' }, status: 201 });
+ ok({ body: undefined, status: 204 });
+ const result = await runAction({
+ action: createContact,
+ props: { email: '[email protected]', locale: 'fr', tagSource: 'existing', existingTags: [7] },
+ });
+ expect(sendRequest).toHaveBeenCalledTimes(2);
+ expect(request(0).method).toBe('POST');
+ expect(request(0).url).toBe(`${BASE}/contacts`);
+ expect(request(0).body).toEqual({ email: '[email protected]', locale: 'fr' });
+ expect(request(1).url).toBe(`${BASE}/contacts/42/tags`);
+ expect(request(1).body).toEqual({ tagId: 7 });
+ expect(result).toMatchObject({ contact: { id: 42 }, totalTagsAssigned: 1 });
+ });
+
+ it('addTagToContact (human) assigns an existing tag', async () => {
+ ok({ body: undefined, status: 204 });
+ expect(await runAction({ action: addTagToContact, props: { contactId: 5, tagSource: 'existing', existingTagId: 7 } })).toMatchObject({
+ success: true,
+ contactId: 5,
+ tagId: 7,
+ });
+ expect(sendRequest).toHaveBeenCalledTimes(1);
+ expect(request(0).method).toBe('POST');
+ expect(request(0).url).toBe(`${BASE}/contacts/5/tags`);
+ expect(request(0).body).toEqual({ tagId: 7 });
+ });
+
+ it('removeTagFromContact reads the tag name, then deletes /contacts/{id}/tags/{tagId}', async () => {
+ ok({ body: CONTACT });
+ ok({ body: undefined, status: 204 });
+ expect(await runAction({ action: removeTagFromContact, props: { contactId: 5, tagId: 7 } })).toMatchObject({ success: true, tagName: 'vip' });
+ expect(sendRequest).toHaveBeenCalledTimes(2);
+ expect(request(0).url).toBe(`${BASE}/contacts/5`);
+ expect(request(1).method).toBe('DELETE');
+ expect(request(1).url).toBe(`${BASE}/contacts/5/tags/7`);
+ });
+
+ it('systeme_get_tag reads /tags/{id} and flattens it', async () => {
+ ok({ body: { id: 9, name: 'vip', createdAt: '2026-09-01T00:00:00+00:00' } });
+ expect(await runAction({ action: systemeGetTag, props: { tag_id: '9' } })).toEqual({ id: 9, name: 'vip', created_at: '2026-09-01T00:00:00+00:00' });
+ expect(sendRequest).toHaveBeenCalledTimes(1);
+ expect(request(0).url).toBe(`${BASE}/tags/9`);
+ });
+
+ it('systeme_list_communities searches /community/communities', async () => {
+ ok({ body: { items: [{ id: 3, name: 'Club', path: 'club', domainName: 'x.systeme.io' }], hasMore: false } });
+ expect(await runAction({ action: systemeListCommunities, props: { query: ' club ' } })).toEqual({
+ communities: [{ id: 3, name: 'Club', path: 'club', domain_name: 'x.systeme.io' }],
+ count: 1,
+ has_more: false,
+ next_cursor: null,
+ });
+ expect(request(0).url).toBe(`${BASE}/community/communities`);
+ expect(request(0).queryParams).toEqual({ query: 'club', limit: '100' });
+ });
+
+ it('systeme_list_community_memberships filters by community and contact', async () => {
+ ok({ body: { items: [{ id: 77, community: { id: 3, name: 'Club' }, contact: { id: 5 } }], hasMore: false } });
+ expect(await runAction({ action: systemeListCommunityMemberships, props: { community_id: '3', contact_id: '5' } })).toMatchObject({
+ memberships: [{ id: 77, community_id: 3, community_name: 'Club', contact_id: 5 }],
+ count: 1,
+ });
+ expect(request(0).url).toBe(`${BASE}/community/memberships`);
+ expect(request(0).queryParams).toEqual({ community: '3', contact: '5', limit: '100' });
+ });
+
+ it('systeme_list_contact_fields reads /contact_fields', async () => {
+ ok({ body: { items: [{ slug: 'first_name', fieldName: 'First name' }], hasMore: false } });
+ expect(await runAction({ action: systemeListContactFields, props: {} })).toEqual({
+ fields: [{ slug: 'first_name', field_name: 'First name' }],
+ count: 1,
+ has_more: false,
+ });
+ expect(sendRequest).toHaveBeenCalledTimes(1);
+ expect(request(0).url).toBe(`${BASE}/contact_fields`);
+ });
+
+ it('systeme_list_courses sends the active filter as three states', async () => {
+ expect(String(systemeListCourses.props.active.type)).toBe('SHORT_TEXT');
+ ok({ body: { items: [], hasMore: false } });
+ await runAction({ action: systemeListCourses, props: { query: 'yoga', active: 'false' } });
+ expect(request(0).url).toBe(`${BASE}/school/courses`);
+ expect(request(0).queryParams).toEqual({ query: 'yoga', active: 'false', limit: '100' });
+ ok({ body: { items: [], hasMore: false } });
+ await runAction({ action: systemeListCourses, props: { active: '' } });
+ expect(request(1).queryParams).toEqual({ limit: '100' });
+ await expect(runAction({ action: systemeListCourses, props: { active: 'maybe' } })).rejects.toThrow(/active must be true or false/);
+ });
+
+ it('systeme_list_enrollments filters by course and contact, and again client-side', async () => {
+ ok({
+ body: {
+ items: [
+ { id: 1, accessType: 'full_access', course: { id: 2 }, contact: { id: 5 } },
+ { id: 2, accessType: 'full_access', course: { id: 3 }, contact: { id: 5 } },
+ ],
+ hasMore: false,
+ },
+ });
+ const result = await runAction({ action: systemeListEnrollments, props: { course_id: '2', contact_id: '5' } });
+ expect(request(0).url).toBe(`${BASE}/school/enrollments`);
+ expect(request(0).queryParams).toEqual({ course: '2', contact: '5', limit: '100' });
+ expect(result).toMatchObject({ enrollments: [{ id: 1, course_id: 2, contact_id: 5 }], count: 1 });
+ });
+});
+
+describe('triggers: payloads and filters', () => {
+ it('newTagAddedToContact returns {contact, tag} for the documented double nesting too', async () => {
+ const { store } = memoryStore({ new_tag_added_webhook_secret: SECRET });
+ const body = { contact: { contact: CONTACT }, tag: { id: 7, name: 'vip' } };
+ expect(await runHook({ trigger: newTagAddedToContact, hook: 'run', context: { store, payload: signed({ body, messageId: 'a1' }) } })).toEqual([
+ { contact: CONTACT, tag: { id: 7, name: 'vip' } },
+ ]);
+ });
+
+ it('contact_tag_removed honours Only for Tag', async () => {
+ const { store } = memoryStore({ contact_tag_removed_webhook_secret: SECRET });
+ const body = { contact: CONTACT, tag: { id: 7, name: 'vip' } };
+ const run = ({ tag, messageId }: { tag: unknown; messageId: string }) =>
+ runHook({ trigger: contactTagRemoved, hook: 'run', context: { store, payload: signed({ body, messageId }), propsValue: { tag } } });
+ expect(await run({ tag: 8, messageId: 'r1' })).toEqual([]);
+ expect(await run({ tag: 7, messageId: 'r2' })).toEqual([body]);
+ expect(await run({ tag: undefined, messageId: 'r3' })).toEqual([body]);
+ });
+
+ it('newSale returns the sale payload and unwraps a {sale} envelope', async () => {
+ const { store } = memoryStore({ new_sale_webhook_secret: SECRET });
+ const sale = { customer: { contactId: 5, email: '[email protected]' }, order: { id: 11 }, pricePlan: { id: 3, amount: 1200 } };
+ expect(await runHook({ trigger: newSale, hook: 'run', context: { store, payload: signed({ body: sale, messageId: 's1' }) } })).toEqual([sale]);
+ expect(await runHook({ trigger: newSale, hook: 'run', context: { store, payload: signed({ body: { sale }, messageId: 's2' }) } })).toEqual([sale]);
+ });
+
+ it('sale_canceled subscribes to SALE_CANCELED, verifies the signature and returns the payload as sent', async () => {
+ const { store, data } = memoryStore();
+ ok({ body: { id: 'wh_9' }, status: 201 });
+ await runHook({ trigger: saleCanceled, hook: 'onEnable', context: { store } });
+ expect(request(0).body.subscriptions).toEqual([{ event: 'SALE_CANCELED', schemaVersion: 2 }]);
+ expect(request(0).body.name).toBe('Activepieces Webhook - SALE_CANCELED - abc');
+ const secret = data.get('sale_canceled_webhook_secret');
+ if (typeof secret !== 'string') {
+ throw new Error('no secret stored');
+ }
+ const body = { customer: { contactId: 5 }, order: { id: 11 } };
+ const raw = JSON.stringify(body);
+ const payload = { headers: { 'x-webhook-signature': sign({ secret, body: raw }), 'x-webhook-message-id': 'c1' }, body, rawBody: raw };
+ expect(await runHook({ trigger: saleCanceled, hook: 'run', context: { store, payload } })).toEqual([body]);
+ const forged = { ...payload, headers: { 'x-webhook-signature': 'deadbeef', 'x-webhook-message-id': 'c2' } };
+ await expect(runHook({ trigger: saleCanceled, hook: 'run', context: { store, payload: forged } })).rejects.toThrow(/signature does not match/);
+ });
+
+ it('a published enable leaves the flow\'s test webhook alone, and a test enable leaves the published one alone', async () => {
+ const clash = { detail: 'name: This value is already used.', violations: [{ propertyPath: 'name', message: 'This value is already used.' }] };
+ const hooks = [
+ { id: 'wh_pub', name: 'Activepieces Webhook - CONTACT_CREATED - abc', url: 'https://ap.example.com/v1/webhooks/abc' },
+ { id: 'wh_test', name: 'Activepieces Webhook - CONTACT_CREATED - abc-test', url: 'https://ap.example.com/v1/webhooks/abc/test' },
+ ];
+ fail({ status: 422, body: clash });
+ ok({ body: { items: hooks, hasMore: false } });
+ ok({ body: undefined, status: 204 });
+ ok({ body: { id: 'wh_new' }, status: 201 });
+ await runHook({ trigger: newContact, hook: 'onEnable', context: { store: memoryStore().store } });
+ expect(sendRequest.mock.calls.filter((call) => call[0].method === 'DELETE').map((call) => call[0].url)).toEqual([`${BASE}/webhooks/wh_pub`]);
+
+ sendRequest.mockReset();
+ fail({ status: 422, body: clash });
+ ok({ body: { items: hooks, hasMore: false } });
+ ok({ body: undefined, status: 204 });
+ ok({ body: { id: 'wh_new2' }, status: 201 });
+ await runHook({
+ trigger: newContact,
+ hook: 'onEnable',
+ context: { store: memoryStore().store, webhookUrl: 'https://ap.example.com/v1/webhooks/abc/test' },
+ });
+ expect(sendRequest.mock.calls.filter((call) => call[0].method === 'DELETE').map((call) => call[0].url)).toEqual([`${BASE}/webhooks/wh_test`]);
+ });
+});
+
+describe('review fixes', () => {
+ it('rejects ids beyond the safe integer range instead of rounding them', () => {
+ expect(systemeIoInput.requireId({ value: '9007199254740991', name: 'Contact' })).toBe(9007199254740991);
+ expect(() => systemeIoInput.requireId({ value: '9007199254740993', name: 'Contact' })).toThrow(/positive whole number/);
+ });
+
+ it('auth validate does not double the period of a vendor message', async () => {
+ fail({ status: 500, body: { detail: 'Server error.' } });
+ const result: unknown = await Reflect.apply(systemeIoAuth.validate ?? (() => undefined), undefined, [{ auth: API_KEY }]);
+ expect(result).toEqual({
+ valid: false,
+ error: 'Authentication failed: Systeme.io API error 500: Server error. Please verify your API key is correct.',
+ });
+ });
+
+ it('systeme_add_tag_to_contact keeps the original 422 when the follow-up read fails', async () => {
+ fail({ status: 422, body: { detail: 'tagId: Tag with ID 9 not found.' } });
+ fail({ status: 500, body: { detail: 'boom' } });
+ await expect(runAction({ action: systemeAddTagToContact, props: { contact_id: '5', tag_id: '9' } })).rejects.toThrow(/422: tagId: Tag with ID 9 not found/);
+ });
+
+ it('systeme_create_contact returns the contact with the tags it just assigned, and the created one if that read fails', async () => {
+ ok({ body: { id: 42, email: '[email protected]', tags: [] }, status: 201 });
+ ok({ body: undefined, status: 204 });
+ ok({ body: { id: 42, email: '[email protected]', tags: [{ id: 7, name: 'vip' }] } });
+ const tagged = await runAction({ action: systemeCreateContact, props: { email: '[email protected]', tag_ids: ['7'] } });
+ expect(request(2).url).toBe(`${BASE}/contacts/42`);
+ expect(tagged).toMatchObject({ contact: { tags: [{ id: 7, name: 'vip' }] }, tags_assigned: 1 });
+
+ ok({ body: { id: 43, email: '[email protected]', tags: [] }, status: 201 });
+ ok({ body: undefined, status: 204 });
+ fail({ status: 500, body: { detail: 'boom' } });
+ expect(await runAction({ action: systemeCreateContact, props: { email: '[email protected]', tag_ids: ['7'] } })).toMatchObject({
+ contact: { id: 43, tags: [] },
+ tags_assigned: 1,
+ });
+ });
+
+ it('tag pickers search by name and say when the list is cut at 1,000', async () => {
+ const page = (start: number) => ({ items: Array.from({ length: 100 }, (_, i) => ({ id: start - i, name: `t${start - i}` })), hasMore: true });
+ for (let i = 0; i < 10; i++) ok({ body: page(5000 - i * 100) });
+ const state = await options({ prop: tagPicker({ required: false }) });
+ expect(state).toMatchObject({ disabled: false, placeholder: 'Showing the first 1,000 tags. Type to search, or map an id.' });
+
+ for (const prop of [findContacts.props.tag_ids, addTagToContact.props.existingTagId, createContact.props.existingTags]) {
+ expect(Reflect.get(prop, 'refreshOnSearch')).toBe(true);
+ }
+ sendRequest.mockReset();
+ ok({ body: { items: [{ id: 7, name: 'vip' }], hasMore: false } });
+ expect(await options({ prop: addTagToContact.props.existingTagId, input: { tagSource: 'existing' }, searchValue: 'vi' })).toEqual({
+ disabled: false,
+ placeholder: undefined,
+ options: [{ label: 'vip', value: 7 }],
+ });
+ expect(request(0).url).toBe(`${BASE}/tags`);
+ expect(request(0).queryParams).toEqual({ query: 'vi', limit: '100' });
+ });
+
+ it('the module picker pages /school/course-modules for the course', async () => {
+ ok({ body: { items: [{ id: 11, name: 'Intro' }, { id: 12, name: 'Deep dive' }], hasMore: true } });
+ ok({ body: { items: [{ id: 13, name: 'Wrap-up' }], hasMore: false } });
+ const state = await options({ prop: courseModulesDropdown, input: { course_id: 4, access_type: 'partial_access' } });
+ expect(request(0).url).toBe(`${BASE}/school/course-modules`);
+ expect(request(0).queryParams).toEqual({ courseId: '4', limit: '100' });
+ expect(request(1).queryParams).toEqual({ courseId: '4', limit: '100', startingAfter: '12' });
+ expect(state).toMatchObject({ options: [{ value: 11 }, { value: 12 }, { value: 13 }] });
+ });
+});
+
+describe('webhook schema versions', () => {
+ it('subscribes contact events at version 1 and sale events at version 2, as the plain-string form resolves them', async () => {
+ const cases: Array<[Record<string, unknown>, string, number]> = [
+ [newContact, 'CONTACT_CREATED', 1],
+ [newTagAddedToContact, 'CONTACT_TAG_ADDED', 1],
+ [contactTagRemoved, 'CONTACT_TAG_REMOVED', 1],
+ [newOptIn, 'CONTACT_OPT_IN', 1],
+ [newSale, 'SALE_NEW', 2],
+ [saleCanceled, 'SALE_CANCELED', 2],
+ ];
+ for (const [trigger, event, schemaVersion] of cases) {
+ sendRequest.mockReset();
+ ok({ body: { id: 'wh' }, status: 201 });
+ await runHook({ trigger, hook: 'onEnable', context: { store: memoryStore().store } });
+ expect(request(0).body.subscriptions).toEqual([{ event, schemaVersion }]);
+ }
+ });
+});
+
+describe('review round 2', () => {
+ const newest = {
+ items: [
+ { id: 3, email: '[email protected]', fields: [{ slug: 'first_name', value: 'Jane' }] },
+ { id: 2, email: '[email protected]', fields: [{ slug: 'first_name', value: 'Bob' }] },
+ ],
+ hasMore: false,
+ };
+
+ it('the contact picker does not send a partial email to the email filter, and never disables itself for it', async () => {
+ for (const search of ['jane@', '@']) {
+ sendRequest.mockReset();
+ ok({ body: newest });
+ const state = await contactDropdownOptions({ apiKey: API_KEY, searchValue: search });
+ expect(sendRequest).toHaveBeenCalledTimes(1);
+ expect(request(0).queryParams).toEqual({ limit: '100' });
+ expect(state.disabled).toBe(false);
+ }
+ expect((await contactDropdownOptions({ apiKey: API_KEY, searchValue: 'jane@' })).options).toEqual([]);
+ });
+
+ it('the contact picker treats a rejected email and an unsafe id as no match', async () => {
+ fail({ status: 422, body: { detail: 'email: This value is not a valid email address.' } });
+ expect(await contactDropdownOptions({ apiKey: API_KEY, searchValue: '[email protected]' })).toEqual({
+ disabled: false,
+ placeholder: 'No contact matches "[email protected]". Type the full email address or a contact id.',
+ options: [],
+ });
+ sendRequest.mockReset();
+ expect(await contactDropdownOptions({ apiKey: API_KEY, searchValue: '9007199254740993' })).toMatchObject({ disabled: false, options: [] });
+ expect(sendRequest).not.toHaveBeenCalled();
+ });
+
+ it('a name search filters the newest contacts by name or email', async () => {
+ ok({ body: newest });
+ expect(await contactDropdownOptions({ apiKey: API_KEY, searchValue: 'JAN' })).toEqual({
+ disabled: false,
+ placeholder: undefined,
+ options: [{ label: 'Jane ([email protected])', value: 3 }],
+ });
+ ok({ body: newest });
+ expect(await contactDropdownOptions({ apiKey: API_KEY, searchValue: 'zed' })).toMatchObject({ options: [], disabled: false });
+ });
+
+ it('a tag or course search reads one page per keystroke and says to type more', async () => {
+ const page = { items: Array.from({ length: 100 }, (_, i) => ({ id: 500 - i, name: `vip${i}` })), hasMore: true };
+ ok({ body: page });
+ const tags = await options({ prop: tagPicker({ required: false }), searchValue: 'vip' });
+ expect(sendRequest).toHaveBeenCalledTimes(1);
+ expect(tags).toMatchObject({ placeholder: 'Showing the first 100 matching tags. Type more to narrow the search.' });
+ sendRequest.mockReset();
+ ok({ body: page });
+ const courses = await options({ prop: courseDropdown, searchValue: 'vip' });
+ expect(sendRequest).toHaveBeenCalledTimes(1);
+ expect(request(0).queryParams).toEqual({ query: 'vip', limit: '100' });
+ expect(courses).toMatchObject({ placeholder: 'Showing the first 100 matching courses. Type more to narrow the search.' });
+ });
+
+ it('sale_canceled unwraps a {sale} envelope like New Sale', async () => {
+ const { store } = memoryStore({ sale_canceled_webhook_secret: SECRET });
+ const sale = { customer: { contactId: 5 }, order: { id: 11 } };
+ expect(await runHook({ trigger: saleCanceled, hook: 'run', context: { store, payload: signed({ body: { sale }, messageId: 'x1' }) } })).toEqual([sale]);
+ });
+
+ it('the human contact actions refuse a malformed contact id before any request', async () => {
+ await expect(runAction({ action: updateContact, props: { contactId: '1/../x', locale: 'de' } })).rejects.toThrow(/Contact ID must be a positive whole number/);
+ await expect(runAction({ action: addTagToContact, props: { contactId: '1/x', tagSource: 'new', newTagName: 'vip' } })).rejects.toThrow(/Contact ID/);
+ await expect(runAction({ action: removeTagFromContact, props: { contactId: 5, tagId: '7/x' } })).rejects.toThrow(/Tag ID/);
+ expect(sendRequest).not.toHaveBeenCalled();
+ });
+
+ it('create_tag creates nothing when the name search is cut off before an exact match', async () => {
+ const page = (start: number) => ({ items: Array.from({ length: 100 }, (_, i) => ({ id: start - i, name: `vip ${start - i}` })), hasMore: true });
+ for (let i = 0; i < 10; i++) ok({ body: page(5000 - i * 100) });
+ await expect(runAction({ action: createTag, props: { name: 'vip' } })).rejects.toThrow(/could not be ruled out. No tag was created/);
+ expect(sendRequest.mock.calls.every((call) => call[0].method === 'GET')).toBe(true);
+ });
+
+ it('a removal that fails part-way reports what it already removed', async () => {
+ ok({ body: { items: [{ id: 1, course: { id: 2 }, contact: { id: 5 } }, { id: 2, course: { id: 2 }, contact: { id: 5 } }], hasMore: false } });
+ ok({ body: undefined, status: 204 });
+ fail({ status: 500, body: { detail: 'boom' } });
+ await expect(runAction({ action: removeCourseEnrollment, props: { course_id: 2, contact_id: 5 } })).rejects.toThrow(
+ /^Removed 1, then removing 2 failed: Systeme\.io API error 500: boom\.$/,
+ );
+ });
+});
+
+describe('greptile round 1', () => {
+ it('both tag triggers keep every top-level field of the delivery', async () => {
+ const body = { contact: CONTACT, tag: { id: 7, name: 'vip' }, addedAt: '2026-09-30T10:00:00+00:00', source: 'api' };
+ const added = memoryStore({ new_tag_added_webhook_secret: SECRET });
+ expect(await runHook({ trigger: newTagAddedToContact, hook: 'run', context: { store: added.store, payload: signed({ body, messageId: 'g1' }) } })).toEqual([body]);
+ const removed = memoryStore({ contact_tag_removed_webhook_secret: SECRET });
+ expect(await runHook({ trigger: contactTagRemoved, hook: 'run', context: { store: removed.store, payload: signed({ body, messageId: 'g2' }) } })).toEqual([body]);
+ const nested = { contact: { contact: CONTACT }, tag: { id: 7, name: 'vip' }, addedAt: '2026-09-30T10:00:00+00:00' };
+ expect(await runHook({ trigger: newTagAddedToContact, hook: 'run', context: { store: added.store, payload: signed({ body: nested, messageId: 'g3' }) } })).toEqual([
+ { contact: CONTACT, tag: { id: 7, name: 'vip' }, addedAt: '2026-09-30T10:00:00+00:00' },
+ ]);
+ });
+
+ it('onEnable clears the stored id when saving the secret fails, and deletes the new webhook', async () => {
+ const data = new Map<string, unknown>();
+ const store = {
+ put: async (key: string, value: unknown) => {
+ if (key.endsWith('_webhook_secret')) {
+ throw new Error('store down');
+ }
+ data.set(key, value);
+ return value;
+ },
+ get: async (key: string) => data.get(key) ?? null,
+ delete: async (key: string) => {
+ data.delete(key);
+ },
+ };
+ ok({ body: { id: 'wh_5' }, status: 201 });
+ ok({ body: undefined, status: 204 });
+ await expect(runHook({ trigger: newContact, hook: 'onEnable', context: { store } })).rejects.toThrow('store down');
+ expect(request(1).method).toBe('DELETE');
+ expect(request(1).url).toBe(`${BASE}/webhooks/wh_5`);
+ expect(data.has('new_contact_webhook_id')).toBe(false);
+ });
+
+ it('a name search with no match says it only covered the newest 100 contacts', async () => {
+ ok({ body: { items: [{ id: 3, email: '[email protected]', fields: [] }], hasMore: false } });
+ expect(await contactDropdownOptions({ apiKey: API_KEY, searchValue: 'zed' })).toEqual({
+ disabled: false,
+ placeholder: 'No match for "zed" among the newest 100 contacts. Type the full email address or a contact id.',
+ options: [],
+ });
+ });
+
+ it('Find Contacts status filters describe Yes and No in plain words', () => {
+ expect(findContacts.props.bounced.description).toBe('Optional. Yes: only contacts whose emails bounced. No: only contacts whose emails did not bounce. Leave empty for both.');
+ expect(findContacts.props.unsubscribed.description).toBe(
+ 'Optional. Yes: only contacts unsubscribed from emails. No: only contacts still subscribed to emails. Leave empty for both.',
+ );
+ });
+});
diff --git a/packages/pieces/community/systeme-io/test/systeme-io.test.ts b/packages/pieces/community/systeme-io/test/systeme-io.test.ts
new file mode 100644
index 00000000000..b09fe3c9e87
--- /dev/null
+++ b/packages/pieces/community/systeme-io/test/systeme-io.test.ts
@@ -0,0 +1,649 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { API_KEY, BASE, fail, memoryStore, ok, request, runAction, runHook, sendRequest, sign } from './helpers';
+import { systemeIoCommon, systemeIoInput } from '../src/lib/common/client';
+import { contactDropdownOptions } from '../src/lib/common/dropdowns';
+import { findContactByEmail } from '../src/lib/actions/find-contact-by-email';
+import { updateContact } from '../src/lib/actions/update-contact';
+import { findContacts } from '../src/lib/actions/find-contacts';
+import { deleteContact } from '../src/lib/actions/delete-contact';
+import { createTag } from '../src/lib/actions/create-tag';
+import { enrollContactInCourse } from '../src/lib/actions/enroll-contact-in-course';
+import { removeCourseEnrollment } from '../src/lib/actions/remove-course-enrollment';
+import { addContactToCommunity } from '../src/lib/actions/add-contact-to-community';
+import { cancelSubscription } from '../src/lib/actions/cancel-subscription';
+import { removeContactFromCommunity } from '../src/lib/actions/remove-contact-from-community';
+import { newContact } from '../src/lib/triggers/new-contact';
+import { newSale } from '../src/lib/triggers/new-sale';
+import { newTagAddedToContact } from '../src/lib/triggers/new-tag-added-to-contact';
+import { contactTagRemoved } from '../src/lib/triggers/contact-tag-removed';
+import { newOptIn } from '../src/lib/triggers/new-opt-in';
+
+vi.mock('@activepieces/pieces-common', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@activepieces/pieces-common')>();
+ return {
+ ...actual,
+ httpClient: { sendRequest: (...args: unknown[]) => sendRequest(...args) },
+ };
+});
+
+const CONTACT = {
+ id: 501,
+ email: '[email protected]',
+ fields: [{ fieldName: 'First name', slug: 'first_name', value: 'Jane' }],
+ tags: [{ id: 7, name: 'vip' }],
+};
+
+beforeEach(() => {
+ sendRequest.mockReset();
+});
+
+describe('webhook signature (B6)', () => {
+ const secret = 'webhook-secret';
+
+ it('matches the normalized payload from the systeme.io docs byte for byte', () => {
+ const original = {
+ contact: {
+ id: 123,
+ sourceURL: 'http://example.com',
+ fields: [{ fieldName: 'Prénom', slug: 'first_name', value: 'Jean' }],
+ },
+ };
+ expect(systemeIoInput.phpJsonEncode(original)).toBe(
+ '{"contact":{"id":123,"sourceURL":"http:\\/\\/example.com","fields":[{"fieldName":"Pr\\u00e9nom","slug":"first_name","value":"Jean"}]}}',
+ );
+ });
+
+ it('escapes astral characters as a lowercase surrogate pair', () => {
+ expect(systemeIoInput.phpJsonEncode({ v: '😀' })).toBe('{"v":"\\ud83d\\ude00"}');
+ });
+
+ it('accepts a signature over the raw body (today\'s behaviour)', () => {
+ const raw = '{"contact":{"id":1,"email":"[email protected]"}}';
+ expect(systemeIoCommon.verifyWebhookSignature({ secret: secret, signatureHeader: sign({ secret, body: raw }), rawBody: raw })).toBe(true);
+ });
+
+ it('accepts a signature over the PHP-normalized body when the raw body has unescaped accents and slashes', () => {
+ const raw = '{\n "contact": {"id": 1, "sourceURL": "https://x.io/p", "fields": [{"fieldName": "Prénom", "value": "Zoë"}]}\n}';
+ const normalized = '{"contact":{"id":1,"sourceURL":"https:\\/\\/x.io\\/p","fields":[{"fieldName":"Pr\\u00e9nom","value":"Zo\\u00eb"}]}}';
+ expect(systemeIoCommon.verifyWebhookSignature({ secret: secret, signatureHeader: sign({ secret, body: normalized }), rawBody: raw })).toBe(true);
+ });
+
+ it('accepts an upper-case hex signature', () => {
+ const raw = '{"a":1}';
+ expect(systemeIoCommon.verifyWebhookSignature({ secret: secret, signatureHeader: sign({ secret, body: raw }).toUpperCase(), rawBody: raw })).toBe(true);
+ });
+
+ it('rejects a wrong secret, a tampered body, a missing header, a missing secret and non-hex junk', () => {
+ const raw = '{"a":1}';
+ const good = sign({ secret, body: raw });
+ expect(systemeIoCommon.verifyWebhookSignature({ secret: 'other', signatureHeader: good, rawBody: raw })).toBe(false);
+ expect(systemeIoCommon.verifyWebhookSignature({ secret: secret, signatureHeader: good, rawBody: '{"a":2}' })).toBe(false);
+ expect(systemeIoCommon.verifyWebhookSignature({ secret: secret, signatureHeader: undefined, rawBody: raw })).toBe(false);
+ expect(systemeIoCommon.verifyWebhookSignature({ secret: undefined, signatureHeader: good, rawBody: raw })).toBe(false);
+ expect(systemeIoCommon.verifyWebhookSignature({ secret: secret, signatureHeader: 'zz', rawBody: raw })).toBe(false);
+ });
+});
+
+describe('webhook triggers', () => {
+ const secret = 'abc123';
+ const body = { contact: { ...CONTACT } };
+ const raw = JSON.stringify(body);
+
+ function delivery({ signature, messageId }: { signature?: string; messageId?: string }) {
+ const headers: Record<string, string> = {};
+ if (signature) headers['x-webhook-signature'] = signature;
+ if (messageId) headers['x-webhook-message-id'] = messageId;
+ return { headers, body, rawBody: raw };
+ }
+
+ it('newContact still returns the unwrapped contact for a valid delivery', async () => {
+ const { store } = memoryStore({ new_contact_webhook_secret: secret });
+ const result = await runHook({ trigger: newContact, hook: 'run', context: {
+ store,
+ payload: delivery({ signature: sign({ secret, body: raw }), messageId: 'm1' }),
+ } });
+ expect(result).toEqual([CONTACT]);
+ });
+
+ it('a bad signature throws visibly (with the message id) instead of silently returning []', async () => {
+ const { store } = memoryStore({ new_contact_webhook_secret: secret });
+ await expect(
+ runHook({ trigger: newContact, hook: 'run', context: { store, payload: delivery({ signature: 'deadbeef', messageId: 'm-bad' }) } }),
+ ).rejects.toThrow(/signature does not match \(message id m-bad\)/);
+ });
+
+ it('a delivery with no stored secret throws with a re-publish hint', async () => {
+ const { store } = memoryStore();
+ await expect(
+ runHook({ trigger: newSale, hook: 'run', context: { store, payload: delivery({ signature: sign({ secret, body: raw }) }) } }),
+ ).rejects.toThrow(/no webhook secret/);
+ });
+
+ it('drops a retry of the same X-Webhook-Message-Id', async () => {
+ const { store } = memoryStore({ new_contact_webhook_secret: secret });
+ const payload = delivery({ signature: sign({ secret, body: raw }), messageId: 'dup-1' });
+ expect(await runHook({ trigger: newContact, hook: 'run', context: { store, payload } })).toHaveLength(1);
+ expect(await runHook({ trigger: newContact, hook: 'run', context: { store, payload } })).toEqual([]);
+ });
+
+ it('keeps the last 200 message ids, so a retry within that window is still dropped', async () => {
+ const { store, data } = memoryStore({ new_contact_webhook_secret: secret });
+ for (let i = 0; i < 205; i++) {
+ await runHook({ trigger: newContact, hook: 'run', context: { store, payload: delivery({ signature: sign({ secret, body: raw }), messageId: `m${i}` }) } });
+ }
+ const seen = data.get('new_contact_seen_message_ids');
+ expect(Array.isArray(seen) && seen.length).toBe(200);
+ const retry = delivery({ signature: sign({ secret, body: raw }), messageId: 'm60' });
+ expect(await runHook({ trigger: newContact, hook: 'run', context: { store, payload: retry } })).toEqual([]);
+ });
+
+ it('newTagAddedToContact fires for every tag when the filter is unset, and only for the chosen tag when set (B5)', async () => {
+ const tagBody = { contact: CONTACT, tag: { id: 7, name: 'vip' } };
+ const tagRaw = JSON.stringify(tagBody);
+ const payload = { headers: { 'x-webhook-signature': sign({ secret, body: tagRaw }) }, body: tagBody, rawBody: tagRaw };
+ const { store } = memoryStore({ new_tag_added_webhook_secret: secret });
+ expect(await runHook({ trigger: newTagAddedToContact, hook: 'run', context: { store, payload, propsValue: {} } })).toEqual([tagBody]);
+ expect(await runHook({ trigger: newTagAddedToContact, hook: 'run', context: { store, payload, propsValue: { tag: 7 } } })).toEqual([tagBody]);
+ expect(await runHook({ trigger: newTagAddedToContact, hook: 'run', context: { store, payload, propsValue: { tag: 8 } } })).toEqual([]);
+ });
+
+ it('contact_tag_removed unwraps the documented contact.contact nesting', async () => {
+ const nested = { contact: { contact: CONTACT }, tag: { id: 2, name: 'old' } };
+ const nestedRaw = JSON.stringify(nested);
+ const { store } = memoryStore({ contact_tag_removed_webhook_secret: secret });
+ const result = await runHook({ trigger: contactTagRemoved, hook: 'run', context: {
+ store,
+ payload: { headers: { 'x-webhook-signature': sign({ secret, body: nestedRaw }) }, body: nested, rawBody: nestedRaw },
+ } });
+ expect(result).toEqual([{ contact: CONTACT, tag: { id: 2, name: 'old' } }]);
+ });
+
+ it('new_opt_in returns the contact', async () => {
+ const { store } = memoryStore({ new_opt_in_webhook_secret: secret });
+ const result = await runHook({ trigger: newOptIn, hook: 'run', context: { store, payload: delivery({ signature: sign({ secret, body: raw }) }) } });
+ expect(result).toEqual([CONTACT]);
+ });
+
+ it('onEnable subscribes with the event name and stores id + secret under the original keys', async () => {
+ const { store, data } = memoryStore();
+ ok({ body: { id: 'wh_1' }, status: 201 });
+ await runHook({ trigger: newTagAddedToContact, hook: 'onEnable', context: { store } });
+ const req = request(0);
+ expect(req.method).toBe('POST');
+ expect(req.url).toBe(`${BASE}/webhooks`);
+ expect(req.body.subscriptions).toEqual([{ event: 'CONTACT_TAG_ADDED', schemaVersion: 1 }]);
+ expect(req.body.url).toBe('https://ap.example.com/v1/webhooks/abc');
+ expect(data.get('new_tag_added_webhook_id')).toBe('wh_1');
+ expect(data.get('new_tag_added_webhook_secret')).toBe(req.body.secret);
+ });
+
+ it('onEnable names the webhook after the flow, the same on every enable, with a test suffix while testing', async () => {
+ ok({ body: { id: 'wh_a' }, status: 201 });
+ await runHook({ trigger: newContact, hook: 'onEnable', context: { store: memoryStore().store } });
+ ok({ body: { id: 'wh_b' }, status: 201 });
+ await runHook({ trigger: newContact, hook: 'onEnable', context: { store: memoryStore().store } });
+ ok({ body: { id: 'wh_c' }, status: 201 });
+ await runHook({
+ trigger: newContact,
+ hook: 'onEnable',
+ context: { store: memoryStore().store, webhookUrl: 'https://ap.example.com/api/v1/webhooks/abc/test' },
+ });
+ ok({ body: { id: 'wh_d' }, status: 201 });
+ await runHook({
+ trigger: newContact,
+ hook: 'onEnable',
+ context: { store: memoryStore().store, webhookUrl: 'https://ap.example.com/api/v1/webhooks/other' },
+ });
+ expect(request(0).body.name).toBe('Activepieces Webhook - CONTACT_CREATED - abc');
+ expect(request(1).body.name).toBe('Activepieces Webhook - CONTACT_CREATED - abc');
+ expect(request(2).body.name).toBe('Activepieces Webhook - CONTACT_CREATED - abc-test');
+ expect(request(3).body.name).toBe('Activepieces Webhook - CONTACT_CREATED - other');
+ });
+
+ it('onEnable replaces a stale webhook that already points at this flow url, then retries', async () => {
+ const { store, data } = memoryStore();
+ fail({ status: 422, body: { detail: 'url: This value is already used.', violations: [{ propertyPath: 'url', message: 'This value is already used.' }] } });
+ ok({ body: { items: [
+ { id: 'wh_other', url: 'https://ap.example.com/v1/webhooks/zzz' },
+ { id: 'wh_stale', url: 'https://ap.example.com/v1/webhooks/abc' },
+ ], hasMore: false } });
+ ok({ body: undefined, status: 204 });
+ ok({ body: { id: 'wh_new' }, status: 201 });
+ await runHook({ trigger: contactTagRemoved, hook: 'onEnable', context: { store } });
+ expect(request(1).method).toBe('GET');
+ expect(request(2).method).toBe('DELETE');
+ expect(request(2).url).toBe(`${BASE}/webhooks/wh_stale`);
+ expect(request(3).method).toBe('POST');
+ expect(sendRequest).toHaveBeenCalledTimes(4);
+ expect(data.get('contact_tag_removed_webhook_id')).toBe('wh_new');
+ });
+
+ it('onEnable replaces this flow\'s leftover webhook on a name clash (old tunnel url), keeping other webhooks', async () => {
+ const { store, data } = memoryStore();
+ fail({ status: 422, body: { detail: 'name: This value is already used.', violations: [{ propertyPath: 'name', message: 'This value is already used.' }] } });
+ ok({ body: { items: [
+ { id: 'wh_legacy', name: 'Activepieces Webhook - CONTACT_CREATED', url: 'https://dead-tunnel.example/v1/webhooks/zzz' },
+ { id: 'wh_other_flow', name: 'Activepieces Webhook - CONTACT_CREATED - zzz', url: 'https://ap.example.com/v1/webhooks/zzz' },
+ { id: 'wh_ours', name: 'Activepieces Webhook - CONTACT_CREATED - abc', url: 'https://dead-tunnel.example/v1/webhooks/abc' },
+ ], hasMore: false } });
+ fail({ status: 404, body: { detail: 'Not Found' } });
+ ok({ body: { id: 'wh_new' }, status: 201 });
+ await runHook({ trigger: newContact, hook: 'onEnable', context: { store } });
+ expect(sendRequest).toHaveBeenCalledTimes(4);
+ expect(request(2).method).toBe('DELETE');
+ expect(request(2).url).toBe(`${BASE}/webhooks/wh_ours`);
+ expect(request(3).method).toBe('POST');
+ expect(data.get('new_contact_webhook_id')).toBe('wh_new');
+ });
+
+ it('onEnable rethrows a name clash when no webhook belongs to this flow', async () => {
+ fail({ status: 422, body: { detail: 'name: This value is already used.', violations: [{ propertyPath: 'name', message: 'This value is already used.' }] } });
+ ok({ body: { items: [{ id: 'wh_x', name: 'Something else', url: 'https://elsewhere.example/hook' }], hasMore: false } });
+ await expect(runHook({ trigger: newContact, hook: 'onEnable', context: { store: memoryStore().store } })).rejects.toThrow(/422: name: This value is already used/);
+ expect(sendRequest).toHaveBeenCalledTimes(2);
+ expect(request(1).method).toBe('GET');
+ });
+
+ it('onEnable rethrows other 422s without touching existing webhooks', async () => {
+ fail({ status: 422, body: { detail: 'subscriptions: This value is not valid.', violations: [{ propertyPath: 'subscriptions', message: 'This value is not valid.' }] } });
+ await expect(runHook({ trigger: newContact, hook: 'onEnable', context: { store: memoryStore().store } })).rejects.toThrow(/422: subscriptions: This value is not valid/);
+ expect(sendRequest).toHaveBeenCalledTimes(1);
+ });
+
+ it('contact_tag_removed passes the live single-nested payload through unchanged', async () => {
+ const live = { contact: { ...CONTACT, tags: [] }, tag: { id: 7, name: 'vip' } };
+ const liveRaw = JSON.stringify(live);
+ const { store } = memoryStore({ contact_tag_removed_webhook_secret: secret });
+ const result = await runHook({ trigger: contactTagRemoved, hook: 'run', context: {
+ store,
+ payload: { headers: { 'x-webhook-signature': sign({ secret, body: liveRaw }) }, body: live, rawBody: liveRaw },
+ } });
+ expect(result).toEqual([live]);
+ });
+
+ it('onEnable deletes the webhook it created when storing fails', async () => {
+ ok({ body: { id: 'wh_2' }, status: 201 });
+ ok({ body: undefined, status: 204 });
+ const store = {
+ put: async () => {
+ throw new Error('store down');
+ },
+ get: async () => null,
+ delete: async () => undefined,
+ };
+ await expect(runHook({ trigger: newContact, hook: 'onEnable', context: { store } })).rejects.toThrow('store down');
+ expect(request(1).method).toBe('DELETE');
+ expect(request(1).url).toBe(`${BASE}/webhooks/wh_2`);
+ });
+
+ it('onDisable treats 404 as deleted and clears the store (B9)', async () => {
+ const { store, data } = memoryStore({ new_sale_webhook_id: 'wh_3', new_sale_webhook_secret: 's' });
+ fail({ status: 404, body: { detail: 'Not Found' } });
+ await runHook({ trigger: newSale, hook: 'onDisable', context: { store } });
+ expect(data.get('new_sale_webhook_id')).toBeNull();
+ expect(data.get('new_sale_webhook_secret')).toBeNull();
+ });
+
+ it('onDisable keeps the id when the delete fails for another reason', async () => {
+ const { store, data } = memoryStore({ new_sale_webhook_id: 'wh_4', new_sale_webhook_secret: 's' });
+ fail({ status: 500, body: { detail: 'boom' } });
+ await expect(runHook({ trigger: newSale, hook: 'onDisable', context: { store } })).rejects.toThrow(/500/);
+ expect(data.get('new_sale_webhook_id')).toBe('wh_4');
+ });
+});
+
+describe('Find Contact by Email (B1)', () => {
+ it('uses the exact email filter: one request on a hit, same output keys', async () => {
+ ok({ body: { items: [CONTACT], hasMore: false } });
+ const result = await runAction({ action: findContactByEmail, props: { email: ' [email protected] ' } });
+ expect(sendRequest).toHaveBeenCalledTimes(1);
+ expect(request(0).url).toBe(`${BASE}/contacts`);
+ expect(request(0).queryParams).toEqual({ email: '[email protected]', limit: '10' });
+ expect(request(0).headers['X-API-Key']).toBe(API_KEY);
+ expect(result).toEqual({ success: true, contact: CONTACT, message: 'Contact found successfully' });
+ });
+
+ it('sends a mixed-case email as typed and matches ignoring case (the filter ignores case, Tier-2)', async () => {
+ ok({ body: { items: [CONTACT], hasMore: false } });
+ const result = await runAction({ action: findContactByEmail, props: { email: '[email protected]' } });
+ expect(sendRequest).toHaveBeenCalledTimes(1);
+ expect(request(0).queryParams.email).toBe('[email protected]');
+ expect(result).toMatchObject({ success: true, contact: CONTACT });
+ });
+
+ it('a miss costs one request, with no scan of every contact', async () => {
+ ok({ body: { items: [], hasMore: false } });
+ expect(await runAction({ action: findContactByEmail, props: { email: '[email protected]' } })).toMatchObject({ success: false });
+ expect(sendRequest).toHaveBeenCalledTimes(1);
+ });
+
+ it('returns the not-found shape on a miss', async () => {
+ ok({ body: { items: [], hasMore: false } });
+ expect(await runAction({ action: findContactByEmail, props: { email: '[email protected]' } })).toEqual({
+ success: false,
+ contact: null,
+ message: 'No contact found with email: [email protected]',
+ });
+ });
+});
+
+describe('pagination', () => {
+ it('pages with startingAfter = last id, keeps order, and reports a cursor when truncated', async () => {
+ ok({ body: { items: [{ id: 30 }, { id: 29 }], hasMore: true } });
+ ok({ body: { items: [{ id: 28 }, { id: 27 }], hasMore: true } });
+ const result = await systemeIoCommon.paginate<{ id: number }>({
+ auth: API_KEY,
+ url: '/tags',
+ query: { order: 'asc' },
+ maxItems: 3,
+ });
+ expect(request(0).queryParams).toEqual({ order: 'asc', limit: '100' });
+ expect(request(1).queryParams).toEqual({ order: 'asc', limit: '100', startingAfter: '29' });
+ expect(result).toEqual({ items: [{ id: 30 }, { id: 29 }, { id: 28 }], hasMore: true, nextCursor: 28 });
+ });
+
+ it('retries with a smaller page when the endpoint rejects the limit', async () => {
+ fail({ status: 422, body: {
+ detail: 'pagination.limit: Wrong value of pagination limit parameter',
+ violations: [{ propertyPath: 'pagination.limit', message: 'Wrong value of pagination limit parameter' }],
+ } });
+ ok({ body: { items: [{ id: 9 }], hasMore: false } });
+ const result = await systemeIoCommon.paginate({ auth: API_KEY, url: '/payment/subscriptions', query: { contact: 3 }, maxItems: 1000 });
+ expect(request(0).queryParams.limit).toBe('100');
+ expect(request(1).queryParams).toEqual({ contact: '3', limit: '50' });
+ expect(result).toEqual({ items: [{ id: 9 }], hasMore: false, nextCursor: null });
+ });
+
+ it('does not retry other 422s', async () => {
+ fail({ status: 422, body: { detail: 'contact: This value should be positive.' } });
+ await expect(systemeIoCommon.paginate({ auth: API_KEY, url: '/payment/subscriptions', maxItems: 10 })).rejects.toThrow(/should be positive/);
+ expect(sendRequest).toHaveBeenCalledTimes(1);
+ });
+
+ it('stops when hasMore is false', async () => {
+ ok({ body: { items: [{ id: 5 }], hasMore: false } });
+ const result = await systemeIoCommon.paginate({ auth: API_KEY, url: '/tags', maxItems: 1000 });
+ expect(sendRequest).toHaveBeenCalledTimes(1);
+ expect(result).toEqual({ items: [{ id: 5 }], hasMore: false, nextCursor: null });
+ });
+
+ it('clamps the page size to the documented 10-100 range', async () => {
+ ok({ body: { items: [], hasMore: false } });
+ await systemeIoCommon.paginate({ auth: API_KEY, url: '/tags', maxItems: 5, pageSize: 5 });
+ expect(request(0).queryParams.limit).toBe('10');
+ });
+
+ it('getTags pages past 100 tags (B2)', async () => {
+ ok({ body: { items: Array.from({ length: 100 }, (_, i) => ({ id: 200 - i, name: `t${i}` })), hasMore: true } });
+ ok({ body: { items: [{ id: 50, name: 'last' }], hasMore: false } });
+ const { items } = await systemeIoCommon.getTags({ auth: API_KEY });
+ expect(items).toHaveLength(101);
+ });
+
+ it('find_contacts maps filters and returns a continuation cursor', async () => {
+ ok({ body: { items: [CONTACT, { ...CONTACT, id: 500 }], hasMore: true } });
+ const result = await runAction({ action: findContacts, props: {
+ tag_ids: ['7', 8],
+ unsubscribed: 'no',
+ bounced: undefined,
+ registered_after: '2026-01-01T00:00:00Z',
+ max_results: 2,
+ } });
+ expect(request(0).queryParams).toEqual({
+ tags: '7,8',
+ unsubscribed: 'false',
+ registeredAfter: '2026-01-01T00:00:00.000Z',
+ limit: '100',
+ });
+ expect(result).toMatchObject({ count: 2, has_more: true, next_cursor: 500 });
+ });
+
+ it('rejects ids that are not positive integers before any request', async () => {
+ await expect(runAction({ action: deleteContact, props: { contact_id: '../webhooks/1' } })).rejects.toThrow(/positive whole number/);
+ expect(sendRequest).not.toHaveBeenCalled();
+ });
+});
+
+describe('errors (B8)', () => {
+ it('surfaces 422 violations', async () => {
+ fail({ status: 422, body: {
+ detail: 'email: This value is already used.',
+ violations: [{ propertyPath: 'email', message: 'This value is already used.', code: 'x' }],
+ } });
+ await expect(
+ systemeIoCommon.apiCall({ method: HttpMethod.POST, url: '/contacts', auth: API_KEY, body: { email: '[email protected]' } }),
+ ).rejects.toThrow(/^Systeme\.io API error 422: email: This value is already used\.$/);
+ });
+
+ it('keeps its own 404 text (single period, hint) and no body/error field for the engine to lift', async () => {
+ fail({ status: 404, body: { title: 'An error occurred', detail: 'Not Found' } });
+ const error = await systemeIoCommon
+ .apiCall({ method: HttpMethod.GET, url: '/tags/1', auth: API_KEY })
+ .catch((e: unknown) => e);
+ if (!(error instanceof Error)) {
+ throw new Error('expected an Error');
+ }
+ expect(error.message).toBe('Systeme.io API error 404: Not Found. The record was not found; check the id.');
+ expect(Reflect.get(error, 'body')).toBeUndefined();
+ expect(Reflect.get(error, 'error')).toBeUndefined();
+ });
+
+ it('tells a 401 (bad key) apart from a 403 (no access to this record)', async () => {
+ fail({ status: 401, body: { detail: 'Unauthorized' } });
+ await expect(systemeIoCommon.apiCall({ method: HttpMethod.GET, url: '/tags', auth: API_KEY })).rejects.toThrow(/401: Unauthorized\. Check that the API key is valid/);
+ fail({ status: 403, body: { detail: 'Forbidden' } });
+ const error = await systemeIoCommon
+ .apiCall({ method: HttpMethod.POST, url: '/payment/subscriptions/1/cancel', auth: API_KEY, body: {} })
+ .catch((e: unknown) => e);
+ if (!(error instanceof Error)) {
+ throw new Error('expected an Error');
+ }
+ expect(error.message).toBe('Systeme.io API error 403: Forbidden. This API key may not access this record or feature; check the id and your Systeme.io plan.');
+ });
+
+ it('adds a rate-limit hint on 429', async () => {
+ fail({ status: 429, body: { detail: 'Too many requests' } });
+ await expect(systemeIoCommon.apiCall({ method: HttpMethod.GET, url: '/tags', auth: API_KEY })).rejects.toThrow(/Rate limited/);
+ });
+});
+
+describe('contact dropdown', () => {
+ it('shows no options for an unknown id, but a disabled error for other failures', async () => {
+ fail({ status: 404, body: { detail: 'Not Found' } });
+ expect(await contactDropdownOptions({ apiKey: API_KEY, searchValue: '999' })).toMatchObject({ disabled: false, options: [] });
+ fail({ status: 401, body: { detail: 'Invalid API key' } });
+ const state = await contactDropdownOptions({ apiKey: API_KEY, searchValue: '999' });
+ expect(state.disabled).toBe(true);
+ expect(state.placeholder).toMatch(/401/);
+ });
+});
+
+describe('Update Contact locale (B7)', () => {
+ it('does not send locale when unset (unchanged request)', async () => {
+ ok({ body: CONTACT });
+ await runAction({ action: updateContact, props: { contactId: 501, customFields: [{ fieldSlug: 'country', fieldValue: 'US' }] } });
+ expect(request(0).body).toEqual({ fields: [{ slug: 'country', value: 'US' }] });
+ expect(request(0).headers['Content-Type']).toBe('application/merge-patch+json');
+ });
+
+ it('sends locale when set, even with no fields', async () => {
+ ok({ body: CONTACT });
+ await runAction({ action: updateContact, props: { contactId: 501, locale: 'fr' } });
+ expect(request(0).body).toEqual({ locale: 'fr' });
+ });
+});
+
+describe('both actions', () => {
+ it('delete_contact converges on 404', async () => {
+ fail({ status: 404, body: { detail: 'Not Found' } });
+ expect(await runAction({ action: deleteContact, props: { contact_id: 501 } })).toEqual({ deleted: false, not_found: true, id: 501 });
+ });
+
+ it('create_tag returns the existing tag (exact, case-insensitive) without creating', async () => {
+ ok({ body: { items: [{ id: 3, name: 'Webinar 2026 extra' }, { id: 4, name: 'webinar 2026', createdAt: '2026-01-01T00:00:00+00:00' }], hasMore: false } });
+ const result = await runAction({ action: createTag, props: { name: ' Webinar 2026 ' } });
+ expect(sendRequest).toHaveBeenCalledTimes(1);
+ expect(request(0).queryParams.query).toBe('Webinar 2026');
+ expect(result).toEqual({ id: 4, name: 'webinar 2026', created_at: '2026-01-01T00:00:00+00:00', created: false });
+ });
+
+ it('create_tag creates when no exact match exists, and refuses names over 64 chars', async () => {
+ ok({ body: { items: [{ id: 3, name: 'Webinar 2026 extra' }], hasMore: false } });
+ ok({ body: { id: 9, name: 'Webinar 2026', createdAt: 'x' }, status: 201 });
+ expect(await runAction({ action: createTag, props: { name: 'Webinar 2026' } })).toMatchObject({ id: 9, created: true });
+ expect(request(1).body).toEqual({ name: 'Webinar 2026' });
+ await expect(runAction({ action: createTag, props: { name: 'x'.repeat(65) } })).rejects.toThrow(/64/);
+ });
+
+ it('find_contacts and enroll_contact_in_course send id lists as numbers and refuse a non-list before any request', async () => {
+ ok({ body: { items: [], hasMore: false } });
+ await runAction({ action: findContacts, props: { tag_ids: [7, '8'] } });
+ expect(request(0).queryParams.tags).toBe('7,8');
+ ok({ body: { id: 78, accessType: 'partial_access', course: { id: 1 }, contact: { id: 2 } }, status: 201 });
+ await runAction({ action: enrollContactInCourse, props: { course_id: 1, contact_id: 2, access_type: 'partial_access', modules: ['5', 6] } });
+ expect(request(1).body).toEqual({ contactId: 2, accessType: 'partial_access', modules: [5, 6] });
+ await expect(runAction({ action: findContacts, props: { tag_ids: '7' } })).rejects.toThrow(/must be a list of ids/);
+ expect(sendRequest).toHaveBeenCalledTimes(2);
+ });
+
+ it('enroll_contact_in_course requires modules for partial access and omits them for full access', async () => {
+ await expect(
+ runAction({ action: enrollContactInCourse, props: { course_id: 1, contact_id: 2, access_type: 'partial_access', modules: [] } }),
+ ).rejects.toThrow(/at least one module/);
+ ok({ body: { id: 77, accessType: 'full_access', active: true, course: { id: 1, name: 'C' }, contact: { id: 2, email: '[email protected]' } }, status: 201 });
+ const result = await runAction({ action: enrollContactInCourse, props: { course_id: 1, contact_id: 2, access_type: 'full_access', modules: [5] } });
+ expect(request(0).url).toBe(`${BASE}/school/courses/1/enrollments`);
+ expect(request(0).body).toEqual({ contactId: 2, accessType: 'full_access' });
+ expect(result).toEqual({
+ id: 77,
+ access_type: 'full_access',
+ active: true,
+ course_id: 1,
+ course_name: 'C',
+ contact_id: 2,
+ contact_email: '[email protected]',
+ });
+ });
+
+ it('remove_course_enrollment deletes only rows matching both course and contact', async () => {
+ ok({ body: {
+ items: [
+ { id: 10, course: { id: 1 }, contact: { id: 2 } },
+ { id: 11, course: { id: 99 }, contact: { id: 2 } },
+ ],
+ hasMore: false,
+ } });
+ ok({ body: undefined, status: 204 });
+ const result = await runAction({ action: removeCourseEnrollment, props: { course_id: 1, contact_id: 2 } });
+ expect(request(0).queryParams).toEqual({ course: '1', contact: '2', limit: '100' });
+ expect(sendRequest).toHaveBeenCalledTimes(2);
+ expect(request(1).url).toBe(`${BASE}/school/enrollments/10`);
+ expect(result).toEqual({ removed: true, removed_count: 1, removed_ids: [10], not_found: false });
+ });
+
+ it('remove_course_enrollment and remove_contact_from_community refuse a truncated list before deleting anything', async () => {
+ const page = (start: number) => ({ items: Array.from({ length: 100 }, (_, i) => ({ id: start - i, course: { id: 9 }, contact: { id: 9 } })), hasMore: true });
+ for (let i = 0; i < 10; i++) ok({ body: page(5000 - i * 100) });
+ await expect(runAction({ action: removeCourseEnrollment, props: { course_id: 1, contact_id: 2 } })).rejects.toThrow(/more than 1,000 matching rows/);
+ expect(sendRequest).toHaveBeenCalledTimes(10);
+ expect(sendRequest.mock.calls.every((call) => call[0].method === 'GET')).toBe(true);
+
+ sendRequest.mockReset();
+ for (let i = 0; i < 10; i++) ok({ body: page(5000 - i * 100) });
+ await expect(runAction({ action: removeContactFromCommunity, props: { community_id: 1, contact_id: 2 } })).rejects.toThrow(/Nothing was removed/);
+ expect(sendRequest.mock.calls.every((call) => call[0].method === 'GET')).toBe(true);
+ });
+
+ it('remove_course_enrollment reports not_found and deletes nothing when there is no match', async () => {
+ ok({ body: { items: [{ id: 11, course: { id: 99 }, contact: { id: 2 } }], hasMore: false } });
+ expect(await runAction({ action: removeCourseEnrollment, props: { course_id: 1, contact_id: 2 } })).toMatchObject({ not_found: true, removed_count: 0 });
+ expect(sendRequest).toHaveBeenCalledTimes(1);
+ });
+
+ it('add_contact_to_community returns queued on 202', async () => {
+ ok({ body: {}, status: 202 });
+ expect(await runAction({ action: addContactToCommunity, props: { community_id: 3, contact_id: 2 } })).toEqual({
+ queued: true,
+ community_id: 3,
+ contact_id: 2,
+ });
+ expect(request(0).body).toEqual({ contactId: 2 });
+ });
+
+ it('cancel_subscription checks the subscription belongs to the contact, then cancels at the end of the period by default', async () => {
+ ok({ body: { items: [{ id: 40, status: 'active', cancelledAt: null }], hasMore: false } });
+ ok({ body: undefined, status: 204 });
+ expect(await runAction({ action: cancelSubscription, props: { contact_id: 2, subscription_id: 40 } })).toEqual({
+ cancelled: true,
+ already_cancelled: false,
+ subscription_id: 40,
+ contact_id: 2,
+ cancel_type: 'WhenBillingPeriodEnds',
+ });
+ expect(sendRequest).toHaveBeenCalledTimes(2);
+ expect(request(0).url).toBe(`${BASE}/payment/subscriptions`);
+ expect(request(0).queryParams).toEqual({ contact: '2', limit: '100' });
+ expect(request(1).method).toBe('POST');
+ expect(request(1).url).toBe(`${BASE}/payment/subscriptions/40/cancel`);
+ expect(request(1).body).toEqual({ cancel: 'WhenBillingPeriodEnds' });
+ });
+
+ it('cancel_subscription refuses a subscription of another contact without cancelling anything', async () => {
+ ok({ body: { items: [{ id: 41, status: 'active', cancelledAt: null }], hasMore: false } });
+ await expect(runAction({ action: cancelSubscription, props: { contact_id: 2, subscription_id: 999 } })).rejects.toThrow(
+ /Subscription 999 does not belong to contact 2, so nothing was cancelled/,
+ );
+ expect(sendRequest).toHaveBeenCalledTimes(1);
+ expect(request(0).method).toBe('GET');
+ });
+
+ it('cancel_subscription reports an already cancelled subscription without a second cancel', async () => {
+ ok({ body: { items: [{ id: 40, status: 'cancelled', cancelledAt: '2026-09-01T00:00:00+00:00' }], hasMore: false } });
+ expect(await runAction({ action: cancelSubscription, props: { contact_id: 2, subscription_id: 40, cancel: 'Now' } })).toMatchObject({
+ cancelled: true,
+ already_cancelled: true,
+ cancel_type: 'Now',
+ });
+ expect(sendRequest).toHaveBeenCalledTimes(1);
+ });
+
+ it('cancel_subscription still sends the cancel for a scheduled end, and converges on its 422 only for the end-of-period option', async () => {
+ const scheduled = [{ id: 40, status: 'active', cancelledAt: '2026-09-01T00:00:00+00:00' }];
+ ok({ body: { items: scheduled, hasMore: false } });
+ ok({ body: undefined, status: 204 });
+ expect(await runAction({ action: cancelSubscription, props: { contact_id: 2, subscription_id: 40 } })).toMatchObject({
+ cancelled: true,
+ already_cancelled: false,
+ });
+ expect(sendRequest).toHaveBeenCalledTimes(2);
+ expect(request(1).body).toEqual({ cancel: 'WhenBillingPeriodEnds' });
+
+ sendRequest.mockReset();
+ ok({ body: { items: scheduled, hasMore: false } });
+ fail({ status: 422, body: { detail: 'Subscription is already cancelled' } });
+ ok({ body: { items: scheduled, hasMore: false } });
+ expect(await runAction({ action: cancelSubscription, props: { contact_id: 2, subscription_id: 40 } })).toMatchObject({ already_cancelled: true });
+
+ sendRequest.mockReset();
+ ok({ body: { items: scheduled, hasMore: false } });
+ fail({ status: 422, body: { detail: 'Subscription is already cancelled' } });
+ ok({ body: { items: scheduled, hasMore: false } });
+ await expect(runAction({ action: cancelSubscription, props: { contact_id: 2, subscription_id: 40, cancel: 'Now' } })).rejects.toThrow(
+ /422: Subscription is already cancelled/,
+ );
+ expect(request(1).body).toEqual({ cancel: 'Now' });
+ });
+
+ it('cancel_subscription keeps the original 422 when the follow-up read fails, and rethrows it for an active subscription', async () => {
+ ok({ body: { items: [{ id: 40, status: 'active', cancelledAt: null }], hasMore: false } });
+ fail({ status: 422, body: { detail: 'Cannot cancel' } });
+ fail({ status: 500, body: { detail: 'boom' } });
+ await expect(runAction({ action: cancelSubscription, props: { contact_id: 2, subscription_id: 40 } })).rejects.toThrow(/422: Cannot cancel/);
+
+ ok({ body: { items: [{ id: 40, status: 'active', cancelledAt: null }], hasMore: false } });
+ fail({ status: 422, body: { detail: 'Cannot cancel' } });
+ ok({ body: { items: [{ id: 40, status: 'active', cancelledAt: null }], hasMore: false } });
+ await expect(runAction({ action: cancelSubscription, props: { contact_id: 2, subscription_id: 40 } })).rejects.toThrow(/422: Cannot cancel/);
+ });
+});
diff --git a/packages/pieces/community/systeme-io/vitest.config.ts b/packages/pieces/community/systeme-io/vitest.config.ts
new file mode 100644
index 00000000000..79c97261904
--- /dev/null
+++ b/packages/pieces/community/systeme-io/vitest.config.ts
@@ -0,0 +1,19 @@
+import path from 'path'
+import { defineConfig } from 'vitest/config'
+
+const repoRoot = path.resolve(__dirname, '../../../..')
+
+export default defineConfig({
+ root: __dirname,
+ test: {
+ globals: true,
+ environment: 'node',
+ include: ['test/**/*.test.ts'],
+ },
+ 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'),
+ },
+ },
+})