';
}
public function description() {
return __( 'Create Odoo CRM leads or opportunities, linked to contacts, with team, salesperson and tags.', 'fieldwren' );
}
public function help() {
return '- ' . esc_html__( 'Odoo URL: your instance, e.g. https://mycompany.odoo.com (no /odoo or /web path).', 'fieldwren' ) . '
- ' . esc_html__( 'Database: shown in Settings → Activate developer mode, or in the database manager; on odoo.com it is usually the subdomain.', 'fieldwren' ) . '
- ' . esc_html__( 'API key: your user avatar → My Profile / Preferences → Account Security → New API Key. Use a user with Sales access; Login is that user\'s email.', 'fieldwren' ) . '
- ' . esc_html__( 'Protocol: JSON-RPC works on Odoo 8 to 19; JSON-2 needs Odoo 19 or later.', 'fieldwren' ) . '
';
}
public function credential_fields() {
return array(
'url' => array( 'label' => __( 'Odoo URL', 'fieldwren' ), 'type' => 'url', 'required' => true, 'placeholder' => 'https://mycompany.odoo.com' ),
'db' => array( 'label' => __( 'Database', 'fieldwren' ), 'type' => 'text', 'required' => true ),
'login' => array( 'label' => __( 'Login (user email)', 'fieldwren' ), 'type' => 'text', 'required' => true ),
'api_key' => array( 'label' => __( 'API key', 'fieldwren' ), 'type' => 'password', 'required' => true ),
'protocol' => array( 'label' => __( 'Protocol', 'fieldwren' ), 'type' => 'select', 'default' => 'jsonrpc', 'options' => array( 'jsonrpc' => 'JSON-RPC (/jsonrpc)', 'json2' => 'JSON-2 (/json/2, Odoo 19+)' ) ),
);
}
/* ---------------- Transport ---------------- */
/** @return array Normalised connection settings. */
private function conn( array $creds = null ) {
$c = null === $creds ? $this->creds() : $creds;
$u = untrailingslashit( preg_replace( '#/(odoo|web)(/.*)?$#', '', trim( (string) ( $c['url'] ?? '' ) ) ) );
return array(
'url' => $u,
'db' => trim( (string) ( $c['db'] ?? '' ) ),
'login' => trim( (string) ( $c['login'] ?? '' ) ),
'key' => trim( (string) ( $c['api_key'] ?? '' ) ),
'protocol' => 'json2' === ( $c['protocol'] ?? '' ) ? 'json2' : 'jsonrpc',
);
}
/**
* Raw JSON-RPC call.
*
* @return mixed|\WP_Error Result.
*/
private function rpc( array $c, $service, $method, array $args ) {
$this->secrets[] = $c['key'];
$res = $this->http(
'POST',
$c['url'] . '/jsonrpc',
array(
'timeout' => 30,
'body' => array(
'jsonrpc' => '2.0',
'method' => 'call',
'params' => array( 'service' => $service, 'method' => $method, 'args' => $args ),
'id' => wp_rand( 1, 999999 ),
),
)
);
if ( is_wp_error( $res ) ) {
return $res;
}
$b = $res['body'];
if ( ! is_array( $b ) ) {
return new \WP_Error( 'fwren_odoo', __( 'Odoo did not answer with JSON. Check the URL (it must be the instance root, reachable over HTTPS).', 'fieldwren' ) );
}
if ( isset( $b['error'] ) ) {
return new \WP_Error( 'fwren_odoo', $this->odoo_error( $b['error'] ) );
}
return $b['result'] ?? null;
}
/** @return string Readable Odoo error. */
private function odoo_error( $e ) {
if ( ! is_array( $e ) ) {
return (string) $e;
}
$msg = (string) ( $e['data']['message'] ?? ( $e['message'] ?? '' ) );
$cls = (string) ( $e['data']['name'] ?? ( $e['name'] ?? '' ) );
if ( false !== strpos( $cls, 'AccessDenied' ) || false !== stripos( $msg, 'Access Denied' ) ) {
return __( 'Odoo refused the login or API key (Access Denied).', 'fieldwren' );
}
return trim( 'Odoo: ' . $msg . ( $cls ? ' (' . preg_replace( '/^.*\./', '', $cls ) . ')' : '' ) );
}
protected function error_message( $body, $code ) {
if ( is_array( $body ) && ( isset( $body['message'] ) || isset( $body['name'] ) ) && ! isset( $body['jsonrpc'] ) ) {
return $this->odoo_error( $body );
}
return parent::error_message( $body, $code );
}
/** @return int|\WP_Error User id (JSON-RPC; cached 12 h). */
private function uid( array $c ) {
$key = 'fwren_odoo_uid_' . md5( $c['url'] . '|' . $c['db'] . '|' . $c['login'] . '|' . $c['key'] );
$uid = get_transient( $key );
if ( $uid ) {
return (int) $uid;
}
$uid = $this->rpc( $c, 'common', 'authenticate', array( $c['db'], $c['login'], $c['key'], (object) array() ) );
if ( is_wp_error( $uid ) ) {
return $uid;
}
if ( ! $uid ) {
return new \WP_Error( 'fwren_odoo_auth', __( 'Odoo refused the database, login or API key.', 'fieldwren' ) );
}
set_transient( $key, (int) $uid, 12 * HOUR_IN_SECONDS );
return (int) $uid;
}
/**
* Call a model method.
*
* @param string $model Model.
* @param string $method create | write | search_read | fields_get.
* @param array $args Positional arguments (JSON-RPC).
* @param array $kw Keyword arguments.
* @param array $creds Credentials (verify).
* @return mixed|\WP_Error
*/
private function call( $model, $method, array $args = array(), array $kw = array(), array $creds = null ) {
$c = $this->conn( $creds );
if ( 'json2' === $c['protocol'] ) {
$named = $kw;
if ( 'create' === $method ) {
$named['vals_list'] = array( $args[0] );
} elseif ( 'write' === $method ) {
$named['ids'] = $args[0];
$named['vals'] = (object) $args[1];
} elseif ( in_array( $method, array( 'search_read', 'search', 'search_count' ), true ) ) {
$named['domain'] = $args[0] ?? array();
}
$this->secrets[] = $c['key'];
$res = $this->http(
'POST',
$c['url'] . '/json/2/' . rawurlencode( $model ) . '/' . rawurlencode( $method ),
array(
'timeout' => 30,
'headers' => array( 'Authorization' => 'bearer ' . $c['key'], 'X-Odoo-Database' => $c['db'] ),
'body' => (object) $named,
)
);
if ( is_wp_error( $res ) ) {
return $res;
}
$out = $res['body'];
return ( 'create' === $method && is_array( $out ) ) ? (int) ( $out[0] ?? 0 ) : $out;
}
$uid = $this->uid( $c );
if ( is_wp_error( $uid ) ) {
return $uid;
}
return $this->rpc( $c, 'object', 'execute_kw', array( $c['db'], $uid, $c['key'], $model, $method, $args, (object) $kw ) );
}
/** @return array|\WP_Error crm.lead fields (cached 1 h): name => [ string, type, readonly, required ]. */
private function lead_fields( $refresh = false ) {
$c = $this->conn();
$key = 'fwren_odoo_f_' . md5( $c['url'] . $c['db'] . $c['login'] );
$hit = $refresh ? false : get_transient( $key );
if ( is_array( $hit ) ) {
return $hit;
}
$f = $this->call( 'crm.lead', 'fields_get', array(), array( 'attributes' => array( 'string', 'type', 'readonly', 'required', 'store' ) ) );
if ( is_wp_error( $f ) ) {
return $f;
}
$f = is_array( $f ) ? $f : array();
set_transient( $key, $f, HOUR_IN_SECONDS );
return $f;
}
/* ---------------- Admin ---------------- */
public function verify( array $creds ) {
$c = $this->conn( $creds );
if ( ! preg_match( '#^https?://#', $c['url'] ) ) {
return new \WP_Error( 'fwren_odoo_url', __( 'Enter the full Odoo URL, starting with https://', 'fieldwren' ) );
}
if ( 'jsonrpc' === $c['protocol'] ) {
delete_transient( 'fwren_odoo_uid_' . md5( $c['url'] . '|' . $c['db'] . '|' . $c['login'] . '|' . $c['key'] ) );
}
$f = $this->call( 'crm.lead', 'fields_get', array(), array( 'attributes' => array( 'type' ) ), $creds );
if ( is_wp_error( $f ) ) {
if ( false !== stripos( $f->get_error_message(), 'crm.lead' ) ) {
return new \WP_Error( 'fwren_odoo_crm', __( 'Connected, but the CRM app is not installed (no crm.lead model).', 'fieldwren' ) );
}
return $f;
}
$ver = $this->rpc( $c, 'common', 'version', array() );
$v = is_array( $ver ) && ! empty( $ver['server_version'] ) ? 'Odoo ' . $ver['server_version'] . ' · ' : '';
return $v . $c['db'];
}
public function options( $source, array $settings ) {
$simple = array(
'teams' => array( 'crm.team', array() ),
'users' => array( 'res.users', array( array( 'share', '=', false ) ) ),
'tags' => array( 'crm.tag', array() ),
'stages' => array( 'crm.stage', array() ),
'sources' => array( 'utm.source', array() ),
'mediums' => array( 'utm.medium', array() ),
);
if ( isset( $simple[ $source ] ) ) {
$rows = $this->call( $simple[ $source ][0], 'search_read', array( $simple[ $source ][1] ), array( 'fields' => array( 'id', 'name' ), 'limit' => 500 ) );
if ( is_wp_error( $rows ) ) {
return $rows;
}
$out = array();
foreach ( (array) $rows as $r ) {
$name = is_array( $r['name'] ) ? (string) reset( $r['name'] ) : (string) $r['name']; // Translatable names may come as { lang: value }.
$out[ (string) $r['id'] ] = $name;
}
return $out;
}
if ( 'fields' === $source ) {
$f = $this->lead_fields( true );
if ( is_wp_error( $f ) ) {
return $f;
}
$types = array( 'char', 'text', 'html', 'selection', 'integer', 'float', 'monetary', 'boolean', 'date', 'datetime' );
$auto = array( 'website' => 'url', 'mobile' => 'phone', 'function' => '' );
$out = array();
foreach ( $f as $name => $d ) {
if ( in_array( $name, self::OWN, true ) || ! empty( $d['readonly'] ) || ( isset( $d['store'] ) && ! $d['store'] ) || ! in_array( $d['type'] ?? '', $types, true ) || 0 === strpos( $name, 'message_' ) || 0 === strpos( $name, 'activity_' ) || 0 === strpos( $name, '__' ) ) {
continue;
}
$out[] = array( 'key' => $name, 'label' => ( $d['string'] ?? $name ) . ' [' . $d['type'] . ']', 'required' => ! empty( $d['required'] ), 'auto' => $auto[ $name ] ?? '' );
}
usort(
$out,
static function ( $a, $b ) {
return strcasecmp( $a['label'], $b['label'] );
}
);
return $out;
}
return parent::options( $source, $settings );
}
public function feed_fields( $form_id ) {
$auto = self::auto_values( $form_id );
return array(
array( 'key' => 'type', 'type' => 'select', 'label' => __( 'Create', 'fieldwren' ), 'default' => 'lead', 'no_empty' => true, 'options' => array( 'lead' => __( 'Lead', 'fieldwren' ), 'opportunity' => __( 'Opportunity', 'fieldwren' ) ), 'desc' => __( 'Use Opportunity when "Leads" is turned off in CRM settings.', 'fieldwren' ) ),
array( 'key' => 'lead_name', 'type' => 'text', 'label' => __( 'Title', 'fieldwren' ), 'required' => true, 'default' => '{form_title} – ' . ( $auto['name'] ? $auto['name'] : ( $auto['email'] ? $auto['email'] : '#{entry.serial}' ) ) ),
array( 'key' => 'contact_name', 'type' => 'value', 'label' => __( 'Contact name', 'fieldwren' ), 'default' => 'auto:name' ),
array( 'key' => 'email', 'type' => 'value', 'label' => __( 'Email', 'fieldwren' ), 'default' => 'auto:email' ),
array( 'key' => 'phone', 'type' => 'value', 'label' => __( 'Phone', 'fieldwren' ), 'default' => 'auto:phone' ),
array( 'key' => 'partner_name', 'type' => 'value', 'label' => __( 'Company name', 'fieldwren' ), 'default' => 'auto:company' ),
array( 'key' => 'description', 'type' => 'textarea', 'label' => __( 'Internal notes', 'fieldwren' ), 'rows' => 4, 'default' => '{all_data_text}' ),
array( 'key' => 'map', 'type' => 'map', 'source' => 'fields', 'label' => __( 'Other lead fields', 'fieldwren' ), 'desc' => __( 'Selection fields need the technical value; booleans accept yes/1/true.', 'fieldwren' ) ),
array( 'key' => 'partner', 'type' => 'toggle', 'label' => __( 'Contact', 'fieldwren' ), 'text' => __( 'Link the lead to the contact with this email (create the contact when missing)', 'fieldwren' ), 'default' => true ),
array( 'key' => 'team_id', 'type' => 'select', 'source' => 'teams', 'label' => __( 'Sales team', 'fieldwren' ) ),
array( 'key' => 'user_id', 'type' => 'select', 'source' => 'users', 'label' => __( 'Salesperson', 'fieldwren' ) ),
array( 'key' => 'tag_ids', 'type' => 'select', 'multiple' => true, 'source' => 'tags', 'label' => __( 'Tags', 'fieldwren' ) ),
array( 'key' => 'tags_text', 'type' => 'text', 'label' => __( 'More tags', 'fieldwren' ), 'desc' => __( 'Comma separated names; missing tags are created. Smartcodes allowed.', 'fieldwren' ) ),
array( 'key' => 'stage_id', 'type' => 'select', 'source' => 'stages', 'label' => __( 'Stage', 'fieldwren' ), 'show_if' => array( 'type' => 'opportunity' ) ),
array( 'key' => 'source_id', 'type' => 'select', 'source' => 'sources', 'label' => __( 'UTM source', 'fieldwren' ) ),
array( 'key' => 'medium_id', 'type' => 'select', 'source' => 'mediums', 'label' => __( 'UTM medium', 'fieldwren' ) ),
array( 'key' => 'priority', 'type' => 'select', 'label' => __( 'Priority', 'fieldwren' ), 'default' => '', 'options' => array( '0' => __( 'Normal', 'fieldwren' ), '1' => '★', '2' => '★★', '3' => '★★★' ) ),
array( 'key' => 'duplicates', 'type' => 'select', 'label' => __( 'Open lead with the same email', 'fieldwren' ), 'default' => 'create', 'no_empty' => true, 'options' => array( 'create' => __( 'Create another lead', 'fieldwren' ), 'update' => __( 'Update it (notes are appended)', 'fieldwren' ), 'skip' => __( 'Skip', 'fieldwren' ) ) ),
);
}
/* ---------------- Process ---------------- */
/** @return int|\WP_Error Partner id by email (created when missing). */
private function partner( $email, $name, $phone, $company ) {
$rows = $this->call( 'res.partner', 'search_read', array( array( array( 'email', '=ilike', $email ) ) ), array( 'fields' => array( 'id' ), 'limit' => 1 ) );
if ( is_wp_error( $rows ) ) {
return $rows;
}
if ( ! empty( $rows[0]['id'] ) ) {
return (int) $rows[0]['id'];
}
$vals = array_filter( array( 'name' => $name ? $name : $email, 'email' => $email, 'phone' => $phone, 'company_name' => $company ), 'strlen' );
$id = $this->call( 'res.partner', 'create', array( $vals ) );
return is_wp_error( $id ) ? $id : (int) ( is_array( $id ) ? reset( $id ) : $id );
}
/** @return int[]|\WP_Error Tag ids for names (created when missing). */
private function tag_ids( array $names ) {
$ids = array();
foreach ( $names as $n ) {
$rows = $this->call( 'crm.tag', 'search_read', array( array( array( 'name', '=ilike', $n ) ) ), array( 'fields' => array( 'id' ), 'limit' => 1 ) );
if ( is_wp_error( $rows ) ) {
return $rows;
}
if ( ! empty( $rows[0]['id'] ) ) {
$ids[] = (int) $rows[0]['id'];
continue;
}
$id = $this->call( 'crm.tag', 'create', array( array( 'name' => $n ) ) );
if ( is_wp_error( $id ) ) {
return $id;
}
$ids[] = (int) ( is_array( $id ) ? reset( $id ) : $id );
}
return $ids;
}
/** @return mixed Value coerced to the Odoo field type. */
private static function coerce( $v, $type ) {
switch ( $type ) {
case 'integer':
return (int) preg_replace( '/[^\d\-]/', '', $v );
case 'float':
case 'monetary':
return (float) preg_replace( '/[^\d.\-]/', '', str_replace( ',', '.', $v ) );
case 'boolean':
return in_array( strtolower( trim( $v ) ), array( '1', 'yes', 'true', 'on', 'accepted', 'y' ), true );
case 'date':
$t = strtotime( $v );
return $t ? gmdate( 'Y-m-d', $t ) : $v;
case 'datetime':
$t = strtotime( $v );
return $t ? gmdate( 'Y-m-d H:i:s', $t ) : $v;
case 'html':
return wpautop( esc_html( $v ) );
}
return $v;
}
public function process( array $feed, array $entry, array $values ) {
$s = $feed['settings'];
$fields = $this->lead_fields();
if ( is_wp_error( $fields ) ) {
return $fields;
}
$email = sanitize_email( $this->sval( 'email' ) );
$name = $this->sval( 'contact_name' );
$phone = $this->sval( 'phone' );
$comp = $this->sval( 'partner_name' );
$title = $this->sval( 'lead_name' );
$desc = $this->val( $s['description'] ?? '' );
$vals = array(
'name' => '' !== $title ? $title : $this->default_title(),
'type' => 'opportunity' === ( $s['type'] ?? 'lead' ) ? 'opportunity' : 'lead',
'contact_name' => $name,
'email_from' => $email,
'phone' => $phone,
'partner_name' => $comp,
);
if ( '' !== $desc ) {
$vals['description'] = self::coerce( $desc, $fields['description']['type'] ?? 'text' );
}
foreach ( $this->mapped( 'map' ) as $k => $v ) {
if ( isset( $fields[ $k ] ) && ! in_array( $k, self::OWN, true ) ) {
$vals[ $k ] = self::coerce( $v, $fields[ $k ]['type'] ?? 'char' );
}
}
foreach ( array( 'team_id', 'user_id', 'source_id', 'medium_id' ) as $m2o ) {
if ( ! empty( $s[ $m2o ] ) && isset( $fields[ $m2o ] ) ) {
$vals[ $m2o ] = (int) $s[ $m2o ];
}
}
if ( 'opportunity' === $vals['type'] && ! empty( $s['stage_id'] ) ) {
$vals['stage_id'] = (int) $s['stage_id'];
}
if ( '' !== (string) ( $s['priority'] ?? '' ) && isset( $fields['priority'] ) ) {
$vals['priority'] = (string) $s['priority'];
}
$tags = array_map( 'intval', (array) ( $s['tag_ids'] ?? array() ) );
$more = $this->list_of( $s['tags_text'] ?? '' );
if ( $more ) {
$ids = $this->tag_ids( $more );
if ( is_wp_error( $ids ) ) {
return $ids;
}
$tags = array_merge( $tags, $ids );
}
if ( $tags ) {
$vals['tag_ids'] = array( array( 6, 0, array_values( array_unique( $tags ) ) ) );
}
if ( ! empty( $s['partner'] ) && is_email( $email ) ) {
$pid = $this->partner( $email, $name, $phone, $comp );
if ( is_wp_error( $pid ) ) {
return $pid;
}
if ( $pid ) {
$vals['partner_id'] = $pid;
}
}
$vals = array_filter(
$vals,
static function ( $v ) {
return ! ( is_string( $v ) && '' === $v );
}
);
$vals = apply_filters( 'fwren/odoo/lead_values', $vals, $feed, $entry, $values );
$dup = (string) ( $s['duplicates'] ?? 'create' );
if ( 'create' !== $dup && is_email( $email ) ) {
$domain = array( array( 'email_from', '=ilike', $email ), array( 'active', '=', true ) );
if ( isset( $fields['probability'] ) ) {
$domain[] = array( 'probability', '<', 100 );
}
$rows = $this->call( 'crm.lead', 'search_read', array( $domain ), array( 'fields' => array( 'id', 'description' ), 'limit' => 1, 'order' => 'id desc' ) );
if ( is_wp_error( $rows ) ) {
return $rows;
}
if ( ! empty( $rows[0]['id'] ) ) {
$id = (int) $rows[0]['id'];
if ( 'skip' === $dup ) {
/* translators: %d lead id */
return sprintf( __( 'Open lead #%d exists; skipped.', 'fieldwren' ), $id );
}
unset( $vals['type'] );
if ( isset( $vals['description'] ) && ! empty( $rows[0]['description'] ) && is_string( $rows[0]['description'] ) ) {
$sep = 'html' === ( $fields['description']['type'] ?? '' ) ? '
' : "\n\n----\n\n";
$vals['description'] = $rows[0]['description'] . $sep . $vals['description'];
}
$ok = $this->call( 'crm.lead', 'write', array( array( $id ), $vals ) );
/* translators: %d lead id */
return is_wp_error( $ok ) ? $ok : sprintf( __( 'Lead #%d updated.', 'fieldwren' ), $id );
}
}
$id = $this->call( 'crm.lead', 'create', array( $vals ) );
if ( is_wp_error( $id ) ) {
return $id;
}
$id = (int) ( is_array( $id ) ? reset( $id ) : $id );
/* translators: 1: lead or opportunity, 2: id */
return sprintf( __( '%1$s #%2$d created.', 'fieldwren' ), 'opportunity' === ( $vals['type'] ?? 'lead' ) ? __( 'Opportunity', 'fieldwren' ) : __( 'Lead', 'fieldwren' ), $id );
}
}