File: /var/www/informe-admision/app/Services/ApiOdooService.php
<?php
namespace App\Services;
use App\Models\ApiConnections;
use DOMDocument;
use Exception;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
require_once base_path('app/Libraries/ripcord-master/ripcord.php');
class ApiOdooService
{
protected $uid;
public $models;
protected $credentials;
public function __construct()
{
$credentials = ApiConnections::where('software_id', 1)->first();
if (empty($credentials)) {
throw new Exception('Error de configuración de cuenta API', 503);
}
if (empty($credentials->endpoint) || empty($credentials->database) || empty($credentials->username) || empty($credentials->api_key)) {
throw new Exception('Error de configuración de cuenta API', 503);
}
if (!$credentials->status) {
throw new Exception('Cuenta API deshabilitada', 503);
}
if($credentials->deleted) {
throw new Exception('Cuenta API no existe o fue eliminada', 404);
}
try {
$this->models = \ripcord::client($credentials->endpoint . '/xmlrpc/2/object');
$this->uid = \ripcord::client($credentials->endpoint . '/xmlrpc/2/common')->authenticate($credentials->database, $credentials->username, $credentials->api_key, array());
if (!$this->uid || isset($this->uid['faultCode']) || !is_int($this->uid)) {
throw new Exception('Error de autenticación en Odoo', 401);
}
$this->credentials = $credentials;
} catch (Exception $e) {
if ($e->getCode() == 401) {
throw $e; // Se lanza el error 401 si es de autenticación
}
// Si es otro tipo de error de configuración o problema de conexión, lanzamos un 503
throw new Exception('Error de configuración de cuenta API', 503);
}
}
// Listar modelos
public function listModel($model, $fields=[], $domain=[])
{
$records = $this->models->execute_kw(
$this->credentials->database,
$this->uid,
$this->credentials->api_key,
$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->credentials->database,
$this->uid,
$this->credentials->api_key,
$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->credentials->database,
$this->uid,
$this->credentials->api_key,
$model,
'read',
array($batchIds),
[
'fields' => $fields
]
);
// return $batchRecords;
if (!empty($batchRecords)) {
$records = array_merge($records, $batchRecords);
}
$index += $batch_size;
}
return $records;
}
}