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
TypeScript ai-agentai-agent-toolsai-agentsai-agents-frameworkmcpmcp-servermcp-toolsmcpsn8n-alternativeno-code-automationworkflowworkflow-automationworkflows
fix(shopify): product status, customer toggles and trigger reliability (#16507)
Talal Jaber50629735135d
diff --git a/bun.lock b/bun.lockindex 2d9467bb8ce..7b14b728f8d 100644--- a/bun.lock+++ b/bun.lock@@ -8418,7 +8418,7 @@},"packages/pieces/community/shopify": {"name": "@activepieces/piece-shopify",- "version": "0.10.1",+ "version": "0.11.0","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",diff --git a/docs/install/reference/breaking-changes-unreleased.mdx b/docs/install/reference/breaking-changes-unreleased.mdxindex ff54652cf34..c2c2f2485be 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?+#### Shopify 0.11.0: Update Customer toggles that are off no longer unverify or unsubscribe the customer++Update Customer sent **Verified Email**, **Send Email Invite** and **Accepts Marketing** on every run. A fresh step saves an untouched toggle as `false`, so every update marked the customer's email as unverified and unsubscribed them from email marketing, whatever the rest of the step changed. From Shopify 0.11.0 a toggle that is off sends nothing and the customer's current setting is kept; a toggle that is on still verifies the email, sends the invite or subscribes the customer. New Update Customer steps no longer start with Verified Email switched on.++#### What you need to do++Nothing for flows that only ever verify or subscribe customers. A flow that relied on Update Customer to unsubscribe a customer or mark their email as unverified can no longer do it from this action; use **Custom API Call** with `PUT /customers/{id}.json` and a body of `{"customer": {"email_marketing_consent": {"state": "unsubscribed", "opt_in_level": "unknown"}}}` (or `"verified_email": false`). Steps keep running on the version they were built with until you upgrade them.+#### PostHog requires https hosts, and agents can no longer create projectsPostHog 0.7.0 changes what an existing 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/shopify/package.json b/packages/pieces/community/shopify/package.jsonindex 87471b4db3d..013693c638f 100644--- a/packages/pieces/community/shopify/package.json+++ b/packages/pieces/community/shopify/package.json@@ -1,6 +1,6 @@{"name": "@activepieces/piece-shopify",- "version": "0.10.1",+ "version": "0.11.0","main": "./dist/src/index.js","types": "./dist/src/index.d.ts","scripts": {diff --git a/packages/pieces/community/shopify/src/i18n/de.json b/packages/pieces/community/shopify/src/i18n/de.jsonindex f4903177545..14e30838ba4 100644--- a/packages/pieces/community/shopify/src/i18n/de.json+++ b/packages/pieces/community/shopify/src/i18n/de.json@@ -2078,5 +2078,9 @@"Triggers when a customer is created.": "Triggers when a customer is created.","Triggers when an order is created.": "Triggers when an order is created.","Triggers when a product is updated.": "Triggers when a product is updated.",- "Triggers when an order is paid.": "Triggers when an order is paid."+ "Triggers when an order is paid.": "Triggers when an order is paid.",+ "Leave empty to use Shopify's default.": "Leer lassen, um den Shopify-Standard zu verwenden.",+ "Switched off, these leave the customer's current setting unchanged.": "Ausgeschaltet lassen diese die aktuelle Einstellung des Kunden unverändert.",+ "Mark the customer's email as verified.": "Die E-Mail-Adresse des Kunden als bestätigt markieren.",+ "Leave empty to keep the current status.": "Leer lassen, um den aktuellen Status beizubehalten."}\ No newline at end of filediff --git a/packages/pieces/community/shopify/src/i18n/es.json b/packages/pieces/community/shopify/src/i18n/es.jsonindex d6471cb52ac..96529c8af53 100644--- a/packages/pieces/community/shopify/src/i18n/es.json+++ b/packages/pieces/community/shopify/src/i18n/es.json@@ -2078,5 +2078,9 @@"Triggers when a customer is created.": "Triggers when a customer is created.","Triggers when an order is created.": "Triggers when an order is created.","Triggers when a product is updated.": "Triggers when a product is updated.",- "Triggers when an order is paid.": "Triggers when an order is paid."+ "Triggers when an order is paid.": "Triggers when an order is paid.",+ "Leave empty to use Shopify's default.": "Déjalo vacío para usar el valor predeterminado de Shopify.",+ "Switched off, these leave the customer's current setting unchanged.": "Desactivadas, no cambian la configuración actual del cliente.",+ "Mark the customer's email as verified.": "Marcar el e-mail del cliente como verificado.",+ "Leave empty to keep the current status.": "Déjalo vacío para mantener el estado actual."}\ No newline at end of filediff --git a/packages/pieces/community/shopify/src/i18n/fr.json b/packages/pieces/community/shopify/src/i18n/fr.jsonindex abf2a21978f..8c346fff9dc 100644--- a/packages/pieces/community/shopify/src/i18n/fr.json+++ b/packages/pieces/community/shopify/src/i18n/fr.json@@ -2078,5 +2078,9 @@"Triggers when a customer is created.": "Triggers when a customer is created.","Triggers when an order is created.": "Triggers when an order is created.","Triggers when a product is updated.": "Triggers when a product is updated.",- "Triggers when an order is paid.": "Triggers when an order is paid."+ "Triggers when an order is paid.": "Triggers when an order is paid.",+ "Leave empty to use Shopify's default.": "Laissez vide pour utiliser la valeur par défaut de Shopify.",+ "Switched off, these leave the customer's current setting unchanged.": "Désactivées, elles laissent le réglage actuel du client inchangé.",+ "Mark the customer's email as verified.": "Marquer l'e-mail du client comme vérifié.",+ "Leave empty to keep the current status.": "Laissez vide pour conserver le statut actuel."}\ No newline at end of filediff --git a/packages/pieces/community/shopify/src/i18n/ja.json b/packages/pieces/community/shopify/src/i18n/ja.jsonindex ad16c34ba1e..f1e5962defe 100644--- a/packages/pieces/community/shopify/src/i18n/ja.json+++ b/packages/pieces/community/shopify/src/i18n/ja.json@@ -2078,5 +2078,9 @@"Triggers when a customer is created.": "Triggers when a customer is created.","Triggers when an order is created.": "Triggers when an order is created.","Triggers when a product is updated.": "Triggers when a product is updated.",- "Triggers when an order is paid.": "Triggers when an order is paid."+ "Triggers when an order is paid.": "Triggers when an order is paid.",+ "Leave empty to use Shopify's default.": "空欄の場合はShopifyの既定値を使用します。",+ "Switched off, these leave the customer's current setting unchanged.": "オフの場合、顧客の現在の設定は変更されません。",+ "Mark the customer's email as verified.": "顧客のメールアドレスを確認済みにします。",+ "Leave empty to keep the current status.": "空欄の場合は現在のステータスを維持します。"}\ No newline at end of filediff --git a/packages/pieces/community/shopify/src/i18n/nl.json b/packages/pieces/community/shopify/src/i18n/nl.jsonindex aa9b0e8bbcc..5408907c6b4 100644--- a/packages/pieces/community/shopify/src/i18n/nl.json+++ b/packages/pieces/community/shopify/src/i18n/nl.json@@ -2078,5 +2078,9 @@"Triggers when a customer is created.": "Triggers when a customer is created.","Triggers when an order is created.": "Triggers when an order is created.","Triggers when a product is updated.": "Triggers when a product is updated.",- "Triggers when an order is paid.": "Triggers when an order is paid."+ "Triggers when an order is paid.": "Triggers when an order is paid.",+ "Leave empty to use Shopify's default.": "Laat leeg om de standaardwaarde van Shopify te gebruiken.",+ "Switched off, these leave the customer's current setting unchanged.": "Uitgeschakeld laten deze de huidige instelling van de klant ongewijzigd.",+ "Mark the customer's email as verified.": "Markeer het e-mailadres van de klant als geverifieerd.",+ "Leave empty to keep the current status.": "Laat leeg om de huidige status te behouden."}\ No newline at end of filediff --git a/packages/pieces/community/shopify/src/i18n/pt.json b/packages/pieces/community/shopify/src/i18n/pt.jsonindex 7366fb70154..0fb836305f9 100644--- a/packages/pieces/community/shopify/src/i18n/pt.json+++ b/packages/pieces/community/shopify/src/i18n/pt.json@@ -2078,5 +2078,9 @@"Triggers when a customer is created.": "Triggers when a customer is created.","Triggers when an order is created.": "Triggers when an order is created.","Triggers when a product is updated.": "Triggers when a product is updated.",- "Triggers when an order is paid.": "Triggers when an order is paid."+ "Triggers when an order is paid.": "Triggers when an order is paid.",+ "Leave empty to use Shopify's default.": "Deixe vazio para usar a predefinição da Shopify.",+ "Switched off, these leave the customer's current setting unchanged.": "Desligadas, mantêm a definição atual do cliente.",+ "Mark the customer's email as verified.": "Marcar o e-mail do cliente como verificado.",+ "Leave empty to keep the current status.": "Deixe vazio para manter o estado atual."}\ No newline at end of filediff --git a/packages/pieces/community/shopify/src/i18n/ru.json b/packages/pieces/community/shopify/src/i18n/ru.jsonindex 290da346ea0..32e4add7208 100644--- a/packages/pieces/community/shopify/src/i18n/ru.json+++ b/packages/pieces/community/shopify/src/i18n/ru.json@@ -218,5 +218,9 @@"Triggers when a customer is created.": "Срабатывает при создании клиента.","Triggers when an order is created.": "Срабатывает при создании заказа.","Triggers when a product is updated.": "Срабатывает при обновлении товара.",- "Triggers when an order is paid.": "Срабатывает при оплате заказа."+ "Triggers when an order is paid.": "Срабатывает при оплате заказа.",+ "Leave empty to use Shopify's default.": "Оставьте пустым, чтобы использовать значение Shopify по умолчанию.",+ "Switched off, these leave the customer's current setting unchanged.": "Выключенные параметры не меняют текущие настройки клиента.",+ "Mark the customer's email as verified.": "Отметить email клиента как подтверждённый.",+ "Leave empty to keep the current status.": "Оставьте пустым, чтобы сохранить текущий статус."}\ No newline at end of filediff --git a/packages/pieces/community/shopify/src/i18n/translation.json b/packages/pieces/community/shopify/src/i18n/translation.jsonindex 1c053daf4c8..a98cafd28b8 100644--- a/packages/pieces/community/shopify/src/i18n/translation.json+++ b/packages/pieces/community/shopify/src/i18n/translation.json@@ -1006,7 +1006,7 @@"HTML is allowed.": "HTML is allowed.","Your own category, used to filter products.": "Your own category, used to filter products.","A file, or a public URL to an image.": "A file, or a public URL to an image.",- "Not sent to Shopify yet, so this choice has no effect.": "Not sent to Shopify yet, so this choice has no effect.",+ "Leave empty to use Shopify's default.": "Leave empty to use Shopify's default.","Capture, Void and Refund act on the Parent Transaction ID.": "Capture, Void and Refund act on the Parent Transaction ID.","The transaction to capture, void or refund.": "The transaction to capture, void or refund.","Required for refunds and captures on multi-currency orders.": "Required for refunds and captures on multi-currency orders.",@@ -1017,10 +1017,11 @@"Filter by product title. Empty: all products.": "Filter by product title. Empty: all products.","Get it from a Get Order Transactions step.": "Get it from a Get Order Transactions step.","Empty fields keep their current value.": "Empty fields keep their current value.",- "These three are always sent. Leaving Accepts Marketing off unsubscribes the customer.": "These three are always sent. Leaving Accepts Marketing off unsubscribes the customer.",+ "Switched off, these leave the customer's current setting unchanged.": "Switched off, these leave the customer's current setting unchanged.",+ "Mark the customer's email as verified.": "Mark the customer's email as verified.","Replaces the current tags. Separate them with commas.": "Replaces the current tags. Separate them with commas.",- "Off unsubscribes the customer from email marketing.": "Off unsubscribes the customer from email marketing.","Replaces the current note.": "Replaces the current note.",+ "Leave empty to keep the current status.": "Leave empty to keep the current status.","1 makes it the main image.": "1 makes it the main image.","The inventory item id, numeric or \"gid://shopify/InventoryItem/…\" (from get_product_variant_details).": "The inventory item id, numeric or \"gid://shopify/InventoryItem/…\" (from get_product_variant_details).","The location id, numeric or \"gid://shopify/Location/…\" (from list_locations).": "The location id, numeric or \"gid://shopify/Location/…\" (from list_locations).",diff --git a/packages/pieces/community/shopify/src/i18n/zh.json b/packages/pieces/community/shopify/src/i18n/zh.jsonindex 51e31b91cbe..0ae5f855f18 100644--- a/packages/pieces/community/shopify/src/i18n/zh.json+++ b/packages/pieces/community/shopify/src/i18n/zh.json@@ -2078,5 +2078,9 @@"Triggers when a customer is created.": "Triggers when a customer is created.","Triggers when an order is created.": "Triggers when an order is created.","Triggers when a product is updated.": "Triggers when a product is updated.",- "Triggers when an order is paid.": "Triggers when an order is paid."+ "Triggers when an order is paid.": "Triggers when an order is paid.",+ "Leave empty to use Shopify's default.": "留空则使用 Shopify 的默认值。",+ "Switched off, these leave the customer's current setting unchanged.": "关闭时,这些设置会保持客户当前的设置不变。",+ "Mark the customer's email as verified.": "将客户的电子邮件地址标记为已验证。",+ "Leave empty to keep the current status.": "留空则保留当前状态。"}\ No newline at end of filediff --git a/packages/pieces/community/shopify/src/lib/actions/create-product.ts b/packages/pieces/community/shopify/src/lib/actions/create-product.tsindex 1c30e9d5dab..71f078cb068 100644--- a/packages/pieces/community/shopify/src/lib/actions/create-product.ts+++ b/packages/pieces/community/shopify/src/lib/actions/create-product.ts@@ -24,7 +24,7 @@ export const createProductAction = createAction({display: 'section',label: 'Organise',icon: 'tag',- props: ['productType', 'vendor', 'tags', 'status'],+ props: ['productType', 'vendor', 'tags', 'productStatus'],},],props: {@@ -51,11 +51,10 @@ export const createProductAction = createAction({description: 'A file, or a public URL to an image.',required: false,}),- status: Property.StaticDropdown({+ productStatus: Property.StaticDropdown({displayName: 'Status',- description: 'Not sent to Shopify yet, so this choice has no effect.',- required: true,- defaultValue: ShopifyProductStatuses.DRAFT,+ description: "Leave empty to use Shopify's default.",+ required: false,options: {options: [{@@ -87,8 +86,15 @@ export const createProductAction = createAction({}),},async run({ auth, propsValue }) {- const { title, bodyHtml, vendor, productType, tags, productImage } =- propsValue;+ const {+ title,+ bodyHtml,+ vendor,+ productType,+ tags,+ productImage,+ productStatus,+ } = propsValue;const images: Partial<ShopifyImage>[] = [];if (productImage) {@@ -105,6 +111,7 @@ export const createProductAction = createAction({product_type: productType,tags,images,+ ...(productStatus ? { status: productStatus } : {}),},auth);diff --git a/packages/pieces/community/shopify/src/lib/actions/update-customer.ts b/packages/pieces/community/shopify/src/lib/actions/update-customer.tsindex 1886af314b1..b81dbe465ad 100644--- a/packages/pieces/community/shopify/src/lib/actions/update-customer.ts+++ b/packages/pieces/community/shopify/src/lib/actions/update-customer.ts@@ -1,8 +1,4 @@-import {- MarkdownVariant,- Property,- createAction,-} from '@activepieces/pieces-framework';+import { Property, createAction } from '@activepieces/pieces-framework';import { shopifyAuth } from '../..';import { updateCustomer } from '../common';import * as z from 'zod/mini'@@ -44,7 +40,7 @@ export const updateCustomerAction = createAction({label: 'Account',icon: 'inbox',props: [- 'account_warning',+ 'account_info','verifiedEmail','sendEmailInvite','acceptsMarketing',@@ -67,15 +63,13 @@ export const updateCustomerAction = createAction({required: false,width: 'half',}),- account_warning: Property.MarkDown({- value: 'These three are always sent. Leaving Accepts Marketing off unsubscribes the customer.',- variant: MarkdownVariant.WARNING,+ account_info: Property.MarkDown({+ value: "Switched off, these leave the customer's current setting unchanged.",}),verifiedEmail: Property.Checkbox({displayName: 'Verified Email',- description: 'Whether the customer has verified their email.',+ description: "Mark the customer's email as verified.",required: false,- defaultValue: true,}),sendEmailInvite: Property.Checkbox({displayName: 'Send Email Invite',@@ -108,7 +102,7 @@ export const updateCustomerAction = createAction({}),acceptsMarketing: Property.Checkbox({displayName: 'Accepts Marketing',- description: 'Off unsubscribes the customer from email marketing.',+ description: 'Subscribe the customer to email marketing.',required: false,}),},@@ -133,16 +127,20 @@ export const updateCustomerAction = createAction({customerId,{email,- verified_email: verifiedEmail,- send_email_invite: sendEmailInvite,first_name: firstName,last_name: lastName,phone: phoneNumber,tags,- email_marketing_consent:{- state:acceptsMarketing?'subscribed':'unsubscribed',- opt_in_level:"unknown"- }+ ...(verifiedEmail ? { verified_email: true } : {}),+ ...(sendEmailInvite ? { send_email_invite: true } : {}),+ ...(acceptsMarketing+ ? {+ email_marketing_consent: {+ state: 'subscribed',+ opt_in_level: 'unknown',+ },+ }+ : {}),},auth);diff --git a/packages/pieces/community/shopify/src/lib/actions/update-product.ts b/packages/pieces/community/shopify/src/lib/actions/update-product.tsindex adabbf28a34..daf84854362 100644--- a/packages/pieces/community/shopify/src/lib/actions/update-product.ts+++ b/packages/pieces/community/shopify/src/lib/actions/update-product.ts@@ -32,7 +32,7 @@ export const updateProductAction = createAction({'vendor','tags','productImage',- 'status',+ 'productStatus',],},],@@ -69,11 +69,10 @@ export const updateProductAction = createAction({description: 'A file, or a public URL to an image.',required: false,}),- status: Property.StaticDropdown({+ productStatus: Property.StaticDropdown({displayName: 'Status',- description: 'Not sent to Shopify yet, so this choice has no effect.',- required: true,- defaultValue: ShopifyProductStatuses.DRAFT,+ description: 'Leave empty to keep the current status.',+ required: false,options: {options: [{@@ -105,8 +104,16 @@ export const updateProductAction = createAction({}),},async run({ auth, propsValue }) {- const { id, title, bodyHtml, vendor, productType, tags, productImage } =- propsValue;+ const {+ id,+ title,+ bodyHtml,+ vendor,+ productType,+ tags,+ productImage,+ productStatus,+ } = propsValue;return await updateProduct(+id,@@ -119,6 +126,7 @@ export const updateProductAction = createAction({...(productImage? { images: [{ attachment: productImage.base64 }] }: {}),+ ...(productStatus ? { status: productStatus } : {}),},auth);diff --git a/packages/pieces/community/shopify/src/lib/common/index.ts b/packages/pieces/community/shopify/src/lib/common/index.tsindex 65268a96085..fa9cc3fe84e 100644--- a/packages/pieces/community/shopify/src/lib/common/index.ts+++ b/packages/pieces/community/shopify/src/lib/common/index.ts@@ -512,7 +512,9 @@ export async function getAbandonedCheckouts(sinceId: string;}): Promise<ShopifyCheckout[]> {- const queryParams: QueryParams = {};+ const queryParams: QueryParams = {+ limit: String(ABANDONED_CHECKOUTS_PAGE_LIMIT),+ };const { sinceId } = search;if (sinceId) {queryParams.since_id = sinceId;@@ -552,3 +554,5 @@ function withMerchantApprovalHint(error: unknown): unknown {},});}++export const ABANDONED_CHECKOUTS_PAGE_LIMIT = 250;diff --git a/packages/pieces/community/shopify/src/lib/common/register-webhook.ts b/packages/pieces/community/shopify/src/lib/common/register-webhook.tsindex 9950e4db75a..a3811150c1d 100644--- a/packages/pieces/community/shopify/src/lib/common/register-webhook.ts+++ b/packages/pieces/community/shopify/src/lib/common/register-webhook.ts@@ -1,10 +1,15 @@-import { httpClient, HttpMethod } from '@activepieces/pieces-common';+import { HttpError, httpClient, HttpMethod } from '@activepieces/pieces-common';import {createTrigger,- Trigger,+ isNil,TriggerStrategy,} from '@activepieces/pieces-framework';-import { SHOPIFY_API_VERSION, shopifyAuth, shopifyAuthHelpers } from './auth';+import {+ SHOPIFY_API_VERSION,+ ShopifyAuth,+ shopifyAuth,+ shopifyAuthHelpers,+} from './auth';export const createShopifyWebhookTrigger = ({name,@@ -32,41 +37,110 @@ export const createShopifyWebhookTrigger = ({sampleData: sampleData,type: TriggerStrategy.WEBHOOK,async onEnable(context) {- const shopName = shopifyAuthHelpers.getShopName(context.auth);- const response = await httpClient.sendRequest<{- webhook: {- id: string;- };- }>({- method: HttpMethod.POST,- url: `https://${shopName}.myshopify.com/admin/api/${SHOPIFY_API_VERSION}/webhooks.json`,- headers: shopifyAuthHelpers.getAuthHeaders(context.auth),- body: {- webhook: {- topic: topic,- address: context.webhookUrl,- format: 'json',- },- },+ const webhookId = await createOrFindWebhook({+ auth: context.auth,+ topic,+ address: context.webhookUrl,});- await context.store?.put(`shopify_webhook_id`, response.body.webhook.id);- console.log('webhook created', response.body.webhook.id);+ await context.store.put(WEBHOOK_ID_KEY, webhookId);},async onDisable(context) {- const webhookId = await context.store.get<string>(`shopify_webhook_id`);- const shopName = shopifyAuthHelpers.getShopName(context.auth);- await httpClient.sendRequest<{- webhook: {- id: string;- };- }>({- method: HttpMethod.DELETE,- url: `https://${shopName}.myshopify.com/admin/api/${SHOPIFY_API_VERSION}/webhooks/${webhookId}.json`,- headers: shopifyAuthHelpers.getAuthHeaders(context.auth),- });- await context.store?.put(`shopify_webhook_id`, null);+ const webhookId = await context.store.get<number>(WEBHOOK_ID_KEY);+ if (isNil(webhookId)) {+ return;+ }+ await deleteWebhook({ auth: context.auth, webhookId });+ await context.store.delete(WEBHOOK_ID_KEY);},async run(context) {return [context.payload.body];},});++async function createOrFindWebhook({+ auth,+ topic,+ address,+}: {+ auth: ShopifyAuth;+ topic: string;+ address: string;+}): Promise<number> {+ try {+ const response = await httpClient.sendRequest<{ webhook: ShopifyWebhook }>({+ method: HttpMethod.POST,+ url: `${webhooksUrl({ auth })}.json`,+ headers: shopifyAuthHelpers.getAuthHeaders(auth),+ body: {+ webhook: {+ topic,+ address,+ format: 'json',+ },+ },+ });+ return response.body.webhook.id;+ } catch (error) {+ if (!(error instanceof HttpError) || error.response.status !== 422) {+ throw error;+ }+ const existing = await findWebhook({ auth, topic, address });+ if (isNil(existing)) {+ throw error;+ }+ return existing.id;+ }+}++async function findWebhook({+ auth,+ topic,+ address,+}: {+ auth: ShopifyAuth;+ topic: string;+ address: string;+}): Promise<ShopifyWebhook | undefined> {+ const response = await httpClient.sendRequest<{ webhooks: ShopifyWebhook[] }>({+ method: HttpMethod.GET,+ url: `${webhooksUrl({ auth })}.json`,+ headers: shopifyAuthHelpers.getAuthHeaders(auth),+ queryParams: { topic, address },+ });+ return response.body.webhooks.find(+ (webhook) => webhook.topic === topic && webhook.address === address+ );+}++async function deleteWebhook({+ auth,+ webhookId,+}: {+ auth: ShopifyAuth;+ webhookId: number;+}): Promise<void> {+ try {+ await httpClient.sendRequest({+ method: HttpMethod.DELETE,+ url: `${webhooksUrl({ auth })}/${webhookId}.json`,+ headers: shopifyAuthHelpers.getAuthHeaders(auth),+ });+ } catch (error) {+ if (!(error instanceof HttpError) || error.response.status !== 404) {+ throw error;+ }+ }+}++function webhooksUrl({ auth }: { auth: ShopifyAuth }): string {+ const shopName = shopifyAuthHelpers.getShopName(auth);+ return `https://${shopName}.myshopify.com/admin/api/${SHOPIFY_API_VERSION}/webhooks`;+}++const WEBHOOK_ID_KEY = 'shopify_webhook_id';++type ShopifyWebhook = {+ id: number;+ topic: string;+ address: string;+};diff --git a/packages/pieces/community/shopify/src/lib/triggers/new-abandoned-checkout.ts b/packages/pieces/community/shopify/src/lib/triggers/new-abandoned-checkout.tsindex c799259db32..36291d39061 100644--- a/packages/pieces/community/shopify/src/lib/triggers/new-abandoned-checkout.ts+++ b/packages/pieces/community/shopify/src/lib/triggers/new-abandoned-checkout.ts@@ -3,10 +3,15 @@ import {DedupeStrategy,pollingHelper,} from '@activepieces/pieces-common';-import { TriggerStrategy, createTrigger } from '@activepieces/pieces-framework';-import { getAbandonedCheckouts } from '../common';+import {+ Store,+ TriggerStrategy,+ createTrigger,+ isNil,+} from '@activepieces/pieces-framework';+import { ABANDONED_CHECKOUTS_PAGE_LIMIT, getAbandonedCheckouts } from '../common';import { shopifyAuth } from '../..';-import { ShopifyAuth } from '../common/types';+import { ShopifyAuth, ShopifyCheckout } from '../common/types';export const newAbandonedCheckout = createTrigger({name: 'new_abandoned_checkout',@@ -19,15 +24,117 @@ export const newAbandonedCheckout = createTrigger({'Fires when a shopper adds items to their cart and begins the Shopify checkout but leaves without completing the purchase. Each event represents one abandoned checkout, including the line items, contact details, and recovery URL, enabling cart-recovery and follow-up workflows. Detected via polling, so there may be a delay before an abandoned checkout surfaces.',},props: {},- sampleData: {},+ sampleData: {+ id: 450789469,+ token: 'example-checkout-token',+ cart_token: 'example-cart-token',+ email: '[email protected]',+ buyer_accepts_marketing: false,+ created_at: '2026-10-12T07:05:27-04:00',+ updated_at: '2026-10-12T07:05:27-04:00',+ completed_at: null,+ closed_at: null,+ currency: 'USD',+ presentment_currency: 'USD',+ customer_locale: 'en',+ name: '#450789469',+ source_name: 'web',+ abandoned_checkout_url:+ 'https://example.myshopify.com/548380009/checkouts/ac/example-checkout-token/recover',+ line_items: [+ {+ key: 'example-line-item-key',+ product_id: 632910392,+ variant_id: 49148385,+ title: 'IPod Nano - 8GB',+ variant_title: 'Red',+ sku: 'IPOD2008RED',+ vendor: 'Apple',+ quantity: 1,+ price: '199.00',+ line_price: '199.00',+ requires_shipping: true,+ taxable: true,+ },+ ],+ shipping_lines: [+ {+ code: 'Free Shipping',+ price: '0.00',+ source: 'shopify',+ title: 'Free Shipping',+ },+ ],+ discount_codes: [{ code: 'TENOFF', amount: '39.80', type: 'percentage' }],+ total_line_items_price: '398.00',+ total_discounts: '39.80',+ subtotal_price: '358.20',+ total_tax: '0.00',+ total_price: '358.20',+ taxes_included: false,+ billing_address: {+ first_name: 'Bob',+ last_name: 'Norman',+ name: 'Bob Norman',+ address1: 'Chestnut Street 92',+ address2: '',+ city: 'Louisville',+ province: 'Kentucky',+ province_code: 'KY',+ country: 'United States',+ country_code: 'US',+ zip: '40202',+ phone: '+1(502)-459-2181',+ },+ shipping_address: {+ first_name: 'Bob',+ last_name: 'Norman',+ name: 'Bob Norman',+ address1: 'Chestnut Street 92',+ address2: '',+ city: 'Louisville',+ province: 'Kentucky',+ province_code: 'KY',+ country: 'United States',+ country_code: 'US',+ zip: '40202',+ phone: '+1(502)-459-2181',+ },+ customer: {+ id: 207119551,+ email: '[email protected]',+ first_name: 'Bob',+ last_name: 'Norman',+ phone: '+16136120707',+ verified_email: true,+ currency: 'USD',+ admin_graphql_api_id: 'gid://shopify/Customer/207119551',+ },+ },type: TriggerStrategy.POLLING,- async onEnable({ auth, propsValue, store }) {- await pollingHelper.onEnable(polling, { auth, propsValue, store });+ async onEnable({ auth, store }) {+ const enabledAt = Date.now();+ const scan = await scanForNewest({+ auth,+ fromId: undefined,+ enabledAt: undefined,+ });+ await saveScan({ store, scan, enabledAt });},async onDisable({ auth, propsValue, store }) {await pollingHelper.onDisable(polling, { auth, propsValue, store });},async run({ auth, propsValue, store, files }) {+ const scanCursor = await store.get<number>(SCAN_CURSOR_KEY);+ if (!isNil(scanCursor)) {+ const enabledAt = (await store.get<number>(SCAN_ENABLED_AT_KEY)) ?? undefined;+ const scan = await scanForNewest({ auth, fromId: scanCursor, enabledAt });+ await saveScan({ store, scan, enabledAt });+ return sortNewestFirst({ checkouts: scan.createdAfterEnable });+ }+ if (isNil(await store.get(LAST_ITEM_KEY))) {+ await store.put(LAST_ITEM_KEY, READ_FROM_FIRST_CHECKOUT);+ }return await pollingHelper.poll(polling, { auth, propsValue, store, files });},async test({ auth, propsValue, store, files }) {@@ -38,12 +145,128 @@ export const newAbandonedCheckout = createTrigger({const polling: Polling<ShopifyAuth, unknown> = {strategy: DedupeStrategy.LAST_ITEM,items: async ({ auth, lastItemId }) => {- const checkouts = await getAbandonedCheckouts(auth, {- sinceId: lastItemId as string,- });- return checkouts.map((checkout) => ({+ const sinceId = toSinceId({ lastItemId });+ const checkouts = isNil(sinceId)+ ? (await scanForNewest({ auth, fromId: undefined, enabledAt: undefined }))+ .checkouts+ : await getAbandonedCheckouts(auth, { sinceId });+ return sortNewestFirst({ checkouts }).map((checkout) => ({id: checkout.id,data: checkout,}));},};++async function scanForNewest({+ auth,+ fromId,+ enabledAt,+}: {+ auth: ShopifyAuth;+ fromId: number | undefined;+ enabledAt: number | undefined;+}): Promise<NewestCheckoutScan> {+ let page = await getAbandonedCheckouts(auth, {+ sinceId: isNil(fromId) ? '' : String(fromId),+ });+ let newestId = page.length > 0 ? maxId({ checkouts: page }) : fromId;+ let createdAfterEnable = createdSince({ checkouts: page, since: enabledAt });+ for (+ let hop = 0;+ hop < MAX_PAGES_TO_FIND_NEWEST &&+ page.length >= ABANDONED_CHECKOUTS_PAGE_LIMIT;+ hop+++ ) {+ const next = await getAbandonedCheckouts(auth, {+ sinceId: String(newestId),+ });+ if (next.length === 0) {+ return { checkouts: page, newestId, complete: true, createdAfterEnable };+ }+ page = next;+ newestId = maxId({ checkouts: page });+ createdAfterEnable = [+ ...createdAfterEnable,+ ...createdSince({ checkouts: page, since: enabledAt }),+ ];+ }+ return {+ checkouts: page,+ newestId,+ complete: page.length < ABANDONED_CHECKOUTS_PAGE_LIMIT,+ createdAfterEnable,+ };+}++async function saveScan({+ store,+ scan,+ enabledAt,+}: {+ store: Store;+ scan: NewestCheckoutScan;+ enabledAt: number | undefined;+}): Promise<void> {+ if (!scan.complete) {+ await store.put(SCAN_CURSOR_KEY, scan.newestId);+ if (!isNil(enabledAt)) {+ await store.put(SCAN_ENABLED_AT_KEY, enabledAt);+ }+ await store.delete(LAST_ITEM_KEY);+ return;+ }+ await store.delete(SCAN_CURSOR_KEY);+ await store.delete(SCAN_ENABLED_AT_KEY);+ if (isNil(scan.newestId)) {+ await store.delete(LAST_ITEM_KEY);+ return;+ }+ await store.put(LAST_ITEM_KEY, scan.newestId);+}++function toSinceId({ lastItemId }: { lastItemId: unknown }): string | undefined {+ if (typeof lastItemId === 'number' || typeof lastItemId === 'string') {+ return String(lastItemId);+ }+ return undefined;+}++function sortNewestFirst({+ checkouts,+}: {+ checkouts: ShopifyCheckout[];+}): ShopifyCheckout[] {+ return [...checkouts].sort((a, b) => b.id - a.id);+}++function maxId({ checkouts }: { checkouts: ShopifyCheckout[] }): number {+ return checkouts.reduce((max, checkout) => Math.max(max, checkout.id), 0);+}++function createdSince({+ checkouts,+ since,+}: {+ checkouts: ShopifyCheckout[];+ since: number | undefined;+}): ShopifyCheckout[] {+ if (isNil(since)) {+ return [];+ }+ return checkouts.filter(+ (checkout) => Date.parse(checkout.created_at) >= since+ );+}++const MAX_PAGES_TO_FIND_NEWEST = 40;+const LAST_ITEM_KEY = 'lastItem';+const SCAN_CURSOR_KEY = 'newestCheckoutScanCursor';+const SCAN_ENABLED_AT_KEY = 'newestCheckoutScanEnabledAt';+const READ_FROM_FIRST_CHECKOUT = 0;++type NewestCheckoutScan = {+ checkouts: ShopifyCheckout[];+ newestId: number | undefined;+ complete: boolean;+ createdAfterEnable: ShopifyCheckout[];+};diff --git a/packages/pieces/community/shopify/test/follow-ups.test.ts b/packages/pieces/community/shopify/test/follow-ups.test.tsnew file mode 100644index 00000000000..5d1d9e70f08--- /dev/null+++ b/packages/pieces/community/shopify/test/follow-ups.test.ts@@ -0,0 +1,286 @@+import { HttpError, HttpRequest, HttpResponse, httpClient } from '@activepieces/pieces-common';+import { createMockActionContext, createMockPollingTriggerContext, InputPropertyMap } from '@activepieces/pieces-framework';+import { afterEach, describe, expect, it, vi } from 'vitest';+import '../src';+import { createProductAction } from '../src/lib/actions/create-product';+import { updateCustomerAction } from '../src/lib/actions/update-customer';+import { updateProductAction } from '../src/lib/actions/update-product';+import { newAbandonedCheckout } from '../src/lib/triggers/new-abandoned-checkout';+import { newOrder } from '../src/lib/triggers/new-order';+import { runAction, TEST_AUTH } from './helpers';++const WEBHOOK_URL = 'https://cloud.example.com/api/v1/webhooks/flow-1';+const WEBHOOKS_URL = 'https://test-shop.myshopify.com/admin/api/2026-10/webhooks';++afterEach(() => {+ vi.restoreAllMocks();+});++describe.each([+ { label: 'create_product', action: createProductAction, base: { title: 'Shirt' } },+ { label: 'update_product', action: updateProductAction, base: { id: '1' } },+])('$label status', ({ action, base }) => {+ it('sends the picked status', async () => {+ const sent = mockRest({ replies: [{ body: { product: { id: 1 } } }] });++ await runAction({ action, propsValue: { ...base, productStatus: 'archived' } });++ expect(readBodyField({ request: sent[0], key: 'product' })).toHaveProperty('status', 'archived');+ });++ it('sends no status when none is picked, even if a saved step still holds the old field', async () => {+ const sent = mockRest({ replies: [{ body: { product: { id: 1 } } }] });++ await runAction({ action, propsValue: { ...base, status: 'draft' } });++ expect(readBodyField({ request: sent[0], key: 'product' })).not.toHaveProperty('status');+ });+});++describe('update_customer toggles', () => {+ it('leaves verification, invite and marketing untouched when the toggles are off', async () => {+ const sent = mockRest({ replies: [{ body: { customer: { id: 7 } } }] });++ await runAction({+ action: updateCustomerAction,+ propsValue: { customerId: '7', firstName: 'Ada', verifiedEmail: false, sendEmailInvite: false, acceptsMarketing: false },+ });++ const customer = readBodyField({ request: sent[0], key: 'customer' });+ expect(customer).toHaveProperty('first_name', 'Ada');+ expect(customer).not.toHaveProperty('verified_email');+ expect(customer).not.toHaveProperty('send_email_invite');+ expect(customer).not.toHaveProperty('email_marketing_consent');+ });++ it('sends each setting whose toggle is on', async () => {+ const sent = mockRest({ replies: [{ body: { customer: { id: 7 } } }] });++ await runAction({+ action: updateCustomerAction,+ propsValue: { customerId: '7', verifiedEmail: true, sendEmailInvite: true, acceptsMarketing: true },+ });++ const customer = readBodyField({ request: sent[0], key: 'customer' });+ expect(customer).toHaveProperty('verified_email', true);+ expect(customer).toHaveProperty('send_email_invite', true);+ expect(customer).toHaveProperty('email_marketing_consent', { state: 'subscribed', opt_in_level: 'unknown' });+ });+});++describe('webhook trigger lifecycle', () => {+ it('stores the id of the webhook it creates', async () => {+ mockRest({ replies: [{ body: { webhook: { id: 7, topic: 'orders/create', address: WEBHOOK_URL } } }] });+ const store = createStore({ entries: {} });++ await newOrder.onEnable(webhookContext({ store }));++ expect(store.put).toHaveBeenCalledWith('shopify_webhook_id', 7);+ });++ it('reuses the existing webhook when Shopify reports the address is already registered, as on republish', async () => {+ const sent = mockRest({+ replies: [+ { error: 422 },+ { body: { webhooks: [{ id: 9, topic: 'orders/create', address: WEBHOOK_URL }] } },+ ],+ });+ const store = createStore({ entries: { shopify_webhook_id: 7 } });++ await newOrder.onEnable(webhookContext({ store }));++ expect(sent[1].method).toBe('GET');+ expect(sent[1].url).toBe(`${WEBHOOKS_URL}.json`);+ expect(sent[1].queryParams).toEqual({ topic: 'orders/create', address: WEBHOOK_URL });+ expect(store.put).toHaveBeenCalledWith('shopify_webhook_id', 9);+ });++ it('fails with the original error when no registered webhook matches', async () => {+ mockRest({ replies: [{ error: 422 }, { body: { webhooks: [{ id: 9, topic: 'orders/paid', address: WEBHOOK_URL }] } }] });+ const store = createStore({ entries: {} });++ await expect(newOrder.onEnable(webhookContext({ store }))).rejects.toBeInstanceOf(HttpError);+ expect(store.put).not.toHaveBeenCalled();+ });++ it('does nothing on disable when no webhook id was stored', async () => {+ const sent = mockRest({ replies: [] });+ const store = createStore({ entries: {} });++ await newOrder.onDisable(webhookContext({ store }));++ expect(sent).toHaveLength(0);+ expect(store.delete).not.toHaveBeenCalled();+ });++ it('treats a webhook that is already gone as deleted', async () => {+ const sent = mockRest({ replies: [{ error: 404 }] });+ const store = createStore({ entries: { shopify_webhook_id: 7 } });++ await newOrder.onDisable(webhookContext({ store }));++ expect(sent[0].url).toBe(`${WEBHOOKS_URL}/7.json`);+ expect(store.delete).toHaveBeenCalledWith('shopify_webhook_id');+ });++ it('keeps the stored id when the delete fails for another reason', async () => {+ mockRest({ replies: [{ error: 500 }] });+ const store = createStore({ entries: { shopify_webhook_id: 7 } });++ await expect(newOrder.onDisable(webhookContext({ store }))).rejects.toBeInstanceOf(HttpError);+ expect(store.delete).not.toHaveBeenCalled();+ });+});++describe('new_abandoned_checkout polling', () => {+ it('remembers the newest checkout on enable, whatever order Shopify returns pages in', async () => {+ const firstPage = Array.from({ length: 250 }, (_, index) => ({ id: index + 1 }));+ const sent = mockRest({+ replies: [{ body: { checkouts: firstPage } }, { body: { checkouts: [{ id: 252 }, { id: 251 }] } }],+ });+ const store = createStore({ entries: {} });++ await newAbandonedCheckout.onEnable(pollingContext({ store }));++ expect(sent[0].queryParams).toEqual({ limit: '250' });+ expect(sent[1].queryParams).toEqual({ limit: '250', since_id: '250' });+ expect(store.put).toHaveBeenCalledWith('lastItem', 252);+ });++ it('returns new checkouts newest first and remembers the newest', async () => {+ const sent = mockRest({ replies: [{ body: { checkouts: [{ id: 253 }, { id: 255 }, { id: 254 }] } }] });+ const store = createStore({ entries: { lastItem: 252 } });++ const result = await newAbandonedCheckout.run(pollingContext({ store }));++ expect(sent[0].queryParams).toEqual({ limit: '250', since_id: '252' });+ expect(result).toEqual([{ id: 255 }, { id: 254 }, { id: 253 }]);+ expect(store.put).toHaveBeenCalledWith('lastItem', 255);+ });++ it('reports every checkout that arrives after enabling on an empty store, across pages', async () => {+ const firstPage = Array.from({ length: 250 }, (_, index) => ({ id: index + 1 }));+ const sent = mockRest({+ replies: [+ { body: { checkouts: [] } },+ { body: { checkouts: firstPage } },+ { body: { checkouts: [{ id: 251 }] } },+ ],+ });+ const store = createStore({ entries: {} });++ await newAbandonedCheckout.onEnable(pollingContext({ store }));+ const firstPoll = await newAbandonedCheckout.run(pollingContext({ store }));+ const secondPoll = await newAbandonedCheckout.run(pollingContext({ store }));++ expect(sent[1].queryParams).toEqual({ limit: '250', since_id: '0' });+ expect(sent[2].queryParams).toEqual({ limit: '250', since_id: '250' });+ expect(firstPoll).toHaveLength(250);+ expect(secondPoll).toEqual([{ id: 251 }]);+ });++ it('finishes finding the newest checkout before reporting any, when enable stops at the request cap', async () => {+ const fullPages = Array.from({ length: 41 }, (_, page) => ({+ body: { checkouts: Array.from({ length: 250 }, (_, index) => ({ id: page * 250 + index + 1 })) },+ }));+ const sent = mockRest({+ replies: [...fullPages, { body: { checkouts: [{ id: 10251 }] } }, { body: { checkouts: [{ id: 10252 }] } }],+ });+ const store = createStore({ entries: {} });++ await newAbandonedCheckout.onEnable(pollingContext({ store }));++ expect(sent).toHaveLength(41);+ expect(store.put).toHaveBeenCalledWith('newestCheckoutScanCursor', 10250);+ expect(store.put).not.toHaveBeenCalledWith('lastItem', expect.anything());++ const resumedPoll = await newAbandonedCheckout.run(pollingContext({ store }));+ const nextPoll = await newAbandonedCheckout.run(pollingContext({ store }));++ expect(sent[41].queryParams).toEqual({ limit: '250', since_id: '10250' });+ expect(resumedPoll).toEqual([]);+ expect(store.put).toHaveBeenCalledWith('lastItem', 10251);+ expect(store.delete).toHaveBeenCalledWith('newestCheckoutScanCursor');+ expect(sent[42].queryParams).toEqual({ limit: '250', since_id: '10251' });+ expect(nextPoll).toEqual([{ id: 10252 }]);+ });++ it('reports checkouts created after enabling that the unfinished scan reaches, but not older ones', async () => {+ const oldCheckout = { created_at: '2020-01-01T00:00:00Z' };+ const fullPages = Array.from({ length: 41 }, (_, page) => ({+ body: { checkouts: Array.from({ length: 250 }, (_, index) => ({ id: page * 250 + index + 1, ...oldCheckout })) },+ }));+ const newCheckout = { id: 10252, created_at: '2999-01-01T00:00:00Z' };+ mockRest({+ replies: [...fullPages, { body: { checkouts: [{ id: 10251, ...oldCheckout }, newCheckout] } }],+ });+ const store = createStore({ entries: {} });++ await newAbandonedCheckout.onEnable(pollingContext({ store }));+ const resumedPoll = await newAbandonedCheckout.run(pollingContext({ store }));++ expect(store.put).toHaveBeenCalledWith('newestCheckoutScanEnabledAt', expect.any(Number));+ expect(resumedPoll).toEqual([newCheckout]);+ expect(store.put).toHaveBeenCalledWith('lastItem', 10252);+ expect(store.delete).toHaveBeenCalledWith('newestCheckoutScanEnabledAt');+ });+});++function webhookContext({ store }: { store: ReturnType<typeof createStore> }) {+ return {+ ...createMockActionContext<InputPropertyMap>({ propsValue: {} }),+ auth: TEST_AUTH,+ store,+ webhookUrl: WEBHOOK_URL,+ payload: { body: {}, headers: {}, queryParams: {} },+ };+}++function pollingContext({ store }: { store: ReturnType<typeof createStore> }) {+ return {+ ...createMockPollingTriggerContext<InputPropertyMap>({ propsValue: {} }),+ auth: TEST_AUTH,+ store,+ };+}++function createStore({ entries }: { entries: Record<string, number> }) {+ const data = new Map<string, unknown>(Object.entries(entries));+ return {+ put: vi.fn(async (key: string, value: unknown) => {+ data.set(key, value);+ return value;+ }),+ get: vi.fn(async (key: string) => data.get(key) ?? null),+ delete: vi.fn(async (key: string) => {+ data.delete(key);+ }),+ };+}++function mockRest({ replies }: { replies: RestReply[] }): HttpRequest[] {+ const sent: HttpRequest[] = [];+ const queue = [...replies];+ vi.spyOn(httpClient, 'sendRequest').mockImplementation(async (request: HttpRequest): Promise<HttpResponse> => {+ sent.push(request);+ const reply = queue.shift();+ if (!reply) {+ throw new Error(`unexpected request: ${request.method} ${request.url}`);+ }+ if ('error' in reply) {+ throw new HttpError(request.body, { status: reply.error, responseBody: { errors: 'error' } });+ }+ return { status: 200, headers: {}, body: reply.body };+ });+ return sent;+}++function readBodyField({ request, key }: { request: HttpRequest; key: string }): unknown {+ return isRecord(request.body) ? request.body[key] : undefined;+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === 'object' && value !== null && !Array.isArray(value);+}++type RestReply = { body: Record<string, unknown> } | { error: number };diff --git a/packages/pieces/community/shopify/test/rest-fixes.test.ts b/packages/pieces/community/shopify/test/rest-fixes.test.tsindex bd91b1996f6..824bf79142f 100644--- a/packages/pieces/community/shopify/test/rest-fixes.test.ts+++ b/packages/pieces/community/shopify/test/rest-fixes.test.ts@@ -15,7 +15,7 @@ describe('update_product images', () => {it('sends no images key when no image is attached, so Shopify keeps the current images', async () => {const sent = mockRest({ replies: [{ body: { product: { id: 1 } } }] });- await runAction({ action: updateProductAction, propsValue: { id: '1', title: 'Shirt', status: 'DRAFT' } });+ await runAction({ action: updateProductAction, propsValue: { id: '1', title: 'Shirt', status: 'draft' } });expect(sent).toHaveLength(1);expect(readProduct({ request: sent[0] })).not.toHaveProperty('images');@@ -26,7 +26,7 @@ describe('update_product images', () => {await runAction({action: updateProductAction,- propsValue: { id: '1', status: 'DRAFT', productImage: { filename: 'shirt.png', extension: 'png', base64: 'aW1hZ2U=' } },+ propsValue: { id: '1', status: 'draft', productImage: { filename: 'shirt.png', extension: 'png', base64: 'aW1hZ2U=' } },});expect(readProduct({ request: sent[0] })).toHaveProperty('images', [{ attachment: 'aW1hZ2U=' }]);