AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents
TypeScript ai-agentai-agent-toolsai-agentsai-agents-frameworkmcpmcp-servermcp-toolsmcpsn8n-alternativeno-code-automationworkflowworkflow-automationworkflows
feat(moxie-crm): let AI agents manage clients, projects, tasks, invoices and more (#16097)
Odai Ahmadd74858f03c82
diff --git a/bun.lock b/bun.lockindex 04ef6a2f2e1..dd9923d1c26 100644--- a/bun.lock+++ b/bun.lock@@ -6219,7 +6219,7 @@},"packages/pieces/community/moxie-crm": {"name": "@activepieces/piece-moxie-crm",- "version": "0.3.0",+ "version": "0.4.0","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",diff --git a/packages/pieces/community/moxie-crm/package.json b/packages/pieces/community/moxie-crm/package.jsonindex 38243ac0866..3f5cdc4e798 100644--- a/packages/pieces/community/moxie-crm/package.json+++ b/packages/pieces/community/moxie-crm/package.json@@ -1,6 +1,6 @@{"name": "@activepieces/piece-moxie-crm",- "version": "0.3.0",+ "version": "0.4.0","main": "./dist/src/index.js","types": "./dist/src/index.d.ts","scripts": {diff --git a/packages/pieces/community/moxie-crm/src/i18n/translation.json b/packages/pieces/community/moxie-crm/src/i18n/translation.jsonindex 1d96b0c5ed4..4bdcfe5bd93 100644--- a/packages/pieces/community/moxie-crm/src/i18n/translation.json+++ b/packages/pieces/community/moxie-crm/src/i18n/translation.json@@ -3,15 +3,115 @@"API Key": "API Key","Base URL": "Base URL","The API Key of the Moxie CRM account": "The API Key of the Moxie CRM account",- "The Base URL of the Moxie CRM account": "The Base URL of the Moxie CRM account",- "\n To obtain your Moxie CRM token, follow these steps:\n\n 1. Log in to your Moxie CRM account and click on **Workspace Settings** (Bottom left).\n 2. Click on **Connected Apps** and navigate to **Integrations** tab.\n 3. Now, under \"Custom Integration\", click on **Enable Custom Integration**.\n 4. Copy **API Key** and **Base URL** and click on Save button.\n ": "\n To obtain your Moxie CRM token, follow these steps:\n\n 1. Log in to your Moxie CRM account and click on **Workspace Settings** (Bottom left).\n 2. Click on **Connected Apps** and navigate to **Integrations** tab.\n 3. Now, under \"Custom Integration\", click on **Enable Custom Integration**.\n 4. Copy **API Key** and **Base URL** and click on Save button.\n ",+ "The Base URL shown next to the API key, for example https://pod01.withmoxie.com/api/public": "The Base URL shown next to the API key, for example https://pod01.withmoxie.com/api/public",+ "\n To connect your Moxie workspace:\n\n 1. Log in to Moxie and click **Workspace Settings** (bottom left).\n 2. Open **Connected Apps** and go to the **Integrations** tab.\n 3. Under **Custom Integration**, click **Enable Custom Integration**.\n 4. Copy the **API Key** and the **Base URL** (it looks like `https://pod01.withmoxie.com/api/public`) and click **Save**.\n ": "\n To connect your Moxie workspace:\n\n 1. Log in to Moxie and click **Workspace Settings** (bottom left).\n 2. Open **Connected Apps** and go to the **Integrations** tab.\n 3. Under **Custom Integration**, click **Enable Custom Integration**.\n 4. Copy the **API Key** and the **Base URL** (it looks like `https://pod01.withmoxie.com/api/public`) and click **Save**.\n ","Create a Client": "Create a Client",+ "Create a Contact": "Create a Contact","Create a Task": "Create a Task","Create a Project": "Create a Project",+ "List Clients": "List Clients",+ "Search Clients": "Search Clients",+ "Search Contacts": "Search Contacts",+ "Search Projects": "Search Projects",+ "List Pipeline Stages": "List Pipeline Stages",+ "List Workspace Users": "List Workspace Users",+ "List Invoice Templates": "List Invoice Templates",+ "Add Ticket Comment": "Add Ticket Comment",+ "Record Payment": "Record Payment",+ "Approve Task": "Approve Task",+ "Attach File from URL": "Attach File from URL",+ "Create Expense": "Create Expense",+ "Submit Lead Form": "Submit Lead Form",+ "Create Invoice": "Create Invoice",+ "Create Opportunity": "Create Opportunity",+ "Create or Update Calendar Event": "Create or Update Calendar Event",+ "Create Ticket": "Create Ticket",+ "Log Time": "Log Time",+ "Delete Calendar Event": "Delete Calendar Event",+ "Get Email Template": "Get Email Template",+ "Get Workspace Account": "Get Workspace Account",+ "List Email Templates": "List Email Templates",+ "List Form Names": "List Form Names",+ "List Project Types": "List Project Types",+ "List Task Stages": "List Task Stages",+ "List Tasks": "List Tasks",+ "List Tickets": "List Tickets",+ "List Vendors": "List Vendors",+ "Search Agreements": "Search Agreements",+ "Search Open Invoices": "Search Open Invoices",+ "Search Tasks": "Search Tasks",+ "Search Tickets": "Search Tickets",+ "Update Client": "Update Client",+ "Update Contact": "Update Contact",+ "Update Expense": "Update Expense",+ "Update Opportunity": "Update Opportunity",+ "Update Project": "Update Project",+ "Update Task": "Update Task",+ "Update Ticket Status": "Update Ticket Status",+ "Upload Attachment": "Upload Attachment",+ "Create Client": "Create Client",+ "Create Contact": "Create Contact",+ "Create Project": "Create Project",+ "Create Task": "Create Task","Custom API Call": "Custom API Call","Create a new client record in moxie CRM.": "Create a new client record in moxie CRM.",+ "Create a new contact record in moxie CRM.": "Create a new contact record in moxie CRM.","Create a task in project.": "Create a task in project.","Creates a new project in moxie CRM.": "Creates a new project in moxie CRM.",+ "Retrieve every client and prospect in the workspace.": "Retrieve every client and prospect in the workspace.",+ "Find clients by name, phone, contact email or contact name, or look one up by id.": "Find clients by name, phone, contact email or contact name, or look one up by id.",+ "Find contacts by first name, last name or email, or look one up by id.": "Find contacts by first name, last name or email, or look one up by id.",+ "List a client's projects, look up one project by id, or list every project.": "List a client's projects, look up one project by id, or list every project.",+ "Retrieve the opportunity pipeline stages of the workspace.": "Retrieve the opportunity pipeline stages of the workspace.",+ "Retrieve the users of the workspace and their access.": "Retrieve the users of the workspace and their access.",+ "Retrieve the invoice template names of the workspace.": "Retrieve the invoice template names of the workspace.",+ "Add a comment to a ticket.": "Add a comment to a ticket.",+ "Record a payment against an open invoice.": "Record a payment against an open invoice.",+ "Approve a task that is waiting for client approval.": "Approve a task that is waiting for client approval.",+ "Attach a file from a public URL to a client, project, task, opportunity, expense or ticket.": "Attach a file from a public URL to a client, project, task, opportunity, expense or ticket.",+ "Record an expense, optionally billable to a client.": "Record an expense, optionally billable to a client.",+ "Submit a Moxie lead or discovery form, which adds a lead to the pipeline.": "Submit a Moxie lead or discovery form, which adds a lead to the pipeline.",+ "Create an invoice with line items. It stays a draft unless you turn on Send Invoice.": "Create an invoice with line items. It stays a draft unless you turn on Send Invoice.",+ "Add a deal to the sales pipeline.": "Add a deal to the sales pipeline.",+ "Create a Moxie calendar event, or update one by id.": "Create a Moxie calendar event, or update one by id.",+ "Open a support ticket.": "Open a support ticket.",+ "Log a time entry against a client, project and task.": "Log a time entry against a client, project and task.",+ "Delete a Moxie calendar event.": "Delete a Moxie calendar event.",+ "Get the subject and HTML content of an email template.": "Get the subject and HTML content of an email template.",+ "Get the business name, address, tax id and currency of the workspace.": "Get the business name, address, tax id and currency of the workspace.",+ "List the email templates of the workspace.": "List the email templates of the workspace.",+ "List the names of the lead and discovery forms.": "List the names of the lead and discovery forms.",+ "List the project types with their task stages and custom fields.": "List the project types with their task stages and custom fields.",+ "List the task stages of a project type.": "List the task stages of a project type.",+ "List tasks, optionally filtered by project, client, stage or archived state.": "List tasks, optionally filtered by project, client, stage or archived state.",+ "List tickets, optionally filtered by client, open state or archived state.": "List tickets, optionally filtered by client, open state or archived state.",+ "List the vendor names of the workspace.": "List the vendor names of the workspace.",+ "List agreements (contracts), for one client or by id.": "List agreements (contracts), for one client or by id.",+ "List outstanding invoices, for one client or by invoice id.": "List outstanding invoices, for one client or by invoice id.",+ "Find tasks by name or description, or look one up by id.": "Find tasks by name or description, or look one up by id.",+ "Find tickets by text, id or ticket number.": "Find tickets by text, id or ticket number.",+ "Update details of an existing client. Empty fields keep their current value.": "Update details of an existing client. Empty fields keep their current value.",+ "Update details of an existing contact. Empty fields keep their current value.": "Update details of an existing contact. Empty fields keep their current value.",+ "Update fields on an existing expense.": "Update fields on an existing expense.",+ "Move a deal to another pipeline stage or update its details. Empty fields keep their current value.": "Move a deal to another pipeline stage or update its details. Empty fields keep their current value.",+ "Update details of an existing project. Empty fields keep their current value.": "Update details of an existing project. Empty fields keep their current value.",+ "Update a task, move it to another stage or change its assignees. Empty fields keep their current value.": "Update a task, move it to another stage or change its assignees. Empty fields keep their current value.",+ "Change the status of a ticket.": "Change the status of a ticket.",+ "Upload a file and attach it to a client, project, task, opportunity, expense or ticket.": "Upload a file and attach it to a client, project, task, opportunity, expense or ticket.",+ "Creates a client or prospect in Moxie.": "Creates a client or prospect in Moxie.",+ "Updates fields on an existing Moxie client.": "Updates fields on an existing Moxie client.",+ "Creates a contact in Moxie, optionally under a client.": "Creates a contact in Moxie, optionally under a client.",+ "Updates fields on an existing Moxie contact.": "Updates fields on an existing Moxie contact.",+ "Records an expense in Moxie.": "Records an expense in Moxie.",+ "Creates a draft invoice in Moxie, and optionally sends it.": "Creates a draft invoice in Moxie, and optionally sends it.",+ "Creates a sales pipeline opportunity in Moxie.": "Creates a sales pipeline opportunity in Moxie.",+ "Updates an existing Moxie opportunity, including its pipeline stage.": "Updates an existing Moxie opportunity, including its pipeline stage.",+ "Records a payment against an open Moxie invoice.": "Records a payment against an open Moxie invoice.",+ "Creates a project for an existing Moxie client.": "Creates a project for an existing Moxie client.",+ "Updates fields on an existing Moxie project.": "Updates fields on an existing Moxie project.",+ "Creates a task inside an existing Moxie project.": "Creates a task inside an existing Moxie project.",+ "Updates fields on an existing Moxie task, including its stage.": "Updates fields on an existing Moxie task, including its stage.",+ "Logs a time entry in Moxie.": "Logs a time entry in Moxie.","Make a custom API call to a specific endpoint": "Make a custom API call to a specific endpoint","Name": "Name","Client Type": "Client Type",@@ -34,6 +134,13 @@"Currency": "Currency","Stripe Client ID": "Stripe Client ID","Notes": "Notes",+ "First Name": "First Name",+ "Last Name": "Last Name",+ "Email": "Email",+ "Client": "Client",+ "Default Contact": "Default Contact",+ "Invoice Contact": "Invoice Contact",+ "Portal Access": "Portal Access","Client Name": "Client Name","Project Name": "Project Name","Status": "Status",@@ -44,7 +151,6 @@"Subtasks": "Subtasks","Assigned To": "Assigned To","Custom Values": "Custom Values",- "Client": "Client","Client Portal Access": "Client Portal Access","Show time worked in portal ?": "Show time worked in portal ?","Fee Type": "Fee Type",@@ -52,27 +158,275 @@"Estimate maximum Amount": "Estimate maximum Amount","Estimate minimum Amount": "Estimate minimum Amount","Is amount taxable ?": "Is amount taxable ?",+ "Project Template": "Project Template",+ "Query": "Query",+ "Client ID": "Client ID",+ "Contact ID": "Contact ID",+ "Project ID": "Project ID",+ "Ticket Number": "Ticket Number",+ "Comment": "Comment",+ "Author Email": "Author Email",+ "Private Note": "Private Note",+ "Invoice": "Invoice",+ "Payment Date": "Payment Date",+ "Payment Method": "Payment Method",+ "Reference Number": "Reference Number",+ "Memo": "Memo",+ "Task Name": "Task Name",+ "Attach To": "Attach To",+ "Record ID": "Record ID",+ "File URL": "File URL",+ "File Name": "File Name",+ "Vendor": "Vendor",+ "Expense Date": "Expense Date",+ "Category": "Category",+ "Paid": "Paid",+ "Billable to Client": "Billable to Client",+ "Markup Percentage": "Markup Percentage",+ "Bill or Receipt Number": "Bill or Receipt Number",+ "Form Name": "Form Name",+ "Role": "Role",+ "Business Name": "Business Name",+ "Address Line 1": "Address Line 1",+ "Address Line 2": "Address Line 2",+ "State or Region": "State or Region",+ "Postal Code": "Postal Code",+ "Source URL": "Source URL",+ "Pipeline Stage": "Pipeline Stage",+ "Answers": "Answers",+ "Invoice Template": "Invoice Template",+ "Line Items": "Line Items",+ "Tax Rate": "Tax Rate",+ "Discount Percentage": "Discount Percentage",+ "Payment Instructions": "Payment Instructions",+ "Invoice Number": "Invoice Number",+ "Send Invoice": "Send Invoice",+ "Send To Contacts": "Send To Contacts",+ "Email Template": "Email Template",+ "Opportunity Name": "Opportunity Name",+ "Estimated Value": "Estimated Value",+ "Estimated Close Date": "Estimated Close Date",+ "Event ID": "Event ID",+ "Start Time": "Start Time",+ "End Time": "End Time",+ "Time Zone": "Time Zone",+ "All Day": "All Day",+ "Show as Busy": "Show as Busy",+ "Title": "Title",+ "Location": "Location",+ "Owner Email": "Owner Email",+ "Subject": "Subject",+ "Requester Email": "Requester Email",+ "Ticket Type": "Ticket Type",+ "Project": "Project",+ "Task": "Task",+ "User": "User",+ "Template ID": "Template ID",+ "Project Type ID": "Project Type ID",+ "Stage ID": "Stage ID",+ "Archived": "Archived",+ "Open": "Open",+ "Agreement ID": "Agreement ID",+ "Invoice ID": "Invoice ID",+ "Task ID": "Task ID",+ "Ticket ID": "Ticket ID",+ "Colour": "Colour",+ "Hourly Rate": "Hourly Rate",+ "Time Rounding Increment": "Time Rounding Increment",+ "Clear Fields": "Clear Fields",+ "Contact": "Contact",+ "Mobile": "Mobile",+ "Move to Client": "Move to Client",+ "Expense ID": "Expense ID",+ "Paid Date": "Paid Date",+ "Opportunity ID": "Opportunity ID",+ "Move to Stage": "Move to Stage",+ "Actual Close Date": "Actual Close Date",+ "Sentiment": "Sentiment",+ "Active": "Active",+ "Show Time Worked in Portal": "Show Time Worked in Portal",+ "Stage": "Stage",+ "Assignees": "Assignees",+ "File": "File",+ "Fee Amount": "Fee Amount",+ "Estimate Minimum": "Estimate Minimum",+ "Estimate Maximum": "Estimate Maximum",+ "Fee Taxable": "Fee Taxable",+ "Assignee Emails": "Assignee Emails",+ "Assignee User IDs": "Assignee User IDs",+ "User Email": "User Email",+ "Create Client if Missing": "Create Client if Missing",+ "Create Project if Missing": "Create Project if Missing",+ "Create Task if Missing": "Create Task if Missing","Method": "Method","Headers": "Headers","Query Parameters": "Query Parameters","Body Type": "Body Type","Body": "Body",- "Response is Binary ?": "Response is Binary ?",- "No Error on Failure": "No Error on Failure",- "Timeout (in seconds)": "Timeout (in seconds)",+ "Response is Binary": "Response is Binary",+ "Return Error as Output": "Return Error as Output",+ "Timeout": "Timeout","Follow redirects": "Follow redirects","ISO 3166-1 alpha-2 country code": "ISO 3166-1 alpha-2 country code","Valid 3-Letter ISO 4217 currency code.": "Valid 3-Letter ISO 4217 currency code.",+ "The client this contact belongs to.": "The client this contact belongs to.",+ "Make this the primary contact for the client.": "Make this the primary contact for the client.",+ "Send invoices for the client to this contact.": "Send invoices for the client to this contact.",+ "Allow this contact to sign in to the client portal.": "Allow this contact to sign in to the client portal.","Exact match of a client name in your CRM": "Exact match of a client name in your CRM","Exact match of a project that is owned by the client.": "Exact match of a project that is owned by the client.",+ "The stage to place the task in. Stages come from the selected project type.": "The stage to place the task in. Stages come from the selected project type.","ISO 8601 format date i.e. 2023-07-20": "ISO 8601 format date i.e. 2023-07-20","Numeric priority for sorting in kanban.": "Numeric priority for sorting in kanban.","email addresses of users in the workspace.": "email addresses of users in the workspace.",+ "The client, matched by its exact name.": "The client, matched by its exact name.","Please enter date in YYYY-MM-DD format.": "Please enter date in YYYY-MM-DD format.","One of: None, Overview, Full access, or Read only.": "One of: None, Overview, Full access, or Read only.","One of: Hourly, Fixed Price, Retainer, Per Item.": "One of: Hourly, Fixed Price, Retainer, Per Item.",+ "Exact name of a project template to copy tasks and settings from. Leave empty for none.": "Exact name of a project template to copy tasks and settings from. Leave empty for none.",+ "Custom project field values keyed by field name.": "Custom project field values keyed by field name.",+ "Matches a client name, client phone, contact email or contact phone that starts with this value, or a contact full name that contains it.": "Matches a client name, client phone, contact email or contact phone that starts with this value, or a contact full name that contains it.",+ "Exact client id. When set, the query is ignored.": "Exact client id. When set, the query is ignored.",+ "Matches a contact first name, last name or email. Leave empty to return every contact.": "Matches a contact first name, last name or email. Leave empty to return every contact.",+ "Exact contact id. When set, the query is ignored.": "Exact contact id. When set, the query is ignored.",+ "Exact client name whose projects should be returned. Leave empty to list all projects.": "Exact client name whose projects should be returned. Leave empty to list all projects.",+ "Exact project id. When set, the client name is ignored.": "Exact project id. When set, the client name is ignored.",+ "The ticket number (not the id), from Search Tickets or Create Ticket.": "The ticket number (not the id), from Search Tickets or Create Ticket.",+ "Email of the workspace user or client contact posting the comment.": "Email of the workspace user or client contact posting the comment.",+ "On keeps the comment internal; off (default) shows it to the client.": "On keeps the comment internal; off (default) shows it to the client.",+ "An open (sent, not fully paid) invoice of the selected client.": "An open (sent, not fully paid) invoice of the selected client.",+ "Date in YYYY-MM-DD format.": "Date in YYYY-MM-DD format.",+ "External payment reference, such as a bank or Stripe id. A repeat run with the same reference is skipped.": "External payment reference, such as a bank or Stripe id. A repeat run with the same reference is skipped.",+ "Free-text note on the payment.": "Free-text note on the payment.",+ "Exact client name, from Search Clients.": "Exact client name, from Search Clients.",+ "Exact project name, from Search Projects.": "Exact project name, from Search Projects.",+ "Exact task name, from Search Tasks or List Tasks.": "Exact task name, from Search Tasks or List Tasks.",+ "Id of the client, project, task, opportunity, expense or ticket to attach the file to.": "Id of the client, project, task, opportunity, expense or ticket to attach the file to.",+ "Public https URL of the file.": "Public https URL of the file.",+ "Name to store the file under, including its extension.": "Name to store the file under, including its extension.",+ "Client to bill the expense to.": "Client to bill the expense to.",+ "Three-letter ISO 4217 code, for example USD.": "Three-letter ISO 4217 code, for example USD.",+ "Leave empty to not send this value (an update keeps the current one).": "Leave empty to not send this value (an update keeps the current one).",+ "Yes marks the expense as reimbursable, so it can be billed to the client.": "Yes marks the expense as reimbursable, so it can be billed to the client.",+ "Exact form name, from List Form Names.": "Exact form name, from List Form Names.",+ "Exact stage label to place the lead in (see List Pipeline Stages).": "Exact stage label to place the lead in (see List Pipeline Stages).",+ "Question and answer pairs to store on the submission.": "Question and answer pairs to store on the submission.",+ "The client to bill.": "The client to bill.",+ "Leave empty for the default template.": "Leave empty for the default template.",+ "Flat tax rate percentage applied to taxable items.": "Flat tax rate percentage applied to taxable items.",+ "Leave empty to use the next number in the sequence.": "Leave empty to use the next number in the sequence.",+ "Off (default) keeps the invoice as a draft. On emails it to the contacts below.": "Off (default) keeps the invoice as a draft. On emails it to the contacts below.",+ "Contacts of the selected client who receive the invoice email. Used only when Send Invoice is on.": "Contacts of the selected client who receive the invoice email. Used only when Send Invoice is on.",+ "Email used to send the invoice. Only used when Send Invoice is on.": "Email used to send the invoice. Only used when Send Invoice is on.",+ "Name of the deal.": "Name of the deal.",+ "The client this deal is for. Leave empty for none.": "The client this deal is for. Leave empty for none.",+ "Leave empty for the default stage.": "Leave empty for the default stage.",+ "Custom opportunity field values keyed by field name.": "Custom opportunity field values keyed by field name.",+ "Id of an existing event to update. Leave empty to create a new event.": "Id of an existing event to update. Leave empty to create a new event.",+ "ISO 8601 start, for example 2026-10-01T09:00:00Z. Required when creating.": "ISO 8601 start, for example 2026-10-01T09:00:00Z. Required when creating.",+ "ISO 8601 end, after the start. Required when creating.": "ISO 8601 end, after the start. Required when creating.",+ "IANA time zone, for example America/New_York.": "IANA time zone, for example America/New_York.",+ "Email of the workspace user who owns the event (see List Workspace Users).": "Email of the workspace user who owns the event (see List Workspace Users).",+ "Short summary of the request.": "Short summary of the request.",+ "The first message on the ticket.": "The first message on the ticket.",+ "Email of the client contact or workspace user who raised the ticket.": "Email of the client contact or workspace user who raised the ticket.",+ "Ticket type label as configured in Moxie, for example Support.": "Ticket type label as configured in Moxie, for example Support.",+ "The task, matched by its exact name.": "The task, matched by its exact name.",+ "The workspace user the time is logged for.": "The workspace user the time is logged for.",+ "Id of the event, from Create or Update Calendar Event.": "Id of the event, from Create or Update Calendar Event.",+ "Template id, from List Email Templates.": "Template id, from List Email Templates.",+ "Project type id, from List Project Types or a project record. Leave empty for the default project type.": "Project type id, from List Project Types or a project record. Leave empty for the default project type.",+ "Only tasks of this project, from Search Projects.": "Only tasks of this project, from Search Projects.",+ "Only tasks of this client, from Search Clients.": "Only tasks of this client, from Search Clients.",+ "Only tasks in this stage, from List Task Stages.": "Only tasks in this stage, from List Task Stages.",+ "Yes returns only archived tasks. No or empty returns active ones (the Moxie default).": "Yes returns only archived tasks. No or empty returns active ones (the Moxie default).",+ "Only tickets of this client, from Search Clients.": "Only tickets of this client, from Search Clients.",+ "Yes returns only open tickets, No only closed ones. Leave empty for both.": "Yes returns only open tickets, No only closed ones. Leave empty for both.",+ "Yes returns only archived tickets. No or empty returns active ones (the Moxie default).": "Yes returns only archived tickets. No or empty returns active ones (the Moxie default).",+ "Only agreements of this client, from Search Clients.": "Only agreements of this client, from Search Clients.",+ "Exact agreement id. When set, the client id is ignored.": "Exact agreement id. When set, the client id is ignored.",+ "Exact client name. Leave empty to list the open invoices of every client.": "Exact client name. Leave empty to list the open invoices of every client.",+ "Exact invoice id. When set, the client name is ignored.": "Exact invoice id. When set, the client name is ignored.",+ "Text to match in the task name or description.": "Text to match in the task name or description.",+ "Exact task id. When set, the query is ignored.": "Exact task id. When set, the query is ignored.",+ "Text to match in the subject, status, summary or number.": "Text to match in the subject, status, summary or number.",+ "Exact ticket id. Overrides the number and the query.": "Exact ticket id. Overrides the number and the query.",+ "Exact ticket number. Overrides the query.": "Exact ticket number. Overrides the query.",+ "Client for a paying account, Prospect for a lead.": "Client for a paying account, Prospect for a lead.",+ "Two-letter ISO 3166-1 country code, for example US.": "Two-letter ISO 3166-1 country code, for example US.",+ "Hex colour, for example #78909C.": "Hex colour, for example #78909C.",+ "Minutes to round tracked time to.": "Minutes to round tracked time to.",+ "Yes archives the client, No restores it. Leave empty to keep the current state.": "Yes archives the client, No restores it. Leave empty to keep the current state.",+ "Fields to blank out on the record. Only text fields can be cleared; dates and numbers keep their value.": "Fields to blank out on the record. Only text fields can be cleared; dates and numbers keep their value.",+ "Yes makes this the client's primary contact.": "Yes makes this the client's primary contact.",+ "Yes sends invoices for the client to this contact.": "Yes sends invoices for the client to this contact.",+ "Yes lets this contact sign in to the client portal.": "Yes lets this contact sign in to the client portal.",+ "Moves the contact to this client. Leave empty to keep the current client.": "Moves the contact to this client. Leave empty to keep the current client.",+ "Id of the expense, from Create Expense.": "Id of the expense, from Create Expense.",+ "Tax rate percentage.": "Tax rate percentage.",+ "Client to bill the expense to (from Search Clients).": "Client to bill the expense to (from Search Clients).",+ "Project to file the expense under (from Search Projects).": "Project to file the expense under (from Search Projects).",+ "Map the id from an opportunity trigger or the Create Opportunity step.": "Map the id from an opportunity trigger or the Create Opportunity step.",+ "Leave empty to keep the current stage.": "Leave empty to keep the current stage.",+ "Links the deal to this client. Leave empty to keep the current client.": "Links the deal to this client. Leave empty to keep the current client.",+ "Whole number rating of how the deal is going.": "Whole number rating of how the deal is going.",+ "Yes archives the opportunity, No restores it.": "Yes archives the opportunity, No restores it.",+ "No marks the project inactive, Yes reactivates it.": "No marks the project inactive, Yes reactivates it.",+ "Moves the task to this stage. Leave empty to keep the current stage.": "Moves the task to this stage. Leave empty to keep the current stage.",+ "Replaces the current assignees. Leave empty to keep them.": "Replaces the current assignees. Leave empty to keep them.",+ "Whole number used to sort the kanban board.": "Whole number used to sort the kanban board.",+ "Exact ticket id, from Search Tickets. Give this or the ticket number.": "Exact ticket id, from Search Tickets. Give this or the ticket number.",+ "The ticket number. Give this or the ticket id.": "The ticket number. Give this or the ticket id.",+ "Status label configured for the ticket type, for example Open.": "Status label configured for the ticket type, for example Open.",+ "Id of the record, for example mapped from a trigger or a Search step.": "Id of the record, for example mapped from a trigger or a Search step.",+ "Id of the client to update, from Search Clients, List Clients or a client trigger.": "Id of the client to update, from Search Clients, List Clients or a client trigger.",+ "Exact name of the client to attach the contact to, from Search Clients. Leave empty for a contact without a client.": "Exact name of the client to attach the contact to, from Search Clients. Leave empty for a contact without a client.",+ "Id of the contact to update, from Search Contacts.": "Id of the contact to update, from Search Contacts.",+ "Moves the contact to this client id, from Search Clients. Leave empty to keep the current client.": "Moves the contact to this client id, from Search Clients. Leave empty to keep the current client.",+ "Vendor name, from List Vendors.": "Vendor name, from List Vendors.",+ "Exact client name to bill the expense to, from Search Clients.": "Exact client name to bill the expense to, from Search Clients.",+ "ISO 8601 date and time, for example 2026-10-01T09:30:00Z.": "ISO 8601 date and time, for example 2026-10-01T09:30:00Z.",+ "Exact name of the client to bill, from Search Clients.": "Exact name of the client to bill, from Search Clients.",+ "Exact invoice template name, from List Invoice Templates. Leave empty for the default.": "Exact invoice template name, from List Invoice Templates. Leave empty for the default.",+ "At least one line, each with a description, quantity and rate.": "At least one line, each with a description, quantity and rate.",+ "Emails of the client contacts who receive the invoice. Only used when Send Invoice is on.": "Emails of the client contacts who receive the invoice. Only used when Send Invoice is on.",+ "Exact email template name for the invoice email, from List Email Templates. Only used when Send Invoice is on.": "Exact email template name for the invoice email, from List Email Templates. Only used when Send Invoice is on.",+ "Exact name of the client, from Search Clients. Leave empty for a deal without a client.": "Exact name of the client, from Search Clients. Leave empty for a deal without a client.",+ "Exact pipeline stage label, from List Pipeline Stages. Leave empty for the default stage.": "Exact pipeline stage label, from List Pipeline Stages. Leave empty for the default stage.",+ "Id of the opportunity, from Create Opportunity or an opportunity trigger.": "Id of the opportunity, from Create Opportunity or an opportunity trigger.",+ "Moves the deal to this pipeline stage id, from List Pipeline Stages.": "Moves the deal to this pipeline stage id, from List Pipeline Stages.",+ "Links the deal to this client id, from Search Clients.": "Links the deal to this client id, from Search Clients.",+ "Formatted invoice number, for example E-2026-042, from Search Open Invoices.": "Formatted invoice number, for example E-2026-042, from Search Open Invoices.",+ "Exact name of the client the invoice belongs to.": "Exact name of the client the invoice belongs to.",+ "Payment amount, more than 0.": "Payment amount, more than 0.",+ "Date in YYYY-MM-DD format. Leave empty to use the Moxie default.": "Date in YYYY-MM-DD format. Leave empty to use the Moxie default.",+ "External payment reference. Also used to skip a payment that was already recorded.": "External payment reference. Also used to skip a payment that was already recorded.",+ "Name of the new project.": "Name of the new project.",+ "Exact name of an existing client, from Search Clients.": "Exact name of an existing client, from Search Clients.",+ "Exact name of a project template to copy tasks and settings from.": "Exact name of a project template to copy tasks and settings from.",+ "Sets the fee schedule. Leave empty to create the project without one.": "Sets the fee schedule. Leave empty to create the project without one.",+ "Hourly rate, fixed price, retainer amount or per-item price, depending on Fee Type.": "Hourly rate, fixed price, retainer amount or per-item price, depending on Fee Type.",+ "Id of the project to update, from Search Projects or a project trigger.": "Id of the project to update, from Search Projects or a project trigger.",+ "Name of the new task.": "Name of the new task.",+ "Exact name of the client that owns the project, from Search Clients.": "Exact name of the client that owns the project, from Search Clients.",+ "Exact name of the project, from Search Projects.": "Exact name of the project, from Search Projects.",+ "Stage label to place the task in, from List Task Stages. Leave empty for the default stage.": "Stage label to place the task in, from List Task Stages. Leave empty for the default stage.",+ "Names of subtasks to add.": "Names of subtasks to add.",+ "Emails of workspace users to assign (see List Workspace Users).": "Emails of workspace users to assign (see List Workspace Users).",+ "Custom task field values keyed by field name.": "Custom task field values keyed by field name.",+ "Id of the task to update, from Search Tasks, List Tasks or a task trigger.": "Id of the task to update, from Search Tasks, List Tasks or a task trigger.",+ "Moves the task to this stage id, from List Task Stages or List Project Types. Leave empty to keep the stage.": "Moves the task to this stage id, from List Task Stages or List Project Types. Leave empty to keep the stage.",+ "Numeric user ids (user.userId from List Workspace Users). Replaces the current assignees.": "Numeric user ids (user.userId from List Workspace Users). Replaces the current assignees.",+ "ISO 8601 start, for example 2026-10-01T09:00:00Z.": "ISO 8601 start, for example 2026-10-01T09:00:00Z.",+ "ISO 8601 end, after the start.": "ISO 8601 end, after the start.",+ "Exact task name, from Search Tasks.": "Exact task name, from Search Tasks.",+ "Email of the workspace user the time is logged for, from List Workspace Users. Leave empty to let Moxie use its default user.": "Email of the workspace user the time is logged for, from List Workspace Users. Leave empty to let Moxie use its default user.","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.","Prospect": "Prospect","Not Visible": "Not Visible","Overview only": "Overview only",@@ -82,16 +436,35 @@"Fixed Price": "Fixed Price","Retainer": "Retainer","Per Item": "Per Item",+ "STRIPE": "STRIPE",+ "CHECK": "CHECK",+ "BANK TRANSFER": "BANK TRANSFER",+ "CASH": "CASH",+ "VENMO": "VENMO",+ "PAYPAL": "PAYPAL",+ "ZELLE": "ZELLE",+ "APP PAYOUT": "APP PAYOUT",+ "CREDIT CARD": "CREDIT CARD",+ "OTHER": "OTHER",+ "Deliverable": "Deliverable",+ "Opportunity": "Opportunity",+ "Expense": "Expense",+ "Ticket": "Ticket",+ "Yes": "Yes",+ "No": "No",+ "Full access": "Full access",+ "Read only": "Read only",+ "Overview": "Overview",+ "None": "None",+ "BANK_TRANSFER": "BANK_TRANSFER",+ "APP_PAYOUT": "APP_PAYOUT",+ "CREDIT_CARD": "CREDIT_CARD","GET": "GET","POST": "POST","PATCH": "PATCH","PUT": "PUT","DELETE": "DELETE","HEAD": "HEAD",- "None": "None",- "JSON": "JSON",- "Form Data": "Form Data",- "Raw": "Raw","Client Created": "Client Created","Client Updated": "Client Updated","Client Deleted": "Client Deleted",@@ -114,6 +487,16 @@"Opportunity Deleted": "Opportunity Deleted","Invoice Sent": "Invoice Sent","Payment Received": "Payment Received",+ "Invoice Voided": "Invoice Voided",+ "Invoice Written Off": "Invoice Written Off",+ "Agreement Sent": "Agreement Sent",+ "Agreement Viewed": "Agreement Viewed",+ "Agreement Signed": "Agreement Signed",+ "Ticket Created": "Ticket Created",+ "Ticket Updated": "Ticket Updated",+ "Ticket Closed": "Ticket Closed",+ "Ticket Comment Added": "Ticket Comment Added",+ "Ticket Deleted": "Ticket Deleted","Triggered when a new client is created.": "Triggered when a new client is created.","Triggered when an existing client is updated.": "Triggered when an existing client is updated.","Triggered when an existing client is deleted.": "Triggered when an existing client is deleted.",@@ -136,27 +519,38 @@"Triggered when an existing pipeline opportunity is deleted.": "Triggered when an existing pipeline opportunity is deleted.","Triggered when an invoice is sent.": "Triggered when an invoice is sent.","Triggered when a payment is received.": "Triggered when a payment is received.",+ "Triggered when a sent invoice is voided.": "Triggered when a sent invoice is voided.",+ "Triggered when an invoice is written off.": "Triggered when an invoice is written off.",+ "Triggered when an agreement is sent to a client.": "Triggered when an agreement is sent to a client.",+ "Triggered when a client views an agreement.": "Triggered when a client views an agreement.",+ "Triggered when an agreement is signed.": "Triggered when an agreement is signed.",+ "Triggered when a new support ticket is created.": "Triggered when a new support ticket is created.",+ "Triggered when a ticket is updated.": "Triggered when a ticket is updated.",+ "Triggered when a ticket is closed.": "Triggered when a ticket is closed.",+ "Triggered when a comment is added to a ticket.": "Triggered when a comment is added to a ticket.",+ "Triggered when a ticket is deleted.": "Triggered when a ticket is deleted.","Markdown": "Markdown",- "\n - Go to the **Workspace Settngs -> Connected Apps -> Integration** section.\n - Under **Custom Integration** , click on **Add Rest Hook**.\n - Click on **Integrations** section.\n - In the endpoint field, paste the following URL: \n ```text\n {{webhookUrl}}\n ```\n\n - Select the event as **`Client Created`** and click on **Save**.\n ": "\n - Go to the **Workspace Settngs -> Connected Apps -> Integration** section.\n - Under **Custom Integration** , click on **Add Rest Hook**.\n - Click on **Integrations** section.\n - In the endpoint field, paste the following URL: \n ```text\n {{webhookUrl}}\n ```\n\n - Select the event as **`Client Created`** and click on **Save**.\n ",- "\n - Go to the **Workspace Settngs -> Connected Apps -> Integration** section.\n - Under **Custom Integration** , click on **Add Rest Hook**.\n - Click on **Integrations** section.\n - In the endpoint field, paste the following URL: \n ```text\n {{webhookUrl}}\n ```\n\n - Select the event as **`Client Updated`** and click on **Save**.\n ": "\n - Go to the **Workspace Settngs -> Connected Apps -> Integration** section.\n - Under **Custom Integration** , click on **Add Rest Hook**.\n - Click on **Integrations** section.\n - In the endpoint field, paste the following URL: \n ```text\n {{webhookUrl}}\n ```\n\n - Select the event as **`Client Updated`** and click on **Save**.\n ",- "\n - Go to the **Workspace Settngs -> Connected Apps -> Integration** section.\n - Under **Custom Integration** , click on **Add Rest Hook**.\n - Click on **Integrations** section.\n - In the endpoint field, paste the following URL: \n ```text\n {{webhookUrl}}\n ```\n\n - Select the event as **`Client Deleted`** and click on **Save**.\n ": "\n - Go to the **Workspace Settngs -> Connected Apps -> Integration** section.\n - Under **Custom Integration** , click on **Add Rest Hook**.\n - Click on **Integrations** section.\n - In the endpoint field, paste the following URL: \n ```text\n {{webhookUrl}}\n ```\n\n - Select the event as **`Client Deleted`** and click on **Save**.\n ",- "\n - Go to the **Workspace Settngs -> Connected Apps -> Integration** section.\n - Under **Custom Integration** , click on **Add Rest Hook**.\n - Click on **Integrations** section.\n - In the endpoint field, paste the following URL: \n ```text\n {{webhookUrl}}\n ```\n\n - Select the event as **`Project Created`** and click on **Save**.\n ": "\n - Go to the **Workspace Settngs -> Connected Apps -> Integration** section.\n - Under **Custom Integration** , click on **Add Rest Hook**.\n - Click on **Integrations** section.\n - In the endpoint field, paste the following URL: \n ```text\n {{webhookUrl}}\n ```\n\n - Select the event as **`Project Created`** and click on **Save**.\n ",- "\n - Go to the **Workspace Settngs -> Connected Apps -> Integration** section.\n - Under **Custom Integration** , click on **Add Rest Hook**.\n - Click on **Integrations** section.\n - In the endpoint field, paste the following URL: \n ```text\n {{webhookUrl}}\n ```\n\n - Select the event as **`Project Updated`** and click on **Save**.\n ": "\n - Go to the **Workspace Settngs -> Connected Apps -> Integration** section.\n - Under **Custom Integration** , click on **Add Rest Hook**.\n - Click on **Integrations** section.\n - In the endpoint field, paste the following URL: \n ```text\n {{webhookUrl}}\n ```\n\n - Select the event as **`Project Updated`** and click on **Save**.\n ",- "\n - Go to the **Workspace Settngs -> Connected Apps -> Integration** section.\n - Under **Custom Integration** , click on **Add Rest Hook**.\n - Click on **Integrations** section.\n - In the endpoint field, paste the following URL: \n ```text\n {{webhookUrl}}\n ```\n\n - Select the event as **`Project Completed`** and click on **Save**.\n ": "\n - Go to the **Workspace Settngs -> Connected Apps -> Integration** section.\n - Under **Custom Integration** , click on **Add Rest Hook**.\n - Click on **Integrations** section.\n - In the endpoint field, paste the following URL: \n ```text\n {{webhookUrl}}\n ```\n\n - Select the event as **`Project Completed`** and click on **Save**.\n ",- "\n - Go to the **Workspace Settngs -> Connected Apps -> Integration** section.\n - Under **Custom Integration** , click on **Add Rest Hook**.\n - Click on **Integrations** section.\n - In the endpoint field, paste the following URL: \n ```text\n {{webhookUrl}}\n ```\n\n - Select the event as **`Task Created`** and click on **Save**.\n ": "\n - Go to the **Workspace Settngs -> Connected Apps -> Integration** section.\n - Under **Custom Integration** , click on **Add Rest Hook**.\n - Click on **Integrations** section.\n - In the endpoint field, paste the following URL: \n ```text\n {{webhookUrl}}\n ```\n\n - Select the event as **`Task Created`** and click on **Save**.\n ",- "\n - Go to the **Workspace Settngs -> Connected Apps -> Integration** section.\n - Under **Custom Integration** , click on **Add Rest Hook**.\n - Click on **Integrations** section.\n - In the endpoint field, paste the following URL: \n ```text\n {{webhookUrl}}\n ```\n\n - Select the event as **`Task Updated`** and click on **Save**.\n ": "\n - Go to the **Workspace Settngs -> Connected Apps -> Integration** section.\n - Under **Custom Integration** , click on **Add Rest Hook**.\n - Click on **Integrations** section.\n - In the endpoint field, paste the following URL: \n ```text\n {{webhookUrl}}\n ```\n\n - Select the event as **`Task Updated`** and click on **Save**.\n ",- "\n - Go to the **Workspace Settngs -> Connected Apps -> Integration** section.\n - Under **Custom Integration** , click on **Add Rest Hook**.\n - Click on **Integrations** section.\n - In the endpoint field, paste the following URL: \n ```text\n {{webhookUrl}}\n ```\n\n - Select the event as **`Task Deleted`** and click on **Save**.\n ": "\n - Go to the **Workspace Settngs -> Connected Apps -> Integration** section.\n - Under **Custom Integration** , click on **Add Rest Hook**.\n - Click on **Integrations** section.\n - In the endpoint field, paste the following URL: \n ```text\n {{webhookUrl}}\n ```\n\n - Select the event as **`Task Deleted`** and click on **Save**.\n ",- "\n - Go to the **Workspace Settngs -> Connected Apps -> Integration** section.\n - Under **Custom Integration** , click on **Add Rest Hook**.\n - Click on **Integrations** section.\n - In the endpoint field, paste the following URL: \n ```text\n {{webhookUrl}}\n ```\n\n - Select the event as **`Client Task Approval`** and click on **Save**.\n ": "\n - Go to the **Workspace Settngs -> Connected Apps -> Integration** section.\n - Under **Custom Integration** , click on **Add Rest Hook**.\n - Click on **Integrations** section.\n - In the endpoint field, paste the following URL: \n ```text\n {{webhookUrl}}\n ```\n\n - Select the event as **`Client Task Approval`** and click on **Save**.\n ",- "\n - Go to the **Workspace Settngs -> Connected Apps -> Integration** section.\n - Under **Custom Integration** , click on **Add Rest Hook**.\n - Click on **Integrations** section.\n - In the endpoint field, paste the following URL: \n ```text\n {{webhookUrl}}\n ```\n\n - Select the event as **`Form Submitted`** and click on **Save**.\n ": "\n - Go to the **Workspace Settngs -> Connected Apps -> Integration** section.\n - Under **Custom Integration** , click on **Add Rest Hook**.\n - Click on **Integrations** section.\n - In the endpoint field, paste the following URL: \n ```text\n {{webhookUrl}}\n ```\n\n - Select the event as **`Form Submitted`** and click on **Save**.\n ",- "\n - Go to the **Workspace Settngs -> Connected Apps -> Integration** section.\n - Under **Custom Integration** , click on **Add Rest Hook**.\n - Click on **Integrations** section.\n - In the endpoint field, paste the following URL: \n ```text\n {{webhookUrl}}\n ```\n\n - Select the event as **`Time Entry Created`** and click on **Save**.\n ": "\n - Go to the **Workspace Settngs -> Connected Apps -> Integration** section.\n - Under **Custom Integration** , click on **Add Rest Hook**.\n - Click on **Integrations** section.\n - In the endpoint field, paste the following URL: \n ```text\n {{webhookUrl}}\n ```\n\n - Select the event as **`Time Entry Created`** and click on **Save**.\n ",- "\n - Go to the **Workspace Settngs -> Connected Apps -> Integration** section.\n - Under **Custom Integration** , click on **Add Rest Hook**.\n - Click on **Integrations** section.\n - In the endpoint field, paste the following URL: \n ```text\n {{webhookUrl}}\n ```\n\n - Select the event as **`Time Entry Updated`** and click on **Save**.\n ": "\n - Go to the **Workspace Settngs -> Connected Apps -> Integration** section.\n - Under **Custom Integration** , click on **Add Rest Hook**.\n - Click on **Integrations** section.\n - In the endpoint field, paste the following URL: \n ```text\n {{webhookUrl}}\n ```\n\n - Select the event as **`Time Entry Updated`** and click on **Save**.\n ",- "\n - Go to the **Workspace Settngs -> Connected Apps -> Integration** section.\n - Under **Custom Integration** , click on **Add Rest Hook**.\n - Click on **Integrations** section.\n - In the endpoint field, paste the following URL: \n ```text\n {{webhookUrl}}\n ```\n\n - Select the event as **`Time Entry Deleted`** and click on **Save**.\n ": "\n - Go to the **Workspace Settngs -> Connected Apps -> Integration** section.\n - Under **Custom Integration** , click on **Add Rest Hook**.\n - Click on **Integrations** section.\n - In the endpoint field, paste the following URL: \n ```text\n {{webhookUrl}}\n ```\n\n - Select the event as **`Time Entry Deleted`** and click on **Save**.\n ",- "\n - Go to the **Workspace Settngs -> Connected Apps -> Integration** section.\n - Under **Custom Integration** , click on **Add Rest Hook**.\n - Click on **Integrations** section.\n - In the endpoint field, paste the following URL: \n ```text\n {{webhookUrl}}\n ```\n\n - Select the event as **`Meeting Scheduled`** and click on **Save**.\n ": "\n - Go to the **Workspace Settngs -> Connected Apps -> Integration** section.\n - Under **Custom Integration** , click on **Add Rest Hook**.\n - Click on **Integrations** section.\n - In the endpoint field, paste the following URL: \n ```text\n {{webhookUrl}}\n ```\n\n - Select the event as **`Meeting Scheduled`** and click on **Save**.\n ",- "\n - Go to the **Workspace Settngs -> Connected Apps -> Integration** section.\n - Under **Custom Integration** , click on **Add Rest Hook**.\n - Click on **Integrations** section.\n - In the endpoint field, paste the following URL: \n ```text\n {{webhookUrl}}\n ```\n\n - Select the event as **`Meeting Updated`** and click on **Save**.\n ": "\n - Go to the **Workspace Settngs -> Connected Apps -> Integration** section.\n - Under **Custom Integration** , click on **Add Rest Hook**.\n - Click on **Integrations** section.\n - In the endpoint field, paste the following URL: \n ```text\n {{webhookUrl}}\n ```\n\n - Select the event as **`Meeting Updated`** and click on **Save**.\n ",- "\n - Go to the **Workspace Settngs -> Connected Apps -> Integration** section.\n - Under **Custom Integration** , click on **Add Rest Hook**.\n - Click on **Integrations** section.\n - In the endpoint field, paste the following URL: \n ```text\n {{webhookUrl}}\n ```\n\n - Select the event as **`Meeting Cancelled`** and click on **Save**.\n ": "\n - Go to the **Workspace Settngs -> Connected Apps -> Integration** section.\n - Under **Custom Integration** , click on **Add Rest Hook**.\n - Click on **Integrations** section.\n - In the endpoint field, paste the following URL: \n ```text\n {{webhookUrl}}\n ```\n\n - Select the event as **`Meeting Cancelled`** and click on **Save**.\n ",- "\n - Go to the **Workspace Settngs -> Connected Apps -> Integration** section.\n - Under **Custom Integration** , click on **Add Rest Hook**.\n - Click on **Integrations** section.\n - In the endpoint field, paste the following URL: \n ```text\n {{webhookUrl}}\n ```\n\n - Select the event as **`Opportunity Created`** and click on **Save**.\n ": "\n - Go to the **Workspace Settngs -> Connected Apps -> Integration** section.\n - Under **Custom Integration** , click on **Add Rest Hook**.\n - Click on **Integrations** section.\n - In the endpoint field, paste the following URL: \n ```text\n {{webhookUrl}}\n ```\n\n - Select the event as **`Opportunity Created`** and click on **Save**.\n ",- "\n - Go to the **Workspace Settngs -> Connected Apps -> Integration** section.\n - Under **Custom Integration** , click on **Add Rest Hook**.\n - Click on **Integrations** section.\n - In the endpoint field, paste the following URL: \n ```text\n {{webhookUrl}}\n ```\n\n - Select the event as **`Opportunity Updated`** and click on **Save**.\n ": "\n - Go to the **Workspace Settngs -> Connected Apps -> Integration** section.\n - Under **Custom Integration** , click on **Add Rest Hook**.\n - Click on **Integrations** section.\n - In the endpoint field, paste the following URL: \n ```text\n {{webhookUrl}}\n ```\n\n - Select the event as **`Opportunity Updated`** and click on **Save**.\n ",- "\n - Go to the **Workspace Settngs -> Connected Apps -> Integration** section.\n - Under **Custom Integration** , click on **Add Rest Hook**.\n - Click on **Integrations** section.\n - In the endpoint field, paste the following URL: \n ```text\n {{webhookUrl}}\n ```\n\n - Select the event as **`Opportunity Deleted`** and click on **Save**.\n ": "\n - Go to the **Workspace Settngs -> Connected Apps -> Integration** section.\n - Under **Custom Integration** , click on **Add Rest Hook**.\n - Click on **Integrations** section.\n - In the endpoint field, paste the following URL: \n ```text\n {{webhookUrl}}\n ```\n\n - Select the event as **`Opportunity Deleted`** and click on **Save**.\n ",- "\n - Go to the **Workspace Settngs -> Connected Apps -> Integration** section.\n - Under **Custom Integration** , click on **Add Rest Hook**.\n - Click on **Integrations** section.\n - In the endpoint field, paste the following URL: \n ```text\n {{webhookUrl}}\n ```\n\n - Select the event as **`Invoice Sent`** and click on **Save**.\n ": "\n - Go to the **Workspace Settngs -> Connected Apps -> Integration** section.\n - Under **Custom Integration** , click on **Add Rest Hook**.\n - Click on **Integrations** section.\n - In the endpoint field, paste the following URL: \n ```text\n {{webhookUrl}}\n ```\n\n - Select the event as **`Invoice Sent`** and click on **Save**.\n ",- "\n - Go to the **Workspace Settngs -> Connected Apps -> Integration** section.\n - Under **Custom Integration** , click on **Add Rest Hook**.\n - Click on **Integrations** section.\n - In the endpoint field, paste the following URL: \n ```text\n {{webhookUrl}}\n ```\n\n - Select the event as **`Payment Received`** and click on **Save**.\n ": "\n - Go to the **Workspace Settngs -> Connected Apps -> Integration** section.\n - Under **Custom Integration** , click on **Add Rest Hook**.\n - Click on **Integrations** section.\n - In the endpoint field, paste the following URL: \n ```text\n {{webhookUrl}}\n ```\n\n - Select the event as **`Payment Received`** and click on **Save**.\n "+ "\n - In Moxie, go to **Workspace Settings > Connected Apps > Integrations**.\n - Under **Custom Integration**, click **Add Rest Hook**.\n - In the endpoint field, paste the following URL:\n ```text\n {{webhookUrl}}\n ```\n\n - Select the event **`Client Created`** and click **Save**.\n\n Deliveries for any other event type are ignored, and a delivery repeated within 15 minutes runs the flow only once.\n ": "\n - In Moxie, go to **Workspace Settings > Connected Apps > Integrations**.\n - Under **Custom Integration**, click **Add Rest Hook**.\n - In the endpoint field, paste the following URL:\n ```text\n {{webhookUrl}}\n ```\n\n - Select the event **`Client Created`** and click **Save**.\n\n Deliveries for any other event type are ignored, and a delivery repeated within 15 minutes runs the flow only once.\n ",+ "\n - In Moxie, go to **Workspace Settings > Connected Apps > Integrations**.\n - Under **Custom Integration**, click **Add Rest Hook**.\n - In the endpoint field, paste the following URL:\n ```text\n {{webhookUrl}}\n ```\n\n - Select the event **`Client Updated`** and click **Save**.\n\n Deliveries for any other event type are ignored, and a delivery repeated within 15 minutes runs the flow only once.\n ": "\n - In Moxie, go to **Workspace Settings > Connected Apps > Integrations**.\n - Under **Custom Integration**, click **Add Rest Hook**.\n - In the endpoint field, paste the following URL:\n ```text\n {{webhookUrl}}\n ```\n\n - Select the event **`Client Updated`** and click **Save**.\n\n Deliveries for any other event type are ignored, and a delivery repeated within 15 minutes runs the flow only once.\n ",+ "\n - In Moxie, go to **Workspace Settings > Connected Apps > Integrations**.\n - Under **Custom Integration**, click **Add Rest Hook**.\n - In the endpoint field, paste the following URL:\n ```text\n {{webhookUrl}}\n ```\n\n - Select the event **`Client Deleted`** and click **Save**.\n\n Deliveries for any other event type are ignored, and a delivery repeated within 15 minutes runs the flow only once.\n ": "\n - In Moxie, go to **Workspace Settings > Connected Apps > Integrations**.\n - Under **Custom Integration**, click **Add Rest Hook**.\n - In the endpoint field, paste the following URL:\n ```text\n {{webhookUrl}}\n ```\n\n - Select the event **`Client Deleted`** and click **Save**.\n\n Deliveries for any other event type are ignored, and a delivery repeated within 15 minutes runs the flow only once.\n ",+ "\n - In Moxie, go to **Workspace Settings > Connected Apps > Integrations**.\n - Under **Custom Integration**, click **Add Rest Hook**.\n - In the endpoint field, paste the following URL:\n ```text\n {{webhookUrl}}\n ```\n\n - Select the event **`Project Created`** and click **Save**.\n\n Deliveries for any other event type are ignored, and a delivery repeated within 15 minutes runs the flow only once.\n ": "\n - In Moxie, go to **Workspace Settings > Connected Apps > Integrations**.\n - Under **Custom Integration**, click **Add Rest Hook**.\n - In the endpoint field, paste the following URL:\n ```text\n {{webhookUrl}}\n ```\n\n - Select the event **`Project Created`** and click **Save**.\n\n Deliveries for any other event type are ignored, and a delivery repeated within 15 minutes runs the flow only once.\n ",+ "\n - In Moxie, go to **Workspace Settings > Connected Apps > Integrations**.\n - Under **Custom Integration**, click **Add Rest Hook**.\n - In the endpoint field, paste the following URL:\n ```text\n {{webhookUrl}}\n ```\n\n - Select the event **`Project Updated`** and click **Save**.\n\n Deliveries for any other event type are ignored, and a delivery repeated within 15 minutes runs the flow only once.\n ": "\n - In Moxie, go to **Workspace Settings > Connected Apps > Integrations**.\n - Under **Custom Integration**, click **Add Rest Hook**.\n - In the endpoint field, paste the following URL:\n ```text\n {{webhookUrl}}\n ```\n\n - Select the event **`Project Updated`** and click **Save**.\n\n Deliveries for any other event type are ignored, and a delivery repeated within 15 minutes runs the flow only once.\n ",+ "\n - In Moxie, go to **Workspace Settings > Connected Apps > Integrations**.\n - Under **Custom Integration**, click **Add Rest Hook**.\n - In the endpoint field, paste the following URL:\n ```text\n {{webhookUrl}}\n ```\n\n - Select the event **`Project Completed`** and click **Save**.\n\n Deliveries for any other event type are ignored, and a delivery repeated within 15 minutes runs the flow only once.\n ": "\n - In Moxie, go to **Workspace Settings > Connected Apps > Integrations**.\n - Under **Custom Integration**, click **Add Rest Hook**.\n - In the endpoint field, paste the following URL:\n ```text\n {{webhookUrl}}\n ```\n\n - Select the event **`Project Completed`** and click **Save**.\n\n Deliveries for any other event type are ignored, and a delivery repeated within 15 minutes runs the flow only once.\n ",+ "\n - In Moxie, go to **Workspace Settings > Connected Apps > Integrations**.\n - Under **Custom Integration**, click **Add Rest Hook**.\n - In the endpoint field, paste the following URL:\n ```text\n {{webhookUrl}}\n ```\n\n - Select the event **`Task Created`** and click **Save**.\n\n Deliveries for any other event type are ignored, and a delivery repeated within 15 minutes runs the flow only once.\n ": "\n - In Moxie, go to **Workspace Settings > Connected Apps > Integrations**.\n - Under **Custom Integration**, click **Add Rest Hook**.\n - In the endpoint field, paste the following URL:\n ```text\n {{webhookUrl}}\n ```\n\n - Select the event **`Task Created`** and click **Save**.\n\n Deliveries for any other event type are ignored, and a delivery repeated within 15 minutes runs the flow only once.\n ",+ "\n - In Moxie, go to **Workspace Settings > Connected Apps > Integrations**.\n - Under **Custom Integration**, click **Add Rest Hook**.\n - In the endpoint field, paste the following URL:\n ```text\n {{webhookUrl}}\n ```\n\n - Select the event **`Task Updated`** and click **Save**.\n\n Deliveries for any other event type are ignored, and a delivery repeated within 15 minutes runs the flow only once.\n ": "\n - In Moxie, go to **Workspace Settings > Connected Apps > Integrations**.\n - Under **Custom Integration**, click **Add Rest Hook**.\n - In the endpoint field, paste the following URL:\n ```text\n {{webhookUrl}}\n ```\n\n - Select the event **`Task Updated`** and click **Save**.\n\n Deliveries for any other event type are ignored, and a delivery repeated within 15 minutes runs the flow only once.\n ",+ "\n - In Moxie, go to **Workspace Settings > Connected Apps > Integrations**.\n - Under **Custom Integration**, click **Add Rest Hook**.\n - In the endpoint field, paste the following URL:\n ```text\n {{webhookUrl}}\n ```\n\n - Select the event **`Task Deleted`** and click **Save**.\n\n Deliveries for any other event type are ignored, and a delivery repeated within 15 minutes runs the flow only once.\n ": "\n - In Moxie, go to **Workspace Settings > Connected Apps > Integrations**.\n - Under **Custom Integration**, click **Add Rest Hook**.\n - In the endpoint field, paste the following URL:\n ```text\n {{webhookUrl}}\n ```\n\n - Select the event **`Task Deleted`** and click **Save**.\n\n Deliveries for any other event type are ignored, and a delivery repeated within 15 minutes runs the flow only once.\n ",+ "\n - In Moxie, go to **Workspace Settings > Connected Apps > Integrations**.\n - Under **Custom Integration**, click **Add Rest Hook**.\n - In the endpoint field, paste the following URL:\n ```text\n {{webhookUrl}}\n ```\n\n - Select the event **`Client Task Approval`** and click **Save**.\n\n Deliveries for any other event type are ignored, and a delivery repeated within 15 minutes runs the flow only once.\n ": "\n - In Moxie, go to **Workspace Settings > Connected Apps > Integrations**.\n - Under **Custom Integration**, click **Add Rest Hook**.\n - In the endpoint field, paste the following URL:\n ```text\n {{webhookUrl}}\n ```\n\n - Select the event **`Client Task Approval`** and click **Save**.\n\n Deliveries for any other event type are ignored, and a delivery repeated within 15 minutes runs the flow only once.\n ",+ "\n - In Moxie, go to **Workspace Settings > Connected Apps > Integrations**.\n - Under **Custom Integration**, click **Add Rest Hook**.\n - In the endpoint field, paste the following URL:\n ```text\n {{webhookUrl}}\n ```\n\n - Select the event **`Form Submitted`** and click **Save**.\n\n Deliveries for any other event type are ignored, and a delivery repeated within 15 minutes runs the flow only once.\n ": "\n - In Moxie, go to **Workspace Settings > Connected Apps > Integrations**.\n - Under **Custom Integration**, click **Add Rest Hook**.\n - In the endpoint field, paste the following URL:\n ```text\n {{webhookUrl}}\n ```\n\n - Select the event **`Form Submitted`** and click **Save**.\n\n Deliveries for any other event type are ignored, and a delivery repeated within 15 minutes runs the flow only once.\n ",+ "\n - In Moxie, go to **Workspace Settings > Connected Apps > Integrations**.\n - Under **Custom Integration**, click **Add Rest Hook**.\n - In the endpoint field, paste the following URL:\n ```text\n {{webhookUrl}}\n ```\n\n - Select the event **`Time Entry Created`** and click **Save**.\n\n Deliveries for any other event type are ignored, and a delivery repeated within 15 minutes runs the flow only once.\n ": "\n - In Moxie, go to **Workspace Settings > Connected Apps > Integrations**.\n - Under **Custom Integration**, click **Add Rest Hook**.\n - In the endpoint field, paste the following URL:\n ```text\n {{webhookUrl}}\n ```\n\n - Select the event **`Time Entry Created`** and click **Save**.\n\n Deliveries for any other event type are ignored, and a delivery repeated within 15 minutes runs the flow only once.\n ",+ "\n - In Moxie, go to **Workspace Settings > Connected Apps > Integrations**.\n - Under **Custom Integration**, click **Add Rest Hook**.\n - In the endpoint field, paste the following URL:\n ```text\n {{webhookUrl}}\n ```\n\n - Select the event **`Time Entry Updated`** and click **Save**.\n\n Deliveries for any other event type are ignored, and a delivery repeated within 15 minutes runs the flow only once.\n ": "\n - In Moxie, go to **Workspace Settings > Connected Apps > Integrations**.\n - Under **Custom Integration**, click **Add Rest Hook**.\n - In the endpoint field, paste the following URL:\n ```text\n {{webhookUrl}}\n ```\n\n - Select the event **`Time Entry Updated`** and click **Save**.\n\n Deliveries for any other event type are ignored, and a delivery repeated within 15 minutes runs the flow only once.\n ",+ "\n - In Moxie, go to **Workspace Settings > Connected Apps > Integrations**.\n - Under **Custom Integration**, click **Add Rest Hook**.\n - In the endpoint field, paste the following URL:\n ```text\n {{webhookUrl}}\n ```\n\n - Select the event **`Time Entry Deleted`** and click **Save**.\n\n Deliveries for any other event type are ignored, and a delivery repeated within 15 minutes runs the flow only once.\n ": "\n - In Moxie, go to **Workspace Settings > Connected Apps > Integrations**.\n - Under **Custom Integration**, click **Add Rest Hook**.\n - In the endpoint field, paste the following URL:\n ```text\n {{webhookUrl}}\n ```\n\n - Select the event **`Time Entry Deleted`** and click **Save**.\n\n Deliveries for any other event type are ignored, and a delivery repeated within 15 minutes runs the flow only once.\n ",+ "\n - In Moxie, go to **Workspace Settings > Connected Apps > Integrations**.\n - Under **Custom Integration**, click **Add Rest Hook**.\n - In the endpoint field, paste the following URL:\n ```text\n {{webhookUrl}}\n ```\n\n - Select the event **`Meeting Scheduled`** and click **Save**.\n\n Deliveries for any other event type are ignored, and a delivery repeated within 15 minutes runs the flow only once.\n ": "\n - In Moxie, go to **Workspace Settings > Connected Apps > Integrations**.\n - Under **Custom Integration**, click **Add Rest Hook**.\n - In the endpoint field, paste the following URL:\n ```text\n {{webhookUrl}}\n ```\n\n - Select the event **`Meeting Scheduled`** and click **Save**.\n\n Deliveries for any other event type are ignored, and a delivery repeated within 15 minutes runs the flow only once.\n ",+ "\n - In Moxie, go to **Workspace Settings > Connected Apps > Integrations**.\n - Under **Custom Integration**, click **Add Rest Hook**.\n - In the endpoint field, paste the following URL:\n ```text\n {{webhookUrl}}\n ```\n\n - Select the event **`Meeting Updated`** and click **Save**.\n\n Deliveries for any other event type are ignored, and a delivery repeated within 15 minutes runs the flow only once.\n ": "\n - In Moxie, go to **Workspace Settings > Connected Apps > Integrations**.\n - Under **Custom Integration**, click **Add Rest Hook**.\n - In the endpoint field, paste the following URL:\n ```text\n {{webhookUrl}}\n ```\n\n - Select the event **`Meeting Updated`** and click **Save**.\n\n Deliveries for any other event type are ignored, and a delivery repeated within 15 minutes runs the flow only once.\n ",+ "\n - In Moxie, go to **Workspace Settings > Connected Apps > Integrations**.\n - Under **Custom Integration**, click **Add Rest Hook**.\n - In the endpoint field, paste the following URL:\n ```text\n {{webhookUrl}}\n ```\n\n - Select the event **`Meeting Cancelled`** and click **Save**.\n\n Deliveries for any other event type are ignored, and a delivery repeated within 15 minutes runs the flow only once.\n ": "\n - In Moxie, go to **Workspace Settings > Connected Apps > Integrations**.\n - Under **Custom Integration**, click **Add Rest Hook**.\n - In the endpoint field, paste the following URL:\n ```text\n {{webhookUrl}}\n ```\n\n - Select the event **`Meeting Cancelled`** and click **Save**.\n\n Deliveries for any other event type are ignored, and a delivery repeated within 15 minutes runs the flow only once.\n ",+ "\n - In Moxie, go to **Workspace Settings > Connected Apps > Integrations**.\n - Under **Custom Integration**, click **Add Rest Hook**.\n - In the endpoint field, paste the following URL:\n ```text\n {{webhookUrl}}\n ```\n\n - Select the event **`Opportunity Created`** and click **Save**.\n\n Deliveries for any other event type are ignored, and a delivery repeated within 15 minutes runs the flow only once.\n ": "\n - In Moxie, go to **Workspace Settings > Connected Apps > Integrations**.\n - Under **Custom Integration**, click **Add Rest Hook**.\n - In the endpoint field, paste the following URL:\n ```text\n {{webhookUrl}}\n ```\n\n - Select the event **`Opportunity Created`** and click **Save**.\n\n Deliveries for any other event type are ignored, and a delivery repeated within 15 minutes runs the flow only once.\n ",+ "\n - In Moxie, go to **Workspace Settings > Connected Apps > Integrations**.\n - Under **Custom Integration**, click **Add Rest Hook**.\n - In the endpoint field, paste the following URL:\n ```text\n {{webhookUrl}}\n ```\n\n - Select the event **`Opportunity Updated`** and click **Save**.\n\n Deliveries for any other event type are ignored, and a delivery repeated within 15 minutes runs the flow only once.\n ": "\n - In Moxie, go to **Workspace Settings > Connected Apps > Integrations**.\n - Under **Custom Integration**, click **Add Rest Hook**.\n - In the endpoint field, paste the following URL:\n ```text\n {{webhookUrl}}\n ```\n\n - Select the event **`Opportunity Updated`** and click **Save**.\n\n Deliveries for any other event type are ignored, and a delivery repeated within 15 minutes runs the flow only once.\n ",+ "\n - In Moxie, go to **Workspace Settings > Connected Apps > Integrations**.\n - Under **Custom Integration**, click **Add Rest Hook**.\n - In the endpoint field, paste the following URL:\n ```text\n {{webhookUrl}}\n ```\n\n - Select the event **`Opportunity Deleted`** and click **Save**.\n\n Deliveries for any other event type are ignored, and a delivery repeated within 15 minutes runs the flow only once.\n ": "\n - In Moxie, go to **Workspace Settings > Connected Apps > Integrations**.\n - Under **Custom Integration**, click **Add Rest Hook**.\n - In the endpoint field, paste the following URL:\n ```text\n {{webhookUrl}}\n ```\n\n - Select the event **`Opportunity Deleted`** and click **Save**.\n\n Deliveries for any other event type are ignored, and a delivery repeated within 15 minutes runs the flow only once.\n ",+ "\n - In Moxie, go to **Workspace Settings > Connected Apps > Integrations**.\n - Under **Custom Integration**, click **Add Rest Hook**.\n - In the endpoint field, paste the following URL:\n ```text\n {{webhookUrl}}\n ```\n\n - Select the event **`Invoice Sent`** and click **Save**.\n\n Deliveries for any other event type are ignored, and a delivery repeated within 15 minutes runs the flow only once.\n ": "\n - In Moxie, go to **Workspace Settings > Connected Apps > Integrations**.\n - Under **Custom Integration**, click **Add Rest Hook**.\n - In the endpoint field, paste the following URL:\n ```text\n {{webhookUrl}}\n ```\n\n - Select the event **`Invoice Sent`** and click **Save**.\n\n Deliveries for any other event type are ignored, and a delivery repeated within 15 minutes runs the flow only once.\n ",+ "\n - In Moxie, go to **Workspace Settings > Connected Apps > Integrations**.\n - Under **Custom Integration**, click **Add Rest Hook**.\n - In the endpoint field, paste the following URL:\n ```text\n {{webhookUrl}}\n ```\n\n - Select the event **`Payment Received`** and click **Save**.\n\n Deliveries for any other event type are ignored, and a delivery repeated within 15 minutes runs the flow only once.\n ": "\n - In Moxie, go to **Workspace Settings > Connected Apps > Integrations**.\n - Under **Custom Integration**, click **Add Rest Hook**.\n - In the endpoint field, paste the following URL:\n ```text\n {{webhookUrl}}\n ```\n\n - Select the event **`Payment Received`** and click **Save**.\n\n Deliveries for any other event type are ignored, and a delivery repeated within 15 minutes runs the flow only once.\n ",+ "This trigger registers its webhook in Moxie automatically when the flow is published, and removes it when the flow is turned off. There is nothing to set up in Moxie.": "This trigger registers its webhook in Moxie automatically when the flow is published, and removes it when the flow is turned off. There is nothing to set up in Moxie."}\ No newline at end of filediff --git a/packages/pieces/community/moxie-crm/src/index.ts b/packages/pieces/community/moxie-crm/src/index.tsindex 84ada198ee1..b560e7b526c 100644--- a/packages/pieces/community/moxie-crm/src/index.ts+++ b/packages/pieces/community/moxie-crm/src/index.ts@@ -1,31 +1,74 @@import { createCustomApiCallAction } from '@activepieces/pieces-common';-import {- createPiece,- PieceAuth,- Property,-} from '@activepieces/pieces-framework';-import { PieceCategory } from '@activepieces/pieces-framework';+import { PieceCategory, createPiece } from '@activepieces/pieces-framework';import { moxieCreateClientAction } from './lib/actions/create-client';import { moxieCreateContactAction } from './lib/actions/create-contact';-import { moxieCreateProjectAction } from './lib/actions/create-project';import { moxieCreateTaskAction } from './lib/actions/create-task';+import { moxieCreateProjectAction } from './lib/actions/create-project';import { moxieListClientsAction } from './lib/actions/list-clients';-import { moxieListInvoiceTemplatesAction } from './lib/actions/list-invoice-templates';-import { moxieListPipelineStagesAction } from './lib/actions/list-pipeline-stages';-import { moxieListWorkspaceUsersAction } from './lib/actions/list-workspace-users';import { moxieSearchClientsAction } from './lib/actions/search-clients';import { moxieSearchContactsAction } from './lib/actions/search-contacts';import { moxieSearchProjectsAction } from './lib/actions/search-projects';-import { moxieCRMTriggers } from './lib/triggers';+import { moxieListPipelineStagesAction } from './lib/actions/list-pipeline-stages';+import { moxieListWorkspaceUsersAction } from './lib/actions/list-workspace-users';+import { moxieListInvoiceTemplatesAction } from './lib/actions/list-invoice-templates';+import { moxieAddTicketCommentAction } from './lib/actions/add-ticket-comment';+import { moxieApplyPaymentAction } from './lib/actions/apply-payment';+import { moxieApproveTaskAction } from './lib/actions/approve-task';+import { moxieAttachFileFromUrlAction } from './lib/actions/attach-file-from-url';+import { moxieCreateExpenseAction } from './lib/actions/create-expense';+import { moxieCreateFormSubmissionAction } from './lib/actions/create-form-submission';+import { moxieCreateInvoiceAction } from './lib/actions/create-invoice';+import { moxieCreateOpportunityAction } from './lib/actions/create-opportunity';+import { moxieCreateOrUpdateCalendarEventAction } from './lib/actions/create-or-update-calendar-event';+import { moxieCreateTicketAction } from './lib/actions/create-ticket';+import { moxieCreateTimeEntryAction } from './lib/actions/create-time-entry';+import { moxieDeleteCalendarEventAction } from './lib/actions/delete-calendar-event';+import { moxieGetEmailTemplateAction } from './lib/actions/get-email-template';+import { moxieGetWorkspaceAccountAction } from './lib/actions/get-workspace-account';+import { moxieListEmailTemplatesAction } from './lib/actions/list-email-templates';+import { moxieListFormNamesAction } from './lib/actions/list-form-names';+import { moxieListProjectTypesAction } from './lib/actions/list-project-types';+import { moxieListTaskStagesAction } from './lib/actions/list-task-stages';+import { moxieListTasksAction } from './lib/actions/list-tasks';+import { moxieListTicketsAction } from './lib/actions/list-tickets';+import { moxieListVendorsAction } from './lib/actions/list-vendors';+import { moxieSearchAgreementsAction } from './lib/actions/search-agreements';+import { moxieSearchPayableInvoicesAction } from './lib/actions/search-payable-invoices';+import { moxieSearchTasksAction } from './lib/actions/search-tasks';+import { moxieSearchTicketsAction } from './lib/actions/search-tickets';+import { moxieUpdateClientAction } from './lib/actions/update-client';+import { moxieUpdateContactAction } from './lib/actions/update-contact';+import { moxieUpdateExpenseAction } from './lib/actions/update-expense';+import { moxieUpdateOpportunityAction } from './lib/actions/update-opportunity';+import { moxieUpdateProjectAction } from './lib/actions/update-project';+import { moxieUpdateTaskAction } from './lib/actions/update-task';+import { moxieUpdateTicketStatusAction } from './lib/actions/update-ticket-status';+import { moxieUploadAttachmentAction } from './lib/actions/upload-attachment';+import { moxieClientCreateAction } from './lib/actions/ai/client-create';+import { moxieClientUpdateAction } from './lib/actions/ai/client-update';+import { moxieContactCreateAction } from './lib/actions/ai/contact-create';+import { moxieContactUpdateAction } from './lib/actions/ai/contact-update';+import { moxieExpenseCreateAction } from './lib/actions/ai/expense-create';+import { moxieInvoiceCreateAction } from './lib/actions/ai/invoice-create';+import { moxieOpportunityCreateAction } from './lib/actions/ai/opportunity-create';+import { moxieOpportunityUpdateAction } from './lib/actions/ai/opportunity-update';+import { moxiePaymentCreateAction } from './lib/actions/ai/payment-create';+import { moxieProjectCreateAction } from './lib/actions/ai/project-create';+import { moxieProjectUpdateAction } from './lib/actions/ai/project-update';+import { moxieTaskCreateAction } from './lib/actions/ai/task-create';+import { moxieTaskUpdateAction } from './lib/actions/ai/task-update';+import { moxieTimeEntryCreateAction } from './lib/actions/ai/time-entry-create';import { moxieCRMAuth } from './lib/auth';+import { assertMoxieRequestUrl, normalizeBaseUrl } from './lib/common/client';+import { moxieCRMTriggers } from './lib/triggers';+export const moxieCrm = createPiece({displayName: 'Moxie',description: 'CRM build for the freelancers.',-auth: moxieCRMAuth,- minimumSupportedRelease: '0.30.0',+ minimumSupportedRelease: '0.88.2',logoUrl: 'https://cdn.activepieces.com/pieces/moxie-crm.png',- authors: ["kishanprmr","MoShizzle","abuaboud"],+ authors: ['kishanprmr', 'MoShizzle', 'abuaboud'],categories: [PieceCategory.SALES_AND_CRM],actions: [moxieCreateClientAction,@@ -39,13 +82,69 @@ export const moxieCrm = createPiece({moxieListPipelineStagesAction,moxieListWorkspaceUsersAction,moxieListInvoiceTemplatesAction,+ moxieAddTicketCommentAction,+ moxieApplyPaymentAction,+ moxieApproveTaskAction,+ moxieAttachFileFromUrlAction,+ moxieCreateExpenseAction,+ moxieCreateFormSubmissionAction,+ moxieCreateInvoiceAction,+ moxieCreateOpportunityAction,+ moxieCreateOrUpdateCalendarEventAction,+ moxieCreateTicketAction,+ moxieCreateTimeEntryAction,+ moxieDeleteCalendarEventAction,+ moxieGetEmailTemplateAction,+ moxieGetWorkspaceAccountAction,+ moxieListEmailTemplatesAction,+ moxieListFormNamesAction,+ moxieListProjectTypesAction,+ moxieListTaskStagesAction,+ moxieListTasksAction,+ moxieListTicketsAction,+ moxieListVendorsAction,+ moxieSearchAgreementsAction,+ moxieSearchPayableInvoicesAction,+ moxieSearchTasksAction,+ moxieSearchTicketsAction,+ moxieUpdateClientAction,+ moxieUpdateContactAction,+ moxieUpdateExpenseAction,+ moxieUpdateOpportunityAction,+ moxieUpdateProjectAction,+ moxieUpdateTaskAction,+ moxieUpdateTicketStatusAction,+ moxieUploadAttachmentAction,+ moxieClientCreateAction,+ moxieClientUpdateAction,+ moxieContactCreateAction,+ moxieContactUpdateAction,+ moxieExpenseCreateAction,+ moxieInvoiceCreateAction,+ moxieOpportunityCreateAction,+ moxieOpportunityUpdateAction,+ moxiePaymentCreateAction,+ moxieProjectCreateAction,+ moxieProjectUpdateAction,+ moxieTaskCreateAction,+ moxieTaskUpdateAction,+ moxieTimeEntryCreateAction,createCustomApiCallAction({- baseUrl: (auth) => (auth?.props.baseUrl ?? ''),+ baseUrl: (auth) => customApiBaseUrl({ baseUrl: auth?.props.baseUrl }),auth: moxieCRMAuth,- authMapping: async (auth) => ({- 'X-API-KEY': (auth.props.apiKey),- }),+ authMapping: async (auth, propsValue) => {+ assertMoxieRequestUrl({ baseUrl: auth.props.baseUrl, url: propsValue['url']?.['url'] });+ return { 'X-API-KEY': auth.props.apiKey.trim() };+ },}),],triggers: moxieCRMTriggers,});++function customApiBaseUrl({ baseUrl }: { baseUrl: string | undefined }): string {+ try {+ return normalizeBaseUrl({ baseUrl });+ } catch {+ return '';+ }+}diff --git a/packages/pieces/community/moxie-crm/src/lib/actions/add-ticket-comment.ts b/packages/pieces/community/moxie-crm/src/lib/actions/add-ticket-comment.tsnew file mode 100644index 00000000000..a79b1b81daf--- /dev/null+++ b/packages/pieces/community/moxie-crm/src/lib/actions/add-ticket-comment.ts@@ -0,0 +1,68 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { Property, createAction } from '@activepieces/pieces-framework';+import { moxieCRMAuth } from '../auth';+import { credentialsOf } from '../common';+import { moxieRequest } from '../common/client';+import { moxieInput } from '../common/props';+import { moxieActionOutputSchemas } from '../output-schemas';++export const moxieAddTicketCommentAction = createAction({+ auth: moxieCRMAuth,+ name: 'moxie_add_ticket_comment',+ classification: 'WRITE',+ displayName: 'Add Ticket Comment',+ description: 'Add a comment to a ticket.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Adds a comment to a Moxie ticket identified by its ticket number, as public reply or private internal note. Needs the email of a workspace user or client contact as author, and only works on tickets that belong to a client. Use to post an update or answer on an existing ticket; ticket numbers come from Search Tickets, List Tickets or Create Ticket. Not idempotent: each call adds another comment.',+ idempotent: false,+ },+ outputSchema: moxieActionOutputSchemas.ticketWrapper,+ props: {+ ticketNumber: Property.Number({+ displayName: 'Ticket Number',+ description: 'The ticket number (not the id), from Search Tickets or Create Ticket.',+ required: true,+ }),+ comment: Property.LongText({+ displayName: 'Comment',+ required: true,+ }),+ userEmail: Property.ShortText({+ displayName: 'Author Email',+ description: 'Email of the workspace user or client contact posting the comment.',+ required: true,+ }),+ privateComment: Property.Checkbox({+ displayName: 'Private Note',+ description: 'On keeps the comment internal; off (default) shows it to the client.',+ required: false,+ defaultValue: false,+ }),+ },+ async run({ auth, propsValue }) {+ const ticketNumber = moxieInput.integer({ value: propsValue.ticketNumber, field: 'Ticket Number', min: 1 });+ if (ticketNumber === undefined) {+ throw new Error('Ticket Number is required.');+ }+ const userEmail = moxieInput.email({ value: propsValue.userEmail, field: 'Author Email' });+ if (userEmail === undefined) {+ throw new Error('Author Email is required.');+ }+ return moxieRequest<unknown>({+ credentials: credentialsOf({ auth }),+ method: HttpMethod.POST,+ path: '/action/tickets/comments/create',+ body: moxieInput.compact({+ values: {+ ticketNumber,+ comment: moxieInput.requiredText({ value: propsValue.comment, field: 'Comment' }),+ userEmail,+ privateComment: moxieInput.triState({ value: propsValue.privateComment, field: 'Private Note' }) === true ? true : undefined,+ },+ }),+ notFoundMessage: `No ticket number ${ticketNumber} with a client in this Moxie workspace. Comments can only be added to tickets that belong to a client.`,+ });+ },+});diff --git a/packages/pieces/community/moxie-crm/src/lib/actions/ai/client-create.ts b/packages/pieces/community/moxie-crm/src/lib/actions/ai/client-create.tsnew file mode 100644index 00000000000..2d1650e9c48--- /dev/null+++ b/packages/pieces/community/moxie-crm/src/lib/actions/ai/client-create.ts@@ -0,0 +1,28 @@+import { createAction } from '@activepieces/pieces-framework';+import { moxieCRMAuth } from '../../auth';+import { credentialsOf } from '../../common';+import { moxieFields } from '../../common/fields';+import { moxieOperations } from '../../common/operations';+import { moxieProps } from '../../common/props';+import { moxieActionOutputSchemas } from '../../output-schemas';++export const moxieClientCreateAction = createAction({+ auth: moxieCRMAuth,+ name: 'moxie_client_create',+ classification: 'WRITE',+ displayName: 'Create Client',+ description: 'Creates a client or prospect in Moxie.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Creates a client or prospect record in Moxie with address, billing and rate details; only Name is required and empty fields are not sent. Use when onboarding a new account, after Search Clients confirms it does not exist yet. Not idempotent: each call creates a separate client, even with the same name.',+ idempotent: false,+ },+ outputSchema: moxieActionOutputSchemas.client,+ props: {+ ...moxieProps.fromSpecs({ specs: moxieFields.clientCreate, audience: 'ai' }),+ },+ async run({ auth, propsValue }) {+ return moxieOperations.createClient({ credentials: credentialsOf({ auth }), values: propsValue });+ },+});diff --git a/packages/pieces/community/moxie-crm/src/lib/actions/ai/client-update.ts b/packages/pieces/community/moxie-crm/src/lib/actions/ai/client-update.tsnew file mode 100644index 00000000000..58cb1d354a9--- /dev/null+++ b/packages/pieces/community/moxie-crm/src/lib/actions/ai/client-update.ts@@ -0,0 +1,34 @@+import { Property, createAction } from '@activepieces/pieces-framework';+import { moxieCRMAuth } from '../../auth';+import { credentialsOf } from '../../common';+import { moxieFields } from '../../common/fields';+import { moxieOperations } from '../../common/operations';+import { moxieProps } from '../../common/props';+import { moxieActionOutputSchemas } from '../../output-schemas';++export const moxieClientUpdateAction = createAction({+ auth: moxieCRMAuth,+ name: 'moxie_client_update',+ classification: 'WRITE',+ displayName: 'Update Client',+ description: 'Updates fields on an existing Moxie client.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Updates an existing Moxie client by id: only the fields you pass change, and Clear Fields blanks text fields. Use to correct address, billing, rate or archive state once you have the client id from Search Clients or List Clients. Idempotent: repeating the same update leaves the client unchanged.',+ idempotent: true,+ },+ outputSchema: moxieActionOutputSchemas.client,+ props: {+ clientId: Property.ShortText({+ displayName: 'Client ID',+ description: 'Id of the client to update, from Search Clients, List Clients or a client trigger.',+ required: true,+ }),+ ...moxieProps.fromSpecs({ specs: moxieFields.clientUpdate, audience: 'ai' }),+ clearFields: moxieProps.clearFields({ specs: moxieFields.clientUpdate }),+ },+ async run({ auth, propsValue }) {+ return moxieOperations.updateClient({ credentials: credentialsOf({ auth }), values: propsValue });+ },+});diff --git a/packages/pieces/community/moxie-crm/src/lib/actions/ai/contact-create.ts b/packages/pieces/community/moxie-crm/src/lib/actions/ai/contact-create.tsnew file mode 100644index 00000000000..8bc8454981d--- /dev/null+++ b/packages/pieces/community/moxie-crm/src/lib/actions/ai/contact-create.ts@@ -0,0 +1,33 @@+import { Property, createAction } from '@activepieces/pieces-framework';+import { moxieCRMAuth } from '../../auth';+import { credentialsOf } from '../../common';+import { moxieFields } from '../../common/fields';+import { moxieOperations } from '../../common/operations';+import { moxieProps } from '../../common/props';+import { moxieActionOutputSchemas } from '../../output-schemas';++export const moxieContactCreateAction = createAction({+ auth: moxieCRMAuth,+ name: 'moxie_contact_create',+ classification: 'WRITE',+ displayName: 'Create Contact',+ description: 'Creates a contact in Moxie, optionally under a client.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Creates a contact person in Moxie, attached to a client when Client Name is given (exact name, from Search Clients). Use to add a person to an account or a named lead; check Search Contacts first to avoid duplicates. Not idempotent: each call creates a separate contact, even with the same email.',+ idempotent: false,+ },+ outputSchema: moxieActionOutputSchemas.contact,+ props: {+ ...moxieProps.fromSpecs({ specs: moxieFields.contactCreate, audience: 'ai' }),+ clientName: Property.ShortText({+ displayName: 'Client Name',+ description: 'Exact name of the client to attach the contact to, from Search Clients. Leave empty for a contact without a client.',+ required: false,+ }),+ },+ async run({ auth, propsValue }) {+ return moxieOperations.createContact({ credentials: credentialsOf({ auth }), values: propsValue });+ },+});diff --git a/packages/pieces/community/moxie-crm/src/lib/actions/ai/contact-update.ts b/packages/pieces/community/moxie-crm/src/lib/actions/ai/contact-update.tsnew file mode 100644index 00000000000..55e933a9ab3--- /dev/null+++ b/packages/pieces/community/moxie-crm/src/lib/actions/ai/contact-update.ts@@ -0,0 +1,39 @@+import { Property, createAction } from '@activepieces/pieces-framework';+import { moxieCRMAuth } from '../../auth';+import { credentialsOf } from '../../common';+import { moxieFields } from '../../common/fields';+import { moxieOperations } from '../../common/operations';+import { moxieProps } from '../../common/props';+import { moxieActionOutputSchemas } from '../../output-schemas';++export const moxieContactUpdateAction = createAction({+ auth: moxieCRMAuth,+ name: 'moxie_contact_update',+ classification: 'WRITE',+ displayName: 'Update Contact',+ description: 'Updates fields on an existing Moxie contact.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Updates an existing Moxie contact by id: only the fields you pass change, Clear Fields blanks text fields, and Client ID moves the contact to another client. Use after finding the contact id with Search Contacts. Idempotent: repeating the same update leaves the contact unchanged.',+ idempotent: true,+ },+ outputSchema: moxieActionOutputSchemas.contact,+ props: {+ contactId: Property.ShortText({+ displayName: 'Contact ID',+ description: 'Id of the contact to update, from Search Contacts.',+ required: true,+ }),+ ...moxieProps.fromSpecs({ specs: moxieFields.contactUpdate, audience: 'ai' }),+ clientId: Property.ShortText({+ displayName: 'Client ID',+ description: 'Moves the contact to this client id, from Search Clients. Leave empty to keep the current client.',+ required: false,+ }),+ clearFields: moxieProps.clearFields({ specs: moxieFields.contactUpdate }),+ },+ async run({ auth, propsValue }) {+ return moxieOperations.updateContact({ credentials: credentialsOf({ auth }), values: propsValue });+ },+});diff --git a/packages/pieces/community/moxie-crm/src/lib/actions/ai/expense-create.ts b/packages/pieces/community/moxie-crm/src/lib/actions/ai/expense-create.tsnew file mode 100644index 00000000000..59ab051e1ab--- /dev/null+++ b/packages/pieces/community/moxie-crm/src/lib/actions/ai/expense-create.ts@@ -0,0 +1,42 @@+import { Property, createAction } from '@activepieces/pieces-framework';+import { moxieCRMAuth } from '../../auth';+import { credentialsOf } from '../../common';+import { moxieFields } from '../../common/fields';+import { moxieOperations } from '../../common/operations';+import { moxieProps } from '../../common/props';+import { moxieActionOutputSchemas } from '../../output-schemas';++export const moxieExpenseCreateAction = createAction({+ auth: moxieCRMAuth,+ name: 'moxie_expense_create',+ classification: 'WRITE',+ displayName: 'Create Expense',+ description: 'Records an expense in Moxie.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Records an expense with amount, date, vendor, category and billing flags, optionally billed to a client matched by exact name. Use to sync receipts or bills from another tool; vendor names come from List Vendors. Not idempotent: each call records another expense.',+ idempotent: false,+ },+ outputSchema: moxieActionOutputSchemas.expense,+ props: {+ amount: Property.Number({+ displayName: 'Amount',+ required: true,+ }),+ vendor: Property.ShortText({+ displayName: 'Vendor',+ description: 'Vendor name, from List Vendors.',+ required: false,+ }),+ clientName: Property.ShortText({+ displayName: 'Client Name',+ description: 'Exact client name to bill the expense to, from Search Clients.',+ required: false,+ }),+ ...moxieProps.fromSpecs({ specs: moxieFields.expenseCreate, audience: 'ai' }),+ },+ async run({ auth, propsValue }) {+ return moxieOperations.createExpense({ credentials: credentialsOf({ auth }), values: propsValue });+ },+});diff --git a/packages/pieces/community/moxie-crm/src/lib/actions/ai/invoice-create.ts b/packages/pieces/community/moxie-crm/src/lib/actions/ai/invoice-create.tsnew file mode 100644index 00000000000..50f8b80d865--- /dev/null+++ b/packages/pieces/community/moxie-crm/src/lib/actions/ai/invoice-create.ts@@ -0,0 +1,66 @@+import { Property, createAction } from '@activepieces/pieces-framework';+import { moxieCRMAuth } from '../../auth';+import { credentialsOf } from '../../common';+import { moxieFields } from '../../common/fields';+import { moxieOperations } from '../../common/operations';+import { moxieProps } from '../../common/props';+import { moxieActionOutputSchemas } from '../../output-schemas';++export const moxieInvoiceCreateAction = createAction({+ auth: moxieCRMAuth,+ name: 'moxie_invoice_create',+ classification: 'WRITE',+ displayName: 'Create Invoice',+ description: 'Creates a draft invoice in Moxie, and optionally sends it.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Creates an invoice with line items for a client matched by exact name. It stays a DRAFT unless Send Invoice is on, in which case Moxie emails it to the listed contacts. Use to bill a client; template names come from List Invoice Templates. Not idempotent: each call creates a new invoice, and with Send Invoice on each call emails the client.',+ idempotent: false,+ },+ outputSchema: moxieActionOutputSchemas.invoice,+ props: {+ clientName: Property.ShortText({+ displayName: 'Client Name',+ description: 'Exact name of the client to bill, from Search Clients.',+ required: true,+ }),+ templateName: Property.ShortText({+ displayName: 'Invoice Template',+ description: 'Exact invoice template name, from List Invoice Templates. Leave empty for the default.',+ required: false,+ }),+ items: Property.Array({+ displayName: 'Line Items',+ description: 'At least one line, each with a description, quantity and rate.',+ required: true,+ properties: {+ description: Property.ShortText({ displayName: 'Description', required: true }),+ quantity: Property.Number({ displayName: 'Quantity', required: true }),+ rate: Property.Number({ displayName: 'Rate', description: 'Price per unit.', required: true }),+ taxable: Property.Checkbox({ displayName: 'Taxable', required: false }),+ projectName: Property.ShortText({ displayName: 'Project Name', description: 'Exact project name to link the line to.', required: false }),+ },+ }),+ ...moxieProps.fromSpecs({ specs: moxieFields.invoice, audience: 'ai' }),+ send: Property.Checkbox({+ displayName: 'Send Invoice',+ description: 'Off (default) keeps the invoice as a draft. On emails it to the contacts below.',+ required: false,+ defaultValue: false,+ }),+ sendToContacts: Property.Array({+ displayName: 'Send To Contacts',+ description: 'Emails of the client contacts who receive the invoice. Only used when Send Invoice is on.',+ required: false,+ }),+ emailTemplateName: Property.ShortText({+ displayName: 'Email Template',+ description: 'Exact email template name for the invoice email, from List Email Templates. Only used when Send Invoice is on.',+ required: false,+ }),+ },+ async run({ auth, propsValue }) {+ return moxieOperations.createInvoice({ credentials: credentialsOf({ auth }), values: propsValue });+ },+});diff --git a/packages/pieces/community/moxie-crm/src/lib/actions/ai/opportunity-create.ts b/packages/pieces/community/moxie-crm/src/lib/actions/ai/opportunity-create.tsnew file mode 100644index 00000000000..5211e163f96--- /dev/null+++ b/packages/pieces/community/moxie-crm/src/lib/actions/ai/opportunity-create.ts@@ -0,0 +1,43 @@+import { Property, createAction } from '@activepieces/pieces-framework';+import { moxieCRMAuth } from '../../auth';+import { credentialsOf } from '../../common';+import { moxieFields } from '../../common/fields';+import { moxieOperations } from '../../common/operations';+import { moxieProps } from '../../common/props';+import { moxieActionOutputSchemas } from '../../output-schemas';++export const moxieOpportunityCreateAction = createAction({+ auth: moxieCRMAuth,+ name: 'moxie_opportunity_create',+ classification: 'WRITE',+ displayName: 'Create Opportunity',+ description: 'Creates a sales pipeline opportunity in Moxie.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Creates a pipeline opportunity (deal) in Moxie, optionally linked to a client by exact name and placed in a stage by exact stage label. Use to log a new deal or lead; get stage labels from List Pipeline Stages. Not idempotent: each call creates a separate opportunity.',+ idempotent: false,+ },+ outputSchema: moxieActionOutputSchemas.opportunity,+ props: {+ name: Property.ShortText({+ displayName: 'Opportunity Name',+ description: 'Name of the deal.',+ required: true,+ }),+ clientName: Property.ShortText({+ displayName: 'Client Name',+ description: 'Exact name of the client, from Search Clients. Leave empty for a deal without a client.',+ required: false,+ }),+ stageName: Property.ShortText({+ displayName: 'Stage',+ description: 'Exact pipeline stage label, from List Pipeline Stages. Leave empty for the default stage.',+ required: false,+ }),+ ...moxieProps.fromSpecs({ specs: moxieFields.opportunityCreate, audience: 'ai' }),+ },+ async run({ auth, propsValue }) {+ return moxieOperations.createOpportunity({ credentials: credentialsOf({ auth }), values: propsValue });+ },+});diff --git a/packages/pieces/community/moxie-crm/src/lib/actions/ai/opportunity-update.ts b/packages/pieces/community/moxie-crm/src/lib/actions/ai/opportunity-update.tsnew file mode 100644index 00000000000..3a833e574eb--- /dev/null+++ b/packages/pieces/community/moxie-crm/src/lib/actions/ai/opportunity-update.ts@@ -0,0 +1,44 @@+import { Property, createAction } from '@activepieces/pieces-framework';+import { moxieCRMAuth } from '../../auth';+import { credentialsOf } from '../../common';+import { moxieFields } from '../../common/fields';+import { moxieOperations } from '../../common/operations';+import { moxieProps } from '../../common/props';+import { moxieActionOutputSchemas } from '../../output-schemas';++export const moxieOpportunityUpdateAction = createAction({+ auth: moxieCRMAuth,+ name: 'moxie_opportunity_update',+ classification: 'WRITE',+ displayName: 'Update Opportunity',+ description: 'Updates an existing Moxie opportunity, including its pipeline stage.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Updates an existing Moxie opportunity by id; set Stage ID to move the deal through the pipeline, or change value, dates, sentiment, client or archive state. Only the fields you pass change. The opportunity id comes from Create Opportunity or an opportunity trigger (there is no search). Idempotent: repeating the same update leaves the deal unchanged.',+ idempotent: true,+ },+ outputSchema: moxieActionOutputSchemas.opportunity,+ props: {+ opportunityId: Property.ShortText({+ displayName: 'Opportunity ID',+ description: 'Id of the opportunity, from Create Opportunity or an opportunity trigger.',+ required: true,+ }),+ statusId: Property.ShortText({+ displayName: 'Stage ID',+ description: 'Moves the deal to this pipeline stage id, from List Pipeline Stages.',+ required: false,+ }),+ clientId: Property.ShortText({+ displayName: 'Client ID',+ description: 'Links the deal to this client id, from Search Clients.',+ required: false,+ }),+ ...moxieProps.fromSpecs({ specs: moxieFields.opportunityUpdate, audience: 'ai' }),+ clearFields: moxieProps.clearFields({ specs: moxieFields.opportunityUpdate }),+ },+ async run({ auth, propsValue }) {+ return moxieOperations.updateOpportunity({ credentials: credentialsOf({ auth }), values: propsValue });+ },+});diff --git a/packages/pieces/community/moxie-crm/src/lib/actions/ai/payment-create.ts b/packages/pieces/community/moxie-crm/src/lib/actions/ai/payment-create.tsnew file mode 100644index 00000000000..7eb6f019989--- /dev/null+++ b/packages/pieces/community/moxie-crm/src/lib/actions/ai/payment-create.ts@@ -0,0 +1,64 @@+import { Property, createAction } from '@activepieces/pieces-framework';+import { moxieCRMAuth } from '../../auth';+import { credentialsOf } from '../../common';+import { PAYMENT_TYPE_OPTIONS } from '../../common/fields';+import { moxieOperations } from '../../common/operations';+import { moxieActionOutputSchemas } from '../../output-schemas';++export const moxiePaymentCreateAction = createAction({+ auth: moxieCRMAuth,+ name: 'moxie_payment_create',+ classification: 'WRITE',+ displayName: 'Record Payment',+ description: 'Records a payment against an open Moxie invoice.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Records a payment on an open (sent, not fully paid) invoice matched by formatted invoice number and exact client name. With a Reference Number, the action first checks the invoice and returns it with already_applied true instead of recording the same payment twice; this check is best-effort, since Moxie has no idempotency key, so two runs started at the same moment can both record it. If the first run paid the invoice in full, the invoice is no longer open and a repeat run fails with a not-found error instead of paying twice. Use to sync payments from another system; find invoices with Search Open Invoices. Not idempotent without a Reference Number.',+ idempotent: false,+ },+ outputSchema: moxieActionOutputSchemas.payment,+ props: {+ invoiceNumber: Property.ShortText({+ displayName: 'Invoice Number',+ description: 'Formatted invoice number, for example E-2026-042, from Search Open Invoices.',+ required: true,+ }),+ clientName: Property.ShortText({+ displayName: 'Client Name',+ description: 'Exact name of the client the invoice belongs to.',+ required: true,+ }),+ amount: Property.Number({+ displayName: 'Amount',+ description: 'Payment amount, more than 0.',+ required: true,+ }),+ date: Property.ShortText({+ displayName: 'Payment Date',+ description: 'Date in YYYY-MM-DD format. Leave empty to use the Moxie default.',+ required: false,+ }),+ paymentType: Property.StaticDropdown({+ displayName: 'Payment Method',+ required: false,+ options: {+ disabled: false,+ options: PAYMENT_TYPE_OPTIONS.map((option) => ({ label: option, value: option })),+ },+ }),+ referenceNumber: Property.ShortText({+ displayName: 'Reference Number',+ description: 'External payment reference. Also used to skip a payment that was already recorded.',+ required: false,+ }),+ memo: Property.ShortText({+ displayName: 'Memo',+ description: 'Free-text note on the payment.',+ required: false,+ }),+ },+ async run({ auth, propsValue }) {+ return moxieOperations.applyPayment({ credentials: credentialsOf({ auth }), values: propsValue });+ },+});diff --git a/packages/pieces/community/moxie-crm/src/lib/actions/ai/project-create.ts b/packages/pieces/community/moxie-crm/src/lib/actions/ai/project-create.tsnew file mode 100644index 00000000000..0bf48d38017--- /dev/null+++ b/packages/pieces/community/moxie-crm/src/lib/actions/ai/project-create.ts@@ -0,0 +1,39 @@+import { Property, createAction } from '@activepieces/pieces-framework';+import { moxieCRMAuth } from '../../auth';+import { credentialsOf } from '../../common';+import { moxieFields } from '../../common/fields';+import { moxieOperations } from '../../common/operations';+import { moxieProps } from '../../common/props';+import { moxieActionOutputSchemas } from '../../output-schemas';++export const moxieProjectCreateAction = createAction({+ auth: moxieCRMAuth,+ name: 'moxie_project_create',+ classification: 'WRITE',+ displayName: 'Create Project',+ description: 'Creates a project for an existing Moxie client.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Creates a project under an existing client matched by exact name, with optional dates, portal access, template and fee schedule (the fee schedule is sent only when Fee Type is set). Use when starting a new engagement for a known client. Not idempotent: each call creates a separate project.',+ idempotent: false,+ },+ outputSchema: moxieActionOutputSchemas.project,+ props: {+ name: Property.ShortText({+ displayName: 'Project Name',+ description: 'Name of the new project.',+ required: true,+ }),+ clientName: Property.ShortText({+ displayName: 'Client Name',+ description: 'Exact name of an existing client, from Search Clients.',+ required: true,+ }),+ ...moxieProps.fromSpecs({ specs: moxieFields.projectCreate, audience: 'ai' }),+ ...moxieProps.fromSpecs({ specs: moxieFields.projectFee, audience: 'ai' }),+ },+ async run({ auth, propsValue }) {+ return moxieOperations.createProject({ credentials: credentialsOf({ auth }), values: propsValue });+ },+});diff --git a/packages/pieces/community/moxie-crm/src/lib/actions/ai/project-update.ts b/packages/pieces/community/moxie-crm/src/lib/actions/ai/project-update.tsnew file mode 100644index 00000000000..1af18b9fe9a--- /dev/null+++ b/packages/pieces/community/moxie-crm/src/lib/actions/ai/project-update.ts@@ -0,0 +1,34 @@+import { Property, createAction } from '@activepieces/pieces-framework';+import { moxieCRMAuth } from '../../auth';+import { credentialsOf } from '../../common';+import { moxieFields } from '../../common/fields';+import { moxieOperations } from '../../common/operations';+import { moxieProps } from '../../common/props';+import { moxieActionOutputSchemas } from '../../output-schemas';++export const moxieProjectUpdateAction = createAction({+ auth: moxieCRMAuth,+ name: 'moxie_project_update',+ classification: 'WRITE',+ displayName: 'Update Project',+ description: 'Updates fields on an existing Moxie project.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Updates an existing Moxie project by id (name, description, dates, active state, portal access, colour); only the fields you pass change and Clear Fields blanks the description. Use after finding the project id with Search Projects; the fee schedule is not changed here. Idempotent: repeating the same update leaves the project unchanged.',+ idempotent: true,+ },+ outputSchema: moxieActionOutputSchemas.project,+ props: {+ projectId: Property.ShortText({+ displayName: 'Project ID',+ description: 'Id of the project to update, from Search Projects or a project trigger.',+ required: true,+ }),+ ...moxieProps.fromSpecs({ specs: moxieFields.projectUpdate, audience: 'ai' }),+ clearFields: moxieProps.clearFields({ specs: moxieFields.projectUpdate }),+ },+ async run({ auth, propsValue }) {+ return moxieOperations.updateProject({ credentials: credentialsOf({ auth }), values: propsValue });+ },+});diff --git a/packages/pieces/community/moxie-crm/src/lib/actions/ai/task-create.ts b/packages/pieces/community/moxie-crm/src/lib/actions/ai/task-create.tsnew file mode 100644index 00000000000..6c60fe9f8a9--- /dev/null+++ b/packages/pieces/community/moxie-crm/src/lib/actions/ai/task-create.ts@@ -0,0 +1,48 @@+import { Property, createAction } from '@activepieces/pieces-framework';+import { moxieCRMAuth } from '../../auth';+import { credentialsOf } from '../../common';+import { moxieFields } from '../../common/fields';+import { moxieOperations } from '../../common/operations';+import { moxieProps } from '../../common/props';+import { moxieActionOutputSchemas } from '../../output-schemas';++export const moxieTaskCreateAction = createAction({+ auth: moxieCRMAuth,+ name: 'moxie_task_create',+ classification: 'WRITE',+ displayName: 'Create Task',+ description: 'Creates a task inside an existing Moxie project.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Creates a task (deliverable) in a project identified by exact client and project names, with optional stage label, dates, priority, subtasks, assignee emails and custom values. Use to add work items to a known project; resolve names with Search Projects and stage labels with List Task Stages. Not idempotent: each call creates a separate task.',+ idempotent: false,+ },+ outputSchema: moxieActionOutputSchemas.task,+ props: {+ name: Property.ShortText({+ displayName: 'Task Name',+ description: 'Name of the new task.',+ required: true,+ }),+ clientName: Property.ShortText({+ displayName: 'Client Name',+ description: 'Exact name of the client that owns the project, from Search Clients.',+ required: true,+ }),+ projectName: Property.ShortText({+ displayName: 'Project Name',+ description: 'Exact name of the project, from Search Projects.',+ required: true,+ }),+ status: Property.ShortText({+ displayName: 'Stage',+ description: 'Stage label to place the task in, from List Task Stages. Leave empty for the default stage.',+ required: false,+ }),+ ...moxieProps.fromSpecs({ specs: moxieFields.taskCreate, audience: 'ai' }),+ },+ async run({ auth, propsValue }) {+ return moxieOperations.createTask({ credentials: credentialsOf({ auth }), values: propsValue });+ },+});diff --git a/packages/pieces/community/moxie-crm/src/lib/actions/ai/task-update.ts b/packages/pieces/community/moxie-crm/src/lib/actions/ai/task-update.tsnew file mode 100644index 00000000000..9fafe26a52a--- /dev/null+++ b/packages/pieces/community/moxie-crm/src/lib/actions/ai/task-update.ts@@ -0,0 +1,44 @@+import { Property, createAction } from '@activepieces/pieces-framework';+import { moxieCRMAuth } from '../../auth';+import { credentialsOf } from '../../common';+import { moxieFields } from '../../common/fields';+import { moxieOperations } from '../../common/operations';+import { moxieProps } from '../../common/props';+import { moxieActionOutputSchemas } from '../../output-schemas';++export const moxieTaskUpdateAction = createAction({+ auth: moxieCRMAuth,+ name: 'moxie_task_update',+ classification: 'WRITE',+ displayName: 'Update Task',+ description: 'Updates fields on an existing Moxie task, including its stage.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Updates an existing Moxie task by id: rename, change description, dates or priority, move it to another stage with Stage ID, or replace its assignees. Only the fields you pass change. Use after finding the task id with Search Tasks or List Tasks. Idempotent: repeating the same update leaves the task unchanged.',+ idempotent: true,+ },+ outputSchema: moxieActionOutputSchemas.task,+ props: {+ taskId: Property.ShortText({+ displayName: 'Task ID',+ description: 'Id of the task to update, from Search Tasks, List Tasks or a task trigger.',+ required: true,+ }),+ ...moxieProps.fromSpecs({ specs: moxieFields.taskUpdate, audience: 'ai' }),+ statusId: Property.ShortText({+ displayName: 'Stage ID',+ description: 'Moves the task to this stage id, from List Task Stages or List Project Types. Leave empty to keep the stage.',+ required: false,+ }),+ assignedToList: Property.Array({+ displayName: 'Assignee User IDs',+ description: 'Numeric user ids (user.userId from List Workspace Users). Replaces the current assignees.',+ required: false,+ }),+ clearFields: moxieProps.clearFields({ specs: moxieFields.taskUpdate }),+ },+ async run({ auth, propsValue }) {+ return moxieOperations.updateTask({ credentials: credentialsOf({ auth }), values: propsValue });+ },+});diff --git a/packages/pieces/community/moxie-crm/src/lib/actions/ai/time-entry-create.ts b/packages/pieces/community/moxie-crm/src/lib/actions/ai/time-entry-create.tsnew file mode 100644index 00000000000..5b7cef2e160--- /dev/null+++ b/packages/pieces/community/moxie-crm/src/lib/actions/ai/time-entry-create.ts@@ -0,0 +1,61 @@+import { Property, createAction } from '@activepieces/pieces-framework';+import { moxieCRMAuth } from '../../auth';+import { credentialsOf } from '../../common';+import { moxieFields } from '../../common/fields';+import { moxieOperations } from '../../common/operations';+import { moxieProps } from '../../common/props';+import { moxieActionOutputSchemas } from '../../output-schemas';++export const moxieTimeEntryCreateAction = createAction({+ auth: moxieCRMAuth,+ name: 'moxie_time_entry_create',+ classification: 'WRITE',+ displayName: 'Log Time',+ description: 'Logs a time entry in Moxie.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Logs a time entry between two ISO 8601 timestamps, optionally against a client, project and task matched by exact name and for a given workspace user. The Create options make Moxie create a missing client, project or task instead of failing. Use to sync time from another tracker. Not idempotent: each call logs another entry.',+ idempotent: false,+ },+ outputSchema: moxieActionOutputSchemas.timeEntry,+ props: {+ timerStart: Property.ShortText({+ displayName: 'Start Time',+ description: 'ISO 8601 start, for example 2026-10-01T09:00:00Z.',+ required: true,+ }),+ timerEnd: Property.ShortText({+ displayName: 'End Time',+ description: 'ISO 8601 end, after the start.',+ required: true,+ }),+ clientName: Property.ShortText({+ displayName: 'Client Name',+ description: 'Exact client name, from Search Clients.',+ required: false,+ }),+ projectName: Property.ShortText({+ displayName: 'Project Name',+ description: 'Exact project name, from Search Projects.',+ required: false,+ }),+ deliverableName: Property.ShortText({+ displayName: 'Task Name',+ description: 'Exact task name, from Search Tasks.',+ required: false,+ }),+ userEmail: Property.ShortText({+ displayName: 'User Email',+ description: 'Email of the workspace user the time is logged for, from List Workspace Users. Leave empty to let Moxie use its default user.',+ required: false,+ }),+ ...moxieProps.fromSpecs({ specs: moxieFields.timeEntry, audience: 'ai' }),+ createClient: Property.Checkbox({ displayName: 'Create Client if Missing', required: false, defaultValue: false }),+ createProject: Property.Checkbox({ displayName: 'Create Project if Missing', required: false, defaultValue: false }),+ createDeliverable: Property.Checkbox({ displayName: 'Create Task if Missing', required: false, defaultValue: false }),+ },+ async run({ auth, propsValue }) {+ return moxieOperations.createTimeEntry({ credentials: credentialsOf({ auth }), values: propsValue });+ },+});diff --git a/packages/pieces/community/moxie-crm/src/lib/actions/apply-payment.ts b/packages/pieces/community/moxie-crm/src/lib/actions/apply-payment.tsnew file mode 100644index 00000000000..f55c868495d--- /dev/null+++ b/packages/pieces/community/moxie-crm/src/lib/actions/apply-payment.ts@@ -0,0 +1,56 @@+import { Property, createAction } from '@activepieces/pieces-framework';+import { moxieCRMAuth } from '../auth';+import { credentialsOf } from '../common';+import { moxieDropdowns } from '../common/dropdowns';+import { PAYMENT_TYPE_OPTIONS } from '../common/fields';+import { moxieOperations } from '../common/operations';+import { moxieActionOutputSchemas } from '../output-schemas';++export const moxieApplyPaymentAction = createAction({+ auth: moxieCRMAuth,+ name: 'moxie_apply_payment',+ classification: 'WRITE',+ displayName: 'Record Payment',+ description: 'Record a payment against an open invoice.',+ audience: 'human',+ aiMetadata: {+ description:+ 'Records a payment on an open Moxie invoice picked by client and invoice; with a Reference Number a repeat run returns the invoice with already_applied true while it is still open (best-effort: two runs at the same moment can both record it), and fails with not-found once it is fully paid, instead of paying twice. For agents use moxie_payment_create. Not idempotent without a Reference Number.',+ idempotent: false,+ },+ outputSchema: moxieActionOutputSchemas.payment,+ props: {+ clientName: moxieDropdowns.clientName({ required: true }),+ invoiceNumber: moxieDropdowns.payableInvoice({ required: true }),+ amount: Property.Number({+ displayName: 'Amount',+ required: true,+ }),+ date: Property.ShortText({+ displayName: 'Payment Date',+ description: 'Date in YYYY-MM-DD format.',+ required: false,+ }),+ paymentType: Property.StaticDropdown({+ displayName: 'Payment Method',+ required: false,+ options: {+ disabled: false,+ options: PAYMENT_TYPE_OPTIONS.map((option) => ({ label: option.replace(/_/g, ' '), value: option })),+ },+ }),+ referenceNumber: Property.ShortText({+ displayName: 'Reference Number',+ description: 'External payment reference, such as a bank or Stripe id. A repeat run with the same reference is skipped.',+ required: false,+ }),+ memo: Property.ShortText({+ displayName: 'Memo',+ description: 'Free-text note on the payment.',+ required: false,+ }),+ },+ async run({ auth, propsValue }) {+ return moxieOperations.applyPayment({ credentials: credentialsOf({ auth }), values: propsValue });+ },+});diff --git a/packages/pieces/community/moxie-crm/src/lib/actions/approve-task.ts b/packages/pieces/community/moxie-crm/src/lib/actions/approve-task.tsnew file mode 100644index 00000000000..03a7682421b--- /dev/null+++ b/packages/pieces/community/moxie-crm/src/lib/actions/approve-task.ts@@ -0,0 +1,52 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { Property, createAction } from '@activepieces/pieces-framework';+import { moxieCRMAuth } from '../auth';+import { credentialsOf } from '../common';+import { moxieRequest } from '../common/client';+import { moxieInput } from '../common/props';+import { moxieActionOutputSchemas } from '../output-schemas';++export const moxieApproveTaskAction = createAction({+ auth: moxieCRMAuth,+ name: 'moxie_approve_task',+ classification: 'WRITE',+ displayName: 'Approve Task',+ description: 'Approve a task that is waiting for client approval.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Approves a task (deliverable) waiting for client approval, identified by exact client, project and task names, as if the client signed it off in the portal. Use when the approval arrives outside Moxie, for example by email. Not marked idempotent: a repeat call on an approved task may be rejected.',+ idempotent: false,+ },+ outputSchema: moxieActionOutputSchemas.approvedTask,+ props: {+ clientName: Property.ShortText({+ displayName: 'Client Name',+ description: 'Exact client name, from Search Clients.',+ required: true,+ }),+ projectName: Property.ShortText({+ displayName: 'Project Name',+ description: 'Exact project name, from Search Projects.',+ required: true,+ }),+ taskName: Property.ShortText({+ displayName: 'Task Name',+ description: 'Exact task name, from Search Tasks or List Tasks.',+ required: true,+ }),+ },+ async run({ auth, propsValue }) {+ return moxieRequest<unknown>({+ credentials: credentialsOf({ auth }),+ method: HttpMethod.POST,+ path: '/action/deliverable/approve',+ body: {+ clientName: moxieInput.requiredText({ value: propsValue.clientName, field: 'Client Name' }),+ projectName: moxieInput.requiredText({ value: propsValue.projectName, field: 'Project Name' }),+ deliverableName: moxieInput.requiredText({ value: propsValue.taskName, field: 'Task Name' }),+ },+ notFoundMessage: 'Moxie could not find that client, project or task. All three names must match exactly.',+ });+ },+});diff --git a/packages/pieces/community/moxie-crm/src/lib/actions/attach-file-from-url.ts b/packages/pieces/community/moxie-crm/src/lib/actions/attach-file-from-url.tsnew file mode 100644index 00000000000..d034d04be71--- /dev/null+++ b/packages/pieces/community/moxie-crm/src/lib/actions/attach-file-from-url.ts@@ -0,0 +1,65 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { Property, createAction } from '@activepieces/pieces-framework';+import { moxieCRMAuth } from '../auth';+import { credentialsOf } from '../common';+import { moxieRequest } from '../common/client';+import { ATTACHMENT_OBJECT_TYPES } from '../common/fields';+import { moxieInput } from '../common/props';+import { moxieActionOutputSchemas } from '../output-schemas';++export const moxieAttachFileFromUrlAction = createAction({+ auth: moxieCRMAuth,+ name: 'moxie_attach_file_from_url',+ classification: 'WRITE',+ displayName: 'Attach File from URL',+ description: 'Attach a file from a public URL to a client, project, task, opportunity, expense or ticket.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Makes Moxie download a file from a public https URL and attach it to a client, project, task, opportunity, expense or ticket by id. Use to file a document, receipt or design that already lives online; the URL must be reachable by Moxie without credentials. Not idempotent: each call adds another copy of the file.',+ idempotent: false,+ },+ outputSchema: moxieActionOutputSchemas.attachment,+ props: {+ objectType: Property.StaticDropdown({+ displayName: 'Attach To',+ required: true,+ options: {+ disabled: false,+ options: ATTACHMENT_OBJECT_TYPES.map((type) => ({ label: type.charAt(0) + type.slice(1).toLowerCase(), value: type })),+ },+ }),+ objectId: Property.ShortText({+ displayName: 'Record ID',+ description: 'Id of the client, project, task, opportunity, expense or ticket to attach the file to.',+ required: true,+ }),+ fileUrl: Property.ShortText({+ displayName: 'File URL',+ description: 'Public https URL of the file.',+ required: true,+ }),+ fileName: Property.ShortText({+ displayName: 'File Name',+ description: 'Name to store the file under, including its extension.',+ required: true,+ }),+ },+ async run({ auth, propsValue }) {+ const objectType = moxieInput.requiredText({ value: propsValue.objectType, field: 'Attach To' }).toUpperCase();+ if (!ATTACHMENT_OBJECT_TYPES.includes(objectType)) {+ throw new Error(`Attach To must be one of: ${ATTACHMENT_OBJECT_TYPES.join(', ')}.`);+ }+ const objectId = moxieInput.id({ value: propsValue.objectId, field: 'Record ID' });+ const fileUrl = moxieInput.httpsUrl({ value: propsValue.fileUrl, field: 'File URL' });+ const fileName = moxieInput.requiredText({ value: propsValue.fileName, field: 'File Name' });+ const url = await moxieRequest<unknown>({+ credentials: credentialsOf({ auth }),+ method: HttpMethod.POST,+ path: '/action/attachments/createFromUrl',+ query: { id: objectId, type: objectType, fileUrl, fileName },+ notFoundMessage: `No ${objectType.toLowerCase()} with id ${objectId} in this Moxie workspace.`,+ });+ return { url: typeof url === 'string' ? url : null, objectType, objectId, fileName };+ },+});diff --git a/packages/pieces/community/moxie-crm/src/lib/actions/create-contact.ts b/packages/pieces/community/moxie-crm/src/lib/actions/create-contact.tsindex fee02c6c654..48c83b22d29 100644--- a/packages/pieces/community/moxie-crm/src/lib/actions/create-contact.ts+++ b/packages/pieces/community/moxie-crm/src/lib/actions/create-contact.ts@@ -1,6 +1,7 @@import { Property, createAction } from '@activepieces/pieces-framework';import { makeClient } from '../common';import { moxieCRMAuth } from '../auth';+import { moxieDropdowns } from '../common/dropdowns';import { createContactActionOutputSchema } from '../output-schemas';export const moxieCreateContactAction = createAction({@@ -33,26 +34,9 @@ export const moxieCreateContactAction = createAction({displayName: 'Phone',required: false,}),- clientName: Property.Dropdown({- auth: moxieCRMAuth,- displayName: 'Client',- description: 'The client this contact belongs to.',+ clientName: moxieDropdowns.clientName({required: false,- refreshers: [],- options: async ({ auth }) => {- if (!auth) {- return {- disabled: true,- options: [],- placeholder: 'Please connect your account first',- };- }- const client = await makeClient(auth);- const clients = await client.listClients();- return {- options: clients.map((c) => ({ label: c.name, value: c.name })),- };- },+ description: 'The client this contact belongs to.',}),defaultContact: Property.Checkbox({displayName: 'Default Contact',diff --git a/packages/pieces/community/moxie-crm/src/lib/actions/create-expense.ts b/packages/pieces/community/moxie-crm/src/lib/actions/create-expense.tsnew file mode 100644index 00000000000..49b915a64c4--- /dev/null+++ b/packages/pieces/community/moxie-crm/src/lib/actions/create-expense.ts@@ -0,0 +1,35 @@+import { Property, createAction } from '@activepieces/pieces-framework';+import { moxieCRMAuth } from '../auth';+import { credentialsOf } from '../common';+import { moxieDropdowns } from '../common/dropdowns';+import { moxieFields } from '../common/fields';+import { moxieOperations } from '../common/operations';+import { moxieProps } from '../common/props';+import { moxieActionOutputSchemas } from '../output-schemas';++export const moxieCreateExpenseAction = createAction({+ auth: moxieCRMAuth,+ name: 'moxie_create_expense',+ classification: 'WRITE',+ displayName: 'Create Expense',+ description: 'Record an expense, optionally billable to a client.',+ audience: 'human',+ aiMetadata: {+ description:+ 'Records a Moxie expense with vendor and client picked from lists. For agents use moxie_expense_create. Not idempotent: each run records another expense.',+ idempotent: false,+ },+ outputSchema: moxieActionOutputSchemas.expense,+ props: {+ amount: Property.Number({+ displayName: 'Amount',+ required: true,+ }),+ vendor: moxieDropdowns.stringList({ required: false, displayName: 'Vendor', path: '/action/vendors/list' }),+ clientName: moxieDropdowns.clientName({ required: false, description: 'Client to bill the expense to.' }),+ ...moxieProps.fromSpecs({ specs: moxieFields.expenseCreate, audience: 'human' }),+ },+ async run({ auth, propsValue }) {+ return moxieOperations.createExpense({ credentials: credentialsOf({ auth }), values: propsValue });+ },+});diff --git a/packages/pieces/community/moxie-crm/src/lib/actions/create-form-submission.ts b/packages/pieces/community/moxie-crm/src/lib/actions/create-form-submission.tsnew file mode 100644index 00000000000..ad7e2289ea3--- /dev/null+++ b/packages/pieces/community/moxie-crm/src/lib/actions/create-form-submission.ts@@ -0,0 +1,61 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { Property, createAction } from '@activepieces/pieces-framework';+import { moxieCRMAuth } from '../auth';+import { credentialsOf } from '../common';+import { moxieRequest } from '../common/client';+import { moxieFields } from '../common/fields';+import { moxieInput, moxieProps, moxieBody } from '../common/props';+import { moxieActionOutputSchemas } from '../output-schemas';++export const moxieCreateFormSubmissionAction = createAction({+ auth: moxieCRMAuth,+ name: 'moxie_create_form_submission',+ classification: 'WRITE',+ displayName: 'Submit Lead Form',+ description: 'Submit a Moxie lead or discovery form, which adds a lead to the pipeline.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Submits a Moxie lead or discovery form by exact form name with the lead contact details and answers, which creates a pipeline lead the same way a website submission does. Use to push leads from other forms or tools into the Moxie pipeline; form names come from List Form Names. Not idempotent: each call creates another submission and lead.',+ idempotent: false,+ },+ outputSchema: moxieActionOutputSchemas.formSubmission,+ props: {+ formName: Property.ShortText({+ displayName: 'Form Name',+ description: 'Exact form name, from List Form Names.',+ required: true,+ }),+ ...moxieProps.fromSpecs({ specs: moxieFields.formSubmission, audience: 'ai' }),+ answers: Property.Array({+ displayName: 'Answers',+ description: 'Question and answer pairs to store on the submission.',+ required: false,+ properties: {+ question: Property.ShortText({ displayName: 'Question', required: true }),+ answer: Property.LongText({ displayName: 'Answer', required: false }),+ },+ }),+ },+ async run({ auth, propsValue }) {+ const answers = (moxieInput.recordList({ value: propsValue.answers, field: 'Answers' }) ?? []).map((row) =>+ moxieInput.compact({+ values: {+ question: moxieInput.requiredText({ value: row['question'], field: 'Answer question' }),+ answer: moxieInput.text({ value: row['answer'] }),+ },+ }),+ );+ return moxieRequest<unknown>({+ credentials: credentialsOf({ auth }),+ method: HttpMethod.POST,+ path: '/action/formSubmissions/create',+ body: {+ formName: moxieInput.requiredText({ value: propsValue.formName, field: 'Form Name' }),+ ...moxieBody.fromSpecs({ specs: moxieFields.formSubmission, values: propsValue }),+ ...(answers.length === 0 ? {} : { answers }),+ },+ notFoundMessage: 'Moxie could not find that form or pipeline stage. Names must match exactly.',+ });+ },+});diff --git a/packages/pieces/community/moxie-crm/src/lib/actions/create-invoice.ts b/packages/pieces/community/moxie-crm/src/lib/actions/create-invoice.tsnew file mode 100644index 00000000000..95d148fbcbc--- /dev/null+++ b/packages/pieces/community/moxie-crm/src/lib/actions/create-invoice.ts@@ -0,0 +1,60 @@+import { Property, createAction } from '@activepieces/pieces-framework';+import { moxieCRMAuth } from '../auth';+import { credentialsOf } from '../common';+import { moxieDropdowns } from '../common/dropdowns';+import { moxieFields } from '../common/fields';+import { moxieOperations } from '../common/operations';+import { moxieProps } from '../common/props';+import { moxieActionOutputSchemas } from '../output-schemas';++export const moxieCreateInvoiceAction = createAction({+ auth: moxieCRMAuth,+ name: 'moxie_create_invoice',+ classification: 'WRITE',+ displayName: 'Create Invoice',+ description: 'Create an invoice with line items. It stays a draft unless you turn on Send Invoice.',+ audience: 'human',+ aiMetadata: {+ description:+ 'Creates a Moxie invoice with client, template and email template picked from lists, as a draft unless Send Invoice is on. For agents use moxie_invoice_create. Not idempotent: each run creates another invoice and, when sending, emails the client.',+ idempotent: false,+ },+ outputSchema: moxieActionOutputSchemas.invoice,+ props: {+ clientName: moxieDropdowns.clientName({ required: true, description: 'The client to bill.' }),+ templateName: moxieDropdowns.stringList({+ required: false,+ displayName: 'Invoice Template',+ description: 'Leave empty for the default template.',+ path: '/action/invoiceTemplates/list',+ }),+ items: Property.Array({+ displayName: 'Line Items',+ required: true,+ properties: {+ description: Property.ShortText({ displayName: 'Description', required: true }),+ quantity: Property.Number({ displayName: 'Quantity', required: true }),+ rate: Property.Number({ displayName: 'Rate', description: 'Price per unit.', required: true }),+ taxable: Property.Checkbox({ displayName: 'Taxable', required: false }),+ projectName: Property.ShortText({ displayName: 'Project Name', description: 'Exact project name to link the line to.', required: false }),+ },+ }),+ ...moxieProps.fromSpecs({ specs: moxieFields.invoice, audience: 'human' }),+ send: Property.Checkbox({+ displayName: 'Send Invoice',+ description: 'Off (default) keeps the invoice as a draft. On emails it to the contacts below.',+ required: false,+ defaultValue: false,+ }),+ sendToContacts: moxieDropdowns.clientContactEmails({ required: false }),+ emailTemplateName: moxieDropdowns.stringList({+ required: false,+ displayName: 'Email Template',+ description: 'Email used to send the invoice. Only used when Send Invoice is on.',+ path: '/action/emailTemplates/list',+ }),+ },+ async run({ auth, propsValue }) {+ return moxieOperations.createInvoice({ credentials: credentialsOf({ auth }), values: propsValue });+ },+});diff --git a/packages/pieces/community/moxie-crm/src/lib/actions/create-opportunity.ts b/packages/pieces/community/moxie-crm/src/lib/actions/create-opportunity.tsnew file mode 100644index 00000000000..a7eac3b4902--- /dev/null+++ b/packages/pieces/community/moxie-crm/src/lib/actions/create-opportunity.ts@@ -0,0 +1,36 @@+import { Property, createAction } from '@activepieces/pieces-framework';+import { moxieCRMAuth } from '../auth';+import { credentialsOf } from '../common';+import { moxieDropdowns } from '../common/dropdowns';+import { moxieFields } from '../common/fields';+import { moxieOperations } from '../common/operations';+import { moxieProps } from '../common/props';+import { moxieActionOutputSchemas } from '../output-schemas';++export const moxieCreateOpportunityAction = createAction({+ auth: moxieCRMAuth,+ name: 'moxie_create_opportunity',+ classification: 'WRITE',+ displayName: 'Create Opportunity',+ description: 'Add a deal to the sales pipeline.',+ audience: 'human',+ aiMetadata: {+ description:+ 'Creates a Moxie pipeline opportunity with client and stage picked from lists. For agents use moxie_opportunity_create. Not idempotent: each run creates another opportunity.',+ idempotent: false,+ },+ outputSchema: moxieActionOutputSchemas.opportunity,+ props: {+ name: Property.ShortText({+ displayName: 'Opportunity Name',+ description: 'Name of the deal.',+ required: true,+ }),+ clientName: moxieDropdowns.clientName({ required: false, description: 'The client this deal is for. Leave empty for none.' }),+ stageName: moxieDropdowns.pipelineStage({ required: false, valueKey: 'label', description: 'Leave empty for the default stage.' }),+ ...moxieProps.fromSpecs({ specs: moxieFields.opportunityCreate, audience: 'human' }),+ },+ async run({ auth, propsValue }) {+ return moxieOperations.createOpportunity({ credentials: credentialsOf({ auth }), values: propsValue });+ },+});diff --git a/packages/pieces/community/moxie-crm/src/lib/actions/create-or-update-calendar-event.ts b/packages/pieces/community/moxie-crm/src/lib/actions/create-or-update-calendar-event.tsnew file mode 100644index 00000000000..7e83e702560--- /dev/null+++ b/packages/pieces/community/moxie-crm/src/lib/actions/create-or-update-calendar-event.ts@@ -0,0 +1,65 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { Property, createAction } from '@activepieces/pieces-framework';+import { moxieCRMAuth } from '../auth';+import { credentialsOf } from '../common';+import { moxieRequest } from '../common/client';+import { moxieFields } from '../common/fields';+import { moxieInput, moxieProps, moxieBody } from '../common/props';+import { moxieActionOutputSchemas } from '../output-schemas';++export const moxieCreateOrUpdateCalendarEventAction = createAction({+ auth: moxieCRMAuth,+ name: 'moxie_create_or_update_calendar_event',+ classification: 'WRITE',+ displayName: 'Create or Update Calendar Event',+ description: 'Create a Moxie calendar event, or update one by id.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Creates a Moxie calendar event when Event ID is empty (Start Time and End Time required), or updates the event with that id; when updating, pass every field the event should keep. Use to block time or mirror meetings from another calendar. Not idempotent in create mode: each call without an Event ID creates another event.',+ idempotent: false,+ },+ outputSchema: moxieActionOutputSchemas.calendarEvent,+ props: {+ eventId: Property.ShortText({+ displayName: 'Event ID',+ description: 'Id of an existing event to update. Leave empty to create a new event.',+ required: false,+ }),+ startTime: Property.ShortText({+ displayName: 'Start Time',+ description: 'ISO 8601 start, for example 2026-10-01T09:00:00Z. Required when creating.',+ required: false,+ }),+ endTime: Property.ShortText({+ displayName: 'End Time',+ description: 'ISO 8601 end, after the start. Required when creating.',+ required: false,+ }),+ ...moxieProps.fromSpecs({ specs: moxieFields.calendarEvent, audience: 'ai' }),+ },+ async run({ auth, propsValue }) {+ const eventId = moxieInput.optionalId({ value: propsValue.eventId, field: 'Event ID' });+ const startTime = moxieInput.dateTime({ value: propsValue.startTime, field: 'Start Time' });+ const endTime = moxieInput.dateTime({ value: propsValue.endTime, field: 'End Time' });+ if (eventId === undefined && (startTime === undefined || endTime === undefined)) {+ throw new Error('Start Time and End Time are required to create an event.');+ }+ if (startTime !== undefined && endTime !== undefined && Date.parse(endTime) <= Date.parse(startTime)) {+ throw new Error('End Time must be after Start Time.');+ }+ return moxieRequest<unknown>({+ credentials: credentialsOf({ auth }),+ method: HttpMethod.POST,+ path: '/action/calendar/createOrUpdate',+ body: {+ ...moxieInput.compact({ values: { eventId, startTime, endTime } }),+ ...moxieBody.fromSpecs({ specs: moxieFields.calendarEvent, values: propsValue }),+ },+ notFoundMessage:+ eventId === undefined+ ? 'Moxie could not find the owner. Owner Email must belong to a workspace user.'+ : `No calendar event with id ${eventId} in this Moxie workspace.`,+ });+ },+});diff --git a/packages/pieces/community/moxie-crm/src/lib/actions/create-project.ts b/packages/pieces/community/moxie-crm/src/lib/actions/create-project.tsindex e8ada73c82a..e9a13f789e0 100644--- a/packages/pieces/community/moxie-crm/src/lib/actions/create-project.ts+++ b/packages/pieces/community/moxie-crm/src/lib/actions/create-project.ts@@ -1,9 +1,7 @@-import {- Property,- createAction,- PiecePropValueSchema,-} from '@activepieces/pieces-framework';+import { Property, createAction } from '@activepieces/pieces-framework';import { makeClient, reformatDate } from '../common';+import { moxieDropdowns } from '../common/dropdowns';+import { moxieInput } from '../common/props';import { moxieCRMAuth } from '../auth';import { createProjectActionOutputSchema } from '../output-schemas';@@ -24,35 +22,7 @@ export const moxieCreateProjectAction = createAction({displayName: 'Project Name',required: true,}),- clientName: Property.Dropdown({- auth: moxieCRMAuth,- displayName: 'Client',- required: true,- refreshers: [],- options: async ({ auth }) => {- if (!auth) {- return {- disabled: true,- placeholder: 'Connect your account first',- options: [],- };- }-- const client = await makeClient(- auth- );- const clients = await client.listClients();- return {- disabled: false,- options: clients.map((client) => {- return {- label: client.name,- value: client.name,- };- }),- };- },- }),+ clientName: moxieDropdowns.clientName({ required: true }),startDate: Property.DateTime({displayName: 'Start Date',description: 'Please enter date in YYYY-MM-DD format.',@@ -67,7 +37,7 @@ export const moxieCreateProjectAction = createAction({displayName: 'Client Portal Access',description: 'One of: None, Overview, Full access, or Read only.',required: true,- defaultValue: 'Read Only',+ defaultValue: 'Read only',options: {options: [{@@ -139,6 +109,16 @@ export const moxieCreateProjectAction = createAction({required: false,defaultValue: false,}),+ templateName: Property.ShortText({+ displayName: 'Project Template',+ description: 'Exact name of a project template to copy tasks and settings from. Leave empty for none.',+ required: false,+ }),+ customValues: Property.Object({+ displayName: 'Custom Values',+ description: 'Custom project field values keyed by field name.',+ required: false,+ }),},async run({ auth, propsValue }) {const {@@ -152,12 +132,14 @@ export const moxieCreateProjectAction = createAction({estimateMin,taxable,} = propsValue;- const dueDate = reformatDate(propsValue.dueDate) as string;- const startDate = reformatDate(propsValue.startDate) as string;+ const dueDate = reformatDate(propsValue.dueDate);+ const startDate = reformatDate(propsValue.startDate);+ const templateName = moxieInput.text({ value: propsValue.templateName });+ const customValues = moxieInput.record({ value: propsValue.customValues, field: 'Custom Values' });const client = await makeClient(auth);return await client.createProject({name,- clientName,+ clientName: moxieInput.requiredText({ value: clientName, field: 'Client' }),startDate,dueDate,portalAccess,@@ -169,6 +151,8 @@ export const moxieCreateProjectAction = createAction({estimateMin,taxable,},+ ...(templateName === undefined ? {} : { templateName }),+ ...(customValues === undefined ? {} : { customValues }),});},});diff --git a/packages/pieces/community/moxie-crm/src/lib/actions/create-task.ts b/packages/pieces/community/moxie-crm/src/lib/actions/create-task.tsindex b6fe801f8c0..7de245c4ac5 100644--- a/packages/pieces/community/moxie-crm/src/lib/actions/create-task.ts+++ b/packages/pieces/community/moxie-crm/src/lib/actions/create-task.ts@@ -1,9 +1,7 @@-import {- Property,- createAction,- PiecePropValueSchema,-} from '@activepieces/pieces-framework';+import { Property, createAction } from '@activepieces/pieces-framework';import { makeClient, reformatDate } from '../common';+import { moxieDropdowns } from '../common/dropdowns';+import { moxieInput } from '../common/props';import { moxieCRMAuth } from '../auth';import { createTaskActionOutputSchema } from '../output-schemas';@@ -24,93 +22,20 @@ export const moxieCreateTaskAction = createAction({displayName: 'Name',required: true,}),- clientName: Property.Dropdown({- auth: moxieCRMAuth,+ clientName: moxieDropdowns.clientName({+ required: true,displayName: 'Client Name',description: 'Exact match of a client name in your CRM',- required: true,- refreshers: [],- options: async ({ auth }) => {- if (!auth) {- return {- disabled: true,- placeholder: 'Connect your account first',- options: [],- };- }-- const client = await makeClient(- auth- );- const clients = await client.listClients();- return {- disabled: false,- options: clients.map((client) => {- return {- label: client.name,- value: client.name,- };- }),- };- },}),- projectName: Property.Dropdown({- auth: moxieCRMAuth,+ projectName: moxieDropdowns.projectByClientName({+ required: true,+ valueKey: 'name',displayName: 'Project Name',description: 'Exact match of a project that is owned by the client.',- required: true,- refreshers: ['clientName'],- options: async ({ auth, clientName }) => {- if (!auth || !clientName) {- return {- disabled: true,- placeholder: 'Connect your account first and select client',- options: [],- };- }- const client = await makeClient(- auth- );- const projects = await client.searchProjects(clientName as string);- return {- disabled: false,- options: projects.map((project) => {- return {- label: project.name,- value: project.name,- };- }),- };- },}),- status: Property.Dropdown({- auth: moxieCRMAuth,- displayName: 'Status',+ status: moxieDropdowns.taskStageLabelByProjectName({required: true,- defaultValue: 'Not Started',- refreshers: [],- options: async ({ auth }) => {- if (!auth) {- return {- disabled: true,- placeholder: 'Connect your account first',- options: [],- };- }- const client = await makeClient(- auth- );- const stages = await client.listProjectTaskStages();- return {- disabled: false,- options: stages.map((stage) => {- return {- label: stage.label,- value: stage.label,- };- }),- };- },+ description: 'The stage to place the task in. Stages come from the selected project type.',}),description: Property.LongText({displayName: 'Description',@@ -149,18 +74,17 @@ export const moxieCreateTaskAction = createAction({async run({ auth, propsValue }) {const { name, clientName, projectName, status, description, priority } =propsValue;- const dueDate = reformatDate(propsValue.dueDate) as string;- const startDate = reformatDate(propsValue.startDate) as string;- const tasks = (propsValue.tasks as string[]) || [];- const assignedTo = (propsValue.assignedTo as string[]) || [];- const customValues =- (propsValue.customValues as Record<string, string>) || {};+ const dueDate = reformatDate(propsValue.dueDate);+ const startDate = reformatDate(propsValue.startDate);+ const tasks = moxieInput.stringList({ value: propsValue.tasks, field: 'Subtasks' }) ?? [];+ const assignedTo = moxieInput.stringList({ value: propsValue.assignedTo, field: 'Assigned To' }) ?? [];+ const customValues = moxieInput.record({ value: propsValue.customValues, field: 'Custom Values' }) ?? {};const client = await makeClient(auth);return await client.createTask({name,- clientName,- projectName,- status,+ clientName: moxieInput.requiredText({ value: clientName, field: 'Client Name' }),+ projectName: moxieInput.requiredText({ value: projectName, field: 'Project Name' }),+ status: moxieInput.requiredText({ value: status, field: 'Status' }),description,dueDate,startDate,diff --git a/packages/pieces/community/moxie-crm/src/lib/actions/create-ticket.ts b/packages/pieces/community/moxie-crm/src/lib/actions/create-ticket.tsnew file mode 100644index 00000000000..60ce367dd85--- /dev/null+++ b/packages/pieces/community/moxie-crm/src/lib/actions/create-ticket.ts@@ -0,0 +1,66 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { Property, createAction } from '@activepieces/pieces-framework';+import { moxieCRMAuth } from '../auth';+import { credentialsOf } from '../common';+import { moxieRequest } from '../common/client';+import { moxieInput } from '../common/props';+import { moxieActionOutputSchemas } from '../output-schemas';++export const moxieCreateTicketAction = createAction({+ auth: moxieCRMAuth,+ name: 'moxie_create_ticket',+ classification: 'WRITE',+ displayName: 'Create Ticket',+ description: 'Open a support ticket.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Opens a Moxie support ticket with a subject, first comment, ticket type label and due date, on behalf of the workspace user or client contact with the given email. Use to log a client request that arrived outside the client portal. Not idempotent: each call opens another ticket.',+ idempotent: false,+ },+ outputSchema: moxieActionOutputSchemas.ticketWrapper,+ props: {+ subject: Property.ShortText({+ displayName: 'Subject',+ description: 'Short summary of the request.',+ required: true,+ }),+ comment: Property.LongText({+ displayName: 'Comment',+ description: 'The first message on the ticket.',+ required: false,+ }),+ userEmail: Property.ShortText({+ displayName: 'Requester Email',+ description: 'Email of the client contact or workspace user who raised the ticket.',+ required: false,+ }),+ ticketType: Property.ShortText({+ displayName: 'Ticket Type',+ description: 'Ticket type label as configured in Moxie, for example Support.',+ required: false,+ }),+ dueDate: Property.ShortText({+ displayName: 'Due Date',+ description: 'Date in YYYY-MM-DD format.',+ required: false,+ }),+ },+ async run({ auth, propsValue }) {+ return moxieRequest<unknown>({+ credentials: credentialsOf({ auth }),+ method: HttpMethod.POST,+ path: '/action/tickets/create',+ body: moxieInput.compact({+ values: {+ subject: moxieInput.requiredText({ value: propsValue.subject, field: 'Subject' }),+ comment: moxieInput.text({ value: propsValue.comment }),+ userEmail: moxieInput.email({ value: propsValue.userEmail, field: 'Requester Email' }),+ ticketType: moxieInput.text({ value: propsValue.ticketType }),+ dueDate: moxieInput.date({ value: propsValue.dueDate, field: 'Due Date' }),+ },+ }),+ notFoundMessage: 'Moxie could not find the requester or ticket type. Check the email and the ticket type label.',+ });+ },+});diff --git a/packages/pieces/community/moxie-crm/src/lib/actions/create-time-entry.ts b/packages/pieces/community/moxie-crm/src/lib/actions/create-time-entry.tsnew file mode 100644index 00000000000..6202018d3c4--- /dev/null+++ b/packages/pieces/community/moxie-crm/src/lib/actions/create-time-entry.ts@@ -0,0 +1,41 @@+import { Property, createAction } from '@activepieces/pieces-framework';+import { moxieCRMAuth } from '../auth';+import { credentialsOf } from '../common';+import { moxieDropdowns } from '../common/dropdowns';+import { moxieFields } from '../common/fields';+import { moxieOperations } from '../common/operations';+import { moxieProps } from '../common/props';+import { moxieActionOutputSchemas } from '../output-schemas';++export const moxieCreateTimeEntryAction = createAction({+ auth: moxieCRMAuth,+ name: 'moxie_create_time_entry',+ classification: 'WRITE',+ displayName: 'Log Time',+ description: 'Log a time entry against a client, project and task.',+ audience: 'human',+ aiMetadata: {+ description:+ 'Logs a Moxie time entry with client, project, task and user picked from lists. For agents use moxie_time_entry_create. Not idempotent: each run logs another entry.',+ idempotent: false,+ },+ outputSchema: moxieActionOutputSchemas.timeEntry,+ props: {+ timerStart: Property.DateTime({+ displayName: 'Start Time',+ required: true,+ }),+ timerEnd: Property.DateTime({+ displayName: 'End Time',+ required: true,+ }),+ clientName: moxieDropdowns.clientName({ required: false }),+ projectName: moxieDropdowns.projectByClientName({ required: false, valueKey: 'name' }),+ deliverableName: moxieDropdowns.taskNameByProjectName({ required: false }),+ userEmail: moxieDropdowns.userEmail({ required: false, description: 'The workspace user the time is logged for.' }),+ ...moxieProps.fromSpecs({ specs: moxieFields.timeEntry, audience: 'human' }),+ },+ async run({ auth, propsValue }) {+ return moxieOperations.createTimeEntry({ credentials: credentialsOf({ auth }), values: propsValue });+ },+});diff --git a/packages/pieces/community/moxie-crm/src/lib/actions/delete-calendar-event.ts b/packages/pieces/community/moxie-crm/src/lib/actions/delete-calendar-event.tsnew file mode 100644index 00000000000..669709df94c--- /dev/null+++ b/packages/pieces/community/moxie-crm/src/lib/actions/delete-calendar-event.ts@@ -0,0 +1,39 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { Property, createAction } from '@activepieces/pieces-framework';+import { moxieCRMAuth } from '../auth';+import { credentialsOf } from '../common';+import { moxieRequest } from '../common/client';+import { moxieInput } from '../common/props';+import { moxieActionOutputSchemas } from '../output-schemas';++export const moxieDeleteCalendarEventAction = createAction({+ auth: moxieCRMAuth,+ name: 'moxie_delete_calendar_event',+ classification: 'DESTRUCTIVE',+ displayName: 'Delete Calendar Event',+ description: 'Delete a Moxie calendar event.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Permanently deletes a Moxie calendar event by its id. Use to remove an event that was cancelled elsewhere. Not idempotent: a second call for the same id fails with a not-found error.',+ idempotent: false,+ },+ outputSchema: moxieActionOutputSchemas.deletedCalendarEvent,+ props: {+ eventId: Property.ShortText({+ displayName: 'Event ID',+ description: 'Id of the event, from Create or Update Calendar Event.',+ required: true,+ }),+ },+ async run({ auth, propsValue }) {+ const id = moxieInput.id({ value: propsValue.eventId, field: 'Event ID' });+ await moxieRequest<unknown>({+ credentials: credentialsOf({ auth }),+ method: HttpMethod.DELETE,+ path: `/action/calendar/${encodeURIComponent(id)}`,+ notFoundMessage: `No calendar event with id ${id} in this Moxie workspace (it may already be deleted).`,+ });+ return { id, deleted: true };+ },+});diff --git a/packages/pieces/community/moxie-crm/src/lib/actions/get-email-template.ts b/packages/pieces/community/moxie-crm/src/lib/actions/get-email-template.tsnew file mode 100644index 00000000000..cf361d4338d--- /dev/null+++ b/packages/pieces/community/moxie-crm/src/lib/actions/get-email-template.ts@@ -0,0 +1,37 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { Property, createAction } from '@activepieces/pieces-framework';+import { moxieCRMAuth } from '../auth';+import { credentialsOf } from '../common';+import { moxieRequest } from '../common/client';+import { moxieInput } from '../common/props';+import { moxieActionOutputSchemas } from '../output-schemas';++export const moxieGetEmailTemplateAction = createAction({+ auth: moxieCRMAuth,+ name: 'moxie_get_email_template',+ classification: 'READ',+ displayName: 'Get Email Template',+ description: 'Get the subject and HTML content of an email template.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Returns the subject and raw HTML content of a Moxie email template by id; merge tokens are returned as written, not filled in. Use to reuse Moxie email wording in another tool. Read-only and idempotent.',+ idempotent: true,+ },+ outputSchema: moxieActionOutputSchemas.emailTemplate,+ props: {+ templateId: Property.ShortText({+ displayName: 'Template ID',+ description: 'Template id, from List Email Templates.',+ required: true,+ }),+ },+ async run({ auth, propsValue }) {+ return moxieRequest<unknown>({+ credentials: credentialsOf({ auth }),+ method: HttpMethod.GET,+ path: `/action/emailTemplates/${encodeURIComponent(moxieInput.id({ value: propsValue.templateId, field: 'Template ID' }))}`,+ notFoundMessage: 'Email template not found in this Moxie workspace.',+ });+ },+});diff --git a/packages/pieces/community/moxie-crm/src/lib/actions/get-workspace-account.ts b/packages/pieces/community/moxie-crm/src/lib/actions/get-workspace-account.tsnew file mode 100644index 00000000000..9f096df9237--- /dev/null+++ b/packages/pieces/community/moxie-crm/src/lib/actions/get-workspace-account.ts@@ -0,0 +1,37 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { moxieCRMAuth } from '../auth';+import { credentialsOf, isRecord } from '../common';+import { moxieRequest } from '../common/client';+import { moxieActionOutputSchemas } from '../output-schemas';++export const moxieGetWorkspaceAccountAction = createAction({+ auth: moxieCRMAuth,+ name: 'moxie_get_workspace_account',+ classification: 'READ',+ displayName: 'Get Workspace Account',+ description: 'Get the business name, address, tax id and currency of the workspace.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Returns the workspace business identity from Moxie: account name, address, tax id and label, and currency (never bank or payment details). Use when another system needs the supplier details printed on invoices. Read-only and idempotent.',+ idempotent: true,+ },+ outputSchema: moxieActionOutputSchemas.account,+ props: {++ },+ async run({ auth }) {+ const credentials = credentialsOf({ auth });+ const account = await moxieRequest<unknown>({ credentials, method: HttpMethod.GET, path: '/api/auth' });+ const accountId = isRecord(account) ? account['accountId'] : undefined;+ if (typeof accountId !== 'number' && typeof accountId !== 'string') {+ throw new Error('Moxie did not return the account id for this API key.');+ }+ return moxieRequest<unknown>({+ credentials,+ method: HttpMethod.GET,+ path: `/action/account/${encodeURIComponent(String(accountId))}`,+ });+ },+});diff --git a/packages/pieces/community/moxie-crm/src/lib/actions/list-clients.ts b/packages/pieces/community/moxie-crm/src/lib/actions/list-clients.tsindex 1174c5ce960..fe988d046d7 100644--- a/packages/pieces/community/moxie-crm/src/lib/actions/list-clients.ts+++ b/packages/pieces/community/moxie-crm/src/lib/actions/list-clients.ts@@ -6,7 +6,7 @@ import { listClientsActionOutputSchema } from '../output-schemas';export const moxieListClientsAction = createAction({auth: moxieCRMAuth,name: 'moxie_list_clients',- classification: 'READ',+ classification: 'SEARCH',displayName: 'List Clients',description: 'Retrieve every client and prospect in the workspace.',audience: 'both',diff --git a/packages/pieces/community/moxie-crm/src/lib/actions/list-email-templates.ts b/packages/pieces/community/moxie-crm/src/lib/actions/list-email-templates.tsnew file mode 100644index 00000000000..f13a8b55756--- /dev/null+++ b/packages/pieces/community/moxie-crm/src/lib/actions/list-email-templates.ts@@ -0,0 +1,31 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { moxieCRMAuth } from '../auth';+import { credentialsOf } from '../common';+import { moxieRequest } from '../common/client';+import { moxieActionOutputSchemas } from '../output-schemas';++export const moxieListEmailTemplatesAction = createAction({+ auth: moxieCRMAuth,+ name: 'moxie_list_email_templates',+ classification: 'SEARCH',+ displayName: 'List Email Templates',+ description: 'List the email templates of the workspace.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Returns the id and name of every email template in the Moxie workspace. Use to pick a template name for sending an invoice, or an id for Get Email Template. Read-only and idempotent.',+ idempotent: true,+ },+ outputSchema: moxieActionOutputSchemas.emailTemplateList,+ props: {++ },+ async run({ auth }) {+ return moxieRequest<unknown>({+ credentials: credentialsOf({ auth }),+ method: HttpMethod.GET,+ path: '/action/emailTemplates',+ });+ },+});diff --git a/packages/pieces/community/moxie-crm/src/lib/actions/list-form-names.ts b/packages/pieces/community/moxie-crm/src/lib/actions/list-form-names.tsnew file mode 100644index 00000000000..12ee1843bd5--- /dev/null+++ b/packages/pieces/community/moxie-crm/src/lib/actions/list-form-names.ts@@ -0,0 +1,32 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { moxieCRMAuth } from '../auth';+import { credentialsOf, asArray } from '../common';+import { moxieRequest } from '../common/client';+import { moxieActionOutputSchemas } from '../output-schemas';++export const moxieListFormNamesAction = createAction({+ auth: moxieCRMAuth,+ name: 'moxie_list_form_names',+ classification: 'SEARCH',+ displayName: 'List Form Names',+ description: 'List the names of the lead and discovery forms.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Returns the names of the lead and discovery forms in the Moxie workspace. Use to pick a valid form name before Submit Lead Form. Read-only and idempotent.',+ idempotent: true,+ },+ outputSchema: moxieActionOutputSchemas.nameList,+ props: {++ },+ async run({ auth }) {+ const result = await moxieRequest<unknown>({+ credentials: credentialsOf({ auth }),+ method: HttpMethod.GET,+ path: '/action/formNames/list',+ });+ return asArray({ value: result }).filter((name): name is string => typeof name === 'string').map((name) => ({ name }));+ },+});diff --git a/packages/pieces/community/moxie-crm/src/lib/actions/list-invoice-templates.ts b/packages/pieces/community/moxie-crm/src/lib/actions/list-invoice-templates.tsindex f8b04ee22cc..fa44bcb0a14 100644--- a/packages/pieces/community/moxie-crm/src/lib/actions/list-invoice-templates.ts+++ b/packages/pieces/community/moxie-crm/src/lib/actions/list-invoice-templates.ts@@ -5,7 +5,7 @@ import { moxieCRMAuth } from '../auth';export const moxieListInvoiceTemplatesAction = createAction({auth: moxieCRMAuth,name: 'moxie_list_invoice_templates',- classification: 'READ',+ classification: 'SEARCH',displayName: 'List Invoice Templates',description: 'Retrieve the invoice template names of the workspace.',audience: 'both',diff --git a/packages/pieces/community/moxie-crm/src/lib/actions/list-pipeline-stages.ts b/packages/pieces/community/moxie-crm/src/lib/actions/list-pipeline-stages.tsindex 54268e33a83..e84edabb120 100644--- a/packages/pieces/community/moxie-crm/src/lib/actions/list-pipeline-stages.ts+++ b/packages/pieces/community/moxie-crm/src/lib/actions/list-pipeline-stages.ts@@ -6,13 +6,13 @@ import { listPipelineStagesActionOutputSchema } from '../output-schemas';export const moxieListPipelineStagesAction = createAction({auth: moxieCRMAuth,name: 'moxie_list_pipeline_stages',- classification: 'READ',+ classification: 'SEARCH',displayName: 'List Pipeline Stages',description: 'Retrieve the opportunity pipeline stages of the workspace.',audience: 'both',aiMetadata: {description:- 'Returns the Moxie pipeline stages, each with its id, label, colour and stage type (New, InProgress, OnHold, ClosedWon, ClosedLost or Complete). Use to resolve a stage id before creating or moving an opportunity. Read-only and idempotent.',+ 'Returns the Moxie pipeline stages, each with its id, label, colour and stage type (New, InProgress, OnHold, ClosedWon, ClosedLost or Complete). Use to get the stage label for Create Opportunity or the stage id for Update Opportunity. Read-only and idempotent.',idempotent: true,},outputSchema: listPipelineStagesActionOutputSchema,diff --git a/packages/pieces/community/moxie-crm/src/lib/actions/list-project-types.ts b/packages/pieces/community/moxie-crm/src/lib/actions/list-project-types.tsnew file mode 100644index 00000000000..70993c24d7c--- /dev/null+++ b/packages/pieces/community/moxie-crm/src/lib/actions/list-project-types.ts@@ -0,0 +1,31 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { moxieCRMAuth } from '../auth';+import { credentialsOf } from '../common';+import { moxieRequest } from '../common/client';+import { moxieActionOutputSchemas } from '../output-schemas';++export const moxieListProjectTypesAction = createAction({+ auth: moxieCRMAuth,+ name: 'moxie_list_project_types',+ classification: 'SEARCH',+ displayName: 'List Project Types',+ description: 'List the project types with their task stages and custom fields.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Returns the Moxie project types with their task stages and the custom project and task fields each defines. Use to find the stage ids of a specific project type before moving tasks. Read-only and idempotent.',+ idempotent: true,+ },+ outputSchema: moxieActionOutputSchemas.projectTypeList,+ props: {++ },+ async run({ auth }) {+ return moxieRequest<unknown>({+ credentials: credentialsOf({ auth }),+ method: HttpMethod.GET,+ path: '/action/projectTypes/list',+ });+ },+});diff --git a/packages/pieces/community/moxie-crm/src/lib/actions/list-task-stages.ts b/packages/pieces/community/moxie-crm/src/lib/actions/list-task-stages.tsnew file mode 100644index 00000000000..1e4f619b785--- /dev/null+++ b/packages/pieces/community/moxie-crm/src/lib/actions/list-task-stages.ts@@ -0,0 +1,37 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { Property, createAction } from '@activepieces/pieces-framework';+import { moxieCRMAuth } from '../auth';+import { credentialsOf } from '../common';+import { moxieRequest } from '../common/client';+import { moxieInput } from '../common/props';+import { moxieActionOutputSchemas } from '../output-schemas';++export const moxieListTaskStagesAction = createAction({+ auth: moxieCRMAuth,+ name: 'moxie_list_task_stages',+ classification: 'SEARCH',+ displayName: 'List Task Stages',+ description: 'List the task stages of a project type.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Returns the task stages (kanban columns) of a project type, or of the default project type when no id is given, with their id, label and completion and approval flags. Use to get a stage label for Create Task or a stage id for Update Task and List Tasks. Read-only and idempotent.',+ idempotent: true,+ },+ outputSchema: moxieActionOutputSchemas.taskStageList,+ props: {+ projectTypeId: Property.ShortText({+ displayName: 'Project Type ID',+ description: 'Project type id, from List Project Types or a project record. Leave empty for the default project type.',+ required: false,+ }),+ },+ async run({ auth, propsValue }) {+ return moxieRequest<unknown>({+ credentials: credentialsOf({ auth }),+ method: HttpMethod.GET,+ path: '/action/taskStages/list',+ query: { projectTypeId: moxieInput.optionalId({ value: propsValue.projectTypeId, field: 'Project Type ID' }) },+ });+ },+});diff --git a/packages/pieces/community/moxie-crm/src/lib/actions/list-tasks.ts b/packages/pieces/community/moxie-crm/src/lib/actions/list-tasks.tsnew file mode 100644index 00000000000..62195823987--- /dev/null+++ b/packages/pieces/community/moxie-crm/src/lib/actions/list-tasks.ts@@ -0,0 +1,56 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { Property, createAction } from '@activepieces/pieces-framework';+import { moxieCRMAuth } from '../auth';+import { credentialsOf } from '../common';+import { moxieRequest } from '../common/client';+import { moxieInput, moxieProps } from '../common/props';+import { moxieActionOutputSchemas } from '../output-schemas';++export const moxieListTasksAction = createAction({+ auth: moxieCRMAuth,+ name: 'moxie_list_tasks',+ classification: 'SEARCH',+ displayName: 'List Tasks',+ description: 'List tasks, optionally filtered by project, client, stage or archived state.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Lists Moxie tasks filtered by any mix of project id, client id, stage id and archived state; with no filters it returns every active task (archived ones only when Archived is Yes). Use to review the work on a project or find tasks in a given stage; use Search Tasks to match by name. Read-only and idempotent.',+ idempotent: true,+ },+ outputSchema: moxieActionOutputSchemas.taskList,+ props: {+ projectId: Property.ShortText({+ displayName: 'Project ID',+ description: 'Only tasks of this project, from Search Projects.',+ required: false,+ }),+ clientId: Property.ShortText({+ displayName: 'Client ID',+ description: 'Only tasks of this client, from Search Clients.',+ required: false,+ }),+ statusId: Property.ShortText({+ displayName: 'Stage ID',+ description: 'Only tasks in this stage, from List Task Stages.',+ required: false,+ }),+ archived: moxieProps.triState({+ displayName: 'Archived',+ description: 'Yes returns only archived tasks. No or empty returns active ones (the Moxie default).',+ }),+ },+ async run({ auth, propsValue }) {+ return moxieRequest<unknown>({+ credentials: credentialsOf({ auth }),+ method: HttpMethod.GET,+ path: '/action/tasks/list',+ query: {+ projectId: moxieInput.optionalId({ value: propsValue.projectId, field: 'Project ID' }),+ clientId: moxieInput.optionalId({ value: propsValue.clientId, field: 'Client ID' }),+ statusId: moxieInput.optionalId({ value: propsValue.statusId, field: 'Stage ID' }),+ archived: moxieInput.triState({ value: propsValue.archived, field: 'Archived' }),+ },+ });+ },+});diff --git a/packages/pieces/community/moxie-crm/src/lib/actions/list-tickets.ts b/packages/pieces/community/moxie-crm/src/lib/actions/list-tickets.tsnew file mode 100644index 00000000000..f728797b49a--- /dev/null+++ b/packages/pieces/community/moxie-crm/src/lib/actions/list-tickets.ts@@ -0,0 +1,49 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { Property, createAction } from '@activepieces/pieces-framework';+import { moxieCRMAuth } from '../auth';+import { credentialsOf } from '../common';+import { moxieRequest } from '../common/client';+import { moxieInput, moxieProps } from '../common/props';+import { moxieActionOutputSchemas } from '../output-schemas';++export const moxieListTicketsAction = createAction({+ auth: moxieCRMAuth,+ name: 'moxie_list_tickets',+ classification: 'SEARCH',+ displayName: 'List Tickets',+ description: 'List tickets, optionally filtered by client, open state or archived state.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Lists Moxie tickets filtered by any mix of client id, open state and archived state; with no filters it returns every active ticket (archived ones only when Archived is Yes). Use to review open requests for a client or build a support report; use Search Tickets to match by text. Read-only and idempotent.',+ idempotent: true,+ },+ outputSchema: moxieActionOutputSchemas.ticketList,+ props: {+ clientId: Property.ShortText({+ displayName: 'Client ID',+ description: 'Only tickets of this client, from Search Clients.',+ required: false,+ }),+ open: moxieProps.triState({+ displayName: 'Open',+ description: 'Yes returns only open tickets, No only closed ones. Leave empty for both.',+ }),+ archived: moxieProps.triState({+ displayName: 'Archived',+ description: 'Yes returns only archived tickets. No or empty returns active ones (the Moxie default).',+ }),+ },+ async run({ auth, propsValue }) {+ return moxieRequest<unknown>({+ credentials: credentialsOf({ auth }),+ method: HttpMethod.GET,+ path: '/action/tickets/list',+ query: {+ clientId: moxieInput.optionalId({ value: propsValue.clientId, field: 'Client ID' }),+ open: moxieInput.triState({ value: propsValue.open, field: 'Open' }),+ archived: moxieInput.triState({ value: propsValue.archived, field: 'Archived' }),+ },+ });+ },+});diff --git a/packages/pieces/community/moxie-crm/src/lib/actions/list-vendors.ts b/packages/pieces/community/moxie-crm/src/lib/actions/list-vendors.tsnew file mode 100644index 00000000000..2f7327df742--- /dev/null+++ b/packages/pieces/community/moxie-crm/src/lib/actions/list-vendors.ts@@ -0,0 +1,32 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { moxieCRMAuth } from '../auth';+import { credentialsOf, asArray } from '../common';+import { moxieRequest } from '../common/client';+import { moxieActionOutputSchemas } from '../output-schemas';++export const moxieListVendorsAction = createAction({+ auth: moxieCRMAuth,+ name: 'moxie_list_vendors',+ classification: 'SEARCH',+ displayName: 'List Vendors',+ description: 'List the vendor names of the workspace.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Returns the names of the vendors in the Moxie workspace. Use to pick a valid vendor name before creating an expense. Read-only and idempotent.',+ idempotent: true,+ },+ outputSchema: moxieActionOutputSchemas.nameList,+ props: {++ },+ async run({ auth }) {+ const result = await moxieRequest<unknown>({+ credentials: credentialsOf({ auth }),+ method: HttpMethod.GET,+ path: '/action/vendors/list',+ });+ return asArray({ value: result }).filter((name): name is string => typeof name === 'string').map((name) => ({ name }));+ },+});diff --git a/packages/pieces/community/moxie-crm/src/lib/actions/list-workspace-users.ts b/packages/pieces/community/moxie-crm/src/lib/actions/list-workspace-users.tsindex 0e1bbdc9e41..7e9b7d25b47 100644--- a/packages/pieces/community/moxie-crm/src/lib/actions/list-workspace-users.ts+++ b/packages/pieces/community/moxie-crm/src/lib/actions/list-workspace-users.ts@@ -6,7 +6,7 @@ import { listWorkspaceUsersActionOutputSchema } from '../output-schemas';export const moxieListWorkspaceUsersAction = createAction({auth: moxieCRMAuth,name: 'moxie_list_workspace_users',- classification: 'READ',+ classification: 'SEARCH',displayName: 'List Workspace Users',description: 'Retrieve the users of the workspace and their access.',audience: 'both',diff --git a/packages/pieces/community/moxie-crm/src/lib/actions/search-agreements.ts b/packages/pieces/community/moxie-crm/src/lib/actions/search-agreements.tsnew file mode 100644index 00000000000..d5332086754--- /dev/null+++ b/packages/pieces/community/moxie-crm/src/lib/actions/search-agreements.ts@@ -0,0 +1,45 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { Property, createAction } from '@activepieces/pieces-framework';+import { moxieCRMAuth } from '../auth';+import { credentialsOf } from '../common';+import { moxieRequest } from '../common/client';+import { moxieInput } from '../common/props';+import { moxieActionOutputSchemas } from '../output-schemas';++export const moxieSearchAgreementsAction = createAction({+ auth: moxieCRMAuth,+ name: 'moxie_search_agreements',+ classification: 'SEARCH',+ displayName: 'Search Agreements',+ description: 'List agreements (contracts), for one client or by id.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Lists Moxie agreements (contracts) with their status and signatures: every one, those of a client id, or the one agreement with an exact Agreement ID. Use to check whether a client has signed before starting work or invoicing. Read-only and idempotent.',+ idempotent: true,+ },+ outputSchema: moxieActionOutputSchemas.agreementList,+ props: {+ clientId: Property.ShortText({+ displayName: 'Client ID',+ description: 'Only agreements of this client, from Search Clients.',+ required: false,+ }),+ id: Property.ShortText({+ displayName: 'Agreement ID',+ description: 'Exact agreement id. When set, the client id is ignored.',+ required: false,+ }),+ },+ async run({ auth, propsValue }) {+ return moxieRequest<unknown>({+ credentials: credentialsOf({ auth }),+ method: HttpMethod.GET,+ path: '/action/agreements/search',+ query: {+ clientId: moxieInput.optionalId({ value: propsValue.clientId, field: 'Client ID' }),+ id: moxieInput.optionalId({ value: propsValue.id, field: 'Agreement ID' }),+ },+ });+ },+});diff --git a/packages/pieces/community/moxie-crm/src/lib/actions/search-clients.ts b/packages/pieces/community/moxie-crm/src/lib/actions/search-clients.tsindex 6d9afae3226..28a7a0c4f94 100644--- a/packages/pieces/community/moxie-crm/src/lib/actions/search-clients.ts+++ b/packages/pieces/community/moxie-crm/src/lib/actions/search-clients.ts@@ -1,18 +1,19 @@import { Property, createAction } from '@activepieces/pieces-framework';import { makeClient } from '../common';+import { moxieInput } from '../common/props';import { moxieCRMAuth } from '../auth';import { searchClientsActionOutputSchema } from '../output-schemas';export const moxieSearchClientsAction = createAction({auth: moxieCRMAuth,name: 'moxie_search_clients',- classification: 'READ',+ classification: 'SEARCH',displayName: 'Search Clients',- description: 'Find clients by name, contact email or contact full name.',+ description: 'Find clients by name, phone, contact email or contact name, or look one up by id.',audience: 'both',aiMetadata: {description:- 'Searches Moxie clients by client name (starts with), contact email (starts with) or contact full name (contains), and returns the matching client records with their address, billing terms and contacts. Returns an empty list when nothing matches. Read-only and idempotent.',+ 'Searches Moxie clients by client name or phone (starts with), contact email or phone (starts with) or contact full name (contains), or returns the one client with an exact Client ID. Use to resolve a client id or exact client name before creating projects, tasks, invoices or contacts for it. Returns an empty list when nothing matches. Read-only and idempotent.',idempotent: true,},outputSchema: searchClientsActionOutputSchema,@@ -20,12 +21,18 @@ export const moxieSearchClientsAction = createAction({query: Property.ShortText({displayName: 'Query',description:- 'Matches a client name or contact email that starts with this value, or a contact full name that contains it.',- required: true,+ 'Matches a client name, client phone, contact email or contact phone that starts with this value, or a contact full name that contains it.',+ required: false,+ }),+ id: Property.ShortText({+ displayName: 'Client ID',+ description: 'Exact client id. When set, the query is ignored.',+ required: false,}),},async run({ auth, propsValue }) {+ const { query, id } = moxieInput.queryOrId({ query: propsValue.query, id: propsValue.id, idField: 'Client ID' });const client = await makeClient(auth);- return await client.searchClients(propsValue.query);+ return await client.searchClients({ query, id });},});diff --git a/packages/pieces/community/moxie-crm/src/lib/actions/search-contacts.ts b/packages/pieces/community/moxie-crm/src/lib/actions/search-contacts.tsindex 6aff716c2de..d3805494203 100644--- a/packages/pieces/community/moxie-crm/src/lib/actions/search-contacts.ts+++ b/packages/pieces/community/moxie-crm/src/lib/actions/search-contacts.ts@@ -1,18 +1,19 @@import { Property, createAction } from '@activepieces/pieces-framework';import { makeClient } from '../common';+import { moxieInput } from '../common/props';import { moxieCRMAuth } from '../auth';import { searchContactsActionOutputSchema } from '../output-schemas';export const moxieSearchContactsAction = createAction({auth: moxieCRMAuth,name: 'moxie_search_contacts',- classification: 'READ',+ classification: 'SEARCH',displayName: 'Search Contacts',- description: 'Find contacts by first name, last name or email.',+ description: 'Find contacts by first name, last name or email, or look one up by id.',audience: 'both',aiMetadata: {description:- 'Searches Moxie contacts by first name, last name or email and returns the matching contact records, including the client each belongs to. Leave the query empty to list every contact. Read-only and idempotent.',+ 'Searches Moxie contacts whose first name, last name or email contains the query, or returns the one contact with an exact Contact ID; leave both empty to list every active contact. Each contact carries its clientId (resolve the client with Search Clients by id). Read-only and idempotent.',idempotent: true,},outputSchema: searchContactsActionOutputSchema,@@ -23,9 +24,17 @@ export const moxieSearchContactsAction = createAction({'Matches a contact first name, last name or email. Leave empty to return every contact.',required: false,}),+ id: Property.ShortText({+ displayName: 'Contact ID',+ description: 'Exact contact id. When set, the query is ignored.',+ required: false,+ }),},async run({ auth, propsValue }) {const client = await makeClient(auth);- return await client.searchContacts(propsValue.query);+ return await client.searchContacts({+ query: moxieInput.text({ value: propsValue.query }),+ id: moxieInput.optionalId({ value: propsValue.id, field: 'Contact ID' }),+ });},});diff --git a/packages/pieces/community/moxie-crm/src/lib/actions/search-payable-invoices.ts b/packages/pieces/community/moxie-crm/src/lib/actions/search-payable-invoices.tsnew file mode 100644index 00000000000..e19b875a2ef--- /dev/null+++ b/packages/pieces/community/moxie-crm/src/lib/actions/search-payable-invoices.ts@@ -0,0 +1,45 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { Property, createAction } from '@activepieces/pieces-framework';+import { moxieCRMAuth } from '../auth';+import { credentialsOf } from '../common';+import { moxieRequest } from '../common/client';+import { moxieInput } from '../common/props';+import { moxieActionOutputSchemas } from '../output-schemas';++export const moxieSearchPayableInvoicesAction = createAction({+ auth: moxieCRMAuth,+ name: 'moxie_search_payable_invoices',+ classification: 'SEARCH',+ displayName: 'Search Open Invoices',+ description: 'List outstanding invoices, for one client or by invoice id.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Lists outstanding (sent and not fully paid) Moxie invoices with totals, payments and line items: every one, those of the client whose exact name is given (an unknown name returns an empty list), or the one invoice with an exact Invoice ID. Use to find an invoice number before recording a payment or chasing a balance. Read-only and idempotent.',+ idempotent: true,+ },+ outputSchema: moxieActionOutputSchemas.invoiceList,+ props: {+ clientName: Property.ShortText({+ displayName: 'Client Name',+ description: 'Exact client name. Leave empty to list the open invoices of every client.',+ required: false,+ }),+ id: Property.ShortText({+ displayName: 'Invoice ID',+ description: 'Exact invoice id. When set, the client name is ignored.',+ required: false,+ }),+ },+ async run({ auth, propsValue }) {+ return moxieRequest<unknown>({+ credentials: credentialsOf({ auth }),+ method: HttpMethod.GET,+ path: '/action/payableInvoices/search',+ query: {+ query: moxieInput.text({ value: propsValue.clientName }),+ id: moxieInput.optionalId({ value: propsValue.id, field: 'Invoice ID' }),+ },+ });+ },+});diff --git a/packages/pieces/community/moxie-crm/src/lib/actions/search-projects.ts b/packages/pieces/community/moxie-crm/src/lib/actions/search-projects.tsindex 11576f68a66..0a66f20dff9 100644--- a/packages/pieces/community/moxie-crm/src/lib/actions/search-projects.ts+++ b/packages/pieces/community/moxie-crm/src/lib/actions/search-projects.ts@@ -1,30 +1,39 @@import { Property, createAction } from '@activepieces/pieces-framework';import { makeClient } from '../common';+import { moxieInput } from '../common/props';import { moxieCRMAuth } from '../auth';import { searchProjectsActionOutputSchema } from '../output-schemas';export const moxieSearchProjectsAction = createAction({auth: moxieCRMAuth,name: 'moxie_search_projects',- classification: 'READ',+ classification: 'SEARCH',displayName: 'Search Projects',- description: 'Find projects belonging to a client.',+ description: "List a client's projects, look up one project by id, or list every project.",audience: 'both',aiMetadata: {description:- 'Searches Moxie projects and returns the matches. Use to resolve a project name or id before creating a task or logging time against it. Read-only and idempotent.',+ 'Returns the projects of the client whose exact name is given in Query (fails with a not-found error when no client has that name), the one project with an exact Project ID, or every project when both are empty. Use to resolve a project id or exact project name before creating tasks, logging time or invoicing. Read-only and idempotent.',idempotent: true,},outputSchema: searchProjectsActionOutputSchema,props: {query: Property.ShortText({- displayName: 'Query',- description: 'Client name whose projects should be returned.',- required: true,+ displayName: 'Client Name',+ description: 'Exact client name whose projects should be returned. Leave empty to list all projects.',+ required: false,+ }),+ id: Property.ShortText({+ displayName: 'Project ID',+ description: 'Exact project id. When set, the client name is ignored.',+ required: false,}),},async run({ auth, propsValue }) {const client = await makeClient(auth);- return await client.searchProjects(propsValue.query);+ return await client.searchProjects({+ query: moxieInput.text({ value: propsValue.query }),+ id: moxieInput.optionalId({ value: propsValue.id, field: 'Project ID' }),+ });},});diff --git a/packages/pieces/community/moxie-crm/src/lib/actions/search-tasks.ts b/packages/pieces/community/moxie-crm/src/lib/actions/search-tasks.tsnew file mode 100644index 00000000000..04a79b36532--- /dev/null+++ b/packages/pieces/community/moxie-crm/src/lib/actions/search-tasks.ts@@ -0,0 +1,42 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { Property, createAction } from '@activepieces/pieces-framework';+import { moxieCRMAuth } from '../auth';+import { credentialsOf } from '../common';+import { moxieRequest } from '../common/client';+import { moxieInput } from '../common/props';+import { moxieActionOutputSchemas } from '../output-schemas';++export const moxieSearchTasksAction = createAction({+ auth: moxieCRMAuth,+ name: 'moxie_search_tasks',+ classification: 'SEARCH',+ displayName: 'Search Tasks',+ description: 'Find tasks by name or description, or look one up by id.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Searches Moxie tasks whose name or description contains the query (case-insensitive), or returns the one task with an exact Task ID. Use to find a task id before updating or approving it; use List Tasks to filter by project, client or stage instead. Read-only and idempotent.',+ idempotent: true,+ },+ outputSchema: moxieActionOutputSchemas.taskList,+ props: {+ query: Property.ShortText({+ displayName: 'Query',+ description: 'Text to match in the task name or description.',+ required: false,+ }),+ id: Property.ShortText({+ displayName: 'Task ID',+ description: 'Exact task id. When set, the query is ignored.',+ required: false,+ }),+ },+ async run({ auth, propsValue }) {+ return moxieRequest<unknown>({+ credentials: credentialsOf({ auth }),+ method: HttpMethod.GET,+ path: '/action/tasks/search',+ query: moxieInput.queryOrId({ query: propsValue.query, id: propsValue.id, idField: 'Task ID' }),+ });+ },+});diff --git a/packages/pieces/community/moxie-crm/src/lib/actions/search-tickets.ts b/packages/pieces/community/moxie-crm/src/lib/actions/search-tickets.tsnew file mode 100644index 00000000000..1e2f1e67d15--- /dev/null+++ b/packages/pieces/community/moxie-crm/src/lib/actions/search-tickets.ts@@ -0,0 +1,53 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { Property, createAction } from '@activepieces/pieces-framework';+import { moxieCRMAuth } from '../auth';+import { credentialsOf } from '../common';+import { moxieRequest } from '../common/client';+import { moxieInput } from '../common/props';+import { moxieActionOutputSchemas } from '../output-schemas';++export const moxieSearchTicketsAction = createAction({+ auth: moxieCRMAuth,+ name: 'moxie_search_tickets',+ classification: 'SEARCH',+ displayName: 'Search Tickets',+ description: 'Find tickets by text, id or ticket number.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Searches Moxie tickets whose subject, status, summary or number matches the query (case-insensitive), or returns the one ticket with an exact Ticket ID or Ticket Number. Use to find a ticket before commenting on it or changing its status; use List Tickets to filter by client or open state. Read-only and idempotent.',+ idempotent: true,+ },+ outputSchema: moxieActionOutputSchemas.ticketList,+ props: {+ query: Property.ShortText({+ displayName: 'Query',+ description: 'Text to match in the subject, status, summary or number.',+ required: false,+ }),+ id: Property.ShortText({+ displayName: 'Ticket ID',+ description: 'Exact ticket id. Overrides the number and the query.',+ required: false,+ }),+ ticketNumber: Property.Number({+ displayName: 'Ticket Number',+ description: 'Exact ticket number. Overrides the query.',+ required: false,+ }),+ },+ async run({ auth, propsValue }) {+ const query = moxieInput.text({ value: propsValue.query });+ const id = moxieInput.optionalId({ value: propsValue.id, field: 'Ticket ID' });+ const ticketNumber = moxieInput.integer({ value: propsValue.ticketNumber, field: 'Ticket Number', min: 1 });+ if (query === undefined && id === undefined && ticketNumber === undefined) {+ throw new Error('Enter a Query, a Ticket ID or a Ticket Number.');+ }+ return moxieRequest<unknown>({+ credentials: credentialsOf({ auth }),+ method: HttpMethod.GET,+ path: '/action/tickets/search',+ query: { query, id, ticketNumber },+ });+ },+});diff --git a/packages/pieces/community/moxie-crm/src/lib/actions/update-client.ts b/packages/pieces/community/moxie-crm/src/lib/actions/update-client.tsnew file mode 100644index 00000000000..659e9058e35--- /dev/null+++ b/packages/pieces/community/moxie-crm/src/lib/actions/update-client.ts@@ -0,0 +1,31 @@+import { createAction } from '@activepieces/pieces-framework';+import { moxieCRMAuth } from '../auth';+import { credentialsOf } from '../common';+import { moxieDropdowns } from '../common/dropdowns';+import { moxieFields } from '../common/fields';+import { moxieOperations } from '../common/operations';+import { moxieProps } from '../common/props';+import { moxieActionOutputSchemas } from '../output-schemas';++export const moxieUpdateClientAction = createAction({+ auth: moxieCRMAuth,+ name: 'moxie_update_client',+ classification: 'WRITE',+ displayName: 'Update Client',+ description: 'Update details of an existing client. Empty fields keep their current value.',+ audience: 'human',+ aiMetadata: {+ description:+ 'Updates fields on a Moxie client picked from a list; only filled fields change. For agents use moxie_client_update, which takes the client id directly. Idempotent.',+ idempotent: true,+ },+ outputSchema: moxieActionOutputSchemas.client,+ props: {+ clientId: moxieDropdowns.clientId({ required: true }),+ ...moxieProps.fromSpecs({ specs: moxieFields.clientUpdate, audience: 'human' }),+ clearFields: moxieProps.clearFields({ specs: moxieFields.clientUpdate }),+ },+ async run({ auth, propsValue }) {+ return moxieOperations.updateClient({ credentials: credentialsOf({ auth }), values: propsValue });+ },+});diff --git a/packages/pieces/community/moxie-crm/src/lib/actions/update-contact.ts b/packages/pieces/community/moxie-crm/src/lib/actions/update-contact.tsnew file mode 100644index 00000000000..df16bf1681f--- /dev/null+++ b/packages/pieces/community/moxie-crm/src/lib/actions/update-contact.ts@@ -0,0 +1,36 @@+import { createAction } from '@activepieces/pieces-framework';+import { moxieCRMAuth } from '../auth';+import { credentialsOf } from '../common';+import { moxieDropdowns } from '../common/dropdowns';+import { moxieFields } from '../common/fields';+import { moxieOperations } from '../common/operations';+import { moxieProps } from '../common/props';+import { moxieActionOutputSchemas } from '../output-schemas';++export const moxieUpdateContactAction = createAction({+ auth: moxieCRMAuth,+ name: 'moxie_update_contact',+ classification: 'WRITE',+ displayName: 'Update Contact',+ description: 'Update details of an existing contact. Empty fields keep their current value.',+ audience: 'human',+ aiMetadata: {+ description:+ 'Updates fields on a Moxie contact picked from a list; only filled fields change. For agents use moxie_contact_update. Idempotent.',+ idempotent: true,+ },+ outputSchema: moxieActionOutputSchemas.contact,+ props: {+ contactId: moxieDropdowns.contactId({ required: true }),+ ...moxieProps.fromSpecs({ specs: moxieFields.contactUpdate, audience: 'human' }),+ clientId: moxieDropdowns.clientId({+ required: false,+ displayName: 'Move to Client',+ description: 'Moves the contact to this client. Leave empty to keep the current client.',+ }),+ clearFields: moxieProps.clearFields({ specs: moxieFields.contactUpdate }),+ },+ async run({ auth, propsValue }) {+ return moxieOperations.updateContact({ credentials: credentialsOf({ auth }), values: propsValue });+ },+});diff --git a/packages/pieces/community/moxie-crm/src/lib/actions/update-expense.ts b/packages/pieces/community/moxie-crm/src/lib/actions/update-expense.tsnew file mode 100644index 00000000000..265071c5ff2--- /dev/null+++ b/packages/pieces/community/moxie-crm/src/lib/actions/update-expense.ts@@ -0,0 +1,34 @@+import { Property, createAction } from '@activepieces/pieces-framework';+import { moxieCRMAuth } from '../auth';+import { credentialsOf } from '../common';+import { moxieFields } from '../common/fields';+import { moxieOperations } from '../common/operations';+import { moxieProps } from '../common/props';+import { moxieActionOutputSchemas } from '../output-schemas';++export const moxieUpdateExpenseAction = createAction({+ auth: moxieCRMAuth,+ name: 'moxie_update_expense',+ classification: 'WRITE',+ displayName: 'Update Expense',+ description: 'Update fields on an existing expense.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Updates an existing Moxie expense by id (amount, tax, category, dates, paid and billable flags, client or project); only the fields you pass change and Clear Fields blanks text fields. The expense id comes from Create Expense (Moxie has no expense search). Idempotent: repeating the same update leaves the expense unchanged.',+ idempotent: true,+ },+ outputSchema: moxieActionOutputSchemas.expense,+ props: {+ expenseId: Property.ShortText({+ displayName: 'Expense ID',+ description: 'Id of the expense, from Create Expense.',+ required: true,+ }),+ ...moxieProps.fromSpecs({ specs: moxieFields.expenseUpdate, audience: 'ai' }),+ clearFields: moxieProps.clearFields({ specs: moxieFields.expenseUpdate }),+ },+ async run({ auth, propsValue }) {+ return moxieOperations.updateExpense({ credentials: credentialsOf({ auth }), values: propsValue });+ },+});diff --git a/packages/pieces/community/moxie-crm/src/lib/actions/update-opportunity.ts b/packages/pieces/community/moxie-crm/src/lib/actions/update-opportunity.tsnew file mode 100644index 00000000000..ab15e9ddd84--- /dev/null+++ b/packages/pieces/community/moxie-crm/src/lib/actions/update-opportunity.ts@@ -0,0 +1,42 @@+import { Property, createAction } from '@activepieces/pieces-framework';+import { moxieCRMAuth } from '../auth';+import { credentialsOf } from '../common';+import { moxieDropdowns } from '../common/dropdowns';+import { moxieFields } from '../common/fields';+import { moxieOperations } from '../common/operations';+import { moxieProps } from '../common/props';+import { moxieActionOutputSchemas } from '../output-schemas';++export const moxieUpdateOpportunityAction = createAction({+ auth: moxieCRMAuth,+ name: 'moxie_update_opportunity',+ classification: 'WRITE',+ displayName: 'Update Opportunity',+ description: 'Move a deal to another pipeline stage or update its details. Empty fields keep their current value.',+ audience: 'human',+ aiMetadata: {+ description:+ 'Updates a Moxie opportunity by id with stage and client picked from lists; only filled fields change. For agents use moxie_opportunity_update. Idempotent.',+ idempotent: true,+ },+ outputSchema: moxieActionOutputSchemas.opportunity,+ props: {+ opportunityId: Property.ShortText({+ displayName: 'Opportunity ID',+ description: 'Map the id from an opportunity trigger or the Create Opportunity step.',+ required: true,+ }),+ statusId: moxieDropdowns.pipelineStage({+ required: false,+ valueKey: 'id',+ displayName: 'Move to Stage',+ description: 'Leave empty to keep the current stage.',+ }),+ clientId: moxieDropdowns.clientId({ required: false, description: 'Links the deal to this client. Leave empty to keep the current client.' }),+ ...moxieProps.fromSpecs({ specs: moxieFields.opportunityUpdate, audience: 'human' }),+ clearFields: moxieProps.clearFields({ specs: moxieFields.opportunityUpdate }),+ },+ async run({ auth, propsValue }) {+ return moxieOperations.updateOpportunity({ credentials: credentialsOf({ auth }), values: propsValue });+ },+});diff --git a/packages/pieces/community/moxie-crm/src/lib/actions/update-project.ts b/packages/pieces/community/moxie-crm/src/lib/actions/update-project.tsnew file mode 100644index 00000000000..3248f943fee--- /dev/null+++ b/packages/pieces/community/moxie-crm/src/lib/actions/update-project.ts@@ -0,0 +1,32 @@+import { createAction } from '@activepieces/pieces-framework';+import { moxieCRMAuth } from '../auth';+import { credentialsOf } from '../common';+import { moxieDropdowns } from '../common/dropdowns';+import { moxieFields } from '../common/fields';+import { moxieOperations } from '../common/operations';+import { moxieProps } from '../common/props';+import { moxieActionOutputSchemas } from '../output-schemas';++export const moxieUpdateProjectAction = createAction({+ auth: moxieCRMAuth,+ name: 'moxie_update_project',+ classification: 'WRITE',+ displayName: 'Update Project',+ description: 'Update details of an existing project. Empty fields keep their current value.',+ audience: 'human',+ aiMetadata: {+ description:+ 'Updates fields on a Moxie project picked by client and project; only filled fields change. For agents use moxie_project_update. Idempotent.',+ idempotent: true,+ },+ outputSchema: moxieActionOutputSchemas.project,+ props: {+ clientName: moxieDropdowns.clientName({ required: true }),+ projectId: moxieDropdowns.projectByClientName({ required: true, valueKey: 'id' }),+ ...moxieProps.fromSpecs({ specs: moxieFields.projectUpdate, audience: 'human' }),+ clearFields: moxieProps.clearFields({ specs: moxieFields.projectUpdate }),+ },+ async run({ auth, propsValue }) {+ return moxieOperations.updateProject({ credentials: credentialsOf({ auth }), values: propsValue });+ },+});diff --git a/packages/pieces/community/moxie-crm/src/lib/actions/update-task.ts b/packages/pieces/community/moxie-crm/src/lib/actions/update-task.tsnew file mode 100644index 00000000000..fbc39da5b87--- /dev/null+++ b/packages/pieces/community/moxie-crm/src/lib/actions/update-task.ts@@ -0,0 +1,38 @@+import { createAction } from '@activepieces/pieces-framework';+import { moxieCRMAuth } from '../auth';+import { credentialsOf } from '../common';+import { moxieDropdowns } from '../common/dropdowns';+import { moxieFields } from '../common/fields';+import { moxieOperations } from '../common/operations';+import { moxieProps } from '../common/props';+import { moxieActionOutputSchemas } from '../output-schemas';++export const moxieUpdateTaskAction = createAction({+ auth: moxieCRMAuth,+ name: 'moxie_update_task',+ classification: 'WRITE',+ displayName: 'Update Task',+ description: 'Update a task, move it to another stage or change its assignees. Empty fields keep their current value.',+ audience: 'human',+ aiMetadata: {+ description:+ 'Updates a Moxie task picked by client, project and task, including its stage and assignees; only filled fields change. For agents use moxie_task_update. Idempotent.',+ idempotent: true,+ },+ outputSchema: moxieActionOutputSchemas.task,+ props: {+ clientName: moxieDropdowns.clientName({ required: true }),+ projectId: moxieDropdowns.projectByClientName({ required: true, valueKey: 'id' }),+ taskId: moxieDropdowns.taskIdByProject({ required: true }),+ statusId: moxieDropdowns.taskStageIdByProject({ required: false }),+ assignedToList: moxieDropdowns.userIds({+ required: false,+ description: 'Replaces the current assignees. Leave empty to keep them.',+ }),+ ...moxieProps.fromSpecs({ specs: moxieFields.taskUpdate, audience: 'human' }),+ clearFields: moxieProps.clearFields({ specs: moxieFields.taskUpdate }),+ },+ async run({ auth, propsValue }) {+ return moxieOperations.updateTask({ credentials: credentialsOf({ auth }), values: propsValue });+ },+});diff --git a/packages/pieces/community/moxie-crm/src/lib/actions/update-ticket-status.ts b/packages/pieces/community/moxie-crm/src/lib/actions/update-ticket-status.tsnew file mode 100644index 00000000000..471e871d3cf--- /dev/null+++ b/packages/pieces/community/moxie-crm/src/lib/actions/update-ticket-status.ts@@ -0,0 +1,55 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { Property, createAction } from '@activepieces/pieces-framework';+import { moxieCRMAuth } from '../auth';+import { credentialsOf } from '../common';+import { moxieRequest } from '../common/client';+import { moxieInput } from '../common/props';+import { moxieActionOutputSchemas } from '../output-schemas';++export const moxieUpdateTicketStatusAction = createAction({+ auth: moxieCRMAuth,+ name: 'moxie_update_ticket_status',+ classification: 'WRITE',+ displayName: 'Update Ticket Status',+ description: 'Change the status of a ticket.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Changes only the workflow status of a Moxie ticket, identified by its id or its ticket number (give exactly one). The status must be one configured for the ticket type; an unknown status is rejected. Use to close or move a ticket after handling it. Idempotent: setting the same status again leaves the ticket unchanged.',+ idempotent: true,+ },+ outputSchema: moxieActionOutputSchemas.ticket,+ props: {+ ticketId: Property.ShortText({+ displayName: 'Ticket ID',+ description: 'Exact ticket id, from Search Tickets. Give this or the ticket number.',+ required: false,+ }),+ ticketNumber: Property.Number({+ displayName: 'Ticket Number',+ description: 'The ticket number. Give this or the ticket id.',+ required: false,+ }),+ status: Property.ShortText({+ displayName: 'Status',+ description: 'Status label configured for the ticket type, for example Open.',+ required: true,+ }),+ },+ async run({ auth, propsValue }) {+ const id = moxieInput.optionalId({ value: propsValue.ticketId, field: 'Ticket ID' });+ const ticketNumber = moxieInput.integer({ value: propsValue.ticketNumber, field: 'Ticket Number', min: 1 });+ if ((id === undefined) === (ticketNumber === undefined)) {+ throw new Error('Give exactly one of Ticket ID or Ticket Number.');+ }+ return moxieRequest<unknown>({+ credentials: credentialsOf({ auth }),+ method: HttpMethod.PATCH,+ path: '/action/tickets/status',+ body: moxieInput.compact({+ values: { id, ticketNumber, status: moxieInput.requiredText({ value: propsValue.status, field: 'Status' }) },+ }),+ notFoundMessage: `No ticket ${id ?? `number ${ticketNumber}`} in this Moxie workspace.`,+ });+ },+});diff --git a/packages/pieces/community/moxie-crm/src/lib/actions/upload-attachment.ts b/packages/pieces/community/moxie-crm/src/lib/actions/upload-attachment.tsnew file mode 100644index 00000000000..b6568ac63d9--- /dev/null+++ b/packages/pieces/community/moxie-crm/src/lib/actions/upload-attachment.ts@@ -0,0 +1,61 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { Property, createAction } from '@activepieces/pieces-framework';+import { moxieCRMAuth } from '../auth';+import { credentialsOf } from '../common';+import { moxieRequest, multipartFileBody } from '../common/client';+import { ATTACHMENT_OBJECT_TYPES } from '../common/fields';+import { moxieInput } from '../common/props';+import { moxieActionOutputSchemas } from '../output-schemas';++export const moxieUploadAttachmentAction = createAction({+ auth: moxieCRMAuth,+ name: 'moxie_upload_attachment',+ classification: 'WRITE',+ displayName: 'Upload Attachment',+ description: 'Upload a file and attach it to a client, project, task, opportunity, expense or ticket.',+ audience: 'human',+ aiMetadata: {+ description:+ 'Uploads a file from the flow and attaches it to a Moxie record by id. For agents use moxie_attach_file_from_url. Not idempotent: each run adds another copy.',+ idempotent: false,+ },+ outputSchema: moxieActionOutputSchemas.attachment,+ props: {+ objectType: Property.StaticDropdown({+ displayName: 'Attach To',+ required: true,+ options: {+ disabled: false,+ options: ATTACHMENT_OBJECT_TYPES.map((type) => ({ label: type.charAt(0) + type.slice(1).toLowerCase(), value: type })),+ },+ }),+ objectId: Property.ShortText({+ displayName: 'Record ID',+ description: 'Id of the record, for example mapped from a trigger or a Search step.',+ required: true,+ }),+ file: Property.File({+ displayName: 'File',+ required: true,+ }),+ },+ async run({ auth, propsValue }) {+ const objectType = moxieInput.requiredText({ value: propsValue.objectType, field: 'Attach To' }).toUpperCase();+ if (!ATTACHMENT_OBJECT_TYPES.includes(objectType)) {+ throw new Error(`Attach To must be one of: ${ATTACHMENT_OBJECT_TYPES.join(', ')}.`);+ }+ const objectId = moxieInput.id({ value: propsValue.objectId, field: 'Record ID' });+ const file = moxieInput.file({ value: propsValue.file, field: 'File' });+ const multipart = multipartFileBody({ fieldName: 'file', filename: file.filename, data: file.data });+ const url = await moxieRequest<unknown>({+ credentials: credentialsOf({ auth }),+ method: HttpMethod.POST,+ path: '/action/attachments/create',+ query: { id: objectId, type: objectType },+ body: multipart.body,+ contentType: multipart.contentType,+ notFoundMessage: `No ${objectType.toLowerCase()} with id ${objectId} in this Moxie workspace.`,+ });+ return { url: typeof url === 'string' ? url : null, objectType, objectId, fileName: file.filename };+ },+});diff --git a/packages/pieces/community/moxie-crm/src/lib/auth.ts b/packages/pieces/community/moxie-crm/src/lib/auth.tsindex 41d965169fc..688cd5f52ba 100644--- a/packages/pieces/community/moxie-crm/src/lib/auth.ts+++ b/packages/pieces/community/moxie-crm/src/lib/auth.ts@@ -1,14 +1,22 @@+import { HttpMethod } from '@activepieces/pieces-common';import { PieceAuth, Property } from '@activepieces/pieces-framework';+import {+ MOXIE_BASE_URL_EXAMPLE,+ MOXIE_SETTINGS_PATH,+ moxieRequest,+ responseStatusOf,+} from './common/client';+import { MoxieSimpleAccount } from './common/models';export const moxieCRMAuth = PieceAuth.CustomAuth({required: true,description: `- To obtain your Moxie CRM token, follow these steps:+ To connect your Moxie workspace:- 1. Log in to your Moxie CRM account and click on **Workspace Settings** (Bottom left).- 2. Click on **Connected Apps** and navigate to **Integrations** tab.- 3. Now, under "Custom Integration", click on **Enable Custom Integration**.- 4. Copy **API Key** and **Base URL** and click on Save button.+ 1. Log in to Moxie and click **Workspace Settings** (bottom left).+ 2. Open **Connected Apps** and go to the **Integrations** tab.+ 3. Under **Custom Integration**, click **Enable Custom Integration**.+ 4. Copy the **API Key** and the **Base URL** (it looks like \`${MOXIE_BASE_URL_EXAMPLE}\`) and click **Save**.`,props: {apiKey: PieceAuth.SecretText({@@ -18,8 +26,32 @@ export const moxieCRMAuth = PieceAuth.CustomAuth({}),baseUrl: Property.ShortText({displayName: 'Base URL',- description: 'The Base URL of the Moxie CRM account',+ description: `The Base URL shown next to the API key, for example ${MOXIE_BASE_URL_EXAMPLE}`,required: true,}),},+ validate: async ({ auth }) => {+ try {+ const account = await moxieRequest<MoxieSimpleAccount>({+ credentials: { baseUrl: auth.baseUrl, apiKey: auth.apiKey },+ method: HttpMethod.GET,+ path: '/api/auth',+ });+ if (typeof account !== 'object' || account === null || account.accountId === undefined) {+ return { valid: false, error: notApiUrlMessage };+ }+ return { valid: true };+ } catch (error) {+ const status = responseStatusOf({ error });+ if (status === 401 || status === 403) {+ return { valid: false, error: `Invalid API key. Copy it again from ${MOXIE_SETTINGS_PATH}.` };+ }+ if (status === 404 || status === 200) {+ return { valid: false, error: notApiUrlMessage };+ }+ return { valid: false, error: error instanceof Error ? error.message : String(error) };+ }+ },});++const notApiUrlMessage = `This Base URL is not the Moxie API URL. Copy the Base URL from ${MOXIE_SETTINGS_PATH}; it looks like ${MOXIE_BASE_URL_EXAMPLE}.`;diff --git a/packages/pieces/community/moxie-crm/src/lib/common/client.ts b/packages/pieces/community/moxie-crm/src/lib/common/client.tsindex be9be4e8b8c..fb866ce223e 100644--- a/packages/pieces/community/moxie-crm/src/lib/common/client.ts+++ b/packages/pieces/community/moxie-crm/src/lib/common/client.ts@@ -1,137 +1,365 @@import {- HttpMethod,HttpMessageBody,- httpClient,- HttpResponse,+ HttpMethod,QueryParams,+ httpClient,} from '@activepieces/pieces-common';-import { isNil } from '@activepieces/pieces-framework';+import { randomBytes } from 'crypto';import {- ContactCreateRequest,ClientCreateRequest,ClientListResponse,- TaskCreateRequest,+ ContactCreateRequest,+ MoxieCredentials,ProjectCreateRequest,ProjectSearchResponse,ProjectTaskStageListResponse,+ TaskCreateRequest,} from './models';-export class MoxieCRMClient {- constructor(private baseUrl: string, private apiKey: string) {- // Remove trailing slash from base URL- this.baseUrl = baseUrl.replace(/\/$/, '');- }- async makeRequest<T extends HttpMessageBody>(- method: HttpMethod,- resourceUri: string,- body: any | undefined = undefined,- query?: QueryParams- ): Promise<HttpResponse<T>> {- return await httpClient.sendRequest<T>({- method: method,- url: `${this.baseUrl}${resourceUri}`,+export const MOXIE_SETTINGS_PATH =+ 'Workspace Settings > Connected Apps > Integrations > Custom Integration';++export const MOXIE_BASE_URL_EXAMPLE = 'https://pod01.withmoxie.com/api/public';++export class MoxieApiError extends Error {+ readonly status: number | undefined;+ readonly responseBody: unknown;++ constructor({+ message,+ status,+ responseBody,+ }: {+ message: string;+ status?: number;+ responseBody?: unknown;+ }) {+ super(message);+ this.name = 'MoxieApiError';+ this.status = status;+ this.responseBody = responseBody;+ }+}++export function normalizeBaseUrl({ baseUrl }: { baseUrl: unknown }): string {+ const raw = typeof baseUrl === 'string' ? baseUrl.trim() : '';+ const hint = `Copy the Base URL from ${MOXIE_SETTINGS_PATH} (for example ${MOXIE_BASE_URL_EXAMPLE}).`;+ if (raw === '') {+ throw new MoxieApiError({ message: `The Moxie Base URL is empty. ${hint}` });+ }+ let parsed: URL;+ try {+ parsed = new URL(raw);+ } catch {+ throw new MoxieApiError({ message: `The Moxie Base URL "${raw}" is not a valid URL. ${hint}` });+ }+ const host = parsed.hostname.toLowerCase();+ const isMoxieHost = host === 'withmoxie.com' || host.endsWith('.withmoxie.com');+ if (+ parsed.protocol !== 'https:' ||+ parsed.username !== '' ||+ parsed.password !== '' ||+ parsed.port !== '' ||+ parsed.search !== '' ||+ parsed.hash !== '' ||+ !isMoxieHost+ ) {+ throw new MoxieApiError({+ message: `The Moxie Base URL must be an https address on withmoxie.com, with no user name, port or query. ${hint}`,+ });+ }+ return `${parsed.origin}${parsed.pathname.replace(/\/+$/, '')}`;+}++export function assertMoxieRequestUrl({ baseUrl, url }: { baseUrl: unknown; url: unknown }): void {+ const base = new URL(normalizeBaseUrl({ baseUrl }));+ if (typeof url !== 'string' || !/^https?:\/\//i.test(url.trim())) {+ return;+ }+ let target: URL;+ try {+ target = new URL(url.trim());+ } catch {+ throw new MoxieApiError({ message: `The URL "${url}" is not a valid URL.` });+ }+ if (target.origin !== base.origin || target.username !== '' || target.password !== '') {+ throw new MoxieApiError({+ message: `Custom API Call only sends the Moxie API key to your Base URL host (${base.origin}). Use a path such as /action/clients/list instead of a full URL on another host.`,+ });+ }+}++export function moxieHeaders({ apiKey }: { apiKey: string }): Record<string, string> {+ return { 'X-API-KEY': apiKey.trim() };+}++export function responseStatusOf({ error }: { error: unknown }): number | undefined {+ if (error instanceof MoxieApiError) {+ return error.status;+ }+ const response = responseOf({ error });+ return response?.status;+}++export function looksLikeWebPage({+ headers,+ body,+}: {+ headers: Record<string, unknown> | undefined;+ body: unknown;+}): boolean {+ const contentType = headerValue({ headers, name: 'content-type' }) ?? '';+ if (contentType.toLowerCase().includes('text/html')) {+ return true;+ }+ return typeof body === 'string' && body.trimStart().startsWith('<');+}++export async function moxieRequest<T extends HttpMessageBody>({+ credentials,+ method,+ path,+ body,+ query,+ notFoundMessage,+ contentType,+}: MoxieRequest): Promise<T> {+ const baseUrl = normalizeBaseUrl({ baseUrl: credentials.baseUrl });+ const queryParams = toQueryParams({ query });+ const response = await httpClient+ .sendRequest<T>({+ method,+ url: `${baseUrl}${path}`,headers: {- 'X-API-KEY': this.apiKey,+ ...moxieHeaders({ apiKey: credentials.apiKey }),+ ...(contentType === undefined ? {} : { 'Content-Type': contentType }),},- body: body,- queryParams: query,+ body,+ queryParams,+ })+ .catch((error: unknown) => {+ throw toMoxieError({ error, notFoundMessage });+ });+ if (looksLikeWebPage({ headers: response.headers, body: response.body })) {+ throw new MoxieApiError({+ message: `Moxie returned a web page instead of API data. Check the connection's Base URL: copy it from ${MOXIE_SETTINGS_PATH} (for example ${MOXIE_BASE_URL_EXAMPLE}).`,+ status: response.status,+ });+ }+ return response.body;+}++export function multipartFileBody({ fieldName, filename, data }: { fieldName: string; filename: string; data: Buffer }): {+ body: Buffer;+ contentType: string;+} {+ const boundary = `----moxie${randomBytes(12).toString('hex')}`;+ const safeName = filename.replace(/["\\\r\n]/g, '_');+ const head = Buffer.from(+ `--${boundary}\r\nContent-Disposition: form-data; name="${fieldName}"; filename="${safeName}"\r\nContent-Type: application/octet-stream\r\n\r\n`,+ );+ const tail = Buffer.from(`\r\n--${boundary}--\r\n`);+ return { body: Buffer.concat([head, data, tail]), contentType: `multipart/form-data; boundary=${boundary}` };+}++export class MoxieCRMClient {+ private readonly credentials: MoxieCredentials;++ constructor({ baseUrl, apiKey }: MoxieCredentials) {+ this.credentials = { baseUrl, apiKey };+ }++ request<T extends HttpMessageBody>(params: Omit<MoxieRequest, 'credentials'>): Promise<T> {+ return moxieRequest<T>({ ...params, credentials: this.credentials });+ }++ createContact(request: ContactCreateRequest): Promise<unknown> {+ return this.request({ method: HttpMethod.POST, path: '/action/contacts/create', body: request });+ }++ createClient(request: ClientCreateRequest): Promise<unknown> {+ return this.request({ method: HttpMethod.POST, path: '/action/clients/create', body: request });+ }++ listClients(): Promise<ClientListResponse[]> {+ return this.request<ClientListResponse[]>({ method: HttpMethod.GET, path: '/action/clients/list' });+ }++ listInvoiceTemplates(): Promise<string[]> {+ return this.request<string[]>({ method: HttpMethod.GET, path: '/action/invoiceTemplates/list' });+ }++ createProject(request: ProjectCreateRequest): Promise<unknown> {+ return this.request({ method: HttpMethod.POST, path: '/action/projects/create', body: request });+ }++ createTask(request: TaskCreateRequest): Promise<unknown> {+ return this.request({ method: HttpMethod.POST, path: '/action/tasks/create', body: request });+ }++ searchProjects({ query, id }: { query?: string; id?: string }): Promise<ProjectSearchResponse[]> {+ return this.request<ProjectSearchResponse[]>({+ method: HttpMethod.GET,+ path: '/action/projects/search',+ query: { query, id },+ notFoundMessage:+ query !== undefined && query !== ''+ ? `No client named "${query}" in this Moxie workspace. The query must be the exact client name.`+ : undefined,+ });+ }++ listProjectTaskStages({ projectTypeId }: { projectTypeId?: string } = {}): Promise<ProjectTaskStageListResponse[]> {+ return this.request<ProjectTaskStageListResponse[]>({+ method: HttpMethod.GET,+ path: '/action/taskStages/list',+ query: { projectTypeId },});}- async createContact(request: ContactCreateRequest) {- return (- await this.makeRequest(- HttpMethod.POST,- '/action/contacts/create',- request- )- ).body;- }- async createClient(request: ClientCreateRequest) {- return (- await this.makeRequest(HttpMethod.POST, '/action/clients/create', request)- ).body;- }- async listClients(): Promise<ClientListResponse[]> {- return (- await this.makeRequest<ClientListResponse[]>(- HttpMethod.GET,- '/action/clients/list'- )- ).body;- }- async listInvoiceTemplates(): Promise<string[]> {- return (- await this.makeRequest<string[]>(- HttpMethod.GET,- '/action/invoiceTemplates/list'- )- ).body;- }-- async createProject(request: ProjectCreateRequest) {- return (- await this.makeRequest(- HttpMethod.POST,- '/action/projects/create',- request- )- ).body;- }- async createTask(request: TaskCreateRequest) {- return (- await this.makeRequest(HttpMethod.POST, '/action/tasks/create', request)- ).body;- }-- async searchProjects(clientName: string): Promise<ProjectSearchResponse[]> {- return (- await this.makeRequest<ProjectSearchResponse[]>(- HttpMethod.GET,- '/action/projects/search',- undefined,- { query: clientName }- )- ).body;- }-- async listProjectTaskStages(): Promise<ProjectTaskStageListResponse[]> {- return (- await this.makeRequest<ProjectTaskStageListResponse[]>(- HttpMethod.GET,- '/action/taskStages/list'- )- ).body;- }-- async searchClients(query: string) {- return (- await this.makeRequest(- HttpMethod.GET,- '/action/clients/search',- undefined,- { query }- )- ).body;- }-- async searchContacts(query?: string) {- return (- await this.makeRequest(- HttpMethod.GET,- '/action/contacts/search',- undefined,- isNil(query) || query.length === 0 ? undefined : { query }- )- ).body;- }-- async listPipelineStages() {- return (- await this.makeRequest(HttpMethod.GET, '/action/pipelineStages/list')- ).body;- }-- async listWorkspaceUsers() {- return (await this.makeRequest(HttpMethod.GET, '/action/users/list')).body;++ searchClients({ query, id }: { query?: string; id?: string }): Promise<unknown> {+ return this.request({ method: HttpMethod.GET, path: '/action/clients/search', query: { query, id } });+ }++ searchContacts({ query, id }: { query?: string; id?: string } = {}): Promise<unknown> {+ return this.request({ method: HttpMethod.GET, path: '/action/contacts/search', query: { query, id } });+ }++ listPipelineStages(): Promise<unknown> {+ return this.request({ method: HttpMethod.GET, path: '/action/pipelineStages/list' });+ }++ listWorkspaceUsers(): Promise<unknown> {+ return this.request({ method: HttpMethod.GET, path: '/action/users/list' });}}++function toQueryParams({ query }: { query: MoxieQuery | undefined }): QueryParams | undefined {+ if (query === undefined) {+ return undefined;+ }+ const result: QueryParams = {};+ for (const [key, value] of Object.entries(query)) {+ if (value === undefined || value === null) {+ continue;+ }+ const text = String(value);+ if (text.trim() === '') {+ continue;+ }+ result[key] = text;+ }+ return Object.keys(result).length === 0 ? undefined : result;+}++function responseOf({ error }: { error: unknown }): { status?: number; body?: unknown } | undefined {+ if (typeof error !== 'object' || error === null) {+ return undefined;+ }+ const response: unknown = Reflect.get(error, 'response');+ if (typeof response !== 'object' || response === null) {+ return undefined;+ }+ const status: unknown = Reflect.get(response, 'status');+ return {+ status: typeof status === 'number' ? status : undefined,+ body: Reflect.get(response, 'body'),+ };+}++function headerValue({+ headers,+ name,+}: {+ headers: Record<string, unknown> | undefined;+ name: string;+}): string | undefined {+ if (headers === undefined) {+ return undefined;+ }+ for (const [key, value] of Object.entries(headers)) {+ if (key.toLowerCase() !== name) {+ continue;+ }+ if (typeof value === 'string') {+ return value;+ }+ if (Array.isArray(value) && typeof value[0] === 'string') {+ return value[0];+ }+ }+ return undefined;+}++function vendorMessage({ body }: { body: unknown }): string | undefined {+ if (typeof body === 'string') {+ const text = body.trim();+ if (text === '') {+ return undefined;+ }+ if (text.startsWith('<')) {+ return 'the server answered with a web page';+ }+ return text.slice(0, 300);+ }+ if (typeof body !== 'object' || body === null) {+ return undefined;+ }+ for (const key of ['message', 'detail', 'error']) {+ const value: unknown = Reflect.get(body, key);+ if (typeof value === 'string' && value.trim() !== '') {+ return value.trim().slice(0, 300);+ }+ }+ return undefined;+}++function toMoxieError({+ error,+ notFoundMessage,+}: {+ error: unknown;+ notFoundMessage: string | undefined;+}): Error {+ if (error instanceof MoxieApiError) {+ return error;+ }+ const response = responseOf({ error });+ if (response?.status === undefined) {+ return error instanceof Error ? error : new Error(String(error));+ }+ const { status, body } = response;+ const detail = vendorMessage({ body });+ const suffix = detail === undefined ? '' : ` Moxie said: ${detail}`;+ let message: string;+ if (status === 401) {+ message = `Moxie rejected the API key (HTTP 401). Copy the API Key again from ${MOXIE_SETTINGS_PATH}.${suffix}`;+ } else if (status === 403) {+ message = `Moxie refused access (HTTP 403). Check that the API key belongs to this workspace.${suffix}`;+ } else if (status === 404 && detail !== undefined && detail.startsWith('No endpoint')) {+ message = `Moxie does not know this API route (HTTP 404). Check the connection's Base URL: it should look like ${MOXIE_BASE_URL_EXAMPLE}.${suffix}`;+ } else if (status === 404) {+ message = `${notFoundMessage ?? 'Moxie could not find the requested record (HTTP 404).'}${suffix}`;+ } else if (status === 412) {+ message = `Moxie rejected the request because a required value is missing or invalid (HTTP 412).${suffix}`;+ } else if (status === 400) {+ message = `Moxie rejected the request body (HTTP 400).${suffix}`;+ } else if (status === 429) {+ message = `Moxie is rate limiting this workspace (HTTP 429). Wait a few minutes before retrying, or space out the requests.${suffix}`;+ } else {+ message = `Moxie request failed (HTTP ${status}).${suffix}`;+ }+ return new MoxieApiError({ message, status, responseBody: body });+}++type MoxieQuery = Record<string, string | number | boolean | undefined | null>;++type MoxieRequest = {+ credentials: MoxieCredentials;+ method: HttpMethod;+ path: string;+ body?: unknown;+ query?: MoxieQuery;+ notFoundMessage?: string;+ contentType?: string;+};diff --git a/packages/pieces/community/moxie-crm/src/lib/common/dropdowns.ts b/packages/pieces/community/moxie-crm/src/lib/common/dropdowns.tsnew file mode 100644index 00000000000..6cf949947fe--- /dev/null+++ b/packages/pieces/community/moxie-crm/src/lib/common/dropdowns.ts@@ -0,0 +1,528 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { Property } from '@activepieces/pieces-framework';+import { moxieCRMAuth } from '../auth';+import { moxieRequest, responseStatusOf } from './client';+import { asArray, credentialsOf, disabledOptions, isRecord, safeOptions, stringField } from '.';+import { MoxieCredentials } from './models';++export const moxieDropdowns = {+ clientName({ required, displayName = 'Client', description }: DropdownParams) {+ return Property.Dropdown<string, boolean, typeof moxieCRMAuth>({+ auth: moxieCRMAuth,+ displayName,+ description: description ?? 'The client, matched by its exact name.',+ required,+ refreshers: [],+ options: async ({ auth }) =>+ safeOptions({+ auth,+ emptyPlaceholder: 'No clients in this workspace yet.',+ load: async () =>+ (await listClients({ credentials: credentialsOf({ auth: requireAuth({ auth }) }) })).map((client) => ({+ label: client.name,+ value: client.name,+ })),+ }),+ });+ },++ clientId({ required, displayName = 'Client', description }: DropdownParams) {+ return Property.Dropdown<string, boolean, typeof moxieCRMAuth>({+ auth: moxieCRMAuth,+ displayName,+ description,+ required,+ refreshers: [],+ options: async ({ auth }) =>+ safeOptions({+ auth,+ emptyPlaceholder: 'No clients in this workspace yet.',+ load: async () =>+ (await listClients({ credentials: credentialsOf({ auth: requireAuth({ auth }) }) })).map((client) => ({+ label: client.name,+ value: client.id,+ })),+ }),+ });+ },++ projectByClientName({ required, valueKey, displayName = 'Project', description }: ProjectDropdownParams) {+ return Property.Dropdown<string, boolean, typeof moxieCRMAuth>({+ auth: moxieCRMAuth,+ displayName,+ description,+ required,+ refreshers: ['clientName'],+ options: async ({ auth, clientName }) => {+ if (typeof clientName !== 'string' || clientName === '') {+ return disabledOptions({ placeholder: 'Select a client first.' });+ }+ return safeOptions({+ auth,+ emptyPlaceholder: 'This client has no projects.',+ notFoundPlaceholder: 'This client has no projects.',+ load: async () =>+ (+ await listProjectsOfClient({+ credentials: credentialsOf({ auth: requireAuth({ auth }) }),+ clientName,+ })+ ).map((project) => ({ label: project.name, value: valueKey === 'id' ? project.id : project.name })),+ });+ },+ });+ },++ taskIdByProject({ required }: { required: boolean }) {+ return Property.Dropdown<string, boolean, typeof moxieCRMAuth>({+ auth: moxieCRMAuth,+ displayName: 'Task',+ required,+ refreshers: ['projectId'],+ options: async ({ auth, projectId }) => {+ if (typeof projectId !== 'string' || projectId === '') {+ return disabledOptions({ placeholder: 'Select a project first.' });+ }+ return safeOptions({+ auth,+ emptyPlaceholder: 'This project has no tasks.',+ load: async () =>+ (await listTasks({ credentials: credentialsOf({ auth: requireAuth({ auth }) }), projectId })).map((task) => ({+ label: task.name,+ value: task.id,+ })),+ });+ },+ });+ },++ taskNameByProjectName({ required }: { required: boolean }) {+ return Property.Dropdown<string, boolean, typeof moxieCRMAuth>({+ auth: moxieCRMAuth,+ displayName: 'Task',+ description: 'The task, matched by its exact name.',+ required,+ refreshers: ['clientName', 'projectName'],+ options: async ({ auth, clientName, projectName }) => {+ if (typeof clientName !== 'string' || clientName === '' || typeof projectName !== 'string' || projectName === '') {+ return disabledOptions({ placeholder: 'Select a client and a project first.' });+ }+ return safeOptions({+ auth,+ emptyPlaceholder: 'This project has no tasks.',+ notFoundPlaceholder: 'This client has no projects.',+ load: async () => {+ const credentials = credentialsOf({ auth: requireAuth({ auth }) });+ const projects = await listProjectsOfClient({ credentials, clientName });+ const project = projects.find((candidate) => candidate.name === projectName);+ if (project === undefined) {+ return [];+ }+ return (await listTasks({ credentials, projectId: project.id })).map((task) => ({+ label: task.name,+ value: task.name,+ }));+ },+ });+ },+ });+ },++ taskStageIdByProject({ required }: { required: boolean }) {+ return Property.Dropdown<string, boolean, typeof moxieCRMAuth>({+ auth: moxieCRMAuth,+ displayName: 'Stage',+ description: 'Moves the task to this stage. Leave empty to keep the current stage.',+ required,+ refreshers: ['projectId'],+ options: async ({ auth, projectId }) => {+ if (typeof projectId !== 'string' || projectId === '') {+ return disabledOptions({ placeholder: 'Select a project first.' });+ }+ return safeOptions({+ auth,+ emptyPlaceholder: 'No task stages found for this project.',+ load: async () => {+ const credentials = credentialsOf({ auth: requireAuth({ auth }) });+ const projects = asArray({+ value: await moxieRequest<unknown>({+ credentials,+ method: HttpMethod.GET,+ path: '/action/projects/search',+ query: { id: projectId },+ }),+ });+ const projectTypeId = stringField({ record: projects[0], key: 'projectTypeId' });+ if (projectTypeId === undefined) {+ throw new Error('Project not found or it has no project type.');+ }+ const stages = asArray({+ value: await moxieRequest<unknown>({+ credentials,+ method: HttpMethod.GET,+ path: '/action/taskStages/list',+ query: { projectTypeId },+ }),+ });+ return idLabelOptions({ items: stages, labelKey: 'label' });+ },+ });+ },+ });+ },++ taskStageLabelByProjectName({ required, description }: { required: boolean; description?: string }) {+ return Property.Dropdown<string, boolean, typeof moxieCRMAuth>({+ auth: moxieCRMAuth,+ displayName: 'Status',+ description,+ required,+ refreshers: ['clientName', 'projectName'],+ options: async ({ auth, clientName, projectName }) =>+ safeOptions({+ auth,+ emptyPlaceholder: 'No task stages found.',+ load: async () => {+ const credentials = credentialsOf({ auth: requireAuth({ auth }) });+ const projectTypeId =+ typeof clientName === 'string' && clientName !== '' && typeof projectName === 'string' && projectName !== ''+ ? (await listProjectsOfClient({ credentials, clientName }).catch((error: unknown) => ignoreNotFound({ error }))).find(+ (project) => project.name === projectName,+ )?.projectTypeId+ : undefined;+ const stages = asArray({+ value: await moxieRequest<unknown>({+ credentials,+ method: HttpMethod.GET,+ path: '/action/taskStages/list',+ query: { projectTypeId },+ }),+ });+ return stringOptions({ items: stages.map((stage) => stringField({ record: stage, key: 'label' })) });+ },+ }),+ });+ },++ contactId({ required }: { required: boolean }) {+ return Property.Dropdown<string, boolean, typeof moxieCRMAuth>({+ auth: moxieCRMAuth,+ displayName: 'Contact',+ required,+ refreshers: [],+ options: async ({ auth }) =>+ safeOptions({+ auth,+ emptyPlaceholder: 'No contacts in this workspace yet.',+ load: async () => {+ const contacts = asArray({+ value: await moxieRequest<unknown>({+ credentials: credentialsOf({ auth: requireAuth({ auth }) }),+ method: HttpMethod.GET,+ path: '/action/contacts/search',+ }),+ });+ return contacts.filter(isRecord).flatMap((contact) => {+ const id = stringField({ record: contact, key: 'id' });+ if (id === undefined) {+ return [];+ }+ const name = [stringField({ record: contact, key: 'firstName' }), stringField({ record: contact, key: 'lastName' })]+ .filter((part) => part !== undefined && part !== '')+ .join(' ');+ const email = stringField({ record: contact, key: 'email' });+ const label = email === undefined || email === '' ? name || id : `${name || email} <${email}>`;+ return [{ label, value: id }];+ });+ },+ }),+ });+ },++ pipelineStage({ required, valueKey, displayName = 'Pipeline Stage', description }: StageDropdownParams) {+ return Property.Dropdown<string, boolean, typeof moxieCRMAuth>({+ auth: moxieCRMAuth,+ displayName,+ description,+ required,+ refreshers: [],+ options: async ({ auth }) =>+ safeOptions({+ auth,+ emptyPlaceholder: 'No pipeline stages in this workspace.',+ load: async () => {+ const stages = asArray({+ value: await moxieRequest<unknown>({+ credentials: credentialsOf({ auth: requireAuth({ auth }) }),+ method: HttpMethod.GET,+ path: '/action/pipelineStages/list',+ }),+ });+ return valueKey === 'id'+ ? idLabelOptions({ items: stages, labelKey: 'label' })+ : stringOptions({ items: stages.map((stage) => stringField({ record: stage, key: 'label' })) });+ },+ }),+ });+ },++ stringList({ required, displayName, description, path, emptyPlaceholder }: StringListDropdownParams) {+ return Property.Dropdown<string, boolean, typeof moxieCRMAuth>({+ auth: moxieCRMAuth,+ displayName,+ description,+ required,+ refreshers: [],+ options: async ({ auth }) =>+ safeOptions({+ auth,+ emptyPlaceholder,+ load: async () =>+ stringOptions({+ items: asArray({+ value: await moxieRequest<unknown>({+ credentials: credentialsOf({ auth: requireAuth({ auth }) }),+ method: HttpMethod.GET,+ path,+ }),+ }),+ }),+ }),+ });+ },++ payableInvoice({ required }: { required: boolean }) {+ return Property.Dropdown<string, boolean, typeof moxieCRMAuth>({+ auth: moxieCRMAuth,+ displayName: 'Invoice',+ description: 'An open (sent, not fully paid) invoice of the selected client.',+ required,+ refreshers: ['clientName'],+ options: async ({ auth, clientName }) => {+ if (typeof clientName !== 'string' || clientName === '') {+ return disabledOptions({ placeholder: 'Select a client first.' });+ }+ return safeOptions({+ auth,+ emptyPlaceholder: 'This client has no open invoices.',+ load: async () => {+ const invoices = asArray({+ value: await moxieRequest<unknown>({+ credentials: credentialsOf({ auth: requireAuth({ auth }) }),+ method: HttpMethod.GET,+ path: '/action/payableInvoices/search',+ query: { query: clientName },+ }),+ });+ return invoices.filter(isRecord).flatMap((invoice) => {+ const number = stringField({ record: invoice, key: 'invoiceNumberFormatted' });+ if (number === undefined) {+ return [];+ }+ const due = invoice['amountDue'];+ const currency = stringField({ record: invoice, key: 'currency' });+ const amount = currency === undefined ? `${due}` : `${due} ${currency}`;+ const label = typeof due === 'number' ? `${number} (${amount} due)` : number;+ return [{ label, value: number }];+ });+ },+ });+ },+ });+ },++ userEmail({ required, displayName = 'User', description }: DropdownParams) {+ return Property.Dropdown<string, boolean, typeof moxieCRMAuth>({+ auth: moxieCRMAuth,+ displayName,+ description,+ required,+ refreshers: [],+ options: async ({ auth }) =>+ safeOptions({+ auth,+ load: async () =>+ (await listUsers({ credentials: credentialsOf({ auth: requireAuth({ auth }) }) })).flatMap((user) =>+ user.email === undefined ? [] : [{ label: user.label, value: user.email }],+ ),+ }),+ });+ },++ userIds({ required, displayName = 'Assignees', description }: DropdownParams) {+ return Property.MultiSelectDropdown<string, boolean, typeof moxieCRMAuth>({+ auth: moxieCRMAuth,+ displayName,+ description,+ required,+ refreshers: [],+ options: async ({ auth }) =>+ safeOptions({+ auth,+ load: async () =>+ (await listUsers({ credentials: credentialsOf({ auth: requireAuth({ auth }) }) })).flatMap((user) =>+ user.userId === undefined ? [] : [{ label: user.label, value: String(user.userId) }],+ ),+ }),+ });+ },++ clientContactEmails({ required }: { required: boolean }) {+ return Property.MultiSelectDropdown<string, boolean, typeof moxieCRMAuth>({+ auth: moxieCRMAuth,+ displayName: 'Send To Contacts',+ description: 'Contacts of the selected client who receive the invoice email. Used only when Send Invoice is on.',+ required,+ refreshers: ['clientName'],+ options: async ({ auth, clientName }) => {+ if (typeof clientName !== 'string' || clientName === '') {+ return disabledOptions({ placeholder: 'Select a client first.' });+ }+ return safeOptions({+ auth,+ emptyPlaceholder: 'This client has no contacts with an email address.',+ load: async () => {+ const credentials = credentialsOf({ auth: requireAuth({ auth }) });+ const client = (await listClients({ credentials })).find((candidate) => candidate.name === clientName);+ if (client === undefined) {+ return [];+ }+ const contacts = asArray({+ value: await moxieRequest<unknown>({ credentials, method: HttpMethod.GET, path: '/action/contacts/search' }),+ });+ return contacts.filter(isRecord).flatMap((contact) => {+ const email = stringField({ record: contact, key: 'email' });+ if (stringField({ record: contact, key: 'clientId' }) !== client.id || email === undefined || email === '') {+ return [];+ }+ return [{ label: email, value: email }];+ });+ },+ });+ },+ });+ },+};++function ignoreNotFound({ error }: { error: unknown }): { id: string; name: string; projectTypeId: string | undefined }[] {+ if (responseStatusOf({ error }) === 404) {+ return [];+ }+ throw error;+}++function requireAuth<T>({ auth }: { auth: T | undefined }): T {+ if (auth === undefined) {+ throw new Error('Connect your Moxie account first.');+ }+ return auth;+}++async function listClients({ credentials }: { credentials: MoxieCredentials }): Promise<{ id: string; name: string }[]> {+ const clients = asArray({+ value: await moxieRequest<unknown>({ credentials, method: HttpMethod.GET, path: '/action/clients/list' }),+ });+ return clients.flatMap((client) => {+ const id = stringField({ record: client, key: 'id' });+ const name = stringField({ record: client, key: 'name' });+ return id === undefined || name === undefined ? [] : [{ id, name }];+ });+}++async function listProjectsOfClient({+ credentials,+ clientName,+}: {+ credentials: MoxieCredentials;+ clientName: string;+}): Promise<{ id: string; name: string; projectTypeId: string | undefined }[]> {+ const projects = asArray({+ value: await moxieRequest<unknown>({+ credentials,+ method: HttpMethod.GET,+ path: '/action/projects/search',+ query: { query: clientName },+ }),+ });+ return projects.flatMap((project) => {+ const id = stringField({ record: project, key: 'id' });+ const name = stringField({ record: project, key: 'name' });+ const projectTypeId = stringField({ record: project, key: 'projectTypeId' });+ return id === undefined || name === undefined ? [] : [{ id, name, projectTypeId }];+ });+}++async function listTasks({+ credentials,+ projectId,+}: {+ credentials: MoxieCredentials;+ projectId: string;+}): Promise<{ id: string; name: string }[]> {+ const tasks = asArray({+ value: await moxieRequest<unknown>({+ credentials,+ method: HttpMethod.GET,+ path: '/action/tasks/list',+ query: { projectId },+ }),+ });+ return tasks.flatMap((task) => {+ const id = stringField({ record: task, key: 'id' });+ const name = stringField({ record: task, key: 'name' });+ return id === undefined || name === undefined ? [] : [{ id, name }];+ });+}++async function listUsers({+ credentials,+}: {+ credentials: MoxieCredentials;+}): Promise<{ userId: number | undefined; email: string | undefined; label: string }[]> {+ const accounts = asArray({+ value: await moxieRequest<unknown>({ credentials, method: HttpMethod.GET, path: '/action/users/list' }),+ });+ return accounts.flatMap((account) => {+ const user = isRecord(account) ? account['user'] : undefined;+ if (!isRecord(user)) {+ return [];+ }+ const userId = typeof user['userId'] === 'number' ? user['userId'] : undefined;+ const email = stringField({ record: user, key: 'email' });+ const name = [stringField({ record: user, key: 'firstName' }), stringField({ record: user, key: 'lastName' })]+ .filter((part) => part !== undefined && part !== '')+ .join(' ');+ const label = email === undefined ? name : name === '' ? email : `${name} <${email}>`;+ return [{ userId, email, label: label === '' ? String(userId) : label }];+ });+}++function idLabelOptions({ items, labelKey }: { items: unknown[]; labelKey: string }): { label: string; value: string }[] {+ return items.flatMap((item) => {+ const id = stringField({ record: item, key: 'id' });+ const label = stringField({ record: item, key: labelKey });+ return id === undefined ? [] : [{ label: label ?? id, value: id }];+ });+}++function stringOptions({ items }: { items: unknown[] }): { label: string; value: string }[] {+ return items.flatMap((item) => (typeof item === 'string' && item !== '' ? [{ label: item, value: item }] : []));+}++type DropdownParams = {+ required: boolean;+ displayName?: string;+ description?: string;+};++type ProjectDropdownParams = DropdownParams & { valueKey: 'id' | 'name' };++type StageDropdownParams = DropdownParams & { valueKey: 'id' | 'label' };++type StringListDropdownParams = {+ required: boolean;+ displayName: string;+ description?: string;+ path: string;+ emptyPlaceholder?: string;+};diff --git a/packages/pieces/community/moxie-crm/src/lib/common/fields.ts b/packages/pieces/community/moxie-crm/src/lib/common/fields.tsnew file mode 100644index 00000000000..9a4e23105e8--- /dev/null+++ b/packages/pieces/community/moxie-crm/src/lib/common/fields.ts@@ -0,0 +1,216 @@+import { MoxieFieldSpec } from './props';++export const CLIENT_DETAIL_FIELDS: MoxieFieldSpec[] = [+ { key: 'clientType', kind: 'enum', displayName: 'Client Type', options: ['Client', 'Prospect'], description: 'Client for a paying account, Prospect for a lead.' },+ { key: 'initials', kind: 'text', displayName: 'Initials', clearable: true },+ { key: 'address1', kind: 'text', displayName: 'Address Line 1', clearable: true },+ { key: 'address2', kind: 'text', displayName: 'Address Line 2', clearable: true },+ { key: 'city', kind: 'text', displayName: 'City', clearable: true },+ { key: 'locality', kind: 'text', displayName: 'State or Region', clearable: true },+ { key: 'postal', kind: 'text', displayName: 'Postal Code', clearable: true },+ { key: 'country', kind: 'text', displayName: 'Country', description: 'Two-letter ISO 3166-1 country code, for example US.', clearable: true },+ { key: 'website', kind: 'text', displayName: 'Website', clearable: true },+ { key: 'phone', kind: 'text', displayName: 'Phone', clearable: true },+ { key: 'color', kind: 'text', displayName: 'Colour', description: 'Hex colour, for example #78909C.' },+ { key: 'taxId', kind: 'text', displayName: 'Tax ID', clearable: true },+ { key: 'leadSource', kind: 'text', displayName: 'Lead Source', clearable: true },+ { key: 'payInstructions', kind: 'longText', displayName: 'Payment Instructions', clearable: true },+ { key: 'hourlyAmount', kind: 'number', displayName: 'Hourly Rate', min: 0 },+ { key: 'roundingIncrement', kind: 'integer', displayName: 'Time Rounding Increment', description: 'Minutes to round tracked time to.', min: 0 },+ { key: 'currency', kind: 'text', displayName: 'Currency', description: 'Three-letter ISO 4217 code, for example USD.' },+ { key: 'notes', kind: 'longText', displayName: 'Notes', clearable: true },+ { key: 'archive', kind: 'triState', displayName: 'Archived', description: 'Yes archives the client, No restores it. Leave empty to keep the current state.' },+];++export const CONTACT_FLAG_FIELDS: MoxieFieldSpec[] = [+ { key: 'defaultContact', kind: 'triState', displayName: 'Default Contact', description: "Yes makes this the client's primary contact." },+ { key: 'invoiceContact', kind: 'triState', displayName: 'Invoice Contact', description: 'Yes sends invoices for the client to this contact.' },+ { key: 'portalAccess', kind: 'triState', displayName: 'Portal Access', description: 'Yes lets this contact sign in to the client portal.' },+];++export const PORTAL_ACCESS_OPTIONS = ['Full access', 'Read only', 'Overview', 'None'];++export const FEE_TYPE_OPTIONS = ['Hourly', 'Fixed Price', 'Retainer', 'Per Item'];++export const PAYMENT_TYPE_OPTIONS = [+ 'STRIPE',+ 'CHECK',+ 'BANK_TRANSFER',+ 'CASH',+ 'VENMO',+ 'PAYPAL',+ 'ZELLE',+ 'APP_PAYOUT',+ 'CREDIT_CARD',+ 'OTHER',+];++export const ATTACHMENT_OBJECT_TYPES = ['CLIENT', 'PROJECT', 'DELIVERABLE', 'OPPORTUNITY', 'EXPENSE', 'TICKET'];++export const moxieFields = {+ clientCreate: [+ { key: 'name', kind: 'text', displayName: 'Name', required: true },+ ...CLIENT_DETAIL_FIELDS,+ ] satisfies MoxieFieldSpec[],++ clientUpdate: [+ { key: 'name', kind: 'text', displayName: 'Name' },+ ...CLIENT_DETAIL_FIELDS,+ ] satisfies MoxieFieldSpec[],++ contactCreate: [+ { key: 'first', kind: 'text', displayName: 'First Name', required: true },+ { key: 'last', kind: 'text', displayName: 'Last Name' },+ { key: 'email', kind: 'email', displayName: 'Email' },+ { key: 'phone', kind: 'text', displayName: 'Phone' },+ { key: 'notes', kind: 'longText', displayName: 'Notes' },+ ...CONTACT_FLAG_FIELDS,+ ] satisfies MoxieFieldSpec[],++ contactUpdate: [+ { key: 'firstName', kind: 'text', displayName: 'First Name' },+ { key: 'lastName', kind: 'text', displayName: 'Last Name', clearable: true },+ { key: 'role', kind: 'text', displayName: 'Role', clearable: true },+ { key: 'email', kind: 'email', displayName: 'Email', clearable: true },+ { key: 'phone', kind: 'text', displayName: 'Phone', clearable: true },+ { key: 'mobile', kind: 'text', displayName: 'Mobile', clearable: true },+ { key: 'notes', kind: 'longText', displayName: 'Notes', clearable: true },+ ...CONTACT_FLAG_FIELDS,+ ] satisfies MoxieFieldSpec[],++ projectCreate: [+ { key: 'startDate', kind: 'date', displayName: 'Start Date' },+ { key: 'dueDate', kind: 'date', displayName: 'Due Date' },+ { key: 'portalAccess', kind: 'enum', displayName: 'Client Portal Access', options: PORTAL_ACCESS_OPTIONS },+ { key: 'showTimeWorkedInPortal', kind: 'triState', displayName: 'Show Time Worked in Portal' },+ { key: 'templateName', kind: 'text', displayName: 'Project Template', description: 'Exact name of a project template to copy tasks and settings from.' },+ { key: 'customValues', kind: 'record', displayName: 'Custom Values', description: 'Custom project field values keyed by field name.' },+ ] satisfies MoxieFieldSpec[],++ projectFee: [+ { key: 'feeType', kind: 'enum', displayName: 'Fee Type', options: FEE_TYPE_OPTIONS, description: 'Sets the fee schedule. Leave empty to create the project without one.' },+ { key: 'amount', kind: 'number', displayName: 'Fee Amount', min: 0, description: 'Hourly rate, fixed price, retainer amount or per-item price, depending on Fee Type.' },+ { key: 'estimateMin', kind: 'number', displayName: 'Estimate Minimum', min: 0 },+ { key: 'estimateMax', kind: 'number', displayName: 'Estimate Maximum', min: 0 },+ { key: 'taxable', kind: 'triState', displayName: 'Fee Taxable' },+ ] satisfies MoxieFieldSpec[],++ projectUpdate: [+ { key: 'name', kind: 'text', displayName: 'Name' },+ { key: 'description', kind: 'longText', displayName: 'Description', clearable: true },+ { key: 'startDate', kind: 'date', displayName: 'Start Date' },+ { key: 'dueDate', kind: 'date', displayName: 'Due Date' },+ { key: 'active', kind: 'triState', displayName: 'Active', description: 'No marks the project inactive, Yes reactivates it.' },+ { key: 'portalAccess', kind: 'enum', displayName: 'Client Portal Access', options: PORTAL_ACCESS_OPTIONS },+ { key: 'showTimeWorkedInPortal', kind: 'triState', displayName: 'Show Time Worked in Portal' },+ { key: 'hexColor', kind: 'text', displayName: 'Colour', description: 'Hex colour, for example #78909C.' },+ ] satisfies MoxieFieldSpec[],++ taskCreate: [+ { key: 'description', kind: 'longText', displayName: 'Description' },+ { key: 'startDate', kind: 'date', displayName: 'Start Date' },+ { key: 'dueDate', kind: 'date', displayName: 'Due Date' },+ { key: 'priority', kind: 'integer', displayName: 'Priority', description: 'Whole number used to sort the kanban board.' },+ { key: 'tasks', kind: 'list', displayName: 'Subtasks', description: 'Names of subtasks to add.' },+ { key: 'assignedTo', kind: 'list', displayName: 'Assignee Emails', description: 'Emails of workspace users to assign (see List Workspace Users).' },+ { key: 'customValues', kind: 'record', displayName: 'Custom Values', description: 'Custom task field values keyed by field name.' },+ ] satisfies MoxieFieldSpec[],++ taskUpdate: [+ { key: 'name', kind: 'text', displayName: 'Name' },+ { key: 'description', kind: 'longText', displayName: 'Description', clearable: true },+ { key: 'priority', kind: 'integer', displayName: 'Priority', description: 'Whole number used to sort the kanban board.' },+ { key: 'startDate', kind: 'date', displayName: 'Start Date' },+ { key: 'dueDate', kind: 'date', displayName: 'Due Date' },+ ] satisfies MoxieFieldSpec[],++ opportunityCreate: [+ { key: 'description', kind: 'longText', displayName: 'Description' },+ { key: 'value', kind: 'number', displayName: 'Estimated Value', min: 0 },+ { key: 'estCloseDate', kind: 'date', displayName: 'Estimated Close Date' },+ { key: 'customValues', kind: 'record', displayName: 'Custom Values', description: 'Custom opportunity field values keyed by field name.' },+ ] satisfies MoxieFieldSpec[],++ opportunityUpdate: [+ { key: 'name', kind: 'text', displayName: 'Name' },+ { key: 'description', kind: 'longText', displayName: 'Description', clearable: true },+ { key: 'value', kind: 'number', displayName: 'Estimated Value', min: 0 },+ { key: 'estCloseDate', kind: 'date', displayName: 'Estimated Close Date' },+ { key: 'actualCloseDate', kind: 'date', displayName: 'Actual Close Date' },+ { key: 'sentiment', kind: 'integer', displayName: 'Sentiment', description: 'Whole number rating of how the deal is going.' },+ { key: 'archive', kind: 'triState', displayName: 'Archived', description: 'Yes archives the opportunity, No restores it.' },+ ] satisfies MoxieFieldSpec[],++ expenseCreate: [+ { key: 'date', kind: 'dateTime', displayName: 'Expense Date' },+ { key: 'category', kind: 'text', displayName: 'Category' },+ { key: 'currency', kind: 'text', displayName: 'Currency', description: 'Three-letter ISO 4217 code, for example USD.' },+ { key: 'paid', kind: 'triState', displayName: 'Paid' },+ { key: 'reimbursable', kind: 'triState', displayName: 'Billable to Client', description: 'Yes marks the expense as reimbursable, so it can be billed to the client.' },+ { key: 'markupPercentage', kind: 'number', displayName: 'Markup Percentage', min: 0 },+ { key: 'billNo', kind: 'text', displayName: 'Bill or Receipt Number' },+ { key: 'description', kind: 'text', displayName: 'Description' },+ { key: 'notes', kind: 'longText', displayName: 'Notes' },+ ] satisfies MoxieFieldSpec[],++ expenseUpdate: [+ { key: 'amount', kind: 'number', displayName: 'Amount', min: 0 },+ { key: 'taxRate', kind: 'number', displayName: 'Tax Rate', min: 0, description: 'Tax rate percentage.' },+ { key: 'category', kind: 'text', displayName: 'Category', clearable: true },+ { key: 'currency', kind: 'text', displayName: 'Currency', description: 'Three-letter ISO 4217 code, for example USD.' },+ { key: 'paid', kind: 'triState', displayName: 'Paid' },+ { key: 'paidDate', kind: 'date', displayName: 'Paid Date' },+ { key: 'dueDate', kind: 'date', displayName: 'Due Date' },+ { key: 'reimbursable', kind: 'triState', displayName: 'Billable to Client' },+ { key: 'markupPercent', kind: 'number', displayName: 'Markup Percentage', min: 0 },+ { key: 'billNo', kind: 'text', displayName: 'Bill or Receipt Number', clearable: true },+ { key: 'description', kind: 'text', displayName: 'Description', clearable: true },+ { key: 'notes', kind: 'longText', displayName: 'Notes', clearable: true },+ { key: 'clientId', kind: 'id', displayName: 'Client ID', description: 'Client to bill the expense to (from Search Clients).' },+ { key: 'projectId', kind: 'id', displayName: 'Project ID', description: 'Project to file the expense under (from Search Projects).' },+ ] satisfies MoxieFieldSpec[],++ timeEntry: [+ { key: 'notes', kind: 'longText', displayName: 'Notes' },+ ] satisfies MoxieFieldSpec[],++ invoice: [+ { key: 'dueDate', kind: 'date', displayName: 'Due Date' },+ { key: 'taxRate', kind: 'number', displayName: 'Tax Rate', min: 0, description: 'Flat tax rate percentage applied to taxable items.' },+ { key: 'discountPercent', kind: 'number', displayName: 'Discount Percentage', min: 0 },+ { key: 'paymentInstructions', kind: 'longText', displayName: 'Payment Instructions' },+ { key: 'description', kind: 'longText', displayName: 'Description' },+ { key: 'invoiceNumber', kind: 'text', displayName: 'Invoice Number', description: 'Leave empty to use the next number in the sequence.' },+ ] satisfies MoxieFieldSpec[],++ calendarEvent: [+ { key: 'timezone', kind: 'text', displayName: 'Time Zone', description: 'IANA time zone, for example America/New_York.' },+ { key: 'fullDay', kind: 'triState', displayName: 'All Day' },+ { key: 'busy', kind: 'triState', displayName: 'Show as Busy' },+ { key: 'summary', kind: 'text', displayName: 'Title' },+ { key: 'description', kind: 'longText', displayName: 'Description' },+ { key: 'location', kind: 'text', displayName: 'Location' },+ { key: 'userEmail', kind: 'email', displayName: 'Owner Email', description: 'Email of the workspace user who owns the event (see List Workspace Users).' },+ ] satisfies MoxieFieldSpec[],++ formSubmission: [+ { key: 'firstName', kind: 'text', displayName: 'First Name' },+ { key: 'lastName', kind: 'text', displayName: 'Last Name' },+ { key: 'email', kind: 'email', displayName: 'Email' },+ { key: 'phone', kind: 'text', displayName: 'Phone' },+ { key: 'role', kind: 'text', displayName: 'Role' },+ { key: 'businessName', kind: 'text', displayName: 'Business Name' },+ { key: 'website', kind: 'text', displayName: 'Website' },+ { key: 'address1', kind: 'text', displayName: 'Address Line 1' },+ { key: 'address2', kind: 'text', displayName: 'Address Line 2' },+ { key: 'city', kind: 'text', displayName: 'City' },+ { key: 'locality', kind: 'text', displayName: 'State or Region' },+ { key: 'postal', kind: 'text', displayName: 'Postal Code' },+ { key: 'country', kind: 'text', displayName: 'Country' },+ { key: 'taxId', kind: 'text', displayName: 'Tax ID' },+ { key: 'sourceUrl', kind: 'text', displayName: 'Source URL' },+ { key: 'leadSource', kind: 'text', displayName: 'Lead Source' },+ { key: 'pipelineStageName', kind: 'text', displayName: 'Pipeline Stage', description: 'Exact stage label to place the lead in (see List Pipeline Stages).' },+ { key: 'notes', kind: 'longText', displayName: 'Notes' },+ ] satisfies MoxieFieldSpec[],+};diff --git a/packages/pieces/community/moxie-crm/src/lib/common/index.ts b/packages/pieces/community/moxie-crm/src/lib/common/index.tsindex 132fcc78be4..55079a8ebe7 100644--- a/packages/pieces/community/moxie-crm/src/lib/common/index.ts+++ b/packages/pieces/community/moxie-crm/src/lib/common/index.ts@@ -1,16 +1,71 @@-import { AppConnectionValueForAuthProperty, PiecePropValueSchema } from '@activepieces/pieces-framework';-+import { AppConnectionValueForAuthProperty, DropdownOption, DropdownState } from '@activepieces/pieces-framework';import { moxieCRMAuth } from '../auth';-import { MoxieCRMClient } from './client';+import { MoxieCRMClient, responseStatusOf } from './client';+import { MoxieCredentials } from './models';++export async function makeClient(auth: MoxieAuthValue): Promise<MoxieCRMClient> {+ return new MoxieCRMClient(credentialsOf({ auth }));+}-export async function makeClient(- auth: AppConnectionValueForAuthProperty<typeof moxieCRMAuth>-): Promise<MoxieCRMClient> {- const client = new MoxieCRMClient(auth.props.baseUrl, auth.props.apiKey);- return client;+export function credentialsOf({ auth }: { auth: MoxieAuthValue }): MoxieCredentials {+ return { baseUrl: auth.props.baseUrl, apiKey: auth.props.apiKey };}export function reformatDate(s?: string): string | undefined {if (!s) return undefined;return s.split('T', 2)[0];}++export async function safeOptions<T>({+ auth,+ load,+ emptyPlaceholder,+ notFoundPlaceholder,+}: {+ auth: unknown;+ load: () => Promise<DropdownOption<T>[]>;+ emptyPlaceholder?: string;+ notFoundPlaceholder?: string;+}): Promise<DropdownState<T>> {+ if (auth === undefined || auth === null) {+ return { disabled: true, options: [], placeholder: 'Connect your Moxie account first.' };+ }+ try {+ const options = await load();+ if (options.length === 0 && emptyPlaceholder !== undefined) {+ return { disabled: true, options: [], placeholder: emptyPlaceholder };+ }+ return { disabled: false, options };+ } catch (error) {+ if (responseStatusOf({ error }) === 404 && notFoundPlaceholder !== undefined) {+ return { disabled: true, options: [], placeholder: notFoundPlaceholder };+ }+ const reason = error instanceof Error ? error.message : String(error);+ return { disabled: true, options: [], placeholder: `Could not load options: ${reason}` };+ }+}++export function disabledOptions<T>({ placeholder }: { placeholder: string }): DropdownState<T> {+ return { disabled: true, options: [], placeholder };+}++export function asArray({ value }: { value: unknown }): unknown[] {+ if (!Array.isArray(value)) {+ throw new Error('Moxie returned an unexpected response (expected a list).');+ }+ return value;+}++export function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === 'object' && value !== null && !Array.isArray(value);+}++export function stringField({ record, key }: { record: unknown; key: string }): string | undefined {+ if (!isRecord(record)) {+ return undefined;+ }+ const value = record[key];+ return typeof value === 'string' ? value : undefined;+}++export type MoxieAuthValue = AppConnectionValueForAuthProperty<typeof moxieCRMAuth>;diff --git a/packages/pieces/community/moxie-crm/src/lib/common/models.ts b/packages/pieces/community/moxie-crm/src/lib/common/models.tsindex cf784714c5e..8d20af697b2 100644--- a/packages/pieces/community/moxie-crm/src/lib/common/models.ts+++ b/packages/pieces/community/moxie-crm/src/lib/common/models.ts@@ -1,6 +1,11 @@+export type MoxieCredentials = {+ baseUrl: string;+ apiKey: string;+};+export type ContactCreateRequest = {- first: string;- last: string;+ first?: string;+ last?: string;email?: string;phone?: string;notes?: string;@@ -18,6 +23,8 @@ export type ClientListResponse = {export type ProjectSearchResponse = {id: string;name: string;+ projectTypeId?: string;+ clientId?: string;};export type ProjectTaskStageListResponse = {@@ -33,20 +40,22 @@ export type ProjectCreateRequest = {clientName: string;startDate?: string;dueDate?: string;- portalAccess: string;+ portalAccess?: string;showTimeWorkedInPortal?: boolean;- feeSchedule: {+ feeSchedule?: {feeType: string;amount?: number;estimateMax?: number;estimateMin?: number;taxable?: boolean;};+ templateName?: string;+ customValues?: Record<string, unknown>;};export type ClientCreateRequest = {name: string;- clientType: string;+ clientType?: string;initials?: string;address1?: string;address2?: string;@@ -59,7 +68,7 @@ export type ClientCreateRequest = {color?: string;taxId?: string;leadSource?: string;- archive: boolean;+ archive?: boolean;payInstructions?: string;hourlyAmount?: number;roundingIncrement?: number;@@ -70,14 +79,69 @@ export type ClientCreateRequest = {export type TaskCreateRequest = {name: string;- clientName: string;- projectName: string;- status: string;+ clientName?: string;+ projectName?: string;+ status?: string;description?: string;dueDate?: string;startDate?: string;priority?: number;tasks?: string[];assignedTo?: string[];- customValues?: Record<string, string>;+ customValues?: Record<string, unknown>;+};++export type MoxiePayment = {+ id?: string;+ referenceNumber?: string | null;+};++export type MoxieInvoiceMini = {+ id?: string;+ invoiceNumberFormatted?: string;+ payments?: MoxiePayment[];+};++export type MoxieSimpleAccount = {+ accountId?: number;+ accountName?: string;+};++export type MoxieStoredHook = {+ id: string | null;+ type: string;+ hookUrl: string;+};++export type MoxieContact = {+ id: string;+ firstName?: string | null;+ lastName?: string | null;+ email?: string | null;+ clientId?: string | null;+};++export type MoxieTaskMini = {+ id: string;+ name?: string;+ status?: string;+};++export type MoxieUserAccount = {+ user?: {+ userId?: number;+ firstName?: string | null;+ lastName?: string | null;+ email?: string | null;+ };+};++export type MoxieStage = {+ id: string;+ label: string;+};++export type MoxieEmailTemplateSummary = {+ id: string;+ name: string;};diff --git a/packages/pieces/community/moxie-crm/src/lib/common/operations.ts b/packages/pieces/community/moxie-crm/src/lib/common/operations.tsnew file mode 100644index 00000000000..ec5f1cb47d6--- /dev/null+++ b/packages/pieces/community/moxie-crm/src/lib/common/operations.ts@@ -0,0 +1,408 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { moxieRequest } from './client';+import { PAYMENT_TYPE_OPTIONS, moxieFields } from './fields';+import { isRecord } from '.';+import { MoxieCredentials, MoxieInvoiceMini } from './models';+import { moxieBody, moxieInput } from './props';++export const moxieOperations = {+ createClient({ credentials, values }: OperationParams): Promise<unknown> {+ const body = moxieBody.fromSpecs({ specs: moxieFields.clientCreate, values });+ return post({ credentials, path: '/action/clients/create', body });+ },++ updateClient({ credentials, values }: OperationParams): Promise<unknown> {+ const id = moxieInput.id({ value: values['clientId'], field: 'Client ID' });+ const fields = moxieBody.withClears({+ specs: moxieFields.clientUpdate,+ body: moxieBody.fromSpecs({ specs: moxieFields.clientUpdate, values }),+ clearFields: values['clearFields'],+ });+ moxieBody.requireChanges({ body: fields, objectName: 'client' });+ return patch({+ credentials,+ path: '/action/clients/update',+ body: { id, ...fields },+ notFoundMessage: `No client with id ${id} in this Moxie workspace.`,+ });+ },++ createContact({ credentials, values }: OperationParams): Promise<unknown> {+ const body = {+ ...moxieBody.fromSpecs({ specs: moxieFields.contactCreate, values }),+ ...moxieInput.compact({ values: { clientName: moxieInput.text({ value: values['clientName'] }) } }),+ };+ return post({+ credentials,+ path: '/action/contacts/create',+ body,+ notFoundMessage: 'Moxie could not find the client. Client Name must match an existing client exactly.',+ });+ },++ updateContact({ credentials, values }: OperationParams): Promise<unknown> {+ const id = moxieInput.id({ value: values['contactId'], field: 'Contact ID' });+ const fields = moxieBody.withClears({+ specs: moxieFields.contactUpdate,+ body: {+ ...moxieBody.fromSpecs({ specs: moxieFields.contactUpdate, values }),+ ...moxieInput.compact({+ values: { clientId: moxieInput.optionalId({ value: values['clientId'], field: 'Client ID' }) },+ }),+ },+ clearFields: values['clearFields'],+ });+ moxieBody.requireChanges({ body: fields, objectName: 'contact' });+ return patch({+ credentials,+ path: '/action/contacts/update',+ body: { id, ...fields },+ notFoundMessage: `No contact with id ${id} in this Moxie workspace.`,+ });+ },++ createProject({ credentials, values }: OperationParams): Promise<unknown> {+ const name = moxieInput.requiredText({ value: values['name'], field: 'Project Name' });+ const clientName = moxieInput.requiredText({ value: values['clientName'], field: 'Client Name' });+ const fee = moxieBody.fromSpecs({ specs: moxieFields.projectFee, values });+ if (fee['feeType'] === undefined && Object.keys(fee).length > 0) {+ throw new Error('Set Fee Type to send a fee amount, estimate or taxable flag.');+ }+ const body = {+ name,+ clientName,+ ...moxieBody.fromSpecs({ specs: moxieFields.projectCreate, values }),+ ...(fee['feeType'] === undefined ? {} : { feeSchedule: fee }),+ };+ return post({+ credentials,+ path: '/action/projects/create',+ body,+ notFoundMessage: `Moxie could not find the client "${clientName}" or the project template. Names must match exactly.`,+ });+ },++ updateProject({ credentials, values }: OperationParams): Promise<unknown> {+ const id = moxieInput.id({ value: values['projectId'], field: 'Project ID' });+ const fields = moxieBody.withClears({+ specs: moxieFields.projectUpdate,+ body: moxieBody.fromSpecs({ specs: moxieFields.projectUpdate, values }),+ clearFields: values['clearFields'],+ });+ moxieBody.requireChanges({ body: fields, objectName: 'project' });+ return patch({+ credentials,+ path: '/action/projects/update',+ body: { id, ...fields },+ notFoundMessage: `No project with id ${id} in this Moxie workspace.`,+ });+ },++ createTask({ credentials, values }: OperationParams): Promise<unknown> {+ const body = {+ name: moxieInput.requiredText({ value: values['name'], field: 'Task Name' }),+ clientName: moxieInput.requiredText({ value: values['clientName'], field: 'Client Name' }),+ projectName: moxieInput.requiredText({ value: values['projectName'], field: 'Project Name' }),+ ...moxieInput.compact({ values: { status: moxieInput.text({ value: values['status'] }) } }),+ ...moxieBody.fromSpecs({ specs: moxieFields.taskCreate, values }),+ };+ return post({+ credentials,+ path: '/action/tasks/create',+ body,+ notFoundMessage: 'Moxie could not find the client or project. Client Name and Project Name must match exactly.',+ });+ },++ updateTask({ credentials, values }: OperationParams): Promise<unknown> {+ const id = moxieInput.id({ value: values['taskId'], field: 'Task ID' });+ const fields = moxieBody.withClears({+ specs: moxieFields.taskUpdate,+ body: {+ ...moxieBody.fromSpecs({ specs: moxieFields.taskUpdate, values }),+ ...moxieInput.compact({+ values: {+ statusId: moxieInput.optionalId({ value: values['statusId'], field: 'Stage ID' }),+ assignedToList: moxieInput.integerList({ value: values['assignedToList'], field: 'Assignee User IDs' }),+ },+ }),+ },+ clearFields: values['clearFields'],+ });+ moxieBody.requireChanges({ body: fields, objectName: 'task' });+ return patch({+ credentials,+ path: '/action/tasks/update',+ body: { id, ...fields },+ notFoundMessage: `No task with id ${id} in this Moxie workspace.`,+ });+ },++ createOpportunity({ credentials, values }: OperationParams): Promise<unknown> {+ const body = {+ name: moxieInput.requiredText({ value: values['name'], field: 'Opportunity Name' }),+ ...moxieInput.compact({+ values: {+ clientName: moxieInput.text({ value: values['clientName'] }),+ stageName: moxieInput.text({ value: values['stageName'] }),+ },+ }),+ ...moxieBody.fromSpecs({ specs: moxieFields.opportunityCreate, values }),+ };+ return post({+ credentials,+ path: '/action/opportunities/create',+ body,+ notFoundMessage: 'Moxie could not find the client or pipeline stage. Names must match exactly.',+ });+ },++ updateOpportunity({ credentials, values }: OperationParams): Promise<unknown> {+ const id = moxieInput.id({ value: values['opportunityId'], field: 'Opportunity ID' });+ const fields = moxieBody.withClears({+ specs: moxieFields.opportunityUpdate,+ body: {+ ...moxieBody.fromSpecs({ specs: moxieFields.opportunityUpdate, values }),+ ...moxieInput.compact({+ values: {+ statusId: moxieInput.optionalId({ value: values['statusId'], field: 'Stage ID' }),+ clientId: moxieInput.optionalId({ value: values['clientId'], field: 'Client ID' }),+ },+ }),+ },+ clearFields: values['clearFields'],+ });+ moxieBody.requireChanges({ body: fields, objectName: 'opportunity' });+ return patch({+ credentials,+ path: '/action/opportunities/update',+ body: { id, ...fields },+ notFoundMessage: `No opportunity with id ${id} in this Moxie workspace.`,+ });+ },++ createInvoice({ credentials, values }: OperationParams): Promise<unknown> {+ const clientName = moxieInput.requiredText({ value: values['clientName'], field: 'Client Name' });+ const items = parseLineItems({ value: values['items'] });+ const send = moxieInput.triState({ value: values['send'], field: 'Send Invoice' }) === true;+ const contacts = moxieInput.stringList({ value: values['sendToContacts'], field: 'Send To Contacts' });+ const emailTemplateName = moxieInput.text({ value: values['emailTemplateName'] });+ if (!send && (contacts !== undefined || emailTemplateName !== undefined)) {+ throw new Error('Send To Contacts and Email Template only apply when Send Invoice is on.');+ }+ contacts?.forEach((email) => moxieInput.email({ value: email, field: 'Send To Contacts' }));+ const body = {+ clientName,+ items,+ ...moxieInput.compact({ values: { templateName: moxieInput.text({ value: values['templateName'] }) } }),+ ...moxieBody.fromSpecs({ specs: moxieFields.invoice, values }),+ ...(send ? { sendTo: moxieInput.compact({ values: { send: true, contacts, emailTemplateName } }) } : {}),+ };+ return post({+ credentials,+ path: '/action/invoices/create',+ body,+ notFoundMessage: `Moxie could not find the client "${clientName}", the email template or a send-to contact. Names must match exactly.`,+ });+ },++ async applyPayment({ credentials, values }: OperationParams): Promise<unknown> {+ const invoiceNumber = moxieInput.requiredText({ value: values['invoiceNumber'], field: 'Invoice Number' });+ const clientName = moxieInput.requiredText({ value: values['clientName'], field: 'Client Name' });+ const amount = moxieInput.number({ value: values['amount'], field: 'Amount', min: 0 });+ if (amount === undefined || amount === 0) {+ throw new Error('Amount must be more than 0.');+ }+ const referenceNumber = moxieInput.text({ value: values['referenceNumber'] });+ if (referenceNumber !== undefined) {+ const existing = await findAppliedPayment({ credentials, clientName, invoiceNumber, referenceNumber });+ if (existing !== undefined) {+ return { ...existing, already_applied: true };+ }+ }+ const body = moxieInput.compact({+ values: {+ invoiceNumber,+ clientName,+ amount,+ date: moxieInput.date({ value: values['date'], field: 'Payment Date' }),+ paymentType: parsePaymentType({ value: values['paymentType'] }),+ referenceNumber,+ memo: moxieInput.text({ value: values['memo'] }),+ },+ });+ const result = await post({+ credentials,+ path: '/action/payment/create',+ body,+ notFoundMessage: `Moxie could not find an open invoice ${invoiceNumber} for client "${clientName}". The invoice must be sent and not fully paid, and both values must match exactly.`,+ });+ return isRecord(result) ? { ...result, already_applied: false } : { result, already_applied: false };+ },++ createTimeEntry({ credentials, values }: OperationParams): Promise<unknown> {+ const timerStart = moxieInput.dateTime({ value: values['timerStart'], field: 'Start Time' });+ const timerEnd = moxieInput.dateTime({ value: values['timerEnd'], field: 'End Time' });+ if (timerStart === undefined || timerEnd === undefined) {+ throw new Error('Start Time and End Time are required.');+ }+ if (Date.parse(timerEnd) <= Date.parse(timerStart)) {+ throw new Error('End Time must be after Start Time.');+ }+ const body = moxieInput.compact({+ values: {+ timerStart,+ timerEnd,+ clientName: moxieInput.text({ value: values['clientName'] }),+ projectName: moxieInput.text({ value: values['projectName'] }),+ deliverableName: moxieInput.text({ value: values['deliverableName'] }),+ notes: moxieInput.text({ value: values['notes'] }),+ userEmail: moxieInput.email({ value: values['userEmail'], field: 'User Email' }),+ createClient: moxieInput.triState({ value: values['createClient'], field: 'Create Client if Missing' }) === true ? true : undefined,+ createProject: moxieInput.triState({ value: values['createProject'], field: 'Create Project if Missing' }) === true ? true : undefined,+ createDeliverable: moxieInput.triState({ value: values['createDeliverable'], field: 'Create Task if Missing' }) === true ? true : undefined,+ },+ });+ return post({+ credentials,+ path: '/action/timeWorked/create',+ body,+ notFoundMessage:+ 'Moxie could not find the client, project, task or user. Names must match exactly, or turn on the matching Create option.',+ });+ },++ createExpense({ credentials, values }: OperationParams): Promise<unknown> {+ const amount = moxieInput.number({ value: values['amount'], field: 'Amount', min: 0 });+ if (amount === undefined) {+ throw new Error('Amount is required.');+ }+ const body = {+ amount,+ markupPercentage: 0,+ ...moxieInput.compact({+ values: {+ vendor: moxieInput.text({ value: values['vendor'] }),+ clientName: moxieInput.text({ value: values['clientName'] }),+ },+ }),+ ...moxieBody.fromSpecs({ specs: moxieFields.expenseCreate, values }),+ };+ return post({+ credentials,+ path: '/action/expenses/create',+ body,+ notFoundMessage: 'Moxie could not find the client. Client Name must match an existing client exactly.',+ });+ },++ updateExpense({ credentials, values }: OperationParams): Promise<unknown> {+ const id = moxieInput.id({ value: values['expenseId'], field: 'Expense ID' });+ const fields = moxieBody.withClears({+ specs: moxieFields.expenseUpdate,+ body: moxieBody.fromSpecs({ specs: moxieFields.expenseUpdate, values }),+ clearFields: values['clearFields'],+ });+ moxieBody.requireChanges({ body: fields, objectName: 'expense' });+ return patch({+ credentials,+ path: '/action/expenses/update',+ body: { id, ...fields },+ notFoundMessage: `No expense with id ${id} in this Moxie workspace.`,+ });+ },+};++function post({ credentials, path, body, notFoundMessage }: WriteParams): Promise<unknown> {+ return moxieRequest<unknown>({ credentials, method: HttpMethod.POST, path, body, notFoundMessage });+}++function patch({ credentials, path, body, notFoundMessage }: WriteParams): Promise<unknown> {+ return moxieRequest<unknown>({ credentials, method: HttpMethod.PATCH, path, body, notFoundMessage });+}++function parseLineItems({ value }: { value: unknown }): Record<string, unknown>[] {+ const rows = moxieInput.recordList({ value, field: 'Line Items' });+ if (rows === undefined) {+ throw new Error('Add at least one line item.');+ }+ return rows.map((row, index) => {+ const label = `Line item ${index + 1}`;+ const quantity = moxieInput.number({ value: row['quantity'], field: `${label} quantity`, min: 0 });+ const rate = moxieInput.number({ value: row['rate'], field: `${label} rate`, min: 0 });+ if (quantity === undefined || rate === undefined) {+ throw new Error(`${label} needs a quantity and a rate.`);+ }+ return moxieInput.compact({+ values: {+ description: moxieInput.requiredText({ value: row['description'], field: `${label} description` }),+ quantity,+ rate,+ taxable: moxieInput.triState({ value: row['taxable'], field: `${label} taxable` }),+ projectName: moxieInput.text({ value: row['projectName'] }),+ },+ });+ });+}++function parsePaymentType({ value }: { value: unknown }): string | undefined {+ const text = moxieInput.text({ value });+ if (text === undefined) {+ return undefined;+ }+ const match = PAYMENT_TYPE_OPTIONS.find((option) => option === text.toUpperCase());+ if (match === undefined) {+ throw new Error(`Payment Type must be one of: ${PAYMENT_TYPE_OPTIONS.join(', ')}. Got "${text}".`);+ }+ return match;+}++async function findAppliedPayment({+ credentials,+ clientName,+ invoiceNumber,+ referenceNumber,+}: {+ credentials: MoxieCredentials;+ clientName: string;+ invoiceNumber: string;+ referenceNumber: string;+}): Promise<MoxieInvoiceMini | undefined> {+ const invoices = await moxieRequest<unknown>({+ credentials,+ method: HttpMethod.GET,+ path: '/action/payableInvoices/search',+ query: { query: clientName },+ });+ if (!Array.isArray(invoices)) {+ return undefined;+ }+ const invoice = invoices.filter(isInvoiceMini).find(+ (candidate) => candidate.invoiceNumberFormatted?.toLowerCase() === invoiceNumber.toLowerCase(),+ );+ const alreadyApplied = invoice?.payments?.some((payment) => payment.referenceNumber === referenceNumber) === true;+ return alreadyApplied ? invoice : undefined;+}++function isInvoiceMini(value: unknown): value is MoxieInvoiceMini {+ if (!isRecord(value)) {+ return false;+ }+ const payments = value['payments'];+ return (+ (value['invoiceNumberFormatted'] === undefined || typeof value['invoiceNumberFormatted'] === 'string') &&+ (payments === undefined || payments === null || (Array.isArray(payments) && payments.every(isRecord)))+ );+}++type OperationParams = {+ credentials: MoxieCredentials;+ values: Record<string, unknown>;+};++type WriteParams = {+ credentials: MoxieCredentials;+ path: string;+ body: unknown;+ notFoundMessage?: string;+};diff --git a/packages/pieces/community/moxie-crm/src/lib/common/props.ts b/packages/pieces/community/moxie-crm/src/lib/common/props.tsnew file mode 100644index 00000000000..fe801347847--- /dev/null+++ b/packages/pieces/community/moxie-crm/src/lib/common/props.ts@@ -0,0 +1,423 @@+import { Property } from '@activepieces/pieces-framework';++export const moxieInput = {+ text({ value }: { 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 === '' ? undefined : trimmed;+ },++ requiredText({ value, field }: { value: unknown; field: string }): string {+ const text = moxieInput.text({ value });+ if (text === undefined) {+ throw new Error(`${field} is required.`);+ }+ return text;+ },++ id({ value, field }: { value: unknown; field: string }): string {+ const text = moxieInput.optionalId({ value, field });+ if (text === undefined) {+ throw new Error(`${field} is required.`);+ }+ return text;+ },++ optionalId({ value, field }: { value: unknown; field: string }): string | undefined {+ const text = moxieInput.text({ value });+ if (text === undefined) {+ return undefined;+ }+ if (/[\s/?#]/.test(text)) {+ throw new Error(`${field} "${text}" is not a valid Moxie id (it contains spaces or URL characters).`);+ }+ return text;+ },++ email({ value, field }: { value: unknown; field: string }): string | undefined {+ const text = moxieInput.text({ value });+ if (text === undefined) {+ return undefined;+ }+ if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(text)) {+ throw new Error(`${field} "${text}" is not a valid email address.`);+ }+ return text;+ },++ httpsUrl({ value, field }: { value: unknown; field: string }): string {+ const text = moxieInput.requiredText({ value, field });+ let parsed: URL;+ try {+ parsed = new URL(text);+ } catch {+ throw new Error(`${field} "${text}" is not a valid URL.`);+ }+ if (parsed.protocol !== 'https:' || parsed.username !== '' || parsed.password !== '') {+ throw new Error(`${field} must be a public https URL without a user name or password.`);+ }+ return parsed.toString();+ },++ file({ value, field }: { value: unknown; field: string }): { filename: string; data: Buffer } {+ if (typeof value !== 'object' || value === null) {+ throw new Error(`${field} is required.`);+ }+ const filename: unknown = Reflect.get(value, 'filename');+ const data: unknown = Reflect.get(value, 'data');+ if (typeof filename !== 'string' || !Buffer.isBuffer(data)) {+ throw new Error(`${field} must be a file.`);+ }+ return { filename, data };+ },++ date({ value, field }: { value: unknown; field: string }): string | undefined {+ const text = moxieInput.text({ value });+ if (text === undefined) {+ return undefined;+ }+ const match = /^(\d{4})-(\d{2})-(\d{2})(?:$|T)/.exec(text);+ if (match === null || !isRealDate({ year: Number(match[1]), month: Number(match[2]), day: Number(match[3]) })) {+ throw new Error(`${field} must be a date in YYYY-MM-DD format, got "${text}".`);+ }+ return text.slice(0, 10);+ },++ dateTime({ value, field }: { value: unknown; field: string }): string | undefined {+ const text = moxieInput.text({ value });+ if (text === undefined) {+ return undefined;+ }+ const time = Date.parse(text);+ if (!/^\d{4}-\d{2}-\d{2}/.test(text) || Number.isNaN(time)) {+ throw new Error(`${field} must be an ISO 8601 date and time (for example 2026-10-01T09:30:00Z), got "${text}".`);+ }+ return new Date(time).toISOString();+ },++ number({ value, field, min }: { value: unknown; field: string; min?: number }): number | undefined {+ if (value === undefined || value === null || (typeof value === 'string' && value.trim() === '')) {+ return undefined;+ }+ const parsed = typeof value === 'number' ? value : typeof value === 'string' ? Number(value.trim()) : Number.NaN;+ if (!Number.isFinite(parsed)) {+ throw new Error(`${field} must be a number, got "${String(value)}".`);+ }+ if (min !== undefined && parsed < min) {+ throw new Error(`${field} must be ${min} or more, got ${parsed}.`);+ }+ return parsed;+ },++ integer({ value, field, min }: { value: unknown; field: string; min?: number }): number | undefined {+ const parsed = moxieInput.number({ value, field, min });+ if (parsed !== undefined && !Number.isInteger(parsed)) {+ throw new Error(`${field} must be a whole number, got ${parsed}.`);+ }+ return parsed;+ },++ triState({ value, field }: { value: unknown; field: string }): boolean | undefined {+ if (value === undefined || value === null || value === '') {+ return undefined;+ }+ if (value === true || value === 'yes' || value === 'true') {+ return true;+ }+ if (value === false || value === 'no' || value === 'false') {+ return false;+ }+ throw new Error(`${field} must be "yes" or "no", got "${String(value)}".`);+ },++ stringList({ value, field }: { value: unknown; field: string }): string[] | undefined {+ if (value === undefined || value === null || value === '') {+ return undefined;+ }+ const items = Array.isArray(value) ? value : [value];+ const result: string[] = [];+ for (const item of items) {+ const text = moxieInput.text({ value: item });+ if (text === undefined) {+ if (item === undefined || item === null || item === '') {+ continue;+ }+ throw new Error(`${field} must be a list of text values.`);+ }+ result.push(text);+ }+ return result.length === 0 ? undefined : result;+ },++ integerList({ value, field }: { value: unknown; field: string }): number[] | undefined {+ const items = moxieInput.stringList({ value, field });+ if (items === undefined) {+ return undefined;+ }+ return items.map((item) => {+ const parsed = moxieInput.integer({ value: item, field, min: 0 });+ if (parsed === undefined) {+ throw new Error(`${field} must be a list of numeric ids.`);+ }+ return parsed;+ });+ },++ record({ value, field }: { value: unknown; field: string }): Record<string, unknown> | undefined {+ if (value === undefined || value === null || value === '') {+ return undefined;+ }+ let parsed: unknown = value;+ if (typeof value === 'string') {+ try {+ parsed = JSON.parse(value);+ } catch {+ throw new Error(`${field} must be an object of field name to value.`);+ }+ }+ if (!isPlainRecord(parsed)) {+ throw new Error(`${field} must be an object of field name to value.`);+ }+ return Object.keys(parsed).length === 0 ? undefined : parsed;+ },++ recordList({ value, field }: { value: unknown; field: string }): Record<string, unknown>[] | undefined {+ if (value === undefined || value === null || value === '') {+ return undefined;+ }+ if (!Array.isArray(value)) {+ throw new Error(`${field} must be a list.`);+ }+ const items = value.filter((item) => item !== undefined && item !== null);+ const records = items.filter(isPlainRecord);+ if (records.length !== items.length) {+ throw new Error(`${field} must be a list of objects.`);+ }+ return records.length === 0 ? undefined : records;+ },++ queryOrId({ query, id, idField }: { query: unknown; id: unknown; idField: string }): { query?: string; id?: string } {+ const text = moxieInput.text({ value: query });+ const exactId = moxieInput.optionalId({ value: id, field: idField });+ if (text === undefined && exactId === undefined) {+ throw new Error(`Enter a Query or a ${idField}.`);+ }+ return exactId === undefined ? { query: text } : { id: exactId };+ },++ compact({ values }: { values: Record<string, unknown> }): Record<string, unknown> {+ return Object.fromEntries(Object.entries(values).filter(([, value]) => value !== undefined));+ },+};++export const moxieProps = {+ triState({ displayName, description }: { displayName: string; description?: string }) {+ return Property.StaticDropdown({+ displayName,+ description: description ?? 'Leave empty to not send this value (an update keeps the current one).',+ required: false,+ options: {+ disabled: false,+ options: [+ { label: 'Yes', value: 'yes' },+ { label: 'No', value: 'no' },+ ],+ },+ });+ },++ fromSpecs({ specs, audience }: { specs: MoxieFieldSpec[]; audience: MoxieAudience }) {+ const entries = specs.map((spec) => [spec.key, propFromSpec({ spec, audience })] as const);+ return Object.fromEntries(entries);+ },++ clearFields({ specs }: { specs: MoxieFieldSpec[] }) {+ const options = specs+ .filter((spec) => spec.clearable === true)+ .map((spec) => ({ label: spec.displayName, value: spec.key }));+ return Property.StaticMultiSelectDropdown({+ displayName: 'Clear Fields',+ description:+ 'Fields to blank out on the record. Only text fields can be cleared; dates and numbers keep their value.',+ required: false,+ options: { disabled: false, options },+ });+ },+};++export const moxieBody = {+ fromSpecs({ specs, values }: { specs: MoxieFieldSpec[]; values: Record<string, unknown> }): Record<string, unknown> {+ const entries = specs.map((spec) => [spec.key, parseSpec({ spec, value: values[spec.key] })] as const);+ return moxieInput.compact({ values: Object.fromEntries(entries) });+ },++ withClears({+ specs,+ body,+ clearFields,+ }: {+ specs: MoxieFieldSpec[];+ body: Record<string, unknown>;+ clearFields: unknown;+ }): Record<string, unknown> {+ const requested = moxieInput.stringList({ value: clearFields, field: 'Clear Fields' }) ?? [];+ const clearable = new Set(specs.filter((spec) => spec.clearable === true).map((spec) => spec.key));+ const cleared: Record<string, string> = {};+ for (const key of requested) {+ if (!clearable.has(key)) {+ throw new Error(`"${key}" cannot be cleared. Clearable fields: ${[...clearable].join(', ')}.`);+ }+ if (body[key] !== undefined) {+ throw new Error(`"${key}" is both set and cleared. Pick one.`);+ }+ cleared[key] = '';+ }+ return { ...body, ...cleared };+ },++ requireChanges({ body, objectName }: { body: Record<string, unknown>; objectName: string }): void {+ if (Object.keys(body).length === 0) {+ throw new Error(`Nothing to update on the ${objectName}: set at least one field or pick a field to clear.`);+ }+ },+};++function propFromSpec({ spec, audience }: { spec: MoxieFieldSpec; audience: MoxieAudience }) {+ const required = spec.required === true;+ const description = spec.description;+ switch (spec.kind) {+ case 'longText':+ return Property.LongText({ displayName: spec.displayName, description, required });+ case 'number':+ case 'integer':+ return Property.Number({ displayName: spec.displayName, description, required });+ case 'date':+ return Property.ShortText({+ displayName: spec.displayName,+ description: description ?? 'Date in YYYY-MM-DD format.',+ required,+ });+ case 'dateTime':+ return audience === 'human'+ ? Property.DateTime({ displayName: spec.displayName, description, required })+ : Property.ShortText({+ displayName: spec.displayName,+ description: description ?? 'ISO 8601 date and time, for example 2026-10-01T09:30:00Z.',+ required,+ });+ case 'triState':+ return moxieProps.triState({ displayName: spec.displayName, description });+ case 'enum':+ return Property.StaticDropdown({+ displayName: spec.displayName,+ description,+ required,+ options: {+ disabled: false,+ options: (spec.options ?? []).map((option) => ({ label: option, value: option })),+ },+ });+ case 'list':+ case 'integerList':+ return Property.Array({ displayName: spec.displayName, description, required });+ case 'record':+ return Property.Object({ displayName: spec.displayName, description, required });+ case 'email':+ case 'id':+ case 'text':+ return Property.ShortText({ displayName: spec.displayName, description, required });+ }+}++function parseSpec({ spec, value }: { spec: MoxieFieldSpec; value: unknown }): unknown {+ const field = spec.displayName;+ const parsed = parseByKind({ spec, value, field });+ if (spec.required === true && parsed === undefined) {+ throw new Error(`${field} is required.`);+ }+ return parsed;+}++function parseByKind({ spec, value, field }: { spec: MoxieFieldSpec; value: unknown; field: string }): unknown {+ switch (spec.kind) {+ case 'text':+ case 'longText':+ return moxieInput.text({ value });+ case 'id':+ return moxieInput.optionalId({ value, field });+ case 'email':+ return moxieInput.email({ value, field });+ case 'number':+ return moxieInput.number({ value, field, min: spec.min });+ case 'integer':+ return moxieInput.integer({ value, field, min: spec.min });+ case 'date':+ return moxieInput.date({ value, field });+ case 'dateTime':+ return moxieInput.dateTime({ value, field });+ case 'triState':+ return moxieInput.triState({ value, field });+ case 'enum':+ return parseEnum({ value, field, options: spec.options ?? [] });+ case 'list':+ return moxieInput.stringList({ value, field });+ case 'integerList':+ return moxieInput.integerList({ value, field });+ case 'record':+ return moxieInput.record({ value, field });+ }+}++function parseEnum({ value, field, options }: { value: unknown; field: string; options: string[] }): string | undefined {+ const text = moxieInput.text({ value });+ if (text === undefined) {+ return undefined;+ }+ const match = options.find((option) => option.toLowerCase() === text.toLowerCase());+ if (match === undefined) {+ throw new Error(`${field} must be one of: ${options.join(', ')}. Got "${text}".`);+ }+ return match;+}++function isRealDate({ year, month, day }: { year: number; month: number; day: number }): boolean {+ const date = new Date(Date.UTC(year, month - 1, day));+ return date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day;+}++function isPlainRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === 'object' && value !== null && !Array.isArray(value);+}++export type MoxieAudience = 'ai' | 'human';++export type MoxieFieldKind =+ | 'text'+ | 'longText'+ | 'id'+ | 'email'+ | 'number'+ | 'integer'+ | 'date'+ | 'dateTime'+ | 'triState'+ | 'enum'+ | 'list'+ | 'integerList'+ | 'record';++export type MoxieFieldSpec = {+ key: string;+ kind: MoxieFieldKind;+ displayName: string;+ description?: string;+ required?: boolean;+ clearable?: boolean;+ min?: number;+ options?: string[];+};diff --git a/packages/pieces/community/moxie-crm/src/lib/common/webhook.ts b/packages/pieces/community/moxie-crm/src/lib/common/webhook.tsnew file mode 100644index 00000000000..660b9e7d949--- /dev/null+++ b/packages/pieces/community/moxie-crm/src/lib/common/webhook.ts@@ -0,0 +1,169 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { Store } from '@activepieces/pieces-framework';+import { moxieRequest, responseStatusOf } from './client';+import { MoxieCredentials, MoxieStoredHook } from './models';++export const MOXIE_HOOK_STORE_KEY = 'moxie_rest_hook';++export const MOXIE_STALE_HOOKS_STORE_KEY = 'moxie_stale_hooks';++export const moxieWebhook = {+ async subscribe({+ credentials,+ type,+ hookUrl,+ }: {+ credentials: MoxieCredentials;+ type: string;+ hookUrl: string;+ }): Promise<MoxieStoredHook> {+ const response = await moxieRequest<unknown>({+ credentials,+ method: HttpMethod.POST,+ path: '/api/subscribe',+ body: { type, hookUrl },+ });+ const id = typeof response === 'string' && response.trim() !== '' ? response.trim() : null;+ return { id, type, hookUrl };+ },++ async unsubscribe({ credentials, hook }: { credentials: MoxieCredentials; hook: MoxieStoredHook }): Promise<void> {+ await moxieRequest<unknown>({+ credentials,+ method: HttpMethod.POST,+ path: '/api/unsubscribe',+ body: hook.id === null ? { type: hook.type, hookUrl: hook.hookUrl } : { id: hook.id, type: hook.type, hookUrl: hook.hookUrl },+ });+ },++ async enable({+ credentials,+ store,+ type,+ hookUrl,+ }: {+ credentials: MoxieCredentials;+ store: Store;+ type: string;+ hookUrl: string;+ }): Promise<void> {+ const previous = await store.get<unknown>(MOXIE_HOOK_STORE_KEY);+ const staleBefore = parseHooks({ value: await store.get<unknown>(MOXIE_STALE_HOOKS_STORE_KEY) });+ const hook = await moxieWebhook.subscribe({ credentials, type, hookUrl });+ const replaced = isStoredHook(previous) && needsRemoval({ previous, current: hook }) ? previous : undefined;+ try {+ if (replaced !== undefined) {+ await store.put(MOXIE_STALE_HOOKS_STORE_KEY, [...staleBefore, replaced]);+ }+ await store.put(MOXIE_HOOK_STORE_KEY, hook);+ } catch (error) {+ await moxieWebhook.unsubscribe({ credentials, hook }).catch(() => undefined);+ throw error;+ }+ if (replaced === undefined) {+ return;+ }+ const removed = await unsubscribeIgnoringMissing({ credentials, hook: replaced }).then(+ () => true,+ () => false,+ );+ if (removed) {+ const restore = staleBefore.length === 0 ? store.delete(MOXIE_STALE_HOOKS_STORE_KEY) : store.put(MOXIE_STALE_HOOKS_STORE_KEY, staleBefore);+ await restore.catch(() => undefined);+ }+ },++ async disable({ credentials, store }: { credentials: MoxieCredentials; store: Store }): Promise<void> {+ const stale = parseHooks({ value: await store.get<unknown>(MOXIE_STALE_HOOKS_STORE_KEY) });+ if (stale.length > 0) {+ const results = await Promise.all(+ stale.map((hook) =>+ unsubscribeIgnoringMissing({ credentials, hook }).then(+ () => undefined,+ () => hook,+ ),+ ),+ );+ const remaining = results.filter((hook): hook is MoxieStoredHook => hook !== undefined);+ if (remaining.length === 0) {+ await store.delete(MOXIE_STALE_HOOKS_STORE_KEY);+ } else {+ await store.put(MOXIE_STALE_HOOKS_STORE_KEY, remaining);+ }+ }+ const stored = await store.get<unknown>(MOXIE_HOOK_STORE_KEY);+ if (!isStoredHook(stored)) {+ return;+ }+ await unsubscribeIgnoringMissing({ credentials, hook: stored });+ await store.delete(MOXIE_HOOK_STORE_KEY);+ },++ acceptDelivery({ eventType, payload }: { eventType: string; payload: MoxieDeliveryPayload }): unknown[] {+ const deliveredType = headerOf({ headers: payload.headers, name: 'x-event-type' });+ if (deliveredType !== undefined && deliveredType !== eventType) {+ return [];+ }+ const origin = headerOf({ headers: payload.headers, name: 'x-event-origin' });+ if (origin !== undefined && origin.toLowerCase() !== 'withmoxie.com') {+ return [];+ }+ return [payload.body];+ },+};++async function unsubscribeIgnoringMissing({+ credentials,+ hook,+}: {+ credentials: MoxieCredentials;+ hook: MoxieStoredHook;+}): Promise<void> {+ try {+ await moxieWebhook.unsubscribe({ credentials, hook });+ } catch (error) {+ if (responseStatusOf({ error }) !== 404) {+ throw error;+ }+ }+}++function needsRemoval({ previous, current }: { previous: MoxieStoredHook; current: MoxieStoredHook }): boolean {+ if (previous.id !== null) {+ return previous.id !== current.id;+ }+ return previous.type !== current.type || previous.hookUrl !== current.hookUrl;+}++function parseHooks({ value }: { value: unknown }): MoxieStoredHook[] {+ return Array.isArray(value) ? value.filter(isStoredHook) : [];+}++function headerOf({ headers, name }: { headers: Record<string, unknown> | undefined; name: string }): string | undefined {+ if (headers === undefined || headers === null) {+ return undefined;+ }+ for (const [key, value] of Object.entries(headers)) {+ if (key.toLowerCase() === name && typeof value === 'string' && value.trim() !== '') {+ return value.trim();+ }+ }+ return undefined;+}++function isStoredHook(value: unknown): value is MoxieStoredHook {+ if (typeof value !== 'object' || value === null) {+ return false;+ }+ const id: unknown = Reflect.get(value, 'id');+ return (+ (id === null || typeof id === 'string') &&+ typeof Reflect.get(value, 'type') === 'string' &&+ typeof Reflect.get(value, 'hookUrl') === 'string'+ );+}++type MoxieDeliveryPayload = {+ body: unknown;+ headers?: Record<string, unknown>;+};diff --git a/packages/pieces/community/moxie-crm/src/lib/output-schemas.ts b/packages/pieces/community/moxie-crm/src/lib/output-schemas.tsindex 57caf7b0da1..dd0f0c487fb 100644--- a/packages/pieces/community/moxie-crm/src/lib/output-schemas.ts+++ b/packages/pieces/community/moxie-crm/src/lib/output-schemas.ts@@ -1,5 +1,20 @@import { OutputSchema } from '@activepieces/pieces-framework';+const customValueFields: OutputSchema['fields'] = [+ { key: 'fieldId', label: 'Field ID' },+ { key: 'mappingKey', label: 'Mapping Key' },+ { key: 'fieldName', label: 'Field Name' },+ { key: 'value', label: 'Value' },+ { key: 'type', label: 'Field Type' },+];++const customValuesField: OutputSchema['fields'][number] = {+ key: 'customValues',+ label: 'Custom Values',+ labelKey: 'fieldName',+ listItems: customValueFields,+};+const contactFields: OutputSchema['fields'] = [{ key: 'id', label: 'Contact ID' },{ key: 'firstName', label: 'First Name' },@@ -13,6 +28,7 @@ const contactFields: OutputSchema['fields'] = [{ key: 'invoiceContact', label: 'Invoice Contact', format: 'boolean' },{ key: 'portalAccess', label: 'Portal Access', format: 'boolean' },{ key: 'notes', label: 'Notes' },+ customValuesField,];const paymentTermsFields: OutputSchema['fields'] = [@@ -63,6 +79,8 @@ const clientFields: OutputSchema['fields'] = [{ key: 'xeroId', label: 'Xero ID' },],},+ { key: 'contacts', label: 'Contacts', labelKey: 'email', listItems: contactFields },+ customValuesField,];const clientMiniFields: OutputSchema['fields'] = [@@ -120,6 +138,13 @@ const projectCoreFields: OutputSchema['fields'] = [{ key: 'proposalId', label: 'Proposal ID' },{ key: 'proposalName', label: 'Proposal Name' },{ key: 'feeSchedule', label: 'Fee Schedule', children: feeScheduleFields },+ customValuesField,+];++const subtaskFields: OutputSchema['fields'] = [+ { key: 'id', label: 'Subtask ID' },+ { key: 'description', label: 'Description' },+ { key: 'complete', label: 'Complete', format: 'boolean' },];const taskFields: OutputSchema['fields'] = [@@ -163,6 +188,8 @@ const taskFields: OutputSchema['fields'] = [{ key: 'timestamp', label: 'Timestamp', format: 'datetime' },],},+ customValuesField,+ { key: 'tasks', label: 'Subtasks', labelKey: 'description', listItems: subtaskFields },];const triggerProjectFields: OutputSchema['fields'] = [@@ -326,6 +353,260 @@ const triggerOpportunityFields: OutputSchema['fields'] = [},];+const idNameFields: OutputSchema['fields'] = [+ { key: 'id', label: 'ID' },+ { key: 'name', label: 'Name' },+];++const taskMiniFields: OutputSchema['fields'] = [+ ...triggerTaskFields,+ customValuesField,+ { key: 'tasks', label: 'Subtasks', labelKey: 'description', listItems: subtaskFields },+];++const opportunityFields: OutputSchema['fields'] = [+ ...triggerOpportunityFields,+ { key: 'client', label: 'Client', children: idNameFields },+ customValuesField,+ {+ key: 'toDos',+ label: 'To-dos',+ labelKey: 'item',+ listItems: [+ { key: 'id', label: 'To-do ID' },+ { key: 'item', label: 'Item' },+ { key: 'complete', label: 'Complete', format: 'boolean' },+ { key: 'dueDate', label: 'Due Date', format: 'date' },+ ],+ },+];++const invoicePaymentFields: OutputSchema['fields'] = [+ { key: 'id', label: 'Payment ID' },+ { key: 'amount', label: 'Amount', format: 'currency' },+ { key: 'currency', label: 'Currency' },+ { key: 'datePaid', label: 'Date Paid', format: 'date' },+ { key: 'paidBy', label: 'Paid By' },+ { key: 'paymentProvider', label: 'Payment Method' },+ { key: 'referenceNumber', label: 'Reference Number' },+ { key: 'memo', label: 'Memo' },+ { key: 'pending', label: 'Pending', format: 'boolean' },+];++const invoiceMiniFields: OutputSchema['fields'] = [+ { key: 'id', label: 'Invoice ID' },+ { key: 'invoiceNumber', label: 'Invoice Number', format: 'number' },+ { key: 'invoiceNumberFormatted', label: 'Invoice Number Formatted' },+ { key: 'description', label: 'Description' },+ { key: 'clientId', label: 'Client ID' },+ { key: 'status', label: 'Status' },+ { key: 'invoiceType', label: 'Invoice Type' },+ { key: 'dateCreated', label: 'Date Created', format: 'date' },+ { key: 'dateSent', label: 'Date Sent', format: 'date' },+ { key: 'dateDue', label: 'Date Due', format: 'date' },+ { key: 'datePaid', label: 'Date Paid', format: 'date' },+ { key: 'currency', label: 'Currency' },+ { key: 'subTotal', label: 'Subtotal', format: 'currency' },+ { key: 'discountAmount', label: 'Discount Amount', format: 'currency' },+ { key: 'tax', label: 'Tax', format: 'currency' },+ { key: 'taxPercentage', label: 'Tax Percentage', format: 'number' },+ { key: 'total', label: 'Total', format: 'currency' },+ { key: 'paymentTotal', label: 'Payment Total', format: 'currency' },+ { key: 'amountDue', label: 'Amount Due', format: 'currency' },+ { key: 'viewOnlineUrl', label: 'View Online URL', format: 'url' },+ {+ key: 'clientInfo',+ label: 'Client',+ children: [+ { key: 'id', label: 'Client ID' },+ { key: 'name', label: 'Name' },+ { key: 'taxId', label: 'Tax ID' },+ ],+ },+ { key: 'payments', label: 'Payments', labelKey: 'datePaid', listItems: invoicePaymentFields },+ {+ key: 'lineItems',+ label: 'Line Items',+ labelKey: 'description',+ listItems: [+ { key: 'description', label: 'Description' },+ { key: 'quantity', label: 'Quantity', format: 'number' },+ { key: 'unitPrice', label: 'Unit Price', format: 'currency' },+ { key: 'unit', label: 'Unit' },+ { key: 'taxable', label: 'Taxable', format: 'boolean' },+ { key: 'lineTotal', label: 'Line Total', format: 'currency' },+ { key: 'type', label: 'Type' },+ { key: 'projectName', label: 'Project Name' },+ ],+ },+ {+ key: 'taxBreakdown',+ label: 'Tax Breakdown',+ labelKey: 'name',+ listItems: [+ { key: 'name', label: 'Tax Name' },+ { key: 'rate', label: 'Rate', format: 'number' },+ { key: 'taxableAmount', label: 'Taxable Amount', format: 'currency' },+ { key: 'amount', label: 'Amount', format: 'currency' },+ ],+ },+];++const expenseFields: OutputSchema['fields'] = [+ { key: 'id', label: 'Expense ID' },+ { key: 'amount', label: 'Amount', format: 'currency' },+ { key: 'tax', label: 'Tax', format: 'currency' },+ { key: 'taxRate', label: 'Tax Rate', format: 'number' },+ { key: 'total', label: 'Total', format: 'currency' },+ { key: 'totalWithMarkup', label: 'Total With Markup', format: 'currency' },+ { key: 'markupPercent', label: 'Markup Percentage', format: 'number' },+ { key: 'currency', label: 'Currency' },+ { key: 'category', label: 'Category' },+ { key: 'billNo', label: 'Bill Number' },+ { key: 'description', label: 'Description' },+ { key: 'notes', label: 'Notes' },+ { key: 'paid', label: 'Paid', format: 'boolean' },+ { key: 'paidDate', label: 'Paid Date', format: 'date' },+ { key: 'dueDate', label: 'Due Date', format: 'date' },+ { key: 'reimbursable', label: 'Billable to Client', format: 'boolean' },+ { key: 'dateCreated', label: 'Created', format: 'datetime' },+ { key: 'invoiceId', label: 'Invoice ID' },+ { key: 'invoiceNumber', label: 'Invoice Number' },+ { key: 'vendor', label: 'Vendor', children: idNameFields },+ { key: 'client', label: 'Client', children: idNameFields },+ { key: 'project', label: 'Project', children: idNameFields },+];++const ticketFields: OutputSchema['fields'] = [+ { key: 'id', label: 'Ticket ID' },+ { key: 'ticketNumber', label: 'Ticket Number', format: 'number' },+ { key: 'subject', label: 'Subject' },+ { key: 'type', label: 'Ticket Type' },+ { key: 'status', label: 'Status' },+ { key: 'open', label: 'Open', format: 'boolean' },+ { key: 'archived', label: 'Archived', format: 'boolean' },+ { key: 'unread', label: 'Unread', format: 'boolean' },+ { key: 'dueDate', label: 'Due Date', format: 'date' },+ { key: 'summary', label: 'Summary' },+ { key: 'lastComment', label: 'Last Comment' },+ { key: 'created', label: 'Created', format: 'datetime' },+ { key: 'updated', label: 'Updated', format: 'datetime' },+ { key: 'closed', label: 'Closed', format: 'datetime' },+ { key: 'clientId', label: 'Client ID' },+ { key: 'assignedTo', label: 'Assigned User IDs' },+ { key: 'ccList', label: 'CC List' },+ { key: 'client', label: 'Client', children: idNameFields },+];++const ticketWrapperFields: OutputSchema['fields'] = [+ { key: 'ticket', label: 'Ticket', children: ticketFields },+ {+ key: 'comments',+ label: 'Comments',+ labelKey: 'commentUserName',+ listItems: [+ { key: 'id', label: 'Comment ID' },+ { key: 'commentUserName', label: 'Author' },+ { key: 'commentUserEmail', label: 'Author Email', format: 'email' },+ { key: 'comment', label: 'Comment' },+ { key: 'commentType', label: 'Visibility' },+ { key: 'created', label: 'Created', format: 'datetime' },+ ],+ },+];++const calendarEventFields: OutputSchema['fields'] = [+ { key: 'id', label: 'Event ID' },+ { key: 'summary', label: 'Title' },+ { key: 'description', label: 'Description' },+ { key: 'location', label: 'Location' },+ { key: 'startDate', label: 'Start Date', format: 'date' },+ { key: 'startTime', label: 'Start Time' },+ { key: 'endDate', label: 'End Date', format: 'date' },+ { key: 'endTime', label: 'End Time' },+ { key: 'timezone', label: 'Time Zone' },+ { key: 'dateOnly', label: 'All Day', format: 'boolean' },+ { key: 'busyEvent', label: 'Busy', format: 'boolean' },+ { key: 'userId', label: 'Owner User ID', format: 'number' },+];++const agreementFields: OutputSchema['fields'] = [+ { key: 'id', label: 'Agreement ID' },+ { key: 'name', label: 'Name' },+ { key: 'status', label: 'Status' },+ { key: 'statusTime', label: 'Status Changed', format: 'datetime' },+ { key: 'currency', label: 'Currency' },+ { key: 'dateCreated', label: 'Created', format: 'datetime' },+ { key: 'dateCompleted', label: 'Completed', format: 'datetime' },+ { key: 'fullyExecuted', label: 'Fully Executed', format: 'boolean' },+ { key: 'userSigned', label: 'Signed by You', format: 'boolean' },+ { key: 'clientSigned', label: 'Signed by Client', format: 'boolean' },+ { key: 'client', label: 'Client', children: idNameFields },+];++const formSubmissionFields: OutputSchema['fields'] = [+ { key: 'id', label: 'Submission ID' },+ { key: 'formName', label: 'Form Name' },+ { key: 'clientId', label: 'Client ID' },+ { key: 'opportunityId', label: 'Opportunity ID' },+ { key: 'submittedAt', label: 'Submitted At', format: 'datetime' },+ { key: 'summary', label: 'Summary' },+ { key: 'notes', label: 'Notes' },+ {+ key: 'formData',+ label: 'Lead Details',+ children: [+ { key: 'firstName', label: 'First Name' },+ { key: 'lastName', label: 'Last Name' },+ { key: 'email', label: 'Email', format: 'email' },+ { key: 'phone', label: 'Phone' },+ { key: 'businessName', label: 'Business Name' },+ { key: 'website', label: 'Website', format: 'url' },+ { key: 'leadSource', label: 'Lead Source' },+ ],+ },+];++const taskStageFields: OutputSchema['fields'] = [+ { key: 'id', label: 'Stage ID' },+ { key: 'label', label: 'Label' },+ { key: 'hexColor', label: 'Colour' },+ { key: 'complete', label: 'Marks Complete', format: 'boolean' },+ { key: 'clientApproval', label: 'Needs Client Approval', format: 'boolean' },+];++const customFieldDefinitionFields: OutputSchema['fields'] = [+ { key: 'id', label: 'Field ID' },+ { key: 'name', label: 'Name' },+ { key: 'mappingKey', label: 'Mapping Key' },+ { key: 'type', label: 'Type' },+];++const projectTypeFields: OutputSchema['fields'] = [+ { key: 'id', label: 'Project Type ID' },+ { key: 'name', label: 'Name' },+ { key: 'isDefaultProjectType', label: 'Default', format: 'boolean' },+ { key: 'created', label: 'Created', format: 'datetime' },+ { key: 'statusList', label: 'Task Stages', labelKey: 'label', listItems: taskStageFields },+ { key: 'projectFields', label: 'Project Fields', labelKey: 'name', listItems: customFieldDefinitionFields },+ { key: 'deliverableFields', label: 'Task Fields', labelKey: 'name', listItems: customFieldDefinitionFields },+];++const accountFields: OutputSchema['fields'] = [+ { key: 'accountId', label: 'Account ID', format: 'number' },+ { key: 'accountName', label: 'Account Name' },+ { key: 'address1', label: 'Address Line 1' },+ { key: 'address2', label: 'Address Line 2' },+ { key: 'city', label: 'City' },+ { key: 'locality', label: 'State or Region' },+ { key: 'postal', label: 'Postal Code' },+ { key: 'country', label: 'Country' },+ { key: 'taxId', label: 'Tax ID' },+ { key: 'taxLabel', label: 'Tax Label' },+ { key: 'currency', label: 'Currency' },+];++export const createClientActionOutputSchema: OutputSchema = {fields: clientFields,};@@ -386,6 +667,14 @@ export const searchProjectsActionOutputSchema: OutputSchema = {labelKey: 'name',listItems: [...projectCoreFields,+ {+ key: 'client',+ label: 'Client',+ children: [+ { key: 'id', label: 'Client ID' },+ { key: 'name', label: 'Name' },+ ],+ },{key: 'paymentHistory',label: 'Payment History',@@ -467,6 +756,10 @@ export const timeEntryEventTriggerOutputSchema: OutputSchema = { fields: triggerexport const opportunityEventTriggerOutputSchema: OutputSchema = { fields: triggerOpportunityFields };+export const invoiceEventTriggerOutputSchema: OutputSchema = { fields: invoiceMiniFields };++export const ticketEventTriggerOutputSchema: OutputSchema = { fields: ticketWrapperFields };+export const moxieCRMTriggerOutputSchemas: Record<string, OutputSchema> = {client_created: clientEventTriggerOutputSchema,client_updated: clientEventTriggerOutputSchema,@@ -484,4 +777,67 @@ export const moxieCRMTriggerOutputSchemas: Record<string, OutputSchema> = {opportunity_created: opportunityEventTriggerOutputSchema,opportunity_updated: opportunityEventTriggerOutputSchema,opportunity_deleted: opportunityEventTriggerOutputSchema,+ invoice_sent: invoiceEventTriggerOutputSchema,+ payment_received: invoiceEventTriggerOutputSchema,+ invoice_voided: invoiceEventTriggerOutputSchema,+ invoice_write_off: invoiceEventTriggerOutputSchema,+ ticket_created: ticketEventTriggerOutputSchema,+ ticket_updated: ticketEventTriggerOutputSchema,+ ticket_comment_added: ticketEventTriggerOutputSchema,+ ticket_closed: ticketEventTriggerOutputSchema,+ ticket_deleted: ticketEventTriggerOutputSchema,+};++export const moxieActionOutputSchemas = {+ client: { fields: clientFields } satisfies OutputSchema,+ contact: { fields: contactFields } satisfies OutputSchema,+ project: createProjectActionOutputSchema,+ task: { fields: taskFields } satisfies OutputSchema,+ taskList: listSchema({ key: 'tasks', label: 'Tasks', labelKey: 'name', itemLabel: '{name}', fields: taskMiniFields }),+ approvedTask: { fields: taskMiniFields } satisfies OutputSchema,+ opportunity: { fields: opportunityFields } satisfies OutputSchema,+ timeEntry: { fields: triggerTimeEntryFields } satisfies OutputSchema,+ invoice: { fields: invoiceMiniFields } satisfies OutputSchema,+ payment: {+ fields: [...invoiceMiniFields, { key: 'already_applied', label: 'Already Applied', format: 'boolean' }],+ } satisfies OutputSchema,+ invoiceList: listSchema({ key: 'invoices', label: 'Invoices', labelKey: 'invoiceNumberFormatted', itemLabel: '{invoiceNumberFormatted}', fields: invoiceMiniFields }),+ expense: { fields: expenseFields } satisfies OutputSchema,+ ticket: { fields: ticketFields } satisfies OutputSchema,+ ticketWrapper: { fields: ticketWrapperFields } satisfies OutputSchema,+ ticketList: listSchema({ key: 'tickets', label: 'Tickets', labelKey: 'subject', itemLabel: '#{ticketNumber} {subject}', fields: ticketFields }),+ calendarEvent: { fields: calendarEventFields } satisfies OutputSchema,+ deletedCalendarEvent: {+ fields: [+ { key: 'id', label: 'Event ID' },+ { key: 'deleted', label: 'Deleted', format: 'boolean' },+ ],+ } satisfies OutputSchema,+ agreementList: listSchema({ key: 'agreements', label: 'Agreements', labelKey: 'name', itemLabel: '{name}', fields: agreementFields }),+ formSubmission: { fields: formSubmissionFields } satisfies OutputSchema,+ attachment: {+ fields: [+ { key: 'url', label: 'File URL', format: 'url' },+ { key: 'objectType', label: 'Attached To Type' },+ { key: 'objectId', label: 'Attached To ID' },+ { key: 'fileName', label: 'File Name' },+ ],+ } satisfies OutputSchema,+ nameList: listSchema({ key: 'items', label: 'Names', labelKey: 'name', itemLabel: '{name}', fields: [{ key: 'name', label: 'Name' }] }),+ taskStageList: listSchema({ key: 'stages', label: 'Task Stages', labelKey: 'label', itemLabel: '{label}', fields: taskStageFields }),+ projectTypeList: listSchema({ key: 'projectTypes', label: 'Project Types', labelKey: 'name', itemLabel: '{name}', fields: projectTypeFields }),+ emailTemplateList: listSchema({ key: 'templates', label: 'Email Templates', labelKey: 'name', itemLabel: '{name}', fields: idNameFields }),+ emailTemplate: {+ fields: [+ { key: 'id', label: 'Template ID' },+ { key: 'name', label: 'Name' },+ { key: 'subject', label: 'Subject' },+ { key: 'htmlContent', label: 'HTML Content', format: 'html' },+ ],+ } satisfies OutputSchema,+ account: { fields: accountFields } satisfies OutputSchema,};++function listSchema({ key, label, labelKey, itemLabel, fields }: { key: string; label: string; labelKey: string; itemLabel: string; fields: OutputSchema['fields'] }): OutputSchema {+ return { itemLabel, fields: [{ key, label, value: '', labelKey, listItems: fields }] };+}diff --git a/packages/pieces/community/moxie-crm/src/lib/triggers/index.ts b/packages/pieces/community/moxie-crm/src/lib/triggers/index.tsindex e099abe962b..b77c99fa4cf 100644--- a/packages/pieces/community/moxie-crm/src/lib/triggers/index.ts+++ b/packages/pieces/community/moxie-crm/src/lib/triggers/index.ts@@ -22,9 +22,108 @@ export const enum MoxieCRMEventType {OPPORTUNITY_DELETED = 'OpportunityDelete',INVOICE_SENT = 'InvoiceSent',PAYMENT_RECEIVED = 'PaymentReceived',+ INVOICE_VOIDED = 'InvoiceVoided',+ INVOICE_WRITE_OFF = 'InvoiceWriteOff',+ AGREEMENT_SENT = 'AgreementSent',+ AGREEMENT_VIEWED = 'AgreementViewed',+ AGREEMENT_SIGNED = 'AgreementSigned',+ TICKET_CREATED = 'TicketCreate',+ TICKET_UPDATED = 'TicketUpdate',+ TICKET_CLOSED = 'TicketClose',+ TICKET_COMMENT = 'TicketComment',+ TICKET_DELETED = 'TicketDelete',}const MoxieCRMWebhookSampleData = {+ INVOICE_VOIDED_SAMPLE_DATA: {+ id: '66b0f2a1c3a9e40012ab34cd',+ accountId: 10016,+ invoiceNumber: 1042,+ invoiceNumberFormatted: 'E-2026-042',+ clientId: '66b0f2a1c3a9e40012ab34cd',+ status: 'VOIDED',+ invoiceType: 'STANDARD',+ currency: 'HUF',+ subTotal: 100.0,+ tax: 15.47,+ taxPercentage: 15.47375,+ taxBreakdown: [+ { name: 'GST', rate: 5.0, order: 0, compound: false, taxableAmount: 100.0, amount: 5.0 },+ { name: 'PST', rate: 9.975, order: 1, compound: true, taxableAmount: 105.0, amount: 10.47 },+ ],+ total: 115.47,+ amountDue: 0.0,+ viewOnlineUrl: 'https://pay.withmoxie.com/i/...',+ payments: [],+ },+ AGREEMENT_EVENT_SAMPLE_DATA: {+ id: '66c1a2b3c4d5e60012ab3401',+ accountId: 10016,+ name: 'Website Redesign Agreement',+ client: {+ id: '64b800010000000000000000',+ name: 'Moxie, Inc.',+ clientType: 'Client',+ },+ status: 'Finalized',+ statusTime: '2026-09-30T14:05:00.000Z',+ currency: 'USD',+ dateCreated: '2026-09-28T10:00:00.000Z',+ dateCompleted: null,+ fullyExecuted: false,+ userSigned: true,+ clientSigned: false,+ },+ TICKET_EVENT_SAMPLE_DATA: {+ ticket: {+ id: '66d2b3c4d5e6f70012ab3402',+ accountId: 10016,+ clientId: '64b800010000000000000000',+ clientContactId: -1,+ ticketNumber: 1001,+ ccList: [],+ assignedTo: [54197],+ mergedTickets: [],+ dueDate: '2026-10-05',+ subject: 'Website contact form is not sending email',+ open: true,+ type: '23e90abb-21c3-4a28-abdd-85b7bb4e3031',+ status: 'New',+ unread: false,+ unreadClient: true,+ lastComment: 'The contact form on the home page stopped sending email yesterday.',+ formData: null,+ summary: null,+ created: '2026-09-30T09:12:00.000Z',+ updated: '2026-09-30T09:12:00.000Z',+ closed: null,+ snoozedUntil: null,+ archived: false,+ client: {+ id: '64b800010000000000000000',+ name: 'Moxie, Inc.',+ clientType: 'Client',+ },+ },+ comments: [+ {+ id: '66d2b3c4d5e6f70012ab3404',+ accountId: 10016,+ ticketId: '66d2b3c4d5e6f70012ab3402',+ clientId: '64b800010000000000000000',+ commentType: 'PUBLIC',+ commentBy: -1,+ commentUserEmail: '[email protected]',+ commentUserName: 'Jane Doe',+ attachments: [],+ comment: 'The contact form on the home page stopped sending email yesterday.',+ fromEmail: false,+ created: '2026-09-30T09:12:00.000Z',+ updated: null,+ commentFormat: 'PlainText',+ },+ ],+ },PROJECT_EVENT_SAMPLE_DATA: {id: '64b800020000000000000000',accountId: 10016,@@ -749,4 +848,114 @@ export const moxieCRMTriggers = [eventType: MoxieCRMEventType.PAYMENT_RECEIVED,sampleData: MoxieCRMWebhookSampleData.INVOICE_EVENT_SAMPLE_DATA,},+ {+ name: 'invoice_voided',+ displayName: 'Invoice Voided',+ description: 'Triggered when a sent invoice is voided.',+ aiMetadata: {+ description: "Fires once when a sent invoice with no payments is voided in Moxie and moves to VOIDED. Use to cancel the matching invoice or post a reversal in an accounting system.",+ },+ eventType: MoxieCRMEventType.INVOICE_VOIDED,+ sampleData: MoxieCRMWebhookSampleData.INVOICE_VOIDED_SAMPLE_DATA,+ autoRegister: true,+ },+ {+ name: 'invoice_write_off',+ displayName: 'Invoice Written Off',+ description: 'Triggered when an invoice is written off.',+ aiMetadata: {+ description: "Fires once when a sent or partially paid invoice is written off in Moxie and moves to WRITE-OFF. Use to record the bad debt or close the receivable elsewhere.",+ },+ eventType: MoxieCRMEventType.INVOICE_WRITE_OFF,+ sampleData: MoxieCRMWebhookSampleData.INVOICE_EVENT_SAMPLE_DATA,+ autoRegister: true,+ },+ {+ name: 'agreement_sent',+ displayName: 'Agreement Sent',+ description: 'Triggered when an agreement is sent to a client.',+ aiMetadata: {+ description: "Fires once when an agreement (contract) is sent to a client from Moxie. Use to follow up or log the outgoing contract.",+ },+ eventType: MoxieCRMEventType.AGREEMENT_SENT,+ sampleData: MoxieCRMWebhookSampleData.AGREEMENT_EVENT_SAMPLE_DATA,+ autoRegister: true,+ },+ {+ name: 'agreement_viewed',+ displayName: 'Agreement Viewed',+ description: 'Triggered when a client views an agreement.',+ aiMetadata: {+ description: "Fires when a client opens an agreement sent from Moxie. Use to time a follow-up while the client is engaged.",+ },+ eventType: MoxieCRMEventType.AGREEMENT_VIEWED,+ sampleData: MoxieCRMWebhookSampleData.AGREEMENT_EVENT_SAMPLE_DATA,+ autoRegister: true,+ },+ {+ name: 'agreement_signed',+ displayName: 'Agreement Signed',+ description: 'Triggered when an agreement is signed.',+ aiMetadata: {+ description: "Fires when an agreement is signed in Moxie. Use to start onboarding, create the project or send the deposit invoice once the contract is signed.",+ },+ eventType: MoxieCRMEventType.AGREEMENT_SIGNED,+ sampleData: MoxieCRMWebhookSampleData.AGREEMENT_EVENT_SAMPLE_DATA,+ autoRegister: true,+ },+ {+ name: 'ticket_created',+ displayName: 'Ticket Created',+ description: 'Triggered when a new support ticket is created.',+ aiMetadata: {+ description: "Fires once when a new support ticket is created in Moxie, from the client portal, email or the API. Use to route or acknowledge new client requests.",+ },+ eventType: MoxieCRMEventType.TICKET_CREATED,+ sampleData: MoxieCRMWebhookSampleData.TICKET_EVENT_SAMPLE_DATA,+ autoRegister: true,+ },+ {+ name: 'ticket_updated',+ displayName: 'Ticket Updated',+ description: 'Triggered when a ticket is updated.',+ aiMetadata: {+ description: "Fires when an existing ticket changes in Moxie, such as its status, assignee or due date. Use to keep another help desk or task list in sync.",+ },+ eventType: MoxieCRMEventType.TICKET_UPDATED,+ sampleData: MoxieCRMWebhookSampleData.TICKET_EVENT_SAMPLE_DATA,+ autoRegister: true,+ },+ {+ name: 'ticket_closed',+ displayName: 'Ticket Closed',+ description: 'Triggered when a ticket is closed.',+ aiMetadata: {+ description: "Fires when a ticket is closed in Moxie. Use to send a satisfaction survey or close the matching item elsewhere.",+ },+ eventType: MoxieCRMEventType.TICKET_CLOSED,+ sampleData: MoxieCRMWebhookSampleData.TICKET_EVENT_SAMPLE_DATA,+ autoRegister: true,+ },+ {+ name: 'ticket_comment_added',+ displayName: 'Ticket Comment Added',+ description: 'Triggered when a comment is added to a ticket.',+ aiMetadata: {+ description: "Fires when a comment is added to a ticket in Moxie, by the team or the client. Use to notify the assignee or mirror the conversation.",+ },+ eventType: MoxieCRMEventType.TICKET_COMMENT,+ sampleData: MoxieCRMWebhookSampleData.TICKET_EVENT_SAMPLE_DATA,+ autoRegister: true,+ },+ {+ name: 'ticket_deleted',+ displayName: 'Ticket Deleted',+ description: 'Triggered when a ticket is deleted.',+ aiMetadata: {+ description: "Fires when a ticket is deleted in Moxie. Use to remove the matching item from other systems.",+ },+ eventType: MoxieCRMEventType.TICKET_DELETED,+ sampleData: MoxieCRMWebhookSampleData.TICKET_EVENT_SAMPLE_DATA,+ autoRegister: true,+ },].map((props) => moxieCRMRegisterTrigger(props));diff --git a/packages/pieces/community/moxie-crm/src/lib/triggers/register-trigger.ts b/packages/pieces/community/moxie-crm/src/lib/triggers/register-trigger.tsindex 9864552be05..a33e9529b76 100644--- a/packages/pieces/community/moxie-crm/src/lib/triggers/register-trigger.ts+++ b/packages/pieces/community/moxie-crm/src/lib/triggers/register-trigger.ts@@ -1,12 +1,15 @@import {+ AiMetadata,+ OutputSchema,+ Property,TriggerStrategy,createTrigger,- Property,- AiMetadata,} from '@activepieces/pieces-framework';-import { MoxieCRMEventType } from '.';import { moxieCRMAuth } from '../auth';+import { credentialsOf } from '../common';+import { moxieWebhook } from '../common/webhook';import { moxieCRMTriggerOutputSchemas } from '../output-schemas';+export const moxieCRMRegisterTrigger = ({name,displayName,@@ -14,15 +17,53 @@ export const moxieCRMRegisterTrigger = ({aiMetadata,eventType,sampleData,+ autoRegister,}: {name: string;displayName: string;description: string;aiMetadata?: AiMetadata;- eventType: MoxieCRMEventType;+ eventType: string;sampleData: unknown;-}) =>- createTrigger({+ autoRegister?: boolean;+}) => {+ const outputSchema: OutputSchema | undefined = moxieCRMTriggerOutputSchemas[name];+ if (autoRegister === true) {+ return createTrigger({+ auth: moxieCRMAuth,+ name: `moxie_trigger_${name}`,+ classification: 'READ',+ displayName,+ description,+ aiMetadata,+ props: {+ md: Property.MarkDown({+ value: `This trigger registers its webhook in Moxie automatically when the flow is published, and removes it when the flow is turned off. There is nothing to set up in Moxie.`,+ }),+ },+ outputSchema,+ type: TriggerStrategy.WEBHOOK,+ sampleData,+ async onEnable(context) {+ await moxieWebhook.enable({+ credentials: credentialsOf({ auth: context.auth }),+ store: context.store,+ type: eventType,+ hookUrl: context.webhookUrl,+ });+ },+ async onDisable(context) {+ await moxieWebhook.disable({+ credentials: credentialsOf({ auth: context.auth }),+ store: context.store,+ });+ },+ async run(context) {+ return moxieWebhook.acceptDelivery({ eventType, payload: context.payload });+ },+ });+ }+ return createTrigger({auth: moxieCRMAuth,name: `moxie_trigger_${name}`,classification: 'READ',@@ -32,28 +73,30 @@ export const moxieCRMRegisterTrigger = ({props: {md: Property.MarkDown({value: `- - Go to the **Workspace Settngs -> Connected Apps -> Integration** section.- - Under **Custom Integration** , click on **Add Rest Hook**.- - Click on **Integrations** section.- - In the endpoint field, paste the following URL:+ - In Moxie, go to **Workspace Settings > Connected Apps > Integrations**.+ - Under **Custom Integration**, click **Add Rest Hook**.+ - In the endpoint field, paste the following URL:\`\`\`text{{webhookUrl}}\`\`\`- - Select the event as **\`${displayName}\`** and click on **Save**.+ - Select the event **\`${displayName}\`** and click **Save**.++ Deliveries for any other event type are ignored, and a delivery repeated within 15 minutes runs the flow only once.`,}),},- outputSchema: moxieCRMTriggerOutputSchemas[name],+ outputSchema,type: TriggerStrategy.WEBHOOK,- sampleData: sampleData,- async onEnable(context) {- // Empty+ sampleData,+ async onEnable() {+ return;},- async onDisable(context) {- // Empty+ async onDisable() {+ return;},async run(context) {- return [context.payload.body];+ return moxieWebhook.acceptDelivery({ eventType, payload: context.payload });},});+};diff --git a/packages/pieces/community/moxie-crm/test/actions.test.ts b/packages/pieces/community/moxie-crm/test/actions.test.tsnew file mode 100644index 00000000000..b8b0071abac--- /dev/null+++ b/packages/pieces/community/moxie-crm/test/actions.test.ts@@ -0,0 +1,761 @@+import { beforeEach, describe, expect, test, vi } from 'vitest';+import { HttpMethod } from '@activepieces/pieces-common';+import { BASE, fail, lastRequest, loadOptions, ok, request, runAction, sendRequest } from './helpers';+import { moxieCrm } from '../src';+import { moxieClientCreateAction } from '../src/lib/actions/ai/client-create';+import { moxieClientUpdateAction } from '../src/lib/actions/ai/client-update';+import { moxieContactCreateAction } from '../src/lib/actions/ai/contact-create';+import { moxieContactUpdateAction } from '../src/lib/actions/ai/contact-update';+import { moxieExpenseCreateAction } from '../src/lib/actions/ai/expense-create';+import { moxieInvoiceCreateAction } from '../src/lib/actions/ai/invoice-create';+import { moxieOpportunityCreateAction } from '../src/lib/actions/ai/opportunity-create';+import { moxieOpportunityUpdateAction } from '../src/lib/actions/ai/opportunity-update';+import { moxiePaymentCreateAction } from '../src/lib/actions/ai/payment-create';+import { moxieProjectCreateAction } from '../src/lib/actions/ai/project-create';+import { moxieProjectUpdateAction } from '../src/lib/actions/ai/project-update';+import { moxieTaskCreateAction } from '../src/lib/actions/ai/task-create';+import { moxieTaskUpdateAction } from '../src/lib/actions/ai/task-update';+import { moxieTimeEntryCreateAction } from '../src/lib/actions/ai/time-entry-create';+import { moxieAddTicketCommentAction } from '../src/lib/actions/add-ticket-comment';+import { moxieApplyPaymentAction } from '../src/lib/actions/apply-payment';+import { moxieApproveTaskAction } from '../src/lib/actions/approve-task';+import { moxieAttachFileFromUrlAction } from '../src/lib/actions/attach-file-from-url';+import { moxieCreateExpenseAction } from '../src/lib/actions/create-expense';+import { moxieCreateFormSubmissionAction } from '../src/lib/actions/create-form-submission';+import { moxieCreateInvoiceAction } from '../src/lib/actions/create-invoice';+import { moxieCreateOpportunityAction } from '../src/lib/actions/create-opportunity';+import { moxieCreateOrUpdateCalendarEventAction } from '../src/lib/actions/create-or-update-calendar-event';+import { moxieCreateProjectAction } from '../src/lib/actions/create-project';+import { moxieCreateTaskAction } from '../src/lib/actions/create-task';+import { moxieCreateTicketAction } from '../src/lib/actions/create-ticket';+import { moxieCreateTimeEntryAction } from '../src/lib/actions/create-time-entry';+import { moxieDeleteCalendarEventAction } from '../src/lib/actions/delete-calendar-event';+import { moxieGetEmailTemplateAction } from '../src/lib/actions/get-email-template';+import { moxieGetWorkspaceAccountAction } from '../src/lib/actions/get-workspace-account';+import { moxieListEmailTemplatesAction } from '../src/lib/actions/list-email-templates';+import { moxieListFormNamesAction } from '../src/lib/actions/list-form-names';+import { moxieListProjectTypesAction } from '../src/lib/actions/list-project-types';+import { moxieListTaskStagesAction } from '../src/lib/actions/list-task-stages';+import { moxieListTasksAction } from '../src/lib/actions/list-tasks';+import { moxieListTicketsAction } from '../src/lib/actions/list-tickets';+import { moxieListVendorsAction } from '../src/lib/actions/list-vendors';+import { moxieSearchAgreementsAction } from '../src/lib/actions/search-agreements';+import { moxieSearchClientsAction } from '../src/lib/actions/search-clients';+import { moxieSearchContactsAction } from '../src/lib/actions/search-contacts';+import { moxieSearchPayableInvoicesAction } from '../src/lib/actions/search-payable-invoices';+import { moxieSearchProjectsAction } from '../src/lib/actions/search-projects';+import { moxieSearchTasksAction } from '../src/lib/actions/search-tasks';+import { moxieSearchTicketsAction } from '../src/lib/actions/search-tickets';+import { moxieUpdateClientAction } from '../src/lib/actions/update-client';+import { moxieUpdateContactAction } from '../src/lib/actions/update-contact';+import { moxieUpdateExpenseAction } from '../src/lib/actions/update-expense';+import { moxieUpdateOpportunityAction } from '../src/lib/actions/update-opportunity';+import { moxieUpdateProjectAction } from '../src/lib/actions/update-project';+import { moxieUpdateTaskAction } from '../src/lib/actions/update-task';+import { moxieUpdateTicketStatusAction } from '../src/lib/actions/update-ticket-status';+import { moxieUploadAttachmentAction } from '../src/lib/actions/upload-attachment';++vi.mock('@activepieces/pieces-common', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@activepieces/pieces-common')>();+ return { ...actual, httpClient: { sendRequest: (...args: unknown[]) => sendRequest(...args) } };+});++beforeEach(() => {+ sendRequest.mockReset();+ sendRequest.mockResolvedValue({ status: 200, headers: {}, body: {} });+});++describe('piece metadata', () => {+ const actions = Object.values(moxieCrm.actions());+ const handWritten = actions.filter((a) => a.name !== 'custom_api_call');++ test('58 hand-written actions: 14 ai atomics, 11 human, 33 both, plus the custom API call', () => {+ expect(handWritten).toHaveLength(58);+ expect(handWritten.filter((a) => a.audience === 'ai')).toHaveLength(14);+ expect(handWritten.filter((a) => a.audience === 'human')).toHaveLength(11);+ expect(handWritten.filter((a) => a.audience === 'both')).toHaveLength(33);+ });++ test('every hand-written action has classification and aiMetadata, and every new one an outputSchema', () => {+ for (const action of handWritten) {+ expect(action.classification, action.name).toBeDefined();+ expect(action.aiMetadata?.description, action.name).toBeTruthy();+ expect(typeof action.aiMetadata?.idempotent, action.name).toBe('boolean');+ if (action.name !== 'moxie_list_invoice_templates') {+ expect(action.outputSchema, action.name).toBeDefined();+ }+ }+ });++ test('the four twinned originals are not demoted before Tier-2', () => {+ const audience = Object.fromEntries(handWritten.map((a) => [a.name, a.audience]));+ for (const name of ['moxie_create_client', 'moxie_create_contact', 'moxie_create_project', 'moxie_create_task']) {+ expect(audience[name], name).toBe('both');+ }+ });++ test('only Delete Calendar Event is destructive', () => {+ expect(handWritten.filter((a) => a.classification === 'DESTRUCTIVE').map((a) => a.name)).toEqual([+ 'moxie_delete_calendar_event',+ ]);+ });++ test('fixed defaults: portal access matches its option, task status has no invented default', () => {+ expect(moxieCreateProjectAction.props.portalAccess.defaultValue).toBe('Read only');+ expect(moxieCreateTaskAction.props.status.defaultValue).toBeUndefined();+ });++ test('the release floor is 0.88.2', () => {+ expect(moxieCrm.minimumSupportedRelease).toBe('0.88.2');+ });+});++const requestCases: Case[] = [+ {+ name: 'client create sends only set fields',+ action: moxieClientCreateAction,+ props: { name: ' Acme ', clientType: 'prospect', hourlyAmount: '90', archive: 'no', city: '' },+ method: HttpMethod.POST,+ path: '/action/clients/create',+ body: { name: 'Acme', clientType: 'Prospect', hourlyAmount: 90, archive: false },+ },+ {+ name: 'client update patches by id with clears',+ action: moxieClientUpdateAction,+ props: { clientId: 'c1', phone: '+1555', clearFields: ['notes'] },+ method: HttpMethod.PATCH,+ path: '/action/clients/update',+ body: { id: 'c1', phone: '+1555', notes: '' },+ },+ {+ name: 'human client update uses the same body',+ action: moxieUpdateClientAction,+ props: { clientId: 'c1', archive: 'yes' },+ method: HttpMethod.PATCH,+ path: '/action/clients/update',+ body: { id: 'c1', archive: true },+ },+ {+ name: 'contact create uses first/last keys',+ action: moxieContactCreateAction,+ props: { first: 'Ada', last: 'Chen', email: '[email protected]', clientName: 'Acme', portalAccess: 'yes' },+ method: HttpMethod.POST,+ path: '/action/contacts/create',+ body: { first: 'Ada', last: 'Chen', email: '[email protected]', clientName: 'Acme', portalAccess: true },+ },+ {+ name: 'contact update uses firstName/lastName keys and can move the client',+ action: moxieContactUpdateAction,+ props: { contactId: 'k1', firstName: 'Ada', clientId: 'c2', invoiceContact: 'no' },+ method: HttpMethod.PATCH,+ path: '/action/contacts/update',+ body: { id: 'k1', firstName: 'Ada', invoiceContact: false, clientId: 'c2' },+ },+ {+ name: 'human contact update',+ action: moxieUpdateContactAction,+ props: { contactId: 'k1', role: 'CEO' },+ method: HttpMethod.PATCH,+ path: '/action/contacts/update',+ body: { id: 'k1', role: 'CEO' },+ },+ {+ name: 'project create without a fee type sends no fee schedule',+ action: moxieProjectCreateAction,+ props: { name: 'Site', clientName: 'Acme', startDate: '2026-10-01', portalAccess: 'read only', templateName: 'Web' },+ method: HttpMethod.POST,+ path: '/action/projects/create',+ body: { name: 'Site', clientName: 'Acme', startDate: '2026-10-01', portalAccess: 'Read only', templateName: 'Web' },+ },+ {+ name: 'project create with a fee type nests the fee schedule',+ action: moxieProjectCreateAction,+ props: { name: 'Site', clientName: 'Acme', feeType: 'Hourly', amount: 120, taxable: 'yes' },+ method: HttpMethod.POST,+ path: '/action/projects/create',+ body: { name: 'Site', clientName: 'Acme', feeSchedule: { feeType: 'Hourly', amount: 120, taxable: true } },+ },+ {+ name: 'project update',+ action: moxieProjectUpdateAction,+ props: { projectId: 'p1', dueDate: '2026-12-31', active: 'no' },+ method: HttpMethod.PATCH,+ path: '/action/projects/update',+ body: { id: 'p1', dueDate: '2026-12-31', active: false },+ },+ {+ name: 'human project update takes the date part of a DateTime',+ action: moxieUpdateProjectAction,+ props: { clientName: 'Acme', projectId: 'p1', startDate: '2026-10-01T00:00:00.000Z' },+ method: HttpMethod.PATCH,+ path: '/action/projects/update',+ body: { id: 'p1', startDate: '2026-10-01' },+ },+ {+ name: 'task create sends names, subtasks and assignees, no default stage',+ action: moxieTaskCreateAction,+ props: { name: 'Wireframes', clientName: 'Acme', projectName: 'Site', tasks: ['a', ''], assignedTo: ['[email protected]'] },+ method: HttpMethod.POST,+ path: '/action/tasks/create',+ body: { name: 'Wireframes', clientName: 'Acme', projectName: 'Site', tasks: ['a'], assignedTo: ['[email protected]'] },+ },+ {+ name: 'task update moves the stage and replaces assignees',+ action: moxieTaskUpdateAction,+ props: { taskId: 't1', statusId: 's2', assignedToList: ['7', 8], clearFields: ['description'] },+ method: HttpMethod.PATCH,+ path: '/action/tasks/update',+ body: { id: 't1', statusId: 's2', assignedToList: [7, 8], description: '' },+ },+ {+ name: 'human task update',+ action: moxieUpdateTaskAction,+ props: { clientName: 'Acme', projectId: 'p1', taskId: 't1', priority: 3 },+ method: HttpMethod.PATCH,+ path: '/action/tasks/update',+ body: { id: 't1', priority: 3 },+ },+ {+ name: 'opportunity create',+ action: moxieOpportunityCreateAction,+ props: { name: 'Redesign', clientName: 'Acme', stageName: 'Qualified', value: 5000, estCloseDate: '2026-11-01' },+ method: HttpMethod.POST,+ path: '/action/opportunities/create',+ body: { name: 'Redesign', clientName: 'Acme', stageName: 'Qualified', value: 5000, estCloseDate: '2026-11-01' },+ },+ {+ name: 'human opportunity create',+ action: moxieCreateOpportunityAction,+ props: { name: 'Redesign', stageName: 'New' },+ method: HttpMethod.POST,+ path: '/action/opportunities/create',+ body: { name: 'Redesign', stageName: 'New' },+ },+ {+ name: 'opportunity update moves the stage',+ action: moxieOpportunityUpdateAction,+ props: { opportunityId: 'o1', statusId: 'st3', sentiment: 4, archive: 'yes' },+ method: HttpMethod.PATCH,+ path: '/action/opportunities/update',+ body: { id: 'o1', statusId: 'st3', sentiment: 4, archive: true },+ },+ {+ name: 'human opportunity update',+ action: moxieUpdateOpportunityAction,+ props: { opportunityId: 'o1', clientId: 'c1' },+ method: HttpMethod.PATCH,+ path: '/action/opportunities/update',+ body: { id: 'o1', clientId: 'c1' },+ },+ {+ name: 'invoice create stays a draft by default',+ action: moxieInvoiceCreateAction,+ props: { clientName: 'Acme', items: [{ description: 'Design', quantity: 2, rate: '50', taxable: true }], taxRate: 10 },+ method: HttpMethod.POST,+ path: '/action/invoices/create',+ body: { clientName: 'Acme', items: [{ description: 'Design', quantity: 2, rate: 50, taxable: true }], taxRate: 10 },+ },+ {+ name: 'invoice create with send builds sendTo',+ action: moxieCreateInvoiceAction,+ props: {+ clientName: 'Acme',+ templateName: 'Default',+ items: [{ description: 'Design', quantity: 1, rate: 100 }],+ send: true,+ sendToContacts: ['[email protected]'],+ emailTemplateName: 'Invoice',+ },+ method: HttpMethod.POST,+ path: '/action/invoices/create',+ body: {+ clientName: 'Acme',+ items: [{ description: 'Design', quantity: 1, rate: 100 }],+ templateName: 'Default',+ sendTo: { send: true, contacts: ['[email protected]'], emailTemplateName: 'Invoice' },+ },+ },+ {+ name: 'time entry create normalises timestamps and only sends true create flags',+ action: moxieTimeEntryCreateAction,+ props: {+ timerStart: '2026-10-01T09:00:00Z',+ timerEnd: '2026-10-01T10:30:00Z',+ clientName: 'Acme',+ createProject: true,+ createClient: false,+ },+ method: HttpMethod.POST,+ path: '/action/timeWorked/create',+ body: {+ timerStart: '2026-10-01T09:00:00.000Z',+ timerEnd: '2026-10-01T10:30:00.000Z',+ clientName: 'Acme',+ createProject: true,+ },+ },+ {+ name: 'human time entry create',+ action: moxieCreateTimeEntryAction,+ props: { timerStart: '2026-10-01T09:00:00.000Z', timerEnd: '2026-10-01T09:15:00.000Z', userEmail: '[email protected]' },+ method: HttpMethod.POST,+ path: '/action/timeWorked/create',+ body: { timerStart: '2026-10-01T09:00:00.000Z', timerEnd: '2026-10-01T09:15:00.000Z', userEmail: '[email protected]' },+ },+ {+ name: 'expense create',+ action: moxieExpenseCreateAction,+ props: { amount: 42.5, vendor: 'Adobe', paid: 'yes', markupPercentage: 10 },+ method: HttpMethod.POST,+ path: '/action/expenses/create',+ body: { amount: 42.5, vendor: 'Adobe', paid: true, markupPercentage: 10 },+ },+ {+ name: 'human expense create',+ action: moxieCreateExpenseAction,+ props: { amount: 10, clientName: 'Acme', reimbursable: 'yes' },+ method: HttpMethod.POST,+ path: '/action/expenses/create',+ body: { amount: 10, markupPercentage: 0, clientName: 'Acme', reimbursable: true },+ },+ {+ name: 'expense update uses Expense keys',+ action: moxieUpdateExpenseAction,+ props: { expenseId: 'e1', markupPercent: 5, paidDate: '2026-10-02', clearFields: ['billNo'] },+ method: HttpMethod.PATCH,+ path: '/action/expenses/update',+ body: { id: 'e1', markupPercent: 5, paidDate: '2026-10-02', billNo: '' },+ },+ {+ name: 'search tasks by query',+ action: moxieSearchTasksAction,+ props: { query: 'logo' },+ method: HttpMethod.GET,+ path: '/action/tasks/search',+ query: { query: 'logo' },+ },+ {+ name: 'search tasks by id ignores the query',+ action: moxieSearchTasksAction,+ props: { query: 'logo', id: 't1' },+ method: HttpMethod.GET,+ path: '/action/tasks/search',+ query: { id: 't1' },+ },+ {+ name: 'list tasks with filters',+ action: moxieListTasksAction,+ props: { projectId: 'p1', archived: 'no' },+ method: HttpMethod.GET,+ path: '/action/tasks/list',+ query: { projectId: 'p1', archived: 'false' },+ },+ {+ name: 'approve task maps the task name to deliverableName',+ action: moxieApproveTaskAction,+ props: { clientName: 'Acme', projectName: 'Site', taskName: 'Logo' },+ method: HttpMethod.POST,+ path: '/action/deliverable/approve',+ body: { clientName: 'Acme', projectName: 'Site', deliverableName: 'Logo' },+ },+ {+ name: 'search payable invoices by client',+ action: moxieSearchPayableInvoicesAction,+ props: { clientName: 'Acme' },+ method: HttpMethod.GET,+ path: '/action/payableInvoices/search',+ query: { query: 'Acme' },+ },+ {+ name: 'form submission with answers',+ action: moxieCreateFormSubmissionAction,+ props: { formName: 'Intake', email: '[email protected]', answers: [{ question: 'Budget?', answer: '5k' }] },+ method: HttpMethod.POST,+ path: '/action/formSubmissions/create',+ body: { formName: 'Intake', email: '[email protected]', answers: [{ question: 'Budget?', answer: '5k' }] },+ },+ {+ name: 'create ticket',+ action: moxieCreateTicketAction,+ props: { subject: 'Bug', comment: 'Broken', userEmail: '[email protected]', ticketType: 'Support', dueDate: '2026-10-05' },+ method: HttpMethod.POST,+ path: '/action/tickets/create',+ body: { subject: 'Bug', comment: 'Broken', userEmail: '[email protected]', ticketType: 'Support', dueDate: '2026-10-05' },+ },+ {+ name: 'add ticket comment uses privateComment',+ action: moxieAddTicketCommentAction,+ props: { ticketNumber: 1001, comment: 'On it', userEmail: '[email protected]', privateComment: true },+ method: HttpMethod.POST,+ path: '/action/tickets/comments/create',+ body: { ticketNumber: 1001, comment: 'On it', userEmail: '[email protected]', privateComment: true },+ },+ {+ name: 'update ticket status by number',+ action: moxieUpdateTicketStatusAction,+ props: { ticketNumber: 1001, status: 'Closed' },+ method: HttpMethod.PATCH,+ path: '/action/tickets/status',+ body: { ticketNumber: 1001, status: 'Closed' },+ },+ {+ name: 'search tickets by number',+ action: moxieSearchTicketsAction,+ props: { ticketNumber: 1001 },+ method: HttpMethod.GET,+ path: '/action/tickets/search',+ query: { ticketNumber: '1001' },+ },+ {+ name: 'list tickets open only',+ action: moxieListTicketsAction,+ props: { open: 'yes' },+ method: HttpMethod.GET,+ path: '/action/tickets/list',+ query: { open: 'true' },+ },+ {+ name: 'attach from URL sends query params only',+ action: moxieAttachFileFromUrlAction,+ props: { objectType: 'CLIENT', objectId: 'c1', fileUrl: 'https://cdn.example.com/a.pdf', fileName: 'a.pdf' },+ method: HttpMethod.POST,+ path: '/action/attachments/createFromUrl',+ query: { id: 'c1', type: 'CLIENT', fileUrl: 'https://cdn.example.com/a.pdf', fileName: 'a.pdf' },+ },+ {+ name: 'calendar event create maps to startTime/endTime',+ action: moxieCreateOrUpdateCalendarEventAction,+ props: { startTime: '2026-10-01T09:00:00Z', endTime: '2026-10-01T10:00:00Z', summary: 'Kickoff', busy: 'yes' },+ method: HttpMethod.POST,+ path: '/action/calendar/createOrUpdate',+ body: {+ startTime: '2026-10-01T09:00:00.000Z',+ endTime: '2026-10-01T10:00:00.000Z',+ busy: true,+ summary: 'Kickoff',+ },+ },+ {+ name: 'calendar event update by id',+ action: moxieCreateOrUpdateCalendarEventAction,+ props: { eventId: 'ev1', location: 'Zoom' },+ method: HttpMethod.POST,+ path: '/action/calendar/createOrUpdate',+ body: { eventId: 'ev1', location: 'Zoom' },+ },+ {+ name: 'search agreements by client',+ action: moxieSearchAgreementsAction,+ props: { clientId: 'c1' },+ method: HttpMethod.GET,+ path: '/action/agreements/search',+ query: { clientId: 'c1' },+ },+ {+ name: 'list task stages for a project type',+ action: moxieListTaskStagesAction,+ props: { projectTypeId: 'pt1' },+ method: HttpMethod.GET,+ path: '/action/taskStages/list',+ query: { projectTypeId: 'pt1' },+ },+ { name: 'list project types', action: moxieListProjectTypesAction, props: {}, method: HttpMethod.GET, path: '/action/projectTypes/list' },+ { name: 'list email templates', action: moxieListEmailTemplatesAction, props: {}, method: HttpMethod.GET, path: '/action/emailTemplates' },+ {+ name: 'get email template encodes the id',+ action: moxieGetEmailTemplateAction,+ props: { templateId: 'tpl-1' },+ method: HttpMethod.GET,+ path: '/action/emailTemplates/tpl-1',+ },+ {+ name: 'search clients by id',+ action: moxieSearchClientsAction,+ props: { id: 'c1' },+ method: HttpMethod.GET,+ path: '/action/clients/search',+ query: { id: 'c1' },+ },+ {+ name: 'search contacts by id',+ action: moxieSearchContactsAction,+ props: { id: 'k1' },+ method: HttpMethod.GET,+ path: '/action/contacts/search',+ query: { id: 'k1' },+ },+ {+ name: 'search projects with no input lists all projects',+ action: moxieSearchProjectsAction,+ props: {},+ method: HttpMethod.GET,+ path: '/action/projects/search',+ },+];++describe('outgoing requests', () => {+ test.each(requestCases)('$name', async ({ action, props, method, path, body, query }) => {+ await runAction({ action, props });+ const sent = lastRequest();+ expect(sent['method']).toBe(method);+ expect(sent['url']).toBe(`${BASE}${path}`);+ if (body === undefined) {+ expect(sent['body']).toBeUndefined();+ } else {+ expect(sent['body']).toEqual(body);+ }+ expect(sent['queryParams']).toEqual(query);+ });++ test('legacy create project keeps its fee schedule and adds template only when set', async () => {+ await runAction({+ action: moxieCreateProjectAction,+ props: { name: 'Site', clientName: 'Acme', portalAccess: 'Read only', feeType: 'Hourly', amount: 0, templateName: 'Web' },+ });+ expect(lastRequest()['body']).toEqual({+ name: 'Site',+ clientName: 'Acme',+ portalAccess: 'Read only',+ feeSchedule: { feeType: 'Hourly', amount: 0 },+ templateName: 'Web',+ });+ });++ test('legacy create task keeps sending empty subtask, assignee and custom value defaults', async () => {+ await runAction({ action: moxieCreateTaskAction, props: { name: 'T', clientName: 'Acme', projectName: 'Site', status: 'To Do' } });+ expect(lastRequest()['body']).toEqual({+ name: 'T',+ clientName: 'Acme',+ projectName: 'Site',+ status: 'To Do',+ tasks: [],+ assignedTo: [],+ customValues: {},+ });+ });++ test('delete calendar event returns the id and a deleted flag', async () => {+ ok({ body: undefined });+ await expect(runAction({ action: moxieDeleteCalendarEventAction, props: { eventId: 'ev1' } })).resolves.toEqual({+ id: 'ev1',+ deleted: true,+ });+ expect(lastRequest()).toMatchObject({ method: HttpMethod.DELETE, url: `${BASE}/action/calendar/ev1` });+ });++ test('a second delete fails with a not-found message', async () => {+ fail({ status: 404 });+ await expect(runAction({ action: moxieDeleteCalendarEventAction, props: { eventId: 'ev1' } })).rejects.toThrow(+ 'may already be deleted',+ );+ });++ test('list vendors and form names wrap bare strings in objects', async () => {+ ok({ body: ['Adobe', 'Figma'] });+ await expect(runAction({ action: moxieListVendorsAction, props: {} })).resolves.toEqual([{ name: 'Adobe' }, { name: 'Figma' }]);+ ok({ body: ['Intake'] });+ await expect(runAction({ action: moxieListFormNamesAction, props: {} })).resolves.toEqual([{ name: 'Intake' }]);+ expect(lastRequest()['url']).toBe(`${BASE}/action/formNames/list`);+ });++ test('attach from URL returns the stored URL with the record it was attached to', async () => {+ ok({ body: 'https://files.withmoxie.com/x.pdf' });+ await expect(+ runAction({+ action: moxieAttachFileFromUrlAction,+ props: { objectType: 'ticket', objectId: 't1', fileUrl: 'https://cdn.example.com/x.pdf', fileName: 'x.pdf' },+ }),+ ).resolves.toEqual({ url: 'https://files.withmoxie.com/x.pdf', objectType: 'TICKET', objectId: 't1', fileName: 'x.pdf' });+ });++ test('upload attachment sends a multipart body with the file', async () => {+ ok({ body: 'https://files.withmoxie.com/up.txt' });+ const file = { filename: 'up.txt', extension: 'txt', data: Buffer.from('hello') };+ await runAction({ action: moxieUploadAttachmentAction, props: { objectType: 'CLIENT', objectId: 'c1', file } });+ const sent = lastRequest();+ expect(sent['url']).toBe(`${BASE}/action/attachments/create`);+ expect(sent['queryParams']).toEqual({ id: 'c1', type: 'CLIENT' });+ const headers = sent['headers'];+ const contentType = typeof headers === 'object' && headers !== null ? Reflect.get(headers, 'Content-Type') : undefined;+ expect(String(contentType)).toMatch(/^multipart\/form-data; boundary=/);+ const payload = sent['body'];+ expect(Buffer.isBuffer(payload) && payload.toString('utf8')).toContain('filename="up.txt"');+ expect(Buffer.isBuffer(payload) && payload.toString('utf8')).toContain('hello');+ });++ test('get workspace account reads the account id first', async () => {+ ok({ body: { accountId: 10016, accountName: 'Moxie' } });+ ok({ body: { accountId: 10016, accountName: 'Moxie', currency: 'USD' } });+ await expect(runAction({ action: moxieGetWorkspaceAccountAction, props: {} })).resolves.toMatchObject({ currency: 'USD' });+ expect(request(0)['url']).toBe(`${BASE}/api/auth`);+ expect(request(1)['url']).toBe(`${BASE}/action/account/10016`);+ });+});++describe('payment retry guard', () => {+ const invoice = {+ id: 'i1',+ invoiceNumberFormatted: 'E-2026-042',+ payments: [{ id: 'pay1', referenceNumber: 'REF-1', amount: 50 }],+ };++ test('a payment whose reference is already on the invoice is not applied again', async () => {+ ok({ body: [invoice] });+ await expect(+ runAction({+ action: moxiePaymentCreateAction,+ props: { invoiceNumber: 'e-2026-042', clientName: 'Acme', amount: 50, referenceNumber: 'REF-1' },+ }),+ ).resolves.toMatchObject({ id: 'i1', already_applied: true });+ expect(sendRequest).toHaveBeenCalledTimes(1);+ expect(request(0)).toMatchObject({ url: `${BASE}/action/payableInvoices/search`, queryParams: { query: 'Acme' } });+ });++ test('a new reference is applied after the check', async () => {+ ok({ body: [invoice] });+ ok({ body: { ...invoice, status: 'PAID' } });+ await expect(+ runAction({+ action: moxieApplyPaymentAction,+ props: {+ invoiceNumber: 'E-2026-042',+ clientName: 'Acme',+ amount: '25',+ referenceNumber: 'REF-2',+ paymentType: 'bank_transfer',+ date: '2026-10-01T00:00:00.000Z',+ },+ }),+ ).resolves.toMatchObject({ status: 'PAID', already_applied: false });+ expect(request(1)).toMatchObject({+ method: HttpMethod.POST,+ url: `${BASE}/action/payment/create`,+ body: {+ invoiceNumber: 'E-2026-042',+ clientName: 'Acme',+ amount: 25,+ date: '2026-10-01',+ paymentType: 'BANK_TRANSFER',+ referenceNumber: 'REF-2',+ },+ });+ });++ test('without a reference the payment is applied directly', async () => {+ ok({ body: invoice });+ await runAction({ action: moxiePaymentCreateAction, props: { invoiceNumber: 'E-2026-042', clientName: 'Acme', amount: 5 } });+ expect(sendRequest).toHaveBeenCalledTimes(1);+ expect(request(0)['url']).toBe(`${BASE}/action/payment/create`);+ });++ test('an invoice that is no longer open fails with a clear message', async () => {+ fail({ status: 404, body: { message: 'Invoice not found' } });+ await expect(+ runAction({ action: moxiePaymentCreateAction, props: { invoiceNumber: 'E-1', clientName: 'Acme', amount: 5 } }),+ ).rejects.toThrow('open invoice E-1');+ });+});++describe('input validation happens before any request', () => {+ test.each([+ ['an update with no fields', moxieClientUpdateAction, { clientId: 'c1' }, 'Nothing to update'],+ ['an id with spaces', moxieTaskUpdateAction, { taskId: 'a b', name: 'x' }, 'not a valid Moxie id'],+ ['a field both set and cleared', moxieClientUpdateAction, { clientId: 'c1', notes: 'x', clearFields: ['notes'] }, 'both set and cleared'],+ ['a field that cannot be cleared', moxieClientUpdateAction, { clientId: 'c1', clearFields: ['color'] }, 'cannot be cleared'],+ ['a bad date', moxieProjectUpdateAction, { projectId: 'p1', dueDate: '2026-02-30' }, 'YYYY-MM-DD'],+ ['fee fields without a fee type', moxieProjectCreateAction, { name: 'S', clientName: 'A', amount: 5 }, 'Set Fee Type'],+ ['an invoice without items', moxieInvoiceCreateAction, { clientName: 'Acme', items: [] }, 'at least one line item'],+ ['a negative line rate', moxieInvoiceCreateAction, { clientName: 'Acme', items: [{ description: 'x', quantity: 1, rate: -1 }] }, '0 or more'],+ ['contacts without send', moxieInvoiceCreateAction, { clientName: 'A', items: [{ description: 'x', quantity: 1, rate: 1 }], sendToContacts: ['[email protected]'] }, 'only apply when Send Invoice'],+ ['a zero payment', moxiePaymentCreateAction, { invoiceNumber: 'E-1', clientName: 'A', amount: 0 }, 'more than 0'],+ ['an unknown payment type', moxiePaymentCreateAction, { invoiceNumber: 'E-1', clientName: 'A', amount: 1, paymentType: 'GOLD' }, 'Payment Type must be one of'],+ ['a time entry ending before it starts', moxieTimeEntryCreateAction, { timerStart: '2026-10-01T10:00:00Z', timerEnd: '2026-10-01T09:00:00Z' }, 'after Start Time'],+ ['a calendar create without times', moxieCreateOrUpdateCalendarEventAction, { summary: 'x' }, 'required to create'],+ ['both ticket id and number', moxieUpdateTicketStatusAction, { ticketId: 't1', ticketNumber: 3, status: 'Closed' }, 'exactly one'],+ ['a ticket search with nothing to match', moxieSearchTicketsAction, {}, 'Enter a Query'],+ ['a task search with nothing to match', moxieSearchTasksAction, {}, 'Enter a Query'],+ ['a client search with nothing to match', moxieSearchClientsAction, {}, 'Enter a Query'],+ ['an http file URL', moxieAttachFileFromUrlAction, { objectType: 'CLIENT', objectId: 'c1', fileUrl: 'http://x.io/a', fileName: 'a' }, 'https URL'],+ ['an unknown attachment type', moxieAttachFileFromUrlAction, { objectType: 'INVOICE', objectId: 'c1', fileUrl: 'https://x.io/a', fileName: 'a' }, 'Attach To must be one of'],+ ['an invalid email', moxieCreateTicketAction, { subject: 'x', userEmail: 'nope' }, 'not a valid email'],+ ['an upload that is not a file', moxieUploadAttachmentAction, { objectType: 'CLIENT', objectId: 'c1', file: 'abc' }, 'File is required'],+ ['a ticket comment with no author email', moxieAddTicketCommentAction, { ticketNumber: 1001, comment: 'x' }, 'Author Email is required'],+ ])('rejects %s', async (_label, action, props, message) => {+ await expect(runAction({ action, props })).rejects.toThrow(message);+ expect(sendRequest).not.toHaveBeenCalled();+ });+});++describe('dropdowns', () => {+ test('a dropdown shows a disabled reason instead of throwing on 401', async () => {+ fail({ status: 401, body: { message: 'Invalid X-API-Key specified.' } });+ const state = await loadOptions({ prop: moxieUpdateClientAction.props.clientId, values: { auth: { props: { baseUrl: BASE, apiKey: 'k' } } } });+ expect(state).toMatchObject({ disabled: true, options: [] });+ expect(JSON.stringify(state)).toContain('API key');+ });++ test('a dropdown without a connection asks to connect', async () => {+ const state = await loadOptions({ prop: moxieUpdateClientAction.props.clientId, values: {} });+ expect(state).toMatchObject({ disabled: true, placeholder: 'Connect your Moxie account first.' });+ });++ test('the project dropdown of a client with no projects says so', async () => {+ fail({ status: 404, body: { message: 'Client not found' } });+ const state = await loadOptions({+ prop: moxieCreateTaskAction.props.projectName,+ values: { auth: { props: { baseUrl: BASE, apiKey: 'k' } }, clientName: 'Empty Co' },+ });+ expect(state).toMatchObject({ disabled: true, placeholder: 'This client has no projects.' });+ });++ test('the project dropdown waits for a client', async () => {+ const state = await loadOptions({ prop: moxieUpdateProjectAction.props.projectId, values: { auth: { props: {} } } });+ expect(state).toMatchObject({ disabled: true, placeholder: 'Select a client first.' });+ });++ test('the client dropdown lists names as values', async () => {+ ok({ body: [{ id: 'c1', name: 'Acme' }] });+ const state = await loadOptions({ prop: moxieCreateTaskAction.props.clientName, values: { auth: { props: { baseUrl: BASE, apiKey: 'k' } } } });+ expect(state).toEqual({ disabled: false, options: [{ label: 'Acme', value: 'Acme' }] });+ });++ test('the task stage dropdown uses the stages of the selected project type', async () => {+ ok({ body: [{ id: 'p1', name: 'Site', projectTypeId: 'pt9' }] });+ ok({ body: [{ id: 's1', label: 'To Do' }] });+ const state = await loadOptions({+ prop: moxieCreateTaskAction.props.status,+ values: { auth: { props: { baseUrl: BASE, apiKey: 'k' } }, clientName: 'Acme', projectName: 'Site' },+ });+ expect(state).toEqual({ disabled: false, options: [{ label: 'To Do', value: 'To Do' }] });+ expect(request(1)).toMatchObject({ url: `${BASE}/action/taskStages/list`, queryParams: { projectTypeId: 'pt9' } });+ });++ test('the update-task stage dropdown refuses to guess when the project is not found', async () => {+ ok({ body: [] });+ const state = await loadOptions({+ prop: moxieUpdateTaskAction.props.statusId,+ values: { auth: { props: { baseUrl: BASE, apiKey: 'k' } }, projectId: 'missing' },+ });+ expect(state).toMatchObject({ disabled: true });+ expect(JSON.stringify(state)).toContain('Project not found');+ expect(sendRequest).toHaveBeenCalledTimes(1);+ });++ test('every dynamic dropdown lists its parent props in refreshers', () => {+ expect(moxieUpdateTaskAction.props.taskId.refreshers).toEqual(['projectId']);+ expect(moxieUpdateTaskAction.props.statusId.refreshers).toEqual(['projectId']);+ expect(moxieCreateTimeEntryAction.props.deliverableName.refreshers).toEqual(['clientName', 'projectName']);+ expect(moxieApplyPaymentAction.props.invoiceNumber.refreshers).toEqual(['clientName']);+ expect(moxieCreateInvoiceAction.props.sendToContacts.refreshers).toEqual(['clientName']);+ });+});++type Case = {+ name: string;+ action: { run: unknown };+ props: Record<string, unknown>;+ method: HttpMethod;+ path: string;+ body?: unknown;+ query?: Record<string, string>;+};diff --git a/packages/pieces/community/moxie-crm/test/client.test.ts b/packages/pieces/community/moxie-crm/test/client.test.tsindex 3fd61012043..901bc0fae82 100644--- a/packages/pieces/community/moxie-crm/test/client.test.ts+++ b/packages/pieces/community/moxie-crm/test/client.test.ts@@ -1,32 +1,24 @@-/// <reference types="vitest/globals" />-+import { beforeEach, describe, expect, test, vi } from 'vitest';import { HttpMethod } from '@activepieces/pieces-common';--const { sendRequest } = vi.hoisted(() => ({- sendRequest: vi.fn(),-}));+import { API_KEY, BASE, fail, lastRequest, ok, sendRequest } from './helpers';+import { MoxieApiError, MoxieCRMClient, assertMoxieRequestUrl, looksLikeWebPage, normalizeBaseUrl } from '../src/lib/common/client';+import { moxieCRMAuth } from '../src/lib/auth';vi.mock('@activepieces/pieces-common', async (importOriginal) => {- const actual = await importOriginal<- typeof import('@activepieces/pieces-common')- >();- return {- ...actual,- httpClient: { sendRequest },- };+ const actual = await importOriginal<typeof import('@activepieces/pieces-common')>();+ return { ...actual, httpClient: { sendRequest: (...args: unknown[]) => sendRequest(...args) } };});-const { MoxieCRMClient } = await import('../src/lib/common/client');--const BASE_URL = 'https://pod01.withmoxie.com/api/public';-const API_KEY = 'test-api-key';--function buildClient(baseUrl: string = BASE_URL) {- return new MoxieCRMClient(baseUrl, API_KEY);+function buildClient({ baseUrl = BASE }: { baseUrl?: string } = {}) {+ return new MoxieCRMClient({ baseUrl, apiKey: API_KEY });}-function lastRequest() {- return sendRequest.mock.calls[sendRequest.mock.calls.length - 1][0];+function validate({ baseUrl, apiKey = API_KEY }: { baseUrl: string; apiKey?: string }): Promise<unknown> {+ const fn: unknown = Reflect.get(moxieCRMAuth, 'validate');+ if (typeof fn !== 'function') {+ throw new Error('validate missing');+ }+ return Promise.resolve(Reflect.apply(fn, undefined, [{ auth: { baseUrl, apiKey }, server: {} }]));}beforeEach(() => {@@ -34,173 +26,204 @@ beforeEach(() => {sendRequest.mockResolvedValue({ status: 200, headers: {}, body: [] });});-describe('MoxieCRMClient base url handling', () => {+describe('base url handling', () => {test('a base url without a trailing slash builds a single-slash path', async () => {await buildClient().listWorkspaceUsers();-- expect(lastRequest().url).toBe(- 'https://pod01.withmoxie.com/api/public/action/users/list'- );+ expect(lastRequest()['url']).toBe(`${BASE}/action/users/list`);});test('a trailing slash on the base url does not produce a double slash', async () => {- await buildClient(`${BASE_URL}/`).listWorkspaceUsers();-- expect(lastRequest().url).toBe(- 'https://pod01.withmoxie.com/api/public/action/users/list'- );- expect(lastRequest().url).not.toContain('//action');+ await buildClient({ baseUrl: `${BASE}/` }).listWorkspaceUsers();+ expect(lastRequest()['url']).toBe(`${BASE}/action/users/list`);});test('every request carries the X-API-KEY header and no bearer token', async () => {await buildClient().listPipelineStages();+ expect(lastRequest()['headers']).toEqual({ 'X-API-KEY': API_KEY });+ });++ test('normalizeBaseUrl accepts the documented pod URL and strips the trailing slash', () => {+ expect(normalizeBaseUrl({ baseUrl: ' https://pod01.withmoxie.com/api/public/ ' })).toBe(BASE);+ expect(normalizeBaseUrl({ baseUrl: 'https://withmoxie.com/api/public' })).toBe('https://withmoxie.com/api/public');+ });- expect(lastRequest().headers).toEqual({ 'X-API-KEY': API_KEY });- expect(lastRequest().headers).not.toHaveProperty('Authorization');+ test.each([+ ['http://pod01.withmoxie.com/api/public'],+ ['https://pod01.withmoxie.com.evil.io/api/public'],+ ['https://evilwithmoxie.com/api/public'],+ ['https://[email protected]/api/public'],+ ['https://pod01.withmoxie.com:8443/api/public'],+ ['https://pod01.withmoxie.com/api/public?x=1'],+ ['https://evil.io'],+ ['not a url'],+ [''],+ ])('normalizeBaseUrl rejects %s', (baseUrl) => {+ expect(() => normalizeBaseUrl({ baseUrl })).toThrow(MoxieApiError);+ });++ test('a lookalike host never receives the API key', async () => {+ await expect(buildClient({ baseUrl: 'https://pod01.withmoxie.com.evil.io/api/public' }).listClients()).rejects.toThrow(+ 'withmoxie.com',+ );+ expect(sendRequest).not.toHaveBeenCalled();});});-describe('MoxieCRMClient read endpoints', () => {+describe('read and search endpoints keep their request shape', () => {test('listClients calls GET /action/clients/list with no body or query', async () => {await buildClient().listClients();-- expect(lastRequest()).toMatchObject({- method: HttpMethod.GET,- url: `${BASE_URL}/action/clients/list`,- });- expect(lastRequest().body).toBeUndefined();- expect(lastRequest().queryParams).toBeUndefined();+ expect(lastRequest()).toMatchObject({ method: HttpMethod.GET, url: `${BASE}/action/clients/list` });+ expect(lastRequest()['body']).toBeUndefined();+ expect(lastRequest()['queryParams']).toBeUndefined();});- test('listPipelineStages calls GET /action/pipelineStages/list', async () => {- await buildClient().listPipelineStages();+ test('listInvoiceTemplates calls GET /action/invoiceTemplates/list', async () => {+ await buildClient().listInvoiceTemplates();+ expect(lastRequest()['url']).toBe(`${BASE}/action/invoiceTemplates/list`);+ });- expect(lastRequest().method).toBe(HttpMethod.GET);- expect(lastRequest().url).toBe(`${BASE_URL}/action/pipelineStages/list`);+ test('searchClients sends the query as a query param, unencoded', async () => {+ await buildClient().searchClients({ query: 'Ada & Co' });+ expect(lastRequest()).toMatchObject({ url: `${BASE}/action/clients/search`, queryParams: { query: 'Ada & Co' } });});- test('listWorkspaceUsers calls GET /action/users/list', async () => {- await buildClient().listWorkspaceUsers();+ test('searchContacts with no query omits queryParams entirely', async () => {+ await buildClient().searchContacts();+ expect(lastRequest()['queryParams']).toBeUndefined();+ await buildClient().searchContacts({ query: '' });+ expect(lastRequest()['queryParams']).toBeUndefined();+ });- expect(lastRequest().method).toBe(HttpMethod.GET);- expect(lastRequest().url).toBe(`${BASE_URL}/action/users/list`);+ test('searchProjects sends an id lookup', async () => {+ await buildClient().searchProjects({ id: 'p1' });+ expect(lastRequest()).toMatchObject({ url: `${BASE}/action/projects/search`, queryParams: { id: 'p1' } });});- test('listInvoiceTemplates calls GET /action/invoiceTemplates/list', async () => {- await buildClient().listInvoiceTemplates();+ test('createContact posts the request body unchanged', async () => {+ const body = { first: 'Ada', last: 'Chen', clientName: 'Moxie', defaultContact: true };+ await buildClient().createContact(body);+ expect(lastRequest()).toMatchObject({ method: HttpMethod.POST, url: `${BASE}/action/contacts/create`, body });+ });- expect(lastRequest().url).toBe(- `${BASE_URL}/action/invoiceTemplates/list`- );+ test('methods return response.body, not the HttpResponse wrapper', async () => {+ const payload = [{ id: 'c1', name: 'Moxie' }];+ sendRequest.mockResolvedValue({ status: 200, headers: { 'x-secret': 'no' }, body: payload });+ await expect(buildClient().listClients()).resolves.toBe(payload);});});-describe('MoxieCRMClient search endpoints', () => {- test('searchClients sends the query as a query param, not in the path', async () => {- await buildClient().searchClients('Moxie');-- expect(lastRequest()).toMatchObject({- method: HttpMethod.GET,- url: `${BASE_URL}/action/clients/search`,- queryParams: { query: 'Moxie' },- });- expect(lastRequest().url).not.toContain('Moxie');+describe('a web page instead of API data fails the step', () => {+ test('an HTML content type throws a Base URL hint', async () => {+ ok({ body: '<!DOCTYPE html><html></html>', headers: { 'content-type': 'text/html; charset=utf-8' } });+ await expect(buildClient().listPipelineStages()).rejects.toThrow('Moxie returned a web page instead of API data');});- test('searchClients passes a query with spaces and ampersands through unencoded', async () => {- await buildClient().searchClients('Ada & Co');-- expect(lastRequest().queryParams).toEqual({ query: 'Ada & Co' });+ test('a string body that starts with < throws even without a content type', async () => {+ ok({ body: ' <html>' });+ await expect(buildClient().listPipelineStages()).rejects.toThrow('Base URL');});- test('searchProjects sends the query as a query param', async () => {- await buildClient().searchProjects('Moxie');+ test('a JSON string body, such as an attachment URL, is valid', async () => {+ ok({ body: 'https://files.withmoxie.com/a.png', headers: { 'content-type': 'application/json' } });+ await expect(buildClient().request({ method: HttpMethod.POST, path: '/action/attachments/createFromUrl' })).resolves.toBe(+ 'https://files.withmoxie.com/a.png',+ );+ });- expect(lastRequest()).toMatchObject({- method: HttpMethod.GET,- url: `${BASE_URL}/action/projects/search`,- queryParams: { query: 'Moxie' },- });+ test('looksLikeWebPage reads header names case-insensitively', () => {+ expect(looksLikeWebPage({ headers: { 'Content-Type': 'text/html' }, body: {} })).toBe(true);+ expect(looksLikeWebPage({ headers: { 'content-type': 'application/json' }, body: [] })).toBe(false);});+});- test('searchContacts with a query sends it', async () => {- await buildClient().searchContacts('ada');+describe('custom API call URL guard', () => {+ test.each([+ ['a relative path', '/action/clients/list'],+ ['a full URL on the Base URL host', 'https://pod01.withmoxie.com/api/public/action/clients/list'],+ ['an empty URL', undefined],+ ])('allows %s', (_label, url) => {+ expect(() => assertMoxieRequestUrl({ baseUrl: 'https://pod01.withmoxie.com/api/public', url })).not.toThrow();+ });++ test.each([+ ['another host', 'https://attacker.example/steal'],+ ['a look-alike host', 'https://pod01.withmoxie.com.evil.io/api'],+ ['another Moxie pod', 'https://pod02.withmoxie.com/api/public/action/clients/list'],+ ['plain http on the same host', 'http://pod01.withmoxie.com/api/public/action/clients/list'],+ ['user info in the URL', 'https://user:[email protected]/api/public'],+ ])('refuses %s before the API key is attached', (_label, url) => {+ expect(() => assertMoxieRequestUrl({ baseUrl: 'https://pod01.withmoxie.com/api/public', url })).toThrow(+ 'only sends the Moxie API key to your Base URL host',+ );+ });+});- expect(lastRequest()).toMatchObject({- url: `${BASE_URL}/action/contacts/search`,- queryParams: { query: 'ada' },- });+describe('vendor errors', () => {+ test('a 401 names the API key and keeps the vendor text in responseBody, not body', async () => {+ const vendor = { status: 401, error: 'Unauthorized', message: 'Invalid X-API-Key specified.' };+ fail({ status: 401, body: vendor });+ const error = await buildClient().listClients().catch((e: unknown) => e);+ expect(error).toBeInstanceOf(MoxieApiError);+ expect(error).toMatchObject({ status: 401, responseBody: vendor });+ expect(String(Reflect.get(Object(error), 'message'))).toContain('Moxie rejected the API key');+ expect(String(Reflect.get(Object(error), 'message'))).toContain('Invalid X-API-Key specified.');+ expect(Reflect.has(Object(error), 'body')).toBe(false);});- test('searchContacts with no query omits queryParams entirely', async () => {- await buildClient().searchContacts();+ test('an unknown route points at the Base URL', async () => {+ fail({ status: 404, body: 'No endpoint GET /action/clients/list.' });+ await expect(buildClient().listClients()).rejects.toThrow('Check the connection');+ });- expect(lastRequest().url).toBe(`${BASE_URL}/action/contacts/search`);- expect(lastRequest().queryParams).toBeUndefined();+ test('a 429 is reported as rate limiting', async () => {+ fail({ status: 429, body: { status: 429, message: 'Too Many Requests' } });+ await expect(buildClient().listClients()).rejects.toThrow('Moxie is rate limiting this workspace (HTTP 429)');});- test('searchContacts with an empty query omits queryParams rather than sending query=', async () => {- await buildClient().searchContacts('');+ test('searchProjects with an unknown client explains that the query is an exact client name', async () => {+ fail({ status: 404, body: { status: 404, message: 'Client not found' } });+ await expect(buildClient().searchProjects({ query: 'Nobody' })).rejects.toThrow('No client named "Nobody"');+ });- expect(lastRequest().queryParams).toBeUndefined();+ test('a network error propagates unchanged', async () => {+ sendRequest.mockRejectedValueOnce(new Error('getaddrinfo ENOTFOUND'));+ await expect(buildClient().listClients()).rejects.toThrow('getaddrinfo ENOTFOUND');});});-describe('MoxieCRMClient createContact', () => {- test('posts the request body to /action/contacts/create', async () => {- const request = {- first: 'Ada',- last: 'Chen',- email: '[email protected]',- clientName: 'Moxie',- defaultContact: true,- };-- await buildClient().createContact(request);-- expect(lastRequest()).toMatchObject({- method: HttpMethod.POST,- url: `${BASE_URL}/action/contacts/create`,- body: request,- });+describe('auth.validate', () => {+ test('GET /api/auth with an account id is valid', async () => {+ ok({ body: { accountId: 10016, accountName: 'Moxie' } });+ await expect(validate({ baseUrl: `${BASE}/` })).resolves.toEqual({ valid: true });+ expect(lastRequest()).toMatchObject({ method: HttpMethod.GET, url: `${BASE}/api/auth`, headers: { 'X-API-KEY': API_KEY } });});- test('omitted optional fields are not invented', async () => {- await buildClient().createContact({ first: 'Ada', last: 'Chen' });-- expect(lastRequest().body).toEqual({ first: 'Ada', last: 'Chen' });+ test('a 401 is reported as an invalid API key', async () => {+ fail({ status: 401, body: { message: 'Invalid X-API-Key specified.' } });+ await expect(validate({ baseUrl: BASE })).resolves.toMatchObject({ valid: false, error: expect.stringContaining('Invalid API key') });});-});-describe('MoxieCRMClient response unwrapping', () => {- test('every method returns response.body, not the HttpResponse wrapper', async () => {- const payload = [{ id: 'c1', name: 'Moxie' }];- sendRequest.mockResolvedValue({- status: 200,- headers: { 'x-secret': 'do-not-surface' },- body: payload,+ test('the web-app URL is reported as not the API URL', async () => {+ ok({ body: '<!DOCTYPE html>', headers: { 'content-type': 'text/html' } });+ await expect(validate({ baseUrl: 'https://create.withmoxie.com/me/profile' })).resolves.toMatchObject({+ valid: false,+ error: expect.stringContaining('not the Moxie API URL'),});-- const client = buildClient();-- await expect(client.listClients()).resolves.toBe(payload);- await expect(client.searchClients('Moxie')).resolves.toBe(payload);- await expect(client.searchContacts()).resolves.toBe(payload);- await expect(client.listPipelineStages()).resolves.toBe(payload);- await expect(client.listWorkspaceUsers()).resolves.toBe(payload);});- test('an empty result set comes back as an empty array, not undefined', async () => {- sendRequest.mockResolvedValue({ status: 200, headers: {}, body: [] });-- await expect(buildClient().searchClients('nothing')).resolves.toEqual([]);+ test('a 404 is reported as not the API URL', async () => {+ fail({ status: 404, body: 'No endpoint GET /api/auth.' });+ await expect(validate({ baseUrl: 'https://pod01.withmoxie.com' })).resolves.toMatchObject({+ valid: false,+ error: expect.stringContaining('not the Moxie API URL'),+ });});- test('a rejected request propagates rather than resolving undefined', async () => {- sendRequest.mockRejectedValue(new Error('429 Too Many Requests'));-- await expect(buildClient().listClients()).rejects.toThrow(- '429 Too Many Requests'- );+ test('a non-Moxie host is refused before any request', async () => {+ await expect(validate({ baseUrl: 'https://evil.io/api/public' })).resolves.toMatchObject({+ valid: false,+ error: expect.stringContaining('withmoxie.com'),+ });+ expect(sendRequest).not.toHaveBeenCalled();});});diff --git a/packages/pieces/community/moxie-crm/test/helpers.ts b/packages/pieces/community/moxie-crm/test/helpers.tsnew file mode 100644index 00000000000..788555eed9b--- /dev/null+++ b/packages/pieces/community/moxie-crm/test/helpers.ts@@ -0,0 +1,113 @@+import { AppConnectionType, createMockActionContext, Store } from '@activepieces/pieces-framework';+import { vi } from 'vitest';++export const BASE = 'https://pod01.withmoxie.com/api/public';+export const API_KEY = 'test-api-key';+export const AUTH = {+ type: AppConnectionType.CUSTOM_AUTH,+ props: { baseUrl: BASE, apiKey: API_KEY },+};+export const WEBHOOK_URL = 'https://ap.example.com/api/v1/webhooks/flow123';++export const sendRequest = vi.fn();++export function ok({ body, headers = {} }: { body: unknown; headers?: Record<string, string> }): void {+ sendRequest.mockResolvedValueOnce({ status: 200, headers, body });+}++export function fail({ status, body = {} }: { status: number; body?: unknown }): void {+ sendRequest.mockRejectedValueOnce(new FakeHttpError({ status, body }));+}++export function request(index: number): Record<string, unknown> {+ const call: unknown = sendRequest.mock.calls[index]?.[0];+ if (typeof call !== 'object' || call === null) {+ throw new Error(`no request #${index}`);+ }+ return Object.fromEntries(Object.entries(call));+}++export function lastRequest(): Record<string, unknown> {+ return request(sendRequest.mock.calls.length - 1);+}++export function memoryStore({ initial = {}, failPut = false }: { initial?: Record<string, unknown>; failPut?: boolean } = {}) {+ const data = new Map<string, unknown>(Object.entries(initial));+ const store: Store = {+ put: async (key, value) => {+ if (failPut) {+ throw new Error('store unavailable');+ }+ data.set(key, value);+ return value;+ },+ get: async (key) => (data.has(key) ? JSON.parse(JSON.stringify(data.get(key))) : null),+ delete: async (key) => {+ data.delete(key);+ },+ };+ const spies = {+ put: vi.spyOn(store, 'put'),+ get: vi.spyOn(store, 'get'),+ delete: vi.spyOn(store, 'delete'),+ };+ return { data, store, spies };+}++export function runAction({+ action,+ props,+ auth = AUTH,+}: {+ action: { run: unknown };+ props: Record<string, unknown>;+ auth?: unknown;+}): Promise<unknown> {+ const context = { ...createMockActionContext({ propsValue: props }), auth };+ return Promise.resolve(Reflect.apply(asFunction(action.run), action, [context]));+}++export function runHook({+ trigger,+ hook,+ context,+}: {+ trigger: object;+ hook: 'run' | 'onEnable' | 'onDisable';+ context: Record<string, unknown>;+}): Promise<unknown> {+ const fn: unknown = Reflect.get(trigger, hook);+ return Promise.resolve(+ Reflect.apply(asFunction(fn), trigger, [{ auth: AUTH, webhookUrl: WEBHOOK_URL, propsValue: {}, ...context }]),+ );+}++export function loadOptions({+ prop,+ values,+}: {+ prop: unknown;+ values: Record<string, unknown>;+}): Promise<unknown> {+ if (typeof prop !== 'object' || prop === null) {+ throw new Error('not a property');+ }+ const options: unknown = Reflect.get(prop, 'options');+ return Promise.resolve(Reflect.apply(asFunction(options), prop, [values, {}]));+}++function asFunction(value: unknown): (...args: unknown[]) => unknown {+ if (typeof value !== 'function') {+ throw new Error('not a function');+ }+ return (...args: unknown[]) => Reflect.apply(value, undefined, args);+}++class FakeHttpError extends Error {+ readonly response: { status: number; body: unknown };++ constructor({ status, body }: { status: number; body: unknown }) {+ super(JSON.stringify({ response: { status, body } }));+ this.response = { status, body };+ }+}diff --git a/packages/pieces/community/moxie-crm/test/webhook.test.ts b/packages/pieces/community/moxie-crm/test/webhook.test.tsnew file mode 100644index 00000000000..a5a85012408--- /dev/null+++ b/packages/pieces/community/moxie-crm/test/webhook.test.ts@@ -0,0 +1,293 @@+import { beforeEach, describe, expect, test, vi } from 'vitest';+import { HttpMethod } from '@activepieces/pieces-common';+import { BASE, WEBHOOK_URL, fail, memoryStore, ok, request, runHook, sendRequest } from './helpers';+import { MOXIE_HOOK_STORE_KEY, MOXIE_STALE_HOOKS_STORE_KEY, moxieWebhook } from '../src/lib/common/webhook';+import { moxieCRMTriggers } from '../src/lib/triggers';++vi.mock('@activepieces/pieces-common', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@activepieces/pieces-common')>();+ return { ...actual, httpClient: { sendRequest: (...args: unknown[]) => sendRequest(...args) } };+});++const CREDENTIALS = { baseUrl: BASE, apiKey: 'test-api-key' };+const BODY = { id: 'c1', name: 'Moxie, Inc.' };++function triggerNamed(name: string) {+ const trigger = moxieCRMTriggers.find((t) => t.name === `moxie_trigger_${name}`);+ if (trigger === undefined) {+ throw new Error(`missing trigger ${name}`);+ }+ return trigger;+}++beforeEach(() => {+ sendRequest.mockReset();+ sendRequest.mockResolvedValue({ status: 200, headers: {}, body: '' });+});++describe('delivery filter', () => {+ test('a delivery with the expected event type is emitted', () => {+ const payload = { body: BODY, headers: { 'x-event-type': 'ClientCreate', 'x-event-origin': 'withmoxie.com' } };+ expect(moxieWebhook.acceptDelivery({ eventType: 'ClientCreate', payload })).toEqual([BODY]);+ });++ test('a delivery for another event type is dropped', () => {+ const payload = { body: BODY, headers: { 'x-event-type': 'ClientDelete' } };+ expect(moxieWebhook.acceptDelivery({ eventType: 'ClientCreate', payload })).toEqual([]);+ });++ test('header names are matched case-insensitively', () => {+ const payload = { body: BODY, headers: { 'X-Event-Type': 'ClientDelete' } };+ expect(moxieWebhook.acceptDelivery({ eventType: 'ClientCreate', payload })).toEqual([]);+ });++ test('a delivery without the header still runs, for hooks added by hand', () => {+ expect(moxieWebhook.acceptDelivery({ eventType: 'ClientCreate', payload: { body: BODY, headers: {} } })).toEqual([BODY]);+ });++ test('a delivery from another origin is dropped', () => {+ const payload = { body: BODY, headers: { 'x-event-origin': 'evil.io' } };+ expect(moxieWebhook.acceptDelivery({ eventType: 'ClientCreate', payload })).toEqual([]);+ });++ test('two identical deliveries both run, since Moxie sends no event id to tell a retry from a repeat', () => {+ const payload = { body: BODY, headers: { 'x-event-type': 'AgreementViewed' } };+ expect(moxieWebhook.acceptDelivery({ eventType: 'AgreementViewed', payload })).toEqual([BODY]);+ expect(moxieWebhook.acceptDelivery({ eventType: 'AgreementViewed', payload })).toEqual([BODY]);+ });+});++describe('subscribe and unsubscribe', () => {+ test('enable posts the event type and flow URL, then stores the hook', async () => {+ ok({ body: 'hook-1' });+ const { store, data } = memoryStore();+ await moxieWebhook.enable({ credentials: CREDENTIALS, store, type: 'TicketCreate', hookUrl: WEBHOOK_URL });+ expect(request(0)).toMatchObject({+ method: HttpMethod.POST,+ url: `${BASE}/api/subscribe`,+ body: { type: 'TicketCreate', hookUrl: WEBHOOK_URL },+ });+ expect(data.get(MOXIE_HOOK_STORE_KEY)).toEqual({ id: 'hook-1', type: 'TicketCreate', hookUrl: WEBHOOK_URL });+ });++ test('a failed store write unsubscribes the new hook and rethrows', async () => {+ ok({ body: 'hook-1' });+ ok({ body: '' });+ const { store } = memoryStore({ failPut: true });+ await expect(+ moxieWebhook.enable({ credentials: CREDENTIALS, store, type: 'TicketCreate', hookUrl: WEBHOOK_URL }),+ ).rejects.toThrow('store unavailable');+ expect(request(1)).toMatchObject({+ url: `${BASE}/api/unsubscribe`,+ body: { id: 'hook-1', type: 'TicketCreate', hookUrl: WEBHOOK_URL },+ });+ });++ test('a hook left from an earlier enable is removed only after the new one is stored', async () => {+ const previous = { id: 'old', type: 'TicketCreate', hookUrl: WEBHOOK_URL };+ const { store, data } = memoryStore({ initial: { [MOXIE_HOOK_STORE_KEY]: previous } });+ ok({ body: 'new' });+ ok({ body: '' });+ await moxieWebhook.enable({ credentials: CREDENTIALS, store, type: 'TicketCreate', hookUrl: WEBHOOK_URL });+ expect(request(0)).toMatchObject({ url: `${BASE}/api/subscribe` });+ expect(request(1)).toMatchObject({ url: `${BASE}/api/unsubscribe`, body: previous });+ expect(data.get(MOXIE_HOOK_STORE_KEY)).toMatchObject({ id: 'new' });+ });++ test('a failed subscribe keeps the earlier hook registered and tracked', async () => {+ const previous = { id: 'old', type: 'TicketCreate', hookUrl: WEBHOOK_URL };+ const { store, data } = memoryStore({ initial: { [MOXIE_HOOK_STORE_KEY]: previous } });+ fail({ status: 500, body: { message: 'boom' } });+ await expect(+ moxieWebhook.enable({ credentials: CREDENTIALS, store, type: 'TicketCreate', hookUrl: WEBHOOK_URL }),+ ).rejects.toThrow('HTTP 500');+ expect(data.get(MOXIE_HOOK_STORE_KEY)).toEqual(previous);+ expect(sendRequest).toHaveBeenCalledTimes(1);+ });++ test('a failed removal of the earlier hook keeps it tracked, and disable removes it later', async () => {+ const previous = { id: 'old', type: 'TicketCreate', hookUrl: WEBHOOK_URL };+ const { store, data } = memoryStore({ initial: { [MOXIE_HOOK_STORE_KEY]: previous } });+ ok({ body: 'new' });+ fail({ status: 500, body: { message: 'boom' } });+ await moxieWebhook.enable({ credentials: CREDENTIALS, store, type: 'TicketCreate', hookUrl: WEBHOOK_URL });+ expect(data.get(MOXIE_HOOK_STORE_KEY)).toMatchObject({ id: 'new' });+ expect(data.get(MOXIE_STALE_HOOKS_STORE_KEY)).toEqual([previous]);+ ok({ body: '' });+ ok({ body: '' });+ await moxieWebhook.disable({ credentials: CREDENTIALS, store });+ expect(request(2)).toMatchObject({ url: `${BASE}/api/unsubscribe`, body: previous });+ expect(request(3)).toMatchObject({ url: `${BASE}/api/unsubscribe`, body: { id: 'new' } });+ expect(data.has(MOXIE_STALE_HOOKS_STORE_KEY)).toBe(false);+ expect(data.has(MOXIE_HOOK_STORE_KEY)).toBe(false);+ });++ test('the earlier hook is recorded for removal before the new one replaces it, so no single failure loses it', async () => {+ const previous = { id: 'old', type: 'TicketCreate', hookUrl: WEBHOOK_URL };+ const { store, data, spies } = memoryStore({ initial: { [MOXIE_HOOK_STORE_KEY]: previous } });+ spies.put.mockImplementation(async (key, value) => {+ if (key === MOXIE_HOOK_STORE_KEY) {+ throw new Error('store unavailable');+ }+ data.set(key, value);+ return value;+ });+ ok({ body: 'new' });+ ok({ body: '' });+ await expect(+ moxieWebhook.enable({ credentials: CREDENTIALS, store, type: 'TicketCreate', hookUrl: WEBHOOK_URL }),+ ).rejects.toThrow('store unavailable');+ expect(request(1)).toMatchObject({ url: `${BASE}/api/unsubscribe`, body: { id: 'new' } });+ expect(data.get(MOXIE_HOOK_STORE_KEY)).toEqual(previous);+ expect(data.get(MOXIE_STALE_HOOKS_STORE_KEY)).toEqual([previous]);+ });++ test('a failed store read stops enable before anything is subscribed', async () => {+ const { store, spies } = memoryStore();+ spies.get.mockRejectedValue(new Error('store unavailable'));+ await expect(+ moxieWebhook.enable({ credentials: CREDENTIALS, store, type: 'TicketCreate', hookUrl: WEBHOOK_URL }),+ ).rejects.toThrow('store unavailable');+ expect(sendRequest).not.toHaveBeenCalled();+ });++ test('a successful removal clears the earlier hook from the removal list', async () => {+ const previous = { id: 'old', type: 'TicketCreate', hookUrl: WEBHOOK_URL };+ const { store, data } = memoryStore({ initial: { [MOXIE_HOOK_STORE_KEY]: previous } });+ ok({ body: 'new' });+ ok({ body: '' });+ await moxieWebhook.enable({ credentials: CREDENTIALS, store, type: 'TicketCreate', hookUrl: WEBHOOK_URL });+ expect(data.has(MOXIE_STALE_HOOKS_STORE_KEY)).toBe(false);+ });++ test('disable keeps a stale hook tracked when its removal fails again', async () => {+ const stale = { id: 'old', type: 'TicketCreate', hookUrl: WEBHOOK_URL };+ const { store, data } = memoryStore({ initial: { [MOXIE_STALE_HOOKS_STORE_KEY]: [stale] } });+ fail({ status: 500, body: { message: 'boom' } });+ await moxieWebhook.disable({ credentials: CREDENTIALS, store });+ expect(data.get(MOXIE_STALE_HOOKS_STORE_KEY)).toEqual([stale]);+ });++ test('an earlier hook with an id is removed even when the new subscription returns no id', async () => {+ const previous = { id: 'old', type: 'TicketCreate', hookUrl: WEBHOOK_URL };+ const { store, data } = memoryStore({ initial: { [MOXIE_HOOK_STORE_KEY]: previous } });+ ok({ body: { unexpected: true } });+ ok({ body: '' });+ await moxieWebhook.enable({ credentials: CREDENTIALS, store, type: 'TicketCreate', hookUrl: WEBHOOK_URL });+ expect(request(1)).toMatchObject({ url: `${BASE}/api/unsubscribe`, body: previous });+ expect(data.get(MOXIE_HOOK_STORE_KEY)).toEqual({ id: null, type: 'TicketCreate', hookUrl: WEBHOOK_URL });+ });++ test('an earlier hook without an id on the same URL is not removed, since that would remove the new one too', async () => {+ const previous = { id: null, type: 'TicketCreate', hookUrl: WEBHOOK_URL };+ const { store } = memoryStore({ initial: { [MOXIE_HOOK_STORE_KEY]: previous } });+ ok({ body: '' });+ await moxieWebhook.enable({ credentials: CREDENTIALS, store, type: 'TicketCreate', hookUrl: WEBHOOK_URL });+ expect(sendRequest).toHaveBeenCalledTimes(1);+ });++ test('a subscribe response without an id still allows unsubscribing by type and URL', async () => {+ ok({ body: { unexpected: true } });+ const { store, data } = memoryStore();+ await moxieWebhook.enable({ credentials: CREDENTIALS, store, type: 'TicketClose', hookUrl: WEBHOOK_URL });+ expect(data.get(MOXIE_HOOK_STORE_KEY)).toEqual({ id: null, type: 'TicketClose', hookUrl: WEBHOOK_URL });+ ok({ body: '' });+ await moxieWebhook.disable({ credentials: CREDENTIALS, store });+ expect(request(1)).toMatchObject({ body: { type: 'TicketClose', hookUrl: WEBHOOK_URL } });+ });++ test('disable forgets the hook after a 200', async () => {+ const hook = { id: 'hook-1', type: 'TicketCreate', hookUrl: WEBHOOK_URL };+ const { store, data } = memoryStore({ initial: { [MOXIE_HOOK_STORE_KEY]: hook } });+ ok({ body: '' });+ await moxieWebhook.disable({ credentials: CREDENTIALS, store });+ expect(request(0)).toMatchObject({ url: `${BASE}/api/unsubscribe`, body: hook });+ expect(data.has(MOXIE_HOOK_STORE_KEY)).toBe(false);+ });++ test('disable forgets the hook after a 404', async () => {+ const hook = { id: 'hook-1', type: 'TicketCreate', hookUrl: WEBHOOK_URL };+ const { store, data } = memoryStore({ initial: { [MOXIE_HOOK_STORE_KEY]: hook } });+ fail({ status: 404 });+ await moxieWebhook.disable({ credentials: CREDENTIALS, store });+ expect(data.has(MOXIE_HOOK_STORE_KEY)).toBe(false);+ });++ test('disable keeps the hook id when Moxie fails with a 500', async () => {+ const hook = { id: 'hook-1', type: 'TicketCreate', hookUrl: WEBHOOK_URL };+ const { store, data } = memoryStore({ initial: { [MOXIE_HOOK_STORE_KEY]: hook } });+ fail({ status: 500, body: { message: 'boom' } });+ await expect(moxieWebhook.disable({ credentials: CREDENTIALS, store })).rejects.toThrow('HTTP 500');+ expect(data.get(MOXIE_HOOK_STORE_KEY)).toEqual(hook);+ });++ test('disable with nothing stored sends no request', async () => {+ const { store } = memoryStore();+ await moxieWebhook.disable({ credentials: CREDENTIALS, store });+ expect(sendRequest).not.toHaveBeenCalled();+ });+});++describe('trigger wiring', () => {+ test('32 triggers ship: the 22 existing names plus 10 new ones, no Proposal triggers', () => {+ const names = moxieCRMTriggers.map((t) => t.name.replace('moxie_trigger_', ''));+ expect(names).toHaveLength(32);+ expect(names).toEqual(+ expect.arrayContaining([+ 'client_created',+ 'payment_received',+ 'invoice_voided',+ 'invoice_write_off',+ 'agreement_sent',+ 'agreement_viewed',+ 'agreement_signed',+ 'ticket_created',+ 'ticket_updated',+ 'ticket_closed',+ 'ticket_comment_added',+ 'ticket_deleted',+ ]),+ );+ expect(names.some((n) => n.startsWith('proposal'))).toBe(false);+ for (const trigger of moxieCRMTriggers) {+ expect(trigger.classification).toBe('READ');+ expect(trigger.aiMetadata?.description).toBeTruthy();+ }+ });++ test('a new trigger subscribes its own event type on enable and unsubscribes on disable', async () => {+ const { store } = memoryStore();+ ok({ body: 'hook-9' });+ await runHook({ trigger: triggerNamed('ticket_created'), hook: 'onEnable', context: { store } });+ expect(request(0)).toMatchObject({ url: `${BASE}/api/subscribe`, body: { type: 'TicketCreate', hookUrl: WEBHOOK_URL } });+ ok({ body: '' });+ await runHook({ trigger: triggerNamed('ticket_created'), hook: 'onDisable', context: { store } });+ expect(request(1)).toMatchObject({ url: `${BASE}/api/unsubscribe`, body: { id: 'hook-9', type: 'TicketCreate' } });+ });++ test('an existing trigger keeps manual setup: enable sends nothing', async () => {+ const { store } = memoryStore();+ await runHook({ trigger: triggerNamed('client_created'), hook: 'onEnable', context: { store } });+ await runHook({ trigger: triggerNamed('client_created'), hook: 'onDisable', context: { store } });+ expect(sendRequest).not.toHaveBeenCalled();+ });++ test('an existing trigger drops deliveries of another event and runs every matching one', async () => {+ const { store } = memoryStore();+ const trigger = triggerNamed('client_created');+ const wrong = { body: BODY, headers: { 'x-event-type': 'ClientUpdate' }, queryParams: {} };+ const right = { body: BODY, headers: { 'x-event-type': 'ClientCreate' }, queryParams: {} };+ await expect(runHook({ trigger, hook: 'run', context: { store, payload: wrong } })).resolves.toEqual([]);+ await expect(runHook({ trigger, hook: 'run', context: { store, payload: right } })).resolves.toEqual([BODY]);+ await expect(runHook({ trigger, hook: 'run', context: { store, payload: right } })).resolves.toEqual([BODY]);+ });++ test('invoice triggers carry the InvoiceMini output schema and every ticket trigger the ticket schema', () => {+ expect(triggerNamed('invoice_voided').outputSchema?.fields.map((f) => f.key)).toContain('invoiceNumberFormatted');+ expect(triggerNamed('payment_received').outputSchema).toBeDefined();+ for (const name of ['ticket_created', 'ticket_updated', 'ticket_comment_added', 'ticket_closed', 'ticket_deleted']) {+ expect(triggerNamed(name).outputSchema?.fields.map((f) => f.key)).toEqual(['ticket', 'comments']);+ }+ expect(triggerNamed('agreement_signed').outputSchema).toBeUndefined();+ });+});