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(tarvent): let agents manage Tarvent contacts safely and fail steps on Tarvent errors (#16730)

Odai Ahmadbf74efc1b822
diff --git a/bun.lock b/bun.lock
index e85faa0140d..a67cf10e2a5 100644
--- a/bun.lock
+++ b/bun.lock
@@ -9111,16 +9111,18 @@
},
"packages/pieces/community/tarvent": {
"name": "@activepieces/piece-tarvent",
- "version": "0.1.8",
+ "version": "0.2.0",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
"@activepieces/pieces-common": "workspace:*",
"@activepieces/pieces-framework": "workspace:*",
+ "undici": "7.29.1",
"zod": "4.3.6",
},
"devDependencies": {
"tslib": "2.6.2",
+ "vitest": "3.2.6",
},
},
"packages/pieces/community/taskade": {
diff --git a/docs/install/reference/breaking-changes-unreleased.mdx b/docs/install/reference/breaking-changes-unreleased.mdx
index c5bfc8d8b8a..89ee3328860 100644
--- a/docs/install/reference/breaking-changes-unreleased.mdx
+++ b/docs/install/reference/breaking-changes-unreleased.mdx
@@ -8,6 +8,14 @@ Entries here move to [Breaking Changes](/install/reference/breaking-changes) aut
## What has changed?
+#### Tarvent 0.2.0: actions return the record itself, and Tarvent errors now fail the step
+
+Tarvent actions used to return the raw GraphQL envelope, so later steps read values like `data.createContact.id` or `data.audiences.nodes`. From Tarvent 0.2.0 actions return the record itself (for example `id`), and searches return `items`, `hasMore` and `nextCursor`. Tarvent reports errors with HTTP 200, and earlier versions treated those as success; upgraded steps now fail with Tarvent's message, and a connection with a wrong API key or account ID no longer saves. These 11 actions are no longer offered to AI agents as tools: **Create/Update Contact**, **Find Contact**, **Add/Remove Contact Tag**, **Add/Remove Contact From Audience Group**, **Add/Remove A Contact From A Journey**, **Start/Stop Journey**, **Create An Audience Group**, **Find Audience Group**, **Generate A Custom Event**, **Send A Transactional Email** and **Send Campaign**. Agents get new **(AI)** tools that take plain IDs instead; **Send A Transactional Email (AI)** always respects suppression filters, and **Create or Update Contact (AI)** never replaces existing groups or tags. Searches now return up to 50 results per call with paging: **Find Audience**, **Find Campaign** and **Find Audience Group** used to return up to 100, and **Find Journey** returned only 1. Step settings are unchanged. Existing connections keep working: the API key is now a masked secret under the same field.
+
+#### What you need to do
+
+When you upgrade a Tarvent step, re-map the fields later steps use from its output (drop the `data.<operation>` prefix; searches use `items`). If a Run Agent step or MCP server used one of the demoted actions as a tool, switch it to the matching (AI) tool. Steps keep running on the version they were built with until you upgrade them.
+
#### Asana 0.8.0 Create Task sends a plain date as an all-day due date and fails on unknown tags
Asana 0.8.0 changes what an existing **Create Task** step does once it is upgraded to that version. Steps keep running on the version they were built with until you upgrade them.
diff --git a/packages/pieces/community/tarvent/package.json b/packages/pieces/community/tarvent/package.json
index 496165954f3..92dcf84cd15 100644
--- a/packages/pieces/community/tarvent/package.json
+++ b/packages/pieces/community/tarvent/package.json
@@ -1,21 +1,24 @@
{
"name": "@activepieces/piece-tarvent",
- "version": "0.1.8",
+ "version": "0.2.0",
"main": "./dist/src/index.js",
"types": "./dist/src/index.d.ts",
"scripts": {
"build": "tsc -p tsconfig.lib.json && cp package.json dist/",
"bundle": "node ../../../../dist/packages/cli/src/index.js pieces bundle",
- "lint": "eslint 'src/**/*.ts'"
+ "lint": "eslint 'src/**/*.ts'",
+ "test": "vitest run"
},
"dependencies": {
"@activepieces/pieces-common": "workspace:*",
"@activepieces/pieces-framework": "workspace:*",
"zod": "4.3.6",
"@activepieces/core-piece-types": "workspace:*",
- "@activepieces/core-utils": "workspace:*"
+ "@activepieces/core-utils": "workspace:*",
+ "undici": "7.29.1"
},
"devDependencies": {
- "tslib": "2.6.2"
+ "tslib": "2.6.2",
+ "vitest": "3.2.6"
}
}
diff --git a/packages/pieces/community/tarvent/src/i18n/translation.json b/packages/pieces/community/tarvent/src/i18n/translation.json
index ddbb3dbc8b4..10c84761e53 100644
--- a/packages/pieces/community/tarvent/src/i18n/translation.json
+++ b/packages/pieces/community/tarvent/src/i18n/translation.json
@@ -1,44 +1,85 @@
{
- "Tarvent is an email marketing, automation, and email API platform that allows to you to send campaigns, manage contacts, automate your marketing, and more.": "Tarvent is an email marketing, automation, and email API platform that allows to you to send campaigns, manage contacts, automate your marketing, and more.",
+ "Tarvent is an email marketing, automation, and email API platform that allows you to send campaigns, manage contacts, automate your marketing, and more.": "Tarvent is an email marketing, automation, and email API platform that allows you to send campaigns, manage contacts, automate your marketing, and more.",
"Account ID": "Account ID",
"API Key": "API Key",
- "\nTo obtain your Tarvent Account ID and API Key, follow these steps:\n\n1. Log in to your Tarvent account.\n2. Go to **Account->API Keys** section.\n3. **Create an API key** and copy it. Make sure to give it the correct permissions.\n4. The **Account ID** is available to copy at the top right\n": "\nTo obtain your Tarvent Account ID and API Key, follow these steps:\n\n1. Log in to your Tarvent account.\n2. Go to **Account->API Keys** section.\n3. **Create an API key** and copy it. Make sure to give it the correct permissions.\n4. The **Account ID** is available to copy at the top right\n",
+ "\nTo obtain your Tarvent Account ID and API Key, follow these steps:\n\n1. Log in to your Tarvent account.\n2. Go to **Account->API Keys** section.\n3. **Create an API key** and copy it. Give it permission for everything your flows use (contacts, audiences, campaigns, journeys, webhooks, transactions).\n4. The **Account ID** is available to copy at the top right.\n\nNote: the Transactional Email API (Send A Transactional Email) is a paid Tarvent add-on that uses email API credits.\n": "\nTo obtain your Tarvent Account ID and API Key, follow these steps:\n\n1. Log in to your Tarvent account.\n2. Go to **Account->API Keys** section.\n3. **Create an API key** and copy it. Give it permission for everything your flows use (contacts, audiences, campaigns, journeys, webhooks, transactions).\n4. The **Account ID** is available to copy at the top right.\n\nNote: the Transactional Email API (Send A Transactional Email) is a paid Tarvent add-on that uses email API credits.\n",
"Create/Update Contact": "Create/Update Contact",
+ "Update Contact": "Update Contact",
+ "Find Contact": "Find Contact",
+ "List Contacts": "List Contacts",
+ "Delete Contact": "Delete Contact",
"Add/Remove Contact Tag": "Add/Remove Contact Tag",
"Add/Remove Contact From Audience Group": "Add/Remove Contact From Audience Group",
"Add Note To Contact": "Add Note To Contact",
+ "List Contact Notes": "List Contact Notes",
"Add/Remove A Contact From A Journey": "Add/Remove A Contact From A Journey",
"Subscribe/Unsubscribe Contact From Audience": "Subscribe/Unsubscribe Contact From Audience",
"Create An Audience Group": "Create An Audience Group",
"Start/Stop Journey": "Start/Stop Journey",
"Send A Transactional Email": "Send A Transactional Email",
+ "Send A Transactional Email (AI)": "Send A Transactional Email (AI)",
+ "Get Transaction": "Get Transaction",
"Send Campaign": "Send Campaign",
+ "Get Campaign Stats": "Get Campaign Stats",
"Generate A Custom Event": "Generate A Custom Event",
"Find Audience": "Find Audience",
"Find Audience Group": "Find Audience Group",
"Add Contact To Suppression List": "Add Contact To Suppression List",
+ "Remove From Suppression List": "Remove From Suppression List",
"Find Campaign": "Find Campaign",
- "Find Contact": "Find Contact",
"Find Custom Event": "Find Custom Event",
"Find Journey": "Find Journey",
- "This action is used to create or update a contact in an audience.": "This action is used to create or update a contact in an audience.",
- "Adds or removes a tag from contact.": "Adds or removes a tag from contact.",
+ "List Tags": "List Tags",
+ "Custom API Call": "Custom API Call",
+ "Create Audience Group (AI)": "Create Audience Group (AI)",
+ "Delete Contact (AI)": "Delete Contact (AI)",
+ "Find Audience Groups (AI)": "Find Audience Groups (AI)",
+ "Find Contact (AI)": "Find Contact (AI)",
+ "List Contacts (AI)": "List Contacts (AI)",
+ "Record Custom Event (AI)": "Record Custom Event (AI)",
+ "Add or Remove Contact From Group (AI)": "Add or Remove Contact From Group (AI)",
+ "Enter or Exit Contact From Journey (AI)": "Enter or Exit Contact From Journey (AI)",
+ "Add or Remove Contact Tags (AI)": "Add or Remove Contact Tags (AI)",
+ "Start or Stop Journey (AI)": "Start or Stop Journey (AI)",
+ "Update Contact (AI)": "Update Contact (AI)",
+ "Create or Update Contact (AI)": "Create or Update Contact (AI)",
+ "Creates a contact in an audience, or updates it if the email already exists.": "Creates a contact in an audience, or updates it if the email already exists.",
+ "Updates fields of an existing contact by its ID. Fields left empty are not changed (Tarvent does not clear fields through the API).": "Updates fields of an existing contact by its ID. Fields left empty are not changed (Tarvent does not clear fields through the API).",
+ "Finds one contact in an audience by email or by contact ID.": "Finds one contact in an audience by email or by contact ID.",
+ "Lists contacts in an audience, optionally only those in one group or segment.": "Lists contacts in an audience, optionally only those in one group or segment.",
+ "Permanently deletes a contact from an audience.": "Permanently deletes a contact from an audience.",
+ "Adds or removes tags on a contact.": "Adds or removes tags on a contact.",
"Adds or removes a contact from an audience group.": "Adds or removes a contact from an audience group.",
"Adds a note to a contact.": "Adds a note to a contact.",
+ "Lists the notes on a contact, newest first.": "Lists the notes on a contact, newest first.",
"Adds or removes the contact from a journey.": "Adds or removes the contact from a journey.",
- "Subscribes or unsubscribe a contact in an audience.": "Subscribes or unsubscribe a contact in an audience.",
+ "Subscribes or unsubscribes a contact in an audience.": "Subscribes or unsubscribes a contact in an audience.",
"Creates an audience group in the selected audience.": "Creates an audience group in the selected audience.",
"Starts or stops a journey.": "Starts or stops a journey.",
- "Sends a transactional email. NOTE: This will use your email API credits.": "Sends a transactional email. NOTE: This will use your email API credits.",
- "Sends a copy of a campaign.": "Sends a copy of a campaign.",
- "Generate a custom event in your Tarvent account.": "Generate a custom event in your Tarvent account.",
- "Finds an audience by name or tags.": "Finds an audience by name or tags.",
- "Finds an audience group by name.": "Finds an audience group by name.",
- "Creates a suppression filter in your account to suppress a contact.": "Creates a suppression filter in your account to suppress a contact.",
- "Finds a campaign by name, status or tags.": "Finds a campaign by name, status or tags.",
- "Finds a contact by your custom key data field (typically this is by email).": "Finds a contact by your custom key data field (typically this is by email).",
- "Finds a custom event by name.": "Finds a custom event by name.",
- "Finds a journey by name, status or tags.": "Finds a journey by name, status or tags.",
+ "Sends a transactional email. NOTE: This uses your Tarvent email API credits (a paid add-on).": "Sends a transactional email. NOTE: This uses your Tarvent email API credits (a paid add-on).",
+ "Sends a transactional email that always respects your suppression filters. Uses Tarvent email API credits (a paid add-on).": "Sends a transactional email that always respects your suppression filters. Uses Tarvent email API credits (a paid add-on).",
+ "Gets the delivery status of a transactional email.": "Gets the delivery status of a transactional email.",
+ "Sends a copy of a campaign to its audience now.": "Sends a copy of a campaign to its audience now.",
+ "Gets delivery and engagement stats for a campaign.": "Gets delivery and engagement stats for a campaign.",
+ "Records a custom event for a contact in your Tarvent account.": "Records a custom event for a contact in your Tarvent account.",
+ "Finds audiences by name or tags.": "Finds audiences by name or tags.",
+ "Finds static groups in an audience by name.": "Finds static groups in an audience by name.",
+ "Creates a suppression filter in your account so an email address receives no more email.": "Creates a suppression filter in your account so an email address receives no more email.",
+ "Removes an email address from your account suppression list.": "Removes an email address from your account suppression list.",
+ "Finds campaigns by name, status or tags.": "Finds campaigns by name, status or tags.",
+ "Finds custom events by name.": "Finds custom events by name.",
+ "Finds journeys by name, status or tags.": "Finds journeys by name, status or tags.",
+ "Lists the tags used in your account.": "Lists the tags used in your account.",
+ "Send a raw GraphQL request to Tarvent (POST /graphql with a JSON body of query and variables). The API key and account ID headers are added for you. Note: Tarvent reports GraphQL errors with HTTP 200, so check body.errors.": "Send a raw GraphQL request to Tarvent (POST /graphql with a JSON body of query and variables). The API key and account ID headers are added for you. Note: Tarvent reports GraphQL errors with HTTP 200, so check body.errors.",
+ "Creates a static group in an audience.": "Creates a static group in an audience.",
+ "Finds one contact by email or contact ID.": "Finds one contact by email or contact ID.",
+ "Lists contacts in an audience one page at a time.": "Lists contacts in an audience one page at a time.",
+ "Records a custom event for a contact.": "Records a custom event for a contact.",
+ "Adds a contact to, or removes it from, an audience group.": "Adds a contact to, or removes it from, an audience group.",
+ "Enters a contact into a journey, or removes it.": "Enters a contact into a journey, or removes it.",
+ "Starts or stops a whole journey.": "Starts or stops a whole journey.",
+ "Updates fields of an existing contact by its ID.": "Updates fields of an existing contact by its ID.",
+ "Creates a contact by email, or updates the existing one.": "Creates a contact by email, or updates the existing one.",
"Audience": "Audience",
"Email": "Email",
"Update existing contact": "Update existing contact",
@@ -56,6 +97,12 @@
"Country": "Country",
"Data fields": "Data fields",
"Contact ID": "Contact ID",
+ "New email": "New email",
+ "Language": "Language",
+ "Time zone": "Time zone",
+ "Contact email": "Contact email",
+ "Limit": "Limit",
+ "Cursor": "Cursor",
"Tag action": "Tag action",
"Add or remove": "Add or remove",
"Note": "Note",
@@ -79,41 +126,79 @@
"Message type": "Message type",
"Content": "Content",
"Ignore suppression filters": "Ignore suppression filters",
+ "Template ID": "Template ID",
+ "Transaction ID": "Transaction ID",
"Campaign": "Campaign",
+ "Campaign ID": "Campaign ID",
"Custom event": "Custom event",
"Audience name": "Audience name",
"Audience tags": "Audience tags",
"Email address": "Email address",
"Suppression reason": "Suppression reason",
+ "Suppression filter ID": "Suppression filter ID",
"Campaign name": "Campaign name",
"Campaign tags": "Campaign tags",
"Campaign status": "Campaign status",
- "Contact email": "Contact email",
"Custom event name": "Custom event name",
"Journey name": "Journey name",
"Journey tags": "Journey tags",
"Journey status": "Journey status",
- "Enter the contacts email. NOTE: If the audience uses a custom contact identifier and overwrite is enabled, then this will update the FIRST contact that matches the email.": "Enter the contacts email. NOTE: If the audience uses a custom contact identifier and overwrite is enabled, then this will update the FIRST contact that matches the email.",
+ "Method": "Method",
+ "Headers": "Headers",
+ "Query Parameters": "Query Parameters",
+ "Body Type": "Body Type",
+ "Body": "Body",
+ "Response is Binary": "Response is Binary",
+ "Return Error as Output": "Return Error as Output",
+ "Timeout": "Timeout",
+ "Follow redirects": "Follow redirects",
+ "Audience ID": "Audience ID",
+ "Name": "Name",
+ "Description": "Description",
+ "Public": "Public",
+ "Name contains": "Name contains",
+ "Group ID": "Group ID",
+ "Event key": "Event key",
+ "Journey ID": "Journey ID",
+ "City": "City",
+ "State / Region": "State / Region",
+ "Postal code": "Postal code",
+ "Update if exists": "Update if exists",
+ "Group IDs": "Group IDs",
+ "Custom fields": "Custom fields",
+ "Audience to add the contact to.": "Audience to add the contact to.",
+ "The contact's email. NOTE: If the audience uses a custom contact identifier and overwrite is enabled, then this will update the FIRST contact that matches the email.": "The contact's email. NOTE: If the audience uses a custom contact identifier and overwrite is enabled, then this will update the FIRST contact that matches the email.",
"Update the contact's profile if it already exists. Otherwise, return the \"Duplicate\" error.": "Update the contact's profile if it already exists. Otherwise, return the \"Duplicate\" error.",
- "Select whether to replace or only add to contact groups. NOTE: Add only will only add the contact to the groups they are not already in. Replace will remove the contact from all existing groups and add them to the selected groups.": "Select whether to replace or only add to contact groups. NOTE: Add only will only add the contact to the groups they are not already in. Replace will remove the contact from all existing groups and add them to the selected groups.",
- "Select whether to replace or only add to contact tags of an existing contact. NOTE: Add only will only add the tags the contact does not already have. Replace will replace all contact tags with the entered tags.": "Select whether to replace or only add to contact tags of an existing contact. NOTE: Add only will only add the tags the contact does not already have. Replace will replace all contact tags with the entered tags.",
- "Select which tags you would like to add to the contact.": "Select which tags you would like to add to the contact.",
- "The contacts first name.": "The contacts first name.",
- "The contacts last name.": "The contacts last name.",
- "If specified, the trigger will only fire if contact is in the selected audience.": "If specified, the trigger will only fire if contact is in the selected audience.",
- "Find this in the edit contact dialog on the details page.": "Find this in the edit contact dialog on the details page.",
+ "Add only adds the contact to the selected groups they are not already in. Replace removes the contact from all existing groups and adds them to the selected groups.": "Add only adds the contact to the selected groups they are not already in. Replace removes the contact from all existing groups and adds them to the selected groups.",
+ "Groups to put the contact in.": "Groups to put the contact in.",
+ "Add only adds the tags the contact does not already have. Replace replaces all contact tags with the entered tags.": "Add only adds the tags the contact does not already have. Replace replaces all contact tags with the entered tags.",
+ "Tags to add to the contact.": "Tags to add to the contact.",
+ "Audience the contact belongs to.": "Audience the contact belongs to.",
+ "The Tarvent contact ID. Find it in the edit contact dialog on the details page, or from Find Contact.": "The Tarvent contact ID. Find it in the edit contact dialog on the details page, or from Find Contact.",
+ "Change the contact's email address.": "Change the contact's email address.",
+ "A culture code such as en or en-US, or Auto.": "A culture code such as en or en-US, or Auto.",
+ "An IANA time zone such as America/Denver, or Auto.": "An IANA time zone such as America/Denver, or Auto.",
+ "Audience to search.": "Audience to search.",
+ "Find the contact by email. A value without @ is treated as a contact ID, as in earlier versions.": "Find the contact by email. A value without @ is treated as a contact ID, as in earlier versions.",
+ "Find the contact by ID. Leave empty when using email.": "Find the contact by ID. Leave empty when using email.",
+ "Audience to list.": "Audience to list.",
+ "Only list contacts in this group.": "Only list contacts in this group.",
+ "Maximum number of results to return (1-50). Use the returned Next Cursor to get more.": "Maximum number of results to return (1-50). Use the returned Next Cursor to get more.",
+ "Next Cursor from a previous run, to get the next page of results.": "Next Cursor from a previous run, to get the next page of results.",
"Select whether to add or remove tags.": "Select whether to add or remove tags.",
- "Enter which tags you would like to add or remove.": "Enter which tags you would like to add or remove.",
+ "Tags to add or remove.": "Tags to add or remove.",
+ "Audience the contact and group belong to.": "Audience the contact and group belong to.",
+ "Group to add the contact to or remove it from.": "Group to add the contact to or remove it from.",
"Select whether to add or remove the contact from the group.": "Select whether to add or remove the contact from the group.",
- "Enter the note you would like to add to the contact.": "Enter the note you would like to add to the contact.",
- "Select which journey to start or stop.": "Select which journey to start or stop.",
+ "The note to add to the contact (255 character limit).": "The note to add to the contact (255 character limit).",
+ "Journey to add the contact to or remove it from.": "Journey to add the contact to or remove it from.",
"Select whether to add or remove the contact from the journey.": "Select whether to add or remove the contact from the journey.",
"Select whether to subscribe or unsubscribe the contact.": "Select whether to subscribe or unsubscribe the contact.",
"Audience to create the group in.": "Audience to create the group in.",
"Enter the group name. (100 character limit)": "Enter the group name. (100 character limit)",
- "Use the description to describe what the group is for. NOTE: If the group is public this description will show up in forms that have the groups question.": "Use the description to describe what the group is for. NOTE: If the group is public this description will show up in forms that have the groups question.",
- "Select whether the group is public or not. Public groups are shown in forms with the groups question.": "Select whether the group is public or not. Public groups are shown in forms with the groups question.",
- "Select which journey to start or stop": "Select which journey to start or stop",
+ "What the group is for (255 character limit). If the group is public this description shows in forms that have the groups question.": "What the group is for (255 character limit). If the group is public this description shows in forms that have the groups question.",
+ "Public groups are shown in forms with the groups question.": "Public groups are shown in forms with the groups question.",
+ "Journey to start or stop.": "Journey to start or stop.",
"Select whether to start or stop the journey.": "Select whether to start or stop the journey.",
"Choose an existing group name or use \"Custom\" to enter a new group name. This name is used for reporting.": "Choose an existing group name or use \"Custom\" to enter a new group name. This name is used for reporting.",
"Enter who this transaction is from.": "Enter who this transaction is from.",
@@ -124,22 +209,61 @@
"Enter a subject line for the transaction.": "Enter a subject line for the transaction.",
"Enter the email that the replies should go to.": "Enter the email that the replies should go to.",
"Enter a friendly name the replies should go to.": "Enter a friendly name the replies should go to.",
- "NOTE: Variable names (first column) can have Letters, numbers, underscores, and hyphens. Any other characters in the first column only will be removed.": "NOTE: Variable names (first column) can have Letters, numbers, underscores, and hyphens. Any other characters in the first column only will be removed.",
+ "NOTE: Variable names (first column) keep only letters and numbers; any other characters are removed.": "NOTE: Variable names (first column) keep only letters and numbers; any other characters are removed.",
"Select which template you'd like to used for this transaction.": "Select which template you'd like to used for this transaction.",
"If \"Template\" is specified, this will be ignored..": "If \"Template\" is specified, this will be ignored..",
"To merge in variables, you must use the syntax [[Tx.VariableData.VariableName]] (ex. Variable name is FirstName, merge syntax would be [[Tx.VariableData.FirstName]]) If \"Template\" is specified, this will be ignored.": "To merge in variables, you must use the syntax [[Tx.VariableData.VariableName]] (ex. Variable name is FirstName, merge syntax would be [[Tx.VariableData.FirstName]]) If \"Template\" is specified, this will be ignored.",
- "Select if the suppression filters on your account should be ignored for this transaction.": "Select if the suppression filters on your account should be ignored for this transaction.",
- "Select which campaign to send. **NOTE:** Make sure all campaign settings are correct (from, subject, content) before configuring this automation.": "Select which campaign to send. **NOTE:** Make sure all campaign settings are correct (from, subject, content) before configuring this automation.",
- "Find an audience by searching using its name.": "Find an audience by searching using its name.",
- "Find an audience by searching using its tags. To search using multiple tags, separate the tags with a comma.": "Find an audience by searching using its tags. To search using multiple tags, separate the tags with a comma.",
- "Enter the email to add to the suppression list.": "Enter the email to add to the suppression list.",
- "Use the description to describe why this contact is being suppressed.": "Use the description to describe why this contact is being suppressed.",
- "Find a campaign by searching using its name.": "Find a campaign by searching using its name.",
- "Find a campaign by searching using its tags. To search using multiple tags, separate the tags with a comma.": "Find a campaign by searching using its tags. To search using multiple tags, separate the tags with a comma.",
- "Search for a contact by email. If the audience uses a custom contact identifier, then the search returns the FIRST contact that matches the email address. To target a specific contact, please use the contact's ID.": "Search for a contact by email. If the audience uses a custom contact identifier, then the search returns the FIRST contact that matches the email address. To target a specific contact, please use the contact's ID.",
- "Find a custom event by searching using its name.": "Find a custom event by searching using its name.",
- "Find a journey by searching using its name.": "Find a journey by searching using its name.",
- "Find a journey by searching using its tags. To search using multiple tags, separate the tags with a comma.": "Find a journey by searching using its tags. To search using multiple tags, separate the tags with a comma.",
+ "Select if the suppression filters on your account should be ignored for this transaction. Leave as \"Do not ignore\" unless you are sure the recipient wants this email.": "Select if the suppression filters on your account should be ignored for this transaction. Leave as \"Do not ignore\" unless you are sure the recipient wants this email.",
+ "Optional reporting group name.": "Optional reporting group name.",
+ "Tarvent template ID. Leave empty to send Content instead.": "Tarvent template ID. Leave empty to send Content instead.",
+ "The transaction ID from Send A Transactional Email.": "The transaction ID from Send A Transactional Email.",
+ "Select which campaign to send. **NOTE:** Make sure all campaign settings are correct (from, subject, content) before configuring this automation. Every run sends the campaign to its audience again.": "Select which campaign to send. **NOTE:** Make sure all campaign settings are correct (from, subject, content) before configuring this automation. Every run sends the campaign to its audience again.",
+ "The campaign ID (from Find Campaign).": "The campaign ID (from Find Campaign).",
+ "The custom event to record (its key is sent).": "The custom event to record (its key is sent).",
+ "Find audiences whose name contains this text.": "Find audiences whose name contains this text.",
+ "Find audiences with any of these tags. Separate multiple tags with a comma.": "Find audiences with any of these tags. Separate multiple tags with a comma.",
+ "Find groups whose name contains this text.": "Find groups whose name contains this text.",
+ "The email to add to the suppression list.": "The email to add to the suppression list.",
+ "Why this contact is being suppressed (255 character limit).": "Why this contact is being suppressed (255 character limit).",
+ "Remove filters for this exact email address.": "Remove filters for this exact email address.",
+ "Or remove one filter by its ID.": "Or remove one filter by its ID.",
+ "Find campaigns whose name contains this text.": "Find campaigns whose name contains this text.",
+ "Find campaigns with any of these tags. Separate multiple tags with a comma.": "Find campaigns with any of these tags. Separate multiple tags with a comma.",
+ "Find custom events whose name contains this text.": "Find custom events whose name contains this text.",
+ "Find journeys whose name contains this text.": "Find journeys whose name contains this text.",
+ "Find journeys with any of these tags. Separate multiple tags with a comma.": "Find journeys with any of these tags. Separate multiple tags with a comma.",
+ "Authorization headers are injected automatically from your connection.": "Authorization headers are injected automatically from your connection.",
+ "Appended to the URL as ?key=value.": "Appended to the URL as ?key=value.",
+ "Enable for files like PDFs, images, etc.": "Enable for files like PDFs, images, etc.",
+ "On a failed request, output the error instead of failing the step.": "On a failed request, output the error instead of failing the step.",
+ "Seconds to wait for a response. Empty: up to the flow limit (10 min).": "Seconds to wait for a response. Empty: up to the flow limit (10 min).",
+ "Follow 3xx redirects instead of returning them as the response.": "Follow 3xx redirects instead of returning them as the response.",
+ "The Tarvent audience ID (from Find Audience).": "The Tarvent audience ID (from Find Audience).",
+ "Group name (100 character limit).": "Group name (100 character limit).",
+ "What the group is for (255 character limit).": "What the group is for (255 character limit).",
+ "Show the group on forms with the groups question.": "Show the group on forms with the groups question.",
+ "The Tarvent contact ID (from Find Contact or List Contacts).": "The Tarvent contact ID (from Find Contact or List Contacts).",
+ "Text the group name contains.": "Text the group name contains.",
+ "Results per page, 1-50 (default 50).": "Results per page, 1-50 (default 50).",
+ "nextCursor from the previous page.": "nextCursor from the previous page.",
+ "Find by email. Leave empty when using Contact ID.": "Find by email. Leave empty when using Contact ID.",
+ "Find by contact ID. Leave empty when using email.": "Find by contact ID. Leave empty when using email.",
+ "Only contacts in this group or segment.": "Only contacts in this group or segment.",
+ "The custom event key (from Find Custom Event).": "The custom event key (from Find Custom Event).",
+ "The audience group ID (from Find Audience Groups).": "The audience group ID (from Find Audience Groups).",
+ "ADD to or REMOVE from the group.": "ADD to or REMOVE from the group.",
+ "The journey ID (from Find Journey).": "The journey ID (from Find Journey).",
+ "ENTER or EXIT the journey.": "ENTER or EXIT the journey.",
+ "Tag names to add or remove.": "Tag names to add or remove.",
+ "ADD or REMOVE the tags.": "ADD or REMOVE the tags.",
+ "START or STOP the journey.": "START or STOP the journey.",
+ "The Tarvent audience ID.": "The Tarvent audience ID.",
+ "The Tarvent contact ID (from Find Contact).": "The Tarvent contact ID (from Find Contact).",
+ "The contact email.": "The contact email.",
+ "Update the contact when the email already exists (default true).": "Update the contact when the email already exists (default true).",
+ "Audience group IDs to add the contact to.": "Audience group IDs to add the contact to.",
+ "Tag names to add.": "Tag names to add.",
+ "Data field ID to value.": "Data field ID to value.",
"Update": "Update",
"Return duplicate error": "Return duplicate error",
"Replace": "Replace",
@@ -165,6 +289,16 @@
"Pending multivariate winner": "Pending multivariate winner",
"Running": "Running",
"Not running": "Not running",
+ "GET": "GET",
+ "POST": "POST",
+ "PATCH": "PATCH",
+ "PUT": "PUT",
+ "DELETE": "DELETE",
+ "HEAD": "HEAD",
+ "Enter": "Enter",
+ "Exit": "Exit",
+ "Request": "Request",
+ "Data to send": "Data to send",
"Contact Added": "Contact Added",
"Contact Added Or Removed From A Group": "Contact Added Or Removed From A Group",
"Contact Profile Updated": "Contact Profile Updated",
@@ -210,6 +344,7 @@
"Campaign link": "Campaign link",
"Bounce type": "Bounce type",
"If not included, only the contact ID, email and unique identifier will be passed back.": "If not included, only the contact ID, email and unique identifier will be passed back.",
+ "If specified, the trigger will only fire if contact is in the selected audience.": "If specified, the trigger will only fire if contact is in the selected audience.",
"If specified, the trigger will only fire if contact is in the selected group.": "If specified, the trigger will only fire if contact is in the selected group.",
"If specified, the trigger will only fire if contact has the selected tag.": "If specified, the trigger will only fire if contact has the selected tag.",
"Select if the trigger should fire when a contact is added or removed.": "Select if the trigger should fire when a contact is added or removed.",
@@ -229,6 +364,7 @@
"Any": "Any",
"Both": "Both",
"Transaction": "Transaction",
+ "Any campaign": "Any campaign",
"Any of the last 5 campaigns": "Any of the last 5 campaigns",
"All of the last 5 campaigns": "All of the last 5 campaigns",
"Any campaigns within last...": "Any campaigns within last...",
diff --git a/packages/pieces/community/tarvent/src/index.ts b/packages/pieces/community/tarvent/src/index.ts
index b52b19e482d..be3c0ede27e 100644
--- a/packages/pieces/community/tarvent/src/index.ts
+++ b/packages/pieces/community/tarvent/src/index.ts
@@ -1,28 +1,134 @@
-
-import { createPiece, PieceAuth, Property } from "@activepieces/pieces-framework";
-import { AppConnectionType, PieceCategory } from '@activepieces/pieces-framework';
-import { makeClient } from "./lib/common";
-import { campaignSendFinishedTrigger, contactAddedTrigger, contactBouncedTrigger, contactClickedTrigger, contactGroupUpdatedTrigger, contactNoteAddedTrigger, contactOpenedTrigger, contactRepliedTrigger, contactStatusUpdatedTrigger, contactTagUpdatedTrigger, contactUnsubscribedTrigger, contactUpdatedTrigger, formSubmittedTrigger, pagePerformedTrigger, surveySubmittedTrigger, transactionCreatedTrigger, transactionSentTrigger } from "./lib/triggers";
-import { updateContactTags, sendCampaign, createAudienceGroup, updateContactGroup, createContactNote, updateContactJourney, updateContactStatus, generateCustomEvent, updateJourneyStatus, createSuppressionFilter, getAudiences, getAudienceGroups, getCampaigns, getContact, getCustomEvent, getJourney, createContact, createTransaction } from "./lib/actions";
+import { createPiece, PieceCategory } from '@activepieces/pieces-framework';
+import {
+ createAudienceGroup,
+ createContact,
+ createContactNote,
+ createSuppressionFilter,
+ createTransaction,
+ createTransactionAi,
+ deleteContact,
+ generateCustomEvent,
+ getAudienceGroups,
+ getAudiences,
+ getCampaigns,
+ getCampaignStats,
+ getContact,
+ getCustomEvent,
+ getJourney,
+ getTransaction,
+ listContactNotes,
+ listContacts,
+ listTags,
+ removeSuppressionFilter,
+ sendCampaign,
+ tarventCustomApiCall,
+ updateContact,
+ updateContactGroup,
+ updateContactJourney,
+ updateContactStatus,
+ updateContactTags,
+ updateJourneyStatus,
+ createAudienceGroupAi,
+ deleteContactAi,
+ findAudienceGroupsAi,
+ findContactAi,
+ listContactsAi,
+ recordCustomEventAi,
+ setContactGroupMembershipAi,
+ setContactJourneyAi,
+ setContactTagsAi,
+ setJourneyStatusAi,
+ updateContactAi,
+ upsertContactAi,
+} from './lib/actions';
import { tarventAuth } from './lib/auth';
-
-const authGuide = `
-To obtain your Tarvent Account ID and API Key, follow these steps:
-
-1. Log in to your Tarvent account.
-2. Go to **Account->API Keys** section.
-3. **Create an API key** and copy it. Make sure to give it the correct permissions.
-4. The **Account ID** is available to copy at the top right
-`;
+import {
+ campaignSendFinishedTrigger,
+ contactAddedTrigger,
+ contactBouncedTrigger,
+ contactClickedTrigger,
+ contactGroupUpdatedTrigger,
+ contactNoteAddedTrigger,
+ contactOpenedTrigger,
+ contactRepliedTrigger,
+ contactStatusUpdatedTrigger,
+ contactTagUpdatedTrigger,
+ contactUnsubscribedTrigger,
+ contactUpdatedTrigger,
+ formSubmittedTrigger,
+ pagePerformedTrigger,
+ surveySubmittedTrigger,
+ transactionCreatedTrigger,
+ transactionSentTrigger,
+} from './lib/triggers';
export const tarvent = createPiece({
- displayName: "Tarvent",
- description: "Tarvent is an email marketing, automation, and email API platform that allows to you to send campaigns, manage contacts, automate your marketing, and more.",
+ displayName: 'Tarvent',
+ description: 'Tarvent is an email marketing, automation, and email API platform that allows you to send campaigns, manage contacts, automate your marketing, and more.',
auth: tarventAuth,
- minimumSupportedRelease: '0.36.1',
+ minimumSupportedRelease: '0.88.2',
logoUrl: 'https://cdn.activepieces.com/pieces/tarvent.png',
categories: [PieceCategory.MARKETING, PieceCategory.FORMS_AND_SURVEYS],
- authors: ["derekjdev","206mph"],
- actions: [createContact, updateContactTags, updateContactGroup, createContactNote, updateContactJourney, updateContactStatus, createAudienceGroup, updateJourneyStatus, createTransaction, sendCampaign, generateCustomEvent, getAudiences, getAudienceGroups, createSuppressionFilter, getCampaigns, getContact, getCustomEvent, getJourney],
- triggers: [contactAddedTrigger, contactGroupUpdatedTrigger, contactUpdatedTrigger, contactStatusUpdatedTrigger, contactTagUpdatedTrigger, contactNoteAddedTrigger, contactUnsubscribedTrigger, formSubmittedTrigger, pagePerformedTrigger, surveySubmittedTrigger, contactClickedTrigger, contactOpenedTrigger, contactRepliedTrigger, contactBouncedTrigger,campaignSendFinishedTrigger, transactionCreatedTrigger, transactionSentTrigger],
+ authors: ['derekjdev', '206mph', 'OdaiAhmed99'],
+ actions: [
+ createContact,
+ updateContact,
+ getContact,
+ listContacts,
+ deleteContact,
+ updateContactTags,
+ updateContactGroup,
+ createContactNote,
+ listContactNotes,
+ updateContactJourney,
+ updateContactStatus,
+ createAudienceGroup,
+ updateJourneyStatus,
+ createTransaction,
+ createTransactionAi,
+ getTransaction,
+ sendCampaign,
+ getCampaignStats,
+ generateCustomEvent,
+ getAudiences,
+ getAudienceGroups,
+ createSuppressionFilter,
+ removeSuppressionFilter,
+ getCampaigns,
+ getCustomEvent,
+ getJourney,
+ listTags,
+ tarventCustomApiCall,
+ createAudienceGroupAi,
+ deleteContactAi,
+ findAudienceGroupsAi,
+ findContactAi,
+ listContactsAi,
+ recordCustomEventAi,
+ setContactGroupMembershipAi,
+ setContactJourneyAi,
+ setContactTagsAi,
+ setJourneyStatusAi,
+ updateContactAi,
+ upsertContactAi,
+ ],
+ triggers: [
+ contactAddedTrigger,
+ contactGroupUpdatedTrigger,
+ contactUpdatedTrigger,
+ contactStatusUpdatedTrigger,
+ contactTagUpdatedTrigger,
+ contactNoteAddedTrigger,
+ contactUnsubscribedTrigger,
+ formSubmittedTrigger,
+ pagePerformedTrigger,
+ surveySubmittedTrigger,
+ contactClickedTrigger,
+ contactOpenedTrigger,
+ contactRepliedTrigger,
+ contactBouncedTrigger,
+ campaignSendFinishedTrigger,
+ transactionCreatedTrigger,
+ transactionSentTrigger,
+ ],
});
diff --git a/packages/pieces/community/tarvent/src/lib/actions/ai/create-audience-group-ai.ts b/packages/pieces/community/tarvent/src/lib/actions/ai/create-audience-group-ai.ts
new file mode 100644
index 00000000000..ad215bf59e7
--- /dev/null
+++ b/packages/pieces/community/tarvent/src/lib/actions/ai/create-audience-group-ai.ts
@@ -0,0 +1,29 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { tarventAuth } from '../../auth';
+import { tarventOperations } from '../../common/operations';
+import { tarventOutputSchemas } from '../../output-schemas';
+
+export const createAudienceGroupAi = createAction({
+ auth: tarventAuth,
+ name: 'tarvent_create_audience_group_ai',
+ classification: 'WRITE',
+ displayName: 'Create Audience Group (AI)',
+ description: 'Creates a static group in an audience.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Creates a static group in a Tarvent audience: audience ID, name (up to 100 characters), optional description (up to 255) and whether it is public (shown on forms). Returns the group with its ID. Not idempotent: each call creates another group, so check Find Audience Groups first.',
+ idempotent: false,
+ },
+ outputSchema: tarventOutputSchemas.audienceGroup,
+ props: {
+ audienceId: Property.ShortText({ displayName: 'Audience ID', description: 'The Tarvent audience ID (from Find Audience).', required: true }),
+ name: Property.ShortText({ displayName: 'Name', description: 'Group name (100 character limit).', required: true }),
+ description: Property.ShortText({ displayName: 'Description', description: 'What the group is for (255 character limit).', required: false }),
+ isPublic: Property.Checkbox({ displayName: 'Public', description: 'Show the group on forms with the groups question.', required: false, defaultValue: false }),
+ },
+ async run(context) {
+ const p = context.propsValue;
+ return tarventOperations.createAudienceGroup({ auth: context.auth.props, audienceId: p.audienceId, name: p.name, description: p.description, isPublic: p.isPublic === true });
+ },
+});
diff --git a/packages/pieces/community/tarvent/src/lib/actions/ai/delete-contact-ai.ts b/packages/pieces/community/tarvent/src/lib/actions/ai/delete-contact-ai.ts
new file mode 100644
index 00000000000..7d4a47606b4
--- /dev/null
+++ b/packages/pieces/community/tarvent/src/lib/actions/ai/delete-contact-ai.ts
@@ -0,0 +1,27 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { tarventAuth } from '../../auth';
+import { tarventOperations } from '../../common/operations';
+import { tarventOutputSchemas } from '../../output-schemas';
+
+export const deleteContactAi = createAction({
+ auth: tarventAuth,
+ name: 'tarvent_delete_contact_ai',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Delete Contact (AI)',
+ description: 'Permanently deletes a contact from an audience.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Permanently deletes one Tarvent contact (audience ID + contact ID) with its history; this cannot be undone, so only do it when the user asked to delete. To stop emailing someone use Subscribe/Unsubscribe Contact instead. Fails if the contact does not exist.',
+ idempotent: false,
+ },
+ outputSchema: tarventOutputSchemas.deleteContact,
+ props: {
+ audienceId: Property.ShortText({ displayName: 'Audience ID', description: 'The Tarvent audience ID (from Find Audience).', required: true }),
+ contactId: Property.ShortText({ displayName: 'Contact ID', description: 'The Tarvent contact ID (from Find Contact or List Contacts).', required: true }),
+ },
+ async run(context) {
+ const p = context.propsValue;
+ return tarventOperations.deleteContact({ auth: context.auth.props, audienceId: p.audienceId, contactId: p.contactId });
+ },
+});
diff --git a/packages/pieces/community/tarvent/src/lib/actions/ai/find-audience-groups-ai.ts b/packages/pieces/community/tarvent/src/lib/actions/ai/find-audience-groups-ai.ts
new file mode 100644
index 00000000000..d14b25ae845
--- /dev/null
+++ b/packages/pieces/community/tarvent/src/lib/actions/ai/find-audience-groups-ai.ts
@@ -0,0 +1,29 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { tarventAuth } from '../../auth';
+import { tarventOperations } from '../../common/operations';
+import { tarventOutputSchemas } from '../../output-schemas';
+
+export const findAudienceGroupsAi = createAction({
+ auth: tarventAuth,
+ name: 'tarvent_find_audience_groups_ai',
+ classification: 'SEARCH',
+ displayName: 'Find Audience Groups (AI)',
+ description: 'Finds static groups in an audience by name.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Searches the static groups of one Tarvent audience whose name contains the given text (empty returns all), up to 50 per call with totalCount, hasMore and nextCursor. Use to get a group ID. Read-only.',
+ idempotent: true,
+ },
+ outputSchema: tarventOutputSchemas.audienceGroupPage,
+ props: {
+ audienceId: Property.ShortText({ displayName: 'Audience ID', description: 'The Tarvent audience ID (from Find Audience).', required: true }),
+ name: Property.ShortText({ displayName: 'Name contains', description: 'Text the group name contains.', required: false }),
+ limit: Property.Number({ displayName: 'Limit', description: 'Results per page, 1-50 (default 50).', required: false }),
+ cursor: Property.ShortText({ displayName: 'Cursor', description: 'nextCursor from the previous page.', required: false }),
+ },
+ async run(context) {
+ const p = context.propsValue;
+ return tarventOperations.findAudienceGroups({ auth: context.auth.props, audienceId: p.audienceId, name: p.name, limit: p.limit, cursor: p.cursor });
+ },
+});
diff --git a/packages/pieces/community/tarvent/src/lib/actions/ai/find-contact-ai.ts b/packages/pieces/community/tarvent/src/lib/actions/ai/find-contact-ai.ts
new file mode 100644
index 00000000000..75cdcb385cb
--- /dev/null
+++ b/packages/pieces/community/tarvent/src/lib/actions/ai/find-contact-ai.ts
@@ -0,0 +1,28 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { tarventAuth } from '../../auth';
+import { tarventOperations } from '../../common/operations';
+import { tarventOutputSchemas } from '../../output-schemas';
+
+export const findContactAi = createAction({
+ auth: tarventAuth,
+ name: 'tarvent_find_contact_ai',
+ classification: 'READ',
+ displayName: 'Find Contact (AI)',
+ description: 'Finds one contact by email or contact ID.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Looks up one Tarvent contact in an audience by email or by contact ID (give exactly one). Returns found=false and contact=null when nothing matches. With a custom identifier the email lookup returns the first match. To list many contacts use List Contacts. Read-only.',
+ idempotent: true,
+ },
+ outputSchema: tarventOutputSchemas.findContact,
+ props: {
+ audienceId: Property.ShortText({ displayName: 'Audience ID', description: 'The Tarvent audience ID (from Find Audience).', required: true }),
+ email: Property.ShortText({ displayName: 'Email', description: 'Find by email. Leave empty when using Contact ID.', required: false }),
+ contactId: Property.ShortText({ displayName: 'Contact ID', description: 'Find by contact ID. Leave empty when using email.', required: false }),
+ },
+ async run(context) {
+ const p = context.propsValue;
+ return tarventOperations.findContact({ auth: context.auth.props, audienceId: p.audienceId, email: p.email, contactId: p.contactId });
+ },
+});
diff --git a/packages/pieces/community/tarvent/src/lib/actions/ai/list-contacts-ai.ts b/packages/pieces/community/tarvent/src/lib/actions/ai/list-contacts-ai.ts
new file mode 100644
index 00000000000..4782c6f0f80
--- /dev/null
+++ b/packages/pieces/community/tarvent/src/lib/actions/ai/list-contacts-ai.ts
@@ -0,0 +1,29 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { tarventAuth } from '../../auth';
+import { tarventOperations } from '../../common/operations';
+import { tarventOutputSchemas } from '../../output-schemas';
+
+export const listContactsAi = createAction({
+ auth: tarventAuth,
+ name: 'tarvent_list_contacts_ai',
+ classification: 'SEARCH',
+ displayName: 'List Contacts (AI)',
+ description: 'Lists contacts in an audience one page at a time.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists contacts in a Tarvent audience, optionally only one group or segment ID, up to 50 per call. Returns items, hasMore and nextCursor; pass nextCursor as cursor for the next page. Read-only.',
+ idempotent: true,
+ },
+ outputSchema: tarventOutputSchemas.contactPage,
+ props: {
+ audienceId: Property.ShortText({ displayName: 'Audience ID', description: 'The Tarvent audience ID (from Find Audience).', required: true }),
+ groupId: Property.ShortText({ displayName: 'Group ID', description: 'Only contacts in this group or segment.', required: false }),
+ limit: Property.Number({ displayName: 'Limit', description: 'Results per page, 1-50 (default 50).', required: false }),
+ cursor: Property.ShortText({ displayName: 'Cursor', description: 'nextCursor from the previous page.', required: false }),
+ },
+ async run(context) {
+ const p = context.propsValue;
+ return tarventOperations.listContacts({ auth: context.auth.props, audienceId: p.audienceId, groupId: p.groupId, limit: p.limit, cursor: p.cursor });
+ },
+});
diff --git a/packages/pieces/community/tarvent/src/lib/actions/ai/record-custom-event-ai.ts b/packages/pieces/community/tarvent/src/lib/actions/ai/record-custom-event-ai.ts
new file mode 100644
index 00000000000..7c5cb747b36
--- /dev/null
+++ b/packages/pieces/community/tarvent/src/lib/actions/ai/record-custom-event-ai.ts
@@ -0,0 +1,27 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { tarventAuth } from '../../auth';
+import { tarventOperations } from '../../common/operations';
+import { tarventOutputSchemas } from '../../output-schemas';
+
+export const recordCustomEventAi = createAction({
+ auth: tarventAuth,
+ name: 'tarvent_record_custom_event_ai',
+ classification: 'WRITE',
+ displayName: 'Record Custom Event (AI)',
+ description: 'Records a custom event for a contact.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Records a predefined Tarvent custom event for one contact; journeys listening for it can then run. Give the contact ID and the event key (the key field from Find Custom Event, not its ID). Not idempotent: each call records another occurrence.',
+ idempotent: false,
+ },
+ outputSchema: tarventOutputSchemas.customEventGenerated,
+ props: {
+ contactId: Property.ShortText({ displayName: 'Contact ID', description: 'The Tarvent contact ID (from Find Contact or List Contacts).', required: true }),
+ eventKey: Property.ShortText({ displayName: 'Event key', description: 'The custom event key (from Find Custom Event).', required: true }),
+ },
+ async run(context) {
+ const p = context.propsValue;
+ return tarventOperations.recordCustomEvent({ auth: context.auth.props, contactId: p.contactId, eventKey: p.eventKey });
+ },
+});
diff --git a/packages/pieces/community/tarvent/src/lib/actions/ai/set-contact-group-membership-ai.ts b/packages/pieces/community/tarvent/src/lib/actions/ai/set-contact-group-membership-ai.ts
new file mode 100644
index 00000000000..b3ec5da7cdd
--- /dev/null
+++ b/packages/pieces/community/tarvent/src/lib/actions/ai/set-contact-group-membership-ai.ts
@@ -0,0 +1,29 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { tarventAuth } from '../../auth';
+import { tarventOperations } from '../../common/operations';
+import { tarventOutputSchemas } from '../../output-schemas';
+
+export const setContactGroupMembershipAi = createAction({
+ auth: tarventAuth,
+ name: 'tarvent_set_contact_group_membership_ai',
+ classification: 'WRITE',
+ displayName: 'Add or Remove Contact From Group (AI)',
+ description: 'Adds a contact to, or removes it from, an audience group.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Adds one Tarvent contact to, or removes it from, one static audience group. Give the audience ID, group ID (from Find Audience Groups), contact ID and action ADD or REMOVE. Not idempotent: Tarvent may reject adding a contact that is already in the group.',
+ idempotent: false,
+ },
+ outputSchema: tarventOutputSchemas.contactGroup,
+ props: {
+ audienceId: Property.ShortText({ displayName: 'Audience ID', description: 'The Tarvent audience ID (from Find Audience).', required: true }),
+ groupId: Property.ShortText({ displayName: 'Group ID', description: 'The audience group ID (from Find Audience Groups).', required: true }),
+ contactId: Property.ShortText({ displayName: 'Contact ID', description: 'The Tarvent contact ID (from Find Contact or List Contacts).', required: true }),
+ action: Property.StaticDropdown({ displayName: 'Action', description: 'ADD to or REMOVE from the group.', required: true, options: { options: [{ label: 'Add', value: 'ADD' }, { label: 'Remove', value: 'REMOVE' }] } }),
+ },
+ async run(context) {
+ const p = context.propsValue;
+ return tarventOperations.setGroupMembership({ auth: context.auth.props, audienceId: p.audienceId, groupId: p.groupId, contactId: p.contactId, add: p.action === 'ADD' });
+ },
+});
diff --git a/packages/pieces/community/tarvent/src/lib/actions/ai/set-contact-journey-ai.ts b/packages/pieces/community/tarvent/src/lib/actions/ai/set-contact-journey-ai.ts
new file mode 100644
index 00000000000..cbcda6803e7
--- /dev/null
+++ b/packages/pieces/community/tarvent/src/lib/actions/ai/set-contact-journey-ai.ts
@@ -0,0 +1,28 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { tarventAuth } from '../../auth';
+import { tarventOperations } from '../../common/operations';
+import { tarventOutputSchemas } from '../../output-schemas';
+
+export const setContactJourneyAi = createAction({
+ auth: tarventAuth,
+ name: 'tarvent_set_contact_journey_ai',
+ classification: 'WRITE',
+ displayName: 'Enter or Exit Contact From Journey (AI)',
+ description: 'Enters a contact into a journey, or removes it.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Enters one Tarvent contact into an automation journey (ENTER), which can start the journey emails for that contact, or removes it (EXIT). Give the contact ID and journey ID (from Find Journey). Not idempotent: entering again can re-run journey steps.',
+ idempotent: false,
+ },
+ outputSchema: tarventOutputSchemas.contactJourney,
+ props: {
+ contactId: Property.ShortText({ displayName: 'Contact ID', description: 'The Tarvent contact ID (from Find Contact or List Contacts).', required: true }),
+ journeyId: Property.ShortText({ displayName: 'Journey ID', description: 'The journey ID (from Find Journey).', required: true }),
+ action: Property.StaticDropdown({ displayName: 'Action', description: 'ENTER or EXIT the journey.', required: true, options: { options: [{ label: 'Enter', value: 'ENTER' }, { label: 'Exit', value: 'EXIT' }] } }),
+ },
+ async run(context) {
+ const p = context.propsValue;
+ return tarventOperations.setContactJourney({ auth: context.auth.props, contactId: p.contactId, journeyId: p.journeyId, add: p.action === 'ENTER' });
+ },
+});
diff --git a/packages/pieces/community/tarvent/src/lib/actions/ai/set-contact-tags-ai.ts b/packages/pieces/community/tarvent/src/lib/actions/ai/set-contact-tags-ai.ts
new file mode 100644
index 00000000000..0031de7608b
--- /dev/null
+++ b/packages/pieces/community/tarvent/src/lib/actions/ai/set-contact-tags-ai.ts
@@ -0,0 +1,29 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { tarventAuth } from '../../auth';
+import { tarventOperations } from '../../common/operations';
+import { tarventOutputSchemas } from '../../output-schemas';
+
+export const setContactTagsAi = createAction({
+ auth: tarventAuth,
+ name: 'tarvent_set_contact_tags_ai',
+ classification: 'WRITE',
+ displayName: 'Add or Remove Contact Tags (AI)',
+ description: 'Adds or removes tags on a contact.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Adds tags to, or removes tags from, one Tarvent contact. Give the audience ID, contact ID, the tag names (1-100, free text) and action ADD or REMOVE. Existing tags not listed are kept. Idempotent: tags behave as a set.',
+ idempotent: true,
+ },
+ outputSchema: tarventOutputSchemas.contactTags,
+ props: {
+ audienceId: Property.ShortText({ displayName: 'Audience ID', description: 'The Tarvent audience ID (from Find Audience).', required: true }),
+ contactId: Property.ShortText({ displayName: 'Contact ID', description: 'The Tarvent contact ID (from Find Contact or List Contacts).', required: true }),
+ tags: Property.Array({ displayName: 'Tags', description: 'Tag names to add or remove.', required: true }),
+ action: Property.StaticDropdown({ displayName: 'Action', description: 'ADD or REMOVE the tags.', required: true, options: { options: [{ label: 'Add', value: 'ADD' }, { label: 'Remove', value: 'REMOVE' }] } }),
+ },
+ async run(context) {
+ const p = context.propsValue;
+ return tarventOperations.setContactTags({ auth: context.auth.props, audienceId: p.audienceId, contactId: p.contactId, tags: p.tags, remove: p.action === 'REMOVE' });
+ },
+});
diff --git a/packages/pieces/community/tarvent/src/lib/actions/ai/set-journey-status-ai.ts b/packages/pieces/community/tarvent/src/lib/actions/ai/set-journey-status-ai.ts
new file mode 100644
index 00000000000..6442fe776db
--- /dev/null
+++ b/packages/pieces/community/tarvent/src/lib/actions/ai/set-journey-status-ai.ts
@@ -0,0 +1,27 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { tarventAuth } from '../../auth';
+import { tarventOperations } from '../../common/operations';
+import { tarventOutputSchemas } from '../../output-schemas';
+
+export const setJourneyStatusAi = createAction({
+ auth: tarventAuth,
+ name: 'tarvent_set_journey_status_ai',
+ classification: 'WRITE',
+ displayName: 'Start or Stop Journey (AI)',
+ description: 'Starts or stops a whole journey.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Starts (START) or stops (STOP) a whole Tarvent automation journey by journey ID; starting can begin sending its emails to every contact it targets, so only start when the user asked for it. To move one contact use Enter or Exit Contact From Journey. Not idempotent: Tarvent may reject starting a running journey.',
+ idempotent: false,
+ },
+ outputSchema: tarventOutputSchemas.journeyStatus,
+ props: {
+ journeyId: Property.ShortText({ displayName: 'Journey ID', description: 'The journey ID (from Find Journey).', required: true }),
+ action: Property.StaticDropdown({ displayName: 'Action', description: 'START or STOP the journey.', required: true, options: { options: [{ label: 'Start', value: 'START' }, { label: 'Stop', value: 'STOP' }] } }),
+ },
+ async run(context) {
+ const p = context.propsValue;
+ return tarventOperations.setJourneyStatus({ auth: context.auth.props, journeyId: p.journeyId, start: p.action === 'START' });
+ },
+});
diff --git a/packages/pieces/community/tarvent/src/lib/actions/ai/update-contact-ai.ts b/packages/pieces/community/tarvent/src/lib/actions/ai/update-contact-ai.ts
new file mode 100644
index 00000000000..16601b15bfd
--- /dev/null
+++ b/packages/pieces/community/tarvent/src/lib/actions/ai/update-contact-ai.ts
@@ -0,0 +1,66 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { tarventAuth } from '../../auth';
+import { tarventCommon } from '../../common';
+import { tarventClient } from '../../common/client';
+import { tarventOutputSchemas } from '../../output-schemas';
+
+const FIELDS: { key: string; label: string; max: number }[] = [
+ { key: 'email', label: 'Email', max: 320 },
+ { key: 'firstName', label: 'First name', max: 100 },
+ { key: 'lastName', label: 'Last name', max: 100 },
+ { key: 'streetAddress', label: 'Street address', max: 100 },
+ { key: 'streetAddress2', label: 'Street address 2', max: 50 },
+ { key: 'addressLocality', label: 'City', max: 100 },
+ { key: 'addressRegion', label: 'State / Region', max: 100 },
+ { key: 'postalCode', label: 'Postal code', max: 15 },
+ { key: 'addressCountry', label: 'Country', max: 100 },
+ { key: 'language', label: 'Language', max: 20 },
+ { key: 'timeZone', label: 'Time zone', max: 100 },
+];
+
+export const updateContactAi = createAction({
+ auth: tarventAuth,
+ name: 'tarvent_update_contact_ai',
+ classification: 'WRITE',
+ displayName: 'Update Contact (AI)',
+ description: 'Updates fields of an existing contact by its ID.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Changes fields of an existing Tarvent contact given its audience ID and contact ID; only the fields you pass change, nothing is cleared. Can change the email address, names, address, language (culture code or Auto) and time zone (IANA name or Auto). Use Add or Remove Contact Tags and Add or Remove Contact From Group for tags and groups, and Create or Update Contact to add a contact by email. Fails if the contact does not exist. Idempotent: the same input sets the same values.',
+ idempotent: true,
+ },
+ outputSchema: tarventOutputSchemas.contact,
+ props: {
+ audienceId: Property.ShortText({ displayName: 'Audience ID', description: 'The Tarvent audience ID.', required: true }),
+ contactId: Property.ShortText({ displayName: 'Contact ID', description: 'The Tarvent contact ID (from Find Contact).', required: true }),
+ email: Property.ShortText({ displayName: 'New email', required: false }),
+ firstName: Property.ShortText({ displayName: 'First name', required: false }),
+ lastName: Property.ShortText({ displayName: 'Last name', required: false }),
+ streetAddress: Property.ShortText({ displayName: 'Street address', required: false }),
+ streetAddress2: Property.ShortText({ displayName: 'Street address 2', required: false }),
+ addressLocality: Property.ShortText({ displayName: 'City', required: false }),
+ addressRegion: Property.ShortText({ displayName: 'State / Region', required: false }),
+ postalCode: Property.ShortText({ displayName: 'Postal code', required: false }),
+ addressCountry: Property.ShortText({ displayName: 'Country', required: false }),
+ language: Property.ShortText({ displayName: 'Language', required: false }),
+ timeZone: Property.ShortText({ displayName: 'Time zone', required: false }),
+ },
+ async run(context) {
+ const values: Record<string, unknown> = context.propsValue;
+ const audienceId = tarventCommon.requireText({ value: context.propsValue.audienceId, label: 'Audience ID' });
+ const id = tarventCommon.requireText({ value: context.propsValue.contactId, label: 'Contact ID' });
+ const set = Object.fromEntries(
+ FIELDS.flatMap((f) => {
+ const value = tarventCommon.trimmed(values[f.key]);
+ if (value === undefined) return [];
+ tarventCommon.checkLength({ value, label: f.label, max: f.max });
+ return [[f.key, value]];
+ }),
+ );
+ if (Object.keys(set).length === 0) {
+ throw new Error('Nothing to update. Pass at least one field.');
+ }
+ return tarventClient.updateContact({ auth: context.auth.props, input: { id, audienceId, ...set } });
+ },
+});
diff --git a/packages/pieces/community/tarvent/src/lib/actions/ai/upsert-contact-ai.ts b/packages/pieces/community/tarvent/src/lib/actions/ai/upsert-contact-ai.ts
new file mode 100644
index 00000000000..8981bb82292
--- /dev/null
+++ b/packages/pieces/community/tarvent/src/lib/actions/ai/upsert-contact-ai.ts
@@ -0,0 +1,95 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { tarventAuth } from '../../auth';
+import { tarventCommon } from '../../common';
+import { tarventClient } from '../../common/client';
+import { tarventOutputSchemas } from '../../output-schemas';
+
+const TEXT_FIELDS: { key: string; label: string; max: number }[] = [
+ { key: 'firstName', label: 'First name', max: 100 },
+ { key: 'lastName', label: 'Last name', max: 100 },
+ { key: 'streetAddress', label: 'Street address', max: 100 },
+ { key: 'streetAddress2', label: 'Street address 2', max: 50 },
+ { key: 'addressLocality', label: 'City', max: 100 },
+ { key: 'addressRegion', label: 'State / Region', max: 100 },
+ { key: 'postalCode', label: 'Postal code', max: 15 },
+ { key: 'addressCountry', label: 'Country', max: 100 },
+];
+
+export const upsertContactAi = createAction({
+ auth: tarventAuth,
+ name: 'tarvent_upsert_contact_ai',
+ classification: 'WRITE',
+ displayName: 'Create or Update Contact (AI)',
+ description: 'Creates a contact by email, or updates the existing one.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Creates a Tarvent contact in an audience by email, or updates the contact that already has that email (set ifExists=FAIL to fail instead). Optional name and address fields are set, and comma-separated group IDs and tag names are added; existing groups and tags are never removed. customFields maps data field IDs to values (GDPR fields take 1 or 0). Empty fields are not sent. Returns the contact with its ID. To change a known contact by ID, for example its email, use Update Contact. Repeating the same call leaves the same contact, but groups and tags only ever grow.',
+ idempotent: true,
+ },
+ outputSchema: tarventOutputSchemas.contact,
+ props: {
+ audienceId: Property.ShortText({ displayName: 'Audience ID', description: 'The Tarvent audience ID (from Find Audience).', required: true }),
+ email: Property.ShortText({ displayName: 'Email', description: 'The contact email.', required: true }),
+ ifExists: Property.StaticDropdown({
+ displayName: 'If the email exists',
+ description: 'What to do when a contact with this email already exists (default: update it).',
+ required: false,
+ options: {
+ options: [
+ { label: 'Update the contact', value: 'UPDATE' },
+ { label: 'Fail', value: 'FAIL' },
+ ],
+ },
+ }),
+ firstName: Property.ShortText({ displayName: 'First name', required: false }),
+ lastName: Property.ShortText({ displayName: 'Last name', required: false }),
+ streetAddress: Property.ShortText({ displayName: 'Street address', required: false }),
+ streetAddress2: Property.ShortText({ displayName: 'Street address 2', required: false }),
+ addressLocality: Property.ShortText({ displayName: 'City', required: false }),
+ addressRegion: Property.ShortText({ displayName: 'State / Region', required: false }),
+ postalCode: Property.ShortText({ displayName: 'Postal code', required: false }),
+ addressCountry: Property.ShortText({ displayName: 'Country', required: false }),
+ groupIds: Property.ShortText({ displayName: 'Group IDs', description: 'Audience group IDs to add the contact to. Separate multiple IDs with a comma.', required: false }),
+ tags: Property.ShortText({ displayName: 'Tags', description: 'Tag names to add. Separate multiple tags with a comma.', required: false }),
+ customFields: Property.Object({ displayName: 'Custom fields', description: 'Data field ID to value.', required: false }),
+ },
+ async run(context) {
+ const p = context.propsValue;
+ const values: Record<string, unknown> = p;
+ const audienceId = tarventCommon.requireText({ value: p.audienceId, label: 'Audience ID' });
+ const email = tarventCommon.requireText({ value: p.email, label: 'Email' });
+ tarventCommon.checkLength({ value: email, label: 'Email', max: 320 });
+ const text = Object.fromEntries(
+ TEXT_FIELDS.flatMap((f) => {
+ const value = tarventCommon.trimmed(values[f.key]);
+ if (value === undefined) return [];
+ tarventCommon.checkLength({ value, label: f.label, max: f.max });
+ return [[f.key, value]];
+ }),
+ );
+ const groupIds = stringList(p.groupIds);
+ const tags = stringList(p.tags);
+ const profile = tarventCommon.profileFromDataFields(p.customFields);
+ return tarventClient.createContact({
+ auth: context.auth.props,
+ input: {
+ ...text,
+ email,
+ audienceId,
+ updateExisting: p.ifExists !== 'FAIL',
+ audienceGroupManagementType: 'ADD_NEW_GROUPS_ONLY',
+ tagManagementType: 'ADD_NEW_TAGS_ONLY',
+ ...(profile.length > 0 ? { profile } : {}),
+ ...(tags.length > 0 ? { tags } : {}),
+ ...(groupIds.length > 0 ? { groupIds } : {}),
+ sendFormat: 'MULTIPART',
+ },
+ });
+ },
+});
+
+function stringList(value: unknown): string[] {
+ const items = Array.isArray(value) ? value : typeof value === 'string' ? value.split(',') : [];
+ return items.map((v) => tarventCommon.trimmed(v)).filter((v): v is string => v !== undefined);
+}
diff --git a/packages/pieces/community/tarvent/src/lib/actions/create-audience-group.ts b/packages/pieces/community/tarvent/src/lib/actions/create-audience-group.ts
index fa453c211fe..f9b99e4a830 100644
--- a/packages/pieces/community/tarvent/src/lib/actions/create-audience-group.ts
+++ b/packages/pieces/community/tarvent/src/lib/actions/create-audience-group.ts
@@ -1,8 +1,8 @@
-import { tarventAuth } from '../auth';
import { createAction, Property } from '@activepieces/pieces-framework';
-import { makeClient, tarventCommon } from '../common';
-import { propsValidation } from '@activepieces/pieces-common';
-import * as z from 'zod/mini'
+import { tarventAuth } from '../auth';
+import { tarventCommon } from '../common';
+import { tarventOperations } from '../common/operations';
+import { tarventOutputSchemas } from '../output-schemas';
export const createAudienceGroup = createAction({
auth: tarventAuth,
@@ -10,40 +10,31 @@ export const createAudienceGroup = createAction({
classification: 'WRITE',
displayName: 'Create An Audience Group',
description: 'Creates an audience group in the selected audience.',
- audience: 'both',
- aiMetadata: { description: 'Creates a new group within a Tarvent audience, optionally marked public so it appears as a question on forms. Use to set up a segment before assigning contacts to it. Not idempotent: each call creates another group, even with the same name.', idempotent: false },
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Creates a new static group in a Tarvent audience (name up to 100 characters, optional description up to 255), optionally public so it appears as a question on forms. Use to set up a segment before assigning contacts. Returns the new group with its ID. Not idempotent: each call creates another group, even with the same name.',
+ idempotent: false,
+ },
+ outputSchema: tarventOutputSchemas.audienceGroup,
props: {
audienceId: tarventCommon.audienceId(true, 'Audience to create the group in.'),
name: tarventCommon.name('Group name', true, 'Enter the group name. (100 character limit)'),
- description: tarventCommon.name('Group description', false, 'Use the description to describe what the group is for. NOTE: If the group is public this description will show up in forms that have the groups question.'),
+ description: tarventCommon.name('Group description', false, 'What the group is for (255 character limit). If the group is public this description shows in forms that have the groups question.'),
isPublic: Property.StaticDropdown({
displayName: 'Public group',
- description: 'Select whether the group is public or not. Public groups are shown in forms with the groups question.',
+ description: 'Public groups are shown in forms with the groups question.',
required: true,
+ defaultValue: 'false',
options: {
options: [
- {
- label: 'True',
-
- value: 'true',
- },
- {
- label: 'False',
- value: 'false',
- },
+ { label: 'True', value: 'true' },
+ { label: 'False', value: 'false' },
],
},
}),
},
async run(context) {
- const { audienceId, name, description, isPublic } = context.propsValue;
-
- await propsValidation.validateZod(context.propsValue, {
- name: z.string().check(z.minLength(1), z.maxLength(100, 'Name has to be less than 100 characters.')),
- description: z.string().check(z.minLength(1), z.maxLength(255, 'Description has to be less than 255 characters.')),
- });
-
- const client = makeClient(context.auth);
- return await client.createAudienceGroup(audienceId, name, description, isPublic);
+ return tarventOperations.createAudienceGroup({ auth: context.auth.props, audienceId: context.propsValue.audienceId, name: context.propsValue.name, description: context.propsValue.description, isPublic: String(context.propsValue.isPublic) === 'true' });
},
});
diff --git a/packages/pieces/community/tarvent/src/lib/actions/create-contact-note.ts b/packages/pieces/community/tarvent/src/lib/actions/create-contact-note.ts
index e7166ff140a..521f9201a80 100644
--- a/packages/pieces/community/tarvent/src/lib/actions/create-contact-note.ts
+++ b/packages/pieces/community/tarvent/src/lib/actions/create-contact-note.ts
@@ -1,8 +1,8 @@
-import { tarventAuth } from '../auth';
import { createAction, Property } from '@activepieces/pieces-framework';
-import { makeClient, tarventCommon } from '../common';
-import { propsValidation } from '@activepieces/pieces-common';
-import * as z from 'zod/mini'
+import { tarventAuth } from '../auth';
+import { tarventCommon } from '../common';
+import { tarventTransport } from '../common/transport';
+import { tarventOutputSchemas } from '../output-schemas';
export const createContactNote = createAction({
auth: tarventAuth,
@@ -11,23 +11,30 @@ export const createContactNote = createAction({
displayName: 'Add Note To Contact',
description: 'Adds a note to a contact.',
audience: 'both',
- aiMetadata: { description: 'Appends a free-text note to a Tarvent contact record. Use to log context or activity against a contact. Not idempotent: each call adds another note, so repeating creates duplicates.', idempotent: false },
+ aiMetadata: {
+ description:
+ 'Adds a free-text note (up to 255 characters) to one Tarvent contact by contact ID. Use to log context or activity against a contact. Returns the contact ID and the note text; Tarvent does not return the new note ID (use List Contact Notes). Not idempotent: each call adds another note.',
+ idempotent: false,
+ },
+ outputSchema: tarventOutputSchemas.contactNoteCreated,
props: {
contactId: tarventCommon.contactId,
note: Property.LongText({
displayName: 'Note',
- description: 'Enter the note you would like to add to the contact.',
- required: true
- })
+ description: 'The note to add to the contact (255 character limit).',
+ required: true,
+ }),
},
async run(context) {
- const { contactId, note } = context.propsValue;
-
- await propsValidation.validateZod(context.propsValue, {
- note: z.string().check(z.minLength(1), z.maxLength(255, 'Description has to be less than 256 characters.'))
+ const contactId = tarventCommon.requireText({ value: context.propsValue.contactId, label: 'Contact ID' });
+ const message = tarventCommon.requireText({ value: context.propsValue.note, label: 'Note' });
+ tarventCommon.checkLength({ value: message, label: 'Note', max: 255 });
+ await tarventTransport.field<{ id: string }>({
+ auth: context.auth.props,
+ query: 'mutation CreateContactNote($input: CreateContactNoteInput!) { createContactNote(input: $input) { id } }',
+ variables: { input: { contactId, message } },
+ name: 'createContactNote',
});
-
- const client = makeClient(context.auth);
- return await client.createContactNote(contactId, note);
+ return { success: true, contactId, message };
},
});
diff --git a/packages/pieces/community/tarvent/src/lib/actions/create-contact.ts b/packages/pieces/community/tarvent/src/lib/actions/create-contact.ts
index 7c379e2913d..435b81d9d01 100644
--- a/packages/pieces/community/tarvent/src/lib/actions/create-contact.ts
+++ b/packages/pieces/community/tarvent/src/lib/actions/create-contact.ts
@@ -1,149 +1,109 @@
-import { tarventAuth } from '../auth';
import { createAction, Property } from '@activepieces/pieces-framework';
-import { makeClient, tarventCommon } from '../common';
-import { propsValidation } from '@activepieces/pieces-common';
-import * as z from 'zod/mini'
+import { tarventAuth } from '../auth';
+import { tarventCommon } from '../common';
+import { tarventClient } from '../common/client';
+import { tarventOutputSchemas } from '../output-schemas';
export const createContact = createAction({
auth: tarventAuth,
name: 'tarvent_create_contact',
classification: 'WRITE',
displayName: 'Create/Update Contact',
- description: 'This action is used to create or update a contact in an audience.',
- audience: 'both',
- aiMetadata: { description: 'Creates a contact in a Tarvent audience, or updates the existing one matched by email/custom identifier; choose whether a duplicate is updated or returns an error, and whether group/tag assignments replace or add to current ones. Use to onboard or maintain a subscriber profile. Not idempotent: it creates on the first call and, in add-only mode, appends to groups/tags.', idempotent: false },
+ description: 'Creates a contact in an audience, or updates it if the email already exists.',
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Upserts a contact into a Tarvent audience by email: creates it, or (when Update existing contact is "Update") updates the existing contact with that email; with "Return duplicate error" an existing email fails the step. Group and tag assignments either replace or add to the current ones. Use this to add a subscriber or to set profile fields by email; to change a known contact by ID (for example its email address) use Update Contact. Empty text fields are not sent, so they never blank existing values. Returns the full contact record including its ID. Not idempotent: in add-only mode repeated calls keep adding groups and tags.',
+ idempotent: false,
+ },
+ outputSchema: tarventOutputSchemas.contact,
props: {
- audienceId: tarventCommon.audienceId(true, ''),
+ audienceId: tarventCommon.audienceId(true, 'Audience to add the contact to.'),
email: Property.ShortText({
displayName: 'Email',
- description: 'Enter the contacts email. NOTE: If the audience uses a custom contact identifier and overwrite is enabled, then this will update the FIRST contact that matches the email.',
+ description: 'The contact\'s email. NOTE: If the audience uses a custom contact identifier and overwrite is enabled, then this will update the FIRST contact that matches the email.',
required: true,
- defaultValue: ''
}),
updateAction: Property.StaticDropdown({
displayName: 'Update existing contact',
description: 'Update the contact\'s profile if it already exists. Otherwise, return the "Duplicate" error.',
required: true,
+ defaultValue: 'Update',
options: {
options: [
- {
- label: 'Update',
-
- value: 'Update',
- },
- {
- label: 'Return duplicate error',
- value: 'ReturnError',
- },
+ { label: 'Update', value: 'Update' },
+ { label: 'Return duplicate error', value: 'ReturnError' },
],
},
}),
groupAction: Property.StaticDropdown({
displayName: 'Replace existing groups',
- description: 'Select whether to replace or only add to contact groups. NOTE: Add only will only add the contact to the groups they are not already in. Replace will remove the contact from all existing groups and add them to the selected groups.',
+ description: 'Add only adds the contact to the selected groups they are not already in. Replace removes the contact from all existing groups and adds them to the selected groups.',
required: false,
options: {
options: [
- {
- label: 'Replace',
-
- value: 'Replace',
- },
- {
- label: 'Add only',
- value: 'Add',
- },
+ { label: 'Replace', value: 'Replace' },
+ { label: 'Add only', value: 'Add' },
],
},
}),
- groupIds: tarventCommon.audienceGroupIds(false, ''),
+ groupIds: tarventCommon.audienceGroupIds(false, 'Groups to put the contact in.'),
tagAction: Property.StaticDropdown({
displayName: 'Replace existing tags',
- description: 'Select whether to replace or only add to contact tags of an existing contact. NOTE: Add only will only add the tags the contact does not already have. Replace will replace all contact tags with the entered tags.',
+ description: 'Add only adds the tags the contact does not already have. Replace replaces all contact tags with the entered tags.',
required: false,
options: {
options: [
- {
- label: 'Replace',
-
- value: 'Replace',
- },
- {
- label: 'Add only',
- value: 'Add',
- },
+ { label: 'Replace', value: 'Replace' },
+ { label: 'Add only', value: 'Add' },
],
},
}),
- tagIds: tarventCommon.tagIds(false, `Select which tags you would like to add to the contact.`),
- firstName: Property.ShortText({
- displayName: 'First name',
- description: 'The contacts first name.',
- required: false,
- defaultValue: ''
- }),
- lastName: Property.ShortText({
- displayName: 'Last name',
- description: 'The contacts last name.',
- required: false,
- defaultValue: ''
- }),
- streetAddress: Property.ShortText({
- displayName: 'Street address',
- description: '',
- required: false,
- defaultValue: ''
- }),
- streetAddress2: Property.ShortText({
- displayName: 'Street address 2',
- description: '',
- required: false,
- defaultValue: ''
- }),
- addressLocality: Property.ShortText({
- displayName: 'City (Locality)',
- description: '',
- required: false,
- defaultValue: ''
- }),
- addressRegion: Property.ShortText({
- displayName: 'State (Region)',
- description: '',
- required: false,
- defaultValue: ''
- }),
- postalCode: Property.ShortText({
- displayName: 'Zip code (Postal code)',
- description: '',
- required: false,
- defaultValue: ''
- }),
- addressCountry: Property.ShortText({
- displayName: 'Country',
- description: '',
- required: false,
- defaultValue: ''
- }),
- audienceDataFields: tarventCommon.audienceDataFields
+ tagIds: tarventCommon.tagIds(false, 'Tags to add to the contact.'),
+ firstName: Property.ShortText({ displayName: 'First name', required: false }),
+ lastName: Property.ShortText({ displayName: 'Last name', required: false }),
+ streetAddress: Property.ShortText({ displayName: 'Street address', required: false }),
+ streetAddress2: Property.ShortText({ displayName: 'Street address 2', required: false }),
+ addressLocality: Property.ShortText({ displayName: 'City (Locality)', required: false }),
+ addressRegion: Property.ShortText({ displayName: 'State (Region)', required: false }),
+ postalCode: Property.ShortText({ displayName: 'Zip code (Postal code)', required: false }),
+ addressCountry: Property.ShortText({ displayName: 'Country', required: false }),
+ audienceDataFields: tarventCommon.audienceDataFields,
},
async run(context) {
- const { audienceId, email, updateAction, groupAction, groupIds, tagAction, tagIds, firstName, lastName,
- streetAddress, streetAddress2, addressLocality, addressRegion, postalCode, addressCountry, audienceDataFields } = context.propsValue;
-
- await propsValidation.validateZod(context.propsValue, {
- email: z.string().check(z.maxLength(100, 'Email has to be equal to or less than 100 characters.')),
- firstName: z.optional(z.string().check(z.maxLength(100, 'First name has to be equal to or less than 100 characters.'))),
- lastName: z.optional(z.string().check(z.maxLength(100, 'Last name has to be equal to or less than 100 characters.'))),
- streetAddress: z.optional(z.string().check(z.maxLength(100, 'Street address has to be equal to or less than 100 characters.'))),
- streetAddress2: z.optional(z.string().check(z.maxLength(100, 'Street address 2 has to be equal to or less than 100 characters.'))),
- addressLocality: z.optional(z.string().check(z.maxLength(100, 'City (Locality) has to be equal to or less than 100 characters.'))),
- addressRegion: z.optional(z.string().check(z.maxLength(100, 'State (Region) has to be equal to or less than 100 characters.'))),
- postalCode: z.optional(z.string().check(z.maxLength(15, 'Zip code (Postal code) has to be equal to or less than 15 characters.'))),
- addressCountry: z.optional(z.string().check(z.maxLength(100, 'Country has to be equal to or less than 100 characters.'))),
+ const p = context.propsValue;
+ const audienceId = tarventCommon.requireText({ value: p.audienceId, label: 'Audience' });
+ const email = tarventCommon.requireText({ value: p.email, label: 'Email' });
+ const text = contactTextFields(p);
+ tarventCommon.checkLength({ value: email, label: 'Email', max: 320 });
+ for (const [key, value] of Object.entries(text)) {
+ tarventCommon.checkLength({ value, label: key, max: key === 'postalCode' ? 15 : 100 });
+ }
+ const tags = Array.isArray(p.tagIds) ? p.tagIds.map(String) : undefined;
+ const groupIds = Array.isArray(p.groupIds) ? p.groupIds.map(String) : undefined;
+ const profile = tarventCommon.profileFromDataFields(p.audienceDataFields);
+ return tarventClient.createContact({
+ auth: context.auth.props,
+ input: {
+ ...text,
+ email,
+ audienceId,
+ updateExisting: p.updateAction !== 'ReturnError',
+ audienceGroupManagementType: p.groupAction === 'Replace' ? 'REPLACE_EXISTING' : 'ADD_NEW_GROUPS_ONLY',
+ tagManagementType: p.tagAction === 'Replace' ? 'REPLACE_EXISTING' : 'ADD_NEW_TAGS_ONLY',
+ ...(profile.length > 0 ? { profile } : {}),
+ ...(tags && (tags.length > 0 || p.tagAction === 'Replace') ? { tags } : {}),
+ ...(groupIds && (groupIds.length > 0 || p.groupAction === 'Replace') ? { groupIds } : {}),
+ sendFormat: 'MULTIPART',
+ },
});
-
- const client = makeClient(context.auth);
- return await client.createContact(audienceId, email, updateAction, groupAction, tagAction, tagIds, groupIds, firstName, lastName, streetAddress, streetAddress2, addressLocality, addressRegion, postalCode, addressCountry,
- audienceDataFields);
},
});
+
+function contactTextFields(p: Record<string, unknown>): Record<string, string> {
+ const keys = ['firstName', 'lastName', 'streetAddress', 'streetAddress2', 'addressLocality', 'addressRegion', 'postalCode', 'addressCountry'];
+ return Object.fromEntries(keys.flatMap((key) => {
+ const value = tarventCommon.trimmed(p[key]);
+ return value === undefined ? [] : [[key, value]];
+ }));
+}
diff --git a/packages/pieces/community/tarvent/src/lib/actions/create-suppression-filter.ts b/packages/pieces/community/tarvent/src/lib/actions/create-suppression-filter.ts
index bd38f939221..e4a174ca9a4 100644
--- a/packages/pieces/community/tarvent/src/lib/actions/create-suppression-filter.ts
+++ b/packages/pieces/community/tarvent/src/lib/actions/create-suppression-filter.ts
@@ -1,40 +1,46 @@
-import { propsValidation } from '@activepieces/pieces-common';
import { createAction, Property } from '@activepieces/pieces-framework';
-import * as z from 'zod/mini'
import { tarventAuth } from '../auth';
-import { makeClient } from '../common';
+import { tarventCommon } from '../common';
+import { tarventTransport } from '../common/transport';
+import { tarventOutputSchemas } from '../output-schemas';
export const createSuppressionFilter = createAction({
auth: tarventAuth,
name: 'tarvent_create_suppression_filter',
- classification: 'DESTRUCTIVE',
+ classification: 'WRITE',
displayName: 'Add Contact To Suppression List',
- description: 'Creates a suppression filter in your account to suppress a contact.',
+ description: 'Creates a suppression filter in your account so an email address receives no more email.',
audience: 'both',
- aiMetadata: { description: 'Adds an email address to the Tarvent account-level suppression list so it is blocked from future sends, with an optional reason. Use to permanently stop messaging a specific address. Not idempotent: each call creates another suppression filter record.', idempotent: false },
+ aiMetadata: {
+ description:
+ 'Adds one email address to the Tarvent account-level suppression list (with an optional reason up to 255 characters) so no campaign or transactional email is sent to it from any audience. Reversible with Remove From Suppression List. Returns the filter ID. Not idempotent: each call creates another suppression filter record.',
+ idempotent: false,
+ },
+ outputSchema: tarventOutputSchemas.suppressionFilter,
props: {
email: Property.ShortText({
displayName: 'Email address',
- description: 'Enter the email to add to the suppression list.',
+ description: 'The email to add to the suppression list.',
required: true,
- defaultValue: '',
}),
reason: Property.LongText({
displayName: 'Suppression reason',
- description: 'Use the description to describe why this contact is being suppressed.',
+ description: 'Why this contact is being suppressed (255 character limit).',
required: false,
- defaultValue: '',
- })
+ }),
},
async run(context) {
- const { email, reason } = context.propsValue;
-
- await propsValidation.validateZod(context.propsValue, {
- email: z.string().check(z.minLength(1), z.maxLength(100, 'Email has no more than 100 characters.')),
- reason: z.string().check(z.minLength(0), z.maxLength(255, 'Suppression reason has no more than 255 characters.')),
+ const email = tarventCommon.requireText({ value: context.propsValue.email, label: 'Email address' });
+ const reason = tarventCommon.trimmed(context.propsValue.reason);
+ tarventCommon.checkLength({ value: email, label: 'Email address', max: 320 });
+ tarventCommon.checkLength({ value: reason, label: 'Suppression reason', max: 255 });
+ const { localPart, domain } = tarventCommon.splitEmail(email);
+ return tarventTransport.field<Record<string, unknown>>({
+ auth: context.auth.props,
+ query: 'mutation CreateSuppressionFilter($input: CreateSuppressionFilterInput!) { createAccountSuppressionFilter(input: $input) { id localPart domain reason createdUtc } }',
+ variables: { input: { localPart, domain, reason: reason ?? '' } },
+ name: 'createAccountSuppressionFilter',
});
-
- const client = makeClient(context.auth);
- return await client.createSuppressionFilter(email, reason);
},
});
+
diff --git a/packages/pieces/community/tarvent/src/lib/actions/create-transaction.ts b/packages/pieces/community/tarvent/src/lib/actions/create-transaction.ts
index dfaac27861f..d221a2b34ba 100644
--- a/packages/pieces/community/tarvent/src/lib/actions/create-transaction.ts
+++ b/packages/pieces/community/tarvent/src/lib/actions/create-transaction.ts
@@ -1,36 +1,38 @@
-import { tarventAuth } from '../auth';
import { createAction, Property } from '@activepieces/pieces-framework';
-import { makeClient, tarventCommon } from '../common';
-import { propsValidation } from '@activepieces/pieces-common';
-import * as z from 'zod/mini'
+import { tarventAuth } from '../auth';
+import { tarventCommon } from '../common';
+import { TarventApiError, TarventCredentials, tarventTransport } from '../common/transport';
+import { tarventOutputSchemas } from '../output-schemas';
export const createTransaction = createAction({
auth: tarventAuth,
name: 'tarvent_create_transaction',
classification: 'WRITE',
displayName: 'Send A Transactional Email',
- description: 'Sends a transactional email. NOTE: This will use your email API credits.',
- audience: 'both',
- aiMetadata: { description: 'Sends a one-off transactional email through Tarvent to a specified recipient (with optional CC/BCC), using either an existing template or inline HTML/plain-text content with merge variables. Use for individual triggered messages such as receipts or confirmations, not bulk campaigns. Consumes email API credits and sends on every call, so it is not idempotent.', idempotent: false },
+ description: 'Sends a transactional email. NOTE: This uses your Tarvent email API credits (a paid add-on).',
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Sends one transactional email through Tarvent, optionally ignoring the account suppression filters. Human-only; agents use the AI variant, which always respects suppression filters. Not idempotent: every call sends another email.',
+ idempotent: false,
+ },
+ outputSchema: tarventOutputSchemas.transactionSent,
props: {
groupName: tarventCommon.txGroupName(false, 'Choose an existing group name or use "Custom" to enter a new group name. This name is used for reporting.'),
fromEmail: Property.ShortText({
displayName: 'From email',
description: 'Enter who this transaction is from.',
required: true,
- defaultValue: ''
}),
fromName: Property.ShortText({
displayName: 'From name',
description: 'Enter a friendly name for who this transaction is from.',
required: false,
- defaultValue: ''
}),
toEmail: Property.ShortText({
displayName: 'To email',
description: 'Enter the email that the transaction should be sent to.',
required: true,
- defaultValue: ''
}),
ccEmail: Property.Array({
displayName: 'CC Emails',
@@ -39,7 +41,6 @@ export const createTransaction = createAction({
email: Property.ShortText({
displayName: 'Email',
required: false,
- defaultValue: ''
})
},
required: false,
@@ -52,7 +53,6 @@ export const createTransaction = createAction({
email: Property.ShortText({
displayName: 'Email',
required: false,
- defaultValue: ''
})
},
required: false,
@@ -62,25 +62,21 @@ export const createTransaction = createAction({
displayName: 'Subject line',
description: 'Enter a subject line for the transaction.',
required: true,
- defaultValue: ''
}),
replyToEmail: Property.ShortText({
displayName: 'Reply to email',
description: 'Enter the email that the replies should go to.',
required: true,
- defaultValue: ''
}),
replyToName: Property.ShortText({
displayName: 'Reply to name',
description: 'Enter a friendly name the replies should go to.',
required: false,
- defaultValue: ''
}),
variables: Property.Object({
displayName: 'Variables',
- description: 'NOTE: Variable names (first column) can have Letters, numbers, underscores, and hyphens. Any other characters in the first column only will be removed.',
+ description: 'NOTE: Variable names (first column) keep only letters and numbers; any other characters are removed.',
required: false,
- defaultValue: '',
}),
templateId: tarventCommon.templateId(false, 'Select which template you\'d like to used for this transaction.'),
mimeType: Property.StaticDropdown({
@@ -108,8 +104,8 @@ export const createTransaction = createAction({
}),
ignoreSuppressCheck: Property.StaticDropdown({
displayName: 'Ignore suppression filters',
- description: 'Select if the suppression filters on your account should be ignored for this transaction.',
- required: true,
+ description: 'Select if the suppression filters on your account should be ignored for this transaction. Leave as "Do not ignore" unless you are sure the recipient wants this email.',
+ required: false,
options: {
options: [
{
@@ -127,18 +123,142 @@ export const createTransaction = createAction({
})
},
async run(context) {
- const { groupName, fromEmail, fromName, toEmail, ccEmail, bccEmail, subject, replyToEmail, replyToName, variables, templateId, mimeType, content, ignoreSuppressCheck } = context.propsValue;
-
- await propsValidation.validateZod(context.propsValue, {
- groupName: z.optional(z.string().check(z.maxLength(100, 'Group name has to be equal to or less than 100 characters.'))),
- fromEmail: z.string().check(z.maxLength(320, 'From email has to be equal to or less than 320 characters.')),
- fromName: z.optional(z.string().check(z.maxLength(255, 'From name has to be equal to or less than 255 characters.'))),
- subject: z.string().check(z.maxLength(500, 'Subject has to be equal to or less than 500 characters.')),
- replyToEmail: z.string().check(z.maxLength(320, 'Reply to email has to be equal to or less than 320 characters.')),
- replyToName: z.optional(z.string().check(z.maxLength(255, 'Reply to name has to be equal to or less than 255 characters.'))),
- });
+ return sendTransaction({ auth: context.auth.props, p: context.propsValue, ignoreSuppressCheck: String(context.propsValue.ignoreSuppressCheck) === 'true' });
+ },
+});
- const client = makeClient(context.auth);
- return await client.createTransaction(groupName, fromEmail, fromName, toEmail, ccEmail, bccEmail, subject, replyToEmail, replyToName, variables, templateId, mimeType, content, ignoreSuppressCheck);
+export const createTransactionAi = createAction({
+ auth: tarventAuth,
+ name: 'tarvent_create_transaction_ai',
+ classification: 'WRITE',
+ displayName: 'Send A Transactional Email (AI)',
+ description: 'Sends a transactional email that always respects your suppression filters. Uses Tarvent email API credits (a paid add-on).',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Sends one transactional email through Tarvent to one TO recipient (with optional CC/BCC), using either an existing template ID or inline HTML/plain-text content with merge variables. Use for individual triggered messages such as receipts or confirmations, never for bulk marketing. Requires the paid Transactional Email API add-on and uses credits. Always respects the account suppression filters. Fails if Tarvent rejects the TO recipient; CC/BCC rejections are reported per recipient in the output. Not idempotent: every call sends another email.',
+ idempotent: false,
+ },
+ outputSchema: tarventOutputSchemas.transactionSent,
+ props: agentProps(),
+ async run(context) {
+ return sendTransaction({ auth: context.auth.props, p: context.propsValue, ignoreSuppressCheck: false });
},
});
+
+
+function agentProps() {
+ const { ignoreSuppressCheck: _ignoreSuppressCheck, groupName: _groupName, templateId: _templateId, ...rest } = createTransaction.props;
+ return {
+ ...rest,
+ groupName: Property.ShortText({ displayName: 'Transaction group name', description: 'Optional reporting group name.', required: false }),
+ templateId: Property.ShortText({ displayName: 'Template ID', description: 'Tarvent template ID. Leave empty to send Content instead.', required: false }),
+ };
+}
+
+async function sendTransaction({ auth, p, ignoreSuppressCheck }: { auth: TarventCredentials; p: TransactionInput; ignoreSuppressCheck: boolean }) {
+ const fromEmail = tarventCommon.requireText({ value: p.fromEmail, label: 'From email' });
+ const toEmail = tarventCommon.requireText({ value: p.toEmail, label: 'To email' });
+ const subject = tarventCommon.requireText({ value: p.subject, label: 'Subject line' });
+ const replyToEmail = tarventCommon.requireText({ value: p.replyToEmail, label: 'Reply to email' });
+ const groupName = tarventCommon.trimmed(p.groupName);
+ const fromName = tarventCommon.trimmed(p.fromName);
+ const replyToName = tarventCommon.trimmed(p.replyToName);
+ const templateId = tarventCommon.trimmed(p.templateId);
+ const content = typeof p.content === 'string' && p.content.trim().length > 0 ? p.content : undefined;
+ tarventCommon.checkLength({ value: groupName, label: 'Group name', max: 100 });
+ tarventCommon.checkLength({ value: fromEmail, label: 'From email', max: 320 });
+ tarventCommon.checkLength({ value: fromName, label: 'From name', max: 255 });
+ tarventCommon.checkLength({ value: subject, label: 'Subject line', max: 500 });
+ tarventCommon.checkLength({ value: replyToEmail, label: 'Reply to email', max: 320 });
+ tarventCommon.checkLength({ value: replyToName, label: 'Reply to name', max: 255 });
+ if (!templateId && !content) {
+ throw new Error('Choose a Template or enter Content.');
+ }
+ if (!templateId && p.mimeType !== 'HTML' && p.mimeType !== 'TEXT') {
+ throw new Error('Choose a Message type (HTML or Plain text) when sending Content without a template.');
+ }
+ const variables = Object.entries(p.variables ?? {}).flatMap(([name, value]) => {
+ const clean = name.replace(/[^A-Za-z0-9]/g, '');
+ return clean.length > 0 ? [{ name: clean, value }] : [];
+ });
+ const recipients = [
+ { emailAddress: toEmail, type: 'TO', variables },
+ ...emailList(p.ccEmail).map((emailAddress) => ({ emailAddress, type: 'CC', variables })),
+ ...emailList(p.bccEmail).map((emailAddress) => ({ emailAddress, type: 'BCC', variables })),
+ ];
+ const results = await tarventTransport.field<TransactionResult[]>({
+ auth,
+ query: 'mutation CreateTransaction($input: CreateTransactionInput!) { createTransaction(input: $input) { emailAddress errorCode errorMsg requestId transactionId } }',
+ variables: {
+ input: {
+ content: {
+ templateId: templateId ?? null,
+ contentBodies: templateId ? null : [{ bodyContent: (content ?? '').replace(/\[\[/g, '{{').replace(/\]\]/g, '}}'), mimeType: p.mimeType }],
+ },
+ groupName,
+ header: {
+ from: { emailAddress: fromEmail, name: fromName ?? '' },
+ replyTo: { emailAddress: replyToEmail, name: replyToName ?? '' },
+ subject,
+ },
+ recipients,
+ settings: { ignoreSuppressCheck: ignoreSuppressCheck },
+ },
+ },
+ name: 'createTransaction',
+ });
+ const toResult = results.find((r) => (r.emailAddress ?? '').toLowerCase() === toEmail.toLowerCase()) ?? results[0];
+ if (!toResult || toResult.errorCode || toResult.errorMsg) {
+ throw new TarventApiError(
+ `Tarvent did not send the email to ${toEmail}: ${toResult?.errorMsg ?? 'no result returned'}${toResult?.errorCode ? ` (code ${toResult.errorCode})` : ''}`,
+ toResult?.errorCode ? String(toResult.errorCode) : undefined,
+ 200,
+ results,
+ );
+ }
+ return {
+ requestId: toResult.requestId ?? null,
+ transactionId: toResult.transactionId ?? null,
+ recipients: results.map((r) => ({
+ emailAddress: r.emailAddress ?? null,
+ transactionId: r.transactionId ?? null,
+ errorCode: r.errorCode ?? null,
+ errorMsg: r.errorMsg ?? null,
+ sent: !r.errorCode && !r.errorMsg,
+ })),
+ };
+}
+
+function emailList(value: unknown): string[] {
+ if (!Array.isArray(value)) {
+ return [];
+ }
+ return value.flatMap((row: unknown) => {
+ const email = typeof row === 'object' && row !== null ? tarventCommon.trimmed(Reflect.get(row, 'email')) : undefined;
+ return email ? [email] : [];
+ });
+}
+
+type TransactionResult = {
+ emailAddress?: string | null;
+ errorCode?: string | number | null;
+ errorMsg?: string | null;
+ requestId?: string | null;
+ transactionId?: string | null;
+};
+
+type TransactionInput = {
+ groupName?: unknown;
+ fromEmail?: unknown;
+ fromName?: unknown;
+ toEmail?: unknown;
+ ccEmail?: unknown;
+ bccEmail?: unknown;
+ subject?: unknown;
+ replyToEmail?: unknown;
+ replyToName?: unknown;
+ variables?: Record<string, unknown>;
+ templateId?: unknown;
+ mimeType?: unknown;
+ content?: unknown;
+};
diff --git a/packages/pieces/community/tarvent/src/lib/actions/custom-api-call.ts b/packages/pieces/community/tarvent/src/lib/actions/custom-api-call.ts
new file mode 100644
index 00000000000..37c3631a8ed
--- /dev/null
+++ b/packages/pieces/community/tarvent/src/lib/actions/custom-api-call.ts
@@ -0,0 +1,135 @@
+import { createCustomApiCallAction, httpClient, HttpMethod, toFailsafeOutput } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { tarventAuth } from '../auth';
+import { tarventTransport } from '../common/transport';
+import { tarventOutputSchemas } from '../output-schemas';
+
+const base = createCustomApiCallAction({
+ auth: tarventAuth,
+ baseUrl: () => tarventTransport.baseUrl,
+ authMapping: async (auth) => tarventTransport.authHeaders(auth.props),
+});
+
+export const tarventCustomApiCall = createAction({
+ auth: tarventAuth,
+ name: base.name,
+ displayName: base.displayName,
+ description: 'Send a raw GraphQL request to Tarvent (POST /graphql with a JSON body of query and variables). The API key and account ID headers are added for you. Note: Tarvent reports GraphQL errors with HTTP 200, so check body.errors.',
+ audience: 'human',
+ classification: 'WRITE',
+ outputSchema: tarventOutputSchemas.customApiCall,
+ aiMetadata: {
+ description:
+ 'Sends any request to the Tarvent API at https://api.tarvent.com (normally POST /graphql with a query and variables) using the connection API key and account ID, for operations the other actions do not cover. Returns the status, headers and body; GraphQL errors appear in body.errors with HTTP 200. Can change data when the query is a mutation.',
+ idempotent: false,
+ },
+ props: base.props,
+ propertyGroups: base.propertyGroups,
+ async run({ auth, propsValue, files }) {
+ const method = methodOf({ value: propsValue.method });
+ const url = urlOf({ value: propsValue.url });
+ const request = {
+ method,
+ url,
+ headers: {
+ ...stringRecord({ value: propsValue.headers }),
+ ...tarventTransport.authHeaders(auth.props),
+ },
+ queryParams: stringRecord({ value: propsValue.queryParams }),
+ timeout: typeof propsValue.timeout === 'number' && propsValue.timeout > 0 ? propsValue.timeout * 1000 : 0,
+ followRedirects: propsValue.followRedirects === true,
+ body: bodyOf({ body: propsValue.body, bodyType: propsValue.body_type }),
+ responseType: propsValue.response_is_binary ? ('arraybuffer' as const) : ('json' as const),
+ };
+ try {
+ const response = await httpClient.sendRequest(request, { dispatcher: await tarventTransport.verifiedTls() });
+ const data: unknown = response.body;
+ if (propsValue.response_is_binary && (Buffer.isBuffer(data) || data instanceof ArrayBuffer)) {
+ const buffer = Buffer.isBuffer(data) ? data : Buffer.from(new Uint8Array(data));
+ return { status: response.status, headers: response.headers, body: await files.write({ fileName: 'output.bin', data: buffer }) };
+ }
+ return { status: response.status, headers: response.headers, body: data };
+ } catch (error) {
+ if (propsValue.failsafe) {
+ return toFailsafeOutput({ error, requestBody: request.body });
+ }
+ throw error;
+ }
+ },
+});
+
+function methodOf({ value }: { value: unknown }): HttpMethod {
+ const method = Object.values(HttpMethod).find((option) => option === value);
+ if (!method) {
+ throw new Error('Method is required.');
+ }
+ return method;
+}
+
+function urlOf({ value }: { value: unknown }): string {
+ const raw = typeof value === 'object' && value !== null ? Reflect.get(value, 'url') : undefined;
+ const text = typeof raw === 'string' ? raw.trim() : '';
+ if (text.length === 0) {
+ throw new Error('URL is required.');
+ }
+ if (text.split(/[/?#]/).some((part) => part === '..' || part.toLowerCase() === '%2e%2e')) {
+ throw new Error('The URL must not contain ".." segments.');
+ }
+ if (/^[a-z][a-z0-9+.-]*:/i.test(text) || text.startsWith('//')) {
+ const parsed = new URL(text, tarventTransport.baseUrl);
+ if (parsed.origin !== tarventTransport.baseUrl || parsed.username || parsed.password) {
+ throw new Error(`The URL must be on ${tarventTransport.baseUrl}, so your Tarvent API key is not sent anywhere else.`);
+ }
+ return parsed.toString();
+ }
+ return `${tarventTransport.baseUrl}/${text.replace(/^\/+/, '')}`;
+}
+
+function stringRecord({ value }: { value: unknown }): Record<string, string> {
+ if (typeof value !== 'object' || value === null) {
+ return {};
+ }
+ return Object.fromEntries(
+ Object.entries(value).flatMap(([key, entry]) =>
+ entry === undefined || entry === null ? [] : [[key, typeof entry === 'string' ? entry : JSON.stringify(entry)]]
+ )
+ );
+}
+
+function bodyOf({ body, bodyType }: { body: unknown; bodyType: unknown }): FormData | string | Record<string, unknown> | unknown[] | undefined {
+ if (!bodyType || bodyType === 'none' || typeof body !== 'object' || body === null) {
+ return undefined;
+ }
+ const data: unknown = Reflect.get(body, 'data');
+ if (bodyType === 'raw') {
+ return typeof data === 'string' ? data : undefined;
+ }
+ if (bodyType === 'json') {
+ if (Array.isArray(data)) {
+ return data;
+ }
+ return typeof data === 'object' && data !== null ? Object.fromEntries(Object.entries(data)) : undefined;
+ }
+ if (bodyType === 'form_data' && Array.isArray(data)) {
+ const form = new FormData();
+ for (const field of data) {
+ const name: unknown = Reflect.get(field, 'fieldName');
+ const text: unknown = Reflect.get(field, 'textFieldValue');
+ const file: unknown = Reflect.get(field, 'fileFieldValue');
+ if (typeof name !== 'string') {
+ continue;
+ }
+ if (Reflect.get(field, 'fieldType') === 'file' && typeof file === 'object' && file !== null) {
+ const fileData: unknown = Reflect.get(file, 'data');
+ const filename: unknown = Reflect.get(file, 'filename');
+ if (Buffer.isBuffer(fileData)) {
+ form.append(name, new Blob([new Uint8Array(fileData)]), typeof filename === 'string' ? filename : 'file');
+ }
+ } else if (typeof text === 'string') {
+ form.append(name, text);
+ }
+ }
+ return form;
+ }
+ return undefined;
+}
diff --git a/packages/pieces/community/tarvent/src/lib/actions/delete-contact.ts b/packages/pieces/community/tarvent/src/lib/actions/delete-contact.ts
new file mode 100644
index 00000000000..d8a33d10deb
--- /dev/null
+++ b/packages/pieces/community/tarvent/src/lib/actions/delete-contact.ts
@@ -0,0 +1,27 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { tarventAuth } from '../auth';
+import { tarventCommon } from '../common';
+import { tarventOperations } from '../common/operations';
+import { tarventOutputSchemas } from '../output-schemas';
+
+export const deleteContact = createAction({
+ auth: tarventAuth,
+ name: 'tarvent_delete_contact',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Delete Contact',
+ description: 'Permanently deletes a contact from an audience.',
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Permanently deletes one Tarvent contact (by audience ID and contact ID) including its history; this cannot be undone. To stop emailing someone without deleting them use Subscribe/Unsubscribe Contact or Add Contact To Suppression List. Fails if the contact does not exist, so a second call with the same ID fails.',
+ idempotent: false,
+ },
+ outputSchema: tarventOutputSchemas.deleteContact,
+ props: {
+ audienceId: tarventCommon.audienceId(true, 'Audience the contact belongs to.'),
+ contactId: tarventCommon.contactId,
+ },
+ async run(context) {
+ return tarventOperations.deleteContact({ auth: context.auth.props, audienceId: context.propsValue.audienceId, contactId: context.propsValue.contactId });
+ },
+});
diff --git a/packages/pieces/community/tarvent/src/lib/actions/generate-custom-event.ts b/packages/pieces/community/tarvent/src/lib/actions/generate-custom-event.ts
index b4f86beda5e..acc9e249a37 100644
--- a/packages/pieces/community/tarvent/src/lib/actions/generate-custom-event.ts
+++ b/packages/pieces/community/tarvent/src/lib/actions/generate-custom-event.ts
@@ -1,23 +1,27 @@
import { createAction } from '@activepieces/pieces-framework';
import { tarventAuth } from '../auth';
-import { makeClient, tarventCommon } from '../common';
+import { tarventCommon } from '../common';
+import { tarventOperations } from '../common/operations';
+import { tarventOutputSchemas } from '../output-schemas';
export const generateCustomEvent = createAction({
auth: tarventAuth,
name: 'tarvent_generate_custom_event',
classification: 'WRITE',
displayName: 'Generate A Custom Event',
- description: 'Generate a custom event in your Tarvent account.',
- audience: 'both',
- aiMetadata: { description: 'Fires a predefined custom event in Tarvent for a specific contact, which can drive journeys and automations listening for that event. Use to signal that a contact performed a tracked action. Not idempotent: each call emits another event occurrence.', idempotent: false },
+ description: 'Records a custom event for a contact in your Tarvent account.',
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Records a predefined Tarvent custom event (by its event key) for one contact (by contact ID); journeys and automations listening for that event can then run. Use Find Custom Event to get the key. Not idempotent: each call records another event occurrence.',
+ idempotent: false,
+ },
+ outputSchema: tarventOutputSchemas.customEventGenerated,
props: {
- customEventId: tarventCommon.customEventId(true, ''),
- contactId: tarventCommon.contactId
+ customEventId: tarventCommon.customEventId(true, 'The custom event to record (its key is sent).'),
+ contactId: tarventCommon.contactId,
},
async run(context) {
- const { customEventId, contactId } = context.propsValue;
-
- const client = makeClient(context.auth);
- return await client.generateCustomEvent(contactId,customEventId);
+ return tarventOperations.recordCustomEvent({ auth: context.auth.props, contactId: context.propsValue.contactId, eventKey: context.propsValue.customEventId });
},
});
diff --git a/packages/pieces/community/tarvent/src/lib/actions/get-audience-groups.ts b/packages/pieces/community/tarvent/src/lib/actions/get-audience-groups.ts
index e154aee5283..e8c1660d858 100644
--- a/packages/pieces/community/tarvent/src/lib/actions/get-audience-groups.ts
+++ b/packages/pieces/community/tarvent/src/lib/actions/get-audience-groups.ts
@@ -1,29 +1,29 @@
import { createAction, Property } from '@activepieces/pieces-framework';
import { tarventAuth } from '../auth';
-import { makeClient, tarventCommon } from '../common';
+import { tarventCommon } from '../common';
+import { tarventOperations } from '../common/operations';
+import { tarventOutputSchemas } from '../output-schemas';
export const getAudienceGroups = createAction({
auth: tarventAuth,
name: 'tarvent_get_audience_groups',
classification: 'SEARCH',
displayName: 'Find Audience Group',
- description: 'Finds an audience group by name.',
- audience: 'both',
- aiMetadata: { description: 'Searches the groups within a given Tarvent audience, optionally filtered by name; leaving the name empty returns all groups in that audience. Use to look up a group or its ID before assigning contacts. Idempotent read-only lookup.', idempotent: true },
+ description: 'Finds static groups in an audience by name.',
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Searches the static (non-dynamic) groups of one Tarvent audience whose name contains the given text; an empty name returns all groups. Returns up to 50 per call with totalCount, hasMore and nextCursor (pass it back as Cursor for more). Use to get a group ID before adding contacts to it. Read-only.',
+ idempotent: true,
+ },
+ outputSchema: tarventOutputSchemas.audienceGroupPage,
props: {
- audienceId: tarventCommon.audienceId(true, ''),
- name: Property.ShortText({
- displayName: 'Audience name',
- description: 'Find an audience by searching using its name.',
- required: false,
- defaultValue: '',
-
- })
+ audienceId: tarventCommon.audienceId(true, 'Audience to search.'),
+ name: Property.ShortText({ displayName: 'Group name', description: 'Find groups whose name contains this text.', required: false }),
+ limit: tarventCommon.limit,
+ cursor: tarventCommon.cursor,
},
async run(context) {
- const { audienceId, name } = context.propsValue;
-
- const client = makeClient(context.auth);
- return await client.listAudienceGroupsAdv(audienceId, name);
+ return tarventOperations.findAudienceGroups({ auth: context.auth.props, audienceId: context.propsValue.audienceId, name: context.propsValue.name, limit: context.propsValue.limit, cursor: context.propsValue.cursor });
},
});
diff --git a/packages/pieces/community/tarvent/src/lib/actions/get-audiences.ts b/packages/pieces/community/tarvent/src/lib/actions/get-audiences.ts
index 45c7f6d2b72..0dfc7514820 100644
--- a/packages/pieces/community/tarvent/src/lib/actions/get-audiences.ts
+++ b/packages/pieces/community/tarvent/src/lib/actions/get-audiences.ts
@@ -1,34 +1,40 @@
import { createAction, Property } from '@activepieces/pieces-framework';
import { tarventAuth } from '../auth';
-import { makeClient } from '../common';
+import { tarventCommon } from '../common';
+import { tarventClient } from '../common/client';
+import { tarventOutputSchemas } from '../output-schemas';
export const getAudiences = createAction({
auth: tarventAuth,
name: 'tarvent_get_audiences',
classification: 'SEARCH',
displayName: 'Find Audience',
- description: 'Finds an audience by name or tags.',
+ description: 'Finds audiences by name or tags.',
audience: 'both',
- aiMetadata: { description: 'Searches Tarvent audiences, optionally filtered by name and/or comma-separated tags; leaving the filters empty returns all audiences. Use to look up an audience or its ID before acting on contacts. Idempotent read-only lookup.', idempotent: true },
+ aiMetadata: {
+ description:
+ 'Searches Tarvent audiences whose name contains the given text and/or that have any of the given comma-separated tags; empty filters return all audiences. Returns up to 50 per call with totalCount, hasMore and nextCursor (pass it back as Cursor for more). Use to get an audience ID. Read-only.',
+ idempotent: true,
+ },
+ outputSchema: tarventOutputSchemas.audiencePage,
props: {
- name: Property.ShortText({
- displayName: 'Audience name',
- description: 'Find an audience by searching using its name.',
- required: false,
- defaultValue: '',
-
- }),
- tags: Property.LongText({
- displayName: 'Audience tags',
- description: 'Find an audience by searching using its tags. To search using multiple tags, separate the tags with a comma.',
- required: false,
- defaultValue: '',
- })
+ name: Property.ShortText({ displayName: 'Audience name', description: 'Find audiences whose name contains this text.', required: false }),
+ tags: Property.LongText({ displayName: 'Audience tags', description: 'Find audiences with any of these tags. Separate multiple tags with a comma.', required: false }),
+ limit: tarventCommon.limit,
+ cursor: tarventCommon.cursor,
},
async run(context) {
- const { name, tags } = context.propsValue;
-
- const client = makeClient(context.auth);
- return await client.listAudiencesAdv(name, tags);
+ return tarventClient.listPage({
+ auth: context.auth.props,
+ operation: 'FindAudiences',
+ field: 'audiences',
+ selection: tarventClient.fields.audience,
+ argDefs: ', $where: AudienceInfoFilterInput',
+ args: ', where: $where',
+ variables: { where: tarventClient.audienceWhere({ name: context.propsValue.name, tags: context.propsValue.tags }) },
+ first: tarventCommon.pageLimit(context.propsValue.limit),
+ after: tarventCommon.trimmed(context.propsValue.cursor),
+ withTotalCount: true,
+ });
},
});
diff --git a/packages/pieces/community/tarvent/src/lib/actions/get-campaign-stats.ts b/packages/pieces/community/tarvent/src/lib/actions/get-campaign-stats.ts
new file mode 100644
index 00000000000..1120c0a8a0e
--- /dev/null
+++ b/packages/pieces/community/tarvent/src/lib/actions/get-campaign-stats.ts
@@ -0,0 +1,33 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { tarventAuth } from '../auth';
+import { tarventCommon } from '../common';
+import { tarventClient } from '../common/client';
+import { tarventTransport } from '../common/transport';
+import { tarventOutputSchemas } from '../output-schemas';
+
+export const getCampaignStats = createAction({
+ auth: tarventAuth,
+ name: 'tarvent_get_campaign_stats',
+ classification: 'READ',
+ displayName: 'Get Campaign Stats',
+ description: 'Gets delivery and engagement stats for a campaign.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Gets the totals for one Tarvent campaign by campaign ID: sent, delivered, opens, clicks, replies, bounces, opt-outs and spam complaints, with unique counts and percentages. Use Find Campaign to get the ID. Fails if the campaign does not exist. Read-only.',
+ idempotent: true,
+ },
+ outputSchema: tarventOutputSchemas.campaignStats,
+ props: {
+ campaignId: Property.ShortText({ displayName: 'Campaign ID', description: 'The campaign ID (from Find Campaign).', required: true }),
+ },
+ async run(context) {
+ const id = tarventCommon.requireText({ value: context.propsValue.campaignId, label: 'Campaign ID' });
+ return tarventTransport.field<Record<string, unknown>>({
+ auth: context.auth.props,
+ query: `query GetCampaignStats($input: CampaignStatsInput!) { campaignStats(input: $input) { ${tarventClient.fields.campaignStats} } }`,
+ variables: { input: { id } },
+ name: 'campaignStats',
+ });
+ },
+});
diff --git a/packages/pieces/community/tarvent/src/lib/actions/get-campaigns.ts b/packages/pieces/community/tarvent/src/lib/actions/get-campaigns.ts
index aaf8885786f..01577bc749e 100644
--- a/packages/pieces/community/tarvent/src/lib/actions/get-campaigns.ts
+++ b/packages/pieces/community/tarvent/src/lib/actions/get-campaigns.ts
@@ -1,71 +1,56 @@
import { createAction, Property } from '@activepieces/pieces-framework';
import { tarventAuth } from '../auth';
-import { makeClient } from '../common';
+import { tarventCommon } from '../common';
+import { tarventClient } from '../common/client';
+import { tarventOutputSchemas } from '../output-schemas';
export const getCampaigns = createAction({
auth: tarventAuth,
name: 'tarvent_get_campaigns',
classification: 'SEARCH',
displayName: 'Find Campaign',
- description: 'Finds a campaign by name, status or tags.',
+ description: 'Finds campaigns by name, status or tags.',
audience: 'both',
- aiMetadata: { description: 'Searches Tarvent campaigns, optionally filtered by name, comma-separated tags, and/or status (sent, draft, scheduled, paused, etc.); leaving the filters empty returns all campaigns. Use to look up a campaign or its ID, e.g. before sending it. Idempotent read-only lookup.', idempotent: true },
+ aiMetadata: {
+ description:
+ 'Searches Tarvent campaigns whose name contains the given text, that have any of the given comma-separated tags, and/or that are in a status (COMPLETED = sent, READY_TO_SEND, NOT_SCHEDULED = draft, PENDING = scheduled, Paused, STOPPED, SENDING_PENDING_AB_WINNER), newest first; empty filters return all campaigns. Returns up to 50 per call with totalCount, hasMore and nextCursor. Use to get a campaign ID for Get Campaign Stats. Read-only.',
+ idempotent: true,
+ },
+ outputSchema: tarventOutputSchemas.campaignPage,
props: {
- name: Property.ShortText({
- displayName: 'Campaign name',
- description: 'Find a campaign by searching using its name.',
- required: false,
- defaultValue: '',
-
- }),
- tags: Property.LongText({
- displayName: 'Campaign tags',
- description: 'Find a campaign by searching using its tags. To search using multiple tags, separate the tags with a comma.',
- required: false,
- defaultValue: '',
- }),
+ name: Property.ShortText({ displayName: 'Campaign name', description: 'Find campaigns whose name contains this text.', required: false }),
+ tags: Property.LongText({ displayName: 'Campaign tags', description: 'Find campaigns with any of these tags. Separate multiple tags with a comma.', required: false }),
status: Property.StaticDropdown({
displayName: 'Campaign status',
- description: '',
required: false,
options: {
options: [
- {
- label: 'Sent',
- value: 'COMPLETED'
- },
- {
- label: 'Ready to send',
- value: 'READY_TO_SEND'
- },
- {
- label: 'Draft',
- value: 'NOT_SCHEDULED'
- },
- {
- label: 'Scheduled',
- value: 'PENDING'
- },
- {
- label: 'Paused',
- value: 'Paused'
- },
- {
- label: 'Stopped',
- value: 'STOPPED'
- },
- {
- label: 'Pending multivariate winner',
- value: 'SENDING_PENDING_AB_WINNER'
- },
+ { label: 'Sent', value: 'COMPLETED' },
+ { label: 'Ready to send', value: 'READY_TO_SEND' },
+ { label: 'Draft', value: 'NOT_SCHEDULED' },
+ { label: 'Scheduled', value: 'PENDING' },
+ { label: 'Paused', value: 'Paused' },
+ { label: 'Stopped', value: 'STOPPED' },
+ { label: 'Pending multivariate winner', value: 'SENDING_PENDING_AB_WINNER' },
],
},
}),
+ limit: tarventCommon.limit,
+ cursor: tarventCommon.cursor,
},
async run(context) {
const { name, tags, status } = context.propsValue;
-
- const client = makeClient(context.auth);
- return await client.listCampaignsAdv(name, tags, status);
+ return tarventClient.listPage({
+ auth: context.auth.props,
+ operation: 'FindCampaigns',
+ field: 'campaigns',
+ selection: tarventClient.fields.campaign,
+ argDefs: ', $order: [CampaignInfoSortInput!], $where: CampaignInfoFilterInput',
+ args: ', order: $order, where: $where',
+ variables: { order: [{ modifiedUtc: 'DESC' }], where: tarventClient.campaignWhere({ name, tags, status }) },
+ first: tarventCommon.pageLimit(context.propsValue.limit),
+ after: tarventCommon.trimmed(context.propsValue.cursor),
+ withTotalCount: true,
+ });
},
});
diff --git a/packages/pieces/community/tarvent/src/lib/actions/get-contact.ts b/packages/pieces/community/tarvent/src/lib/actions/get-contact.ts
index a0aa69e944c..1f9e4da374c 100644
--- a/packages/pieces/community/tarvent/src/lib/actions/get-contact.ts
+++ b/packages/pieces/community/tarvent/src/lib/actions/get-contact.ts
@@ -1,34 +1,28 @@
import { createAction, Property } from '@activepieces/pieces-framework';
import { tarventAuth } from '../auth';
-import { makeClient, tarventCommon } from '../common';
-import { propsValidation } from '@activepieces/pieces-common';
-import * as z from 'zod/mini'
+import { tarventCommon } from '../common';
+import { tarventOperations } from '../common/operations';
+import { tarventOutputSchemas } from '../output-schemas';
export const getContact = createAction({
auth: tarventAuth,
name: 'tarvent_get_contact',
classification: 'READ',
displayName: 'Find Contact',
- description: 'Finds a contact by your custom key data field (typically this is by email).',
- audience: 'both',
- aiMetadata: { description: 'Looks up a contact within a Tarvent audience by email (the audience\'s key field). Use to retrieve a contact or its ID before acting on it. If the audience uses a custom identifier, this returns the first contact matching the email, so target a specific record by ID when precision matters. Idempotent read-only lookup.', idempotent: true },
+ description: 'Finds one contact in an audience by email or by contact ID.',
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Looks up a single Tarvent contact in an audience by email address or by contact ID (give exactly one). Returns found=false with contact=null when there is no match, instead of failing. If the audience uses a custom identifier, an email lookup returns the first contact with that email, so use the ID when precision matters. To list many contacts use List Contacts. Read-only.',
+ idempotent: true,
+ },
+ outputSchema: tarventOutputSchemas.findContact,
props: {
- audienceId: tarventCommon.audienceId(true, ''),
- email: Property.ShortText({
- displayName: 'Contact email',
- description: 'Search for a contact by email. If the audience uses a custom contact identifier, then the search returns the FIRST contact that matches the email address. To target a specific contact, please use the contact\'s ID.',
- required: true,
- defaultValue: ''
- })
+ audienceId: tarventCommon.audienceId(true, 'Audience to search.'),
+ email: Property.ShortText({ displayName: 'Contact email', description: 'Find the contact by email. A value without @ is treated as a contact ID, as in earlier versions.', required: false }),
+ contactId: Property.ShortText({ displayName: 'Contact ID', description: 'Find the contact by ID. Leave empty when using email.', required: false }),
},
async run(context) {
- const { audienceId, email } = context.propsValue;
-
- await propsValidation.validateZod(context.propsValue, {
- email: z.string().check(z.minLength(1), z.maxLength(255, 'Email has no more than 255 characters.')),
- });
-
- const client = makeClient(context.auth);
- return await client.listContact(audienceId, email);
+ return tarventOperations.findContact({ auth: context.auth.props, audienceId: context.propsValue.audienceId, email: context.propsValue.email, contactId: context.propsValue.contactId, legacyIdInEmail: true });
},
});
diff --git a/packages/pieces/community/tarvent/src/lib/actions/get-custom-event.ts b/packages/pieces/community/tarvent/src/lib/actions/get-custom-event.ts
index 8b5aff73d64..243de189568 100644
--- a/packages/pieces/community/tarvent/src/lib/actions/get-custom-event.ts
+++ b/packages/pieces/community/tarvent/src/lib/actions/get-custom-event.ts
@@ -1,28 +1,39 @@
import { createAction, Property } from '@activepieces/pieces-framework';
import { tarventAuth } from '../auth';
-import { makeClient } from '../common';
+import { tarventCommon } from '../common';
+import { tarventClient } from '../common/client';
+import { tarventOutputSchemas } from '../output-schemas';
export const getCustomEvent = createAction({
auth: tarventAuth,
name: 'tarvent_get_custom_event',
classification: 'SEARCH',
displayName: 'Find Custom Event',
- description: 'Finds a custom event by name.',
+ description: 'Finds custom events by name.',
audience: 'both',
- aiMetadata: { description: 'Searches the custom event definitions in a Tarvent account, optionally filtered by name; leaving the name empty returns all custom events. Use to look up a custom event or its ID before generating it for a contact. Idempotent read-only lookup.', idempotent: true },
+ aiMetadata: {
+ description:
+ 'Searches the custom event definitions in a Tarvent account whose name contains the given text; an empty name returns all. Returns up to 50 per call with hasMore and nextCursor. The key field is what Generate A Custom Event needs. Read-only.',
+ idempotent: true,
+ },
+ outputSchema: tarventOutputSchemas.customEventPage,
props: {
- name: Property.ShortText({
- displayName: 'Custom event name',
- description: 'Find a custom event by searching using its name.',
- required: false,
- defaultValue: '',
-
- })
+ name: Property.ShortText({ displayName: 'Custom event name', description: 'Find custom events whose name contains this text.', required: false }),
+ limit: tarventCommon.limit,
+ cursor: tarventCommon.cursor,
},
async run(context) {
- const { name } = context.propsValue;
-
- const client = makeClient(context.auth);
- return await client.listCustomEventsAdv(name);
+ const name = tarventCommon.trimmed(context.propsValue.name);
+ return tarventClient.listPage({
+ auth: context.auth.props,
+ operation: 'FindCustomEvents',
+ field: 'customApiEvents',
+ selection: 'id key name description createdUtc modifiedUtc',
+ argDefs: ', $where: CustomApiEventFilterInput',
+ args: ', where: $where',
+ variables: { where: name ? { name: { contains: name } } : null },
+ first: tarventCommon.pageLimit(context.propsValue.limit),
+ after: tarventCommon.trimmed(context.propsValue.cursor),
+ });
},
});
diff --git a/packages/pieces/community/tarvent/src/lib/actions/get-journey.ts b/packages/pieces/community/tarvent/src/lib/actions/get-journey.ts
index 9c406b934b9..6b509e5d6bc 100644
--- a/packages/pieces/community/tarvent/src/lib/actions/get-journey.ts
+++ b/packages/pieces/community/tarvent/src/lib/actions/get-journey.ts
@@ -1,51 +1,50 @@
import { createAction, Property } from '@activepieces/pieces-framework';
import { tarventAuth } from '../auth';
-import { makeClient } from '../common';
+import { tarventCommon } from '../common';
+import { tarventClient } from '../common/client';
+import { tarventOutputSchemas } from '../output-schemas';
export const getJourney = createAction({
auth: tarventAuth,
name: 'tarvent_get_journey',
classification: 'SEARCH',
displayName: 'Find Journey',
- description: 'Finds a journey by name, status or tags.',
+ description: 'Finds journeys by name, status or tags.',
audience: 'both',
- aiMetadata: { description: 'Searches Tarvent automation journeys, optionally filtered by name, comma-separated tags, and/or run status (running or not running); leaving the filters empty returns all journeys. Use to look up a journey or its ID before starting/stopping it or enrolling contacts. Idempotent read-only lookup.', idempotent: true },
+ aiMetadata: {
+ description:
+ 'Searches Tarvent automation journeys whose name contains the given text, that have any of the given comma-separated tags, and/or with run status RUNNING or NOT_RUNNING; empty filters return all journeys. Returns up to 50 per call with hasMore and nextCursor (pass it back as Cursor for more). Use to get a journey ID. Read-only.',
+ idempotent: true,
+ },
+ outputSchema: tarventOutputSchemas.journeyPage,
props: {
- name: Property.ShortText({
- displayName: 'Journey name',
- description: 'Find a journey by searching using its name.',
- required: false,
- defaultValue: '',
-
- }),
- tags: Property.LongText({
- displayName: 'Journey tags',
- description: 'Find a journey by searching using its tags. To search using multiple tags, separate the tags with a comma.',
- required: false,
- defaultValue: '',
- }),
+ name: Property.ShortText({ displayName: 'Journey name', description: 'Find journeys whose name contains this text.', required: false }),
+ tags: Property.LongText({ displayName: 'Journey tags', description: 'Find journeys with any of these tags. Separate multiple tags with a comma.', required: false }),
status: Property.StaticDropdown({
displayName: 'Journey status',
- description: '',
required: false,
options: {
options: [
- {
- label: 'Running',
- value: 'RUNNING'
- },
- {
- label: 'Not running',
- value: 'NOT_RUNNING'
- }
+ { label: 'Running', value: 'RUNNING' },
+ { label: 'Not running', value: 'NOT_RUNNING' },
],
},
}),
+ limit: tarventCommon.limit,
+ cursor: tarventCommon.cursor,
},
async run(context) {
const { name, tags, status } = context.propsValue;
-
- const client = makeClient(context.auth);
- return await client.listJourneysAdv(name, tags, status);
+ return tarventClient.listPage({
+ auth: context.auth.props,
+ operation: 'FindJourneys',
+ field: 'journeys',
+ selection: tarventClient.fields.journey,
+ argDefs: ', $where: JourneyInfoFilterInput',
+ args: ', where: $where',
+ variables: { where: tarventClient.journeyWhere({ name, tags, status }) },
+ first: tarventCommon.pageLimit(context.propsValue.limit),
+ after: tarventCommon.trimmed(context.propsValue.cursor),
+ });
},
});
diff --git a/packages/pieces/community/tarvent/src/lib/actions/get-transaction.ts b/packages/pieces/community/tarvent/src/lib/actions/get-transaction.ts
new file mode 100644
index 00000000000..d2aed6c36eb
--- /dev/null
+++ b/packages/pieces/community/tarvent/src/lib/actions/get-transaction.ts
@@ -0,0 +1,34 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { tarventAuth } from '../auth';
+import { tarventCommon } from '../common';
+import { tarventClient } from '../common/client';
+import { tarventTransport } from '../common/transport';
+import { tarventOutputSchemas } from '../output-schemas';
+
+export const getTransaction = createAction({
+ auth: tarventAuth,
+ name: 'tarvent_get_transaction',
+ classification: 'READ',
+ displayName: 'Get Transaction',
+ description: 'Gets the delivery status of a transactional email.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Gets the processing and engagement status of a Tarvent transactional email by the transaction ID returned from Send A Transactional Email: one record per recipient with status, error, bounce category, open and click counts. Returns found=false with no items when the ID is unknown. Read-only.',
+ idempotent: true,
+ },
+ outputSchema: tarventOutputSchemas.transaction,
+ props: {
+ transactionId: Property.ShortText({ displayName: 'Transaction ID', description: 'The transaction ID from Send A Transactional Email.', required: true }),
+ },
+ async run(context) {
+ const id = tarventCommon.requireText({ value: context.propsValue.transactionId, label: 'Transaction ID' });
+ const data = await tarventTransport.graphql<{ transaction?: Record<string, unknown>[] | null }>({
+ auth: context.auth.props,
+ query: `query GetTransaction($id: String!) { transaction(id: $id) { ${tarventClient.fields.transaction} } }`,
+ variables: { id },
+ });
+ const items = (data.transaction ?? []).filter((item) => item !== null);
+ return { found: items.length > 0, transactionId: id, items };
+ },
+});
diff --git a/packages/pieces/community/tarvent/src/lib/actions/index.ts b/packages/pieces/community/tarvent/src/lib/actions/index.ts
index 563979bcd2c..fe49159e589 100644
--- a/packages/pieces/community/tarvent/src/lib/actions/index.ts
+++ b/packages/pieces/community/tarvent/src/lib/actions/index.ts
@@ -1,18 +1,39 @@
export * from './create-contact';
+export * from './update-contact';
+export * from './get-contact';
+export * from './list-contacts';
+export * from './delete-contact';
export * from './create-transaction';
+export * from './get-transaction';
export * from './send-campaign';
+export * from './get-campaign-stats';
export * from './create-audience-group';
export * from './update-contact-tag';
export * from './create-contact-note';
+export * from './list-contact-notes';
export * from './update-contact-group';
export * from './update-contact-journey';
export * from './update-contact-status';
export * from './generate-custom-event';
export * from './update-journey-status';
export * from './create-suppression-filter';
+export * from './remove-suppression-filter';
export * from './get-audiences';
export * from './get-audience-groups';
export * from './get-campaigns';
-export * from './get-contact';
export * from './get-custom-event';
export * from './get-journey';
+export * from './list-tags';
+export * from './custom-api-call';
+export * from './ai/create-audience-group-ai';
+export * from './ai/delete-contact-ai';
+export * from './ai/find-audience-groups-ai';
+export * from './ai/find-contact-ai';
+export * from './ai/list-contacts-ai';
+export * from './ai/record-custom-event-ai';
+export * from './ai/set-contact-group-membership-ai';
+export * from './ai/set-contact-journey-ai';
+export * from './ai/set-contact-tags-ai';
+export * from './ai/set-journey-status-ai';
+export * from './ai/update-contact-ai';
+export * from './ai/upsert-contact-ai';
diff --git a/packages/pieces/community/tarvent/src/lib/actions/list-contact-notes.ts b/packages/pieces/community/tarvent/src/lib/actions/list-contact-notes.ts
new file mode 100644
index 00000000000..341981615d6
--- /dev/null
+++ b/packages/pieces/community/tarvent/src/lib/actions/list-contact-notes.ts
@@ -0,0 +1,39 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { tarventAuth } from '../auth';
+import { tarventCommon } from '../common';
+import { tarventClient } from '../common/client';
+import { tarventOutputSchemas } from '../output-schemas';
+
+export const listContactNotes = createAction({
+ auth: tarventAuth,
+ name: 'tarvent_list_contact_notes',
+ classification: 'READ',
+ displayName: 'List Contact Notes',
+ description: 'Lists the notes on a contact, newest first.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Lists the notes on one Tarvent contact by contact ID, newest first, up to 50 per call. Returns items plus hasMore and nextCursor; pass nextCursor back as Cursor for the next page. Read-only.',
+ idempotent: true,
+ },
+ outputSchema: tarventOutputSchemas.contactNotePage,
+ props: {
+ contactId: tarventCommon.contactId,
+ limit: tarventCommon.limit,
+ cursor: tarventCommon.cursor,
+ },
+ async run(context) {
+ const contactId = tarventCommon.requireText({ value: context.propsValue.contactId, label: 'Contact ID' });
+ return tarventClient.listPage({
+ auth: context.auth.props,
+ operation: 'ListContactNotes',
+ field: 'contactNotes',
+ selection: 'id message status createdBy createdUtc modifiedUtc',
+ argDefs: ', $contactId: String!, $order: [ContactNoteSortInput!]',
+ args: ', contactId: $contactId, order: $order',
+ variables: { contactId, order: [{ createdUtc: 'DESC' }] },
+ first: tarventCommon.pageLimit(context.propsValue.limit),
+ after: tarventCommon.trimmed(context.propsValue.cursor),
+ });
+ },
+});
diff --git a/packages/pieces/community/tarvent/src/lib/actions/list-contacts.ts b/packages/pieces/community/tarvent/src/lib/actions/list-contacts.ts
new file mode 100644
index 00000000000..8d47b777514
--- /dev/null
+++ b/packages/pieces/community/tarvent/src/lib/actions/list-contacts.ts
@@ -0,0 +1,29 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { tarventAuth } from '../auth';
+import { tarventCommon } from '../common';
+import { tarventOperations } from '../common/operations';
+import { tarventOutputSchemas } from '../output-schemas';
+
+export const listContacts = createAction({
+ auth: tarventAuth,
+ name: 'tarvent_list_contacts',
+ classification: 'SEARCH',
+ displayName: 'List Contacts',
+ description: 'Lists contacts in an audience, optionally only those in one group or segment.',
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Lists contacts in a Tarvent audience one page at a time (up to 50 per call), optionally limited to one audience group or segment ID. Returns items plus hasMore and nextCursor; pass nextCursor back as Cursor to get the next page. To fetch one known contact use Find Contact. Read-only.',
+ idempotent: true,
+ },
+ outputSchema: tarventOutputSchemas.contactPage,
+ props: {
+ audienceId: tarventCommon.audienceId(true, 'Audience to list.'),
+ groupId: tarventCommon.audienceGroupId(false, 'Only list contacts in this group.'),
+ limit: tarventCommon.limit,
+ cursor: tarventCommon.cursor,
+ },
+ async run(context) {
+ return tarventOperations.listContacts({ auth: context.auth.props, audienceId: context.propsValue.audienceId, groupId: context.propsValue.groupId, limit: context.propsValue.limit, cursor: context.propsValue.cursor });
+ },
+});
diff --git a/packages/pieces/community/tarvent/src/lib/actions/list-tags.ts b/packages/pieces/community/tarvent/src/lib/actions/list-tags.ts
new file mode 100644
index 00000000000..fb42ea7f2e3
--- /dev/null
+++ b/packages/pieces/community/tarvent/src/lib/actions/list-tags.ts
@@ -0,0 +1,34 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { tarventAuth } from '../auth';
+import { tarventCommon } from '../common';
+import { tarventClient } from '../common/client';
+import { tarventOutputSchemas } from '../output-schemas';
+
+export const listTags = createAction({
+ auth: tarventAuth,
+ name: 'tarvent_list_tags',
+ classification: 'SEARCH',
+ displayName: 'List Tags',
+ description: 'Lists the tags used in your account.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Lists the tag names used in the Tarvent account with how often each is used, up to 50 per call with hasMore and nextCursor. Use to pick existing tag names before tagging contacts. Read-only.',
+ idempotent: true,
+ },
+ outputSchema: tarventOutputSchemas.tagPage,
+ props: {
+ limit: tarventCommon.limit,
+ cursor: tarventCommon.cursor,
+ },
+ async run(context) {
+ return tarventClient.listPage({
+ auth: context.auth.props,
+ operation: 'ListTags',
+ field: 'tags',
+ selection: 'name count type isSystem',
+ first: tarventCommon.pageLimit(context.propsValue.limit),
+ after: tarventCommon.trimmed(context.propsValue.cursor),
+ });
+ },
+});
diff --git a/packages/pieces/community/tarvent/src/lib/actions/remove-suppression-filter.ts b/packages/pieces/community/tarvent/src/lib/actions/remove-suppression-filter.ts
new file mode 100644
index 00000000000..6ab5e448360
--- /dev/null
+++ b/packages/pieces/community/tarvent/src/lib/actions/remove-suppression-filter.ts
@@ -0,0 +1,72 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { tarventAuth } from '../auth';
+import { tarventCommon } from '../common';
+import { tarventClient } from '../common/client';
+import { tarventTransport } from '../common/transport';
+import { tarventOutputSchemas } from '../output-schemas';
+
+export const removeSuppressionFilter = createAction({
+ auth: tarventAuth,
+ name: 'tarvent_remove_suppression_filter',
+ classification: 'WRITE',
+ displayName: 'Remove From Suppression List',
+ description: 'Removes an email address from your account suppression list.',
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Removes an email address from the Tarvent account-level suppression list so it can receive email again. Give the email address (every filter that exactly matches it is removed) or a suppression filter ID. Returns the removed filter IDs; removed=0 means nothing matched. Idempotent: a second call finds nothing left to remove.',
+ idempotent: true,
+ },
+ outputSchema: tarventOutputSchemas.suppressionRemoved,
+ props: {
+ email: Property.ShortText({ displayName: 'Email address', description: 'Remove filters for this exact email address.', required: false }),
+ filterId: Property.ShortText({ displayName: 'Suppression filter ID', description: 'Or remove one filter by its ID.', required: false }),
+ },
+ async run(context) {
+ const auth = context.auth.props;
+ const email = tarventCommon.trimmed(context.propsValue.email);
+ const filterId = tarventCommon.trimmed(context.propsValue.filterId);
+ if ((email === undefined) === (filterId === undefined)) {
+ throw new Error('Enter either Email address or Suppression filter ID (exactly one).');
+ }
+ const ids = filterId ? [filterId] : await idsForEmail({ auth, email: email ?? '' });
+ const removed = [];
+ for (const id of ids) {
+ try {
+ await tarventClient.booleanMutation({
+ auth,
+ operation: 'DeleteSuppressionFilter',
+ field: 'deleteAccountSuppressionFilter',
+ argDefs: '$id: String!',
+ args: 'id: $id',
+ variables: { id },
+ });
+ removed.push(id);
+ } catch (error) {
+ if (!tarventClient.isNotFound(error)) {
+ throw error;
+ }
+ }
+ }
+ return { removed: removed.length, filterIds: removed };
+ },
+});
+
+async function idsForEmail({ auth, email }: { auth: Parameters<typeof tarventTransport.graphql>[0]['auth']; email: string }): Promise<string[]> {
+ const { localPart, domain } = tarventCommon.splitEmail(email);
+ const { items, truncated } = await tarventClient.listAll<{ id: string; localPart?: string | null; domain?: string | null }>({
+ auth,
+ operation: 'FindSuppressionFilters',
+ field: 'accountSuppressionFilters',
+ selection: 'id localPart domain',
+ argDefs: ', $where: AccountSuppressionFilterFilterInput',
+ args: ', where: $where',
+ variables: { where: { and: [{ localPart: { eq: localPart } }, { domain: { eq: domain } }] } },
+ });
+ if (truncated) {
+ throw new Error('Too many suppression filters match this email. Remove them by filter ID instead.');
+ }
+ return items
+ .filter((f) => (f.localPart ?? '').toLowerCase() === localPart.toLowerCase() && (f.domain ?? '').toLowerCase() === domain.toLowerCase())
+ .map((f) => f.id);
+}
diff --git a/packages/pieces/community/tarvent/src/lib/actions/send-campaign.ts b/packages/pieces/community/tarvent/src/lib/actions/send-campaign.ts
index 657d88f5fc3..17465d5ece3 100644
--- a/packages/pieces/community/tarvent/src/lib/actions/send-campaign.ts
+++ b/packages/pieces/community/tarvent/src/lib/actions/send-campaign.ts
@@ -1,24 +1,36 @@
import { createAction } from '@activepieces/pieces-framework';
import { tarventAuth } from '../auth';
-import { makeClient, tarventCommon } from '../common';
-
-
+import { tarventCommon } from '../common';
+import { tarventClient } from '../common/client';
+import { tarventOutputSchemas } from '../output-schemas';
export const sendCampaign = createAction({
auth: tarventAuth,
name: 'tarvent_send_campaign',
classification: 'WRITE',
displayName: 'Send Campaign',
- description: 'Sends a copy of a campaign.',
- audience: 'both',
- aiMetadata: { description: 'Triggers Tarvent to send a copy of an existing, fully configured campaign to its audience. Use to dispatch a prepared campaign; the campaign must already have its from address, subject, and content set up. Not idempotent: each call sends the campaign again.', idempotent: false },
+ description: 'Sends a copy of a campaign to its audience now.',
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Sends a copy of an existing, fully configured Tarvent campaign to its whole audience immediately. Every run emails the audience again. Not available to AI agents.',
+ idempotent: false,
+ },
+ outputSchema: tarventOutputSchemas.campaignSent,
props: {
- campaignId: tarventCommon.campaignId(true, 'Select which campaign to send. **NOTE:** Make sure all campaign settings are correct (from, subject, content) before configuring this automation.', true),
+ campaignId: tarventCommon.campaignId(true, 'Select which campaign to send. **NOTE:** Make sure all campaign settings are correct (from, subject, content) before configuring this automation. Every run sends the campaign to its audience again.', true),
},
async run(context) {
- const { campaignId } = context.propsValue;
-
- const client = makeClient(context.auth);
- return await client.sendCampaignCopy(campaignId);
+ const campaignId = tarventCommon.requireText({ value: context.propsValue.campaignId, label: 'Campaign' });
+ const sendUtc = new Date().toISOString();
+ await tarventClient.booleanMutation({
+ auth: context.auth.props,
+ operation: 'SendCampaignCopy',
+ field: 'sendCampaignCopy',
+ argDefs: '$id: String!, $sendsUtc: [DateTime!]!',
+ args: 'id: $id, sendsUtc: $sendsUtc',
+ variables: { id: campaignId, sendsUtc: [sendUtc] },
+ });
+ return { success: true, campaignId, sendUtc };
},
});
diff --git a/packages/pieces/community/tarvent/src/lib/actions/update-contact-group.ts b/packages/pieces/community/tarvent/src/lib/actions/update-contact-group.ts
index df4c2cd735b..a6aba987c41 100644
--- a/packages/pieces/community/tarvent/src/lib/actions/update-contact-group.ts
+++ b/packages/pieces/community/tarvent/src/lib/actions/update-contact-group.ts
@@ -1,6 +1,8 @@
import { createAction, Property } from '@activepieces/pieces-framework';
import { tarventAuth } from '../auth';
-import { makeClient, tarventCommon } from '../common';
+import { tarventCommon } from '../common';
+import { tarventOperations } from '../common/operations';
+import { tarventOutputSchemas } from '../output-schemas';
export const updateContactGroup = createAction({
auth: tarventAuth,
@@ -8,11 +10,16 @@ export const updateContactGroup = createAction({
classification: 'WRITE',
displayName: 'Add/Remove Contact From Audience Group',
description: 'Adds or removes a contact from an audience group.',
- audience: 'both',
- aiMetadata: { description: 'Adds or removes a Tarvent contact from a specific audience group, with the direction (add vs. remove) chosen by the action input. Use to manage group membership for segmentation. Idempotent: re-running with the same group and direction leaves membership unchanged.', idempotent: true },
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Adds one Tarvent contact to, or removes it from, one audience group (by audience ID, group ID and contact ID). Use to manage group membership for segmentation. Returns the contact ID, group ID and action. Not marked idempotent: Tarvent may reject adding a contact that is already in the group.',
+ idempotent: false,
+ },
+ outputSchema: tarventOutputSchemas.contactGroup,
props: {
- audienceId: tarventCommon.audienceId(true, ''),
- groupId: tarventCommon.audienceGroupId(true, ''),
+ audienceId: tarventCommon.audienceId(true, 'Audience the contact and group belong to.'),
+ groupId: tarventCommon.audienceGroupId(true, 'Group to add the contact to or remove it from.'),
contactId: tarventCommon.contactId,
action: Property.StaticDropdown({
displayName: 'Add or remove',
@@ -20,23 +27,13 @@ export const updateContactGroup = createAction({
required: true,
options: {
options: [
- {
- label: 'Add',
-
- value: 'Add',
- },
- {
- label: 'Remove',
- value: 'Remove',
- },
+ { label: 'Add', value: 'Add' },
+ { label: 'Remove', value: 'Remove' },
],
},
}),
},
async run(context) {
- const { audienceId, groupId, contactId, action } = context.propsValue;
-
- const client = makeClient(context.auth);
- return await client.addRemoveContactGroup(action, contactId, audienceId, groupId);
+ return tarventOperations.setGroupMembership({ auth: context.auth.props, audienceId: context.propsValue.audienceId, groupId: context.propsValue.groupId, contactId: context.propsValue.contactId, add: context.propsValue.action === 'Add' });
},
});
diff --git a/packages/pieces/community/tarvent/src/lib/actions/update-contact-journey.ts b/packages/pieces/community/tarvent/src/lib/actions/update-contact-journey.ts
index 10fee91b020..43905ac47e7 100644
--- a/packages/pieces/community/tarvent/src/lib/actions/update-contact-journey.ts
+++ b/packages/pieces/community/tarvent/src/lib/actions/update-contact-journey.ts
@@ -1,6 +1,8 @@
import { createAction, Property } from '@activepieces/pieces-framework';
import { tarventAuth } from '../auth';
-import { makeClient, tarventCommon } from '../common';
+import { tarventCommon } from '../common';
+import { tarventOperations } from '../common/operations';
+import { tarventOutputSchemas } from '../output-schemas';
export const updateContactJourney = createAction({
auth: tarventAuth,
@@ -8,34 +10,29 @@ export const updateContactJourney = createAction({
classification: 'WRITE',
displayName: 'Add/Remove A Contact From A Journey',
description: 'Adds or removes the contact from a journey.',
- audience: 'both',
- aiMetadata: { description: 'Enrolls a Tarvent contact into an automation journey or removes them from it, with the direction (add vs. remove) chosen by the action input. Use to start or stop a contact in an automated flow. Not idempotent on add: re-adding can re-enter the contact and re-run journey steps.', idempotent: false },
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Enters one Tarvent contact into an automation journey, or removes it, by contact ID and journey ID. Entering can start the journey\'s emails for that contact. Returns the contact ID, journey ID and action. Not idempotent on add: re-entering can re-run journey steps, depending on the journey\'s re-entry setting.',
+ idempotent: false,
+ },
+ outputSchema: tarventOutputSchemas.contactJourney,
props: {
contactId: tarventCommon.contactId,
- journeyId: tarventCommon.journeyId(true, 'Select which journey to start or stop.'),
+ journeyId: tarventCommon.journeyId(true, 'Journey to add the contact to or remove it from.'),
action: Property.StaticDropdown({
displayName: 'Add or remove',
description: 'Select whether to add or remove the contact from the journey.',
required: true,
options: {
options: [
- {
- label: 'Add',
-
- value: 'Add',
- },
- {
- label: 'Remove',
- value: 'Remove',
- },
+ { label: 'Add', value: 'Add' },
+ { label: 'Remove', value: 'Remove' },
],
},
}),
},
async run(context) {
- const { contactId, journeyId, action } = context.propsValue;
-
- const client = makeClient(context.auth);
- return await client.addRemoveJourneyContact(action, contactId, journeyId);
+ return tarventOperations.setContactJourney({ auth: context.auth.props, contactId: context.propsValue.contactId, journeyId: context.propsValue.journeyId, add: context.propsValue.action === 'Add' });
},
});
diff --git a/packages/pieces/community/tarvent/src/lib/actions/update-contact-status.ts b/packages/pieces/community/tarvent/src/lib/actions/update-contact-status.ts
index e7f36cc705b..b9b4530e9f5 100644
--- a/packages/pieces/community/tarvent/src/lib/actions/update-contact-status.ts
+++ b/packages/pieces/community/tarvent/src/lib/actions/update-contact-status.ts
@@ -1,16 +1,22 @@
import { createAction, Property } from '@activepieces/pieces-framework';
import { tarventAuth } from '../auth';
-import { makeClient, tarventCommon } from '../common';
-import { ContactStatus } from '../common/types';
+import { tarventCommon } from '../common';
+import { tarventClient } from '../common/client';
+import { tarventOutputSchemas } from '../output-schemas';
export const updateContactStatus = createAction({
auth: tarventAuth,
name: 'tarvent_update_contact_status',
- classification: 'DESTRUCTIVE',
+ classification: 'WRITE',
displayName: 'Subscribe/Unsubscribe Contact From Audience',
- description: 'Subscribes or unsubscribe a contact in an audience.',
+ description: 'Subscribes or unsubscribes a contact in an audience.',
audience: 'both',
- aiMetadata: { description: 'Sets a Tarvent contact\'s subscription status to subscribed (active) or unsubscribed (opt-out), chosen by the action input. Use to manage consent or suppression for a contact. Idempotent: it sets an absolute status, so repeating with the same value yields the same state.', idempotent: true },
+ aiMetadata: {
+ description:
+ 'Sets one Tarvent contact\'s subscription status to subscribed (ACTIVE) or unsubscribed (OPT_OUT) by contact ID. Unsubscribing stops campaign email to the contact but keeps the record and can be reversed. Use for consent changes; to block an address account-wide use Add Contact To Suppression List. Idempotent: it sets an absolute status.',
+ idempotent: true,
+ },
+ outputSchema: tarventOutputSchemas.contactStatus,
props: {
contactId: tarventCommon.contactId,
action: Property.StaticDropdown({
@@ -19,23 +25,26 @@ export const updateContactStatus = createAction({
required: true,
options: {
options: [
- {
- label: 'Subscribe',
-
- value: 'ACTIVE',
- },
- {
- label: 'Unsubscribe',
- value: 'OPT_OUT',
- },
+ { label: 'Subscribe', value: 'ACTIVE' },
+ { label: 'Unsubscribe', value: 'OPT_OUT' },
],
},
}),
},
async run(context) {
- const { contactId, action } = context.propsValue;
-
- const client = makeClient(context.auth);
- return await client.updateContactStatus(contactId, action as ContactStatus);
+ const id = tarventCommon.requireText({ value: context.propsValue.contactId, label: 'Contact ID' });
+ const status = context.propsValue.action;
+ if (status !== 'ACTIVE' && status !== 'OPT_OUT') {
+ throw new Error('Status must be ACTIVE (subscribe) or OPT_OUT (unsubscribe).');
+ }
+ await tarventClient.booleanMutation({
+ auth: context.auth.props,
+ operation: 'UpdateContactStatus',
+ field: 'updateContactStatus',
+ argDefs: '$input: UpdateContactStatusInput!',
+ args: 'input: $input',
+ variables: { input: { id, status } },
+ });
+ return { success: true, contactId: id, status };
},
});
diff --git a/packages/pieces/community/tarvent/src/lib/actions/update-contact-tag.ts b/packages/pieces/community/tarvent/src/lib/actions/update-contact-tag.ts
index 7890e1ee8e8..fc74b295183 100644
--- a/packages/pieces/community/tarvent/src/lib/actions/update-contact-tag.ts
+++ b/packages/pieces/community/tarvent/src/lib/actions/update-contact-tag.ts
@@ -1,17 +1,24 @@
-import { tarventAuth } from '../auth';
import { createAction, Property } from '@activepieces/pieces-framework';
-import { makeClient, tarventCommon } from '../common';
+import { tarventAuth } from '../auth';
+import { tarventCommon } from '../common';
+import { tarventOperations } from '../common/operations';
+import { tarventOutputSchemas } from '../output-schemas';
export const updateContactTags = createAction({
auth: tarventAuth,
name: 'tarvent_update_contact_tag',
classification: 'WRITE',
displayName: 'Add/Remove Contact Tag',
- description: 'Adds or removes a tag from contact.',
- audience: 'both',
- aiMetadata: { description: 'Adds or removes one or more tags on a Tarvent contact, with the direction (add vs. remove) chosen by the action input. Use to label or unlabel a contact for segmentation. Idempotent: re-running with the same tags and direction leaves the contact in the same tagged state.', idempotent: true },
+ description: 'Adds or removes tags on a contact.',
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Adds tags to, or removes tags from, one Tarvent contact (by audience ID and contact ID). Tags are free text; up to 100 per call. Use to label or unlabel a contact for segmentation. Returns the contact ID, the action and the tags sent. Idempotent: tags behave as a set, so repeating the same call leaves the same tags.',
+ idempotent: true,
+ },
+ outputSchema: tarventOutputSchemas.contactTags,
props: {
- audienceId: tarventCommon.audienceId(true, 'If specified, the trigger will only fire if contact is in the selected audience.'),
+ audienceId: tarventCommon.audienceId(true, 'Audience the contact belongs to.'),
contactId: tarventCommon.contactId,
action: Property.StaticDropdown({
displayName: 'Tag action',
@@ -20,24 +27,14 @@ export const updateContactTags = createAction({
defaultValue: 'Add',
options: {
options: [
- {
- label: 'Add',
-
- value: 'Add',
- },
- {
- label: 'Remove',
- value: 'remove',
- },
+ { label: 'Add', value: 'Add' },
+ { label: 'Remove', value: 'Remove' },
],
},
}),
- tagIds: tarventCommon.tagIds(true, `Enter which tags you would like to add or remove.`),
+ tagIds: tarventCommon.tagIds(true, 'Tags to add or remove.'),
},
async run(context) {
- const { audienceId, contactId, action, tagIds } = context.propsValue;
-
- const client = makeClient(context.auth);
- return await client.updateContactTags(audienceId, contactId, action, tagIds);
+ return tarventOperations.setContactTags({ auth: context.auth.props, audienceId: context.propsValue.audienceId, contactId: context.propsValue.contactId, tags: context.propsValue.tagIds, remove: String(context.propsValue.action).toLowerCase() === 'remove' });
},
});
diff --git a/packages/pieces/community/tarvent/src/lib/actions/update-contact.ts b/packages/pieces/community/tarvent/src/lib/actions/update-contact.ts
new file mode 100644
index 00000000000..4e4d9ab35a3
--- /dev/null
+++ b/packages/pieces/community/tarvent/src/lib/actions/update-contact.ts
@@ -0,0 +1,71 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { tarventAuth } from '../auth';
+import { tarventCommon } from '../common';
+import { tarventClient } from '../common/client';
+import { tarventOutputSchemas } from '../output-schemas';
+
+const TEXT_FIELDS: { key: string; label: string; max: number }[] = [
+ { key: 'firstName', label: 'First name', max: 100 },
+ { key: 'lastName', label: 'Last name', max: 100 },
+ { key: 'streetAddress', label: 'Street address', max: 100 },
+ { key: 'streetAddress2', label: 'Street address 2', max: 50 },
+ { key: 'addressLocality', label: 'City (Locality)', max: 100 },
+ { key: 'addressRegion', label: 'State (Region)', max: 100 },
+ { key: 'postalCode', label: 'Zip code (Postal code)', max: 15 },
+ { key: 'addressCountry', label: 'Country', max: 100 },
+ { key: 'language', label: 'Language', max: 20 },
+ { key: 'timeZone', label: 'Time zone', max: 100 },
+];
+
+export const updateContact = createAction({
+ auth: tarventAuth,
+ name: 'tarvent_update_contact',
+ classification: 'WRITE',
+ displayName: 'Update Contact',
+ description: 'Updates fields of an existing contact by its ID. Fields left empty are not changed (Tarvent does not clear fields through the API).',
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Partially updates an existing Tarvent contact identified by audience ID and contact ID: only the fields you pass change; Tarvent cannot blank a field through this API, so empty values are ignored. Can change the contact\'s email address. Use this when you already have the contact ID; to create a contact or upsert by email use Create/Update Contact, and use the tag, group and status actions for those. Fails if the contact does not exist. Returns the updated contact. Idempotent: the same input sets the same values.',
+ idempotent: true,
+ },
+ outputSchema: tarventOutputSchemas.contact,
+ props: {
+ audienceId: tarventCommon.audienceId(true, 'Audience the contact belongs to.'),
+ contactId: tarventCommon.contactId,
+ email: Property.ShortText({ displayName: 'New email', description: 'Change the contact\'s email address.', required: false }),
+ firstName: Property.ShortText({ displayName: 'First name', required: false }),
+ lastName: Property.ShortText({ displayName: 'Last name', required: false }),
+ streetAddress: Property.ShortText({ displayName: 'Street address', required: false }),
+ streetAddress2: Property.ShortText({ displayName: 'Street address 2', required: false }),
+ addressLocality: Property.ShortText({ displayName: 'City (Locality)', required: false }),
+ addressRegion: Property.ShortText({ displayName: 'State (Region)', required: false }),
+ postalCode: Property.ShortText({ displayName: 'Zip code (Postal code)', required: false }),
+ addressCountry: Property.ShortText({ displayName: 'Country', required: false }),
+ language: Property.ShortText({ displayName: 'Language', description: 'A culture code such as en or en-US, or Auto.', required: false }),
+ timeZone: Property.ShortText({ displayName: 'Time zone', description: 'An IANA time zone such as America/Denver, or Auto.', required: false }),
+ },
+ async run(context) {
+ const p = context.propsValue;
+ const audienceId = tarventCommon.requireText({ value: p.audienceId, label: 'Audience' });
+ const id = tarventCommon.requireText({ value: p.contactId, label: 'Contact ID' });
+ const values: Record<string, unknown> = p;
+ const set = Object.fromEntries(
+ TEXT_FIELDS.flatMap((f) => {
+ const value = tarventCommon.trimmed(values[f.key]);
+ if (value === undefined) return [];
+ tarventCommon.checkLength({ value, label: f.label, max: f.max });
+ return [[f.key, value]];
+ }),
+ );
+ const email = tarventCommon.trimmed(p.email);
+ tarventCommon.checkLength({ value: email, label: 'New email', max: 320 });
+ if (Object.keys(set).length === 0 && email === undefined) {
+ throw new Error('Nothing to update. Set at least one field.');
+ }
+ return tarventClient.updateContact({
+ auth: context.auth.props,
+ input: { id, audienceId, ...set, ...(email ? { email } : {}) },
+ });
+ },
+});
diff --git a/packages/pieces/community/tarvent/src/lib/actions/update-journey-status.ts b/packages/pieces/community/tarvent/src/lib/actions/update-journey-status.ts
index 453cf3ae4d5..769fb5f0270 100644
--- a/packages/pieces/community/tarvent/src/lib/actions/update-journey-status.ts
+++ b/packages/pieces/community/tarvent/src/lib/actions/update-journey-status.ts
@@ -1,6 +1,8 @@
import { createAction, Property } from '@activepieces/pieces-framework';
import { tarventAuth } from '../auth';
-import { makeClient, tarventCommon } from '../common';
+import { tarventCommon } from '../common';
+import { tarventOperations } from '../common/operations';
+import { tarventOutputSchemas } from '../output-schemas';
export const updateJourneyStatus = createAction({
auth: tarventAuth,
@@ -8,33 +10,28 @@ export const updateJourneyStatus = createAction({
classification: 'WRITE',
displayName: 'Start/Stop Journey',
description: 'Starts or stops a journey.',
- audience: 'both',
- aiMetadata: { description: 'Starts or stops a Tarvent automation journey, with the direction chosen by the action input. Use to activate or pause an entire journey (not an individual contact). Idempotent: it sets the journey to a target run state, so repeating with the same value has no further effect.', idempotent: true },
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Starts or stops a whole Tarvent automation journey by journey ID (not one contact; use Add/Remove A Contact From A Journey for that). Starting a journey can begin sending its emails to every contact it targets. Returns the journey ID and action. Not marked idempotent: Tarvent may reject starting a journey that is already running.',
+ idempotent: false,
+ },
+ outputSchema: tarventOutputSchemas.journeyStatus,
props: {
- journeyId: tarventCommon.journeyId(true, 'Select which journey to start or stop'),
+ journeyId: tarventCommon.journeyId(true, 'Journey to start or stop.'),
action: Property.StaticDropdown({
displayName: 'Action',
description: 'Select whether to start or stop the journey.',
required: true,
options: {
options: [
- {
- label: 'Start',
-
- value: 'Start',
- },
- {
- label: 'Stop',
- value: 'Stop',
- },
+ { label: 'Start', value: 'Start' },
+ { label: 'Stop', value: 'Stop' },
],
},
}),
},
async run(context) {
- const { journeyId, action } = context.propsValue;
-
- const client = makeClient(context.auth);
- return await client.updateJourneyStatus(action, journeyId);
+ return tarventOperations.setJourneyStatus({ auth: context.auth.props, journeyId: context.propsValue.journeyId, start: context.propsValue.action === 'Start' });
},
});
diff --git a/packages/pieces/community/tarvent/src/lib/auth.ts b/packages/pieces/community/tarvent/src/lib/auth.ts
index fb68334467a..af251105ae4 100644
--- a/packages/pieces/community/tarvent/src/lib/auth.ts
+++ b/packages/pieces/community/tarvent/src/lib/auth.ts
@@ -1,14 +1,15 @@
import { PieceAuth, Property } from '@activepieces/pieces-framework';
-import { AppConnectionType } from '@activepieces/pieces-framework';
-import { makeClient } from './common';
+import { TarventApiError, tarventTransport } from './common/transport';
const authGuide = `
To obtain your Tarvent Account ID and API Key, follow these steps:
1. Log in to your Tarvent account.
2. Go to **Account->API Keys** section.
-3. **Create an API key** and copy it. Make sure to give it the correct permissions.
-4. The **Account ID** is available to copy at the top right
+3. **Create an API key** and copy it. Give it permission for everything your flows use (contacts, audiences, campaigns, journeys, webhooks, transactions). A key limited to some areas (for example transactional email only) still connects; actions outside its permissions fail with a permission error.
+4. The **Account ID** is available to copy at the top right.
+
+Note: the Transactional Email API (Send A Transactional Email) is a paid Tarvent add-on that uses email API credits.
`;
export const tarventAuth = PieceAuth.CustomAuth({
@@ -19,23 +20,28 @@ export const tarventAuth = PieceAuth.CustomAuth({
displayName: 'Account ID',
required: true,
}),
- apiKey: Property.ShortText({
+ apiKey: PieceAuth.SecretText({
displayName: 'API Key',
required: true,
}),
},
validate: async ({ auth }) => {
try {
- const client = makeClient({
- props:auth,
- type: AppConnectionType.CUSTOM_AUTH,
+ await tarventTransport.graphql({
+ auth,
+ query: 'query ValidateConnection { audiences(first: 1) { nodes { id } } }',
});
- await client.authenticate();
return { valid: true };
} catch (error) {
+ if (error instanceof TarventApiError && error.isUnauthorized) {
+ return { valid: false, error: tarventTransport.invalidCredentialsMessage };
+ }
+ if (error instanceof TarventApiError && error.code === tarventTransport.permissionCode) {
+ return { valid: true };
+ }
return {
valid: false,
- error: 'Invalid API credentials',
+ error: `Could not verify the Tarvent connection: ${error instanceof Error ? error.message : 'unknown error'}`,
};
}
},
diff --git a/packages/pieces/community/tarvent/src/lib/common/client.ts b/packages/pieces/community/tarvent/src/lib/common/client.ts
index 8ade7b253bd..416f9c3ed0f 100644
--- a/packages/pieces/community/tarvent/src/lib/common/client.ts
+++ b/packages/pieces/community/tarvent/src/lib/common/client.ts
@@ -1,1099 +1,299 @@
-import {
- httpClient,
- HttpMessageBody,
- HttpMethod,
- HttpRequest
-} from '@activepieces/pieces-common';
-import { ContactStatus, CreateAudienceGroupResponse, CreateContactNoteResponse, CreateContactResponse, CreateGroupContactResponse, CreateSuppressionFilterResponse, CreateWebhookResponse, DeleteGroupContactResponse, ListAudienceDataFieldsResponse, ListAudienceFormsResponse, ListAudienceGroupAdvResponse, ListAudienceGroupResponse, ListAudiencesAdvResponse, ListAudiencesResponse, ListCampaignLinksResponse, ListCampaignsAdvResponse, ListCampaignsResponse, ListContactResponse, ListCustomEventsAdvResponse, ListCustomEventsResponse, ListJourneysAdvResponse, ListJourneysResponse, ListLandingPagesResponse, ListSurveysResponse, ListTagsResponse, ListTemplatesResponse, ListTxGroupNamesResponse } from './types';
-
-export class TarventClient {
- constructor(private accountId: string, private apiKey: string) { }
-
- async makeRequest<T extends HttpMessageBody>(
- body: unknown | undefined = undefined,
- ): Promise<T> {
- const request: HttpRequest = {
- method: HttpMethod.POST,
- url: 'https://api.tarvent.com/graphql',
- headers: {
- 'x-api-key': this.apiKey,
- 'account': this.accountId
- },
- body: body,
- };
- const res = await httpClient.sendRequest<T>(request);
- return res.body;
- }
-
- async authenticate() {
- // Call to get account audiences to check if authentication is valid
- const body: unknown = {
- "query": "query GetAudiences{\r\naudiences{\r\nnodes{\r\nid\r\nname}\r\n}\r\n}"
- };
- return await this.makeRequest(body);
- }
- // #region Webhook create and delete
- async createWebhook(context: any, webhookType: string): Promise<CreateWebhookResponse> {
- const body: unknown = {
- "query": "mutation CreateWebhook($name: String!, $description: String!, $events: [WebhookEventInput!]!, $callBackUrl: String!, $dataSettings: WebhookDataSetting, $filter: ConditionGroupInput) { createWebhook( name: $name description: $description events: $events callBackUrl: $callBackUrl dataSettings: $dataSettings filter: $filter ) { id } }",
- "variables": {
- "name": this.getWebhookName(),
- "description": "",
- "callBackUrl": context.webhookUrl,
- "events": this.getWebhookEvent(webhookType, context.propsValue),
- "filter": this.generateWebhookInput(webhookType, context.propsValue),
- "dataSettings": context.propsValue.include,
- "integrationType": "ZAPIER"
- }
- }
- return await this.makeRequest<CreateWebhookResponse>(body);
- }
-
- async deleteWebhook(webhookId: string): Promise<CreateWebhookResponse> {
- const body: unknown = {
- "query": "mutation DeleteWebhook($id: String!) { deleteWebhook(id: $id) }",
- "variables": {
- "id": webhookId
- }
- }
- return await this.makeRequest<CreateWebhookResponse>(body);
- }
- //#endregion
-
- // #region Searches and entity lists
- async listAudiences(): Promise<ListAudiencesResponse> {
- const body: unknown = {
- "query": "query GetAudience( $first: Int $after: String $last: Int $before: String $order: [AudienceInfoSortInput!] $where: AudienceInfoFilterInput ) { audiences( first: $first after: $after last: $last before: $before order: $order where: $where ) { nodes { id name } } }",
- "variables": {
- "first": 100,
- "after": null,
- "last": null,
- "before": null,
- "order": null,
- "where": null
- }
- }
- return await this.makeRequest<ListAudiencesResponse>(body);
- }
-
- async listAudiencesAdv(name = '', tags = '', itemCount = 100): Promise<ListAudiencesAdvResponse> {
- const filters = [];
- if (name && name !== '') filters.push({ name: { contains: name } });
- if (tags && tags !== '') filters.push({ tags: { some: { in: tags.split(',').map((t) => t.trim()) } } });
-
- const body: unknown = {
- "query": "query GetAudience( $first: Int $after: String $last: Int $before: String $order: [AudienceInfoSortInput!] $where: AudienceInfoFilterInput ) { audiences( first: $first after: $after last: $last before: $before order: $order where: $where ) { nodes { id name companyName streetAddress streetAddress2 addressLocality addressRegion postalCode addressCountry phone website totalContacts totalActiveContacts totalUnconfirmedContacts totalUndeliverableContacts totalUnsubscribedContacts totalComplaintContacts totalSuppressedContacts tags customKeyDataField { id labelText } createdUtc lastModifiedUtc } } }",
- "variables": {
- "first": itemCount,
- "after": null,
- "last": null,
- "before": null,
- "order": null,
- "where": filters.length !== 0 ? { and: filters } : null
- }
- }
- return await this.makeRequest<ListAudiencesAdvResponse>(body);
- }
-
- async listAudienceGroups(audienceId: string): Promise<ListAudienceGroupResponse> {
- const body: unknown = {
- "query": "query GetAudienceGroups($first: Int, $after: String, $last: Int, $before: String, $audienceId: String!, $order: [AudienceGroupInfoSortInput!], $where: AudienceGroupInfoFilterInput) { audienceGroups( first: $first after: $after last: $last before: $before audienceId: $audienceId order: $order where: $where ) { totalCount nodes { id name } } }",
- "variables": {
- "first": 50,
- "audienceId": audienceId,
- "order": [
- {
- "name": "ASC"
- }
- ],
- "where": {
- "isDynamic": {
- "eq": false
- }
- }
- }
- };
- return await this.makeRequest<ListAudienceGroupResponse>(body);
- }
-
- async listAudienceGroupsAdv(audienceId: string | undefined, name = ''): Promise<ListAudienceGroupAdvResponse> {
- const filters: any = [{ isDynamic: { eq: false } }];
- if (name && name !== '') filters.push({ name: { contains: name } });
- const body: unknown = {
- "query": "query GetAudienceGroups($first: Int, $after: String, $last: Int, $before: String, $audienceId: String!, $order: [AudienceGroupInfoSortInput!], $where: AudienceGroupInfoFilterInput) { audienceGroups( first: $first after: $after last: $last before: $before audienceId: $audienceId order: $order where: $where ) { totalCount nodes { id name description isPublic } } }",
- "variables": {
- "first": 100,
- "audienceId": audienceId,
- "order": [
- {
- "name": "ASC"
- }
- ],
- "where": { and: filters }
- }
- };
- return await this.makeRequest<ListAudienceGroupAdvResponse>(body);
- }
-
- async listAudienceDataFields(audienceId: unknown): Promise<ListAudienceDataFieldsResponse> {
- const body: unknown = {
- query: "query GetDataFields($first: Int, $after: String, $last: Int, $before: String, $audienceId: String!, $order: [DataFieldSortInput!], $where: DataFieldFilterInput) { audienceDataFields(first: $first, after: $after, last: $last, before: $before, audienceId: $audienceId, order: $order, where: $where) { nodes { id dataType labelText required isSystem defaultValue mergeTag isPrimaryKey isGdprField category } } }",
- variables: {
- first: 200,
- after: null,
- last: null,
- before: null,
- audienceId,
- order: null,
- where: null
- }
- };
- return await this.makeRequest<ListAudienceDataFieldsResponse>(body);
- }
-
- async listAudienceForms(audienceId: string): Promise<ListAudienceFormsResponse> {
- const body: unknown = {
- query: `query GetForms($first: Int, $after: String, $last: Int, $before: String, $audienceId: String, $order: [FormInfoSortInput!], $where: FormInfoFilterInput) {
- forms(
- first: $first
- after: $after
- last: $last
- before: $before
- audienceId: $audienceId
- order: $order
- where: $where
- ) {
- nodes {
- id
- name
- }
- }
- }`,
- variables: {
- first: 50,
- audienceId,
- order: [{ name: "ASC" }]
- },
- };
- return await this.makeRequest<ListAudienceFormsResponse>(body);
- }
-
- async listTags(): Promise<ListTagsResponse> {
- const body: unknown = {
- "query": "query GetTags($first: Int $after: String $last: Int $before: String $order: [TagSortInput!] $where: TagFilterInput) { tags(first: $first after: $after last: $last before: $before order: $order where: $where) { nodes { name } } }",
- "variables": {
- "first": 50,
- "after": null,
- "order": null,
- "where": null
- }
- };
- return await this.makeRequest<ListTagsResponse>(body);
- }
-
- async listCampaigns(ignoreStatus = false, isEvent = false): Promise<ListCampaignsResponse> {
- const filters = [];
- filters.push({ isArchived: { eq: false } });
- if (!ignoreStatus) {
- filters.push({
- sendStatus: {
- in: isEvent ? ['NOT_SCHEDULED', 'COMPLETED'] : ['NOT_SCHEDULED', 'READY_TO_SEND']
- },
- });
- } else {
- filters.push({
- sendStatus: {
- nin: ['PAUSED', 'PENDING', 'PROCESSING', 'QUEUED', 'SYSTEM_STOPPED'],
- },
- });
- }
- const body: unknown = {
- query: `query GetCampaigns(
- $first: Int
- $after: String
- $last: Int
- $before: String
- $order: [CampaignInfoSortInput!]
- $where: CampaignInfoFilterInput
- )
- {
- campaigns(
- first: $first
- after: $after
- last: $last
- before: $before
- order: $order
- where: $where
- ) {
- totalCount
- nodes {
- id
- name
- }
- }
- }`,
- variables: {
- first: 100,
- after: null,
- order: [
- {
- modifiedUtc: 'DESC',
- },
- ],
- where: {
- and: filters,
- },
- },
- };
- return await this.makeRequest<ListCampaignsResponse>(body);
- }
-
- async listCampaignsAdv(name = '', tags = '', status = ''): Promise<ListCampaignsAdvResponse> {
- const filters = [];
- if (name && name !== '') {
- filters.push({ name: { contains: name } });
- }
- if (tags && tags !== '') {
- filters.push({
- tags: {
- some: { in: tags.split(',').map((t) => t.trim()) },
- },
- });
- }
- if (status && status.length !== 0) {
- const allStatus: string[] = status.split(',').map((s) => s.trim());
- if (status.split(',').some((s) => s === 'PENDING')) {
- allStatus.push('PROCESSING');
- allStatus.push('QUEUED');
- }
- if (status.split(',').some((s) => s === 'STOPPED')) {
- allStatus.push('SYSTEM_STOPPED');
- }
- filters.push({ sendStatus: { in: allStatus } });
- }
- const body: unknown = {
- query: `query GetCampaign( $first: Int $after: String $last: Int $before: String $order: [CampaignInfoSortInput!] $where: CampaignInfoFilterInput ) { campaigns( first: $first after: $after last: $last before: $before order: $order where: $where ) { nodes { id tags name audienceId description mvWinType timeJumper sendStatus scheduledToSendUtc createdUtc modifiedUtc } } }`,
- variables: {
- first: 100,
- after: null,
- order: [
- {
- modifiedUtc: 'DESC',
- },
- ],
- where: filters.length !== 0 ? { and: filters } : null
- },
- };
- return await this.makeRequest<ListCampaignsAdvResponse>(body);
- }
-
- async listCampaignLinks(campaignId: string): Promise<ListCampaignLinksResponse> {
- const body: unknown = {
- query: `query GetCampaignLinks($id: String!) {
- campaignLinks(id: $id) {
- id
- url
- track
- entityName
- entityType
- formType
- }
- }`,
- variables: {
- id: campaignId,
- },
- };
- return await this.makeRequest<ListCampaignLinksResponse>(body);
- }
-
- async listJourneys(): Promise<ListJourneysResponse> {
- const body: unknown = {
- query: `query GetJourneys($first: Int, $after: String, $last: Int, $before: String, $order: [JourneyInfoSortInput!], $where: JourneyInfoFilterInput) {
- journeys(
- first: $first
- after: $after
- last: $last
- before: $before
- order: $order
- where: $where
- ) {
- nodes {
- id
- name
- }
- pageInfo {
- hasNextPage
- endCursor
- }
- }
- }`,
- variables: {
- first: 50,
- after: null,
- last: null,
- before: null,
- order: null,
- where: null,
- },
- };
- return await this.makeRequest<ListJourneysResponse>(body);
- }
-
- async listJourneysAdv(name = '', tags = '', status = ''): Promise<ListJourneysAdvResponse> {
- const filters = [];
- if (name && name !== '') {
- filters.push({ name: { contains: name } });
- }
- if (tags && tags !== '') {
- filters.push({
- tags: {
- some: { in: tags.split(',').map((t) => t.trim()) },
- },
- });
- }
- if (status && status.length !== 0) {
- const allStatus: string[] = status.split(',').map((s) => s.trim());
- filters.push({ status: { in: allStatus } });
- }
- const body: unknown = {
- query: `query GetJourneys($first: Int, $after: String, $last: Int, $before: String, $order: [JourneyInfoSortInput!], $where: JourneyInfoFilterInput) { journeys(first: $first, after: $after, last: $last, before: $before, order: $order, where: $where) { nodes { id tags name audienceId description reEntryType status totalEmailNodes totalNotificationEmailNodes totalSiteNotificationNodes totalSMSNodes createdUtc modifiedUtc } } }`,
- variables: {
- first: 1,
- after: null,
- last: null,
- before: null,
- order: null,
- where: filters.length !== 0 ? { and: filters } : null,
- },
- };
- return await this.makeRequest<ListJourneysAdvResponse>(body);
- }
-
- async listContact(audienceId: string | undefined, email: string): Promise<ListContactResponse> {
- const body: unknown = {
- query: `query GetContact($input: GetContactInput!) { contact(input: $input) { id email firstName lastName groups { id name } tags rating longitude latitude streetAddress streetAddress2 addressLocality addressRegion postalCode addressCountry timeZone language sendFormat status optInUtc confirmedUtc optOutUtc profileFields { id dataField { id labelText } value } modifiedUtc createdUtc } }`,
- variables: {
- input: {
- audienceId: audienceId,
- emailAddress: email.includes('@') ? email : null,
- id: !email.includes('@') ? email : null
- }
- },
- };
- console.log(body);
- return await this.makeRequest<ListContactResponse>(body);
- }
-
- async listLandingPages(): Promise<ListLandingPagesResponse> {
- const body: unknown = {
- query: `query GetLandingPages($first: Int, $after: String, $last: Int, $before: String, $order: [LandingPageInfoSortInput!], $where: LandingPageInfoFilterInput) {
- landingPages(
- first: $first
- after: $after
- last: $last
- before: $before
- order: $order
- where: $where
- ) {
- nodes {
- id
- name
- }
- }
- }`,
- variables: {
- first: 50,
- after: null,
- last: null,
- before: null,
- order: null,
- where: null,
- },
- };
- return await this.makeRequest<ListLandingPagesResponse>(body);
- }
-
- async listSurveys(): Promise<ListSurveysResponse> {
- const body: unknown = {
- query: `query GetSurveys($first: Int, $after: String, $last: Int, $before: String, $order: [SurveyInfoSortInput!], $where: SurveyInfoFilterInput) {
- surveys(
- first: $first
- after: $after
- last: $last
- before: $before
- order: $order
- where: $where
- ) {
- nodes {
- id
- name
- }
- }
- }`,
- variables: {
- first: 50,
- after: null,
- last: null,
- before: null,
- order: null,
- where: null,
- },
- };
- return await this.makeRequest<ListSurveysResponse>(body);
- }
-
- async listTemplates(): Promise<ListTemplatesResponse> {
- const body: unknown = {
- query: `query GetTemplates($first: Int, $after: String, $last: Int, $before: String, $order: [TemplateInformationSortInput!], $where: TemplateInformationFilterInput) {
- templates(
- first: $first
- after: $after
- last: $last
- before: $before
- order: $order
- where: $where
- ) {
- nodes {
- id
- name
- }
- }
- }`,
- variables: {
- first: 50,
- after: null,
- where: null
- },
- };
- return await this.makeRequest<ListTemplatesResponse>(body);
- }
-
- async listTxGroupNames(): Promise<ListTxGroupNamesResponse> {
- const body: unknown = {
- query: `query GetTxGroupNames($where: StringOperationFilterInput) { transactionGroupNames(where: $where) }`,
- variables: {
- where: null
- },
- };
- return await this.makeRequest<ListTxGroupNamesResponse>(body);
- }
-
- async listCustomEvents(): Promise<ListCustomEventsResponse> {
- const body: unknown = {
- query: `query GetCustomEvents($first: Int, $after: String, $last: Int, $before: String, $order: [CustomApiEventSortInput!], $where: CustomApiEventFilterInput) {
- customApiEvents(
- first: $first
- after: $after
- last: $last
- before: $before
- order: $order
- where: $where
- ) {
- nodes {
- id
- key
- name
- }
- }
- }`,
- variables: {
- first: 50,
- after: null,
- last: null,
- before: null,
- order: null,
- where: null,
- },
- };
- return await this.makeRequest<ListCustomEventsResponse>(body);
- }
-
- async listCustomEventsAdv(name = ''): Promise<ListCustomEventsAdvResponse> {
- const filters = [];
- if (name && name !== '') {
- filters.push({ name: { contains: name } });
- }
- const body: unknown = {
- query: `query GetCustomEvents($first: Int, $after: String, $last: Int, $before: String, $order: [CustomApiEventSortInput!], $where: CustomApiEventFilterInput) { customApiEvents(first: $first, after: $after, last: $last, before: $before, order: $order, where: $where) { nodes { id key name createdUtc modifiedUtc } } }`,
- variables: {
- first: 10,
- after: null,
- last: null,
- before: null,
- order: null,
- where: filters.length !== 0 ? { and: filters } : null,
- },
- };
- return await this.makeRequest<ListCustomEventsAdvResponse>(body);
- }
- //#endregion
-
- // #region Creates and updates
- // Create/update contact
- async createContact(audienceId: string | undefined, emailAddress: string, updateExisting: string, groupAction: string | undefined, tagAction: string | undefined, tagIds: string[] | undefined, groupIds: string[] | undefined, firstName: string | undefined, lastName: string | undefined, streetAddress: string | undefined, streetAddress2: string | undefined, addressLocality: string | undefined, addressRegion: string | undefined, postalCode: string | undefined, addressCountry: string | undefined, profileFields: Record<string, string> | undefined): Promise<CreateContactResponse> {
- const profile = [];
- for (const f in profileFields) {
- if (profileFields[f]) {
- profile.push({
- dataFieldId: f,
- value: this.isISODate(profileFields[f].toString()) ? this.formatISODateToYMD(profileFields[f].toString()) : profileFields[f].toString(),
- });
- }
- }
- const body: unknown = {
- query: `mutation CreateContact($input: CreateContactInput!) { createContact(input: $input) { id email firstName lastName tags groups { id name } streetAddress streetAddress2 addressLocality addressRegion postalCode addressCountry profileFields { dataField { id labelText } value } modifiedUtc createdUtc } }`,
- variables: {
- input: {
- email: emailAddress,
- audienceId,
- updateExisting: updateExisting === 'Update',
- audienceGroupManagementType: groupAction === 'Replace'
- ? 'REPLACE_EXISTING'
- : 'ADD_NEW_GROUPS_ONLY',
- tagManagementType: tagAction === 'Replace'
- ? 'REPLACE_EXISTING'
- : 'ADD_NEW_TAGS_ONLY',
- firstName,
- lastName,
- streetAddress,
- streetAddress2,
- addressLocality,
- addressRegion,
- postalCode,
- addressCountry,
- profile,
- tags: tagIds ? tagIds : null,
- groupIds: groupIds ? groupIds : null,
- sendFormat: 'MULTIPART',
- },
- },
- };
- return await this.makeRequest<CreateContactResponse>(body);
- }
-
- // Update contact tags
- async updateContactTags(audienceId: string | undefined, contactId: string, action: string, tagIds: string[] | undefined): Promise<boolean> {
- const body: unknown = {
- query: "mutation UpdateContactTags($input: UpdateContactTagsInput!) { updateContactTags(input: $input) }",
- variables: {
- input: {
- id: contactId,
- audienceId,
- operator: action === 'Add' ? 'ADD' : 'REMOVE',
- tags: tagIds
- }
- }
- };
- return await this.makeRequest<boolean>(body);
- }
-
- // Create audience group
- async createAudienceGroup(audienceId: string | undefined, name: string | undefined, description: string | undefined, isPublic: string): Promise<CreateAudienceGroupResponse> {
- const body: unknown = {
- query: `mutation CreateAudienceGroup($input: CreateGroupInput!) {
- createAudienceGroup(input: $input) {
- id
- name
- description
- isPublic
- isDynamic
- }
- }`,
- variables: {
- input: {
- name,
- description,
- isDynamic: false,
- isPublic: isPublic === "false" ? false : true,
- audienceId,
- criteria: null
- }
- }
- };
- return await this.makeRequest<CreateAudienceGroupResponse>(body);
- }
-
- // Send campaign copy
- async sendCampaignCopy(campaignId: string | undefined): Promise<boolean> {
- const body: unknown = {
- query: `mutation SendCampaignCopy($id: String!, $sendsUtc: [DateTime!]!) { sendCampaignCopy(id: $id, sendsUtc: $sendsUtc) }`,
- variables: {
- id: campaignId,
- sendsUtc: [new Date().toISOString()]
- }
- };
- return await this.makeRequest<boolean>(body);
- }
-
- // Add note to contact
- async createContactNote(contactId: string | undefined, note: string | undefined): Promise<CreateContactNoteResponse> {
- const body: unknown = {
- query: `mutation CreateContactNote($input: CreateContactNoteInput!) { createContactNote(input: $input) { id } }`,
- variables: {
- input: {
- contactId,
- message: note
- }
- }
- };
- return await this.makeRequest<CreateContactNoteResponse>(body);
- }
-
- // Add or remove contact from group
- async addRemoveContactGroup(action: string | undefined, contactId: string | undefined, audienceId: string | undefined, groupId: string | undefined): Promise<CreateGroupContactResponse | DeleteGroupContactResponse> {
- let body: unknown = undefined;
- if (action === 'Add') {
- body = {
- query: `mutation CreateGroupContact($input: CreateGroupContactInput!) { createGroupContact(input: $input) { id } }`,
- variables: {
- input: {
- id: contactId,
- groupId: groupId,
- audienceId: audienceId,
- }
- }
- };
- } else {
- body = {
- query: `mutation DeleteGroupContact($input: DeleteGroupContactInput!) { deleteGroupContact(input: $input) { id } }`,
- variables: {
- input: {
- id: contactId,
- groupId: groupId,
- audienceId: audienceId,
- }
- }
- };
- }
- return await this.makeRequest<CreateGroupContactResponse | DeleteGroupContactResponse>(body);
- }
-
- // Add or remove contact from journey
- async addRemoveJourneyContact(action: string | undefined, contactId: string | undefined, journeyId: string | undefined): Promise<boolean> {
- let body: unknown = undefined;
- if (action === 'Add') {
- body = {
- query: `mutation EnterContactIntoJourney($id: String!, $journeyId: String!) { enterContactIntoJourney(id: $id, journeyId: $journeyId) }`,
- variables: {
- id: contactId,
- journeyId
- }
- };
- } else {
- body = {
- query: `mutation ExitContactFromJourney($id: String!, $journeyId: String!) { exitContactFromJourney(id: $id, journeyId: $journeyId) }`,
- variables: {
- id: contactId,
- journeyId
- }
- };
- }
- return await this.makeRequest<boolean>(body);
- }
-
- // Update contact status
- async updateContactStatus(contactId: string | undefined, status: ContactStatus | undefined): Promise<boolean> {
- const body: unknown = {
- query: `mutation UpdateContactStatus($input: UpdateContactStatusInput!) { updateContactStatus(input: $input) }`,
- variables: {
- input: {
- id: contactId,
- status
- }
- }
- };
- return await this.makeRequest<boolean>(body);
- }
-
- // Generate custom event
- async generateCustomEvent(contactId: string | undefined, customEventId: string | undefined): Promise<boolean> {
- const body: unknown = {
- query: `mutation CreateContactCustomEvent($id: String!, $key: String!) { createContactCustomEvent(id: $id, key: $key) }`,
- variables: {
- id: contactId,
- key: customEventId
- }
- };
- return await this.makeRequest<boolean>(body);
- }
-
- // Update journey status
- async updateJourneyStatus(action: string | undefined, journeyId: string | undefined): Promise<boolean> {
- let body: unknown = undefined;
- if (action === 'Start') {
- body = {
- query: `mutation StartJourney($id: String!) { startJourney(id: $id) }`,
- variables: {
- id: journeyId
- }
- };
- } else {
- body = {
- query: `mutation StopJourney($id: String!) { stopJourney(id: $id) }`,
- variables: {
- id: journeyId
- }
- };
- }
- return await this.makeRequest<boolean>(body);
- }
-
- // Add suppression filter
- async createSuppressionFilter(emailAddress: string, reason: string | undefined): Promise<CreateSuppressionFilterResponse> {
- const body: unknown = {
- query: `mutation CreateSuppressionFilter($input: CreateSuppressionFilterInput!) {
- createAccountSuppressionFilter(input: $input) {
- id
- localPart
- domain
- reason
- }
- }`,
- variables: {
- input: {
- domain: emailAddress.split('@')[1],
- localPart: emailAddress.split('@')[0],
- reason
- }
- }
- };
- return await this.makeRequest<CreateSuppressionFilterResponse>(body);
- }
-
- // Create transaction
- async createTransaction(groupName: string | undefined, fromEmail: string, fromName: string | undefined, toEmail: string, ccEmail: unknown[] | undefined, bccEmail: unknown[] | undefined, subject: string, replyToEmail: string | undefined, replyToName: string | undefined, variables: Record<string, unknown> | undefined, templateId: string | undefined, mimeType: string | undefined, content: string | undefined, ignoreSuppressCheck: string): Promise<CreateSuppressionFilterResponse> {
- const vars: { name: string, value: unknown }[] = [];
- for (const prop in variables) {
- if (prop && prop !== '') {
- vars.push({
- name: prop.replace(/\s/g, '').replace(/[\W_-]+/g, ''),
- value: variables[prop],
- });
- }
- }
+import { TarventApiError, TarventCredentials, tarventTransport } from './transport';
+
+const PAGE_SIZE = 50;
+const DROPDOWN_MAX_PAGES = 20;
+const NOT_FOUND_CODE = '1030';
+
+const CONTACT_FIELDS = 'id email firstName lastName status tags groups { id name } rating latitude longitude streetAddress streetAddress2 addressLocality addressRegion postalCode addressCountry timeZone language sendFormat optInUtc confirmedUtc optOutUtc profileFields { id dataField { id labelText } value } createdUtc modifiedUtc';
+const AUDIENCE_FIELDS = 'id name companyName streetAddress streetAddress2 addressLocality addressRegion postalCode addressCountry phone website totalContacts totalActiveContacts totalUnconfirmedContacts totalUndeliverableContacts totalUnsubscribedContacts totalComplaintContacts totalSuppressedContacts tags customKeyDataField { id labelText } createdUtc lastModifiedUtc';
+const CAMPAIGN_FIELDS = 'id tags name audienceId description mvWinType timeJumper sendStatus scheduledToSendUtc createdUtc modifiedUtc';
+const JOURNEY_FIELDS = 'id tags name audienceId description reEntryType status totalEmailNodes totalNotificationEmailNodes totalSiteNotificationNodes totalSMSNodes createdUtc modifiedUtc';
+const PAGE_INFO = 'pageInfo { hasNextPage endCursor }';
+const CAMPAIGN_STATS_FIELDS = 'campaignId totalSent totalDelivered totalDeliveredPct totalOpens uniqueOpens uniqueOpensPct totalClicks uniqueClicks uniqueClicksPct clickToOpenPct totalReplies uniqueReplies uniqueRepliesPct totalBounce totalBouncePct uniqueHardBounce uniqueHardBouncePct uniqueSoftBounce uniqueSoftBouncePct uniqueOptOut uniqueOptOutPct uniqueSpam uniqueSpamPct uniqueSuppressed engagementScore engagementScoreAvg senderReputation sendDomain';
+const TRANSACTION_FIELDS = 'id requestId status recipient recipientName recipientType from fromName replyTo subject groupName tags error bounceCategory openCount clickCount sendCount complaint unsubscribe contactId sendAtUtc processedUtc createdUtc modifiedUtc';
+
+function isNotFound(error: unknown): boolean {
+ return error instanceof TarventApiError && error.code === NOT_FOUND_CODE;
+}
+async function assertAudienceReadable({ auth, audienceId }: { auth: TarventCredentials; audienceId: string }): Promise<void> {
+ await listPage<{ id: string }>({
+ auth,
+ operation: 'CheckAudience',
+ field: 'contacts',
+ selection: 'id',
+ argDefs: ', $input: GetAllContactsInput!',
+ args: ', input: $input',
+ variables: { input: { audienceId } },
+ first: 1,
+ });
+}
- const recips = [];
- recips.push({
- emailAddress: toEmail,
- type: 'TO',
- variables: vars,
- });
- ccEmail?.forEach((r: any) => {
- recips.push({
- emailAddress: r.email,
- type: 'CC',
- variables: vars,
- });
- });
- bccEmail?.forEach((r: any) => {
- recips.push({
- emailAddress: r.email,
- type: 'BCC',
- variables: vars,
- });
- });
- const body: unknown = {
- query: `mutation createTransaction($input: CreateTransactionInput!) { createTransaction(input: $input) { emailAddress errorCode errorMsg requestId transactionId } }`,
- variables: {
- input: {
- content: {
- templateId: templateId ? templateId : null,
- contentBodies: !templateId
- ? [
- {
- bodyContent: content?.replace(/\[\[/g, '{{').replace(/\]\]/g, '}}'),
- mimeType: mimeType,
- },
- ]
- : null,
- },
- groupName: groupName,
- header: {
- from: {
- emailAddress: fromEmail,
- name: fromName,
- },
- replyTo: {
- emailAddress: replyToEmail ? replyToEmail : '',
- name: replyToName ? replyToName : '',
- },
- subject,
- },
- recipients: recips,
- settings: {
- ignoreSuppressCheck: ignoreSuppressCheck === 'true' ? true : false,
- },
- },
- }
- };
- return await this.makeRequest<CreateSuppressionFilterResponse>(body);
- }
- //#endregion
+function isContactNotFound(error: unknown): boolean {
+ return isNotFound(error) && error instanceof Error && /contact/i.test(error.message) && !/audience/i.test(error.message);
+}
- // #region Utilities
- getWebhookName(): string {
- return `ActivePieces-${Date.now()}`;
- }
+async function listPage<T>({
+ auth,
+ operation,
+ field,
+ selection,
+ argDefs = '',
+ args = '',
+ variables = {},
+ first = PAGE_SIZE,
+ after,
+ withTotalCount = false,
+}: {
+ auth: TarventCredentials;
+ operation: string;
+ field: string;
+ selection: string;
+ argDefs?: string;
+ args?: string;
+ variables?: Record<string, unknown>;
+ first?: number;
+ after?: string;
+ withTotalCount?: boolean;
+}): Promise<TarventPage<T>> {
+ const query = `query ${operation}($first: Int, $after: String${argDefs}) { ${field}(first: $first, after: $after${args}) { ${withTotalCount ? 'totalCount ' : ''}nodes { ${selection} } ${PAGE_INFO} } }`;
+ const connection = await tarventTransport.field<TarventConnection<T>>({
+ auth,
+ query,
+ variables: { ...variables, first, after: after ?? null },
+ name: field,
+ });
+ const items = connection.nodes ?? [];
+ const hasMore = connection.pageInfo?.hasNextPage === true;
+ return {
+ items,
+ count: items.length,
+ totalCount: typeof connection.totalCount === 'number' ? connection.totalCount : null,
+ hasMore,
+ nextCursor: hasMore ? connection.pageInfo?.endCursor ?? null : null,
+ };
+}
- getWebhookEvent(type: string, parameters: any): Array<{ entityType: unknown; eventType: string }> {
- switch (type) {
- case 'contactAdded':
- return [{ entityType: null, eventType: 'CONTACT_ADDED' }];
- case 'campaignSendFinished':
- return [{ entityType: null, eventType: 'CAMPAIGN_SENT' }];
- case 'campaignSendStarted':
- return [{ entityType: null, eventType: 'STARTED_CAMPAIGN_SEND' }];
- case 'contactBounced': {
- let entityType = null;
- if (parameters.entity !== 'BOTH') {
- entityType = parameters.entity;
- }
- if (parameters.type === 'Any') {
- return [
- { entityType, eventType: 'BLOCK' },
- { entityType, eventType: 'BLOCK_CONTENT' },
- { entityType, eventType: 'BLOCK_SENDER' },
- { entityType, eventType: 'HARD' },
- { entityType, eventType: 'SOFT' },
- { entityType, eventType: 'SOFT_DNS' },
- { entityType, eventType: 'SOFT_IP' },
- { entityType, eventType: 'SOFT_SENDER_AUTH' },
- ];
- } else {
- return [{ entityType, eventType: parameters.type }];
- }
- }
- case 'contactClicked': {
- let entityType = null;
- if (parameters.entity !== 'BOTH') {
- entityType = parameters.entity;
- }
- return [{ entityType, eventType: 'CLICK' }];
- }
- case 'contactReplied': {
- let entityType = null;
- if (parameters.entity !== 'BOTH') {
- entityType = parameters.entity;
- }
- return [{ entityType, eventType: 'REPLIED' }];
- }
- case 'contactGroupUpdated':
- return [{
- entityType: null,
- eventType:
- parameters.action === 'Add' ? 'GROUP_ADDED' : 'GROUP_REMOVED',
- }];
- case 'contactNoteAdded':
- return [{ entityType: null, eventType: 'NOTE_ADDED' }];
- case 'contactOpened': {
- let entityType = null;
- if (parameters.entity !== 'BOTH') {
- entityType = parameters.entity;
- }
- return [{ entityType, eventType: 'OPEN' }];
- }
- case 'contactStatusUpdated': {
- if (parameters.status === 'Any') {
- return [
- { entityType: null, eventType: 'SUBSCRIBED' },
- { entityType: null, eventType: 'UNSUBSCRIBED' },
- ];
- } else if (parameters.status === 'ACTIVE') {
- return [
- { entityType: null, eventType: 'SUBSCRIBED' }
- ];
- } else {
- return [
- { entityType: null, eventType: 'UNSUBSCRIBED' },
- ];
- }
- }
- case 'contactTagUpdated': {
- return [{
- entityType: null,
- eventType: parameters.action === 'Add' ? 'TAG_ADDED' : 'TAG_REMOVED',
- }];
- }
- case 'contactUnsubscribed':
- return [{ entityType: null, eventType: 'UNSUBSCRIBED' }];
- case 'contactUpdated':
- return [{ entityType: null, eventType: 'FIELD_UPDATED' }];
- case 'formSubmitted':
- return [
- { entityType: 'FORM', eventType: 'SUBMITTED_COMPLETE_FORM' },
- { entityType: 'FORM', eventType: 'SUBMITTED_PARTIAL_FORM' },
- ];
- case 'landingPageCtaPerformed':
- return [{ entityType: 'PAGE', eventType: 'CTA' }];
- case 'surveySubmitted':
- return [
- { entityType: 'SURVEY', eventType: 'SUBMITTED_COMPLETE_FORM' },
- { entityType: 'SURVEY', eventType: 'SUBMITTED_PARTIAL_FORM' },
- ];
- case 'transactionCreated':
- return [{ entityType: null, eventType: 'CREATED' }];
- case 'transactionSent':
- return [{ entityType: null, eventType: 'PROCESSED' }];
- default: return [];
- }
- }
+async function listAll<T>(params: Parameters<typeof listPage>[0] & { maxPages?: number }): Promise<{ items: T[]; truncated: boolean }> {
+ const { maxPages = DROPDOWN_MAX_PAGES, ...rest } = params;
+ const pages: T[][] = [];
+ let after: string | undefined;
+ for (let page = 0; page < maxPages; page++) {
+ const result = await listPage<T>({ ...rest, after });
+ pages.push(result.items);
+ if (!result.hasMore || !result.nextCursor) {
+ return { items: pages.flat(), truncated: false };
+ }
+ after = result.nextCursor;
+ }
+ return { items: pages.flat(), truncated: true };
+}
- generateWebhookInput(type: string, parameters: any): any {
- const conditions = [];
- if (parameters.audienceId) {
- conditions.push({
- dataFieldId: null,
- fieldName: 'audience',
- operator: 'IF_TRUE',
- value: parameters.audienceId,
- });
- }
- if (parameters.groupId) {
- conditions.push({
- dataFieldId: null,
- fieldName: 'groups',
- operator: 'CONTAINS',
- value: parameters.groupId,
- });
- }
- if (parameters.tagId) {
- conditions.push({
- dataFieldId: null,
- fieldName: 'tags',
- operator: 'CONTAINS',
- value: parameters.tagId,
- });
- }
+function andFilter(filters: Record<string, unknown>[]): Record<string, unknown> | null {
+ return filters.length === 0 ? null : { and: filters };
+}
- if (type === 'contactClicked' || type === 'contactOpened') {
- let campaignString = '';
- let value = null;
- if (parameters.campaignType === 'Any') {
- campaignString = `Campaign.AnyLast5.${type === 'contactClicked' ? 'Clicked' : 'Opened'
- }`;
- }
- if (parameters.campaignType === 'All') {
- campaignString = `Campaign.AllLast5.${type === 'contactClicked' ? 'Clicked' : 'Opened'
- }`;
- }
- if (parameters.campaignType === 'AnyX') {
- campaignString = `Campaign.AnyWithinLast.${type === 'contactClicked' ? 'Clicked' : 'Opened'
- }`;
- value = `${parameters.campaignScope.campaignRange}${parameters.campaignScope.campaignPeriod}`;
- }
- if (parameters.campaignType === 'Specific') {
- campaignString = `Campaign.${parameters.campaignScope.campaignId}.${type === 'contactClicked' ? 'Clicked' : 'Opened'
- }${type === 'contactClicked' && parameters.campaignScope.linkId
- ? '.' + parameters.campaignScope.linkId
- : ''
- }`;
- }
+function splitList(value: string | undefined): string[] {
+ return (value ?? '')
+ .split(',')
+ .map((part) => part.trim())
+ .filter((part) => part.length > 0);
+}
- conditions.push({
- dataFieldId: null,
- fieldName: campaignString,
- operator: 'IF_TRUE',
- value,
- });
- }
+function audienceWhere({ name, tags }: { name?: string; tags?: string }): Record<string, unknown> | null {
+ const tagList = splitList(tags);
+ return andFilter([
+ ...(name && name.trim() ? [{ name: { contains: name.trim() } }] : []),
+ ...(tagList.length > 0 ? [{ tags: { some: { in: tagList } } }] : []),
+ ]);
+}
- if (type === 'contactStatusUpdated' && parameters.status !== 'Any') {
- conditions.push({
- dataFieldId: null,
- fieldName: 'Status',
- operator: 'EQUAL',
- value: parameters.status,
- });
- }
+function campaignWhere({ name, tags, status }: { name?: string; tags?: string; status?: string }): Record<string, unknown> | null {
+ const tagList = splitList(tags);
+ const statuses = splitList(status).flatMap((s) => {
+ if (s === 'PENDING') return ['PENDING', 'PROCESSING', 'QUEUED'];
+ if (s === 'STOPPED') return ['STOPPED', 'SYSTEM_STOPPED'];
+ if (s === 'Paused') return ['PAUSED'];
+ return [s];
+ });
+ return andFilter([
+ ...(name && name.trim() ? [{ name: { contains: name.trim() } }] : []),
+ ...(tagList.length > 0 ? [{ tags: { some: { in: tagList } } }] : []),
+ ...(statuses.length > 0 ? [{ sendStatus: { in: statuses } }] : []),
+ ]);
+}
- if (type === 'formSubmitted' && parameters.formId) {
- conditions.push({
- dataFieldId: null,
- fieldName: `Form.${parameters.formId}.Submitted`,
- operator: 'IF_TRUE',
- value: null,
- });
- }
+function journeyWhere({ name, tags, status }: { name?: string; tags?: string; status?: string }): Record<string, unknown> | null {
+ const tagList = splitList(tags);
+ const statuses = splitList(status);
+ return andFilter([
+ ...(name && name.trim() ? [{ name: { contains: name.trim() } }] : []),
+ ...(tagList.length > 0 ? [{ tags: { some: { in: tagList } } }] : []),
+ ...(statuses.length > 0 ? [{ status: { in: statuses } }] : []),
+ ]);
+}
- if (type === 'landingPageCtaPerformed' && parameters.pageId) {
- conditions.push({
- dataFieldId: null,
- fieldName: `Page.${parameters.pageId}.CTA`,
- operator: 'IF_TRUE',
- value: null,
- });
- }
+function dropdownCampaignWhere({ ignoreStatus, isEvent }: { ignoreStatus: boolean; isEvent: boolean }): Record<string, unknown> {
+ const statusFilter = ignoreStatus
+ ? { sendStatus: { nin: ['PAUSED', 'PENDING', 'PROCESSING', 'QUEUED', 'SYSTEM_STOPPED'] } }
+ : { sendStatus: { in: isEvent ? ['NOT_SCHEDULED', 'COMPLETED'] : ['NOT_SCHEDULED', 'READY_TO_SEND'] } };
+ return { and: [{ isArchived: { eq: false } }, statusFilter] };
+}
- if (type === 'surveySubmitted' && parameters.surveyId) {
- conditions.push({
- dataFieldId: null,
- fieldName: `Survey.${parameters.surveyId}.Submitted`,
- operator: 'IF_TRUE',
- value: null,
- });
- }
+async function getContact({
+ auth,
+ audienceId,
+ contactId,
+ email,
+}: {
+ auth: TarventCredentials;
+ audienceId: string;
+ contactId?: string;
+ email?: string;
+}): Promise<TarventContact | null> {
+ try {
+ return await tarventTransport.field<TarventContact>({
+ auth,
+ query: `query GetContact($input: GetContactInput!) { contact(input: $input) { ${CONTACT_FIELDS} } }`,
+ variables: { input: { audienceId, emailAddress: email ?? null, id: contactId ?? null } },
+ name: 'contact',
+ });
+ } catch (error) {
+ if (isContactNotFound(error)) {
+ await assertAudienceReadable({ auth, audienceId });
+ return null;
+ }
+ throw error;
+ }
+}
- return conditions.length !== 0
- ? {
- operator: 'AND',
- conditions,
- conditionGroups: [],
- }
- : null;
- }
+async function createContact({ auth, input }: { auth: TarventCredentials; input: Record<string, unknown> }): Promise<TarventContact> {
+ return tarventTransport.field<TarventContact>({
+ auth,
+ query: `mutation CreateContact($input: CreateContactInput!) { createContact(input: $input) { ${CONTACT_FIELDS} } }`,
+ variables: { input },
+ name: 'createContact',
+ });
+}
- getHelpText(fieldName: string, dataType: string, defaultValue: string, isGdpr = false): string {
- switch (dataType) {
- case 'BIRTHDAY': {
- return `This will set the value for the ${fieldName} data field.`;
- }
- case 'DATE': {
- return `This will set the value for the ${fieldName} data field.`;
- }
- case 'DATE_TIME': {
- return `This will set the value for the ${fieldName} data field.`;
- }
- case 'NUMBER': {
- if (isGdpr) {
- return `Enter 1 to allow and 0 to not allow. This will set the value for the ${fieldName}* GDPR permission.`;
- } else {
- return `This will set the value for the ${fieldName} data field. Must contain only numbers. (255 character limit)`;
- }
- }
- case 'ZIP_CODE': {
- return `U.S. Only. This will set the value for the ${fieldName} data field. Format: ##### or #####-#### (10 character limit)`;
- }
- case 'PHONE': {
- return `This will set the value for the ${fieldName} data field.`;
- }
- case 'COUNTRY':
- case 'EMAIL':
- case 'IMAGE':
- case 'INT_PHONE':
- case 'STATE':
- case 'TEXT':
- case 'URL': {
- return `This will set the value for the ${fieldName} data field.${defaultValue ? ' Default value: ' + defaultValue : ''
- } (255 character limit)`;
- }
- default: return '';
- }
- };
+async function updateContact({ auth, input }: { auth: TarventCredentials; input: Record<string, unknown> }): Promise<TarventContact> {
+ return tarventTransport.field<TarventContact>({
+ auth,
+ query: `mutation UpdateContact($input: UpdateContactInput!) { updateContact(input: $input) { ${CONTACT_FIELDS} } }`,
+ variables: { input },
+ name: 'updateContact',
+ });
+}
- isISODate(str: string): boolean {
- const isoFormat = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z?$/;
- return isoFormat.test(str) && !isNaN(Date.parse(str));
- }
+async function booleanMutation({
+ auth,
+ operation,
+ field,
+ argDefs,
+ args,
+ variables,
+}: {
+ auth: TarventCredentials;
+ operation: string;
+ field: string;
+ argDefs: string;
+ args: string;
+ variables: Record<string, unknown>;
+}): Promise<boolean> {
+ const result = await tarventTransport.field<unknown>({
+ auth,
+ query: `mutation ${operation}(${argDefs}) { ${field}(${args}) }`,
+ variables,
+ name: field,
+ });
+ if (result !== true) {
+ throw new TarventApiError(`Tarvent did not confirm ${field} (returned ${JSON.stringify(result)}).`, undefined, 200, result);
+ }
+ return true;
+}
- formatISODateToYMD(isoString: string): string {
- console.log(isoString);
- const date = new Date(isoString);
- const year = date.getFullYear();
- const month = date.getMonth() + 1; // Months are zero-based
- const day = date.getDate();
+async function createWebhook({
+ auth,
+ name,
+ callBackUrl,
+ events,
+ filter,
+ dataSettings,
+}: {
+ auth: TarventCredentials;
+ name: string;
+ callBackUrl: string;
+ events: TarventWebhookEvent[];
+ filter: Record<string, unknown> | null;
+ dataSettings: string;
+}): Promise<{ id: string }> {
+ return tarventTransport.field<{ id: string }>({
+ auth,
+ query:
+ 'mutation CreateWebhook($name: String!, $description: String, $events: [WebhookEventInput!]!, $callBackUrl: String!, $dataSettings: WebhookDataSetting, $filter: ConditionGroupInput) { createWebhook(name: $name, description: $description, events: $events, callBackUrl: $callBackUrl, dataSettings: $dataSettings, filter: $filter) { id } }',
+ variables: { name, description: '', callBackUrl, events, filter, dataSettings },
+ name: 'createWebhook',
+ });
+}
- return `${year}/${month}/${day}`;
- }
- //#endregion
+async function deleteWebhook({ auth, id }: { auth: TarventCredentials; id: string }): Promise<void> {
+ try {
+ await booleanMutation({
+ auth,
+ operation: 'DeleteWebhook',
+ field: 'deleteWebhook',
+ argDefs: '$id: String!',
+ args: 'id: $id',
+ variables: { id },
+ });
+ } catch (error) {
+ if (isNotFound(error)) {
+ return;
+ }
+ throw error;
+ }
}
+
+export const tarventClient = {
+ listPage,
+ listAll,
+ audienceWhere,
+ campaignWhere,
+ journeyWhere,
+ dropdownCampaignWhere,
+ getContact,
+ createContact,
+ updateContact,
+ booleanMutation,
+ createWebhook,
+ deleteWebhook,
+ isNotFound,
+ splitList,
+ pageSize: PAGE_SIZE,
+ fields: {
+ contact: CONTACT_FIELDS,
+ audience: AUDIENCE_FIELDS,
+ campaign: CAMPAIGN_FIELDS,
+ journey: JOURNEY_FIELDS,
+ campaignStats: CAMPAIGN_STATS_FIELDS,
+ transaction: TRANSACTION_FIELDS,
+ },
+};
+
+export type TarventPage<T> = {
+ items: T[];
+ count: number;
+ totalCount: number | null;
+ hasMore: boolean;
+ nextCursor: string | null;
+};
+
+export type TarventConnection<T> = {
+ totalCount?: number;
+ nodes?: T[];
+ pageInfo?: { hasNextPage?: boolean; endCursor?: string | null };
+};
+
+export type TarventWebhookEvent = { entityType: string | null; eventType: string };
+
+export type TarventContact = Record<string, unknown> & { id: string };
diff --git a/packages/pieces/community/tarvent/src/lib/common/constants.ts b/packages/pieces/community/tarvent/src/lib/common/constants.ts
deleted file mode 100644
index 1f4a6cf05ce..00000000000
--- a/packages/pieces/community/tarvent/src/lib/common/constants.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-// export const WEBHOOK_SOURCES = ['public', 'admin', 'api', 'system'];
-
-export enum CUSTOM_FIELD_TYPE {
- TEXT = 'text',
- DROPDOWN = 'dropdown',
- TEXTAREA = 'textarea',
- NUMBER = 'number',
- MONEY = 'currency',
- DATE = 'date',
- DATETIME = 'datetime',
- LIST_BOX = 'listbox',
- MULTISELECT = 'multiselect',
- RADIO = 'radio',
- CHECKBOX = 'checkbox',
- HIDDEN = 'hidden',
-}
diff --git a/packages/pieces/community/tarvent/src/lib/common/index.ts b/packages/pieces/community/tarvent/src/lib/common/index.ts
index 18f9bc0dc2d..8f298ba0c56 100644
--- a/packages/pieces/community/tarvent/src/lib/common/index.ts
+++ b/packages/pieces/community/tarvent/src/lib/common/index.ts
@@ -1,633 +1,537 @@
-import { AppConnectionValueForAuthProperty, DynamicPropsValue, PiecePropValueSchema, Property } from '@activepieces/pieces-framework';
+import { DropdownOption, DropdownState, DynamicPropsValue, Property } from '@activepieces/pieces-framework';
import { tarventAuth } from '../auth';
-import { TarventClient } from './client';
-
-export function makeClient(auth: AppConnectionValueForAuthProperty<typeof tarventAuth>) {
- const client = new TarventClient(auth.props.accountId, auth.props.apiKey);
- return client;
-}
+import { tarventClient } from './client';
+import { TarventCredentials, tarventTransport } from './transport';
export const tarventCommon = {
- customEventId: (required = false, description = '') => Property.Dropdown({
+ customEventId: (required = false, description = '') =>
+ Property.Dropdown({
auth: tarventAuth,
-
-
- displayName: 'Custom event',
- description,
- required,
- refreshers: [],
- options: async ({ auth }) => {
- if (!auth) {
- return {
- disabled: true,
- placeholder: 'Please connect your account first',
- options: [],
- };
- }
- const client = makeClient(auth);
- const res = await client.listCustomEvents();
-
- return {
- disabled: false,
- options: res.data.customApiEvents.nodes.map((customApiEvents) => {
- return {
- label: customApiEvents.name,
- value: customApiEvents.key,
- };
- }),
- };
- },
+ displayName: 'Custom event',
+ description,
+ required,
+ refreshers: [],
+ options: async ({ auth }) =>
+ loadOptions({
+ auth: auth?.props,
+ load: async (credentials) => {
+ const result = await tarventClient.listAll<{ key: string; name: string }>({
+ auth: credentials,
+ operation: 'GetCustomEvents',
+ field: 'customApiEvents',
+ selection: 'id key name',
+ });
+ return { ...result, options: result.items.map((e) => ({ label: e.name, value: e.key })) };
+ },
+ }),
}),
- campaignId: (required = false, description = '', ignoreStatus = false, isEvent = false) =>
- Property.Dropdown({
+ campaignId: (required = false, description = '', ignoreStatus = false, isEvent = false) =>
+ Property.Dropdown({
auth: tarventAuth,
-
- displayName: 'Campaign',
- description,
- required,
- refreshers: [],
- options: async ({ auth }) => {
- if (!auth) {
- return {
- disabled: true,
- placeholder: 'Please connect your account first',
- options: [],
- };
- }
- const client = makeClient(auth);
- const res = await client.listCampaigns(ignoreStatus, isEvent);
- console.log(res);
- return {
- disabled: false,
- options: res.data.campaigns.nodes.map((campaigns) => {
- return {
- label: campaigns.name,
- value: campaigns.id,
- };
- }),
- };
- },
+ displayName: 'Campaign',
+ description,
+ required,
+ refreshers: [],
+ options: async ({ auth }) =>
+ loadOptions({
+ auth: auth?.props,
+ load: async (credentials) => {
+ const result = await tarventClient.listAll<{ id: string; name: string }>({
+ auth: credentials,
+ operation: 'GetCampaigns',
+ field: 'campaigns',
+ selection: 'id name',
+ argDefs: ', $where: CampaignInfoFilterInput, $order: [CampaignInfoSortInput!]',
+ args: ', where: $where, order: $order',
+ variables: { where: tarventClient.dropdownCampaignWhere({ ignoreStatus, isEvent }), order: [{ modifiedUtc: 'DESC' }] },
+ });
+ return { ...result, options: result.items.map((c) => ({ label: c.name, value: c.id })) };
+ },
}),
- campaignLinkId: (required = false) =>
- Property.Dropdown({
+ }),
+ campaignLinkId: (required = false) =>
+ Property.Dropdown({
auth: tarventAuth,
-
- displayName: 'Campaign link',
- description: 'Only used if campaign type is set to "Specific". If specified, the trigger will only fire if a contact clicks the selected link.',
- required,
- refreshers: ['campaignId'],
- options: async ({ auth, campaignId }) => {
- if (!auth) {
- return {
- disabled: true,
- placeholder: 'Please connect your account first',
- options: [],
- };
- }
- const client = makeClient(auth);
- const res = await client.listCampaignLinks(campaignId as string);
-
- return {
- disabled: false,
- options: res.data.campaignLinks.nodes.map((link) => {
- return {
- label: link.url,
- value: link.id,
- };
- }),
- };
- },
+ displayName: 'Campaign link',
+ description: 'Only used if campaign type is set to "Specific". If specified, the trigger will only fire if a contact clicks the selected link.',
+ required,
+ refreshers: ['campaignId'],
+ options: async ({ auth, campaignId }) => {
+ if (!campaignId) {
+ return { disabled: true, placeholder: 'Select a campaign first', options: [] };
+ }
+ return loadOptions({
+ auth: auth?.props,
+ load: async (credentials) => {
+ const links = await tarventTransport.field<{ id: string; url: string }[]>({
+ auth: credentials,
+ query: 'query GetCampaignLinks($id: String!) { campaignLinks(id: $id) { id url } }',
+ variables: { id: campaignId },
+ name: 'campaignLinks',
+ });
+ return { truncated: false, options: links.map((l) => ({ label: l.url, value: l.id })) };
+ },
+ });
+ },
+ }),
+ journeyId: (required = false, description = '') =>
+ Property.Dropdown({
+ auth: tarventAuth,
+ displayName: 'Journey',
+ description,
+ required,
+ refreshers: [],
+ options: async ({ auth }) =>
+ loadOptions({
+ auth: auth?.props,
+ load: async (credentials) => {
+ const result = await tarventClient.listAll<{ id: string; name: string }>({
+ auth: credentials,
+ operation: 'GetJourneys',
+ field: 'journeys',
+ selection: 'id name',
+ });
+ return { ...result, options: result.items.map((j) => ({ label: j.name, value: j.id })) };
+ },
+ }),
+ }),
+ campaignScope: Property.DynamicProperties({
+ auth: tarventAuth,
+ displayName: 'Campaign scope',
+ refreshers: ['campaignType'],
+ required: false,
+ props: async ({ campaignType }) => {
+ if (String(campaignType) !== 'AnyX') {
+ return {};
+ }
+ const prop: DynamicPropsValue = {
+ campaignRange: Property.Number({ displayName: 'Range', required: true }),
+ campaignPeriod: Property.StaticDropdown({
+ displayName: 'Period',
+ required: true,
+ options: {
+ options: [
+ { label: 'Hour(s)', value: 'h' },
+ { label: 'Day(s)', value: 'd' },
+ { label: 'Week(s)', value: 'w' },
+ { label: 'Month(s)', value: 'm' },
+ ],
+ },
+ defaultValue: 'd',
}),
- journeyId: (required = false, description = '') =>
- Property.Dropdown({
+ };
+ return prop;
+ },
+ }),
+ audienceId: (required = false, description = '') =>
+ Property.Dropdown({
auth: tarventAuth,
-
- displayName: 'Journey',
- description,
- required,
- refreshers: [],
- options: async ({ auth }) => {
- if (!auth) {
- return {
- disabled: true,
- placeholder: 'Please connect your account first',
- options: [],
- };
- }
- const client = makeClient(auth);
- const res = await client.listJourneys();
-
- return {
- disabled: false,
- options: res.data.journeys.nodes.map((journey) => {
- return {
- label: journey.name,
- value: journey.id,
- };
- }),
- };
- },
+ displayName: 'Audience',
+ description,
+ required,
+ refreshers: [],
+ options: async ({ auth }) =>
+ loadOptions({
+ auth: auth?.props,
+ load: async (credentials) => {
+ const result = await tarventClient.listAll<{ id: string; name: string }>({
+ auth: credentials,
+ operation: 'GetAudiences',
+ field: 'audiences',
+ selection: 'id name',
+ });
+ return { ...result, options: result.items.map((a) => ({ label: a.name, value: a.id })) };
+ },
}),
- campaignScope: Property.DynamicProperties({
+ }),
+ audienceGroupId: (required = false, description = '') =>
+ Property.Dropdown({
auth: tarventAuth,
- displayName: 'Campaign scope',
- refreshers: ['campaignType'],
- required: false,
- props: async ({ campaignType }) => {
- const prop: DynamicPropsValue = {};
-
- if (campaignType as unknown === 'AnyX') {
- prop['campaignRange'] = Property.Number({
- displayName: 'Range',
- required: true,
- });
- prop['campaignPeriod'] = Property.StaticDropdown({
- displayName: 'Period',
- description: '',
- required: true,
- options: {
- options: [
- {
- label: 'Hour(s)',
-
- value: 'h',
- },
- {
- label: 'Day(s)',
- value: 'd',
- },
- {
- label: 'Week(s)',
- value: 'w',
- },
- {
- label: 'Month(s)',
- value: 'm',
- },
- ],
- },
- defaultValue: 'd'
- });
- }
-
- return prop;
- },
+ displayName: 'Audience group',
+ description,
+ required,
+ refreshers: ['audienceId'],
+ options: async ({ auth, audienceId }) => groupOptions({ auth: auth?.props, audienceId }),
}),
- audienceId: (required = false, description = '') =>
- Property.Dropdown({
+ audienceGroupIds: (required = false, description = '') =>
+ Property.MultiSelectDropdown({
auth: tarventAuth,
-
- displayName: 'Audience',
- description,
- required,
- refreshers: [],
- options: async ({ auth }) => {
- if (!auth) {
- return {
- disabled: true,
- placeholder: 'Please connect your account first',
- options: [],
- };
- }
- const client = makeClient(auth);
- const res = await client.listAudiences();
-
- return {
- disabled: false,
- options: res.data.audiences.nodes.map((audience) => {
- return {
- label: audience.name,
- value: audience.id,
- };
- }),
- };
- },
- }),
- audienceGroupId: (required = false, description = '') =>
- Property.Dropdown({
+ displayName: 'Audience group',
+ description,
+ required,
+ refreshers: ['audienceId'],
+ options: async ({ auth, audienceId }) => groupOptions({ auth: auth?.props, audienceId }),
+ }),
+ audienceFormId: (required = false, description = '') =>
+ Property.Dropdown({
auth: tarventAuth,
-
- displayName: 'Audience group',
- description,
- required,
- refreshers: ['audienceId'],
- options: async ({ auth, audienceId }) => {
- if (!auth) {
- return {
- disabled: true,
- placeholder: 'Please connect your account first',
- options: [],
- };
- }
- if (!audienceId) {
- return {
- disabled: true,
- placeholder: 'Please select an audience first',
- options: [],
- };
- }
- const client = makeClient(auth);
- const res = await client.listAudienceGroups(audienceId as string);
-
- return {
- disabled: false,
- options: res.data.audienceGroups.nodes.map((group) => {
- return {
- label: group.name,
- value: group.id,
- };
- }),
- };
- },
- }),
- audienceFormId: (required = false, description = '') =>
- Property.Dropdown({
+ displayName: 'Audience form',
+ description,
+ required,
+ refreshers: ['audienceId'],
+ options: async ({ auth, audienceId }) => {
+ if (!audienceId) {
+ return { disabled: true, placeholder: 'Please select an audience first', options: [] };
+ }
+ return loadOptions({
+ auth: auth?.props,
+ load: async (credentials) => {
+ const result = await tarventClient.listAll<{ id: string; name: string }>({
+ auth: credentials,
+ operation: 'GetForms',
+ field: 'forms',
+ selection: 'id name',
+ argDefs: ', $audienceId: String, $order: [FormInfoSortInput!]',
+ args: ', audienceId: $audienceId, order: $order',
+ variables: { audienceId, order: [{ name: 'ASC' }] },
+ });
+ return { ...result, options: result.items.map((f) => ({ label: f.name, value: f.id })) };
+ },
+ });
+ },
+ }),
+ audienceDataFields: Property.DynamicProperties({
+ displayName: 'Data fields',
+ auth: tarventAuth,
+ refreshers: ['audienceId'],
+ required: false,
+ props: async ({ auth, audienceId }) => {
+ if (!auth || !audienceId) {
+ return {};
+ }
+ const { items } = await tarventClient.listAll<TarventDataField>({
+ auth: auth.props,
+ operation: 'GetDataFields',
+ field: 'audienceDataFields',
+ selection: 'id dataType labelText required isSystem defaultValue isGdprField',
+ argDefs: ', $audienceId: String!',
+ args: ', audienceId: $audienceId',
+ variables: { audienceId },
+ });
+ return Object.fromEntries(
+ items.filter((f) => !f.isSystem || f.isGdprField).map((f) => [f.id, dataFieldProperty({ field: f })]),
+ );
+ },
+ }),
+ contactId: Property.ShortText({
+ displayName: 'Contact ID',
+ description: 'The Tarvent contact ID. Find it in the edit contact dialog on the details page, or from Find Contact.',
+ required: true,
+ }),
+ name: (displayName: string, required: boolean, description = '') =>
+ Property.ShortText({ displayName, description, required }),
+ include: Property.StaticDropdown({
+ displayName: 'Include all contact data',
+ description: 'If not included, only the contact ID, email and unique identifier will be passed back.',
+ required: true,
+ defaultValue: 'BASIC',
+ options: {
+ options: [
+ { label: 'Include', value: 'EXTENDED' },
+ { label: 'Do not include', value: 'BASIC' },
+ ],
+ },
+ }),
+ entity: Property.StaticDropdown({
+ displayName: 'Email type',
+ description: 'Select if a campaign, transactional email or both should fire the trigger.',
+ required: true,
+ defaultValue: 'BOTH',
+ options: {
+ options: [
+ { label: 'Both', value: 'BOTH' },
+ { label: 'Campaign', value: 'CAMPAIGN' },
+ { label: 'Transaction', value: 'TRANSACTION' },
+ ],
+ },
+ }),
+ tagId: (required = false, description = '') =>
+ Property.Dropdown({
auth: tarventAuth,
-
- displayName: 'Audience form',
- description,
- required,
- refreshers: ['audienceId'],
- options: async ({ auth, audienceId }) => {
- if (!auth) {
- return {
- disabled: true,
- placeholder: 'Please connect your account first',
- options: [],
- };
- }
- if (!audienceId) {
- return {
- disabled: true,
- placeholder: 'Please select an audience first',
- options: [],
- };
- }
- const client = makeClient(auth);
- const res = await client.listAudienceForms(audienceId as string);
-
- return {
- disabled: false,
- options: res.data.forms.nodes.map((form) => {
- return {
- label: form.name,
- value: form.id,
- };
- }),
- };
- },
- }),
- audienceGroupIds: (required = false, description = '') =>
- Property.MultiSelectDropdown({
- auth: tarventAuth,
- displayName: 'Audience group',
- description,
- required,
- refreshers: ['audienceId'],
- options: async ({ auth, audienceId }) => {
- if (!auth) {
- return {
- disabled: true,
- placeholder: 'Please connect your account first',
- options: [],
- };
- }
- if (!audienceId) {
- return {
- disabled: true,
- placeholder: 'Please select an audience first',
- options: [],
- };
- }
- const client = makeClient(auth);
- const res = await client.listAudienceGroups(audienceId as string);
-
- return {
- disabled: false,
- options: res.data.audienceGroups.nodes.map((group) => {
- return {
- label: group.name,
- value: group.id,
- };
- }),
- };
- },
- }),
- audienceDataFields: Property.DynamicProperties({
- displayName: 'Data fields',
- auth: tarventAuth,
- refreshers: ['audienceId'],
- required: false,
- props: async ({ auth, audienceId }) => {
- if (!auth) return {};
-
- const client = makeClient(auth);
- const res = await client.listAudienceDataFields(audienceId as unknown);
-
- const fields: DynamicPropsValue = {};
- const fieldsFromApi = res.data.audienceDataFields.nodes;
-
- if (fieldsFromApi) {
- fieldsFromApi.forEach((f) => {
- if (!f.isSystem && !f.isGdprField) {
- switch (f.dataType) {
- case 'NUMBER': {
- fields[f.id] = Property.Number({
- displayName: f.labelText,
- required: f.required,
- description: client.getHelpText(
- f.labelText,
- f.dataType,
- f.defaultValue
- ),
- });
- break;
- }
- case 'DATE':
- case 'DATE_TIME': {
- fields[f.id] = Property.DateTime({
- displayName: f.labelText,
- required: f.required,
- description: client.getHelpText(
- f.labelText,
- f.dataType,
- f.defaultValue
- ),
- });
- break;
- }
- default: {
- fields[f.id] = Property.ShortText({
- displayName: f.labelText,
- required: f.required,
- description: client.getHelpText(
- f.labelText,
- f.dataType,
- f.defaultValue
- ),
- });
- break;
- }
- }
-
- }
- if (f.isGdprField) {
- fields[f.id] = {
- displayName: f.labelText.replace('GDPR_', '') + ' (GDPR Permission)',
- required: f.required,
- description: client.getHelpText(
- f.labelText.replace('GDPR_', ''),
- f.dataType,
- f.defaultValue,
- true
- ),
- };
- }
- });
- }
- return fields;
- },
+ displayName: 'Tags',
+ description,
+ required,
+ refreshers: [],
+ options: async ({ auth }) => tagOptions({ auth: auth?.props }),
}),
-
- contactId: Property.ShortText({
- displayName: 'Contact ID',
- description: 'Find this in the edit contact dialog on the details page.',
- required: true,
- defaultValue: '',
+ tagIds: (required = false, description = '') =>
+ Property.MultiSelectDropdown({
+ auth: tarventAuth,
+ displayName: 'Tags',
+ description,
+ required,
+ refreshers: [],
+ options: async ({ auth }) => tagOptions({ auth: auth?.props }),
}),
- name: (displayName: string, required: boolean, description = '') =>
- Property.ShortText({
- displayName,
- description,
- required,
- defaultValue: '',
+ txGroupName: (required = false, description = '') =>
+ Property.Dropdown({
+ auth: tarventAuth,
+ displayName: 'Transaction group name',
+ description,
+ required,
+ refreshers: [],
+ options: async ({ auth }) =>
+ loadOptions({
+ auth: auth?.props,
+ load: async (credentials) => {
+ const data = await tarventTransport.graphql<{ transactionGroupNames?: string[] | null }>({
+ auth: credentials,
+ query: 'query GetTxGroupNames { transactionGroupNames }',
+ });
+ return { truncated: false, options: (data.transactionGroupNames ?? []).map((n) => ({ label: n, value: n })) };
+ },
}),
- description: (displayName: string, required: boolean, description = '') =>
- Property.LongText({
- displayName,
- description,
- required,
- defaultValue: '',
+ }),
+ templateId: (required = false, description = '') =>
+ Property.Dropdown({
+ auth: tarventAuth,
+ displayName: 'Template',
+ description,
+ required,
+ refreshers: [],
+ options: async ({ auth }) =>
+ loadOptions({
+ auth: auth?.props,
+ load: async (credentials) => {
+ const result = await tarventClient.listAll<{ id: string; name: string }>({
+ auth: credentials,
+ operation: 'GetTemplates',
+ field: 'templates',
+ selection: 'id name',
+ });
+ return { ...result, options: result.items.map((t) => ({ label: t.name, value: t.id })) };
+ },
}),
- include: Property.StaticDropdown({
- displayName: 'Include all contact data',
- description: 'If not included, only the contact ID, email and unique identifier will be passed back.',
- required: true,
- defaultValue: 'BASIC',
- options: {
- options: [
- {
- label: 'Include',
-
- value: 'EXTENDED',
- },
- {
- label: 'Do not include',
- value: 'BASIC',
- },
- ],
- },
}),
- entity: Property.StaticDropdown({
- displayName: 'Email type',
- description: 'Select if a campaign, transactional email or both should fire the trigger.',
- required: true,
- defaultValue: 'BOTH',
- options: {
- options: [
- {
- label: 'Both',
-
- value: 'BOTH',
- },
- {
- label: 'Campaign',
- value: 'CAMPAIGN',
- },
- {
- label: 'Transaction',
- value: 'TRANSACTION',
- },
- ],
+ landingPageId: Property.Dropdown({
+ auth: tarventAuth,
+ displayName: 'Landing page',
+ description: 'If specified, the trigger will only fire if CTA (call-to-action) is performed on the selected landing page.',
+ required: false,
+ refreshers: [],
+ options: async ({ auth }) =>
+ loadOptions({
+ auth: auth?.props,
+ load: async (credentials) => {
+ const result = await tarventClient.listAll<{ id: string; name: string }>({
+ auth: credentials,
+ operation: 'GetLandingPages',
+ field: 'landingPages',
+ selection: 'id name',
+ });
+ return { ...result, options: result.items.map((p) => ({ label: p.name, value: p.id })) };
},
- }),
- tagId: (required = false, description = '') =>
- Property.Dropdown({
- auth: tarventAuth,
+ }),
+ }),
+ surveyId: Property.Dropdown({
+ auth: tarventAuth,
+ displayName: 'Survey',
+ description: 'If specified, the trigger will only fire if the selected survey is submitted.',
+ required: false,
+ refreshers: [],
+ options: async ({ auth }) =>
+ loadOptions({
+ auth: auth?.props,
+ load: async (credentials) => {
+ const result = await tarventClient.listAll<{ id: string; name: string }>({
+ auth: credentials,
+ operation: 'GetSurveys',
+ field: 'surveys',
+ selection: 'id name',
+ });
+ return { ...result, options: result.items.map((s) => ({ label: s.name, value: s.id })) };
+ },
+ }),
+ }),
+ limit: Property.Number({
+ displayName: 'Limit',
+ description: 'Maximum number of results to return (1-50). Use the returned Next Cursor to get more.',
+ required: false,
+ defaultValue: 50,
+ }),
+ cursor: Property.ShortText({
+ displayName: 'Cursor',
+ description: 'Next Cursor from a previous run, to get the next page of results.',
+ required: false,
+ }),
+ pageLimit,
+ trimmed,
+ requireText,
+ checkLength,
+ splitEmail,
+ profileFromDataFields,
+};
- displayName: 'Tags',
- description,
- required,
- refreshers: [],
- options: async ({ auth, searchField }) => {
- if (!auth) {
- return {
- disabled: true,
- placeholder: 'Please connect your account first',
- options: [],
- };
- }
- const client = makeClient(auth);
- const res = await client.listTags();
+function splitEmail(email: string): { localPart: string; domain: string } {
+ const at = email.lastIndexOf('@');
+ if (at <= 0 || at === email.length - 1) {
+ throw new Error('Email address must look like [email protected].');
+ }
+ return { localPart: email.slice(0, at), domain: email.slice(at + 1) };
+}
- console.log(res, searchField)
+function checkLength({ value, label, max }: { value: string | undefined; label: string; max: number }): void {
+ if (value !== undefined && value.length > max) {
+ throw new Error(`${label} must be ${max} characters or fewer.`);
+ }
+}
- return {
- disabled: false,
- options: res.data.tags.nodes.map((tag) => {
- return {
- label: tag.name,
- value: tag.name,
- };
- }),
- };
- },
- }),
- tagIds: (required = false, description = '') =>
- Property.MultiSelectDropdown({
- auth: tarventAuth,
- displayName: 'Tags',
- description,
- required,
- refreshers: [],
- options: async ({ auth }) => {
- if (!auth) {
- return {
- disabled: true,
- placeholder: 'Please connect your account first',
- options: [],
- };
- }
- const client = makeClient(auth);
- const res = await client.listTags();
+function pageLimit(value: unknown): number {
+ const parsed = typeof value === 'string' && value.trim() !== '' ? Number(value) : value;
+ if (parsed === undefined || parsed === null || parsed === '') {
+ return 50;
+ }
+ if (typeof parsed !== 'number' || !Number.isInteger(parsed) || parsed < 1 || parsed > 50) {
+ throw new Error('Limit must be a whole number between 1 and 50.');
+ }
+ return parsed;
+}
- return {
- disabled: false,
- options: res.data.tags.nodes.map((tag) => {
- return {
- label: tag.name,
- value: tag.name,
- };
- }),
- };
- },
- }),
- txGroupName: (required = false, description = '') =>
- Property.Dropdown({
- auth: tarventAuth,
+function trimmed(value: unknown): string | undefined {
+ if (typeof value !== 'string' && typeof value !== 'number') {
+ return undefined;
+ }
+ const text = String(value).trim();
+ return text.length > 0 ? text : undefined;
+}
- displayName: 'Transaction group name',
- description,
- required,
- refreshers: [],
- options: async ({ auth }) => {
- if (!auth) {
- return {
- disabled: true,
- placeholder: 'Please connect your account first',
- options: [],
- };
- }
- const client = makeClient(auth);
- const res = await client.listTxGroupNames();
- console.log(res);
- return {
- disabled: false,
- options: res.data.transactionGroupNames ? res.data.transactionGroupNames.map((name) => {
- return {
- label: name,
- value: name,
- };
- }) : [],
- };
- },
- }),
- templateId: (required = false, description = '') =>
- Property.Dropdown({
- auth: tarventAuth,
+function requireText({ value, label }: { value: unknown; label: string }): string {
+ const text = trimmed(value);
+ if (!text) {
+ throw new Error(`${label} is required.`);
+ }
+ return text;
+}
- displayName: 'Template',
- description,
- required,
- refreshers: [],
- options: async ({ auth }) => {
- if (!auth) {
- return {
- disabled: true,
- placeholder: 'Please connect your account first',
- options: [],
- };
- }
- const client = makeClient(auth);
- const res = await client.listTemplates();
+function profileFromDataFields(fields: Record<string, unknown> | undefined): { dataFieldId: string; value: string }[] {
+ return Object.entries(fields ?? {}).flatMap(([dataFieldId, raw]) => {
+ if (raw === undefined || raw === null || raw === '') {
+ return [];
+ }
+ const text = typeof raw === 'string' ? raw : typeof raw === 'number' || typeof raw === 'boolean' ? String(raw) : JSON.stringify(raw);
+ return [{ dataFieldId, value: isIsoDateTime(text) ? formatYmd(text) : text }];
+ });
+}
- return {
- disabled: false,
- options: res.data.templates.nodes.map((template) => {
- return {
- label: template.name,
- value: template.id,
- };
- }),
- };
- },
- }),
- landingPageId: Property.Dropdown({
- auth: tarventAuth,
+function isIsoDateTime(text: string): boolean {
+ return /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z?$/.test(text) && !Number.isNaN(Date.parse(text));
+}
- displayName: 'Landing page',
- description: 'If specified, the trigger will only fire if CTA (call-to-action) is performed on the selected landing page.',
- required: false,
- refreshers: [],
- options: async ({ auth }) => {
- if (!auth) {
- return {
- disabled: true,
- placeholder: 'Please connect your account first',
- options: [],
- };
- }
- const client = makeClient(auth);
- const res = await client.listLandingPages();
+function formatYmd(text: string): string {
+ const date = new Date(text);
+ return `${date.getUTCFullYear()}/${date.getUTCMonth() + 1}/${date.getUTCDate()}`;
+}
- return {
- disabled: false,
- options: res.data.landingPages.nodes.map((lp) => {
- return {
- label: lp.name,
- value: lp.id,
- };
- }),
- };
- },
- }),
- surveyId: Property.Dropdown({
- auth: tarventAuth,
+function dataFieldProperty({ field }: { field: TarventDataField }) {
+ if (field.isGdprField) {
+ const label = field.labelText.replace('GDPR_', '');
+ return Property.StaticDropdown({
+ displayName: `${label} (GDPR Permission)`,
+ description: `Sets the ${label} GDPR permission. Leave empty to keep the current value.`,
+ required: field.required,
+ options: {
+ options: [
+ { label: 'Allow', value: '1' },
+ { label: 'Do not allow', value: '0' },
+ ],
+ },
+ });
+ }
+ const description = helpText({ field });
+ if (field.dataType === 'NUMBER') {
+ return Property.Number({ displayName: field.labelText, required: field.required, description });
+ }
+ if (field.dataType === 'DATE' || field.dataType === 'DATE_TIME') {
+ return Property.DateTime({ displayName: field.labelText, required: field.required, description });
+ }
+ return Property.ShortText({ displayName: field.labelText, required: field.required, description });
+}
- displayName: 'Survey',
- description: 'If specified, the trigger will only fire if the selected survey is submitted.',
- required: false,
- refreshers: [],
- options: async ({ auth }) => {
- if (!auth) {
- return {
- disabled: true,
- placeholder: 'Please connect your account first',
- options: [],
- };
- }
- const client = makeClient(auth);
- const res = await client.listSurveys();
+function helpText({ field }: { field: TarventDataField }): string {
+ const base = `This will set the value for the ${field.labelText} data field.`;
+ switch (field.dataType) {
+ case 'NUMBER':
+ return `${base} Must contain only numbers. (255 character limit)`;
+ case 'ZIP_CODE':
+ return `U.S. Only. ${base} Format: ##### or #####-#### (10 character limit)`;
+ case 'BIRTHDAY':
+ case 'DATE':
+ case 'DATE_TIME':
+ case 'PHONE':
+ return base;
+ default:
+ return `${base}${field.defaultValue ? ` Default value: ${field.defaultValue}` : ''} (255 character limit)`;
+ }
+}
- return {
- disabled: false,
- options: res.data.surveys.nodes.map((s) => {
- return {
- label: s.name,
- value: s.id,
- };
- }),
- };
- },
- }),
+async function loadOptions({
+ auth,
+ load,
+}: {
+ auth: TarventCredentials | undefined;
+ load: (auth: TarventCredentials) => Promise<{ options: DropdownOption<string>[]; truncated: boolean }>;
+}): Promise<DropdownState<string>> {
+ if (!auth) {
+ return { disabled: true, placeholder: 'Please connect your account first', options: [] };
+ }
+ try {
+ const { options, truncated } = await load(auth);
+ return {
+ disabled: false,
+ options,
+ placeholder: truncated ? 'Showing the first results only. Use a custom value for others.' : undefined,
+ };
+ } catch (error) {
+ return {
+ disabled: true,
+ placeholder: `Could not load options: ${error instanceof Error ? error.message : 'unknown error'}`,
+ options: [],
+ };
+ }
+}
+
+async function groupOptions({ auth, audienceId }: { auth: TarventCredentials | undefined; audienceId: unknown }): Promise<DropdownState<string>> {
+ if (!audienceId) {
+ return { disabled: true, placeholder: 'Please select an audience first', options: [] };
+ }
+ return loadOptions({
+ auth,
+ load: async (credentials) => {
+ const result = await tarventClient.listAll<{ id: string; name: string }>({
+ auth: credentials,
+ operation: 'GetAudienceGroups',
+ field: 'audienceGroups',
+ selection: 'id name',
+ argDefs: ', $audienceId: String!, $order: [AudienceGroupInfoSortInput!], $where: AudienceGroupInfoFilterInput',
+ args: ', audienceId: $audienceId, order: $order, where: $where',
+ variables: { audienceId, order: [{ name: 'ASC' }], where: { isDynamic: { eq: false } } },
+ });
+ return { ...result, options: result.items.map((g) => ({ label: g.name, value: g.id })) };
+ },
+ });
+}
+
+async function tagOptions({ auth }: { auth: TarventCredentials | undefined }): Promise<DropdownState<string>> {
+ return loadOptions({
+ auth,
+ load: async (credentials) => {
+ const result = await tarventClient.listAll<{ name: string }>({
+ auth: credentials,
+ operation: 'GetTags',
+ field: 'tags',
+ selection: 'name',
+ });
+ return { ...result, options: result.items.map((t) => ({ label: t.name, value: t.name })) };
+ },
+ });
+}
+
+type TarventDataField = {
+ id: string;
+ dataType: string;
+ labelText: string;
+ required: boolean;
+ isSystem: boolean;
+ defaultValue: string;
+ isGdprField: boolean;
};
diff --git a/packages/pieces/community/tarvent/src/lib/common/operations.ts b/packages/pieces/community/tarvent/src/lib/common/operations.ts
new file mode 100644
index 00000000000..40dd1d2a8b4
--- /dev/null
+++ b/packages/pieces/community/tarvent/src/lib/common/operations.ts
@@ -0,0 +1,222 @@
+import { tarventCommon } from '.';
+import { tarventClient } from './client';
+import { TarventCredentials, tarventTransport } from './transport';
+
+async function setContactTags({
+ auth,
+ audienceId,
+ contactId,
+ tags,
+ remove,
+}: {
+ auth: TarventCredentials;
+ audienceId: unknown;
+ contactId: unknown;
+ tags: unknown;
+ remove: boolean;
+}) {
+ const audience = tarventCommon.requireText({ value: audienceId, label: 'Audience' });
+ const id = tarventCommon.requireText({ value: contactId, label: 'Contact ID' });
+ const list = (Array.isArray(tags) ? tags : [])
+ .map((tag) => tarventCommon.trimmed(tag))
+ .filter((tag): tag is string => tag !== undefined);
+ if (list.length === 0) {
+ throw new Error('Enter at least one tag.');
+ }
+ if (list.length > 100) {
+ throw new Error('Tarvent accepts at most 100 tags per call.');
+ }
+ const operator = remove ? 'REMOVE' : 'ADD';
+ await tarventClient.booleanMutation({
+ auth,
+ operation: 'UpdateContactTags',
+ field: 'updateContactTags',
+ argDefs: '$input: UpdateContactTagsInput!',
+ args: 'input: $input',
+ variables: { input: { id, audienceId: audience, operator, tags: list } },
+ });
+ return { success: true, contactId: id, action: operator, tags: list };
+}
+
+async function setGroupMembership({
+ auth,
+ audienceId,
+ groupId,
+ contactId,
+ add,
+}: {
+ auth: TarventCredentials;
+ audienceId: unknown;
+ groupId: unknown;
+ contactId: unknown;
+ add: boolean;
+}) {
+ const audience = tarventCommon.requireText({ value: audienceId, label: 'Audience' });
+ const group = tarventCommon.requireText({ value: groupId, label: 'Audience group' });
+ const id = tarventCommon.requireText({ value: contactId, label: 'Contact ID' });
+ const mutation = add ? 'createGroupContact' : 'deleteGroupContact';
+ await tarventTransport.field<{ id?: string }>({
+ auth,
+ query: `mutation ${add ? 'CreateGroupContact' : 'DeleteGroupContact'}($input: ${add ? 'CreateGroupContactInput' : 'DeleteGroupContactInput'}!) { ${mutation}(input: $input) { id } }`,
+ variables: { input: { id, groupId: group, audienceId: audience } },
+ name: mutation,
+ });
+ return { success: true, contactId: id, groupId: group, audienceId: audience, action: add ? 'ADD' : 'REMOVE' };
+}
+
+async function setContactJourney({ auth, contactId, journeyId, add }: { auth: TarventCredentials; contactId: unknown; journeyId: unknown; add: boolean }) {
+ const id = tarventCommon.requireText({ value: contactId, label: 'Contact ID' });
+ const journey = tarventCommon.requireText({ value: journeyId, label: 'Journey' });
+ await tarventClient.booleanMutation({
+ auth,
+ operation: add ? 'EnterContactIntoJourney' : 'ExitContactFromJourney',
+ field: add ? 'enterContactIntoJourney' : 'exitContactFromJourney',
+ argDefs: '$id: String!, $journeyId: String!',
+ args: 'id: $id, journeyId: $journeyId',
+ variables: { id, journeyId: journey },
+ });
+ return { success: true, contactId: id, journeyId: journey, action: add ? 'ADD' : 'REMOVE' };
+}
+
+async function setJourneyStatus({ auth, journeyId, start }: { auth: TarventCredentials; journeyId: unknown; start: boolean }) {
+ const id = tarventCommon.requireText({ value: journeyId, label: 'Journey' });
+ await tarventClient.booleanMutation({
+ auth,
+ operation: start ? 'StartJourney' : 'StopJourney',
+ field: start ? 'startJourney' : 'stopJourney',
+ argDefs: '$id: String!',
+ args: 'id: $id',
+ variables: { id },
+ });
+ return { success: true, journeyId: id, action: start ? 'START' : 'STOP' };
+}
+
+async function deleteContact({ auth, audienceId, contactId }: { auth: TarventCredentials; audienceId: unknown; contactId: unknown }) {
+ const audience = tarventCommon.requireText({ value: audienceId, label: 'Audience' });
+ const id = tarventCommon.requireText({ value: contactId, label: 'Contact ID' });
+ await tarventClient.booleanMutation({
+ auth,
+ operation: 'DeleteContact',
+ field: 'deleteContact',
+ argDefs: '$input: DeleteContactInput!',
+ args: 'input: $input',
+ variables: { input: { audienceId: audience, id } },
+ });
+ return { success: true, contactId: id, audienceId: audience };
+}
+
+async function recordCustomEvent({ auth, contactId, eventKey }: { auth: TarventCredentials; contactId: unknown; eventKey: unknown }) {
+ const key = tarventCommon.requireText({ value: eventKey, label: 'Custom event' });
+ const id = tarventCommon.requireText({ value: contactId, label: 'Contact ID' });
+ await tarventClient.booleanMutation({
+ auth,
+ operation: 'CreateContactCustomEvent',
+ field: 'createContactCustomEvent',
+ argDefs: '$id: String!, $key: String!',
+ args: 'id: $id, key: $key',
+ variables: { id, key },
+ });
+ return { success: true, contactId: id, eventKey: key };
+}
+
+async function createAudienceGroup({
+ auth,
+ audienceId,
+ name,
+ description,
+ isPublic,
+}: {
+ auth: TarventCredentials;
+ audienceId: unknown;
+ name: unknown;
+ description: unknown;
+ isPublic: boolean;
+}) {
+ const audience = tarventCommon.requireText({ value: audienceId, label: 'Audience' });
+ const groupName = tarventCommon.requireText({ value: name, label: 'Group name' });
+ const text = tarventCommon.trimmed(description);
+ tarventCommon.checkLength({ value: groupName, label: 'Group name', max: 100 });
+ tarventCommon.checkLength({ value: text, label: 'Group description', max: 255 });
+ return tarventTransport.field<Record<string, unknown>>({
+ auth,
+ query: 'mutation CreateAudienceGroup($input: CreateGroupInput!) { createAudienceGroup(input: $input) { id name description isPublic isDynamic } }',
+ variables: { input: { name: groupName, description: text ?? '', isDynamic: false, isPublic, audienceId: audience, criteria: null } },
+ name: 'createAudienceGroup',
+ });
+}
+
+async function findContact({
+ auth,
+ audienceId,
+ email,
+ contactId,
+ legacyIdInEmail = false,
+}: {
+ auth: TarventCredentials;
+ audienceId: unknown;
+ email: unknown;
+ contactId: unknown;
+ legacyIdInEmail?: boolean;
+}) {
+ const audience = tarventCommon.requireText({ value: audienceId, label: 'Audience' });
+ const rawEmail = tarventCommon.trimmed(email);
+ const rawId = tarventCommon.trimmed(contactId);
+ const emailIsLegacyId = legacyIdInEmail && rawId === undefined && rawEmail !== undefined && !rawEmail.includes('@');
+ const byEmail = emailIsLegacyId ? undefined : rawEmail;
+ const byId = emailIsLegacyId ? rawEmail : rawId;
+ if ((byEmail === undefined) === (byId === undefined)) {
+ throw new Error('Enter either Contact email or Contact ID (exactly one).');
+ }
+ const contact = await tarventClient.getContact({ auth, audienceId: audience, email: byEmail, contactId: byId });
+ return { found: contact !== null, contact };
+}
+
+async function listContacts({ auth, audienceId, groupId, limit, cursor }: { auth: TarventCredentials; audienceId: unknown; groupId: unknown; limit: unknown; cursor: unknown }) {
+ const audience = tarventCommon.requireText({ value: audienceId, label: 'Audience' });
+ const group = tarventCommon.trimmed(groupId);
+ return tarventClient.listPage({
+ auth,
+ operation: 'ListContacts',
+ field: 'contacts',
+ selection: tarventClient.fields.contact,
+ argDefs: ', $input: GetAllContactsInput!',
+ args: ', input: $input',
+ variables: { input: { audienceId: audience, ...(group ? { groupId: group } : {}) } },
+ first: tarventCommon.pageLimit(limit),
+ after: tarventCommon.trimmed(cursor),
+ });
+}
+
+async function findAudienceGroups({ auth, audienceId, name, limit, cursor }: { auth: TarventCredentials; audienceId: unknown; name: unknown; limit: unknown; cursor: unknown }) {
+ const audience = tarventCommon.requireText({ value: audienceId, label: 'Audience' });
+ const text = tarventCommon.trimmed(name);
+ return tarventClient.listPage({
+ auth,
+ operation: 'FindAudienceGroups',
+ field: 'audienceGroups',
+ selection: 'id name description isPublic',
+ argDefs: ', $audienceId: String!, $order: [AudienceGroupInfoSortInput!], $where: AudienceGroupInfoFilterInput',
+ args: ', audienceId: $audienceId, order: $order, where: $where',
+ variables: {
+ audienceId: audience,
+ order: [{ name: 'ASC' }],
+ where: { and: [{ isDynamic: { eq: false } }, ...(text ? [{ name: { contains: text } }] : [])] },
+ },
+ first: tarventCommon.pageLimit(limit),
+ after: tarventCommon.trimmed(cursor),
+ withTotalCount: true,
+ });
+}
+
+export const tarventOperations = {
+ setContactTags,
+ setGroupMembership,
+ setContactJourney,
+ setJourneyStatus,
+ deleteContact,
+ recordCustomEvent,
+ createAudienceGroup,
+ findContact,
+ listContacts,
+ findAudienceGroups,
+};
diff --git a/packages/pieces/community/tarvent/src/lib/common/transport.ts b/packages/pieces/community/tarvent/src/lib/common/transport.ts
new file mode 100644
index 00000000000..d34d08ddc22
--- /dev/null
+++ b/packages/pieces/community/tarvent/src/lib/common/transport.ts
@@ -0,0 +1,170 @@
+import { httpClient, HttpMethod } from '@activepieces/pieces-common';
+
+const BASE_URL = 'https://api.tarvent.com';
+const GRAPHQL_URL = `${BASE_URL}/graphql`;
+const UNAUTHORIZED_PATTERN = /not authori[sz]ed to access|not authenticated/i;
+const PERMISSION_CODE = '1070';
+const INVALID_CREDENTIALS = 'Invalid Tarvent API key or account ID. Check both values in the connection.';
+let verifiedTlsAgent: Promise<unknown> | undefined;
+
+export class TarventApiError extends Error {
+ constructor(
+ message: string,
+ public readonly code: string | undefined,
+ public readonly status: number | undefined,
+ public readonly responseBody: unknown,
+ public readonly unauthorized = false,
+ ) {
+ super(message);
+ this.name = 'TarventApiError';
+ }
+
+ get isUnauthorized(): boolean {
+ return this.unauthorized;
+ }
+}
+
+function verifiedTls(): Promise<unknown> {
+ verifiedTlsAgent ??= import('undici').then(({ Agent }) => new Agent({ connect: { rejectUnauthorized: true } }));
+ return verifiedTlsAgent;
+}
+
+function authHeaders({ accountId, apiKey }: TarventCredentials): Record<string, string> {
+ return {
+ 'x-api-key': String(apiKey ?? '').trim(),
+ account: String(accountId ?? '').trim(),
+ };
+}
+
+function graphqlErrors(body: unknown): { message: string; code?: string }[] {
+ if (typeof body !== 'object' || body === null) {
+ return [];
+ }
+ const errors: unknown = Reflect.get(body, 'errors');
+ if (!Array.isArray(errors)) {
+ return [];
+ }
+ return errors.map((error: unknown) => {
+ const message: unknown = typeof error === 'object' && error !== null ? Reflect.get(error, 'message') : undefined;
+ const extensions: unknown = typeof error === 'object' && error !== null ? Reflect.get(error, 'extensions') : undefined;
+ const code: unknown = typeof extensions === 'object' && extensions !== null ? Reflect.get(extensions, 'code') : undefined;
+ return {
+ message: typeof message === 'string' && message.length > 0 ? message : 'Unknown error',
+ code: typeof code === 'string' || typeof code === 'number' ? String(code) : undefined,
+ };
+ });
+}
+
+function toApiError({ status, body }: { status: number | undefined; body: unknown }): TarventApiError {
+ const errors = graphqlErrors(body);
+ const code = errors.find((error) => error.code !== undefined)?.code;
+ if (status === 401 || status === 403 || errors.some((e) => UNAUTHORIZED_PATTERN.test(e.message))) {
+ return new TarventApiError(INVALID_CREDENTIALS, code, status, body, true);
+ }
+ if (errors.some((e) => e.code === PERMISSION_CODE)) {
+ return new TarventApiError(
+ `The Tarvent API key does not have permission for this operation. In Tarvent, open Account -> API Keys and grant the key the permission it needs. Tarvent said: ${errors.map((e) => e.message).join('; ')}`,
+ code,
+ status,
+ body,
+ );
+ }
+ if (status === 429) {
+ return new TarventApiError('Tarvent rate limit reached (HTTP 429). Try again in a few seconds.', code, status, body);
+ }
+ if (errors.length > 0) {
+ const text = errors.map((e) => (e.code ? `${e.message} (code ${e.code})` : e.message)).join('; ');
+ return new TarventApiError(`Tarvent returned an error: ${text}`, code, status, body);
+ }
+ return new TarventApiError(`Tarvent request failed${status ? ` (HTTP ${status})` : ''}.`, code, status, body);
+}
+
+function readHttpFailure(error: unknown): { status: number; body: unknown } | null {
+ if (typeof error !== 'object' || error === null) {
+ return null;
+ }
+ const response: unknown = Reflect.get(error, 'response');
+ if (typeof response !== 'object' || response === null) {
+ return null;
+ }
+ const status: unknown = Reflect.get(response, 'status');
+ if (typeof status !== 'number') {
+ return null;
+ }
+ return { status, body: Reflect.get(response, 'body') };
+}
+
+async function graphql<T>({
+ auth,
+ query,
+ variables,
+}: {
+ auth: TarventCredentials;
+ query: string;
+ variables?: Record<string, unknown>;
+}): Promise<T> {
+ let body: GraphqlBody<T> | undefined;
+ try {
+ const response = await httpClient.sendRequest<GraphqlBody<T>>(
+ {
+ method: HttpMethod.POST,
+ url: GRAPHQL_URL,
+ headers: { ...authHeaders(auth), 'Content-Type': 'application/json', Accept: 'application/json' },
+ body: { query, variables: variables ?? {} },
+ redactBodyInErrors: true,
+ },
+ { dispatcher: await verifiedTls() },
+ );
+ body = response.body;
+ } catch (error) {
+ const failure = readHttpFailure(error);
+ if (!failure) {
+ throw error;
+ }
+ throw toApiError({ status: failure.status, body: failure.body });
+ }
+ if (graphqlErrors(body).length > 0) {
+ throw toApiError({ status: 200, body });
+ }
+ const data = typeof body === 'object' && body !== null ? body.data : undefined;
+ if (typeof data !== 'object' || data === null || data === undefined) {
+ throw new TarventApiError('Tarvent returned an empty response.', undefined, 200, body);
+ }
+ return data;
+}
+
+async function field<T>({
+ auth,
+ query,
+ variables,
+ name,
+}: {
+ auth: TarventCredentials;
+ query: string;
+ variables?: Record<string, unknown>;
+ name: string;
+}): Promise<T> {
+ const data = await graphql<Record<string, T | null | undefined>>({ auth, query, variables });
+ const value = data[name];
+ if (value === null || value === undefined) {
+ throw new TarventApiError(`Tarvent returned no result for ${name}.`, undefined, 200, data);
+ }
+ return value;
+}
+
+export const tarventTransport = {
+ graphql,
+ field,
+ authHeaders,
+ verifiedTls,
+ toApiError,
+ graphqlErrors,
+ baseUrl: BASE_URL,
+ graphqlUrl: GRAPHQL_URL,
+ invalidCredentialsMessage: INVALID_CREDENTIALS,
+ permissionCode: PERMISSION_CODE,
+};
+
+type GraphqlBody<T> = { data?: T | null; errors?: unknown };
+
+export type TarventCredentials = { accountId: string; apiKey: string };
diff --git a/packages/pieces/community/tarvent/src/lib/common/types.ts b/packages/pieces/community/tarvent/src/lib/common/types.ts
deleted file mode 100644
index 7a6ced72f47..00000000000
--- a/packages/pieces/community/tarvent/src/lib/common/types.ts
+++ /dev/null
@@ -1,371 +0,0 @@
-export type CreateWebhookResponse = {
- data: {
- createWebhook: {
- id: string;
- }
- }
-
-};
-
-export type ListAudiencesResponse = {
- data: {
- audiences: {
- nodes: {
- name: string;
- id: string;
- }[]
- }
- };
-};
-
-export type ListAudiencesAdvResponse = {
- data: {
- audiences: {
- nodes: {
- name: string;
- id: string;
- companyName: string;
- streetAddress: string;
- streetAddress2: string;
- addressLocality: string;
- addressRegion: string;
- postalCode: string;
- addressCountry: string;
- phone: string;
- website: string;
- totalContacts: number;
- totalActiveContacts: number;
- totalUnconfirmedContacts: number;
- totalUndeliverableContacts: number;
- totalUnsubscribedContacts: number;
- totalComplaintContacts: number;
- totalSuppressedContacts: number;
- tags: string[];
- customKeyDataField: { id: string, labelText: string };
- createdUtc: string;
- lastModifiedUtc: string;
- }[]
- }
- };
-};
-
-
-export type ListAudienceGroupResponse = {
- data: {
- audienceGroups: {
- nodes: {
- name: string;
- id: string;
- }[]
- }
- };
-};
-
-export type ListAudienceGroupAdvResponse = {
- data: {
- audienceGroups: {
- nodes: {
- name: string;
- id: string;
- description: string;
- isPublic: boolean;
- }[]
- }
- };
-};
-
-export type ListAudienceDataFieldsResponse = {
- data: {
- audienceDataFields: {
- nodes: {
- labelText: string;
- id: string;
- dataType: string;
- required: boolean;
- isSystem: boolean;
- defaultValue: string;
- mergeTag: string;
- isPrimaryKey: boolean;
- isGdprField: boolean;
- category: boolean;
- }[]
- }
- };
-};
-
-
-export type ListAudienceFormsResponse = {
- data: {
- forms: {
- nodes: {
- name: string;
- id: string;
- }[]
- }
- };
-};
-
-export type ListTagsResponse = {
- data: {
- tags: {
- nodes: {
- name: string;
- }[]
- }
- };
-};
-
-export type ListCampaignsResponse = {
- data: {
- campaigns: {
- nodes: {
- id: string;
- name: string;
- }[]
- }
- };
-};
-
-export type ListCampaignsAdvResponse = {
- data: {
- campaigns: {
- nodes: {
- id: string;
- name: string;
- tags: string[];
- audienceId: string;
- description: string;
- enableMvTesting: boolean;
- mvWinType: string;
- timeJumper: boolean;
- sendStatus: string;
- scheduledToSendUtc: string;
- createdUtc: string;
- modifiedUtc: string;
- }[]
- }
- };
-};
-
-export type ListCampaignLinksResponse = {
- data: {
- campaignLinks: {
- nodes: {
- id: string;
- url: string;
- track: boolean;
- entityName: string;
- entityType: string;
- formType: string;
- }[]
- }
- };
-};
-
-export type ListJourneysResponse = {
- data: {
- journeys: {
- nodes: {
- id: string;
- name: string;
- }[],
- pageInfo: {
- hasNextPage: boolean;
- endCursor: string | null;
- }
- }
- };
-};
-
-export type ListJourneysAdvResponse = {
- data: {
- journeys: {
- nodes: {
- id: string;
- name: string;
- tags: string[];
- audienceId: string;
- description: string;
- reEntryType: string;
- status: string;
- totalEmailNodes: string;
- totalNotificationEmailNodes: string;
- totalSiteNotificationNodes: string;
- totalSMSNodes: string;
- createdUtc: string;
- modifiedUtc: string;
- }[],
- }
- };
-};
-
-export type ListContactResponse = {
- data: {
- contact: {
- id: string;
- email: string;
- firstName: string;
- lastName: string;
- tags: string[];
- groups: { id: string, name: string }[];
- streetAddress: string;
- streetAddress2: string;
- addressLocality: string;
- addressRegion: string;
- postalCode: string;
- addressCountry: string;
- profileFields: { dataField: {id: string, labelText: string }, value: string }[];
- modifiedUtc: string;
- createdUtc: string;
- longitude: string;
- latitude: string;
- timeZone: string;
- language: string;
- sendFormat: string;
- status: string;
- optInUtc: string;
- confirmedUtc: string;
- optOUtUtc: string;
- }
- };
-};
-
-
-export type ListLandingPagesResponse = {
- data: {
- landingPages: {
- nodes: {
- id: string;
- name: string;
- }[]
- }
- };
-};
-
-export type ListSurveysResponse = {
- data: {
- surveys: {
- nodes: {
- id: string;
- name: string;
- }[]
- }
- };
-};
-
-export type ListTemplatesResponse = {
- data: {
- templates: {
- nodes: {
- id: string;
- name: string;
- }[]
- }
- };
-};
-
-export type ListTxGroupNamesResponse = {
- data: {
- transactionGroupNames: string[]
- };
-};
-
-export type ListCustomEventsResponse = {
- data: {
- customApiEvents: {
- nodes: {
- id: string;
- key: string;
- name: string;
- }[]
- }
- };
-};
-
-export type ListCustomEventsAdvResponse = {
- data: {
- customApiEvents: {
- nodes: {
- id: string;
- key: string;
- name: string;
- createdUtc: string;
- modifiedUtc: string;
- }[]
- }
- };
-};
-
-export type CreateContactResponse = {
- data: {
- createContact: {
- id: string;
- email: string;
- firstName: string;
- lastName: string;
- tags: string[];
- groups: { id: string, name: string }[];
- streetAddress: string;
- streetAddress2: string;
- addressLocality: string;
- addressRegion: string;
- postalCode: string;
- addressCountry: string;
- profileFields: { dataField: {id: string, labelText: string }, value: string }[];
- modifiedUtc: string;
- createdUtc: string;
- }
- }
-};
-
-export type CreateAudienceGroupResponse = {
- data: {
- createAudienceGroup: {
- id: string;
- name: string;
- description: string;
- isPublic: boolean;
- isDynamic: boolean;
- }
- }
-};
-
-export type CreateContactNoteResponse = {
- data: {
- createContactNote: {
- id: string;
- }
- }
-};
-
-export type CreateGroupContactResponse = {
- data: {
- createGroupContact: {
- id: string;
- }
- }
-};
-
-export type DeleteGroupContactResponse = {
- data: {
- deleteGroupContact: {
- id: string;
- }
- }
-};
-
-export type CreateSuppressionFilterResponse = {
- data: {
- createAccountSuppressionFilter: {
- id: string;
- localPart: string;
- domain: string;
- reason: string;
- }
- }
-};
-
-export enum ContactStatus {
- ACTIVE = 'ACTIVE',
- OPT_OUT = 'OPT_OUT'
-}
diff --git a/packages/pieces/community/tarvent/src/lib/common/webhook.ts b/packages/pieces/community/tarvent/src/lib/common/webhook.ts
new file mode 100644
index 00000000000..99c3a8dca22
--- /dev/null
+++ b/packages/pieces/community/tarvent/src/lib/common/webhook.ts
@@ -0,0 +1,234 @@
+import { DEDUPE_KEY_PROPERTY } from '@activepieces/pieces-framework';
+import { tarventClient, TarventWebhookEvent } from './client';
+import { TarventCredentials } from './transport';
+
+const MAX_SEEN_IDS = 200;
+const SEEN_SUFFIX = '_seen_event_ids';
+
+const BOUNCE_TYPES = ['BLOCK', 'BLOCK_CONTENT', 'BLOCK_SENDER', 'HARD', 'SOFT', 'SOFT_DNS', 'SOFT_IP', 'SOFT_SENDER_AUTH'];
+
+function entityOf(params: WebhookParams): string | null {
+ return params.entity && params.entity !== 'BOTH' ? String(params.entity) : null;
+}
+
+function webhookEvents({ type, params }: { type: TarventWebhookType; params: WebhookParams }): TarventWebhookEvent[] {
+ switch (type) {
+ case 'contactAdded':
+ return [{ entityType: null, eventType: 'CONTACT_ADDED' }];
+ case 'campaignSendFinished':
+ return [{ entityType: null, eventType: 'CAMPAIGN_SENT' }];
+ case 'contactBounced': {
+ const entityType = entityOf(params);
+ const types = !params.type || params.type === 'Any' ? BOUNCE_TYPES : [String(params.type)];
+ return types.map((eventType) => ({ entityType, eventType }));
+ }
+ case 'contactClicked':
+ return [{ entityType: entityOf(params), eventType: 'CLICK' }];
+ case 'contactReplied':
+ return [{ entityType: entityOf(params), eventType: 'REPLIED' }];
+ case 'contactOpened':
+ return [{ entityType: entityOf(params), eventType: 'OPEN' }];
+ case 'contactGroupUpdated':
+ return [{ entityType: null, eventType: params.action === 'Add' ? 'GROUP_ADDED' : 'GROUP_REMOVED' }];
+ case 'contactNoteAdded':
+ return [{ entityType: null, eventType: 'NOTE_ADDED' }];
+ case 'contactStatusUpdated':
+ if (!params.status || params.status === 'Any') {
+ return [
+ { entityType: null, eventType: 'SUBSCRIBED' },
+ { entityType: null, eventType: 'UNSUBSCRIBED' },
+ ];
+ }
+ return [{ entityType: null, eventType: params.status === 'ACTIVE' ? 'SUBSCRIBED' : 'UNSUBSCRIBED' }];
+ case 'contactTagUpdated':
+ return [{ entityType: null, eventType: params.action === 'Add' ? 'TAG_ADDED' : 'TAG_REMOVED' }];
+ case 'contactUnsubscribed':
+ return [{ entityType: null, eventType: 'UNSUBSCRIBED' }];
+ case 'contactUpdated':
+ return [{ entityType: null, eventType: 'FIELD_UPDATED' }];
+ case 'formSubmitted':
+ return [
+ { entityType: 'FORM', eventType: 'SUBMITTED_COMPLETE_FORM' },
+ { entityType: 'FORM', eventType: 'SUBMITTED_PARTIAL_FORM' },
+ ];
+ case 'landingPageCtaPerformed':
+ return [{ entityType: 'PAGE', eventType: 'CTA' }];
+ case 'surveySubmitted':
+ return [
+ { entityType: 'SURVEY', eventType: 'SUBMITTED_COMPLETE_FORM' },
+ { entityType: 'SURVEY', eventType: 'SUBMITTED_PARTIAL_FORM' },
+ ];
+ case 'transactionCreated':
+ return [{ entityType: null, eventType: 'CREATED' }];
+ case 'transactionSent':
+ return [{ entityType: null, eventType: 'PROCESSED' }];
+ }
+}
+
+function campaignCondition({ type, params }: { type: TarventWebhookType; params: WebhookParams }): WebhookCondition[] {
+ if (type !== 'contactClicked' && type !== 'contactOpened') {
+ return [];
+ }
+ const verb = type === 'contactClicked' ? 'Clicked' : 'Opened';
+ const scope = typeof params.campaignScope === 'object' && params.campaignScope !== null ? params.campaignScope : {};
+ switch (params.campaignType) {
+ case 'Any':
+ return [{ dataFieldId: null, fieldName: `Campaign.AnyLast5.${verb}`, operator: 'IF_TRUE', value: null }];
+ case 'All':
+ return [{ dataFieldId: null, fieldName: `Campaign.AllLast5.${verb}`, operator: 'IF_TRUE', value: null }];
+ case 'AnyX': {
+ const range = Reflect.get(scope, 'campaignRange');
+ const period = Reflect.get(scope, 'campaignPeriod');
+ if (range === undefined || range === null || range === '' || !period) {
+ throw new Error('Set the campaign scope range and period for "Any campaigns within last...".');
+ }
+ return [{ dataFieldId: null, fieldName: `Campaign.AnyWithinLast.${verb}`, operator: 'IF_TRUE', value: `${range}${period}` }];
+ }
+ case 'Specific': {
+ if (!params.campaignId) {
+ throw new Error('Select a campaign when the campaign type is "A specific campaign".');
+ }
+ const link = type === 'contactClicked' && params.linkId ? `.${params.linkId}` : '';
+ return [{ dataFieldId: null, fieldName: `Campaign.${params.campaignId}.${verb}${link}`, operator: 'IF_TRUE', value: null }];
+ }
+ default:
+ return [];
+ }
+}
+
+function webhookFilter({ type, params }: { type: TarventWebhookType; params: WebhookParams }): Record<string, unknown> | null {
+ const conditions: WebhookCondition[] = [
+ ...(params.audienceId ? [{ dataFieldId: null, fieldName: 'audience', operator: 'IF_TRUE', value: String(params.audienceId) }] : []),
+ ...(params.groupId ? [{ dataFieldId: null, fieldName: 'groups', operator: 'CONTAINS', value: String(params.groupId) }] : []),
+ ...(params.tagId ? [{ dataFieldId: null, fieldName: 'tags', operator: 'CONTAINS', value: String(params.tagId) }] : []),
+ ...campaignCondition({ type, params }),
+ ...(type === 'contactStatusUpdated' && params.status && params.status !== 'Any'
+ ? [{ dataFieldId: null, fieldName: 'Status', operator: 'EQUAL', value: String(params.status) }]
+ : []),
+ ...(type === 'formSubmitted' && params.formId ? [{ dataFieldId: null, fieldName: `Form.${params.formId}.Submitted`, operator: 'IF_TRUE', value: null }] : []),
+ ...(type === 'landingPageCtaPerformed' && params.landingPageId ? [{ dataFieldId: null, fieldName: `Page.${params.landingPageId}.CTA`, operator: 'IF_TRUE', value: null }] : []),
+ ...(type === 'surveySubmitted' && params.surveyId ? [{ dataFieldId: null, fieldName: `Survey.${params.surveyId}.Submitted`, operator: 'IF_TRUE', value: null }] : []),
+ ];
+ return conditions.length === 0 ? null : { operator: 'AND', conditions, conditionGroups: [] };
+}
+
+function storedWebhookId(stored: unknown): string | undefined {
+ if (typeof stored === 'string') {
+ return stored.length > 0 ? stored : undefined;
+ }
+ if (typeof stored !== 'object' || stored === null) {
+ return undefined;
+ }
+ const direct: unknown = Reflect.get(stored, 'id');
+ if (typeof direct === 'string') {
+ return direct;
+ }
+ const data: unknown = Reflect.get(stored, 'data');
+ const created: unknown = typeof data === 'object' && data !== null ? Reflect.get(data, 'createWebhook') : undefined;
+ const legacyId: unknown = typeof created === 'object' && created !== null ? Reflect.get(created, 'id') : undefined;
+ return typeof legacyId === 'string' ? legacyId : undefined;
+}
+
+function rememberEvent({ seen, eventId }: { seen: unknown; eventId: string }): { duplicate: boolean; seen: string[] } {
+ const ids = Array.isArray(seen) ? seen.filter((id): id is string => typeof id === 'string') : [];
+ if (ids.includes(eventId)) {
+ return { duplicate: true, seen: ids };
+ }
+ return { duplicate: false, seen: [...ids, eventId].slice(-MAX_SEEN_IDS) };
+}
+
+function handlers({ type, storeKey }: { type: TarventWebhookType; storeKey: string }) {
+ return {
+ async onEnable(context: EnableContext): Promise<void> {
+ const params: WebhookParams = context.propsValue ?? {};
+ const created = await tarventClient.createWebhook({
+ auth: context.auth.props,
+ name: `ActivePieces-${Date.now()}`,
+ callBackUrl: context.webhookUrl,
+ events: webhookEvents({ type, params }),
+ filter: webhookFilter({ type, params }),
+ dataSettings: params.include ? String(params.include) : 'BASIC',
+ });
+ try {
+ await context.store.put(storeKey, { id: created.id });
+ } catch (error) {
+ await tarventClient.deleteWebhook({ auth: context.auth.props, id: created.id }).catch(() => undefined);
+ throw error;
+ }
+ },
+ async onDisable(context: DisableContext): Promise<void> {
+ const webhookId = storedWebhookId(await context.store.get<unknown>(storeKey));
+ if (webhookId) {
+ await tarventClient.deleteWebhook({ auth: context.auth.props, id: webhookId });
+ }
+ await context.store.delete(storeKey);
+ await context.store.delete(`${storeKey}${SEEN_SUFFIX}`);
+ },
+ async run(context: RunContext): Promise<unknown[]> {
+ const body = context.payload.body;
+ if (typeof body !== 'object' || body === null) {
+ return [];
+ }
+ const eventId: unknown = Reflect.get(body, 'id');
+ if (typeof eventId === 'string' && eventId.length > 0) {
+ const remembered = rememberEvent({ seen: await context.store.get<unknown>(`${storeKey}${SEEN_SUFFIX}`), eventId });
+ if (remembered.duplicate) {
+ return [];
+ }
+ await context.store.put(`${storeKey}${SEEN_SUFFIX}`, remembered.seen);
+ return [{ ...body, [DEDUPE_KEY_PROPERTY]: eventId }];
+ }
+ return [body];
+ },
+ };
+}
+
+export const tarventWebhook = { webhookEvents, webhookFilter, storedWebhookId, rememberEvent, handlers, MAX_SEEN_IDS };
+
+export type TarventWebhookType =
+ | 'contactAdded'
+ | 'campaignSendFinished'
+ | 'contactBounced'
+ | 'contactClicked'
+ | 'contactReplied'
+ | 'contactOpened'
+ | 'contactGroupUpdated'
+ | 'contactNoteAdded'
+ | 'contactStatusUpdated'
+ | 'contactTagUpdated'
+ | 'contactUnsubscribed'
+ | 'contactUpdated'
+ | 'formSubmitted'
+ | 'landingPageCtaPerformed'
+ | 'surveySubmitted'
+ | 'transactionCreated'
+ | 'transactionSent';
+
+type WebhookParams = {
+ [K in 'entity' | 'type' | 'action' | 'status' | 'campaignType' | 'campaignScope' | 'campaignId' | 'linkId' | 'audienceId' | 'groupId' | 'tagId' | 'formId' | 'landingPageId' | 'surveyId' | 'include']?: unknown;
+};
+
+type WebhookCondition = { dataFieldId: null; fieldName: string; operator: string; value: string | null };
+
+type WebhookStore = {
+ put<T>(key: string, value: T): Promise<T>;
+ get<T>(key: string): Promise<T | null>;
+ delete(key: string): Promise<void>;
+};
+
+type EnableContext = {
+ auth: { props: TarventCredentials };
+ propsValue?: Record<string, unknown>;
+ webhookUrl: string;
+ store: WebhookStore;
+};
+
+type DisableContext = {
+ auth: { props: TarventCredentials };
+ store: WebhookStore;
+};
+
+type RunContext = {
+ payload: { body: unknown };
+ store: WebhookStore;
+};
diff --git a/packages/pieces/community/tarvent/src/lib/output-schemas.ts b/packages/pieces/community/tarvent/src/lib/output-schemas.ts
new file mode 100644
index 00000000000..309a82dc5c3
--- /dev/null
+++ b/packages/pieces/community/tarvent/src/lib/output-schemas.ts
@@ -0,0 +1,502 @@
+import { OutputSchema } from '@activepieces/pieces-framework';
+
+type Field = OutputSchema['fields'][number];
+
+const contactFields: Field[] = [
+ { key: 'id', label: 'Contact ID' },
+ { key: 'email', label: 'Email', format: 'email' },
+ { key: 'firstName', label: 'First Name' },
+ { key: 'lastName', label: 'Last Name' },
+ { key: 'status', label: 'Status' },
+ { key: 'tags', label: 'Tags' },
+ {
+ key: 'groups',
+ label: 'Groups',
+ labelKey: 'name',
+ listItems: [
+ { key: 'id', label: 'Group ID' },
+ { key: 'name', label: 'Group Name' },
+ ],
+ },
+ { key: 'rating', label: 'Rating', format: 'number' },
+ { key: 'streetAddress', label: 'Street Address' },
+ { key: 'streetAddress2', label: 'Street Address 2' },
+ { key: 'addressLocality', label: 'City' },
+ { key: 'addressRegion', label: 'State / Region' },
+ { key: 'postalCode', label: 'Postal Code' },
+ { key: 'addressCountry', label: 'Country' },
+ { key: 'timeZone', label: 'Time Zone' },
+ { key: 'language', label: 'Language' },
+ { key: 'sendFormat', label: 'Send Format' },
+ { key: 'optInUtc', label: 'Opted In At', format: 'datetime' },
+ { key: 'confirmedUtc', label: 'Confirmed At', format: 'datetime' },
+ { key: 'optOutUtc', label: 'Opted Out At', format: 'datetime' },
+ {
+ key: 'profileFields',
+ label: 'Profile Fields',
+ listItems: [
+ { key: 'id', label: 'Profile Field ID' },
+ {
+ key: 'dataField',
+ label: 'Data Field',
+ children: [
+ { key: 'id', label: 'Data Field ID' },
+ { key: 'labelText', label: 'Label' },
+ ],
+ },
+ { key: 'value', label: 'Value' },
+ ],
+ },
+ { key: 'createdUtc', label: 'Created At', format: 'datetime' },
+ { key: 'modifiedUtc', label: 'Modified At', format: 'datetime' },
+];
+
+const pageFields: Field[] = [
+ { key: 'count', label: 'Count', format: 'number' },
+ { key: 'hasMore', label: 'Has More', format: 'boolean' },
+ { key: 'nextCursor', label: 'Next Cursor' },
+];
+
+const countedPageFields: Field[] = [...pageFields, { key: 'totalCount', label: 'Total Count', format: 'number' }];
+
+const webhookContactFields: Field[] = [
+ { key: 'id', label: 'Contact ID' },
+ { key: 'key', label: 'Contact Key' },
+ { key: 'email', label: 'Email', format: 'email' },
+ { key: 'status', label: 'Status Code' },
+ { key: 'rating', label: 'Rating' },
+ { key: 'firstname', label: 'First Name' },
+ { key: 'lastname', label: 'Last Name' },
+ { key: 'streetaddress', label: 'Street Address' },
+ { key: 'streetaddress2', label: 'Street Address 2' },
+ { key: 'addresslocality', label: 'City' },
+ { key: 'addressregion', label: 'State / Region' },
+ { key: 'postalcode', label: 'Postal Code' },
+ { key: 'addresscountry', label: 'Country' },
+ { key: 'timezone', label: 'Time Zone' },
+ { key: 'language', label: 'Language' },
+ { key: 'sendformat', label: 'Send Format Code' },
+ { key: 'optinsource', label: 'Opt-in Source Code' },
+ { key: 'optinutc', label: 'Opted In At (UTC, MM/DD/YYYY)' },
+ { key: 'confirmedutc', label: 'Confirmed At (UTC, MM/DD/YYYY)' },
+ { key: 'createdutc', label: 'Created At (UTC, MM/DD/YYYY)' },
+ { key: 'modifiedutc', label: 'Modified At (UTC, MM/DD/YYYY)' },
+ { key: 'groups', label: 'Group IDs (JSON text)' },
+ { key: 'tags', label: 'Tags (JSON text)' },
+];
+
+const contactPayloadField: Field = { key: 'contact', label: 'Contact', children: webhookContactFields };
+
+function webhookEvent({ payload }: { payload: Field[] }): OutputSchema {
+ return {
+ fields: [
+ { key: 'id', label: 'Event ID' },
+ { key: 'dateUtc', label: 'Event Time', format: 'datetime' },
+ { key: 'accountId', label: 'Account ID' },
+ { key: 'eventType', label: 'Event Type', format: 'number' },
+ {
+ key: 'initiator',
+ label: 'Initiator',
+ children: [
+ { key: 'source', label: 'Source Code' },
+ { key: 'ip', label: 'IP' },
+ { key: 'device', label: 'Device' },
+ { key: 'software', label: 'Software' },
+ { key: 'os', label: 'Operating System' },
+ { key: 'referrer', label: 'Referrer', format: 'url' },
+ ],
+ },
+ { key: 'payload', label: 'Payload', children: [...payload, contactPayloadField] },
+ ],
+ };
+}
+
+export const tarventOutputSchemas = {
+ contact: { fields: contactFields },
+ findContact: {
+ fields: [
+ { key: 'found', label: 'Found', format: 'boolean' },
+ { key: 'contact', label: 'Contact', children: contactFields },
+ ],
+ },
+ contactPage: {
+ fields: [{ key: 'items', label: 'Contacts', labelKey: 'email', listItems: contactFields }, ...pageFields],
+ },
+ deleteContact: {
+ fields: [
+ { key: 'success', label: 'Success', format: 'boolean' },
+ { key: 'contactId', label: 'Contact ID' },
+ { key: 'audienceId', label: 'Audience ID' },
+ ],
+ },
+ contactTags: {
+ fields: [
+ { key: 'success', label: 'Success', format: 'boolean' },
+ { key: 'contactId', label: 'Contact ID' },
+ { key: 'action', label: 'Action' },
+ { key: 'tags', label: 'Tags' },
+ ],
+ },
+ contactGroup: {
+ fields: [
+ { key: 'success', label: 'Success', format: 'boolean' },
+ { key: 'contactId', label: 'Contact ID' },
+ { key: 'groupId', label: 'Group ID' },
+ { key: 'audienceId', label: 'Audience ID' },
+ { key: 'action', label: 'Action' },
+ ],
+ },
+ contactNoteCreated: {
+ fields: [
+ { key: 'success', label: 'Success', format: 'boolean' },
+ { key: 'contactId', label: 'Contact ID' },
+ { key: 'message', label: 'Note' },
+ ],
+ },
+ contactNotePage: {
+ fields: [
+ {
+ key: 'items',
+ label: 'Notes',
+ labelKey: 'message',
+ listItems: [
+ { key: 'id', label: 'Note ID' },
+ { key: 'message', label: 'Note' },
+ { key: 'status', label: 'Status' },
+ { key: 'createdBy', label: 'Created By' },
+ { key: 'createdUtc', label: 'Created At', format: 'datetime' },
+ { key: 'modifiedUtc', label: 'Modified At', format: 'datetime' },
+ ],
+ },
+ ...pageFields,
+ ],
+ },
+ contactStatus: {
+ fields: [
+ { key: 'success', label: 'Success', format: 'boolean' },
+ { key: 'contactId', label: 'Contact ID' },
+ { key: 'status', label: 'Status' },
+ ],
+ },
+ contactJourney: {
+ fields: [
+ { key: 'success', label: 'Success', format: 'boolean' },
+ { key: 'contactId', label: 'Contact ID' },
+ { key: 'journeyId', label: 'Journey ID' },
+ { key: 'action', label: 'Action' },
+ ],
+ },
+ journeyStatus: {
+ fields: [
+ { key: 'success', label: 'Success', format: 'boolean' },
+ { key: 'journeyId', label: 'Journey ID' },
+ { key: 'action', label: 'Action' },
+ ],
+ },
+ customEventGenerated: {
+ fields: [
+ { key: 'success', label: 'Success', format: 'boolean' },
+ { key: 'contactId', label: 'Contact ID' },
+ { key: 'eventKey', label: 'Event Key' },
+ ],
+ },
+ audienceGroup: {
+ fields: [
+ { key: 'id', label: 'Group ID' },
+ { key: 'name', label: 'Name' },
+ { key: 'description', label: 'Description' },
+ { key: 'isPublic', label: 'Public', format: 'boolean' },
+ { key: 'isDynamic', label: 'Dynamic', format: 'boolean' },
+ ],
+ },
+ suppressionFilter: {
+ fields: [
+ { key: 'id', label: 'Suppression Filter ID' },
+ { key: 'localPart', label: 'Local Part' },
+ { key: 'domain', label: 'Domain' },
+ { key: 'reason', label: 'Reason' },
+ { key: 'createdUtc', label: 'Created At', format: 'datetime' },
+ ],
+ },
+ suppressionRemoved: {
+ fields: [
+ { key: 'removed', label: 'Filters Removed', format: 'number' },
+ { key: 'filterIds', label: 'Removed Filter IDs' },
+ ],
+ },
+ transactionSent: {
+ fields: [
+ { key: 'requestId', label: 'Request ID' },
+ { key: 'transactionId', label: 'Transaction ID' },
+ {
+ key: 'recipients',
+ label: 'Recipients',
+ labelKey: 'emailAddress',
+ listItems: [
+ { key: 'emailAddress', label: 'Email', format: 'email' },
+ { key: 'transactionId', label: 'Transaction ID' },
+ { key: 'sent', label: 'Accepted', format: 'boolean' },
+ { key: 'errorCode', label: 'Error Code' },
+ { key: 'errorMsg', label: 'Error Message' },
+ ],
+ },
+ ],
+ },
+ transaction: {
+ fields: [
+ { key: 'found', label: 'Found', format: 'boolean' },
+ { key: 'transactionId', label: 'Transaction ID' },
+ {
+ key: 'items',
+ label: 'Recipients',
+ labelKey: 'recipient',
+ listItems: [
+ { key: 'id', label: 'Transaction ID' },
+ { key: 'requestId', label: 'Request ID' },
+ { key: 'status', label: 'Status' },
+ { key: 'recipient', label: 'Recipient', format: 'email' },
+ { key: 'recipientName', label: 'Recipient Name' },
+ { key: 'recipientType', label: 'Recipient Type' },
+ { key: 'from', label: 'From', format: 'email' },
+ { key: 'fromName', label: 'From Name' },
+ { key: 'replyTo', label: 'Reply To', format: 'email' },
+ { key: 'subject', label: 'Subject' },
+ { key: 'groupName', label: 'Group Name' },
+ { key: 'tags', label: 'Tags' },
+ { key: 'error', label: 'Error' },
+ { key: 'bounceCategory', label: 'Bounce Category' },
+ { key: 'openCount', label: 'Opens', format: 'number' },
+ { key: 'clickCount', label: 'Clicks', format: 'number' },
+ { key: 'sendCount', label: 'Send Count', format: 'number' },
+ { key: 'complaint', label: 'Spam Complaint', format: 'boolean' },
+ { key: 'unsubscribe', label: 'Unsubscribed', format: 'boolean' },
+ { key: 'contactId', label: 'Contact ID' },
+ { key: 'sendAtUtc', label: 'Send At', format: 'datetime' },
+ { key: 'processedUtc', label: 'Processed At', format: 'datetime' },
+ { key: 'createdUtc', label: 'Created At', format: 'datetime' },
+ ],
+ },
+ ],
+ },
+ campaignSent: {
+ fields: [
+ { key: 'success', label: 'Success', format: 'boolean' },
+ { key: 'campaignId', label: 'Campaign ID' },
+ { key: 'sendUtc', label: 'Send Time', format: 'datetime' },
+ ],
+ },
+ campaignStats: {
+ fields: [
+ { key: 'campaignId', label: 'Campaign ID' },
+ { key: 'totalSent', label: 'Sent', format: 'number' },
+ { key: 'totalDelivered', label: 'Delivered', format: 'number' },
+ { key: 'totalDeliveredPct', label: 'Delivered %', format: 'number' },
+ { key: 'totalOpens', label: 'Opens', format: 'number' },
+ { key: 'uniqueOpens', label: 'Unique Opens', format: 'number' },
+ { key: 'uniqueOpensPct', label: 'Unique Opens %', format: 'number' },
+ { key: 'totalClicks', label: 'Clicks', format: 'number' },
+ { key: 'uniqueClicks', label: 'Unique Clicks', format: 'number' },
+ { key: 'uniqueClicksPct', label: 'Unique Clicks %', format: 'number' },
+ { key: 'clickToOpenPct', label: 'Click-to-Open %', format: 'number' },
+ { key: 'totalReplies', label: 'Replies', format: 'number' },
+ { key: 'uniqueReplies', label: 'Unique Replies', format: 'number' },
+ { key: 'uniqueRepliesPct', label: 'Unique Replies %', format: 'number' },
+ { key: 'totalBounce', label: 'Bounces', format: 'number' },
+ { key: 'totalBouncePct', label: 'Bounces %', format: 'number' },
+ { key: 'uniqueHardBounce', label: 'Hard Bounces', format: 'number' },
+ { key: 'uniqueHardBouncePct', label: 'Hard Bounces %', format: 'number' },
+ { key: 'uniqueSoftBounce', label: 'Soft Bounces', format: 'number' },
+ { key: 'uniqueSoftBouncePct', label: 'Soft Bounces %', format: 'number' },
+ { key: 'uniqueOptOut', label: 'Opt-outs', format: 'number' },
+ { key: 'uniqueOptOutPct', label: 'Opt-outs %', format: 'number' },
+ { key: 'uniqueSpam', label: 'Spam Complaints', format: 'number' },
+ { key: 'uniqueSpamPct', label: 'Spam Complaints %', format: 'number' },
+ { key: 'uniqueSuppressed', label: 'Suppressed', format: 'number' },
+ { key: 'engagementScore', label: 'Engagement Score', format: 'number' },
+ { key: 'engagementScoreAvg', label: 'Average Engagement Score', format: 'number' },
+ { key: 'senderReputation', label: 'Sender Reputation', format: 'number' },
+ { key: 'sendDomain', label: 'Send Domain' },
+ ],
+ },
+ audiencePage: {
+ fields: [
+ {
+ key: 'items',
+ label: 'Audiences',
+ labelKey: 'name',
+ listItems: [
+ { key: 'id', label: 'Audience ID' },
+ { key: 'name', label: 'Name' },
+ { key: 'companyName', label: 'Company Name' },
+ { key: 'streetAddress', label: 'Street Address' },
+ { key: 'streetAddress2', label: 'Street Address 2' },
+ { key: 'addressLocality', label: 'City' },
+ { key: 'addressRegion', label: 'State / Region' },
+ { key: 'postalCode', label: 'Postal Code' },
+ { key: 'addressCountry', label: 'Country' },
+ { key: 'phone', label: 'Phone' },
+ { key: 'website', label: 'Website', format: 'url' },
+ { key: 'totalContacts', label: 'Total Contacts', format: 'number' },
+ { key: 'totalActiveContacts', label: 'Active Contacts', format: 'number' },
+ { key: 'totalUnconfirmedContacts', label: 'Unconfirmed Contacts', format: 'number' },
+ { key: 'totalUndeliverableContacts', label: 'Undeliverable Contacts', format: 'number' },
+ { key: 'totalUnsubscribedContacts', label: 'Unsubscribed Contacts', format: 'number' },
+ { key: 'totalComplaintContacts', label: 'Complaint Contacts', format: 'number' },
+ { key: 'totalSuppressedContacts', label: 'Suppressed Contacts', format: 'number' },
+ { key: 'tags', label: 'Tags' },
+ {
+ key: 'customKeyDataField',
+ label: 'Custom Key Field',
+ children: [
+ { key: 'id', label: 'Data Field ID' },
+ { key: 'labelText', label: 'Label' },
+ ],
+ },
+ { key: 'createdUtc', label: 'Created At', format: 'datetime' },
+ { key: 'lastModifiedUtc', label: 'Modified At', format: 'datetime' },
+ ],
+ },
+ ...countedPageFields,
+ ],
+ },
+ audienceGroupPage: {
+ fields: [
+ {
+ key: 'items',
+ label: 'Groups',
+ labelKey: 'name',
+ listItems: [
+ { key: 'id', label: 'Group ID' },
+ { key: 'name', label: 'Name' },
+ { key: 'description', label: 'Description' },
+ { key: 'isPublic', label: 'Public', format: 'boolean' },
+ ],
+ },
+ ...countedPageFields,
+ ],
+ },
+ campaignPage: {
+ fields: [
+ {
+ key: 'items',
+ label: 'Campaigns',
+ labelKey: 'name',
+ listItems: [
+ { key: 'id', label: 'Campaign ID' },
+ { key: 'name', label: 'Name' },
+ { key: 'description', label: 'Description' },
+ { key: 'audienceId', label: 'Audience ID' },
+ { key: 'sendStatus', label: 'Send Status' },
+ { key: 'tags', label: 'Tags' },
+ { key: 'mvWinType', label: 'Multivariate Win Type' },
+ { key: 'timeJumper', label: 'Time Jumper', format: 'boolean' },
+ { key: 'scheduledToSendUtc', label: 'Scheduled To Send At', format: 'datetime' },
+ { key: 'createdUtc', label: 'Created At', format: 'datetime' },
+ { key: 'modifiedUtc', label: 'Modified At', format: 'datetime' },
+ ],
+ },
+ ...countedPageFields,
+ ],
+ },
+ journeyPage: {
+ fields: [
+ {
+ key: 'items',
+ label: 'Journeys',
+ labelKey: 'name',
+ listItems: [
+ { key: 'id', label: 'Journey ID' },
+ { key: 'name', label: 'Name' },
+ { key: 'description', label: 'Description' },
+ { key: 'audienceId', label: 'Audience ID' },
+ { key: 'status', label: 'Status' },
+ { key: 'reEntryType', label: 'Re-entry Type' },
+ { key: 'tags', label: 'Tags' },
+ { key: 'totalEmailNodes', label: 'Email Steps', format: 'number' },
+ { key: 'totalNotificationEmailNodes', label: 'Notification Email Steps', format: 'number' },
+ { key: 'totalSiteNotificationNodes', label: 'Site Notification Steps', format: 'number' },
+ { key: 'totalSMSNodes', label: 'SMS Steps', format: 'number' },
+ { key: 'createdUtc', label: 'Created At', format: 'datetime' },
+ { key: 'modifiedUtc', label: 'Modified At', format: 'datetime' },
+ ],
+ },
+ ...pageFields,
+ ],
+ },
+ customEventPage: {
+ fields: [
+ {
+ key: 'items',
+ label: 'Custom Events',
+ labelKey: 'name',
+ listItems: [
+ { key: 'id', label: 'Custom Event ID' },
+ { key: 'key', label: 'Event Key' },
+ { key: 'name', label: 'Name' },
+ { key: 'description', label: 'Description' },
+ { key: 'createdUtc', label: 'Created At', format: 'datetime' },
+ { key: 'modifiedUtc', label: 'Modified At', format: 'datetime' },
+ ],
+ },
+ ...pageFields,
+ ],
+ },
+ tagPage: {
+ fields: [
+ {
+ key: 'items',
+ label: 'Tags',
+ labelKey: 'name',
+ listItems: [
+ { key: 'name', label: 'Tag' },
+ { key: 'count', label: 'Times Used', format: 'number' },
+ { key: 'type', label: 'Entity Type' },
+ { key: 'isSystem', label: 'System Tag', format: 'boolean' },
+ ],
+ },
+ ...pageFields,
+ ],
+ },
+ customApiCall: {
+ fields: [
+ { key: 'status', label: 'Status Code', format: 'number' },
+ { key: 'headers', label: 'Headers', dynamicKey: true },
+ { key: 'body', label: 'Body' },
+ ],
+ },
+ contactEvent: webhookEvent({ payload: [{ key: 'audienceId', label: 'Audience ID' }] }),
+ emailEvent: webhookEvent({ payload: [{ key: 'emailId', label: 'Email ID' }] }),
+ clickEvent: webhookEvent({
+ payload: [
+ { key: 'emailId', label: 'Email ID' },
+ {
+ key: 'link',
+ label: 'Link',
+ children: [
+ { key: 'id', label: 'Link ID' },
+ { key: 'url', label: 'URL', format: 'url' },
+ ],
+ },
+ ],
+ }),
+ bounceEvent: webhookEvent({
+ payload: [
+ { key: 'emailId', label: 'Email ID' },
+ {
+ key: 'bounce',
+ label: 'Bounce',
+ children: [
+ { key: 'type', label: 'Bounce Type', format: 'number' },
+ { key: 'response', label: 'Server Response' },
+ ],
+ },
+ ],
+ }),
+ formEvent: webhookEvent({
+ payload: [
+ { key: 'formId', label: 'Form ID' },
+ { key: 'questionData', label: 'Answers' },
+ ],
+ }),
+ pageEvent: webhookEvent({ payload: [{ key: 'pageId', label: 'Page ID' }] }),
+} satisfies Record<string, OutputSchema>;
diff --git a/packages/pieces/community/tarvent/src/lib/triggers/campaign-send-finished.ts b/packages/pieces/community/tarvent/src/lib/triggers/campaign-send-finished.ts
index 3fa10c1ceb3..2644f565856 100644
--- a/packages/pieces/community/tarvent/src/lib/triggers/campaign-send-finished.ts
+++ b/packages/pieces/community/tarvent/src/lib/triggers/campaign-send-finished.ts
@@ -1,7 +1,8 @@
import { TriggerStrategy, createTrigger } from '@activepieces/pieces-framework';
import { tarventAuth } from '../auth';
-import { makeClient, tarventCommon } from '../common';
-import { CreateWebhookResponse } from '../common/types';
+import { tarventCommon } from '../common';
+import { tarventWebhook } from '../common/webhook';
+import { tarventOutputSchemas } from '../output-schemas';
export const campaignSendFinishedTrigger = createTrigger({
auth: tarventAuth,
@@ -13,29 +14,14 @@ export const campaignSendFinishedTrigger = createTrigger({
description: 'Fires once per contact each time a campaign is delivered to them, optionally scoped to a specific audience, group, or tag. High volume: it fires for every recipient of the campaign.',
},
type: TriggerStrategy.WEBHOOK,
+ outputSchema: tarventOutputSchemas.contactEvent,
props: {
include: tarventCommon.include,
audienceId: tarventCommon.audienceId(false, 'If specified, the trigger will only fire if contact is in the selected audience.'),
groupId: tarventCommon.audienceGroupId(false, 'If specified, the trigger will only fire if contact is in the selected group.'),
tagId: tarventCommon.tagId(false, 'If specified, the trigger will only fire if contact has the selected tag.')
},
- async onEnable(context) {
- const client = makeClient(context.auth);
- const res = await client.createWebhook(context, 'campaignSendFinished');
- await context.store.put<CreateWebhookResponse>('tarvent_campaign_send_finished', res);
- },
- async run(context) {
- return [context.payload.body];
- },
- async onDisable(context) {
- const webhook = await context.store.get<CreateWebhookResponse>(
- 'tarvent_campaign_send_finished',
- );
- if (webhook != null) {
- const client = makeClient(context.auth);
- await client.deleteWebhook(webhook.data.createWebhook.id);
- }
- },
+ ...tarventWebhook.handlers({ type: 'campaignSendFinished', storeKey: 'tarvent_campaign_send_finished' }),
sampleData: {
id: '000000000000000000',
dateUtc: '2022-09-27T17:37:26.482913Z',
@@ -54,38 +40,33 @@ export const campaignSendFinishedTrigger = createTrigger({
payload: {
audienceId: '000000000000000000',
contact: {
- id: '000000000000000000',
- email: '[email protected]',
- status: 1,
- rating: 3,
- firstName: 'Kayla',
- lastName: 'Johnson',
- streetAddress: '165 Caprice Court',
- streetAddress2: 'Suite A',
- addressLocality: 'Castle Rock',
- addressRegion: 'Colorado',
- postalCode: '80109',
- addressCountry: 'United States',
- latitude: 39.38363820960583,
- longitude: -104.86229586128452,
- timeZone: 'Mountain Standard Time',
- language: 'en',
- sendFormat: 1,
- optInUtc: '2022-08-28T17:37:26.6236851Z',
- optInSource: 6,
- optInIp: '0.0.0.0',
- confirmedUtc: '2022-08-29T17:37:26.6236972Z',
- confirmedIp: '0.0.0.0',
- optOutUtc: null,
- optOutSource: null,
- optOutIp: null,
- optOutReason: '',
- groups: ['359949389556096655', '359949389556097786'],
- tags: ['TarventTest', 'TarventTest2', 'TarventTest3'],
- profileFields: null,
- createdUtc: '2022-08-28T17:37:26.6237782Z',
- modifiedUtc: '2022-09-17T17:37:26.6237797Z',
+ id: '1594408175877314400',
+ email: '[email protected]',
+ status: '1',
+ rating: '',
+ firstname: 'ApTest',
+ lastname: 'Example',
+ streetaddress: '',
+ streetaddress2: '',
+ addresslocality: '',
+ addressregion: '',
+ postalcode: '',
+ addresscountry: '',
+ longitude: '',
+ latitude: '',
+ language: '',
+ timezone: '',
+ sendformat: '1',
+ optinsource: '6',
+ optinip: '',
+ optinutc: '10/21/2026 20:44:25',
+ confirmedutc: '',
+ confirmedip: '',
+ createdutc: '10/21/2026 20:44:25',
+ modifiedutc: '10/21/2026 20:44:25',
+ groups: '[]',
+ tags: '[]',
},
},
}
diff --git a/packages/pieces/community/tarvent/src/lib/triggers/contact-added.ts b/packages/pieces/community/tarvent/src/lib/triggers/contact-added.ts
index fa1157704dd..fb0be22f9c0 100644
--- a/packages/pieces/community/tarvent/src/lib/triggers/contact-added.ts
+++ b/packages/pieces/community/tarvent/src/lib/triggers/contact-added.ts
@@ -1,7 +1,8 @@
import { TriggerStrategy, createTrigger } from '@activepieces/pieces-framework';
import { tarventAuth } from '../auth';
-import { makeClient, tarventCommon } from '../common';
-import { CreateWebhookResponse } from '../common/types';
+import { tarventCommon } from '../common';
+import { tarventWebhook } from '../common/webhook';
+import { tarventOutputSchemas } from '../output-schemas';
export const contactAddedTrigger = createTrigger({
auth: tarventAuth,
@@ -10,32 +11,17 @@ export const contactAddedTrigger = createTrigger({
displayName: 'Contact Added',
description: 'Triggers when a contact is added to the selected audience.',
aiMetadata: {
- description: 'Fires when a new contact is added to a Tarvent audience, optionally scoped to a specific audience, group, or tag. Represents a newly created subscriber.',
+ description: 'Fires when a new contact is added to a Tarvent audience, optionally scoped to a specific audience, group, or tag. Retried deliveries with the same event ID are ignored. Represents a newly created subscriber.',
},
type: TriggerStrategy.WEBHOOK,
+ outputSchema: tarventOutputSchemas.contactEvent,
props: {
include: tarventCommon.include,
audienceId: tarventCommon.audienceId(false, 'If specified, the trigger will only fire if contact is in the selected audience.'),
groupId: tarventCommon.audienceGroupId(false, 'If specified, the trigger will only fire if contact is in the selected group.'),
tagId: tarventCommon.tagId(false, 'If specified, the trigger will only fire if contact has the selected tag.')
},
- async onEnable(context) {
- const client = makeClient(context.auth);
- const res = await client.createWebhook(context, 'contactAdded');
- await context.store.put<CreateWebhookResponse>('tarvent_contact_added', res);
- },
- async run(context) {
- return [context.payload.body];
- },
- async onDisable(context) {
- const webhook = await context.store.get<CreateWebhookResponse>(
- 'tarvent_contact_added',
- );
- if (webhook != null) {
- const client = makeClient(context.auth);
- await client.deleteWebhook(webhook.data.createWebhook.id);
- }
- },
+ ...tarventWebhook.handlers({ type: 'contactAdded', storeKey: 'tarvent_contact_added' }),
sampleData: {
"id": "000000000000000000",
"dateUtc": "2022-09-27T17:37:26.482913Z",
@@ -53,46 +39,34 @@ export const contactAddedTrigger = createTrigger({
},
"payload": {
"audienceId": "000000000000000000",
- "contact": {
- "id": "000000000000000000",
- "key": "[email protected]",
- "email": "[email protected]",
- "status": 1,
- "rating": 3,
- "firstName": "Kayla",
- "lastName": "Johnson",
- "streetAddress": "165 Caprice Court",
- "streetAddress2": "Suite A",
- "addressLocality": "Castle Rock",
- "addressRegion": "Colorado",
- "postalCode": "80109",
- "addressCountry": "United States",
- "latitude": 39.38363820960583,
- "longitude": -104.86229586128452,
- "timeZone": "Mountain Standard Time",
- "language": "en",
- "sendFormat": 1,
- "optInUtc": "2022-08-28T17:37:26.6236851Z",
- "optInSource": 6,
- "optInIp": "0.0.0.0",
- "confirmedUtc": "2022-08-29T17:37:26.6236972Z",
- "confirmedIp": "0.0.0.0",
- "optOutUtc": null,
- "optOutSource": null,
- "optOutIp": null,
- "optOutReason": "",
- "groups": [
- "359949389556096655",
- "359949389556097786"
- ],
- "tags": [
- "TarventTest",
- "TarventTest2",
- "TarventTest3"
- ],
- "profileFields": null,
- "createdUtc": "2022-08-28T17:37:26.6237782Z",
- "modifiedUtc": "2022-09-17T17:37:26.6237797Z"
+ contact: {
+ id: '1594408175877314400',
+ email: '[email protected]',
+ status: '1',
+ rating: '',
+ firstname: 'ApTest',
+ lastname: 'Example',
+ streetaddress: '',
+ streetaddress2: '',
+ addresslocality: '',
+ addressregion: '',
+ postalcode: '',
+ addresscountry: '',
+ longitude: '',
+ latitude: '',
+ language: '',
+ timezone: '',
+ sendformat: '1',
+ optinsource: '6',
+ optinip: '',
+ optinutc: '10/21/2026 20:44:25',
+ confirmedutc: '',
+ confirmedip: '',
+ createdutc: '10/21/2026 20:44:25',
+ modifiedutc: '10/21/2026 20:44:25',
+ groups: '[]',
+ tags: '[]',
}
}
},
diff --git a/packages/pieces/community/tarvent/src/lib/triggers/contact-bounced.ts b/packages/pieces/community/tarvent/src/lib/triggers/contact-bounced.ts
index 08786b16c8a..d00da827d4e 100644
--- a/packages/pieces/community/tarvent/src/lib/triggers/contact-bounced.ts
+++ b/packages/pieces/community/tarvent/src/lib/triggers/contact-bounced.ts
@@ -1,7 +1,8 @@
import { tarventAuth } from '../auth';
import { Property, TriggerStrategy, createTrigger } from '@activepieces/pieces-framework';
-import { makeClient, tarventCommon } from '../common';
-import { CreateWebhookResponse } from '../common/types';
+import { tarventCommon } from '../common';
+import { tarventWebhook } from '../common/webhook';
+import { tarventOutputSchemas } from '../output-schemas';
export const contactBouncedTrigger = createTrigger({
auth: tarventAuth,
@@ -10,9 +11,10 @@ export const contactBouncedTrigger = createTrigger({
displayName: 'Campaign Or Transactional Email Bounced',
description: 'Triggers when a campaign or transactional email bounces (is rejected) for a contact.',
aiMetadata: {
- description: 'Fires when a campaign or transactional email bounces (is rejected) for a contact. Can be scoped by entity (campaign vs. transactional) and by bounce type (any, hard, soft, block, DNS failure, etc.), and optionally by audience, group, or tag. Represents a failed delivery.',
+ description: 'Fires when a campaign or transactional email bounces (is rejected) for a contact. Can be scoped by entity (campaign vs. transactional) and by bounce type (any, hard, soft, block, DNS failure, etc.), and optionally by audience, group, or tag. Retried deliveries with the same event ID are ignored. Represents a failed delivery.',
},
type: TriggerStrategy.WEBHOOK,
+ outputSchema: tarventOutputSchemas.bounceEvent,
props: {
include: tarventCommon.include,
entity: tarventCommon.entity,
@@ -39,23 +41,7 @@ export const contactBouncedTrigger = createTrigger({
groupId: tarventCommon.audienceGroupId(false, 'If specified, the trigger will only fire if contact is in the selected group.'),
tagId: tarventCommon.tagId(false, 'If specified, the trigger will only fire if contact has the selected tag.')
},
- async onEnable(context) {
- const client = makeClient(context.auth);
- const res = await client.createWebhook(context, 'contactBounced');
- await context.store.put<CreateWebhookResponse>('tarvent_contact_bounced', res);
- },
- async run(context) {
- return [context.payload.body];
- },
- async onDisable(context) {
- const webhook = await context.store.get<CreateWebhookResponse>(
- 'tarvent_contact_bounced',
- );
- if (webhook != null) {
- const client = makeClient(context.auth);
- await client.deleteWebhook(webhook.data.createWebhook.id);
- }
- },
+ ...tarventWebhook.handlers({ type: 'contactBounced', storeKey: 'tarvent_contact_bounced' }),
sampleData: {
id: '000000000000000000',
dateUtc: '2022-09-27T17:37:26.482913Z',
@@ -78,38 +64,33 @@ export const contactBouncedTrigger = createTrigger({
response: 'smtp;550 5.1.1 The email account that you tried to reach does not exist.'
},
contact: {
- id: '000000000000000000',
- email: '[email protected]',
- status: 1,
- rating: 3,
- firstName: 'Kayla',
- lastName: 'Johnson',
- streetAddress: '165 Caprice Court',
- streetAddress2: 'Suite A',
- addressLocality: 'Castle Rock',
- addressRegion: 'Colorado',
- postalCode: '80109',
- addressCountry: 'United States',
- latitude: 39.38363820960583,
- longitude: -104.86229586128452,
- timeZone: 'Mountain Standard Time',
- language: 'en',
- sendFormat: 1,
- optInUtc: '2022-08-28T17:37:26.6236851Z',
- optInSource: 6,
- optInIp: '0.0.0.0',
- confirmedUtc: '2022-08-29T17:37:26.6236972Z',
- confirmedIp: '0.0.0.0',
- optOutUtc: null,
- optOutSource: null,
- optOutIp: null,
- optOutReason: '',
- groups: ['359949389556096655', '359949389556097786'],
- tags: ['TarventTest', 'TarventTest2', 'TarventTest3'],
- profileFields: null,
- createdUtc: '2022-08-28T17:37:26.6237782Z',
- modifiedUtc: '2022-09-17T17:37:26.6237797Z',
+ id: '1594408175877314400',
+ email: '[email protected]',
+ status: '1',
+ rating: '',
+ firstname: 'ApTest',
+ lastname: 'Example',
+ streetaddress: '',
+ streetaddress2: '',
+ addresslocality: '',
+ addressregion: '',
+ postalcode: '',
+ addresscountry: '',
+ longitude: '',
+ latitude: '',
+ language: '',
+ timezone: '',
+ sendformat: '1',
+ optinsource: '6',
+ optinip: '',
+ optinutc: '10/21/2026 20:44:25',
+ confirmedutc: '',
+ confirmedip: '',
+ createdutc: '10/21/2026 20:44:25',
+ modifiedutc: '10/21/2026 20:44:25',
+ groups: '[]',
+ tags: '[]',
},
},
}
diff --git a/packages/pieces/community/tarvent/src/lib/triggers/contact-clicked.ts b/packages/pieces/community/tarvent/src/lib/triggers/contact-clicked.ts
index 4901a53bc54..3b7d95a05cb 100644
--- a/packages/pieces/community/tarvent/src/lib/triggers/contact-clicked.ts
+++ b/packages/pieces/community/tarvent/src/lib/triggers/contact-clicked.ts
@@ -1,7 +1,8 @@
import { tarventAuth } from '../auth';
import { Property, TriggerStrategy, createTrigger } from '@activepieces/pieces-framework';
-import { makeClient, tarventCommon } from '../common';
-import { CreateWebhookResponse } from '../common/types';
+import { tarventCommon } from '../common';
+import { tarventWebhook } from '../common/webhook';
+import { tarventOutputSchemas } from '../output-schemas';
export const contactClickedTrigger = createTrigger({
auth: tarventAuth,
@@ -10,9 +11,10 @@ export const contactClickedTrigger = createTrigger({
displayName: 'Campaign Or Transactional Link Clicked',
description: 'Triggers when a link within a campaign or transactional email is clicked by a recipient.',
aiMetadata: {
- description: 'Fires when a recipient clicks a link in a campaign or transactional email. Can be scoped by entity (campaign vs. transactional), by which campaign(s) qualify (any/all of the last 5, any within a recent window, or a specific campaign), by a specific link, and optionally by audience, group, or tag. Represents a click engagement event.',
+ description: 'Fires when a recipient clicks a link in a campaign or transactional email. Can be scoped by entity (campaign vs. transactional), by which campaign(s) qualify (any/all of the last 5, any within a recent window, or a specific campaign), by a specific link, and optionally by audience, group, or tag. Retried deliveries with the same event ID are ignored. Represents a click engagement event.',
},
type: TriggerStrategy.WEBHOOK,
+ outputSchema: tarventOutputSchemas.clickEvent,
props: {
include: tarventCommon.include,
entity: tarventCommon.entity,
@@ -23,6 +25,10 @@ export const contactClickedTrigger = createTrigger({
defaultValue: 'BOTH',
options: {
options: [
+ {
+ label: 'Any campaign',
+ value: 'BOTH',
+ },
{
label: 'Any of the last 5 campaigns',
@@ -51,23 +57,7 @@ export const contactClickedTrigger = createTrigger({
groupId: tarventCommon.audienceGroupId(false, 'If specified, the trigger will only fire if contact is in the selected group.'),
tagId: tarventCommon.tagId(false, 'If specified, the trigger will only fire if contact has the selected tag.')
},
- async onEnable(context) {
- const client = makeClient(context.auth);
- const res = await client.createWebhook(context, 'contactClicked');
- await context.store.put<CreateWebhookResponse>('tarvent_contact_clicked', res);
- },
- async run(context) {
- return [context.payload.body];
- },
- async onDisable(context) {
- const webhook = await context.store.get<CreateWebhookResponse>(
- 'tarvent_contact_clicked',
- );
- if (webhook != null) {
- const client = makeClient(context.auth);
- await client.deleteWebhook(webhook.data.createWebhook.id);
- }
- },
+ ...tarventWebhook.handlers({ type: 'contactClicked', storeKey: 'tarvent_contact_clicked' }),
sampleData: {
id: '000000000000000000',
dateUtc: '2022-09-27T17:37:26.482913Z',
@@ -90,38 +80,33 @@ export const contactClickedTrigger = createTrigger({
url: 'https://yourdomain.com/yourpage'
},
contact: {
- id: '000000000000000000',
- email: '[email protected]',
- status: 1,
- rating: 3,
- firstName: 'Kayla',
- lastName: 'Johnson',
- streetAddress: '165 Caprice Court',
- streetAddress2: 'Suite A',
- addressLocality: 'Castle Rock',
- addressRegion: 'Colorado',
- postalCode: '80109',
- addressCountry: 'United States',
- latitude: 39.38363820960583,
- longitude: -104.86229586128452,
- timeZone: 'Mountain Standard Time',
- language: 'en',
- sendFormat: 1,
- optInUtc: '2022-08-28T17:37:26.6236851Z',
- optInSource: 6,
- optInIp: '0.0.0.0',
- confirmedUtc: '2022-08-29T17:37:26.6236972Z',
- confirmedIp: '0.0.0.0',
- optOutUtc: null,
- optOutSource: null,
- optOutIp: null,
- optOutReason: '',
- groups: ['359949389556096655', '359949389556097786'],
- tags: ['TarventTest', 'TarventTest2', 'TarventTest3'],
- profileFields: null,
- createdUtc: '2022-08-28T17:37:26.6237782Z',
- modifiedUtc: '2022-09-17T17:37:26.6237797Z',
+ id: '1594408175877314400',
+ email: '[email protected]',
+ status: '1',
+ rating: '',
+ firstname: 'ApTest',
+ lastname: 'Example',
+ streetaddress: '',
+ streetaddress2: '',
+ addresslocality: '',
+ addressregion: '',
+ postalcode: '',
+ addresscountry: '',
+ longitude: '',
+ latitude: '',
+ language: '',
+ timezone: '',
+ sendformat: '1',
+ optinsource: '6',
+ optinip: '',
+ optinutc: '10/21/2026 20:44:25',
+ confirmedutc: '',
+ confirmedip: '',
+ createdutc: '10/21/2026 20:44:25',
+ modifiedutc: '10/21/2026 20:44:25',
+ groups: '[]',
+ tags: '[]',
},
},
}
diff --git a/packages/pieces/community/tarvent/src/lib/triggers/contact-group-updated.ts b/packages/pieces/community/tarvent/src/lib/triggers/contact-group-updated.ts
index 3ed3bd3f54c..d06fde69419 100644
--- a/packages/pieces/community/tarvent/src/lib/triggers/contact-group-updated.ts
+++ b/packages/pieces/community/tarvent/src/lib/triggers/contact-group-updated.ts
@@ -1,7 +1,8 @@
import { Property, TriggerStrategy, createTrigger } from '@activepieces/pieces-framework';
import { tarventAuth } from '../auth';
-import { makeClient, tarventCommon } from '../common';
-import { CreateWebhookResponse } from '../common/types';
+import { tarventCommon } from '../common';
+import { tarventWebhook } from '../common/webhook';
+import { tarventOutputSchemas } from '../output-schemas';
export const contactGroupUpdatedTrigger = createTrigger({
auth: tarventAuth,
@@ -10,9 +11,10 @@ export const contactGroupUpdatedTrigger = createTrigger({
displayName: 'Contact Added Or Removed From A Group',
description: 'Triggers when a contact is added or removed from a group.',
aiMetadata: {
- description: 'Fires when a contact is added to or removed from an audience group, with the direction (added vs. removed) selectable. Represents a change in group membership.',
+ description: 'Fires when a contact is added to or removed from an audience group, with the direction (added vs. removed) selectable. Retried deliveries with the same event ID are ignored. Represents a change in group membership.',
},
type: TriggerStrategy.WEBHOOK,
+ outputSchema: tarventOutputSchemas.contactEvent,
props: {
include: tarventCommon.include,
audienceId: tarventCommon.audienceId(false, 'If specified, the trigger will only fire if contact is in the selected audience.'),
@@ -37,23 +39,7 @@ export const contactGroupUpdatedTrigger = createTrigger({
},
}),
},
- async onEnable(context) {
- const client = makeClient(context.auth);
- const res = await client.createWebhook(context, 'contactGroupUpdated');
- await context.store.put<CreateWebhookResponse>('tarvent_contact_group_updated', res);
- },
- async run(context) {
- return [context.payload.body];
- },
- async onDisable(context) {
- const webhook = await context.store.get<CreateWebhookResponse>(
- 'tarvent_contact_group_updated',
- );
- if (webhook != null) {
- const client = makeClient(context.auth);
- await client.deleteWebhook(webhook.data.createWebhook.id);
- }
- },
+ ...tarventWebhook.handlers({ type: 'contactGroupUpdated', storeKey: 'tarvent_contact_group_updated' }),
sampleData: {
"id": "000000000000000000",
"dateUtc": "2022-09-27T17:37:26.482913Z",
@@ -71,46 +57,34 @@ export const contactGroupUpdatedTrigger = createTrigger({
},
"payload": {
"audienceId": "000000000000000000",
- "contact": {
- "id": "000000000000000000",
- "key": "[email protected]",
- "email": "[email protected]",
- "status": 1,
- "rating": 3,
- "firstName": "Kayla",
- "lastName": "Johnson",
- "streetAddress": "165 Caprice Court",
- "streetAddress2": "Suite A",
- "addressLocality": "Castle Rock",
- "addressRegion": "Colorado",
- "postalCode": "80109",
- "addressCountry": "United States",
- "latitude": 39.38363820960583,
- "longitude": -104.86229586128452,
- "timeZone": "Mountain Standard Time",
- "language": "en",
- "sendFormat": 1,
- "optInUtc": "2022-08-28T17:37:26.6236851Z",
- "optInSource": 6,
- "optInIp": "0.0.0.0",
- "confirmedUtc": "2022-08-29T17:37:26.6236972Z",
- "confirmedIp": "0.0.0.0",
- "optOutUtc": null,
- "optOutSource": null,
- "optOutIp": null,
- "optOutReason": "",
- "groups": [
- "359949389556096655",
- "359949389556097786"
- ],
- "tags": [
- "TarventTest",
- "TarventTest2",
- "TarventTest3"
- ],
- "profileFields": null,
- "createdUtc": "2022-08-28T17:37:26.6237782Z",
- "modifiedUtc": "2022-09-17T17:37:26.6237797Z"
+ contact: {
+ id: '1594408175877314400',
+ email: '[email protected]',
+ status: '1',
+ rating: '',
+ firstname: 'ApTest',
+ lastname: 'Example',
+ streetaddress: '',
+ streetaddress2: '',
+ addresslocality: '',
+ addressregion: '',
+ postalcode: '',
+ addresscountry: '',
+ longitude: '',
+ latitude: '',
+ language: '',
+ timezone: '',
+ sendformat: '1',
+ optinsource: '6',
+ optinip: '',
+ optinutc: '10/21/2026 20:44:25',
+ confirmedutc: '',
+ confirmedip: '',
+ createdutc: '10/21/2026 20:44:25',
+ modifiedutc: '10/21/2026 20:44:25',
+ groups: '[]',
+ tags: '[]',
}
}
},
diff --git a/packages/pieces/community/tarvent/src/lib/triggers/contact-node-added.ts b/packages/pieces/community/tarvent/src/lib/triggers/contact-node-added.ts
index e219d9109de..ae1a788ab09 100644
--- a/packages/pieces/community/tarvent/src/lib/triggers/contact-node-added.ts
+++ b/packages/pieces/community/tarvent/src/lib/triggers/contact-node-added.ts
@@ -1,7 +1,8 @@
import { TriggerStrategy, createTrigger } from '@activepieces/pieces-framework';
import { tarventAuth } from '../auth';
-import { makeClient, tarventCommon } from '../common';
-import { CreateWebhookResponse } from '../common/types';
+import { tarventCommon } from '../common';
+import { tarventWebhook } from '../common/webhook';
+import { tarventOutputSchemas } from '../output-schemas';
export const contactNoteAddedTrigger = createTrigger({
auth: tarventAuth,
@@ -10,32 +11,17 @@ export const contactNoteAddedTrigger = createTrigger({
displayName: 'Contact Note Added',
description: 'Triggers when a note is added to a contact.',
aiMetadata: {
- description: 'Fires when a note is added to a contact in Tarvent. Represents new annotation activity logged against a contact.',
+ description: 'Fires when a note is added to a contact in Tarvent. Retried deliveries with the same event ID are ignored. Represents new annotation activity logged against a contact.',
},
type: TriggerStrategy.WEBHOOK,
+ outputSchema: tarventOutputSchemas.contactEvent,
props: {
include: tarventCommon.include,
audienceId: tarventCommon.audienceId(false, 'If specified, the trigger will only fire if contact is in the selected audience.'),
groupId: tarventCommon.audienceGroupId(false, 'If specified, the trigger will only fire if contact is in the selected group.'),
tagId: tarventCommon.tagId(false, 'If specified, the trigger will only fire if contact has the selected tag.')
},
- async onEnable(context) {
- const client = makeClient(context.auth);
- const res = await client.createWebhook(context, 'contactNoteAdded');
- await context.store.put<CreateWebhookResponse>('tarvent_contact_note_added', res);
- },
- async run(context) {
- return [context.payload.body];
- },
- async onDisable(context) {
- const webhook = await context.store.get<CreateWebhookResponse>(
- 'tarvent_contact_note_added',
- );
- if (webhook != null) {
- const client = makeClient(context.auth);
- await client.deleteWebhook(webhook.data.createWebhook.id);
- }
- },
+ ...tarventWebhook.handlers({ type: 'contactNoteAdded', storeKey: 'tarvent_contact_note_added' }),
sampleData: {
"id": "000000000000000000",
"dateUtc": "2022-09-27T17:37:26.482913Z",
@@ -53,46 +39,34 @@ export const contactNoteAddedTrigger = createTrigger({
},
"payload": {
"audienceId": "000000000000000000",
- "contact": {
- "id": "000000000000000000",
- "key": "[email protected]",
- "email": "[email protected]",
- "status": 1,
- "rating": 3,
- "firstName": "Kayla",
- "lastName": "Johnson",
- "streetAddress": "165 Caprice Court",
- "streetAddress2": "Suite A",
- "addressLocality": "Castle Rock",
- "addressRegion": "Colorado",
- "postalCode": "80109",
- "addressCountry": "United States",
- "latitude": 39.38363820960583,
- "longitude": -104.86229586128452,
- "timeZone": "Mountain Standard Time",
- "language": "en",
- "sendFormat": 1,
- "optInUtc": "2022-08-28T17:37:26.6236851Z",
- "optInSource": 6,
- "optInIp": "0.0.0.0",
- "confirmedUtc": "2022-08-29T17:37:26.6236972Z",
- "confirmedIp": "0.0.0.0",
- "optOutUtc": null,
- "optOutSource": null,
- "optOutIp": null,
- "optOutReason": "",
- "groups": [
- "359949389556096655",
- "359949389556097786"
- ],
- "tags": [
- "TarventTest",
- "TarventTest2",
- "TarventTest3"
- ],
- "profileFields": null,
- "createdUtc": "2022-08-28T17:37:26.6237782Z",
- "modifiedUtc": "2022-09-17T17:37:26.6237797Z"
+ contact: {
+ id: '1594408175877314400',
+ email: '[email protected]',
+ status: '1',
+ rating: '',
+ firstname: 'ApTest',
+ lastname: 'Example',
+ streetaddress: '',
+ streetaddress2: '',
+ addresslocality: '',
+ addressregion: '',
+ postalcode: '',
+ addresscountry: '',
+ longitude: '',
+ latitude: '',
+ language: '',
+ timezone: '',
+ sendformat: '1',
+ optinsource: '6',
+ optinip: '',
+ optinutc: '10/21/2026 20:44:25',
+ confirmedutc: '',
+ confirmedip: '',
+ createdutc: '10/21/2026 20:44:25',
+ modifiedutc: '10/21/2026 20:44:25',
+ groups: '[]',
+ tags: '[]',
}
}
},
diff --git a/packages/pieces/community/tarvent/src/lib/triggers/contact-opened.ts b/packages/pieces/community/tarvent/src/lib/triggers/contact-opened.ts
index 3f0678c7314..67f43fb9a9e 100644
--- a/packages/pieces/community/tarvent/src/lib/triggers/contact-opened.ts
+++ b/packages/pieces/community/tarvent/src/lib/triggers/contact-opened.ts
@@ -1,7 +1,8 @@
import { Property, TriggerStrategy, createTrigger } from '@activepieces/pieces-framework';
import { tarventAuth } from '../auth';
-import { makeClient, tarventCommon } from '../common';
-import { CreateWebhookResponse } from '../common/types';
+import { tarventCommon } from '../common';
+import { tarventWebhook } from '../common/webhook';
+import { tarventOutputSchemas } from '../output-schemas';
export const contactOpenedTrigger = createTrigger({
auth: tarventAuth,
@@ -10,9 +11,10 @@ export const contactOpenedTrigger = createTrigger({
displayName: 'Campaign Or Transactional Email Opened',
description: 'Triggers when a campaign or transactional email is opened by a recipient.',
aiMetadata: {
- description: 'Fires when a recipient opens a campaign or transactional email. Can be scoped by entity (campaign vs. transactional), by which campaign(s) qualify (any/all of the last 5, any within a recent window, or a specific campaign), and optionally by audience, group, or tag. Represents an open engagement event.',
+ description: 'Fires when a recipient opens a campaign or transactional email. Can be scoped by entity (campaign vs. transactional), by which campaign(s) qualify (any/all of the last 5, any within a recent window, or a specific campaign), and optionally by audience, group, or tag. Retried deliveries with the same event ID are ignored. Represents an open engagement event.',
},
type: TriggerStrategy.WEBHOOK,
+ outputSchema: tarventOutputSchemas.emailEvent,
props: {
include: tarventCommon.include,
entity: tarventCommon.entity,
@@ -23,6 +25,10 @@ export const contactOpenedTrigger = createTrigger({
defaultValue: 'BOTH',
options: {
options: [
+ {
+ label: 'Any campaign',
+ value: 'BOTH',
+ },
{
label: 'Any of the last 5 campaigns',
@@ -50,23 +56,7 @@ export const contactOpenedTrigger = createTrigger({
groupId: tarventCommon.audienceGroupId(false, 'If specified, the trigger will only fire if contact is in the selected group.'),
tagId: tarventCommon.tagId(false, 'If specified, the trigger will only fire if contact has the selected tag.')
},
- async onEnable(context) {
- const client = makeClient(context.auth);
- const res = await client.createWebhook(context, 'contactOpened');
- await context.store.put<CreateWebhookResponse>('tarvent_contact_opened', res);
- },
- async run(context) {
- return [context.payload.body];
- },
- async onDisable(context) {
- const webhook = await context.store.get<CreateWebhookResponse>(
- 'tarvent_contact_opened',
- );
- if (webhook != null) {
- const client = makeClient(context.auth);
- await client.deleteWebhook(webhook.data.createWebhook.id);
- }
- },
+ ...tarventWebhook.handlers({ type: 'contactOpened', storeKey: 'tarvent_contact_opened' }),
sampleData: {
id: '000000000000000000',
dateUtc: '2022-09-27T17:37:26.482913Z',
@@ -85,38 +75,33 @@ export const contactOpenedTrigger = createTrigger({
payload: {
emailId: '000000000000000000',
contact: {
- id: '000000000000000000',
- email: '[email protected]',
- status: 1,
- rating: 3,
- firstName: 'Kayla',
- lastName: 'Johnson',
- streetAddress: '165 Caprice Court',
- streetAddress2: 'Suite A',
- addressLocality: 'Castle Rock',
- addressRegion: 'Colorado',
- postalCode: '80109',
- addressCountry: 'United States',
- latitude: 39.38363820960583,
- longitude: -104.86229586128452,
- timeZone: 'Mountain Standard Time',
- language: 'en',
- sendFormat: 1,
- optInUtc: '2022-08-28T17:37:26.6236851Z',
- optInSource: 6,
- optInIp: '0.0.0.0',
- confirmedUtc: '2022-08-29T17:37:26.6236972Z',
- confirmedIp: '0.0.0.0',
- optOutUtc: null,
- optOutSource: null,
- optOutIp: null,
- optOutReason: '',
- groups: ['359949389556096655', '359949389556097786'],
- tags: ['TarventTest', 'TarventTest2', 'TarventTest3'],
- profileFields: null,
- createdUtc: '2022-08-28T17:37:26.6237782Z',
- modifiedUtc: '2022-09-17T17:37:26.6237797Z',
+ id: '1594408175877314400',
+ email: '[email protected]',
+ status: '1',
+ rating: '',
+ firstname: 'ApTest',
+ lastname: 'Example',
+ streetaddress: '',
+ streetaddress2: '',
+ addresslocality: '',
+ addressregion: '',
+ postalcode: '',
+ addresscountry: '',
+ longitude: '',
+ latitude: '',
+ language: '',
+ timezone: '',
+ sendformat: '1',
+ optinsource: '6',
+ optinip: '',
+ optinutc: '10/21/2026 20:44:25',
+ confirmedutc: '',
+ confirmedip: '',
+ createdutc: '10/21/2026 20:44:25',
+ modifiedutc: '10/21/2026 20:44:25',
+ groups: '[]',
+ tags: '[]',
},
},
}
diff --git a/packages/pieces/community/tarvent/src/lib/triggers/contact-replied.ts b/packages/pieces/community/tarvent/src/lib/triggers/contact-replied.ts
index 11a292827c6..06ee393da17 100644
--- a/packages/pieces/community/tarvent/src/lib/triggers/contact-replied.ts
+++ b/packages/pieces/community/tarvent/src/lib/triggers/contact-replied.ts
@@ -1,7 +1,8 @@
import { TriggerStrategy, createTrigger } from '@activepieces/pieces-framework';
import { tarventAuth } from '../auth';
-import { makeClient, tarventCommon } from '../common';
-import { CreateWebhookResponse } from '../common/types';
+import { tarventCommon } from '../common';
+import { tarventWebhook } from '../common/webhook';
+import { tarventOutputSchemas } from '../output-schemas';
export const contactRepliedTrigger = createTrigger({
auth: tarventAuth,
@@ -10,9 +11,10 @@ export const contactRepliedTrigger = createTrigger({
displayName: 'Contact Replied',
description: 'Triggers when a contact replies.',
aiMetadata: {
- description: 'Fires when a contact replies to a campaign or transactional email. Represents an inbound reply from a recipient.',
+ description: 'Fires when a contact replies to a campaign or transactional email. Retried deliveries with the same event ID are ignored. Represents an inbound reply from a recipient.',
},
type: TriggerStrategy.WEBHOOK,
+ outputSchema: tarventOutputSchemas.emailEvent,
props: {
include: tarventCommon.include,
entity: tarventCommon.entity,
@@ -20,23 +22,7 @@ export const contactRepliedTrigger = createTrigger({
groupId: tarventCommon.audienceGroupId(false, 'If specified, the trigger will only fire if contact is in the selected group.'),
tagId: tarventCommon.tagId(false, 'If specified, the trigger will only fire if contact has the selected tag.')
},
- async onEnable(context) {
- const client = makeClient(context.auth);
- const res = await client.createWebhook(context, 'contactReplied');
- await context.store.put<CreateWebhookResponse>('tarvent_contact_replied', res);
- },
- async run(context) {
- return [context.payload.body];
- },
- async onDisable(context) {
- const webhook = await context.store.get<CreateWebhookResponse>(
- 'tarvent_contact_replied',
- );
- if (webhook != null) {
- const client = makeClient(context.auth);
- await client.deleteWebhook(webhook.data.createWebhook.id);
- }
- },
+ ...tarventWebhook.handlers({ type: 'contactReplied', storeKey: 'tarvent_contact_replied' }),
sampleData: {
id: '000000000000000000',
dateUtc: '2022-09-27T17:37:26.482913Z',
@@ -59,38 +45,33 @@ export const contactRepliedTrigger = createTrigger({
response: 'smtp;550 5.1.1 The email account that you tried to reach does not exist.'
},
contact: {
- id: '000000000000000000',
- email: '[email protected]',
- status: 1,
- rating: 3,
- firstName: 'Kayla',
- lastName: 'Johnson',
- streetAddress: '165 Caprice Court',
- streetAddress2: 'Suite A',
- addressLocality: 'Castle Rock',
- addressRegion: 'Colorado',
- postalCode: '80109',
- addressCountry: 'United States',
- latitude: 39.38363820960583,
- longitude: -104.86229586128452,
- timeZone: 'Mountain Standard Time',
- language: 'en',
- sendFormat: 1,
- optInUtc: '2022-08-28T17:37:26.6236851Z',
- optInSource: 6,
- optInIp: '0.0.0.0',
- confirmedUtc: '2022-08-29T17:37:26.6236972Z',
- confirmedIp: '0.0.0.0',
- optOutUtc: null,
- optOutSource: null,
- optOutIp: null,
- optOutReason: '',
- groups: ['359949389556096655', '359949389556097786'],
- tags: ['TarventTest', 'TarventTest2', 'TarventTest3'],
- profileFields: null,
- createdUtc: '2022-08-28T17:37:26.6237782Z',
- modifiedUtc: '2022-09-17T17:37:26.6237797Z',
+ id: '1594408175877314400',
+ email: '[email protected]',
+ status: '1',
+ rating: '',
+ firstname: 'ApTest',
+ lastname: 'Example',
+ streetaddress: '',
+ streetaddress2: '',
+ addresslocality: '',
+ addressregion: '',
+ postalcode: '',
+ addresscountry: '',
+ longitude: '',
+ latitude: '',
+ language: '',
+ timezone: '',
+ sendformat: '1',
+ optinsource: '6',
+ optinip: '',
+ optinutc: '10/21/2026 20:44:25',
+ confirmedutc: '',
+ confirmedip: '',
+ createdutc: '10/21/2026 20:44:25',
+ modifiedutc: '10/21/2026 20:44:25',
+ groups: '[]',
+ tags: '[]',
},
},
}
diff --git a/packages/pieces/community/tarvent/src/lib/triggers/contact-status-updated.ts b/packages/pieces/community/tarvent/src/lib/triggers/contact-status-updated.ts
index 5e180f1ef86..acb56e170cb 100644
--- a/packages/pieces/community/tarvent/src/lib/triggers/contact-status-updated.ts
+++ b/packages/pieces/community/tarvent/src/lib/triggers/contact-status-updated.ts
@@ -1,7 +1,8 @@
import { tarventAuth } from '../auth';
import { Property, TriggerStrategy, createTrigger } from '@activepieces/pieces-framework';
-import { makeClient, tarventCommon } from '../common';
-import { CreateWebhookResponse } from '../common/types';
+import { tarventCommon } from '../common';
+import { tarventWebhook } from '../common/webhook';
+import { tarventOutputSchemas } from '../output-schemas';
export const contactStatusUpdatedTrigger = createTrigger({
auth: tarventAuth,
@@ -10,9 +11,10 @@ export const contactStatusUpdatedTrigger = createTrigger({
displayName: 'Contact Status Changed',
description: 'Triggers when a contact\'s status changes.',
aiMetadata: {
- description: 'Fires when a contact\'s subscription status changes, with a selectable status filter (any change, or specifically subscribe vs. unsubscribe). Represents a consent or lifecycle state transition.',
+ description: 'Fires when a contact\'s subscription status changes, with a selectable status filter (any change, or specifically subscribe vs. unsubscribe). Retried deliveries with the same event ID are ignored. Represents a consent or lifecycle state transition.',
},
type: TriggerStrategy.WEBHOOK,
+ outputSchema: tarventOutputSchemas.contactEvent,
props: {
include: tarventCommon.include,
status: Property.StaticDropdown({
@@ -42,23 +44,7 @@ export const contactStatusUpdatedTrigger = createTrigger({
groupId: tarventCommon.audienceGroupId(false, 'If specified, the trigger will only fire if contact is in the selected group.'),
tagId: tarventCommon.tagId(false, 'If specified, the trigger will only fire if contact has the selected tag.')
},
- async onEnable(context) {
- const client = makeClient(context.auth);
- const res = await client.createWebhook(context, 'contactStatusUpdated');
- await context.store.put<CreateWebhookResponse>('tarvent_contact_status_updated', res);
- },
- async run(context) {
- return [context.payload.body];
- },
- async onDisable(context) {
- const webhook = await context.store.get<CreateWebhookResponse>(
- 'tarvent_contact_status_updated',
- );
- if (webhook != null) {
- const client = makeClient(context.auth);
- await client.deleteWebhook(webhook.data.createWebhook.id);
- }
- },
+ ...tarventWebhook.handlers({ type: 'contactStatusUpdated', storeKey: 'tarvent_contact_status_updated' }),
sampleData: {
"id": "000000000000000000",
"dateUtc": "2022-09-27T17:37:26.482913Z",
@@ -76,46 +62,34 @@ export const contactStatusUpdatedTrigger = createTrigger({
},
"payload": {
"audienceId": "000000000000000000",
- "contact": {
- "id": "000000000000000000",
- "key": "[email protected]",
- "email": "[email protected]",
- "status": 1,
- "rating": 3,
- "firstName": "Kayla",
- "lastName": "Johnson",
- "streetAddress": "165 Caprice Court",
- "streetAddress2": "Suite A",
- "addressLocality": "Castle Rock",
- "addressRegion": "Colorado",
- "postalCode": "80109",
- "addressCountry": "United States",
- "latitude": 39.38363820960583,
- "longitude": -104.86229586128452,
- "timeZone": "Mountain Standard Time",
- "language": "en",
- "sendFormat": 1,
- "optInUtc": "2022-08-28T17:37:26.6236851Z",
- "optInSource": 6,
- "optInIp": "0.0.0.0",
- "confirmedUtc": "2022-08-29T17:37:26.6236972Z",
- "confirmedIp": "0.0.0.0",
- "optOutUtc": null,
- "optOutSource": null,
- "optOutIp": null,
- "optOutReason": "",
- "groups": [
- "359949389556096655",
- "359949389556097786"
- ],
- "tags": [
- "TarventTest",
- "TarventTest2",
- "TarventTest3"
- ],
- "profileFields": null,
- "createdUtc": "2022-08-28T17:37:26.6237782Z",
- "modifiedUtc": "2022-09-17T17:37:26.6237797Z"
+ contact: {
+ id: '1594408175877314400',
+ email: '[email protected]',
+ status: '1',
+ rating: '',
+ firstname: 'ApTest',
+ lastname: 'Example',
+ streetaddress: '',
+ streetaddress2: '',
+ addresslocality: '',
+ addressregion: '',
+ postalcode: '',
+ addresscountry: '',
+ longitude: '',
+ latitude: '',
+ language: '',
+ timezone: '',
+ sendformat: '1',
+ optinsource: '6',
+ optinip: '',
+ optinutc: '10/21/2026 20:44:25',
+ confirmedutc: '',
+ confirmedip: '',
+ createdutc: '10/21/2026 20:44:25',
+ modifiedutc: '10/21/2026 20:44:25',
+ groups: '[]',
+ tags: '[]',
}
}
},
diff --git a/packages/pieces/community/tarvent/src/lib/triggers/contact-tag-updated.ts b/packages/pieces/community/tarvent/src/lib/triggers/contact-tag-updated.ts
index 0f5bca77aad..6824013996b 100644
--- a/packages/pieces/community/tarvent/src/lib/triggers/contact-tag-updated.ts
+++ b/packages/pieces/community/tarvent/src/lib/triggers/contact-tag-updated.ts
@@ -1,7 +1,8 @@
import { tarventAuth } from '../auth';
import { Property, TriggerStrategy, createTrigger } from '@activepieces/pieces-framework';
-import { makeClient, tarventCommon } from '../common';
-import { CreateWebhookResponse } from '../common/types';
+import { tarventCommon } from '../common';
+import { tarventWebhook } from '../common/webhook';
+import { tarventOutputSchemas } from '../output-schemas';
export const contactTagUpdatedTrigger = createTrigger({
auth: tarventAuth,
@@ -10,9 +11,10 @@ export const contactTagUpdatedTrigger = createTrigger({
displayName: 'Contact Tag Added Or Removed',
description: 'Triggers when a tag is added or removed from a contact.',
aiMetadata: {
- description: 'Fires when a tag is added to or removed from a contact, with the direction (added vs. removed) selectable. Represents a change in a contact\'s tags.',
+ description: 'Fires when a tag is added to or removed from a contact, with the direction (added vs. removed) selectable. Retried deliveries with the same event ID are ignored. Represents a change in a contact\'s tags.',
},
type: TriggerStrategy.WEBHOOK,
+ outputSchema: tarventOutputSchemas.contactEvent,
props: {
include: tarventCommon.include,
action: Property.StaticDropdown({
@@ -38,23 +40,7 @@ export const contactTagUpdatedTrigger = createTrigger({
groupId: tarventCommon.audienceGroupId(false, 'If specified, the trigger will only fire if contact is in the selected group.'),
tagId: tarventCommon.tagId(false, 'If specified, the trigger will only fire if contact has the selected tag.')
},
- async onEnable(context) {
- const client = makeClient(context.auth);
- const res = await client.createWebhook(context, 'contactTagUpdated');
- await context.store.put<CreateWebhookResponse>('tarvent_contact_tag_updated', res);
- },
- async run(context) {
- return [context.payload.body];
- },
- async onDisable(context) {
- const webhook = await context.store.get<CreateWebhookResponse>(
- 'tarvent_contact_tag_updated',
- );
- if (webhook != null) {
- const client = makeClient(context.auth);
- await client.deleteWebhook(webhook.data.createWebhook.id);
- }
- },
+ ...tarventWebhook.handlers({ type: 'contactTagUpdated', storeKey: 'tarvent_contact_tag_updated' }),
sampleData: {
"id": "000000000000000000",
"dateUtc": "2022-09-27T17:37:26.482913Z",
@@ -72,46 +58,34 @@ export const contactTagUpdatedTrigger = createTrigger({
},
"payload": {
"audienceId": "000000000000000000",
- "contact": {
- "id": "000000000000000000",
- "key": "[email protected]",
- "email": "[email protected]",
- "status": 1,
- "rating": 3,
- "firstName": "Kayla",
- "lastName": "Johnson",
- "streetAddress": "165 Caprice Court",
- "streetAddress2": "Suite A",
- "addressLocality": "Castle Rock",
- "addressRegion": "Colorado",
- "postalCode": "80109",
- "addressCountry": "United States",
- "latitude": 39.38363820960583,
- "longitude": -104.86229586128452,
- "timeZone": "Mountain Standard Time",
- "language": "en",
- "sendFormat": 1,
- "optInUtc": "2022-08-28T17:37:26.6236851Z",
- "optInSource": 6,
- "optInIp": "0.0.0.0",
- "confirmedUtc": "2022-08-29T17:37:26.6236972Z",
- "confirmedIp": "0.0.0.0",
- "optOutUtc": null,
- "optOutSource": null,
- "optOutIp": null,
- "optOutReason": "",
- "groups": [
- "359949389556096655",
- "359949389556097786"
- ],
- "tags": [
- "TarventTest",
- "TarventTest2",
- "TarventTest3"
- ],
- "profileFields": null,
- "createdUtc": "2022-08-28T17:37:26.6237782Z",
- "modifiedUtc": "2022-09-17T17:37:26.6237797Z"
+ contact: {
+ id: '1594408175877314400',
+ email: '[email protected]',
+ status: '1',
+ rating: '',
+ firstname: 'ApTest',
+ lastname: 'Example',
+ streetaddress: '',
+ streetaddress2: '',
+ addresslocality: '',
+ addressregion: '',
+ postalcode: '',
+ addresscountry: '',
+ longitude: '',
+ latitude: '',
+ language: '',
+ timezone: '',
+ sendformat: '1',
+ optinsource: '6',
+ optinip: '',
+ optinutc: '10/21/2026 20:44:25',
+ confirmedutc: '',
+ confirmedip: '',
+ createdutc: '10/21/2026 20:44:25',
+ modifiedutc: '10/21/2026 20:44:25',
+ groups: '[]',
+ tags: '[]',
}
}
},
diff --git a/packages/pieces/community/tarvent/src/lib/triggers/contact-unsubscribed.ts b/packages/pieces/community/tarvent/src/lib/triggers/contact-unsubscribed.ts
index 90248be7848..005515a5094 100644
--- a/packages/pieces/community/tarvent/src/lib/triggers/contact-unsubscribed.ts
+++ b/packages/pieces/community/tarvent/src/lib/triggers/contact-unsubscribed.ts
@@ -1,7 +1,8 @@
import { TriggerStrategy, createTrigger } from '@activepieces/pieces-framework';
import { tarventAuth } from '../auth';
-import { makeClient, tarventCommon } from '../common';
-import { CreateWebhookResponse } from '../common/types';
+import { tarventCommon } from '../common';
+import { tarventWebhook } from '../common/webhook';
+import { tarventOutputSchemas } from '../output-schemas';
export const contactUnsubscribedTrigger = createTrigger({
auth: tarventAuth,
@@ -10,32 +11,17 @@ export const contactUnsubscribedTrigger = createTrigger({
displayName: 'Contact Unsubscribed',
description: 'Triggers when a contact unsubscribes from an audience.',
aiMetadata: {
- description: 'Fires when a contact unsubscribes (opts out) from an audience. Represents a withdrawal of consent.',
+ description: 'Fires when a contact unsubscribes (opts out) from an audience. Retried deliveries with the same event ID are ignored. Represents a withdrawal of consent.',
},
type: TriggerStrategy.WEBHOOK,
+ outputSchema: tarventOutputSchemas.contactEvent,
props: {
include: tarventCommon.include,
audienceId: tarventCommon.audienceId(false, 'If specified, the trigger will only fire if contact is in the selected audience.'),
groupId: tarventCommon.audienceGroupId(false, 'If specified, the trigger will only fire if contact is in the selected group.'),
tagId: tarventCommon.tagId(false, 'If specified, the trigger will only fire if contact has the selected tag.')
},
- async onEnable(context) {
- const client = makeClient(context.auth);
- const res = await client.createWebhook(context, 'contactUnsubscribed');
- await context.store.put<CreateWebhookResponse>('tarvent_contact_unsubscribed', res);
- },
- async run(context) {
- return [context.payload.body];
- },
- async onDisable(context) {
- const webhook = await context.store.get<CreateWebhookResponse>(
- 'tarvent_contact_unsubscribed',
- );
- if (webhook != null) {
- const client = makeClient(context.auth);
- await client.deleteWebhook(webhook.data.createWebhook.id);
- }
- },
+ ...tarventWebhook.handlers({ type: 'contactUnsubscribed', storeKey: 'tarvent_contact_unsubscribed' }),
sampleData: {
"id": "000000000000000000",
"dateUtc": "2022-09-27T17:37:26.482913Z",
@@ -53,46 +39,34 @@ export const contactUnsubscribedTrigger = createTrigger({
},
"payload": {
"audienceId": "000000000000000000",
- "contact": {
- "id": "000000000000000000",
- "key": "[email protected]",
- "email": "[email protected]",
- "status": 1,
- "rating": 3,
- "firstName": "Kayla",
- "lastName": "Johnson",
- "streetAddress": "165 Caprice Court",
- "streetAddress2": "Suite A",
- "addressLocality": "Castle Rock",
- "addressRegion": "Colorado",
- "postalCode": "80109",
- "addressCountry": "United States",
- "latitude": 39.38363820960583,
- "longitude": -104.86229586128452,
- "timeZone": "Mountain Standard Time",
- "language": "en",
- "sendFormat": 1,
- "optInUtc": "2022-08-28T17:37:26.6236851Z",
- "optInSource": 6,
- "optInIp": "0.0.0.0",
- "confirmedUtc": "2022-08-29T17:37:26.6236972Z",
- "confirmedIp": "0.0.0.0",
- "optOutUtc": null,
- "optOutSource": null,
- "optOutIp": null,
- "optOutReason": "",
- "groups": [
- "359949389556096655",
- "359949389556097786"
- ],
- "tags": [
- "TarventTest",
- "TarventTest2",
- "TarventTest3"
- ],
- "profileFields": null,
- "createdUtc": "2022-08-28T17:37:26.6237782Z",
- "modifiedUtc": "2022-09-17T17:37:26.6237797Z"
+ contact: {
+ id: '1594408175877314400',
+ email: '[email protected]',
+ status: '1',
+ rating: '',
+ firstname: 'ApTest',
+ lastname: 'Example',
+ streetaddress: '',
+ streetaddress2: '',
+ addresslocality: '',
+ addressregion: '',
+ postalcode: '',
+ addresscountry: '',
+ longitude: '',
+ latitude: '',
+ language: '',
+ timezone: '',
+ sendformat: '1',
+ optinsource: '6',
+ optinip: '',
+ optinutc: '10/21/2026 20:44:25',
+ confirmedutc: '',
+ confirmedip: '',
+ createdutc: '10/21/2026 20:44:25',
+ modifiedutc: '10/21/2026 20:44:25',
+ groups: '[]',
+ tags: '[]',
}
}
},
diff --git a/packages/pieces/community/tarvent/src/lib/triggers/contact-updated.ts b/packages/pieces/community/tarvent/src/lib/triggers/contact-updated.ts
index 820dc8d88f0..891ef5d5ad1 100644
--- a/packages/pieces/community/tarvent/src/lib/triggers/contact-updated.ts
+++ b/packages/pieces/community/tarvent/src/lib/triggers/contact-updated.ts
@@ -1,7 +1,8 @@
import { TriggerStrategy, createTrigger } from '@activepieces/pieces-framework';
import { tarventAuth } from '../auth';
-import { makeClient, tarventCommon } from '../common';
-import { CreateWebhookResponse } from '../common/types';
+import { tarventCommon } from '../common';
+import { tarventWebhook } from '../common/webhook';
+import { tarventOutputSchemas } from '../output-schemas';
export const contactUpdatedTrigger = createTrigger({
auth: tarventAuth,
@@ -10,32 +11,17 @@ export const contactUpdatedTrigger = createTrigger({
displayName: 'Contact Profile Updated',
description: 'Triggers when a contact\'s profile is updated.',
aiMetadata: {
- description: 'Fires when a contact\'s profile fields are updated in Tarvent. Represents a change to an existing contact\'s details.',
+ description: 'Fires when a contact\'s profile fields are updated in Tarvent. Retried deliveries with the same event ID are ignored. Represents a change to an existing contact\'s details.',
},
type: TriggerStrategy.WEBHOOK,
+ outputSchema: tarventOutputSchemas.contactEvent,
props: {
include: tarventCommon.include,
audienceId: tarventCommon.audienceId(false, 'If specified, the trigger will only fire if contact is in the selected audience.'),
groupId: tarventCommon.audienceGroupId(false, 'If specified, the trigger will only fire if contact is in the selected group.'),
tagId: tarventCommon.tagId(false, 'If specified, the trigger will only fire if contact has the selected tag.')
},
- async onEnable(context) {
- const client = makeClient(context.auth);
- const res = await client.createWebhook(context, 'contactUpdated');
- await context.store.put<CreateWebhookResponse>('tarvent_contact_updated', res);
- },
- async run(context) {
- return [context.payload.body];
- },
- async onDisable(context) {
- const webhook = await context.store.get<CreateWebhookResponse>(
- 'tarvent_contact_updated',
- );
- if (webhook != null) {
- const client = makeClient(context.auth);
- await client.deleteWebhook(webhook.data.createWebhook.id);
- }
- },
+ ...tarventWebhook.handlers({ type: 'contactUpdated', storeKey: 'tarvent_contact_updated' }),
sampleData: {
"id": "000000000000000000",
"dateUtc": "2022-09-27T17:37:26.482913Z",
@@ -53,46 +39,34 @@ export const contactUpdatedTrigger = createTrigger({
},
"payload": {
"audienceId": "000000000000000000",
- "contact": {
- "id": "000000000000000000",
- "key": "[email protected]",
- "email": "[email protected]",
- "status": 1,
- "rating": 3,
- "firstName": "Kayla",
- "lastName": "Johnson",
- "streetAddress": "165 Caprice Court",
- "streetAddress2": "Suite A",
- "addressLocality": "Castle Rock",
- "addressRegion": "Colorado",
- "postalCode": "80109",
- "addressCountry": "United States",
- "latitude": 39.38363820960583,
- "longitude": -104.86229586128452,
- "timeZone": "Mountain Standard Time",
- "language": "en",
- "sendFormat": 1,
- "optInUtc": "2022-08-28T17:37:26.6236851Z",
- "optInSource": 6,
- "optInIp": "0.0.0.0",
- "confirmedUtc": "2022-08-29T17:37:26.6236972Z",
- "confirmedIp": "0.0.0.0",
- "optOutUtc": null,
- "optOutSource": null,
- "optOutIp": null,
- "optOutReason": "",
- "groups": [
- "359949389556096655",
- "359949389556097786"
- ],
- "tags": [
- "TarventTest",
- "TarventTest2",
- "TarventTest3"
- ],
- "profileFields": null,
- "createdUtc": "2022-08-28T17:37:26.6237782Z",
- "modifiedUtc": "2022-09-17T17:37:26.6237797Z"
+ contact: {
+ id: '1594408175877314400',
+ email: '[email protected]',
+ status: '1',
+ rating: '',
+ firstname: 'ApTest',
+ lastname: 'Example',
+ streetaddress: '',
+ streetaddress2: '',
+ addresslocality: '',
+ addressregion: '',
+ postalcode: '',
+ addresscountry: '',
+ longitude: '',
+ latitude: '',
+ language: '',
+ timezone: '',
+ sendformat: '1',
+ optinsource: '6',
+ optinip: '',
+ optinutc: '10/21/2026 20:44:25',
+ confirmedutc: '',
+ confirmedip: '',
+ createdutc: '10/21/2026 20:44:25',
+ modifiedutc: '10/21/2026 20:44:25',
+ groups: '[]',
+ tags: '[]',
}
}
},
diff --git a/packages/pieces/community/tarvent/src/lib/triggers/form-submitted.ts b/packages/pieces/community/tarvent/src/lib/triggers/form-submitted.ts
index 3c2c35a9e3b..f8b0cc38aab 100644
--- a/packages/pieces/community/tarvent/src/lib/triggers/form-submitted.ts
+++ b/packages/pieces/community/tarvent/src/lib/triggers/form-submitted.ts
@@ -1,7 +1,8 @@
import { TriggerStrategy, createTrigger } from '@activepieces/pieces-framework';
import { tarventAuth } from '../auth';
-import { makeClient, tarventCommon } from '../common';
-import { CreateWebhookResponse } from '../common/types';
+import { tarventCommon } from '../common';
+import { tarventWebhook } from '../common/webhook';
+import { tarventOutputSchemas } from '../output-schemas';
export const formSubmittedTrigger = createTrigger({
auth: tarventAuth,
@@ -10,9 +11,10 @@ export const formSubmittedTrigger = createTrigger({
displayName: 'Form Submission Received',
description: 'Triggers when a known or unknown contact submits a sign up, profile update, or other form.',
aiMetadata: {
- description: 'Fires when a known or unknown contact submits a Tarvent form (sign-up, profile update, or other). Represents a form submission and its captured data.',
+ description: 'Fires when a known or unknown contact submits a Tarvent form (sign-up, profile update, or other). Retried deliveries with the same event ID are ignored. Represents a form submission and its captured data.',
},
type: TriggerStrategy.WEBHOOK,
+ outputSchema: tarventOutputSchemas.formEvent,
props: {
include: tarventCommon.include,
audienceId: tarventCommon.audienceId(false, 'If specified, the trigger will only fire if contact is in the selected audience.'),
@@ -20,23 +22,7 @@ export const formSubmittedTrigger = createTrigger({
groupId: tarventCommon.audienceGroupId(false, 'If specified, the trigger will only fire if contact is in the selected group.'),
tagId: tarventCommon.tagId(false, 'If specified, the trigger will only fire if contact has the selected tag.')
},
- async onEnable(context) {
- const client = makeClient(context.auth);
- const res = await client.createWebhook(context, 'formSubmitted');
- await context.store.put<CreateWebhookResponse>('tarvent_form_submitted', res);
- },
- async run(context) {
- return [context.payload.body];
- },
- async onDisable(context) {
- const webhook = await context.store.get<CreateWebhookResponse>(
- 'tarvent_form_submitted',
- );
- if (webhook != null) {
- const client = makeClient(context.auth);
- await client.deleteWebhook(webhook.data.createWebhook.id);
- }
- },
+ ...tarventWebhook.handlers({ type: 'formSubmitted', storeKey: 'tarvent_form_submitted' }),
sampleData: {
"id": "000000000000000000",
"dateUtc": "2022-09-27T17:37:26.482913Z",
@@ -57,46 +43,34 @@ export const formSubmittedTrigger = createTrigger({
questionData: [{
"questionText": "Question answer"
}],
- "contact": {
- "id": "000000000000000000",
- "key": "[email protected]",
- "email": "[email protected]",
- "status": 1,
- "rating": 3,
- "firstName": "Kayla",
- "lastName": "Johnson",
- "streetAddress": "165 Caprice Court",
- "streetAddress2": "Suite A",
- "addressLocality": "Castle Rock",
- "addressRegion": "Colorado",
- "postalCode": "80109",
- "addressCountry": "United States",
- "latitude": 39.38363820960583,
- "longitude": -104.86229586128452,
- "timeZone": "Mountain Standard Time",
- "language": "en",
- "sendFormat": 1,
- "optInUtc": "2022-08-28T17:37:26.6236851Z",
- "optInSource": 6,
- "optInIp": "0.0.0.0",
- "confirmedUtc": "2022-08-29T17:37:26.6236972Z",
- "confirmedIp": "0.0.0.0",
- "optOutUtc": null,
- "optOutSource": null,
- "optOutIp": null,
- "optOutReason": "",
- "groups": [
- "359949389556096655",
- "359949389556097786"
- ],
- "tags": [
- "TarventTest",
- "TarventTest2",
- "TarventTest3"
- ],
- "profileFields": null,
- "createdUtc": "2022-08-28T17:37:26.6237782Z",
- "modifiedUtc": "2022-09-17T17:37:26.6237797Z"
+ contact: {
+ id: '1594408175877314400',
+ email: '[email protected]',
+ status: '1',
+ rating: '',
+ firstname: 'ApTest',
+ lastname: 'Example',
+ streetaddress: '',
+ streetaddress2: '',
+ addresslocality: '',
+ addressregion: '',
+ postalcode: '',
+ addresscountry: '',
+ longitude: '',
+ latitude: '',
+ language: '',
+ timezone: '',
+ sendformat: '1',
+ optinsource: '6',
+ optinip: '',
+ optinutc: '10/21/2026 20:44:25',
+ confirmedutc: '',
+ confirmedip: '',
+ createdutc: '10/21/2026 20:44:25',
+ modifiedutc: '10/21/2026 20:44:25',
+ groups: '[]',
+ tags: '[]',
}
}
},
diff --git a/packages/pieces/community/tarvent/src/lib/triggers/page-performed.ts b/packages/pieces/community/tarvent/src/lib/triggers/page-performed.ts
index db40367f25a..181a8c22ae3 100644
--- a/packages/pieces/community/tarvent/src/lib/triggers/page-performed.ts
+++ b/packages/pieces/community/tarvent/src/lib/triggers/page-performed.ts
@@ -1,7 +1,8 @@
import { TriggerStrategy, createTrigger } from '@activepieces/pieces-framework';
import { tarventAuth } from '../auth';
-import { makeClient, tarventCommon } from '../common';
-import { CreateWebhookResponse } from '../common/types';
+import { tarventCommon } from '../common';
+import { tarventWebhook } from '../common/webhook';
+import { tarventOutputSchemas } from '../output-schemas';
export const pagePerformedTrigger = createTrigger({
auth: tarventAuth,
@@ -10,9 +11,10 @@ export const pagePerformedTrigger = createTrigger({
displayName: 'Landing Page CTA Performed',
description: 'Triggers when a known or unknown contact performs a Call-To-Action within a landing page.',
aiMetadata: {
- description: 'Fires when a known or unknown contact performs a call-to-action on a Tarvent landing page. Represents a landing-page CTA interaction.',
+ description: 'Fires when a known or unknown contact performs a call-to-action on a Tarvent landing page. Retried deliveries with the same event ID are ignored. Represents a landing-page CTA interaction.',
},
type: TriggerStrategy.WEBHOOK,
+ outputSchema: tarventOutputSchemas.pageEvent,
props: {
include: tarventCommon.include,
landingPageId: tarventCommon.landingPageId,
@@ -20,23 +22,7 @@ export const pagePerformedTrigger = createTrigger({
groupId: tarventCommon.audienceGroupId(false, 'If specified, the trigger will only fire if contact is in the selected group.'),
tagId: tarventCommon.tagId(false, 'If specified, the trigger will only fire if contact has the selected tag.')
},
- async onEnable(context) {
- const client = makeClient(context.auth);
- const res = await client.createWebhook(context, 'landingPageCtaPerformed');
- await context.store.put<CreateWebhookResponse>('tarvent_page_performed', res);
- },
- async run(context) {
- return [context.payload.body];
- },
- async onDisable(context) {
- const webhook = await context.store.get<CreateWebhookResponse>(
- 'tarvent_page_performed',
- );
- if (webhook != null) {
- const client = makeClient(context.auth);
- await client.deleteWebhook(webhook.data.createWebhook.id);
- }
- },
+ ...tarventWebhook.handlers({ type: 'landingPageCtaPerformed', storeKey: 'tarvent_page_performed' }),
sampleData: {
"id": "000000000000000000",
"dateUtc": "2022-09-27T17:37:26.482913Z",
@@ -54,46 +40,34 @@ export const pagePerformedTrigger = createTrigger({
},
"payload": {
pageId: '000000000000000000',
- "contact": {
- "id": "000000000000000000",
- "key": "[email protected]",
- "email": "[email protected]",
- "status": 1,
- "rating": 3,
- "firstName": "Kayla",
- "lastName": "Johnson",
- "streetAddress": "165 Caprice Court",
- "streetAddress2": "Suite A",
- "addressLocality": "Castle Rock",
- "addressRegion": "Colorado",
- "postalCode": "80109",
- "addressCountry": "United States",
- "latitude": 39.38363820960583,
- "longitude": -104.86229586128452,
- "timeZone": "Mountain Standard Time",
- "language": "en",
- "sendFormat": 1,
- "optInUtc": "2022-08-28T17:37:26.6236851Z",
- "optInSource": 6,
- "optInIp": "0.0.0.0",
- "confirmedUtc": "2022-08-29T17:37:26.6236972Z",
- "confirmedIp": "0.0.0.0",
- "optOutUtc": null,
- "optOutSource": null,
- "optOutIp": null,
- "optOutReason": "",
- "groups": [
- "359949389556096655",
- "359949389556097786"
- ],
- "tags": [
- "TarventTest",
- "TarventTest2",
- "TarventTest3"
- ],
- "profileFields": null,
- "createdUtc": "2022-08-28T17:37:26.6237782Z",
- "modifiedUtc": "2022-09-17T17:37:26.6237797Z"
+ contact: {
+ id: '1594408175877314400',
+ email: '[email protected]',
+ status: '1',
+ rating: '',
+ firstname: 'ApTest',
+ lastname: 'Example',
+ streetaddress: '',
+ streetaddress2: '',
+ addresslocality: '',
+ addressregion: '',
+ postalcode: '',
+ addresscountry: '',
+ longitude: '',
+ latitude: '',
+ language: '',
+ timezone: '',
+ sendformat: '1',
+ optinsource: '6',
+ optinip: '',
+ optinutc: '10/21/2026 20:44:25',
+ confirmedutc: '',
+ confirmedip: '',
+ createdutc: '10/21/2026 20:44:25',
+ modifiedutc: '10/21/2026 20:44:25',
+ groups: '[]',
+ tags: '[]',
}
}
},
diff --git a/packages/pieces/community/tarvent/src/lib/triggers/survey-submitted.ts b/packages/pieces/community/tarvent/src/lib/triggers/survey-submitted.ts
index d900207619e..4dd7e91f1cd 100644
--- a/packages/pieces/community/tarvent/src/lib/triggers/survey-submitted.ts
+++ b/packages/pieces/community/tarvent/src/lib/triggers/survey-submitted.ts
@@ -1,7 +1,8 @@
import { tarventAuth } from '../auth';
import { TriggerStrategy, createTrigger } from '@activepieces/pieces-framework';
-import { makeClient, tarventCommon } from '../common';
-import { CreateWebhookResponse } from '../common/types';
+import { tarventCommon } from '../common';
+import { tarventWebhook } from '../common/webhook';
+import { tarventOutputSchemas } from '../output-schemas';
export const surveySubmittedTrigger = createTrigger({
auth: tarventAuth,
@@ -10,9 +11,10 @@ export const surveySubmittedTrigger = createTrigger({
displayName: 'Survey Submission Received',
description: 'Triggers when a known or unknown contact submits a survey.',
aiMetadata: {
- description: 'Fires when a known or unknown contact submits a Tarvent survey. Represents a survey submission and its responses.',
+ description: 'Fires when a known or unknown contact submits a Tarvent survey. Retried deliveries with the same event ID are ignored. Represents a survey submission and its responses.',
},
type: TriggerStrategy.WEBHOOK,
+ outputSchema: tarventOutputSchemas.pageEvent,
props: {
include: tarventCommon.include,
surveyId: tarventCommon.surveyId,
@@ -20,23 +22,7 @@ export const surveySubmittedTrigger = createTrigger({
groupId: tarventCommon.audienceGroupId(false, 'If specified, the trigger will only fire if contact is in the selected group.'),
tagId: tarventCommon.tagId(false, 'If specified, the trigger will only fire if contact has the selected tag.')
},
- async onEnable(context) {
- const client = makeClient(context.auth);
- const res = await client.createWebhook(context, 'surveySubmitted');
- await context.store.put<CreateWebhookResponse>('tarvent_survey_submitted', res);
- },
- async run(context) {
- return [context.payload.body];
- },
- async onDisable(context) {
- const webhook = await context.store.get<CreateWebhookResponse>(
- 'tarvent_survey_submitted',
- );
- if (webhook != null) {
- const client = makeClient(context.auth);
- await client.deleteWebhook(webhook.data.createWebhook.id);
- }
- },
+ ...tarventWebhook.handlers({ type: 'surveySubmitted', storeKey: 'tarvent_survey_submitted' }),
sampleData: {
"id": "000000000000000000",
"dateUtc": "2022-09-27T17:37:26.482913Z",
@@ -54,46 +40,34 @@ export const surveySubmittedTrigger = createTrigger({
},
"payload": {
pageId: '000000000000000000',
- "contact": {
- "id": "000000000000000000",
- "key": "[email protected]",
- "email": "[email protected]",
- "status": 1,
- "rating": 3,
- "firstName": "Kayla",
- "lastName": "Johnson",
- "streetAddress": "165 Caprice Court",
- "streetAddress2": "Suite A",
- "addressLocality": "Castle Rock",
- "addressRegion": "Colorado",
- "postalCode": "80109",
- "addressCountry": "United States",
- "latitude": 39.38363820960583,
- "longitude": -104.86229586128452,
- "timeZone": "Mountain Standard Time",
- "language": "en",
- "sendFormat": 1,
- "optInUtc": "2022-08-28T17:37:26.6236851Z",
- "optInSource": 6,
- "optInIp": "0.0.0.0",
- "confirmedUtc": "2022-08-29T17:37:26.6236972Z",
- "confirmedIp": "0.0.0.0",
- "optOutUtc": null,
- "optOutSource": null,
- "optOutIp": null,
- "optOutReason": "",
- "groups": [
- "359949389556096655",
- "359949389556097786"
- ],
- "tags": [
- "TarventTest",
- "TarventTest2",
- "TarventTest3"
- ],
- "profileFields": null,
- "createdUtc": "2022-08-28T17:37:26.6237782Z",
- "modifiedUtc": "2022-09-17T17:37:26.6237797Z"
+ contact: {
+ id: '1594408175877314400',
+ email: '[email protected]',
+ status: '1',
+ rating: '',
+ firstname: 'ApTest',
+ lastname: 'Example',
+ streetaddress: '',
+ streetaddress2: '',
+ addresslocality: '',
+ addressregion: '',
+ postalcode: '',
+ addresscountry: '',
+ longitude: '',
+ latitude: '',
+ language: '',
+ timezone: '',
+ sendformat: '1',
+ optinsource: '6',
+ optinip: '',
+ optinutc: '10/21/2026 20:44:25',
+ confirmedutc: '',
+ confirmedip: '',
+ createdutc: '10/21/2026 20:44:25',
+ modifiedutc: '10/21/2026 20:44:25',
+ groups: '[]',
+ tags: '[]',
}
}
},
diff --git a/packages/pieces/community/tarvent/src/lib/triggers/transaction-created.ts b/packages/pieces/community/tarvent/src/lib/triggers/transaction-created.ts
index f0ac31f20b4..c17319b50f4 100644
--- a/packages/pieces/community/tarvent/src/lib/triggers/transaction-created.ts
+++ b/packages/pieces/community/tarvent/src/lib/triggers/transaction-created.ts
@@ -1,7 +1,8 @@
import { TriggerStrategy, createTrigger } from '@activepieces/pieces-framework';
import { tarventAuth } from '../auth';
-import { makeClient, tarventCommon } from '../common';
-import { CreateWebhookResponse } from '../common/types';
+import { tarventCommon } from '../common';
+import { tarventWebhook } from '../common/webhook';
+import { tarventOutputSchemas } from '../output-schemas';
export const transactionCreatedTrigger = createTrigger({
auth: tarventAuth,
@@ -10,32 +11,17 @@ export const transactionCreatedTrigger = createTrigger({
displayName: 'Transaction Created',
description: 'Triggers when a transactional email is created for a known or unknown contact.',
aiMetadata: {
- description: 'Fires when a transactional email is created (queued) for a known or unknown contact, before it is sent. Represents a newly initiated transactional message.',
+ description: 'Fires when a transactional email is created (queued) for a known or unknown contact, before it is sent. Retried deliveries with the same event ID are ignored. Represents a newly initiated transactional message.',
},
type: TriggerStrategy.WEBHOOK,
+ outputSchema: tarventOutputSchemas.emailEvent,
props: {
include: tarventCommon.include,
audienceId: tarventCommon.audienceId(false, 'If specified, the trigger will only fire if contact is in the selected audience.'),
groupId: tarventCommon.audienceGroupId(false, 'If specified, the trigger will only fire if contact is in the selected group.'),
tagId: tarventCommon.tagId(false, 'If specified, the trigger will only fire if contact has the selected tag.')
},
- async onEnable(context) {
- const client = makeClient(context.auth);
- const res = await client.createWebhook(context, 'transactionCreated');
- await context.store.put<CreateWebhookResponse>('tarvent_transaction_created', res);
- },
- async run(context) {
- return [context.payload.body];
- },
- async onDisable(context) {
- const webhook = await context.store.get<CreateWebhookResponse>(
- 'tarvent_transaction_created',
- );
- if (webhook != null) {
- const client = makeClient(context.auth);
- await client.deleteWebhook(webhook.data.createWebhook.id);
- }
- },
+ ...tarventWebhook.handlers({ type: 'transactionCreated', storeKey: 'tarvent_transaction_created' }),
sampleData: {
"id": "000000000000000000",
"dateUtc": "2022-09-27T17:37:26.482913Z",
@@ -53,46 +39,34 @@ export const transactionCreatedTrigger = createTrigger({
},
"payload": {
"emailId": "000000000000000000",
- "contact": {
- "id": "000000000000000000",
- "key": "[email protected]",
- "email": "[email protected]",
- "status": 1,
- "rating": 3,
- "firstName": "Kayla",
- "lastName": "Johnson",
- "streetAddress": "165 Caprice Court",
- "streetAddress2": "Suite A",
- "addressLocality": "Castle Rock",
- "addressRegion": "Colorado",
- "postalCode": "80109",
- "addressCountry": "United States",
- "latitude": 39.38363820960583,
- "longitude": -104.86229586128452,
- "timeZone": "Mountain Standard Time",
- "language": "en",
- "sendFormat": 1,
- "optInUtc": "2022-08-28T17:37:26.6236851Z",
- "optInSource": 6,
- "optInIp": "0.0.0.0",
- "confirmedUtc": "2022-08-29T17:37:26.6236972Z",
- "confirmedIp": "0.0.0.0",
- "optOutUtc": null,
- "optOutSource": null,
- "optOutIp": null,
- "optOutReason": "",
- "groups": [
- "359949389556096655",
- "359949389556097786"
- ],
- "tags": [
- "TarventTest",
- "TarventTest2",
- "TarventTest3"
- ],
- "profileFields": null,
- "createdUtc": "2022-08-28T17:37:26.6237782Z",
- "modifiedUtc": "2022-09-17T17:37:26.6237797Z"
+ contact: {
+ id: '1594408175877314400',
+ email: '[email protected]',
+ status: '1',
+ rating: '',
+ firstname: 'ApTest',
+ lastname: 'Example',
+ streetaddress: '',
+ streetaddress2: '',
+ addresslocality: '',
+ addressregion: '',
+ postalcode: '',
+ addresscountry: '',
+ longitude: '',
+ latitude: '',
+ language: '',
+ timezone: '',
+ sendformat: '1',
+ optinsource: '6',
+ optinip: '',
+ optinutc: '10/21/2026 20:44:25',
+ confirmedutc: '',
+ confirmedip: '',
+ createdutc: '10/21/2026 20:44:25',
+ modifiedutc: '10/21/2026 20:44:25',
+ groups: '[]',
+ tags: '[]',
}
}
},
diff --git a/packages/pieces/community/tarvent/src/lib/triggers/transaction-sent.ts b/packages/pieces/community/tarvent/src/lib/triggers/transaction-sent.ts
index 52d4d4fc0bb..b74f5489b5d 100644
--- a/packages/pieces/community/tarvent/src/lib/triggers/transaction-sent.ts
+++ b/packages/pieces/community/tarvent/src/lib/triggers/transaction-sent.ts
@@ -1,7 +1,8 @@
import { TriggerStrategy, createTrigger } from '@activepieces/pieces-framework';
import { tarventAuth } from '../auth';
-import { makeClient, tarventCommon } from '../common';
-import { CreateWebhookResponse } from '../common/types';
+import { tarventCommon } from '../common';
+import { tarventWebhook } from '../common/webhook';
+import { tarventOutputSchemas } from '../output-schemas';
export const transactionSentTrigger = createTrigger({
auth: tarventAuth,
@@ -10,32 +11,17 @@ export const transactionSentTrigger = createTrigger({
displayName: 'Transaction Sent',
description: 'Triggers when a transactional email is processed and sent to one or more recipients.',
aiMetadata: {
- description: 'Fires when a transactional email is processed and delivered to one or more recipients. Represents a completed transactional send.',
+ description: 'Fires when a transactional email is processed and delivered to one or more recipients. Retried deliveries with the same event ID are ignored. Represents a completed transactional send.',
},
type: TriggerStrategy.WEBHOOK,
+ outputSchema: tarventOutputSchemas.emailEvent,
props: {
include: tarventCommon.include,
audienceId: tarventCommon.audienceId(false, 'If specified, the trigger will only fire if contact is in the selected audience.'),
groupId: tarventCommon.audienceGroupId(false, 'If specified, the trigger will only fire if contact is in the selected group.'),
tagId: tarventCommon.tagId(false, 'If specified, the trigger will only fire if contact has the selected tag.')
},
- async onEnable(context) {
- const client = makeClient(context.auth);
- const res = await client.createWebhook(context, 'transactionSent');
- await context.store.put<CreateWebhookResponse>('tarvent_transaction_sent', res);
- },
- async run(context) {
- return [context.payload.body];
- },
- async onDisable(context) {
- const webhook = await context.store.get<CreateWebhookResponse>(
- 'tarvent_transaction_sent',
- );
- if (webhook != null) {
- const client = makeClient(context.auth);
- await client.deleteWebhook(webhook.data.createWebhook.id);
- }
- },
+ ...tarventWebhook.handlers({ type: 'transactionSent', storeKey: 'tarvent_transaction_sent' }),
sampleData: {
"id": "000000000000000000",
"dateUtc": "2022-09-27T17:37:26.482913Z",
@@ -53,46 +39,34 @@ export const transactionSentTrigger = createTrigger({
},
"payload": {
"emailId": "000000000000000000",
- "contact": {
- "id": "000000000000000000",
- "key": "[email protected]",
- "email": "[email protected]",
- "status": 1,
- "rating": 3,
- "firstName": "Kayla",
- "lastName": "Johnson",
- "streetAddress": "165 Caprice Court",
- "streetAddress2": "Suite A",
- "addressLocality": "Castle Rock",
- "addressRegion": "Colorado",
- "postalCode": "80109",
- "addressCountry": "United States",
- "latitude": 39.38363820960583,
- "longitude": -104.86229586128452,
- "timeZone": "Mountain Standard Time",
- "language": "en",
- "sendFormat": 1,
- "optInUtc": "2022-08-28T17:37:26.6236851Z",
- "optInSource": 6,
- "optInIp": "0.0.0.0",
- "confirmedUtc": "2022-08-29T17:37:26.6236972Z",
- "confirmedIp": "0.0.0.0",
- "optOutUtc": null,
- "optOutSource": null,
- "optOutIp": null,
- "optOutReason": "",
- "groups": [
- "359949389556096655",
- "359949389556097786"
- ],
- "tags": [
- "TarventTest",
- "TarventTest2",
- "TarventTest3"
- ],
- "profileFields": null,
- "createdUtc": "2022-08-28T17:37:26.6237782Z",
- "modifiedUtc": "2022-09-17T17:37:26.6237797Z"
+ contact: {
+ id: '1594408175877314400',
+ email: '[email protected]',
+ status: '1',
+ rating: '',
+ firstname: 'ApTest',
+ lastname: 'Example',
+ streetaddress: '',
+ streetaddress2: '',
+ addresslocality: '',
+ addressregion: '',
+ postalcode: '',
+ addresscountry: '',
+ longitude: '',
+ latitude: '',
+ language: '',
+ timezone: '',
+ sendformat: '1',
+ optinsource: '6',
+ optinip: '',
+ optinutc: '10/21/2026 20:44:25',
+ confirmedutc: '',
+ confirmedip: '',
+ createdutc: '10/21/2026 20:44:25',
+ modifiedutc: '10/21/2026 20:44:25',
+ groups: '[]',
+ tags: '[]',
}
}
},
diff --git a/packages/pieces/community/tarvent/test/actions.test.ts b/packages/pieces/community/tarvent/test/actions.test.ts
new file mode 100644
index 00000000000..1981916a482
--- /dev/null
+++ b/packages/pieces/community/tarvent/test/actions.test.ts
@@ -0,0 +1,241 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { httpError, ok, runAction, TEST_AUTH } from './helpers';
+
+const sendRequest = vi.fn();
+
+vi.mock('@activepieces/pieces-common', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@activepieces/pieces-common')>();
+ return { ...actual, httpClient: { sendRequest: (...args: unknown[]) => sendRequest(...args) } };
+});
+
+import { tarventAuth } from '../src/lib/auth';
+import { createAudienceGroup } from '../src/lib/actions/create-audience-group';
+import { createContact } from '../src/lib/actions/create-contact';
+import { createContactNote } from '../src/lib/actions/create-contact-note';
+import { createSuppressionFilter } from '../src/lib/actions/create-suppression-filter';
+import { createTransaction, createTransactionAi } from '../src/lib/actions/create-transaction';
+import { tarventCustomApiCall } from '../src/lib/actions/custom-api-call';
+import { getContact } from '../src/lib/actions/get-contact';
+import { getJourney } from '../src/lib/actions/get-journey';
+import { removeSuppressionFilter } from '../src/lib/actions/remove-suppression-filter';
+import { sendCampaign } from '../src/lib/actions/send-campaign';
+import { updateContact } from '../src/lib/actions/update-contact';
+import { updateContactTags } from '../src/lib/actions/update-contact-tag';
+import { tarvent } from '../src';
+
+const UNAUTHORIZED = { errors: [{ message: 'The current user is not authorized to access this resource.', extensions: { code: '1020' } }], data: { audiences: null } };
+
+function validate(): Promise<unknown> {
+ return Reflect.apply(tarventAuth.validate ?? (() => undefined), tarventAuth, [{ auth: TEST_AUTH.props, server: { apiUrl: '', publicUrl: '' } }]);
+}
+
+function call(index = 0) {
+ return sendRequest.mock.calls[index][0];
+}
+
+beforeEach(() => {
+ sendRequest.mockReset();
+});
+
+describe('transport', () => {
+ it('sends trimmed key and account headers to the GraphQL endpoint with TLS verification', async () => {
+ sendRequest.mockResolvedValueOnce(ok({ data: { contact: { id: 'c1' } } }));
+ await runAction({ action: getContact, propsValue: { audienceId: 'a1', contactId: 'c1' } });
+ const request = call();
+ expect(request.url).toBe('https://api.tarvent.com/graphql');
+ expect(request.method).toBe('POST');
+ expect(request.headers).toMatchObject({ 'x-api-key': 'key_1', account: 'acc_1', 'Content-Type': 'application/json' });
+ expect(request.body.variables).toEqual({ input: { audienceId: 'a1', emailAddress: null, id: 'c1' } });
+ expect(sendRequest.mock.calls[0][1].dispatcher).toBeDefined();
+ });
+
+ it('fails a 200 response that carries GraphQL errors', async () => {
+ sendRequest.mockResolvedValueOnce(ok({ errors: [{ message: "NotFound: Entity 'Audience' was not found.", extensions: { code: '1030' } }], data: { createContact: null } }));
+ await expect(runAction({ action: createContact, propsValue: { audienceId: 'a1', email: '[email protected]', updateAction: 'Update' } })).rejects.toThrow(/Entity 'Audience' was not found.*1030/);
+ });
+
+ it('maps the unauthorized message (not the shared 1020 code) to invalid credentials', async () => {
+ sendRequest.mockResolvedValueOnce(ok(UNAUTHORIZED));
+ await expect(runAction({ action: getJourney, propsValue: {} })).rejects.toThrow(/Invalid Tarvent API key or account ID/);
+ sendRequest.mockResolvedValueOnce(ok({ errors: [{ message: 'The maximum allowed items per page were exceeded.', extensions: { code: '1020' } }] }));
+ await expect(runAction({ action: getJourney, propsValue: {} })).rejects.toThrow(/maximum allowed items/);
+ });
+
+ it('explains missing key permissions (code 1070)', async () => {
+ sendRequest.mockResolvedValueOnce(ok({ errors: [{ message: 'BadRequest: Unauthorized. User does not have appropriate rights to grant access.', extensions: { code: '1070' } }] }));
+ await expect(runAction({ action: getJourney, propsValue: {} })).rejects.toThrow(/does not have permission/);
+ });
+
+ it('maps HTTP 401 to invalid credentials', async () => {
+ sendRequest.mockRejectedValueOnce(httpError({ status: 401, body: {} }));
+ await expect(runAction({ action: getJourney, propsValue: {} })).rejects.toThrow(/Invalid Tarvent API key/);
+ });
+});
+
+describe('auth.validate', () => {
+ it('rejects a key that Tarvent answers with 200 + unauthorized error', async () => {
+ sendRequest.mockResolvedValueOnce(ok(UNAUTHORIZED));
+ const result = await validate();
+ expect(result).toEqual({ valid: false, error: expect.stringMatching(/Invalid Tarvent API key/) });
+ });
+
+ it('accepts a working key', async () => {
+ sendRequest.mockResolvedValueOnce(ok({ data: { audiences: { nodes: [] } } }));
+ const result = await validate();
+ expect(result).toEqual({ valid: true });
+ });
+
+ it('accepts a key that lacks permission to read audiences (code 1070)', async () => {
+ sendRequest.mockResolvedValueOnce(ok({ errors: [{ message: 'BadRequest: Unauthorized. User does not have appropriate rights to grant access.', extensions: { code: '1070' } }] }));
+ const result = await validate();
+ expect(result).toEqual({ valid: true });
+ });
+
+ it('stores the API key as a secret', () => {
+ expect(tarventAuth.props.apiKey.type).toBe('SECRET_TEXT');
+ });
+});
+
+describe('actions', () => {
+ it('Find Journey asks for a full page and returns paging info', async () => {
+ sendRequest.mockResolvedValueOnce(ok({ data: { journeys: { nodes: [{ id: 'j1' }, { id: 'j2' }], pageInfo: { hasNextPage: true, endCursor: 'cur2' } } } }));
+ const result = await runAction({ action: getJourney, propsValue: { name: 'Welcome', status: 'RUNNING' } });
+ expect(call().body.variables.first).toBe(50);
+ expect(call().body.variables.where).toEqual({ and: [{ name: { contains: 'Welcome' } }, { status: { in: ['RUNNING'] } }] });
+ expect(result).toMatchObject({ count: 2, hasMore: true, nextCursor: 'cur2' });
+ });
+
+ it('Find Contact needs exactly one of email or ID and reports not found', async () => {
+ await expect(runAction({ action: getContact, propsValue: { audienceId: 'a1' } })).rejects.toThrow(/exactly one/);
+ sendRequest
+ .mockResolvedValueOnce(ok({ errors: [{ message: 'NotFound: No contact not found.', extensions: { code: '1030' } }], data: { contact: null } }))
+ .mockResolvedValueOnce(ok({ data: { contacts: { nodes: [], pageInfo: { hasNextPage: false } } } }));
+ await expect(runAction({ action: getContact, propsValue: { audienceId: 'a1', email: '[email protected]' } })).resolves.toEqual({ found: false, contact: null });
+ expect(call(1).body.variables).toMatchObject({ input: { audienceId: 'a1' }, first: 1 });
+ });
+
+ it('Find Contact fails when the audience itself is missing or not granted', async () => {
+ sendRequest
+ .mockResolvedValueOnce(ok({ errors: [{ message: 'NotFound: No contact not found.', extensions: { code: '1030' } }], data: { contact: null } }))
+ .mockResolvedValueOnce(ok({ errors: [{ message: 'BadRequest: Access to audience has not been granted', extensions: { code: '1090' } }] }));
+ await expect(runAction({ action: getContact, propsValue: { audienceId: 'gone', email: '[email protected]' } })).rejects.toThrow(/Access to audience/);
+ sendRequest.mockResolvedValueOnce(ok({ errors: [{ message: "NotFound: Entity 'Audience' was not found.", extensions: { code: '1030' } }] }));
+ await expect(runAction({ action: getContact, propsValue: { audienceId: 'gone', email: '[email protected]' } })).rejects.toThrow(/Audience/);
+ });
+
+ it('Find Contact keeps treating an email value without @ as a contact ID', async () => {
+ sendRequest.mockResolvedValueOnce(ok({ data: { contact: { id: 'c9' } } }));
+ await runAction({ action: getContact, propsValue: { audienceId: 'a1', email: 'c9' } });
+ expect(call().body.variables.input).toEqual({ audienceId: 'a1', emailAddress: null, id: 'c9' });
+ });
+
+ it('Create Audience Group works without a description', async () => {
+ sendRequest.mockResolvedValueOnce(ok({ data: { createAudienceGroup: { id: 'g1', name: 'VIP', description: '', isPublic: false, isDynamic: false } } }));
+ const result = await runAction({ action: createAudienceGroup, propsValue: { audienceId: 'a1', name: 'VIP', isPublic: 'false' } });
+ expect(result).toMatchObject({ id: 'g1' });
+ expect(call().body.variables.input).toMatchObject({ name: 'VIP', description: '', isPublic: false, audienceId: 'a1' });
+ });
+
+ it('Create/Update Contact unwraps the contact and does not send empty fields', async () => {
+ sendRequest.mockResolvedValueOnce(ok({ data: { createContact: { id: 'c1', email: '[email protected]' } } }));
+ const result = await runAction({ action: createContact, propsValue: { audienceId: 'a1', email: '[email protected]', updateAction: 'Update', firstName: '', lastName: 'Doe', audienceDataFields: { f1: '1', f2: '' } } });
+ expect(result).toEqual({ id: 'c1', email: '[email protected]' });
+ const input = call().body.variables.input;
+ expect(input).not.toHaveProperty('firstName');
+ expect(input).toMatchObject({ lastName: 'Doe', updateExisting: true, profile: [{ dataFieldId: 'f1', value: '1' }] });
+ });
+
+ it('Update Contact sends only the set fields', async () => {
+ sendRequest.mockResolvedValueOnce(ok({ data: { updateContact: { id: 'c1' } } }));
+ await runAction({ action: updateContact, propsValue: { audienceId: 'a1', contactId: 'c1', firstName: 'Ann', lastName: '' } });
+ expect(call().body.variables.input).toEqual({ id: 'c1', audienceId: 'a1', firstName: 'Ann' });
+ await expect(runAction({ action: updateContact, propsValue: { audienceId: 'a1', contactId: 'c1' } })).rejects.toThrow(/Nothing to update/);
+ });
+
+ it('Add Note To Contact does not report the contact ID as a note ID', async () => {
+ sendRequest.mockResolvedValueOnce(ok({ data: { createContactNote: { id: 'c1' } } }));
+ await expect(runAction({ action: createContactNote, propsValue: { contactId: 'c1', note: 'Hi' } })).resolves.toEqual({ success: true, contactId: 'c1', message: 'Hi' });
+ });
+
+ it('Add/Remove Contact Tag maps the legacy lower-case remove value', async () => {
+ sendRequest.mockResolvedValueOnce(ok({ data: { updateContactTags: true } }));
+ const result = await runAction({ action: updateContactTags, propsValue: { audienceId: 'a1', contactId: 'c1', action: 'remove', tagIds: ['VIP'] } });
+ expect(call().body.variables.input).toEqual({ id: 'c1', audienceId: 'a1', operator: 'REMOVE', tags: ['VIP'] });
+ expect(result).toEqual({ success: true, contactId: 'c1', action: 'REMOVE', tags: ['VIP'] });
+ });
+
+ it('Add Contact To Suppression List splits the email at the last @', async () => {
+ sendRequest.mockResolvedValueOnce(ok({ data: { createAccountSuppressionFilter: { id: 's1', localPart: 'a@b', domain: 'example.com' } } }));
+ await runAction({ action: createSuppressionFilter, propsValue: { email: 'a@[email protected]' } });
+ expect(call().body.variables.input).toEqual({ localPart: 'a@b', domain: 'example.com', reason: '' });
+ });
+
+ it('Remove From Suppression List deletes every exact match', async () => {
+ sendRequest
+ .mockResolvedValueOnce(ok({ data: { accountSuppressionFilters: { nodes: [{ id: 's1', localPart: 'a', domain: 'example.com' }], pageInfo: { hasNextPage: false } } } }))
+ .mockResolvedValueOnce(ok({ data: { deleteAccountSuppressionFilter: true } }));
+ const result = await runAction({ action: removeSuppressionFilter, propsValue: { email: '[email protected]' } });
+ expect(result).toEqual({ removed: 1, filterIds: ['s1'] });
+ expect(call(1).body.variables).toEqual({ id: 's1' });
+ });
+
+ it('Send A Transactional Email fails when Tarvent rejects the TO recipient', async () => {
+ sendRequest.mockResolvedValueOnce(ok({ data: { createTransaction: [{ emailAddress: '[email protected]', errorCode: '500', errorMsg: 'Suppressed', requestId: 'r1', transactionId: null }] } }));
+ await expect(
+ runAction({ action: createTransaction, propsValue: { fromEmail: '[email protected]', toEmail: '[email protected]', subject: 'Hi', replyToEmail: '[email protected]', content: '<p>x</p>', mimeType: 'HTML' } }),
+ ).rejects.toThrow(/did not send the email to [email protected]: Suppressed/);
+ });
+
+ it('Send A Transactional Email needs a template or content', async () => {
+ await expect(
+ runAction({ action: createTransaction, propsValue: { fromEmail: '[email protected]', toEmail: '[email protected]', subject: 'Hi', replyToEmail: '[email protected]' } }),
+ ).rejects.toThrow(/Template or enter Content/);
+ expect(sendRequest).not.toHaveBeenCalled();
+ });
+
+ it('Send A Transactional Email returns per-recipient results', async () => {
+ sendRequest.mockResolvedValueOnce(ok({ data: { createTransaction: [
+ { emailAddress: '[email protected]', errorCode: null, errorMsg: null, requestId: 'r1', transactionId: 't1' },
+ { emailAddress: '[email protected]', errorCode: '9', errorMsg: 'Bad', requestId: 'r1', transactionId: null },
+ ] } }));
+ const result = await runAction({ action: createTransaction, propsValue: { fromEmail: '[email protected]', toEmail: '[email protected]', ccEmail: [{ email: '[email protected]' }], subject: 'Hi', replyToEmail: '[email protected]', templateId: 'tpl1' } });
+ expect(result).toMatchObject({ requestId: 'r1', transactionId: 't1', recipients: [{ sent: true }, { sent: false, errorMsg: 'Bad' }] });
+ expect(call().body.variables.input.recipients.map((r: { type: string }) => r.type)).toEqual(['TO', 'CC']);
+ expect(call().body.variables.input.settings).toEqual({ ignoreSuppressCheck: false });
+ });
+
+ it('the AI transactional email cannot ignore suppression filters', async () => {
+ expect(createTransaction.audience).toBe('human');
+ expect(createTransactionAi.audience).toBe('ai');
+ expect(Object.keys(createTransactionAi.props)).not.toContain('ignoreSuppressCheck');
+ expect(Object.keys(createTransaction.props)).toContain('ignoreSuppressCheck');
+ sendRequest.mockResolvedValueOnce(ok({ data: { createTransaction: [{ emailAddress: '[email protected]', requestId: 'r1', transactionId: 't1' }] } }));
+ await runAction({ action: createTransactionAi, propsValue: { fromEmail: '[email protected]', toEmail: '[email protected]', subject: 'Hi', replyToEmail: '[email protected]', templateId: 'tpl1', ignoreSuppressCheck: 'true' } });
+ expect(call().body.variables.input.settings).toEqual({ ignoreSuppressCheck: false });
+ });
+
+ it('Send Campaign is human-only and fails when Tarvent does not confirm the send', async () => {
+ expect(sendCampaign.audience).toBe('human');
+ sendRequest.mockResolvedValueOnce(ok({ data: { sendCampaignCopy: null } }));
+ await expect(runAction({ action: sendCampaign, propsValue: { campaignId: 'c1' } })).rejects.toThrow(/returned no result/);
+ });
+
+ it('Custom API Call refuses other hosts', async () => {
+ for (const url of ['https://api.tarvent.com.evil.io/graphql', '//evil.io/x', 'https://[email protected]/graphql', 'http://api.tarvent.com/graphql', '/a/../b']) {
+ await expect(runAction({ action: tarventCustomApiCall, propsValue: { method: 'POST', url: { url } } })).rejects.toThrow();
+ }
+ expect(sendRequest).not.toHaveBeenCalled();
+ });
+});
+
+describe('piece metadata', () => {
+ it('every action and trigger has an output schema and AI metadata', () => {
+ for (const action of Object.values(tarvent.actions())) {
+ expect(action.outputSchema, action.name).toBeDefined();
+ expect(action.aiMetadata?.description, action.name).toBeTruthy();
+ }
+ for (const trigger of Object.values(tarvent.triggers())) {
+ expect(trigger.outputSchema, trigger.name).toBeDefined();
+ }
+ });
+});
diff --git a/packages/pieces/community/tarvent/test/ai.test.ts b/packages/pieces/community/tarvent/test/ai.test.ts
new file mode 100644
index 00000000000..6ad5ac94388
--- /dev/null
+++ b/packages/pieces/community/tarvent/test/ai.test.ts
@@ -0,0 +1,107 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { ok, runAction } from './helpers';
+
+const sendRequest = vi.fn();
+
+vi.mock('@activepieces/pieces-common', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@activepieces/pieces-common')>();
+ return { ...actual, httpClient: { sendRequest: (...args: unknown[]) => sendRequest(...args) } };
+});
+
+import { tarvent } from '../src';
+import { upsertContactAi } from '../src/lib/actions/ai/upsert-contact-ai';
+import { updateContactAi } from '../src/lib/actions/ai/update-contact-ai';
+import { setContactTagsAi } from '../src/lib/actions/ai/set-contact-tags-ai';
+import { setContactGroupMembershipAi } from '../src/lib/actions/ai/set-contact-group-membership-ai';
+import { setJourneyStatusAi } from '../src/lib/actions/ai/set-journey-status-ai';
+import { findContactAi } from '../src/lib/actions/ai/find-contact-ai';
+
+function call(index = 0) {
+ return sendRequest.mock.calls[index][0];
+}
+
+beforeEach(() => {
+ sendRequest.mockReset();
+});
+
+describe('audience split', () => {
+ it('has 13 ai, 16 human and 11 both actions', () => {
+ const actions = Object.values(tarvent.actions());
+ const count = (audience: string) => actions.filter((a) => a.audience === audience).length;
+ expect({ ai: count('ai'), human: count('human'), both: count('both') }).toEqual({ ai: 13, human: 16, both: 11 });
+ });
+
+ it('agent tools take plain text IDs, never dropdowns', () => {
+ for (const action of Object.values(tarvent.actions()).filter((a) => a.audience === 'ai')) {
+ for (const [key, prop] of Object.entries(action.props)) {
+ expect(['DROPDOWN', 'MULTI_SELECT_DROPDOWN', 'DYNAMIC'], `${action.name}.${key}`).not.toContain(prop.type);
+ }
+ }
+ });
+
+ it('keeps Send Campaign and the suppression bypass away from agents', () => {
+ const agentNames = Object.values(tarvent.actions()).filter((a) => a.audience !== 'human').map((a) => a.name);
+ expect(agentNames).not.toContain('tarvent_send_campaign');
+ expect(agentNames).not.toContain('tarvent_create_transaction');
+ expect(agentNames).not.toContain('tarvent_remove_suppression_filter');
+ });
+});
+
+describe('ai tools', () => {
+ it('Create or Update Contact (AI) only ever adds groups and tags', async () => {
+ sendRequest.mockResolvedValueOnce(ok({ data: { createContact: { id: 'c1' } } }));
+ await runAction({ action: upsertContactAi, propsValue: { audienceId: 'a1', email: '[email protected]', firstName: ' Ann ', lastName: '', tags: 'VIP, ', groupIds: 'g1', customFields: { f1: '1' } } });
+ expect(call().body.variables.input).toEqual({
+ firstName: 'Ann',
+ email: '[email protected]',
+ audienceId: 'a1',
+ updateExisting: true,
+ audienceGroupManagementType: 'ADD_NEW_GROUPS_ONLY',
+ tagManagementType: 'ADD_NEW_TAGS_ONLY',
+ profile: [{ dataFieldId: 'f1', value: '1' }],
+ tags: ['VIP'],
+ groupIds: ['g1'],
+ sendFormat: 'MULTIPART',
+ });
+ });
+
+ it('Create or Update Contact (AI) updates by default and fails only when asked', async () => {
+ sendRequest.mockResolvedValueOnce(ok({ data: { createContact: { id: 'c1' } } }));
+ await runAction({ action: upsertContactAi, propsValue: { audienceId: 'a1', email: '[email protected]', groupIds: '', tags: '' } });
+ expect(call().body.variables.input).toMatchObject({ updateExisting: true });
+ expect(call().body.variables.input).not.toHaveProperty('tags');
+ expect(call().body.variables.input).not.toHaveProperty('groupIds');
+ sendRequest.mockResolvedValueOnce(ok({ data: { createContact: { id: 'c1' } } }));
+ await runAction({ action: upsertContactAi, propsValue: { audienceId: 'a1', email: '[email protected]', ifExists: 'FAIL' } });
+ expect(call(1).body.variables.input).toMatchObject({ updateExisting: false });
+ });
+
+ it('Update Contact (AI) sends only the given fields and refuses an empty update', async () => {
+ sendRequest.mockResolvedValueOnce(ok({ data: { updateContact: { id: 'c1' } } }));
+ await runAction({ action: updateContactAi, propsValue: { audienceId: 'a1', contactId: 'c1', email: '[email protected]' } });
+ expect(call().body.variables.input).toEqual({ id: 'c1', audienceId: 'a1', email: '[email protected]' });
+ await expect(runAction({ action: updateContactAi, propsValue: { audienceId: 'a1', contactId: 'c1' } })).rejects.toThrow(/Nothing to update/);
+ });
+
+ it('Add or Remove Contact Tags (AI) maps the enum', async () => {
+ sendRequest.mockResolvedValueOnce(ok({ data: { updateContactTags: true } }));
+ await runAction({ action: setContactTagsAi, propsValue: { audienceId: 'a1', contactId: 'c1', tags: ['A'], action: 'REMOVE' } });
+ expect(call().body.variables.input).toEqual({ id: 'c1', audienceId: 'a1', operator: 'REMOVE', tags: ['A'] });
+ });
+
+ it('Add or Remove Contact From Group (AI) uses the right mutation', async () => {
+ sendRequest.mockResolvedValueOnce(ok({ data: { deleteGroupContact: { id: 'x' } } }));
+ const result = await runAction({ action: setContactGroupMembershipAi, propsValue: { audienceId: 'a1', groupId: 'g1', contactId: 'c1', action: 'REMOVE' } });
+ expect(call().body.query).toContain('deleteGroupContact');
+ expect(result).toMatchObject({ action: 'REMOVE', groupId: 'g1' });
+ });
+
+ it('Start or Stop Journey (AI) fails when Tarvent does not confirm', async () => {
+ sendRequest.mockResolvedValueOnce(ok({ data: { startJourney: false } }));
+ await expect(runAction({ action: setJourneyStatusAi, propsValue: { journeyId: 'j1', action: 'START' } })).rejects.toThrow(/did not confirm startJourney/);
+ });
+
+ it('Find Contact (AI) needs exactly one identifier', async () => {
+ await expect(runAction({ action: findContactAi, propsValue: { audienceId: 'a1' } })).rejects.toThrow(/exactly one/);
+ });
+});
diff --git a/packages/pieces/community/tarvent/test/helpers.ts b/packages/pieces/community/tarvent/test/helpers.ts
new file mode 100644
index 00000000000..5f812a9a826
--- /dev/null
+++ b/packages/pieces/community/tarvent/test/helpers.ts
@@ -0,0 +1,41 @@
+import { HttpError } from '@activepieces/pieces-common';
+import { AppConnectionType, createMockActionContext, InputPropertyMap, Store } from '@activepieces/pieces-framework';
+
+export const TEST_AUTH = { type: AppConnectionType.CUSTOM_AUTH, props: { accountId: ' acc_1 ', apiKey: ' key_1 ' } } as const;
+
+export function runAction({ action, propsValue }: { action: { run: unknown }; propsValue: Record<string, unknown> }): Promise<unknown> {
+ const base = createMockActionContext<InputPropertyMap>({ propsValue: {} });
+ const run = action.run;
+ if (typeof run !== 'function') {
+ throw new Error('action has no run');
+ }
+ return Reflect.apply(run, action, [{ ...base, propsValue, auth: TEST_AUTH }]);
+}
+
+export function httpError({ status, body }: { status: number; body: unknown }) {
+ return new HttpError({}, { status, responseBody: body });
+}
+
+export function ok(body: unknown) {
+ return { status: 200, headers: {}, body };
+}
+
+export function memoryStore({ failPut = false }: { failPut?: boolean } = {}): Store & { data: Map<string, unknown> } {
+ const data = new Map<string, unknown>();
+ return {
+ data,
+ async put<T>(key: string, value: T): Promise<T> {
+ if (failPut) {
+ throw new Error('store down');
+ }
+ data.set(key, value);
+ return value;
+ },
+ async get<T>(key: string): Promise<T | null> {
+ return data.has(key) ? JSON.parse(JSON.stringify(data.get(key))) : null;
+ },
+ async delete(key: string): Promise<void> {
+ data.delete(key);
+ },
+ };
+}
diff --git a/packages/pieces/community/tarvent/test/webhook.test.ts b/packages/pieces/community/tarvent/test/webhook.test.ts
new file mode 100644
index 00000000000..7ac8f7e92d2
--- /dev/null
+++ b/packages/pieces/community/tarvent/test/webhook.test.ts
@@ -0,0 +1,113 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { memoryStore, ok, TEST_AUTH } from './helpers';
+
+const sendRequest = vi.fn();
+
+vi.mock('@activepieces/pieces-common', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@activepieces/pieces-common')>();
+ return { ...actual, httpClient: { sendRequest: (...args: unknown[]) => sendRequest(...args) } };
+});
+
+import { tarventWebhook } from '../src/lib/common/webhook';
+import { tarventCommon } from '../src/lib/common';
+
+beforeEach(() => {
+ sendRequest.mockReset();
+});
+
+const handlers = tarventWebhook.handlers({ type: 'contactAdded', storeKey: 'tarvent_contact_added' });
+
+describe('webhook lifecycle', () => {
+ it('stores the created webhook id', async () => {
+ sendRequest.mockResolvedValueOnce(ok({ data: { createWebhook: { id: 'w1' } } }));
+ const store = memoryStore();
+ await handlers.onEnable({ auth: TEST_AUTH, propsValue: { include: 'BASIC' }, webhookUrl: 'https://hook', store });
+ expect(store.data.get('tarvent_contact_added')).toEqual({ id: 'w1' });
+ expect(sendRequest.mock.calls[0][0].body.variables).toMatchObject({ callBackUrl: 'https://hook', events: [{ entityType: null, eventType: 'CONTACT_ADDED' }], filter: null, dataSettings: 'BASIC' });
+ });
+
+ it('fails onEnable when Tarvent returns an error, storing nothing', async () => {
+ sendRequest.mockResolvedValueOnce(ok({ errors: [{ message: 'BadRequest' }], data: { createWebhook: null } }));
+ const store = memoryStore();
+ await expect(handlers.onEnable({ auth: TEST_AUTH, propsValue: {}, webhookUrl: 'https://hook', store })).rejects.toThrow(/BadRequest/);
+ expect(store.data.size).toBe(0);
+ });
+
+ it('deletes the webhook when the store write fails', async () => {
+ sendRequest.mockResolvedValueOnce(ok({ data: { createWebhook: { id: 'w1' } } })).mockResolvedValueOnce(ok({ data: { deleteWebhook: true } }));
+ await expect(handlers.onEnable({ auth: TEST_AUTH, propsValue: {}, webhookUrl: 'https://hook', store: memoryStore({ failPut: true }) })).rejects.toThrow('store down');
+ expect(sendRequest.mock.calls[1][0].body.variables).toEqual({ id: 'w1' });
+ });
+
+ it('deletes legacy-shaped stored webhooks and treats not found as gone', async () => {
+ sendRequest.mockResolvedValueOnce(ok({ errors: [{ message: "NotFound: Entity 'Webhook' was not found.", extensions: { code: '1030' } }], data: { deleteWebhook: null } }));
+ const store = memoryStore();
+ await store.put('tarvent_contact_added', { data: { createWebhook: { id: 'old1' } } });
+ await handlers.onDisable({ auth: TEST_AUTH, store });
+ expect(sendRequest.mock.calls[0][0].body.variables).toEqual({ id: 'old1' });
+ expect(store.data.has('tarvent_contact_added')).toBe(false);
+ });
+
+ it('keeps the stored id when the delete fails for another reason', async () => {
+ sendRequest.mockResolvedValueOnce(ok({ errors: [{ message: 'Server error' }] }));
+ const store = memoryStore();
+ await store.put('tarvent_contact_added', { id: 'w1' });
+ await expect(handlers.onDisable({ auth: TEST_AUTH, store })).rejects.toThrow(/Server error/);
+ expect(store.data.get('tarvent_contact_added')).toEqual({ id: 'w1' });
+ });
+
+ it('keeps the stored id when Tarvent does not confirm the delete', async () => {
+ sendRequest.mockResolvedValueOnce(ok({ data: { deleteWebhook: false } }));
+ const store = memoryStore();
+ await store.put('tarvent_contact_added', { id: 'w1' });
+ await expect(handlers.onDisable({ auth: TEST_AUTH, store })).rejects.toThrow(/did not confirm deleteWebhook/);
+ expect(store.data.get('tarvent_contact_added')).toEqual({ id: 'w1' });
+ });
+
+ it('drops a retried delivery with the same event id', async () => {
+ const store = memoryStore();
+ const body = { id: 'evt1', payload: {} };
+ expect(await handlers.run({ payload: { body }, store })).toEqual([{ ...body, _dedupe_key: 'evt1' }]);
+ expect(await handlers.run({ payload: { body }, store })).toEqual([]);
+ expect(await handlers.run({ payload: { body: { id: 'evt2' } }, store })).toHaveLength(1);
+ });
+
+ it('bounds the dedupe list', () => {
+ const seen = Array.from({ length: tarventWebhook.MAX_SEEN_IDS }, (_, i) => `e${i}`);
+ expect(tarventWebhook.rememberEvent({ seen, eventId: 'new' }).seen).toHaveLength(tarventWebhook.MAX_SEEN_IDS);
+ });
+});
+
+describe('webhook filters', () => {
+ it('treats the legacy BOTH campaign type as any campaign', () => {
+ expect(tarventWebhook.webhookFilter({ type: 'contactOpened', params: { campaignType: 'BOTH' } })).toBeNull();
+ });
+
+ it('applies the specific campaign and link from the top-level props', () => {
+ const filter = tarventWebhook.webhookFilter({ type: 'contactClicked', params: { campaignType: 'Specific', campaignId: 'c1', linkId: 'l1' } });
+ expect(filter).toMatchObject({ conditions: [{ fieldName: 'Campaign.c1.Clicked.l1', operator: 'IF_TRUE' }] });
+ });
+
+ it('applies the landing page filter', () => {
+ const filter = tarventWebhook.webhookFilter({ type: 'landingPageCtaPerformed', params: { landingPageId: 'p1' } });
+ expect(filter).toMatchObject({ conditions: [{ fieldName: 'Page.p1.CTA' }] });
+ });
+
+ it('expands Any bounce type to every bounce event', () => {
+ expect(tarventWebhook.webhookEvents({ type: 'contactBounced', params: { type: 'Any', entity: 'CAMPAIGN' } })).toHaveLength(8);
+ });
+});
+
+describe('data fields', () => {
+ it('GDPR fields are real dropdown properties with 1/0 values', async () => {
+ sendRequest.mockResolvedValueOnce(ok({ data: { audienceDataFields: { nodes: [
+ { id: 'g1', dataType: 'NUMBER', labelText: 'GDPR_Email', required: false, isSystem: true, defaultValue: '', isGdprField: true },
+ { id: 'f1', dataType: 'TEXT', labelText: 'Company', required: false, isSystem: false, defaultValue: '', isGdprField: false },
+ { id: 's1', dataType: 'TEXT', labelText: 'System', required: false, isSystem: true, defaultValue: '', isGdprField: false },
+ ], pageInfo: { hasNextPage: false } } } }));
+ const props = await Reflect.apply(tarventCommon.audienceDataFields.props, tarventCommon.audienceDataFields, [{ auth: TEST_AUTH, audienceId: 'a1' }, {}]);
+ expect(Object.keys(props)).toEqual(['g1', 'f1']);
+ expect(props['g1']).toMatchObject({ type: 'STATIC_DROPDOWN', displayName: 'Email (GDPR Permission)' });
+ expect(props['f1']).toMatchObject({ type: 'SHORT_TEXT' });
+ });
+});
diff --git a/packages/pieces/community/tarvent/vitest.config.ts b/packages/pieces/community/tarvent/vitest.config.ts
new file mode 100644
index 00000000000..79c97261904
--- /dev/null
+++ b/packages/pieces/community/tarvent/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'),
+ },
+ },
+})