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(odoo): new record, lead and sales order triggers, plus actions for leads, quotations, invoices and chatter (#15949)
Odai Ahmada3ba6ca5c874
diff --git a/bun.lock b/bun.lockindex 90f0c33e431..3af807a3fa9 100644--- a/bun.lock+++ b/bun.lock@@ -6459,7 +6459,7 @@},"packages/pieces/community/odoo": {"name": "@activepieces/piece-odoo",- "version": "0.1.7",+ "version": "0.2.0","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",@@ -6472,6 +6472,7 @@"devDependencies": {"@types/xmlrpc": "^1.3.10","tslib": "2.6.2",+ "vitest": "3.2.6",},},"packages/pieces/community/okta": {diff --git a/packages/pieces/community/odoo/package.json b/packages/pieces/community/odoo/package.jsonindex 108af01da63..787a1eb7829 100644--- a/packages/pieces/community/odoo/package.json+++ b/packages/pieces/community/odoo/package.json@@ -1,6 +1,6 @@{"name": "@activepieces/piece-odoo",- "version": "0.1.7",+ "version": "0.2.0","main": "./dist/src/index.js","types": "./dist/src/index.d.ts","dependencies": {@@ -14,11 +14,13 @@},"devDependencies": {"@types/xmlrpc": "^1.3.10",- "tslib": "2.6.2"+ "tslib": "2.6.2",+ "vitest": "3.2.6"},"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"}}diff --git a/packages/pieces/community/odoo/src/commom/index.ts b/packages/pieces/community/odoo/src/commom/index.tsindex e614faf5e59..e72cab483d7 100644--- a/packages/pieces/community/odoo/src/commom/index.ts+++ b/packages/pieces/community/odoo/src/commom/index.ts@@ -203,12 +203,16 @@ class Odoo {})}- async getRecords<T = any>({model, domain, fields, offset, limit}: GetRecordsParams): Promise<T> {+ async getRecords<T = unknown>({model, domain, fields, offset, limit, order}: GetRecordsParams): Promise<T> {+ const args: unknown[] = [domain, fields, offset, limit];+ if (order) {+ args.push(order);+ }return this.execute_kw<T>({model: model,method: "search_read",params: [- [domain, fields, offset, limit]+ args]})}@@ -246,14 +250,16 @@ class Odoo {address,}: SaveContactParams): Promise<T> {- const contact = {+ const contact: Record<string, unknown> = {name: name,phone: phone,email: email,company_name: company,- company_id: company_id || null,function: title,};+ if (company_id) {+ contact['company_id'] = company_id;+ }try {const record = await this.execute_kw<T>({@@ -264,7 +270,7 @@ class Odoo {]})- this.execute_kw<T>({+ await this.execute_kw<T>({model: "res.partner",method: "write",params: [[record, contact]],@@ -307,7 +313,7 @@ class Odoo {]})- this.execute_kw<T>({+ await this.execute_kw<T>({model: "res.partner",method: "write",params: [[record, contact]],diff --git a/packages/pieces/community/odoo/src/commom/type.ts b/packages/pieces/community/odoo/src/commom/type.tsindex f6a83b645e2..ab20d1a62f7 100644--- a/packages/pieces/community/odoo/src/commom/type.ts+++ b/packages/pieces/community/odoo/src/commom/type.ts@@ -53,6 +53,7 @@ export type GetRecordsParams = {fields?: any[];offset?: number;limit?: number;+ order?: string;};export type CreateRecordParams = {diff --git a/packages/pieces/community/odoo/src/i18n/translation.json b/packages/pieces/community/odoo/src/i18n/translation.jsonindex e59e0d7fc0e..fa8bbe7fd11 100644--- a/packages/pieces/community/odoo/src/i18n/translation.json+++ b/packages/pieces/community/odoo/src/i18n/translation.json@@ -4,10 +4,13 @@"Odoo Database": "Odoo Database","Odoo Username": "Odoo Username","Odoo API Key": "Odoo API Key",- "Enter the base URL": "Enter the base URL",- "Enter the database name": "Enter the database name",- "Enter the username": "Enter the username",- "Enter the API Key": "Enter the API Key",+ "Port (optional)": "Port (optional)",+ "The address of your Odoo without a port, for example https://mycompany.odoo.com. Put a port in the Port field.": "The address of your Odoo without a port, for example https://mycompany.odoo.com. Put a port in the Port field.",+ "The database name, for example mycompany": "The database name, for example mycompany",+ "The login of the Odoo user, usually an email address": "The login of the Odoo user, usually an email address",+ "The API key created under My Profile → Account Security → New API Key": "The API key created under My Profile → Account Security → New API Key",+ "Leave empty to use port 443 (the default, right for Odoo Online and most HTTPS setups). Set it only when Odoo listens on another port, for example 8069 for a self-hosted Odoo reached directly.": "Leave empty to use port 443 (the default, right for Odoo Online and most HTTPS setups). Set it only when Odoo listens on another port, for example 8069 for a self-hosted Odoo reached directly.",+ "Connect with an Odoo API key.\n\n1. In Odoo, click your avatar (top right) → **My Profile** (or **Preferences**) → **Account Security** tab.\n2. Click **New API Key**, confirm your password, give it a name and copy the key. Odoo shows it once.\n3. The **Username** is the login you sign in with (usually your email).\n4. The **Database** is shown in the URL of the database manager, or ask your Odoo admin. On Odoo Online it is usually the first part of the address (for **mycompany**.odoo.com it is `mycompany`).\n\nOd": "Connect with an Odoo API key.\n\n1. In Odoo, click your avatar (top right) → **My Profile** (or **Preferences**) → **Account Security** tab.\n2. Click **New API Key**, confirm your password, give it a name and copy the key. Odoo shows it once.\n3. The **Username** is the login you sign in with (usually your email).\n4. The **Database** is shown in the URL of the database manager, or ask your Odoo admin. On Odoo Online it is usually the first part of the address (for **mycompany**.odoo.com it is `mycompany`).\n\nOdoo Online allows the external API only on the Custom plan. API keys can expire, so create a new one if the connection stops working.","Get contacts": "Get contacts","Create contact": "Create contact","Create company": "Create company",@@ -15,6 +18,14 @@"Custom Create Record": "Custom Create Record","Custom Update Record": "Custom Update Record","Custom API Call": "Custom API Call",+ "Get Record": "Get Record",+ "Delete Record": "Delete Record",+ "Run Record Action": "Run Record Action",+ "Post Chatter Message": "Post Chatter Message",+ "Attach File to Record": "Attach File to Record",+ "Create Lead or Opportunity": "Create Lead or Opportunity",+ "Create Quotation": "Create Quotation",+ "Find Invoices": "Find Invoices","Get contacts on Odoo": "Get contacts on Odoo","Create/Update contact on Odoo": "Create/Update contact on Odoo","Create/Update company on Odoo": "Create/Update company on Odoo",@@ -22,6 +33,14 @@"Create a new record in the specified model": "Create a new record in the specified model","Update an existing record in the specified model": "Update an existing record in the specified model","Make a custom XML-RPC API call to Odoo": "Make a custom XML-RPC API call to Odoo",+ "Get one record of any Odoo model by picking it from a list.": "Get one record of any Odoo model by picking it from a list.",+ "Permanently delete a record of any Odoo model. This cannot be undone.": "Permanently delete a record of any Odoo model. This cannot be undone.",+ "Run a button action on a record, for example confirm a quotation or post an invoice.": "Run a button action on a record, for example confirm a quotation or post an invoice.",+ "Log a note or send a message in the chatter of a record.": "Log a note or send a message in the chatter of a record.",+ "Attach a file to a record, for example a signed PDF to a sales order.": "Attach a file to a record, for example a signed PDF to a sales order.",+ "Create a lead or opportunity in Odoo CRM.": "Create a lead or opportunity in Odoo CRM.",+ "Create a quotation (draft sales order) with order lines.": "Create a quotation (draft sales order) with order lines.",+ "List invoices, bills and credit notes, filtered by type, status, customer and dates.": "List invoices, bills and credit notes, filtered by type, status, customer and dates.","Type": "Type","Contact Name": "Contact Name","Contact Phone": "Contact Phone",@@ -35,18 +54,69 @@"Fields": "Fields","Offset": "Offset","Limit": "Limit",+ "Sort Order": "Sort Order","Fields and Values": "Fields and Values","Record ID": "Record ID","Method": "Method",+ "Record": "Record",+ "Record to Delete": "Record to Delete",+ "Action (method name)": "Action (method name)",+ "Extra Arguments": "Extra Arguments",+ "Message": "Message",+ "Post As": "Post As",+ "File": "File",+ "File Name": "File Name",+ "Title": "Title",+ "Customer": "Customer",+ "Email": "Email",+ "Phone": "Phone",+ "Expected Revenue": "Expected Revenue",+ "Stage": "Stage",+ "Salesperson": "Salesperson",+ "Sales Team": "Sales Team",+ "Expected Closing": "Expected Closing",+ "Notes": "Notes",+ "Order Lines": "Order Lines",+ "Customer Reference": "Customer Reference",+ "Expiration Date": "Expiration Date",+ "Status": "Status",+ "Payment Status": "Payment Status",+ "Customer / Vendor": "Customer / Vendor",+ "Number or Reference Contains": "Number or Reference Contains",+ "Invoice Date From": "Invoice Date From",+ "Invoice Date To": "Invoice Date To",+ "Due Date From": "Due Date From",+ "Due Date To": "Due Date To","Select which contact type to get": "Select which contact type to get","Would you like to search any specific name?": "Would you like to search any specific name?","Model name. e.g.: res.partner": "Model name. e.g.: res.partner","A domain is a list of criteria, each criterion being a triple of (field_name, operator, value). See https://www.odoo.com/documentation/17.0/developer/reference/backend/orm.html#reference-orm-domains for details.": "A domain is a list of criteria, each criterion being a triple of (field_name, operator, value). See https://www.odoo.com/documentation/17.0/developer/reference/backend/orm.html#reference-orm-domains for details.","Returns the requested fields of the records. When undefined, returns all fields.": "Returns the requested fields of the records. When undefined, returns all fields.",+ "Optional. Field names with asc or desc, separated by commas, for example \"create_date desc, id desc\". Leave empty for Odoo's default order.": "Optional. Field names with asc or desc, separated by commas, for example \"create_date desc, id desc\". Leave empty for Odoo's default order.","JSON object of field names and their corresponding values": "JSON object of field names and their corresponding values","ID of the record to update": "ID of the record to update","The Odoo model to interact with (e.g., res.partner, product.product)": "The Odoo model to interact with (e.g., res.partner, product.product)","The method to call on the model (e.g., search_read, create, write)": "The method to call on the model (e.g., search_read, create, write)",+ "The kind of record. Type to search, for example \"contact\" or \"sale\". Admin users see every model; other users see the common ones.": "The kind of record. Type to search, for example \"contact\" or \"sale\". Admin users see every model; other users see the common ones.",+ "The record to use. Type to search by name.": "The record to use. Type to search by name.",+ "Optional. Field names to return, for example name, email. Leave empty for all fields except files and images.": "Optional. Field names to return, for example name, email. Leave empty for all fields except files and images.",+ "The technical name of the button method. Examples: action_confirm (confirm a quotation), action_post (post an invoice), action_set_won (mark a lead won), action_archive (archive any record). Turn on developer mode in Odoo and hover a button to see its name.": "The technical name of the button method. Examples: action_confirm (confirm a quotation), action_post (post an invoice), action_set_won (mark a lead won), action_archive (archive any record). Turn on developer mode in Odoo and hover a button to see its name.",+ "Optional JSON object of named arguments, for example {\"lost_reason_id\": 3} for action_set_lost.": "Optional JSON object of named arguments, for example {\"lost_reason_id\": 3} for action_set_lost.",+ "Plain text. Odoo shows HTML tags as text when the message comes from the API.": "Plain text. Odoo shows HTML tags as text when the message comes from the API.",+ "An internal note is only visible to employees. A message is emailed to the followers of the record.": "An internal note is only visible to employees. A message is emailed to the followers of the record.",+ "Optional. For example contract.pdf. Leave empty to keep the original name.": "Optional. For example contract.pdf. Leave empty to keep the original name.",+ "For example \"Website: 20 office chairs\".": "For example \"Website: 20 office chairs\".",+ "Choose Lead only when Leads are turned on in CRM settings.": "Choose Lead only when Leads are turned on in CRM settings.",+ "Optional. An existing contact or company.": "Optional. An existing contact or company.",+ "Used when there is no existing customer.": "Used when there is no existing customer.",+ "Optional. Leave empty for the first stage.": "Optional. Leave empty for the first stage.",+ "Optional. Leave empty to assign it to the connected user.": "Optional. Leave empty to assign it to the connected user.",+ "Optional.": "Optional.",+ "The contact or company the quotation is for.": "The contact or company the quotation is for.",+ "Leave empty for all four types.": "Leave empty for all four types.",+ "Optional. Includes invoices of its contacts.": "Optional. Includes invoices of its contacts.",+ "Default 50, maximum 500.": "Default 50, maximum 500.",+ "Skip this many invoices (for paging).": "Skip this many invoices (for paging).","Contact": "Contact","Company": "Company","Read": "Read",@@ -56,5 +126,48 @@"Create": "Create","Write": "Write","Unlink": "Unlink",- "Fields get": "Fields get"+ "Fields get": "Fields get",+ "Internal note": "Internal note",+ "Message to followers": "Message to followers",+ "Opportunity": "Opportunity",+ "Lead": "Lead",+ "Customer invoice": "Customer invoice",+ "Customer credit note": "Customer credit note",+ "Vendor bill": "Vendor bill",+ "Vendor refund": "Vendor refund",+ "Draft": "Draft",+ "Posted": "Posted",+ "Cancelled": "Cancelled",+ "Not paid": "Not paid",+ "Partially paid": "Partially paid",+ "In payment": "In payment",+ "Paid": "Paid",+ "Reversed": "Reversed",+ "New Record": "New Record",+ "New or Updated Record": "New or Updated Record",+ "New Contact": "New Contact",+ "New Lead or Opportunity": "New Lead or Opportunity",+ "New Sales Order": "New Sales Order",+ "Triggers when a new record is created in any Odoo model (contacts, orders, invoices, tasks...).": "Triggers when a new record is created in any Odoo model (contacts, orders, invoices, tasks...).",+ "Triggers when a record is created or changed in any Odoo model. Odoo also counts automatic updates (computed fields, scheduled actions) as changes.": "Triggers when a record is created or changed in any Odoo model. Odoo also counts automatic updates (computed fields, scheduled actions) as changes.",+ "Triggers when a new contact (person or company) is created in Odoo.": "Triggers when a new contact (person or company) is created in Odoo.",+ "Triggers when a new lead or opportunity is created in Odoo CRM.": "Triggers when a new lead or opportunity is created in Odoo CRM.",+ "Triggers when a sales order is confirmed in Odoo, or when a new quotation is created.": "Triggers when a sales order is confirmed in Odoo, or when a new quotation is created.",+ "Filter domain": "Filter domain",+ "Contact Type": "Contact Type",+ "Fire On": "Fire On",+ "Optional. Only fire for records that match this Odoo domain, for example [[\"is_company\", \"=\", true]]. Leave empty for every new record. Archived records are included unless the domain mentions active.": "Optional. Only fire for records that match this Odoo domain, for example [[\"is_company\", \"=\", true]]. Leave empty for every new record. Archived records are included unless the domain mentions active.",+ "Optional. Only fire for created or updated records that match this Odoo domain, for example [[\"is_company\", \"=\", true]]. Leave empty for every change. Archived records are included (so archiving a record fires it) unless the domain mentions active.": "Optional. Only fire for created or updated records that match this Odoo domain, for example [[\"is_company\", \"=\", true]]. Leave empty for every change. Archived records are included (so archiving a record fires it) unless the domain mentions active.",+ "Which new contacts should start the flow.": "Which new contacts should start the flow.",+ "Leads only exist when \"Leads\" is turned on in CRM settings; otherwise every record is an opportunity. For leads, the type and team are checked while the record is new (until a record created more than 5 minutes later exists), so later changes do not fire. \"Opportunities only\" also fires when a lead is converted to an opportunity after the trigger was turned on, and checks the team on every poll, so an opportunity moved into the chosen team later fires then (once; the last 2,000 fired opportunities are remembered).": "Leads only exist when \"Leads\" is turned on in CRM settings; otherwise every record is an opportunity. For leads, the type and team are checked while the record is new (until a record created more than 5 minutes later exists), so later changes do not fire. \"Opportunities only\" also fires when a lead is converted to an opportunity after the trigger was turned on, and checks the team on every poll, so an opportunity moved into the chosen team later fires then (once; the last 2,000 fired opportunities are remembered).",+ "Optional. Only fire for this sales team.": "Optional. Only fire for this sales team.",+ "Orders confirmed after the trigger was turned on, or new quotations. Only orders confirmed with the Confirm button (action_confirm) fire; orders set to confirmed by a direct state write or an import keep their old order date and do not fire.": "Orders confirmed after the trigger was turned on, or new quotations. Only orders confirmed with the Confirm button (action_confirm) fire; orders set to confirmed by a direct state write or an import keep their old order date and do not fire.",+ "People and companies": "People and companies",+ "People only": "People only",+ "Companies only": "Companies only",+ "Leads and opportunities": "Leads and opportunities",+ "Leads only": "Leads only",+ "Opportunities only": "Opportunities only",+ "Order confirmed": "Order confirmed",+ "New quotation": "New quotation"}\ No newline at end of filediff --git a/packages/pieces/community/odoo/src/index.ts b/packages/pieces/community/odoo/src/index.tsindex 294b0c6f236..f33322504b7 100644--- a/packages/pieces/community/odoo/src/index.ts+++ b/packages/pieces/community/odoo/src/index.ts@@ -1,11 +1,11 @@-import {- createPiece,- PieceAuth,- Property,-} from '@activepieces/pieces-framework';-import Odoo from './commom/index';+import { createPiece } from '@activepieces/pieces-framework';import actions from './lib/actions';import { odooAuth } from './lib/auth';+import { newContactTrigger } from './lib/triggers/new-contact';+import { newLeadTrigger } from './lib/triggers/new-lead';+import { newOrUpdatedRecordTrigger } from './lib/triggers/new-or-updated-record';+import { newRecordTrigger } from './lib/triggers/new-record';+import { newSalesOrderTrigger } from './lib/triggers/new-sales-order';export const odoo = createPiece({displayName: 'Odoo',@@ -15,5 +15,11 @@ export const odoo = createPiece({logoUrl: 'https://cdn.activepieces.com/pieces/odoo.png',authors: ["mariomeyer","kishanprmr","abuaboud"],actions,- triggers: [],+ triggers: [+ newRecordTrigger,+ newOrUpdatedRecordTrigger,+ newContactTrigger,+ newLeadTrigger,+ newSalesOrderTrigger,+ ],});diff --git a/packages/pieces/community/odoo/src/lib/actions/attach-file.ts b/packages/pieces/community/odoo/src/lib/actions/attach-file.tsnew file mode 100644index 00000000000..690c8b8b1ef--- /dev/null+++ b/packages/pieces/community/odoo/src/lib/actions/attach-file.ts@@ -0,0 +1,47 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { odooAuth } from '../auth';+import { OdooClient } from '../common/client';+import { odooOperations } from '../common/operations';+import { odooProps } from '../common/props';+import { odooInput } from '../common/values';+import { createdAttachmentOutputSchema } from '../output-schemas';++export const attachFileAction = createAction({+ auth: odooAuth,+ name: 'attach_file',+ classification: 'WRITE',+ displayName: 'Attach File to Record',+ description: 'Attach a file to a record, for example a signed PDF to a sales order.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Uploads a file as an attachment (ir.attachment) linked to one Odoo record, shown in its chatter attachments. Not idempotent: each call adds another attachment. If read_back_error is set, the record was created but could not be read back: do not create it again; open it with Get Record using the returned id.',+ idempotent: false,+ },+ outputSchema: createdAttachmentOutputSchema,+ props: {+ model: odooProps.modelDropdown(),+ record_id: odooProps.recordDropdown(),+ file: Property.File({+ displayName: 'File',+ required: true,+ }),+ file_name: Property.ShortText({+ displayName: 'File Name',+ description: 'Optional. For example contract.pdf. Leave empty to keep the original name.',+ required: false,+ }),+ },+ async run(context) {+ const model = odooInput.toModelName(context.propsValue.model);+ const recordId = odooInput.toId({ value: context.propsValue.record_id, label: 'Record' });+ const client = OdooClient.fromAuth({ auth: context.auth.props });+ return odooOperations.attachFile({+ client,+ model,+ recordId,+ file: context.propsValue.file,+ name: odooInput.optionalText(context.propsValue.file_name),+ });+ },+});diff --git a/packages/pieces/community/odoo/src/lib/actions/create-company.ts b/packages/pieces/community/odoo/src/lib/actions/create-company.tsindex bf135ac4edb..66f38b9f111 100644--- a/packages/pieces/community/odoo/src/lib/actions/create-company.ts+++ b/packages/pieces/community/odoo/src/lib/actions/create-company.ts@@ -1,6 +1,7 @@import { createAction, Property } from "@activepieces/pieces-framework";import Odoo from "../../commom/index";import { odooAuth } from '../auth';+import { odooRpc } from '../common/client';export default createAction({name: 'create_company', // Must be a unique across the piece, this shouldn't be changed.@@ -31,7 +32,7 @@ export default createAction({async run(context) {const odoo = new Odoo({url: context.auth.props.base_url,- port: 443,+ port: odooRpc.resolvePort(context.auth.props.port),db: context.auth.props.database,username: context.auth.props.username,password: context.auth.props.api_key,diff --git a/packages/pieces/community/odoo/src/lib/actions/create-contact.ts b/packages/pieces/community/odoo/src/lib/actions/create-contact.tsindex 326932d4b69..b6676f5f2ad 100644--- a/packages/pieces/community/odoo/src/lib/actions/create-contact.ts+++ b/packages/pieces/community/odoo/src/lib/actions/create-contact.ts@@ -1,6 +1,7 @@import { createAction, Property } from "@activepieces/pieces-framework";import Odoo from "../../commom/index";import { odooAuth } from '../auth';+import { odooRpc } from '../common/client';export default createAction({name: 'create_contact', // Must be a unique across the piece, this shouldn't be changed.@@ -41,7 +42,7 @@ export default createAction({async run(context) {const odoo = new Odoo({url: context.auth.props.base_url,- port: 443,+ port: odooRpc.resolvePort(context.auth.props.port),db: context.auth.props.database,username: context.auth.props.username,password: context.auth.props.api_key,@@ -51,8 +52,8 @@ export default createAction({await odoo.connect();const c = await odoo.saveContact({name: context.propsValue['name'],- phone: context.propsValue['name'],- email: context.propsValue['name'],+ phone: context.propsValue['phone'],+ email: context.propsValue['email'],company: context.propsValue['company'],title: context.propsValue['title']});diff --git a/packages/pieces/community/odoo/src/lib/actions/create-lead.ts b/packages/pieces/community/odoo/src/lib/actions/create-lead.tsnew file mode 100644index 00000000000..193d4b16bd5--- /dev/null+++ b/packages/pieces/community/odoo/src/lib/actions/create-lead.ts@@ -0,0 +1,93 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { odooAuth } from '../auth';+import { OdooClient } from '../common/client';+import { odooOperations } from '../common/operations';+import { odooProps } from '../common/props';+import { odooDates, odooInput } from '../common/values';+import { createdLeadOutputSchema } from '../output-schemas';++export const createLeadAction = createAction({+ auth: odooAuth,+ name: 'create_lead',+ classification: 'WRITE',+ displayName: 'Create Lead or Opportunity',+ description: 'Create a lead or opportunity in Odoo CRM.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Creates one Odoo CRM record (crm.lead) as a lead or an opportunity, with optional customer, contact details, revenue, stage, salesperson and team. Needs the CRM app. Not idempotent: each call creates a new record. If read_back_error is set, the record was created but could not be read back: do not create it again; open it with Get Record using the returned id.',+ idempotent: false,+ },+ outputSchema: createdLeadOutputSchema,+ props: {+ name: Property.ShortText({+ displayName: 'Title',+ description: 'For example "Website: 20 office chairs".',+ required: true,+ }),+ lead_type: Property.StaticDropdown({+ displayName: 'Type',+ description: 'Choose Lead only when Leads are turned on in CRM settings.',+ required: false,+ defaultValue: 'opportunity',+ options: {+ options: [+ { label: 'Opportunity', value: 'opportunity' },+ { label: 'Lead', value: 'lead' },+ ],+ },+ }),+ partner_id: odooProps.fixedModelDropdown({+ model: 'res.partner',+ displayName: 'Customer',+ description: 'Optional. An existing contact or company.',+ required: false,+ }),+ contact_name: Property.ShortText({ displayName: 'Contact Name', required: false }),+ partner_name: Property.ShortText({ displayName: 'Company Name', description: 'Used when there is no existing customer.', required: false }),+ email_from: Property.ShortText({ displayName: 'Email', required: false }),+ phone: Property.ShortText({ displayName: 'Phone', required: false }),+ expected_revenue: Property.Number({ displayName: 'Expected Revenue', required: false }),+ stage_id: odooProps.fixedModelDropdown({+ model: 'crm.stage',+ displayName: 'Stage',+ description: 'Optional. Leave empty for the first stage.',+ required: false,+ }),+ user_id: odooProps.fixedModelDropdown({+ model: 'res.users',+ displayName: 'Salesperson',+ description: 'Optional. Leave empty to assign it to the connected user.',+ required: false,+ domain: [['share', '=', false]],+ }),+ team_id: odooProps.fixedModelDropdown({+ model: 'crm.team',+ displayName: 'Sales Team',+ description: 'Optional.',+ required: false,+ }),+ date_deadline: Property.DateTime({ displayName: 'Expected Closing', required: false }),+ description: Property.LongText({ displayName: 'Notes', required: false }),+ },+ async run(context) {+ const p = context.propsValue;+ const values = odooInput.definedOnly({+ name: p.name,+ type: p.lead_type === 'lead' ? 'lead' : 'opportunity',+ partner_id: odooInput.optionalId({ value: p.partner_id, label: 'Customer' }),+ contact_name: odooInput.optionalText(p.contact_name),+ partner_name: odooInput.optionalText(p.partner_name),+ email_from: odooInput.optionalText(p.email_from),+ phone: odooInput.optionalText(p.phone),+ expected_revenue: odooInput.toOptionalNumber({ value: p.expected_revenue, label: 'Expected Revenue' }),+ stage_id: odooInput.optionalId({ value: p.stage_id, label: 'Stage' }),+ user_id: odooInput.optionalId({ value: p.user_id, label: 'Salesperson' }),+ team_id: odooInput.optionalId({ value: p.team_id, label: 'Sales Team' }),+ date_deadline: odooDates.inputToOdooDate({ value: p.date_deadline, label: 'Expected Closing' }),+ description: odooInput.optionalText(p.description),+ });+ const client = OdooClient.fromAuth({ auth: context.auth.props });+ return odooOperations.createLead({ client, values });+ },+});diff --git a/packages/pieces/community/odoo/src/lib/actions/create-record.ts b/packages/pieces/community/odoo/src/lib/actions/create-record.tsindex 1359a4dd32d..3010e4d202f 100644--- a/packages/pieces/community/odoo/src/lib/actions/create-record.ts+++ b/packages/pieces/community/odoo/src/lib/actions/create-record.ts@@ -1,6 +1,8 @@import { createAction, Property } from "@activepieces/pieces-framework";import Odoo from "../../commom/index";import { odooAuth } from '../auth';+import { odooRpc } from '../common/client';+import { createRecordOutputSchema } from '../output-schemas';export default createAction({name: 'create_record',@@ -10,6 +12,7 @@ export default createAction({description: 'Create a new record in the specified model',audience: 'both',aiMetadata: { description: 'Creates a new record in any Odoo model via the XML-RPC create call, given a model name and a JSON object of field names to values, and returns the new record id. Use this generic writer when no model-specific create action fits. Not idempotent — each call inserts a new record.', idempotent: false },+ outputSchema: createRecordOutputSchema,props: {model: Property.ShortText({displayName: 'Model',@@ -30,7 +33,7 @@ export default createAction({async run(context) {const odoo = new Odoo({url: context.auth.props.base_url,- port: 443,+ port: odooRpc.resolvePort(context.auth.props.port),db: context.auth.props.database,username: context.auth.props.username,password: context.auth.props.api_key,diff --git a/packages/pieces/community/odoo/src/lib/actions/create-sales-order.ts b/packages/pieces/community/odoo/src/lib/actions/create-sales-order.tsnew file mode 100644index 00000000000..23b51772ef4--- /dev/null+++ b/packages/pieces/community/odoo/src/lib/actions/create-sales-order.ts@@ -0,0 +1,69 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { odooAuth } from '../auth';+import { OdooClient } from '../common/client';+import { odooOperations } from '../common/operations';+import { odooProps } from '../common/props';+import { odooDates, odooInput } from '../common/values';+import { createdSaleOrderOutputSchema } from '../output-schemas';++export const createSalesOrderAction = createAction({+ auth: odooAuth,+ name: 'create_sales_order',+ classification: 'WRITE',+ displayName: 'Create Quotation',+ description: 'Create a quotation (draft sales order) with order lines.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Creates a draft Odoo quotation (sale.order) for a customer with one or more product lines; confirm it afterwards with action_confirm. Needs the Sales app. Not idempotent: each call creates a new quotation. If read_back_error is set, the record was created but could not be read back: do not create it again; open it with Get Record using the returned id.',+ idempotent: false,+ },+ outputSchema: createdSaleOrderOutputSchema,+ props: {+ partner_id: odooProps.fixedModelDropdown({+ model: 'res.partner',+ displayName: 'Customer',+ description: 'The contact or company the quotation is for.',+ required: true,+ }),+ lines: Property.Array({+ displayName: 'Order Lines',+ required: true,+ properties: {+ product: Property.ShortText({+ displayName: 'Product',+ description: 'Product variant ID, or its Internal Reference (for example FURN_7800).',+ required: true,+ }),+ quantity: Property.Number({ displayName: 'Quantity', description: 'Defaults to 1.', required: false }),+ price_unit: Property.Number({ displayName: 'Unit Price', description: 'Leave empty to use the product price.', required: false }),+ description: Property.ShortText({ displayName: 'Description', description: 'Leave empty to use the product name.', required: false }),+ },+ }),+ client_order_ref: Property.ShortText({ displayName: 'Customer Reference', required: false }),+ validity_date: Property.DateTime({ displayName: 'Expiration Date', required: false }),+ },+ async run(context) {+ const p = context.propsValue;+ const partnerId = odooInput.toId({ value: p.partner_id, label: 'Customer' });+ const lines = odooInput.parseArray({ value: p.lines, label: 'Order Lines' }).map((line, index) => {+ if (!odooInput.isRecord(line)) throw new Error(`Order Lines: line ${index + 1} must be an object with a product, for example {"product": "FURN_7800", "quantity": 2}.`);+ return {+ product: line['product'],+ quantity: line['quantity'],+ price_unit: line['price_unit'],+ description: line['description'],+ };+ });+ const client = OdooClient.fromAuth({ auth: context.auth.props });+ return odooOperations.createSaleOrder({+ client,+ partnerId,+ lines,+ values: odooInput.definedOnly({+ client_order_ref: odooInput.optionalText(p.client_order_ref),+ validity_date: odooDates.inputToOdooDate({ value: p.validity_date, label: 'Expiration Date' }),+ }),+ });+ },+});diff --git a/packages/pieces/community/odoo/src/lib/actions/custom-api-call.ts b/packages/pieces/community/odoo/src/lib/actions/custom-api-call.tsindex 67af1cb8169..6ebfb863f4c 100644--- a/packages/pieces/community/odoo/src/lib/actions/custom-api-call.ts+++ b/packages/pieces/community/odoo/src/lib/actions/custom-api-call.ts@@ -4,6 +4,7 @@ import {} from '@activepieces/pieces-framework';import { odooAuth } from '../auth';import Odoo from '../../commom/index';+import { odooRpc } from '../common/client';export const customOdooApiCall = createAction({name: 'custom_odoo_api_call',@@ -179,7 +180,7 @@ export const customOdooApiCall = createAction({const odoo = new Odoo({url: base_url,- port: 443,+ port: odooRpc.resolvePort(auth.props.port),db: database,username: username,password: api_key,@@ -249,7 +250,7 @@ export const customOdooApiCall = createAction({// For write, the structure is [[ids], values]const { record_id, values } = method_params;- params = [record_id !== undefined ? [[parseInt(record_id, 10)]] : [], values ? { values } : {}];+ params = [[[parseInt(record_id, 10)], values || {}]];break;}case 'unlink': {@@ -258,6 +259,12 @@ export const customOdooApiCall = createAction({params = [record_id !== undefined ? [[parseInt(record_id, 10)]] : []];break;}+ case 'fields_get': {+ const { attributes } = method_params;++ params = [[], attributes && attributes.length > 0 ? { attributes } : {}];+ break;+ }}const result = await odoo.execute_kw({diff --git a/packages/pieces/community/odoo/src/lib/actions/delete-record.ts b/packages/pieces/community/odoo/src/lib/actions/delete-record.tsnew file mode 100644index 00000000000..b4fc35bbb9b--- /dev/null+++ b/packages/pieces/community/odoo/src/lib/actions/delete-record.ts@@ -0,0 +1,33 @@+import { createAction } from '@activepieces/pieces-framework';+import { odooAuth } from '../auth';+import { OdooClient } from '../common/client';+import { odooOperations } from '../common/operations';+import { odooProps } from '../common/props';+import { odooInput } from '../common/values';+import { deleteRecordOutputSchema } from '../output-schemas';++export const deleteRecordAction = createAction({+ auth: odooAuth,+ name: 'delete_record',+ classification: 'DESTRUCTIVE',+ displayName: 'Delete Record',+ description: 'Permanently delete a record of any Odoo model. This cannot be undone.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Permanently deletes one Odoo record of any model (unlink). Odoo may refuse when other records depend on it; archiving via Run Record Action with action_archive is the recoverable alternative. Not idempotent: a second call fails because the record is gone.',+ idempotent: false,+ },+ outputSchema: deleteRecordOutputSchema,+ props: {+ model: odooProps.modelDropdown(),+ record_id: odooProps.recordDropdown({ displayName: 'Record to Delete' }),+ },+ async run(context) {+ const model = odooInput.toModelName(context.propsValue.model);+ const id = odooInput.toId({ value: context.propsValue.record_id, label: 'Record' });+ const client = OdooClient.fromAuth({ auth: context.auth.props });+ const result = await odooOperations.deleteRecords({ client, model, ids: [id] });+ return { success: result.success, model, deleted_id: id };+ },+});diff --git a/packages/pieces/community/odoo/src/lib/actions/find-invoices.ts b/packages/pieces/community/odoo/src/lib/actions/find-invoices.tsnew file mode 100644index 00000000000..8e61091c65e--- /dev/null+++ b/packages/pieces/community/odoo/src/lib/actions/find-invoices.ts@@ -0,0 +1,94 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { odooAuth } from '../auth';+import { OdooClient } from '../common/client';+import { odooOperations } from '../common/operations';+import { odooProps } from '../common/props';+import { odooInput } from '../common/values';+import { findInvoicesOutputSchema } from '../output-schemas';++export const findInvoicesAction = createAction({+ auth: odooAuth,+ name: 'find_invoices',+ classification: 'SEARCH',+ displayName: 'Find Invoices',+ description: 'List invoices, bills and credit notes, filtered by type, status, customer and dates.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Searches Odoo invoices, vendor bills and credit notes (account.move) by type, status, payment status, partner (including its contacts), number and invoice/due date ranges, newest first with offset paging. Needs Invoicing. Read-only and idempotent.',+ idempotent: true,+ },+ outputSchema: findInvoicesOutputSchema,+ props: {+ move_types: Property.StaticMultiSelectDropdown({+ displayName: 'Type',+ description: 'Leave empty for all four types.',+ required: false,+ options: {+ options: [+ { label: 'Customer invoice', value: 'out_invoice' },+ { label: 'Customer credit note', value: 'out_refund' },+ { label: 'Vendor bill', value: 'in_invoice' },+ { label: 'Vendor refund', value: 'in_refund' },+ ],+ },+ }),+ state: Property.StaticDropdown({+ displayName: 'Status',+ required: false,+ options: {+ options: [+ { label: 'Draft', value: 'draft' },+ { label: 'Posted', value: 'posted' },+ { label: 'Cancelled', value: 'cancel' },+ ],+ },+ }),+ payment_states: Property.StaticMultiSelectDropdown({+ displayName: 'Payment Status',+ required: false,+ options: {+ options: [+ { label: 'Not paid', value: 'not_paid' },+ { label: 'Partially paid', value: 'partial' },+ { label: 'In payment', value: 'in_payment' },+ { label: 'Paid', value: 'paid' },+ { label: 'Reversed', value: 'reversed' },+ ],+ },+ }),+ partner_id: odooProps.fixedModelDropdown({+ model: 'res.partner',+ displayName: 'Customer / Vendor',+ description: 'Optional. Includes invoices of its contacts.',+ required: false,+ }),+ number: Property.ShortText({ displayName: 'Number or Reference Contains', required: false }),+ invoice_date_from: Property.DateTime({ displayName: 'Invoice Date From', required: false }),+ invoice_date_to: Property.DateTime({ displayName: 'Invoice Date To', required: false }),+ due_date_from: Property.DateTime({ displayName: 'Due Date From', required: false }),+ due_date_to: Property.DateTime({ displayName: 'Due Date To', required: false }),+ limit: Property.Number({ displayName: 'Limit', description: 'Default 50, maximum 500.', required: false }),+ offset: Property.Number({ displayName: 'Offset', description: 'Skip this many invoices (for paging).', required: false }),+ },+ async run(context) {+ const p = context.propsValue;+ const client = OdooClient.fromAuth({ auth: context.auth.props });+ return odooOperations.findInvoices({+ client,+ filters: {+ move_types: odooInput.toStringList(p.move_types),+ state: odooInput.optionalText(p.state),+ payment_states: odooInput.toStringList(p.payment_states),+ partner_id: odooInput.optionalId({ value: p.partner_id, label: 'Customer / Vendor' }),+ number: p.number,+ invoice_date_from: p.invoice_date_from,+ invoice_date_to: p.invoice_date_to,+ due_date_from: p.due_date_from,+ due_date_to: p.due_date_to,+ },+ limit: odooInput.clampLimit({ value: p.limit, fallback: 50, max: 500 }),+ offset: odooInput.toOffset(p.offset),+ });+ },+});diff --git a/packages/pieces/community/odoo/src/lib/actions/get-contacts.ts b/packages/pieces/community/odoo/src/lib/actions/get-contacts.tsindex 60c9e4b4a12..7da3bf51e4d 100644--- a/packages/pieces/community/odoo/src/lib/actions/get-contacts.ts+++ b/packages/pieces/community/odoo/src/lib/actions/get-contacts.ts@@ -1,6 +1,7 @@import { createAction, Property } from "@activepieces/pieces-framework";import Odoo from "../../commom/index";import { odooAuth } from '../auth';+import { odooRpc } from '../common/client';export default createAction({name: 'get_contacts', // Must be a unique across the piece, this shouldn't be changed.@@ -38,7 +39,7 @@ export default createAction({async run(context) {const odoo = new Odoo({url: context.auth.props.base_url,- port: 443,+ port: odooRpc.resolvePort(context.auth.props.port),db: context.auth.props.database,username: context.auth.props.username,password: context.auth.props.api_key,diff --git a/packages/pieces/community/odoo/src/lib/actions/get-record.ts b/packages/pieces/community/odoo/src/lib/actions/get-record.tsnew file mode 100644index 00000000000..0b06cfd9dbe--- /dev/null+++ b/packages/pieces/community/odoo/src/lib/actions/get-record.ts@@ -0,0 +1,37 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { odooAuth } from '../auth';+import { OdooClient } from '../common/client';+import { odooOperations } from '../common/operations';+import { odooProps } from '../common/props';+import { odooInput } from '../common/values';+import { getRecordOutputSchema } from '../output-schemas';++export const getRecordAction = createAction({+ auth: odooAuth,+ name: 'get_record',+ classification: 'READ',+ displayName: 'Get Record',+ description: 'Get one record of any Odoo model by picking it from a list.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Reads one Odoo record of any model by ID and returns its fields, with many2one values split into an ID and a name. Use when the record is already known; to find records by criteria use a search action. Read-only and idempotent.',+ idempotent: true,+ },+ outputSchema: getRecordOutputSchema,+ props: {+ model: odooProps.modelDropdown(),+ record_id: odooProps.recordDropdown(),+ fields: Property.Array({+ displayName: 'Fields',+ description: 'Optional. Field names to return, for example name, email. Leave empty for all fields except files and images.',+ required: false,+ }),+ },+ async run(context) {+ const model = odooInput.toModelName(context.propsValue.model);+ const id = odooInput.toId({ value: context.propsValue.record_id, label: 'Record' });+ const client = OdooClient.fromAuth({ auth: context.auth.props });+ return odooOperations.getRecord({ client, model, id, fields: odooInput.toStringList(context.propsValue.fields) });+ },+});diff --git a/packages/pieces/community/odoo/src/lib/actions/get-records.ts b/packages/pieces/community/odoo/src/lib/actions/get-records.tsindex 54b558a622e..123805d0cec 100644--- a/packages/pieces/community/odoo/src/lib/actions/get-records.ts+++ b/packages/pieces/community/odoo/src/lib/actions/get-records.ts@@ -1,6 +1,7 @@import { createAction, Property } from "@activepieces/pieces-framework";import Odoo from "../../commom/index";import { odooAuth } from '../auth';+import { odooRpc } from '../common/client';import * as z from 'zod/mini'import { propsValidation } from '@activepieces/pieces-common';@@ -40,7 +41,12 @@ export default createAction({limit: Property.Number({displayName: 'Limit',required: false,- })+ }),+ order: Property.ShortText({+ displayName: 'Sort Order',+ description: 'Optional. Field names with asc or desc, separated by commas, for example "create_date desc, id desc". Leave empty for Odoo\'s default order.',+ required: false,+ }),},async run(context) {await propsValidation.validateZod(context.propsValue, {@@ -49,7 +55,7 @@ export default createAction({const odoo = new Odoo({url: context.auth.props.base_url,- port: 443,+ port: odooRpc.resolvePort(context.auth.props.port),db: context.auth.props.database,username: context.auth.props.username,password: context.auth.props.api_key,@@ -60,7 +66,7 @@ export default createAction({const domainArray = context.propsValue.domain? (context.propsValue.domain as unknown as any[]): [];- return await odoo.getRecords({model: context.propsValue.model, domain: domainArray, fields: context.propsValue.fields, offset: context.propsValue.offset, limit: context.propsValue.limit})+ return await odoo.getRecords({model: context.propsValue.model, domain: domainArray, fields: context.propsValue.fields, offset: context.propsValue.offset, limit: context.propsValue.limit, order: context.propsValue.order || undefined})} catch (err) {return err}diff --git a/packages/pieces/community/odoo/src/lib/actions/index.ts b/packages/pieces/community/odoo/src/lib/actions/index.tsindex 35204cb9dc7..34cdf91b1bd 100644--- a/packages/pieces/community/odoo/src/lib/actions/index.ts+++ b/packages/pieces/community/odoo/src/lib/actions/index.ts@@ -5,6 +5,14 @@ import getRecords from './get-records';import createRecord from './create-record';import updateRecord from './update-record';import customOdooApiCall from './custom-api-call';+import { getRecordAction } from './get-record';+import { deleteRecordAction } from './delete-record';+import { runRecordActionAction } from './run-record-action';+import { postChatterMessageAction } from './post-chatter-message';+import { attachFileAction } from './attach-file';+import { createLeadAction } from './create-lead';+import { createSalesOrderAction } from './create-sales-order';+import { findInvoicesAction } from './find-invoices';export default [getContacts,@@ -14,4 +22,12 @@ export default [createRecord,updateRecord,customOdooApiCall,+ getRecordAction,+ deleteRecordAction,+ runRecordActionAction,+ postChatterMessageAction,+ attachFileAction,+ createLeadAction,+ createSalesOrderAction,+ findInvoicesAction,];diff --git a/packages/pieces/community/odoo/src/lib/actions/post-chatter-message.ts b/packages/pieces/community/odoo/src/lib/actions/post-chatter-message.tsnew file mode 100644index 00000000000..2c2ddaaafc0--- /dev/null+++ b/packages/pieces/community/odoo/src/lib/actions/post-chatter-message.ts@@ -0,0 +1,58 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { odooAuth } from '../auth';+import { OdooClient } from '../common/client';+import { odooOperations } from '../common/operations';+import { odooProps } from '../common/props';+import { odooInput } from '../common/values';+import { postMessageOutputSchema } from '../output-schemas';++export const postChatterMessageAction = createAction({+ auth: odooAuth,+ name: 'post_chatter_message',+ classification: 'WRITE',+ displayName: 'Post Chatter Message',+ description: 'Log a note or send a message in the chatter of a record.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Posts in the chatter of one Odoo record: an internal note (no email) or a message sent to followers. Works on models with a chatter (contacts, leads, orders, invoices, tasks). Not idempotent: each call posts another message.',+ idempotent: false,+ },+ outputSchema: postMessageOutputSchema,+ props: {+ model: odooProps.modelDropdown(),+ record_id: odooProps.recordDropdown(),+ body: Property.LongText({+ displayName: 'Message',+ description: 'Plain text. Odoo shows HTML tags as text when the message comes from the API.',+ required: true,+ }),+ kind: Property.StaticDropdown({+ displayName: 'Post As',+ description: 'An internal note is only visible to employees. A message is emailed to the followers of the record.',+ required: true,+ defaultValue: 'note',+ options: {+ options: [+ { label: 'Internal note', value: 'note' },+ { label: 'Message to followers', value: 'message' },+ ],+ },+ }),+ },+ async run(context) {+ const model = odooInput.toModelName(context.propsValue.model);+ const recordId = odooInput.toId({ value: context.propsValue.record_id, label: 'Record' });+ const body = odooInput.optionalText(context.propsValue.body);+ if (!body) throw new Error('Message cannot be empty.');+ const client = OdooClient.fromAuth({ auth: context.auth.props });+ return odooOperations.postMessage({+ client,+ model,+ recordId,+ body,+ kind: context.propsValue.kind === 'message' ? 'message' : 'note',+ partnerIds: [],+ });+ },+});diff --git a/packages/pieces/community/odoo/src/lib/actions/run-record-action.ts b/packages/pieces/community/odoo/src/lib/actions/run-record-action.tsnew file mode 100644index 00000000000..6ffb365e78b--- /dev/null+++ b/packages/pieces/community/odoo/src/lib/actions/run-record-action.ts@@ -0,0 +1,47 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { odooAuth } from '../auth';+import { OdooClient } from '../common/client';+import { odooOperations } from '../common/operations';+import { odooProps } from '../common/props';+import { odooInput } from '../common/values';+import { runMethodOutputSchema } from '../output-schemas';++export const runRecordActionAction = createAction({+ auth: odooAuth,+ name: 'run_record_action',+ classification: 'WRITE',+ displayName: 'Run Record Action',+ description: 'Run a button action on a record, for example confirm a quotation or post an invoice.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Calls a public business method on one Odoo record (for example action_confirm on sale.order, action_post on account.move, action_set_won on crm.lead, action_archive). Methods that return nothing are reported as success. unlink, write, update, create, name_create, load, web_save, copy, browse, sudo, with_user, with_context, with_env and private (_) methods are refused; use Delete Record, Custom Update Record, Custom Create Record or Get Record instead. This list steers you to the right action; it is not a security boundary, and Odoo access rights of the connected user still decide what the call may do. Not idempotent: most actions fail or repeat their effect when run twice.',+ idempotent: false,+ },+ outputSchema: runMethodOutputSchema,+ props: {+ model: odooProps.modelDropdown(),+ record_id: odooProps.recordDropdown(),+ method: Property.ShortText({+ displayName: 'Action (method name)',+ description:+ 'The technical name of the button method. Examples: action_confirm (confirm a quotation), action_post (post an invoice), action_set_won (mark a lead won), action_archive (archive any record). Turn on developer mode in Odoo and hover a button to see its name.',+ required: true,+ }),+ kwargs: Property.Json({+ displayName: 'Extra Arguments',+ description: 'Optional JSON object of named arguments, for example {"lost_reason_id": 3} for action_set_lost.',+ required: false,+ }),+ },+ async run(context) {+ const model = odooInput.toModelName(context.propsValue.model);+ const id = odooInput.toId({ value: context.propsValue.record_id, label: 'Record' });+ const method = odooInput.toMethodName({ value: context.propsValue.method, actions: HUMAN_ACTIONS });+ const kwargs = odooInput.parseObject({ value: context.propsValue.kwargs, label: 'Extra Arguments', allowEmpty: true });+ const client = OdooClient.fromAuth({ auth: context.auth.props });+ return odooOperations.runMethod({ client, model, method, ids: [id], args: [], kwargs });+ },+});++const HUMAN_ACTIONS = { delete: 'Delete Record', update: 'Custom Update Record', create: 'Custom Create Record', read: 'Get Record' };diff --git a/packages/pieces/community/odoo/src/lib/actions/update-record.ts b/packages/pieces/community/odoo/src/lib/actions/update-record.tsindex b98ed69ab99..fc6c1fb83a3 100644--- a/packages/pieces/community/odoo/src/lib/actions/update-record.ts+++ b/packages/pieces/community/odoo/src/lib/actions/update-record.ts@@ -1,6 +1,8 @@import { createAction, Property } from "@activepieces/pieces-framework";import Odoo from "../../commom/index";import { odooAuth } from '../auth';+import { odooRpc } from '../common/client';+import { updateRecordOutputSchema } from '../output-schemas';export default createAction({name: 'update_record',@@ -10,6 +12,7 @@ export default createAction({description: 'Update an existing record in the specified model',audience: 'both',aiMetadata: { description: 'Overwrites fields on an existing Odoo record via the XML-RPC write call, given a model name, the target record id, and a JSON object of field names to new values. Requires a known record id (look it up first if needed). Idempotent — writing the same fields to the same id repeatedly leaves the record in the same state.', idempotent: true },+ outputSchema: updateRecordOutputSchema,props: {model: Property.ShortText({displayName: 'Model',@@ -34,7 +37,7 @@ export default createAction({async run(context) {const odoo = new Odoo({url: context.auth.props.base_url,- port: 443,+ port: odooRpc.resolvePort(context.auth.props.port),db: context.auth.props.database,username: context.auth.props.username,password: context.auth.props.api_key,diff --git a/packages/pieces/community/odoo/src/lib/auth.ts b/packages/pieces/community/odoo/src/lib/auth.tsindex 3393d7593c5..4d7033c4e67 100644--- a/packages/pieces/community/odoo/src/lib/auth.ts+++ b/packages/pieces/community/odoo/src/lib/auth.ts@@ -1,52 +1,75 @@import { PieceAuth, Property } from '@activepieces/pieces-framework';-import Odoo from '../commom/index';+import { OdooClient, OdooRequestError } from './common/client';++function urlPort(value: unknown): string | null {+ const text = String(value ?? '').trim();+ const authority = text.replace(/^[a-z][a-z0-9+.-]*:(?!\d+(?:[\\/?#]|$))[\\/]*/i, '').split(/[\\/?#]/)[0];+ const host = authority.slice(authority.lastIndexOf('@') + 1);+ const port = /^(?:\[[^\]]*\]|[^:]*):(\d*)$/.exec(host)?.[1] ?? '';+ return port === '' ? null : port;+}export const odooAuth = PieceAuth.CustomAuth({+ description: `Connect with an Odoo API key.++1. In Odoo, click your avatar (top right) → **My Profile** (or **Preferences**) → **Account Security** tab.+2. Click **New API Key**, confirm your password, give it a name and copy the key. Odoo shows it once.+3. The **Username** is the login you sign in with (usually your email).+4. The **Database** is shown in the URL of the database manager, or ask your Odoo admin. On Odoo Online it is usually the first part of the address (for **mycompany**.odoo.com it is \`mycompany\`).++Odoo Online allows the external API only on the Custom plan. API keys can expire, so create a new one if the connection stops working.`,props: {base_url: Property.ShortText({displayName: 'Odoo URL',- description: 'Enter the base URL',+ description: 'The address of your Odoo without a port, for example https://mycompany.odoo.com. Put a port in the Port field.',required: true,}),database: Property.ShortText({displayName: 'Odoo Database',- description: 'Enter the database name',+ description: 'The database name, for example mycompany',required: true,}),username: Property.ShortText({displayName: 'Odoo Username',- description: 'Enter the username',+ description: 'The login of the Odoo user, usually an email address',required: true,}),api_key: PieceAuth.SecretText({displayName: 'Odoo API Key',- description: 'Enter the API Key',+ description: 'The API key created under My Profile → Account Security → New API Key',required: true,}),+ port: Property.Number({+ displayName: 'Port (optional)',+ description:+ 'Leave empty to use port 443 (the default, right for Odoo Online and most HTTPS setups). Set it only when Odoo listens on another port, for example 8069 for a self-hosted Odoo reached directly.',+ required: false,+ }),},- // Optional Validationvalidate: async ({ auth }) => {- const { base_url, database, username, api_key } = auth;-- const odoo = new Odoo({- url: base_url,- port: 443,- db: database,- username: username,- password: api_key,- });-- try {- await odoo.connect();-+ const port = urlPort(auth.base_url);+ if (port !== null) {return {- valid: true,+ valid: false,+ error: `Remove ":${port}" from the URL and enter ${port} in the Port field instead (a port in the URL is ignored).`,};- } catch (err) {+ }+ let client: OdooClient;+ try {+ client = OdooClient.fromAuth({ auth });+ } catch (error) {+ return { valid: false, error: error instanceof Error ? error.message : String(error) };+ }+ try {+ await client.authenticate();+ return { valid: true };+ } catch (error) {+ if (error instanceof OdooRequestError && error.message.startsWith('Odoo rejected the login')) {+ return { valid: false, error: 'Invalid credentials. Please check the database, username and API key.' };+ }return {valid: false,- error:- 'Connection failed. Please check your credentials and try again.',+ error: `Connection failed. Please check the URL, port and credentials and try again. (${error instanceof Error ? error.message : String(error)})`,};}},diff --git a/packages/pieces/community/odoo/src/lib/common/app-fields.ts b/packages/pieces/community/odoo/src/lib/common/app-fields.tsnew file mode 100644index 00000000000..70feb0c1680--- /dev/null+++ b/packages/pieces/community/odoo/src/lib/common/app-fields.ts@@ -0,0 +1,106 @@+const partner = {+ model: 'res.partner',+ fields: [+ 'id', 'display_name', 'name', 'is_company', 'parent_id', 'email', 'phone', 'mobile', 'website', 'function',+ 'ref', 'vat', 'street', 'street2', 'city', 'zip', 'state_id', 'country_id', 'company_name', 'lang',+ 'active', 'create_date', 'write_date',+ ],+ manyToOne: ['parent_id', 'state_id', 'country_id'],+};++const lead = {+ model: 'crm.lead',+ fields: [+ 'id', 'name', 'type', 'active', 'stage_id', 'probability', 'expected_revenue', 'partner_id', 'contact_name',+ 'partner_name', 'email_from', 'phone', 'user_id', 'team_id', 'tag_ids', 'priority', 'date_deadline',+ 'lost_reason_id', 'won_status', 'create_date', 'write_date',+ ],+ manyToOne: ['stage_id', 'partner_id', 'user_id', 'team_id', 'lost_reason_id'],+};++const stage = {+ model: 'crm.stage',+ fields: ['id', 'name', 'sequence', 'is_won', 'fold', 'team_id', 'team_ids'],+ manyToOne: ['team_id'],+};++const saleOrder = {+ model: 'sale.order',+ fields: [+ 'id', 'name', 'state', 'partner_id', 'date_order', 'validity_date', 'client_order_ref', 'amount_untaxed',+ 'amount_tax', 'amount_total', 'currency_id', 'user_id', 'invoice_status', 'create_date', 'write_date',+ ],+ manyToOne: ['partner_id', 'currency_id', 'user_id'],+};++const invoice = {+ model: 'account.move',+ fields: [+ 'id', 'name', 'move_type', 'state', 'payment_state', 'partner_id', 'invoice_date', 'invoice_date_due', 'ref',+ 'payment_reference', 'invoice_origin', 'amount_untaxed', 'amount_tax', 'amount_total', 'amount_residual',+ 'currency_id', 'create_date', 'write_date',+ ],+ manyToOne: ['partner_id', 'currency_id'],+};++const product = {+ model: 'product.product',+ fields: [+ 'id', 'display_name', 'name', 'default_code', 'barcode', 'lst_price', 'standard_price', 'type', 'detailed_type',+ 'is_storable', 'sale_ok', 'purchase_ok', 'uom_id', 'categ_id', 'product_tmpl_id', 'active',+ ],+ manyToOne: ['uom_id', 'categ_id', 'product_tmpl_id'],+};++const project = {+ model: 'project.project',+ fields: ['id', 'name', 'partner_id', 'user_id', 'date_start', 'date', 'task_count', 'active', 'create_date'],+ manyToOne: ['partner_id', 'user_id'],+};++const task = {+ model: 'project.task',+ fields: [+ 'id', 'name', 'project_id', 'stage_id', 'user_ids', 'date_deadline', 'priority', 'state', 'kanban_state',+ 'tag_ids', 'parent_id', 'partner_id', 'create_date', 'write_date',+ ],+ manyToOne: ['project_id', 'stage_id', 'parent_id', 'partner_id'],+};++const user = {+ model: 'res.users',+ fields: ['id', 'name', 'login', 'email', 'partner_id', 'active'],+ manyToOne: ['partner_id'],+};++const attachment = {+ model: 'ir.attachment',+ fields: ['id', 'name', 'mimetype', 'file_size', 'res_model', 'res_id', 'type', 'url', 'create_date'],+ manyToOne: [],+};++const appProbes: { key: string; label: string; model: string }[] = [+ { key: 'has_contacts', label: 'Contacts', model: 'res.partner' },+ { key: 'has_crm', label: 'CRM', model: 'crm.lead' },+ { key: 'has_sales', label: 'Sales', model: 'sale.order' },+ { key: 'has_invoicing', label: 'Invoicing', model: 'account.move' },+ { key: 'has_products', label: 'Products', model: 'product.product' },+ { key: 'has_project', label: 'Project', model: 'project.task' },+ { key: 'has_inventory', label: 'Inventory', model: 'stock.picking' },+];++export const odooApps = {+ partner,+ lead,+ stage,+ saleOrder,+ invoice,+ product,+ project,+ task,+ user,+ attachment,+ appProbes,+};++export type OdooAppSpec = { model: string; fields: string[]; manyToOne: string[] };diff --git a/packages/pieces/community/odoo/src/lib/common/client.ts b/packages/pieces/community/odoo/src/lib/common/client.tsnew file mode 100644index 00000000000..04eb74f09a0--- /dev/null+++ b/packages/pieces/community/odoo/src/lib/common/client.ts@@ -0,0 +1,294 @@+import { Client, createClient, createSecureClient } from 'xmlrpc';++function resolvePort(port: OdooAuthProps['port']): number {+ if (port === undefined || port === null || port === '') {+ return DEFAULT_ODOO_PORT;+ }+ const value = typeof port === 'number' ? port : Number(String(port).trim());+ if (!Number.isInteger(value) || value < 1 || value > 65535) {+ throw new Error(+ `Invalid Odoo port "${port}". Use a whole number between 1 and 65535, or leave it empty for 443.`,+ );+ }+ return value;+}++function resolveConnection(auth: OdooAuthProps): OdooConnection {+ const url = parseUrl(auth.base_url);+ if (url.protocol !== 'https:' && url.protocol !== 'http:') {+ throw new Error('The Odoo URL must start with https:// or http://');+ }+ if (url.username || url.password) {+ throw new Error('The Odoo URL must not contain a user name or password.');+ }+ return {+ host: url.hostname,+ port: resolvePort(auth.port),+ secure: url.protocol === 'https:',+ db: auth.database,+ username: auth.username,+ password: auth.api_key,+ };+}++function faultText(error: unknown): string {+ if (typeof error === 'string') return error;+ if (error instanceof OdooRequestError && (typeof error.raw === 'string' || (typeof error.raw === 'object' && error.raw !== null))) {+ return faultText(error.raw);+ }+ if (error instanceof Error) {+ const fault: unknown = Reflect.get(error, 'faultString');+ return typeof fault === 'string' ? fault : error.message;+ }+ if (error && typeof error === 'object') {+ const fault: unknown = Reflect.get(error, 'faultString');+ if (typeof fault === 'string') return fault;+ const message: unknown = Reflect.get(error, 'message');+ if (typeof message === 'string') return message;+ }+ return String(error);+}++function isNoneReturnFault(error: unknown): boolean {+ return /cannot marshal None/i.test(faultText(error));+}++function isAccessFault(error: unknown): boolean {+ return /AccessError|access rights|not allowed to access|AccessDenied/i.test(faultText(error));+}++function isMissingModelFault(error: unknown): boolean {+ return /Object [\w.]+ doesn't exist/.test(faultText(error));+}++function describeError(error: unknown): string {+ const text = faultText(error).trim();+ const lines = text+ .split('\n')+ .map((line) => line.trim())+ .filter((line) => line.length > 0);+ const message = /Traceback \(most recent call last\)/.test(text)+ ? lines.length > 0+ ? lines[lines.length - 1]+ : text+ : lines.join(' ');+ return message.length > 600 ? `${message.slice(0, 600)}…` : message;+}++function cleanValue(value: unknown): unknown {+ if (typeof value === 'number' && !Number.isFinite(value)) {+ throw new Error(`Invalid number ${value} in an Odoo request.`);+ }+ if (Array.isArray(value)) {+ return value.map((item) => (item === undefined ? null : cleanValue(item)));+ }+ if (isPlainObject(value)) {+ return Object.fromEntries(+ Object.entries(value)+ .filter(([, item]) => item !== undefined)+ .map(([key, item]) => [key, cleanValue(item)]),+ );+ }+ return value;+}++function isPlainObject(value: unknown): value is Record<string, unknown> {+ return (+ typeof value === 'object' &&+ value !== null &&+ !Array.isArray(value) &&+ !(value instanceof Date) &&+ !Buffer.isBuffer(value)+ );+}++function parseUrl(value: unknown): URL {+ try {+ return new URL(String(value ?? '').trim());+ } catch {+ throw new Error('Invalid Odoo URL. Use the full address, for example https://mycompany.odoo.com');+ }+}++const defaultFactory: ClientFactory = ({ options, secure }) =>+ secure ? createSecureClient(options) : createClient(options);++export class OdooRequestError extends Error {+ readonly raw: unknown;++ constructor({ message, raw }: { message: string; raw: unknown }) {+ super(message);+ this.name = 'OdooRequestError';+ this.raw = raw;+ }+}++export class OdooClient {+ readonly connection: OdooConnection;+ private readonly factory: ClientFactory;+ private uid: number | null = null;+ private readonly fieldsCache = new Map<string, OdooFieldMap>();++ constructor({ connection, factory = defaultFactory }: { connection: OdooConnection; factory?: ClientFactory }) {+ this.connection = connection;+ this.factory = factory;+ }++ static fromAuth({ auth, factory }: { auth: OdooAuthProps; factory?: ClientFactory }): OdooClient {+ return new OdooClient({ connection: resolveConnection(auth), factory });+ }++ private rpc<T>({ path, method, params }: { path: string; method: string; params: unknown[] }): Promise<T> {+ const client = this.factory({+ options: { host: this.connection.host, port: this.connection.port, path },+ secure: this.connection.secure,+ });+ return new Promise<T>((resolve, reject) => {+ client.methodCall(method, params, (error, value) => {+ if (error) reject(error);+ else resolve(value);+ });+ });+ }++ async version(): Promise<Record<string, unknown>> {+ try {+ return await this.rpc<Record<string, unknown>>({ path: '/xmlrpc/2/common', method: 'version', params: [] });+ } catch (error) {+ throw new OdooRequestError({ message: `Could not reach Odoo: ${describeError(error)}`, raw: error });+ }+ }++ async authenticate(): Promise<number> {+ if (this.uid !== null) return this.uid;+ let value: unknown;+ try {+ value = await this.rpc<unknown>({+ path: '/xmlrpc/2/common',+ method: 'authenticate',+ params: [this.connection.db, this.connection.username, this.connection.password, {}],+ });+ } catch (error) {+ throw new OdooRequestError({ message: `Could not reach Odoo: ${describeError(error)}`, raw: error });+ }+ if (typeof value !== 'number' || value <= 0) {+ throw new OdooRequestError({+ message: 'Odoo rejected the login. Check the database name, the username and the API key.',+ raw: value,+ });+ }+ this.uid = value;+ return value;+ }++ async call<T = unknown>(request: OdooCallRequest): Promise<T> {+ const result = await this.callAllowNone<T>({ ...request, allowNone: false });+ if (result.returnedNone) {+ throw new OdooRequestError({ message: `Odoo ${request.model}.${request.method} returned nothing.`, raw: null });+ }+ return result.value;+ }++ async callAllowNone<T = unknown>({+ model,+ method,+ args = [],+ kwargs = {},+ allowNone = true,+ }: OdooCallRequest & { allowNone?: boolean }): Promise<OdooCallResult<T>> {+ const uid = await this.authenticate();+ const params = [+ this.connection.db,+ uid,+ this.connection.password,+ model,+ method,+ cleanValue(args),+ cleanValue(kwargs),+ ];+ try {+ const value = await this.rpc<T>({ path: '/xmlrpc/2/object', method: 'execute_kw', params });+ return { value, returnedNone: false };+ } catch (error) {+ if (allowNone && isNoneReturnFault(error)) {+ return { value: null, returnedNone: true };+ }+ throw new OdooRequestError({ message: `Odoo ${model}.${method} failed: ${describeError(error)}`, raw: error });+ }+ }++ async fieldsGet(model: string): Promise<OdooFieldMap> {+ const cached = this.fieldsCache.get(model);+ if (cached) return cached;+ const fields = await this.call<OdooFieldMap>({+ model,+ method: 'fields_get',+ args: [],+ kwargs: { attributes: ['string', 'type', 'required', 'readonly', 'relation', 'selection', 'help', 'store'] },+ });+ this.fieldsCache.set(model, fields);+ return fields;+ }++ async availableFields({ model, wanted }: { model: string; wanted: readonly string[] }): Promise<string[]> {+ const fields = await this.fieldsGet(model);+ return wanted.filter((name) => name === 'id' || name in fields);+ }+}++export const DEFAULT_ODOO_PORT = 443;++export const odooRpc = {+ resolvePort,+ resolveConnection,+ faultText,+ describeError,+ isNoneReturnFault,+ isAccessFault,+ isMissingModelFault,+ cleanValue,+};++export type OdooAuthProps = {+ base_url: string;+ database: string;+ username: string;+ api_key: string;+ port?: number | string | null;+};++export type OdooConnection = {+ host: string;+ port: number;+ secure: boolean;+ db: string;+ username: string;+ password: string;+};++export type OdooCallRequest = {+ model: string;+ method: string;+ args?: unknown[];+ kwargs?: Record<string, unknown>;+};++export type OdooCallResult<T> = { value: T; returnedNone: false } | { value: null; returnedNone: true };++export type ClientFactory = (params: {+ options: { host: string; port: number; path: string };+ secure: boolean;+}) => Client;++export type OdooFieldInfo = {+ string?: string;+ type: string;+ required?: boolean;+ readonly?: boolean;+ relation?: string;+ selection?: [string, string][] | false;+ help?: string | false;+ store?: boolean;+};++export type OdooFieldMap = Record<string, OdooFieldInfo>;diff --git a/packages/pieces/community/odoo/src/lib/common/operations.ts b/packages/pieces/community/odoo/src/lib/common/operations.tsnew file mode 100644index 00000000000..a1f1202a8a9--- /dev/null+++ b/packages/pieces/community/odoo/src/lib/common/operations.ts@@ -0,0 +1,289 @@+import { odooApps } from './app-fields';+import { OdooClient } from './client';+import { odooRecords } from './records';+import { Condition, Domain, odooDates, odooDomain, odooInput, odooOutput } from './values';++async function getRecord({ client, model, id, fields }: { client: OdooClient; model: string; id: number; fields?: string[] }) {+ const { names, map } = await odooRecords.resolveFields({ client, model, fields });+ const [record] = await odooRecords.readByIds({ client, model, ids: [id], fields: names, map });+ if (!record) throw new Error(`${model} record ${id} was not found.`);+ return { model, id, record };+}++async function deleteRecords({ client, model, ids }: { client: OdooClient; model: string; ids: number[] }) {+ await client.call<boolean>({ model, method: 'unlink', args: [ids] });+ return { success: true, model, deleted_ids: ids };+}++async function runMethod({+ client,+ model,+ method,+ ids,+ args,+ kwargs,+}: {+ client: OdooClient;+ model: string;+ method: string;+ ids: number[];+ args: unknown[];+ kwargs: Record<string, unknown>;+}) {+ const positional = ids.length > 0 ? [ids, ...args] : args;+ const result = await client.callAllowNone<unknown>({ model, method, args: positional, kwargs });+ return {+ model,+ method,+ record_ids: ids,+ returned_none: result.returnedNone,+ result: result.value,+ };+}++async function postMessage({+ client,+ model,+ recordId,+ body,+ kind,+ partnerIds,+}: {+ client: OdooClient;+ model: string;+ recordId: number;+ body: string;+ kind: 'note' | 'message';+ partnerIds: number[];+}) {+ const result = await client.call<unknown>({+ model,+ method: 'message_post',+ args: [[recordId]],+ kwargs: odooInput.definedOnly({+ body,+ message_type: 'comment',+ subtype_xmlid: kind === 'note' ? 'mail.mt_note' : 'mail.mt_comment',+ partner_ids: partnerIds.length > 0 ? partnerIds : undefined,+ }),+ });+ return { message_id: odooOutput.firstId(result), model, record_id: recordId, message_type: kind };+}++function fileToBase64(file: unknown): { base64: string; filename: string | null } {+ if (!odooInput.isRecord(file)) throw new Error('File is missing.');+ const data = file['data'];+ const filename = typeof file['filename'] === 'string' ? file['filename'] : null;+ if (Buffer.isBuffer(data)) return { base64: data.toString('base64'), filename };+ const base64 = file['base64'];+ if (typeof base64 === 'string' && base64.length > 0) return { base64, filename };+ throw new Error('File is missing or empty.');+}++async function attachFile({+ client,+ model,+ recordId,+ file,+ name,+ mimetype,+}: {+ client: OdooClient;+ model: string;+ recordId: number;+ file: unknown;+ name?: string;+ mimetype?: string;+}) {+ const { base64, filename } = fileToBase64(file);+ const fileName = name ?? filename ?? 'attachment';+ const id = await client.call<number>({+ model: odooApps.attachment.model,+ method: 'create',+ args: [odooInput.definedOnly({ name: fileName, datas: base64, res_model: model, res_id: recordId, mimetype })],+ });+ return odooRecords.readCreated({ client, model: odooApps.attachment.model, id, wanted: odooApps.attachment.fields });+}++async function resolveProducts({ client, refs }: { client: OdooClient; refs: ProductRef[] }): Promise<number[]> {+ const parsed = refs.map((ref) => parseProductRef(ref));+ const codes = Array.from(new Set(parsed.flatMap((ref) => (ref.text === null ? [] : [ref.text]))));+ const numeric = Array.from(new Set(codes.filter((code) => /^\d+$/.test(code)).map(Number)));+ const [byCode, byId] = await Promise.all([+ codes.length > 0+ ? client.call<Record<string, unknown>[]>({+ model: odooApps.product.model,+ method: 'search_read',+ args: [[['default_code', 'in', codes]]],+ kwargs: { fields: ['id', 'default_code'] },+ })+ : Promise.resolve([]),+ numeric.length > 0+ ? client.call<Record<string, unknown>[]>({ model: odooApps.product.model, method: 'search_read', args: [[['id', 'in', numeric]]], kwargs: { fields: ['id'] } })+ : Promise.resolve([]),+ ]);+ const codeMatches = new Map<string, number[]>();+ for (const row of Array.isArray(byCode) ? byCode : []) {+ const id = row['id'];+ const code = row['default_code'];+ if (typeof id === 'number' && typeof code === 'string') codeMatches.set(code, [...(codeMatches.get(code) ?? []), id]);+ }+ const knownIds = new Set((Array.isArray(byId) ? byId : []).flatMap((row) => (typeof row['id'] === 'number' ? [row['id']] : [])));+ return parsed.map((ref) => (ref.id !== null ? ref.id : pickProduct({ text: ref.text ?? '', label: ref.label, codeMatches, knownIds })));+}++function parseProductRef({ value, label }: ProductRef): { id: number | null; text: string | null; label: string } {+ if (typeof value === 'number') return { id: odooInput.toId({ value, label: `${label} ID` }), text: null, label };+ const text = String(value ?? '').trim();+ if (!text) throw new Error(`${label}: enter a product ID or internal reference.`);+ return { id: null, text, label };+}++function pickProduct({+ text,+ label,+ codeMatches,+ knownIds,+}: {+ text: string;+ label: string;+ codeMatches: Map<string, number[]>;+ knownIds: Set<number>;+}): number {+ const byCode = codeMatches.get(text) ?? [];+ if (byCode.length > 1) throw new Error(`${label}: more than one product has the internal reference "${text}". Use the product ID.`);+ const [codeMatch] = byCode;+ const idMatch = /^\d+$/.test(text) && knownIds.has(Number(text)) ? Number(text) : undefined;+ if (codeMatch !== undefined && idMatch !== undefined && codeMatch !== idMatch) {+ throw new Error(+ `${label}: "${text}" is the internal reference of product ${codeMatch} and also the ID of product ${idMatch}. Pass the ID as a number, or use the internal reference of the product you mean.`,+ );+ }+ const found = codeMatch ?? idMatch;+ if (found === undefined) throw new Error(`${label}: no product with ID or internal reference "${text}".`);+ return found;+}++function checkLineCount({ count, label }: { count: number; label: string }): void {+ if (count > MAX_LINES) throw new Error(`Add at most ${MAX_LINES} ${label} per call (got ${count}). Split the rest into another call.`);+}++async function createLead({ client, values }: { client: OdooClient; values: Record<string, unknown> }) {+ const id = await client.call<number>({ model: odooApps.lead.model, method: 'create', args: [values] });+ return odooRecords.readCreated({ client, model: odooApps.lead.model, id, wanted: odooApps.lead.fields, manyToOne: odooApps.lead.manyToOne });+}++async function createSaleOrder({+ client,+ partnerId,+ lines,+ values,+}: {+ client: OdooClient;+ partnerId: number;+ lines: SaleLineInput[];+ values: Record<string, unknown>;+}) {+ if (lines.length === 0) throw new Error('Add at least one order line.');+ checkLineCount({ count: lines.length, label: 'order lines' });+ const parsed = lines.map((line, index) => ({+ quantity: odooInput.toOptionalNumber({ value: line.quantity, label: `Line ${index + 1} quantity` }),+ price_unit: odooInput.toOptionalNumber({ value: line.price_unit, label: `Line ${index + 1} unit price` }),+ name: odooInput.optionalText(line.description),+ }));+ const productIds = await resolveProducts({ client, refs: lines.map((line, index) => ({ value: line.product, label: `Line ${index + 1} product` })) });+ const orderLines = parsed.map((line, index) => [+ 0,+ 0,+ odooInput.definedOnly({ product_id: productIds[index], product_uom_qty: line.quantity ?? 1, price_unit: line.price_unit, name: line.name }),+ ]);+ const id = await client.call<number>({+ model: odooApps.saleOrder.model,+ method: 'create',+ args: [{ ...values, partner_id: partnerId, order_line: orderLines }],+ });+ return odooRecords.readCreated({+ client,+ model: odooApps.saleOrder.model,+ id,+ wanted: odooApps.saleOrder.fields,+ manyToOne: odooApps.saleOrder.manyToOne,+ });+}++function invoiceDomain(filters: InvoiceFilters): Domain {+ const conditions: Condition[] = [];+ const moveTypes = filters.move_types.length > 0 ? filters.move_types : ['out_invoice', 'in_invoice', 'out_refund', 'in_refund'];+ conditions.push(['move_type', 'in', moveTypes]);+ if (filters.state) conditions.push(['state', '=', filters.state]);+ if (filters.payment_states.length > 0) conditions.push(['payment_state', 'in', filters.payment_states]);+ if (filters.partner_id) conditions.push(['partner_id', 'child_of', filters.partner_id]);+ const invoiceFrom = odooDates.inputToOdooDate({ value: filters.invoice_date_from, label: 'Invoice date from' });+ const invoiceTo = odooDates.inputToOdooDate({ value: filters.invoice_date_to, label: 'Invoice date to' });+ const dueFrom = odooDates.inputToOdooDate({ value: filters.due_date_from, label: 'Due date from' });+ const dueTo = odooDates.inputToOdooDate({ value: filters.due_date_to, label: 'Due date to' });+ if (invoiceFrom) conditions.push(['invoice_date', '>=', invoiceFrom]);+ if (invoiceTo) conditions.push(['invoice_date', '<=', invoiceTo]);+ if (dueFrom) conditions.push(['invoice_date_due', '>=', dueFrom]);+ if (dueTo) conditions.push(['invoice_date_due', '<=', dueTo]);+ const text = odooInput.optionalText(filters.number);+ const search: Domain = text ? odooDomain.orConditions([['name', 'ilike', text], ['ref', 'ilike', text], ['payment_reference', 'ilike', text]]) : [];+ return odooDomain.andDomains([conditions, search]);+}++async function findInvoices({+ client,+ filters,+ limit,+ offset,+}: {+ client: OdooClient;+ filters: InvoiceFilters;+ limit: number;+ offset: number;+}) {+ return odooRecords.findApp({+ client,+ model: odooApps.invoice.model,+ wanted: odooApps.invoice.fields,+ manyToOne: odooApps.invoice.manyToOne,+ domain: invoiceDomain(filters),+ limit,+ offset,+ order: 'invoice_date desc, id desc',+ });+}++const MAX_LINES = 200;++export const odooOperations = {+ getRecord,+ deleteRecords,+ runMethod,+ postMessage,+ attachFile,+ fileToBase64,+ resolveProducts,+ checkLineCount,+ MAX_LINES,+ createLead,+ createSaleOrder,+ invoiceDomain,+ findInvoices,+};++export type ProductRef = { value: unknown; label: string };++export type SaleLineInput = { product: unknown; quantity?: unknown; price_unit?: unknown; description?: unknown };++export type InvoiceFilters = {+ move_types: string[];+ state?: string;+ payment_states: string[];+ partner_id?: number;+ invoice_date_from?: unknown;+ invoice_date_to?: unknown;+ due_date_from?: unknown;+ due_date_to?: unknown;+ number?: unknown;+};diff --git a/packages/pieces/community/odoo/src/lib/common/polling.ts b/packages/pieces/community/odoo/src/lib/common/polling.tsnew file mode 100644index 00000000000..9bd2918526c--- /dev/null+++ b/packages/pieces/community/odoo/src/lib/common/polling.ts@@ -0,0 +1,443 @@+import { Store } from '@activepieces/pieces-framework';+import { OdooClient, OdooFieldMap } from './client';+import { odooRecords } from './records';+import { Domain, odooDates, odooDomain, odooInput, odooOutput } from './values';++async function newestCursor({ client, source }: { client: OdooClient; source: PollSource }): Promise<PollCursor> {+ const modelWide = { ...source, domain: [] };+ const newest = await newestInModel({ client, source });+ return newest ? cursorAt({ client, source: modelWide, date: newest.date }) : EMPTY_CURSOR;+}++async function newestInModel({ client, source }: { client: OdooClient; source: PollSource }): Promise<RowKey | null> {+ return newestRow({ client, source: { ...source, domain: [] }, domain: [[source.dateField, '!=', false]] });+}++async function cursorAt({ client, source, date }: { client: OdooClient; source: PollSource; date: string }): Promise<PollCursor> {+ const ranges = await rangesInSecond({ client, source, date });+ if (ranges === null) return { date, floor: { date, id: await maxIdInSecond({ client, source, date }) }, emitted: [] };+ const before = await newestRow({ client, source, domain: [[source.dateField, '<', date]] });+ return { date, floor: before, emitted: [{ date, ranges }] };+}++async function newestRow({ client, source, domain }: { client: OdooClient; source: PollSource; domain: Domain }): Promise<RowKey | null> {+ const rows = await client.call<Record<string, unknown>[]>({+ model: source.model,+ method: 'search_read',+ args: [odooDomain.andDomains([source.domain, domain])],+ kwargs: { fields: ['id', source.dateField], order: `${source.dateField} desc, id desc`, limit: 1, context: source.context },+ });+ const row = Array.isArray(rows) ? rows[0] : undefined;+ const [key] = row ? keyOf({ row, dateField: source.dateField }) : [];+ return key ?? null;+}++async function rangesInSecond({ client, source, date }: { client: OdooClient; source: PollSource; date: string }): Promise<IdRange[] | null> {+ let ranges: IdRange[] = [];+ let after = 0;+ for (let page = 0; page < SEED_MAX_PAGES; page++) {+ const ids = readIds(+ await client.call<number[]>({+ model: source.model,+ method: 'search',+ args: [odooDomain.andDomains([source.domain, secondDomain({ dateField: source.dateField, date }), [['id', '>', after]]])],+ kwargs: { order: 'id asc', limit: SEED_PAGE_SIZE, context: source.context },+ }),+ );+ ranges = addIds({ ranges, ids });+ if (ranges.length > MAX_WINDOW_RANGES) return null;+ if (ids.length < SEED_PAGE_SIZE) return ranges;+ after = Math.max(after, ...ids);+ }+ return null;+}++async function maxIdInSecond({ client, source, date }: { client: OdooClient; source: PollSource; date: string }): Promise<number> {+ const ids = await client.call<number[]>({+ model: source.model,+ method: 'search',+ args: [odooDomain.andDomains([source.domain, secondDomain({ dateField: source.dateField, date })])],+ kwargs: { order: 'id desc', limit: 1, context: source.context },+ });+ return readIds(ids)[0] ?? 0;+}++function secondDomain({ dateField, date }: { dateField: string; date: string }): Domain {+ return [[dateField, '>=', date], [dateField, '<', shiftSeconds({ date, seconds: 1 })]];+}++function secondOf(value: unknown): string | null {+ const epoch = odooDates.parseOdooDatetime(value);+ return epoch === null ? null : odooDates.toOdooDatetime(epoch);+}++function shiftSeconds({ date, seconds }: { date: string; seconds: number }): string {+ const epoch = odooDates.parseOdooDatetime(date);+ if (epoch === null) throw new Error(`Invalid trigger cursor date "${date}".`);+ return odooDates.toOdooDatetime(epoch + seconds * 1000);+}++function keyOf({ row, dateField }: { row: Record<string, unknown>; dateField: string }): RowKey[] {+ const id = row['id'];+ const date = secondOf(row[dateField]);+ return typeof id === 'number' && date !== null ? [{ id, date }] : [];+}++function addIds({ ranges, ids }: { ranges: IdRange[]; ids: number[] }): IdRange[] {+ const sorted = [...ranges, ...ids.map((id): IdRange => [id, id])].sort((a, b) => a[0] - b[0]);+ const merged: IdRange[] = [];+ for (const range of sorted) {+ const last = merged[merged.length - 1];+ if (last && range[0] <= last[1] + 1) merged[merged.length - 1] = [last[0], Math.max(last[1], range[1])];+ else merged.push(range);+ }+ return merged;+}++function remember({ emitted, keys }: { emitted: EmittedSecond[]; keys: RowKey[] }): EmittedSecond[] {+ const bySecond = new Map(emitted.map((second): [string, IdRange[]] => [second.date, second.ranges]));+ for (const date of new Set(keys.map((key) => key.date))) {+ const ids = keys.filter((key) => key.date === date).map((key) => key.id);+ bySecond.set(date, addIds({ ranges: bySecond.get(date) ?? [], ids }));+ }+ return [...bySecond.entries()].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)).map(([date, ranges]) => ({ date, ranges }));+}++function countRanges(emitted: EmittedSecond[]): number {+ return emitted.reduce((total, second) => total + second.ranges.length, 0);+}++function isAfter({ entry, than }: { entry: RowKey; than: RowKey }): boolean {+ return entry.date === than.date ? entry.id > than.id : entry.date > than.date;+}++function startDomain({ dateField, cursor }: { dateField: string; cursor: PollCursor }): Domain {+ const lookBack = shiftSeconds({ date: cursor.date, seconds: -LOOK_BACK_SECONDS });+ const floor = cursor.floor;+ if (floor === null || floor.date < lookBack) return [[dateField, '>=', lookBack]];+ return ['|', [dateField, '>=', shiftSeconds({ date: floor.date, seconds: 1 })], '&', [dateField, '>=', floor.date], ['id', '>', floor.id]];+}++function outsideRanges(ranges: IdRange[]): Domain {+ const singles = ranges.filter(([from, to]) => from === to).map(([from]) => from);+ const spans = ranges.filter(([from, to]) => from !== to);+ return odooDomain.andDomains([+ singles.length > 0 ? [['id', 'not in', singles]] : [],+ ...spans.map(([from, to]): Domain => ['|', ['id', '<', from], ['id', '>', to]]),+ ]);+}++function unseenDomain({ dateField, cursor }: { dateField: string; cursor: PollCursor }): Domain {+ const exclusions = cursor.emitted+ .filter((second) => second.ranges.length > 0)+ .map((second): Domain => [+ '|',+ '|',+ [dateField, '<', second.date],+ [dateField, '>=', shiftSeconds({ date: second.date, seconds: 1 })],+ ...outsideRanges(second.ranges),+ ]);+ return odooDomain.andDomains([startDomain({ dateField, cursor }), ...exclusions]);+}++function isEmitted({ row, cursor, dateField }: { row: Record<string, unknown>; cursor: PollCursor; dateField: string }): boolean {+ const [key] = keyOf({ row, dateField });+ if (key === undefined) return true;+ return cursor.emitted.some((second) => second.date === key.date && second.ranges.some(([from, to]) => key.id >= from && key.id <= to));+}++function settle(cursor: PollCursor): PollCursor {+ const lookBack = shiftSeconds({ date: cursor.date, seconds: -LOOK_BACK_SECONDS });+ const inWindow = cursor.emitted.filter((second) => second.date >= lookBack);+ let excess = Math.max(0, countRanges(inWindow) - MAX_WINDOW_RANGES);+ let dropped: RowKey | null = null;+ const kept: EmittedSecond[] = [];+ for (const second of inWindow) {+ const drop = Math.min(excess, second.ranges.length);+ if (drop > 0) dropped = { date: second.date, id: second.ranges[drop - 1][1] };+ excess -= drop;+ if (drop < second.ranges.length) kept.push({ date: second.date, ranges: second.ranges.slice(drop) });+ }+ const floors = [cursor.floor, dropped].filter((floor): floor is RowKey => floor !== null && floor.date >= lookBack);+ const floor = floors.length > 0 ? floors.reduce((a, b) => (isAfter({ entry: a, than: b }) ? a : b)) : null;+ const emitted = floor === null ? kept : aboveFloor({ emitted: kept, floor });+ return { date: cursor.date, floor, emitted };+}++function aboveFloor({ emitted, floor }: { emitted: EmittedSecond[]; floor: RowKey }): EmittedSecond[] {+ return emitted+ .filter((second) => second.date >= floor.date)+ .map((second) => (second.date === floor.date ? { date: second.date, ranges: second.ranges.filter(([, to]) => to > floor.id) } : second))+ .filter((second) => second.ranges.length > 0);+}++async function pollAfter({+ client,+ source,+ cursor,+ pageSize = PAGE_SIZE,+ maxPages = MAX_PAGES,+}: {+ client: OdooClient;+ source: PollSource;+ cursor: PollCursor;+ pageSize?: number;+ maxPages?: number;+}): Promise<{ records: Record<string, unknown>[]; cursor: PollCursor }> {+ const { names, map } = await fieldsFor({ client, source });+ const collected: Record<string, unknown>[] = [];+ let current = cursor;+ let pending: string | null = null;+ let drained = false;+ const take = (rows: Record<string, unknown>[]): number => {+ const seen = current;+ const fresh = rows.filter((row) => !isEmitted({ row, cursor: seen, dateField: source.dateField }));+ for (const row of fresh) {+ collected.push(pad({ record: odooOutput.normalizeRecord({ record: row, fields: map, requested: names }), source }));+ }+ const keys = fresh.flatMap((row) => keyOf({ row, dateField: source.dateField }));+ const newest = keys.reduce((max, key) => (key.date > max ? key.date : max), current.date);+ current = { date: newest, floor: current.floor, emitted: remember({ emitted: current.emitted, keys }) };+ return fresh.length;+ };+ for (let page = 0; page < maxPages; page++) {+ if (pending === null) {+ const list = await readUnseen({ client, source, cursor: current, names, limit: pageSize, second: null });+ const last = list.length < pageSize ? null : secondOf(list[list.length - 1][source.dateField]);+ const complete = last === null ? list : list.filter((row) => secondOf(row[source.dateField]) !== last);+ if (take(complete) === 0 && complete.length > 0) break;+ if (list.length < pageSize) {+ drained = true;+ break;+ }+ if (last === null) continue;+ pending = last;+ }+ const rows = await readUnseen({ client, source, cursor: current, names, limit: pageSize, second: pending });+ if (take(rows) === 0 && rows.length > 0) break;+ if (rows.length < pageSize) pending = null;+ }+ const newest = drained ? await newestInModel({ client, source }) : null;+ const caughtUp = newest !== null && newest.date > current.date ? { ...current, date: newest.date } : current;+ return { records: collected, cursor: settle(caughtUp) };+}++async function readUnseen({+ client,+ source,+ cursor,+ names,+ limit,+ second,+}: {+ client: OdooClient;+ source: PollSource;+ cursor: PollCursor;+ names: string[];+ limit: number;+ second: string | null;+}): Promise<Record<string, unknown>[]> {+ const rows = await client.call<Record<string, unknown>[]>({+ model: source.model,+ method: 'search_read',+ args: [+ odooDomain.andDomains([+ source.domain,+ unseenDomain({ dateField: source.dateField, cursor }),+ second === null ? [] : secondDomain({ dateField: source.dateField, date: second }),+ ]),+ ],+ kwargs: { fields: names, order: second === null ? `${source.dateField} asc, id asc` : 'id asc', limit, context: source.context },+ });+ return Array.isArray(rows) ? rows : [];+}++async function latest({ client, source, limit = 5 }: { client: OdooClient; source: PollSource; limit?: number }): Promise<Record<string, unknown>[]> {+ const { names, map } = await fieldsFor({ client, source });+ const rows = await client.call<Record<string, unknown>[]>({+ model: source.model,+ method: 'search_read',+ args: [source.domain],+ kwargs: { fields: names, order: `${source.dateField} desc, id desc`, limit, context: source.context },+ });+ const list = Array.isArray(rows) ? rows : [];+ return list.map((row) => pad({ record: odooOutput.normalizeRecord({ record: row, fields: map, requested: names }), source }));+}++function pad({ record, source }: { record: Record<string, unknown>; source: PollSource }): Record<string, unknown> {+ const known = source.knownFields ?? [];+ const manyToOne = source.manyToOne ?? [];+ const declared = [+ ...(known.includes('id') ? [] : ['id']),+ ...known.flatMap((name) => (manyToOne.includes(name) ? [name, `${name}_name`] : [name])),+ ...manyToOne.filter((name) => !known.includes(name)).map((name) => `${name}_name`),+ ];+ const placed = new Set(declared);+ return Object.fromEntries([+ ...declared.filter((key) => key !== 'id' || key in record).map((key): [string, unknown] => [key, key in record ? record[key] : null]),+ ...Object.entries(record).filter(([key]) => !placed.has(key)),+ ]);+}++async function fieldsFor({ client, source }: { client: OdooClient; source: PollSource }): Promise<{ names: string[]; map: OdooFieldMap }> {+ const resolved = source.knownFields+ ? await odooRecords.resolveKnownFields({ client, model: source.model, wanted: source.knownFields })+ : await odooRecords.resolveFields({ client, model: source.model, fields: source.fields });+ const names = resolved.names.includes(source.dateField) ? resolved.names : [...resolved.names, source.dateField];+ return { names, map: resolved.map };+}++function readCursor(value: unknown): PollCursor | null {+ if (!odooInput.isRecord(value)) return null;+ const date = value['date'];+ const emitted = value['emitted'];+ if (typeof date !== 'string' || secondOf(date) !== date || !Array.isArray(emitted)) return null;+ const floor = readFloor(value['floor']);+ if (floor === undefined) return null;+ const seconds = emitted.map(readSecond);+ if (seconds.some((second) => second === null)) return null;+ return { date, floor, emitted: seconds.filter((second): second is EmittedSecond => second !== null) };+}++function readFloor(value: unknown): RowKey | null | undefined {+ if (value === null) return null;+ if (!odooInput.isRecord(value)) return undefined;+ const date = value['date'];+ const id = value['id'];+ return typeof date === 'string' && secondOf(date) === date && typeof id === 'number' && Number.isInteger(id) ? { date, id } : undefined;+}++function readSecond(value: unknown): EmittedSecond | null {+ if (!odooInput.isRecord(value)) return null;+ const date = value['date'];+ const ranges = value['ranges'];+ if (typeof date !== 'string' || secondOf(date) !== date || !Array.isArray(ranges)) return null;+ const valid = ranges.flatMap((range): IdRange[] => {+ if (!Array.isArray(range) || range.length !== 2) return [];+ const [from, to] = range;+ return typeof from === 'number' && typeof to === 'number' && Number.isInteger(from) && Number.isInteger(to) && from <= to ? [[from, to]] : [];+ });+ return valid.length === ranges.length ? { date, ranges: valid } : null;+}++function readIds(value: unknown): number[] {+ return Array.isArray(value) ? value.filter((id): id is number => typeof id === 'number') : [];+}++async function recentIds({ client, source }: { client: OdooClient; source: PollSource }): Promise<number[]> {+ const ids = await client.call<number[]>({+ model: source.model,+ method: 'search',+ args: [source.domain],+ kwargs: { order: `${source.dateField} desc, id desc`, limit: MAX_EMITTED, context: source.context },+ });+ return readIds(ids).reverse();+}++async function seed({ client, source, store }: HookParams): Promise<void> {+ await store.put(CURSOR_KEY, await newestCursor({ client, source }));+ if (source.emitOnce) await store.put(EMITTED_KEY, await recentIds({ client, source }));+}++async function enabledAt({ store, reset = false }: { store: Store; reset?: boolean }): Promise<string> {+ const stored = await store.get<unknown>(ENABLED_AT_KEY);+ if (!reset && typeof stored === 'string' && secondOf(stored) === stored) return stored;+ const now = odooDates.toOdooDatetime(Date.now());+ await store.put(ENABLED_AT_KEY, now);+ return now;+}++async function onEnable({ client, source, store, isRepublish }: HookParams & { isRepublish?: boolean }): Promise<void> {+ if (isRepublish && readCursor(await store.get<unknown>(CURSOR_KEY))) return;+ await seed({ client, source, store });+}++async function onDisable({ store }: { store: Store }): Promise<void> {+ await store.delete(CURSOR_KEY);+ await store.delete(EMITTED_KEY);+ await store.delete(ENABLED_AT_KEY);+}++async function run({ client, source, store }: HookParams): Promise<Record<string, unknown>[]> {+ const cursor = readCursor(await store.get<unknown>(CURSOR_KEY));+ if (!cursor) {+ await seed({ client, source, store });+ return [];+ }+ const result = await pollAfter({ client, source, cursor });+ if (JSON.stringify(result.cursor) !== JSON.stringify(cursor)) await store.put(CURSOR_KEY, result.cursor);+ if (!source.emitOnce) return result.records;+ const emitted = readIds(await store.get<unknown>(EMITTED_KEY));+ const done = new Set(emitted);+ const fresh = result.records.filter((record) => {+ const id = record['id'];+ if (typeof id !== 'number') return true;+ if (done.has(id)) return false;+ done.add(id);+ return true;+ });+ const freshIds = readIds(fresh.map((record) => record['id']));+ if (freshIds.length > 0) await store.put(EMITTED_KEY, [...emitted, ...freshIds].slice(-MAX_EMITTED));+ return fresh;+}++async function test({ client, source }: { client: OdooClient; source: PollSource }): Promise<Record<string, unknown>[]> {+ return latest({ client, source });+}++function withArchived({ domain }: { domain: Domain }): Record<string, unknown> | undefined {+ const mentionsActive = domain.some((term) => Array.isArray(term) && (term[0] === 'active' || term[0].startsWith('active.')));+ return mentionsActive ? undefined : { active_test: false };+}++const CURSOR_KEY = 'odoo_poll_cursor';+const EMITTED_KEY = 'odoo_poll_emitted_ids';+const ENABLED_AT_KEY = 'odoo_poll_enabled_at';+const PAGE_SIZE = 100;+const MAX_PAGES = 5;+const MAX_EMITTED = 2000;+const LOOK_BACK_SECONDS = 300;+const MAX_WINDOW_RANGES = 5000;+const SEED_PAGE_SIZE = 5000;+const SEED_MAX_PAGES = 20;+const EMPTY_CURSOR: PollCursor = { date: '1970-01-01 00:00:00', floor: null, emitted: [] };++export const odooPolling = {+ onEnable,+ onDisable,+ run,+ test,+ enabledAt,+ withArchived,+ pollAfter,+ newestCursor,+ unseenDomain,+ CURSOR_KEY,+ EMITTED_KEY,+ ENABLED_AT_KEY,+ MAX_EMITTED,+ LOOK_BACK_SECONDS,+ MAX_WINDOW_RANGES,+ SEED_PAGE_SIZE,+};++export type IdRange = [number, number];++export type EmittedSecond = { date: string; ranges: IdRange[] };++export type RowKey = { date: string; id: number };++export type PollCursor = { date: string; floor: RowKey | null; emitted: EmittedSecond[] };++export type PollSource = {+ model: string;+ dateField: string;+ domain: Domain;+ fields?: string[];+ knownFields?: readonly string[];+ manyToOne?: readonly string[];+ context?: Record<string, unknown>;+ emitOnce?: boolean;+};++type HookParams = { client: OdooClient; source: PollSource; store: Store };diff --git a/packages/pieces/community/odoo/src/lib/common/props.ts b/packages/pieces/community/odoo/src/lib/common/props.tsnew file mode 100644index 00000000000..cf6b117099c--- /dev/null+++ b/packages/pieces/community/odoo/src/lib/common/props.ts@@ -0,0 +1,154 @@+import { DropdownState, Property } from '@activepieces/pieces-framework';+import { odooAuth } from '../auth';+import { OdooAuthProps, OdooClient, odooRpc } from './client';+import { Domain } from './values';++async function loadModels({ auth, searchValue }: { auth: OdooAuthProps; searchValue?: string }): Promise<DropdownState<string>> {+ const client = OdooClient.fromAuth({ auth });+ const query = (searchValue ?? '').trim();+ const domain: Domain = query+ ? ['&', ['transient', '=', false], '|', ['model', 'ilike', query], ['name', 'ilike', query]]+ : [['transient', '=', false]];+ try {+ const rows = await client.call<{ model: string; name: string }[]>({+ model: 'ir.model',+ method: 'search_read',+ args: [domain],+ kwargs: { fields: ['model', 'name'], order: 'name asc', limit: 200 },+ });+ return {+ disabled: false,+ options: rows.map((row) => ({ label: `${row.name} (${row.model})`, value: row.model })),+ };+ } catch (error) {+ if (!odooRpc.isAccessFault(error)) throw error;+ const filtered = COMMON_MODELS.filter(+ (m) => !query || m.model.includes(query.toLowerCase()) || m.name.toLowerCase().includes(query.toLowerCase()),+ );+ return {+ disabled: false,+ placeholder: 'Your Odoo user cannot list all models, so only common ones are shown.',+ options: filtered.map((m) => ({ label: `${m.name} (${m.model})`, value: m.model })),+ };+ }+}++async function nameSearch({+ auth,+ model,+ searchValue,+ domain = [],+}: {+ auth: OdooAuthProps;+ model: string;+ searchValue?: string;+ domain?: Domain;+}): Promise<DropdownState<number>> {+ const client = OdooClient.fromAuth({ auth });+ const rows = await client.call<[number, string][]>({+ model,+ method: 'name_search',+ args: [searchValue ?? '', domain, 'ilike', 100],+ });+ return {+ disabled: false,+ options: rows.map(([id, name]) => ({ label: `${name} (#${id})`, value: id })),+ };+}++function disabled(placeholder: string): DropdownState<never> {+ return { disabled: true, options: [], placeholder };+}++async function safely<T>({ load }: { load: () => Promise<DropdownState<T>> }): Promise<DropdownState<T>> {+ try {+ return await load();+ } catch (error) {+ return disabled(`Could not load options: ${odooRpc.describeError(error)}`);+ }+}++function modelDropdown({ displayName = 'Model', description }: { displayName?: string; description?: string } = {}) {+ return Property.Dropdown({+ auth: odooAuth,+ displayName,+ description:+ description ??+ 'The kind of record. Type to search, for example "contact" or "sale". Admin users see every model; other users see the common ones.',+ required: true,+ refreshers: [],+ refreshOnSearch: true,+ options: async ({ auth }, { searchValue }) => {+ if (!auth) return disabled('Please connect your Odoo account first');+ return safely({ load: () => loadModels({ auth: auth.props, searchValue }) });+ },+ });+}++function recordDropdown({ displayName = 'Record', description }: { displayName?: string; description?: string } = {}) {+ return Property.Dropdown({+ auth: odooAuth,+ displayName,+ description: description ?? 'The record to use. Type to search by name.',+ required: true,+ refreshers: ['model'],+ refreshOnSearch: true,+ options: async ({ auth, model }, { searchValue }) => {+ if (!auth) return disabled('Please connect your Odoo account first');+ if (typeof model !== 'string' || !model) return disabled('Please select a model first');+ return safely({ load: () => nameSearch({ auth: auth.props, model, searchValue }) });+ },+ });+}++function fixedModelDropdown({+ model,+ displayName,+ description,+ required,+ domain,+}: {+ model: string;+ displayName: string;+ description: string;+ required: boolean;+ domain?: Domain;+}) {+ return Property.Dropdown({+ auth: odooAuth,+ displayName,+ description,+ required,+ refreshers: [],+ refreshOnSearch: true,+ options: async ({ auth }, { searchValue }) => {+ if (!auth) return disabled('Please connect your Odoo account first');+ return safely({ load: () => nameSearch({ auth: auth.props, model, searchValue, domain }) });+ },+ });+}++const COMMON_MODELS: { model: string; name: string }[] = [+ { model: 'res.partner', name: 'Contact' },+ { model: 'crm.lead', name: 'Lead/Opportunity' },+ { model: 'sale.order', name: 'Sales Order' },+ { model: 'account.move', name: 'Journal Entry / Invoice' },+ { model: 'product.template', name: 'Product' },+ { model: 'product.product', name: 'Product Variant' },+ { model: 'project.project', name: 'Project' },+ { model: 'project.task', name: 'Task' },+ { model: 'res.users', name: 'User' },+ { model: 'purchase.order', name: 'Purchase Order' },+ { model: 'stock.picking', name: 'Transfer' },+ { model: 'hr.employee', name: 'Employee' },+ { model: 'calendar.event', name: 'Calendar Event' },+ { model: 'helpdesk.ticket', name: 'Helpdesk Ticket' },+];++export const odooProps = {+ modelDropdown,+ recordDropdown,+ fixedModelDropdown,+ loadModels,+ COMMON_MODELS,+};diff --git a/packages/pieces/community/odoo/src/lib/common/records.ts b/packages/pieces/community/odoo/src/lib/common/records.tsnew file mode 100644index 00000000000..7660eb331b7--- /dev/null+++ b/packages/pieces/community/odoo/src/lib/common/records.ts@@ -0,0 +1,250 @@+import { OdooClient, OdooFieldMap } from './client';+import { Domain, odooOutput } from './values';++async function resolveFields({+ client,+ model,+ fields,+}: {+ client: OdooClient;+ model: string;+ fields?: readonly string[];+}): Promise<{ names: string[]; map: OdooFieldMap }> {+ const map = await client.fieldsGet(model);+ if (fields && fields.length > 0) {+ const unknown = fields.filter((name) => name !== 'id' && !(name in map));+ if (unknown.length > 0) {+ throw new Error(+ `Unknown field(s) on ${model}: ${unknown.join(', ')}. Use Get Model Fields to see the field names of this Odoo version.`,+ );+ }+ return { names: withId(fields), map };+ }+ const names = Object.entries(map)+ .filter(([, info]) => info.type !== 'binary')+ .map(([name]) => name);+ return { names: withId(names), map };+}++async function resolveKnownFields({+ client,+ model,+ wanted,+}: {+ client: OdooClient;+ model: string;+ wanted: readonly string[];+}): Promise<{ names: string[]; map: OdooFieldMap }> {+ const map = await client.fieldsGet(model);+ return { names: withId(wanted.filter((name) => name === 'id' || name in map)), map };+}++function withId(names: readonly string[]): string[] {+ return names.includes('id') ? [...names] : ['id', ...names];+}++async function searchPage({+ client,+ model,+ domain,+ fields,+ map,+ limit,+ offset,+ order,+ context,+}: SearchPageParams): Promise<SearchPageResult> {+ const rows = await client.call<Record<string, unknown>[]>({+ model,+ method: 'search_read',+ args: [domain],+ kwargs: {+ fields,+ offset,+ limit: limit + 1,+ order,+ context,+ },+ });+ const list = Array.isArray(rows) ? rows : [];+ const hasMore = list.length > limit;+ const page = hasMore ? list.slice(0, limit) : list;+ return {+ records: page.map((record) => odooOutput.normalizeRecord({ record, fields: map, requested: fields })),+ has_more: hasMore,+ next_offset: hasMore ? offset + limit : null,+ };+}++async function readByIds({+ client,+ model,+ ids,+ fields,+ map,+}: {+ client: OdooClient;+ model: string;+ ids: number[];+ fields: string[];+ map: OdooFieldMap;+}): Promise<Record<string, unknown>[]> {+ const rows = await client.call<Record<string, unknown>[]>({+ model,+ method: 'read',+ args: [ids],+ kwargs: { fields },+ });+ const list = Array.isArray(rows) ? rows : [];+ return list.map((record) => odooOutput.normalizeRecord({ record, fields: map, requested: fields }));+}++async function readOne({+ client,+ model,+ id,+ wanted,+}: {+ client: OdooClient;+ model: string;+ id: number;+ wanted: readonly string[];+}): Promise<Record<string, unknown>> {+ const { names, map } = await resolveKnownFields({ client, model, wanted });+ const [record] = await readByIds({ client, model, ids: [id], fields: names, map });+ if (!record) throw new Error(`${model} record ${id} was not found.`);+ return fillMissing({ record, wanted });+}++function fillMissing({ record, wanted }: { record: Record<string, unknown>; wanted: readonly string[] }): Record<string, unknown> {+ const ordered = wanted.flatMap((name): [string, unknown][] => {+ const own: [string, unknown] = [name, name in record ? record[name] : null];+ const label = `${name}_name`;+ return label in record ? [own, [label, record[label]]] : [own];+ });+ const placed = new Set(ordered.map(([key]) => key));+ return Object.fromEntries([...ordered, ...Object.entries(record).filter(([key]) => !placed.has(key))]);+}++async function findApp({+ client,+ model,+ wanted,+ domain,+ limit,+ offset,+ order,+ context,+ manyToOne,+}: {+ client: OdooClient;+ model: string;+ wanted: readonly string[];+ domain: Domain;+ limit: number;+ offset: number;+ order?: string;+ context?: Record<string, unknown>;+ manyToOne?: readonly string[];+}): Promise<{ model: string; count: number; offset: number; limit: number; has_more: boolean; next_offset: number | null; records: Record<string, unknown>[] }> {+ const { names, map } = await resolveKnownFields({ client, model, wanted });+ const page = await searchPage({ client, model, domain, fields: names, map, limit, offset, order, context });+ const records = page.records.map((record) => fillMissing({ record: fillManyToOne({ record, manyToOne }), wanted }));+ return { model, count: records.length, offset, limit, has_more: page.has_more, next_offset: page.next_offset, records };+}++function fillManyToOne({ record, manyToOne }: { record: Record<string, unknown>; manyToOne?: readonly string[] }): Record<string, unknown> {+ if (!manyToOne) return record;+ const missing = manyToOne.filter((name) => !(`${name}_name` in record));+ return { ...record, ...Object.fromEntries(missing.map((name) => [`${name}_name`, null])) };+}++async function readApp({+ client,+ model,+ id,+ wanted,+ manyToOne,+}: {+ client: OdooClient;+ model: string;+ id: number;+ wanted: readonly string[];+ manyToOne?: readonly string[];+}): Promise<Record<string, unknown>> {+ const record = await readOne({ client, model, id, wanted });+ return fillMissing({ record: fillManyToOne({ record, manyToOne }), wanted });+}++async function readCreated({+ client,+ model,+ id,+ wanted,+ manyToOne,+}: {+ client: OdooClient;+ model: string;+ id: number;+ wanted: readonly string[];+ manyToOne?: readonly string[];+}): Promise<Record<string, unknown>> {+ try {+ const record = await readApp({ client, model, id, wanted, manyToOne });+ return { ...record, read_back_error: null };+ } catch (error) {+ return unreadCreated({ id, wanted, manyToOne, error });+ }+}++function unreadCreated({+ id,+ wanted,+ manyToOne,+ error,+ known = {},+}: {+ id: number | null;+ wanted: readonly string[];+ manyToOne?: readonly string[];+ error: unknown;+ known?: Record<string, unknown>;+}): Record<string, unknown> {+ const record = fillMissing({ record: fillManyToOne({ record: { id, ...known }, manyToOne }), wanted });+ return { ...record, read_back_error: readBackReason(error) };+}++function readBackReason(error: unknown): string {+ return (error instanceof Error ? error.message : String(error)).trim().replace(/\.+$/, '');+}++export const odooRecords = {+ resolveFields,+ resolveKnownFields,+ searchPage,+ readByIds,+ readOne,+ findApp,+ readApp,+ readCreated,+ unreadCreated,+ readBackReason,+};++type SearchPageParams = {+ client: OdooClient;+ model: string;+ domain: Domain;+ fields: string[];+ map: OdooFieldMap;+ limit: number;+ offset: number;+ order?: string;+ context?: Record<string, unknown>;+};++type SearchPageResult = {+ records: Record<string, unknown>[];+ has_more: boolean;+ next_offset: number | null;+};diff --git a/packages/pieces/community/odoo/src/lib/common/values.ts b/packages/pieces/community/odoo/src/lib/common/values.tsnew file mode 100644index 00000000000..fc7bf928e6a--- /dev/null+++ b/packages/pieces/community/odoo/src/lib/common/values.ts@@ -0,0 +1,297 @@+import { OdooFieldMap } from './client';++function pad(n: number): string {+ return String(n).padStart(2, '0');+}++function toOdooDatetime(input: number | Date): string {+ const d = typeof input === 'number' ? new Date(input) : input;+ if (Number.isNaN(d.getTime())) throw new Error('Invalid date.');+ return (+ `${d.getUTCFullYear()}-${pad(d.getUTCMonth() + 1)}-${pad(d.getUTCDate())} ` ++ `${pad(d.getUTCHours())}:${pad(d.getUTCMinutes())}:${pad(d.getUTCSeconds())}`+ );+}++function parseOdooDatetime(value: unknown): number | null {+ if (typeof value !== 'string' || value.length === 0) return null;+ const match = /^(\d{4})-(\d{2})-(\d{2})(?:[ T](\d{2}):(\d{2}):(\d{2})(?:\.\d+)?)?$/.exec(value.trim());+ if (!match) return null;+ const [, y, mo, d, h = '0', mi = '0', s = '0'] = match;+ return Date.UTC(Number(y), Number(mo) - 1, Number(d), Number(h), Number(mi), Number(s));+}++function inputToOdooDatetime({ value, label }: LabelledValue): string | undefined {+ if (value === undefined || value === null || value === '') return undefined;+ const text = String(value).trim();+ const hasZone = /(Z|[+-]\d{2}:?\d{2})$/.test(text);+ const epoch = hasZone ? Date.parse(text) : parseOdooDatetime(text) ?? Number.NaN;+ if (Number.isNaN(epoch)) {+ throw new Error(`${label} must be a date like 2026-10-01 or 2026-10-01T09:30:00Z.`);+ }+ return toOdooDatetime(epoch);+}++function inputToOdooDate({ value, label }: LabelledValue): string | undefined {+ if (value === undefined || value === null || value === '') return undefined;+ const match = /^(\d{4}-\d{2}-\d{2})/.exec(String(value).trim());+ if (!match) throw new Error(`${label} must be a date like 2026-10-01.`);+ return match[1];+}++function parseDomain({ value, label = 'Domain' }: { value: unknown; label?: string }): Domain {+ if (value === undefined || value === null || value === '') return [];+ const parsed = typeof value === 'string' ? parseJson({ text: value, label, example: '[["is_company", "=", true]]' }) : value;+ if (!Array.isArray(parsed)) {+ throw new Error(`${label} must be a list of [field, operator, value] triples.`);+ }+ return parsed.map((term, index) => toDomainTerm({ term, index, label }));+}++function toDomainTerm({ term, index, label }: { term: unknown; index: number; label: string }): DomainTerm {+ if (term === '&' || term === '|' || term === '!') return term;+ if (Array.isArray(term) && term.length === 3 && typeof term[0] === 'string' && typeof term[1] === 'string') {+ return [term[0], term[1], term[2]];+ }+ throw new Error(`${label}: item ${index + 1} must be [field, operator, value] or one of "&", "|", "!".`);+}++function andDomains(domains: Domain[]): Domain {+ const nonEmpty = domains.filter((d) => d.length > 0);+ if (nonEmpty.length <= 1) return nonEmpty[0] ?? [];+ const expressions = nonEmpty.flatMap((d) => splitExpressions(d));+ return [...expressions.slice(1).map((): DomainTerm => '&'), ...expressions.flat()];+}++function orConditions(conditions: Condition[]): Domain {+ if (conditions.length === 0) return [];+ return [...conditions.slice(1).map((): DomainTerm => '|'), ...conditions];+}++function arity(term: DomainTerm): number {+ if (term === '&' || term === '|') return 2;+ if (term === '!') return 1;+ return 0;+}++function splitExpressions(domain: Domain): Domain[] {+ const expressions: Domain[] = [];+ let i = 0;+ while (i < domain.length) {+ const start = i;+ let needed = 1;+ while (needed > 0 && i < domain.length) {+ needed = needed - 1 + arity(domain[i]);+ i++;+ }+ expressions.push(domain.slice(start, i));+ }+ return expressions;+}++function parseJson({ text, label, example }: { text: string; label: string; example: string }): unknown {+ try {+ return JSON.parse(text);+ } catch {+ throw new Error(`${label} must be JSON, for example ${example}.`);+ }+}++function toId({ value, label }: LabelledValue): number {+ const n = typeof value === 'number' ? value : Number(String(value ?? '').trim());+ if (!Number.isInteger(n) || n <= 0) {+ throw new Error(`${label} must be a positive whole number (an Odoo record ID).`);+ }+ return n;+}++function optionalId({ value, label }: LabelledValue): number | undefined {+ if (value === undefined || value === null || value === '') return undefined;+ return toId({ value, label });+}++function toIdList({ value, label, allowEmpty = false }: LabelledValue & { allowEmpty?: boolean }): number[] {+ const list = asList({ value, label });+ const ids = list.map((item) => toId({ value: item, label }));+ if (!allowEmpty && ids.length === 0) throw new Error(`${label} must contain at least one ID.`);+ return Array.from(new Set(ids));+}++function asList({ value, label }: LabelledValue): unknown[] {+ if (value === undefined || value === null || value === '') return [];+ if (Array.isArray(value)) return value;+ if (typeof value === 'string') {+ const text = value.trim();+ if (text.startsWith('[')) {+ const parsed = parseJson({ text, label, example: '[12, 15]' });+ return Array.isArray(parsed) ? parsed : [parsed];+ }+ return text+ .split(',')+ .map((s) => s.trim())+ .filter((s) => s.length > 0);+ }+ return [value];+}++function toStringList(value: unknown): string[] {+ if (value === undefined || value === null || value === '') return [];+ const list = Array.isArray(value) ? value : String(value).split(',');+ return list.map((v) => String(v).trim()).filter((v) => v.length > 0);+}++function parseObject({ value, label, allowEmpty = false }: LabelledValue & { allowEmpty?: boolean }): Record<string, unknown> {+ const parsed = typeof value === 'string' && value.trim() !== '' ? parseJson({ text: value, label, example: '{"name": "Acme"}' }) : value;+ const record = parsed === undefined || parsed === null || parsed === '' ? {} : parsed;+ if (!isRecord(record)) throw new Error(`${label} must be a JSON object.`);+ if (!allowEmpty && Object.keys(record).length === 0) throw new Error(`${label} must set at least one field.`);+ return record;+}++function parseArray({ value, label }: LabelledValue): unknown[] {+ if (value === undefined || value === null || value === '') return [];+ const parsed = typeof value === 'string' ? parseJson({ text: value, label, example: '[1, "a"]' }) : value;+ if (!Array.isArray(parsed)) throw new Error(`${label} must be a JSON list.`);+ return parsed;+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === 'object' && value !== null && !Array.isArray(value);+}++function toOptionalNumber({ value, label }: LabelledValue): number | undefined {+ if (value === undefined || value === null || value === '') return undefined;+ const n = typeof value === 'number' ? value : Number(String(value).trim());+ if (!Number.isFinite(n)) throw new Error(`${label} must be a number.`);+ return n;+}++function clampLimit({ value, fallback, max }: { value: unknown; fallback: number; max: number }): number {+ if (value === undefined || value === null || value === '') return fallback;+ const n = Number(value);+ if (!Number.isInteger(n) || n < 1) throw new Error('Limit must be a whole number of at least 1.');+ return Math.min(n, max);+}++function toOffset(value: unknown): number {+ if (value === undefined || value === null || value === '') return 0;+ const n = Number(value);+ if (!Number.isInteger(n) || n < 0) throw new Error('Offset must be a whole number of at least 0.');+ return n;+}++function toModelName(value: unknown): string {+ const model = String(value ?? '').trim();+ if (!/^[a-z_][a-z0-9_]*(\.[a-z0-9_]+)*$/i.test(model)) {+ throw new Error(`"${model}" is not a valid Odoo model name. Use the technical name, for example res.partner.`);+ }+ return model;+}++function toMethodName({ value, actions }: { value: unknown; actions: DedicatedActions }): string {+ const method = String(value ?? '').trim();+ if (!/^[a-z][a-z0-9_]*$/i.test(method)) {+ throw new Error(+ `"${method}" is not a callable Odoo method. Use a public method name such as action_confirm (Odoo refuses names starting with "_").`,+ );+ }+ const refusal = refusedMethod({ method: method.toLowerCase(), actions });+ if (refusal) throw new Error(`"${method}" cannot be called here. ${refusal}`);+ return method;+}++function refusedMethod({ method, actions }: { method: string; actions: DedicatedActions }): string | null {+ if (method === 'unlink') return `Use ${actions.delete} to delete records.`;+ if (method === 'write' || method === 'update') return `Use ${actions.update} to change field values.`;+ if (method === 'create' || method === 'name_create' || method === 'load') return `Use ${actions.create} to create records.`;+ if (method === 'web_save') return `Use ${actions.update} to change field values, or ${actions.create} to create records.`;+ if (method === 'copy') return `Use ${actions.create} to create a new record with the values you want.`;+ if (method === 'browse') return `Use ${actions.read} to read records.`;+ if (ENVIRONMENT_METHODS.includes(method)) {+ return 'It changes the user or environment of the call. Call the business method directly; pass context values as the "context" keyword argument.';+ }+ return null;+}++function definedOnly(values: Record<string, unknown>): Record<string, unknown> {+ return Object.fromEntries(Object.entries(values).filter(([, value]) => value !== undefined));+}++function optionalText(value: unknown): string | undefined {+ if (value === undefined || value === null) return undefined;+ const text = String(value);+ return text.trim() === '' ? undefined : text;+}++function normalizeRecord({+ record,+ fields,+ requested,+}: {+ record: Record<string, unknown>;+ fields: OdooFieldMap;+ requested?: readonly string[];+}): Record<string, unknown> {+ const keys = requested ?? Object.keys(record);+ return Object.fromEntries(keys.flatMap((key) => normalizeField({ key, raw: key in record ? record[key] : null, type: fields[key]?.type })));+}++function normalizeField({ key, raw, type }: { key: string; raw: unknown; type: string | undefined }): [string, unknown][] {+ if (type === 'many2one') {+ if (Array.isArray(raw) && raw.length >= 1) return [[key, raw[0]], [`${key}_name`, raw.length > 1 ? raw[1] : null]];+ if (typeof raw === 'number') return [[key, raw], [`${key}_name`, null]];+ return [[key, null], [`${key}_name`, null]];+ }+ if (type === 'boolean') return [[key, raw === null || raw === undefined ? null : Boolean(raw)]];+ if (type === 'one2many' || type === 'many2many') return [[key, Array.isArray(raw) ? raw : []]];+ return [[key, raw === false || raw === undefined ? null : raw]];+}++function firstId(value: unknown): number | null {+ if (typeof value === 'number') return value;+ if (Array.isArray(value) && typeof value[0] === 'number') return value[0];+ return null;+}++const ENVIRONMENT_METHODS = ['sudo', 'with_user', 'with_context', 'with_env'];++export const odooDates = {+ toOdooDatetime,+ parseOdooDatetime,+ inputToOdooDatetime,+ inputToOdooDate,+};++export const odooDomain = {+ parseDomain,+ andDomains,+ orConditions,+};++export const odooInput = {+ toId,+ optionalId,+ toIdList,+ toStringList,+ parseObject,+ parseArray,+ toOptionalNumber,+ clampLimit,+ toOffset,+ toModelName,+ toMethodName,+ definedOnly,+ optionalText,+ isRecord,+};++export const odooOutput = {+ normalizeRecord,+ firstId,+};++export type Condition = [string, string, unknown];+export type DomainTerm = Condition | '&' | '|' | '!';+export type Domain = DomainTerm[];+export type DedicatedActions = { delete: string; update: string; create: string; read: string };+type LabelledValue = { value: unknown; label: string };diff --git a/packages/pieces/community/odoo/src/lib/output-schemas.ts b/packages/pieces/community/odoo/src/lib/output-schemas.tsnew file mode 100644index 00000000000..f1128c66ab6--- /dev/null+++ b/packages/pieces/community/odoo/src/lib/output-schemas.ts@@ -0,0 +1,265 @@+import { OutputSchema } from '@activepieces/pieces-framework';++const m2o = ({ key, label }: { key: string; label: string }): OutputSchema['fields'] => [+ { key, label: `${label} ID`, format: 'number' },+ { key: `${key}_name`, label },+];++const timestamps: OutputSchema['fields'] = [+ { key: 'create_date', label: 'Created On (UTC)', format: 'datetime' },+ { key: 'write_date', label: 'Last Updated On (UTC)', format: 'datetime' },+];++const readBackField: OutputSchema['fields'][number] = {+ key: 'read_back_error',+ label: 'Read-Back Error',+ description: 'null when the new record was read back. Otherwise why reading it failed: the record was still created and only id is filled.',+};++const partnerFields: OutputSchema['fields'] = [+ { key: 'id', label: 'Contact ID', format: 'number' },+ { key: 'display_name', label: 'Display Name' },+ { key: 'name', label: 'Name' },+ { key: 'is_company', label: 'Is a Company', format: 'boolean' },+ ...m2o({ key: 'parent_id', label: 'Parent Company' }),+ { key: 'email', label: 'Email', format: 'email' },+ { key: 'phone', label: 'Phone' },+ { key: 'mobile', label: 'Mobile', description: 'Removed in Odoo 19; always null there.' },+ { key: 'website', label: 'Website', format: 'url' },+ { key: 'function', label: 'Job Position' },+ { key: 'ref', label: 'Reference' },+ { key: 'vat', label: 'Tax ID' },+ { key: 'street', label: 'Street' },+ { key: 'street2', label: 'Street 2' },+ { key: 'city', label: 'City' },+ { key: 'zip', label: 'ZIP' },+ ...m2o({ key: 'state_id', label: 'State' }),+ ...m2o({ key: 'country_id', label: 'Country' }),+ { key: 'company_name', label: 'Company Name (free text)' },+ { key: 'lang', label: 'Language' },+ { key: 'active', label: 'Active', format: 'boolean' },+ ...timestamps,+];++const leadFields: OutputSchema['fields'] = [+ { key: 'id', label: 'Lead ID', format: 'number' },+ { key: 'name', label: 'Title' },+ { key: 'type', label: 'Type', description: 'lead or opportunity' },+ { key: 'active', label: 'Active', format: 'boolean', description: 'false when the lead was marked lost' },+ ...m2o({ key: 'stage_id', label: 'Stage' }),+ { key: 'probability', label: 'Probability (%)', format: 'number' },+ { key: 'expected_revenue', label: 'Expected Revenue', format: 'number' },+ ...m2o({ key: 'partner_id', label: 'Customer' }),+ { key: 'contact_name', label: 'Contact Name' },+ { key: 'partner_name', label: 'Company Name' },+ { key: 'email_from', label: 'Email', format: 'email' },+ { key: 'phone', label: 'Phone' },+ ...m2o({ key: 'user_id', label: 'Salesperson' }),+ ...m2o({ key: 'team_id', label: 'Sales Team' }),+ { key: 'tag_ids', label: 'Tag IDs' },+ { key: 'priority', label: 'Priority', description: '"0" (normal) to "3" (very high)' },+ { key: 'date_deadline', label: 'Expected Closing', format: 'date' },+ ...m2o({ key: 'lost_reason_id', label: 'Lost Reason' }),+ { key: 'won_status', label: 'Won Status', description: 'won, lost or pending; null on Odoo versions without this field (for example 18)' },+ ...timestamps,+];++const stageFields: OutputSchema['fields'] = [+ { key: 'id', label: 'Stage ID', format: 'number' },+ { key: 'name', label: 'Name' },+ { key: 'sequence', label: 'Sequence', format: 'number' },+ { key: 'is_won', label: 'Is Won Stage', format: 'boolean' },+ { key: 'fold', label: 'Folded', format: 'boolean' },+ { key: 'team_ids', label: 'Sales Team IDs', description: 'Empty = shared by all teams' },+];++const saleOrderFields: OutputSchema['fields'] = [+ { key: 'id', label: 'Order ID', format: 'number' },+ { key: 'name', label: 'Order Reference' },+ { key: 'state', label: 'Status', description: 'draft, sent, sale, cancel (and done on Odoo 16)' },+ ...m2o({ key: 'partner_id', label: 'Customer' }),+ { key: 'date_order', label: 'Order Date (UTC)', format: 'datetime' },+ { key: 'validity_date', label: 'Expiration', format: 'date' },+ { key: 'client_order_ref', label: 'Customer Reference' },+ { key: 'amount_untaxed', label: 'Untaxed Amount', format: 'number' },+ { key: 'amount_tax', label: 'Taxes', format: 'number' },+ { key: 'amount_total', label: 'Total', format: 'number' },+ ...m2o({ key: 'currency_id', label: 'Currency' }),+ ...m2o({ key: 'user_id', label: 'Salesperson' }),+ { key: 'invoice_status', label: 'Invoice Status' },+ ...timestamps,+];++const invoiceFields: OutputSchema['fields'] = [+ { key: 'id', label: 'Invoice ID', format: 'number' },+ { key: 'name', label: 'Number', description: 'null on Odoo 18 and later while the invoice is a draft; on Odoo 17 and older a draft can already carry its number (or "/")' },+ { key: 'move_type', label: 'Type', description: 'out_invoice, in_invoice, out_refund, in_refund' },+ { key: 'state', label: 'Status', description: 'draft, posted, cancel' },+ { key: 'payment_state', label: 'Payment Status' },+ ...m2o({ key: 'partner_id', label: 'Partner' }),+ { key: 'invoice_date', label: 'Invoice Date', format: 'date' },+ { key: 'invoice_date_due', label: 'Due Date', format: 'date' },+ { key: 'ref', label: 'Reference' },+ { key: 'payment_reference', label: 'Payment Reference' },+ { key: 'invoice_origin', label: 'Source Document' },+ { key: 'amount_untaxed', label: 'Untaxed Amount', format: 'number' },+ { key: 'amount_tax', label: 'Taxes', format: 'number' },+ { key: 'amount_total', label: 'Total', format: 'number' },+ { key: 'amount_residual', label: 'Amount Due', format: 'number' },+ ...m2o({ key: 'currency_id', label: 'Currency' }),+ ...timestamps,+];++const productFields: OutputSchema['fields'] = [+ { key: 'id', label: 'Product Variant ID', format: 'number' },+ { key: 'display_name', label: 'Display Name' },+ { key: 'name', label: 'Name' },+ { key: 'default_code', label: 'Internal Reference' },+ { key: 'barcode', label: 'Barcode' },+ { key: 'lst_price', label: 'Sales Price', format: 'number' },+ { key: 'standard_price', label: 'Cost', format: 'number' },+ { key: 'type', label: 'Product Type' },+ { key: 'detailed_type', label: 'Detailed Type (Odoo 16/17)' },+ { key: 'is_storable', label: 'Track Inventory (Odoo 18+)', format: 'boolean' },+ { key: 'sale_ok', label: 'Can Be Sold', format: 'boolean' },+ { key: 'purchase_ok', label: 'Can Be Purchased', format: 'boolean' },+ ...m2o({ key: 'uom_id', label: 'Unit of Measure' }),+ ...m2o({ key: 'categ_id', label: 'Category' }),+ ...m2o({ key: 'product_tmpl_id', label: 'Product Template' }),+ { key: 'active', label: 'Active', format: 'boolean' },+];++const projectFields: OutputSchema['fields'] = [+ { key: 'id', label: 'Project ID', format: 'number' },+ { key: 'name', label: 'Name' },+ ...m2o({ key: 'partner_id', label: 'Customer' }),+ ...m2o({ key: 'user_id', label: 'Project Manager' }),+ { key: 'date_start', label: 'Start Date', format: 'date' },+ { key: 'date', label: 'End Date', format: 'date' },+ { key: 'task_count', label: 'Task Count', format: 'number' },+ { key: 'active', label: 'Active', format: 'boolean' },+ { key: 'create_date', label: 'Created On (UTC)', format: 'datetime' },+];++const taskFields: OutputSchema['fields'] = [+ { key: 'id', label: 'Task ID', format: 'number' },+ { key: 'name', label: 'Title' },+ ...m2o({ key: 'project_id', label: 'Project' }),+ ...m2o({ key: 'stage_id', label: 'Stage' }),+ { key: 'user_ids', label: 'Assignee User IDs' },+ { key: 'date_deadline', label: 'Deadline', description: 'Date on Odoo 16, UTC datetime on 17+' },+ { key: 'priority', label: 'Priority', description: '"0" normal, "1" high' },+ { key: 'state', label: 'State (Odoo 17+)' },+ { key: 'kanban_state', label: 'Kanban State (Odoo 16)' },+ { key: 'tag_ids', label: 'Tag IDs' },+ ...m2o({ key: 'parent_id', label: 'Parent Task' }),+ ...m2o({ key: 'partner_id', label: 'Customer' }),+ ...timestamps,+];++const userFields: OutputSchema['fields'] = [+ { key: 'id', label: 'User ID', format: 'number' },+ { key: 'name', label: 'Name' },+ { key: 'login', label: 'Login' },+ { key: 'email', label: 'Email', format: 'email' },+ ...m2o({ key: 'partner_id', label: 'Related Contact' }),+ { key: 'active', label: 'Active', format: 'boolean' },+];++const attachmentFields: OutputSchema['fields'] = [+ { key: 'id', label: 'Attachment ID', format: 'number' },+ { key: 'name', label: 'File Name' },+ { key: 'mimetype', label: 'MIME Type' },+ { key: 'file_size', label: 'Size', format: 'filesize' },+ { key: 'res_model', label: 'Attached To Model' },+ { key: 'res_id', label: 'Attached To Record ID', format: 'number' },+ { key: 'type', label: 'Storage Type', description: 'binary or url' },+ { key: 'url', label: 'URL', format: 'url' },+ { key: 'create_date', label: 'Created On (UTC)', format: 'datetime' },+];++const pageFields: OutputSchema['fields'] = [+ { key: 'model', label: 'Model' },+ { key: 'count', label: 'Count', format: 'number' },+ { key: 'offset', label: 'Offset', format: 'number' },+ { key: 'limit', label: 'Limit', format: 'number' },+ { key: 'has_more', label: 'Has More', format: 'boolean' },+ { key: 'next_offset', label: 'Next Offset', format: 'number' },+];++function pageOf({ label, labelKey, items }: { label: string; labelKey: string; items: OutputSchema['fields'] }): OutputSchema {+ return { fields: [...pageFields, { key: 'records', label, labelKey, listItems: items }] };+}++export const createRecordOutputSchema: OutputSchema = {+ fields: [{ key: 'id', label: 'New Record ID', format: 'number' }],+};++export const updateRecordOutputSchema: OutputSchema = {+ fields: [{ key: 'success', label: 'Success', format: 'boolean' }],+};++export const partnerOutputSchema: OutputSchema = { fields: partnerFields };+export const leadOutputSchema: OutputSchema = { fields: leadFields };+export const saleOrderOutputSchema: OutputSchema = { fields: saleOrderFields };+export const invoiceOutputSchema: OutputSchema = { fields: invoiceFields };+export const productOutputSchema: OutputSchema = { fields: productFields };+export const taskOutputSchema: OutputSchema = { fields: taskFields };+export const attachmentOutputSchema: OutputSchema = { fields: attachmentFields };++export const createdLeadOutputSchema: OutputSchema = { fields: [...leadFields, readBackField] };+export const createdSaleOrderOutputSchema: OutputSchema = { fields: [...saleOrderFields, readBackField] };+export const createdAttachmentOutputSchema: OutputSchema = { fields: [...attachmentFields, readBackField] };++export const findInvoicesOutputSchema: OutputSchema = pageOf({ label: 'Invoices', labelKey: 'name', items: invoiceFields });++export const getRecordOutputSchema: OutputSchema = {+ fields: [+ { key: 'model', label: 'Model' },+ { key: 'id', label: 'Record ID', format: 'number' },+ { key: 'record', label: 'Record' },+ ],+};++export const deleteRecordOutputSchema: OutputSchema = {+ fields: [+ { key: 'success', label: 'Success', format: 'boolean' },+ { key: 'model', label: 'Model' },+ { key: 'deleted_id', label: 'Deleted Record ID', format: 'number' },+ ],+};++export const runMethodOutputSchema: OutputSchema = {+ fields: [+ { key: 'model', label: 'Model' },+ { key: 'method', label: 'Method' },+ { key: 'record_ids', label: 'Record IDs' },+ { key: 'returned_none', label: 'Method Returned Nothing', format: 'boolean', description: 'true when the method ran but had no return value' },+ { key: 'result', label: 'Result' },+ ],+};++export const postMessageOutputSchema: OutputSchema = {+ fields: [+ { key: 'message_id', label: 'Message ID', format: 'number' },+ { key: 'model', label: 'Model' },+ { key: 'record_id', label: 'Record ID', format: 'number' },+ { key: 'message_type', label: 'Posted As', description: 'note or message' },+ ],+};++export const odooSchemaFields = {+ partnerFields,+ leadFields,+ stageFields,+ saleOrderFields,+ invoiceFields,+ productFields,+ projectFields,+ taskFields,+ userFields,+ attachmentFields,+ pageFields,+ readBackField,+ pageOf,+};diff --git a/packages/pieces/community/odoo/src/lib/triggers/new-contact.ts b/packages/pieces/community/odoo/src/lib/triggers/new-contact.tsnew file mode 100644index 00000000000..ea9f1e95e24--- /dev/null+++ b/packages/pieces/community/odoo/src/lib/triggers/new-contact.ts@@ -0,0 +1,101 @@+import { createTrigger, Property, TriggerStrategy } from '@activepieces/pieces-framework';+import { odooAuth } from '../auth';+import { odooApps } from '../common/app-fields';+import { OdooClient } from '../common/client';+import { odooPolling, PollSource } from '../common/polling';+import { Domain } from '../common/values';+import { partnerOutputSchema } from '../output-schemas';++function sourceOf(propsValue: { contact_type?: string }): PollSource {+ const domain: Domain =+ propsValue.contact_type === 'person'+ ? [['is_company', '=', false]]+ : propsValue.contact_type === 'company'+ ? [['is_company', '=', true]]+ : [];+ return {+ model: odooApps.partner.model,+ dateField: 'create_date',+ domain,+ knownFields: odooApps.partner.fields,+ manyToOne: odooApps.partner.manyToOne,+ };+}++export const newContactTrigger = createTrigger({+ auth: odooAuth,+ name: 'new_contact',+ displayName: 'New Contact',+ description: 'Triggers when a new contact (person or company) is created in Odoo.',+ classification: 'READ',+ aiMetadata: {+ description:+ 'Fires once per new Odoo contact (res.partner), optionally only people or only companies. Each poll looks back 5 minutes, so contacts saved up to 5 minutes late are still caught. Oldest first; contacts already saved when the trigger was turned on are not replayed. Delivery is exactly once while the 5-minute window holds up to 5,000 separate ID ranges; beyond that, a record whose save commits late, with a timestamp at or before the newest entry it had to forget, can be missed.',+ },+ type: TriggerStrategy.POLLING,+ props: {+ contact_type: Property.StaticDropdown({+ displayName: 'Contact Type',+ description: 'Which new contacts should start the flow.',+ required: false,+ defaultValue: 'any',+ options: {+ options: [+ { label: 'People and companies', value: 'any' },+ { label: 'People only', value: 'person' },+ { label: 'Companies only', value: 'company' },+ ],+ },+ }),+ },+ outputSchema: partnerOutputSchema,+ sampleData: {+ id: 42,+ display_name: 'Acme Corporation, Jane Doe',+ name: 'Jane Doe',+ is_company: false,+ parent_id: 41,+ parent_id_name: 'Acme Corporation',+ email: '[email protected]',+ phone: '+1 555 0100',+ mobile: null,+ website: null,+ function: 'Buyer',+ ref: null,+ vat: null,+ street: '1 Main Street',+ street2: null,+ city: 'Springfield',+ zip: '12345',+ state_id: null,+ state_id_name: null,+ country_id: 233,+ country_id_name: 'United States',+ company_name: null,+ lang: 'en_US',+ active: true,+ create_date: '2026-09-29 10:15:00',+ write_date: '2026-09-29 10:15:00',+ },+ async onEnable(context) {+ await odooPolling.onEnable({+ client: OdooClient.fromAuth({ auth: context.auth.props }),+ source: sourceOf(context.propsValue),+ store: context.store,+ isRepublish: context.isRepublish,+ });+ },+ async onDisable(context) {+ await odooPolling.onDisable({ store: context.store });+ },+ async run(context) {+ return odooPolling.run({+ client: OdooClient.fromAuth({ auth: context.auth.props }),+ source: sourceOf(context.propsValue),+ store: context.store,+ });+ },+ async test(context) {+ return odooPolling.test({ client: OdooClient.fromAuth({ auth: context.auth.props }), source: sourceOf(context.propsValue) });+ },+});diff --git a/packages/pieces/community/odoo/src/lib/triggers/new-lead.ts b/packages/pieces/community/odoo/src/lib/triggers/new-lead.tsnew file mode 100644index 00000000000..fe38a5cc78d--- /dev/null+++ b/packages/pieces/community/odoo/src/lib/triggers/new-lead.ts@@ -0,0 +1,118 @@+import { createTrigger, Property, TriggerStrategy } from '@activepieces/pieces-framework';+import { odooAuth } from '../auth';+import { odooApps } from '../common/app-fields';+import { OdooClient } from '../common/client';+import { odooPolling, PollSource } from '../common/polling';+import { odooProps } from '../common/props';+import { Domain, odooDomain } from '../common/values';+import { leadOutputSchema } from '../output-schemas';++function sourceOf({ propsValue, enabledAt }: { propsValue: { lead_type?: string; team_id?: number }; enabledAt?: string }): PollSource {+ const teamFilter: Domain = propsValue.team_id ? [['team_id', '=', propsValue.team_id]] : [];+ if (propsValue.lead_type === 'opportunity') {+ const since: Domain = enabledAt ? ['|', ['create_date', '>=', enabledAt], ['date_conversion', '>=', enabledAt]] : [];+ return {+ model: odooApps.lead.model,+ dateField: 'write_date',+ domain: odooDomain.andDomains([[['type', '=', 'opportunity']], teamFilter, since]),+ knownFields: odooApps.lead.fields,+ manyToOne: odooApps.lead.manyToOne,+ emitOnce: true,+ };+ }+ const typeFilter: Domain = propsValue.lead_type === 'lead' ? [['type', '=', 'lead']] : [];+ return {+ model: odooApps.lead.model,+ dateField: 'create_date',+ domain: odooDomain.andDomains([typeFilter, teamFilter]),+ knownFields: odooApps.lead.fields,+ manyToOne: odooApps.lead.manyToOne,+ };+}++export const newLeadTrigger = createTrigger({+ auth: odooAuth,+ name: 'new_lead',+ displayName: 'New Lead or Opportunity',+ description: 'Triggers when a new lead or opportunity is created in Odoo CRM.',+ classification: 'READ',+ aiMetadata: {+ description:+ 'Fires once per new Odoo CRM record (crm.lead), optionally only leads or only opportunities, and optionally for one sales team. Leads and "Leads and opportunities" fire when the record is created. The type and team are checked while the record is new: each poll re-checks records created up to 5 minutes before the newest crm.lead record, so moving a record into the team does not fire once a record created more than 5 minutes after it exists. "Opportunities only" fires once for an opportunity created, or a lead converted to one, after the trigger was turned on (the enable time is taken from the Activepieces server clock). The team is checked on every poll, so such an opportunity that is moved into the chosen team later still fires then. Later edits of a fired opportunity do not fire again (it remembers the last 2,000 fired opportunities). Each poll looks back 5 minutes, so records saved up to 5 minutes late are still caught. Needs the CRM app. Oldest first; records already saved when the trigger was turned on are not replayed. Delivery is exactly once while the 5-minute window holds up to 5,000 separate ID ranges; beyond that, a record whose save commits late, with a timestamp at or before the newest entry it had to forget, can be missed.',+ },+ type: TriggerStrategy.POLLING,+ props: {+ lead_type: Property.StaticDropdown({+ displayName: 'Type',+ description:+ 'Leads only exist when "Leads" is turned on in CRM settings; otherwise every record is an opportunity. For leads, the type and team are checked while the record is new (until a record created more than 5 minutes later exists), so later changes do not fire. "Opportunities only" also fires when a lead is converted to an opportunity after the trigger was turned on, and checks the team on every poll, so an opportunity moved into the chosen team later fires then (once; the last 2,000 fired opportunities are remembered).',+ required: false,+ defaultValue: 'any',+ options: {+ options: [+ { label: 'Leads and opportunities', value: 'any' },+ { label: 'Leads only', value: 'lead' },+ { label: 'Opportunities only', value: 'opportunity' },+ ],+ },+ }),+ team_id: odooProps.fixedModelDropdown({+ model: 'crm.team',+ displayName: 'Sales Team',+ description: 'Optional. Only fire for this sales team.',+ required: false,+ }),+ },+ outputSchema: leadOutputSchema,+ sampleData: {+ id: 17,+ name: 'Website: 20 office chairs',+ type: 'opportunity',+ active: true,+ stage_id: 1,+ stage_id_name: 'New',+ probability: 10,+ expected_revenue: 4000,+ partner_id: 42,+ partner_id_name: 'Acme Corporation',+ contact_name: 'Jane Doe',+ partner_name: 'Acme Corporation',+ email_from: '[email protected]',+ phone: '+1 555 0100',+ user_id: 2,+ user_id_name: 'Mitchell Admin',+ team_id: 1,+ team_id_name: 'Sales',+ tag_ids: [3],+ priority: '1',+ date_deadline: '2026-10-15',+ lost_reason_id: null,+ lost_reason_id_name: null,+ won_status: 'pending',+ create_date: '2026-09-29 10:15:00',+ write_date: '2026-09-29 10:15:00',+ },+ async onEnable(context) {+ const enabledAt = await odooPolling.enabledAt({ store: context.store, reset: !context.isRepublish });+ await odooPolling.onEnable({+ client: OdooClient.fromAuth({ auth: context.auth.props }),+ source: sourceOf({ propsValue: context.propsValue, enabledAt }),+ store: context.store,+ isRepublish: context.isRepublish,+ });+ },+ async onDisable(context) {+ await odooPolling.onDisable({ store: context.store });+ },+ async run(context) {+ const enabledAt = await odooPolling.enabledAt({ store: context.store });+ return odooPolling.run({+ client: OdooClient.fromAuth({ auth: context.auth.props }),+ source: sourceOf({ propsValue: context.propsValue, enabledAt }),+ store: context.store,+ });+ },+ async test(context) {+ return odooPolling.test({ client: OdooClient.fromAuth({ auth: context.auth.props }), source: sourceOf({ propsValue: context.propsValue }) });+ },+});diff --git a/packages/pieces/community/odoo/src/lib/triggers/new-or-updated-record.ts b/packages/pieces/community/odoo/src/lib/triggers/new-or-updated-record.tsnew file mode 100644index 00000000000..77a0eb14639--- /dev/null+++ b/packages/pieces/community/odoo/src/lib/triggers/new-or-updated-record.ts@@ -0,0 +1,72 @@+import { createTrigger, Property, TriggerStrategy } from '@activepieces/pieces-framework';+import { odooAuth } from '../auth';+import { OdooClient } from '../common/client';+import { odooPolling, PollSource } from '../common/polling';+import { odooProps } from '../common/props';+import { odooDomain, odooInput } from '../common/values';++function sourceOf(propsValue: { model: string; domain?: unknown; fields?: unknown[] }): PollSource {+ const domain = odooDomain.parseDomain({ value: propsValue.domain, label: 'Filter domain' });+ return {+ model: odooInput.toModelName(propsValue.model),+ dateField: 'write_date',+ domain,+ fields: odooInput.toStringList(propsValue.fields),+ context: odooPolling.withArchived({ domain }),+ };+}++export const newOrUpdatedRecordTrigger = createTrigger({+ auth: odooAuth,+ name: 'new_or_updated_record',+ displayName: 'New or Updated Record',+ description: 'Triggers when a record is created or changed in any Odoo model. Odoo also counts automatic updates (computed fields, scheduled actions) as changes.',+ classification: 'READ',+ aiMetadata: {+ description:+ 'Fires once per create or update of a record in the chosen Odoo model (each new write_date emits the record again), optionally limited by an Odoo domain filter. Automatic writes such as computed fields or scheduled actions also count as updates. Archived records are included unless the filter mentions active, so archiving a record fires it. Each poll looks back 5 minutes, so changes saved up to 5 minutes late are still caught. Oldest change first; changes already saved when the trigger was turned on are not replayed. Delivery is exactly once while the 5-minute window holds up to 5,000 separate ID ranges; beyond that, a record whose save commits late, with a timestamp at or before the newest entry it had to forget, can be missed.',+ },+ type: TriggerStrategy.POLLING,+ props: {+ model: odooProps.modelDropdown(),+ domain: Property.Json({+ displayName: 'Filter domain',+ description:+ 'Optional. Only fire for created or updated records that match this Odoo domain, for example [["is_company", "=", true]]. Leave empty for every change. Archived records are included (so archiving a record fires it) unless the domain mentions active.',+ required: false,+ }),+ fields: Property.Array({+ displayName: 'Fields',+ description: 'Optional. Field names to return, for example name, email. Leave empty for all fields except files and images.',+ required: false,+ }),+ },+ sampleData: {+ id: 42,+ display_name: 'Acme Corporation',+ name: 'Acme Corporation',+ create_date: '2026-09-29 10:15:00',+ write_date: '2026-09-29 10:15:00',+ },+ async onEnable(context) {+ await odooPolling.onEnable({+ client: OdooClient.fromAuth({ auth: context.auth.props }),+ source: sourceOf(context.propsValue),+ store: context.store,+ isRepublish: context.isRepublish,+ });+ },+ async onDisable(context) {+ await odooPolling.onDisable({ store: context.store });+ },+ async run(context) {+ return odooPolling.run({+ client: OdooClient.fromAuth({ auth: context.auth.props }),+ source: sourceOf(context.propsValue),+ store: context.store,+ });+ },+ async test(context) {+ return odooPolling.test({ client: OdooClient.fromAuth({ auth: context.auth.props }), source: sourceOf(context.propsValue) });+ },+});diff --git a/packages/pieces/community/odoo/src/lib/triggers/new-record.ts b/packages/pieces/community/odoo/src/lib/triggers/new-record.tsnew file mode 100644index 00000000000..3b7b7fbba7f--- /dev/null+++ b/packages/pieces/community/odoo/src/lib/triggers/new-record.ts@@ -0,0 +1,72 @@+import { createTrigger, Property, TriggerStrategy } from '@activepieces/pieces-framework';+import { odooAuth } from '../auth';+import { OdooClient } from '../common/client';+import { odooPolling, PollSource } from '../common/polling';+import { odooProps } from '../common/props';+import { odooDomain, odooInput } from '../common/values';++function sourceOf(propsValue: { model: string; domain?: unknown; fields?: unknown[] }): PollSource {+ const domain = odooDomain.parseDomain({ value: propsValue.domain, label: 'Filter domain' });+ return {+ model: odooInput.toModelName(propsValue.model),+ dateField: 'create_date',+ domain,+ fields: odooInput.toStringList(propsValue.fields),+ context: odooPolling.withArchived({ domain }),+ };+}++export const newRecordTrigger = createTrigger({+ auth: odooAuth,+ name: 'new_record',+ displayName: 'New Record',+ description: 'Triggers when a new record is created in any Odoo model (contacts, orders, invoices, tasks...).',+ classification: 'READ',+ aiMetadata: {+ description:+ 'Fires once per record created in the chosen Odoo model, optionally limited by an Odoo domain filter. Polls create_date, oldest first; records already saved when the trigger was turned on are not replayed. Archived records are included unless the filter mentions active. Each poll looks back 5 minutes, so records saved up to 5 minutes late are still caught. Delivery is exactly once while the 5-minute window holds up to 5,000 separate ID ranges; beyond that, a record whose save commits late, with a timestamp at or before the newest entry it had to forget, can be missed.',+ },+ type: TriggerStrategy.POLLING,+ props: {+ model: odooProps.modelDropdown(),+ domain: Property.Json({+ displayName: 'Filter domain',+ description:+ 'Optional. Only fire for records that match this Odoo domain, for example [["is_company", "=", true]]. Leave empty for every new record. Archived records are included unless the domain mentions active.',+ required: false,+ }),+ fields: Property.Array({+ displayName: 'Fields',+ description: 'Optional. Field names to return, for example name, email. Leave empty for all fields except files and images.',+ required: false,+ }),+ },+ sampleData: {+ id: 42,+ display_name: 'Acme Corporation',+ name: 'Acme Corporation',+ create_date: '2026-09-29 10:15:00',+ write_date: '2026-09-29 10:15:00',+ },+ async onEnable(context) {+ await odooPolling.onEnable({+ client: OdooClient.fromAuth({ auth: context.auth.props }),+ source: sourceOf(context.propsValue),+ store: context.store,+ isRepublish: context.isRepublish,+ });+ },+ async onDisable(context) {+ await odooPolling.onDisable({ store: context.store });+ },+ async run(context) {+ return odooPolling.run({+ client: OdooClient.fromAuth({ auth: context.auth.props }),+ source: sourceOf(context.propsValue),+ store: context.store,+ });+ },+ async test(context) {+ return odooPolling.test({ client: OdooClient.fromAuth({ auth: context.auth.props }), source: sourceOf(context.propsValue) });+ },+});diff --git a/packages/pieces/community/odoo/src/lib/triggers/new-sales-order.ts b/packages/pieces/community/odoo/src/lib/triggers/new-sales-order.tsnew file mode 100644index 00000000000..92afc00c1e9--- /dev/null+++ b/packages/pieces/community/odoo/src/lib/triggers/new-sales-order.ts@@ -0,0 +1,93 @@+import { createTrigger, Property, TriggerStrategy } from '@activepieces/pieces-framework';+import { odooAuth } from '../auth';+import { odooApps } from '../common/app-fields';+import { OdooClient } from '../common/client';+import { odooPolling, PollSource } from '../common/polling';+import { Domain, odooDomain } from '../common/values';+import { saleOrderOutputSchema } from '../output-schemas';++function sourceOf({ propsValue, enabledAt }: { propsValue: { order_state?: string }; enabledAt?: string }): PollSource {+ const quotations = propsValue.order_state === 'draft';+ const since: Domain = enabledAt ? [['date_order', '>=', enabledAt]] : [];+ const confirmed = odooDomain.andDomains([[['state', 'in', ['sale', 'done']]], since]);+ return {+ model: odooApps.saleOrder.model,+ dateField: quotations ? 'create_date' : 'write_date',+ domain: quotations ? [] : confirmed,+ knownFields: odooApps.saleOrder.fields,+ manyToOne: odooApps.saleOrder.manyToOne,+ emitOnce: !quotations,+ };+}++export const newSalesOrderTrigger = createTrigger({+ auth: odooAuth,+ name: 'new_sales_order',+ displayName: 'New Sales Order',+ description: 'Triggers when a sales order is confirmed in Odoo, or when a new quotation is created.',+ classification: 'READ',+ aiMetadata: {+ description:+ 'Fires once per Odoo sales order (sale.order). Default mode: once when an order is confirmed after the trigger was turned on (the enable time is taken from the Activepieces server clock). Confirming with the Confirm button or action_confirm sets the order date to the confirmation time, so a quotation with an old order date still fires. An order set to confirmed by a direct state write or an import keeps its old order date and does not fire. Orders confirmed before the trigger was turned on never fire, even when edited later. Later edits of a fired order do not fire again (it remembers the last 2,000 fired orders). Other mode: once per new quotation by creation date, even if it was already sent or confirmed before the poll. Each poll looks back 5 minutes, so orders saved up to 5 minutes late are still caught. Needs the Sales app. Delivery is exactly once while the 5-minute window holds up to 5,000 separate ID ranges; beyond that, a record whose save commits late, with a timestamp at or before the newest entry it had to forget, can be missed.',+ },+ type: TriggerStrategy.POLLING,+ props: {+ order_state: Property.StaticDropdown({+ displayName: 'Fire On',+ description:+ 'Orders confirmed after the trigger was turned on, or new quotations. Only orders confirmed with the Confirm button (action_confirm) fire; orders set to confirmed by a direct state write or an import keep their old order date and do not fire.',+ required: false,+ defaultValue: 'sale',+ options: {+ options: [+ { label: 'Order confirmed', value: 'sale' },+ { label: 'New quotation', value: 'draft' },+ ],+ },+ }),+ },+ outputSchema: saleOrderOutputSchema,+ sampleData: {+ id: 12,+ name: 'S00012',+ state: 'sale',+ partner_id: 42,+ partner_id_name: 'Acme Corporation',+ date_order: '2026-09-29 10:15:00',+ validity_date: '2026-10-29',+ client_order_ref: 'PO-7781',+ amount_untaxed: 1000,+ amount_tax: 150,+ amount_total: 1150,+ currency_id: 1,+ currency_id_name: 'USD',+ user_id: 2,+ user_id_name: 'Mitchell Admin',+ invoice_status: 'to invoice',+ create_date: '2026-09-28 16:02:11',+ write_date: '2026-09-29 10:15:00',+ },+ async onEnable(context) {+ const enabledAt = await odooPolling.enabledAt({ store: context.store, reset: !context.isRepublish });+ await odooPolling.onEnable({+ client: OdooClient.fromAuth({ auth: context.auth.props }),+ source: sourceOf({ propsValue: context.propsValue, enabledAt }),+ store: context.store,+ isRepublish: context.isRepublish,+ });+ },+ async onDisable(context) {+ await odooPolling.onDisable({ store: context.store });+ },+ async run(context) {+ const enabledAt = await odooPolling.enabledAt({ store: context.store });+ return odooPolling.run({+ client: OdooClient.fromAuth({ auth: context.auth.props }),+ source: sourceOf({ propsValue: context.propsValue, enabledAt }),+ store: context.store,+ });+ },+ async test(context) {+ return odooPolling.test({ client: OdooClient.fromAuth({ auth: context.auth.props }), source: sourceOf({ propsValue: context.propsValue }) });+ },+});diff --git a/packages/pieces/community/odoo/test/fake-odoo.ts b/packages/pieces/community/odoo/test/fake-odoo.tsnew file mode 100644index 00000000000..03645159d52--- /dev/null+++ b/packages/pieces/community/odoo/test/fake-odoo.ts@@ -0,0 +1,211 @@+import { vi } from 'vitest';++export const fake = (() => {+ const state: FakeState = {+ calls: [],+ routes: new Map(),+ authUid: 2,+ version: { server_version: '18.0', server_serie: '18.0', protocol_version: 1 },+ };+ function client({ options, secure }: { options: ClientOptions; secure: boolean }) {+ return {+ methodCall(method: string, params: unknown[], cb: (err: unknown, value?: unknown) => void) {+ state.calls.push({ ...options, secure, method, params });+ try {+ if (method === 'authenticate') return cb(null, state.authUid);+ if (method === 'version') return cb(null, state.version);+ const call = toKwCall(params);+ const handler = state.routes.get(`${call.model}.${call.method}`) ?? state.routes.get(`*.${call.method}`);+ if (!handler) return cb({ faultCode: 1, faultString: `no fake route for ${call.model}.${call.method}` });+ return cb(null, handler(call));+ } catch (error) {+ return cb(error);+ }+ },+ };+ }+ return { state, client };+})();++vi.mock('xmlrpc', () => ({+ createClient: (options: ClientOptions) => fake.client({ options, secure: false }),+ createSecureClient: (options: ClientOptions) => fake.client({ options, secure: true }),+}));++export function resetFake() {+ fake.state.calls.length = 0;+ fake.state.routes.clear();+ fake.state.authUid = 2;+ fake.state.version = { server_version: '18.0', server_serie: '18.0', protocol_version: 1 };+}++export function route({ key, handler }: { key: string; handler: Route }) {+ fake.state.routes.set(key, handler);+}++export function fault(message: string): never {+ throw { faultCode: 1, faultString: `Traceback (most recent call last):\n File "x.py"\n${message}` };+}++export function userFault(message: string): never {+ throw { faultCode: 4, faultString: message };+}++export function kwCalls(): KwCall[] {+ return fake.state.calls.filter((c) => c.method === 'execute_kw').map((c) => toKwCall(c.params));+}++export function callsTo({ model, method }: { model: string; method: string }): KwCall[] {+ return kwCalls().filter((c) => c.model === model && c.method === method);+}++export function firstArgList(call: KwCall): unknown[] {+ const [first] = call.args;+ return Array.isArray(first) ? first : [];+}++export function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === 'object' && value !== null && !Array.isArray(value);+}++export function asRecord(value: unknown): Record<string, unknown> {+ if (!isRecord(value)) throw new Error(`expected an object, got ${JSON.stringify(value)}`);+ return value;+}++export function asRecords(value: unknown): Record<string, unknown>[] {+ if (!Array.isArray(value)) throw new Error(`expected a list, got ${JSON.stringify(value)}`);+ const records = value.filter(isRecord);+ if (records.length !== value.length) throw new Error('expected a list of objects');+ return records;+}++export const AUTH_PROPS = {+ base_url: 'https://acme.odoo.com',+ database: 'acme',+ username: '[email protected]',+ api_key: 'key-123',+};++export function auth(extra: Record<string, unknown> = {}) {+ return { type: 'CUSTOM_AUTH', props: { ...AUTH_PROPS, ...extra } };+}++export function fieldsOf(spec: Record<string, string>) {+ return Object.fromEntries(Object.entries(spec).map(([name, type]) => [name, { type, string: name }]));+}++export function evalDomain({ record, domain }: { record: Record<string, unknown>; domain: unknown[] }): boolean {+ let index = 0;+ const next = (): boolean => {+ const term = domain[index++];+ if (term === '&') return [next(), next()].every(Boolean);+ if (term === '|') return [next(), next()].some(Boolean);+ if (term === '!') return !next();+ if (!Array.isArray(term) || term.length !== 3) throw new Error(`fake domain term ${JSON.stringify(term)}`);+ const field = String(term[0]);+ const operator = String(term[1]);+ const value: unknown = term[2];+ const actual = record[field];+ if (operator === '=') return actual === value;+ if (operator === '!=') return actual !== value;+ if (operator === 'in') return Array.isArray(value) && setOf(value).has(actual);+ if (operator === 'not in') return Array.isArray(value) && !setOf(value).has(actual);+ if (actual === null || actual === undefined || actual === false) return false;+ const cmp = typeof actual === 'number' && typeof value === 'number' ? actual - value : String(actual).localeCompare(String(value));+ if (operator === '>') return cmp > 0;+ if (operator === '>=') return cmp >= 0;+ if (operator === '<') return cmp < 0;+ if (operator === '<=') return cmp <= 0;+ throw new Error(`fake domain operator ${operator}`);+ };+ const results: boolean[] = [];+ while (index < domain.length) results.push(next());+ return results.every(Boolean);+}++export function routeTable({ model, dateField, rows }: { model: string; dateField: string; rows: TableRow[] }) {+ const view = (row: TableRow) => ({ ...row.values, id: row.id, [dateField]: row.stamp });+ const matching = (call: KwCall) => rows.filter((row) => evalDomain({ record: view(row), domain: firstArgList(call) }));+ const sorted = (call: KwCall) => {+ const keys = String(call.kwargs['order'] ?? 'id asc').split(',').map((part) => part.trim().split(/\s+/));+ return [...matching(call)].sort((a, b) => {+ for (const [field, direction] of keys) {+ const left = view(a)[field];+ const right = view(b)[field];+ const cmp = typeof left === 'number' && typeof right === 'number' ? left - right : String(left) < String(right) ? -1 : String(left) > String(right) ? 1 : 0;+ if (cmp !== 0) return direction === 'desc' ? -cmp : cmp;+ }+ return 0;+ });+ };+ const limited = (call: KwCall) => {+ const limit = call.kwargs['limit'];+ return typeof limit === 'number' ? sorted(call).slice(0, limit) : sorted(call);+ };+ route({ key: `${model}.search`, handler: (call) => limited(call).map((row) => row.id) });+ route({+ key: `${model}.search_read`,+ handler: (call) => limited(call).map((row) => ({ ...row.values, id: row.id, [dateField]: row.stamp.slice(0, 19) })),+ });+}++export function memoryStore() {+ const data = new Map<string, unknown>();+ return {+ data,+ get: async (key: string) => (data.has(key) ? data.get(key) : null),+ put: async (key: string, value: unknown) => {+ data.set(key, value);+ return value;+ },+ delete: async (key: string) => {+ data.delete(key);+ },+ };+}++function setOf(list: unknown[]): Set<unknown> {+ const known = listSets.get(list);+ if (known) return known;+ const created = new Set(list);+ listSets.set(list, created);+ return created;+}++const listSets = new WeakMap<unknown[], Set<unknown>>();++function toKwCall(params: unknown[]): KwCall {+ const [, , , model, method, args, kwargs] = params;+ return {+ model: String(model),+ method: String(method),+ args: Array.isArray(args) ? args : [],+ kwargs: isRecord(kwargs) ? kwargs : {},+ raw: params,+ };+}++type ClientOptions = { host: string; port: number; path: string };++export type TableRow = { id: number; stamp: string; values: Record<string, unknown> };++type Route = (call: KwCall) => unknown;++type FakeState = {+ calls: RpcCall[];+ routes: Map<string, Route>;+ authUid: unknown;+ version: Record<string, unknown>;+};++export type RpcCall = {+ host: string;+ port: number;+ path: string;+ secure: boolean;+ method: string;+ params: unknown[];+};++export type KwCall = { model: string; method: string; args: unknown[]; kwargs: Record<string, unknown>; raw: unknown[] };diff --git a/packages/pieces/community/odoo/test/pr-a.test.ts b/packages/pieces/community/odoo/test/pr-a.test.tsnew file mode 100644index 00000000000..667fda9d099--- /dev/null+++ b/packages/pieces/community/odoo/test/pr-a.test.ts@@ -0,0 +1,1024 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { createMockActionContext, createMockPollingTriggerContext } from '@activepieces/pieces-framework';+import { asRecord, asRecords, auth, AUTH_PROPS, callsTo, evalDomain, fake, fault, fieldsOf, firstArgList, kwCalls, memoryStore, resetFake, route, routeTable } from './fake-odoo';+import createContact from '../src/lib/actions/create-contact';+import createCompany from '../src/lib/actions/create-company';+import getRecords from '../src/lib/actions/get-records';+import createRecord from '../src/lib/actions/create-record';+import customOdooApiCall from '../src/lib/actions/custom-api-call';+import { odooAuth } from '../src/lib/auth';+import { OdooClient, odooRpc } from '../src/lib/common/client';+import { odooDates, odooDomain, odooInput, odooOutput } from '../src/lib/common/values';+import { odooOperations } from '../src/lib/common/operations';+import { odooPolling } from '../src/lib/common/polling';+import { newRecordTrigger } from '../src/lib/triggers/new-record';+import { newOrUpdatedRecordTrigger } from '../src/lib/triggers/new-or-updated-record';+import { newSalesOrderTrigger } from '../src/lib/triggers/new-sales-order';+import { newContactTrigger } from '../src/lib/triggers/new-contact';+import { newLeadTrigger } from '../src/lib/triggers/new-lead';+import { runRecordActionAction } from '../src/lib/actions/run-record-action';+import { createSalesOrderAction } from '../src/lib/actions/create-sales-order';+import { findInvoicesAction } from '../src/lib/actions/find-invoices';+import { attachFileAction } from '../src/lib/actions/attach-file';+import { createdAttachmentOutputSchema, createdLeadOutputSchema, createdSaleOrderOutputSchema, saleOrderOutputSchema } from '../src/lib/output-schemas';+++beforeEach(() => resetFake());++describe('F1/F2: create_contact and create_company (old Odoo class)', () => {+ it('F1 sends the real phone and email, not the name', async () => {+ route({ key: 'res.partner.search', handler: () => [] });+ route({ key: 'res.partner.create', handler: () => [55] });+ const out = await createContact.run(actionCtx({ propsValue: { name: 'Jane', phone: '+1 555', email: '[email protected]', company: 'Acme', title: 'Buyer' } }));+ const [create] = callsTo({ model: 'res.partner', method: 'create' });+ expect(create.args).toEqual([[{ name: 'Jane', phone: '+1 555', email: '[email protected]', company_name: 'Acme', function: 'Buyer' }]]);+ expect(out).toBe('Contact 55 created!');+ });++ it('F2 awaits the write and F2b never sends company_id on update', async () => {+ route({ key: 'res.partner.search', handler: () => [7] });+ route({ key: 'res.partner.write', handler: () => true });+ const out = await createContact.run(actionCtx({ propsValue: { name: 'Jane', phone: 'p', email: 'e', company: 'Acme', title: 't' } }));+ const [write] = callsTo({ model: 'res.partner', method: 'write' });+ expect(write.args[0]).toBe(7);+ expect(write.args[1]).not.toHaveProperty('company_id');+ expect(out).toBe('Contact 7 created!');+ });++ it('F2 a failed write is no longer reported as created (still returned, not thrown)', async () => {+ route({ key: 'res.partner.search', handler: () => [7] });+ route({ key: 'res.partner.write', handler: () => fault('ValidationError: bad email') });+ await expect(createCompany.run(actionCtx({ propsValue: { name: 'Acme', phone: 'p', email: 'e' } }))).resolves.toBe('Error');+ });+});++describe('F3: custom API call', () => {+ it('write sends values positionally', async () => {+ route({ key: 'res.partner.write', handler: () => true });+ await customOdooApiCall.run(actionCtx({ propsValue: { model: 'res.partner', method: 'write', method_params: { record_id: 5, values: { phone: '1' } } } }));+ const [call] = callsTo({ model: 'res.partner', method: 'write' });+ expect(call.raw.slice(5)).toEqual([[[5], { phone: '1' }]]);+ });++ it('fields_get sends empty args plus attributes', async () => {+ route({ key: 'res.partner.fields_get', handler: () => ({ name: { type: 'char' } }) });+ await customOdooApiCall.run(actionCtx({ propsValue: { model: 'res.partner', method: 'fields_get', method_params: { attributes: ['string', 'type'] } } }));+ const [call] = callsTo({ model: 'res.partner', method: 'fields_get' });+ expect(call.raw.slice(5)).toEqual([[], { attributes: ['string', 'type'] }]);+ });+});++describe('get_records order prop', () => {+ it('request is unchanged when order is empty', async () => {+ route({ key: 'res.partner.search_read', handler: () => [{ id: 1 }, { id: 2 }] });+ await getRecords.run(actionCtx({ propsValue: { model: 'res.partner', domain: [['is_company', '=', true]], fields: ['name'], offset: 0, limit: 5 } }));+ expect(callsTo({ model: 'res.partner', method: 'search_read' })[0].raw.slice(5)).toEqual([[[['is_company', '=', true]], ['name'], 0, 5]]);+ });++ it('appends order when set', async () => {+ route({ key: 'res.partner.search_read', handler: () => [{ id: 1 }, { id: 2 }] });+ await getRecords.run(actionCtx({ propsValue: { model: 'res.partner', domain: [], fields: ['name'], offset: 0, limit: 5, order: 'id desc' } }));+ expect(callsTo({ model: 'res.partner', method: 'search_read' })[0].raw.slice(5)).toEqual([[[], ['name'], 0, 5, 'id desc']]);+ });+});++describe('F4: optional port', () => {+ it('defaults to 443 for old actions, even with a port in the URL (compat)', async () => {+ route({ key: 'res.partner.create', handler: () => 9 });+ await createRecord.run(actionCtx({ propsValue: { model: 'res.partner', fields: { name: 'x' } }, extra: { base_url: 'http://localhost:8069' } }));+ expect(fake.state.calls.every((c) => c.port === 443 && c.host === 'localhost' && c.secure === false)).toBe(true);+ });++ it('uses the port prop when set, for old actions and the new client', async () => {+ route({ key: 'res.partner.create', handler: () => 9 });+ await createRecord.run(actionCtx({ propsValue: { model: 'res.partner', fields: { name: 'x' } }, extra: { base_url: 'http://localhost', port: 8069 } }));+ expect(fake.state.calls.every((c) => c.port === 8069)).toBe(true);+ resetFake();+ await OdooClient.fromAuth({ auth: { ...AUTH_PROPS, port: '8443' } }).authenticate();+ expect(fake.state.calls[0]).toMatchObject({ port: 8443, secure: true, host: 'acme.odoo.com', path: '/xmlrpc/2/common' });+ });++ it('validates the port and the URL', () => {+ expect(odooRpc.resolvePort(undefined)).toBe(443);+ expect(odooRpc.resolvePort(null)).toBe(443);+ expect(odooRpc.resolvePort('')).toBe(443);+ expect(() => odooRpc.resolvePort(70000)).toThrow(/Invalid Odoo port/);+ expect(() => odooRpc.resolvePort('abc')).toThrow(/Invalid Odoo port/);+ expect(() => odooRpc.resolveConnection({ ...AUTH_PROPS, base_url: 'ftp://x' })).toThrow(/https/);+ expect(() => odooRpc.resolveConnection({ ...AUTH_PROPS, base_url: 'https://u:[email protected]' })).toThrow(/user name/);+ });++ it('validate() refuses a URL with a port and points to the Port field', async () => {+ await expect(odooAuth.validate?.({ auth: { ...AUTH_PROPS, base_url: 'http://localhost:8069' } })).resolves.toEqual({+ valid: false,+ error: 'Remove ":8069" from the URL and enter 8069 in the Port field instead (a port in the URL is ignored).',+ });+ expect(fake.state.calls).toHaveLength(0);+ await expect(odooAuth.validate?.({ auth: { ...AUTH_PROPS, base_url: 'https://acme.odoo.com/', port: 8443 } })).resolves.toEqual({ valid: true });+ });++ it('validate() reads the port from the raw URL text, including protocol-default ports and IPv6', async () => {+ const refused = (port: string) => ({+ valid: false,+ error: `Remove ":${port}" from the URL and enter ${port} in the Port field instead (a port in the URL is ignored).`,+ });+ for (const [url, port] of [['http://host:80', '80'], ['https://host:443', '443'], ['https://host:8069', '8069'], ['http://[::1]:8069/odoo', '8069'], ['acme.odoo.com:443', '443'], ['https:/x.com:8069', '8069'], ['https:x.com:8069', '8069'], ['localhost:8069/odoo', '8069']]) {+ await expect(odooAuth.validate?.({ auth: { ...AUTH_PROPS, base_url: url } })).resolves.toEqual(refused(port));+ }+ expect(fake.state.calls).toHaveLength(0);+ for (const url of ['https://acme.odoo.com', 'https://acme.odoo.com/odoo?db=x:1', 'https://[::1]/', 'https://x.com\\:8069']) {+ await expect(odooAuth.validate?.({ auth: { ...AUTH_PROPS, base_url: url } })).resolves.toEqual({ valid: true });+ }+ });++ it('validate() uses the port and reports bad logins as invalid credentials', async () => {+ fake.state.authUid = false;+ const bad = await odooAuth.validate?.({ auth: { ...AUTH_PROPS, port: 8069 } });+ expect(bad).toEqual({ valid: false, error: expect.stringMatching(/Invalid credentials/) });+ expect(fake.state.calls[0].port).toBe(8069);+ fake.state.authUid = 2;+ await expect(odooAuth.validate?.({ auth: AUTH_PROPS })).resolves.toEqual({ valid: true });+ expect(fake.state.calls[1].port).toBe(443);+ });+});++describe('new client request shape', () => {+ it('never sends undefined and never unwraps arrays', async () => {+ route({ key: 'res.partner.search_read', handler: () => [{ id: 1 }] });+ const client = OdooClient.fromAuth({ auth: AUTH_PROPS });+ const rows = await client.call({ model: 'res.partner', method: 'search_read', args: [[]], kwargs: { fields: ['id'], limit: undefined, order: undefined } });+ expect(rows).toEqual([{ id: 1 }]);+ expect(kwCalls()[0].kwargs).toEqual({ fields: ['id'] });+ expect(() => odooRpc.cleanValue({ a: Number.NaN })).toThrow();+ expect(odooRpc.cleanValue([1, undefined, { b: undefined, c: 2 }])).toEqual([1, null, { c: 2 }]);+ });++ it('throws a short Odoo error instead of returning it', async () => {+ route({ key: 'res.partner.read', handler: () => fault('odoo.exceptions.MissingError: Record does not exist or has been deleted.') });+ const client = OdooClient.fromAuth({ auth: AUTH_PROPS });+ await expect(client.call({ model: 'res.partner', method: 'read', args: [[99]] })).rejects.toThrow(+ 'Odoo res.partner.read failed: odoo.exceptions.MissingError: Record does not exist or has been deleted.',+ );+ });++ it('treats "cannot marshal None" as success only where allowed', async () => {+ route({ key: 'crm.lead.action_archive', handler: () => fault('TypeError: cannot marshal None unless allow_none is enabled') });+ const client = OdooClient.fromAuth({ auth: AUTH_PROPS });+ await expect(client.callAllowNone({ model: 'crm.lead', method: 'action_archive', args: [[1]] })).resolves.toEqual({ value: null, returnedNone: true });+ await expect(client.call({ model: 'crm.lead', method: 'action_archive', args: [[1]] })).rejects.toThrow(/cannot marshal None/);+ const out = await runRecordActionAction.run(actionCtx({ propsValue: { model: 'crm.lead', record_id: 1, method: 'action_archive' } }));+ expect(out).toMatchObject({ returned_none: true, result: null, record_ids: [1] });+ });++ it('refuses private, odd and generic CRUD or environment method names, naming the dedicated action', async () => {+ const actions = { delete: 'Delete Record', update: 'Custom Update Record', create: 'Custom Create Record', read: 'Get Record' };+ expect(() => odooInput.toMethodName({ value: '_compute', actions })).toThrow(/"_"/);+ expect(() => odooInput.toMethodName({ value: 'a b', actions })).toThrow();+ expect(odooInput.toMethodName({ value: 'action_confirm', actions })).toBe('action_confirm');+ expect(() => odooInput.toMethodName({ value: 'unlink', actions })).toThrow('"unlink" cannot be called here. Use Delete Record to delete records.');+ expect(() => odooInput.toMethodName({ value: 'write', actions })).toThrow('Use Custom Update Record to change field values.');+ expect(() => odooInput.toMethodName({ value: 'create', actions })).toThrow('Use Custom Create Record to create records.');+ expect(() => odooInput.toMethodName({ value: 'copy', actions })).toThrow(/Use Custom Create Record/);+ expect(() => odooInput.toMethodName({ value: 'browse', actions })).toThrow('Use Get Record to read records.');+ expect(() => odooInput.toMethodName({ value: 'update', actions })).toThrow('"update" cannot be called here. Use Custom Update Record to change field values.');+ expect(() => odooInput.toMethodName({ value: 'name_create', actions })).toThrow('"name_create" cannot be called here. Use Custom Create Record to create records.');+ expect(() => odooInput.toMethodName({ value: 'load', actions })).toThrow('"load" cannot be called here. Use Custom Create Record to create records.');+ expect(() => odooInput.toMethodName({ value: 'Web_Save', actions })).toThrow('"Web_Save" cannot be called here. Use Custom Update Record to change field values, or Custom Create Record to create records.');+ expect(odooInput.toMethodName({ value: 'name_search', actions })).toBe('name_search');+ for (const value of ['sudo', 'with_user', 'with_context', 'with_env', 'SUDO']) {+ expect(() => odooInput.toMethodName({ value, actions })).toThrow(/changes the user or environment/);+ }+ await expect(runRecordActionAction.run(actionCtx({ propsValue: { model: 'res.partner', record_id: 1, method: 'unlink' } }))).rejects.toThrow('Use Delete Record to delete records.');+ expect(kwCalls()).toHaveLength(0);+ });+});++describe('domains', () => {+ it('parses arrays and JSON strings and rejects bad shapes', () => {+ expect(odooDomain.parseDomain({ value: '[["a","=",1],"|",["b","=",2],["c","=",3]]' })).toEqual([['a', '=', 1], '|', ['b', '=', 2], ['c', '=', 3]]);+ expect(odooDomain.parseDomain({ value: undefined })).toEqual([]);+ expect(() => odooDomain.parseDomain({ value: '{"a":1}' })).toThrow(/list/);+ expect(() => odooDomain.parseDomain({ value: [['a', '=']] })).toThrow(/item 1/);+ expect(() => odooDomain.parseDomain({ value: 'not json' })).toThrow(/JSON/);+ });++ it('ANDs domains that use implicit AND and prefix operators', () => {+ const user = odooDomain.parseDomain({ value: [['a', '=', 1], ['b', '=', 2]] });+ const cursor = ['|', ['d', '>', 'x'], '&', ['d', '=', 'x'], ['id', '>', 3]];+ const out = odooDomain.andDomains([user, [...cursor]]);+ expect(out).toEqual(['&', '&', ['a', '=', 1], ['b', '=', 2], '|', ['d', '>', 'x'], '&', ['d', '=', 'x'], ['id', '>', 3]]);+ expect(odooDomain.andDomains([[], [['a', '=', 1]]])).toEqual([['a', '=', 1]]);+ expect(odooDomain.orConditions([['a', '=', 1], ['b', '=', 2], ['c', '=', 3]])).toEqual(['|', '|', ['a', '=', 1], ['b', '=', 2], ['c', '=', 3]]);+ });++ it('builds the invoice domain', () => {+ const domain = odooOperations.invoiceDomain({+ move_types: ['out_invoice'],+ state: 'posted',+ payment_states: ['not_paid', 'partial'],+ partner_id: 7,+ due_date_to: '2026-09-28T23:00:00Z',+ number: 'INV/2026',+ });+ expect(domain).toEqual([+ '&', '&', '&', '&', '&',+ ['move_type', 'in', ['out_invoice']],+ ['state', '=', 'posted'],+ ['payment_state', 'in', ['not_paid', 'partial']],+ ['partner_id', 'child_of', 7],+ ['invoice_date_due', '<=', '2026-09-28'],+ '|', '|', ['name', 'ilike', 'INV/2026'], ['ref', 'ilike', 'INV/2026'], ['payment_reference', 'ilike', 'INV/2026'],+ ]);+ });+});++describe('dates are UTC regardless of the process time zone', () => {+ it('runs under a non-UTC TZ', () => {+ expect(new Date(Date.UTC(2026, 0, 1)).getTimezoneOffset()).not.toBe(0);+ });++ it('formats and parses Odoo naive UTC strings', () => {+ const epoch = Date.UTC(2026, 8, 29, 7, 5, 9);+ expect(odooDates.toOdooDatetime(epoch)).toBe('2026-09-29 07:05:09');+ expect(odooDates.parseOdooDatetime('2026-09-29 07:05:09')).toBe(epoch);+ expect(odooDates.inputToOdooDatetime({ value: '2026-09-29T09:05:09+02:00', label: 'x' })).toBe('2026-09-29 07:05:09');+ expect(odooDates.inputToOdooDatetime({ value: '2026-09-29 07:05:09', label: 'x' })).toBe('2026-09-29 07:05:09');+ expect(odooDates.inputToOdooDate({ value: '2026-09-29T23:30:00.000Z', label: 'x' })).toBe('2026-09-29');+ expect(() => odooDates.inputToOdooDatetime({ value: 'tomorrow', label: 'When' })).toThrow(/When/);+ });+});++describe('output normalisation', () => {+ it('splits many2one, keeps booleans, maps false to null', () => {+ const fields = fieldsOf({ partner_id: 'many2one', is_company: 'boolean', email: 'char', tag_ids: 'many2many' });+ expect(+ odooOutput.normalizeRecord({ record: { id: 1, partner_id: [7, 'Acme'], is_company: false, email: false, tag_ids: [1, 2] }, fields }),+ ).toEqual({ id: 1, partner_id: 7, partner_id_name: 'Acme', is_company: false, email: null, tag_ids: [1, 2] });+ expect(odooOutput.normalizeRecord({ record: { partner_id: false }, fields })).toEqual({ partner_id: null, partner_id_name: null });+ });+});++describe('polling triggers: 5-minute look-back cursor', () => {+ const partnerFields = fieldsOf({ name: 'char', active: 'boolean', create_date: 'datetime', write_date: 'datetime', image_1920: 'binary' });+ const orderFields = fieldsOf({ name: 'char', state: 'selection', date_order: 'datetime', create_date: 'datetime', write_date: 'datetime' });+ const leadFields = fieldsOf({ name: 'char', type: 'selection', team_id: 'many2one', date_conversion: 'datetime', create_date: 'datetime', write_date: 'datetime' });+ const S = '2026-09-29 10:00:00';+ const LOOK = '2026-09-29 09:55:00';+ const shuffledMicros = shuffle({ values: Array.from({ length: 6000 }, (_, i) => i), seed: 42 });++ afterEach(() => vi.useRealTimers());++ it('onEnable takes the cursor from the newest Odoo record, with every id in that second as ranges and a floor at the newest older row', async () => {+ route({ key: 'res.partner.fields_get', handler: () => partnerFields });+ routeTable({ model: 'res.partner', dateField: 'create_date', rows: [+ { id: 44, stamp: `${S}.100000`, values: {} },+ { id: 40, stamp: `${S}.900000`, values: {} },+ { id: 12, stamp: '2026-09-29 09:59:59.000000', values: {} },+ ] });+ const store = memoryStore();+ await newRecordTrigger.onEnable(triggerCtx({ propsValue: { model: 'res.partner' }, store }));+ expect(store.data.get(odooPolling.CURSOR_KEY)).toEqual({+ date: S,+ floor: { date: '2026-09-29 09:59:59', id: 12 },+ emitted: [{ date: S, ranges: [[40, 40], [44, 44]] }],+ });+ const reads = callsTo({ model: 'res.partner', method: 'search_read' });+ expect(reads[0].kwargs).toMatchObject({ order: 'create_date desc, id desc', limit: 1 });+ expect(reads[1].args[0]).toEqual([['create_date', '<', S]]);+ const [ids] = callsTo({ model: 'res.partner', method: 'search' });+ expect(ids.args[0]).toEqual(['&', '&', ['create_date', '>=', S], ['create_date', '<', '2026-09-29 10:00:01'], ['id', '>', 0]]);+ expect(ids.kwargs).toMatchObject({ order: 'id asc', limit: odooPolling.SEED_PAGE_SIZE });+ expect(ids.kwargs['fields']).toBeUndefined();+ });++ it('keeps the cursor on republish', async () => {+ const store = memoryStore();+ await store.put(odooPolling.CURSOR_KEY, { date: '2026-01-01 00:00:00', floor: null, emitted: [{ date: '2026-01-01 00:00:00', ranges: [[1, 1]] }] });+ await newRecordTrigger.onEnable(triggerCtx({ propsValue: { model: 'res.partner' }, store, isRepublish: true }));+ expect(kwCalls()).toHaveLength(0);+ });++ it('reads 5 minutes back, skips what it already emitted in that window, and orders by date then id', async () => {+ route({ key: 'res.partner.fields_get', handler: () => partnerFields });+ routeTable({ model: 'res.partner', dateField: 'create_date', rows: [{ id: 9, stamp: `${S}.2`, values: { is_company: true } }] });+ const store = memoryStore();+ await store.put(odooPolling.CURSOR_KEY, { date: S, floor: null, emitted: [{ date: S, ranges: [[5, 5], [7, 7]] }] });+ const out = asRecords(await newRecordTrigger.run(triggerCtx({ propsValue: { model: 'res.partner', domain: [['is_company', '=', true]] }, store })));+ expect(out.map((r) => r['id'])).toEqual([9]);+ const [call] = callsTo({ model: 'res.partner', method: 'search_read' });+ expect(call.args[0]).toEqual([+ '&',+ ['is_company', '=', true],+ '&',+ ['create_date', '>=', LOOK],+ '|', '|', ['create_date', '<', S], ['create_date', '>=', '2026-09-29 10:00:01'], ['id', 'not in', [5, 7]],+ ]);+ expect(call.kwargs).toMatchObject({ order: 'create_date asc, id asc', limit: 100 });+ expect(call.kwargs['fields']).not.toContain('image_1920');+ expect(store.data.get(odooPolling.CURSOR_KEY)).toEqual({ date: S, floor: null, emitted: [{ date: S, ranges: [[5, 5], [7, 7], [9, 9]] }] });+ });++ it('emits a row stamped 90 s in the past that commits after the cursor moved, exactly once', async () => {+ route({ key: 'res.partner.fields_get', handler: () => partnerFields });+ const rows = [{ id: 50, stamp: `${S}.100000`, values: { name: 'emitted before' } }];+ routeTable({ model: 'res.partner', dateField: 'create_date', rows });+ const store = memoryStore();+ await store.put(odooPolling.CURSOR_KEY, { date: S, floor: null, emitted: [{ date: S, ranges: [[50, 50]] }] });+ await expect(newRecordTrigger.run(triggerCtx({ propsValue: { model: 'res.partner' }, store }))).resolves.toEqual([]);+ rows.push({ id: 49, stamp: '2026-09-29 09:58:30.500000', values: { name: 'late commit' } });+ const late = asRecords(await newRecordTrigger.run(triggerCtx({ propsValue: { model: 'res.partner' }, store })));+ expect(late.map((r) => r['id'])).toEqual([49]);+ expect(readStoredCursor(store).date).toBe(S);+ await expect(newRecordTrigger.run(triggerCtx({ propsValue: { model: 'res.partner' }, store }))).resolves.toEqual([]);+ });++ it('emits a same-second update to a LOWER id exactly once', async () => {+ route({ key: 'res.partner.fields_get', handler: () => partnerFields });+ const rows = [+ { id: 3, stamp: '2026-09-29 09:00:00.000000', values: { name: 'old' } },+ { id: 50, stamp: `${S}.100000`, values: { name: 'emitted before' } },+ ];+ routeTable({ model: 'res.partner', dateField: 'write_date', rows });+ const store = memoryStore();+ await store.put(odooPolling.CURSOR_KEY, { date: S, floor: null, emitted: [{ date: S, ranges: [[50, 50]] }] });+ rows[0].stamp = `${S}.800000`;+ const first = asRecords(await newOrUpdatedRecordTrigger.run(triggerCtx({ propsValue: { model: 'res.partner' }, store })));+ expect(first.map((r) => r['id'])).toEqual([3]);+ expect(readStoredCursor(store).emitted).toEqual([{ date: S, ranges: [[3, 3], [50, 50]] }]);+ await expect(newOrUpdatedRecordTrigger.run(triggerCtx({ propsValue: { model: 'res.partner' }, store }))).resolves.toEqual([]);+ });++ it('emits a record again for a later change, and once per change', async () => {+ route({ key: 'res.partner.fields_get', handler: () => partnerFields });+ const rows = [{ id: 7, stamp: `${S}.100000`, values: {} }];+ routeTable({ model: 'res.partner', dateField: 'write_date', rows });+ const store = memoryStore();+ await store.put(odooPolling.CURSOR_KEY, { date: S, floor: null, emitted: [{ date: S, ranges: [[7, 7]] }] });+ rows[0].stamp = '2026-09-29 10:02:00.000000';+ const out = asRecords(await newOrUpdatedRecordTrigger.run(triggerCtx({ propsValue: { model: 'res.partner' }, store })));+ expect(out.map((r) => r['id'])).toEqual([7]);+ expect(readStoredCursor(store)).toEqual({+ date: '2026-09-29 10:02:00',+ floor: null,+ emitted: [{ date: S, ranges: [[7, 7]] }, { date: '2026-09-29 10:02:00', ranges: [[7, 7]] }],+ });+ await expect(newOrUpdatedRecordTrigger.run(triggerCtx({ propsValue: { model: 'res.partner' }, store }))).resolves.toEqual([]);+ });++ it('does not lose or repeat two records of the same second split by a page boundary', async () => {+ route({ key: 'res.partner.fields_get', handler: () => partnerFields });+ routeTable({ model: 'res.partner', dateField: 'create_date', rows: [+ { id: 1, stamp: '2026-09-29 09:59:59.000000', values: {} },+ { id: 30, stamp: `${S}.100000`, values: {} },+ { id: 20, stamp: `${S}.700000`, values: {} },+ ] });+ const source = { model: 'res.partner', dateField: 'create_date', domain: [] };+ const client = OdooClient.fromAuth({ auth: AUTH_PROPS });+ const start = { date: '2026-09-29 09:00:00', floor: null, emitted: [] };+ const first = await odooPolling.pollAfter({ client, source, cursor: start, pageSize: 2 });+ expect(first.records.map((r) => r['id'])).toEqual([1, 20, 30]);+ expect(first.cursor).toEqual({+ date: S,+ floor: null,+ emitted: [{ date: '2026-09-29 09:59:59', ranges: [[1, 1]] }, { date: S, ranges: [[20, 20], [30, 30]] }],+ });+ const again = await odooPolling.pollAfter({ client, source, cursor: first.cursor, pageSize: 2 });+ expect(again.records).toEqual([]);+ expect(again.cursor).toEqual(first.cursor);+ });++ it('emits a 120-record burst in one second once, across pages, and re-polls to 0', async () => {+ route({ key: 'res.partner.fields_get', handler: () => partnerFields });+ const rows = Array.from({ length: 120 }, (_, i) => ({ id: 1000 - i, stamp: `${S}.${String(i).padStart(6, '0')}`, values: { name: `bulk ${i}` } }));+ routeTable({ model: 'res.partner', dateField: 'create_date', rows });+ const store = memoryStore();+ await store.put(odooPolling.CURSOR_KEY, { date: '2026-09-29 09:00:00', floor: null, emitted: [] });+ const first = asRecords(await newRecordTrigger.run(triggerCtx({ propsValue: { model: 'res.partner' }, store })));+ expect(first.map((r) => r['id'])).toEqual(rows.map((r) => r.id).reverse());+ expect(callsTo({ model: 'res.partner', method: 'search_read' }).map((call) => call.kwargs['order'])).toEqual(['create_date asc, id asc', 'id asc', 'id asc', 'create_date asc, id asc', 'create_date desc, id desc']);+ const cursor = readStoredCursor(store);+ expect(cursor.date).toBe(S);+ expect(cursor.emitted).toEqual([{ date: S, ranges: [[881, 1000]] }]);+ await expect(newRecordTrigger.run(triggerCtx({ propsValue: { model: 'res.partner' }, store }))).resolves.toEqual([]);+ });++ it('never re-emits records whose stored date has microseconds, and stops after 5 pages of 100', async () => {+ route({ key: 'res.partner.fields_get', handler: () => partnerFields });+ const rows = [+ ...Array.from({ length: 120 }, (_, i) => ({ id: 10 + i, stamp: `${S}.500000`, values: { name: `bulk ${i}` } })),+ { id: 7, stamp: `${S}.900000`, values: { name: 'late commit, lower id' } },+ { id: 200, stamp: '2026-09-29 10:00:01.100000', values: { name: 'next second' } },+ ...Array.from({ length: 430 }, (_, i) => ({ id: 300 + i, stamp: `2026-09-29 1${1 + Math.floor(i / 60)}:${String(Math.floor(i / 60)).padStart(2, '0')}:${String(i % 60).padStart(2, '0')}.${String(i).padStart(6, '0')}`, values: { name: `spread ${i}` } })),+ ];+ routeTable({ model: 'res.partner', dateField: 'create_date', rows });+ const store = memoryStore();+ await store.put(odooPolling.CURSOR_KEY, { date: '1970-01-01 00:00:00', floor: null, emitted: [] });+ const first = asRecords(await newRecordTrigger.run(triggerCtx({ propsValue: { model: 'res.partner' }, store })));+ expect(first.slice(0, 121).map((r) => r['id'])).toEqual([7, ...rows.slice(0, 120).map((r) => r.id)]);+ expect(first.length).toBeLessThanOrEqual(500);+ expect(callsTo({ model: 'res.partner', method: 'search_read' }).length).toBeLessThanOrEqual(10);+ const second = asRecords(await newRecordTrigger.run(triggerCtx({ propsValue: { model: 'res.partner' }, store })));+ const ids = [...first, ...second].map((r) => r['id']);+ expect(new Set(ids).size).toBe(ids.length);+ expect(new Set(ids)).toEqual(new Set(rows.map((r) => r.id)));+ await expect(newRecordTrigger.run(triggerCtx({ propsValue: { model: 'res.partner' }, store }))).resolves.toEqual([]);+ });++ it('emits 6,000 rows of one second, updated in DESCENDING id order across several polls, exactly once with few ranges', async () => {+ route({ key: 'res.partner.fields_get', handler: () => partnerFields });+ const rows = Array.from({ length: 6000 }, (_, i) => ({ id: i + 1, stamp: '2026-09-29 09:00:00.000000', values: {} }));+ routeTable({ model: 'res.partner', dateField: 'write_date', rows });+ const store = memoryStore();+ await newOrUpdatedRecordTrigger.onEnable(triggerCtx({ propsValue: { model: 'res.partner' }, store }));+ expect(storedSeconds(store)).toEqual([{ date: '2026-09-29 09:00:00', ranges: [[1, 6000]] }]);+ const seen: unknown[] = [];+ let widest = 0;+ for (let batch = 0; batch < 6; batch++) {+ for (let id = 6000 - batch * 1000; id > 5000 - batch * 1000; id--) rows[id - 1].stamp = `${S}.${String(6000 - id).padStart(6, '0')}`;+ for (let poll = 0; poll < 10; poll++) {+ const out = asRecords(await newOrUpdatedRecordTrigger.run(triggerCtx({ propsValue: { model: 'res.partner' }, store })));+ widest = Math.max(widest, storedRangeCount(store));+ if (out.length === 0) break;+ seen.push(...out.map((r) => r['id']));+ }+ }+ expect(seen).toHaveLength(6000);+ expect(new Set(seen).size).toBe(6000);+ expect(widest).toBeLessThanOrEqual(3);+ expect(readStoredCursor(store)).toEqual({ date: S, floor: null, emitted: [{ date: S, ranges: [[1, 6000]] }] });+ });++ it('does not replay a 6,000-row bulk import of the newest second at enable, then emits the next record once', async () => {+ route({ key: 'res.partner.fields_get', handler: () => partnerFields });+ const rows = [+ { id: 1, stamp: '2026-09-29 09:58:00.000000', values: {} },+ ...Array.from({ length: 6000 }, (_, i) => ({ id: i + 2, stamp: `${S}.${String(i).padStart(6, '0')}`, values: {} })),+ ];+ routeTable({ model: 'res.partner', dateField: 'create_date', rows });+ const store = memoryStore();+ await newRecordTrigger.onEnable(triggerCtx({ propsValue: { model: 'res.partner' }, store }));+ expect(readStoredCursor(store)).toEqual({ date: S, floor: { date: '2026-09-29 09:58:00', id: 1 }, emitted: [{ date: S, ranges: [[2, 6001]] }] });+ expect(callsTo({ model: 'res.partner', method: 'search' })).toHaveLength(2);+ await expect(newRecordTrigger.run(triggerCtx({ propsValue: { model: 'res.partner' }, store }))).resolves.toEqual([]);+ rows.push({ id: 6002, stamp: `${S}.999999`, values: {} });+ const next = asRecords(await newRecordTrigger.run(triggerCtx({ propsValue: { model: 'res.partner' }, store })));+ expect(next.map((r) => r['id'])).toEqual([6002]);+ await expect(newRecordTrigger.run(triggerCtx({ propsValue: { model: 'res.partner' }, store }))).resolves.toEqual([]);+ });++ it('seeds from the newest row of the model when the filter matches nothing at enable, so an old quotation confirmed later does not fire as new', async () => {+ route({ key: 'sale.order.fields_get', handler: () => orderFields });+ const rows = [+ { id: 1, stamp: '2026-09-20 08:00:00.000000', values: { state: 'draft' } },+ { id: 2, stamp: `${S}.400000`, values: { state: 'draft' } },+ ];+ routeTable({ model: 'sale.order', dateField: 'create_date', rows });+ const store = memoryStore();+ const propsValue = { model: 'sale.order', domain: [['state', '=', 'sale']] };+ await newRecordTrigger.onEnable(triggerCtx({ propsValue, store }));+ expect(readStoredCursor(store)).toEqual({ date: S, floor: { date: '2026-09-20 08:00:00', id: 1 }, emitted: [{ date: S, ranges: [[2, 2]] }] });+ rows[0].values = { state: 'sale' };+ await expect(newRecordTrigger.run(triggerCtx({ propsValue, store }))).resolves.toEqual([]);+ rows.push({ id: 3, stamp: '2026-09-29 10:01:00.000000', values: { state: 'sale' } });+ const next = asRecords(await newRecordTrigger.run(triggerCtx({ propsValue, store })));+ expect(next.map((r) => r['id'])).toEqual([3]);+ await expect(newRecordTrigger.run(triggerCtx({ propsValue, store }))).resolves.toEqual([]);+ });++ it('seeds from the newest row of the model even when older rows match the filter, so drafts created after the last match and confirmed later do not fire', async () => {+ route({ key: 'sale.order.fields_get', handler: () => orderFields });+ const rows = [+ { id: 1, stamp: '2026-09-01 08:00:00.000000', values: { state: 'sale' } },+ ...Array.from({ length: 300 }, (_, i) => ({ id: 2 + i, stamp: `2026-09-${10 + (i % 18)} 08:00:00.${String(i).padStart(6, '0')}`, values: { state: 'draft' } })),+ ];+ routeTable({ model: 'sale.order', dateField: 'create_date', rows });+ const store = memoryStore();+ const propsValue = { model: 'sale.order', domain: [['state', '=', 'sale']] };+ await newRecordTrigger.onEnable(triggerCtx({ propsValue, store }));+ expect(readStoredCursor(store).date).toBe('2026-09-27 08:00:00');+ rows.forEach((row) => (row.values = { state: 'sale' }));+ await expect(newRecordTrigger.run(triggerCtx({ propsValue, store }))).resolves.toEqual([]);+ rows.push({ id: 400, stamp: `${S}.100000`, values: { state: 'sale' } });+ const next = asRecords(await newRecordTrigger.run(triggerCtx({ propsValue, store })));+ expect(next.map((r) => r['id'])).toEqual([400]);+ });++ it('moves the cursor to the newest row of the model after a poll that read everything, so a lead moved into the team later does not fire', async () => {+ route({ key: 'crm.lead.fields_get', handler: () => leadFields });+ const rows = [+ { id: 1, stamp: '2026-09-01 08:00:00.000000', values: { type: 'lead', team_id: 2 } },+ { id: 2, stamp: '2026-09-20 08:00:00.000000', values: { type: 'lead', team_id: 1 } },+ ];+ routeTable({ model: 'crm.lead', dateField: 'create_date', rows });+ const store = memoryStore();+ const propsValue = { lead_type: 'lead', team_id: 2 };+ await newLeadTrigger.onEnable(triggerCtx({ propsValue, store }));+ rows[1].values = { type: 'lead', team_id: 2 };+ await expect(newLeadTrigger.run(triggerCtx({ propsValue, store }))).resolves.toEqual([]);+ rows.push({ id: 3, stamp: `${S}.100000`, values: { type: 'lead', team_id: 1 } });+ await expect(newLeadTrigger.run(triggerCtx({ propsValue, store }))).resolves.toEqual([]);+ expect(readStoredCursor(store).date).toBe(S);+ rows.push({ id: 4, stamp: '2026-09-29 10:06:00.000000', values: { type: 'lead', team_id: 1 } });+ await expect(newLeadTrigger.run(triggerCtx({ propsValue, store }))).resolves.toEqual([]);+ expect(readStoredCursor(store).date).toBe('2026-09-29 10:06:00');+ rows[2].values = { type: 'lead', team_id: 2 };+ await expect(newLeadTrigger.run(triggerCtx({ propsValue, store }))).resolves.toEqual([]);+ rows.push({ id: 5, stamp: '2026-09-29 10:07:00.000000', values: { type: 'lead', team_id: 2 } });+ const next = asRecords(await newLeadTrigger.run(triggerCtx({ propsValue, store })));+ expect(next.map((r) => r['id'])).toEqual([5]);+ });++ it('keeps the empty cursor when the model has no rows at enable', async () => {+ route({ key: 'sale.order.fields_get', handler: () => orderFields });+ routeTable({ model: 'sale.order', dateField: 'create_date', rows: [] });+ const store = memoryStore();+ await newRecordTrigger.onEnable(triggerCtx({ propsValue: { model: 'sale.order', domain: [['state', '=', 'sale']] }, store }));+ expect(readStoredCursor(store)).toEqual({ date: '1970-01-01 00:00:00', floor: null, emitted: [] });+ });++ it('floors at the max id when the newest second alone has more separate ranges than the cap at enable', async () => {+ route({ key: 'res.partner.fields_get', handler: () => partnerFields });+ const rows = Array.from({ length: 6000 }, (_, i) => ({ id: 2 * i + 1, stamp: `${S}.000000`, values: {} }));+ routeTable({ model: 'res.partner', dateField: 'create_date', rows });+ const store = memoryStore();+ await newRecordTrigger.onEnable(triggerCtx({ propsValue: { model: 'res.partner' }, store }));+ expect(readStoredCursor(store)).toEqual({ date: S, floor: { date: S, id: 11999 }, emitted: [] });+ await expect(newRecordTrigger.run(triggerCtx({ propsValue: { model: 'res.partner' }, store }))).resolves.toEqual([]);+ rows.push({ id: 12001, stamp: `${S}.500000`, values: {} });+ const next = asRecords(await newRecordTrigger.run(triggerCtx({ propsValue: { model: 'res.partner' }, store })));+ expect(next.map((r) => r['id'])).toEqual([12001]);+ });++ it.each([+ ['in reverse id order', (i: number) => 5999 - i],+ ['in random order', (i: number) => shuffledMicros[i]],+ ])('beyond 5,000 separate ranges with microseconds %s falls back to the keyset floor without missing a row and with a bounded store', async (_, micro) => {+ route({ key: 'res.partner.fields_get', handler: () => partnerFields });+ const rows = [+ { id: 1, stamp: '2026-09-29 09:59:00.000000', values: {} },+ ...Array.from({ length: 6000 }, (_, i) => ({ id: 2 * i + 3, stamp: `${S}.${String(micro(i)).padStart(6, '0')}`, values: {} })),+ ];+ routeTable({ model: 'res.partner', dateField: 'create_date', rows });+ const store = memoryStore();+ await store.put(odooPolling.CURSOR_KEY, { date: '2026-09-29 09:00:00', floor: null, emitted: [] });+ const seen: unknown[] = [];+ for (let poll = 0; poll < 20; poll++) {+ const out = asRecords(await newRecordTrigger.run(triggerCtx({ propsValue: { model: 'res.partner' }, store })));+ expect(storedRangeCount(store)).toBeLessThanOrEqual(odooPolling.MAX_WINDOW_RANGES);+ if (out.length === 0) break;+ seen.push(...out.map((r) => r['id']));+ }+ expect(seen).toHaveLength(6001);+ expect(new Set(seen).size).toBe(6001);+ const cursor = readStoredCursor(store);+ expect(cursor.floor).toEqual({ date: S, id: 2001 });+ expect(storedRangeCount(store)).toBe(odooPolling.MAX_WINDOW_RANGES);+ expect(storedSeconds(store)[0].ranges[0]).toEqual([2003, 2003]);+ rows.push({ id: 20000, stamp: `${S}.900000`, values: {} }, { id: 5000, stamp: `${S}.900000`, values: {} }, { id: 1000, stamp: `${S}.900000`, values: {} });+ const late = asRecords(await newRecordTrigger.run(triggerCtx({ propsValue: { model: 'res.partner' }, store })));+ expect(late.map((r) => r['id'])).toEqual([5000, 20000]);+ await expect(newRecordTrigger.run(triggerCtx({ propsValue: { model: 'res.partner' }, store }))).resolves.toEqual([]);+ });++ it('keeps the stored cursor under 512 KB with 5,000 ranges of large ids spread over the whole window', async () => {+ route({ key: 'res.partner.fields_get', handler: () => partnerFields });+ const base = 2_000_000_000;+ const seconds = Array.from({ length: 301 }, (_, i) => odooDates.toOdooDatetime(Date.parse('2026-09-29T09:55:00Z') + i * 1000));+ const emitted = seconds.map((date, index) => ({+ date,+ ranges: Array.from({ length: index === 300 ? 5000 - 300 * 16 : 16 }, (_, i) => [base + index * 100_000 + i * 10, base + index * 100_000 + i * 10 + 5]),+ }));+ routeTable({ model: 'res.partner', dateField: 'create_date', rows: [{ id: base + 99_999_999, stamp: `${S}.999999`, values: {} }] });+ const store = memoryStore();+ await store.put(odooPolling.CURSOR_KEY, { date: S, floor: null, emitted });+ const out = asRecords(await newRecordTrigger.run(triggerCtx({ propsValue: { model: 'res.partner' }, store })));+ expect(out.map((r) => r['id'])).toEqual([base + 99_999_999]);+ expect(storedRangeCount(store)).toBe(odooPolling.MAX_WINDOW_RANGES);+ expect(JSON.stringify(store.data.get(odooPolling.CURSOR_KEY)).length).toBeLessThan(512 * 1024);+ const [call] = callsTo({ model: 'res.partner', method: 'search_read' });+ expect(JSON.stringify(call.args[0]).length).toBeLessThan(512 * 1024);+ });++ it('prunes window memory older than 5 minutes before the cursor', async () => {+ route({ key: 'res.partner.fields_get', handler: () => partnerFields });+ routeTable({ model: 'res.partner', dateField: 'create_date', rows: [{ id: 8, stamp: '2026-09-29 10:10:00.000000', values: {} }] });+ const store = memoryStore();+ await store.put(odooPolling.CURSOR_KEY, {+ date: S,+ floor: { date: S, id: 6 },+ emitted: [{ date: '2026-09-29 09:58:00', ranges: [[5, 5]] }, { date: S, ranges: [[6, 6]] }],+ });+ await newRecordTrigger.run(triggerCtx({ propsValue: { model: 'res.partner' }, store }));+ const [call] = callsTo({ model: 'res.partner', method: 'search_read' });+ expect(JSON.stringify(call.args[0])).toContain(`["create_date",">=","${S}"],["id",">",6]`);+ expect(readStoredCursor(store)).toEqual({ date: '2026-09-29 10:10:00', floor: null, emitted: [{ date: '2026-09-29 10:10:00', ranges: [[8, 8]] }] });+ });++ it('does not rewrite the cursor when nothing is new', async () => {+ route({ key: 'res.partner.fields_get', handler: () => partnerFields });+ route({ key: 'res.partner.search_read', handler: () => [] });+ const store = memoryStore();+ const cursor = { date: S, floor: null, emitted: [{ date: S, ranges: [[5, 5]] }] };+ await store.put(odooPolling.CURSOR_KEY, cursor);+ await expect(newOrUpdatedRecordTrigger.run(triggerCtx({ propsValue: { model: 'res.partner' }, store }))).resolves.toEqual([]);+ expect(store.data.get(odooPolling.CURSOR_KEY)).toBe(cursor);+ expect(JSON.stringify(callsTo({ model: 'res.partner', method: 'search_read' })[0].args)).toContain('write_date');+ });++ it('first run without a cursor, or with an old-format cursor, only stores one and emits nothing', async () => {+ routeTable({ model: 'res.partner', dateField: 'create_date', rows: [{ id: 3, stamp: '2026-09-29 09:00:00.250000', values: {} }] });+ const seeded = { date: '2026-09-29 09:00:00', floor: null, emitted: [{ date: '2026-09-29 09:00:00', ranges: [[3, 3]] }] };+ const store = memoryStore();+ await expect(newRecordTrigger.run(triggerCtx({ propsValue: { model: 'res.partner' }, store }))).resolves.toEqual([]);+ expect(store.data.get(odooPolling.CURSOR_KEY)).toEqual(seeded);+ const legacyCursors = [+ { date: '2026-09-29 09:00:00', id: 3 },+ { date: '2026-09-29 09:00:00', idsAtDate: [3] },+ { date: '2026-09-29 09:00:00', floor: { date: '2026-09-29 09:00:00', id: 0 }, emitted: [{ id: 3, date: '2026-09-29 09:00:00' }] },+ { date: '2026-09-29 09:00:00', floor: '2026-09-29 09:00:00', emitted: [] },+ { date: '2026-09-29 09:00:00', floor: null, emitted: [{ date: '2026-09-29 09:00:00', ranges: [[5, 4]] }] },+ ];+ for (const legacy of legacyCursors) {+ await store.put(odooPolling.CURSOR_KEY, legacy);+ await expect(newRecordTrigger.run(triggerCtx({ propsValue: { model: 'res.partner' }, store }))).resolves.toEqual([]);+ expect(store.data.get(odooPolling.CURSOR_KEY)).toEqual(seeded);+ }+ });++ it('includes archived records unless the domain mentions active', async () => {+ route({ key: 'res.partner.fields_get', handler: () => partnerFields });+ const rows = [{ id: 4, stamp: '2026-09-29 09:00:00.000000', values: { active: true } }];+ routeTable({ model: 'res.partner', dateField: 'write_date', rows });+ const store = memoryStore();+ await newOrUpdatedRecordTrigger.onEnable(triggerCtx({ propsValue: { model: 'res.partner' }, store }));+ rows[0] = { id: 4, stamp: `${S}.100000`, values: { active: false } };+ const out = asRecords(await newOrUpdatedRecordTrigger.run(triggerCtx({ propsValue: { model: 'res.partner' }, store })));+ expect(out).toMatchObject([{ id: 4, active: false }]);+ expect(kwCalls().filter((call) => call.method !== 'fields_get').every((call) => JSON.stringify(call.kwargs['context']) === '{"active_test":false}')).toBe(true);+ resetFake();+ route({ key: 'res.partner.search_read', handler: () => [] });+ route({ key: 'res.partner.fields_get', handler: () => partnerFields });+ await newRecordTrigger.run(triggerCtx({ propsValue: { model: 'res.partner', domain: [['active', '=', true]] }, store: memoryStore() }));+ await newRecordTrigger.test(triggerCtx({ propsValue: { model: 'res.partner' }, store: memoryStore() }));+ const reads = callsTo({ model: 'res.partner', method: 'search_read' });+ const [scoped, all] = [reads[0], reads[reads.length - 1]];+ expect(scoped.kwargs['context']).toBeUndefined();+ expect(all.kwargs['context']).toEqual({ active_test: false });+ });++ it('confirmed-order mode polls write_date on orders dated after enabling; quotation mode polls create_date with no state filter', async () => {+ route({ key: 'sale.order.fields_get', handler: () => orderFields });+ route({ key: 'sale.order.search_read', handler: () => [] });+ const store = memoryStore();+ await store.put(odooPolling.CURSOR_KEY, { date: S, floor: null, emitted: [] });+ await store.put(odooPolling.ENABLED_AT_KEY, '2026-09-29 09:30:00');+ await newSalesOrderTrigger.run(triggerCtx({ propsValue: {}, store }));+ await newSalesOrderTrigger.run(triggerCtx({ propsValue: { order_state: 'draft' }, store }));+ const [confirmed, quotation] = pollReads({ model: 'sale.order' });+ expect(confirmed).toEqual(['&', '&', ['state', 'in', ['sale', 'done']], ['date_order', '>=', '2026-09-29 09:30:00'], ['write_date', '>=', LOOK]]);+ expect(quotation).toEqual([['create_date', '>=', LOOK]]);+ });++ it('confirmed mode: an old confirmed order edited later never fires; a backdated quotation confirmed after enabling fires once', async () => {+ vi.useFakeTimers({ toFake: ['Date'] });+ vi.setSystemTime(new Date('2026-09-29T09:30:00Z'));+ route({ key: 'sale.order.fields_get', handler: () => orderFields });+ const rows = [+ { id: 5, stamp: '2026-09-20 08:00:00.000000', values: { name: 'S00005', state: 'sale', date_order: '2026-09-20 08:00:00' } },+ { id: 8, stamp: '2026-09-28 12:00:00.000000', values: { name: 'S00008', state: 'draft', date_order: '2026-09-01 09:00:00' } },+ ];+ routeTable({ model: 'sale.order', dateField: 'write_date', rows });+ const store = memoryStore();+ await newSalesOrderTrigger.onEnable(triggerCtx({ propsValue: {}, store }));+ expect(store.data.get(odooPolling.ENABLED_AT_KEY)).toBe('2026-09-29 09:30:00');+ rows[0].stamp = `${S}.100000`;+ rows[1] = { ...rows[1], stamp: `${S}.300000`, values: { ...rows[1].values, state: 'sale', date_order: S } };+ const first = asRecords(await newSalesOrderTrigger.run(triggerCtx({ propsValue: {}, store })));+ expect(first.map((r) => r['id'])).toEqual([8]);+ expect(first[0]).toMatchObject({ state: 'sale', date_order: S });+ rows[1].stamp = '2026-09-29 11:00:00.000000';+ rows[0].stamp = '2026-09-29 11:00:05.000000';+ await expect(newSalesOrderTrigger.run(triggerCtx({ propsValue: {}, store }))).resolves.toEqual([]);+ expect(store.data.get(odooPolling.EMITTED_KEY)).toEqual([8]);+ await newSalesOrderTrigger.onEnable(triggerCtx({ propsValue: {}, store, isRepublish: true }));+ expect(store.data.get(odooPolling.ENABLED_AT_KEY)).toBe('2026-09-29 09:30:00');+ await newSalesOrderTrigger.onDisable(triggerCtx({ propsValue: {}, store }));+ expect(store.data.size).toBe(0);+ });++ it('confirmed mode emits an order once when it is edited between two page reads of the same poll', async () => {+ route({ key: 'sale.order.fields_get', handler: () => orderFields });+ const start = Date.parse('2026-09-29T10:00:00Z');+ const rows = Array.from({ length: 150 }, (_, i) => ({+ id: i + 1,+ stamp: `${new Date(start + i * 1000).toISOString().slice(0, 19).replace('T', ' ')}.000000`,+ values: { state: 'sale', date_order: S },+ }));+ routeTable({ model: 'sale.order', dateField: 'write_date', rows });+ const read = fake.state.routes.get('sale.order.search_read');+ let calls = 0;+ route({+ key: 'sale.order.search_read',+ handler: (call) => {+ const result = read ? read(call) : [];+ calls += 1;+ if (calls === 1) rows[0].stamp = '2026-09-29 10:10:00.000000';+ return result;+ },+ });+ const store = memoryStore();+ await store.put(odooPolling.CURSOR_KEY, { date: '2026-09-29 09:59:00', floor: null, emitted: [] });+ await store.put(odooPolling.ENABLED_AT_KEY, '2026-09-29 09:00:00');+ const out = asRecords(await newSalesOrderTrigger.run(triggerCtx({ propsValue: {}, store })));+ expect(out.map((r) => r['id'])).toEqual(rows.map((row) => row.id));+ expect(store.data.get(odooPolling.EMITTED_KEY)).toEqual(rows.map((row) => row.id));+ });++ it('keeps only the last 2,000 fired order ids', async () => {+ route({ key: 'sale.order.fields_get', handler: () => orderFields });+ routeTable({ model: 'sale.order', dateField: 'write_date', rows: [{ id: 9001, stamp: `${S}.1`, values: { state: 'sale', date_order: S } }] });+ const store = memoryStore();+ await store.put(odooPolling.CURSOR_KEY, { date: '2026-09-29 09:00:00', floor: null, emitted: [] });+ await store.put(odooPolling.ENABLED_AT_KEY, '2026-09-29 09:00:00');+ await store.put(odooPolling.EMITTED_KEY, Array.from({ length: odooPolling.MAX_EMITTED }, (_, i) => i + 1));+ const out = asRecords(await newSalesOrderTrigger.run(triggerCtx({ propsValue: {}, store })));+ expect(out.map((r) => r['id'])).toEqual([9001]);+ const emitted = store.data.get(odooPolling.EMITTED_KEY);+ expect(Array.isArray(emitted) && emitted.length).toBe(odooPolling.MAX_EMITTED);+ expect(Array.isArray(emitted) && emitted[emitted.length - 1]).toBe(9001);+ });++ it('quotation mode fires once for a quotation that was already sent or confirmed before the poll', async () => {+ route({ key: 'sale.order.fields_get', handler: () => orderFields });+ const rows = [+ { id: 2, stamp: '2026-09-28 10:00:00.000000', values: { name: 'S00002', state: 'draft' } },+ { id: 3, stamp: `${S}.100000`, values: { name: 'S00003', state: 'sent' } },+ { id: 4, stamp: `${S}.200000`, values: { name: 'S00004', state: 'sale' } },+ ];+ routeTable({ model: 'sale.order', dateField: 'create_date', rows });+ const store = memoryStore();+ await store.put(odooPolling.CURSOR_KEY, { date: '2026-09-28 10:00:00', floor: null, emitted: [{ date: '2026-09-28 10:00:00', ranges: [[2, 2]] }] });+ const out = asRecords(await newSalesOrderTrigger.run(triggerCtx({ propsValue: { order_state: 'draft' }, store })));+ expect(out.map((r) => [r['id'], r['state']])).toEqual([[3, 'sent'], [4, 'sale']]);+ await expect(newSalesOrderTrigger.run(triggerCtx({ propsValue: { order_state: 'draft' }, store }))).resolves.toEqual([]);+ });++ it('opportunities mode fires once for a lead converted after enabling and for a new opportunity, not for edits of older ones', async () => {+ vi.useFakeTimers({ toFake: ['Date'] });+ vi.setSystemTime(new Date('2026-09-29T09:30:00Z'));+ route({ key: 'crm.lead.fields_get', handler: () => leadFields });+ const rows = [+ { id: 1, stamp: '2026-09-01 08:00:00.000000', values: { type: 'opportunity', create_date: '2026-09-01 08:00:00', date_conversion: false } },+ { id: 2, stamp: '2026-09-29 09:40:00.000000', values: { type: 'lead', create_date: '2026-09-29 09:40:00', date_conversion: false } },+ ];+ routeTable({ model: 'crm.lead', dateField: 'write_date', rows });+ const store = memoryStore();+ await newLeadTrigger.onEnable(triggerCtx({ propsValue: { lead_type: 'opportunity' }, store }));+ rows[0].stamp = `${S}.100000`;+ rows[1] = { ...rows[1], stamp: `${S}.400000`, values: { ...rows[1].values, type: 'opportunity', date_conversion: S } };+ rows.push({ id: 3, stamp: `${S}.600000`, values: { type: 'opportunity', create_date: S, date_conversion: false } });+ const first = asRecords(await newLeadTrigger.run(triggerCtx({ propsValue: { lead_type: 'opportunity' }, store })));+ expect(first.map((r) => [r['id'], r['type']])).toEqual([[2, 'opportunity'], [3, 'opportunity']]);+ rows[1].stamp = '2026-09-29 10:03:00.000000';+ await expect(newLeadTrigger.run(triggerCtx({ propsValue: { lead_type: 'opportunity' }, store }))).resolves.toEqual([]);+ const polls = pollReads({ model: 'crm.lead' });+ expect(polls[polls.length - 1]).toEqual(expect.arrayContaining([['type', '=', 'opportunity'], ['create_date', '>=', '2026-09-29 09:30:00'], ['date_conversion', '>=', '2026-09-29 09:30:00']]));+ });++ it('opportunities mode fires for a lead created before enabling and converted after, and for one moved into the team later', async () => {+ vi.useFakeTimers({ toFake: ['Date'] });+ vi.setSystemTime(new Date('2026-09-29T09:30:00Z'));+ route({ key: 'crm.lead.fields_get', handler: () => leadFields });+ const rows = [+ { id: 4, stamp: '2026-09-10 08:00:00.000000', values: { type: 'lead', team_id: 2, create_date: '2026-09-10 08:00:00', date_conversion: false } },+ { id: 5, stamp: '2026-09-29 09:31:00.000000', values: { type: 'opportunity', team_id: 1, create_date: '2026-09-29 09:31:00', date_conversion: false } },+ ];+ routeTable({ model: 'crm.lead', dateField: 'write_date', rows });+ const store = memoryStore();+ const propsValue = { lead_type: 'opportunity', team_id: 2 };+ await newLeadTrigger.onEnable(triggerCtx({ propsValue, store }));+ rows[0] = { ...rows[0], stamp: `${S}.200000`, values: { ...rows[0].values, type: 'opportunity', date_conversion: S } };+ const converted = asRecords(await newLeadTrigger.run(triggerCtx({ propsValue, store })));+ expect(converted.map((r) => r['id'])).toEqual([4]);+ rows[1] = { ...rows[1], stamp: '2026-09-29 10:01:00.000000', values: { ...rows[1].values, team_id: 2 } };+ const moved = asRecords(await newLeadTrigger.run(triggerCtx({ propsValue, store })));+ expect(moved.map((r) => r['id'])).toEqual([5]);+ rows[0].stamp = '2026-09-29 10:02:00.000000';+ await expect(newLeadTrigger.run(triggerCtx({ propsValue, store }))).resolves.toEqual([]);+ expect(store.data.get(odooPolling.EMITTED_KEY)).toEqual([4, 5]);+ });++ it('leads mode polls create_date and checks type and team when the record is created', async () => {+ route({ key: 'crm.lead.fields_get', handler: () => leadFields });+ route({ key: 'crm.lead.search_read', handler: () => [] });+ const store = memoryStore();+ await store.put(odooPolling.CURSOR_KEY, { date: S, floor: null, emitted: [] });+ await newLeadTrigger.run(triggerCtx({ propsValue: { lead_type: 'lead', team_id: 2 }, store }));+ expect(callsTo({ model: 'crm.lead', method: 'search_read' })[0].args[0]).toEqual(['&', '&', ['type', '=', 'lead'], ['team_id', '=', 2], ['create_date', '>=', LOOK]]);+ expect(store.data.has(odooPolling.EMITTED_KEY)).toBe(false);+ });++ it('contact trigger pads fields missing on this Odoo version', async () => {+ route({ key: 'res.partner.fields_get', handler: () => fieldsOf({ name: 'char', is_company: 'boolean', create_date: 'datetime', parent_id: 'many2one' }) });+ route({ key: 'res.partner.search_read', handler: () => [{ id: 1, name: 'A', is_company: true, create_date: '2026-09-29 10:00:00', parent_id: false }] });+ const out = asRecords(await newContactTrigger.test(triggerCtx({ propsValue: { contact_type: 'company' }, store: memoryStore() })));+ expect(out[0]).toMatchObject({ id: 1, is_company: true, mobile: null, parent_id: null, parent_id_name: null, country_id_name: null });+ expect(Object.keys(out[0]).slice(0, 10)).toEqual(['id', 'display_name', 'name', 'is_company', 'parent_id', 'parent_id_name', 'email', 'phone', 'mobile', 'website']);+ expect(Object.keys(out[0]).slice(-5)).toEqual(['company_name', 'lang', 'active', 'create_date', 'write_date']);+ expect(callsTo({ model: 'res.partner', method: 'search_read' })[0].args[0]).toEqual([['is_company', '=', true]]);+ });+});++describe('new human actions', () => {+ it('create_sales_order resolves internal references and sends only given line values', async () => {+ routeProducts([{ id: 31, default_code: 'FURN_7800' }, { id: 44, default_code: false }]);+ route({ key: 'sale.order.create', handler: () => 12 });+ route({ key: 'sale.order.fields_get', handler: () => fieldsOf({ name: 'char', partner_id: 'many2one', state: 'selection' }) });+ route({ key: 'sale.order.read', handler: () => [{ id: 12, name: 'S00012', partner_id: [7, 'Acme'], state: 'draft' }] });+ const out = await createSalesOrderAction.run(actionCtx({ propsValue: { partner_id: 7, lines: [{ product: 'FURN_7800', quantity: 2 }, { product: '44' }] } }));+ const [create] = callsTo({ model: 'sale.order', method: 'create' });+ expect(create.args).toEqual([{ partner_id: 7, order_line: [[0, 0, { product_id: 31, product_uom_qty: 2 }], [0, 0, { product_id: 44, product_uom_qty: 1 }]] }]);+ expect(out).toMatchObject({ id: 12, partner_id: 7, partner_id_name: 'Acme', amount_total: null });+ });++ it('create_sales_order accepts lines as a JSON string and refuses bad lines instead of dropping them', async () => {+ routeProducts([{ id: 31, default_code: 'FURN_7800' }]);+ route({ key: 'sale.order.create', handler: () => 12 });+ route({ key: 'sale.order.fields_get', handler: () => fieldsOf({ name: 'char' }) });+ route({ key: 'sale.order.read', handler: () => [{ id: 12, name: 'S00012' }] });+ await createSalesOrderAction.run(actionCtx({ propsValue: { partner_id: 7, lines: '[{"product": "FURN_7800", "quantity": 3}]' } }));+ expect(callsTo({ model: 'sale.order', method: 'create' })[0].args).toEqual([{ partner_id: 7, order_line: [[0, 0, { product_id: 31, product_uom_qty: 3 }]] }]);+ await expect(createSalesOrderAction.run(actionCtx({ propsValue: { partner_id: 7, lines: '{"product": "FURN_7800"}' } }))).rejects.toThrow(/Order Lines must be a JSON list/);+ await expect(createSalesOrderAction.run(actionCtx({ propsValue: { partner_id: 7, lines: 'not json' } }))).rejects.toThrow(/Order Lines must be JSON/);+ await expect(createSalesOrderAction.run(actionCtx({ propsValue: { partner_id: 7, lines: [{ product: 'FURN_7800' }, 'FURN_7800'] } }))).rejects.toThrow(/line 2 must be an object/);+ await expect(createSalesOrderAction.run(actionCtx({ propsValue: { partner_id: 7, lines: [] } }))).rejects.toThrow(/at least one order line/);+ expect(callsTo({ model: 'sale.order', method: 'create' })).toHaveLength(1);+ });++ it('a failed read-back after a create still succeeds with the id and read_back_error, and never retries the create', async () => {+ routeProducts([{ id: 31, default_code: 'FURN_7800' }]);+ route({ key: 'sale.order.create', handler: () => 12 });+ route({ key: 'crm.lead.create', handler: () => 17 });+ route({ key: 'ir.attachment.create', handler: () => 90 });+ route({ key: '*.fields_get', handler: () => fault('AccessError: no read access') });+ const order = asRecord(await createSalesOrderAction.run(actionCtx({ propsValue: { partner_id: 7, lines: [{ product: 'FURN_7800' }] } })));+ expect(order).toMatchObject({ id: 12, name: null, partner_id: null, partner_id_name: null, amount_total: null });+ expect(order['read_back_error']).toMatch(/^Odoo sale\.order\.fields_get failed: .*AccessError: no read access$/);+ expect(Object.keys(order)).toEqual([...createdSaleOrderOutputSchema.fields.map((field) => field.key)]);+ const client = OdooClient.fromAuth({ auth: AUTH_PROPS });+ const lead = await odooOperations.createLead({ client, values: { name: 'Chairs' } });+ expect(lead).toMatchObject({ id: 17, name: null, stage_id_name: null, read_back_error: expect.stringMatching(/AccessError/) });+ route({ key: '*.fields_get', handler: () => fieldsOf({ name: 'char' }) });+ route({ key: 'ir.attachment.read', handler: () => [] });+ await expect(odooOperations.attachFile({ client, model: 'sale.order', recordId: 12, file: { data: Buffer.from('PDF'), filename: 'a.pdf' } })).resolves.toMatchObject({+ id: 90,+ name: null,+ read_back_error: 'ir.attachment record 90 was not found',+ });+ expect(callsTo({ model: 'sale.order', method: 'create' })).toHaveLength(1);+ expect(callsTo({ model: 'crm.lead', method: 'create' })).toHaveLength(1);+ expect(createdLeadOutputSchema.fields.map((field) => field.key)).toContain('read_back_error');+ expect(createdAttachmentOutputSchema.fields.map((field) => field.key)).toContain('read_back_error');+ });++ it('resolveProducts: numbers are IDs, strings are internal references first, then IDs, in two batched calls', async () => {+ routeProducts([+ { id: 31, default_code: 'FURN_7800' },+ { id: 44, default_code: false },+ { id: 50, default_code: '777' },+ { id: 60, default_code: '44' },+ { id: 70, default_code: '70' },+ ]);+ const client = OdooClient.fromAuth({ auth: AUTH_PROPS });+ const resolve = (values: unknown[]) => odooOperations.resolveProducts({ client, refs: values.map((value) => ({ value, label: 'Product' })) });+ await expect(resolve([44])).resolves.toEqual([44]);+ expect(kwCalls()).toHaveLength(0);+ await expect(resolve(['FURN_7800', '777', '31', '70', 44, 'FURN_7800'])).resolves.toEqual([31, 50, 31, 70, 44, 31]);+ const calls = callsTo({ model: 'product.product', method: 'search_read' });+ expect(calls.map((call) => firstArgList(call))).toEqual([[['default_code', 'in', ['FURN_7800', '777', '31', '70']]], [['id', 'in', [777, 31, 70]]]]);+ await expect(resolve(['44'])).rejects.toThrow(+ 'Product: "44" is the internal reference of product 60 and also the ID of product 44. Pass the ID as a number, or use the internal reference of the product you mean.',+ );+ await expect(resolve(['999'])).rejects.toThrow('Product: no product with ID or internal reference "999".');+ await expect(resolve(['NOPE'])).rejects.toThrow('Product: no product with ID or internal reference "NOPE".');+ await expect(resolve([' '])).rejects.toThrow('Product: enter a product ID or internal reference.');+ await expect(resolve([4.5])).rejects.toThrow(/positive whole number/);+ resetFake();+ routeProducts([{ id: 31, default_code: 'FURN_7800' }]);+ await expect(resolve(['FURN_7800'])).resolves.toEqual([31]);+ expect(callsTo({ model: 'product.product', method: 'search_read' })).toHaveLength(1);+ });++ it('create_sales_order resolves all line products in one batch and refuses more than 200 lines', async () => {+ routeProducts([{ id: 31, default_code: 'FURN_7800' }, { id: 32, default_code: 'FURN_7801' }]);+ route({ key: 'sale.order.create', handler: () => 12 });+ route({ key: 'sale.order.fields_get', handler: () => fieldsOf({ name: 'char' }) });+ route({ key: 'sale.order.read', handler: () => [{ id: 12, name: 'S00012' }] });+ const lines = Array.from({ length: odooOperations.MAX_LINES }, (_, i) => ({ product: i % 2 === 0 ? 'FURN_7800' : 'FURN_7801' }));+ await createSalesOrderAction.run(actionCtx({ propsValue: { partner_id: 7, lines } }));+ expect(callsTo({ model: 'product.product', method: 'search_read' })).toHaveLength(1);+ const [create] = callsTo({ model: 'sale.order', method: 'create' });+ expect(JSON.stringify(create.args)).toContain('[0,0,{"product_id":32,"product_uom_qty":1}]');+ resetFake();+ await expect(createSalesOrderAction.run(actionCtx({ propsValue: { partner_id: 7, lines: [...lines, { product: 'FURN_7800' }] } }))).rejects.toThrow(+ 'Add at most 200 order lines per call (got 201). Split the rest into another call.',+ );+ expect(kwCalls()).toHaveLength(0);+ });++ it('names the order line when its product cannot be resolved', async () => {+ routeProducts([{ id: 31, default_code: 'FURN_7800' }]);+ await expect(+ createSalesOrderAction.run(+ actionCtx({ propsValue: { partner_id: 7, lines: [{ product: 'FURN_7800' }, { product: 'MISSING' }] } }),+ ),+ ).rejects.toThrow('Line 2 product: no product with ID or internal reference "MISSING".');+ });++ it('refuses two products with the same internal reference', async () => {+ routeProducts([{ id: 1, default_code: 'DUP' }, { id: 2, default_code: 'DUP' }]);+ const client = OdooClient.fromAuth({ auth: AUTH_PROPS });+ await expect(odooOperations.resolveProducts({ client, refs: [{ value: 'DUP', label: 'Product' }] })).rejects.toThrow(+ 'Product: more than one product has the internal reference "DUP". Use the product ID.',+ );+ });++ it('many2one output fields keep the ID and name pair', () => {+ expect(saleOrderOutputSchema.fields).toEqual(+ expect.arrayContaining([+ { key: 'partner_id', label: 'Customer ID', format: 'number' },+ { key: 'partner_id_name', label: 'Customer' },+ ]),+ );+ });++ it('find_invoices pages with limit+1', async () => {+ route({ key: 'account.move.fields_get', handler: () => fieldsOf({ name: 'char', state: 'selection', partner_id: 'many2one' }) });+ route({ key: 'account.move.search_read', handler: (call) => Array.from({ length: Number(call.kwargs['limit']) }, (_, i) => ({ id: i + 1, name: `INV/${i}`, partner_id: false, state: 'posted' })) });+ const out = asRecord(await findInvoicesAction.run(actionCtx({ propsValue: { limit: 2 } })));+ expect(out).toMatchObject({ count: 2, has_more: true, next_offset: 2, limit: 2 });+ expect(callsTo({ model: 'account.move', method: 'search_read' })[0].kwargs['limit']).toBe(3);+ });++ it('attach_file duck-types the file and links it to the record', async () => {+ route({ key: 'ir.attachment.create', handler: () => 5 });+ route({ key: 'ir.attachment.fields_get', handler: () => fieldsOf({ name: 'char', res_model: 'char', res_id: 'integer' }) });+ route({ key: 'ir.attachment.read', handler: () => [{ id: 5, name: 'a.pdf', res_model: 'sale.order', res_id: 12 }] });+ await attachFileAction.run(actionCtx({ propsValue: { model: 'sale.order', record_id: 12, file: { filename: 'a.pdf', data: Buffer.from('PDF') } } }));+ expect(callsTo({ model: 'ir.attachment', method: 'create' })[0].args).toEqual([{ name: 'a.pdf', datas: Buffer.from('PDF').toString('base64'), res_model: 'sale.order', res_id: 12 }]);+ });+});++function shuffle({ values, seed }: { values: number[]; seed: number }): number[] {+ const out = [...values];+ let state = seed;+ for (let i = out.length - 1; i > 0; i--) {+ state = (state * 1103515245 + 12345) % 2147483648;+ const j = state % (i + 1);+ [out[i], out[j]] = [out[j], out[i]];+ }+ return out;+}++function routeProducts(products: Record<string, unknown>[]) {+ route({+ key: 'product.product.search_read',+ handler: (call) => products.filter((record) => evalDomain({ record, domain: firstArgList(call) })),+ });+}++function storedSeconds(store: ReturnType<typeof memoryStore>): { date: unknown; ranges: unknown[] }[] {+ return readStoredCursor(store).emitted.map((second) => {+ const record = asRecord(second);+ const ranges = record['ranges'];+ return { date: record['date'], ranges: Array.isArray(ranges) ? ranges : [] };+ });+}++function storedRangeCount(store: ReturnType<typeof memoryStore>): number {+ return storedSeconds(store).reduce((total, second) => total + second.ranges.length, 0);+}++function pollReads({ model }: { model: string }): unknown[] {+ return callsTo({ model, method: 'search_read' })+ .filter((call) => !String(call.kwargs['order']).endsWith('desc, id desc'))+ .map((call) => call.args[0]);+}++function readStoredCursor(store: ReturnType<typeof memoryStore>): { date: unknown; floor: unknown; emitted: unknown[] } {+ const record = asRecord(store.data.get(odooPolling.CURSOR_KEY));+ const emitted = record['emitted'];+ return { date: record['date'], floor: record['floor'], emitted: Array.isArray(emitted) ? emitted : [] };+}++function actionCtx({ propsValue, extra = {} }: ActionCtxParams) {+ return { ...createMockActionContext({ propsValue }), auth: auth(extra) };+}++function triggerCtx({ propsValue, store, isRepublish }: TriggerCtxParams) {+ return { ...createMockPollingTriggerContext({ propsValue }), auth: auth(), store, isRepublish };+}++type ActionCtxParams = { propsValue: Record<string, unknown>; extra?: Record<string, unknown> };++type TriggerCtxParams = { propsValue: Record<string, unknown>; store: ReturnType<typeof memoryStore>; isRepublish?: boolean };diff --git a/packages/pieces/community/odoo/vitest.config.ts b/packages/pieces/community/odoo/vitest.config.tsnew file mode 100644index 00000000000..95addcbe834--- /dev/null+++ b/packages/pieces/community/odoo/vitest.config.ts@@ -0,0 +1,19 @@+import path from 'path'+import { defineConfig } from 'vitest/config'++const repoRoot = path.resolve(__dirname, '../../../..')++export default defineConfig({+ test: {+ globals: true,+ environment: 'node',+ setupFiles: ['test/fake-odoo.ts'],+ env: { TZ: 'America/Los_Angeles' },+ },+ 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'),+ },+ },+})