API
This commit is contained in:
76
api/common/Service/TiposCambios.php
Normal file
76
api/common/Service/TiposCambios.php
Normal file
@ -0,0 +1,76 @@
|
||||
<?php
|
||||
namespace Contabilidad\Common\Service;
|
||||
|
||||
use Carbon\Carbon;
|
||||
use GuzzleHttp\Client;
|
||||
use GuzzleHttp\Exception\ConnectException;
|
||||
use GuzzleHttp\Exception\RequestException;
|
||||
use ProVM\Common\Factory\Model as Factory;
|
||||
use Contabilidad\Moneda;
|
||||
use Contabilidad\TipoCambio;
|
||||
|
||||
class TiposCambios {
|
||||
protected $client;
|
||||
protected $factory;
|
||||
protected $base_url;
|
||||
protected $key;
|
||||
public function __construct(Client $client, Factory $factory, $api_url, $api_key) {
|
||||
$this->client = $client;
|
||||
$this->factory = $factory;
|
||||
$this->base_url = $api_url;
|
||||
$this->key = $api_key;
|
||||
}
|
||||
public function get(string $fecha, int $moneda_id) {
|
||||
$fecha = Carbon::parse($fecha);
|
||||
$moneda = $this->factory->find(Moneda::class)->one($moneda_id);
|
||||
if ($moneda->codigo == 'USD') {
|
||||
if ($fecha->weekday() == 0) {
|
||||
$fecha = $fecha->subWeek()->weekday(5);
|
||||
}
|
||||
if ($fecha->weekday() == 6) {
|
||||
$fecha = $fecha->weekday(5);
|
||||
}
|
||||
}
|
||||
$cambio = $moneda->cambio($fecha);
|
||||
if ($cambio) {
|
||||
if ($cambio->desde()->id != $moneda->id) {
|
||||
return 1 / $cambio->valor;
|
||||
}
|
||||
return $cambio->valor;
|
||||
}
|
||||
$data = [
|
||||
'fecha' => $fecha->format('Y-m-d'),
|
||||
'desde' => $moneda->codigo
|
||||
];
|
||||
$headers = [
|
||||
'Authorization' => 'Bearer ' . $this->key
|
||||
];
|
||||
$url = implode('/', [
|
||||
$this->base_url,
|
||||
'cambio',
|
||||
'get'
|
||||
]);
|
||||
try {
|
||||
$response = $this->client->request('POST', $url, ['json' => $data, 'headers' => $headers]);
|
||||
} catch (ConnectException | RequestException $e) {
|
||||
error_log($e);
|
||||
return null;
|
||||
}
|
||||
if ($response->getStatusCode() !== 200) {
|
||||
return null;
|
||||
}
|
||||
$result = json_decode($response->getBody());
|
||||
$valor = $result->serie[0]->valor;
|
||||
$data = [
|
||||
'fecha' => $fecha->format('Y-m-d H:i:s'),
|
||||
'desde_id' => $moneda->id,
|
||||
'hasta_id' => 1,
|
||||
'valor' => $valor
|
||||
];
|
||||
$tipo = TipoCambio::add($this->factory, $data);
|
||||
if ($tipo !== false and $tipo->is_new()) {
|
||||
$tipo->save();
|
||||
}
|
||||
return $valor;
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user