Reorden Toku

This commit is contained in:
Juan Pablo Vial
2025-05-10 12:38:14 -04:00
parent 1486d6cf38
commit fb7177fd65
24 changed files with 213 additions and 215 deletions

View File

@ -0,0 +1,166 @@
<?php
namespace Incoviba\Service\Venta\MediosPago;
use HttpException;
use Incoviba\Common\Define\Repository;
use Incoviba\Common\Ideal\LoggerEnabled;
use Incoviba\Common\Implement\Exception\{EmptyResponse, EmptyResult};
use Incoviba\Exception\InvalidResult;
use PDOException;
use Psr\Http\Client\ClientExceptionInterface;
use Psr\Http\Client\ClientInterface;
use Psr\Http\Message\ResponseInterface;
abstract class AbstractEndPoint extends LoggerEnabled implements EndPoint
{
public function __construct(protected ClientInterface $client) {}
/**
* @param ResponseInterface $response
* @param string $request_uri
* @param array $validStatus
* @param array $invalidStatus
* @return void
* @throws EmptyResponse
*/
protected function validateResponse(ResponseInterface $response, string $request_uri, array $validStatus, array $invalidStatus): void
{
$status = $response->getStatusCode();
$reason = $response->getReasonPhrase();
$contents = $response->getBody()->getContents();
if (in_array($status, $invalidStatus)) {
$exception = new HttpException("{$reason}\n{$contents}", $status);
throw new EmptyResponse($request_uri, $exception);
}
if (!in_array($status, $validStatus)) {
$exception = new HttpException("{$reason}\n{$contents}", $status);
throw new EmptyResponse($request_uri, $exception);
}
}
/**
* @param string $request_uri
* @param array $validStatus
* @param array $invalidStatus
* @return string
* @throws EmptyResponse
*/
protected function sendGet(string $request_uri, array $validStatus, array $invalidStatus): array
{
try {
$response = $this->client->get($request_uri);
} catch (ClientExceptionInterface $exception) {
throw new EmptyResponse($request_uri, $exception);
}
$this->validateResponse($response, $request_uri, $validStatus, $invalidStatus);
return json_decode($response->getBody()->getContents(), true);
}
/**
* @param string $request_uri
* @param array $data
* @param array $validStatus
* @param array $invalidStatus
* @return string
* @throws EmptyResponse
*/
protected function sendAdd(string $request_uri, array $data, array $validStatus, array $invalidStatus): bool
{
$params = $this->mapParams($data);
try {
$response = $this->client->post($request_uri, ['json' => $params]);
} catch (ClientExceptionInterface $exception) {
throw new EmptyResponse($request_uri, $exception);
}
$this->validateResponse($response, $request_uri, $validStatus, $invalidStatus);
$contents = $response->getBody()->getContents();
$json = json_decode($contents, true);
return $this->save($json);
}
/**
* @param string $request_uri
* @param array $data
* @param array $validStatus
* @param array $invalidStatus
* @return string
* @throws EmptyResponse
*/
protected function sendEdit(string $request_uri, array $data, array $validStatus, array $invalidStatus): bool
{
$params = $this->mapParams($data);
try {
$response = $this->client->put($request_uri, ['json' => $params]);
} catch (ClientExceptionInterface $exception) {
throw new EmptyResponse($request_uri, $exception);
}
$this->validateResponse($response, $request_uri, $validStatus, $invalidStatus);
$contents = $response->getBody()->getContents();
$json = json_decode($contents, true);
return $this->save($json);
}
/**
* @param string $request_uri
* @param array $validStatus
* @param array $invalidStatus
* @return void
* @throws EmptyResponse
*/
protected function sendDelete(string $request_uri, array $validStatus, array $invalidStatus): void
{
try {
$response = $this->client->delete($request_uri);
} catch (ClientExceptionInterface $exception) {
throw new EmptyResponse($request_uri, $exception);
}
$this->validateResponse($response, $request_uri, $validStatus, $invalidStatus);
}
protected function doSave(Repository $repository, array $data): bool
{
try {
$repository->fetchById($data['id']);
return true;
} catch (EmptyResult) {
$mappedData = $this->mapSave($data);
$filteredData = $repository->filterData($mappedData);
$model = $repository->create($filteredData);
try {
$repository->save($model);
return true;
} catch (PDOException $exception) {
$this->logger->warning($exception);
return false;
}
}
}
/**
* @param callable $callable
* @param string $id
* @param string $message
* @return array
* @throws InvalidResult
*/
protected function doGetById(callable $callable, string $id, string $message): array
{
try {
$model = $callable($id);
return json_decode(json_encode($model), true);
} catch (EmptyResult $exception) {
throw new InvalidResult($message, 404, $exception);
}
}
abstract protected function mapParams(array $data): array;
abstract protected function mapSave(array $data): array;
abstract protected function save(array $data): bool;
}

View File

@ -0,0 +1,50 @@
<?php
namespace Incoviba\Service\Venta\MediosPago;
use Incoviba\Common\Implement\Exception\EmptyResponse;
use Incoviba\Exception\InvalidResult;
interface EndPoint
{
/**
* @param string $id
* @return array
* @throws InvalidResult
*/
public function getById(string $id): array;
/**
* @param string $id
* @return array
* @throws InvalidResult
*/
public function getByExternalId(string $id): array;
/**
* @param string $id
* @return array
* @throws EmptyResponse
*/
public function get(string $id): array;
/**
* @param array $data
* @return bool
* @throws EmptyResponse
*/
public function add(array $data): bool;
/**
* @param string $id
* @param array $data
* @return bool
* @throws EmptyResponse
*/
public function edit(string $id, array $data): bool;
/**
* @param string $id
* @return void
* @throws EmptyResponse
*/
public function delete(string $id): void;
}

View File

@ -0,0 +1,147 @@
<?php
namespace Incoviba\Service\Venta\MediosPago;
use Incoviba\Common\Ideal;
use Incoviba\Common\Implement\Exception\EmptyResponse;
use Incoviba\Exception\InvalidResult;
use Incoviba\Model;
use Incoviba\Model\Persona;
use Incoviba\Model\Venta\Propietario;
use InvalidArgumentException;
use Psr\Log\LoggerInterface;
class Toku extends Ideal\Service
{
public function __construct(LoggerInterface $logger)
{
parent::__construct($logger);
}
const string CUSTOMER = 'customer';
const string SUBSCRIPTION = 'subscription';
const string INVOICE = 'invoice';
protected EndPoint $customer;
protected EndPoint $subscription;
protected EndPoint $invoice;
public function register(string $type, EndPoint $endPoint): self
{
if (!in_array(strtolower($type), ['customer', 'subscription', 'invoice'])) {
throw new InvalidArgumentException("{$type} is not a valid type of EndPoint for " . __CLASS__);
}
$this->{strtolower($type)} = $endPoint;
return $this;
}
/**
* @param Persona|Propietario $persona
* @return array
* @throws InvalidResult
*/
public function sendPersona(Model\Persona|Model\Venta\Propietario $persona): array
{
$rut = implode('', [$persona->rut, strtoupper($persona->dv)]);
try {
return $this->customer->getById($rut);
} catch (InvalidResult $exception) {
$datos = $persona->datos;
$customerData = [
'rut' => $rut,
'nombreCompleto' => $persona->nombreCompleto(),
'email' => $datos?->email ?? '',
'telefono' => $datos?->telefono ?? ''
];
try {
if (!$this->customer->add($customerData)) {
throw new InvalidResult("Could not save Customer for Persona {$rut}", 409, $exception);
}
} catch (EmptyResponse $exception) {
throw new InvalidResult("Could not save Customer for Persona {$rut}", 409, $exception);
}
return $this->customer->getById($rut);
}
}
/**
* @param Model\Venta $venta
* @return array
* @throws InvalidResult
*/
public function sendVenta(Model\Venta $venta): array
{
$customer = $this->sendPersona($venta->propietario());
try {
return $this->subscription->getById($venta->id);
} catch (InvalidResult $exception) {
$subscriptionData = [
'customer' => $customer['toku_id'],
'product_id' => $venta->id,
'venta' => $venta
];
try {
if (!$this->subscription->add($subscriptionData)) {
throw new InvalidResult("Could not save Subscription for Venta {$venta->id}", 409, $exception);
}
} catch (EmptyResponse $exception) {
throw new InvalidResult("Could not save Subscription for Venta {$venta->id}", 409, $exception);
}
return $this->subscription->getById($venta->id);
}
}
/**
* @param Model\Venta $venta
* @param array $cuotas_ids
* @return array
* @throws InvalidResult
*/
public function sendCuotas(Model\Venta $venta, array $cuotas_ids = []): array
{
$customer = $this->sendPersona($venta->propietario());
$subscription = $this->sendVenta($venta);
$invoices = [];
$errors = [];
foreach ($venta->formaPago()->pie->cuotas() as $cuota) {
if (count($cuotas_ids) > 0 and !in_array($cuota->id, $cuotas_ids)) {
continue;
}
try {
$invoices []= $this->invoice->getById($cuota->id);
} catch (InvalidResult $exception) {
try {
$invoiceData = [
'customer' => $customer['toku_id'],
'product_id' => $venta->id,
'subscription' => $subscription['toku_id'],
'cuota' => $cuota
];
if (!$this->invoice->add($invoiceData)) {
throw new EmptyResponse("Could not add Invoice for Cuota {$cuota->id}", $exception);
}
$invoices []= $this->invoice->getById($cuota->id);
} catch (EmptyResponse $exception) {
$this->logger->warning($exception);
$errors []= $exception;
}
}
}
if (count($errors) > 0) {
$this->logger->warning("Revisar el envío de cuotas de la Venta {$venta->id}");
}
return $invoices;
}
/**
* @param array $request
* @return bool
* @throws InvalidResult
*/
public function updatePago(array $request): bool
{
# If $customer is not found, it will throw an exception and stop
$customer = $this->customer->getByExternalId($request['customer']);
$invoice = $this->invoice->getByExternalId($request['invoice']);
return $this->invoice->update($invoice['id'], $request);
}
}

View File

@ -0,0 +1,96 @@
<?php
namespace Incoviba\Service\Venta\MediosPago\Toku;
use Incoviba\Repository;
use Incoviba\Service\Venta\MediosPago\AbstractEndPoint;
use Psr\Http\Client\ClientInterface;
class Customer extends AbstractEndPoint
{
public function __construct(ClientInterface $client,
protected Repository\Venta\MediosPago\Toku\Customer $customerRepository)
{
parent::__construct($client);
}
public function getById(string $id): array
{
return $this->doGetById([$this->customerRepository, 'fetchByRut'], $id, "No existe toku_id para Persona {$id}");
}
public function getByExternalId(string $id): array
{
return $this->doGetById([$this->customerRepository, 'fetchByTokuId'], $id, "No existe Customer para toku_id {$id}");
}
public function get(string $id): array
{
$request_uri = "/customers/{$id}";
return $this->sendGet($request_uri, [200], [404, 422]);
}
public function add(array $data): bool
{
$request_uri = "/customers";
return $this->sendAdd($request_uri, $data, [200, 201], [400, 422]);
}
public function edit(string $id, array $data): bool
{
$request_uri = "customers/{$id}";
return $this->sendEdit($request_uri, $data, [200], [400, 404, 422]);
}
public function delete(string $id): void
{
$request_uri = "/customer/{$id}";
$this->sendDelete($request_uri, [204], [404, 409]);
}
protected function save(array $data): bool
{
return $this->doSave($this->customerRepository, $data);
}
protected function mapParams(array $data): array
{
$paramsMap = [
'government_id' => 'rut',
'external_id' => 'rut',
'email' => 'email',
'name' => 'nombreCompleto',
'phone_number' => 'telefono',
'pac_mandate_id' => null,
'default_agent' => 'contacto@incoviba.cl',
'send_mail' => false,
'agent_phone_number' => null,
'rfc' => null,
'tax_zip_code' => null,
'fiscal_regime' => null,
'default_receipt_type' => null,
'secondary_emails' => null,
'silenced_until' => null,
'metadata' => null
];
$params = [];
foreach ($paramsMap as $key => $ref) {
if ($ref === null) {
continue;
}
if (array_key_exists($ref, $data)) {
$params[$key] = $data[$ref];
}
}
return $params;
}
protected function mapSave(array $data): array
{
$responseMap = [
'government_id' => 'rut',
'id' => 'toku_id'
];
$mappedData = [];
foreach ($responseMap as $responseKey => $dataKey) {
if (isset($data[$responseKey])) {
$mappedData[$dataKey] = $data[$responseKey];
}
}
return $mappedData;
}
}

View File

@ -0,0 +1,159 @@
<?php
namespace Incoviba\Service\Venta\MediosPago\Toku;
use DateMalformedStringException;
use DateTimeImmutable;
use Incoviba\Common\Implement\Exception\EmptyResult;
use Incoviba\Exception\InvalidResult;
use Incoviba\Model;
use Incoviba\Repository;
use Incoviba\Service\UF;
use Incoviba\Service\Venta\MediosPago\AbstractEndPoint;
use Incoviba\Service\Venta\Pago;
use Psr\Http\Client\ClientInterface;
class Invoice extends AbstractEndPoint
{
public function __construct(ClientInterface $client,
protected Repository\Venta\MediosPago\Toku\Invoice $invoiceRepository,
protected Pago $pagoService, protected UF $ufService)
{
parent::__construct($client);
}
public function getById(string $id): array
{
return $this->doGetById([$this->invoiceRepository, 'fetchByCuota'], $id, "No existe toku_id para Cuota {$id}");
}
public function getByExternalId(string $id): array
{
return $this->doGetById([$this->invoiceRepository, 'fetchByTokuId'], $id, "No existe Invoice para toku_id {$id}");
}
public function get(string $id): array
{
$request_uri = "/invoices/{$id}";
return $this->sendGet($request_uri, [200], [404]);
}
public function add(array $data): bool
{
$request_uri = "/invoices";
return $this->sendAdd($request_uri, $data, [200, 201], [400, 409, 422]);
}
public function edit(string $id, array $data): bool
{
$request_uri = "/invoices/{$id}";
return $this->sendEdit($request_uri, $data, [200], [400, 404, 409, 422]);
}
public function delete(string $id): void
{
$request_uri = "/invoices/{$id}";
$this->sendDelete($request_uri, [204], [404, 409]);
}
/**
* @param string $invoice_toku_id
* @param array $data
* @return bool
* @throws InvalidResult
*/
public function update(string $invoice_toku_id, array $data): bool
{
try {
$invoice = $this->invoiceRepository->fetchByTokuId($invoice_toku_id);
} catch (EmptyResult $exception) {
throw new InvalidResult("No existe Invoice para toku_id {$invoice_toku_id}", 404, $exception);
}
if ($data['status'] !== 'AUTHORIZED') {
throw new InvalidResult("Pago no autorizado", 422);
}
try {
$date = new DateTimeImmutable($data['transaction_date']);
} catch (DateMalformedStringException $exception) {
throw new InvalidResult("Fecha no válida: {$data['transaction_date']}", 422, $exception);
}
$uf = $this->ufService->get($date);
if ($uf === 0.0) {
throw new InvalidResult("No hay UF para la fecha: {$data['transaction_date']}", 422);
}
$valor = $data['amount'] / $uf;
if (abs($valor - $invoice->cuota->pago->valor()) >= 0.0001) {
throw new InvalidResult("Valor en UF no coincide: {$data['amount']}", 422);
}
return $this->pagoService->depositar($invoice->cuota->pago, $date);
}
protected function save(array $data): bool
{
return $this->doSave($this->invoiceRepository, $data);
}
protected function mapParams(array $data): array
{
$paramsMap = [
'customer' => 'customer',
'product_id' => 'product_id',
'due_date' => 'fecha',
'subscription' => 'subscription',
'amount' => 'valor',
'is_paid' => null,
'is_void' => null,
'link_payment' => null,
'metadata' => 'datosCuota',
'receipt_type' => null,
'id_receipt' => null,
'disable_automatic_payment' => null,
'currency_code' => 'CLF',
'invoice_external_id' => 'cuota_id'
];
$params = [];
foreach ($paramsMap as $key => $ref) {
if ($ref === null) {
continue;
}
if ($ref === 'fecha') {
$params[$key] = $data['cuota']->pago->fecha->format('Y-m-d');
continue;
}
if ($ref === 'valor') {
$params[$key] = $data['cuota']->pago->valor();
continue;
}
if ($ref === 'datosCuota') {
$params[$key] = $this->datosCuota($data['cuota']);
continue;
}
if ($ref === 'cuota_id') {
$params[$key] = $data['cuota']->id;
continue;
}
if (array_key_exists($ref, $data)) {
$params[$key] = $data[$ref];
}
}
return $params;
}
protected function mapSave(array $data): array
{
$responseMap = [
'invoice_external_id' => 'cuota_id',
'id' => 'toku_id'
];
$mappedData = [];
foreach ($responseMap as $responseKey => $dataKey) {
if (isset($data[$responseKey])) {
$mappedData[$dataKey] = $data[$responseKey];
}
}
return $mappedData;
}
protected function datosCuota(Model\Venta\Cuota $cuota): string
{
return json_encode([
'Numero' => $cuota->numero,
'valor' => $cuota->pago->valor,
'UF' => $cuota->pago->valor()
]);
}
}

View File

@ -0,0 +1,105 @@
<?php
namespace Incoviba\Service\Venta\MediosPago\Toku;
use Incoviba\Model\Venta;
use Incoviba\Repository;
use Incoviba\Service\Venta\MediosPago\AbstractEndPoint;
use Psr\Http\Client\ClientInterface;
class Subscription extends AbstractEndPoint
{
public function __construct(ClientInterface $client, protected Repository\Venta\MediosPago\Toku\Subscription $subscriptionRepsitory)
{
parent::__construct($client);
}
public function getById(string $id): array
{
return $this->doGetById([$this->subscriptionRepsitory, 'fetchByVenta'], $id, "No existe toku_id para Venta {$id}");
}
public function getByExternalId(string $id): array
{
return $this->doGetById([$this->subscriptionRepsitory, 'fetchByTokuId'], $id, "No existe Subscription para toku_id {$id}");
}
public function get(string $id): array
{
$request_uri = "/subscriptions/{$id}";
return $this->sendGet($request_uri, [200], [401, 404, 422]);
}
public function add(array $data): bool
{
$request_uri = '/subscriptions';
return $this->sendAdd($request_uri, $data, [200, 201], [401, 404, 409, 422]);
}
public function edit(string $id, array $data): bool
{
$request_uri = "/subscriptions/{$id}";
return $this->sendEdit($request_uri, $data, [200], [401, 404, 409, 422]);
}
public function delete(string $id): void
{
$request_uri = "/subscriptions/{$id}";
$this->sendDelete($request_uri, [204], [404, 409]);
}
protected function save(array $data): bool
{
return $this->doSave($this->subscriptionRepsitory, $data);
}
protected function mapParams(array $data): array
{
$paramsMap = [
'customer' => 'customer',
'product_id' => 'product_id',
'pac_mandate_id' => null,
'is_recurring' => null,
'due_day' => null,
'amount' => 'pieValor',
'receipt_product_code' => null,
'metadata' => 'datosVenta'
];
$params = [];
foreach ($paramsMap as $key => $ref) {
if ($ref === null) {
continue;
}
if ($ref === 'pieValor') {
$params[$key] = $data['venta']->formaPago()?->pie?->valor ?? 0;
continue;
}
if ($ref === 'datosVenta') {
$params[$key] = $this->datosVenta($data['venta']);
continue;
}
if (array_key_exists($ref, $data)) {
$params[$key] = $data[$ref];
}
}
return $params;
}
protected function mapSave(array $data): array
{
$responseMap = [
'product_id' => 'venta_id',
'id' => 'toku_id'
];
$mappedData = [];
foreach ($responseMap as $responseKey => $dataKey) {
if (isset($data[$responseKey])) {
$mappedData[$dataKey] = $data[$responseKey];
}
}
return $mappedData;
}
protected function datosVenta(Venta $venta): string
{
$datos = [
'proyecto' => $venta->proyecto()->descripcion,
'propiedad' => $venta->propiedad()->summary()
];
return json_encode($datos);
}
}