20 Commits

Author SHA1 Message Date
8ea4995f6b Contratos desde proyectos 2025-03-03 21:46:53 -03:00
aeeca65d94 Correcciones 2025-03-03 21:41:43 -03:00
5f69069aa0 Rutas Reservations 2025-03-03 16:53:36 -03:00
095a65a643 Cleanup por recomendaciones 2025-03-03 16:37:40 -03:00
928d2e57be Merge branch 'develop' into feature/cierres 2025-03-03 15:32:25 -03:00
2a0335f834 Reservation Controller 2025-03-03 15:21:18 -03:00
9ccf53fa4e Reservation Service 2025-03-03 15:21:12 -03:00
ef54c36edc Cleanup 2025-03-03 14:56:18 -03:00
4aa88d5164 Rutas API Contratos 2025-03-03 11:26:45 -03:00
8ea13c3efd API Contratos 2025-03-03 10:47:48 -03:00
12e3d7ed3b Servicio Contratos 2025-03-01 13:26:55 -03:00
a7fc89ac29 Merge branch 'develop' into feature/cierres 2025-02-24 21:36:35 -03:00
a71df4e70d Controlador y ruta de operadores para API 2025-02-24 12:41:50 -03:00
f17b7a758a withJson con error 2025-02-24 12:41:34 -03:00
7fb28cd44c Servicio operadores 2025-02-24 12:41:13 -03:00
a44bd610ad Excepciones de servicios 2025-02-24 12:41:00 -03:00
28bba8a438 Actualizacion de Modelos 2025-02-24 12:40:40 -03:00
0ec6ebdafe Actualizacion de Repos 2025-02-24 12:39:42 -03:00
3ebe256a66 Actualizacion de migraciones 2025-02-24 12:39:25 -03:00
9d135e2c26 Base de Datos 2025-02-18 16:02:10 -03:00
58 changed files with 2364 additions and 20 deletions

View File

@ -26,7 +26,13 @@ abstract class Model implements Define\Model
public function jsonSerialize(): mixed
{
return [
'id' => $this->id
'id' => $this->id,
...$this->jsonComplement()
];
}
protected function jsonComplement(): array
{
return [];
}
}

View File

@ -204,9 +204,11 @@ abstract class Repository implements Define\Repository
{
try {
$result = $this->connection->execute($query, $data)->fetch(PDO::FETCH_ASSOC);
if ($result === false) {
throw new EmptyResult($query);
}
} catch (PDOException $exception) {
throw new EmptyResult($query, $exception);
}
return $this->load($result);
}

View File

@ -0,0 +1,56 @@
<?php
namespace Incoviba\Common\Ideal\Service;
use Psr\Log\LoggerInterface;
use Incoviba\Common\Define;
use Incoviba\Common\Ideal;
use Incoviba\Exception\ServiceAction;
abstract class API extends Ideal\Service
{
public function __construct(LoggerInterface $logger)
{
parent::__construct($logger);
}
/**
* @param string|array|null $order
* @return array
*/
abstract public function getAll(null|string|array $order = null): array;
/**
* @param int $id
* @return Define\Model
* @throws ServiceAction\Read
*/
abstract public function get(int $id): Define\Model;
/**
* @param array $data
* @return Define\Model
* @throws ServiceAction\Create
*/
abstract public function add(array $data): Define\Model;
/**
* @param Define\Model $model
* @param array $new_data
* @return Define\Model
* @throws ServiceAction\Update
*/
abstract public function edit(Define\Model $model, array $new_data): Define\Model;
/**
* @param int $id
* @return Define\Model
* @throws ServiceAction\Delete
*/
abstract public function delete(int $id): Define\Model;
/**
* @param Define\Model $model
* @return Define\Model
*/
abstract protected function process(Define\Model $model): Define\Model;
}

View File

@ -2,6 +2,7 @@
namespace Incoviba\Common\Implement\Repository\Mapper;
use DateTimeImmutable;
use DateMalformedStringException;
use Incoviba\Common\Implement\Repository\Mapper;
class DateTime extends Mapper
@ -9,7 +10,17 @@ class DateTime extends Mapper
public function __construct(string $column, ?string $property = null)
{
$this->setFunction(function($data) use ($column) {
return new DateTimeImmutable($data[$column] ?? '');
if (!isset($data[$column])) {
return null;
}
if (is_a($data[$column], DateTimeImmutable::class)) {
return $data[$column];
}
try {
return new DateTimeImmutable($data[$column] ?? '');
} catch (DateMalformedStringException) {
return new DateTimeImmutable();
}
});
if ($property !== null) {
$this->setProperty($property);

View File

@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
use Phinx\Migration\AbstractMigration;
final class CreateBroker 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('brokers', ['id' => false, 'primary_key' => ['rut']])
->addColumn('rut', 'integer', ['identity' => true, 'signed' => false, 'null' => false])
->addColumn('digit', 'string', ['length' => 1, 'null' => false])
->addColumn('name', 'string', ['length' => 255, 'null' => false])
->create();
}
}

View File

@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
use Phinx\Migration\AbstractMigration;
final class CreateBrokerContract 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->execute('SET unique_checks=0; SET foreign_key_checks=0;');
$this->execute("ALTER DATABASE CHARACTER SET 'utf8mb4';");
$this->execute("ALTER DATABASE COLLATE='utf8mb4_general_ci';");
$this->table('broker_contracts')
->addColumn('broker_rut', 'integer', ['signed' => false, 'null' => false])
->addColumn('project_id', 'integer', ['signed' => false, 'null' => false])
->addColumn('commission', 'decimal', ['precision' => 10, 'scale' => 2, 'null' => false])
->addForeignKey('broker_rut', 'brokers', 'rut', ['delete' => 'cascade', 'update' => 'cascade'])
->addForeignKey('project_id', 'proyecto', 'id', ['delete' => 'cascade', 'update' => 'cascade'])
->create();
$this->execute('SET unique_checks=1; SET foreign_key_checks=1;');
}
}

View File

@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
use Phinx\Migration\AbstractMigration;
final class CreateBrokerData 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->execute('SET unique_checks=0; SET foreign_key_checks=0;');
$this->execute("ALTER DATABASE CHARACTER SET 'utf8mb4';");
$this->execute("ALTER DATABASE COLLATE='utf8mb4_general_ci';");
$this->table('broker_data')
->addColumn('broker_rut', 'integer', ['signed' => false, 'null' => false])
->addColumn('representative_rut', 'integer', ['signed' => false, 'null' => true, 'default' => null])
->addColumn('legal_name', 'string', ['length' => 255, 'default' => null, 'null' => true])
->addForeignKey('broker_rut', 'brokers', ['rut'], ['delete' => 'CASCADE', 'update' => 'CASCADE'])
->addForeignKey('representative_rut', 'personas', ['rut'], ['delete' => 'CASCADE', 'update' => 'CASCADE'])
->create();
$this->execute('SET unique_checks=1; SET foreign_key_checks=1;');
}
}

View File

@ -0,0 +1,38 @@
<?php
declare(strict_types=1);
use Phinx\Migration\AbstractMigration;
final class CreatePromotion 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->execute('SET unique_checks=0; SET foreign_key_checks=0;');
$this->execute("ALTER DATABASE CHARACTER SET 'utf8mb4';");
$this->execute("ALTER DATABASE COLLATE='utf8mb4_general_ci';");
$this->table('promotions')
->addColumn('price_id', 'integer', ['signed' => false, 'null' => false])
->addColumn('amount', 'decimal', ['precision' => 10, 'scale' => 2, 'null' => false])
->addColumn('start_date', 'date', ['null' => false])
->addColumn('end_date', 'date', ['null' => false])
->addColumn('valid_until', 'date', ['null' => false])
->addColumn('state', 'integer', ['length' => 1, 'null' => false, 'default' => 0])
->addForeignKey('price_id', 'prices', 'id', ['delete' => 'cascade', 'update' => 'cascade'])
->create();
$this->execute('SET unique_checks=1; SET foreign_key_checks=1;');
}
}

View File

@ -0,0 +1,34 @@
<?php
declare(strict_types=1);
use Phinx\Migration\AbstractMigration;
final class CreateReservation 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->execute('SET unique_checks=0; SET foreign_key_checks=0;');
$this->execute("ALTER DATABASE CHARACTER SET 'utf8mb4';");
$this->execute("ALTER DATABASE COLLATE='utf8mb4_general_ci';");
$this->table('reservation')
->addColumn('buyer_rut', 'integer', ['signed' => false, 'null' => false])
->addColumn('date', 'date', ['null' => false])
->addForeignKey('buyer_rut', 'personas', 'rut', ['delete' => 'cascade', 'update' => 'cascade'])
->create();
$this->execute('SET unique_checks=1; SET foreign_key_checks=1;');
}
}

View File

@ -0,0 +1,35 @@
<?php
declare(strict_types=1);
use Phinx\Migration\AbstractMigration;
final class CreateBrokerContractState 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->execute('SET unique_checks=0; SET foreign_key_checks=0;');
$this->execute("ALTER DATABASE CHARACTER SET 'utf8mb4';");
$this->execute("ALTER DATABASE COLLATE='utf8mb4_general_ci';");
$this->table('broker_contract_states')
->addColumn('contract_id', 'integer', ['signed' => false, 'null' => false])
->addColumn('date', 'date', ['null' => false])
->addColumn('type', 'integer', ['length' => 1, 'null' => false, 'default' => 0])
->addForeignKey('contract_id', 'broker_contracts', 'id', ['delete' => 'cascade', 'update' => 'cascade'])
->create();
$this->execute('SET unique_checks=1; SET foreign_key_checks=1;');
}
}

View File

@ -0,0 +1,35 @@
<?php
declare(strict_types=1);
use Phinx\Migration\AbstractMigration;
final class CreateReservationDatas 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->execute('SET unique_checks=0; SET foreign_key_checks=0;');
$this->execute("ALTER DATABASE CHARACTER SET 'utf8mb4';");
$this->execute("ALTER DATABASE COLLATE='utf8mb4_general_ci';");
$this->table('reservation_data')
->addColumn('reservation_id', 'integer', ['signed' => false, 'null' => false])
->addColumn('type', 'integer', ['length' => 1, 'signed' => false, 'null' => false])
->addColumn('reference_id', 'integer', ['signed' => false, 'null' => false])
->addColumn('value', 'decimal', ['precision' => 10, 'scale' => 2, 'signed' => false, 'default' => 0.00, 'null' => true])
->create();
$this->execute('SET unique_checks=1; SET foreign_key_checks=1;');
}
}

View File

@ -0,0 +1,35 @@
<?php
declare(strict_types=1);
use Phinx\Migration\AbstractMigration;
final class CreateReservationStates 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->execute('SET unique_checks=0; SET foreign_key_checks=0;');
$this->execute("ALTER DATABASE CHARACTER SET 'utf8mb4';");
$this->execute("ALTER DATABASE COLLATE='utf8mb4_general_ci';");
$this->table('reservation_states')
->addColumn('reservation_id', 'integer', ['signed' => false, 'null' => false])
->addColumn('date', 'date', ['null' => false])
->addColumn('type', 'integer', ['length' => 3, 'null' => false, 'default' => 0])
->addForeignKey('reservation_id', 'reservation', 'id', ['delete' => 'cascade', 'update' => 'cascade'])
->create();
$this->execute('SET unique_checks=1; SET foreign_key_checks=1;');
}
}

View File

@ -3,6 +3,13 @@ use Incoviba\Controller\API\Proyectos;
$app->group('/proyectos', function($app) {
$app->get('/escriturando[/]', [Proyectos::class, 'escriturando']);
$files = new FilesystemIterator(implode(DIRECTORY_SEPARATOR, [__DIR__, 'proyectos']));
foreach ($files as $file) {
if ($file->isDir()) {
continue;
}
include_once $file->getRealPath();
}
$app->get('[/]', [Proyectos::class, 'list']);
});
$app->group('/proyecto/{proyecto_id}', function($app) {
@ -20,4 +27,5 @@ $app->group('/proyecto/{proyecto_id}', function($app) {
$app->group('/terreno', function($app) {
$app->post('/edit[/]', [Proyectos::class, 'terreno']);
});
$app->get('/brokers', [Proyectos::class, 'brokers']);
});

View File

@ -0,0 +1,27 @@
<?php
use Incoviba\Controller\API\Proyectos\Brokers;
use Incoviba\Controller\API\Proyectos\Brokers\Contracts;
$app->group('/brokers', function($app) {
$app->group('/contracts', function($app) {
$app->post('/add[/]', [Contracts::class, 'add']);
$app->get('[/]', Contracts::class);
});
$app->group('/contract/{contract_id}', function($app) {
$app->post('/edit[/]', [Contracts::class, 'edit']);
$app->post('/inactive[/]', [Contracts::class, 'inactive']);
$app->delete('[/]', [Contracts::class, 'delete']);
$app->get('[/]', [Contracts::class, 'get']);
});
$app->post('/add[/]', [Brokers::class, 'add']);
$app->post('/edit[/]', [Brokers::class, 'edit']);
$app->get('[/]', Brokers::class);
});
$app->group('/broker/{broker_rut}', function($app) {
$app->group('/contracts', function($app) {
$app->post('/add[/]', [Contracts::class, 'add']);
$app->get('[/]', [Contracts::class, 'getByBroker']);
});
$app->delete('[/]', [Brokers::class, 'delete']);
$app->get('[/]', [Brokers::class, 'get']);
});

View File

@ -0,0 +1,12 @@
<?php
use Incoviba\Controller\API\Ventas\Reservations;
$app->group('/reservations', function($app) {
$app->post('/add[/]', [Reservations::class, 'add']);
$app->get('[/]', Reservations::class);
});
$app->group('/reservation/{reservation_id}', function($app) {
$app->post('/edit[/]', [Reservations::class, 'edit']);
$app->delete('[/]', [Reservations::class, 'delete']);
$app->get('[/]', [Reservations::class, 'get']);
});

View File

@ -2,23 +2,27 @@
use Psr\Container\ContainerInterface;
return [
Monolog\Formatter\LineFormatter::class => function(ContainerInterface $container) {
return (new Monolog\Formatter\LineFormatter(null, null, false, false, true))
->setBasePath('/code/');
},
Psr\Log\LoggerInterface::class => function(ContainerInterface $container) {
return new Monolog\Logger('incoviba', [
new Monolog\Handler\FilterHandler(
(new Monolog\Handler\RotatingFileHandler('/logs/error.log', 10))
->setFormatter(new Monolog\Formatter\LineFormatter(null, null, false, false, true)),
->setFormatter($container->get(Monolog\Formatter\LineFormatter::class)),
Monolog\Level::Error,
Monolog\Level::Error
),
new Monolog\Handler\FilterHandler(
(new Monolog\Handler\RotatingFileHandler('/logs/critical.log', 10))
->setFormatter(new Monolog\Formatter\LineFormatter(null, null, false, false, true)),
->setFormatter($container->get(Monolog\Formatter\LineFormatter::class)),
Monolog\Level::Critical
),
new Monolog\Handler\FilterHandler(
($container->has('ENVIRONMENT') and $container->get('ENVIRONMENT') === 'development')
? (new Monolog\Handler\RotatingFileHandler('/logs/debug.log', 10))
->setFormatter(new Monolog\Formatter\LineFormatter(null, null, false, false, true))
->setFormatter($container->get(Monolog\Formatter\LineFormatter::class))
: new Monolog\Handler\RedisHandler($container->get(Predis\ClientInterface::class), 'logs:notices'),
Monolog\Level::Debug,
Monolog\Level::Info
@ -26,7 +30,7 @@ return [
new Monolog\Handler\FilterHandler(
($container->has('ENVIRONMENT') and $container->get('ENVIRONMENT') === 'development')
? (new Monolog\Handler\RotatingFileHandler('/logs/notices.log', 10))
->setFormatter(new Monolog\Formatter\LineFormatter(null, null, false, false, true))
->setFormatter($container->get(Monolog\Formatter\LineFormatter::class))
: (new Incoviba\Common\Implement\Log\MySQLHandler($container->get(Incoviba\Common\Define\Connection::class)))
->setFormatter(new Incoviba\Common\Implement\Log\PDOFormatter()),
Monolog\Level::Notice,

View File

@ -4,6 +4,7 @@ namespace Incoviba\Controller\API;
use Incoviba\Common\Implement\Exception\EmptyRedis;
use Incoviba\Common\Implement\Exception\EmptyResult;
use Incoviba\Controller\withRedis;
use Incoviba\Exception\ServiceAction\Read;
use Incoviba\Model;
use Incoviba\Repository;
use Incoviba\Service;
@ -170,4 +171,20 @@ class Proyectos
} catch (EmptyResult) {}
return $this->withJson($response, $output);
}
public function brokers(ServerRequestInterface $request, ResponseInterface $response,
Repository\Proyecto $proyectoRepository, Service\Proyecto\Broker\Contract $contractService,
int $proyecto_id): ResponseInterface
{
$output = [
'proyecto_id' => $proyecto_id,
'contracts' => []
];
try {
$proyecto = $proyectoRepository->fetchById($proyecto_id);
$output['contracts'] = $contractService->getByProject($proyecto->id);
} catch (EmptyResult | Read $exception) {
return $this->withError($response, $exception);
}
return $this->withJson($response, $output);
}
}

View File

@ -0,0 +1,105 @@
<?php
namespace Incoviba\Controller\API\Proyectos;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Incoviba\Controller\API\withJson;
use Incoviba\Exception\ServiceAction;
use Incoviba\Service;
class Brokers
{
use withJson;
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, Service\Proyecto\Broker $brokerService): ResponseInterface
{
$brokers = $brokerService->getAll();
return $this->withJson($response, compact('brokers'));
}
public function get(ServerRequestInterface $request, ResponseInterface $response, Service\Proyecto\Broker $brokerService, int $broker_rut): ResponseInterface
{
try {
$broker = $brokerService->get($broker_rut);
return $this->withJson($response, compact('broker'));
} catch (ServiceAction\Read $exception) {
return $this->withError($response, $exception);
}
}
public function add(ServerRequestInterface $request, ResponseInterface $response, Service\Proyecto\Broker $brokerService): ResponseInterface
{
$body = $request->getParsedBody();
$output = [
'input' => $body,
'brokers' => [],
'success' => false,
'partial' => false,
'errors' => []
];
foreach ($body['brokers'] as $jsonData) {
try {
$data = json_decode($jsonData, true);
if (is_array($jsonData)) {
$data = $jsonData;
}
$output['brokers'] []= [
'broker' => $brokerService->add($data),
'success' => true
];
$output['partial'] = true;
} catch (ServiceAction\Create $exception) {
$output['errors'] []= $this->parseError($exception);
}
}
if (count($output['brokers']) == count($body['brokers'])) {
$output['success'] = true;
}
return $this->withJson($response, $output);
}
public function edit(ServerRequestInterface $request, ResponseInterface $response, Service\Proyecto\Broker $brokerService): ResponseInterface
{
$body = $request->getParsedBody();
$output = [
'input' => $body,
'brokers' => [],
'success' => false,
'partial' => false,
'errors' => []
];
foreach ($body['brokers'] as $data) {
try {
$output['brokers'] []= [
'rut' => $data['rut'],
'broker' => $brokerService->edit(json_decode($data, true)),
'success' => true
];
$output['partial'] = true;
} catch (ServiceAction\Update $exception) {
$output['errors'] []= $this->parseError($exception);
}
}
if (count($output['brokers']) == count($body['brokers'])) {
$output['success'] = true;
}
return $this->withJson($response, $output);
}
public function delete(ServerRequestInterface $request, ResponseInterface $response, Service\Proyecto\Broker $brokerService, int $broker_rut): ResponseInterface
{
$output = [
'broker_rut' => $broker_rut,
'broker' => null,
'success' => false
];
try {
$output['broker'] = $brokerService->delete($broker_rut);
$output['success'] = true;
} catch (ServiceAction\Delete $exception) {
return $this->withError($response, $exception);
}
return $this->withJson($response, $output);
}
}

View File

@ -0,0 +1,143 @@
<?php
namespace Incoviba\Controller\API\Proyectos\Brokers;
use DateTimeImmutable;
use DateMalformedStringException;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Incoviba\Controller\API\withJson;
use Incoviba\Service;
use Incoviba\Exception\ServiceAction;
class Contracts
{
use withJson;
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, Service\Proyecto\Broker\Contract $contractService): ResponseInterface
{
$contracts = $contractService->getAll();
return $this->withJson($response, compact('contracts'));
}
public function getByBroker(ServerRequestInterface $request, ResponseInterface $response, Service\Proyecto\Broker\Contract $contractService,
Service\Proyecto\Broker $brokerService, int $broker_rut): ResponseInterface
{
$output = [
'broker_rut' => $broker_rut,
'contracts' => []
];
try {
$broker = $brokerService->get($broker_rut);
$output['contracts'] = $contractService->getByBroker($broker->rut);
} catch (ServiceAction\Read $exception) {
return $this->withError($response, $exception);
}
return $this->withJson($response, $output);
}
public function get(ServerRequestInterface $request, ResponseInterface $response, Service\Proyecto\Broker\Contract $contractService, int $contract_id): ResponseInterface
{
$output = [
'contract_id' => $contract_id,
'contract' => null
];
try {
$output['contract'] = $contractService->getById($contract_id);
} catch (ServiceAction\Read $exception) {
return $this->withError($response, $exception);
}
return $this->withJson($response, $output);
}
public function add(ServerRequestInterface $request, ResponseInterface $response, Service\Proyecto\Broker\Contract $contractService): ResponseInterface
{
$input = $request->getParsedBody();
$output = [
'input' => $input,
'contracts' => [],
'success' => false,
'partial' => false,
'errors' => [],
];
foreach ($input['contracts'] as $jsonData) {
try {
$contractData = json_decode($jsonData, true);
if (is_array($jsonData)) {
$contractData = $jsonData;
}
$contract = $contractService->add($contractData);
$output['contracts'] []= [
'contract' => $contract,
'success' => true
];
$output['partial'] = true;
} catch (ServiceAction\Create $exception) {
$output['errors'] []= $this->parseError($exception);
}
}
if (count($output['contracts']) == count($input['contracts'])) {
$output['success'] = true;
}
return $this->withJson($response, $output);
}
public function edit(ServerRequestInterface $request, ResponseInterface $response, Service\Proyecto\Broker\Contract $contractService, int $contract_id): ResponseInterface
{
$input = $request->getParsedBody();
$output = [
'contract_id' => $contract_id,
'input' => $input,
'contract' => null,
'success' => false
];
try {
$contract = $contractService->getById($contract_id);
$output['contract'] = $contractService->edit($contract, $input);
$output['success'] = true;
} catch (ServiceAction\Read | ServiceAction\Update $exception) {
return $this->withError($response, $exception);
}
return $this->withJson($response, $output);
}
public function inactive(ServerRequestInterface $request, ResponseInterface $response, Service\Proyecto\Broker\Contract $contractService, int $contract_id): ResponseInterface
{
$input = $request->getParsedBody();
$output = [
'contract_id' => $contract_id,
'input' => $input,
'contract' => null,
'success' => false
];
try {
$contract = $contractService->getById($contract_id);
$date = new DateTimeImmutable();
if (!empty($input['date'])) {
try {
$date = new DateTimeImmutable($input['date']);
} catch (DateMalformedStringException) {}
}
$output['contract'] = $contractService->inactive($contract, $date);
$output['success'] = true;
} catch (ServiceAction\Read | ServiceAction\Update $exception) {
return $this->withError($response, $exception);
}
return $this->withJson($response, $output);
}
public function delete(ServerRequestInterface $request, ResponseInterface $response, Service\Proyecto\Broker\Contract $contractService, int $contract_id): ResponseInterface
{
$output = [
'contract_id' => $contract_id,
'contract' => null,
'success' => false
];
try {
$output['contract'] = $contractService->delete($contract_id);
$output['success'] = true;
} catch (ServiceAction\Delete $exception) {
return $this->withError($response, $exception);
}
return $this->withJson($response, $output);
}
}

View File

@ -0,0 +1,103 @@
<?php
namespace Incoviba\Controller\API\Ventas;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Incoviba\Controller\API\withJson;
use Incoviba\Exception\ServiceAction;
use Incoviba\Service;
class Reservations
{
use withJson;
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, Service\Venta\Reservation $reservationService): ResponseInterface
{
$reservations = [];
try {
$reservations = $reservationService->getAll();
} catch (ServiceAction\Read $exception) {
return $this->withError($response, $exception);
}
return $this->withJson($response, compact('reservations'));
}
public function get(ServerRequestInterface $request, ResponseInterface $response, Service\Venta\Reservation $reservationService, int $reservation_id): ResponseInterface
{
$output = [
'reservation_id' => $reservation_id,
'reservation' => null,
];
try {
$output['reservation'] = $reservationService->get($reservation_id);
} catch (ServiceAction\Read $exception) {
return $this->withError($response, $exception);
}
return $this->withJson($response, $output);
}
public function add(ServerRequestInterface $request, ResponseInterface $response, Service\Venta\Reservation $reservationService): ResponseInterface
{
$input = $request->getParsedBody();
$output = [
'input' => $input,
'reservations' => [],
'success' => false,
'partial' => false,
'errors' => [],
];
try {
$output['reservations'] []= [
'reservation' => $reservationService->add($input),
'success' => true
];
$output['partial'] = true;
} catch (ServiceAction\Create $exception) {
$output['errors'] []= $this->parseError($exception);
}
if (count($input['reservations']) === count($output['reservations'])) {
$output['success'] = true;
}
return $this->withJson($response, $output);
}
public function edit(ServerRequestInterface $request, ResponseInterface $response, Service\Venta\Reservation $reservationService, int $reservation_id): ResponseInterface
{
$input = $request->getParsedBody();
$output = [
'input' => $input,
'reservation_id' => $reservation_id,
'reservations' => null,
'success' => false,
];
try {
$reservation = $reservationService->get($reservation_id);
$output['reservations'] = $reservationService->edit($reservation, $input);
$output['success'] = true;
} catch (ServiceAction\Read | ServiceAction\Update $exception) {
return $this->withError($response, $exception);
}
return $this->withJson($response, $output);
}
public function delete(ServerRequestInterface $request, ResponseInterface $response, Service\Venta\Reservation $reservationService, int $reservation_id): ResponseInterface
{
$output = [
'reservation_id' => $reservation_id,
'success' => false,
];
try {
$reservationService->delete($reservation_id);
$output['success'] = true;
} catch (ServiceAction\Delete $exception) {
return $this->withError($response, $exception);
}
return $this->withJson($response, $output);
}
}

View File

@ -1,6 +1,7 @@
<?php
namespace Incoviba\Controller\API;
use Throwable;
use Psr\Http\Message\ResponseInterface;
trait withJson
@ -10,4 +11,73 @@ trait withJson
$response->getBody()->write(json_encode($data));
return $response->withStatus($statusCode)->withHeader('Content-Type', 'application/json');
}
public function parseError(Throwable $exception): array
{
return [
'code' => $exception->getCode(),
'message' => $exception->getMessage(),
'file' => $this->parseFilename($exception->getFile()),
'line' => $exception->getLine(),
'trace' => $this->parseStack($exception->getTraceAsString()),
'previous' => ($exception->getPrevious() instanceof Throwable) ? $this->parseError($exception->getPrevious()) : ''
];
}
public function withError(ResponseInterface $response, Throwable $exception): ResponseInterface
{
$output = $this->parseError($exception);
$response->getBody()->write(json_encode(['error' => $output]));
return $response->withHeader('Content-Type', 'application/json');
}
public function withErrors(ResponseInterface $response, array $errors): ResponseInterface
{
foreach ($errors as $error) {
$response = $this->withError($response, $error);
}
return $response;
}
protected function parseFilename(string $filename): string
{
return str_replace('/code/', '', $filename);
}
protected function parseStack(string|array $stack): array
{
if (is_string($stack)) {
$stack = explode(PHP_EOL, $stack);
}
$output = [];
foreach ($stack as $line) {
$index = substr($line, 1, strpos($line, ' ') - 1);
$content = substr($line, strpos($line, ' ') + 1);
if (str_contains($line, '{main}')) {
$output [] = [
'stack' => $index,
'message' => $content
];
continue;
}
if (str_starts_with($content, '[internal function]')) {
$content = substr($content, strlen('[internal function]: '));
$output [] = [
'stack' => $index,
'type' => 'internal function',
'message' => $content
];
continue;
}
$fileData = substr($content, 0, strpos($content, ' '));
$file = substr($fileData, 0, strrpos($fileData, '('));
$fileLine = (int) substr($fileData, strrpos($fileData, '(') + 1, -2);
$error = substr($content, strlen($fileData) + 1);
$output []= [
'stack' => $index,
'file' => $this->parseFilename($file),
'line' => $fileLine,
'error' => $error
];
}
return $output;
}
}

View File

@ -0,0 +1,15 @@
<?php
namespace Incoviba\Exception\ServiceAction;
use Throwable;
use Incoviba\Exception\ServiceActionFail;
class Create extends ServiceActionFail
{
public function __construct(string $service, Throwable $previous = null)
{
$action = 'create';
$code = 1;
parent::__construct($service, $action, $code, $previous);
}
}

View File

@ -0,0 +1,15 @@
<?php
namespace Incoviba\Exception\ServiceAction;
use Throwable;
use Incoviba\Exception\ServiceActionFail;
class Delete extends ServiceActionFail
{
public function __construct(string $service, Throwable $previous = null)
{
$action = 'delete';
$code = 4;
parent::__construct($service, $action, $code, $previous);
}
}

View File

@ -0,0 +1,15 @@
<?php
namespace Incoviba\Exception\ServiceAction;
use Throwable;
use Incoviba\Exception\ServiceActionFail;
class Read extends ServiceActionFail
{
public function __construct(string $service, Throwable $previous = null)
{
$action = 'read';
$code = 2;
parent::__construct($service, $action, $code, $previous);
}
}

View File

@ -0,0 +1,15 @@
<?php
namespace Incoviba\Exception\ServiceAction;
use Throwable;
use Incoviba\Exception\ServiceActionFail;
class Update extends ServiceActionFail
{
public function __construct(string $service, Throwable $previous = null)
{
$action = 'edit';
$code = 3;
parent::__construct($service, $action, $code, $previous);
}
}

View File

@ -0,0 +1,15 @@
<?php
namespace Incoviba\Exception;
use Exception;
use Throwable;
class ServiceActionFail extends Exception
{
public function __construct(string $service,string $action = "__invoke", int $code = 0, Throwable $previous = null)
{
$message = "Action {$action} failed for Service {$service}.";
$code = 700 + $code;
parent::__construct($message, $code, $previous);
}
}

View File

@ -0,0 +1,30 @@
<?php
namespace Incoviba\Model\Proyecto;
use Incoviba\Common;
class Broker extends Common\Ideal\Model
{
public int $rut;
public string $digit;
public string $name;
protected ?Broker\Data $data = null;
public function data(): ?Broker\Data
{
if (!isset($this->data)) {
$this->data = $this->runFactory('data');
}
return $this->data;
}
public function jsonSerialize(): mixed
{
return [
'rut' => $this->rut,
'digit' => $this->digit,
'name' => $this->name,
'data' => $this->data()
];
}
}

View File

@ -0,0 +1,45 @@
<?php
namespace Incoviba\Model\Proyecto\Broker;
use Incoviba\Common;
use Incoviba\Model;
class Contract extends Common\Ideal\Model
{
public Model\Proyecto $project;
public Model\Proyecto\Broker $broker;
public float $commission;
protected array $states = [];
public function states(): array
{
if (!isset($this->states) or count($this->states) === 0) {
$this->states = $this->runFactory('states');
}
return $this->states;
}
protected ?Contract\State $current;
public function currentState(): ?Contract\State
{
if (!isset($this->current)) {
try {
$this->current = last($this->states());
} catch (\TypeError $error) {
$this->current = null;
}
}
return $this->current;
}
protected function jsonComplement(): array
{
return [
'project_id' => $this->project->id,
'broker_rut' => $this->broker->rut,
'commission' => $this->commission,
'states' => $this->states(),
'current' => $this->currentState(),
];
}
}

View File

@ -0,0 +1,25 @@
<?php
namespace Incoviba\Model\Proyecto\Broker\Contract;
use DateTimeInterface;
use Incoviba\Common;
use Incoviba\Model;
class State extends Common\Ideal\Model
{
public Model\Proyecto\Broker\Contract $contract;
public DateTimeInterface $date;
public State\Type $type;
protected function jsonComplement(): array
{
return [
'contract_id' => $this->contract->id,
'date' => $this->date->format('Y-m-d'),
'type' => [
'id' => $this->type->value,
'description' => $this->type->name
]
];
}
}

View File

@ -0,0 +1,17 @@
<?php
namespace Incoviba\Model\Proyecto\Broker\Contract\State;
enum Type: int
{
case ACTIVE = 1;
case INACTIVE = 0;
public static function name(int $type): string
{
return match ($type) {
self::ACTIVE => 'active',
self::INACTIVE => 'inactive',
default => throw new \InvalidArgumentException('Unexpected match value')
};
}
}

View File

@ -0,0 +1,21 @@
<?php
namespace Incoviba\Model\Proyecto\Broker;
use Incoviba\Common;
use Incoviba\Model;
class Data extends Common\Ideal\Model
{
public Model\Proyecto\Broker $broker;
public ?Model\Persona $representative = null;
public ?string $legalName = null;
protected function jsonComplement(): array
{
return [
'broker_rut' => $this->broker->rut,
'representative_rut' => $this->representative?->rut,
'legal_name' => $this->legalName
];
}
}

View File

@ -0,0 +1,30 @@
<?php
namespace Incoviba\Model\Venta;
use DateTimeInterface;
use Incoviba\Common;
class Promotion extends Common\Ideal\Model
{
public Precio $price;
public float $amount;
public DateTimeInterface $startDate;
public DateTimeInterface $endDate;
public DateTimeInterface $validUntil;
public int $state;
protected function jsonComplement(): array
{
return [
'price_id' => $this->price->id,
'amount' => $this->amount,
'start_date' => $this->startDate->format('Y-m-d'),
'end_date' => $this->endDate->format('Y-m-d'),
'valid_until' => $this->validUntil->format('Y-m-d'),
'state' => [
'id' => $this->state,
'description' => Promotion\State::name($this->state)
]
];
}
}

View File

@ -0,0 +1,17 @@
<?php
namespace Incoviba\Model\Venta\Promotion;
enum State: int
{
case ACTIVE = 1;
case INACTIVE = 0;
public static function name(int $state): string
{
return match ($state) {
self::ACTIVE => 'active',
self::INACTIVE => 'inactive',
default => throw new \InvalidArgumentException('Unexpected match value')
};
}
}

View File

@ -0,0 +1,83 @@
<?php
namespace Incoviba\Model\Venta;
use DateTimeInterface;
use Incoviba\Common;
use Incoviba\Model;
class Reservation extends Common\Ideal\Model
{
public Model\Persona $buyer;
public DateTimeInterface $date;
public array $units = [];
public array $promotions = [];
public ?Model\Proyecto\Broker $broker = null;
protected array $states = [];
public function states(): array
{
if (!isset($this->states)) {
$this->states = $this->runFactory('states');
}
return $this->states;
}
protected Model\Venta\Reservation\State $currentState;
public function currentState(): Model\Venta\Reservation\State
{
if (!isset($this->currentState)) {
$this->currentState = last($this->states());
}
return $this->currentState;
}
public function addUnit(Model\Venta\Unidad $unit, float $value): self
{
if (($i = $this->findUnit($unit->id)) !== null) {
$this->units[$i]['value'] = $value;
return $this;
}
$this->units[] = [
'unit' => $unit,
'value' => $value,
];
return $this;
}
public function removeUnit(int $unit_id): self
{
if (($i = $this->findUnit($unit_id)) === null) {
return $this;
}
unset($this->units[$i]);
$this->units = array_values($this->units);
return $this;
}
public function findUnit(int $unit_id): ?int
{
foreach ($this->units as $idx => $unit) {
if ($unit['unit']->id == $unit_id) {
return $idx;
}
}
return null;
}
public function hasUnit(int $unit_id): bool
{
return $this->findUnit($unit_id) !== null;
}
protected function jsonComplement(): array
{
return [
'buyer_rut' => $this->buyer->rut,
'date' => $this->date->format('Y-m-d'),
'units' => $this->units,
'promotions' => $this->promotions,
'broker_rut' => $this->broker?->rut,
];
}
}

View File

@ -0,0 +1,25 @@
<?php
namespace Incoviba\Model\Venta\Reservation;
use DateTimeInterface;
use Incoviba\Common;
use Incoviba\Model;
class State extends Common\Ideal\Model
{
public Model\Venta\Reservation $reservation;
public DateTimeInterface $date;
public int $type;
protected function jsonComplement(): array
{
return [
'reservation_id' => $this->reservation->id,
'date' => $this->date->format('Y-m-d'),
'type' => [
'id' => $this->type,
'description' => State\Type::name($this->type)
]
];
}
}

View File

@ -0,0 +1,19 @@
<?php
namespace Incoviba\Model\Venta\Reservation\State;
enum Type: int
{
case ACTIVE = 1;
case INACTIVE = 0;
case REJECTED = -1;
public static function name(int $type): string
{
return match ($type) {
self::ACTIVE => 'active',
self::INACTIVE => 'inactive',
self::REJECTED => 'rejected',
default => throw new \InvalidArgumentException('Unexpected match value')
};
}
}

View File

@ -0,0 +1,63 @@
<?php
namespace Incoviba\Repository\Proyecto;
use Incoviba\Common;
use Incoviba\Common\Define;
use Incoviba\Repository;
use Incoviba\Model;
class Broker extends Common\Ideal\Repository
{
public function getTable(): string
{
return 'brokers';
}
protected function getIndex(Define\Model $model): mixed
{
return $model->rut;
}
protected function getKey(): string
{
return 'rut';
}
public function create(?array $data = null): Model\Proyecto\Broker
{
$map = new Common\Implement\Repository\MapperParser(['rut', 'digit', 'name']);
return $this->parseData(new Model\Proyecto\Broker(), $data, $map);
}
public function save(Common\Define\Model $model): Model\Proyecto\Broker
{
$this->saveNew(
['rut', 'digit', 'name'],
[$model->rut, $model->digit, $model->name]
);
return $model;
}
/**
* @param Define\Model $model
* @param array $new_data
* @return Model\Proyecto\Broker
* @throws Common\Implement\Exception\EmptyResult
*/
public function edit(Common\Define\Model $model, array $new_data): Model\Proyecto\Broker
{
return $this->update($model, ['rut', 'digit', 'name'], $new_data);
}
/**
* @param string $name
* @return Model\Proyecto\Broker|null
* @throws Common\Implement\Exception\EmptyResult
*/
public function fetchByName(string $name): ?Model\Proyecto\Broker
{
$query = $this->connection->getQueryBuilder()
->select()
->from($this->getTable())
->where('name = :name');
return $this->fetchOne($query, ['name' => $name]);
}
}

View File

@ -0,0 +1,135 @@
<?php
namespace Incoviba\Repository\Proyecto\Broker;
use Incoviba\Common;
use Incoviba\Repository;
use Incoviba\Model;
class Contract extends Common\Ideal\Repository
{
public function __construct(Common\Define\Connection $connection, protected Repository\Proyecto\Broker $brokerRepository,
protected Repository\Proyecto $proyectoRepository)
{
parent::__construct($connection);
}
public function getTable(): string
{
return 'broker_contracts';
}
public function create(?array $data = null): Model\Proyecto\Broker\Contract
{
$map = (new Common\Implement\Repository\MapperParser(['commission']))
->register('broker_rut', (new Common\Implement\Repository\Mapper())
->setProperty('broker')
->setFunction(function($data) {
return $this->brokerRepository->fetchById($data['broker_rut']);
})
)
->register('project_id', (new Common\Implement\Repository\Mapper())
->setProperty('project')
->setFunction(function($data) {
return $this->proyectoRepository->fetchById($data['project_id']);
})
);
return $this->parseData(new Model\Proyecto\Broker\Contract(), $data, $map);
}
public function save(Common\Define\Model $model): Model\Proyecto\Broker\Contract
{
$model->id = $this->saveNew(
['broker_rut', 'project_id', 'commission'],
[$model->broker->rut, $model->project->id, $model->commission]);
return $model;
}
/**
* @param Common\Define\Model $model
* @param array $new_data
* @return Model\Proyecto\Broker\Contract
* @throws Common\Implement\Exception\EmptyResult
*/
public function edit(Common\Define\Model $model, array $new_data): Model\Proyecto\Broker\Contract
{
return $this->update($model, ['broker_rut', 'project_id', 'commission'], $new_data);
}
/**
* @param int $brokerRut
* @return array
* @throws Common\Implement\Exception\EmptyResult
*/
public function fetchByBroker(int $brokerRut): array
{
$query = $this->connection->getQueryBuilder()
->select()
->from($this->getTable())
->where('broker_rut = :broker_rut');
return $this->fetchMany($query, ['broker_rut' => $brokerRut]);
}
/**
* @param int $projectId
* @return array
* @throws Common\Implement\Exception\EmptyResult
*/
public function fetchByProject(int $projectId): array
{
$query = $this->connection->getQueryBuilder()
->select()
->from($this->getTable())
->where('project_id = :project_id');
return $this->fetchMany($query, ['project_id' => $projectId]);
}
/**
* @param int $brokerRut
* @return array
* @throws Common\Implement\Exception\EmptyResult
*/
public function fetchActiveByBroker(int $brokerRut): array
{
$query = $this->connection->getQueryBuilder()
->select('a.*')
->from("{$this->getTable()} a")
->joined($this->statusJoin())
->where('a.broker_rut = :broker_rut AND bcs.state = :state');
return $this->fetchMany($query, ['broker_rut' => $brokerRut, 'state' => Model\Proyecto\Broker\Contract\Type::ACTIVE]);
}
/**
* @param int $projectId
* @return array
* @throws Common\Implement\Exception\EmptyResult
*/
public function fetchActiveByProject(int $projectId): array
{
$query = $this->connection->getQueryBuilder()
->select('a.*')
->from("{$this->getTable()} a")
->joined($this->statusJoin())
->where('a.proyecto_id = :proyecto_id AND bcs.state = :state');
return $this->fetchMany($query, ['proyecto_id' => $projectId, 'state' => Model\Proyecto\Broker\Contract\State\Type::ACTIVE->value]);
}
/**
* @param int $projectId
* @param int $brokerRut
* @return Model\Proyecto\Broker\Contract
* @throws Common\Implement\Exception\EmptyResult
*/
public function fetchActiveByProjectAndBroker(int $projectId, int $brokerRut): Model\Proyecto\Broker\Contract
{
$query = $this->connection->getQueryBuilder()
->select('a.*')
->from("{$this->getTable()} a")
->joined($this->statusJoin())
->where('a.project_id = :project_id AND a.broker_rut = :broker_rut AND bcs.type = :state');
return $this->fetchOne($query, ['project_id' => $projectId, 'broker_rut' => $brokerRut, 'state' => Model\Proyecto\Broker\Contract\State\Type::ACTIVE->value]);
}
protected function statusJoin(): string
{
return 'INNER JOIN (SELECT bcs1.* FROM broker_contract_states bcs1 INNER JOIN (SELECT MAX(id) AS id, contract_id FROM broker_contract_states GROUP BY contract_id) bcs0 ON bcs0.id = bcs1.id) bcs ON bcs.contract_id = a.id';
}
}

View File

@ -0,0 +1,72 @@
<?php
namespace Incoviba\Repository\Proyecto\Broker\Contract;
use Incoviba\Common;
use Incoviba\Repository;
use Incoviba\Model;
class State extends Common\Ideal\Repository
{
public function __construct(Common\Define\Connection $connection, protected Repository\Proyecto\Broker\Contract $contractRepository)
{
parent::__construct($connection);
}
public function getTable(): string
{
return 'broker_contract_states';
}
public function create(?array $data = null): Model\Proyecto\Broker\Contract\State
{
$map = (new Common\Implement\Repository\MapperParser())
->register('contract_id', (new Common\Implement\Repository\Mapper())
->setProperty('contract')
->setFunction(function($data) {
return $this->contractRepository->fetchById($data['contract_id']);
}))
->register('type', (new Common\Implement\Repository\Mapper())
->setFunction(function($data) {
return Model\Proyecto\Broker\Contract\State\Type::from($data['type']);
}))
->register('date', new Common\Implement\Repository\Mapper\DateTime('date'));
return $this->parseData(new Model\Proyecto\Broker\Contract\State(), $data, $map);
}
public function save(Common\Define\Model $model): Model\Proyecto\Broker\Contract\State
{
$model->id = $this->saveNew(['contract_id', 'date', 'type'], [$model->contract->id, $model->date->format('Y-m-d'), $model->type->value]);
return $model;
}
public function edit(Common\Define\Model $model, array $new_data): Model\Proyecto\Broker\Contract\State
{
return $this->update($model, ['contract_id', 'date', 'type'], $new_data);
}
/**
* @param int $contract_id
* @return array
* @throws Common\Implement\Exception\EmptyResult
*/
public function fetchByContract(int $contract_id): array
{
$query = $this->connection->getQueryBuilder()
->select()
->from($this->getTable())
->where('contract_id = :contract_id');
return $this->fetchMany($query, ['contract_id' => $contract_id]);
}
/**
* @param int $contract_id
* @return Model\Proyecto\Broker\Contract\State
* @throws Common\Implement\Exception\EmptyResult
*/
public function fetchActiveByContract(int $contract_id): Model\Proyecto\Broker\Contract\State
{
$query = $this->connection->getQueryBuilder()
->select()
->from($this->getTable())
->where('contract_id = :contract_id AND type = :type');
return $this->fetchOne($query, ['contract_id' => $contract_id, 'type' => Model\Proyecto\Broker\Contract\State\Type::ACTIVE]);
}
}

View File

@ -0,0 +1,78 @@
<?php
namespace Incoviba\Repository\Proyecto\Broker;
use Incoviba\Common;
use Incoviba\Repository;
use Incoviba\Model;
class Data extends Common\Ideal\Repository
{
public function __construct(Common\Define\Connection $connection,
protected Repository\Proyecto\Broker $brokerRepository,
protected Repository\Persona $personaRepository)
{
parent::__construct($connection);
}
public function getTable(): string
{
return 'broker_data';
}
public function create(?array $data = null): Model\Proyecto\Broker\Data
{
$map = (new Common\Implement\Repository\MapperParser())
->register('broker_rut', (new Common\Implement\Repository\Mapper())
->setProperty('broker')
->setFunction(function($data) {
return $this->brokerRepository->fetchById($data['broker_rut']);
}))
->register('representative_rut', (new Common\Implement\Repository\Mapper())
->setProperty('representative')
->setDefault(null)
->setFunction(function($data) {
if ($data['representative_rut'] == null) return null;
try {
return $this->personaRepository->fetchById($data['representative_rut']);
} catch (Common\Implement\Exception\EmptyResult) {
return null;
}
}))
->register('legal_name', (new Common\Implement\Repository\Mapper())
->setProperty('legalName')
->setDefault(null));
return $this->parseData(new Model\Proyecto\Broker\Data(), $data, $map);
}
public function save(Common\Define\Model $model): Model\Proyecto\Broker\Data
{
$model->id = $this->saveNew(
['broker_rut', 'representative_rut', 'legal_name'],
[$model->broker->rut, $model->representative?->rut, $model->legalName]);
return $model;
}
/**
* @param Common\Define\Model $model
* @param array $new_data
* @return Model\Proyecto\Broker\Data
* @throws Common\Implement\Exception\EmptyResult
*/
public function edit(Common\Define\Model $model, array $new_data): Model\Proyecto\Broker\Data
{
return $this->update($model, ['representative_rut', 'legal_name'], $new_data);
}
/**
* @param int $broker_rut
* @return Model\Proyecto\Broker\Data
* @throws Common\Implement\Exception\EmptyResult
*/
public function fetchByBroker(int $broker_rut): Model\Proyecto\Broker\Data
{
$query = $this->connection->getQueryBuilder()
->select()
->from($this->getTable())
->where('broker_rut = :broker_rut');
return $this->fetchOne($query, ['broker_rut' => $broker_rut]);
}
}

View File

@ -58,6 +58,12 @@ class Credito extends Ideal\Repository
->where('pago = ?');
return $this->fetchOne($query, [$pago_id]);
}
/**
* @param int $venta_id
* @return Model\Venta\Credito
* @throws Implement\Exception\EmptyResult
*/
public function fetchByVenta(int $venta_id): Model\Venta\Credito
{
$query = $this->connection->getQueryBuilder()

View File

@ -114,6 +114,12 @@ WHERE venta_id = ?";
->where('valor = ? OR ROUND(valor/uf, 3) = ?');
return $this->fetchMany($query, [$value, $value]);
}
/**
* @param int $venta_id
* @return Model\Venta\Pago
* @throws Implement\Exception\EmptyResult
*/
public function fetchDevolucionByVenta(int $venta_id): Model\Venta\Pago
{
$query = $this->connection->getQueryBuilder()

View File

@ -83,6 +83,12 @@ class Pie extends Ideal\Repository
->where('reajuste = ?');
return $this->fetchOne($query, [$reajuste_id]);
}
/**
* @param int $venta_id
* @return Model\Venta\Pie
* @throws Implement\Exception\EmptyResult
*/
public function fetchByVenta(int $venta_id): Model\Venta\Pie
{
$query = $this->connection->getQueryBuilder()

View File

@ -0,0 +1,62 @@
<?php
namespace Incoviba\Repository\Venta;
use Incoviba\Common;
use Incoviba\Model;
class Promotion extends Common\Ideal\Repository
{
public function __construct(Common\Define\Connection $connection, protected Precio $precioRepository)
{
parent::__construct($connection);
}
public function getTable(): string
{
return 'promotions';
}
public function create(?array $data = null): Model\Venta\Promotion
{
$map = (new Implement\Repository\MapperParser(['amount', 'type']))
->register('price_id', (new Implement\Repository\Mapper())
->setProperty('price')
->setFunction(function($data) {
return $this->precioRepository->create($data);
}))
->register('start_date', new Implement\Repository\Mapper\DateTime('start_date', 'startDate'))
->register('end_date', new Implement\Repository\Mapper\DateTime('end_date', 'endDate'))
->register('valid_until', new Implement\Repository\Mapper\DateTime('valid_until', 'validUntil'));
return $this->parseData(new Model\Venta\Promotion(), $data, $map);
}
public function save(Common\Define\Model $model): Model\Venta\Promotion
{
$model->id = $this->saveNew(
['amount', 'type', 'start_date', 'end_date', 'valid_until', 'price_id'],
[$model->amount, $model->type, $model->startDate->format('Y-m-d'), $model->endDate->format('Y-m-d'), $model->validUntil->format('Y-m-d'), $model->price->id]
);
return $model;
}
public function edit(Common\Define\Model $model, array $new_data): Model\Venta\Promotion
{
return $this->update($model, ['amount', 'type', 'start_date', 'end_date', 'valid_until', 'price_id'], $new_data);
}
public function fetchByPrice(int $price_id): array
{
$query = $this->connection->getQueryBuilder()
->select()
->from($this->getTable())
->where('price_id = :price_id');
return $this->fetchMany($query, ['price_id' => $price_id]);
}
public function fetchActiveByPrice(int $price_id): array
{
$query = $this->connection->getQueryBuilder()
->select()
->from($this->getTable())
->where('price_id = :price_id AND state = :state');
return $this->fetchMany($query, ['price_id' => $price_id, 'state' => Model\Venta\Promotion\State::ACTIVE]);
}
}

View File

@ -0,0 +1,230 @@
<?php
namespace Incoviba\Repository\Venta;
use DateTimeInterface;
use DateInterval;
use PDO;
use Incoviba\Common;
use Incoviba\Model;
use Incoviba\Repository;
class Reservation extends Common\Ideal\Repository
{
public function __construct(Common\Define\Connection $connection, protected Repository\Persona $personaRepository,
protected Repository\Proyecto\Broker $brokerRepository,
protected Unidad $unitRepository, protected Promotion $promotionRepository)
{
parent::__construct($connection);
}
public function getTable(): string
{
return 'reservations';
}
public function create(?array $data = null): Model\Venta\Reservation
{
$map = (new Common\Implement\Repository\MapperParser())
->register('buyer_rut', (new Common\Implement\Repository\Mapper())
->setProperty('buyer')
->setFunction(function($data) use ($data) {
return $this->personaRepository->fetchById($data['buyer_rut']);
}))
->register('date', new Common\Implement\Repository\Mapper\DateTime('date'))
->register('broker_rut', (new Common\Implement\Repository\Mapper())
->setProperty('broker')
->setDefault(null)
->setFunction(function($data) use ($data) {
try {
return $this->brokerRepository->fetchById($data['broker_rut']);
} catch (Common\Implement\Exception\EmptyResult) {
return null;
}
}));
return $this->parseData(new Model\Venta\Reservation(), $data, $map);
}
public function save(Common\Define\Model $model): Model\Venta\Reservation
{
$model->id = $this->saveNew([
'buyer_rut',
'date',
'broker_rut'
], [
$model->buyer->rut,
$model->date->format('Y-m-d'),
$model->broker?->rut
]);
$this->saveUnits($model);
$this->savePromotions($model);
return $model;
}
/**
* @param Common\Define\Model $model
* @param array $new_data
* @return Model\Venta\Reservation
* @throws Common\Implement\Exception\EmptyResult
*/
public function edit(Common\Define\Model $model, array $new_data): Model\Venta\Reservation
{
return $this->update($model, ['buyer_rut', 'date', 'broker_rut'], $new_data);
}
public function load(array $data_row): Model\Venta\Reservation
{
$model = parent::load($data_row);
$this->fetchUnits($model);
$this->fetchPromotions($model);
return $model;
}
/**
* @param int $buyer_rut
* @param DateTimeInterface $date
* @return Model\Venta\Reservation
* @throws Common\Implement\Exception\EmptyResult
*/
public function fetchByBuyerAndDate(int $buyer_rut, DateTimeInterface $date): Model\Venta\Reservation
{
$query = $this->connection->getQueryBuilder()
->select()
->from('reservations')
->where('buyer_rut = :buyer_rut AND date >= :date');
return $this->fetchOne($query, ['buyer_rut' => $buyer_rut, 'date' => $date->sub(new DateInterval('P10D'))->format('Y-m-d')]);
}
protected function saveUnits(Model\Venta\Reservation $reservation): void
{
if (empty($reservation->units)) {
return;
}
$queryCheck = $this->connection->getQueryBuilder()
->select('COUNT(id) AS cnt')
->from('reservation_data')
->where('reservation_id = :id AND type = "Unit" AND reference_id = :unit_id');
$statementCheck = $this->connection->prepare($queryCheck);
$queryInsert = $this->connection->getQueryBuilder()
->insert()
->into('reservation_data')
->columns(['reservation_id', 'type', 'reference_id', 'value'])
->values([':reservation_id', ':type', ':reference_id', ':value']);
$statementInsert = $this->connection->prepare($queryInsert);
foreach ($reservation->units as $unit) {
$statementCheck->execute(['id' => $reservation->id, 'unit_id' => $unit['unit']->id]);
$result = $statementCheck->fetch(PDO::FETCH_ASSOC);
if ($result['cnt'] > 0) {
continue;
}
$statementInsert->execute(['reservation_id' => $reservation->id, 'type' => 'Unit', 'reference_id' => $unit['unit']->id, 'value' => $unit['value']]);
}
}
protected function savePromotions(Model\Venta\Reservation $reservation): void
{
if (empty($reservation->promotions)) {
return;
}
$queryCheck = $this->connection->getQueryBuilder()
->select('COUNT(id) AS cnt')
->from('reservation_data')
->where('reservation_id = :id AND type = "Promotion" AND reference_id = :promotion_id');
$statementCheck = $this->connection->prepare($queryCheck);
$queryInsert = $this->connection->getQueryBuilder()
->insert()
->into('reservation_data')
->columns(['reservation_id', 'type', 'reference_id'])
->values([':reservation_id', ':type', ':reference_id']);
$statementInsert = $this->connection->prepare($queryInsert);
foreach ($reservation->promotions as $promotion) {
$statementCheck->execute(['id' => $reservation->id, 'promotion_id' => $promotion->id]);
$result = $statementCheck->fetch(PDO::FETCH_ASSOC);
if ($result['cnt'] > 0) {
continue;
}
$statementInsert->execute(['reservation_id' => $reservation->id, 'type' => 'Promotion', 'reference_id' => $promotion->id]);
}
}
protected function editUnits(Model\Venta\Reservation $reservation, array $new_data): void
{
$querySelect = $this->connection->getQueryBuilder()
->select()
->from('reservation_data')
->where('reservation_id = :id AND type = "Unit" AND reference_id = :unit_id');
$statementSelect = $this->connection->prepare($querySelect);
$queryUpdate = $this->connection->getQueryBuilder()
->update('reservation_data')
->set('value = :value')
->where('reservation_id = :id AND type = "Unit" AND reference_id = :unit_id');
$statementUpdate = $this->connection->prepare($queryUpdate);
foreach ($new_data as $unit_id => $value) {
$idx = $reservation->findUnit($unit_id);
if ($idx === null) {
$reservation->addUnit($this->unitRepository->fetchById($unit_id), $value);
continue;
}
$statementSelect->execute(['id' => $reservation->id, 'unit_id' => $unit_id]);
$result = $statementSelect->fetch(PDO::FETCH_ASSOC);
if (!$result) {
continue;
}
$statementUpdate->execute(['id' => $reservation->id, 'unit_id' => $unit_id, 'value' => $value]);
$reservation->units[$idx]['value'] = $value;
}
}
protected function editPromotions(Model\Venta\Reservation $reservation, array $new_data): void
{
$querySelect = $this->connection->getQueryBuilder()
->select()
->from('reservation_data')
->where('reservation_id = :id AND type = "Promotion" AND reference_id = :promotion_id');
$statementSelect = $this->connection->prepare($querySelect);
$queryUpdate = $this->connection->getQueryBuilder()
->update('reservation_data')
->set('value = :value')
->where('reservation_id = :id AND type = "Promotion" AND reference_id = :promotion_id');
$statementUpdate = $this->connection->prepare($queryUpdate);
foreach ($new_data as $promotion_id => $value) {
$idx = array_search($promotion_id, array_column($reservation->promotions, 'id'));
if ($idx === false) {
$reservation->promotions []= $this->promotionRepository->fetchById($promotion_id);
continue;
}
$statementSelect->execute(['id' => $reservation->id, 'promotion_id' => $promotion_id]);
$result = $statementSelect->fetch(PDO::FETCH_ASSOC);
if (!$result) {
continue;
}
$statementUpdate->execute(['id' => $reservation->id, 'promotion_id' => $promotion_id, 'value' => $value]);
$reservation->promotions[$idx] = $this->promotionRepository->fetchById($promotion_id);
}
}
protected function fetchUnits(Model\Venta\Reservation &$reservation): Model\Venta\Reservation
{
$query = $this->connection->getQueryBuilder()
->select()
->from('reservation_data')
->where('reservation_id = :id AND type = "Unit"');
$statement = $this->connection->execute($query, ['id' => $reservation->id]);
while ($result = $statement->fetch(PDO::FETCH_ASSOC)) {
try {
$reservation->addUnit($this->unitRepository->fetchById($result['reference_id']), $result['value']);
} catch (Common\Implement\Exception\EmptyResult) {}
}
return $reservation;
}
protected function fetchPromotions(Model\Venta\Reservation $reservation): Model\Venta\Reservation
{
$query = $this->connection->getQueryBuilder()
->select()
->from('reservation_data')
->where('type = "Promotion" AND reservation_id = :id');
$statement = $this->connection->execute($query, ['id' => $reservation->id]);
while ($result = $statement->fetch(PDO::FETCH_ASSOC)) {
try {
$reservation->promotions []= $this->promotionRepository->fetchById($result['reference_id']);
} catch (Common\Implement\Exception\EmptyResult) {}
}
return $reservation;
}
}

View File

@ -0,0 +1,60 @@
<?php
namespace Incoviba\Repository\Venta\Reservation;
use Incoviba\Common;
use Incoviba\Model;
use Incoviba\Repository;
class State extends Common\Ideal\Repository
{
public function __construct(Common\Define\Connection $connection, protected Repository\Venta\Reservation $reservationRepository)
{
parent::__construct($connection);
}
public function getTable(): string
{
return 'reservation_states';
}
public function create(?array $data = null): Model\Venta\Reservation\State
{
$map = (new Common\Implement\Repository\MapperParser(['type']))
->register('reservation_id', (new Common\Implement\Repository\Mapper())
->setProperty('reservation')
->setFunction(function($data) use ($data) {
return $this->reservationRepository->fetchById($data['reservation_id']);
}))
->register('date', new Common\Implement\Repository\Mapper\DateTime('date'));
return $this->parseData(new Model\Venta\Reservation\State(), $data, $map);
}
public function save(Common\Define\Model $model): Model\Venta\Reservation\State
{
$model->id = $this->saveNew(
['reservation_id', 'date', 'type'],
[$model->reservation->id, $model->date->format('Y-m-d'), $model->type]
);
return $model;
}
public function edit(Common\Define\Model $model, array $new_data): Model\Venta\Reservation\State
{
return $this->update($model, ['reservation_id', 'date', 'type'], $new_data);
}
public function fetchByReservation(int $reservation_id): array
{
$query = $this->connection->getQueryBuilder()
->select()
->from($this->getTable())
->where('reservation_id = :reservation_id');
return $this->fetchMany($query, ['reservation_id' => $reservation_id]);
}
public function fetchActiveByReservation(int $reservation_id): array
{
$query = $this->connection->getQueryBuilder()
->select()
->from($this->getTable())
->where('reservation_id = :reservation_id AND type = :type');
return $this->fetchMany($query, ['reservation_id' => $reservation_id, 'type' => Model\Venta\Reservation\State\Type::ACTIVE]);
}
}

View File

@ -14,7 +14,7 @@ class Mes extends Banco
}
try {
$reader = PhpSpreadsheet\IOFactory::createReader('Xlsx');
} catch (PhpSpreadsheet\Reader\Exception $exception) {
} catch (PhpSpreadsheet\Reader\Exception) {
return false;
}
$xlsx = $reader->load($filename);

View File

@ -1,7 +1,6 @@
<?php
namespace Incoviba\Service\Contabilidad\Informe\Tesoreria\Input\Excel;
use stdClass;
use PhpOffice\PhpSpreadsheet;
class DAPyFFMM extends Sheet

View File

@ -0,0 +1,171 @@
<?php
namespace Incoviba\Service\Proyecto;
use PDOException;
use Psr\Log\LoggerInterface;
use Incoviba\Common\Ideal;
use Incoviba\Common\Implement\Exception\EmptyResult;
use Incoviba\Common\Implement\Repository\Factory;
use Incoviba\Exception\ServiceAction;
use Incoviba\Model;
use Incoviba\Repository;
use Incoviba\Service;
class Broker extends Ideal\Service
{
public function __construct(LoggerInterface $logger,
protected Repository\Proyecto\Broker $brokerRepository,
protected Repository\Proyecto\Broker\Data $dataRepository, protected Service\Persona $personaService)
{
parent::__construct($logger);
}
/**
* @param array $data
* @return Model\Proyecto\Broker
* @throws ServiceAction\Create
*/
public function add(array $data): Model\Proyecto\Broker
{
try {
$broker = $this->brokerRepository->fetchById($data['rut']);
} catch (EmptyResult) {
$filteredData = $this->brokerRepository->filterData($data);
try {
$broker = $this->brokerRepository->create($filteredData);
$broker = $this->brokerRepository->save($broker);
} catch (PDOException $exception) {
throw new ServiceAction\Create(__CLASS__, $exception);
}
}
$this->addData($broker, $data);
return $this->process($broker);
}
/**
* @param int $id
* @return Model\Proyecto\Broker
* @throws ServiceAction\Read
*/
public function get(int $id): Model\Proyecto\Broker
{
try {
return $this->process($this->brokerRepository->fetchById($id));
} catch (EmptyResult $exception) {
throw new ServiceAction\Read(__CLASS__, $exception);
}
}
/**
* @return array
*/
public function getAll(): array
{
try {
return array_map([$this, 'process'], $this->brokerRepository->fetchAll());
} catch (EmptyResult) {
return [];
}
}
/**
* @param array $data
* @return Model\Proyecto\Broker
* @throws ServiceAction\Update
*/
public function edit(array $data): Model\Proyecto\Broker
{
try {
$broker = $this->brokerRepository->fetchById($data['id']);
} catch (EmptyResult $exception) {
throw new ServiceAction\Update(__CLASS__, $exception);
}
$filteredData = $this->brokerRepository->filterData($data);
try {
$broker = $this->brokerRepository->edit($broker, $filteredData);
$this->editData($broker, $data);
} catch (PDOException | EmptyResult) {
} finally {
return $this->process($broker);
}
}
/**
* @param int $broker_rut
* @return Model\Proyecto\Broker
* @throws ServiceAction\Delete
*/
public function delete(int $broker_rut): Model\Proyecto\Broker
{
try {
$broker = $this->brokerRepository->fetchById($broker_rut);
} catch (EmptyResult $exception) {
throw new ServiceAction\Delete(__CLASS__, $exception);
}
try {
$this->brokerRepository->remove($broker);
} catch (PDOException $exception) {
throw new ServiceAction\Delete(__CLASS__, $exception);
} finally {
return $broker;
}
}
protected function process(Model\Proyecto\Broker $broker): Model\Proyecto\Broker
{
$broker->addFactory('data', (new Factory())
->setArgs(['broker_rut' => $broker->rut])
->setCallable([$this->dataRepository, 'fetchByBroker'])
);
return $broker;
}
/**
* @param Model\Proyecto\Broker $broker
* @param array $data
* @return Model\Proyecto\Broker\Data
* @throws ServiceAction\Create
*/
protected function addData(Model\Proyecto\Broker $broker, array $data): Model\Proyecto\Broker\Data
{
$data['broker_rut'] = $broker->rut;
$filteredData = $this->dataRepository->filterData($data);
if (isset($filteredData['representative_rut'])) {
try {
$this->personaService->getById($filteredData['representative_rut']);
} catch (ServiceAction\Read) {
unset($filteredData['representative_rut']);
}
}
try {
$brokerData = $this->dataRepository->fetchByBroker($broker->rut);
return $this->dataRepository->edit($brokerData, $filteredData);
} catch (EmptyResult) {}
try {
$brokerData = $this->dataRepository->create($filteredData);
return $this->dataRepository->save($brokerData);
} catch (PDOException $exception) {
throw new ServiceAction\Create(__CLASS__, $exception);
}
}
/**
* @param Model\Proyecto\Broker $broker
* @param array $data
* @return Model\Proyecto\Broker\Data
* @throws ServiceAction\Update
*/
protected function editData(Model\Proyecto\Broker $broker, array $data): Model\Proyecto\Broker\Data
{
try {
$brokerData = $this->dataRepository->fetchByBroker($broker->rut);
} catch (EmptyResult $exception) {
throw new ServiceAction\Update(__CLASS__, $exception);
}
try {
$data['broker_rut'] = $broker->rut;
$filteredData = $this->dataRepository->filterData($data);
$brokerData = $this->dataRepository->edit($brokerData, $filteredData);
return $this->dataRepository->save($brokerData);
} catch (PDOException | EmptyResult) {
return $brokerData;
}
}
}

View File

@ -0,0 +1,153 @@
<?php
namespace Incoviba\Service\Proyecto\Broker;
use DateTimeInterface;
use DateTimeImmutable;
use DateMalformedStringException;
use PDOException;
use Psr\Log\LoggerInterface;
use Incoviba\Common\Ideal;
use Incoviba\Common\Implement;
use Incoviba\Exception\ServiceAction;
use Incoviba\Model;
use Incoviba\Repository;
class Contract extends Ideal\Service
{
public function __construct(LoggerInterface $logger,
protected Repository\Proyecto\Broker\Contract $contractRepository,
protected Repository\Proyecto\Broker\Contract\State $stateRepository)
{
parent::__construct($logger);
}
public function getAll(): array
{
try {
return array_map([$this, 'process'], $this->contractRepository->fetchAll());
} catch (Implement\Exception\EmptyResult) {
return [];
}
}
/**
* @param int $project_id
* @return array
* @throws ServiceAction\Read
*/
public function getByProject(int $project_id): array
{
try {
return array_map([$this, 'process'], $this->contractRepository->fetchByProject($project_id));
} catch (Implement\Exception\EmptyResult $exception) {
throw new ServiceAction\Read(__CLASS__, $exception);
}
}
/**
* @param int $broker_rut
* @return array
* @throws ServiceAction\Read
*/
public function getByBroker(int $broker_rut): array
{
try {
return array_map([$this, 'process'], $this->contractRepository->fetchByBroker($broker_rut));
} catch (Implement\Exception\EmptyResult $exception) {
throw new ServiceAction\Read(__CLASS__, $exception);
}
}
/**
* @throws ServiceAction\Read
*/
public function getById(int $id): Model\Proyecto\Broker\Contract
{
try {
return $this->process($this->contractRepository->fetchById($id));
} catch (Implement\Exception\EmptyResult $exception) {
throw new ServiceAction\Read(__CLASS__, $exception);
}
}
/**
* @throws ServiceAction\Create
*/
public function add(array $data): Model\Proyecto\Broker\Contract
{
try {
return $this->process($this->contractRepository->fetchActiveByProjectAndBroker($data['project_id'], $data['broker_rut']));
} catch (Implement\Exception\EmptyResult) {}
try {
$filteredData = $this->contractRepository->filterData($data);
$contract = $this->contractRepository->create($filteredData);
$contract = $this->contractRepository->save($contract);
$type = Model\Proyecto\Broker\Contract\State\Type::ACTIVE->value;
$date = new DateTimeImmutable();
if (isset($data['date'])) {
try {
$date = new DateTimeImmutable($data['date']);
} catch (DateMalformedStringException) {}
}
$state = $this->stateRepository->create(['contract_id' => $contract->id, 'date' => $date, 'type' => $type]);
$this->stateRepository->save($state);
return $this->process($contract);
} catch (PDOException $exception) {
throw new ServiceAction\Create(__CLASS__, $exception);
}
}
/**
* @throws ServiceAction\Update
*/
public function edit(Model\Proyecto\Broker\Contract $contract, array $data): Model\Proyecto\Broker\Contract
{
try {
$filteredData = $this->contractRepository->filterData($data);
return $this->process($this->contractRepository->edit($contract, $filteredData));
} catch (PDOException | Implement\Exception\EmptyResult) {
throw new ServiceAction\Update(__CLASS__);
}
}
/**
* @throws ServiceAction\Delete
*/
public function delete(int $id): Model\Proyecto\Broker\Contract
{
try {
$contract = $this->contractRepository->fetchById($id);
$this->contractRepository->remove($contract->id);
return $contract;
} catch (PDOException | Implement\Exception\EmptyResult $exception) {
throw new ServiceAction\Delete(__CLASS__, $exception);
}
}
/**
* @throws ServiceAction\Update
*/
public function inactive(Model\Proyecto\Broker\Contract $contract, DateTimeInterface $date = new DateTimeImmutable()): Model\Proyecto\Broker\Contract
{
try {
$type = Model\Proyecto\Broker\Contract\State\Type::INACTIVE;
$state = $this->stateRepository->create(['contract_id' => $contract->id, 'date' => $date, 'type' => $type]);
$this->stateRepository->save($state);
return $this->process($contract);
} catch (PDOException $exception) {
throw new ServiceAction\Update(__CLASS__, $exception);
}
}
protected function process(Model\Proyecto\Broker\Contract $contract): Model\Proyecto\Broker\Contract
{
$contract->addFactory('states', (new Implement\Repository\Factory())
->setCallable([$this->stateRepository, 'fetchByContract'])
->setArgs(['contract_id' => $contract->id]));
/*$contract->addFactory('currentState', (new Implement\Repository\Factory())
->setCallable([$this->stateRepository, 'fetchActiveByContract'])
->setArgs(['contract_id' => $contract->id]));*/
return $contract;
}
}

View File

@ -2,7 +2,6 @@
namespace Incoviba\Service;
use Incoviba\Common\Implement\Exception\EmptyResult;
use Incoviba\Common\Implement\Exception\EmptyResponse;
use Incoviba\Model;
use Incoviba\Repository;

View File

@ -3,7 +3,6 @@ namespace Incoviba\Service;
use Exception;
use DateTimeImmutable;
use DateInterval;
use DateMalformedStringException;
use Psr\Log\LoggerInterface;
use Incoviba\Common\Ideal\Service;

View File

@ -1,7 +1,6 @@
<?php
namespace Incoviba\Service\Venta;
use Exception;
use DateTimeInterface;
use DateTimeImmutable;
use DateMalformedStringException;

View File

@ -2,7 +2,6 @@
namespace Incoviba\Service\Venta;
use Incoviba\Common\Implement\Exception\EmptyResult;
use Incoviba\Common\Implement\Repository\Factory;
use Incoviba\Exception\ServiceAction\Read;
use Incoviba\Repository;
use Incoviba\Model;

View File

@ -1,10 +1,8 @@
<?php
namespace Incoviba\Service\Venta;
use Incoviba\Common\Implement\Exception\EmptyResult;
use Incoviba\Exception\ServiceAction\Read;
use Incoviba\Repository;
use Incoviba\Service;
use Incoviba\Model;
class PropiedadUnidad

View File

@ -0,0 +1,81 @@
<?php
namespace Incoviba\Service\Venta;
use DateTimeImmutable;
use DateMalformedStringException;
use PDOException;
use Psr\Log\LoggerInterface;
use Incoviba\Common\Define;
use Incoviba\Common\Ideal;
use Incoviba\Common\Implement;
use Incoviba\Exception\ServiceAction;
use Incoviba\Model;
use Incoviba\Repository;
class Reservation extends Ideal\Service\API
{
public function __construct(LoggerInterface $logger, protected Repository\Venta\Reservation $reservationRepository)
{
parent::__construct($logger);
}
public function getAll(null|string|array $order = null): array
{
try {
return $this->reservationRepository->fetchAll($order);
} catch (Implement\Exception\EmptyResult) {
return [];
}
}
public function get(int $id): Model\Venta\Reservation
{
try {
return $this->process($this->reservationRepository->fetchById($id));
} catch (Implement\Exception\EmptyResult $exception) {
throw new ServiceAction\Read(__CLASS__, $exception);
}
}
public function add(array $data): Model\Venta\Reservation
{
try {
$date = new DateTimeImmutable();
try {
$date = new DateTimeImmutable($data['date']);
} catch (DateMalformedStringException) {}
return $this->process($this->reservationRepository->fetchByBuyerAndDate($data['buyer_rut'], $date));
} catch (Implement\Exception\EmptyResult) {}
try {
$reservationData = $this->reservationRepository->filterData($data);
$reservation = $this->reservationRepository->create($reservationData);
$this->reservationRepository->save($reservation);
return $this->process($reservation);
} catch (PDOException $exception) {
throw new ServiceAction\Create(__CLASS__, $exception);
}
}
public function edit(Define\Model $model, array $new_data): Model\Venta\Reservation
{
try {
return $this->process($this->reservationRepository->edit($model, $new_data));
} catch (PDOException | Implement\Exception\EmptyResult $exception) {
throw new ServiceAction\Update(__CLASS__, $exception);
}
}
public function delete(int $id): Model\Venta\Reservation
{
try {
$reservation = $this->reservationRepository->fetchById($id);
$this->reservationRepository->remove($reservation);
return $reservation;
} catch (PDOException | Implement\Exception\EmptyResult $exception) {
throw new ServiceAction\Delete(__CLASS__, $exception);
}
}
protected function process(Define\Model $model): Model\Venta\Reservation
{
return $model;
}
}

View File

@ -2,6 +2,7 @@
namespace Incoviba\Service\Venta;
use DateTimeImmutable;
use DateMalformedStringException;
use Incoviba\Common\Implement\Exception\EmptyResult;
use Incoviba\Exception\ServiceAction\Read;
use Incoviba\Repository;
@ -34,12 +35,12 @@ class Subsidio
}
}
/**
* @throws Exception
*/
public function add(array $data): Model\Venta\Subsidio
{
$fecha = new DateTimeImmutable($data['fecha']);
$fecha = new DateTimeImmutable();
try {
$fecha = new DateTimeImmutable($data['fecha']);
} catch (DateMalformedStringException) {}
$uf = $data['uf'] ?? $this->moneyService->getUF($fecha);
$tipoPago = $this->tipoPagoRepository->fetchByDescripcion('vale vista');
$ahorro = $this->pagoService->add(['fecha' => $fecha->format('Y-m-d'), 'valor' => $this->valorService->clean($data['ahorro']) * $uf, 'uf' => $uf, 'tipo' => $tipoPago->id]);

View File

@ -5,7 +5,6 @@ use Incoviba\Exception\ServiceAction\Read;
use PDOException;
use Incoviba\Common\Implement\Exception\EmptyResult;
use Incoviba\Repository;
use Incoviba\Service;
use Incoviba\Model;
class Unidad