File: /var/www/middleware-citas-dev/app/Services/ApiOdooService.php
<?php
namespace App\Services;
use Exception;
require_once base_path('app/Libraries/ripcord-master/ripcord.php');
class ApiOdooService
{
protected $uid;
public $models;
protected $endpoint;
protected $database;
protected $apiKey;
public function __construct()
{
$this->endpoint = env('ODOO_ENDPOINT');
$this->database = env('ODOO_DATABASE');
$username = env('ODOO_USERNAME');
$this->apiKey = env('ODOO_API_KEY');
if (empty($this->endpoint) || empty($this->database) || empty($username) || empty($this->apiKey)) {
throw new Exception('Error de configuración de cuenta API Odoo. Revise las variables ODOO_* en .env', 503);
}
try {
$this->models = \ripcord::client($this->endpoint . '/xmlrpc/2/object');
$this->uid = \ripcord::client($this->endpoint . '/xmlrpc/2/common')->authenticate($this->database, $username, $this->apiKey, array());
if (!$this->uid || isset($this->uid['faultCode']) || !is_int($this->uid)) {
throw new Exception('Error de autenticación en Odoo', 401);
}
} catch (Exception $e) {
if ($e->getCode() == 401) {
throw $e;
}
throw new Exception('Error de configuración de cuenta API Odoo', 503);
}
}
// Listar modelos
public function listModel($model, $fields=[], $domain=[])
{
$records = $this->models->execute_kw(
$this->database,
$this->uid,
$this->apiKey,
$model,
'search_read',
[
$domain,
],
[
'fields' => $fields
]
);
if (isset($records['faultCode'])) {
throw new Exception($records['faultString'], 503);
}
return $records;
}
// Listar modelos usando lotes
public function listModelBatches($model, $fields=[], $domain=[], $batch_size=500)
{
$ids = $this->models->execute_kw(
$this->database,
$this->uid,
$this->apiKey,
$model,
'search',
[
$domain,
]
);
if (isset($ids['faultCode'])) {
throw new Exception($ids['faultString'], 503);
}
$index = 0;
$records = [];
while ($index < count($ids)) {
$batchIds = array_slice($ids, $index, $batch_size);
$batchRecords = $this->models->execute_kw(
$this->database,
$this->uid,
$this->apiKey,
$model,
'read',
array($batchIds),
[
'fields' => $fields
]
);
// return $batchRecords;
if (!empty($batchRecords)) {
$records = array_merge($records, $batchRecords);
}
$index += $batch_size;
}
return $records;
}
}