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(invoiceninja): let AI agents manage invoices, clients, payments and reports (#16523)
Odai Ahmad06294b7b60b2
diff --git a/bun.lock b/bun.lockindex 3adc42ba6a1..5701bafeead 100644--- a/bun.lock+++ b/bun.lock@@ -4749,16 +4749,15 @@},"packages/pieces/community/invoiceninja": {"name": "@activepieces/piece-invoiceninja",- "version": "0.4.1",+ "version": "0.5.0","dependencies": {- "@activepieces/core-piece-types": "workspace:*",- "@activepieces/core-utils": "workspace:*","@activepieces/pieces-common": "workspace:*","@activepieces/pieces-framework": "workspace:*",- "zod": "4.3.6",+ "undici": "7.29.1",},"devDependencies": {"tslib": "2.6.2",+ "vitest": "3.2.6",},},"packages/pieces/community/jina-ai": {diff --git a/docs/install/reference/breaking-changes-unreleased.mdx b/docs/install/reference/breaking-changes-unreleased.mdxindex 1d9df580612..c5511e720f0 100644--- a/docs/install/reference/breaking-changes-unreleased.mdx+++ b/docs/install/reference/breaking-changes-unreleased.mdx@@ -8,6 +8,20 @@ Entries here move to [Breaking Changes](/install/reference/breaking-changes) aut## What has changed?+#### Invoice Ninja 0.5.0: Get Report returns columns and rows, the existing actions are builder-only, and some text inputs changed type++Get Report used to send a GET to `/api/v1/reports/<type>`, which does not return report data, and returned whatever came back (or an error message as a successful step). From Invoice Ninja 0.5.0 it runs the report and returns `{ reportType, columns, rows, rowCount }`, where each row is keyed by column key (for example `client.name`). It also gains a date range and fails the step on API errors.++Create Task, Check Task Existence, Get Client Details from e-mail, Get Invoices, Get Report, Create Invoice, Create Recurring Invoice and Perform Action on Recurring Invoice are now builder-only. AI agents use their twins: Create Task (by IDs), List Tasks, Find Clients, List Invoices, Run Report, Create Invoice (from line items), Create Recurring Invoice (from line items), and Start, Stop, Send Now or Delete Recurring Invoice.++Several single-line inputs (client name and address, task number, client email, recurring invoice ID) moved from long text to short text, Private Notes moved to long text, and Invoice Discount is now a number, and the Client ID text box on Get Invoices and Get Report is now a Client dropdown. Values saved by older steps still parse. The API token is now a secret and the connection is checked when it is saved.++TLS certificates are now checked on every request. A self-hosted Invoice Ninja server with a self-signed or expired certificate fails after the upgrade.++#### What you need to do++If a later step reads Get Report's output, map it to `rows` and `columns`. If you self-host Invoice Ninja with a self-signed certificate, give the server a certificate from a trusted authority (for example Let's Encrypt). Agents that used the builder actions as tools switch to the twins above. Steps keep running on the version they were built with until you upgrade them.+#### Gotify 0.5.0: Send Notification returns the message, and server URLs are checkedSend Notification used to return the whole HTTP response, `{ status, headers, body }`. From Gotify 0.5.0 it returns the created message itself (`id`, `appid`, `message`, `title`, `priority`, `extras`, `date`), which was `body` before. The app token is now sent in the `X-Gotify-Key` header instead of the URL query string, and a priority of `0` is sent as `0` instead of being dropped.diff --git a/packages/pieces/community/invoiceninja/package.json b/packages/pieces/community/invoiceninja/package.jsonindex 0ae8cdf59d6..88959c01d29 100644--- a/packages/pieces/community/invoiceninja/package.json+++ b/packages/pieces/community/invoiceninja/package.json@@ -1,21 +1,21 @@{"name": "@activepieces/piece-invoiceninja",- "version": "0.4.1",+ "version": "0.5.0","main": "./dist/src/index.js","types": "./dist/src/index.d.ts","scripts": {"build": "tsc -p tsconfig.lib.json && cp package.json dist/","bundle": "node ../../../../dist/packages/cli/src/index.js pieces bundle",- "lint": "eslint 'src/**/*.ts'"+ "lint": "eslint 'src/**/*.ts'",+ "test": "vitest run"},"dependencies": {"@activepieces/pieces-common": "workspace:*","@activepieces/pieces-framework": "workspace:*",- "zod": "4.3.6",- "@activepieces/core-piece-types": "workspace:*",- "@activepieces/core-utils": "workspace:*"+ "undici": "7.29.1"},"devDependencies": {- "tslib": "2.6.2"+ "tslib": "2.6.2",+ "vitest": "3.2.6"}}diff --git a/packages/pieces/community/invoiceninja/src/i18n/translation.json b/packages/pieces/community/invoiceninja/src/i18n/translation.jsonindex df84deccd58..66b309577b5 100644--- a/packages/pieces/community/invoiceninja/src/i18n/translation.json+++ b/packages/pieces/community/invoiceninja/src/i18n/translation.json@@ -2,9 +2,9 @@"Free open-source invoicing tool": "Free open-source invoicing tool","Base URL": "Base URL","API Token": "API Token",- "Enter the base URL": "Enter the base URL",- "Enter the API token": "Enter the API token",- "Please check https://invoice-ninja.readthedocs.io/en/latest/api_tokens.html#create-token\n to see how to get the API token": "Please check https://invoice-ninja.readthedocs.io/en/latest/api_tokens.html#create-token\n to see how to get the API token",+ "https://invoicing.co for the hosted service, or your self-hosted address such as https://invoices.example.com": "https://invoicing.co for the hosted service, or your self-hosted address such as https://invoices.example.com",+ "Settings > Account Management > API Tokens in Invoice Ninja.": "Settings > Account Management > API Tokens in Invoice Ninja.",+ "\n To connect Invoice Ninja (v5):\n\n 1. Log in to Invoice Ninja (https://invoicing.co or your self-hosted server).\n 2. Open **Settings > Account Management > API Tokens** and create a token.\n 3. Paste the token below. Base URL is https://invoicing.co for the hosted service, or the address of your own server (for example https://invoices.example.com).\n ": "\n To connect Invoice Ninja (v5):\n\n 1. Log in to Invoice Ninja (https://invoicing.co or your self-hosted server).\n 2. Open **Settings > Account Management > API Tokens** and create a token.\n 3. Paste the token below. Base URL is https://invoicing.co for the hosted service, or the address of your own server (for example https://invoices.example.com).\n ","Create Task": "Create Task","Check Task Existence": "Check Task Existence","Get Client Details from e-mail": "Get Client Details from e-mail",@@ -14,56 +14,231 @@"Create Client": "Create Client","Create Recurring Invoice": "Create Recurring Invoice","Perform Action on Recurring Invoice": "Perform Action on Recurring Invoice",+ "Get Client": "Get Client",+ "Find Clients": "Find Clients",+ "Update Client": "Update Client",+ "Archive Client": "Archive Client",+ "Restore Client": "Restore Client",+ "Delete Client": "Delete Client",+ "Get Invoice": "Get Invoice",+ "List Invoices": "List Invoices",+ "Create Invoice (from line items)": "Create Invoice (from line items)",+ "Update Invoice": "Update Invoice",+ "Email Invoice": "Email Invoice",+ "Mark Invoice Sent": "Mark Invoice Sent",+ "Mark Invoice Paid": "Mark Invoice Paid",+ "Archive Invoice": "Archive Invoice",+ "Restore Invoice": "Restore Invoice",+ "Delete Invoice": "Delete Invoice",+ "Get Quote": "Get Quote",+ "List Quotes": "List Quotes",+ "Create Quote": "Create Quote",+ "Update Quote": "Update Quote",+ "Email Quote": "Email Quote",+ "Approve Quote": "Approve Quote",+ "Convert Quote to Invoice": "Convert Quote to Invoice",+ "Delete Quote": "Delete Quote",+ "Get Recurring Invoice": "Get Recurring Invoice",+ "List Recurring Invoices": "List Recurring Invoices",+ "Create Recurring Invoice (from line items)": "Create Recurring Invoice (from line items)",+ "Start Recurring Invoice": "Start Recurring Invoice",+ "Pause Recurring Invoice": "Pause Recurring Invoice",+ "Send Recurring Invoice Now": "Send Recurring Invoice Now",+ "Delete Recurring Invoice": "Delete Recurring Invoice",+ "Get Payment": "Get Payment",+ "List Payments": "List Payments",+ "Create Payment": "Create Payment",+ "Refund Payment": "Refund Payment",+ "Delete Payment": "Delete Payment",+ "Get Credit": "Get Credit",+ "List Credits": "List Credits",+ "Create Credit": "Create Credit",+ "Get Product": "Get Product",+ "List Products": "List Products",+ "Create Product": "Create Product",+ "Update Product": "Update Product",+ "Get Expense": "Get Expense",+ "List Expenses": "List Expenses",+ "Create Expense": "Create Expense",+ "Get Task": "Get Task",+ "List Tasks": "List Tasks",+ "Create Task (by IDs)": "Create Task (by IDs)",+ "Update Task": "Update Task",+ "Start Task Timer": "Start Task Timer",+ "Stop Task Timer": "Stop Task Timer",+ "Get Project": "Get Project",+ "List Projects": "List Projects",+ "Create Project": "Create Project",+ "Get Vendor": "Get Vendor",+ "List Vendors": "List Vendors",+ "Create Vendor": "Create Vendor",+ "Run Report": "Run Report","Custom API Call": "Custom API Call",- "Creates a task instance in Invoice Ninja for billing purposes.": "Creates a task instance in Invoice Ninja for billing purposes.",- "Verify if a Task Already Exists": "Verify if a Task Already Exists",- "Gets the client details if they exist by e-mail.": "Gets the client details if they exist by e-mail.",- "Gets data for invoices.": "Gets data for invoices.",- "Gets report data from InvoiceNinja.": "Gets report data from InvoiceNinja.",- "Creates an invoice in Invoice Ninja for billing purposes.": "Creates an invoice in Invoice Ninja for billing purposes.",- "Creates a new client in InvoiceNinja.": "Creates a new client in InvoiceNinja.",- "Creates a recurring invoice in Invoice Ninja for billing purposes.": "Creates a recurring invoice in Invoice Ninja for billing purposes.",- "Actions include: start, stop, send_now, restore, archive, delete.": "Actions include: start, stop, send_now, restore, archive, delete.",+ "Creates a billable task in Invoice Ninja.": "Creates a billable task in Invoice Ninja.",+ "Returns 1 if a task with this number exists, 0 if not.": "Returns 1 if a task with this number exists, 0 if not.",+ "Gets the client whose contact has this e-mail. Returns false when there is none.": "Gets the client whose contact has this e-mail. Returns false when there is none.",+ "Gets invoices by payment status, optionally for one client. Returns false when none match.": "Gets invoices by payment status, optionally for one client. Returns false when none match.",+ "Runs an Invoice Ninja report and returns its columns and rows.": "Runs an Invoice Ninja report and returns its columns and rows.",+ "Creates an invoice from existing products (price and tax are taken from each product).": "Creates an invoice from existing products (price and tax are taken from each product).",+ "Creates a new client with a primary contact in Invoice Ninja.": "Creates a new client with a primary contact in Invoice Ninja.",+ "Creates a recurring invoice from existing products on a billing schedule.": "Creates a recurring invoice from existing products on a billing schedule.",+ "Start, stop, send now, restore, archive or delete a recurring invoice.": "Start, stop, send now, restore, archive or delete a recurring invoice.",+ "Get one client by its ID.": "Get one client by its ID.",+ "Search clients by text or exact contact email, one page at a time.": "Search clients by text or exact contact email, one page at a time.",+ "Change fields of an existing client. Empty fields are left unchanged.": "Change fields of an existing client. Empty fields are left unchanged.",+ "Archive a client (hidden from lists, can be restored).": "Archive a client (hidden from lists, can be restored).",+ "Restore an archived or deleted client.": "Restore an archived or deleted client.",+ "Delete a client (soft delete, can be restored).": "Delete a client (soft delete, can be restored).",+ "Get one invoice by its ID.": "Get one invoice by its ID.",+ "List invoices with filters, one page at a time.": "List invoices with filters, one page at a time.",+ "Create a draft invoice for a client from explicit line items.": "Create a draft invoice for a client from explicit line items.",+ "Change fields of an invoice. Empty fields are left unchanged.": "Change fields of an invoice. Empty fields are left unchanged.",+ "Email the invoice to the client's contacts and mark it sent.": "Email the invoice to the client's contacts and mark it sent.",+ "Mark a draft invoice as sent without emailing it.": "Mark a draft invoice as sent without emailing it.",+ "Record a payment for the full balance and mark the invoice paid.": "Record a payment for the full balance and mark the invoice paid.",+ "Archive an invoice (can be restored).": "Archive an invoice (can be restored).",+ "Restore an archived or deleted invoice.": "Restore an archived or deleted invoice.",+ "Delete an invoice (soft delete).": "Delete an invoice (soft delete).",+ "Get one quote by its ID.": "Get one quote by its ID.",+ "List quotes with filters, one page at a time.": "List quotes with filters, one page at a time.",+ "Create a draft quote for a client from line items.": "Create a draft quote for a client from line items.",+ "Change fields of a quote. Empty fields are left unchanged.": "Change fields of a quote. Empty fields are left unchanged.",+ "Email the quote to the client's contacts and mark it sent.": "Email the quote to the client's contacts and mark it sent.",+ "Mark a sent quote as approved on the client's behalf.": "Mark a sent quote as approved on the client's behalf.",+ "Create an invoice from a quote.": "Create an invoice from a quote.",+ "Delete a quote (soft delete).": "Delete a quote (soft delete).",+ "Get one recurring invoice by its ID.": "Get one recurring invoice by its ID.",+ "List recurring invoices, one page at a time.": "List recurring invoices, one page at a time.",+ "Create a draft recurring invoice from line items and a schedule.": "Create a draft recurring invoice from line items and a schedule.",+ "Start (or resume) the schedule of a recurring invoice.": "Start (or resume) the schedule of a recurring invoice.",+ "Pause the schedule of a recurring invoice.": "Pause the schedule of a recurring invoice.",+ "Generate and send the next invoice of a recurring invoice now.": "Generate and send the next invoice of a recurring invoice now.",+ "Delete a recurring invoice (soft delete; invoices already generated stay).": "Delete a recurring invoice (soft delete; invoices already generated stay).",+ "Get one payment by its ID.": "Get one payment by its ID.",+ "List payments, one page at a time.": "List payments, one page at a time.",+ "Record a manual payment from a client, optionally applied to an invoice.": "Record a manual payment from a client, optionally applied to an invoice.",+ "Record a refund of a payment in Invoice Ninja (no money is moved at a payment gateway).": "Record a refund of a payment in Invoice Ninja (no money is moved at a payment gateway).",+ "Delete a payment (reopens the invoices it paid).": "Delete a payment (reopens the invoices it paid).",+ "Get one credit by its ID.": "Get one credit by its ID.",+ "List credit notes, one page at a time.": "List credit notes, one page at a time.",+ "Create a draft credit note for a client from line items.": "Create a draft credit note for a client from line items.",+ "Get one product by its ID.": "Get one product by its ID.",+ "List or search products, one page at a time.": "List or search products, one page at a time.",+ "Create a product.": "Create a product.",+ "Change fields of a product. Empty fields are left unchanged.": "Change fields of a product. Empty fields are left unchanged.",+ "Get one expense by its ID.": "Get one expense by its ID.",+ "List expenses, one page at a time.": "List expenses, one page at a time.",+ "Record an expense, optionally for a client, vendor or project.": "Record an expense, optionally for a client, vendor or project.",+ "Get one task by its ID.": "Get one task by its ID.",+ "List tasks, one page at a time.": "List tasks, one page at a time.",+ "Create a task (billable time entry), optionally with logged time.": "Create a task (billable time entry), optionally with logged time.",+ "Change fields of a task. Empty fields are left unchanged.": "Change fields of a task. Empty fields are left unchanged.",+ "Start the timer of a task (adds a new running time entry).": "Start the timer of a task (adds a new running time entry).",+ "Stop the running timer of a task.": "Stop the running timer of a task.",+ "Get one project by its ID.": "Get one project by its ID.",+ "List projects, one page at a time.": "List projects, one page at a time.",+ "Create a project for a client.": "Create a project for a client.",+ "Get one vendor by its ID.": "Get one vendor by its ID.",+ "List or search vendors, one page at a time.": "List or search vendors, one page at a time.",+ "Create a vendor (supplier) with an optional contact.": "Create a vendor (supplier) with an optional contact.",+ "Run an Invoice Ninja report and return its rows.": "Run an Invoice Ninja report and return its rows.","Make a custom API call to a specific endpoint": "Make a custom API call to a specific endpoint",- "Task or Ticket Number (alphanumeric)": "Task or Ticket Number (alphanumeric)",- "Client ID (alphanumeric)": "Client ID (alphanumeric)",- "Project ID (alphanumeric)": "Project ID (alphanumeric)",- "Description of task": "Description of task",- "Custom hourly rate": "Custom hourly rate",+ "Task or Ticket Number": "Task or Ticket Number",+ "Client": "Client",+ "Project": "Project",+ "Description": "Description",+ "Custom Hourly Rate": "Custom Hourly Rate","Client e-mail address": "Client e-mail address","Invoice Status": "Invoice Status",- "Client ID": "Client ID","Max Results": "Max Results","Report Type": "Report Type",- "Purchase Order Number (alphanumeric)": "Purchase Order Number (alphanumeric)",- "Apply discount": "Apply discount",+ "Date Range": "Date Range",+ "Start Date": "Start Date",+ "End Date": "End Date",+ "Max Rows": "Max Rows",+ "Purchase Order Number": "Purchase Order Number",+ "Invoice Discount": "Invoice Discount","Type of discount": "Type of discount",- "Public notes for invoice": "Public notes for invoice",- "Private notes for invoice": "Private notes for invoice",- "Order Items JSON string": "Order Items JSON string",- "Send invoice to the client by InvoiceNinja e-mail?": "Send invoice to the client by InvoiceNinja e-mail?",- "Mark the invoice as sent?": "Mark the invoice as sent?",+ "Public notes": "Public notes",+ "Private notes": "Private notes",+ "Order Items JSON": "Order Items JSON",+ "E-mail the invoice to the client": "E-mail the invoice to the client",+ "Mark the invoice as sent": "Mark the invoice as sent","Invoice due date": "Invoice due date",- "Client First Name (alphanumeric)": "Client First Name (alphanumeric)",- "Client Last Name (alphanumeric)": "Client Last Name (alphanumeric)",- "Client Contact No (alphanumeric)": "Client Contact No (alphanumeric)",- "Client e-mail (alphanumeric)": "Client e-mail (alphanumeric)",+ "Contact First Name": "Contact First Name",+ "Contact Last Name": "Contact Last Name",+ "Contact Phone": "Contact Phone",+ "Contact Email": "Contact Email","Send invoices to the client": "Send invoices to the client",- "Business Name (alphanumeric)": "Business Name (alphanumeric)",- "Client Tax Number (alphanumeric)": "Client Tax Number (alphanumeric)",- "Private notes for client": "Private notes for client",- "Client address 1 (alphanumeric)": "Client address 1 (alphanumeric)",- "Client address 2 (alphanumeric)": "Client address 2 (alphanumeric)",- "Client City/Town (alphanumeric)": "Client City/Town (alphanumeric)",- "Client State (alphanumeric)": "Client State (alphanumeric)",- "Client Postcode (alphanumeric)": "Client Postcode (alphanumeric)",+ "Business Name": "Business Name",+ "VAT / Tax Number": "VAT / Tax Number",+ "Private Notes": "Private Notes",+ "Address Line 1": "Address Line 1",+ "Address Line 2": "Address Line 2",+ "City / Town": "City / Town",+ "State / County": "State / County",+ "Postcode": "Postcode","Frequency of billing": "Frequency of billing",- "No of billing cycles": "No of billing cycles",- "Override Frequency using Frequency ID (optional)": "Override Frequency using Frequency ID (optional)",- "Invoice next send date": "Invoice next send date",- "Invoice last sent date": "Invoice last sent date",- "Recurring Invoice ID (alphanumeric)": "Recurring Invoice ID (alphanumeric)",+ "Number of billing cycles": "Number of billing cycles",+ "Override Frequency ID": "Override Frequency ID",+ "Next send date": "Next send date",+ "Last sent date": "Last sent date",+ "Recurring Invoice ID": "Recurring Invoice ID","Action to perform": "Action to perform",+ "Client ID": "Client ID",+ "Search": "Search",+ "Record State": "Record State",+ "Sort": "Sort",+ "Page": "Page",+ "Per Page": "Per Page",+ "Name": "Name",+ "Website": "Website",+ "Phone": "Phone",+ "VAT Number": "VAT Number",+ "ID Number": "ID Number",+ "City": "City",+ "State": "State",+ "Postal Code": "Postal Code",+ "Public Notes": "Public Notes",+ "Clear Fields": "Clear Fields",+ "Invoice ID": "Invoice ID",+ "Payment State": "Payment State",+ "Line Items": "Line Items",+ "Date": "Date",+ "PO Number": "PO Number",+ "Discount": "Discount",+ "Discount Is Amount": "Discount Is Amount",+ "Terms": "Terms",+ "Project ID": "Project ID",+ "Due Date": "Due Date",+ "Quote ID": "Quote ID",+ "Quote State": "Quote State",+ "Schedule State": "Schedule State",+ "Frequency ID": "Frequency ID",+ "Next Send Date": "Next Send Date",+ "Remaining Cycles": "Remaining Cycles",+ "Payment ID": "Payment ID",+ "Amount": "Amount",+ "Transaction Reference": "Transaction Reference",+ "Credit ID": "Credit ID",+ "Product ID": "Product ID",+ "Product Key": "Product Key",+ "Price": "Price",+ "Cost": "Cost",+ "Default Quantity": "Default Quantity",+ "Tax Name": "Tax Name",+ "Tax Rate (%)": "Tax Rate (%)",+ "Expense ID": "Expense ID",+ "Vendor ID": "Vendor ID",+ "Expense Category ID": "Expense Category ID",+ "Should Be Invoiced": "Should Be Invoiced",+ "Task ID": "Task ID",+ "Task Number": "Task Number",+ "Hourly Rate": "Hourly Rate",+ "Start Time": "Start Time",+ "End Time": "End Time",+ "Task Rate": "Task Rate",+ "Budgeted Hours": "Budgeted Hours","Method": "Method","Headers": "Headers","Query Parameters": "Query Parameters",@@ -73,43 +248,88 @@"Return Error as Output": "Return Error as Output","Timeout": "Timeout","Follow redirects": "Follow redirects",- "A unique task or ticket number that has not been used before in Invoice Ninja": "A unique task or ticket number that has not been used before in Invoice Ninja",- "Client ID from Invoice Ninja (optional)": "Client ID from Invoice Ninja (optional)",- "Project ID from Invoice Ninja (optional)": "Project ID from Invoice Ninja (optional)",- "Description of task to be billed": "Description of task to be billed",- "Custom hourly rate (optional) otherwise default used": "Custom hourly rate (optional) otherwise default used",- "A task or ticket number to check": "A task or ticket number to check",- "A valid e-mail address to get client details for": "A valid e-mail address to get client details for",+ "A task or ticket number not used before in Invoice Ninja.": "A task or ticket number not used before in Invoice Ninja.",+ "The Invoice Ninja client.": "The Invoice Ninja client.",+ "The Invoice Ninja project (optional).": "The Invoice Ninja project (optional).",+ "What the task is about.": "What the task is about.",+ "Leave empty to use the default rate.": "Leave empty to use the default rate.",+ "The task or ticket number to check.": "The task or ticket number to check.",+ "The e-mail address of one of the client's contacts.": "The e-mail address of one of the client's contacts.","Select the invoice status for filtering.": "Select the invoice status for filtering.",- "Filter by Client ID, default is all clients.": "Filter by Client ID, default is all clients.",- "Maximum number of results to return. 9999 is default.": "Maximum number of results to return. 9999 is default.",- "Select the report type.": "Select the report type.",- "Client ID from Invoice Ninja": "Client ID from Invoice Ninja",- "Descriptive text or arbitrary number (optional)": "Descriptive text or arbitrary number (optional)",- "Enter a number for the whole invoice discount": "Enter a number for the whole invoice discount",- "Select either amount or percentage for invoice discount. Applies to line items and invoice.": "Select either amount or percentage for invoice discount. Applies to line items and invoice.",- "Text that may be visible in the client portal (optional)": "Text that may be visible in the client portal (optional)",- "Text not visible for clients (optional)": "Text not visible for clients (optional)",- "e.g., [{ \"quantity\":1,\"product_key\":\"product key\", \"discount\": \"0\" }]": "e.g., [{ \"quantity\":1,\"product_key\":\"product key\", \"discount\": \"0\" }]",- "Should we send the invoice to the client on creation?": "Should we send the invoice to the client on creation?",- "Makes the invoice active otherwise remains pending.": "Makes the invoice active otherwise remains pending.",- "e.g., 2024-01-20": "e.g., 2024-01-20",- "The contact first name for this client (optional)": "The contact first name for this client (optional)",- "The contact last name for this client (optional)": "The contact last name for this client (optional)",- "The contact number for this client (optional)": "The contact number for this client (optional)",- "The contact email for this client (compulsory)": "The contact email for this client (compulsory)",- "Should we send invoices to the client by e-mail?": "Should we send invoices to the client by e-mail?",- "Name of this business or natural person (compulsory)": "Name of this business or natural person (compulsory)",- "Leave blank if not a business (optional)": "Leave blank if not a business (optional)",- "Usually street name and number (compulsory)": "Usually street name and number (compulsory)",- "Additional address details (optional)": "Additional address details (optional)",- "City or Town name (compulsory)": "City or Town name (compulsory)",- "State or county or similar (optional)": "State or county or similar (optional)",- "Postal code (optional)": "Postal code (optional)",- "Choose one": "Choose one",- "Enter a number. How many times should this bill be generated": "Enter a number. How many times should this bill be generated",- "Enter a number. 1-12 - corresponds to dropdown above [Daily being 1, Weekly 2 etc..]!": "Enter a number. 1-12 - corresponds to dropdown above [Daily being 1, Weekly 2 etc..]!",- "Recurring Invoice ID from Invoice Ninja": "Recurring Invoice ID from Invoice Ninja",+ "Maximum number of invoices to return (1-9999). Default 9999.": "Maximum number of invoices to return (1-9999). Default 9999.",+ "Default: all time.": "Default: all time.",+ "YYYY-MM-DD, for a custom range.": "YYYY-MM-DD, for a custom range.",+ "Return at most this many rows. Empty = all.": "Return at most this many rows. Empty = all.",+ "Descriptive text or number (optional).": "Descriptive text or number (optional).",+ "Discount for the whole invoice. 0 = none.": "Discount for the whole invoice. 0 = none.",+ "Amount or percentage. Applies to line items and invoice.": "Amount or percentage. Applies to line items and invoice.",+ "Visible in the client portal (optional).": "Visible in the client portal (optional).",+ "Not visible to the client (optional).": "Not visible to the client (optional).",+ "Each item references an existing product key; price, description and tax come from the product. e.g. [{ \"quantity\":1,\"product_key\":\"product key\", \"discount\": \"0\" }]": "Each item references an existing product key; price, description and tax come from the product. e.g. [{ \"quantity\":1,\"product_key\":\"product key\", \"discount\": \"0\" }]",+ "Send the invoice by Invoice Ninja e-mail when it is created.": "Send the invoice by Invoice Ninja e-mail when it is created.",+ "Makes the invoice active; otherwise it stays a draft.": "Makes the invoice active; otherwise it stays a draft.",+ "The date part is used, e.g. 2024-01-20.": "The date part is used, e.g. 2024-01-20.",+ "First name of the client contact (optional).": "First name of the client contact (optional).",+ "Last name of the client contact (optional).": "Last name of the client contact (optional).",+ "Phone number of the client contact (optional).": "Phone number of the client contact (optional).",+ "E-mail of the client contact.": "E-mail of the client contact.",+ "Should Invoice Ninja e-mail invoices to this contact?": "Should Invoice Ninja e-mail invoices to this contact?",+ "Name of the business or person.": "Name of the business or person.",+ "Leave blank if not a business (optional).": "Leave blank if not a business (optional).",+ "Notes not visible to the client (optional).": "Notes not visible to the client (optional).",+ "Usually street name and number.": "Usually street name and number.",+ "Additional address details (optional).": "Additional address details (optional).",+ "Optional.": "Optional.",+ "How often an invoice is generated.": "How often an invoice is generated.",+ "How many invoices to generate. Empty = endless.": "How many invoices to generate. Empty = endless.",+ "When set, this wins over Frequency: 1-12 (Daily 1, Weekly 2, ...).": "When set, this wins over Frequency: 1-12 (Daily 1, Weekly 2, ...).",+ "Date the first invoice is generated, e.g. 2024-01-20.": "Date the first invoice is generated, e.g. 2024-01-20.",+ "Optional, e.g. 2024-01-20.": "Optional, e.g. 2024-01-20.",+ "The ID of the recurring invoice in Invoice Ninja.": "The ID of the recurring invoice in Invoice Ninja.",+ "Choose one.": "Choose one.",+ "The Invoice Ninja ID of the client (letters and digits, e.g. VolejRejNm).": "The Invoice Ninja ID of the client (letters and digits, e.g. VolejRejNm).",+ "Free-text filter.": "Free-text filter.",+ "Exact contact email.": "Exact contact email.",+ "Which records to include. Default: active only.": "Which records to include. Default: active only.",+ "Sort order. Default: Invoice Ninja default (newest first for most records).": "Sort order. Default: Invoice Ninja default (newest first for most records).",+ "Page number, starting at 1. Default 1.": "Page number, starting at 1. Default 1.",+ "Results per page (1-100). Default 20.": "Results per page (1-100). Default 20.",+ "Fields to blank out. Fields you leave empty above are not changed.": "Fields to blank out. Fields you leave empty above are not changed.",+ "The Invoice Ninja ID of the client.": "The Invoice Ninja ID of the client.",+ "The Invoice Ninja ID of the invoice (letters and digits, e.g. VolejRejNm).": "The Invoice Ninja ID of the invoice (letters and digits, e.g. VolejRejNm).",+ "One entry per line. Give a product key and/or description, the unit cost and the quantity. Values are used as given (no product price lookup).": "One entry per line. Give a product key and/or description, the unit cost and the quantity. Values are used as given (no product price lookup).",+ "YYYY-MM-DD. Default today (company time zone).": "YYYY-MM-DD. Default today (company time zone).",+ "Whole-document discount.": "Whole-document discount.",+ "On = discount is an amount, off = percent. Default off (percent).": "On = discount is an amount, off = percent. Default off (percent).",+ "Visible to the client.": "Visible to the client.",+ "Internal only.": "Internal only.",+ "YYYY-MM-DD.": "YYYY-MM-DD.",+ "The Invoice Ninja ID of the invoice.": "The Invoice Ninja ID of the invoice.",+ "The Invoice Ninja ID of the quote (letters and digits, e.g. VolejRejNm).": "The Invoice Ninja ID of the quote (letters and digits, e.g. VolejRejNm).",+ "The Invoice Ninja ID of the quote.": "The Invoice Ninja ID of the quote.",+ "The Invoice Ninja ID of the recurring invoice (letters and digits, e.g. VolejRejNm).": "The Invoice Ninja ID of the recurring invoice (letters and digits, e.g. VolejRejNm).",+ "1-12, see the description. 5 = monthly.": "1-12, see the description. 5 = monthly.",+ "YYYY-MM-DD, today or later.": "YYYY-MM-DD, today or later.",+ "How many invoices to generate; -1 or empty = endless.": "How many invoices to generate; -1 or empty = endless.",+ "The Invoice Ninja ID of the recurring invoice.": "The Invoice Ninja ID of the recurring invoice.",+ "The Invoice Ninja ID of the payment (letters and digits, e.g. VolejRejNm).": "The Invoice Ninja ID of the payment (letters and digits, e.g. VolejRejNm).",+ "Apply the payment to this invoice.": "Apply the payment to this invoice.",+ "YYYY-MM-DD. Default today.": "YYYY-MM-DD. Default today.",+ "Default: the whole unrefunded amount.": "Default: the whole unrefunded amount.",+ "The Invoice Ninja ID of the payment.": "The Invoice Ninja ID of the payment.",+ "The Invoice Ninja ID of the credit (letters and digits, e.g. VolejRejNm).": "The Invoice Ninja ID of the credit (letters and digits, e.g. VolejRejNm).",+ "The Invoice Ninja ID of the product (letters and digits, e.g. VolejRejNm).": "The Invoice Ninja ID of the product (letters and digits, e.g. VolejRejNm).",+ "Product name or SKU.": "Product name or SKU.",+ "Your purchase cost.": "Your purchase cost.",+ "The Invoice Ninja ID of the expense (letters and digits, e.g. VolejRejNm).": "The Invoice Ninja ID of the expense (letters and digits, e.g. VolejRejNm).",+ "The Invoice Ninja ID of the task (letters and digits, e.g. VolejRejNm).": "The Invoice Ninja ID of the task (letters and digits, e.g. VolejRejNm).",+ "ISO 8601, e.g. 2026-01-31T09:00:00Z.": "ISO 8601, e.g. 2026-01-31T09:00:00Z.",+ "ISO 8601. Empty with a start time = timer keeps running.": "ISO 8601. Empty with a start time = timer keeps running.",+ "The Invoice Ninja ID of the task.": "The Invoice Ninja ID of the task.",+ "The Invoice Ninja ID of the project (letters and digits, e.g. VolejRejNm).": "The Invoice Ninja ID of the project (letters and digits, e.g. VolejRejNm).",+ "Hourly rate for tasks of this project.": "Hourly rate for tasks of this project.",+ "The Invoice Ninja ID of the vendor (letters and digits, e.g. VolejRejNm).": "The Invoice Ninja ID of the vendor (letters and digits, e.g. VolejRejNm).",+ "Only this client (optional).": "Only this client (optional).","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.",@@ -120,8 +340,29 @@"Paid Invoices": "Paid Invoices","Overdue Invoices": "Overdue Invoices","All Invoices": "All Invoices",+ "Clients": "Clients",+ "Contacts": "Contacts","Invoices": "Invoices",- "Amount": "Amount",+ "Invoice Items": "Invoice Items",+ "Quotes": "Quotes",+ "Quote Items": "Quote Items",+ "Credits": "Credits",+ "Payments": "Payments",+ "Recurring Invoices": "Recurring Invoices",+ "Expenses": "Expenses",+ "Tasks": "Tasks",+ "Products": "Products",+ "Vendors": "Vendors",+ "All time": "All time",+ "Last 7 days": "Last 7 days",+ "Last 30 days": "Last 30 days",+ "This month": "This month",+ "Last month": "Last month",+ "This quarter": "This quarter",+ "Last quarter": "Last quarter",+ "This year": "This year",+ "Last year": "Last year",+ "Custom (start and end date)": "Custom (start and end date)","Percentage": "Percentage","Use override below": "Use override below","Daily": "Daily",@@ -142,6 +383,42 @@"Restore": "Restore","Archive": "Archive","Delete": "Delete",+ "Active": "Active",+ "Archived": "Archived",+ "Deleted": "Deleted",+ "Active and archived": "Active and archived",+ "All": "All",+ "Newest first": "Newest first",+ "Oldest first": "Oldest first",+ "Recently updated first": "Recently updated first",+ "website": "website",+ "phone": "phone",+ "vat_number": "vat_number",+ "id_number": "id_number",+ "address1": "address1",+ "address2": "address2",+ "city": "city",+ "state": "state",+ "postal_code": "postal_code",+ "public_notes": "public_notes",+ "private_notes": "private_notes",+ "Draft": "Draft",+ "Paid": "Paid",+ "Unpaid": "Unpaid",+ "Overdue": "Overdue",+ "po_number": "po_number",+ "terms": "terms",+ "due_date": "due_date",+ "Sent": "Sent",+ "Approved": "Approved",+ "Converted": "Converted",+ "Expired": "Expired",+ "Paused": "Paused",+ "Completed": "Completed",+ "notes": "notes",+ "tax_name1": "tax_name1",+ "description": "description",+ "project_id": "project_id","GET": "GET","POST": "POST","PATCH": "PATCH",diff --git a/packages/pieces/community/invoiceninja/src/index.ts b/packages/pieces/community/invoiceninja/src/index.tsindex 696e3dec26b..cd4fe5137d3 100644--- a/packages/pieces/community/invoiceninja/src/index.ts+++ b/packages/pieces/community/invoiceninja/src/index.ts@@ -1,46 +1,32 @@import { createCustomApiCallAction } from '@activepieces/pieces-common';-import {- PieceAuth,- Property,- createPiece,-} from '@activepieces/pieces-framework';-import { PieceCategory } from '@activepieces/pieces-framework';+import { createPiece, PieceCategory } from '@activepieces/pieces-framework';+import { actionRecurringInvoice } from './lib/actions/action-recurring';+import { archiveClient, deleteClient, findClients, getClientAi, restoreClient, updateClient } from './lib/actions/ai/clients';+import { createCredit, createProduct, getCredit, getProduct, listCredits, listProducts, updateProduct } from './lib/actions/ai/credits-products';+import { createExpense, createProject, createVendor, getExpense, getProject, getVendor, listExpenses, listProjects, listVendors } from './lib/actions/ai/expenses-projects-vendors';+import { archiveInvoice, createInvoiceAi, deleteInvoice, emailInvoice, getInvoice, listInvoices, markInvoicePaid, markInvoiceSent, restoreInvoice, updateInvoice } from './lib/actions/ai/invoices';+import { createPayment, deletePayment, getPayment, listPayments, refundPayment } from './lib/actions/ai/payments';+import { approveQuote, convertQuoteToInvoice, createQuote, deleteQuote, emailQuote, getQuote, listQuotes, updateQuote } from './lib/actions/ai/quotes';+import { createRecurringInvoiceAi, deleteRecurringInvoice, getRecurringInvoice, listRecurringInvoices, sendRecurringInvoiceNow, startRecurringInvoice, stopRecurringInvoice } from './lib/actions/ai/recurring-invoices';+import { createTaskAi, getTask, listTasks, runReport, startTask, stopTask, updateTask } from './lib/actions/ai/tasks-reports';+import { createClient } from './lib/actions/create-client';+import { createInvoice } from './lib/actions/create-invoice';+import { createRecurringInvoice } from './lib/actions/create-recurring';import { createTask } from './lib/actions/create-task';import { getClient } from './lib/actions/get-client';import { getInvoices } from './lib/actions/get-invoices';import { getReport } from './lib/actions/get-report';import { existsTask } from './lib/actions/task-exists';-import { createInvoice } from './lib/actions/create-invoice';-import { createClient } from './lib/actions/create-client';-import { createRecurringInvoice } from './lib/actions/create-recurring';-import { actionRecurringInvoice } from './lib/actions/action-recurring';--export const invoiceninjaAuth = PieceAuth.CustomAuth({- props: {- base_url: Property.ShortText({- displayName: 'Base URL',- description: 'Enter the base URL',- required: true,- }),- access_token: Property.ShortText({- displayName: 'API Token',- description: 'Enter the API token',- required: true,- }),- },- description: `Please check https://invoice-ninja.readthedocs.io/en/latest/api_tokens.html#create-token- to see how to get the API token`,- required: true,-});+import { invoiceninjaAuth } from './lib/common/auth';+import { invoiceNinjaClient } from './lib/common/client';export const invoiceninja = createPiece({displayName: 'Invoice Ninja',description: 'Free open-source invoicing tool',-- minimumSupportedRelease: '0.30.0',+ minimumSupportedRelease: '0.88.2',logoUrl: 'https://cdn.activepieces.com/pieces/invoiceninja.png',categories: [PieceCategory.ACCOUNTING],- authors: ["buttonsbond","kishanprmr","MoShizzle","AbdulTheActivePiecer","khaledmashaly","abuaboud"],+ authors: ['buttonsbond', 'kishanprmr', 'MoShizzle', 'AbdulTheActivePiecer', 'khaledmashaly', 'abuaboud'],auth: invoiceninjaAuth,actions: [createTask,@@ -52,14 +38,85 @@ export const invoiceninja = createPiece({createClient,createRecurringInvoice,actionRecurringInvoice,+ getClientAi,+ findClients,+ updateClient,+ archiveClient,+ restoreClient,+ deleteClient,+ getInvoice,+ listInvoices,+ createInvoiceAi,+ updateInvoice,+ emailInvoice,+ markInvoiceSent,+ markInvoicePaid,+ archiveInvoice,+ restoreInvoice,+ deleteInvoice,+ getQuote,+ listQuotes,+ createQuote,+ updateQuote,+ emailQuote,+ approveQuote,+ convertQuoteToInvoice,+ deleteQuote,+ getRecurringInvoice,+ listRecurringInvoices,+ createRecurringInvoiceAi,+ startRecurringInvoice,+ stopRecurringInvoice,+ sendRecurringInvoiceNow,+ deleteRecurringInvoice,+ getPayment,+ listPayments,+ createPayment,+ refundPayment,+ deletePayment,+ getCredit,+ listCredits,+ createCredit,+ getProduct,+ listProducts,+ createProduct,+ updateProduct,+ getExpense,+ listExpenses,+ createExpense,+ getTask,+ listTasks,+ createTaskAi,+ updateTask,+ startTask,+ stopTask,+ getProject,+ listProjects,+ createProject,+ getVendor,+ listVendors,+ createVendor,+ runReport,createCustomApiCallAction({- baseUrl: (auth) =>- auth ? `${(auth).props.base_url.replace(/\/$/, '')}/api/v1` : '',auth: invoiceninjaAuth,- authMapping: async (auth) => ({- 'X-Api-Token': (auth).props.access_token,- }),+ baseUrl: (auth) => (auth ? invoiceNinjaClient.apiBaseUrl(auth.props.base_url) : ''),+ authMapping: async (auth, propsValue) => {+ const baseUrl = invoiceNinjaClient.apiBaseUrl(auth.props.base_url);+ const urlProp = propsValue['url'];+ const url = invoiceNinjaClient.isRecord(urlProp) && typeof urlProp['url'] === 'string' ? urlProp['url'].trim() : '';+ if (/^[a-z][a-z0-9+.-]*:/i.test(url) || url.startsWith('//')) {+ if (!invoiceNinjaClient.isSameOrigin({ url, baseUrl })) {+ throw new Error('The URL must be on the Invoice Ninja Base URL of the connection.');+ }+ }+ if (url.split(/[/?#]/).some((part) => part === '..' || part.toLowerCase().includes('%2e'))) {+ throw new Error('The URL must not contain ".." segments.');+ }+ return invoiceNinjaClient.authHeaders(auth.props);+ },}),],triggers: [],});++export { invoiceninjaAuth };diff --git a/packages/pieces/community/invoiceninja/src/lib/actions/action-recurring.ts b/packages/pieces/community/invoiceninja/src/lib/actions/action-recurring.tsindex c6e428fe900..c77bf6b79e6 100644--- a/packages/pieces/community/invoiceninja/src/lib/actions/action-recurring.ts+++ b/packages/pieces/community/invoiceninja/src/lib/actions/action-recurring.ts@@ -1,92 +1,56 @@-import {- createAction,- Property,-} from '@activepieces/pieces-framework';--import { invoiceninjaAuth } from '../..';+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { invoiceninjaAuth } from '../common/auth';+import { invoiceNinjaClient } from '../common/client';+import { invoiceNinjaOutputSchemas } from '../common/output-schemas';export const actionRecurringInvoice = createAction({auth: invoiceninjaAuth,name: 'action_recurring_invoice',classification: 'DESTRUCTIVE',displayName: 'Perform Action on Recurring Invoice',- description:- 'Actions include: start, stop, send_now, restore, archive, delete.',- audience: 'both',- aiMetadata: { description: 'Performs a lifecycle action on an existing recurring invoice in Invoice Ninja, identified by its id. The action prop selects which operation to apply: start, stop, send_now, restore, archive, or delete. Requires a valid recurring invoice id. Treat as not idempotent — actions such as send_now and delete have per-call side effects.', idempotent: false },+ description: 'Start, stop, send now, restore, archive or delete a recurring invoice.',+ audience: 'human',+ outputSchema: invoiceNinjaOutputSchemas.legacyRecurringAction,props: {- recurring_id: Property.LongText({- displayName: 'Recurring Invoice ID (alphanumeric)',- description: 'Recurring Invoice ID from Invoice Ninja',+ recurring_id: Property.ShortText({+ displayName: 'Recurring Invoice ID',+ description: 'The ID of the recurring invoice in Invoice Ninja.',required: true,}),actionRecurring: Property.StaticDropdown({displayName: 'Action to perform',- description: 'Choose one',- defaultValue: 1,+ description: 'Choose one.',+ defaultValue: 'start',required: true,options: {options: [- {- label: 'Start',- value: 'start',- },- {- label: 'Stop',- value: 'stop',- },- {- label: 'Send Now',- value: 'send_now',- },- {- label: 'Restore',- value: 'restore',- },- {- label: 'Archive',- value: 'archive',- },- {- label: 'Delete',- value: 'delete',- },+ { label: 'Start', value: 'start' },+ { label: 'Stop', value: 'stop' },+ { label: 'Send Now', value: 'send_now' },+ { label: 'Restore', value: 'restore' },+ { label: 'Archive', value: 'archive' },+ { label: 'Delete', value: 'delete' },],},}),},-- async run(context) {- const INapiToken = context.auth.props.access_token;- const headers = {- 'X-Api-Token': INapiToken,- 'Content-Type': 'application/json',- };-- const baseUrl = context.auth.props.base_url.replace(/\/$/, '');- const i: string[] = [context.propsValue.recurring_id];-- const createRequestBody = {- action: context.propsValue.actionRecurring,- ids: i,- };- const createRequestResponse = await fetch(- `${baseUrl}/api/v1/recurring_invoices/bulk`,- {- method: 'POST',- headers,- body: JSON.stringify(createRequestBody),- }- );-- if (!createRequestResponse.ok) {- throw new Error(- `Failed to perform action on recurring invoice. Status: ${createRequestResponse.status}`- );+ async run({ auth, propsValue }) {+ const action = propsValue.actionRecurring;+ if (!['start', 'stop', 'send_now', 'restore', 'archive', 'delete'].includes(action)) {+ throw new Error('Choose an action to perform.');}-- const createResponseBody = await createRequestResponse.json();-- return createResponseBody;+ const id = invoiceNinjaClient.parseId({ value: propsValue.recurring_id, label: 'Recurring Invoice ID' });+ const body = await invoiceNinjaClient.request({+ auth: auth.props,+ method: HttpMethod.POST,+ path: '/recurring_invoices/bulk',+ body: { action, ids: [id] },+ });+ const envelope = invoiceNinjaClient.envelopeOf(body);+ if (invoiceNinjaClient.arrayOf(envelope.data).length === 0) {+ throw new Error(`Invoice Ninja did not return recurring invoice ${id}; it may not exist.`);+ }+ return envelope;},});diff --git a/packages/pieces/community/invoiceninja/src/lib/actions/ai/clients.ts b/packages/pieces/community/invoiceninja/src/lib/actions/ai/clients.tsnew file mode 100644index 00000000000..5935d20ef2c--- /dev/null+++ b/packages/pieces/community/invoiceninja/src/lib/actions/ai/clients.ts@@ -0,0 +1,160 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { invoiceninjaAuth } from '../../common/auth';+import { invoiceNinjaClient } from '../../common/client';+import { entityActions } from '../../common/entity-actions';+import { invoiceNinjaOutputSchemas } from '../../common/output-schemas';+import { invoiceNinjaProps } from '../../common/props';++const CLEARABLE = ['website', 'phone', 'vat_number', 'id_number', 'address1', 'address2', 'city', 'state', 'postal_code', 'public_notes', 'private_notes'] as const;++export const getClientAi = createAction({+ auth: invoiceninjaAuth,+ name: 'get_client',+ classification: 'READ',+ displayName: 'Get Client',+ description: 'Get one client by its ID.',+ audience: 'ai',+ aiMetadata: {+ description: 'Returns one Invoice Ninja client by its ID, with address, balances and contacts. Use Find Clients first if you only know a name or email. Read-only.',+ idempotent: true,+ },+ outputSchema: invoiceNinjaOutputSchemas.client,+ props: { id: entityActions.getIdProp('Client') },+ async run({ auth, propsValue }) {+ return entityActions.runGet({ auth: auth.props, entity: 'clients', label: 'Client', id: propsValue.id });+ },+});++export const findClients = createAction({+ auth: invoiceninjaAuth,+ name: 'find_clients',+ classification: 'SEARCH',+ displayName: 'Find Clients',+ description: 'Search clients by text or exact contact email, one page at a time.',+ audience: 'ai',+ aiMetadata: {+ description: 'Searches Invoice Ninja clients. search matches name, number, contact names and emails; email matches a contact email exactly. Returns {items, page, perPage, total, hasMore}; request the next page while hasMore is true. Active clients only unless status says otherwise. Read-only.',+ idempotent: true,+ },+ outputSchema: invoiceNinjaOutputSchemas.clientList,+ props: {+ search: Property.ShortText({ displayName: 'Search', description: 'Free-text filter.', required: false }),+ email: Property.ShortText({ displayName: 'Contact Email', description: 'Exact contact email.', required: false }),+ status: entityActions.statusProp(),+ sort: entityActions.sortProp(),+ ...entityActions.listProps(),+ },+ async run({ auth, propsValue }) {+ return entityActions.runList({+ auth: auth.props,+ entity: 'clients',+ page: propsValue.page,+ perPage: propsValue.per_page,+ query: {+ filter: invoiceNinjaClient.optionalText(propsValue.search),+ email: invoiceNinjaClient.optionalText(propsValue.email),+ status: propsValue.status,+ sort: propsValue.sort,+ },+ });+ },+});++export const updateClient = createAction({+ auth: invoiceninjaAuth,+ name: 'update_client',+ classification: 'WRITE',+ displayName: 'Update Client',+ description: 'Change fields of an existing client. Empty fields are left unchanged.',+ audience: 'ai',+ aiMetadata: {+ description: 'Updates an Invoice Ninja client by ID. Only fields you pass are changed; list field names in clear_fields to blank them. Contacts are not changed here. Returns the updated client. Idempotent: repeating the same update gives the same result.',+ idempotent: true,+ },+ outputSchema: invoiceNinjaOutputSchemas.client,+ props: {+ client_id: Property.ShortText({ displayName: 'Client ID', required: true }),+ name: Property.ShortText({ displayName: 'Name', required: false }),+ website: Property.ShortText({ displayName: 'Website', required: false }),+ phone: Property.ShortText({ displayName: 'Phone', required: false }),+ vat_number: Property.ShortText({ displayName: 'VAT Number', required: false }),+ id_number: Property.ShortText({ displayName: 'ID Number', required: false }),+ address1: Property.ShortText({ displayName: 'Address Line 1', required: false }),+ address2: Property.ShortText({ displayName: 'Address Line 2', required: false }),+ city: Property.ShortText({ displayName: 'City', required: false }),+ state: Property.ShortText({ displayName: 'State', required: false }),+ postal_code: Property.ShortText({ displayName: 'Postal Code', required: false }),+ public_notes: Property.LongText({ displayName: 'Public Notes', required: false }),+ private_notes: Property.LongText({ displayName: 'Private Notes', required: false }),+ clear_fields: invoiceNinjaProps.clearProp({ fields: CLEARABLE }),+ },+ async run({ auth, propsValue }) {+ const id = invoiceNinjaClient.parseId({ value: propsValue.client_id, label: 'Client ID' });+ const set = invoiceNinjaClient.compact({+ name: invoiceNinjaClient.optionalText(propsValue.name),+ ...Object.fromEntries(CLEARABLE.map((field) => [field, invoiceNinjaClient.optionalText(propsValue[field])])),+ });+ const body = { ...invoiceNinjaClient.clearedFields({ value: propsValue.clear_fields, allowed: CLEARABLE }), ...set };+ if (Object.keys(body).length === 0) {+ throw new Error('Nothing to update: give at least one field or clear_fields.');+ }+ return invoiceNinjaClient.recordOf(+ await invoiceNinjaClient.request({ auth: auth.props, method: HttpMethod.PUT, path: `/clients/${id}`, body }),+ );+ },+});++export const archiveClient = createAction({+ auth: invoiceninjaAuth,+ name: 'archive_client',+ classification: 'DESTRUCTIVE',+ displayName: 'Archive Client',+ description: 'Archive a client (hidden from lists, can be restored).',+ audience: 'ai',+ aiMetadata: {+ description: 'Archives an Invoice Ninja client by ID; it disappears from active lists and can be brought back with Restore Client. Returns the client. Idempotent.',+ idempotent: true,+ },+ outputSchema: invoiceNinjaOutputSchemas.client,+ props: { id: entityActions.bulkIdProp('Client') },+ async run({ auth, propsValue }) {+ return entityActions.runBulk({ auth: auth.props, entity: 'clients', label: 'Client', action: 'archive', id: propsValue.id });+ },+});++export const restoreClient = createAction({+ auth: invoiceninjaAuth,+ name: 'restore_client',+ classification: 'WRITE',+ displayName: 'Restore Client',+ description: 'Restore an archived or deleted client.',+ audience: 'ai',+ aiMetadata: {+ description: 'Restores an archived or deleted Invoice Ninja client by ID back to active. Returns the client. Idempotent.',+ idempotent: true,+ },+ outputSchema: invoiceNinjaOutputSchemas.client,+ props: { id: entityActions.bulkIdProp('Client') },+ async run({ auth, propsValue }) {+ return entityActions.runBulk({ auth: auth.props, entity: 'clients', label: 'Client', action: 'restore', id: propsValue.id });+ },+});++export const deleteClient = createAction({+ auth: invoiceninjaAuth,+ name: 'delete_client',+ classification: 'DESTRUCTIVE',+ displayName: 'Delete Client',+ description: 'Delete a client (soft delete, can be restored).',+ audience: 'ai',+ aiMetadata: {+ description: 'Deletes an Invoice Ninja client by ID (soft delete: is_deleted becomes true; its existing invoices are not deleted). Can be undone with Restore Client. Returns the client. Ask the user before calling.',+ idempotent: false,+ },+ outputSchema: invoiceNinjaOutputSchemas.client,+ props: { id: entityActions.bulkIdProp('Client') },+ async run({ auth, propsValue }) {+ return entityActions.runBulk({ auth: auth.props, entity: 'clients', label: 'Client', action: 'delete', id: propsValue.id });+ },+});diff --git a/packages/pieces/community/invoiceninja/src/lib/actions/ai/credits-products.ts b/packages/pieces/community/invoiceninja/src/lib/actions/ai/credits-products.tsnew file mode 100644index 00000000000..82ee7ca4c2f--- /dev/null+++ b/packages/pieces/community/invoiceninja/src/lib/actions/ai/credits-products.ts@@ -0,0 +1,211 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { invoiceninjaAuth } from '../../common/auth';+import { invoiceNinjaClient } from '../../common/client';+import { entityActions } from '../../common/entity-actions';+import { invoiceNinjaOutputSchemas } from '../../common/output-schemas';+import { invoiceNinjaProps } from '../../common/props';++const PRODUCT_CLEARABLE = ['notes', 'tax_name1'] as const;++export const getCredit = createAction({+ auth: invoiceninjaAuth,+ name: 'get_credit',+ classification: 'READ',+ displayName: 'Get Credit',+ description: 'Get one credit by its ID.',+ audience: 'ai',+ aiMetadata: {+ description: 'Returns one Invoice Ninja credit note by ID with amount, remaining balance and line items. Read-only.',+ idempotent: true,+ },+ outputSchema: invoiceNinjaOutputSchemas.credit,+ props: { id: entityActions.getIdProp('Credit') },+ async run({ auth, propsValue }) {+ return entityActions.runGet({ auth: auth.props, entity: 'credits', label: 'Credit', id: propsValue.id });+ },+});++export const listCredits = createAction({+ auth: invoiceninjaAuth,+ name: 'list_credits',+ classification: 'SEARCH',+ displayName: 'List Credits',+ description: 'List credit notes, one page at a time.',+ audience: 'ai',+ aiMetadata: {+ description: 'Lists Invoice Ninja credit notes, optionally for one client and by free-text search. Returns {items, page, perPage, total, hasMore}. Read-only.',+ idempotent: true,+ },+ outputSchema: invoiceNinjaOutputSchemas.creditList,+ props: {+ client_id: Property.ShortText({ displayName: 'Client ID', required: false }),+ search: Property.ShortText({ displayName: 'Search', required: false }),+ status: entityActions.statusProp(),+ ...entityActions.listProps(),+ },+ async run({ auth, propsValue }) {+ return entityActions.runList({+ auth: auth.props,+ entity: 'credits',+ page: propsValue.page,+ perPage: propsValue.per_page,+ query: {+ client_id: invoiceNinjaClient.optionalId({ value: propsValue.client_id, label: 'Client ID' }),+ filter: invoiceNinjaClient.optionalText(propsValue.search),+ status: propsValue.status,+ },+ });+ },+});++export const createCredit = createAction({+ auth: invoiceninjaAuth,+ name: 'create_credit',+ classification: 'WRITE',+ displayName: 'Create Credit',+ description: 'Create a draft credit note for a client from line items.',+ audience: 'ai',+ aiMetadata: {+ description: 'Creates a draft Invoice Ninja credit note for client_id from line_items (product_key and/or notes, cost, quantity). It can later be applied to invoices in Invoice Ninja. Not idempotent: each call creates a new credit.',+ idempotent: false,+ },+ outputSchema: invoiceNinjaOutputSchemas.credit,+ props: {+ client_id: Property.ShortText({ displayName: 'Client ID', required: true }),+ line_items: invoiceNinjaProps.lineItems({ required: true }),+ ...invoiceNinjaProps.documentProps(),+ },+ async run({ auth, propsValue }) {+ const body = {+ ...invoiceNinjaProps.documentBody(propsValue),+ client_id: invoiceNinjaClient.parseId({ value: propsValue.client_id, label: 'Client ID' }),+ line_items: invoiceNinjaClient.lineItemsOf({ value: propsValue.line_items, label: 'Line Items', required: true, isAmountDiscount: invoiceNinjaClient.parseBoolean(propsValue.is_amount_discount) }),+ };+ return invoiceNinjaClient.recordOf(+ await invoiceNinjaClient.request({ auth: auth.props, method: HttpMethod.POST, path: '/credits', body }),+ );+ },+});++export const getProduct = createAction({+ auth: invoiceninjaAuth,+ name: 'get_product',+ classification: 'READ',+ displayName: 'Get Product',+ description: 'Get one product by its ID.',+ audience: 'ai',+ aiMetadata: {+ description: 'Returns one Invoice Ninja product by ID: product key, description, price, cost and tax. Read-only.',+ idempotent: true,+ },+ outputSchema: invoiceNinjaOutputSchemas.product,+ props: { id: entityActions.getIdProp('Product') },+ async run({ auth, propsValue }) {+ return entityActions.runGet({ auth: auth.props, entity: 'products', label: 'Product', id: propsValue.id });+ },+});++export const listProducts = createAction({+ auth: invoiceninjaAuth,+ name: 'list_products',+ classification: 'SEARCH',+ displayName: 'List Products',+ description: 'List or search products, one page at a time.',+ audience: 'ai',+ aiMetadata: {+ description: 'Lists Invoice Ninja products; search matches product key and description. Returns {items, page, perPage, total, hasMore}. Use the returned price/notes to build invoice line items. Read-only.',+ idempotent: true,+ },+ outputSchema: invoiceNinjaOutputSchemas.productList,+ props: {+ search: Property.ShortText({ displayName: 'Search', required: false }),+ status: entityActions.statusProp(),+ ...entityActions.listProps(),+ },+ async run({ auth, propsValue }) {+ return entityActions.runList({+ auth: auth.props,+ entity: 'products',+ page: propsValue.page,+ perPage: propsValue.per_page,+ query: { filter: invoiceNinjaClient.optionalText(propsValue.search), status: propsValue.status },+ });+ },+});++export const createProduct = createAction({+ auth: invoiceninjaAuth,+ name: 'create_product',+ classification: 'WRITE',+ displayName: 'Create Product',+ description: 'Create a product.',+ audience: 'ai',+ aiMetadata: {+ description: 'Creates an Invoice Ninja product with a product_key (its name/SKU), description, price and optional cost and tax. Product keys are not forced unique, so check List Products first. Not idempotent.',+ idempotent: false,+ },+ outputSchema: invoiceNinjaOutputSchemas.product,+ props: productProps({ forCreate: true }),+ async run({ auth, propsValue }) {+ const body = productBody(propsValue);+ if (body['product_key'] === undefined) throw new Error('Product Key is required.');+ return invoiceNinjaClient.recordOf(+ await invoiceNinjaClient.request({ auth: auth.props, method: HttpMethod.POST, path: '/products', body }),+ );+ },+});++export const updateProduct = createAction({+ auth: invoiceninjaAuth,+ name: 'update_product',+ classification: 'WRITE',+ displayName: 'Update Product',+ description: 'Change fields of a product. Empty fields are left unchanged.',+ audience: 'ai',+ aiMetadata: {+ description: 'Updates an Invoice Ninja product by ID. Only fields you pass change; clear_fields blanks the listed ones. Existing invoices are not changed. Idempotent.',+ idempotent: true,+ },+ outputSchema: invoiceNinjaOutputSchemas.product,+ props: {+ product_id: Property.ShortText({ displayName: 'Product ID', required: true }),+ ...productProps({ forCreate: false }),+ clear_fields: invoiceNinjaProps.clearProp({ fields: PRODUCT_CLEARABLE }),+ },+ async run({ auth, propsValue }) {+ const id = invoiceNinjaClient.parseId({ value: propsValue.product_id, label: 'Product ID' });+ const body = {+ ...invoiceNinjaClient.clearedFields({ value: propsValue.clear_fields, allowed: PRODUCT_CLEARABLE }),+ ...productBody(propsValue),+ };+ if (Object.keys(body).length === 0) throw new Error('Nothing to update: give at least one field or clear_fields.');+ return invoiceNinjaClient.recordOf(+ await invoiceNinjaClient.request({ auth: auth.props, method: HttpMethod.PUT, path: `/products/${id}`, body }),+ );+ },+});++function productProps({ forCreate }: { forCreate: boolean }) {+ return {+ product_key: Property.ShortText({ displayName: 'Product Key', description: 'Product name or SKU.', required: forCreate }),+ notes: Property.LongText({ displayName: 'Description', required: false }),+ price: Property.Number({ displayName: 'Price', required: false }),+ cost: Property.Number({ displayName: 'Cost', description: 'Your purchase cost.', required: false }),+ quantity: Property.Number({ displayName: 'Default Quantity', required: false }),+ tax_name1: Property.ShortText({ displayName: 'Tax Name', required: false }),+ tax_rate1: Property.Number({ displayName: 'Tax Rate (%)', required: false }),+ };+}++function productBody(props: Record<string, unknown>): Record<string, unknown> {+ return invoiceNinjaClient.compact({+ product_key: invoiceNinjaClient.optionalText(props['product_key']),+ notes: invoiceNinjaClient.optionalText(props['notes']),+ price: invoiceNinjaClient.optionalNumber({ value: props['price'], label: 'Price' }),+ cost: invoiceNinjaClient.optionalNumber({ value: props['cost'], label: 'Cost' }),+ quantity: invoiceNinjaClient.optionalNumber({ value: props['quantity'], label: 'Default Quantity', min: 0 }),+ tax_name1: invoiceNinjaClient.optionalText(props['tax_name1']),+ tax_rate1: invoiceNinjaClient.optionalNumber({ value: props['tax_rate1'], label: 'Tax Rate', min: 0, max: 100 }),+ });+}diff --git a/packages/pieces/community/invoiceninja/src/lib/actions/ai/expenses-projects-vendors.ts b/packages/pieces/community/invoiceninja/src/lib/actions/ai/expenses-projects-vendors.tsnew file mode 100644index 00000000000..33d3294f8a2--- /dev/null+++ b/packages/pieces/community/invoiceninja/src/lib/actions/ai/expenses-projects-vendors.ts@@ -0,0 +1,294 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { invoiceninjaAuth } from '../../common/auth';+import { invoiceNinjaClient } from '../../common/client';+import { entityActions } from '../../common/entity-actions';+import { invoiceNinjaOutputSchemas } from '../../common/output-schemas';++export const getExpense = createAction({+ auth: invoiceninjaAuth,+ name: 'get_expense',+ classification: 'READ',+ displayName: 'Get Expense',+ description: 'Get one expense by its ID.',+ audience: 'ai',+ aiMetadata: {+ description: 'Returns one Invoice Ninja expense by ID: amount, date, vendor, client, project and whether it should be invoiced. Read-only.',+ idempotent: true,+ },+ outputSchema: invoiceNinjaOutputSchemas.expense,+ props: { id: entityActions.getIdProp('Expense') },+ async run({ auth, propsValue }) {+ return entityActions.runGet({ auth: auth.props, entity: 'expenses', label: 'Expense', id: propsValue.id });+ },+});++export const listExpenses = createAction({+ auth: invoiceninjaAuth,+ name: 'list_expenses',+ classification: 'SEARCH',+ displayName: 'List Expenses',+ description: 'List expenses, one page at a time.',+ audience: 'ai',+ aiMetadata: {+ description: 'Lists Invoice Ninja expenses, optionally for one client or vendor and by free-text search. Returns {items, page, perPage, total, hasMore}. Read-only.',+ idempotent: true,+ },+ outputSchema: invoiceNinjaOutputSchemas.expenseList,+ props: {+ client_id: Property.ShortText({ displayName: 'Client ID', required: false }),+ vendor_id: Property.ShortText({ displayName: 'Vendor ID', required: false }),+ search: Property.ShortText({ displayName: 'Search', required: false }),+ status: entityActions.statusProp(),+ sort: entityActions.sortProp(),+ ...entityActions.listProps(),+ },+ async run({ auth, propsValue }) {+ return entityActions.runList({+ auth: auth.props,+ entity: 'expenses',+ page: propsValue.page,+ perPage: propsValue.per_page,+ query: {+ client_id: invoiceNinjaClient.optionalId({ value: propsValue.client_id, label: 'Client ID' }),+ vendor_id: invoiceNinjaClient.optionalId({ value: propsValue.vendor_id, label: 'Vendor ID' }),+ filter: invoiceNinjaClient.optionalText(propsValue.search),+ status: propsValue.status,+ sort: propsValue.sort,+ },+ });+ },+});++export const createExpense = createAction({+ auth: invoiceninjaAuth,+ name: 'create_expense',+ classification: 'WRITE',+ displayName: 'Create Expense',+ description: 'Record an expense, optionally for a client, vendor or project.',+ audience: 'ai',+ aiMetadata: {+ description: 'Records an Invoice Ninja expense of amount on date (YYYY-MM-DD, default today), optionally linked to a vendor, a client and a project, with should_be_invoiced to bill it to the client later. Not idempotent.',+ idempotent: false,+ },+ outputSchema: invoiceNinjaOutputSchemas.expense,+ props: {+ amount: Property.Number({ displayName: 'Amount', required: true }),+ date: Property.ShortText({ displayName: 'Date', description: 'YYYY-MM-DD. Default today.', required: false }),+ vendor_id: Property.ShortText({ displayName: 'Vendor ID', required: false }),+ client_id: Property.ShortText({ displayName: 'Client ID', required: false }),+ project_id: Property.ShortText({ displayName: 'Project ID', required: false }),+ category_id: Property.ShortText({ displayName: 'Expense Category ID', required: false }),+ should_be_invoiced: Property.Checkbox({ displayName: 'Should Be Invoiced', required: false }),+ transaction_reference: Property.ShortText({ displayName: 'Transaction Reference', required: false }),+ public_notes: Property.LongText({ displayName: 'Public Notes', required: false }),+ private_notes: Property.LongText({ displayName: 'Private Notes', required: false }),+ },+ async run({ auth, propsValue }) {+ const amount = invoiceNinjaClient.optionalNumber({ value: propsValue.amount, label: 'Amount', min: 0 });+ if (amount === undefined) throw new Error('Amount is required.');+ const body = invoiceNinjaClient.compact({+ amount,+ date: invoiceNinjaClient.toDateOnly({ value: propsValue.date, label: 'Date' }) ?? new Date().toISOString().slice(0, 10),+ vendor_id: invoiceNinjaClient.optionalId({ value: propsValue.vendor_id, label: 'Vendor ID' }),+ client_id: invoiceNinjaClient.optionalId({ value: propsValue.client_id, label: 'Client ID' }),+ project_id: invoiceNinjaClient.optionalId({ value: propsValue.project_id, label: 'Project ID' }),+ category_id: invoiceNinjaClient.optionalId({ value: propsValue.category_id, label: 'Expense Category ID' }),+ should_be_invoiced: invoiceNinjaClient.parseBoolean(propsValue.should_be_invoiced),+ transaction_reference: invoiceNinjaClient.optionalText(propsValue.transaction_reference),+ public_notes: invoiceNinjaClient.optionalText(propsValue.public_notes),+ private_notes: invoiceNinjaClient.optionalText(propsValue.private_notes),+ });+ return invoiceNinjaClient.recordOf(+ await invoiceNinjaClient.request({ auth: auth.props, method: HttpMethod.POST, path: '/expenses', body }),+ );+ },+});++export const getProject = createAction({+ auth: invoiceninjaAuth,+ name: 'get_project',+ classification: 'READ',+ displayName: 'Get Project',+ description: 'Get one project by its ID.',+ audience: 'ai',+ aiMetadata: {+ description: 'Returns one Invoice Ninja project by ID: name, client, task rate, budgeted hours and due date. Read-only.',+ idempotent: true,+ },+ outputSchema: invoiceNinjaOutputSchemas.project,+ props: { id: entityActions.getIdProp('Project') },+ async run({ auth, propsValue }) {+ return entityActions.runGet({ auth: auth.props, entity: 'projects', label: 'Project', id: propsValue.id });+ },+});++export const listProjects = createAction({+ auth: invoiceninjaAuth,+ name: 'list_projects',+ classification: 'SEARCH',+ displayName: 'List Projects',+ description: 'List projects, one page at a time.',+ audience: 'ai',+ aiMetadata: {+ description: 'Lists Invoice Ninja projects, optionally for one client and by free-text search on the name. Returns {items, page, perPage, total, hasMore}. Read-only.',+ idempotent: true,+ },+ outputSchema: invoiceNinjaOutputSchemas.projectList,+ props: {+ client_id: Property.ShortText({ displayName: 'Client ID', required: false }),+ search: Property.ShortText({ displayName: 'Search', required: false }),+ status: entityActions.statusProp(),+ ...entityActions.listProps(),+ },+ async run({ auth, propsValue }) {+ return entityActions.runList({+ auth: auth.props,+ entity: 'projects',+ page: propsValue.page,+ perPage: propsValue.per_page,+ query: {+ client_id: invoiceNinjaClient.optionalId({ value: propsValue.client_id, label: 'Client ID' }),+ filter: invoiceNinjaClient.optionalText(propsValue.search),+ status: propsValue.status,+ },+ });+ },+});++export const createProject = createAction({+ auth: invoiceninjaAuth,+ name: 'create_project',+ classification: 'WRITE',+ displayName: 'Create Project',+ description: 'Create a project for a client.',+ audience: 'ai',+ aiMetadata: {+ description: 'Creates an Invoice Ninja project named name for client_id, with optional hourly task_rate, budgeted_hours and due_date (YYYY-MM-DD). Tasks can then be logged against it. Not idempotent.',+ idempotent: false,+ },+ outputSchema: invoiceNinjaOutputSchemas.project,+ props: {+ name: Property.ShortText({ displayName: 'Name', required: true }),+ client_id: Property.ShortText({ displayName: 'Client ID', required: true }),+ task_rate: Property.Number({ displayName: 'Task Rate', description: 'Hourly rate for tasks of this project.', required: false }),+ budgeted_hours: Property.Number({ displayName: 'Budgeted Hours', required: false }),+ due_date: Property.ShortText({ displayName: 'Due Date', description: 'YYYY-MM-DD.', required: false }),+ public_notes: Property.LongText({ displayName: 'Public Notes', required: false }),+ private_notes: Property.LongText({ displayName: 'Private Notes', required: false }),+ },+ async run({ auth, propsValue }) {+ const name = invoiceNinjaClient.optionalText(propsValue.name);+ if (name === undefined) throw new Error('Name is required.');+ const body = invoiceNinjaClient.compact({+ name,+ client_id: invoiceNinjaClient.parseId({ value: propsValue.client_id, label: 'Client ID' }),+ task_rate: invoiceNinjaClient.optionalNumber({ value: propsValue.task_rate, label: 'Task Rate', min: 0 }),+ budgeted_hours: invoiceNinjaClient.optionalNumber({ value: propsValue.budgeted_hours, label: 'Budgeted Hours', min: 0 }),+ due_date: invoiceNinjaClient.toDateOnly({ value: propsValue.due_date, label: 'Due Date' }),+ public_notes: invoiceNinjaClient.optionalText(propsValue.public_notes),+ private_notes: invoiceNinjaClient.optionalText(propsValue.private_notes),+ });+ return invoiceNinjaClient.recordOf(+ await invoiceNinjaClient.request({ auth: auth.props, method: HttpMethod.POST, path: '/projects', body }),+ );+ },+});++export const getVendor = createAction({+ auth: invoiceninjaAuth,+ name: 'get_vendor',+ classification: 'READ',+ displayName: 'Get Vendor',+ description: 'Get one vendor by its ID.',+ audience: 'ai',+ aiMetadata: {+ description: 'Returns one Invoice Ninja vendor (supplier) by ID with address and contacts. Read-only.',+ idempotent: true,+ },+ outputSchema: invoiceNinjaOutputSchemas.vendor,+ props: { id: entityActions.getIdProp('Vendor') },+ async run({ auth, propsValue }) {+ return entityActions.runGet({ auth: auth.props, entity: 'vendors', label: 'Vendor', id: propsValue.id });+ },+});++export const listVendors = createAction({+ auth: invoiceninjaAuth,+ name: 'list_vendors',+ classification: 'SEARCH',+ displayName: 'List Vendors',+ description: 'List or search vendors, one page at a time.',+ audience: 'ai',+ aiMetadata: {+ description: 'Lists Invoice Ninja vendors (suppliers); search matches name, number and contacts. Returns {items, page, perPage, total, hasMore}. Read-only.',+ idempotent: true,+ },+ outputSchema: invoiceNinjaOutputSchemas.vendorList,+ props: {+ search: Property.ShortText({ displayName: 'Search', required: false }),+ status: entityActions.statusProp(),+ ...entityActions.listProps(),+ },+ async run({ auth, propsValue }) {+ return entityActions.runList({+ auth: auth.props,+ entity: 'vendors',+ page: propsValue.page,+ perPage: propsValue.per_page,+ query: { filter: invoiceNinjaClient.optionalText(propsValue.search), status: propsValue.status },+ });+ },+});++export const createVendor = createAction({+ auth: invoiceninjaAuth,+ name: 'create_vendor',+ classification: 'WRITE',+ displayName: 'Create Vendor',+ description: 'Create a vendor (supplier) with an optional contact.',+ audience: 'ai',+ aiMetadata: {+ description: 'Creates an Invoice Ninja vendor (supplier) named name with optional address, website, VAT number and one contact (contact_first_name, contact_last_name, contact_email, contact_phone). Not idempotent.',+ idempotent: false,+ },+ outputSchema: invoiceNinjaOutputSchemas.vendor,+ props: {+ name: Property.ShortText({ displayName: 'Name', required: true }),+ website: Property.ShortText({ displayName: 'Website', required: false }),+ phone: Property.ShortText({ displayName: 'Phone', required: false }),+ vat_number: Property.ShortText({ displayName: 'VAT Number', required: false }),+ address1: Property.ShortText({ displayName: 'Address Line 1', required: false }),+ city: Property.ShortText({ displayName: 'City', required: false }),+ postal_code: Property.ShortText({ displayName: 'Postal Code', required: false }),+ contact_first_name: Property.ShortText({ displayName: 'Contact First Name', required: false }),+ contact_last_name: Property.ShortText({ displayName: 'Contact Last Name', required: false }),+ contact_email: Property.ShortText({ displayName: 'Contact Email', required: false }),+ contact_phone: Property.ShortText({ displayName: 'Contact Phone', required: false }),+ private_notes: Property.LongText({ displayName: 'Private Notes', required: false }),+ },+ async run({ auth, propsValue }) {+ const name = invoiceNinjaClient.optionalText(propsValue.name);+ if (name === undefined) throw new Error('Name is required.');+ const contact = invoiceNinjaClient.compact({+ first_name: invoiceNinjaClient.optionalText(propsValue.contact_first_name),+ last_name: invoiceNinjaClient.optionalText(propsValue.contact_last_name),+ email: invoiceNinjaClient.optionalText(propsValue.contact_email),+ phone: invoiceNinjaClient.optionalText(propsValue.contact_phone),+ });+ const body = invoiceNinjaClient.compact({+ name,+ website: invoiceNinjaClient.optionalText(propsValue.website),+ phone: invoiceNinjaClient.optionalText(propsValue.phone),+ vat_number: invoiceNinjaClient.optionalText(propsValue.vat_number),+ address1: invoiceNinjaClient.optionalText(propsValue.address1),+ city: invoiceNinjaClient.optionalText(propsValue.city),+ postal_code: invoiceNinjaClient.optionalText(propsValue.postal_code),+ private_notes: invoiceNinjaClient.optionalText(propsValue.private_notes),+ contacts: Object.keys(contact).length === 0 ? undefined : [contact],+ });+ return invoiceNinjaClient.recordOf(+ await invoiceNinjaClient.request({ auth: auth.props, method: HttpMethod.POST, path: '/vendors', body }),+ );+ },+});diff --git a/packages/pieces/community/invoiceninja/src/lib/actions/ai/invoices.ts b/packages/pieces/community/invoiceninja/src/lib/actions/ai/invoices.tsnew file mode 100644index 00000000000..79a9e6d0169--- /dev/null+++ b/packages/pieces/community/invoiceninja/src/lib/actions/ai/invoices.ts@@ -0,0 +1,247 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { invoiceninjaAuth } from '../../common/auth';+import { invoiceNinjaClient } from '../../common/client';+import { entityActions } from '../../common/entity-actions';+import { invoiceNinjaOutputSchemas } from '../../common/output-schemas';+import { invoiceNinjaProps } from '../../common/props';++const CLEARABLE = ['po_number', 'public_notes', 'private_notes', 'terms', 'due_date'] as const;++export const getInvoice = createAction({+ auth: invoiceninjaAuth,+ name: 'get_invoice',+ classification: 'READ',+ displayName: 'Get Invoice',+ description: 'Get one invoice by its ID.',+ audience: 'ai',+ aiMetadata: {+ description: 'Returns one Invoice Ninja invoice by its ID: status, amounts, balance, line items and client portal links. Read-only.',+ idempotent: true,+ },+ outputSchema: invoiceNinjaOutputSchemas.invoice,+ props: { id: entityActions.getIdProp('Invoice') },+ async run({ auth, propsValue }) {+ return entityActions.runGet({ auth: auth.props, entity: 'invoices', label: 'Invoice', id: propsValue.id });+ },+});++export const listInvoices = createAction({+ auth: invoiceninjaAuth,+ name: 'list_invoices',+ classification: 'SEARCH',+ displayName: 'List Invoices',+ description: 'List invoices with filters, one page at a time.',+ audience: 'ai',+ aiMetadata: {+ description: 'Lists Invoice Ninja invoices, optionally for one client, by payment state (paid, unpaid, overdue) and free-text search (number, PO, notes). Returns {items, page, perPage, total, hasMore}; ask for the next page while hasMore is true. Read-only.',+ idempotent: true,+ },+ outputSchema: invoiceNinjaOutputSchemas.invoiceList,+ props: {+ client_id: Property.ShortText({ displayName: 'Client ID', required: false }),+ payment_state: Property.StaticDropdown<string>({+ displayName: 'Payment State',+ required: false,+ options: {+ options: [+ { label: 'All', value: 'all' },+ { label: 'Draft', value: 'draft' },+ { label: 'Paid', value: 'paid' },+ { label: 'Unpaid', value: 'unpaid' },+ { label: 'Overdue', value: 'overdue' },+ ],+ },+ }),+ search: Property.ShortText({ displayName: 'Search', required: false }),+ status: entityActions.statusProp(),+ sort: entityActions.sortProp(),+ ...entityActions.listProps(),+ },+ async run({ auth, propsValue }) {+ return entityActions.runList({+ auth: auth.props,+ entity: 'invoices',+ page: propsValue.page,+ perPage: propsValue.per_page,+ query: {+ client_id: invoiceNinjaClient.optionalId({ value: propsValue.client_id, label: 'Client ID' }),+ client_status: propsValue.payment_state,+ filter: invoiceNinjaClient.optionalText(propsValue.search),+ status: propsValue.status,+ sort: propsValue.sort,+ },+ });+ },+});++export const createInvoiceAi = createAction({+ auth: invoiceninjaAuth,+ name: 'create_invoice_ai',+ classification: 'WRITE',+ displayName: 'Create Invoice (from line items)',+ description: 'Create a draft invoice for a client from explicit line items.',+ audience: 'ai',+ aiMetadata: {+ description: 'Creates a draft Invoice Ninja invoice for client_id with the given line_items (each: product_key and/or notes, cost, quantity, optional discount and tax). Dates are YYYY-MM-DD; date defaults to today. Does not send it: use Email Invoice or Mark Invoice Sent afterwards. Not idempotent: every call creates a new invoice.',+ idempotent: false,+ },+ outputSchema: invoiceNinjaOutputSchemas.invoice,+ props: {+ client_id: Property.ShortText({ displayName: 'Client ID', required: true }),+ line_items: invoiceNinjaProps.lineItems({ required: true }),+ ...invoiceNinjaProps.documentProps(),+ },+ async run({ auth, propsValue }) {+ const body = {+ ...invoiceNinjaProps.documentBody(propsValue),+ client_id: invoiceNinjaClient.parseId({ value: propsValue.client_id, label: 'Client ID' }),+ line_items: invoiceNinjaClient.lineItemsOf({ value: propsValue.line_items, label: 'Line Items', required: true, isAmountDiscount: invoiceNinjaClient.parseBoolean(propsValue.is_amount_discount) }),+ };+ return invoiceNinjaClient.recordOf(+ await invoiceNinjaClient.request({ auth: auth.props, method: HttpMethod.POST, path: '/invoices', body }),+ );+ },+});++export const updateInvoice = createAction({+ auth: invoiceninjaAuth,+ name: 'update_invoice',+ classification: 'WRITE',+ displayName: 'Update Invoice',+ description: 'Change fields of an invoice. Empty fields are left unchanged.',+ audience: 'ai',+ aiMetadata: {+ description: 'Updates an Invoice Ninja invoice by ID. Only fields you pass change; clear_fields blanks the listed ones. line_items, when given, REPLACES all existing lines. Returns the updated invoice. Idempotent.',+ idempotent: true,+ },+ outputSchema: invoiceNinjaOutputSchemas.invoice,+ props: {+ invoice_id: Property.ShortText({ displayName: 'Invoice ID', required: true }),+ line_items: invoiceNinjaProps.lineItems({ required: false }),+ ...invoiceNinjaProps.documentProps(),+ clear_fields: invoiceNinjaProps.clearProp({ fields: CLEARABLE }),+ },+ async run({ auth, propsValue }) {+ const id = invoiceNinjaClient.parseId({ value: propsValue.invoice_id, label: 'Invoice ID' });+ const body = invoiceNinjaClient.compact({+ ...invoiceNinjaClient.clearedFields({ value: propsValue.clear_fields, allowed: CLEARABLE }),+ ...invoiceNinjaProps.documentBody(propsValue),+ line_items: invoiceNinjaClient.lineItemsOf({ value: propsValue.line_items, label: 'Line Items', required: false, isAmountDiscount: invoiceNinjaClient.parseBoolean(propsValue.is_amount_discount) }),+ });+ if (Object.keys(body).length === 0) {+ throw new Error('Nothing to update: give at least one field or clear_fields.');+ }+ return invoiceNinjaClient.recordOf(+ await invoiceNinjaClient.request({ auth: auth.props, method: HttpMethod.PUT, path: `/invoices/${id}`, body }),+ );+ },+});++export const emailInvoice = createAction({+ auth: invoiceninjaAuth,+ name: 'email_invoice',+ classification: 'WRITE',+ displayName: 'Email Invoice',+ description: 'Email the invoice to the client\'s contacts and mark it sent.',+ audience: 'ai',+ aiMetadata: {+ description: 'Emails an Invoice Ninja invoice to the client contacts that receive email, using the company template, and marks a draft as sent. Not idempotent: each call sends another email.',+ idempotent: false,+ },+ outputSchema: invoiceNinjaOutputSchemas.invoice,+ props: { id: entityActions.bulkIdProp('Invoice') },+ async run({ auth, propsValue }) {+ return entityActions.runBulk({ auth: auth.props, entity: 'invoices', label: 'Invoice', action: 'email', id: propsValue.id });+ },+});++export const markInvoiceSent = createAction({+ auth: invoiceninjaAuth,+ name: 'mark_invoice_sent',+ classification: 'WRITE',+ displayName: 'Mark Invoice Sent',+ description: 'Mark a draft invoice as sent without emailing it.',+ audience: 'ai',+ aiMetadata: {+ description: 'Marks an Invoice Ninja draft invoice as sent (status 2) without sending email, which makes its balance due. Idempotent.',+ idempotent: true,+ },+ outputSchema: invoiceNinjaOutputSchemas.invoice,+ props: { id: entityActions.bulkIdProp('Invoice') },+ async run({ auth, propsValue }) {+ return entityActions.runBulk({ auth: auth.props, entity: 'invoices', label: 'Invoice', action: 'mark_sent', id: propsValue.id });+ },+});++export const markInvoicePaid = createAction({+ auth: invoiceninjaAuth,+ name: 'mark_invoice_paid',+ classification: 'WRITE',+ displayName: 'Mark Invoice Paid',+ description: 'Record a payment for the full balance and mark the invoice paid.',+ audience: 'ai',+ aiMetadata: {+ description: 'Marks an Invoice Ninja invoice as paid by creating a manual payment for its whole remaining balance (status 4). Use Create Payment for partial amounts. Calling it on an invoice that is already paid fails with "cannot be marked as paid" and creates nothing.',+ idempotent: false,+ },+ outputSchema: invoiceNinjaOutputSchemas.invoice,+ props: { id: entityActions.bulkIdProp('Invoice') },+ async run({ auth, propsValue }) {+ return entityActions.runBulk({ auth: auth.props, entity: 'invoices', label: 'Invoice', action: 'mark_paid', id: propsValue.id });+ },+});++export const archiveInvoice = createAction({+ auth: invoiceninjaAuth,+ name: 'archive_invoice',+ classification: 'DESTRUCTIVE',+ displayName: 'Archive Invoice',+ description: 'Archive an invoice (can be restored).',+ audience: 'ai',+ aiMetadata: {+ description: 'Archives an Invoice Ninja invoice by ID; restore it with Restore Invoice. Idempotent.',+ idempotent: true,+ },+ outputSchema: invoiceNinjaOutputSchemas.invoice,+ props: { id: entityActions.bulkIdProp('Invoice') },+ async run({ auth, propsValue }) {+ return entityActions.runBulk({ auth: auth.props, entity: 'invoices', label: 'Invoice', action: 'archive', id: propsValue.id });+ },+});++export const restoreInvoice = createAction({+ auth: invoiceninjaAuth,+ name: 'restore_invoice',+ classification: 'WRITE',+ displayName: 'Restore Invoice',+ description: 'Restore an archived or deleted invoice.',+ audience: 'ai',+ aiMetadata: {+ description: 'Restores an archived or deleted Invoice Ninja invoice by ID back to active. Idempotent.',+ idempotent: true,+ },+ outputSchema: invoiceNinjaOutputSchemas.invoice,+ props: { id: entityActions.bulkIdProp('Invoice') },+ async run({ auth, propsValue }) {+ return entityActions.runBulk({ auth: auth.props, entity: 'invoices', label: 'Invoice', action: 'restore', id: propsValue.id });+ },+});++export const deleteInvoice = createAction({+ auth: invoiceninjaAuth,+ name: 'delete_invoice',+ classification: 'DESTRUCTIVE',+ displayName: 'Delete Invoice',+ description: 'Delete an invoice (soft delete).',+ audience: 'ai',+ aiMetadata: {+ description: 'Deletes an Invoice Ninja invoice by ID (soft delete, is_deleted true). Restore Invoice brings it back. Ask the user before calling. Deleting an already deleted invoice fails.',+ idempotent: false,+ },+ outputSchema: invoiceNinjaOutputSchemas.invoice,+ props: { id: entityActions.bulkIdProp('Invoice') },+ async run({ auth, propsValue }) {+ return entityActions.runBulk({ auth: auth.props, entity: 'invoices', label: 'Invoice', action: 'delete', id: propsValue.id });+ },+});diff --git a/packages/pieces/community/invoiceninja/src/lib/actions/ai/payments.ts b/packages/pieces/community/invoiceninja/src/lib/actions/ai/payments.tsnew file mode 100644index 00000000000..9cecfe77a34--- /dev/null+++ b/packages/pieces/community/invoiceninja/src/lib/actions/ai/payments.ts@@ -0,0 +1,186 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { invoiceninjaAuth } from '../../common/auth';+import { invoiceNinjaClient } from '../../common/client';+import { entityActions } from '../../common/entity-actions';+import { invoiceNinjaOutputSchemas } from '../../common/output-schemas';++export const getPayment = createAction({+ auth: invoiceninjaAuth,+ name: 'get_payment',+ classification: 'READ',+ displayName: 'Get Payment',+ description: 'Get one payment by its ID.',+ audience: 'ai',+ aiMetadata: {+ description: 'Returns one Invoice Ninja payment by ID with amount, refunded amount and the invoices it is applied to. Read-only.',+ idempotent: true,+ },+ outputSchema: invoiceNinjaOutputSchemas.payment,+ props: { id: entityActions.getIdProp('Payment') },+ async run({ auth, propsValue }) {+ return entityActions.runGet({ auth: auth.props, entity: 'payments', label: 'Payment', id: propsValue.id });+ },+});++export const listPayments = createAction({+ auth: invoiceninjaAuth,+ name: 'list_payments',+ classification: 'SEARCH',+ displayName: 'List Payments',+ description: 'List payments, one page at a time.',+ audience: 'ai',+ aiMetadata: {+ description: 'Lists Invoice Ninja payments, optionally for one client and by free-text search (number, reference). Returns {items, page, perPage, total, hasMore}. Read-only.',+ idempotent: true,+ },+ outputSchema: invoiceNinjaOutputSchemas.paymentList,+ props: {+ client_id: Property.ShortText({ displayName: 'Client ID', required: false }),+ search: Property.ShortText({ displayName: 'Search', required: false }),+ status: entityActions.statusProp(),+ sort: entityActions.sortProp(),+ ...entityActions.listProps(),+ },+ async run({ auth, propsValue }) {+ return entityActions.runList({+ auth: auth.props,+ entity: 'payments',+ page: propsValue.page,+ perPage: propsValue.per_page,+ query: {+ client_id: invoiceNinjaClient.optionalId({ value: propsValue.client_id, label: 'Client ID' }),+ filter: invoiceNinjaClient.optionalText(propsValue.search),+ status: propsValue.status,+ sort: propsValue.sort,+ },+ });+ },+});++export const createPayment = createAction({+ auth: invoiceninjaAuth,+ name: 'create_payment',+ classification: 'WRITE',+ displayName: 'Create Payment',+ description: 'Record a manual payment from a client, optionally applied to an invoice.',+ audience: 'ai',+ aiMetadata: {+ description: 'Records a manual payment for client_id in Invoice Ninja. With invoice_id the whole amount is applied to that invoice (it must not exceed the invoice balance); without it the amount becomes unapplied client credit. date is YYYY-MM-DD (default today). Not idempotent: each call records another payment.',+ idempotent: false,+ },+ outputSchema: invoiceNinjaOutputSchemas.payment,+ props: {+ client_id: Property.ShortText({ displayName: 'Client ID', required: true }),+ amount: Property.Number({ displayName: 'Amount', required: true }),+ invoice_id: Property.ShortText({ displayName: 'Invoice ID', description: 'Apply the payment to this invoice.', required: false }),+ date: Property.ShortText({ displayName: 'Date', description: 'YYYY-MM-DD. Default today.', required: false }),+ transaction_reference: Property.ShortText({ displayName: 'Transaction Reference', required: false }),+ private_notes: Property.LongText({ displayName: 'Private Notes', required: false }),+ },+ async run({ auth, propsValue }) {+ const amount = invoiceNinjaClient.optionalNumber({ value: propsValue.amount, label: 'Amount', min: 0.01 });+ if (amount === undefined) throw new Error('Amount is required.');+ const invoiceId = invoiceNinjaClient.optionalId({ value: propsValue.invoice_id, label: 'Invoice ID' });+ const body = invoiceNinjaClient.compact({+ client_id: invoiceNinjaClient.parseId({ value: propsValue.client_id, label: 'Client ID' }),+ amount,+ date: invoiceNinjaClient.toDateOnly({ value: propsValue.date, label: 'Date' }),+ transaction_reference: invoiceNinjaClient.optionalText(propsValue.transaction_reference),+ private_notes: invoiceNinjaClient.optionalText(propsValue.private_notes),+ invoices: invoiceId === undefined ? undefined : [{ invoice_id: invoiceId, amount }],+ });+ return invoiceNinjaClient.recordOf(+ await invoiceNinjaClient.request({ auth: auth.props, method: HttpMethod.POST, path: '/payments', body }),+ );+ },+});++export const refundPayment = createAction({+ auth: invoiceninjaAuth,+ name: 'refund_payment',+ classification: 'DESTRUCTIVE',+ displayName: 'Refund Payment',+ description: 'Record a refund of a payment in Invoice Ninja (no money is moved at a payment gateway).',+ audience: 'ai',+ aiMetadata: {+ description: 'Records a refund on an Invoice Ninja payment: amount (default: everything not yet refunded) is taken back from the invoices the payment was applied to, oldest allocation first, and their balances reopen. If part of the payment is unapplied credit, refund the invoice part first; the call fails with the amounts to use, and a second call refunds the credit. It never refunds through a payment gateway and sends no email. Not idempotent: each call refunds again until nothing is left.',+ idempotent: false,+ },+ outputSchema: invoiceNinjaOutputSchemas.payment,+ props: {+ payment_id: Property.ShortText({ displayName: 'Payment ID', required: true }),+ amount: Property.Number({ displayName: 'Amount', description: 'Default: the whole unrefunded amount.', required: false }),+ },+ async run({ auth, propsValue }) {+ const id = invoiceNinjaClient.parseId({ value: propsValue.payment_id, label: 'Payment ID' });+ const payment = await invoiceNinjaClient.getRecord({ auth: auth.props, entity: 'payments', id });+ const paid = numberOf(payment['amount']);+ const refunded = numberOf(payment['refunded']);+ const available = round(paid - refunded);+ const amount = invoiceNinjaClient.optionalNumber({ value: propsValue.amount, label: 'Amount', min: 0.01 }) ?? available;+ if (available <= 0) throw new Error(`Payment ${id} is already fully refunded.`);+ if (amount > available) throw new Error(`Amount ${amount} is more than the refundable ${available} of payment ${id}.`);+ const invoices = allocate({ paymentables: invoiceNinjaClient.arrayOf(payment['paymentables']), amount });+ const allocated = round(invoices.reduce((sum, row) => sum + row.amount, 0));+ if (invoices.length > 0 && allocated < amount) {+ throw new Error(+ `Payment ${id} has only ${allocated} left on its invoices; the other ${round(available - allocated)} is unapplied credit. Refund ${allocated} first, then call again for the credit.`,+ );+ }+ const body = invoiceNinjaClient.compact({+ id,+ amount,+ date: new Date().toISOString().slice(0, 10),+ gateway_refund: false,+ send_email: false,+ invoices: invoices.length > 0 ? invoices : undefined,+ });+ return invoiceNinjaClient.recordOf(+ await invoiceNinjaClient.request({ auth: auth.props, method: HttpMethod.POST, path: '/payments/refund', body }),+ );+ },+});++export const deletePayment = createAction({+ auth: invoiceninjaAuth,+ name: 'delete_payment',+ classification: 'DESTRUCTIVE',+ displayName: 'Delete Payment',+ description: 'Delete a payment (reopens the invoices it paid).',+ audience: 'ai',+ aiMetadata: {+ description: 'Deletes an Invoice Ninja payment by ID (soft delete); invoices it paid get their balance back. Use Refund Payment to record money returned instead. Ask the user before calling.',+ idempotent: false,+ },+ outputSchema: invoiceNinjaOutputSchemas.payment,+ props: { id: entityActions.bulkIdProp('Payment') },+ async run({ auth, propsValue }) {+ return entityActions.runBulk({ auth: auth.props, entity: 'payments', label: 'Payment', action: 'delete', id: propsValue.id });+ },+});++function numberOf(value: unknown): number {+ const parsed = typeof value === 'string' ? Number(value) : value;+ return typeof parsed === 'number' && Number.isFinite(parsed) ? parsed : 0;+}++function round(value: number): number {+ return Math.round(value * 100) / 100;+}++function allocate({ paymentables, amount }: { paymentables: unknown[]; amount: number }): { invoice_id: string; amount: number }[] {+ const open = paymentables+ .filter(invoiceNinjaClient.isRecord)+ .filter((row) => typeof row['invoice_id'] === 'string' && row['invoice_id'] !== '')+ .map((row) => ({ invoice_id: String(row['invoice_id']), left: round(numberOf(row['amount']) - numberOf(row['refunded'])) }))+ .filter((row) => row.left > 0);+ return open.reduce<{ rest: number; rows: { invoice_id: string; amount: number }[] }>(+ (acc, row) => {+ if (acc.rest <= 0) return acc;+ const take = round(Math.min(acc.rest, row.left));+ return { rest: round(acc.rest - take), rows: [...acc.rows, { invoice_id: row.invoice_id, amount: take }] };+ },+ { rest: amount, rows: [] },+ ).rows;+}diff --git a/packages/pieces/community/invoiceninja/src/lib/actions/ai/quotes.ts b/packages/pieces/community/invoiceninja/src/lib/actions/ai/quotes.tsnew file mode 100644index 00000000000..570e12fc0c6--- /dev/null+++ b/packages/pieces/community/invoiceninja/src/lib/actions/ai/quotes.ts@@ -0,0 +1,212 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { invoiceninjaAuth } from '../../common/auth';+import { invoiceNinjaClient } from '../../common/client';+import { entityActions } from '../../common/entity-actions';+import { invoiceNinjaOutputSchemas } from '../../common/output-schemas';+import { invoiceNinjaProps } from '../../common/props';++const CLEARABLE = ['po_number', 'public_notes', 'private_notes', 'terms', 'due_date'] as const;++export const getQuote = createAction({+ auth: invoiceninjaAuth,+ name: 'get_quote',+ classification: 'READ',+ displayName: 'Get Quote',+ description: 'Get one quote by its ID.',+ audience: 'ai',+ aiMetadata: {+ description: 'Returns one Invoice Ninja quote by its ID: status, amount, line items, portal links and, once converted, invoice_id. Read-only.',+ idempotent: true,+ },+ outputSchema: invoiceNinjaOutputSchemas.quote,+ props: { id: entityActions.getIdProp('Quote') },+ async run({ auth, propsValue }) {+ return entityActions.runGet({ auth: auth.props, entity: 'quotes', label: 'Quote', id: propsValue.id });+ },+});++export const listQuotes = createAction({+ auth: invoiceninjaAuth,+ name: 'list_quotes',+ classification: 'SEARCH',+ displayName: 'List Quotes',+ description: 'List quotes with filters, one page at a time.',+ audience: 'ai',+ aiMetadata: {+ description: 'Lists Invoice Ninja quotes, optionally for one client, by quote state and free-text search. Returns {items, page, perPage, total, hasMore}. Read-only.',+ idempotent: true,+ },+ outputSchema: invoiceNinjaOutputSchemas.quoteList,+ props: {+ client_id: Property.ShortText({ displayName: 'Client ID', required: false }),+ quote_state: Property.StaticDropdown<string>({+ displayName: 'Quote State',+ required: false,+ options: {+ options: [+ { label: 'All', value: 'all' },+ { label: 'Draft', value: 'draft' },+ { label: 'Sent', value: 'sent' },+ { label: 'Approved', value: 'approved' },+ { label: 'Converted', value: 'converted' },+ { label: 'Expired', value: 'expired' },+ ],+ },+ }),+ search: Property.ShortText({ displayName: 'Search', required: false }),+ status: entityActions.statusProp(),+ sort: entityActions.sortProp(),+ ...entityActions.listProps(),+ },+ async run({ auth, propsValue }) {+ return entityActions.runList({+ auth: auth.props,+ entity: 'quotes',+ page: propsValue.page,+ perPage: propsValue.per_page,+ query: {+ client_id: invoiceNinjaClient.optionalId({ value: propsValue.client_id, label: 'Client ID' }),+ client_status: propsValue.quote_state,+ filter: invoiceNinjaClient.optionalText(propsValue.search),+ status: propsValue.status,+ sort: propsValue.sort,+ },+ });+ },+});++export const createQuote = createAction({+ auth: invoiceninjaAuth,+ name: 'create_quote',+ classification: 'WRITE',+ displayName: 'Create Quote',+ description: 'Create a draft quote for a client from line items.',+ audience: 'ai',+ aiMetadata: {+ description: 'Creates a draft Invoice Ninja quote for client_id from line_items (product_key and/or notes, cost, quantity). due_date is the valid-until date (YYYY-MM-DD). Send it with Email Quote. Not idempotent: each call creates a new quote.',+ idempotent: false,+ },+ outputSchema: invoiceNinjaOutputSchemas.quote,+ props: {+ client_id: Property.ShortText({ displayName: 'Client ID', required: true }),+ line_items: invoiceNinjaProps.lineItems({ required: true }),+ ...invoiceNinjaProps.documentProps(),+ },+ async run({ auth, propsValue }) {+ const body = {+ ...invoiceNinjaProps.documentBody(propsValue),+ client_id: invoiceNinjaClient.parseId({ value: propsValue.client_id, label: 'Client ID' }),+ line_items: invoiceNinjaClient.lineItemsOf({ value: propsValue.line_items, label: 'Line Items', required: true, isAmountDiscount: invoiceNinjaClient.parseBoolean(propsValue.is_amount_discount) }),+ };+ return invoiceNinjaClient.recordOf(+ await invoiceNinjaClient.request({ auth: auth.props, method: HttpMethod.POST, path: '/quotes', body }),+ );+ },+});++export const updateQuote = createAction({+ auth: invoiceninjaAuth,+ name: 'update_quote',+ classification: 'WRITE',+ displayName: 'Update Quote',+ description: 'Change fields of a quote. Empty fields are left unchanged.',+ audience: 'ai',+ aiMetadata: {+ description: 'Updates an Invoice Ninja quote by ID. Only fields you pass change; clear_fields blanks the listed ones; line_items, when given, REPLACES all lines. Returns the updated quote. Idempotent.',+ idempotent: true,+ },+ outputSchema: invoiceNinjaOutputSchemas.quote,+ props: {+ quote_id: Property.ShortText({ displayName: 'Quote ID', required: true }),+ line_items: invoiceNinjaProps.lineItems({ required: false }),+ ...invoiceNinjaProps.documentProps(),+ clear_fields: invoiceNinjaProps.clearProp({ fields: CLEARABLE }),+ },+ async run({ auth, propsValue }) {+ const id = invoiceNinjaClient.parseId({ value: propsValue.quote_id, label: 'Quote ID' });+ const body = invoiceNinjaClient.compact({+ ...invoiceNinjaClient.clearedFields({ value: propsValue.clear_fields, allowed: CLEARABLE }),+ ...invoiceNinjaProps.documentBody(propsValue),+ line_items: invoiceNinjaClient.lineItemsOf({ value: propsValue.line_items, label: 'Line Items', required: false, isAmountDiscount: invoiceNinjaClient.parseBoolean(propsValue.is_amount_discount) }),+ });+ if (Object.keys(body).length === 0) {+ throw new Error('Nothing to update: give at least one field or clear_fields.');+ }+ return invoiceNinjaClient.recordOf(+ await invoiceNinjaClient.request({ auth: auth.props, method: HttpMethod.PUT, path: `/quotes/${id}`, body }),+ );+ },+});++export const emailQuote = createAction({+ auth: invoiceninjaAuth,+ name: 'email_quote',+ classification: 'WRITE',+ displayName: 'Email Quote',+ description: 'Email the quote to the client\'s contacts and mark it sent.',+ audience: 'ai',+ aiMetadata: {+ description: 'Emails an Invoice Ninja quote to the client contacts that receive email and marks a draft as sent. Not idempotent: each call sends another email.',+ idempotent: false,+ },+ outputSchema: invoiceNinjaOutputSchemas.quote,+ props: { id: entityActions.bulkIdProp('Quote') },+ async run({ auth, propsValue }) {+ return entityActions.runBulk({ auth: auth.props, entity: 'quotes', label: 'Quote', action: 'email', id: propsValue.id });+ },+});++export const approveQuote = createAction({+ auth: invoiceninjaAuth,+ name: 'approve_quote',+ classification: 'WRITE',+ displayName: 'Approve Quote',+ description: 'Mark a sent quote as approved on the client\'s behalf.',+ audience: 'ai',+ aiMetadata: {+ description: 'Approves an Invoice Ninja quote (status 3) on the client\'s behalf, including a draft quote. Idempotent.',+ idempotent: true,+ },+ outputSchema: invoiceNinjaOutputSchemas.quote,+ props: { id: entityActions.bulkIdProp('Quote') },+ async run({ auth, propsValue }) {+ return entityActions.runBulk({ auth: auth.props, entity: 'quotes', label: 'Quote', action: 'approve', id: propsValue.id });+ },+});++export const convertQuoteToInvoice = createAction({+ auth: invoiceninjaAuth,+ name: 'convert_quote_to_invoice',+ classification: 'WRITE',+ displayName: 'Convert Quote to Invoice',+ description: 'Create an invoice from a quote.',+ audience: 'ai',+ aiMetadata: {+ description: 'Converts an Invoice Ninja quote into a new draft invoice; the returned quote has status 4 and invoice_id set to the new invoice (fetch it with Get Invoice). Calling it again on a converted quote fails and creates nothing.',+ idempotent: false,+ },+ outputSchema: invoiceNinjaOutputSchemas.quote,+ props: { id: entityActions.bulkIdProp('Quote') },+ async run({ auth, propsValue }) {+ return entityActions.runBulk({ auth: auth.props, entity: 'quotes', label: 'Quote', action: 'convert_to_invoice', id: propsValue.id });+ },+});++export const deleteQuote = createAction({+ auth: invoiceninjaAuth,+ name: 'delete_quote',+ classification: 'DESTRUCTIVE',+ displayName: 'Delete Quote',+ description: 'Delete a quote (soft delete).',+ audience: 'ai',+ aiMetadata: {+ description: 'Deletes an Invoice Ninja quote by ID (soft delete, is_deleted true). Ask the user before calling. Deleting an already deleted quote fails.',+ idempotent: false,+ },+ outputSchema: invoiceNinjaOutputSchemas.quote,+ props: { id: entityActions.bulkIdProp('Quote') },+ async run({ auth, propsValue }) {+ return entityActions.runBulk({ auth: auth.props, entity: 'quotes', label: 'Quote', action: 'delete', id: propsValue.id });+ },+});diff --git a/packages/pieces/community/invoiceninja/src/lib/actions/ai/recurring-invoices.ts b/packages/pieces/community/invoiceninja/src/lib/actions/ai/recurring-invoices.tsnew file mode 100644index 00000000000..5bd8fb6bf0b--- /dev/null+++ b/packages/pieces/community/invoiceninja/src/lib/actions/ai/recurring-invoices.ts@@ -0,0 +1,180 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { invoiceninjaAuth } from '../../common/auth';+import { invoiceNinjaClient } from '../../common/client';+import { entityActions } from '../../common/entity-actions';+import { invoiceNinjaOutputSchemas } from '../../common/output-schemas';+import { invoiceNinjaProps } from '../../common/props';++export const getRecurringInvoice = createAction({+ auth: invoiceninjaAuth,+ name: 'get_recurring_invoice',+ classification: 'READ',+ displayName: 'Get Recurring Invoice',+ description: 'Get one recurring invoice by its ID.',+ audience: 'ai',+ aiMetadata: {+ description: 'Returns one Invoice Ninja recurring invoice by ID: status, frequency, next send date, remaining cycles and line items. Read-only.',+ idempotent: true,+ },+ outputSchema: invoiceNinjaOutputSchemas.recurring,+ props: { id: entityActions.getIdProp('Recurring Invoice') },+ async run({ auth, propsValue }) {+ return entityActions.runGet({ auth: auth.props, entity: 'recurring_invoices', label: 'Recurring Invoice', id: propsValue.id });+ },+});++export const listRecurringInvoices = createAction({+ auth: invoiceninjaAuth,+ name: 'list_recurring_invoices',+ classification: 'SEARCH',+ displayName: 'List Recurring Invoices',+ description: 'List recurring invoices, one page at a time.',+ audience: 'ai',+ aiMetadata: {+ description: 'Lists Invoice Ninja recurring invoices, optionally for one client or by schedule state (active, paused, completed). Returns {items, page, perPage, total, hasMore}. Read-only.',+ idempotent: true,+ },+ outputSchema: invoiceNinjaOutputSchemas.recurringList,+ props: {+ client_id: Property.ShortText({ displayName: 'Client ID', required: false }),+ schedule_state: Property.StaticDropdown<string>({+ displayName: 'Schedule State',+ required: false,+ options: {+ options: [+ { label: 'All', value: 'all' },+ { label: 'Active', value: 'active' },+ { label: 'Paused', value: 'paused' },+ { label: 'Completed', value: 'completed' },+ ],+ },+ }),+ search: Property.ShortText({ displayName: 'Search', required: false }),+ status: entityActions.statusProp(),+ ...entityActions.listProps(),+ },+ async run({ auth, propsValue }) {+ return entityActions.runList({+ auth: auth.props,+ entity: 'recurring_invoices',+ page: propsValue.page,+ perPage: propsValue.per_page,+ query: {+ client_id: invoiceNinjaClient.optionalId({ value: propsValue.client_id, label: 'Client ID' }),+ client_status: propsValue.schedule_state,+ filter: invoiceNinjaClient.optionalText(propsValue.search),+ status: propsValue.status,+ },+ });+ },+});++export const createRecurringInvoiceAi = createAction({+ auth: invoiceninjaAuth,+ name: 'create_recurring_invoice_ai',+ classification: 'WRITE',+ displayName: 'Create Recurring Invoice (from line items)',+ description: 'Create a draft recurring invoice from line items and a schedule.',+ audience: 'ai',+ aiMetadata: {+ description: 'Creates a draft Invoice Ninja recurring invoice for client_id from line_items, billing every frequency_id (1 daily, 2 weekly, 3 two weeks, 4 four weeks, 5 monthly, 6 two months, 7 quarterly, 8 four months, 9 six months, 10 annually, 11 two years, 12 three years) starting next_send_date (YYYY-MM-DD) for remaining_cycles (-1 or empty = endless). It stays a draft until Start Recurring Invoice. Not idempotent.',+ idempotent: false,+ },+ outputSchema: invoiceNinjaOutputSchemas.recurring,+ props: {+ client_id: Property.ShortText({ displayName: 'Client ID', required: true }),+ line_items: invoiceNinjaProps.lineItems({ required: true }),+ frequency_id: Property.Number({ displayName: 'Frequency ID', description: '1-12, see the description. 5 = monthly.', required: true }),+ next_send_date: Property.ShortText({ displayName: 'Next Send Date', description: 'YYYY-MM-DD, today or later.', required: true }),+ remaining_cycles: Property.Number({ displayName: 'Remaining Cycles', description: 'How many invoices to generate; -1 or empty = endless.', required: false }),+ ...invoiceNinjaProps.recurringDocumentProps(),+ },+ async run({ auth, propsValue }) {+ const frequency = invoiceNinjaClient.optionalInt({ value: propsValue.frequency_id, label: 'Frequency ID', min: 1, max: 12 });+ const cycles = invoiceNinjaClient.optionalInt({ value: propsValue.remaining_cycles, label: 'Remaining Cycles', min: -1, max: 9999 });+ const body = invoiceNinjaClient.compact({+ ...invoiceNinjaProps.documentBody(propsValue),+ client_id: invoiceNinjaClient.parseId({ value: propsValue.client_id, label: 'Client ID' }),+ line_items: invoiceNinjaClient.lineItemsOf({ value: propsValue.line_items, label: 'Line Items', required: true, isAmountDiscount: invoiceNinjaClient.parseBoolean(propsValue.is_amount_discount) }),+ frequency_id: frequency === undefined ? undefined : String(frequency),+ next_send_date: invoiceNinjaClient.toDateOnly({ value: propsValue.next_send_date, label: 'Next Send Date' }),+ remaining_cycles: cycles ?? -1,+ });+ return invoiceNinjaClient.recordOf(+ await invoiceNinjaClient.request({ auth: auth.props, method: HttpMethod.POST, path: '/recurring_invoices', body }),+ );+ },+});++export const startRecurringInvoice = createAction({+ auth: invoiceninjaAuth,+ name: 'start_recurring_invoice',+ classification: 'WRITE',+ displayName: 'Start Recurring Invoice',+ description: 'Start (or resume) the schedule of a recurring invoice.',+ audience: 'ai',+ aiMetadata: {+ description: 'Starts or resumes an Invoice Ninja recurring invoice so it generates invoices on its schedule (status 2 active). Idempotent.',+ idempotent: true,+ },+ outputSchema: invoiceNinjaOutputSchemas.recurring,+ props: { id: entityActions.bulkIdProp('Recurring Invoice') },+ async run({ auth, propsValue }) {+ return entityActions.runBulk({ auth: auth.props, entity: 'recurring_invoices', label: 'Recurring Invoice', action: 'start', id: propsValue.id });+ },+});++export const stopRecurringInvoice = createAction({+ auth: invoiceninjaAuth,+ name: 'stop_recurring_invoice',+ classification: 'DESTRUCTIVE',+ displayName: 'Pause Recurring Invoice',+ description: 'Pause the schedule of a recurring invoice.',+ audience: 'ai',+ aiMetadata: {+ description: 'Pauses an Invoice Ninja recurring invoice (status 3 paused); no invoices are generated until Start Recurring Invoice. Idempotent.',+ idempotent: true,+ },+ outputSchema: invoiceNinjaOutputSchemas.recurring,+ props: { id: entityActions.bulkIdProp('Recurring Invoice') },+ async run({ auth, propsValue }) {+ return entityActions.runBulk({ auth: auth.props, entity: 'recurring_invoices', label: 'Recurring Invoice', action: 'stop', id: propsValue.id });+ },+});++export const sendRecurringInvoiceNow = createAction({+ auth: invoiceninjaAuth,+ name: 'send_recurring_invoice_now',+ classification: 'WRITE',+ displayName: 'Send Recurring Invoice Now',+ description: 'Generate and send the next invoice of a recurring invoice now.',+ audience: 'ai',+ aiMetadata: {+ description: 'Generates the next invoice from an Invoice Ninja recurring invoice immediately (and emails it if the schedule sends emails), then moves next_send_date forward. Not idempotent: each call creates another invoice.',+ idempotent: false,+ },+ outputSchema: invoiceNinjaOutputSchemas.recurring,+ props: { id: entityActions.bulkIdProp('Recurring Invoice') },+ async run({ auth, propsValue }) {+ return entityActions.runBulk({ auth: auth.props, entity: 'recurring_invoices', label: 'Recurring Invoice', action: 'send_now', id: propsValue.id });+ },+});++export const deleteRecurringInvoice = createAction({+ auth: invoiceninjaAuth,+ name: 'delete_recurring_invoice',+ classification: 'DESTRUCTIVE',+ displayName: 'Delete Recurring Invoice',+ description: 'Delete a recurring invoice (soft delete; invoices already generated stay).',+ audience: 'ai',+ aiMetadata: {+ description: 'Deletes an Invoice Ninja recurring invoice by ID (soft delete) so it stops generating invoices; invoices it already created are kept. Ask the user before calling.',+ idempotent: false,+ },+ outputSchema: invoiceNinjaOutputSchemas.recurring,+ props: { id: entityActions.bulkIdProp('Recurring Invoice') },+ async run({ auth, propsValue }) {+ return entityActions.runBulk({ auth: auth.props, entity: 'recurring_invoices', label: 'Recurring Invoice', action: 'delete', id: propsValue.id });+ },+});diff --git a/packages/pieces/community/invoiceninja/src/lib/actions/ai/tasks-reports.ts b/packages/pieces/community/invoiceninja/src/lib/actions/ai/tasks-reports.tsnew file mode 100644index 00000000000..9f1227d1075--- /dev/null+++ b/packages/pieces/community/invoiceninja/src/lib/actions/ai/tasks-reports.ts@@ -0,0 +1,216 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { invoiceninjaAuth } from '../../common/auth';+import { invoiceNinjaClient } from '../../common/client';+import { entityActions } from '../../common/entity-actions';+import { invoiceNinjaOutputSchemas } from '../../common/output-schemas';+import { invoiceNinjaProps } from '../../common/props';+import { invoiceNinjaReports } from '../../common/report';++const TASK_CLEARABLE = ['description', 'project_id'] as const;++export const getTask = createAction({+ auth: invoiceninjaAuth,+ name: 'get_task',+ classification: 'READ',+ displayName: 'Get Task',+ description: 'Get one task by its ID.',+ audience: 'ai',+ aiMetadata: {+ description: 'Returns one Invoice Ninja task (time entry) by ID: description, client, project, rate, duration and time log. Read-only.',+ idempotent: true,+ },+ outputSchema: invoiceNinjaOutputSchemas.task,+ props: { id: entityActions.getIdProp('Task') },+ async run({ auth, propsValue }) {+ return entityActions.runGet({ auth: auth.props, entity: 'tasks', label: 'Task', id: propsValue.id });+ },+});++export const listTasks = createAction({+ auth: invoiceninjaAuth,+ name: 'list_tasks',+ classification: 'SEARCH',+ displayName: 'List Tasks',+ description: 'List tasks, one page at a time.',+ audience: 'ai',+ aiMetadata: {+ description: 'Lists Invoice Ninja tasks, optionally for one client or project, by exact task number, or by free-text search on the description. Use number to check whether a task number already exists (total 0 = no). Returns {items, page, perPage, total, hasMore}. Read-only.',+ idempotent: true,+ },+ outputSchema: invoiceNinjaOutputSchemas.taskList,+ props: {+ client_id: Property.ShortText({ displayName: 'Client ID', required: false }),+ project_id: Property.ShortText({ displayName: 'Project ID', required: false }),+ number: Property.ShortText({ displayName: 'Task Number', required: false }),+ search: Property.ShortText({ displayName: 'Search', required: false }),+ status: entityActions.statusProp(),+ sort: entityActions.sortProp(),+ ...entityActions.listProps(),+ },+ async run({ auth, propsValue }) {+ return entityActions.runList({+ auth: auth.props,+ entity: 'tasks',+ page: propsValue.page,+ perPage: propsValue.per_page,+ query: {+ client_id: invoiceNinjaClient.optionalId({ value: propsValue.client_id, label: 'Client ID' }),+ project_tasks: invoiceNinjaClient.optionalId({ value: propsValue.project_id, label: 'Project ID' }),+ number: invoiceNinjaClient.optionalText(propsValue.number),+ filter: invoiceNinjaClient.optionalText(propsValue.search),+ status: propsValue.status,+ sort: propsValue.sort,+ },+ });+ },+});++export const createTaskAi = createAction({+ auth: invoiceninjaAuth,+ name: 'create_task_ai',+ classification: 'WRITE',+ displayName: 'Create Task (by IDs)',+ description: 'Create a task (billable time entry), optionally with logged time.',+ audience: 'ai',+ aiMetadata: {+ description: 'Creates an Invoice Ninja task with description, optional client_id, project_id, hourly rate and number (must be unique; empty = auto). Pass start_time and end_time (ISO 8601) to log a finished time block, or start_time alone to leave a timer running. Not idempotent unless number is given (a duplicate number is rejected).',+ idempotent: false,+ },+ outputSchema: invoiceNinjaOutputSchemas.task,+ props: {+ description: Property.LongText({ displayName: 'Description', required: true }),+ client_id: Property.ShortText({ displayName: 'Client ID', required: false }),+ project_id: Property.ShortText({ displayName: 'Project ID', required: false }),+ rate: Property.Number({ displayName: 'Hourly Rate', required: false }),+ number: Property.ShortText({ displayName: 'Task Number', required: false }),+ start_time: Property.ShortText({ displayName: 'Start Time', description: 'ISO 8601, e.g. 2026-01-31T09:00:00Z.', required: false }),+ end_time: Property.ShortText({ displayName: 'End Time', description: 'ISO 8601. Empty with a start time = timer keeps running.', required: false }),+ },+ async run({ auth, propsValue }) {+ const body = taskBody(propsValue);+ if (body['description'] === undefined) throw new Error('Description is required.');+ return invoiceNinjaClient.recordOf(+ await invoiceNinjaClient.request({ auth: auth.props, method: HttpMethod.POST, path: '/tasks', body }),+ );+ },+});++export const updateTask = createAction({+ auth: invoiceninjaAuth,+ name: 'update_task',+ classification: 'WRITE',+ displayName: 'Update Task',+ description: 'Change fields of a task. Empty fields are left unchanged.',+ audience: 'ai',+ aiMetadata: {+ description: 'Updates an Invoice Ninja task by ID: description, client, project or hourly rate. Only fields you pass change; clear_fields blanks description or project_id. Use Start Task / Stop Task for the timer. Idempotent.',+ idempotent: true,+ },+ outputSchema: invoiceNinjaOutputSchemas.task,+ props: {+ task_id: Property.ShortText({ displayName: 'Task ID', required: true }),+ description: Property.LongText({ displayName: 'Description', required: false }),+ client_id: Property.ShortText({ displayName: 'Client ID', required: false }),+ project_id: Property.ShortText({ displayName: 'Project ID', required: false }),+ rate: Property.Number({ displayName: 'Hourly Rate', required: false }),+ clear_fields: invoiceNinjaProps.clearProp({ fields: TASK_CLEARABLE }),+ },+ async run({ auth, propsValue }) {+ const id = invoiceNinjaClient.parseId({ value: propsValue.task_id, label: 'Task ID' });+ const body = {+ ...invoiceNinjaClient.clearedFields({ value: propsValue.clear_fields, allowed: TASK_CLEARABLE }),+ ...taskBody({ ...propsValue, number: undefined, start_time: undefined, end_time: undefined }),+ };+ if (Object.keys(body).length === 0) throw new Error('Nothing to update: give at least one field or clear_fields.');+ return invoiceNinjaClient.recordOf(+ await invoiceNinjaClient.request({ auth: auth.props, method: HttpMethod.PUT, path: `/tasks/${id}`, body }),+ );+ },+});++export const startTask = createAction({+ auth: invoiceninjaAuth,+ name: 'start_task',+ classification: 'WRITE',+ displayName: 'Start Task Timer',+ description: 'Start the timer of a task (adds a new running time entry).',+ audience: 'ai',+ aiMetadata: {+ description: 'Starts the timer of an Invoice Ninja task by adding a running time-log entry from now. A task that is already running is left as is. Idempotent.',+ idempotent: true,+ },+ outputSchema: invoiceNinjaOutputSchemas.task,+ props: { id: entityActions.bulkIdProp('Task') },+ async run({ auth, propsValue }) {+ return entityActions.runBulk({ auth: auth.props, entity: 'tasks', label: 'Task', action: 'start', id: propsValue.id });+ },+});++export const stopTask = createAction({+ auth: invoiceninjaAuth,+ name: 'stop_task',+ classification: 'WRITE',+ displayName: 'Stop Task Timer',+ description: 'Stop the running timer of a task.',+ audience: 'ai',+ aiMetadata: {+ description: 'Stops the running timer of an Invoice Ninja task, closing its open time-log entry at now; duration grows accordingly. A stopped task is left as is. Idempotent.',+ idempotent: true,+ },+ outputSchema: invoiceNinjaOutputSchemas.task,+ props: { id: entityActions.bulkIdProp('Task') },+ async run({ auth, propsValue }) {+ return entityActions.runBulk({ auth: auth.props, entity: 'tasks', label: 'Task', action: 'stop', id: propsValue.id });+ },+});++export const runReport = createAction({+ auth: invoiceninjaAuth,+ name: 'run_report',+ classification: 'SEARCH',+ displayName: 'Run Report',+ description: 'Run an Invoice Ninja report and return its rows.',+ audience: 'ai',+ aiMetadata: {+ description: 'Runs an Invoice Ninja report (clients, contacts, invoices, invoice_items, quotes, quote_items, credits, payments, recurring_invoices, expenses, tasks, products, vendors) for a date range (all, last7, last30, this_month, last_month, this_quarter, last_quarter, this_year, last_year, or custom with start_date and end_date) and optionally one client. Waits up to 60 seconds for the result and returns {columns, rows (keyed by column identifier), rowCount}. Read-only.',+ idempotent: true,+ },+ outputSchema: invoiceNinjaOutputSchemas.report,+ props: invoiceNinjaReports.reportProps(),+ async run({ auth, propsValue }) {+ return invoiceNinjaReports.runReport({+ auth: auth.props,+ reportType: propsValue.report_type ?? '',+ dateRange: propsValue.date_range ?? 'all',+ startDate: propsValue.start_date,+ endDate: propsValue.end_date,+ clientId: propsValue.client_id,+ });+ },+});++function unixSeconds({ value, label }: { value: unknown; label: string }): number | undefined {+ const text = invoiceNinjaClient.optionalText(value);+ if (text === undefined) return undefined;+ const ms = Date.parse(text);+ if (Number.isNaN(ms)) throw new Error(`${label} must be an ISO 8601 date-time.`);+ return Math.floor(ms / 1000);+}++function taskBody(props: Record<string, unknown>): Record<string, unknown> {+ const start = unixSeconds({ value: props['start_time'], label: 'Start Time' });+ const end = unixSeconds({ value: props['end_time'], label: 'End Time' });+ if (end !== undefined && start === undefined) throw new Error('End Time needs a Start Time.');+ if (start !== undefined && end !== undefined && end <= start) throw new Error('End Time must be after Start Time.');+ return invoiceNinjaClient.compact({+ description: invoiceNinjaClient.optionalText(props['description']),+ client_id: invoiceNinjaClient.optionalId({ value: props['client_id'], label: 'Client ID' }),+ project_id: invoiceNinjaClient.optionalId({ value: props['project_id'], label: 'Project ID' }),+ rate: invoiceNinjaClient.optionalNumber({ value: props['rate'], label: 'Hourly Rate', min: 0 }),+ number: invoiceNinjaClient.optionalText(props['number']),+ time_log: start === undefined ? undefined : JSON.stringify([[start, end ?? 0, '', true]]),+ });+}++export const invoiceNinjaTaskHelpers = { taskBody };diff --git a/packages/pieces/community/invoiceninja/src/lib/actions/create-client.ts b/packages/pieces/community/invoiceninja/src/lib/actions/create-client.tsindex 9307d2d0a05..5e4802695bb 100644--- a/packages/pieces/community/invoiceninja/src/lib/actions/create-client.ts+++ b/packages/pieces/community/invoiceninja/src/lib/actions/create-client.ts@@ -1,122 +1,68 @@-import {- createAction,- Property,-} from '@activepieces/pieces-framework';-import { httpClient, HttpMethod } from '@activepieces/pieces-common';-import { invoiceninjaAuth } from '../..';+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { invoiceninjaAuth } from '../common/auth';+import { invoiceNinjaClient } from '../common/client';+import { invoiceNinjaOutputSchemas } from '../common/output-schemas';export const createClient = createAction({auth: invoiceninjaAuth,name: 'create_client',classification: 'WRITE',displayName: 'Create Client',- description: 'Creates a new client in InvoiceNinja.',+ description: 'Creates a new client with a primary contact in Invoice Ninja.',audience: 'both',- aiMetadata: { description: 'Creates a new client record in Invoice Ninja with a primary contact, requiring business name, contact email, address line 1, and city; other contact and address fields are optional. Not idempotent — each call creates a new client even if one with the same details already exists.', idempotent: false },-+ aiMetadata: {+ description: 'Creates an Invoice Ninja client with one primary contact. Requires business name, contact email, address line 1 and city; contact names, phone, VAT number, notes, address line 2, state and postcode are optional. Returns {data: client} with the new client id at data.id. Not idempotent: each call creates a new client even if one with the same email exists, so use Find Clients first.',+ idempotent: false,+ },+ outputSchema: invoiceNinjaOutputSchemas.legacyClientCreated,props: {- client_first_name: Property.LongText({- displayName: 'Client First Name (alphanumeric)',- description: 'The contact first name for this client (optional)',- required: false,- }),- client_last_name: Property.ShortText({- displayName: 'Client Last Name (alphanumeric)',- description: 'The contact last name for this client (optional)',- required: false,- }),- client_phone: Property.ShortText({- displayName: 'Client Contact No (alphanumeric)',- description: 'The contact number for this client (optional)',- required: false,- }),- client_email: Property.ShortText({- displayName: 'Client e-mail (alphanumeric)',- description: 'The contact email for this client (compulsory)',- required: true,- }),+ client_first_name: Property.ShortText({ displayName: 'Contact First Name', description: 'First name of the client contact (optional).', required: false }),+ client_last_name: Property.ShortText({ displayName: 'Contact Last Name', description: 'Last name of the client contact (optional).', required: false }),+ client_phone: Property.ShortText({ displayName: 'Contact Phone', description: 'Phone number of the client contact (optional).', required: false }),+ client_email: Property.ShortText({ displayName: 'Contact Email', description: 'E-mail of the client contact.', required: true }),client_send_email: Property.Checkbox({displayName: 'Send invoices to the client',- description: 'Should we send invoices to the client by e-mail?',+ description: 'Should Invoice Ninja e-mail invoices to this contact?',defaultValue: false,required: true,}),- client_business_name: Property.ShortText({- displayName: 'Business Name (alphanumeric)',- description: 'Name of this business or natural person (compulsory)',- required: true,- }),- client_tax_no: Property.ShortText({- displayName: 'Client Tax Number (alphanumeric)',- description: 'Leave blank if not a business (optional)',- required: false,- }),- client_private_notes: Property.ShortText({- displayName: 'Private notes for client',- description: 'Text not visible for clients (optional)',- required: false,- }),- client_address1: Property.LongText({- displayName: 'Client address 1 (alphanumeric)',- description: 'Usually street name and number (compulsory)',- required: true,- }),- client_address2: Property.LongText({- displayName: 'Client address 2 (alphanumeric)',- description: 'Additional address details (optional)',- required: false,- }),- client_city: Property.ShortText({- displayName: 'Client City/Town (alphanumeric)',- description: 'City or Town name (compulsory)',- required: true,- }),- client_state: Property.ShortText({- displayName: 'Client State (alphanumeric)',- description: 'State or county or similar (optional)',- required: false,- }),- client_postcode: Property.ShortText({- displayName: 'Client Postcode (alphanumeric)',- description: 'Postal code (optional)',- required: false,- }),+ client_business_name: Property.ShortText({ displayName: 'Business Name', description: 'Name of the business or person.', required: true }),+ client_tax_no: Property.ShortText({ displayName: 'VAT / Tax Number', description: 'Leave blank if not a business (optional).', required: false }),+ client_private_notes: Property.LongText({ displayName: 'Private Notes', description: 'Notes not visible to the client (optional).', required: false }),+ client_address1: Property.ShortText({ displayName: 'Address Line 1', description: 'Usually street name and number.', required: true }),+ client_address2: Property.ShortText({ displayName: 'Address Line 2', description: 'Additional address details (optional).', required: false }),+ client_city: Property.ShortText({ displayName: 'City / Town', required: true }),+ client_state: Property.ShortText({ displayName: 'State / County', description: 'Optional.', required: false }),+ client_postcode: Property.ShortText({ displayName: 'Postcode', description: 'Optional.', required: false }),},-- async run(context) {- const INapiToken = context.auth.props.access_token;- const headers = {- 'X-Api-Token': INapiToken,- 'Content-Type': 'application/json',- };-- const queryParams = new URLSearchParams();- queryParams.append('name', context.propsValue.client_business_name);- queryParams.append('private_notes', context.propsValue.client_private_notes || '');- queryParams.append('address1', context.propsValue.client_address1 || '');- queryParams.append('address2', context.propsValue.client_address2 || '');- queryParams.append('city', context.propsValue.client_city || '');- queryParams.append('state', context.propsValue.client_state || '');- queryParams.append('postal_code', context.propsValue.client_postcode || '');- queryParams.append('vat_number', context.propsValue.client_tax_no || '');- const body = {- "contacts": {- "first_name": context.propsValue.client_first_name || "", "last_name": context.propsValue.client_last_name || "",- "phone": context.propsValue.client_phone || "", "email": context.propsValue.client_email || "", "send_email": context.propsValue.client_send_email || false- }- };-- const baseUrl = context.auth.props.base_url.replace(/\/$/, '');- const url = `${baseUrl}/api/v1/clients/?${queryParams.toString()}`;-- const httprequestdata = {- method: HttpMethod.POST,- url,- headers,- body,- };-- const response = await httpClient.sendRequest(httprequestdata);- return response.body;+ async run({ auth, propsValue }) {+ const name = invoiceNinjaClient.optionalText(propsValue.client_business_name);+ const email = invoiceNinjaClient.optionalText(propsValue.client_email);+ if (name === undefined) throw new Error('Business Name is required.');+ if (email === undefined || !/^[^\s@]+@[^\s@]+$/.test(email)) throw new Error('Contact Email must be a valid e-mail address.');+ const body = invoiceNinjaClient.compact({+ name,+ private_notes: invoiceNinjaClient.optionalText(propsValue.client_private_notes),+ address1: invoiceNinjaClient.optionalText(propsValue.client_address1),+ address2: invoiceNinjaClient.optionalText(propsValue.client_address2),+ city: invoiceNinjaClient.optionalText(propsValue.client_city),+ state: invoiceNinjaClient.optionalText(propsValue.client_state),+ postal_code: invoiceNinjaClient.optionalText(propsValue.client_postcode),+ vat_number: invoiceNinjaClient.optionalText(propsValue.client_tax_no),+ contacts: [+ invoiceNinjaClient.compact({+ first_name: invoiceNinjaClient.optionalText(propsValue.client_first_name),+ last_name: invoiceNinjaClient.optionalText(propsValue.client_last_name),+ phone: invoiceNinjaClient.optionalText(propsValue.client_phone),+ email,+ send_email: propsValue.client_send_email === true,+ is_primary: true,+ }),+ ],+ });+ return invoiceNinjaClient.envelopeOf(+ await invoiceNinjaClient.request({ auth: auth.props, method: HttpMethod.POST, path: '/clients', body }),+ );},});diff --git a/packages/pieces/community/invoiceninja/src/lib/actions/create-invoice.ts b/packages/pieces/community/invoiceninja/src/lib/actions/create-invoice.tsindex 9b1f9ebcb13..fe111b41d0c 100644--- a/packages/pieces/community/invoiceninja/src/lib/actions/create-invoice.ts+++ b/packages/pieces/community/invoiceninja/src/lib/actions/create-invoice.ts@@ -1,218 +1,65 @@-import {- createAction,- Property,-} from '@activepieces/pieces-framework';-import * as z from 'zod/mini'-import { propsValidation } from '@activepieces/pieces-common';+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { invoiceninjaAuth } from '../common/auth';+import { invoiceNinjaClient } from '../common/client';+import { invoiceNinjaLegacy } from '../common/legacy-invoice';+import { invoiceNinjaOutputSchemas } from '../common/output-schemas';-import { invoiceninjaAuth } from '../..';+const LEGACY_PROPS = invoiceNinjaLegacy.legacyProps();export const createInvoice = createAction({auth: invoiceninjaAuth,name: 'create_invoice',classification: 'WRITE',displayName: 'Create Invoice',- description: 'Creates an invoice in Invoice Ninja for billing purposes.',- audience: 'both',- aiMetadata: { description: 'Creates an invoice for a client in Invoice Ninja from a JSON array of line items (each referencing an existing product_key, whose price and tax are looked up), with optional discount, notes, and due date. Can optionally email the invoice to the client and/or mark it as sent on creation. Requires a valid client id and at least one line item with a known product key. Not idempotent — each call creates a new invoice.', idempotent: false },-+ description: 'Creates an invoice from existing products (price and tax are taken from each product).',+ audience: 'human',+ outputSchema: invoiceNinjaOutputSchemas.legacyInvoiceCreated,props: {- client_id: Property.LongText({- displayName: 'Client ID (alphanumeric)',- description: 'Client ID from Invoice Ninja',- required: true,- }),- purchase_order_no: Property.LongText({- displayName: 'Purchase Order Number (alphanumeric)',- description: 'Descriptive text or arbitrary number (optional)',- required: false,- }),- discount: Property.LongText({- displayName: 'Apply discount',- description: 'Enter a number for the whole invoice discount',- defaultValue: '0',- required: true,- }),- discount_type: Property.StaticDropdown({- displayName: 'Type of discount',- description: 'Select either amount or percentage for invoice discount. Applies to line items and invoice.',- defaultValue: true,- required: true,- options: {- options: [- {- label: 'Amount',- value: true- },- {- label: 'Percentage',- value: false- }- ]- }- }),- public_notes: Property.LongText({- displayName: 'Public notes for invoice',- description: 'Text that may be visible in the client portal (optional)',- required: false,- }),- private_notes: Property.LongText({- displayName: 'Private notes for invoice',- description: 'Text not visible for clients (optional)',- required: false,- }),- order_items_json: Property.LongText({- displayName: 'Order Items JSON string',- description: 'e.g., [{ "quantity":1,"product_key":"product key", "discount": "0" }]',- required: true,- }),+ client_id: LEGACY_PROPS.client_id,+ purchase_order_no: LEGACY_PROPS.purchase_order_no,+ discount: LEGACY_PROPS.discount,+ discount_type: LEGACY_PROPS.discount_type,+ public_notes: LEGACY_PROPS.public_notes,+ private_notes: LEGACY_PROPS.private_notes,+ order_items_json: LEGACY_PROPS.order_items_json,send_email: Property.Checkbox({- displayName: 'Send invoice to the client by InvoiceNinja e-mail?',- description: 'Should we send the invoice to the client on creation?',+ displayName: 'E-mail the invoice to the client',+ description: 'Send the invoice by Invoice Ninja e-mail when it is created.',defaultValue: false,required: true,}),mark_sent: Property.Checkbox({- displayName: 'Mark the invoice as sent?',- description: 'Makes the invoice active otherwise remains pending.',+ displayName: 'Mark the invoice as sent',+ description: 'Makes the invoice active; otherwise it stays a draft.',defaultValue: false,required: true,}),due_date: Property.DateTime({displayName: 'Invoice due date',- description: 'e.g., 2024-01-20',+ description: 'The date part is used, e.g. 2024-01-20.',required: false,}),},-- async run(context) {- await propsValidation.validateZod(context.propsValue, {- due_date: z.optional(z.string().check(z.iso.datetime())),+ async run({ auth, propsValue }) {+ const clientId = invoiceNinjaClient.parseId({ value: propsValue.client_id, label: 'Client' });+ const dueDate = invoiceNinjaClient.toDateOnly({ value: propsValue.due_date, label: 'Invoice due date' });+ const discount = invoiceNinjaClient.optionalNumber({ value: propsValue.discount, label: 'Invoice Discount', min: 0 }) ?? 0;+ const isAmountDiscount = propsValue.discount_type !== false;+ const lineItems = await invoiceNinjaLegacy.lineItemsFromProducts({ auth: auth.props, json: propsValue.order_items_json, isAmountDiscount });+ const body = invoiceNinjaClient.compact({+ client_id: clientId,+ due_date: dueDate,+ po_number: invoiceNinjaClient.optionalText(propsValue.purchase_order_no),+ public_notes: invoiceNinjaClient.optionalText(propsValue.public_notes),+ private_notes: invoiceNinjaClient.optionalText(propsValue.private_notes),+ line_items: lineItems,+ discount,+ is_amount_discount: isAmountDiscount,});-- const INapiToken = context.auth.props.access_token;- const headers = {- 'X-Api-Token': INapiToken,- 'Content-Type': 'application/json',- };-- const lineItemsArray = JSON.parse(context.propsValue.order_items_json);-- if (!Array.isArray(lineItemsArray)) {- throw new Error('Invalid format for order_items_json. It should be an array of objects.');- }-- if (lineItemsArray.length === 0) {- throw new Error('The line_items array must not be empty.');- }-- const isValidLineItem = lineItemsArray.every(item => (- typeof item === 'object' &&- 'quantity' in item && typeof item.quantity === 'number' &&- 'product_key' in item && typeof item.product_key === 'string' &&- 'discount' in item && typeof item.discount === 'string'- ));-- if (!isValidLineItem) {- throw new Error('Each item in the line_items array must be an object with "quantity" (number), "product_key" (string), and "discount" (string).');- }-- const baseUrl = context.auth.props.base_url.replace(/\/$/, '');- let errorMessages = '';-- try {- const lineItemsWithDetailsPromises = lineItemsArray.map(async item => {- try {- const getProductDetailsResponse = await fetch(`${baseUrl}/api/v1/products/?product_key=${item.product_key}`, {- method: 'GET',- headers,- });-- if (!getProductDetailsResponse.ok) {- console.error(`Failed to get product details for ${item.product_key}. Status: ${getProductDetailsResponse.status}`);- errorMessages += `Failed to get product details for ${item.product_key}\n`;- return null;- }-- const productDetailsResponseBody = await getProductDetailsResponse.json();- const productCount = productDetailsResponseBody.meta.pagination.count;-- if (productCount < 1) {- console.error(`No product details found for ${item.product_key}.`);- errorMessages += `No product details found for ${item.product_key}\n`;- return null;- }-- const productDetails = productDetailsResponseBody.data[0];-- return {- quantity: item.quantity,- product_key: item.product_key,- product_cost: productDetails.price,- cost: productDetails.price,- notes: productDetails.notes,- discount: item.discount || '0',- is_amount_discount: context.propsValue.discount_type,- tax_name1: productDetails.tax_name1,- tax_rate1: productDetails.tax_rate1,- tax_id: productDetails.tax_id,- };- } catch (error) {- console.error(`Error getting product details for ${item.product_key}:`, error);- errorMessages += `Error getting product details for ${item.product_key}: ${error}\n`;- return null;- }- });-- const lineItemsWithDetails = await Promise.all(lineItemsWithDetailsPromises);-- if (errorMessages) {- // If there are error messages, throw an error with the accumulated messages- throw new Error(errorMessages.trim());- }-- const today = new Date();- const year = today.getFullYear();- const month = today.getMonth() + 1;- const day = today.getDate();- const formattedDate = `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`;-- const createInvoiceRequestBody = {- due_date: context.propsValue.due_date,- date: formattedDate,- client_id: context.propsValue.client_id || '',- po_number: context.propsValue.purchase_order_no || '',- public_notes: context.propsValue.public_notes || '',- private_notes: context.propsValue.private_notes || '',- line_items: lineItemsWithDetails,- discount: context.propsValue.discount,- is_amount_discount: context.propsValue.discount_type,- send_email: context.propsValue.send_email,- mark_sent: context.propsValue.mark_sent,- };-- const createInvoiceResponse = await fetch(`${baseUrl}/api/v1/invoices`, {- method: 'POST',- headers,- body: JSON.stringify(createInvoiceRequestBody),- });-- if (!createInvoiceResponse.ok) {- throw new Error(`Failed to create invoice. Status: ${createInvoiceResponse.status}`);- }-- const createInvoiceResponseBody = await createInvoiceResponse.json();-- return createInvoiceResponseBody;- } catch (error) {- console.error('Error creating invoice or getting product details:', error);- if (errorMessages) {- // If there are error messages, throw an error with the accumulated messages- throw new Error(errorMessages.trim());- } else {- // If there are no error messages, throw the original error- throw error;- }- }+ const query = { send_email: propsValue.send_email === true ? 'true' : undefined, mark_sent: propsValue.mark_sent === true ? 'true' : undefined };+ return invoiceNinjaClient.envelopeOf(+ await invoiceNinjaClient.request({ auth: auth.props, method: HttpMethod.POST, path: '/invoices', query, body }),+ );},});diff --git a/packages/pieces/community/invoiceninja/src/lib/actions/create-recurring.ts b/packages/pieces/community/invoiceninja/src/lib/actions/create-recurring.tsindex aeb20e55c18..295af945181 100644--- a/packages/pieces/community/invoiceninja/src/lib/actions/create-recurring.ts+++ b/packages/pieces/community/invoiceninja/src/lib/actions/create-recurring.ts@@ -1,289 +1,101 @@-import {- createAction,- Property,- } from '@activepieces/pieces-framework';-import * as z from 'zod/mini'-import { propsValidation } from '@activepieces/pieces-common';+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { invoiceninjaAuth } from '../common/auth';+import { invoiceNinjaClient } from '../common/client';+import { invoiceNinjaLegacy } from '../common/legacy-invoice';+import { invoiceNinjaOutputSchemas } from '../common/output-schemas';-import { invoiceninjaAuth } from '../..';+const LEGACY_PROPS = invoiceNinjaLegacy.legacyProps();export const createRecurringInvoice = createAction({- auth: invoiceninjaAuth,- name: 'create_recurring_invoice',- classification: 'WRITE',- displayName: 'Create Recurring Invoice',- description: 'Creates a recurring invoice in Invoice Ninja for billing purposes.',- audience: 'both',- aiMetadata: { description: 'Creates a recurring invoice for a client in Invoice Ninja from a JSON array of line items (each referencing an existing product_key), set to bill on a chosen frequency for a given number of cycles starting from a next-send date. The frequency can be picked from the preset list or overridden with a numeric frequency id. Requires a valid client id, at least one line item with a known product key, and a next-send date. Not idempotent — each call creates a new recurring invoice.', idempotent: false },-- props: {- client_id: Property.LongText({- displayName: 'Client ID (alphanumeric)',- description: 'Client ID from Invoice Ninja',- required: true,- }),- purchase_order_no: Property.LongText({- displayName: 'Purchase Order Number (alphanumeric)',- description: 'Descriptive text or arbitrary number (optional)',- required: false,- }),- discount: Property.LongText({- displayName: 'Apply discount',- description: 'Enter a number for the whole invoice discount',- defaultValue: '0',- required: true,- }),- discount_type: Property.StaticDropdown({- displayName: 'Type of discount',- description: 'Select either amount or percentage for invoice discount. Applies to line items and invoice.',- defaultValue: true,- required: true,- options: {- options: [- {- label: 'Amount',- value: true- },- {- label: 'Percentage',- value: false- }- ]- }- }),- public_notes: Property.LongText({- displayName: 'Public notes for invoice',- description: 'Text that may be visible in the client portal (optional)',- required: false,- }),- private_notes: Property.LongText({- displayName: 'Private notes for invoice',- description: 'Text not visible for clients (optional)',- required: false,- }),- order_items_json: Property.LongText({- displayName: 'Order Items JSON string',- description: 'e.g., [{ "quantity":1,"product_key":"product key", "discount": "0" }]',- required: true,- }),- frequency: Property.StaticDropdown({- displayName: 'Frequency of billing',- description: 'Choose one',- defaultValue: 5,- required: true,- options: {- options: [- {- label: 'Use override below',- value:0,- },- {- label: 'Daily',- value: 1- },- {- label: 'Weekly',- value: 2- },- {- label: '2 Weeks',- value: 3- },- {- label: '4 Weeks',- value: 4- },- {- label: 'Monthly',- value: 5- },- {- label: 'Two Months',- value: 6- },- {- label: 'Quarterly',- value: 7- },- {- label: 'Four Months',- value: 8- },- {- label: 'Semi Annually',- value: 9- },- {- label: 'Annually',- value: 10- },- {- label: 'Two Years',- value: 11- },- {- label: 'Three Years',- value: 12- }- ]- },- }),- nocycles: Property.Number({- displayName: 'No of billing cycles',- description: 'Enter a number. How many times should this bill be generated',- required: false,- }),- auto_frequency: Property.Number({- displayName: 'Override Frequency using Frequency ID (optional)',- description: 'Enter a number. 1-12 - corresponds to dropdown above [Daily being 1, Weekly 2 etc..]!',- required: false,- }),- due_date: Property.DateTime({- displayName: 'Invoice next send date',- description: 'e.g., 2024-01-20',- required: true,- }),- last_date: Property.DateTime({- displayName: 'Invoice last sent date',- description: 'e.g., 2024-01-20',- required: false,- }),- },-- async run(context) {- await propsValidation.validateZod(context.propsValue, {- nocycles: z.optional(z.number().check(z.minimum(0), z.maximum(999))),- auto_frequency: z.optional(z.number().check(z.minimum(1), z.maximum(12))),- due_date: z.string().check(z.iso.datetime()),- last_date: z.optional(z.string().check(z.iso.datetime())),- });-- const INapiToken = context.auth.props.access_token;- const headers = {- 'X-Api-Token': INapiToken,- 'Content-Type': 'application/json',- };-- const lineItemsArray = JSON.parse(context.propsValue.order_items_json);-- if (!Array.isArray(lineItemsArray)) {- throw new Error('Invalid format for order_items_json. It should be an array of objects.');- }-- if (lineItemsArray.length === 0) {- throw new Error('The line_items array must not be empty.');- }-- const isValidLineItem = lineItemsArray.every(item => (- typeof item === 'object' &&- 'quantity' in item && typeof item.quantity === 'number' &&- 'product_key' in item && typeof item.product_key === 'string' &&- 'discount' in item && typeof item.discount === 'string'- ));-- if (!isValidLineItem) {- throw new Error('Each item in the line_items array must be an object with "quantity" (number), "product_key" (string), and "discount" (string).');- }-- const baseUrl = context.auth.props.base_url.replace(/\/$/, '');- let errorMessages = '';-- try {- const lineItemsWithDetailsPromises = lineItemsArray.map(async item => {- try {- const getProductDetailsResponse = await fetch(`${baseUrl}/api/v1/products/?product_key=${item.product_key}`, {- method: 'GET',- headers,- });-- if (!getProductDetailsResponse.ok) {- console.error(`Failed to get product details for ${item.product_key}. Status: ${getProductDetailsResponse.status}`);- errorMessages += `Failed to get product details for ${item.product_key}\n`;- return null;- }-- const productDetailsResponseBody = await getProductDetailsResponse.json();- const productCount = productDetailsResponseBody.meta.pagination.count;-- if (productCount < 1) {- console.error(`No product details found for ${item.product_key}.`);- errorMessages += `No product details found for ${item.product_key}\n`;- return null;- }-- const productDetails = productDetailsResponseBody.data[0];-- return {- quantity: item.quantity,- product_key: item.product_key,- product_cost: productDetails.price,- cost: productDetails.price,- notes: productDetails.notes,- discount: item.discount || '0',- is_amount_discount: context.propsValue.discount_type,- tax_name1: productDetails.tax_name1,- tax_rate1: productDetails.tax_rate1,- tax_id: productDetails.tax_id,- };- } catch (error) {- console.error(`Error getting product details for ${item.product_key}:`, error);- errorMessages += `Error getting product details for ${item.product_key}: ${error}\n`;- return null;- }- });-- const lineItemsWithDetails = await Promise.all(lineItemsWithDetailsPromises);-- if (errorMessages) {- // If there are error messages, throw an error with the accumulated messages- throw new Error(errorMessages.trim());- }-- const today = new Date();- const year = today.getFullYear();- const month = today.getMonth() + 1;- const day = today.getDate();- const formattedDate = `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`;-- const createInvoiceRequestBody = {- //status_id: 2, // seems cant set the status id when creating need another api call either using the recurring invoice ID and updating the status that way- // or possibly calling /bulk with action=start there's also an action send_now- next_send_date: context.propsValue.due_date,- date: formattedDate,- client_id: context.propsValue.client_id || '',- po_number: context.propsValue.purchase_order_no || '',- public_notes: context.propsValue.public_notes || '',- private_notes: context.propsValue.private_notes || '',- line_items: lineItemsWithDetails,- discount: context.propsValue.discount,- is_amount_discount: context.propsValue.discount_type,- frequency_id: context.propsValue.auto_frequency || context.propsValue.frequency,- remaining_cycles:context.propsValue.nocycles || -1,- };- // if remaining cycles is set to 0 it will automatically go completed -1 is endless!- // status_id 2 is pending ie start scheduling- const createInvoiceResponse = await fetch(`${baseUrl}/api/v1/recurring_invoices`, {- method: 'POST',- headers,- body: JSON.stringify(createInvoiceRequestBody),- });-- if (!createInvoiceResponse.ok) {- throw new Error(`Failed to create recurring invoice. Status: ${createInvoiceResponse.status}`);- }-- const createInvoiceResponseBody = await createInvoiceResponse.json();-- return createInvoiceResponseBody;- } catch (error) {- console.error('Error creating recurring invoice or getting product details:', error);- if (errorMessages) {- // If there are error messages, throw an error with the accumulated messages- throw new Error(errorMessages.trim());- } else {- // If there are no error messages, throw the original error- throw error;- }- }- },- });\ No newline at end of file+ auth: invoiceninjaAuth,+ name: 'create_recurring_invoice',+ classification: 'WRITE',+ displayName: 'Create Recurring Invoice',+ description: 'Creates a recurring invoice from existing products on a billing schedule.',+ audience: 'human',+ outputSchema: invoiceNinjaOutputSchemas.legacyRecurringCreated,+ props: {+ client_id: LEGACY_PROPS.client_id,+ purchase_order_no: LEGACY_PROPS.purchase_order_no,+ discount: LEGACY_PROPS.discount,+ discount_type: LEGACY_PROPS.discount_type,+ public_notes: LEGACY_PROPS.public_notes,+ private_notes: LEGACY_PROPS.private_notes,+ order_items_json: LEGACY_PROPS.order_items_json,+ frequency: Property.StaticDropdown({+ displayName: 'Frequency of billing',+ description: 'How often an invoice is generated.',+ defaultValue: 5,+ required: true,+ options: {+ options: [+ { label: 'Use override below', value: 0 },+ { label: 'Daily', value: 1 },+ { label: 'Weekly', value: 2 },+ { label: '2 Weeks', value: 3 },+ { label: '4 Weeks', value: 4 },+ { label: 'Monthly', value: 5 },+ { label: 'Two Months', value: 6 },+ { label: 'Quarterly', value: 7 },+ { label: 'Four Months', value: 8 },+ { label: 'Semi Annually', value: 9 },+ { label: 'Annually', value: 10 },+ { label: 'Two Years', value: 11 },+ { label: 'Three Years', value: 12 },+ ],+ },+ }),+ nocycles: Property.Number({+ displayName: 'Number of billing cycles',+ description: 'How many invoices to generate. Empty = endless.',+ required: false,+ }),+ auto_frequency: Property.Number({+ displayName: 'Override Frequency ID',+ description: 'When set, this wins over Frequency: 1-12 (Daily 1, Weekly 2, ...).',+ required: false,+ }),+ due_date: Property.DateTime({+ displayName: 'Next send date',+ description: 'Date the first invoice is generated, e.g. 2024-01-20.',+ required: true,+ }),+ last_date: Property.DateTime({+ displayName: 'Last sent date',+ description: 'Optional, e.g. 2024-01-20.',+ required: false,+ }),+ },+ async run({ auth, propsValue }) {+ const clientId = invoiceNinjaClient.parseId({ value: propsValue.client_id, label: 'Client' });+ const nextSendDate = invoiceNinjaClient.toDateOnly({ value: propsValue.due_date, label: 'Next send date' });+ if (nextSendDate === undefined) throw new Error('Next send date is required.');+ const lastSentDate = invoiceNinjaClient.toDateOnly({ value: propsValue.last_date, label: 'Last sent date' });+ const cycles = invoiceNinjaClient.optionalInt({ value: propsValue.nocycles, label: 'Number of billing cycles', min: 0, max: 999 });+ const override = invoiceNinjaClient.optionalInt({ value: propsValue.auto_frequency, label: 'Override Frequency ID', min: 1, max: 12 });+ const frequency = override ?? propsValue.frequency;+ if (frequency === undefined || frequency < 1 || frequency > 12) {+ throw new Error('Choose a billing frequency, or enter an Override Frequency ID (1-12) with "Use override below".');+ }+ const discount = invoiceNinjaClient.optionalNumber({ value: propsValue.discount, label: 'Invoice Discount', min: 0 }) ?? 0;+ const isAmountDiscount = propsValue.discount_type !== false;+ const lineItems = await invoiceNinjaLegacy.lineItemsFromProducts({ auth: auth.props, json: propsValue.order_items_json, isAmountDiscount });+ const body = invoiceNinjaClient.compact({+ client_id: clientId,+ next_send_date: nextSendDate,+ last_sent_date: lastSentDate,+ po_number: invoiceNinjaClient.optionalText(propsValue.purchase_order_no),+ public_notes: invoiceNinjaClient.optionalText(propsValue.public_notes),+ private_notes: invoiceNinjaClient.optionalText(propsValue.private_notes),+ line_items: lineItems,+ discount,+ is_amount_discount: isAmountDiscount,+ frequency_id: String(frequency),+ remaining_cycles: cycles ?? -1,+ });+ return invoiceNinjaClient.envelopeOf(+ await invoiceNinjaClient.request({ auth: auth.props, method: HttpMethod.POST, path: '/recurring_invoices', body }),+ );+ },+});diff --git a/packages/pieces/community/invoiceninja/src/lib/actions/create-task.ts b/packages/pieces/community/invoiceninja/src/lib/actions/create-task.tsindex a78a9b085af..438e3603d3a 100644--- a/packages/pieces/community/invoiceninja/src/lib/actions/create-task.ts+++ b/packages/pieces/community/invoiceninja/src/lib/actions/create-task.ts@@ -1,71 +1,44 @@-import {- createAction,- Property,-} from '@activepieces/pieces-framework';-import { httpClient, HttpMethod } from '@activepieces/pieces-common';-import { invoiceninjaAuth } from '../..';+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { invoiceninjaAuth } from '../common/auth';+import { invoiceNinjaClient } from '../common/client';+import { invoiceNinjaOutputSchemas } from '../common/output-schemas';+import { invoiceNinjaProps } from '../common/props';+import { invoiceNinjaTaskHelpers } from './ai/tasks-reports';+export const createTask = createAction({auth: invoiceninjaAuth,name: 'create_task',classification: 'WRITE',displayName: 'Create Task',- description: 'Creates a task instance in Invoice Ninja for billing purposes.',- audience: 'both',- aiMetadata: { description: 'Creates a billable task in Invoice Ninja, identified by a task/ticket number that must be unique (not previously used). Optionally associates the task with a client and project and applies a custom hourly rate. Not idempotent — each call creates a new task.', idempotent: false },-+ description: 'Creates a billable task in Invoice Ninja.',+ audience: 'human',+ outputSchema: invoiceNinjaOutputSchemas.legacyTaskCreated,props: {- number: Property.LongText({- displayName: 'Task or Ticket Number (alphanumeric)',- description:- 'A unique task or ticket number that has not been used before in Invoice Ninja',+ number: Property.ShortText({+ displayName: 'Task or Ticket Number',+ description: 'A task or ticket number not used before in Invoice Ninja.',required: true,}),- client_id: Property.LongText({- displayName: 'Client ID (alphanumeric)',- description: 'Client ID from Invoice Ninja (optional)',- required: false,- }),- project_id: Property.LongText({- displayName: 'Project ID (alphanumeric)',- description: 'Project ID from Invoice Ninja (optional)',- required: false,- }),+ client_id: invoiceNinjaProps.clientDropdown({ required: false }),+ project_id: invoiceNinjaProps.projectDropdown({ required: false }),description: Property.LongText({- displayName: 'Description of task',- description: 'Description of task to be billed',+ displayName: 'Description',+ description: 'What the task is about.',required: true,}),rate: Property.Number({- displayName: 'Custom hourly rate',- description: 'Custom hourly rate (optional) otherwise default used',+ displayName: 'Custom Hourly Rate',+ description: 'Leave empty to use the default rate.',required: false,}),},-- async run(context) {- const INapiToken = context.auth.props.access_token;-- const headers = {- 'X-Api-Token': INapiToken,- };- const queryParams = new URLSearchParams();- queryParams.append('number', context.propsValue.number || '');- queryParams.append('client_id', context.propsValue.client_id || '');- queryParams.append('project_id', context.propsValue.project_id || '');- queryParams.append('description', context.propsValue.description || '');- // bugfix - only append rate if a rate has been specified in the piece- if (context.propsValue.rate?.valueOf != null) {- queryParams.append('rate', context.propsValue.rate?.toString() || '0');- }- // Remove trailing slash from base_url- const baseUrl = context.auth.props.base_url.replace(/\/$/, '');- const url = `${baseUrl}/api/v1/tasks?${queryParams.toString()}`;- const httprequestdata = {- method: HttpMethod.POST,- url,- headers,- };- const response = await httpClient.sendRequest(httprequestdata);- return response.body;+ async run({ auth, propsValue }) {+ const body = invoiceNinjaTaskHelpers.taskBody(propsValue);+ if (body['description'] === undefined) throw new Error('Description is required.');+ if (body['number'] === undefined) throw new Error('Task or Ticket Number is required.');+ return invoiceNinjaClient.envelopeOf(+ await invoiceNinjaClient.request({ auth: auth.props, method: HttpMethod.POST, path: '/tasks', body }),+ );},});diff --git a/packages/pieces/community/invoiceninja/src/lib/actions/get-client.ts b/packages/pieces/community/invoiceninja/src/lib/actions/get-client.tsindex 8911a95b2ab..b94e20f65fb 100644--- a/packages/pieces/community/invoiceninja/src/lib/actions/get-client.ts+++ b/packages/pieces/community/invoiceninja/src/lib/actions/get-client.ts@@ -1,105 +1,63 @@-import {- createAction,- Property,-} from '@activepieces/pieces-framework';-import { httpClient, HttpMethod, propsValidation } from '@activepieces/pieces-common';-import * as z from 'zod/mini'-import { invoiceninjaAuth } from '../..';+import { createAction, Property } from '@activepieces/pieces-framework';+import { invoiceninjaAuth } from '../common/auth';+import { invoiceNinjaClient } from '../common/client';+import { invoiceNinjaOutputSchemas } from '../common/output-schemas';export const getClient = createAction({auth: invoiceninjaAuth,name: 'getclient_task',classification: 'READ',displayName: 'Get Client Details from e-mail',- description: 'Gets the client details if they exist by e-mail.',- audience: 'both',- aiMetadata: { description: 'Looks up a client in Invoice Ninja by email address and returns a trimmed set of their details (id, name, balances, address, contacts). Use to resolve a client id or fetch client info from an email; returns a falsy result when no matching client is found. Read-only and idempotent.', idempotent: true },-+ description: 'Gets the client whose contact has this e-mail. Returns false when there is none.',+ audience: 'human',+ outputSchema: invoiceNinjaOutputSchemas.legacyClient,props: {- email: Property.LongText({- displayName: 'Client e-mail address',- description: 'A valid e-mail address to get client details for',+ email: Property.ShortText({+ displayName: 'Client e-mail address',+ description: 'The e-mail address of one of the client\'s contacts.',required: true,}),},-- async run(context) {- await propsValidation.validateZod(context.propsValue, {- email: z.string().check(z.email()),- });-- const INapiToken = context.auth.props.access_token;-- const headers = {- 'X-Api-Token': INapiToken,- };- const queryParams = new URLSearchParams();- queryParams.append('email', context.propsValue.email || '');-- // Remove trailing slash from base_url- const baseUrl = context.auth.props.base_url.replace(/\/$/, '');- const url = `${baseUrl}/api/v1/clients/?${queryParams.toString()}`;- const httprequestdata = {- method: HttpMethod.GET,- url,- headers,- };-- try {- const response = await httpClient.sendRequest(httprequestdata);- // Process the successful response here (status 2xx).- //- if (response.body.meta.pagination.total > 0) {- // Each client that is found will have one or more contacts- const NumberOfContactsThisClient =- response.body.data[0].contacts.length;- for (let i = 0; i < NumberOfContactsThisClient; i++) {- // theres a lot of extra data I don't really want in the actual response of contacts so I want to tr and just pick out- // firstname, lastname, email, etc as I don't think we need the rest, just to keep it simpler- delete response.body.data[0].contacts[i].id;- delete response.body.data[0].contacts[i].created_at;- delete response.body.data[0].contacts[i].updated_at;- delete response.body.data[0].contacts[i].archived_at;- delete response.body.data[0].contacts[i].is_primary;- delete response.body.data[0].contacts[i].is_locked;- delete response.body.data[0].contacts[i].contact_key;- delete response.body.data[0].contacts[i].send_email;- delete response.body.data[0].contacts[i].last_login;- delete response.body.data[0].contacts[i].password;- delete response.body.data[0].contacts[i].link;- }- const json = [- {- client_no_contacts: NumberOfContactsThisClient,- client_id: response.body.data[0].id,- client_name: response.body.data[0].name,- client_web: response.body.data[0].website,- client_private_notes: response.body.data[0].private_notes,- client_balance: response.body.data[0].balance,- client_paid_to_date: response.body.data[0].paid_to_date,- client_payment_balance: response.body.data[0].payment_balance,- client_credit_balance: response.body.data[0].credit_balance,- client_public_notes: response.body.data[0].public_notes,- client_address1: response.body.data[0].address1,- client_address2: response.body.data[0].address2,- client_phone: response.body.data[0].phone,- client_city: response.body.data[0].city,- client_state: response.body.data[0].state,- client_postcode: response.body.data[0].postal_code,- client_vat: response.body.data[0].vat_number,- client_display_name: response.body.data[0].display_name,- client_contacts: response.body.data[0].contacts,- //meta: response.body.meta,- },- ];- return json;- return true;- } else {- return false;- } // this is still returned so if it is false we'll return notfound or similar- } catch (error) {- // Handle the error when the request fails (status other than 2xx).- return 'There was a problem getting information from your Invoice Ninja';+ async run({ auth, propsValue }) {+ const email = invoiceNinjaClient.optionalText(propsValue.email);+ if (email === undefined || !/^[^\s@]+@[^\s@]+$/.test(email)) {+ throw new Error('Client e-mail address must be a valid e-mail address.');}+ const result = await invoiceNinjaClient.listPage({ auth: auth.props, entity: 'clients', query: { email }, page: 1, perPage: 1 });+ const client = result.items.find(invoiceNinjaClient.isRecord);+ if (!client) return false;+ const contacts = invoiceNinjaClient.arrayOf(client['contacts']).filter(invoiceNinjaClient.isRecord);+ return [+ {+ client_no_contacts: contacts.length,+ client_id: client['id'],+ client_name: client['name'],+ client_web: client['website'],+ client_private_notes: client['private_notes'],+ client_balance: client['balance'],+ client_paid_to_date: client['paid_to_date'],+ client_payment_balance: client['payment_balance'],+ client_credit_balance: client['credit_balance'],+ client_public_notes: client['public_notes'],+ client_address1: client['address1'],+ client_address2: client['address2'],+ client_phone: client['phone'],+ client_city: client['city'],+ client_state: client['state'],+ client_postcode: client['postal_code'],+ client_vat: client['vat_number'],+ client_display_name: client['display_name'],+ client_contacts: contacts.map((contact) => ({+ first_name: contact['first_name'],+ last_name: contact['last_name'],+ email: contact['email'],+ phone: contact['phone'],+ custom_value1: contact['custom_value1'],+ custom_value2: contact['custom_value2'],+ custom_value3: contact['custom_value3'],+ custom_value4: contact['custom_value4'],+ })),+ },+ ];},});diff --git a/packages/pieces/community/invoiceninja/src/lib/actions/get-invoices.ts b/packages/pieces/community/invoiceninja/src/lib/actions/get-invoices.tsindex 4e070f60b09..d70923b2d8e 100644--- a/packages/pieces/community/invoiceninja/src/lib/actions/get-invoices.ts+++ b/packages/pieces/community/invoiceninja/src/lib/actions/get-invoices.ts@@ -1,16 +1,19 @@-// action to return invoices from InvoiceNinja with filtering by invoice status and client idimport { createAction, Property } from '@activepieces/pieces-framework';-import { httpClient, HttpMethod } from '@activepieces/pieces-common';-import { invoiceninjaAuth } from '../..';+import { invoiceninjaAuth } from '../common/auth';+import { invoiceNinjaClient } from '../common/client';+import { invoiceNinjaOutputSchemas } from '../common/output-schemas';+import { invoiceNinjaProps } from '../common/props';++const MAX_RESULTS = 9999;+export const getInvoices = createAction({auth: invoiceninjaAuth,name: 'getinvoices_task',classification: 'SEARCH',displayName: 'Get Invoices',- description: 'Gets data for invoices.',- audience: 'both',- aiMetadata: { description: 'Retrieves invoices from Invoice Ninja filtered by status (unpaid, paid, overdue, or all) and optionally by client id, capped by a max-results limit. Use to list or report on invoices; omitting the client id returns invoices across all clients. Read-only and idempotent.', idempotent: true },-+ description: 'Gets invoices by payment status, optionally for one client. Returns false when none match.',+ audience: 'human',+ outputSchema: invoiceNinjaOutputSchemas.legacyInvoices,props: {invoiceStatus: Property.StaticDropdown({displayName: 'Invoice Status',@@ -18,114 +21,62 @@ export const getInvoices = createAction({required: true,options: {options: [- {- label: 'Unpaid Invoices',- value: 'unpaid',- },- {- label: 'Paid Invoices',- value: 'paid',- },- {- label: 'Overdue Invoices',- value: 'overdue',- },- {- label: 'All Invoices',- value: 'all',- },+ { label: 'Unpaid Invoices', value: 'unpaid' },+ { label: 'Paid Invoices', value: 'paid' },+ { label: 'Overdue Invoices', value: 'overdue' },+ { label: 'All Invoices', value: 'all' },],},}),- clientID: Property.LongText({- displayName: 'Client ID',- description: 'Filter by Client ID, default is all clients.',- required: false,- }),+ clientID: invoiceNinjaProps.clientDropdown({ required: false, displayName: 'Client' }),numberOfResults: Property.Number({displayName: 'Max Results',- description: 'Maximum number of results to return. 9999 is default.',+ description: `Maximum number of invoices to return (1-${MAX_RESULTS}). Default ${MAX_RESULTS}.`,required: false,}),},-- async run(context) {- const INapiToken = context.auth.props.access_token;-- const headers = {- 'X-Api-Token': INapiToken,- };-- const queryParams = new URLSearchParams();- queryParams.append(- 'client_status',- context.propsValue.invoiceStatus || 'unpaid'- );- // only include client_id in the query parameters if it has been specified- if (- context.propsValue.clientID?.valueOf != null ||- context.propsValue.clientID != undefined- ) {- queryParams.append('client_id', context.propsValue.clientID || '');- }- queryParams.append('is_deleted', 'false'); // only return invoices that are not deleted- queryParams.append(- 'per_page',- context.propsValue.numberOfResults?.toString() || '9999'- ); // otherwise it only returns 20 per page hopefully-- // Remove trailing slash from base_url- const baseUrl = context.auth.props.base_url.replace(/\/$/, '');- const url = `${baseUrl}/api/v1/invoices/?${queryParams.toString()}`;- // console.log("INVOICENINJA: " + url);- const httprequestdata = {- method: HttpMethod.GET,- url,- headers,- };-- try {- const response = await httpClient.sendRequest(httprequestdata);- const my = [];- // Process the response here (status 2xx).- if (response.body.meta.pagination.total > 0) {- // Each invoice that is found will have lots of information, lets remove the guff- // changed from .total to .count because we're only interested in those in the first page of results which- // is what we set the per_page to to correspond to the number of records we wanted- const NumberOfInvoices = response.body.meta.pagination.count;-- for (let i = 0; i < NumberOfInvoices; i++) {- my.push({- invoice: {- clientid: response.body.data[i].client_id,- invoiceno: response.body.data[i].number,- ponumber: response.body.data[i].po_number,- invdate: response.body.data[i].date,- duedate: response.body.data[i].due_date,- punote: response.body.data[i].public_notes,- prnote: response.body.data[i].private_notes,- reminder1: response.body.data[i].reminder1_sent,- reminder2: response.body.data[i].reminder2_sent,- reminder3: response.body.data[i].reminder3_sent,- lastreminder: response.body.data[i].reminder_last_sent,- firstsku: response.body.data[i].line_items[0].product_key,- firstitem: response.body.data[i].line_items[0].notes,- amount: response.body.data[i].amount,- balance: response.body.data[i].balance,- paid: response.body.data[i].paid_to_date,- },- });- // console.log("INVOICENINJA: (" + i.toString() + ") " + response.body.data[i].amount);- }- return my;- } else {- return false;- } // this is still returned so if it is false we'll return notfound or similar- } catch (error) {- // Handle the error when the request fails (status other than 2xx).- // console.log((error as Error).message);- return (error as Error).message;- // return "There was a problem getting information from your Invoice Ninja";+ async run({ auth, propsValue }) {+ const limit = invoiceNinjaClient.optionalInt({ value: propsValue.numberOfResults, label: 'Max Results', min: 1, max: MAX_RESULTS }) ?? MAX_RESULTS;+ const clientId = invoiceNinjaClient.optionalId({ value: propsValue.clientID, label: 'Client' });+ const collected: unknown[] = [];+ let page = 1;+ let hasMore = true;+ while (hasMore && collected.length < limit) {+ const result = await invoiceNinjaClient.listPage({+ auth: auth.props,+ entity: 'invoices',+ query: { client_status: propsValue.invoiceStatus || 'unpaid', client_id: clientId, is_deleted: 'false' },+ page,+ perPage: 100,+ });+ collected.push(...result.items);+ hasMore = result.hasMore && result.items.length > 0;+ page += 1;}+ const invoices = collected.slice(0, limit).filter(invoiceNinjaClient.isRecord);+ if (invoices.length === 0) return false;+ return invoices.map((invoice) => {+ const first = invoiceNinjaClient.arrayOf(invoice['line_items']).find(invoiceNinjaClient.isRecord);+ return {+ invoice: {+ clientid: invoice['client_id'],+ invoiceno: invoice['number'],+ ponumber: invoice['po_number'],+ invdate: invoice['date'],+ duedate: invoice['due_date'],+ punote: invoice['public_notes'],+ prnote: invoice['private_notes'],+ reminder1: invoice['reminder1_sent'],+ reminder2: invoice['reminder2_sent'],+ reminder3: invoice['reminder3_sent'],+ lastreminder: invoice['reminder_last_sent'],+ firstsku: first ? first['product_key'] : null,+ firstitem: first ? first['notes'] : null,+ amount: invoice['amount'],+ balance: invoice['balance'],+ paid: invoice['paid_to_date'],+ },+ };+ });},});diff --git a/packages/pieces/community/invoiceninja/src/lib/actions/get-report.ts b/packages/pieces/community/invoiceninja/src/lib/actions/get-report.tsindex e7c39e060e3..29474c1f6d9 100644--- a/packages/pieces/community/invoiceninja/src/lib/actions/get-report.ts+++ b/packages/pieces/community/invoiceninja/src/lib/actions/get-report.ts@@ -1,114 +1,42 @@-// action to return reports from InvoiceNinja with filteringimport { createAction, Property } from '@activepieces/pieces-framework';-import { httpClient, HttpMethod } from '@activepieces/pieces-common';-import { invoiceninjaAuth } from '../..';+import { invoiceninjaAuth } from '../common/auth';+import { invoiceNinjaClient } from '../common/client';+import { invoiceNinjaOutputSchemas } from '../common/output-schemas';+import { invoiceNinjaProps } from '../common/props';+import { invoiceNinjaReports } from '../common/report';+export const getReport = createAction({auth: invoiceninjaAuth,name: 'getreport_task',classification: 'SEARCH',displayName: 'Get Report',- description: 'Gets report data from InvoiceNinja.',- audience: 'both',- aiMetadata: { description: 'Fetches report data from Invoice Ninja for the selected report type (currently invoices) over a fixed last-7-days range, capped by a max-results limit. Use to pull aggregated invoice report data. Read-only and idempotent.', idempotent: true },-+ description: 'Runs an Invoice Ninja report and returns its columns and rows.',+ audience: 'human',+ outputSchema: invoiceNinjaOutputSchemas.report,props: {- reportType: Property.StaticDropdown({- displayName: 'Report Type',- description: 'Select the report type.',- required: true,- options: {- options: [- {- label: 'Invoices',- value: 'invoices',- },- ],- },- }),- clientID: Property.LongText({- displayName: 'Client ID',- description: 'Filter by Client ID, default is all clients.',- required: false,- }),+ reportType: invoiceNinjaReports.reportProps().report_type,+ dateRange: invoiceNinjaReports.reportProps().date_range,+ startDate: invoiceNinjaReports.reportProps().start_date,+ endDate: invoiceNinjaReports.reportProps().end_date,+ clientID: invoiceNinjaProps.clientDropdown({ required: false, displayName: 'Client' }),numberOfResults: Property.Number({- displayName: 'Max Results',- description: 'Maximum number of results to return. 9999 is default.',+ displayName: 'Max Rows',+ description: 'Return at most this many rows. Empty = all.',required: false,}),},-- async run(context) {- const INapiToken = context.auth.props.access_token;-- const headers = {- 'X-Api-Token': INapiToken,- serializers: 'JSON',- 'Content-Type': 'application/json',- };-- const report_keys = JSON.stringify(['client', 'name', 'date']);- const queryParams = new URLSearchParams();- queryParams.append('report_keys', report_keys);- queryParams.append('date_range', 'last7');- // date range - last7, last_quarter, last_year etc..- queryParams.append(- 'per_page',- context.propsValue.numberOfResults?.toString() || '9999'- ); // otherwise it only returns 20 per page hopefully-- // Remove trailing slash from base_url- const baseUrl = context.auth.props.base_url.replace(/\/$/, '');- const url = `${baseUrl}/api/v1/reports/${- context.propsValue.reportType- }?${queryParams.toString()}`;- // console.log("INVOICENINJA: " + url);- const httprequestdata = {- method: HttpMethod.GET,- url,- headers,- };-- try {- const response = await httpClient.sendRequest(httprequestdata);- const my = [];- // Process the response here (status 2xx).- if (response.body.meta.pagination.total > 0) {- return response.body;-- const NumberOfInvoices = response.body.meta.pagination.count;-- for (let i = 0; i < NumberOfInvoices; i++) {- my.push({- invoice: {- clientid: response.body.data[i].client_id,- invoiceno: response.body.data[i].number,- ponumber: response.body.data[i].po_number,- invdate: response.body.data[i].date,- duedate: response.body.data[i].due_date,- punote: response.body.data[i].public_notes,- prnote: response.body.data[i].private_notes,- reminder1: response.body.data[i].reminder1_sent,- reminder2: response.body.data[i].reminder2_sent,- reminder3: response.body.data[i].reminder3_sent,- lastreminder: response.body.data[i].reminder_last_sent,- firstsku: response.body.data[i].line_items[0].product_key,- firstitem: response.body.data[i].line_items[0].notes,- amount: response.body.data[i].amount,- balance: response.body.data[i].balance,- paid: response.body.data[i].paid_to_date,- },- });- // console.log("INVOICENINJA: (" + i.toString() + ") " + response.body.data[i].amount);- }- return my;- } else {- return false;- } // this is still returned so if it is false we'll return notfound or similar- } catch (error) {- // Handle the error when the request fails (status other than 2xx).- // console.log((error as Error).message);- return (error as Error).message;- // return "There was a problem getting information from your Invoice Ninja";- }+ async run({ auth, propsValue }) {+ const limit = invoiceNinjaClient.optionalInt({ value: propsValue.numberOfResults, label: 'Max Rows', min: 1, max: 100000 });+ const report = await invoiceNinjaReports.runReport({+ auth: auth.props,+ reportType: propsValue.reportType ?? '',+ dateRange: propsValue.dateRange ?? 'all',+ startDate: propsValue.startDate,+ endDate: propsValue.endDate,+ clientId: propsValue.clientID,+ });+ if (limit === undefined || report.rows.length <= limit) return report;+ const rows = report.rows.slice(0, limit);+ return { ...report, rows, rowCount: rows.length };},});diff --git a/packages/pieces/community/invoiceninja/src/lib/actions/task-exists.ts b/packages/pieces/community/invoiceninja/src/lib/actions/task-exists.tsindex a7873782881..1c5851ce951 100644--- a/packages/pieces/community/invoiceninja/src/lib/actions/task-exists.ts+++ b/packages/pieces/community/invoiceninja/src/lib/actions/task-exists.ts@@ -1,56 +1,34 @@import { createAction, Property } from '@activepieces/pieces-framework';-import { httpClient, HttpMethod } from '@activepieces/pieces-common';-import { invoiceninjaAuth } from '../..';-// 05/09/23 - returns 1 or 0 instead of true or false as was having issues+import { invoiceninjaAuth } from '../common/auth';+import { invoiceNinjaClient } from '../common/client';+import { invoiceNinjaOutputSchemas } from '../common/output-schemas';+export const existsTask = createAction({auth: invoiceninjaAuth,name: 'exists_task',classification: 'READ',displayName: 'Check Task Existence',- description: 'Verify if a Task Already Exists',- audience: 'both',- aiMetadata: { description: 'Checks whether a task with the given task/ticket number already exists in Invoice Ninja, returning a truthy/falsy result. Use to guard against duplicate task creation before calling Create Task. Read-only and idempotent.', idempotent: true },+ description: 'Returns 1 if a task with this number exists, 0 if not.',+ audience: 'human',+ outputSchema: invoiceNinjaOutputSchemas.taskExists,props: {- number: Property.LongText({- displayName: 'Task or Ticket Number (alphanumeric)',- description: 'A task or ticket number to check',+ number: Property.ShortText({+ displayName: 'Task or Ticket Number',+ description: 'The task or ticket number to check.',required: true,}),},-- async run(context) {- const INapiToken = context.auth.props.access_token;-- const headers = {- 'X-Api-Token': INapiToken,- };-- const queryParams = new URLSearchParams();- // number=context.propsValue.number - last update 'number' was also on the const url which- // was incorrect- queryParams.append('number', context.propsValue.number || '');-- // Remove trailing slash from base_url- const baseUrl = context.auth.props.base_url.replace(/\/$/, '');- const url = `${baseUrl}/api/v1/tasks?${queryParams.toString()}`;- const httprequestdata = {- method: HttpMethod.GET,- url,- headers,- };- try {- const response = await httpClient.sendRequest(httprequestdata);- // meta data only present if ticket exists. had issues testing true and false on- // branch piece so switched to 1 and 0 respectively instead to see if that works- // better.- if (response.body.meta.pagination.total > 0) {- return 1;- } else {- return 0;- }- } catch (error) {- // Handle the error when the request fails (status other than 2xx).- return 'There was a problem getting information from your Invoice Ninja';- }+ async run({ auth, propsValue }) {+ const number = invoiceNinjaClient.optionalText(propsValue.number);+ if (number === undefined) throw new Error('Task or Ticket Number is required.');+ const result = await invoiceNinjaClient.listPage({+ auth: auth.props,+ entity: 'tasks',+ query: { number, status: 'active,archived' },+ page: 1,+ perPage: 100,+ });+ const found = result.items.some((item) => invoiceNinjaClient.isRecord(item) && item['number'] === number);+ return found ? 1 : 0;},});diff --git a/packages/pieces/community/invoiceninja/src/lib/common/auth.ts b/packages/pieces/community/invoiceninja/src/lib/common/auth.tsnew file mode 100644index 00000000000..7a039241da4--- /dev/null+++ b/packages/pieces/community/invoiceninja/src/lib/common/auth.ts@@ -0,0 +1,49 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { PieceAuth, Property } from '@activepieces/pieces-framework';+import { InvoiceNinjaApiError, invoiceNinjaClient } from './client';++export const invoiceninjaAuth = PieceAuth.CustomAuth({+ description: `+ To connect Invoice Ninja (v5):++ 1. Log in to Invoice Ninja (https://invoicing.co or your self-hosted server).+ 2. Open **Settings > Account Management > API Tokens** and create a token.+ 3. Paste the token below. Base URL is https://invoicing.co for the hosted service, or the address of your own server (for example https://invoices.example.com).+ `,+ props: {+ base_url: Property.ShortText({+ displayName: 'Base URL',+ description: 'https://invoicing.co for the hosted service, or your self-hosted address such as https://invoices.example.com',+ required: true,+ }),+ access_token: PieceAuth.SecretText({+ displayName: 'API Token',+ description: 'Settings > Account Management > API Tokens in Invoice Ninja.',+ required: true,+ }),+ },+ validate: async ({ auth }) => {+ try {+ invoiceNinjaClient.normalizeBaseUrl(auth.base_url);+ invoiceNinjaClient.tokenOf(auth);+ } catch (error) {+ return { valid: false, error: error instanceof Error ? error.message : 'Invalid connection.' };+ }+ try {+ const body = await invoiceNinjaClient.request({ auth, method: HttpMethod.GET, path: '/ping' });+ if (!invoiceNinjaClient.isRecord(body) || typeof body['company_name'] !== 'string') {+ return { valid: false, error: 'The Base URL does not point to an Invoice Ninja v5 server.' };+ }+ return { valid: true };+ } catch (error) {+ if (error instanceof InvoiceNinjaApiError && (error.status === 401 || error.status === 403)) {+ return { valid: false, error: 'Invalid API Token.' };+ }+ return {+ valid: false,+ error: error instanceof Error ? `Could not reach Invoice Ninja: ${error.message}` : 'Could not reach Invoice Ninja.',+ };+ }+ },+ required: true,+});diff --git a/packages/pieces/community/invoiceninja/src/lib/common/client.ts b/packages/pieces/community/invoiceninja/src/lib/common/client.tsnew file mode 100644index 00000000000..77b66dadc76--- /dev/null+++ b/packages/pieces/community/invoiceninja/src/lib/common/client.ts@@ -0,0 +1,408 @@+import { httpClient, HttpMethod, HttpResponse, QueryParams } from '@activepieces/pieces-common';++const REQUEST_TIMEOUT_MS = 30_000;+const ID_PATTERN = /^[A-Za-z0-9]{1,64}$/;+let verifiedTlsAgent: Promise<unknown> | undefined;++export class InvoiceNinjaApiError extends Error {+ constructor(+ message: string,+ public readonly status: number,+ public readonly responseBody: unknown,+ ) {+ super(message);+ this.name = 'InvoiceNinjaApiError';+ }+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return value !== null && typeof value === 'object' && !Array.isArray(value);+}++function arrayOf(value: unknown): unknown[] {+ return Array.isArray(value) ? value : [];+}++function normalizeBaseUrl(raw: unknown): string {+ const text = typeof raw === 'string' ? raw.trim() : '';+ if (!text) {+ throw new Error('The Invoice Ninja connection has no Base URL.');+ }+ let parsed: URL;+ try {+ parsed = new URL(text);+ } catch {+ throw new Error('The Base URL is not a valid URL. Use a full address like https://invoicing.co or https://invoices.example.com.');+ }+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {+ throw new Error('The Base URL must start with https:// (or http:// for a self-hosted server).');+ }+ if (parsed.username || parsed.password) {+ throw new Error('The Base URL must not contain a username or password.');+ }+ if (parsed.search || parsed.hash || text.includes('?') || text.includes('#')) {+ throw new Error('The Base URL must not contain a query string or fragment.');+ }+ const segments = parsed.pathname.split('/').filter((part) => part !== '');+ if (/\/\.{1,2}(\/|$)|%2e/i.test(text) || segments.some((part) => part.includes('%'))) {+ throw new Error('The Base URL must not contain relative or encoded path segments.');+ }+ const path = `/${segments.join('/')}`.replace(/\/api\/v1$/i, '').replace(/\/+$/, '');+ return `${parsed.origin}${path}`;+}++function apiBaseUrl(raw: unknown): string {+ return `${normalizeBaseUrl(raw)}/api/v1`;+}++function tokenOf(auth: InvoiceNinjaAuthValue): string {+ const token = typeof auth.access_token === 'string' ? auth.access_token.trim() : '';+ if (!token) {+ throw new Error('The Invoice Ninja connection has no API Token.');+ }+ return token;+}++function authHeaders(auth: InvoiceNinjaAuthValue): Record<string, string> {+ return {+ 'X-API-TOKEN': tokenOf(auth),+ 'X-Requested-With': 'XMLHttpRequest',+ Accept: 'application/json',+ };+}++function isSameOrigin({ url, baseUrl }: { url: string; baseUrl: string }): boolean {+ let parsed: URL;+ try {+ parsed = new URL(url);+ } catch {+ return false;+ }+ if (parsed.username || parsed.password) return false;+ const base = new URL(baseUrl);+ if (parsed.origin !== base.origin) return false;+ const basePath = base.pathname.replace(/\/+$/, '');+ if (basePath === '') return true;+ return parsed.pathname === basePath || parsed.pathname.startsWith(`${basePath}/`);+}++function vendorMessage(body: unknown): string {+ if (isRecord(body)) {+ const message = typeof body['message'] === 'string' ? body['message'].trim() : '';+ const errors = isRecord(body['errors'])+ ? Object.entries(body['errors'])+ .map(([field, value]) => `${field}: ${arrayOf(value).filter((item): item is string => typeof item === 'string').map((item) => item.replace(/\.+$/, '')).join(' ')}`)+ .join('; ')+ : '';+ const notFound = /^No query results for model/i.test(message) ? 'record not found' : message;+ const combined = [notFound.replace(/\.+$/, ''), errors].filter((part) => part !== '').join('. ');+ if (combined) return combined.slice(0, 500);+ }+ if (typeof body === 'string' && body.trim()) return body.trim().slice(0, 300);+ return 'request failed';+}++function hintFor({ status, body }: { status: number; body: unknown }): string {+ const notFound = isRecord(body) && typeof body['message'] === 'string' && /^No query results for model/i.test(body['message']);+ if (status === 401 || status === 403) return ' Check the API Token in the Invoice Ninja connection.';+ if (status === 404 || notFound) return ' Check the Base URL and the ID.';+ if (status === 429) return ' Invoice Ninja rate limit reached, try again later.';+ return '';+}++function toApiError({ status, body }: { status: number; body: unknown }): InvoiceNinjaApiError {+ const base = status >= 300 && status < 400 ? 'unexpected redirect (check the Base URL)' : vendorMessage(body);+ return new InvoiceNinjaApiError(`Invoice Ninja API error (${status}): ${base}.${hintFor({ status, body })}`, status, body);+}++function verifiedTls(): Promise<unknown> {+ verifiedTlsAgent ??= import('undici').then(({ Agent }) => new Agent({ connect: { rejectUnauthorized: true } }));+ return verifiedTlsAgent;+}++function failureOf(error: unknown): { status: number; body: unknown } | null {+ if (error === null || typeof error !== 'object') return null;+ const response = Reflect.get(error, 'response');+ if (!isRecord(response)) return null;+ const status = response['status'];+ return typeof status === 'number' ? { status, body: response['body'] } : null;+}++function buildQuery(query?: QueryInput): QueryParams {+ return Object.fromEntries(+ Object.entries(query ?? {})+ .filter(([, value]) => value !== undefined && value !== '')+ .map(([key, value]) => [key, String(value)]),+ );+}++async function request({ auth, method, path, query, body, timeoutMs }: InvoiceNinjaRequest): Promise<unknown> {+ const baseUrl = apiBaseUrl(auth.base_url);+ const headers = authHeaders(auth);+ const hasBody = body !== undefined;+ if (hasBody) headers['Content-Type'] = 'application/json';+ const dispatcher = await verifiedTls();+ let status: number;+ let responseBody: unknown;+ try {+ const response: HttpResponse = await httpClient.sendRequest(+ {+ method,+ url: `${baseUrl}${path}`,+ headers,+ queryParams: buildQuery(query),+ body: hasBody ? body : undefined,+ timeout: Math.min(REQUEST_TIMEOUT_MS, Math.max(1, Math.floor(timeoutMs ?? REQUEST_TIMEOUT_MS))),+ followRedirects: false,+ },+ { dispatcher },+ );+ status = response.status;+ responseBody = response.body;+ } catch (error) {+ const failure = failureOf(error);+ if (!failure) throw error;+ status = failure.status;+ responseBody = failure.body;+ }+ if (status < 200 || status >= 300) {+ throw toApiError({ status, body: responseBody });+ }+ return responseBody;+}++function sanitize(value: unknown): unknown {+ if (Array.isArray(value)) return value.map(sanitize);+ if (!isRecord(value)) return value;+ return Object.fromEntries(+ Object.entries(value)+ .filter(([key]) => key !== 'password')+ .map(([key, inner]) => [key, sanitize(inner)]),+ );+}++function dataOf(body: unknown): unknown {+ return sanitize(isRecord(body) && 'data' in body ? body['data'] : body);+}++function recordOf(body: unknown): Record<string, unknown> {+ const data = dataOf(body);+ if (Array.isArray(data)) {+ const first = data[0];+ return isRecord(first) ? first : {};+ }+ return isRecord(data) ? data : {};+}++function envelopeOf(body: unknown): { data: unknown } {+ return { data: dataOf(body) };+}++async function getRecord({ auth, entity, id, include }: { auth: InvoiceNinjaAuthValue; entity: string; id: string; include?: string }): Promise<Record<string, unknown>> {+ const body = await request({ auth, method: HttpMethod.GET, path: `/${entity}/${id}`, query: { include } });+ return recordOf(body);+}++async function listPage({ auth, entity, query, page, perPage }: ListPageInput): Promise<ListPageResult> {+ const body = await request({+ auth,+ method: HttpMethod.GET,+ path: `/${entity}`,+ query: { ...query, page, per_page: perPage },+ });+ const items = arrayOf(dataOf(body));+ const meta = isRecord(body) && isRecord(body['meta']) ? body['meta'] : {};+ const pagination = isRecord(meta['pagination']) ? meta['pagination'] : {};+ const total = typeof pagination['total'] === 'number' ? pagination['total'] : items.length;+ const totalPages = typeof pagination['total_pages'] === 'number' ? pagination['total_pages'] : page;+ return { items, page, perPage, total, hasMore: page < totalPages };+}++async function bulk({ auth, entity, action, ids }: BulkInput): Promise<Record<string, unknown>> {+ const body = await request({ auth, method: HttpMethod.POST, path: `/${entity}/bulk`, body: { action, ids } });+ return recordOf(body);+}++function parseId({ value, label }: { value: unknown; label: string }): string {+ const text = typeof value === 'string' ? value.trim() : typeof value === 'number' ? String(value) : '';+ if (!ID_PATTERN.test(text)) {+ throw new Error(`${label} must be an Invoice Ninja ID (letters and digits only, e.g. VolejRejNm).`);+ }+ return text;+}++function optionalId({ value, label }: { value: unknown; label: string }): string | undefined {+ const text = optionalText(value);+ return text === undefined ? undefined : parseId({ value: text, label });+}++function optionalText(value: unknown): string | undefined {+ if (typeof value === 'number') return String(value);+ if (typeof value !== 'string') return undefined;+ const text = value.trim();+ return text === '' ? undefined : text;+}++function optionalNumber({ value, label, min, max }: { value: unknown; label: string; min?: number; max?: number }): number | undefined {+ if (value === undefined || value === null || value === '') return undefined;+ const parsed = typeof value === 'string' ? Number(value.trim()) : value;+ if (typeof parsed !== 'number' || !Number.isFinite(parsed)) {+ throw new Error(`${label} must be a number.`);+ }+ if ((min !== undefined && parsed < min) || (max !== undefined && parsed > max)) {+ throw new Error(`${label} must be between ${min ?? '-∞'} and ${max ?? '∞'}.`);+ }+ return parsed;+}++function optionalInt({ value, label, min, max }: { value: unknown; label: string; min: number; max: number }): number | undefined {+ const parsed = optionalNumber({ value, label, min, max });+ if (parsed !== undefined && !Number.isInteger(parsed)) {+ throw new Error(`${label} must be a whole number.`);+ }+ return parsed;+}++function toDateOnly({ value, label }: { value: unknown; label: string }): string | undefined {+ const text = optionalText(value);+ if (text === undefined) return undefined;+ const match = /^(\d{4}-\d{2}-\d{2})(?:$|T)/.exec(text);+ if (!match || Number.isNaN(Date.parse(`${match[1]}T00:00:00Z`))) {+ throw new Error(`${label} must be a date like 2026-01-31.`);+ }+ return match[1];+}++function parseBoolean(value: unknown): boolean | undefined {+ if (typeof value === 'boolean') return value;+ if (value === 'true') return true;+ if (value === 'false') return false;+ return undefined;+}++function paging({ page, perPage }: { page: unknown; perPage: unknown }): { page: number; perPage: number } {+ return {+ page: optionalInt({ value: page, label: 'Page', min: 1, max: 100000 }) ?? 1,+ perPage: optionalInt({ value: perPage, label: 'Per Page', min: 1, max: 100 }) ?? 20,+ };+}++function clearedFields({ value, allowed }: { value: unknown; allowed: readonly string[] }): Record<string, string> {+ const list = arrayOf(value).filter((item): item is string => typeof item === 'string');+ const unknown = list.filter((item) => !allowed.includes(item));+ if (unknown.length > 0) {+ throw new Error(`Cannot clear ${unknown.join(', ')}. Allowed: ${allowed.join(', ')}.`);+ }+ return Object.fromEntries(list.map((field) => [field, '']));+}++function compact(record: Record<string, unknown>): Record<string, unknown> {+ return Object.fromEntries(Object.entries(record).filter(([, value]) => value !== undefined));+}++function lineItemsOf({+ value,+ label,+ required,+ isAmountDiscount,+}: {+ value: unknown;+ label: string;+ required: boolean;+ isAmountDiscount?: boolean;+}): Record<string, unknown>[] | undefined {+ if (value === undefined || value === null || value === '') {+ if (required) throw new Error(`${label} needs at least one line item.`);+ return undefined;+ }+ const list = arrayOf(value);+ if (list.length === 0) {+ if (required) throw new Error(`${label} needs at least one line item.`);+ return undefined;+ }+ return list.map((item, index) => {+ if (!isRecord(item)) throw new Error(`${label} item ${index + 1} must be an object.`);+ const row = `${label} item ${index + 1}`;+ const line = compact({+ product_key: optionalText(item['product_key']),+ notes: optionalText(item['notes']),+ cost: optionalNumber({ value: item['cost'], label: `${row} cost` }),+ quantity: optionalNumber({ value: item['quantity'], label: `${row} quantity` }) ?? 1,+ discount: optionalNumber({ value: item['discount'], label: `${row} discount`, min: 0 }),+ is_amount_discount: isAmountDiscount,+ tax_name1: optionalText(item['tax_name1']),+ tax_rate1: optionalNumber({ value: item['tax_rate1'], label: `${row} tax rate`, min: 0, max: 100 }),+ });+ if (line['product_key'] === undefined && line['notes'] === undefined) {+ throw new Error(`${row} needs a product key or a description.`);+ }+ return line;+ });+}++export const invoiceNinjaClient = {+ request,+ normalizeBaseUrl,+ apiBaseUrl,+ authHeaders,+ tokenOf,+ isSameOrigin,+ getRecord,+ listPage,+ bulk,+ dataOf,+ envelopeOf,+ recordOf,+ parseId,+ optionalId,+ optionalText,+ optionalNumber,+ optionalInt,+ toDateOnly,+ parseBoolean,+ paging,+ clearedFields,+ compact,+ lineItemsOf,+ isRecord,+ arrayOf,+};++type QueryInput = Record<string, string | number | boolean | undefined>;++export type InvoiceNinjaAuthValue = {+ base_url: string;+ access_token: string;+};++export type InvoiceNinjaRequest = {+ auth: InvoiceNinjaAuthValue;+ method: HttpMethod;+ path: string;+ query?: QueryInput;+ body?: unknown;+ timeoutMs?: number;+};++type ListPageInput = {+ auth: InvoiceNinjaAuthValue;+ entity: string;+ query: QueryInput;+ page: number;+ perPage: number;+};++export type ListPageResult = {+ items: unknown[];+ page: number;+ perPage: number;+ total: number;+ hasMore: boolean;+};++type BulkInput = {+ auth: InvoiceNinjaAuthValue;+ entity: string;+ action: string;+ ids: string[];+};diff --git a/packages/pieces/community/invoiceninja/src/lib/common/entity-actions.ts b/packages/pieces/community/invoiceninja/src/lib/common/entity-actions.tsnew file mode 100644index 00000000000..02dc612c68f--- /dev/null+++ b/packages/pieces/community/invoiceninja/src/lib/common/entity-actions.ts@@ -0,0 +1,103 @@+import { Property } from '@activepieces/pieces-framework';+import { invoiceNinjaClient } from './client';++function getIdProp(label: string) {+ return Property.ShortText({+ displayName: `${label} ID`,+ description: `The Invoice Ninja ID of the ${label.toLowerCase()} (letters and digits, e.g. VolejRejNm).`,+ required: true,+ });+}++function bulkIdProp(label: string) {+ return Property.ShortText({+ displayName: `${label} ID`,+ description: `The Invoice Ninja ID of the ${label.toLowerCase()}.`,+ required: true,+ });+}++async function runGet({ auth, entity, label, id }: RunGetInput) {+ const parsed = invoiceNinjaClient.parseId({ value: id, label: `${label} ID` });+ return invoiceNinjaClient.getRecord({ auth, entity, id: parsed });+}++async function runBulk({ auth, entity, label, action, id }: RunBulkInput) {+ const parsed = invoiceNinjaClient.parseId({ value: id, label: `${label} ID` });+ const record = await invoiceNinjaClient.bulk({ auth, entity, action, ids: [parsed] });+ if (Object.keys(record).length === 0) {+ throw new Error(`Invoice Ninja did not return the ${label.toLowerCase()} ${parsed}; it may not exist or the action does not apply to it.`);+ }+ return record;+}++function listProps() {+ return {+ page: Property.Number({+ displayName: 'Page',+ description: 'Page number, starting at 1. Default 1.',+ required: false,+ }),+ per_page: Property.Number({+ displayName: 'Per Page',+ description: 'Results per page (1-100). Default 20.',+ required: false,+ }),+ };+}++function statusProp() {+ return Property.StaticDropdown<string>({+ displayName: 'Record State',+ description: 'Which records to include. Default: active only.',+ required: false,+ options: {+ options: [+ { label: 'Active', value: 'active' },+ { label: 'Archived', value: 'archived' },+ { label: 'Deleted', value: 'deleted' },+ { label: 'Active and archived', value: 'active,archived' },+ { label: 'All', value: 'active,archived,deleted' },+ ],+ },+ });+}++function sortProp() {+ return Property.StaticDropdown<string>({+ displayName: 'Sort',+ description: 'Sort order. Default: Invoice Ninja default (newest first for most records).',+ required: false,+ options: {+ options: [+ { label: 'Newest first', value: 'created_at|desc' },+ { label: 'Oldest first', value: 'created_at|asc' },+ { label: 'Recently updated first', value: 'updated_at|desc' },+ ],+ },+ });+}++async function runList({ auth, entity, page, perPage, query }: RunListInput) {+ const paging = invoiceNinjaClient.paging({ page, perPage });+ return invoiceNinjaClient.listPage({ auth, entity, query, page: paging.page, perPage: paging.perPage });+}++export const entityActions = { getIdProp, bulkIdProp, runGet, runBulk, listProps, statusProp, sortProp, runList };++type RunGetInput = {+ auth: { base_url: string; access_token: string };+ entity: string;+ label: string;+ id: string;+};++type RunBulkInput = RunGetInput & { action: string };++type RunListInput = {+ auth: { base_url: string; access_token: string };+ entity: string;+ page: unknown;+ perPage: unknown;+ query: Record<string, string | number | boolean | undefined>;+};diff --git a/packages/pieces/community/invoiceninja/src/lib/common/legacy-invoice.ts b/packages/pieces/community/invoiceninja/src/lib/common/legacy-invoice.tsnew file mode 100644index 00000000000..d4abd0c81f2--- /dev/null+++ b/packages/pieces/community/invoiceninja/src/lib/common/legacy-invoice.ts@@ -0,0 +1,106 @@+import { Property } from '@activepieces/pieces-framework';+import { InvoiceNinjaAuthValue, invoiceNinjaClient } from './client';+import { invoiceNinjaProps } from './props';++const MAX_ITEMS = 100;++function parseOrderItems(json: unknown): { product_key: string; quantity: number; discount: number }[] {+ const text = typeof json === 'string' ? json.trim() : '';+ let parsed: unknown;+ try {+ parsed = text === '' ? null : JSON.parse(text);+ } catch {+ throw new Error('Order Items JSON is not valid JSON. Example: [{"quantity":1,"product_key":"my-product","discount":"0"}]');+ }+ const list = Array.isArray(json) ? json : parsed;+ if (!Array.isArray(list) || list.length === 0) {+ throw new Error('Order Items JSON must be a non-empty array of items.');+ }+ if (list.length > MAX_ITEMS) {+ throw new Error(`Order Items JSON can hold at most ${MAX_ITEMS} items.`);+ }+ return list.map((item, index) => {+ const row = `Order item ${index + 1}`;+ if (!invoiceNinjaClient.isRecord(item)) throw new Error(`${row} must be an object.`);+ const productKey = invoiceNinjaClient.optionalText(item['product_key']);+ if (productKey === undefined) throw new Error(`${row} needs a product_key.`);+ const quantity = invoiceNinjaClient.optionalNumber({ value: item['quantity'], label: `${row} quantity` });+ if (quantity === undefined) throw new Error(`${row} needs a numeric quantity.`);+ const discount = invoiceNinjaClient.optionalNumber({ value: item['discount'], label: `${row} discount`, min: 0 }) ?? 0;+ return { product_key: productKey, quantity, discount };+ });+}++async function lineItemsFromProducts({ auth, json, isAmountDiscount }: LineItemsInput): Promise<Record<string, unknown>[]> {+ const items = parseOrderItems(json);+ const keys = [...new Set(items.map((item) => item.product_key))];+ const products = new Map<string, Record<string, unknown>>();+ for (const key of keys) {+ const result = await invoiceNinjaClient.listPage({ auth, entity: 'products', query: { product_key: key }, page: 1, perPage: 100 });+ const match = result.items.filter(invoiceNinjaClient.isRecord).find((product) => product['product_key'] === key);+ if (match) products.set(key, match);+ }+ const missing = keys.filter((key) => !products.has(key));+ if (missing.length > 0) {+ throw new Error(`No active product with product key: ${missing.join(', ')}.`);+ }+ return items.map((item) => {+ const product = products.get(item.product_key) ?? {};+ return {+ quantity: item.quantity,+ product_key: item.product_key,+ product_cost: product['price'],+ cost: product['price'],+ notes: product['notes'],+ discount: item.discount,+ is_amount_discount: isAmountDiscount,+ tax_name1: product['tax_name1'],+ tax_rate1: product['tax_rate1'],+ tax_id: product['tax_id'],+ };+ });+}++function legacyProps() {+ return {+ client_id: invoiceNinjaProps.clientDropdown({ required: true }),+ purchase_order_no: Property.ShortText({+ displayName: 'Purchase Order Number',+ description: 'Descriptive text or number (optional).',+ required: false,+ }),+ discount: Property.Number({+ displayName: 'Invoice Discount',+ description: 'Discount for the whole invoice. 0 = none.',+ defaultValue: 0,+ required: true,+ }),+ discount_type: Property.StaticDropdown({+ displayName: 'Type of discount',+ description: 'Amount or percentage. Applies to line items and invoice.',+ defaultValue: true,+ required: true,+ options: {+ options: [+ { label: 'Amount', value: true },+ { label: 'Percentage', value: false },+ ],+ },+ }),+ public_notes: Property.LongText({ displayName: 'Public notes', description: 'Visible in the client portal (optional).', required: false }),+ private_notes: Property.LongText({ displayName: 'Private notes', description: 'Not visible to the client (optional).', required: false }),+ order_items_json: Property.LongText({+ displayName: 'Order Items JSON',+ description: 'Each item references an existing product key; price, description and tax come from the product. e.g. [{ "quantity":1,"product_key":"product key", "discount": "0" }]',+ required: true,+ }),+ };+}++export const invoiceNinjaLegacy = { parseOrderItems, lineItemsFromProducts, legacyProps };++type LineItemsInput = {+ auth: InvoiceNinjaAuthValue;+ json: unknown;+ isAmountDiscount: boolean;+};diff --git a/packages/pieces/community/invoiceninja/src/lib/common/output-schemas.ts b/packages/pieces/community/invoiceninja/src/lib/common/output-schemas.tsnew file mode 100644index 00000000000..0023c5f1c41--- /dev/null+++ b/packages/pieces/community/invoiceninja/src/lib/common/output-schemas.ts@@ -0,0 +1,395 @@+import { OutputSchema } from '@activepieces/pieces-framework';++type Fields = OutputSchema['fields'];++const timestamps: Fields = [+ { key: 'created_at', label: 'Created At (Unix seconds)', format: 'number' },+ { key: 'updated_at', label: 'Updated At (Unix seconds)', format: 'number' },+ { key: 'archived_at', label: 'Archived At (Unix seconds, 0 = not archived)', format: 'number' },+ { key: 'is_deleted', label: 'Is Deleted', format: 'boolean' },+];++const contactFields: Fields = [+ { key: 'id', label: 'Contact ID' },+ { key: 'first_name', label: 'First Name' },+ { key: 'last_name', label: 'Last Name' },+ { key: 'email', label: 'Email', format: 'email' },+ { key: 'phone', label: 'Phone' },+ { key: 'is_primary', label: 'Is Primary', format: 'boolean' },+ { key: 'send_email', label: 'Receives Emails', format: 'boolean' },+];++const addressFields: Fields = [+ { key: 'address1', label: 'Address Line 1' },+ { key: 'address2', label: 'Address Line 2' },+ { key: 'city', label: 'City' },+ { key: 'state', label: 'State' },+ { key: 'postal_code', label: 'Postal Code' },+ { key: 'country_id', label: 'Country ID' },+];++const clientFields: Fields = [+ { key: 'id', label: 'Client ID' },+ { key: 'number', label: 'Client Number' },+ { key: 'name', label: 'Name' },+ { key: 'display_name', label: 'Display Name' },+ { key: 'website', label: 'Website' },+ { key: 'phone', label: 'Phone' },+ { key: 'vat_number', label: 'VAT Number' },+ { key: 'id_number', label: 'ID Number' },+ ...addressFields,+ { key: 'balance', label: 'Balance', format: 'number' },+ { key: 'paid_to_date', label: 'Paid To Date', format: 'number' },+ { key: 'credit_balance', label: 'Credit Balance', format: 'number' },+ { key: 'public_notes', label: 'Public Notes' },+ { key: 'private_notes', label: 'Private Notes' },+ {+ key: 'settings',+ label: 'Settings',+ children: [{ key: 'currency_id', label: 'Currency ID' }],+ },+ { key: 'contacts', label: 'Contacts', labelKey: 'email', listItems: contactFields },+ ...timestamps,+];++const lineItemFields: Fields = [+ { key: 'product_key', label: 'Product Key' },+ { key: 'notes', label: 'Description' },+ { key: 'cost', label: 'Unit Cost', format: 'number' },+ { key: 'quantity', label: 'Quantity', format: 'number' },+ { key: 'discount', label: 'Discount', format: 'number' },+ { key: 'tax_name1', label: 'Tax Name' },+ { key: 'tax_rate1', label: 'Tax Rate', format: 'number' },+ { key: 'line_total', label: 'Line Total', format: 'number' },+];++const invitationFields: Fields = [+ { key: 'id', label: 'Invitation ID' },+ { key: 'client_contact_id', label: 'Contact ID' },+ { key: 'link', label: 'Client Portal Link', format: 'url' },+ { key: 'sent_date', label: 'Sent Date' },+ { key: 'viewed_date', label: 'Viewed Date' },+];++const documentFields: Fields = [+ { key: 'id', label: 'Invoice ID' },+ { key: 'number', label: 'Number' },+ { key: 'client_id', label: 'Client ID' },+ { key: 'status_id', label: 'Status ID', description: 'Invoice: 1 draft, 2 sent, 3 partial, 4 paid, 5 cancelled, 6 reversed.' },+ { key: 'date', label: 'Date', format: 'date' },+ { key: 'due_date', label: 'Due Date', format: 'date' },+ { key: 'po_number', label: 'PO Number' },+ { key: 'amount', label: 'Amount', format: 'number' },+ { key: 'balance', label: 'Balance', format: 'number' },+ { key: 'paid_to_date', label: 'Paid To Date', format: 'number' },+ { key: 'discount', label: 'Discount', format: 'number' },+ { key: 'is_amount_discount', label: 'Discount Is Amount', format: 'boolean' },+ { key: 'total_taxes', label: 'Total Taxes', format: 'number' },+ { key: 'public_notes', label: 'Public Notes' },+ { key: 'private_notes', label: 'Private Notes' },+ { key: 'terms', label: 'Terms' },+ { key: 'project_id', label: 'Project ID' },+ { key: 'line_items', label: 'Line Items', labelKey: 'notes', listItems: lineItemFields },+ { key: 'invitations', label: 'Invitations', labelKey: 'link', listItems: invitationFields },+ ...timestamps,+];++const invoiceFields: Fields = documentFields;++const quoteFields: Fields = [+ ...documentFields.map((field) =>+ field.key === 'id'+ ? { ...field, label: 'Quote ID' }+ : field.key === 'status_id'+ ? { ...field, description: 'Quote: 1 draft, 2 sent, 3 approved, 4 converted, -1 expired.' }+ : field,+ ),+ { key: 'invoice_id', label: 'Converted Invoice ID' },+];++const creditFields: Fields = documentFields.map((field) =>+ field.key === 'id'+ ? { ...field, label: 'Credit ID' }+ : field.key === 'status_id'+ ? { ...field, description: 'Credit: 1 draft, 2 sent, 3 partially applied, 4 applied.' }+ : field,+);++const recurringFields: Fields = [+ ...documentFields+ .filter((field) => field.key !== 'paid_to_date')+ .map((field) =>+ field.key === 'id'+ ? { ...field, label: 'Recurring Invoice ID' }+ : field.key === 'status_id'+ ? { ...field, description: 'Recurring: 1 draft, 2 active, 3 paused, 4 completed, -1 pending.' }+ : field,+ ),+ { key: 'frequency_id', label: 'Frequency ID', description: '1 daily, 2 weekly, 3 two weeks, 4 four weeks, 5 monthly, 6 two months, 7 quarterly, 8 four months, 9 six months, 10 annually, 11 two years, 12 three years.' },+ { key: 'remaining_cycles', label: 'Remaining Cycles (-1 = endless)', format: 'number' },+ { key: 'next_send_date', label: 'Next Send Date', format: 'date' },+ { key: 'last_sent_date', label: 'Last Sent Date', format: 'date' },+ { key: 'auto_bill', label: 'Auto Bill' },+];++const paymentFields: Fields = [+ { key: 'id', label: 'Payment ID' },+ { key: 'number', label: 'Number' },+ { key: 'client_id', label: 'Client ID' },+ { key: 'amount', label: 'Amount', format: 'number' },+ { key: 'applied', label: 'Applied', format: 'number' },+ { key: 'refunded', label: 'Refunded', format: 'number' },+ { key: 'date', label: 'Date', format: 'date' },+ { key: 'status_id', label: 'Status ID', description: '1 pending, 4 completed, 5 partially refunded, 6 refunded.' },+ { key: 'type_id', label: 'Payment Type ID' },+ { key: 'transaction_reference', label: 'Transaction Reference' },+ { key: 'private_notes', label: 'Private Notes' },+ { key: 'currency_id', label: 'Currency ID' },+ {+ key: 'paymentables',+ label: 'Allocations',+ labelKey: 'invoice_id',+ listItems: [+ { key: 'invoice_id', label: 'Invoice ID' },+ { key: 'amount', label: 'Amount', format: 'number' },+ { key: 'refunded', label: 'Refunded', format: 'number' },+ ],+ },+ ...timestamps,+];++const productFields: Fields = [+ { key: 'id', label: 'Product ID' },+ { key: 'product_key', label: 'Product Key' },+ { key: 'notes', label: 'Description' },+ { key: 'price', label: 'Price', format: 'number' },+ { key: 'cost', label: 'Cost', format: 'number' },+ { key: 'quantity', label: 'Default Quantity', format: 'number' },+ { key: 'tax_name1', label: 'Tax Name' },+ { key: 'tax_rate1', label: 'Tax Rate', format: 'number' },+ { key: 'in_stock_quantity', label: 'In Stock', format: 'number' },+ ...timestamps,+];++const expenseFields: Fields = [+ { key: 'id', label: 'Expense ID' },+ { key: 'number', label: 'Number' },+ { key: 'amount', label: 'Amount', format: 'number' },+ { key: 'date', label: 'Date', format: 'date' },+ { key: 'client_id', label: 'Client ID' },+ { key: 'vendor_id', label: 'Vendor ID' },+ { key: 'project_id', label: 'Project ID' },+ { key: 'category_id', label: 'Category ID' },+ { key: 'invoice_id', label: 'Invoice ID' },+ { key: 'currency_id', label: 'Currency ID' },+ { key: 'should_be_invoiced', label: 'Should Be Invoiced', format: 'boolean' },+ { key: 'transaction_reference', label: 'Transaction Reference' },+ { key: 'public_notes', label: 'Public Notes' },+ { key: 'private_notes', label: 'Private Notes' },+ ...timestamps,+];++const taskFields: Fields = [+ { key: 'id', label: 'Task ID' },+ { key: 'number', label: 'Number' },+ { key: 'description', label: 'Description' },+ { key: 'client_id', label: 'Client ID' },+ { key: 'project_id', label: 'Project ID' },+ { key: 'invoice_id', label: 'Invoice ID' },+ { key: 'status_id', label: 'Task Status ID' },+ { key: 'rate', label: 'Hourly Rate', format: 'number' },+ { key: 'duration', label: 'Stored Duration (seconds)', format: 'number', description: 'Often 0 over the API; compute time from time_log.' },+ { key: 'is_running', label: 'Timer Running', format: 'boolean' },+ { key: 'time_log', label: 'Time Log', description: 'JSON string of [start, end, description, billable] entries (Unix seconds; end 0 = running).' },+ ...timestamps,+];++const projectFields: Fields = [+ { key: 'id', label: 'Project ID' },+ { key: 'number', label: 'Number' },+ { key: 'name', label: 'Name' },+ { key: 'client_id', label: 'Client ID' },+ { key: 'task_rate', label: 'Task Rate', format: 'number' },+ { key: 'budgeted_hours', label: 'Budgeted Hours', format: 'number' },+ { key: 'due_date', label: 'Due Date', format: 'date' },+ { key: 'public_notes', label: 'Public Notes' },+ { key: 'private_notes', label: 'Private Notes' },+ ...timestamps,+];++const vendorFields: Fields = [+ { key: 'id', label: 'Vendor ID' },+ { key: 'number', label: 'Number' },+ { key: 'name', label: 'Name' },+ { key: 'website', label: 'Website' },+ { key: 'phone', label: 'Phone' },+ { key: 'vat_number', label: 'VAT Number' },+ ...addressFields,+ { key: 'currency_id', label: 'Currency ID' },+ { key: 'public_notes', label: 'Public Notes' },+ { key: 'private_notes', label: 'Private Notes' },+ {+ key: 'contacts',+ label: 'Contacts',+ labelKey: 'email',+ listItems: [+ { key: 'id', label: 'Contact ID' },+ { key: 'first_name', label: 'First Name' },+ { key: 'last_name', label: 'Last Name' },+ { key: 'email', label: 'Email', format: 'email' },+ { key: 'phone', label: 'Phone' },+ ],+ },+ ...timestamps,+];++function record(fields: Fields): OutputSchema {+ return { fields };+}++function list({ label, labelKey, fields }: { label: string; labelKey: string; fields: Fields }): OutputSchema {+ return {+ fields: [+ { key: 'items', label, labelKey, listItems: fields },+ { key: 'page', label: 'Page', format: 'number' },+ { key: 'perPage', label: 'Per Page', format: 'number' },+ { key: 'total', label: 'Total Matching', format: 'number' },+ { key: 'hasMore', label: 'Has More Pages', format: 'boolean' },+ ],+ };+}++const report: OutputSchema = {+ fields: [+ { key: 'reportType', label: 'Report Type' },+ { key: 'columns', label: 'Columns', labelKey: 'display_value', listItems: [+ { key: 'identifier', label: 'Column Key' },+ { key: 'display_value', label: 'Column Name' },+ ] },+ { key: 'rows', label: 'Rows', description: 'One object per row, keyed by column key (e.g. client.name), holding the display value.' },+ { key: 'rowCount', label: 'Row Count', format: 'number' },+ ],+};++const legacyClient: OutputSchema = {+ itemLabel: '{client_name}',+ fields: [+ {+ key: 'clients',+ label: 'Client (empty result = false)',+ value: '',+ listItems: [+ { key: 'client_id', label: 'Client ID' },+ { key: 'client_name', label: 'Name' },+ { key: 'client_display_name', label: 'Display Name' },+ { key: 'client_web', label: 'Website' },+ { key: 'client_phone', label: 'Phone' },+ { key: 'client_vat', label: 'VAT Number' },+ { key: 'client_address1', label: 'Address Line 1' },+ { key: 'client_address2', label: 'Address Line 2' },+ { key: 'client_city', label: 'City' },+ { key: 'client_state', label: 'State' },+ { key: 'client_postcode', label: 'Postal Code' },+ { key: 'client_balance', label: 'Balance', format: 'number' },+ { key: 'client_paid_to_date', label: 'Paid To Date', format: 'number' },+ { key: 'client_payment_balance', label: 'Payment Balance', format: 'number' },+ { key: 'client_credit_balance', label: 'Credit Balance', format: 'number' },+ { key: 'client_public_notes', label: 'Public Notes' },+ { key: 'client_private_notes', label: 'Private Notes' },+ { key: 'client_no_contacts', label: 'Number Of Contacts', format: 'number' },+ {+ key: 'client_contacts',+ label: 'Contacts',+ labelKey: 'email',+ listItems: [+ { key: 'first_name', label: 'First Name' },+ { key: 'last_name', label: 'Last Name' },+ { key: 'email', label: 'Email', format: 'email' },+ { key: 'phone', label: 'Phone' },+ ],+ },+ ],+ },+ ],+};++const legacyInvoices: OutputSchema = {+ itemLabel: 'Invoice {invoice.invoiceno}',+ fields: [+ {+ key: 'invoices',+ label: 'Invoices (no match = false)',+ value: '',+ listItems: [+ {+ key: 'invoice',+ label: 'Invoice',+ children: [+ { key: 'clientid', label: 'Client ID' },+ { key: 'invoiceno', label: 'Invoice Number' },+ { key: 'ponumber', label: 'PO Number' },+ { key: 'invdate', label: 'Date', format: 'date' },+ { key: 'duedate', label: 'Due Date', format: 'date' },+ { key: 'punote', label: 'Public Notes' },+ { key: 'prnote', label: 'Private Notes' },+ { key: 'reminder1', label: 'Reminder 1 Sent' },+ { key: 'reminder2', label: 'Reminder 2 Sent' },+ { key: 'reminder3', label: 'Reminder 3 Sent' },+ { key: 'lastreminder', label: 'Last Reminder Sent' },+ { key: 'firstsku', label: 'First Line Product Key' },+ { key: 'firstitem', label: 'First Line Description' },+ { key: 'amount', label: 'Amount', format: 'number' },+ { key: 'balance', label: 'Balance', format: 'number' },+ { key: 'paid', label: 'Paid To Date', format: 'number' },+ ],+ },+ ],+ },+ ],+};++const taskExists: OutputSchema = {+ fields: [{ key: 'exists', label: 'Task Exists (1 = yes, 0 = no)', value: '', format: 'number' }],+};++function envelope(fields: Fields): OutputSchema {+ return { fields: [{ key: 'data', label: 'Data', children: fields }] };+}++function envelopeList(fields: Fields): OutputSchema {+ return { fields: [{ key: 'data', label: 'Data', listItems: fields }] };+}++export const invoiceNinjaOutputSchemas = {+ legacyClientCreated: envelope(clientFields),+ legacyInvoiceCreated: envelope(invoiceFields),+ legacyRecurringCreated: envelope(recurringFields),+ legacyTaskCreated: envelope(taskFields),+ legacyRecurringAction: envelopeList(recurringFields),+ client: record(clientFields),+ clientList: list({ label: 'Clients', labelKey: 'name', fields: clientFields }),+ invoice: record(invoiceFields),+ invoiceList: list({ label: 'Invoices', labelKey: 'number', fields: invoiceFields }),+ quote: record(quoteFields),+ quoteList: list({ label: 'Quotes', labelKey: 'number', fields: quoteFields }),+ credit: record(creditFields),+ creditList: list({ label: 'Credits', labelKey: 'number', fields: creditFields }),+ recurring: record(recurringFields),+ recurringList: list({ label: 'Recurring Invoices', labelKey: 'number', fields: recurringFields }),+ payment: record(paymentFields),+ paymentList: list({ label: 'Payments', labelKey: 'number', fields: paymentFields }),+ product: record(productFields),+ productList: list({ label: 'Products', labelKey: 'product_key', fields: productFields }),+ expense: record(expenseFields),+ expenseList: list({ label: 'Expenses', labelKey: 'number', fields: expenseFields }),+ task: record(taskFields),+ taskList: list({ label: 'Tasks', labelKey: 'description', fields: taskFields }),+ project: record(projectFields),+ projectList: list({ label: 'Projects', labelKey: 'name', fields: projectFields }),+ vendor: record(vendorFields),+ vendorList: list({ label: 'Vendors', labelKey: 'name', fields: vendorFields }),+ report,+ legacyClient,+ legacyInvoices,+ taskExists,+};diff --git a/packages/pieces/community/invoiceninja/src/lib/common/props.ts b/packages/pieces/community/invoiceninja/src/lib/common/props.tsnew file mode 100644index 00000000000..910342b6e84--- /dev/null+++ b/packages/pieces/community/invoiceninja/src/lib/common/props.ts@@ -0,0 +1,139 @@+import { Property } from '@activepieces/pieces-framework';+import { invoiceninjaAuth } from './auth';+import { invoiceNinjaClient } from './client';++async function optionsFor({ auth, entity, labelOf }: OptionsInput) {+ if (!auth) {+ return { disabled: true, placeholder: 'Connect your Invoice Ninja account first.', options: [] };+ }+ try {+ const options: { label: string; value: string }[] = [];+ let page = 1;+ let hasMore = true;+ while (hasMore && page <= 20) {+ const result = await invoiceNinjaClient.listPage({ auth: auth.props, entity, query: { status: 'active' }, page, perPage: 100 });+ for (const item of result.items) {+ if (invoiceNinjaClient.isRecord(item) && typeof item['id'] === 'string') {+ options.push({ label: labelOf(item), value: item['id'] });+ }+ }+ hasMore = result.hasMore;+ page += 1;+ }+ return {+ disabled: false,+ placeholder: hasMore ? 'Showing the first 2000; type an ID in a custom value for others.' : undefined,+ options,+ };+ } catch (error) {+ return {+ disabled: true,+ placeholder: error instanceof Error ? `Could not load: ${error.message}` : 'Could not load options.',+ options: [],+ };+ }+}++function textOf(value: unknown): string {+ return typeof value === 'string' ? value : '';+}++function clientDropdown({ required, displayName }: { required: boolean; displayName?: string }) {+ return Property.Dropdown({+ auth: invoiceninjaAuth,+ displayName: displayName ?? 'Client',+ description: 'The Invoice Ninja client.',+ required,+ refreshers: [],+ options: async ({ auth }) =>+ optionsFor({+ auth,+ entity: 'clients',+ labelOf: (item) => textOf(item['display_name']) || textOf(item['name']) || textOf(item['id']),+ }),+ });+}++function projectDropdown({ required }: { required: boolean }) {+ return Property.Dropdown({+ auth: invoiceninjaAuth,+ displayName: 'Project',+ description: 'The Invoice Ninja project (optional).',+ required,+ refreshers: [],+ options: async ({ auth }) =>+ optionsFor({+ auth,+ entity: 'projects',+ labelOf: (item) => textOf(item['name']) || textOf(item['id']),+ }),+ });+}++function lineItems({ required }: { required: boolean }) {+ return Property.Array({+ displayName: 'Line Items',+ description: 'One entry per line. Give a product key and/or description, the unit cost and the quantity. Values are used as given (no product price lookup).',+ required,+ properties: {+ product_key: Property.ShortText({ displayName: 'Product Key', description: 'Optional product key/name shown on the line.', required: false }),+ notes: Property.ShortText({ displayName: 'Description', required: false }),+ cost: Property.Number({ displayName: 'Unit Cost', required: true }),+ quantity: Property.Number({ displayName: 'Quantity', description: 'Default 1.', required: false }),+ discount: Property.Number({ displayName: 'Line Discount', description: 'Amount or percent, per the document discount type.', required: false }),+ tax_name1: Property.ShortText({ displayName: 'Tax Name', required: false }),+ tax_rate1: Property.Number({ displayName: 'Tax Rate (%)', required: false }),+ },+ });+}++function documentProps() {+ return {+ ...recurringDocumentProps(),+ due_date: Property.ShortText({ displayName: 'Due Date', description: 'YYYY-MM-DD.', required: false }),+ };+}++function recurringDocumentProps() {+ return {+ date: Property.ShortText({ displayName: 'Date', description: 'YYYY-MM-DD. Default today (company time zone).', required: false }),+ po_number: Property.ShortText({ displayName: 'PO Number', required: false }),+ discount: Property.Number({ displayName: 'Discount', description: 'Whole-document discount.', required: false }),+ is_amount_discount: Property.Checkbox({ displayName: 'Discount Is Amount', description: 'On = discount is an amount, off = percent. Default off (percent).', required: false }),+ public_notes: Property.LongText({ displayName: 'Public Notes', description: 'Visible to the client.', required: false }),+ private_notes: Property.LongText({ displayName: 'Private Notes', description: 'Internal only.', required: false }),+ terms: Property.LongText({ displayName: 'Terms', required: false }),+ project_id: Property.ShortText({ displayName: 'Project ID', required: false }),+ };+}++function documentBody(props: Record<string, unknown>): Record<string, unknown> {+ return invoiceNinjaClient.compact({+ date: invoiceNinjaClient.toDateOnly({ value: props['date'], label: 'Date' }),+ due_date: invoiceNinjaClient.toDateOnly({ value: props['due_date'], label: 'Due Date' }),+ po_number: invoiceNinjaClient.optionalText(props['po_number']),+ discount: invoiceNinjaClient.optionalNumber({ value: props['discount'], label: 'Discount', min: 0 }),+ is_amount_discount: invoiceNinjaClient.parseBoolean(props['is_amount_discount']),+ public_notes: invoiceNinjaClient.optionalText(props['public_notes']),+ private_notes: invoiceNinjaClient.optionalText(props['private_notes']),+ terms: invoiceNinjaClient.optionalText(props['terms']),+ project_id: invoiceNinjaClient.optionalId({ value: props['project_id'], label: 'Project ID' }),+ });+}++function clearProp({ fields }: { fields: readonly string[] }) {+ return Property.StaticMultiSelectDropdown<string>({+ displayName: 'Clear Fields',+ description: 'Fields to blank out. Fields you leave empty above are not changed.',+ required: false,+ options: { options: fields.map((field) => ({ label: field, value: field })) },+ });+}++export const invoiceNinjaProps = { clientDropdown, projectDropdown, lineItems, documentProps, recurringDocumentProps, documentBody, clearProp };++type OptionsInput = {+ auth: { props: { base_url: string; access_token: string } } | undefined;+ entity: string;+ labelOf: (item: Record<string, unknown>) => string;+};diff --git a/packages/pieces/community/invoiceninja/src/lib/common/report.ts b/packages/pieces/community/invoiceninja/src/lib/common/report.tsnew file mode 100644index 00000000000..1014b19382f--- /dev/null+++ b/packages/pieces/community/invoiceninja/src/lib/common/report.ts@@ -0,0 +1,145 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { Property } from '@activepieces/pieces-framework';+import { InvoiceNinjaApiError, InvoiceNinjaAuthValue, invoiceNinjaClient } from './client';++const POLL_INTERVAL_MS = 2_000;+const POLL_DEADLINE_MS = 60_000;++async function runReport({ auth, reportType, dateRange, startDate, endDate, clientId }: RunReportInput): Promise<ReportResult> {+ if (!REPORT_TYPES.some((type) => type.value === reportType)) {+ throw new Error(`Unknown report type ${reportType}.`);+ }+ if (!DATE_RANGES.some((range) => range.value === dateRange)) {+ throw new Error(`Unknown date range ${dateRange}.`);+ }+ const start = invoiceNinjaClient.toDateOnly({ value: startDate, label: 'Start Date' });+ const end = invoiceNinjaClient.toDateOnly({ value: endDate, label: 'End Date' });+ if (dateRange === 'custom' && (start === undefined || end === undefined)) {+ throw new Error('A custom date range needs both Start Date and End Date.');+ }+ const started = await invoiceNinjaClient.request({+ auth,+ method: HttpMethod.POST,+ path: `/reports/${reportType}`,+ query: { output: 'json' },+ body: invoiceNinjaClient.compact({+ date_range: dateRange,+ start_date: dateRange === 'custom' ? start : undefined,+ end_date: dateRange === 'custom' ? end : undefined,+ client_id: invoiceNinjaClient.optionalId({ value: clientId, label: 'Client ID' }),+ report_keys: [],+ send_email: false,+ include_deleted: false,+ }),+ });+ const reportId = invoiceNinjaClient.isRecord(started) && typeof started['message'] === 'string' ? started['message'] : '';+ if (!/^[A-Za-z0-9-]{8,64}$/.test(reportId)) {+ throw new Error('Invoice Ninja did not return a report job ID.');+ }+ const deadline = Date.now() + POLL_DEADLINE_MS;+ while (deadline - Date.now() > POLL_INTERVAL_MS) {+ await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));+ const remainingMs = deadline - Date.now();+ if (remainingMs <= 0) break;+ try {+ const preview = await invoiceNinjaClient.request({+ auth,+ method: HttpMethod.POST,+ path: `/reports/preview/${reportId}`,+ timeoutMs: remainingMs,+ });+ return shape({ reportType, preview });+ } catch (error) {+ if (!(error instanceof InvoiceNinjaApiError) || error.status !== 409) throw error;+ }+ }+ throw new Error(`The Invoice Ninja report ${reportType} was not ready after ${POLL_DEADLINE_MS / 1000} seconds; try a smaller date range.`);+}++function shape({ reportType, preview }: { reportType: string; preview: unknown }): ReportResult {+ if (!invoiceNinjaClient.isRecord(preview)) {+ throw new Error('Invoice Ninja returned the report in an unexpected format.');+ }+ const columns = invoiceNinjaClient+ .arrayOf(preview['columns'])+ .filter(invoiceNinjaClient.isRecord)+ .map((column) => ({ identifier: String(column['identifier'] ?? ''), display_value: String(column['display_value'] ?? '') }));+ const rows = Object.entries(preview)+ .filter(([key]) => /^\d+$/.test(key))+ .sort(([a], [b]) => Number(a) - Number(b))+ .map(([, cells]) =>+ Object.fromEntries(+ invoiceNinjaClient+ .arrayOf(cells)+ .filter(invoiceNinjaClient.isRecord)+ .map((cell) => [String(cell['identifier'] ?? ''), cell['display_value'] ?? cell['value'] ?? null]),+ ),+ );+ return { reportType, columns, rows, rowCount: rows.length };+}++function reportProps() {+ return {+ report_type: Property.StaticDropdown<string>({+ displayName: 'Report Type',+ required: true,+ options: { options: REPORT_TYPES },+ }),+ date_range: Property.StaticDropdown<string>({+ displayName: 'Date Range',+ description: 'Default: all time.',+ required: false,+ options: { options: DATE_RANGES },+ }),+ start_date: Property.ShortText({ displayName: 'Start Date', description: 'YYYY-MM-DD, for a custom range.', required: false }),+ end_date: Property.ShortText({ displayName: 'End Date', description: 'YYYY-MM-DD, for a custom range.', required: false }),+ client_id: Property.ShortText({ displayName: 'Client ID', description: 'Only this client (optional).', required: false }),+ };+}++const REPORT_TYPES = [+ { label: 'Clients', value: 'clients' },+ { label: 'Contacts', value: 'contacts' },+ { label: 'Invoices', value: 'invoices' },+ { label: 'Invoice Items', value: 'invoice_items' },+ { label: 'Quotes', value: 'quotes' },+ { label: 'Quote Items', value: 'quote_items' },+ { label: 'Credits', value: 'credits' },+ { label: 'Payments', value: 'payments' },+ { label: 'Recurring Invoices', value: 'recurring_invoices' },+ { label: 'Expenses', value: 'expenses' },+ { label: 'Tasks', value: 'tasks' },+ { label: 'Products', value: 'products' },+ { label: 'Vendors', value: 'vendors' },+];++const DATE_RANGES = [+ { label: 'All time', value: 'all' },+ { label: 'Last 7 days', value: 'last7' },+ { label: 'Last 30 days', value: 'last30' },+ { label: 'This month', value: 'this_month' },+ { label: 'Last month', value: 'last_month' },+ { label: 'This quarter', value: 'this_quarter' },+ { label: 'Last quarter', value: 'last_quarter' },+ { label: 'This year', value: 'this_year' },+ { label: 'Last year', value: 'last_year' },+ { label: 'Custom (start and end date)', value: 'custom' },+];++export const invoiceNinjaReports = { runReport, reportProps };++type RunReportInput = {+ auth: InvoiceNinjaAuthValue;+ reportType: string;+ dateRange: string;+ startDate?: unknown;+ endDate?: unknown;+ clientId?: unknown;+};++export type ReportResult = {+ reportType: string;+ columns: { identifier: string; display_value: string }[];+ rows: Record<string, unknown>[];+ rowCount: number;+};diff --git a/packages/pieces/community/invoiceninja/test/fixtures/report-preview-clients.json b/packages/pieces/community/invoiceninja/test/fixtures/report-preview-clients.jsonnew file mode 100644index 00000000000..0d9cd44adb5--- /dev/null+++ b/packages/pieces/community/invoiceninja/test/fixtures/report-preview-clients.json@@ -0,0 +1,54 @@+{+ "columns": [+ {+ "identifier": "client.name",+ "display_value": "Name"+ },+ {+ "identifier": "client.number",+ "display_value": "Number"+ },+ {+ "identifier": "client.user",+ "display_value": "Client User"+ },+ {+ "identifier": "client.assigned_user",+ "display_value": "Client Assigned User"+ }+ ],+ "0": [+ {+ "entity": "client",+ "id": "name",+ "hashed_id": null,+ "value": "Report Fixture Co",+ "identifier": "client.name",+ "display_value": "Report Fixture Co"+ },+ {+ "entity": "client",+ "id": "number",+ "hashed_id": null,+ "value": "0004",+ "identifier": "client.number",+ "display_value": "0004"+ },+ {+ "entity": "client",+ "id": "user",+ "hashed_id": null,+ "value": "New User",+ "identifier": "client.user",+ "display_value": "New User"+ },+ {+ "entity": "client",+ "id": "assigned_user",+ "hashed_id": null,+ "value": "",+ "identifier": "client.assigned_user",+ "display_value": ""+ }+ ]+}diff --git a/packages/pieces/community/invoiceninja/test/invoiceninja.test.ts b/packages/pieces/community/invoiceninja/test/invoiceninja.test.tsnew file mode 100644index 00000000000..ab1be13e9a1--- /dev/null+++ b/packages/pieces/community/invoiceninja/test/invoiceninja.test.ts@@ -0,0 +1,300 @@+import { httpClient } from '@activepieces/pieces-common';+import { readFileSync } from 'node:fs';+import { join } from 'node:path';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { invoiceninja } from '../src';+import { InvoiceNinjaApiError, invoiceNinjaClient } from '../src/lib/common/client';++const auth = { props: { base_url: 'https://invoices.example.com/', access_token: 'tok-secret' } };++function action(name: string) {+ const found = invoiceninja.actions()[name];+ if (!found) throw new Error(`missing ${name}`);+ return found;+}++function mockResponses(bodies: unknown[]) {+ const spy = vi.spyOn(httpClient, 'sendRequest');+ for (const body of bodies) spy.mockResolvedValueOnce({ status: 200, headers: {}, body });+ return spy;+}++function runAction({ name, propsValue = {} }: { name: string; propsValue?: Record<string, unknown> }) {+ return Reflect.apply(action(name).run, undefined, [{ auth, propsValue }]);+}++function requestOf({ spy, index = 0 }: { spy: ReturnType<typeof mockResponses>; index?: number }) {+ return spy.mock.calls[index][0];+}++afterEach(() => {+ vi.useRealTimers();+ vi.restoreAllMocks();+});++describe('normalizeBaseUrl', () => {+ it('strips trailing slashes and a pasted /api/v1', () => {+ expect(invoiceNinjaClient.normalizeBaseUrl('https://invoicing.co/')).toBe('https://invoicing.co');+ expect(invoiceNinjaClient.normalizeBaseUrl(' http://localhost:8090/api/v1/ ')).toBe('http://localhost:8090');+ expect(invoiceNinjaClient.normalizeBaseUrl('https://h.example.com/ninja')).toBe('https://h.example.com/ninja');+ });+ it.each(['ftp://h.example.com', 'https://u:[email protected]', 'https://h.example.com/?x=1', 'https://h.example.com/#a', 'https://h.example.com/%2e%2e/x', 'h.example.com', ''])(+ 'rejects %s',+ (value) => {+ expect(() => invoiceNinjaClient.normalizeBaseUrl(value)).toThrow();+ },+ );+});++describe('isSameOrigin', () => {+ it('rejects lookalike hosts and other paths', () => {+ const baseUrl = 'https://invoices.example.com/api/v1';+ expect(invoiceNinjaClient.isSameOrigin({ url: 'https://invoices.example.com/api/v1/clients', baseUrl })).toBe(true);+ expect(invoiceNinjaClient.isSameOrigin({ url: 'https://invoices.example.com.evil.io/api/v1/clients', baseUrl })).toBe(false);+ expect(invoiceNinjaClient.isSameOrigin({ url: 'https://invoices.example.com/other', baseUrl })).toBe(false);+ expect(invoiceNinjaClient.isSameOrigin({ url: 'https://[email protected]/api/v1', baseUrl })).toBe(false);+ });+});++describe('ids, dates and line items', () => {+ it('accepts hashed ids only', () => {+ expect(invoiceNinjaClient.parseId({ value: ' VolejRejNm ', label: 'ID' })).toBe('VolejRejNm');+ expect(() => invoiceNinjaClient.parseId({ value: 'a/../b', label: 'ID' })).toThrow();+ expect(() => invoiceNinjaClient.parseId({ value: '', label: 'ID' })).toThrow();+ });+ it('keeps the calendar date of an ISO date-time', () => {+ expect(invoiceNinjaClient.toDateOnly({ value: '2026-12-01T23:30:00.000Z', label: 'D' })).toBe('2026-12-01');+ expect(invoiceNinjaClient.toDateOnly({ value: '', label: 'D' })).toBeUndefined();+ expect(() => invoiceNinjaClient.toDateOnly({ value: '01/12/2026', label: 'D' })).toThrow();+ });+ it('maps line items and parses numeric strings', () => {+ expect(invoiceNinjaClient.lineItemsOf({ value: [{ notes: 'x', cost: '10', quantity: '2' }], label: 'L', required: true })).toEqual([+ { notes: 'x', cost: 10, quantity: 2 },+ ]);+ expect(() => invoiceNinjaClient.lineItemsOf({ value: [{ cost: 1 }], label: 'L', required: true })).toThrow();+ expect(() => invoiceNinjaClient.lineItemsOf({ value: [], label: 'L', required: true })).toThrow();+ });+ it('gives each line the document discount type', () => {+ expect(invoiceNinjaClient.lineItemsOf({ value: [{ notes: 'x', discount: 5 }], label: 'L', required: true, isAmountDiscount: true })).toEqual([+ { notes: 'x', quantity: 1, discount: 5, is_amount_discount: true },+ ]);+ });+});++describe('requests', () => {+ it('sends the token, X-Requested-With and no redirects', async () => {+ const spy = mockResponses([{ data: { id: 'Abc123' } }]);+ await runAction({ name: 'get_client', propsValue: { id: 'Abc123' } });+ const request = requestOf({ spy });+ expect(request.url).toBe('https://invoices.example.com/api/v1/clients/Abc123');+ expect(request.headers).toMatchObject({ 'X-API-TOKEN': 'tok-secret', 'X-Requested-With': 'XMLHttpRequest' });+ expect(request.followRedirects).toBe(false);+ });++ it('create_client sends a JSON body with a contacts array and no query string', async () => {+ const spy = mockResponses([{ data: { id: 'C1', contacts: [{ password: 'x', email: '[email protected]' }] } }]);+ const result = await runAction({+ name: 'create_client',+ propsValue: { client_business_name: 'Acme', client_email: '[email protected]', client_address1: '1 St', client_city: 'Rome', client_send_email: true },+ });+ const request = requestOf({ spy });+ expect(request.url).toBe('https://invoices.example.com/api/v1/clients');+ expect(request.queryParams).toEqual({});+ expect(request.body).toEqual({+ name: 'Acme',+ address1: '1 St',+ city: 'Rome',+ contacts: [{ email: '[email protected]', send_email: true, is_primary: true }],+ });+ expect(result).toEqual({ data: { id: 'C1', contacts: [{ email: '[email protected]' }] } });+ });++ it('create_task sends its fields in the body', async () => {+ const spy = mockResponses([{ data: { id: 'T1' } }]);+ await runAction({ name: 'create_task', propsValue: { number: 'T-1', description: 'Work', client_id: 'C1', rate: 0 } });+ expect(requestOf({ spy }).body).toEqual({ number: 'T-1', description: 'Work', client_id: 'C1', rate: 0 });+ });++ it('list actions return paging info', async () => {+ mockResponses([{ data: [{ id: 'A' }], meta: { pagination: { total: 41, total_pages: 3 } } }]);+ const result = await runAction({ name: 'find_clients', propsValue: { search: 'acme', page: 2, per_page: 20 } });+ expect(result).toEqual({ items: [{ id: 'A' }], page: 2, perPage: 20, total: 41, hasMore: true });+ });++ it('update_client sends only given fields plus cleared ones', async () => {+ const spy = mockResponses([{ data: { id: 'C1' } }]);+ await runAction({ name: 'update_client', propsValue: { client_id: 'C1', city: 'Paris', clear_fields: ['website'] } });+ expect(requestOf({ spy }).body).toEqual({ website: '', city: 'Paris' });+ });++ it('update_client refuses an empty update', async () => {+ await expect(runAction({ name: 'update_client', propsValue: { client_id: 'C1' } })).rejects.toThrow('Nothing to update');+ });+});++describe('errors', () => {+ it('throws InvoiceNinjaApiError with the vendor message instead of returning a string', async () => {+ vi.spyOn(httpClient, 'sendRequest').mockRejectedValue(+ Object.assign(new Error('x'), { response: { status: 422, body: { message: 'The given data was invalid.', errors: { client_id: ['Client is required'] } } } }),+ );+ const promise = runAction({ name: 'getclient_task', propsValue: { email: '[email protected]' } });+ await expect(promise).rejects.toBeInstanceOf(InvoiceNinjaApiError);+ await expect(runAction({ name: 'getclient_task', propsValue: { email: '[email protected]' } })).rejects.toThrow('client_id: Client is required');+ });++ it('getclient_task returns false when no client matches', async () => {+ mockResponses([{ data: [], meta: { pagination: { total: 0, total_pages: 1 } } }]);+ expect(await runAction({ name: 'getclient_task', propsValue: { email: '[email protected]' } })).toBe(false);+ });++ it('getinvoices_task copes with an invoice without line items', async () => {+ mockResponses([{ data: [{ number: '1', line_items: [] }], meta: { pagination: { total: 1, total_pages: 1 } } }]);+ const result = await runAction({ name: 'getinvoices_task', propsValue: { invoiceStatus: 'all' } });+ expect(result).toEqual([expect.objectContaining({ invoice: expect.objectContaining({ invoiceno: '1', firstsku: null }) })]);+ });+});++describe('legacy create_invoice', () => {+ it('matches the product key exactly and sends a date-only due date', async () => {+ const spy = mockResponses([+ { data: [{ product_key: 'W&1-extra', price: 99 }, { product_key: 'W&1', price: 12.5, notes: 'Widget' }], meta: { pagination: { total: 2, total_pages: 1 } } },+ { data: { id: 'I1' } },+ ]);+ await runAction({+ name: 'create_invoice',+ propsValue: { client_id: 'C1', discount: 0, discount_type: true, order_items_json: '[{"quantity":2,"product_key":"W&1","discount":"0"}]', send_email: false, mark_sent: true, due_date: '2026-12-01T23:30:00.000Z' },+ });+ expect(requestOf({ spy, index: 0 }).queryParams).toMatchObject({ product_key: 'W&1' });+ const body = requestOf({ spy, index: 1 }).body;+ expect(body).toMatchObject({ client_id: 'C1', due_date: '2026-12-01', line_items: [expect.objectContaining({ product_key: 'W&1', cost: 12.5 })] });+ expect(requestOf({ spy, index: 1 }).queryParams).toEqual({ mark_sent: 'true' });+ });++ it('rejects invalid JSON with a clear message', async () => {+ await expect(+ runAction({ name: 'create_invoice', propsValue: { client_id: 'C1', discount: 0, discount_type: true, order_items_json: '{bad' } }),+ ).rejects.toThrow('not valid JSON');+ });+});++describe('legacy create_recurring_invoice', () => {+ const product = { data: [{ product_key: 'W1', price: 10 }], meta: { pagination: { total: 1, total_pages: 1 } } };+ const base = { client_id: 'C1', discount: 0, discount_type: true, order_items_json: '[{"quantity":1,"product_key":"W1","discount":"0"}]', due_date: '2026-12-01T00:00:00.000Z' };++ it('a supplied override wins over the chosen frequency, as saved steps expect', async () => {+ const spy = mockResponses([product, { data: { id: 'R1' } }]);+ await runAction({ name: 'create_recurring_invoice', propsValue: { ...base, frequency: 5, auto_frequency: 7 } });+ expect(requestOf({ spy, index: 1 }).body).toMatchObject({ frequency_id: '7', next_send_date: '2026-12-01' });+ });++ it('uses the chosen frequency when no override is given', async () => {+ const spy = mockResponses([product, { data: { id: 'R1' } }]);+ await runAction({ name: 'create_recurring_invoice', propsValue: { ...base, frequency: 5 } });+ expect(requestOf({ spy, index: 1 }).body).toMatchObject({ frequency_id: '5' });+ });++ it('"Use override below" without an override is rejected', async () => {+ await expect(runAction({ name: 'create_recurring_invoice', propsValue: { ...base, frequency: 0 } })).rejects.toThrow('Choose a billing frequency');+ });+});++describe('getreport_task', () => {+ const preview = JSON.parse(readFileSync(join(__dirname, 'fixtures', 'report-preview-clients.json'), 'utf8'));+ const jobId = 'b5f785dc-3a04-4ac2-ad53-305d5de0b188';+ const stillWorking = Object.assign(new Error('x'), { response: { status: 409, body: { message: 'Still working.....' } } });++ it('starts the job, retries on 409 and maps the preview to columns and rows', async () => {+ vi.useFakeTimers();+ const spy = vi.spyOn(httpClient, 'sendRequest');+ spy.mockResolvedValueOnce({ status: 200, headers: {}, body: { message: jobId } });+ spy.mockRejectedValueOnce(stillWorking);+ spy.mockResolvedValueOnce({ status: 200, headers: {}, body: preview });+ const promise = runAction({ name: 'getreport_task', propsValue: { reportType: 'clients' } });+ await vi.advanceTimersByTimeAsync(5_000);+ const result = await promise;+ expect(spy).toHaveBeenCalledTimes(3);+ expect(requestOf({ spy, index: 0 }).url).toBe('https://invoices.example.com/api/v1/reports/clients');+ expect(requestOf({ spy, index: 0 }).queryParams).toEqual({ output: 'json' });+ expect(requestOf({ spy, index: 0 }).body).toMatchObject({ date_range: 'all', send_email: false });+ expect(requestOf({ spy, index: 2 }).url).toBe(`https://invoices.example.com/api/v1/reports/preview/${jobId}`);+ expect(result).toEqual({+ reportType: 'clients',+ columns: [+ { identifier: 'client.name', display_value: 'Name' },+ { identifier: 'client.number', display_value: 'Number' },+ { identifier: 'client.user', display_value: 'Client User' },+ { identifier: 'client.assigned_user', display_value: 'Client Assigned User' },+ ],+ rows: [{ 'client.name': 'Report Fixture Co', 'client.number': '0004', 'client.user': 'New User', 'client.assigned_user': '' }],+ rowCount: 1,+ });+ });++ it('keeps row order numeric and applies Max Rows', async () => {+ vi.useFakeTimers();+ const row = (name: string) => preview['0'].map((cell: Record<string, unknown>) => (cell['identifier'] === 'client.name' ? { ...cell, display_value: name } : cell));+ const spy = vi.spyOn(httpClient, 'sendRequest');+ spy.mockResolvedValueOnce({ status: 200, headers: {}, body: { message: jobId } });+ spy.mockResolvedValueOnce({ status: 200, headers: {}, body: { columns: preview.columns, '10': row('ten'), '2': row('two'), '0': row('zero') } });+ const promise = runAction({ name: 'getreport_task', propsValue: { reportType: 'clients', numberOfResults: 2 } });+ await vi.advanceTimersByTimeAsync(3_000);+ const result = await promise;+ expect(result.rows.map((r: Record<string, unknown>) => r['client.name'])).toEqual(['zero', 'two']);+ expect(result.rowCount).toBe(2);+ });++ it('gives up with a clear message when the job is still running after 60 seconds', async () => {+ vi.useFakeTimers();+ const spy = vi.spyOn(httpClient, 'sendRequest');+ spy.mockResolvedValueOnce({ status: 200, headers: {}, body: { message: jobId } });+ spy.mockRejectedValue(stillWorking);+ const promise = runAction({ name: 'getreport_task', propsValue: { reportType: 'clients' } });+ const assertion = expect(promise).rejects.toThrow('was not ready after 60 seconds');+ await vi.advanceTimersByTimeAsync(62_000);+ await assertion;+ });++ it('bounds every poll timeout by the time left before the deadline', async () => {+ vi.useFakeTimers();+ const spy = vi.spyOn(httpClient, 'sendRequest');+ spy.mockResolvedValueOnce({ status: 200, headers: {}, body: { message: jobId } });+ spy.mockRejectedValue(stillWorking);+ const promise = runAction({ name: 'getreport_task', propsValue: { reportType: 'clients' } });+ const assertion = expect(promise).rejects.toThrow('was not ready after 60 seconds');+ await vi.advanceTimersByTimeAsync(62_000);+ await assertion;+ const timeouts = spy.mock.calls.slice(1).map((call) => call[0].timeout ?? 0);+ expect(timeouts.length).toBeGreaterThan(1);+ expect(timeouts[timeouts.length - 1]).toBeLessThanOrEqual(2_000);+ expect(timeouts.every((timeout) => timeout <= 58_000)).toBe(true);+ });++ it('does not retry other errors', async () => {+ vi.useFakeTimers();+ const spy = vi.spyOn(httpClient, 'sendRequest');+ spy.mockResolvedValueOnce({ status: 200, headers: {}, body: { message: jobId } });+ spy.mockRejectedValueOnce(Object.assign(new Error('x'), { response: { status: 500, body: { message: 'Server Error' } } }));+ const promise = runAction({ name: 'getreport_task', propsValue: { reportType: 'clients' } });+ const assertion = expect(promise).rejects.toThrow('Server Error');+ await vi.advanceTimersByTimeAsync(3_000);+ await assertion;+ expect(spy).toHaveBeenCalledTimes(2);+ });++ it('rejects a start response without a job ID', async () => {+ mockResponses([{ message: 'nope' }]);+ await expect(runAction({ name: 'getreport_task', propsValue: { reportType: 'clients' } })).rejects.toThrow('did not return a report job ID');+ });+});++describe('metadata', () => {+ it('has the expected audiences and an outputSchema on every action but the custom call', () => {+ const actions = Object.values(invoiceninja.actions());+ const human = actions.filter((a) => a.audience === 'human').map((a) => a.name).sort();+ expect(human).toEqual(+ ['action_recurring_invoice', 'create_invoice', 'create_recurring_invoice', 'create_task', 'custom_api_call', 'exists_task', 'getclient_task', 'getinvoices_task', 'getreport_task'].sort(),+ );+ expect(actions.filter((a) => a.audience === 'both').map((a) => a.name)).toEqual(['create_client']);+ expect(actions.filter((a) => a.name !== 'custom_api_call' && !a.outputSchema)).toEqual([]);+ });+});diff --git a/packages/pieces/community/invoiceninja/vitest.config.ts b/packages/pieces/community/invoiceninja/vitest.config.tsnew file mode 100644index 00000000000..79c97261904--- /dev/null+++ b/packages/pieces/community/invoiceninja/vitest.config.ts@@ -0,0 +1,19 @@+import path from 'path'+import { defineConfig } from 'vitest/config'++const repoRoot = path.resolve(__dirname, '../../../..')++export default defineConfig({+ root: __dirname,+ test: {+ globals: true,+ environment: 'node',+ include: ['test/**/*.test.ts'],+ },+ resolve: {+ alias: {+ '@activepieces/pieces-framework': path.resolve(repoRoot, 'packages/pieces/framework/src/index.ts'),+ '@activepieces/pieces-common': path.resolve(repoRoot, 'packages/pieces/common/src/index.ts'),+ },+ },+})