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(flowlu): manage CRM accounts, opportunities, tasks and projects, with new-record triggers (#16015)
Odai Ahmad9205f1bd2195
diff --git a/bun.lock b/bun.lockindex fff538f8594..27156051794 100644--- a/bun.lock+++ b/bun.lock@@ -3317,7 +3317,7 @@},"packages/pieces/community/flowlu": {"name": "@activepieces/piece-flowlu",- "version": "0.1.7",+ "version": "0.2.0","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",@@ -3327,6 +3327,7 @@},"devDependencies": {"tslib": "2.6.2",+ "vitest": "3.2.6",},},"packages/pieces/community/folk": {diff --git a/packages/pieces/community/flowlu/package.json b/packages/pieces/community/flowlu/package.jsonindex 380d43962e8..1246006a9c2 100644--- a/packages/pieces/community/flowlu/package.json+++ b/packages/pieces/community/flowlu/package.json@@ -1,12 +1,13 @@{"name": "@activepieces/piece-flowlu",- "version": "0.1.7",+ "version": "0.2.0","main": "./dist/src/index.js","types": "./dist/src/index.d.ts","scripts": {"build": "tsc -p tsconfig.lib.json && cp package.json dist/","bundle": "node ../../../../dist/packages/cli/src/index.js pieces bundle",- "lint": "eslint 'src/**/*.ts'"+ "lint": "eslint 'src/**/*.ts'",+ "test": "vitest run"},"dependencies": {"@activepieces/pieces-common": "workspace:*",@@ -16,6 +17,7 @@"@activepieces/core-utils": "workspace:*"},"devDependencies": {- "tslib": "2.6.2"+ "tslib": "2.6.2",+ "vitest": "3.2.6"}}diff --git a/packages/pieces/community/flowlu/src/i18n/translation.json b/packages/pieces/community/flowlu/src/i18n/translation.jsonindex b5e31d6befb..41a1d374ad0 100644--- a/packages/pieces/community/flowlu/src/i18n/translation.json+++ b/packages/pieces/community/flowlu/src/i18n/translation.json@@ -2,29 +2,71 @@"Business management software": "Business management software","Domain": "Domain","API Key": "API Key",+ "Your portal name only, for example \"example\" for https://example.flowlu.com. A pasted portal URL such as https://example.flowlu.com is also accepted.": "Your portal name only, for example \"example\" for https://example.flowlu.com. A pasted portal URL such as https://example.flowlu.com is also accepted.","\n 1. Log in to your flowlu account.\n 2. Click on your profile-pic(top-right) and navigate to **Portal Settings->API Settings**.\n 3. Create new API key with any name and appropriate scope.\n 4. Copy API Key to your clipboard and paste it in **API Key** field\n 5. In the Domain field, enter your company from your account URL address. For example, if your account URL address is https://example.flowlu.com, then your domain is **example**.\n ": "\n 1. Log in to your flowlu account.\n 2. Click on your profile-pic(top-right) and navigate to **Portal Settings->API Settings**.\n 3. Create new API key with any name and appropriate scope.\n 4. Copy API Key to your clipboard and paste it in **API Key** field\n 5. In the Domain field, enter your company from your account URL address. For example, if your account URL address is https://example.flowlu.com, then your domain is **example**.\n ","Create CRM Account(Contact)": "Create CRM Account(Contact)","Update CRM Account(Contact)": "Update CRM Account(Contact)","Delete CRM Account(Contact)": "Delete CRM Account(Contact)","Create CRM Account(Organization)": "Create CRM Account(Organization)",+ "Update CRM Account(Organization)": "Update CRM Account(Organization)",+ "Get CRM Account": "Get CRM Account",+ "Find CRM Accounts": "Find CRM Accounts","Create Opportunity": "Create Opportunity","Update Opportunity": "Update Opportunity","Delete Opportunity": "Delete Opportunity",+ "Get Opportunity": "Get Opportunity",+ "Find Opportunities": "Find Opportunities",+ "Link Account to Opportunity": "Link Account to Opportunity","Create Task": "Create Task","Update Task": "Update Task","Get Task": "Get Task","Delete Task": "Delete Task",+ "Find Tasks": "Find Tasks",+ "Create Project": "Create Project",+ "Update Project": "Update Project",+ "Get Project": "Get Project",+ "Find Projects": "Find Projects",+ "List Users": "List Users",+ "List Reference Values": "List Reference Values",+ "Create CRM Account": "Create CRM Account",+ "Update CRM Account": "Update CRM Account",+ "Delete CRM Account": "Delete CRM Account","Creates a new contact in CRM.": "Creates a new contact in CRM.","Updates an existing contact in CRM.": "Updates an existing contact in CRM.","Deletes an existing contact in CRM.": "Deletes an existing contact in CRM.","Creates a new organization in CRM.": "Creates a new organization in CRM.",+ "Updates an existing organization in CRM.": "Updates an existing organization in CRM.",+ "Gets a CRM contact or organization by ID.": "Gets a CRM contact or organization by ID.",+ "Searches CRM contacts and organizations.": "Searches CRM contacts and organizations.","Creates a new opportunity.": "Creates a new opportunity.","Updates an existing opportunity.": "Updates an existing opportunity.","Deletes an existing opportunity.": "Deletes an existing opportunity.",+ "Gets a CRM opportunity by ID.": "Gets a CRM opportunity by ID.",+ "Searches CRM opportunities (deals).": "Searches CRM opportunities (deals).",+ "Links a CRM contact or organization to an opportunity.": "Links a CRM contact or organization to an opportunity.","Creates a new task.": "Creates a new task.","Updates an existing task.": "Updates an existing task.","Retrieves an existing task.": "Retrieves an existing task.","Deletes an existing task.": "Deletes an existing task.",+ "Searches tasks.": "Searches tasks.",+ "Creates a new project.": "Creates a new project.",+ "Updates an existing project.": "Updates an existing project.",+ "Gets a project by ID.": "Gets a project by ID.",+ "Searches projects.": "Searches projects.",+ "Lists the users in your Flowlu portal.": "Lists the users in your Flowlu portal.",+ "Lists pipelines, stages, sources, categories, workflows and other reference values with their IDs.": "Lists pipelines, stages, sources, categories, workflows and other reference values with their IDs.",+ "Creates a CRM contact or organization in Flowlu.": "Creates a CRM contact or organization in Flowlu.",+ "Updates fields on a CRM contact or organization.": "Updates fields on a CRM contact or organization.",+ "Deletes a CRM contact or organization.": "Deletes a CRM contact or organization.",+ "Creates a CRM opportunity (deal) in Flowlu.": "Creates a CRM opportunity (deal) in Flowlu.",+ "Updates fields on a CRM opportunity, including marking it won or lost.": "Updates fields on a CRM opportunity, including marking it won or lost.",+ "Deletes a CRM opportunity.": "Deletes a CRM opportunity.",+ "Creates a task in Flowlu.": "Creates a task in Flowlu.",+ "Updates fields on a Flowlu task.": "Updates fields on a Flowlu task.",+ "Gets a Flowlu task by ID.": "Gets a Flowlu task by ID.",+ "Deletes a Flowlu task.": "Deletes a Flowlu task.",+ "Creates a project in Flowlu.": "Creates a project in Flowlu.",+ "Updates fields on a Flowlu project.": "Updates fields on a Flowlu project.","Title": "Title","First Name": "First Name","Middle Name": "Middle Name",@@ -61,6 +103,15 @@"Contact ID": "Contact ID","Organization Name": "Organization Name","Full legal name for Organization": "Full legal name for Organization",+ "Organization": "Organization",+ "Account ID": "Account ID",+ "Search": "Search",+ "Account Type": "Account Type",+ "Owner User ID": "Owner User ID",+ "Include Inactive": "Include Inactive",+ "Order": "Order",+ "Page": "Page",+ "Limit": "Limit","Opportunity Amount": "Opportunity Amount","Opportunity Source": "Opportunity Source","Start Date": "Start Date",@@ -69,6 +120,12 @@"Sales Pipeline ID": "Sales Pipeline ID","Sales Pipeline Stage ID": "Sales Pipeline Stage ID","Opportunity ID": "Opportunity ID",+ "Status": "Status",+ "Loss Reason": "Loss Reason",+ "Closing Comment": "Closing Comment",+ "Pipeline ID": "Pipeline ID",+ "Pipeline Stage ID": "Pipeline Stage ID",+ "Assignee User ID": "Assignee User ID","Name": "Name","Priority": "Priority","The assignee can change the end date for this task?": "The assignee can change the end date for this task?",@@ -77,15 +134,254 @@"Task Type": "Task Type","Task Workflow ID": "Task Workflow ID","Task Workflow Status ID": "Task Workflow Status ID",+ "Project": "Project",+ "CRM Account": "CRM Account","Task ID": "Task ID",+ "Project ID": "Project ID",+ "Project Template": "Project Template",+ "Project Manager": "Project Manager",+ "Customer (Organization)": "Customer (Organization)",+ "Customer Contact": "Customer Contact",+ "Portfolio": "Portfolio",+ "Contract Amount": "Contract Amount",+ "Planned Expenses": "Planned Expenses",+ "Archived": "Archived",+ "Manager User ID": "Manager User ID",+ "Customer Organization ID": "Customer Organization ID",+ "Include Archived": "Include Archived",+ "Include Users Without Login": "Include Users Without Login",+ "Values": "Values",+ "Parent ID": "Parent ID",+ "Full Legal Name": "Full Legal Name",+ "Honorific Title ID": "Honorific Title ID",+ "Category ID": "Category ID",+ "Industry ID": "Industry ID",+ "Phone": "Phone",+ "Phone 2": "Phone 2",+ "Phone 3": "Phone 3",+ "VAT or Tax ID": "VAT or Tax ID",+ "Skype": "Skype",+ "Facebook": "Facebook",+ "X (Twitter)": "X (Twitter)",+ "LinkedIn": "LinkedIn",+ "Instagram": "Instagram",+ "Billing Postal Code": "Billing Postal Code",+ "Billing Address": "Billing Address",+ "Shipping Postal Code": "Shipping Postal Code",+ "Shipping Address": "Shipping Address",+ "Amount": "Amount",+ "Source ID": "Source ID",+ "Expected Close Date": "Expected Close Date",+ "Contact Name": "Contact Name",+ "Contact Email": "Contact Email",+ "Contact Phone": "Contact Phone",+ "Contact Company": "Contact Company",+ "Contact Position": "Contact Position",+ "Organization ID": "Organization ID",+ "Close Date": "Close Date",+ "Loss Reason ID": "Loss Reason ID",+ "Type": "Type",+ "Deadline": "Deadline",+ "Workflow ID": "Workflow ID",+ "Workflow Status ID": "Workflow Status ID",+ "CRM Account ID": "CRM Account ID",+ "Parent Task ID": "Parent Task ID",+ "Assignee Can Change Deadline": "Assignee Can Change Deadline",+ "Needs Owner Approval": "Needs Owner Approval",+ "Customer Contact ID": "Customer Contact ID",+ "Portfolio ID": "Portfolio ID",+ "Template ID": "Template ID",+ "Google+ no longer exists and Flowlu has no field for it, so this value is not saved.": "Google+ no longer exists and Flowlu has no field for it, so this value is not saved.",+ "Numeric ID of the contact or organization, such as \"42\". Map it from an earlier step or from Find CRM Accounts.": "Numeric ID of the contact or organization, such as \"42\". Map it from an earlier step or from Find CRM Accounts.",+ "Text to look for in account names and other text fields, such as \"Acme\". Leave empty to list all.": "Text to look for in account names and other text fields, such as \"Acme\". Leave empty to list all.",+ "Only contacts, only organizations, or both.": "Only contacts, only organizations, or both.",+ "Only accounts owned by this user. Numeric user ID from List Users.": "Only accounts owned by this user. Numeric user ID from List Users.",+ "Also return accounts marked inactive.": "Also return accounts marked inactive.",+ "Newest first (highest ID first) or oldest first.": "Newest first (highest ID first) or oldest first.",+ "Page of results to return, starting at 1. Use with Limit; check has_more in the output to know if another page exists.": "Page of results to return, starting at 1. Use with Limit; check has_more in the output to know if another page exists.",+ "How many records to return per page, 1 to 100. Default 50.": "How many records to return per page, 1 to 100. Default 50.","Please use YYYY-MM-DD HH:mm:ss format.": "Please use YYYY-MM-DD HH:mm:ss format.","This is an id of the CRM company or contact which is needed to be linked with the opportunity. This allows you to link the client to the opportunity. If your client is a company, and you need to relate an opportunity to the person (contact) at this company, then enter his/her id in the contact_id field.": "This is an id of the CRM company or contact which is needed to be linked with the opportunity. This allows you to link the client to the opportunity. If your client is a company, and you need to relate an opportunity to the person (contact) at this company, then enter his/her id in the contact_id field.","Id of the company-related contact (account_id).": "Id of the company-related contact (account_id).",+ "Set to Won or Lost to close the opportunity, or In progress to reopen it. Moving it to Won or Lost sets the close date to today; an opportunity that already has that status keeps its close date. Leave empty to keep the current status.": "Set to Won or Lost to close the opportunity, or In progress to reopen it. Moving it to Won or Lost sets the close date to today; an opportunity that already has that status keeps its close date. Leave empty to keep the current status.",+ "Why the opportunity was lost. Only used when Status is Lost.": "Why the opportunity was lost. Only used when Status is Lost.",+ "Note about why the opportunity was won or lost.": "Note about why the opportunity was won or lost.",+ "Numeric opportunity ID, such as \"42\". Map it from an earlier step or from Find Opportunities.": "Numeric opportunity ID, such as \"42\". Map it from an earlier step or from Find Opportunities.",+ "Text to look for in opportunity names and other text fields. Leave empty to list all.": "Text to look for in opportunity names and other text fields. Leave empty to list all.",+ "Only opportunities in this pipeline. Numeric ID from List Reference Values (pipelines).": "Only opportunities in this pipeline. Numeric ID from List Reference Values (pipelines).",+ "Only opportunities in this stage. Numeric ID from List Reference Values (pipeline_stages).": "Only opportunities in this stage. Numeric ID from List Reference Values (pipeline_stages).",+ "Only in-progress, lost or won opportunities. Leave empty for all.": "Only in-progress, lost or won opportunities. Leave empty for all.",+ "Only opportunities assigned to this user. Numeric user ID from List Users.": "Only opportunities assigned to this user. Numeric user ID from List Users.",+ "Numeric opportunity ID, such as \"42\".": "Numeric opportunity ID, such as \"42\".",+ "Numeric ID of the contact or organization to link, such as \"17\".": "Numeric ID of the contact or organization to link, such as \"17\".",+ "Whether the account is a contact (person) or an organization (company).": "Whether the account is a contact (person) or an organization (company).",+ "Links the task to this project.": "Links the task to this project.",+ "Links the task to this CRM contact or organization.": "Links the task to this CRM contact or organization.",+ "New task status. Leave empty to keep the current status.": "New task status. Leave empty to keep the current status.",+ "Text to look for in task names and other text fields. Leave empty to list all.": "Text to look for in task names and other text fields. Leave empty to list all.",+ "Only tasks with this status. Leave empty for all.": "Only tasks with this status. Leave empty for all.",+ "Only tasks assigned to this user. Numeric user ID from List Users.": "Only tasks assigned to this user. Numeric user ID from List Users.",+ "Only tasks in this project. Numeric ID from Find Projects.": "Only tasks in this project. Numeric ID from Find Projects.",+ "The CRM organization the project is for.": "The CRM organization the project is for.",+ "The contact person at the customer.": "The contact person at the customer.",+ "Only the date part is used.": "Only the date part is used.",+ "Planned revenue for the project.": "Planned revenue for the project.",+ "Archive or restore the project. Leave empty to keep it as is.": "Archive or restore the project. Leave empty to keep it as is.",+ "Numeric project ID, such as \"42\". Map it from an earlier step or from Find Projects.": "Numeric project ID, such as \"42\". Map it from an earlier step or from Find Projects.",+ "Text to look for in project names and other text fields. Leave empty to list all.": "Text to look for in project names and other text fields. Leave empty to list all.",+ "Only projects managed by this user. Numeric user ID from List Users.": "Only projects managed by this user. Numeric user ID from List Users.",+ "Only projects for this CRM organization. Numeric ID from Find CRM Accounts.": "Only projects for this CRM organization. Numeric ID from Find CRM Accounts.",+ "Also return archived projects.": "Also return archived projects.",+ "Text to look for in user names and emails, such as \"jane\". Leave empty to list all.": "Text to look for in user names and emails, such as \"jane\". Leave empty to list all.",+ "Also return users who are not allowed to log in.": "Also return users who are not allowed to log in.",+ "Which kind of reference value to list.": "Which kind of reference value to list.",+ "For pipeline_stages: the pipeline ID. For task_statuses: the workflow ID. Leave empty to list all.": "For pipeline_stages: the pipeline ID. For task_statuses: the workflow ID. Leave empty to list all.",+ "contact for a person, organization for a company.": "contact for a person, organization for a company.",+ "Organization name. Required when creating an organization.": "Organization name. Required when creating an organization.",+ "Full legal name of the organization.": "Full legal name of the organization.",+ "Get IDs from flowlu_list_lookup_values with entity honorific_titles. Numeric ID such as \"42\".": "Get IDs from flowlu_list_lookup_values with entity honorific_titles. Numeric ID such as \"42\".",+ "Contact first name. Required when creating a contact.": "Contact first name. Required when creating a contact.",+ "Contact middle name.": "Contact middle name.",+ "Contact last name.": "Contact last name.",+ "User responsible for the account. Get user IDs from flowlu_list_users. Numeric ID such as \"42\".": "User responsible for the account. Get user IDs from flowlu_list_users. Numeric ID such as \"42\".",+ "Get IDs from flowlu_list_lookup_values with entity account_categories. Numeric ID such as \"42\".": "Get IDs from flowlu_list_lookup_values with entity account_categories. Numeric ID such as \"42\".",+ "Get IDs from flowlu_list_lookup_values with entity industries. Numeric ID such as \"42\".": "Get IDs from flowlu_list_lookup_values with entity industries. Numeric ID such as \"42\".",+ "Main email address, such as \"[email protected]\".": "Main email address, such as \"[email protected]\".",+ "Main phone number.": "Main phone number.",+ "Second phone number.": "Second phone number.",+ "Third phone number.": "Third phone number.",+ "Website URL, such as \"https://example.com\".": "Website URL, such as \"https://example.com\".",+ "Notes about the account.": "Notes about the account.",+ "VAT or tax identification number.": "VAT or tax identification number.",+ "Skype name or link.": "Skype name or link.",+ "Telegram username.": "Telegram username.",+ "Facebook profile link.": "Facebook profile link.",+ "X / Twitter profile link.": "X / Twitter profile link.",+ "LinkedIn profile link.": "LinkedIn profile link.",+ "Instagram profile link.": "Instagram profile link.",+ "Billing country.": "Billing country.",+ "Billing state or region.": "Billing state or region.",+ "Billing city.": "Billing city.",+ "Billing postal code.": "Billing postal code.",+ "Billing street address.": "Billing street address.",+ "Shipping country.": "Shipping country.",+ "Shipping state or region.": "Shipping state or region.",+ "Shipping city.": "Shipping city.",+ "Shipping postal code.": "Shipping postal code.",+ "Shipping street address.": "Shipping street address.",+ "Numeric ID of the contact or organization, such as \"42\". Get it from flowlu_find_accounts.": "Numeric ID of the contact or organization, such as \"42\". Get it from flowlu_find_accounts.",+ "Numeric ID of the contact or organization to delete, such as \"42\".": "Numeric ID of the contact or organization to delete, such as \"42\".",+ "Opportunity name, such as \"Website redesign for Acme\".": "Opportunity name, such as \"Website redesign for Acme\".",+ "Opportunity value in the portal currency, such as 1500.": "Opportunity value in the portal currency, such as 1500.",+ "Sales pipeline. Get IDs from flowlu_list_lookup_values with entity pipelines. Numeric ID such as \"42\".": "Sales pipeline. Get IDs from flowlu_list_lookup_values with entity pipelines. Numeric ID such as \"42\".",+ "Stage in the pipeline, checked against it before saving. Creating needs Pipeline ID too; updating without Pipeline ID uses the pipeline the opportunity is already in. Get IDs from flowlu_list_lookup_values with entity pipeline_stages and parent_id = the pipeline ID. Numeric ID such as \"42\".": "Stage in the pipeline, checked against it before saving. Creating needs Pipeline ID too; updating without Pipeline ID uses the pipeline the opportunity is already in. Get IDs from flowlu_list_lookup_values with entity pipeline_stages and parent_id = the pipeline ID. Numeric ID such as \"42\".",+ "Where the opportunity came from. Get IDs from flowlu_list_lookup_values with entity opportunity_sources. Numeric ID such as \"42\".": "Where the opportunity came from. Get IDs from flowlu_list_lookup_values with entity opportunity_sources. Numeric ID such as \"42\".",+ "User responsible for the opportunity. Get user IDs from flowlu_list_users. Numeric ID such as \"42\".": "User responsible for the opportunity. Get user IDs from flowlu_list_users. Numeric ID such as \"42\".",+ "Start date, such as \"2026-10-01\". Only the date part is used.": "Start date, such as \"2026-10-01\". Only the date part is used.",+ "Planned close date, such as \"2026-11-30\". Only the date part is used.": "Planned close date, such as \"2026-11-30\". Only the date part is used.",+ "Notes about the opportunity.": "Notes about the opportunity.",+ "Free-text contact name stored on the opportunity (not a CRM link).": "Free-text contact name stored on the opportunity (not a CRM link).",+ "Free-text contact email stored on the opportunity.": "Free-text contact email stored on the opportunity.",+ "Free-text contact phone stored on the opportunity.": "Free-text contact phone stored on the opportunity.",+ "Free-text company name stored on the opportunity.": "Free-text company name stored on the opportunity.",+ "Free-text job title stored on the opportunity.": "Free-text job title stored on the opportunity.",+ "CRM organization to link to the opportunity. Numeric ID from flowlu_find_accounts.": "CRM organization to link to the opportunity. Numeric ID from flowlu_find_accounts.",+ "CRM contact to link to the opportunity. Numeric ID from flowlu_find_accounts.": "CRM contact to link to the opportunity. Numeric ID from flowlu_find_accounts.",+ "Numeric ID of the opportunity, such as \"42\". Get it from flowlu_find_opportunities.": "Numeric ID of the opportunity, such as \"42\". Get it from flowlu_find_opportunities.",+ "New opportunity name.": "New opportunity name.",+ "Won or Lost closes the opportunity; In progress reopens it.": "Won or Lost closes the opportunity; In progress reopens it.",+ "When the opportunity was won or lost, such as \"2026-10-01\". When empty and Status moves the opportunity to Won or Lost, today (UTC) is used; an opportunity that already has that status keeps its close date.": "When the opportunity was won or lost, such as \"2026-10-01\". When empty and Status moves the opportunity to Won or Lost, today (UTC) is used; an opportunity that already has that status keeps its close date.",+ "Why it was lost. Numeric ID from flowlu_list_lookup_values with entity loss_reasons.": "Why it was lost. Numeric ID from flowlu_list_lookup_values with entity loss_reasons.",+ "Numeric ID of the opportunity to delete, such as \"42\".": "Numeric ID of the opportunity to delete, such as \"42\".",+ "Task name, up to 255 characters.": "Task name, up to 255 characters.",+ "Task description (plain text).": "Task description (plain text).",+ "Task priority.": "Task priority.",+ "Task type. Leave empty for a regular task (Flowlu default).": "Task type. Leave empty for a regular task (Flowlu default).",+ "Planned start, ISO 8601 such as \"2026-10-01T09:00:00Z\". Sent as \"YYYY-MM-DD HH:mm:ss\" in the Activepieces server time (UTC on Activepieces Cloud); Flowlu reads it in the portal timezone.": "Planned start, ISO 8601 such as \"2026-10-01T09:00:00Z\". Sent as \"YYYY-MM-DD HH:mm:ss\" in the Activepieces server time (UTC on Activepieces Cloud); Flowlu reads it in the portal timezone.",+ "End date, ISO 8601 such as \"2026-10-05T17:00:00Z\". Sent as \"YYYY-MM-DD HH:mm:ss\" in the Activepieces server time (UTC on Activepieces Cloud); Flowlu reads it in the portal timezone.": "End date, ISO 8601 such as \"2026-10-05T17:00:00Z\". Sent as \"YYYY-MM-DD HH:mm:ss\" in the Activepieces server time (UTC on Activepieces Cloud); Flowlu reads it in the portal timezone.",+ "User who does the task. Get user IDs from flowlu_list_users. Numeric ID such as \"42\".": "User who does the task. Get user IDs from flowlu_list_users. Numeric ID such as \"42\".",+ "User who owns (set) the task. Get user IDs from flowlu_list_users. Numeric ID such as \"42\".": "User who owns (set) the task. Get user IDs from flowlu_list_users. Numeric ID such as \"42\".",+ "Task workflow. Get IDs from flowlu_list_lookup_values with entity task_workflows. Numeric ID such as \"42\".": "Task workflow. Get IDs from flowlu_list_lookup_values with entity task_workflows. Numeric ID such as \"42\".",+ "Status within the workflow. Get IDs from flowlu_list_lookup_values with entity task_statuses. Numeric ID such as \"42\".": "Status within the workflow. Get IDs from flowlu_list_lookup_values with entity task_statuses. Numeric ID such as \"42\".",+ "Links the task to this project. Get IDs from flowlu_find_projects. Numeric ID such as \"42\".": "Links the task to this project. Get IDs from flowlu_find_projects. Numeric ID such as \"42\".",+ "Links the task to a CRM contact or organization. Get IDs from flowlu_find_accounts. Numeric ID such as \"42\".": "Links the task to a CRM contact or organization. Get IDs from flowlu_find_accounts. Numeric ID such as \"42\".",+ "Makes this a subtask of that task. Numeric ID such as \"42\".": "Makes this a subtask of that task. Numeric ID such as \"42\".",+ "Yes lets the assignee move the deadline. Leave empty to keep the current setting.": "Yes lets the assignee move the deadline. Leave empty to keep the current setting.",+ "Yes means the owner must approve the task before it is completed. Leave empty to keep the current setting.": "Yes means the owner must approve the task before it is completed. Leave empty to keep the current setting.",+ "Numeric ID of the task to update, such as \"42\". Get it from flowlu_find_tasks.": "Numeric ID of the task to update, such as \"42\". Get it from flowlu_find_tasks.",+ "New task name.": "New task name.",+ "New task status. Completed closes the task.": "New task status. Completed closes the task.",+ "Numeric task ID, such as \"42\". Get it from flowlu_find_tasks.": "Numeric task ID, such as \"42\". Get it from flowlu_find_tasks.",+ "Numeric ID of the task to delete, such as \"42\".": "Numeric ID of the task to delete, such as \"42\".",+ "Project name, such as \"Acme website relaunch\".": "Project name, such as \"Acme website relaunch\".",+ "Project description.": "Project description.",+ "Project manager. Get user IDs from flowlu_list_users. Numeric ID such as \"42\".": "Project manager. Get user IDs from flowlu_list_users. Numeric ID such as \"42\".",+ "CRM organization the project is for. Get IDs from flowlu_find_accounts. Numeric ID such as \"42\".": "CRM organization the project is for. Get IDs from flowlu_find_accounts. Numeric ID such as \"42\".",+ "CRM contact at the customer. Get IDs from flowlu_find_accounts. Numeric ID such as \"42\".": "CRM contact at the customer. Get IDs from flowlu_find_accounts. Numeric ID such as \"42\".",+ "CRM opportunity the project came from. Get IDs from flowlu_find_opportunities. Numeric ID such as \"42\".": "CRM opportunity the project came from. Get IDs from flowlu_find_opportunities. Numeric ID such as \"42\".",+ "Project start, such as \"2026-10-01\". Only the date part is used.": "Project start, such as \"2026-10-01\". Only the date part is used.",+ "Project end, such as \"2026-12-31\". Only the date part is used.": "Project end, such as \"2026-12-31\". Only the date part is used.",+ "Project priority.": "Project priority.",+ "Project portfolio. Get IDs from flowlu_list_lookup_values with entity project_portfolios. Numeric ID such as \"42\".": "Project portfolio. Get IDs from flowlu_list_lookup_values with entity project_portfolios. Numeric ID such as \"42\".",+ "Workflow used by tasks in this project. Get IDs from flowlu_list_lookup_values with entity task_workflows. Numeric ID such as \"42\".": "Workflow used by tasks in this project. Get IDs from flowlu_list_lookup_values with entity task_workflows. Numeric ID such as \"42\".",+ "Planned revenue (contract sum).": "Planned revenue (contract sum).",+ "Planned expense sum.": "Planned expense sum.",+ "Project template to start from. Numeric ID from flowlu_list_lookup_values with entity project_templates.": "Project template to start from. Numeric ID from flowlu_list_lookup_values with entity project_templates.",+ "Numeric ID of the project, such as \"42\". Get it from flowlu_find_projects.": "Numeric ID of the project, such as \"42\". Get it from flowlu_find_projects.",+ "New project name.": "New project name.",+ "Yes archives the project, No restores it. Leave empty to keep it as is.": "Yes archives the project, No restores it. Leave empty to keep it as is.",+ "Any": "Any",+ "Contacts": "Contacts",+ "Organizations": "Organizations",+ "Newest first": "Newest first",+ "Oldest first": "Oldest first",+ "In progress": "In progress",+ "Lost": "Lost",+ "Won": "Won",+ "Contact": "Contact","Low": "Low","Medium": "Medium","High": "High","Task": "Task","Inbox": "Inbox","Event": "Event",- "Task template": "Task template"+ "Task template": "Task template",+ "New": "New",+ "Pending owner approval": "Pending owner approval",+ "Completed": "Completed",+ "Archive": "Archive",+ "Restore (not archived)": "Restore (not archived)",+ "Sales pipelines": "Sales pipelines",+ "Pipeline stages": "Pipeline stages",+ "Opportunity sources": "Opportunity sources",+ "Loss reasons": "Loss reasons",+ "Account categories": "Account categories",+ "Industries": "Industries",+ "Honorific titles": "Honorific titles",+ "Task workflows": "Task workflows",+ "Task workflow statuses": "Task workflow statuses",+ "Project templates": "Project templates",+ "Project portfolios": "Project portfolios",+ "Contact (person)": "Contact (person)",+ "Organization (company)": "Organization (company)",+ "Event: call": "Event: call",+ "Event: email": "Event: email",+ "Event: appointment": "Event: appointment",+ "Milestone": "Milestone",+ "Yes": "Yes",+ "No": "No",+ "New Task": "New Task",+ "New Opportunity": "New Opportunity",+ "New CRM Account": "New CRM Account",+ "New Project": "New Project",+ "Triggers when a new task is created.": "Triggers when a new task is created.",+ "Triggers when a new opportunity (deal) is created.": "Triggers when a new opportunity (deal) is created.",+ "Triggers when a new CRM contact or organization is created.": "Triggers when a new CRM contact or organization is created.",+ "Triggers when a new project is created.": "Triggers when a new project is created.",+ "Assignee": "Assignee",+ "Only tasks in this project.": "Only tasks in this project.",+ "Which new accounts start the flow.": "Which new accounts start the flow.",+ "Contacts and organizations": "Contacts and organizations",+ "Contacts only": "Contacts only",+ "Organizations only": "Organizations only"}\ No newline at end of filediff --git a/packages/pieces/community/flowlu/src/index.ts b/packages/pieces/community/flowlu/src/index.tsindex bc501ba8e62..1f14c5ca132 100644--- a/packages/pieces/community/flowlu/src/index.ts+++ b/packages/pieces/community/flowlu/src/index.ts@@ -1,42 +1,97 @@-import {- createPiece,- PieceAuth,- Property,-} from '@activepieces/pieces-framework';+import { createPiece } from '@activepieces/pieces-framework';import { PieceCategory } from '@activepieces/pieces-framework';import { createContactAction } from './lib/actions/accounts/create-contact';import { createOrganizationAction } from './lib/actions/accounts/create-organization';import { deleteContactAction } from './lib/actions/accounts/delete-contact';+import { findAccountsAction } from './lib/actions/accounts/find-accounts';+import { getAccountAction } from './lib/actions/accounts/get-account';import { updateContactAction } from './lib/actions/accounts/update-contact';+import { updateOrganizationAction } from './lib/actions/accounts/update-organization';+import { flowluAccountCreate } from './lib/actions/ai/account-create';+import { flowluAccountDelete } from './lib/actions/ai/account-delete';+import { flowluAccountUpdate } from './lib/actions/ai/account-update';+import { flowluOpportunityCreate } from './lib/actions/ai/opportunity-create';+import { flowluOpportunityDelete } from './lib/actions/ai/opportunity-delete';+import { flowluOpportunityUpdate } from './lib/actions/ai/opportunity-update';+import { flowluProjectCreate } from './lib/actions/ai/project-create';+import { flowluProjectUpdate } from './lib/actions/ai/project-update';+import { flowluTaskCreate } from './lib/actions/ai/task-create';+import { flowluTaskDelete } from './lib/actions/ai/task-delete';+import { flowluTaskGet } from './lib/actions/ai/task-get';+import { flowluTaskUpdate } from './lib/actions/ai/task-update';+import { listLookupValuesAction } from './lib/actions/lookups/list-lookup-values';+import { listUsersAction } from './lib/actions/lookups/list-users';import { createOpportunityAction } from './lib/actions/opportunities/create-opportunity';import { deleteOpportunityAction } from './lib/actions/opportunities/delete-opportunity';+import { findOpportunitiesAction } from './lib/actions/opportunities/find-opportunities';+import { getOpportunityAction } from './lib/actions/opportunities/get-opportunity';+import { linkAccountToOpportunityAction } from './lib/actions/opportunities/link-account-to-opportunity';import { updateOpportunityAction } from './lib/actions/opportunities/update-opportunity';+import { createProjectAction } from './lib/actions/projects/create-project';+import { findProjectsAction } from './lib/actions/projects/find-projects';+import { getProjectAction } from './lib/actions/projects/get-project';+import { updateProjectAction } from './lib/actions/projects/update-project';import { createTaskAction } from './lib/actions/tasks/create-task';import { deleteTaskAction } from './lib/actions/tasks/delete-task';+import { findTasksAction } from './lib/actions/tasks/find-tasks';import { getTaskAction } from './lib/actions/tasks/get-task';import { updateTaskAction } from './lib/actions/tasks/update-task';import { flowluAuth } from './lib/auth';+import { newCrmAccountTrigger } from './lib/triggers/new-crm-account';+import { newOpportunityTrigger } from './lib/triggers/new-opportunity';+import { newProjectTrigger } from './lib/triggers/new-project';+import { newTaskTrigger } from './lib/triggers/new-task';export const flowlu = createPiece({displayName: 'Flowlu',description: 'Business management software',auth: flowluAuth,- minimumSupportedRelease: '0.30.0',+ minimumSupportedRelease: '0.88.2',logoUrl: 'https://cdn.activepieces.com/pieces/flowlu.png',categories: [PieceCategory.SALES_AND_CRM],- authors: ["kishanprmr","abuaboud"],+ authors: ['kishanprmr', 'abuaboud'],actions: [createContactAction,updateContactAction,deleteContactAction,createOrganizationAction,+ updateOrganizationAction,+ getAccountAction,+ findAccountsAction,createOpportunityAction,updateOpportunityAction,deleteOpportunityAction,+ getOpportunityAction,+ findOpportunitiesAction,+ linkAccountToOpportunityAction,createTaskAction,updateTaskAction,getTaskAction,deleteTaskAction,+ findTasksAction,+ createProjectAction,+ updateProjectAction,+ getProjectAction,+ findProjectsAction,+ listUsersAction,+ listLookupValuesAction,+ flowluAccountCreate,+ flowluAccountUpdate,+ flowluAccountDelete,+ flowluOpportunityCreate,+ flowluOpportunityUpdate,+ flowluOpportunityDelete,+ flowluTaskCreate,+ flowluTaskUpdate,+ flowluTaskGet,+ flowluTaskDelete,+ flowluProjectCreate,+ flowluProjectUpdate,+ ],+ triggers: [+ newTaskTrigger,+ newOpportunityTrigger,+ newCrmAccountTrigger,+ newProjectTrigger,],- triggers: [],});diff --git a/packages/pieces/community/flowlu/src/lib/actions/accounts/create-contact.ts b/packages/pieces/community/flowlu/src/lib/actions/accounts/create-contact.tsindex d156b4138dc..a02b5952567 100644--- a/packages/pieces/community/flowlu/src/lib/actions/accounts/create-contact.ts+++ b/packages/pieces/community/flowlu/src/lib/actions/accounts/create-contact.ts@@ -1,11 +1,8 @@-import {- PiecePropValueSchema,- Property,- createAction,-} from '@activepieces/pieces-framework';+import { Property, createAction } from '@activepieces/pieces-framework';import { flowluAuth } from '../../auth';import { flowluCommon, makeClient } from '../../common';-import { flowluProps } from '../../common/props';+import { flowluProps, flowluWire } from '../../common/props';+import { accountEnvelopeOutputSchema } from '../../output-schemas';export const createContactAction = createAction({auth: flowluAuth,@@ -13,8 +10,12 @@ export const createContactAction = createAction({classification: 'WRITE',displayName: 'Create CRM Account(Contact)',description: 'Creates a new contact in CRM.',- audience: 'both',- aiMetadata: { description: 'Creates a new person-type CRM account (a contact) in Flowlu, requiring at least a first name. Use to add an individual to the CRM; for companies use Create CRM Account (Organization) instead. Not idempotent — each call creates a new contact record.', idempotent: false },+ audience: 'human',+ aiMetadata: {+ description:+ 'Creates a new person-type CRM account (a contact) in Flowlu, requiring at least a first name. Use to add an individual to the CRM; for companies use Create CRM Account (Organization) instead. Not idempotent — each call creates a new contact record. For agents use flowlu_account_create.',+ idempotent: false,+ },props: {honorific_title_id: flowluCommon.honorific_title_id(false),first_name: Property.ShortText({@@ -31,11 +32,12 @@ export const createContactAction = createAction({}),...flowluProps.account,},+ outputSchema: accountEnvelopeOutputSchema,async run(context) {- const {auth, ...propsValue} = context;- const client = makeClient(- context.auth- );- return await client.createAccount({ type: 2, ...propsValue });+ const client = makeClient(context.auth);+ return await client.createAccount({+ ...flowluWire.account(context.propsValue),+ type: 2,+ });},});diff --git a/packages/pieces/community/flowlu/src/lib/actions/accounts/create-organization.ts b/packages/pieces/community/flowlu/src/lib/actions/accounts/create-organization.tsindex a71e97c6322..54b41becd2c 100644--- a/packages/pieces/community/flowlu/src/lib/actions/accounts/create-organization.ts+++ b/packages/pieces/community/flowlu/src/lib/actions/accounts/create-organization.ts@@ -1,11 +1,8 @@-import {- PiecePropValueSchema,- Property,- createAction,-} from '@activepieces/pieces-framework';+import { Property, createAction } from '@activepieces/pieces-framework';import { flowluAuth } from '../../auth';import { makeClient } from '../../common';-import { flowluProps } from '../../common/props';+import { flowluProps, flowluWire } from '../../common/props';+import { accountEnvelopeOutputSchema } from '../../output-schemas';export const createOrganizationAction = createAction({auth: flowluAuth,@@ -13,8 +10,12 @@ export const createOrganizationAction = createAction({classification: 'WRITE',displayName: 'Create CRM Account(Organization)',description: 'Creates a new organization in CRM.',- audience: 'both',- aiMetadata: { description: 'Creates a new company-type CRM account (an organization) in Flowlu, requiring an organization name. Use to add a business to the CRM; for individual people use Create CRM Account (Contact) instead. Not idempotent — each call creates a new organization record.', idempotent: false },+ audience: 'human',+ aiMetadata: {+ description:+ 'Creates a new company-type CRM account (an organization) in Flowlu, requiring an organization name. Use to add a business to the CRM; for individual people use Create CRM Account (Contact) instead. Not idempotent — each call creates a new organization record. For agents use flowlu_account_create.',+ idempotent: false,+ },props: {name: Property.ShortText({displayName: 'Organization Name',@@ -26,10 +27,12 @@ export const createOrganizationAction = createAction({}),...flowluProps.account,},+ outputSchema: accountEnvelopeOutputSchema,async run(context) {- const client = makeClient(- context.auth- );- return await client.createAccount({ type: 1, ...context.propsValue });+ const client = makeClient(context.auth);+ return await client.createAccount({+ ...flowluWire.account(context.propsValue),+ type: 1,+ });},});diff --git a/packages/pieces/community/flowlu/src/lib/actions/accounts/delete-contact.ts b/packages/pieces/community/flowlu/src/lib/actions/accounts/delete-contact.tsindex 606ffe1b678..c07b6fb66f8 100644--- a/packages/pieces/community/flowlu/src/lib/actions/accounts/delete-contact.ts+++ b/packages/pieces/community/flowlu/src/lib/actions/accounts/delete-contact.ts@@ -1,10 +1,9 @@-import {- createAction,- PiecePropValueSchema,-} from '@activepieces/pieces-framework';+import { createAction } from '@activepieces/pieces-framework';import { flowluAuth } from '../../auth';import { flowluCommon, makeClient } from '../../common';+import { flowluInput } from '../../common/utils';import { FlowluEntity, FlowluModule } from '../../common/constants';+import { deletedEnvelopeOutputSchema } from '../../output-schemas';export const deleteContactAction = createAction({auth: flowluAuth,@@ -12,16 +11,22 @@ export const deleteContactAction = createAction({classification: 'DESTRUCTIVE',displayName: 'Delete CRM Account(Contact)',description: 'Deletes an existing contact in CRM.',- audience: 'both',- aiMetadata: { description: 'Deletes a CRM account (contact) in Flowlu by its account id. Use to remove a contact record permanently. Effectively idempotent in end state once the record is gone, but it mutates data and a repeat call targets an already-deleted record.', idempotent: false },+ audience: 'human',+ aiMetadata: {+ description:+ 'Deletes a CRM account (contact) in Flowlu by its account id. Use to remove a contact record permanently. Effectively idempotent in end state once the record is gone, but it mutates data and a repeat call targets an already-deleted record. For agents use flowlu_account_delete.',+ idempotent: false,+ },props: {id: flowluCommon.contact_id(true),},+ outputSchema: deletedEnvelopeOutputSchema,async run(context) {- const id = context.propsValue.id!;- const client = makeClient(- context.auth- );+ const id = flowluInput.requireId({+ value: context.propsValue.id,+ name: 'Contact ID',+ });+ const client = makeClient(context.auth);return await client.deleteAction(FlowluModule.CRM,FlowluEntity.ACCOUNT,diff --git a/packages/pieces/community/flowlu/src/lib/actions/accounts/find-accounts.ts b/packages/pieces/community/flowlu/src/lib/actions/accounts/find-accounts.tsnew file mode 100644index 00000000000..f88598390b1--- /dev/null+++ b/packages/pieces/community/flowlu/src/lib/actions/accounts/find-accounts.ts@@ -0,0 +1,72 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { flowluAuth } from '../../auth';+import { makeClient } from '../../common';+import { flowluFind, flowluInput, flowluSharedProps } from '../../common/utils';+import { accountListOutputSchema } from '../../output-schemas';++export const findAccountsAction = createAction({+ auth: flowluAuth,+ name: 'flowlu_find_accounts',+ classification: 'SEARCH',+ displayName: 'Find CRM Accounts',+ description: 'Searches CRM contacts and organizations.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Searches Flowlu CRM accounts by text (matches names and other text fields) and optional filters for account type, owner and active state, returning one page of matching contacts/organizations with has_more for paging. Use to find an account ID before getting, updating, linking or deleting it, or to check for duplicates before creating one. Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ search: flowluSharedProps.search(+ 'Text to look for in account names and other text fields, such as "Acme". Leave empty to list all.'+ ),+ account_type: Property.StaticDropdown({+ displayName: 'Account Type',+ description: 'Only contacts, only organizations, or both.',+ required: false,+ defaultValue: 'any',+ options: {+ disabled: false,+ options: [+ { label: 'Any', value: 'any' },+ { label: 'Contacts', value: 'contact' },+ { label: 'Organizations', value: 'organization' },+ ],+ },+ }),+ owner_id: Property.ShortText({+ displayName: 'Owner User ID',+ description:+ 'Only accounts owned by this user. Numeric user ID from List Users.',+ required: false,+ }),+ include_inactive: Property.Checkbox({+ displayName: 'Include Inactive',+ description: 'Also return accounts marked inactive.',+ required: false,+ defaultValue: false,+ }),+ order: flowluSharedProps.order(),+ page: flowluSharedProps.page(),+ limit: flowluSharedProps.limit(),+ },+ outputSchema: accountListOutputSchema,+ async run(context) {+ const type = context.propsValue.account_type;+ return flowluFind.run({+ client: makeClient(context.auth),+ module: 'crm',+ entity: 'account',+ props: context.propsValue,+ filters: {+ 'filter[type]':+ type === 'contact' ? 2 : type === 'organization' ? 1 : undefined,+ 'filter[owner_id]': flowluInput.optionalId({+ value: context.propsValue.owner_id,+ name: 'Owner User ID',+ }),+ 'filter[active]': context.propsValue.include_inactive ? undefined : 1,+ },+ });+ },+});diff --git a/packages/pieces/community/flowlu/src/lib/actions/accounts/get-account.ts b/packages/pieces/community/flowlu/src/lib/actions/accounts/get-account.tsnew file mode 100644index 00000000000..3b94bddd2d7--- /dev/null+++ b/packages/pieces/community/flowlu/src/lib/actions/accounts/get-account.ts@@ -0,0 +1,35 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { flowluAuth } from '../../auth';+import { makeClient } from '../../common';+import { flowluInput } from '../../common/utils';+import { accountOutputSchema } from '../../output-schemas';++export const getAccountAction = createAction({+ auth: flowluAuth,+ name: 'flowlu_get_account',+ classification: 'READ',+ displayName: 'Get CRM Account',+ description: 'Gets a CRM contact or organization by ID.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Returns one Flowlu CRM account (contact or organization: names, phones, website, owner, category, addresses) by its numeric account_id. Use to read an account before updating it or linking it; use flowlu_find_accounts to look one up by name or email. Fails if the account does not exist. Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ account_id: Property.ShortText({+ displayName: 'Account ID',+ description:+ 'Numeric ID of the contact or organization, such as "42". Map it from an earlier step or from Find CRM Accounts.',+ required: true,+ }),+ },+ outputSchema: accountOutputSchema,+ async run(context) {+ const id = flowluInput.requireId({+ value: context.propsValue.account_id,+ name: 'Account ID',+ });+ return makeClient(context.auth).getRecord('crm', 'account', id);+ },+});diff --git a/packages/pieces/community/flowlu/src/lib/actions/accounts/update-contact.ts b/packages/pieces/community/flowlu/src/lib/actions/accounts/update-contact.tsindex 8a5f0410a01..dd9c9116ecb 100644--- a/packages/pieces/community/flowlu/src/lib/actions/accounts/update-contact.ts+++ b/packages/pieces/community/flowlu/src/lib/actions/accounts/update-contact.ts@@ -1,11 +1,9 @@-import {- PiecePropValueSchema,- Property,- createAction,-} from '@activepieces/pieces-framework';+import { Property, createAction } from '@activepieces/pieces-framework';import { flowluAuth } from '../../auth';import { flowluCommon, makeClient } from '../../common';-import { flowluProps } from '../../common/props';+import { flowluInput } from '../../common/utils';+import { flowluProps, flowluWire } from '../../common/props';+import { accountEnvelopeOutputSchema } from '../../output-schemas';export const updateContactAction = createAction({auth: flowluAuth,@@ -13,8 +11,12 @@ export const updateContactAction = createAction({classification: 'WRITE',displayName: 'Update CRM Account(Contact)',description: 'Updates an existing contact in CRM.',- audience: 'both',- aiMetadata: { description: 'Updates fields on an existing CRM account (contact) in Flowlu, identified by its account id. Use to change details such as name, contact info, or category on a known contact. The id is required and must reference an existing contact.', idempotent: false },+ audience: 'human',+ aiMetadata: {+ description:+ 'Updates fields on an existing CRM account (contact) in Flowlu, identified by its account id. Use to change details such as name, contact info, or category on a known contact. Only the fields you fill are sent, so other fields keep their values; the account type is never changed. The id is required and must reference an existing contact. Idempotent: repeating the same update leaves the contact unchanged. For agents use flowlu_account_update.',+ idempotent: true,+ },props: {id: flowluCommon.contact_id(true),honorific_title_id: flowluCommon.honorific_title_id(false),@@ -32,11 +34,16 @@ export const updateContactAction = createAction({}),...flowluProps.account,},+ outputSchema: accountEnvelopeOutputSchema,async run(context) {- const id = context.propsValue.id!;- const client = makeClient(- context.auth+ const id = flowluInput.requireId({+ value: context.propsValue.id,+ name: 'Contact ID',+ });+ const client = makeClient(context.auth);+ return await client.updateContact(+ id,+ flowluWire.account(context.propsValue));- return await client.updateContact(id, { type: 2, ...context.propsValue });},});diff --git a/packages/pieces/community/flowlu/src/lib/actions/accounts/update-organization.ts b/packages/pieces/community/flowlu/src/lib/actions/accounts/update-organization.tsnew file mode 100644index 00000000000..ed265fcd84c--- /dev/null+++ b/packages/pieces/community/flowlu/src/lib/actions/accounts/update-organization.ts@@ -0,0 +1,45 @@+import { Property, createAction } from '@activepieces/pieces-framework';+import { flowluAuth } from '../../auth';+import { flowluCommon, makeClient } from '../../common';+import { flowluProps, flowluWire } from '../../common/props';+import { flowluInput } from '../../common/utils';+import { accountOutputSchema } from '../../output-schemas';++export const updateOrganizationAction = createAction({+ auth: flowluAuth,+ name: 'flowlu_update_organization',+ classification: 'WRITE',+ displayName: 'Update CRM Account(Organization)',+ description: 'Updates an existing organization in CRM.',+ audience: 'human',+ aiMetadata: {+ description:+ 'Updates fields on an existing CRM organization in Flowlu picked from a list. Only filled fields are sent; the account type is never changed. For agents use flowlu_account_update. Idempotent: repeating the same update leaves the organization unchanged.',+ idempotent: true,+ },+ props: {+ id: flowluCommon.organization_id(true, 'Organization'),+ name: Property.ShortText({+ displayName: 'Organization Name',+ required: false,+ }),+ name_legal_full: Property.ShortText({+ displayName: 'Full legal name for Organization',+ required: false,+ }),+ ...flowluProps.account,+ },+ outputSchema: accountOutputSchema,+ async run(context) {+ const id = flowluInput.requireId({+ value: context.propsValue.id,+ name: 'Organization',+ });+ return makeClient(context.auth).updateRecord(+ 'crm',+ 'account',+ id,+ flowluWire.account(context.propsValue)+ );+ },+});diff --git a/packages/pieces/community/flowlu/src/lib/actions/ai/account-create.ts b/packages/pieces/community/flowlu/src/lib/actions/ai/account-create.tsnew file mode 100644index 00000000000..900e081a03e--- /dev/null+++ b/packages/pieces/community/flowlu/src/lib/actions/ai/account-create.ts@@ -0,0 +1,67 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { flowluAuth } from '../../auth';+import { makeClient } from '../../common';+import { flowluAiBody, flowluAiProps } from '../../common/ai-props';+import { FlowluApiError } from '../../common/client';+import { flowluOutput } from '../../common/utils';+import { accountCreateOutputSchema } from '../../output-schemas';++export const flowluAccountCreate = createAction({+ auth: flowluAuth,+ name: 'flowlu_account_create',+ classification: 'WRITE',+ displayName: 'Create CRM Account',+ description: 'Creates a CRM contact or organization in Flowlu.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Creates one Flowlu CRM account, either a contact (person, needs first_name) or an organization (company, needs name), chosen by account_type. Use to add a person or company to the CRM; search with flowlu_find_accounts first to avoid duplicates. Not idempotent: each call creates a new account.',+ idempotent: false,+ },+ props: {+ account_type: Property.StaticDropdown({+ displayName: 'Account Type',+ description: 'contact for a person, organization for a company.',+ required: true,+ options: {+ disabled: false,+ options: [+ { label: 'Contact (person)', value: 'contact' },+ { label: 'Organization (company)', value: 'organization' },+ ],+ },+ }),+ ...flowluAiProps.account(),+ },+ outputSchema: accountCreateOutputSchema,+ async run(context) {+ const accountType = context.propsValue.account_type;+ if (accountType !== 'contact' && accountType !== 'organization') {+ throw new FlowluApiError({+ message: 'Account Type must be "contact" or "organization".',+ });+ }+ const body = flowluAiBody.account(context.propsValue);+ if (accountType === 'contact' && body['first_name'] === undefined) {+ throw new FlowluApiError({+ message: 'First Name is required to create a contact.',+ });+ }+ if (accountType === 'organization' && body['name'] === undefined) {+ throw new FlowluApiError({+ message: 'Organization Name is required to create an organization.',+ });+ }+ const client = makeClient(context.auth);+ const created = await client.createRecord('crm', 'account', {+ ...body,+ type: accountType === 'contact' ? 2 : 1,+ });+ return flowluOutput.fullRecord({+ client,+ module: 'crm',+ entity: 'account',+ created,+ });+ },+});diff --git a/packages/pieces/community/flowlu/src/lib/actions/ai/account-delete.ts b/packages/pieces/community/flowlu/src/lib/actions/ai/account-delete.tsnew file mode 100644index 00000000000..a49e556c2af--- /dev/null+++ b/packages/pieces/community/flowlu/src/lib/actions/ai/account-delete.ts@@ -0,0 +1,40 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { flowluAuth } from '../../auth';+import { makeClient } from '../../common';+import { flowluInput } from '../../common/utils';+import { deletedOutputSchema } from '../../output-schemas';++export const flowluAccountDelete = createAction({+ auth: flowluAuth,+ name: 'flowlu_account_delete',+ classification: 'DESTRUCTIVE',+ displayName: 'Delete CRM Account',+ description: 'Deletes a CRM contact or organization.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Permanently deletes one Flowlu CRM account (contact or organization) by its numeric account_id. Use only when the record must be removed. Not idempotent: a second call fails because the account no longer exists.',+ idempotent: false,+ },+ props: {+ account_id: Property.ShortText({+ displayName: 'Account ID',+ description:+ 'Numeric ID of the contact or organization to delete, such as "42".',+ required: true,+ }),+ },+ outputSchema: deletedOutputSchema,+ async run(context) {+ const id = flowluInput.requireId({+ value: context.propsValue.account_id,+ name: 'Account ID',+ });+ const res = await makeClient(context.auth).deleteRecord(+ 'crm',+ 'account',+ id+ );+ return { id: Number(res.id ?? id), deleted: true };+ },+});diff --git a/packages/pieces/community/flowlu/src/lib/actions/ai/account-update.ts b/packages/pieces/community/flowlu/src/lib/actions/ai/account-update.tsnew file mode 100644index 00000000000..f421f664773--- /dev/null+++ b/packages/pieces/community/flowlu/src/lib/actions/ai/account-update.ts@@ -0,0 +1,44 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { flowluAuth } from '../../auth';+import { makeClient } from '../../common';+import { flowluAiBody, flowluAiProps } from '../../common/ai-props';+import { FlowluApiError } from '../../common/client';+import { flowluInput } from '../../common/utils';+import { accountOutputSchema } from '../../output-schemas';++export const flowluAccountUpdate = createAction({+ auth: flowluAuth,+ name: 'flowlu_account_update',+ classification: 'WRITE',+ displayName: 'Update CRM Account',+ description: 'Updates fields on a CRM contact or organization.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Changes only the fields you pass on one Flowlu CRM account (contact or organization), identified by account_id; omitted fields keep their value and the account type never changes. Use to correct names, phones, website, owner or address. Requires at least one field. Idempotent: repeating the same update leaves the account unchanged.',+ idempotent: true,+ },+ props: {+ account_id: Property.ShortText({+ displayName: 'Account ID',+ description:+ 'Numeric ID of the contact or organization, such as "42". Get it from flowlu_find_accounts.',+ required: true,+ }),+ ...flowluAiProps.account(),+ },+ outputSchema: accountOutputSchema,+ async run(context) {+ const id = flowluInput.requireId({+ value: context.propsValue.account_id,+ name: 'Account ID',+ });+ const body = flowluAiBody.account(context.propsValue);+ if (Object.keys(body).length === 0) {+ throw new FlowluApiError({+ message: 'Nothing to update: pass at least one field to change.',+ });+ }+ return makeClient(context.auth).updateRecord('crm', 'account', id, body);+ },+});diff --git a/packages/pieces/community/flowlu/src/lib/actions/ai/opportunity-create.ts b/packages/pieces/community/flowlu/src/lib/actions/ai/opportunity-create.tsnew file mode 100644index 00000000000..c5b0f0f4aad--- /dev/null+++ b/packages/pieces/community/flowlu/src/lib/actions/ai/opportunity-create.ts@@ -0,0 +1,101 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { flowluAuth } from '../../auth';+import { makeClient } from '../../common';+import { flowluAiBody, flowluAiProps } from '../../common/ai-props';+import { flowluLinks } from '../../common/links';+import { flowluOpportunity } from '../../common/opportunity';+import { flowluInput, flowluOutput } from '../../common/utils';+import { opportunityCreateOutputSchema } from '../../output-schemas';++export const flowluOpportunityCreate = createAction({+ auth: flowluAuth,+ name: 'flowlu_opportunity_create',+ classification: 'WRITE',+ displayName: 'Create Opportunity',+ description: 'Creates a CRM opportunity (deal) in Flowlu.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Creates one Flowlu sales opportunity (deal) with a name and optional amount, pipeline and stage, source, assignee, dates and free-text contact fields, then links it to a CRM organization and/or contact when organization_id or contact_id is given. Link failures are reported in link_errors without failing the step. Not idempotent: each call creates a new opportunity.',+ idempotent: false,+ },+ props: {+ name: Property.ShortText({+ displayName: 'Name',+ description: 'Opportunity name, such as "Website redesign for Acme".',+ required: true,+ }),+ ...flowluAiProps.opportunity(),+ organization_id: Property.ShortText({+ displayName: 'Organization ID',+ description:+ 'CRM organization to link to the opportunity. Numeric ID from flowlu_find_accounts.',+ required: false,+ }),+ contact_id: Property.ShortText({+ displayName: 'Contact ID',+ description:+ 'CRM contact to link to the opportunity. Numeric ID from flowlu_find_accounts.',+ required: false,+ }),+ },+ outputSchema: opportunityCreateOutputSchema,+ async run(context) {+ const body = flowluAiBody.opportunity(context.propsValue);+ const organizationId = flowluInput.optionalId({+ value: context.propsValue.organization_id,+ name: 'Organization ID',+ });+ const contactId = flowluInput.optionalId({+ value: context.propsValue.contact_id,+ name: 'Contact ID',+ });+ const client = makeClient(context.auth);+ const stage = await flowluOpportunity.stageAndCloseFields({+ client,+ opportunityId: undefined,+ pipelineId: flowluInput.optionalId({+ value: context.propsValue.pipeline_id,+ name: 'Pipeline ID',+ }),+ stageId: flowluInput.optionalId({+ value: context.propsValue.pipeline_stage_id,+ name: 'Pipeline Stage ID',+ }),+ status: undefined,+ closingDate: undefined,+ });+ const created = await client.createRecord(+ 'crm',+ 'lead',+ flowluInput.compact({+ ...body,+ pipeline_id: stage.pipeline_id,+ pipeline_stage_id: stage.pipeline_stage_id,+ })+ );+ const leadId = flowluInput.requireId({+ value: created['id'],+ name: 'Created opportunity id',+ });+ const links: { accountId: number; accountType: 1 | 2 }[] = [];+ if (organizationId !== undefined) {+ links.push({ accountId: organizationId, accountType: 1 });+ }+ if (contactId !== undefined) {+ links.push({ accountId: contactId, accountType: 2 });+ }+ const linkResult = await flowluLinks.linkAccountsReported({+ client,+ leadId,+ links,+ });+ const record = await flowluOutput.fullRecord({+ client,+ module: 'crm',+ entity: 'lead',+ created,+ });+ return { ...record, ...linkResult };+ },+});diff --git a/packages/pieces/community/flowlu/src/lib/actions/ai/opportunity-delete.ts b/packages/pieces/community/flowlu/src/lib/actions/ai/opportunity-delete.tsnew file mode 100644index 00000000000..5a80987200d--- /dev/null+++ b/packages/pieces/community/flowlu/src/lib/actions/ai/opportunity-delete.ts@@ -0,0 +1,35 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { flowluAuth } from '../../auth';+import { makeClient } from '../../common';+import { flowluInput } from '../../common/utils';+import { deletedOutputSchema } from '../../output-schemas';++export const flowluOpportunityDelete = createAction({+ auth: flowluAuth,+ name: 'flowlu_opportunity_delete',+ classification: 'DESTRUCTIVE',+ displayName: 'Delete Opportunity',+ description: 'Deletes a CRM opportunity.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Permanently deletes one Flowlu opportunity (deal) by its numeric opportunity_id. Use only when the deal must be removed; to close it instead, set status won or lost with flowlu_opportunity_update. Not idempotent: a second call fails because the opportunity no longer exists.',+ idempotent: false,+ },+ props: {+ opportunity_id: Property.ShortText({+ displayName: 'Opportunity ID',+ description: 'Numeric ID of the opportunity to delete, such as "42".',+ required: true,+ }),+ },+ outputSchema: deletedOutputSchema,+ async run(context) {+ const id = flowluInput.requireId({+ value: context.propsValue.opportunity_id,+ name: 'Opportunity ID',+ });+ const res = await makeClient(context.auth).deleteRecord('crm', 'lead', id);+ return { id: Number(res.id ?? id), deleted: true };+ },+});diff --git a/packages/pieces/community/flowlu/src/lib/actions/ai/opportunity-update.ts b/packages/pieces/community/flowlu/src/lib/actions/ai/opportunity-update.tsnew file mode 100644index 00000000000..55b54a0ecc0--- /dev/null+++ b/packages/pieces/community/flowlu/src/lib/actions/ai/opportunity-update.ts@@ -0,0 +1,128 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { flowluAuth } from '../../auth';+import { makeClient } from '../../common';+import { flowluAiBody, flowluAiProps } from '../../common/ai-props';+import { FlowluApiError } from '../../common/client';+import { flowluOpportunity } from '../../common/opportunity';+import { flowluInput } from '../../common/utils';+import { opportunityOutputSchema } from '../../output-schemas';++export const flowluOpportunityUpdate = createAction({+ auth: flowluAuth,+ name: 'flowlu_opportunity_update',+ classification: 'WRITE',+ displayName: 'Update Opportunity',+ description:+ 'Updates fields on a CRM opportunity, including marking it won or lost.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Changes only the fields you pass on one Flowlu opportunity, identified by opportunity_id; omitted fields keep their value. Use to move it to another pipeline stage, change the amount or assignee, or close it as won or lost (status), optionally with a loss reason and comment. A Pipeline Stage ID without Pipeline ID is checked against the pipeline the opportunity is in. Requires at least one field. Idempotent: repeating the same update leaves the opportunity unchanged, and repeating Won or Lost keeps the existing close date.',+ idempotent: true,+ },+ props: {+ opportunity_id: Property.ShortText({+ displayName: 'Opportunity ID',+ description:+ 'Numeric ID of the opportunity, such as "42". Get it from flowlu_find_opportunities.',+ required: true,+ }),+ name: Property.ShortText({+ displayName: 'Name',+ description: 'New opportunity name.',+ required: false,+ }),+ ...flowluAiProps.opportunity(),+ status: Property.StaticDropdown({+ displayName: 'Status',+ description:+ 'Won or Lost closes the opportunity; In progress reopens it.',+ required: false,+ options: {+ disabled: false,+ options: [+ { label: 'In progress', value: 1 },+ { label: 'Lost', value: 2 },+ { label: 'Won', value: 3 },+ ],+ },+ }),+ closing_date: Property.DateTime({+ displayName: 'Close Date',+ description:+ 'When the opportunity was won or lost, such as "2026-10-01". When empty and Status moves the opportunity to Won or Lost, today (UTC) is used; an opportunity that already has that status keeps its close date.',+ required: false,+ }),+ closing_status_id: Property.ShortText({+ displayName: 'Loss Reason ID',+ description:+ 'Why it was lost. Numeric ID from flowlu_list_lookup_values with entity loss_reasons.',+ required: false,+ }),+ closing_comment: Property.LongText({+ displayName: 'Closing Comment',+ description: 'Note about why the opportunity was won or lost.',+ required: false,+ }),+ },+ outputSchema: opportunityOutputSchema,+ async run(context) {+ const id = flowluInput.requireId({+ value: context.propsValue.opportunity_id,+ name: 'Opportunity ID',+ });+ const status = flowluInput.optionalNumber({+ value: context.propsValue.status,+ name: 'Status',+ });+ if (status !== undefined && ![1, 2, 3].includes(status)) {+ throw new FlowluApiError({+ message: 'Status must be 1 (in progress), 2 (lost) or 3 (won).',+ });+ }+ const body = flowluInput.compact({+ ...flowluAiBody.opportunity(context.propsValue),+ active: status,+ closing_date: flowluInput.formatDate({+ value: context.propsValue.closing_date,+ name: 'Close Date',+ }),+ closing_status_id: flowluInput.optionalId({+ value: context.propsValue.closing_status_id,+ name: 'Loss Reason ID',+ }),+ closing_comment: flowluInput.optionalText(+ context.propsValue.closing_comment+ ),+ });+ if (Object.keys(body).length === 0) {+ throw new FlowluApiError({+ message: 'Nothing to update: pass at least one field to change.',+ });+ }+ const client = makeClient(context.auth);+ const derived = await flowluOpportunity.stageAndCloseFields({+ client,+ opportunityId: id,+ pipelineId: flowluInput.optionalId({+ value: context.propsValue.pipeline_id,+ name: 'Pipeline ID',+ }),+ stageId: flowluInput.optionalId({+ value: context.propsValue.pipeline_stage_id,+ name: 'Pipeline Stage ID',+ }),+ status,+ closingDate: flowluInput.formatDate({+ value: context.propsValue.closing_date,+ name: 'Close Date',+ }),+ });+ return client.updateRecord(+ 'crm',+ 'lead',+ id,+ flowluInput.compact({ ...body, ...derived })+ );+ },+});diff --git a/packages/pieces/community/flowlu/src/lib/actions/ai/project-create.ts b/packages/pieces/community/flowlu/src/lib/actions/ai/project-create.tsnew file mode 100644index 00000000000..73d1a9c7804--- /dev/null+++ b/packages/pieces/community/flowlu/src/lib/actions/ai/project-create.ts@@ -0,0 +1,46 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { flowluAuth } from '../../auth';+import { makeClient } from '../../common';+import { flowluAiBody, flowluAiProps } from '../../common/ai-props';+import { flowluOutput } from '../../common/utils';+import { projectCreateOutputSchema } from '../../output-schemas';++export const flowluProjectCreate = createAction({+ auth: flowluAuth,+ name: 'flowlu_project_create',+ classification: 'WRITE',+ displayName: 'Create Project',+ description: 'Creates a project in Flowlu.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Creates one Flowlu project with a name and optional manager, CRM customer (organization and contact), source opportunity, dates, priority, template, portfolio, task workflow and planned revenue/expenses. Use when work for a client or deal needs its own project; add tasks to it afterwards with flowlu_task_create and project_id. Not idempotent: each call creates a new project.',+ idempotent: false,+ },+ props: {+ name: Property.ShortText({+ displayName: 'Name',+ description: 'Project name, such as "Acme website relaunch".',+ required: true,+ }),+ ...flowluAiProps.project(),+ project_type_id: Property.ShortText({+ displayName: 'Template ID',+ description:+ 'Project template to start from. Numeric ID from flowlu_list_lookup_values with entity project_templates.',+ required: false,+ }),+ },+ outputSchema: projectCreateOutputSchema,+ async run(context) {+ const body = flowluAiBody.project(context.propsValue);+ const client = makeClient(context.auth);+ const created = await client.createRecord('st', 'projects', body);+ return flowluOutput.fullRecord({+ client,+ module: 'st',+ entity: 'projects',+ created,+ });+ },+});diff --git a/packages/pieces/community/flowlu/src/lib/actions/ai/project-update.ts b/packages/pieces/community/flowlu/src/lib/actions/ai/project-update.tsnew file mode 100644index 00000000000..f08c25fd830--- /dev/null+++ b/packages/pieces/community/flowlu/src/lib/actions/ai/project-update.ts@@ -0,0 +1,54 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { flowluAuth } from '../../auth';+import { makeClient } from '../../common';+import { flowluAiBody, flowluAiProps } from '../../common/ai-props';+import { FlowluApiError } from '../../common/client';+import { flowluInput, flowluSharedProps } from '../../common/utils';+import { projectOutputSchema } from '../../output-schemas';++export const flowluProjectUpdate = createAction({+ auth: flowluAuth,+ name: 'flowlu_project_update',+ classification: 'WRITE',+ displayName: 'Update Project',+ description: 'Updates fields on a Flowlu project.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Changes only the fields you pass on one Flowlu project, identified by project_id; omitted fields keep their value. Use to rename, reschedule, reassign the manager, change the customer, or archive/unarchive the project (is_archive). Requires at least one field. Idempotent: repeating the same update leaves the project unchanged.',+ idempotent: true,+ },+ props: {+ project_id: Property.ShortText({+ displayName: 'Project ID',+ description:+ 'Numeric ID of the project, such as "42". Get it from flowlu_find_projects.',+ required: true,+ }),+ name: Property.ShortText({+ displayName: 'Name',+ description: 'New project name.',+ required: false,+ }),+ ...flowluAiProps.project(),+ is_archive: flowluSharedProps.triState({+ displayName: 'Archived',+ description:+ 'Yes archives the project, No restores it. Leave empty to keep it as is.',+ }),+ },+ outputSchema: projectOutputSchema,+ async run(context) {+ const id = flowluInput.requireId({+ value: context.propsValue.project_id,+ name: 'Project ID',+ });+ const body = flowluAiBody.project(context.propsValue);+ if (Object.keys(body).length === 0) {+ throw new FlowluApiError({+ message: 'Nothing to update: pass at least one field to change.',+ });+ }+ return makeClient(context.auth).updateRecord('st', 'projects', id, body);+ },+});diff --git a/packages/pieces/community/flowlu/src/lib/actions/ai/task-create.ts b/packages/pieces/community/flowlu/src/lib/actions/ai/task-create.tsnew file mode 100644index 00000000000..89213149018--- /dev/null+++ b/packages/pieces/community/flowlu/src/lib/actions/ai/task-create.ts@@ -0,0 +1,40 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { flowluAuth } from '../../auth';+import { makeClient } from '../../common';+import { flowluAiBody, flowluAiProps } from '../../common/ai-props';+import { flowluOutput } from '../../common/utils';+import { taskCreateOutputSchema } from '../../output-schemas';++export const flowluTaskCreate = createAction({+ auth: flowluAuth,+ name: 'flowlu_task_create',+ classification: 'WRITE',+ displayName: 'Create Task',+ description: 'Creates a task in Flowlu.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Creates one Flowlu task with a name and optional description, priority, dates, assignee, owner, workflow status, and links to a project (project_id), CRM account or parent task. Use to add a to-do; link it to a project by passing project_id from flowlu_find_projects. Not idempotent: each call creates a new task, so check flowlu_find_tasks first to avoid duplicates.',+ idempotent: false,+ },+ props: {+ name: Property.ShortText({+ displayName: 'Name',+ description: 'Task name, up to 255 characters.',+ required: true,+ }),+ ...flowluAiProps.task(),+ },+ outputSchema: taskCreateOutputSchema,+ async run(context) {+ const body = flowluAiBody.task(context.propsValue);+ const client = makeClient(context.auth);+ const created = await client.createRecord('task', 'tasks', body);+ return flowluOutput.fullRecord({+ client,+ module: 'task',+ entity: 'tasks',+ created,+ });+ },+});diff --git a/packages/pieces/community/flowlu/src/lib/actions/ai/task-delete.ts b/packages/pieces/community/flowlu/src/lib/actions/ai/task-delete.tsnew file mode 100644index 00000000000..93d12b09bc3--- /dev/null+++ b/packages/pieces/community/flowlu/src/lib/actions/ai/task-delete.ts@@ -0,0 +1,39 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { flowluAuth } from '../../auth';+import { makeClient } from '../../common';+import { flowluInput } from '../../common/utils';+import { deletedOutputSchema } from '../../output-schemas';++export const flowluTaskDelete = createAction({+ auth: flowluAuth,+ name: 'flowlu_task_delete',+ classification: 'DESTRUCTIVE',+ displayName: 'Delete Task',+ description: 'Deletes a Flowlu task.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Permanently deletes one Flowlu task by its numeric task_id. Use only when the task should be removed; to close it instead, set status 5 with flowlu_task_update. Not idempotent: a second call fails because the task no longer exists.',+ idempotent: false,+ },+ props: {+ task_id: Property.ShortText({+ displayName: 'Task ID',+ description: 'Numeric ID of the task to delete, such as "42".',+ required: true,+ }),+ },+ outputSchema: deletedOutputSchema,+ async run(context) {+ const id = flowluInput.requireId({+ value: context.propsValue.task_id,+ name: 'Task ID',+ });+ const res = await makeClient(context.auth).deleteRecord(+ 'task',+ 'tasks',+ id+ );+ return { id: Number(res.id ?? id), deleted: true };+ },+});diff --git a/packages/pieces/community/flowlu/src/lib/actions/ai/task-get.ts b/packages/pieces/community/flowlu/src/lib/actions/ai/task-get.tsnew file mode 100644index 00000000000..4d65cb5708c--- /dev/null+++ b/packages/pieces/community/flowlu/src/lib/actions/ai/task-get.ts@@ -0,0 +1,35 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { flowluAuth } from '../../auth';+import { makeClient } from '../../common';+import { flowluInput } from '../../common/utils';+import { taskOutputSchema } from '../../output-schemas';++export const flowluTaskGet = createAction({+ auth: flowluAuth,+ name: 'flowlu_task_get',+ classification: 'READ',+ displayName: 'Get Task',+ description: 'Gets a Flowlu task by ID.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Returns one Flowlu task (name, status, dates, assignee, workflow, linked project or account) by its numeric task_id. Use to read a task before updating it; use flowlu_find_tasks to look tasks up by name or filter. Fails if the task does not exist. Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ task_id: Property.ShortText({+ displayName: 'Task ID',+ description:+ 'Numeric task ID, such as "42". Get it from flowlu_find_tasks.',+ required: true,+ }),+ },+ outputSchema: taskOutputSchema,+ async run(context) {+ const id = flowluInput.requireId({+ value: context.propsValue.task_id,+ name: 'Task ID',+ });+ return makeClient(context.auth).getRecord('task', 'tasks', id);+ },+});diff --git a/packages/pieces/community/flowlu/src/lib/actions/ai/task-update.ts b/packages/pieces/community/flowlu/src/lib/actions/ai/task-update.tsnew file mode 100644index 00000000000..b8eb27c0051--- /dev/null+++ b/packages/pieces/community/flowlu/src/lib/actions/ai/task-update.ts@@ -0,0 +1,63 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { flowluAuth } from '../../auth';+import { makeClient } from '../../common';+import { flowluAiBody, flowluAiProps } from '../../common/ai-props';+import { FlowluApiError } from '../../common/client';+import { flowluInput } from '../../common/utils';+import { taskOutputSchema } from '../../output-schemas';++export const flowluTaskUpdate = createAction({+ auth: flowluAuth,+ name: 'flowlu_task_update',+ classification: 'WRITE',+ displayName: 'Update Task',+ description: 'Updates fields on a Flowlu task.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Changes only the fields you pass on one Flowlu task, identified by task_id; omitted fields keep their current value. Use to rename, reschedule, reassign, move to another workflow status, or complete a task (status 5). Requires at least one field to change. Idempotent: repeating the same update leaves the task in the same state.',+ idempotent: true,+ },+ props: {+ task_id: Property.ShortText({+ displayName: 'Task ID',+ description:+ 'Numeric ID of the task to update, such as "42". Get it from flowlu_find_tasks.',+ required: true,+ }),+ name: Property.ShortText({+ displayName: 'Name',+ description: 'New task name.',+ required: false,+ }),+ status: Property.StaticDropdown({+ displayName: 'Status',+ description: 'New task status. Completed closes the task.',+ required: false,+ options: {+ disabled: false,+ options: [+ { label: 'New', value: 1 },+ { label: 'In progress', value: 3 },+ { label: 'Pending owner approval', value: 4 },+ { label: 'Completed', value: 5 },+ ],+ },+ }),+ ...flowluAiProps.task(),+ },+ outputSchema: taskOutputSchema,+ async run(context) {+ const id = flowluInput.requireId({+ value: context.propsValue.task_id,+ name: 'Task ID',+ });+ const body = flowluAiBody.task(context.propsValue);+ if (Object.keys(body).length === 0) {+ throw new FlowluApiError({+ message: 'Nothing to update: pass at least one field to change.',+ });+ }+ return makeClient(context.auth).updateRecord('task', 'tasks', id, body);+ },+});diff --git a/packages/pieces/community/flowlu/src/lib/actions/lookups/list-lookup-values.ts b/packages/pieces/community/flowlu/src/lib/actions/lookups/list-lookup-values.tsnew file mode 100644index 00000000000..854b002be5b--- /dev/null+++ b/packages/pieces/community/flowlu/src/lib/actions/lookups/list-lookup-values.ts@@ -0,0 +1,171 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { flowluAuth } from '../../auth';+import { makeClient } from '../../common';+import { FlowluApiError } from '../../common/client';+import { flowluInput } from '../../common/utils';+import { lookupOutputSchema } from '../../output-schemas';++const LOOKUPS: Record<+ string,+ { label: string; module: string; entity: string; parentField?: string }+> = {+ pipelines: { label: 'Sales pipelines', module: 'crm', entity: 'pipeline' },+ pipeline_stages: {+ label: 'Pipeline stages',+ module: 'crm',+ entity: 'pipeline_stage',+ parentField: 'pipeline_id',+ },+ opportunity_sources: {+ label: 'Opportunity sources',+ module: 'crm',+ entity: 'source',+ },+ loss_reasons: { label: 'Loss reasons', module: 'crm', entity: 'loss_reason' },+ account_categories: {+ label: 'Account categories',+ module: 'crm',+ entity: 'account_category',+ },+ industries: { label: 'Industries', module: 'crm', entity: 'industry' },+ honorific_titles: {+ label: 'Honorific titles',+ module: 'crm',+ entity: 'honorific_title',+ },+ task_workflows: {+ label: 'Task workflows',+ module: 'task',+ entity: 'workflows',+ },+ task_statuses: {+ label: 'Task workflow statuses',+ module: 'task',+ entity: 'stages',+ parentField: 'workflow_id',+ },+ project_templates: {+ label: 'Project templates',+ module: 'st',+ entity: 'project_types',+ },+ project_portfolios: {+ label: 'Project portfolios',+ module: 'st',+ entity: 'portfolio',+ },+};++export const listLookupValuesAction = createAction({+ auth: flowluAuth,+ name: 'flowlu_list_lookup_values',+ classification: 'SEARCH',+ displayName: 'List Reference Values',+ description:+ 'Lists pipelines, stages, sources, categories, workflows and other reference values with their IDs.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Lists the IDs and names of one kind of Flowlu reference value: sales pipelines, pipeline stages (pass parent_id = pipeline ID), opportunity sources, loss reasons, account categories, industries, honorific titles, task workflows, task statuses (parent_id = workflow ID), project templates or project portfolios. Use to turn a name into the ID that create/update actions need. Returns up to 1000 values with has_more. Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ entity: Property.StaticDropdown({+ displayName: 'Values',+ description: 'Which kind of reference value to list.',+ required: true,+ options: {+ disabled: false,+ options: Object.entries(LOOKUPS).map(([value, lookup]) => ({+ label: lookup.label,+ value,+ })),+ },+ }),+ parent_id: Property.ShortText({+ displayName: 'Parent ID',+ description:+ 'For pipeline_stages: the pipeline ID. For task_statuses: the workflow ID. Leave empty to list all.',+ required: false,+ }),+ },+ outputSchema: lookupOutputSchema,+ async run(context) {+ const key = context.propsValue.entity;+ const lookup = typeof key === 'string' ? LOOKUPS[key] : undefined;+ if (lookup === undefined) {+ throw new FlowluApiError({+ message: `Unknown reference value type ${JSON.stringify(key)}.`,+ });+ }+ const parentId = flowluInput.optionalId({+ value: context.propsValue.parent_id,+ name: 'Parent ID',+ });+ if (parentId !== undefined && lookup.parentField === undefined) {+ throw new FlowluApiError({+ message: `${lookup.label} have no parent; leave Parent ID empty.`,+ });+ }+ const client = makeClient(context.auth);+ const pages = await fetchPages({+ fetchPage: (page) =>+ client.list<Record<string, unknown>>(lookup.module, lookup.entity, {+ ...(parentId !== undefined && lookup.parentField+ ? { [`filter[${lookup.parentField}]`]: parentId }+ : {}),+ 'order_by[asc][]': 'id',+ page,+ limit: PAGE_SIZE,+ }),+ });+ const items = pages.items.map((item) => ({+ id: item['id'] ?? null,+ name: item['name'] ?? null,+ parent_id: lookup.parentField ? item[lookup.parentField] ?? null : null,+ active: item['active'] ?? item['is_active'] ?? null,+ }));+ return {+ entity: key,+ items,+ count: items.length,+ total: pages.total,+ has_more: pages.hasMore,+ };+ },+});++async function fetchPages({+ fetchPage,+}: {+ fetchPage: (page: number) => Promise<{+ items: Record<string, unknown>[];+ total_result?: number;+ total?: number;+ }>;+}): Promise<{+ items: Record<string, unknown>[];+ total: number;+ hasMore: boolean;+}> {+ const collected: Record<string, unknown>[][] = [];+ let total = 0;+ for (let page = 1; page <= MAX_PAGES; page++) {+ const envelope = await fetchPage(page);+ collected.push(envelope.items);+ total = Number(envelope.total_result ?? envelope.total ?? 0);+ const seen = collected.reduce((sum, chunk) => sum + chunk.length, 0);+ if (envelope.items.length < PAGE_SIZE || seen >= total) {+ return {+ items: collected.flat(),+ total: Math.max(total, seen),+ hasMore: false,+ };+ }+ }+ const items = collected.flat();+ return { items, total, hasMore: items.length < total };+}++const PAGE_SIZE = 100;+const MAX_PAGES = 10;diff --git a/packages/pieces/community/flowlu/src/lib/actions/lookups/list-users.ts b/packages/pieces/community/flowlu/src/lib/actions/lookups/list-users.tsnew file mode 100644index 00000000000..b9292cbeac0--- /dev/null+++ b/packages/pieces/community/flowlu/src/lib/actions/lookups/list-users.ts@@ -0,0 +1,70 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { flowluAuth } from '../../auth';+import { makeClient } from '../../common';+import {+ flowluInput,+ flowluOutput,+ flowluSharedProps,+} from '../../common/utils';+import { userListOutputSchema } from '../../output-schemas';++export const listUsersAction = createAction({+ auth: flowluAuth,+ name: 'flowlu_list_users',+ classification: 'SEARCH',+ displayName: 'List Users',+ description: 'Lists the users in your Flowlu portal.',+ audience: 'both',+ aiMetadata: {+ description:+ "Lists Flowlu portal users (id, name, email login, admin flag) with optional text search, one page at a time with has_more. Use to resolve a person's name or email to the user ID needed for task assignee/owner, opportunity assignee, account owner or project manager. Read-only and idempotent.",+ idempotent: true,+ },+ props: {+ search: flowluSharedProps.search(+ 'Text to look for in user names and emails, such as "jane". Leave empty to list all.'+ ),+ include_disabled: Property.Checkbox({+ displayName: 'Include Users Without Login',+ description: 'Also return users who are not allowed to log in.',+ required: false,+ defaultValue: false,+ }),+ page: flowluSharedProps.page(),+ limit: flowluSharedProps.limit(),+ },+ outputSchema: userListOutputSchema,+ async run(context) {+ const props = context.propsValue;+ const { page, limit } = flowluInput.pageParams({+ page: props.page,+ limit: props.limit,+ });+ const envelope = await makeClient(context.auth).list<+ Record<string, unknown>+ >('core', 'user', {+ search: flowluInput.optionalText(props.search),+ 'filter[role_login]': props.include_disabled ? undefined : 1,+ 'order_by[asc][]': 'id',+ page,+ limit,+ });+ const result = flowluOutput.listResult({ envelope, page, limit });+ return { ...result, items: result.items.map(userRow) };+ },+});++function userRow(user: Record<string, unknown>) {+ return {+ id: user['id'] ?? null,+ name: user['name'] ?? null,+ first_name: user['first_name'] ?? null,+ last_name: user['last_name'] ?? null,+ username: user['username'] ?? null,+ position: user['position'] ?? null,+ timezone: user['timezone'] ?? null,+ role_admin: user['role_admin'] ?? null,+ role_login: user['role_login'] ?? null,+ last_active: user['last_active'] ?? null,+ };+}diff --git a/packages/pieces/community/flowlu/src/lib/actions/opportunities/create-opportunity.ts b/packages/pieces/community/flowlu/src/lib/actions/opportunities/create-opportunity.tsindex eb35daf09d2..3dc2666074b 100644--- a/packages/pieces/community/flowlu/src/lib/actions/opportunities/create-opportunity.ts+++ b/packages/pieces/community/flowlu/src/lib/actions/opportunities/create-opportunity.ts@@ -1,11 +1,11 @@-import {- PiecePropValueSchema,- Property,- createAction,-} from '@activepieces/pieces-framework';+import { Property, createAction } from '@activepieces/pieces-framework';import { flowluAuth } from '../../auth';import { makeClient } from '../../common';-import { flowluProps } from '../../common/props';+import { flowluLinks } from '../../common/links';+import { flowluOpportunity } from '../../common/opportunity';+import { flowluProps, flowluWire } from '../../common/props';+import { flowluInput } from '../../common/utils';+import { opportunityEnvelopeOutputSchema } from '../../output-schemas';export const createOpportunityAction = createAction({auth: flowluAuth,@@ -13,8 +13,12 @@ export const createOpportunityAction = createAction({classification: 'WRITE',displayName: 'Create Opportunity',description: 'Creates a new opportunity.',- audience: 'both',- aiMetadata: { description: 'Creates a new sales opportunity (deal) in Flowlu CRM, requiring a title. Use to open a new deal, optionally linking it to an account, sales pipeline, and stage. Not idempotent — each call creates a new opportunity record.', idempotent: false },+ audience: 'human',+ aiMetadata: {+ description:+ 'Creates a new sales opportunity (deal) in Flowlu CRM, requiring a title. Use to open a new deal, optionally linking it to an account, sales pipeline, and stage. Not idempotent — each call creates a new opportunity record. For agents use flowlu_opportunity_create.',+ idempotent: false,+ },props: {name: Property.ShortText({displayName: 'Title',@@ -22,10 +26,60 @@ export const createOpportunityAction = createAction({}),...flowluProps.opportunity,},+ outputSchema: opportunityEnvelopeOutputSchema,async run(context) {- const client = makeClient(- context.auth- );- return await client.createOpportunity(context.propsValue);+ const props = context.propsValue;+ const customerId = flowluInput.optionalId({+ value: props.customer_id,+ name: 'Customer ID',+ });+ const contactId = flowluInput.optionalId({+ value: props.contact_id,+ name: 'Contact ID',+ });+ const fields = {+ ...flowluWire.fieldsOnly(props),+ start_date: flowluInput.formatDate({+ value: props.start_date,+ name: 'Start Date',+ }),+ deadline: flowluInput.formatDate({+ value: props.deadline,+ name: 'End Date',+ }),+ };+ const client = makeClient(context.auth);+ const stage = await flowluOpportunity.stageAndCloseFields({+ client,+ opportunityId: undefined,+ pipelineId: flowluInput.optionalId({+ value: props.pipeline_id,+ name: 'Sales Pipeline ID',+ }),+ stageId: flowluInput.optionalId({+ value: props.pipeline_stage_id,+ name: 'Sales Pipeline Stage ID',+ }),+ status: undefined,+ closingDate: undefined,+ });+ const res = await client.createOpportunity({+ ...fields,+ pipeline_id: stage.pipeline_id,+ pipeline_stage_id: stage.pipeline_stage_id,+ });+ if (customerId === undefined && contactId === undefined) {+ return res;+ }+ const links = await flowluLinks.linkLegacyCustomer({+ client,+ leadId: flowluInput.requireId({+ value: res.response?.['id'],+ name: 'Created opportunity id',+ }),+ customerId,+ contactId,+ });+ return links === undefined ? res : { ...res, ...links };},});diff --git a/packages/pieces/community/flowlu/src/lib/actions/opportunities/delete-opportunity.ts b/packages/pieces/community/flowlu/src/lib/actions/opportunities/delete-opportunity.tsindex e0a893d0b3b..0aed7831ed8 100644--- a/packages/pieces/community/flowlu/src/lib/actions/opportunities/delete-opportunity.ts+++ b/packages/pieces/community/flowlu/src/lib/actions/opportunities/delete-opportunity.ts@@ -1,10 +1,9 @@-import {- createAction,- PiecePropValueSchema,-} from '@activepieces/pieces-framework';+import { createAction } from '@activepieces/pieces-framework';import { flowluAuth } from '../../auth';import { flowluCommon, makeClient } from '../../common';+import { flowluInput } from '../../common/utils';import { FlowluEntity, FlowluModule } from '../../common/constants';+import { deletedEnvelopeOutputSchema } from '../../output-schemas';export const deleteOpportunityAction = createAction({auth: flowluAuth,@@ -12,16 +11,22 @@ export const deleteOpportunityAction = createAction({classification: 'DESTRUCTIVE',displayName: 'Delete Opportunity',description: 'Deletes an existing opportunity.',- audience: 'both',- aiMetadata: { description: 'Deletes a sales opportunity (deal) in Flowlu CRM by its opportunity id. Use to permanently remove a deal. Effectively idempotent in end state once removed, but it mutates data and a repeat call targets an already-deleted record.', idempotent: false },+ audience: 'human',+ aiMetadata: {+ description:+ 'Deletes a sales opportunity (deal) in Flowlu CRM by its opportunity id. Use to permanently remove a deal. Effectively idempotent in end state once removed, but it mutates data and a repeat call targets an already-deleted record. For agents use flowlu_opportunity_delete.',+ idempotent: false,+ },props: {id: flowluCommon.opportunity_id(true),},+ outputSchema: deletedEnvelopeOutputSchema,async run(context) {- const id = context.propsValue.id!;- const client = makeClient(- context.auth- );+ const id = flowluInput.requireId({+ value: context.propsValue.id,+ name: 'Opportunity ID',+ });+ const client = makeClient(context.auth);return await client.deleteAction(FlowluModule.CRM,FlowluEntity.OPPORTUNITY,diff --git a/packages/pieces/community/flowlu/src/lib/actions/opportunities/find-opportunities.ts b/packages/pieces/community/flowlu/src/lib/actions/opportunities/find-opportunities.tsnew file mode 100644index 00000000000..0768e316bb1--- /dev/null+++ b/packages/pieces/community/flowlu/src/lib/actions/opportunities/find-opportunities.ts@@ -0,0 +1,87 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { flowluAuth } from '../../auth';+import { makeClient } from '../../common';+import { flowluFind, flowluInput, flowluSharedProps } from '../../common/utils';+import { opportunityListOutputSchema } from '../../output-schemas';++export const findOpportunitiesAction = createAction({+ auth: flowluAuth,+ name: 'flowlu_find_opportunities',+ classification: 'SEARCH',+ displayName: 'Find Opportunities',+ description: 'Searches CRM opportunities (deals).',+ audience: 'both',+ aiMetadata: {+ description:+ 'Searches Flowlu opportunities by text and optional filters for pipeline, stage, status (in progress, lost, won) and assignee, returning one page of deals with has_more for paging. Use to find an opportunity ID before reading, updating, linking or deleting it. Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ search: flowluSharedProps.search(+ 'Text to look for in opportunity names and other text fields. Leave empty to list all.'+ ),+ pipeline_id: Property.ShortText({+ displayName: 'Pipeline ID',+ description:+ 'Only opportunities in this pipeline. Numeric ID from List Reference Values (pipelines).',+ required: false,+ }),+ pipeline_stage_id: Property.ShortText({+ displayName: 'Pipeline Stage ID',+ description:+ 'Only opportunities in this stage. Numeric ID from List Reference Values (pipeline_stages).',+ required: false,+ }),+ status: Property.StaticDropdown({+ displayName: 'Status',+ description:+ 'Only in-progress, lost or won opportunities. Leave empty for all.',+ required: false,+ options: {+ disabled: false,+ options: [+ { label: 'In progress', value: 1 },+ { label: 'Lost', value: 2 },+ { label: 'Won', value: 3 },+ ],+ },+ }),+ assignee_id: Property.ShortText({+ displayName: 'Assignee User ID',+ description:+ 'Only opportunities assigned to this user. Numeric user ID from List Users.',+ required: false,+ }),+ order: flowluSharedProps.order(),+ page: flowluSharedProps.page(),+ limit: flowluSharedProps.limit(),+ },+ outputSchema: opportunityListOutputSchema,+ async run(context) {+ const props = context.propsValue;+ return flowluFind.run({+ client: makeClient(context.auth),+ module: 'crm',+ entity: 'lead',+ props,+ filters: {+ 'filter[pipeline_id]': flowluInput.optionalId({+ value: props.pipeline_id,+ name: 'Pipeline ID',+ }),+ 'filter[pipeline_stage_id]': flowluInput.optionalId({+ value: props.pipeline_stage_id,+ name: 'Pipeline Stage ID',+ }),+ 'filter[active]': flowluInput.optionalNumber({+ value: props.status,+ name: 'Status',+ }),+ 'filter[assignee_id]': flowluInput.optionalId({+ value: props.assignee_id,+ name: 'Assignee User ID',+ }),+ },+ });+ },+});diff --git a/packages/pieces/community/flowlu/src/lib/actions/opportunities/get-opportunity.ts b/packages/pieces/community/flowlu/src/lib/actions/opportunities/get-opportunity.tsnew file mode 100644index 00000000000..b9c315fffd7--- /dev/null+++ b/packages/pieces/community/flowlu/src/lib/actions/opportunities/get-opportunity.ts@@ -0,0 +1,35 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { flowluAuth } from '../../auth';+import { makeClient } from '../../common';+import { flowluInput } from '../../common/utils';+import { opportunityOutputSchema } from '../../output-schemas';++export const getOpportunityAction = createAction({+ auth: flowluAuth,+ name: 'flowlu_get_opportunity',+ classification: 'READ',+ displayName: 'Get Opportunity',+ description: 'Gets a CRM opportunity by ID.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Returns one Flowlu opportunity (deal: name, amount, pipeline and stage, status, assignee, dates) by its numeric opportunity_id. Use to read a deal before updating or closing it; use flowlu_find_opportunities to look deals up by name or pipeline. Fails if it does not exist. Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ opportunity_id: Property.ShortText({+ displayName: 'Opportunity ID',+ description:+ 'Numeric opportunity ID, such as "42". Map it from an earlier step or from Find Opportunities.',+ required: true,+ }),+ },+ outputSchema: opportunityOutputSchema,+ async run(context) {+ const id = flowluInput.requireId({+ value: context.propsValue.opportunity_id,+ name: 'Opportunity ID',+ });+ return makeClient(context.auth).getRecord('crm', 'lead', id);+ },+});diff --git a/packages/pieces/community/flowlu/src/lib/actions/opportunities/link-account-to-opportunity.ts b/packages/pieces/community/flowlu/src/lib/actions/opportunities/link-account-to-opportunity.tsnew file mode 100644index 00000000000..1169c6ad743--- /dev/null+++ b/packages/pieces/community/flowlu/src/lib/actions/opportunities/link-account-to-opportunity.ts@@ -0,0 +1,70 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { flowluAuth } from '../../auth';+import { makeClient } from '../../common';+import { FlowluApiError } from '../../common/client';+import { flowluLinks } from '../../common/links';+import { flowluInput } from '../../common/utils';+import { linkOutputSchema } from '../../output-schemas';++export const linkAccountToOpportunityAction = createAction({+ auth: flowluAuth,+ name: 'flowlu_link_account_to_opportunity',+ classification: 'WRITE',+ displayName: 'Link Account to Opportunity',+ description: 'Links a CRM contact or organization to an opportunity.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Links one Flowlu CRM account (contact or organization) to one opportunity, so the deal shows that customer. Checks for an existing link first and returns it with already_linked true instead of adding a duplicate, so it is safe to retry. Needs the opportunity ID, the account ID and whether the account is a contact or an organization.',+ idempotent: true,+ },+ props: {+ opportunity_id: Property.ShortText({+ displayName: 'Opportunity ID',+ description: 'Numeric opportunity ID, such as "42".',+ required: true,+ }),+ account_id: Property.ShortText({+ displayName: 'Account ID',+ description:+ 'Numeric ID of the contact or organization to link, such as "17".',+ required: true,+ }),+ account_type: Property.StaticDropdown({+ displayName: 'Account Type',+ description:+ 'Whether the account is a contact (person) or an organization (company).',+ required: true,+ options: {+ disabled: false,+ options: [+ { label: 'Organization', value: 'organization' },+ { label: 'Contact', value: 'contact' },+ ],+ },+ }),+ },+ outputSchema: linkOutputSchema,+ async run(context) {+ const leadId = flowluInput.requireId({+ value: context.propsValue.opportunity_id,+ name: 'Opportunity ID',+ });+ const accountId = flowluInput.requireId({+ value: context.propsValue.account_id,+ name: 'Account ID',+ });+ const type = context.propsValue.account_type;+ if (type !== 'organization' && type !== 'contact') {+ throw new FlowluApiError({+ message: 'Account Type must be "organization" or "contact".',+ });+ }+ return flowluLinks.linkAccountToLead({+ client: makeClient(context.auth),+ leadId,+ accountId,+ accountType: type === 'organization' ? 1 : 2,+ });+ },+});diff --git a/packages/pieces/community/flowlu/src/lib/actions/opportunities/update-opportunity.ts b/packages/pieces/community/flowlu/src/lib/actions/opportunities/update-opportunity.tsindex ce0c2520ee3..d4673b447f5 100644--- a/packages/pieces/community/flowlu/src/lib/actions/opportunities/update-opportunity.ts+++ b/packages/pieces/community/flowlu/src/lib/actions/opportunities/update-opportunity.ts@@ -1,11 +1,11 @@-import {- PiecePropValueSchema,- Property,- createAction,-} from '@activepieces/pieces-framework';+import { Property, createAction } from '@activepieces/pieces-framework';import { flowluAuth } from '../../auth';import { flowluCommon, makeClient } from '../../common';-import { flowluProps } from '../../common/props';+import { flowluLinks } from '../../common/links';+import { flowluOpportunity } from '../../common/opportunity';+import { flowluProps, flowluWire } from '../../common/props';+import { flowluInput } from '../../common/utils';+import { opportunityEnvelopeOutputSchema } from '../../output-schemas';export const updateOpportunityAction = createAction({auth: flowluAuth,@@ -13,8 +13,12 @@ export const updateOpportunityAction = createAction({classification: 'WRITE',displayName: 'Update Opportunity',description: 'Updates an existing opportunity.',- audience: 'both',- aiMetadata: { description: 'Updates fields on an existing sales opportunity (deal) in Flowlu CRM, identified by its opportunity id. Use to change a deal\'s title, pipeline stage, linked account, or other details. The id is required and must reference an existing opportunity.', idempotent: false },+ audience: 'human',+ aiMetadata: {+ description:+ "Updates fields on an existing sales opportunity (deal) in Flowlu CRM, identified by its opportunity id. Use to change a deal's title, pipeline stage, linked account, or other details, or to mark it won or lost. Only filled fields are sent; a stage without a pipeline is checked against the deal's current pipeline. Idempotent: repeating the same update leaves the deal unchanged, and repeating Won or Lost keeps the existing close date. For agents use flowlu_opportunity_update.",+ idempotent: true,+ },props: {id: flowluCommon.opportunity_id(true),name: Property.ShortText({@@ -22,12 +26,78 @@ export const updateOpportunityAction = createAction({required: false,}),...flowluProps.opportunity,+ status: Property.StaticDropdown({+ displayName: 'Status',+ description:+ 'Set to Won or Lost to close the opportunity, or In progress to reopen it. Moving it to Won or Lost sets the close date to today; an opportunity that already has that status keeps its close date. Leave empty to keep the current status.',+ required: false,+ options: {+ disabled: false,+ options: [+ { label: 'In progress', value: 1 },+ { label: 'Lost', value: 2 },+ { label: 'Won', value: 3 },+ ],+ },+ }),+ closing_status_id: flowluCommon.loss_reason_id(false),+ closing_comment: Property.LongText({+ displayName: 'Closing Comment',+ description: 'Note about why the opportunity was won or lost.',+ required: false,+ }),},+ outputSchema: opportunityEnvelopeOutputSchema,async run(context) {- const id = context.propsValue.id!;- const client = makeClient(- context.auth- );- return await client.updateOpportunity(id, context.propsValue);+ const { id: rawId, status: rawStatus, ...props } = context.propsValue;+ const id = flowluInput.requireId({ value: rawId, name: 'Opportunity ID' });+ const status = flowluInput.oneOf({+ value: rawStatus,+ name: 'Status',+ allowed: [1, 2, 3],+ });+ const customerId = flowluInput.optionalId({+ value: props.customer_id,+ name: 'Customer ID',+ });+ const contactId = flowluInput.optionalId({+ value: props.contact_id,+ name: 'Contact ID',+ });+ const fields = {+ ...flowluWire.fieldsOnly(props),+ start_date: flowluInput.formatDate({+ value: props.start_date,+ name: 'Start Date',+ }),+ deadline: flowluInput.formatDate({+ value: props.deadline,+ name: 'End Date',+ }),+ active: status,+ };+ const client = makeClient(context.auth);+ const derived = await flowluOpportunity.stageAndCloseFields({+ client,+ opportunityId: id,+ pipelineId: flowluInput.optionalId({+ value: props.pipeline_id,+ name: 'Sales Pipeline ID',+ }),+ stageId: flowluInput.optionalId({+ value: props.pipeline_stage_id,+ name: 'Sales Pipeline Stage ID',+ }),+ status,+ closingDate: undefined,+ });+ const res = await client.updateOpportunity(id, { ...fields, ...derived });+ const links = await flowluLinks.linkLegacyCustomer({+ client,+ leadId: id,+ customerId,+ contactId,+ });+ return links === undefined ? res : { ...res, ...links };},});diff --git a/packages/pieces/community/flowlu/src/lib/actions/projects/create-project.ts b/packages/pieces/community/flowlu/src/lib/actions/projects/create-project.tsnew file mode 100644index 00000000000..9f63bc2e3c9--- /dev/null+++ b/packages/pieces/community/flowlu/src/lib/actions/projects/create-project.ts@@ -0,0 +1,44 @@+import { Property, createAction } from '@activepieces/pieces-framework';+import { flowluAuth } from '../../auth';+import { flowluCommon, makeClient } from '../../common';+import { flowluAiBody } from '../../common/ai-props';+import { flowluProjectProps } from '../../common/project-props';+import { flowluOutput } from '../../common/utils';+import { projectCreateOutputSchema } from '../../output-schemas';++export const createProjectAction = createAction({+ auth: flowluAuth,+ name: 'flowlu_create_project',+ classification: 'WRITE',+ displayName: 'Create Project',+ description: 'Creates a new project.',+ audience: 'human',+ aiMetadata: {+ description:+ 'Creates a new Flowlu project with a manager, customer, dates and template picked from lists. For agents use flowlu_project_create. Not idempotent: each call creates a new project.',+ idempotent: false,+ },+ props: {+ name: Property.ShortText({+ displayName: 'Name',+ required: true,+ }),+ project_type_id: flowluCommon.project_template_id(false),+ ...flowluProjectProps.fields(),+ },+ outputSchema: projectCreateOutputSchema,+ async run(context) {+ const client = makeClient(context.auth);+ const created = await client.createRecord(+ 'st',+ 'projects',+ flowluAiBody.project(context.propsValue)+ );+ return flowluOutput.fullRecord({+ client,+ module: 'st',+ entity: 'projects',+ created,+ });+ },+});diff --git a/packages/pieces/community/flowlu/src/lib/actions/projects/find-projects.ts b/packages/pieces/community/flowlu/src/lib/actions/projects/find-projects.tsnew file mode 100644index 00000000000..68d2854d667--- /dev/null+++ b/packages/pieces/community/flowlu/src/lib/actions/projects/find-projects.ts@@ -0,0 +1,66 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { flowluAuth } from '../../auth';+import { makeClient } from '../../common';+import { flowluFind, flowluInput, flowluSharedProps } from '../../common/utils';+import { projectListOutputSchema } from '../../output-schemas';++export const findProjectsAction = createAction({+ auth: flowluAuth,+ name: 'flowlu_find_projects',+ classification: 'SEARCH',+ displayName: 'Find Projects',+ description: 'Searches projects.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Searches Flowlu projects by text and optional filters for manager and customer organization, skipping archived projects unless include_archived is set, and returns one page with has_more for paging. Use to find a project ID before reading or updating it or adding tasks to it. Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ search: flowluSharedProps.search(+ 'Text to look for in project names and other text fields. Leave empty to list all.'+ ),+ manager_id: Property.ShortText({+ displayName: 'Manager User ID',+ description:+ 'Only projects managed by this user. Numeric user ID from List Users.',+ required: false,+ }),+ customer_id: Property.ShortText({+ displayName: 'Customer Organization ID',+ description:+ 'Only projects for this CRM organization. Numeric ID from Find CRM Accounts.',+ required: false,+ }),+ include_archived: Property.Checkbox({+ displayName: 'Include Archived',+ description: 'Also return archived projects.',+ required: false,+ defaultValue: false,+ }),+ order: flowluSharedProps.order(),+ page: flowluSharedProps.page(),+ limit: flowluSharedProps.limit(),+ },+ outputSchema: projectListOutputSchema,+ async run(context) {+ const props = context.propsValue;+ return flowluFind.run({+ client: makeClient(context.auth),+ module: 'st',+ entity: 'projects',+ props,+ filters: {+ 'filter[manager_id]': flowluInput.optionalId({+ value: props.manager_id,+ name: 'Manager User ID',+ }),+ 'filter[customer_id]': flowluInput.optionalId({+ value: props.customer_id,+ name: 'Customer Organization ID',+ }),+ 'filter[is_archive]': props.include_archived ? undefined : 0,+ },+ });+ },+});diff --git a/packages/pieces/community/flowlu/src/lib/actions/projects/get-project.ts b/packages/pieces/community/flowlu/src/lib/actions/projects/get-project.tsnew file mode 100644index 00000000000..b882cde8317--- /dev/null+++ b/packages/pieces/community/flowlu/src/lib/actions/projects/get-project.ts@@ -0,0 +1,35 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { flowluAuth } from '../../auth';+import { makeClient } from '../../common';+import { flowluInput } from '../../common/utils';+import { projectOutputSchema } from '../../output-schemas';++export const getProjectAction = createAction({+ auth: flowluAuth,+ name: 'flowlu_get_project',+ classification: 'READ',+ displayName: 'Get Project',+ description: 'Gets a project by ID.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Returns one Flowlu project (name, manager, customer, dates, priority, archive state, planned revenue/expenses) by its numeric project_id. Use to read a project before updating it; use flowlu_find_projects to look projects up by name. Fails if it does not exist. Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ project_id: Property.ShortText({+ displayName: 'Project ID',+ description:+ 'Numeric project ID, such as "42". Map it from an earlier step or from Find Projects.',+ required: true,+ }),+ },+ outputSchema: projectOutputSchema,+ async run(context) {+ const id = flowluInput.requireId({+ value: context.propsValue.project_id,+ name: 'Project ID',+ });+ return makeClient(context.auth).getRecord('st', 'projects', id);+ },+});diff --git a/packages/pieces/community/flowlu/src/lib/actions/projects/update-project.ts b/packages/pieces/community/flowlu/src/lib/actions/projects/update-project.tsnew file mode 100644index 00000000000..51af5a8972a--- /dev/null+++ b/packages/pieces/community/flowlu/src/lib/actions/projects/update-project.ts@@ -0,0 +1,57 @@+import { Property, createAction } from '@activepieces/pieces-framework';+import { flowluAuth } from '../../auth';+import { flowluCommon, makeClient } from '../../common';+import { flowluAiBody } from '../../common/ai-props';+import { FlowluApiError } from '../../common/client';+import { flowluProjectProps } from '../../common/project-props';+import { flowluInput } from '../../common/utils';+import { projectOutputSchema } from '../../output-schemas';++export const updateProjectAction = createAction({+ auth: flowluAuth,+ name: 'flowlu_update_project',+ classification: 'WRITE',+ displayName: 'Update Project',+ description: 'Updates an existing project.',+ audience: 'human',+ aiMetadata: {+ description:+ 'Updates fields on an existing Flowlu project picked from a list, including archiving it. Only filled fields are sent. For agents use flowlu_project_update. Idempotent: repeating the same update leaves the project unchanged.',+ idempotent: true,+ },+ props: {+ project_id: flowluCommon.project_id(true, 'Project'),+ name: Property.ShortText({+ displayName: 'Name',+ required: false,+ }),+ ...flowluProjectProps.fields(),+ is_archive: Property.StaticDropdown({+ displayName: 'Archived',+ description:+ 'Archive or restore the project. Leave empty to keep it as is.',+ required: false,+ options: {+ disabled: false,+ options: [+ { label: 'Archive', value: 'yes' },+ { label: 'Restore (not archived)', value: 'no' },+ ],+ },+ }),+ },+ outputSchema: projectOutputSchema,+ async run(context) {+ const id = flowluInput.requireId({+ value: context.propsValue.project_id,+ name: 'Project',+ });+ const body = flowluAiBody.project(context.propsValue);+ if (Object.keys(body).length === 0) {+ throw new FlowluApiError({+ message: 'Nothing to update: fill at least one field to change.',+ });+ }+ return makeClient(context.auth).updateRecord('st', 'projects', id, body);+ },+});diff --git a/packages/pieces/community/flowlu/src/lib/actions/tasks/create-task.ts b/packages/pieces/community/flowlu/src/lib/actions/tasks/create-task.tsindex 981b916fd46..3ec74f1e5aa 100644--- a/packages/pieces/community/flowlu/src/lib/actions/tasks/create-task.ts+++ b/packages/pieces/community/flowlu/src/lib/actions/tasks/create-task.ts@@ -1,11 +1,9 @@-import {- PiecePropValueSchema, Property,- createAction,-} from '@activepieces/pieces-framework';-import dayjs from 'dayjs';+import { Property, createAction } from '@activepieces/pieces-framework';import { flowluAuth } from '../../auth';import { makeClient } from '../../common';import { flowluProps } from '../../common/props';+import { flowluTaskWire } from '../../common/task-wire';+import { taskEnvelopeOutputSchema } from '../../output-schemas';export const createTaskAction = createAction({auth: flowluAuth,@@ -13,8 +11,12 @@ export const createTaskAction = createAction({classification: 'WRITE',displayName: 'Create Task',description: 'Creates a new task.',- audience: 'both',- aiMetadata: { description: 'Creates a new task in Flowlu, requiring a name and optionally setting priority, start/deadline dates, assignee (responsible/owner), type, and task workflow stage. Use to add a to-do or assignment. Not idempotent — each call creates a new task.', idempotent: false },+ audience: 'human',+ aiMetadata: {+ description:+ 'Creates a new task in Flowlu, requiring a name and optionally setting priority, start/deadline dates, assignee (responsible/owner), type, task workflow stage, project and CRM account. Use to add a to-do or assignment. Not idempotent — each call creates a new task. For agents use flowlu_task_create.',+ idempotent: false,+ },props: {name: Property.ShortText({displayName: 'Name',@@ -22,29 +24,12 @@ export const createTaskAction = createAction({}),...flowluProps.task,},+ outputSchema: taskEnvelopeOutputSchema,async run(context) {- const client = makeClient(- context.auth- );+ const client = makeClient(context.auth);return await client.createTask({- name: context.propsValue.name,- description: context.propsValue.description,- priority: context.propsValue.priority,- plan_start_date: context.propsValue.plan_start_date- ? dayjs(context.propsValue.plan_start_date).format(- 'YYYY-MM-DD HH:mm:ss'- )- : undefined,- deadline: context.propsValue.deadline- ? dayjs(context.propsValue.deadline).format('YYYY-MM-DD HH:mm:ss')- : undefined,- deadline_allowchange: context.propsValue.deadline_allowchange ? 1 : 0,- task_checkbyowner: context.propsValue.task_checkbyowner ? 1 : 0,- responsible_id: context.propsValue.responsible_id,- owner_id: context.propsValue.owner_id,+ ...flowluTaskWire.fields(context.propsValue),type: context.propsValue.type,- workflow_id: context.propsValue.workflow_id,- workflow_stage_id: context.propsValue.workflow_stage_id,});},});diff --git a/packages/pieces/community/flowlu/src/lib/actions/tasks/delete-task.ts b/packages/pieces/community/flowlu/src/lib/actions/tasks/delete-task.tsindex 75ec36d6947..070f3513d6a 100644--- a/packages/pieces/community/flowlu/src/lib/actions/tasks/delete-task.ts+++ b/packages/pieces/community/flowlu/src/lib/actions/tasks/delete-task.ts@@ -1,10 +1,9 @@-import {- createAction,- PiecePropValueSchema,-} from '@activepieces/pieces-framework';+import { createAction } from '@activepieces/pieces-framework';import { flowluAuth } from '../../auth';import { flowluCommon, makeClient } from '../../common';+import { flowluInput } from '../../common/utils';import { FlowluEntity, FlowluModule } from '../../common/constants';+import { deletedEnvelopeOutputSchema } from '../../output-schemas';export const deleteTaskAction = createAction({auth: flowluAuth,@@ -12,16 +11,22 @@ export const deleteTaskAction = createAction({classification: 'DESTRUCTIVE',displayName: 'Delete Task',description: 'Deletes an existing task.',- audience: 'both',- aiMetadata: { description: 'Deletes a task in Flowlu by its task id. Use to permanently remove a task. Effectively idempotent in end state once removed, but it mutates data and a repeat call targets an already-deleted record.', idempotent: false },+ audience: 'human',+ aiMetadata: {+ description:+ 'Deletes a task in Flowlu by its task id. Use to permanently remove a task. Effectively idempotent in end state once removed, but it mutates data and a repeat call targets an already-deleted record. For agents use flowlu_task_delete.',+ idempotent: false,+ },props: {task_id: flowluCommon.task_id(true),},+ outputSchema: deletedEnvelopeOutputSchema,async run(context) {- const task_id = context.propsValue.task_id!;- const client = makeClient(- context.auth- );+ const task_id = flowluInput.requireId({+ value: context.propsValue.task_id,+ name: 'Task ID',+ });+ const client = makeClient(context.auth);return await client.deleteAction(FlowluModule.TASK,FlowluEntity.TASKS,diff --git a/packages/pieces/community/flowlu/src/lib/actions/tasks/find-tasks.ts b/packages/pieces/community/flowlu/src/lib/actions/tasks/find-tasks.tsnew file mode 100644index 00000000000..bb64f1f0e29--- /dev/null+++ b/packages/pieces/community/flowlu/src/lib/actions/tasks/find-tasks.ts@@ -0,0 +1,79 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { flowluAuth } from '../../auth';+import { makeClient } from '../../common';+import { flowluFind, flowluInput, flowluSharedProps } from '../../common/utils';+import { taskListOutputSchema } from '../../output-schemas';++export const findTasksAction = createAction({+ auth: flowluAuth,+ name: 'flowlu_find_tasks',+ classification: 'SEARCH',+ displayName: 'Find Tasks',+ description: 'Searches tasks.',+ audience: 'both',+ aiMetadata: {+ description:+ "Searches Flowlu tasks by text and optional filters for status, assignee and project, returning one page of tasks with has_more for paging. Use to find a task ID before reading, updating or deleting it, or to list a project's open tasks. Read-only and idempotent.",+ idempotent: true,+ },+ props: {+ search: flowluSharedProps.search(+ 'Text to look for in task names and other text fields. Leave empty to list all.'+ ),+ status: Property.StaticDropdown({+ displayName: 'Status',+ description: 'Only tasks with this status. Leave empty for all.',+ required: false,+ options: {+ disabled: false,+ options: [+ { label: 'New', value: 1 },+ { label: 'In progress', value: 3 },+ { label: 'Pending owner approval', value: 4 },+ { label: 'Completed', value: 5 },+ ],+ },+ }),+ responsible_id: Property.ShortText({+ displayName: 'Assignee User ID',+ description:+ 'Only tasks assigned to this user. Numeric user ID from List Users.',+ required: false,+ }),+ project_id: Property.ShortText({+ displayName: 'Project ID',+ description: 'Only tasks in this project. Numeric ID from Find Projects.',+ required: false,+ }),+ order: flowluSharedProps.order(),+ page: flowluSharedProps.page(),+ limit: flowluSharedProps.limit(),+ },+ outputSchema: taskListOutputSchema,+ async run(context) {+ const props = context.propsValue;+ const projectId = flowluInput.optionalId({+ value: props.project_id,+ name: 'Project ID',+ });+ return flowluFind.run({+ client: makeClient(context.auth),+ module: 'task',+ entity: 'tasks',+ props,+ filters: {+ 'filter[status]': flowluInput.optionalNumber({+ value: props.status,+ name: 'Status',+ }),+ 'filter[responsible_id]': flowluInput.optionalId({+ value: props.responsible_id,+ name: 'Assignee User ID',+ }),+ 'filter[module]': projectId === undefined ? undefined : 'st',+ 'filter[model]': projectId === undefined ? undefined : 'project',+ 'filter[model_id]': projectId,+ },+ });+ },+});diff --git a/packages/pieces/community/flowlu/src/lib/actions/tasks/get-task.ts b/packages/pieces/community/flowlu/src/lib/actions/tasks/get-task.tsindex ebb051f1ba5..2f945dac2f5 100644--- a/packages/pieces/community/flowlu/src/lib/actions/tasks/get-task.ts+++ b/packages/pieces/community/flowlu/src/lib/actions/tasks/get-task.ts@@ -1,9 +1,8 @@-import {- createAction,- PiecePropValueSchema,-} from '@activepieces/pieces-framework';+import { createAction } from '@activepieces/pieces-framework';import { flowluAuth } from '../../auth';import { flowluCommon, makeClient } from '../../common';+import { flowluInput } from '../../common/utils';+import { taskEnvelopeOutputSchema } from '../../output-schemas';export const getTaskAction = createAction({auth: flowluAuth,@@ -11,16 +10,22 @@ export const getTaskAction = createAction({classification: 'READ',displayName: 'Get Task',description: 'Retrieves an existing task.',- audience: 'both',- aiMetadata: { description: 'Retrieves a single task from Flowlu by its task id. Use to look up a task\'s current details before acting on it. Read-only and idempotent.', idempotent: true },+ audience: 'human',+ aiMetadata: {+ description:+ "Retrieves a single task from Flowlu by its task id. Use to look up a task's current details before acting on it. Read-only and idempotent. For agents use flowlu_task_get.",+ idempotent: true,+ },props: {task_id: flowluCommon.task_id(true),},+ outputSchema: taskEnvelopeOutputSchema,async run(context) {- const task_id = context.propsValue.task_id!;- const client = makeClient(- context.auth- );+ const task_id = flowluInput.requireId({+ value: context.propsValue.task_id,+ name: 'Task ID',+ });+ const client = makeClient(context.auth);return await client.getTask(task_id);},});diff --git a/packages/pieces/community/flowlu/src/lib/actions/tasks/update-task.ts b/packages/pieces/community/flowlu/src/lib/actions/tasks/update-task.tsindex 998cf5ef33b..fd6e09423a6 100644--- a/packages/pieces/community/flowlu/src/lib/actions/tasks/update-task.ts+++ b/packages/pieces/community/flowlu/src/lib/actions/tasks/update-task.ts@@ -1,11 +1,10 @@-import {- PiecePropValueSchema, Property,- createAction,-} from '@activepieces/pieces-framework';-import dayjs from 'dayjs';+import { Property, createAction } from '@activepieces/pieces-framework';import { flowluAuth } from '../../auth';import { flowluCommon, makeClient } from '../../common';import { flowluProps } from '../../common/props';+import { flowluTaskWire } from '../../common/task-wire';+import { flowluInput } from '../../common/utils';+import { taskEnvelopeOutputSchema } from '../../output-schemas';export const updateTaskAction = createAction({auth: flowluAuth,@@ -13,8 +12,12 @@ export const updateTaskAction = createAction({classification: 'WRITE',displayName: 'Update Task',description: 'Updates an existing task.',- audience: 'both',- aiMetadata: { description: 'Updates fields on an existing task in Flowlu, identified by its task id. Use to change a task\'s name, priority, dates, assignee, type, or workflow stage. The task id is required and must reference an existing task.', idempotent: false },+ audience: 'human',+ aiMetadata: {+ description:+ "Updates fields on an existing task in Flowlu, identified by its task id. Use to change a task's name, priority, dates, assignee, status, project, or workflow stage, or to change its type to Inbox, Event or Task template (choosing Task keeps the current type). Empty fields are not sent; the two approval/deadline checkboxes are always sent. The task id is required and must reference an existing task. Idempotent: repeating the same update leaves the task unchanged. For agents use flowlu_task_update.",+ idempotent: true,+ },props: {task_id: flowluCommon.task_id(true),name: Property.ShortText({@@ -22,30 +25,30 @@ export const updateTaskAction = createAction({required: false,}),...flowluProps.task,+ status: Property.StaticDropdown({+ displayName: 'Status',+ description: 'New task status. Leave empty to keep the current status.',+ required: false,+ options: {+ disabled: false,+ options: [+ { label: 'New', value: 1 },+ { label: 'In progress', value: 3 },+ { label: 'Pending owner approval', value: 4 },+ { label: 'Completed', value: 5 },+ ],+ },+ }),},+ outputSchema: taskEnvelopeOutputSchema,async run(context) {- const client = makeClient(- context.auth- );- return await client.updateTask(context.propsValue.task_id!, {- name: context.propsValue.name,- description: context.propsValue.description,- priority: context.propsValue.priority,- plan_start_date: context.propsValue.plan_start_date- ? dayjs(context.propsValue.plan_start_date).format(- 'YYYY-MM-DD HH:mm:ss'- )- : undefined,- deadline: context.propsValue.deadline- ? dayjs(context.propsValue.deadline).format('YYYY-MM-DD HH:mm:ss')- : undefined,- deadline_allowchange: context.propsValue.deadline_allowchange ? 1 : 0,- task_checkbyowner: context.propsValue.task_checkbyowner ? 1 : 0,- type: context.propsValue.type,- responsible_id: context.propsValue.responsible_id,- owner_id: context.propsValue.owner_id,- workflow_id: context.propsValue.workflow_id,- workflow_stage_id: context.propsValue.workflow_stage_id,+ const props = context.propsValue;+ const id = flowluInput.requireId({ value: props.task_id, name: 'Task ID' });+ const client = makeClient(context.auth);+ return await client.updateTask(id, {+ ...flowluTaskWire.fields(props),+ type: props.type === 0 ? undefined : props.type,+ status: props.status,});},});diff --git a/packages/pieces/community/flowlu/src/lib/auth.ts b/packages/pieces/community/flowlu/src/lib/auth.tsindex d41a8b19d7f..d12bdee2b66 100644--- a/packages/pieces/community/flowlu/src/lib/auth.ts+++ b/packages/pieces/community/flowlu/src/lib/auth.ts@@ -1,4 +1,6 @@+import { HttpMethod } from '@activepieces/pieces-common';import { PieceAuth, Property } from '@activepieces/pieces-framework';+import { FlowluApiError, FlowluClient } from './common/client';export const flowluAuth = PieceAuth.CustomAuth({required: true,@@ -12,6 +14,8 @@ export const flowluAuth = PieceAuth.CustomAuth({props: {domain: Property.ShortText({displayName: 'Domain',+ description:+ 'Your portal name only, for example "example" for https://example.flowlu.com. A pasted portal URL such as https://example.flowlu.com is also accepted.',required: true,}),apiKey: PieceAuth.SecretText({@@ -19,4 +23,35 @@ export const flowluAuth = PieceAuth.CustomAuth({required: true,}),},+ validate: async ({ auth }) => {+ try {+ const client = new FlowluClient(auth.domain, auth.apiKey);+ await client.request({+ method: HttpMethod.GET,+ path: '/core/user/list',+ query: { limit: 1 },+ });+ return { valid: true };+ } catch (error) {+ if (error instanceof FlowluApiError) {+ if (+ error.status === undefined ||+ error.errorCode === 11 ||+ error.status === 401 ||+ error.status === 403+ ) {+ return { valid: false, error: error.message };+ }+ if (error.status === 200) {+ return { valid: true };+ }+ return { valid: false, error: error.message };+ }+ return {+ valid: false,+ error:+ 'Could not reach Flowlu. Check that the Domain is your portal name, for example "example".',+ };+ }+ },});diff --git a/packages/pieces/community/flowlu/src/lib/common/ai-props.ts b/packages/pieces/community/flowlu/src/lib/common/ai-props.tsnew file mode 100644index 00000000000..ece637118c9--- /dev/null+++ b/packages/pieces/community/flowlu/src/lib/common/ai-props.ts@@ -0,0 +1,613 @@+import { Property } from '@activepieces/pieces-framework';+import { FormValue } from './client';+import { flowluInput, flowluSharedProps } from './utils';++export const flowluAiProps = {+ task: () => ({+ description: text({+ displayName: 'Description',+ description: 'Task description (plain text).',+ long: true,+ }),+ priority: Property.StaticDropdown({+ displayName: 'Priority',+ description: 'Task priority.',+ required: false,+ options: { disabled: false, options: PRIORITY_OPTIONS },+ }),+ type: Property.StaticDropdown({+ displayName: 'Type',+ description:+ 'Task type. Leave empty for a regular task (Flowlu default).',+ required: false,+ options: { disabled: false, options: TASK_TYPE_OPTIONS },+ }),+ plan_start_date: Property.DateTime({+ displayName: 'Start Date',+ description:+ 'Planned start, ISO 8601 such as "2026-10-01T09:00:00Z". Sent as "YYYY-MM-DD HH:mm:ss" in the Activepieces server time (UTC on Activepieces Cloud); Flowlu reads it in the portal timezone.',+ required: false,+ }),+ deadline: Property.DateTime({+ displayName: 'Deadline',+ description:+ 'End date, ISO 8601 such as "2026-10-05T17:00:00Z". Sent as "YYYY-MM-DD HH:mm:ss" in the Activepieces server time (UTC on Activepieces Cloud); Flowlu reads it in the portal timezone.',+ required: false,+ }),+ responsible_id: id({+ displayName: 'Assignee User ID',+ description:+ 'User who does the task. Get user IDs from flowlu_list_users.',+ }),+ owner_id: id({+ displayName: 'Owner User ID',+ description:+ 'User who owns (set) the task. Get user IDs from flowlu_list_users.',+ }),+ workflow_id: id({+ displayName: 'Workflow ID',+ description:+ 'Task workflow. Get IDs from flowlu_list_lookup_values with entity task_workflows.',+ }),+ workflow_stage_id: id({+ displayName: 'Workflow Status ID',+ description:+ 'Status within the workflow. Get IDs from flowlu_list_lookup_values with entity task_statuses.',+ }),+ project_id: id({+ displayName: 'Project ID',+ description:+ 'Links the task to this project. Get IDs from flowlu_find_projects.',+ }),+ crm_account_id: id({+ displayName: 'CRM Account ID',+ description:+ 'Links the task to a CRM contact or organization. Get IDs from flowlu_find_accounts.',+ }),+ parent_id: id({+ displayName: 'Parent Task ID',+ description: 'Makes this a subtask of that task.',+ }),+ deadline_allowchange: flowluSharedProps.triState({+ displayName: 'Assignee Can Change Deadline',+ description:+ 'Yes lets the assignee move the deadline. Leave empty to keep the current setting.',+ }),+ task_checkbyowner: flowluSharedProps.triState({+ displayName: 'Needs Owner Approval',+ description:+ 'Yes means the owner must approve the task before it is completed. Leave empty to keep the current setting.',+ }),+ }),+ account: () => ({+ name: text({+ displayName: 'Organization Name',+ description: 'Organization name. Required when creating an organization.',+ }),+ name_legal_full: text({+ displayName: 'Full Legal Name',+ description: 'Full legal name of the organization.',+ }),+ honorific_title_id: id({+ displayName: 'Honorific Title ID',+ description:+ 'Get IDs from flowlu_list_lookup_values with entity honorific_titles.',+ }),+ first_name: text({+ displayName: 'First Name',+ description: 'Contact first name. Required when creating a contact.',+ }),+ middle_name: text({+ displayName: 'Middle Name',+ description: 'Contact middle name.',+ }),+ last_name: text({+ displayName: 'Last Name',+ description: 'Contact last name.',+ }),+ owner_id: id({+ displayName: 'Owner User ID',+ description:+ 'User responsible for the account. Get user IDs from flowlu_list_users.',+ }),+ account_category_id: id({+ displayName: 'Category ID',+ description:+ 'Get IDs from flowlu_list_lookup_values with entity account_categories.',+ }),+ industry_id: id({+ displayName: 'Industry ID',+ description:+ 'Get IDs from flowlu_list_lookup_values with entity industries.',+ }),+ email: text({+ displayName: 'Email',+ description: 'Main email address, such as "[email protected]".',+ }),+ phone: text({ displayName: 'Phone', description: 'Main phone number.' }),+ phone2: text({+ displayName: 'Phone 2',+ description: 'Second phone number.',+ }),+ phone3: text({+ displayName: 'Phone 3',+ description: 'Third phone number.',+ }),+ web: text({+ displayName: 'Website',+ description: 'Website URL, such as "https://example.com".',+ }),+ description: text({+ displayName: 'Description',+ description: 'Notes about the account.',+ long: true,+ }),+ vat: text({+ displayName: 'VAT or Tax ID',+ description: 'VAT or tax identification number.',+ }),+ skype: text({ displayName: 'Skype', description: 'Skype name or link.' }),+ telegram: text({+ displayName: 'Telegram',+ description: 'Telegram username.',+ }),+ facebook: text({+ displayName: 'Facebook',+ description: 'Facebook profile link.',+ }),+ x: text({+ displayName: 'X (Twitter)',+ description: 'X / Twitter profile link.',+ }),+ linkedin: text({+ displayName: 'LinkedIn',+ description: 'LinkedIn profile link.',+ }),+ instagram: text({+ displayName: 'Instagram',+ description: 'Instagram profile link.',+ }),+ billing_country: text({+ displayName: 'Billing Country',+ description: 'Billing country.',+ }),+ billing_state: text({+ displayName: 'Billing State',+ description: 'Billing state or region.',+ }),+ billing_city: text({+ displayName: 'Billing City',+ description: 'Billing city.',+ }),+ billing_zip: text({+ displayName: 'Billing Postal Code',+ description: 'Billing postal code.',+ }),+ billing_address_line_1: text({+ displayName: 'Billing Address',+ description: 'Billing street address.',+ }),+ shipping_country: text({+ displayName: 'Shipping Country',+ description: 'Shipping country.',+ }),+ shipping_state: text({+ displayName: 'Shipping State',+ description: 'Shipping state or region.',+ }),+ shipping_city: text({+ displayName: 'Shipping City',+ description: 'Shipping city.',+ }),+ shipping_zip: text({+ displayName: 'Shipping Postal Code',+ description: 'Shipping postal code.',+ }),+ shipping_address_line_1: text({+ displayName: 'Shipping Address',+ description: 'Shipping street address.',+ }),+ }),+ opportunity: () => ({+ budget: Property.Number({+ displayName: 'Amount',+ description: 'Opportunity value in the portal currency, such as 1500.',+ required: false,+ }),+ pipeline_id: id({+ displayName: 'Pipeline ID',+ description:+ 'Sales pipeline. Get IDs from flowlu_list_lookup_values with entity pipelines.',+ }),+ pipeline_stage_id: id({+ displayName: 'Pipeline Stage ID',+ description:+ 'Stage in the pipeline, checked against it before saving. Creating needs Pipeline ID too; updating without Pipeline ID uses the pipeline the opportunity is already in. Get IDs from flowlu_list_lookup_values with entity pipeline_stages and parent_id = the pipeline ID.',+ }),+ source_id: id({+ displayName: 'Source ID',+ description:+ 'Where the opportunity came from. Get IDs from flowlu_list_lookup_values with entity opportunity_sources.',+ }),+ assignee_id: id({+ displayName: 'Assignee User ID',+ description:+ 'User responsible for the opportunity. Get user IDs from flowlu_list_users.',+ }),+ start_date: Property.DateTime({+ displayName: 'Start Date',+ description:+ 'Start date, such as "2026-10-01". Only the date part is used.',+ required: false,+ }),+ deadline: Property.DateTime({+ displayName: 'Expected Close Date',+ description:+ 'Planned close date, such as "2026-11-30". Only the date part is used.',+ required: false,+ }),+ description: text({+ displayName: 'Description',+ description: 'Notes about the opportunity.',+ long: true,+ }),+ contact_name: text({+ displayName: 'Contact Name',+ description:+ 'Free-text contact name stored on the opportunity (not a CRM link).',+ }),+ contact_email: text({+ displayName: 'Contact Email',+ description: 'Free-text contact email stored on the opportunity.',+ }),+ contact_phone: text({+ displayName: 'Contact Phone',+ description: 'Free-text contact phone stored on the opportunity.',+ }),+ contact_company: text({+ displayName: 'Contact Company',+ description: 'Free-text company name stored on the opportunity.',+ }),+ contact_position: text({+ displayName: 'Contact Position',+ description: 'Free-text job title stored on the opportunity.',+ }),+ }),+ project: () => ({+ description: text({+ displayName: 'Description',+ description: 'Project description.',+ long: true,+ }),+ manager_id: id({+ displayName: 'Manager User ID',+ description: 'Project manager. Get user IDs from flowlu_list_users.',+ }),+ customer_id: id({+ displayName: 'Customer Organization ID',+ description:+ 'CRM organization the project is for. Get IDs from flowlu_find_accounts.',+ }),+ customer_crm_contact_id: id({+ displayName: 'Customer Contact ID',+ description:+ 'CRM contact at the customer. Get IDs from flowlu_find_accounts.',+ }),+ crm_lead_id: id({+ displayName: 'Opportunity ID',+ description:+ 'CRM opportunity the project came from. Get IDs from flowlu_find_opportunities.',+ }),+ startdate: Property.DateTime({+ displayName: 'Start Date',+ description:+ 'Project start, such as "2026-10-01". Only the date part is used.',+ required: false,+ }),+ enddate: Property.DateTime({+ displayName: 'End Date',+ description:+ 'Project end, such as "2026-12-31". Only the date part is used.',+ required: false,+ }),+ priority: Property.StaticDropdown({+ displayName: 'Priority',+ description: 'Project priority.',+ required: false,+ options: { disabled: false, options: PRIORITY_OPTIONS },+ }),+ portfolio_id: id({+ displayName: 'Portfolio ID',+ description:+ 'Project portfolio. Get IDs from flowlu_list_lookup_values with entity project_portfolios.',+ }),+ tasks_workflow_id: id({+ displayName: 'Task Workflow ID',+ description:+ 'Workflow used by tasks in this project. Get IDs from flowlu_list_lookup_values with entity task_workflows.',+ }),+ estimated_revenue: Property.Number({+ displayName: 'Contract Amount',+ description: 'Planned revenue (contract sum).',+ required: false,+ }),+ estimated_expenses: Property.Number({+ displayName: 'Planned Expenses',+ description: 'Planned expense sum.',+ required: false,+ }),+ }),+};++export const flowluAiBody = {+ task: (props: Record<string, unknown>): Record<string, FormValue> => {+ const projectId = flowluInput.optionalId({+ value: props['project_id'],+ name: 'Project ID',+ });+ return flowluInput.compact({+ name: flowluInput.optionalText(props['name']),+ description: flowluInput.optionalText(props['description']),+ priority: flowluInput.oneOf({+ value: props['priority'],+ name: 'Priority',+ allowed: [1, 2, 3],+ }),+ type: flowluInput.oneOf({+ value: props['type'],+ name: 'Type',+ allowed: TASK_TYPE_OPTIONS.map((o) => o.value),+ }),+ status: flowluInput.oneOf({+ value: props['status'],+ name: 'Status',+ allowed: [1, 3, 4, 5],+ }),+ plan_start_date: flowluInput.formatDateTime({+ value: props['plan_start_date'],+ name: 'Start Date',+ }),+ deadline: flowluInput.formatDateTime({+ value: props['deadline'],+ name: 'Deadline',+ }),+ responsible_id: flowluInput.optionalId({+ value: props['responsible_id'],+ name: 'Assignee User ID',+ }),+ owner_id: flowluInput.optionalId({+ value: props['owner_id'],+ name: 'Owner User ID',+ }),+ workflow_id: flowluInput.optionalId({+ value: props['workflow_id'],+ name: 'Workflow ID',+ }),+ workflow_stage_id: flowluInput.optionalId({+ value: props['workflow_stage_id'],+ name: 'Workflow Status ID',+ }),+ module: projectId === undefined ? undefined : 'st',+ model: projectId === undefined ? undefined : 'project',+ model_id: projectId,+ crm_account_id: flowluInput.optionalId({+ value: props['crm_account_id'],+ name: 'CRM Account ID',+ }),+ parent_id: flowluInput.optionalId({+ value: props['parent_id'],+ name: 'Parent Task ID',+ }),+ deadline_allowchange: flowluInput.triStateFlag(+ props['deadline_allowchange']+ ),+ task_checkbyowner: flowluInput.triStateFlag(props['task_checkbyowner']),+ });+ },+ account: (props: Record<string, unknown>): Record<string, FormValue> =>+ flowluInput.compact({+ ...Object.fromEntries(+ ACCOUNT_TEXT_FIELDS.map((field) => [+ ACCOUNT_WIRE_NAMES[field] ?? field,+ flowluInput.optionalText(props[field]),+ ])+ ),+ honorific_title_id: flowluInput.optionalId({+ value: props['honorific_title_id'],+ name: 'Honorific Title ID',+ }),+ owner_id: flowluInput.optionalId({+ value: props['owner_id'],+ name: 'Owner User ID',+ }),+ account_category_id: flowluInput.optionalId({+ value: props['account_category_id'],+ name: 'Category ID',+ }),+ industry_id: flowluInput.optionalId({+ value: props['industry_id'],+ name: 'Industry ID',+ }),+ }),+ opportunity: (props: Record<string, unknown>): Record<string, FormValue> => {+ const pipelineId = flowluInput.optionalId({+ value: props['pipeline_id'],+ name: 'Pipeline ID',+ });+ const stageId = flowluInput.optionalId({+ value: props['pipeline_stage_id'],+ name: 'Pipeline Stage ID',+ });+ return flowluInput.compact({+ name: flowluInput.optionalText(props['name']),+ budget: flowluInput.optionalNumber({+ value: props['budget'],+ name: 'Amount',+ }),+ pipeline_id: pipelineId,+ pipeline_stage_id: stageId,+ source_id: flowluInput.optionalId({+ value: props['source_id'],+ name: 'Source ID',+ }),+ assignee_id: flowluInput.optionalId({+ value: props['assignee_id'],+ name: 'Assignee User ID',+ }),+ start_date: flowluInput.formatDate({+ value: props['start_date'],+ name: 'Start Date',+ }),+ deadline: flowluInput.formatDate({+ value: props['deadline'],+ name: 'Expected Close Date',+ }),+ description: flowluInput.optionalText(props['description']),+ contact_name: flowluInput.optionalText(props['contact_name']),+ contact_email: flowluInput.optionalText(props['contact_email']),+ contact_phone: flowluInput.optionalText(props['contact_phone']),+ contact_company: flowluInput.optionalText(props['contact_company']),+ contact_position: flowluInput.optionalText(props['contact_position']),+ });+ },+ project: (props: Record<string, unknown>): Record<string, FormValue> =>+ flowluInput.compact({+ name: flowluInput.optionalText(props['name']),+ description: flowluInput.optionalText(props['description']),+ manager_id: flowluInput.optionalId({+ value: props['manager_id'],+ name: 'Manager User ID',+ }),+ customer_id: flowluInput.optionalId({+ value: props['customer_id'],+ name: 'Customer Organization ID',+ }),+ customer_crm_contact_id: flowluInput.optionalId({+ value: props['customer_crm_contact_id'],+ name: 'Customer Contact ID',+ }),+ crm_lead_id: flowluInput.optionalId({+ value: props['crm_lead_id'],+ name: 'Opportunity ID',+ }),+ startdate: flowluInput.formatDate({+ value: props['startdate'],+ name: 'Start Date',+ }),+ enddate: flowluInput.formatDate({+ value: props['enddate'],+ name: 'End Date',+ }),+ priority: flowluInput.oneOf({+ value: props['priority'],+ name: 'Priority',+ allowed: [1, 2, 3],+ }),+ project_type_id: flowluInput.optionalId({+ value: props['project_type_id'],+ name: 'Template ID',+ }),+ briefcase_id: flowluInput.optionalId({+ value: props['portfolio_id'],+ name: 'Portfolio ID',+ }),+ tasks_workflow_id: flowluInput.optionalId({+ value: props['tasks_workflow_id'],+ name: 'Task Workflow ID',+ }),+ estimated_revenue: flowluInput.optionalNumber({+ value: props['estimated_revenue'],+ name: 'Contract Amount',+ }),+ estimated_expenses: flowluInput.optionalNumber({+ value: props['estimated_expenses'],+ name: 'Planned Expenses',+ }),+ is_archive: flowluInput.triStateFlag(props['is_archive']),+ }),+};++export const ACCOUNT_WIRE_NAMES: Record<string, string> = {+ vat: 'VAT',+ skype: 'social_network_link_1',+ facebook: 'social_network_link_3',+ x: 'social_network_link_4',+ linkedin: 'social_network_link_5',+ instagram: 'social_network_link_6',+};++function text({+ displayName,+ description,+ long = false,+}: {+ displayName: string;+ description: string;+ long?: boolean;+}) {+ return long+ ? Property.LongText({ displayName, description, required: false })+ : Property.ShortText({ displayName, description, required: false });+}++function id({+ displayName,+ description,+}: {+ displayName: string;+ description: string;+}) {+ return Property.ShortText({+ displayName,+ description: `${description} Numeric ID such as "42".`,+ required: false,+ });+}++const PRIORITY_OPTIONS = [+ { label: 'Low', value: 1 },+ { label: 'Medium', value: 2 },+ { label: 'High', value: 3 },+];++const TASK_TYPE_OPTIONS = [+ { label: 'Task', value: 0 },+ { label: 'Inbox', value: 1 },+ { label: 'Event', value: 20 },+ { label: 'Event: call', value: 21 },+ { label: 'Event: email', value: 22 },+ { label: 'Event: appointment', value: 23 },+ { label: 'Task template', value: 30 },+ { label: 'Milestone', value: 40 },+];++const ACCOUNT_TEXT_FIELDS = [+ 'name',+ 'name_legal_full',+ 'first_name',+ 'middle_name',+ 'last_name',+ 'email',+ 'phone',+ 'phone2',+ 'phone3',+ 'web',+ 'description',+ 'vat',+ 'skype',+ 'telegram',+ 'facebook',+ 'x',+ 'linkedin',+ 'instagram',+ 'billing_country',+ 'billing_state',+ 'billing_city',+ 'billing_zip',+ 'billing_address_line_1',+ 'shipping_country',+ 'shipping_state',+ 'shipping_city',+ 'shipping_zip',+ 'shipping_address_line_1',+];diff --git a/packages/pieces/community/flowlu/src/lib/common/client.ts b/packages/pieces/community/flowlu/src/lib/common/client.tsindex 4004aede778..6b24d0c0f98 100644--- a/packages/pieces/community/flowlu/src/lib/common/client.ts+++ b/packages/pieces/community/flowlu/src/lib/common/client.ts@@ -10,9 +10,6 @@ import {AccountCategory,AccountHonorificTitle,AccountIndustry,- CreateCRMAccountAPIRequest,- CreateOpportunityAPIRequest,- CreateTaskAPIRequest,ListAPIResponse,Opportunity,OpportunitySource,@@ -24,88 +21,435 @@ import {User,} from './types';-function emptyValueFilter(- accessor: (key: string) => any-): (key: string) => boolean {- return (key: string) => {- const val = accessor(key);- return (- val !== null &&- val !== undefined &&- (typeof val != 'string' || val.length > 0)- );- };+export class FlowluApiError extends Error {+ readonly status: number | undefined;+ readonly errorCode: number | undefined;+ readonly responseBody: unknown;++ constructor({+ message,+ status,+ errorCode,+ responseBody,+ }: {+ message: string;+ status?: number;+ errorCode?: number;+ responseBody?: unknown;+ }) {+ super(message);+ this.name = 'FlowluApiError';+ this.status = status;+ this.errorCode = errorCode;+ this.responseBody = responseBody;+ }}-export function prepareQuery(request?: Record<string, any>): QueryParams {- const params: QueryParams = {};- if (!request) return params;- Object.keys(request)- .filter(emptyValueFilter((k) => request[k]))- .forEach((k: string) => {- params[k] = (request as Record<string, any>)[k].toString();+const SLUG = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;++export function normalizeDomain(raw: unknown): string {+ const text = typeof raw === 'string' ? raw.trim().toLowerCase() : '';+ const slug = text+ .replace(/^https?:\/\//, '')+ .replace(/\/+$/, '')+ .replace(/\.flowlu\.com$/, '');+ if (!SLUG.test(slug)) {+ throw new FlowluApiError({+ message:+ 'The Flowlu Domain must be your portal name only, for example "example" for https://example.flowlu.com.',});+ }+ return slug;+}++export type FormValue = string | number | boolean | null | undefined;++export function toFormBody(fields: object): string {+ const params = new URLSearchParams();+ for (const [key, value] of Object.entries(fields)) {+ if (value === undefined || value === null || value === '') {+ continue;+ }+ if (typeof value === 'boolean') {+ params.append(key, value ? '1' : '0');+ } else if (typeof value === 'number') {+ if (!Number.isFinite(value)) {+ throw new FlowluApiError({+ message: `Field "${key}" must be a finite number.`,+ });+ }+ params.append(key, String(value));+ } else if (typeof value === 'string') {+ params.append(key, value);+ } else {+ throw new FlowluApiError({+ message: `Field "${key}" must be text, a number or a boolean.`,+ });+ }+ }+ return params.toString();+}++function cleanQuery(query: Record<string, FormValue> | undefined): QueryParams {+ const params: QueryParams = {};+ for (const [key, value] of Object.entries(query ?? {})) {+ if (value === undefined || value === null || value === '') {+ continue;+ }+ params[key] =+ typeof value === 'boolean' ? (value ? '1' : '0') : String(value);+ }return params;}+function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === 'object' && value !== null && !Array.isArray(value);+}++function short(text: string): string {+ return text.length > 300 ? `${text.slice(0, 300)}…` : text;+}++export function flowluErrorOf(body: unknown): FlowluApiError | undefined {+ if (+ !isRecord(body) ||+ body['error'] === undefined ||+ body['error'] === null+ ) {+ return undefined;+ }+ const error = body['error'];+ if (isRecord(error)) {+ const code =+ typeof error['error_code'] === 'number'+ ? error['error_code']+ : Number(error['error_code']);+ const msg =+ typeof error['error_msg'] === 'string'+ ? error['error_msg']+ : 'unknown error';+ const errorCode = Number.isFinite(code) ? code : undefined;+ let message = `Flowlu error ${errorCode ?? '?'}: ${msg}.`;+ if (errorCode === 11) {+ message = `Flowlu rejected the connection (error 11: ${msg}). Check the API key and the Domain.`;+ } else if (errorCode === 20) {+ message = `Flowlu could not find the record (error 20: ${msg}). Check the ID.`;+ }+ return new FlowluApiError({+ message,+ status: 200,+ errorCode,+ responseBody: body,+ });+ }+ const details = isRecord(body['details'])+ ? Object.entries(body['details'])+ .map(+ ([field, text]) =>+ `${field}: ${+ typeof text === 'string' ? text : JSON.stringify(text)+ }`+ )+ .join('; ')+ : '';+ const description =+ typeof body['description'] === 'string' ? body['description'] : '';+ const kind = typeof error === 'string' ? error : 'error';+ const message =+ kind === 'validation'+ ? `Flowlu validation error: ${+ details || description || 'the request was rejected'+ }.`+ : `Flowlu error: ${short(+ [kind, description, details].filter((p) => p !== '').join(' - ')+ )}.`;+ return new FlowluApiError({ message, status: 200, responseBody: body });+}++export function httpResponseOf(+ error: unknown+): { status: number; body: unknown } | undefined {+ if (!isRecord(error) && !(error instanceof Error)) {+ return undefined;+ }+ const response: unknown = Reflect.get(error, 'response');+ if (!isRecord(response) || typeof response['status'] !== 'number') {+ return undefined;+ }+ return { status: response['status'], body: response['body'] };+}++function httpFailure({+ status,+ body,+}: {+ status: number;+ body: unknown;+}): FlowluApiError {+ const vendor = flowluErrorOf(body);+ const text = vendor+ ? vendor.message+ : typeof body === 'string'+ ? short(body)+ : body === undefined+ ? ''+ : short(JSON.stringify(body));+ let message = `Flowlu request failed with HTTP ${status}${+ text ? `: ${text}` : '.'+ }`;+ if (status === 429) {+ message =+ 'Flowlu rate limit reached (HTTP 429) after 3 retries. Your Flowlu plan limits requests per second; try again later.';+ } else if (status === 401 || status === 403) {+ message = `Flowlu refused the request (HTTP ${status}). Check that the API key is valid and has access to this module.`;+ }+ return new FlowluApiError({+ message,+ status,+ errorCode: vendor?.errorCode,+ responseBody: body,+ });+}++export const RETRY_DELAYS_MS = [1000, 2000, 4000];++const REQUEST_TIMEOUT_MS = 20000;++export const flowluTiming = {+ sleep: (ms: number) =>+ new Promise<void>((resolve) => setTimeout(resolve, ms)),+};++export type ListEnvelope<T> = {+ total?: number;+ total_result?: number;+ page?: number;+ count?: number;+ items: T[];+};+export class FlowluClient {- constructor(private domain: string, private apiKey: string) {}+ private readonly slug: string;+ private readonly apiKey: string;++ constructor(domain: string, apiKey: string) {+ this.slug = normalizeDomain(domain);+ this.apiKey = typeof apiKey === 'string' ? apiKey.trim() : '';+ if (this.apiKey === '') {+ throw new FlowluApiError({+ message:+ 'The Flowlu API key is empty. Paste the key from Portal Settings > API Settings.',+ });+ }+ }++ get baseUrl(): string {+ return `https://${this.slug}.flowlu.com/api/v1/module`;+ }++ async request<T extends HttpMessageBody>({+ method,+ path,+ query,+ body,+ }: {+ method: HttpMethod;+ path: string;+ query?: Record<string, FormValue>;+ body?: object;+ }): Promise<T> {+ if (!/^\/[a-z_]+\/[a-z_]+(\/[a-z_]+(\/\d+)?)?$/.test(path)) {+ throw new FlowluApiError({ message: `Invalid Flowlu API path ${path}.` });+ }+ for (let attempt = 0; ; attempt++) {+ try {+ const res = await httpClient.sendRequest<T>({+ method,+ url: `${this.baseUrl}${path}`,+ headers:+ body === undefined+ ? undefined+ : { 'Content-Type': 'application/x-www-form-urlencoded' },+ queryParams: { ...cleanQuery(query), api_key: this.apiKey },+ body: body === undefined ? undefined : toFormBody(body),+ followRedirects: false,+ timeout: REQUEST_TIMEOUT_MS,+ });+ const payload: unknown = res.body;+ if (res.status >= 300) {+ throw new FlowluApiError({+ message: `Flowlu redirected the request (HTTP ${res.status}). Check that the Domain is your portal name, for example "example" for https://example.flowlu.com.`,+ status: res.status,+ });+ }+ const vendor = flowluErrorOf(payload);+ if (vendor) {+ throw vendor.errorCode === 11+ ? new FlowluApiError({+ message: `${vendor.message} The request went to https://${this.slug}.flowlu.com.`,+ status: vendor.status,+ errorCode: vendor.errorCode,+ responseBody: vendor.responseBody,+ })+ : vendor;+ }+ if (!isRecord(payload)) {+ throw new FlowluApiError({+ message:+ 'Flowlu returned an unexpected response (not a JSON object). Check the Domain.',+ status: res.status,+ responseBody:+ typeof payload === 'string' ? short(payload) : payload,+ });+ }+ return res.body;+ } catch (error) {+ if (error instanceof FlowluApiError) {+ throw error;+ }+ const response = httpResponseOf(error);+ if (response === undefined) {+ if (error instanceof Error && error.name === 'AbortError') {+ throw new FlowluApiError({+ message: `Flowlu did not answer within ${+ REQUEST_TIMEOUT_MS / 1000+ } seconds. Try again later.`,+ });+ }+ throw error;+ }+ if (response.status === 429 && attempt < RETRY_DELAYS_MS.length) {+ await flowluTiming.sleep(RETRY_DELAYS_MS[attempt]);+ continue;+ }+ throw httpFailure(response);+ }+ }+ }+async makeRequest<T extends HttpMessageBody>(method: HttpMethod,resourceUri: string,- query?: QueryParams,- body: any | undefined = undefined+ query?: Record<string, FormValue>,+ body: object | undefined = undefined): Promise<T> {- const res = await httpClient.sendRequest<T>({- method: method,- url: `https://${this.domain}.flowlu.com/api/v1/module` + resourceUri,- headers: {- 'Content-Type': 'application/x-www-form-urlencoded',- },- queryParams: { api_key: this.apiKey, ...query },- body: body,+ return this.request<T>({ method, path: resourceUri, query, body });+ }++ async getRecord<T = Record<string, unknown>>(+ module: string,+ entity: string,+ id: number+ ): Promise<T> {+ const res = await this.request<{ response: T }>({+ method: HttpMethod.GET,+ path: `/${module}/${entity}/get/${id}`,+ });+ return res.response;+ }++ async createRecord<T = Record<string, unknown>>(+ module: string,+ entity: string,+ body: Record<string, unknown>+ ): Promise<T> {+ const res = await this.request<{ response: T }>({+ method: HttpMethod.POST,+ path: `/${module}/${entity}/create`,+ body,});- return res.body;+ return res.response;}- async createAccount(request: CreateCRMAccountAPIRequest) {- return await this.makeRequest(++ async updateRecord<T = Record<string, unknown>>(+ module: string,+ entity: string,+ id: number,+ body: Record<string, unknown>+ ): Promise<T> {+ const res = await this.request<{ response: T }>({+ method: HttpMethod.POST,+ path: `/${module}/${entity}/update/${id}`,+ body,+ });+ return res.response;+ }++ async deleteRecord(+ module: string,+ entity: string,+ id: number+ ): Promise<{ id: string | number }> {+ const res = await this.request<{ response: { id: string | number } }>({+ method: HttpMethod.GET,+ path: `/${module}/${entity}/delete/${id}`,+ });+ return res.response;+ }++ async list<T = Record<string, unknown>>(+ module: string,+ entity: string,+ query?: Record<string, FormValue>+ ): Promise<ListEnvelope<T>> {+ const res = await this.request<{ response: ListEnvelope<T> }>({+ method: HttpMethod.GET,+ path: `/${module}/${entity}/list`,+ query,+ });+ const envelope = res.response;+ if (!isRecord(envelope) || !Array.isArray(envelope.items)) {+ throw new FlowluApiError({+ message: 'Flowlu returned a list without items.',+ responseBody: res,+ });+ }+ return envelope;+ }++ async createAccount(request: object) {+ return await this.makeRequest<RecordResponse>(HttpMethod.POST,'/crm/account/create',undefined,request);}- async updateContact(id: number, request: CreateCRMAccountAPIRequest) {- return await this.makeRequest(+ async updateContact(id: number, request: object) {+ return await this.makeRequest<RecordResponse>(HttpMethod.POST,`/crm/account/update/${id}`,undefined,request);}- async listAllAccounts() {+ async listAllAccounts(query?: Record<string, FormValue>) {return await this.makeRequest<ListAPIResponse<Account[]>>(HttpMethod.GET,- '/crm/account/list'+ '/crm/account/list',+ query);}- async listAllContacts() {+ async listAllContacts(query?: Record<string, FormValue>) {return await this.makeRequest<ListAPIResponse<Account[]>>(HttpMethod.GET,'/crm/account/list',- { 'filter[type]': '2' }+ {+ ...query,+ 'filter[type]': '2',+ });}- async createTask(request: CreateTaskAPIRequest) {- return await this.makeRequest(+ async createTask(request: object) {+ return await this.makeRequest<RecordResponse>(HttpMethod.POST,'/task/tasks/create',undefined,request);}- async updateTask(id: number, request: CreateTaskAPIRequest) {- return await this.makeRequest(+ async updateTask(id: number, request: object) {+ return await this.makeRequest<RecordResponse>(HttpMethod.POST,`/task/tasks/update/${id}`,undefined,@@ -113,90 +457,108 @@ export class FlowluClient {);}async getTask(id: number) {- return await this.makeRequest(HttpMethod.GET, `/task/tasks/get/${id}`);+ return await this.makeRequest<RecordResponse>(+ HttpMethod.GET,+ `/task/tasks/get/${id}`+ );}- async listAllTasks() {+ async listAllTasks(query?: Record<string, FormValue>) {return await this.makeRequest<ListAPIResponse<Task[]>>(HttpMethod.GET,- '/task/tasks/list'+ '/task/tasks/list',+ query);}- async createOpportunity(request: CreateOpportunityAPIRequest) {- return await this.makeRequest(+ async createOpportunity(request: object) {+ return await this.makeRequest<RecordResponse>(HttpMethod.POST,'/crm/lead/create',undefined,request);}- async updateOpportunity(id: number, request: CreateOpportunityAPIRequest) {- return await this.makeRequest(+ async updateOpportunity(id: number, request: object) {+ return await this.makeRequest<RecordResponse>(HttpMethod.POST,`/crm/lead/update/${id}`,undefined,request);}- async listAllOpportunities() {+ async listAllOpportunities(query?: Record<string, FormValue>) {return await this.makeRequest<ListAPIResponse<Opportunity[]>>(HttpMethod.GET,- '/crm/lead/list'+ '/crm/lead/list',+ query);}- async listAllUsers() {+ async listAllUsers(query?: Record<string, FormValue>) {return await this.makeRequest<ListAPIResponse<User[]>>(HttpMethod.GET,- '/core/user/list'+ '/core/user/list',+ query);}- async listAllTaskWorkflow() {+ async listAllTaskWorkflow(query?: Record<string, FormValue>) {return await this.makeRequest<ListAPIResponse<TaskWorkflow[]>>(HttpMethod.GET,- '/task/workflows/list'+ '/task/workflows/list',+ query);}- async listAllTaskStages() {+ async listAllTaskStages(query?: Record<string, FormValue>) {return await this.makeRequest<ListAPIResponse<TaskWorkflowStage[]>>(HttpMethod.GET,- '/task/stages/list'+ '/task/stages/list',+ query);}- async listAllHonorificTitles() {+ async listAllHonorificTitles(query?: Record<string, FormValue>) {return await this.makeRequest<ListAPIResponse<AccountHonorificTitle[]>>(HttpMethod.GET,- '/crm/honorific_title/list'+ '/crm/honorific_title/list',+ query);}- async listAllAccountCategories() {+ async listAllAccountCategories(query?: Record<string, FormValue>) {return await this.makeRequest<ListAPIResponse<AccountCategory[]>>(HttpMethod.GET,- '/crm/account_category/list'+ '/crm/account_category/list',+ query);}-- async listAllAccountIndustries() {+ async listAllAccountIndustries(query?: Record<string, FormValue>) {return await this.makeRequest<ListAPIResponse<AccountIndustry[]>>(HttpMethod.GET,- '/crm/industry/list'+ '/crm/industry/list',+ query);}- async listAllOpportunitySources() {+ async listAllOpportunitySources(query?: Record<string, FormValue>) {return await this.makeRequest<ListAPIResponse<OpportunitySource[]>>(HttpMethod.GET,- '/crm/source/list'+ '/crm/source/list',+ query);}- async listSalesPipelines() {+ async listSalesPipelines(query?: Record<string, FormValue>) {return await this.makeRequest<ListAPIResponse<Pipeline[]>>(HttpMethod.GET,- '/crm/pipeline/list'+ '/crm/pipeline/list',+ query);}- async listSalesPipelineStages(pipeline_id: number) {+ async listSalesPipelineStages(+ pipeline_id: number,+ query?: Record<string, FormValue>+ ) {return await this.makeRequest<ListAPIResponse<PipelineStage[]>>(HttpMethod.GET,'/crm/pipeline_stage/list',- { 'filter[pipeline_id]': pipeline_id.toString() }+ {+ ...query,+ 'filter[pipeline_id]': pipeline_id.toString(),+ });}@@ -205,9 +567,11 @@ export class FlowluClient {entityName: FlowluEntity,id: number) {- return await this.makeRequest(+ return await this.makeRequest<RecordResponse>(HttpMethod.GET,`/${moduleName}/${entityName}/delete/${id}`);}}++export type RecordResponse = { response: Record<string, unknown> };diff --git a/packages/pieces/community/flowlu/src/lib/common/index.ts b/packages/pieces/community/flowlu/src/lib/common/index.tsindex a3f45a9b7ca..4775fdce73c 100644--- a/packages/pieces/community/flowlu/src/lib/common/index.ts+++ b/packages/pieces/community/flowlu/src/lib/common/index.ts@@ -1,375 +1,147 @@-import { AppConnectionValueForAuthProperty, PiecePropValueSchema, Property } from '@activepieces/pieces-framework';+import {+ AppConnectionValueForAuthProperty,+ DropdownState,+ Property,+} from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';import { flowluAuth } from '../auth';-import { FlowluClient } from './client';+import { FlowluApiError, FlowluClient, FormValue } from './client';export function makeClient(auth: AppConnectionValueForAuthProperty<typeof flowluAuth>): FlowluClient {- const client = new FlowluClient(auth.props.domain, auth.props.apiKey);- return client;-}-function mapItemsToOptions(items: { id: string | number; name: string }[]) {- return items.map((item) => ({ label: item.name, value: item.id }));+ return new FlowluClient(auth.props.domain, auth.props.apiKey);}+export const flowluCommon = {task_id: (required = true) =>- Property.Dropdown({+ searchableDropdown({displayName: 'Task ID',required,- refreshers: [],- auth: flowluAuth,- options: async ({ auth }) => {- if (!auth) {- return {- disabled: true,- placeholder: 'Connect your account first',- options: [],- };- }- const client = makeClient(- auth- );- const { response } = await client.listAllTasks();- return {- disabled: false,- options: response.items.map((item) => {- return {- label: item.name,- value: item.id,- };- }),- };- },+ path: '/task/tasks/list',+ label: (item) => textOf(item['name']),}),user_id: (required = true, displayName = 'User ID') =>- Property.Dropdown({- auth: flowluAuth,+ searchableDropdown({displayName,required,- refreshers: [],- options: async ({ auth }) => {- if (!auth) {- return {- disabled: true,- placeholder: 'Connect your account first',- options: [],- };- }- const client = makeClient(- auth- );- const { response } = await client.listAllUsers();- return {- disabled: false,- options: response.items.map((item) => {- return {- label: item.name,- value: item.id,- };- }),- };- },+ path: '/core/user/list',+ label: (item) => textOf(item['name']),}),workflow_id: (required = false) =>- Property.Dropdown({- auth: flowluAuth,+ simpleDropdown({displayName: 'Task Workflow ID',required,- refreshers: [],- options: async ({ auth }) => {- if (!auth) {- return {- disabled: true,- placeholder: 'Connect your account first',- options: [],- };- }- const client = makeClient(- auth- );- const { response } = await client.listAllTaskWorkflow();- return {- disabled: false,- options: response.items.map((item) => {- return {- label: item.name,- value: item.id,- };- }),- };- },+ path: '/task/workflows/list',}),workflow_stage_id: (required = false) =>- Property.Dropdown({- auth: flowluAuth,+ simpleDropdown({displayName: 'Task Workflow Status ID',required,- refreshers: [],- options: async ({ auth }) => {- if (!auth) {- return {- disabled: true,- placeholder: 'Connect your account first',- options: [],- };- }- const client = makeClient(- auth- );- const { response } = await client.listAllTaskStages();- return {- disabled: false,- options: response.items.map((item) => {- return {- label: item.name,- value: item.id,- };- }),- };- },+ path: '/task/stages/list',}),honorific_title_id: (required = false) =>- Property.Dropdown({- auth: flowluAuth,+ simpleDropdown({displayName: 'Title',required,- refreshers: [],- options: async ({ auth }) => {- if (!auth) {- return {- disabled: true,- placeholder: 'Connect your account first',- options: [],- };- }- const client = makeClient(- auth- );- const res = await client.listAllHonorificTitles();- const { response } = res;- return {- disabled: false,- options: response.items.map((item) => {- return {- label: item.name,- value: item.id,- };- }),- };- },+ path: '/crm/honorific_title/list',}),account_category_id: (required = false) =>- Property.Dropdown({- auth: flowluAuth,+ simpleDropdown({displayName: 'Account Category',required,- refreshers: [],- options: async ({ auth }) => {- if (!auth) {- return {- disabled: true,- placeholder: 'Connect your account first',- options: [],- };- }- const client = makeClient(- auth- );- const { response } = await client.listAllAccountCategories();- return {- disabled: false,- options: response.items.map((item) => {- return {- label: item.name,- value: item.id,- };- }),- };- },+ path: '/crm/account_category/list',}),industry_id: (required = false) =>- Property.Dropdown({- auth: flowluAuth,+ simpleDropdown({displayName: 'Account Industry',required,- refreshers: [],- options: async ({ auth }) => {- if (!auth) {- return {- disabled: true,- placeholder: 'Connect your account first',- options: [],- };- }- const client = makeClient(- auth- );- const { response } = await client.listAllAccountIndustries();- return {- disabled: false,- options: response.items.map((item) => {- return {- label: item.name,- value: item.id,- };- }),- };- },+ path: '/crm/industry/list',}),source_id: (required = false) =>- Property.Dropdown({- auth: flowluAuth,+ simpleDropdown({displayName: 'Opportunity Source',required,- refreshers: [],- options: async ({ auth }) => {- if (!auth) {- return {- disabled: true,- placeholder: 'Connect your account first',- options: [],- };- }- const client = makeClient(- auth- );- const { response } = await client.listAllOpportunitySources();- return {- disabled: false,- options: response.items.map((item) => {- return {- label: item.name,- value: item.id,- };- }),- };- },+ path: '/crm/source/list',+ }),+ loss_reason_id: (required = false) =>+ simpleDropdown({+ displayName: 'Loss Reason',+ description:+ 'Why the opportunity was lost. Only used when Status is Lost.',+ required,+ path: '/crm/loss_reason/list',}),opportunity_id: (required = false) =>- Property.Dropdown({- auth: flowluAuth,+ searchableDropdown({displayName: 'Opportunity ID',required,- refreshers: [],- options: async ({ auth }) => {- if (!auth) {- return {- disabled: true,- placeholder: 'Connect your account first',- options: [],- };- }- const client = makeClient(- auth- );- const { response } = await client.listAllOpportunities();- return {- disabled: false,- options: response.items.map((item) => {- return {- label: item.name,- value: item.id,- };- }),- };- },+ path: '/crm/lead/list',+ label: (item) => textOf(item['name']),}),account_id: (required = false,displayName = 'Account ID',description = '') =>- Property.Dropdown({- auth: flowluAuth,+ searchableDropdown({displayName,description,required,- refreshers: [],- options: async ({ auth }) => {- if (!auth) {- return {- disabled: true,- placeholder: 'Connect your account first',- options: [],- };- }- const client = makeClient(- auth- );- const { response } = await client.listAllAccounts();- return {- disabled: false,- options: response.items.map((item) => {- return {- label: item.name,- value: item.id,- };- }),- };- },+ path: '/crm/account/list',+ label: (item) => textOf(item['name']),}),contact_id: (required = false,displayName = 'Contact ID',description = '') =>- Property.Dropdown({- auth: flowluAuth,+ searchableDropdown({displayName,description,required,- refreshers: [],- options: async ({ auth }) => {- if (!auth) {- return {- disabled: true,- placeholder: 'Connect your account first',- options: [],- };- }- const client = makeClient(- auth- );- const { response } = await client.listAllContacts();- return {- disabled: false,- options: response.items.map((item) => {- return {- label: item.name,- value: item.id,- };- }),- };- },+ path: '/crm/account/list',+ filter: { 'filter[type]': '2' },+ label: (item) => textOf(item['name']),+ }),+ organization_id: (+ required = false,+ displayName = 'Organization',+ description = ''+ ) =>+ searchableDropdown({+ displayName,+ description,+ required,+ path: '/crm/account/list',+ filter: { 'filter[type]': '1' },+ label: (item) => textOf(item['name']),+ }),+ project_id: (required = false, displayName = 'Project', description = '') =>+ searchableDropdown({+ displayName,+ description,+ required,+ path: '/st/projects/list',+ label: (item) => textOf(item['name']),+ }),+ project_template_id: (required = false) =>+ simpleDropdown({+ displayName: 'Project Template',+ required,+ path: '/st/project_types/list',+ }),+ portfolio_id: (required = false) =>+ simpleDropdown({+ displayName: 'Portfolio',+ required,+ path: '/st/portfolio/list',}),pipeline_id: (required = false) =>- Property.Dropdown({- auth: flowluAuth,+ simpleDropdown({displayName: 'Sales Pipeline ID',required,- refreshers: [],- options: async ({ auth }) => {- if (!auth) {- return {- disabled: true,- placeholder: 'Connect your account first',- options: [],- };- }- const client = makeClient(- auth- );- const { response } = await client.listSalesPipelines();- return {- disabled: false,- options: response.items.map((item) => {- return {- label: item.name,- value: item.id,- };- }),- };- },+ path: '/crm/pipeline/list',}),pipeline_stage_id: (required = false) =>Property.Dropdown({@@ -386,21 +158,169 @@ export const flowluCommon = {options: [],};}- const client = makeClient(- auth- );- const { response } = await client.listSalesPipelineStages(- pipeline_id as number- );- return {- disabled: false,- options: response.items.map((item) => {- return {- label: item.name,- value: item.id,- };- }),- };+ return loadOptions({+ client: () => makeClient(auth),+ path: '/crm/pipeline_stage/list',+ query: {+ 'filter[pipeline_id]': String(pipeline_id),+ 'order_by[asc][]': 'id',+ },+ label: (item) => textOf(item['name']),+ });},}),};++function simpleDropdown({+ displayName,+ description,+ required,+ path,+}: {+ displayName: string;+ description?: string;+ required: boolean;+ path: string;+}) {+ return Property.Dropdown({+ auth: flowluAuth,+ displayName,+ description,+ required,+ refreshers: [],+ options: async ({ auth }) => {+ if (!auth) {+ return {+ disabled: true,+ placeholder: 'Connect your account first',+ options: [],+ };+ }+ return loadOptions({+ client: () => makeClient(auth),+ path,+ query: { 'order_by[asc][]': 'id' },+ label: (item) => textOf(item['name']),+ });+ },+ });+}++function searchableDropdown({+ displayName,+ description,+ required,+ path,+ filter,+ label,+}: {+ displayName: string;+ description?: string;+ required: boolean;+ path: string;+ filter?: Record<string, FormValue>;+ label: (item: Record<string, unknown>) => string;+}) {+ return Property.Dropdown({+ auth: flowluAuth,+ displayName,+ description,+ required,+ refreshers: [],+ refreshOnSearch: true,+ options: async ({ auth }, { searchValue }) => {+ if (!auth) {+ return {+ disabled: true,+ placeholder: 'Connect your account first',+ options: [],+ };+ }+ const search = searchValue?.trim() ?? '';+ return loadOptions({+ client: () => makeClient(auth),+ path,+ query: {+ ...filter,+ 'order_by[desc][]': 'id',+ search: search === '' ? undefined : search,+ },+ label,+ searchHint: search === '',+ });+ },+ });+}++async function loadOptions({+ client,+ path,+ query,+ label,+ searchHint = false,+}: {+ client: () => FlowluClient;+ path: string;+ query: Record<string, FormValue>;+ label: (item: Record<string, unknown>) => string;+ searchHint?: boolean;+}): Promise<DropdownState<number>> {+ try {+ const res = await client().request<{+ response: {+ items?: Record<string, unknown>[];+ total_result?: number;+ total?: number;+ };+ }>({+ method: HttpMethod.GET,+ path,+ query: { ...query, limit: DROPDOWN_LIMIT },+ });+ const items = Array.isArray(res.response?.items) ? res.response.items : [];+ const options = items.flatMap((item) => {+ const id = Number(item['id']);+ if (!Number.isFinite(id)) {+ return [];+ }+ const text = label(item);+ return [+ { label: text === '' ? `#${id}` : `${text} (#${id})`, value: id },+ ];+ });+ const total = Number(+ res.response?.total_result ?? res.response?.total ?? options.length+ );+ const truncated = total > options.length;+ return {+ disabled: false,+ options,+ placeholder: truncated+ ? searchHint+ ? `Showing the latest ${options.length} of ${total}. Type to search.`+ : `Showing the first ${options.length} of ${total}.`+ : options.length === 0+ ? 'No records found'+ : undefined,+ };+ } catch (error) {+ return {+ disabled: true,+ options: [],+ placeholder:+ error instanceof FlowluApiError+ ? error.message+ : 'Could not load options from Flowlu.',+ };+ }+}++function textOf(value: unknown): string {+ return typeof value === 'string'+ ? value.trim()+ : typeof value === 'number'+ ? String(value)+ : '';+}++const DROPDOWN_LIMIT = 100;diff --git a/packages/pieces/community/flowlu/src/lib/common/links.ts b/packages/pieces/community/flowlu/src/lib/common/links.tsnew file mode 100644index 00000000000..9ae9a8fab5a--- /dev/null+++ b/packages/pieces/community/flowlu/src/lib/common/links.ts@@ -0,0 +1,132 @@+import { FlowluApiError, FlowluClient } from './client';++async function linkAccountToLead({+ client,+ leadId,+ accountId,+ accountType,+}: {+ client: FlowluClient;+ leadId: number;+ accountId: number;+ accountType: 1 | 2;+}): Promise<LinkResult> {+ const existing = await client.list<Record<string, unknown>>(+ 'crm',+ 'lead_accounts',+ {+ 'filter[lead_id]': leadId,+ 'filter[account_id]': accountId,+ limit: 1,+ }+ );+ const match = existing.items.find(+ (item) =>+ Number(item['lead_id']) === leadId &&+ Number(item['account_id']) === accountId+ );+ if (match) {+ return { ...match, already_linked: true };+ }+ const created = await client.createRecord<Record<string, unknown>>(+ 'crm',+ 'lead_accounts',+ {+ lead_id: leadId,+ account_id: accountId,+ account_type: accountType,+ }+ );+ return {+ ...created,+ lead_id: leadId,+ account_id: accountId,+ account_type: accountType,+ already_linked: false,+ };+}++async function linkAccountsReported({+ client,+ leadId,+ links,+}: {+ client: FlowluClient;+ leadId: number;+ links: { accountId: number; accountType: 1 | 2 }[];+}): Promise<{+ linked_accounts: LinkResult[];+ link_errors: { account_id: number; error: string }[];+}> {+ const linked: LinkResult[] = [];+ const errors: { account_id: number; error: string }[] = [];+ for (const link of links) {+ try {+ linked.push(await linkAccountToLead({ client, leadId, ...link }));+ } catch (error) {+ if (!(error instanceof FlowluApiError)) {+ throw error;+ }+ errors.push({ account_id: link.accountId, error: error.message });+ }+ }+ return { linked_accounts: linked, link_errors: errors };+}++async function linkLegacyCustomer({+ client,+ leadId,+ customerId,+ contactId,+}: {+ client: FlowluClient;+ leadId: number;+ customerId: number | undefined;+ contactId: number | undefined;+}): Promise<+ | {+ linked_accounts: LinkResult[];+ link_errors: { account_id: number; error: string }[];+ }+ | undefined+> {+ if (customerId === undefined && contactId === undefined) {+ return undefined;+ }+ const lookupErrors: { account_id: number; error: string }[] = [];+ const links: { accountId: number; accountType: 1 | 2 }[] = [];+ if (customerId !== undefined) {+ try {+ const account = await client.getRecord<Record<string, unknown>>(+ 'crm',+ 'account',+ customerId+ );+ links.push({+ accountId: customerId,+ accountType: Number(account['type']) === 2 ? 2 : 1,+ });+ } catch (error) {+ if (!(error instanceof FlowluApiError)) {+ throw error;+ }+ lookupErrors.push({ account_id: customerId, error: error.message });+ }+ }+ if (contactId !== undefined && contactId !== customerId) {+ links.push({ accountId: contactId, accountType: 2 });+ }+ const result = await linkAccountsReported({ client, leadId, links });+ return {+ linked_accounts: result.linked_accounts,+ link_errors: [...lookupErrors, ...result.link_errors],+ };+}++export const flowluLinks = {+ linkAccountToLead,+ linkAccountsReported,+ linkLegacyCustomer,+};++type LinkResult = Record<string, unknown> & { already_linked: boolean };diff --git a/packages/pieces/community/flowlu/src/lib/common/opportunity.ts b/packages/pieces/community/flowlu/src/lib/common/opportunity.tsnew file mode 100644index 00000000000..ffd9316ac51--- /dev/null+++ b/packages/pieces/community/flowlu/src/lib/common/opportunity.ts@@ -0,0 +1,142 @@+import dayjs from 'dayjs';+import { FlowluApiError, FlowluClient } from './client';++async function stageAndCloseFields({+ client,+ opportunityId,+ pipelineId,+ stageId,+ status,+ closingDate,+}: {+ client: FlowluClient;+ opportunityId: number | undefined;+ pipelineId: number | undefined;+ stageId: number | undefined;+ status: number | undefined;+ closingDate: string | undefined;+}): Promise<{+ pipeline_id: number | undefined;+ pipeline_stage_id: number | undefined;+ closing_date: string | undefined;+}> {+ const closing = status === 2 || status === 3;+ const needsStagePipeline = stageId !== undefined && pipelineId === undefined;+ const needsCloseDate = closing && closingDate === undefined;+ if (opportunityId === undefined && needsStagePipeline) {+ throw new FlowluApiError({+ message:+ 'Pipeline Stage ID needs Pipeline ID: a stage belongs to one pipeline.',+ });+ }+ const current =+ opportunityId !== undefined && (needsStagePipeline || needsCloseDate)+ ? await client.getRecord<Record<string, unknown>>(+ 'crm',+ 'lead',+ opportunityId+ )+ : undefined;+ const pipeline = pipelineId ?? positiveNumber(current?.['pipeline_id']);+ if (stageId !== undefined) {+ if (pipeline === undefined) {+ throw new FlowluApiError({+ message:+ 'Pipeline Stage ID needs Pipeline ID: this opportunity is not in a pipeline yet.',+ });+ }+ await assertStageInPipeline({ client, pipelineId: pipeline, stageId });+ }+ return {+ pipeline_id: stageId === undefined ? pipelineId : pipeline,+ pipeline_stage_id: stageId,+ closing_date:+ closingDate ??+ (needsCloseDate && !alreadyClosedAs({ current, status })+ ? dayjs().format('YYYY-MM-DD')+ : undefined),+ };+}++async function assertStageInPipeline({+ client,+ pipelineId,+ stageId,+}: {+ client: FlowluClient;+ pipelineId: number;+ stageId: number;+}): Promise<void> {+ for (let page = 1; page <= STAGE_MAX_PAGES; page++) {+ const stages = await client.list<Record<string, unknown>>(+ 'crm',+ 'pipeline_stage',+ { 'filter[pipeline_id]': pipelineId, limit: STAGE_PAGE_SIZE, page }+ );+ const match = stages.items.find((item) => Number(item['id']) === stageId);+ if (match !== undefined) {+ if (+ match['pipeline_id'] !== undefined &&+ Number(match['pipeline_id']) !== pipelineId+ ) {+ throw stageError({ pipelineId, stageId });+ }+ return;+ }+ const total = Number(stages.total_result ?? stages.total);+ const seen = (page - 1) * STAGE_PAGE_SIZE + stages.items.length;+ const lastPage =+ stages.items.length < STAGE_PAGE_SIZE ||+ (Number.isFinite(total) && seen >= total);+ if (lastPage) {+ throw stageError({ pipelineId, stageId });+ }+ }+ throw new FlowluApiError({+ message: `Could not confirm that Pipeline Stage ID ${stageId} belongs to pipeline ${pipelineId}: the pipeline has more than ${+ STAGE_PAGE_SIZE * STAGE_MAX_PAGES+ } stages. Nothing was changed.`,+ });+}++function stageError({+ pipelineId,+ stageId,+}: {+ pipelineId: number;+ stageId: number;+}): FlowluApiError {+ return new FlowluApiError({+ message: `Pipeline Stage ID ${stageId} is not a stage of pipeline ${pipelineId}. List the pipeline's stages (pipeline_stages) to get a valid ID, or pass the Pipeline ID the stage belongs to.`,+ });+}++function alreadyClosedAs({+ current,+ status,+}: {+ current: Record<string, unknown> | undefined;+ status: number | undefined;+}): boolean {+ if (current === undefined) {+ return false;+ }+ const closedOn = current['closing_date'];+ return (+ Number(current['active']) === status &&+ typeof closedOn === 'string' &&+ closedOn.trim() !== ''+ );+}++function positiveNumber(value: unknown): number | undefined {+ const num = Number(value);+ return Number.isInteger(num) && num > 0 ? num : undefined;+}++const STAGE_PAGE_SIZE = 100;+const STAGE_MAX_PAGES = 20;++export const flowluOpportunity = {+ stageAndCloseFields,+};diff --git a/packages/pieces/community/flowlu/src/lib/common/polling-trigger.ts b/packages/pieces/community/flowlu/src/lib/common/polling-trigger.tsnew file mode 100644index 00000000000..895fbb81d81--- /dev/null+++ b/packages/pieces/community/flowlu/src/lib/common/polling-trigger.ts@@ -0,0 +1,57 @@+import { Store } from '@activepieces/pieces-framework';+import { makeClient } from '.';+import { FormValue } from './client';+import { flowluPolling, PollSource } from './polling';++export function flowluPollingHooks({+ source,+ filters,+}: {+ source: PollSource;+ filters: (propsValue: Record<string, unknown>) => Record<string, FormValue>;+}) {+ return {+ async onEnable(context: HookContext): Promise<void> {+ const checkpoint = await flowluPolling.latestId({+ client: makeClient(context.auth),+ source,+ });+ await context.store.put(flowluPolling.storeKey, checkpoint);+ },+ async onDisable(context: HookContext): Promise<void> {+ await context.store.delete(flowluPolling.storeKey);+ },+ async test(context: HookContext): Promise<unknown[]> {+ return flowluPolling.latest({+ client: makeClient(context.auth),+ source,+ filters: filters(context.propsValue),+ });+ },+ async run(context: HookContext): Promise<unknown[]> {+ const client = makeClient(context.auth);+ const stored = await context.store.get<number>(flowluPolling.storeKey);+ if (typeof stored !== 'number') {+ const checkpoint = await flowluPolling.latestId({ client, source });+ await context.store.put(flowluPolling.storeKey, checkpoint);+ return [];+ }+ const result = await flowluPolling.newSince({+ client,+ source,+ filters: filters(context.propsValue),+ checkpoint: stored,+ });+ if (result.checkpoint !== stored) {+ await context.store.put(flowluPolling.storeKey, result.checkpoint);+ }+ return result.items;+ },+ };+}++type HookContext = {+ auth: Parameters<typeof makeClient>[0];+ propsValue: Record<string, unknown>;+ store: Store;+};diff --git a/packages/pieces/community/flowlu/src/lib/common/polling.ts b/packages/pieces/community/flowlu/src/lib/common/polling.tsnew file mode 100644index 00000000000..8f563f434e3--- /dev/null+++ b/packages/pieces/community/flowlu/src/lib/common/polling.ts@@ -0,0 +1,208 @@+import {+ FlowluApiError,+ FlowluClient,+ FormValue,+ ListEnvelope,+} from './client';++async function latestId({+ client,+ source,+}: {+ client: FlowluClient;+ source: PollSource;+}): Promise<number> {+ const envelope = await client.list(source.module, source.entity, {+ 'order_by[desc][]': 'id',+ limit: 1,+ });+ return maxId({ items: envelope.items, floor: 0 });+}++async function newSince({+ client,+ source,+ filters,+ checkpoint,+}: {+ client: FlowluClient;+ source: PollSource;+ filters: Record<string, FormValue>;+ checkpoint: number;+}): Promise<{ items: Record<string, unknown>[]; checkpoint: number }> {+ const snapshot = await latestId({ client, source });+ const first = await client.list(source.module, source.entity, {+ ...filters,+ 'filter[id]': JSON.stringify({ type: 'more', value: checkpoint }),+ 'order_by[asc][]': 'id',+ page: 1,+ limit: PAGE_SIZE,+ });+ const filterHonoured = !first.items.some((item) => idOf(item) <= checkpoint);+ const batch = filterHonoured+ ? await readFiltered({ client, source, filters, checkpoint, first })+ : await readUnfiltered({ client, source, filters, checkpoint, first });+ const items = batch.items+ .filter((item) => idOf(item) > checkpoint)+ .sort((a, b) => idOf(a) - idOf(b));+ const unique = items.filter(+ (item, index) => index === 0 || idOf(item) !== idOf(items[index - 1])+ );+ const lastEmitted = maxId({ items: unique, floor: checkpoint });+ return {+ items: unique,+ checkpoint: batch.complete ? Math.max(lastEmitted, snapshot) : lastEmitted,+ };+}++async function readFiltered({+ client,+ source,+ filters,+ checkpoint,+ first,+}: ReadInput): Promise<Batch> {+ const pages: Record<string, unknown>[][] = [first.items];+ let complete = first.items.length < PAGE_SIZE;+ for (let page = 2; !complete && page <= MAX_PAGES; page++) {+ const envelope = await client.list(source.module, source.entity, {+ ...filters,+ 'filter[id]': JSON.stringify({ type: 'more', value: checkpoint }),+ 'order_by[asc][]': 'id',+ page,+ limit: PAGE_SIZE,+ });+ pages.push(envelope.items);+ complete = envelope.items.length < PAGE_SIZE;+ }+ return { items: pages.flat(), complete };+}++async function readUnfiltered({+ client,+ source,+ filters,+ checkpoint,+ first,+}: ReadInput): Promise<Batch> {+ if (!isAscending(first.items)) {+ throw new FlowluApiError({+ message:+ 'Flowlu ignored both the id filter and the sort order, so new records cannot be found reliably. Try again later.',+ });+ }+ const cache = new Map<number, Record<string, unknown>[]>([[1, first.items]]);+ const fetchPage = async (page: number) => {+ const cached = cache.get(page);+ if (cached !== undefined) {+ return cached;+ }+ const envelope = await client.list(source.module, source.entity, {+ ...filters,+ 'order_by[asc][]': 'id',+ page,+ limit: PAGE_SIZE,+ });+ cache.set(page, envelope.items);+ return envelope.items;+ };+ const reachesNew = (items: Record<string, unknown>[]) =>+ items.length < PAGE_SIZE || idOf(items[items.length - 1]) > checkpoint;+ const start = await firstPageWith({ fetchPage, reachesNew });+ const pages: Record<string, unknown>[][] = [];+ let complete = false;+ for (let page = start; !complete && page < start + MAX_PAGES; page++) {+ const items = await fetchPage(page);+ pages.push(items);+ complete = items.length < PAGE_SIZE;+ }+ return { items: pages.flat(), complete };+}++async function firstPageWith({+ fetchPage,+ reachesNew,+}: {+ fetchPage: (page: number) => Promise<Record<string, unknown>[]>;+ reachesNew: (items: Record<string, unknown>[]) => boolean;+}): Promise<number> {+ if (reachesNew(await fetchPage(1))) {+ return 1;+ }+ let below = 1;+ let above = 2;+ while (!reachesNew(await fetchPage(above))) {+ below = above;+ above *= 2;+ }+ while (above - below > 1) {+ const middle = Math.floor((below + above) / 2);+ if (reachesNew(await fetchPage(middle))) {+ above = middle;+ } else {+ below = middle;+ }+ }+ return above;+}++async function latest({+ client,+ source,+ filters,+}: {+ client: FlowluClient;+ source: PollSource;+ filters: Record<string, FormValue>;+}): Promise<Record<string, unknown>[]> {+ const envelope = await client.list(source.module, source.entity, {+ ...filters,+ 'order_by[desc][]': 'id',+ limit: TEST_ITEMS,+ });+ return envelope.items;+}++function isAscending(items: Record<string, unknown>[]): boolean {+ return items.every(+ (item, index) => index === 0 || idOf(items[index - 1]) <= idOf(item)+ );+}++function maxId({+ items,+ floor,+}: {+ items: Record<string, unknown>[];+ floor: number;+}): number {+ return items.reduce((max, item) => Math.max(max, idOf(item)), floor);+}++function idOf(item: Record<string, unknown>): number {+ const id = Number(item['id']);+ return Number.isFinite(id) ? id : 0;+}++export const flowluPolling = {+ latestId,+ newSince,+ latest,+ storeKey: 'flowlu_last_seen_id',+};++const PAGE_SIZE = 100;+const MAX_PAGES = 5;+const TEST_ITEMS = 5;++export type PollSource = { module: string; entity: string };++type Batch = { items: Record<string, unknown>[]; complete: boolean };++type ReadInput = {+ client: FlowluClient;+ source: PollSource;+ filters: Record<string, FormValue>;+ checkpoint: number;+ first: ListEnvelope<Record<string, unknown>>;+};diff --git a/packages/pieces/community/flowlu/src/lib/common/project-props.ts b/packages/pieces/community/flowlu/src/lib/common/project-props.tsnew file mode 100644index 00000000000..937f4f9ffec--- /dev/null+++ b/packages/pieces/community/flowlu/src/lib/common/project-props.ts@@ -0,0 +1,56 @@+import { Property } from '@activepieces/pieces-framework';+import { flowluCommon } from '.';++export const flowluProjectProps = {+ fields: () => ({+ description: Property.LongText({+ displayName: 'Description',+ required: false,+ }),+ manager_id: flowluCommon.user_id(false, 'Project Manager'),+ customer_id: flowluCommon.organization_id(+ false,+ 'Customer (Organization)',+ 'The CRM organization the project is for.'+ ),+ customer_crm_contact_id: flowluCommon.contact_id(+ false,+ 'Customer Contact',+ 'The contact person at the customer.'+ ),+ crm_lead_id: flowluCommon.opportunity_id(false),+ startdate: Property.DateTime({+ displayName: 'Start Date',+ description: 'Only the date part is used.',+ required: false,+ }),+ enddate: Property.DateTime({+ displayName: 'End Date',+ description: 'Only the date part is used.',+ required: false,+ }),+ priority: Property.StaticDropdown({+ displayName: 'Priority',+ required: false,+ options: {+ disabled: false,+ options: [+ { label: 'Low', value: 1 },+ { label: 'Medium', value: 2 },+ { label: 'High', value: 3 },+ ],+ },+ }),+ portfolio_id: flowluCommon.portfolio_id(false),+ tasks_workflow_id: flowluCommon.workflow_id(false),+ estimated_revenue: Property.Number({+ displayName: 'Contract Amount',+ description: 'Planned revenue for the project.',+ required: false,+ }),+ estimated_expenses: Property.Number({+ displayName: 'Planned Expenses',+ required: false,+ }),+ }),+};diff --git a/packages/pieces/community/flowlu/src/lib/common/props.ts b/packages/pieces/community/flowlu/src/lib/common/props.tsindex 089730a9ffa..ab841fccf65 100644--- a/packages/pieces/community/flowlu/src/lib/common/props.ts+++ b/packages/pieces/community/flowlu/src/lib/common/props.ts@@ -78,6 +78,16 @@ export const flowluProps = {}),workflow_id: flowluCommon.workflow_id(false),workflow_stage_id: flowluCommon.workflow_stage_id(false),+ project_id: flowluCommon.project_id(+ false,+ 'Project',+ 'Links the task to this project.'+ ),+ crm_account_id: flowluCommon.account_id(+ false,+ 'CRM Account',+ 'Links the task to this CRM contact or organization.'+ ),},account: {owner_id: flowluCommon.user_id(false, 'Assignee ID'),@@ -117,6 +127,8 @@ export const flowluProps = {}),link_google: Property.ShortText({displayName: 'Link to Google+',+ description:+ 'Google+ no longer exists and Flowlu has no field for it, so this value is not saved.',required: false,}),link_facebook: Property.ShortText({@@ -223,3 +235,28 @@ export const flowluProps = {pipeline_stage_id: flowluCommon.pipeline_stage_id(false),},};++export const flowluWire = {+ fieldsOnly: (props: Record<string, unknown>): Record<string, unknown> =>+ Object.fromEntries(+ Object.entries(props).filter(([key]) => !NON_FIELD_KEYS.includes(key))+ ),+ account: (props: Record<string, unknown>): Record<string, unknown> =>+ Object.fromEntries(+ Object.entries(props)+ .filter(([key]) => !DROPPED_ACCOUNT_FIELDS.includes(key))+ .map(([key, value]) => [LEGACY_ACCOUNT_FIELDS[key] ?? key, value])+ ),+};++const LEGACY_ACCOUNT_FIELDS: Record<string, string> = {+ vat: 'VAT',+ skype: 'social_network_link_1',+ link_facebook: 'social_network_link_3',+ link_linkedin: 'social_network_link_5',+ link_instagram: 'social_network_link_6',+};++const NON_FIELD_KEYS = ['auth'];++const DROPPED_ACCOUNT_FIELDS = ['id', 'link_google', ...NON_FIELD_KEYS];diff --git a/packages/pieces/community/flowlu/src/lib/common/task-wire.ts b/packages/pieces/community/flowlu/src/lib/common/task-wire.tsnew file mode 100644index 00000000000..dbef68e6c31--- /dev/null+++ b/packages/pieces/community/flowlu/src/lib/common/task-wire.ts@@ -0,0 +1,51 @@+import { FormValue } from './client';+import { flowluInput } from './utils';++export const flowluTaskWire = {+ fields: (props: {+ name?: string;+ description?: string;+ priority?: number;+ plan_start_date?: string;+ deadline?: string;+ deadline_allowchange?: boolean;+ task_checkbyowner?: boolean;+ responsible_id?: number;+ owner_id?: number;+ workflow_id?: number;+ workflow_stage_id?: number;+ project_id?: number;+ crm_account_id?: number;+ }): Record<string, FormValue> => {+ const projectId = flowluInput.optionalId({+ value: props.project_id,+ name: 'Project',+ });+ return {+ name: props.name,+ description: props.description,+ priority: props.priority,+ plan_start_date: flowluInput.formatDateTime({+ value: props.plan_start_date,+ name: 'Start Date',+ }),+ deadline: flowluInput.formatDateTime({+ value: props.deadline,+ name: 'End Date',+ }),+ deadline_allowchange: props.deadline_allowchange ? 1 : 0,+ task_checkbyowner: props.task_checkbyowner ? 1 : 0,+ responsible_id: props.responsible_id,+ owner_id: props.owner_id,+ workflow_id: props.workflow_id,+ workflow_stage_id: props.workflow_stage_id,+ module: projectId === undefined ? undefined : 'st',+ model: projectId === undefined ? undefined : 'project',+ model_id: projectId,+ crm_account_id: flowluInput.optionalId({+ value: props.crm_account_id,+ name: 'CRM Account',+ }),+ };+ },+};diff --git a/packages/pieces/community/flowlu/src/lib/common/types.ts b/packages/pieces/community/flowlu/src/lib/common/types.tsindex a67a6cadb4e..8299d9fc995 100644--- a/packages/pieces/community/flowlu/src/lib/common/types.ts+++ b/packages/pieces/community/flowlu/src/lib/common/types.ts@@ -171,8 +171,8 @@ export interface CreateTaskAPIRequest {deadline?: string;deadline_allowchange?: number;task_checkbyowner?: number;- responsible_id?: string;- owner_id?: string;+ responsible_id?: number | string;+ owner_id?: number | string;type?: number;workflow_id?: number;workflow_stage_id?: number;@@ -184,7 +184,7 @@ export interface CreateCRMAccountAPIRequest {first_name?: string;middle_name?: string;last_name?: string;- owner_id?: string;+ owner_id?: number | string;account_category_id?: number;industry_id?: number;web?: string;@@ -221,7 +221,7 @@ export interface CreateOpportunityAPIRequest {source_id?: number;start_date?: string;deadline?: string;- assignee_id?: string;+ assignee_id?: number | string;customer_id?: number;contact_id?: number;pipeline_id?: number;diff --git a/packages/pieces/community/flowlu/src/lib/common/utils.ts b/packages/pieces/community/flowlu/src/lib/common/utils.tsnew file mode 100644index 00000000000..33ec8002fb2--- /dev/null+++ b/packages/pieces/community/flowlu/src/lib/common/utils.ts@@ -0,0 +1,361 @@+import { Property } from '@activepieces/pieces-framework';+import dayjs from 'dayjs';+import {+ FlowluApiError,+ FlowluClient,+ FormValue,+ ListEnvelope,+} from './client';++function requireId({ value, name }: { value: unknown; name: string }): number {+ const id = optionalId({ value, name });+ if (id === undefined) {+ throw new FlowluApiError({ message: `${name} is required.` });+ }+ return id;+}++function optionalId({+ value,+ name,+}: {+ value: unknown;+ name: string;+}): number | undefined {+ if (value === undefined || value === null) {+ return undefined;+ }+ const text =+ typeof value === 'number'+ ? String(value)+ : typeof value === 'string'+ ? value.trim()+ : undefined;+ if (text === '') {+ return undefined;+ }+ if (+ text === undefined ||+ !/^\d{1,10}$/.test(text) ||+ Number(text) < 1 ||+ Number(text) > 2147483647+ ) {+ throw new FlowluApiError({+ message: `${name} must be a numeric Flowlu ID such as "42", got ${JSON.stringify(+ value+ )}.`,+ });+ }+ return Number(text);+}++function idList({ value, name }: { value: unknown; name: string }): number[] {+ if (value === undefined || value === null || value === '') {+ return [];+ }+ const parts = Array.isArray(value)+ ? value+ : typeof value === 'string'+ ? value+ .split(',')+ .map((part) => part.trim())+ .filter((part) => part !== '')+ : [value];+ const ids = parts.map((part) => requireId({ value: part, name }));+ return [...new Set(ids)];+}++function formatDateTime({+ value,+ name,+}: {+ value: unknown;+ name: string;+}): string | undefined {+ return formatWith({ value, name, format: 'YYYY-MM-DD HH:mm:ss' });+}++function formatDate({+ value,+ name,+}: {+ value: unknown;+ name: string;+}): string | undefined {+ return formatWith({ value, name, format: 'YYYY-MM-DD' });+}++function oneOf({+ value,+ name,+ allowed,+}: {+ value: unknown;+ name: string;+ allowed: number[];+}): number | undefined {+ const num = optionalNumber({ value, name });+ if (num !== undefined && !allowed.includes(num)) {+ throw new FlowluApiError({+ message: `${name} must be one of ${allowed.join(+ ', '+ )}, got ${JSON.stringify(value)}.`,+ });+ }+ return num;+}++function triStateFlag(value: unknown): number | undefined {+ if (value === 'yes' || value === true) {+ return 1;+ }+ if (value === 'no' || value === false) {+ return 0;+ }+ return undefined;+}++function optionalNumber({+ value,+ name,+}: {+ value: unknown;+ name: string;+}): number | undefined {+ if (value === undefined || value === null || value === '') {+ return undefined;+ }+ const num =+ typeof value === 'number'+ ? value+ : typeof value === 'string'+ ? Number(value.trim())+ : NaN;+ if (!Number.isFinite(num)) {+ throw new FlowluApiError({+ message: `${name} must be a number, got ${JSON.stringify(value)}.`,+ });+ }+ return num;+}++function optionalText(value: unknown): string | undefined {+ if (value === undefined || value === null) {+ return undefined;+ }+ const text = typeof value === 'string' ? value : String(value);+ return text.trim() === '' ? undefined : text;+}++function pageParams({ page, limit }: { page: unknown; limit: unknown }): {+ page: number;+ limit: number;+} {+ const pageNumber = optionalNumber({ value: page, name: 'Page' }) ?? 1;+ const limitNumber = optionalNumber({ value: limit, name: 'Limit' }) ?? 50;+ if (!Number.isInteger(pageNumber) || pageNumber < 1) {+ throw new FlowluApiError({+ message: 'Page must be a whole number of 1 or more.',+ });+ }+ if (!Number.isInteger(limitNumber) || limitNumber < 1 || limitNumber > 100) {+ throw new FlowluApiError({+ message: 'Limit must be a whole number from 1 to 100.',+ });+ }+ return { page: pageNumber, limit: limitNumber };+}++function orderQuery(order: unknown): Record<string, string> {+ return order === 'oldest'+ ? { 'order_by[asc][]': 'id' }+ : { 'order_by[desc][]': 'id' };+}++function listResult<T>({+ envelope,+ page,+ limit,+}: {+ envelope: ListEnvelope<T>;+ page: number;+ limit: number;+}) {+ const total = Number(+ envelope.total_result ?? envelope.total ?? envelope.items.length+ );+ return {+ items: envelope.items,+ page,+ count: envelope.items.length,+ total,+ has_more: page * limit < total,+ };+}++async function fullRecord({+ client,+ module,+ entity,+ created,+}: {+ client: FlowluClient;+ module: string;+ entity: string;+ created: Record<string, unknown>;+}): Promise<Record<string, unknown>> {+ const id = requireId({ value: created['id'], name: 'Created record id' });+ try {+ const record = await client.getRecord(module, entity, id);+ return { ...record, read_back_error: null };+ } catch (error) {+ if (!(error instanceof FlowluApiError)) {+ throw error;+ }+ return {+ ...created,+ id,+ read_back_error: `The record was created, but reading it back failed: ${error.message}`,+ };+ }+}++function compact(fields: Record<string, FormValue>): Record<string, FormValue> {+ return Object.fromEntries(+ Object.entries(fields).filter(([, value]) => value !== undefined)+ );+}++function formatWith({+ value,+ name,+ format,+}: {+ value: unknown;+ name: string;+ format: string;+}): string | undefined {+ if (value === undefined || value === null || value === '') {+ return undefined;+ }+ if (typeof value !== 'string' && typeof value !== 'number') {+ throw new FlowluApiError({+ message: `${name} must be a date such as "2026-10-01T09:30:00Z".`,+ });+ }+ const parsed = dayjs(value);+ if (!parsed.isValid()) {+ throw new FlowluApiError({+ message: `${name} must be a date such as "2026-10-01T09:30:00Z", got ${JSON.stringify(+ value+ )}.`,+ });+ }+ return parsed.format(format);+}++export const flowluInput = {+ requireId,+ optionalId,+ idList,+ formatDateTime,+ formatDate,+ triStateFlag,+ oneOf,+ optionalNumber,+ optionalText,+ pageParams,+ orderQuery,+ compact,+};++export const flowluOutput = {+ listResult,+ fullRecord,+};++export const flowluSharedProps = {+ triState: ({+ displayName,+ description,+ }: {+ displayName: string;+ description: string;+ }) =>+ Property.StaticDropdown({+ displayName,+ description,+ required: false,+ options: {+ disabled: false,+ options: [+ { label: 'Yes', value: 'yes' },+ { label: 'No', value: 'no' },+ ],+ },+ }),+ page: () =>+ Property.Number({+ displayName: 'Page',+ description:+ 'Page of results to return, starting at 1. Use with Limit; check has_more in the output to know if another page exists.',+ required: false,+ defaultValue: 1,+ }),+ limit: () =>+ Property.Number({+ displayName: 'Limit',+ description: 'How many records to return per page, 1 to 100. Default 50.',+ required: false,+ defaultValue: 50,+ }),+ order: () =>+ Property.StaticDropdown({+ displayName: 'Order',+ description: 'Newest first (highest ID first) or oldest first.',+ required: false,+ defaultValue: 'newest',+ options: {+ disabled: false,+ options: [+ { label: 'Newest first', value: 'newest' },+ { label: 'Oldest first', value: 'oldest' },+ ],+ },+ }),+ search: (description: string) =>+ Property.ShortText({+ displayName: 'Search',+ description,+ required: false,+ }),+};++export const flowluFind = {+ run: async ({+ client,+ module,+ entity,+ props,+ filters,+ }: {+ client: FlowluClient;+ module: string;+ entity: string;+ props: Record<string, unknown>;+ filters: Record<string, FormValue>;+ }) => {+ const { page, limit } = pageParams({+ page: props['page'],+ limit: props['limit'],+ });+ const envelope = await client.list(module, entity, {+ ...filters,+ ...orderQuery(props['order']),+ search: optionalText(props['search']),+ page,+ limit,+ });+ return listResult({ envelope, page, limit });+ },+};diff --git a/packages/pieces/community/flowlu/src/lib/output-schemas.ts b/packages/pieces/community/flowlu/src/lib/output-schemas.tsnew file mode 100644index 00000000000..589c981a486--- /dev/null+++ b/packages/pieces/community/flowlu/src/lib/output-schemas.ts@@ -0,0 +1,394 @@+import {+ OutputSchema,+ OutputSchemaField,+} from '@activepieces/pieces-framework';++const PORTAL_TIME =+ 'Portal time zone, formatted YYYY-MM-DD HH:mm:ss. Empty when not set.';++const taskFields: OutputSchemaField[] = [+ {+ key: 'id',+ label: 'Task ID',+ description: 'Use this to get, update or delete the task in a later step.',+ },+ { key: 'name', label: 'Name' },+ { key: 'description', label: 'Description' },+ {+ key: 'status',+ label: 'Status',+ description: '1 new, 3 in progress, 4 pending owner approval, 5 completed.',+ },+ {+ key: 'priority',+ label: 'Priority',+ description: '1 low, 2 medium, 3 high.',+ },+ {+ key: 'type',+ label: 'Type',+ description: '0 task, 1 inbox, 20-23 event, 30 template, 40 milestone.',+ },+ { key: 'responsible_id', label: 'Assignee User ID' },+ { key: 'owner_id', label: 'Owner User ID' },+ { key: 'plan_start_date', label: 'Start Date', description: PORTAL_TIME },+ { key: 'deadline', label: 'Deadline', description: PORTAL_TIME },+ { key: 'start_date', label: 'Started At', description: PORTAL_TIME },+ { key: 'closed_date', label: 'Completed At', description: PORTAL_TIME },+ { key: 'workflow_id', label: 'Workflow ID' },+ { key: 'workflow_stage_id', label: 'Workflow Status ID' },+ {+ key: 'module',+ label: 'Linked Module',+ description: '"st" when the task belongs to a project.',+ },+ {+ key: 'model',+ label: 'Linked Object Type',+ description: '"project" when the task belongs to a project.',+ },+ {+ key: 'model_id',+ label: 'Linked Object ID',+ description: 'The project ID when the task belongs to a project.',+ },+ { key: 'crm_account_id', label: 'CRM Account ID' },+ { key: 'parent_id', label: 'Parent Task ID' },+ {+ key: 'deadline_allowchange',+ label: 'Assignee Can Change Deadline',+ description: '1 yes, 0 no.',+ },+ {+ key: 'task_checkbyowner',+ label: 'Needs Owner Approval',+ description: '1 yes, 0 no.',+ },+ { key: 'time_estimate', label: 'Estimated Time' },+ { key: 'time_spent', label: 'Time Spent' },+ { key: 'created_date', label: 'Created At', description: PORTAL_TIME },+ { key: 'updated_date', label: 'Updated At', description: PORTAL_TIME },+];++function accountFieldsWith({+ vatKey,+}: {+ vatKey: string;+}): OutputSchemaField[] {+ return [+ {+ key: 'id',+ label: 'Account ID',+ description:+ 'Use this to get, update, link or delete the account in a later step.',+ },+ {+ key: 'type',+ label: 'Account Type',+ description: '1 organization, 2 contact.',+ },+ { key: 'name', label: 'Name' },+ { key: 'first_name', label: 'First Name' },+ { key: 'middle_name', label: 'Middle Name' },+ { key: 'last_name', label: 'Last Name' },+ { key: 'name_legal_full', label: 'Full Legal Name' },+ { key: 'email', label: 'Email', format: 'email' },+ { key: 'phone', label: 'Phone' },+ { key: 'phone2', label: 'Phone 2' },+ { key: 'phone3', label: 'Phone 3' },+ { key: 'web', label: 'Website', format: 'url' },+ { key: 'owner_id', label: 'Owner User ID' },+ { key: 'account_category_id', label: 'Category ID' },+ { key: 'industry_id', label: 'Industry ID' },+ { key: 'honorific_title_id', label: 'Honorific Title ID' },+ { key: vatKey, label: 'VAT or Tax ID' },+ { key: 'description', label: 'Description' },+ { key: 'telegram', label: 'Telegram' },+ { key: 'social_network_link_1', label: 'Skype' },+ { key: 'social_network_link_3', label: 'Facebook', format: 'url' },+ { key: 'social_network_link_4', label: 'X (Twitter)', format: 'url' },+ { key: 'social_network_link_5', label: 'LinkedIn', format: 'url' },+ { key: 'social_network_link_6', label: 'Instagram', format: 'url' },+ { key: 'billing_country', label: 'Billing Country' },+ { key: 'billing_state', label: 'Billing State' },+ { key: 'billing_city', label: 'Billing City' },+ { key: 'billing_zip', label: 'Billing Postal Code' },+ { key: 'billing_address_line_1', label: 'Billing Address' },+ { key: 'shipping_country', label: 'Shipping Country' },+ { key: 'shipping_city', label: 'Shipping City' },+ { key: 'shipping_address_line_1', label: 'Shipping Address' },+ { key: 'active', label: 'Active', description: '1 active, 0 inactive.' },+ { key: 'created_date', label: 'Created At', description: PORTAL_TIME },+ { key: 'updated_date', label: 'Updated At', description: PORTAL_TIME },+ ];+}++const accountFields = accountFieldsWith({ vatKey: 'vat' });+const accountListFields = accountFieldsWith({ vatKey: 'VAT' });++const opportunityFields: OutputSchemaField[] = [+ {+ key: 'id',+ label: 'Opportunity ID',+ description:+ 'Use this to get, update, link or delete the opportunity in a later step.',+ },+ { key: 'name', label: 'Name' },+ { key: 'budget', label: 'Amount', format: 'number' },+ {+ key: 'active',+ label: 'Status',+ description: '1 in progress, 2 lost, 3 won.',+ },+ { key: 'pipeline_id', label: 'Pipeline ID' },+ { key: 'pipeline_stage_id', label: 'Pipeline Stage ID' },+ { key: 'source_id', label: 'Source ID' },+ { key: 'assignee_id', label: 'Assignee User ID' },+ { key: 'start_date', label: 'Start Date', format: 'date' },+ { key: 'deadline', label: 'Expected Close Date', format: 'date' },+ { key: 'closing_date', label: 'Close Date', format: 'date' },+ { key: 'closing_status_id', label: 'Loss Reason ID' },+ { key: 'closing_comment', label: 'Closing Comment' },+ { key: 'description', label: 'Description' },+ { key: 'contact_name', label: 'Contact Name' },+ { key: 'contact_email', label: 'Contact Email', format: 'email' },+ { key: 'contact_phone', label: 'Contact Phone' },+ { key: 'contact_company', label: 'Contact Company' },+ { key: 'contact_position', label: 'Contact Position' },+ { key: 'created_date', label: 'Created At', description: PORTAL_TIME },+ { key: 'updated_date', label: 'Updated At', description: PORTAL_TIME },+];++const projectFields: OutputSchemaField[] = [+ {+ key: 'id',+ label: 'Project ID',+ description:+ 'Use this to get or update the project, or to add tasks to it, in a later step.',+ },+ { key: 'name', label: 'Name' },+ { key: 'description', label: 'Description' },+ { key: 'manager_id', label: 'Manager User ID' },+ { key: 'customer_id', label: 'Customer Organization ID' },+ { key: 'customer_crm_contact_id', label: 'Customer Contact ID' },+ { key: 'crm_lead_id', label: 'Opportunity ID' },+ { key: 'project_type_id', label: 'Template ID' },+ { key: 'briefcase_id', label: 'Portfolio ID' },+ { key: 'tasks_workflow_id', label: 'Task Workflow ID' },+ {+ key: 'priority',+ label: 'Priority',+ description: '1 low, 2 medium, 3 high.',+ },+ { key: 'startdate', label: 'Start Date', format: 'date' },+ { key: 'enddate', label: 'End Date', format: 'date' },+ { key: 'estimated_revenue', label: 'Contract Amount', format: 'number' },+ { key: 'estimated_expenses', label: 'Planned Expenses', format: 'number' },+ {+ key: 'is_archive',+ label: 'Archived',+ description: '1 archived, 0 not archived.',+ },+ { key: 'created_date', label: 'Created At', description: PORTAL_TIME },+ { key: 'updated_date', label: 'Updated At', description: PORTAL_TIME },+];++const userFields: OutputSchemaField[] = [+ {+ key: 'id',+ label: 'User ID',+ description: 'Use this as an assignee, owner or manager ID.',+ },+ { key: 'name', label: 'Name' },+ { key: 'first_name', label: 'First Name' },+ { key: 'last_name', label: 'Last Name' },+ { key: 'username', label: 'Login Email', format: 'email' },+ { key: 'position', label: 'Position' },+ { key: 'timezone', label: 'Timezone' },+ { key: 'role_admin', label: 'Administrator', description: '1 yes, 0 no.' },+ { key: 'role_login', label: 'Can Log In', description: '1 yes, 0 no.' },+ {+ key: 'last_active',+ label: 'Last Active',+ description: 'Unix time in seconds.',+ },+];++const linkFields: OutputSchemaField[] = [+ { key: 'id', label: 'Link ID' },+ { key: 'lead_id', label: 'Opportunity ID' },+ { key: 'account_id', label: 'Account ID' },+ {+ key: 'account_type',+ label: 'Account Type',+ description: '1 organization, 2 contact.',+ },+ {+ key: 'already_linked',+ label: 'Already Linked',+ format: 'boolean',+ description: 'True when the link existed before this step.',+ },+];++const linkReportFields: OutputSchemaField[] = [+ {+ key: 'linked_accounts',+ label: 'Linked Accounts',+ labelKey: 'account_id',+ description:+ 'Accounts linked to the opportunity. On Create/Update Opportunity only present when Customer or Contact is set.',+ listItems: linkFields,+ },+ {+ key: 'link_errors',+ label: 'Link Errors',+ labelKey: 'account_id',+ description:+ 'Accounts that could not be linked. The opportunity itself was saved.',+ listItems: [+ { key: 'account_id', label: 'Account ID' },+ { key: 'error', label: 'Error' },+ ],+ },+];++const readBackField: OutputSchemaField = {+ key: 'read_back_error',+ label: 'Read-back Error',+ description:+ 'Empty unless the record was created but reading it back failed; the record exists either way.',+};++function listOf({+ fields,+ label,+}: {+ fields: OutputSchemaField[];+ label: string;+}): OutputSchema {+ return {+ fields: [+ { key: 'items', label, labelKey: 'name', listItems: fields },+ { key: 'page', label: 'Page', format: 'number' },+ {+ key: 'count',+ label: 'Returned',+ format: 'number',+ description: 'Records on this page.',+ },+ { key: 'total', label: 'Total Matches', format: 'number' },+ {+ key: 'has_more',+ label: 'Has More',+ format: 'boolean',+ description: 'True when another page exists.',+ },+ ],+ };+}++function envelope({+ fields,+ label,+ extra = [],+}: {+ fields: OutputSchemaField[];+ label: string;+ extra?: OutputSchemaField[];+}): OutputSchema {+ return { fields: [{ key: 'response', label, children: fields }, ...extra] };+}++export const taskOutputSchema: OutputSchema = { fields: taskFields };+export const accountOutputSchema: OutputSchema = { fields: accountFields };+export const accountTriggerOutputSchema: OutputSchema = {+ fields: accountListFields,+};+export const opportunityOutputSchema: OutputSchema = {+ fields: opportunityFields,+};+export const opportunityCreateOutputSchema: OutputSchema = {+ fields: [...opportunityFields, readBackField, ...linkReportFields],+};+export const projectOutputSchema: OutputSchema = { fields: projectFields };+export const taskCreateOutputSchema: OutputSchema = {+ fields: [...taskFields, readBackField],+};+export const accountCreateOutputSchema: OutputSchema = {+ fields: [...accountFields, readBackField],+};+export const projectCreateOutputSchema: OutputSchema = {+ fields: [...projectFields, readBackField],+};+export const linkOutputSchema: OutputSchema = { fields: linkFields };++export const deletedOutputSchema: OutputSchema = {+ fields: [+ { key: 'id', label: 'Deleted ID' },+ { key: 'deleted', label: 'Deleted', format: 'boolean' },+ ],+};++export const taskListOutputSchema = listOf({+ fields: taskFields,+ label: 'Tasks',+});+export const accountListOutputSchema = listOf({+ fields: accountListFields,+ label: 'Accounts',+});+export const opportunityListOutputSchema = listOf({+ fields: opportunityFields,+ label: 'Opportunities',+});+export const projectListOutputSchema = listOf({+ fields: projectFields,+ label: 'Projects',+});+export const userListOutputSchema = listOf({+ fields: userFields,+ label: 'Users',+});++export const lookupOutputSchema: OutputSchema = {+ fields: [+ { key: 'entity', label: 'Values' },+ {+ key: 'items',+ label: 'Values',+ labelKey: 'name',+ listItems: [+ { key: 'id', label: 'ID' },+ { key: 'name', label: 'Name' },+ {+ key: 'parent_id',+ label: 'Parent ID',+ description: 'Pipeline ID for stages, workflow ID for task statuses.',+ },+ { key: 'active', label: 'Active' },+ ],+ },+ { key: 'count', label: 'Returned', format: 'number' },+ { key: 'total', label: 'Total', format: 'number' },+ { key: 'has_more', label: 'Has More', format: 'boolean' },+ ],+};++export const taskEnvelopeOutputSchema = envelope({+ fields: taskFields,+ label: 'Task',+});+export const accountEnvelopeOutputSchema = envelope({+ fields: accountFields,+ label: 'Account',+});+export const opportunityEnvelopeOutputSchema = envelope({+ fields: opportunityFields,+ label: 'Opportunity',+ extra: linkReportFields,+});+export const deletedEnvelopeOutputSchema = envelope({+ fields: [{ key: 'id', label: 'Deleted ID' }],+ label: 'Deleted Record',+});diff --git a/packages/pieces/community/flowlu/src/lib/triggers/new-crm-account.ts b/packages/pieces/community/flowlu/src/lib/triggers/new-crm-account.tsnew file mode 100644index 00000000000..9a64213bf28--- /dev/null+++ b/packages/pieces/community/flowlu/src/lib/triggers/new-crm-account.ts@@ -0,0 +1,86 @@+import {+ createTrigger,+ Property,+ TriggerStrategy,+} from '@activepieces/pieces-framework';+import { flowluAuth } from '../auth';+import { flowluPollingHooks } from '../common/polling-trigger';+import { accountTriggerOutputSchema } from '../output-schemas';++export const newCrmAccountTrigger = createTrigger({+ auth: flowluAuth,+ name: 'new_crm_account',+ displayName: 'New CRM Account',+ description: 'Triggers when a new CRM contact or organization is created.',+ classification: 'READ',+ aiMetadata: {+ description:+ 'Fires once for each new Flowlu CRM account created after the trigger was turned on: contacts, organizations, or both (account_type). Each run carries one account record.',+ },+ props: {+ account_type: Property.StaticDropdown({+ displayName: 'Account Type',+ description: 'Which new accounts start the flow.',+ required: false,+ defaultValue: 'any',+ options: {+ disabled: false,+ options: [+ { label: 'Contacts and organizations', value: 'any' },+ { label: 'Contacts only', value: 'contact' },+ { label: 'Organizations only', value: 'organization' },+ ],+ },+ }),+ },+ type: TriggerStrategy.POLLING,+ ...flowluPollingHooks({+ source: { module: 'crm', entity: 'account' },+ filters: (props) => ({+ 'filter[type]':+ props['account_type'] === 'contact'+ ? 2+ : props['account_type'] === 'organization'+ ? 1+ : undefined,+ }),+ }),+ outputSchema: accountTriggerOutputSchema,+ sampleData: {+ id: 19,+ type: 2,+ name: 'Ms. AP-TEST-Jane Doe',+ first_name: 'AP-TEST-Jane',+ middle_name: '',+ last_name: 'Doe',+ name_legal_full: 'Ms. AP-TEST-Jane Doe',+ email: '[email protected]',+ phone: '+15550101',+ phone2: '+15550199',+ phone3: '',+ web: '',+ owner_id: 0,+ account_category_id: 0,+ industry_id: 0,+ honorific_title_id: 3,+ VAT: '',+ description: '',+ telegram: '',+ social_network_link_1: '',+ social_network_link_3: '',+ social_network_link_4: '',+ social_network_link_5: '',+ social_network_link_6: '',+ billing_country: '',+ billing_state: '',+ billing_city: '',+ billing_zip: '',+ billing_address_line_1: '',+ shipping_country: '',+ shipping_city: '',+ shipping_address_line_1: '',+ active: 1,+ created_date: '2026-10-01 07:01:33',+ updated_date: '2026-10-01 07:02:11',+ },+});diff --git a/packages/pieces/community/flowlu/src/lib/triggers/new-opportunity.ts b/packages/pieces/community/flowlu/src/lib/triggers/new-opportunity.tsnew file mode 100644index 00000000000..e6bfbe84b44--- /dev/null+++ b/packages/pieces/community/flowlu/src/lib/triggers/new-opportunity.ts@@ -0,0 +1,55 @@+import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';+import { flowluCommon } from '../common';+import { flowluAuth } from '../auth';+import { flowluPollingHooks } from '../common/polling-trigger';+import { flowluInput } from '../common/utils';+import { opportunityOutputSchema } from '../output-schemas';++export const newOpportunityTrigger = createTrigger({+ auth: flowluAuth,+ name: 'new_opportunity',+ displayName: 'New Opportunity',+ description: 'Triggers when a new opportunity (deal) is created.',+ classification: 'READ',+ aiMetadata: {+ description:+ 'Fires once for each new Flowlu opportunity (deal) created after the trigger was turned on, optionally only in one sales pipeline. Each run carries one opportunity record.',+ },+ props: {+ pipeline_id: flowluCommon.pipeline_id(false),+ },+ type: TriggerStrategy.POLLING,+ ...flowluPollingHooks({+ source: { module: 'crm', entity: 'lead' },+ filters: (props) => ({+ 'filter[pipeline_id]': flowluInput.optionalId({+ value: props['pipeline_id'],+ name: 'Sales Pipeline',+ }),+ }),+ }),+ outputSchema: opportunityOutputSchema,+ sampleData: {+ id: 8,+ name: 'AP-TEST-Deal-AI',+ budget: 1500,+ active: 2,+ pipeline_id: 1,+ pipeline_stage_id: 2,+ source_id: 1,+ assignee_id: 1,+ start_date: '2026-10-01',+ deadline: '2026-11-30',+ closing_date: '2026-10-01',+ closing_status_id: 4,+ closing_comment: 'AP-TEST price',+ description: 'test',+ contact_name: 'Jane',+ contact_email: '[email protected]',+ contact_phone: '',+ contact_company: '',+ contact_position: '',+ created_date: '2026-10-01 07:02:29',+ updated_date: '2026-10-01 07:03:28',+ },+});diff --git a/packages/pieces/community/flowlu/src/lib/triggers/new-project.ts b/packages/pieces/community/flowlu/src/lib/triggers/new-project.tsnew file mode 100644index 00000000000..aad8a9a53bf--- /dev/null+++ b/packages/pieces/community/flowlu/src/lib/triggers/new-project.ts@@ -0,0 +1,43 @@+import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';+import { flowluAuth } from '../auth';+import { flowluPollingHooks } from '../common/polling-trigger';+import { projectOutputSchema } from '../output-schemas';++export const newProjectTrigger = createTrigger({+ auth: flowluAuth,+ name: 'new_project',+ displayName: 'New Project',+ description: 'Triggers when a new project is created.',+ classification: 'READ',+ aiMetadata: {+ description:+ 'Fires once for each new Flowlu project created after the trigger was turned on. Each run carries one project record.',+ },+ props: {},+ type: TriggerStrategy.POLLING,+ ...flowluPollingHooks({+ source: { module: 'st', entity: 'projects' },+ filters: () => ({}),+ }),+ outputSchema: projectOutputSchema,+ sampleData: {+ id: 3,+ name: 'AP-TEST-Proj-AI',+ description: 'test',+ manager_id: 1,+ customer_id: 18,+ customer_crm_contact_id: 19,+ crm_lead_id: 8,+ project_type_id: 0,+ briefcase_id: 1,+ tasks_workflow_id: 1,+ priority: 3,+ startdate: '2026-10-01',+ enddate: '2026-12-31',+ estimated_revenue: 15000,+ estimated_expenses: 4000,+ is_archive: 0,+ created_date: '2026-10-01 07:03:28',+ updated_date: '2026-10-01 07:04:06',+ },+});diff --git a/packages/pieces/community/flowlu/src/lib/triggers/new-task.ts b/packages/pieces/community/flowlu/src/lib/triggers/new-task.tsnew file mode 100644index 00000000000..ef6a56faf67--- /dev/null+++ b/packages/pieces/community/flowlu/src/lib/triggers/new-task.ts@@ -0,0 +1,73 @@+import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';+import { flowluCommon } from '../common';+import { flowluAuth } from '../auth';+import { flowluPollingHooks } from '../common/polling-trigger';+import { flowluInput } from '../common/utils';+import { taskOutputSchema } from '../output-schemas';++export const newTaskTrigger = createTrigger({+ auth: flowluAuth,+ name: 'new_task',+ displayName: 'New Task',+ description: 'Triggers when a new task is created.',+ classification: 'READ',+ aiMetadata: {+ description:+ 'Fires once for each new Flowlu task created after the trigger was turned on, optionally only tasks that are assigned to one user or in one project when Flowlu is next polled. Tasks that existed before the trigger was turned on never fire, even if they are reassigned later. Each run carries one task record.',+ },+ props: {+ responsible_id: flowluCommon.user_id(false, 'Assignee'),+ project_id: flowluCommon.project_id(+ false,+ 'Project',+ 'Only tasks in this project.'+ ),+ },+ type: TriggerStrategy.POLLING,+ ...flowluPollingHooks({+ source: { module: 'task', entity: 'tasks' },+ filters: (props) => {+ const projectId = flowluInput.optionalId({+ value: props['project_id'],+ name: 'Project',+ });+ return {+ 'filter[responsible_id]': flowluInput.optionalId({+ value: props['responsible_id'],+ name: 'Assignee',+ }),+ 'filter[module]': projectId === undefined ? undefined : 'st',+ 'filter[model]': projectId === undefined ? undefined : 'project',+ 'filter[model_id]': projectId,+ };+ },+ }),+ outputSchema: taskOutputSchema,+ sampleData: {+ id: 103,+ name: 'AP-TEST-Task-AI',+ description: '',+ status: 5,+ priority: 3,+ type: 0,+ responsible_id: 1,+ owner_id: 0,+ plan_start_date: '2026-10-02 12:00:00',+ deadline: '2026-10-05 20:00:00',+ start_date: '2026-10-01 07:04:53',+ closed_date: '2026-10-01 07:04:53',+ workflow_id: 1,+ workflow_stage_id: 4,+ module: 'st',+ model: 'project',+ model_id: 3,+ crm_account_id: 18,+ parent_id: 0,+ deadline_allowchange: 1,+ task_checkbyowner: 0,+ time_estimate: 0,+ time_spent: 0,+ created_date: '2026-10-01 07:04:09',+ updated_date: '2026-10-01 07:04:53',+ },+});diff --git a/packages/pieces/community/flowlu/test/actions.test.ts b/packages/pieces/community/flowlu/test/actions.test.tsnew file mode 100644index 00000000000..da9ed2e1135--- /dev/null+++ b/packages/pieces/community/flowlu/test/actions.test.ts@@ -0,0 +1,770 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import dayjs from 'dayjs';+import {+ AUTH,+ BASE,+ form,+ listBody,+ ok,+ request,+ runAction,+ sendRequest,+} from './helpers';+import { createContactAction } from '../src/lib/actions/accounts/create-contact';+import { createOrganizationAction } from '../src/lib/actions/accounts/create-organization';+import { updateContactAction } from '../src/lib/actions/accounts/update-contact';+import { findAccountsAction } from '../src/lib/actions/accounts/find-accounts';+import { createOpportunityAction } from '../src/lib/actions/opportunities/create-opportunity';+import { updateOpportunityAction } from '../src/lib/actions/opportunities/update-opportunity';+import { linkAccountToOpportunityAction } from '../src/lib/actions/opportunities/link-account-to-opportunity';+import { createTaskAction } from '../src/lib/actions/tasks/create-task';+import { updateTaskAction } from '../src/lib/actions/tasks/update-task';+import { getTaskAction } from '../src/lib/actions/tasks/get-task';+import { findTasksAction } from '../src/lib/actions/tasks/find-tasks';+import { listLookupValuesAction } from '../src/lib/actions/lookups/list-lookup-values';+import { listUsersAction } from '../src/lib/actions/lookups/list-users';+import { updateProjectAction } from '../src/lib/actions/projects/update-project';+import { flowluAccountCreate } from '../src/lib/actions/ai/account-create';+import { flowluOpportunityCreate } from '../src/lib/actions/ai/opportunity-create';+import { flowluOpportunityUpdate } from '../src/lib/actions/ai/opportunity-update';+import { flowluTaskCreate } from '../src/lib/actions/ai/task-create';+import { flowluTaskUpdate } from '../src/lib/actions/ai/task-update';+import { flowluTaskDelete } from '../src/lib/actions/ai/task-delete';+import { flowluCommon } from '../src/lib/common';++vi.mock('@activepieces/pieces-common', async (importOriginal) => {+ const actual = await importOriginal<+ typeof import('@activepieces/pieces-common')+ >();+ return {+ ...actual,+ httpClient: { sendRequest: (...args: unknown[]) => sendRequest(...args) },+ };+});++beforeEach(() => {+ sendRequest.mockReset();+});++describe('existing account actions', () => {+ it('Create Contact sends the props, not the whole context (P1-2)', async () => {+ ok({ response: { id: 1 } });+ await runAction({+ action: createContactAction,+ props: {+ first_name: 'Jane',+ last_name: 'Doe',+ vat: 'DE123',+ link_linkedin: 'https://linkedin.com/in/jane',+ description: undefined,+ },+ });+ expect(request(0).url).toBe(`${BASE}/crm/account/create`);+ expect(form(0)).toEqual({+ first_name: 'Jane',+ last_name: 'Doe',+ VAT: 'DE123',+ social_network_link_5: 'https://linkedin.com/in/jane',+ type: '2',+ });+ });++ it('Create Organization maps legacy prop keys to Flowlu field names and drops Google+', async () => {+ ok({ response: { id: 2 } });+ await runAction({+ action: createOrganizationAction,+ props: {+ name: 'Acme',+ skype: 'acme.sk',+ link_facebook: 'fb',+ link_instagram: 'ig',+ link_google: 'g+',+ telegram: '@acme',+ },+ });+ expect(form(0)).toEqual({+ name: 'Acme',+ social_network_link_1: 'acme.sk',+ social_network_link_3: 'fb',+ social_network_link_6: 'ig',+ telegram: '@acme',+ type: '1',+ });+ });++ it('Update Contact sends only filled fields, without id or a forced type (P2-7)', async () => {+ ok({ response: { id: 3, first_name: 'Janet' } });+ await runAction({+ action: updateContactAction,+ props: { id: 3, first_name: 'Janet', last_name: undefined },+ });+ expect(request(0).url).toBe(`${BASE}/crm/account/update/3`);+ expect(form(0)).toEqual({ first_name: 'Janet' });+ });+});++describe('existing task actions', () => {+ it('Create Task never sends "undefined" (P1-3) and links a project', async () => {+ ok({ response: { id: 10 } });+ await runAction({+ action: createTaskAction,+ props: { name: 'Call Jane', type: 0, project_id: 7 },+ });+ const body = request(0).body ?? '';+ expect(body).not.toContain('undefined');+ expect(form(0)).toEqual({+ name: 'Call Jane',+ deadline_allowchange: '0',+ task_checkbyowner: '0',+ module: 'st',+ model: 'project',+ model_id: '7',+ type: '0',+ });+ });++ it('Update Task without a name does not rename it, and keeps an event an event (P1-3, P1-4)', async () => {+ ok({ response: { id: 10 } });+ await runAction({+ action: updateTaskAction,+ props: { task_id: 10, priority: 3, type: 0 },+ });+ expect(form(0)).toEqual({+ priority: '3',+ deadline_allowchange: '0',+ task_checkbyowner: '0',+ });+ });++ it('Update Task sends a non-default type, the checkboxes and an optional status', async () => {+ ok({ response: { id: 10 } });+ await runAction({+ action: updateTaskAction,+ props: {+ task_id: 10,+ type: 20,+ deadline_allowchange: true,+ status: 5,+ deadline: '2026-10-05T17:00:00.000Z',+ },+ });+ expect(form(0)).toMatchObject({+ type: '20',+ deadline_allowchange: '1',+ task_checkbyowner: '0',+ status: '5',+ });+ expect(form(0)['deadline']).toMatch(/^2026-10-0\d \d\d:00:00$/);+ });++ it('Get Task fails on Flowlu not-found instead of returning the error body (P1-1)', async () => {+ ok({ error: { error_code: 20, error_msg: 'not found' } });+ await expect(+ runAction({ action: getTaskAction, props: { task_id: 999 } })+ ).rejects.toThrow('could not find the record');+ });++ it('rejects a non-numeric ID before any request', async () => {+ await expect(+ runAction({ action: getTaskAction, props: { task_id: 'abc' } })+ ).rejects.toThrow('numeric Flowlu ID');+ expect(sendRequest).not.toHaveBeenCalled();+ });+});++describe('existing opportunity actions', () => {+ it('Create Opportunity formats dates and links the customer through crm/lead_accounts (P2-3, P2-4)', async () => {+ ok({ response: { id: 50 } });+ ok({ response: { id: 17, type: 1 } });+ ok(listBody({ items: [] }));+ ok({ response: { id: 900 } });+ const result = await runAction({+ action: createOpportunityAction,+ props: {+ name: 'Deal',+ customer_id: 17,+ start_date: '2026-10-01T10:00:00.000Z',+ deadline: '2026-11-30T10:00:00.000Z',+ },+ });+ expect(form(0)).toMatchObject({+ name: 'Deal',+ start_date: '2026-10-01',+ deadline: '2026-11-30',+ });+ expect(request(1).url).toBe(`${BASE}/crm/account/get/17`);+ expect(request(2).queryParams).toMatchObject({+ 'filter[lead_id]': '50',+ 'filter[account_id]': '17',+ });+ expect(form(3)).toEqual({+ lead_id: '50',+ account_id: '17',+ account_type: '1',+ });+ expect(result).toMatchObject({+ response: { id: 50 },+ linked_accounts: [+ {+ id: 900,+ lead_id: 50,+ account_id: 17,+ account_type: 1,+ already_linked: false,+ },+ ],+ link_errors: [],+ });+ });++ it('Create Opportunity reports a failed link without failing the step', async () => {+ ok({ response: { id: 51 } });+ ok(listBody({ items: [] }));+ ok({ error: 'validation', details: { account_id: 'not found' } });+ const result = await runAction({+ action: createOpportunityAction,+ props: { name: 'Deal', contact_id: 5 },+ });+ expect(result).toMatchObject({+ response: { id: 51 },+ linked_accounts: [],+ link_errors: [+ {+ account_id: 5,+ error: 'Flowlu validation error: account_id: not found.',+ },+ ],+ });+ });++ it('Create Opportunity output is unchanged when no account is given', async () => {+ ok({ response: { id: 52 } });+ await expect(+ runAction({ action: createOpportunityAction, props: { name: 'Deal' } })+ ).resolves.toEqual({ response: { id: 52 } });+ expect(sendRequest).toHaveBeenCalledTimes(1);+ });++ it('Update Opportunity can mark a deal won and stamps the close date', async () => {+ ok({ response: { id: 50, active: 1, closing_date: '' } });+ ok({ response: { id: 50 } });+ await runAction({+ action: updateOpportunityAction,+ props: { id: 50, status: 3, closing_comment: 'Signed' },+ });+ expect(request(0).url).toBe(`${BASE}/crm/lead/get/50`);+ expect(request(1).url).toBe(`${BASE}/crm/lead/update/50`);+ expect(form(1)).toEqual({+ active: '3',+ closing_date: dayjs().format('YYYY-MM-DD'),+ closing_comment: 'Signed',+ });+ });++ it('Update Opportunity marked Won again keeps the existing close date', async () => {+ ok({ response: { id: 50, active: 3, closing_date: '2026-09-01' } });+ ok({ response: { id: 50 } });+ await runAction({+ action: updateOpportunityAction,+ props: { id: 50, status: 3 },+ });+ expect(sendRequest).toHaveBeenCalledTimes(2);+ expect(form(1)).toEqual({ active: '3' });+ });++ it('Update Opportunity moves the stage within the current pipeline without a Pipeline ID', async () => {+ ok({ response: { id: 50, pipeline_id: 1, pipeline_stage_id: 1 } });+ ok(listBody({ items: [{ id: 3, pipeline_id: 1 }] }));+ ok({ response: { id: 50 } });+ await runAction({+ action: updateOpportunityAction,+ props: { id: 50, pipeline_stage_id: 3 },+ });+ expect(request(1).url).toBe(`${BASE}/crm/pipeline_stage/list`);+ expect(request(1).queryParams).toMatchObject({+ 'filter[pipeline_id]': '1',+ });+ expect(request(2).url).toBe(`${BASE}/crm/lead/update/50`);+ expect(form(2)).toEqual({ pipeline_id: '1', pipeline_stage_id: '3' });+ });++ it('Create Opportunity rejects a non-numeric Customer ID before creating anything', async () => {+ await expect(+ runAction({+ action: createOpportunityAction,+ props: { name: 'Deal', customer_id: 'acme' },+ })+ ).rejects.toThrow('Customer ID must be a numeric Flowlu ID');+ expect(sendRequest).not.toHaveBeenCalled();+ });++ it('Create Opportunity rejects a stage of another pipeline before creating anything', async () => {+ ok(listBody({ items: [{ id: 1, pipeline_id: 1 }] }));+ await expect(+ runAction({+ action: createOpportunityAction,+ props: { name: 'Deal', pipeline_id: 1, pipeline_stage_id: 9 },+ })+ ).rejects.toThrow('Pipeline Stage ID 9 is not a stage of pipeline 1');+ expect(sendRequest).toHaveBeenCalledTimes(1);+ });++ it('Create Opportunity finds a stage on a later page of a large pipeline', async () => {+ const firstPage = Array.from({ length: 100 }, (_, i) => ({ id: i + 1, pipeline_id: 1 }));+ ok(listBody({ items: firstPage, total: 150 }));+ ok(listBody({ items: [{ id: 140, pipeline_id: 1 }], total: 150, page: 2 }));+ ok({ response: { id: 70 } });+ ok({ response: { id: 70, name: 'Deal', pipeline_id: 1, pipeline_stage_id: 140 } });+ await runAction({+ action: createOpportunityAction,+ props: { name: 'Deal', pipeline_id: 1, pipeline_stage_id: 140 },+ });+ expect(request(0).queryParams['page']).toBe('1');+ expect(request(1).queryParams['page']).toBe('2');+ expect(request(2).url).toBe(`${BASE}/crm/lead/create`);+ });++ it('Create Opportunity rejects a stage missing from every page before creating anything', async () => {+ const firstPage = Array.from({ length: 100 }, (_, i) => ({ id: i + 1, pipeline_id: 1 }));+ ok(listBody({ items: firstPage, total: 150 }));+ ok(listBody({ items: Array.from({ length: 50 }, (_, i) => ({ id: i + 101, pipeline_id: 1 })), total: 150, page: 2 }));+ await expect(+ runAction({+ action: createOpportunityAction,+ props: { name: 'Deal', pipeline_id: 1, pipeline_stage_id: 999 },+ })+ ).rejects.toThrow('Pipeline Stage ID 999 is not a stage of pipeline 1');+ expect(sendRequest).toHaveBeenCalledTimes(2);+ });++ it('Update Opportunity rejects a non-numeric Contact ID before updating', async () => {+ await expect(+ runAction({+ action: updateOpportunityAction,+ props: { id: 50, name: 'Renamed', contact_id: 'jane' },+ })+ ).rejects.toThrow('Contact ID must be a numeric Flowlu ID');+ expect(sendRequest).not.toHaveBeenCalled();+ });+});++describe('AI atomics', () => {+ it('flowlu_task_update sends only the given fields and models flags as three states', async () => {+ ok({ response: { id: 10 } });+ await runAction({+ action: flowluTaskUpdate,+ props: { task_id: '10', task_checkbyowner: 'no', status: 5 },+ });+ expect(form(0)).toEqual({ status: '5', task_checkbyowner: '0' });+ });++ it('flowlu_task_update refuses an empty update', async () => {+ await expect(+ runAction({ action: flowluTaskUpdate, props: { task_id: '10' } })+ ).rejects.toThrow('Nothing to update');+ expect(sendRequest).not.toHaveBeenCalled();+ });++ it('flowlu_task_create re-reads the task when create returns only the id', async () => {+ ok({ response: { id: 11, _resultMessage: 'ok' } });+ ok({ response: { id: 11, name: 'Call', status: 1 } });+ const result = await runAction({+ action: flowluTaskCreate,+ props: { name: 'Call', project_id: '7' },+ });+ expect(form(0)).toEqual({+ name: 'Call',+ module: 'st',+ model: 'project',+ model_id: '7',+ });+ expect(request(1).url).toBe(`${BASE}/task/tasks/get/11`);+ expect(result).toEqual({+ id: 11,+ name: 'Call',+ status: 1,+ read_back_error: null,+ });+ });++ it('flowlu_task_create reports a failed read-back instead of failing, so a retry does not duplicate the task', async () => {+ ok({ response: { id: 12 } });+ ok({ error: { error_code: 20, error_msg: 'not found' } });+ const result = await runAction({+ action: flowluTaskCreate,+ props: { name: 'Call' },+ });+ expect(result).toMatchObject({ id: 12 });+ expect(JSON.stringify(result)).toContain('reading it back failed');+ });++ it('flowlu_task_update rejects a status Flowlu does not have', async () => {+ await expect(+ runAction({+ action: flowluTaskUpdate,+ props: { task_id: '10', status: 2 },+ })+ ).rejects.toThrow('Status must be one of 1, 3, 4, 5');+ expect(sendRequest).not.toHaveBeenCalled();+ });++ it('flowlu_task_delete returns the deleted id', async () => {+ ok({ response: { id: '11' } });+ await expect(+ runAction({ action: flowluTaskDelete, props: { task_id: '11' } })+ ).resolves.toEqual({ id: 11, deleted: true });+ expect(request(0).url).toBe(`${BASE}/task/tasks/delete/11`);+ });++ it('flowlu_account_create needs a first name for a contact, before any request', async () => {+ await expect(+ runAction({+ action: flowluAccountCreate,+ props: { account_type: 'contact', last_name: 'Doe' },+ })+ ).rejects.toThrow('First Name is required');+ expect(sendRequest).not.toHaveBeenCalled();+ });++ it('flowlu_account_create reads the record back even when create returns some fields', async () => {+ ok({ response: { id: 3, name: 'Acme' } });+ ok({ response: { id: 3, name: 'Acme', type: 1, email: '[email protected]' } });+ const result = await runAction({+ action: flowluAccountCreate,+ props: { account_type: 'organization', name: 'Acme' },+ });+ expect(request(1).url).toBe(`${BASE}/crm/account/get/3`);+ expect(result).toEqual({+ id: 3,+ name: 'Acme',+ type: 1,+ email: '[email protected]',+ read_back_error: null,+ });+ });++ it('flowlu_account_create uses Flowlu field names', async () => {+ ok({ response: { id: 3, name: 'Acme' } });+ ok({ response: { id: 3, name: 'Acme' } });+ await runAction({+ action: flowluAccountCreate,+ props: {+ account_type: 'organization',+ name: 'Acme',+ vat: 'X1',+ linkedin: 'li',+ },+ });+ expect(form(0)).toEqual({+ name: 'Acme',+ VAT: 'X1',+ social_network_link_5: 'li',+ type: '1',+ });+ });++ it('flowlu_opportunity_create refuses a stage without a pipeline', async () => {+ await expect(+ runAction({+ action: flowluOpportunityCreate,+ props: { name: 'Deal', pipeline_stage_id: '4' },+ })+ ).rejects.toThrow('Pipeline Stage ID needs Pipeline ID');+ expect(sendRequest).not.toHaveBeenCalled();+ });++ it('flowlu_opportunity_create links organization and contact with their types', async () => {+ ok({ response: { id: 60, name: 'Deal' } });+ ok(listBody({ items: [] }));+ ok({ response: { id: 1 } });+ ok(listBody({ items: [] }));+ ok({ response: { id: 2 } });+ ok({ response: { id: 60, name: 'Deal', company_id: '17' } });+ const result = await runAction({+ action: flowluOpportunityCreate,+ props: { name: 'Deal', organization_id: '17', contact_id: '18' },+ });+ expect(request(5).url).toBe(`${BASE}/crm/lead/get/60`);+ expect(form(2)).toEqual({+ lead_id: '60',+ account_id: '17',+ account_type: '1',+ });+ expect(form(4)).toEqual({+ lead_id: '60',+ account_id: '18',+ account_type: '2',+ });+ expect(result).toMatchObject({+ id: 60,+ company_id: '17',+ read_back_error: null,+ link_errors: [],+ });+ });++ it('flowlu_opportunity_create rejects a bad Contact ID before creating anything', async () => {+ await expect(+ runAction({+ action: flowluOpportunityCreate,+ props: { name: 'Deal', contact_id: 'jane' },+ })+ ).rejects.toThrow('Contact ID must be a numeric Flowlu ID');+ expect(sendRequest).not.toHaveBeenCalled();+ });++ it('flowlu_opportunity_update moves the stage with only a Pipeline Stage ID', async () => {+ ok({ response: { id: 60, pipeline_id: 2 } });+ ok(listBody({ items: [{ id: 7, pipeline_id: 2 }] }));+ ok({ response: { id: 60, pipeline_id: 2, pipeline_stage_id: 7 } });+ await runAction({+ action: flowluOpportunityUpdate,+ props: { opportunity_id: '60', pipeline_stage_id: '7' },+ });+ expect(request(0).url).toBe(`${BASE}/crm/lead/get/60`);+ expect(form(2)).toEqual({ pipeline_id: '2', pipeline_stage_id: '7' });+ });++ it('flowlu_opportunity_update refuses a stage outside the current pipeline without updating', async () => {+ ok({ response: { id: 60, pipeline_id: 2 } });+ ok(listBody({ items: [{ id: 7, pipeline_id: 2 }] }));+ await expect(+ runAction({+ action: flowluOpportunityUpdate,+ props: { opportunity_id: '60', pipeline_stage_id: '3' },+ })+ ).rejects.toThrow('Pipeline Stage ID 3 is not a stage of pipeline 2');+ expect(sendRequest).toHaveBeenCalledTimes(2);+ });++ it('flowlu_opportunity_update marked Won again keeps the existing close date', async () => {+ ok({ response: { id: 60, active: 3, closing_date: '2026-09-01' } });+ ok({ response: { id: 60, active: 3, closing_date: '2026-09-01' } });+ await runAction({+ action: flowluOpportunityUpdate,+ props: { opportunity_id: '60', status: 3 },+ });+ expect(form(1)).toEqual({ active: '3' });+ });++ it('flowlu_opportunity_update stamps today when a deal moves from Lost to Won', async () => {+ ok({ response: { id: 60, active: 2, closing_date: '2026-09-01' } });+ ok({ response: { id: 60 } });+ await runAction({+ action: flowluOpportunityUpdate,+ props: { opportunity_id: '60', status: 3 },+ });+ expect(form(1)).toEqual({+ active: '3',+ closing_date: dayjs().format('YYYY-MM-DD'),+ });+ });++ it('flowlu_opportunity_update closes a deal as lost with a reason', async () => {+ ok({ response: { id: 60 } });+ await runAction({+ action: flowluOpportunityUpdate,+ props: {+ opportunity_id: '60',+ status: 2,+ closing_status_id: '3',+ closing_date: '2026-09-30T12:00:00Z',+ },+ });+ expect(form(0)).toEqual({+ active: '2',+ closing_date: '2026-09-30',+ closing_status_id: '3',+ });+ });+});++describe('link and search actions', () => {+ it('Link Account to Opportunity returns the existing link instead of duplicating it', async () => {+ ok(+ listBody({+ items: [{ id: 5, lead_id: 60, account_id: 17, account_type: 1 }],+ })+ );+ const result = await runAction({+ action: linkAccountToOpportunityAction,+ props: {+ opportunity_id: '60',+ account_id: '17',+ account_type: 'organization',+ },+ });+ expect(result).toEqual({+ id: 5,+ lead_id: 60,+ account_id: 17,+ account_type: 1,+ already_linked: true,+ });+ expect(sendRequest).toHaveBeenCalledTimes(1);+ });++ it('Find Tasks pages with has_more and filters by project', async () => {+ ok(listBody({ items: [{ id: 1 }, { id: 2 }], total: 5, page: 2 }));+ const result = await runAction({+ action: findTasksAction,+ props: { project_id: '7', page: 2, limit: 2, status: 5 },+ });+ expect(request(0).queryParams).toMatchObject({+ 'filter[module]': 'st',+ 'filter[model]': 'project',+ 'filter[model_id]': '7',+ 'filter[status]': '5',+ 'order_by[desc][]': 'id',+ page: '2',+ limit: '2',+ });+ expect(result).toEqual({+ items: [{ id: 1 }, { id: 2 }],+ page: 2,+ count: 2,+ total: 5,+ has_more: true,+ });+ });++ it('Find CRM Accounts filters contacts and active ones by default', async () => {+ ok(listBody({ items: [] }));+ await runAction({+ action: findAccountsAction,+ props: { account_type: 'contact', search: 'acme' },+ });+ expect(request(0).queryParams).toMatchObject({+ 'filter[type]': '2',+ 'filter[active]': '1',+ search: 'acme',+ limit: '50',+ });+ });++ it("rejects a limit above Flowlu's maximum of 100 (0 would switch Flowlu to export mode)", async () => {+ await expect(+ runAction({ action: findTasksAction, props: { limit: 101 } })+ ).rejects.toThrow('Limit must be');+ await expect(+ runAction({ action: findTasksAction, props: { limit: 0 } })+ ).rejects.toThrow('Limit must be');+ expect(sendRequest).not.toHaveBeenCalled();+ });++ it('List Users returns curated rows only', async () => {+ ok(+ listBody({+ items: [+ {+ id: 1,+ name: 'Jane',+ username: '[email protected]',+ image: '/x.png',+ role_admin: 1,+ },+ ],+ })+ );+ const result = await runAction({ action: listUsersAction, props: {} });+ expect(request(0).url).toBe(`${BASE}/core/user/list`);+ expect(result).toMatchObject({+ items: [+ { id: 1, name: 'Jane', username: '[email protected]', role_admin: 1 },+ ],+ has_more: false,+ });+ expect(JSON.stringify(result)).not.toContain('image');+ });++ it('List Reference Values pages to the end and filters stages by pipeline', async () => {+ const page1 = Array.from({ length: 100 }, (_, i) => ({+ id: i + 1,+ name: `S${i + 1}`,+ pipeline_id: 4,+ }));+ ok(listBody({ items: page1, total: 101 }));+ ok(+ listBody({+ items: [{ id: 101, name: 'S101', pipeline_id: 4 }],+ total: 101,+ page: 2,+ })+ );+ const result = await runAction({+ action: listLookupValuesAction,+ props: { entity: 'pipeline_stages', parent_id: '4' },+ });+ expect(request(0).url).toBe(`${BASE}/crm/pipeline_stage/list`);+ expect(request(0).queryParams).toMatchObject({+ 'filter[pipeline_id]': '4',+ page: '1',+ limit: '100',+ });+ expect(request(1).queryParams).toMatchObject({ page: '2' });+ expect(result).toMatchObject({+ entity: 'pipeline_stages',+ count: 101,+ total: 101,+ has_more: false,+ });+ });++ it('List Reference Values refuses a parent for a value type without one', async () => {+ await expect(+ runAction({+ action: listLookupValuesAction,+ props: { entity: 'industries', parent_id: '4' },+ })+ ).rejects.toThrow('have no parent');+ });++ it('Update Project refuses an empty update', async () => {+ await expect(+ runAction({ action: updateProjectAction, props: { project_id: 7 } })+ ).rejects.toThrow('Nothing to update');+ });+});++describe('dropdowns', () => {+ const options = ({+ prop,+ searchValue,+ }: {+ prop: unknown;+ searchValue?: string;+ }) => {+ const fn: unknown = Reflect.get(Object(prop), 'options');+ if (typeof fn !== 'function') {+ throw new Error('no options');+ }+ return Promise.resolve(+ Reflect.apply(fn, undefined, [{ auth: AUTH }, { searchValue }])+ );+ };++ it('asks for 100 newest records, searches, and says when the list is cut', async () => {+ ok(listBody({ items: [{ id: 9, name: 'Task 9' }], total: 250 }));+ const result = await options({+ prop: flowluCommon.task_id(true),+ searchValue: 'call',+ });+ expect(request(0).queryParams).toMatchObject({+ limit: '100',+ 'order_by[desc][]': 'id',+ search: 'call',+ });+ expect(result).toEqual({+ disabled: false,+ options: [{ label: 'Task 9 (#9)', value: 9 }],+ placeholder: 'Showing the first 1 of 250.',+ });+ });++ it('returns a disabled state with the reason when Flowlu fails', async () => {+ ok({ error: { error_code: 11, error_msg: 'api key not found' } });+ const result = await options({ prop: flowluCommon.user_id(true) });+ expect(result).toMatchObject({ disabled: true, options: [] });+ expect(JSON.stringify(result)).toContain('error 11');+ });+});diff --git a/packages/pieces/community/flowlu/test/client.test.ts b/packages/pieces/community/flowlu/test/client.test.tsnew file mode 100644index 00000000000..b9fd7c3ac46--- /dev/null+++ b/packages/pieces/community/flowlu/test/client.test.ts@@ -0,0 +1,270 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import {+ API_KEY,+ BASE,+ fail,+ ok,+ okWithStatus,+ request,+ sendRequest,+} from './helpers';+import {+ FlowluApiError,+ FlowluClient,+ flowluTiming,+ normalizeDomain,+ toFormBody,+} from '../src/lib/common/client';+import { flowluAuth } from '../src/lib/auth';++vi.mock('@activepieces/pieces-common', async (importOriginal) => {+ const actual = await importOriginal<+ typeof import('@activepieces/pieces-common')+ >();+ return {+ ...actual,+ httpClient: { sendRequest: (...args: unknown[]) => sendRequest(...args) },+ };+});++const client = () => new FlowluClient('example', API_KEY);++async function caught(promise: Promise<unknown>): Promise<FlowluApiError> {+ try {+ await promise;+ } catch (error) {+ if (error instanceof FlowluApiError) {+ return error;+ }+ throw error;+ }+ throw new Error('expected a FlowluApiError');+}++beforeEach(() => {+ sendRequest.mockReset();+ vi.restoreAllMocks();+});++describe('normalizeDomain', () => {+ it.each([+ ['example', 'example'],+ [' Example ', 'example'],+ ['example.flowlu.com', 'example'],+ ['https://example.flowlu.com/', 'example'],+ ['http://my-company.flowlu.com', 'my-company'],+ ])('accepts %s', (input, expected) => {+ expect(normalizeDomain(input)).toBe(expected);+ });++ it.each([+ 'example.flowlu.com.evil.io',+ 'evil.io/x#',+ 'evil.io',+ '[email protected]',+ 'https://evil.io/example.flowlu.com',+ 'example.flowlu.com/../x',+ '-example',+ '',+ 'exa mple',+ ])('rejects %s so the key never leaves *.flowlu.com', (input) => {+ expect(() => normalizeDomain(input)).toThrow(FlowluApiError);+ });+});++describe('toFormBody', () => {+ it('drops unset values instead of sending "undefined" or "null"', () => {+ const body = toFormBody({+ a: undefined,+ b: null,+ c: '',+ d: 0,+ e: false,+ f: true,+ g: 'x y',+ h: 1.5,+ });+ expect(body).toBe('d=0&e=0&f=1&g=x+y&h=1.5');+ expect(body).not.toContain('undefined');+ expect(body).not.toContain('null');+ });++ it('refuses objects and arrays', () => {+ expect(() => toFormBody({ a: { b: 1 } })).toThrow(FlowluApiError);+ expect(() => toFormBody({ a: [1] })).toThrow(FlowluApiError);+ });+});++describe('FlowluClient.request', () => {+ it('sends the key only as a query param to the portal host and never follows redirects', async () => {+ ok({ response: { id: 5 } });+ await client().getRecord('task', 'tasks', 5);+ const req = request(0);+ expect(req.method).toBe(HttpMethod.GET);+ expect(req.url).toBe(`${BASE}/task/tasks/get/5`);+ expect(req.queryParams).toEqual({ api_key: API_KEY });+ expect(req.body).toBeUndefined();+ expect(req.followRedirects).toBe(false);+ });++ it('posts a form-urlencoded body', async () => {+ ok({ response: { id: 9 } });+ await client().createRecord('crm', 'lead', {+ name: 'Deal',+ budget: 10,+ description: undefined,+ });+ const req = request(0);+ expect(req.method).toBe(HttpMethod.POST);+ expect(req.headers).toEqual({+ 'Content-Type': 'application/x-www-form-urlencoded',+ });+ expect(req.body).toBe('name=Deal&budget=10');+ });++ it('turns a 200 not-found body into a failure', async () => {+ ok({ error: { error_code: 20, error_msg: 'not found' } });+ const error = await caught(client().getRecord('task', 'tasks', 99));+ expect(error.message).toBe(+ 'Flowlu could not find the record (error 20: not found). Check the ID.'+ );+ expect(error.errorCode).toBe(20);+ expect(error.responseBody).toEqual({+ error: { error_code: 20, error_msg: 'not found' },+ });+ expect(Reflect.has(error, 'body')).toBe(false);+ });++ it('turns a 200 validation body into a failure that names the field', async () => {+ ok({+ error: 'validation',+ description: 'Form filling error',+ details: { name: 'name cannot be empty' },+ });+ const error = await caught(client().createRecord('crm', 'lead', {}));+ expect(error.message).toBe(+ 'Flowlu validation error: name: name cannot be empty.'+ );+ });++ it('names the portal host, never the key, on error 11', async () => {+ ok({ error: { error_code: 11, error_msg: 'account not found' } });+ const error = await caught(client().list('core', 'user'));+ expect(error.message).toContain('https://example.flowlu.com');+ expect(error.message).not.toContain(API_KEY);+ expect(error.errorCode).toBe(11);+ });++ it('retries 429 with 1 s, 2 s, 4 s backoff and then succeeds', async () => {+ const sleep = vi.spyOn(flowluTiming, 'sleep').mockResolvedValue();+ fail({ status: 429 });+ fail({ status: 429 });+ fail({ status: 429 });+ ok({ response: { id: 1 } });+ await expect(client().getRecord('task', 'tasks', 1)).resolves.toEqual({+ id: 1,+ });+ expect(sleep.mock.calls.map((call) => call[0])).toEqual([1000, 2000, 4000]);+ expect(sendRequest).toHaveBeenCalledTimes(4);+ });++ it('gives up after three 429 retries with a rate-limit message', async () => {+ vi.spyOn(flowluTiming, 'sleep').mockResolvedValue();+ fail({ status: 429 });+ fail({ status: 429 });+ fail({ status: 429 });+ fail({ status: 429, body: 'Too Many Requests' });+ const error = await caught(client().getRecord('task', 'tasks', 1));+ expect(error.status).toBe(429);+ expect(error.message).toContain('rate limit');+ expect(sendRequest).toHaveBeenCalledTimes(4);+ });++ it('does not retry other HTTP errors and keeps the vendor body in responseBody', async () => {+ fail({ status: 500, body: { message: 'boom' } });+ const error = await caught(client().getRecord('task', 'tasks', 1));+ expect(error.status).toBe(500);+ expect(error.message).toBe(+ 'Flowlu request failed with HTTP 500: {"message":"boom"}'+ );+ expect(error.responseBody).toEqual({ message: 'boom' });+ expect(sendRequest).toHaveBeenCalledTimes(1);+ });++ it('fails on a redirect instead of following it with the key', async () => {+ okWithStatus({ body: '', status: 302 });+ const error = await caught(client().getRecord('task', 'tasks', 1));+ expect(error.status).toBe(302);+ expect(error.message).toContain('redirected');+ });++ it('turns a timeout into a readable failure', async () => {+ const abort = new Error('This operation was aborted');+ abort.name = 'AbortError';+ sendRequest.mockRejectedValueOnce(abort);+ const error = await caught(client().getRecord('task', 'tasks', 1));+ expect(error.message).toBe(+ 'Flowlu did not answer within 20 seconds. Try again later.'+ );+ expect(request(0)).toMatchObject({ timeout: 20000 });+ });++ it('fails on a non-JSON response', async () => {+ ok('<html>login</html>');+ const error = await caught(client().getRecord('task', 'tasks', 1));+ expect(error.message).toContain('unexpected response');+ });++ it('rejects an empty key and a bad domain before any request', () => {+ expect(() => new FlowluClient('example', ' ')).toThrow(FlowluApiError);+ expect(() => new FlowluClient('evil.io/x#', API_KEY)).toThrow(+ FlowluApiError+ );+ expect(sendRequest).not.toHaveBeenCalled();+ });+});++describe('auth.validate', () => {+ const validate = (domain: string) =>+ Reflect.apply(asValidate(), undefined, [+ { auth: { domain, apiKey: API_KEY }, server: {} },+ ]);++ it('accepts a working key and calls the users list with limit 1', async () => {+ ok({ response: { items: [] } });+ await expect(validate('https://example.flowlu.com/')).resolves.toEqual({+ valid: true,+ });+ expect(request(0).url).toBe(`${BASE}/core/user/list`);+ expect(request(0).queryParams).toEqual({ limit: '1', api_key: API_KEY });+ });++ it('rejects a key Flowlu does not know', async () => {+ ok({ error: { error_code: 11, error_msg: 'api key not found' } });+ const result = await validate('example');+ expect(result.valid).toBe(false);+ });++ it('accepts a valid key that lacks access to the users module', async () => {+ ok({ error: { error_code: 30, error_msg: 'access denied' } });+ await expect(validate('example')).resolves.toEqual({ valid: true });+ });++ it('rejects a lookalike domain without sending the key', async () => {+ const result = await validate('example.flowlu.com.evil.io');+ expect(result.valid).toBe(false);+ expect(sendRequest).not.toHaveBeenCalled();+ });+});++function asValidate(): (+ ...args: unknown[]+) => Promise<{ valid: boolean; error?: string }> {+ const fn: unknown = Reflect.get(flowluAuth, 'validate');+ if (typeof fn !== 'function') {+ throw new Error('validate missing');+ }+ return (...args: unknown[]) =>+ Promise.resolve(Reflect.apply(fn, undefined, args));+}diff --git a/packages/pieces/community/flowlu/test/helpers.ts b/packages/pieces/community/flowlu/test/helpers.tsnew file mode 100644index 00000000000..4a63676cccc--- /dev/null+++ b/packages/pieces/community/flowlu/test/helpers.ts@@ -0,0 +1,132 @@+import { vi } from 'vitest';++export const API_KEY = 'flowlu-test-key-123';+export const AUTH = {+ type: 'CUSTOM_AUTH',+ props: { domain: 'example', apiKey: API_KEY },+};+export const BASE = 'https://example.flowlu.com/api/v1/module';++export const sendRequest = vi.fn();++export function ok(body: unknown) {+ okWithStatus({ body, status: 200 });+}++export function okWithStatus({+ body,+ status,+}: {+ body: unknown;+ status: number;+}) {+ sendRequest.mockResolvedValueOnce({ status, headers: {}, body });+}++export function fail({+ status,+ body = {},+}: {+ status: number;+ body?: unknown;+}) {+ sendRequest.mockRejectedValueOnce(new FakeHttpError({ status, body }));+}++export function request(index: number): {+ method: string;+ url: string;+ headers?: Record<string, string>;+ queryParams: Record<string, string>;+ body?: string;+ followRedirects?: boolean;+} {+ return sendRequest.mock.calls[index][0];+}++export function form(index: number): Record<string, string> {+ return Object.fromEntries(new URLSearchParams(request(index).body ?? ''));+}++export function memoryStore(initial: Record<string, unknown> = {}) {+ const data = new Map<string, unknown>(Object.entries(initial));+ return {+ data,+ store: {+ put: async <T>(key: string, value: T) => {+ data.set(key, value);+ return value;+ },+ get: async <T>(key: string): Promise<T | null> => {+ const value: unknown = data.get(key);+ return value === undefined ? null : JSON.parse(JSON.stringify(value));+ },+ delete: async (key: string) => {+ data.delete(key);+ },+ },+ };+}++export function runAction({+ action,+ props,+}: {+ action: { run: unknown };+ props: Record<string, unknown>;+}): Promise<unknown> {+ return Promise.resolve(+ Reflect.apply(asFunction(action.run), action, [+ {+ auth: AUTH,+ propsValue: { auth: AUTH, ...props },+ store: memoryStore().store,+ },+ ])+ );+}++export function runHook({+ trigger,+ hook,+ context,+}: {+ trigger: Record<string, unknown>;+ hook: 'run' | 'onEnable' | 'onDisable' | 'test';+ context: Record<string, unknown>;+}): Promise<unknown> {+ return Promise.resolve(+ Reflect.apply(asFunction(trigger[hook]), trigger, [+ { auth: AUTH, propsValue: {}, ...context },+ ])+ );+}++export function asFunction(value: unknown): (...args: unknown[]) => unknown {+ if (typeof value !== 'function') {+ throw new Error('not a function');+ }+ return (...args: unknown[]) => Reflect.apply(value, undefined, args);+}++export function listBody({+ items,+ total = items.length,+ page = 1,+}: {+ items: Record<string, unknown>[];+ total?: number;+ page?: number;+}) {+ return {+ response: { total, total_result: total, page, count: items.length, items },+ };+}++class FakeHttpError extends Error {+ readonly response: { status: number; body: unknown };+ constructor({ status, body }: { status: number; body: unknown }) {+ super(JSON.stringify({ response: { status, body } }));+ this.response = { status, body };+ }+}diff --git a/packages/pieces/community/flowlu/test/triggers.test.ts b/packages/pieces/community/flowlu/test/triggers.test.tsnew file mode 100644index 00000000000..ca0043e2659--- /dev/null+++ b/packages/pieces/community/flowlu/test/triggers.test.ts@@ -0,0 +1,368 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import {+ API_KEY,+ BASE,+ listBody,+ memoryStore,+ ok,+ request,+ runHook,+ sendRequest,+} from './helpers';+import { newTaskTrigger } from '../src/lib/triggers/new-task';+import { newCrmAccountTrigger } from '../src/lib/triggers/new-crm-account';+import { newOpportunityTrigger } from '../src/lib/triggers/new-opportunity';+import { newProjectTrigger } from '../src/lib/triggers/new-project';++vi.mock('@activepieces/pieces-common', async (importOriginal) => {+ const actual = await importOriginal<+ typeof import('@activepieces/pieces-common')+ >();+ return {+ ...actual,+ httpClient: { sendRequest: (...args: unknown[]) => sendRequest(...args) },+ };+});++const KEY = 'flowlu_last_seen_id';+const asRecord = (value: unknown): Record<string, unknown> => Object(value);++beforeEach(() => {+ sendRequest.mockReset();+});++describe('polling triggers', () => {+ it('onEnable stores the newest id of the whole entity, ignoring the filters', async () => {+ const { store, data } = memoryStore();+ fakeFlowlu({+ records: [+ { id: 1, responsible_id: 2 },+ { id: 42, responsible_id: 3 },+ ],+ });+ await runHook({+ trigger: asRecord(newTaskTrigger),+ hook: 'onEnable',+ context: { store, propsValue: { responsible_id: 2 } },+ });+ expect(request(0).url).toBe(`${BASE}/task/tasks/list`);+ expect(request(0).queryParams).toEqual({+ 'order_by[desc][]': 'id',+ limit: '1',+ api_key: API_KEY,+ });+ expect(data.get(KEY)).toBe(42);+ });++ it('run asks only for ids above the checkpoint, oldest first, and emits them in order', async () => {+ const { store, data } = memoryStore({ [KEY]: 42 });+ fakeFlowlu({ records: ids({ from: 40, to: 45 }) });+ const items = await runHook({+ trigger: asRecord(newTaskTrigger),+ hook: 'run',+ context: { store },+ });+ expect(request(1).queryParams).toMatchObject({+ 'filter[id]': '{"type":"more","value":42}',+ 'order_by[asc][]': 'id',+ limit: '100',+ page: '1',+ });+ expect(items).toEqual(ids({ from: 43, to: 45 }));+ expect(data.get(KEY)).toBe(45);+ });++ it('run follows full pages and never re-emits an item on the next poll', async () => {+ const { store, data } = memoryStore({ [KEY]: 0 });+ fakeFlowlu({ records: ids({ from: 1, to: 103 }) });+ const first = await poll({ trigger: newProjectTrigger, store });+ expect(first.map(idOf)).toEqual(range({ from: 1, to: 103 }));+ expect(data.get(KEY)).toBe(103);+ const second = await poll({ trigger: newProjectTrigger, store });+ expect(second).toEqual([]);+ });++ it('more than 500 new records arrive across two polls, each emitted exactly once', async () => {+ const { store, data } = memoryStore({ [KEY]: 100 });+ const records = ids({ from: 1, to: 100 });+ fakeFlowlu({ records });+ records.push(...ids({ from: 101, to: 750 }));+ const first = await poll({ trigger: newProjectTrigger, store });+ expect(first.map(idOf)).toEqual(range({ from: 101, to: 600 }));+ expect(data.get(KEY)).toBe(600);+ const second = await poll({ trigger: newProjectTrigger, store });+ expect(second.map(idOf)).toEqual(range({ from: 601, to: 750 }));+ expect(await poll({ trigger: newProjectTrigger, store })).toEqual([]);+ });++ it('an old record reassigned into the filter never fires; a new matching one does', async () => {+ const { store } = memoryStore();+ const records = ids({ from: 1, to: 10 }).map((r) => ({+ ...r,+ responsible_id: 3,+ }));+ fakeFlowlu({ records });+ const propsValue = { responsible_id: 2 };+ await runHook({+ trigger: asRecord(newTaskTrigger),+ hook: 'onEnable',+ context: { store, propsValue },+ });+ expect(await poll({ trigger: newTaskTrigger, store, propsValue })).toEqual(+ []+ );+ records[2] = { ...records[2], responsible_id: 2 };+ expect(await poll({ trigger: newTaskTrigger, store, propsValue })).toEqual(+ []+ );+ records.push({ id: 11, responsible_id: 2 }, { id: 12, responsible_id: 3 });+ const fired = await poll({ trigger: newTaskTrigger, store, propsValue });+ expect(fired).toEqual([{ id: 11, responsible_id: 2 }]);+ });++ it('nothing matches the filter at enable time: older records still never fire', async () => {+ const { store, data } = memoryStore();+ const records = ids({ from: 1, to: 5 }).map((r) => ({+ ...r,+ responsible_id: 3,+ }));+ fakeFlowlu({ records });+ const propsValue = { responsible_id: 2 };+ await runHook({+ trigger: asRecord(newTaskTrigger),+ hook: 'onEnable',+ context: { store, propsValue },+ });+ expect(data.get(KEY)).toBe(5);+ records[1] = { ...records[1], responsible_id: 2 };+ expect(await poll({ trigger: newTaskTrigger, store, propsValue })).toEqual(+ []+ );+ expect(data.get(KEY)).toBe(5);+ });++ it('an empty entity at enable time stores 0, and the first new record fires', async () => {+ const { store, data } = memoryStore();+ const records: Record<string, unknown>[] = [];+ fakeFlowlu({ records });+ await runHook({+ trigger: asRecord(newProjectTrigger),+ hook: 'onEnable',+ context: { store },+ });+ expect(data.get(KEY)).toBe(0);+ records.push({ id: 1 });+ expect(await poll({ trigger: newProjectTrigger, store })).toEqual([+ { id: 1 },+ ]);+ expect(data.get(KEY)).toBe(1);+ });++ it('records that do not match the filter still move the checkpoint, so they never fire later', async () => {+ const { store, data } = memoryStore({ [KEY]: 1 });+ fakeFlowlu({+ records: ids({ from: 1, to: 5 }).map((r) => ({ ...r, type: 1 })),+ });+ const propsValue = { account_type: 'contact' };+ expect(+ await poll({ trigger: newCrmAccountTrigger, store, propsValue })+ ).toEqual([]);+ expect(data.get(KEY)).toBe(5);+ });++ it('when Flowlu ignores the id filter, it finds the checkpoint and emits >500 new records oldest first, once each', async () => {+ const { store, data } = memoryStore({ [KEY]: 1000 });+ const records = ids({ from: 1, to: 1000 });+ fakeFlowlu({ records, honourIdFilter: false });+ records.push(...ids({ from: 1001, to: 1650 }));+ const first = await poll({ trigger: newProjectTrigger, store });+ expect(first.map(idOf)).toEqual(range({ from: 1001, to: 1500 }));+ expect(data.get(KEY)).toBe(1500);+ expect(sendRequest.mock.calls.length).toBeLessThan(20);+ const second = await poll({ trigger: newProjectTrigger, store });+ expect(second.map(idOf)).toEqual(range({ from: 1501, to: 1650 }));+ expect(data.get(KEY)).toBe(1650);+ expect(await poll({ trigger: newProjectTrigger, store })).toEqual([]);+ });++ it('when Flowlu ignores the id filter, filters still apply and the checkpoint is found on page 1', async () => {+ const { store, data } = memoryStore({ [KEY]: 10 });+ fakeFlowlu({+ records: [+ { id: 1, pipeline_id: 3 },+ { id: 11, pipeline_id: 3 },+ { id: 12, pipeline_id: 4 },+ { id: 13, pipeline_id: 3 },+ ],+ honourIdFilter: false,+ });+ const items = await poll({+ trigger: newOpportunityTrigger,+ store,+ propsValue: { pipeline_id: 3 },+ });+ expect(items).toEqual([+ { id: 11, pipeline_id: 3 },+ { id: 13, pipeline_id: 3 },+ ]);+ expect(data.get(KEY)).toBe(13);+ });++ it('fails, keeping the checkpoint, when Flowlu ignores both the id filter and the sort order', async () => {+ const { store, data } = memoryStore({ [KEY]: 2 });+ fakeFlowlu({+ records: [{ id: 5 }, { id: 1 }, { id: 3 }],+ honourIdFilter: false,+ honourOrder: false,+ });+ await expect(poll({ trigger: newProjectTrigger, store })).rejects.toThrow(+ 'ignored both the id filter and the sort order'+ );+ expect(data.get(KEY)).toBe(2);+ });++ it('run without a checkpoint initialises it and emits nothing', async () => {+ const { store, data } = memoryStore();+ fakeFlowlu({ records: ids({ from: 1, to: 7 }) });+ const items = await poll({ trigger: newProjectTrigger, store });+ expect(items).toEqual([]);+ expect(data.get(KEY)).toBe(7);+ });++ it('a failed poll keeps the checkpoint', async () => {+ const { store, data } = memoryStore({ [KEY]: 5 });+ ok({ error: { error_code: 11, error_msg: 'api key not found' } });+ await expect(poll({ trigger: newProjectTrigger, store })).rejects.toThrow(+ 'error 11'+ );+ expect(data.get(KEY)).toBe(5);+ });++ it('filters go to Flowlu on the new-records query only', async () => {+ const { store } = memoryStore({ [KEY]: 1 });+ fakeFlowlu({ records: [] });+ await poll({+ trigger: newCrmAccountTrigger,+ store,+ propsValue: { account_type: 'contact' },+ });+ expect(request(0).url).toBe(`${BASE}/crm/account/list`);+ expect(request(0).queryParams['filter[type]']).toBeUndefined();+ expect(request(1).queryParams).toMatchObject({ 'filter[type]': '2' });+ await poll({+ trigger: newOpportunityTrigger,+ store,+ propsValue: { pipeline_id: 3 },+ });+ expect(request(3).queryParams).toMatchObject({+ 'filter[pipeline_id]': '3',+ });+ await poll({+ trigger: newTaskTrigger,+ store,+ propsValue: { project_id: 7, responsible_id: 2 },+ });+ expect(request(5).queryParams).toMatchObject({+ 'filter[model_id]': '7',+ 'filter[model]': 'project',+ 'filter[responsible_id]': '2',+ });+ });++ it('test returns the 5 newest records', async () => {+ ok(listBody({ items: [{ id: 9 }, { id: 8 }] }));+ const items = await runHook({+ trigger: asRecord(newTaskTrigger),+ hook: 'test',+ context: { store: memoryStore().store },+ });+ expect(request(0).queryParams).toMatchObject({+ 'order_by[desc][]': 'id',+ limit: '5',+ });+ expect(items).toEqual([{ id: 9 }, { id: 8 }]);+ });++ it('onDisable forgets the checkpoint', async () => {+ const { store, data } = memoryStore({ [KEY]: 5 });+ await runHook({+ trigger: asRecord(newTaskTrigger),+ hook: 'onDisable',+ context: { store },+ });+ expect(data.has(KEY)).toBe(false);+ });+});++function poll({+ trigger,+ store,+ propsValue = {},+}: {+ trigger: unknown;+ store: ReturnType<typeof memoryStore>['store'];+ propsValue?: Record<string, unknown>;+}): Promise<Record<string, unknown>[]> {+ return runHook({+ trigger: asRecord(trigger),+ hook: 'run',+ context: { store, propsValue },+ }).then((items) => (Array.isArray(items) ? items : []));+}++function fakeFlowlu({+ records,+ honourIdFilter = true,+ honourOrder = true,+}: {+ records: Record<string, unknown>[];+ honourIdFilter?: boolean;+ honourOrder?: boolean;+}) {+ sendRequest.mockImplementation(+ async (req: { queryParams: Record<string, string> }) => {+ const query = req.queryParams;+ const matching = records.filter((record) =>+ Object.entries(query).every(([key, value]) => {+ const field = /^filter\[(\w+)\]$/.exec(key)?.[1];+ if (field === undefined) {+ return true;+ }+ if (field === 'id') {+ return (+ !honourIdFilter ||+ idOf(record) > Number(JSON.parse(value)['value'])+ );+ }+ return String(record[field]) === value;+ })+ );+ const desc = query['order_by[desc][]'] === 'id';+ const ordered = honourOrder+ ? [...matching].sort((a, b) =>+ desc ? idOf(b) - idOf(a) : idOf(a) - idOf(b)+ )+ : matching;+ const limit = Number(query['limit']);+ const page = Number(query['page'] ?? 1);+ const items = ordered.slice((page - 1) * limit, page * limit);+ return {+ status: 200,+ headers: {},+ body: listBody({ items, total: ordered.length, page }),+ };+ }+ );+}++function ids({ from, to }: { from: number; to: number }) {+ return range({ from, to }).map((id) => ({ id }));+}++function range({ from, to }: { from: number; to: number }) {+ return Array.from({ length: to - from + 1 }, (_, i) => from + i);+}++function idOf(item: Record<string, unknown>): number {+ return Number(item['id']);+}diff --git a/packages/pieces/community/flowlu/vitest.config.ts b/packages/pieces/community/flowlu/vitest.config.tsnew file mode 100644index 00000000000..fccdb644d65--- /dev/null+++ b/packages/pieces/community/flowlu/vitest.config.ts@@ -0,0 +1,25 @@+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'+ ),+ },+ },+});