14 Commits

48 changed files with 2359 additions and 66 deletions

View File

@ -0,0 +1,18 @@
<?php
namespace Incoviba\Common\Ideal;
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerInterface;
abstract class LoggerEnabled implements LoggerAwareInterface
{
protected LoggerInterface $logger;
public function setLogger(LoggerInterface $logger): void
{
$this->logger = $logger;
}
public function getLogger(): LoggerInterface
{
return $this->logger;
}
}

View File

@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
use Phinx\Migration\AbstractMigration;
final class CreateTokuCustomers extends AbstractMigration
{
/**
* Change Method.
*
* Write your reversible migrations using this method.
*
* More information on writing migrations is available here:
* https://book.cakephp.org/phinx/0/en/migrations.html#the-change-method
*
* Remember to call "create()" or "update()" and NOT "save()" when working
* with the Table class.
*/
public function change(): void
{
$this->table('toku_customers')
->addColumn('rut', 'string', ['length' => 9])
->addColumn('toku_id', 'string', ['length' => 255])
->addTimestamps()
->create();
}
}

View File

@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
use Phinx\Migration\AbstractMigration;
final class CreateTokuSubscriptions extends AbstractMigration
{
/**
* Change Method.
*
* Write your reversible migrations using this method.
*
* More information on writing migrations is available here:
* https://book.cakephp.org/phinx/0/en/migrations.html#the-change-method
*
* Remember to call "create()" or "update()" and NOT "save()" when working
* with the Table class.
*/
public function change(): void
{
$this->table('toku_subscriptions')
->addColumn('venta_id', 'integer', ['signed' => false])
->addColumn('toku_id', 'string', ['length' => 255])
->addTimestamps()
->create();
}
}

View File

@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
use Phinx\Migration\AbstractMigration;
final class CreateTokuInvoices extends AbstractMigration
{
/**
* Change Method.
*
* Write your reversible migrations using this method.
*
* More information on writing migrations is available here:
* https://book.cakephp.org/phinx/0/en/migrations.html#the-change-method
*
* Remember to call "create()" or "update()" and NOT "save()" when working
* with the Table class.
*/
public function change(): void
{
$this->table('toku_invoices')
->addColumn('cuota_id', 'integer', ['signed' => false])
->addColumn('toku_id', 'string', ['length' => 255])
->addTimestamps()
->create();
}
}

View File

@ -18,6 +18,8 @@
</div>
@endsection
@include('layout.body.scripts.rut')
@push('page_scripts')
@include('ventas.facturacion.show.factura')
@include('ventas.facturacion.show.propietario')

View File

@ -28,7 +28,11 @@
facturas.draw().facturas()
},
rut: rut => {
this.props.rut = rut
rut = rut.replaceAll(/~\d|\.|-/g, '')
const digito = rut.slice(-1)
rut = rut.slice(0, -1)
this.props.rut = Rut.format(rut) + '-' + digito
document.getElementById('rut'+this.props.index).value = this.props.rut
facturas.venta.update().facturas()
facturas.draw().facturas()
},
@ -72,7 +76,7 @@
})
},
rut: () => {
document.getElementById('rut'+this.props.index).addEventListener('input', inputEvent => {
document.getElementById('rut'+this.props.index).addEventListener('change', inputEvent => {
const rut = inputEvent.currentTarget.value
if (rut === this.props.rut) {
return
@ -81,7 +85,7 @@
})
},
nombre: () => {
document.getElementById('propietario'+this.props.index).addEventListener('input', inputEvent => {
document.getElementById('propietario'+this.props.index).addEventListener('change', inputEvent => {
const nombre = inputEvent.currentTarget.value
if (nombre === this.props.nombre) {
return
@ -90,7 +94,7 @@
})
},
direccion: () => {
document.getElementById('direccion_propietario'+this.props.index).addEventListener('input', inputEvent => {
document.getElementById('direccion_propietario'+this.props.index).addEventListener('change', inputEvent => {
const direccion = inputEvent.currentTarget.value
if (direccion === this.props.direccion) {
return

View File

@ -0,0 +1,24 @@
<?php
namespace Incoviba\Model\MediosPago\Toku;
use Incoviba\Common\Ideal;
use Incoviba\Model\Persona;
class Customer extends Ideal\Model
{
public Persona $persona;
public string $toku_id;
public function rut(): string
{
return implode('', [$this->persona->rut, strtoupper($this->persona->digito)]);
}
protected function jsonComplement(): array
{
return [
'rut' => $this->rut(),
'toku_id' => $this->toku_id
];
}
}

View File

@ -0,0 +1,19 @@
<?php
namespace Incoviba\Model\MediosPago\Toku;
use Incoviba\Common\Ideal;
use Incoviba\Model\Venta\Cuota;
class Invoice extends Ideal\Model
{
public Cuota $cuota;
public string $toku_id;
protected function jsonComplement(): array
{
return [
'cuota_id' => $this->cuota->id,
'toku_id' => $this->toku_id
];
}
}

View File

@ -0,0 +1,19 @@
<?php
namespace Incoviba\Model\MediosPago\Toku;
use Incoviba\Common\Ideal;
use Incoviba\Model\Venta;
class Subscription extends Ideal\Model
{
public Venta $venta;
public string $toku_id;
protected function jsonComplement(): array
{
return [
'venta_id' => $this->venta->id,
'toku_id' => $this->toku_id
];
}
}

View File

@ -0,0 +1,68 @@
<?php
namespace Incoviba\Repository\MediosPago\Toku;
use DateTimeImmutable;
use Incoviba\Common\Define;
use Incoviba\Common\Ideal;
use Incoviba\Common\Implement;
use Incoviba\Model;
use Incoviba\Service;
class Customer extends Ideal\Repository
{
public function __construct(Define\Connection $connection, protected Service\Persona $personaService)
{
parent::__construct($connection);
}
public function getTable(): string
{
return 'teku_customers';
}
public function create(?array $data = null): Model\MediosPago\Toku\Customer
{
$map = (new Implement\Repository\MapperParser(['toku_id']))
->register('rut', (new Implement\Repository\Mapper())
->setProperty('persona')
->setFunction(function($data) {
$rut = (int) substr($data['rut'], 0, -1);
return $this->personaService->getById($rut);
})
);
return $this->parseData(new Model\MediosPago\Toku\Customer(), $data, $map);
}
public function save(Define\Model $model): Model\MediosPago\Toku\Customer
{
$model->id = $this->saveNew(
['rut', 'toku_id', 'created_at'],
[implode('', [$model->persona->rut, $model->persona->digito]), $model->toku_id, (new DateTimeImmutable())->format('Y-m-d H:i:s.u')]
);
return $model;
}
public function edit(Define\Model $model, array $new_data): Model\MediosPago\Toku\Customer
{
return $this->update($model, ['rut', 'toku_id', 'updated_at'], array_merge($new_data, ['updated_at' => (new DateTimeImmutable())->format('Y-m-d H:i:s.u')]));
}
/**
* @param string $rut
* @return Model\MediosPago\Toku\Customer
* @throws Implement\Exception\EmptyResult
*/
public function fetchByRut(string $rut): Model\MediosPago\Toku\Customer
{
if (str_contains($rut, '-')) {
$rut = str_replace('-', '', $rut);
}
if (str_contains($rut, '.')) {
$rut = str_replace('.', '', $rut);
}
$rut = strtoupper($rut);
$query = $this->connection->getQueryBuilder()
->select()
->from($this->getTable())
->where('rut = :rut');
return $this->fetchOne($query, compact('rut'));
}
}

View File

@ -0,0 +1,53 @@
<?php
namespace Incoviba\Repository\MediosPago\Toku;
use DateTimeImmutable;
use Incoviba\Common\Define;
use Incoviba\Common\Ideal;
use Incoviba\Common\Implement;
use Incoviba\Repository;
use Incoviba\Model;
class Invoice extends Ideal\Repository
{
public function __construct(Define\Connection $connection, protected Repository\Venta\Cuota $cuotaRepository)
{
parent::__construct($connection);
}
public function getTable(): string
{
return 'toku_invoices';
}
public function create(?array $data = null): Model\MediosPago\Toku\Invoice
{
$map = (new Implement\Repository\MapperParser(['toku_id']))
->register('cuota_id', (new Implement\Repository\Mapper())
->setProperty('cuota')
->setFunction(function($data) {
return $this->cuotaRepository->fetchById($data['cuota_id']);
}));
return $this->parseData(new Model\MediosPago\Toku\Invoice(), $data, $map);
}
public function save(Define\Model $model): Model\MediosPago\Toku\Invoice
{
$model->id = $this->saveNew(
['cuota_id', 'toku_id', 'created_at'],
[$model->cuota->id, $model->toku_id, (new DateTimeImmutable())->format('Y-m-d H:i:s.u')]
);
return $model;
}
public function edit(Define\Model $model, array $new_data): Model\MediosPago\Toku\Invoice
{
return $this->update($model, ['cuota_id', 'toku_id', 'updated_at'], array_merge($new_data, ['updated_at' => (new DateTimeImmutable())->format('Y-m-d H:i:s.u')]));
}
public function fetchByCuota(int $cuota_id): Model\MediosPago\Toku\Invoice
{
$query = $this->connection->getQueryBuilder()
->select()
->from($this->getTable())
->where('cuota_id = :cuota_id');
return $this->fetchOne($query, compact('cuota_id'));
}
}

View File

@ -0,0 +1,54 @@
<?php
namespace Incoviba\Repository\MediosPago\Toku;
use DateTimeImmutable;
use Incoviba\Common\Ideal;
use Incoviba\Common\Define;
use Incoviba\Common\Implement;
use Incoviba\Model;
use Incoviba\Repository;
class Subscription extends Ideal\Repository
{
public function __construct(Define\Connection $connection, protected Repository\Venta $ventaRepository)
{
parent::__construct($connection);
}
public function getTable(): string
{
return 'toku_subscriptions';
}
public function create(?array $data = null): Model\MediosPago\Toku\Subscription
{
$map = (new Implement\Repository\MapperParser(['toku_id']))
->register('venta_id', (new Implement\Repository\Mapper())
->setProperty('venta')
->setFunction(function($data) {
return $this->ventaRepository->fetchById($data['venta_id']);
}));
return $this->parseData(new Model\MediosPago\Toku\Subscription(), $data, $map);
}
public function save(Define\Model $model): Model\MediosPago\Toku\Subscription
{
$model->id = $this->saveNew(
['venta_id', 'toku_id', 'created_at'],
[$model->venta->id, $model->toku_id, (new DateTimeImmutable())->format('Y-m-d H:i:s.u')]
);
return $model;
}
public function edit(Define\Model $model, array $new_data): Model\MediosPago\Toku\Subscription
{
return $this->update($model, ['venta_id', 'toku_id', 'updated_at'], array_merge($new_data, ['updated_at' => (new DateTimeImmutable())->format('Y-m-d H:i:s.u')]));
}
public function fetchByVenta(int $venta_id): Model\MediosPago\Toku\Subscription
{
$query = $this->connection->getQueryBuilder()
->select()
->from($this->getTable())
->where('venta_id = :venta_id');
return $this->fetchOne($query, compact('venta_id'));
}
}

View File

@ -0,0 +1,165 @@
<?php
namespace Incoviba\Service\MediosPago;
use HttpException;
use PDOException;
use Psr\Http\Client\ClientExceptionInterface;
use Psr\Http\Client\ClientInterface;
use Psr\Http\Message\ResponseInterface;
use Incoviba\Common\Define\Repository;
use Incoviba\Common\Implement\Exception\{EmptyResponse, EmptyResult};
use Incoviba\Common\Ideal\LoggerEnabled;
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 EmptyResponse
*/
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 EmptyResponse($message, $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,42 @@
<?php
namespace Incoviba\Service\MediosPago;
use Incoviba\Common\Implement\Exception\EmptyResponse;
interface EndPoint
{
/**
* @param string $id
* @return array
* @throws EmptyResponse
*/
public function getById(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,119 @@
<?php
namespace Incoviba\Service\MediosPago;
use InvalidArgumentException;
use Psr\Http\Client\ClientInterface;
use Psr\Log\LoggerInterface;
use Incoviba\Common\Ideal;
use Incoviba\Common\Implement\Exception\EmptyResponse;
use Incoviba\Model;
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 Model\Persona $persona
* @return array
* @throws EmptyResponse
*/
public function sendPersona(Model\Persona|Model\Venta\Propietario $persona): array
{
$rut = implode('', [$persona->rut, strtoupper($persona->dv)]);
try {
return $this->customer->getById($rut);
} catch (EmptyResponse $exception) {
$datos = $persona->datos;
$customerData = [
'rut' => $rut,
'nombreCompleto' => $persona->nombreCompleto(),
'email' => $datos?->email ?? '',
'telefono' => $datos?->telefono ?? ''
];
if (!$this->customer->add($customerData)) {
throw new EmptyResponse("Could not save Customer for Persona {$rut}", $exception);
}
return $this->customer->getById($rut);
}
}
/**
* @param Model\Venta $venta
* @return bool
* @throws EmptyResponse
*/
public function sendVenta(Model\Venta $venta): array
{
$customer = $this->sendPersona($venta->propietario());
try {
return $this->subscription->getById($venta->id);
} catch (EmptyResponse $exception) {
$subscriptionData = [
'customer' => $customer['toku_id'],
'product_id' => $venta->id,
'venta' => $venta
];
if (!$this->subscription->add($subscriptionData)) {
throw new EmptyResponse("Could not save Subscription for Venta {$venta->id}", $exception);
}
return $this->subscription->getById($venta->id);
}
}
/**
* @param Model\Venta $venta
* @return array
* @throws EmptyResponse
*/
public function sendCuotas(Model\Venta $venta): array
{
$customer = $this->sendPersona($venta->propietario());
$subscription = $this->sendVenta($venta);
$invoices = [];
$errors = [];
foreach ($venta->formaPago()->pie->cuotas() as $cuota) {
try {
$invoices []= $this->invoice->getById($cuota->id);
} catch (EmptyResponse $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;
}
}

View File

@ -0,0 +1,92 @@
<?php
namespace Incoviba\Service\MediosPago\Toku;
use Psr\Http\Client\ClientInterface;
use Incoviba\Repository;
use Incoviba\Service\MediosPago\AbstractEndPoint;
class Customer extends AbstractEndPoint
{
public function __construct(ClientInterface $client,
protected Repository\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 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,115 @@
<?php
namespace Incoviba\Service\MediosPago\Toku;
use Incoviba\Model\Venta\Cuota;
use Psr\Http\Client\ClientInterface;
use Incoviba\Repository;
use Incoviba\Service\MediosPago\AbstractEndPoint;
class Invoice extends AbstractEndPoint
{
public function __construct(ClientInterface $client, protected Repository\MediosPago\Toku\Invoice $invoiceRepository)
{
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 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]);
}
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(Cuota $cuota): string
{
return json_encode([
'Numero' => $cuota->numero,
'valor' => $cuota->pago->valor,
'UF' => $cuota->pago->valor()
]);
}
}

View File

@ -0,0 +1,100 @@
<?php
namespace Incoviba\Service\MediosPago\Toku;
use Psr\Http\Client\ClientInterface;
use Incoviba\Model\Venta;
use Incoviba\Repository;
use Incoviba\Service\MediosPago\AbstractEndPoint;
class Subscription extends AbstractEndPoint
{
public function __construct(ClientInterface $client, protected Repository\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 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);
}
}

View File

@ -152,10 +152,10 @@ class TestBootstrap
spl_autoload_register(function($className) {
$baseTestPath = __DIR__ . "/tests";
$namespaceMap = [
"ProVM\\Tests\\Extension\\" => "{$baseTestPath}/extension",
"ProVM\\Integration\\" => "{$baseTestPath}/integration",
"ProVM\\Unit\\" => "{$baseTestPath}/unit/src",
"ProVM\\Performance\\" => "{$baseTestPath}/performance",
"Tests\\Extension\\" => "{$baseTestPath}/extension",
"Tests\\Integration\\" => "{$baseTestPath}/integration",
"Tests\\Unit\\" => "{$baseTestPath}/unit/src",
"Tests\\Performance\\" => "{$baseTestPath}/performance",
];
foreach ($namespaceMap as $namespace => $path) {
if (str_starts_with($className, $namespace)) {

View File

@ -1,5 +1,5 @@
<?php
namespace ProVM\Tests\Extension;
namespace Tests\Extension;
use GuzzleHttp\Client;
use PHPUnit\Framework\TestCase;
@ -12,4 +12,4 @@ abstract class AbstractIntegration extends TestCase
{
$this->client = new Client(['base_uri' => $_ENV['APP_URL']]);
}
}
}

View File

@ -1,5 +1,5 @@
<?php
namespace ProVM\Tests\Extension;
namespace Tests\Extension;
use PHPUnit\Framework\TestCase;
use Incoviba\Common\Define\Model;
@ -7,4 +7,4 @@ use Incoviba\Common\Define\Model;
abstract class AbstractModel extends TestCase
{
protected Model $model;
}
}

View File

@ -1,5 +1,5 @@
<?php
namespace ProVM\Tests\Extension;
namespace Tests\Extension;
use PHPUnit\Framework\TestCase;
@ -14,4 +14,4 @@ abstract class AbstractPerformance extends TestCase
{
return microtime(true) - $this->startTime;
}
}
}

View File

@ -1,5 +1,5 @@
<?php
namespace ProVM\Tests\Extension;
namespace Tests\Extension;
trait ObjectHasMethodTrait
{
@ -7,4 +7,4 @@ trait ObjectHasMethodTrait
{
$this->assertTrue(method_exists($object, $method), sprintf('The object %s does not have the method %s', get_class($object), $method));
}
}
}

View File

@ -1,5 +1,5 @@
<?php
namespace ProVM\Tests\Extension;
namespace Tests\Extension;
trait testMethodsTrait
{
@ -15,4 +15,4 @@ trait testMethodsTrait
}
protected array $methods = [];
}
}

View File

@ -1,5 +1,5 @@
<?php
namespace ProVM\Tests\Extension;
namespace Tests\Extension;
use Incoviba\Common\Define\Model;
@ -21,4 +21,4 @@ trait testPropertiesTrait
$this->assertObjectHasProperty($key, $model);
}
}
}
}

View File

@ -1,7 +1,7 @@
<?php
namespace ProVM\Integration;
namespace Test\Integration;
use ProVM\Tests\Extension\AbstractIntegration;
use Tests\Extension\AbstractIntegration;
class HomeTest extends AbstractIntegration
{
@ -11,4 +11,4 @@ class HomeTest extends AbstractIntegration
$this->assertEquals(200, $response->getStatusCode());
$this->assertStringContainsString('Incoviba', $response->getBody()->getContents());
}
}
}

View File

@ -1,8 +1,8 @@
<?php
namespace ProVM\Performance;
namespace Tests\Performance;
use GuzzleHttp\Client;
use ProVM\Tests\Extension\AbstractPerformance;
use Tests\Extension\AbstractPerformance;
class HomeTest extends AbstractPerformance
{

View File

@ -0,0 +1,53 @@
<?php
namespace Test\Unit\Model\MediosPago\Toku;
use Faker;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
use Incoviba\Model\MediosPago\Toku\Customer;
use Incoviba\Model\Persona;
class CustomerTest extends TestCase
{
public static function dataProperties(): array
{
return [
['id'],
['persona'],
['toku_id']
];
}
#[DataProvider('dataProperties')]
public function testProperties(string $propertyName): void
{
$customer = new Customer();
$this->assertObjectHasProperty($propertyName, $customer);
}
public function testJson(): void
{
$faker = Faker\Factory::create();
$persona = $this->getMockBuilder(Persona::class)->disableOriginalConstructor()->getMock();
$persona->rut = $faker->randomNumber(8);
$persona->digito = 'k';
$toku_id = $faker->ean13();
$id = $faker->randomNumber(4);
$customer = new Customer();
$customer->id = $id;
$customer->persona = $persona;
$customer->toku_id = $toku_id;
$expected = json_encode([
'id' => $id,
'rut' => implode('', [$persona->rut, strtoupper($persona->digito)]),
'toku_id' => $toku_id
]);
$this->assertJsonStringEqualsJsonString($expected, json_encode($customer));
}
}

View File

@ -0,0 +1,50 @@
<?php
namespace Tests\Unit\Model\MediosPago\Toku;
use Faker;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
use Incoviba\Model;
class InvoiceTest extends TestCase
{
public static function dataProperties(): array
{
return [
['id'],
['cuota'],
['toku_id'],
];
}
#[DataProvider('dataProperties')]
public function testProperties(string $propertyName): void
{
$invoice = new Model\MediosPago\Toku\Invoice();
$this->assertObjectHasProperty($propertyName, $invoice);
}
public function testJson(): void
{
$faker = Faker\Factory::create();
$cuota = $this->getMockBuilder(Model\Venta\Cuota::class)
->disableOriginalConstructor()->getMock();
$cuota->id = $faker->randomNumber();
$toku_id = $faker->ean13();
$id = $faker->randomNumber();
$invoice = new Model\MediosPago\Toku\Invoice();
$invoice->id = $id;
$invoice->cuota = $cuota;
$invoice->toku_id = $toku_id;
$expected = json_encode([
'id' => $id,
'cuota_id' => $cuota->id,
'toku_id' => $toku_id,
]);
$this->assertEquals($expected, json_encode($invoice));
}
}

View File

@ -0,0 +1,49 @@
<?php
namespace Tests\Unit\Model\MediosPago\Toku;
use Faker;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
use Incoviba\Model;
class SubscriptionTest extends TestCase
{
public static function dataProperties(): array
{
return [
['id'],
['venta'],
['toku_id'],
];
}
#[DataProvider('dataProperties')]
public function testProperties(string $propertyName): void
{
$subscription = new Model\MediosPago\Toku\Subscription();
$this->assertObjectHasProperty($propertyName, $subscription);
}
public function testJson(): void
{
$faker = Faker\Factory::create();
$venta = $this->getMockBuilder(Model\Venta::class)->disableOriginalConstructor()->getMock();
$venta->id = $faker->randomNumber();
$toku_id = $faker->ean13();
$id = $faker->randomNumber();
$subscription = new Model\MediosPago\Toku\Subscription();
$subscription->id = $id;
$subscription->venta = $venta;
$subscription->toku_id = $toku_id;
$expected = json_encode([
'id' => $id,
'venta_id' => $venta->id,
'toku_id' => $toku_id,
]);
$this->assertEquals($expected, json_encode($subscription));
}
}

View File

@ -1,9 +1,9 @@
<?php
namespace ProVM\Unit\Model;
namespace Tests\Unit\Model;
use Incoviba\Model\Inmobiliaria\Proveedor;
use ProVM\Tests\Extension\AbstractModel;
use ProVM\Tests\Extension\testPropertiesTrait;
use Tests\Extension\AbstractModel;
use Tests\Extension\testPropertiesTrait;
class ProveedorTest extends AbstractModel
{

View File

@ -1,9 +1,9 @@
<?php
namespace ProVM\Unit\Model\Proyecto\Broker;
namespace Tests\Unit\Model\Proyecto\Broker;
use Incoviba\Model\Proyecto\Broker\Contact;
use ProVM\Tests\Extension\AbstractModel;
use ProVM\Tests\Extension\testPropertiesTrait;
use Tests\Extension\AbstractModel;
use Tests\Extension\testPropertiesTrait;
class ContactTest extends AbstractModel
{
@ -14,4 +14,4 @@ class ContactTest extends AbstractModel
$this->model = new Contact();
$this->properties = ['name', 'email', 'phone', 'address'];
}
}
}

View File

@ -1,9 +1,9 @@
<?php
namespace ProVM\Unit\Model\Proyecto\Broker\Contract;
namespace Tests\Unit\Model\Proyecto\Broker\Contract;
use Incoviba\Model\Proyecto\Broker\Contract\State;
use ProVM\Tests\Extension\AbstractModel;
use ProVM\Tests\Extension\testPropertiesTrait;
use Tests\Extension\AbstractModel;
use Tests\Extension\testPropertiesTrait;
class StateTest extends AbstractModel
{
@ -14,4 +14,4 @@ class StateTest extends AbstractModel
$this->model = new State();
$this->properties = ['contract', 'date', 'type'];
}
}
}

View File

@ -1,10 +1,10 @@
<?php
namespace ProVM\Unit\Model\Proyecto\Broker;
namespace Tests\Unit\Model\Proyecto\Broker;
use Incoviba\Model\Proyecto\Broker\Contract;
use ProVM\Tests\Extension\AbstractModel;
use ProVM\Tests\Extension\testMethodsTrait;
use ProVM\Tests\Extension\testPropertiesTrait;
use Tests\Extension\AbstractModel;
use Tests\Extension\testMethodsTrait;
use Tests\Extension\testPropertiesTrait;
class ContractTest extends AbstractModel
{
@ -16,4 +16,4 @@ class ContractTest extends AbstractModel
$this->properties = ['project', 'broker', 'commission'];
$this->methods = ['states', 'current', 'promotions'];
}
}
}

View File

@ -1,9 +1,9 @@
<?php
namespace ProVM\Unit\Model\Proyecto\Broker;
namespace Tests\Unit\Model\Proyecto\Broker;
use Incoviba\Model\Proyecto\Broker;
use ProVM\Tests\Extension\AbstractModel;
use ProVM\Tests\Extension\testPropertiesTrait;
use Tests\Extension\AbstractModel;
use Tests\Extension\testPropertiesTrait;
class DataTest extends AbstractModel
{
@ -14,4 +14,4 @@ class DataTest extends AbstractModel
$this->model = new Broker\Data();
$this->properties = ['broker', 'representative', 'legalName'];
}
}
}

View File

@ -1,10 +1,10 @@
<?php
namespace ProVM\Unit\Model\Proyecto;
namespace Tests\Unit\Model\Proyecto;
use Incoviba\Model\Proyecto\Broker;
use ProVM\Tests\Extension\AbstractModel;
use ProVM\Tests\Extension\testMethodsTrait;
use ProVM\Tests\Extension\testPropertiesTrait;
use Tests\Extension\AbstractModel;
use Tests\Extension\testMethodsTrait;
use Tests\Extension\testPropertiesTrait;
class BrokerTest extends AbstractModel
{
@ -16,4 +16,4 @@ class BrokerTest extends AbstractModel
$this->properties = ['rut', 'digit', 'name'];
$this->methods = ['data', 'contracts'];
}
}
}

View File

@ -1,10 +1,10 @@
<?php
namespace ProVM\Unit\Model\Venta;
namespace Tests\Unit\Model\Venta;
use Incoviba\Model\Venta\Promotion;
use ProVM\Tests\Extension\AbstractModel;
use ProVM\Tests\Extension\testMethodsTrait;
use ProVM\Tests\Extension\testPropertiesTrait;
use Tests\Extension\AbstractModel;
use Tests\Extension\testMethodsTrait;
use Tests\Extension\testPropertiesTrait;
class PromotionTest extends AbstractModel
{
@ -16,4 +16,4 @@ class PromotionTest extends AbstractModel
$this->properties = ['description', 'amount', 'startDate', 'endDate', 'validUntil', 'type', 'state'];
$this->methods = ['projects', 'brokers', 'unitTypes', 'unitLines', 'units', 'value'];
}
}
}

View File

@ -1,9 +1,9 @@
<?php
namespace ProVM\Unit\Model\Venta\Reservation;
namespace Tests\Unit\Model\Venta\Reservation;
use Incoviba\Model\Venta\Reservation\State;
use ProVM\Tests\Extension\AbstractModel;
use ProVM\Tests\Extension\testPropertiesTrait;
use Tests\Extension\AbstractModel;
use Tests\Extension\testPropertiesTrait;
class StateTest extends AbstractModel
{
@ -14,4 +14,4 @@ class StateTest extends AbstractModel
$this->model = new State();
$this->properties = ['reservation', 'date', 'type'];
}
}
}

View File

@ -1,10 +1,10 @@
<?php
namespace ProVM\Unit\Model\Venta;
namespace Tests\Unit\Model\Venta;
use Incoviba\Model\Venta\Reservation;
use ProVM\Tests\Extension\AbstractModel;
use ProVM\Tests\Extension\testMethodsTrait;
use ProVM\Tests\Extension\testPropertiesTrait;
use Tests\Extension\AbstractModel;
use Tests\Extension\testMethodsTrait;
use Tests\Extension\testPropertiesTrait;
class ReservationTest extends AbstractModel
{
@ -16,4 +16,4 @@ class ReservationTest extends AbstractModel
$this->properties = ['buyer', 'date', 'units', 'promotions', 'broker'];
$this->methods = ['states', 'currentState', 'addUnit', 'removeUnit', 'findUnit', 'hasUnit'];
}
}
}

View File

@ -0,0 +1,120 @@
<?php
namespace Tests\Unit\Repository\MediosPago\Toku;
use PDO;
use PHPUnit\Framework\Attributes\Depends;
use PHPUnit\Framework\TestCase;
use Faker;
use Incoviba\Common\Define;
use Incoviba\Model;
use Incoviba\Repository;
use Incoviba\Service;
class CustomerTest extends TestCase
{
protected PDO $pdo;
protected Define\Connection $connection;
protected Model\Persona $persona;
protected Service\Persona $personaService;
protected function setUp(): void
{
$dsn = "mysql:host={$_ENV['DB_HOST']};dbname={$_ENV['DB_DATABASE']}";
$this->pdo = new PDO($dsn, $_ENV['DB_USER'], $_ENV['DB_PASSWORD']);
$this->connection = $this->getMockBuilder(Define\Connection::class)
->disableOriginalConstructor()
->getMock();
$this->connection->method('getPDO')->willReturn($this->pdo);
$faker = Faker\Factory::create();
$datos = $this->getMockBuilder(Model\Persona\Datos::class)
->disableOriginalConstructor()->getMock();
$datos->email = $faker->email();
$datos->telefono = $faker->randomNumber(9);
$this->persona = $this->getMockBuilder(Model\Persona::class)
->disableOriginalConstructor()->getMock();
$this->persona->rut = $faker->randomNumber(8);
$digit = $faker->numberBetween(0, 11);
$this->persona->digito = $digit === 11 ? 'k' : $digit;
$this->persona->method('datos')->willReturn($datos);
$this->personaService = $this->getMockBuilder(Service\Persona::class)
->disableOriginalConstructor()->getMock();
$this->personaService->method('getById')->willReturn($this->persona);
}
public function testCreate(): void
{
$repository = new Repository\MediosPago\Toku\Customer($this->connection, $this->personaService);
$faker = Faker\Factory::create();
$data = [
'rut' => implode('', [$this->persona->rut, $this->persona->digito]),
'toku_id' => $faker->iban(),
];
$customer = $repository->create($data);
$this->assertEquals($this->persona, $customer->persona);
$this->assertEquals($data['toku_id'], $customer->toku_id);
}
public function testSave(): Model\MediosPago\Toku\Customer
{
$repository = new Repository\MediosPago\Toku\Customer($this->connection, $this->personaService);
$faker = Faker\Factory::create();
$data = [
'rut' => implode('', [$this->persona->rut, $this->persona->digito]),
'toku_id' => $faker->iban(),
];
$customer = $repository->create($data);
$customer = $repository->save($customer);
$this->assertNotNull($customer->id);
$this->assertEquals($this->persona, $customer->persona);
$this->assertEquals($data['toku_id'], $customer->toku_id);
return $customer;
}
#[Depends('testSave')]
public function testFetch(Model\MediosPago\Toku\Customer $reference): void
{
$result = [
'id' => $reference->id,
'rut' => implode('', [$this->persona->rut, $this->persona->digito]),
'toku_id' => $reference->toku_id,
];
$resultSet = $this->getMockBuilder(\PDOStatement::class)
->disableOriginalConstructor()->getMock();
$resultSet->method('fetch')->willReturn($result);
$this->connection->method('execute')->willReturn($resultSet);
$repository = new Repository\MediosPago\Toku\Customer($this->connection, $this->personaService);
$customer = $repository->fetchById($reference->id);
$this->assertInstanceOf(Model\MediosPago\Toku\Customer::class, $customer);
$this->assertEquals($reference->id, $customer->id);
$this->assertEquals($this->persona, $customer->persona);
$this->assertEquals($reference->toku_id, $customer->toku_id);
}
#[Depends('testSave')]
public function testFetchByRut(Model\MediosPago\Toku\Customer $reference): void
{
$result = [
'id' => $reference->id,
'rut' => implode('', [$this->persona->rut, $this->persona->digito]),
'toku_id' => $reference->toku_id,
];
$resultSet = $this->getMockBuilder(\PDOStatement::class)
->disableOriginalConstructor()->getMock();
$resultSet->method('fetch')->willReturn($result);
$this->connection->method('execute')->willReturn($resultSet);
$repository = new Repository\MediosPago\Toku\Customer($this->connection, $this->personaService);
$customer = $repository->fetchByRut($this->persona->rut);
$this->assertEquals($reference->id, $customer->id);
$this->assertEquals($this->persona, $customer->persona);
$this->assertEquals($reference->toku_id, $customer->toku_id);
}
}

View File

@ -0,0 +1,113 @@
<?php
namespace Tests\Unit\Repository\MediosPago\Toku;
use PDO;
use PHPUnit\Framework\Attributes\Depends;
use PHPUnit\Framework\TestCase;
use Faker;
use Incoviba\Common\Define;
use Incoviba\Model;
use Incoviba\Repository;
class InvoiceTest extends TestCase
{
protected Define\Connection $connection;
protected PDO $pdo;
protected Model\Venta\Cuota $cuota;
protected Repository\Venta\Cuota $cuotaRepository;
protected function setUp(): void
{
$dsn = "mysql:host={$_ENV['DB_HOST']};dbname={$_ENV['DB_DATABASE']}";
$this->pdo = new PDO($dsn, $_ENV['DB_USER'], $_ENV['DB_PASSWORD']);
$this->connection = $this->getMockBuilder(Define\Connection::class)
->disableOriginalConstructor()->getMock();
$this->connection->method('getPDO')->willReturn($this->pdo);
$faker = Faker\Factory::create();
$this->cuota = $this->getMockBuilder(Model\Venta\Cuota::class)
->disableOriginalConstructor()->getMock();
$this->cuota->id = $faker->randomNumber();
$this->cuotaRepository = $this->getMockBuilder(Repository\Venta\Cuota::class)
->disableOriginalConstructor()->getMock();
$this->cuotaRepository->method('fetchById')->willReturn($this->cuota);
}
public function testCreate(): void
{
$repository = new Repository\MediosPago\Toku\Invoice($this->connection, $this->cuotaRepository);
$faker = Faker\Factory::create();
$data = [
'cuota_id' => $this->cuota->id,
'toku_id' => $faker->ean13(),
];
$invoice = $repository->create($data);
$this->assertEquals($this->cuota->id, $invoice->cuota->id);
$this->assertEquals($data['toku_id'], $invoice->toku_id);
}
public function testSave(): Model\MediosPago\Toku\Invoice
{
$repository = new Repository\MediosPago\Toku\Invoice($this->connection, $this->cuotaRepository);
$faker = Faker\Factory::create();
$data = [
'cuota_id' => $this->cuota->id,
'toku_id' => $faker->ean13(),
];
$invoice = $repository->create($data);
$invoice = $repository->save($invoice);
$this->assertNotNull($invoice->id);
$this->assertEquals($this->cuota->id, $invoice->cuota->id);
$this->assertEquals($data['toku_id'], $invoice->toku_id);
return $invoice;
}
#[Depends('testSave')]
public function testFetch(Model\MediosPago\Toku\Invoice $reference): void
{
$result = [
'id' => $reference->id,
'cuota_id' => $this->cuota->id,
'toku_id' => $reference->toku_id,
];
$resultSet = $this->getMockBuilder(\PDOStatement::class)
->disableOriginalConstructor()->getMock();
$resultSet->method('fetch')->willReturn($result);
$this->connection->method('execute')->willReturn($resultSet);
$repository = new Repository\MediosPago\Toku\Invoice($this->connection, $this->cuotaRepository);
$invoice = $repository->fetchById($reference->id);
$this->assertInstanceOf(Model\MediosPago\Toku\Invoice::class, $invoice);
$this->assertEquals($reference->id, $invoice->id);
$this->assertEquals($this->cuota->id, $invoice->cuota->id);
$this->assertEquals($reference->toku_id, $invoice->toku_id);
}
#[Depends('testSave')]
public function testFetchByCuota(Model\MediosPago\Toku\Invoice $reference): void
{
$result = [
'id' => $reference->id,
'cuota_id' => $this->cuota->id,
'toku_id' => $reference->toku_id,
];
$resultSet = $this->getMockBuilder(\PDOStatement::class)
->disableOriginalConstructor()->getMock();
$resultSet->method('fetch')->willReturn($result);
$this->connection->method('execute')->willReturn($resultSet);
$repository = new Repository\MediosPago\Toku\Invoice($this->connection, $this->cuotaRepository);
$invoice = $repository->fetchByCuota($this->cuota->id);
$this->assertEquals($reference->id, $invoice->id);
$this->assertEquals($this->cuota->id, $invoice->cuota->id);
$this->assertEquals($reference->toku_id, $invoice->toku_id);
}
}

View File

@ -0,0 +1,112 @@
<?php
namespace Tests\Unit\Repository\MediosPago\Toku;
use PDO;
use PHPUnit\Framework\Attributes\Depends;
use PHPUnit\Framework\TestCase;
use Faker;
use Incoviba\Common\Define;
use Incoviba\Model;
use Incoviba\Repository;
class SubscriptionTest extends TestCase
{
protected PDO $pdo;
protected Define\Connection $connection;
protected Model\Venta $venta;
protected Repository\Venta $ventaRepository;
protected function setUp(): void
{
$dsn = "mysql:host={$_ENV['DB_HOST']};dbname={$_ENV['DB_DATABASE']}";
$this->pdo = new PDO($dsn, $_ENV['DB_USER'], $_ENV['DB_PASSWORD']);
$this->connection = $this->getMockBuilder(Define\Connection::class)
->disableOriginalConstructor()
->getMock();
$this->connection->method('getPDO')->willReturn($this->pdo);
$faker = Faker\Factory::create();
$this->venta = $this->getMockBuilder(Model\Venta::class)
->disableOriginalConstructor()->getMock();
$this->venta->id = $faker->randomNumber();
$this->ventaRepository = $this->getMockBuilder(Repository\Venta::class)
->disableOriginalConstructor()->getMock();
$this->ventaRepository->method('fetchById')->willReturn($this->venta);
}
public function testCreate(): void
{
$repository = new Repository\MediosPago\Toku\Subscription($this->connection, $this->ventaRepository);
$faker = Faker\Factory::create();
$data = [
'venta_id' => $this->venta->id,
'toku_id' => $faker->ean13(),
];
$subscription = $repository->create($data);
$this->assertEquals($this->venta->id, $subscription->venta->id);
$this->assertEquals($data['toku_id'], $subscription->toku_id);
}
public function testSave(): Model\MediosPago\Toku\Subscription
{
$repository = new Repository\MediosPago\Toku\Subscription($this->connection, $this->ventaRepository);
$faker = Faker\Factory::create();
$data = [
'venta_id' => $this->venta->id,
'toku_id' => $faker->ean13(),
];
$subscription = $repository->create($data);
$subscription = $repository->save($subscription);
$this->assertNotNull($subscription->id);
$this->assertEquals($this->venta->id, $subscription->venta->id);
$this->assertEquals($data['toku_id'], $subscription->toku_id);
return $subscription;
}
#[Depends('testSave')]
public function testFetch(Model\MediosPago\Toku\Subscription $reference): void
{
$result = [
'id' => $reference->id,
'venta_id' => $this->venta->id,
'toku_id' => $reference->toku_id,
];
$resultSet = $this->getMockBuilder(\PDOStatement::class)
->disableOriginalConstructor()->getMock();
$resultSet->method('fetch')->willReturn($result);
$this->connection->method('execute')->willReturn($resultSet);
$repository = new Repository\MediosPago\Toku\Subscription($this->connection, $this->ventaRepository);
$subscription = $repository->fetchById($reference->id);
$this->assertInstanceOf(Model\MediosPago\Toku\Subscription::class, $subscription);
$this->assertEquals($reference->id, $subscription->id);
$this->assertEquals($this->venta->id, $subscription->venta->id);
$this->assertEquals($reference->toku_id, $subscription->toku_id);
}
#[Depends('testSave')]
public function testFetchByVenta(Model\MediosPago\Toku\Subscription $reference): void
{
$result = [
'id' => $reference->id,
'venta_id' => $this->venta->id,
'toku_id' => $reference->toku_id,
];
$resultSet = $this->getMockBuilder(\PDOStatement::class)
->disableOriginalConstructor()->getMock();
$resultSet->method('fetch')->willReturn($result);
$this->connection->method('execute')->willReturn($resultSet);
$repository = new Repository\MediosPago\Toku\Subscription($this->connection, $this->ventaRepository);
$subscription = $repository->fetchByVenta($this->venta->id);
$this->assertEquals($reference->id, $subscription->id);
$this->assertEquals($this->venta->id, $subscription->venta->id);
$this->assertEquals($reference->toku_id, $subscription->toku_id);
}
}

View File

@ -0,0 +1,191 @@
<?php
namespace Tests\Unit\Service\MediosPago\Toku;
use PDO;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\StreamInterface;
use PHPUnit\Framework\TestCase;
use Faker;
use GuzzleHttp\Client;
use Incoviba\Common\Define;
use Incoviba\Repository;
use Incoviba\Model;
use Incoviba\Service;
class CustomerTest extends TestCase
{
protected Client $client;
protected Model\MediosPago\Toku\Customer $customer;
protected Repository\MediosPago\Toku\Customer $customerRepository;
protected array $getData;
protected array $postData;
protected function setUp(): void
{
$dsn = "mysql:host={$_ENV['DB_HOST']};dbname={$_ENV['DB_DATABASE']}";
$pdo = new PDO($dsn, $_ENV['DB_USER'], $_ENV['DB_PASSWORD']);
$connection = $this->getMockBuilder(Define\Connection::class)
->disableOriginalConstructor()->getMock();
$connection->method('getPDO')->willReturn($pdo);
$faker = Faker\Factory::create();
$datos = $this->getMockBuilder(Model\Persona\Datos::class)
->disableOriginalConstructor()->getMock();
$datos->email = $faker->email();
$datos->telefono = $faker->randomNumber(8);
$persona = $this->getMockBuilder(Model\Persona::class)
->disableOriginalConstructor()->getMock();
$persona->rut = $faker->randomNumber();
$persona->digito = $faker->randomNumber();
$persona->nombres = $faker->firstName();
$persona->apellidoPaterno = $faker->lastName();
$persona->apellidoMaterno = $faker->lastName();
$persona->method('datos')->willReturn($datos);
$persona->method('nombreCompleto')->willReturn(implode(' ', [
$persona->nombres,
$persona->apellidoPaterno,
$persona->apellidoMaterno
]));
$this->customer = $this->getMockBuilder(Model\MediosPago\Toku\Customer::class)
->disableOriginalConstructor()->getMock();
$this->customer->id = $faker->randomNumber();
$this->customer->persona = $persona;
$this->customer->toku_id = $faker->ean13();
$this->customer->method('rut')->willReturn(implode('', [
$persona->rut,
strtoupper($persona->digito)
]));
$this->customer->method('jsonSerialize')->willReturn([
'id' => $this->customer->id,
'rut' => $this->customer->rut(),
'toku_id' => $this->customer->toku_id
]);
$this->customerRepository = $this->getMockBuilder(Repository\MediosPago\Toku\Customer::class)
->disableOriginalConstructor()->getMock();
$this->customerRepository->method('fetchById')->willReturn($this->customer);
$this->customerRepository->method('fetchByRut')->willReturn($this->customer);
$this->getData = [
'id' => $this->customer->id,
'external_id' => $this->customer->rut(),
'government_id' => $this->customer->rut(),
'email' => $persona->datos()->email,
'name' => $persona->nombreCompleto(),
'phone_number' => $persona->datos()->telefono,
'silenced_until' => null,
'default_agent' => null,
'agent_phone_number' => null,
'pac_mandate_id' => null,
'send_mail' => false,
'default_receipt_type' => 'bill',
'rfc' => null,
'tax_zip_code' => null,
'fiscal_regime' => null,
'secondary_emails' => [],
'metadata' => []
];
$getBody = $this->getMockBuilder(StreamInterface::class)
->disableOriginalConstructor()->getMock();
$getBody->method('getContents')->willReturn(json_encode($this->getData));
$getResponse = $this->getMockBuilder(ResponseInterface::class)
->disableOriginalConstructor()->getMock();
$getResponse->method('getStatusCode')->willReturn(200);
$getResponse->method('getBody')->willReturn($getBody);
$this->postData = [
'id' => $this->customer->id,
'external_id' => $this->customer->rut(),
'government_id' => $this->customer->rut(),
'email' => $persona->datos()->email,
'name' => $persona->nombreCompleto(),
'phone_number' => $persona->datos()->telefono,
'silenced_until' => null,
'default_agent' => null,
'agent_phone_number' => null,
'pac_mandate_id' => null,
'send_mail' => false,
'default_receipt_type' => null,
'rfc' => null,
'tax_zip_code' => null,
'fiscal_regime' => null,
'secondary_emails' => [],
'metadata' => []
];
$postBody = $this->getMockBuilder(StreamInterface::class)
->disableOriginalConstructor()->getMock();
$postBody->method('getContents')->willReturn(json_encode($this->postData));
$postResponse = $this->getMockBuilder(ResponseInterface::class)
->disableOriginalConstructor()->getMock();
$postResponse->method('getStatusCode')->willReturn(200);
$postResponse->method('getBody')->willReturn($postBody);
$deleteBody = $this->getMockBuilder(StreamInterface::class)
->disableOriginalConstructor()->getMock();
$deleteBody->method('getContents')->willReturn('Customer Deleted');
$deleteResponse = $this->getMockBuilder(ResponseInterface::class)
->disableOriginalConstructor()->getMock();
$deleteResponse->method('getStatusCode')->willReturn(204);
$deleteResponse->method('getBody')->willReturn($deleteBody);
$this->client = $this->getMockBuilder(Client::class)
->disableOriginalConstructor()->getMock();
$this->client->method('get')->willReturn($getResponse);
$this->client->method('post')->willReturn($postResponse);
$this->client->method('put')->willReturn($postResponse);
$this->client->method('delete')->willReturn($deleteResponse);
}
public function testGetById(): void
{
$service = new Service\MediosPago\Toku\Customer($this->client, $this->customerRepository);
$this->assertEquals(json_decode(json_encode($this->customer), true), $service->getById($this->customer->id));
}
public function testGet(): void
{
$service = new Service\MediosPago\Toku\Customer($this->client, $this->customerRepository);
$this->assertArrayIsEqualToArrayIgnoringListOfKeys($this->getData, $service->get($this->customer->toku_id), []);
}
public function testAdd(): void
{
$service = new Service\MediosPago\Toku\Customer($this->client, $this->customerRepository);
$sendData = [
'rut' => $this->postData['government_id'],
'nombreCompleto' => $this->postData['name'],
'email' => $this->postData['email'],
'telefono' => $this->postData['phone_number']
];
$this->assertTrue($service->add($sendData));
}
public function testEdit(): void
{
$service = new Service\MediosPago\Toku\Customer($this->client, $this->customerRepository);
$sendData = [
'rut' => $this->postData['government_id'],
'nombreCompleto' => $this->postData['name'],
'email' => $this->postData['email'],
'telefono' => $this->postData['phone_number']
];
$this->assertTrue($service->edit($this->customer->toku_id, $sendData));
}
public function testDelete(): void
{
$service = new Service\MediosPago\Toku\Customer($this->client, $this->customerRepository);
$this->expectNotToPerformAssertions();
$service->delete($this->customer->toku_id);
}
}

View File

@ -0,0 +1,200 @@
<?php
namespace Tests\Unit\Service\MediosPago\Toku;
use PDO;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\StreamInterface;
use PHPUnit\Framework\TestCase;
use Faker;
use GuzzleHttp\Client;
use Incoviba\Common\Define;
use Incoviba\Repository;
use Incoviba\Model;
use Incoviba\Service;
class InvoiceTest extends TestCase
{
protected Client $client;
protected Model\MediosPago\Toku\Invoice $invoice;
protected Repository\MediosPago\Toku\Invoice $invoiceRepository;
protected Model\Venta\Cuota $cuota;
protected array $getData;
protected array $saveData;
protected function setUp(): void
{
$dsn = "mysql:host={$_ENV['DB_HOST']};dbname={$_ENV['DB_DATABASE']}";
$pdo = new PDO($dsn, $_ENV['DB_USER'], $_ENV['DB_PASSWORD']);
$connection = $this->getMockBuilder(Define\Connection::class)
->disableOriginalConstructor()->getMock();
$connection->method('getPDO')->willReturn($pdo);
$faker = Faker\Factory::create();
$customer = $this->getMockBuilder(Model\MediosPago\Toku\Customer::class)
->disableOriginalConstructor()->getMock();
$customer->id = $faker->randomNumber();
$customer->toku_id = $faker->ean13();
$venta = $this->getMockBuilder(Model\Venta::class)
->disableOriginalConstructor()->getMock();
$venta->id = $faker->randomNumber();
$subscription = $this->getMockBuilder(Model\MediosPago\Toku\Subscription::class)
->disableOriginalConstructor()->getMock();
$subscription->id = $faker->randomNumber();
$subscription->venta = $venta;
$subscription->toku_id = $faker->ean13();
$pago = $this->getMockBuilder(Model\Venta\Pago::class)
->disableOriginalConstructor()->getMock();
$pago->fecha = $faker->dateTime();
$pago->valor = $faker->randomNumber(6, true);
$pago->method('valor')->willReturn($faker->randomFloat(3, true));
$this->cuota = $this->getMockBuilder(Model\Venta\Cuota::class)
->disableOriginalConstructor()->getMock();
$this->cuota->id = $faker->randomNumber();
$this->cuota->numero = $faker->randomNumber(2);
$this->cuota->pago = $pago;
$this->invoice = $this->getMockBuilder(Model\MediosPago\Toku\Invoice::class)
->disableOriginalConstructor()->getMock();
$this->invoice->id = $faker->randomNumber();
$this->invoice->cuota = $this->cuota;
$this->invoice->toku_id = $faker->ean13();
$this->invoice->method('jsonSerialize')->willReturn([
'id' => $this->invoice->id,
'cuota_id' => $this->cuota->id,
'toku_id' => $this->invoice->toku_id
]);
$this->invoiceRepository = $this->getMockBuilder(Repository\MediosPago\Toku\Invoice::class)
->disableOriginalConstructor()->getMock();
$this->invoiceRepository->method('fetchById')->willReturn($this->invoice);
$this->invoiceRepository->method('fetchByCuota')->willReturn($this->invoice);
$this->getData = [
'customer' => $customer->toku_id,
'product_id' => $subscription->venta->id,
'subscription' => $subscription->toku_id,
'is_paid' => false,
'due_date' => $this->cuota->pago->fecha->format('Y-m-d'),
'is_void' => false,
'amount' => $this->cuota->pago->valor,
'link_payment' => '',
'metadata' => [
'numero' => $this->cuota->numero,
'valor' => $this->cuota->pago->valor,
'UF' => $this->cuota->pago->valor()
],
'receipt_type' => null,
'id_receipt' => null,
'source' => null,
'disable_automatic_payment' => false,
'currency_code' => 'CLP',
'invoice_external_id' => $this->cuota->id,
'id' => $this->invoice->toku_id,
];
$getBody = $this->getMockBuilder(StreamInterface::class)
->disableOriginalConstructor()->getMock();
$getBody->method('getContents')->willReturn(json_encode($this->getData));
$getResponse = $this->getMockBuilder(ResponseInterface::class)
->disableOriginalConstructor()->getMock();
$getResponse->method('getBody')->willReturn($getBody);
$getResponse->method('getStatusCode')->willReturn(200);
$this->postData = [
'customer' => $customer->toku_id,
'product_id' => $subscription->venta->id,
'subscription' => $subscription->toku_id,
'is_paid' => false,
'due_date' => $this->cuota->pago->fecha->format('Y-m-d'),
'is_void' => false,
'amount' => $this->cuota->pago->valor,
'link_payment' => '',
'metadata' => [
'numero' => $this->cuota->numero,
'valor' => $this->cuota->pago->valor,
'UF' => $this->cuota->pago->valor()
],
'receipt_type' => null,
'id_receipt' => null,
'source' => null,
'disable_automatic_payment' => false,
'currency_code' => 'CLF',
'invoice_external_id' => $this->cuota->id,
'id' => $this->invoice->toku_id,
];
$postBody = $this->getMockBuilder(StreamInterface::class)
->disableOriginalConstructor()->getMock();
$postBody->method('getContents')->willReturn(json_encode($this->postData));
$postResponse = $this->getMockBuilder(ResponseInterface::class)
->disableOriginalConstructor()->getMock();
$postResponse->method('getBody')->willReturn($postBody);
$postResponse->method('getStatusCode')->willReturn(200);
$deleteBody = $this->getMockBuilder(StreamInterface::class)
->disableOriginalConstructor()->getMock();
$deleteBody->method('getContents')->willReturn("Invoice deleted");
$deleteResponse = $this->getMockBuilder(ResponseInterface::class)
->disableOriginalConstructor()->getMock();
$deleteResponse->method('getBody')->willReturn($deleteBody);
$deleteResponse->method('getStatusCode')->willReturn(204);
$this->client = $this->getMockBuilder(Client::class)
->disableOriginalConstructor()->getMock();
$this->client->method('get')->willReturn($getResponse);
$this->client->method('post')->willReturn($postResponse);
$this->client->method('put')->willReturn($postResponse);
$this->client->method('delete')->willReturn($deleteResponse);
}
public function testGetById(): void
{
$service = new Service\MediosPago\Toku\Invoice($this->client, $this->invoiceRepository);
$this->assertEquals(json_decode(json_encode($this->invoice), true), $service->getById($this->invoice->toku_id));
}
public function testGet(): void
{
$service = new Service\MediosPago\Toku\Invoice($this->client, $this->invoiceRepository);
$this->assertEquals($this->getData, $service->get($this->invoice->toku_id));
}
public function testAdd(): void
{
$service = new Service\MediosPago\Toku\Invoice($this->client, $this->invoiceRepository);
$sendData = [
'customer' => $this->postData['customer'],
'product_id' => $this->postData['product_id'],
'subscription' => $this->postData['subscription'],
'cuota' => $this->cuota
];
$this->assertTrue($service->add($sendData));
}
public function testEdit(): void
{
$service = new Service\MediosPago\Toku\Invoice($this->client, $this->invoiceRepository);
$sendData = [
'customer' => $this->postData['customer'],
'product_id' => $this->postData['product_id'],
'subscription' => $this->postData['subscription'],
'cuota' => $this->cuota
];
$this->assertTrue($service->edit($this->invoice->toku_id, $sendData));
}
public function testDelete(): void
{
$service = new Service\MediosPago\Toku\Invoice($this->client, $this->invoiceRepository);
$this->expectNotToPerformAssertions();
$service->delete($this->invoice->toku_id);
}
}

View File

@ -0,0 +1,183 @@
<?php
namespace Tests\Unit\Service\MediosPago\Toku;
use PDO;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\StreamInterface;
use PHPUnit\Framework\TestCase;
use Faker;
use GuzzleHttp\Client;
use Incoviba\Common\Define;
use Incoviba\Repository;
use Incoviba\Model;
use Incoviba\Service;
class SubscriptionTest extends TestCase
{
protected Client $client;
protected Model\MediosPago\Toku\Subscription $subscription;
protected Repository\MediosPago\Toku\Subscription $subscriptionRepository;
protected Model\Venta $venta;
protected array $getData;
protected array $postData;
protected function setUp(): void
{
$dsn = "mysql:host={$_ENV['DB_HOST']};dbname={$_ENV['DB_DATABASE']}";
$pdo = new PDO($dsn, $_ENV['DB_USER'], $_ENV['DB_PASSWORD']);
$connection = $this->getMockBuilder(Define\Connection::class)
->disableOriginalConstructor()->getMock();
$connection->method('getPDO')->willReturn($pdo);
$faker = Faker\Factory::create();
$customer = $this->getMockBuilder(Model\MediosPago\Toku\Customer::class)
->disableOriginalConstructor()->getMock();
$customer->id = $faker->randomNumber();
$pie = $this->getMockBuilder(Model\Venta\Pie::class)
->disableOriginalConstructor()->getMock();
$pie->valor = $faker->randomFloat();
$formaPago = $this->getMockBuilder(Model\Venta\FormaPago::class)
->disableOriginalConstructor()->getMock();
$formaPago->pie = $pie;
$proyecto = $this->getMockBuilder(Model\Proyecto::class)
->disableOriginalConstructor()->getMock();
$proyecto->descripcion = $faker->sentence();
$summary = implode(' - ', [
$faker->randomNumber(4),
'E' . $faker->randomNumber(3),
'B' . $faker->randomNumber(3),
]);
$propiedad = $this->getMockBuilder(Model\Venta\Propiedad::class)
->disableOriginalConstructor()->getMock();
$propiedad->method('summary')->willReturn($summary);
$this->venta = $this->getMockBuilder(Model\Venta::class)
->disableOriginalConstructor()->getMock();
$this->venta->id = $faker->randomNumber();
$this->venta->method('formaPago')->willReturn($formaPago);
$this->venta->method('proyecto')->willReturn($proyecto);
$this->venta->method('propiedad')->willReturn($propiedad);
$this->subscription = $this->getMockBuilder(Model\MediosPago\Toku\Subscription::class)
->disableOriginalConstructor()->getMock();
$this->subscription->id = $faker->randomNumber();
$this->subscription->venta = $this->venta;
$this->subscription->toku_id = $faker->ean13();
$this->subscription->method('jsonSerialize')->willReturn([
'id' => $this->subscription->id,
'venta_id' => $this->venta->id,
'toku_id' => $this->subscription->toku_id,
]);
$this->subscriptionRepository = $this->getMockBuilder(Repository\MediosPago\Toku\Subscription::class)
->disableOriginalConstructor()->getMock();
$this->subscriptionRepository->method('fetchById')->willReturn($this->subscription);
$this->subscriptionRepository->method('fetchByVenta')->willReturn($this->subscription);
$this->getData = [
'id' => $this->subscription->toku_id,
'customer' => $customer->id,
'product_id' => $this->venta->id,
'pac_mandate_id' => null,
'is_recurring' => false,
'amount' => $pie->valor,
'due_day' => null,
'receipt_product_code' => null,
'metadata' => [
'proyecto' => $proyecto->descripcion,
'propiedad' => $propiedad->summary(),
]
];
$getBody = $this->getMockBuilder(StreamInterface::class)
->disableOriginalConstructor()->getMock();
$getBody->method('getContents')->willReturn(json_encode($this->getData));
$getResponse = $this->getMockBuilder(ResponseInterface::class)
->disableOriginalConstructor()->getMock();
$getResponse->method('getStatusCode')->willReturn(200);
$getResponse->method('getBody')->willReturn($getBody);
$this->postData = [
'id' => $this->subscription->toku_id,
'customer' => $customer->id,
'product_id' => $this->venta->id,
'pac_mandate_id' => null,
'is_recurring' => false,
'amount' => $pie->valor,
'due_day' => null,
'metadata' => [
'proyecto' => $proyecto->descripcion,
'propiedad' => $propiedad->summary(),
]
];
$postBody = $this->getMockBuilder(StreamInterface::class)
->disableOriginalConstructor()->getMock();
$postBody->method('getContents')->willReturn(json_encode($this->postData));
$postResponse = $this->getMockBuilder(ResponseInterface::class)
->disableOriginalConstructor()->getMock();
$postResponse->method('getStatusCode')->willReturn(200);
$postResponse->method('getBody')->willReturn($postBody);
$deleteBody = $this->getMockBuilder(StreamInterface::class)
->disableOriginalConstructor()->getMock();
$deleteBody->method('getContents')->willReturn('Subscription deleted');
$deleteResponse = $this->getMockBuilder(ResponseInterface::class)
->disableOriginalConstructor()->getMock();
$deleteResponse->method('getStatusCode')->willReturn(204);
$deleteResponse->method('getBody')->willReturn($deleteBody);
$this->client = $this->getMockBuilder(Client::class)
->disableOriginalConstructor()->getMock();
$this->client->method('get')->willReturn($getResponse);
$this->client->method('post')->willReturn($postResponse);
$this->client->method('put')->willReturn($postResponse);
$this->client->method('delete')->willReturn($deleteResponse);
}
public function testGetById(): void
{
$service = new Service\MediosPago\Toku\Subscription($this->client, $this->subscriptionRepository);
$this->assertEquals(json_decode(json_encode($this->subscription), true), $service->getById($this->subscription->toku_id));
}
public function testGet(): void
{
$service = new Service\MediosPago\Toku\Subscription($this->client, $this->subscriptionRepository);
$this->assertArrayIsEqualToArrayIgnoringListOfKeys($this->getData, $service->get($this->subscription->toku_id), []);
}
public function testAdd(): void
{
$service = new Service\MediosPago\Toku\Subscription($this->client, $this->subscriptionRepository);
$sendData = [
'customer' => $this->postData['customer'],
'product_id' => $this->postData['product_id'],
'venta' => $this->venta
];
$this->assertTrue($service->add($sendData));
}
public function testEdit(): void
{
$service = new Service\MediosPago\Toku\Subscription($this->client, $this->subscriptionRepository);
$sendData = [
'customer' => $this->postData['customer'],
'product_id' => $this->postData['product_id'],
'venta' => $this->venta
];
$this->assertTrue($service->edit($this->subscription->toku_id, $sendData));
}
public function testDelete(): void
{
$service = new Service\MediosPago\Toku\Subscription($this->client, $this->subscriptionRepository);
$this->expectNotToPerformAssertions();
$service->delete($this->subscription->toku_id);
}
}

View File

@ -0,0 +1,244 @@
<?php
namespace Tests\Unit\Service\MediosPago;
use Psr\Log\LoggerInterface;
use PHPUnit\Framework\TestCase;
use Faker;
use Incoviba\Model;
use Incoviba\Service;
class TokuTest extends TestCase
{
protected LoggerInterface $logger;
protected Service\MediosPago\Toku\Customer $customerService;
protected Service\MediosPago\Toku\Subscription $subscriptionService;
protected Service\MediosPago\Toku\Invoice $invoiceService;
protected Model\MediosPago\Toku\Customer $customer;
protected Model\MediosPago\Toku\Subscription $subscription;
protected Model\MediosPago\Toku\Invoice $invoice;
protected Model\Persona $persona;
protected Model\Venta $venta;
protected Model\Venta\Cuota $cuota;
protected function setUp(): void
{
$faker = Faker\Factory::create();
$this->logger = $this->getMockBuilder(LoggerInterface::class)
->disableOriginalConstructor()->getMock();
$datos = $this->getMockBuilder(Model\Persona\Datos::class)
->disableOriginalConstructor()->getMock();
$datos->email = $faker->email();
$datos->telefono = $faker->randomNumber(9);
$this->persona = $this->getMockBuilder(Model\Persona::class)
->disableOriginalConstructor()->getMock();
$this->persona->rut = $faker->randomNumber();
$this->persona->digito = 'K';
$this->persona->nombres = $faker->firstName();
$this->persona->apellidoPaterno = $faker->lastName();
$this->persona->apellidoMaterno = $faker->lastName();
$this->persona->method('datos')->willReturn($datos);
$this->persona->method('__get')->with('dv')->willReturn($this->persona->digito);
$this->customer = $this->getMockBuilder(Model\MediosPago\Toku\Customer::class)
->disableOriginalConstructor()->getMock();
$this->customer->id = $faker->randomNumber();
$this->customer->persona = $this->persona;
$this->customer->toku_id = $faker->ean13();
$this->customer->method('rut')->willReturn(implode('', [
$this->persona->rut,
strtoupper($this->persona->digito)
]));
$pie = $this->getMockBuilder(Model\Venta\Pie::class)
->disableOriginalConstructor()->getMock();
$pie->valor = $faker->randomFloat();
$formaPago = $this->getMockBuilder(Model\Venta\FormaPago::class)
->disableOriginalConstructor()->getMock();
$formaPago->pie = $pie;
$proyecto = $this->getMockBuilder(Model\Proyecto::class)
->disableOriginalConstructor()->getMock();
$proyecto->descripcion = $faker->sentence();
$summary = implode(' - ', [
$faker->randomNumber(4),
'E' . $faker->randomNumber(3),
'B' . $faker->randomNumber(3),
]);
$propiedad = $this->getMockBuilder(Model\Venta\Propiedad::class)
->disableOriginalConstructor()->getMock();
$propiedad->method('summary')->willReturn($summary);
$datos2 = $this->getMockBuilder(Model\Venta\Datos::class)
->disableOriginalConstructor()->getMock();
$datos2->email = $datos->email;
$datos2->telefono = $datos->telefono;
$propietario = $this->getMockBuilder(Model\Venta\Propietario::class)
->disableOriginalConstructor()->getMock();
$propietario->rut = $this->persona->rut;
$propietario->dv = $this->persona->dv;
$propietario->nombres = $this->persona->nombres;
$propietario->apellidos = ['paterno' => $this->persona->apellidoPaterno, 'materno' => $this->persona->apellidoMaterno];
$propietario->datos = $datos2;
$this->venta = $this->getMockBuilder(Model\Venta::class)
->disableOriginalConstructor()->getMock();
$this->venta->id = $faker->randomNumber();
$this->venta->method('formaPago')->willReturn($formaPago);
$this->venta->method('proyecto')->willReturn($proyecto);
$this->venta->method('propiedad')->willReturn($propiedad);
$this->venta->method('propietario')->willReturn($propietario);
$this->subscription = $this->getMockBuilder(Model\MediosPago\Toku\Subscription::class)
->disableOriginalConstructor()->getMock();
$this->subscription->id = $faker->randomNumber();
$this->subscription->venta = $this->venta;
$this->subscription->toku_id = $faker->ean13();
$pago = $this->getMockBuilder(Model\Venta\Pago::class)
->disableOriginalConstructor()->getMock();
$pago->fecha = $faker->dateTime();
$pago->valor = $faker->randomNumber(6);
$pago->method('valor')->willReturn($faker->randomFloat(3, 10, 500));
$this->cuota = $this->getMockBuilder(Model\Venta\Cuota::class)
->disableOriginalConstructor()->getMock();
$this->cuota->id = $faker->randomNumber();
$this->cuota->numero = $faker->randomNumber(2);
$this->cuota->pago = $pago;
$pie->method('cuotas')->willReturn([$this->cuota]);
$this->invoice = $this->getMockBuilder(Model\MediosPago\Toku\Invoice::class)
->disableOriginalConstructor()->getMock();
$this->invoice->id = $faker->randomNumber();
$this->invoice->cuota = $this->cuota;
$this->invoice->toku_id = $faker->ean13();
$this->customerService = $this->getMockBuilder(Service\MediosPago\Toku\Customer::class)
->disableOriginalConstructor()->getMock();
$this->customerService->method('getById')->willReturn([
'id' => $this->customer->id,
'rut' => $this->customer->rut(),
'toku_id' => $this->customer->toku_id
]);
$this->customerService->method('get')->willReturn([
'id' => $this->customer->toku_id,
'goverment_id' => $this->customer->rut(),
'external_id' => $this->customer->rut(),
'name' => implode(' ', [$this->persona->nombres, $this->persona->apellidoPaterno, $this->persona->apellidoMaterno]),
'mail' => $this->persona->datos()->email,
'phone_number' => $this->persona->datos()->telefono,
'silenced_until' => null,
'default_agent' => 'contacto@incoviba.cl',
'agent_phone_number' => null,
'pac_mandate_id' => null,
'send_mail' => false,
'default_receipt_type' => null,
'rfc' => null,
'tax_zip_code' => null,
'fiscal_regime' => null,
'secondary_emails' => [],
'metadata' => []
]);
$this->customerService->method('add')->willReturn(true);
$this->customerService->method('edit')->willReturn(true);
$this->customerService->method('delete');
$this->subscriptionService = $this->getMockBuilder(Service\MediosPago\Toku\Subscription::class)
->disableOriginalConstructor()->getMock();
$this->subscriptionService->method('getById')->willReturn([
'id' => $this->subscription->id,
'venta_id' => $this->venta->id,
'toku_id' => $this->subscription->toku_id,
]);
$this->subscriptionService->method('get')->willReturn([
'id' => $this->subscription->toku_id,
'customer' => $this->customer->toku_id,
'product_id' => $this->venta->id,
'pac_mandate_id' => null,
'is_recurring' => false,
'amount' => $pie->valor,
'due_day' => null,
'receipt_product_code' => null,
'metadata' => [
'proyecto' => $proyecto->descripcion,
'propiedad' => $propiedad->summary(),
]
]);
$this->subscriptionService->method('add')->willReturn(true);
$this->subscriptionService->method('edit')->willReturn(true);
$this->subscriptionService->method('delete');
$this->invoiceService = $this->getMockBuilder(Service\MediosPago\Toku\Invoice::class)
->disableOriginalConstructor()->getMock();
$this->invoiceService->method('getById')->willReturn([
'id' => $this->invoice->id,
'cuota_id' => $this->cuota->id,
'toku_id' => $this->invoice->toku_id,
]);
$this->invoiceService->method('get')->willReturn([
'id' => $this->invoice->toku_id,
'customer' => $this->customer->toku_id,
'product_id' => $this->venta->id,
'subscription' => $this->subscription->toku_id,
'is_paid' => false,
'due_date' => $pago->fecha->format('Y-m-d'),
'is_void' => false,
'amount' => $pago->valor(),
'link_payment' => '',
'metadata' => [
'numero' => $this->cuota->numero,
'valor' => $this->cuota->pago->valor,
'UF' => $this->cuota->pago->valor(),
],
'receipt_type' => null,
'id_receipt' => null,
'source' => null,
'disable_automatic_payment' => false,
'currency_code' => 'CLF',
'invoice_external_id' => $this->cuota->id,
]);
$this->invoiceService->method('add')->willReturn(true);
$this->invoiceService->method('edit')->willReturn(true);
$this->invoiceService->method('delete');
}
public function testSendCustomer(): void
{
$service = new Service\MediosPago\Toku($this->logger);
$service->register(Service\MediosPago\Toku::CUSTOMER, $this->customerService);
$expected = [
'id' => $this->customer->id,
'rut' => $this->customer->rut(),
'toku_id' => $this->customer->toku_id
];
$this->assertEquals($expected, $service->sendPersona($this->persona));
}
public function testSendSubscription(): void
{
$service = new Service\MediosPago\Toku($this->logger);
$service->register(Service\MediosPago\Toku::CUSTOMER, $this->customerService);
$service->register(Service\MediosPago\Toku::SUBSCRIPTION, $this->subscriptionService);
$expected = [
'id' => $this->subscription->id,
'venta_id' => $this->venta->id,
'toku_id' => $this->subscription->toku_id,
];
$this->assertEquals($expected, $service->sendVenta($this->venta));
}
public function testSendInvoice(): void
{
$service = new Service\MediosPago\Toku($this->logger);
$service->register(Service\MediosPago\Toku::CUSTOMER, $this->customerService);
$service->register(Service\MediosPago\Toku::SUBSCRIPTION, $this->subscriptionService);
$service->register(Service\MediosPago\Toku::INVOICE, $this->invoiceService);
$expected = [
[
'id' => $this->invoice->id,
'cuota_id' => $this->cuota->id,
'toku_id' => $this->invoice->toku_id,
]
];
$this->assertEquals($expected, $service->sendCuotas($this->venta));
}
}

View File

@ -1,5 +1,5 @@
<?php
namespace ProVM\Unit\Service\Money;
namespace Tests\Unit\Service\Money;
use PDO;
use PDOStatement;

View File

@ -1,5 +1,5 @@
<?php
namespace ProVM\Unit\Service;
namespace Tests\Unit\Service;
use PHPUnit\Framework\TestCase;
use PHPUnit\Framework\Attributes\DataProvider;