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(shopify): let AI agents manage orders, refunds, draft orders and customers (#16087)

Odai Ahmadda1309d3289a
diff --git a/bun.lock b/bun.lock
index 6d2e3064753..c5a5c7c7f51 100644
--- a/bun.lock
+++ b/bun.lock
@@ -8313,7 +8313,7 @@
},
"packages/pieces/community/shopify": {
"name": "@activepieces/piece-shopify",
- "version": "0.4.1",
+ "version": "0.5.0",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
@@ -8323,6 +8323,7 @@
},
"devDependencies": {
"tslib": "2.6.2",
+ "vitest": "3.2.6",
},
},
"packages/pieces/community/short-io": {
diff --git a/packages/pieces/community/shopify/package.json b/packages/pieces/community/shopify/package.json
index 76d3a9c8640..e76c8529a5e 100644
--- a/packages/pieces/community/shopify/package.json
+++ b/packages/pieces/community/shopify/package.json
@@ -1,12 +1,13 @@
{
"name": "@activepieces/piece-shopify",
- "version": "0.4.1",
+ "version": "0.5.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:*",
@@ -16,6 +17,7 @@
"@activepieces/core-utils": "workspace:*"
},
"devDependencies": {
- "tslib": "2.6.2"
+ "tslib": "2.6.2",
+ "vitest": "3.2.6"
}
}
diff --git a/packages/pieces/community/shopify/src/i18n/translation.json b/packages/pieces/community/shopify/src/i18n/translation.json
index 2156732622c..8b6b98651cd 100644
--- a/packages/pieces/community/shopify/src/i18n/translation.json
+++ b/packages/pieces/community/shopify/src/i18n/translation.json
@@ -1,7 +1,5 @@
{
"Ecommerce platform for online stores": "Ecommerce platform for online stores",
- "Shop Name": "Shop Name",
- "Admin Token": "Admin Token",
"Adjust Inventory Level": "Adjust Inventory Level",
"Cancel Order": "Cancel Order",
"Close Order": "Close Order",
@@ -28,6 +26,59 @@
"Update Order": "Update Order",
"Update Product": "Update Product",
"Upload Product Image": "Upload Product Image",
+ "Add Tags": "Add Tags",
+ "Send Payment Method Update Email": "Send Payment Method Update Email",
+ "Resolve Requested Order Edit": "Resolve Requested Order Edit",
+ "Decline Requested Order Edit": "Decline Requested Order Edit",
+ "Create Requested Order Edit": "Create Requested Order Edit",
+ "Calculate Requested Order Edit": "Calculate Requested Order Edit",
+ "List Requested Order Edits": "List Requested Order Edits",
+ "Archive Order": "Archive Order",
+ "Calculate Refund": "Calculate Refund",
+ "Capture Order Payment": "Capture Order Payment",
+ "Complete Draft Order": "Complete Draft Order",
+ "Count Abandoned Checkouts": "Count Abandoned Checkouts",
+ "Count Customer Segments": "Count Customer Segments",
+ "Count Customers": "Count Customers",
+ "Count Draft Orders": "Count Draft Orders",
+ "Create Customer Address": "Create Customer Address",
+ "Create Order Risk Assessment": "Create Order Risk Assessment",
+ "Create Refund": "Create Refund",
+ "Delete Customer Address": "Delete Customer Address",
+ "Delete Customer": "Delete Customer",
+ "Delete Draft Order": "Delete Draft Order",
+ "Delete Order": "Delete Order",
+ "Generate Customer Activation URL": "Generate Customer Activation URL",
+ "Get Abandonment": "Get Abandonment",
+ "Get Checkout Abandonment": "Get Checkout Abandonment",
+ "Get Draft Order": "Get Draft Order",
+ "Get Granted Access Scopes": "Get Granted Access Scopes",
+ "Get Job Status": "Get Job Status",
+ "Get Order Risk Assessments": "Get Order Risk Assessments",
+ "Get Order Transaction": "Get Order Transaction",
+ "Get Order": "Get Order",
+ "Get Refund": "Get Refund",
+ "Get Shop": "Get Shop",
+ "List Abandoned Checkouts": "List Abandoned Checkouts",
+ "List Customer Addresses": "List Customer Addresses",
+ "List Customer Orders": "List Customer Orders",
+ "List Draft Orders": "List Draft Orders",
+ "List Order Refunds": "List Order Refunds",
+ "List Order Transactions": "List Order Transactions",
+ "List Tender Transactions": "List Tender Transactions",
+ "Mark Order as Paid": "Mark Order as Paid",
+ "Remove Tags": "Remove Tags",
+ "Search Customers": "Search Customers",
+ "Search Orders": "Search Orders",
+ "Send Customer Account Invite": "Send Customer Account Invite",
+ "Send Draft Order Invoice": "Send Draft Order Invoice",
+ "Set Default Customer Address": "Set Default Customer Address",
+ "Start Order Cancellation": "Start Order Cancellation",
+ "Unarchive Order": "Unarchive Order",
+ "Update Customer Address": "Update Customer Address",
+ "Update Draft Order": "Update Draft Order",
+ "Update Order Details": "Update Order Details",
+ "Void Payment Authorization": "Void Payment Authorization",
"Custom API Call": "Custom API Call",
"Adjust inventory level of an item at a location.": "Adjust inventory level of an item at a location.",
"Cancel an order.": "Cancel an order.",
@@ -55,6 +106,64 @@
"Update an existing order.": "Update an existing order.",
"Update an existing product.": "Update an existing product.",
"Upload a new product image.": "Upload a new product image.",
+ "Add tags to an order, draft order, customer or product.": "Add tags to an order, draft order, customer or product.",
+ "Email a customer a secure link to add a new payment method for an order, draft order or subscription contract.": "Email a customer a secure link to add a new payment method for an order, draft order or subscription contract.",
+ "Mark a buyer request to edit an order as completed.": "Mark a buyer request to edit an order as completed.",
+ "Decline a buyer request to edit an order, with an optional note to the buyer.": "Decline a buyer request to edit an order, with an optional note to the buyer.",
+ "Record a buyer request to remove unfulfilled line items from an order.": "Record a buyer request to remove unfulfilled line items from an order.",
+ "Preview the money effect of removing line items from an order, without changing anything.": "Preview the money effect of removing line items from an order, without changing anything.",
+ "List the edits a buyer requested on an order, such as removing unfulfilled items.": "List the edits a buyer requested on an order, such as removing unfulfilled items.",
+ "Close (archive) an order.": "Close (archive) an order.",
+ "Preview the refund Shopify suggests for an order, without refunding.": "Preview the refund Shopify suggests for an order, without refunding.",
+ "Capture money from an authorized payment on an order.": "Capture money from an authorized payment on an order.",
+ "Turn a draft order into a real order.": "Turn a draft order into a real order.",
+ "Count abandoned checkouts, optionally filtered.": "Count abandoned checkouts, optionally filtered.",
+ "Count the customer segments defined in the store.": "Count the customer segments defined in the store.",
+ "Count customers, optionally filtered.": "Count customers, optionally filtered.",
+ "Count draft orders, optionally filtered.": "Count draft orders, optionally filtered.",
+ "Add a new address to a customer.": "Add a new address to a customer.",
+ "Create a customer with contact details, tags and optional email marketing consent.": "Create a customer with contact details, tags and optional email marketing consent.",
+ "Create a draft order with one or more product or custom line items.": "Create a draft order with one or more product or custom line items.",
+ "Record a fraud risk assessment with supporting facts on an order.": "Record a fraud risk assessment with supporting facts on an order.",
+ "Create a real order with one or more line items.": "Create a real order with one or more line items.",
+ "Refund money and/or line items on an order.": "Refund money and/or line items on an order.",
+ "Delete a saved address from a customer.": "Delete a saved address from a customer.",
+ "Permanently delete a customer who has no orders.": "Permanently delete a customer who has no orders.",
+ "Permanently delete a draft order.": "Permanently delete a draft order.",
+ "Permanently delete an archived or cancelled order.": "Permanently delete an archived or cancelled order.",
+ "Create a one-time account activation link for a customer.": "Create a one-time account activation link for a customer.",
+ "Get a customer abandonment (browse, cart or checkout) by id.": "Get a customer abandonment (browse, cart or checkout) by id.",
+ "Get the abandonment record of an abandoned checkout.": "Get the abandonment record of an abandoned checkout.",
+ "Get one customer with contact details, marketing state and default address.": "Get one customer with contact details, marketing state and default address.",
+ "Get one draft order with its line items and totals.": "Get one draft order with its line items and totals.",
+ "List the Admin API access scopes granted to the connected app.": "List the Admin API access scopes granted to the connected app.",
+ "Check whether an asynchronous Shopify job has finished.": "Check whether an asynchronous Shopify job has finished.",
+ "Get the fraud risk recommendation and assessments of an order.": "Get the fraud risk recommendation and assessments of an order.",
+ "Get one payment transaction by id.": "Get one payment transaction by id.",
+ "Get one order with its totals, addresses and line items.": "Get one order with its totals, addresses and line items.",
+ "Get one refund by id.": "Get one refund by id.",
+ "Get the store name, domain, currency, timezone and plan.": "Get the store name, domain, currency, timezone and plan.",
+ "List checkouts that customers started but did not complete.": "List checkouts that customers started but did not complete.",
+ "List the saved addresses of one customer.": "List the saved addresses of one customer.",
+ "List the orders of one customer, one page at a time.": "List the orders of one customer, one page at a time.",
+ "Search draft orders, one page at a time.": "Search draft orders, one page at a time.",
+ "List every refund made on an order.": "List every refund made on an order.",
+ "List every payment transaction on an order.": "List every payment transaction on an order.",
+ "List money actually received or paid out across all orders.": "List money actually received or paid out across all orders.",
+ "Record the outstanding balance of an order as paid manually.": "Record the outstanding balance of an order as paid manually.",
+ "Remove tags from an order, draft order, customer or product.": "Remove tags from an order, draft order, customer or product.",
+ "Search customers with Shopify search syntax, one page at a time.": "Search customers with Shopify search syntax, one page at a time.",
+ "Search orders with Shopify search syntax, one page at a time.": "Search orders with Shopify search syntax, one page at a time.",
+ "Email a customer an invitation to create their store account.": "Email a customer an invitation to create their store account.",
+ "Email the checkout invoice of a draft order to the customer.": "Email the checkout invoice of a draft order to the customer.",
+ "Make one of a customer's saved addresses the default.": "Make one of a customer's saved addresses the default.",
+ "Cancel an order asynchronously and get a job to poll.": "Cancel an order asynchronously and get a job to poll.",
+ "Reopen a closed (archived) order.": "Reopen a closed (archived) order.",
+ "Change fields of a saved customer address.": "Change fields of a saved customer address.",
+ "Change the name, email, phone, note, tags, locale or tax exemption of a customer.": "Change the name, email, phone, note, tags, locale or tax exemption of a customer.",
+ "Change the line items, customer, contact, tags or payment terms of a draft order.": "Change the line items, customer, contact, tags or payment terms of a draft order.",
+ "Change the email, phone, note, tags or PO number of an order.": "Change the email, phone, note, tags or PO number of an order.",
+ "Void an uncaptured payment authorization on an order.": "Void an uncaptured payment authorization on an order.",
"Make a custom API call to a specific endpoint": "Make a custom API call to a specific endpoint",
"Inventory Item": "Inventory Item",
"Location": "Location",
@@ -98,14 +207,101 @@
"Note": "Note",
"Image": "Image",
"Position": "Position",
+ "Resource Type": "Resource Type",
+ "Resource ID": "Resource ID",
+ "Sender Email": "Sender Email",
+ "BCC Recipients": "BCC Recipients",
+ "Requested Order Edit ID": "Requested Order Edit ID",
+ "Decline Note": "Decline Note",
+ "Order ID": "Order ID",
+ "Line Items to Remove": "Line Items to Remove",
+ "Page Size": "Page Size",
+ "Cursor": "Cursor",
+ "Line Items to Refund": "Line Items to Refund",
+ "Refund All Shipping": "Refund All Shipping",
+ "Shipping Amount": "Shipping Amount",
+ "Suggest Full Refund": "Suggest Full Refund",
+ "Authorization Transaction ID": "Authorization Transaction ID",
+ "Final Capture": "Final Capture",
+ "Draft Order ID": "Draft Order ID",
+ "Payment Gateway ID": "Payment Gateway ID",
+ "Source Name": "Source Name",
+ "Search Query": "Search Query",
+ "Company": "Company",
+ "Address Line 1": "Address Line 1",
+ "Address Line 2": "Address Line 2",
+ "City": "City",
+ "Province / State Code": "Province / State Code",
+ "Country Code": "Country Code",
+ "Postal Code": "Postal Code",
+ "Phone": "Phone",
+ "Set as Default": "Set as Default",
+ "Locale": "Locale",
+ "Tax Exempt": "Tax Exempt",
+ "Email Marketing Consent": "Email Marketing Consent",
+ "Email Opt-in Level": "Email Opt-in Level",
+ "Line Items": "Line Items",
+ "Use Customer Default Address": "Use Customer Default Address",
+ "PO Number": "PO Number",
+ "Order Discount Value": "Order Discount Value",
+ "Order Discount Type": "Order Discount Type",
+ "Order Discount Title": "Order Discount Title",
+ "Shipping Line Title": "Shipping Line Title",
+ "Shipping Price": "Shipping Price",
+ "Reserve Inventory Until": "Reserve Inventory Until",
+ "Risk Level": "Risk Level",
+ "Facts": "Facts",
+ "Financial Status": "Financial Status",
+ "Payment Amount": "Payment Amount",
+ "Discount Code": "Discount Code",
+ "Discount Type": "Discount Type",
+ "Discount Value": "Discount Value",
+ "Shipping First Name": "Shipping First Name",
+ "Shipping Last Name": "Shipping Last Name",
+ "Shipping Address Line 1": "Shipping Address Line 1",
+ "Shipping Address Line 2": "Shipping Address Line 2",
+ "Shipping City": "Shipping City",
+ "Shipping Province / State Code": "Shipping Province / State Code",
+ "Shipping Country Code": "Shipping Country Code",
+ "Shipping Postal Code": "Shipping Postal Code",
+ "Shipping Phone": "Shipping Phone",
+ "Inventory Behaviour": "Inventory Behaviour",
+ "Send Order Receipt": "Send Order Receipt",
+ "Fulfilled From Location ID": "Fulfilled From Location ID",
+ "Tracking Numbers": "Tracking Numbers",
+ "Tracking Company": "Tracking Company",
+ "Refund Transactions": "Refund Transactions",
+ "Notify Customer": "Notify Customer",
+ "Idempotency Key": "Idempotency Key",
+ "Address ID": "Address ID",
+ "Abandonment ID": "Abandonment ID",
+ "Abandoned Checkout ID": "Abandoned Checkout ID",
+ "Job ID": "Job ID",
+ "Transaction ID": "Transaction ID",
+ "Refund ID": "Refund ID",
+ "Sort By": "Sort By",
+ "Reverse Order": "Reverse Order",
+ "Subject": "Subject",
+ "Custom Message": "Custom Message",
+ "Recipient Email": "Recipient Email",
+ "Reason": "Reason",
+ "Restock Items": "Restock Items",
+ "Refund Method": "Refund Method",
+ "Store Credit Expiry": "Store Credit Expiry",
+ "Staff Note": "Staff Note",
+ "Clear Note": "Clear Note",
+ "Clear Tags": "Clear Tags",
+ "Payment Terms Template ID": "Payment Terms Template ID",
+ "Payment Terms Issued At": "Payment Terms Issued At",
+ "Payment Due At": "Payment Due At",
"Method": "Method",
"Headers": "Headers",
"Query Parameters": "Query Parameters",
"Body Type": "Body Type",
"Body": "Body",
- "Response is Binary ?": "Response is Binary ?",
- "No Error on Failure": "No Error on Failure",
- "Timeout (in seconds)": "Timeout (in seconds)",
+ "Response is Binary": "Response is Binary",
+ "Return Error as Output": "Return Error as Output",
+ "Timeout": "Timeout",
"Follow redirects": "Follow redirects",
"The ID of the inventory item.": "The ID of the inventory item.",
"The ID of the location.": "The ID of the location.",
@@ -130,21 +326,231 @@
"The ID of the product variant.": "The ID of the product variant.",
"The ID of the transaction": "The ID of the transaction",
"1 makes it the main image.": "1 makes it the main image.",
+ "What kind of record the id belongs to. Used to build the full id when a numeric id is given.": "What kind of record the id belongs to. Used to build the full id when a numeric id is given.",
+ "Numeric id such as \"450789469\" or a full id such as \"gid://shopify/Order/450789469\".": "Numeric id such as \"450789469\" or a full id such as \"gid://shopify/Order/450789469\".",
+ "Tags to add, for example [\"vip\", \"follow-up\"].": "Tags to add, for example [\"vip\", \"follow-up\"].",
+ "What the new payment method is for.": "What the new payment method is for.",
+ "The id of the order, draft order or subscription contract, numeric or a full id such as \"gid://shopify/Order/450789469\", \"gid://shopify/DraftOrder/…\" or \"gid://shopify/SubscriptionContract/…\". It must match the resource type; Shopify receives the number.": "The id of the order, draft order or subscription contract, numeric or a full id such as \"gid://shopify/Order/450789469\", \"gid://shopify/DraftOrder/…\" or \"gid://shopify/SubscriptionContract/…\". It must match the resource type; Shopify receives the number.",
+ "Send from this address instead of the store default, for example \"[email protected]\".": "Send from this address instead of the store default, for example \"[email protected]\".",
+ "Email addresses that receive a blind copy, for example [\"[email protected]\"].": "Email addresses that receive a blind copy, for example [\"[email protected]\"].",
+ "The requested order edit id, numeric or \"gid://shopify/RequestedOrderEdit/…\". Find it with list_requested_order_edits.": "The requested order edit id, numeric or \"gid://shopify/RequestedOrderEdit/…\". Find it with list_requested_order_edits.",
+ "Message sent to the buyer explaining the decline, at most 500 characters. Leave empty to send none.": "Message sent to the buyer explaining the decline, at most 500 characters. Leave empty to send none.",
+ "The order id, numeric or \"gid://shopify/Order/…\". Find it with search_orders.": "The order id, numeric or \"gid://shopify/Order/…\". Find it with search_orders.",
+ "The order line items the buyer wants removed and how many units of each. Line item ids come from get_order (line_items[].id). The quantity cannot exceed the unfulfilled quantity of the line item.": "The order line items the buyer wants removed and how many units of each. Line item ids come from get_order (line_items[].id). The quantity cannot exceed the unfulfilled quantity of the line item.",
+ "How many records to return, 1 to 25. Defaults to 25.": "How many records to return, 1 to 25. Defaults to 25.",
+ "The end_cursor from the previous page. Leave empty for the first page; pass it only while has_next_page is true.": "The end_cursor from the previous page. Leave empty for the first page; pass it only while has_next_page is true.",
+ "Line items and quantities to refund. Line item ids come from get_order.": "Line items and quantities to refund. Line item ids come from get_order.",
+ "Include the full shipping cost in the suggestion. Off by default.": "Include the full shipping cost in the suggestion. Off by default.",
+ "Refund only this much shipping, for example 4.50. Ignored when refunding all shipping.": "Refund only this much shipping, for example 4.50. Ignored when refunding all shipping.",
+ "Suggest refunding everything still refundable on the order. Off by default.": "Suggest refunding everything still refundable on the order. Off by default.",
+ "The order id, numeric or \"gid://shopify/Order/…\".": "The order id, numeric or \"gid://shopify/Order/…\".",
+ "The AUTHORIZATION transaction to capture, numeric or \"gid://shopify/OrderTransaction/…\". Find it with list_order_transactions.": "The AUTHORIZATION transaction to capture, numeric or \"gid://shopify/OrderTransaction/…\". Find it with list_order_transactions.",
+ "Amount to capture, for example 49.99. Cannot exceed the authorized amount still capturable.": "Amount to capture, for example 49.99. Cannot exceed the authorized amount still capturable.",
+ "Three-letter currency of the amount, for example \"EUR\". Required when the order was paid in a currency other than the shop currency.": "Three-letter currency of the amount, for example \"EUR\". Required when the order was paid in a currency other than the shop currency.",
+ "For payments that allow several captures: Yes releases the rest of the authorization after this capture. Leave empty for the gateway default.": "For payments that allow several captures: Yes releases the rest of the authorization after this capture. Leave empty for the gateway default.",
+ "The draft order id, numeric or \"gid://shopify/DraftOrder/…\". Find it with list_draft_orders.": "The draft order id, numeric or \"gid://shopify/DraftOrder/…\". Find it with list_draft_orders.",
+ "Optional manual payment gateway to record the payment against, as a full id such as \"gid://shopify/PaymentGateway/1\".": "Optional manual payment gateway to record the payment against, as a full id such as \"gid://shopify/PaymentGateway/1\".",
+ "Optional channel label stored on the order, for example \"phone\".": "Optional channel label stored on the order, for example \"phone\".",
+ "Shopify search syntax, for example \"created_at:>=2026-09-01\". Leave empty to count all.": "Shopify search syntax, for example \"created_at:>=2026-09-01\". Leave empty to count all.",
+ "Filter by created_at, updated_at or id, for example \"created_at:>2026-01-01\". Leave empty to count all.": "Filter by created_at, updated_at or id, for example \"created_at:>2026-01-01\". Leave empty to count all.",
+ "Shopify draft order search syntax, for example \"status:open\". Leave empty to count all.": "Shopify draft order search syntax, for example \"status:open\". Leave empty to count all.",
+ "The customer id, numeric or \"gid://shopify/Customer/…\". Find it with search_customers.": "The customer id, numeric or \"gid://shopify/Customer/…\". Find it with search_customers.",
+ "First name on the address.": "First name on the address.",
+ "Last name on the address.": "Last name on the address.",
+ "Company name on the address.": "Company name on the address.",
+ "Street address, for example \"150 Elgin Street\".": "Street address, for example \"150 Elgin Street\".",
+ "Apartment, suite or unit, for example \"Suite 800\".": "Apartment, suite or unit, for example \"Suite 800\".",
+ "City, for example \"Ottawa\".": "City, for example \"Ottawa\".",
+ "Region code, for example \"ON\" or \"CA\".": "Region code, for example \"ON\" or \"CA\".",
+ "Two-letter ISO country code, for example \"CA\" or \"US\".": "Two-letter ISO country code, for example \"CA\" or \"US\".",
+ "Postal or ZIP code, for example \"K2P 1L4\".": "Postal or ZIP code, for example \"K2P 1L4\".",
+ "Phone number in E.164 format, for example \"+16135551111\".": "Phone number in E.164 format, for example \"+16135551111\".",
+ "Make this the customer's default address. Off by default.": "Make this the customer's default address. Off by default.",
+ "Customer email, for example \"[email protected]\". Must be unique in the store.": "Customer email, for example \"[email protected]\". Must be unique in the store.",
+ "Customer phone in E.164 format, for example \"+16135551111\". Must be unique in the store.": "Customer phone in E.164 format, for example \"+16135551111\". Must be unique in the store.",
+ "Customer first name.": "Customer first name.",
+ "Customer last name.": "Customer last name.",
+ "Internal note about the customer.": "Internal note about the customer.",
+ "Tags to set, for example [\"vip\", \"wholesale\"].": "Tags to set, for example [\"vip\", \"wholesale\"].",
+ "Language for customer emails, for example \"en\" or \"fr-CA\".": "Language for customer emails, for example \"en\" or \"fr-CA\".",
+ "Whether the customer is exempt from taxes. Off by default.": "Whether the customer is exempt from taxes. Off by default.",
+ "Record the email marketing consent the customer gave. Leave empty to record none (the customer is not subscribed). Requires an email.": "Record the email marketing consent the customer gave. Leave empty to record none (the customer is not subscribed). Requires an email.",
+ "How consent was collected. Only used with email marketing consent.": "How consent was collected. Only used with email marketing consent.",
+ "The items on the draft. Give either a variant id (price comes from the product) or a title and price for a custom item.": "The items on the draft. Give either a variant id (price comes from the product) or a title and price for a custom item.",
+ "Three-letter currency code for the unit prices and shipping price given here, for example \"USD\". Required when any price is given. Find the shop currency with get_shop.": "Three-letter currency code for the unit prices and shipping price given here, for example \"USD\". Required when any price is given. Find the shop currency with get_shop.",
+ "Customer the draft is for, numeric or \"gid://shopify/Customer/…\". Find it with search_customers.": "Customer the draft is for, numeric or \"gid://shopify/Customer/…\". Find it with search_customers.",
+ "Use the customer's default address as the shipping address. Needs a customer.": "Use the customer's default address as the shipping address. Needs a customer.",
+ "Email the invoice is sent to, for example \"[email protected]\".": "Email the invoice is sent to, for example \"[email protected]\".",
+ "Contact phone in E.164 format, for example \"+16135551111\".": "Contact phone in E.164 format, for example \"+16135551111\".",
+ "Internal note on the draft.": "Internal note on the draft.",
+ "Tags to set on the draft, for example [\"quote\", \"b2b\"].": "Tags to set on the draft, for example [\"quote\", \"b2b\"].",
+ "Purchase order number, for example \"PO-2026-114\".": "Purchase order number, for example \"PO-2026-114\".",
+ "Discount on the whole draft: a percentage (10 for 10%) or a fixed amount, per the discount type.": "Discount on the whole draft: a percentage (10 for 10%) or a fixed amount, per the discount type.",
+ "How the order discount value applies. Required with a discount value.": "How the order discount value applies. Required with a discount value.",
+ "Label shown for the discount, for example \"Loyalty discount\".": "Label shown for the discount, for example \"Loyalty discount\".",
+ "Name of a custom shipping line, for example \"Courier\".": "Name of a custom shipping line, for example \"Courier\".",
+ "Price of the custom shipping line, for example 12.00. Requires a shipping title and a currency.": "Price of the custom shipping line, for example 12.00. Requires a shipping title and a currency.",
+ "Hold the stock for this draft until this time (ISO 8601). Leave empty to not reserve stock.": "Hold the stock for this draft until this time (ISO 8601). Leave empty to not reserve stock.",
+ "The assessed fraud risk.": "The assessed fraud risk.",
+ "Reasons behind the assessment, at least one.": "Reasons behind the assessment, at least one.",
+ "The items to order. Give either a variant id (price comes from the product) or a title and price for a custom item.": "The items to order. Give either a variant id (price comes from the product) or a title and price for a custom item.",
+ "Three-letter currency code for every price given here, for example \"USD\". Required when any unit price, shipping price or fixed discount is given. Find the shop currency with get_shop.": "Three-letter currency code for every price given here, for example \"USD\". Required when any unit price, shipping price or fixed discount is given. Find the shop currency with get_shop.",
+ "Existing customer to attach, numeric or \"gid://shopify/Customer/…\". Find it with search_customers.": "Existing customer to attach, numeric or \"gid://shopify/Customer/…\". Find it with search_customers.",
+ "Order contact email, for example \"[email protected]\".": "Order contact email, for example \"[email protected]\".",
+ "Order contact phone in E.164 format, for example \"+16135551111\".": "Order contact phone in E.164 format, for example \"+16135551111\".",
+ "Payment status of the order. Authorized, Paid and Partially paid need payment_amount, which records a manual payment; without it Shopify would only show the label and the order could not be refunded, captured or marked as paid. Leave empty for pending.": "Payment status of the order. Authorized, Paid and Partially paid need payment_amount, which records a manual payment; without it Shopify would only show the label and the order could not be refunded, captured or marked as paid. Leave empty for pending.",
+ "Amount already paid (Paid, Partially paid) or authorized (Authorized), recorded as a manual payment in the order currency, for example 40.5. Needed with those financial statuses.": "Amount already paid (Paid, Partially paid) or authorized (Authorized), recorded as a manual payment in the order currency, for example 40.5. Needed with those financial statuses.",
+ "Internal note on the order.": "Internal note on the order.",
+ "Tags to set on the order, for example [\"wholesale\", \"phone-order\"].": "Tags to set on the order, for example [\"wholesale\", \"phone-order\"].",
+ "One discount code to record on the order, for example \"SUMMER10\". Only one code is allowed.": "One discount code to record on the order, for example \"SUMMER10\". Only one code is allowed.",
+ "How the discount code applies. Required with a discount code.": "How the discount code applies. Required with a discount code.",
+ "Percentage (for example 10 for 10%) or fixed amount, depending on the discount type.": "Percentage (for example 10 for 10%) or fixed amount, depending on the discount type.",
+ "Name of the shipping method, for example \"Standard Shipping\". Needs a shipping price.": "Name of the shipping method, for example \"Standard Shipping\". Needs a shipping price.",
+ "Shipping price in the order currency, for example 5.00 (use 0 for free shipping). Required together with the shipping line title, and needs a currency.": "Shipping price in the order currency, for example 5.00 (use 0 for free shipping). Required together with the shipping line title, and needs a currency.",
+ "First name on the shipping address.": "First name on the shipping address.",
+ "Last name on the shipping address.": "Last name on the shipping address.",
+ "Apartment, suite or unit.": "Apartment, suite or unit.",
+ "Region code, for example \"ON\".": "Region code, for example \"ON\".",
+ "Two-letter ISO country code, for example \"CA\".": "Two-letter ISO country code, for example \"CA\".",
+ "Postal or ZIP code.": "Postal or ZIP code.",
+ "Phone on the shipping address.": "Phone on the shipping address.",
+ "Whether to decrement stock. Leave empty for the Shopify default (bypass, stock is not changed).": "Whether to decrement stock. Leave empty for the Shopify default (bypass, stock is not changed).",
+ "Email the order confirmation to the customer. Off by default.": "Email the order confirmation to the customer. Off by default.",
+ "Email a shipping confirmation when the order is fulfilled. Off by default.": "Email a shipping confirmation when the order is fulfilled. Off by default.",
+ "Set only when importing an order that was already shipped: the location id (from list_locations) it shipped from. The order is then created fulfilled for all line items. Leave empty for an unfulfilled order.": "Set only when importing an order that was already shipped: the location id (from list_locations) it shipped from. The order is then created fulfilled for all line items. Leave empty for an unfulfilled order.",
+ "Tracking numbers of the imported fulfillment, one per package, for example [\"1Z999AA10123456784\", \"1Z999AA10123456785\"]. Needs fulfillment_location_id.": "Tracking numbers of the imported fulfillment, one per package, for example [\"1Z999AA10123456784\", \"1Z999AA10123456785\"]. Needs fulfillment_location_id.",
+ "Carrier of the tracking numbers, for example \"UPS\", \"USPS\" or \"DHL Express\". Needs fulfillment_location_id.": "Carrier of the tracking numbers, for example \"UPS\", \"USPS\" or \"DHL Express\". Needs fulfillment_location_id.",
+ "The money to return, one entry per original payment. Copy parent_transaction_id, gateway and amount from calculate_refund suggested_transactions; when the order has a presentment currency different from the shop currency, copy presentment_amount instead of amount and set currency. Leave empty to refund items without returning money.": "The money to return, one entry per original payment. Copy parent_transaction_id, gateway and amount from calculate_refund suggested_transactions; when the order has a presentment currency different from the shop currency, copy presentment_amount instead of amount and set currency. Leave empty to refund items without returning money.",
+ "Refund the full remaining shipping cost. Off by default.": "Refund the full remaining shipping cost. Off by default.",
+ "Refund only this much shipping, for example 4.50, in the same currency as the transaction amounts. Ignored when refunding all shipping.": "Refund only this much shipping, for example 4.50, in the same currency as the transaction amounts. Ignored when refunding all shipping.",
+ "Presentment (customer) currency of the refund, for example \"EUR\" (presentment_currency_code from calculate_refund). Required when the presentment currency differs from the shop currency; then every amount given here must be the presentment amount. Leave empty when both currencies are the same.": "Presentment (customer) currency of the refund, for example \"EUR\" (presentment_currency_code from calculate_refund). Required when the presentment currency differs from the shop currency; then every amount given here must be the presentment amount. Leave empty when both currencies are the same.",
+ "Internal reason for the refund.": "Internal reason for the refund.",
+ "Email the customer a refund notification. Off by default.": "Email the customer a refund notification. Off by default.",
+ "A unique key for this operation, for example a UUID such as \"3f1c2a9e-6b1d-4c8e-9a51-2f7d0e4b8c10\". Generate your own key on the first call and pass the same key again when retrying after a timeout or error, so Shopify does not repeat the operation. If left empty a key is generated; it is returned as idempotency_key and included in any error message.": "A unique key for this operation, for example a UUID such as \"3f1c2a9e-6b1d-4c8e-9a51-2f7d0e4b8c10\". Generate your own key on the first call and pass the same key again when retrying after a timeout or error, so Shopify does not repeat the operation. If left empty a key is generated; it is returned as idempotency_key and included in any error message.",
+ "The customer id, numeric or \"gid://shopify/Customer/…\".": "The customer id, numeric or \"gid://shopify/Customer/…\".",
+ "The address id from list_customer_addresses, for example \"gid://shopify/MailingAddress/1053318585?model_name=CustomerAddress\" or its number.": "The address id from list_customer_addresses, for example \"gid://shopify/MailingAddress/1053318585?model_name=CustomerAddress\" or its number.",
+ "The abandonment id, numeric or \"gid://shopify/Abandonment/…\".": "The abandonment id, numeric or \"gid://shopify/Abandonment/…\".",
+ "The abandoned checkout id, numeric or \"gid://shopify/AbandonedCheckout/…\". Find it with list_abandoned_checkouts.": "The abandoned checkout id, numeric or \"gid://shopify/AbandonedCheckout/…\". Find it with list_abandoned_checkouts.",
+ "The customer id, numeric such as \"207119551\" or \"gid://shopify/Customer/207119551\". Find it with search_customers.": "The customer id, numeric such as \"207119551\" or \"gid://shopify/Customer/207119551\". Find it with search_customers.",
+ "The job id returned by the start action, for example \"gid://shopify/Job/dc9b2604-c73b-45c6-8942-e235bac987e8\". A bare UUID such as \"dc9b2604-c73b-45c6-8942-e235bac987e8\" is also accepted.": "The job id returned by the start action, for example \"gid://shopify/Job/dc9b2604-c73b-45c6-8942-e235bac987e8\". A bare UUID such as \"dc9b2604-c73b-45c6-8942-e235bac987e8\" is also accepted.",
+ "The transaction id, numeric such as \"389404469\" or \"gid://shopify/OrderTransaction/389404469\". Find it with list_order_transactions.": "The transaction id, numeric such as \"389404469\" or \"gid://shopify/OrderTransaction/389404469\". Find it with list_order_transactions.",
+ "The order id: a numeric id such as \"450789469\" or a full id such as \"gid://shopify/Order/450789469\". Find it with search_orders.": "The order id: a numeric id such as \"450789469\" or a full id such as \"gid://shopify/Order/450789469\". Find it with search_orders.",
+ "The refund id, numeric or \"gid://shopify/Refund/…\". Find it with list_order_refunds.": "The refund id, numeric or \"gid://shopify/Refund/…\". Find it with list_order_refunds.",
+ "Shopify search syntax, for example \"created_at:>=2026-09-01\" or \"status:open\". Leave empty for all.": "Shopify search syntax, for example \"created_at:>=2026-09-01\" or \"status:open\". Leave empty for all.",
+ "Field to sort by. Defaults to the checkout id.": "Field to sort by. Defaults to the checkout id.",
+ "Return results in reverse sort order (for example newest first).": "Return results in reverse sort order (for example newest first).",
+ "How many records to return, 1 to 100. Defaults to 50.": "How many records to return, 1 to 100. Defaults to 50.",
+ "How many records to return, 1 to 250. Defaults to 50.": "How many records to return, 1 to 250. Defaults to 50.",
+ "Optional order search syntax to narrow the list, for example \"financial_status:paid\" or \"created_at:>=2026-01-01\".": "Optional order search syntax to narrow the list, for example \"financial_status:paid\" or \"created_at:>=2026-01-01\".",
+ "Field to sort by. Defaults to the order id.": "Field to sort by. Defaults to the order id.",
+ "How many records to return, 1 to 40. Defaults to 40.": "How many records to return, 1 to 40. Defaults to 40.",
+ "Shopify draft order search syntax, for example \"status:open\", \"status:invoice_sent\" or \"tag:quote\". Leave empty for all.": "Shopify draft order search syntax, for example \"status:open\", \"status:invoice_sent\" or \"tag:quote\". Leave empty for all.",
+ "Field to sort by. Defaults to the draft id.": "Field to sort by. Defaults to the draft id.",
+ "How many records to return, 1 to 60. Defaults to 50.": "How many records to return, 1 to 60. Defaults to 50.",
+ "Shopify search syntax, for example \"processed_at:>=2026-09-01\" or \"test:false\". Leave empty for all.": "Shopify search syntax, for example \"processed_at:>=2026-09-01\" or \"test:false\". Leave empty for all.",
+ "How many records to return, 1 to 200. Defaults to 50.": "How many records to return, 1 to 200. Defaults to 50.",
+ "Tags to remove, for example [\"follow-up\"].": "Tags to remove, for example [\"follow-up\"].",
+ "Shopify customer search syntax, for example \"email:[email protected]\", \"country:Canada\" or \"orders_count:>5\". Leave empty to list all customers.": "Shopify customer search syntax, for example \"email:[email protected]\", \"country:Canada\" or \"orders_count:>5\". Leave empty to list all customers.",
+ "Field to sort by. Defaults to the customer id.": "Field to sort by. Defaults to the customer id.",
+ "How many records to return, 1 to 130. Defaults to 50.": "How many records to return, 1 to 130. Defaults to 50.",
+ "Shopify order search syntax, for example \"status:open financial_status:paid\", \"tag:wholesale\" or \"created_at:>=2026-01-01\". Leave empty to list all orders.": "Shopify order search syntax, for example \"status:open financial_status:paid\", \"tag:wholesale\" or \"created_at:>=2026-01-01\". Leave empty to list all orders.",
+ "Email subject. Leave empty for the store default.": "Email subject. Leave empty for the store default.",
+ "A personal message added to the invitation.": "A personal message added to the invitation.",
+ "Send to this address instead of the draft email, for example \"[email protected]\".": "Send to this address instead of the draft email, for example \"[email protected]\".",
+ "A personal message added to the invoice email.": "A personal message added to the invoice email.",
+ "Why the order is cancelled.": "Why the order is cancelled.",
+ "Return the line items to inventory. Off by default.": "Return the line items to inventory. Off by default.",
+ "How to refund captured payments. Leave empty to cancel without refunding captured money (authorized payments are still voided).": "How to refund captured payments. Leave empty to cancel without refunding captured money (authorized payments are still voided).",
+ "Only for a store credit refund: when the credit expires (ISO 8601). Leave empty for no expiry.": "Only for a store credit refund: when the credit expires (ISO 8601). Leave empty for no expiry.",
+ "Email the customer about the cancellation. Off by default.": "Email the customer about the cancellation. Off by default.",
+ "Internal note about the cancellation, not shown to the customer.": "Internal note about the cancellation, not shown to the customer.",
+ "Yes makes this the customer's default address. Leave empty to leave the default unchanged.": "Yes makes this the customer's default address. Leave empty to leave the default unchanged.",
+ "New email, for example \"[email protected]\".": "New email, for example \"[email protected]\".",
+ "New phone in E.164 format, for example \"+16135551111\".": "New phone in E.164 format, for example \"+16135551111\".",
+ "New first name.": "New first name.",
+ "New last name.": "New last name.",
+ "New internal note. Replaces the existing note.": "New internal note. Replaces the existing note.",
+ "The complete new tag list. Replaces every existing tag; leave empty to keep the current tags (use clear_tags to remove all).": "The complete new tag list. Replaces every existing tag; leave empty to keep the current tags (use clear_tags to remove all).",
+ "Set whether the customer is exempt from taxes. Leave empty to keep the current setting.": "Set whether the customer is exempt from taxes. Leave empty to keep the current setting.",
+ "Remove the existing note. Leave note empty when using this.": "Remove the existing note. Leave note empty when using this.",
+ "Remove every tag. Leave tags empty when using this.": "Remove every tag. Leave tags empty when using this.",
+ "The complete new list of line items. Replaces every existing line item; leave empty to keep the current items.": "The complete new list of line items. Replaces every existing line item; leave empty to keep the current items.",
+ "Three-letter currency for the unit prices given in line items, for example \"USD\".": "Three-letter currency for the unit prices given in line items, for example \"USD\".",
+ "Customer the draft is for, numeric or \"gid://shopify/Customer/…\".": "Customer the draft is for, numeric or \"gid://shopify/Customer/…\".",
+ "Email the invoice is sent to.": "Email the invoice is sent to.",
+ "Contact phone in E.164 format.": "Contact phone in E.164 format.",
+ "Purchase order number.": "Purchase order number.",
+ "Payment terms to apply, as a full id such as \"gid://shopify/PaymentTermsTemplate/4\". With payment terms, completing the draft leaves the order payment-pending.": "Payment terms to apply, as a full id such as \"gid://shopify/PaymentTermsTemplate/4\". With payment terms, completing the draft leaves the order payment-pending.",
+ "Start date for net payment terms (for example net 30), ISO 8601.": "Start date for net payment terms (for example net 30), ISO 8601.",
+ "Due date for fixed-date payment terms, ISO 8601.": "Due date for fixed-date payment terms, ISO 8601.",
+ "Hold the stock for this draft until this time (ISO 8601).": "Hold the stock for this draft until this time (ISO 8601).",
+ "New contact email, for example \"[email protected]\".": "New contact email, for example \"[email protected]\".",
+ "New contact phone in E.164 format, for example \"+16135551111\".": "New contact phone in E.164 format, for example \"+16135551111\".",
+ "The complete new tag list, for example [\"wholesale\", \"priority\"]. Replaces every existing tag; leave empty to keep the current tags (use clear_tags to remove all).": "The complete new tag list, for example [\"wholesale\", \"priority\"]. Replaces every existing tag; leave empty to keep the current tags (use clear_tags to remove all).",
+ "The AUTHORIZATION transaction to void, numeric or \"gid://shopify/OrderTransaction/…\". Find it with list_order_transactions.": "The AUTHORIZATION transaction to void, numeric or \"gid://shopify/OrderTransaction/…\". Find it with list_order_transactions.",
"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.",
"Active": "Active",
"Draft": "Draft",
"Archived": "Archived",
+ "Draft order": "Draft order",
+ "Subscription contract": "Subscription contract",
+ "Yes": "Yes",
+ "No": "No",
+ "Subscribed": "Subscribed",
+ "Not subscribed": "Not subscribed",
+ "Unsubscribed": "Unsubscribed",
+ "Pending confirmation": "Pending confirmation",
+ "Single opt-in": "Single opt-in",
+ "Confirmed opt-in": "Confirmed opt-in",
+ "Unknown": "Unknown",
+ "Percentage": "Percentage",
+ "Fixed amount": "Fixed amount",
+ "High": "High",
+ "Medium": "Medium",
+ "Low": "Low",
+ "None": "None",
+ "Pending": "Pending",
+ "Authorized": "Authorized",
+ "Paid": "Paid",
+ "Partially paid": "Partially paid",
+ "Percentage off items": "Percentage off items",
+ "Fixed amount off items": "Fixed amount off items",
+ "Free shipping": "Free shipping",
+ "Bypass (do not change stock)": "Bypass (do not change stock)",
+ "Decrement, obey inventory policy": "Decrement, obey inventory policy",
+ "Decrement, ignore inventory policy": "Decrement, ignore inventory policy",
+ "Created at": "Created at",
+ "Checkout id": "Checkout id",
+ "Customer name": "Customer name",
+ "Total price": "Total price",
+ "Relevance (with a query)": "Relevance (with a query)",
+ "ID": "ID",
+ "Processed at": "Processed at",
+ "Updated at": "Updated at",
+ "Order number": "Order number",
+ "Number": "Number",
+ "Name": "Name",
+ "Financial status": "Financial status",
+ "Fulfillment status": "Fulfillment status",
+ "Customer changed or cancelled the order": "Customer changed or cancelled the order",
+ "Payment declined": "Payment declined",
+ "Fraudulent order": "Fraudulent order",
+ "Items unavailable": "Items unavailable",
+ "Staff error": "Staff error",
+ "Other": "Other",
+ "Refund to the original payment methods": "Refund to the original payment methods",
+ "Refund as store credit": "Refund as store credit",
"GET": "GET",
"POST": "POST",
"PATCH": "PATCH",
"PUT": "PUT",
"DELETE": "DELETE",
"HEAD": "HEAD",
- "None": "None",
- "JSON": "JSON",
- "Form Data": "Form Data",
- "Raw": "Raw",
"New Abandoned Checkout": "New Abandoned Checkout",
"New Cancelled Order": "New Cancelled Order",
"New Customer": "New Customer",
@@ -156,10 +562,5 @@
"Triggered when a new customer is created": "Triggered when a new customer is created",
"Triggered when a new order is created": "Triggered when a new order is created",
"Triggered when a product is updated.": "Triggered when a product is updated.",
- "Triggered when a paid order is created": "Triggered when a paid order is created",
- "\nUse this option for custom apps created in the Shopify admin **before January 1, 2026**. Shopify no longer lets you create these apps, but existing ones keep working and their Admin API access token does not expire. For a new app, choose the **Dev Dashboard app** option instead.\n\n**Shop Name**:\n\nYou can find your shop name in the URL. For example, if the URL is `https://example.myshopify.com/admin`, then your shop name is **example**.\n\n**Admin Token**:\n\n1. Log in to your Shopify admin.\n2. Go to **Settings*": "\nUse this option for custom apps created in the Shopify admin **before January 1, 2026**. Shopify no longer lets you create these apps, but existing ones keep working and their Admin API access token does not expire. For a new app, choose the **Dev Dashboard app** option instead.\n\n**Shop Name**:\n\nYou can find your shop name in the URL. For example, if the URL is `https://example.myshopify.com/admin`, then your shop name is **example**.\n\n**Admin Token**:\n\n1. Log in to your Shopify admin.\n2. Go to **Settings** -> **Apps and sales channels** -> **Develop apps**.\n3. Open your existing custom app.\n4. Under **Configuration**, check that the Admin API scopes include: `read_orders`, `write_orders`, `read_customers`, `write_customers`, `read_products`, `write_products`, `read_draft_orders`, `write_draft_orders`, `read_locations`, `read_inventory`, `write_inventory`, `read_themes`, `write_fulfillments`.\n5. Under **API credentials**, copy the **Admin API access token**.\n",
- "Admin Token (legacy custom app)": "Admin Token (legacy custom app)",
- "The part before .myshopify.com in your store URL. For https://example.myshopify.com, enter example.": "The part before .myshopify.com in your store URL. For https://example.myshopify.com, enter example.",
- "\nUse this option for apps created in the Shopify **Dev Dashboard** (all new apps from January 1, 2026). Activepieces exchanges the app's client ID and client secret for an access token and renews it automatically every 24 hours.\n\n**Important:** the app and the store must belong to the **same Shopify organization**, otherwise Shopify rejects the connection.\n\n1. Go to the [Shopify Dev Dashboard](https://dev.shopify.com/dashboard) and click **Create app**. Give it a name.\n2. Create a version of the app and, un": "\nUse this option for apps created in the Shopify **Dev Dashboard** (all new apps from January 1, 2026). Activepieces exchanges the app's client ID and client secret for an access token and renews it automatically every 24 hours.\n\n**Important:** the app and the store must belong to the **same Shopify organization**, otherwise Shopify rejects the connection.\n\n1. Go to the [Shopify Dev Dashboard](https://dev.shopify.com/dashboard) and click **Create app**. Give it a name.\n2. Create a version of the app and, under **Access** -> **Scopes**, select these Admin API scopes: `read_orders`, `write_orders`, `read_customers`, `write_customers`, `read_products`, `write_products`, `read_draft_orders`, `write_draft_orders`, `read_locations`, `read_inventory`, `write_inventory`, `read_themes`, `write_fulfillments`.\n3. Release a version with these scopes and install/approve it on the store: from the app's **Home** page, click **Install app** and install it on your store (reinstall it if it was installed before the scopes were added). The store must be in the same organization as the app.\n4. Open the app's **Settings** page and copy the **Client ID** and **Client secret**.\n5. Enter your shop name below (for `https://example.myshopify.com`, enter **example**), then paste the client ID and client secret.\n\n**Note:** If you change the app's scopes later, reconnect this connection so a new token is issued (tokens keep the scopes they were issued with for up to 24 hours).\n",
- "Dev Dashboard app": "Dev Dashboard app"
+ "Triggered when a paid order is created": "Triggered when a paid order is created"
}
\ No newline at end of file
diff --git a/packages/pieces/community/shopify/src/index.ts b/packages/pieces/community/shopify/src/index.ts
index 1353e3b91f6..f091a693f7e 100644
--- a/packages/pieces/community/shopify/src/index.ts
+++ b/packages/pieces/community/shopify/src/index.ts
@@ -27,6 +27,64 @@ import { updateOrderAction } from './lib/actions/update-order';
import { updateProductAction } from './lib/actions/update-product';
import { uploadProductImageAction } from './lib/actions/upload-product-image';
import { shopifyAuth, shopifyAuthHelpers } from './lib/common/auth';
+import { shopifyAiAddTags } from './lib/actions/ai/add-tags';
+import { shopifyAiSendPaymentMethodUpdateEmail } from './lib/actions/ai/send-payment-method-update-email';
+import { shopifyAiResolveRequestedOrderEdit } from './lib/actions/ai/resolve-requested-order-edit';
+import { shopifyAiDeclineRequestedOrderEdit } from './lib/actions/ai/decline-requested-order-edit';
+import { shopifyAiCreateRequestedOrderEdit } from './lib/actions/ai/create-requested-order-edit';
+import { shopifyAiCalculateRequestedOrderEdit } from './lib/actions/ai/calculate-requested-order-edit';
+import { shopifyAiListRequestedOrderEdits } from './lib/actions/ai/list-requested-order-edits';
+import { shopifyAiArchiveOrder } from './lib/actions/ai/archive-order';
+import { shopifyAiCalculateRefund } from './lib/actions/ai/calculate-refund';
+import { shopifyAiCaptureOrderPayment } from './lib/actions/ai/capture-order-payment';
+import { shopifyAiCompleteDraftOrder } from './lib/actions/ai/complete-draft-order';
+import { shopifyAiCountAbandonedCheckouts } from './lib/actions/ai/count-abandoned-checkouts';
+import { shopifyAiCountCustomerSegments } from './lib/actions/ai/count-customer-segments';
+import { shopifyAiCountCustomers } from './lib/actions/ai/count-customers';
+import { shopifyAiCountDraftOrders } from './lib/actions/ai/count-draft-orders';
+import { shopifyAiCreateCustomerAddress } from './lib/actions/ai/create-customer-address';
+import { shopifyAiCreateCustomerProfile } from './lib/actions/ai/create-customer-profile';
+import { shopifyAiCreateDraftOrderWithLineItems } from './lib/actions/ai/create-draft-order-with-line-items';
+import { shopifyAiCreateOrderRiskAssessment } from './lib/actions/ai/create-order-risk-assessment';
+import { shopifyAiCreateOrderWithLineItems } from './lib/actions/ai/create-order-with-line-items';
+import { shopifyAiCreateRefund } from './lib/actions/ai/create-refund';
+import { shopifyAiDeleteCustomerAddress } from './lib/actions/ai/delete-customer-address';
+import { shopifyAiDeleteCustomer } from './lib/actions/ai/delete-customer';
+import { shopifyAiDeleteDraftOrder } from './lib/actions/ai/delete-draft-order';
+import { shopifyAiDeleteOrder } from './lib/actions/ai/delete-order';
+import { shopifyAiGenerateCustomerActivationUrl } from './lib/actions/ai/generate-customer-activation-url';
+import { shopifyAiGetAbandonment } from './lib/actions/ai/get-abandonment';
+import { shopifyAiGetCheckoutAbandonment } from './lib/actions/ai/get-checkout-abandonment';
+import { shopifyAiGetCustomerProfile } from './lib/actions/ai/get-customer-profile';
+import { shopifyAiGetDraftOrder } from './lib/actions/ai/get-draft-order';
+import { shopifyAiGetGrantedAccessScopes } from './lib/actions/ai/get-granted-access-scopes';
+import { shopifyAiGetJob } from './lib/actions/ai/get-job';
+import { shopifyAiGetOrderRiskAssessments } from './lib/actions/ai/get-order-risk-assessments';
+import { shopifyAiGetOrderTransaction } from './lib/actions/ai/get-order-transaction';
+import { shopifyAiGetOrder } from './lib/actions/ai/get-order';
+import { shopifyAiGetRefund } from './lib/actions/ai/get-refund';
+import { shopifyAiGetShop } from './lib/actions/ai/get-shop';
+import { shopifyAiListAbandonedCheckouts } from './lib/actions/ai/list-abandoned-checkouts';
+import { shopifyAiListCustomerAddresses } from './lib/actions/ai/list-customer-addresses';
+import { shopifyAiListCustomerOrders } from './lib/actions/ai/list-customer-orders';
+import { shopifyAiListDraftOrders } from './lib/actions/ai/list-draft-orders';
+import { shopifyAiListOrderRefunds } from './lib/actions/ai/list-order-refunds';
+import { shopifyAiListOrderTransactions } from './lib/actions/ai/list-order-transactions';
+import { shopifyAiListTenderTransactions } from './lib/actions/ai/list-tender-transactions';
+import { shopifyAiMarkOrderAsPaid } from './lib/actions/ai/mark-order-as-paid';
+import { shopifyAiRemoveTags } from './lib/actions/ai/remove-tags';
+import { shopifyAiSearchCustomers } from './lib/actions/ai/search-customers';
+import { shopifyAiSearchOrders } from './lib/actions/ai/search-orders';
+import { shopifyAiSendCustomerAccountInvite } from './lib/actions/ai/send-customer-account-invite';
+import { shopifyAiSendDraftOrderInvoice } from './lib/actions/ai/send-draft-order-invoice';
+import { shopifyAiSetDefaultCustomerAddress } from './lib/actions/ai/set-default-customer-address';
+import { shopifyAiStartOrderCancellation } from './lib/actions/ai/start-order-cancellation';
+import { shopifyAiUnarchiveOrder } from './lib/actions/ai/unarchive-order';
+import { shopifyAiUpdateCustomerAddress } from './lib/actions/ai/update-customer-address';
+import { shopifyAiUpdateCustomerProfile } from './lib/actions/ai/update-customer-profile';
+import { shopifyAiUpdateDraftOrder } from './lib/actions/ai/update-draft-order';
+import { shopifyAiUpdateOrderDetails } from './lib/actions/ai/update-order-details';
+import { shopifyAiVoidOrderTransaction } from './lib/actions/ai/void-order-transaction';
import { newAbandonedCheckout } from './lib/triggers/new-abandoned-checkout';
import { newCancelledOrder } from './lib/triggers/new-cancelled-order';
import { newCustomer } from './lib/triggers/new-customer';
@@ -42,7 +100,7 @@ export const shopify = createPiece({
logoUrl: 'https://cdn.activepieces.com/pieces/shopify.png',
authors: ["kishanprmr","MoShizzle","AbdulTheActivePiecer","khaledmashaly","abuaboud","ikus060"],
categories: [PieceCategory.COMMERCE],
- minimumSupportedRelease: '0.87.0',
+ minimumSupportedRelease: '0.88.2',
auth: shopifyAuth,
actions: [
adjustInventoryLevelAction,
@@ -71,6 +129,64 @@ export const shopify = createPiece({
updateOrderAction,
updateProductAction,
uploadProductImageAction,
+ shopifyAiAddTags,
+ shopifyAiSendPaymentMethodUpdateEmail,
+ shopifyAiResolveRequestedOrderEdit,
+ shopifyAiDeclineRequestedOrderEdit,
+ shopifyAiCreateRequestedOrderEdit,
+ shopifyAiCalculateRequestedOrderEdit,
+ shopifyAiListRequestedOrderEdits,
+ shopifyAiArchiveOrder,
+ shopifyAiCalculateRefund,
+ shopifyAiCaptureOrderPayment,
+ shopifyAiCompleteDraftOrder,
+ shopifyAiCountAbandonedCheckouts,
+ shopifyAiCountCustomerSegments,
+ shopifyAiCountCustomers,
+ shopifyAiCountDraftOrders,
+ shopifyAiCreateCustomerAddress,
+ shopifyAiCreateCustomerProfile,
+ shopifyAiCreateDraftOrderWithLineItems,
+ shopifyAiCreateOrderRiskAssessment,
+ shopifyAiCreateOrderWithLineItems,
+ shopifyAiCreateRefund,
+ shopifyAiDeleteCustomerAddress,
+ shopifyAiDeleteCustomer,
+ shopifyAiDeleteDraftOrder,
+ shopifyAiDeleteOrder,
+ shopifyAiGenerateCustomerActivationUrl,
+ shopifyAiGetAbandonment,
+ shopifyAiGetCheckoutAbandonment,
+ shopifyAiGetCustomerProfile,
+ shopifyAiGetDraftOrder,
+ shopifyAiGetGrantedAccessScopes,
+ shopifyAiGetJob,
+ shopifyAiGetOrderRiskAssessments,
+ shopifyAiGetOrderTransaction,
+ shopifyAiGetOrder,
+ shopifyAiGetRefund,
+ shopifyAiGetShop,
+ shopifyAiListAbandonedCheckouts,
+ shopifyAiListCustomerAddresses,
+ shopifyAiListCustomerOrders,
+ shopifyAiListDraftOrders,
+ shopifyAiListOrderRefunds,
+ shopifyAiListOrderTransactions,
+ shopifyAiListTenderTransactions,
+ shopifyAiMarkOrderAsPaid,
+ shopifyAiRemoveTags,
+ shopifyAiSearchCustomers,
+ shopifyAiSearchOrders,
+ shopifyAiSendCustomerAccountInvite,
+ shopifyAiSendDraftOrderInvoice,
+ shopifyAiSetDefaultCustomerAddress,
+ shopifyAiStartOrderCancellation,
+ shopifyAiUnarchiveOrder,
+ shopifyAiUpdateCustomerAddress,
+ shopifyAiUpdateCustomerProfile,
+ shopifyAiUpdateDraftOrder,
+ shopifyAiUpdateOrderDetails,
+ shopifyAiVoidOrderTransaction,
createCustomApiCallAction({
baseUrl: (auth) => {
return auth ? shopifyAuthHelpers.getBaseUrl(auth) : '';
diff --git a/packages/pieces/community/shopify/src/lib/actions/ai/add-tags.ts b/packages/pieces/community/shopify/src/lib/actions/ai/add-tags.ts
new file mode 100644
index 00000000000..a5ed85155ab
--- /dev/null
+++ b/packages/pieces/community/shopify/src/lib/actions/ai/add-tags.ts
@@ -0,0 +1,72 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { shopifyAuth } from '../../..';
+import { shopifyGraphqlClient, shopifyValues } from '../../common/graphql';
+import { addTagsOutputSchema } from '../../output-schemas/orders';
+
+export const shopifyAiAddTags = createAction({
+ auth: shopifyAuth,
+ name: 'add_tags',
+ classification: 'WRITE',
+ displayName: 'Add Tags',
+ description: 'Add tags to an order, draft order, customer or product.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Adds one or more tags to an order, draft order, customer or product while keeping its existing tags; prefer this over sending a full tag list to an update action. Adding a tag that is already present changes nothing, so repeating is safe. Returns the resulting tag list.',
+ idempotent: true,
+ },
+ outputSchema: addTagsOutputSchema,
+ props: {
+ resource_type: Property.StaticDropdown({
+ displayName: 'Resource Type',
+ description: 'What kind of record the id belongs to. Used to build the full id when a numeric id is given.',
+ required: true,
+ options: {
+ options: [
+ { label: 'Order', value: 'Order' },
+ { label: 'Draft order', value: 'DraftOrder' },
+ { label: 'Customer', value: 'Customer' },
+ { label: 'Product', value: 'Product' },
+ ],
+ },
+ }),
+ resource_id: Property.ShortText({
+ displayName: 'Resource ID',
+ description: 'Numeric id such as "450789469" or a full id such as "gid://shopify/Order/450789469".',
+ required: true,
+ }),
+ tags: Property.Array({
+ displayName: 'Tags',
+ description: 'Tags to add, for example ["vip", "follow-up"].',
+ required: true,
+ }),
+ },
+ async run({ auth, propsValue }) {
+ const tags = shopifyValues.readStringList(propsValue.tags) ?? [];
+ if (tags.length === 0) {
+ throw new Error('Provide at least one tag.');
+ }
+ const id = shopifyGraphqlClient.toGid({ type: propsValue.resource_type, id: propsValue.resource_id });
+ const { data, redactedFields } = await shopifyGraphqlClient.request<{
+ tagsAdd: { node: TaggedNode | null } | null;
+ }>({
+ auth,
+ query: `mutation AddTags($id: ID!, $tags: [String!]!) { tagsAdd(id: $id, tags: $tags) { node { id ${TAGGED_NODE_FRAGMENTS} } userErrors { field message } } }`,
+ variables: { id, tags },
+ });
+ return {
+ id: data.tagsAdd?.node?.id ?? id,
+ tags_added: tags.join(', '),
+ tags: Array.isArray(data.tagsAdd?.node?.tags) ? data.tagsAdd?.node?.tags?.join(', ') ?? null : null,
+ redacted_fields: redactedFields,
+ };
+ },
+});
+
+const TAGGED_NODE_FRAGMENTS =
+ '... on Order { tags } ... on DraftOrder { tags } ... on Customer { tags } ... on Product { tags }';
+
+type TaggedNode = {
+ id: string;
+ tags?: string[] | null;
+};
diff --git a/packages/pieces/community/shopify/src/lib/actions/ai/archive-order.ts b/packages/pieces/community/shopify/src/lib/actions/ai/archive-order.ts
new file mode 100644
index 00000000000..a7432d3cfce
--- /dev/null
+++ b/packages/pieces/community/shopify/src/lib/actions/ai/archive-order.ts
@@ -0,0 +1,50 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { shopifyAuth } from '../../..';
+import {
+ GqlOrder,
+ shopifyFields,
+ shopifyGraphqlClient,
+ shopifyMappers,
+} from '../../common/graphql';
+import { orderSummaryOutputSchema } from '../../output-schemas/orders';
+
+export const shopifyAiArchiveOrder = createAction({
+ auth: shopifyAuth,
+ name: 'archive_order',
+ classification: 'WRITE',
+ displayName: 'Archive Order',
+ description: 'Close (archive) an order.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Closes an order, which Shopify shows as archived; use it once an order is fully paid and fulfilled. This does not cancel or refund anything, and unarchive_order reopens it. Archiving an already archived order leaves it archived, so repeating is safe.',
+ idempotent: true,
+ },
+ outputSchema: orderSummaryOutputSchema,
+ props: {
+ order_id: Property.ShortText({
+ displayName: 'Order ID',
+ description: 'The order id, numeric or "gid://shopify/Order/…". Find it with search_orders.',
+ required: true,
+ }),
+ },
+ async run({ auth, propsValue }) {
+ const id = shopifyGraphqlClient.toGid({ type: 'Order', id: propsValue.order_id });
+ const { data, redactedFields } = await shopifyGraphqlClient.request<{
+ orderClose: { order: GqlOrder | null } | null;
+ }>({
+ auth,
+ query: `mutation ArchiveOrder($input: OrderCloseInput!) { orderClose(input: $input) { order { ${shopifyFields.ORDER_SUMMARY_FIELDS} } userErrors { field message } } }`,
+ primaryPaths: ['orderClose.order'],
+ variables: { input: { id } },
+ });
+ const order = data.orderClose?.order;
+ if (!order) {
+ throw new Error(`Order ${id} was not returned by Shopify.`);
+ }
+ return {
+ ...shopifyMappers.mapOrderSummary(order),
+ redacted_fields: redactedFields,
+ };
+ },
+});
diff --git a/packages/pieces/community/shopify/src/lib/actions/ai/calculate-refund.ts b/packages/pieces/community/shopify/src/lib/actions/ai/calculate-refund.ts
new file mode 100644
index 00000000000..78542e0ac8d
--- /dev/null
+++ b/packages/pieces/community/shopify/src/lib/actions/ai/calculate-refund.ts
@@ -0,0 +1,154 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { shopifyAuth } from '../../..';
+import {
+ GqlMoneyBag,
+ shopifyFields,
+ shopifyGraphqlClient,
+ shopifyProps,
+ shopifyValues,
+} from '../../common/graphql';
+import { calculateRefundOutputSchema } from '../../output-schemas/orders';
+
+export const shopifyAiCalculateRefund = createAction({
+ auth: shopifyAuth,
+ name: 'calculate_refund',
+ classification: 'READ',
+ displayName: 'Calculate Refund',
+ description: 'Preview the refund Shopify suggests for an order, without refunding.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Previews a refund without moving money: returns the amount, tax, shipping and the suggested refund transactions (parent transaction id, gateway, amount) for the chosen line items and shipping. Every amount is in the shop currency; the presentment_* fields give the same amounts in the customer (presentment) currency. Run it before create_refund and pass its suggested transactions and line items there; when presentment_currency_code differs from currency_code, pass the presentment amounts and presentment_currency_code to create_refund. Read-only and safe to repeat.',
+ idempotent: true,
+ },
+ outputSchema: calculateRefundOutputSchema,
+ props: {
+ order_id: Property.ShortText({
+ displayName: 'Order ID',
+ description: 'The order id, numeric or "gid://shopify/Order/…". Find it with search_orders.',
+ required: true,
+ }),
+ line_items: shopifyProps.refundLineItems(),
+ refund_shipping: Property.Checkbox({
+ displayName: 'Refund All Shipping',
+ description: 'Include the full shipping cost in the suggestion. Off by default.',
+ required: false,
+ defaultValue: false,
+ }),
+ shipping_amount: Property.Number({
+ displayName: 'Shipping Amount',
+ description: 'Refund only this much shipping, for example 4.50. Ignored when refunding all shipping.',
+ required: false,
+ }),
+ suggest_full_refund: Property.Checkbox({
+ displayName: 'Suggest Full Refund',
+ description: 'Suggest refunding everything still refundable on the order. Off by default.',
+ required: false,
+ defaultValue: false,
+ }),
+ },
+ async run({ auth, propsValue }) {
+ const id = shopifyGraphqlClient.toGid({ type: 'Order', id: propsValue.order_id });
+ const refundShipping = propsValue.refund_shipping ?? false;
+ const shippingAmount =
+ !refundShipping && propsValue.shipping_amount !== undefined && propsValue.shipping_amount !== null
+ ? String(propsValue.shipping_amount)
+ : undefined;
+ const { data, redactedFields } = await shopifyGraphqlClient.request<{
+ order: { id: string; suggestedRefund?: GqlSuggestedRefund | null } | null;
+ }>({
+ auth,
+ query: `query CalculateRefund($id: ID!, $refundLineItems: [RefundLineItemInput!], $refundShipping: Boolean, $shippingAmount: Money, $suggestFullRefund: Boolean) { order(id: $id) { id suggestedRefund(refundLineItems: $refundLineItems, refundShipping: $refundShipping, shippingAmount: $shippingAmount, suggestFullRefund: $suggestFullRefund) { amountSet { ${shopifyFields.MONEY_WITH_PRESENTMENT_FIELDS} } subtotalSet { ${shopifyFields.MONEY_WITH_PRESENTMENT_FIELDS} } totalTaxSet { ${shopifyFields.MONEY_WITH_PRESENTMENT_FIELDS} } maximumRefundableSet { ${shopifyFields.MONEY_WITH_PRESENTMENT_FIELDS} } discountedSubtotalSet { ${shopifyFields.MONEY_WITH_PRESENTMENT_FIELDS} } shipping { amountSet { ${shopifyFields.MONEY_WITH_PRESENTMENT_FIELDS} } maximumRefundableSet { ${shopifyFields.MONEY_WITH_PRESENTMENT_FIELDS} } taxSet { ${shopifyFields.MONEY_WITH_PRESENTMENT_FIELDS} } } refundLineItems { quantity restockType priceSet { ${shopifyFields.MONEY_WITH_PRESENTMENT_FIELDS} } subtotalSet { ${shopifyFields.MONEY_WITH_PRESENTMENT_FIELDS} } totalTaxSet { ${shopifyFields.MONEY_WITH_PRESENTMENT_FIELDS} } lineItem { id title sku } location { id } } suggestedTransactions { kind gateway amountSet { ${shopifyFields.MONEY_WITH_PRESENTMENT_FIELDS} } maximumRefundableSet { ${shopifyFields.MONEY_WITH_PRESENTMENT_FIELDS} } parentTransaction { id } } } } }`,
+ primaryPaths: ['order.suggestedRefund'],
+ variables: shopifyValues.compact({
+ id,
+ refundLineItems: shopifyValues.buildRefundLineItems(propsValue.line_items),
+ refundShipping,
+ shippingAmount,
+ suggestFullRefund: propsValue.suggest_full_refund ?? false,
+ }),
+ });
+ if (!data.order) {
+ throw new Error(`Order ${id} was not found.`);
+ }
+ const suggestion = data.order.suggestedRefund;
+ return {
+ order_id: data.order.id,
+ amount: shopifyValues.money(suggestion?.amountSet),
+ currency_code: suggestion?.amountSet?.shopMoney?.currencyCode ?? null,
+ presentment_amount: shopifyValues.presentmentMoney(suggestion?.amountSet),
+ presentment_currency_code: shopifyValues.presentmentCurrency(suggestion?.amountSet),
+ subtotal: shopifyValues.money(suggestion?.subtotalSet),
+ presentment_subtotal: shopifyValues.presentmentMoney(suggestion?.subtotalSet),
+ total_tax: shopifyValues.money(suggestion?.totalTaxSet),
+ presentment_total_tax: shopifyValues.presentmentMoney(suggestion?.totalTaxSet),
+ maximum_refundable: shopifyValues.money(suggestion?.maximumRefundableSet),
+ presentment_maximum_refundable: shopifyValues.presentmentMoney(suggestion?.maximumRefundableSet),
+ discounted_subtotal: shopifyValues.money(suggestion?.discountedSubtotalSet),
+ presentment_discounted_subtotal: shopifyValues.presentmentMoney(suggestion?.discountedSubtotalSet),
+ shipping_amount: shopifyValues.money(suggestion?.shipping?.amountSet),
+ presentment_shipping_amount: shopifyValues.presentmentMoney(suggestion?.shipping?.amountSet),
+ shipping_tax: shopifyValues.money(suggestion?.shipping?.taxSet),
+ presentment_shipping_tax: shopifyValues.presentmentMoney(suggestion?.shipping?.taxSet),
+ shipping_maximum_refundable: shopifyValues.money(suggestion?.shipping?.maximumRefundableSet),
+ presentment_shipping_maximum_refundable: shopifyValues.presentmentMoney(
+ suggestion?.shipping?.maximumRefundableSet
+ ),
+ refund_line_items: (suggestion?.refundLineItems ?? []).map((item) => ({
+ line_item_id: item.lineItem?.id ?? null,
+ title: item.lineItem?.title ?? null,
+ sku: item.lineItem?.sku ?? null,
+ quantity: item.quantity ?? null,
+ restock_type: item.restockType ?? null,
+ location_id: item.location?.id ?? null,
+ price: shopifyValues.money(item.priceSet),
+ presentment_price: shopifyValues.presentmentMoney(item.priceSet),
+ subtotal: shopifyValues.money(item.subtotalSet),
+ presentment_subtotal: shopifyValues.presentmentMoney(item.subtotalSet),
+ total_tax: shopifyValues.money(item.totalTaxSet),
+ presentment_total_tax: shopifyValues.presentmentMoney(item.totalTaxSet),
+ })),
+ suggested_transactions: (suggestion?.suggestedTransactions ?? []).map((transaction) => ({
+ kind: transaction.kind ?? null,
+ gateway: transaction.gateway ?? null,
+ parent_transaction_id: transaction.parentTransaction?.id ?? null,
+ amount: shopifyValues.money(transaction.amountSet),
+ currency_code: transaction.amountSet?.shopMoney?.currencyCode ?? null,
+ presentment_amount: shopifyValues.presentmentMoney(transaction.amountSet),
+ presentment_currency_code: shopifyValues.presentmentCurrency(transaction.amountSet),
+ maximum_refundable: shopifyValues.money(transaction.maximumRefundableSet),
+ presentment_maximum_refundable: shopifyValues.presentmentMoney(transaction.maximumRefundableSet),
+ })),
+ redacted_fields: redactedFields,
+ };
+ },
+});
+
+type GqlSuggestedRefund = {
+ amountSet?: GqlMoneyBag | null;
+ subtotalSet?: GqlMoneyBag | null;
+ totalTaxSet?: GqlMoneyBag | null;
+ maximumRefundableSet?: GqlMoneyBag | null;
+ discountedSubtotalSet?: GqlMoneyBag | null;
+ shipping?: {
+ amountSet?: GqlMoneyBag | null;
+ maximumRefundableSet?: GqlMoneyBag | null;
+ taxSet?: GqlMoneyBag | null;
+ } | null;
+ refundLineItems?: {
+ quantity?: number | null;
+ restockType?: string | null;
+ priceSet?: GqlMoneyBag | null;
+ subtotalSet?: GqlMoneyBag | null;
+ totalTaxSet?: GqlMoneyBag | null;
+ lineItem?: { id?: string | null; title?: string | null; sku?: string | null } | null;
+ location?: { id?: string | null } | null;
+ }[] | null;
+ suggestedTransactions?: {
+ kind?: string | null;
+ gateway?: string | null;
+ amountSet?: GqlMoneyBag | null;
+ maximumRefundableSet?: GqlMoneyBag | null;
+ parentTransaction?: { id?: string | null } | null;
+ }[] | null;
+};
diff --git a/packages/pieces/community/shopify/src/lib/actions/ai/calculate-requested-order-edit.ts b/packages/pieces/community/shopify/src/lib/actions/ai/calculate-requested-order-edit.ts
new file mode 100644
index 00000000000..fdf6c9a9986
--- /dev/null
+++ b/packages/pieces/community/shopify/src/lib/actions/ai/calculate-requested-order-edit.ts
@@ -0,0 +1,53 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { shopifyAuth } from '../../..';
+import { shopifyGraphqlClient } from '../../common/graphql';
+import {
+ GqlCalculatedRequestedOrderEdit,
+ requestedOrderEditFields,
+ requestedOrderEditHelpers,
+} from '../../common/requested-order-edits';
+import { calculateRequestedOrderEditOutputSchema } from '../../output-schemas/requested-order-edits';
+
+export const shopifyAiCalculateRequestedOrderEdit = createAction({
+ auth: shopifyAuth,
+ name: 'calculate_requested_order_edit',
+ classification: 'READ',
+ displayName: 'Calculate Requested Order Edit',
+ description: 'Preview the money effect of removing line items from an order, without changing anything.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Previews the financial outcome of a buyer-style order edit that removes unfulfilled line items: the subtotal, order-level discounts, tax and total of the removed items (shop and presentment currency) plus the per-line-item amounts. Nothing is saved and no one is notified. Take the line item ids and unfulfilled quantities from get_order; the quantity per line item cannot exceed its unfulfilled quantity. Run it before create_requested_order_edit to show the buyer or merchant the impact. Needs the read_orders access scope. Without the read_all_orders scope only orders from the last 60 days are visible. Read-only, safe to repeat.',
+ idempotent: true,
+ },
+ outputSchema: calculateRequestedOrderEditOutputSchema,
+ props: {
+ order_id: Property.ShortText({
+ displayName: 'Order ID',
+ description: 'The order id, numeric or "gid://shopify/Order/…". Find it with search_orders.',
+ required: true,
+ }),
+ line_items: requestedOrderEditHelpers.removalsProp(),
+ },
+ async run({ auth, propsValue }) {
+ const orderId = requestedOrderEditHelpers.readTypedId({ type: 'Order', value: propsValue.order_id, label: 'order_id' });
+ const removals = requestedOrderEditHelpers.buildRemovals(propsValue.line_items);
+ const { data, redactedFields } = await shopifyGraphqlClient.request<{
+ requestedOrderEditCalculate: GqlCalculatedRequestedOrderEdit | null;
+ }>({
+ auth,
+ query: `query CalculateRequestedOrderEdit($input: CalculateRequestedOrderEditInput!) { requestedOrderEditCalculate(input: $input) { ${requestedOrderEditFields.CALCULATED_REQUESTED_ORDER_EDIT_FIELDS} } }`,
+ variables: { input: { orderId, lineItems: { removals } } },
+ primaryPaths: ['requestedOrderEditCalculate'],
+ });
+ const calculated = data.requestedOrderEditCalculate;
+ if (!calculated) {
+ throw new Error(`Shopify returned no calculation for order ${orderId}. Check the order and line item ids with get_order.`);
+ }
+ return {
+ order_id: orderId,
+ ...requestedOrderEditHelpers.mapCalculatedRequestedOrderEdit(calculated),
+ redacted_fields: redactedFields,
+ };
+ },
+});
diff --git a/packages/pieces/community/shopify/src/lib/actions/ai/capture-order-payment.ts b/packages/pieces/community/shopify/src/lib/actions/ai/capture-order-payment.ts
new file mode 100644
index 00000000000..a15eab7e071
--- /dev/null
+++ b/packages/pieces/community/shopify/src/lib/actions/ai/capture-order-payment.ts
@@ -0,0 +1,83 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { shopifyAuth } from '../../..';
+import {
+ GqlTransaction,
+ shopifyFields,
+ shopifyGraphqlClient,
+ shopifyMappers,
+ shopifyProps,
+ shopifyValues,
+} from '../../common/graphql';
+import { orderTransactionOutputSchema } from '../../output-schemas/orders';
+
+export const shopifyAiCaptureOrderPayment = createAction({
+ auth: shopifyAuth,
+ name: 'capture_order_payment',
+ classification: 'WRITE',
+ displayName: 'Capture Order Payment',
+ description: 'Capture money from an authorized payment on an order.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Moves money: captures all or part of an authorized payment on an order. Needs the authorization transaction id from list_order_transactions and the amount to capture. To release an authorization without charging use void_order_transaction; to record an offline payment use mark_order_as_paid. Each call is a new capture, so do not retry blindly; check list_order_transactions first.',
+ idempotent: false,
+ },
+ outputSchema: orderTransactionOutputSchema,
+ props: {
+ order_id: Property.ShortText({
+ displayName: 'Order ID',
+ description: 'The order id, numeric or "gid://shopify/Order/…".',
+ required: true,
+ }),
+ parent_transaction_id: Property.ShortText({
+ displayName: 'Authorization Transaction ID',
+ description:
+ 'The AUTHORIZATION transaction to capture, numeric or "gid://shopify/OrderTransaction/…". Find it with list_order_transactions.',
+ required: true,
+ }),
+ amount: Property.Number({
+ displayName: 'Amount',
+ description: 'Amount to capture, for example 49.99. Cannot exceed the authorized amount still capturable.',
+ required: true,
+ }),
+ currency: Property.ShortText({
+ displayName: 'Currency',
+ description:
+ 'Three-letter currency of the amount, for example "EUR". Required when the order was paid in a currency other than the shop currency.',
+ required: false,
+ }),
+ final_capture: shopifyProps.booleanChoice({
+ displayName: 'Final Capture',
+ description:
+ 'For payments that allow several captures: Yes releases the rest of the authorization after this capture. Leave empty for the gateway default.',
+ }),
+ },
+ async run({ auth, propsValue }) {
+ const input = shopifyValues.compact({
+ id: shopifyGraphqlClient.toGid({ type: 'Order', id: propsValue.order_id }),
+ parentTransactionId: shopifyGraphqlClient.toGid({
+ type: 'OrderTransaction',
+ id: propsValue.parent_transaction_id,
+ }),
+ amount: String(propsValue.amount),
+ currency: shopifyValues.nonEmpty(propsValue.currency)?.toUpperCase(),
+ finalCapture: shopifyValues.toBooleanChoice(propsValue.final_capture),
+ });
+ const { data, redactedFields } = await shopifyGraphqlClient.request<{
+ orderCapture: { transaction: GqlTransaction | null } | null;
+ }>({
+ auth,
+ query: `mutation CaptureOrderPayment($input: OrderCaptureInput!) { orderCapture(input: $input) { transaction { ${shopifyFields.TRANSACTION_FIELDS} } userErrors { field message } } }`,
+ primaryPaths: ['orderCapture.transaction'],
+ variables: { input },
+ });
+ const transaction = data.orderCapture?.transaction;
+ if (!transaction) {
+ throw new Error('Shopify did not return the capture transaction.');
+ }
+ return {
+ ...shopifyMappers.mapTransaction(transaction),
+ redacted_fields: redactedFields,
+ };
+ },
+});
diff --git a/packages/pieces/community/shopify/src/lib/actions/ai/complete-draft-order.ts b/packages/pieces/community/shopify/src/lib/actions/ai/complete-draft-order.ts
new file mode 100644
index 00000000000..7942bd8d6cd
--- /dev/null
+++ b/packages/pieces/community/shopify/src/lib/actions/ai/complete-draft-order.ts
@@ -0,0 +1,69 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { shopifyAuth } from '../../..';
+import {
+ GqlDraftOrder,
+ shopifyFields,
+ shopifyGraphqlClient,
+ shopifyMappers,
+ shopifyValues,
+} from '../../common/graphql';
+import { draftOrderOutputSchema } from '../../output-schemas/orders';
+
+export const shopifyAiCompleteDraftOrder = createAction({
+ auth: shopifyAuth,
+ name: 'complete_draft_order',
+ classification: 'WRITE',
+ displayName: 'Complete Draft Order',
+ description: 'Turn a draft order into a real order.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Converts a draft order into a real order and reserves its inventory; the new order id is returned in order_id. To leave the order payment-pending, set payment terms on the draft first with update_draft_order; without payment terms Shopify records the order as paid. A payment gateway id only chooses the gateway the payment is recorded against; it does not keep the order unpaid. Completing twice fails, so do not repeat it.',
+ idempotent: false,
+ },
+ outputSchema: draftOrderOutputSchema,
+ props: {
+ draft_order_id: Property.ShortText({
+ displayName: 'Draft Order ID',
+ description: 'The draft order id, numeric or "gid://shopify/DraftOrder/…". Find it with list_draft_orders.',
+ required: true,
+ }),
+ payment_gateway_id: Property.ShortText({
+ displayName: 'Payment Gateway ID',
+ description:
+ 'Optional manual payment gateway to record the payment against, as a full id such as "gid://shopify/PaymentGateway/1".',
+ required: false,
+ }),
+ source_name: Property.ShortText({
+ displayName: 'Source Name',
+ description: 'Optional channel label stored on the order, for example "phone".',
+ required: false,
+ }),
+ },
+ async run({ auth, propsValue }) {
+ const id = shopifyGraphqlClient.toGid({ type: 'DraftOrder', id: propsValue.draft_order_id });
+ const gatewayId = shopifyValues.nonEmpty(propsValue.payment_gateway_id);
+ const { data, redactedFields } = await shopifyGraphqlClient.request<{
+ draftOrderComplete: { draftOrder: GqlDraftOrder | null } | null;
+ }>({
+ auth,
+ query: `mutation CompleteDraftOrder($id: ID!, $paymentGatewayId: ID, $sourceName: String) { draftOrderComplete(id: $id, paymentGatewayId: $paymentGatewayId, sourceName: $sourceName) { draftOrder { ${shopifyFields.DRAFT_ORDER_DETAIL_FIELDS} } userErrors { field message } } }`,
+ primaryPaths: ['draftOrderComplete.draftOrder'],
+ variables: shopifyValues.compact({
+ id,
+ paymentGatewayId: gatewayId
+ ? shopifyGraphqlClient.toGid({ type: 'PaymentGateway', id: gatewayId })
+ : undefined,
+ sourceName: shopifyValues.nonEmpty(propsValue.source_name),
+ }),
+ });
+ const draft = data.draftOrderComplete?.draftOrder;
+ if (!draft) {
+ throw new Error(`Draft order ${id} was not returned by Shopify.`);
+ }
+ return {
+ ...shopifyMappers.mapDraftOrderDetail(draft),
+ redacted_fields: redactedFields,
+ };
+ },
+});
diff --git a/packages/pieces/community/shopify/src/lib/actions/ai/count-abandoned-checkouts.ts b/packages/pieces/community/shopify/src/lib/actions/ai/count-abandoned-checkouts.ts
new file mode 100644
index 00000000000..79af60d0cb2
--- /dev/null
+++ b/packages/pieces/community/shopify/src/lib/actions/ai/count-abandoned-checkouts.ts
@@ -0,0 +1,43 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { shopifyAuth } from '../../..';
+import {
+ GqlCount,
+ shopifyGraphqlClient,
+ shopifyProps,
+ shopifyValues,
+} from '../../common/graphql';
+import { countOutputSchema } from '../../output-schemas/orders';
+
+export const shopifyAiCountAbandonedCheckouts = createAction({
+ auth: shopifyAuth,
+ name: 'count_abandoned_checkouts',
+ classification: 'READ',
+ displayName: 'Count Abandoned Checkouts',
+ description: 'Count abandoned checkouts, optionally filtered.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Counts abandoned checkouts, optionally filtered with search syntax such as "created_at:>=2026-09-01". precision is AT_LEAST when Shopify stopped counting at its limit. Use list_abandoned_checkouts to see them. Read-only.',
+ idempotent: true,
+ },
+ outputSchema: countOutputSchema,
+ props: {
+ query: shopifyProps.searchQuery(
+ 'Shopify search syntax, for example "created_at:>=2026-09-01". Leave empty to count all.'
+ ),
+ },
+ async run({ auth, propsValue }) {
+ const { data, redactedFields } = await shopifyGraphqlClient.request<{
+ abandonedCheckoutsCount: GqlCount | null;
+ }>({
+ auth,
+ query: `query CountAbandonedCheckouts($query: String) { abandonedCheckoutsCount(query: $query) { count precision } }`,
+ variables: { query: shopifyValues.nonEmpty(propsValue.query) },
+ });
+ return {
+ count: data.abandonedCheckoutsCount?.count ?? 0,
+ precision: data.abandonedCheckoutsCount?.precision ?? null,
+ redacted_fields: redactedFields,
+ };
+ },
+});
diff --git a/packages/pieces/community/shopify/src/lib/actions/ai/count-customer-segments.ts b/packages/pieces/community/shopify/src/lib/actions/ai/count-customer-segments.ts
new file mode 100644
index 00000000000..9be89c19b93
--- /dev/null
+++ b/packages/pieces/community/shopify/src/lib/actions/ai/count-customer-segments.ts
@@ -0,0 +1,33 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { shopifyAuth } from '../../..';
+import { GqlCount, shopifyGraphqlClient } from '../../common/graphql';
+import { countOutputSchema } from '../../output-schemas/orders';
+
+export const shopifyAiCountCustomerSegments = createAction({
+ auth: shopifyAuth,
+ name: 'count_customer_segments',
+ classification: 'READ',
+ displayName: 'Count Customer Segments',
+ description: 'Count the customer segments defined in the store.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Returns how many customer segments (saved customer groups) the store has. precision is AT_LEAST when Shopify stopped counting at its limit. Read-only.',
+ idempotent: true,
+ },
+ outputSchema: countOutputSchema,
+ props: {},
+ async run({ auth }) {
+ const { data, redactedFields } = await shopifyGraphqlClient.request<{
+ segmentsCount: GqlCount | null;
+ }>({
+ auth,
+ query: `query CountCustomerSegments { segmentsCount { count precision } }`,
+ });
+ return {
+ count: data.segmentsCount?.count ?? 0,
+ precision: data.segmentsCount?.precision ?? null,
+ redacted_fields: redactedFields,
+ };
+ },
+});
diff --git a/packages/pieces/community/shopify/src/lib/actions/ai/count-customers.ts b/packages/pieces/community/shopify/src/lib/actions/ai/count-customers.ts
new file mode 100644
index 00000000000..b0bd86da30c
--- /dev/null
+++ b/packages/pieces/community/shopify/src/lib/actions/ai/count-customers.ts
@@ -0,0 +1,43 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { shopifyAuth } from '../../..';
+import {
+ GqlCount,
+ shopifyGraphqlClient,
+ shopifyProps,
+ shopifyValues,
+} from '../../common/graphql';
+import { countOutputSchema } from '../../output-schemas/orders';
+
+export const shopifyAiCountCustomers = createAction({
+ auth: shopifyAuth,
+ name: 'count_customers',
+ classification: 'READ',
+ displayName: 'Count Customers',
+ description: 'Count customers, optionally filtered.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Counts customers, optionally filtered by created_at, updated_at or id (for example "created_at:>2026-01-01"). Shopify ignores other filters such as tag or email when counting customers; the action then fails with a clear error instead of returning the count of every customer, so use search_customers to find customers by tag or email. precision is AT_LEAST when Shopify stopped counting at its limit. Use search_customers to see them. Read-only.',
+ idempotent: true,
+ },
+ outputSchema: countOutputSchema,
+ props: {
+ query: shopifyProps.searchQuery(
+ 'Filter by created_at, updated_at or id, for example "created_at:>2026-01-01". Leave empty to count all.'
+ ),
+ },
+ async run({ auth, propsValue }) {
+ const { data, redactedFields } = await shopifyGraphqlClient.request<{
+ customersCount: GqlCount | null;
+ }>({
+ auth,
+ query: `query CountCustomers($query: String) { customersCount(query: $query) { count precision } }`,
+ variables: { query: shopifyValues.nonEmpty(propsValue.query) },
+ });
+ return {
+ count: data.customersCount?.count ?? 0,
+ precision: data.customersCount?.precision ?? null,
+ redacted_fields: redactedFields,
+ };
+ },
+});
diff --git a/packages/pieces/community/shopify/src/lib/actions/ai/count-draft-orders.ts b/packages/pieces/community/shopify/src/lib/actions/ai/count-draft-orders.ts
new file mode 100644
index 00000000000..7dd8a99d2af
--- /dev/null
+++ b/packages/pieces/community/shopify/src/lib/actions/ai/count-draft-orders.ts
@@ -0,0 +1,43 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { shopifyAuth } from '../../..';
+import {
+ GqlCount,
+ shopifyGraphqlClient,
+ shopifyProps,
+ shopifyValues,
+} from '../../common/graphql';
+import { countOutputSchema } from '../../output-schemas/orders';
+
+export const shopifyAiCountDraftOrders = createAction({
+ auth: shopifyAuth,
+ name: 'count_draft_orders',
+ classification: 'READ',
+ displayName: 'Count Draft Orders',
+ description: 'Count draft orders, optionally filtered.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Counts draft orders, optionally filtered with search syntax such as "status:open". precision is AT_LEAST when Shopify stopped counting at its limit. Use list_draft_orders to see them. Read-only.',
+ idempotent: true,
+ },
+ outputSchema: countOutputSchema,
+ props: {
+ query: shopifyProps.searchQuery(
+ 'Shopify draft order search syntax, for example "status:open". Leave empty to count all.'
+ ),
+ },
+ async run({ auth, propsValue }) {
+ const { data, redactedFields } = await shopifyGraphqlClient.request<{
+ draftOrdersCount: GqlCount | null;
+ }>({
+ auth,
+ query: `query CountDraftOrders($query: String) { draftOrdersCount(query: $query) { count precision } }`,
+ variables: { query: shopifyValues.nonEmpty(propsValue.query) },
+ });
+ return {
+ count: data.draftOrdersCount?.count ?? 0,
+ precision: data.draftOrdersCount?.precision ?? null,
+ redacted_fields: redactedFields,
+ };
+ },
+});
diff --git a/packages/pieces/community/shopify/src/lib/actions/ai/create-customer-address.ts b/packages/pieces/community/shopify/src/lib/actions/ai/create-customer-address.ts
new file mode 100644
index 00000000000..27062ca3c8b
--- /dev/null
+++ b/packages/pieces/community/shopify/src/lib/actions/ai/create-customer-address.ts
@@ -0,0 +1,64 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { shopifyAuth } from '../../..';
+import {
+ GqlMailingAddress,
+ shopifyFields,
+ shopifyGraphqlClient,
+ shopifyMappers,
+ shopifyProps,
+ shopifyValues,
+} from '../../common/graphql';
+import { customerAddressOutputSchema } from '../../output-schemas/orders';
+
+export const shopifyAiCreateCustomerAddress = createAction({
+ auth: shopifyAuth,
+ name: 'create_customer_address',
+ classification: 'WRITE',
+ displayName: 'Create Customer Address',
+ description: 'Add a new address to a customer.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Adds a new saved address to one customer and optionally makes it the default. Use update_customer_address to change an existing address instead. Each call adds another address, so retries create duplicates.',
+ idempotent: false,
+ },
+ outputSchema: customerAddressOutputSchema,
+ props: {
+ customer_id: Property.ShortText({
+ displayName: 'Customer ID',
+ description: 'The customer id, numeric or "gid://shopify/Customer/…". Find it with search_customers.',
+ required: true,
+ }),
+ ...shopifyProps.address(),
+ set_as_default: Property.Checkbox({
+ displayName: 'Set as Default',
+ description: "Make this the customer's default address. Off by default.",
+ required: false,
+ defaultValue: false,
+ }),
+ },
+ async run({ auth, propsValue }) {
+ const address = shopifyValues.buildMailingAddress(propsValue);
+ if (Object.keys(address).length === 0) {
+ throw new Error('Provide at least one address field.');
+ }
+ const customerId = shopifyGraphqlClient.toGid({ type: 'Customer', id: propsValue.customer_id });
+ const { data, redactedFields } = await shopifyGraphqlClient.request<{
+ customerAddressCreate: { address: GqlMailingAddress | null } | null;
+ }>({
+ auth,
+ query: `mutation CreateCustomerAddress($customerId: ID!, $address: MailingAddressInput!, $setAsDefault: Boolean) { customerAddressCreate(customerId: $customerId, address: $address, setAsDefault: $setAsDefault) { address { ${shopifyFields.ADDRESS_FIELDS} } userErrors { field message } } }`,
+ primaryPaths: ['customerAddressCreate.address'],
+ variables: { customerId, address, setAsDefault: propsValue.set_as_default ?? false },
+ });
+ const created = data.customerAddressCreate?.address;
+ if (!created) {
+ throw new Error('Shopify did not return the created address.');
+ }
+ return {
+ customer_id: customerId,
+ ...shopifyMappers.mapAddress(created),
+ redacted_fields: redactedFields,
+ };
+ },
+});
diff --git a/packages/pieces/community/shopify/src/lib/actions/ai/create-customer-profile.ts b/packages/pieces/community/shopify/src/lib/actions/ai/create-customer-profile.ts
new file mode 100644
index 00000000000..54a57b02e36
--- /dev/null
+++ b/packages/pieces/community/shopify/src/lib/actions/ai/create-customer-profile.ts
@@ -0,0 +1,139 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { shopifyAuth } from '../../..';
+import {
+ GqlCustomer,
+ shopifyFields,
+ shopifyGraphqlClient,
+ shopifyMappers,
+ shopifyValues,
+} from '../../common/graphql';
+import { customerOutputSchema } from '../../output-schemas/orders';
+
+export const shopifyAiCreateCustomerProfile = createAction({
+ auth: shopifyAuth,
+ name: 'create_customer_profile',
+ classification: 'WRITE',
+ displayName: 'Create Customer',
+ description: 'Create a customer with contact details, tags and optional email marketing consent.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Creates a customer with name, email, phone, note, tags and locale, optionally recording email marketing consent. Search first with search_customers, because Shopify rejects a duplicate email or phone. Add addresses afterwards with create_customer_address. Each call creates a new customer, so retries fail or duplicate.',
+ idempotent: false,
+ },
+ outputSchema: customerOutputSchema,
+ props: {
+ email: Property.ShortText({
+ displayName: 'Email',
+ description: 'Customer email, for example "[email protected]". Must be unique in the store.',
+ required: false,
+ }),
+ phone: Property.ShortText({
+ displayName: 'Phone',
+ description: 'Customer phone in E.164 format, for example "+16135551111". Must be unique in the store.',
+ required: false,
+ }),
+ first_name: Property.ShortText({
+ displayName: 'First Name',
+ description: 'Customer first name.',
+ required: false,
+ }),
+ last_name: Property.ShortText({
+ displayName: 'Last Name',
+ description: 'Customer last name.',
+ required: false,
+ }),
+ note: Property.LongText({
+ displayName: 'Note',
+ description: 'Internal note about the customer.',
+ required: false,
+ }),
+ tags: Property.Array({
+ displayName: 'Tags',
+ description: 'Tags to set, for example ["vip", "wholesale"].',
+ required: false,
+ }),
+ locale: Property.ShortText({
+ displayName: 'Locale',
+ description: 'Language for customer emails, for example "en" or "fr-CA".',
+ required: false,
+ }),
+ tax_exempt: Property.Checkbox({
+ displayName: 'Tax Exempt',
+ description: 'Whether the customer is exempt from taxes. Off by default.',
+ required: false,
+ defaultValue: false,
+ }),
+ email_marketing_state: Property.StaticDropdown({
+ displayName: 'Email Marketing Consent',
+ description:
+ 'Record the email marketing consent the customer gave. Leave empty to record none (the customer is not subscribed). Requires an email.',
+ required: false,
+ options: {
+ options: [
+ { label: 'Subscribed', value: 'SUBSCRIBED' },
+ { label: 'Not subscribed', value: 'NOT_SUBSCRIBED' },
+ { label: 'Unsubscribed', value: 'UNSUBSCRIBED' },
+ { label: 'Pending confirmation', value: 'PENDING' },
+ ],
+ },
+ }),
+ email_marketing_opt_in_level: Property.StaticDropdown({
+ displayName: 'Email Opt-in Level',
+ description: 'How consent was collected. Only used with email marketing consent.',
+ required: false,
+ options: {
+ options: [
+ { label: 'Single opt-in', value: 'SINGLE_OPT_IN' },
+ { label: 'Confirmed opt-in', value: 'CONFIRMED_OPT_IN' },
+ { label: 'Unknown', value: 'UNKNOWN' },
+ ],
+ },
+ }),
+ },
+ async run({ auth, propsValue }) {
+ const email = shopifyValues.nonEmpty(propsValue.email);
+ const phone = shopifyValues.nonEmpty(propsValue.phone);
+ const firstName = shopifyValues.nonEmpty(propsValue.first_name);
+ const lastName = shopifyValues.nonEmpty(propsValue.last_name);
+ if (!email && !phone && !firstName && !lastName) {
+ throw new Error('Provide at least an email, a phone, a first name or a last name.');
+ }
+ const marketingState = propsValue.email_marketing_state;
+ if (marketingState && !email) {
+ throw new Error('Email marketing consent needs an email.');
+ }
+ const input = shopifyValues.compact({
+ email,
+ phone,
+ firstName,
+ lastName,
+ note: shopifyValues.nonEmpty(propsValue.note),
+ tags: shopifyValues.readStringList(propsValue.tags),
+ locale: shopifyValues.nonEmpty(propsValue.locale),
+ taxExempt: propsValue.tax_exempt ?? false,
+ emailMarketingConsent: marketingState
+ ? shopifyValues.compact({
+ marketingState,
+ marketingOptInLevel: propsValue.email_marketing_opt_in_level,
+ })
+ : undefined,
+ });
+ const { data, redactedFields } = await shopifyGraphqlClient.request<{
+ customerCreate: { customer: GqlCustomer | null } | null;
+ }>({
+ auth,
+ query: `mutation CreateCustomerProfile($input: CustomerInput!) { customerCreate(input: $input) { customer { ${shopifyFields.CUSTOMER_FIELDS} } userErrors { field message } } }`,
+ primaryPaths: ['customerCreate.customer'],
+ variables: { input },
+ });
+ const customer = data.customerCreate?.customer;
+ if (!customer) {
+ throw new Error('Shopify did not return the created customer.');
+ }
+ return {
+ ...shopifyMappers.mapCustomer(customer),
+ redacted_fields: redactedFields,
+ };
+ },
+});
diff --git a/packages/pieces/community/shopify/src/lib/actions/ai/create-draft-order-with-line-items.ts b/packages/pieces/community/shopify/src/lib/actions/ai/create-draft-order-with-line-items.ts
new file mode 100644
index 00000000000..661d690fcf3
--- /dev/null
+++ b/packages/pieces/community/shopify/src/lib/actions/ai/create-draft-order-with-line-items.ts
@@ -0,0 +1,200 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { shopifyAuth } from '../../..';
+import {
+ GqlDraftOrder,
+ shopifyFields,
+ shopifyGraphqlClient,
+ shopifyMappers,
+ shopifyProps,
+ shopifyValues,
+} from '../../common/graphql';
+import { draftOrderOutputSchema } from '../../output-schemas/orders';
+
+export const shopifyAiCreateDraftOrderWithLineItems = createAction({
+ auth: shopifyAuth,
+ name: 'create_draft_order_with_line_items',
+ classification: 'WRITE',
+ displayName: 'Create Draft Order',
+ description: 'Create a draft order with one or more product or custom line items.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Creates a draft order (a quote the merchant or customer can review) with one or more product-variant or custom line items, an optional customer, order-level discount and shipping line. Nothing is charged and no stock is committed; send it with send_draft_order_invoice or turn it into an order with complete_draft_order. Each call creates a new draft, so retries duplicate.',
+ idempotent: false,
+ },
+ outputSchema: draftOrderOutputSchema,
+ props: {
+ line_items: shopifyProps.draftLineItems({
+ required: true,
+ description:
+ 'The items on the draft. Give either a variant id (price comes from the product) or a title and price for a custom item.',
+ }),
+ currency: Property.ShortText({
+ displayName: 'Currency',
+ description:
+ 'Three-letter currency code for the unit prices and shipping price given here, for example "USD". Required when any price is given. Find the shop currency with get_shop.',
+ required: false,
+ }),
+ customer_id: Property.ShortText({
+ displayName: 'Customer ID',
+ description: 'Customer the draft is for, numeric or "gid://shopify/Customer/…". Find it with search_customers.',
+ required: false,
+ }),
+ use_customer_default_address: Property.Checkbox({
+ displayName: 'Use Customer Default Address',
+ description: "Use the customer's default address as the shipping address. Needs a customer.",
+ required: false,
+ defaultValue: false,
+ }),
+ email: Property.ShortText({
+ displayName: 'Email',
+ description: 'Email the invoice is sent to, for example "[email protected]".',
+ required: false,
+ }),
+ phone: Property.ShortText({
+ displayName: 'Phone',
+ description: 'Contact phone in E.164 format, for example "+16135551111".',
+ required: false,
+ }),
+ note: Property.LongText({
+ displayName: 'Note',
+ description: 'Internal note on the draft.',
+ required: false,
+ }),
+ tags: Property.Array({
+ displayName: 'Tags',
+ description: 'Tags to set on the draft, for example ["quote", "b2b"].',
+ required: false,
+ }),
+ po_number: Property.ShortText({
+ displayName: 'PO Number',
+ description: 'Purchase order number, for example "PO-2026-114".',
+ required: false,
+ }),
+ discount_value: Property.Number({
+ displayName: 'Order Discount Value',
+ description: 'Discount on the whole draft: a percentage (10 for 10%) or a fixed amount, per the discount type.',
+ required: false,
+ }),
+ discount_value_type: Property.StaticDropdown({
+ displayName: 'Order Discount Type',
+ description: 'How the order discount value applies. Required with a discount value.',
+ required: false,
+ options: {
+ options: [
+ { label: 'Percentage', value: 'PERCENTAGE' },
+ { label: 'Fixed amount', value: 'FIXED_AMOUNT' },
+ ],
+ },
+ }),
+ discount_title: Property.ShortText({
+ displayName: 'Order Discount Title',
+ description: 'Label shown for the discount, for example "Loyalty discount".',
+ required: false,
+ }),
+ shipping_title: Property.ShortText({
+ displayName: 'Shipping Line Title',
+ description: 'Name of a custom shipping line, for example "Courier".',
+ required: false,
+ }),
+ shipping_price: Property.Number({
+ displayName: 'Shipping Price',
+ description: 'Price of the custom shipping line, for example 12.00. Requires a shipping title and a currency.',
+ required: false,
+ }),
+ reserve_inventory_until: Property.DateTime({
+ displayName: 'Reserve Inventory Until',
+ description: 'Hold the stock for this draft until this time (ISO 8601). Leave empty to not reserve stock.',
+ required: false,
+ }),
+ },
+ async run({ auth, propsValue }) {
+ const currency = shopifyValues.nonEmpty(propsValue.currency)?.toUpperCase();
+ const lineItems = shopifyValues.buildDraftLineItems({ value: propsValue.line_items, currency });
+ if (lineItems.length === 0) {
+ throw new Error('Add at least one line item.');
+ }
+ const customerId = shopifyValues.nonEmpty(propsValue.customer_id);
+ const input = shopifyValues.compact({
+ lineItems,
+ purchasingEntity: customerId
+ ? { customerId: shopifyGraphqlClient.toGid({ type: 'Customer', id: customerId }) }
+ : undefined,
+ useCustomerDefaultAddress: customerId && propsValue.use_customer_default_address ? true : undefined,
+ email: shopifyValues.nonEmpty(propsValue.email),
+ phone: shopifyValues.nonEmpty(propsValue.phone),
+ note: shopifyValues.nonEmpty(propsValue.note),
+ tags: shopifyValues.readStringList(propsValue.tags),
+ poNumber: shopifyValues.nonEmpty(propsValue.po_number),
+ appliedDiscount: buildAppliedDiscount({
+ value: propsValue.discount_value,
+ valueType: propsValue.discount_value_type,
+ title: shopifyValues.nonEmpty(propsValue.discount_title),
+ }),
+ shippingLine: buildShippingLine({
+ title: shopifyValues.nonEmpty(propsValue.shipping_title),
+ price: propsValue.shipping_price,
+ currency,
+ }),
+ reserveInventoryUntil: shopifyValues.nonEmpty(propsValue.reserve_inventory_until),
+ });
+ const { data, redactedFields } = await shopifyGraphqlClient.request<{
+ draftOrderCreate: { draftOrder: GqlDraftOrder | null } | null;
+ }>({
+ auth,
+ query: `mutation CreateDraftOrder($input: DraftOrderInput!) { draftOrderCreate(input: $input) { draftOrder { ${shopifyFields.DRAFT_ORDER_DETAIL_FIELDS} } userErrors { field message } } }`,
+ primaryPaths: ['draftOrderCreate.draftOrder'],
+ variables: { input },
+ });
+ const draft = data.draftOrderCreate?.draftOrder;
+ if (!draft) {
+ throw new Error('Shopify did not return the created draft order.');
+ }
+ return {
+ ...shopifyMappers.mapDraftOrderDetail(draft),
+ redacted_fields: redactedFields,
+ };
+ },
+});
+
+function buildAppliedDiscount({
+ value,
+ valueType,
+ title,
+}: {
+ value: number | undefined | null;
+ valueType: string | undefined;
+ title: string | undefined;
+}): Record<string, unknown> | undefined {
+ if (value === undefined || value === null) {
+ return undefined;
+ }
+ if (!valueType) {
+ throw new Error('Set "discount_value_type" when giving a discount value.');
+ }
+ return shopifyValues.compact({ value, valueType, title });
+}
+
+function buildShippingLine({
+ title,
+ price,
+ currency,
+}: {
+ title: string | undefined;
+ price: number | undefined | null;
+ currency: string | undefined;
+}): Record<string, unknown> | undefined {
+ if (!title) {
+ if (price !== undefined && price !== null) {
+ throw new Error('Set "shipping_title" when giving a shipping price.');
+ }
+ return undefined;
+ }
+ if (price === undefined || price === null) {
+ return { title };
+ }
+ if (!currency) {
+ throw new Error('Set "currency" (for example "USD") when giving a shipping price.');
+ }
+ return { title, priceWithCurrency: { amount: String(price), currencyCode: currency } };
+}
diff --git a/packages/pieces/community/shopify/src/lib/actions/ai/create-order-risk-assessment.ts b/packages/pieces/community/shopify/src/lib/actions/ai/create-order-risk-assessment.ts
new file mode 100644
index 00000000000..46341eb8872
--- /dev/null
+++ b/packages/pieces/community/shopify/src/lib/actions/ai/create-order-risk-assessment.ts
@@ -0,0 +1,102 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { shopifyAuth } from '../../..';
+import { shopifyGraphqlClient, shopifyValues } from '../../common/graphql';
+import { createOrderRiskAssessmentOutputSchema } from '../../output-schemas/orders';
+
+export const shopifyAiCreateOrderRiskAssessment = createAction({
+ auth: shopifyAuth,
+ name: 'create_order_risk_assessment',
+ classification: 'WRITE',
+ displayName: 'Create Order Risk Assessment',
+ description: 'Record a fraud risk assessment with supporting facts on an order.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Adds a fraud-risk assessment from this app to one order: a risk level (high, medium, low, none, pending) and at least one fact explaining it. It is shown to staff in the order\'s risk panel and feeds the order\'s risk recommendation; it does not cancel or hold the order. Each call adds another assessment, so do not repeat it.',
+ idempotent: false,
+ },
+ outputSchema: createOrderRiskAssessmentOutputSchema,
+ props: {
+ order_id: Property.ShortText({
+ displayName: 'Order ID',
+ description: 'The order id, numeric or "gid://shopify/Order/…". Find it with search_orders.',
+ required: true,
+ }),
+ risk_level: Property.StaticDropdown({
+ displayName: 'Risk Level',
+ description: 'The assessed fraud risk.',
+ required: true,
+ options: {
+ options: [
+ { label: 'High', value: 'HIGH' },
+ { label: 'Medium', value: 'MEDIUM' },
+ { label: 'Low', value: 'LOW' },
+ { label: 'None', value: 'NONE' },
+ { label: 'Pending', value: 'PENDING' },
+ ],
+ },
+ }),
+ facts: Property.Array({
+ displayName: 'Facts',
+ description: 'Reasons behind the assessment, at least one.',
+ required: true,
+ properties: {
+ description: Property.ShortText({
+ displayName: 'Description',
+ description: 'A short reason, for example "Billing and shipping countries differ".',
+ required: true,
+ }),
+ sentiment: Property.StaticDropdown({
+ displayName: 'Sentiment',
+ description: 'Whether this fact raises or lowers the risk.',
+ required: true,
+ options: {
+ options: [
+ { label: 'Negative (raises risk)', value: 'NEGATIVE' },
+ { label: 'Neutral', value: 'NEUTRAL' },
+ { label: 'Positive (lowers risk)', value: 'POSITIVE' },
+ ],
+ },
+ }),
+ },
+ }),
+ },
+ async run({ auth, propsValue }) {
+ const facts = shopifyValues.readRecords(propsValue.facts).map((fact) => {
+ const description = shopifyValues.readText(fact['description']);
+ const sentiment = shopifyValues.readText(fact['sentiment']);
+ if (!description || !sentiment) {
+ throw new Error('Every fact needs a description and a sentiment.');
+ }
+ return { description, sentiment };
+ });
+ if (facts.length === 0) {
+ throw new Error('Provide at least one fact.');
+ }
+ const orderId = shopifyGraphqlClient.toGid({ type: 'Order', id: propsValue.order_id });
+ const { data, redactedFields } = await shopifyGraphqlClient.request<{
+ orderRiskAssessmentCreate: {
+ orderRiskAssessment: {
+ riskLevel?: string | null;
+ provider?: { title?: string | null } | null;
+ facts?: { description?: string | null; sentiment?: string | null }[] | null;
+ } | null;
+ } | null;
+ }>({
+ auth,
+ query: `mutation CreateOrderRiskAssessment($input: OrderRiskAssessmentCreateInput!) { orderRiskAssessmentCreate(orderRiskAssessmentInput: $input) { orderRiskAssessment { riskLevel provider { title } facts { description sentiment } } userErrors { field message code } } }`,
+ variables: { input: { orderId, riskLevel: propsValue.risk_level, facts } },
+ });
+ const assessment = data.orderRiskAssessmentCreate?.orderRiskAssessment;
+ return {
+ order_id: orderId,
+ risk_level: assessment?.riskLevel ?? null,
+ provider: assessment?.provider?.title ?? null,
+ facts: (assessment?.facts ?? []).map((fact) => ({
+ description: fact.description ?? null,
+ sentiment: fact.sentiment ?? null,
+ })),
+ redacted_fields: redactedFields,
+ };
+ },
+});
diff --git a/packages/pieces/community/shopify/src/lib/actions/ai/create-order-with-line-items.ts b/packages/pieces/community/shopify/src/lib/actions/ai/create-order-with-line-items.ts
new file mode 100644
index 00000000000..46711bb6f20
--- /dev/null
+++ b/packages/pieces/community/shopify/src/lib/actions/ai/create-order-with-line-items.ts
@@ -0,0 +1,437 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { shopifyAuth } from '../../..';
+import {
+ GqlOrder,
+ shopifyFields,
+ shopifyGraphqlClient,
+ shopifyMappers,
+ shopifyValues,
+} from '../../common/graphql';
+import { orderOutputSchema } from '../../output-schemas/orders';
+
+export const shopifyAiCreateOrderWithLineItems = createAction({
+ auth: shopifyAuth,
+ name: 'create_order_with_line_items',
+ classification: 'WRITE',
+ displayName: 'Create Order',
+ description: 'Create a real order with one or more line items.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Creates a committed order (not a draft) with one or more product-variant or custom line items, an optional customer, shipping address, shipping line and at most one discount code. Use create_draft_order_with_line_items instead when the customer should review or pay through an invoice. Each call creates a new order, so retries duplicate; development stores allow 5 orders per minute. No receipt is emailed unless send_receipt is on. For a paid or authorized order give payment_amount, which records an offline (manual gateway) payment: no card is charged. A manual PAID payment can later be refunded; a manual AUTHORIZED one can be marked captured (capture_order_payment) or voided, which only updates the order records. To import an order that already shipped, set fulfillment_location_id (and tracking_numbers, one per package): the order is created fulfilled for all line items.',
+ idempotent: false,
+ },
+ outputSchema: orderOutputSchema,
+ props: {
+ line_items: Property.Array({
+ displayName: 'Line Items',
+ description:
+ 'The items to order. Give either a variant id (price comes from the product) or a title and price for a custom item.',
+ required: true,
+ properties: {
+ variant_id: Property.ShortText({
+ displayName: 'Variant ID',
+ description: 'Product variant id, for example "39072856" or "gid://shopify/ProductVariant/39072856".',
+ required: false,
+ }),
+ title: Property.ShortText({
+ displayName: 'Title',
+ description: 'Title of a custom item (no variant), for example "Gift wrapping".',
+ required: false,
+ }),
+ quantity: Property.Number({
+ displayName: 'Quantity',
+ description: 'How many units, at least 1.',
+ required: true,
+ }),
+ price: Property.Number({
+ displayName: 'Unit Price',
+ description: 'Unit price in the order currency, for example 19.99. Required for custom items.',
+ required: false,
+ }),
+ sku: Property.ShortText({
+ displayName: 'SKU',
+ description: 'Optional SKU for a custom item.',
+ required: false,
+ }),
+ },
+ }),
+ currency: Property.ShortText({
+ displayName: 'Currency',
+ description:
+ 'Three-letter currency code for every price given here, for example "USD". Required when any unit price, shipping price or fixed discount is given. Find the shop currency with get_shop.',
+ required: false,
+ }),
+ customer_id: Property.ShortText({
+ displayName: 'Customer ID',
+ description: 'Existing customer to attach, numeric or "gid://shopify/Customer/…". Find it with search_customers.',
+ required: false,
+ }),
+ email: Property.ShortText({
+ displayName: 'Email',
+ description: 'Order contact email, for example "[email protected]".',
+ required: false,
+ }),
+ phone: Property.ShortText({
+ displayName: 'Phone',
+ description: 'Order contact phone in E.164 format, for example "+16135551111".',
+ required: false,
+ }),
+ financial_status: Property.StaticDropdown({
+ displayName: 'Financial Status',
+ description:
+ 'Payment status of the order. Authorized, Paid and Partially paid need payment_amount, which records a manual payment; without it Shopify would only show the label and the order could not be refunded, captured or marked as paid. Leave empty for pending.',
+ required: false,
+ options: {
+ options: [
+ { label: 'Pending', value: 'PENDING' },
+ { label: 'Authorized', value: 'AUTHORIZED' },
+ { label: 'Paid', value: 'PAID' },
+ { label: 'Partially paid', value: 'PARTIALLY_PAID' },
+ ],
+ },
+ }),
+ payment_amount: Property.Number({
+ displayName: 'Payment Amount',
+ description:
+ 'Amount already paid (Paid, Partially paid) or authorized (Authorized), recorded as a manual payment in the order currency, for example 40.5. Needed with those financial statuses.',
+ required: false,
+ }),
+ note: Property.LongText({
+ displayName: 'Note',
+ description: 'Internal note on the order.',
+ required: false,
+ }),
+ tags: Property.Array({
+ displayName: 'Tags',
+ description: 'Tags to set on the order, for example ["wholesale", "phone-order"].',
+ required: false,
+ }),
+ discount_code: Property.ShortText({
+ displayName: 'Discount Code',
+ description: 'One discount code to record on the order, for example "SUMMER10". Only one code is allowed.',
+ required: false,
+ }),
+ discount_type: Property.StaticDropdown({
+ displayName: 'Discount Type',
+ description: 'How the discount code applies. Required with a discount code.',
+ required: false,
+ options: {
+ options: [
+ { label: 'Percentage off items', value: 'PERCENTAGE' },
+ { label: 'Fixed amount off items', value: 'FIXED_AMOUNT' },
+ { label: 'Free shipping', value: 'FREE_SHIPPING' },
+ ],
+ },
+ }),
+ discount_value: Property.Number({
+ displayName: 'Discount Value',
+ description: 'Percentage (for example 10 for 10%) or fixed amount, depending on the discount type.',
+ required: false,
+ }),
+ shipping_title: Property.ShortText({
+ displayName: 'Shipping Line Title',
+ description: 'Name of the shipping method, for example "Standard Shipping". Needs a shipping price.',
+ required: false,
+ }),
+ shipping_price: Property.Number({
+ displayName: 'Shipping Price',
+ description:
+ 'Shipping price in the order currency, for example 5.00 (use 0 for free shipping). Required together with the shipping line title, and needs a currency.',
+ required: false,
+ }),
+ shipping_first_name: Property.ShortText({
+ displayName: 'Shipping First Name',
+ description: 'First name on the shipping address.',
+ required: false,
+ }),
+ shipping_last_name: Property.ShortText({
+ displayName: 'Shipping Last Name',
+ description: 'Last name on the shipping address.',
+ required: false,
+ }),
+ shipping_address1: Property.ShortText({
+ displayName: 'Shipping Address Line 1',
+ description: 'Street address, for example "150 Elgin Street".',
+ required: false,
+ }),
+ shipping_address2: Property.ShortText({
+ displayName: 'Shipping Address Line 2',
+ description: 'Apartment, suite or unit.',
+ required: false,
+ }),
+ shipping_city: Property.ShortText({
+ displayName: 'Shipping City',
+ description: 'City, for example "Ottawa".',
+ required: false,
+ }),
+ shipping_province_code: Property.ShortText({
+ displayName: 'Shipping Province / State Code',
+ description: 'Region code, for example "ON".',
+ required: false,
+ }),
+ shipping_country_code: Property.ShortText({
+ displayName: 'Shipping Country Code',
+ description: 'Two-letter ISO country code, for example "CA".',
+ required: false,
+ }),
+ shipping_zip: Property.ShortText({
+ displayName: 'Shipping Postal Code',
+ description: 'Postal or ZIP code.',
+ required: false,
+ }),
+ shipping_phone: Property.ShortText({
+ displayName: 'Shipping Phone',
+ description: 'Phone on the shipping address.',
+ required: false,
+ }),
+ inventory_behaviour: Property.StaticDropdown({
+ displayName: 'Inventory Behaviour',
+ description: 'Whether to decrement stock. Leave empty for the Shopify default (bypass, stock is not changed).',
+ required: false,
+ options: {
+ options: [
+ { label: 'Bypass (do not change stock)', value: 'BYPASS' },
+ { label: 'Decrement, obey inventory policy', value: 'DECREMENT_OBEYING_POLICY' },
+ { label: 'Decrement, ignore inventory policy', value: 'DECREMENT_IGNORING_POLICY' },
+ ],
+ },
+ }),
+ send_receipt: Property.Checkbox({
+ displayName: 'Send Order Receipt',
+ description: 'Email the order confirmation to the customer. Off by default.',
+ required: false,
+ defaultValue: false,
+ }),
+ send_fulfillment_receipt: Property.Checkbox({
+ displayName: 'Send Fulfillment Receipt',
+ description: 'Email a shipping confirmation when the order is fulfilled. Off by default.',
+ required: false,
+ defaultValue: false,
+ }),
+ fulfillment_location_id: Property.ShortText({
+ displayName: 'Fulfilled From Location ID',
+ description:
+ 'Set only when importing an order that was already shipped: the location id (from list_locations) it shipped from. The order is then created fulfilled for all line items. Leave empty for an unfulfilled order.',
+ required: false,
+ }),
+ tracking_numbers: Property.Array({
+ displayName: 'Tracking Numbers',
+ description:
+ 'Tracking numbers of the imported fulfillment, one per package, for example ["1Z999AA10123456784", "1Z999AA10123456785"]. Needs fulfillment_location_id.',
+ required: false,
+ }),
+ tracking_company: Property.ShortText({
+ displayName: 'Tracking Company',
+ description: 'Carrier of the tracking numbers, for example "UPS", "USPS" or "DHL Express". Needs fulfillment_location_id.',
+ required: false,
+ }),
+ },
+ async run({ auth, propsValue }) {
+ const currency = shopifyValues.nonEmpty(propsValue.currency)?.toUpperCase();
+ const lineItems = shopifyValues.readRecords(propsValue.line_items).map((item) => {
+ const variantId = shopifyValues.readText(item['variant_id']);
+ const title = shopifyValues.readText(item['title']);
+ const quantity = shopifyValues.readNumber(item['quantity']);
+ const price = shopifyValues.readNumber(item['price']);
+ if (quantity === undefined || quantity < 1) {
+ throw new Error('Every line item needs a quantity of at least 1.');
+ }
+ if (!variantId && (!title || price === undefined)) {
+ throw new Error('Every line item needs a variant_id, or a title and a price for a custom item.');
+ }
+ return shopifyValues.compact({
+ variantId: variantId
+ ? shopifyGraphqlClient.toGid({ type: 'ProductVariant', id: variantId })
+ : undefined,
+ title,
+ quantity,
+ sku: shopifyValues.readText(item['sku']),
+ priceSet: price === undefined ? undefined : toMoneyBag({ amount: price, currency }),
+ });
+ });
+ if (lineItems.length === 0) {
+ throw new Error('Add at least one line item.');
+ }
+ const discountCode = shopifyValues.nonEmpty(propsValue.discount_code);
+ const discount = buildDiscount({
+ code: discountCode,
+ type: propsValue.discount_type,
+ value: propsValue.discount_value,
+ currency,
+ });
+ const shippingTitle = shopifyValues.nonEmpty(propsValue.shipping_title);
+ const shippingPrice = propsValue.shipping_price ?? undefined;
+ if (shippingPrice !== undefined && !shippingTitle) {
+ throw new Error('Set "shipping_title" when giving a shipping price.');
+ }
+ if (shippingTitle && shippingPrice === undefined) {
+ throw new Error(
+ 'Set "shipping_price" (and "currency") when giving a shipping title. Shopify requires a price on every order shipping line; use 0 for free shipping.'
+ );
+ }
+ const shippingAddress = shopifyValues.buildMailingAddress({
+ first_name: propsValue.shipping_first_name,
+ last_name: propsValue.shipping_last_name,
+ address1: propsValue.shipping_address1,
+ address2: propsValue.shipping_address2,
+ city: propsValue.shipping_city,
+ province_code: propsValue.shipping_province_code,
+ country_code: propsValue.shipping_country_code,
+ zip: propsValue.shipping_zip,
+ phone: propsValue.shipping_phone,
+ });
+ const customerId = shopifyValues.nonEmpty(propsValue.customer_id);
+ const fulfillment = buildFulfillment({
+ locationId: shopifyValues.nonEmpty(propsValue.fulfillment_location_id),
+ trackingNumbers: shopifyValues.readStringList(propsValue.tracking_numbers),
+ trackingCompany: shopifyValues.nonEmpty(propsValue.tracking_company),
+ notifyCustomer: propsValue.send_fulfillment_receipt ?? false,
+ });
+ const transactions = buildPaymentTransactions({
+ financialStatus: propsValue.financial_status,
+ amount: propsValue.payment_amount ?? undefined,
+ currency,
+ });
+ const order = shopifyValues.compact({
+ transactions,
+ fulfillment,
+ fulfillmentStatus: fulfillment ? 'FULFILLED' : undefined,
+ lineItems,
+ currency,
+ email: shopifyValues.nonEmpty(propsValue.email),
+ phone: shopifyValues.nonEmpty(propsValue.phone),
+ financialStatus: propsValue.financial_status,
+ note: shopifyValues.nonEmpty(propsValue.note),
+ tags: shopifyValues.readStringList(propsValue.tags),
+ customer: customerId
+ ? { toAssociate: { id: shopifyGraphqlClient.toGid({ type: 'Customer', id: customerId }) } }
+ : undefined,
+ discountCode: discount,
+ shippingLines:
+ shippingTitle && shippingPrice !== undefined
+ ? [{ title: shippingTitle, priceSet: toMoneyBag({ amount: shippingPrice, currency }) }]
+ : undefined,
+ shippingAddress: Object.keys(shippingAddress).length > 0 ? shippingAddress : undefined,
+ });
+ const options = shopifyValues.compact({
+ sendReceipt: propsValue.send_receipt ?? false,
+ sendFulfillmentReceipt: propsValue.send_fulfillment_receipt ?? false,
+ inventoryBehaviour: propsValue.inventory_behaviour,
+ });
+ const { data, redactedFields } = await shopifyGraphqlClient.request<{
+ orderCreate: { order: GqlOrder | null } | null;
+ }>({
+ auth,
+ query: `mutation CreateOrder($order: OrderCreateOrderInput!, $options: OrderCreateOptionsInput) { orderCreate(order: $order, options: $options) { order { ${shopifyFields.ORDER_DETAIL_FIELDS} } userErrors { field message code } } }`,
+ primaryPaths: ['orderCreate.order'],
+ variables: { order, options },
+ });
+ const created = data.orderCreate?.order;
+ if (!created) {
+ throw new Error('Shopify did not return the created order.');
+ }
+ return {
+ ...shopifyMappers.mapOrderDetail(created),
+ redacted_fields: redactedFields,
+ };
+ },
+});
+
+function buildPaymentTransactions({
+ financialStatus,
+ amount,
+ currency,
+}: {
+ financialStatus: string | undefined;
+ amount: number | undefined;
+ currency: string | undefined;
+}): Record<string, unknown>[] | undefined {
+ const needsPayment = financialStatus !== undefined && financialStatus !== 'PENDING';
+ if (!needsPayment) {
+ if (amount !== undefined) {
+ throw new Error('Set financial_status to PAID, PARTIALLY_PAID or AUTHORIZED when giving payment_amount.');
+ }
+ return undefined;
+ }
+ if (amount === undefined || amount <= 0) {
+ throw new Error(
+ `Set "payment_amount" (greater than 0) with financial_status ${financialStatus}. Without it Shopify records no payment, so the order could not be refunded, captured or marked as paid. To record the payment later, create the order as PENDING and call mark_order_as_paid.`
+ );
+ }
+ return [
+ {
+ kind: financialStatus === 'AUTHORIZED' ? 'AUTHORIZATION' : 'SALE',
+ status: 'SUCCESS',
+ gateway: 'manual',
+ amountSet: toMoneyBag({ amount, currency }),
+ },
+ ];
+}
+
+function buildFulfillment({
+ locationId,
+ trackingNumbers,
+ trackingCompany,
+ notifyCustomer,
+}: {
+ locationId: string | undefined;
+ trackingNumbers: string[] | undefined;
+ trackingCompany: string | undefined;
+ notifyCustomer: boolean;
+}): Record<string, unknown> | undefined {
+ if (!locationId) {
+ if ((trackingNumbers?.length ?? 0) > 0 || trackingCompany) {
+ throw new Error('Set "fulfillment_location_id" when giving tracking numbers or a tracking company.');
+ }
+ return undefined;
+ }
+ return shopifyValues.compact({
+ locationId: shopifyGraphqlClient.toGid({ type: 'Location', id: locationId }),
+ trackingNumbers: trackingNumbers && trackingNumbers.length > 0 ? trackingNumbers : undefined,
+ trackingCompany,
+ notifyCustomer,
+ });
+}
+
+function buildDiscount({
+ code,
+ type,
+ value,
+ currency,
+}: {
+ code: string | undefined;
+ type: string | undefined;
+ value: number | undefined | null;
+ currency: string | undefined;
+}): Record<string, unknown> | undefined {
+ if (!code) {
+ return undefined;
+ }
+ if (type === 'FREE_SHIPPING') {
+ return { freeShippingDiscountCode: { code } };
+ }
+ if (value === undefined || value === null) {
+ throw new Error('Set "discount_value" for a percentage or fixed-amount discount code.');
+ }
+ if (type === 'PERCENTAGE') {
+ return { itemPercentageDiscountCode: { code, percentage: value } };
+ }
+ if (type === 'FIXED_AMOUNT') {
+ return { itemFixedDiscountCode: { code, amountSet: toMoneyBag({ amount: value, currency }) } };
+ }
+ throw new Error('Set "discount_type" when giving a discount code.');
+}
+
+function toMoneyBag({
+ amount,
+ currency,
+}: {
+ amount: number;
+ currency: string | undefined;
+}): { shopMoney: { amount: string; currencyCode: string } } {
+ if (!currency) {
+ throw new Error('Set "currency" (for example "USD") when giving a price or a fixed discount amount.');
+ }
+ return { shopMoney: { amount: String(amount), currencyCode: currency } };
+}
diff --git a/packages/pieces/community/shopify/src/lib/actions/ai/create-refund.ts b/packages/pieces/community/shopify/src/lib/actions/ai/create-refund.ts
new file mode 100644
index 00000000000..7a6027aa811
--- /dev/null
+++ b/packages/pieces/community/shopify/src/lib/actions/ai/create-refund.ts
@@ -0,0 +1,151 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { shopifyAuth } from '../../..';
+import {
+ GqlRefund,
+ shopifyFields,
+ shopifyGraphqlClient,
+ shopifyMappers,
+ shopifyProps,
+ shopifyValues,
+} from '../../common/graphql';
+import { createRefundOutputSchema } from '../../output-schemas/orders';
+
+export const shopifyAiCreateRefund = createAction({
+ auth: shopifyAuth,
+ name: 'create_refund',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Create Refund',
+ description: 'Refund money and/or line items on an order.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Moves money back to the customer: creates a refund on an order for the given line items, shipping and refund transactions. Run calculate_refund first and pass its suggested transactions (parent transaction id, gateway, amount) and line items. When calculate_refund shows a presentment_currency_code different from the shop currency_code, pass the presentment amounts (presentment_amount, presentment_shipping_amount) and set currency to that presentment code. The customer is emailed only if notify is on. Generate your own idempotency_key (for example a UUID) on the first call and pass the same key again on every retry after an error or timeout so Shopify does not refund twice; the key used is returned and is included in any error message.',
+ idempotent: false,
+ },
+ outputSchema: createRefundOutputSchema,
+ props: {
+ order_id: Property.ShortText({
+ displayName: 'Order ID',
+ description: 'The order id, numeric or "gid://shopify/Order/…". Find it with search_orders.',
+ required: true,
+ }),
+ line_items: shopifyProps.refundLineItems(),
+ transactions: Property.Array({
+ displayName: 'Refund Transactions',
+ description:
+ 'The money to return, one entry per original payment. Copy parent_transaction_id, gateway and amount from calculate_refund suggested_transactions; when the order has a presentment currency different from the shop currency, copy presentment_amount instead of amount and set currency. Leave empty to refund items without returning money.',
+ required: false,
+ properties: {
+ parent_transaction_id: Property.ShortText({
+ displayName: 'Parent Transaction ID',
+ description: 'The captured SALE or CAPTURE transaction being refunded, numeric or "gid://shopify/OrderTransaction/…".',
+ required: true,
+ }),
+ amount: Property.Number({
+ displayName: 'Amount',
+ description:
+ 'Amount to refund on this transaction, for example 19.99. In the presentment (customer) currency when currency is set, otherwise in the shop currency.',
+ required: true,
+ }),
+ gateway: Property.ShortText({
+ displayName: 'Gateway',
+ description: 'Payment gateway of the parent transaction, for example "shopify_payments" or "bogus".',
+ required: true,
+ }),
+ },
+ }),
+ shipping_full_refund: Property.Checkbox({
+ displayName: 'Refund All Shipping',
+ description: 'Refund the full remaining shipping cost. Off by default.',
+ required: false,
+ defaultValue: false,
+ }),
+ shipping_amount: Property.Number({
+ displayName: 'Shipping Amount',
+ description:
+ 'Refund only this much shipping, for example 4.50, in the same currency as the transaction amounts. Ignored when refunding all shipping.',
+ required: false,
+ }),
+ currency: Property.ShortText({
+ displayName: 'Currency',
+ description:
+ 'Presentment (customer) currency of the refund, for example "EUR" (presentment_currency_code from calculate_refund). Required when the presentment currency differs from the shop currency; then every amount given here must be the presentment amount. Leave empty when both currencies are the same.',
+ required: false,
+ }),
+ note: Property.ShortText({
+ displayName: 'Note',
+ description: 'Internal reason for the refund.',
+ required: false,
+ }),
+ notify: Property.Checkbox({
+ displayName: 'Notify Customer',
+ description: 'Email the customer a refund notification. Off by default.',
+ required: false,
+ defaultValue: false,
+ }),
+ idempotency_key: shopifyProps.idempotencyKey(),
+ },
+ async run({ auth, propsValue }) {
+ const orderId = shopifyGraphqlClient.toGid({ type: 'Order', id: propsValue.order_id });
+ const transactions = shopifyValues.readRecords(propsValue.transactions).map((item) => {
+ const parentId = shopifyValues.readText(item['parent_transaction_id']);
+ const amount = shopifyValues.readNumber(item['amount']);
+ const gateway = shopifyValues.readText(item['gateway']);
+ if (!parentId || amount === undefined || !gateway) {
+ throw new Error('Every refund transaction needs a parent_transaction_id, an amount and a gateway.');
+ }
+ return {
+ orderId,
+ parentId: shopifyGraphqlClient.toGid({ type: 'OrderTransaction', id: parentId }),
+ amount: String(amount),
+ gateway,
+ kind: 'REFUND',
+ };
+ });
+ const refundLineItems = shopifyValues.buildRefundLineItems(propsValue.line_items);
+ const fullShipping = propsValue.shipping_full_refund ?? false;
+ const shippingAmount = propsValue.shipping_amount;
+ const shipping = fullShipping
+ ? { fullRefund: true }
+ : shippingAmount !== undefined && shippingAmount !== null
+ ? { amount: String(shippingAmount) }
+ : undefined;
+ if (transactions.length === 0 && !refundLineItems && !shipping) {
+ throw new Error('Provide line items, shipping or refund transactions to refund.');
+ }
+ const idempotencyKey = shopifyGraphqlClient.resolveIdempotencyKey(propsValue.idempotency_key);
+ const input = shopifyValues.compact({
+ orderId,
+ refundLineItems,
+ transactions: transactions.length > 0 ? transactions : undefined,
+ shipping,
+ currency: shopifyValues.nonEmpty(propsValue.currency)?.toUpperCase(),
+ note: shopifyValues.nonEmpty(propsValue.note),
+ notify: propsValue.notify ?? false,
+ });
+ const { data, redactedFields } = await shopifyGraphqlClient.request<{
+ refundCreate: {
+ refund: GqlRefund | null;
+ order: { id: string; totalRefundedSet?: { shopMoney?: { amount?: string | null } | null } | null } | null;
+ } | null;
+ }>({
+ auth,
+ query: `mutation CreateRefund($input: RefundInput!, $idempotencyKey: String!) { refundCreate(input: $input) @idempotent(key: $idempotencyKey) { refund { ${shopifyFields.REFUND_FIELDS} } order { id totalRefundedSet { ${shopifyFields.MONEY_FIELDS} } } userErrors { field message } } }`,
+ primaryPaths: ['refundCreate.refund'],
+ variables: { input },
+ idempotencyKey,
+ });
+ const refund = data.refundCreate?.refund;
+ if (!refund) {
+ throw new Error(
+ `Shopify did not return the refund. [idempotency_key used: ${idempotencyKey}. Retry with this same idempotency_key so Shopify does not repeat the operation.]`
+ );
+ }
+ return {
+ ...shopifyMappers.mapRefund(refund),
+ order_total_refunded: data.refundCreate?.order?.totalRefundedSet?.shopMoney?.amount ?? null,
+ idempotency_key: idempotencyKey,
+ redacted_fields: redactedFields,
+ };
+ },
+});
diff --git a/packages/pieces/community/shopify/src/lib/actions/ai/create-requested-order-edit.ts b/packages/pieces/community/shopify/src/lib/actions/ai/create-requested-order-edit.ts
new file mode 100644
index 00000000000..2082604b9f8
--- /dev/null
+++ b/packages/pieces/community/shopify/src/lib/actions/ai/create-requested-order-edit.ts
@@ -0,0 +1,54 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { shopifyAuth } from '../../..';
+import { shopifyGraphqlClient } from '../../common/graphql';
+import {
+ GqlRequestedOrderEdit,
+ requestedOrderEditFields,
+ requestedOrderEditHelpers,
+} from '../../common/requested-order-edits';
+import { requestedOrderEditOutputSchema } from '../../output-schemas/requested-order-edits';
+
+export const shopifyAiCreateRequestedOrderEdit = createAction({
+ auth: shopifyAuth,
+ name: 'create_requested_order_edit',
+ classification: 'WRITE',
+ displayName: 'Create Requested Order Edit',
+ description: 'Record a buyer request to remove unfulfilled line items from an order.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Records, on behalf of the buyer, a request to remove unfulfilled line items (with quantities) from one order. It does not edit the order or move money: it creates a requested order edit with status REQUESTED that the merchant then resolves (resolve_requested_order_edit) or declines (decline_requested_order_edit). Take line item ids and unfulfilled quantities from get_order; the quantity cannot exceed the unfulfilled quantity. Use calculate_requested_order_edit first to preview the amounts. Returns the new requested_order_edit id. Needs the write_orders access scope. If Shopify ever answers that it APPLIED the change but withheld the result, the request exists: do not repeat it. Not idempotent: each call creates another request, so after an error or timeout call list_requested_order_edits on the order and only retry if the request is not there.',
+ idempotent: false,
+ },
+ outputSchema: requestedOrderEditOutputSchema,
+ props: {
+ order_id: Property.ShortText({
+ displayName: 'Order ID',
+ description: 'The order id, numeric or "gid://shopify/Order/…". Find it with search_orders.',
+ required: true,
+ }),
+ line_items: requestedOrderEditHelpers.removalsProp(),
+ },
+ async run({ auth, propsValue }) {
+ const orderId = requestedOrderEditHelpers.readTypedId({ type: 'Order', value: propsValue.order_id, label: 'order_id' });
+ const removals = requestedOrderEditHelpers.buildRemovals(propsValue.line_items);
+ const { data, redactedFields } = await shopifyGraphqlClient.request<{
+ requestedOrderEditCreate: { requestedOrderEdit: GqlRequestedOrderEdit | null } | null;
+ }>({
+ auth,
+ query: `mutation CreateRequestedOrderEdit($input: RequestedOrderEditCreateInput!) { requestedOrderEditCreate(input: $input) { requestedOrderEdit { ${requestedOrderEditFields.REQUESTED_ORDER_EDIT_FIELDS} } userErrors { field message code } } }`,
+ variables: { input: { orderId, lineItems: { removals } } },
+ primaryPaths: ['requestedOrderEditCreate.requestedOrderEdit'],
+ });
+ const edit = data.requestedOrderEditCreate?.requestedOrderEdit;
+ if (!edit) {
+ throw new Error(
+ `Shopify did not return the requested order edit for order ${orderId}. It may still have been created: check with list_requested_order_edits before retrying.`
+ );
+ }
+ return {
+ ...requestedOrderEditHelpers.mapRequestedOrderEdit(edit),
+ redacted_fields: redactedFields,
+ };
+ },
+});
diff --git a/packages/pieces/community/shopify/src/lib/actions/ai/decline-requested-order-edit.ts b/packages/pieces/community/shopify/src/lib/actions/ai/decline-requested-order-edit.ts
new file mode 100644
index 00000000000..58d35a7b3e3
--- /dev/null
+++ b/packages/pieces/community/shopify/src/lib/actions/ai/decline-requested-order-edit.ts
@@ -0,0 +1,63 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { shopifyAuth } from '../../..';
+import { shopifyGraphqlClient, shopifyValues } from '../../common/graphql';
+import {
+ GqlRequestedOrderEdit,
+ requestedOrderEditFields,
+ requestedOrderEditHelpers,
+} from '../../common/requested-order-edits';
+import { requestedOrderEditOutputSchema } from '../../output-schemas/requested-order-edits';
+
+export const shopifyAiDeclineRequestedOrderEdit = createAction({
+ auth: shopifyAuth,
+ name: 'decline_requested_order_edit',
+ classification: 'WRITE',
+ displayName: 'Decline Requested Order Edit',
+ description: 'Decline a buyer request to edit an order, with an optional note to the buyer.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Declines one pending (status REQUESTED) buyer-requested order edit; the order itself is not changed and the status becomes DECLINED. The optional decline_note (up to 500 characters) is the message Shopify sends to the buyer about the decline. Get the requested_order_edit_id from list_requested_order_edits. Needs the write_orders access scope. Not idempotent: an edit that is already declined or resolved is rejected, so check its status with list_requested_order_edits before retrying.',
+ idempotent: false,
+ },
+ outputSchema: requestedOrderEditOutputSchema,
+ props: {
+ requested_order_edit_id: Property.ShortText({
+ displayName: 'Requested Order Edit ID',
+ description:
+ 'The requested order edit id, numeric or "gid://shopify/RequestedOrderEdit/…". Find it with list_requested_order_edits.',
+ required: true,
+ }),
+ decline_note: Property.LongText({
+ displayName: 'Decline Note',
+ description: `Message sent to the buyer explaining the decline, at most ${requestedOrderEditFields.DECLINE_NOTE_MAX_LENGTH} characters. Leave empty to send none.`,
+ required: false,
+ }),
+ },
+ async run({ auth, propsValue }) {
+ const id = requestedOrderEditHelpers.readTypedId({
+ type: 'RequestedOrderEdit',
+ value: propsValue.requested_order_edit_id,
+ label: 'requested_order_edit_id',
+ });
+ const declineNote = requestedOrderEditHelpers.readDeclineNote(propsValue.decline_note);
+ const { data, redactedFields } = await shopifyGraphqlClient.request<{
+ requestedOrderEditDecline: { requestedOrderEdit: GqlRequestedOrderEdit | null } | null;
+ }>({
+ auth,
+ query: `mutation DeclineRequestedOrderEdit($input: RequestedOrderEditDeclineInput!) { requestedOrderEditDecline(input: $input) { requestedOrderEdit { ${requestedOrderEditFields.REQUESTED_ORDER_EDIT_FIELDS} } userErrors { field message code } } }`,
+ variables: { input: shopifyValues.compact({ id, declineNote }) },
+ primaryPaths: ['requestedOrderEditDecline.requestedOrderEdit'],
+ });
+ const edit = data.requestedOrderEditDecline?.requestedOrderEdit;
+ if (!edit) {
+ throw new Error(
+ `Shopify did not return requested order edit ${id}. Check its status with list_requested_order_edits before retrying.`
+ );
+ }
+ return {
+ ...requestedOrderEditHelpers.mapRequestedOrderEdit(edit),
+ redacted_fields: redactedFields,
+ };
+ },
+});
diff --git a/packages/pieces/community/shopify/src/lib/actions/ai/delete-customer-address.ts b/packages/pieces/community/shopify/src/lib/actions/ai/delete-customer-address.ts
new file mode 100644
index 00000000000..3dca0cdb5f3
--- /dev/null
+++ b/packages/pieces/community/shopify/src/lib/actions/ai/delete-customer-address.ts
@@ -0,0 +1,52 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { shopifyAuth } from '../../..';
+import { shopifyGraphqlClient } from '../../common/graphql';
+import { deleteCustomerAddressOutputSchema } from '../../output-schemas/orders';
+
+export const shopifyAiDeleteCustomerAddress = createAction({
+ auth: shopifyAuth,
+ name: 'delete_customer_address',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Delete Customer Address',
+ description: 'Delete a saved address from a customer.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Permanently deletes one saved address of a customer. Find the address id with list_customer_addresses. Cannot be undone; a repeat call fails because the address is gone.',
+ idempotent: false,
+ },
+ outputSchema: deleteCustomerAddressOutputSchema,
+ props: {
+ customer_id: Property.ShortText({
+ displayName: 'Customer ID',
+ description: 'The customer id, numeric or "gid://shopify/Customer/…".',
+ required: true,
+ }),
+ address_id: Property.ShortText({
+ displayName: 'Address ID',
+ description:
+ 'The address id from list_customer_addresses, for example "gid://shopify/MailingAddress/1053318585?model_name=CustomerAddress" or its number.',
+ required: true,
+ }),
+ },
+ async run({ auth, propsValue }) {
+ const customerId = shopifyGraphqlClient.toGid({ type: 'Customer', id: propsValue.customer_id });
+ const addressId = shopifyGraphqlClient.toGid({
+ type: 'MailingAddress',
+ id: propsValue.address_id,
+ query: 'model_name=CustomerAddress',
+ });
+ const { data, redactedFields } = await shopifyGraphqlClient.request<{
+ customerAddressDelete: { deletedAddressId?: string | null } | null;
+ }>({
+ auth,
+ query: `mutation DeleteCustomerAddress($customerId: ID!, $addressId: ID!) { customerAddressDelete(customerId: $customerId, addressId: $addressId) { deletedAddressId userErrors { field message } } }`,
+ variables: { customerId, addressId },
+ });
+ return {
+ customer_id: customerId,
+ deleted_address_id: data.customerAddressDelete?.deletedAddressId ?? addressId,
+ redacted_fields: redactedFields,
+ };
+ },
+});
diff --git a/packages/pieces/community/shopify/src/lib/actions/ai/delete-customer.ts b/packages/pieces/community/shopify/src/lib/actions/ai/delete-customer.ts
new file mode 100644
index 00000000000..a2f9816a855
--- /dev/null
+++ b/packages/pieces/community/shopify/src/lib/actions/ai/delete-customer.ts
@@ -0,0 +1,40 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { shopifyAuth } from '../../..';
+import { shopifyGraphqlClient } from '../../common/graphql';
+import { deleteCustomerOutputSchema } from '../../output-schemas/orders';
+
+export const shopifyAiDeleteCustomer = createAction({
+ auth: shopifyAuth,
+ name: 'delete_customer',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Delete Customer',
+ description: 'Permanently delete a customer who has no orders.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Permanently deletes one customer and their addresses. Shopify refuses when the customer has any orders (check can_delete on get_customer_profile). Cannot be undone; a repeat call fails because the customer is gone.',
+ idempotent: false,
+ },
+ outputSchema: deleteCustomerOutputSchema,
+ props: {
+ customer_id: Property.ShortText({
+ displayName: 'Customer ID',
+ description: 'The customer id, numeric or "gid://shopify/Customer/…". Find it with search_customers.',
+ required: true,
+ }),
+ },
+ async run({ auth, propsValue }) {
+ const id = shopifyGraphqlClient.toGid({ type: 'Customer', id: propsValue.customer_id });
+ const { data, redactedFields } = await shopifyGraphqlClient.request<{
+ customerDelete: { deletedCustomerId?: string | null } | null;
+ }>({
+ auth,
+ query: `mutation DeleteCustomer($input: CustomerDeleteInput!) { customerDelete(input: $input) { deletedCustomerId userErrors { field message } } }`,
+ variables: { input: { id } },
+ });
+ return {
+ deleted_customer_id: data.customerDelete?.deletedCustomerId ?? id,
+ redacted_fields: redactedFields,
+ };
+ },
+});
diff --git a/packages/pieces/community/shopify/src/lib/actions/ai/delete-draft-order.ts b/packages/pieces/community/shopify/src/lib/actions/ai/delete-draft-order.ts
new file mode 100644
index 00000000000..b86193a8f5d
--- /dev/null
+++ b/packages/pieces/community/shopify/src/lib/actions/ai/delete-draft-order.ts
@@ -0,0 +1,40 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { shopifyAuth } from '../../..';
+import { shopifyGraphqlClient } from '../../common/graphql';
+import { deleteDraftOrderOutputSchema } from '../../output-schemas/orders';
+
+export const shopifyAiDeleteDraftOrder = createAction({
+ auth: shopifyAuth,
+ name: 'delete_draft_order',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Delete Draft Order',
+ description: 'Permanently delete a draft order.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Permanently deletes one draft order. An invoice URL already sent to the customer stops working. Orders created from a completed draft are not affected. Cannot be undone; a repeat call fails because the draft is gone.',
+ idempotent: false,
+ },
+ outputSchema: deleteDraftOrderOutputSchema,
+ props: {
+ draft_order_id: Property.ShortText({
+ displayName: 'Draft Order ID',
+ description: 'The draft order id, numeric or "gid://shopify/DraftOrder/…". Find it with list_draft_orders.',
+ required: true,
+ }),
+ },
+ async run({ auth, propsValue }) {
+ const id = shopifyGraphqlClient.toGid({ type: 'DraftOrder', id: propsValue.draft_order_id });
+ const { data, redactedFields } = await shopifyGraphqlClient.request<{
+ draftOrderDelete: { deletedId?: string | null } | null;
+ }>({
+ auth,
+ query: `mutation DeleteDraftOrder($input: DraftOrderDeleteInput!) { draftOrderDelete(input: $input) { deletedId userErrors { field message } } }`,
+ variables: { input: { id } },
+ });
+ return {
+ deleted_id: data.draftOrderDelete?.deletedId ?? id,
+ redacted_fields: redactedFields,
+ };
+ },
+});
diff --git a/packages/pieces/community/shopify/src/lib/actions/ai/delete-order.ts b/packages/pieces/community/shopify/src/lib/actions/ai/delete-order.ts
new file mode 100644
index 00000000000..1f770256430
--- /dev/null
+++ b/packages/pieces/community/shopify/src/lib/actions/ai/delete-order.ts
@@ -0,0 +1,40 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { shopifyAuth } from '../../..';
+import { shopifyGraphqlClient } from '../../common/graphql';
+import { deleteOrderOutputSchema } from '../../output-schemas/orders';
+
+export const shopifyAiDeleteOrder = createAction({
+ auth: shopifyAuth,
+ name: 'delete_order',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Delete Order',
+ description: 'Permanently delete an archived or cancelled order.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Permanently deletes one order. Shopify refuses orders it does not allow deleting, for example orders paid through an online gateway, POS or gift card that are not archived or cancelled; orders paid manually can be deleted even while open. Prefer archive_order or start_order_cancellation to keep records. Cannot be undone; a repeat call fails because the order is gone.',
+ idempotent: false,
+ },
+ outputSchema: deleteOrderOutputSchema,
+ props: {
+ order_id: Property.ShortText({
+ displayName: 'Order ID',
+ description: 'The order id, numeric or "gid://shopify/Order/…". Find it with search_orders.',
+ required: true,
+ }),
+ },
+ async run({ auth, propsValue }) {
+ const orderId = shopifyGraphqlClient.toGid({ type: 'Order', id: propsValue.order_id });
+ const { data, redactedFields } = await shopifyGraphqlClient.request<{
+ orderDelete: { deletedId?: string | null } | null;
+ }>({
+ auth,
+ query: `mutation DeleteOrder($orderId: ID!) { orderDelete(orderId: $orderId) { deletedId userErrors { field message code } } }`,
+ variables: { orderId },
+ });
+ return {
+ deleted_id: data.orderDelete?.deletedId ?? orderId,
+ redacted_fields: redactedFields,
+ };
+ },
+});
diff --git a/packages/pieces/community/shopify/src/lib/actions/ai/generate-customer-activation-url.ts b/packages/pieces/community/shopify/src/lib/actions/ai/generate-customer-activation-url.ts
new file mode 100644
index 00000000000..85985a1d65d
--- /dev/null
+++ b/packages/pieces/community/shopify/src/lib/actions/ai/generate-customer-activation-url.ts
@@ -0,0 +1,41 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { shopifyAuth } from '../../..';
+import { shopifyGraphqlClient } from '../../common/graphql';
+import { generateCustomerActivationUrlOutputSchema } from '../../output-schemas/orders';
+
+export const shopifyAiGenerateCustomerActivationUrl = createAction({
+ auth: shopifyAuth,
+ name: 'generate_customer_activation_url',
+ classification: 'WRITE',
+ displayName: 'Generate Customer Activation URL',
+ description: 'Create a one-time account activation link for a customer.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Generates a one-time URL the customer opens to activate a classic customer account and set a password; nothing is emailed (use send_customer_account_invite to email an invite instead). Each call invalidates any earlier activation URL for that customer, so do not repeat it after sharing a link. Only for customers whose account is not yet enabled.',
+ idempotent: false,
+ },
+ outputSchema: generateCustomerActivationUrlOutputSchema,
+ props: {
+ customer_id: Property.ShortText({
+ displayName: 'Customer ID',
+ description: 'The customer id, numeric or "gid://shopify/Customer/…". Find it with search_customers.',
+ required: true,
+ }),
+ },
+ async run({ auth, propsValue }) {
+ const customerId = shopifyGraphqlClient.toGid({ type: 'Customer', id: propsValue.customer_id });
+ const { data, redactedFields } = await shopifyGraphqlClient.request<{
+ customerGenerateAccountActivationUrl: { accountActivationUrl?: string | null } | null;
+ }>({
+ auth,
+ query: `mutation GenerateCustomerActivationUrl($customerId: ID!) { customerGenerateAccountActivationUrl(customerId: $customerId) { accountActivationUrl userErrors { field message } } }`,
+ variables: { customerId },
+ });
+ return {
+ customer_id: customerId,
+ account_activation_url: data.customerGenerateAccountActivationUrl?.accountActivationUrl ?? null,
+ redacted_fields: redactedFields,
+ };
+ },
+});
diff --git a/packages/pieces/community/shopify/src/lib/actions/ai/get-abandonment.ts b/packages/pieces/community/shopify/src/lib/actions/ai/get-abandonment.ts
new file mode 100644
index 00000000000..b6c4e62b8ae
--- /dev/null
+++ b/packages/pieces/community/shopify/src/lib/actions/ai/get-abandonment.ts
@@ -0,0 +1,48 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { shopifyAuth } from '../../..';
+import {
+ GqlAbandonment,
+ shopifyFields,
+ shopifyGraphqlClient,
+ shopifyMappers,
+} from '../../common/graphql';
+import { abandonmentOutputSchema } from '../../output-schemas/orders';
+
+export const shopifyAiGetAbandonment = createAction({
+ auth: shopifyAuth,
+ name: 'get_abandonment',
+ classification: 'READ',
+ displayName: 'Get Abandonment',
+ description: 'Get a customer abandonment (browse, cart or checkout) by id.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Returns one abandonment record by its Abandonment id: whether it was a browse, cart or checkout abandonment, the recovery email state, whether the customer ordered since, and the linked abandoned checkout. Use get_checkout_abandonment when you only have an abandoned checkout id. Customer fields may be null on stores without protected customer data access (see redacted_fields). Read-only.',
+ idempotent: true,
+ },
+ outputSchema: abandonmentOutputSchema,
+ props: {
+ abandonment_id: Property.ShortText({
+ displayName: 'Abandonment ID',
+ description: 'The abandonment id, numeric or "gid://shopify/Abandonment/…".',
+ required: true,
+ }),
+ },
+ async run({ auth, propsValue }) {
+ const id = shopifyGraphqlClient.toGid({ type: 'Abandonment', id: propsValue.abandonment_id });
+ const { data, redactedFields } = await shopifyGraphqlClient.request<{
+ abandonment: GqlAbandonment | null;
+ }>({
+ auth,
+ query: `query GetAbandonment($id: ID!) { abandonment(id: $id) { ${shopifyFields.ABANDONMENT_FIELDS} } }`,
+ variables: { id },
+ });
+ if (!data.abandonment) {
+ throw new Error(`Abandonment ${id} was not found.`);
+ }
+ return {
+ ...shopifyMappers.mapAbandonment(data.abandonment),
+ redacted_fields: redactedFields,
+ };
+ },
+});
diff --git a/packages/pieces/community/shopify/src/lib/actions/ai/get-checkout-abandonment.ts b/packages/pieces/community/shopify/src/lib/actions/ai/get-checkout-abandonment.ts
new file mode 100644
index 00000000000..cc2703fb916
--- /dev/null
+++ b/packages/pieces/community/shopify/src/lib/actions/ai/get-checkout-abandonment.ts
@@ -0,0 +1,59 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { shopifyAuth } from '../../..';
+import {
+ GqlAbandonment,
+ shopifyFields,
+ shopifyGraphqlClient,
+ shopifyMappers,
+} from '../../common/graphql';
+import { checkoutAbandonmentOutputSchema } from '../../output-schemas/orders';
+
+export const shopifyAiGetCheckoutAbandonment = createAction({
+ auth: shopifyAuth,
+ name: 'get_checkout_abandonment',
+ classification: 'READ',
+ displayName: 'Get Checkout Abandonment',
+ description: 'Get the abandonment record of an abandoned checkout.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Looks up the abandonment record for an abandoned checkout id (from list_abandoned_checkouts): recovery email state, whether the customer ordered since and the recovery URL. Returns found=false when Shopify does not track an abandonment for that checkout. Customer fields may be null on stores without protected customer data access. Read-only.',
+ idempotent: true,
+ },
+ outputSchema: checkoutAbandonmentOutputSchema,
+ props: {
+ abandoned_checkout_id: Property.ShortText({
+ displayName: 'Abandoned Checkout ID',
+ description:
+ 'The abandoned checkout id, numeric or "gid://shopify/AbandonedCheckout/…". Find it with list_abandoned_checkouts.',
+ required: true,
+ }),
+ },
+ async run({ auth, propsValue }) {
+ const abandonedCheckoutId = shopifyGraphqlClient.toGid({
+ type: 'AbandonedCheckout',
+ id: propsValue.abandoned_checkout_id,
+ });
+ const { data, redactedFields } = await shopifyGraphqlClient.request<{
+ abandonmentByAbandonedCheckoutId: GqlAbandonment | null;
+ }>({
+ auth,
+ query: `query GetCheckoutAbandonment($abandonedCheckoutId: ID!) { abandonmentByAbandonedCheckoutId(abandonedCheckoutId: $abandonedCheckoutId) { ${shopifyFields.ABANDONMENT_FIELDS} } }`,
+ variables: { abandonedCheckoutId },
+ });
+ const abandonment = data.abandonmentByAbandonedCheckoutId;
+ if (!abandonment) {
+ return {
+ found: false,
+ ...shopifyMappers.mapAbandonment(null),
+ abandoned_checkout_id: abandonedCheckoutId,
+ redacted_fields: redactedFields,
+ };
+ }
+ return {
+ found: true,
+ ...shopifyMappers.mapAbandonment(abandonment),
+ redacted_fields: redactedFields,
+ };
+ },
+});
diff --git a/packages/pieces/community/shopify/src/lib/actions/ai/get-customer-profile.ts b/packages/pieces/community/shopify/src/lib/actions/ai/get-customer-profile.ts
new file mode 100644
index 00000000000..72604bff84b
--- /dev/null
+++ b/packages/pieces/community/shopify/src/lib/actions/ai/get-customer-profile.ts
@@ -0,0 +1,49 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { shopifyAuth } from '../../..';
+import {
+ GqlCustomer,
+ shopifyFields,
+ shopifyGraphqlClient,
+ shopifyMappers,
+} from '../../common/graphql';
+import { customerOutputSchema } from '../../output-schemas/orders';
+
+export const shopifyAiGetCustomerProfile = createAction({
+ auth: shopifyAuth,
+ name: 'get_customer_profile',
+ classification: 'READ',
+ displayName: 'Get Customer',
+ description: 'Get one customer with contact details, marketing state and default address.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Returns one customer by id: name, email and its marketing state, phone, tags, note, account state, order count, amount spent and default address. Use search_customers to find a customer by email, name or phone first. Name, email, phone and address may be null on stores without protected customer data access; such fields are listed in redacted_fields.',
+ idempotent: true,
+ },
+ outputSchema: customerOutputSchema,
+ props: {
+ customer_id: Property.ShortText({
+ displayName: 'Customer ID',
+ description:
+ 'The customer id, numeric such as "207119551" or "gid://shopify/Customer/207119551". Find it with search_customers.',
+ required: true,
+ }),
+ },
+ async run({ auth, propsValue }) {
+ const id = shopifyGraphqlClient.toGid({ type: 'Customer', id: propsValue.customer_id });
+ const { data, redactedFields } = await shopifyGraphqlClient.request<{
+ customer: GqlCustomer | null;
+ }>({
+ auth,
+ query: `query GetCustomerProfile($id: ID!) { customer(id: $id) { ${shopifyFields.CUSTOMER_FIELDS} } }`,
+ variables: { id },
+ });
+ if (!data.customer) {
+ throw new Error(`Customer ${id} was not found.`);
+ }
+ return {
+ ...shopifyMappers.mapCustomer(data.customer),
+ redacted_fields: redactedFields,
+ };
+ },
+});
diff --git a/packages/pieces/community/shopify/src/lib/actions/ai/get-draft-order.ts b/packages/pieces/community/shopify/src/lib/actions/ai/get-draft-order.ts
new file mode 100644
index 00000000000..74a6de415b4
--- /dev/null
+++ b/packages/pieces/community/shopify/src/lib/actions/ai/get-draft-order.ts
@@ -0,0 +1,48 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { shopifyAuth } from '../../..';
+import {
+ GqlDraftOrder,
+ shopifyFields,
+ shopifyGraphqlClient,
+ shopifyMappers,
+} from '../../common/graphql';
+import { draftOrderOutputSchema } from '../../output-schemas/orders';
+
+export const shopifyAiGetDraftOrder = createAction({
+ auth: shopifyAuth,
+ name: 'get_draft_order',
+ classification: 'READ',
+ displayName: 'Get Draft Order',
+ description: 'Get one draft order with its line items and totals.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Returns one draft order by id: status, invoice URL, totals, customer, payment terms, the first 100 line items and, once completed, the resulting order id. Use list_draft_orders to find a draft first. Read-only.',
+ idempotent: true,
+ },
+ outputSchema: draftOrderOutputSchema,
+ props: {
+ draft_order_id: Property.ShortText({
+ displayName: 'Draft Order ID',
+ description: 'The draft order id, numeric or "gid://shopify/DraftOrder/…". Find it with list_draft_orders.',
+ required: true,
+ }),
+ },
+ async run({ auth, propsValue }) {
+ const id = shopifyGraphqlClient.toGid({ type: 'DraftOrder', id: propsValue.draft_order_id });
+ const { data, redactedFields } = await shopifyGraphqlClient.request<{
+ draftOrder: GqlDraftOrder | null;
+ }>({
+ auth,
+ query: `query GetDraftOrder($id: ID!) { draftOrder(id: $id) { ${shopifyFields.DRAFT_ORDER_DETAIL_FIELDS} } }`,
+ variables: { id },
+ });
+ if (!data.draftOrder) {
+ throw new Error(`Draft order ${id} was not found.`);
+ }
+ return {
+ ...shopifyMappers.mapDraftOrderDetail(data.draftOrder),
+ redacted_fields: redactedFields,
+ };
+ },
+});
diff --git a/packages/pieces/community/shopify/src/lib/actions/ai/get-granted-access-scopes.ts b/packages/pieces/community/shopify/src/lib/actions/ai/get-granted-access-scopes.ts
new file mode 100644
index 00000000000..7ced8b3cb4e
--- /dev/null
+++ b/packages/pieces/community/shopify/src/lib/actions/ai/get-granted-access-scopes.ts
@@ -0,0 +1,40 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { shopifyAuth } from '../../..';
+import { shopifyGraphqlClient } from '../../common/graphql';
+import { getGrantedAccessScopesOutputSchema } from '../../output-schemas/orders';
+
+export const shopifyAiGetGrantedAccessScopes = createAction({
+ auth: shopifyAuth,
+ name: 'get_granted_access_scopes',
+ classification: 'READ',
+ displayName: 'Get Granted Access Scopes',
+ description: 'List the Admin API access scopes granted to the connected app.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists the access scopes (for example read_orders, write_customers) granted to the connected custom app. Use it to diagnose an "access denied" or missing-scope error before retrying: if the scope is absent, the merchant must add it to the app and reinstall. Read-only.',
+ idempotent: true,
+ },
+ outputSchema: getGrantedAccessScopesOutputSchema,
+ props: {},
+ async run({ auth }) {
+ const { data, redactedFields } = await shopifyGraphqlClient.request<{
+ currentAppInstallation: {
+ accessScopes?: { handle: string; description?: string | null }[] | null;
+ };
+ }>({
+ auth,
+ query: `query GetGrantedAccessScopes { currentAppInstallation { accessScopes { handle description } } }`,
+ });
+ const items = (data.currentAppInstallation.accessScopes ?? []).map((scope) => ({
+ handle: scope.handle,
+ description: scope.description ?? null,
+ }));
+ return {
+ items,
+ count: items.length,
+ handles: items.map((item) => item.handle).join(', '),
+ redacted_fields: redactedFields,
+ };
+ },
+});
diff --git a/packages/pieces/community/shopify/src/lib/actions/ai/get-job.ts b/packages/pieces/community/shopify/src/lib/actions/ai/get-job.ts
new file mode 100644
index 00000000000..8f11396ea5b
--- /dev/null
+++ b/packages/pieces/community/shopify/src/lib/actions/ai/get-job.ts
@@ -0,0 +1,55 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { shopifyAuth } from '../../..';
+import { shopifyGraphqlClient } from '../../common/graphql';
+import { getJobOutputSchema } from '../../output-schemas/orders';
+
+export const shopifyAiGetJob = createAction({
+ auth: shopifyAuth,
+ name: 'get_job',
+ classification: 'READ',
+ displayName: 'Get Job Status',
+ description: 'Check whether an asynchronous Shopify job has finished.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Reads the status of an asynchronous Shopify job, such as the job returned by start_order_cancellation. Returns done=true once Shopify has finished the work; call it again later while done is false. Shopify also reports done=true for an unknown job id, so pass the exact id you were given. One status read, it never waits.',
+ idempotent: true,
+ },
+ outputSchema: getJobOutputSchema,
+ props: {
+ job_id: Property.ShortText({
+ displayName: 'Job ID',
+ description:
+ 'The job id returned by the start action, for example "gid://shopify/Job/dc9b2604-c73b-45c6-8942-e235bac987e8". A bare UUID such as "dc9b2604-c73b-45c6-8942-e235bac987e8" is also accepted.',
+ required: true,
+ }),
+ },
+ async run({ auth, propsValue }) {
+ const id = toJobGid(propsValue.job_id);
+ const { data, redactedFields } = await shopifyGraphqlClient.request<{
+ job: { id: string; done?: boolean | null } | null;
+ }>({
+ auth,
+ query: `query GetJob($id: ID!) { job(id: $id) { id done } }`,
+ variables: { id },
+ });
+ if (!data.job) {
+ throw new Error(`Job ${id} was not found. Pass the job id returned by the start action.`);
+ }
+ return {
+ id: data.job.id,
+ done: data.job.done ?? false,
+ redacted_fields: redactedFields,
+ };
+ },
+});
+
+function toJobGid(value: string): string {
+ const trimmed = value.trim();
+ if (UUID_PATTERN.test(trimmed)) {
+ return `gid://shopify/Job/${trimmed}`;
+ }
+ return shopifyGraphqlClient.toGid({ type: 'Job', id: trimmed });
+}
+
+const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
diff --git a/packages/pieces/community/shopify/src/lib/actions/ai/get-order-risk-assessments.ts b/packages/pieces/community/shopify/src/lib/actions/ai/get-order-risk-assessments.ts
new file mode 100644
index 00000000000..9d24ea18768
--- /dev/null
+++ b/packages/pieces/community/shopify/src/lib/actions/ai/get-order-risk-assessments.ts
@@ -0,0 +1,67 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { shopifyAuth } from '../../..';
+import { shopifyGraphqlClient } from '../../common/graphql';
+import { getOrderRiskAssessmentsOutputSchema } from '../../output-schemas/orders';
+
+export const shopifyAiGetOrderRiskAssessments = createAction({
+ auth: shopifyAuth,
+ name: 'get_order_risk_assessments',
+ classification: 'READ',
+ displayName: 'Get Order Risk Assessments',
+ description: 'Get the fraud risk recommendation and assessments of an order.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Returns the fraud-risk summary of one order: the overall recommendation (accept, investigate, cancel) and every risk assessment with its level, provider and supporting facts. Use it before fulfilling or cancelling a suspicious order. Read-only.',
+ idempotent: true,
+ },
+ outputSchema: getOrderRiskAssessmentsOutputSchema,
+ props: {
+ order_id: Property.ShortText({
+ displayName: 'Order ID',
+ description: 'The order id, numeric or "gid://shopify/Order/…". Find it with search_orders.',
+ required: true,
+ }),
+ },
+ async run({ auth, propsValue }) {
+ const id = shopifyGraphqlClient.toGid({ type: 'Order', id: propsValue.order_id });
+ const { data, redactedFields } = await shopifyGraphqlClient.request<{
+ order: {
+ id: string;
+ risk?: {
+ recommendation?: string | null;
+ assessments?: GqlRiskAssessment[] | null;
+ } | null;
+ } | null;
+ }>({
+ auth,
+ primaryPaths: ['order.risk'],
+ query: `query GetOrderRiskAssessments($id: ID!) { order(id: $id) { id risk { recommendation assessments { riskLevel provider { title } facts { description sentiment } } } } }`,
+ variables: { id },
+ });
+ if (!data.order) {
+ throw new Error(`Order ${id} was not found.`);
+ }
+ const items = (data.order.risk?.assessments ?? []).map((assessment) => ({
+ risk_level: assessment.riskLevel ?? null,
+ provider: assessment.provider?.title ?? null,
+ facts: (assessment.facts ?? []).map((fact) => ({
+ description: fact.description ?? null,
+ sentiment: fact.sentiment ?? null,
+ })),
+ }));
+ return {
+ order_id: data.order.id,
+ recommendation: data.order.risk?.recommendation ?? null,
+ items,
+ count: items.length,
+ redacted_fields: redactedFields,
+ };
+ },
+});
+
+type GqlRiskAssessment = {
+ riskLevel?: string | null;
+ provider?: { title?: string | null } | null;
+ facts?: { description?: string | null; sentiment?: string | null }[] | null;
+};
diff --git a/packages/pieces/community/shopify/src/lib/actions/ai/get-order-transaction.ts b/packages/pieces/community/shopify/src/lib/actions/ai/get-order-transaction.ts
new file mode 100644
index 00000000000..491583f4718
--- /dev/null
+++ b/packages/pieces/community/shopify/src/lib/actions/ai/get-order-transaction.ts
@@ -0,0 +1,49 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { shopifyAuth } from '../../..';
+import {
+ GqlTransaction,
+ shopifyFields,
+ shopifyGraphqlClient,
+ shopifyMappers,
+} from '../../common/graphql';
+import { orderTransactionOutputSchema } from '../../output-schemas/orders';
+
+export const shopifyAiGetOrderTransaction = createAction({
+ auth: shopifyAuth,
+ name: 'get_order_transaction',
+ classification: 'READ',
+ displayName: 'Get Order Transaction',
+ description: 'Get one payment transaction by id.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Returns one order transaction by its id: kind, status, amount, gateway, capturable state, parent transaction and the order it belongs to. Use list_order_transactions when you only know the order. Read-only.',
+ idempotent: true,
+ },
+ outputSchema: orderTransactionOutputSchema,
+ props: {
+ transaction_id: Property.ShortText({
+ displayName: 'Transaction ID',
+ description:
+ 'The transaction id, numeric such as "389404469" or "gid://shopify/OrderTransaction/389404469". Find it with list_order_transactions.',
+ required: true,
+ }),
+ },
+ async run({ auth, propsValue }) {
+ const id = shopifyGraphqlClient.toGid({ type: 'OrderTransaction', id: propsValue.transaction_id });
+ const { data, redactedFields } = await shopifyGraphqlClient.request<{
+ node: GqlTransaction | null;
+ }>({
+ auth,
+ query: `query GetOrderTransaction($id: ID!) { node(id: $id) { id ... on OrderTransaction { ${shopifyFields.TRANSACTION_FIELDS} } } }`,
+ variables: { id },
+ });
+ if (!data.node) {
+ throw new Error(`Transaction ${id} was not found.`);
+ }
+ return {
+ ...shopifyMappers.mapTransaction(data.node),
+ redacted_fields: redactedFields,
+ };
+ },
+});
diff --git a/packages/pieces/community/shopify/src/lib/actions/ai/get-order.ts b/packages/pieces/community/shopify/src/lib/actions/ai/get-order.ts
new file mode 100644
index 00000000000..b8cbc1caf72
--- /dev/null
+++ b/packages/pieces/community/shopify/src/lib/actions/ai/get-order.ts
@@ -0,0 +1,49 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { shopifyAuth } from '../../..';
+import {
+ GqlOrder,
+ shopifyFields,
+ shopifyGraphqlClient,
+ shopifyMappers,
+} from '../../common/graphql';
+import { orderOutputSchema } from '../../output-schemas/orders';
+
+export const shopifyAiGetOrder = createAction({
+ auth: shopifyAuth,
+ name: 'get_order',
+ classification: 'READ',
+ displayName: 'Get Order',
+ description: 'Get one order with its totals, addresses and line items.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Returns one order by id: status, money totals, customer, shipping and billing address, the first 100 line items, and the fulfillment and transaction counts. Use search_orders to find an order by name, email or date first. Customer contact fields may be null on stores without protected customer data access; such fields are listed in redacted_fields.',
+ idempotent: true,
+ },
+ outputSchema: orderOutputSchema,
+ props: {
+ order_id: Property.ShortText({
+ displayName: 'Order ID',
+ description:
+ 'The order id: a numeric id such as "450789469" or a full id such as "gid://shopify/Order/450789469". Find it with search_orders.',
+ required: true,
+ }),
+ },
+ async run({ auth, propsValue }) {
+ const id = shopifyGraphqlClient.toGid({ type: 'Order', id: propsValue.order_id });
+ const { data, redactedFields } = await shopifyGraphqlClient.request<{
+ order: GqlOrder | null;
+ }>({
+ auth,
+ query: `query GetOrder($id: ID!) { order(id: $id) { ${shopifyFields.ORDER_DETAIL_FIELDS} } }`,
+ variables: { id },
+ });
+ if (!data.order) {
+ throw new Error(`Order ${id} was not found.`);
+ }
+ return {
+ ...shopifyMappers.mapOrderDetail(data.order),
+ redacted_fields: redactedFields,
+ };
+ },
+});
diff --git a/packages/pieces/community/shopify/src/lib/actions/ai/get-refund.ts b/packages/pieces/community/shopify/src/lib/actions/ai/get-refund.ts
new file mode 100644
index 00000000000..d25364b0019
--- /dev/null
+++ b/packages/pieces/community/shopify/src/lib/actions/ai/get-refund.ts
@@ -0,0 +1,48 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { shopifyAuth } from '../../..';
+import {
+ GqlRefund,
+ shopifyFields,
+ shopifyGraphqlClient,
+ shopifyMappers,
+} from '../../common/graphql';
+import { refundOutputSchema } from '../../output-schemas/orders';
+
+export const shopifyAiGetRefund = createAction({
+ auth: shopifyAuth,
+ name: 'get_refund',
+ classification: 'READ',
+ displayName: 'Get Refund',
+ description: 'Get one refund by id.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Returns one refund by id with its amount, note, refunded line items, refund transactions and the order it belongs to. Use list_order_refunds when you only know the order. Read-only.',
+ idempotent: true,
+ },
+ outputSchema: refundOutputSchema,
+ props: {
+ refund_id: Property.ShortText({
+ displayName: 'Refund ID',
+ description: 'The refund id, numeric or "gid://shopify/Refund/…". Find it with list_order_refunds.',
+ required: true,
+ }),
+ },
+ async run({ auth, propsValue }) {
+ const id = shopifyGraphqlClient.toGid({ type: 'Refund', id: propsValue.refund_id });
+ const { data, redactedFields } = await shopifyGraphqlClient.request<{
+ refund: GqlRefund | null;
+ }>({
+ auth,
+ query: `query GetRefund($id: ID!) { refund(id: $id) { ${shopifyFields.REFUND_FIELDS} } }`,
+ variables: { id },
+ });
+ if (!data.refund) {
+ throw new Error(`Refund ${id} was not found.`);
+ }
+ return {
+ ...shopifyMappers.mapRefund(data.refund),
+ redacted_fields: redactedFields,
+ };
+ },
+});
diff --git a/packages/pieces/community/shopify/src/lib/actions/ai/get-shop.ts b/packages/pieces/community/shopify/src/lib/actions/ai/get-shop.ts
new file mode 100644
index 00000000000..4bc9552ae08
--- /dev/null
+++ b/packages/pieces/community/shopify/src/lib/actions/ai/get-shop.ts
@@ -0,0 +1,88 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { shopifyAuth } from '../../..';
+import { shopifyGraphqlClient } from '../../common/graphql';
+import { getShopOutputSchema } from '../../output-schemas/orders';
+
+export const shopifyAiGetShop = createAction({
+ auth: shopifyAuth,
+ name: 'get_shop',
+ classification: 'READ',
+ displayName: 'Get Shop',
+ description: 'Get the store name, domain, currency, timezone and plan.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Returns the connected store: name, domains, shop currency and enabled presentment currencies, IANA timezone, weight unit and plan. Call it first when you need the currency for money fields or the timezone to build date filters for search_orders and other searches. Read-only.',
+ idempotent: true,
+ },
+ outputSchema: getShopOutputSchema,
+ props: {},
+ async run({ auth }) {
+ const { data, redactedFields } = await shopifyGraphqlClient.request<{
+ shop: GqlShop;
+ }>({
+ auth,
+ query: `query GetShop { shop { id name email contactEmail myshopifyDomain url primaryDomain { host url } currencyCode enabledPresentmentCurrencies ianaTimezone timezoneAbbreviation timezoneOffset weightUnit unitSystem taxesIncluded taxShipping createdAt plan { publicDisplayName partnerDevelopment shopifyPlus } shopAddress { city provinceCode countryCodeV2 zip } } }`,
+ });
+ const shop = data.shop;
+ return {
+ id: shop.id,
+ name: shop.name ?? null,
+ email: shop.email ?? null,
+ contact_email: shop.contactEmail ?? null,
+ myshopify_domain: shop.myshopifyDomain ?? null,
+ url: shop.url ?? null,
+ primary_domain_host: shop.primaryDomain?.host ?? null,
+ primary_domain_url: shop.primaryDomain?.url ?? null,
+ currency_code: shop.currencyCode ?? null,
+ enabled_presentment_currencies: (shop.enabledPresentmentCurrencies ?? []).join(', '),
+ iana_timezone: shop.ianaTimezone ?? null,
+ timezone_abbreviation: shop.timezoneAbbreviation ?? null,
+ timezone_offset: shop.timezoneOffset ?? null,
+ weight_unit: shop.weightUnit ?? null,
+ unit_system: shop.unitSystem ?? null,
+ taxes_included: shop.taxesIncluded ?? null,
+ tax_shipping: shop.taxShipping ?? null,
+ plan_name: shop.plan?.publicDisplayName ?? null,
+ plan_partner_development: shop.plan?.partnerDevelopment ?? null,
+ plan_shopify_plus: shop.plan?.shopifyPlus ?? null,
+ address_city: shop.shopAddress?.city ?? null,
+ address_province_code: shop.shopAddress?.provinceCode ?? null,
+ address_country_code: shop.shopAddress?.countryCodeV2 ?? null,
+ address_zip: shop.shopAddress?.zip ?? null,
+ created_at: shop.createdAt ?? null,
+ redacted_fields: redactedFields,
+ };
+ },
+});
+
+type GqlShop = {
+ id: string;
+ name?: string | null;
+ email?: string | null;
+ contactEmail?: string | null;
+ myshopifyDomain?: string | null;
+ url?: string | null;
+ primaryDomain?: { host?: string | null; url?: string | null } | null;
+ currencyCode?: string | null;
+ enabledPresentmentCurrencies?: string[] | null;
+ ianaTimezone?: string | null;
+ timezoneAbbreviation?: string | null;
+ timezoneOffset?: string | null;
+ weightUnit?: string | null;
+ unitSystem?: string | null;
+ taxesIncluded?: boolean | null;
+ taxShipping?: boolean | null;
+ createdAt?: string | null;
+ plan?: {
+ publicDisplayName?: string | null;
+ partnerDevelopment?: boolean | null;
+ shopifyPlus?: boolean | null;
+ } | null;
+ shopAddress?: {
+ city?: string | null;
+ provinceCode?: string | null;
+ countryCodeV2?: string | null;
+ zip?: string | null;
+ } | null;
+};
diff --git a/packages/pieces/community/shopify/src/lib/actions/ai/list-abandoned-checkouts.ts b/packages/pieces/community/shopify/src/lib/actions/ai/list-abandoned-checkouts.ts
new file mode 100644
index 00000000000..6e0a1f9a260
--- /dev/null
+++ b/packages/pieces/community/shopify/src/lib/actions/ai/list-abandoned-checkouts.ts
@@ -0,0 +1,72 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { shopifyAuth } from '../../..';
+import {
+ GqlAbandonedCheckout,
+ GqlConnection,
+ shopifyFields,
+ shopifyGraphqlClient,
+ shopifyMappers,
+ shopifyProps,
+ shopifyValues,
+} from '../../common/graphql';
+import { listAbandonedCheckoutsOutputSchema } from '../../output-schemas/orders';
+
+const MAX_PAGE_SIZE = 100;
+
+export const shopifyAiListAbandonedCheckouts = createAction({
+ auth: shopifyAuth,
+ name: 'list_abandoned_checkouts',
+ classification: 'SEARCH',
+ displayName: 'List Abandoned Checkouts',
+ description: 'List checkouts that customers started but did not complete.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists abandoned checkouts with total, customer and the recovery URL to send to the shopper. Supports search syntax such as "created_at:>=2026-09-01". Use get_checkout_abandonment for the marketing-email state of one checkout. Paged: pass end_cursor back as the cursor while has_next_page is true. Customer name and email may be null on stores without protected customer data access (see redacted_fields).',
+ idempotent: true,
+ },
+ outputSchema: listAbandonedCheckoutsOutputSchema,
+ props: {
+ query: shopifyProps.searchQuery(
+ 'Shopify search syntax, for example "created_at:>=2026-09-01" or "status:open". Leave empty for all.'
+ ),
+ sort_key: Property.StaticDropdown({
+ displayName: 'Sort By',
+ description: 'Field to sort by. Defaults to the checkout id.',
+ required: false,
+ options: {
+ options: [
+ { label: 'Created at', value: 'CREATED_AT' },
+ { label: 'Checkout id', value: 'CHECKOUT_ID' },
+ { label: 'Customer name', value: 'CUSTOMER_NAME' },
+ { label: 'Total price', value: 'TOTAL_PRICE' },
+ { label: 'Relevance (with a query)', value: 'RELEVANCE' },
+ { label: 'ID', value: 'ID' },
+ ],
+ },
+ }),
+ reverse: shopifyProps.reverse(),
+ first: shopifyProps.first({ max: MAX_PAGE_SIZE }),
+ after: shopifyProps.after(),
+ },
+ async run({ auth, propsValue }) {
+ const { data, redactedFields } = await shopifyGraphqlClient.request<{
+ abandonedCheckouts: GqlConnection<GqlAbandonedCheckout>;
+ }>({
+ auth,
+ query: `query ListAbandonedCheckouts($first: Int!, $after: String, $query: String, $sortKey: AbandonedCheckoutSortKeys, $reverse: Boolean) { abandonedCheckouts(first: $first, after: $after, query: $query, sortKey: $sortKey, reverse: $reverse) { nodes { ${shopifyFields.ABANDONED_CHECKOUT_FIELDS} } ${shopifyFields.PAGE_INFO_FIELDS} } }`,
+ variables: {
+ first: shopifyValues.readFirst({ value: propsValue.first, max: MAX_PAGE_SIZE }),
+ after: shopifyValues.nonEmpty(propsValue.after),
+ query: shopifyValues.nonEmpty(propsValue.query),
+ sortKey: propsValue.sort_key,
+ reverse: propsValue.reverse ?? false,
+ },
+ });
+ return shopifyMappers.toPage({
+ connection: data.abandonedCheckouts,
+ map: shopifyMappers.mapAbandonedCheckout,
+ redactedFields,
+ });
+ },
+});
diff --git a/packages/pieces/community/shopify/src/lib/actions/ai/list-customer-addresses.ts b/packages/pieces/community/shopify/src/lib/actions/ai/list-customer-addresses.ts
new file mode 100644
index 00000000000..be899957fca
--- /dev/null
+++ b/packages/pieces/community/shopify/src/lib/actions/ai/list-customer-addresses.ts
@@ -0,0 +1,75 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { shopifyAuth } from '../../..';
+import {
+ GqlConnection,
+ GqlMailingAddress,
+ shopifyFields,
+ shopifyGraphqlClient,
+ shopifyMappers,
+ shopifyProps,
+ shopifyValues,
+} from '../../common/graphql';
+import { listCustomerAddressesOutputSchema } from '../../output-schemas/orders';
+
+const MAX_PAGE_SIZE = 250;
+
+export const shopifyAiListCustomerAddresses = createAction({
+ auth: shopifyAuth,
+ name: 'list_customer_addresses',
+ classification: 'SEARCH',
+ displayName: 'List Customer Addresses',
+ description: 'List the saved addresses of one customer.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists the saved addresses of one customer, marking the default one. Use the address id with update_customer_address, delete_customer_address or set_default_customer_address. Paged: pass end_cursor back as the cursor while has_next_page is true. Address fields may be null on stores without protected customer data access (see redacted_fields).',
+ idempotent: true,
+ },
+ outputSchema: listCustomerAddressesOutputSchema,
+ props: {
+ customer_id: Property.ShortText({
+ displayName: 'Customer ID',
+ description: 'The customer id, numeric or "gid://shopify/Customer/…". Find it with search_customers.',
+ required: true,
+ }),
+ reverse: shopifyProps.reverse(),
+ first: shopifyProps.first({ max: MAX_PAGE_SIZE }),
+ after: shopifyProps.after(),
+ },
+ async run({ auth, propsValue }) {
+ const id = shopifyGraphqlClient.toGid({ type: 'Customer', id: propsValue.customer_id });
+ const { data, redactedFields } = await shopifyGraphqlClient.request<{
+ customer: {
+ id: string;
+ defaultAddress?: { id?: string | null } | null;
+ addressesV2?: GqlConnection<GqlMailingAddress> | null;
+ } | null;
+ }>({
+ auth,
+ primaryPaths: ['customer.addressesV2'],
+ query: `query ListCustomerAddresses($id: ID!, $first: Int!, $after: String, $reverse: Boolean) { customer(id: $id) { id defaultAddress { id } addressesV2(first: $first, after: $after, reverse: $reverse) { nodes { ${shopifyFields.ADDRESS_FIELDS} } ${shopifyFields.PAGE_INFO_FIELDS} } } }`,
+ variables: {
+ id,
+ first: shopifyValues.readFirst({ value: propsValue.first, max: MAX_PAGE_SIZE }),
+ after: shopifyValues.nonEmpty(propsValue.after),
+ reverse: propsValue.reverse ?? false,
+ },
+ });
+ const customer = data.customer;
+ if (!customer) {
+ throw new Error(`Customer ${id} was not found.`);
+ }
+ const defaultId = customer.defaultAddress?.id ?? null;
+ return {
+ customer_id: customer.id,
+ ...shopifyMappers.toPage({
+ connection: customer.addressesV2,
+ map: (address: GqlMailingAddress) => ({
+ ...shopifyMappers.mapAddress(address),
+ is_default: defaultId !== null && address.id === defaultId,
+ }),
+ redactedFields,
+ }),
+ };
+ },
+});
diff --git a/packages/pieces/community/shopify/src/lib/actions/ai/list-customer-orders.ts b/packages/pieces/community/shopify/src/lib/actions/ai/list-customer-orders.ts
new file mode 100644
index 00000000000..9745799dbd1
--- /dev/null
+++ b/packages/pieces/community/shopify/src/lib/actions/ai/list-customer-orders.ts
@@ -0,0 +1,86 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { shopifyAuth } from '../../..';
+import {
+ GqlConnection,
+ GqlOrder,
+ shopifyFields,
+ shopifyGraphqlClient,
+ shopifyMappers,
+ shopifyProps,
+ shopifyValues,
+} from '../../common/graphql';
+import { listCustomerOrdersOutputSchema } from '../../output-schemas/orders';
+
+const MAX_PAGE_SIZE = 40;
+
+export const shopifyAiListCustomerOrders = createAction({
+ auth: shopifyAuth,
+ name: 'list_customer_orders',
+ classification: 'SEARCH',
+ displayName: 'List Customer Orders',
+ description: 'List the orders of one customer, one page at a time.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists the orders placed by one customer as order summaries (no line items), newest last unless reversed, optionally filtered with order search syntax such as "financial_status:paid". Use get_order for the full order. Paged: pass end_cursor back as the cursor while has_next_page is true. Without the read_all_orders scope only the last 60 days are visible.',
+ idempotent: true,
+ },
+ outputSchema: listCustomerOrdersOutputSchema,
+ props: {
+ customer_id: Property.ShortText({
+ displayName: 'Customer ID',
+ description: 'The customer id, numeric or "gid://shopify/Customer/…". Find it with search_customers.',
+ required: true,
+ }),
+ query: shopifyProps.searchQuery(
+ 'Optional order search syntax to narrow the list, for example "financial_status:paid" or "created_at:>=2026-01-01".'
+ ),
+ sort_key: Property.StaticDropdown({
+ displayName: 'Sort By',
+ description: 'Field to sort by. Defaults to the order id.',
+ required: false,
+ options: {
+ options: [
+ { label: 'Created at', value: 'CREATED_AT' },
+ { label: 'Processed at', value: 'PROCESSED_AT' },
+ { label: 'Updated at', value: 'UPDATED_AT' },
+ { label: 'Order number', value: 'ORDER_NUMBER' },
+ { label: 'Total price', value: 'TOTAL_PRICE' },
+ { label: 'ID', value: 'ID' },
+ ],
+ },
+ }),
+ reverse: shopifyProps.reverse(),
+ first: shopifyProps.first({ max: MAX_PAGE_SIZE }),
+ after: shopifyProps.after(),
+ },
+ async run({ auth, propsValue }) {
+ const id = shopifyGraphqlClient.toGid({ type: 'Customer', id: propsValue.customer_id });
+ const { data, redactedFields } = await shopifyGraphqlClient.request<{
+ customer: { id: string; orders?: GqlConnection<GqlOrder> | null } | null;
+ }>({
+ auth,
+ primaryPaths: ['customer.orders'],
+ query: `query ListCustomerOrders($id: ID!, $first: Int!, $after: String, $query: String, $sortKey: OrderSortKeys, $reverse: Boolean) { customer(id: $id) { id orders(first: $first, after: $after, query: $query, sortKey: $sortKey, reverse: $reverse) { nodes { ${shopifyFields.ORDER_SUMMARY_FIELDS} } ${shopifyFields.PAGE_INFO_FIELDS} } } }`,
+ variables: {
+ id,
+ first: shopifyValues.readFirst({ value: propsValue.first, max: MAX_PAGE_SIZE }),
+ after: shopifyValues.nonEmpty(propsValue.after),
+ query: shopifyValues.nonEmpty(propsValue.query),
+ sortKey: propsValue.sort_key,
+ reverse: propsValue.reverse ?? false,
+ },
+ });
+ if (!data.customer) {
+ throw new Error(`Customer ${id} was not found.`);
+ }
+ return {
+ customer_id: data.customer.id,
+ ...shopifyMappers.toPage({
+ connection: data.customer.orders,
+ map: shopifyMappers.mapOrderSummary,
+ redactedFields,
+ }),
+ };
+ },
+});
diff --git a/packages/pieces/community/shopify/src/lib/actions/ai/list-draft-orders.ts b/packages/pieces/community/shopify/src/lib/actions/ai/list-draft-orders.ts
new file mode 100644
index 00000000000..04436e62bf8
--- /dev/null
+++ b/packages/pieces/community/shopify/src/lib/actions/ai/list-draft-orders.ts
@@ -0,0 +1,73 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { shopifyAuth } from '../../..';
+import {
+ GqlConnection,
+ GqlDraftOrder,
+ shopifyFields,
+ shopifyGraphqlClient,
+ shopifyMappers,
+ shopifyProps,
+ shopifyValues,
+} from '../../common/graphql';
+import { listDraftOrdersOutputSchema } from '../../output-schemas/orders';
+
+const MAX_PAGE_SIZE = 60;
+
+export const shopifyAiListDraftOrders = createAction({
+ auth: shopifyAuth,
+ name: 'list_draft_orders',
+ classification: 'SEARCH',
+ displayName: 'List Draft Orders',
+ description: 'Search draft orders, one page at a time.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Searches draft orders with Shopify search syntax (for example "status:open" or "customer_id:207119551") and returns one page of draft summaries without line items; use get_draft_order for the full draft. Paged: pass end_cursor back as the cursor while has_next_page is true. Read-only.',
+ idempotent: true,
+ },
+ outputSchema: listDraftOrdersOutputSchema,
+ props: {
+ query: shopifyProps.searchQuery(
+ 'Shopify draft order search syntax, for example "status:open", "status:invoice_sent" or "tag:quote". Leave empty for all.'
+ ),
+ sort_key: Property.StaticDropdown({
+ displayName: 'Sort By',
+ description: 'Field to sort by. Defaults to the draft id.',
+ required: false,
+ options: {
+ options: [
+ { label: 'Updated at', value: 'UPDATED_AT' },
+ { label: 'Number', value: 'NUMBER' },
+ { label: 'Status', value: 'STATUS' },
+ { label: 'Total price', value: 'TOTAL_PRICE' },
+ { label: 'Customer name', value: 'CUSTOMER_NAME' },
+ { label: 'Relevance (with a query)', value: 'RELEVANCE' },
+ { label: 'ID', value: 'ID' },
+ ],
+ },
+ }),
+ reverse: shopifyProps.reverse(),
+ first: shopifyProps.first({ max: MAX_PAGE_SIZE }),
+ after: shopifyProps.after(),
+ },
+ async run({ auth, propsValue }) {
+ const { data, redactedFields } = await shopifyGraphqlClient.request<{
+ draftOrders: GqlConnection<GqlDraftOrder>;
+ }>({
+ auth,
+ query: `query ListDraftOrders($first: Int!, $after: String, $query: String, $sortKey: DraftOrderSortKeys, $reverse: Boolean) { draftOrders(first: $first, after: $after, query: $query, sortKey: $sortKey, reverse: $reverse) { nodes { ${shopifyFields.DRAFT_ORDER_SUMMARY_FIELDS} } ${shopifyFields.PAGE_INFO_FIELDS} } }`,
+ variables: {
+ first: shopifyValues.readFirst({ value: propsValue.first, max: MAX_PAGE_SIZE }),
+ after: shopifyValues.nonEmpty(propsValue.after),
+ query: shopifyValues.nonEmpty(propsValue.query),
+ sortKey: propsValue.sort_key,
+ reverse: propsValue.reverse ?? false,
+ },
+ });
+ return shopifyMappers.toPage({
+ connection: data.draftOrders,
+ map: shopifyMappers.mapDraftOrderSummary,
+ redactedFields,
+ });
+ },
+});
diff --git a/packages/pieces/community/shopify/src/lib/actions/ai/list-order-refunds.ts b/packages/pieces/community/shopify/src/lib/actions/ai/list-order-refunds.ts
new file mode 100644
index 00000000000..995dc2e5003
--- /dev/null
+++ b/packages/pieces/community/shopify/src/lib/actions/ai/list-order-refunds.ts
@@ -0,0 +1,55 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { shopifyAuth } from '../../..';
+import {
+ GqlRefund,
+ shopifyFields,
+ shopifyGraphqlClient,
+ shopifyMappers,
+} from '../../common/graphql';
+import { listOrderRefundsOutputSchema } from '../../output-schemas/orders';
+
+export const shopifyAiListOrderRefunds = createAction({
+ auth: shopifyAuth,
+ name: 'list_order_refunds',
+ classification: 'SEARCH',
+ displayName: 'List Order Refunds',
+ description: 'List every refund made on an order.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists the refunds of one order (up to 50) with the refunded amount, note and dates. Returns the list in one call (no paging); truncated=true means the order may have more than 50 refunds; use get_refund for the refunded line items and transactions of one refund. Read-only.',
+ idempotent: true,
+ },
+ outputSchema: listOrderRefundsOutputSchema,
+ props: {
+ order_id: Property.ShortText({
+ displayName: 'Order ID',
+ description: 'The order id, numeric or "gid://shopify/Order/…". Find it with search_orders.',
+ required: true,
+ }),
+ },
+ async run({ auth, propsValue }) {
+ const id = shopifyGraphqlClient.toGid({ type: 'Order', id: propsValue.order_id });
+ const { data, redactedFields } = await shopifyGraphqlClient.request<{
+ order: { id: string; refunds?: GqlRefund[] | null } | null;
+ }>({
+ auth,
+ query: `query ListOrderRefunds($id: ID!) { order(id: $id) { id refunds(first: ${REFUND_LIMIT}) { ${shopifyFields.REFUND_SUMMARY_FIELDS} } } }`,
+ variables: { id },
+ primaryPaths: ['order.refunds'],
+ });
+ if (!data.order) {
+ throw new Error(`Order ${id} was not found.`);
+ }
+ const items = (data.order.refunds ?? []).map(shopifyMappers.mapRefundSummary);
+ return {
+ order_id: data.order.id,
+ items,
+ count: items.length,
+ truncated: items.length === REFUND_LIMIT,
+ redacted_fields: redactedFields,
+ };
+ },
+});
+
+const REFUND_LIMIT = 50;
diff --git a/packages/pieces/community/shopify/src/lib/actions/ai/list-order-transactions.ts b/packages/pieces/community/shopify/src/lib/actions/ai/list-order-transactions.ts
new file mode 100644
index 00000000000..39c5601e4b4
--- /dev/null
+++ b/packages/pieces/community/shopify/src/lib/actions/ai/list-order-transactions.ts
@@ -0,0 +1,55 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { shopifyAuth } from '../../..';
+import {
+ GqlTransaction,
+ shopifyFields,
+ shopifyGraphqlClient,
+ shopifyMappers,
+} from '../../common/graphql';
+import { listOrderTransactionsOutputSchema } from '../../output-schemas/orders';
+
+export const shopifyAiListOrderTransactions = createAction({
+ auth: shopifyAuth,
+ name: 'list_order_transactions',
+ classification: 'SEARCH',
+ displayName: 'List Order Transactions',
+ description: 'List every payment transaction on an order.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists all payment transactions of one order (authorizations, captures, sales, refunds, voids) with amount, status, gateway and parent transaction. Use it to find the authorization id for capture_order_payment or void_order_transaction, or the parent id and gateway for create_refund. Returns up to 100 transactions in one call (no paging); truncated=true means the order may have more. Read-only.',
+ idempotent: true,
+ },
+ outputSchema: listOrderTransactionsOutputSchema,
+ props: {
+ order_id: Property.ShortText({
+ displayName: 'Order ID',
+ description: 'The order id, numeric or "gid://shopify/Order/…". Find it with search_orders.',
+ required: true,
+ }),
+ },
+ async run({ auth, propsValue }) {
+ const id = shopifyGraphqlClient.toGid({ type: 'Order', id: propsValue.order_id });
+ const { data, redactedFields } = await shopifyGraphqlClient.request<{
+ order: { id: string; transactions?: GqlTransaction[] | null } | null;
+ }>({
+ auth,
+ query: `query ListOrderTransactions($id: ID!) { order(id: $id) { id transactions(first: ${TRANSACTION_LIMIT}) { ${shopifyFields.TRANSACTION_FIELDS} } } }`,
+ variables: { id },
+ primaryPaths: ['order.transactions'],
+ });
+ if (!data.order) {
+ throw new Error(`Order ${id} was not found.`);
+ }
+ const items = (data.order.transactions ?? []).map(shopifyMappers.mapTransaction);
+ return {
+ order_id: data.order.id,
+ items,
+ count: items.length,
+ truncated: items.length === TRANSACTION_LIMIT,
+ redacted_fields: redactedFields,
+ };
+ },
+});
+
+const TRANSACTION_LIMIT = 100;
diff --git a/packages/pieces/community/shopify/src/lib/actions/ai/list-requested-order-edits.ts b/packages/pieces/community/shopify/src/lib/actions/ai/list-requested-order-edits.ts
new file mode 100644
index 00000000000..fd75b77d627
--- /dev/null
+++ b/packages/pieces/community/shopify/src/lib/actions/ai/list-requested-order-edits.ts
@@ -0,0 +1,76 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { shopifyAuth } from '../../..';
+import {
+ GqlConnection,
+ shopifyFields,
+ shopifyGraphqlClient,
+ shopifyMappers,
+ shopifyProps,
+ shopifyValues,
+} from '../../common/graphql';
+import {
+ GqlRequestedOrderEdit,
+ requestedOrderEditFields,
+ requestedOrderEditHelpers,
+} from '../../common/requested-order-edits';
+import { listRequestedOrderEditsOutputSchema } from '../../output-schemas/requested-order-edits';
+
+const MAX_PAGE_SIZE = 25;
+const FETCH_PAGE_SIZE = 10;
+
+export const shopifyAiListRequestedOrderEdits = createAction({
+ auth: shopifyAuth,
+ name: 'list_requested_order_edits',
+ classification: 'SEARCH',
+ displayName: 'List Requested Order Edits',
+ description: 'List the edits a buyer requested on an order, such as removing unfulfilled items.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists the buyer-requested order edits of one order, each with its id, status (REQUESTED = waiting for the merchant, RESOLVED, DECLINED), request, decline and resolve dates, and the line items the buyer asked to remove with quantities (up to 50 per edit, the most an edit can hold; removals_truncated tells when there are more). Also returns the order-level order_requested_edit_status (NONE, REQUESTED, RESOLVED, DECLINED). Use it to find the requested_order_edit_id for decline_requested_order_edit or resolve_requested_order_edit, and to check whether create_requested_order_edit already took effect before retrying it. Paged: pass end_cursor back as the cursor while has_next_page is true. Needs the read_orders access scope. Without the read_all_orders scope only orders from the last 60 days are visible. No customer contact fields are read, so protected customer data access is not needed. Read-only. Returns at most 10 edits per call, even when first is larger; pass end_cursor back as after while has_next_page is true.',
+ idempotent: true,
+ },
+ outputSchema: listRequestedOrderEditsOutputSchema,
+ props: {
+ order_id: Property.ShortText({
+ displayName: 'Order ID',
+ description: 'The order id, numeric or "gid://shopify/Order/…". Find it with search_orders.',
+ required: true,
+ }),
+ first: shopifyProps.first({ max: MAX_PAGE_SIZE }),
+ after: shopifyProps.after(),
+ },
+ async run({ auth, propsValue }) {
+ const id = requestedOrderEditHelpers.readTypedId({ type: 'Order', value: propsValue.order_id, label: 'order_id' });
+ const { data, redactedFields } = await shopifyGraphqlClient.request<{
+ order: {
+ id: string;
+ name?: string | null;
+ displayRequestedEditStatus?: string | null;
+ requestedOrderEdits?: GqlConnection<GqlRequestedOrderEdit> | null;
+ } | null;
+ }>({
+ auth,
+ query: `query ListRequestedOrderEdits($id: ID!, $first: Int!, $after: String) { order(id: $id) { id name displayRequestedEditStatus requestedOrderEdits(first: $first, after: $after) { nodes { ${requestedOrderEditFields.REQUESTED_ORDER_EDIT_FIELDS} } ${shopifyFields.PAGE_INFO_FIELDS} } } }`,
+ variables: {
+ id,
+ first: Math.min(shopifyValues.readFirst({ value: propsValue.first, max: MAX_PAGE_SIZE }), FETCH_PAGE_SIZE),
+ after: shopifyValues.nonEmpty(propsValue.after),
+ },
+ primaryPaths: ['order.requestedOrderEdits'],
+ });
+ if (!data.order) {
+ throw new Error(`Order ${id} was not found.`);
+ }
+ return {
+ order_id: data.order.id,
+ order_name: data.order.name ?? null,
+ order_requested_edit_status: data.order.displayRequestedEditStatus ?? null,
+ ...shopifyMappers.toPage({
+ connection: data.order.requestedOrderEdits,
+ map: requestedOrderEditHelpers.mapRequestedOrderEdit,
+ redactedFields,
+ }),
+ };
+ },
+});
diff --git a/packages/pieces/community/shopify/src/lib/actions/ai/list-tender-transactions.ts b/packages/pieces/community/shopify/src/lib/actions/ai/list-tender-transactions.ts
new file mode 100644
index 00000000000..c328c9b3fec
--- /dev/null
+++ b/packages/pieces/community/shopify/src/lib/actions/ai/list-tender-transactions.ts
@@ -0,0 +1,78 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { shopifyAuth } from '../../..';
+import {
+ GqlConnection,
+ GqlMoneyV2,
+ shopifyFields,
+ shopifyGraphqlClient,
+ shopifyMappers,
+ shopifyProps,
+ shopifyValues,
+} from '../../common/graphql';
+import { listTenderTransactionsOutputSchema } from '../../output-schemas/orders';
+
+const MAX_PAGE_SIZE = 200;
+
+export const shopifyAiListTenderTransactions = createAction({
+ auth: shopifyAuth,
+ name: 'list_tender_transactions',
+ classification: 'SEARCH',
+ displayName: 'List Tender Transactions',
+ description: 'List money actually received or paid out across all orders.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists tender transactions: the money actually received or refunded across the whole store, with amount, payment method, processed date and order. Use it for payout reconciliation or daily takings; use list_order_transactions for one order. Supports search syntax such as "processed_at:>=2026-09-01". Paged: pass end_cursor back as the cursor while has_next_page is true.',
+ idempotent: true,
+ },
+ outputSchema: listTenderTransactionsOutputSchema,
+ props: {
+ query: shopifyProps.searchQuery(
+ 'Shopify search syntax, for example "processed_at:>=2026-09-01" or "test:false". Leave empty for all.'
+ ),
+ reverse: shopifyProps.reverse(),
+ first: shopifyProps.first({ max: MAX_PAGE_SIZE }),
+ after: shopifyProps.after(),
+ },
+ async run({ auth, propsValue }) {
+ const { data, redactedFields } = await shopifyGraphqlClient.request<{
+ tenderTransactions: GqlConnection<GqlTenderTransaction>;
+ }>({
+ auth,
+ query: `query ListTenderTransactions($first: Int!, $after: String, $query: String, $reverse: Boolean) { tenderTransactions(first: $first, after: $after, query: $query, reverse: $reverse) { nodes { id amount { amount currencyCode } paymentMethod processedAt remoteReference test order { id name } transactionDetails { ... on TenderTransactionCreditCardDetails { creditCardCompany } } } ${shopifyFields.PAGE_INFO_FIELDS} } }`,
+ variables: {
+ first: shopifyValues.readFirst({ value: propsValue.first, max: MAX_PAGE_SIZE }),
+ after: shopifyValues.nonEmpty(propsValue.after),
+ query: shopifyValues.nonEmpty(propsValue.query),
+ reverse: propsValue.reverse ?? false,
+ },
+ });
+ return shopifyMappers.toPage({
+ connection: data.tenderTransactions,
+ map: (transaction: GqlTenderTransaction) => ({
+ id: transaction.id,
+ amount: transaction.amount?.amount ?? null,
+ currency_code: transaction.amount?.currencyCode ?? null,
+ payment_method: transaction.paymentMethod ?? null,
+ credit_card_company: transaction.transactionDetails?.creditCardCompany ?? null,
+ processed_at: transaction.processedAt ?? null,
+ remote_reference: transaction.remoteReference ?? null,
+ test: transaction.test ?? null,
+ order_id: transaction.order?.id ?? null,
+ order_name: transaction.order?.name ?? null,
+ }),
+ redactedFields,
+ });
+ },
+});
+
+type GqlTenderTransaction = {
+ id: string;
+ amount?: GqlMoneyV2 | null;
+ paymentMethod?: string | null;
+ processedAt?: string | null;
+ remoteReference?: string | null;
+ test?: boolean | null;
+ order?: { id?: string | null; name?: string | null } | null;
+ transactionDetails?: { creditCardCompany?: string | null } | null;
+};
diff --git a/packages/pieces/community/shopify/src/lib/actions/ai/mark-order-as-paid.ts b/packages/pieces/community/shopify/src/lib/actions/ai/mark-order-as-paid.ts
new file mode 100644
index 00000000000..fee11081a97
--- /dev/null
+++ b/packages/pieces/community/shopify/src/lib/actions/ai/mark-order-as-paid.ts
@@ -0,0 +1,50 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { shopifyAuth } from '../../..';
+import {
+ GqlOrder,
+ shopifyFields,
+ shopifyGraphqlClient,
+ shopifyMappers,
+} from '../../common/graphql';
+import { orderOutputSchema } from '../../output-schemas/orders';
+
+export const shopifyAiMarkOrderAsPaid = createAction({
+ auth: shopifyAuth,
+ name: 'mark_order_as_paid',
+ classification: 'WRITE',
+ displayName: 'Mark Order as Paid',
+ description: 'Record the outstanding balance of an order as paid manually.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Changes payment state: records a manual payment for the full outstanding balance of an order (for example cash, bank transfer or cheque received offline). No card is charged. Only works when the order can be marked as paid (see can_mark_as_paid on get_order); use capture_order_payment for card authorizations. Each call adds a payment record, so do not repeat it.',
+ idempotent: false,
+ },
+ outputSchema: orderOutputSchema,
+ props: {
+ order_id: Property.ShortText({
+ displayName: 'Order ID',
+ description: 'The order id, numeric or "gid://shopify/Order/…". Find it with search_orders.',
+ required: true,
+ }),
+ },
+ async run({ auth, propsValue }) {
+ const id = shopifyGraphqlClient.toGid({ type: 'Order', id: propsValue.order_id });
+ const { data, redactedFields } = await shopifyGraphqlClient.request<{
+ orderMarkAsPaid: { order: GqlOrder | null } | null;
+ }>({
+ auth,
+ query: `mutation MarkOrderAsPaid($input: OrderMarkAsPaidInput!) { orderMarkAsPaid(input: $input) { order { ${shopifyFields.ORDER_DETAIL_FIELDS} } userErrors { field message } } }`,
+ primaryPaths: ['orderMarkAsPaid.order'],
+ variables: { input: { id } },
+ });
+ const order = data.orderMarkAsPaid?.order;
+ if (!order) {
+ throw new Error(`Order ${id} was not returned by Shopify.`);
+ }
+ return {
+ ...shopifyMappers.mapOrderDetail(order),
+ redacted_fields: redactedFields,
+ };
+ },
+});
diff --git a/packages/pieces/community/shopify/src/lib/actions/ai/remove-tags.ts b/packages/pieces/community/shopify/src/lib/actions/ai/remove-tags.ts
new file mode 100644
index 00000000000..ad38d7c39bc
--- /dev/null
+++ b/packages/pieces/community/shopify/src/lib/actions/ai/remove-tags.ts
@@ -0,0 +1,72 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { shopifyAuth } from '../../..';
+import { shopifyGraphqlClient, shopifyValues } from '../../common/graphql';
+import { removeTagsOutputSchema } from '../../output-schemas/orders';
+
+export const shopifyAiRemoveTags = createAction({
+ auth: shopifyAuth,
+ name: 'remove_tags',
+ classification: 'WRITE',
+ displayName: 'Remove Tags',
+ description: 'Remove tags from an order, draft order, customer or product.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Removes one or more tags from an order, draft order, customer or product and keeps the others; prefer this over sending a full tag list to an update action. Removing a tag that is not present changes nothing, so repeating is safe. Returns the resulting tag list.',
+ idempotent: true,
+ },
+ outputSchema: removeTagsOutputSchema,
+ props: {
+ resource_type: Property.StaticDropdown({
+ displayName: 'Resource Type',
+ description: 'What kind of record the id belongs to. Used to build the full id when a numeric id is given.',
+ required: true,
+ options: {
+ options: [
+ { label: 'Order', value: 'Order' },
+ { label: 'Draft order', value: 'DraftOrder' },
+ { label: 'Customer', value: 'Customer' },
+ { label: 'Product', value: 'Product' },
+ ],
+ },
+ }),
+ resource_id: Property.ShortText({
+ displayName: 'Resource ID',
+ description: 'Numeric id such as "450789469" or a full id such as "gid://shopify/Order/450789469".',
+ required: true,
+ }),
+ tags: Property.Array({
+ displayName: 'Tags',
+ description: 'Tags to remove, for example ["follow-up"].',
+ required: true,
+ }),
+ },
+ async run({ auth, propsValue }) {
+ const tags = shopifyValues.readStringList(propsValue.tags) ?? [];
+ if (tags.length === 0) {
+ throw new Error('Provide at least one tag.');
+ }
+ const id = shopifyGraphqlClient.toGid({ type: propsValue.resource_type, id: propsValue.resource_id });
+ const { data, redactedFields } = await shopifyGraphqlClient.request<{
+ tagsRemove: { node: TaggedNode | null } | null;
+ }>({
+ auth,
+ query: `mutation RemoveTags($id: ID!, $tags: [String!]!) { tagsRemove(id: $id, tags: $tags) { node { id ${TAGGED_NODE_FRAGMENTS} } userErrors { field message } } }`,
+ variables: { id, tags },
+ });
+ return {
+ id: data.tagsRemove?.node?.id ?? id,
+ tags_removed: tags.join(', '),
+ tags: Array.isArray(data.tagsRemove?.node?.tags) ? data.tagsRemove?.node?.tags?.join(', ') ?? null : null,
+ redacted_fields: redactedFields,
+ };
+ },
+});
+
+const TAGGED_NODE_FRAGMENTS =
+ '... on Order { tags } ... on DraftOrder { tags } ... on Customer { tags } ... on Product { tags }';
+
+type TaggedNode = {
+ id: string;
+ tags?: string[] | null;
+};
diff --git a/packages/pieces/community/shopify/src/lib/actions/ai/resolve-requested-order-edit.ts b/packages/pieces/community/shopify/src/lib/actions/ai/resolve-requested-order-edit.ts
new file mode 100644
index 00000000000..96a4be24213
--- /dev/null
+++ b/packages/pieces/community/shopify/src/lib/actions/ai/resolve-requested-order-edit.ts
@@ -0,0 +1,57 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { shopifyAuth } from '../../..';
+import { shopifyGraphqlClient } from '../../common/graphql';
+import {
+ GqlRequestedOrderEdit,
+ requestedOrderEditFields,
+ requestedOrderEditHelpers,
+} from '../../common/requested-order-edits';
+import { requestedOrderEditOutputSchema } from '../../output-schemas/requested-order-edits';
+
+export const shopifyAiResolveRequestedOrderEdit = createAction({
+ auth: shopifyAuth,
+ name: 'resolve_requested_order_edit',
+ classification: 'WRITE',
+ displayName: 'Resolve Requested Order Edit',
+ description: 'Mark a buyer request to edit an order as completed.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Marks one pending (status REQUESTED) buyer-requested order edit as completed; the status becomes RESOLVED. Use it after the merchant has handled the request (for example removed the items in the Shopify admin). Get the requested_order_edit_id from list_requested_order_edits; use decline_requested_order_edit to refuse a request instead. Returns the edit with the resolved quantity per line item. Needs the write_orders access scope. Not idempotent: an edit that is already resolved or declined is rejected, so check its status with list_requested_order_edits before retrying.',
+ idempotent: false,
+ },
+ outputSchema: requestedOrderEditOutputSchema,
+ props: {
+ requested_order_edit_id: Property.ShortText({
+ displayName: 'Requested Order Edit ID',
+ description:
+ 'The requested order edit id, numeric or "gid://shopify/RequestedOrderEdit/…". Find it with list_requested_order_edits.',
+ required: true,
+ }),
+ },
+ async run({ auth, propsValue }) {
+ const id = requestedOrderEditHelpers.readTypedId({
+ type: 'RequestedOrderEdit',
+ value: propsValue.requested_order_edit_id,
+ label: 'requested_order_edit_id',
+ });
+ const { data, redactedFields } = await shopifyGraphqlClient.request<{
+ requestedOrderEditResolve: { requestedOrderEdit: GqlRequestedOrderEdit | null } | null;
+ }>({
+ auth,
+ query: `mutation ResolveRequestedOrderEdit($input: RequestedOrderEditResolveInput!) { requestedOrderEditResolve(input: $input) { requestedOrderEdit { ${requestedOrderEditFields.REQUESTED_ORDER_EDIT_FIELDS} } userErrors { field message code } } }`,
+ variables: { input: { id } },
+ primaryPaths: ['requestedOrderEditResolve.requestedOrderEdit'],
+ });
+ const edit = data.requestedOrderEditResolve?.requestedOrderEdit;
+ if (!edit) {
+ throw new Error(
+ `Shopify did not return requested order edit ${id}. Check its status with list_requested_order_edits before retrying.`
+ );
+ }
+ return {
+ ...requestedOrderEditHelpers.mapRequestedOrderEdit(edit),
+ redacted_fields: redactedFields,
+ };
+ },
+});
diff --git a/packages/pieces/community/shopify/src/lib/actions/ai/search-customers.ts b/packages/pieces/community/shopify/src/lib/actions/ai/search-customers.ts
new file mode 100644
index 00000000000..f7dc7d6a088
--- /dev/null
+++ b/packages/pieces/community/shopify/src/lib/actions/ai/search-customers.ts
@@ -0,0 +1,72 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { shopifyAuth } from '../../..';
+import {
+ GqlConnection,
+ GqlCustomer,
+ shopifyFields,
+ shopifyGraphqlClient,
+ shopifyMappers,
+ shopifyProps,
+ shopifyValues,
+} from '../../common/graphql';
+import { searchCustomersOutputSchema } from '../../output-schemas/orders';
+
+const MAX_PAGE_SIZE = 130;
+
+export const shopifyAiSearchCustomers = createAction({
+ auth: shopifyAuth,
+ name: 'search_customers',
+ classification: 'SEARCH',
+ displayName: 'Search Customers',
+ description: 'Search customers with Shopify search syntax, one page at a time.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Searches customers with Shopify search syntax (for example "email:[email protected]", "phone:+16135551111", "tag:vip" or a plain name) and returns one page of customer profiles. Use get_customer_profile when you already have the id. Paged: pass end_cursor back as the cursor while has_next_page is true. Contact fields may be null on stores without protected customer data access (see redacted_fields).',
+ idempotent: true,
+ },
+ outputSchema: searchCustomersOutputSchema,
+ props: {
+ query: shopifyProps.searchQuery(
+ 'Shopify customer search syntax, for example "email:[email protected]", "country:Canada" or "orders_count:>5". Leave empty to list all customers.'
+ ),
+ sort_key: Property.StaticDropdown({
+ displayName: 'Sort By',
+ description: 'Field to sort by. Defaults to the customer id.',
+ required: false,
+ options: {
+ options: [
+ { label: 'Created at', value: 'CREATED_AT' },
+ { label: 'Updated at', value: 'UPDATED_AT' },
+ { label: 'Name', value: 'NAME' },
+ { label: 'Location', value: 'LOCATION' },
+ { label: 'Relevance (with a query)', value: 'RELEVANCE' },
+ { label: 'ID', value: 'ID' },
+ ],
+ },
+ }),
+ reverse: shopifyProps.reverse(),
+ first: shopifyProps.first({ max: MAX_PAGE_SIZE }),
+ after: shopifyProps.after(),
+ },
+ async run({ auth, propsValue }) {
+ const { data, redactedFields } = await shopifyGraphqlClient.request<{
+ customers: GqlConnection<GqlCustomer>;
+ }>({
+ auth,
+ query: `query SearchCustomers($first: Int!, $after: String, $query: String, $sortKey: CustomerSortKeys, $reverse: Boolean) { customers(first: $first, after: $after, query: $query, sortKey: $sortKey, reverse: $reverse) { nodes { ${shopifyFields.CUSTOMER_FIELDS} } ${shopifyFields.PAGE_INFO_FIELDS} } }`,
+ variables: {
+ first: shopifyValues.readFirst({ value: propsValue.first, max: MAX_PAGE_SIZE }),
+ after: shopifyValues.nonEmpty(propsValue.after),
+ query: shopifyValues.nonEmpty(propsValue.query),
+ sortKey: propsValue.sort_key,
+ reverse: propsValue.reverse ?? false,
+ },
+ });
+ return shopifyMappers.toPage({
+ connection: data.customers,
+ map: shopifyMappers.mapCustomer,
+ redactedFields,
+ });
+ },
+});
diff --git a/packages/pieces/community/shopify/src/lib/actions/ai/search-orders.ts b/packages/pieces/community/shopify/src/lib/actions/ai/search-orders.ts
new file mode 100644
index 00000000000..c34e1996658
--- /dev/null
+++ b/packages/pieces/community/shopify/src/lib/actions/ai/search-orders.ts
@@ -0,0 +1,76 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { shopifyAuth } from '../../..';
+import {
+ GqlConnection,
+ GqlOrder,
+ shopifyFields,
+ shopifyGraphqlClient,
+ shopifyMappers,
+ shopifyProps,
+ shopifyValues,
+} from '../../common/graphql';
+import { searchOrdersOutputSchema } from '../../output-schemas/orders';
+
+const MAX_PAGE_SIZE = 40;
+
+export const shopifyAiSearchOrders = createAction({
+ auth: shopifyAuth,
+ name: 'search_orders',
+ classification: 'SEARCH',
+ displayName: 'Search Orders',
+ description: 'Search orders with Shopify search syntax, one page at a time.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Searches orders with Shopify search syntax (for example "financial_status:paid created_at:>=2026-01-01" or "email:[email protected]" or "name:#1001") and returns one page of order summaries without line items; use get_order for the full order. Paged: pass end_cursor back as the cursor while has_next_page is true. Without the read_all_orders scope only the last 60 days are visible.',
+ idempotent: true,
+ },
+ outputSchema: searchOrdersOutputSchema,
+ props: {
+ query: shopifyProps.searchQuery(
+ 'Shopify order search syntax, for example "status:open financial_status:paid", "tag:wholesale" or "created_at:>=2026-01-01". Leave empty to list all orders.'
+ ),
+ sort_key: Property.StaticDropdown({
+ displayName: 'Sort By',
+ description: 'Field to sort by. Defaults to the order id.',
+ required: false,
+ options: {
+ options: [
+ { label: 'Created at', value: 'CREATED_AT' },
+ { label: 'Processed at', value: 'PROCESSED_AT' },
+ { label: 'Updated at', value: 'UPDATED_AT' },
+ { label: 'Order number', value: 'ORDER_NUMBER' },
+ { label: 'Total price', value: 'TOTAL_PRICE' },
+ { label: 'Customer name', value: 'CUSTOMER_NAME' },
+ { label: 'Financial status', value: 'FINANCIAL_STATUS' },
+ { label: 'Fulfillment status', value: 'FULFILLMENT_STATUS' },
+ { label: 'Relevance (with a query)', value: 'RELEVANCE' },
+ { label: 'ID', value: 'ID' },
+ ],
+ },
+ }),
+ reverse: shopifyProps.reverse(),
+ first: shopifyProps.first({ max: MAX_PAGE_SIZE }),
+ after: shopifyProps.after(),
+ },
+ async run({ auth, propsValue }) {
+ const { data, redactedFields } = await shopifyGraphqlClient.request<{
+ orders: GqlConnection<GqlOrder>;
+ }>({
+ auth,
+ query: `query SearchOrders($first: Int!, $after: String, $query: String, $sortKey: OrderSortKeys, $reverse: Boolean) { orders(first: $first, after: $after, query: $query, sortKey: $sortKey, reverse: $reverse) { nodes { ${shopifyFields.ORDER_SUMMARY_FIELDS} } ${shopifyFields.PAGE_INFO_FIELDS} } }`,
+ variables: {
+ first: shopifyValues.readFirst({ value: propsValue.first, max: MAX_PAGE_SIZE }),
+ after: shopifyValues.nonEmpty(propsValue.after),
+ query: shopifyValues.nonEmpty(propsValue.query),
+ sortKey: propsValue.sort_key,
+ reverse: propsValue.reverse ?? false,
+ },
+ });
+ return shopifyMappers.toPage({
+ connection: data.orders,
+ map: shopifyMappers.mapOrderSummary,
+ redactedFields,
+ });
+ },
+});
diff --git a/packages/pieces/community/shopify/src/lib/actions/ai/send-customer-account-invite.ts b/packages/pieces/community/shopify/src/lib/actions/ai/send-customer-account-invite.ts
new file mode 100644
index 00000000000..31666f7bdfa
--- /dev/null
+++ b/packages/pieces/community/shopify/src/lib/actions/ai/send-customer-account-invite.ts
@@ -0,0 +1,61 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { shopifyAuth } from '../../..';
+import { shopifyGraphqlClient, shopifyValues } from '../../common/graphql';
+import { sendCustomerAccountInviteOutputSchema } from '../../output-schemas/orders';
+
+export const shopifyAiSendCustomerAccountInvite = createAction({
+ auth: shopifyAuth,
+ name: 'send_customer_account_invite',
+ classification: 'WRITE',
+ displayName: 'Send Customer Account Invite',
+ description: 'Email a customer an invitation to create their store account.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Emails one customer an invitation to activate their classic store account, optionally with a custom subject and message. Use generate_customer_activation_url to get a link without sending an email. Each call sends another email, so do not repeat it.',
+ idempotent: false,
+ },
+ outputSchema: sendCustomerAccountInviteOutputSchema,
+ props: {
+ customer_id: Property.ShortText({
+ displayName: 'Customer ID',
+ description: 'The customer id, numeric or "gid://shopify/Customer/…". Find it with search_customers.',
+ required: true,
+ }),
+ subject: Property.ShortText({
+ displayName: 'Subject',
+ description: 'Email subject. Leave empty for the store default.',
+ required: false,
+ }),
+ custom_message: Property.LongText({
+ displayName: 'Custom Message',
+ description: 'A personal message added to the invitation.',
+ required: false,
+ }),
+ },
+ async run({ auth, propsValue }) {
+ const customerId = shopifyGraphqlClient.toGid({ type: 'Customer', id: propsValue.customer_id });
+ const email = shopifyValues.compact({
+ subject: shopifyValues.nonEmpty(propsValue.subject),
+ customMessage: shopifyValues.nonEmpty(propsValue.custom_message),
+ });
+ const { data, redactedFields } = await shopifyGraphqlClient.request<{
+ customerSendAccountInviteEmail: {
+ customer: { id: string; state?: string | null } | null;
+ } | null;
+ }>({
+ auth,
+ query: `mutation SendCustomerAccountInvite($customerId: ID!, $email: EmailInput) { customerSendAccountInviteEmail(customerId: $customerId, email: $email) { customer { id state } userErrors { field message code } } }`,
+ variables: shopifyValues.compact({
+ customerId,
+ email: Object.keys(email).length > 0 ? email : undefined,
+ }),
+ });
+ const customer = data.customerSendAccountInviteEmail?.customer;
+ return {
+ customer_id: customer?.id ?? customerId,
+ state: customer?.state ?? null,
+ redacted_fields: redactedFields,
+ };
+ },
+});
diff --git a/packages/pieces/community/shopify/src/lib/actions/ai/send-draft-order-invoice.ts b/packages/pieces/community/shopify/src/lib/actions/ai/send-draft-order-invoice.ts
new file mode 100644
index 00000000000..ec5b7215cfa
--- /dev/null
+++ b/packages/pieces/community/shopify/src/lib/actions/ai/send-draft-order-invoice.ts
@@ -0,0 +1,74 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { shopifyAuth } from '../../..';
+import {
+ GqlDraftOrder,
+ shopifyFields,
+ shopifyGraphqlClient,
+ shopifyMappers,
+ shopifyValues,
+} from '../../common/graphql';
+import { draftOrderSummaryOutputSchema } from '../../output-schemas/orders';
+
+export const shopifyAiSendDraftOrderInvoice = createAction({
+ auth: shopifyAuth,
+ name: 'send_draft_order_invoice',
+ classification: 'WRITE',
+ displayName: 'Send Draft Order Invoice',
+ description: 'Email the checkout invoice of a draft order to the customer.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Sends an email with the draft order invoice and its checkout link so the customer can pay; the draft status becomes invoice sent. Goes to the draft email unless a recipient is given. Each call sends another email, so do not repeat it.',
+ idempotent: false,
+ },
+ outputSchema: draftOrderSummaryOutputSchema,
+ props: {
+ draft_order_id: Property.ShortText({
+ displayName: 'Draft Order ID',
+ description: 'The draft order id, numeric or "gid://shopify/DraftOrder/…". Find it with list_draft_orders.',
+ required: true,
+ }),
+ to: Property.ShortText({
+ displayName: 'Recipient Email',
+ description: 'Send to this address instead of the draft email, for example "[email protected]".',
+ required: false,
+ }),
+ subject: Property.ShortText({
+ displayName: 'Subject',
+ description: 'Email subject. Leave empty for the store default.',
+ required: false,
+ }),
+ custom_message: Property.LongText({
+ displayName: 'Custom Message',
+ description: 'A personal message added to the invoice email.',
+ required: false,
+ }),
+ },
+ async run({ auth, propsValue }) {
+ const id = shopifyGraphqlClient.toGid({ type: 'DraftOrder', id: propsValue.draft_order_id });
+ const email = shopifyValues.compact({
+ to: shopifyValues.nonEmpty(propsValue.to),
+ subject: shopifyValues.nonEmpty(propsValue.subject),
+ customMessage: shopifyValues.nonEmpty(propsValue.custom_message),
+ });
+ const { data, redactedFields } = await shopifyGraphqlClient.request<{
+ draftOrderInvoiceSend: { draftOrder: GqlDraftOrder | null } | null;
+ }>({
+ auth,
+ query: `mutation SendDraftOrderInvoice($id: ID!, $email: EmailInput) { draftOrderInvoiceSend(id: $id, email: $email) { draftOrder { ${shopifyFields.DRAFT_ORDER_SUMMARY_FIELDS} } userErrors { field message } } }`,
+ primaryPaths: ['draftOrderInvoiceSend.draftOrder'],
+ variables: shopifyValues.compact({
+ id,
+ email: Object.keys(email).length > 0 ? email : undefined,
+ }),
+ });
+ const draft = data.draftOrderInvoiceSend?.draftOrder;
+ if (!draft) {
+ throw new Error(`Draft order ${id} was not returned by Shopify.`);
+ }
+ return {
+ ...shopifyMappers.mapDraftOrderSummary(draft),
+ redacted_fields: redactedFields,
+ };
+ },
+});
diff --git a/packages/pieces/community/shopify/src/lib/actions/ai/send-payment-method-update-email.ts b/packages/pieces/community/shopify/src/lib/actions/ai/send-payment-method-update-email.ts
new file mode 100644
index 00000000000..2984ca40ef3
--- /dev/null
+++ b/packages/pieces/community/shopify/src/lib/actions/ai/send-payment-method-update-email.ts
@@ -0,0 +1,105 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { shopifyAuth } from '../../..';
+import { shopifyGraphqlClient, shopifyValues } from '../../common/graphql';
+import { sendPaymentMethodUpdateEmailOutputSchema } from '../../output-schemas/requested-order-edits';
+
+export const shopifyAiSendPaymentMethodUpdateEmail = createAction({
+ auth: shopifyAuth,
+ name: 'send_payment_method_update_email',
+ classification: 'WRITE',
+ displayName: 'Send Payment Method Update Email',
+ description:
+ 'Email a customer a secure link to add a new payment method for an order, draft order or subscription contract.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Emails the customer of one order, draft order or subscription contract a secure link to add a new payment method (for example a credit card) for that resource, such as after a payment method was revoked or a subscription needs payment details. Pick resource_type and pass the matching id: an order id from search_orders, a draft order id from list_draft_orders, or a subscription contract id from the subscription app. Only the sender address and bcc recipients can be set; subject and body are Shopify\'s. Returns the customer id, which may be null with the path in redacted_fields on stores without protected customer data access (the email is still sent). Needs the write_customers access scope plus read access to the resource (read_orders, read_draft_orders or read_own_subscription_contracts). Not idempotent: each call sends another email, so do not repeat it after a success.',
+ idempotent: false,
+ },
+ outputSchema: sendPaymentMethodUpdateEmailOutputSchema,
+ props: {
+ resource_type: Property.StaticDropdown({
+ displayName: 'Resource Type',
+ description: 'What the new payment method is for.',
+ required: true,
+ options: {
+ options: [
+ { label: 'Order', value: 'ORDERS' },
+ { label: 'Draft order', value: 'DRAFT_ORDERS' },
+ { label: 'Subscription contract', value: 'SUBSCRIPTIONS' },
+ ],
+ },
+ }),
+ resource_id: Property.ShortText({
+ displayName: 'Resource ID',
+ description:
+ 'The id of the order, draft order or subscription contract, numeric or a full id such as "gid://shopify/Order/450789469", "gid://shopify/DraftOrder/…" or "gid://shopify/SubscriptionContract/…". It must match the resource type; Shopify receives the number.',
+ required: true,
+ }),
+ from: Property.ShortText({
+ displayName: 'Sender Email',
+ description: 'Send from this address instead of the store default, for example "[email protected]".',
+ required: false,
+ }),
+ bcc: Property.Array({
+ displayName: 'BCC Recipients',
+ description: 'Email addresses that receive a blind copy, for example ["[email protected]"].',
+ required: false,
+ }),
+ },
+ async run({ auth, propsValue }) {
+ const resourceType = propsValue.resource_type;
+ const resourceId = toMandateResourceId({ resourceType, value: propsValue.resource_id });
+ const bcc = shopifyValues.readStringList(propsValue.bcc) ?? [];
+ const email = shopifyValues.compact({
+ from: shopifyValues.nonEmpty(propsValue.from),
+ bcc: bcc.length > 0 ? bcc : undefined,
+ });
+ const { data, redactedFields } = await shopifyGraphqlClient.request<{
+ paymentInstrumentSendAddEmail: { customer: { id: string } | null } | null;
+ }>({
+ auth,
+ query: `mutation SendPaymentMethodUpdateEmail($mandate: PaymentInstrumentMandateInput!, $email: EmailInput) { paymentInstrumentSendAddEmail(mandate: $mandate, email: $email) { customer { id } userErrors { field message } } }`,
+ variables: shopifyValues.compact({
+ mandate: { resourceType, resourceId },
+ email: Object.keys(email).length > 0 ? email : undefined,
+ }),
+ });
+ return {
+ customer_id: data.paymentInstrumentSendAddEmail?.customer?.id ?? null,
+ resource_type: resourceType,
+ resource_id: resourceId,
+ redacted_fields: redactedFields,
+ };
+ },
+});
+
+function toMandateResourceId({ resourceType, value }: { resourceType: string; value: string }): string {
+ const gidType = MANDATE_GID_TYPES[resourceType];
+ if (!gidType) {
+ throw new Error(`Unknown resource type "${resourceType}". Use ORDERS, DRAFT_ORDERS or SUBSCRIPTIONS. Nothing was sent.`);
+ }
+ const trimmed = value.trim();
+ if (trimmed.length === 0) {
+ throw new Error('Provide the resource id. Nothing was sent.');
+ }
+ const gid = shopifyGraphqlClient.toGid({ type: gidType, id: trimmed });
+ const match = gid.match(/^gid:\/\/shopify\/([A-Za-z]+)\/\d+$/);
+ if (!match) {
+ throw new Error(
+ `Resource id "${trimmed}" is not a numeric id or a full id such as "gid://shopify/${gidType}/123". Nothing was sent.`
+ );
+ }
+ if (match[1] !== gidType) {
+ throw new Error(
+ `Resource id "${trimmed}" is ${/^[AEIOU]/.test(match[1]) ? 'an' : 'a'} ${match[1]} id, but resource type ${resourceType} needs a ${gidType} id. Nothing was sent.`
+ );
+ }
+ return gid.slice(gid.lastIndexOf('/') + 1);
+}
+
+const MANDATE_GID_TYPES: Record<string, string> = {
+ ORDERS: 'Order',
+ DRAFT_ORDERS: 'DraftOrder',
+ SUBSCRIPTIONS: 'SubscriptionContract',
+};
diff --git a/packages/pieces/community/shopify/src/lib/actions/ai/set-default-customer-address.ts b/packages/pieces/community/shopify/src/lib/actions/ai/set-default-customer-address.ts
new file mode 100644
index 00000000000..e5cbb48a1db
--- /dev/null
+++ b/packages/pieces/community/shopify/src/lib/actions/ai/set-default-customer-address.ts
@@ -0,0 +1,64 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { shopifyAuth } from '../../..';
+import {
+ GqlMailingAddress,
+ shopifyFields,
+ shopifyGraphqlClient,
+ shopifyMappers,
+} from '../../common/graphql';
+import { customerAddressOutputSchema } from '../../output-schemas/orders';
+
+export const shopifyAiSetDefaultCustomerAddress = createAction({
+ auth: shopifyAuth,
+ name: 'set_default_customer_address',
+ classification: 'WRITE',
+ displayName: 'Set Default Customer Address',
+ description: "Make one of a customer's saved addresses the default.",
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ "Makes one saved address the customer's default address. Find the address id with list_customer_addresses. Setting the address that is already the default changes nothing, so repeating is safe.",
+ idempotent: true,
+ },
+ outputSchema: customerAddressOutputSchema,
+ props: {
+ customer_id: Property.ShortText({
+ displayName: 'Customer ID',
+ description: 'The customer id, numeric or "gid://shopify/Customer/…".',
+ required: true,
+ }),
+ address_id: Property.ShortText({
+ displayName: 'Address ID',
+ description:
+ 'The address id from list_customer_addresses, for example "gid://shopify/MailingAddress/1053318585?model_name=CustomerAddress" or its number.',
+ required: true,
+ }),
+ },
+ async run({ auth, propsValue }) {
+ const customerId = shopifyGraphqlClient.toGid({ type: 'Customer', id: propsValue.customer_id });
+ const addressId = shopifyGraphqlClient.toGid({
+ type: 'MailingAddress',
+ id: propsValue.address_id,
+ query: 'model_name=CustomerAddress',
+ });
+ const { data, redactedFields } = await shopifyGraphqlClient.request<{
+ customerUpdateDefaultAddress: {
+ customer: { id: string; defaultAddress?: GqlMailingAddress | null } | null;
+ } | null;
+ }>({
+ auth,
+ query: `mutation SetDefaultCustomerAddress($customerId: ID!, $addressId: ID!) { customerUpdateDefaultAddress(customerId: $customerId, addressId: $addressId) { customer { id defaultAddress { ${shopifyFields.ADDRESS_FIELDS} } } userErrors { field message } } }`,
+ primaryPaths: ['customerUpdateDefaultAddress.customer', 'customerUpdateDefaultAddress.customer.defaultAddress'],
+ variables: { customerId, addressId },
+ });
+ const customer = data.customerUpdateDefaultAddress?.customer;
+ if (!customer) {
+ throw new Error(`Customer ${customerId} was not returned by Shopify.`);
+ }
+ return {
+ customer_id: customer.id,
+ ...shopifyMappers.mapAddress(customer.defaultAddress),
+ redacted_fields: redactedFields,
+ };
+ },
+});
diff --git a/packages/pieces/community/shopify/src/lib/actions/ai/start-order-cancellation.ts b/packages/pieces/community/shopify/src/lib/actions/ai/start-order-cancellation.ts
new file mode 100644
index 00000000000..0bdc71b1f7a
--- /dev/null
+++ b/packages/pieces/community/shopify/src/lib/actions/ai/start-order-cancellation.ts
@@ -0,0 +1,122 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { shopifyAuth } from '../../..';
+import { shopifyGraphqlClient, shopifyValues } from '../../common/graphql';
+import { startOrderCancellationOutputSchema } from '../../output-schemas/orders';
+
+export const shopifyAiStartOrderCancellation = createAction({
+ auth: shopifyAuth,
+ name: 'start_order_cancellation',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Start Order Cancellation',
+ description: 'Cancel an order asynchronously and get a job to poll.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Starts the irreversible, asynchronous cancellation of one order and returns only a job id; poll get_job until done is true, then read the order with get_order. A reason is required. Stock is restocked only if restock is on, and money is refunded only if a refund method is chosen; authorized (uncaptured) payments are voided either way. The customer is notified only if notify_customer is on. Not safe to repeat.',
+ idempotent: false,
+ },
+ outputSchema: startOrderCancellationOutputSchema,
+ props: {
+ order_id: Property.ShortText({
+ displayName: 'Order ID',
+ description: 'The order id, numeric or "gid://shopify/Order/…". Find it with search_orders.',
+ required: true,
+ }),
+ reason: Property.StaticDropdown({
+ displayName: 'Reason',
+ description: 'Why the order is cancelled.',
+ required: true,
+ options: {
+ options: [
+ { label: 'Customer changed or cancelled the order', value: 'CUSTOMER' },
+ { label: 'Payment declined', value: 'DECLINED' },
+ { label: 'Fraudulent order', value: 'FRAUD' },
+ { label: 'Items unavailable', value: 'INVENTORY' },
+ { label: 'Staff error', value: 'STAFF' },
+ { label: 'Other', value: 'OTHER' },
+ ],
+ },
+ }),
+ restock: Property.Checkbox({
+ displayName: 'Restock Items',
+ description: 'Return the line items to inventory. Off by default.',
+ required: false,
+ defaultValue: false,
+ }),
+ refund_method: Property.StaticDropdown({
+ displayName: 'Refund Method',
+ description:
+ 'How to refund captured payments. Leave empty to cancel without refunding captured money (authorized payments are still voided).',
+ required: false,
+ options: {
+ options: [
+ { label: 'Refund to the original payment methods', value: 'ORIGINAL_PAYMENT_METHODS' },
+ { label: 'Refund as store credit', value: 'STORE_CREDIT' },
+ ],
+ },
+ }),
+ store_credit_expires_at: Property.DateTime({
+ displayName: 'Store Credit Expiry',
+ description: 'Only for a store credit refund: when the credit expires (ISO 8601). Leave empty for no expiry.',
+ required: false,
+ }),
+ notify_customer: Property.Checkbox({
+ displayName: 'Notify Customer',
+ description: 'Email the customer about the cancellation. Off by default.',
+ required: false,
+ defaultValue: false,
+ }),
+ staff_note: Property.ShortText({
+ displayName: 'Staff Note',
+ description: 'Internal note about the cancellation, not shown to the customer.',
+ required: false,
+ }),
+ },
+ async run({ auth, propsValue }) {
+ const orderId = shopifyGraphqlClient.toGid({ type: 'Order', id: propsValue.order_id });
+ const refundMethod = buildRefundMethod({
+ method: propsValue.refund_method,
+ expiresAt: shopifyValues.nonEmpty(propsValue.store_credit_expires_at),
+ });
+ const { data, redactedFields } = await shopifyGraphqlClient.request<{
+ orderCancel: { job: { id: string; done?: boolean | null } | null } | null;
+ }>({
+ auth,
+ query: `mutation StartOrderCancellation($orderId: ID!, $reason: OrderCancelReason!, $restock: Boolean!, $notifyCustomer: Boolean, $refundMethod: OrderCancelRefundMethodInput, $staffNote: String) { orderCancel(orderId: $orderId, reason: $reason, restock: $restock, notifyCustomer: $notifyCustomer, refundMethod: $refundMethod, staffNote: $staffNote) { job { id done } orderCancelUserErrors { field message code } } }`,
+ variables: shopifyValues.compact({
+ orderId,
+ reason: propsValue.reason,
+ restock: propsValue.restock ?? false,
+ notifyCustomer: propsValue.notify_customer ?? false,
+ refundMethod,
+ staffNote: shopifyValues.nonEmpty(propsValue.staff_note),
+ }),
+ });
+ const job = data.orderCancel?.job;
+ if (!job) {
+ throw new Error('Shopify did not return a cancellation job.');
+ }
+ return {
+ order_id: orderId,
+ job_id: job.id,
+ job_done: job.done ?? false,
+ redacted_fields: redactedFields,
+ };
+ },
+});
+
+function buildRefundMethod({
+ method,
+ expiresAt,
+}: {
+ method: string | undefined;
+ expiresAt: string | undefined;
+}): Record<string, unknown> | undefined {
+ if (method === 'ORIGINAL_PAYMENT_METHODS') {
+ return { originalPaymentMethodsRefund: true };
+ }
+ if (method === 'STORE_CREDIT') {
+ return { storeCreditRefund: shopifyValues.compact({ expiresAt }) };
+ }
+ return undefined;
+}
diff --git a/packages/pieces/community/shopify/src/lib/actions/ai/unarchive-order.ts b/packages/pieces/community/shopify/src/lib/actions/ai/unarchive-order.ts
new file mode 100644
index 00000000000..87643414efa
--- /dev/null
+++ b/packages/pieces/community/shopify/src/lib/actions/ai/unarchive-order.ts
@@ -0,0 +1,50 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { shopifyAuth } from '../../..';
+import {
+ GqlOrder,
+ shopifyFields,
+ shopifyGraphqlClient,
+ shopifyMappers,
+} from '../../common/graphql';
+import { orderSummaryOutputSchema } from '../../output-schemas/orders';
+
+export const shopifyAiUnarchiveOrder = createAction({
+ auth: shopifyAuth,
+ name: 'unarchive_order',
+ classification: 'WRITE',
+ displayName: 'Unarchive Order',
+ description: 'Reopen a closed (archived) order.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Reopens an order that was closed with archive_order so it shows as open again. It does not restore a cancelled order. Reopening an open order leaves it open, so repeating is safe.',
+ idempotent: true,
+ },
+ outputSchema: orderSummaryOutputSchema,
+ props: {
+ order_id: Property.ShortText({
+ displayName: 'Order ID',
+ description: 'The order id, numeric or "gid://shopify/Order/…". Find it with search_orders.',
+ required: true,
+ }),
+ },
+ async run({ auth, propsValue }) {
+ const id = shopifyGraphqlClient.toGid({ type: 'Order', id: propsValue.order_id });
+ const { data, redactedFields } = await shopifyGraphqlClient.request<{
+ orderOpen: { order: GqlOrder | null } | null;
+ }>({
+ auth,
+ query: `mutation UnarchiveOrder($input: OrderOpenInput!) { orderOpen(input: $input) { order { ${shopifyFields.ORDER_SUMMARY_FIELDS} } userErrors { field message } } }`,
+ primaryPaths: ['orderOpen.order'],
+ variables: { input: { id } },
+ });
+ const order = data.orderOpen?.order;
+ if (!order) {
+ throw new Error(`Order ${id} was not returned by Shopify.`);
+ }
+ return {
+ ...shopifyMappers.mapOrderSummary(order),
+ redacted_fields: redactedFields,
+ };
+ },
+});
diff --git a/packages/pieces/community/shopify/src/lib/actions/ai/update-customer-address.ts b/packages/pieces/community/shopify/src/lib/actions/ai/update-customer-address.ts
new file mode 100644
index 00000000000..28170936e74
--- /dev/null
+++ b/packages/pieces/community/shopify/src/lib/actions/ai/update-customer-address.ts
@@ -0,0 +1,100 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { shopifyAuth } from '../../..';
+import {
+ GqlMailingAddress,
+ shopifyFields,
+ shopifyGraphqlClient,
+ shopifyMappers,
+ shopifyProps,
+ shopifyValues,
+} from '../../common/graphql';
+import { customerAddressOutputSchema } from '../../output-schemas/orders';
+
+export const shopifyAiUpdateCustomerAddress = createAction({
+ auth: shopifyAuth,
+ name: 'update_customer_address',
+ classification: 'WRITE',
+ displayName: 'Update Customer Address',
+ description: 'Change fields of a saved customer address.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Changes one saved address of a customer and can make it the default. Only the address fields you fill in are sent; with no address fields and set_as_default = Yes it only makes the address the default. Find the address id with list_customer_addresses. Re-running with the same values is safe.',
+ idempotent: true,
+ },
+ outputSchema: customerAddressOutputSchema,
+ props: {
+ customer_id: Property.ShortText({
+ displayName: 'Customer ID',
+ description: 'The customer id, numeric or "gid://shopify/Customer/…".',
+ required: true,
+ }),
+ address_id: Property.ShortText({
+ displayName: 'Address ID',
+ description:
+ 'The address id from list_customer_addresses, for example "gid://shopify/MailingAddress/1053318585?model_name=CustomerAddress" or its number.',
+ required: true,
+ }),
+ ...shopifyProps.address(),
+ set_as_default: shopifyProps.booleanChoice({
+ displayName: 'Set as Default',
+ description: "Yes makes this the customer's default address. Leave empty to leave the default unchanged.",
+ }),
+ },
+ async run({ auth, propsValue }) {
+ const address = shopifyValues.buildMailingAddress(propsValue);
+ const setAsDefault = shopifyValues.toBooleanChoice(propsValue.set_as_default);
+ const hasAddressFields = Object.keys(address).length > 0;
+ if (!hasAddressFields && setAsDefault !== true) {
+ throw new Error(
+ setAsDefault === false
+ ? 'Shopify cannot unset a default address on its own. Make another address the default instead (set_as_default = Yes on that address), or provide address fields to update.'
+ : 'Provide at least one address field to update, or set as default.'
+ );
+ }
+ const customerId = shopifyGraphqlClient.toGid({ type: 'Customer', id: propsValue.customer_id });
+ const addressId = shopifyGraphqlClient.toGid({
+ type: 'MailingAddress',
+ id: propsValue.address_id,
+ query: 'model_name=CustomerAddress',
+ });
+ if (!hasAddressFields) {
+ const { data, redactedFields } = await shopifyGraphqlClient.request<{
+ customerUpdateDefaultAddress: {
+ customer: { id: string; defaultAddress?: GqlMailingAddress | null } | null;
+ } | null;
+ }>({
+ auth,
+ query: `mutation SetDefaultCustomerAddress($customerId: ID!, $addressId: ID!) { customerUpdateDefaultAddress(customerId: $customerId, addressId: $addressId) { customer { id defaultAddress { ${shopifyFields.ADDRESS_FIELDS} } } userErrors { field message } } }`,
+ primaryPaths: ['customerUpdateDefaultAddress.customer', 'customerUpdateDefaultAddress.customer.defaultAddress'],
+ variables: { customerId, addressId },
+ });
+ const defaultAddress = data.customerUpdateDefaultAddress?.customer?.defaultAddress;
+ if (!defaultAddress) {
+ throw new Error(`Address ${addressId} was not returned by Shopify as the default address.`);
+ }
+ return {
+ customer_id: customerId,
+ ...shopifyMappers.mapAddress(defaultAddress),
+ redacted_fields: redactedFields,
+ };
+ }
+ const { data, redactedFields } = await shopifyGraphqlClient.request<{
+ customerAddressUpdate: { address: GqlMailingAddress | null } | null;
+ }>({
+ auth,
+ query: `mutation UpdateCustomerAddress($customerId: ID!, $addressId: ID!, $address: MailingAddressInput!, $setAsDefault: Boolean) { customerAddressUpdate(customerId: $customerId, addressId: $addressId, address: $address, setAsDefault: $setAsDefault) { address { ${shopifyFields.ADDRESS_FIELDS} } userErrors { field message } } }`,
+ primaryPaths: ['customerAddressUpdate.address'],
+ variables: shopifyValues.compact({ customerId, addressId, address, setAsDefault }),
+ });
+ const updated = data.customerAddressUpdate?.address;
+ if (!updated) {
+ throw new Error(`Address ${addressId} was not returned by Shopify.`);
+ }
+ return {
+ customer_id: customerId,
+ ...shopifyMappers.mapAddress(updated),
+ redacted_fields: redactedFields,
+ };
+ },
+});
diff --git a/packages/pieces/community/shopify/src/lib/actions/ai/update-customer-profile.ts b/packages/pieces/community/shopify/src/lib/actions/ai/update-customer-profile.ts
new file mode 100644
index 00000000000..cfa16773c66
--- /dev/null
+++ b/packages/pieces/community/shopify/src/lib/actions/ai/update-customer-profile.ts
@@ -0,0 +1,117 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { shopifyAuth } from '../../..';
+import {
+ GqlCustomer,
+ shopifyFields,
+ shopifyGraphqlClient,
+ shopifyMappers,
+ shopifyProps,
+ shopifyValues,
+} from '../../common/graphql';
+import { customerOutputSchema } from '../../output-schemas/orders';
+
+export const shopifyAiUpdateCustomerProfile = createAction({
+ auth: shopifyAuth,
+ name: 'update_customer_profile',
+ classification: 'WRITE',
+ displayName: 'Update Customer',
+ description: 'Change the name, email, phone, note, tags, locale or tax exemption of a customer.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Changes one customer; fields left empty are not sent and keep their values, and marketing consent is never touched. Sending tags replaces all tags, so use add_tags or remove_tags for single tags. Addresses are changed with the customer address actions. Re-running with the same values is safe. To blank the note or remove every tag, set clear_note or clear_tags instead of sending an empty value.',
+ idempotent: true,
+ },
+ outputSchema: customerOutputSchema,
+ props: {
+ customer_id: Property.ShortText({
+ displayName: 'Customer ID',
+ description: 'The customer id, numeric or "gid://shopify/Customer/…". Find it with search_customers.',
+ required: true,
+ }),
+ email: Property.ShortText({
+ displayName: 'Email',
+ description: 'New email, for example "[email protected]".',
+ required: false,
+ }),
+ phone: Property.ShortText({
+ displayName: 'Phone',
+ description: 'New phone in E.164 format, for example "+16135551111".',
+ required: false,
+ }),
+ first_name: Property.ShortText({
+ displayName: 'First Name',
+ description: 'New first name.',
+ required: false,
+ }),
+ last_name: Property.ShortText({
+ displayName: 'Last Name',
+ description: 'New last name.',
+ required: false,
+ }),
+ note: Property.LongText({
+ displayName: 'Note',
+ description: 'New internal note. Replaces the existing note.',
+ required: false,
+ }),
+ tags: Property.Array({
+ displayName: 'Tags',
+ description: 'The complete new tag list. Replaces every existing tag; leave empty to keep the current tags (use clear_tags to remove all).',
+ required: false,
+ }),
+ locale: Property.ShortText({
+ displayName: 'Locale',
+ description: 'Language for customer emails, for example "en" or "fr-CA".',
+ required: false,
+ }),
+ tax_exempt: shopifyProps.booleanChoice({
+ displayName: 'Tax Exempt',
+ description: 'Set whether the customer is exempt from taxes. Leave empty to keep the current setting.',
+ }),
+ clear_note: Property.Checkbox({
+ displayName: 'Clear Note',
+ description: 'Remove the existing note. Leave note empty when using this.',
+ required: false,
+ defaultValue: false,
+ }),
+ clear_tags: Property.Checkbox({
+ displayName: 'Clear Tags',
+ description: 'Remove every tag. Leave tags empty when using this.',
+ required: false,
+ defaultValue: false,
+ }),
+ },
+ async run({ auth, propsValue }) {
+ const tags = shopifyValues.readStringList(propsValue.tags);
+ const patch = shopifyValues.compact({
+ email: shopifyValues.nonEmpty(propsValue.email),
+ phone: shopifyValues.nonEmpty(propsValue.phone),
+ firstName: shopifyValues.nonEmpty(propsValue.first_name),
+ lastName: shopifyValues.nonEmpty(propsValue.last_name),
+ note: shopifyValues.readClearable({ value: shopifyValues.nonEmpty(propsValue.note), clear: propsValue.clear_note, name: 'note', empty: '' }),
+ tags: shopifyValues.readClearable({ value: tags && tags.length > 0 ? tags : undefined, clear: propsValue.clear_tags, name: 'tags', empty: [] }),
+ locale: shopifyValues.nonEmpty(propsValue.locale),
+ taxExempt: shopifyValues.toBooleanChoice(propsValue.tax_exempt),
+ });
+ if (Object.keys(patch).length === 0) {
+ throw new Error('Provide at least one field to update.');
+ }
+ const id = shopifyGraphqlClient.toGid({ type: 'Customer', id: propsValue.customer_id });
+ const { data, redactedFields } = await shopifyGraphqlClient.request<{
+ customerUpdate: { customer: GqlCustomer | null } | null;
+ }>({
+ auth,
+ query: `mutation UpdateCustomerProfile($input: CustomerInput!) { customerUpdate(input: $input) { customer { ${shopifyFields.CUSTOMER_FIELDS} } userErrors { field message } } }`,
+ primaryPaths: ['customerUpdate.customer'],
+ variables: { input: { id, ...patch } },
+ });
+ const customer = data.customerUpdate?.customer;
+ if (!customer) {
+ throw new Error(`Customer ${id} was not returned by Shopify.`);
+ }
+ return {
+ ...shopifyMappers.mapCustomer(customer),
+ redacted_fields: redactedFields,
+ };
+ },
+});
diff --git a/packages/pieces/community/shopify/src/lib/actions/ai/update-draft-order.ts b/packages/pieces/community/shopify/src/lib/actions/ai/update-draft-order.ts
new file mode 100644
index 00000000000..32646ea247c
--- /dev/null
+++ b/packages/pieces/community/shopify/src/lib/actions/ai/update-draft-order.ts
@@ -0,0 +1,171 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { shopifyAuth } from '../../..';
+import {
+ GqlDraftOrder,
+ shopifyFields,
+ shopifyGraphqlClient,
+ shopifyMappers,
+ shopifyProps,
+ shopifyValues,
+} from '../../common/graphql';
+import { draftOrderOutputSchema } from '../../output-schemas/orders';
+
+export const shopifyAiUpdateDraftOrder = createAction({
+ auth: shopifyAuth,
+ name: 'update_draft_order',
+ classification: 'WRITE',
+ displayName: 'Update Draft Order',
+ description: 'Change the line items, customer, contact, tags or payment terms of a draft order.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Changes an open draft order; fields left empty are not sent and keep their values. Sending line items replaces all existing line items, and sending tags replaces all tags (use add_tags / remove_tags for single tags). Set payment terms here before complete_draft_order to leave the resulting order payment-pending. Re-running with the same values is safe. To blank the note or remove every tag, set clear_note or clear_tags instead of sending an empty value.',
+ idempotent: true,
+ },
+ outputSchema: draftOrderOutputSchema,
+ props: {
+ draft_order_id: Property.ShortText({
+ displayName: 'Draft Order ID',
+ description: 'The draft order id, numeric or "gid://shopify/DraftOrder/…". Find it with list_draft_orders.',
+ required: true,
+ }),
+ line_items: shopifyProps.draftLineItems({
+ required: false,
+ description:
+ 'The complete new list of line items. Replaces every existing line item; leave empty to keep the current items.',
+ }),
+ currency: Property.ShortText({
+ displayName: 'Currency',
+ description: 'Three-letter currency for the unit prices given in line items, for example "USD".',
+ required: false,
+ }),
+ customer_id: Property.ShortText({
+ displayName: 'Customer ID',
+ description: 'Customer the draft is for, numeric or "gid://shopify/Customer/…".',
+ required: false,
+ }),
+ email: Property.ShortText({
+ displayName: 'Email',
+ description: 'Email the invoice is sent to.',
+ required: false,
+ }),
+ phone: Property.ShortText({
+ displayName: 'Phone',
+ description: 'Contact phone in E.164 format.',
+ required: false,
+ }),
+ note: Property.LongText({
+ displayName: 'Note',
+ description: 'New internal note. Replaces the existing note.',
+ required: false,
+ }),
+ tags: Property.Array({
+ displayName: 'Tags',
+ description: 'The complete new tag list. Replaces every existing tag; leave empty to keep the current tags (use clear_tags to remove all).',
+ required: false,
+ }),
+ po_number: Property.ShortText({
+ displayName: 'PO Number',
+ description: 'Purchase order number.',
+ required: false,
+ }),
+ payment_terms_template_id: Property.ShortText({
+ displayName: 'Payment Terms Template ID',
+ description:
+ 'Payment terms to apply, as a full id such as "gid://shopify/PaymentTermsTemplate/4". With payment terms, completing the draft leaves the order payment-pending.',
+ required: false,
+ }),
+ payment_issued_at: Property.DateTime({
+ displayName: 'Payment Terms Issued At',
+ description: 'Start date for net payment terms (for example net 30), ISO 8601.',
+ required: false,
+ }),
+ payment_due_at: Property.DateTime({
+ displayName: 'Payment Due At',
+ description: 'Due date for fixed-date payment terms, ISO 8601.',
+ required: false,
+ }),
+ reserve_inventory_until: Property.DateTime({
+ displayName: 'Reserve Inventory Until',
+ description: 'Hold the stock for this draft until this time (ISO 8601).',
+ required: false,
+ }),
+ clear_note: Property.Checkbox({
+ displayName: 'Clear Note',
+ description: 'Remove the existing note. Leave note empty when using this.',
+ required: false,
+ defaultValue: false,
+ }),
+ clear_tags: Property.Checkbox({
+ displayName: 'Clear Tags',
+ description: 'Remove every tag. Leave tags empty when using this.',
+ required: false,
+ defaultValue: false,
+ }),
+ },
+ async run({ auth, propsValue }) {
+ const currency = shopifyValues.nonEmpty(propsValue.currency)?.toUpperCase();
+ const lineItems = shopifyValues.buildDraftLineItems({ value: propsValue.line_items, currency });
+ const tags = shopifyValues.readStringList(propsValue.tags);
+ const customerId = shopifyValues.nonEmpty(propsValue.customer_id);
+ const patch = shopifyValues.compact({
+ lineItems: lineItems.length > 0 ? lineItems : undefined,
+ purchasingEntity: customerId
+ ? { customerId: shopifyGraphqlClient.toGid({ type: 'Customer', id: customerId }) }
+ : undefined,
+ email: shopifyValues.nonEmpty(propsValue.email),
+ phone: shopifyValues.nonEmpty(propsValue.phone),
+ note: shopifyValues.readClearable({ value: shopifyValues.nonEmpty(propsValue.note), clear: propsValue.clear_note, name: 'note', empty: '' }),
+ tags: shopifyValues.readClearable({ value: tags && tags.length > 0 ? tags : undefined, clear: propsValue.clear_tags, name: 'tags', empty: [] }),
+ poNumber: shopifyValues.nonEmpty(propsValue.po_number),
+ paymentTerms: buildPaymentTerms({
+ templateId: shopifyValues.nonEmpty(propsValue.payment_terms_template_id),
+ issuedAt: shopifyValues.nonEmpty(propsValue.payment_issued_at),
+ dueAt: shopifyValues.nonEmpty(propsValue.payment_due_at),
+ }),
+ reserveInventoryUntil: shopifyValues.nonEmpty(propsValue.reserve_inventory_until),
+ });
+ if (Object.keys(patch).length === 0) {
+ throw new Error('Provide at least one field to update.');
+ }
+ const id = shopifyGraphqlClient.toGid({ type: 'DraftOrder', id: propsValue.draft_order_id });
+ const { data, redactedFields } = await shopifyGraphqlClient.request<{
+ draftOrderUpdate: { draftOrder: GqlDraftOrder | null } | null;
+ }>({
+ auth,
+ query: `mutation UpdateDraftOrder($id: ID!, $input: DraftOrderInput!) { draftOrderUpdate(id: $id, input: $input) { draftOrder { ${shopifyFields.DRAFT_ORDER_DETAIL_FIELDS} } userErrors { field message } } }`,
+ primaryPaths: ['draftOrderUpdate.draftOrder'],
+ variables: { id, input: patch },
+ });
+ const draft = data.draftOrderUpdate?.draftOrder;
+ if (!draft) {
+ throw new Error(`Draft order ${id} was not returned by Shopify.`);
+ }
+ return {
+ ...shopifyMappers.mapDraftOrderDetail(draft),
+ redacted_fields: redactedFields,
+ };
+ },
+});
+
+function buildPaymentTerms({
+ templateId,
+ issuedAt,
+ dueAt,
+}: {
+ templateId: string | undefined;
+ issuedAt: string | undefined;
+ dueAt: string | undefined;
+}): Record<string, unknown> | undefined {
+ if (!templateId) {
+ if (issuedAt || dueAt) {
+ throw new Error('Set "payment_terms_template_id" when giving payment dates.');
+ }
+ return undefined;
+ }
+ const schedule = shopifyValues.compact({ issuedAt, dueAt });
+ return shopifyValues.compact({
+ paymentTermsTemplateId: shopifyGraphqlClient.toGid({ type: 'PaymentTermsTemplate', id: templateId }),
+ paymentSchedules: Object.keys(schedule).length > 0 ? [schedule] : undefined,
+ });
+}
diff --git a/packages/pieces/community/shopify/src/lib/actions/ai/update-order-details.ts b/packages/pieces/community/shopify/src/lib/actions/ai/update-order-details.ts
new file mode 100644
index 00000000000..9e8a2591e97
--- /dev/null
+++ b/packages/pieces/community/shopify/src/lib/actions/ai/update-order-details.ts
@@ -0,0 +1,100 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { shopifyAuth } from '../../..';
+import {
+ GqlOrder,
+ shopifyFields,
+ shopifyGraphqlClient,
+ shopifyMappers,
+ shopifyValues,
+} from '../../common/graphql';
+import { orderOutputSchema } from '../../output-schemas/orders';
+
+export const shopifyAiUpdateOrderDetails = createAction({
+ auth: shopifyAuth,
+ name: 'update_order_details',
+ classification: 'WRITE',
+ displayName: 'Update Order Details',
+ description: 'Change the email, phone, note, tags or PO number of an order.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Changes the contact email, phone, internal note, PO number or tags of one order; fields left empty are not sent and keep their values. Sending tags replaces the whole tag list, so use add_tags or remove_tags to change single tags. Line items and payments cannot be changed here. Re-running with the same values is safe. To blank the note or remove every tag, set clear_note or clear_tags instead of sending an empty value.',
+ idempotent: true,
+ },
+ outputSchema: orderOutputSchema,
+ props: {
+ order_id: Property.ShortText({
+ displayName: 'Order ID',
+ description: 'The order id, numeric or "gid://shopify/Order/…". Find it with search_orders.',
+ required: true,
+ }),
+ email: Property.ShortText({
+ displayName: 'Email',
+ description: 'New contact email, for example "[email protected]".',
+ required: false,
+ }),
+ phone: Property.ShortText({
+ displayName: 'Phone',
+ description: 'New contact phone in E.164 format, for example "+16135551111".',
+ required: false,
+ }),
+ note: Property.LongText({
+ displayName: 'Note',
+ description: 'New internal note. Replaces the existing note.',
+ required: false,
+ }),
+ po_number: Property.ShortText({
+ displayName: 'PO Number',
+ description: 'Purchase order number, for example "PO-2026-114".',
+ required: false,
+ }),
+ tags: Property.Array({
+ displayName: 'Tags',
+ description:
+ 'The complete new tag list, for example ["wholesale", "priority"]. Replaces every existing tag; leave empty to keep the current tags (use clear_tags to remove all).',
+ required: false,
+ }),
+ clear_note: Property.Checkbox({
+ displayName: 'Clear Note',
+ description: 'Remove the existing note. Leave note empty when using this.',
+ required: false,
+ defaultValue: false,
+ }),
+ clear_tags: Property.Checkbox({
+ displayName: 'Clear Tags',
+ description: 'Remove every tag. Leave tags empty when using this.',
+ required: false,
+ defaultValue: false,
+ }),
+ },
+ async run({ auth, propsValue }) {
+ const tags = shopifyValues.readStringList(propsValue.tags);
+ const patch = shopifyValues.compact({
+ email: shopifyValues.nonEmpty(propsValue.email),
+ phone: shopifyValues.nonEmpty(propsValue.phone),
+ note: shopifyValues.readClearable({ value: shopifyValues.nonEmpty(propsValue.note), clear: propsValue.clear_note, name: 'note', empty: '' }),
+ poNumber: shopifyValues.nonEmpty(propsValue.po_number),
+ tags: shopifyValues.readClearable({ value: tags && tags.length > 0 ? tags : undefined, clear: propsValue.clear_tags, name: 'tags', empty: [] }),
+ });
+ if (Object.keys(patch).length === 0) {
+ throw new Error('Provide at least one field to update (email, phone, note, po_number or tags).');
+ }
+ const id = shopifyGraphqlClient.toGid({ type: 'Order', id: propsValue.order_id });
+ const { data, redactedFields } = await shopifyGraphqlClient.request<{
+ orderUpdate: { order: GqlOrder | null } | null;
+ }>({
+ auth,
+ query: `mutation UpdateOrderDetails($input: OrderInput!) { orderUpdate(input: $input) { order { ${shopifyFields.ORDER_DETAIL_FIELDS} } userErrors { field message } } }`,
+ primaryPaths: ['orderUpdate.order'],
+ variables: { input: { id, ...patch } },
+ });
+ const order = data.orderUpdate?.order;
+ if (!order) {
+ throw new Error(`Order ${id} was not returned by Shopify.`);
+ }
+ return {
+ ...shopifyMappers.mapOrderDetail(order),
+ redacted_fields: redactedFields,
+ };
+ },
+});
diff --git a/packages/pieces/community/shopify/src/lib/actions/ai/void-order-transaction.ts b/packages/pieces/community/shopify/src/lib/actions/ai/void-order-transaction.ts
new file mode 100644
index 00000000000..15769e32e19
--- /dev/null
+++ b/packages/pieces/community/shopify/src/lib/actions/ai/void-order-transaction.ts
@@ -0,0 +1,54 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { shopifyAuth } from '../../..';
+import {
+ GqlTransaction,
+ shopifyFields,
+ shopifyGraphqlClient,
+ shopifyMappers,
+} from '../../common/graphql';
+import { orderTransactionOutputSchema } from '../../output-schemas/orders';
+
+export const shopifyAiVoidOrderTransaction = createAction({
+ auth: shopifyAuth,
+ name: 'void_order_transaction',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Void Payment Authorization',
+ description: 'Void an uncaptured payment authorization on an order.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Changes payment state: voids an authorization that has not been captured, releasing the hold on the customer\'s card so it can no longer be captured. Needs the AUTHORIZATION transaction id from list_order_transactions. Use create_refund instead for money that was already captured. Cannot be undone; a repeat call fails.',
+ idempotent: false,
+ },
+ outputSchema: orderTransactionOutputSchema,
+ props: {
+ parent_transaction_id: Property.ShortText({
+ displayName: 'Authorization Transaction ID',
+ description:
+ 'The AUTHORIZATION transaction to void, numeric or "gid://shopify/OrderTransaction/…". Find it with list_order_transactions.',
+ required: true,
+ }),
+ },
+ async run({ auth, propsValue }) {
+ const parentTransactionId = shopifyGraphqlClient.toGid({
+ type: 'OrderTransaction',
+ id: propsValue.parent_transaction_id,
+ });
+ const { data, redactedFields } = await shopifyGraphqlClient.request<{
+ transactionVoid: { transaction: GqlTransaction | null } | null;
+ }>({
+ auth,
+ query: `mutation VoidOrderTransaction($parentTransactionId: ID!) { transactionVoid(parentTransactionId: $parentTransactionId) { transaction { ${shopifyFields.TRANSACTION_FIELDS} } userErrors { field message code } } }`,
+ primaryPaths: ['transactionVoid.transaction'],
+ variables: { parentTransactionId },
+ });
+ const transaction = data.transactionVoid?.transaction;
+ if (!transaction) {
+ throw new Error('Shopify did not return the void transaction.');
+ }
+ return {
+ ...shopifyMappers.mapTransaction(transaction),
+ redacted_fields: redactedFields,
+ };
+ },
+});
diff --git a/packages/pieces/community/shopify/src/lib/common/auth.ts b/packages/pieces/community/shopify/src/lib/common/auth.ts
index bcfbbd2d17d..676083016c2 100644
--- a/packages/pieces/community/shopify/src/lib/common/auth.ts
+++ b/packages/pieces/community/shopify/src/lib/common/auth.ts
@@ -44,6 +44,8 @@ Use this option for apps created in the Shopify **Dev Dashboard** (all new apps
const NO_APPROVED_SCOPES_ERROR =
'Your Shopify app has no approved Admin API scopes on this store. In the Dev Dashboard, release an app version that includes the scopes, then install/approve it on the store (reinstall if needed), and try again.';
+export const SHOPIFY_API_VERSION = '2026-10';
+
const SHOP_NAME_PATTERN = /^[a-zA-Z0-9][a-zA-Z0-9-]*$/;
const INVALID_SHOP_NAME_ERROR =
@@ -53,7 +55,7 @@ export function getBaseUrl(shopName: string) {
if (!isValidShopName(shopName)) {
throw new Error(INVALID_SHOP_NAME_ERROR);
}
- return `https://${shopName}.myshopify.com/admin/api/2023-10`;
+ return `https://${shopName}.myshopify.com/admin/api/${SHOPIFY_API_VERSION}`;
}
export const shopifyAdminTokenAuth = PieceAuth.CustomAuth({
diff --git a/packages/pieces/community/shopify/src/lib/common/graphql.ts b/packages/pieces/community/shopify/src/lib/common/graphql.ts
new file mode 100644
index 00000000000..d9faa696b45
--- /dev/null
+++ b/packages/pieces/community/shopify/src/lib/common/graphql.ts
@@ -0,0 +1,1563 @@
+import { randomUUID } from 'crypto';
+import {
+ HttpError,
+ HttpMethod,
+ httpClient,
+} from '@activepieces/pieces-common';
+import { Property, tryCatch } from '@activepieces/pieces-framework';
+import {
+ SHOPIFY_API_VERSION,
+ ShopifyAuth,
+ shopifyAuthHelpers,
+} from './auth';
+
+async function shopifyGraphql<TData>(
+ params: ShopifyGraphqlParams
+): Promise<ShopifyGraphqlResult<TData>> {
+ const { idempotencyKey } = params;
+ if (idempotencyKey === undefined) {
+ return sendGraphqlRequest<TData>(params);
+ }
+ const { data, error } = await tryCatch(() => sendGraphqlRequest<TData>(params));
+ if (error) {
+ const hint = error.message.startsWith(WITHHELD_RESULT_PREFIX)
+ ? `[idempotency_key used: ${idempotencyKey}.]`
+ : `[idempotency_key used: ${idempotencyKey}. Retry with this same idempotency_key so Shopify does not repeat the operation.]`;
+ throw new Error(`${error.message} ${hint}`);
+ }
+ return data;
+}
+
+async function sendGraphqlRequest<TData>({
+ auth,
+ query,
+ variables,
+ idempotencyKey,
+ primaryPaths,
+ toleratedUserErrorCodes,
+}: ShopifyGraphqlParams): Promise<ShopifyGraphqlResult<TData>> {
+ const requestVariables: Record<string, unknown> = { ...(variables ?? {}) };
+ if (idempotencyKey !== undefined) {
+ requestVariables['idempotencyKey'] = idempotencyKey;
+ }
+ const { data: response, error } = await tryCatch(() =>
+ httpClient.sendRequest<ShopifyGraphqlResponse<TData>>({
+ method: HttpMethod.POST,
+ url: `${shopifyAuthHelpers.getBaseUrl(auth)}/graphql.json`,
+ headers: {
+ ...shopifyAuthHelpers.getAuthHeaders(auth),
+ 'Content-Type': 'application/json',
+ },
+ body: { query, variables: requestVariables },
+ })
+ );
+ if (error) {
+ throw toHttpError(error);
+ }
+ const body = response.body;
+ const errors = Array.isArray(body?.errors) ? body.errors : [];
+ const throttled = errors.find(
+ (entry) => entry.extensions?.code === 'THROTTLED'
+ );
+ if (throttled) {
+ const throttleStatus = body?.extensions?.cost?.throttleStatus;
+ throw new Error(
+ `Shopify rate limit reached (THROTTLED). Wait a few seconds and retry. Throttle status: ${JSON.stringify(
+ throttleStatus ?? {}
+ )}`
+ );
+ }
+ const searchWarning = findSearchWarning(body?.extensions?.search ?? []);
+ if (searchWarning) {
+ throw new Error(
+ `Shopify ignored part of the search query "${searchWarning.query}" (${searchWarning.message}), so the result would cover every record. Use a filter this action supports, or a list or search action that supports it. Nothing was changed.`
+ );
+ }
+ const data = body?.data;
+ if (data === null || data === undefined) {
+ throw toGraphqlError(errors);
+ }
+ const withheld = findWithheldMutationResult({
+ query,
+ errors,
+ primaryPaths: primaryPaths ?? [],
+ });
+ if (withheld) {
+ throwOnUserErrors({ data, toleratedCodes: toleratedUserErrorCodes ?? [] });
+ throw toWithheldResultError(withheld);
+ }
+ const blocking = errors.filter(
+ (entry) => !isFieldRedaction({ entry, primaryPaths: primaryPaths ?? [] })
+ );
+ if (blocking.length > 0) {
+ throw toGraphqlError(blocking);
+ }
+ throwOnUserErrors({ data, toleratedCodes: toleratedUserErrorCodes ?? [] });
+ const redactedFields = errors.map((entry) =>
+ (entry.path ?? []).map((segment) => String(segment)).join('.')
+ );
+ return { data, redactedFields };
+}
+
+function findSearchWarning(
+ searches: ShopifySearchExtension[]
+): { query: string; message: string } | undefined {
+ for (const search of searches) {
+ const warning = (search.warnings ?? [])[0];
+ if (warning) {
+ return {
+ query: search.query ?? '',
+ message: `${warning.field ? `${warning.field}: ` : ''}${warning.message ?? 'unsupported filter'}`,
+ };
+ }
+ }
+ return undefined;
+}
+
+function isFieldRedaction({
+ entry,
+ primaryPaths,
+}: {
+ entry: ShopifyGraphqlError;
+ primaryPaths: string[];
+}): boolean {
+ const path = entry.path ?? [];
+ if (path.length < 2) {
+ return false;
+ }
+ if (isPrimaryPath({ path, primaryPaths })) {
+ return false;
+ }
+ const code = entry.extensions?.code;
+ if (code === 'ACCESS_DENIED') {
+ return true;
+ }
+ return isProtectedDataDenial(entry);
+}
+
+function isProtectedDataDenial(entry: ShopifyGraphqlError): boolean {
+ if (/protected customer data|not approved to access/i.test(entry.message ?? '')) {
+ return true;
+ }
+ return String(entry.extensions?.documentation ?? '').includes(
+ 'protected-customer-data'
+ );
+}
+
+function findWithheldMutationResult({
+ query,
+ errors,
+ primaryPaths,
+}: {
+ query: string;
+ errors: ShopifyGraphqlError[];
+ primaryPaths: string[];
+}): ShopifyGraphqlError | undefined {
+ if (!/^\s*mutation\b/.test(query)) {
+ return undefined;
+ }
+ return errors.find((entry) => {
+ const path = (entry.path ?? []).map((segment) => String(segment));
+ return (
+ path.length >= 2 &&
+ primaryPaths.includes(path.join('.')) &&
+ isProtectedDataDenial(entry)
+ );
+ });
+}
+
+const WITHHELD_RESULT_PREFIX = 'Shopify APPLIED this change';
+
+function toWithheldResultError(entry: ShopifyGraphqlError): Error {
+ const path = (entry.path ?? []).map((segment) => String(segment)).join('.');
+ return new Error(
+ `${WITHHELD_RESULT_PREFIX}, but withheld the returned record (${path}) because this app is not approved for protected customer data. Do not repeat the operation: it already took effect. To get the result back, grant the app protected customer data access (Partner Dashboard > App > API access > Protected customer data). Shopify said: ${entry.message ?? ''}`.trim()
+ );
+}
+
+function toProtectedDataError(entry: ShopifyGraphqlError): Error {
+ return new Error(
+ `Shopify withheld protected customer data: ${entry.message ?? ''} The app needs protected customer data access (Partner Dashboard > App > API access > Protected customer data, including the name, email, phone and address fields it reads). Adding Admin API scopes or reinstalling the app will not fix this.`
+ );
+}
+
+function isPrimaryPath({
+ path,
+ primaryPaths,
+}: {
+ path: (string | number)[];
+ primaryPaths: string[];
+}): boolean {
+ if (path.length === 2 && CONNECTION_LIST_FIELDS.includes(String(path[1]))) {
+ return true;
+ }
+ const joined = path.map((segment) => String(segment)).join('.');
+ return primaryPaths.some(
+ (primary) =>
+ joined === primary ||
+ CONNECTION_LIST_FIELDS.some((field) => joined === `${primary}.${field}`)
+ );
+}
+
+function toGraphqlError(errors: ShopifyGraphqlError[]): Error {
+ if (errors.length === 0) {
+ return new Error('Shopify returned no data and no error details.');
+ }
+ const protectedData = errors.find(isProtectedDataDenial);
+ if (protectedData) {
+ return toProtectedDataError(protectedData);
+ }
+ const denied = errors.find(
+ (entry) => entry.extensions?.code === 'ACCESS_DENIED'
+ );
+ if (denied) {
+ const scope = readRequiredScope(denied);
+ const scopeText = scope ? `the "${scope}" access scope` : 'an access scope';
+ return new Error(
+ `Shopify denied access: the app token is missing ${scopeText}. Add it to your custom app's Admin API scopes and reinstall the app, then paste the new token into the connection. Shopify said: ${denied.message ?? ''}`.trim()
+ );
+ }
+ const messages = errors.map((entry) => {
+ const path = (entry.path ?? []).join('.');
+ return path ? `${path}: ${entry.message ?? ''}` : entry.message ?? '';
+ });
+ return new Error(`Shopify GraphQL error: ${messages.join('; ')}`);
+}
+
+function readRequiredScope(entry: ShopifyGraphqlError): string | null {
+ const candidates = [entry.extensions?.requiredAccess, entry.message];
+ for (const candidate of candidates) {
+ if (typeof candidate !== 'string') {
+ continue;
+ }
+ const match = candidate.match(/`?([a-z_]+)`? access scope/i);
+ if (match) {
+ return match[1];
+ }
+ }
+ return null;
+}
+
+function throwOnUserErrors({
+ data,
+ toleratedCodes,
+}: {
+ data: unknown;
+ toleratedCodes: string[];
+}): void {
+ if (!isRecord(data)) {
+ return;
+ }
+ const problems: string[] = [];
+ for (const payload of Object.values(data)) {
+ if (!isRecord(payload)) {
+ continue;
+ }
+ for (const [key, value] of Object.entries(payload)) {
+ if (key !== 'userErrors' && !key.endsWith('UserErrors')) {
+ continue;
+ }
+ if (!Array.isArray(value)) {
+ continue;
+ }
+ for (const item of value) {
+ if (isRecord(item) && typeof item['code'] === 'string' && toleratedCodes.includes(item['code'])) {
+ continue;
+ }
+ problems.push(describeUserError(item));
+ }
+ }
+ }
+ if (problems.length > 0) {
+ throw new Error(`Shopify rejected the request: ${problems.join('; ')}`);
+ }
+}
+
+function describeUserError(item: unknown): string {
+ if (!isRecord(item)) {
+ return String(item);
+ }
+ const field = Array.isArray(item['field'])
+ ? item['field'].map((part: unknown) => String(part)).join('.')
+ : '';
+ const message =
+ typeof item['message'] === 'string' ? item['message'] : 'Unknown error';
+ const code = typeof item['code'] === 'string' ? ` (${item['code']})` : '';
+ return field ? `${field}: ${message}${code}` : `${message}${code}`;
+}
+
+function toHttpError(error: Error): Error {
+ if (!(error instanceof HttpError)) {
+ return error;
+ }
+ const status = error.response.status;
+ const detail = JSON.stringify(error.response.body ?? '');
+ if (status === 401) {
+ return new Error(
+ `Shopify returned 401: the Admin API access token is invalid or expired. Reconnect with a valid token. ${detail}`
+ );
+ }
+ if (status === 402) {
+ return new Error(
+ `Shopify returned 402: the shop is frozen or its plan does not allow this request. ${detail}`
+ );
+ }
+ if (status === 403) {
+ return new Error(
+ `Shopify returned 403: the app is not allowed to perform this request. Check the custom app's Admin API scopes and that it is still installed. ${detail}`
+ );
+ }
+ if (status === 404) {
+ return new Error(
+ `Shopify returned 404: the shop was not found. Check the shop name in the connection. ${detail}`
+ );
+ }
+ if (status === 423) {
+ return new Error(`Shopify returned 423: the shop is locked. ${detail}`);
+ }
+ if (status === 429) {
+ return new Error(
+ `Shopify returned 429: rate limit reached. Wait a few seconds and retry. ${detail}`
+ );
+ }
+ if (status >= 500) {
+ return new Error(
+ `Shopify returned ${status}: a Shopify server error. Retry later. ${detail}`
+ );
+ }
+ return new Error(`Shopify returned ${status}: ${detail}`);
+}
+
+function toGid({ type, id, query }: ToGidParams): string {
+ const value = String(id).trim();
+ if (value.startsWith('gid://')) {
+ return value;
+ }
+ if (/^\d+$/.test(value)) {
+ return `gid://shopify/${type}/${value}${query ? `?${query}` : ''}`;
+ }
+ return value;
+}
+
+function resolveIdempotencyKey(value: string | undefined | null): string {
+ const trimmed = (value ?? '').trim();
+ return trimmed.length > 0 ? trimmed : randomUUID();
+}
+
+function readFirst({
+ value,
+ max,
+}: {
+ value: number | undefined | null;
+ max: number;
+}): number {
+ if (value === undefined || value === null) {
+ return Math.min(50, max);
+ }
+ if (!Number.isInteger(value) || value < 1 || value > max) {
+ throw new Error(`Page size must be a whole number between 1 and ${max}.`);
+ }
+ return value;
+}
+
+function nonEmpty(value: string | undefined | null): string | undefined {
+ if (value === undefined || value === null) {
+ return undefined;
+ }
+ const trimmed = value.trim();
+ return trimmed.length > 0 ? trimmed : undefined;
+}
+
+function readStringList(value: unknown): string[] | undefined {
+ const list = readArray(value);
+ if (!list) {
+ return undefined;
+ }
+ return list
+ .map((item) => String(item ?? '').trim())
+ .filter((item) => item.length > 0);
+}
+
+function readRecords(value: unknown): Record<string, unknown>[] {
+ const list = readArray(value);
+ if (!list) {
+ return [];
+ }
+ return list.filter(isRecord);
+}
+
+function readArray(value: unknown): unknown[] | undefined {
+ if (Array.isArray(value)) {
+ return value;
+ }
+ if (typeof value !== 'string') {
+ return undefined;
+ }
+ const trimmed = value.trim();
+ if (!trimmed.startsWith('[')) {
+ return undefined;
+ }
+ try {
+ const parsed: unknown = JSON.parse(trimmed);
+ return Array.isArray(parsed) ? parsed : undefined;
+ } catch {
+ return undefined;
+ }
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
+}
+
+function readText(value: unknown): string | undefined {
+ if (value === undefined || value === null) {
+ return undefined;
+ }
+ const text = String(value).trim();
+ return text.length > 0 ? text : undefined;
+}
+
+function readNumber(value: unknown): number | undefined {
+ if (value === undefined || value === null || value === '') {
+ return undefined;
+ }
+ const parsed = Number(value);
+ return Number.isFinite(parsed) ? parsed : undefined;
+}
+
+function toBooleanChoice(value: unknown): boolean | undefined {
+ if (value === true || value === 'true') {
+ return true;
+ }
+ if (value === false || value === 'false') {
+ return false;
+ }
+ return undefined;
+}
+
+function readClearable<T>({
+ value,
+ clear,
+ name,
+ empty,
+}: {
+ value: T | undefined;
+ clear: boolean | undefined;
+ name: string;
+ empty: T;
+}): T | undefined {
+ if (!clear) {
+ return value;
+ }
+ if (value !== undefined) {
+ throw new Error(`Give either ${name} or clear_${name === 'body_html' ? 'body' : name}, not both. Nothing was changed.`);
+ }
+ return empty;
+}
+
+function compact(input: Record<string, unknown>): Record<string, unknown> {
+ const result: Record<string, unknown> = {};
+ for (const [key, value] of Object.entries(input)) {
+ if (value !== undefined) {
+ result[key] = value;
+ }
+ }
+ return result;
+}
+
+function money(bag: GqlMoneyBag | null | undefined): string | null {
+ return bag?.shopMoney?.amount ?? null;
+}
+
+function presentmentMoney(bag: GqlMoneyBag | null | undefined): string | null {
+ return bag?.presentmentMoney?.amount ?? null;
+}
+
+function presentmentCurrency(bag: GqlMoneyBag | null | undefined): string | null {
+ return bag?.presentmentMoney?.currencyCode ?? null;
+}
+
+function joinTags(tags: string[] | null | undefined): string | null {
+ return Array.isArray(tags) ? tags.join(', ') : null;
+}
+
+function toPage<TNode, TItem>({
+ connection,
+ map,
+ redactedFields,
+}: {
+ connection: GqlConnection<TNode> | null | undefined;
+ map: (node: TNode) => TItem;
+ redactedFields: string[];
+}): ShopifyPage<TItem> {
+ const items = (connection?.nodes ?? []).map(map);
+ return {
+ items,
+ count: items.length,
+ has_next_page: connection?.pageInfo?.hasNextPage ?? false,
+ end_cursor: connection?.pageInfo?.endCursor ?? null,
+ redacted_fields: redactedFields,
+ };
+}
+
+function mapAddress(address: GqlMailingAddress | null | undefined): FlatAddress {
+ return {
+ id: address?.id ?? null,
+ first_name: address?.firstName ?? null,
+ last_name: address?.lastName ?? null,
+ name: address?.name ?? null,
+ company: address?.company ?? null,
+ address1: address?.address1 ?? null,
+ address2: address?.address2 ?? null,
+ city: address?.city ?? null,
+ province: address?.province ?? null,
+ province_code: address?.provinceCode ?? null,
+ country: address?.country ?? null,
+ country_code: address?.countryCodeV2 ?? null,
+ zip: address?.zip ?? null,
+ phone: address?.phone ?? null,
+ };
+}
+
+function prefixAddress({
+ prefix,
+ address,
+}: {
+ prefix: string;
+ address: GqlMailingAddress | null | undefined;
+}): Record<string, string | null> {
+ const flat = mapAddress(address);
+ return {
+ [`${prefix}_name`]: flat.name,
+ [`${prefix}_company`]: flat.company,
+ [`${prefix}_address1`]: flat.address1,
+ [`${prefix}_address2`]: flat.address2,
+ [`${prefix}_city`]: flat.city,
+ [`${prefix}_province_code`]: flat.province_code,
+ [`${prefix}_country_code`]: flat.country_code,
+ [`${prefix}_zip`]: flat.zip,
+ [`${prefix}_phone`]: flat.phone,
+ };
+}
+
+function mapOrderSummary(order: GqlOrder) {
+ return {
+ id: order.id,
+ legacy_resource_id: order.legacyResourceId ?? null,
+ name: order.name ?? null,
+ created_at: order.createdAt ?? null,
+ updated_at: order.updatedAt ?? null,
+ processed_at: order.processedAt ?? null,
+ closed: order.closed ?? null,
+ closed_at: order.closedAt ?? null,
+ cancelled_at: order.cancelledAt ?? null,
+ cancel_reason: order.cancelReason ?? null,
+ financial_status: order.displayFinancialStatus ?? null,
+ fulfillment_status: order.displayFulfillmentStatus ?? null,
+ test: order.test ?? null,
+ email: order.email ?? null,
+ phone: order.phone ?? null,
+ note: order.note ?? null,
+ tags: joinTags(order.tags),
+ po_number: order.poNumber ?? null,
+ source_name: order.sourceName ?? null,
+ currency_code: order.currencyCode ?? null,
+ subtotal_price: money(order.subtotalPriceSet),
+ total_price: money(order.totalPriceSet),
+ total_tax: money(order.totalTaxSet),
+ total_discounts: money(order.totalDiscountsSet),
+ total_shipping: money(order.totalShippingPriceSet),
+ total_refunded: money(order.totalRefundedSet),
+ total_outstanding: money(order.totalOutstandingSet),
+ current_total_price: money(order.currentTotalPriceSet),
+ customer_id: order.customer?.id ?? null,
+ customer_name: order.customer?.displayName ?? null,
+ customer_email: order.customer?.defaultEmailAddress?.emailAddress ?? null,
+ };
+}
+
+function mapOrderDetail(order: GqlOrder) {
+ return {
+ ...mapOrderSummary(order),
+ number: order.number ?? null,
+ confirmed: order.confirmed ?? null,
+ capturable: order.capturable ?? null,
+ refundable: order.refundable ?? null,
+ fully_paid: order.fullyPaid ?? null,
+ unpaid: order.unpaid ?? null,
+ can_mark_as_paid: order.canMarkAsPaid ?? null,
+ fulfillments_count: order.fulfillmentsCount?.count ?? null,
+ transactions_count: order.transactionsCount?.count ?? null,
+ discount_codes: joinTags(order.discountCodes),
+ payment_gateway_names: joinTags(order.paymentGatewayNames),
+ shipping_line_title: order.shippingLine?.title ?? null,
+ shipping_line_price: money(order.shippingLine?.originalPriceSet),
+ ...prefixAddress({ prefix: 'shipping', address: order.shippingAddress }),
+ ...prefixAddress({ prefix: 'billing', address: order.billingAddress }),
+ line_items: (order.lineItems?.nodes ?? []).map((item) => ({
+ id: item.id,
+ name: item.name ?? null,
+ title: item.title ?? null,
+ sku: item.sku ?? null,
+ variant_title: item.variantTitle ?? null,
+ vendor: item.vendor ?? null,
+ quantity: item.quantity ?? null,
+ current_quantity: item.currentQuantity ?? null,
+ refundable_quantity: item.refundableQuantity ?? null,
+ unfulfilled_quantity: item.unfulfilledQuantity ?? null,
+ requires_shipping: item.requiresShipping ?? null,
+ taxable: item.taxable ?? null,
+ original_unit_price: money(item.originalUnitPriceSet),
+ discounted_total: money(item.discountedTotalSet),
+ variant_id: item.variant?.id ?? null,
+ product_id: item.product?.id ?? null,
+ })),
+ line_items_has_more: order.lineItems?.pageInfo?.hasNextPage ?? false,
+ };
+}
+
+function mapTransaction(transaction: GqlTransaction) {
+ return {
+ id: transaction.id,
+ kind: transaction.kind ?? null,
+ status: transaction.status ?? null,
+ gateway: transaction.gateway ?? null,
+ formatted_gateway: transaction.formattedGateway ?? null,
+ test: transaction.test ?? null,
+ amount: money(transaction.amountSet),
+ currency_code: transaction.amountSet?.shopMoney?.currencyCode ?? null,
+ total_unsettled: money(transaction.totalUnsettledSet),
+ maximum_refundable: transaction.maximumRefundableV2?.amount ?? null,
+ manually_capturable: transaction.manuallyCapturable ?? null,
+ multi_capturable: transaction.multiCapturable ?? null,
+ authorization_expires_at: transaction.authorizationExpiresAt ?? null,
+ error_code: transaction.errorCode ?? null,
+ payment_id: transaction.paymentId ?? null,
+ parent_transaction_id: transaction.parentTransaction?.id ?? null,
+ order_id: transaction.order?.id ?? null,
+ order_name: transaction.order?.name ?? null,
+ created_at: transaction.createdAt ?? null,
+ processed_at: transaction.processedAt ?? null,
+ };
+}
+
+function mapRefund(refund: GqlRefund) {
+ return {
+ id: refund.id,
+ legacy_resource_id: refund.legacyResourceId ?? null,
+ note: refund.note ?? null,
+ created_at: refund.createdAt ?? null,
+ processed_at: refund.processedAt ?? null,
+ updated_at: refund.updatedAt ?? null,
+ total_refunded: money(refund.totalRefundedSet),
+ currency_code: refund.totalRefundedSet?.shopMoney?.currencyCode ?? null,
+ order_id: refund.order?.id ?? null,
+ order_name: refund.order?.name ?? null,
+ refund_line_items: (refund.refundLineItems?.nodes ?? []).map((item) => ({
+ line_item_id: item.lineItem?.id ?? null,
+ title: item.lineItem?.title ?? null,
+ sku: item.lineItem?.sku ?? null,
+ quantity: item.quantity ?? null,
+ restock_type: item.restockType ?? null,
+ restocked: item.restocked ?? null,
+ subtotal: money(item.subtotalSet),
+ total_tax: money(item.totalTaxSet),
+ })),
+ transactions: (refund.transactions?.nodes ?? []).map((item) => ({
+ id: item.id,
+ kind: item.kind ?? null,
+ status: item.status ?? null,
+ gateway: item.gateway ?? null,
+ amount: money(item.amountSet),
+ })),
+ };
+}
+
+function mapRefundSummary(refund: GqlRefund) {
+ return {
+ id: refund.id,
+ legacy_resource_id: refund.legacyResourceId ?? null,
+ note: refund.note ?? null,
+ created_at: refund.createdAt ?? null,
+ processed_at: refund.processedAt ?? null,
+ updated_at: refund.updatedAt ?? null,
+ total_refunded: money(refund.totalRefundedSet),
+ currency_code: refund.totalRefundedSet?.shopMoney?.currencyCode ?? null,
+ };
+}
+
+function mapDraftOrderSummary(draft: GqlDraftOrder) {
+ return {
+ id: draft.id,
+ legacy_resource_id: draft.legacyResourceId ?? null,
+ name: draft.name ?? null,
+ status: draft.status ?? null,
+ created_at: draft.createdAt ?? null,
+ updated_at: draft.updatedAt ?? null,
+ completed_at: draft.completedAt ?? null,
+ invoice_url: draft.invoiceUrl ?? null,
+ invoice_sent_at: draft.invoiceSentAt ?? null,
+ email: draft.email ?? null,
+ phone: draft.phone ?? null,
+ note: draft.note2 ?? null,
+ tags: joinTags(draft.tags),
+ po_number: draft.poNumber ?? null,
+ ready: draft.ready ?? null,
+ currency_code: draft.currencyCode ?? null,
+ subtotal_price: money(draft.subtotalPriceSet),
+ total_price: money(draft.totalPriceSet),
+ total_tax: money(draft.totalTaxSet),
+ total_discounts: money(draft.totalDiscountsSet),
+ total_shipping: money(draft.totalShippingPriceSet),
+ customer_id: draft.customer?.id ?? null,
+ customer_name: draft.customer?.displayName ?? null,
+ order_id: draft.order?.id ?? null,
+ order_name: draft.order?.name ?? null,
+ };
+}
+
+function mapDraftOrderDetail(draft: GqlDraftOrder) {
+ return {
+ ...mapDraftOrderSummary(draft),
+ reserve_inventory_until: draft.reserveInventoryUntil ?? null,
+ tax_exempt: draft.taxExempt ?? null,
+ taxes_included: draft.taxesIncluded ?? null,
+ discount_codes: joinTags(draft.discountCodes),
+ applied_discount_title: draft.appliedDiscount?.title ?? null,
+ applied_discount_value: draft.appliedDiscount?.value ?? null,
+ applied_discount_value_type: draft.appliedDiscount?.valueType ?? null,
+ applied_discount_amount: money(draft.appliedDiscount?.amountSet),
+ payment_terms_id: draft.paymentTerms?.id ?? null,
+ payment_terms_name: draft.paymentTerms?.paymentTermsName ?? null,
+ payment_terms_type: draft.paymentTerms?.paymentTermsType ?? null,
+ payment_terms_due_in_days: draft.paymentTerms?.dueInDays ?? null,
+ shipping_line_title: draft.shippingLine?.title ?? null,
+ shipping_line_price: money(draft.shippingLine?.originalPriceSet),
+ ...prefixAddress({ prefix: 'shipping', address: draft.shippingAddress }),
+ line_items: (draft.lineItems?.nodes ?? []).map((item) => ({
+ id: item.id,
+ name: item.name ?? null,
+ title: item.title ?? null,
+ sku: item.sku ?? null,
+ quantity: item.quantity ?? null,
+ custom: item.custom ?? null,
+ original_unit_price: money(item.originalUnitPriceSet),
+ discounted_total: money(item.discountedTotalSet),
+ variant_id: item.variant?.id ?? null,
+ })),
+ line_items_has_more: draft.lineItems?.pageInfo?.hasNextPage ?? false,
+ };
+}
+
+function mapCustomer(customer: GqlCustomer) {
+ const email = customer.defaultEmailAddress;
+ const address = customer.defaultAddress;
+ return {
+ id: customer.id,
+ legacy_resource_id: customer.legacyResourceId ?? null,
+ display_name: customer.displayName ?? null,
+ first_name: customer.firstName ?? null,
+ last_name: customer.lastName ?? null,
+ email: email?.emailAddress ?? null,
+ email_marketing_state: email?.marketingState ?? null,
+ email_marketing_opt_in_level: email?.marketingOptInLevel ?? null,
+ email_marketing_updated_at: email?.marketingUpdatedAt ?? null,
+ phone: customer.defaultPhoneNumber?.phoneNumber ?? null,
+ note: customer.note ?? null,
+ tags: joinTags(customer.tags),
+ state: customer.state ?? null,
+ verified_email: customer.verifiedEmail ?? null,
+ tax_exempt: customer.taxExempt ?? null,
+ locale: customer.locale ?? null,
+ number_of_orders: customer.numberOfOrders ?? null,
+ amount_spent: customer.amountSpent?.amount ?? null,
+ amount_spent_currency: customer.amountSpent?.currencyCode ?? null,
+ can_delete: customer.canDelete ?? null,
+ last_order_id: customer.lastOrder?.id ?? null,
+ last_order_name: customer.lastOrder?.name ?? null,
+ default_address_id: address?.id ?? null,
+ ...prefixAddress({ prefix: 'default_address', address }),
+ created_at: customer.createdAt ?? null,
+ updated_at: customer.updatedAt ?? null,
+ };
+}
+
+function mapAbandonedCheckout(checkout: GqlAbandonedCheckout) {
+ return {
+ id: checkout.id,
+ name: checkout.name ?? null,
+ created_at: checkout.createdAt ?? null,
+ updated_at: checkout.updatedAt ?? null,
+ completed_at: checkout.completedAt ?? null,
+ recovery_url: checkout.abandonedCheckoutUrl ?? null,
+ note: checkout.note ?? null,
+ discount_codes: joinTags(checkout.discountCodes),
+ taxes_included: checkout.taxesIncluded ?? null,
+ currency_code: checkout.totalPriceSet?.shopMoney?.currencyCode ?? null,
+ subtotal_price: money(checkout.subtotalPriceSet),
+ total_price: money(checkout.totalPriceSet),
+ customer_id: checkout.customer?.id ?? null,
+ customer_name: checkout.customer?.displayName ?? null,
+ customer_email: checkout.customer?.defaultEmailAddress?.emailAddress ?? null,
+ shipping_country_code: checkout.shippingAddress?.countryCodeV2 ?? null,
+ };
+}
+
+function mapAbandonment(abandonment: GqlAbandonment | null) {
+ return {
+ id: abandonment?.id ?? null,
+ abandonment_type: abandonment?.abandonmentType ?? null,
+ most_recent_step: abandonment?.mostRecentStep ?? null,
+ created_at: abandonment?.createdAt ?? null,
+ email_state: abandonment?.emailState ?? null,
+ email_sent_at: abandonment?.emailSentAt ?? null,
+ cart_url: abandonment?.cartUrl ?? null,
+ inventory_available: abandonment?.inventoryAvailable ?? null,
+ is_from_online_store: abandonment?.isFromOnlineStore ?? null,
+ customer_has_no_order_since_abandonment:
+ abandonment?.customerHasNoOrderSinceAbandonment ?? null,
+ last_checkout_abandonment_date: abandonment?.lastCheckoutAbandonmentDate ?? null,
+ customer_id: abandonment?.customer?.id ?? null,
+ customer_name: abandonment?.customer?.displayName ?? null,
+ customer_email: abandonment?.customer?.defaultEmailAddress?.emailAddress ?? null,
+ abandoned_checkout_id: abandonment?.abandonedCheckoutPayload?.id ?? null,
+ abandoned_checkout_name: abandonment?.abandonedCheckoutPayload?.name ?? null,
+ abandoned_checkout_url:
+ abandonment?.abandonedCheckoutPayload?.abandonedCheckoutUrl ?? null,
+ abandoned_checkout_total_price: money(
+ abandonment?.abandonedCheckoutPayload?.totalPriceSet
+ ),
+ };
+}
+
+function buildMailingAddress(props: AddressProps): Record<string, unknown> {
+ return compact({
+ firstName: nonEmpty(props.first_name),
+ lastName: nonEmpty(props.last_name),
+ company: nonEmpty(props.company),
+ address1: nonEmpty(props.address1),
+ address2: nonEmpty(props.address2),
+ city: nonEmpty(props.city),
+ provinceCode: nonEmpty(props.province_code),
+ countryCode: nonEmpty(props.country_code)?.toUpperCase(),
+ zip: nonEmpty(props.zip),
+ phone: nonEmpty(props.phone),
+ });
+}
+
+function addressProps() {
+ return {
+ first_name: Property.ShortText({
+ displayName: 'First Name',
+ description: 'First name on the address.',
+ required: false,
+ }),
+ last_name: Property.ShortText({
+ displayName: 'Last Name',
+ description: 'Last name on the address.',
+ required: false,
+ }),
+ company: Property.ShortText({
+ displayName: 'Company',
+ description: 'Company name on the address.',
+ required: false,
+ }),
+ address1: Property.ShortText({
+ displayName: 'Address Line 1',
+ description: 'Street address, for example "150 Elgin Street".',
+ required: false,
+ }),
+ address2: Property.ShortText({
+ displayName: 'Address Line 2',
+ description: 'Apartment, suite or unit, for example "Suite 800".',
+ required: false,
+ }),
+ city: Property.ShortText({
+ displayName: 'City',
+ description: 'City, for example "Ottawa".',
+ required: false,
+ }),
+ province_code: Property.ShortText({
+ displayName: 'Province / State Code',
+ description: 'Region code, for example "ON" or "CA".',
+ required: false,
+ }),
+ country_code: Property.ShortText({
+ displayName: 'Country Code',
+ description: 'Two-letter ISO country code, for example "CA" or "US".',
+ required: false,
+ }),
+ zip: Property.ShortText({
+ displayName: 'Postal Code',
+ description: 'Postal or ZIP code, for example "K2P 1L4".',
+ required: false,
+ }),
+ phone: Property.ShortText({
+ displayName: 'Phone',
+ description: 'Phone number in E.164 format, for example "+16135551111".',
+ required: false,
+ }),
+ };
+}
+
+function buildRefundLineItems(value: unknown): Record<string, unknown>[] | undefined {
+ const items = readRecords(value).map((item) => {
+ const lineItemId = readText(item['line_item_id']);
+ const quantity = readNumber(item['quantity']);
+ if (!lineItemId || quantity === undefined) {
+ throw new Error('Every refund line item needs a line_item_id and a quantity.');
+ }
+ const locationId = readText(item['location_id']);
+ return compact({
+ lineItemId: toGid({ type: 'LineItem', id: lineItemId }),
+ quantity,
+ restockType: readText(item['restock_type']) ?? 'NO_RESTOCK',
+ locationId: locationId ? toGid({ type: 'Location', id: locationId }) : undefined,
+ });
+ });
+ return items.length > 0 ? items : undefined;
+}
+
+function refundLineItemsProp() {
+ return Property.Array({
+ displayName: 'Line Items to Refund',
+ description: 'Line items and quantities to refund. Line item ids come from get_order.',
+ required: false,
+ properties: {
+ line_item_id: Property.ShortText({
+ displayName: 'Line Item ID',
+ description: 'Line item id, numeric or "gid://shopify/LineItem/…".',
+ required: true,
+ }),
+ quantity: Property.Number({
+ displayName: 'Quantity',
+ description: 'How many units of this line item to refund.',
+ required: true,
+ }),
+ restock_type: Property.StaticDropdown({
+ displayName: 'Restock Type',
+ description: 'What happens to the stock. Defaults to no restock.',
+ required: false,
+ options: {
+ options: [
+ { label: 'No restock', value: 'NO_RESTOCK' },
+ { label: 'Return (item was delivered and returned)', value: 'RETURN' },
+ { label: 'Cancel (item was not shipped)', value: 'CANCEL' },
+ ],
+ },
+ }),
+ location_id: Property.ShortText({
+ displayName: 'Restock Location ID',
+ description: 'Location to restock at, numeric or "gid://shopify/Location/…". Only used when restocking.',
+ required: false,
+ }),
+ },
+ });
+}
+
+function buildDraftLineItems({
+ value,
+ currency,
+}: {
+ value: unknown;
+ currency: string | undefined;
+}): Record<string, unknown>[] {
+ return readRecords(value).map((item) => {
+ const variantId = readText(item['variant_id']);
+ const title = readText(item['title']);
+ const quantity = readNumber(item['quantity']);
+ const price = readNumber(item['price']);
+ if (quantity === undefined || quantity < 1) {
+ throw new Error('Every line item needs a quantity of at least 1.');
+ }
+ if (!variantId && (!title || price === undefined)) {
+ throw new Error('Every line item needs a variant_id, or a title and a price for a custom item.');
+ }
+ if (price !== undefined && !currency) {
+ throw new Error('Set "currency" (for example "USD") when giving a unit price.');
+ }
+ const unitPrice =
+ price !== undefined && currency ? { amount: String(price), currencyCode: currency } : undefined;
+ if (variantId) {
+ return compact({
+ variantId: toGid({ type: 'ProductVariant', id: variantId }),
+ quantity,
+ priceOverride: unitPrice,
+ });
+ }
+ return compact({
+ title,
+ quantity,
+ sku: readText(item['sku']),
+ originalUnitPriceWithCurrency: unitPrice,
+ });
+ });
+}
+
+function draftLineItemsProp({
+ required,
+ description,
+}: {
+ required: boolean;
+ description: string;
+}) {
+ return Property.Array({
+ displayName: 'Line Items',
+ description,
+ required,
+ properties: {
+ variant_id: Property.ShortText({
+ displayName: 'Variant ID',
+ description: 'Product variant id, for example "39072856" or "gid://shopify/ProductVariant/39072856".',
+ required: false,
+ }),
+ title: Property.ShortText({
+ displayName: 'Title',
+ description: 'Title of a custom item (no variant), for example "Custom engraving".',
+ required: false,
+ }),
+ quantity: Property.Number({
+ displayName: 'Quantity',
+ description: 'How many units, at least 1.',
+ required: true,
+ }),
+ price: Property.Number({
+ displayName: 'Unit Price',
+ description: 'Unit price in the draft currency, for example 19.99. Required for custom items. On a variant line it replaces the catalog price for this draft only (sent as a price override); leave empty to use the variant price.',
+ required: false,
+ }),
+ sku: Property.ShortText({
+ displayName: 'SKU',
+ description: 'Optional SKU for a custom item.',
+ required: false,
+ }),
+ },
+ });
+}
+
+function firstProp({ max }: { max: number }) {
+ return Property.Number({
+ displayName: 'Page Size',
+ description: `How many records to return, 1 to ${max}. Defaults to ${Math.min(50, max)}.`,
+ required: false,
+ defaultValue: Math.min(50, max),
+ });
+}
+
+function afterProp() {
+ return Property.ShortText({
+ displayName: 'Cursor',
+ description:
+ 'The end_cursor from the previous page. Leave empty for the first page; pass it only while has_next_page is true.',
+ required: false,
+ });
+}
+
+function reverseProp() {
+ return Property.Checkbox({
+ displayName: 'Reverse Order',
+ description: 'Return results in reverse sort order (for example newest first).',
+ required: false,
+ defaultValue: false,
+ });
+}
+
+function searchQueryProp(description: string) {
+ return Property.ShortText({
+ displayName: 'Search Query',
+ description,
+ required: false,
+ });
+}
+
+function booleanChoiceProp({
+ displayName,
+ description,
+}: {
+ displayName: string;
+ description: string;
+}) {
+ return Property.StaticDropdown({
+ displayName,
+ description,
+ required: false,
+ options: {
+ options: [
+ { label: 'Yes', value: 'true' },
+ { label: 'No', value: 'false' },
+ ],
+ },
+ });
+}
+
+function idempotencyKeyProp() {
+ return Property.ShortText({
+ displayName: 'Idempotency Key',
+ description:
+ 'A unique key for this operation, for example a UUID such as "3f1c2a9e-6b1d-4c8e-9a51-2f7d0e4b8c10". Generate your own key on the first call and pass the same key again when retrying after a timeout or error, so Shopify does not repeat the operation. If left empty a key is generated; it is returned as idempotency_key and included in any error message.',
+ required: false,
+ });
+}
+
+const MONEY_FIELDS = 'shopMoney { amount currencyCode }';
+
+const MONEY_WITH_PRESENTMENT_FIELDS =
+ 'shopMoney { amount currencyCode } presentmentMoney { amount currencyCode }';
+
+const CONNECTION_LIST_FIELDS = ['nodes', 'edges'];
+
+const ADDRESS_FIELDS =
+ 'id firstName lastName name company address1 address2 city province provinceCode country countryCodeV2 zip phone';
+
+const ORDER_SUMMARY_FIELDS = `id legacyResourceId name createdAt updatedAt processedAt closed closedAt cancelledAt cancelReason displayFinancialStatus displayFulfillmentStatus test email phone note tags poNumber sourceName currencyCode subtotalPriceSet { ${MONEY_FIELDS} } totalPriceSet { ${MONEY_FIELDS} } totalTaxSet { ${MONEY_FIELDS} } totalDiscountsSet { ${MONEY_FIELDS} } totalShippingPriceSet { ${MONEY_FIELDS} } totalRefundedSet { ${MONEY_FIELDS} } totalOutstandingSet { ${MONEY_FIELDS} } currentTotalPriceSet { ${MONEY_FIELDS} } customer { id displayName defaultEmailAddress { emailAddress } }`;
+
+const ORDER_DETAIL_FIELDS = `${ORDER_SUMMARY_FIELDS} number confirmed capturable refundable fullyPaid unpaid canMarkAsPaid fulfillmentsCount { count } transactionsCount { count } discountCodes paymentGatewayNames shippingLine { title originalPriceSet { ${MONEY_FIELDS} } } shippingAddress { ${ADDRESS_FIELDS} } billingAddress { ${ADDRESS_FIELDS} } lineItems(first: 100) { pageInfo { hasNextPage } nodes { id name title sku variantTitle vendor quantity currentQuantity refundableQuantity unfulfilledQuantity requiresShipping taxable originalUnitPriceSet { ${MONEY_FIELDS} } discountedTotalSet { ${MONEY_FIELDS} } variant { id } product { id } } }`;
+
+const TRANSACTION_FIELDS = `id kind status gateway formattedGateway test createdAt processedAt errorCode paymentId authorizationExpiresAt manuallyCapturable multiCapturable amountSet { ${MONEY_FIELDS} } totalUnsettledSet { ${MONEY_FIELDS} } maximumRefundableV2 { amount currencyCode } parentTransaction { id } order { id name }`;
+
+const REFUND_FIELDS = `id legacyResourceId note createdAt processedAt updatedAt totalRefundedSet { ${MONEY_FIELDS} } order { id name } refundLineItems(first: 50) { nodes { quantity restockType restocked subtotalSet { ${MONEY_FIELDS} } totalTaxSet { ${MONEY_FIELDS} } lineItem { id title sku } } } transactions(first: 20) { nodes { id kind status gateway amountSet { ${MONEY_FIELDS} } } }`;
+
+const REFUND_SUMMARY_FIELDS = `id legacyResourceId note createdAt processedAt updatedAt totalRefundedSet { ${MONEY_FIELDS} }`;
+
+const DRAFT_ORDER_SUMMARY_FIELDS = `id legacyResourceId name status createdAt updatedAt completedAt invoiceUrl invoiceSentAt email phone note2 tags poNumber ready currencyCode subtotalPriceSet { ${MONEY_FIELDS} } totalPriceSet { ${MONEY_FIELDS} } totalTaxSet { ${MONEY_FIELDS} } totalDiscountsSet { ${MONEY_FIELDS} } totalShippingPriceSet { ${MONEY_FIELDS} } customer { id displayName } order { id name }`;
+
+const DRAFT_ORDER_DETAIL_FIELDS = `${DRAFT_ORDER_SUMMARY_FIELDS} reserveInventoryUntil taxExempt taxesIncluded discountCodes appliedDiscount { title value valueType amountSet { ${MONEY_FIELDS} } } paymentTerms { id paymentTermsName paymentTermsType dueInDays } shippingLine { title originalPriceSet { ${MONEY_FIELDS} } } shippingAddress { ${ADDRESS_FIELDS} } lineItems(first: 100) { pageInfo { hasNextPage } nodes { id name title sku quantity custom originalUnitPriceSet { ${MONEY_FIELDS} } discountedTotalSet { ${MONEY_FIELDS} } variant { id } } }`;
+
+const CUSTOMER_FIELDS = `id legacyResourceId displayName firstName lastName defaultEmailAddress { emailAddress marketingState marketingOptInLevel marketingUpdatedAt } defaultPhoneNumber { phoneNumber } note tags state verifiedEmail taxExempt locale numberOfOrders amountSpent { amount currencyCode } canDelete lastOrder { id name } defaultAddress { ${ADDRESS_FIELDS} } createdAt updatedAt`;
+
+const ABANDONED_CHECKOUT_FIELDS = `id name createdAt updatedAt completedAt abandonedCheckoutUrl note discountCodes taxesIncluded subtotalPriceSet { ${MONEY_FIELDS} } totalPriceSet { ${MONEY_FIELDS} } customer { id displayName defaultEmailAddress { emailAddress } } shippingAddress { countryCodeV2 }`;
+
+const ABANDONMENT_FIELDS = `id abandonmentType mostRecentStep createdAt emailState emailSentAt cartUrl inventoryAvailable isFromOnlineStore customerHasNoOrderSinceAbandonment lastCheckoutAbandonmentDate customer { id displayName defaultEmailAddress { emailAddress } } abandonedCheckoutPayload { id name abandonedCheckoutUrl totalPriceSet { ${MONEY_FIELDS} } }`;
+
+const PAGE_INFO_FIELDS = 'pageInfo { hasNextPage endCursor }';
+
+export { SHOPIFY_API_VERSION };
+
+export const shopifyFields = {
+ MONEY_FIELDS,
+ MONEY_WITH_PRESENTMENT_FIELDS,
+ ADDRESS_FIELDS,
+ ORDER_SUMMARY_FIELDS,
+ ORDER_DETAIL_FIELDS,
+ TRANSACTION_FIELDS,
+ REFUND_FIELDS,
+ REFUND_SUMMARY_FIELDS,
+ DRAFT_ORDER_SUMMARY_FIELDS,
+ DRAFT_ORDER_DETAIL_FIELDS,
+ CUSTOMER_FIELDS,
+ ABANDONED_CHECKOUT_FIELDS,
+ ABANDONMENT_FIELDS,
+ PAGE_INFO_FIELDS,
+};
+
+export const shopifyGraphqlClient = {
+ request: shopifyGraphql,
+ toGid,
+ resolveIdempotencyKey,
+};
+
+export const shopifyValues = {
+ readClearable,
+ readFirst,
+ nonEmpty,
+ readStringList,
+ readRecords,
+ readText,
+ readNumber,
+ toBooleanChoice,
+ compact,
+ money,
+ presentmentMoney,
+ presentmentCurrency,
+ isRecord,
+ buildMailingAddress,
+ buildRefundLineItems,
+ buildDraftLineItems,
+};
+
+export const shopifyMappers = {
+ toPage,
+ mapAddress,
+ mapOrderSummary,
+ mapOrderDetail,
+ mapTransaction,
+ mapRefund,
+ mapRefundSummary,
+ mapDraftOrderSummary,
+ mapDraftOrderDetail,
+ mapCustomer,
+ mapAbandonedCheckout,
+ mapAbandonment,
+};
+
+export const shopifyProps = {
+ address: addressProps,
+ first: firstProp,
+ after: afterProp,
+ reverse: reverseProp,
+ searchQuery: searchQueryProp,
+ booleanChoice: booleanChoiceProp,
+ idempotencyKey: idempotencyKeyProp,
+ refundLineItems: refundLineItemsProp,
+ draftLineItems: draftLineItemsProp,
+};
+
+export type ShopifyGraphqlParams = {
+ auth: ShopifyAuth;
+ query: string;
+ variables?: Record<string, unknown>;
+ idempotencyKey?: string;
+ primaryPaths?: string[];
+ toleratedUserErrorCodes?: string[];
+};
+
+export type ShopifyGraphqlResult<TData> = {
+ data: TData;
+ redactedFields: string[];
+};
+
+export type ShopifyGraphqlError = {
+ message?: string;
+ path?: (string | number)[];
+ extensions?: {
+ code?: string;
+ requiredAccess?: string;
+ documentation?: string;
+ };
+};
+
+export type ShopifyGraphqlResponse<TData> = {
+ data?: TData | null;
+ errors?: ShopifyGraphqlError[];
+ extensions?: {
+ cost?: {
+ throttleStatus?: Record<string, unknown>;
+ };
+ search?: ShopifySearchExtension[];
+ };
+};
+
+export type ShopifySearchExtension = {
+ query?: string;
+ warnings?: { field?: string; message?: string; code?: string }[];
+};
+
+export type ShopifyPage<TItem> = {
+ items: TItem[];
+ count: number;
+ has_next_page: boolean;
+ end_cursor: string | null;
+ redacted_fields: string[];
+};
+
+export type ToGidParams = {
+ type: string;
+ id: string | number;
+ query?: string;
+};
+
+export type AddressProps = {
+ first_name?: string;
+ last_name?: string;
+ company?: string;
+ address1?: string;
+ address2?: string;
+ city?: string;
+ province_code?: string;
+ country_code?: string;
+ zip?: string;
+ phone?: string;
+};
+
+export type FlatAddress = {
+ id: string | null;
+ first_name: string | null;
+ last_name: string | null;
+ name: string | null;
+ company: string | null;
+ address1: string | null;
+ address2: string | null;
+ city: string | null;
+ province: string | null;
+ province_code: string | null;
+ country: string | null;
+ country_code: string | null;
+ zip: string | null;
+ phone: string | null;
+};
+
+export type GqlMoneyBag = {
+ shopMoney?: { amount?: string | null; currencyCode?: string | null } | null;
+ presentmentMoney?: { amount?: string | null; currencyCode?: string | null } | null;
+};
+
+export type GqlMoneyV2 = {
+ amount?: string | null;
+ currencyCode?: string | null;
+};
+
+export type GqlConnection<TNode> = {
+ nodes?: TNode[] | null;
+ pageInfo?: { hasNextPage?: boolean | null; endCursor?: string | null } | null;
+};
+
+export type GqlCount = {
+ count?: number | null;
+ precision?: string | null;
+};
+
+export type GqlMailingAddress = {
+ id?: string | null;
+ firstName?: string | null;
+ lastName?: string | null;
+ name?: string | null;
+ company?: string | null;
+ address1?: string | null;
+ address2?: string | null;
+ city?: string | null;
+ province?: string | null;
+ provinceCode?: string | null;
+ country?: string | null;
+ countryCodeV2?: string | null;
+ zip?: string | null;
+ phone?: string | null;
+};
+
+export type GqlCustomerRef = {
+ id?: string | null;
+ displayName?: string | null;
+ defaultEmailAddress?: { emailAddress?: string | null } | null;
+};
+
+export type GqlOrder = {
+ id: string;
+ legacyResourceId?: string | null;
+ name?: string | null;
+ number?: number | null;
+ createdAt?: string | null;
+ updatedAt?: string | null;
+ processedAt?: string | null;
+ closed?: boolean | null;
+ closedAt?: string | null;
+ cancelledAt?: string | null;
+ cancelReason?: string | null;
+ displayFinancialStatus?: string | null;
+ displayFulfillmentStatus?: string | null;
+ confirmed?: boolean | null;
+ test?: boolean | null;
+ email?: string | null;
+ phone?: string | null;
+ note?: string | null;
+ tags?: string[] | null;
+ poNumber?: string | null;
+ sourceName?: string | null;
+ currencyCode?: string | null;
+ subtotalPriceSet?: GqlMoneyBag | null;
+ totalPriceSet?: GqlMoneyBag | null;
+ totalTaxSet?: GqlMoneyBag | null;
+ totalDiscountsSet?: GqlMoneyBag | null;
+ totalShippingPriceSet?: GqlMoneyBag | null;
+ totalRefundedSet?: GqlMoneyBag | null;
+ totalOutstandingSet?: GqlMoneyBag | null;
+ currentTotalPriceSet?: GqlMoneyBag | null;
+ capturable?: boolean | null;
+ refundable?: boolean | null;
+ fullyPaid?: boolean | null;
+ unpaid?: boolean | null;
+ canMarkAsPaid?: boolean | null;
+ fulfillmentsCount?: GqlCount | null;
+ transactionsCount?: GqlCount | null;
+ discountCodes?: string[] | null;
+ paymentGatewayNames?: string[] | null;
+ shippingLine?: { title?: string | null; originalPriceSet?: GqlMoneyBag | null } | null;
+ shippingAddress?: GqlMailingAddress | null;
+ billingAddress?: GqlMailingAddress | null;
+ customer?: GqlCustomerRef | null;
+ lineItems?: GqlConnection<GqlLineItem> | null;
+};
+
+export type GqlLineItem = {
+ id: string;
+ name?: string | null;
+ title?: string | null;
+ sku?: string | null;
+ variantTitle?: string | null;
+ vendor?: string | null;
+ quantity?: number | null;
+ currentQuantity?: number | null;
+ refundableQuantity?: number | null;
+ unfulfilledQuantity?: number | null;
+ requiresShipping?: boolean | null;
+ taxable?: boolean | null;
+ originalUnitPriceSet?: GqlMoneyBag | null;
+ discountedTotalSet?: GqlMoneyBag | null;
+ variant?: { id?: string | null } | null;
+ product?: { id?: string | null } | null;
+};
+
+export type GqlTransaction = {
+ id: string;
+ kind?: string | null;
+ status?: string | null;
+ gateway?: string | null;
+ formattedGateway?: string | null;
+ test?: boolean | null;
+ createdAt?: string | null;
+ processedAt?: string | null;
+ errorCode?: string | null;
+ paymentId?: string | null;
+ authorizationExpiresAt?: string | null;
+ manuallyCapturable?: boolean | null;
+ multiCapturable?: boolean | null;
+ amountSet?: GqlMoneyBag | null;
+ totalUnsettledSet?: GqlMoneyBag | null;
+ maximumRefundableV2?: GqlMoneyV2 | null;
+ parentTransaction?: { id?: string | null } | null;
+ order?: { id?: string | null; name?: string | null } | null;
+};
+
+export type GqlRefund = {
+ id: string;
+ legacyResourceId?: string | null;
+ note?: string | null;
+ createdAt?: string | null;
+ processedAt?: string | null;
+ updatedAt?: string | null;
+ totalRefundedSet?: GqlMoneyBag | null;
+ order?: { id?: string | null; name?: string | null } | null;
+ refundLineItems?: GqlConnection<{
+ quantity?: number | null;
+ restockType?: string | null;
+ restocked?: boolean | null;
+ subtotalSet?: GqlMoneyBag | null;
+ totalTaxSet?: GqlMoneyBag | null;
+ lineItem?: { id?: string | null; title?: string | null; sku?: string | null } | null;
+ }> | null;
+ transactions?: GqlConnection<{
+ id: string;
+ kind?: string | null;
+ status?: string | null;
+ gateway?: string | null;
+ amountSet?: GqlMoneyBag | null;
+ }> | null;
+};
+
+export type GqlDraftOrder = {
+ id: string;
+ legacyResourceId?: string | null;
+ name?: string | null;
+ status?: string | null;
+ createdAt?: string | null;
+ updatedAt?: string | null;
+ completedAt?: string | null;
+ invoiceUrl?: string | null;
+ invoiceSentAt?: string | null;
+ email?: string | null;
+ phone?: string | null;
+ note2?: string | null;
+ tags?: string[] | null;
+ poNumber?: string | null;
+ ready?: boolean | null;
+ currencyCode?: string | null;
+ subtotalPriceSet?: GqlMoneyBag | null;
+ totalPriceSet?: GqlMoneyBag | null;
+ totalTaxSet?: GqlMoneyBag | null;
+ totalDiscountsSet?: GqlMoneyBag | null;
+ totalShippingPriceSet?: GqlMoneyBag | null;
+ customer?: { id?: string | null; displayName?: string | null } | null;
+ order?: { id?: string | null; name?: string | null } | null;
+ reserveInventoryUntil?: string | null;
+ taxExempt?: boolean | null;
+ taxesIncluded?: boolean | null;
+ discountCodes?: string[] | null;
+ appliedDiscount?: {
+ title?: string | null;
+ value?: number | null;
+ valueType?: string | null;
+ amountSet?: GqlMoneyBag | null;
+ } | null;
+ paymentTerms?: {
+ id?: string | null;
+ paymentTermsName?: string | null;
+ paymentTermsType?: string | null;
+ dueInDays?: number | null;
+ } | null;
+ shippingLine?: { title?: string | null; originalPriceSet?: GqlMoneyBag | null } | null;
+ shippingAddress?: GqlMailingAddress | null;
+ lineItems?: GqlConnection<{
+ id: string;
+ name?: string | null;
+ title?: string | null;
+ sku?: string | null;
+ quantity?: number | null;
+ custom?: boolean | null;
+ originalUnitPriceSet?: GqlMoneyBag | null;
+ discountedTotalSet?: GqlMoneyBag | null;
+ variant?: { id?: string | null } | null;
+ }> | null;
+};
+
+export type GqlCustomer = {
+ id: string;
+ legacyResourceId?: string | null;
+ displayName?: string | null;
+ firstName?: string | null;
+ lastName?: string | null;
+ defaultEmailAddress?: {
+ emailAddress?: string | null;
+ marketingState?: string | null;
+ marketingOptInLevel?: string | null;
+ marketingUpdatedAt?: string | null;
+ } | null;
+ defaultPhoneNumber?: { phoneNumber?: string | null } | null;
+ note?: string | null;
+ tags?: string[] | null;
+ state?: string | null;
+ verifiedEmail?: boolean | null;
+ taxExempt?: boolean | null;
+ locale?: string | null;
+ numberOfOrders?: string | null;
+ amountSpent?: GqlMoneyV2 | null;
+ canDelete?: boolean | null;
+ lastOrder?: { id?: string | null; name?: string | null } | null;
+ defaultAddress?: GqlMailingAddress | null;
+ createdAt?: string | null;
+ updatedAt?: string | null;
+};
+
+export type GqlAbandonedCheckout = {
+ id: string;
+ name?: string | null;
+ createdAt?: string | null;
+ updatedAt?: string | null;
+ completedAt?: string | null;
+ abandonedCheckoutUrl?: string | null;
+ note?: string | null;
+ discountCodes?: string[] | null;
+ taxesIncluded?: boolean | null;
+ subtotalPriceSet?: GqlMoneyBag | null;
+ totalPriceSet?: GqlMoneyBag | null;
+ customer?: GqlCustomerRef | null;
+ shippingAddress?: { countryCodeV2?: string | null } | null;
+};
+
+export type GqlAbandonment = {
+ id: string;
+ abandonmentType?: string | null;
+ mostRecentStep?: string | null;
+ createdAt?: string | null;
+ emailState?: string | null;
+ emailSentAt?: string | null;
+ cartUrl?: string | null;
+ inventoryAvailable?: boolean | null;
+ isFromOnlineStore?: boolean | null;
+ customerHasNoOrderSinceAbandonment?: boolean | null;
+ lastCheckoutAbandonmentDate?: string | null;
+ customer?: GqlCustomerRef | null;
+ abandonedCheckoutPayload?: {
+ id?: string | null;
+ name?: string | null;
+ abandonedCheckoutUrl?: string | null;
+ totalPriceSet?: GqlMoneyBag | null;
+ } | null;
+};
diff --git a/packages/pieces/community/shopify/src/lib/common/register-webhook.ts b/packages/pieces/community/shopify/src/lib/common/register-webhook.ts
index 53a0d3da1da..9950e4db75a 100644
--- a/packages/pieces/community/shopify/src/lib/common/register-webhook.ts
+++ b/packages/pieces/community/shopify/src/lib/common/register-webhook.ts
@@ -4,7 +4,7 @@ import {
Trigger,
TriggerStrategy,
} from '@activepieces/pieces-framework';
-import { shopifyAuth, shopifyAuthHelpers } from './auth';
+import { SHOPIFY_API_VERSION, shopifyAuth, shopifyAuthHelpers } from './auth';
export const createShopifyWebhookTrigger = ({
name,
@@ -39,7 +39,7 @@ export const createShopifyWebhookTrigger = ({
};
}>({
method: HttpMethod.POST,
- url: `https://${shopName}.myshopify.com/admin/api/2023-01/webhooks.json`,
+ url: `https://${shopName}.myshopify.com/admin/api/${SHOPIFY_API_VERSION}/webhooks.json`,
headers: shopifyAuthHelpers.getAuthHeaders(context.auth),
body: {
webhook: {
@@ -61,7 +61,7 @@ export const createShopifyWebhookTrigger = ({
};
}>({
method: HttpMethod.DELETE,
- url: `https://${shopName}.myshopify.com/admin/api/2023-01/webhooks/${webhookId}.json`,
+ 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);
diff --git a/packages/pieces/community/shopify/src/lib/common/requested-order-edits.ts b/packages/pieces/community/shopify/src/lib/common/requested-order-edits.ts
new file mode 100644
index 00000000000..bd401b28ae0
--- /dev/null
+++ b/packages/pieces/community/shopify/src/lib/common/requested-order-edits.ts
@@ -0,0 +1,239 @@
+import { Property } from '@activepieces/pieces-framework';
+import {
+ GqlConnection,
+ GqlMoneyBag,
+ shopifyGraphqlClient,
+ shopifyValues,
+} from './graphql';
+
+const REQUESTED_EDIT_REMOVALS_LIMIT = 50;
+
+const CALCULATED_REQUESTED_EDIT_REMOVALS_LIMIT = 50;
+
+const DECLINE_NOTE_MAX_LENGTH = 500;
+
+const REQUESTED_EDIT_LINE_ITEM_FIELDS =
+ 'id name title sku variantTitle quantity currentQuantity unfulfilledQuantity variant { id } product { id }';
+
+const REQUESTED_ORDER_EDIT_FIELDS = `id status requestedAt requestDeclinedAt requestResolvedAt createdAt updatedAt order { id name displayRequestedEditStatus } lineItems { removals(first: ${REQUESTED_EDIT_REMOVALS_LIMIT}) { pageInfo { hasNextPage } nodes { id quantity resolvedQuantity lineItem { ${REQUESTED_EDIT_LINE_ITEM_FIELDS} } } } }`;
+
+const REQUESTED_EDIT_MONEY_FIELDS =
+ 'shopMoney { amount currencyCode } presentmentMoney { amount currencyCode }';
+
+const CALCULATED_REQUESTED_ORDER_EDIT_FIELDS = `financialSummary { editSubtotalBeforeTargetAllDiscountsSet { ${REQUESTED_EDIT_MONEY_FIELDS} } editOrderLevelDiscountSubtotalSet { ${REQUESTED_EDIT_MONEY_FIELDS} } editSubtotalSet { ${REQUESTED_EDIT_MONEY_FIELDS} } editSubtotalWithCartDiscountSet { ${REQUESTED_EDIT_MONEY_FIELDS} } editTotalTaxSet { ${REQUESTED_EDIT_MONEY_FIELDS} } editTotalSet { ${REQUESTED_EDIT_MONEY_FIELDS} } } lineItems { removals(first: ${CALCULATED_REQUESTED_EDIT_REMOVALS_LIMIT}) { pageInfo { hasNextPage } nodes { quantity subtotalSet { ${REQUESTED_EDIT_MONEY_FIELDS} } totalTaxSet { ${REQUESTED_EDIT_MONEY_FIELDS} } lineItem { id name sku unfulfilledQuantity } } } }`;
+
+function removalsProp() {
+ return Property.Array({
+ displayName: 'Line Items to Remove',
+ description:
+ 'The order line items the buyer wants removed and how many units of each. Line item ids come from get_order (line_items[].id). The quantity cannot exceed the unfulfilled quantity of the line item.',
+ required: true,
+ properties: {
+ line_item_id: Property.ShortText({
+ displayName: 'Line Item ID',
+ description: 'Order line item id, numeric or "gid://shopify/LineItem/…".',
+ required: true,
+ }),
+ quantity: Property.Number({
+ displayName: 'Quantity',
+ description: 'How many units of this line item to remove, a whole number of at least 1.',
+ required: true,
+ }),
+ },
+ });
+}
+
+function buildRemovals(value: unknown): { lineItemId: string; quantity: number }[] {
+ const seen = new Set<string>();
+ const removals = shopifyValues.readRecords(value).map((item) => {
+ const lineItemId = shopifyValues.readText(item['line_item_id']);
+ const quantity = shopifyValues.readNumber(item['quantity']);
+ if (!lineItemId) {
+ throw new Error('Every line item to remove needs a line_item_id. Nothing was sent to Shopify.');
+ }
+ if (quantity === undefined || !Number.isInteger(quantity) || quantity < 1) {
+ throw new Error(
+ `Line item ${lineItemId} needs a whole-number quantity of at least 1. Nothing was sent to Shopify.`
+ );
+ }
+ const gid = shopifyGraphqlClient.toGid({ type: 'LineItem', id: lineItemId });
+ if (seen.has(gid)) {
+ throw new Error(
+ `Line item ${gid} is listed more than once; give each line item once with its total quantity. Nothing was sent to Shopify.`
+ );
+ }
+ seen.add(gid);
+ return { lineItemId: gid, quantity };
+ });
+ if (removals.length === 0) {
+ throw new Error('Provide at least one line item to remove. Nothing was sent to Shopify.');
+ }
+ if (removals.length > CALCULATED_REQUESTED_EDIT_REMOVALS_LIMIT) {
+ throw new Error(
+ `Provide at most ${CALCULATED_REQUESTED_EDIT_REMOVALS_LIMIT} line items to remove per call. Nothing was sent to Shopify.`
+ );
+ }
+ return removals;
+}
+
+function mapRequestedOrderEdit(edit: GqlRequestedOrderEdit) {
+ const removals = edit.lineItems?.removals;
+ const items = (removals?.nodes ?? []).map((removal) => ({
+ id: removal.id,
+ quantity: removal.quantity ?? null,
+ resolved_quantity: removal.resolvedQuantity ?? null,
+ line_item_id: removal.lineItem?.id ?? null,
+ line_item_name: removal.lineItem?.name ?? null,
+ line_item_title: removal.lineItem?.title ?? null,
+ sku: removal.lineItem?.sku ?? null,
+ variant_title: removal.lineItem?.variantTitle ?? null,
+ line_item_quantity: removal.lineItem?.quantity ?? null,
+ line_item_current_quantity: removal.lineItem?.currentQuantity ?? null,
+ line_item_unfulfilled_quantity: removal.lineItem?.unfulfilledQuantity ?? null,
+ variant_id: removal.lineItem?.variant?.id ?? null,
+ product_id: removal.lineItem?.product?.id ?? null,
+ }));
+ return {
+ id: edit.id,
+ status: edit.status ?? null,
+ requested_at: edit.requestedAt ?? null,
+ request_declined_at: edit.requestDeclinedAt ?? null,
+ request_resolved_at: edit.requestResolvedAt ?? null,
+ created_at: edit.createdAt ?? null,
+ updated_at: edit.updatedAt ?? null,
+ order_id: edit.order?.id ?? null,
+ order_name: edit.order?.name ?? null,
+ order_requested_edit_status: edit.order?.displayRequestedEditStatus ?? null,
+ removals: items,
+ removals_count: items.length,
+ removals_truncated: removals?.pageInfo?.hasNextPage ?? false,
+ };
+}
+
+function mapCalculatedRequestedOrderEdit(calculated: GqlCalculatedRequestedOrderEdit) {
+ const summary = calculated.financialSummary;
+ const removals = calculated.lineItems?.removals;
+ const items = (removals?.nodes ?? []).map((removal) => ({
+ line_item_id: removal.lineItem?.id ?? null,
+ line_item_name: removal.lineItem?.name ?? null,
+ sku: removal.lineItem?.sku ?? null,
+ line_item_unfulfilled_quantity: removal.lineItem?.unfulfilledQuantity ?? null,
+ quantity: removal.quantity ?? null,
+ subtotal: shopifyValues.money(removal.subtotalSet),
+ total_tax: shopifyValues.money(removal.totalTaxSet),
+ presentment_subtotal: shopifyValues.presentmentMoney(removal.subtotalSet),
+ presentment_total_tax: shopifyValues.presentmentMoney(removal.totalTaxSet),
+ }));
+ return {
+ edit_subtotal_before_target_all_discounts: shopifyValues.money(
+ summary?.editSubtotalBeforeTargetAllDiscountsSet
+ ),
+ edit_order_level_discount_subtotal: shopifyValues.money(summary?.editOrderLevelDiscountSubtotalSet),
+ edit_subtotal: shopifyValues.money(summary?.editSubtotalSet),
+ edit_subtotal_with_cart_discount: shopifyValues.money(summary?.editSubtotalWithCartDiscountSet),
+ edit_total_tax: shopifyValues.money(summary?.editTotalTaxSet),
+ edit_total: shopifyValues.money(summary?.editTotalSet),
+ currency_code: summary?.editTotalSet?.shopMoney?.currencyCode ?? null,
+ presentment_edit_subtotal: shopifyValues.presentmentMoney(summary?.editSubtotalSet),
+ presentment_edit_total_tax: shopifyValues.presentmentMoney(summary?.editTotalTaxSet),
+ presentment_edit_total: shopifyValues.presentmentMoney(summary?.editTotalSet),
+ presentment_currency_code: shopifyValues.presentmentCurrency(summary?.editTotalSet),
+ removals: items,
+ removals_count: items.length,
+ removals_truncated: removals?.pageInfo?.hasNextPage ?? false,
+ };
+}
+
+function readTypedId({ type, value, label }: { type: string; value: string | undefined | null; label: string }): string {
+ const trimmed = (value ?? '').trim();
+ const gid = shopifyGraphqlClient.toGid({ type, id: trimmed });
+ const match = gid.match(/^gid:\/\/shopify\/([A-Za-z]+)\/\d+$/);
+ if (!match || match[1] !== type) {
+ throw new Error(
+ `${label} "${trimmed}" is not a ${type} id. Pass the number or "gid://shopify/${type}/123". Nothing was sent to Shopify.`
+ );
+ }
+ return gid;
+}
+
+function readDeclineNote(value: string | undefined | null): string | undefined {
+ const note = shopifyValues.nonEmpty(value);
+ if (note !== undefined && note.length > DECLINE_NOTE_MAX_LENGTH) {
+ throw new Error(
+ `The decline note is ${note.length} characters; Shopify accepts at most ${DECLINE_NOTE_MAX_LENGTH}. Shorten it. Nothing was sent to Shopify.`
+ );
+ }
+ return note;
+}
+
+export const requestedOrderEditFields = {
+ REQUESTED_ORDER_EDIT_FIELDS,
+ CALCULATED_REQUESTED_ORDER_EDIT_FIELDS,
+ REQUESTED_EDIT_REMOVALS_LIMIT,
+ DECLINE_NOTE_MAX_LENGTH,
+};
+
+export const requestedOrderEditHelpers = {
+ removalsProp,
+ buildRemovals,
+ mapRequestedOrderEdit,
+ mapCalculatedRequestedOrderEdit,
+ readDeclineNote,
+ readTypedId,
+};
+
+export type GqlRequestedOrderEdit = {
+ id: string;
+ status?: string | null;
+ requestedAt?: string | null;
+ requestDeclinedAt?: string | null;
+ requestResolvedAt?: string | null;
+ createdAt?: string | null;
+ updatedAt?: string | null;
+ order?: { id: string; name?: string | null; displayRequestedEditStatus?: string | null } | null;
+ lineItems?: {
+ removals?: GqlConnection<GqlRequestedOrderEditLineItem> | null;
+ } | null;
+};
+
+type GqlRequestedOrderEditLineItem = {
+ id: string;
+ quantity?: number | null;
+ resolvedQuantity?: number | null;
+ lineItem?: {
+ id: string;
+ name?: string | null;
+ title?: string | null;
+ sku?: string | null;
+ variantTitle?: string | null;
+ quantity?: number | null;
+ currentQuantity?: number | null;
+ unfulfilledQuantity?: number | null;
+ variant?: { id: string } | null;
+ product?: { id: string } | null;
+ } | null;
+};
+
+export type GqlCalculatedRequestedOrderEdit = {
+ financialSummary?: {
+ editSubtotalBeforeTargetAllDiscountsSet?: GqlMoneyBag | null;
+ editOrderLevelDiscountSubtotalSet?: GqlMoneyBag | null;
+ editSubtotalSet?: GqlMoneyBag | null;
+ editSubtotalWithCartDiscountSet?: GqlMoneyBag | null;
+ editTotalTaxSet?: GqlMoneyBag | null;
+ editTotalSet?: GqlMoneyBag | null;
+ } | null;
+ lineItems?: {
+ removals?: GqlConnection<{
+ quantity?: number | null;
+ subtotalSet?: GqlMoneyBag | null;
+ totalTaxSet?: GqlMoneyBag | null;
+ lineItem?: {
+ id: string;
+ name?: string | null;
+ sku?: string | null;
+ unfulfilledQuantity?: number | null;
+ } | null;
+ }> | null;
+ } | null;
+};
diff --git a/packages/pieces/community/shopify/src/lib/output-schemas.ts b/packages/pieces/community/shopify/src/lib/output-schemas.ts
new file mode 100644
index 00000000000..0b3e723b230
--- /dev/null
+++ b/packages/pieces/community/shopify/src/lib/output-schemas.ts
@@ -0,0 +1 @@
+export const shopifyOutputSchemas = {};
diff --git a/packages/pieces/community/shopify/src/lib/output-schemas/orders.ts b/packages/pieces/community/shopify/src/lib/output-schemas/orders.ts
new file mode 100644
index 00000000000..c66cc9afc07
--- /dev/null
+++ b/packages/pieces/community/shopify/src/lib/output-schemas/orders.ts
@@ -0,0 +1,928 @@
+import { OutputSchema, OutputSchemaField } from '@activepieces/pieces-framework';
+
+const redactedFieldsField: OutputSchemaField = {
+ key: 'redacted_fields',
+ label: 'Redacted Fields',
+ description:
+ 'Response paths Shopify withheld, for example because the app is not approved for protected customer data.',
+};
+
+const countFields: OutputSchema['fields'] = [
+ { key: 'count', label: 'Count', format: 'number' },
+ {
+ key: 'precision',
+ label: 'Precision',
+ description: 'EXACT, or AT_LEAST when Shopify capped the count.',
+ },
+ redactedFieldsField,
+];
+
+const pageFields: OutputSchema['fields'] = [
+ { key: 'count', label: 'Count', format: 'number' },
+ { key: 'has_next_page', label: 'Has Next Page', format: 'boolean' },
+ {
+ key: 'end_cursor',
+ label: 'End Cursor',
+ description: 'Pass back as the cursor to read the next page.',
+ },
+ redactedFieldsField,
+];
+
+const shippingAddressFields: OutputSchema['fields'] = [
+ { key: 'shipping_name', label: 'Shipping Name' },
+ { key: 'shipping_company', label: 'Shipping Company' },
+ { key: 'shipping_address1', label: 'Shipping Address 1' },
+ { key: 'shipping_address2', label: 'Shipping Address 2' },
+ { key: 'shipping_city', label: 'Shipping City' },
+ { key: 'shipping_province_code', label: 'Shipping Province Code' },
+ { key: 'shipping_country_code', label: 'Shipping Country Code' },
+ { key: 'shipping_zip', label: 'Shipping ZIP' },
+ { key: 'shipping_phone', label: 'Shipping Phone' },
+];
+
+const billingAddressFields: OutputSchema['fields'] = [
+ { key: 'billing_name', label: 'Billing Name' },
+ { key: 'billing_company', label: 'Billing Company' },
+ { key: 'billing_address1', label: 'Billing Address 1' },
+ { key: 'billing_address2', label: 'Billing Address 2' },
+ { key: 'billing_city', label: 'Billing City' },
+ { key: 'billing_province_code', label: 'Billing Province Code' },
+ { key: 'billing_country_code', label: 'Billing Country Code' },
+ { key: 'billing_zip', label: 'Billing ZIP' },
+ { key: 'billing_phone', label: 'Billing Phone' },
+];
+
+const defaultAddressFields: OutputSchema['fields'] = [
+ { key: 'default_address_name', label: 'Default Address Name' },
+ { key: 'default_address_company', label: 'Default Address Company' },
+ { key: 'default_address_address1', label: 'Default Address Address 1' },
+ { key: 'default_address_address2', label: 'Default Address Address 2' },
+ { key: 'default_address_city', label: 'Default Address City' },
+ {
+ key: 'default_address_province_code',
+ label: 'Default Address Province Code',
+ },
+ {
+ key: 'default_address_country_code',
+ label: 'Default Address Country Code',
+ },
+ { key: 'default_address_zip', label: 'Default Address ZIP' },
+ { key: 'default_address_phone', label: 'Default Address Phone' },
+];
+
+const orderSummaryFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Order ID' },
+ { key: 'legacy_resource_id', label: 'Numeric ID' },
+ { key: 'name', label: 'Order Name' },
+ { key: 'created_at', label: 'Created At', format: 'datetime' },
+ { key: 'updated_at', label: 'Updated At', format: 'datetime' },
+ { key: 'processed_at', label: 'Processed At', format: 'datetime' },
+ { key: 'closed', label: 'Closed', format: 'boolean' },
+ { key: 'closed_at', label: 'Closed At', format: 'datetime' },
+ { key: 'cancelled_at', label: 'Cancelled At', format: 'datetime' },
+ { key: 'cancel_reason', label: 'Cancel Reason' },
+ {
+ key: 'financial_status',
+ label: 'Financial Status',
+ description: 'Display status, for example PAID, PENDING or REFUNDED.',
+ },
+ { key: 'fulfillment_status', label: 'Fulfillment Status' },
+ { key: 'test', label: 'Test', format: 'boolean' },
+ { key: 'email', label: 'Email', format: 'email' },
+ { key: 'phone', label: 'Phone' },
+ { key: 'note', label: 'Note' },
+ { key: 'tags', label: 'Tags', description: 'Comma-separated.' },
+ { key: 'po_number', label: 'PO Number' },
+ { key: 'source_name', label: 'Source Name' },
+ { key: 'currency_code', label: 'Currency Code' },
+ { key: 'subtotal_price', label: 'Subtotal Price', format: 'number' },
+ { key: 'total_price', label: 'Total Price', format: 'number' },
+ { key: 'total_tax', label: 'Total Tax', format: 'number' },
+ { key: 'total_discounts', label: 'Total Discounts', format: 'number' },
+ { key: 'total_shipping', label: 'Total Shipping', format: 'number' },
+ { key: 'total_refunded', label: 'Total Refunded', format: 'number' },
+ { key: 'total_outstanding', label: 'Total Outstanding', format: 'number' },
+ { key: 'current_total_price', label: 'Current Total Price', format: 'number' },
+ { key: 'customer_id', label: 'Customer ID' },
+ { key: 'customer_name', label: 'Customer Name' },
+ { key: 'customer_email', label: 'Customer Email', format: 'email' },
+];
+
+const orderDetailFields: OutputSchema['fields'] = [
+ ...orderSummaryFields,
+ { key: 'number', label: 'Order Number', format: 'number' },
+ { key: 'confirmed', label: 'Confirmed', format: 'boolean' },
+ { key: 'capturable', label: 'Capturable', format: 'boolean' },
+ { key: 'refundable', label: 'Refundable', format: 'boolean' },
+ { key: 'fully_paid', label: 'Fully Paid', format: 'boolean' },
+ { key: 'unpaid', label: 'Unpaid', format: 'boolean' },
+ { key: 'can_mark_as_paid', label: 'Can Mark As Paid', format: 'boolean' },
+ { key: 'fulfillments_count', label: 'Fulfillments Count', format: 'number' },
+ { key: 'transactions_count', label: 'Transactions Count', format: 'number' },
+ { key: 'discount_codes', label: 'Discount Codes', description: 'Comma-separated.' },
+ {
+ key: 'payment_gateway_names',
+ label: 'Payment Gateway Names',
+ description: 'Comma-separated.',
+ },
+ { key: 'shipping_line_title', label: 'Shipping Line Title' },
+ { key: 'shipping_line_price', label: 'Shipping Line Price', format: 'number' },
+ ...shippingAddressFields,
+ ...billingAddressFields,
+ {
+ key: 'line_items',
+ label: 'Line Items',
+ labelKey: 'name',
+ listItems: [
+ { key: 'id', label: 'Line Item ID' },
+ { key: 'name', label: 'Name' },
+ { key: 'title', label: 'Title' },
+ { key: 'sku', label: 'SKU' },
+ { key: 'variant_title', label: 'Variant Title' },
+ { key: 'vendor', label: 'Vendor' },
+ { key: 'quantity', label: 'Quantity', format: 'number' },
+ { key: 'current_quantity', label: 'Current Quantity', format: 'number' },
+ { key: 'refundable_quantity', label: 'Refundable Quantity', format: 'number' },
+ { key: 'unfulfilled_quantity', label: 'Unfulfilled Quantity', format: 'number' },
+ { key: 'requires_shipping', label: 'Requires Shipping', format: 'boolean' },
+ { key: 'taxable', label: 'Taxable', format: 'boolean' },
+ { key: 'original_unit_price', label: 'Original Unit Price', format: 'number' },
+ { key: 'discounted_total', label: 'Discounted Total', format: 'number' },
+ { key: 'variant_id', label: 'Variant ID' },
+ { key: 'product_id', label: 'Product ID' },
+ ],
+ },
+ {
+ key: 'line_items_has_more',
+ label: 'Line Items Has More',
+ format: 'boolean',
+ description: 'True when the order has more than the 100 line items returned.',
+ },
+];
+
+const transactionFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Transaction ID' },
+ { key: 'kind', label: 'Kind' },
+ { key: 'status', label: 'Status' },
+ { key: 'gateway', label: 'Gateway' },
+ { key: 'formatted_gateway', label: 'Formatted Gateway' },
+ { key: 'test', label: 'Test', format: 'boolean' },
+ { key: 'amount', label: 'Amount', format: 'number' },
+ { key: 'currency_code', label: 'Currency Code' },
+ { key: 'total_unsettled', label: 'Total Unsettled', format: 'number' },
+ {
+ key: 'maximum_refundable',
+ label: 'Maximum Refundable',
+ format: 'number',
+ description:
+ 'Null for manual-gateway transactions; use calculate_refund for the refundable amount.',
+ },
+ { key: 'manually_capturable', label: 'Manually Capturable', format: 'boolean' },
+ { key: 'multi_capturable', label: 'Multi Capturable', format: 'boolean' },
+ {
+ key: 'authorization_expires_at',
+ label: 'Authorization Expires At',
+ format: 'datetime',
+ },
+ { key: 'error_code', label: 'Error Code' },
+ { key: 'payment_id', label: 'Payment ID' },
+ { key: 'parent_transaction_id', label: 'Parent Transaction ID' },
+ { key: 'order_id', label: 'Order ID' },
+ { key: 'order_name', label: 'Order Name' },
+ { key: 'created_at', label: 'Created At', format: 'datetime' },
+ { key: 'processed_at', label: 'Processed At', format: 'datetime' },
+];
+
+const refundSummaryFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Refund ID' },
+ { key: 'legacy_resource_id', label: 'Numeric ID' },
+ { key: 'note', label: 'Note' },
+ { key: 'created_at', label: 'Created At', format: 'datetime' },
+ { key: 'processed_at', label: 'Processed At', format: 'datetime' },
+ { key: 'updated_at', label: 'Updated At', format: 'datetime' },
+ { key: 'total_refunded', label: 'Total Refunded', format: 'number' },
+ { key: 'currency_code', label: 'Currency Code' },
+];
+
+const refundFields: OutputSchema['fields'] = [
+ ...refundSummaryFields,
+ { key: 'order_id', label: 'Order ID' },
+ { key: 'order_name', label: 'Order Name' },
+ {
+ key: 'refund_line_items',
+ label: 'Refund Line Items',
+ labelKey: 'title',
+ listItems: [
+ { key: 'line_item_id', label: 'Line Item ID' },
+ { key: 'title', label: 'Title' },
+ { key: 'sku', label: 'SKU' },
+ { key: 'quantity', label: 'Quantity', format: 'number' },
+ { key: 'restock_type', label: 'Restock Type' },
+ { key: 'restocked', label: 'Restocked', format: 'boolean' },
+ { key: 'subtotal', label: 'Subtotal', format: 'number' },
+ { key: 'total_tax', label: 'Total Tax', format: 'number' },
+ ],
+ },
+ {
+ key: 'transactions',
+ label: 'Transactions',
+ labelKey: 'kind',
+ listItems: [
+ { key: 'id', label: 'Transaction ID' },
+ { key: 'kind', label: 'Kind' },
+ { key: 'status', label: 'Status' },
+ { key: 'gateway', label: 'Gateway' },
+ { key: 'amount', label: 'Amount', format: 'number' },
+ ],
+ },
+];
+
+const draftOrderSummaryFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Draft Order ID' },
+ { key: 'legacy_resource_id', label: 'Numeric ID' },
+ { key: 'name', label: 'Draft Order Name' },
+ { key: 'status', label: 'Status', description: 'OPEN, INVOICE_SENT or COMPLETED.' },
+ { key: 'created_at', label: 'Created At', format: 'datetime' },
+ { key: 'updated_at', label: 'Updated At', format: 'datetime' },
+ { key: 'completed_at', label: 'Completed At', format: 'datetime' },
+ { key: 'invoice_url', label: 'Invoice URL', format: 'url' },
+ { key: 'invoice_sent_at', label: 'Invoice Sent At', format: 'datetime' },
+ { key: 'email', label: 'Email', format: 'email' },
+ { key: 'phone', label: 'Phone' },
+ { key: 'note', label: 'Note' },
+ { key: 'tags', label: 'Tags', description: 'Comma-separated.' },
+ { key: 'po_number', label: 'PO Number' },
+ { key: 'ready', label: 'Ready', format: 'boolean' },
+ { key: 'currency_code', label: 'Currency Code' },
+ { key: 'subtotal_price', label: 'Subtotal Price', format: 'number' },
+ { key: 'total_price', label: 'Total Price', format: 'number' },
+ { key: 'total_tax', label: 'Total Tax', format: 'number' },
+ { key: 'total_discounts', label: 'Total Discounts', format: 'number' },
+ { key: 'total_shipping', label: 'Total Shipping', format: 'number' },
+ { key: 'customer_id', label: 'Customer ID' },
+ { key: 'customer_name', label: 'Customer Name' },
+ {
+ key: 'order_id',
+ label: 'Order ID',
+ description: 'Set once the draft order is completed.',
+ },
+ { key: 'order_name', label: 'Order Name' },
+];
+
+const draftOrderDetailFields: OutputSchema['fields'] = [
+ ...draftOrderSummaryFields,
+ {
+ key: 'reserve_inventory_until',
+ label: 'Reserve Inventory Until',
+ format: 'datetime',
+ },
+ { key: 'tax_exempt', label: 'Tax Exempt', format: 'boolean' },
+ { key: 'taxes_included', label: 'Taxes Included', format: 'boolean' },
+ { key: 'discount_codes', label: 'Discount Codes', description: 'Comma-separated.' },
+ { key: 'applied_discount_title', label: 'Applied Discount Title' },
+ { key: 'applied_discount_value', label: 'Applied Discount Value', format: 'number' },
+ {
+ key: 'applied_discount_value_type',
+ label: 'Applied Discount Value Type',
+ description: 'PERCENTAGE or FIXED_AMOUNT.',
+ },
+ {
+ key: 'applied_discount_amount',
+ label: 'Applied Discount Amount',
+ format: 'number',
+ },
+ { key: 'payment_terms_id', label: 'Payment Terms ID' },
+ { key: 'payment_terms_name', label: 'Payment Terms Name' },
+ { key: 'payment_terms_type', label: 'Payment Terms Type' },
+ {
+ key: 'payment_terms_due_in_days',
+ label: 'Payment Terms Due In Days',
+ format: 'number',
+ },
+ { key: 'shipping_line_title', label: 'Shipping Line Title' },
+ { key: 'shipping_line_price', label: 'Shipping Line Price', format: 'number' },
+ ...shippingAddressFields,
+ {
+ key: 'line_items',
+ label: 'Line Items',
+ labelKey: 'name',
+ listItems: [
+ { key: 'id', label: 'Line Item ID' },
+ { key: 'name', label: 'Name' },
+ { key: 'title', label: 'Title' },
+ { key: 'sku', label: 'SKU' },
+ { key: 'quantity', label: 'Quantity', format: 'number' },
+ { key: 'custom', label: 'Custom Item', format: 'boolean' },
+ { key: 'original_unit_price', label: 'Original Unit Price', format: 'number' },
+ { key: 'discounted_total', label: 'Discounted Total', format: 'number' },
+ { key: 'variant_id', label: 'Variant ID' },
+ ],
+ },
+ {
+ key: 'line_items_has_more',
+ label: 'Line Items Has More',
+ format: 'boolean',
+ description: 'True when the draft order has more than the line items returned.',
+ },
+];
+
+const customerFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Customer ID' },
+ { key: 'legacy_resource_id', label: 'Numeric ID' },
+ { key: 'display_name', label: 'Display Name' },
+ { key: 'first_name', label: 'First Name' },
+ { key: 'last_name', label: 'Last Name' },
+ { key: 'email', label: 'Email', format: 'email' },
+ { key: 'email_marketing_state', label: 'Email Marketing State' },
+ { key: 'email_marketing_opt_in_level', label: 'Email Marketing Opt-in Level' },
+ {
+ key: 'email_marketing_updated_at',
+ label: 'Email Marketing Updated At',
+ format: 'datetime',
+ },
+ { key: 'phone', label: 'Phone' },
+ { key: 'note', label: 'Note' },
+ { key: 'tags', label: 'Tags', description: 'Comma-separated.' },
+ { key: 'state', label: 'Account State' },
+ { key: 'verified_email', label: 'Verified Email', format: 'boolean' },
+ { key: 'tax_exempt', label: 'Tax Exempt', format: 'boolean' },
+ { key: 'locale', label: 'Locale' },
+ { key: 'number_of_orders', label: 'Number Of Orders', format: 'number' },
+ { key: 'amount_spent', label: 'Amount Spent', format: 'number' },
+ { key: 'amount_spent_currency', label: 'Amount Spent Currency' },
+ { key: 'can_delete', label: 'Can Delete', format: 'boolean' },
+ { key: 'last_order_id', label: 'Last Order ID' },
+ { key: 'last_order_name', label: 'Last Order Name' },
+ { key: 'default_address_id', label: 'Default Address ID' },
+ ...defaultAddressFields,
+ { key: 'created_at', label: 'Created At', format: 'datetime' },
+ { key: 'updated_at', label: 'Updated At', format: 'datetime' },
+];
+
+const addressFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Address ID' },
+ { key: 'first_name', label: 'First Name' },
+ { key: 'last_name', label: 'Last Name' },
+ { key: 'name', label: 'Name' },
+ { key: 'company', label: 'Company' },
+ { key: 'address1', label: 'Address 1' },
+ { key: 'address2', label: 'Address 2' },
+ { key: 'city', label: 'City' },
+ { key: 'province', label: 'Province' },
+ { key: 'province_code', label: 'Province Code' },
+ { key: 'country', label: 'Country' },
+ { key: 'country_code', label: 'Country Code' },
+ { key: 'zip', label: 'ZIP' },
+ { key: 'phone', label: 'Phone' },
+];
+
+const abandonedCheckoutFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Abandoned Checkout ID' },
+ { key: 'name', label: 'Name' },
+ { key: 'created_at', label: 'Created At', format: 'datetime' },
+ { key: 'updated_at', label: 'Updated At', format: 'datetime' },
+ { key: 'completed_at', label: 'Completed At', format: 'datetime' },
+ {
+ key: 'recovery_url',
+ label: 'Recovery URL',
+ format: 'url',
+ description: 'Link to send to the shopper to finish the checkout.',
+ },
+ { key: 'note', label: 'Note' },
+ { key: 'discount_codes', label: 'Discount Codes', description: 'Comma-separated.' },
+ { key: 'taxes_included', label: 'Taxes Included', format: 'boolean' },
+ { key: 'currency_code', label: 'Currency Code' },
+ { key: 'subtotal_price', label: 'Subtotal Price', format: 'number' },
+ { key: 'total_price', label: 'Total Price', format: 'number' },
+ { key: 'customer_id', label: 'Customer ID' },
+ { key: 'customer_name', label: 'Customer Name' },
+ { key: 'customer_email', label: 'Customer Email', format: 'email' },
+ { key: 'shipping_country_code', label: 'Shipping Country Code' },
+];
+
+const abandonmentFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Abandonment ID' },
+ {
+ key: 'abandonment_type',
+ label: 'Abandonment Type',
+ description: 'BROWSE, CART or CHECKOUT.',
+ },
+ { key: 'most_recent_step', label: 'Most Recent Step' },
+ { key: 'created_at', label: 'Created At', format: 'datetime' },
+ { key: 'email_state', label: 'Email State' },
+ { key: 'email_sent_at', label: 'Email Sent At', format: 'datetime' },
+ { key: 'cart_url', label: 'Cart URL', format: 'url' },
+ { key: 'inventory_available', label: 'Inventory Available', format: 'boolean' },
+ { key: 'is_from_online_store', label: 'From Online Store', format: 'boolean' },
+ {
+ key: 'customer_has_no_order_since_abandonment',
+ label: 'No Order Since Abandonment',
+ format: 'boolean',
+ },
+ {
+ key: 'last_checkout_abandonment_date',
+ label: 'Last Checkout Abandonment Date',
+ format: 'datetime',
+ },
+ { key: 'customer_id', label: 'Customer ID' },
+ { key: 'customer_name', label: 'Customer Name' },
+ { key: 'customer_email', label: 'Customer Email', format: 'email' },
+ { key: 'abandoned_checkout_id', label: 'Abandoned Checkout ID' },
+ { key: 'abandoned_checkout_name', label: 'Abandoned Checkout Name' },
+ { key: 'abandoned_checkout_url', label: 'Abandoned Checkout URL', format: 'url' },
+ {
+ key: 'abandoned_checkout_total_price',
+ label: 'Abandoned Checkout Total Price',
+ format: 'number',
+ },
+];
+
+export const getShopOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'id', label: 'Shop ID' },
+ { key: 'name', label: 'Name' },
+ { key: 'email', label: 'Email', format: 'email' },
+ { key: 'contact_email', label: 'Contact Email', format: 'email' },
+ { key: 'myshopify_domain', label: 'Myshopify Domain' },
+ { key: 'url', label: 'URL', format: 'url' },
+ { key: 'primary_domain_host', label: 'Primary Domain Host' },
+ { key: 'primary_domain_url', label: 'Primary Domain URL', format: 'url' },
+ { key: 'currency_code', label: 'Currency Code' },
+ {
+ key: 'enabled_presentment_currencies',
+ label: 'Enabled Presentment Currencies',
+ },
+ { key: 'iana_timezone', label: 'IANA Timezone' },
+ { key: 'timezone_abbreviation', label: 'Timezone Abbreviation' },
+ { key: 'timezone_offset', label: 'Timezone Offset' },
+ { key: 'weight_unit', label: 'Weight Unit' },
+ { key: 'unit_system', label: 'Unit System' },
+ { key: 'taxes_included', label: 'Taxes Included', format: 'boolean' },
+ { key: 'tax_shipping', label: 'Tax Shipping', format: 'boolean' },
+ { key: 'plan_name', label: 'Plan Name' },
+ {
+ key: 'plan_partner_development',
+ label: 'Partner Development Plan',
+ format: 'boolean',
+ },
+ { key: 'plan_shopify_plus', label: 'Shopify Plus Plan', format: 'boolean' },
+ { key: 'address_city', label: 'Address City' },
+ { key: 'address_province_code', label: 'Address Province Code' },
+ { key: 'address_country_code', label: 'Address Country Code' },
+ { key: 'address_zip', label: 'Address ZIP' },
+ { key: 'created_at', label: 'Created At', format: 'datetime' },
+ redactedFieldsField,
+ ],
+};
+
+export const getGrantedAccessScopesOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'items',
+ label: 'Scopes',
+ labelKey: 'handle',
+ listItems: [
+ { key: 'handle', label: 'Handle' },
+ { key: 'description', label: 'Description' },
+ ],
+ },
+ { key: 'count', label: 'Count', format: 'number' },
+ { key: 'handles', label: 'Handles', description: 'Comma-separated scope handles.' },
+ redactedFieldsField,
+ ],
+};
+
+export const countOutputSchema: OutputSchema = { fields: countFields };
+
+export const generateCustomerActivationUrlOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'customer_id', label: 'Customer ID' },
+ {
+ key: 'account_activation_url',
+ label: 'Account Activation URL',
+ format: 'url',
+ },
+ redactedFieldsField,
+ ],
+};
+
+export const sendCustomerAccountInviteOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'customer_id', label: 'Customer ID' },
+ {
+ key: 'state',
+ label: 'Account State',
+ description: 'Null when Shopify withholds the customer record.',
+ },
+ redactedFieldsField,
+ ],
+};
+
+export const addTagsOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'id', label: 'Resource ID' },
+ { key: 'tags_added', label: 'Tags Added' },
+ {
+ key: 'tags',
+ label: 'Current Tags',
+ description: 'Null when Shopify withholds the tagged record.',
+ },
+ redactedFieldsField,
+ ],
+};
+
+export const removeTagsOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'id', label: 'Resource ID' },
+ { key: 'tags_removed', label: 'Tags Removed' },
+ {
+ key: 'tags',
+ label: 'Current Tags',
+ description: 'Null when Shopify withholds the tagged record.',
+ },
+ redactedFieldsField,
+ ],
+};
+
+export const createOrderRiskAssessmentOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'order_id', label: 'Order ID' },
+ { key: 'risk_level', label: 'Risk Level' },
+ { key: 'provider', label: 'Provider' },
+ {
+ key: 'facts',
+ label: 'Facts',
+ labelKey: 'description',
+ listItems: [
+ { key: 'description', label: 'Description' },
+ { key: 'sentiment', label: 'Sentiment' },
+ ],
+ },
+ redactedFieldsField,
+ ],
+};
+
+export const startOrderCancellationOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'order_id', label: 'Order ID' },
+ { key: 'job_id', label: 'Job ID' },
+ { key: 'job_done', label: 'Job Done', format: 'boolean' },
+ redactedFieldsField,
+ ],
+};
+
+export const getJobOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'id', label: 'Job ID' },
+ { key: 'done', label: 'Done', format: 'boolean' },
+ redactedFieldsField,
+ ],
+};
+
+export const deleteOrderOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'deleted_id', label: 'Deleted Order ID' },
+ redactedFieldsField,
+ ],
+};
+
+export const deleteDraftOrderOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'deleted_id', label: 'Deleted Draft Order ID' },
+ redactedFieldsField,
+ ],
+};
+
+export const deleteCustomerOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'deleted_customer_id', label: 'Deleted Customer ID' },
+ redactedFieldsField,
+ ],
+};
+
+export const orderSummaryOutputSchema: OutputSchema = {
+ fields: [...orderSummaryFields, redactedFieldsField],
+};
+
+export const orderOutputSchema: OutputSchema = {
+ fields: [...orderDetailFields, redactedFieldsField],
+};
+
+export const searchOrdersOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'items', label: 'Orders', labelKey: 'name', listItems: orderSummaryFields },
+ ...pageFields,
+ ],
+};
+
+export const listCustomerOrdersOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'customer_id', label: 'Customer ID' },
+ { key: 'items', label: 'Orders', labelKey: 'name', listItems: orderSummaryFields },
+ ...pageFields,
+ ],
+};
+
+export const orderTransactionOutputSchema: OutputSchema = {
+ fields: [...transactionFields, redactedFieldsField],
+};
+
+export const listOrderTransactionsOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'order_id', label: 'Order ID' },
+ { key: 'items', label: 'Transactions', labelKey: 'kind', listItems: transactionFields },
+ { key: 'count', label: 'Count', format: 'number' },
+ {
+ key: 'truncated',
+ label: 'Truncated',
+ format: 'boolean',
+ description: 'True when Shopify returned the 100-transaction maximum.',
+ },
+ redactedFieldsField,
+ ],
+};
+
+export const listTenderTransactionsOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'items',
+ label: 'Tender Transactions',
+ labelKey: 'order_name',
+ listItems: [
+ { key: 'id', label: 'Tender Transaction ID' },
+ { key: 'amount', label: 'Amount', format: 'number' },
+ { key: 'currency_code', label: 'Currency Code' },
+ { key: 'payment_method', label: 'Payment Method' },
+ { key: 'credit_card_company', label: 'Credit Card Company' },
+ { key: 'processed_at', label: 'Processed At', format: 'datetime' },
+ { key: 'remote_reference', label: 'Remote Reference' },
+ { key: 'test', label: 'Test', format: 'boolean' },
+ { key: 'order_id', label: 'Order ID' },
+ { key: 'order_name', label: 'Order Name' },
+ ],
+ },
+ ...pageFields,
+ ],
+};
+
+export const getOrderRiskAssessmentsOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'order_id', label: 'Order ID' },
+ {
+ key: 'recommendation',
+ label: 'Recommendation',
+ description: 'ACCEPT, INVESTIGATE, CANCEL or NONE.',
+ },
+ {
+ key: 'items',
+ label: 'Assessments',
+ labelKey: 'provider',
+ listItems: [
+ { key: 'risk_level', label: 'Risk Level' },
+ { key: 'provider', label: 'Provider' },
+ {
+ key: 'facts',
+ label: 'Facts',
+ labelKey: 'description',
+ listItems: [
+ { key: 'description', label: 'Description' },
+ { key: 'sentiment', label: 'Sentiment' },
+ ],
+ },
+ ],
+ },
+ { key: 'count', label: 'Count', format: 'number' },
+ redactedFieldsField,
+ ],
+};
+
+export const calculateRefundOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'order_id', label: 'Order ID' },
+ { key: 'amount', label: 'Amount', format: 'number' },
+ { key: 'currency_code', label: 'Currency Code' },
+ { key: 'presentment_amount', label: 'Presentment Amount', format: 'number' },
+ { key: 'presentment_currency_code', label: 'Presentment Currency Code' },
+ { key: 'subtotal', label: 'Subtotal', format: 'number' },
+ { key: 'presentment_subtotal', label: 'Presentment Subtotal', format: 'number' },
+ { key: 'total_tax', label: 'Total Tax', format: 'number' },
+ { key: 'presentment_total_tax', label: 'Presentment Total Tax', format: 'number' },
+ { key: 'maximum_refundable', label: 'Maximum Refundable', format: 'number' },
+ {
+ key: 'presentment_maximum_refundable',
+ label: 'Presentment Maximum Refundable',
+ format: 'number',
+ },
+ { key: 'discounted_subtotal', label: 'Discounted Subtotal', format: 'number' },
+ {
+ key: 'presentment_discounted_subtotal',
+ label: 'Presentment Discounted Subtotal',
+ format: 'number',
+ },
+ { key: 'shipping_amount', label: 'Shipping Amount', format: 'number' },
+ {
+ key: 'presentment_shipping_amount',
+ label: 'Presentment Shipping Amount',
+ format: 'number',
+ },
+ { key: 'shipping_tax', label: 'Shipping Tax', format: 'number' },
+ {
+ key: 'presentment_shipping_tax',
+ label: 'Presentment Shipping Tax',
+ format: 'number',
+ },
+ {
+ key: 'shipping_maximum_refundable',
+ label: 'Shipping Maximum Refundable',
+ format: 'number',
+ },
+ {
+ key: 'presentment_shipping_maximum_refundable',
+ label: 'Presentment Shipping Maximum Refundable',
+ format: 'number',
+ },
+ {
+ key: 'refund_line_items',
+ label: 'Refund Line Items',
+ labelKey: 'title',
+ listItems: [
+ { key: 'line_item_id', label: 'Line Item ID' },
+ { key: 'title', label: 'Title' },
+ { key: 'sku', label: 'SKU' },
+ { key: 'quantity', label: 'Quantity', format: 'number' },
+ { key: 'restock_type', label: 'Restock Type' },
+ { key: 'location_id', label: 'Location ID' },
+ { key: 'price', label: 'Price', format: 'number' },
+ { key: 'presentment_price', label: 'Presentment Price', format: 'number' },
+ { key: 'subtotal', label: 'Subtotal', format: 'number' },
+ { key: 'presentment_subtotal', label: 'Presentment Subtotal', format: 'number' },
+ { key: 'total_tax', label: 'Total Tax', format: 'number' },
+ { key: 'presentment_total_tax', label: 'Presentment Total Tax', format: 'number' },
+ ],
+ },
+ {
+ key: 'suggested_transactions',
+ label: 'Suggested Transactions',
+ labelKey: 'gateway',
+ listItems: [
+ { key: 'kind', label: 'Kind' },
+ { key: 'gateway', label: 'Gateway' },
+ {
+ key: 'parent_transaction_id',
+ label: 'Parent Transaction ID',
+ description: 'Pass as the parent of a refund transaction in create_refund.',
+ },
+ { key: 'amount', label: 'Amount', format: 'number' },
+ { key: 'currency_code', label: 'Currency Code' },
+ { key: 'presentment_amount', label: 'Presentment Amount', format: 'number' },
+ { key: 'presentment_currency_code', label: 'Presentment Currency Code' },
+ { key: 'maximum_refundable', label: 'Maximum Refundable', format: 'number' },
+ {
+ key: 'presentment_maximum_refundable',
+ label: 'Presentment Maximum Refundable',
+ format: 'number',
+ },
+ ],
+ },
+ redactedFieldsField,
+ ],
+};
+
+export const refundOutputSchema: OutputSchema = {
+ fields: [...refundFields, redactedFieldsField],
+};
+
+export const createRefundOutputSchema: OutputSchema = {
+ fields: [
+ ...refundFields,
+ {
+ key: 'order_total_refunded',
+ label: 'Order Total Refunded',
+ format: 'number',
+ description: 'Total refunded on the order after this refund.',
+ },
+ {
+ key: 'idempotency_key',
+ label: 'Idempotency Key',
+ description: 'The key Shopify used to deduplicate this refund.',
+ },
+ redactedFieldsField,
+ ],
+};
+
+export const listOrderRefundsOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'order_id', label: 'Order ID' },
+ {
+ key: 'items',
+ label: 'Refunds',
+ labelKey: 'created_at',
+ listItems: refundSummaryFields,
+ },
+ { key: 'count', label: 'Count', format: 'number' },
+ {
+ key: 'truncated',
+ label: 'Truncated',
+ format: 'boolean',
+ description: 'True when Shopify returned the 50-refund maximum.',
+ },
+ redactedFieldsField,
+ ],
+};
+
+export const draftOrderSummaryOutputSchema: OutputSchema = {
+ fields: [...draftOrderSummaryFields, redactedFieldsField],
+};
+
+export const draftOrderOutputSchema: OutputSchema = {
+ fields: [...draftOrderDetailFields, redactedFieldsField],
+};
+
+export const listDraftOrdersOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'items',
+ label: 'Draft Orders',
+ labelKey: 'name',
+ listItems: draftOrderSummaryFields,
+ },
+ ...pageFields,
+ ],
+};
+
+export const customerOutputSchema: OutputSchema = {
+ fields: [...customerFields, redactedFieldsField],
+};
+
+export const searchCustomersOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'items',
+ label: 'Customers',
+ labelKey: 'display_name',
+ listItems: customerFields,
+ },
+ ...pageFields,
+ ],
+};
+
+export const customerAddressOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'customer_id', label: 'Customer ID' },
+ ...addressFields,
+ redactedFieldsField,
+ ],
+};
+
+export const listCustomerAddressesOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'customer_id', label: 'Customer ID' },
+ {
+ key: 'items',
+ label: 'Addresses',
+ labelKey: 'address1',
+ listItems: [
+ ...addressFields,
+ { key: 'is_default', label: 'Is Default', format: 'boolean' },
+ ],
+ },
+ ...pageFields,
+ ],
+};
+
+export const deleteCustomerAddressOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'customer_id', label: 'Customer ID' },
+ { key: 'deleted_address_id', label: 'Deleted Address ID' },
+ redactedFieldsField,
+ ],
+};
+
+export const abandonmentOutputSchema: OutputSchema = {
+ fields: [...abandonmentFields, redactedFieldsField],
+};
+
+export const checkoutAbandonmentOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'found',
+ label: 'Found',
+ format: 'boolean',
+ description: 'False when Shopify has no abandonment for this checkout; other fields are then null.',
+ },
+ ...abandonmentFields,
+ redactedFieldsField,
+ ],
+};
+
+export const listAbandonedCheckoutsOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'items',
+ label: 'Abandoned Checkouts',
+ labelKey: 'name',
+ listItems: abandonedCheckoutFields,
+ },
+ ...pageFields,
+ ],
+};
diff --git a/packages/pieces/community/shopify/src/lib/output-schemas/requested-order-edits.ts b/packages/pieces/community/shopify/src/lib/output-schemas/requested-order-edits.ts
new file mode 100644
index 00000000000..13a119e30c9
--- /dev/null
+++ b/packages/pieces/community/shopify/src/lib/output-schemas/requested-order-edits.ts
@@ -0,0 +1,162 @@
+import { OutputSchema, OutputSchemaField } from '@activepieces/pieces-framework';
+
+const redactedFieldsField: OutputSchemaField = {
+ key: 'redacted_fields',
+ label: 'Redacted Fields',
+ description:
+ 'Response paths Shopify withheld, for example because the app is not approved for protected customer data.',
+};
+
+const removalFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Requested Line Item ID' },
+ { key: 'quantity', label: 'Quantity Requested', format: 'number' },
+ {
+ key: 'resolved_quantity',
+ label: 'Resolved Quantity',
+ format: 'number',
+ description: 'How much of the requested quantity has been resolved.',
+ },
+ { key: 'line_item_id', label: 'Order Line Item ID' },
+ { key: 'line_item_name', label: 'Line Item Name' },
+ { key: 'line_item_title', label: 'Line Item Title' },
+ { key: 'sku', label: 'SKU' },
+ { key: 'variant_title', label: 'Variant Title' },
+ { key: 'line_item_quantity', label: 'Line Item Ordered Quantity', format: 'number' },
+ { key: 'line_item_current_quantity', label: 'Line Item Current Quantity', format: 'number' },
+ {
+ key: 'line_item_unfulfilled_quantity',
+ label: 'Line Item Unfulfilled Quantity',
+ format: 'number',
+ },
+ { key: 'variant_id', label: 'Variant ID' },
+ { key: 'product_id', label: 'Product ID' },
+];
+
+const requestedOrderEditFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Requested Order Edit ID' },
+ { key: 'status', label: 'Status', description: 'REQUESTED, RESOLVED or DECLINED.' },
+ { key: 'requested_at', label: 'Requested At', format: 'datetime' },
+ { key: 'request_declined_at', label: 'Declined At', format: 'datetime' },
+ { key: 'request_resolved_at', label: 'Resolved At', format: 'datetime' },
+ { key: 'created_at', label: 'Created At', format: 'datetime' },
+ { key: 'updated_at', label: 'Updated At', format: 'datetime' },
+ { key: 'order_id', label: 'Order ID' },
+ { key: 'order_name', label: 'Order Name' },
+ {
+ key: 'order_requested_edit_status',
+ label: 'Order Requested Edit Status',
+ description: 'The order-level status: NONE, REQUESTED, RESOLVED or DECLINED.',
+ },
+ {
+ key: 'removals',
+ label: 'Line Items to Remove',
+ labelKey: 'line_item_name',
+ listItems: removalFields,
+ },
+ { key: 'removals_count', label: 'Removals Returned', format: 'number' },
+ {
+ key: 'removals_truncated',
+ label: 'Removals Truncated',
+ format: 'boolean',
+ description: 'True when the edit has more line items than were returned (50).',
+ },
+];
+
+export const listRequestedOrderEditsOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'order_id', label: 'Order ID' },
+ { key: 'order_name', label: 'Order Name' },
+ {
+ key: 'order_requested_edit_status',
+ label: 'Order Requested Edit Status',
+ description: 'NONE, REQUESTED (at least one is pending), RESOLVED or DECLINED.',
+ },
+ {
+ key: 'items',
+ label: 'Requested Order Edits',
+ labelKey: 'id',
+ listItems: requestedOrderEditFields,
+ },
+ { key: 'count', label: 'Count', format: 'number' },
+ { key: 'has_next_page', label: 'Has Next Page', format: 'boolean' },
+ {
+ key: 'end_cursor',
+ label: 'End Cursor',
+ description: 'Pass back as the cursor to read the next page.',
+ },
+ redactedFieldsField,
+ ],
+};
+
+export const requestedOrderEditOutputSchema: OutputSchema = {
+ fields: [...requestedOrderEditFields, redactedFieldsField],
+};
+
+export const calculateRequestedOrderEditOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'order_id', label: 'Order ID' },
+ {
+ key: 'edit_subtotal_before_target_all_discounts',
+ label: 'Subtotal Before Order-Level Discounts',
+ description: 'Shop currency.',
+ },
+ {
+ key: 'edit_order_level_discount_subtotal',
+ label: 'Order-Level Discounts',
+ description: 'Shop currency.',
+ },
+ { key: 'edit_subtotal', label: 'Subtotal', description: 'Shop currency.' },
+ {
+ key: 'edit_subtotal_with_cart_discount',
+ label: 'Subtotal With Order-Level Discounts',
+ description: 'Shop currency.',
+ },
+ { key: 'edit_total_tax', label: 'Total Tax', description: 'Shop currency.' },
+ {
+ key: 'edit_total',
+ label: 'Total',
+ description: 'Value of the removed items including tax, in the shop currency.',
+ },
+ { key: 'currency_code', label: 'Shop Currency Code' },
+ { key: 'presentment_edit_subtotal', label: 'Presentment Subtotal' },
+ { key: 'presentment_edit_total_tax', label: 'Presentment Total Tax' },
+ { key: 'presentment_edit_total', label: 'Presentment Total' },
+ { key: 'presentment_currency_code', label: 'Presentment Currency Code' },
+ {
+ key: 'removals',
+ label: 'Line Items to Remove',
+ labelKey: 'line_item_name',
+ listItems: [
+ { key: 'line_item_id', label: 'Order Line Item ID' },
+ { key: 'line_item_name', label: 'Line Item Name' },
+ { key: 'sku', label: 'SKU' },
+ {
+ key: 'line_item_unfulfilled_quantity',
+ label: 'Line Item Unfulfilled Quantity',
+ format: 'number',
+ },
+ { key: 'quantity', label: 'Quantity Removed', format: 'number' },
+ { key: 'subtotal', label: 'Subtotal', description: 'Shop currency.' },
+ { key: 'total_tax', label: 'Total Tax', description: 'Shop currency.' },
+ { key: 'presentment_subtotal', label: 'Presentment Subtotal' },
+ { key: 'presentment_total_tax', label: 'Presentment Total Tax' },
+ ],
+ },
+ { key: 'removals_count', label: 'Removals Returned', format: 'number' },
+ { key: 'removals_truncated', label: 'Removals Truncated', format: 'boolean' },
+ redactedFieldsField,
+ ],
+};
+
+export const sendPaymentMethodUpdateEmailOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'customer_id',
+ label: 'Customer ID',
+ description: 'The customer the email was sent to. Null when Shopify does not return the customer.',
+ },
+ { key: 'resource_type', label: 'Resource Type', description: 'SUBSCRIPTIONS, ORDERS or DRAFT_ORDERS.' },
+ { key: 'resource_id', label: 'Resource ID', description: 'The id sent to Shopify as the mandate resource.' },
+ redactedFieldsField,
+ ],
+};
diff --git a/packages/pieces/community/shopify/test/helpers.ts b/packages/pieces/community/shopify/test/helpers.ts
new file mode 100644
index 00000000000..7aa0d046589
--- /dev/null
+++ b/packages/pieces/community/shopify/test/helpers.ts
@@ -0,0 +1,76 @@
+import { HttpRequest, HttpResponse, httpClient } from '@activepieces/pieces-common';
+import {
+ ActionContext,
+ AppConnectionType,
+ createMockActionContext,
+ InputPropertyMap,
+ StaticPropsValue,
+} from '@activepieces/pieces-framework';
+import { vi } from 'vitest';
+import { ShopifyAuth, shopifyAuth } from '../src/lib/common/auth';
+
+export const TEST_AUTH: ShopifyAuth = {
+ type: AppConnectionType.CUSTOM_AUTH,
+ props: { shopName: 'test-shop', adminToken: 'shpat_test' },
+};
+
+export const GRAPHQL_URL = 'https://test-shop.myshopify.com/admin/api/2026-10/graphql.json';
+
+export function mockShopify({ replies }: { replies: GraphqlBody[] }): SentGraphqlRequest[] {
+ const sent: SentGraphqlRequest[] = [];
+ const queue = [...replies];
+ vi.spyOn(httpClient, 'sendRequest').mockImplementation(async (request: HttpRequest): Promise<HttpResponse> => {
+ const query = readField({ value: request.body, key: 'query' });
+ const variables = readField({ value: request.body, key: 'variables' });
+ sent.push({
+ request,
+ query: typeof query === 'string' ? query : '',
+ variables: isRecord(variables) ? variables : {},
+ });
+ const reply = queue.shift();
+ if (!reply) {
+ throw new Error(`unexpected request: ${String(query).slice(0, 80)}`);
+ }
+ return { status: 200, headers: {}, body: reply };
+ });
+ return sent;
+}
+
+export function runAction({ action, propsValue }: RunActionParams): Promise<unknown> {
+ const context: ShopifyActionContext = {
+ ...createMockActionContext<InputPropertyMap>({ propsValue }),
+ auth: TEST_AUTH,
+ };
+ return action.run(context);
+}
+
+function readField({ value, key }: { value: unknown; key: string }): unknown {
+ return isRecord(value) ? value[key] : undefined;
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
+}
+
+type ShopifyActionContext =ActionContext<typeof shopifyAuth, InputPropertyMap>;
+
+export type TestAction = {
+ run(context: ShopifyActionContext): Promise<unknown>;
+};
+
+type RunActionParams = {
+ action: TestAction;
+ propsValue: StaticPropsValue<InputPropertyMap>;
+};
+
+export type GraphqlBody = {
+ data?: Record<string, unknown> | null;
+ errors?: Record<string, unknown>[];
+ extensions?: Record<string, unknown>;
+};
+
+export type SentGraphqlRequest = {
+ request: HttpRequest;
+ query: string;
+ variables: Record<string, unknown>;
+};
diff --git a/packages/pieces/community/shopify/test/w1-orders.test.ts b/packages/pieces/community/shopify/test/w1-orders.test.ts
new file mode 100644
index 00000000000..b887fd755f6
--- /dev/null
+++ b/packages/pieces/community/shopify/test/w1-orders.test.ts
@@ -0,0 +1,310 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import '../src';
+import { shopifyAiCountCustomers } from '../src/lib/actions/ai/count-customers';
+import { shopifyAiCreateOrderWithLineItems } from '../src/lib/actions/ai/create-order-with-line-items';
+import { shopifyAiResolveRequestedOrderEdit } from '../src/lib/actions/ai/resolve-requested-order-edit';
+import { shopifyAiSendPaymentMethodUpdateEmail } from '../src/lib/actions/ai/send-payment-method-update-email';
+import { shopifyAiUpdateCustomerProfile } from '../src/lib/actions/ai/update-customer-profile';
+import { shopifyGraphqlClient } from '../src/lib/common/graphql';
+import { GRAPHQL_URL, mockShopify, runAction, TEST_AUTH } from './helpers';
+
+const PROTECTED_DENIAL = {
+ message: 'This app is not approved to access the Order object. See https://shopify.dev/docs/apps/launch/protected-customer-data for more details.',
+ path: ['orderCreate', 'order'],
+ extensions: { code: 'ACCESS_DENIED' },
+};
+
+const SEARCH_WARNING = {
+ search: [{ path: ['customersCount'], query: 'tag:vip', warnings: [{ field: 'tag', message: 'Invalid search field for this query.' }] }],
+};
+
+const CREATED_ORDER = { orderCreate: { order: { id: 'gid://shopify/Order/1', name: '#1001' }, userErrors: [] } };
+
+const LINE_ITEM = [{ variant_id: '111', quantity: 2 }];
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+describe('shopifyGraphqlClient.request', () => {
+ it('POSTs the query and variables to the shop GraphQL endpoint with the admin token', async () => {
+ const sent = mockShopify({ replies: [{ data: { shop: { id: 'gid://shopify/Shop/1' } } }] });
+
+ await shopifyGraphqlClient.request({ auth: TEST_AUTH, query: 'query { shop { id } }', variables: { a: 1 } });
+
+ expect(sent).toHaveLength(1);
+ expect(sent[0].request.method).toBe('POST');
+ expect(sent[0].request.url).toBe(GRAPHQL_URL);
+ expect(sent[0].request.headers).toEqual({ 'X-Shopify-Access-Token': 'shpat_test', 'Content-Type': 'application/json' });
+ expect(sent[0].request.body).toEqual({ query: 'query { shop { id } }', variables: { a: 1 } });
+ });
+
+ it('throws when Shopify reports a search warning instead of returning every record', async () => {
+ mockShopify({ replies: [{ data: { customersCount: { count: 4120, precision: 'EXACT' } }, extensions: SEARCH_WARNING }] });
+
+ await expect(
+ shopifyGraphqlClient.request({
+ auth: TEST_AUTH,
+ query: 'query Count($query: String) { customersCount(query: $query) { count } }',
+ variables: { query: 'tag:vip' },
+ })
+ ).rejects.toThrow('Shopify ignored part of the search query "tag:vip" (tag: Invalid search field for this query.)');
+ });
+
+ it('reports a withheld mutation result as applied, without a retry hint, when an idempotency key was used', async () => {
+ const sent = mockShopify({ replies: [{ data: { orderCreate: { order: null, userErrors: [] } }, errors: [PROTECTED_DENIAL] }] });
+
+ const message = await shopifyGraphqlClient
+ .request({
+ auth: TEST_AUTH,
+ query: 'mutation CreateOrder($order: OrderCreateOrderInput!) { orderCreate(order: $order) { order { id } } }',
+ variables: { order: { lineItems: [] } },
+ primaryPaths: ['orderCreate.order'],
+ idempotencyKey: 'key-123',
+ })
+ .then(
+ () => 'resolved',
+ (e: Error) => e.message
+ );
+
+ expect(sent[0].variables).toEqual({ order: { lineItems: [] }, idempotencyKey: 'key-123' });
+ expect(message.startsWith('Shopify APPLIED this change')).toBe(true);
+ expect(message).toContain('(orderCreate.order)');
+ expect(message).toContain('[idempotency_key used: key-123.]');
+ expect(message).not.toContain('Retry with this same idempotency_key');
+ });
+
+ it('keeps the retry hint on an ordinary failure with an idempotency key', async () => {
+ mockShopify({ replies: [{ data: null, errors: [{ message: 'Internal error' }] }] });
+
+ await expect(
+ shopifyGraphqlClient.request({
+ auth: TEST_AUTH,
+ query: 'mutation M { orderCreate { order { id } } }',
+ idempotencyKey: 'key-9',
+ })
+ ).rejects.toThrow('Retry with this same idempotency_key');
+ });
+
+ it('treats a protected-data denial on a non-primary path of a query as a redaction', async () => {
+ mockShopify({
+ replies: [
+ {
+ data: { order: { id: 'gid://shopify/Order/1', customer: null } },
+ errors: [{ ...PROTECTED_DENIAL, path: ['order', 'customer'] }],
+ },
+ ],
+ });
+
+ const result = await shopifyGraphqlClient.request({ auth: TEST_AUTH, query: 'query { order(id: "x") { id customer { id } } }' });
+
+ expect(result.redactedFields).toEqual(['order.customer']);
+ });
+});
+
+describe('count_customers', () => {
+ it('sends the filter and refuses a result where Shopify ignored the tag filter', async () => {
+ const sent = mockShopify({ replies: [{ data: { customersCount: { count: 4120, precision: 'EXACT' } }, extensions: SEARCH_WARNING }] });
+
+ await expect(runAction({ action: shopifyAiCountCustomers, propsValue: { query: 'tag:vip' } })).rejects.toThrow(
+ 'Shopify ignored part of the search query'
+ );
+ expect(sent[0].variables).toEqual({ query: 'tag:vip' });
+ });
+
+ it('returns the count when Shopify accepts the filter', async () => {
+ mockShopify({ replies: [{ data: { customersCount: { count: 7, precision: 'EXACT' } } }] });
+
+ const result = await runAction({ action: shopifyAiCountCustomers, propsValue: { query: 'created_at:>2026-01-01' } });
+
+ expect(result).toEqual({ count: 7, precision: 'EXACT', redacted_fields: [] });
+ });
+});
+
+describe('create_order_with_line_items', () => {
+ it('refuses financial_status PAID without payment_amount before calling Shopify', async () => {
+ const sent = mockShopify({ replies: [] });
+
+ await expect(
+ runAction({
+ action: shopifyAiCreateOrderWithLineItems,
+ propsValue: { line_items: LINE_ITEM, currency: 'USD', financial_status: 'PAID' },
+ })
+ ).rejects.toThrow('Set "payment_amount" (greater than 0) with financial_status PAID');
+ expect(sent).toHaveLength(0);
+ });
+
+ it('records a manual SALE transaction for a PAID order', async () => {
+ const sent = mockShopify({ replies: [{ data: CREATED_ORDER }] });
+
+ await runAction({
+ action: shopifyAiCreateOrderWithLineItems,
+ propsValue: { line_items: LINE_ITEM, currency: 'usd', financial_status: 'PAID', payment_amount: 10 },
+ });
+
+ expect(sent).toHaveLength(1);
+ expect(sent[0].variables).toEqual({
+ order: {
+ transactions: [
+ { kind: 'SALE', status: 'SUCCESS', gateway: 'manual', amountSet: { shopMoney: { amount: '10', currencyCode: 'USD' } } },
+ ],
+ lineItems: [{ variantId: 'gid://shopify/ProductVariant/111', quantity: 2 }],
+ currency: 'USD',
+ financialStatus: 'PAID',
+ },
+ options: { sendReceipt: false, sendFulfillmentReceipt: false },
+ });
+ });
+
+ it('records an AUTHORIZATION transaction for an AUTHORIZED order', async () => {
+ const sent = mockShopify({ replies: [{ data: CREATED_ORDER }] });
+
+ await runAction({
+ action: shopifyAiCreateOrderWithLineItems,
+ propsValue: { line_items: LINE_ITEM, currency: 'USD', financial_status: 'AUTHORIZED', payment_amount: 25.5 },
+ });
+
+ const order = sent[0].variables['order'];
+ expect(order).toMatchObject({
+ transactions: [
+ { kind: 'AUTHORIZATION', status: 'SUCCESS', gateway: 'manual', amountSet: { shopMoney: { amount: '25.5', currencyCode: 'USD' } } },
+ ],
+ financialStatus: 'AUTHORIZED',
+ });
+ });
+
+ it('creates an imported order fulfilled from a location with tracking numbers', async () => {
+ const sent = mockShopify({ replies: [{ data: CREATED_ORDER }] });
+
+ await runAction({
+ action: shopifyAiCreateOrderWithLineItems,
+ propsValue: {
+ line_items: LINE_ITEM,
+ fulfillment_location_id: '555',
+ tracking_numbers: ['1Z1', '1Z2'],
+ tracking_company: 'UPS',
+ },
+ });
+
+ expect(sent[0].variables).toEqual({
+ order: {
+ fulfillment: {
+ locationId: 'gid://shopify/Location/555',
+ trackingNumbers: ['1Z1', '1Z2'],
+ trackingCompany: 'UPS',
+ notifyCustomer: false,
+ },
+ fulfillmentStatus: 'FULFILLED',
+ lineItems: [{ variantId: 'gid://shopify/ProductVariant/111', quantity: 2 }],
+ },
+ options: { sendReceipt: false, sendFulfillmentReceipt: false },
+ });
+ });
+
+ it('refuses tracking numbers without a fulfillment location before calling Shopify', async () => {
+ const sent = mockShopify({ replies: [] });
+
+ await expect(
+ runAction({ action: shopifyAiCreateOrderWithLineItems, propsValue: { line_items: LINE_ITEM, tracking_numbers: ['1Z1'] } })
+ ).rejects.toThrow('Set "fulfillment_location_id" when giving tracking numbers');
+ expect(sent).toHaveLength(0);
+ });
+});
+
+describe('send_payment_method_update_email', () => {
+ it('sends the numeric order id as the mandate resource id', async () => {
+ const sent = mockShopify({
+ replies: [{ data: { paymentInstrumentSendAddEmail: { customer: { id: 'gid://shopify/Customer/9' }, userErrors: [] } } }],
+ });
+
+ const result = await runAction({
+ action: shopifyAiSendPaymentMethodUpdateEmail,
+ propsValue: { resource_type: 'ORDERS', resource_id: 'gid://shopify/Order/123' },
+ });
+
+ expect(sent[0].variables).toEqual({ mandate: { resourceType: 'ORDERS', resourceId: '123' } });
+ expect(result).toEqual({
+ customer_id: 'gid://shopify/Customer/9',
+ resource_type: 'ORDERS',
+ resource_id: '123',
+ redacted_fields: [],
+ });
+ });
+
+ it('refuses an Order id for DRAFT_ORDERS before calling Shopify', async () => {
+ const sent = mockShopify({ replies: [] });
+
+ await expect(
+ runAction({
+ action: shopifyAiSendPaymentMethodUpdateEmail,
+ propsValue: { resource_type: 'DRAFT_ORDERS', resource_id: 'gid://shopify/Order/123' },
+ })
+ ).rejects.toThrow('is an Order id, but resource type DRAFT_ORDERS needs a DraftOrder id');
+ expect(sent).toHaveLength(0);
+ });
+});
+
+describe('resolve_requested_order_edit', () => {
+ it('refuses an Order id before calling Shopify', async () => {
+ const sent = mockShopify({ replies: [] });
+
+ await expect(
+ runAction({ action: shopifyAiResolveRequestedOrderEdit, propsValue: { requested_order_edit_id: 'gid://shopify/Order/1' } })
+ ).rejects.toThrow('requested_order_edit_id "gid://shopify/Order/1" is not a RequestedOrderEdit id');
+ expect(sent).toHaveLength(0);
+ });
+});
+
+describe('update_customer_profile', () => {
+ const UPDATED = { data: { customerUpdate: { customer: { id: 'gid://shopify/Customer/7' }, userErrors: [] } } };
+
+ it('sends an empty note when clear_note is set', async () => {
+ const sent = mockShopify({ replies: [UPDATED] });
+
+ await runAction({ action: shopifyAiUpdateCustomerProfile, propsValue: { customer_id: '7', clear_note: true } });
+
+ expect(sent[0].variables).toEqual({ input: { id: 'gid://shopify/Customer/7', note: '' } });
+ });
+
+ it('sends empty tags when clear_tags is set', async () => {
+ const sent = mockShopify({ replies: [UPDATED] });
+
+ await runAction({ action: shopifyAiUpdateCustomerProfile, propsValue: { customer_id: '7', clear_tags: true } });
+
+ expect(sent[0].variables).toEqual({ input: { id: 'gid://shopify/Customer/7', tags: [] } });
+ });
+
+ it('keeps the note when an empty note is given without clear_note', async () => {
+ const sent = mockShopify({ replies: [UPDATED] });
+
+ await runAction({ action: shopifyAiUpdateCustomerProfile, propsValue: { customer_id: '7', note: '', first_name: 'Ada' } });
+
+ expect(sent[0].variables).toEqual({ input: { id: 'gid://shopify/Customer/7', firstName: 'Ada' } });
+ });
+
+ it('accepts an empty note together with clear_note', async () => {
+ const sent = mockShopify({ replies: [UPDATED] });
+
+ await runAction({ action: shopifyAiUpdateCustomerProfile, propsValue: { customer_id: '7', note: '', clear_note: true } });
+
+ expect(sent[0].variables).toEqual({ input: { id: 'gid://shopify/Customer/7', note: '' } });
+ });
+
+ it('refuses a note together with clear_note before calling Shopify', async () => {
+ const sent = mockShopify({ replies: [] });
+
+ await expect(
+ runAction({ action: shopifyAiUpdateCustomerProfile, propsValue: { customer_id: '7', note: 'VIP', clear_note: true } })
+ ).rejects.toThrow('Give either note or clear_note, not both');
+ expect(sent).toHaveLength(0);
+ });
+
+ it('refuses an update with no fields before calling Shopify', async () => {
+ const sent = mockShopify({ replies: [] });
+
+ await expect(runAction({ action: shopifyAiUpdateCustomerProfile, propsValue: { customer_id: '7' } })).rejects.toThrow(
+ 'Provide at least one field to update.'
+ );
+ expect(sent).toHaveLength(0);
+ });
+});
diff --git a/packages/pieces/community/shopify/vitest.config.ts b/packages/pieces/community/shopify/vitest.config.ts
new file mode 100644
index 00000000000..79c97261904
--- /dev/null
+++ b/packages/pieces/community/shopify/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'),
+ },
+ },
+})