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(square): manage customers, catalog, inventory, orders and payments from flows and AI agents (#16219)

Odai Ahmad89f6270326d9
diff --git a/bun.lock b/bun.lock
index 7ff5eb9c2d3..317c5f1758c 100644
--- a/bun.lock
+++ b/bun.lock
@@ -8716,7 +8716,7 @@
},
"packages/pieces/community/square": {
"name": "@activepieces/piece-square",
- "version": "0.4.7",
+ "version": "1.0.0",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
@@ -8725,6 +8725,7 @@
},
"devDependencies": {
"tslib": "2.6.2",
+ "vitest": "3.2.6",
},
},
"packages/pieces/community/stability-ai": {
diff --git a/docs/install/reference/breaking-changes.mdx b/docs/install/reference/breaking-changes.mdx
index aad1f313243..0da704c22d2 100644
--- a/docs/install/reference/breaking-changes.mdx
+++ b/docs/install/reference/breaking-changes.mdx
@@ -8,6 +8,14 @@ icon: "hammer"
### What has changed?
+#### Square 1.0.0 removes the New Invoice and New Appointment triggers
+
+Square 1.0.0 removes the **New Invoice** and **New Appointment** triggers. It also stops requesting the `INVOICES_READ`, `APPOINTMENTS_READ` and `APPOINTMENTS_WRITE` permissions, which nothing in the piece uses any more, and requests `PAYMENTS_WRITE`, `INVENTORY_READ`, `INVENTORY_WRITE` and `EMPLOYEES_READ` for the new payment, inventory and team actions.
+
+#### What you need to do
+
+Flows keep running on the Square version they were built with. If a flow starts with New Invoice or New Appointment, keep its Square trigger on its current version. To move it to 1.0.0, replace the trigger with the **Webhook** piece, subscribed in the Square Developer Console to `invoice.created` or `booking.created`. The webhook already carries the invoice or booking. To read the full record with **Custom API Call** (`GET /v2/invoices/{id}` or `GET /v2/bookings/{id}`), use a Square connection created before 1.0.0, because connections created or reconnected on 1.0.0 no longer have the invoice and appointment read permissions. Existing Square connections keep working. Reconnect Square only for the new actions that need payment, inventory or team permissions, and keep a separate older connection for invoice or booking reads.
+
#### Total CMS 1.0.0 supports Total CMS 3 only
Total CMS 0.2.0 called the Total CMS 1 and 2 API (`rw_common/plugins/stacks/total-cms/totalapi.php` with a license key), which Total CMS 3 no longer has. From 1.0.0 the piece uses the Total CMS 3 REST API. The connection now takes a **Site URL** and an **API Key** (Utilities → API Keys in the Total CMS admin, Pro edition) instead of a domain and license key.
@@ -17,6 +25,7 @@ Actions now take a Collection ID and an Object ID instead of a "CMS ID", and a b
#### What you need to do
Upgrade the site to Total CMS 3, create an API key and reconnect with the Site URL and API Key. Then upgrade each Total CMS step to 1.0.0 and map its inputs again. Steps keep running on the version they were built with until you upgrade them, and those steps stop working once the site runs Total CMS 3.
+
#### AI steps and agents stop running a model their key no longer allows
An AI provider key can limit which models it offers. Until now, a flow AI step or a flow-step agent that already named a model kept running it after an admin removed that model from the key's list. From this release the step fails with "The model … isn't allowed for this AI provider key anymore". This is checked when the step is queued and again when it runs.
diff --git a/packages/pieces/community/square/package.json b/packages/pieces/community/square/package.json
index 66c3cba63d7..30d4a82e20f 100644
--- a/packages/pieces/community/square/package.json
+++ b/packages/pieces/community/square/package.json
@@ -1,12 +1,13 @@
{
"name": "@activepieces/piece-square",
- "version": "0.4.7",
+ "version": "1.0.0",
"main": "./dist/src/index.js",
"types": "./dist/src/index.d.ts",
"scripts": {
"build": "tsc -p tsconfig.lib.json && cp package.json dist/",
"bundle": "node ../../../../dist/packages/cli/src/index.js pieces bundle",
- "lint": "eslint 'src/**/*.ts'"
+ "lint": "eslint 'src/**/*.ts'",
+ "test": "vitest run"
},
"dependencies": {
"@activepieces/pieces-common": "workspace:*",
@@ -15,6 +16,7 @@
"@activepieces/core-utils": "workspace:*"
},
"devDependencies": {
- "tslib": "2.6.2"
+ "tslib": "2.6.2",
+ "vitest": "3.2.6"
}
}
diff --git a/packages/pieces/community/square/src/i18n/translation.json b/packages/pieces/community/square/src/i18n/translation.json
index 995166f85c3..fa725f9ec7c 100644
--- a/packages/pieces/community/square/src/i18n/translation.json
+++ b/packages/pieces/community/square/src/i18n/translation.json
@@ -1,18 +1,280 @@
{
"Payment solutions for every business": "Payment solutions for every business",
- "Authentication": "Authentication",
+ "Sign in with the Square seller account you want to automate (production accounts only). Connections created before piece version 1.0.0 do not have the payment, inventory and team permissions: reconnect Square to use those actions.": "Sign in with the Square seller account you want to automate (production accounts only). Connections created before piece version 1.0.0 do not have the payment, inventory and team permissions: reconnect Square to use those actions.",
+ "Get Business Profile": "Get Business Profile",
+ "List Locations": "List Locations",
+ "List Team Members": "List Team Members",
+ "Create Customer": "Create Customer",
+ "Find Customers": "Find Customers",
+ "Get Customer": "Get Customer",
+ "Update Customer": "Update Customer",
+ "Delete Customer": "Delete Customer",
+ "Search Catalog Items": "Search Catalog Items",
+ "Get Catalog Item": "Get Catalog Item",
+ "Create Catalog Item": "Create Catalog Item",
+ "Update Item Price": "Update Item Price",
+ "Delete Catalog Item": "Delete Catalog Item",
+ "Get Inventory Count": "Get Inventory Count",
+ "Adjust Inventory": "Adjust Inventory",
+ "Set Inventory Count": "Set Inventory Count",
+ "Create Order": "Create Order",
+ "Get Order": "Get Order",
+ "Search Orders": "Search Orders",
+ "Complete or Cancel Order": "Complete or Cancel Order",
+ "Get Payment": "Get Payment",
+ "List Payments": "List Payments",
+ "Record Cash or External Payment": "Record Cash or External Payment",
+ "Refund Payment": "Refund Payment",
+ "Get Refund": "Get Refund",
+ "List Refunds": "List Refunds",
+ "Create Payment Link": "Create Payment Link",
+ "Get Customer (by ID)": "Get Customer (by ID)",
+ "Update Customer (by ID)": "Update Customer (by ID)",
+ "Delete Customer (by ID)": "Delete Customer (by ID)",
+ "Create Catalog Item (by ID)": "Create Catalog Item (by ID)",
+ "Update Item Price (by ID)": "Update Item Price (by ID)",
+ "Get Inventory Count (by ID)": "Get Inventory Count (by ID)",
+ "Adjust Inventory (by ID)": "Adjust Inventory (by ID)",
+ "Set Inventory Count (by ID)": "Set Inventory Count (by ID)",
+ "Create Order (by ID)": "Create Order (by ID)",
+ "Search Orders (by ID)": "Search Orders (by ID)",
+ "Create Payment Link (by ID)": "Create Payment Link (by ID)",
+ "Custom API Call": "Custom API Call",
+ "Gets the connected Square business: name, country, currency and main location.": "Gets the connected Square business: name, country, currency and main location.",
+ "Lists the business locations (stores) of the Square account.": "Lists the business locations (stores) of the Square account.",
+ "Lists staff members of the Square account. Needs a connection created or reconnected with piece version 1.0.0 or later.": "Lists staff members of the Square account. Needs a connection created or reconnected with piece version 1.0.0 or later.",
+ "Adds a customer profile to the Square Customer Directory.": "Adds a customer profile to the Square Customer Directory.",
+ "Searches customers by email, phone, reference ID or creation date.": "Searches customers by email, phone, reference ID or creation date.",
+ "Gets a customer profile.": "Gets a customer profile.",
+ "Changes fields on a customer profile. Empty fields keep their current value.": "Changes fields on a customer profile. Empty fields keep their current value.",
+ "Permanently deletes a customer profile.": "Permanently deletes a customer profile.",
+ "Finds products and services in the Square catalog by name, category or location.": "Finds products and services in the Square catalog by name, category or location.",
+ "Gets a catalog item with its variations and prices.": "Gets a catalog item with its variations and prices.",
+ "Adds a product or service with one price to the Square catalog.": "Adds a product or service with one price to the Square catalog.",
+ "Changes the price, SKU or name of an item variation.": "Changes the price, SKU or name of an item variation.",
+ "Permanently deletes a catalog item (with all its variations) or a single variation.": "Permanently deletes a catalog item (with all its variations) or a single variation.",
+ "Gets the stock count of an item variation. Needs a connection created or reconnected with piece version 1.0.0 or later.": "Gets the stock count of an item variation. Needs a connection created or reconnected with piece version 1.0.0 or later.",
+ "Adds or removes stock for an item variation. Needs a connection created or reconnected with piece version 1.0.0 or later.": "Adds or removes stock for an item variation. Needs a connection created or reconnected with piece version 1.0.0 or later.",
+ "Sets the in-stock count of an item variation after a stock take. Needs a connection created or reconnected with piece version 1.0.0 or later.": "Sets the in-stock count of an item variation after a stock take. Needs a connection created or reconnected with piece version 1.0.0 or later.",
+ "Creates an open order (no payment is taken).": "Creates an open order (no payment is taken).",
+ "Gets an order with its line items and totals.": "Gets an order with its line items and totals.",
+ "Finds orders by location, state, customer and creation date, newest first.": "Finds orders by location, state, customer and creation date, newest first.",
+ "Marks an open order as completed or canceled.": "Marks an open order as completed or canceled.",
+ "Gets a payment with its amount, status and card summary.": "Gets a payment with its amount, status and card summary.",
+ "Lists payments in a time range, newest first.": "Lists payments in a time range, newest first.",
+ "Records money you received outside Square (cash, check, bank transfer, another app). Never charges a card. Needs a connection created or reconnected with piece version 1.0.0 or later.": "Records money you received outside Square (cash, check, bank transfer, another app). Never charges a card. Needs a connection created or reconnected with piece version 1.0.0 or later.",
+ "Refunds all or part of a payment. Card refunds send real money back to the buyer and cannot be undone. Needs a connection created or reconnected with piece version 1.0.0 or later.": "Refunds all or part of a payment. Card refunds send real money back to the buyer and cannot be undone. Needs a connection created or reconnected with piece version 1.0.0 or later.",
+ "Gets a refund and its status.": "Gets a refund and its status.",
+ "Lists refunds in a time range, newest first.": "Lists refunds in a time range, newest first.",
+ "Creates a Square checkout link for a fixed amount that you can send to a buyer. Needs a connection created or reconnected with piece version 1.0.0 or later.": "Creates a Square checkout link for a fixed amount that you can send to a buyer. Needs a connection created or reconnected with piece version 1.0.0 or later.",
+ "Gets a customer profile by customer ID.": "Gets a customer profile by customer ID.",
+ "Changes fields on a customer profile by customer ID.": "Changes fields on a customer profile by customer ID.",
+ "Permanently deletes a customer profile by customer ID.": "Permanently deletes a customer profile by customer ID.",
+ "Adds a product or service with one price to the Square catalog, using a category ID.": "Adds a product or service with one price to the Square catalog, using a category ID.",
+ "Changes the price, SKU or name of an item variation by variation ID.": "Changes the price, SKU or name of an item variation by variation ID.",
+ "Gets stock counts for one or more item variations by ID.": "Gets stock counts for one or more item variations by ID.",
+ "Adds or removes stock for an item variation by ID.": "Adds or removes stock for an item variation by ID.",
+ "Sets the in-stock count of an item variation by ID.": "Sets the in-stock count of an item variation by ID.",
+ "Creates an open order from variation IDs or custom items.": "Creates an open order from variation IDs or custom items.",
+ "Finds orders by location IDs, state, customer ID and creation date.": "Finds orders by location IDs, state, customer ID and creation date.",
+ "Creates a Square checkout link for a fixed amount at a location ID.": "Creates a Square checkout link for a fixed amount at a location ID.",
+ "Make a custom API call to a specific endpoint": "Make a custom API call to a specific endpoint",
+ "Status": "Status",
+ "Location ID": "Location ID",
+ "Limit": "Limit",
+ "Cursor": "Cursor",
+ "First Name": "First Name",
+ "Last Name": "Last Name",
+ "Company": "Company",
+ "Nickname": "Nickname",
+ "Email": "Email",
+ "Phone": "Phone",
+ "Birthday": "Birthday",
+ "Note": "Note",
+ "Reference ID": "Reference ID",
+ "Address Line 1": "Address Line 1",
+ "Address Line 2": "Address Line 2",
+ "City": "City",
+ "State / Region": "State / Region",
+ "Postal Code": "Postal Code",
+ "Country": "Country",
+ "Idempotency Key": "Idempotency Key",
+ "Match": "Match",
+ "Created After": "Created After",
+ "Created Before": "Created Before",
+ "Customer": "Customer",
+ "Fields to Clear": "Fields to Clear",
+ "Search Text": "Search Text",
+ "Category ID": "Category ID",
+ "Item or Variation ID": "Item or Variation ID",
+ "Name": "Name",
+ "Description": "Description",
+ "Category": "Category",
+ "Variation Name": "Variation Name",
+ "Price": "Price",
+ "Currency": "Currency",
+ "SKU": "SKU",
+ "Item": "Item",
+ "Variation": "Variation",
+ "New Price": "New Price",
+ "New SKU": "New SKU",
+ "New Variation Name": "New Variation Name",
+ "Location": "Location",
+ "Reason": "Reason",
+ "Quantity": "Quantity",
+ "Quantity In Stock": "Quantity In Stock",
+ "Line Items": "Line Items",
+ "Order ID": "Order ID",
+ "States": "States",
+ "New State": "New State",
+ "Payment ID": "Payment ID",
+ "Payment Type": "Payment Type",
+ "Amount": "Amount",
+ "External Type": "External Type",
+ "External Source": "External Source",
+ "Customer ID": "Customer ID",
+ "Amount to Refund": "Amount to Refund",
+ "Refund ID": "Refund ID",
+ "Item Name": "Item Name",
+ "Payment Note": "Payment Note",
+ "Redirect URL": "Redirect URL",
+ "Variation ID": "Variation ID",
+ "Variation IDs": "Variation IDs",
+ "Location IDs": "Location IDs",
+ "Customer IDs": "Customer IDs",
+ "Method": "Method",
+ "Headers": "Headers",
+ "Query Parameters": "Query Parameters",
+ "Body Type": "Body Type",
+ "Body": "Body",
+ "Response is Binary": "Response is Binary",
+ "Return Error as Output": "Return Error as Output",
+ "Timeout": "Timeout",
+ "Follow redirects": "Follow redirects",
+ "Which locations to return.": "Which locations to return.",
+ "Square location ID (from List Locations). Leave empty to use the main location.": "Square location ID (from List Locations). Leave empty to use the main location.",
+ "How many results to return (1-200, default 50).": "How many results to return (1-200, default 50).",
+ "Next Cursor from a previous run, to get the next page. Cursors expire after about 5 minutes.": "Next Cursor from a previous run, to get the next page. Cursors expire after about 5 minutes.",
+ "Given name.": "Given name.",
+ "Family name.": "Family name.",
+ "Phone number in international format, for example +14155550123.": "Phone number in international format, for example +14155550123.",
+ "YYYY-MM-DD, or 0000-MM-DD when the year is unknown.": "YYYY-MM-DD, or 0000-MM-DD when the year is unknown.",
+ "Your own ID for this customer, for example from your CRM.": "Your own ID for this customer, for example from your CRM.",
+ "Two-letter country code, for example US.": "Two-letter country code, for example US.",
+ "Optional, up to 45 characters. Leave empty: a retried step returns the same record, but identical calls in one run (such as a loop with the same input) count as one. Set a unique value, like the loop item, to keep them separate.": "Optional, up to 45 characters. Leave empty: a retried step returns the same record, but identical calls in one run (such as a loop with the same input) count as one. Set a unique value, like the loop item, to keep them separate.",
+ "For example +14155550123.": "For example +14155550123.",
+ "Exact match, or partial match (contains) for email, phone and reference ID.": "Exact match, or partial match (contains) for email, phone and reference ID.",
+ "How many results to return (1-100, default 50).": "How many results to return (1-100, default 50).",
+ "Pick a customer. Type part of a name or email to search.": "Pick a customer. Type part of a name or email to search.",
+ "Given name. Leave empty to keep the current value.": "Given name. Leave empty to keep the current value.",
+ "Family name. Leave empty to keep the current value.": "Family name. Leave empty to keep the current value.",
+ "Leave empty to keep the current value.": "Leave empty to keep the current value.",
+ "Fields to empty on the customer. A field you also fill above is set, not cleared. Address clears the whole address.": "Fields to empty on the customer. A field you also fill above is set, not cleared. Address clears the whole address.",
+ "Words to match in the item name, SKU or description. Leave empty to list items.": "Words to match in the item name, SKU or description. Leave empty to list items.",
+ "Only items enabled at this location.": "Only items enabled at this location.",
+ "How many results to return (1-100, default 25).": "How many results to return (1-100, default 25).",
+ "The catalog item ID, or one of its variation IDs (from Search Catalog Items or an order line item).": "The catalog item ID, or one of its variation IDs (from Search Catalog Items or an order line item).",
+ "The catalog category for the item.": "The catalog category for the item.",
+ "Defaults to \"Regular\".": "Defaults to \"Regular\".",
+ "For example 12.50. Leave empty for a variable price set at checkout.": "For example 12.50. Leave empty for a variable price set at checkout.",
+ "Three-letter code such as USD. Leave empty to use your main location currency.": "Three-letter code such as USD. Leave empty to use your main location currency.",
+ "Pick a catalog item. Type to search by name.": "Pick a catalog item. Type to search by name.",
+ "The item variation (size, color, ...). Items without options have a single \"Regular\" variation.": "The item variation (size, color, ...). Items without options have a single \"Regular\" variation.",
+ "For example 12.50. Leave empty to keep the price.": "For example 12.50. Leave empty to keep the price.",
+ "Leave empty to keep the current currency.": "Leave empty to keep the current currency.",
+ "From Search Catalog Items.": "From Search Catalog Items.",
+ "Leave empty to get the count at every location.": "Leave empty to get the count at every location.",
+ "The Square location (store) to use.": "The Square location (store) to use.",
+ "How many units to add or remove, for example 5 or 1.5.": "How many units to add or remove, for example 5 or 1.5.",
+ "The counted number of units, for example 12.": "The counted number of units, for example 12.",
+ "The Square location (store) to use. Leave empty for your main location.": "The Square location (store) to use. Leave empty for your main location.",
+ "Optional. Type part of a name or email to search.": "Optional. Type part of a name or email to search.",
+ "What the order contains. Pick a catalog item, or leave Catalog Item empty and fill Custom Name and Custom Price.": "What the order contains. Pick a catalog item, or leave Catalog Item empty and fill Custom Name and Custom Price.",
+ "Your own ID for this order, for example from your web shop.": "Your own ID for this order, for example from your web shop.",
+ "Map it from the New Order trigger or a payment.": "Map it from the New Order trigger or a payment.",
+ "Leave empty to search all active locations (up to 10).": "Leave empty to search all active locations (up to 10).",
+ "Leave empty for all states.": "Leave empty for all states.",
+ "How many results to return (1-500, default 50).": "How many results to return (1-500, default 50).",
+ "Map it from the New Payment trigger or List Payments.": "Map it from the New Payment trigger or List Payments.",
+ "Leave empty for all locations.": "Leave empty for all locations.",
+ "For example 12.50.": "For example 12.50.",
+ "Leave empty to use the location currency.": "Leave empty to use the location currency.",
+ "For Other payments: how the money was received.": "For Other payments: how the money was received.",
+ "For Other payments: the provider, for example \"Venmo\" or \"Bank of X\".": "For Other payments: the provider, for example \"Venmo\" or \"Bank of X\".",
+ "Leave empty to use the main location.": "Leave empty to use the main location.",
+ "Optional order this payment pays for.": "Optional order this payment pays for.",
+ "Map it from the New Payment trigger, Get Payment or List Payments.": "Map it from the New Payment trigger, Get Payment or List Payments.",
+ "Decimal amount in the payment currency, for example 12.50. Must not exceed what is left to refund.": "Decimal amount in the payment currency, for example 12.50. Must not exceed what is left to refund.",
+ "Shown to the buyer on the refund receipt.": "Shown to the buyer on the refund receipt.",
+ "What the buyer pays for, shown on the checkout page.": "What the buyer pays for, shown on the checkout page.",
+ "Internal description, not shown to the buyer.": "Internal description, not shown to the buyer.",
+ "Added to the resulting payment.": "Added to the resulting payment.",
+ "Where to send the buyer after paying.": "Where to send the buyer after paying.",
+ "Square customer ID (from Find Customers).": "Square customer ID (from Find Customers).",
+ "Decimal amount, for example 12.50.": "Decimal amount, for example 12.50.",
+ "Three-letter code such as USD.": "Three-letter code such as USD.",
+ "Item variation ID from Search Catalog Items.": "Item variation ID from Search Catalog Items.",
+ "Item variation IDs from Search Catalog Items.": "Item variation IDs from Search Catalog Items.",
+ "How many results to return (1-1000, default 100).": "How many results to return (1-1000, default 100).",
+ "From List Locations.": "From List Locations.",
+ "Positive number of units, for example 5 or 1.5.": "Positive number of units, for example 5 or 1.5.",
+ "Optional, from Find Customers.": "Optional, from Find Customers.",
+ "Up to 10. Leave empty for all active locations.": "Up to 10. Leave empty for all active locations.",
+ "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 only": "Active only",
+ "Inactive only": "Inactive only",
+ "All": "All",
+ "Active": "Active",
+ "Inactive": "Inactive",
+ "Exact": "Exact",
+ "Partial": "Partial",
+ "Address": "Address",
+ "Stock received (adds)": "Stock received (adds)",
+ "Sold (removes)": "Sold (removes)",
+ "Damaged / waste (removes)": "Damaged / waste (removes)",
+ "Open": "Open",
+ "Completed": "Completed",
+ "Canceled": "Canceled",
+ "Draft": "Draft",
+ "Cash": "Cash",
+ "Other (outside Square)": "Other (outside Square)",
+ "Check": "Check",
+ "Bank transfer": "Bank transfer",
+ "Other gift card": "Other gift card",
+ "Crypto": "Crypto",
+ "Square cash": "Square cash",
+ "Social": "Social",
+ "External": "External",
+ "Emoney": "Emoney",
+ "Card": "Card",
+ "Stored balance": "Stored balance",
+ "Food voucher": "Food voucher",
+ "Other": "Other",
+ "Pending": "Pending",
+ "Rejected": "Rejected",
+ "Failed": "Failed",
+ "GET": "GET",
+ "POST": "POST",
+ "PATCH": "PATCH",
+ "PUT": "PUT",
+ "DELETE": "DELETE",
+ "HEAD": "HEAD",
"New Order": "New Order",
"Order Updated": "Order Updated",
"New Customer": "New Customer",
"Customer Updated": "Customer Updated",
- "New Appointment": "New Appointment",
"New Payment": "New Payment",
- "New Invoice": "New Invoice",
"Triggered when a new order is created": "Triggered when a new order is created",
"Triggered when an order is updated": "Triggered when an order is updated",
"Triggered when a customer is created": "Triggered when a customer is created",
"Triggered when a customer is updated": "Triggered when a customer is updated",
- "Triggered when a new appointment is created": "Triggered when a new appointment is created",
"Triggered when a new payment is created": "Triggered when a new payment is created",
- "Triggered when a new invoice is created": "Triggered when a new invoice is created"
+ "Include Full Order": "Include Full Order",
+ "Only fire for this location. Leave empty for all locations.": "Only fire for this location. Leave empty for all locations.",
+ "Also fetch the whole order (line items, totals, customer) and add it as \"order\" to the output.": "Also fetch the whole order (line items, totals, customer) and add it as \"order\" to the output."
}
\ No newline at end of file
diff --git a/packages/pieces/community/square/src/index.ts b/packages/pieces/community/square/src/index.ts
index fc7d344761e..f3172a6e4c2 100644
--- a/packages/pieces/community/square/src/index.ts
+++ b/packages/pieces/community/square/src/index.ts
@@ -1,25 +1,68 @@
-import { PieceAuth, createPiece } from '@activepieces/pieces-framework';
-import { PieceCategory } from '@activepieces/pieces-framework';
import crypto from 'crypto';
-import { triggers } from './lib/triggers';
+import { createCustomApiCallAction } from '@activepieces/pieces-common';
+import { createPiece, PieceCategory } from '@activepieces/pieces-framework';
import { squareAuth } from './lib/auth';
+import { squareClient } from './lib/common/client';
+import { squareShape } from './lib/common/shape';
+import { triggers } from './lib/triggers';
+import { adjustInventoryAction } from './lib/actions/adjust-inventory';
+import { adjustInventoryByIdAction } from './lib/actions/ai/adjust-inventory-by-id';
+import { createCatalogItemAction } from './lib/actions/create-catalog-item';
+import { createCatalogItemByIdAction } from './lib/actions/ai/create-catalog-item-by-id';
+import { createCustomerAction } from './lib/actions/create-customer';
+import { createOrderAction } from './lib/actions/create-order';
+import { createOrderByIdAction } from './lib/actions/ai/create-order-by-id';
+import { createPaymentLinkAction } from './lib/actions/create-payment-link';
+import { createPaymentLinkByIdAction } from './lib/actions/ai/create-payment-link-by-id';
+import { deleteCatalogObjectAction } from './lib/actions/delete-catalog-object';
+import { deleteCustomerAction } from './lib/actions/delete-customer';
+import { deleteCustomerByIdAction } from './lib/actions/ai/delete-customer-by-id';
+import { findCustomersAction } from './lib/actions/find-customers';
+import { getCatalogItemAction } from './lib/actions/get-catalog-item';
+import { getCustomerAction } from './lib/actions/get-customer';
+import { getCustomerByIdAction } from './lib/actions/ai/get-customer-by-id';
+import { getInventoryCountAction } from './lib/actions/get-inventory-count';
+import { getInventoryCountByIdAction } from './lib/actions/ai/get-inventory-count-by-id';
+import { getMerchantAction } from './lib/actions/get-merchant';
+import { getOrderAction } from './lib/actions/get-order';
+import { getPaymentAction } from './lib/actions/get-payment';
+import { getRefundAction } from './lib/actions/get-refund';
+import { listLocationsAction } from './lib/actions/list-locations';
+import { listPaymentsAction } from './lib/actions/list-payments';
+import { listRefundsAction } from './lib/actions/list-refunds';
+import { listTeamMembersAction } from './lib/actions/list-team-members';
+import { recordExternalPaymentAction } from './lib/actions/record-external-payment';
+import { refundPaymentAction } from './lib/actions/refund-payment';
+import { searchCatalogItemsAction } from './lib/actions/search-catalog-items';
+import { searchOrdersAction } from './lib/actions/search-orders';
+import { searchOrdersByIdAction } from './lib/actions/ai/search-orders-by-id';
+import { setInventoryCountAction } from './lib/actions/set-inventory-count';
+import { setInventoryCountByIdAction } from './lib/actions/ai/set-inventory-count-by-id';
+import { updateCustomerAction } from './lib/actions/update-customer';
+import { updateCustomerByIdAction } from './lib/actions/ai/update-customer-by-id';
+import { updateItemVariationPriceAction } from './lib/actions/update-item-variation-price';
+import { updateItemVariationPriceByIdAction } from './lib/actions/ai/update-item-variation-price-by-id';
+import { updateOrderStateAction } from './lib/actions/update-order-state';
export const square = createPiece({
displayName: 'Square',
description: 'Payment solutions for every business',
- minimumSupportedRelease: '0.30.0',
+ minimumSupportedRelease: '0.88.2',
logoUrl: 'https://cdn.activepieces.com/pieces/square.png',
categories: [PieceCategory.COMMERCE],
- authors: ["kishanprmr","MoShizzle","khaledmashaly","abuaboud"],
+ authors: ['kishanprmr', 'MoShizzle', 'khaledmashaly', 'abuaboud'],
auth: squareAuth,
events: {
verify: ({ webhookSecret, payload, appWebhookUrl }) => {
- const signature = payload.headers['x-square-hmacsha256-signature'];
- const hmac = crypto.createHmac('sha256', webhookSecret as string);
- hmac.update(appWebhookUrl + payload.rawBody);
- const hash = hmac.digest('base64');
- return hash === signature;
+ const header = payload.headers['x-square-hmacsha256-signature'];
+ const signature = Array.isArray(header) ? header[0] : header;
+ if (typeof signature !== 'string' || signature.length === 0 || typeof webhookSecret !== 'string' || webhookSecret.length === 0) {
+ return false;
+ }
+ const expected = crypto.createHmac('sha256', webhookSecret).update(appWebhookUrl + payload.rawBody).digest();
+ const received = Buffer.from(signature, 'base64');
+ return received.length === expected.length && crypto.timingSafeEqual(received, expected);
},
parseAndReply: ({ payload }) => {
const payloadBody = payload.body as Payload | undefined;
@@ -29,7 +72,57 @@ export const square = createPiece({
};
},
},
- actions: [],
+ actions: [
+ getMerchantAction,
+ listLocationsAction,
+ listTeamMembersAction,
+ createCustomerAction,
+ findCustomersAction,
+ getCustomerAction,
+ updateCustomerAction,
+ deleteCustomerAction,
+ searchCatalogItemsAction,
+ getCatalogItemAction,
+ createCatalogItemAction,
+ updateItemVariationPriceAction,
+ deleteCatalogObjectAction,
+ getInventoryCountAction,
+ adjustInventoryAction,
+ setInventoryCountAction,
+ createOrderAction,
+ getOrderAction,
+ searchOrdersAction,
+ updateOrderStateAction,
+ getPaymentAction,
+ listPaymentsAction,
+ recordExternalPaymentAction,
+ refundPaymentAction,
+ getRefundAction,
+ listRefundsAction,
+ createPaymentLinkAction,
+ getCustomerByIdAction,
+ updateCustomerByIdAction,
+ deleteCustomerByIdAction,
+ createCatalogItemByIdAction,
+ updateItemVariationPriceByIdAction,
+ getInventoryCountByIdAction,
+ adjustInventoryByIdAction,
+ setInventoryCountByIdAction,
+ createOrderByIdAction,
+ searchOrdersByIdAction,
+ createPaymentLinkByIdAction,
+ createCustomApiCallAction({
+ baseUrl: () => squareClient.BASE_URL,
+ auth: squareAuth,
+ authMapping: async (auth, propsValue) => {
+ squareClient.assertSquareUrl({ url: squareShape.rec({ value: propsValue, key: 'url' })['url'] });
+ return {
+ Authorization: `Bearer ${auth.access_token}`,
+ 'Square-Version': squareClient.SQUARE_VERSION,
+ };
+ },
+ }),
+ ],
triggers,
});
diff --git a/packages/pieces/community/square/src/lib/actions/adjust-inventory.ts b/packages/pieces/community/square/src/lib/actions/adjust-inventory.ts
new file mode 100644
index 00000000000..832d4a81eb3
--- /dev/null
+++ b/packages/pieces/community/square/src/lib/actions/adjust-inventory.ts
@@ -0,0 +1,57 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { squareAuth } from '../auth';
+import { squareIdempotency } from '../common/idempotency';
+import { squareInputs } from '../common/inputs';
+import { squareMoney } from '../common/money';
+import { squareOps } from '../common/operations';
+import { squareProps } from '../common/props';
+import { squareOutputSchemas } from '../output-schemas';
+
+export const adjustInventoryAction = createAction({
+ name: 'adjust_inventory',
+ classification: 'WRITE',
+ auth: squareAuth,
+ displayName: 'Adjust Inventory',
+ description: 'Adds or removes stock for an item variation. Needs a connection created or reconnected with piece version 1.0.0 or later.',
+ audience: 'human',
+ aiMetadata: {
+ description: 'Adds or removes stock for a variation picked from lists; agents use Adjust Inventory (by ID). A retried step returns the same change instead of repeating the write, and identical calls within one run (for example a loop with the same input) count as one; set Idempotency Key (for example to the loop item) to keep them separate. A new run writes again.',
+ idempotent: false,
+ },
+ props: {
+ item: squareProps.catalogItem({ required: true }),
+ variation_id: squareProps.variation({ required: true }),
+ location_id: squareProps.location({ required: true }),
+ reason: reasonProp(),
+ quantity: Property.ShortText({ displayName: 'Quantity', description: 'How many units to add or remove, for example 5 or 1.5.', required: true }),
+ idempotency_key: squareProps.idempotencyKey(),
+ },
+ outputSchema: squareOutputSchemas.inventoryCounts,
+ async run(context) {
+ const p = context.propsValue;
+ const change = squareOps.adjustmentChange({
+ variationId: squareInputs.requireId({ value: p.variation_id, label: 'Variation' }),
+ locationId: squareInputs.requireId({ value: p.location_id, label: 'Location' }),
+ quantity: squareMoney.quantity({ value: p.quantity, label: 'Quantity' }),
+ reason: squareInputs.requireText({ value: p.reason, label: 'Reason' }),
+ });
+ return squareIdempotency.execute({ context, action: 'adjust_inventory', input: change, send: ({ idempotencyKey }) => squareOps.changeInventory({ auth: context.auth, change: { ...change, adjustment: { ...change.adjustment, occurred_at: new Date().toISOString() } }, idempotencyKey }) });
+ },
+});
+
+function reasonProp() {
+ return Property.StaticDropdown({
+ displayName: 'Reason',
+ required: true,
+ defaultValue: 'RECEIVED',
+ options: {
+ options: [
+ { label: 'Stock received (adds)', value: 'RECEIVED' },
+ { label: 'Sold (removes)', value: 'SOLD' },
+ { label: 'Damaged / waste (removes)', value: 'WASTE' },
+ ],
+ },
+ });
+}
+
+export const inventoryReasonProp = reasonProp;
diff --git a/packages/pieces/community/square/src/lib/actions/ai/adjust-inventory-by-id.ts b/packages/pieces/community/square/src/lib/actions/ai/adjust-inventory-by-id.ts
new file mode 100644
index 00000000000..7509079dd7c
--- /dev/null
+++ b/packages/pieces/community/square/src/lib/actions/ai/adjust-inventory-by-id.ts
@@ -0,0 +1,41 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { squareAuth } from '../../auth';
+import { squareIdempotency } from '../../common/idempotency';
+import { squareInputs } from '../../common/inputs';
+import { squareMoney } from '../../common/money';
+import { squareOps } from '../../common/operations';
+import { squareProps } from '../../common/props';
+import { squareOutputSchemas } from '../../output-schemas';
+import { inventoryReasonProp } from '../adjust-inventory';
+
+export const adjustInventoryByIdAction = createAction({
+ name: 'adjust_inventory_by_id',
+ classification: 'WRITE',
+ auth: squareAuth,
+ displayName: 'Adjust Inventory (by ID)',
+ description: 'Adds or removes stock for an item variation by ID.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Changes stock relative to the current count: RECEIVED adds the quantity to IN_STOCK, SOLD or WASTE removes it. Use Set Inventory Count (by ID) to set an absolute count after a stock take. Needs INVENTORY_WRITE (reconnect older connections). A retried step returns the same change instead of repeating the write, and identical calls within one run (for example a loop with the same input) count as one; set Idempotency Key (for example to the loop item) to keep them separate. A new run writes again.',
+ idempotent: false,
+ },
+ props: {
+ variation_id: squareProps.idText({ displayName: 'Variation ID', description: 'Item variation ID from Search Catalog Items.' }),
+ location_id: squareProps.idText({ displayName: 'Location ID', description: 'From List Locations.' }),
+ reason: inventoryReasonProp(),
+ quantity: Property.ShortText({ displayName: 'Quantity', description: 'Positive number of units, for example 5 or 1.5.', required: true }),
+ idempotency_key: squareProps.idempotencyKey(),
+ },
+ outputSchema: squareOutputSchemas.inventoryCounts,
+ async run(context) {
+ const p = context.propsValue;
+ const change = squareOps.adjustmentChange({
+ variationId: squareInputs.requireId({ value: p.variation_id, label: 'Variation ID' }),
+ locationId: squareInputs.requireId({ value: p.location_id, label: 'Location ID' }),
+ quantity: squareMoney.quantity({ value: p.quantity, label: 'Quantity' }),
+ reason: squareInputs.requireText({ value: p.reason, label: 'Reason' }),
+ });
+ return squareIdempotency.execute({ context, action: 'adjust_inventory', input: change, send: ({ idempotencyKey }) => squareOps.changeInventory({ auth: context.auth, change: { ...change, adjustment: { ...change.adjustment, occurred_at: new Date().toISOString() } }, idempotencyKey }) });
+ },
+});
diff --git a/packages/pieces/community/square/src/lib/actions/ai/create-catalog-item-by-id.ts b/packages/pieces/community/square/src/lib/actions/ai/create-catalog-item-by-id.ts
new file mode 100644
index 00000000000..21031e8715d
--- /dev/null
+++ b/packages/pieces/community/square/src/lib/actions/ai/create-catalog-item-by-id.ts
@@ -0,0 +1,35 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { squareAuth } from '../../auth';
+import { squareIdempotency } from '../../common/idempotency';
+import { squareOps } from '../../common/operations';
+import { squareProps } from '../../common/props';
+import { squareOutputSchemas } from '../../output-schemas';
+
+export const createCatalogItemByIdAction = createAction({
+ name: 'create_catalog_item_by_id',
+ classification: 'WRITE',
+ auth: squareAuth,
+ displayName: 'Create Catalog Item (by ID)',
+ description: 'Adds a product or service with one price to the Square catalog, using a category ID.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Creates a Square catalog item with one variation (name, optional price as a decimal like "12.50", SKU, category ID). Price uses the main location currency unless Currency is given; no price means variable pricing. Search Catalog Items first to avoid duplicates. A retried step returns the same item instead of repeating the write, and identical calls within one run (for example a loop with the same input) count as one; set Idempotency Key (for example to the loop item) to keep them separate. A new run writes again.',
+ idempotent: false,
+ },
+ props: {
+ name: Property.ShortText({ displayName: 'Name', required: true }),
+ description: Property.LongText({ displayName: 'Description', required: false }),
+ category_id: Property.ShortText({ displayName: 'Category ID', required: false }),
+ variation_name: Property.ShortText({ displayName: 'Variation Name', description: 'Defaults to "Regular".', required: false }),
+ price: Property.ShortText({ displayName: 'Price', description: 'Decimal amount, for example 12.50.', required: false }),
+ currency: Property.ShortText({ displayName: 'Currency', description: 'Three-letter code such as USD.', required: false }),
+ sku: Property.ShortText({ displayName: 'SKU', required: false }),
+ idempotency_key: squareProps.idempotencyKey(),
+ },
+ outputSchema: squareOutputSchemas.catalogItem,
+ async run(context) {
+ const { idempotency_key: _ignored, ...input } = context.propsValue;
+ return squareIdempotency.execute({ context, action: 'create_catalog_item', input, send: ({ idempotencyKey }) => squareOps.createCatalogItem({ auth: context.auth, props: context.propsValue, idempotencyKey }) });
+ },
+});
diff --git a/packages/pieces/community/square/src/lib/actions/ai/create-order-by-id.ts b/packages/pieces/community/square/src/lib/actions/ai/create-order-by-id.ts
new file mode 100644
index 00000000000..518fb289b91
--- /dev/null
+++ b/packages/pieces/community/square/src/lib/actions/ai/create-order-by-id.ts
@@ -0,0 +1,57 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { squareAuth } from '../../auth';
+import { squareIdempotency } from '../../common/idempotency';
+import { squareInputs } from '../../common/inputs';
+import { squareOps } from '../../common/operations';
+import { squareProps } from '../../common/props';
+import { squareOutputSchemas } from '../../output-schemas';
+
+export const createOrderByIdAction = createAction({
+ name: 'create_order_by_id',
+ classification: 'WRITE',
+ auth: squareAuth,
+ displayName: 'Create Order (by ID)',
+ description: 'Creates an open order from variation IDs or custom items.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Creates an OPEN Square order (no payment taken). Each line item is either a catalog variation ID (from Search Catalog Items) with a quantity, or a custom name plus a decimal price like "12.50" in the location currency. Orders cannot be deleted, only canceled with Update Order State. A retried step returns the same order instead of repeating the write, and identical calls within one run (for example a loop with the same input) count as one; set Idempotency Key (for example to the loop item) to keep them separate. A new run writes again.',
+ idempotent: false,
+ },
+ props: {
+ location_id: squareProps.locationIdText(),
+ customer_id: Property.ShortText({ displayName: 'Customer ID', description: 'Optional, from Find Customers.', required: false }),
+ line_items: Property.Array({
+ displayName: 'Line Items',
+ required: true,
+ properties: {
+ variation_id: Property.ShortText({ displayName: 'Variation ID', description: 'Catalog item variation ID. Leave empty for a custom item.', required: false }),
+ name: Property.ShortText({ displayName: 'Custom Name', required: false }),
+ price: Property.ShortText({ displayName: 'Price', description: 'Unit price as a decimal, required for a custom item; optional override for a catalog item.', required: false }),
+ quantity: Property.ShortText({ displayName: 'Quantity', description: 'Whole number, defaults to 1.', required: false }),
+ note: Property.ShortText({ displayName: 'Note', required: false }),
+ },
+ }),
+ reference_id: Property.ShortText({ displayName: 'Reference ID', required: false }),
+ idempotency_key: squareProps.idempotencyKey(),
+ },
+ outputSchema: squareOutputSchemas.order,
+ async run(context) {
+ const p = context.propsValue;
+ const input = { location_id: p.location_id, customer_id: p.customer_id, items: p.line_items, reference_id: p.reference_id };
+ return squareIdempotency.execute({
+ context,
+ action: 'create_order',
+ input,
+ send: ({ idempotencyKey }) =>
+ squareOps.createOrder({
+ auth: context.auth,
+ locationId: squareInputs.optionalId({ value: p.location_id, label: 'Location ID' }),
+ customerId: squareInputs.optionalId({ value: p.customer_id, label: 'Customer ID' }),
+ referenceId: squareInputs.text(p.reference_id),
+ items: p.line_items,
+ idempotencyKey,
+ }),
+ });
+ },
+});
diff --git a/packages/pieces/community/square/src/lib/actions/ai/create-payment-link-by-id.ts b/packages/pieces/community/square/src/lib/actions/ai/create-payment-link-by-id.ts
new file mode 100644
index 00000000000..00a81e06752
--- /dev/null
+++ b/packages/pieces/community/square/src/lib/actions/ai/create-payment-link-by-id.ts
@@ -0,0 +1,27 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { squareAuth } from '../../auth';
+import { squareProps } from '../../common/props';
+import { squareOutputSchemas } from '../../output-schemas';
+import { paymentLinkShared } from '../create-payment-link';
+
+export const createPaymentLinkByIdAction = createAction({
+ name: 'create_payment_link_by_id',
+ classification: 'WRITE',
+ auth: squareAuth,
+ displayName: 'Create Payment Link (by ID)',
+ description: 'Creates a Square checkout link for a fixed amount at a location ID.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Creates a Square quick-pay checkout link (URL) for one named item at a fixed decimal amount like "12.50", at a location ID (empty = main location). It only creates the link; nothing is sent to anyone and no money moves until a buyer pays. Needs PAYMENTS_WRITE (reconnect older connections). A retried step returns the same link instead of repeating the write, and identical calls within one run (for example a loop with the same input) count as one; set Idempotency Key (for example to the loop item) to keep them separate. A new run writes again.',
+ idempotent: false,
+ },
+ props: {
+ location_id: squareProps.locationIdText(),
+ ...paymentLinkShared.linkProps(),
+ },
+ outputSchema: squareOutputSchemas.paymentLink,
+ async run(context) {
+ return paymentLinkShared.runCreateLink({ context, locationLabel: 'Location ID' });
+ },
+});
diff --git a/packages/pieces/community/square/src/lib/actions/ai/delete-customer-by-id.ts b/packages/pieces/community/square/src/lib/actions/ai/delete-customer-by-id.ts
new file mode 100644
index 00000000000..fd78716bbbe
--- /dev/null
+++ b/packages/pieces/community/square/src/lib/actions/ai/delete-customer-by-id.ts
@@ -0,0 +1,28 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { squareAuth } from '../../auth';
+import { squareInputs } from '../../common/inputs';
+import { squareOps } from '../../common/operations';
+import { squareProps } from '../../common/props';
+import { squareOutputSchemas } from '../../output-schemas';
+
+export const deleteCustomerByIdAction = createAction({
+ name: 'delete_customer_by_id',
+ classification: 'DESTRUCTIVE',
+ auth: squareAuth,
+ displayName: 'Delete Customer (by ID)',
+ description: 'Permanently deletes a customer profile by customer ID.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Permanently deletes a Square customer by customer ID, including it from the Customer Directory. Cannot be undone; prefer Update Customer (by ID) when the user only wants to change details. A second call fails with not found.',
+ idempotent: false,
+ },
+ props: {
+ customer_id: squareProps.idText({ displayName: 'Customer ID', description: 'Square customer ID (from Find Customers).' }),
+ },
+ outputSchema: squareOutputSchemas.deleted,
+ async run(context) {
+ const customerId = squareInputs.requireId({ value: context.propsValue.customer_id, label: 'Customer ID' });
+ return squareOps.deleteCustomer({ auth: context.auth, customerId });
+ },
+});
diff --git a/packages/pieces/community/square/src/lib/actions/ai/get-customer-by-id.ts b/packages/pieces/community/square/src/lib/actions/ai/get-customer-by-id.ts
new file mode 100644
index 00000000000..828b78d1a41
--- /dev/null
+++ b/packages/pieces/community/square/src/lib/actions/ai/get-customer-by-id.ts
@@ -0,0 +1,28 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { squareAuth } from '../../auth';
+import { squareInputs } from '../../common/inputs';
+import { squareOps } from '../../common/operations';
+import { squareProps } from '../../common/props';
+import { squareOutputSchemas } from '../../output-schemas';
+
+export const getCustomerByIdAction = createAction({
+ name: 'get_customer_by_id',
+ classification: 'READ',
+ auth: squareAuth,
+ displayName: 'Get Customer (by ID)',
+ description: 'Gets a customer profile by customer ID.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Reads one Square customer (contact details, address, notes, version) by customer ID, as returned by Find Customers or a customer trigger. Read-only and safe to retry.',
+ idempotent: true,
+ },
+ props: {
+ customer_id: squareProps.idText({ displayName: 'Customer ID', description: 'Square customer ID (from Find Customers).' }),
+ },
+ outputSchema: squareOutputSchemas.customer,
+ async run(context) {
+ const customerId = squareInputs.requireId({ value: context.propsValue.customer_id, label: 'Customer ID' });
+ return squareOps.getCustomer({ auth: context.auth, customerId });
+ },
+});
diff --git a/packages/pieces/community/square/src/lib/actions/ai/get-inventory-count-by-id.ts b/packages/pieces/community/square/src/lib/actions/ai/get-inventory-count-by-id.ts
new file mode 100644
index 00000000000..04af34f54b9
--- /dev/null
+++ b/packages/pieces/community/square/src/lib/actions/ai/get-inventory-count-by-id.ts
@@ -0,0 +1,38 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { squareAuth } from '../../auth';
+import { squareInputs } from '../../common/inputs';
+import { squareOps } from '../../common/operations';
+import { squareProps } from '../../common/props';
+import { squareOutputSchemas } from '../../output-schemas';
+
+export const getInventoryCountByIdAction = createAction({
+ name: 'get_inventory_count_by_id',
+ classification: 'READ',
+ auth: squareAuth,
+ displayName: 'Get Inventory Count (by ID)',
+ description: 'Gets stock counts for one or more item variations by ID.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Reads current stock counts (quantity per location and state such as IN_STOCK) for up to 100 variation IDs, optionally limited to one location. A variation that was never counted returns no rows. Needs the INVENTORY_READ permission (reconnect older connections). Read-only and safe to retry.',
+ idempotent: true,
+ },
+ props: {
+ variation_ids: Property.Array({ displayName: 'Variation IDs', description: 'Item variation IDs from Search Catalog Items.', required: true }),
+ location_id: Property.ShortText({ displayName: 'Location ID', description: 'Leave empty for all locations.', required: false }),
+ limit: squareProps.limitProp({ max: 1000, fallback: 100 }),
+ cursor: squareProps.cursorProp(),
+ },
+ outputSchema: squareOutputSchemas.inventoryCounts,
+ async run(context) {
+ const variationIds = squareInputs.idList({ value: context.propsValue.variation_ids, label: 'Variation IDs', max: 100 });
+ const locationId = squareInputs.optionalId({ value: context.propsValue.location_id, label: 'Location ID' });
+ return squareOps.getInventory({
+ auth: context.auth,
+ variationIds,
+ locationIds: locationId ? [locationId] : [],
+ limit: squareInputs.limit({ value: context.propsValue.limit, fallback: 100, max: 1000 }),
+ cursor: squareInputs.cursor(context.propsValue.cursor),
+ });
+ },
+});
diff --git a/packages/pieces/community/square/src/lib/actions/ai/search-orders-by-id.ts b/packages/pieces/community/square/src/lib/actions/ai/search-orders-by-id.ts
new file mode 100644
index 00000000000..e4c9f4332c6
--- /dev/null
+++ b/packages/pieces/community/square/src/lib/actions/ai/search-orders-by-id.ts
@@ -0,0 +1,44 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { squareAuth } from '../../auth';
+import { squareInputs } from '../../common/inputs';
+import { squareOps } from '../../common/operations';
+import { squareProps } from '../../common/props';
+import { squareOutputSchemas } from '../../output-schemas';
+import { orderStatesSelect } from '../search-orders';
+
+export const searchOrdersByIdAction = createAction({
+ name: 'search_orders_by_id',
+ classification: 'SEARCH',
+ auth: squareAuth,
+ displayName: 'Search Orders (by ID)',
+ description: 'Finds orders by location IDs, state, customer ID and creation date.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Searches Square orders newest first and returns one page with totals and line items. Filter by up to 10 location IDs (empty = all active locations), states (OPEN, COMPLETED, CANCELED, DRAFT), customer IDs and a created-at range (ISO 8601). Use Next Cursor within about 5 minutes for more. Read-only and safe to retry.',
+ idempotent: true,
+ },
+ props: {
+ location_ids: Property.Array({ displayName: 'Location IDs', description: 'Up to 10. Leave empty for all active locations.', required: false }),
+ states: orderStatesSelect(),
+ customer_ids: Property.Array({ displayName: 'Customer IDs', required: false }),
+ created_after: Property.DateTime({ displayName: 'Created After', required: false }),
+ created_before: Property.DateTime({ displayName: 'Created Before', required: false }),
+ limit: squareProps.limitProp({ max: 500, fallback: 50 }),
+ cursor: squareProps.cursorProp(),
+ },
+ outputSchema: squareOutputSchemas.orders,
+ async run(context) {
+ const p = context.propsValue;
+ return squareOps.searchOrders({
+ auth: context.auth,
+ locationIds: squareInputs.idList({ value: p.location_ids, label: 'Location IDs', max: 10 }),
+ states: Array.isArray(p.states) ? p.states.filter((s): s is string => typeof s === 'string') : [],
+ createdAfter: squareInputs.dateTime({ value: p.created_after, label: 'Created After' }),
+ createdBefore: squareInputs.dateTime({ value: p.created_before, label: 'Created Before' }),
+ customerIds: squareInputs.idList({ value: p.customer_ids, label: 'Customer IDs', max: 10 }),
+ limit: squareInputs.limit({ value: p.limit, fallback: 50, max: 500 }),
+ cursor: squareInputs.cursor(p.cursor),
+ });
+ },
+});
diff --git a/packages/pieces/community/square/src/lib/actions/ai/set-inventory-count-by-id.ts b/packages/pieces/community/square/src/lib/actions/ai/set-inventory-count-by-id.ts
new file mode 100644
index 00000000000..6ad5e9394a0
--- /dev/null
+++ b/packages/pieces/community/square/src/lib/actions/ai/set-inventory-count-by-id.ts
@@ -0,0 +1,37 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { squareAuth } from '../../auth';
+import { squareIdempotency } from '../../common/idempotency';
+import { squareInputs } from '../../common/inputs';
+import { squareMoney } from '../../common/money';
+import { squareOps } from '../../common/operations';
+import { squareProps } from '../../common/props';
+import { squareOutputSchemas } from '../../output-schemas';
+
+export const setInventoryCountByIdAction = createAction({
+ name: 'set_inventory_count_by_id',
+ classification: 'WRITE',
+ auth: squareAuth,
+ displayName: 'Set Inventory Count (by ID)',
+ description: 'Sets the in-stock count of an item variation by ID.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Records a physical count: sets the IN_STOCK quantity of one variation at one location to an absolute number (0 allowed). Use Adjust Inventory (by ID) for relative changes. Needs INVENTORY_WRITE (reconnect older connections). Setting the same count again is safe to retry.',
+ idempotent: true,
+ },
+ props: {
+ variation_id: squareProps.idText({ displayName: 'Variation ID', description: 'Item variation ID from Search Catalog Items.' }),
+ location_id: squareProps.idText({ displayName: 'Location ID', description: 'From List Locations.' }),
+ quantity: Property.ShortText({ displayName: 'Quantity In Stock', description: 'The counted number of units, for example 12.', required: true }),
+ },
+ outputSchema: squareOutputSchemas.inventoryCounts,
+ async run(context) {
+ const p = context.propsValue;
+ const change = squareOps.physicalCountChange({
+ variationId: squareInputs.requireId({ value: p.variation_id, label: 'Variation ID' }),
+ locationId: squareInputs.requireId({ value: p.location_id, label: 'Location ID' }),
+ quantity: squareMoney.quantity({ value: p.quantity, label: 'Quantity In Stock', allowZero: true }),
+ });
+ return squareIdempotency.execute({ context, action: 'set_inventory_count', input: change, send: ({ idempotencyKey }) => squareOps.changeInventory({ auth: context.auth, change: { ...change, physical_count: { ...change.physical_count, occurred_at: new Date().toISOString() } }, idempotencyKey }) });
+ },
+});
diff --git a/packages/pieces/community/square/src/lib/actions/ai/update-customer-by-id.ts b/packages/pieces/community/square/src/lib/actions/ai/update-customer-by-id.ts
new file mode 100644
index 00000000000..183fc90cb56
--- /dev/null
+++ b/packages/pieces/community/square/src/lib/actions/ai/update-customer-by-id.ts
@@ -0,0 +1,30 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { squareAuth } from '../../auth';
+import { squareInputs } from '../../common/inputs';
+import { squareOps } from '../../common/operations';
+import { squareProps } from '../../common/props';
+import { squareOutputSchemas } from '../../output-schemas';
+
+export const updateCustomerByIdAction = createAction({
+ name: 'update_customer_by_id',
+ classification: 'WRITE',
+ auth: squareAuth,
+ displayName: 'Update Customer (by ID)',
+ description: 'Changes fields on a customer profile by customer ID.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Updates a Square customer by customer ID: only the fields you pass change, and Fields to Clear empties fields. It reads the current version first, so it does not overwrite concurrent edits silently. Setting the same values again is safe to retry.',
+ idempotent: true,
+ },
+ props: {
+ customer_id: squareProps.idText({ displayName: 'Customer ID', description: 'Square customer ID (from Find Customers).' }),
+ ...squareProps.customerFields({ forUpdate: true }),
+ clear_fields: squareProps.clearCustomerFields(),
+ },
+ outputSchema: squareOutputSchemas.customer,
+ async run(context) {
+ const customerId = squareInputs.requireId({ value: context.propsValue.customer_id, label: 'Customer ID' });
+ return squareOps.updateCustomer({ auth: context.auth, customerId, props: context.propsValue });
+ },
+});
diff --git a/packages/pieces/community/square/src/lib/actions/ai/update-item-variation-price-by-id.ts b/packages/pieces/community/square/src/lib/actions/ai/update-item-variation-price-by-id.ts
new file mode 100644
index 00000000000..702513eadfd
--- /dev/null
+++ b/packages/pieces/community/square/src/lib/actions/ai/update-item-variation-price-by-id.ts
@@ -0,0 +1,33 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { squareAuth } from '../../auth';
+import { squareIdempotency } from '../../common/idempotency';
+import { squareInputs } from '../../common/inputs';
+import { squareOps } from '../../common/operations';
+import { squareProps } from '../../common/props';
+import { squareOutputSchemas } from '../../output-schemas';
+
+export const updateItemVariationPriceByIdAction = createAction({
+ name: 'update_item_variation_price_by_id',
+ classification: 'WRITE',
+ auth: squareAuth,
+ displayName: 'Update Item Price (by ID)',
+ description: 'Changes the price, SKU or name of an item variation by variation ID.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Sets the price (decimal string like "12.50"), SKU and/or name of one Square item variation by variation ID (from Search Catalog Items > variations, not the item ID). Reads the current version first. Setting the same values again is safe to retry.',
+ idempotent: true,
+ },
+ props: {
+ variation_id: squareProps.idText({ displayName: 'Variation ID', description: 'Item variation ID from Search Catalog Items.' }),
+ price: Property.ShortText({ displayName: 'New Price', description: 'Decimal amount, for example 12.50.', required: false }),
+ currency: Property.ShortText({ displayName: 'Currency', description: 'Leave empty to keep the current currency.', required: false }),
+ sku: Property.ShortText({ displayName: 'New SKU', required: false }),
+ name: Property.ShortText({ displayName: 'New Variation Name', required: false }),
+ },
+ outputSchema: squareOutputSchemas.variation,
+ async run(context) {
+ const variationId = squareInputs.requireId({ value: context.propsValue.variation_id, label: 'Variation ID' });
+ return squareIdempotency.execute({ context, action: 'update_item_variation_price', input: context.propsValue, send: ({ idempotencyKey }) => squareOps.updateVariation({ auth: context.auth, variationId, props: context.propsValue, idempotencyKey }) });
+ },
+});
diff --git a/packages/pieces/community/square/src/lib/actions/create-catalog-item.ts b/packages/pieces/community/square/src/lib/actions/create-catalog-item.ts
new file mode 100644
index 00000000000..5389b51386e
--- /dev/null
+++ b/packages/pieces/community/square/src/lib/actions/create-catalog-item.ts
@@ -0,0 +1,34 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { squareAuth } from '../auth';
+import { squareIdempotency } from '../common/idempotency';
+import { squareOps } from '../common/operations';
+import { squareProps } from '../common/props';
+import { squareOutputSchemas } from '../output-schemas';
+
+export const createCatalogItemAction = createAction({
+ name: 'create_catalog_item',
+ classification: 'WRITE',
+ auth: squareAuth,
+ displayName: 'Create Catalog Item',
+ description: 'Adds a product or service with one price to the Square catalog.',
+ audience: 'human',
+ aiMetadata: {
+ description: 'Creates a catalog item with one variation; agents use Create Catalog Item (by ID). A retried step returns the same item instead of repeating the write, and identical calls within one run (for example a loop with the same input) count as one; set Idempotency Key (for example to the loop item) to keep them separate. A new run writes again.',
+ idempotent: false,
+ },
+ props: {
+ name: Property.ShortText({ displayName: 'Name', required: true }),
+ description: Property.LongText({ displayName: 'Description', required: false }),
+ category_id: squareProps.category({ required: false }),
+ variation_name: Property.ShortText({ displayName: 'Variation Name', description: 'Defaults to "Regular".', required: false }),
+ price: Property.ShortText({ displayName: 'Price', description: 'For example 12.50. Leave empty for a variable price set at checkout.', required: false }),
+ currency: Property.ShortText({ displayName: 'Currency', description: 'Three-letter code such as USD. Leave empty to use your main location currency.', required: false }),
+ sku: Property.ShortText({ displayName: 'SKU', required: false }),
+ idempotency_key: squareProps.idempotencyKey(),
+ },
+ outputSchema: squareOutputSchemas.catalogItem,
+ async run(context) {
+ const { idempotency_key: _ignored, ...input } = context.propsValue;
+ return squareIdempotency.execute({ context, action: 'create_catalog_item', input, send: ({ idempotencyKey }) => squareOps.createCatalogItem({ auth: context.auth, props: context.propsValue, idempotencyKey }) });
+ },
+});
diff --git a/packages/pieces/community/square/src/lib/actions/create-customer.ts b/packages/pieces/community/square/src/lib/actions/create-customer.ts
new file mode 100644
index 00000000000..2b902f81a1e
--- /dev/null
+++ b/packages/pieces/community/square/src/lib/actions/create-customer.ts
@@ -0,0 +1,48 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { squareAuth } from '../auth';
+import { squareClient } from '../common/client';
+import { squareIdempotency } from '../common/idempotency';
+import { squareOps } from '../common/operations';
+import { squareProps } from '../common/props';
+import { squareShape } from '../common/shape';
+import { squareOutputSchemas } from '../output-schemas';
+
+export const createCustomerAction = createAction({
+ name: 'create_customer',
+ classification: 'WRITE',
+ auth: squareAuth,
+ displayName: 'Create Customer',
+ description: 'Adds a customer profile to the Square Customer Directory.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Creates a Square customer profile; needs at least one of first name, last name, company, email or phone. Square allows duplicate emails, so run Find Customers first to avoid duplicates. A retried step returns the same customer instead of repeating the write, and identical calls within one run (for example a loop with the same input) count as one; set Idempotency Key (for example to the loop item) to keep them separate. A new run writes again.',
+ idempotent: false,
+ },
+ props: {
+ ...squareProps.customerFields({ forUpdate: false }),
+ idempotency_key: squareProps.idempotencyKey(),
+ },
+ outputSchema: squareOutputSchemas.customer,
+ async run(context) {
+ const fields = squareOps.customerFields(context.propsValue);
+ if (!['given_name', 'family_name', 'company_name', 'email_address', 'phone_number'].some((key) => fields[key] !== undefined)) {
+ throw new Error('Fill at least one of First Name, Last Name, Company, Email or Phone.');
+ }
+ const body = await squareIdempotency.execute({
+ context,
+ action: 'create_customer',
+ input: fields,
+ send: ({ idempotencyKey }) =>
+ squareClient.request<unknown>({
+ auth: context.auth,
+ method: HttpMethod.POST,
+ path: ['v2', 'customers'],
+ body: { ...fields, idempotency_key: idempotencyKey },
+ operation: 'create the customer',
+ }),
+ });
+ return squareShape.customer(squareShape.requireObject({ body, key: 'customer', what: 'customer' }));
+ },
+});
diff --git a/packages/pieces/community/square/src/lib/actions/create-order.ts b/packages/pieces/community/square/src/lib/actions/create-order.ts
new file mode 100644
index 00000000000..161af5dbb9f
--- /dev/null
+++ b/packages/pieces/community/square/src/lib/actions/create-order.ts
@@ -0,0 +1,48 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { squareAuth } from '../auth';
+import { squareIdempotency } from '../common/idempotency';
+import { squareInputs } from '../common/inputs';
+import { squareOps } from '../common/operations';
+import { squareProps } from '../common/props';
+import { squareShape } from '../common/shape';
+import { squareOutputSchemas } from '../output-schemas';
+
+export const createOrderAction = createAction({
+ name: 'create_order',
+ classification: 'WRITE',
+ auth: squareAuth,
+ displayName: 'Create Order',
+ description: 'Creates an open order (no payment is taken).',
+ audience: 'human',
+ aiMetadata: {
+ description: 'Creates an OPEN Square order from items picked in lists; agents use Create Order (by ID). No payment is taken. A retried step returns the same order instead of repeating the write, and identical calls within one run (for example a loop with the same input) count as one; set Idempotency Key (for example to the loop item) to keep them separate. A new run writes again.',
+ idempotent: false,
+ },
+ props: {
+ location_id: squareProps.location({ required: false }),
+ customer_id: squareProps.customer({ required: false, description: 'Optional. Type part of a name or email to search.' }),
+ line_items: squareProps.lineItems(),
+ reference_id: Property.ShortText({ displayName: 'Reference ID', description: 'Your own ID for this order, for example from your web shop.', required: false }),
+ idempotency_key: squareProps.idempotencyKey(),
+ },
+ outputSchema: squareOutputSchemas.order,
+ async run(context) {
+ const p = context.propsValue;
+ const items = squareShape.isRecord(p.line_items) ? p.line_items['items'] : undefined;
+ const input = { location_id: p.location_id, customer_id: p.customer_id, items, reference_id: p.reference_id };
+ return squareIdempotency.execute({
+ context,
+ action: 'create_order',
+ input,
+ send: ({ idempotencyKey }) =>
+ squareOps.createOrder({
+ auth: context.auth,
+ locationId: squareInputs.optionalId({ value: p.location_id, label: 'Location' }),
+ customerId: squareInputs.optionalId({ value: p.customer_id, label: 'Customer' }),
+ referenceId: squareInputs.text(p.reference_id),
+ items,
+ idempotencyKey,
+ }),
+ });
+ },
+});
diff --git a/packages/pieces/community/square/src/lib/actions/create-payment-link.ts b/packages/pieces/community/square/src/lib/actions/create-payment-link.ts
new file mode 100644
index 00000000000..b178a80b7bd
--- /dev/null
+++ b/packages/pieces/community/square/src/lib/actions/create-payment-link.ts
@@ -0,0 +1,71 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { squareAuth } from '../auth';
+import { squareIdempotency } from '../common/idempotency';
+import { squareInputs } from '../common/inputs';
+import { squareOps } from '../common/operations';
+import { squareProps } from '../common/props';
+import { squareOutputSchemas } from '../output-schemas';
+
+export const createPaymentLinkAction = createAction({
+ name: 'create_payment_link',
+ classification: 'WRITE',
+ auth: squareAuth,
+ displayName: 'Create Payment Link',
+ description: 'Creates a Square checkout link for a fixed amount that you can send to a buyer. Needs a connection created or reconnected with piece version 1.0.0 or later.',
+ audience: 'human',
+ aiMetadata: {
+ description: 'Creates a quick-pay checkout link at a location picked from a list; agents use Create Payment Link (by ID). A retried step returns the same link instead of repeating the write, and identical calls within one run (for example a loop with the same input) count as one; set Idempotency Key (for example to the loop item) to keep them separate. A new run writes again.',
+ idempotent: false,
+ },
+ props: {
+ location_id: squareProps.location({ required: false }),
+ ...linkProps(),
+ },
+ outputSchema: squareOutputSchemas.paymentLink,
+ async run(context) {
+ return runCreateLink({ context, locationLabel: 'Location' });
+ },
+});
+
+function linkProps() {
+ return {
+ name: Property.ShortText({ displayName: 'Item Name', description: 'What the buyer pays for, shown on the checkout page.', required: true }),
+ amount: Property.ShortText({ displayName: 'Amount', description: 'For example 12.50.', required: true }),
+ currency: Property.ShortText({ displayName: 'Currency', description: 'Leave empty to use the location currency.', required: false }),
+ description: Property.ShortText({ displayName: 'Description', description: 'Internal description, not shown to the buyer.', required: false }),
+ payment_note: Property.ShortText({ displayName: 'Payment Note', description: 'Added to the resulting payment.', required: false }),
+ redirect_url: Property.ShortText({ displayName: 'Redirect URL', description: 'Where to send the buyer after paying.', required: false }),
+ idempotency_key: squareProps.idempotencyKey(),
+ };
+}
+
+async function runCreateLink({ context, locationLabel }: { context: LinkContext; locationLabel: string }) {
+ const p = context.propsValue;
+ const input = { location_id: p['location_id'], name: p['name'], amount: p['amount'], currency: p['currency'], description: p['description'], payment_note: p['payment_note'], redirect_url: p['redirect_url'] };
+ return squareIdempotency.execute({
+ context,
+ action: 'create_payment_link',
+ input,
+ send: ({ idempotencyKey }) =>
+ squareOps.createPaymentLink({
+ auth: context.auth,
+ locationId: squareInputs.optionalId({ value: p['location_id'], label: locationLabel }),
+ name: squareInputs.requireText({ value: p['name'], label: 'Item Name' }),
+ amount: p['amount'],
+ currency: p['currency'],
+ description: squareInputs.text(p['description']),
+ paymentNote: squareInputs.text(p['payment_note']),
+ redirectUrl: squareInputs.url({ value: p['redirect_url'], label: 'Redirect URL' }),
+ idempotencyKey,
+ }),
+ });
+}
+
+export const paymentLinkShared = { linkProps, runCreateLink };
+
+type LinkContext = {
+ auth: { access_token: string };
+ propsValue: Record<string, unknown>;
+ run?: { id: string };
+ step?: { name: string };
+};
diff --git a/packages/pieces/community/square/src/lib/actions/delete-catalog-object.ts b/packages/pieces/community/square/src/lib/actions/delete-catalog-object.ts
new file mode 100644
index 00000000000..9b17008eddd
--- /dev/null
+++ b/packages/pieces/community/square/src/lib/actions/delete-catalog-object.ts
@@ -0,0 +1,35 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { squareAuth } from '../auth';
+import { squareClient } from '../common/client';
+import { squareInputs } from '../common/inputs';
+import { squareShape } from '../common/shape';
+import { squareOutputSchemas } from '../output-schemas';
+
+export const deleteCatalogObjectAction = createAction({
+ name: 'delete_catalog_object',
+ classification: 'DESTRUCTIVE',
+ auth: squareAuth,
+ displayName: 'Delete Catalog Item',
+ description: 'Permanently deletes a catalog item (with all its variations) or a single variation.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Permanently deletes a Square catalog object by ID: an item ID deletes the item and all its variations; a variation ID deletes only that variation. Cannot be undone; a second call fails with not found.',
+ idempotent: false,
+ },
+ props: {
+ object_id: Property.ShortText({ displayName: 'Item or Variation ID', description: 'From Search Catalog Items.', required: true }),
+ },
+ outputSchema: squareOutputSchemas.deletedCatalog,
+ async run(context) {
+ const objectId = squareInputs.requireId({ value: context.propsValue.object_id, label: 'Item or Variation ID' });
+ const body = await squareClient.request<unknown>({
+ auth: context.auth,
+ method: HttpMethod.DELETE,
+ path: ['v2', 'catalog', 'object', objectId],
+ operation: `delete catalog object "${objectId}"`,
+ });
+ return { id: objectId, deleted: true, deleted_object_ids: squareShape.strings({ value: body, key: 'deleted_object_ids' }), deleted_at: squareShape.str({ value: body, key: 'deleted_at' }) };
+ },
+});
diff --git a/packages/pieces/community/square/src/lib/actions/delete-customer.ts b/packages/pieces/community/square/src/lib/actions/delete-customer.ts
new file mode 100644
index 00000000000..0d3db4f2afc
--- /dev/null
+++ b/packages/pieces/community/square/src/lib/actions/delete-customer.ts
@@ -0,0 +1,27 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { squareAuth } from '../auth';
+import { squareInputs } from '../common/inputs';
+import { squareOps } from '../common/operations';
+import { squareProps } from '../common/props';
+import { squareOutputSchemas } from '../output-schemas';
+
+export const deleteCustomerAction = createAction({
+ name: 'delete_customer',
+ classification: 'DESTRUCTIVE',
+ auth: squareAuth,
+ displayName: 'Delete Customer',
+ description: 'Permanently deletes a customer profile.',
+ audience: 'human',
+ aiMetadata: {
+ description: 'Permanently deletes a Square customer picked from a list; agents use Delete Customer (by ID). Cannot be undone; a second run fails with not found.',
+ idempotent: false,
+ },
+ props: {
+ customer_id: squareProps.customer({ required: true }),
+ },
+ outputSchema: squareOutputSchemas.deleted,
+ async run(context) {
+ const customerId = squareInputs.requireId({ value: context.propsValue.customer_id, label: 'Customer' });
+ return squareOps.deleteCustomer({ auth: context.auth, customerId });
+ },
+});
diff --git a/packages/pieces/community/square/src/lib/actions/find-customers.ts b/packages/pieces/community/square/src/lib/actions/find-customers.ts
new file mode 100644
index 00000000000..28687ed3c84
--- /dev/null
+++ b/packages/pieces/community/square/src/lib/actions/find-customers.ts
@@ -0,0 +1,65 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { squareAuth } from '../auth';
+import { squareClient } from '../common/client';
+import { squareInputs } from '../common/inputs';
+import { squareOps } from '../common/operations';
+import { squareProps } from '../common/props';
+import { squareShape } from '../common/shape';
+import { squareOutputSchemas } from '../output-schemas';
+
+export const findCustomersAction = createAction({
+ name: 'find_customers',
+ classification: 'SEARCH',
+ auth: squareAuth,
+ displayName: 'Find Customers',
+ description: 'Searches customers by email, phone, reference ID or creation date.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Searches the Square Customer Directory by email, phone, reference ID and/or creation date and returns one page of matching customers with their IDs. Use it before Create Customer to avoid duplicates, or to get a customer ID for orders and payments. Square cannot search by name, and a customer created seconds ago may not be searchable yet. Read-only and safe to retry.',
+ idempotent: true,
+ },
+ props: {
+ email_address: Property.ShortText({ displayName: 'Email', required: false }),
+ phone_number: Property.ShortText({ displayName: 'Phone', description: 'For example +14155550123.', required: false }),
+ reference_id: Property.ShortText({ displayName: 'Reference ID', required: false }),
+ match: Property.StaticDropdown({
+ displayName: 'Match',
+ description: 'Exact match, or partial match (contains) for email, phone and reference ID.',
+ required: false,
+ defaultValue: 'exact',
+ options: { options: [{ label: 'Exact', value: 'exact' }, { label: 'Partial', value: 'fuzzy' }] },
+ }),
+ created_after: Property.DateTime({ displayName: 'Created After', required: false }),
+ created_before: Property.DateTime({ displayName: 'Created Before', required: false }),
+ limit: squareProps.limitProp({ max: 100, fallback: 50 }),
+ cursor: squareProps.cursorProp(),
+ },
+ outputSchema: squareOutputSchemas.customers,
+ async run(context) {
+ const p = context.propsValue;
+ const mode = p.match === 'fuzzy' ? 'fuzzy' : 'exact';
+ const term = (value: string | undefined) => (value === undefined ? undefined : { [mode]: value });
+ const createdAfter = squareInputs.dateTime({ value: p.created_after, label: 'Created After' });
+ const createdBefore = squareInputs.dateTime({ value: p.created_before, label: 'Created Before' });
+ const filter = squareOps.dropUndefined({
+ email_address: term(squareInputs.text(p.email_address)),
+ phone_number: term(squareInputs.text(p.phone_number)),
+ reference_id: term(squareInputs.text(p.reference_id)),
+ created_at: createdAfter || createdBefore ? squareOps.dropUndefined({ start_at: createdAfter, end_at: createdBefore }) : undefined,
+ });
+ const body = await squareClient.request<unknown>({
+ auth: context.auth,
+ method: HttpMethod.POST,
+ path: ['v2', 'customers', 'search'],
+ body: squareOps.dropUndefined({
+ query: { ...(Object.keys(filter).length > 0 ? { filter } : {}), sort: { field: 'CREATED_AT', order: 'DESC' } },
+ limit: squareInputs.limit({ value: p.limit, fallback: 50, max: 100 }),
+ cursor: squareInputs.cursor(p.cursor),
+ }),
+ operation: 'search customers',
+ });
+ return squareShape.page({ items: squareShape.list({ value: body, key: 'customers' }).map(squareShape.customer), cursor: squareShape.str({ value: body, key: 'cursor' }) });
+ },
+});
diff --git a/packages/pieces/community/square/src/lib/actions/get-catalog-item.ts b/packages/pieces/community/square/src/lib/actions/get-catalog-item.ts
new file mode 100644
index 00000000000..0067b8a65d3
--- /dev/null
+++ b/packages/pieces/community/square/src/lib/actions/get-catalog-item.ts
@@ -0,0 +1,42 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { squareAuth } from '../auth';
+import { squareInputs } from '../common/inputs';
+import { squareOps } from '../common/operations';
+import { squareShape } from '../common/shape';
+import { squareOutputSchemas } from '../output-schemas';
+
+export const getCatalogItemAction = createAction({
+ name: 'get_catalog_item',
+ classification: 'READ',
+ auth: squareAuth,
+ displayName: 'Get Catalog Item',
+ description: 'Gets a catalog item with its variations and prices.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Reads one Square catalog item with its variations (IDs, SKUs, prices). Accepts an item ID or a variation ID (then returns the parent item), for example from an order line item. Read-only and safe to retry.',
+ idempotent: true,
+ },
+ props: {
+ object_id: Property.ShortText({
+ displayName: 'Item or Variation ID',
+ description: 'The catalog item ID, or one of its variation IDs (from Search Catalog Items or an order line item).',
+ required: true,
+ }),
+ },
+ outputSchema: squareOutputSchemas.catalogItem,
+ async run(context) {
+ const objectId = squareInputs.requireId({ value: context.propsValue.object_id, label: 'Item or Variation ID' });
+ const object = await squareOps.retrieveObject({ auth: context.auth, objectId });
+ if (object['type'] === 'ITEM') {
+ return squareShape.catalogItem(object);
+ }
+ if (object['type'] === 'ITEM_VARIATION') {
+ const itemId = squareShape.str({ value: squareShape.rec({ value: object, key: 'item_variation_data' }), key: 'item_id' });
+ if (itemId) {
+ return squareShape.catalogItem(await squareOps.retrieveObject({ auth: context.auth, objectId: itemId }));
+ }
+ }
+ throw new Error(`Catalog object "${objectId}" is a ${String(object['type'])}, not an item or item variation.`);
+ },
+});
diff --git a/packages/pieces/community/square/src/lib/actions/get-customer.ts b/packages/pieces/community/square/src/lib/actions/get-customer.ts
new file mode 100644
index 00000000000..9f211e844f9
--- /dev/null
+++ b/packages/pieces/community/square/src/lib/actions/get-customer.ts
@@ -0,0 +1,27 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { squareAuth } from '../auth';
+import { squareInputs } from '../common/inputs';
+import { squareOps } from '../common/operations';
+import { squareProps } from '../common/props';
+import { squareOutputSchemas } from '../output-schemas';
+
+export const getCustomerAction = createAction({
+ name: 'get_customer',
+ classification: 'READ',
+ auth: squareAuth,
+ displayName: 'Get Customer',
+ description: 'Gets a customer profile.',
+ audience: 'human',
+ aiMetadata: {
+ description: 'Reads one Square customer picked from a list. Agents use Get Customer (by ID). Read-only and safe to retry.',
+ idempotent: true,
+ },
+ props: {
+ customer_id: squareProps.customer({ required: true }),
+ },
+ outputSchema: squareOutputSchemas.customer,
+ async run(context) {
+ const customerId = squareInputs.requireId({ value: context.propsValue.customer_id, label: 'Customer' });
+ return squareOps.getCustomer({ auth: context.auth, customerId });
+ },
+});
diff --git a/packages/pieces/community/square/src/lib/actions/get-inventory-count.ts b/packages/pieces/community/square/src/lib/actions/get-inventory-count.ts
new file mode 100644
index 00000000000..f219ff85862
--- /dev/null
+++ b/packages/pieces/community/square/src/lib/actions/get-inventory-count.ts
@@ -0,0 +1,30 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { squareAuth } from '../auth';
+import { squareInputs } from '../common/inputs';
+import { squareOps } from '../common/operations';
+import { squareProps } from '../common/props';
+import { squareOutputSchemas } from '../output-schemas';
+
+export const getInventoryCountAction = createAction({
+ name: 'get_inventory_count',
+ classification: 'READ',
+ auth: squareAuth,
+ displayName: 'Get Inventory Count',
+ description: 'Gets the stock count of an item variation. Needs a connection created or reconnected with piece version 1.0.0 or later.',
+ audience: 'human',
+ aiMetadata: {
+ description: 'Reads the stock count of a variation picked from lists; agents use Get Inventory Count (by ID). Read-only and safe to retry.',
+ idempotent: true,
+ },
+ props: {
+ item: squareProps.catalogItem({ required: true }),
+ variation_id: squareProps.variation({ required: true }),
+ location_id: squareProps.location({ required: false, description: 'Leave empty to get the count at every location.' }),
+ },
+ outputSchema: squareOutputSchemas.inventoryCounts,
+ async run(context) {
+ const variationId = squareInputs.requireId({ value: context.propsValue.variation_id, label: 'Variation' });
+ const locationId = squareInputs.optionalId({ value: context.propsValue.location_id, label: 'Location' });
+ return squareOps.getInventory({ auth: context.auth, variationIds: [variationId], locationIds: locationId ? [locationId] : [], limit: 100, cursor: undefined });
+ },
+});
diff --git a/packages/pieces/community/square/src/lib/actions/get-merchant.ts b/packages/pieces/community/square/src/lib/actions/get-merchant.ts
new file mode 100644
index 00000000000..62b5b9cbace
--- /dev/null
+++ b/packages/pieces/community/square/src/lib/actions/get-merchant.ts
@@ -0,0 +1,26 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { squareAuth } from '../auth';
+import { squareClient } from '../common/client';
+import { squareShape } from '../common/shape';
+import { squareOutputSchemas } from '../output-schemas';
+
+export const getMerchantAction = createAction({
+ name: 'get_merchant',
+ classification: 'READ',
+ auth: squareAuth,
+ displayName: 'Get Business Profile',
+ description: 'Gets the connected Square business: name, country, currency and main location.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Returns the connected Square seller profile (business name, country, default currency, main location ID). Use it to learn the currency before entering amounts, or which account a connection points at. Read-only and safe to retry.',
+ idempotent: true,
+ },
+ props: {},
+ outputSchema: squareOutputSchemas.merchant,
+ async run(context) {
+ const body = await squareClient.request<unknown>({ auth: context.auth, method: HttpMethod.GET, path: ['v2', 'merchants', 'me'], operation: 'read the business profile' });
+ return squareShape.merchant(squareShape.requireObject({ body, key: 'merchant', what: 'merchant' }));
+ },
+});
diff --git a/packages/pieces/community/square/src/lib/actions/get-order.ts b/packages/pieces/community/square/src/lib/actions/get-order.ts
new file mode 100644
index 00000000000..b4d0edf7bcf
--- /dev/null
+++ b/packages/pieces/community/square/src/lib/actions/get-order.ts
@@ -0,0 +1,30 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { squareAuth } from '../auth';
+import { squareClient } from '../common/client';
+import { squareInputs } from '../common/inputs';
+import { squareShape } from '../common/shape';
+import { squareOutputSchemas } from '../output-schemas';
+
+export const getOrderAction = createAction({
+ name: 'get_order',
+ classification: 'READ',
+ auth: squareAuth,
+ displayName: 'Get Order',
+ description: 'Gets an order with its line items and totals.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Reads one Square order by order ID (from an order trigger, Search Orders or a payment): state, customer, totals as decimal strings and up to 100 line items. Read-only and safe to retry.',
+ idempotent: true,
+ },
+ props: {
+ order_id: Property.ShortText({ displayName: 'Order ID', description: 'Map it from the New Order trigger or a payment.', required: true }),
+ },
+ outputSchema: squareOutputSchemas.order,
+ async run(context) {
+ const orderId = squareInputs.requireId({ value: context.propsValue.order_id, label: 'Order ID' });
+ const body = await squareClient.request<unknown>({ auth: context.auth, method: HttpMethod.GET, path: ['v2', 'orders', orderId], operation: `read order "${orderId}"` });
+ return squareShape.order(squareShape.requireObject({ body, key: 'order', what: 'order' }));
+ },
+});
diff --git a/packages/pieces/community/square/src/lib/actions/get-payment.ts b/packages/pieces/community/square/src/lib/actions/get-payment.ts
new file mode 100644
index 00000000000..445b92637ef
--- /dev/null
+++ b/packages/pieces/community/square/src/lib/actions/get-payment.ts
@@ -0,0 +1,30 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { squareAuth } from '../auth';
+import { squareClient } from '../common/client';
+import { squareInputs } from '../common/inputs';
+import { squareShape } from '../common/shape';
+import { squareOutputSchemas } from '../output-schemas';
+
+export const getPaymentAction = createAction({
+ name: 'get_payment',
+ classification: 'READ',
+ auth: squareAuth,
+ displayName: 'Get Payment',
+ description: 'Gets a payment with its amount, status and card summary.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Reads one Square payment by payment ID (from the New Payment trigger, List Payments or an order): status, amounts as decimal strings, refunded amount, card brand and last 4 digits, linked order and customer. Read-only and safe to retry.',
+ idempotent: true,
+ },
+ props: {
+ payment_id: Property.ShortText({ displayName: 'Payment ID', description: 'Map it from the New Payment trigger or List Payments.', required: true }),
+ },
+ outputSchema: squareOutputSchemas.payment,
+ async run(context) {
+ const paymentId = squareInputs.requireId({ value: context.propsValue.payment_id, label: 'Payment ID' });
+ const body = await squareClient.request<unknown>({ auth: context.auth, method: HttpMethod.GET, path: ['v2', 'payments', paymentId], operation: `read payment "${paymentId}"` });
+ return squareShape.payment(squareShape.requireObject({ body, key: 'payment', what: 'payment' }));
+ },
+});
diff --git a/packages/pieces/community/square/src/lib/actions/get-refund.ts b/packages/pieces/community/square/src/lib/actions/get-refund.ts
new file mode 100644
index 00000000000..f040ed86d6d
--- /dev/null
+++ b/packages/pieces/community/square/src/lib/actions/get-refund.ts
@@ -0,0 +1,29 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { squareAuth } from '../auth';
+import { squareClient } from '../common/client';
+import { squareInputs } from '../common/inputs';
+import { squareShape } from '../common/shape';
+import { squareOutputSchemas } from '../output-schemas';
+
+export const getRefundAction = createAction({
+ name: 'get_refund',
+ classification: 'READ',
+ auth: squareAuth,
+ displayName: 'Get Refund',
+ description: 'Gets a refund and its status.',
+ audience: 'both',
+ aiMetadata: {
+ description: 'Reads one Square refund by refund ID (from a payment\'s refund IDs or List Refunds): status (PENDING, COMPLETED, REJECTED, FAILED), amount and the refunded payment. Read-only and safe to retry.',
+ idempotent: true,
+ },
+ props: {
+ refund_id: Property.ShortText({ displayName: 'Refund ID', required: true }),
+ },
+ outputSchema: squareOutputSchemas.refund,
+ async run(context) {
+ const refundId = squareInputs.requireId({ value: context.propsValue.refund_id, label: 'Refund ID' });
+ const body = await squareClient.request<unknown>({ auth: context.auth, method: HttpMethod.GET, path: ['v2', 'refunds', refundId], operation: `read refund "${refundId}"` });
+ return squareShape.refund(squareShape.requireObject({ body, key: 'refund', what: 'refund' }));
+ },
+});
diff --git a/packages/pieces/community/square/src/lib/actions/list-locations.ts b/packages/pieces/community/square/src/lib/actions/list-locations.ts
new file mode 100644
index 00000000000..8ddafee9cf2
--- /dev/null
+++ b/packages/pieces/community/square/src/lib/actions/list-locations.ts
@@ -0,0 +1,45 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { squareAuth } from '../auth';
+import { squareClient } from '../common/client';
+import { squareShape } from '../common/shape';
+import { squareOutputSchemas } from '../output-schemas';
+
+export const listLocationsAction = createAction({
+ name: 'list_locations',
+ classification: 'SEARCH',
+ auth: squareAuth,
+ displayName: 'List Locations',
+ description: 'Lists the business locations (stores) of the Square account.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Lists the seller locations with their IDs, currency, time zone and address. Location IDs are needed by orders, payment links and inventory; "main" is also accepted wherever a location ID is optional. Read-only and safe to retry.',
+ idempotent: true,
+ },
+ props: {
+ status: Property.StaticDropdown({
+ displayName: 'Status',
+ description: 'Which locations to return.',
+ required: false,
+ defaultValue: 'ACTIVE',
+ options: {
+ options: [
+ { label: 'Active only', value: 'ACTIVE' },
+ { label: 'Inactive only', value: 'INACTIVE' },
+ { label: 'All', value: 'ALL' },
+ ],
+ },
+ }),
+ },
+ outputSchema: squareOutputSchemas.locations,
+ async run(context) {
+ const status = context.propsValue.status ?? 'ACTIVE';
+ const body = await squareClient.request<unknown>({ auth: context.auth, method: HttpMethod.GET, path: ['v2', 'locations'], operation: 'list locations' });
+ const items = squareShape
+ .list({ value: body, key: 'locations' })
+ .map(squareShape.location)
+ .filter((location) => status === 'ALL' || location.status === status);
+ return squareShape.page({ items, cursor: null });
+ },
+});
diff --git a/packages/pieces/community/square/src/lib/actions/list-payments.ts b/packages/pieces/community/square/src/lib/actions/list-payments.ts
new file mode 100644
index 00000000000..06236055150
--- /dev/null
+++ b/packages/pieces/community/square/src/lib/actions/list-payments.ts
@@ -0,0 +1,48 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { squareAuth } from '../auth';
+import { squareClient } from '../common/client';
+import { squareInputs } from '../common/inputs';
+import { squareProps } from '../common/props';
+import { squareShape } from '../common/shape';
+import { squareOutputSchemas } from '../output-schemas';
+
+export const listPaymentsAction = createAction({
+ name: 'list_payments',
+ classification: 'SEARCH',
+ auth: squareAuth,
+ displayName: 'List Payments',
+ description: 'Lists payments in a time range, newest first.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Lists Square payments newest first, optionally limited to a location ID and a created-at range (ISO 8601; Square defaults to the last year). Returns one page; pass Next Cursor within about 5 minutes for more. Read-only and safe to retry.',
+ idempotent: true,
+ },
+ props: {
+ location_id: Property.ShortText({ displayName: 'Location ID', description: 'Leave empty for all locations.', required: false }),
+ begin_time: Property.DateTime({ displayName: 'Created After', required: false }),
+ end_time: Property.DateTime({ displayName: 'Created Before', required: false }),
+ limit: squareProps.limitProp({ max: 100, fallback: 50 }),
+ cursor: squareProps.cursorProp(),
+ },
+ outputSchema: squareOutputSchemas.payments,
+ async run(context) {
+ const p = context.propsValue;
+ const body = await squareClient.request<unknown>({
+ auth: context.auth,
+ method: HttpMethod.GET,
+ path: ['v2', 'payments'],
+ query: {
+ location_id: squareInputs.optionalId({ value: p.location_id, label: 'Location ID' }),
+ begin_time: squareInputs.dateTime({ value: p.begin_time, label: 'Created After' }),
+ end_time: squareInputs.dateTime({ value: p.end_time, label: 'Created Before' }),
+ sort_order: 'DESC',
+ limit: squareInputs.limit({ value: p.limit, fallback: 50, max: 100 }),
+ cursor: squareInputs.cursor(p.cursor),
+ },
+ operation: 'list payments',
+ });
+ return squareShape.page({ items: squareShape.list({ value: body, key: 'payments' }).map(squareShape.payment), cursor: squareShape.str({ value: body, key: 'cursor' }) });
+ },
+});
diff --git a/packages/pieces/community/square/src/lib/actions/list-refunds.ts b/packages/pieces/community/square/src/lib/actions/list-refunds.ts
new file mode 100644
index 00000000000..cdb6b458c02
--- /dev/null
+++ b/packages/pieces/community/square/src/lib/actions/list-refunds.ts
@@ -0,0 +1,54 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { squareAuth } from '../auth';
+import { squareClient } from '../common/client';
+import { squareInputs } from '../common/inputs';
+import { squareProps } from '../common/props';
+import { squareShape } from '../common/shape';
+import { squareOutputSchemas } from '../output-schemas';
+
+export const listRefundsAction = createAction({
+ name: 'list_refunds',
+ classification: 'SEARCH',
+ auth: squareAuth,
+ displayName: 'List Refunds',
+ description: 'Lists refunds in a time range, newest first.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Lists Square refunds newest first, optionally by location ID, status and created-at range (ISO 8601). Returns one page; pass Next Cursor within about 5 minutes for more. Read-only and safe to retry.',
+ idempotent: true,
+ },
+ props: {
+ location_id: Property.ShortText({ displayName: 'Location ID', description: 'Leave empty for all locations.', required: false }),
+ status: Property.StaticDropdown({
+ displayName: 'Status',
+ required: false,
+ options: { options: ['PENDING', 'COMPLETED', 'REJECTED', 'FAILED'].map((value) => ({ label: value.charAt(0) + value.slice(1).toLowerCase(), value })) },
+ }),
+ begin_time: Property.DateTime({ displayName: 'Created After', required: false }),
+ end_time: Property.DateTime({ displayName: 'Created Before', required: false }),
+ limit: squareProps.limitProp({ max: 100, fallback: 50 }),
+ cursor: squareProps.cursorProp(),
+ },
+ outputSchema: squareOutputSchemas.refunds,
+ async run(context) {
+ const p = context.propsValue;
+ const body = await squareClient.request<unknown>({
+ auth: context.auth,
+ method: HttpMethod.GET,
+ path: ['v2', 'refunds'],
+ query: {
+ location_id: squareInputs.optionalId({ value: p.location_id, label: 'Location ID' }),
+ status: squareInputs.text(p.status),
+ begin_time: squareInputs.dateTime({ value: p.begin_time, label: 'Created After' }),
+ end_time: squareInputs.dateTime({ value: p.end_time, label: 'Created Before' }),
+ sort_order: 'DESC',
+ limit: squareInputs.limit({ value: p.limit, fallback: 50, max: 100 }),
+ cursor: squareInputs.cursor(p.cursor),
+ },
+ operation: 'list refunds',
+ });
+ return squareShape.page({ items: squareShape.list({ value: body, key: 'refunds' }).map(squareShape.refund), cursor: squareShape.str({ value: body, key: 'cursor' }) });
+ },
+});
diff --git a/packages/pieces/community/square/src/lib/actions/list-team-members.ts b/packages/pieces/community/square/src/lib/actions/list-team-members.ts
new file mode 100644
index 00000000000..c451aa633ca
--- /dev/null
+++ b/packages/pieces/community/square/src/lib/actions/list-team-members.ts
@@ -0,0 +1,61 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { squareAuth } from '../auth';
+import { squareClient } from '../common/client';
+import { squareInputs } from '../common/inputs';
+import { squareOps } from '../common/operations';
+import { squareProps } from '../common/props';
+import { squareShape } from '../common/shape';
+import { squareOutputSchemas } from '../output-schemas';
+
+export const listTeamMembersAction = createAction({
+ name: 'list_team_members',
+ classification: 'SEARCH',
+ auth: squareAuth,
+ displayName: 'List Team Members',
+ description: 'Lists staff members of the Square account. Needs a connection created or reconnected with piece version 1.0.0 or later.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Lists Square team members (staff) with IDs, names, status and assigned locations, one page at a time. Use it to see who works at which location. Needs the EMPLOYEES_READ permission (reconnect older connections). Read-only and safe to retry.',
+ idempotent: true,
+ },
+ props: {
+ location_id: squareProps.locationIdText(),
+ status: Property.StaticDropdown({
+ displayName: 'Status',
+ required: false,
+ defaultValue: 'ACTIVE',
+ options: {
+ options: [
+ { label: 'Active', value: 'ACTIVE' },
+ { label: 'Inactive', value: 'INACTIVE' },
+ { label: 'All', value: 'ALL' },
+ ],
+ },
+ }),
+ limit: squareProps.limitProp({ max: 200, fallback: 50 }),
+ cursor: squareProps.cursorProp(),
+ },
+ outputSchema: squareOutputSchemas.teamMembers,
+ async run(context) {
+ const locationId = squareInputs.optionalId({ value: context.propsValue.location_id, label: 'Location ID' });
+ const status = context.propsValue.status ?? 'ACTIVE';
+ const filter = squareOps.dropUndefined({
+ location_ids: locationId ? [locationId] : undefined,
+ status: status === 'ALL' ? undefined : status,
+ });
+ const body = await squareClient.request<unknown>({
+ auth: context.auth,
+ method: HttpMethod.POST,
+ path: ['v2', 'team-members', 'search'],
+ body: squareOps.dropUndefined({
+ query: Object.keys(filter).length > 0 ? { filter } : undefined,
+ limit: squareInputs.limit({ value: context.propsValue.limit, fallback: 50, max: 200 }),
+ cursor: squareInputs.cursor(context.propsValue.cursor),
+ }),
+ operation: 'list team members',
+ });
+ return squareShape.page({ items: squareShape.list({ value: body, key: 'team_members' }).map(squareShape.teamMember), cursor: squareShape.str({ value: body, key: 'cursor' }) });
+ },
+});
diff --git a/packages/pieces/community/square/src/lib/actions/record-external-payment.ts b/packages/pieces/community/square/src/lib/actions/record-external-payment.ts
new file mode 100644
index 00000000000..0981cde2b6f
--- /dev/null
+++ b/packages/pieces/community/square/src/lib/actions/record-external-payment.ts
@@ -0,0 +1,105 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { squareAuth } from '../auth';
+import { squareClient } from '../common/client';
+import { squareIdempotency } from '../common/idempotency';
+import { squareInputs } from '../common/inputs';
+import { squareMoney } from '../common/money';
+import { squareOps } from '../common/operations';
+import { squareProps } from '../common/props';
+import { squareShape } from '../common/shape';
+import { squareOutputSchemas } from '../output-schemas';
+
+const EXTERNAL_TYPES = ['CHECK', 'BANK_TRANSFER', 'OTHER_GIFT_CARD', 'CRYPTO', 'SQUARE_CASH', 'SOCIAL', 'EXTERNAL', 'EMONEY', 'CARD', 'STORED_BALANCE', 'FOOD_VOUCHER', 'OTHER'];
+
+export const recordExternalPaymentAction = createAction({
+ name: 'record_external_payment',
+ classification: 'WRITE',
+ auth: squareAuth,
+ displayName: 'Record Cash or External Payment',
+ description:
+ 'Records money you received outside Square (cash, check, bank transfer, another app). Never charges a card. Needs a connection created or reconnected with piece version 1.0.0 or later.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Records a completed CASH or EXTERNAL payment in Square for money already received elsewhere; it never charges a card. Amount is a decimal string like "12.50" in the location currency; with an Order ID it must equal the order total due. Needs PAYMENTS_WRITE (reconnect older connections). A retried step returns the same payment instead of repeating the write, and identical calls within one run (for example a loop with the same input) count as one; set Idempotency Key (for example to the loop item) to keep them separate. A new run writes again.',
+ idempotent: false,
+ },
+ props: {
+ source: Property.StaticDropdown({
+ displayName: 'Payment Type',
+ required: true,
+ defaultValue: 'CASH',
+ options: {
+ options: [
+ { label: 'Cash', value: 'CASH' },
+ { label: 'Other (outside Square)', value: 'EXTERNAL' },
+ ],
+ },
+ }),
+ amount: Property.ShortText({ displayName: 'Amount', description: 'For example 12.50.', required: true }),
+ currency: Property.ShortText({ displayName: 'Currency', description: 'Leave empty to use the location currency.', required: false }),
+ external_type: Property.StaticDropdown({
+ displayName: 'External Type',
+ description: 'For Other payments: how the money was received.',
+ required: false,
+ options: {
+ options: EXTERNAL_TYPES.map((value) => ({ label: value.replace(/_/g, ' ').toLowerCase().replace(/^./, (c) => c.toUpperCase()), value })),
+ },
+ }),
+ external_source: Property.ShortText({ displayName: 'External Source', description: 'For Other payments: the provider, for example "Venmo" or "Bank of X".', required: false }),
+ location_id: Property.ShortText({ displayName: 'Location ID', description: 'Leave empty to use the main location.', required: false }),
+ order_id: Property.ShortText({ displayName: 'Order ID', description: 'Optional order this payment pays for.', required: false }),
+ customer_id: Property.ShortText({ displayName: 'Customer ID', required: false }),
+ reference_id: Property.ShortText({ displayName: 'Reference ID', required: false }),
+ note: Property.ShortText({ displayName: 'Note', required: false }),
+ idempotency_key: squareProps.idempotencyKey(),
+ },
+ outputSchema: squareOutputSchemas.payment,
+ async run(context) {
+ const p = context.propsValue;
+ const source = p.source === 'EXTERNAL' ? 'EXTERNAL' : 'CASH';
+ const location = await squareClient.resolveLocation({ auth: context.auth, locationId: squareInputs.optionalId({ value: p.location_id, label: 'Location ID' }) });
+ const currency = squareMoney.normalizeCurrency(p.currency) ?? squareShape.str({ value: location, key: 'currency' });
+ if (!currency) {
+ throw new Error('Could not find the currency of the location. Fill Currency.');
+ }
+ const amountMoney = { amount: squareMoney.toMinor({ amount: p.amount, currency, label: 'Amount' }), currency };
+ const externalType = squareInputs.text(p.external_type);
+ const externalSource = squareInputs.text(p.external_source);
+ if (source === 'EXTERNAL') {
+ if (!externalType || !EXTERNAL_TYPES.includes(externalType)) {
+ throw new Error(`External Type is required for Other payments: one of ${EXTERNAL_TYPES.join(', ')}.`);
+ }
+ if (!externalSource) {
+ throw new Error('External Source is required for Other payments, for example "Venmo".');
+ }
+ }
+ const payload = squareOps.dropUndefined({
+ source_id: source,
+ amount_money: amountMoney,
+ location_id: String(location['id']),
+ order_id: squareInputs.optionalId({ value: p.order_id, label: 'Order ID' }),
+ customer_id: squareInputs.optionalId({ value: p.customer_id, label: 'Customer ID' }),
+ reference_id: squareInputs.text(p.reference_id),
+ note: squareInputs.text(p.note),
+ cash_details: source === 'CASH' ? { buyer_supplied_money: amountMoney } : undefined,
+ external_details: source === 'EXTERNAL' ? { type: externalType, source: externalSource } : undefined,
+ autocomplete: true,
+ });
+ const body = await squareIdempotency.execute({
+ context,
+ action: 'record_external_payment',
+ input: payload,
+ send: ({ idempotencyKey }) =>
+ squareClient.request<unknown>({
+ auth: context.auth,
+ method: HttpMethod.POST,
+ path: ['v2', 'payments'],
+ body: { ...payload, idempotency_key: idempotencyKey },
+ operation: 'record the payment',
+ }),
+ });
+ return squareShape.payment(squareShape.requireObject({ body, key: 'payment', what: 'payment' }));
+ },
+});
diff --git a/packages/pieces/community/square/src/lib/actions/refund-payment.ts b/packages/pieces/community/square/src/lib/actions/refund-payment.ts
new file mode 100644
index 00000000000..9fef156eaa6
--- /dev/null
+++ b/packages/pieces/community/square/src/lib/actions/refund-payment.ts
@@ -0,0 +1,72 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { squareAuth } from '../auth';
+import { squareClient, SquareApiError } from '../common/client';
+import { squareIdempotency } from '../common/idempotency';
+import { squareInputs } from '../common/inputs';
+import { squareMoney } from '../common/money';
+import { squareOps } from '../common/operations';
+import { squareProps } from '../common/props';
+import { squareShape } from '../common/shape';
+import { squareOutputSchemas } from '../output-schemas';
+
+export const refundPaymentAction = createAction({
+ name: 'refund_payment',
+ classification: 'DESTRUCTIVE',
+ auth: squareAuth,
+ displayName: 'Refund Payment',
+ description:
+ 'Refunds all or part of a payment. Card refunds send real money back to the buyer and cannot be undone. Needs a connection created or reconnected with piece version 1.0.0 or later.',
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Refunds an amount of a completed Square payment back to the buyer; cannot be undone. Not offered to agents. A retried step returns the same refund instead of repeating the write, and identical calls within one run (for example a loop with the same input) count as one; set Idempotency Key (for example to the loop item) to keep them separate. A new run writes again.',
+ idempotent: false,
+ },
+ props: {
+ payment_id: Property.ShortText({ displayName: 'Payment ID', description: 'Map it from the New Payment trigger, Get Payment or List Payments.', required: true }),
+ amount: Property.ShortText({ displayName: 'Amount to Refund', description: 'Decimal amount in the payment currency, for example 12.50. Must not exceed what is left to refund.', required: true }),
+ reason: Property.ShortText({ displayName: 'Reason', description: 'Shown to the buyer on the refund receipt.', required: false }),
+ idempotency_key: squareProps.idempotencyKey(),
+ },
+ outputSchema: squareOutputSchemas.refund,
+ async run(context) {
+ const p = context.propsValue;
+ const paymentId = squareInputs.requireId({ value: p.payment_id, label: 'Payment ID' });
+ const current = await squareClient.request<unknown>({ auth: context.auth, method: HttpMethod.GET, path: ['v2', 'payments', paymentId], operation: `read payment "${paymentId}"` });
+ const payment = squareShape.payment(squareShape.requireObject({ body: current, key: 'payment', what: 'payment' }));
+ if (!payment.currency || payment.total_minor === null) {
+ throw new Error(`Payment "${paymentId}" has no amount to refund.`);
+ }
+ const minor = squareMoney.toMinor({ amount: p.amount, currency: payment.currency, label: 'Amount to Refund' });
+ const payload = squareOps.dropUndefined({
+ payment_id: paymentId,
+ amount_money: { amount: minor, currency: payment.currency },
+ reason: squareInputs.text(p.reason),
+ });
+ const body = await squareIdempotency
+ .execute({
+ context,
+ action: 'refund_payment',
+ input: payload,
+ send: ({ idempotencyKey }) =>
+ squareClient.request<unknown>({
+ auth: context.auth,
+ method: HttpMethod.POST,
+ path: ['v2', 'refunds'],
+ body: { ...payload, idempotency_key: idempotencyKey },
+ operation: 'refund the payment',
+ }),
+ })
+ .catch((error: unknown) => {
+ if (error instanceof SquareApiError && error.code === 'REFUND_AMOUNT_INVALID') {
+ const remaining = Math.max(0, (payment.total_minor ?? 0) - (payment.refunded_minor ?? 0));
+ throw new Error(
+ `Amount to Refund ${p.amount} is more than the ${squareMoney.format({ minor: remaining, currency: payment.currency ?? '' })} ${payment.currency ?? ''} left to refund on this payment.`,
+ );
+ }
+ throw error;
+ });
+ return squareShape.refund(squareShape.requireObject({ body, key: 'refund', what: 'refund' }));
+ },
+});
diff --git a/packages/pieces/community/square/src/lib/actions/search-catalog-items.ts b/packages/pieces/community/square/src/lib/actions/search-catalog-items.ts
new file mode 100644
index 00000000000..ce08f70d1db
--- /dev/null
+++ b/packages/pieces/community/square/src/lib/actions/search-catalog-items.ts
@@ -0,0 +1,50 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { squareAuth } from '../auth';
+import { squareClient } from '../common/client';
+import { squareInputs } from '../common/inputs';
+import { squareOps } from '../common/operations';
+import { squareProps } from '../common/props';
+import { squareShape } from '../common/shape';
+import { squareOutputSchemas } from '../output-schemas';
+
+export const searchCatalogItemsAction = createAction({
+ name: 'search_catalog_items',
+ classification: 'SEARCH',
+ auth: squareAuth,
+ displayName: 'Search Catalog Items',
+ description: 'Finds products and services in the Square catalog by name, category or location.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Searches the Square item catalog by text (name, SKU, description), category ID and/or location ID, and returns one page of items with their variations (variation IDs, SKUs and prices). Use it to find the variation ID needed by Create Order, inventory and price updates. Read-only and safe to retry.',
+ idempotent: true,
+ },
+ props: {
+ text: Property.ShortText({ displayName: 'Search Text', description: 'Words to match in the item name, SKU or description. Leave empty to list items.', required: false }),
+ category_id: Property.ShortText({ displayName: 'Category ID', required: false }),
+ location_id: Property.ShortText({ displayName: 'Location ID', description: 'Only items enabled at this location.', required: false }),
+ limit: squareProps.limitProp({ max: 100, fallback: 25 }),
+ cursor: squareProps.cursorProp(),
+ },
+ outputSchema: squareOutputSchemas.catalogItems,
+ async run(context) {
+ const p = context.propsValue;
+ const categoryId = squareInputs.optionalId({ value: p.category_id, label: 'Category ID' });
+ const locationId = squareInputs.optionalId({ value: p.location_id, label: 'Location ID' });
+ const body = await squareClient.request<unknown>({
+ auth: context.auth,
+ method: HttpMethod.POST,
+ path: ['v2', 'catalog', 'search-catalog-items'],
+ body: squareOps.dropUndefined({
+ text_filter: squareInputs.text(p.text),
+ category_ids: categoryId ? [categoryId] : undefined,
+ enabled_location_ids: locationId ? [locationId] : undefined,
+ limit: squareInputs.limit({ value: p.limit, fallback: 25, max: 100 }),
+ cursor: squareInputs.cursor(p.cursor),
+ }),
+ operation: 'search catalog items',
+ });
+ return squareShape.page({ items: squareShape.list({ value: body, key: 'items' }).map(squareShape.catalogItem), cursor: squareShape.str({ value: body, key: 'cursor' }) });
+ },
+});
diff --git a/packages/pieces/community/square/src/lib/actions/search-orders.ts b/packages/pieces/community/square/src/lib/actions/search-orders.ts
new file mode 100644
index 00000000000..abf18ee8ca4
--- /dev/null
+++ b/packages/pieces/community/square/src/lib/actions/search-orders.ts
@@ -0,0 +1,62 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { squareAuth } from '../auth';
+import { squareInputs } from '../common/inputs';
+import { squareOps } from '../common/operations';
+import { squareProps } from '../common/props';
+import { squareOutputSchemas } from '../output-schemas';
+
+export const searchOrdersAction = createAction({
+ name: 'search_orders',
+ classification: 'SEARCH',
+ auth: squareAuth,
+ displayName: 'Search Orders',
+ description: 'Finds orders by location, state, customer and creation date, newest first.',
+ audience: 'human',
+ aiMetadata: {
+ description: 'Searches Square orders with filters picked from lists; agents use Search Orders (by ID). Read-only and safe to retry.',
+ idempotent: true,
+ },
+ props: {
+ location_id: squareProps.location({ required: false, description: 'Leave empty to search all active locations (up to 10).' }),
+ states: orderStatesProp(),
+ customer_id: squareProps.customer({ required: false }),
+ created_after: Property.DateTime({ displayName: 'Created After', required: false }),
+ created_before: Property.DateTime({ displayName: 'Created Before', required: false }),
+ limit: squareProps.limitProp({ max: 500, fallback: 50 }),
+ cursor: squareProps.cursorProp(),
+ },
+ outputSchema: squareOutputSchemas.orders,
+ async run(context) {
+ const p = context.propsValue;
+ const locationId = squareInputs.optionalId({ value: p.location_id, label: 'Location' });
+ const customerId = squareInputs.optionalId({ value: p.customer_id, label: 'Customer' });
+ return squareOps.searchOrders({
+ auth: context.auth,
+ locationIds: locationId ? [locationId] : [],
+ states: Array.isArray(p.states) ? p.states.filter((s): s is string => typeof s === 'string') : [],
+ createdAfter: squareInputs.dateTime({ value: p.created_after, label: 'Created After' }),
+ createdBefore: squareInputs.dateTime({ value: p.created_before, label: 'Created Before' }),
+ customerIds: customerId ? [customerId] : [],
+ limit: squareInputs.limit({ value: p.limit, fallback: 50, max: 500 }),
+ cursor: squareInputs.cursor(p.cursor),
+ });
+ },
+});
+
+function orderStatesProp() {
+ return Property.StaticMultiSelectDropdown({
+ displayName: 'States',
+ description: 'Leave empty for all states.',
+ required: false,
+ options: {
+ options: [
+ { label: 'Open', value: 'OPEN' },
+ { label: 'Completed', value: 'COMPLETED' },
+ { label: 'Canceled', value: 'CANCELED' },
+ { label: 'Draft', value: 'DRAFT' },
+ ],
+ },
+ });
+}
+
+export const orderStatesSelect = orderStatesProp;
diff --git a/packages/pieces/community/square/src/lib/actions/set-inventory-count.ts b/packages/pieces/community/square/src/lib/actions/set-inventory-count.ts
new file mode 100644
index 00000000000..728db079747
--- /dev/null
+++ b/packages/pieces/community/square/src/lib/actions/set-inventory-count.ts
@@ -0,0 +1,37 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { squareAuth } from '../auth';
+import { squareIdempotency } from '../common/idempotency';
+import { squareInputs } from '../common/inputs';
+import { squareMoney } from '../common/money';
+import { squareOps } from '../common/operations';
+import { squareProps } from '../common/props';
+import { squareOutputSchemas } from '../output-schemas';
+
+export const setInventoryCountAction = createAction({
+ name: 'set_inventory_count',
+ classification: 'WRITE',
+ auth: squareAuth,
+ displayName: 'Set Inventory Count',
+ description: 'Sets the in-stock count of an item variation after a stock take. Needs a connection created or reconnected with piece version 1.0.0 or later.',
+ audience: 'human',
+ aiMetadata: {
+ description: 'Sets the absolute in-stock count of a variation picked from lists; agents use Set Inventory Count (by ID). Setting the same count again is safe.',
+ idempotent: true,
+ },
+ props: {
+ item: squareProps.catalogItem({ required: true }),
+ variation_id: squareProps.variation({ required: true }),
+ location_id: squareProps.location({ required: true }),
+ quantity: Property.ShortText({ displayName: 'Quantity In Stock', description: 'The counted number of units, for example 12.', required: true }),
+ },
+ outputSchema: squareOutputSchemas.inventoryCounts,
+ async run(context) {
+ const p = context.propsValue;
+ const change = squareOps.physicalCountChange({
+ variationId: squareInputs.requireId({ value: p.variation_id, label: 'Variation' }),
+ locationId: squareInputs.requireId({ value: p.location_id, label: 'Location' }),
+ quantity: squareMoney.quantity({ value: p.quantity, label: 'Quantity In Stock', allowZero: true }),
+ });
+ return squareIdempotency.execute({ context, action: 'set_inventory_count', input: change, send: ({ idempotencyKey }) => squareOps.changeInventory({ auth: context.auth, change: { ...change, physical_count: { ...change.physical_count, occurred_at: new Date().toISOString() } }, idempotencyKey }) });
+ },
+});
diff --git a/packages/pieces/community/square/src/lib/actions/update-customer.ts b/packages/pieces/community/square/src/lib/actions/update-customer.ts
new file mode 100644
index 00000000000..1be87d46396
--- /dev/null
+++ b/packages/pieces/community/square/src/lib/actions/update-customer.ts
@@ -0,0 +1,29 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { squareAuth } from '../auth';
+import { squareInputs } from '../common/inputs';
+import { squareOps } from '../common/operations';
+import { squareProps } from '../common/props';
+import { squareOutputSchemas } from '../output-schemas';
+
+export const updateCustomerAction = createAction({
+ name: 'update_customer',
+ classification: 'WRITE',
+ auth: squareAuth,
+ displayName: 'Update Customer',
+ description: 'Changes fields on a customer profile. Empty fields keep their current value.',
+ audience: 'human',
+ aiMetadata: {
+ description: 'Updates a Square customer picked from a list; agents use Update Customer (by ID). Only filled fields change. Setting the same values again is safe.',
+ idempotent: true,
+ },
+ props: {
+ customer_id: squareProps.customer({ required: true }),
+ ...squareProps.customerFields({ forUpdate: true }),
+ clear_fields: squareProps.clearCustomerFields(),
+ },
+ outputSchema: squareOutputSchemas.customer,
+ async run(context) {
+ const customerId = squareInputs.requireId({ value: context.propsValue.customer_id, label: 'Customer' });
+ return squareOps.updateCustomer({ auth: context.auth, customerId, props: context.propsValue });
+ },
+});
diff --git a/packages/pieces/community/square/src/lib/actions/update-item-variation-price.ts b/packages/pieces/community/square/src/lib/actions/update-item-variation-price.ts
new file mode 100644
index 00000000000..8d092b4840f
--- /dev/null
+++ b/packages/pieces/community/square/src/lib/actions/update-item-variation-price.ts
@@ -0,0 +1,34 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { squareAuth } from '../auth';
+import { squareIdempotency } from '../common/idempotency';
+import { squareInputs } from '../common/inputs';
+import { squareOps } from '../common/operations';
+import { squareProps } from '../common/props';
+import { squareOutputSchemas } from '../output-schemas';
+
+export const updateItemVariationPriceAction = createAction({
+ name: 'update_item_variation_price',
+ classification: 'WRITE',
+ auth: squareAuth,
+ displayName: 'Update Item Price',
+ description: 'Changes the price, SKU or name of an item variation.',
+ audience: 'human',
+ aiMetadata: {
+ description: 'Updates the price, SKU or name of a variation picked from lists; agents use Update Item Price (by ID). Setting the same values again is safe.',
+ idempotent: true,
+ },
+ props: {
+ item: squareProps.catalogItem({ required: true }),
+ variation_id: squareProps.variation({ required: true }),
+ price: Property.ShortText({ displayName: 'New Price', description: 'For example 12.50. Leave empty to keep the price.', required: false }),
+ currency: Property.ShortText({ displayName: 'Currency', description: 'Leave empty to keep the current currency.', required: false }),
+ sku: Property.ShortText({ displayName: 'New SKU', required: false }),
+ name: Property.ShortText({ displayName: 'New Variation Name', required: false }),
+ },
+ outputSchema: squareOutputSchemas.variation,
+ async run(context) {
+ const variationId = squareInputs.requireId({ value: context.propsValue.variation_id, label: 'Variation' });
+ const { item: _item, ...input } = context.propsValue;
+ return squareIdempotency.execute({ context, action: 'update_item_variation_price', input, send: ({ idempotencyKey }) => squareOps.updateVariation({ auth: context.auth, variationId, props: context.propsValue, idempotencyKey }) });
+ },
+});
diff --git a/packages/pieces/community/square/src/lib/actions/update-order-state.ts b/packages/pieces/community/square/src/lib/actions/update-order-state.ts
new file mode 100644
index 00000000000..160c8994bc2
--- /dev/null
+++ b/packages/pieces/community/square/src/lib/actions/update-order-state.ts
@@ -0,0 +1,42 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { squareAuth } from '../auth';
+import { squareIdempotency } from '../common/idempotency';
+import { squareInputs } from '../common/inputs';
+import { squareOps } from '../common/operations';
+import { squareOutputSchemas } from '../output-schemas';
+
+export const updateOrderStateAction = createAction({
+ name: 'update_order_state',
+ classification: 'DESTRUCTIVE',
+ auth: squareAuth,
+ displayName: 'Complete or Cancel Order',
+ description: 'Marks an open order as completed or canceled.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Moves an OPEN Square order to COMPLETED (needs all its payments completed) or CANCELED. Canceling cannot be undone. It reads the current version first. A retried step in the same run returns the same order; a later run on an order that is no longer OPEN fails without changing it.',
+ idempotent: true,
+ },
+ props: {
+ order_id: Property.ShortText({ displayName: 'Order ID', required: true }),
+ state: Property.StaticDropdown({
+ displayName: 'New State',
+ required: true,
+ options: {
+ options: [
+ { label: 'Completed', value: 'COMPLETED' },
+ { label: 'Canceled', value: 'CANCELED' },
+ ],
+ },
+ }),
+ },
+ outputSchema: squareOutputSchemas.order,
+ async run(context) {
+ const orderId = squareInputs.requireId({ value: context.propsValue.order_id, label: 'Order ID' });
+ const state = squareInputs.requireText({ value: context.propsValue.state, label: 'New State' });
+ if (state !== 'COMPLETED' && state !== 'CANCELED') {
+ throw new Error('New State must be COMPLETED or CANCELED.');
+ }
+ return squareIdempotency.execute({ context, action: 'update_order_state', input: { orderId, state }, send: ({ idempotencyKey }) => squareOps.setOrderState({ auth: context.auth, orderId, state, idempotencyKey }) });
+ },
+});
diff --git a/packages/pieces/community/square/src/lib/auth.ts b/packages/pieces/community/square/src/lib/auth.ts
index 24cfd170434..83874b421a8 100644
--- a/packages/pieces/community/square/src/lib/auth.ts
+++ b/packages/pieces/community/square/src/lib/auth.ts
@@ -1,21 +1,25 @@
import { PieceAuth } from '@activepieces/pieces-framework';
+export const SQUARE_SCOPES = [
+ 'MERCHANT_PROFILE_READ',
+ 'CUSTOMERS_READ',
+ 'CUSTOMERS_WRITE',
+ 'ITEMS_READ',
+ 'ITEMS_WRITE',
+ 'ORDERS_READ',
+ 'ORDERS_WRITE',
+ 'PAYMENTS_READ',
+ 'PAYMENTS_WRITE',
+ 'INVENTORY_READ',
+ 'INVENTORY_WRITE',
+ 'EMPLOYEES_READ',
+];
+
export const squareAuth = PieceAuth.OAuth2({
- description: 'Authentication',
+ description:
+ 'Sign in with the Square seller account you want to automate (production accounts only). Connections created before piece version 1.0.0 do not have the payment, inventory and team permissions: reconnect Square to use those actions.',
authUrl: 'https://connect.squareup.com/oauth2/authorize',
tokenUrl: 'https://connect.squareup.com/oauth2/token',
required: true,
- scope: [
- 'MERCHANT_PROFILE_READ',
- 'CUSTOMERS_READ',
- 'CUSTOMERS_WRITE',
- 'ITEMS_READ',
- 'ITEMS_WRITE',
- 'ORDERS_READ',
- 'ORDERS_WRITE',
- 'PAYMENTS_READ',
- 'INVOICES_READ',
- 'APPOINTMENTS_READ',
- 'APPOINTMENTS_WRITE',
- ],
+ scope: SQUARE_SCOPES,
});
diff --git a/packages/pieces/community/square/src/lib/common/client.ts b/packages/pieces/community/square/src/lib/common/client.ts
new file mode 100644
index 00000000000..55abc34abe2
--- /dev/null
+++ b/packages/pieces/community/square/src/lib/common/client.ts
@@ -0,0 +1,239 @@
+import { httpClient, HttpMethod, QueryParams } from '@activepieces/pieces-common';
+
+const BASE_URL = 'https://connect.squareup.com';
+const SQUARE_VERSION = '2026-09-16';
+const REQUEST_TIMEOUT_MS = 60_000;
+const MAX_RATE_LIMIT_RETRIES = 3;
+const RATE_LIMIT_BASE_DELAY_MS = 1_000;
+const MAX_ERROR_TEXT = 600;
+
+export class SquareApiError extends Error {
+ readonly status: number;
+ readonly code: string | undefined;
+ readonly responseBody: unknown;
+
+ constructor({ operation, status, responseBody }: { operation: string; status: number; responseBody: unknown }) {
+ super(`Square could not ${operation}: ${describe({ status, responseBody })}`);
+ this.name = 'SquareApiError';
+ this.status = status;
+ this.code = firstError(responseBody)?.code;
+ this.responseBody = responseBody;
+ }
+}
+
+async function request<T>({
+ auth,
+ method,
+ path,
+ query,
+ body,
+ operation,
+}: {
+ auth: SquareAuth;
+ method: HttpMethod;
+ path: string[];
+ query?: Record<string, string | number | boolean | undefined>;
+ body?: unknown;
+ operation: string;
+}): Promise<T> {
+ const url = `${BASE_URL}/${path.map((part, index) => (index === 0 ? part : segment({ value: part, label: 'ID' }))).join('/')}`;
+ const queryParams = toQueryParams(query);
+ for (let attempt = 0; ; attempt++) {
+ try {
+ const response = await httpClient.sendRequest<T>({
+ method,
+ url,
+ headers: {
+ Authorization: `Bearer ${auth.access_token}`,
+ 'Square-Version': SQUARE_VERSION,
+ Accept: 'application/json',
+ ...(body === undefined ? {} : { 'Content-Type': 'application/json' }),
+ },
+ queryParams,
+ body,
+ timeout: REQUEST_TIMEOUT_MS,
+ followRedirects: false,
+ });
+ if (response.status >= 300) {
+ throw new SquareApiError({ operation, status: response.status, responseBody: 'Square answered with an unexpected redirect.' });
+ }
+ return response.body;
+ } catch (error) {
+ if (error instanceof SquareApiError) {
+ throw error;
+ }
+ const status = statusOf(error);
+ if (status === undefined) {
+ throw error;
+ }
+ if (status === 429 && attempt < MAX_RATE_LIMIT_RETRIES) {
+ await sleep(RATE_LIMIT_BASE_DELAY_MS * 2 ** attempt + Math.floor(Math.random() * 250));
+ continue;
+ }
+ throw new SquareApiError({ operation, status, responseBody: responseBodyOf(error) });
+ }
+ }
+}
+
+function segment({ value, label }: { value: unknown; label: string }): string {
+ const text = typeof value === 'string' ? value.trim() : typeof value === 'number' ? String(value) : '';
+ if (text.length === 0) {
+ throw new Error(`${label} is required.`);
+ }
+ if (text === '.' || text === '..' || text.includes('/') || text.includes('\\') || text.includes('?') || text.includes('#')) {
+ throw new Error(`${label} "${text.slice(0, 80)}" is not valid. Use the Square ID only.`);
+ }
+ return encodeURIComponent(text);
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
+}
+
+async function resolveLocation({ auth, locationId }: { auth: SquareAuth; locationId?: string }): Promise<Record<string, unknown>> {
+ const id = typeof locationId === 'string' && locationId.trim().length > 0 ? locationId.trim() : 'main';
+ const body = await request<unknown>({
+ auth,
+ method: HttpMethod.GET,
+ path: ['v2', 'locations', id],
+ operation: `read location "${id}"`,
+ });
+ const location = isRecord(body) ? body['location'] : undefined;
+ if (!isRecord(location) || typeof location['id'] !== 'string') {
+ throw new Error('Square returned an unexpected location response.');
+ }
+ return location;
+}
+
+function toQueryParams(query: Record<string, string | number | boolean | undefined> | undefined): QueryParams | undefined {
+ if (!query) {
+ return undefined;
+ }
+ const entries = Object.entries(query).filter((entry): entry is [string, string | number | boolean] => entry[1] !== undefined && entry[1] !== '');
+ return entries.length === 0 ? undefined : Object.fromEntries(entries.map(([key, value]) => [key, String(value)]));
+}
+
+function firstError(responseBody: unknown): SquareErrorItem | undefined {
+ if (!isRecord(responseBody) || !Array.isArray(responseBody['errors'])) {
+ return undefined;
+ }
+ const first = responseBody['errors'].find(isRecord);
+ if (!first) {
+ return undefined;
+ }
+ return {
+ code: typeof first['code'] === 'string' ? first['code'] : undefined,
+ detail: typeof first['detail'] === 'string' ? first['detail'] : undefined,
+ field: typeof first['field'] === 'string' ? first['field'] : undefined,
+ };
+}
+
+function vendorText(responseBody: unknown): string {
+ if (isRecord(responseBody) && Array.isArray(responseBody['errors'])) {
+ const parts = responseBody['errors'].filter(isRecord).slice(0, 3).map((item) => {
+ const code = typeof item['code'] === 'string' ? item['code'] : 'ERROR';
+ const detail = typeof item['detail'] === 'string' ? `: ${item['detail']}` : '';
+ const field = typeof item['field'] === 'string' ? ` (field ${item['field']})` : '';
+ return `${code}${detail}${field}`;
+ });
+ if (parts.length > 0) {
+ return parts.join('; ').slice(0, MAX_ERROR_TEXT);
+ }
+ }
+ if (typeof responseBody === 'string' && responseBody.trim().length > 0) {
+ return responseBody.trim().slice(0, MAX_ERROR_TEXT);
+ }
+ if (isRecord(responseBody)) {
+ return JSON.stringify(responseBody).slice(0, MAX_ERROR_TEXT);
+ }
+ return 'no details returned';
+}
+
+function missingScopes(detail: string | undefined): string | undefined {
+ if (!detail) {
+ return undefined;
+ }
+ const match = /scopes?:\s*([A-Z_,\s]+)/.exec(detail);
+ return match ? match[1].trim().replace(/[,\s]+$/, '') : undefined;
+}
+
+function describe({ status, responseBody }: { status: number; responseBody: unknown }): string {
+ const detail = vendorText(responseBody);
+ const first = firstError(responseBody);
+ if (status === 401) {
+ return `the Square connection has expired or was revoked. Reconnect Square and try again. (${detail})`;
+ }
+ if (status === 403 && first?.code === 'INSUFFICIENT_SCOPES') {
+ const scopes = missingScopes(first.detail);
+ return `this connection is missing the Square permission${scopes ? ` ${scopes}` : ''}. Reconnect your Square connection (connections created before piece version 1.0.0 lack the newer permissions) and approve the requested permissions, then run the step again.`;
+ }
+ if (status === 404) {
+ return `not found. Check the ID; it must belong to the connected Square account. (${detail})`;
+ }
+ if (status === 409 || first?.code === 'VERSION_MISMATCH') {
+ return `the record changed in Square while this step ran. Run the step again to use the latest version. (${detail})`;
+ }
+ if (status === 429) {
+ return `Square rate limit reached after several retries; try again in a minute. (${detail})`;
+ }
+ return `HTTP ${status}. ${detail}`;
+}
+
+function statusOf(error: unknown): number | undefined {
+ if (!(error instanceof Error)) {
+ return undefined;
+ }
+ const response: unknown = Reflect.get(error, 'response');
+ if (isRecord(response) && typeof response['status'] === 'number') {
+ return response['status'];
+ }
+ return undefined;
+}
+
+function responseBodyOf(error: unknown): unknown {
+ if (!(error instanceof Error)) {
+ return undefined;
+ }
+ const response: unknown = Reflect.get(error, 'response');
+ return isRecord(response) ? response['body'] : undefined;
+}
+
+function assertSquareUrl({ url }: { url: unknown }): void {
+ if (typeof url !== 'string') {
+ return;
+ }
+ const trimmed = url.trim();
+ if (!/^[a-z][a-z0-9+.-]*:/i.test(trimmed) && !trimmed.startsWith('//')) {
+ return;
+ }
+ const allowed = new URL(BASE_URL);
+ const parsed = URL.canParse(trimmed) ? new URL(trimmed) : null;
+ if (
+ parsed === null ||
+ parsed.protocol !== allowed.protocol ||
+ parsed.hostname !== allowed.hostname ||
+ parsed.port !== '' ||
+ parsed.username !== '' ||
+ parsed.password !== ''
+ ) {
+ throw new Error(`Custom API Call only sends the Square token to ${BASE_URL}. Use a path like /v2/locations or a full ${BASE_URL} URL.`);
+ }
+}
+
+function sleep(ms: number): Promise<void> {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
+
+export const squareClient = {
+ request,
+ segment,
+ isRecord,
+ resolveLocation,
+ assertSquareUrl,
+ BASE_URL,
+ SQUARE_VERSION,
+};
+
+export type SquareAuth = { access_token: string; data?: Record<string, unknown> };
+
+type SquareErrorItem = { code: string | undefined; detail: string | undefined; field: string | undefined };
diff --git a/packages/pieces/community/square/src/lib/common/idempotency.ts b/packages/pieces/community/square/src/lib/common/idempotency.ts
new file mode 100644
index 00000000000..63ee6ec48ea
--- /dev/null
+++ b/packages/pieces/community/square/src/lib/common/idempotency.ts
@@ -0,0 +1,50 @@
+import crypto from 'crypto';
+
+const KEY_LENGTH = 40;
+const MAX_CUSTOM_KEY_LENGTH = 45;
+
+function customKey({ value }: { value: unknown }): string | null {
+ if (typeof value !== 'string' || value.trim().length === 0) {
+ return null;
+ }
+ const trimmed = value.trim();
+ if (trimmed.length > MAX_CUSTOM_KEY_LENGTH) {
+ throw new Error(`Idempotency Key must be at most ${MAX_CUSTOM_KEY_LENGTH} characters.`);
+ }
+ return trimmed;
+}
+
+function key({ custom, runId, stepName, action, input }: { custom: unknown; runId: string | undefined; stepName: string | undefined; action: string; input: unknown }): string {
+ const given = customKey({ value: custom });
+ if (given !== null) {
+ return given;
+ }
+ const seed = runId && runId.length > 0 ? `${runId}|${stepName ?? ''}` : crypto.randomUUID();
+ return crypto.createHash('sha256').update(`${seed}|${action}|${canonical(input)}`).digest('hex').slice(0, KEY_LENGTH);
+}
+
+async function execute<T>({ context, action, input, send }: { context: IdempotencyContext; action: string; input: unknown; send: (params: { idempotencyKey: string }) => Promise<T> }): Promise<T> {
+ const idempotencyKey = key({ custom: context.propsValue['idempotency_key'], runId: context.run?.id, stepName: context.step?.name, action, input });
+ return send({ idempotencyKey });
+}
+
+function canonical(value: unknown): string {
+ if (Array.isArray(value)) {
+ return `[${value.map(canonical).join(',')}]`;
+ }
+ if (value !== null && typeof value === 'object') {
+ const entries = Object.entries(value)
+ .filter((entry) => entry[1] !== undefined)
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
+ return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`).join(',')}}`;
+ }
+ return JSON.stringify(value ?? null);
+}
+
+export const squareIdempotency = { key, execute, customKey, canonical, MAX_CUSTOM_KEY_LENGTH };
+
+type IdempotencyContext = {
+ propsValue: Record<string, unknown>;
+ run?: { id: string };
+ step?: { name: string };
+};
diff --git a/packages/pieces/community/square/src/lib/common/inputs.ts b/packages/pieces/community/square/src/lib/common/inputs.ts
new file mode 100644
index 00000000000..fe8f401a437
--- /dev/null
+++ b/packages/pieces/community/square/src/lib/common/inputs.ts
@@ -0,0 +1,113 @@
+function text(value: unknown): string | undefined {
+ if (typeof value === 'number' && Number.isFinite(value)) {
+ return String(value);
+ }
+ if (typeof value !== 'string') {
+ return undefined;
+ }
+ const trimmed = value.trim();
+ return trimmed.length > 0 ? trimmed : undefined;
+}
+
+function requireText({ value, label }: { value: unknown; label: string }): string {
+ const result = text(value);
+ if (result === undefined) {
+ throw new Error(`${label} is required.`);
+ }
+ return result;
+}
+
+function requireId({ value, label }: { value: unknown; label: string }): string {
+ const id = requireText({ value, label });
+ if (id.length > 192 || /[\s/\\?#]/.test(id)) {
+ throw new Error(`${label} "${id.slice(0, 80)}" is not a valid Square ID.`);
+ }
+ return id;
+}
+
+function optionalId({ value, label }: { value: unknown; label: string }): string | undefined {
+ return text(value) === undefined ? undefined : requireId({ value, label });
+}
+
+function idList({ value, label, max }: { value: unknown; label: string; max: number }): string[] {
+ const raw = Array.isArray(value) ? value : typeof value === 'string' ? value.split(',') : [];
+ const ids = raw.map((item) => text(item)).filter((item): item is string => item !== undefined);
+ const unique = [...new Set(ids)];
+ if (unique.length > max) {
+ throw new Error(`${label} accepts at most ${max} IDs (got ${unique.length}).`);
+ }
+ return unique.map((id) => requireId({ value: id, label }));
+}
+
+function limit({ value, fallback, max }: { value: unknown; fallback: number; max: number }): number {
+ if (value === undefined || value === null || value === '') {
+ return fallback;
+ }
+ const parsed = typeof value === 'number' ? value : Number(String(value).trim());
+ if (!Number.isInteger(parsed) || parsed < 1) {
+ throw new Error(`Limit must be a whole number between 1 and ${max}.`);
+ }
+ return Math.min(parsed, max);
+}
+
+function dateTime({ value, label }: { value: unknown; label: string }): string | undefined {
+ const raw = text(value);
+ if (raw === undefined) {
+ return undefined;
+ }
+ const parsed = new Date(raw);
+ if (Number.isNaN(parsed.getTime())) {
+ throw new Error(`${label} "${raw.slice(0, 40)}" is not a valid date and time. Use ISO 8601, for example 2026-10-07T09:00:00Z.`);
+ }
+ return parsed.toISOString();
+}
+
+function dateOnly({ value, label }: { value: unknown; label: string }): string | undefined {
+ const raw = text(value);
+ if (raw === undefined) {
+ return undefined;
+ }
+ const match = /^(\d{4}-\d{2}-\d{2})/.exec(raw);
+ if (!match || Number.isNaN(new Date(`${match[1]}T00:00:00Z`).getTime())) {
+ throw new Error(`${label} "${raw.slice(0, 40)}" is not a valid date. Use YYYY-MM-DD.`);
+ }
+ return match[1];
+}
+
+function email({ value, label }: { value: unknown; label: string }): string | undefined {
+ const raw = text(value);
+ if (raw === undefined) {
+ return undefined;
+ }
+ if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(raw)) {
+ throw new Error(`${label} "${raw.slice(0, 80)}" is not a valid email address.`);
+ }
+ return raw;
+}
+
+function bool(value: unknown): boolean {
+ return value === true || value === 'true';
+}
+
+function url({ value, label }: { value: unknown; label: string }): string | undefined {
+ const raw = text(value);
+ if (raw === undefined) {
+ return undefined;
+ }
+ let parsed: URL;
+ try {
+ parsed = new URL(raw);
+ } catch {
+ throw new Error(`${label} "${raw.slice(0, 80)}" is not a valid URL.`);
+ }
+ if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {
+ throw new Error(`${label} must start with https:// or http://.`);
+ }
+ return raw;
+}
+
+function cursor(value: unknown): string | undefined {
+ return text(value);
+}
+
+export const squareInputs = { text, requireText, requireId, optionalId, idList, limit, dateTime, dateOnly, email, bool, url, cursor };
diff --git a/packages/pieces/community/square/src/lib/common/money.ts b/packages/pieces/community/square/src/lib/common/money.ts
new file mode 100644
index 00000000000..6763d60d9d1
--- /dev/null
+++ b/packages/pieces/community/square/src/lib/common/money.ts
@@ -0,0 +1,89 @@
+const MAX_MINOR = BigInt(Number.MAX_SAFE_INTEGER);
+
+function exponent(currency: string): number {
+ try {
+ const digits = new Intl.NumberFormat('en', { style: 'currency', currency }).resolvedOptions().maximumFractionDigits;
+ return typeof digits === 'number' ? digits : 2;
+ } catch {
+ return 2;
+ }
+}
+
+function normalizeCurrency(value: unknown): string | undefined {
+ if (typeof value !== 'string' || value.trim().length === 0) {
+ return undefined;
+ }
+ const code = value.trim().toUpperCase();
+ if (!/^[A-Z]{3}$/.test(code)) {
+ throw new Error(`Currency "${value.slice(0, 20)}" is not a 3-letter ISO code such as USD.`);
+ }
+ return code;
+}
+
+function toMinor({ amount, currency, label, allowZero = false }: { amount: unknown; currency: string; label: string; allowZero?: boolean }): number {
+ const text = typeof amount === 'number' ? numberText(amount) : typeof amount === 'string' ? amount.trim() : '';
+ if (text.length === 0) {
+ throw new Error(`${label} is required, for example 12.50.`);
+ }
+ const match = /^(\d+)(?:\.(\d+))?$/.exec(text);
+ if (!match) {
+ throw new Error(`${label} "${text.slice(0, 30)}" is not a valid amount. Use digits and an optional decimal point, for example 12.50 (no currency symbol, no minus sign).`);
+ }
+ const places = exponent(currency);
+ const fraction = match[2] ?? '';
+ if (fraction.length > places) {
+ const trimmed = fraction.replace(/0+$/, '');
+ if (trimmed.length > places) {
+ throw new Error(`${label} ${text} has more decimal places than ${currency} allows (${places}).`);
+ }
+ }
+ const minorText = `${match[1]}${fraction.padEnd(places, '0').slice(0, places)}`;
+ const minor = BigInt(minorText);
+ if (minor > MAX_MINOR) {
+ throw new Error(`${label} ${text} is too large.`);
+ }
+ if (minor === BigInt(0) && !allowZero) {
+ throw new Error(`${label} must be greater than zero.`);
+ }
+ return Number(minor);
+}
+
+function format({ minor, currency }: { minor: number; currency: string }): string {
+ const places = exponent(currency);
+ const negative = minor < 0;
+ const digits = String(Math.abs(Math.trunc(minor)));
+ if (places === 0) {
+ return `${negative ? '-' : ''}${digits}`;
+ }
+ const padded = digits.padStart(places + 1, '0');
+ return `${negative ? '-' : ''}${padded.slice(0, -places)}.${padded.slice(-places)}`;
+}
+
+function numberText(value: number): string {
+ if (!Number.isFinite(value)) {
+ return 'invalid';
+ }
+ const text = String(value);
+ if (/e/i.test(text)) {
+ return value.toFixed(20).replace(/0+$/, '').replace(/\.$/, '');
+ }
+ return text;
+}
+
+function quantity({ value, label, allowZero = false, wholeOnly = false }: { value: unknown; label: string; allowZero?: boolean; wholeOnly?: boolean }): string {
+ const text = typeof value === 'number' ? numberText(value) : typeof value === 'string' ? value.trim() : '';
+ if (wholeOnly && !/^\d{1,9}$/.test(text)) {
+ throw new Error(`${label} "${String(value ?? '').slice(0, 30)}" must be a whole number such as 1 or 3.`);
+ }
+ if (!/^\d{1,12}(\.\d{1,5})?$/.test(text)) {
+ throw new Error(`${label} "${String(value ?? '').slice(0, 30)}" is not a valid quantity. Use a positive number with up to 5 decimals, for example 2 or 1.5.`);
+ }
+ const normalized = text.includes('.') ? text.replace(/0+$/, '').replace(/\.$/, '') : text;
+ const stripped = normalized.replace(/^0+(?=\d)/, '');
+ if (!allowZero && /^0(\.0*)?$/.test(stripped)) {
+ throw new Error(`${label} must be greater than zero.`);
+ }
+ return stripped;
+}
+
+export const squareMoney = { exponent, normalizeCurrency, toMinor, format, quantity };
diff --git a/packages/pieces/community/square/src/lib/common/operations.ts b/packages/pieces/community/square/src/lib/common/operations.ts
new file mode 100644
index 00000000000..bf1d42ae201
--- /dev/null
+++ b/packages/pieces/community/square/src/lib/common/operations.ts
@@ -0,0 +1,396 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { squareClient, SquareAuth } from './client';
+import { squareInputs } from './inputs';
+import { squareMoney } from './money';
+import { squareShape } from './shape';
+
+const MAX_LINE_ITEMS = 100;
+const ORDER_SEARCH_MAX_LOCATIONS = 10;
+
+const { request } = squareClient;
+
+async function getCustomer({ auth, customerId }: { auth: SquareAuth; customerId: string }) {
+ const body = await request<unknown>({ auth, method: HttpMethod.GET, path: ['v2', 'customers', customerId], operation: `read customer "${customerId}"` });
+ return squareShape.customer(squareShape.requireObject({ body, key: 'customer', what: 'customer' }));
+}
+
+function customerFields(props: Record<string, unknown>): Record<string, unknown> {
+ const address = {
+ address_line_1: squareInputs.text(props['address_line_1']),
+ address_line_2: squareInputs.text(props['address_line_2']),
+ locality: squareInputs.text(props['city']),
+ administrative_district_level_1: squareInputs.text(props['state']),
+ postal_code: squareInputs.text(props['postal_code']),
+ country: squareInputs.text(props['country'])?.toUpperCase(),
+ };
+ const hasAddress = Object.values(address).some((value) => value !== undefined);
+ return dropUndefined({
+ given_name: squareInputs.text(props['given_name']),
+ family_name: squareInputs.text(props['family_name']),
+ company_name: squareInputs.text(props['company_name']),
+ nickname: squareInputs.text(props['nickname']),
+ email_address: squareInputs.email({ value: props['email_address'], label: 'Email' }),
+ phone_number: squareInputs.text(props['phone_number']),
+ birthday: squareInputs.dateOnly({ value: props['birthday'], label: 'Birthday' }),
+ note: squareInputs.text(props['note']),
+ reference_id: squareInputs.text(props['reference_id']),
+ address: hasAddress ? dropUndefined(address) : undefined,
+ });
+}
+
+async function updateCustomer({ auth, customerId, props }: { auth: SquareAuth; customerId: string; props: Record<string, unknown> }) {
+ const fields = customerFields(props);
+ const clear = clearList(props['clear_fields']);
+ const clears = Object.fromEntries(clear.filter((name) => fields[name] === undefined).map((name) => [name, null]));
+ const changes = { ...clears, ...fields };
+ if (Object.keys(changes).length === 0) {
+ throw new Error('Nothing to update. Fill at least one field or pick a field to clear.');
+ }
+ const current = await getCustomer({ auth, customerId });
+ const body = await request<unknown>({
+ auth,
+ method: HttpMethod.PUT,
+ path: ['v2', 'customers', customerId],
+ body: { ...changes, version: current.version ?? undefined },
+ operation: `update customer "${customerId}"`,
+ });
+ return squareShape.customer(squareShape.requireObject({ body, key: 'customer', what: 'customer' }));
+}
+
+async function deleteCustomer({ auth, customerId }: { auth: SquareAuth; customerId: string }) {
+ await request<unknown>({ auth, method: HttpMethod.DELETE, path: ['v2', 'customers', customerId], operation: `delete customer "${customerId}"` });
+ return { id: customerId, deleted: true };
+}
+
+async function retrieveObject({ auth, objectId }: { auth: SquareAuth; objectId: string }) {
+ const body = await request<unknown>({
+ auth,
+ method: HttpMethod.GET,
+ path: ['v2', 'catalog', 'object', objectId],
+ operation: `read catalog object "${objectId}"`,
+ });
+ return squareShape.requireObject({ body, key: 'object', what: 'catalog object' });
+}
+
+async function createCatalogItem({ auth, props, idempotencyKey }: { auth: SquareAuth; props: Record<string, unknown>; idempotencyKey: string }) {
+ const name = squareInputs.requireText({ value: props['name'], label: 'Name' });
+ const categoryId = squareInputs.optionalId({ value: props['category_id'], label: 'Category' });
+ const priceText = squareInputs.text(props['price']);
+ const currency = priceText === undefined ? undefined : await currencyFor({ auth, currency: props['currency'], locationId: undefined });
+ const variationData = dropUndefined({
+ item_id: '#item',
+ name: squareInputs.text(props['variation_name']) ?? 'Regular',
+ sku: squareInputs.text(props['sku']),
+ pricing_type: priceText === undefined ? 'VARIABLE_PRICING' : 'FIXED_PRICING',
+ price_money: priceText === undefined || currency === undefined ? undefined : { amount: squareMoney.toMinor({ amount: priceText, currency, label: 'Price', allowZero: true }), currency },
+ });
+ const body = await request<unknown>({
+ auth,
+ method: HttpMethod.POST,
+ path: ['v2', 'catalog', 'object'],
+ body: {
+ idempotency_key: idempotencyKey,
+ object: {
+ type: 'ITEM',
+ id: '#item',
+ present_at_all_locations: true,
+ item_data: dropUndefined({
+ name,
+ description: squareInputs.text(props['description']),
+ categories: categoryId ? [{ id: categoryId }] : undefined,
+ variations: [{ type: 'ITEM_VARIATION', id: '#variation', present_at_all_locations: true, item_variation_data: variationData }],
+ }),
+ },
+ },
+ operation: 'create the catalog item',
+ });
+ return squareShape.catalogItem(squareShape.requireObject({ body, key: 'catalog_object', what: 'catalog item' }));
+}
+
+async function updateVariation({ auth, variationId, props, idempotencyKey }: { auth: SquareAuth; variationId: string; props: Record<string, unknown>; idempotencyKey: string }) {
+ const priceText = squareInputs.text(props['price']);
+ const sku = squareInputs.text(props['sku']);
+ const name = squareInputs.text(props['name']);
+ if (priceText === undefined && sku === undefined && name === undefined) {
+ throw new Error('Nothing to update. Fill Price, SKU or Name.');
+ }
+ const current = await retrieveObject({ auth, objectId: variationId });
+ if (current['type'] !== 'ITEM_VARIATION') {
+ throw new Error(`Catalog object "${variationId}" is a ${String(current['type'])}, not an item variation. Use the variation ID (from Search Catalog Items > variations).`);
+ }
+ const data = squareShape.rec({ value: current, key: 'item_variation_data' });
+ const existingCurrency = squareShape.str({ value: squareShape.rec({ value: data, key: 'price_money' }), key: 'currency' });
+ const currency = priceText === undefined ? undefined : squareMoney.normalizeCurrency(props['currency']) ?? existingCurrency ?? (await currencyFor({ auth, currency: undefined, locationId: undefined }));
+ const updatedData = {
+ ...data,
+ ...(name === undefined ? {} : { name }),
+ ...(sku === undefined ? {} : { sku }),
+ ...(priceText === undefined || currency === undefined
+ ? {}
+ : { pricing_type: 'FIXED_PRICING', price_money: { amount: squareMoney.toMinor({ amount: priceText, currency, label: 'Price', allowZero: true }), currency } }),
+ };
+ const body = await request<unknown>({
+ auth,
+ method: HttpMethod.POST,
+ path: ['v2', 'catalog', 'object'],
+ body: { idempotency_key: idempotencyKey, object: { ...current, item_variation_data: updatedData } },
+ operation: `update variation "${variationId}"`,
+ });
+ return squareShape.variation(squareShape.requireObject({ body, key: 'catalog_object', what: 'catalog variation' }));
+}
+
+async function getInventory({ auth, variationIds, locationIds, limit, cursor }: { auth: SquareAuth; variationIds: string[]; locationIds: string[]; limit: number; cursor: string | undefined }) {
+ if (variationIds.length === 0) {
+ throw new Error('Give at least one variation ID.');
+ }
+ const body = await request<unknown>({
+ auth,
+ method: HttpMethod.POST,
+ path: ['v2', 'inventory', 'counts', 'batch-retrieve'],
+ body: dropUndefined({ catalog_object_ids: variationIds, location_ids: locationIds.length > 0 ? locationIds : undefined, limit, cursor }),
+ operation: 'read inventory counts',
+ });
+ return squareShape.page({ items: squareShape.list({ value: body, key: 'counts' }).map(squareShape.inventoryCount), cursor: squareShape.str({ value: body, key: 'cursor' }) });
+}
+
+async function changeInventory({ auth, change, idempotencyKey }: { auth: SquareAuth; change: Record<string, unknown>; idempotencyKey: string }) {
+ const body = await request<unknown>({
+ auth,
+ method: HttpMethod.POST,
+ path: ['v2', 'inventory', 'changes', 'batch-create'],
+ body: { idempotency_key: idempotencyKey, changes: [change], ignore_unchanged_counts: false },
+ operation: 'change the inventory count',
+ });
+ return squareShape.page({ items: squareShape.list({ value: body, key: 'counts' }).map(squareShape.inventoryCount), cursor: null });
+}
+
+function adjustmentChange({ variationId, locationId, quantity, reason }: { variationId: string; locationId: string; quantity: string; reason: string }) {
+ const states = ADJUSTMENT_STATES[reason];
+ if (!states) {
+ throw new Error(`Reason "${reason}" is not supported. Use one of: ${Object.keys(ADJUSTMENT_STATES).join(', ')}.`);
+ }
+ return {
+ type: 'ADJUSTMENT',
+ adjustment: { catalog_object_id: variationId, from_location_id: locationId, to_location_id: locationId, from_state: states.from, to_state: states.to, quantity },
+ };
+}
+
+function physicalCountChange({ variationId, locationId, quantity }: { variationId: string; locationId: string; quantity: string }) {
+ return { type: 'PHYSICAL_COUNT', physical_count: { catalog_object_id: variationId, location_id: locationId, state: 'IN_STOCK', quantity } };
+}
+
+async function currencyFor({ auth, currency, locationId }: { auth: SquareAuth; currency: unknown; locationId: string | undefined }): Promise<string> {
+ const explicit = squareMoney.normalizeCurrency(currency);
+ if (explicit) {
+ return explicit;
+ }
+ const location = await squareClient.resolveLocation({ auth, locationId });
+ const found = squareShape.str({ value: location, key: 'currency' });
+ if (!found) {
+ throw new Error('Could not find the currency of the location. Fill Currency.');
+ }
+ return found;
+}
+
+function buildLineItems({ items, currency }: { items: unknown; currency: string }) {
+ const rows = Array.isArray(items) ? items.filter(squareShape.isRecord) : [];
+ if (rows.length === 0) {
+ throw new Error('Add at least one line item.');
+ }
+ if (rows.length > MAX_LINE_ITEMS) {
+ throw new Error(`At most ${MAX_LINE_ITEMS} line items are allowed per order.`);
+ }
+ return rows.map((row, index) => {
+ const label = `Line item ${index + 1}`;
+ const variationId = squareInputs.optionalId({ value: row['variation_id'] ?? row['catalog_object_id'], label: `${label} variation ID` });
+ const name = squareInputs.text(row['name']);
+ const price = squareInputs.text(row['price'] ?? row['amount']);
+ const quantity = squareMoney.quantity({ value: squareInputs.text(row['quantity']) ?? '1', label: `${label} quantity`, wholeOnly: true });
+ const note = squareInputs.text(row['note']);
+ if (variationId) {
+ if (price !== undefined) {
+ return dropUndefined({ catalog_object_id: variationId, quantity, note, base_price_money: { amount: squareMoney.toMinor({ amount: price, currency, label: `${label} price`, allowZero: true }), currency } });
+ }
+ return dropUndefined({ catalog_object_id: variationId, quantity, note });
+ }
+ if (!name || price === undefined) {
+ throw new Error(`${label}: pick a catalog item (variation ID), or give both a name and a price.`);
+ }
+ return dropUndefined({ name, quantity, note, base_price_money: { amount: squareMoney.toMinor({ amount: price, currency, label: `${label} price`, allowZero: true }), currency } });
+ });
+}
+
+async function createOrder({
+ auth,
+ locationId,
+ customerId,
+ referenceId,
+ items,
+ idempotencyKey,
+}: {
+ auth: SquareAuth;
+ locationId: string | undefined;
+ customerId: string | undefined;
+ referenceId: string | undefined;
+ items: unknown;
+ idempotencyKey: string;
+}) {
+ const location = await squareClient.resolveLocation({ auth, locationId });
+ const currency = squareShape.str({ value: location, key: 'currency' }) ?? 'USD';
+ const lineItems = buildLineItems({ items, currency });
+ const body = await request<unknown>({
+ auth,
+ method: HttpMethod.POST,
+ path: ['v2', 'orders'],
+ body: {
+ idempotency_key: idempotencyKey,
+ order: dropUndefined({ location_id: String(location['id']), customer_id: customerId, reference_id: referenceId, line_items: lineItems }),
+ },
+ operation: 'create the order',
+ });
+ return squareShape.order(squareShape.requireObject({ body, key: 'order', what: 'order' }));
+}
+
+async function setOrderState({ auth, orderId, state, idempotencyKey }: { auth: SquareAuth; orderId: string; state: string; idempotencyKey: string }) {
+ const current = await request<unknown>({ auth, method: HttpMethod.GET, path: ['v2', 'orders', orderId], operation: `read order "${orderId}"` });
+ const order = squareShape.requireObject({ body: current, key: 'order', what: 'order' });
+ const body = await request<unknown>({
+ auth,
+ method: HttpMethod.PUT,
+ path: ['v2', 'orders', orderId],
+ body: { idempotency_key: idempotencyKey, order: { location_id: order['location_id'], version: order['version'], state } },
+ operation: `set order "${orderId}" to ${state}`,
+ });
+ return squareShape.order(squareShape.requireObject({ body, key: 'order', what: 'order' }));
+}
+
+async function searchOrders({
+ auth,
+ locationIds,
+ states,
+ createdAfter,
+ createdBefore,
+ customerIds,
+ limit,
+ cursor,
+}: {
+ auth: SquareAuth;
+ locationIds: string[];
+ states: string[];
+ createdAfter: string | undefined;
+ createdBefore: string | undefined;
+ customerIds: string[];
+ limit: number;
+ cursor: string | undefined;
+}) {
+ const ids = locationIds.length > 0 ? locationIds : await activeLocationIds({ auth });
+ if (ids.length > ORDER_SEARCH_MAX_LOCATIONS) {
+ throw new Error(`Search Orders covers at most ${ORDER_SEARCH_MAX_LOCATIONS} locations per call. Pick the locations to search.`);
+ }
+ const filter = dropUndefined({
+ state_filter: states.length > 0 ? { states } : undefined,
+ date_time_filter: createdAfter || createdBefore ? { created_at: dropUndefined({ start_at: createdAfter, end_at: createdBefore }) } : undefined,
+ customer_filter: customerIds.length > 0 ? { customer_ids: customerIds } : undefined,
+ });
+ const body = await request<unknown>({
+ auth,
+ method: HttpMethod.POST,
+ path: ['v2', 'orders', 'search'],
+ body: dropUndefined({ location_ids: ids, limit, cursor, return_entries: false, query: { filter, sort: { sort_field: 'CREATED_AT', sort_order: 'DESC' } } }),
+ operation: 'search orders',
+ });
+ return squareShape.page({ items: squareShape.list({ value: body, key: 'orders' }).map(squareShape.order), cursor: squareShape.str({ value: body, key: 'cursor' }) });
+}
+
+async function activeLocationIds({ auth }: { auth: SquareAuth }): Promise<string[]> {
+ const body = await request<unknown>({ auth, method: HttpMethod.GET, path: ['v2', 'locations'], operation: 'list locations' });
+ return squareShape
+ .list({ value: body, key: 'locations' })
+ .filter((l) => l['status'] === 'ACTIVE' && typeof l['id'] === 'string')
+ .map((l) => String(l['id']));
+}
+
+async function createPaymentLink({
+ auth,
+ locationId,
+ name,
+ amount,
+ currency,
+ description,
+ redirectUrl,
+ paymentNote,
+ idempotencyKey,
+}: {
+ auth: SquareAuth;
+ locationId: string | undefined;
+ name: string;
+ amount: unknown;
+ currency: unknown;
+ description: string | undefined;
+ redirectUrl: string | undefined;
+ paymentNote: string | undefined;
+ idempotencyKey: string;
+}) {
+ const location = await squareClient.resolveLocation({ auth, locationId });
+ const resolvedCurrency = squareMoney.normalizeCurrency(currency) ?? squareShape.str({ value: location, key: 'currency' });
+ if (!resolvedCurrency) {
+ throw new Error('Could not find the currency of the location. Fill Currency.');
+ }
+ const body = await request<unknown>({
+ auth,
+ method: HttpMethod.POST,
+ path: ['v2', 'online-checkout', 'payment-links'],
+ body: dropUndefined({
+ idempotency_key: idempotencyKey,
+ description,
+ payment_note: paymentNote,
+ quick_pay: {
+ name,
+ location_id: String(location['id']),
+ price_money: { amount: squareMoney.toMinor({ amount, currency: resolvedCurrency, label: 'Amount' }), currency: resolvedCurrency },
+ },
+ checkout_options: redirectUrl ? { redirect_url: redirectUrl } : undefined,
+ }),
+ operation: 'create the payment link',
+ });
+ return squareShape.paymentLink(squareShape.requireObject({ body, key: 'payment_link', what: 'payment link' }));
+}
+
+function clearList(value: unknown): string[] {
+ return Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string' && CLEARABLE_CUSTOMER_FIELDS.includes(item)) : [];
+}
+
+function dropUndefined<T extends Record<string, unknown>>(value: T): Record<string, unknown> {
+ return Object.fromEntries(Object.entries(value).filter((entry) => entry[1] !== undefined));
+}
+
+const ADJUSTMENT_STATES: Record<string, { from: string; to: string }> = {
+ RECEIVED: { from: 'NONE', to: 'IN_STOCK' },
+ SOLD: { from: 'IN_STOCK', to: 'SOLD' },
+ WASTE: { from: 'IN_STOCK', to: 'WASTE' },
+};
+
+const CLEARABLE_CUSTOMER_FIELDS = ['given_name', 'family_name', 'company_name', 'nickname', 'email_address', 'phone_number', 'birthday', 'note', 'reference_id', 'address'];
+
+export const squareOps = {
+ getCustomer,
+ customerFields,
+ updateCustomer,
+ deleteCustomer,
+ retrieveObject,
+ createCatalogItem,
+ updateVariation,
+ getInventory,
+ changeInventory,
+ adjustmentChange,
+ physicalCountChange,
+ currencyFor,
+ createOrder,
+ setOrderState,
+ searchOrders,
+ activeLocationIds,
+ createPaymentLink,
+ dropUndefined,
+ ADJUSTMENT_STATES,
+ CLEARABLE_CUSTOMER_FIELDS,
+};
diff --git a/packages/pieces/community/square/src/lib/common/props.ts b/packages/pieces/community/square/src/lib/common/props.ts
new file mode 100644
index 00000000000..9fef1fa5bd4
--- /dev/null
+++ b/packages/pieces/community/square/src/lib/common/props.ts
@@ -0,0 +1,376 @@
+import { DropdownOption, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { squareAuth } from '../auth';
+import { squareClient, SquareAuth } from './client';
+import { squareShape } from './shape';
+
+const DROPDOWN_MAX = 1000;
+const LINE_ITEM_ITEMS_MAX = 500;
+const CUSTOMER_MATCH_MAX = 100;
+const CUSTOMER_SCAN_MAX = 10000;
+const CUSTOMER_SEARCH_BUDGET_MS = 20_000;
+
+function location({ required, displayName = 'Location', description }: { required: boolean; displayName?: string; description?: string }) {
+ return Property.Dropdown({
+ auth: squareAuth,
+ displayName,
+ description: description ?? (required ? 'The Square location (store) to use.' : 'The Square location (store) to use. Leave empty for your main location.'),
+ required,
+ refreshers: [],
+ options: async ({ auth }) => {
+ if (!auth) {
+ return connectFirst();
+ }
+ try {
+ const body = await squareClient.request<unknown>({ auth, method: HttpMethod.GET, path: ['v2', 'locations'], operation: 'list locations' });
+ const options = squareShape
+ .list({ value: body, key: 'locations' })
+ .map(squareShape.location)
+ .filter((l) => l.id !== null && l.status === 'ACTIVE')
+ .map((l) => ({ label: `${l.name ?? l.id}${l.currency ? ` (${l.currency})` : ''}`, value: l.id ?? '' }));
+ return options.length > 0 ? { disabled: false, options } : { disabled: true, placeholder: 'No active locations found in Square.', options: [] };
+ } catch (error) {
+ return failed({ error, what: 'locations' });
+ }
+ },
+ });
+}
+
+function customer({ required, displayName = 'Customer', description }: { required: boolean; displayName?: string; description?: string }) {
+ return Property.Dropdown({
+ auth: squareAuth,
+ displayName,
+ description:
+ description ??
+ 'Pick a customer. Type an email to search all customers, or part of a name to search up to the 10,000 newest (the search stops after 20 seconds). For an older customer, search by email or map the Customer ID.',
+ required,
+ refreshers: [],
+ refreshOnSearch: true,
+ options: async ({ auth }, { searchValue }) => {
+ if (!auth) {
+ return connectFirst();
+ }
+ try {
+ const term = (searchValue ?? '').trim().toLowerCase();
+ const found = term.includes('@')
+ ? { customers: await searchCustomersByEmail({ auth, email: term }), scanned: 0, complete: true }
+ : await listCustomers({ auth, nameTerm: term.length > 0 ? term : undefined });
+ const options = found.customers
+ .filter((c) => term.length === 0 || customerLabel(c).toLowerCase().includes(term))
+ .slice(0, DROPDOWN_MAX)
+ .map((c) => ({ label: customerLabel(c), value: c.id ?? '' }));
+ if (options.length === 0) {
+ if (term && !found.complete) {
+ return { disabled: false, placeholder: `No match in the ${found.scanned} newest customers searched. Search by email or map the Customer ID.`, options: [] };
+ }
+ return { disabled: false, placeholder: term ? 'No customer matches this search.' : 'No customers found. New customers can take a few seconds to appear.', options: [] };
+ }
+ return { disabled: false, options };
+ } catch (error) {
+ return failed({ error, what: 'customers' });
+ }
+ },
+ });
+}
+
+function catalogItem({ required, displayName = 'Item', description }: { required: boolean; displayName?: string; description?: string }) {
+ return Property.Dropdown({
+ auth: squareAuth,
+ displayName,
+ description: description ?? 'Pick a catalog item. Type to search by name.',
+ required,
+ refreshers: [],
+ refreshOnSearch: true,
+ options: async ({ auth }, { searchValue }) => {
+ if (!auth) {
+ return connectFirst();
+ }
+ try {
+ const items = await searchItems({ auth, text: searchValue, productTypes: undefined, max: DROPDOWN_MAX });
+ const options = items.map((i) => ({ label: i.name ?? i.id ?? '', value: i.id ?? '' }));
+ return options.length > 0 ? { disabled: false, options } : { disabled: false, placeholder: 'No items found.', options: [] };
+ } catch (error) {
+ return failed({ error, what: 'catalog items' });
+ }
+ },
+ });
+}
+
+function variation({ required, itemProp = 'item', displayName = 'Variation', description }: { required: boolean; itemProp?: string; displayName?: string; description?: string }) {
+ return Property.Dropdown({
+ auth: squareAuth,
+ displayName,
+ description: description ?? 'The item variation (size, color, ...). Items without options have a single "Regular" variation.',
+ required,
+ refreshers: [itemProp],
+ options: async (propsValue) => {
+ const auth = propsValue.auth;
+ const itemId = propsValue[itemProp];
+ if (!auth) {
+ return connectFirst();
+ }
+ if (typeof itemId !== 'string' || itemId.length === 0) {
+ return { disabled: true, placeholder: 'Select an item first.', options: [] };
+ }
+ try {
+ const body = await squareClient.request<unknown>({ auth, method: HttpMethod.GET, path: ['v2', 'catalog', 'object', itemId], operation: 'read the item' });
+ const itemData = squareShape.rec({ value: squareShape.rec({ value: body, key: 'object' }), key: 'item_data' });
+ const options = squareShape
+ .list({ value: itemData, key: 'variations' })
+ .map((raw) => squareShape.variation(raw))
+ .filter((v) => v.id !== null)
+ .map((v) => ({ label: variationLabel(v), value: v.id ?? '' }));
+ return options.length > 0 ? { disabled: false, options } : { disabled: true, placeholder: 'This item has no variations.', options: [] };
+ } catch (error) {
+ return failed({ error, what: 'variations' });
+ }
+ },
+ });
+}
+
+function category({ required, displayName = 'Category', description }: { required: boolean; displayName?: string; description?: string }) {
+ return Property.Dropdown({
+ auth: squareAuth,
+ displayName,
+ description: description ?? 'The catalog category for the item.',
+ required,
+ refreshers: [],
+ options: async ({ auth }) => {
+ if (!auth) {
+ return connectFirst();
+ }
+ try {
+ const objects = await listCatalog({ auth, types: 'CATEGORY' });
+ const options = objects.map((o) => ({ label: squareShape.str({ value: squareShape.rec({ value: o, key: 'category_data' }), key: 'name' }) ?? String(o['id']), value: String(o['id']) }));
+ return options.length > 0 ? { disabled: false, options } : { disabled: false, placeholder: 'No categories found.', options: [] };
+ } catch (error) {
+ return failed({ error, what: 'categories' });
+ }
+ },
+ });
+}
+
+function lineItems({ displayName = 'Line Items', description }: { displayName?: string; description?: string } = {}) {
+ return Property.DynamicProperties({
+ auth: squareAuth,
+ displayName,
+ description: description ?? 'What the order contains. Pick a catalog item, or leave Catalog Item empty and fill Custom Name and Custom Price.',
+ required: true,
+ refreshers: [],
+ props: async ({ auth }) => {
+ let options: DropdownOption<string>[] = [];
+ if (auth) {
+ try {
+ const items = await searchItemObjects({ auth, text: undefined, productTypes: undefined, max: LINE_ITEM_ITEMS_MAX });
+ options = items
+ .flatMap((raw) => {
+ const name = squareShape.str({ value: squareShape.rec({ value: raw, key: 'item_data' }), key: 'name' }) ?? squareShape.str({ value: raw, key: 'id' });
+ return squareShape
+ .list({ value: squareShape.rec({ value: raw, key: 'item_data' }), key: 'variations' })
+ .map((variationRaw) => squareShape.variation(variationRaw))
+ .filter((v) => v.id !== null)
+ .map((v) => ({ label: `${name}${v.name && v.name !== 'Regular' ? ` - ${v.name}` : ''}${v.price ? ` (${v.price} ${v.currency ?? ''})` : ''}`.trim(), value: v.id ?? '' }));
+ })
+ .slice(0, DROPDOWN_MAX);
+ } catch {
+ options = [];
+ }
+ }
+ return {
+ items: Property.Array({
+ displayName: 'Items',
+ required: true,
+ properties: {
+ variation_id: Property.StaticDropdown({
+ displayName: 'Catalog Item',
+ required: false,
+ options: { disabled: false, options },
+ }),
+ name: Property.ShortText({ displayName: 'Custom Name', description: 'For an item that is not in the catalog.', required: false }),
+ price: Property.ShortText({ displayName: 'Custom Price', description: 'Unit price for a custom item, for example 12.50.', required: false }),
+ quantity: Property.ShortText({ displayName: 'Quantity', description: 'Whole number, defaults to 1.', required: false }),
+ note: Property.ShortText({ displayName: 'Note', required: false }),
+ },
+ }),
+ };
+ },
+ });
+}
+
+function locationIdText({ required = false }: { required?: boolean } = {}) {
+ return Property.ShortText({
+ displayName: 'Location ID',
+ description: required ? 'Square location ID (from List Locations).' : 'Square location ID (from List Locations). Leave empty to use the main location.',
+ required,
+ });
+}
+
+function idText({ displayName, description, required = true }: { displayName: string; description: string; required?: boolean }) {
+ return Property.ShortText({ displayName, description, required });
+}
+
+function limitProp({ max, fallback }: { max: number; fallback: number }) {
+ return Property.Number({ displayName: 'Limit', description: `How many results to return (1-${max}, default ${fallback}).`, required: false, defaultValue: fallback });
+}
+
+function cursorProp() {
+ return Property.ShortText({ displayName: 'Cursor', description: 'Next Cursor from a previous run, to get the next page. Cursors expire after about 5 minutes.', required: false });
+}
+
+function idempotencyKey() {
+ return Property.ShortText({
+ displayName: 'Idempotency Key',
+ description: 'Optional, up to 45 characters. Leave empty: a retried step returns the same record, but identical calls in one run (such as a loop with the same input) count as one. Set a unique value, like the loop item, to keep them separate.',
+ required: false,
+ });
+}
+
+function customerFields({ forUpdate }: { forUpdate: boolean }) {
+ const keep = forUpdate ? ' Leave empty to keep the current value.' : '';
+ return {
+ given_name: Property.ShortText({ displayName: 'First Name', description: `Given name.${keep}`, required: false }),
+ family_name: Property.ShortText({ displayName: 'Last Name', description: `Family name.${keep}`, required: false }),
+ company_name: Property.ShortText({ displayName: 'Company', required: false, description: forUpdate ? keep.trim() : undefined }),
+ nickname: Property.ShortText({ displayName: 'Nickname', required: false }),
+ email_address: Property.ShortText({ displayName: 'Email', required: false }),
+ phone_number: Property.ShortText({ displayName: 'Phone', description: 'Phone number in international format, for example +14155550123.', required: false }),
+ birthday: Property.ShortText({ displayName: 'Birthday', description: 'YYYY-MM-DD, or 0000-MM-DD when the year is unknown.', required: false }),
+ note: Property.LongText({ displayName: 'Note', required: false }),
+ reference_id: Property.ShortText({ displayName: 'Reference ID', description: 'Your own ID for this customer, for example from your CRM.', required: false }),
+ address_line_1: Property.ShortText({ displayName: 'Address Line 1', required: false }),
+ address_line_2: Property.ShortText({ displayName: 'Address Line 2', required: false }),
+ city: Property.ShortText({ displayName: 'City', required: false }),
+ state: Property.ShortText({ displayName: 'State / Region', required: false }),
+ postal_code: Property.ShortText({ displayName: 'Postal Code', required: false }),
+ country: Property.ShortText({ displayName: 'Country', description: 'Two-letter country code, for example US.', required: false }),
+ };
+}
+
+function clearCustomerFields() {
+ return Property.StaticMultiSelectDropdown({
+ displayName: 'Fields to Clear',
+ description: 'Fields to empty on the customer. A field you also fill above is set, not cleared. Address clears the whole address.',
+ required: false,
+ options: {
+ options: [
+ { label: 'First Name', value: 'given_name' },
+ { label: 'Last Name', value: 'family_name' },
+ { label: 'Company', value: 'company_name' },
+ { label: 'Nickname', value: 'nickname' },
+ { label: 'Email', value: 'email_address' },
+ { label: 'Phone', value: 'phone_number' },
+ { label: 'Birthday', value: 'birthday' },
+ { label: 'Note', value: 'note' },
+ { label: 'Reference ID', value: 'reference_id' },
+ { label: 'Address', value: 'address' },
+ ],
+ },
+ });
+}
+
+async function listCustomers({ auth, nameTerm }: { auth: SquareAuth; nameTerm?: string }) {
+ const results: ReturnType<typeof squareShape.customer>[] = [];
+ const deadline = Date.now() + CUSTOMER_SEARCH_BUDGET_MS;
+ let scanned = 0;
+ let cursor: string | undefined;
+ do {
+ const body = await squareClient.request<unknown>({
+ auth,
+ method: HttpMethod.GET,
+ path: ['v2', 'customers'],
+ query: { limit: 100, sort_field: 'CREATED_AT', sort_order: 'DESC', cursor },
+ operation: 'list customers',
+ });
+ const page = squareShape.list({ value: body, key: 'customers' }).map(squareShape.customer);
+ scanned += page.length;
+ results.push(...(nameTerm ? page.filter((c) => customerLabel(c).toLowerCase().includes(nameTerm)) : page));
+ cursor = squareShape.str({ value: body, key: 'cursor' }) ?? undefined;
+ } while (cursor && Date.now() < deadline && (nameTerm ? results.length < CUSTOMER_MATCH_MAX && scanned < CUSTOMER_SCAN_MAX : results.length < DROPDOWN_MAX));
+ return { customers: results, scanned, complete: cursor === undefined };
+}
+
+async function searchCustomersByEmail({ auth, email }: { auth: SquareAuth; email: string }) {
+ const body = await squareClient.request<unknown>({
+ auth,
+ method: HttpMethod.POST,
+ path: ['v2', 'customers', 'search'],
+ body: { query: { filter: { email_address: { fuzzy: email } } }, limit: 100 },
+ operation: 'search customers',
+ });
+ return squareShape.list({ value: body, key: 'customers' }).map(squareShape.customer);
+}
+
+async function searchItems(params: { auth: SquareAuth; text: string | undefined; productTypes: string[] | undefined; max: number }) {
+ return (await searchItemObjects(params)).map(squareShape.catalogItem);
+}
+
+async function searchItemObjects({ auth, text, productTypes, max }: { auth: SquareAuth; text: string | undefined; productTypes: string[] | undefined; max: number }) {
+ const results: Record<string, unknown>[] = [];
+ let cursor: string | undefined;
+ const textFilter = text && text.trim().length > 0 ? text.trim() : undefined;
+ do {
+ const body = await squareClient.request<unknown>({
+ auth,
+ method: HttpMethod.POST,
+ path: ['v2', 'catalog', 'search-catalog-items'],
+ body: { text_filter: textFilter, product_types: productTypes, limit: 100, cursor },
+ operation: 'search catalog items',
+ });
+ results.push(...squareShape.list({ value: body, key: 'items' }));
+ cursor = squareShape.str({ value: body, key: 'cursor' }) ?? undefined;
+ } while (cursor && results.length < max);
+ return results.slice(0, max);
+}
+
+async function listCatalog({ auth, types }: { auth: SquareAuth; types: string }) {
+ const results: Record<string, unknown>[] = [];
+ let cursor: string | undefined;
+ do {
+ const body = await squareClient.request<unknown>({ auth, method: HttpMethod.GET, path: ['v2', 'catalog', 'list'], query: { types, cursor }, operation: 'list the catalog' });
+ results.push(...squareShape.list({ value: body, key: 'objects' }).filter((o) => typeof o['id'] === 'string'));
+ cursor = squareShape.str({ value: body, key: 'cursor' }) ?? undefined;
+ } while (cursor && results.length < DROPDOWN_MAX);
+ return results.slice(0, DROPDOWN_MAX);
+}
+
+function customerLabel(c: ReturnType<typeof squareShape.customer>): string {
+ const name = [c.given_name, c.family_name].filter(Boolean).join(' ') || c.company_name || c.nickname || '';
+ const contact = c.email_address ?? c.phone_number ?? '';
+ if (name && contact) {
+ return `${name} (${contact})`;
+ }
+ return name || contact || (c.id ?? '');
+}
+
+function variationLabel(v: ReturnType<typeof squareShape.variation>): string {
+ const price = v.price ? ` - ${v.price} ${v.currency ?? ''}`.trimEnd() : '';
+ const sku = v.sku ? ` [${v.sku}]` : '';
+ return `${v.name ?? v.id}${sku}${price}`;
+}
+
+function connectFirst() {
+ return { disabled: true, placeholder: 'Connect your Square account first.', options: [] };
+}
+
+function failed({ error, what }: { error: unknown; what: string }) {
+ const message = error instanceof Error ? error.message : 'unknown error';
+ return { disabled: true, placeholder: `Could not load ${what}: ${message}`.slice(0, 300), options: [] };
+}
+
+export const squareProps = {
+ location,
+ customer,
+ catalogItem,
+ variation,
+ category,
+ lineItems,
+ locationIdText,
+ idText,
+ limitProp,
+ cursorProp,
+ idempotencyKey,
+ customerFields,
+ clearCustomerFields,
+};
+
+export const squareLookups = { listCustomers, searchItems };
diff --git a/packages/pieces/community/square/src/lib/common/shape.ts b/packages/pieces/community/square/src/lib/common/shape.ts
new file mode 100644
index 00000000000..ca9e247e0c6
--- /dev/null
+++ b/packages/pieces/community/square/src/lib/common/shape.ts
@@ -0,0 +1,355 @@
+import { squareMoney } from './money';
+
+const MAX_LINE_ITEMS = 100;
+const MAX_VARIATIONS = 50;
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
+}
+
+function rec({ value, key }: { value: unknown; key: string }): Record<string, unknown> {
+ if (!isRecord(value)) {
+ return {};
+ }
+ const inner = value[key];
+ return isRecord(inner) ? inner : {};
+}
+
+function str({ value, key }: { value: unknown; key: string }): string | null {
+ if (!isRecord(value)) {
+ return null;
+ }
+ const inner = value[key];
+ return typeof inner === 'string' ? inner : typeof inner === 'number' ? String(inner) : null;
+}
+
+function num({ value, key }: { value: unknown; key: string }): number | null {
+ if (!isRecord(value)) {
+ return null;
+ }
+ const inner = value[key];
+ return typeof inner === 'number' && Number.isFinite(inner) ? inner : null;
+}
+
+function flag({ value, key }: { value: unknown; key: string }): boolean | null {
+ if (!isRecord(value)) {
+ return null;
+ }
+ const inner = value[key];
+ return typeof inner === 'boolean' ? inner : null;
+}
+
+function list({ value, key }: { value: unknown; key: string }): Record<string, unknown>[] {
+ if (!isRecord(value)) {
+ return [];
+ }
+ const inner = value[key];
+ return Array.isArray(inner) ? inner.filter(isRecord) : [];
+}
+
+function strings({ value, key }: { value: unknown; key: string }): string[] {
+ if (!isRecord(value)) {
+ return [];
+ }
+ const inner = value[key];
+ return Array.isArray(inner) ? inner.filter((item): item is string => typeof item === 'string') : [];
+}
+
+function money({ value, key }: { value: unknown; key: string }): { amount: string | null; minor: number | null; currency: string | null } {
+ const inner = rec({ value: value, key: key });
+ const minor = num({ value: inner, key: 'amount' });
+ const currency = str({ value: inner, key: 'currency' });
+ if (minor === null || currency === null) {
+ return { amount: null, minor: null, currency };
+ }
+ return { amount: squareMoney.format({ minor, currency }), minor, currency };
+}
+
+function address(value: unknown): Record<string, string | null> {
+ const a = rec({ value: value, key: 'address' });
+ return {
+ address_line_1: str({ value: a, key: 'address_line_1' }),
+ address_line_2: str({ value: a, key: 'address_line_2' }),
+ city: str({ value: a, key: 'locality' }),
+ state: str({ value: a, key: 'administrative_district_level_1' }),
+ postal_code: str({ value: a, key: 'postal_code' }),
+ country: str({ value: a, key: 'country' }),
+ };
+}
+
+function customer(c: unknown) {
+ return {
+ id: str({ value: c, key: 'id' }),
+ given_name: str({ value: c, key: 'given_name' }),
+ family_name: str({ value: c, key: 'family_name' }),
+ company_name: str({ value: c, key: 'company_name' }),
+ nickname: str({ value: c, key: 'nickname' }),
+ email_address: str({ value: c, key: 'email_address' }),
+ phone_number: str({ value: c, key: 'phone_number' }),
+ birthday: str({ value: c, key: 'birthday' }),
+ note: str({ value: c, key: 'note' }),
+ reference_id: str({ value: c, key: 'reference_id' }),
+ ...address(c),
+ email_unsubscribed: flag({ value: rec({ value: c, key: 'preferences' }), key: 'email_unsubscribed' }),
+ creation_source: str({ value: c, key: 'creation_source' }),
+ group_ids: strings({ value: c, key: 'group_ids' }),
+ version: num({ value: c, key: 'version' }),
+ created_at: str({ value: c, key: 'created_at' }),
+ updated_at: str({ value: c, key: 'updated_at' }),
+ };
+}
+
+function location(l: unknown) {
+ return {
+ id: str({ value: l, key: 'id' }),
+ name: str({ value: l, key: 'name' }),
+ business_name: str({ value: l, key: 'business_name' }),
+ status: str({ value: l, key: 'status' }),
+ type: str({ value: l, key: 'type' }),
+ country: str({ value: l, key: 'country' }),
+ currency: str({ value: l, key: 'currency' }),
+ timezone: str({ value: l, key: 'timezone' }),
+ language_code: str({ value: l, key: 'language_code' }),
+ ...address(l),
+ phone_number: str({ value: l, key: 'phone_number' }),
+ business_email: str({ value: l, key: 'business_email' }),
+ website_url: str({ value: l, key: 'website_url' }),
+ capabilities: strings({ value: l, key: 'capabilities' }),
+ merchant_id: str({ value: l, key: 'merchant_id' }),
+ created_at: str({ value: l, key: 'created_at' }),
+ };
+}
+
+function merchant(m: unknown) {
+ return {
+ id: str({ value: m, key: 'id' }),
+ business_name: str({ value: m, key: 'business_name' }),
+ country: str({ value: m, key: 'country' }),
+ language_code: str({ value: m, key: 'language_code' }),
+ currency: str({ value: m, key: 'currency' }),
+ status: str({ value: m, key: 'status' }),
+ main_location_id: str({ value: m, key: 'main_location_id' }),
+ created_at: str({ value: m, key: 'created_at' }),
+ };
+}
+
+function teamMember(t: unknown) {
+ const assigned = rec({ value: t, key: 'assigned_locations' });
+ return {
+ id: str({ value: t, key: 'id' }),
+ given_name: str({ value: t, key: 'given_name' }),
+ family_name: str({ value: t, key: 'family_name' }),
+ email_address: str({ value: t, key: 'email_address' }),
+ phone_number: str({ value: t, key: 'phone_number' }),
+ status: str({ value: t, key: 'status' }),
+ is_owner: flag({ value: t, key: 'is_owner' }),
+ reference_id: str({ value: t, key: 'reference_id' }),
+ assignment_type: str({ value: assigned, key: 'assignment_type' }),
+ location_ids: strings({ value: assigned, key: 'location_ids' }),
+ created_at: str({ value: t, key: 'created_at' }),
+ updated_at: str({ value: t, key: 'updated_at' }),
+ };
+}
+
+function variation(v: unknown) {
+ const data = rec({ value: v, key: 'item_variation_data' });
+ const price = money({ value: data, key: 'price_money' });
+ return {
+ id: str({ value: v, key: 'id' }),
+ item_id: str({ value: data, key: 'item_id' }),
+ name: str({ value: data, key: 'name' }),
+ sku: str({ value: data, key: 'sku' }),
+ pricing_type: str({ value: data, key: 'pricing_type' }),
+ price: price.amount,
+ price_minor: price.minor,
+ currency: price.currency,
+ version: num({ value: v, key: 'version' }),
+ is_deleted: flag({ value: v, key: 'is_deleted' }),
+ updated_at: str({ value: v, key: 'updated_at' }),
+ };
+}
+
+function catalogItem(o: unknown) {
+ const data = rec({ value: o, key: 'item_data' });
+ const variations = list({ value: data, key: 'variations' });
+ const categories = list({ value: data, key: 'categories' }).map((c) => str({ value: c, key: 'id' })).filter((id): id is string => id !== null);
+ const legacyCategory = str({ value: data, key: 'category_id' });
+ return {
+ id: str({ value: o, key: 'id' }),
+ type: str({ value: o, key: 'type' }),
+ name: str({ value: data, key: 'name' }),
+ description: str({ value: data, key: 'description_plaintext' }) ?? str({ value: data, key: 'description' }),
+ product_type: str({ value: data, key: 'product_type' }),
+ category_ids: categories.length > 0 ? categories : legacyCategory ? [legacyCategory] : [],
+ reporting_category_id: str({ value: rec({ value: data, key: 'reporting_category' }), key: 'id' }),
+ is_archived: flag({ value: data, key: 'is_archived' }),
+ is_deleted: flag({ value: o, key: 'is_deleted' }),
+ present_at_all_locations: flag({ value: o, key: 'present_at_all_locations' }),
+ version: num({ value: o, key: 'version' }),
+ updated_at: str({ value: o, key: 'updated_at' }),
+ variation_count: variations.length,
+ variations_truncated: variations.length > MAX_VARIATIONS,
+ variations: variations.slice(0, MAX_VARIATIONS).map(variation),
+ };
+}
+
+function lineItem(li: unknown) {
+ const base = money({ value: li, key: 'base_price_money' });
+ const total = money({ value: li, key: 'total_money' });
+ return {
+ uid: str({ value: li, key: 'uid' }),
+ name: str({ value: li, key: 'name' }),
+ variation_name: str({ value: li, key: 'variation_name' }),
+ catalog_object_id: str({ value: li, key: 'catalog_object_id' }),
+ quantity: str({ value: li, key: 'quantity' }),
+ note: str({ value: li, key: 'note' }),
+ base_price: base.amount,
+ total: total.amount,
+ total_minor: total.minor,
+ };
+}
+
+function order(o: unknown) {
+ const items = list({ value: o, key: 'line_items' });
+ const total = money({ value: o, key: 'total_money' });
+ const due = money({ value: o, key: 'net_amount_due_money' });
+ return {
+ id: str({ value: o, key: 'id' }),
+ location_id: str({ value: o, key: 'location_id' }),
+ customer_id: str({ value: o, key: 'customer_id' }),
+ reference_id: str({ value: o, key: 'reference_id' }),
+ state: str({ value: o, key: 'state' }),
+ version: num({ value: o, key: 'version' }),
+ source_name: str({ value: rec({ value: o, key: 'source' }), key: 'name' }),
+ ticket_name: str({ value: o, key: 'ticket_name' }),
+ currency: total.currency,
+ total: total.amount,
+ total_minor: total.minor,
+ total_tax: money({ value: o, key: 'total_tax_money' }).amount,
+ total_discount: money({ value: o, key: 'total_discount_money' }).amount,
+ total_tip: money({ value: o, key: 'total_tip_money' }).amount,
+ total_service_charge: money({ value: o, key: 'total_service_charge_money' }).amount,
+ net_amount_due: due.amount,
+ payment_ids: list({ value: o, key: 'tenders' }).map((t) => str({ value: t, key: 'payment_id' }) ?? str({ value: t, key: 'id' })).filter((id): id is string => id !== null),
+ fulfillment_states: list({ value: o, key: 'fulfillments' }).map((f) => str({ value: f, key: 'state' })).filter((s): s is string => s !== null),
+ line_item_count: items.length,
+ line_items_truncated: items.length > MAX_LINE_ITEMS,
+ line_items: items.slice(0, MAX_LINE_ITEMS).map(lineItem),
+ created_at: str({ value: o, key: 'created_at' }),
+ updated_at: str({ value: o, key: 'updated_at' }),
+ closed_at: str({ value: o, key: 'closed_at' }),
+ };
+}
+
+function payment(p: unknown) {
+ const amount = money({ value: p, key: 'amount_money' });
+ const total = money({ value: p, key: 'total_money' });
+ const card = rec({ value: rec({ value: p, key: 'card_details' }), key: 'card' });
+ const external = rec({ value: p, key: 'external_details' });
+ return {
+ id: str({ value: p, key: 'id' }),
+ status: str({ value: p, key: 'status' }),
+ source_type: str({ value: p, key: 'source_type' }),
+ location_id: str({ value: p, key: 'location_id' }),
+ order_id: str({ value: p, key: 'order_id' }),
+ customer_id: str({ value: p, key: 'customer_id' }),
+ reference_id: str({ value: p, key: 'reference_id' }),
+ note: str({ value: p, key: 'note' }),
+ currency: total.currency ?? amount.currency,
+ amount: amount.amount,
+ amount_minor: amount.minor,
+ tip: money({ value: p, key: 'tip_money' }).amount,
+ total: total.amount,
+ total_minor: total.minor,
+ refunded: money({ value: p, key: 'refunded_money' }).amount,
+ refunded_minor: money({ value: p, key: 'refunded_money' }).minor,
+ card_brand: str({ value: card, key: 'card_brand' }),
+ card_last_4: str({ value: card, key: 'last_4' }),
+ card_entry_method: str({ value: rec({ value: p, key: 'card_details' }), key: 'entry_method' }),
+ external_type: str({ value: external, key: 'type' }),
+ external_source: str({ value: external, key: 'source' }),
+ receipt_number: str({ value: p, key: 'receipt_number' }),
+ receipt_url: str({ value: p, key: 'receipt_url' }),
+ refund_ids: strings({ value: p, key: 'refund_ids' }),
+ created_at: str({ value: p, key: 'created_at' }),
+ updated_at: str({ value: p, key: 'updated_at' }),
+ };
+}
+
+function refund(r: unknown) {
+ const amount = money({ value: r, key: 'amount_money' });
+ return {
+ id: str({ value: r, key: 'id' }),
+ status: str({ value: r, key: 'status' }),
+ payment_id: str({ value: r, key: 'payment_id' }),
+ order_id: str({ value: r, key: 'order_id' }),
+ location_id: str({ value: r, key: 'location_id' }),
+ reason: str({ value: r, key: 'reason' }),
+ currency: amount.currency,
+ amount: amount.amount,
+ amount_minor: amount.minor,
+ processing_fee: money({ value: list({ value: r, key: 'processing_fee' })[0], key: 'amount_money' }).amount,
+ created_at: str({ value: r, key: 'created_at' }),
+ updated_at: str({ value: r, key: 'updated_at' }),
+ };
+}
+
+function inventoryCount(c: unknown) {
+ return {
+ variation_id: str({ value: c, key: 'catalog_object_id' }),
+ object_type: str({ value: c, key: 'catalog_object_type' }),
+ location_id: str({ value: c, key: 'location_id' }),
+ state: str({ value: c, key: 'state' }),
+ quantity: str({ value: c, key: 'quantity' }),
+ calculated_at: str({ value: c, key: 'calculated_at' }),
+ };
+}
+
+function paymentLink(l: unknown) {
+ return {
+ id: str({ value: l, key: 'id' }),
+ version: num({ value: l, key: 'version' }),
+ url: str({ value: l, key: 'url' }),
+ long_url: str({ value: l, key: 'long_url' }),
+ order_id: str({ value: l, key: 'order_id' }),
+ description: str({ value: l, key: 'description' }),
+ created_at: str({ value: l, key: 'created_at' }),
+ };
+}
+
+function page<T>({ items, cursor }: { items: T[]; cursor: unknown }) {
+ const next = typeof cursor === 'string' && cursor.length > 0 ? cursor : null;
+ return { count: items.length, has_more: next !== null, next_cursor: next, items };
+}
+
+function requireObject({ body, key, what }: { body: unknown; key: string; what: string }): Record<string, unknown> {
+ const inner = rec({ value: body, key: key });
+ if (typeof inner['id'] !== 'string') {
+ throw new Error(`Square returned an unexpected ${what} response.`);
+ }
+ return inner;
+}
+
+export const squareShape = {
+ isRecord,
+ rec,
+ str,
+ num,
+ list,
+ strings,
+ money,
+ customer,
+ location,
+ merchant,
+ teamMember,
+ catalogItem,
+ variation,
+ order,
+ payment,
+ refund,
+ inventoryCount,
+ paymentLink,
+ page,
+ requireObject,
+ MAX_LINE_ITEMS,
+};
diff --git a/packages/pieces/community/square/src/lib/output-schemas.ts b/packages/pieces/community/square/src/lib/output-schemas.ts
new file mode 100644
index 00000000000..dc8ed9ccb0a
--- /dev/null
+++ b/packages/pieces/community/square/src/lib/output-schemas.ts
@@ -0,0 +1,370 @@
+import { OutputSchema } from '@activepieces/pieces-framework';
+
+const addressFields: OutputSchema['fields'] = [
+ { key: 'address_line_1', label: 'Address Line 1' },
+ { key: 'address_line_2', label: 'Address Line 2' },
+ { key: 'city', label: 'City' },
+ { key: 'state', label: 'State / Region' },
+ { key: 'postal_code', label: 'Postal Code' },
+ { key: 'country', label: 'Country' },
+];
+
+const customerFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Customer ID' },
+ { key: 'given_name', label: 'First Name' },
+ { key: 'family_name', label: 'Last Name' },
+ { key: 'company_name', label: 'Company' },
+ { key: 'nickname', label: 'Nickname' },
+ { key: 'email_address', label: 'Email', format: 'email' },
+ { key: 'phone_number', label: 'Phone' },
+ { key: 'birthday', label: 'Birthday' },
+ { key: 'note', label: 'Note' },
+ { key: 'reference_id', label: 'Reference ID' },
+ ...addressFields,
+ { key: 'email_unsubscribed', label: 'Email Unsubscribed', format: 'boolean' },
+ { key: 'creation_source', label: 'Creation Source' },
+ { key: 'group_ids', label: 'Group IDs' },
+ { key: 'version', label: 'Version', format: 'number' },
+ { key: 'created_at', label: 'Created At', format: 'datetime' },
+ { key: 'updated_at', label: 'Updated At', format: 'datetime' },
+];
+
+const locationFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Location ID' },
+ { key: 'name', label: 'Name' },
+ { key: 'business_name', label: 'Business Name' },
+ { key: 'status', label: 'Status' },
+ { key: 'type', label: 'Type' },
+ { key: 'country', label: 'Country' },
+ { key: 'currency', label: 'Currency' },
+ { key: 'timezone', label: 'Time Zone' },
+ { key: 'language_code', label: 'Language' },
+ ...addressFields,
+ { key: 'phone_number', label: 'Phone' },
+ { key: 'business_email', label: 'Business Email', format: 'email' },
+ { key: 'website_url', label: 'Website', format: 'url' },
+ { key: 'capabilities', label: 'Capabilities' },
+ { key: 'merchant_id', label: 'Merchant ID' },
+ { key: 'created_at', label: 'Created At', format: 'datetime' },
+];
+
+const teamMemberFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Team Member ID' },
+ { key: 'given_name', label: 'First Name' },
+ { key: 'family_name', label: 'Last Name' },
+ { key: 'email_address', label: 'Email', format: 'email' },
+ { key: 'phone_number', label: 'Phone' },
+ { key: 'status', label: 'Status' },
+ { key: 'is_owner', label: 'Is Owner', format: 'boolean' },
+ { key: 'reference_id', label: 'Reference ID' },
+ { key: 'assignment_type', label: 'Location Assignment' },
+ { key: 'location_ids', label: 'Location IDs' },
+ { key: 'created_at', label: 'Created At', format: 'datetime' },
+ { key: 'updated_at', label: 'Updated At', format: 'datetime' },
+];
+
+const variationFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Variation ID' },
+ { key: 'item_id', label: 'Item ID' },
+ { key: 'name', label: 'Name' },
+ { key: 'sku', label: 'SKU' },
+ { key: 'pricing_type', label: 'Pricing Type' },
+ { key: 'price', label: 'Price', description: 'Decimal amount in major units, for example 12.50.' },
+ { key: 'price_minor', label: 'Price (Smallest Unit)', format: 'number', description: 'Amount in the smallest currency unit, for example cents.' },
+ { key: 'currency', label: 'Currency' },
+ { key: 'version', label: 'Version', format: 'number' },
+ { key: 'is_deleted', label: 'Is Deleted', format: 'boolean' },
+ { key: 'updated_at', label: 'Updated At', format: 'datetime' },
+];
+
+const catalogItemFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Item ID' },
+ { key: 'type', label: 'Object Type' },
+ { key: 'name', label: 'Name' },
+ { key: 'description', label: 'Description' },
+ { key: 'product_type', label: 'Product Type' },
+ { key: 'category_ids', label: 'Category IDs' },
+ { key: 'reporting_category_id', label: 'Reporting Category ID' },
+ { key: 'is_archived', label: 'Is Archived', format: 'boolean' },
+ { key: 'is_deleted', label: 'Is Deleted', format: 'boolean' },
+ { key: 'present_at_all_locations', label: 'At All Locations', format: 'boolean' },
+ { key: 'version', label: 'Version', format: 'number' },
+ { key: 'updated_at', label: 'Updated At', format: 'datetime' },
+ { key: 'variation_count', label: 'Variation Count', format: 'number' },
+ { key: 'variations_truncated', label: 'Variations Truncated', format: 'boolean' },
+ { key: 'variations', label: 'Variations', labelKey: 'name', listItems: variationFields },
+];
+
+const lineItemFields: OutputSchema['fields'] = [
+ { key: 'uid', label: 'Line Item UID' },
+ { key: 'name', label: 'Name' },
+ { key: 'variation_name', label: 'Variation Name' },
+ { key: 'catalog_object_id', label: 'Variation ID' },
+ { key: 'quantity', label: 'Quantity' },
+ { key: 'note', label: 'Note' },
+ { key: 'base_price', label: 'Unit Price' },
+ { key: 'total', label: 'Total' },
+ { key: 'total_minor', label: 'Total (Smallest Unit)', format: 'number' },
+];
+
+const orderFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Order ID' },
+ { key: 'location_id', label: 'Location ID' },
+ { key: 'customer_id', label: 'Customer ID' },
+ { key: 'reference_id', label: 'Reference ID' },
+ { key: 'state', label: 'State' },
+ { key: 'version', label: 'Version', format: 'number' },
+ { key: 'source_name', label: 'Source' },
+ { key: 'ticket_name', label: 'Ticket Name' },
+ { key: 'currency', label: 'Currency' },
+ { key: 'total', label: 'Total', description: 'Decimal amount in major units.' },
+ { key: 'total_minor', label: 'Total (Smallest Unit)', format: 'number' },
+ { key: 'total_tax', label: 'Total Tax' },
+ { key: 'total_discount', label: 'Total Discount' },
+ { key: 'total_tip', label: 'Total Tip' },
+ { key: 'total_service_charge', label: 'Total Service Charge' },
+ { key: 'net_amount_due', label: 'Amount Due' },
+ { key: 'payment_ids', label: 'Payment IDs' },
+ { key: 'fulfillment_states', label: 'Fulfillment States' },
+ { key: 'line_item_count', label: 'Line Item Count', format: 'number' },
+ { key: 'line_items_truncated', label: 'Line Items Truncated', format: 'boolean' },
+ { key: 'line_items', label: 'Line Items', labelKey: 'name', listItems: lineItemFields },
+ { key: 'created_at', label: 'Created At', format: 'datetime' },
+ { key: 'updated_at', label: 'Updated At', format: 'datetime' },
+ { key: 'closed_at', label: 'Closed At', format: 'datetime' },
+];
+
+const paymentFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Payment ID' },
+ { key: 'status', label: 'Status' },
+ { key: 'source_type', label: 'Source Type' },
+ { key: 'location_id', label: 'Location ID' },
+ { key: 'order_id', label: 'Order ID' },
+ { key: 'customer_id', label: 'Customer ID' },
+ { key: 'reference_id', label: 'Reference ID' },
+ { key: 'note', label: 'Note' },
+ { key: 'currency', label: 'Currency' },
+ { key: 'amount', label: 'Amount', description: 'Decimal amount in major units, before tip.' },
+ { key: 'amount_minor', label: 'Amount (Smallest Unit)', format: 'number' },
+ { key: 'tip', label: 'Tip' },
+ { key: 'total', label: 'Total' },
+ { key: 'total_minor', label: 'Total (Smallest Unit)', format: 'number' },
+ { key: 'refunded', label: 'Refunded' },
+ { key: 'refunded_minor', label: 'Refunded (Smallest Unit)', format: 'number' },
+ { key: 'card_brand', label: 'Card Brand' },
+ { key: 'card_last_4', label: 'Card Last 4' },
+ { key: 'card_entry_method', label: 'Card Entry Method' },
+ { key: 'external_type', label: 'External Payment Type' },
+ { key: 'external_source', label: 'External Payment Source' },
+ { key: 'receipt_number', label: 'Receipt Number' },
+ { key: 'receipt_url', label: 'Receipt URL', format: 'url' },
+ { key: 'refund_ids', label: 'Refund IDs' },
+ { key: 'created_at', label: 'Created At', format: 'datetime' },
+ { key: 'updated_at', label: 'Updated At', format: 'datetime' },
+];
+
+const refundFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Refund ID' },
+ { key: 'status', label: 'Status' },
+ { key: 'payment_id', label: 'Payment ID' },
+ { key: 'order_id', label: 'Order ID' },
+ { key: 'location_id', label: 'Location ID' },
+ { key: 'reason', label: 'Reason' },
+ { key: 'currency', label: 'Currency' },
+ { key: 'amount', label: 'Amount' },
+ { key: 'amount_minor', label: 'Amount (Smallest Unit)', format: 'number' },
+ { key: 'processing_fee', label: 'Processing Fee' },
+ { key: 'created_at', label: 'Created At', format: 'datetime' },
+ { key: 'updated_at', label: 'Updated At', format: 'datetime' },
+];
+
+const inventoryCountFields: OutputSchema['fields'] = [
+ { key: 'variation_id', label: 'Variation ID' },
+ { key: 'object_type', label: 'Object Type' },
+ { key: 'location_id', label: 'Location ID' },
+ { key: 'state', label: 'State' },
+ { key: 'quantity', label: 'Quantity', description: 'Decimal string, for example 12 or 2.5.' },
+ { key: 'calculated_at', label: 'Calculated At', format: 'datetime' },
+];
+
+const paymentLinkFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Payment Link ID' },
+ { key: 'version', label: 'Version', format: 'number' },
+ { key: 'url', label: 'Checkout URL', format: 'url' },
+ { key: 'long_url', label: 'Long URL', format: 'url' },
+ { key: 'order_id', label: 'Order ID' },
+ { key: 'description', label: 'Description' },
+ { key: 'created_at', label: 'Created At', format: 'datetime' },
+];
+
+const merchantFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Merchant ID' },
+ { key: 'business_name', label: 'Business Name' },
+ { key: 'country', label: 'Country' },
+ { key: 'language_code', label: 'Language' },
+ { key: 'currency', label: 'Currency' },
+ { key: 'status', label: 'Status' },
+ { key: 'main_location_id', label: 'Main Location ID' },
+ { key: 'created_at', label: 'Created At', format: 'datetime' },
+];
+
+const webhookEnvelope: OutputSchema['fields'] = [
+ { key: 'event_id', label: 'Event ID' },
+ { key: 'type', label: 'Event Type' },
+ { key: 'merchant_id', label: 'Merchant ID' },
+ { key: 'created_at', label: 'Event Time', format: 'datetime' },
+];
+
+function pageOf({ itemsLabel, labelKey, fields }: { itemsLabel: string; labelKey: string; fields: OutputSchema['fields'] }): OutputSchema {
+ return {
+ fields: [
+ { key: 'count', label: 'Count (This Page)', format: 'number' },
+ { key: 'has_more', label: 'Has More', format: 'boolean' },
+ { key: 'next_cursor', label: 'Next Cursor', description: 'Pass to Cursor to get the next page. Expires after about 5 minutes.' },
+ { key: 'items', label: itemsLabel, labelKey, listItems: fields },
+ ],
+ };
+}
+
+function eventSchema({ objectKey, objectLabel, fields }: { objectKey: string; objectLabel: string; fields: OutputSchema['fields'] }): OutputSchema {
+ return {
+ fields: [
+ ...webhookEnvelope,
+ {
+ key: 'data',
+ label: 'Data',
+ children: [
+ { key: 'id', label: 'Object ID' },
+ { key: 'type', label: 'Object Type' },
+ { key: 'object', label: 'Object', children: [{ key: objectKey, label: objectLabel, children: fields }] },
+ ],
+ },
+ ],
+ };
+}
+
+const rawCustomerFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Customer ID' },
+ { key: 'given_name', label: 'First Name' },
+ { key: 'family_name', label: 'Last Name' },
+ { key: 'company_name', label: 'Company' },
+ { key: 'email_address', label: 'Email', format: 'email' },
+ { key: 'phone_number', label: 'Phone' },
+ { key: 'reference_id', label: 'Reference ID' },
+ { key: 'note', label: 'Note' },
+ { key: 'creation_source', label: 'Creation Source' },
+ { key: 'version', label: 'Version', format: 'number' },
+ { key: 'created_at', label: 'Created At', format: 'datetime' },
+ { key: 'updated_at', label: 'Updated At', format: 'datetime' },
+];
+
+const rawMoney = ({ key, label }: { key: string; label: string }): OutputSchema['fields'][number] => ({
+ key,
+ label,
+ children: [
+ { key: 'amount', label: 'Amount (Smallest Unit)', format: 'number' },
+ { key: 'currency', label: 'Currency' },
+ ],
+});
+
+const rawPaymentFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Payment ID' },
+ { key: 'status', label: 'Status' },
+ { key: 'source_type', label: 'Source Type' },
+ { key: 'location_id', label: 'Location ID' },
+ { key: 'order_id', label: 'Order ID' },
+ { key: 'customer_id', label: 'Customer ID' },
+ { key: 'reference_id', label: 'Reference ID' },
+ { key: 'note', label: 'Note' },
+ rawMoney({ key: 'amount_money', label: 'Amount' }),
+ rawMoney({ key: 'tip_money', label: 'Tip' }),
+ rawMoney({ key: 'total_money', label: 'Total' }),
+ { key: 'receipt_number', label: 'Receipt Number' },
+ { key: 'receipt_url', label: 'Receipt URL', format: 'url' },
+ { key: 'created_at', label: 'Created At', format: 'datetime' },
+ { key: 'updated_at', label: 'Updated At', format: 'datetime' },
+];
+
+const updatedAtField: OutputSchema['fields'][number] = { key: 'updated_at', label: 'Updated At', format: 'datetime' };
+
+const orderEventSummary = (objectKey: string): OutputSchema => ({
+ fields: [
+ ...webhookEnvelope,
+ {
+ key: 'data',
+ label: 'Data',
+ children: [
+ { key: 'id', label: 'Order ID' },
+ {
+ key: 'object',
+ label: 'Object',
+ children: [
+ {
+ key: objectKey,
+ label: 'Order Summary',
+ children: [
+ { key: 'order_id', label: 'Order ID' },
+ { key: 'location_id', label: 'Location ID' },
+ { key: 'state', label: 'State' },
+ { key: 'version', label: 'Version', format: 'number' },
+ { key: 'created_at', label: 'Created At', format: 'datetime' },
+ ...(objectKey === 'order_updated' ? [updatedAtField] : []),
+ ],
+ },
+ ],
+ },
+ ],
+ },
+ { key: 'order', label: 'Full Order (when Include Full Order is on)', children: orderFields },
+ ],
+});
+
+const triggerSchemas: Record<string, OutputSchema> = {
+ new_order: orderEventSummary('order_created'),
+ order_updated: orderEventSummary('order_updated'),
+ new_customer: eventSchema({ objectKey: 'customer', objectLabel: 'Customer', fields: rawCustomerFields }),
+ customer_updated: eventSchema({ objectKey: 'customer', objectLabel: 'Customer', fields: rawCustomerFields }),
+ new_payment: eventSchema({ objectKey: 'payment', objectLabel: 'Payment', fields: rawPaymentFields }),
+};
+
+export const squareOutputSchemas = {
+ merchant: { fields: merchantFields },
+ locations: pageOf({ itemsLabel: 'Locations', labelKey: 'name', fields: locationFields }),
+ teamMembers: pageOf({ itemsLabel: 'Team Members', labelKey: 'given_name', fields: teamMemberFields }),
+ customer: { fields: customerFields },
+ customers: pageOf({ itemsLabel: 'Customers', labelKey: 'email_address', fields: customerFields }),
+ deleted: {
+ fields: [
+ { key: 'id', label: 'ID' },
+ { key: 'deleted', label: 'Deleted', format: 'boolean' },
+ ],
+ },
+ catalogItem: { fields: catalogItemFields },
+ catalogItems: pageOf({ itemsLabel: 'Items', labelKey: 'name', fields: catalogItemFields }),
+ variation: { fields: variationFields },
+ deletedCatalog: {
+ fields: [
+ { key: 'id', label: 'Deleted Object ID' },
+ { key: 'deleted', label: 'Deleted', format: 'boolean' },
+ { key: 'deleted_object_ids', label: 'All Deleted IDs' },
+ { key: 'deleted_at', label: 'Deleted At', format: 'datetime' },
+ ],
+ },
+ inventoryCounts: {
+ fields: [
+ { key: 'count', label: 'Count', format: 'number' },
+ { key: 'has_more', label: 'Has More', format: 'boolean' },
+ { key: 'next_cursor', label: 'Next Cursor' },
+ { key: 'items', label: 'Inventory Counts', labelKey: 'variation_id', listItems: inventoryCountFields },
+ ],
+ },
+ order: { fields: orderFields },
+ orders: pageOf({ itemsLabel: 'Orders', labelKey: 'id', fields: orderFields }),
+ payment: { fields: paymentFields },
+ payments: pageOf({ itemsLabel: 'Payments', labelKey: 'id', fields: paymentFields }),
+ refund: { fields: refundFields },
+ refunds: pageOf({ itemsLabel: 'Refunds', labelKey: 'id', fields: refundFields }),
+ paymentLink: { fields: paymentLinkFields },
+
+ triggers: triggerSchemas,
+} satisfies Record<string, OutputSchema | Record<string, OutputSchema>>;
diff --git a/packages/pieces/community/square/src/lib/triggers/index.ts b/packages/pieces/community/square/src/lib/triggers/index.ts
index 2e2a147b97f..2204468e17a 100644
--- a/packages/pieces/community/square/src/lib/triggers/index.ts
+++ b/packages/pieces/community/square/src/lib/triggers/index.ts
@@ -1,35 +1,32 @@
+import crypto from 'crypto';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { DEDUPE_KEY_PROPERTY, Property, TriggerStrategy, createTrigger } from '@activepieces/pieces-framework';
import { squareAuth } from '../auth';
-import { TriggerStrategy, createTrigger } from '@activepieces/pieces-framework';
+import { squareClient, SquareApiError, SquareAuth } from '../common/client';
+import { squareProps } from '../common/props';
+import { squareShape } from '../common/shape';
+import { squareOutputSchemas } from '../output-schemas';
+import { squareSamples } from './samples';
-const triggerData = [
+const DEDUPE_KEY_PREFIX = 'square_seen_events_';
+const DEDUPE_SLOT_COUNT = 64;
+const DEDUPE_WINDOW_MS = 15 * 60 * 1000;
+const DEDUPE_CLAIM_TIMEOUT_MS = 2 * 60 * 1000;
+const DEDUPE_MAX_PER_SLOT = 100;
+
+const triggerData: TriggerDefinition[] = [
{
name: 'new_order',
displayName: 'New Order',
description: 'Triggered when a new order is created',
aiMetadata: {
description:
- 'Fires when a new order is created in the Square seller account (order.created event). Represents a newly opened sale or transaction tied to a location, including the order id, location, state, and version.',
+ 'Fires when a new order is created in the Square seller account (order.created event). The payload is a summary (order id, location, state, version); turn on Include Full Order to also get line items and totals.',
},
event: 'order.created',
- sampleData: {
- merchant_id: 'MLTZ79VE64YTN',
- type: 'order.created',
- event_id: '03441e3a-47f1-49a7-a64c-55ab26703f8d',
- created_at: '2023-03-14T01:42:54.984089903Z',
- data: {
- type: 'order',
- id: 'eA3vssLHKJrv9H0IdJCM3gNqfdcZY',
- object: {
- order_created: {
- created_at: '2020-04-16T23:14:26.129Z',
- location_id: 'FPYCBCHYMXFK1',
- order_id: 'eA3vssLHKJrv9H0IdJCM3gNqfdcZY',
- state: 'OPEN',
- version: 1,
- },
- },
- },
- },
+ objectKey: 'order_created',
+ sampleData: squareSamples.new_order,
+ orderSummary: true,
},
{
name: 'order_updated',
@@ -37,29 +34,12 @@ const triggerData = [
description: 'Triggered when an order is updated',
aiMetadata: {
description:
- 'Fires when an existing order is modified in the Square seller account (order.updated event). Represents a change to an order such as its state, line items, or version bump, including the order id, location, and new version.',
+ 'Fires when an existing order is modified in the Square seller account (order.updated event), for example a state change or a version bump. The payload is a summary; turn on Include Full Order to also get line items and totals.',
},
event: 'order.updated',
- sampleData: {
- merchant_id: 'MLTZ79VE64YTN',
- type: 'order.updated',
- event_id: '7e1d596e-ebf1-443d-87aa-a5f397bce1e5',
- created_at: '2023-03-14T01:56:10.454184371Z',
- data: {
- type: 'order',
- id: 'eA3vssLHKJrv9H0IdJCM3gNqfdcZY',
- object: {
- order_updated: {
- created_at: '2020-04-16T23:14:26.129Z',
- location_id: 'FPYCBCHYMXFK1',
- order_id: 'eA3vssLHKJrv9H0IdJCM3gNqfdcZY',
- state: 'OPEN',
- updated_at: '2020-04-16T23:14:26.359Z',
- version: 2,
- },
- },
- },
- },
+ objectKey: 'order_updated',
+ sampleData: squareSamples.order_updated,
+ orderSummary: true,
},
{
name: 'new_customer',
@@ -70,40 +50,9 @@ const triggerData = [
'Fires when a new customer profile is added to the Square Customer Directory (customer.created event). Represents a newly created customer record including contact details, address, creation source, and identifiers.',
},
event: 'customer.created',
- sampleData: {
- merchant_id: 'MLTZ79VE64YTN',
- type: 'customer.created',
- event_id: '2985c7c7-2ccc-409e-8aba-998684732cab',
- created_at: '2023-03-14T01:57:28.679389163Z',
- data: {
- type: 'customer',
- id: 'QPTXM8PQNX3Q726ZYHPMNP46XC',
- object: {
- customer: {
- address: {
- address_line_1: '1018 40th Street',
- administrative_district_level_1: 'CA',
- locality: 'Oakland',
- postal_code: '94608',
- },
- birthday: '1962-03-04',
- created_at: '2022-11-09T21:23:25.519Z',
- creation_source: 'DIRECTORY',
- email_address: '[email protected]',
- family_name: 'Smorly',
- given_name: 'Jenkins',
- group_ids: ['JGJCW9S0G68NE.APPOINTMENTS'],
- id: 'QPTXM8PQNX3Q726ZYHPMNP46XC',
- phone_number: '+12126668929',
- preferences: {
- email_unsubscribed: false,
- },
- updated_at: '2022-11-09T21:23:25Z',
- version: 0,
- },
- },
- },
- },
+ objectKey: 'customer',
+ sampleData: squareSamples.new_customer,
+ orderSummary: false,
},
{
name: 'customer_updated',
@@ -114,123 +63,11 @@ const triggerData = [
'Fires when an existing customer profile is changed in the Square Customer Directory (customer.updated event). Represents an update to a customer record such as contact details or preferences, including the customer id and incremented version.',
},
event: 'customer.updated',
- sampleData: {
- merchant_id: 'MLTZ79VE64YTN',
- type: 'customer.updated',
- event_id: 'f6e89469-de2f-4ae4-84c7-83a95681759a',
- created_at: '2023-03-14T01:58:22.076902762Z',
- data: {
- type: 'customer',
- id: 'A0AP25A6SCVTH8JES9BX01GXM4',
- object: {
- customer: {
- created_at: '2022-07-09T18:23:01.795Z',
- creation_source: 'THIRD_PARTY',
- email_address: '[email protected]',
- family_name: 'Smorly',
- given_name: 'Jenkins',
- id: 'A0AP25A6SCVTH8JES9BX01GXM4',
- phone_number: '+13477947111',
- preferences: {
- email_unsubscribed: false,
- },
- updated_at: '2022-11-09T21:38:30Z',
- version: 1,
- },
- },
- },
- },
- },
- {
- name: 'new_appointment',
- displayName: 'New Appointment',
- description: 'Triggered when a new appointment is created',
- aiMetadata: {
- description:
- 'Fires when a new appointment booking is created in Square Appointments (booking.created event). Represents a newly scheduled appointment for a service at a location.',
- },
- event: 'booking.created',
- sampleData: {
- merchant_id: 'MLTZ79VE64YTN',
- location_id: 'ES0RJRZYEC39A',
- type: 'invoice.created',
- event_id: 'ee17dc22-5e38-4aba-ad15-af8e25adcc93',
- created_at: '2023-03-14T02:01:46.497709569Z',
- data: {
- type: 'invoice',
- id: 'inv:0-ChCHu2mZEabLeeHahQnXDjZQECY',
- object: {
- invoice: {
- accepted_payment_methods: {
- bank_account: false,
- buy_now_pay_later: false,
- card: true,
- square_gift_card: false,
- },
- created_at: '2020-06-18T17:45:13Z',
- custom_fields: [
- {
- label: 'Event Reference Number',
- placement: 'ABOVE_LINE_ITEMS',
- value: 'Ref. #1234',
- },
- {
- label: 'Terms of Service',
- placement: 'BELOW_LINE_ITEMS',
- value: 'The terms of service are...',
- },
- ],
- delivery_method: 'EMAIL',
- description: 'We appreciate your business!',
- id: 'inv:0-ChCHu2mZEabLeeHahQnXDjZQECY',
- invoice_number: 'inv-100',
- location_id: 'ES0RJRZYEC39A',
- order_id: 'CAISENgvlJ6jLWAzERDzjyHVybY',
- payment_requests: [
- {
- automatic_payment_source: 'NONE',
- computed_amount_money: {
- amount: 10000,
- currency: 'USD',
- },
- due_date: '2030-01-24',
- reminders: [
- {
- message: 'Your invoice is due tomorrow',
- relative_scheduled_days: -1,
- status: 'PENDING',
- uid: 'beebd363-e47f-4075-8785-c235aaa7df11',
- },
- ],
- request_type: 'BALANCE',
- tipping_enabled: true,
- total_completed_amount_money: {
- amount: 0,
- currency: 'USD',
- },
- uid: '2da7964f-f3d2-4f43-81e8-5aa220bf3355',
- },
- ],
- primary_recipient: {
- customer_id: 'JDKYHBWT1D4F8MFH63DBMEN8Y4',
- email_address: '[email protected]',
- family_name: 'Earhart',
- given_name: 'Amelia',
- phone_number: '1-212-555-4240',
- },
- sale_or_service_date: '2030-01-24',
- scheduled_at: '2030-01-13T10:00:00Z',
- status: 'DRAFT',
- store_payment_method_enabled: false,
- timezone: 'America/Los_Angeles',
- title: 'Event Planning Services',
- updated_at: '2020-06-18T17:45:13Z',
- version: 0,
- },
- },
- },
- },
+ objectKey: 'customer',
+ sampleData: squareSamples.customer_updated,
+ orderSummary: false,
},
+
{
name: 'new_payment',
displayName: 'New Payment',
@@ -240,165 +77,11 @@ const triggerData = [
'Fires when a new payment is created in the Square seller account (payment.created event). Represents a payment taken against an order, including amounts, currency, card details, status, and the associated order and location.',
},
event: 'payment.created',
- sampleData: {
- merchant_id: 'MLTZ79VE64YTN',
- type: 'payment.created',
- event_id: '11fb274d-6882-417a-879c-faec367e0665',
- created_at: '2023-03-14T02:00:56.000119371Z',
- data: {
- type: 'payment',
- id: 'KkAkhdMsgzn59SM8A89WgKwekxLZY',
- object: {
- payment: {
- amount_money: {
- amount: 100,
- currency: 'USD',
- },
- approved_money: {
- amount: 100,
- currency: 'USD',
- },
- capabilities: [
- 'EDIT_TIP_AMOUNT',
- 'EDIT_TIP_AMOUNT_UP',
- 'EDIT_TIP_AMOUNT_DOWN',
- ],
- card_details: {
- avs_status: 'AVS_ACCEPTED',
- card: {
- bin: '540988',
- card_brand: 'MASTERCARD',
- card_type: 'CREDIT',
- exp_month: 11,
- exp_year: 2022,
- fingerprint:
- 'sq-1-Tvruf3vPQxlvI6n0IcKYfBukrcv6IqWr8UyBdViWXU2yzGn5VMJvrsHMKpINMhPmVg',
- last_4: '9029',
- prepaid_type: 'NOT_PREPAID',
- },
- card_payment_timeline: {
- authorized_at: '2020-11-22T21:16:51.198Z',
- },
- cvv_status: 'CVV_ACCEPTED',
- entry_method: 'KEYED',
- statement_description: 'SQ *DEFAULT TEST ACCOUNT',
- status: 'AUTHORIZED',
- },
- created_at: '2020-11-22T21:16:51.086Z',
- delay_action: 'CANCEL',
- delay_duration: 'PT168H',
- delayed_until: '2020-11-29T21:16:51.086Z',
- id: 'hYy9pRFVxpDsO1FB05SunFWUe9JZY',
- location_id: 'S8GWD5R9QB376',
- order_id: '03O3USaPaAaFnI6kkwB1JxGgBsUZY',
- receipt_number: 'hYy9',
- risk_evaluation: {
- created_at: '2020-11-22T21:16:51.198Z',
- risk_level: 'NORMAL',
- },
- source_type: 'CARD',
- status: 'APPROVED',
- total_money: {
- amount: 100,
- currency: 'USD',
- },
- updated_at: '2020-11-22T21:16:51.198Z',
- version_token: 'FfQhQJf9r3VSQIgyWBk1oqhIwiznLwVwJbVVA0bdyEv6o',
- },
- },
- },
- },
- },
- {
- name: 'new_invoice',
- displayName: 'New Invoice',
- description: 'Triggered when a new invoice is created',
- aiMetadata: {
- description:
- 'Fires when a new invoice is created in Square Invoices (invoice.created event). Represents a newly created invoice including its number, status, recipient, payment requests, amounts, and the associated order and location.',
- },
- event: 'invoice.created',
- sampleData: {
- merchant_id: 'MLTZ79VE64YTN',
- location_id: 'ES0RJRZYEC39A',
- type: 'invoice.created',
- event_id: 'ee17dc22-5e38-4aba-ad15-af8e25adcc93',
- created_at: '2023-03-14T02:01:46.497709569Z',
- data: {
- type: 'invoice',
- id: 'inv:0-ChCHu2mZEabLeeHahQnXDjZQECY',
- object: {
- invoice: {
- accepted_payment_methods: {
- bank_account: false,
- buy_now_pay_later: false,
- card: true,
- square_gift_card: false,
- },
- created_at: '2020-06-18T17:45:13Z',
- custom_fields: [
- {
- label: 'Event Reference Number',
- placement: 'ABOVE_LINE_ITEMS',
- value: 'Ref. #1234',
- },
- {
- label: 'Terms of Service',
- placement: 'BELOW_LINE_ITEMS',
- value: 'The terms of service are...',
- },
- ],
- delivery_method: 'EMAIL',
- description: 'We appreciate your business!',
- id: 'inv:0-ChCHu2mZEabLeeHahQnXDjZQECY',
- invoice_number: 'inv-100',
- location_id: 'ES0RJRZYEC39A',
- order_id: 'CAISENgvlJ6jLWAzERDzjyHVybY',
- payment_requests: [
- {
- automatic_payment_source: 'NONE',
- computed_amount_money: {
- amount: 10000,
- currency: 'USD',
- },
- due_date: '2030-01-24',
- reminders: [
- {
- message: 'Your invoice is due tomorrow',
- relative_scheduled_days: -1,
- status: 'PENDING',
- uid: 'beebd363-e47f-4075-8785-c235aaa7df11',
- },
- ],
- request_type: 'BALANCE',
- tipping_enabled: true,
- total_completed_amount_money: {
- amount: 0,
- currency: 'USD',
- },
- uid: '2da7964f-f3d2-4f43-81e8-5aa220bf3355',
- },
- ],
- primary_recipient: {
- customer_id: 'JDKYHBWT1D4F8MFH63DBMEN8Y4',
- email_address: '[email protected]',
- family_name: 'Earhart',
- given_name: 'Amelia',
- phone_number: '1-212-555-4240',
- },
- sale_or_service_date: '2030-01-24',
- scheduled_at: '2030-01-13T10:00:00Z',
- status: 'DRAFT',
- store_payment_method_enabled: false,
- timezone: 'America/Los_Angeles',
- title: 'Event Planning Services',
- updated_at: '2020-06-18T17:45:13Z',
- version: 0,
- },
- },
- },
- },
+ objectKey: 'payment',
+ sampleData: squareSamples.new_payment,
+ orderSummary: false,
},
+
];
export const triggers = triggerData.map((trigger) =>
@@ -409,23 +92,201 @@ export const triggers = triggerData.map((trigger) =>
displayName: trigger.displayName,
description: trigger.description,
aiMetadata: trigger.aiMetadata,
- props: {},
+ props: trigger.orderSummary
+ ? {
+ location_id: squareProps.location({ required: false, description: 'Only fire for this location. Leave empty for all locations.' }),
+ include_full_order: Property.Checkbox({
+ displayName: 'Include Full Order',
+ description: 'Also fetch the whole order (line items, totals, customer) and add it as "order" to the output.',
+ required: false,
+ defaultValue: false,
+ }),
+ }
+ : trigger.objectKey === 'customer'
+ ? {}
+ : { location_id: squareProps.location({ required: false, description: 'Only fire for this location. Leave empty for all locations.' }) },
type: TriggerStrategy.APP_WEBHOOK,
sampleData: trigger.sampleData,
+ outputSchema: squareOutputSchemas.triggers[trigger.name],
onEnable: async (context) => {
context.app.createListeners({
events: [trigger.event],
- identifierValue: context.auth.data['merchant_id'],
+ identifierValue: String(context.auth.data['merchant_id']),
});
},
onDisable: async () => {
- // Ignored
+ return;
},
- test: async () => {
+ test: async (context) => {
+ if (trigger.orderSummary && context.propsValue['include_full_order'] === true) {
+ return [{ ...trigger.sampleData, order: squareShape.order(SAMPLE_ORDER) }];
+ }
return [trigger.sampleData];
},
run: async (context) => {
- return [context.payload.body];
+ const body = context.payload.body;
+ if (!squareShape.isRecord(body)) {
+ return [];
+ }
+ const locationFilter = context.propsValue['location_id'];
+ if (typeof locationFilter === 'string' && locationFilter.length > 0) {
+ const eventLocation = squareShape.str({ value: squareShape.rec({ value: squareShape.rec({ value: body, key: 'data' }), key: 'object' })[trigger.objectKey], key: 'location_id' }) ?? squareShape.str({ value: body, key: 'location_id' });
+ if (eventLocation !== null && eventLocation !== locationFilter) {
+ return [];
+ }
+ }
+ const eventId = squareShape.str({ value: body, key: 'event_id' });
+ const claim = await claimEvent({ store: context.store, eventId });
+ if (claim === 'duplicate') {
+ return [];
+ }
+ try {
+ const events = await buildEvents({ trigger, body, auth: context.auth, includeFullOrder: context.propsValue['include_full_order'] === true });
+ await finishClaim({ store: context.store, claim, succeeded: true });
+ return withDedupeKey({ events, eventId });
+ } catch (error) {
+ await finishClaim({ store: context.store, claim, succeeded: false }).catch(() => undefined);
+ throw error;
+ }
},
- })
+ }),
);
+
+function withDedupeKey({ events, eventId }: { events: Record<string, unknown>[]; eventId: string | null }): Record<string, unknown>[] {
+ if (!eventId) {
+ return events;
+ }
+ return events.map((event) => ({ ...event, [DEDUPE_KEY_PROPERTY]: `square:${eventId}` }));
+}
+
+async function buildEvents({ trigger, body, auth, includeFullOrder }: { trigger: TriggerDefinition; body: Record<string, unknown>; auth: SquareAuth; includeFullOrder: boolean }): Promise<Record<string, unknown>[]> {
+ if (!trigger.orderSummary || !includeFullOrder) {
+ return [body];
+ }
+ const orderId = squareShape.str({ value: squareShape.rec({ value: body, key: 'data' }), key: 'id' });
+ if (!orderId) {
+ return [body];
+ }
+ const order = await fetchOrder({ auth, orderId });
+ return order === null ? [] : [{ ...body, order }];
+}
+
+async function claimEvent({ store, eventId }: { store: DedupeStore; eventId: string | null }): Promise<Claim | 'duplicate'> {
+ if (!eventId) {
+ return null;
+ }
+ const key = slotKey({ eventId });
+ const now = Date.now();
+ const before = await readSlot({ store, key, now });
+ if (before.some((entry) => entry.id === eventId && blocks({ entry, now }))) {
+ return 'duplicate';
+ }
+ const token = crypto.randomUUID();
+ const mine: SeenEvent = { id: eventId, at: now, token, done: false };
+ await store.put(key, [...before.filter((entry) => entry.id !== eventId).slice(-(DEDUPE_MAX_PER_SLOT - 1)), mine]);
+ const after = await readSlot({ store, key, now });
+ const winner = after.find((entry) => entry.id === eventId);
+ if (winner !== undefined && winner.token !== token) {
+ return 'duplicate';
+ }
+ if (winner === undefined) {
+ await store.put(key, [...after.slice(-(DEDUPE_MAX_PER_SLOT - 1)), mine]);
+ }
+ return { key, eventId, token };
+}
+
+// A delivery is marked done for DEDUPE_WINDOW_MS before run() returns its events.
+// The piece cannot see whether the server then starts a run, so a retried job and a
+// late duplicate look the same. Square flows often move money, so this trigger
+// chooses at-most-once: a retry inside the window is dropped rather than risk a
+// second run. The platform _dedupe_key only covers 30 seconds.
+async function finishClaim({ store, claim, succeeded }: { store: DedupeStore; claim: Claim; succeeded: boolean }): Promise<void> {
+ if (claim === null) {
+ return;
+ }
+ const now = Date.now();
+ const entries = (await readSlot({ store, key: claim.key, now })).filter((entry) => entry.token !== claim.token);
+ const updated = succeeded ? [...entries.filter((entry) => entry.id !== claim.eventId).slice(-(DEDUPE_MAX_PER_SLOT - 1)), { id: claim.eventId, at: now, token: claim.token, done: true }] : entries;
+ await store.put(claim.key, updated);
+}
+
+async function readSlot({ store, key, now }: { store: DedupeStore; key: string; now: number }): Promise<SeenEvent[]> {
+ const stored = await store.get<unknown>(key);
+ return (Array.isArray(stored) ? stored : []).filter(
+ (entry): entry is SeenEvent =>
+ squareShape.isRecord(entry) &&
+ typeof entry['id'] === 'string' &&
+ typeof entry['at'] === 'number' &&
+ typeof entry['token'] === 'string' &&
+ typeof entry['done'] === 'boolean' &&
+ now - entry['at'] < DEDUPE_WINDOW_MS,
+ );
+}
+
+function blocks({ entry, now }: { entry: SeenEvent; now: number }): boolean {
+ return entry.done || now - entry.at < DEDUPE_CLAIM_TIMEOUT_MS;
+}
+
+function slotKey({ eventId }: { eventId: string }): string {
+ const slot = crypto.createHash('sha256').update(eventId).digest().readUInt32BE(0) % DEDUPE_SLOT_COUNT;
+ return `${DEDUPE_KEY_PREFIX}${slot}`;
+}
+
+async function fetchOrder({ auth, orderId }: { auth: SquareAuth; orderId: string }) {
+ try {
+ const body = await squareClient.request<unknown>({ auth, method: HttpMethod.GET, path: ['v2', 'orders', orderId], operation: `read order "${orderId}"` });
+ return squareShape.order(squareShape.requireObject({ body, key: 'order', what: 'order' }));
+ } catch (error) {
+ if (error instanceof SquareApiError && error.status === 404) {
+ return null;
+ }
+ throw error;
+ }
+}
+
+const SAMPLE_ORDER = {
+ id: 'eA3vssLHKJrv9H0IdJCM3gNqfdcZY',
+ location_id: 'FPYCBCHYMXFK1',
+ state: 'OPEN',
+ version: 1,
+ customer_id: 'QPTXM8PQNX3Q726ZYHPMNP46XC',
+ line_items: [
+ {
+ uid: 'k8ziVbfuGnF3vK9g0Tq9qC',
+ name: 'Coffee',
+ variation_name: 'Large',
+ catalog_object_id: 'W62UWFY35CWMYGVWK6TWJDNI',
+ quantity: '2',
+ base_price_money: { amount: 450, currency: 'USD' },
+ total_money: { amount: 900, currency: 'USD' },
+ },
+ ],
+ total_money: { amount: 900, currency: 'USD' },
+ total_tax_money: { amount: 0, currency: 'USD' },
+ total_discount_money: { amount: 0, currency: 'USD' },
+ total_tip_money: { amount: 0, currency: 'USD' },
+ total_service_charge_money: { amount: 0, currency: 'USD' },
+ net_amount_due_money: { amount: 900, currency: 'USD' },
+ created_at: '2020-04-16T23:14:26.129Z',
+ updated_at: '2020-04-16T23:14:26.129Z',
+};
+
+type TriggerDefinition = {
+ name: string;
+ displayName: string;
+ description: string;
+ aiMetadata: { description: string };
+ event: string;
+ objectKey: string;
+ sampleData: Record<string, unknown>;
+ orderSummary: boolean;
+};
+
+type SeenEvent = { id: string; at: number; token: string; done: boolean };
+
+type Claim = { key: string; eventId: string; token: string } | null;
+
+type DedupeStore = {
+ get: <T>(key: string) => Promise<T | null>;
+ put: <T>(key: string, value: T) => Promise<T>;
+};
diff --git a/packages/pieces/community/square/src/lib/triggers/samples.ts b/packages/pieces/community/square/src/lib/triggers/samples.ts
new file mode 100644
index 00000000000..08c5a6f0bc4
--- /dev/null
+++ b/packages/pieces/community/square/src/lib/triggers/samples.ts
@@ -0,0 +1,171 @@
+export const squareSamples = {
+ new_order: {
+ merchant_id: 'MLTZ79VE64YTN',
+ type: 'order.created',
+ event_id: '03441e3a-47f1-49a7-a64c-55ab26703f8d',
+ created_at: '2023-03-14T01:42:54.984089903Z',
+ data: {
+ type: 'order_created',
+ id: 'eA3vssLHKJrv9H0IdJCM3gNqfdcZY',
+ object: {
+ order_created: {
+ created_at: '2020-04-16T23:14:26.129Z',
+ location_id: 'FPYCBCHYMXFK1',
+ order_id: 'eA3vssLHKJrv9H0IdJCM3gNqfdcZY',
+ state: 'OPEN',
+ version: 1,
+ },
+ },
+ },
+ },
+ order_updated: {
+ merchant_id: 'MLTZ79VE64YTN',
+ type: 'order.updated',
+ event_id: '7e1d596e-ebf1-443d-87aa-a5f397bce1e5',
+ created_at: '2023-03-14T01:56:10.454184371Z',
+ data: {
+ type: 'order_updated',
+ id: 'eA3vssLHKJrv9H0IdJCM3gNqfdcZY',
+ object: {
+ order_updated: {
+ created_at: '2020-04-16T23:14:26.129Z',
+ location_id: 'FPYCBCHYMXFK1',
+ order_id: 'eA3vssLHKJrv9H0IdJCM3gNqfdcZY',
+ state: 'OPEN',
+ updated_at: '2020-04-16T23:14:26.359Z',
+ version: 2,
+ },
+ },
+ },
+ },
+ new_customer: {
+ merchant_id: 'MLTZ79VE64YTN',
+ type: 'customer.created',
+ event_id: '2985c7c7-2ccc-409e-8aba-998684732cab',
+ created_at: '2023-03-14T01:57:28.679389163Z',
+ data: {
+ type: 'customer',
+ id: 'QPTXM8PQNX3Q726ZYHPMNP46XC',
+ object: {
+ customer: {
+ address: {
+ address_line_1: '1018 40th Street',
+ administrative_district_level_1: 'CA',
+ locality: 'Oakland',
+ postal_code: '94608',
+ },
+ birthday: '1962-03-04',
+ created_at: '2022-11-09T21:23:25.519Z',
+ creation_source: 'DIRECTORY',
+ email_address: '[email protected]',
+ family_name: 'Smorly',
+ given_name: 'Jenkins',
+ group_ids: ['JGJCW9S0G68NE.REGULARS'],
+ id: 'QPTXM8PQNX3Q726ZYHPMNP46XC',
+ phone_number: '+12126668929',
+ preferences: {
+ email_unsubscribed: false,
+ },
+ updated_at: '2022-11-09T21:23:25Z',
+ version: 0,
+ },
+ },
+ },
+ },
+ customer_updated: {
+ merchant_id: 'MLTZ79VE64YTN',
+ type: 'customer.updated',
+ event_id: 'f6e89469-de2f-4ae4-84c7-83a95681759a',
+ created_at: '2023-03-14T01:58:22.076902762Z',
+ data: {
+ type: 'customer',
+ id: 'A0AP25A6SCVTH8JES9BX01GXM4',
+ object: {
+ customer: {
+ created_at: '2022-07-09T18:23:01.795Z',
+ creation_source: 'THIRD_PARTY',
+ email_address: '[email protected]',
+ family_name: 'Smorly',
+ given_name: 'Jenkins',
+ id: 'A0AP25A6SCVTH8JES9BX01GXM4',
+ phone_number: '+13477947111',
+ preferences: {
+ email_unsubscribed: false,
+ },
+ updated_at: '2022-11-09T21:38:30Z',
+ version: 1,
+ },
+ },
+ },
+ },
+
+ new_payment: {
+ merchant_id: 'MLTZ79VE64YTN',
+ type: 'payment.created',
+ event_id: '11fb274d-6882-417a-879c-faec367e0665',
+ created_at: '2023-03-14T02:00:56.000119371Z',
+ data: {
+ type: 'payment',
+ id: 'KkAkhdMsgzn59SM8A89WgKwekxLZY',
+ object: {
+ payment: {
+ amount_money: {
+ amount: 100,
+ currency: 'USD',
+ },
+ approved_money: {
+ amount: 100,
+ currency: 'USD',
+ },
+ capabilities: [
+ 'EDIT_TIP_AMOUNT',
+ 'EDIT_TIP_AMOUNT_UP',
+ 'EDIT_TIP_AMOUNT_DOWN',
+ ],
+ card_details: {
+ avs_status: 'AVS_ACCEPTED',
+ card: {
+ bin: '540988',
+ card_brand: 'MASTERCARD',
+ card_type: 'CREDIT',
+ exp_month: 11,
+ exp_year: 2022,
+ fingerprint:
+ 'sq-1-Tvruf3vPQxlvI6n0IcKYfBukrcv6IqWr8UyBdViWXU2yzGn5VMJvrsHMKpINMhPmVg',
+ last_4: '9029',
+ prepaid_type: 'NOT_PREPAID',
+ },
+ card_payment_timeline: {
+ authorized_at: '2020-11-22T21:16:51.198Z',
+ },
+ cvv_status: 'CVV_ACCEPTED',
+ entry_method: 'KEYED',
+ statement_description: 'SQ *DEFAULT TEST ACCOUNT',
+ status: 'AUTHORIZED',
+ },
+ created_at: '2020-11-22T21:16:51.086Z',
+ delay_action: 'CANCEL',
+ delay_duration: 'PT168H',
+ delayed_until: '2020-11-29T21:16:51.086Z',
+ id: 'hYy9pRFVxpDsO1FB05SunFWUe9JZY',
+ location_id: 'S8GWD5R9QB376',
+ order_id: '03O3USaPaAaFnI6kkwB1JxGgBsUZY',
+ receipt_number: 'hYy9',
+ risk_evaluation: {
+ created_at: '2020-11-22T21:16:51.198Z',
+ risk_level: 'NORMAL',
+ },
+ source_type: 'CARD',
+ status: 'APPROVED',
+ total_money: {
+ amount: 100,
+ currency: 'USD',
+ },
+ updated_at: '2020-11-22T21:16:51.198Z',
+ version_token: 'FfQhQJf9r3VSQIgyWBk1oqhIwiznLwVwJbVVA0bdyEv6o',
+ },
+ },
+ },
+ },
+
+};
diff --git a/packages/pieces/community/square/test/actions.test.ts b/packages/pieces/community/square/test/actions.test.ts
new file mode 100644
index 00000000000..38207d98b81
--- /dev/null
+++ b/packages/pieces/community/square/test/actions.test.ts
@@ -0,0 +1,248 @@
+import { afterEach, describe, expect, test, vi } from 'vitest';
+import { adjustInventoryByIdAction } from '../src/lib/actions/ai/adjust-inventory-by-id';
+import { createOrderByIdAction } from '../src/lib/actions/ai/create-order-by-id';
+import { updateCustomerByIdAction } from '../src/lib/actions/ai/update-customer-by-id';
+import { updateItemVariationPriceByIdAction } from '../src/lib/actions/ai/update-item-variation-price-by-id';
+import { createCatalogItemAction } from '../src/lib/actions/create-catalog-item';
+import { createCustomerAction } from '../src/lib/actions/create-customer';
+import { createOrderAction } from '../src/lib/actions/create-order';
+import { findCustomersAction } from '../src/lib/actions/find-customers';
+import { recordExternalPaymentAction } from '../src/lib/actions/record-external-payment';
+import { refundPaymentAction } from '../src/lib/actions/refund-payment';
+import { searchOrdersByIdAction } from '../src/lib/actions/ai/search-orders-by-id';
+import { squareProps } from '../src/lib/common/props';
+import { connection, context, LOCATION, stubFetch } from './helpers';
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+const customer = { customer: { id: 'C1', given_name: 'Ada', version: 3, email_address: '[email protected]' } };
+
+describe('customers', () => {
+ test('create sends fields plus an idempotency key', async () => {
+ const seen = stubFetch(() => ({ body: customer }));
+ const props = { given_name: ' Ada ', email_address: '[email protected]', city: 'Oakland' };
+ const first = await createCustomerAction.run(context(props));
+ expect(seen[0].method).toBe('POST');
+ expect(seen[0].path).toBe('/v2/customers');
+ expect(seen[0].json).toMatchObject({ given_name: 'Ada', email_address: '[email protected]', address: { locality: 'Oakland' } });
+ expect(Reflect.get(Object(seen[0].json), 'idempotency_key')).toEqual(expect.any(String));
+ expect(first).toMatchObject({ id: 'C1', given_name: 'Ada' });
+ });
+
+ test('create refuses an empty profile before any request', async () => {
+ const seen = stubFetch(() => ({ body: customer }));
+ await expect(createCustomerAction.run(context({ note: 'only a note' }))).rejects.toThrow('Fill at least one');
+ await expect(createCustomerAction.run(context({ email_address: 'not-an-email' }))).rejects.toThrow('not a valid email');
+ expect(seen).toHaveLength(0);
+ });
+
+ test('update sends only filled fields, nulls for cleared fields, and the current version', async () => {
+ const seen = stubFetch(() => ({ body: customer }));
+ await updateCustomerByIdAction.run(context({ customer_id: 'C1', company_name: 'Acme', clear_fields: ['note', 'company_name', 'bogus'] }));
+ expect(seen.map((request) => request.method)).toEqual(['GET', 'PUT']);
+ expect(seen[1].json).toEqual({ note: null, company_name: 'Acme', version: 3 });
+ });
+
+ test('update with nothing to change fails without a request', async () => {
+ const seen = stubFetch(() => ({ body: customer }));
+ await expect(updateCustomerByIdAction.run(context({ customer_id: 'C1' }))).rejects.toThrow('Nothing to update');
+ expect(seen).toHaveLength(0);
+ });
+
+ test('find builds an exact or fuzzy filter and returns a page', async () => {
+ const seen = stubFetch(() => ({ body: { customers: [customer.customer], cursor: 'NEXT' } }));
+ const result = await findCustomersAction.run(context({ email_address: 'ada@', match: 'fuzzy', limit: 500 }));
+ expect(seen[0].json).toEqual({ query: { filter: { email_address: { fuzzy: 'ada@' } }, sort: { field: 'CREATED_AT', order: 'DESC' } }, limit: 100 });
+ expect(result).toMatchObject({ count: 1, has_more: true, next_cursor: 'NEXT' });
+ });
+});
+
+describe('catalog', () => {
+ test('create item converts the price with string math and uses temporary ids', async () => {
+ const seen = stubFetch((request) =>
+ request.path === '/v2/locations/main' ? { body: LOCATION } : { body: { catalog_object: { id: 'I1', type: 'ITEM', item_data: { name: 'Tea', variations: [] } } } },
+ );
+ await createCatalogItemAction.run(context({ name: 'Tea', price: '19.99', sku: 'T-1' }));
+ const object = Reflect.get(Object(seen[1].json), 'object');
+ expect(object).toMatchObject({
+ type: 'ITEM',
+ id: '#item',
+ item_data: { name: 'Tea', variations: [{ id: '#variation', item_variation_data: { item_id: '#item', name: 'Regular', sku: 'T-1', pricing_type: 'FIXED_PRICING', price_money: { amount: 1999, currency: 'USD' } } }] },
+ });
+ });
+
+ test('variation price update reads the object and upserts it with its version', async () => {
+ const variation = { id: 'V1', type: 'ITEM_VARIATION', version: 77, item_variation_data: { item_id: 'I1', name: 'Large', price_money: { amount: 450, currency: 'USD' } } };
+ const seen = stubFetch((request) => (request.method === 'GET' ? { body: { object: variation } } : { body: { catalog_object: { ...variation, version: 78 } } }));
+ await updateItemVariationPriceByIdAction.run(context({ variation_id: 'V1', price: '5.25' }));
+ expect(seen[1].json).toMatchObject({ object: { id: 'V1', version: 77, item_variation_data: { name: 'Large', pricing_type: 'FIXED_PRICING', price_money: { amount: 525, currency: 'USD' } } } });
+ });
+});
+
+describe('inventory', () => {
+ test('adjust maps the reason to Square states and keeps the key stable across retries', async () => {
+ const seen = stubFetch((_request, index) => (index === 0 ? { status: 503, body: { errors: [{ code: 'SERVICE_UNAVAILABLE' }] } } : { body: { counts: [{ catalog_object_id: 'V1', location_id: 'L1', state: 'IN_STOCK', quantity: '7' }] } }));
+ const props = { variation_id: 'V1', location_id: 'L1', reason: 'SOLD', quantity: '2' };
+ await expect(adjustInventoryByIdAction.run(context(props))).rejects.toThrow('503');
+ const result = await adjustInventoryByIdAction.run(context(props));
+ const body = Object(seen[0].json);
+ expect(Reflect.get(body, 'changes')[0]).toMatchObject({ type: 'ADJUSTMENT', adjustment: { from_state: 'IN_STOCK', to_state: 'SOLD', quantity: '2', catalog_object_id: 'V1', from_location_id: 'L1', to_location_id: 'L1' } });
+ expect(Reflect.get(body, 'idempotency_key')).toBe(Reflect.get(Object(seen[1].json), 'idempotency_key'));
+ expect(result.items[0]).toMatchObject({ variation_id: 'V1', quantity: '7' });
+ });
+});
+
+describe('orders', () => {
+ test('creates an order from catalog and custom line items in the location currency', async () => {
+ const seen = stubFetch((request) => (request.method === 'GET' ? { body: LOCATION } : { body: { order: { id: 'O1', total_money: { amount: 1380, currency: 'USD' } } } }));
+ const result = await createOrderByIdAction.run(
+ context({ line_items: [{ variation_id: 'V1', quantity: '2' }, { name: 'Custom', price: '1.10', quantity: '3' }], customer_id: 'C1' }),
+ );
+ expect(seen[0].path).toBe('/v2/locations/main');
+ expect(seen[1].json).toMatchObject({
+ order: {
+ location_id: 'LOC1',
+ customer_id: 'C1',
+ line_items: [
+ { catalog_object_id: 'V1', quantity: '2' },
+ { name: 'Custom', quantity: '3', base_price_money: { amount: 110, currency: 'USD' } },
+ ],
+ },
+ });
+ expect(result).toMatchObject({ id: 'O1', total: '13.80', total_minor: 1380 });
+ });
+
+ test('human create order reads the dynamic line items', async () => {
+ const seen = stubFetch((request) => (request.method === 'GET' ? { body: LOCATION } : { body: { order: { id: 'O2' } } }));
+ await createOrderAction.run(context({ line_items: { items: [{ name: 'Cake', price: '0.99' }] } }));
+ expect(Reflect.get(Object(seen[1].json), 'order')).toMatchObject({ line_items: [{ name: 'Cake', quantity: '1', base_price_money: { amount: 99 } }] });
+ });
+
+ test('rejects fractional quantities and incomplete custom items', async () => {
+ stubFetch(() => ({ body: LOCATION }));
+ await expect(createOrderByIdAction.run(context({ line_items: [{ name: 'x', price: '1', quantity: '1.5' }] }))).rejects.toThrow('whole number');
+ await expect(createOrderByIdAction.run(context({ line_items: [{ name: 'x' }] }))).rejects.toThrow('give both a name and a price');
+ });
+
+ test('search defaults to all active locations and sorts newest first', async () => {
+ const seen = stubFetch((request) =>
+ request.method === 'GET'
+ ? { body: { locations: [{ id: 'A', status: 'ACTIVE' }, { id: 'B', status: 'INACTIVE' }] } }
+ : { body: { orders: [], cursor: undefined } },
+ );
+ await searchOrdersByIdAction.run(context({ states: ['OPEN'], created_after: '2026-10-01T00:00:00Z' }));
+ expect(seen[1].json).toEqual({
+ location_ids: ['A'],
+ limit: 50,
+ return_entries: false,
+ query: { filter: { state_filter: { states: ['OPEN'] }, date_time_filter: { created_at: { start_at: '2026-10-01T00:00:00.000Z' } } }, sort: { sort_field: 'CREATED_AT', sort_order: 'DESC' } },
+ });
+ });
+});
+
+describe('money actions', () => {
+ test('record cash payment sends CASH details and never a card source', async () => {
+ const seen = stubFetch((request) => (request.method === 'GET' ? { body: LOCATION } : { body: { payment: { id: 'P1', amount_money: { amount: 100, currency: 'USD' } } } }));
+ await recordExternalPaymentAction.run(context({ source: 'CASH', amount: '1.00', note: 'cash' }));
+ expect(seen[1].json).toMatchObject({ source_id: 'CASH', amount_money: { amount: 100, currency: 'USD' }, cash_details: { buyer_supplied_money: { amount: 100, currency: 'USD' } }, location_id: 'LOC1', autocomplete: true });
+ });
+
+ test('identical cash payments in one run share a key unless Idempotency Key separates them', async () => {
+ const seen = stubFetch((request) => (request.method === 'GET' ? { body: LOCATION } : { body: { payment: { id: 'P1', amount_money: { amount: 1000, currency: 'USD' } } } }));
+ await recordExternalPaymentAction.run(context({ source: 'CASH', amount: '10.00' }));
+ await recordExternalPaymentAction.run(context({ source: 'CASH', amount: '10.00' }));
+ await recordExternalPaymentAction.run(context({ source: 'CASH', amount: '10.00', idempotency_key: 'loop-item-1' }));
+ await recordExternalPaymentAction.run(context({ source: 'CASH', amount: '10.00', idempotency_key: 'loop-item-2' }));
+ const keys = seen.filter((request) => request.method === 'POST').map((request) => Reflect.get(Object(request.json), 'idempotency_key'));
+ expect(keys[0]).toBe(keys[1]);
+ expect(keys.slice(2)).toEqual(['loop-item-1', 'loop-item-2']);
+ });
+
+ test('external payment needs a type and source', async () => {
+ stubFetch(() => ({ body: LOCATION }));
+ await expect(recordExternalPaymentAction.run(context({ source: 'EXTERNAL', amount: '1.00' }))).rejects.toThrow('External Type is required');
+ });
+
+ test('refund maps Square over-refund errors to what is left to refund', async () => {
+ stubFetch((request) =>
+ request.method === 'GET'
+ ? { body: { payment: { id: 'P1', total_money: { amount: 1000, currency: 'USD' }, refunded_money: { amount: 600, currency: 'USD' } } } }
+ : { status: 400, body: { errors: [{ code: 'REFUND_AMOUNT_INVALID', detail: 'The requested refund amount exceeds the amount available to refund.' }] } },
+ );
+ await expect(refundPaymentAction.run(context({ payment_id: 'P1', amount: '4.01' }))).rejects.toThrow('4.00 USD left to refund');
+ });
+
+ test('refund retried after a lost response resends the same key even when nothing is left to refund', async () => {
+ const full = { payment: { id: 'P1', total_money: { amount: 1000, currency: 'USD' } } };
+ const refunded = { payment: { id: 'P1', total_money: { amount: 1000, currency: 'USD' }, refunded_money: { amount: 1000, currency: 'USD' } } };
+ const seen = stubFetch((request, index) => {
+ if (request.method === 'GET') {
+ return { body: index === 0 ? full : refunded };
+ }
+ return index === 1 ? { status: 500, body: { errors: [{ code: 'INTERNAL_SERVER_ERROR' }] } } : { body: { refund: { id: 'R1', status: 'PENDING', amount_money: { amount: 1000, currency: 'USD' } } } };
+ });
+ await expect(refundPaymentAction.run(context({ payment_id: 'P1', amount: '10' }))).rejects.toThrow('500');
+ const result = await refundPaymentAction.run(context({ payment_id: 'P1', amount: '10' }));
+ const posts = seen.filter((request) => request.method === 'POST').map((request) => Reflect.get(Object(request.json), 'idempotency_key'));
+ expect(posts).toHaveLength(2);
+ expect(posts[0]).toBe(posts[1]);
+ expect(result).toMatchObject({ id: 'R1' });
+ });
+
+ test('refund sends the exact amount in the payment currency', async () => {
+ const seen = stubFetch((request) =>
+ request.method === 'GET' ? { body: { payment: { id: 'P1', total_money: { amount: 1000, currency: 'USD' } } } } : { body: { refund: { id: 'R1', status: 'PENDING', amount_money: { amount: 400, currency: 'USD' } } } },
+ );
+ const result = await refundPaymentAction.run(context({ payment_id: 'P1', amount: '4', reason: 'test' }));
+ expect(seen[1].path).toBe('/v2/refunds');
+ expect(seen[1].json).toMatchObject({ payment_id: 'P1', amount_money: { amount: 400, currency: 'USD' }, reason: 'test' });
+ expect(result).toMatchObject({ id: 'R1', amount: '4.00' });
+ });
+});
+
+describe('dropdowns', () => {
+ test('the variation dropdown lists every variation of a large item', async () => {
+ const variations = Array.from({ length: 120 }, (_, i) => ({ id: `V${i}`, type: 'ITEM_VARIATION', item_variation_data: { item_id: 'I1', name: `Size ${i}` } }));
+ stubFetch(() => ({ body: { object: { id: 'I1', type: 'ITEM', item_data: { name: 'Shirt', variations } } } }));
+ const result = await squareProps.variation({ required: true }).options({ auth: connection(), item: 'I1' }, {});
+ expect(result.options).toHaveLength(120);
+ expect(result.options[119]).toMatchObject({ value: 'V119' });
+ });
+
+ test('the order line item picker lists every variation of a large item', async () => {
+ const variations = Array.from({ length: 120 }, (_, i) => ({ id: `V${i}`, type: 'ITEM_VARIATION', item_variation_data: { item_id: 'I1', name: `Size ${i}` } }));
+ stubFetch(() => ({ body: { items: [{ id: 'I1', type: 'ITEM', item_data: { name: 'Shirt', variations } }] } }));
+ const props = await squareProps.lineItems().props({ auth: connection() }, {} as never);
+ const options = Reflect.get(Object(Reflect.get(Object(props['items']), 'properties'))['variation_id'], 'options').options;
+ expect(options).toHaveLength(120);
+ expect(options[119]).toMatchObject({ value: 'V119', label: 'Shirt - Size 119' });
+ });
+
+ test('the customer dropdown finds a name beyond the first 1,000 customers', async () => {
+ const page = (start: number) => Array.from({ length: 100 }, (_, i) => ({ id: `C${start + i}`, given_name: `Person ${start + i}` }));
+ const seen = stubFetch((request) => {
+ const index = Number(request.query.get('cursor') ?? '0');
+ const customers = index === 11 ? [...page(1100).slice(0, 99), { id: 'OLD', given_name: 'Grace', family_name: 'Hopper' }] : page(index * 100);
+ return { body: { customers, cursor: index < 11 ? String(index + 1) : undefined } };
+ });
+ const result = await squareProps.customer({ required: true }).options({ auth: connection() }, { searchValue: 'grace hop' });
+ expect(result.options).toEqual([{ label: 'Grace Hopper', value: 'OLD' }]);
+ expect(seen).toHaveLength(12);
+ });
+
+ test('the customer name search stops after its time budget and says how far it got', async () => {
+ let now = 0;
+ vi.spyOn(Date, 'now').mockImplementation(() => now);
+ stubFetch((request) => {
+ now += 5_000;
+ const index = Number(request.query.get('cursor') ?? '0');
+ return { body: { customers: [{ id: `C${index}`, given_name: `Person ${index}` }], cursor: String(index + 1) } };
+ });
+ const result = await squareProps.customer({ required: true }).options({ auth: connection() }, { searchValue: 'grace' });
+ expect(result.options).toEqual([]);
+ expect(result.placeholder).toBe('No match in the 4 newest customers searched. Search by email or map the Customer ID.');
+ vi.restoreAllMocks();
+ });
+});
diff --git a/packages/pieces/community/square/test/client.test.ts b/packages/pieces/community/square/test/client.test.ts
new file mode 100644
index 00000000000..faba86c574b
--- /dev/null
+++ b/packages/pieces/community/square/test/client.test.ts
@@ -0,0 +1,66 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { afterEach, describe, expect, test, vi } from 'vitest';
+import { squareClient, SquareApiError } from '../src/lib/common/client';
+import { connection, stubFetch, TOKEN } from './helpers';
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+describe('squareClient.request', () => {
+ test('sends bearer token, pinned Square-Version and JSON to the production host', async () => {
+ const seen = stubFetch(() => ({ body: { ok: true } }));
+ await squareClient.request({ auth: connection(), method: HttpMethod.POST, path: ['v2', 'customers', 'search'], body: { limit: 1 }, operation: 'x' });
+ expect(seen[0].url).toBe('https://connect.squareup.com/v2/customers/search');
+ expect(seen[0].headers.get('authorization')).toBe(`Bearer ${TOKEN}`);
+ expect(seen[0].headers.get('square-version')).toBe('2026-09-16');
+ expect(seen[0].headers.get('accept')).toBe('application/json');
+ expect(seen[0].json).toEqual({ limit: 1 });
+ });
+
+ test('encodes id segments and refuses path tricks before any request', async () => {
+ const seen = stubFetch(() => ({ body: {} }));
+ await squareClient.request({ auth: connection(), method: HttpMethod.GET, path: ['v2', 'catalog', 'object', 'obj:0-abc'], operation: 'x' });
+ expect(seen[0].path).toBe('/v2/catalog/object/obj%3A0-abc');
+ await expect(squareClient.request({ auth: connection(), method: HttpMethod.GET, path: ['v2', 'orders', '../merchants/me'], operation: 'x' })).rejects.toThrow('not valid');
+ expect(seen).toHaveLength(1);
+ });
+
+ test('maps INSUFFICIENT_SCOPES to a reconnect message naming the scope', async () => {
+ stubFetch(() => ({
+ status: 403,
+ body: {
+ errors: [
+ {
+ category: 'AUTHENTICATION_ERROR',
+ code: 'INSUFFICIENT_SCOPES',
+ detail: 'The merchant has not given your application sufficient permissions to do that. The merchant must authorize your application for the following scopes: INVENTORY_READ',
+ },
+ ],
+ },
+ }));
+ const error = await squareClient.request({ auth: connection(), method: HttpMethod.GET, path: ['v2', 'x'], operation: 'read inventory counts' }).catch((e: unknown) => e);
+ expect(error).toBeInstanceOf(SquareApiError);
+ expect(String(Reflect.get(Object(error), 'message'))).toContain('missing the Square permission INVENTORY_READ. Reconnect your Square connection');
+ expect(Reflect.get(Object(error), 'body')).toBeUndefined();
+ expect(Reflect.get(Object(error), 'responseBody')).toBeDefined();
+ });
+
+ test('explains 401 and 404', async () => {
+ stubFetch((request) => {
+ if (request.path.endsWith('expired')) {
+ return { status: 401, body: { errors: [{ code: 'ACCESS_TOKEN_EXPIRED', detail: 'expired' }] } };
+ }
+ return { status: 404, body: { errors: [{ code: 'NOT_FOUND', detail: 'Could not find payment' }] } };
+ });
+ await expect(squareClient.request({ auth: connection(), method: HttpMethod.GET, path: ['v2', 'expired'], operation: 'x' })).rejects.toThrow('expired or was revoked');
+ await expect(squareClient.request({ auth: connection(), method: HttpMethod.GET, path: ['v2', 'payments', 'P1'], operation: 'x' })).rejects.toThrow('not found');
+ });
+
+ test('retries a 429 and then succeeds', async () => {
+ const seen = stubFetch((_request, index) => (index === 0 ? { status: 429, body: { errors: [{ code: 'RATE_LIMITED' }] } } : { body: { ok: 1 } }));
+ const result = await squareClient.request<{ ok: number }>({ auth: connection(), method: HttpMethod.GET, path: ['v2', 'locations'], operation: 'x' });
+ expect(result.ok).toBe(1);
+ expect(seen).toHaveLength(2);
+ });
+});
diff --git a/packages/pieces/community/square/test/helpers.ts b/packages/pieces/community/square/test/helpers.ts
new file mode 100644
index 00000000000..d813572f765
--- /dev/null
+++ b/packages/pieces/community/square/test/helpers.ts
@@ -0,0 +1,78 @@
+import { vi } from 'vitest';
+
+export const TOKEN = 'sq-test-token';
+
+export function connection() {
+ return { access_token: TOKEN, data: { merchant_id: 'MERCHANT1' } };
+}
+
+export function stubFetch(respond: (request: SeenRequest, index: number) => FakeReply): SeenRequest[] {
+ const seen: SeenRequest[] = [];
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async (input: string | URL | Request, init?: RequestInit) => {
+ const url = input instanceof Request ? input.url : String(input);
+ const headers = new Headers(init?.headers);
+ const parsed = new URL(url);
+ const raw = init?.body;
+ const text = typeof raw === 'string' ? raw : '';
+ const request: SeenRequest = {
+ url,
+ method: (init?.method ?? 'GET').toUpperCase(),
+ path: parsed.pathname,
+ query: parsed.searchParams,
+ headers,
+ json: text ? JSON.parse(text) : null,
+ };
+ seen.push(request);
+ const reply = respond(request, seen.length - 1);
+ return new Response(reply.body === undefined ? '' : JSON.stringify(reply.body), {
+ status: reply.status ?? 200,
+ headers: { 'content-type': 'application/json' },
+ });
+ }),
+ );
+ return seen;
+}
+
+export function memoryStore() {
+ const data = new Map<string, string>();
+ return {
+ put: async <T>(key: string, value: T): Promise<T> => {
+ data.set(key, JSON.stringify(value));
+ return value;
+ },
+ get: async <T>(key: string): Promise<T | null> => {
+ const raw = data.get(key);
+ return raw === undefined ? null : JSON.parse(raw);
+ },
+ delete: async (key: string): Promise<void> => {
+ data.delete(key);
+ },
+ };
+}
+
+export function context(propsValue: Record<string, unknown>) {
+ return {
+ auth: connection(),
+ propsValue,
+ store: memoryStore(),
+ files: {},
+ server: { apiUrl: '', publicUrl: '', token: '' },
+ run: { id: 'run-1' },
+ step: { name: 'step_1' },
+ };
+}
+
+export const LOCATION = { location: { id: 'LOC1', status: 'ACTIVE', currency: 'USD', name: 'Main' } };
+
+export type SeenRequest = {
+ url: string;
+ method: string;
+ path: string;
+ query: URLSearchParams;
+ headers: Headers;
+ json: unknown;
+};
+
+export type FakeReply = { status?: number; body?: unknown };
diff --git a/packages/pieces/community/square/test/metadata.test.ts b/packages/pieces/community/square/test/metadata.test.ts
new file mode 100644
index 00000000000..6f856a5d81b
--- /dev/null
+++ b/packages/pieces/community/square/test/metadata.test.ts
@@ -0,0 +1,73 @@
+import { describe, expect, test } from 'vitest';
+import { square } from '../src';
+import { SQUARE_SCOPES } from '../src/lib/auth';
+
+const actions = Object.values(square.actions());
+const handWritten = actions.filter((action) => action.name !== 'custom_api_call');
+const triggers = Object.values(square.triggers());
+
+describe('piece metadata', () => {
+ test('38 actions plus custom API call, 5 triggers with unchanged names', () => {
+ expect(handWritten).toHaveLength(38);
+ expect(actions.map((action) => action.name)).toContain('custom_api_call');
+ expect(triggers.map((trigger) => trigger.name).sort()).toEqual(['customer_updated', 'new_customer', 'new_order', 'new_payment', 'order_updated']);
+ });
+
+ test.each(handWritten.map((action) => [action.name, action]))('%s declares audience, classification, aiMetadata and outputSchema', (_name, action) => {
+ expect(['both', 'ai', 'human']).toContain(action.audience);
+ expect(['READ', 'SEARCH', 'WRITE', 'DESTRUCTIVE']).toContain(action.classification);
+ expect(action.aiMetadata?.description?.length ?? 0).toBeGreaterThan(60);
+ expect(typeof action.aiMetadata?.idempotent).toBe('boolean');
+ expect(action.outputSchema?.fields.length).toBeGreaterThan(0);
+ });
+
+ test('agent-visible actions have no dynamic dropdowns', () => {
+ for (const action of handWritten.filter((item) => item.audience !== 'human')) {
+ const types = Object.values(action.props).map((prop: unknown) => (prop !== null && typeof prop === 'object' ? Reflect.get(prop, 'type') : undefined));
+ expect(types, action.name).not.toContain('DROPDOWN');
+ expect(types, action.name).not.toContain('DYNAMIC');
+ }
+ });
+
+ test('every human dropdown action has an ai twin', () => {
+ const names = new Set(handWritten.map((action) => action.name));
+ const humanOnly = handWritten.filter((action) => action.audience === 'human' && action.name !== 'refund_payment');
+ for (const action of humanOnly) {
+ expect(names.has(`${action.name}_by_id`), action.name).toBe(true);
+ }
+ });
+
+ test('refund is human only and destructive', () => {
+ const refund = handWritten.find((action) => action.name === 'refund_payment');
+ expect(refund?.audience).toBe('human');
+ expect(refund?.classification).toBe('DESTRUCTIVE');
+ expect(handWritten.some((action) => action.name.startsWith('refund_payment_'))).toBe(false);
+ });
+
+ test('no action charges a card', () => {
+ for (const action of handWritten) {
+ expect(JSON.stringify(action.props)).not.toMatch(/source_id|card_nonce|card on file/i);
+ }
+ });
+
+ test('triggers are READ with aiMetadata and an output schema', () => {
+ for (const trigger of triggers) {
+ expect(trigger.classification).toBe('READ');
+ expect(trigger.aiMetadata?.description?.length ?? 0).toBeGreaterThan(40);
+ expect(trigger.outputSchema?.fields.length).toBeGreaterThan(0);
+ }
+ });
+
+ test('scopes', () => {
+ expect(SQUARE_SCOPES).toEqual([
+ 'MERCHANT_PROFILE_READ', 'CUSTOMERS_READ', 'CUSTOMERS_WRITE', 'ITEMS_READ', 'ITEMS_WRITE', 'ORDERS_READ', 'ORDERS_WRITE', 'PAYMENTS_READ',
+ 'PAYMENTS_WRITE', 'INVENTORY_READ', 'INVENTORY_WRITE', 'EMPLOYEES_READ',
+ ]);
+ });
+});
+
+test('no invoice or appointment steps ship', () => {
+ for (const step of [...handWritten, ...triggers]) {
+ expect(step.name, step.name).not.toMatch(/invoice|booking|appointment|availability/);
+ }
+});
diff --git a/packages/pieces/community/square/test/money.test.ts b/packages/pieces/community/square/test/money.test.ts
new file mode 100644
index 00000000000..6e6682b65d7
--- /dev/null
+++ b/packages/pieces/community/square/test/money.test.ts
@@ -0,0 +1,115 @@
+import { describe, expect, test } from 'vitest';
+import { squareIdempotency } from '../src/lib/common/idempotency';
+import { squareInputs } from '../src/lib/common/inputs';
+import { squareMoney } from '../src/lib/common/money';
+
+describe('money', () => {
+ test.each([
+ ['12.50', 'USD', 1250],
+ ['12.5', 'USD', 1250],
+ ['0.10', 'USD', 10],
+ ['19.99', 'USD', 1999],
+ ['12.500', 'USD', 1250],
+ ['1000', 'JPY', 1000],
+ ['1000.0', 'JPY', 1000],
+ ['4.35', 'EUR', 435],
+ [0.29, 'USD', 29],
+ [1.005, 'USD', null],
+ ])('%s %s -> %s', (amount, currency, expected) => {
+ if (expected === null) {
+ expect(() => squareMoney.toMinor({ amount, currency, label: 'Amount' })).toThrow('more decimal places');
+ } else {
+ expect(squareMoney.toMinor({ amount, currency, label: 'Amount' })).toBe(expected);
+ }
+ });
+
+ test('rejects bad amounts', () => {
+ expect(() => squareMoney.toMinor({ amount: '-1', currency: 'USD', label: 'Amount' })).toThrow('not a valid amount');
+ expect(() => squareMoney.toMinor({ amount: '$5', currency: 'USD', label: 'Amount' })).toThrow('not a valid amount');
+ expect(() => squareMoney.toMinor({ amount: '10.5', currency: 'JPY', label: 'Amount' })).toThrow('more decimal places');
+ expect(() => squareMoney.toMinor({ amount: '0', currency: 'USD', label: 'Amount' })).toThrow('greater than zero');
+ expect(squareMoney.toMinor({ amount: '0', currency: 'USD', label: 'Amount', allowZero: true })).toBe(0);
+ expect(() => squareMoney.toMinor({ amount: '99999999999999999', currency: 'USD', label: 'Amount' })).toThrow('too large');
+ expect(() => squareMoney.toMinor({ amount: '', currency: 'USD', label: 'Amount' })).toThrow('required');
+ });
+
+ test('formats minor units with string math', () => {
+ expect(squareMoney.format({ minor: 1250, currency: 'USD' })).toBe('12.50');
+ expect(squareMoney.format({ minor: 5, currency: 'USD' })).toBe('0.05');
+ expect(squareMoney.format({ minor: -1999, currency: 'USD' })).toBe('-19.99');
+ expect(squareMoney.format({ minor: 1000, currency: 'JPY' })).toBe('1000');
+ expect(squareMoney.format({ minor: 9007199254740991, currency: 'USD' })).toBe('90071992547409.91');
+ });
+
+ test('normalizes currency codes', () => {
+ expect(squareMoney.normalizeCurrency(' usd ')).toBe('USD');
+ expect(squareMoney.normalizeCurrency('')).toBeUndefined();
+ expect(() => squareMoney.normalizeCurrency('dollars')).toThrow('3-letter');
+ });
+
+ test('quantities', () => {
+ expect(squareMoney.quantity({ value: '2', label: 'Q' })).toBe('2');
+ expect(squareMoney.quantity({ value: '1.50', label: 'Q' })).toBe('1.5');
+ expect(squareMoney.quantity({ value: 3, label: 'Q', wholeOnly: true })).toBe('3');
+ expect(() => squareMoney.quantity({ value: '1.5', label: 'Q', wholeOnly: true })).toThrow('whole number');
+ expect(() => squareMoney.quantity({ value: '0', label: 'Q' })).toThrow('greater than zero');
+ expect(squareMoney.quantity({ value: '0', label: 'Q', allowZero: true })).toBe('0');
+ expect(() => squareMoney.quantity({ value: '-2', label: 'Q' })).toThrow('not a valid quantity');
+ });
+});
+
+describe('idempotency keys', () => {
+ const base = { custom: undefined, runId: 'run-1', stepName: 'step_1', action: 'refund_payment', input: { a: 1, b: { c: 2 } } };
+
+ test('a retried step gets the same key, whatever the key order of the input', () => {
+ const first = squareIdempotency.key(base);
+ expect(first).toHaveLength(40);
+ expect(squareIdempotency.key(base)).toBe(first);
+ expect(squareIdempotency.key({ ...base, input: { b: { c: 2 }, a: 1 } })).toBe(first);
+ });
+
+ test('identical loop iterations in one run share a key by design', () => {
+ expect(squareIdempotency.key(base)).toBe(squareIdempotency.key({ ...base }));
+ });
+
+ test('a different run, step or input gives a new key', () => {
+ const first = squareIdempotency.key(base);
+ expect(squareIdempotency.key({ ...base, runId: 'run-2' })).not.toBe(first);
+ expect(squareIdempotency.key({ ...base, stepName: 'step_2' })).not.toBe(first);
+ expect(squareIdempotency.key({ ...base, input: { a: 2, b: { c: 2 } } })).not.toBe(first);
+ });
+
+ test('custom keys are sent as given and keep loop iterations separate', () => {
+ expect(squareIdempotency.key({ ...base, custom: ' item-1 ' })).toBe('item-1');
+ expect(squareIdempotency.key({ ...base, custom: 'item-2' })).not.toBe(squareIdempotency.key({ ...base, custom: 'item-1' }));
+ expect(() => squareIdempotency.key({ ...base, custom: 'x'.repeat(46) })).toThrow('at most 45');
+ });
+
+ test('without a run id each call is unique', () => {
+ expect(squareIdempotency.key({ ...base, runId: undefined })).not.toBe(squareIdempotency.key({ ...base, runId: undefined }));
+ });
+});
+
+describe('inputs', () => {
+ test('ids reject path tricks', () => {
+ expect(squareInputs.requireId({ value: ' ABC ', label: 'ID' })).toBe('ABC');
+ expect(() => squareInputs.requireId({ value: '../x', label: 'ID' })).toThrow('not a valid Square ID');
+ expect(() => squareInputs.requireId({ value: 'a?b', label: 'ID' })).toThrow('not a valid Square ID');
+ expect(() => squareInputs.requireId({ value: '', label: 'ID' })).toThrow('required');
+ });
+
+ test('limits clamp to the endpoint max', () => {
+ expect(squareInputs.limit({ value: undefined, fallback: 50, max: 100 })).toBe(50);
+ expect(squareInputs.limit({ value: 500, fallback: 50, max: 100 })).toBe(100);
+ expect(squareInputs.limit({ value: '7', fallback: 50, max: 100 })).toBe(7);
+ expect(() => squareInputs.limit({ value: 0, fallback: 50, max: 100 })).toThrow('whole number');
+ });
+
+ test('dates', () => {
+ expect(squareInputs.dateTime({ value: '2026-10-07T10:00:00+02:00', label: 'D' })).toBe('2026-10-07T08:00:00.000Z');
+ expect(() => squareInputs.dateTime({ value: 'soon', label: 'D' })).toThrow('not a valid date');
+ expect(squareInputs.dateOnly({ value: '2026-11-30', label: 'D' })).toBe('2026-11-30');
+ expect(squareInputs.idList({ value: 'A, B,A', label: 'IDs', max: 5 })).toEqual(['A', 'B']);
+ expect(() => squareInputs.idList({ value: ['A', 'B', 'C'], label: 'IDs', max: 2 })).toThrow('at most 2');
+ });
+});
diff --git a/packages/pieces/community/square/test/triggers.test.ts b/packages/pieces/community/square/test/triggers.test.ts
new file mode 100644
index 00000000000..bd851e06f29
--- /dev/null
+++ b/packages/pieces/community/square/test/triggers.test.ts
@@ -0,0 +1,204 @@
+import crypto from 'crypto';
+import { DEDUPE_KEY_PROPERTY } from '@activepieces/pieces-framework';
+import { afterEach, describe, expect, test, vi } from 'vitest';
+import { square } from '../src';
+import { triggers } from '../src/lib/triggers';
+import { squareSamples } from '../src/lib/triggers/samples';
+import { connection, memoryStore, stubFetch, TOKEN } from './helpers';
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+function trigger(name: string) {
+ const found = triggers.find((item) => item.name === name);
+ if (!found) {
+ throw new Error(`missing trigger ${name}`);
+ }
+ return found;
+}
+
+function runContext({ body, propsValue = {}, store = memoryStore() }: { body: unknown; propsValue?: Record<string, unknown>; store?: ReturnType<typeof memoryStore> }) {
+ return { auth: connection(), propsValue, store, payload: { body, headers: {}, queryParams: {} } };
+}
+
+describe('custom api call', () => {
+ function customCall() {
+ const found = square.actions()['custom_api_call'];
+ if (!found) {
+ throw new Error('missing custom_api_call');
+ }
+ return found;
+ }
+ const call = (url: string) =>
+ customCall().run({ auth: connection(), propsValue: { url: { url }, method: 'GET', headers: {}, queryParams: {}, failsafe: false }, store: memoryStore() });
+
+ test.each([
+ 'https://evil.example.com/v2/locations',
+ 'https://connect.squareup.com.evil.io/v2/locations',
+ 'http://connect.squareup.com/v2/locations',
+ 'https://[email protected]/v2/locations',
+ 'https://connect.squareup.com:8443/v2/locations',
+ 'HTTPS://evil.example.com/v2',
+ ])('refuses to send the token to %s', async (url) => {
+ const seen = stubFetch(() => ({ body: {} }));
+ await expect(call(url)).rejects.toThrow('only sends the Square token');
+ expect(seen).toHaveLength(0);
+ });
+
+ test.each(['/v2/locations', 'https://connect.squareup.com/v2/locations'])('sends %s to Square with the token', async (url) => {
+ const seen = stubFetch(() => ({ body: { locations: [] } }));
+ await call(url);
+ expect(seen[0].url.startsWith('https://connect.squareup.com/v2/locations')).toBe(true);
+ expect(seen[0].headers.get('authorization')).toBe(`Bearer ${TOKEN}`);
+ });
+});
+
+describe('webhook signature', () => {
+ const secret = 'sig-key';
+ const url = 'https://cloud.example.com/api/v1/app-events/square';
+ const rawBody = '{"type":"customer.created","merchant_id":"M1"}';
+ const good = crypto.createHmac('sha256', secret).update(url + rawBody).digest('base64');
+ const verify = (signature: unknown) =>
+ square.events?.verify({ webhookSecret: secret, appWebhookUrl: url, payload: { body: JSON.parse(rawBody), rawBody, headers: { 'x-square-hmacsha256-signature': signature }, queryParams: {} } });
+
+ test('accepts the right signature and rejects others', () => {
+ expect(verify(good)).toBe(true);
+ expect(verify(good.slice(0, -2) + 'AA')).toBe(false);
+ expect(verify('short')).toBe(false);
+ expect(verify(undefined)).toBe(false);
+ expect(verify([good])).toBe(true);
+ });
+
+ test('parseAndReply routes by event type and merchant', () => {
+ expect(square.events?.parseAndReply({ payload: { body: { type: 'order.created', merchant_id: 'M1' }, headers: {}, queryParams: {} } })).toEqual({ event: 'order.created', identifierValue: 'M1' });
+ });
+});
+
+describe('trigger runs', () => {
+ test('dedupes a retried delivery by event_id', async () => {
+ const store = memoryStore();
+ const t = trigger('new_customer');
+ expect(await t.run(runContext({ body: squareSamples.new_customer, store }))).toHaveLength(1);
+ expect(await t.run(runContext({ body: squareSamples.new_customer, store }))).toHaveLength(0);
+ expect(await t.run(runContext({ body: { ...squareSamples.new_customer, event_id: 'other' }, store }))).toHaveLength(1);
+ });
+
+ test('a delivery stays blocked for 15 minutes so a retried job cannot start a second run', async () => {
+ const store = memoryStore();
+ const t = trigger('new_customer');
+ const start = Date.now();
+ expect(await t.run(runContext({ body: squareSamples.new_customer, store }))).toHaveLength(1);
+ try {
+ vi.spyOn(Date, 'now').mockReturnValue(start + 8 * 60 * 1000);
+ expect(await t.run(runContext({ body: squareSamples.new_customer, store }))).toHaveLength(0);
+ vi.spyOn(Date, 'now').mockReturnValue(start + 16 * 60 * 1000);
+ expect(await t.run(runContext({ body: squareSamples.new_customer, store }))).toHaveLength(1);
+ } finally {
+ vi.restoreAllMocks();
+ }
+ });
+
+ test('keeps the dedupe state bounded', async () => {
+ const store = memoryStore();
+ const t = trigger('new_payment');
+ for (let i = 0; i < 700; i++) {
+ await t.run(runContext({ body: { ...squareSamples.new_payment, event_id: `e${i}` }, store }));
+ }
+ const sizes = await Promise.all(Array.from({ length: 64 }, (_, slot) => store.get<unknown[]>(`square_seen_events_${slot}`)));
+ expect(sizes.every((entries) => (entries?.length ?? 0) <= 100)).toBe(true);
+ expect(await store.get('square_seen_events_64')).toBeNull();
+ });
+
+ test('a failed order read does not mark the event as seen', async () => {
+ const store = memoryStore();
+ const seen = stubFetch((_request, index) =>
+ index === 0 ? { status: 500, body: { errors: [{ code: 'INTERNAL_SERVER_ERROR' }] } } : { body: { order: { id: 'eA3vssLHKJrv9H0IdJCM3gNqfdcZY', state: 'OPEN' } } },
+ );
+ const t = trigger('new_order');
+ const props = { include_full_order: true };
+ await expect(t.run(runContext({ body: squareSamples.new_order, propsValue: props, store }))).rejects.toThrow('500');
+ expect(await t.run(runContext({ body: squareSamples.new_order, propsValue: props, store }))).toHaveLength(1);
+ expect(await t.run(runContext({ body: squareSamples.new_order, propsValue: props, store }))).toHaveLength(0);
+ expect(seen).toHaveLength(2);
+ });
+
+ test('a delivery in progress blocks a concurrent copy until its claim goes stale', async () => {
+ const store = memoryStore();
+ const t = trigger('new_customer');
+ const eventId = squareSamples.new_customer.event_id;
+ const slotKeys = Array.from({ length: 64 }, (_, slot) => `square_seen_events_${slot}`);
+ const now = Date.now();
+ await Promise.all(slotKeys.map((key) => store.put(key, [{ id: eventId, at: now, token: 'other-job', done: false }])));
+ expect(await t.run(runContext({ body: squareSamples.new_customer, store }))).toHaveLength(0);
+ const stale = now - 3 * 60 * 1000;
+ await Promise.all(slotKeys.map((key) => store.put(key, [{ id: eventId, at: stale, token: 'crashed-job', done: false }])));
+ expect(await t.run(runContext({ body: squareSamples.new_customer, store }))).toHaveLength(1);
+ });
+
+ test('different events sharing a slot keep each other', async () => {
+ const store = memoryStore();
+ const t = trigger('new_payment');
+ const ids = Array.from({ length: 200 }, (_, i) => `evt-${i}`);
+ for (const id of ids) {
+ await t.run(runContext({ body: { ...squareSamples.new_payment, event_id: id }, store }));
+ }
+ const replays = await Promise.all(ids.map((id) => t.run(runContext({ body: { ...squareSamples.new_payment, event_id: id }, store }))));
+ expect(replays.every((events) => events.length === 0)).toBe(true);
+ });
+
+ test('every emitted event carries the platform dedupe key square:<event_id>', async () => {
+ stubFetch(() => ({ body: { order: { id: 'eA3vssLHKJrv9H0IdJCM3gNqfdcZY', state: 'OPEN' } } }));
+ const cases: { name: string; body: { event_id: string }; propsValue: Record<string, unknown> }[] = [
+ { name: 'new_customer', body: squareSamples.new_customer, propsValue: {} },
+ { name: 'new_payment', body: squareSamples.new_payment, propsValue: {} },
+ { name: 'new_order', body: squareSamples.new_order, propsValue: { include_full_order: true } },
+ ];
+ for (const { name, body, propsValue } of cases) {
+ const events = await trigger(name).run(runContext({ body, propsValue }));
+ expect(events).toHaveLength(1);
+ expect(Reflect.get(Object(events[0]), DEDUPE_KEY_PROPERTY)).toBe(`square:${body.event_id}`);
+ }
+ const noId = await trigger('new_customer').run(runContext({ body: { ...squareSamples.new_customer, event_id: undefined } }));
+ expect(Object.keys(Object(noId[0]))).not.toContain(DEDUPE_KEY_PROPERTY);
+ });
+
+ test('sample data and output schemas do not carry the dedupe key', () => {
+ for (const t of triggers) {
+ expect(JSON.stringify(t.sampleData)).not.toContain(DEDUPE_KEY_PROPERTY);
+ expect(JSON.stringify(t.outputSchema ?? {})).not.toContain(DEDUPE_KEY_PROPERTY);
+ }
+ });
+
+ test('location filter drops events from other locations', async () => {
+ const t = trigger('new_payment');
+ expect(await t.run(runContext({ body: squareSamples.new_payment, propsValue: { location_id: 'OTHER' } }))).toHaveLength(0);
+ expect(await t.run(runContext({ body: squareSamples.new_payment, propsValue: { location_id: 'S8GWD5R9QB376' } }))).toHaveLength(1);
+ });
+
+ test('include full order adds the fetched order, drops unknown orders', async () => {
+ const seen = stubFetch((request) =>
+ request.path.endsWith('missing')
+ ? { status: 404, body: { errors: [{ code: 'NOT_FOUND' }] } }
+ : { body: { order: { id: 'eA3vssLHKJrv9H0IdJCM3gNqfdcZY', state: 'OPEN', total_money: { amount: 900, currency: 'USD' } } } },
+ );
+ const t = trigger('new_order');
+ const [event] = await t.run(runContext({ body: squareSamples.new_order, propsValue: { include_full_order: true } }));
+ expect(seen[0].path).toBe('/v2/orders/eA3vssLHKJrv9H0IdJCM3gNqfdcZY');
+ expect(event).toMatchObject({ type: 'order.created', order: { id: 'eA3vssLHKJrv9H0IdJCM3gNqfdcZY', total: '9.00' } });
+ const forged = { ...squareSamples.new_order, event_id: 'forged', data: { ...squareSamples.new_order.data, id: 'missing' } };
+ expect(await t.run(runContext({ body: forged, propsValue: { include_full_order: true } }))).toHaveLength(0);
+ });
+
+ test('without the opt-in the order payload is unchanged and nothing is fetched', async () => {
+ const seen = stubFetch(() => ({ body: {} }));
+ const t = trigger('order_updated');
+ expect(await t.run(runContext({ body: squareSamples.order_updated }))).toEqual([{ ...squareSamples.order_updated, [DEDUPE_KEY_PROPERTY]: `square:${squareSamples.order_updated.event_id}` }]);
+ expect(seen).toHaveLength(0);
+ });
+
+ test('order samples use the real data.type values', () => {
+ expect(squareSamples.new_order.data.type).toBe('order_created');
+ expect(squareSamples.order_updated.data.type).toBe('order_updated');
+ });
+});
diff --git a/packages/pieces/community/square/vitest.config.ts b/packages/pieces/community/square/vitest.config.ts
new file mode 100644
index 00000000000..79c97261904
--- /dev/null
+++ b/packages/pieces/community/square/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'),
+ },
+ },
+})